Files
window-axis-innovators-box/library/jcef/lib/win64/devtools_resources.pak

33947 lines
6.0 MiB
Plaintext
Raw Normal View History

2025-11-02 17:17:24 +08:00
<00>p<00>p<EFBFBD><70><00>pu6<00>pU9<00>p@u<00>p<EFBFBD>4 <00>p5: <00>pS= <00>p<EFBFBD><70> <00>p<70> <00>p<EFBFBD><70> <00>p<EFBFBD><70> <00>p<13> <00>p<EFBFBD>x$<00>p<EFBFBD>z$<00>p[L%<00>p7O%<00>p<EFBFBD><70>%<00>pn<70>&<00>pP<70>+<00>p6=,<00>p<19>,<00>p٥,<00>p}51<00>pY2<00>pe4<00>pl<70>4<00>p_ 5<00>p*<2A>5<00>pjR6<00>p<EFBFBD><70>6<00>p<EFBFBD><70>:<00>p<EFBFBD>%;<00>p1F;<00>p4;<00>pi<70>;<00>pr<70>;<00>p:<3A><<00>pt<70>><00>pt<70>><00>p0<70>?<00>p<18>?<00>p<07>C<00>p<EFBFBD><70>D<00>pw\F<00>p<EFBFBD><70>F<00>p<EFBFBD><70>Iq<>/Jq<><71>LqP:Mq<><71>Mq9Nq])Nq4=OqA<71>Sq<><71>U q<>SW
q<EFBFBD>M[ q<>~[ qL<71>[ q<>6\q']q3<71>]q<04>]qƘ]q˟]q2<71>]q<><71>]qd<71>]qS<71>]q
<EFBFBD>]q<><71>]q<><71>]q<1C>]q<><71>]q<><71>]q <0A>]q<><71>]q<><71>] q7<71>]!q<><71>]"q,^#q<>^$q<>%^%q<>&^&q<>&^'qg'^(q(^)q#)^*q<>)^+q<>C^,q<>}^-q%<25>^.q<><71>^/qɽ^0q<30><71>^1qH<71>^2q<32><71>^3q<1F>^4q<34><71>^5q<35><71>^6qf<71>^7qR<71>^8q<38><71>^9qM<71>^:q<1E>^;q<><71>^<q1<71>^=q<1E>^>q<><71>^?qb<71>^@qu<71>^Aq<41><71>^Bq<0E>^Cq<43><71>^Dq<44><71>^EqD<71>^Fq<46><71>^Gqb<71>^Hq<48>_IqH-_Jq<4A>._Kq//_Lq>0_MqD2_Nq<4E>2_Oq<4F>3_`c_<00>p&W3vLUll<00>zotܵR<DCB5><52> Kl<4B><6C>,<2C><>><3E>me<00><><EFBFBD>|<7C>*<2A><>e@<19><1E>d<EFBFBD><64><EFBFBD>V<EFBFBD><56><EFBFBD>k*<2A><01><><EFBFBD>á<EFBFBD>qD<71><44><EFBFBD><14>_<EFBFBD><5F><EFBFBD><13>VB<>QSٚ<>=<3D> GTK <20><><EFBFBD>U<EFBFBD><55><EFBFBD><EFBFBD><EFBFBD>34P<34><50>v<EFBFBD>ղ8#uz=WP<57>$<24>3dL+<2B><><EFBFBD><EFBFBD>sU; <1F> o<18><02>]<5D>5<EFBFBD>f<EFBFBD>>"P<>L٦Cr<43><72>pOx<03><>j<EFBFBD>O<EFBFBD>|=<3D><> *<2A>q<EFBFBD><71><EFBFBD>Bl<02><><EFBFBD><EFBFBD><EFBFBD>W<EFBFBD>>;]<5D>W,O<><4F><EFBFBD><EFBFBD><1D><><EFBFBD><EFBFBD>@<40>9a<39>W=P<06><14>,١CZ Q<14>B<EFBFBD><42><EFBFBD><EFBFBD><EFBFBD><EFBFBD>H<EFBFBD>&<26><>,V<>V<EFBFBD><56>uw<75>f"9<>n<EFBFBD><19>+<2B><>%<25> x<>NtT& p<><70><EFBFBD>WO<57>s
<EFBFBD>ŦwJ <20>Z<EFBFBD>X<05><><EFBFBD>{K<><4B>f<EFBFBD>J<>VJ<56>m<EFBFBD><6D> w<0F>B(3<02>0#<08>3iөF<D3A9>x<EFBFBD>}<7D>{<7B>@0 <06><>0<05><><EFBFBD>-<2D>-<2D>^<5E><><EFBFBD>B<EFBFBD><42><EFBFBD><EFBFBD><EFBFBD><1D>@pDUc<55>d<EFBFBD>Tws<77>Z<EFBFBD><5A><6A><D58B>Ds<44><73>L<EFBFBD><4C>E<EFBFBD><45>1f<31><66><EFBFBD>1<EFBFBD>,
DDE<EFBFBD>{<7B>/<2F><><12><>r<19><16><>:?<3F>j<EFBFBD>yS.k<><6B>[H J`xc_D<5F>/<2F>o<EFBFBD><6F><EFBFBD>q#<23>(<11>(nq<00><><EFBFBD><EFBFBD><EFBFBD>*<2A>S<EFBFBD><53><EFBFBD>ww彩 <02><10>3<EFBFBD>ُaZ<61>f&<26><><EFBFBD>s<EFBFBD>#ma<6D>
<EFBFBD>xNi<EFBFBD>%<25>ߞ<EFBFBD>/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><05>& ><3E><>4Py}<7D><>]y&<26><>ѺI<D1BA><49><EFBFBD><EFBFBD><EFBFBD><1B><>?<3F><>uK<75>׾;$<24>lD<><44><EFBFBD>j<1B>8<EFBFBD><38><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;<3B>}y<>$L<><4C><EFBFBD>b <09>'=<3D>])<29><><EFBFBD><02>]M<>0 <0C><>%o<>B<EFBFBD><42>W<EFBFBD>3<EFBFBD><33><07><>
TzaN8<EFBFBD><EFBFBD>*(̶<><CCB6><EFBFBD><EFBFBD>Jx<4A>bl<>2[<5B><><EFBFBD><EFBFBD><EFBFBD>4<EFBFBD>u7I`;<3B><>כ}<7D>/z<><7A>T2<54><32>}I<><49>f?%Θ<>5<EFBFBD><35>Wg<57><67> <<3C><>B/ҏ<><D28F>L<EFBFBD>s<EFBFBD>9vr<><72><EFBFBD><EFBFBD>E<EFBFBD>1<><31><EFBFBD><17><><EFBFBD><EFBFBD> <0B>\+xa<78><61>a<EFBFBD>#<1E><>D?<08><><EFBFBD>ۖ<<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>n<EFBFBD>de<64><65><EFBFBD>"0<><30>L<EFBFBD>f<EFBFBD>r<EFBFBD>̪X<CCAA>C.<12><><1A>V;<3B> <50>U"<22>y<EFBFBD><79>_<EFBFBD><5F><EFBFBD>T<EFBFBD>
3<EFBFBD>LZȜK<EFBFBD><EFBFBD>s<EFBFBD><EFBFBD>t<EFBFBD>2<EFBFBD><EFBFBD><EFBFBD>.Tf<54>I<EFBFBD><49>{<7B>I/<2F><>N<EFBFBD><4E> 9<><39>[cR<05>c9<63>FI<46>=<3D><><EFBFBD><EFBFBD>9<EFBFBD><05><>_6<06>V<EFBFBD>40X<17><>M<EFBFBD>W<EFBFBD><57><EFBFBD>(<28>Z<EFBFBD>;m<1E><>|<7C>><3E><>#<23><><EFBFBD><EFBFBD>$(M<>ER<45>{<7B>%S<><53><EFBFBD><EFBFBD>Q\̉3r <20>l+<2B><>τ<EFBFBD>tG<74>8U~.<2E><><08><1F>ִf*<2A>+U]<5D><0E>_,<2C>@<40><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>_R<5F><52>g.pF ß<>C<01>9<EFBFBD><13>@<40>e<EFBFBD>X<EFBFBD><58> &<26><>><3E>f]F<>ɨ<><C9A8>T "(9z-<2D>8<EFBFBD><38>ul<75><6C>_<<14><><EFBFBD><EFBFBD>j<EFBFBD>jZFעp<>R<EFBFBD>M<EFBFBD>?'WO<1C><><EFBFBD><EFBFBD>'@ٚQ<D99A><05>J<EFBFBD>ˇ<EFBFBD><CB87>[<5B><<3C>2&<26>*<2A>z/l<><6C>`T<>Ȱ)%<25><><EFBFBD> &<26><><EFBFBD>f<EFBFBD><66><08>h/5<>H<>9<EFBFBD>G_<47><05><><EFBFBD>c| .<2E><><03>+<2B>ѵbDIA~<12><1C><><EFBFBD><0F><>Կ<EFBFBD>},<2C>r<EFBFBD><72><EFBFBD>)/|<7C>/ǫS%<25>[<5B><>K<EFBFBD>!<21>m.<2E>2<EFBFBD><32>`<60>D<EFBFBD><44><EFBFBD>9<EFBFBD> <0B><>0<EFBFBD>S&t:1<>$
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>{d<<3C><>n<EFBFBD><6E>)<29>A<EFBFBD>ʭ<EFBFBD><1A>iX<69>4~Z<>k/a<><61>53Y<16><>t<EFBFBD><74>Ni1ϰ.<2E>ΔF&
<EFBFBD>$<11><>Ϸ<01>Pk<50>$<24>_V*<2A>+?<3F>+<2B><><EFBFBD>@<40>uyu<79>5<EFBFBD>2<0E><1D><>;ܐ+K}<15>]<5D>-H<>ui<>T<EFBFBD><54><EFBFBD><EFBFBD>}*<2A>|<7C>=<3D><EFBFBD><0E><><EFBFBD><EFBFBD><EFBFBD>5<EFBFBD>T<EFBFBD>@<40>ѐqJJ<4A><4A><EFBFBD>:<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>I R<>؄<EFBFBD><18>4<08>c<63><05><><EFBFBD>PI<50><49> q <0A><><18><>N6{ns<6E><73>-L<><4C><14>^{y<>|<7C>Т<EFBFBD><D0A2>{<7B>$<24>p<EFBFBD>;<3B><><EFBFBD><EFBFBD>g}鮵<><E9AEB5><13>xs<78>d<EFBFBD><64><EFBFBD><EFBFBD>O<EFBFBD>6-9<>D&D
<EFBFBD><EFBFBD>l<12>M<EFBFBD><4D><EFBFBD>W<EFBFBD>Yo<59>!}<7D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>j痉<6A><12>X4<58><34><EFBFBD><EFBFBD>g_(<28><>}<7D><>ι<EFBFBD>~<7E><>\<5C><><EFBFBD><EFBFBD><1C><>=R<><52>K<EFBFBD>b<EFBFBD>_<EFBFBD>1r><3E><><EFBFBD>rs<72>Mk<><6B><EFBFBD>B<EFBFBD>Vlٳ<7F>ۜ<EFBFBD>#/<2F><16>ۮ<EFBFBD><DBAE><EFBFBD><EFBFBD><EFBFBD>,<2C>f<66><7F>o<EFBFBD><6F>G<><47><EFBFBD><10><><EFBFBD>)B<><42><EFBFBD><EFBFBD><EFBFBD>1<EFBFBD>\w<><77><EFBFBD><EFBFBD>a<EFBFBD>A<EFBFBD><1C><>̑Mg<><67>=苬<>.<2E><><EFBFBD><EFBFBD><EFBFBD>ԣ<EFBFBD>f<02>z<EFBFBD><7A>2<EFBFBD>Ÿ<EFBFBD><C29F><EFBFBD>;<3B>O<EFBFBD>̓<> Ba<42>Y<EFBFBD>\J<><00>@-<2D><><EFBFBD>RO<52><4F><EFBFBD><EFBFBD><EFBFBD>LGb<47>Gl]<07><><EFBFBD>eE<65><45><EFBFBD><EFBFBD><03><>n<EFBFBD><6E>-<2D>y<EFBFBD>H%A<>9<EFBFBD><39>E<11><>m<EFBFBD><1A><><EFBFBD>i#B<>yz_<7A> ,W1z<31>g<EFBFBD><67><61>Ve<56>E<EFBFBD>ê<EFBFBD>!_<><5F>)<29><>$P<><03>ܗ<EFBFBD><08><>ڃ*U<>iIg<>K}*<2A><><EFBFBD>[<0F><><EFBFBD><EFBFBD>qe<71>(*i<>ū<EFBFBD><C5AB>E)P<><50>1A<><41><EFBFBD><00><><14>ep<65>!<21><>u<EFBFBD><75>%<25><>Q<EFBFBD>}!<21><m<><6D><01><>U<EFBFBD>Eg:<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>xñt<19><><EFBFBD>}C<>?<3F><><14><><EFBFBD><EFBFBD>z<EFBFBD><7A><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>QW
A<EFBFBD>m<EFBFBD>F\<5C>%<25><><<3C>ޖ<EFBFBD>^<5E>s0or <0C>Je<4A>cj<63><6A><02><>8,<2C>w(Ɨf<C697><66><EFBFBD>@z<><7A><EFBFBD>Q?<3F>N1<4E>M;<3B>]&<26>u<EFBFBD><75><EFBFBD><EFBFBD>U<>?<3F>6<EFBFBD><36>x<EFBFBD><78><EFBFBD>m<EFBFBD>|Js<4A><73>) <1A>&<26>C<EFBFBD><43><EFBFBD><EFBFBD><EFBFBD>g<EFBFBD><67>F<EFBFBD>ٓ<EFBFBD>Az#<23>1<>B)<13><>g0w<30>͕<EFBFBD><CD95><EFBFBD>;Y<><12><01>`h<><68>oڮM2-wuq8,<2C><>Ѐ:<3A>O<EFBFBD>=YKx<4B>qQ^:<3A>DHI ˁ<><CB81><EFBFBD><EFBFBD>1<EFBFBD><31><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\<5C><><EFBFBD><EFBFBD>CC<43>q<EFBFBD>x<EFBFBD><78>><3E>I]<5D>~l<>p<EFBFBD>3<>͎R<1C>nK<>}<7D>Z<EFBFBD><5A>U<EFBFBD>.읥C<EC9DA5><43><EFBFBD>N8w@1<>L<EFBFBD><4C><EFBFBD><EFBFBD><EFBFBD>n1va<76><61><EFBFBD>o.1$<11><16><><EFBFBD><10>T<EFBFBD><54>R<EFBFBD><52>K5<4B>r<EFBFBD><72><EFBFBD>'f<>MNb0(<28>?<1B><><EFBFBD>D<EFBFBD>\[<5B><>_F?.~<7E>M<1F><>bIZ<><5A>c<EFBFBD>o$<24>Q<>RV<52><56>o@<40>}<7D>o<EFBFBD>U<EFBFBD><55>7<EFBFBD>[:<3A>S<EFBFBD> <0B>zG<7A>Wy<57>q<EFBFBD><71><13><>?<3F>-<2D>?<3F><>/Q֍<51><D68D>*<2A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>{<7B><><EFBFBD><00><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.otsL<0F>n0mɜ<6D><C99C>m<EFBFBD><6D><EFBFBD><EFBFBD><EFBFBD>gрlC<><43>u <0C><><EFBFBD>o<EFBFBD><6F><EFBFBD>g<1E> <0C>c):<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)<29><><EFBFBD>u!<16><>;<3B>3k<0E>&j<><6A>UU<55><55><EFBFBD>(ҡL<D2A1>$<24><>
S<>#`<60>$<03>f<EFBFBD>8<><38><12>W`<19>K<EFBFBD><15><>aB<61><42><EFBFBD>q|<7C>Gu<47><75>ԟi<1D>#AX<41><58><EFBFBD>ϒ<EFBFBD><CF92><EFBFBD>H<EFBFBD>Q<EFBFBD><13>9<EFBFBD> V<><56>.<1C><>5<EFBFBD>_<EFBFBD><5F><EFBFBD><EFBFBD><10>/<2F><>.<2E><>x<EFBFBD><78>!<21>5<EFBFBD>h?K<><4B><EFBFBD>u<EFBFBD><75><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>A^<5E>p<19><><EFBFBD>7<EFBFBD>gMo<4D><6F><EFBFBD>x<03>C<EFBFBD><43>@Ya<59><05><>Iag<61><67>C$Ҫ&{><17>L<01>{<05>p"<22>b<EFBFBD><62><1E><1D><>~Y<><59><EFBFBD> <0C><1B><>d<>& <0A>+<2B>"<22><> p<>H<EFBFBD>'lrXu@<40>H<EFBFBD>Y<EFBFBD><59><EFBFBD><EFBFBD><0F>WJ<57>u<EFBFBD><75>;Qzl*{F<>(<28><><<3C>4سI<D8B3>b;<3B>[<5B><><EFBFBD>u\<5C><0F>Sn^M]<5D><>v<1A>'<0E>TutB<74><
*<2A>&<26>I<EFBFBD>&0<>V=fJ<66><4A><EFBFBD>N<EFBFBD><4E><EFBFBD>AJ<>r<EFBFBD>4<EFBFBD>,T<><54><1B> <09>}VRb<52><62><EFBFBD><EFBFBD>A"<22>V<><56><EFBFBD>K.<2E>'k<>x<EFBFBD><78>X<EFBFBD>$<24><>S_R<5F>7<EFBFBD><37>ެ<EFBFBD><DEAC>T<EFBFBD><05><><EFBFBD>ڛ<EFBFBD><05>7.Ү"+<2B>g<10><><EFBFBD><EFBFBD>PY<50>^w_Y<07><><EFBFBD>-<2D>}J<>$<0F>_<EFBFBD><5F><EFBFBD>Y<EFBFBD>f<EFBFBD><66>GB<16><>Ck;Y~$E[<5B>|\<5C><> mn<6D>P<13><>ho<68><6F><13>D<EFBFBD><14><>WxqF<71> <09> BP<42> <20><><EFBFBD><1B><>j<EFBFBD>%<25><08>X<>O<EFBFBD><4F>D? <0B>7<EFBFBD><37><EFBFBD>K<EFBFBD><4B>(<28><><EFBFBD>T<EFBFBD><54><EFBFBD><EFBFBD><48>q<EFBFBD><71>R<EFBFBD><52>[LL<4C>u9<75><39>05~-<2D><><EFBFBD><EFBFBD><16><>|<7C>#[<5B><><EFBFBD><EFBFBD><EFBFBD>6AϬ<41><CFAC><EFBFBD><EFBFBD><EFBFBD>q<EFBFBD>U<11>k4_<04>I <09><04>j<>o<EFBFBD><6F>C,W<57><7F><EFBFBD>}<7D>l5ժ5<D5AA>Q+ <20><><0E>><3E> ?.<2E><>Bsl@<40><><EFBFBD>F' JA@<40><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>d9<64>@U<>F<EFBFBD>I<EFBFBD><16><><1D>૰W<1E><><02><><EFBFBD>0&<26>\<5C><>+<2B><1A>SmΗL<CE97>w> .u<>o<EFBFBD>R<02>sG<73><47><EFBFBD>4?<12><><EFBFBD>[<5B><>GE<47>(X<>k<EFBFBD><6B><EFBFBD>T<EFBFBD><Oo<4F><6F><EFBFBD><EFBFBD><EFBFBD>D<EFBFBD><44>? <09>)<29><>S`<04>lM<6C><4D><10>i<EFBFBD><69><EFBFBD>@<40>W<> <0B>!#<23>0<EFBFBD><04>k<EFBFBD><6B>Y<15><><EFBFBD>'<27><><EFBFBD>4z<34>,<2C>?V<><56><EFBFBD><7F>D.%cJ`,b<>,$u<><75><EFBFBD><EFBFBD>*)<29><><EFBFBD><EFBFBD><08>B3<42>a<EFBFBD><61>aH$<24>g<EFBFBD><67><EFBFBD>.<2E>ۉ<EFBFBD>[b6<62><36>k<EFBFBD>̦h<CCA6><68><EFBFBD>74<37>3<EFBFBD>C<EFBFBD>.,<2C><11><><EFBFBD>+d<>O$<00>0<>&<26>]<12>b<EFBFBD><62><EFBFBD><1E><16>S<EFBFBD>N<EFBFBD><4E>j<EFBFBD>h<EFBFBD><68>.<2E>B<EFBFBD><42><EFBFBD>Gs<47>r<EFBFBD>̚<EFBFBD><CC9A>5<01><><EFBFBD><14>KL<4B><0F>c<1E><>w<EFBFBD>)9L_<><5F><EFBFBD><EFBFBD>pvQ<76>f<EFBFBD><14><><EFBFBD>8fahV<>c<>S<1B><>q<EFBFBD><71><EFBFBD>5<EFBFBD>P<14>2&<26>ݴH|j <0A><02><><13><><EFBFBD>`J#$<24>)<29>q<EFBFBD>E<EFBFBD>2<EFBFBD><32><EFBFBD><EFBFBD><EFBFBD>ڶ<EFBFBD>0<EFBFBD>0<EFBFBD><30> <20>Fl<46><14>L<<3C><><EFBFBD><EFBFBD>!2w<32>i<EFBFBD><69><EFBFBD>}<7D><>K#FXJt<4A>o<>A^;<3B><><EFBFBD>;<3B><><EFBFBD><7F><EFBFBD>ɭ2<k|<7C><>c<EFBFBD>
9Tk<EFBFBD>MIĸB<EFBFBD> 9<><39>M<EFBFBD><4D><EFBFBD>h<19><><EFBFBD><EFBFBD>6<EFBFBD><06>h}_{ne<6E><65>1i<31><69>:<1C>2;IҸ<49><D2B8>X.<2E>)R<>e(<28><><EFBFBD><EFBFBD>[<02>& t<>#0<>n<EFBFBD><6E><EFBFBD>S<EFBFBD><04>2<32>,<2C><><EFBFBD><EFBFBD>lx<6C><08><><EFBFBD><EFBFBD>w<EFBFBD>c<EFBFBD>LO<4C><4F>z<EFBFBD>j<EFBFBD>-;Bƌ<42><C68C>Fwg<77><67><EFBFBD><EFBFBD>s<EFBFBD><73>-<2D><>]<5D>/<2F><>z<EFBFBD><7A>SH-a<><61><EFBFBD>$<24>Ik2<6B>&<26>-?4<><34><EFBFBD><1B>򠔟X-<2D><>.<2E>`<60>Y<EFBFBD><59>Ux<><78>+<2B>A<EFBFBD><41>B<EFBFBD><42><EFBFBD>?r<><72>P<EFBFBD><50>T <0C><><EFBFBD>:<12>~<7E>KS<4B><EFBFBD>`<60>F<06><><EFBFBD>/<2F> <0A> <20><<3C>}<7D><>O<EFBFBD>A<EFBFBD>%)\<5C><>E2Ά؄J<D884><4A><EFBFBD><EFBFBD><EFBFBD><EFBFBD>bZ<15>rB<72>UGe V<>v!K<><4B><EFBFBD>N<EFBFBD>جa<D8AC><61><EFBFBD>}L<><4C>t <10>Ga<>i<EFBFBD><10><><02><><1A>x<EFBFBD>!ۈz<DB88><7A><1E><02>L<EFBFBD>A+<Hx<48><78><EFBFBD>[
<1B>><3E>d r<><72>J <09><>o<EFBFBD>O<EFBFBD>x<EFBFBD><78>[<5B><07><>w<EFBFBD>K<EFBFBD>IJ <0B><>k<EFBFBD>cH<63><48>D<EFBFBD><44><EFBFBD>J<EFBFBD>V<56>3<EFBFBD><33>2k+<2B><>C<EFBFBD><11><><EFBFBD><01>:0<05>1 `H<>;yo<79>#<16><>%ŪPBY<42><><16><>{W4z<34>psV<73>&<26>y~<7E><><EFBFBD><EFBFBD>4<EFBFBD>\<5C>k{<7B><<3C>Az!<21>l(cT<10><>?<3F><18><><EFBFBD>/+eܼ<>cY<63><59>v<07>-J<11><><EFBFBD>m<EFBFBD>=<3D>G<EFBFBD>އ<EFBFBD>õ<EFBFBD><04>lj<EFBFBD>_<EFBFBD>]':Nz-]<5D><><EFBFBD>7<EFBFBD><37>I<><49><<3C>է<EFBFBD><D5A7><1D><><EFBFBD><10><>E<16>c<EFBFBD>U舄<55>%_wQ<77>[<5B>= <20><>Q<EFBFBD><51><EFBFBD><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>&G<><47><EFBFBD>v<EFBFBD><50><CB9A>\<5C><>WH<57><48>ٛ<EFBFBD>g~Q<>,<2C><> <0C><>]<5D><><EFBFBD>7<EFBFBD>C<EFBFBD><43><EFBFBD>ԍW<D48D>n xɂc<C982><63>wȀ Z<1C> <> Q<><51>c<EFBFBD>ʍ<EFBFBD>W<EFBFBD> & %<25><><EFBFBD>69<36>6<EFBFBD>F<EFBFBD><46><EFBFBD><EFBFBD><EFBFBD>@<04><16> #<23><07><>c<EFBFBD>w<EFBFBD><1C><><EFBFBD>$s<1A><><EFBFBD><EFBFBD><EFBFBD>!<21>!5ЍAKCz<17><>gx<67><78>?<17><><EFBFBD><EFBFBD>K=W<>E2(4<>ئ6<D8A6><36>DO'<27>nR{<7B><>&<26>},<2C>=<3D><>9<EFBFBD><39><EFBFBD>c8<63><38>/1:UG<02><01>x$<24><>{<00><><EFBFBD><EFBFBD><EFBFBD>/<2F><>ߏ<03>T?Fʉ<46>z-*a<><61> Y<>{5r{<7B><><00><>g<EFBFBD>
`#<23><>({<7B>y<EFBFBD><79>f<EFBFBD><0F>[{<7B>$<24>ҨN<D2A8>f<EFBFBD> <0B> D<07>3q<33>P<EFBFBD><50><EFBFBD>|<7C><>A<EFBFBD>Q<EFBFBD>0:}&<26>J<EFBFBD>XWd<57>0$<24>l+r<><72><EFBFBD>%<25>z<EFBFBD>7In<49><6E><EFBFBD> <0C>?<3F>/ȍa<C88D>#<23>t<EFBFBD><74>G<><47>ci+Km<<3C><>d0?Q<><51>sm<73><6D>
<EFBFBD><EFBFBD>w<EFBFBD><EFBFBD>"<15><><EFBFBD>Q<51>%<25><><EFBFBD>A<01>\<5C>n <1F>#<1A>J$-QH͎<48>p<EFBFBD><70><EFBFBD>I<EFBFBD><49>Y<EFBFBD><59><EFBFBD>r<EFBFBD><72>d!<21>^<5E><>(/&B橖<42>8<EFBFBD><38><EFBFBD>D/<2F>s<19>1<EFBFBD>֬
cD2<EFBFBD>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>u@<40>:(<28><>l1(z<1E><08>px <09><>
%sǺ<73><C7BA>μG˕<47><CB95>z<EFBFBD>/H<>+<05>R3bO<62>5<EFBFBD>Z<10>8<EFBFBD><38>Z<EFBFBD>mu<6D><75><EFBFBD><EFBFBD><18><><00><>e<EFBFBD><65>#g<><67><EFBFBD>O:]<02>fYK<>C i_<69>z/T6f]<5D><>)<29>W<EFBFBD><57><1F><>Ir :<3A><><EFBFBD><1B><><EFBFBD>(r<>؅<EFBFBD><13>K<EFBFBD><4B>V<EFBFBD><56>'FRLp<4C><70>$<24><>e܁<65>%<25><EFBFBD>_8<5F><38><EFBFBD>J<EFBFBD><4A>Q<EFBFBD>ȁ<><C881><14><>- ͕<>p<EFBFBD><70><03>#2NԠ H3t <20>\<5C><>ޣ}<7D><>Y2knxgv<><76><EFBFBD>-wn<77>Ԯ<EFBFBD><D4AE>c<EFBFBD><63><EFBFBD>֬o<D6AC>X'1b{|<04>Hw<48>ʡ<EFBFBD>m<15><><EFBFBD>S<EFBFBD><53>1<EFBFBD><31><EFBFBD><EFBFBD>s<07> <0C>t<EFBFBD><74>̠<EFBFBD><CCA0> b<><62><EFBFBD>_<0E>
籏|t<>~<7E><>d:<3A><><EFBFBD><EFBFBD>x<1B>EfD<66><44><1E>9<EFBFBD>b<7F>rH<72>;<3B><><EFBFBD> ?<3F><>Ћ<EFBFBD>}<7D>b<EFBFBD><62><EFBFBD><EFBFBD>L<EFBFBD>*=<3D><><EFBFBD>i<>{#`7 U<>4<EFBFBD><13>z<EFBFBD>e/<2F><07>cY189x<39><78><EFBFBD>؉LE$<24>d<EFBFBD><64><EFBFBD>.e<>5<19><><EFBFBD>}&de7"!M<> T<>'<27> Fq<46>H<EFBFBD>z)<29><>d<EFBFBD><64><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>2z<32>B<EFBFBD>N<02><>ea<65>{8<><38><13><><EFBFBD>2<EFBFBD>Z
Ϝ<EFBFBD>_5<00>4<EFBFBD><34><13>|<7C>5<EFBFBD>k<EFBFBD>A<EFBFBD>/Y<><59><EFBFBD><EFBFBD><02>v<EFBFBD>l<EFBFBD><6C><13> <0C><><EFBFBD><15>
5<EFBFBD>c\0<>k<EFBFBD><6B>6׃<36>e<EFBFBD><65>E<EFBFBD>k@g<05><><EFBFBD>jt<6A>;<3B>i<10> <0B>G%<25><10>5iKVչO{<7B><><EFBFBD><EFBFBD><EFBFBD>U<EFBFBD><54><CB93>2<EFBFBD>L퇫<4C>o'<27>K<EFBFBD><4B>>[$<24><> \@<13>
T<EFBFBD>Q<EFBFBD>x FX^<5E><>)<29>?<3F><>5<EFBFBD><35><EFBFBD><10><>r)<29>C<EFBFBD><43><12><><17><><1E>'-զ<>q<EFBFBD>D<J<>h<EFBFBD>&<26><><EFBFBD>&x<>eE*<2A>l&L<><1C>mL<><4C>DA<44>DQN<51><4E><EFBFBD>Nݿ\<5C><>ٔ<EFBFBD><D994>ͭ<EFBFBD><CDAD>ji<6A>R<> su]<5D><><EFBFBD>ܙ<13>L(a<><61>.<2E>7<06><>[ <0B>z<15>L|<7C>1<>2L<"<22><><07><<3C>]zb<7A>rk<72>ݕ<EFBFBD><DD95>ܠR<11>3<>Z<EFBFBD>,Y<i<0E><><EFBFBD>6<1E>#08<30>&<26><><EFBFBD>n<EFBFBD><6E><EFBFBD>&<26>>0<><30>%7<>|.:2<><32>n<EFBFBD>{<7B>Y<EFBFBD><59>)<29><><02><14><><EFBFBD>/ X<><58><EFBFBD>gj<67><6A><EFBFBD><<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>i0<69>o<EFBFBD>(<28><0E><>Ƌj<C68B> g<>U<EFBFBD><55>S<><53><EFBFBD><EFBFBD><18>COU<4F><EFBFBD><7F><1C><>5W<><57>Xp<58><70> xk<><6B><EFBFBD><EFBFBD><EFBFBD>1V<12><><1F><1E><><EFBFBD><EFBFBD>LZ<4C>ʸw<CAB8><><D3B6>'<27>0<00><>6<EFBFBD><36><EFBFBD>8a<38>w<>q<>W}<7D>cw<17><><EFBFBD><EFBFBD><0E>^g<>C><3E>9g<39>Om5<04><1C>D<EFBFBD>M藌<4D>:<3A><08>_<EFBFBD>.<2E>& s<><73><EFBFBD>H<EFBFBD><48>,<2C><><EFBFBD><EFBFBD><EFBFBD>.6; <0A><>@<40><>٠<EFBFBD><D9A0>g<EFBFBD>г<EFBFBD>0<EFBFBD>W<EFBFBD>{%K6<4B>w<>7 <02>.<2E><>%=8/<2F><>XLou<><13>62wW<77>T/6R<36><52> <0A>M<EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <17><><EFBFBD>G<EFBFBD>k<EFBFBD><6B><EFBFBD><EFBFBD>orv<72><76>a_<61>,O<><4F><1A><> ά<><>ia<>Sx1<78>"7
<EFBFBD>#<23>-<2D>h<EFBFBD><68>.<03>8<EFBFBD><38><EFBFBD><EFBFBD>(<28><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E0B3B5>ʨ<><CAA8>h<EFBFBD>_c<5F><13>Ak<41><6B><EFBFBD>M<EFBFBD><13>b<EFBFBD>Io<49><6F><EFBFBD>_<>6@l<>)y<>@J<06><>N j<><6A>"]ʈ+<2B><>)<29><08>o<EFBFBD>Š<EFBFBD> <0B><>λ<EFBFBD><CEBB>\<5C><><EFBFBD>E<EFBFBD><45><EFBFBD><EFBFBD><EFBFBD>V<EFBFBD>@tE6?<3F>~<7E><1F><><EFBFBD>vz<76><7A><EFBFBD><EFBFBD>j<1B>R~<7E>ּk<><6B>?<3F><><EFBFBD>5<EFBFBD>ΨY<CEA8>t撡<74><E692A1><EFBFBD>7Rg<52><67>go'<27><>;x<><78><EFBFBD>9<EFBFBD>y<EFBFBD><10><><EFBFBD><EFBFBD>pZ0<14>סk娽<00>*F<>8<EFBFBD><38>~<15><00><>a<EFBFBD><61>4<EFBFBD><34><EFBFBD>+<><E9BBA6>΂<EFBFBD>O<EFBFBD>*<2A>8<EFBFBD>e<EFBFBD>`F<><46>
b<EFBFBD><EFBFBD>zIfR:<3A><50><04><09>(<28><0F><><EFBFBD>Hw{<7B>%#<23><>K<><03> D<>:c<><63><EFBFBD>KWqq<71>b<EFBFBD><62><EFBFBD>3<0E><1F>O6<4F>ޖ<EFBFBD>&`{zز<7A><D8B2>0<11> =?<3F><><EFBFBD>E\<5C>A<EFBFBD>&ws)\{<7B><><EFBFBD><0E>$/<2F><><EFBFBD><EFBFBD>i<EFBFBD><69><EFBFBD><EFBFBD>aK<>><3E>"<22>0$<24><><EFBFBD><EFBFBD>R<EFBFBD>IQ<49>A:K<><05>w<EFBFBD>'ق<><D982><01><>I:y<><79>Ul<55><6C>^<5E>o<<3C><><04><>G<EFBFBD>Ic<49><63><EFBFBD>}<7D>)<29>;<1D><15>#AtU<74><55><EFBFBD><EFBFBD>V<EFBFBD>
ޡ<EFBFBD><EFBFBD>r <0B><>W<EFBFBD><57>X<EFBFBD>i<><69>4<EFBFBD><10>H<EFBFBD><48>Ȳ<><14><>'<27>׬<>hO<68><4F>Vz8Wu<02>=KW<4B><57>CRY<>F<><46><EFBFBD>dtJ<74>ba<62><61>@<40>,<2C><>$Nx:Wc<57><63><EFBFBD>[<5B><>K<EFBFBD>c<EFBFBD>Ũ<EFBFBD>$<24>9<><39>K!<1B>><3E>$j eK<65>;ֆTҡ)<29><><EFBFBD>*MI<4D><49>,<2C>O+<2B>9[<04><>O:<3A>&1_P<5F>)<> <0A>R<10>"xڟR? +<2B><><EFBFBD><EFBFBD>[<5B>*<2A>e<EFBFBD>K<><4B>9<EFBFBD>Ln<4C><6E>x<EFBFBD>(G<><47>4<EFBFBD>&zL#<23><><EFBFBD><EFBFBD> 7"<22><>d$<24><><EFBFBD>i<EFBFBD><69><EFBFBD><EFBFBD><EFBFBD><EFBFBD>5D<><44>k(Y U<><55>c<>\<5C>ET<45><54>5<EFBFBD><1E><>I<EFBFBD>bx<62><78><EFBFBD><EFBFBD>z<EFBFBD><7A>p<>䪁i<E4AA81>l<EFBFBD><6C>Y<EFBFBD><59><EFBFBD><EFBFBD>8X&b<>Q<EFBFBD><15><>1]<5D>+?W<><11>DK8<4B><38>3<EF8CB0><EFBFBD>U<EFBFBD>&C<>v<>n<>'<1E><>\<5C>A<EFBFBD><41><EFBFBD><EFBFBD>_<EFBFBD><5F><EFBFBD>ΊJ Ԋ3<D48A><1A>BS<42>;<3B><>ײ<>O<EFBFBD>9 |<03><><EFBFBD>/<2F> <0A>E<EFBFBD><45><13><><EFBFBD>M<EFBFBD>V<EFBFBD>'<27><>DW<44>7\<5C>0 g<><1B>1<>yz<79> <09>R,<2C>F<EFBFBD>(,K"!cC<63>Q%<⃲a<E283B2><61>XdY0<59>?S-<1B>-<2D>\<5C><<3C>Cf<43><66><EFBFBD><EFBFBD><EFBFBD><00><>Žj<C28E>Z<EFBFBD><5A><EFBFBD><03>k.<2E>^#7<>+<15>\<5C><><EFBFBD><EFBFBD><EFBFBD>[<5B><><EFBFBD>vD2dǺ"<22><48> 9O<39>v<>'M<>% <0A><>%<25><> <0A> <0B><>Ċ<EFBFBD>l<13> <0A><><EFBFBD>E<EFBFBD>Z~*T=<3D><11><EFBFBD>y<EFBFBD><79>&<26>,<2C><><EFBFBD> <18>JW(o<>V<><56>Wbez<65>9W<00><11><05>SR<14><1A> o*<2A><>8<EFBFBD>f<EFBFBD>ܓN<16>H<><13><><EFBFBD> <0B><><EFBFBD><0F><>w<EFBFBD><15>{<7B>}L<>3,<2C>l<EFBFBD>+Q$61ԏCw(+e<>i>w<><77><EFBFBD><EFBFBD>?0E<30>1K{<1A><><EFBFBD><EFBFBD>Q<1B>g,<2C> krg<06><17>a<EFBFBD><01>s<7F>P8J<38><4A>3<EFBFBD><33>2NݓB<DD93>.#ҏ`H×<48><C397><EFBFBD>i<EFBFBD>"<22><><EFBFBD><EFBFBD><0F><>uP<75>Ǩ#<23>/BU8<1C><><11><EFBFBD><E89D9C>!`<60><>uvA_q 񞂂|Dû<><C3BB>?8
<EFBFBD>8]݇<R9<52>k<EFBFBD><6B>(-c<><63>`<00>&<13>
<EFBFBD>ă0Ӯ><3E><>`<60><03>4GY<47><59>[<5B>O<EFBFBD>ñ<EFBFBD>U<EFBFBD><55> <20><> <07>?<3F><>1<00><1A><>n<EFBFBD><6E><EFBFBD>5J;<3B><><EFBFBD><EFBFBD>M<18><>
u<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>~<1A><><EFBFBD><EFBFBD>^<5E><11>=<1D><><EFBFBD><7F><EFBFBD><EFBFBD><EFBFBD>3<06>
<EFBFBD>
<EFBFBD> f<03>Q<EFBFBD>>j<><6A>TLJ<4C><4A>a<EFBFBD><61>=<3D> !V-<2D> [I<><15><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>l<EFBFBD>n<EFBFBD><19><><EFBFBD>D:"<14><12><><EFBFBD><5F><32><CAA5>^<5E>Ҙ<EFBFBD>o<08>#Va2ݒ<32>jӒG<D392><47><EFBFBD><1E>l<EFBFBD><6C><EFBFBD><EFBFBD>|<7C><>/<2F><><1D><><EFBFBD>><3E><><04><>o <09>G<EFBFBD>+<2B>6<><36><EFBFBD>3?<3F>z<EFBFBD>`<60>bH<62><48><17><><EFBFBD>76o<36>)<29>l<EFBFBD><13><>;<3B>V<EFBFBD><56><EFBFBD>G<EFBFBD><47><EFBFBD> <0B><><EFBFBD><EFBFBD>P<EFBFBD><50>؇ѷ<D887>ȟjZ<> <0A> <09>_<EFBFBD><5F><EFBFBD><EFBFBD>hɗ=n!<21>ߊ`+y{L<1A><><EFBFBD>| <0C> <>&<26><>D<EFBFBD>|L L<><4C><EFBFBD>S<EFBFBD><53>u<EFBFBD><75>Q~<7E>{<7B>2f߭<66><DFAD><1E>˟<EFBFBD><CB9F><EFBFBD>.<2E><><EFBFBD><EFBFBD>ғ<EFBFBD># `3k<33><6B><EFBFBD><EFBFBD><14><><EFBFBD> <16>B<EFBFBD>U8<55><12><>T<EFBFBD>Y<>l<><13><>x<>v<EFBFBD>DŽ<EFBFBD>?<3F><><EFBFBD><EFBFBD>2AW<41>UG<55>M#<23>Q<EFBFBD>EF<18><>o<EFBFBD><6F>S|<7C><>- <0C><><EFBFBD><EFBFBD><0E><>_<04>{<<3C><><18>Ы3<D0AB>U,<2C>T<EFBFBD><54><EFBFBD>Gg<47>)<29><><EFBFBD>[<5B><>_<EFBFBD><5F>5`<60><> p<><70>rmE<6D><45><EFBFBD><EFBFBD><0E><><EFBFBD><EFBFBD><EFBFBD>!<21><><EFBFBD>ʈVrk7X[<5B>J<EFBFBD><4A>2<EFBFBD><32><13>ɹ<EFBFBD><C9B9><EFBFBD>2Y<32><59>>P <17><>S9<53><39><EFBFBD>rr'<27><><EFBFBD>'^k!v7<76><37><EFBFBD><00>
ٌ"<22>T<EFBFBD> [x<1E><13>?⛐<><E29B90>p<><70><EFBFBD>:<15><>tp<74><70><EFBFBD>s<EFBFBD>><3E>|8<>
<06>Q><><7F>"o/<2F>(@UW]<5D><>t<EFBFBD><19>(+<2B><>u3]{^<5E>%<25><>i"p<><70>h<EFBFBD><68><05><><1B><>2<EFBFBD>r<EFBFBD><72>R[Bd<42><64>N <09>G<05>XB6X<36><58><EFBFBD><11>q<EFBFBD><71><EFBFBD><EFBFBD>rD<><44><EFBFBD>$3<>Ij<>#<23><>.<2E><>Y<EFBFBD>hNH<1E>X<EFBFBD><58><EFBFBD>EX|/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>=<3D> h<18>}<7D><>_<>|<7C>܂<EFBFBD>)%x<>r<EFBFBD>2<EFBFBD>H<1C>h<>v<1A><0F>D<7F><44><EFBFBD>Ʋ<EFBFBD><C6B2>X%G<>²<>`<60>h<EFBFBD>w<EFBFBD>k<EFBFBD><6B><EFBFBD>"6H<C28D>_E K<><4B> <09>}<7D><><EFBFBD><EFBFBD><EFBFBD>S<EFBFBD>ٓ<EFBFBD>$4b<>k<EFBFBD><6B>,<2C><><EFBFBD>Ov<4F><76>&Wc<>m<EFBFBD>7G <0A><><EFBFBD>G&F<><46><EFBFBD><EFBFBD><EFBFBD><EFBFBD>فbL<62>=<3D>f<EFBFBD>Xrā G)K<><4B>,<0F>$<24><><EFBFBD>V<EFBFBD><56><EFBFBD>W,<2C>`<60>҉<EFBFBD><>J<1D><>ar<61>r<EFBFBD>A<EFBFBD><41><EFBFBD><EFBFBD>T<EFBFBD>z<EFBFBD><7A>z*-\(q<13><><EFBFBD>0o-<15>&+ <0A><>Ӟ<EFBFBD>~H<03><><EFBFBD>=<3D><!<21><><EFBFBD>t<EFBFBD><74><EFBFBD><EFBFBD> <0B>sP0")<29><>;Ց`<60><><EFBFBD>v<EFBFBD>*<2A>]X<>q<EFBFBD><71>Z<EFBFBD><5A>Tf<54><66><EFBFBD><EFBFBD>-V<>y<EFBFBD>*<2A>}gׄ<67>L)~F=<3D>s=T{<7B><><EFBFBD><EFBFBD><EFBFBD>3<02>_<EFBFBD>Q ضIK@<40><08><><EFBFBD><EFBFBD><EFBFBD>&.By(<28>'9<><39><12><><EFBFBD><EFBFBD>[S<>3IH<><48>6<><36>Ʊ<EFBFBD><10><><EFBFBD><10>6<><36>%<25>U<03>J)<29>EZ<45>X<<3C>
<EFBFBD>nL<EFBFBD>Q]W<0E><><EFBFBD>9<EFBFBD><39>/<2F>,<2C>5<EFBFBD>0R<>J<><4A>b<EFBFBD>U
4<EFBFBD><EFBFBD>"b贽о<E8B4BD>n<EFBFBD>x<EFBFBD>c<EFBFBD><63><EFBFBD>ͭ<EFBFBD>ȟh<C89F>YW/xݨs<DDA8>S<EFBFBD>u<>9<<3C><>5<EFBFBD><35><03><><EFBFBD><EFBFBD><EFBFBD>{<7B><><EFBFBD><>e<EFBFBD><65><1C>*<2A><>9<EFBFBD><39><EFBFBD>R{<07>T<EFBFBD>Pi!<21>n<EFBFBD><6E><EFBFBD>[i<>qD<71>"<22><12>j<EFBFBD>-'`<60>A<1E><17>~<7E>.A/<2F><> H<00><00>t<EFBFBD><74><EFBFBD>/<2F>$<24><>b<EFBFBD><62>FĔj/<2F>?<3F>x<><78>K<EFBFBD>s<EFBFBD><73>u\<5C>><02><><EFBFBD><EFBFBD>S<><53>䗇3<E49787><33>)<29>~w<1A><>$On<4F>-<2D>'<27>b<EFBFBD>3<EFBFBD>v<>сjʕ<12><>!S<>.>A!?<3F><>f<EFBFBD>J&<26><>0p<30>1'<02>{<16><>,<2C><> u<>0<EFBFBD><30><EFBFBD> <0A>{<7B>'<27>I<1A>E'k<><6B>]<5D>f<EFBFBD><66>V<><56>6&<26><><02><02> f<><66><EFBFBD><EFBFBD><EFBFBD><EFBFBD><14><>?<3F>sQB&'E<>E1<45>l<EFBFBD><6C>L<EFBFBD>5<><1A>{!<21>d@A<>.<2E><<3C>h<EFBFBD>.G<><47><<3C><><38><75>Kp<4B>'[<5B>z<EFBFBD><7A>a<EFBFBD> Q]h<><68>jrH<72>}g<>&C<>dW\][<5B>#Wɪ<57>{K<>%i<00><><EFBFBD><EFBFBD>s7C<><43><EFBFBD><19><>i<04>6 <0A>!c<> 6<>O<EFBFBD><4F>d<><64><EFBFBD>6|<01>CY .K<><4B><EFBFBD>҉<EFBFBD><D289>`?<3F>'F<><q<><71><EFBFBD><EFBFBD><00><> 7<>c<EFBFBD><63>q<EFBFBD><71><EFBFBD>%,<2C><17><><EFBFBD><EFBFBD>K<EFBFBD>_
d<EFBFBD>6<EFBFBD><EFBFBD>f0<EFBFBD><EFBFBD>:<3A><18>_</٠<><EFBFBD>R<EFBFBD><52>H<EFBFBD>E0"<22><>wT5܅<35><DC85>.<2E><>d<EFBFBD>b[N<><4E>. bcQH<51>D5s:<3A>^m=2G<32><47><EFBFBD>Y<EFBFBD> <0A>w<EFBFBD>MZ<4D><12>1I!<21>F-<2D>M#<23>}j<>8<EFBFBD><38>I+|:<01>C<EFBFBD>ްX<DEB0><58>{j4<6A><34>ԬȒ,<2C><>(<0F><>5A<35><41><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><39><D483><EFBFBD>sY<73>:d<>S0x<30>IL<49>x^<5E><><EFBFBD><EFBFBD><EFBFBD>K<EFBFBD>d?<3F><><EFBFBD>E<EFBFBD>0\*3<><33>|I<>I<EFBFBD>:<3A><><EFBFBD>9(<28><><EFBFBD><EFBFBD><12>d\>q!&F<><13><>P<EFBFBD>1<EFBFBD><31>b<EFBFBD>5<EFBFBD>3<EFBFBD>V<><56><EFBFBD>;<3B> նh<>W<EFBFBD><57>'<27><12>۝<05><>2+<2B>:=<3D>g<EFBFBD>Eu<45><0E><><EFBFBD><EFBFBD><<3C>RB<52>j<EFBFBD><6A><EFBFBD><EFBFBD>S<EFBFBD><53>E
<17><><EFBFBD><E8B084><EFBFBD>Tw*<2A>1<EFBFBD><31>I8=j<1B><><EFBFBD> <20>%<25><><EFBFBD>1<EFBFBD>b<07>ѝ<06><><EFBFBD>^&["<18>'S<>{<7B>zD<7A>N+<2B>y<04><> [:<3A>`<60><><EFBFBD>m<EFBFBD>GQ%<25>b<EFBFBD>W<EFBFBD><57>v<EFBFBD>#~K<><4B>|<7C>/<2F><><>P$<24>E<>*e<16>d<EFBFBD><64><07><<3C>Y:<3A><><EFBFBD>;g<>Ǐi<C78F>Z<EFBFBD><5A><04><>]C<><43>ma<6D><61>-<2D><>_<<3C><>2#3)ь-<2D><><EFBFBD><EFBFBD><11>y/F<><46><EFBFBD><EFBFBD><EFBFBD>m<EFBFBD>O<>'<27>lk<>>@<40>>4<><34><EFBFBD>4T<34><54>Ce<43>{<7B><>"<22><4F>Q(<28><><EFBFBD>semGͩ<47>^5Ι<35>!<21>Iz<49><7A>g<EFBFBD><67>J<EFBFBD><4A>~<7E>U6<55>~6<>n<EFBFBD>K<EFBFBD><4B>:<3A><><EFBFBD><EFBFBD>8<EFBFBD>eZy&<26><><EFBFBD>Ɵ<EFBFBD>k1<6B>, <0B>ZhU<68><55>]<5D><10>4y<34>4<EFBFBD><!<21><><EFBFBD><EFBFBD>i<EFBFBD><69><EFBFBD>u<EFBFBD>_.<2E>'<12><>#<23>u<EFBFBD>K<EFBFBD><4B>@<40><>6<EFBFBD>m<EFBFBD>(<28>H+mr(5 <0C>w*%A<1F><34><C790>{Kw'<27>-<2D><><EFBFBD><EFBFBD><EFBFBD>>D<>\xW(<28><><EFBFBD><EFBFBD><EFBFBD><03>p-S<><53><EFBFBD><EFBFBD>MR<4D>><3E>Z*%j=<3D><06><>0<EFBFBD><30>?'<27>#<23>YȊψ<C88A><CF88><EFBFBD><EFBFBD><EFBFBD><EFBFBD>rFL!<21><><EFBFBD><EFBFBD>'<02><><EFBFBD>s<EFBFBD>ђɎ<D192><C98E><EFBFBD>cb<63><62><08>%"<22>F<><46><08>Dか<0E><>{z<>p <0C><>U<><55>C<77><5A>'<27>e<EFBFBD><65>3G<33>7a<37><61>c<08><>?x<17>#/<2F>w<EFBFBD>t<EFBFBD>-<05><>b!<21><><EFBFBD>˗<EFBFBD><CB97><EFBFBD>7<EFBFBD>"N<><4E>R ʆ߽<CA86><DFBD><EFBFBD>D<EFBFBD><44>˶p<CBB6> w<><77>w<EFBFBD>!_<10>d2z9<7A>AM<><4D>6<EFBFBD><36><EFBFBD><EFBFBD><EFBFBD>o<00>Fh<><68><EFBFBD>̯d<CCAF><64><EFBFBD>iR<69><52><EFBFBD><EFBFBD>W<EFBFBD><57><02>A<EFBFBD><41><EFBFBD>ݢ<EFBFBD> <0A><>f C<><43>l<EFBFBD><6C>i<EFBFBD>G&<26>XbN<62><03><><EFBFBD>YQ<59><51><EFBFBD><EFBFBD>Kg<4B><67><EFBFBD>\<5C><>JW<4A><57><EFBFBD><EFBFBD><EFBFBD>U<EFBFBD>U<EFBFBD><55> <0B><>h<EFBFBD><35><D6B6>v<EFBFBD>($x<><1C><>ux<75><78>а<><D0B0><EFBFBD>i7]r<>l
rTP<1F><><EFBFBD>p<EFBFBD>_B<5F><18>`<60>6̿rH<72>I<03> n<>ŋ+[s<73><08>%<25><17>P<EFBFBD>D^fzfkd<6B>$<13>
hf<EFBFBD><EFBFBD>f<EFBFBD><EFBFBD><EFBFBD><EFBFBD>H<><48>, <0B><><EFBFBD><EFBFBD><EFBFBD>b<EFBFBD>}<7D><><EFBFBD>\<5C><02><17><>P<><50>T[(<12><><EFBFBD> v<>`<60> k{<7B><07><>R.<2E><>c%^<5E>•<EFBFBD>a<EFBFBD><1B><><01><>
ۡ<EFBFBD><03>N<EFBFBD>m<EFBFBD> Ƴ<><C6B3>r}VU<56>v`<60><>&<26>_<EFBFBD><5F>SҰ:<3A><>z<EFBFBD>/<2F><>Յ̔|<7C>I<17><><13><>'<27>&7<1A>_<EFBFBD>J<EFBFBD>ŽN:t<>S<EFBFBD>v<EFBFBD><76><03>69>ã<>5<>_<EFBFBD>CY뎥<59>C<EFBFBD>f}<7D><>P<EFBFBD>̆<EFBFBD>#<23><08><>Z)<29><><03><><EFBFBD>ha<><04><><EFBFBD>5<EFBFBD><35><EFBFBD>{t\<5C><>ٖ<EFBFBD><D996>zK<7A><4B>2BI^o<><6F>I$ݭ<03>Y<EFBFBD><59><EFBFBD><6E><CF9F><EFBFBD>ѹt<D1B9><74>1<00>^F<00>6<EFBFBD><36>Ket<65>h<EFBFBD>`<60><><08><>n<EFBFBD>2.<1F><><EFBFBD><EFBFBD>&L<><4C><EFBFBD>,Jd<4A>?<3F>,8<>6u#<23>(zZ<7A><5A><EFBFBD>'<27><><12>&<26><><EFBFBD>Q3<<3C><1C>j<EFBFBD>4<EFBFBD>h<EFBFBD><68><EFBFBD>щ<EFBFBD>.<2E>NE<4E>l<EFBFBD><6C><EFBFBD><EFBFBD> ,<2C>: ē<><C493>`I<><49><EFBFBD><04>x<>r<EFBFBD><72>/1<><31><EFBFBD><EFBFBD>(IeH_<48><5F><EFBFBD>+ab9<62><39><EFBFBD><EFBFBD><EFBFBD>b<EFBFBD><62>#<23>h<EFBFBD>G<7F><47><EFBFBD><EFBFBD>@<40><>9/<2F>S<EFBFBD>!<21>m<EFBFBD><6D><EFBFBD>%ee<65>ǘ@h<>W$~<7E><>(<06>|<7C><><EFBFBD> ar叽<72><E58FBD>p<EFBFBD>E<EFBFBD><45><EFBFBD>P<EFBFBD>ƴ<EFBFBD>߇<EFBFBD><DF87><EFBFBD>#<23>.<2E>J N<><4E> ]<5D>kK$<16>mS<03>o<EFBFBD>YR!<21>5Y*6<>9\<5C>&C0<43> ֢<>+<2B>w<><77><EFBFBD>Y?<3F>;䬁'vx<76>3<EFBFBD>><18>&}<7D><14><><EFBFBD><EFBFBD><EFBFBD>hC\<5C>G<EFBFBD><47>[<5B><>f<EFBFBD><66>'w!<21><>"<18>བྷ^Q<><0E>'<27><><EFBFBD>)<17><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>XyX;6H񖈅<48>Y<EFBFBD>$U<><02>a<EFBFBD>><3E>p<EFBFBD><07>p<EFBFBD> ><3E><><<3C>0Hlx<6C><78><EFBFBD><EFBFBD>/Px<><78>,
y<EFBFBD>@ӫ<><D3AB><EFBFBD><EFBFBD>o,<2C><>4J`e<><><DB9B>"<18><>Z<EFBFBD>[<5B> <0A>T<EFBFBD><54><01>pm<70>$㸁<><E3B881>-<2D><><EFBFBD>p2LnW<><57><EFBFBD><17><>a<EFBFBD>K.<01>@<40><50>E<EFBFBD>_<EFBFBD><EFBFBD>4W<34>D<EFBFBD><1B>
lY<EFBFBD><EFBFBD><EFBFBD><EFBFBD>|<7C><>n|<7C><>w<00><><EFBFBD>Ʃ<EFBFBD><C6A9><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>i<EFBFBD><69><EFBFBD><EFBFBD><EFBFBD><EFBFBD>n6<6E>}<7D>d<17><>p<EFBFBD><6F><CB9F><EFBFBD>e<EFBFBD>N<-<2D><>l<EFBFBD><6C><EFBFBD>\<5C><><EFBFBD>ݶ<EFBFBD>nt<6E>z<EFBFBD><18>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>r1(F8<46>=<3D>.F<>vH<76>z}6# <0A><11>B<><42>` WDs<44>o<EFBFBD>ݝ<EFBFBD><DD9D><EFBFBD>S<EFBFBD>a<EFBFBD>/'xV~<7E><><EFBFBD>@<40><>L<EFBFBD>m:<3A><>)<29>+<2B>K<EFBFBD>/<2F>Grq<72><71><1B> V<><56>P<EFBFBD>դ0vI:<3A>/B<><42>M<EFBFBD><EFBFBD>f<EFBFBD>M<EFBFBD>Y<><59>}UT<04><08><> <0C><>Q<EFBFBD><51><EFBFBD><<3C>/<2F>Y5<59><35>F]:<3A>+<2B>7F)<29>pϹ<70>ʤ)$
<EFBFBD><EFBFBD>M<EFBFBD>K<EFBFBD><EFBFBD><EFBFBD><EFBFBD>>)?<3F>nA<6E>#rb<72>6Sc<53><11>a9c<39>N"lVrbm<62>S<>*<2A><>7<EFBFBD>H<EFBFBD>:<3A>(<28><><EFBFBD>p<01>&<26>1<EFBFBD><31><EFBFBD>><3E><10>)<29>V<EFBFBD>x<EFBFBD>d6'0<>R<EFBFBD><52>uJ9<>%{x;<3B><>@;g<><67>1<EFBFBD><30>u<EFBFBD>d<EFBFBD><64>}.<2E>} 6#ܬ<03>`<03><17>D*<2A>ۣ N> <12><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><13>'<27><>&<26><>WTm<54><6D>5<EFBFBD>HI<48><49><17><><EFBFBD><EFBFBD><EFBFBD> &<08><><EFBFBD> 6<><36>".D<><44><EFBFBD>ttr<1B><>\k<>ַ<EFBFBD><D6B7>0=吝+Kz<4B><7A>F<EFBFBD><46>;.<2E><> <20><>e<EFBFBD>0MR-xi<78>d<EFBFBD><64><1E><><EFBFBD><14><>6 <20>ӆ<EFBFBD><D386>.X<><58><EFBFBD><EFBFBD><06>Y
<10><12><>jxun?<3F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>XP<58>;<3B>$<14>e3|<7C><><EFBFBD><19>"s<>7<EFBFBD><37><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"<22><><EFBFBD>͊R<><06><><EFBFBD><EFBFBD>9ڗ0<DA97>dMb<4D><62><EFBFBD>v9<76><39><EFBFBD><EFBFBD><<3C>p<EFBFBD><70><EFBFBD><EFBFBD> <20><>)$<24>C<EFBFBD><43><EFBFBD><EFBFBD><EFBFBD>%\ϡދ<CFA1>R<08><>3Mc<4D><63>nj<1C><><EFBFBD>x<EFBFBD><78><EFBFBD><1C>O<>Sx<53>x<EFBFBD>(B<>A<EFBFBD><41>Ճ<>E<><45><EFBFBD><EFBFBD>"8 4<>| f<01><>9<1E>4p<34><70>x<EFBFBD>U<EFBFBD>}uX<75> <20>};8<>qa<71>_Н<><D09D><EFBFBD>"<22>2<EFBFBD>C`G<><47>\<5C>B<EFBFBD><14>)A<>\<5C>P<EFBFBD>PS'g8<67>,<2C><1E><>.<2E>FQ<46><51><EFBFBD>"w<><77><EFBFBD>p<EFBFBD><70><EFBFBD>S8.'4t<34><74><0E><>\Jɳ&<26>,<2C>aq&@NȠ,$<15>!<21><18>
K<EFBFBD>Kb1,$ w,<2C>";W<1B><><EFBFBD>i[)<29><>ω<1B>c)<29><><EFBFBD>w<><77>t<EFBFBD>l<07>A<EFBFBD><41>1l<31><6C>U,T"<22><>zM{<7B>[H<>62L<16>Zi~<7E><><EFBFBD>t<00><><EFBFBD>.<2E>U<><55>%<25><>ΠLt'<27>Dr<44><1C>t<EFBFBD>5<><35>
#<23><>o <20>3<EFBFBD>t:<3A>X<EFBFBD><02><><EFBFBD> L<>^g<14>K<EFBFBD><4B> ?<3F><>}/{~9<><11><><EFBFBD>H<EFBFBD><48><EFBFBD>P<EFBFBD>`[<5B><1A>M<>q~(Ÿ9<C29F><39>dg<64>O<EFBFBD><4F>~<7E><><EFBFBD><EFBFBD>-<2D><>}w6<77><1F>g<><67><EFBFBD><EFBFBD><EFBFBD> <0C><> <0B><19><><EFBFBD><17><><EFBFBD>><3E><>Z<EFBFBD>0<EFBFBD><07><>qwtO)<29><>mf<6D><66> i^ b<>i<EFBFBD>"<22><>@<0E><1C>K<>)xϊn$<24>y<EFBFBD><5F>~<7E>K<EFBFBD><4B>U{<7B><>)<29>i(<19><><EFBFBD><n9ib4<62>XN<58>n<EFBFBD><<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>r``<1B> w<>}<7D><>U<EFBFBD>n<EFBFBD>))Fdc<06><><EFBFBD>[$\\<5C><><EFBFBD>a$V<><56><EFBFBD>K7<4B><37>ƥ<05>fRf(<28><>˵ <20>U<EFBFBD>%uZ<75>Y,M<>?<3F>Y<EFBFBD> WEtS<74>PB<50>O<><4F><EFBFBD><EFBFBD>wuh<75><68>pI<><11><13><>"c/<2F>0<EFBFBD>"c<><05><><EFBFBD><EFBFBD><EFBFBD>M<1D>q<EFBFBD>A<EFBFBD><41><EFBFBD>#m<12>h<EFBFBD><68>*!<21><><EFBFBD>ɨY<C9A8><59><EFBFBD>}<7D>U<><55>&<26>S<EFBFBD>~<7E>Ce<43>J<7F><4A><EFBFBD>Ceb:<3A><>s<EFBFBD><73>+<2B><><EFBFBD>Ӄ<EFBFBD>}<15>=<3D>D<><44><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>f<EFBFBD>w<EFBFBD>1<EFBFBD>oF<6F>}o&<26><EFBFBD><7F><EFBFBD>y6<79>aY<61><59>M<EFBFBD>)e0<12>X<EFBFBD><58>B<> x<><08><>"<22><>z<><7A><EFBFBD><EFBFBD><EFBFBD><EFBFBD>|P_<50>B<>S<EFBFBD><53><EFBFBD><1B>$<24>=<3D><><EFBFBD>7<EFBFBD>&<26>v_&<26>]<5D><1F><><EFBFBD>%x{)<29><><EFBFBD>,0UB<55>P y<>M<06>؈*Q4<>g5<67>Nm<><6D><EFBFBD><EFBFBD>k<EFBFBD>V<EFBFBD>Rap<1D><1A>C<EFBFBD>8\?Z<><5A><EFBFBD><EFBFBD>/ms<01>[,<2C><>!<21><><EFBFBD>iD<69>zT<7A><54>}<7D>(<18>?<3F><>(l<1A><><EFBFBD>M<1E>W <20>+<2B>W <20><><EFBFBD><EFBFBD><EFBFBD>u<EFBFBD>H.<18><>~<7E>Z<EFBFBD><5A><EFBFBD><EFBFBD><EFBFBD>=<3D><><EFBFBD>#<23><<3C>c<><63>9<EFBFBD><39>
<EFBFBD><EFBFBD><12>B}<7D>j<EFBFBD>N3<4E>tKh<1F>ڼ<EFBFBD>h<EFBFBD><68><EFBFBD> o%<25><>u<EFBFBD><75><EFBFBD><EFBFBD><EFBFBD>d{<7B>/b<> 4$[Η<><CE97>忙5TD<>)Y<>SKf]<5D>3U<33><55>,:K<><4B>ǿ<EFBFBD>(.<2E><>;<3B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <0B>7Jݎ<4A><0E>C;<3B>D<EFBFBD>Ģ!<21><16><>p5<70>A <0A>[tD<13><13>I<EFBFBD>n<EFBFBD>;v<>%<u,<2C><>~<7E><><EFBFBD><EFBFBD>2m<32> LC<1E>"<22><>ߛ]NJ<4E>ͻ2<CDBB><32><EFBFBD><EFBFBD>[<5B>N1<4E>Kl<4B>ON,<2C><>L_<11>%<25>Y<EFBFBD>qL^L6<4C><36><EFBFBD><EFBFBD> <20><>D<EFBFBD><44>F<EFBFBD>Y<03>~<7E><><EFBFBD><EFBFBD><EFBFBD>E<EFBFBD><45>'<27>0_k<5F>1~<7E>pG<70>4L<34> ]<5D>P<>2<EFBFBD><32>ҠM<D2A0><4D><EFBFBD><EFBFBD>j*̸X
<EFBFBD>$<24><>]]<5D>d}7<><37><EFBFBD>Áw<1F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ː<EFBFBD><02>;#(<28><52><D1A3>۱}<7D><18><07><> <20><>(<28>`<60><>"28/н<><D0BD><EFBFBD>d<EFBFBD>P<EFBFBD><06><><EFBFBD>p<EFBFBD>t5W<>? <14><70><CF88><EFBFBD>g<><67>p$3<04>2N<32>Q<EFBFBD>'<27><01>NB<4E>D<EFBFBD><44><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>d%<14> "<22><>G<><47>h>2<>AƖd<C696>55<35><35>v
*J@<40><><EFBFBD>W<EFBFBD>t<EFBFBD><74>Z=7: <03>HP]Y<><59>ӂ<EFBFBD>;`(w<1A><>.pl仍'<27>*z<>-<2D><><13><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>bD<><44><EFBFBD><EFBFBD><EFBFBD>@<40><>dz^<5E><>=<3D>k$<24>s1d<31>t<16>k<>,@<40>%s<><73>#t<><74>nY<6E>[<5B>x<EFBFBD>sO<73>d<EFBFBD>4<EFBFBD><34><02><><EFBFBD>]<<3C>W<1C> ze<7A><65><EFBFBD>[It5:*<2A><>3<EFBFBD><33>a<EFBFBD>J<1D><>u<EFBFBD><06><><EFBFBD>[<5B><<3C><1D><><EFBFBD>U<EFBFBD>eR{<7B>
<EFBFBD><EFBFBD>\O2@?URI<49>k<EFBFBD><6B><1F>T<EFBFBD><54>R<05>̦^gf'Js<4A><73><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/<2F>0<EFBFBD>Y<EFBFBD>X<EFBFBD> <01>Y<EFBFBD>m<EFBFBD><6D>8<><38>F<><46><EFBFBD><EFBFBD><EFBFBD>V<10>D<EFBFBD>X<EFBFBD><58>a^<5E>Qn<51><6E><EFBFBD>b<EFBFBD>Fe<46><65> <13><><13>B9W<39><57>a<EFBFBD>G<EFBFBD>cL<63><10><><EFBFBD>y̐'<27><>d<EFBFBD><64>t<EFBFBD>v<EFBFBD><76><07><>q<EFBFBD>?T/7½1<C2BD><1E><05>M1<><31><EFBFBD>y]w><3E>O<EFBFBD>£yIuQt<51><74>A<12><><EFBFBD>,!yz<05>[(<28><><EFBFBD><EFBFBD><EFBFBD>B<EFBFBD>B<7F><42>X<EFBFBD><58><EFBFBD><EFBFBD><EFBFBD><EFBFBD>K<13>{<7B><>U<EFBFBD><55>{v<>.<2E><>EG1̫7<CCAB><0E><>wR<>T?<3F>/<2F>]`3y<1D><>JY%<25><sa4<61>Ő`zY#B<14>\#<23><><EFBFBD><EFBFBD><EFBFBD><EFBFBD># #¾՝)A<1B>_Qi<51>(<28>-YM<59>R<EFBFBD><52>Q<EFBFBD>$<24><>('<27><><EFBFBD><EFBFBD><EFBFBD>Fq|S<>L<EFBFBD>#_<><5F> <<3C><>8<EFBFBD>J|<7C><><EFBFBD>Dz/<2F>/<2F><><EFBFBD><EFBFBD>qՋ<>H<EFBFBD><48>m<EFBFBD><6D>ptP<74><50>_<10><><EFBFBD>n-HS<48>NO]<5D>es<65><73>܃<EFBFBD>E<EFBFBD><45><EFBFBD>'<27>t<EFBFBD><74>UI<>?<3F> <0B>@;<3B><>ȩk<C8A9>9<EFBFBD><39>D"><12>a<EFBFBD>L<EFBFBD><4C><EFBFBD>m!<21><>c<><0F>c<EFBFBD>leo<1E><>s-I<>Ί>AF4<46>kڋK<DA8B><4B>
<EFBFBD>86JA<EFBFBD><EFBFBD><EFBFBD>]x<><78><EFBFBD><EFBFBD>K<EFBFBD>|<7C>Һ<EFBFBD>(Q<>|<7C>V<EFBFBD><56><0E><><<1A><>w<EFBFBD><77>g_<67><5F>.h<>*y<1D><><EFBFBD>٪j<D9AA><6A>ם<EFBFBD><D79D>{<7B><07><><EFBFBD><EFBFBD>ݨP%<25>&i.<2E><>k<EFBFBD><6B><EFBFBD><EFBFBD>U<EFBFBD><55>~k<>m <09>S<EFBFBD>l<EFBFBD><11>7?D<><44><EFBFBD><EFBFBD><00><1A><><EFBFBD> $I<>=<3D><EFBFBD><0F><><EFBFBD><70>y<EFBFBD>F<EFBFBD><46>?<3F><06>d<EFBFBD><64><EFBFBD>R<EFBFBD>@<40>
<16><><EFBFBD><05>7o <1A><06><>DÆ@_<>]<5D>Jn<4A>t<EFBFBD>, !\S<><53><EFBFBD><EFBFBD><>?m<><6D>S<EFBFBD><53> <09><19>0rH
<EFBFBD>h<>":s\ym<79><6D>J<EFBFBD><4A><EFBFBD><EFBFBD><EFBFBD>9<EFBFBD>@<40><<3C><>c,#ZY<5A>Ӗ <09>e<10><><EFBFBD><EFBFBD>Q<EFBFBD><51><EFBFBD>Q<EFBFBD><51>MX<4D><58><EFBFBD>sj<73>!8<04><><EFBFBD>'<27>s$<24>d<EFBFBD> f<11>X<EFBFBD>֣ C<>bvq<1F><>k<EFBFBD>L<><1E><>N <0C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><>b<EFBFBD>=<3D><>.H<><48><EFBFBD>:<3A>^<5E><>P~[ދ<>թ<EFBFBD><D5A9><EFBFBD>U<EFBFBD><55>k<EFBFBD><6B><EFBFBD>>N~7 *<2A>F<EFBFBD><46>,ꪓ0~<7E>Tg.<2E><>%1}<7D><><EFBFBD>q<EFBFBD><71><EFBFBD><EFBFBD>N]<5D>~O8>m:`<60>k<EFBFBD><6B>e<EFBFBD><11>R<EFBFBD><52>Eh߃g#!}<7D><><EFBFBD>D<18>W<><57><14> q<>[w<><77><EFBFBD><EFBFBD><18>C<EFBFBD><43><1B><><EFBFBD><00>j|<7C>=<3D><>M<EFBFBD><4D>**<2A>Ӕ<><D394>
zv<EFBFBD>գ~V<><EFBFBD>l}~<7E><>m<EFBFBD><6D><EFBFBD><15><>íZB<5A><><7F> <0B><>S<\<5C>h)<29><>:<3A>f<EFBFBD>c<EFBFBD><63>DP<44>5<EFBFBD><35>e<><65><EFBFBD>F<EFBFBD><46><EFBFBD><EFBFBD><07>7<EFBFBD><37>[&<26>%<25>i<EFBFBD>X<7F>IW<49>{<7B><>l<EFBFBD><6C><EFBFBD><EFBFBD>V9<56><39>*V<><1C><> ܐ<>><15><>#<23>6<EFBFBD>!<21>b<EFBFBD>M<10><><EFBFBD>^1`k<>*<2A><>J<EFBFBD><4A><EFBFBD><EFBFBD>+7<>)<29>6<>j <09><>+ <0B>`\<5C>mh<6D>y<EFBFBD><79>~U<><55><EFBFBD>J<EFBFBD><4A>c%Or2jU<6A><55>,JȖ4<C896>!<21>1<EFBFBD>7ɼb<C9BC>(<28><0E>91%V<>;<3B>f<EFBFBD><66><EFBFBD><EFBFBD> <0C>m2<6D><32><EFBFBD>ۉ#<23>5~#馧<>'<27><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!<21><>Y<EFBFBD>#w&?<3F>1<EFBFBD>~<7E>Aq<11>҃<EFBFBD>=1<><31><EFBFBD><EFBFBD>->A<><41><EFBFBD><EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Z6<5A><18>3<EFBFBD><01>@<19>0J<><1E>s<EFBFBD>ls<12><><EFBFBD>W<11>;<1D><><EFBFBD><16>I Ȗ<><C896><EFBFBD><EFBFBD>U<1A><>Y]<5D>X<EFBFBD>rҎ*iE<69>^m<><6D><EFBFBD>y<EFBFBD>,<2C><> <09><><EFBFBD>c<EFBFBD><63>s<EFBFBD><73><EFBFBD>F<EFBFBD><00><>7<EFBFBD><37><EFBFBD>P<EFBFBD><50>3<EFBFBD>H-4?<3F>:i<><69>X<EFBFBD><58>p`N<>!4H<34>V<> )Ex<45>fH<>i<1A>\gTC <0B>O<EFBFBD>7<EFBFBD><11> <09><>m<EFBFBD>TZ<54>8=Iu<><75>e <0B>o
<EFBFBD><EFBFBD>\4Up;d `<60>Z,J<>bF<1B>1<EFBFBD>@a<>99<19>p<EFBFBD>H<EFBFBD><48><EFBFBD><EFBFBD><EFBFBD><EFBFBD>x<EFBFBD><78><1D>r/Ժ2<D4BA><32><EFBFBD><EFBFBD>6<EFBFBD><36>α<EFBFBD><CEB1>'B<>GMR{<04>J<7F><4A><EFBFBD>.8<EFBFBD>q<EFBFBD>,FC<46>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <09>q<1D> ˴p<CBB4>[<5B>s<EFBFBD><73><EFBFBD><EFBFBD><EFBFBD>7{<7B>m<>؊ʥV<CAA5>Z<EFBFBD><02><>PS?<3F> <<3C><03><08><>@<40><12>ߗ<EFBFBD>:K<><4B><EFBFBD><EFBFBD>l6<15><>a.<<3C>L<EFBFBD>L<><17>iЍi<05>U%<25><><13><><EFBFBD><EFBFBD>98~<7E><><EFBFBD>H<EFBFBD><<3C><><05><><EFBFBD><EFBFBD>AK<41>7<EFBFBD>[R<>r<EFBFBD>&<26>m<EFBFBD><6D> <0B><><15><><EFBFBD><EFBFBD>z<EFBFBD>l<7F><6C><EFBFBD>B<EFBFBD><42><EFBFBD>`<60>뚒|KR;<3B>r<EFBFBD>T}<0F>ş<><C59F>B<EFBFBD>(SH<53>-<2D>R1
F<EFBFBD>N`<19><>%<25>Ի*<1E>N<><4E>W<EFBFBD>q<>z<1A><><EFBFBD>+<2B>8a1<61><31>}<7D><>sA8<41>,<05><><EFBFBD> +'7j7%~JK<4A><4B>'<27><><EFBFBD>Tg<54><67><EFBFBD>`<60><1A>דgQ<67><51><EFBFBD>pa<><61>?j"=eH[<5B><>nI<6E>~<7E><><EFBFBD><EFBFBD>p<><70>Ky<><79>]<5D>jF4nȰ7<>+<2B><1D><>-<2D><>Z!<21><>l7K"<22>,lH<6C>j1<>Nh<4E><68><EFBFBD>#<23>\<5C>n<EFBFBD>V<EFBFBD>658<><7F><04><>_$ke<6B><00>_<EFBFBD>Ʀ<EFBFBD><79><D78E>i(E7<1E><>t<EFBFBD>Ac<41><63>s?ґB_g<5F>(<28>7<EFBFBD>[<5B>:<3A>f<EFBFBD><66>{,Uj6\e<><65>j`<60><>
<EFBFBD>pzV<>jk0<6B>#A۬޸94<39>Z<EFBFBD>\<5C><>O<EFBFBD><4F>aY<61><59>4ep<65>P<01><><EFBFBD>u<><75><EFBFBD><EFBFBD>P<EFBFBD>ۜ<EFBFBD>B<><42><EFBFBD>ig.<2E>rF<72><46><EFBFBD>i3isY<73><59><EFBFBD>j<EFBFBD>L<EFBFBD>HyNM X)x<><78>s<EFBFBD>mq<6D>3$<24>C<EFBFBD>9x`o<><6F>jx<6A>S1<53><31>7:<3A><><EFBFBD> <0B><16><>c<EFBFBD><63><16>:<3A><11>Z<EFBFBD><1F>W<EFBFBD><57>8<EFBFBD><38>1G<31>1<EFBFBD>n<10>o<EFBFBD><6F>(<11><75><C4BE><EFBFBD><EFBFBD><EFBFBD><05><01>' <09><08><>ڳ<EFBFBD>@<40>F<1F>=<3D><>S<><53><EFBFBD>tV<<3C><>2<EFBFBD><32><EFBFBD><EFBFBD><EFBFBD><EFBFBD>=hLȂ<4C>X<EFBFBD>)<08>G<EFBFBD><47> <0A>jo/⟯Fd<13>p<EFBFBD>ѽ<>]<5D>B&Y%<25> ڋ<>ĉf<C489><66><1C>
1:<3A>͵S3<53>y{<07><><EFBFBD><EFBFBD>8<EFBFBD>+<2B>^e<><65>:<3A><31><D4BA><<3C> <0B><17><><EFBFBD> O<><<3C>2<EFBFBD>EN_y<5F>'&2X)<29><>3<EFBFBD>9<EFBFBD><39><EFBFBD> <20>NT<4E><54>N<EFBFBD>ă<EFBFBD>n<EFBFBD><6E>x,<2C>L<EFBFBD><4C>n>[<5B><><EFBFBD>֧[<5B><>3<EFBFBD>j<EFBFBD>lG<6C>*<2A><>/)<>0<EFBFBD><30>ZAYx<59><78><EFBFBD>ʹm<CAB9><6D> =5e#<23>H<EFBFBD><48>k'<27>I<EFBFBD><49><EFBFBD><EFBFBD><EFBFBD><0F><>L<EFBFBD><4C><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>s<13>G<00>dQI.<2E><><EFBFBD>жU<D0B6>t<EFBFBD>W<1B><><EFBFBD>z<EFBFBD>84N<34><4E><EFBFBD>J!Ĭ"z/<2F><>v<EFBFBD><76><EFBFBD><EFBFBD>g=<3D><>+ <0C>bB<62>,<2C>H<EFBFBD>iG<69><47>vu<76><75><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/<2F><>Ʃ_<C6A9><5F>a<EFBFBD><61><EFBFBD><EFBFBD>B<EFBFBD>1<><31><EFBFBD><1F>8<>@<40> â<>0WӲQ~<7E><><EFBFBD>2<><32>s8<73>D<<3C><><EFBFBD>M<><16>D<EFBFBD><44>7+<2B><><EFBFBD>zZ<7A><5A>x<EFBFBD><78>`<60><1D>R<EFBFBD>ހ<12>
<EFBFBD>CyR<>[<1D><0F> <0A><>1<EFBFBD><31><EFBFBD><02>~<7E>kOg<4F><67><EFBFBD>X <0C> cxQ;<3B><>*;<3B>J<16><>&;<3B>lR<1D><><EFBFBD><19> K<>;ZÆoaU<61><55>ԃ<05><>򧙤<EFBFBD><F2A799A4>n <0B>2ԑ<>E<>X<EFBFBD><58><EFBFBD><EFBFBD><EFBFBD>g<EFBFBD>MV<4D>ւ=<14><><EFBFBD>B<EFBFBD><42>T<EFBFBD><54>ǮY<>_<08><03><><EFBFBD><EFBFBD><7F>N(<28><><EFBFBD>A*<2A>@<40><><EFBFBD><EFBFBD><EFBFBD><0E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
y
<EFBFBD>d<>B)kkY<16>=<3D>/XC]<5D><><EFBFBD><EFBFBD>vXH1<48><EFBFBD><EAA79F>zEݡ=3<><33>P|f浙Y<E6B599>29<1C><>U<EFBFBD>lMF<4D>@ <20><>Pة:<3A><>V<EFBFBD>WJ<57>+b<><62><EFBFBD><0E>&<26><>R<52><7F>ޢK<DEA2>*9<><39><15>l<EFBFBD>Jq<4A><71>,2<><32><EFBFBD>NY;<3B>9e<39>`<60><14>@ <09>}<7D><>~ FeCwR0A)ʹ/%<25>C<EFBFBD><43><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Sg<53><67><EFBFBD>8<EFBFBD><38>D<><44>C*<2A><><EFBFBD><EFBFBD>ݘ,<2C><>w,<2C><><EFBFBD>JMS<4D><53>wN<77>ۋ<EFBFBD><DB8B><EFBFBD><EFBFBD>A<EFBFBD>K<EFBFBD>.<2E><><EFBFBD>W<1D><><EFBFBD>A<1A><><EFBFBD>`<60><><EFBFBD><EFBFBD> <05><>̎<EFBFBD>#<1A><>;<3B><><EFBFBD>F'%Dh[<5B>ڴ)<29><><EFBFBD>T5\<5C>>;<3B>#<23><> "<22>P<EFBFBD><50>}l<><6C>e~B+<2B><>ՠ<EFBFBD>m<>Y<EFBFBD>瓹 @ <20><10>2<05><>1vV<76><56> a<>\<5C>'<27><19>Ң<EFBFBD>6<EFBFBD><36>a<>MQ<4D><51><EFBFBD>iw1<77>١E<>s&~P<><50>n$<24> }<7D>v<EFBFBD><76><EFBFBD><EFBFBD><EFBFBD> <0C><19>|<04><><EFBFBD><EFBFBD><1C><>dW<64><57><EFBFBD>$<24><>w$At<16><>*<2A>QZ<51>$b<>u]0<><30>rC1Rx<52><78>><3E><>Vw߻<77>>L<>}<7D><>@<40><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>s9^<5E><><EFBFBD>!mfwF<77>[<5B> 8b<38>~<7E>H%<25>V<1F>X<EFBFBD>U<EFBFBD>x<EFBFBD>''<27>+<2B>Sv<53>q<EFBFBD><71><EFBFBD>| <04>9<EFBFBD>n6<6E>[G<>V"<22><><EFBFBD>$E{<7B><>(f i<><69><EFBFBD>井X<E4BA95>3k<><6B><EFBFBD>'<15><><EFBFBD><EFBFBD><EFBFBD><57><C588>b$%,<2C><>.=&|ƚP/t<>FFJ<46><4A><EFBFBD>,-<2D><>1 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>_<EFBFBD>"<22>,<2C>>ms<6D>W/<2F>.2<EEAE80><32> |<7C><>q<EFBFBD><18><><EFBFBD><EFBFBD>B9=c۾#<23><><EFBFBD>_<>l<><6C><EFBFBD>h<>۽%)%<25><>3H\<5C><>`<60>ͫl<CDAB><6C>T<EFBFBD>s <0C>j-#<23><><EFBFBD>ղ<EFBFBD>f<EFBFBD>@29<32><39><EFBFBD><EFBFBD>5i FZ<46>NJM<C78A><4D>J:^#<23>g<EFBFBD>fJd,<2C>e}<7D>pr ԹH<>@<40><>.<2E><><EFBFBD><EFBFBD><EFBFBD>:.H<><48><EFBFBD>j<EFBFBD><6A>x|'a<17><>m<EFBFBD>e<EFBFBD><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD>d<EFBFBD>)y`<60><>O̿<4F>,<2C>Hv<48>p<EFBFBD>0l' <0B><><EFBFBD>û<EFBFBD><C3BB><EFBFBD>y<>0k.<2E><>[<5B>MP<4D><50>ӆ<EFBFBD><D386>gSs <0C><>T<EFBFBD>J$O<>`.NK1<><31><EFBFBD>-<07><>`2á<32>$<24><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>><3E><>b01v<31><76>E<EFBFBD><45>(<28>Ԥ<0E>w<EFBFBD><77><0F><17><>6Fm@<40>V<EFBFBD> <0C><>@<40><><EFBFBD><EFBFBD><EFBFBD> =.<2E><><EFBFBD><EFBFBD>,<04>Y<1C>dDd̵<64>KK<4B>ѷ-[b<>x<EFBFBD>T-i<>B<06> <20>cI<63><49>
y?<3F>6<EFBFBD>~<7E>u<EFBFBD>Ѝ<><D08D><EFBFBD>Jh<4A>nf:<3A><>><3E>| <0C><><EFBFBD> ~<7E><><1B>-<2D>6<EFBFBD><36>yBI½Μ"<22><11><>i<EFBFBD>eM<65>Q0<51><30>70,2#<23><><EFBFBD>Z<EFBFBD><5A><EFBFBD><EFBFBD><02>5ef_<66>&&D<02>-<07>><3E>#6<>o<EFBFBD><6F><EFBFBD>C~fCDW<44><10><><EFBFBD>њ[<1A><1B><0F><13>j9<6A><39> <09><>|<7C><> <1A>m<EFBFBD>f<EFBFBD><66><EFBFBD><EFBFBD>s<EFBFBD><73><<3C> \+M<><4D><EFBFBD>_<EFBFBD>ʹ<><CAB9><EFBFBD>Q<EFBFBD><51>-<2D><>F _<>[<5B><>X0<58>k<EFBFBD><6B><EFBFBD><EFBFBD>G<EFBFBD><47><18>ȽH<C8BD><48>B<EFBFBD>]p7uɜbZ"10<31>e<EFBFBD>4 <0B><>C<EFBFBD>%g٤<><04>7$ <0B><>XS
W<EFBFBD>JJ3<>pY S<><05><><13><>,'<27><>X<EFBFBD><58>Q<EFBFBD>1<EFBFBD>bZO~Je<4A>du<64><75>!#p~|C<><07>K<EFBFBD>Ou<4F><75><EFBFBD>J<EFBFBD>f|<7C> <20><>x}4.><3E><><EFBFBD>K<01>򭤭߬r<DFAC><72>p<EFBFBD> <0A><><EFBFBD><EFBFBD><1F><><EFBFBD><EFBFBD><EFBFBD>u<EFBFBD><75><EFBFBD>r5<72>9<>Ip<49><70><EFBFBD>/ <03>$<24>:<3A><><EFBFBD><00><1C>)D<><44>h<>3<EFBFBD><33><EFBFBD><EFBFBD>%<25>'gv<><76><EFBFBD><EFBFBD>:N<>S<EFBFBD>}<7D><>6,h<>/<2F>UkU<6B><55><EFBFBD>΢<EFBFBD><CEA2><EFBFBD>D<><44><14>}CxR
Z-<2D>q<EFBFBD><71>v<><76><EFBFBD>~<7E>Э<EFBFBD>.<05><>Y<EFBFBD><59><EFBFBD><EFBFBD>7x<g<><67><EFBFBD>n<EFBFBD><6E>Ai+xT<><54><EFBFBD>Q<EFBFBD>4<17><><EFBFBD>5:'<27><><EFBFBD>]<5D><>\y<10><><EFBFBD><EFBFBD><1F><>Rx뺲x(٫<><D9AB><EFBFBD><EFBFBD><EFBFBD><0E>\5<><35>V<EFBFBD>]@<02>I<EFBFBD><49>- <><><08>dcD<63>^<5E>p<EFBFBD><70><EFBFBD><EFBFBD><EFBFBD>R8<52>Ч<11><><EFBFBD>X<EFBFBD>ҝ͔CT<43><54><EFBFBD>aJ<61>`<60><>G<EFBFBD>x.^#<23>E[{<7B>bg$@bcJ<63>0<EFBFBD>5<EFBFBD>Qn<51><6E> G^<5E>.1<EFBFBD><10><>n<EFBFBD>ӣ<EFBFBD><D3A3><EFBFBD><EFBFBD>b<1B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>w<><77>Lh<4C><68>E<>Xb<00>y<EFBFBD>m<EFBFBD>'b<><62><EFBFBD>\#0<>X;<1C><> ѷ<><D1B7><EFBFBD>p<EFBFBD><70><EFBFBD>m<EFBFBD>6<EFBFBD>V<16><><EFBFBD>x<EFBFBD><78>Ot<4F>S<EFBFBD>Hk& <07><>q<EFBFBD><08><>щ<EFBFBD>4<EFBFBD><34><EFBFBD><EFBFBD>~<04>6H=$<24><><EFBFBD>O$fbގ<62><10><>:<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;<3B><><EFBFBD><EFBFBD><EFBFBD> <09><>~F]<5D><><EFBFBD><EFBFBD>ѿ<EFBFBD><D1BF><EFBFBD>E<EFBFBD>8<EFBFBD><38>0<EFBFBD>A<EFBFBD><19><>b<EFBFBD><62>P<EFBFBD><50>l<EFBFBD>n<EFBFBD>D"z<><7A>Z<EFBFBD><5A><EFBFBD><EFBFBD>HQ<48><51>V<EFBFBD>.<2E><><EFBFBD>|<7C>k<EFBFBD>qߊԕ4<D495>e<EFBFBD><65>ce<63><65>VUߦ<55><DFA6><EFBFBD>C<02>Z.<2E>JD<4A><44><18>B<EFBFBD>˯<EFBFBD><CBAF>ѵ<>1&<26><03><>x<EFBFBD>'!~.<2E><>/<2F><><EFBFBD><EFBFBD><EFBFBD>T<EFBFBD><54>OE<4F><45><EFBFBD><EFBFBD>;]<5D>4<EFBFBD><34>'<27>6<EFBFBD><36><17><><EFBFBD><EFBFBD><EFBFBD>O<EFBFBD>g<EFBFBD>] <0B><>w<EFBFBD>$na<6E><61><EFBFBD><03>ԭ<EFBFBD>Q~<7E><>0<EFBFBD>v1<76><31>&}ko<6B><6F>)<29>4!=3t<33>RB<<3C><><EFBFBD><EFBFBD>nW<<3C><>p<EFBFBD> q%F<><45><D7A7><EFBFBD><EFBFBD><EFBFBD>?<3F>{<7B>s<EFBFBD>tYr<59>V<><56><EFBFBD>c<EFBFBD><18><><EFBFBD><18>b<EFBFBD>R<><52>~<7E>g!<21>T<EFBFBD>|<7C><>yd<79><64><15>05<30><13>f-<2D>=g<>8h<38>><3E><><EFBFBD><EFBFBD><EFBFBD><06><07>o<EFBFBD><06><><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD>><3E><>v<EFBFBD><76><EFBFBD>N
<EFBFBD><EFBFBD>h<EFBFBD><EFBFBD>^<5E><0E>D<EFBFBD>v@fP<66><50>h<EFBFBD>2K<18>FOXmODwk(<10><1A><><07>4<><34><EFBFBD>ϩ<EFBFBD>Q%ٳ4T<34><54>cA<63><41><EFBFBD><EFBFBD>,<13><>L<EFBFBD><4C><EFBFBD><EFBFBD><EFBFBD>)Q<><51><EFBFBD>!<21>,<2C><><EFBFBD><EFBFBD>$^<5E><><16><><EFBFBD>{!k <0B><> <0C><><EFBFBD> ~<7E><>Gz P<13>ܐj.J.<<3C><><><6D>ijt<6A>pN<70><4E>L3Jr.<2E>$<24>Es<45>q(7ښ<37><DA9A><EFBFBD><EFBFBD>Ȥ<EFBFBD><C8A4><EFBFBD><EFBFBD><EFBFBD>^X<>7<EFBFBD>UOU6<55> J<><4A>aL<61>2<EFBFBD><32><EFBFBD><EFBFBD><14>C<>2<EFBFBD>l<><16>iN<69><4E>]<14><><31>F<EFBFBD>&Le%<25>"Xݕ<58>ζ<EFBFBD>r%<25>m<EFBFBD><6D> <0C>K<EFBFBD><4B>/I<>F<EFBFBD>,<2C>*<2A>Bc?r<><72>_kӌ<D38C>W9<57>ݴ<11>F<><46><EFBFBD><EFBFBD>d<EFBFBD><64><EFBFBD><EFBFBD><EFBFBD>]<5D>((!<21><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>(<28><>A<EFBFBD>"'<27>\xk΍<6B>Q<EFBFBD>a!9F'W<>G<13><><EFBFBD>y<EFBFBD><79>U4<10>B<EFBFBD>s<EFBFBD><73>j$<24><><EFBFBD>D<EFBFBD>NF<4E><46>G  <0F>[<5B> <20><> <0B>K<EFBFBD><4B>@8<><38><EFBFBD>Oo<19><>|Oh<><68>SQ<1F><><EFBFBD><0F>q<EFBFBD><1F>K<EFBFBD>@<40>s<EFBFBD><73><EFBFBD>H<><48>ϙo<CF99><6F><EFBFBD>b^bǷm<C7B7><6D><0E><1C><>R<EFBFBD>J<EFBFBD><4A>l<EFBFBD><6C>5 <20>H<EFBFBD><48><EFBFBD><EFBFBD>؁5<>\^<5E>*<2A><><EFBFBD><17>0<EFBFBD>q.<2E><><EFBFBD>v<EFBFBD><76>X<EFBFBD><58><EFBFBD><EFBFBD><EFBFBD>Q<EFBFBD>Է0<D4B7><30>b<EFBFBD><62>/;ۈ*<2A><>R[<5B>{<7B>*R<>V<EFBFBD><56><EFBFBD>B<EFBFBD><42>„<><DC8D>;<08>l3<17>5<EFBFBD><<3C><><EFBFBD>goF|<7C>A<EFBFBD><41><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD><63><EFBFBD><04>:<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>MK<4D><17><><EFBFBD>"J#<23><>޶<EFBFBD>8<EFBFBD>.<2E>†<EFBFBD><C286><EFBFBD>'<27><><EFBFBD><EFBFBD><17><16>s<>%̯<>yjm<6A>E<EFBFBD>]5|y9<79>41<34>U<EFBFBD><55><EFBFBD><EFBFBD>{]& w_k<5F>r<EFBFBD><11><>{<7B>sv}/<2F>ƲcSH(<28>R <0A>w<EFBFBD><77> Sd'EW<45><57>X<EFBFBD><58>.g<><67>_<EFBFBD><5F>&<26><>c<EFBFBD><63>QrDtO<>ihqf<71>-V#¾<><C2BE><EFBFBD>@<40><>X+[<5B>r<EFBFBD>RM*<2A><0E>\<5C><>P,<2C>X]O<>OB<4F> U<><55><EFBFBD>vP<><50><EFBFBD>ݺ<EFBFBD>¿vWF<57><46>/<2F>y<>v<EFBFBD><76>m <09>c <09><><08><><EFBFBD>!S<>y<13><><EFBFBD>k<EFBFBD> V<><56><1B><><EFBFBD>_<EFBFBD><5F>]|<7C>c&=$<24><><1D>e<EFBFBD>9<EFBFBD>IDl<1F>,dԿw<D4BF>\<5C>2t<32><74>a<7F>e<EFBFBD><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>d[<5B>rB<72><42> <07><>W<EFBFBD><57><EFBFBD><EFBFBD><EFBFBD>2<EFBFBD><32><18><>L<EFBFBD>`<1C><><EFBFBD><EFBFBD>D@<40>E{<7B><>jw<6A>w<>?]<5D><><EFBFBD>"<22><02><EFBFBD>5<EFBFBD>[1<1C>30H?<3F>8<EFBFBD><38><EFBFBD>R><3E>)<29><>t<EFBFBD>毌e<E6AF8C>.@oa<6F>i<EFBFBD>)<29>.*<2A>@=Ef<45><66><EFBFBD><EFBFBD><EFBFBD>e<EFBFBD><65><EFBFBD>u<EFBFBD><00>Q:*<2A>X<EFBFBD>E@<40><>X{ XRc j<>eIR<49>O<EFBFBD><4F><EFBFBD>@<40><03>k,<07><>P<EFBFBD><50><EFBFBD>MA<4D>^+W<>z<EFBFBD><7A>c^%E}<7D>VfN<66><4E><EFBFBD><EFBFBD>&<1A><>X<1F><><0E>o<06><><EFBFBD>@<40><03>Z<EFBFBD>?<3F>><3E> __B<5F>c<EFBFBD><63>O<EFBFBD>c!Ż}ؖ <0B><><EFBFBD>p<EFBFBD>5<EFBFBD>!<21><>W+K<>,<2C>{=<3D>V:<3A><>4<EFBFBD>7~<7E>?'<27>O<EFBFBD>U\<5C>
<EFBFBD>}<7D><>Ydk7H\s <0C>x?V<>*]<5D><>P<EFBFBD>f45v<04>X<EFBFBD>'<27>#<23>,<1B><><EFBFBD>"<22>Ϛ<><CF9A><EFBFBD><EFBFBD><EFBFBD>Qݗlp <0C><>&p <10><<3C><1E>=0<>u<EFBFBD><75><EFBFBD><EFBFBD>0<1A><><EFBFBD>W<EFBFBD>"<22><><EFBFBD>Y.G?(<28><><EFBFBD> <09><><<18>.to<>J<08>|<7C><17><><08><>G<EFBFBD><47>1<<16><><EFBFBD>ʹ<EFBFBD><CDB4><08>ȇd<C887><64><03>| 'P<1F>?<3F><><12> r G?<18><10><>m`f<>@<40><><1A><>#A<>@=<3D><><EFBFBD><1A><>θ|7.@<40>v5&<26><><EFBFBD>P<><50><EFBFBD><EFBFBD>Ju<00>ALРp{<7B>tn<74><6E>,<2C><>7C<37><1B>j6\Q<><51><EFBFBD><EFBFBD><EFBFBD>@\<5C>]<5D><>H+<2B><><EFBFBD>4<><34>_<><5F>F<EFBFBD><46>[k<> <$<24><><17><>ٮR<D9AE> <0C><><EFBFBD><EFBFBD>4Kﱱ<4B>w͆<1A><5A><CC84><EFBFBD><EFBFBD>c.Ϩ<>\<5C>p<>sa]mf<6D><66><EFBFBD>!(<28><><EFBFBD>Y<1B><14><><EFBFBD>2W<<14>o<EFBFBD>*Œ<> <0C>m9=<3D>1<EFBFBD><31>BA<42>=d8!Nf<4E><66><EFBFBD><06><><EFBFBD>8<EFBFBD><38><EFBFBD><EFBFBD>i<EFBFBD><69>ZS;o<><6F>2<><32>b<>P.<01>;<14>v<EFBFBD>1G<31>/<2F><><12><>_<EFBFBD> <0C><04>tՏ<74>v9O<39>xO<78>`Ory<72><79><EFBFBD>%<25><>B<EFBFBD>+<2B>N61<><31>m<EFBFBD>ƞ{<7B>`:<3A><>%<25><><EFBFBD><EFBFBD>B<EFBFBD>|<7C> <20>]0<>
<EFBFBD>5<EFBFBD>_ۿ]<5D><><12>H<EFBFBD>w <0C>݆03+A<><01><>Ů<EFBFBD><C5AE>VĂz<C482>/<1C><><EFBFBD><EFBFBD><EFBFBD><06><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>]P<><50><EFBFBD>lsF<73><46>ې<>gD<67><1B>d<EFBFBD><64>_<EFBFBD><07><><EFBFBD><EFBFBD>Tho<68> @<40>f<EFBFBD><43><CDA7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><17><17>N""<22><><EFBFBD> :<3A>x<>u_M<5F>x<EFBFBD><78>C%u<><75><0F><>;<3B>x<EFBFBD><78>o<EFBFBD><6F><EFBFBD>b<EFBFBD>><3E>)f<0E><><1C><><EFBFBD><EFBFBD><EFBFBD>s<18><><EFBFBD><1B><><1B>7o<37><6F>D=" WQ<57>[<5B><>AF<41><1F>T<EFBFBD>Y$<19>t )s!<21><>K<EFBFBD>J b<>+<2B>{<7B><>(<28>
P<EFBFBD> <20>מ<EFBFBD>oss<73><73><EFBFBD><EFBFBD>=<3D>ڃ<EFBFBD>s<EFBFBD>P&<26><12><1B><5A>*Z<>}<7D> I<><49>G<EFBFBD><><E58893><EFBFBD>K<EFBFBD><4B>j<01>b<EFBFBD>8o@<40>,<2C>q<EFBFBD>gX99<39><39><EFBFBD>ݠ<EFBFBD><DDA0>C<EFBFBD><43> <0A><>{%<25><0E>YK8<4B><38>Ӹu<D3B8>a<EFBFBD><61><EFBFBD>R<EFBFBD><52><16>!<05><>L-<2D><15>2VpDbt<62><74><EFBFBD><EFBFBD>B<EFBFBD><42><EFBFBD>_<EFBFBD>$`a<>yq<><71><EFBFBD><EFBFBD>ńH<10><>/<2F><><EFBFBD><EFBFBD><EFBFBD><0E>'<27>%<25>)r<><72><17>5Z<>P<EFBFBD>(<28>1<EFBFBD><08>hT<>A<EFBFBD><41><EFBFBD><EFBFBD>OX<4F>(<28>WC<57>
CO<EFBFBD>p-<2D>p<EFBFBD><70><EFBFBD>7<EFBFBD><1F>1<EFBFBD><31><EFBFBD><EFBFBD>f<e0<65>d<EFBFBD>a/<2F><08><>144<16>'<27><> <20><07>5<>!<1B><>~<18>>Y<>2^s<>E<EFBFBD><15> <20>(]<5D><><EFBFBD>!<21><>uQ<75><51><EFBFBD>2[<5B> <0B>M<EFBFBD>'R<<3C>bҒY[|<7C>'D3<<3C>˒<1C><><EFBFBD>ə<EFBFBD>^;<3B><>UJ<55>B<06><10>#c<><63><EFBFBD><EFBFBD>Dwo<77><6F>@<40>H<EFBFBD>,<2C><><1E><>/P@y<><79>:<05><>c<EFBFBD>?<3F><EFBFBD><7F><EFBFBD><EFBFBD>Q?yG^<5E> ˴<>1<<3C>L<EFBFBD><18>=F<><1D>1L$<24>IG<49><47>xrx<72>-<2D>J`<60><0E>h<EFBFBD>.z1$<24>:,<2C>uS<>b5<62><35><>߅i<DF85><69>e Sk<53>+$_<>,<2C>P=B<><42><EFBFBD>z <09><>ؑ<13> <0A><><EFBFBD>
<EFBFBD>W8<>.<16><><EFBFBD> <0C><>"> <20><><EFBFBD>Ŝ<EFBFBD>l<EFBFBD><6C>7&<26><><EFBFBD><EFBFBD>QS<51>,Q<>W<EFBFBD><57>@<40>7<EFBFBD><37><><C4A6>D<EFBFBD>+|]JFɂ<46><C982>sYP~<7E>;;m<><6D><EFBFBD><EFBFBD><EFBFBD>C<EFBFBD>y<EFBFBD>eii<14>Z_<5A><16>I<17>"S<><53>a<EFBFBD>+wܦB<DCA6><06>L<1E>7,<03><><08> <0C><><EFBFBD>L<EFBFBD>M<EFBFBD>ϻ<1A>g<EFBFBD><67><EFBFBD>B<EFBFBD><42>5C<35><43>l<EFBFBD> p<>bV<62>B[^<5E><>V<EFBFBD><1B><>Pi)9q<39><71>_2:t<><74><EFBFBD><EFBFBD>nA<6E><41><EFBFBD>s<EFBFBD><73><EFBFBD><17>4<EFBFBD><34><EFBFBD>kx=.<2E>?U6qc<71><63><EFBFBD><EFBFBD>8<EFBFBD>7uBD<42>-<2D><>p7<19><>ro<72><6F>
#5XuK<75>ʼ<EFBFBD>X\~<7E><<3C>z.<2E><><EFBFBD><E38AAF><EFBFBD>'<06>[<5B><><EFBFBD><EFBFBD>t<EFBFBD>8<11><>p=<3D><><18><><EFBFBD>"<22>]S<><53>פn<D7A4>w<EFBFBD><77><EFBFBD><05>\<Q<><51><EFBFBD>ʍ <0C><>m\R<><52>EL\<5C><><EFBFBD>}k<>*<2A><>Oۯs<DBAF>8.<2E>ʊM<0E>x-<2D>^<5E> <0B><> U<><55> <09>VCc<43><63>"<22> Ov<4F><76><08>v<EFBFBD><76><EFBFBD>*<2A><>@<40>L}l<><6C><EFBFBD>P"<22><><EFBFBD>V<EFBFBD><56>n)<07><>"+<2B><>L\<5C>N<EFBFBD><4E>| )E<0F>v<1B><><18>P<EFBFBD>\<5C>2P<32>ԝ.<2E>VV@ <20><>!f<>QYu3<><02><>%t<><74>^<5E><>/3<0E><>%<25><>(%<25>ė
%<25>m
<EFBFBD>m<><6D>ۭ<1A>r
c<EFBFBD><07><><11><>4,p<>Tڔ"<22>vUP<> 4R־<52>Z<>M<EFBFBD>H<>)w<01>-<2D><03>ayy<19><>FJ<46><4A><EFBFBD>I<><49>f<EFBFBD><66><EFBFBD>G\<5C>j^{<1C>;<3B>J<EFBFBD><16>a!$<24>=O_<4F>amP<6D><50><EFBFBD><1E><>j<EFBFBD>kI<>w<EFBFBD> <0B><>S<EFBFBD><53><EFBFBD>Ze<5A>3<EFBFBD>l<EFBFBD><6C>,<2C>\6<>%<25><><EFBFBD>'<27>V<EFBFBD><56>ckG.Q<>A_<41><5F><01><>g<EFBFBD><67>d<0F>(<28><>L:<1E><68>aa<61><61><EFBFBD><<3C><><EFBFBD>A<><41>ɲR<C9B2><52><EFBFBD><EFBFBD><EFBFBD>F<EFBFBD>R<1F>W@"<22>{-<14><><EFBFBD>)|k<><6B><EFBFBD><02>#R滇<52>:"<11>j<EFBFBD><6A><EFBFBD>;B<><42>4<EFBFBD><07><><EFBFBD><EFBFBD><10><>O<>S<EFBFBD><53><EFBFBD><EFBFBD>.<2E><>f{L<>a<EFBFBD>.<2E><><EFBFBD><EFBFBD><EFBFBD>z{<7B>'F<>k<1D><>ז^<5E><>S/<2F>w<EFBFBD><77> Q„5<C284>WM<57><4D> elρ<6C>{<7B><>C<><43>r<04><>d<EFBFBD><64>ᰨlB<6C><42>gYtDl5C<35>\<5C>T <20>K<EFBFBD><4B><EFBFBD><EFBFBD><EFBFBD>c#>O<><4F><EFBFBD><EFBFBD><EFBFBD>)OKG2F<32><46>m<EFBFBD><6D><EFBFBD>'<27><> <0A><><EFBFBD>q<EFBFBD>?<3F>O<EFBFBD><4F><EFBFBD>/<07>g<EFBFBD><67>փ<EFBFBD>]<5D>N<EFBFBD><4E>A<EFBFBD>%f<>Rl5<6C> }<7D><><EFBFBD><EFBFBD>k9<06><>K<EFBFBD>~<7E>q<EFBFBD><15><>b<EFBFBD>
){uRO<52><05>t<EFBFBD><74>vDݷ<44><DDB7><EFBFBD>4gX<67>)Qܥ<51><DCA5><EFBFBD><EFBFBD>8<EFBFBD>;ڤd_E<5F>` <09><><EFBFBD><EFBFBD>28<32>]Տ<><D58F>-H_<48><5F>Zu]<5D><16><>l<EFBFBD>8 ·jӔ<6A><D394>P<EFBFBD><50><EFBFBD>F<EFBFBD>F<1C>><3E><04>. <10><><EFBFBD><EFBFBD><EFBFBD>xF0<46><30>bC<62><43>}<7D><><EFBFBD><EFBFBD>`<60>E<EFBFBD>@<40><><EFBFBD><EFBFBD> <0A><>1 s<>2<EFBFBD>WѸC Y<><59><05><>0Xa<58><61>:B뷫ȷ<EBB7AB>S<EFBFBD>D7Fi<46>%E<>ʵ<EFBFBD>T<EFBFBD>ص<EFBFBD>G><3E>-<2D>1eV<65><56><EFBFBD><15>+*7<15>bX<19><><EFBFBD><EFBFBD>y*8D_a]̥\?<>]gN<67>ʠ=<3D><05><>$0;kl̵<1C>e<><65><EFBFBD>$m )<29><><EFBFBD>2<EFBFBD><32>RF"{s <09>K@)<29><>A
Ȇ<EFBFBD>N7<EFBFBD><EFBFBD>%<25>0<EFBFBD>BC<42><43>dtv<74><76>5<19>Վ<EFBFBD><D58E>j #dp<64> "<22>Zfd=<3D>K<EFBFBD><4B><EFBFBD><0F><>r<EFBFBD>in<69><6E><06><><EFBFBD>YY<1A><><EFBFBD><EFBFBD><EFBFBD>;<3B><>{o5<6F><05>
3D<>*<2A>f<EFBFBD>H<EFBFBD>H<EFBFBD>;<3B><><EFBFBD>y<EFBFBD>><3E><>s<14>G<EFBFBD><47>Rz<52>49<34><39><EFBFBD>G<07>R#9Hf<48><66>pU<70>\<5C><><EFBFBD>ES<45>&<26>P<EFBFBD><50><<03><><EFBFBD><13><><EFBFBD>W.q_}<7D><><EFBFBD><EFBFBD>f/<2F>.<2E><><EFBFBD>-<2D>VJ <09>7o<>3<EFBFBD>?$H<><48><EFBFBD><EFBFBD>)r<>@<40>(C<>\fL<>G<EFBFBD><47><EFBFBD>n<EFBFBD><6E><EFBFBD><EFBFBD>C<EFBFBD>v/<2F>o<6F><7F><EFBFBD>=<3D><><EFBFBD><EFBFBD><EFBFBD>[<5B> <1B><>L:<3A><><EFBFBD>|1pv<70><76>u<><75>tg<74>v<10>b%<25>z<EFBFBD>$<24><>`<16><>̘m<CC98>(W#<23>F<EFBFBD>Q<EFBFBD>,<2C><>;<3B>Q><3E>r݈>Jg <09><><EFBFBD><EFBFBD>ֹT;g<>a[*<2A> WP bCK<43><4B><EFBFBD>EQʇ<51><CA87><EFBFBD><EFBFBD><EFBFBD>D<02><><EFBFBD><EFBFBD><EFBFBD>}<7D><><EFBFBD>*<2A><>ҕ<EFBFBD>'<17><>B˕5<CB95><35>L\r!8<>e<11><>R<EFBFBD>&<26>̭<EFBFBD><CCAD><EFBFBD><EFBFBD>#<23><>{Y<><59><EFBFBD><EFBFBD><EFBFBD><EFBFBD>=<3D><><EFBFBD>5<EFBFBD>~! <15>k<EFBFBD><6B>ɹ<>0R<30>[<5B><>;<3B><><EFBFBD><EFBFBD>L<05><17>!s<><73> <09><1B><>x4Pҗz#j<><6A>?WZ<57>Q<+<2B>;<3B><>O<EFBFBD><4F><EFBFBD>N<EFBFBD><4E>2<EFBFBD>IBc<02>^<5E>U <0C><><1F>N<>*<2A>5X<><58>t<EFBFBD>B<EFBFBD>-!<21>h<EFBFBD>Q<EFBFBD>c<EFBFBD>=b<>K<EFBFBD>i<EFBFBD>X<EFBFBD><58><06><>_<EFBFBD>n<EFBFBD><07>ekP<6B><13>p<EFBFBD><70><16>X<EFBFBD><58><EFBFBD><EFBFBD>{<7B>W<EFBFBD><57>Q<EFBFBD>S<0E><B<><42>l<>t[P<><50><EFBFBD><17><><EFBFBD>z<EFBFBD><7A><EFBFBD><EFBFBD>D#?&<00>G<EFBFBD>srr<72><72><EFBFBD>W"}<7D><05><>d<15><>u|d<><64><EFBFBD><E89FAA><EFBFBD><EFBFBD>YL<59><4C>_Zl<5A><6C><EFBFBD>l<>C}<10><EFBFBD>a<EFBFBD>}:<3A><>[Bo$У|<7C>K<><4B>pZ<0F><>ʹC<CDB4>i<EFBFBD>4?s<>0<EFBFBD><30>y<EFBFBD>=<3D>ߏ<EFBFBD><DF8F><EFBFBD><EFBFBD>Џ<EFBFBD>+-<2D>.<2E>d<EFBFBD><64><EFBFBD>B<>m<EFBFBD><15><><EFBFBD><EFBFBD>b(=<3D>aP<61><50>իH<10><>T<><54><EFBFBD>[<5B><><06><><14>w <09><0E>;<3B><><EFBFBD>br<62><00><>&<26><1E>6%Ԋ<>m򎀟<> uIg<49>ΈX<CE88>6н?<3F>GPBx<42>.<2E><>z<EFBFBD><EFBFBD><7F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>mj;<6A><CDBE>O<EFBFBD>a<EFBFBD>qP<>`<60>NQ<4E>C<EFBFBD>yba<62><61>qȴd<C8B4><64><EFBFBD><06><>-q<><71><EFBFBD><EFBFBD> <1A>Ъ <05><>C4>nl<6E><6C>(a<19>c9<1E>vr<1E><><EFBFBD> :<3A><>[d|跄<><1F>]<5D>k/ <0B><><0E>O`<60>d<EFBFBD><64>=b<>-x]<5D><><EFBFBD>S<EFBFBD><53>܈ <0A>I<EFBFBD><49><EFBFBD>}<7D>r<EFBFBD>*B<><42>v<><76>;<3B>Af<14>9<EFBFBD><17>d<EFBFBD>s:?k<><6B> bg<>C<EFBFBD>D<>h<EFBFBD><68><EFBFBD><EFBFBD> 5<> y7<>֜o<D69C><6F><EFBFBD>F`0<>Q<><51>f<EFBFBD>o<EFBFBD><6F>vj-7<><37><EFBFBD>A<EFBFBD><41>A<EFBFBD><41><EFBFBD><EFBFBD><EFBFBD>χ<EFBFBD><CF87>q<EFBFBD><71>綫vg<76>x<EFBFBD>>'<27>{f<><66>l<<3C><>l)V<><56>X<EFBFBD><58>`<60><>k<EFBFBD>7'l<><6C>A<EFBFBD>f?p <09><1D><>%v<>J<EFBFBD>/h&K<>r^<5E><01>h<EFBFBD><68>j<EFBFBD><6A><EFBFBD>X<EFBFBD><58><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <0B>. <0B><>{<7B><><0E>tD5b<35><62><EFBFBD><EFBFBD><EFBFBD>2<EFBFBD><03>:^<5E>^<5E>"<<3C><>Y<EFBFBD><08>ƀi<C680><1D><02>}XY<58>sVݬEj⃐T<E28390>ަ,%<25><1C><>p5<70>!<21>_E1|ed<65>l@<40>؞<EFBFBD>OAE<41><45><EFBFBD><EFBFBD><EFBFBD>6{p<>ɝ<EFBFBD><C99D><EFBFBD><EFBFBD>a<EFBFBD><61>d[<5B><><EFBFBD>
<EFBFBD>><3E><><EFBFBD><EFBFBD><EFBFBD>'%<25><><EFBFBD><EFBFBD>\<5C>
Eb<EFBFBD><EFBFBD><07><02><><EFBFBD><EFBFBD>/1<><15>y6<79>",z2ۘ<32>><1A>]<5D>4<EFBFBD>Td<54><64><EFBFBD>x<EFBFBD>t<06>NI!<21>g;I<>ؼ<EFBFBD>-<2D><>%<25>z?<3F>v<><76>?;<05><>w,ܞ<><DC9E><1A>V<><56><EFBFBD><0E><><EFBFBD>T<EFBFBD>޾<EFBFBD><DEBE>j3<6A><33>¾n<C2BE><6E><EFBFBD>K9)<29><><EFBFBD>)n<> ><3E>.<2E>=m<>;ȝ)4<><34>?<3F><>0{R<>eq~<7E><>%l<00>E <09><>xT<78><54>r<EFBFBD><72> )t<><74>3
<EFBFBD>(# <0B><><13>N <10>'<27>(`<60>*c2<63><32>ϰ<><CFB0><EFBFBD>K(<12><><EFBFBD>JT<4A><54><EFBFBD><EFBFBD><EFBFBD><12><13><>E, <1D><>#<23>f<> q<>Y<EFBFBD>+
<1D><07>9<EFBFBD><39>Y<EFBFBD><59>|<7C>
<EFBFBD>c<EFBFBD><EFBFBD>%m<><6D><EFBFBD><EFBFBD>·<EFBFBD>{<7B>Ӵ`<60>V<EFBFBD>R3<52><33>E<EFBFBD>^<5E>`'ʈ<>"'<27>A<EFBFBD><#<23>"<22><><EFBFBD>X<04><>M<><4D>h<EFBFBD>x<EFBFBD>(tKN'<27><><EFBFBD><EFBFBD><EFBFBD>Я<EFBFBD><D0AF>l<EFBFBD>X_<58>bۯř<DBAF><19><><19><>p<><13><>Cu<05><><EFBFBD>oG<04>Y<EFBFBD>/<10>t<EFBFBD><74>:Xv<58><76>lb<10>3h<33><68><EFBFBD>yW-8-ZBѷ !<21><0F><><EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD>/<14>t4:.<2E><><13>t<EFBFBD>!
<EFBFBD>[%IȬpR<70><11>,<2C><><EFBFBD>Q<EFBFBD>(<28><>?3*<2A><>N<7F><4E><EFBFBD><EFBFBD>I<EFBFBD><49><EFBFBD><EFBFBD> <0B><><EFBFBD>=?<3F>ٙ#2n<32><6E><EFBFBD>mY<05><06><><EFBFBD>z<EFBFBD><7A><EFBFBD>B<EFBFBD><42><EFBFBD><1C>Dc/ <20>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>-<2D>3<EFBFBD>@ <20>\MB<4D>.<2E><> -<18>9O [<5B><> <0A><><EFBFBD><EFBFBD><EFBFBD>P<EFBFBD><42><D89B>
<0B><><EFBFBD><05>l<EFBFBD><6C><EFBFBD>j<EFBFBD><6A>/<2F><> u<><75><EFBFBD><EFBFBD>Bo<42>L}<7D>/n<03>P<> Ʈ.<2E>a<1C>f#<00>L<EFBFBD><4C><EFBFBD><EFBFBD><EFBFBD>%A1ŧJ4+<2B>H<EFBFBD><48>4<EFBFBD><34><EFBFBD>t<EFBFBD><74>N<EFBFBD>?<3F><><EFBFBD> J<14>+<2B><>+<1D><><<3C><>G <0A><><EFBFBD>W<>Z<EFBFBD> <14><>ն#A<><41>&<26>Ți<C89A><7F><E6B2BA>^<5E><>%<25><11> | ҰPJ&LG,.ƾ<><15><><EFBFBD><EFBFBD>q<EFBFBD>j<05><><EFBFBD><EFBFBD>2<EFBFBD>|q<><18>uO<75><08>:<0E><><EFBFBD><EFBFBD>j<EFBFBD><6A>2<EFBFBD><15><><EFBFBD>@<40><>~[<00><><EFBFBD>5y<35>D<EFBFBD>B<EFBFBD><42>jZņ<5A>k<14><>cO<63><4F><EFBFBD>A^p<><70><EFBFBD><EFBFBD>%<25>&<26><>~<1A><><EFBFBD><14><>u<EFBFBD>
Gb<05>rk9<6B><39>Z<14><>\<5C>X<><58><EFBFBD><EFBFBD>t<EFBFBD>m0<6D><30>b<EFBFBD><11><14><> <09><><EFBFBD><EFBFBD>l<EFBFBD><6C>tj<74><6A>_<EFBFBD>u<EFBFBD><75>PJ<>?G<>G<EFBFBD><47>g<02><><EFBFBD><EFBFBD><12><> <20><>`ʫ<>h^<5E><>Q<03><>VmE2x<>-<2D>fA<66><41><EFBFBD>Xj<58><6A>Q<EFBFBD>-ŰG<C5B0> M8<4D><38>M<EFBFBD>>b<00><>Bi씮<69><EC94AE><EFBFBD><EFBFBD>o¤;<3B>(<28>~<7E><><<3C><><EFBFBD>&<26>U<EFBFBD><55><EFBFBD><EFBFBD>ؖ<EFBFBD><D896><EFBFBD>~<13>&<26>d;s<><73>ς)D0<44><30><EFBFBD><EFBFBD>g<EFBFBD><67><EFBFBD><EFBFBD><EFBFBD><EFBFBD>0<EFBFBD><30><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>-:><3E><>vh<76><68>'<27><><EFBFBD> ]NJR@v<16>i<EFBFBD><69>_<<3C><>M<EFBFBD>Sm<53>j<6A>ό(I<><49>*%<25><><EFBFBD>/}<7D>eB<65><04><><EFBFBD><EFBFBD>]<5D><>f<16>++<2B>Ѱ<EFBFBD>[<5B><> !<21><><EFBFBD><EFBFBD><EFBFBD>Sh<53>G<EFBFBD>?<3F>(<28>ZX۵<58><DBB5>Ҳun]d<>z<>>ǿ<><C7BF>y<EFBFBD><79><EFBFBD><EFBFBD><EFBFBD>txыA<D18B>M<EFBFBD>M\<5C><><1A><>><3E><12><>|`<60><15>u<EFBFBD>wp<12>Ae6<65><36><EFBFBD>\<5C><><EFBFBD>+Ml<4D>2F<32>T<EFBFBD><07>P<EFBFBD>5<EFBFBD><35>20X<30><58> <09>v g<>+<2B>h, <09>V<12>R<EFBFBD>>X<>%B<<3C>q*Ӻ<><D3BA>L*<2A>T<16><><EFBFBD> <20>c<EFBFBD><63>!<21>.<03><><EFBFBD><EFBFBD>ŮIק<49>;<3B>ɻ<EFBFBD> <0B>S<EFBFBD><53>ϣ<10>o<EFBFBD>n<EFBFBD>4<EFBFBD><34><EFBFBD><EFBFBD>%<00><>][AC`C-9<><39>܎<EFBFBD><DC8E><EFBFBD>6Y<36><59><EFBFBD>`<1B>rt<72><74><EFBFBD>Y<1B>2d<32><14>{<7B>$<24>dۜ<>D<EFBFBD><44><<3C><><EFBFBD><12><1F><>1<EFBFBD><31><EFBFBD>:<3A>Y<1C>{<7B><10><>C<EFBFBD>,5C<1D><>o<00><><EFBFBD>Wdk<>8<EFBFBD><16>d<><64><1E><><0E>U<EFBFBD>[<5B>><3E>Gyu@<40><1B><>9<EFBFBD><39>%<25><>p<EFBFBD><08>zL`i ~<7E>Ď<EFBFBD><C48E><EFBFBD>j<EFBFBD>Q<EFBFBD>J ,L<>><3E> _ C<>|<7C>e<1A>[<5B><19>c<0E>i<EFBFBD><69>U<EFBFBD>h<EFBFBD>*<2A><><EFBFBD>6<EFBFBD><36>A<EFBFBD><41><EFBFBD>Ut"<22>Cio|,<2C>Cy<>Ƭ<EFBFBD>
<EFBFBD>I<EFBFBD><EFBFBD>*<2A><><EFBFBD> <09><>J<EFBFBD>_<EFBFBD> <0B>Cv <09>vU0<55>C8<43>]0<><30><EFBFBD>b&Ԑ<>\(|<7C>v<>&<26>XVݡ<1B>#:AC!<21>q<EFBFBD><71><EFBFBD>,<2C><>Wr<57><72><EFBFBD><EFBFBD><EFBFBD>D<EFBFBD><1A>L<EFBFBD><4C><08>M>%DK<44><4B> çHsTQV<1F>o,<2C>~<7E>Pшr<D188>/<2F><><EFBFBD><EFBFBD>UxP<78><50><EFBFBD>/<2F> yF1<46>/f[<5B><00>2<EFBFBD>Ak<41>ip<69>]<5D><><EFBFBD><EFBFBD>:<3A>h<EFBFBD><18>2<0F><<3C>0ݨ^ $C|'v 5<><35>xM<78>1BǓ<><C793>b<EFBFBD>"<0F>?<3F>?<3F><><EFBFBD><EFBFBD><EFBFBD>q><3E>m<EFBFBD>љh<>nX?+<2B><>gO<67>P<EFBFBD><50><36> tR,%I<><49>}<7D>~<7E><><08>y<EFBFBD><79><EFBFBD><EFBFBD><EFBFBD>';<3B>c<><63><EFBFBD><EFBFBD>9<EFBFBD>FC/<2F>z<EFBFBD>><3E>5<EFBFBD><35><EFBFBD>U
<EFBFBD>m*<2A>5@<40><><EFBFBD><EFBFBD>H<EFBFBD>%
UK<EFBFBD><EFBFBD>p<EFBFBD>k:$<24>-z _T<><54>5<EFBFBD><35>U-<2D>#<23><>J1[
><3E><><EFBFBD>W<EFBFBD><07>@$<24>CI=)<15><>v%ۘ!<21><13>:<3A><><>=Pv<7F><76><EFBFBD><EFBFBD>?=<3D><><EFBFBD>-<2D><>uF<75>LB<4C>K<EFBFBD>ɥ<EFBFBD><02><><EFBFBD><EFBFBD><EFBFBD><14>w<EFBFBD><77>jj<6A><6A><EFBFBD><EFBFBD>P<EFBFBD><50><EFBFBD>*hpϥ<70> <0C>L<4C><7F>p><3E>j4<6A><34><EFBFBD>$1m<31>-P8Dy<0E>unv<1C>]<5D><>}<7D>ƴ<EFBFBD>K<EFBFBD>4 <0A>.<2E><06><><EFBFBD>P<>19<31>4<EFBFBD><34><EFBFBD><EFBFBD><EFBFBD>'<27>?E<><04>gD<67>s<EFBFBD><73><03>T<EFBFBD>Xci<63>n<EFBFBD>B<EFBFBD>2<EFBFBD><32><EFBFBD>FC<46><43><08>ܿ<EFBFBD><DCBF><EFBFBD><EFBFBD><06><>C5"<22>$)ٛ<>̱n<CCB1><6E>A<EFBFBD><41><EFBFBD><17>IW<49>S<EFBFBD>G<EFBFBD><47>O)<29>Q<EFBFBD><02>,<2C>'`<60><75><C78D>t<EFBFBD>#<23>yPu<50>|b <0B><><EFBFBD>s}<7D>kF<6B><46><05><1D>u`<60>õ Rb<52>e<EFBFBD><65>h$3zZa<1E><><EFBFBD>Q<52>\<5C><16><> <0C><>%<25><>
<EFBFBD>_<EFBFBD><EFBFBD> <0B>+ࣉ,I<><49>U<55><EFA194>]<5D>=<3D><>u<EFBFBD><75>z<EFBFBD><7A><EFBFBD><07><><EFBFBD> 5<>Ю;H<>`ZP=<3D><><EFBFBD><EFBFBD>k<EFBFBD>Î<EFBFBD><C38E><16>.<11>PXF޾B[G<06>Hv<48>bNI<08>{C<>B<EFBFBD> <0B><>(
Q<EFBFBD>%"<22>3@<40>z<EFBFBD>d<EFBFBD>Xn<58>9<EFBFBD>cE<63><45> s<><73>Z,9]<5D>!<21>K<EFBFBD>4<EFBFBD>y<><79>>k<>K:<3A><><EFBFBD>j<>r<EFBFBD>;!Ib<14>;:Bgm<67>-%<25>M<EFBFBD><02>%7<><37><EFBFBD>Z<EFBFBD><5A>?<16><>-?<3F><>(ͣM<koݡ<><DDA1><EFBFBD><EFBFBD>V<EFBFBD><56>D<EFBFBD><44>k<EFBFBD><6B>ȭ<17><><EFBFBD><EFBFBD>:<3A><>8<>%<25><>աU+<2B><1E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Si<53> <0C>i+<2B>x$#/<2F> <0C><EFBFBD><E887B9><EFBFBD>L<EFBFBD><1A><14><><EFBFBD><12>m<EFBFBD><a<><1E><>l<EFBFBD>أ`<60>ݫ<EFBFBD>
?6%z<>"<22><><00> `<60><>~<`[<5B>@><3E>߇<EFBFBD><DF87><EFBFBD>_<EFBFBD><5F>7vYz<59>
<09> z<><7A><EFBFBD><<04>'U<>4P<34><50>'<27>E<EFBFBD>-<2D> <0C>)\<5C><><EFBFBD>F<14> <0C><><EFBFBD>0<0E><><EFBFBD>aJY<0F><>Y<EFBFBD><59><08>g<EFBFBD><67><EFBFBD><EFBFBD><EFBFBD>$<24>\<5C>b<17>n<EFBFBD>ĝ<EFBFBD>~>P<><50>ϛ<EFBFBD><CF9B><EFBFBD><EFBFBD><EFBFBD><1B><>o<14>~fO<><4F>|iq<02><>d<EFBFBD><64>Q(<28>$<18><>|<7C>M<EFBFBD>],q-<2D><><EFBFBD><07><>"<22>TbGl<47><0E>8'<27>ة<EFBFBD>2<EFBFBD>%<25><><EFBFBD>cF<63><46><EFBFBD>u<EFBFBD><75>S<EFBFBD><53>*<2A>R<EFBFBD><52>V.<2E><>&<26><>z8<7A≯<EFBFBD><CCB8><EFBFBD>*<2A>-لX<D984><15>Nl<4E><6C><EFBFBD><EFBFBD>Zf<5A>jV<6A>fG?{<7B>9<EFBFBD>N\<5C>n<EFBFBD><6E>3<08><><EFBFBD><EFBFBD><14><>/<2F><><EFBFBD><EFBFBD>h<EFBFBD>8N<38><4E><1F>&<26><><19><>K<EFBFBD> <20><00>
m36<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>?(<28><1D><><EFBFBD><EFBFBD>(^<5E><><EFBFBD><EFBFBD>?<3F><14>&<26>%<25><>Lv<4C><1A>sF<73><46>%W<><57>q<EFBFBD><71><EFBFBD><EFBFBD>Զ(VB<56><42><EFBFBD><07><07><><EFBFBD><02><>m $<24>E<EFBFBD>hh[<5B><>l3ki<6B>y<EFBFBD><12>Y<EFBFBD><59>:<3A>`<60>a<EFBFBD>R<EFBFBD>I<EFBFBD>a<EFBFBD>a<1F>켜1B<31>;<3B>N8@<16><>[<5B>+<2B>U<EFBFBD><55><EFBFBD><EFBFBD>j<6A><7F><EFBFBD>QI<51>d<EFBFBD>#'kw*<2A>vg<76>#w0<10>w3<77>^<5E>(<28><06><>5(<13><>fD~<7E>?ld<6C><64>7?<01>5Ș<>t<EFBFBD>\p<><70><EFBFBD>)<29>x<EFBFBD>1v<07><><EFBFBD><EFBFBD><EFBFBD>Z<EFBFBD><5A><EFBFBD><EFBFBD><EFBFBD>$<24>Sc <0A>,<2C> <0C><>@~<0F>#iS,-_gtǠ<74><C7A0>f<>(<28><><04><><15><>(<28>xC&<26>DT;<3B>e<14>[<5B>7|<7C>oe<6F>p6p<36>aW<61>hzѤ<1F>;<3B><><EFBFBD>PHi<48><69>:D<>4W<34>6<EFBFBD>wZ<77><5A><EFBFBD>]vJ<76><4A><1B><><EFBFBD>K<><4B><EFBFBD><70><DFB9><EFBFBD><17>E <20>1<><31>Q:)z<14><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>zX<7A>~^<5E>* _`<60>eǽ%<04>};/$<24>ُ<EFBFBD>"<22><>p<EFBFBD><70>9a<39><61>&6\<5C><>'zo!<21><>T<EFBFBD>] <20><><EFBFBD>O@<40>%n0<6E>) <20><02><><EFBFBD>g@<40><>zr<@<40>A<EFBFBD>)<29>S<EFBFBD><53><EFBFBD><EFBFBD><EFBFBD><!<21><><EFBFBD><EFBFBD><EFBFBD><16><><01>6<EFBFBD>OZZ<5A><5A><14>R<>d$|4z<34>s}<7D>S<EFBFBD>q
<EFBFBD>cPR<EFBFBD>%<18><04>ϑ_O<5F><4F>\<5C>/<1F>G<><47><<3C><>'<27><>><3E><><EFBFBD><EFBFBD>r<EFBFBD>S< <0A><><EFBFBD>X~ <0A><><EFBFBD>|<7C><>7<EFBFBD><37> <20><><EFBFBD><EFBFBD>Q<EFBFBD><51><EFBFBD><EFBFBD>׉<<3C>N=<3D><><06>V<EFBFBD><1D> <09>n4<07><>1<EFBFBD>p{Rԗ<52><D497>͗b<08><>_d2[<5B><><EFBFBD>~<7E><>r<EFBFBD><1E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>f<EFBFBD><66>i<><69><EFBFBD><EFBFBD>`<60><><EFBFBD>@<40>0D<>z<14>'<27><><EFBFBD>Jo<4A>,<2C>@<40>k<EFBFBD>_<EFBFBD>/;<3B><><EFBFBD><EFBFBD>{M<>}<7D>I<EFBFBD>d<EFBFBD>n<EFBFBD><6E><EFBFBD><EFBFBD>⡐&<26><><EFBFBD><EFBFBD><EFBFBD><11><>/<2F>}<7D><1E>Q<EFBFBD>o6(<28>t:<18>C<EFBFBD><43>4-<2D>P<03><>[{8<>H<EFBFBD>Dž<EFBFBD>p<EFBFBD>u~&<26>aj<18>K0<4B><1C>N<1E>1 }B<>Q<EFBFBD>Qki<6B><69><EFBFBD>&<26><>#)t~<7E>7<EFBFBD>)M<><1B><><0F>=<3D><07>k<><6B><17><><EFBFBD><EFBFBD><>;eN@<40>f@<40><>ܧ<EFBFBD>־<08><>N<EFBFBD><4E><EFBFBD>S<>߾<EFBFBD><DFBE><EFBFBD><EFBFBD><EFBFBD>%<25><>O<EFBFBD><4F><EFBFBD><EFBFBD>L<EFBFBD><4C><11>vlJu<4A>[<5B>݇}<7D><><EFBFBD>h<EFBFBD>,<2C>~<7E>@<40><EFBFBD>2<7F><32>RU<52>j<EFBFBD><6A><EFBFBD><EFBFBD>7׌J<D78C>?r<><72><EFBFBD><EFBFBD># A<><41><EFBFBD><EFBFBD>yfx!f4\.<2E><>JNm<4E>v<><76>X<EFBFBD><58>\<5C>"<22><06><><00>#<23><><6F>\<5C><>L<EFBFBD><06><>t9ZM<5A><4D> <0C>RӤQ<D3A4>E<EFBFBD>ӌ5 XQ<58><51><61>]1<>%F7h<37>y[n8<6E> <09>b.p<>:<3A>}<10>4<EFBFBD> <05>q<EFBFBD><71><EFBFBD><EFBFBD>{52U<32>j<1C>ݛ <0C>j <0A>W"<22>rz<72><06>R-$<1D><><EFBFBD>(<28>8<EFBFBD>e<12>W<EFBFBD><57><EFBFBD>m<EFBFBD>g<EFBFBD>p<EFBFBD>i<EFBFBD>Ё<EFBFBD><D081>QY6%<25><>}
p<><70><EFBFBD><14>d<EFBFBD>[&8[V<><56>m<EFBFBD>(<28>K<EFBFBD>޽g<DEBD>2<00><>\<5C><><EFBFBD>!<01><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>=.<2E><><EFBFBD>F<>2m<32><15><>KP(<28>k<EFBFBD> =V<><56>g<1D>V&<26>R7ܫ<37>4#<23>/<2F><>#<23>[F<><07>Y<EFBFBD>qqb-)q<11>׺5<><35><EFBFBD>ȿ<EFBFBD>[aR7<52>u<07><><EFBFBD><15><>ۏ<EFBFBD><DB8F>4<EFBFBD>n<EFBFBD><6E>90<39><07>О<><D09E>Sdp<64>2<1B><>
<EFBFBD><EFBFBD><EFBFBD>?<3F><>a<19>t<EFBFBD><74>l?<3F>:qi<71><69> <09><><EFBFBD>l'0<><30><EFBFBD>3<EFBFBD>ن+<2B><>!<21><><EFBFBD>m3B<33>_Et<><74>pa`aџ=I<><49>z<EFBFBD> <0C>-<2D><><EFBFBD><EFBFBD>Q<7F>c<EFBFBD><63><EFBFBD>F &<26><1C>H<><48><EFBFBD>_Nӡs<01> e<>n<EFBFBD>u<EFBFBD>h<7F><68><EFBFBD>b<EFBFBD><62>'Y1أ=<3D>"W_` <0A>g]<5D><><17>x("*<14>v<1E><>;<1E><02><>?<3F>x<EFBFBD>u\ <17>|<7C>0<EFBFBD>edr<64>F5Z<35> <0B><>Ԋ1<D48A><31><EFBFBD><04>-3E(<28>y+"<22>><3E><><18>S' <20><><EFBFBD>ēhԤ<68><D4A4><EFBFBD>h<EFBFBD><68><EFBFBD>N<12><><EFBFBD><7F><EFBFBD><EFBFBD>"<22><><EFBFBD><EFBFBD>A,<2C>֠<EFBFBD> <09>&b<>Ե<><D4B5>"X<>F<>B<EFBFBD><42>С<EFBFBD><D0A1>(椭􎞟<E6A4AD><F48E9E9F>#<23><>e<EFBFBD>f=<1C>v<EFBFBD> <19>Л<EFBFBD><D09B>%-)<29>u<EFBFBD>.<2E>n<EFBFBD><6E>A<>_<EFBFBD><1B><>{<7B><> <0B>2!э<><15>;yʫ<79>]<5D>ŕz<C595> .<01><>vZD<5A> ,|76<37><36><EFBFBD>\<5C><><EFBFBD>jhL<68>FY]<5D><>v<EFBFBD><76><EFBFBD><EFBFBD><EFBFBD>*<2A>`<60>n<EFBFBD>cżc<C5BC><63>3s<33>P<EFBFBD><0E>{<7B><>k_<6B><5F><EFBFBD>V<><1D><><EFBFBD>I<01><><EFBFBD><EFBFBD>d<EFBFBD><64><WiM~j <0A>{ <09>9<EFBFBD>v<EFBFBD>u<EFBFBD><75><EFBFBD><EFBFBD>n<EFBFBD><18>N<EFBFBD>s<EFBFBD>/<2F><>z<0F><>̵1R<31>H<EFBFBD><><D79D>qD<71>gI9<49><39>`<60>[<5B>P?<<3C><>J<EFBFBD><04>6<EFBFBD>v<><76>t<EFBFBD><74><EFBFBD><EFBFBD>K<EFBFBD><14><>}<7D><10><>e<EFBFBD><65>\<5C><>ZA<5A><41><EFBFBD><EFBFBD>F?<3F><><EFBFBD><EFBFBD>@<40>3<EFBFBD>So<53><0E>#G~<7E>g<EFBFBD><67><EFBFBD><EFBFBD>3WIQt@<40><>NL<><4C><EFBFBD>2Μ<7F>gF<67>Ps<50><73>0 <20><>39<33><39><14><0E> <0A>t<EFBFBD>(<28>=<3D><>o<EFBFBD>A<EFBFBD><41>^<5E>=<3D>55Dž<35><1F>;8<03><>u<EFBFBD><75>0Zu<><75>ESt<53><74>]U<>
<EFBFBD>n<EFBFBD><EFBFBD>2<EFBFBD><EFBFBD>_<EFBFBD>of<6F>^0<>e<1D>!<<3C>q1&<18><00>*<2A>QW<51><57>n/ ~<7E><>C<><12>y)X<>"|W(<28><><EFBFBD><EFBFBD>3yL<>(<28><><EFBFBD><EFBFBD> <10><><EFBFBD><EFBFBD>o<EFBFBD>0<EFBFBD><30>d<EFBFBD><64><EFBFBD><EFBFBD><EFBFBD>H<EFBFBD><48><EFBFBD><EFBFBD><18>{<7B><><EFBFBD><01><>P<1A><>3<EFBFBD>B<EFBFBD><1E><><EFBFBD> F<>i<EFBFBD>]<5D><><EFBFBD><EFBFBD><EFBFBD> <09>
χ<EFBFBD><EFBFBD><0E>n<EFBFBD><6E>gZx<5A><78><EFBFBD><EFBFBD>Luʂ4<0E>@;7<>ʡ<EFBFBD><1D><><EFBFBD><EFBFBD>~U<>϶-W2/<2F>%<25><>w<EFBFBD>Bb\|<00><><EFBFBD>+<13><><EFBFBD>i[s<><14>uV<75><56>j~<7E>%<25>NHu<1B><><17><>JD<17>-<2D>o<EFBFBD><11><><EFBFBD><EFBFBD>> <0B><>ܒ<EFBFBD><DC92>5<EFBFBD><35>|<7C><><00><><EFBFBD><EFBFBD><EFBFBD><1F>f<EFBFBD>z<EFBFBD>IÅN<C385>x3<78><33><EFBFBD>g<EFBFBD><67>`Oz ]`j<19><><EFBFBD><EFBFBD>yI<79>K<EFBFBD><4B><EFBFBD>?j<><6A><EFBFBD>]<5D><>A<EFBFBD><41>+<2B><>pc<>K@<40><EFBFBD><7F>Og<00>E<EFBFBD>Z<EFBFBD><5A><EFBFBD>m<EFBFBD>P<EFBFBD> <0A><>Q<EFBFBD>5<EFBFBD>u<>j>촇<> 3<><33><EFBFBD>n<EFBFBD>bL<62><4C><EFBFBD><EFBFBD><0E>_<EFBFBD><5F>X&v=<3D><><EFBFBD>ͩ;<3B>Kp<>K<EFBFBD>t<EFBFBD><74><EFBFBD><EFBFBD><EFBFBD><13><><EFBFBD>S
A<EFBFBD><EFBFBD><EFBFBD>pL/d<>v<EFBFBD><1A>vF>Ҽ<> <20>O<EFBFBD><4F><EFBFBD><EFBFBD>{]<5D>/<2F> <0C>_<EFBFBD>u<EFBFBD>e<EFBFBD><65>T<EFBFBD>q~}<7D>$<24><><EFBFBD><EFBFBD><EFBFBD>>F<>F<>c<EFBFBD><63><EFBFBD><EFBFBD>sܻ19<03><>s<EFBFBD><73><EFBFBD>1<EFBFBD><31><EFBFBD><EFBFBD>E<EFBFBD>3<EFBFBD><02><>K<EFBFBD><4B>|Zdճ<64><D5B3>
<EFBFBD><EFBFBD><07>ѳ<EFBFBD>#<1B><>gb
e<EFBFBD><EFBFBD>0<EFBFBD><1E>?<3F><>2<EFBFBD>;j<>13=<3D><><EFBFBD><1C><><EFBFBD><EFBFBD><EFBFBD>?u<08><>mL<6D><4C>44<34><34><EFBFBD>!H<><48><EFBFBD>$\<5C>ܱh<DCB1>f<EFBFBD><66><EFBFBD>~<7E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>C<EFBFBD><02>1<EFBFBD>~'E+-Gn<47>A%<25><01><0F>R<EFBFBD>า\<5C>r4<72><34><EFBFBD><02><>YGMz)wb <0B><01>]<5D><17>\z<1A>S<>ĺ<EFBFBD>=>(! <0B><>x<EFBFBD>|<7C><>9<00><><EFBFBD><EFBFBD><EFBFBD>W<57><EEAE9B><EFBFBD>gMLdZI<5A><49><EFBFBD>\@0<>sV<73>Y<EFBFBD>ȷ<EFBFBD> <20><>4d,N8<4E>'O6OU<4F>yٖx/_<><5F><EFBFBD>Ʃ<EFBFBD><04><>S-Ɓ<>݈<EFBFBD>)H2xXB[<5B>G;ͱ:Z<>e<EFBFBD><65><EFBFBD>ݫF<DDAB>v<EFBFBD><76><EFBFBD><12><><EFBFBD>NU<4E>V<18><>l@ m<> ޴<><DEB4>FH'Ч<1C><>LyB<79><42>-[%<25><1A>X<EFBFBD>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>j<EFBFBD>~7]<5D><04><><EFBFBD>,<2C><18><><EFBFBD><EFBFBD><EFBFBD>8A<38>3<EFBFBD>#S<><53><EFBFBD><EFBFBD>r<EFBFBD><72>Y<EFBFBD>p~<7E><><EFBFBD><EFBFBD>G+<0E>DC<<3C><>_yY&U<>X<><58>8~<7E>5<EFBFBD>"L<><4C>W<EFBFBD><57>t<EFBFBD><74><EFBFBD><EFBFBD><EFBFBD> P<>KY<4B> <0A>k<EFBFBD>"<22> Z<><02>.Y<>?:><3E>˚`P6\n<>l<EFBFBD>ܛ<EFBFBD>h <20>8<EFBFBD>ߜo<DF9C><6F><05>J̿ <0C><>F<EFBFBD><46><EFBFBD>0<EFBFBD>-<2D><><EFBFBD>
<EFBFBD>?L<>2<EFBFBD>Tm<54>ٽ<EFBFBD><D9BD>A3<41>/<2F>~2<><32>(k<><6B><|<7C>l<EFBFBD><6C><EFBFBD><EFBFBD><08>+<2B><>L<EFBFBD>%<25><>˹*ԙ<>d<EFBFBD>L<EFBFBD>#H<>m<EFBFBD><6D><EFBFBD><EFBFBD><10>~<7E>F[<5B><><EFBFBD>I㿄<49>W<><07>V<EFBFBD><56>}H<>N&Gl<13>>G }<7D><>+<2B>o<EFBFBD><6F><EFBFBD><EFBFBD>޺<EFBFBD><DEBA>f(;<3B><13><>:<3A>j<><6A>r<EFBFBD>c<>k`<60><>p<><70> P>I<> \#1<><31>vyTSP<53><50>R<EFBFBD><52><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>?<1A><00>'f[n|<7C><>8<EFBFBD>ˢ<EFBFBD><CBA2>Wi<57>iDy<44><04><>l@<40>.)<29>B<><42>ׂ<EFBFBD><D782><10>k<EFBFBD>;
k<EFBFBD><EFBFBD><EFBFBD><EFBFBD>E7=<3D><>%J<><19><>[^<5E>D<EFBFBD><44><EFBFBD>e<EFBFBD><65>sm֣E<D6A3>3<EFBFBD>V<EFBFBD>l]<5D>ř<EFBFBD><C599><EFBFBD><EFBFBD>wG<77>><3E><>@St<53><74><EFBFBD>f<EFBFBD><66>V<1D><14><> g<><67>N3'i<><69><EFBFBD>;dE<64><45>sgUV<12><><EFBFBD>Z<EFBFBD>A<EFBFBD><-t<>;<3B>/<2F>h<EFBFBD>~<7E>2<EFBFBD><32>g<EFBFBD>r<EFBFBD>8U#K<><4B>}b2<62>7<EFBFBD>T<EFBFBD><54>L<EFBFBD><4C>O8<4F><38><EFBFBD>1<EFBFBD><EFBFBD>U<EFBFBD>7<EFBFBD><37><EFBFBD><EFBFBD>yE<79>;;<3B><>ZH+<2B>Α<EFBFBD><CE91>}<7D>Ua<55><61><<3C>Z><3E>Q<EFBFBD><51><EFBFBD><EFBFBD><EFBFBD>qr=<3D>V<EFBFBD> ة<17>f<EFBFBD> <0A>(<28><15><>v_⓷ ,D<>vN<76>Q<EFBFBD><51><EFBFBD>.7<EFBFBD><EFBFBD>pK @<40>f<EFBFBD>8<EFBFBD><38>_<EFBFBD><5F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>(<28><><EFBFBD>>ʭ*<2A><>=<3D>zk<7A><6B><EFBFBD><EFBFBD>U<EFBFBD>:<3A>v<EFBFBD>T<EFBFBD><54>Ԭ,r<>ރ<EFBFBD><DE83>m<EFBFBD>L<EFBFBD><4C>><3E>ɀ<>}#g<><67><EFBFBD>1V<31><56><05><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>2<><<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>(t{ #|<07><><EFBFBD>f<EFBFBD>)<29>ҴsP<73>Ə<EFBFBD>(r<06>l6P<36>շ<05>6<EFBFBD><10><><EFBFBD><EFBFBD><06><><EFBFBD>c<>Q<EFBFBD><51><EFBFBD>O<EFBFBD>P<EFBFBD><50>;b<>/g|ݭ<>:<3A>P<EFBFBD><50>b<EFBFBD>@<40><>P<EFBFBD><50><EFBFBD>$<24>ә<><D399><EFBFBD><EFBFBD><EFBFBD>5<EFBFBD>f<EFBFBD>po<<3C>2<EFBFBD><32><EFBFBD><EFBFBD>h<EFBFBD><68>ϕ" <09><><EFBFBD>AAPpN<70>(<28><><EFBFBD>Z <>*<2A>bt =<3D>l<EFBFBD>h:f<>(6+rK<03><><EFBFBD>!<21>_<EFBFBD>f<EFBFBD><66><EFBFBD>Hoՙ<6F>V<EFBFBD><56>!<03>E)<29><>E<EFBFBD><45>s<01>6ȿ<><12>4u[Pj(\m1`<60>r<EFBFBD><72><EFBFBD><EFBFBD><EFBFBD>o:<3A><><EFBFBD>U<EFBFBD>|C$umw<6D><77>]=J<><4A> -h<><68>x<EFBFBD>9l<39><6C>]e<1E>wD<77><0F><><EFBFBD><EFBFBD><EFBFBD>=<3D><><EFBFBD>v<19>1<EFBFBD><31>;<1A>ȫ<EFBFBD>hT<68>x'oF<6F>! <20><>'u@m| )<29><><EFBFBD><EFBFBD><06>&<26>T M<><4D><EFBFBD>vb<76><62><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>׋<EFBFBD>yq?Y2h<32><><13><><EFBFBD>~<7E><>Z<EFBFBD> <20><>L<05>#*=AN<41><4E>M<18>^ <20>-
@7(<28>kFv<46><76>q&<26>v<EFBFBD>i<06><><>G!Pe1<02><>sK<73> d!<21><>}<7D>Ed&?$<24><>vr<76><72><EFBFBD>;<3B><>I!ݟJ<DD9F>?<3F>$/<2F><><EFBFBD><EFBFBD>{<`$<24><>k<EFBFBD>g<EFBFBD>e<EFBFBD><65><EFBFBD><EFBFBD>?<3F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>6<EFBFBD>k<`G^<5E>r<EFBFBD><>h<EFBFBD><68>o<EFBFBD>0<EFBFBD>q<EFBFBD>i<>J<EFBFBD><4A><EFBFBD> <0A><><EFBFBD><06>F<EFBFBD><46><EFBFBD><EFBFBD><EFBFBD>x<><78>m.ҁkZ-<2D><><EFBFBD><12>?<3F>-<2D>-<2D>3<EFBFBD><33><><E697B8>B<EFBFBD>3<0E><>KL<4B><4C><EFBFBD><EFBFBD>ךK.m<><6D><EFBFBD>&YA<59><41><EFBFBD>P<EFBFBD><02><EFBFBD><EABB8D>PN3<4E>ѣ <10><>|;<3B>-<2D> <0C><><EFBFBD>R<EFBFBD><52>m<EFBFBD><6D><EFBFBD>5<EFBFBD><OH<4F>V<>1<EFBFBD><31><EFBFBD><EFBFBD>_<EFBFBD>Y<EFBFBD><59><EFBFBD>&V<>?J<><4A><EFBFBD>M<EFBFBD>x<><78>v<EFBFBD><76><EFBFBD>t<EFBFBD><74><EFBFBD><EFBFBD>YF<59><46>f3<66>̭A b}<7D><>1+l<>^Dz<44><7A>.<2E><14><1D>#<1F>J<EFBFBD>6<EFBFBD><EFBFBD>}><3E>[<5B>2<10><>. ]<5D><><EFBFBD>d<EFBFBD>J<EFBFBD>eR<65>PV2<0E><><EFBFBD>9<EFBFBD><39><EFBFBD>R{<7B>R<03><><EFBFBD>L{<7B><>d<19>j&<26>[<5B><><EFBFBD><EFBFBD>D<EFBFBD>>n<00>Ü<EFBFBD> z?<3F><>|<7C><>fLl<4C>mL-] #B<><01>P<EFBFBD>%<25>F<><46><EFBFBD>Ńb<C583><62><EFBFBD>nj<EFBFBD><C78C>LW <0B><>Ϟ<EFBFBD>p<EFBFBD>m<EFBFBD>im<69> ksN<73>M}K<>h<>><3E><11>E=^*>,q<13><>
<EFBFBD>UB<EFBFBD>T8<EFBFBD>})ϵ<><CFB5>①f<E291A0><66><EFBFBD>@SQ3ͫ<33>F<EFBFBD>%<25>#<23>1| X<>-2<>җD<14> <20><<3C><>IQ<49><51>#<23><R<><52><EFBFBD>Q<EFBFBD>#.<2E>S<EFBFBD>=!Nr f8Y<><59>Ν<EFBFBD>WG`b<><62>&<26><><EFBFBD>ÿ<EFBFBD>r<EFBFBD><72><EFBFBD><EFBFBD><EFBFBD>JA<4A><41>h<15><>8<EFBFBD>\h_<68>j<EFBFBD>]<5D><><EFBFBD>P<1B>9<EFBFBD>f<EFBFBD>M<EFBFBD>o<EFBFBD>z<0F>i<EFBFBD>
/<2F>X<EFBFBD>o<EFBFBD><6F>{<7B><>M}<7D>/<2F><><EFBFBD><EFBFBD>d,<1D><>3s<33><73><EFBFBD><EFBFBD>0<EFBFBD><30>&<26>Ua<55><61>(;<3B><><EFBFBD><EFBFBD><EFBFBD>|ځ!<21><1B><>7<EFBFBD><37><EFBFBD>8<EFBFBD>I<EFBFBD><49> Ӛ<><D39A>
!<21><14><0E>~<7E><><EFBFBD>t<EFBFBD><74>M<EFBFBD><4D>VΥ<56>}<7D>;i<11><EFBFBD><7F>V<EFBFBD> [<5B>S<>(a[YNÿվ3<D5BE><33><EFBFBD><79>T{9<><39>C<EFBFBD><43><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.<2E><><EFBFBD><04><><EFBFBD>^c<>E7<45><37>/<<3C>W<EFBFBD><57><EFBFBD>X<EFBFBD>*J(<28><><EFBFBD>v<11>QV"<22><>[ <20><>Q#<23>HV<48><EFBFBD> m<><6D>E <0B><><EFBFBD><EFBFBD>o<EFBFBD>xA,%<25>`U;<3B><>U<EFBFBD>D<EFBFBD>e<EFBFBD>[Qj<51><6A><EFBFBD><EFBFBD><EFBFBD><13><>~d<>nK<6E><4B><EFBFBD>.YCk<43><1B>&p{k><3E><>dtڍ=<3D><18><><EFBFBD><EFBFBD><EFBFBD>%<25>|lU<6C><55>󸢡<EFBFBD><F3B8A2A1>%8<><01>O0<4F><30><EFBFBD><12>xW <0A>$|<7C><><0E>n2<6E>L<EFBFBD><4C>B)v<><11><><EFBFBD>3w<33>>C<><43><EFBFBD>oo^<5E><16><><EFBFBD><EFBFBD>˗g<><67><EFBFBD>><13>)<29><><05>"UN<55><4E><EFBFBD><EFBFBD><EFBFBD><11><12>nqF<71>
us<EFBFBD><EFBFBD>{?<3F><>M<EFBFBD>[BuJǥ;<04><><EFBFBD><EFBFBD>-R<><52>p<EFBFBD>I<EFBFBD><49><EFBFBD>U\Zy2<79><32>ɏ <0E><>j<EFBFBD><6A>穭VkA<6B>=<3D>j<EFBFBD>IV<49>H<EFBFBD><15>5?<3F><><EFBFBD><13>8<EFBFBD><38>y=όK;<3B>m$b8۫<38>|<7C>a<EFBFBD><61><EFBFBD>l"<22><>G<EFBFBD> <0B>S<EFBFBD><53>|_A<5F><41>=Q<><51>s#<23><>F <0C>S<><02>P<EFBFBD><0E><>)i;v<>a<10><><EFBFBD><EFBFBD><1C>b<7F><62><EFBFBD>A\ <10>g<EFBFBD>L<>3<<3C> AK"<22><><EFBFBD>z<EFBFBD><7A><EFBFBD><19>U<EFBFBD><55>,<2C><>*<2A><>_\<5C>7<EFBFBD><37>c<EFBFBD>W<EFBFBD><07>!><3E>a<EFBFBD><61>a~Z<>@{<7B><><EFBFBD><EFBFBD>L,UI<19>(<28><>'E<>m<EFBFBD><6D>¶qL<71><4C><EFBFBD>J<EFBFBD><4A>( S<>>~<7E>otwMW<1D>D<EFBFBD><44><EFBFBD>#<23><>!~<7E>z0<7F><30> <09><><EFBFBD><EFBFBD>><3E>߯{<16>i<EFBFBD>Ǜ`4ߡ<34>O<EFBFBD><4F> <0A>.е<>3<19>Ȕ %<25><>ߡ<EFBFBD><DFA1><EFBFBD><EFBFBD><05><>3<EFBFBD><33> D<>H8%<25>Dۯ]Q6<12><><EFBFBD><EFBFBD><12>M<EFBFBD><4D>D<EFBFBD>.Hء<18>oP<6F>CU<7F>6<1F>5<EFBFBD><35>
<EFBFBD>Y<EFBFBD>SlSVX<56>F9<46>G{͞7<CD9E><37>x<EFBFBD>#<23><>eE#yV5<56>%ts<74><73><EFBFBD>{<7B><>,<2C>A_DR<44><52><EFBFBD><EFBFBD>O<EFBFBD><4F>x<EFBFBD><78><EFBFBD><1F><><EFBFBD><EFBFBD>1k<0F><><EFBFBD><12>Qzg{<7B><><EFBFBD>Y<EFBFBD>h*<2A>c<>V<><56>l<EFBFBD>z<EFBFBD>[Q6<51><1A><><EFBFBD><04><><EFBFBD>ԈXB<1A>/Z@$<24>C<EFBFBD><43>.<2E>U9<55>G#/Vg<56><67>Ԛ뗧<D49A>]<5D><><17><><EFBFBD><EFBFBD>iܰӣ<DCB0>\<5C>W<EFBFBD>_<EFBFBD>*5<><35>y<EFBFBD>K[՛<><D59B><EFBFBD>{;<3B><>b K<>•<EFBFBD><C295>ͪ(YA<16><>1<EFBFBD>.<2E><><EFBFBD><EFBFBD>ޯ<EFBFBD><DEAF><EFBFBD>{0l<>f<EFBFBD>X<EFBFBD><58>v<EFBFBD><76>ǐ<EFBFBD>h<EFBFBD>qm<71>uHE<><45>qHT*7<12>pXɈ'<27>9(<28><>J<EFBFBD> <19>Խ/<2F><>"<22>l!<21><>L<EFBFBD><4C><EFBFBD><EFBFBD>{<7B><07>T<1A>!<21>-<2D><><EFBFBD>'S<><53><EFBFBD>u<EFBFBD><75><16>{S=<3D><>^<5E>A<EFBFBD>-<2D>4<EFBFBD>=<3D><><EFBFBD>H<EFBFBD><48><EFBFBD><EFBFBD>"`y_E<5F>Z<06>/io<69>z<EFBFBD><7A>NaQvͦm <09><><EFBFBD><EFBFBD>w<EFBFBD>8x<38><78>m<EFBFBD>w1vnZ}<01><<3C>4<EFBFBD><34><EFBFBD>*?t<>(<28><>@<40><>Y<12>-<05> <0B><>1<EFBFBD>B<EFBFBD>_m<5F><6D><EFBFBD><EFBFBD>A<EFBFBD>^<5E>3<EFBFBD><33>,<2C>R<EFBFBD>qZ3<5A><33>.<2E><><EFBFBD><EFBFBD>S<14><><EFBFBD><EFBFBD><EFBFBD>by<62><79>TX`<11>?G<<3C>RC<52>Φu<CEA6><75>W<1C><>O<EFBFBD> <20><><EFBFBD>E3<45><33><EFBFBD><EFBFBD>w<1E>=@<01>}CT<43><54>a<>j<x<>%<1A><>9P<39>w<EFBFBD>Y3<59>j<EFBFBD><6A><EFBFBD>@C&5:',_w<5F>!$6<1F><><EFBFBD><EEA09E><EFBFBD>b<EFBFBD><62>ꗃ )<29> <20><>m/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>r<EFBFBD><18><>&<26><><08> V`<60>zs<7A>|"<22>P<EFBFBD> <0B><><EFBFBD><EFBFBD>Nj<><C78B>ǫ<17><>6ig<69>@rN<72>ql62<36><32><EFBFBD><EFBFBD>=<3D><><EFBFBD><EFBFBD><EFBFBD>=<3D>f볧b<EBB3A7>:<3A>>u"<22>2<EFBFBD><32><EFBFBD>Y<EFBFBD><59>^<5E>l<EFBFBD>% <0A><13><><EFBFBD>~<17>&<>e<EFBFBD><65><EFBFBD>ήc_<63><5F>.<2E>3n<33>k<EFBFBD><1A><>'<27>1<EFBFBD>i <05>bw<62><16><EFBFBD>^:<3A>f<EFBFBD>&h<>#mJi<4A><69>!+D<><04><><EFBFBD> <09>i^<5E><><EFBFBD><17><>n<EFBFBD><6E><EFBFBD>=+<2B><><EFBFBD><EFBFBD>5<EFBFBD>9x<39><78><EFBFBD>޲<EFBFBD>ʸ晉p<E69989><70><EFBFBD><EFBFBD><EFBFBD><EFBFBD>t<EFBFBD><74>׭<EFBFBD><D7AD><EFBFBD>K<EFBFBD><4B>l<EFBFBD><6C><EFBFBD><EFBFBD>DO <0A>; <0B><>)<29><>܅ <0B><>0<EFBFBD><30><EFBFBD>p<EFBFBD>(eefG<66><47><EFBFBD>Π<EFBFBD>0TR<54>:<3A><>z4<7A><34><EFBFBD>p<EFBFBD>.͠<>&<26>?Ui<55><69><EFBFBD>0<EFBFBD>2<EFBFBD><32>Y<EFBFBD><1E><><EFBFBD><08>"i`ؾ>4io<69><6F>d<EFBFBD>| W<><57>)<29><>޴<14><17><00>I,g<><19>ǎ.<2E>1٘ב<D998>HE<48><45>:<3A>~|<7C>,:g<03>'<7A>u"[<5B>JQ<4A><51>w<EFBFBD><04>,<2C><>Y <09>7<0E>ɽ<EFBFBD>ĸL<C4B8><4C><EFBFBD>"<22><><EFBFBD><EFBFBD>g1<67>Ȉ<EFBFBD>s<EFBFBD><73>I<EFBFBD>_<EFBFBD><5F>i<><69>
<EFBFBD><EFBFBD><EFBFBD><1B>x܏^<5E>H<EFBFBD><48><EFBFBD><EFBFBD>w<EFBFBD><05><><EFBFBD>"1<><31><EFBFBD>v<EFBFBD><76><EFBFBD>l<EFBFBD><6C><EFBFBD><1B>{<7B>v<EFBFBD>ɠk"2<>2#=-<2D><>
<08><><EFBFBD>P<EFBFBD><50>j<EFBFBD>,<2C>a<EFBFBD><02>^<5E><>]<5D><>=<3D>U<>ai<61>Q-<2D>+ <0A>ܢI<03><>l\<5C><>SYl<59>~<7E>*<2A><>S<EFBFBD><19>?<17>a<EFBFBD><61>ƈX:<3A><1B><>>rC<72><43><EFBFBD>CGEP<16>Jn<4A><6E><EFBFBD><EFBFBD><06>{Z p<><01><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>P{<7B>;Hf <03><>E<EFBFBD><45><EFBFBD><EFBFBD>]k<1F><>k<>bYi<59><06>RZ<52>d0<03>G•d<12>wI<77>=<3D><>/l<><6C>YK<59><4B>3<EFBFBD><33>N<EFBFBD>5H<06><>6<EFBFBD>M%T<1F><>Ou<4F><75><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Hs`^<5E><><EFBFBD>~<7E><>sʧ}<7D><>
<EFBFBD><EFBFBD>* <0A>MO<4D><4F>&yQ<><51><EFBFBD><EFBFBD>~+q<>I;<3B>a<EFBFBD>%<25><>!x\ S8<53><38>h<EFBFBD>h<EFBFBD>q6E9<45>O<EFBFBD><4F><EFBFBD>0<EFBFBD><30><EFBFBD><EFBFBD><1E><><EFBFBD>j<EFBFBD><03>I k^<5E> <0A><>|<7C>Ζ9 ;Q8?<3F><08><>* <0C><>͡GO<>)K<><4B>eiKk}<7D>扁g<E68981><67>z<EFBFBD><7A>̧<EFBFBD><CCA7>Ky<4B>\Օo5ۼ<35>H,|*D2&<26>1<0F><><EFBFBD><05><01><>+2<><32>$<24>[:<3A><00><><EFBFBD><EFBFBD><EFBFBD>bBGG<10>ƞFM<0A>-<2D>O<><4F><EFBFBD><EFBFBD>ِ
<EFBFBD>CU%<14>ᐢH<E190A2>o<EFBFBD>9fè5_o<5F>a<EFBFBD><1F><>z<EFBFBD>b<EFBFBD><62><EFBFBD><EFBFBD><1C>l<7F>H<EFBFBD>6<EFBFBD>t<0E>[,<2C><><EFBFBD>npN[<5B><EFBFBD><E597AD>H^<5E>s@B!.<2E><>S<EFBFBD>h/<11><><EFBFBD>gp)<29>;O<><4F>e<><65>q<EFBFBD>+<2B> u/<2F>xW<78>^5<><35><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <0C><><EFBFBD><EFBFBD>N;<3B><><EFBFBD>PdJ<64><4A>+<2B>F,<2C>lK<6C>{dX<64>J{<DT<44><54>:<3A><>^<5E><><EFBFBD>k<EFBFBD><6B><03>4ХI<D0A5>M<EFBFBD>³)i<13>+n<><6E>i[X<><58><EFBFBD><EFBFBD>D<EFBFBD><44><0F><>|<7C><>9 <20><><EFBFBD>!F@3<>#<23>B<EFBFBD>e 6%+)<29><>5<EFBFBD>"W<>c<EFBFBD>l<02><>O <0B>W1<57><31><06><><0E>(<28><><EFBFBD>6$꼥<><EABCA5>Ϙä<CF98><C3A4><00>h<EFBFBD>:# X<>J8 Z <0B><11>d<><64><EFBFBD><EFBFBD> <09>]6<><<3C>Z|<7C><01><><EFBFBD>9<EFBFBD>z<EFBFBD><7A>z F.F<>~<7E><><EFBFBD>rq<72><71> <04><<3C><>oEU<1C><><EFBFBD>r<><72><EFBFBD><00>V"x<><78>H<EFBFBD><48>z<[<5B>[<00>j<EFBFBD>ʍ<16><1C>>b<>+3<>L<EFBFBD>?L<><4C><EFBFBD><EFBFBD>@Gx<47>بH<D8A8><48>$l؎N2<4E><32>w?<3F>Jo<4A><6F><EFBFBD><EFBFBD><03>ʁg<CA81><67><EFBFBD>(<28>a<EFBFBD>Y&<26>8<EFBFBD><18><>1U; <09>kj<6B>"H<><48>.<2E>1<EFBFBD>"O <20><>#<23><>gbPBY<42>
<EFBFBD>%$Z<><5A>_+<01><><EFBFBD>3B|<7C><>f<EFBFBD><66><EFBFBD><EFBFBD>eY<05><>7<EFBFBD>U<EFBFBD>D5<44>bQ
<EFBFBD><EFBFBD>-q<><71>'<27><03>H<EFBFBD><48>2<17><1F><><EFBFBD><04>t<EFBFBD>MF<4D><46><EFBFBD>_>v<>{<7B><><10><><EFBFBD>ݎG<>@<40>]&~SM<53>][F4<>`<60><><EFBFBD>\<5C><>=<3D>`<60><><EFBFBD>uY<14><><<3C><>nKXPq7<71>Ⱥ<>V<EFBFBD><56>j<EFBFBD>@<40>e<EFBFBD>\8<>2<EFBFBD>W8<05> <0A>&<26>*<2A>j<EFBFBD>n#Ȕkv[jw<6A><77>W<EFBFBD>L<18><><EFBFBD><EFBFBD>YV<59>gХ<67>m<EFBFBD><6D><<3C>HG<48>{><3E><>Nc[ɗ/GSJ<53><4A>Jy<4A><79><EFBFBD>F* <0A><>$}Y<><59><EFBFBD>Z;Q(6t<36>z|<7C>5*<2A>Uխԗ +<16><>҅x<D285><78><EFBFBD><EFBFBD>-<2D><19><>HD<><44>C>%C<00>`Lb<4C>pЏk,<1D>EI<45><18>%<25><><EFBFBD>vS=<<3C>&#<23>\ zM<7A><4D><0F><12>_<EFBFBD>"<22>F<EFBFBD>̻<>VD<56>dueu<65>.wE<77>{q1<7F>H<EFBFBD>$`<60><1E>]%}<7D><><19><><0E><><EFBFBD>ga<67><61><EFBFBD>U<EFBFBD>0v<30><76>{,İJ<C4B0><4A><EFBFBD><EFBFBD>XF a<1A>j<EFBFBD>0I
<EFBFBD>e<EFBFBD><EFBFBD>ۡ32<EFBFBD>y<EFBFBD><EFBFBD>s8<EFBFBD>C_<EFBFBD>m<><6D>_U<5F><55><EFBFBD><EFBFBD>T`<60>F<EFBFBD><46><EFBFBD><EFBFBD>lx<6C><78>-o4<6F> }<7D>[<5B>J K<>.ҧ$<24>1-<2D><>ĠT)<29><><EFBFBD><EFBFBD><14>"<22>+<2B>?<3F>8:Ls<4C>P<EFBFBD><50><19>X<EFBFBD>D:|<7C>[<5B><><EFBFBD><19>QL<0E><><EFBFBD>S<EFBFBD>J<>$<24>95<><ECB59D>ڈX<DA88>~C<>R<EFBFBD>A`<60><>$\<19>;<3B><>Mv<4D>Z<><5A>?<3F>@<40>U<17>ex<65>~W<>^<5E>:<3A>oe<6F><65><EFBFBD><EFBFBD>z<EFBFBD><7A><EFBFBD><EFBFBD><EFBFBD>."<22>pA:<3A><>p<EFBFBD><70><EFBFBD>l<1D>(<28><><EFBFBD>4^<5E>,
<EFBFBD>5<07><>i<EFBFBD>O<EFBFBD>X<EFBFBD><58><EFBFBD>ě<17>Q<EFBFBD><51><07>,P<><50><EFBFBD><EFBFBD>V<EFBFBD>
e<EFBFBD><EFBFBD><EFBFBD><08><>v<EFBFBD> I<><49><EFBFBD>˯<16>%]<5D>uh<75>_<7F>*<2A>
$<24>l <0E><>c<><63><EFBFBD>[j<00>lL<><4C><EFBFBD><14>H(b<>J<EFBFBD>L<EFBFBD>~<7E>^<5E><>򍚀<EFBFBD>;H<>P!<21>[?<3F>:r6Ҩu<D2A8>lY.<2E>)<29>Pd
e<EFBFBD>F"<22>ɩ1<C9A9>|yݨƲĀS<C480><53><06><> <09><13><>8d<11>yS!<21>vt<1E><><EFBFBD>bm<1B><><EFBFBD>몣َ<EBAAA3>?<3F><01>*<2A><><EFBFBD>7RZ:<3A>GE<47><45><EFBFBD><EFBFBD><EFBFBD>`:<08> <01>A3<41><33>c<EFBFBD>hQ <19><><EFBFBD>)` o+l<><6C>@z<><7A>n<EFBFBD>*<2A>i<EFBFBD><69>7eq<65><71>j<EFBFBD>)<29><>]<5D>3V<33>[&<26>v<EFBFBD>M<EFBFBD><4D><19>\Q<fР<66><D0A0><EFBFBD><EFBFBD>= l^_]<5D><>%<25>6Zi.*WA<04>Ú<EFBFBD><04><00><><EFBFBD>(<28><>ɀO<05>j_]Ժ<><D4BA>]fU <0A>&<26><>"<22><>8*<2A><><EFBFBD>p<>c<EFBFBD>=<3D>ݍ<EFBFBD><DD8D><EFBFBD><EFBFBD>0<EFBFBD><12><>+֯E<D6AF> <20><>f`<60>hp|<7C>. <09>b<EFBFBD>BG<42>|<7C><>!R<>E<EFBFBD>`<60><0F><>c<EFBFBD><63>Ì<EFBFBD><C38C><EFBFBD><EFBFBD>l<EFBFBD><6C>~<7E>%<0E>q<EFBFBD><71>%<25>'<27>x<EFBFBD>"<22>h<EFBFBD>|<7C>*<2A>ha<68><61>V<EFBFBD><56><EFBFBD><EFBFBD>VC<>fz=<3D><>_<>l<EFBFBD>kj?<3F><><06><><EFBFBD><17>\/<14>E<EFBFBD><45>8QɕX<C995> <0B><>@Wgm<67><6D><EFBFBD> <20><><EFBFBD><EFBFBD>ջ<18>|<7C><>~<7E>}<7D>w댿<77>!<21><>iQ<69>c_1V<31><56><EFBFBD><EFBFBD>q<EFBFBD><71>D<06><>?~<7E><>#<23>jSP<53><50>R4
<EFBFBD><EFBFBD>4<EFBFBD><EFBFBD><EFBFBD>7Gj<EFBFBD><EFBFBD>x<EFBFBD><EFBFBD><EFBFBD>-<2D><>k<EFBFBD><6B><EFBFBD><EFBFBD>E<><45>hbE<11>Xp^<5E>C,<2C>Q{.<2E><><EFBFBD><EFBFBD>sF<73>QR<51><52>N<EFBFBD>m2ᳰ<32>S1<53><31>
s#m?<3F>+{ <0C>ux<75><78>q<y<>w<EFBFBD>*<2A><>d<EFBFBD><1C><><EFBFBD>f
<EFBFBD><EFBFBD><EFBFBD>S<0E>g<EFBFBD>ne<6E><65><EFBFBD><EFBFBD>,<2C>o<EFBFBD>5<EFBFBD>C<EFBFBD>{3<>jU<6A><55><00><1A><18>3<EFBFBD><33>:<3A>9㫖<1E>e<EFBFBD>i7<69>s<EFBFBD><|<7C>כ<>۷<>t<EFBFBD><74>05h!<21>71<37>Վ^7<><37><EFBFBD><EFBFBD><EFBFBD>T8t<38><74>A4R<<3C>)(: s<>؋<EFBFBD>C<EFBFBD><43>/,:w(}n^ַN<D6B7><4E><EFBFBD><EFBFBD>^x<>n<EFBFBD>C <0C>}/fa<66>b6<><36>N<EFBFBD>:<3A>]<5D>)<29><>=<3D><>?<3F>%<25><><EFBFBD>0<EFBFBD>@<40><><EFBFBD><EFBFBD> <0B><>w<EFBFBD>H<EFBFBD>,$d<><64>Z <20>hNΆ<4E><CE86><EFBFBD><02><> }<7D>u<EFBFBD>b l<>"<22>L<EFBFBD><4C><EFBFBD><EFBFBD>YL<59><W<>E<EFBFBD>Ȏ<EFBFBD>Q@<40>`<60><>5<EFBFBD><19><1D><><EFBFBD>2w<32><77>D<EFBFBD>@b<><62><EFBFBD><EFBFBD>+<07><>lD<6C>sD<73><44>q}QY<51>)<29><><EFBFBD>C\<5C><>•<EFBFBD><C295>p<EFBFBD><70><EFBFBD><EFBFBD>O<1E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;<3B><>BKZq<>+<2B>#Y1<59>P<EFBFBD>iF1<46><1B><>5<EFBFBD>:<1B>J<><4A><EFBFBD><16>@<40>Dr<44>qN<71><4E>h<EFBFBD>\F<19>%_<>-<16> <1D><><EFBFBD><EFBFBD>gh<13><>A<EFBFBD><41><EFBFBD><)<29><>S<EFBFBD><53>/닪<>,<2C><>Ӫό<>_eNb+<13>v9 '-h<><68><EFBFBD><06>F_U08Lw<4C><77>0ɜ~<7E>f88<38><38>_<EFBFBD>Cgƨ<67>2x<32><78><EFBFBD><EFBFBD><EFBFBD><19><><D8B3><EFBFBD><08>w-<2D>f, Ll<4C>a <20><>E<EFBFBD><45>~<bl-<2D>fV…<56><C285><EFBFBD>p <20>a
gct<EFBFBD><EFBFBD>`26Hl8<6C> <0B>L<17><>6<EFBFBD><13>L<><05>=<3D>6&G<>l<EFBFBD><6C>9|:<3A><><11><><EFBFBD><EFBFBD><04>LF<4C> !<03><>{<7B>468؁sy<73><1E><>ImLlo<6C><6F>Z<EFBFBD>~<7E><>e<EFBFBD><65><1F><><EFBFBD>+<2B><>[<5B><>̈<EFBFBD><CC88><EFBFBD><EFBFBD><EFBFBD>_<EFBFBD><5F><1B>S$l<><6C>E<EFBFBD><04>B<><42>.@<40><><EFBFBD><1B><19>!_<><5F>R0$<24><>k<EFBFBD>u<EFBFBD>('<27>
<EFBFBD>Q<EFBFBD><EFBFBD><06><>\ <0B> f<><66><EFBFBD>&v<><76><EFBFBD>4<EFBFBD>[4<>G;!<21><05>;@ڛ$6@<40>).<2E><>mՔ9X<1C><1A><>l<EFBFBD><6C>TiB2 <20><6B>U<EFBFBD><55>-9<><12>$<24><>qMޢ<4D><DEA2>T<>G<>1R<31><52>)^p<>*<2A>t<>/f<>Z<EFBFBD><5A>ݠ<EFBFBD><DDA0>zFq`9n1<6E><31><EFBFBD>.<2E>#!<13><>T<EFBFBD> ma<6D><61><00>c<EFBFBD><63> n<><6E><EFBFBD>@<40>RϪ}<7D><><EFBFBD><EFBFBD>R<EFBFBD><10><>)H<>y2<79><32><05>j<>C{<7B><>E<EFBFBD>Cl<43><6C>h٭<68><08>2<><32><07>B<EFBFBD><42><EFBFBD> <0C><><EFBFBD><EFBFBD>RI<52><14>X<EFBFBD><58>3<>e <0B>J<1B><>&<26>N6YɟեYmK<6D>v<EFBFBD><76>.3<EFBFBD><0E><06><06>ёC\B<>ч<EFBFBD><12>T<EFBFBD><54><0F><>q/l<>ڲ<EFBFBD>O<EFBFBD><4F>q<0F>W<>?(<28><>*<2A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>f<EFBFBD><66>|<7C>v%Ƌ9<C68B>f`<60>M<<3C><>v<EFBFBD><76><EFBFBD>'<27><>u<EFBFBD><75>x<>k+<2B><><EFBFBD>Q<> 5<><1C>/ δL<17><>T<EFBFBD><1F> e<1F><14><>5<EFBFBD>t<>s<> :Wk<57><6B><EFBFBD>?뒩l<EB92A9>Ez<45><7A><EFBFBD>e<1E><><05><13>i<EFBFBD><08><>7<EFBFBD>`<60><10>O<EFBFBD><4F>2<EFBFBD><32>.<2E>Y<EFBFBD><59>++Z<1F><>8<EFBFBD>c/<2F><><EFBFBD><EFBFBD><EFBFBD>N<EFBFBD><4E>.I?<3F><69><CF94>,-{<7B>E<EFBFBD>a6p<><70><EFBFBD>Ev<><76>~X~M<><4D>)<29>$:#)<29><1E><>^<5E><>(<28>Y<EFBFBD>(l<><6C><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>$<24><>],<2C>THdC 1<>đ<EFBFBD>d<EFBFBD> <09>h<EFBFBD><68>G <0B>_=N<>Zk$<24><13><><EFBFBD><EFBFBD>oĤ_<1A><10>z<EFBFBD>$)<1B><>lj <20>;M<>=<3D><><EFBFBD><EFBFBD><EFBFBD>Zc,<2C>m<EFBFBD>8KT<4B>kzo<7A>!<21>'<27><><EFBFBD><EFBFBD>!֪f<D6AA><66><EFBFBD>r<EFBFBD><72><EFBFBD>Du2<75>@<40>]<05><04><><EFBFBD><7F><EFBFBD>t<EFBFBD>u<EFBFBD><75><EFBFBD><EFBFBD>K)<29>a<EFBFBD>+z <09><><EFBFBD>4htD<74>,<2C><><EFBFBD><EFBFBD>:&ϼ<>քG<D684>@><3E><>F<EFBFBD>SS'<1F><> ݰP^<5E>Z<EFBFBD>5_<35>#RG<52><47>#9<>_<EFBFBD>d<EFBFBD> b'uЋlP<6C>'D<><>l <0B><>*|\~b<15>]<5D><>8<EFBFBD><38>Y<EFBFBD>I<EFBFBD>Y?Vr<56><72><EFBFBD>gqt6m<>,<2C><><1C><>cI<63>_<EFBFBD>:<3A><>L<EFBFBD>v<EFBFBD><76>A<EFBFBD><11>̲<EFBFBD>e<EFBFBD>i<EFBFBD><69><EFBFBD>e<EFBFBD><65>E<EFBFBD><07><><EFBFBD><EFBFBD><EFBFBD>+5<><35><EFBFBD><EFBFBD>W<EFBFBD><57><EFBFBD><EFBFBD><EFBFBD><EFBFBD>M[cQ_X<5F>NCYfc<15>^<5E><><EFBFBD>oޫ"x`<60>s=nI<6E><49>?<3F><><EFBFBD>i<17>S<EFBFBD>$0<><30><EFBFBD><EFBFBD><EFBFBD>S`<60>U<EFBFBD><0E>^<5E><>i<>5<EFBFBD><35>A8<41><38>Lj<EFBFBD>m9<6D><39><EFBFBD><EFBFBD><EFBFBD><EFBFBD>#<23>B_h|M4͉<34><17>-m<>x3:P9<50>y2c<32><63>=i<>07e <20>rP%8<><38>֝<EFBFBD>4Q7<51><<3C><>{<7B><>So<53>S<>]y5bؓIp[<5B><06><>7<EFBFBD> )hk5މ)Xh<58>i<EFBFBD>ݬ<EFBFBD>%<25><><EFBFBD>nC!<21>G<EFBFBD><47>w<EFBFBD><77><07>+<>a<EFBFBD><61> <0A><>S<06>9<EFBFBD><39>DY<44><71><D883>T`P<><50><EFBFBD> *<1C><><EFBFBD>p-<2D>U<01>ݰ<EFBFBD><DDB0>:<3A><>!t<><74><EFBFBD>h<><68>'<1E>q<EFBFBD>3<EFBFBD>Ў<EFBFBD>kup p<>N9<4E>)<29><><19><><<3C>^*%b<><62>M<EFBFBD>n<EFBFBD>%P<><50>+<2B>w`T<><54>g<>:K<>C<EFBFBD>T<1A>0<EFBFBD><30><EFBFBD>-1B<31><42>6!/<2F>4w<34><77>f<EFBFBD><66>+<1A><>Sp<53><70>'<19>b2<><06>b<EFBFBD>L<><4C>1<><31>ƕ<EFBFBD><C695>{<7B>j<EFBFBD>]<5D><03>R<>z<EFBFBD>Q<EFBFBD><51>/<2F><><EFBFBD><EFBFBD>.<2E><><EFBFBD>P<EFBFBD>Dc<>y<EFBFBD> <0B><EFBFBD>W<EFBFBD><57><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʒ><3E>n͍&<26>#,/w<><77>[<<3C>#<23><>/ <09>P]<5D>.<2E>s<EFBFBD><73><EFBFBD>;u<17>O<>"<22><>";<3B><><EFBFBD>_<EFBFBD><5F>
E<EFBFBD><><C59E><EFBFBD>6}<7D>9<0E><><01><><EFBFBD>o<7F><6F>V<1C><>m<EFBFBD>RL%<25><1F>e<><65><EFBFBD><EFBFBD>H <09>"U҉)<29><>Y.i{<7B><>0Щ_<00>J<EFBFBD><4A><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԓ<EFBFBD><D492>1@<40><><EFBFBD>_<EFBFBD><5F>1<>i<EFBFBD><69>B<EFBFBD><42><EFBFBD><EFBFBD><EFBFBD>ݛ<EFBFBD><DD9B>[<5B><>n<1D><><EFBFBD><EFBFBD><EFBFBD> (<28>{<7B>ʲGUI+]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>v<> (<28><><EFBFBD>Ox<07><>Z<EFBFBD>P?<3F>G<00><>K0\<5C><><EFBFBD>F|<7C>a<EFBFBD><61><EFBFBD><EFBFBD>Z<><5A>'w<><77><EFBFBD><EFBFBD>Vb<56> z<><7A><1D><16><1C>P7,R<><52><EFBFBD><EFBFBD>7<EFBFBD><07><><EFBFBD>or@<40> <1A>y{<7B><15><>:|<7C>o<EFBFBD> <0A>HW<48>(P<>y<EFBFBD><15>G<><47><EFBFBD>a<EFBFBD>3V<>\`<08>
<11><><EFBFBD>m<EFBFBD>=<06><><<3C><>z <16>&h<><68>V<EFBFBD><56>9<EFBFBD><39><EFBFBD>ױ>V <0C><EFBFBD>$<24><><EFBFBD>* <0A><>am<61><6D><EFBFBD><EFBFBD>UD4L<34><4C>n<EFBFBD><6E>v<14><><EFBFBD><EFBFBD>><3E>@<40><> <1D><><EFBFBD>߫w,opw<70><77><EFBFBD><EFBFBD>oHÿ<48><C3BF><EFBFBD><07><06><><EFBFBD><EFBFBD>#<23>w<EFBFBD><77><EFBFBD><1B>+<2B>;`5]<17>MF]<5D><>P$̜<05><> <0A><> <0C><>q<71><7F><EFBFBD><EFBFBD>j<06>`<60><><EFBFBD>$?,<2C>(,<2C>WMn<<3C>7اÒ&<10><><07>q<EFBFBD>+:N <0B>_<EFBFBD><5F>9"2b<32><01><><EFBFBD>v_^7 B`T <07>0S<>;<08><>w<EFBFBD><EFBFBD><7F><EFBFBD>»<7F>z7g"ʖU'<27><>/<<3C>dc<64><00>*<2A><> <0C><01><>]U<>pD<02><05><>cu<63>k<EFBFBD><6B>a <0C>yQ-a<>{01<04>y<EFBFBD>Wd<57>m<EFBFBD>}!<1E>#<23>zB֮}5<08>t<74>X<EFBFBD><58><EFBFBD>Yx<><78>[<16><><EFBFBD><EFBFBD>L6<4C><36>} <09><05>ׄ>b陣<62><E999A3>K<EFBFBD><4B><EFBFBD>W@x)Di&<26><>A <0F>ǿ<EFBFBD>H<EFBFBD>@<40><>pzU?<3F>f<>z<EFBFBD>ng~<7E><><03><>k<>W8<57><38>? <09>+<2B><><EFBFBD>8j<1D><>
^<5E>><3E> <20><><EFBFBD><EFBFBD><EFBFBD>f<EFBFBD><66><EFBFBD>f<EFBFBD><66><15><10><>j<EFBFBD><6A>N<>K)<29><><EFBFBD><EFBFBD>ـ<EFBFBD>'<27><1E><><EFBFBD><EFBFBD>, j<>ي[݁<><DD81><EFBFBD>S\<5C><>K<EFBFBD><4B><EFBFBD><?W<>w+h<><00>`<60><><07>E0U}<7D><>ʌ<>5<EFBFBD><35>8@}<1F><>]<5D><><EFBFBD>j<EFBFBD>6瑒/<2F> <20><>܇<EFBFBD>'<27>k<EFBFBD><6B>Z<><5A><EFBFBD><19>8<EFBFBD><38><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1E><><EFBFBD><EFBFBD><EFBFBD>Ym0<6D>eΨ{0 <0A>ώ<EFBFBD>ǜ<EFBFBD><C79C>Ej\<5C>#<23>J~Q'<27>I;7<><37><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>*<2A>$+<2B>u<EFBFBD>J~<7E>1x}<7D><>(<28>t@p s,<2C>Dsa,B<><42>X<EFBFBD> <0A><><06><>><3E>F<EFBFBD>VN<56>r6XK<58><03><> q:)<29>9<EFBFBD><39>(<28>y<EFBFBD>չ<EFBFBD>Ep_<70><5F>Ū.<10><>^5Ň^<5E><>d}D<><44>bP<05><10>%(/S-3p<33><70><EFBFBD><11>s<EFBFBD><73>YT<59>w<EFBFBD><77>]p<>:<3A><> <09><07><><EFBFBD><EFBFBD> <0A><>k4<6B><34><EFBFBD>|Z<>q<EFBFBD>0<EFBFBD><30>Ԕ<EFBFBD>׳|<7C><><EFBFBD><EFBFBD>\D;<3B>[<5B><>wCD 𬹿<><F0ACB9BF>&Iz?'<27><>g<EFBFBD>=0<><30>_<EFBFBD>P<EFBFBD><50>Ha/ <0E><>`<60>Sv<53>=<3D><><19>&h<><68>p`bKל;<3B>Oi{<02><>=.q<><71><EFBFBD><EFBFBD>4-<2D><>N<EFBFBD>mw[<5B>τRnJf<4A><66><00><>AP<41>b)<29>l1<6C><18><>B/<2F>7 <0C><>Mn<4D>0<EFBFBD><30><EFBFBD> <0A><>&X<><58><EFBFBD><EFBFBD>S8<53>8<EFBFBD>"<22>?5;<3B><><EFBFBD>c<EFBFBD>: <0C><>1<EFBFBD>o;5<><35>6<EFBFBD>f<EFBFBD><66><EFBFBD>l"<22>&<26>x<EFBFBD><78>wN<77>@f<><66>z<EFBFBD><7A> ۬[<5B>V!4|K<>f@Xµ<58><C2B5>S<>M<EFBFBD><4D><EFBFBD><EFBFBD><10>Ps<50><73>-H<><48><04><>M<00><>䓗¦f<C2A6><66>1<EFBFBD>9 <0A>5<EFBFBD>#(Y<><1C><>S<EFBFBD>aÊY<C38A>\<07><>o
<EFBFBD>[|<7C><><EFBFBD>r<EFBFBD><72><EFBFBD>߅<EFBFBD>/<2F> _P<5F>Jy<>t<EFBFBD><74>a<EFBFBD><61><EFBFBD>j<EFBFBD> ̾<><CCBE>fv`<60>bg< '<27><><1E><><EFBFBD><EFBFBD><EFBFBD>ǎ<> i<>=<1C><06> <72>FQ=<3D><><EFBFBD><15><>`lh<6C>mi~<7E><><11>H&<1A>y<01><><EFBFBD> <0C>~W<><57> <20><><13>v<EFBFBD>><3E><04>0Q(=<3D>=
<15>`<60>0<><30><EFBFBD>9<0E><>C~C|<1C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>#X<>"<18>qi<06>a<EFBFBD>{<7B><>P_s<5F><05>x<EFBFBD><78>:Nu<>8Z<38>(f<>#<23>U<EFBFBD>#"<22>K<EFBFBD>藢j<E897A2><6A>Y
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>X<>1<EFBFBD><31>Yc=<3D><><EFBFBD>T<18>n<EFBFBD>evM<76><4D>T<EFBFBD>m<EFBFBD><6D><EFBFBD><08><><EFBFBD>^<5E>*<2A><><EFBFBD>%d<>T<EFBFBD><54><EFBFBD>
cYWfy<EFBFBD><EFBFBD><EFBFBD><17><06><>0Z<30>k<EFBFBD><6B><EFBFBD><EFBFBD>ڃa<DA83>j<EFBFBD><6A> į<><C4AF><EFBFBD>9<EFBFBD>z<EFBFBD>1<EFBFBD>Sr<53>^<5E><><77><DD83>+<2B> )<29>sf<05><>Ġu<C4A0><75>?<3F>U
<EFBFBD><EFBFBD>ܶG<>ZF<5A>M<EFBFBD><4D><EFBFBD>$<24><><EFBFBD><EFBFBD>*71^<5E><><EFBFBD><EFBFBD><EFBFBD>É<EFBFBD>Hְ{<7B><><EFBFBD>Ϻ<EFBFBD><CFBA>2<EFBFBD>7<EFBFBD><37>H<EFBFBD><1C>[<5B><>o<EFBFBD><6F><EFBFBD>w<EFBFBD><77><19>^q<17>};O.<2E>]X]<1B><0E><>>`<60>v<EFBFBD>VY<56><59> k<>:v<><76><1A><>I<EFBFBD><49><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>x<78>a<EFBFBD><61>i<EFBFBD><07><<3C><05>cJ<63>^r獴^<5E>
EJ<45><4A>g<EFBFBD><67>P<EFBFBD><50><05>~<7E>'<27>?<3F><14>T8Z<38>vy<76><79><EFBFBD>*<2A>d(%<25><><EFBFBD><08><>em
XfS(1Hld<6C>ݤY<DDA4><59>q2p[<13><<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>A<>ڗ<EFBFBD><DA97>X<EFBFBD>JT(\F9ԃe<D483><65><EFBFBD><08><>7)<29>jJ<>@<40>}%<25><>{<7B>]<5D><>O<><4F><EFBFBD><EFBFBD><EFBFBD><EFBFBD>4<EFBFBD><34>$><3E><><EFBFBD><EFBFBD>$<24><13><05>dH<64>5<EFBFBD>g<07>
<EFBFBD>9` <20><> M<><4D> <20>t<EFBFBD><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD>:vI<76>ol<6F>H<>^<5E><>C<EFBFBD>a_<61>'u<><75>'<27>6<<3C>m ܤV#<23>r<EFBFBD>Y<EFBFBD>J<EFBFBD><4A>|<7C>ԓ<>Է5<D4B7><35>̇O<CC87>}<7D>6<EFBFBD>E<04>%<04>YR<> <20><>ư<EFBFBD><05><1D>(<28> <0B><><EFBFBD>[<5B><1B><19><><EFBFBD><EFBFBD>hRlP<6C><18>~<7E>(<28>ڤ<EFBFBD><DAA4> <0C><>ϰ<EFBFBD><1F>i<EFBFBD><69>b[<05><00><>$<24><>0<EFBFBD>s<EFBFBD><73><EFBFBD><12><><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD>1I<01><><EFBFBD><EFBFBD>-<2D><><EFBFBD>T<EFBFBD>,x<>BU,W)Ͼ<><CFBE><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>u<16><>C<EFBFBD><43>L<EFBFBD>î<EFBFBD>!<21>]<5D><>q<EFBFBD>7<EFBFBD><37><1F>'4<>bɡ<62>$֑Q<D691>%<25><><EFBFBD><1D><><EFBFBD><EFBFBD><07><><EFBFBD><EFBFBD>;<3B>%<25>!<21>s<1F><>/<2F><>i"<22><>I<EFBFBD>%w<>%<25>!<21><>#cl<0F>!<21>z<><7A><14>D<EFBFBD><44><03>2\<5C>; I<>ӽ<EFBFBD>[<5B>ڵ<7F><04>'<27>7<EFBFBD>o<EFBFBD>DlQ斥<51>'$o<>ޙ<><DE99><EFBFBD><EFBFBD><E7948E>x<11><>8bAդ<41>蝉+ )<29>`'<27><><EFBFBD>E<EFBFBD>0<>RT"<22>iI;w<>j<EFBFBD>dDd`<60>$<24><><EFBFBD>cMS<4D>Y<1B>s<><73>7c<37><63><EFBFBD><08><>J_<4A><5F>+<2B><>Ӿ<EFBFBD>E<EFBFBD>z<EFBFBD>~<7E><>>y<><79>K<EFBFBD><4B><EFBFBD>w<EFBFBD><17><><EFBFBD>O<EFBFBD>Y<1D><03><06>?<3F>4ǪW<C7AA> <0A><><EFBFBD><EFBFBD>[K,ʿR<CABF><01> ,o<><02><>C<><43><EFBFBD><EFBFBD><EFBFBD>L26'<27><><EFBFBD><19> <0B>|oGp<47>w<EFBFBD><0F><>ˑ"X<>M<11><><EFBFBD><EFBFBD><07>񽩂U1<55>26<32><36><EFBFBD><EFBFBD>X<EFBFBD><58>@Y.<2E><><EFBFBD>KK<4B>D<EFBFBD>`:b<01>\yp<> )<29><><EFBFBD><EFBFBD>#_n<5F><04>X<EFBFBD><58>.<2E><>Aqo<71><6F><EFBFBD><EFBFBD><EFBFBD>K<EFBFBD><4B>IhEK,<2C><><EFBFBD><EFBFBD>(h+<14><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>aF<61><46>\<14>ow_{&<1B><>1<>E<EFBFBD>J\<5C><>8^B <20>P_/`&<26><00><><EFBFBD><EFBFBD><EFBFBD>K<EFBFBD>#a<>jS<6A> <0B>*B-<2D><>c"<22>e<EFBFBD><65><EFBFBD>J<EFBFBD>b
<EFBFBD><EFBFBD>"<22>ys lɉ2<C989>cѿk:<3A><><03><>81<1D>E <0B><>P<EFBFBD><50><EFBFBD><EFBFBD>.<2E><>?<3F>yVp<56>n<EFBFBD>}<7D><>R<EFBFBD>t<EFBFBD><74>)UA<16>\<5C><><EFBFBD>*1U<31>O<EFBFBD><4F>@<1F>LD7<44>L<1B>'<27><16>؋<><04><>5<EFBFBD><35><EFBFBD>Ѿ<EFBFBD>r/ĝ;<3B>4/_<><5F><EFBFBD>$ytjm*<2A><<3C>VN<56>)l<><6C>\<5C><><EFBFBD><EFBFBD>?6<><36><EFBFBD><EFBFBD>&<26>Kh<00><><EFBFBD><EFBFBD><EFBFBD>;<3B><><EFBFBD>C<05><>o<>h<EFBFBD>D(=<3D>p<EFBFBD><70><EFBFBD><EFBFBD>FG<46><03><>Έ<CE88>|7<><11>" <0C><>M&<26>q{<05><>+-I<17><> <0C><>u$k#$Ԋ\pF؛`<60>R0"<22><><EFBFBD>EZ<45><5A>w<EFBFBD><77>)"<22><><EFBFBD><EFBFBD>M<EFBFBD><4D>m@K<> <0A><><EFBFBD> <0C>XTL<54>XVN<56>x<EFBFBD>Y<EFBFBD><59><EFBFBD>.<2E>/<2F><>@<40>fX5Q,T<>J<EFBFBD><4A>*p<0F>w<12>][<5B>ZT<5A>W"<22>U<EFBFBD><55>'vxqҥ<71> d<><64><EFBFBD><>ݷ<EFBFBD><DDB7>O:<3A><><EFBFBD><1C><><EFBFBD>nX)<29><13>j <0B>=p<>u<14><>~<7E>;!}<7D><><EFBFBD><EFBFBD>X<EFBFBD><58>/<2F><><EFBFBD>}<7D>z<EFBFBD><17>|<7C>H<EFBFBD>w>87ξP_<50>ڱ:<0F>ixx<78>ӊ<EFBFBD>S<EFBFBD>.]<5D>Z=<3D> <0B><>
Ub<EFBFBD>^FD<46><44> h1<68><31>g<EFBFBD><67>8<EFBFBD><08>"<22>6<EFBFBD><36><EFBFBD><EFBFBD>t<EFBFBD><74><EFBFBD><1B>!<21>y<EFBFBD><79><EFBFBD>.d0<64><30><EFBFBD> 2<<3C>a.<2E>gg<67><67> FWϓx;&=jK<6A>><3E>͠<EFBFBD>H>1<><19><><EFBFBD>f<EFBFBD>p<<3C>0<EFBFBD>v<EFBFBD><76><EFBFBD><08><>2 <0C><>r<EFBFBD>,<1B>]1<><31>^5<><35><EFBFBD> A<><41><03><>v<EFBFBD><76>4<0E>! f<>=a<61><7F>Ra@<40><>o B`.<2E><19>X<EFBFBD>p<13><><EFBFBD><01>e<EFBFBD><65>a1'<01><><00>\<5C>?)nS<6E>i<00><>܁Uw<><77><1C>-@#<23><><EFBFBD>Zu!<21><><EFBFBD><EFBFBD><EFBFBD>HiĢ)1zǘѫH1g|W<>-j+<2B><EFBFBD><E0A3B3><EFBFBD>n<EFBFBD>;<3B>v<EFBFBD>p$C"O<><4F><EFBFBD><EFBFBD>$E3<45>P<EFBFBD>Jz$<24><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><16><><EFBFBD><EFBFBD>w<EFBFBD><77>khµ<68>xDA<><41><EFBFBD>ϝ{<07><>q`(<28>X<12>"F<>by<7F><79>B1<42>\z<><7A>1<EFBFBD>WNoJJ<18><>{/!\ܶ<>ݯ<EFBFBD>@p<>T<03>~<7E><>`<60><><19>w]<5D><>oBb<42>0~}y<05>qy<71><79><EFBFBD>8<1D>W<EFBFBD>C<EFBFBD><43><EFBFBD><EFBFBD><EFBFBD>.`ϲ@\W<>@<40>'w<>0<EFBFBD><30><51>x+xڣ<78><DAA3><1A>+<08>5<><35>(<28><>-<2D><> ¡"=<3D><>h<EFBFBD><1B><><EFBFBD><EFBFBD>ε'<27><><EFBFBD><EFBFBD><0E><>5M<35><4D>i<EFBFBD><69><EFBFBD>4<EFBFBD><1B><><18><><EFBFBD>l<EFBFBD><03>V=<3D><>¥<EFBFBD>~ <0C><><EFBFBD>ݚqJJ<4A>$@<40><>.<2E>#J C<PXW<58><57><EFBFBD><EFBFBD> r<><1C>s<7F>P<EFBFBD><EFBFBD>]<5D><>lg<6C>;m<>O%<25><><EFBFBD>,<2C><><EFBFBD>s8<73><38>;<3B><><EFBFBD>`<60>=<3D><>n<><6E>;<17><>"<22><><EFBFBD><EFBFBD>ќ<EFBFBD>İ/<><EF9095><EFBFBD>CJ<43>lbq<62>.bc돍<63><05><><EFBFBD>f<07>><3E><>:@<40><><07><>_<>L=@fOx<06>:ۑW<DB91>U@$<05><>x<EFBFBD>4J<34><4A>\o<><6F>bL5<><35><EFBFBD>o<><EFBFBD>#<23>ר<>ޠ3<DEA0><33>s<EFBFBD>R<>-<2D>X <0C>3<10>+<2B>s-<2D><><EFBFBD>ll<07><>R><3E><><EFBFBD><EFBFBD>K<EFBFBD>,q<>E:g<><67>yR<79><52>HZF<5A>ۜ<EFBFBD><00><>L<EFBFBD><4C><EFBFBD><EFBFBD>F\<5C><><>2<1C>\<5C>@[<5B><><EFBFBD>Ү0ik,<2C>Ġ0`~<$p<7F>O<1E>`<60><>lp<6C><70><EFBFBD><EFBFBD><13>l]<5D>Tz<>}<04><><EFBFBD>A<EFBFBD><41>q0<71><30> $%<25><>#E<>2l
><3E><>w]F<><46>;<3B>o<06><><EFBFBD>tV8<56>!9<><39><EFBFBD>`<60><17><>,_<17>?<3F><> <0C>s<EFBFBD><EFBFBD>Z<EFBFBD>t<EFBFBD><74>N<EFBFBD>z<EFBFBD>W<EFBFBD>i<EFBFBD><1B><><EFBFBD>"F+,}<7D><><S<><53>Vf<56>kx<6B><06>G<14>5<EFBFBD><35>t<EFBFBD><74>Av<41>G<EFBFBD><47><EFBFBD><EFBFBD>ȃ`y<><79><EFBFBD> <0C>4<1E>+k(=Xjk<15>w<0F>\F<><46><EFBFBD>i<EFBFBD>\^<5E>@&<26>K"5<>
<EFBFBD><EFBFBD><11><><EFBFBD><06><><EFBFBD>g?2<><EFBFBD>Aw<41>LRP3k<33>D<EFBFBD>"<22><>%u<><75>Ԧ_<><08><><EFBFBD><EFBFBD>K<EFBFBD><13>G<12> &?i<>=4<>
<EFBFBD><00>\D#<13>^<5E>(!<21>݅4R㞟U<E39E9F><55>G/<2F>x&!~<7E><><EFBFBD><EFBFBD><EFBFBD>A<EFBFBD>L,<2C>fb<66>F<13><><EFBFBD><18><>Ġ<EFBFBD>&<26>m8<11><19><>Q<EFBFBD><51><EFBFBD>n<EFBFBD><6E>hv<68><76><EFBFBD>)<29><><EFBFBD>m<EFBFBD><6D>V;<3B>i <20><>v<EFBFBD><76><05>rC<72><43><EFBFBD><1D><><EFBFBD><EFBFBD>F<EFBFBD><46><EFBFBD><EFBFBD>hx% <20><>`<60>X<1E>6<EFBFBD>g<EFBFBD><67> <0A><><EFBFBD> d.:<3A><>E<EFBFBD><16><><EFBFBD>bG<><47>W
q<EFBFBD><EFBFBD>gB,J<>l]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>T4nP<6E><50><EFBFBD><EFBFBD>t<EFBFBD>CO<43>V<><56>^<5E><><0F>L8<4C>ʄ<EFBFBD>vi+<2B>V<EFBFBD><56>/W[<18><05>]9<>5<EFBFBD><35><EFBFBD> <20>[2D<32><44>m<EFBFBD>xϸ}<7D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>$ZR <20>L<EFBFBD>>\=<07> <0B>CR<43> \<5C>d<03><>W#zDM<44><4D><EFBFBD><EFBFBD>qf@ <0B><>,<2C>{<7B>c<EFBFBD><63><EFBFBD>o[j<><02><><EFBFBD><34><CF9B>L$V<02><>ڵ<EFBFBD>g3<67><33>’ <20>4<EFBFBD><34><1E><><EFBFBD>`<00><>k:~<7E><01><>a9<61><39>C<EFBFBD>9<EFBFBD>50U]Y<17>F<EFBFBD><46>˧j<1F>Կ<EFBFBD>m<EFBFBD><6D>B9<42>p<EFBFBD>Q<EFBFBD><51>#hҘ<68><D298><EFBFBD>z<EFBFBD>$u<>r*<2A>EH<EFB884>M<EFBFBD>@<40><><EFBFBD>j<EFBFBD>Q"<22><>(<28><>(<28>:<3A><><10>4<><34> |{<7B>Q<EFBFBD>'<19><>h<><68><0A><>ɒp<>&Q<><06>4=yS<79>tV3<56><33>PyW1<57>Zm<5A>g&<26><>m5ۜ9ʜ<15>[<5B>4<EFBFBD>3<EFBFBD><33><EFBFBD><EFBFBD>a <20><17><><EFBFBD>#e<>ԍ<EFBFBD><D48D><07>"x<>_( <0C><><EFBFBD>,<2C>}<7D><><EFBFBD><EFBFBD><EFBFBD>Tb<54><62>a<EFBFBD>*<2A><><EFBFBD>,<2C>^;+=Z 4=L<>O ]<5D><><17>9<05>zDG4<47> $4<>#qλPǑ<50>C<EFBFBD><43><EFBFBD>"PV<50><56><EFBFBD>a<>\<5C><>:2{z<>R<EFBFBD><52>v+3p0$X<><58><19> iw\W<><57>Y<EFBFBD>X4<>NjR<6A>1;<3B><><EFBFBD>
P<>L
R%<25>(<28>!<21><>><3E><>zo<><6F>^Y<<3C>bX<62>c<EFBFBD><63>c<EFBFBD>jA<6A>MLo<4C>p<EFBFBD>1O[<5B><><EFBFBD><EFBFBD>80AZ<41> <09>:<3A>,H<>r?[<5B><17><><EFBFBD>0R<30>JG<4A><07><1B> I<><49><EFBFBD>4j<34>ĥb<C4A5>q<EFBFBD>V<EFBFBD> s<><73><EFBFBD><EFBFBD>a<EFBFBD><1D>Tv,<2C> <0A>=<3D><19>P<><50><EFBFBD><EFBFBD>'3<><33>8<><38>}<7D><><11>K<EFBFBD>%~qp-<2D><><08>_<EFBFBD><5F><EFBFBD> <09>ӆ-<2D><>fS<66>YA<16>:<3A>_B<5F>݌~<7E>ʤ<EFBFBD><CAA4>9Rl<52>L+/ Y&<26><>EDiS<>]&<26><12><>:a<><61><EFBFBD><EFBFBD>
<0C>̎<EFBFBD><CC8E>j<EFBFBD><6A><EFBFBD>v,Rfo<66>><3E>D<EFBFBD>9<EFBFBD>N<EFBFBD><4E><EFBFBD> <0A><14>nZA<5A><41><EFBFBD>;<3B><13>2H<>hL<68>.<2E>o<EFBFBD>b<EFBFBD>`<60>2<EFBFBD><32>Q<EFBFBD><51><1A>h;$<24><10><> <09>U<EFBFBD>a<EFBFBD> <0C><><EFBFBD><EFBFBD>Z<EFBFBD>v<EFBFBD><76>>|*<2A>r/cn<63>X<07><>+<2B>t<EFBFBD>"<22><12><><EFBFBD><EFBFBD>\<5C>~<7E>od<6F><64>$PT Ap<41>I<EFBFBD>G<EFBFBD><47><EFBFBD>u<EFBFBD>P<08>$<24>A<EFBFBD>wU<><55><EFBFBD><1D>5<EFBFBD><35>'ҙx  <0A><4F><C7A2><EFBFBD><EFBFBD><08><>4<EFBFBD>)<29><><EFBFBD>m<EFBFBD><6D>,`FLA<>8<EFBFBD>V<>He<1E>q!<21><>Ű<1F><><EFBFBD>S<EFBFBD>~<7E>.f<19><>GYӴ<06><36>y<EFBFBD>26<32>j<EFBFBD>-2<><32>~<7E><00>e<EFBFBD><65><EFBFBD><EFBFBD>F<EFBFBD>Ii <06>)$<08> <20><><EFBFBD><EFBFBD>Z<EFBFBD>6H<36><1D><>8<1C><>푉"|<7C>ž6*<2A><>$<24><>E<EFBFBD>Lw<4C><77>!<21><><EFBFBD>b<EFBFBD>}<7D>W<EFBFBD>l<02><>`1<><70><D19F>'<27><>d<EFBFBD><64><EFBFBD>҈$K<><03>wi@<40> <0A>6<EFBFBD><36>y<EFBFBD><79><EFBFBD><15><>)<29>Ei<45><69>46<34> <1F>9eJ5<06><>͚<EFBFBD><CD9A><EFBFBD><EFBFBD><EFBFBD>A<EFBFBD>j<><6A><EFBFBD>0O<30>`&y b<>4<EFBFBD>z$<24>=j<>ߡG<DFA1><47><EFBFBD>)<29><>}<7D>4<EFBFBD>W<EFBFBD>1(fɽ<66><C9BD><EFBFBD>8N<38><4E><EFBFBD>B
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>(<28><><EFBFBD><EFBFBD>5<EFBFBD><35><EFBFBD><EFBFBD><EFBFBD>4<00><>ն<7F><D5B6>[<5B>><3E><11><><EFBFBD>Ư<EFBFBD>ښ<17><>m<>ɧ?g<>K<EFBFBD>8HP<>J<EFBFBD>o$z<>><3E><>Ɋ<EFBFBD><0E>j1I#,<2C> և<><D687><EFBFBD>Q<EFBFBD>uVC<56><43>H<EFBFBD>?<3F><>}<7D> Y<>BTy!<21><>o<9<>Wu<57>^<5E><>/A<><41>mSG<1D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
<EFBFBD>t7w<EFBFBD>Cp<EFBFBD>(<28>Z|L<>=<3D>!xCP<>?<3F><>I<EFBFBD> f<><EFBFBD><7F><EFBFBD>A&"E<><45><EFBFBD>-QyE<79>קsyه<79><D987><EFBFBD><EFBFBD>Ey<><79>!k?<3F>q<><18><>Rڠ}`<60>8@r<00><><EFBFBD><EFBFBD>o<EFBFBD>>f<><66>G<04>S<EFBFBD><17>e5</:<3A><>Z<EFBFBD><5A>We<57>!-<2D>L:<3A>{Eրu/<2F>><1F>3 <<3C>#<23>Vn<56>]}<7D><>#t4{#<1B><>s<EFBFBD>e<EFBFBD>]r<>k`P<><50>0<EFBFBD>{.<2E><><EFBFBD><EFBFBD>-ŵs<C5B5><73>2"<22>H<EFBFBD><48><EFBFBD>:<3A> ,<17><><EFBFBD>Zb-<2D> P$<24><>Aqd<71><64>n<EFBFBD>n<EFBFBD><6E><EFBFBD><EFBFBD><EFBFBD>J<><4A>]<5D><>s<EFBFBD><1B>ֹ<EFBFBD><D6B9>6<EFBFBD><36><EFBFBD><EFBFBD>ʬ<EFBFBD>N<EFBFBD><4E>u<EFBFBD><75><EFBFBD><65><C4AB>m˓0
@<40>im[IfN<19><><EFBFBD>\<5C>ea֧<61>9?<3F>~J<><4A>5<EFBFBD>M<EFBFBD><06><><EFBFBD><00>DA<44>h<EFBFBD><68><EFBFBD>7s<37><73><EFBFBD>D5<44><35><EFBFBD><EFBFBD>}RI<52><0E><>A<><41> <17><><EFBFBD>Y<EFBFBD><59>G<EFBFBD>)\;H<>Qῧ<51>$0<>@<40>G<EFBFBD><47>><3E>,<2C>pbi<62><69><EFBFBD>><3E>%<25><>:<3A>4TS<54><53>z<EFBFBD><7A><EFBFBD><EFBFBD>0s<>ju<6A><75>G<EFBFBD><47><EFBFBD>`<60>s<EFBFBD><0E> xB<78><42><EFBFBD>}<7D>3<EFBFBD>44R<34>0LV<4C>\<5C>A'B[<5B><><EFBFBD><EFBFBD><EFBFBD>H<EFBFBD>I<EFBFBD><49>!<21><><EFBFBD><EFBFBD><EFBFBD><1A><><EFBFBD>_+w"<<06><><00>"G<><47>bIm(+<2B>8.<2E>aJ<61>O<EFBFBD><4F>T<EFBFBD>f]<5D>CGa<>U<1C>m6<6D>2^ D<><44>]<5D><>y#<23><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Uf<55>#<23>Aeŀƽ<<19>}Y3s<02>q<EFBFBD><71>9<EFBFBD>]熟.S<>8<EFBFBD><38>3<EFBFBD><33><EFBFBD><EFBFBD>)<29><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1F><14><><01>u{<7B>l<EFBFBD>u<EFBFBD><75><EFBFBD><EFBFBD>-<1E>m<EFBFBD>8<EFBFBD>
<EFBFBD>7<EFBFBD><EFBFBD><EFBFBD>k5^e<07>J<1B>P^<5E><1E>c<EFBFBD><12>z|<7C>͐<EFBFBD><CD90><EFBFBD> <0A><>Dz<EFBFBD>W<EFBFBD><1E>8<EFBFBD>Ä<EFBFBD><C384><EFBFBD><EFBFBD>m<EFBFBD><1A><1E>zm<7A>cf-<2D>iG<>ۆ<EFBFBD>1<EFBFBD><31>y<EFBFBD>{<7B><>N<><4E><EFBFBD>6<EFBFBD><36><EFBFBD><EFBFBD>(<28><>><3E> T<>{ƫ<>a<EFBFBD>̶<EFBFBD><CCB6><EFBFBD><EFBFBD>F<EFBFBD><46>T<EFBFBD><54>}
<EFBFBD>w<EFBFBD>3Z|<7C>W<EFBFBD>ޣ<>-ڱx<DAB1><16><1E><17><><EFBFBD><EFBFBD><1E> +<2B>F<EFBFBD><46><EFBFBD>/<2F><><EFBFBD><EFBFBD>:i<>A/{<7B><>qi7t<17>*@E@e<>I2<49>d,+<2B><>j˾޵f|u<>s@<40>O<EFBFBD>E><3E><13><><EFBFBD><EFBFBD>o<EFBFBD><35><D885><EFBFBD>W>+<2B> Y<>w.<0F>g<EFBFBD>G[t<>ѹZ[<5B>y <0B>rVL<><4C>\<5C>_<06><>}q<><71>ӻK]<5D> T<>{<7B><><EFBFBD>u7<1B><><EFBFBD>j?Q<><51><EFBFBD><EFBFBD><1F>q<EFBFBD>O2<4F><32>E<EFBFBD><65><D99B>\<5C>/<2F><>1U<31><55>K<EFBFBD><4B><EFBFBD>X<EFBFBD>x<EFBFBD>O<EFBFBD>u0<75>5<EFBFBD><35>fN<66>ӈd<D388>ng<6E>\mA>Z<><5A><EFBFBD><EFBFBD>H<EFBFBD><48><EFBFBD>Vos<6F>&?<3F>!<21><><19>:<0E>4<EFBFBD><06><><EFBFBD>M<EFBFBD>,<2C><><1C>/<2F>2h<32>;<3B><>&.<2E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>#<23><>K<EFBFBD><4B>Hu<48>:<3A>A<EFBFBD><41><EFBFBD><EFBFBD><EFBFBD>z<EFBFBD><7A><EFBFBD>/N<>z<><07>-߲zr<7A>^<5E>4{J<>֓<><D693>YVlf0gɦ<67><C9A6><EFBFBD>J<>zW<7A>fR<x<>+<2B><>>"<22>Yc<59><00><><EFBFBD>7<18>uA<75>X<EFBFBD><58><13>wF_6<5F>Vo<56> <0A>i3^<5E><>C<17>C<EFBFBD>NiL<15><>z<EFBFBD>><1B><><EFBFBD><ED8AB9>c<EFBFBD><63>w1 <17>u{<7B><>{O<>개*N׾P<D7BE>Ìݪ<C38C><DDAA><EFBFBD>S<EFBFBD>.<2E><>7<EFBFBD>0͑<11><><EFBFBD><EFBFBD><EFBFBD>xS<>o<EFBFBD>o<EFBFBD>z<EFBFBD>D<EFBFBD><44><<3C>V<EFBFBD><56>B
USAOռ,<2C>{<7B><>8<EFBFBD>h<EFBFBD><01><><EFBFBD>#<23>.<2E>5o3<<3C><><EFBFBD><EFBFBD>r<EFBFBD>b<EFBFBD><62><EFBFBD><EFBFBD>Z<06> <0B>wc<77>l<EFBFBD>r<EFBFBD>%<0F><><EFBFBD><EFBFBD>/qc_<63><5F> <0B><>H-\J<> "<22><><EFBFBD>]x<><78><EFBFBD><EFBFBD><EFBFBD><EFBFBD>_Cq<43>u]VR<56>_snwչbLv<4C>B<EFBFBD>:W<>̃<EFBFBD> W<>~<7E>}<7D>Q&<26>6<><36>Q0<05><>D굨<44><EAB5A8>Y|,<2C>)<29><>z<EFBFBD>}I<><49>X-f<>[n\xW<><00><1C> ^[<5B>k<EFBFBD>\sy<73>df[C<>
H<EFBFBD>D<EFBFBD>;$<24><><EFBFBD>_la<10>Z<><5A><EFBFBD><EFBFBD><EFBFBD>t<EFBFBD>UF)<29><<1B>XBUgP#<23><>ej<65>s<EFBFBD><73> N<><4E>2 <0B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD><6F><EFBFBD>j<EFBFBD><6A>h<02><11>05<30><35>P<EFBFBD>0<EFBFBD>|3<><33>a %<25><>g<EFBFBD>`<60>C1<43>r%<25>ڱ`<60>.?<3F>?KF<<3C><><EFBFBD>2<>=T<><54><EFBFBD><EFBFBD><EFBFBD><EFBFBD>E<>V<EFBFBD>7<EFBFBD><37>_0.<2E><><EFBFBD><EFBFBD>O(Gnl<6E><6C> T<><54><05>[i<>vk<76><6B><05><>E<EFBFBD>G<EFBFBD><47><0E>w<EFBFBD>(%<25>)<08><><EFBFBD><EFBFBD><18>m<EFBFBD><6D><EFBFBD>F<EFBFBD>;<3B>S<EFBFBD>*<2A>A><3E><>!<21>X<EFBFBD>A<EFBFBD>*<2A>|V<><56>[<06>O<EFBFBD>^<05><><EFBFBD>R<EFBFBD>q<71>O<EFBFBD>=<3D>e<EFBFBD><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD>g3<67><17>w<EFBFBD>y<>)<29>K'<27>N<EFBFBD>p<EFBFBD>,<2C><>m<EFBFBD><6D>)h<>*<17><><EFBFBD><EFBFBD>^g ^<5E><1E>C<EFBFBD>Fq<1D><>O<EFBFBD>{<7B><19><><EFBFBD><EFBFBD><04>rI<72><49><EFBFBD>|<7C><11>C<EFBFBD><43> ԋ}2Į<32><C4AE><EFBFBD>&;Grp <0B><>H<EFBFBD><48><EFBFBD>mZ <20><> g Ľ<><C4BD>Z;_(<28>v<><76>T<EFBFBD><54><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.S<><53><EFBFBD>^<5E>C
<1F><>=@<40><>.&<26><EFBFBD><7F><EFBFBD>c6<63><36>WIj<49>: mO=<3D>iI<69>ۿ)><3E><><EFBFBD><EFBFBD>;<3B>p?<><CEBE><EFBFBD>_*>82<38>~<7E>\<5C><>g&<26>v<01><1F><>ZZ<5A>%<04><>?<3F>3x<33> <09>D_\Q<><51>vѹ~<7E><>5i<35>t<EFBFBD><74>r%8<>8_<><5F><EFBFBD> <0C><EFBFBD>à<EFBFBD><C3A0><EFBFBD>o<EFBFBD><6F>w<EFBFBD><77><EFBFBD>MxjA<6A><41>Ʉ~-/<2F>k!<21>:<16>x><3E><><EFBFBD><EFBFBD><EFBFBD>yRs<52><73><EFBFBD>;<3B>{<7B><>RJa<4A>Z<1F><>*<2A><><EFBFBD>E^<5E><><EFBFBD>6<>>@_m<5F><6D>2Trяs<D18F><1F>
<EFBFBD>3<EFBFBD><EFBFBD>ؚX<1C>FUM@V<><56><EFBFBD><EFBFBD>:^mW<>?f&<26>g<EFBFBD>Yd"?/d~<7E>r<EFBFBD><72>&V<>P<EFBFBD>|<7C><>U<EFBFBD>m<EFBFBD>NE AJ<41><4A>Nvbm<62>U/<<3C><>-<2D>_<EFBFBD><5F>[-<2D>]<06><><EFBFBD>R<EFBFBD><52><EFBFBD><EFBFBD><00><>1<EFBFBD><31><EFBFBD>Λ<03><><EFBFBD>p<EFBFBD><70><EFBFBD>l<EFBFBD>oo<6F>C<EFBFBD>=<3D><<3C><>/84}<7D><><EFBFBD>#<23>L<EFBFBD><4C><EFBFBD><EFBFBD><EFBFBD>Ę<07><>(<28><><EFBFBD>\<5C><>Q<EFBFBD><51>\<5C><05><><EFBFBD><EFBFBD><EFBFBD>^<10><><EFBFBD>ظ<EFBFBD><12><><EFBFBD>-\<5C>M<EFBFBD><4D>u;O<>9<EFBFBD><51><CB94>f<><66>(}t,<2C><><EFBFBD>?Z<>o<18>W<EFBFBD><57>$0<><30>@<40>+p<>V"*H՜kP<>ؔ<EFBFBD><D894>3l<><6C>U0/Q:<16><>U~ <16><>2<EFBFBD>W<EFBFBD>Ё`<60>;h<>% <0B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>RP<52><50>+<0F>@<40><>Q<EFBFBD>Ԛ<>%<1E>O<02>#&c<>4<01>Ҍ<EFBFBD><D28C><EFBFBD>۷;<<3C><>G<EFBFBD><18>B<06><06>
Bd<EFBFBD>S<><53>T*ș<>j<EFBFBD>ȑE<C891><45> <0C><>j<EFBFBD>L<EFBFBD>%<25><>f<EFBFBD><66>z<EFBFBD><7A>k<><6B>;W<>A<EFBFBD><41><EFBFBD>8T<38>z<EFBFBD> vV%ӦmtRb<52><62><EFBFBD><EFBFBD><19>g<EFBFBD>x's<><73>p<EFBFBD>zU<7A>W<EFBFBD>>0<>>
<EFBFBD>S<EFBFBD><07>|<7C><>LN<4C>2D<32>:D<>Ȥ<EFBFBD>d<EFBFBD><64><EFBFBD>K?e<>/<2F><><EFBFBD><4F>29<32><39>͘D.븀<>Z<EFBFBD><5A>Z9<5A>/<2F><><EFBFBD><EFBFBD>Kq<4B>!MF<4D>><3E><><12>֞<1F>s<EFBFBD><|<7C><>^<5E><17>3$$<24><>N<EFBFBD><4E><EFBFBD>> &<26>v><3E><>Pm<50><6D>~t?Iҗ<>f*<1C><>{<7B>XE<58>j<EFBFBD>4V<34>4B<34>m<EFBFBD>,[!D0NJU<4A><55>_lU}<7D><><EFBFBD>><3E><>/<2F><>4<EFBFBD><34><EFBFBD>$\<5C><><EFBFBD><EFBFBD>fPs<11>m1<6D>;|Ӑ<>L}[<5B>V<EFBFBD><56><1C><0E><><EFBFBD>đ<EFBFBD>;<3B>F0G<30>Rcڂ<>T<1A>]<5D><><EFBFBD><EFBFBD>$<24>p<EFBFBD><70><EFBFBD><EFBFBD>C<EFBFBD>¬<EFBFBD>;q<>^<5E>NFeD<65><0F>mv˽ɞĴ]<5D>}<7D>顠PB[<5B>:<3A><><EFBFBD><15><>^<5E><><EFBFBD><EFBFBD><EFBFBD>ƥ8<C6A5>z<><7A>R<EFBFBD><19><>o<03>X<EFBFBD><58>n<EFBFBD>B<EFBFBD>A<EFBFBD>Ȍ<>MG<><47>"<22><>R<EFBFBD>l7<6C><37>|<7C><><EFBFBD>
5<EFBFBD>c<07> <><7F><EFBFBD><EFBFBD><EFBFBD>6<EFBFBD><36><EFBFBD>ζ<EFBFBD>:<3A><>P<><50>.kŸԆ<C29F><D486><EFBFBD>-<2D>S0><3E>p;р<><D180>A<EFBFBD>E<EFBFBD><45><10>C<EFBFBD><43><EFBFBD><7F><EFBFBD>Բ9<D4B2><39><EFBFBD>t<0F><>y<06><><EFBFBD><EFBFBD>`qR<71><52>e<EFBFBD><15><>jP<6A>逼I<E980BC><49><EFBFBD><EFBFBD>0VJV\3.<2E>1<EFBFBD>W7<><37><EFBFBD><EFBFBD><1A><>s)<29>մ<EFBFBD><D5B4>z<EFBFBD>|zkAP<41>x<EFBFBD>g<EFBFBD><67><EFBFBD>xc<78><63><16> <20><EFBFBD> <20><>~w<0E><07>[<5B><>s[<5B>ې<EFBFBD><DB90>G`굅I<EAB585><49><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><<3C>r il-|<7C>.t 锡b<E994A1>1ؖrސOe<4F><65><EFBFBD><EFBFBD>x<><78>:<<3C><><EFBFBD>xVn<56><6E>A}_D<5F><44>Jr-<1B>dwqX<>m<EFBFBD>rev`<60>r. [v42<34>0<EFBFBD><30>0<EFBFBD>
ۃ<EFBFBD>'<27><>{ 0UY ']D ~4<><34>{kU><3E><>!+<2B><>QU<51><55>vn<1C>hDTȗ<<3C>[<5B>$<02>ߧ<EFBFBD><DFA7><EFBFBD>4<EFBFBD>@r<><72><EFBFBD>h2<68>!<21>$ #`8԰<>B&<26><>E<07>25<32><35>CY<43><4B>ƫ<>Q<EFBFBD><51>R&<26><>Dv<44>#<23><><EFBFBD>f<EFBFBD><66>$+<2B><>QgT<67><54><EFBFBD>6<EFBFBD>8U;<3B>R<EFBFBD>p<EFBFBD>[X<><58><EFBFBD><EFBFBD><EFBFBD><EFBFBD>S<EFBFBD><53>gY<1A>9<EFBFBD><39>e <19><>s<EFBFBD>I<EFBFBD>d$kd<6B>Ҭ<EFBFBD><D2AC><EFBFBD>Ւ<EFBFBD><D592>]<5D><1D><><EFBFBD>U<EFBFBD>ʁ:<3A><EFBFBD>[R<><1B><>;<3B><>%<25>Ǩ<EFBFBD><C7A8><EFBFBD><EFBFBD>R<EFBFBD>r^lX<6C>ЛZ<D09B>=]<12>T <07><>m<EFBFBD>KpdVyv><3E>!<21><>T<EFBFBD>6Kl<1C>)[<5B>5<EFBFBD>0}<7D>dY!.IgܧL+<2B>Td<54><64><0F><>)<29><><EFBFBD><EFBFBD>:<3A><>^X<>}<7D><><EFBFBD><EFBFBD>.<2E><>QQ<51>+<2B>}ùC<C3B9>E<1E>^j<>c<EFBFBD><63>Q<EFBFBD><51>W5!ަ<> [<5B>m<EFBFBD>&c΀<63><CE80>3<EFBFBD>^<5E>f<EFBFBD><66><EFBFBD><EFBFBD><EFBFBD>Ev<45>s|<7C><><EFBFBD><EFBFBD>r<EFBFBD><74><D2B7><EFBFBD>ϴ#h<><15><13>v\<5C>/<2F><>*<2A><>8<EFBFBD><11>Fh<46>ƚ<EFBFBD><C69A>b<>dس<>x߻죰Wf<57> <09><EFBFBD>X<EFBFBD>1Q<31><51><><00>Ҵ<7F><06><><1A>ɯ<67><C5A2><EFBFBD>^*<2A>X<EFBFBD><58><EFBFBD>c<EFBFBD>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD>DI<44><1F><><EFBFBD>hJ<68><4A><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!<15><><EFBFBD>y<79><7F>[<5B>}<7D><>fAPf<50><66><EFBFBD>xF?<3F><0F> <0A>a4ЌTfi<66>֌H<0E><>㿬O<E3BFAC><4F>N<EFBFBD>мג<D0BC>4<>YMʭg<CAAD>4<EFBFBD>L<EFBFBD> <0A>^S^<5E><>;<3B>[<5B>D <0A><>U"`<60>z<07>м<EFBFBD><D0BC> eB<65>| <06>C<EFBFBD><43><EFBFBD>X<EFBFBD>L<EFBFBD>Q`<60><6C>a<EFBFBD>y<10>~<7E>sV<73>H<EFBFBD>f<EFBFBD><66><18><00>۩UK<12><>.<2E>[<5B><>T<EFBFBD><54><EFBFBD><EFBFBD><EFBFBD>X<EFBFBD>U<EFBFBD>><3E>¯K<C2AF>0<EFBFBD>xX<78>%<25>Z<EFBFBD><5A>܇<EFBFBD> <20>$<24>T<EFBFBD>6d); ~<7E><><EFBFBD><EFBFBD><11>9<EFBFBD><39>$Td<54>A<><41><EFBFBD><EFBFBD>y<EFBFBD><79>u<>Z"ݵDdXZ)3<18>՝<EFBFBD><D59D><i<><69>~<7E>m2R"d<><64>ނK<DE82>G<EFBFBD><47>p<EFBFBD>
<EFBFBD><EFBFBD>i<EFBFBD><EFBFBD>#V|<7C>iX<11><>Ϳ<EFBFBD><CDBF><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
F<EFBFBD><1C><>{T<><54>JГp<D093>mb<6D>ML<4D>ȳ<EFBFBD><C8B3>m<><6D>ؼ<7F><D8BC><EFBFBD><13> 0<>ܹ<<3C>_<EFBFBD><5F><EFBFBD>J<13>~<7E>m<EFBFBD>(0M<30><4D>IVE{l8ë<38><C3AB><EFBFBD>MI1<49>*ߋ0.<2E><11><>K<EFBFBD><4B>:D<17>'\<5C>P<>%<25>uw<><77><7<>}<7D><><EFBFBD>~<19>\<5C><><EFBFBD><7F><EFBFBD>]!<1C>3<06>%<25><><EFBFBD><EFBFBD><EFBFBD>d<EFBFBD>%x<>z$X<><58>n \<5C> R<> <0B><><EFBFBD>TRZp8wi<77><69><EFBFBD>%.-<2D><><EFBFBD><EFBFBD><EFBFBD>o<01><><EFBFBD> <20>t<><0F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>*<2A><02>JI<13>Л<EFBFBD>><02>v<19><><05><><EFBFBD><EFBFBD>_<EFBFBD>;B<><42>j<EFBFBD><4F><D793>z!~N5<0F><>q<EFBFBD><71>jhɳD)<29>)<1F><><EFBFBD>s<>oY<1E>H<16>̡<EFBFBD>z<><7A>vlah<61>ԛ<EFBFBD>,U:'4H<34><48><EFBFBD>J<EFBFBD>o<EFBFBD><6F><06><> 1<N<><4E><EFBFBD>_<18><00><05>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>v<EFBFBD><EFBFBD>S<EFBFBD>zbj <0C>|W<><57><<3C><06>s<07>TZe<5A><65><EFBFBD>Z<EFBFBD><5A>tk<74><EFBFBD> {6)<29><>;4<><04>;e<16>S\t;<3B><><EFBFBD>j<EFBFBD><6A>8:te<74><65>vuy<75><18>⢌(<28><><EFBFBD><EFBFBD>O<EFBFBD><4F><0F><>Ā27<04><><EFBFBD>t%^,<2C><><EFBFBD><EFBFBD>*<2A><13><><EFBFBD>d<EFBFBD>Lv1&<26>F)<29>n<EFBFBD><6E>uS<75><53><EFBFBD>ݾ<EFBFBD> ]<5D><><EFBFBD><EFBFBD>E<EFBFBD>Z<EFBFBD><07>p<EFBFBD><70><EFBFBD>
u<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>8<EFBFBD>׶<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>PX<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><16>~<7E><>f<EFBFBD><03><><EFBFBD><EFBFBD><><D28A><12>Qq-<2D>7%<25>D<EFBFBD><44>:A<><41>%<1C><>R 2<>:B<><14><>K 3<>ܭ<EFBFBD>S<EFBFBD>4T<34>j<EFBFBD><6A>}<7D><>g<EFBFBD><18>><1B>B$<24>BdGO <0A><>7<EFBFBD>=~-u<>s'P<><1B>O[u<><75>Ȓ<EFBFBD><C892>G]K<>p<><70><EFBFBD>D<EFBFBD><44>Ut<55><1E><>P;<3B>R<1F>0 <09><>!sʑ<73><CA91>"<00><><EFBFBD><03>\<17>H<EFBFBD>Ѕ"<22><1A>ڋE@/;6n1<6E>e<EFBFBD><65>x<EFBFBD><78><EFBFBD>Ѭ<EFBFBD><D1AC>3<03>z <06><>B<EFBFBD>(}<7D>< _{ХάT<CEAC> <0A>%<25><01>:g<13>2|<7C>B<EFBFBD><42>'<27>ϳ#s<>xaK\xǏ<78>1;<1C><16><>u<EFBFBD>_<EFBFBD><5F><EFBFBD>[<5B>ֆR<D686>d<EFBFBD>7<EFBFBD><1D><>B<EFBFBD><01><><EFBFBD>]'<27><>:<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><43>G=<3D>&<26>hX<12><EFBFBD><7F>j>,<12>B<EFBFBD><42><EFBFBD><EFBFBD>-<2D><><04><>$<24><>M<EFBFBD> <20><> <0A><><EFBFBD><EFBFBD>ك R=3<><33>Iʰ<><47><D3AA>=];K<> <0C> :}<7D>r<EFBFBD>+<2B>%<25><>/y t <0B><>"<22>R<EFBFBD>e8d<><11><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>l<EFBFBD><14><><EFBFBD><EFBFBD>U<EFBFBD><55><EFBFBD>Ί<EFBFBD><CE8A><EFBFBD>]w<>ȝ<EFBFBD>B<EFBFBD><42>x<EFBFBD>in<69>@<40><>{g6'<27><>iiN<10>g<EFBFBD><67><EFBFBD>V<EFBFBD><56><EFBFBD>p`<60><><EFBFBD><18>w<EFBFBD><77>W<EFBFBD>rYq<59>+<2B><>x<1C><> <09><><EFBFBD><EFBFBD>սZ<D5BD><5A><EFBFBD><00><>e"<22><>d<EFBFBD><01>{ <20>&<12>`<60><><EFBFBD><1F><>RN<52><4E>g<67>a<>L:<3A><02><><EFBFBD><EFBFBD>rv(4<15>2<1E><><00><>l<EFBFBD>g{P<><50><EFBFBD><EFBFBD>ח<EFBFBD><D797>Q<EFBFBD><51><EFBFBD>:uDGX<47><58>R<EFBFBD><52><15>,X5daIx<49>l|<7C>f<EFBFBD> <0A><>H>u7<75>%<25><><EFBFBD>i<EFBFBD>|ꊀe<EA8A80>M<EFBFBD><4D><EFBFBD><EFBFBD>Yz?<3F><><EFBFBD>8<EFBFBD><38><EFBFBD>2<EFBFBD>Э<0F><>dl<64><6C><EFBFBD><EFBFBD>5<EFBFBD>:l BI<42>L<EFBFBD><4C>bs72<37><32><EFBFBD><EFBFBD>~)<29><17><>?<3F>0G<30><47><EFBFBD><EFBFBD><12><>g<><67>T<EFBFBD> <20> %<13><>r<EFBFBD>A]<11>+d<><64><EFBFBD>ʤu<CAA4>^VЫe<D0AB><0F><><EFBFBD><EFBFBD>o<EFBFBD>$0<><30><EFBFBD><EFBFBD>~<7E><>&<26><><10>m<EFBFBD><6D>$<24>u <0B><><EFBFBD>Φ(~{V<><56><EFBFBD>X<EFBFBD>8w6f<36><66><EFBFBD><EFBFBD><18>o<EFBFBD><6F>Ԉt<><74><EFBFBD>M0o{<7B><>U<EFBFBD>8<EFBFBD><38><EFBFBD>6i)O<>O<1C>jA:<3A><03>\<5C><>T<EFBFBD>d<EFBFBD><64><EFBFBD><EFBFBD>b<EFBFBD><_<><5F>-<2D><35><D9B3>p^<5E><>ǡɆ<C7A1>!<1F><>f<EFBFBD><66><EFBFBD><EFBFBD>Ő<EFBFBD> <0A> y<><79>ck>Qs!䝁<>3/a2<61><16>HnN<6E><4E><EFBFBD><EFBFBD><7F> <0B>t<EFBFBD><74><EFBFBD><13><><EFBFBD><EFBFBD>1QbV<62>o<EFBFBD><6F>P<><50><EFBFBD> <17><><10><><EFBFBD>G<14>!<21>ҕ<EFBFBD>{<7B><>)9 /J<><4A><EFBFBD>A<EFBFBD><41><EFBFBD>a<EFBFBD><61>5ɖ8<C996>b(n0<6E><30>#<23>3q?mi<6D>\m <0C><>̞<EFBFBD>@|<7C><><EFBFBD><EFBFBD><1C><>]<5D>M磊<4D>K@
<EFBFBD><EFBFBD><16>" A<><41> m<><6D>!<21>tM<74><18><04>1=<3D>At|儋x<E5848B><78><EFBFBD><EFBFBD>3C9={3<15><01><>v<00>̽<><16><>a<EFBFBD><61>o<0F>p<EFBFBD>]ӱp<D3B1><70>oG<6F>m<EFBFBD>B<EFBFBD>Ն<EFBFBD><D586><EFBFBD>N&O<>g<EFBFBD><67>7z<37><7A><EFBFBD>߶<EFBFBD><1B><00><><1B>7h<>x<EFBFBD><78><EFBFBD><1B>/<2F>e<EFBFBD><65><EFBFBD>_<EFBFBD>!+6<><36>~<7E>x}<11><><><C58B>?<3F><><EFBFBD>/~<7E>:<3A>g#<23><><EFBFBD>3<EFBFBD>0<EFBFBD>O<EFBFBD><4F>@83:<1A><><EFBFBD><EFBFBD>)<29><>u<EFBFBD><75><EFBFBD>N<EFBFBD>P<EFBFBD><10>{+9j<17><>#<23><38><C8A5><EFBFBD>nP<6E>ׂ<>|fӝJ<D39D>z<EFBFBD>a<EFBFBD> ]<5D><><EFBFBD>O09<30>wp<77>IJ<49><4A><EFBFBD><EFBFBD><EFBFBD>ͽ$<24><04>oG<6F><47><00><>f<Oو<4F>`%<25><>r<EFBFBD><72><EFBFBD><EFBFBD>l)L<><4C>u<EFBFBD>^<5E>m<01> Y5<59>sͫS~<7E>1<EFBFBD>M)<29><><EFBFBD>{ L <14>c <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>e<EFBFBD><65>|<7C>_R<><52><EFBFBD>X<EFBFBD><58>;?<3F><>\<5C><><EFBFBD><EFBFBD>+9<>_<EFBFBD>X<EFBFBD>~<7E><1C>H<EFBFBD>ZKXȏ5<C88F><35><EFBFBD><EFBFBD><1F>6O<36>|m?<3F>+ɹE<C9B9><00>=<3D><>t<EFBFBD><74>5^<5E><>ONɸj<C9B8><<3C>gr<67><72>{Ic<00>q<EFBFBD><71><EFBFBD>6 <0A><EFBFBD><7F>^<5E><><EFBFBD><EFBFBD>ϕW<CF95><57>jiP*.<2E>~<7E>N<4E><7F><04>Q<EFBFBD><51><EFBFBD>g<EFBFBD>|<7C><><EFBFBD><EFBFBD>R<EFBFBD>T<EFBFBD>^hsb{{<7B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/^u<><75>\<5C><><EFBFBD><EFBFBD>au<61>O<EFBFBD>_<EFBFBD><5F>(<28><>Z<EFBFBD><5A><EFBFBD><EFBFBD>`<60><><EFBFBD>/"<22>޲<EFBFBD><DEB2>"<22><><EFBFBD><14><><EFBFBD>$<05><18><12> <0A><><EFBFBD><EFBFBD>iO_<>m%<01><1C><63>F<EFBFBD><46>"<22><>w<EFBFBD>0<EFBFBD>5Z<35> <0A>?~d<>*<2A>"h<><68>=tX<74><58><02><>-<2D><>sw<73>=?<3F><><EFBFBD><EFBFBD>QTG?<3F><10><>m!<21><>0<EFBFBD><30><18>M㯿"<22>4T<34><54><EFBFBD><1C><>Nld<6C>O<EFBFBD><4F>f<EFBFBD>0`<60><03>tlU <09>S<>Dl 0ye<79>M<)<29><><EFBFBD><EFBFBD>uK<75><4B>ih<69>G<EFBFBD><47><EFBFBD>F<EFBFBD>jfm<7F><17>έ[<5B><65><11><><EFBFBD><08><><EFBFBD><EFBFBD>|<7C><>Z<EFBFBD><5A>{<7B>B.<2E><>Zc<><63><0F>}<7D>Yn<59><6E><15><>v<EFBFBD><76>3+l<><6C>p.D<>>$<24>9#XDKQ<4B>8R<38>6<EFBFBD><36>* <20><><EFBFBD>B<EFBFBD>~<7E><><EFBFBD>3a<33>I<EFBFBD><0E>ײg <0A><><EFBFBD>Y<EFBFBD>ȝ<EFBFBD>a<><61>v5,<2C><><EFBFBD>V<7F>#we<77><65>^$2<>+1<><31>uЗ+;<1B><13><11><>X<EFBFBD>B*-<17>LV<4C><56>b<EFBFBD><62><EFBFBD><EFBFBD><EFBFBD>?AV}<7D><>:<3A>Ŗ4<C596><34><1F>`K<>j<EFBFBD><6A>><3E><><EFBFBD>Gu 3<>Xc:<1B><><EFBFBD><><07><1D>b<EFBFBD>Hšg<C5A1><67>j<EFBFBD><6A><EFBFBD>R<EFBFBD><52>&\Ӵ<>}<7D><><EFBFBD><EFBFBD>x\<04>~pݰ<><17><><EFBFBD>8]i'<27><1F><><0F><>[<5B>m<EFBFBD><14>XD<58>V̡Ń<CCA1>>Y`<60><><EFBFBD><18><>)<29><>{<7B><><EFBFBD>+<2B>~o<14>>M<><4D>)<29><><EFBFBD>Y<EFBFBD>.<2E>f<EFBFBD><66><EFBFBD><00>˯<EFBFBD><CBAF>[<5B><><1B><>\ #5 w<><77><EFBFBD><EFBFBD>{.<2E><><EFBFBD>S+_<>Ըoǡ<6F><C7A1>v1l<31><6C>圍E<E59C8D>4<EFBFBD><34><EFBFBD>\u<11><><EFBFBD>q6<71>(<28>ט<01>RU<52>a"<22><>(<28>|_<>[<5B>v<><76><03>߀<>Qd<51><64><EFBFBD>E<EFBFBD>ԑ<>k<EFBFBD>J<EFBFBD>5<EFBFBD><35>q<EFBFBD><71><EFBFBD>7<EFBFBD>L<0E>7<EFBFBD><37><EFBFBD><EFBFBD>j/<2F><>S<><53><1F>bf_?¤<>E<EFBFBD>CLu<4C>/<19><>ɫw*{<7B><><EFBFBD>4~w<> a5]<5D>-<2D><>gFit<69><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>D,<2C><>.<2E>o<EFBFBD>t<EFBFBD><74><EFBFBD><EFBFBD>Q^3 ^<5E>ڪ<02>!7<>E9$<24><>!P=<3D><><EFBFBD> <0C><> ҙc2<63><32>-t<>P<EFBFBD>SP<1A>Z<EFBFBD><5A><EFBFBD>[<5B><><EFBFBD>2<EFBFBD><32>29<32><39><EFBFBD><EFBFBD>2<EFBFBD>+p<>t<EFBFBD><74>,<2C>,<2C>(<28><><EFBFBD>|<7C>7<EFBFBD>Sv<53>X,a<61> <0A><><EFBFBD><EFBFBD>r>/1<>ڠ<EFBFBD>6<EFBFBD><36>y1<79><1F>ӓ<EFBFBD>,<2C>="<22><><Ix<49><78>~R<><52><1A><><1E>w<EFBFBD><77>M<EFBFBD>X<EFBFBD><04><><EFBFBD>{7g]:<3A>Qۏmf<1E><01><><EFBFBD>ϋ-<2D>.H<>jt|T<>Uz<55><7A><EFBFBD>@ydk<64><6B><EFBFBD>_L91<1C> <0B>9<EFBFBD><1C>n<EFBFBD>zl<
\m<><6D><EFBFBD>2?<3F>a<EFBFBD><00>`<60><><EFBFBD>j<EFBFBD><6A><EFBFBD>ocK<63><0E><05><><EFBFBD>632<33><32>p<EFBFBD>+<2B>PVv <0C><>~<7E><0F>w <20><>b<0E><>3S'<27><>ip<69>q{<1D><><EFBFBD>X<EFBFBD><58> &<26><><EFBFBD><EFBFBD>2<EFBFBD>Y<EFBFBD>4p(<1D><>4<EFBFBD><<3C><><EFBFBD><EFBFBD>KK葁c<E89181><63>=ٵxt|<7C> <10>JaF<61>t<EFBFBD>><3E><>.<2E>H<EFBFBD><48><EFBFBD>%j<>9<EFBFBD><39>%\<5C><>xR.<2E>W<EFBFBD><57><EFBFBD><11><>&<26>>&<26><> Vy<56><79>vZ<76><5A><17>G(<19>J֙o<D699>P<EFBFBD>jj|D<>w<EFBFBD><77>j<EFBFBD>w<EFBFBD>̕
<EFBFBD>M<EFBFBD>OT/u<><75>l&<26><><EFBFBD><00>u6<75>g<EFBFBD>y0 <20>YGQ<47>ttŀ<74>;<3B><><EFBFBD>H<EFBFBD>z<EFBFBD><7A><EFBFBD>$<24><><1D>Bd<42><19><>x <0C><>+<2B>d<>؍<13><><EFBFBD>L<EFBFBD><4C>[L<>ϰ<EFBFBD>N<03><0E><>u<EFBFBD><75>Q\<5C><><0E>$=<3D><><EFBFBD>YP<59>9<EFBFBD><1D><><EFBFBD><EFBFBD>D<1E><><EFBFBD><EFBFBD>$<24>z <14>/g^a<>_<EFBFBD><5F><EFBFBD>{<<3C><>@"<22><><EFBFBD><EFBFBD>|<7C>A<>fF<66>+S8O<38>V<EFBFBD>L}<7D><>yY<79>q<EFBFBD><71>x<00><<3C>"<22>DQ<44>щ;c,P$T#@<40><>r<08>1<08>đL<C491> <0B><>~<7E>QV<51>&<26>$~<7E>2:tfe<66>x<EFBFBD>%<25>8HJe}] `<60>NJu<>MG<4D><47>E<EFBFBD>$wϛ<77><CF9B>iD
<EFBFBD><EFBFBD>َ<EFBFBD>8aiv<EFBFBD><EFBFBD>'<1E><><EFBFBD>%+f.r$Yݼ/<2F>83<38><33><EFBFBD><EFBFBD><"VP&<26>o<16>X<EFBFBD><58><EFBFBD><EFBFBD>u-0<><30>g9<67>8<EFBFBD>Z<EFBFBD><5A>\<5C><><EFBFBD>B[<5B>t<EFBFBD><74>f<EFBFBD>P<EFBFBD><50> <0B><>n<EFBFBD>i<EFBFBD>+9<><39>V1<56><31><EFBFBD>L<EFBFBD><4C>h7#6~<7E><>Ȇl<1F>Pa<50><61>l<08>`<00>$'<27><><EFBFBD><EFBFBD>~<7E>GS<47><1C><><EFBFBD>m-<2D><>p<EFBFBD><70><EFBFBD>bN<><4E><EFBFBD>#<23><>5cz<63>1%!<21>le<><00>ҕV <0A>"♜<>i<1D>y<EFBFBD>g(<28><><EFBFBD>Z<EFBFBD>7+<2B><>b<EFBFBD>~<7E>Q`<60><1C><>W(<28><05><>R<EFBFBD>xw?‡U<C287>w<EFBFBD><77>4<><34><EFBFBD>gcg{<7B><02><><EFBFBD><EFBFBD>Ys*e<><65>6h<36><68><EFBFBD><EFBFBD><EFBFBD>ص<>{b<<3C><>>V<><56><EFBFBD>c,|6=<3D><><1A><><1B><14><>SJ<53>͈<EFBFBD><14>
I܎6:-<2D><>R<EFBFBD><52><EFBFBD><EFBFBD>'<27><1F><><EFBFBD><EFBFBD>]G<>Dm<44><6D>#9<><39><EFBFBD>v^1<>|<7C> ʙ<>K<10>i<EFBFBD>o<17>><3E><><EFBFBD>)2<>n<EFBFBD>9?<3F><><r<>|<7C><>lP<6C>1nQ<19><>/-lc<6C><63><EFBFBD>}v8<76><1B><58><D5AF>;<01>x<EFBFBD>j<><6A>(<28><><EFBFBD>K<>L<EFBFBD>^<5E>+<2B>[ܔ'~&<26><49><CDB9>F<EFBFBD>/<2F><> <0B>Ӹ<EFBFBD>H<EFBFBD>\<5C><>8<EFBFBD>L<><4C>\<5C><>U<EFBFBD><55><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>{v<01><><EFBFBD>9<EFBFBD>+U<><55><EFBFBD>”B<0E><><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD><63><EFBFBD>n+(<28>[<5B>&<26><1D>i<EFBFBD>#-<2D>4v;<3B><>n<EFBFBD>r<EFBFBD>]PB<50>.<2E><>#Y<><59>
<EFBFBD>\Μ<>_<EFBFBD><5F>Ŭ<>{R2<52><32><EFBFBD>lJ<6C>(5<>YX<59><58>D+<2B>3<EFBFBD><33><EFBFBD><EFBFBD>K<><4B>n<EFBFBD><6E><EFBFBD><EFBFBD><EFBFBD>q<00><><EFBFBD>$<1C><19><>/<2F>Ǎ=B <0B><>n<EFBFBD><6E><1D><><EFBFBD><01><10><>0h<30><68>C<EFBFBD>wc<63>bD+<2B><>W<EFBFBD>
z <0C><>0<EFBFBD> <15><>s<EFBFBD><09><>R<EFBFBD>X<EFBFBD>/<>U<EFBFBD><55>G<EFBFBD><47>79<37><39>O<EFBFBD><4F>a <0A><>ŕ<7F>(5h<35>+<<3C><>p7<>A<EFBFBD>z<EFBFBD><7A> <0C><>v<1E><18>U<> h5$<24>><3E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Z*<2A>dQ *<2A>\m<>XG<58><06>uj<75>4<EFBFBD>)2<><32><EFBFBD><52>ݥ/<2F><><EFBFBD><00><>z<EFBFBD><7A><EFBFBD>L<EFBFBD><4C><EFBFBD><EFBFBD><EFBFBD>9<EFBFBD><39><EFBFBD><EFBFBD><EFBFBD><EFBFBD>JO.Dk<>`<60>)<29>b<EFBFBD><62><1D><05>VA<56><41><EFBFBD><EFBFBD><10><><EFBFBD><EFBFBD>^+XxĜ<1C><><EFBFBD><EFBFBD>r<EFBFBD>
<1D>5|<7C><<3C>8<EFBFBD><0F><15>0<EFBFBD>8<EFBFBD><38>[<5B><><EFBFBD>9n<39><6E>,1/uLRV9Aރ9b<39><62><EFBFBD>L<EFBFBD>s]<5D><><EFBFBD><EFBFBD>KG<4B><47>ӆ<EFBFBD><D386><EFBFBD><!~L<>M<EFBFBD><4D><EFBFBD><EFBFBD><EFBFBD>"><3E><>.N.<-QV<><56><EFBFBD><0F> <0C>;<3B>%d<><64>{<7B>G<EFBFBD><47>}vA<><41><EFBFBD><EFBFBD>G<EFBFBD><01>ϾD%<25><01><EFBFBD><1C>T<EFBFBD><54><EFBFBD>1)zo<7A>O<EFBFBD>֋<7F>@"<22><><EFBFBD><EFBFBD>Ф<EFBFBD><D0A4><EFBFBD><EFBFBD><EFBFBD>ZHN2<>?w)8T:*ޤes1r"6sZ<73>H'.<2E> o^<5E><><1F>b<EFBFBD>M<EFBFBD>'Q<>u<00>d<EFBFBD>D!<21>l)ƈ<><C688>Q<02>`<60>@<40>c^[<5B><15>gS<67><53>J'<27>s=<3D><><1C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
(<28>oY/<2F><>A<EFBFBD><41>\@<40>ӵ<EFBFBD><D3B5>_ <09><><EFBFBD><EFBFBD>GT<47>G<EFBFBD>$,/<2F>Zz<5A><7A>\b<>'F<> <0A>f<EFBFBD><66><EFBFBD><EFBFBD>u<EFBFBD><75><EFBFBD>Z<14><><10><<3C><>2o<00>Ex|<7C><><EFBFBD>^<5E>;<3B><11>ȣTp<54><16><><EFBFBD><EFBFBD><EFBFBD>ϳl!{<02>Ji<4A>1<EFBFBD><1F><>q[h<><68><EFBFBD>s'he<68><65>~<7E>I6<49><36><EFBFBD>(<0E>a<EFBFBD><61> d<><64>G<EFBFBD>4<EFBFBD><13><><EFBFBD><EFBFBD>4<><05>V<EFBFBD>n)<29><><EFBFBD><EFBFBD>a0+<2B><><EFBFBD>l\ױi풛<69>r,f;<3B><><EFBFBD><05> X#<04><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>p<12><><EFBFBD><EFBFBD><30>C<18>!<21><>EyNVV&)<29><><EFBFBD><02>F<EFBFBD><46>S<EFBFBD><53><EFBFBD><EFBFBD> <0C><>iyL<79><4C><EFBFBD><EFBFBD>٘<EFBFBD><D998><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>K,d<>,T$<24>_s<5F><73><EFBFBD><EFBFBD> Σ<><CEA3>
<EFBFBD>p;Ӳ<>`<60>JC<10><>t<EFBFBD>IY <0C><>:<3A><>P%<>p[<5B>a=<3D><><EFBFBD>-<2D><13><><EFBFBD>&<26> ֘<>ҩ<EFBFBD><D2A9>֏<EFBFBD>kG<6B><47><EFBFBD>ЊU<D08A>#<23><>C5] <0B>[_U<5F><55><2<><32><EFBFBD><EFBFBD>1:/<2F>G<EFBFBD>N2<><08><> @S<><53>i<FD<46>VUU*<2A>U<EFBFBD><55><>_.<2E>m<EFBFBD><6D><EFBFBD>x<> <0C>Y%V<>Ë<04><>+<2B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <09>=<3D><><EFBFBD>K<EFBFBD>w><3E>\1<>l-<2D><>ҌZyIJ<79><C4B2>\<5C>i<EFBFBD>}<7D><>]<5D><>G=<3D><>kP<6B>\<5C><> <><E28BB0><EFBFBD><EFBFBD><EFBFBD>k <09><>lot<6F><74><EFBFBD><EFBFBD>\<5C><07>0 H<>}}[<5B><>t<EFBFBD><74><EFBFBD>4<EFBFBD>/<2F><><EFBFBD>,R=<3D>c-<2D>`%<25>]<5D>~<7E>7<EFBFBD>d<EFBFBD>S<EFBFBD><53>O<EFBFBD><4F>><3E><16><>τ%
<EFBFBD>¾<><C2BE>)<29><><EFBFBD>w<EFBFBD>E<0E><>Ӻ<>Cn<43>3<EFBFBD>$<24><10><><08><><EFBFBD>U#<23><><10>F<EFBFBD><46>%F<>f<11>MZr;<3B><>X<EFBFBD><04>=<3D>p}J<>Ρ<EFBFBD><CEA1><EFBFBD>b76Ra<52>؇<EFBFBD>'<03><><EFBFBD><EFBFBD><1F>sṡ<73><CC87>"<22><><EFBFBD><04>W'<27><><EFBFBD>e<EFBFBD><65>2<EFBFBD>ş<EFBFBD>BFڟ<46><DA9F><EFBFBD><EFBFBD><EFBFBD>><06>G<EFBFBD>YK7<4B>HTkj+2<1B>e<EFBFBD><65><EFBFBD><34><C4AE><EFBFBD>|<7C>e`B<><14>I.;Od<07><><EFBFBD> <0C><><EFBFBD>4<0E>/(,}<7D><>|MZ<18>><3E>c<EFBFBD>C|<7C>'<27>a<EFBFBD><<3C><>0]0=<3D><><13><>y<EFBFBD><79> <0C><><EFBFBD>J<EFBFBD>f<EFBFBD><18>u<EFBFBD>T,><3E><>`<60><><EFBFBD><EFBFBD>(Y<>*<2A>
<EFBFBD>8<13>(y8<19> &<1E>Ϥu<CFA4>ncm,ʾ<><CABE><EFBFBD>i<18><>I4(<28><><EFBFBD><EFBFBD>-<2D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>k<EFBFBD><6B><EFBFBD><EFBFBD>m<EFBFBD><6D><EFBFBD><<3C>/}<7D>-+g<>QHg峏d<E5B38F>d><3E> N<><4E><EFBFBD>"<22>$
<EFBFBD><EFBFBD><EFBFBD>1<><31><EFBFBD><EFBFBD>-3z<03>Px{<7B><>a<EFBFBD>P<EFBFBD><50><EFBFBD>4<EFBFBD>*<2A> <0A>nK<6E><4B>?g*<0F>X<><58>K<EFBFBD>&.]՜R{C<><43><EFBFBD><EFBFBD>_<>W2z<1C>m<EFBFBD>b,թ<><D5A9>#l i5c<1E><>0$<24>?<3F>.z=@<40>8N1<4E><31>{<08><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>|hu<68><75>>'<27>R@b(tWǩ<57><C7A9><EFBFBD>!<21><13>ďL0<>>1Z~<7E>rrŇ'<27> Z<><5A>I,<2C><>hc{2d<32><64><0F>J<EFBFBD>2g<32>;<3B><><EFBFBD>r<EFBFBD>1<><31>
_.Y
<EFBFBD>X<><58>)#6<08>j<EFBFBD>̇<EFBFBD><CC87>><3E>:<1A><><EFBFBD><EFBFBD>%<25><>!L <20><> P/Xu <0A>w<EFBFBD>G~<7E>K<EFBFBD><05><19><>|<7C><><EFBFBD>9.<2E><>D<EFBFBD>0<1C><><EFBFBD>2/<2F>U<EFBFBD>J<EFBFBD>6<EFBFBD>@<40><>g+<2B>^<5E><>li<6C><18>+<2B><>%<25>\z<><7A><EFBFBD>N<>q <0B>H<EFBFBD><48><EFBFBD>C0(<28><>)=<3D>^G<>[<5B><><EFBFBD>#<23><>L<EFBFBD>Q O<>|Uљ<15><>$<24>UǰH%<25>P<EFBFBD><50><EFBFBD><EFBFBD>a<EFBFBD><61><EFBFBD>گ<><DAAF>:⺘<><E2BA98>\_<><08>,<2C>Z<EFBFBD><53><DC9D><EFBFBD>S\<5C>g_V<5F><34>'Q?<3F>]<5D>D<EFBFBD><44><EFBFBD>ـs<EF94AB>e"m<>,<1F>b9<1E><08><><EFBFBD><EFBFBD>2<EFBFBD>4<EFBFBD><0F><>t<EFBFBD><74><EFBFBD>aYH<59><48><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>W<>wW<77><57><EFBFBD><EFBFBD>C<EFBFBD>&sTZ<>Q<EFBFBD><51>^Z&o^o%4_9~n3` E?<3F>,<2C><><EFBFBD>m<EFBFBD>t{J<>G<06>z<EFBFBD>q<EFBFBD>N<U<>%<25>3j<33>C<EFBFBD>:z<>/4<0F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>t^<5E>d<0F>w <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>}<7D><>k<EFBFBD><6B><00>K<EFBFBD>̏L<CC8F>,<2C>J<0F><>3<EFBFBD><33>rE含<45><E590AB>Z <20>ŏ<EFBFBD>],[smPB<50><1D>c<EFBFBD><12>)3>m#<>iKg"<22>K<EFBFBD>y<00>@W<><07>r<EFBFBD>L 8Y"<22>SP<53><50><56><CDAD><EFBFBD>u%<25><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/n<>
Ha<EFBFBD><EFBFBD>m<EFBFBD><EFBFBD>v<EFBFBD>+<2B>i<EFBFBD><69><EFBFBD>e<EFBFBD>9<>gq_<71><5F>b<EFBFBD>UIn<49><6E><EFBFBD>҇iI<69><49><08><><EFBFBD>=+<2B>+<02><14>q<EFBFBD>.<2E>ʫ<EFBFBD>^<5E><EFBFBD><7F>Cv<43><06>~<7E>xtIÚWӯ2<D3AF>?6<>)<29><><EFBFBD>IC<49>5v<35>W<EFBFBD>e=<3D>PM<50>Pi<0E><>s<>%{R<>zV<7A><56><EFBFBD>דGHW<48><57>Ns&<26><><EFBFBD>-<2D>y{<7B>ַy<D6B7><79>xA<78>[<5B><>zϻU<CFBB><55><EFBFBD> "<22><>g]"+b<><62> <20>\ <0B>wY=i<02>Y><3E>t<EFBFBD><74><EFBFBD>|<7C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1F><><<3C>#<23><>nn<6E><19>.<2E>n<EFBFBD><6E><EFBFBD><EFBFBD><EFBFBD>8<>%%xl<78>T<EFBFBD><<01>6DZ<44>Zο<><CEBF>M<EFBFBD>
ۿ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>@k<><6B>]<5D>&<26><>5J<35>b1JA<4A>f<> <09><>୪;<3B>3<EFBFBD>8<06><><EFBFBD><EFBFBD>G<1B>ٱA<D9B1>e<EFBFBD><65>ϰu{<7B><>-Y<><59><EFBFBD><EFBFBD><EFBFBD><EFBFBD> CZ<43>Jq<4A>(<28>C<06><53><CEAD><EFBFBD><00><><EFBFBD>yYg<59><67>1<EFBFBD><31><EFBFBD>TG<54> <0B>7! <0B>'<27><><EFBFBD>H<1A><><EFBFBD><17>b<ÕM<C395><4D><EFBFBD>=wc֞bmd<6D>B<EFBFBD><42>"<22><04><><EFBFBD><14>
<EFBFBD><EFBFBD><EFBFBD>x<EFBFBD>L(l<><1C>2\Y<>X<EFBFBD><58><EFBFBD>Ƭ<EFBFBD>M<EFBFBD>;<3B>(>ū<75><CC84> ػ<00><><B<><42><EFBFBD><05><>H<EFBFBD>Ε<EFBFBD>%a<61>ٞ<EFBFBD><D99E><EFBFBD><15><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"<22>^*B<><00>›<>_R2<03>p<EFBFBD>8<EFBFBD><38>s@<15><06>ݶV5<56>H<EFBFBD>hp-<2D>}i/<2F><>Np<4E>-v<><76><EFBFBD>:<3A>̬.<2E><><12><><EFBFBD>i<EFBFBD><69>2V<32><56><EFBFBD><1D>]<5D><><EFBFBD>mh,N<><4E><EFBFBD>ST<53>vɩ<76>s<EFBFBD><73><EFBFBD><EFBFBD><EFBFBD>^SUA<55>n1<6E>׆⦀<D786><E2A680><<3C>q<EFBFBD><71>M<1B><>f<EFBFBD><66><EFBFBD>T <0C>fv<66>%^|]<5D>[<5B><10> 5/]`<60><>_i<>.=x<>B<EFBFBD>y<EFBFBD><79><EFBFBD><EFBFBD><EFBFBD><EFBFBD>7<1B> v<>H<EFBFBD><48><EFBFBD>WD<00><>n <0A><><EFBFBD>H{ !<21><>Ϟ!<21><>o<EFBFBD><6F>&td+<2B>By"<22>^񕍱<><F1958DB1><EFBFBD>g<EFBFBD><67>'<27><><EFBFBD><EFBFBD>߸`<>f <0C><><EFBFBD>c<EFBFBD>i<EFBFBD>޲<EFBFBD>w"<22>c<EFBFBD><63>C{Z<><5A>x<EFBFBD><78>
<EFBFBD>Ǜw}<7D> V&<26><><EFBFBD><17>Vl<56>k0<6B>V<EFBFBD>"<22>u<>ݵӓ<DDB5><D393>*<2A>č!<12><>mp<>@`4<>*<2A><>I<EFBFBD>]_<><5F>R<EFBFBD>C<EFBFBD><43><EFBFBD>^V<>K<EFBFBD>眗}<7D><>z!RHP<48><50><EFBFBD>o<EFBFBD><6F><EFBFBD>+<12><1C>-AF7Yš<59><C5A1><EFBFBD>׵<EFBFBD><D7B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD>d <0C>EM<45>w/cSi<53>UKf됝<66>7m<37><15><>[<5B><><EFBFBD><1D><>R<EFBFBD>WQ<57><51>oA?DI<44>Ɨ<EFBFBD><C697>0<EFBFBD> <0C>Z<EFBFBD>m;<3B>(<28>
<EFBFBD><EFBFBD><EFBFBD>Cd<43>L<EFBFBD>_<19><><EFBFBD> <0C>7<EFBFBD><37> +<2B>2<EFBFBD>_^6c<02>o<EFBFBD>#FW<46>S<EFBFBD><53><EFBFBD>^
'<27>T^<5E>ӡ<EFBFBD><14><15>Q8<51>R<EFBFBD>8<EFBFBD>}$`<60><>m- <04>v⃭<76>o%<25><>?`Z<><14>P<EFBFBD>E<1E>Y<59><16>7<EFBFBD>S<EFBFBD><53>#><3E>`S <20>j!Ӊ<>}<02>!<11><>Đ<EFBFBD><C490>RK<52>Hv<48>ƶx<C6B6><78><19>L<EFBFBD><4C><EFBFBD><00><><1F><>#RX<52><58><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>$<24>IZ<49><1F><1E><><EFBFBD>!<21><><EFBFBD>=<3D>#<23><>n E
8\_6<><36>'0I5<49>h!<21><>q`b<>U{p<>=i<1E><>691<39><0E>l<19><03><>in<<3C>S<EFBFBD>O<EFBFBD>a<EFBFBD><61>|3N><3E>I<EFBFBD><49><EFBFBD>$<24>6<EFBFBD><36><EFBFBD>r<EFBFBD>Ɓg<C681>%4<><34><EFBFBD>#}#]<5D>$<24><><EFBFBD>Tx<54>6v<36><76><EFBFBD><EFBFBD>pX)<29>0<EFBFBD>]4x<34><78><EFBFBD>t$<24><1A> <09>_<EFBFBD>X<EFBFBD><58><EFBFBD>M)<29>C<EFBFBD><43><EFBFBD><EFBFBD>!<21><><16>ni<6E><69>?<3F><> ~S<1A>Na<4E>3-<2D><><EFBFBD>1<EFBFBD>*<2A>q.<2E><>d<EFBFBD>#<23>lU<><1C><>>,<2C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>*<2A><10>o?Y,<2C>?|N<>K<EFBFBD><4B>eI<65><49>|<7C><><EFBFBD>ռ<00>(m<><6D>T<EFBFBD><54>P<EFBFBD><50>7<EFBFBD><37>K<EFBFBD><4B><1D><><1F>Ҍf] *<2A><>I<EFBFBD>\3<>de<64><65>S:<3A><><f<>0<EFBFBD><30><EFBFBD>^<5E>EJ<45><4A>2Edz<><7A><EFBFBD>Ic<49>$<24><>z<><7A><EFBFBD> <0B>{<7B>,pt<04>@<40>8<EFBFBD><38>t8~o<>zm^<5E><><EFBFBD><EFBFBD><EFBFBD>)<29><>;0M8o<38><6F>U<EFBFBD>b<EFBFBD><62><EFBFBD>5@<40>ES<45>Φ<>Ao『<6F>m_<6D><5F>PS<50>P<><50><EFBFBD><EFBFBD>K@v<><76><15>a<EFBFBD>,RALV<4C>˳<EFBFBD>NG AC<41><43><EFBFBD><06><><EFBFBD><EFBFBD>a<>og<6F><67>|<7C><1E>9<EFBFBD>+<05><>gFL<46>Q<13>q<EFBFBD><71>Y<EFBFBD>#U<>O$<24><>Zo<5A><6F>D<EFBFBD><44><EFBFBD><1E> <16>{<7B>]Q<><51><EFBFBD><EFBFBD> <09>*<2A><1E><><><D19D><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>7a<><61><EFBFBD>5B<35>ùT;<3B><>lq<6C><71> <20>|o<><6F><EFBFBD><EFBFBD><EFBFBD><EFBFBD>x}<7D><><EFBFBD><EFBFBD><19><>y<EFBFBD>ljX<6A>ܽ1/<2F>b}<7D><>@<><11>TLY<4C>4<EFBFBD><34>a<><EA938B><EFBFBD><EFBFBD>!<21>Qb<>]^*~<7E>5H<35>h<EFBFBD>󈂌<EFBFBD><F388828C>Z<EFBFBD> q\<5C>qW<71><1E>x<02><><EFBFBD><EFBFBD>gSI1)L<><1C>9<EFBFBD><39>w<EFBFBD>X)b/)<29><>FC<46>}<7D><1C>M<EFBFBD><4D><EFBFBD><EFBFBD>چpD<70>^<5E>8,<2C>Ќ<EFBFBD> ><3E><>&t<>5<00><><EFBFBD>@<40><16><><EFBFBD><EFBFBD>q<EFBFBD>q;<3B> <20><><EFBFBD><04>Dik<69> G<>)<29>k
_;<3B><>8<EFBFBD><38>K,va<76><61><05>T<EFBFBD>p:<3A>?<3F>/<2F>bG^<5E>{8 x<><78><EFBFBD><EFBFBD><EFBFBD>D<EFBFBD>W<EFBFBD><57><EFBFBD><EFBFBD><EFBFBD>mV<6D><56><EFBFBD><EFBFBD><EFBFBD>\<5C><>0UAP<41><50><EFBFBD><EFBFBD><EFBFBD>V쨮F<>c<EFBFBD>}QAZ<41> )<29>L<0E>w<EFBFBD><77>Z<05><><EFBFBD><01>|<7C><>OGu<47>~EU<45><55>M<EFBFBD><4D><EFBFBD>{kG<6B>|8<><38>W<EFBFBD><57>͚\<5C><>xar!<21><>g<EFBFBD><67><EFBFBD>v8<76>VK
<EFBFBD><01><><EFBFBD>t<EFBFBD><74><EFBFBD>׻<EFBFBD><D7BB>a<EFBFBD>/<2F><07><>/h}Q<><51>?<3F><><03><>F@<40><> <0C><>;<1C>v<EFBFBD><76>:<06>o<EFBFBD><6F>v<EFBFBD><76><EFBFBD>Y<<3C>U-<2D><>e2<65>U$<24>+<2B><>G<EFBFBD><47><EFBFBD><08>0<15>i<EFBFBD><69>
3<EFBFBD><EFBFBD><EFBFBD>wb<77>'0:? a4<61> <1C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȯ<EFBFBD><C8AF><EFBFBD> <0C><><EFBFBD>p<EFBFBD><00>-Ğ:0<16><><EFBFBD>v<EFBFBD><76>w<EFBFBD>*<2A><>W(<28><><EFBFBD>*<2A> <15><>S<EFBFBD><17>b<EFBFBD><62><EFBFBD>C<EFBFBD> w<>l<EFBFBD> <20><><EFBFBD><01><>n'`,<2C><>V<EFBFBD>Kk<4B>ێxo0ߚ<30><DF9A><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD>z<EFBFBD><7A>G<EFBFBD>Ԕs<>Cq<43>(<28><><EFBFBD><1B><><EFBFBD><EFBFBD>P;<3B><> <0B>w<>8jv¾ʕi<CA95><>{&[P<><50>UPA<50>:K<>6<EFBFBD>{<7B><><EFBFBD><EFBFBD><<3C><EFBFBD>w܄ݠC<><43>ZQ<5A>o焾<6F><E784BE>%<25>H<EFBFBD><06>W<EFBFBD><57>/<06>+1S8<1B><><EFBFBD>?vs;}<7D>Z<><5A><EFBFBD><<3C><06><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1C><><EFBFBD><EFBFBD>L<EFBFBD><4C>=<3D>̹ .<2E>[<5B><><|7<><37><EFBFBD><EFBFBD>ߚ<EFBFBD><DF9A>wM:!X<1D>WY&Mޛh-<2D>i<EFBFBD>2pN<70><4E><EFBFBD>V<EFBFBD>Z<EFBFBD>"X<><58>Qi[<19><EFBFBD><EBAC84><EFBFBD><EFBFBD><EFBFBD><EFBFBD>2<EFBFBD><32><EFBFBD>3<>7<EFBFBD><37><EFBFBD><EFBFBD>۔<DB94><E4BD8F><EFBFBD><EFBFBD><EFBFBD>rH<72><48><EFBFBD>Q<EFBFBD>P<00><><EFBFBD>k;<3B>n<EFBFBD><6E><EFBFBD>9v<39>_0i<30>XN<>d@V<><56><EFBFBD>zi<00>w<EFBFBD>6<EFBFBD><02>~?{<01>g<EFBFBD> )<29><>#|C}/<2F>YC<59><18>l<EFBFBD>FS<46><05>5?<3F>2d|$<24>g<EFBFBD>2I<32>*<2A>]u<><75>0]<5D>l<EFBFBD><6C>Qzuk,<2C>"<1D><>B<>
"<22><>8\]4<>(#bw>{<7B>H<08><>S<EFBFBD>Y>o<>6<EFBFBD><36><EFBFBD>4w<34>l<EFBFBD><6C><EFBFBD>n<EFBFBD><6E><EFBFBD><EFBFBD>FC<46>Zbh<62>M<EFBFBD><4D>F<>;2E<32><45><EFBFBD>r<EFBFBD><EFBFBD><E299A4><EFBFBD>A<EFBFBD> ]<5D><><EFBFBD>Mk<4D>I=<3D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> h?O"<22>i<EFBFBD><69>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD><EFBFBD>n<EFBFBD><6E>vV؝<56>c>ЖBm<42>_ơu<6C><C5A8><EFBFBD>0<><30>O<EFBFBD>]<5D><><EFBFBD><EFBFBD> <20>(<28>d<EFBFBD>4?<3F>G<EFBFBD>s<EFBFBD>m<EFBFBD>Q<EFBFBD><51>#zM<7A>b8<62>6x^<5E>J<EFBFBD>d<1A><><0F>DY<44><59><EFBFBD><EFBFBD><EFBFBD>s<EFBFBD><73><EFBFBD>2P<32>[to<74>wY<77>:<3A><>)n]<16><><EFBFBD>&<26><><EFBFBD><04><>?]<5D><01> w<>}?<3F>Y<EFBFBD><59>g<EFBFBD>
̣fk<EFBFBD><EFBFBD><07>
<EFBFBD><EFBFBD>4<EFBFBD>}.<2E><02> <0A>yݠr<DDA0><72>h~m;?<3F><><EFBFBD><EFBFBD>ƴ㣰<C6B4>x<0F>j>Ɍ6<><36><EFBFBD><0E><>ጘƁ<E18C98>ue <20>Q<EFBFBD>z<EFBFBD>{t<><15>̂<EFBFBD><CC82>W<EFBFBD>'<27>"<22><>=<3D><>S?<3F><>bB<62><42><EFBFBD><EFBFBD>X<EFBFBD><58>Hn <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ep8<70>\<5C>0l<04>l<EFBFBD><6C><04><>8?^<14><>ԯ<EFBFBD><D4AF>l<EFBFBD><6C>z<EFBFBD><7A><EFBFBD><EFBFBD>^<5E><><EFBFBD><EFBFBD><1A>?<3F><11>p<05>8<EFBFBD>˪Ac<41>@<40>d<EFBFBD><64><01><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><0F><>ic@Iv<49><76>
#<23>7<EFBFBD>M<EFBFBD><4D><EFBFBD><7F><EFBFBD><EFBFBD>(<28>K<EFBFBD>kz<6B><7A>S<EFBFBD>`<60>B =<3D>F<EFBFBD><46>E<EFBFBD>ܲ56<35>}<7D>p<EFBFBD>I<><49>;<3B><1F><><13>L[P0`<60><>7[[<5B><><EFBFBD><EFBFBD><EFBFBD>LJ)<29><><EFBFBD>W<EFBFBD>A<EFBFBD>y<EFBFBD>a<EFBFBD><61><EFBFBD>_->s<>ؾUM<55><4D><EFBFBD><EFBFBD><EFBFBD>q<EFBFBD>e<EFBFBD><65><EFBFBD>
U<EFBFBD>W <20>r<EFBFBD><72><EFBFBD>9<EFBFBD><39><EFBFBD>X!c<><63><EFBFBD><EFBFBD>T#K<>b<EFBFBD> <20>P&CFh}<7D>%t\<5C>[3fe<66><65><><DB97><EFBFBD><EFBFBD>9ԝ4;&:߀TH<54><48><EFBFBD><EFBFBD><EFBFBD><EFBFBD>X1<58>8<EFBFBD>hK<68>zthp<14><01><><EFBFBD>E <09><>.<11>x<EFBFBD>itK<>]Vi<56>><3E>6<EFBFBD>1<EFBFBD><08><><EFBFBD>3V<33>ݵ<11><>I6<49>><3E><>&cB<63><42>7<08> <0C>d<07>H<EFBFBD>O<x<><78>(<28>6<EFBFBD>nC{k<>}<7D><><EFBFBD><EFBFBD>r<EFBFBD><72>kd<>t<EFBFBD><74>u,J<><<3C><><EFBFBD>|<7C><>4:><3E>`<60>E<EFBFBD><45><EFBFBD><EFBFBD>#qB<71>yb<79>-<2D><01><> 1<08><><EFBFBD><EFBFBD>g G<12><>ÿ<EFBFBD>n <09>w<EFBFBD>+/D<><44><EFBFBD>mӤLa1<61>iqAR<41>_ <0C>-c<><63><EFBFBD><00><><EFBFBD><EFBFBD><13><><EFBFBD><EFBFBD>C<EFBFBD>4<EFBFBD><34><"<22><>Uj<55>eD<65><EFBFBD>!7<>~<1D>]<5D>E<EFBFBD>ē<EFBFBD><C493><EFBFBD>a<EFBFBD>o{&4<><34><>G<EFBFBD><17>ҽ<EFBFBD>q<EFBFBD>y瑲<79>Z0|x<>pP<70>;<3B>S<EFBFBD><53><EFBFBD>]<5D>GI<47><19>C<EFBFBD>$
<EFBFBD>2<EFBFBD><EFBFBD><EFBFBD>X<EFBFBD><EFBFBD>l<EFBFBD>S<EFBFBD>4?Fv<><76><EFBFBD><01>֕-<Q<><51><EFBFBD>]<16>j9<1F>À<><C380>g<07>U<>'9<>y<EFBFBD>A<EFBFBD>n:n3<6E>O<EFBFBD><4F><EFBFBD> %<25>8<EFBFBD><1F> ?<1E>{#<23><><03>߫<EFBFBD>:>ۛ<><DB9B>҄<EFBFBD>u<EFBFBD><75><EFBFBD><EFBFBD><EFBFBD>;P<>'<27>x~<7E><>P<11><><EFBFBD>_gp<67>ƚ<EFBFBD>5<EFBFBD><35>X<EFBFBD><58><EFBFBD><EFBFBD><EFBFBD>1<><31><EFBFBD>}7<><37>me<6D>d_<17>><3E>f:<3A>v<EFBFBD><76><EFBFBD>Y<EFBFBD>J<><16>j<0F>Ǻ<EFBFBD><C7BA>R<EFBFBD><52><EFBFBD><06>Y<EFBFBD><59>m<EFBFBD> T<>P<><50><EFBFBD>u<EFBFBD>HN<48>fF<66><46><EFBFBD>i5<><E59D92>Zs<5A>)jxңD <0B>5<EFBFBD><35>̣6<CCA3><36><EFBFBD>E<EFBFBD>̇t<CC87>ϡ<EFBFBD><CFA1>3<EFBFBD>hvَ<76>0<EFBFBD>&<26><><EFBFBD><EFBFBD>ƅ<EFBFBD>a|<7C>[<5B>pE<70>#<23><><EFBFBD>UD!<21>h<EFBFBD>\<5C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Q<EFBFBD>T<EFBFBD>k<EFBFBD><6B><00> 4|<7C><><EFBFBD>K<><0F><><19>QHP<48><50><EFBFBD><EFBFBD><EFBFBD>W<EFBFBD>Ґ<EFBFBD>ؖ<15><><EFBFBD><EFBFBD>^{<7B>,aM<61>g;<3B><><EFBFBD><EFBFBD>b<EFBFBD><08>Y3<59><-<2D><><EFBFBD><EFBFBD>l<1E><>&AT<><54>t<EFBFBD><74><EFBFBD>Y/<2F><>B<EFBFBD><42><EFBFBD><EFBFBD>r[<5B>
uk<EFBFBD>\9<><39>Zn,<0E>hP<68>o!<21><1D><00>L<EFBFBD><4C><EFBFBD><EFBFBD><03><>9<EFBFBD><39>r <0C>q <0B><> |X\j<><6A><EFBFBD>,<2C><><EFBFBD><EFBFBD>|<7C><15>˳˦<CBB3>Bu<42>x?퉍<>1K<><4B>3$<11><><EFBFBD><EFBFBD><EFBFBD>L<EFBFBD>fr<66><72>B<EFBFBD><42>0*<2A><16>Oa<1D><><EFBFBD>S7<0E><>vK<76><4B>A'lD|T<><54><EFBFBD>A<EFBFBD><41>S<EFBFBD>0<EFBFBD><30>e%<25><><6A> <0B>A <0C><> l<><6C><EFBFBD><EFBFBD>;*\<5C>F<EFBFBD><46>j<03><><EFBFBD>:<3A><>Æz<C386><7A>ޚ<EFBFBD><DE9A>fh<><68>E<0F>tv<<3C>T@<40><>g X튣v-<2D>*<2A><><EFBFBD><EFBFBD>e><3E><00><>N<EFBFBD>M<><E5B797><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD>2!o<><6F><EFBFBD><EFBFBD><EFBFBD>t}ow<><77><EFBFBD><EFBFBD><EFBFBD><EFBFBD>y<12><>o<EFBFBD><<3C><08><>v<EFBFBD><76><EFBFBD>cލӐNѬ<4E>vAeDž<65>-,<1B>up<75><70>ӂ<EFBFBD>J% '<27>,<2C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>aƂr"<02>2<EFBFBD><1D>t&.<2E>U<11><>"#<23>|<7C><><EFBFBD><EFBFBD><11>ߛD<DF9B>7q<>r]Zilm8c<38><63>6{<7B>
b<EFBFBD><EFBFBD>Ѩ&]_<><5F><EFBFBD><EFBFBD>BԲBz<42><7A>T<EFBFBD>ӏ#<23>(<28>3=2L<32><4C>Y)<>g2N<32>%<25><>AO<41>1><3E><><EFBFBD><EFBFBD>&s1:5=H<><48>)<29><0E><><EFBFBD>Ā<EFBFBD>_|<7C><>
<EFBFBD>t<EFBFBD><EFBFBD>{fp5
y <0A>փ<EFBFBD>W<EFBFBD><57><1F> N<><4E><EFBFBD>c<EFBFBD>T<EFBFBD><54><EFBFBD><EFBFBD>?v7<76><16><>?<0F><>aE <0A>g~<7E><>։<37>9<EFBFBD>7<EFBFBD><37>*<2A><>,˅(3*5<>"u<>P.<2E>Nx<0F><>8\<5C><1C><><EFBFBD><EFBFBD>S_{<7B><><EFBFBD>JG<12><><EFBFBD><EFBFBD>m<EFBFBD>!<21><>H<EFBFBD>^<1D><>'#)m4WsTwI<77><49><EFBFBD>z<1E>x<EFBFBD>R<>F_p<5F>&<26><>,<2C><><16>\<5C>#<23>fjd<6A><03><><EFBFBD><EFBFBD>w<EFBFBD>VE<56>A<13>~
<EFBFBD>q"<22><><EFBFBD><EFBFBD>Rd3<08>b-9<0F><>$n<><6E><EFBFBD>X<EFBFBD>
^Y<><59><EFBFBD>ҝ<EFBFBD><D29D>US<55><53>[<5B><><EFBFBD>$wt<77>e<EFBFBD>ֹk<D6B9>zy0<79>W(5<><35><EFBFBD>f̋Y<CC8B><59><EFBFBD>:?Uժdy!~e`s<>C)<07>x{<05><><EFBFBD><EFBFBD>#+"<22><>y<EFBFBD>.<2E><><EFBFBD>}<7D>n"<22>k<EFBFBD><6B><EFBFBD>o<EFBFBD><6F>i<EFBFBD><69><EFBFBD><EFBFBD><EFBFBD>'<0F>%vLk<4C><10><>a|<01>~G<><47><EFBFBD>v<EFBFBD>T' <09>LC<4C><43>
<EFBFBD> <20>j(O<>d[<5B><><EFBFBD>Ed#7wn.R<>{v<>kE<> <0C><18>Lb<4C><62><EFBFBD>D<EFBFBD>Ђu<D082><75>Č<><C48C>4ֽ<>w{<7B><>+(%<25><> R1<52><31>h<EFBFBD>R<<3C><><10>g<EFBFBD>I+<2B>+o׉k<D789><,<2C><03><><EFBFBD><EFBFBD><EFBFBD>̚<EFBFBD><CC9A><EFBFBD>?<3F><>Vi<15><>u<EFBFBD><75><EFBFBD>Z#E<>g9<67><39>Gsj&<26><> <0C><08>A<EFBFBD>ܨh$m<><6D>j<EFBFBD>t<EFBFBD>6<EFBFBD><36>#y<><79><EFBFBD>v<11>N<17>><01>5<EFBFBD><35><4B>
Tm<EFBFBD>/<2F>U3<55><33><EFBFBD>h<EFBFBD>2<EFBFBD><32>x<EFBFBD><78>$E<13><>س_p<5F>e<1C>q<13>v<EFBFBD><76>uA<03> ]r <0C>|R<>q<EFBFBD>|<7C><><10>U} <20>8<EFBFBD><38><EFBFBD><EFBFBD><EFBFBD>i<EFBFBD> I<><49><EFBFBD> ۊ<><DB8A><EFBFBD><EFBFBD>FES<45><53>H<>f5<66>۟<EFBFBD><DB9F>]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>lW=6\!v8<76><38><EFBFBD><EFBFBD><04>B(<28><07>NF<><46>H<EFBFBD><1C>UN<55>$ <0A><>H*<2A><><EFBFBD>J<<3C><><1B>hS<68><53>;<3B>d<EFBFBD><64><EFBFBD><EFBFBD>1<EFBFBD><31><EFBFBD>C<EFBFBD>Q<EFBFBD>[<5B>*<2A>:}
<EFBFBD>d<><64><EFBFBD>nHI<48><49><EFBFBD>I<EFBFBD><19><><EFBFBD> <0A><>6 <0C><><EFBFBD><EFBFBD>br<62><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>97e0v<30>%hAB<41>4z<34><7A><EFBFBD>*~<7E>Ҙ<<3C>|V<>R<EFBFBD>ק<EFBFBD><D7A7>e.<2E>d5<64><35><EFBFBD><EFBFBD>Z<>Hn <0C><>S<10>BHLIn<49>du8<75><38>o<EFBFBD><6F>
<EFBFBD>><3E>-<2D><>4]~cQc<51>~Τʌ<CEA4> OQhhE<68><45><EFBFBD>x<EFBFBD>|<11>„ߵ{ؚrV<72><56><EFBFBD><EFBFBD><<3C>M<EFBFBD><4D>2<EFBFBD><32><EFBFBD><73><D498>?^<5E>j<EFBFBD><6A><EFBFBD>Z<EFBFBD><5A>\J$<24>@Y<><59>b<EFBFBD>w0m[<5B> Y8<59>h<EFBFBD><68><EFBFBD><EFBFBD><EFBFBD>;<3B> V<>?<3F><>G<EFBFBD><47>E"7<>oM->݆<><1D>j[&<26>틶ɻ w<><77>~ <09>+o<><6F>R"m<><6D>y<EFBFBD><79>,<2C>4<EFBFBD>Q<EFBFBD> <0A>i<EFBFBD>\<5C><1C>3<1A><>)<29>3b<33><62><08><1B>UK<08><><EFBFBD><EFBFBD>q<EFBFBD>Z-<2D>A4=<3D>ҫ<EFBFBD><D2AB>3<EFBFBD><33>p<EFBFBD><70><EFBFBD>\<11>B<EFBFBD><42>=)/I<><49><EFBFBD>}<7D><><EFBFBD><EFBFBD><EFBFBD>??Z<15>\<5C><><EFBFBD><EFBFBD>-<2D><EFBFBD><E28682>J<EFBFBD>L<15>W<EFBFBD>#<23>;<3B><>՗Dmuu[<5B>1<EFBFBD>Х<EFBFBD><D0A5><EFBFBD>|<7C><><EFBFBD><EFBFBD><EFBFBD>]<5D><><EFBFBD><EFBFBD>v<EFBFBD><76>Hq'WL<0E><>mm<6D>&<26>{3<><33>`<60> =a= $_<>1<EFBFBD>O<EFBFBD>?<3F><> T<><54><EFBFBD>+I<><49>2&<26><>><3E>ђb<D192><62>O-ާv_4p%<25><>^F<><46><EFBFBD>7<EFBFBD><37><EFBFBD>V<>Y<EFBFBD><59><EFBFBD>1z<31> <0C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>B><3E>Uf ]<5D>8<EFBFBD><38><EFBFBD>"<22><>=<07><><EFBFBD><EFBFBD>S<EFBFBD><53><EFBFBD>t<EFBFBD><74>O<EFBFBD>s v<><76>Ce<43>n<EFBFBD><08>H<EFBFBD><48>{<0E>0<><19><><EFBFBD><10>ʲ<EFBFBD><CAB2><EFBFBD>]<5D><>xܛ<19> <0B><<3C> <0A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>&<26>~<7E><>k<15>R<EFBFBD><0F>5<EFBFBD><35><EFBFBD><EFBFBD><EFBFBD><EFBFBD><0E>ß<EFBFBD> <17><><EFBFBD>L<EFBFBD><18>_V<5F>2<EFBFBD>ܡ<EFBFBD>X<EFBFBD>~Ww\<5C>Z8<>8<EFBFBD>]<5D>i<EFBFBD>]<5D><><EFBFBD>L<EFBFBD>K<EFBFBD>1I<31>h<EFBFBD><68>f<EFBFBD><66><EFBFBD><1F><>L)<29><><01>Pv
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>6<EFBFBD>m<EFBFBD><11>ِH<D990>ڤ<EFBFBD>-k,e/6֚<36><D69A>c<EFBFBD>k<EFBFBD><6B>cX<06>U<1B><><EFBFBD>bY2<59>+r$<24> )]<1C>d!?*%"J<>dH<64>9<EFBFBD><39><EFBFBD><EFBFBD>4`O<05><><EFBFBD><EFBFBD><EFBFBD>6<EFBFBD><36><58>+<2B>#<03>mʼ |W <20>(<28>ɖ,2<><32><19> <0B><><EFBFBD>펴dK<64>.{<7B><><EFBFBD>"P<><50><EFBFBD>J*<1E><03>8vO{)<29>t<EFBFBD><74>զ<EFBFBD>I<EFBFBD>Μv<CE9C><76><EFBFBD><EFBFBD><EFBFBD><EFBFBD>[<5B><>@<40>@<40><><EFBFBD>9<EFBFBD><39><EFBFBD>8T<>婟5<E5A99F> <0C>-<2D>`"_<><5F>b<EFBFBD>+P <20><>A<EFBFBD><EFBFBD>Y<EFBFBD><15><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>B'ٯT<07>FU]<5D><><EFBFBD> <0C><>9<EFBFBD><39>Tb><3E>I Ze?<3F>KN<4B>U<EFBFBD>We4<65>P5Q<15><><EFBFBD>{j<>gB<67>k<EFBFBD><6B><EFBFBD><EFBFBD>0U[$?<3F><>8<00>";<3B><07> <09><><EFBFBD><EFBFBD><EFBFBD>j<EFBFBD>W<EFBFBD><57><EFBFBD>h"<22>%K*<2A><>2<EFBFBD><32> <0C><>?<><7F>T<EFBFBD>70<0F><><05><>X<EFBFBD>Cp<43>eJ<65><4A>T<EFBFBD><54>%y<>j<EFBFBD>D<EFBFBD>ϡ<EFBFBD>q<19>;<3B><>eJ<65><02><>!<21>΅<EFBFBD><CE85>L<EFBFBD>Y <09>s<EFBFBD>JO<4A><4F>6m<36><6D>+]<5D><>X<EFBFBD><58><EFBFBD>ڤmf<1C>i<EFBFBD><69><EFBFBD><07>m<EFBFBD>ʀs's!>'7贼<37><E8B4BC><EFBFBD>t]<5D><><EFBFBD>ַ<17>1H<14><15>yW5%<25>DS^:<3A>A&<26>TI<><49>_ZnO<6E><EFBFBD><7F>ۏږ'<27><>b<EFBFBD><62>j)<29>S<EFBFBD>?<3F>̵<EFBFBD><CCB5> <0B><><EFBFBD>0<06>|*~6<><36><EFBFBD>]<08><><EFBFBD>/]JS<4A>.<2E>28<>cb:<3A>hRT<52>%o<>lh<6C><68><EFBFBD>H,YՒ<59>e<EFBFBD><63>`<60><><EFBFBD>7<02><>
M<EFBFBD>F <0B>4<EFBFBD>5<EFBFBD><35><EFBFBD>x<EFBFBD>ڧ|Zk<5A>n<EFBFBD>E<EFBFBD><45>l{ Y}K<> <0C>ˇ<EFBFBD>w<EFBFBD>S<EFBFBD><53>X/@<40>]*<2A><>j<><6A><EFBFBD>i0<69><30><EFBFBD><EFBFBD><18><><D08B>!<21>A]Y<>6<><36><EFBFBD><01><>XϪƘu<C698><75><EFBFBD> Z<><5A><EFBFBD> <00><><EFBFBD><EFBFBD><EFBFBD>%<06><><1C><>&k*<2A><><EFBFBD>1<EFBFBD>#F<><46>Q<EFBFBD>e<EFBFBD><65>|<7C><>Kn16A<36>j<EFBFBD>\<5C>|<7C>[<>^<5E><><1F>G<EFBFBD><47>T<16>U<EFBFBD><55><EFBFBD><EFBFBD>= j<1E><><EFBFBD><EFBFBD>xj<78>b2<62><32>t<EFBFBD>u<EFBFBD>=<3D><1F><>T+<2B>b<EFBFBD><62>9ċy<C48B><79>^<16><><EFBFBD><1D><1F><><EFBFBD><EFBFBD>|<7C><><1F><>@<40>[zr<7A>-<2D><><EFBFBD><EFBFBD>̏h<CC8F><06><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>f<EFBFBD><66>48<34>*vL<76><4C>Z7<5A>y<EFBFBD> <0B>Kt<4B> <>'F<><1A><>Z[const allDescriptors=[];let applicationDescriptor;const _loadedScripts={};for(const k of[]){}
(function(){const baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();const REMOTE_MODULE_FALLBACK_REVISION='@010ddcfda246975d194964ccf20038ebbdec6084';var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(let i=0;i<descriptors.length;++i)
this._registerModule(descriptors[i]);}
static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){const xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE)
return;const status=/^HTTP\/1.1 404/.test(e.target.response)?404:xhr.status;if([0,200,304].indexOf(status)===-1)
reject(new Error('While loading from url '+url+' server responded with a status of '+status));else
fulfill(e.target.response);}
xhr.send(null);}}
static loadResourcePromiseWithFallback(url){return Runtime.loadResourcePromise(url).catch(err=>{const urlWithFallbackVersion=url.replace(/@[0-9a-f]{40}/,REMOTE_MODULE_FALLBACK_REVISION);if(urlWithFallbackVersion===url||!url.includes('audits2_worker_module'))
throw err;return Runtime.loadResourcePromise(urlWithFallbackVersion);});}
static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1)
return path;const normalizedSegments=[];const segments=path.split('/');for(let i=0;i<segments.length;i++){const segment=segments[i];if(segment==='.')
continue;else if(segment==='..')
normalizedSegments.pop();else if(segment)
normalizedSegments.push(segment);}
let normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/')
return normalizedPath;if(path[0]==='/'&&normalizedPath)
normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..'))
normalizedPath=normalizedPath+'/';return normalizedPath;}
static _loadScriptsPromise(scriptNames,base){const promises=[];const urls=[];const sources=new Array(scriptNames.length);let scriptToEval=0;for(let i=0;i<scriptNames.length;++i){const scriptName=scriptNames[i];let sourceURL=(base||self._importScriptPathPrefix)+scriptName;const schemaIndex=sourceURL.indexOf('://')+3;let pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1)
pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL])
continue;urls.push(sourceURL);const loadResourcePromise=base?Runtime.loadResourcePromiseWithFallback(sourceURL):Runtime.loadResourcePromise(sourceURL);promises.push(loadResourcePromise.then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));}
return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}}
function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;}
self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}}
static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;}
const sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}}
static async appStarted(){return Runtime._appStartedPromise;}
static async startApplication(appName){console.timeStamp('Runtime.startApplication');const allDescriptorsByName={};for(let i=0;i<allDescriptors.length;++i){const d=allDescriptors[i];allDescriptorsByName[d['name']]=d;}
if(!applicationDescriptor){let data=await Runtime.loadResourcePromise(appName+'.json');applicationDescriptor=JSON.parse(data);let descriptor=applicationDescriptor;while(descriptor.extends){data=await Runtime.loadResourcePromise(descriptor.extends+'.json');descriptor=JSON.parse(data);applicationDescriptor.modules=descriptor.modules.concat(applicationDescriptor.modules);}}
const configuration=applicationDescriptor.modules;const moduleJSONPromises=[];const coreModuleNames=[];for(let i=0;i<configuration.length;++i){const descriptor=configuration[i];const name=descriptor['name'];const moduleJSON=allDescriptorsByName[name];if(moduleJSON)
moduleJSONPromises.push(Promise.resolve(moduleJSON));else
moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart')
coreModuleNames.push(name);}
const moduleDescriptors=await Promise.all(moduleJSONPromises);for(let i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';}
self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames)
await self.runtime._loadAutoStartModules(coreModuleNames);Runtime._appStartedPromiseCallback();}
static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}}
static queryParam(name){return Runtime._queryParamsObject.get(name);}
static queryParamsString(){return location.search;}
static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}}
static _assert(value,message){if(value)
return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);}
static setPlatform(platform){Runtime._platform=platform;}
static _isDescriptorEnabled(descriptor){const activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*')
return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1)))
return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment))
return false;const condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition))
return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1)))
return false;return true;}
static resolveSourceURL(path){let sourceURL=self.location.href;if(self.location.search)
sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';}
static setL10nCallback(localizationFunction){Runtime._l10nCallback=localizationFunction;}
useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend'))
Runtime._remoteBase+='debug/';}
_registerModule(descriptor){const module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;}
loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();}
_loadAutoStartModules(moduleNames){const promises=[];for(let i=0;i<moduleNames.length;++i)
promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);}
_checkExtensionApplicability(extension,predicate){if(!predicate)
return false;const contextTypes=extension.descriptor().contextTypes;if(!contextTypes)
return true;for(let i=0;i<contextTypes.length;++i){const contextType=this._resolve(contextTypes[i]);const isMatching=!!contextType&&predicate(contextType);if(isMatching)
return true;}
return false;}
isExtensionApplicableToContext(extension,context){if(!context)
return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}}
isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes)
return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}}
extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type)
return false;if(!extension.enabled())
return false;return!context||extension.isApplicable(context);}
function orderComparator(extension1,extension2){const order1=extension1.descriptor()['order']||0;const order2=extension2.descriptor()['order']||0;return order1-order2;}
function titleComparator(extension1,extension2){const title1=extension1.title()||'';const title2=extension2.title()||'';return title1.localeCompare(title2);}}
extension(type,context){return this.extensions(type,context)[0]||null;}
allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));}
_resolve(typeName){if(!this._cachedTypeClasses[typeName]){const path=typeName.split('.');let object=self;for(let i=0;object&&(i<path.length);++i)
object=object[path[i]];if(object)
this._cachedTypeClasses[typeName]=(object);}
return this._cachedTypeClasses[typeName]||null;}
sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction&&Object.getOwnPropertySymbols(constructorFunction).includes(Runtime._instanceSymbol))
return constructorFunction[Runtime._instanceSymbol];const instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject=new URLSearchParams(Runtime.queryParamsString());Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();const extensions=(descriptor.extensions);for(let i=0;extensions&&i<extensions.length;++i){const extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);}
this._loadedForTest=false;}
name(){return this._name;}
enabled(){return Runtime._isDescriptorEnabled(this._descriptor);}
resource(name){const fullName=this._name+'/'+name;const content=Runtime.cachedResources[fullName];if(!content)
throw new Error(fullName+' not preloaded. Check module.json');return content;}
_loadPromise(){if(!this.enabled())
return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise)
return this._pendingLoadPromise;const dependencies=this._descriptor.dependencies;const dependencyPromises=[];for(let i=0;dependencies&&i<dependencies.length;++i)
dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;}
_loadResources(){const resources=this._descriptor['resources'];if(!resources||!resources.length)
return Promise.resolve();const promises=[];for(let i=0;i<resources.length;++i){const url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));}
return Promise.all(promises).then(undefined);}
_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length)
return Promise.resolve();const specialCases={'sdk':'SDK','js_sdk':'JSSDK','browser_sdk':'BrowserSDK','ui':'UI','object_ui':'ObjectUI','javascript_metadata':'JavaScriptMetadata','perf_ui':'PerfUI','har_importer':'HARImporter','sdk_test_runner':'SDKTestRunner','cpu_profiler_test_runner':'CPUProfilerTestRunner'};const namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());}
_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);}
_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;}
substituteURL(value){const base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;}
descriptor(){return this._descriptor;}
module(){return this._module;}
enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());}
_typeClass(){if(!this._hasTypeClass)
return null;return this._module._manager._resolve(this._type.substring(1));}
isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);}
instance(){return this._module._loadPromise().then(this._createInstance.bind(this));}
canInstantiate(){return!!(this._className||this._factoryName);}
_createInstance(){const className=this._className||this._factoryName;if(!className)
throw new Error('Could not instantiate extension with no class');const constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function))
throw new Error('Could not instantiate: '+className);if(this._className)
return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);}
title(){const title=this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];if(title&&Runtime._l10nCallback)
return Runtime._l10nCallback(title);return title;}
hasContextType(contextType){const contextTypes=this.descriptor().contextTypes;if(!contextTypes)
return false;for(let i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i]))
return true;}
return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
allConfigurableExperiments(){const result=[];for(let i=0;i<this._experiments.length;i++){const experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name])
result.push(experiment);}
return result;}
supportEnabled(){return this._supportEnabled;}
_setExperimentsSetting(value){if(!self.localStorage)
return;self.localStorage['experiments']=JSON.stringify(value);}
register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));}
isEnabled(experimentName){this._checkExperiment(experimentName);if(Runtime._experimentsSetting()[experimentName]===false)
return false;if(this._enabledTransiently[experimentName])
return true;if(!this.supportEnabled())
return false;return!!Runtime._experimentsSetting()[experimentName];}
setEnabled(experimentName,enabled){this._checkExperiment(experimentName);const experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);}
setDefaultExperiments(experimentNames){for(let i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}}
enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;}
clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
cleanUpStaleExperiments(){const experimentsSetting=Runtime._experimentsSetting();const cleanedUpExperimentSetting={};for(let i=0;i<this._experiments.length;++i){const experimentName=this._experiments[i].name;if(experimentsSetting[experimentName])
cleanedUpExperimentSetting[experimentName]=true;}
this._setExperimentsSetting(cleanedUpExperimentSetting);}
_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;}
isEnabled(){return this._experiments.isEnabled(this.name);}
setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._appStartedPromiseCallback;Runtime._appStartedPromise=new Promise(fulfil=>Runtime._appStartedPromiseCallback=fulfil);Runtime._l10nCallback;Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){const versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch)
Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){}
ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;allDescriptors.push(...[{"skip_compilation":["lighthouse/lighthouse-dt-bundle.js"],"dependencies":["worker_service"],"extensions":[{"factoryName":"Audits2Service","type":"@Service","name":"Audits2Service"}],"name":"audits2_worker","scripts":["audits2_worker_module.js"]},{"name":"worker_service"}]);applicationDescriptor={"has_html":false,"modules":[{"type":"remote","name":"audits2_worker"},{"type":"autostart","name":"worker_service"}]}
self['WorkerService']=self['WorkerService']||{};function Service(){}
Service.prototype={dispose(){},setNotify(notify){}};ServiceDispatcher=class{constructor(port){this._objects=new Map();this._lastObjectId=1;this._port=port;this._port.setHandlers(this._dispatchMessageWrapped.bind(this),this._connectionClosed.bind(this));}
_dispatchMessageWrapped(data){let message;try{message=JSON.parse(data);if(!(message instanceof Object)){this._sendErrorResponse(message['id'],'Malformed message');return;}
this._dispatchMessage(message);}catch(e){this._sendErrorResponse(message?message['id']:'',e.toString()+' '+e.stack);}}
_dispatchMessage(message){const domainAndMethod=message['method'].split('.');const serviceName=domainAndMethod[0];const method=domainAndMethod[1];if(method==='create'){const extensions=self.runtime.extensions(Service).filter(extension=>extension.descriptor()['name']===serviceName);if(!extensions.length){this._sendErrorResponse(message['id'],'Could not resolve service \''+serviceName+'\'');return;}
extensions[0].instance().then(object=>{const id=String(this._lastObjectId++);object.setNotify(this._notify.bind(this,id,serviceName));this._objects.set(id,object);this._sendResponse(message['id'],{id:id});});}else if(method==='dispose'){const object=this._objects.get(message['params']['id']);if(!object){console.error('Could not look up object with id for '+JSON.stringify(message));return;}
this._objects.delete(message['params']['id']);object.dispose().then(()=>this._sendResponse(message['id'],{}));}else{if(!message['params']){console.error('No params in the message: '+JSON.stringify(message));return;}
const object=this._objects.get(message['params']['id']);if(!object){console.error('Could not look up object with id for '+JSON.stringify(message));return;}
const handler=object[method];if(!(handler instanceof Function)){console.error('Handler for \''+method+'\' is missing.');return;}
object[method](message['params']).then(result=>this._sendResponse(message['id'],result));}}
_connectionClosed(){for(const object of this._objects.values())
object.dispose();this._objects.clear();}
_notify(objectId,serviceName,method,params){params['id']=objectId;const message={method:serviceName+'.'+method,params:params};this._port.send(JSON.stringify(message));}
_sendResponse(messageId,result){const message={id:messageId,result:result};this._port.send(JSON.stringify(message));}
_sendErrorResponse(messageId,error){const message={id:messageId,error:error};this._port.send(JSON.stringify(message));}};WorkerServicePort=class{constructor(port){this._port=port;this._port.onmessage=this._onMessage.bind(this);this._port.onerror=console.error;}
setHandlers(messageHandler,closeHandler){this._messageHandler=messageHandler;this._closeHandler=closeHandler;}
send(data){this._port.postMessage(data);return Promise.resolve();}
close(){return Promise.resolve();}
_onMessage(event){this._messageHandler(event.data);}};const dispatchers=[];const worker=(self);const servicePort=new WorkerServicePort((worker));dispatchers.push(new ServiceDispatcher(servicePort));;;;if(!self.Runtime)
self.importScripts('Runtime.js');Runtime.startWorker('audits2_worker');<!--
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
<meta name="referrer" content="no-referrer">
<script type="text/javascript" src="shell.js"></script>
<script type="text/javascript" src="devtools_app.js"></script>
<script>Runtime.startApplication('devtools_app');</script>
</head>
<body class="undocked" id="-blink-dev-tools"></body>
</html>
allDescriptors.push(...[{"dependencies":["ui","host"],"extensions":[{"title":"What's New","id":"release-note","className":"Help.ReleaseNoteView","location":"drawer-view","type":"view","order":1,"persistence":"closeable"},{"category":"Appearance","title":"Show What's New after each update","defaultValue":true,"settingName":"help.show-release-note","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show What's New after each update"},{"value":false,"title":"Do not show What's New after each update"}]},{"category":"Help","className":"Help.ReleaseNotesActionDelegate","type":"action","actionId":"help.release-notes","title":"Release notes"},{"order":10,"type":"context-menu-item","location":"mainMenuHelp/default","actionId":"help.release-notes"},{"className":"Help.HelpLateInitialization","type":"late-initialization"}],"name":"help","scripts":["help_module.js"]},{"dependencies":["elements"],"extensions":[{"title":"Accessibility","id":"accessibility.view","className":"Accessibility.AccessibilitySidebarView","location":"elements-sidebar","type":"view","order":10,"persistence":"permanent"}],"name":"accessibility","scripts":["accessibility_module.js"],"skip_compilation":["ARIAProperties.js"]},{"dependencies":["components","sdk","timeline_model","ui","perf_ui"],"name":"layer_viewer","scripts":["layer_viewer_module.js"]},{"dependencies":["ui","sdk","data_grid"],"name":"cookie_table","scripts":["cookie_table_module.js"]},{"dependencies":["emulation"],"extensions":[{"device":{"show-by-default":false,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 4","screen":{"horizontal":{"width":480,"height":320},"device-pixel-ratio":2,"vertical":{"width":320,"height":480}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53","type":"phone"},"type":"emulated-device"},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 5/SE","screen":{"horizontal":{"width":568,"outline":{"insets":{"top":25,"right":115,"bottom":28,"left":115},"image":"@url(iPhone5-landscape.svg)"},"height":320},"device-pixel-ratio":2,"vertical":{"width":320,"outline":{"insets":{"top":105,"right":25,"bottom":111,"left":29},"image":"@url(iPhone5-portrait.svg)"},"height":568}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1","type":"phone"},"type":"emulated-device","order":30},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 6/7/8","screen":{"horizontal":{"width":667,"outline":{"insets":{"top":28,"right":106,"bottom":28,"left":106},"image":"@url(iPhone6-landscape.svg)"},"height":375},"device-pixel-ratio":2,"vertical":{"width":375,"outline":{"insets":{"top":105,"right":28,"bottom":105,"left":28},"image":"@url(iPhone6-portrait.svg)"},"height":667}},"capabilities":["touch","mobile"],"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1","type":"phone"},"type":"emulated-device","order":31},{"device":{"show-by-default":true,"modes":[{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"vertical","title":"default"},{"insets":{"top":0,"right":0,"bottom":0,"left":0},"orientation":"horizontal","title":"default"}],"title":"iPhone 6/7/8 Plus","screen":{"horizontal":{"width":736,"outline":{"insets":{"top":29,"right":109,"bottom":27,"left":109},"imag
self['MobileThrottling']=self['MobileThrottling']||{};MobileThrottling.CPUThrottlingRates={NoThrottling:1,MidTierMobile:4,LowEndMobile:6,};MobileThrottling.Conditions;MobileThrottling.NoThrottlingConditions={title:SDK.NetworkManager.NoThrottlingConditions.title,description:Common.UIString('No throttling'),network:SDK.NetworkManager.NoThrottlingConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.NoThrottling,};MobileThrottling.OfflineConditions={title:SDK.NetworkManager.OfflineConditions.title,description:Common.UIString('No internet connectivity'),network:SDK.NetworkManager.OfflineConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.NoThrottling,};MobileThrottling.LowEndMobileConditions={title:Common.UIString('Low-end mobile'),description:Common.UIString('Slow 3G & 6x CPU slowdown'),network:SDK.NetworkManager.Slow3GConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.LowEndMobile,};MobileThrottling.MidTierMobileConditions={title:Common.UIString('Mid-tier mobile'),description:Common.UIString('Fast 3G & 4x CPU slowdown'),network:SDK.NetworkManager.Fast3GConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.MidTierMobile,};MobileThrottling.PlaceholderConditions;MobileThrottling.CustomConditions={title:Common.UIString('Custom'),description:Common.UIString('Check Network and Performance panels'),};MobileThrottling.NetworkThrottlingConditionsGroup;MobileThrottling.MobileThrottlingConditionsGroup;MobileThrottling.ConditionsList;MobileThrottling.mobilePresets=[MobileThrottling.MidTierMobileConditions,MobileThrottling.LowEndMobileConditions,MobileThrottling.CustomConditions];MobileThrottling.advancedMobilePresets=[MobileThrottling.OfflineConditions,];MobileThrottling.networkPresets=[SDK.NetworkManager.Fast3GConditions,SDK.NetworkManager.Slow3GConditions,SDK.NetworkManager.OfflineConditions,];MobileThrottling.cpuThrottlingPresets=[MobileThrottling.CPUThrottlingRates.NoThrottling,MobileThrottling.CPUThrottlingRates.MidTierMobile,MobileThrottling.CPUThrottlingRates.LowEndMobile,];;MobileThrottling.MobileThrottlingSelector=class{constructor(populateCallback,selectCallback){this._populateCallback=populateCallback;this._selectCallback=selectCallback;MobileThrottling.throttlingManager().addEventListener(MobileThrottling.ThrottlingManager.Events.RateChanged,this._conditionsChanged,this);SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,this._conditionsChanged,this);this._options=this._populateOptions();this._conditionsChanged();}
optionSelected(conditions){SDK.multitargetNetworkManager.setNetworkConditions(conditions.network);MobileThrottling.throttlingManager().setCPUThrottlingRate(conditions.cpuThrottlingRate);}
_populateOptions(){const disabledGroup={title:Common.UIString('Disabled'),items:[MobileThrottling.NoThrottlingConditions]};const presetsGroup={title:Common.UIString('Presets'),items:MobileThrottling.mobilePresets};const advancedGroup={title:Common.UIString('Advanced'),items:MobileThrottling.advancedMobilePresets};return this._populateCallback([disabledGroup,presetsGroup,advancedGroup]);}
_conditionsChanged(){const networkConditions=SDK.multitargetNetworkManager.networkConditions();const cpuThrottlingRate=MobileThrottling.throttlingManager().cpuThrottlingRate();for(let index=0;index<this._options.length;++index){const option=this._options[index];if(option&&option.network===networkConditions&&option.cpuThrottlingRate===cpuThrottlingRate){this._selectCallback(index);return;}}
this._selectCallback(this._options.indexOf(MobileThrottling.CustomConditions));}};;MobileThrottling.NetworkPanelIndicator=class{constructor(){if(!UI.inspectorView.hasPanel('network'))
return;const manager=SDK.multitargetNetworkManager;manager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,updateVisibility);manager.addEventListener(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged,updateVisibility);manager.addEventListener(SDK.MultitargetNetworkManager.Events.InterceptorsChanged,updateVisibility);updateVisibility();function updateVisibility(){let icon=null;if(manager.isThrottling()){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Network throttling is enabled');}else if(SDK.multitargetNetworkManager.isIntercepting()){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Requests may be rewritten by local overrides');}else if(manager.isBlocking()){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Requests may be blocked');}
UI.inspectorView.setPanelIcon('network',icon);}}};;MobileThrottling.NetworkThrottlingSelector=class{constructor(populateCallback,selectCallback,customNetworkConditionsSetting){this._populateCallback=populateCallback;this._selectCallback=selectCallback;this._customNetworkConditionsSetting=customNetworkConditionsSetting;this._customNetworkConditionsSetting.addChangeListener(this._populateOptions,this);SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,this._networkConditionsChanged,this);this._options;this._populateOptions();}
revealAndUpdate(){Common.Revealer.reveal(this._customNetworkConditionsSetting);this._networkConditionsChanged();}
optionSelected(conditions){SDK.multitargetNetworkManager.setNetworkConditions(conditions);}
_populateOptions(){const disabledGroup={title:Common.UIString('Disabled'),items:[SDK.NetworkManager.NoThrottlingConditions]};const presetsGroup={title:Common.UIString('Presets'),items:MobileThrottling.networkPresets};const customGroup={title:Common.UIString('Custom'),items:this._customNetworkConditionsSetting.get()};this._options=this._populateCallback([disabledGroup,presetsGroup,customGroup]);if(!this._networkConditionsChanged()){for(let i=this._options.length-1;i>=0;i--){if(this._options[i]){this.optionSelected((this._options[i]));break;}}}}
_networkConditionsChanged(){const value=SDK.multitargetNetworkManager.networkConditions();for(let index=0;index<this._options.length;++index){const option=this._options[index];if(option&&option.download===value.download&&option.upload===value.upload&&option.latency===value.latency&&option.title===value.title){this._selectCallback(index);return true;}}
return false;}};;MobileThrottling.ThrottlingSettingsTab=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('mobile_throttling/throttlingSettingsTab.css');this.contentElement.createChild('div','header').textContent=Common.UIString('Network Throttling Profiles');const addButton=UI.createTextButton(Common.UIString('Add custom profile...'),this._addButtonClicked.bind(this),'add-conditions-button');this.contentElement.appendChild(addButton);this._list=new UI.ListWidget(this);this._list.element.classList.add('conditions-list');this._list.registerRequiredCSS('mobile_throttling/throttlingSettingsTab.css');this._list.show(this.contentElement);this._customSetting=Common.moduleSetting('customNetworkConditions');this._customSetting.addChangeListener(this._conditionsUpdated,this);this.setDefaultFocusedElement(addButton);this.contentElement.tabIndex=0;}
wasShown(){super.wasShown();this._conditionsUpdated();}
_conditionsUpdated(){this._list.clear();const conditions=this._customSetting.get();for(let i=0;i<conditions.length;++i)
this._list.appendItem(conditions[i],true);this._list.appendSeparator();}
_addButtonClicked(){this._list.addNewItem(this._customSetting.get().length,{title:'',download:-1,upload:-1,latency:0});}
renderItem(item,editable){const conditions=(item);const element=createElementWithClass('div','conditions-list-item');const title=element.createChild('div','conditions-list-text conditions-list-title');const titleText=title.createChild('div','conditions-list-title-text');titleText.textContent=conditions.title;titleText.title=conditions.title;element.createChild('div','conditions-list-separator');element.createChild('div','conditions-list-text').textContent=MobileThrottling.throughputText(conditions.download);element.createChild('div','conditions-list-separator');element.createChild('div','conditions-list-text').textContent=MobileThrottling.throughputText(conditions.upload);element.createChild('div','conditions-list-separator');element.createChild('div','conditions-list-text').textContent=Common.UIString('%dms',conditions.latency);return element;}
removeItemRequested(item,index){const list=this._customSetting.get();list.splice(index,1);this._customSetting.set(list);}
commitEdit(item,editor,isNew){const conditions=(item);conditions.title=editor.control('title').value.trim();const download=editor.control('download').value.trim();conditions.download=download?parseInt(download,10)*(1024/8):-1;const upload=editor.control('upload').value.trim();conditions.upload=upload?parseInt(upload,10)*(1024/8):-1;const latency=editor.control('latency').value.trim();conditions.latency=latency?parseInt(latency,10):0;const list=this._customSetting.get();if(isNew)
list.push(conditions);this._customSetting.set(list);}
beginEdit(item){const conditions=(item);const editor=this._createEditor();editor.control('title').value=conditions.title;editor.control('download').value=conditions.download<=0?'':String(conditions.download/(1024/8));editor.control('upload').value=conditions.upload<=0?'':String(conditions.upload/(1024/8));editor.control('latency').value=conditions.latency?String(conditions.latency):'';return editor;}
_createEditor(){if(this._editor)
return this._editor;const editor=new UI.ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const titles=content.createChild('div','conditions-edit-row');titles.createChild('div','conditions-list-text conditions-list-title').textContent=Common.UIString('Profile Name');titles.createChild('div','conditions-list-separator conditions-list-separator-invisible');titles.createChild('div','conditions-list-text').textContent=Common.UIString('Download');titles.createChild('div','conditions-list-separator conditions-list-separator-invisible');titles.createChild('div','conditions-list-text').textContent=Common.UIString('Upload');titles.createChild('div','conditions-list-separator conditions-list-separator-invisible');titles.createChild('div','conditions-list-text').textContent=Common.UIString('Latency');const fields=content.createChild('div','conditions-edit-row');fields.createChild('div','conditions-list-text conditions-list-title').appendChild(editor.createInput('title','text','',titleValidator));fields.createChild('div','conditions-list-separator conditions-list-separator-invisible');let cell=fields.createChild('div','conditions-list-text');cell.appendChild(editor.createInput('download','text',Common.UIString('kb/s'),throughputValidator));cell.createChild('div','conditions-edit-optional').textContent=Common.UIString('optional');fields.createChild('div','conditions-list-separator conditions-list-separator-invisible');cell=fields.createChild('div','conditions-list-text');cell.appendChild(editor.createInput('upload','text',Common.UIString('kb/s'),throughputValidator));cell.createChild('div','conditions-edit-optional').textContent=Common.UIString('optional');fields.createChild('div','conditions-list-separator conditions-list-separator-invisible');cell=fields.createChild('div','conditions-list-text');cell.appendChild(editor.createInput('latency','text',Common.UIString('ms'),latencyValidator));cell.createChild('div','conditions-edit-optional').textContent=Common.UIString('optional');return editor;function titleValidator(item,index,input){const value=input.value.trim();return value.length>0&&value.length<50;}
function throughputValidator(item,index,input){const value=input.value.trim();return!value||(/^[\d]+(\.\d+)?|\.\d+$/.test(value)&&value>=0&&value<=10000000);}
function latencyValidator(item,index,input){const value=input.value.trim();return!value||(/^[\d]+$/.test(value)&&value>=0&&value<=1000000);}}};MobileThrottling.throughputText=function(throughput,plainText){if(throughput<0)
return'';const throughputInKbps=throughput/(1024/8);const delimiter=plainText?'':' ';if(throughputInKbps<1024)
return Common.UIString('%d%skb/s',throughputInKbps,delimiter);if(throughputInKbps<1024*10)
return Common.UIString('%.1f%sMb/s',throughputInKbps/1024,delimiter);return Common.UIString('%d%sMb/s',(throughputInKbps/1024)|0,delimiter);};;MobileThrottling.ThrottlingManager=class extends Common.Object{constructor(){super();this._cpuThrottlingRate=MobileThrottling.CPUThrottlingRates.NoThrottling;this._cpuThrottlingControls=new Set();this._cpuThrottlingRates=MobileThrottling.cpuThrottlingPresets;this._customNetworkConditionsSetting=Common.moduleSetting('customNetworkConditions');this._currentNetworkThrottlingConditions=SDK.NetworkManager.NoThrottlingConditions;this._lastNetworkThrottlingConditions;SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,()=>{this._lastNetworkThrottlingConditions=this._currentNetworkThrottlingConditions;this._currentNetworkThrottlingConditions=SDK.multitargetNetworkManager.networkConditions();});SDK.targetManager.observeModels(SDK.EmulationModel,this);}
decorateSelectWithNetworkThrottling(selectElement){let options=[];const selector=new MobileThrottling.NetworkThrottlingSelector(populate,select,this._customNetworkConditionsSetting);selectElement.addEventListener('change',optionSelected,false);return selector;function populate(groups){selectElement.removeChildren();options=[];for(let i=0;i<groups.length;++i){const group=groups[i];const groupElement=selectElement.createChild('optgroup');groupElement.label=group.title;for(const conditions of group.items){const title=conditions.title;const option=new Option(title,title);groupElement.appendChild(option);options.push(conditions);}
if(i===groups.length-1){groupElement.appendChild(new Option(Common.UIString('Add\u2026'),Common.UIString('Add\u2026')));options.push(null);}}
return options;}
function optionSelected(){if(selectElement.selectedIndex===selectElement.options.length-1)
selector.revealAndUpdate();else
selector.optionSelected(options[selectElement.selectedIndex]);}
function select(index){if(selectElement.selectedIndex!==index)
selectElement.selectedIndex=index;}}
createOfflineToolbarCheckbox(){const checkbox=new UI.ToolbarCheckbox(Common.UIString('Offline'),Common.UIString('Force disconnected from network'),forceOffline.bind(this));SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,networkConditionsChanged);checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions()===SDK.NetworkManager.OfflineConditions);function forceOffline(){if(checkbox.checked())
SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);else
SDK.multitargetNetworkManager.setNetworkConditions(this._lastNetworkThrottlingConditions);}
function networkConditionsChanged(){checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions()===SDK.NetworkManager.OfflineConditions);}
return checkbox;}
createMobileThrottlingButton(){const button=new UI.ToolbarMenuButton(appendItems);button.setTitle(Common.UIString('Throttling'));button.setGlyph('');button.turnIntoSelect();button.setDarkText();let options=[];let selectedIndex=-1;const selector=new MobileThrottling.MobileThrottlingSelector(populate,select);return button;function appendItems(contextMenu){for(let index=0;index<options.length;++index){const conditions=options[index];if(!conditions)
continue;if(conditions.title===MobileThrottling.CustomConditions.title&&conditions.description===MobileThrottling.CustomConditions.description)
continue;contextMenu.defaultSection().appendCheckboxItem(Common.UIString(conditions.title),selector.optionSelected.bind(selector,(conditions)),selectedIndex===index);}}
function populate(groups){options=[];for(const group of groups){for(const conditions of group.items)
options.push(conditions);options.push(null);}
return options;}
function select(index){selectedIndex=index;button.setText(options[index].title);button.setTitle(options[index].description);}}
cpuThrottlingRate(){return this._cpuThrottlingRate;}
setCPUThrottlingRate(rate){this._cpuThrottlingRate=rate;for(const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate);let icon=null;if(this._cpuThrottlingRate!==MobileThrottling.CPUThrottlingRates.NoThrottling){Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuThrottlingEnabled);icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('CPU throttling is enabled');}
const index=this._cpuThrottlingRates.indexOf(this._cpuThrottlingRate);for(const control of this._cpuThrottlingControls)
control.setSelectedIndex(index);UI.inspectorView.setPanelIcon('timeline',icon);this.dispatchEventToListeners(MobileThrottling.ThrottlingManager.Events.RateChanged,this._cpuThrottlingRate);}
modelAdded(emulationModel){if(this._cpuThrottlingRate!==MobileThrottling.CPUThrottlingRates.NoThrottling)
emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate);}
modelRemoved(emulationModel){}
createCPUThrottlingSelector(){const control=new UI.ToolbarComboBox(event=>this.setCPUThrottlingRate(this._cpuThrottlingRates[event.target.selectedIndex]));this._cpuThrottlingControls.add(control);const currentRate=this._cpuThrottlingRate;for(let i=0;i<this._cpuThrottlingRates.length;++i){const rate=this._cpuThrottlingRates[i];const title=rate===1?Common.UIString('No throttling'):Common.UIString('%d\xD7 slowdown',rate);const option=control.createOption(title);control.addOption(option);if(currentRate===rate)
control.setSelectedIndex(i);}
return control;}};MobileThrottling.ThrottlingManager.Events={RateChanged:Symbol('RateChanged')};MobileThrottling.ThrottlingManager.ActionDelegate=class{handleAction(context,actionId){if(actionId==='network-conditions.network-online'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.NoThrottlingConditions);return true;}
if(actionId==='network-conditions.network-low-end-mobile'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.Slow3GConditions);return true;}
if(actionId==='network-conditions.network-mid-tier-mobile'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.Fast3GConditions);return true;}
if(actionId==='network-conditions.network-offline'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);return true;}
return false;}};MobileThrottling.throttlingManager=function(){return self.singleton(MobileThrottling.ThrottlingManager);};;self['Emulation']=self['Emulation']||{};Emulation.AdvancedApp=class{constructor(){Components.dockController.addEventListener(Components.DockController.Events.BeforeDockSideChanged,this._openToolboxWindow,this);}
static _instance(){if(!Emulation.AdvancedApp._appInstance)
Emulation.AdvancedApp._appInstance=new Emulation.AdvancedApp();return Emulation.AdvancedApp._appInstance;}
presentUI(document){const rootView=new UI.RootView();this._rootSplitWidget=new UI.SplitWidget(false,true,'InspectorView.splitViewState',555,300,true);this._rootSplitWidget.show(rootView.element);this._rootSplitWidget.setSidebarWidget(UI.inspectorView);this._rootSplitWidget.setDefaultFocusedChild(UI.inspectorView);UI.inspectorView.setOwnerSplit(this._rootSplitWidget);this._inspectedPagePlaceholder=Emulation.InspectedPagePlaceholder.instance();this._inspectedPagePlaceholder.addEventListener(Emulation.InspectedPagePlaceholder.Events.Update,this._onSetInspectedPageBounds.bind(this),this);this._deviceModeView=new Emulation.DeviceModeWrapper(this._inspectedPagePlaceholder);Components.dockController.addEventListener(Components.DockController.Events.BeforeDockSideChanged,this._onBeforeDockSideChange,this);Components.dockController.addEventListener(Components.DockController.Events.DockSideChanged,this._onDockSideChange,this);Components.dockController.addEventListener(Components.DockController.Events.AfterDockSideChanged,this._onAfterDockSideChange,this);this._onDockSideChange();console.timeStamp('AdvancedApp.attachToBody');rootView.attachToDocument(document);rootView.focus();this._inspectedPagePlaceholder.update();}
_openToolboxWindow(event){if((event.data.to)!==Components.DockController.State.Undocked)
return;if(this._toolboxWindow)
return;const url=window.location.href.replace('devtools_app.html','toolbox.html');this._toolboxWindow=window.open(url,undefined);}
toolboxLoaded(toolboxDocument){UI.initializeUIUtils(toolboxDocument,Common.settings.createSetting('uiTheme','default'));UI.installComponentRootStyles((toolboxDocument.body));UI.ContextMenu.installHandler(toolboxDocument);UI.Tooltip.installHandler(toolboxDocument);this._toolboxRootView=new UI.RootView();this._toolboxRootView.attachToDocument(toolboxDocument);this._updateDeviceModeView();}
_updateDeviceModeView(){if(this._isDocked())
this._rootSplitWidget.setMainWidget(this._deviceModeView);else if(this._toolboxRootView)
this._deviceModeView.show(this._toolboxRootView.element);}
_onBeforeDockSideChange(event){if((event.data.to)===Components.DockController.State.Undocked&&this._toolboxRootView){this._rootSplitWidget.hideSidebar();this._inspectedPagePlaceholder.update();}
this._changingDockSide=true;}
_onDockSideChange(event){this._updateDeviceModeView();const toDockSide=event?(event.data.to):Components.dockController.dockSide();if(toDockSide===Components.DockController.State.Undocked){this._updateForUndocked();}else if(this._toolboxRootView&&event&&(event.data.from)===Components.DockController.State.Undocked){this._rootSplitWidget.hideSidebar();}else{this._updateForDocked(toDockSide);}}
_onAfterDockSideChange(event){if(!this._changingDockSide)
return;if((event.data.from)===Components.DockController.State.Undocked){this._updateForDocked((event.data.to));}
this._changingDockSide=false;this._inspectedPagePlaceholder.update();}
_updateForDocked(dockSide){this._rootSplitWidget.resizerElement().style.transform=dockSide===Components.DockController.State.DockedToRight?'translateX(2px)':dockSide===Components.DockController.State.DockedToLeft?'translateX(-2px)':'';this._rootSplitWidget.setVertical(dockSide===Components.DockController.State.DockedToRight||dockSide===Components.DockController.State.DockedToLeft);this._rootSplitWidget.setSecondIsSidebar(dockSide===Components.DockController.State.DockedToRight||dockSide===Components.DockController.State.DockedToBottom);this._rootSplitWidget.toggleResizer(this._rootSplitWidget.resizerElement(),true);this._rootSplitWidget.toggleResizer(UI.inspectorView.topResizerElement(),dockSide===Components.DockController.State.DockedToBottom);this._rootSplitWidget.showBoth();}
_updateForUndocked(){this._rootSplitWidget.toggleResizer(this._rootSplitWidget.resizerElement(),false);this._rootSplitWidget.toggleResizer(UI.inspectorView.topResizerElement(),false);this._rootSplitWidget.hideMain();}
_isDocked(){return Components.dockController.dockSide()!==Components.DockController.State.Undocked;}
_onSetInspectedPageBounds(event){if(this._changingDockSide)
return;const window=this._inspectedPagePlaceholder.element.window();if(!window.innerWidth||!window.innerHeight)
return;if(!this._inspectedPagePlaceholder.isShowing())
return;const bounds=(event.data);console.timeStamp('AdvancedApp.setInspectedPageBounds');InspectorFrontendHost.setInspectedPageBounds(bounds);}};Emulation.AdvancedApp._appInstance;Emulation.AdvancedAppProvider=class{createApp(){return Emulation.AdvancedApp._instance();}};;Emulation.EmulatedDevice=class{constructor(){this.title='';this.type=Emulation.EmulatedDevice.Type.Unknown;this.vertical={width:0,height:0,outlineInsets:null,outlineImage:null};this.horizontal={width:0,height:0,outlineInsets:null,outlineImage:null};this.deviceScaleFactor=1;this.capabilities=[Emulation.EmulatedDevice.Capability.Touch,Emulation.EmulatedDevice.Capability.Mobile];this.userAgent='';this.modes=[];this._show=Emulation.EmulatedDevice._Show.Default;this._showByDefault=true;this._extension=null;}
static fromJSONV1(json){try{function parseValue(object,key,type,defaultValue){if(typeof object!=='object'||object===null||!object.hasOwnProperty(key)){if(typeof defaultValue!=='undefined')
return defaultValue;throw new Error('Emulated device is missing required property \''+key+'\'');}
const value=object[key];if(typeof value!==type||value===null)
throw new Error('Emulated device property \''+key+'\' has wrong type \''+typeof value+'\'');return value;}
function parseIntValue(object,key){const value=(parseValue(object,key,'number'));if(value!==Math.abs(value))
throw new Error('Emulated device value \''+key+'\' must be integer');return value;}
function parseInsets(json){return new UI.Insets(parseIntValue(json,'left'),parseIntValue(json,'top'),parseIntValue(json,'right'),parseIntValue(json,'bottom'));}
function parseOrientation(json){const result={};result.width=parseIntValue(json,'width');if(result.width<0||result.width>Emulation.DeviceModeModel.MaxDeviceSize||result.width<Emulation.DeviceModeModel.MinDeviceSize)
throw new Error('Emulated device has wrong width: '+result.width);result.height=parseIntValue(json,'height');if(result.height<0||result.height>Emulation.DeviceModeModel.MaxDeviceSize||result.height<Emulation.DeviceModeModel.MinDeviceSize)
throw new Error('Emulated device has wrong height: '+result.height);const outlineInsets=parseValue(json['outline'],'insets','object',null);if(outlineInsets){result.outlineInsets=parseInsets(outlineInsets);if(result.outlineInsets.left<0||result.outlineInsets.top<0)
throw new Error('Emulated device has wrong outline insets');result.outlineImage=(parseValue(json['outline'],'image','string'));}
return(result);}
const result=new Emulation.EmulatedDevice();result.title=(parseValue(json,'title','string'));result.type=(parseValue(json,'type','string'));const rawUserAgent=(parseValue(json,'user-agent','string'));result.userAgent=SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(rawUserAgent);const capabilities=parseValue(json,'capabilities','object',[]);if(!Array.isArray(capabilities))
throw new Error('Emulated device capabilities must be an array');result.capabilities=[];for(let i=0;i<capabilities.length;++i){if(typeof capabilities[i]!=='string')
throw new Error('Emulated device capability must be a string');result.capabilities.push(capabilities[i]);}
result.deviceScaleFactor=(parseValue(json['screen'],'device-pixel-ratio','number'));if(result.deviceScaleFactor<0||result.deviceScaleFactor>100)
throw new Error('Emulated device has wrong deviceScaleFactor: '+result.deviceScaleFactor);result.vertical=parseOrientation(parseValue(json['screen'],'vertical','object'));result.horizontal=parseOrientation(parseValue(json['screen'],'horizontal','object'));const modes=parseValue(json,'modes','object',[]);if(!Array.isArray(modes))
throw new Error('Emulated device modes must be an array');result.modes=[];for(let i=0;i<modes.length;++i){const mode={};mode.title=(parseValue(modes[i],'title','string'));mode.orientation=(parseValue(modes[i],'orientation','string'));if(mode.orientation!==Emulation.EmulatedDevice.Vertical&&mode.orientation!==Emulation.EmulatedDevice.Horizontal)
throw new Error('Emulated device mode has wrong orientation \''+mode.orientation+'\'');const orientation=result.orientationByName(mode.orientation);mode.insets=parseInsets(parseValue(modes[i],'insets','object'));if(mode.insets.top<0||mode.insets.left<0||mode.insets.right<0||mode.insets.bottom<0||mode.insets.top+mode.insets.bottom>orientation.height||mode.insets.left+mode.insets.right>orientation.width)
throw new Error('Emulated device mode \''+mode.title+'\'has wrong mode insets');mode.image=(parseValue(modes[i],'image','string',null));result.modes.push(mode);}
result._showByDefault=(parseValue(json,'show-by-default','boolean',undefined));result._show=(parseValue(json,'show','string',Emulation.EmulatedDevice._Show.Default));return result;}catch(e){return null;}}
static deviceComparator(device1,device2){const order1=(device1._extension&&device1._extension.descriptor()['order'])||-1;const order2=(device2._extension&&device2._extension.descriptor()['order'])||-1;if(order1>order2)
return 1;if(order2>order1)
return-1;return device1.title<device2.title?-1:(device1.title>device2.title?1:0);}
extension(){return this._extension;}
setExtension(extension){this._extension=extension;}
modesForOrientation(orientation){const result=[];for(let index=0;index<this.modes.length;index++){if(this.modes[index].orientation===orientation)
result.push(this.modes[index]);}
return result;}
_toJSON(){const json={};json['title']=this.title;json['type']=this.type;json['user-agent']=this.userAgent;json['capabilities']=this.capabilities;json['screen']={};json['screen']['device-pixel-ratio']=this.deviceScaleFactor;json['screen']['vertical']=this._orientationToJSON(this.vertical);json['screen']['horizontal']=this._orientationToJSON(this.horizontal);json['modes']=[];for(let i=0;i<this.modes.length;++i){const mode={};mode['title']=this.modes[i].title;mode['orientation']=this.modes[i].orientation;mode['insets']={};mode['insets']['left']=this.modes[i].insets.left;mode['insets']['top']=this.modes[i].insets.top;mode['insets']['right']=this.modes[i].insets.right;mode['insets']['bottom']=this.modes[i].insets.bottom;if(this.modes[i].image)
mode['image']=this.modes[i].image;json['modes'].push(mode);}
json['show-by-default']=this._showByDefault;json['show']=this._show;return json;}
_orientationToJSON(orientation){const json={};json['width']=orientation.width;json['height']=orientation.height;if(orientation.outlineInsets){json['outline']={};json['outline']['insets']={};json['outline']['insets']['left']=orientation.outlineInsets.left;json['outline']['insets']['top']=orientation.outlineInsets.top;json['outline']['insets']['right']=orientation.outlineInsets.right;json['outline']['insets']['bottom']=orientation.outlineInsets.bottom;json['outline']['image']=orientation.outlineImage;}
return json;}
modeImage(mode){if(!mode.image)
return'';if(!this._extension)
return mode.image;return this._extension.module().substituteURL(mode.image);}
outlineImage(mode){const orientation=this.orientationByName(mode.orientation);if(!orientation.outlineImage)
return'';if(!this._extension)
return orientation.outlineImage;return this._extension.module().substituteURL(orientation.outlineImage);}
orientationByName(name){return name===Emulation.EmulatedDevice.Vertical?this.vertical:this.horizontal;}
show(){if(this._show===Emulation.EmulatedDevice._Show.Default)
return this._showByDefault;return this._show===Emulation.EmulatedDevice._Show.Always;}
setShow(show){this._show=show?Emulation.EmulatedDevice._Show.Always:Emulation.EmulatedDevice._Show.Never;}
copyShowFrom(other){this._show=other._show;}
touch(){return this.capabilities.indexOf(Emulation.EmulatedDevice.Capability.Touch)!==-1;}
mobile(){return this.capabilities.indexOf(Emulation.EmulatedDevice.Capability.Mobile)!==-1;}};Emulation.EmulatedDevice.Mode;Emulation.EmulatedDevice.Orientation;Emulation.EmulatedDevice.Horizontal='horizontal';Emulation.EmulatedDevice.Vertical='vertical';Emulation.EmulatedDevice.Type={Phone:'phone',Tablet:'tablet',Notebook:'notebook',Desktop:'desktop',Unknown:'unknown'};Emulation.EmulatedDevice.Capability={Touch:'touch',Mobile:'mobile'};Emulation.EmulatedDevice._Show={Always:'Always',Default:'Default',Never:'Never'};Emulation.EmulatedDevicesList=class extends Common.Object{constructor(){super();this._standardSetting=Common.settings.createSetting('standardEmulatedDeviceList',[]);this._standard=[];this._listFromJSONV1(this._standardSetting.get(),this._standard);this._updateStandardDevices();this._customSetting=Common.settings.createSetting('customEmulatedDeviceList',[]);this._custom=[];if(!this._listFromJSONV1(this._customSetting.get(),this._custom))
this.saveCustomDevices();}
static instance(){if(!Emulation.EmulatedDevicesList._instance)
Emulation.EmulatedDevicesList._instance=new Emulation.EmulatedDevicesList();return(Emulation.EmulatedDevicesList._instance);}
_updateStandardDevices(){const devices=[];const extensions=self.runtime.extensions('emulated-device');for(let i=0;i<extensions.length;++i){const device=Emulation.EmulatedDevice.fromJSONV1(extensions[i].descriptor()['device']);device.setExtension(extensions[i]);devices.push(device);}
this._copyShowValues(this._standard,devices);this._standard=devices;this.saveStandardDevices();}
_listFromJSONV1(jsonArray,result){if(!Array.isArray(jsonArray))
return false;let success=true;for(let i=0;i<jsonArray.length;++i){const device=Emulation.EmulatedDevice.fromJSONV1(jsonArray[i]);if(device){result.push(device);if(!device.modes.length){device.modes.push({title:'',orientation:Emulation.EmulatedDevice.Horizontal,insets:new UI.Insets(0,0,0,0),image:null});device.modes.push({title:'',orientation:Emulation.EmulatedDevice.Vertical,insets:new UI.Insets(0,0,0,0),image:null});}}else{success=false;}}
return success;}
standard(){return this._standard;}
custom(){return this._custom;}
revealCustomSetting(){Common.Revealer.reveal(this._customSetting);}
addCustomDevice(device){this._custom.push(device);this.saveCustomDevices();}
removeCustomDevice(device){this._custom.remove(device);this.saveCustomDevices();}
saveCustomDevices(){const json=this._custom.map(function(device){return device._toJSON();});this._customSetting.set(json);this.dispatchEventToListeners(Emulation.EmulatedDevicesList.Events.CustomDevicesUpdated);}
saveStandardDevices(){const json=this._standard.map(function(device){return device._toJSON();});this._standardSetting.set(json);this.dispatchEventToListeners(Emulation.EmulatedDevicesList.Events.StandardDevicesUpdated);}
_copyShowValues(from,to){const deviceById=new Map();for(let i=0;i<from.length;++i)
deviceById.set(from[i].title,from[i]);for(let i=0;i<to.length;++i){const title=to[i].title;if(deviceById.has(title))
to[i].copyShowFrom((deviceById.get(title)));}}};Emulation.EmulatedDevicesList.Events={CustomDevicesUpdated:Symbol('CustomDevicesUpdated'),StandardDevicesUpdated:Symbol('StandardDevicesUpdated')};Emulation.EmulatedDevicesList._instance;;Emulation.DevicesSettingsTab=class extends UI.VBox{constructor(){super();this.element.classList.add('settings-tab-container');this.element.classList.add('devices-settings-tab');this.registerRequiredCSS('emulation/devicesSettingsTab.css');const header=this.element.createChild('header');header.createChild('h3').createTextChild(Common.UIString('Emulated Devices'));this.containerElement=this.element.createChild('div','settings-container-wrapper').createChild('div','settings-tab settings-content settings-container');const buttonsRow=this.containerElement.createChild('div','devices-button-row');this._addCustomButton=UI.createTextButton(Common.UIString('Add custom device...'),this._addCustomDevice.bind(this));buttonsRow.appendChild(this._addCustomButton);this._list=new UI.ListWidget(this);this._list.registerRequiredCSS('emulation/devicesSettingsTab.css');this._list.element.classList.add('devices-list');this._list.show(this.containerElement);this._muteUpdate=false;this._emulatedDevicesList=Emulation.EmulatedDevicesList.instance();this._emulatedDevicesList.addEventListener(Emulation.EmulatedDevicesList.Events.CustomDevicesUpdated,this._devicesUpdated,this);this._emulatedDevicesList.addEventListener(Emulation.EmulatedDevicesList.Events.StandardDevicesUpdated,this._devicesUpdated,this);this.setDefaultFocusedElement(this._addCustomButton);}
wasShown(){super.wasShown();this._devicesUpdated();}
_devicesUpdated(){if(this._muteUpdate)
return;this._list.clear();let devices=this._emulatedDevicesList.custom().slice();for(let i=0;i<devices.length;++i)
this._list.appendItem(devices[i],true);this._list.appendSeparator();devices=this._emulatedDevicesList.standard().slice();devices.sort(Emulation.EmulatedDevice.deviceComparator);for(let i=0;i<devices.length;++i)
this._list.appendItem(devices[i],false);}
_muteAndSaveDeviceList(custom){this._muteUpdate=true;if(custom)
this._emulatedDevicesList.saveCustomDevices();else
this._emulatedDevicesList.saveStandardDevices();this._muteUpdate=false;}
_addCustomDevice(){const device=new Emulation.EmulatedDevice();device.deviceScaleFactor=0;device.horizontal.width=700;device.horizontal.height=400;device.vertical.width=400;device.vertical.height=700;this._list.addNewItem(this._emulatedDevicesList.custom().length,device);}
_toNumericInputValue(value){return value?String(value):'';}
renderItem(item,editable){const device=(item);const element=createElementWithClass('div','devices-list-item');const checkbox=element.createChild('input','devices-list-checkbox');checkbox.type='checkbox';checkbox.checked=device.show();checkbox.addEventListener('click',event=>event.consume(),false);element.createChild('div','devices-list-title').textContent=device.title;element.addEventListener('click',onItemClicked.bind(this),false);return element;function onItemClicked(event){const show=!checkbox.checked;device.setShow(show);this._muteAndSaveDeviceList(editable);checkbox.checked=show;event.consume();}}
removeItemRequested(item,index){this._emulatedDevicesList.removeCustomDevice((item));}
commitEdit(item,editor,isNew){const device=(item);device.title=editor.control('title').value.trim();device.vertical.width=editor.control('width').value?parseInt(editor.control('width').value,10):0;device.vertical.height=editor.control('height').value?parseInt(editor.control('height').value,10):0;device.horizontal.width=device.vertical.height;device.horizontal.height=device.vertical.width;device.deviceScaleFactor=editor.control('scale').value?parseFloat(editor.control('scale').value):0;device.userAgent=editor.control('user-agent').value;device.modes=[];device.modes.push({title:'',orientation:Emulation.EmulatedDevice.Vertical,insets:new UI.Insets(0,0,0,0),image:null});device.modes.push({title:'',orientation:Emulation.EmulatedDevice.Horizontal,insets:new UI.Insets(0,0,0,0),image:null});device.capabilities=[];const uaType=editor.control('ua-type').value;if(uaType===Emulation.DeviceModeModel.UA.Mobile||uaType===Emulation.DeviceModeModel.UA.MobileNoTouch)
device.capabilities.push(Emulation.EmulatedDevice.Capability.Mobile);if(uaType===Emulation.DeviceModeModel.UA.Mobile||uaType===Emulation.DeviceModeModel.UA.DesktopTouch)
device.capabilities.push(Emulation.EmulatedDevice.Capability.Touch);if(isNew)
this._emulatedDevicesList.addCustomDevice(device);else
this._emulatedDevicesList.saveCustomDevices();this._addCustomButton.scrollIntoViewIfNeeded();this._addCustomButton.focus();}
beginEdit(item){const device=(item);const editor=this._createEditor();editor.control('title').value=device.title;editor.control('width').value=this._toNumericInputValue(device.vertical.width);editor.control('height').value=this._toNumericInputValue(device.vertical.height);editor.control('scale').value=this._toNumericInputValue(device.deviceScaleFactor);editor.control('user-agent').value=device.userAgent;let uaType;if(device.mobile())
uaType=device.touch()?Emulation.DeviceModeModel.UA.Mobile:Emulation.DeviceModeModel.UA.MobileNoTouch;else
uaType=device.touch()?Emulation.DeviceModeModel.UA.DesktopTouch:Emulation.DeviceModeModel.UA.Desktop;editor.control('ua-type').value=uaType;return editor;}
_createEditor(){if(this._editor)
return this._editor;const editor=new UI.ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const fields=content.createChild('div','devices-edit-fields');fields.createChild('div','hbox').appendChild(editor.createInput('title','text',Common.UIString('Device name'),titleValidator));const screen=fields.createChild('div','hbox');screen.appendChild(editor.createInput('width','text',Common.UIString('Width'),sizeValidator));screen.appendChild(editor.createInput('height','text',Common.UIString('height'),sizeValidator));const dpr=editor.createInput('scale','text',Common.UIString('Device pixel ratio'),scaleValidator);dpr.classList.add('device-edit-fixed');screen.appendChild(dpr);const ua=fields.createChild('div','hbox');ua.appendChild(editor.createInput('user-agent','text',Common.UIString('User agent string'),()=>true));const uaType=editor.createSelect('ua-type',[Emulation.DeviceModeModel.UA.Mobile,Emulation.DeviceModeModel.UA.MobileNoTouch,Emulation.DeviceModeModel.UA.Desktop,Emulation.DeviceModeModel.UA.DesktopTouch],()=>true);uaType.classList.add('device-edit-fixed');ua.appendChild(uaType);return editor;function titleValidator(item,index,input){const value=input.value.trim();return value.length>0&&value.length<50;}
function sizeValidator(item,index,input){return Emulation.DeviceModeModel.deviceSizeValidator(input.value);}
function scaleValidator(item,index,input){return Emulation.DeviceModeModel.deviceScaleFactorValidator(input.value);}}};;Emulation.InspectedPagePlaceholder=class extends UI.Widget{constructor(){super(true);this.registerRequiredCSS('emulation/inspectedPagePlaceholder.css');UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this.onResize,this);this.restoreMinimumSize();}
onResize(){if(this._updateId)
this.element.window().cancelAnimationFrame(this._updateId);this._updateId=this.element.window().requestAnimationFrame(this.update.bind(this,false));}
restoreMinimumSize(){this.setMinimumSize(150,150);}
clearMinimumSize(){this.setMinimumSize(1,1);}
_dipPageRect(){const zoomFactor=UI.zoomManager.zoomFactor();const rect=this.element.getBoundingClientRect();const bodyRect=this.element.ownerDocument.body.getBoundingClientRect();const left=Math.max(rect.left*zoomFactor,bodyRect.left*zoomFactor);const top=Math.max(rect.top*zoomFactor,bodyRect.top*zoomFactor);const bottom=Math.min(rect.bottom*zoomFactor,bodyRect.bottom*zoomFactor);const right=Math.min(rect.right*zoomFactor,bodyRect.right*zoomFactor);return{x:left,y:top,width:right-left,height:bottom-top};}
update(force){delete this._updateId;const rect=this._dipPageRect();const bounds={x:Math.round(rect.x),y:Math.round(rect.y),height:Math.max(1,Math.round(rect.height)),width:Math.max(1,Math.round(rect.width)),};if(force){--bounds.height;this.dispatchEventToListeners(Emulation.InspectedPagePlaceholder.Events.Update,bounds);++bounds.height;}
this.dispatchEventToListeners(Emulation.InspectedPagePlaceholder.Events.Update,bounds);}};Emulation.InspectedPagePlaceholder.instance=function(){return self.singleton(Emulation.InspectedPagePlaceholder);};Emulation.InspectedPagePlaceholder.Events={Update:Symbol('Update')};;Emulation.MediaQueryInspector=class extends UI.Widget{constructor(getWidthCallback,setWidthCallback){super(true);this.registerRequiredCSS('emulation/mediaQueryInspector.css');this.contentElement.classList.add('media-inspector-view');this.contentElement.addEventListener('click',this._onMediaQueryClicked.bind(this),false);this.contentElement.addEventListener('contextmenu',this._onContextMenu.bind(this),false);this._mediaThrottler=new Common.Throttler(0);this._getWidthCallback=getWidthCallback;this._setWidthCallback=setWidthCallback;this._scale=1;SDK.targetManager.observeModels(SDK.CSSModel,this);UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._renderMediaQueries.bind(this),this);}
modelAdded(cssModel){if(this._cssModel)
return;this._cssModel=cssModel;this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._scheduleMediaQueriesUpdate,this);this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._scheduleMediaQueriesUpdate,this);this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._scheduleMediaQueriesUpdate,this);this._cssModel.addEventListener(SDK.CSSModel.Events.MediaQueryResultChanged,this._scheduleMediaQueriesUpdate,this);}
modelRemoved(cssModel){if(cssModel!==this._cssModel)
return;this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._scheduleMediaQueriesUpdate,this);this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._scheduleMediaQueriesUpdate,this);this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._scheduleMediaQueriesUpdate,this);this._cssModel.removeEventListener(SDK.CSSModel.Events.MediaQueryResultChanged,this._scheduleMediaQueriesUpdate,this);delete this._cssModel;}
setAxisTransform(scale){if(Math.abs(this._scale-scale)<1e-8)
return;this._scale=scale;this._renderMediaQueries();}
_onMediaQueryClicked(event){const mediaQueryMarker=event.target.enclosingNodeOrSelfWithClass('media-inspector-bar');if(!mediaQueryMarker)
return;const model=mediaQueryMarker._model;if(model.section()===Emulation.MediaQueryInspector.Section.Max){this._setWidthCallback(model.maxWidthExpression().computedLength());return;}
if(model.section()===Emulation.MediaQueryInspector.Section.Min){this._setWidthCallback(model.minWidthExpression().computedLength());return;}
const currentWidth=this._getWidthCallback();if(currentWidth!==model.minWidthExpression().computedLength())
this._setWidthCallback(model.minWidthExpression().computedLength());else
this._setWidthCallback(model.maxWidthExpression().computedLength());}
_onContextMenu(event){if(!this._cssModel||!this._cssModel.isEnabled())
return;const mediaQueryMarker=event.target.enclosingNodeOrSelfWithClass('media-inspector-bar');if(!mediaQueryMarker)
return;const locations=mediaQueryMarker._locations;const uiLocations=new Map();for(let i=0;i<locations.length;++i){const uiLocation=Bindings.cssWorkspaceBinding.rawLocationToUILocation(locations[i]);if(!uiLocation)
continue;const descriptor=String.sprintf('%s:%d:%d',uiLocation.uiSourceCode.url(),uiLocation.lineNumber+1,uiLocation.columnNumber+1);uiLocations.set(descriptor,uiLocation);}
const contextMenuItems=uiLocations.keysArray().sort();const contextMenu=new UI.ContextMenu(event);const subMenuItem=contextMenu.defaultSection().appendSubMenuItem(Common.UIString('Reveal in source code'));for(let i=0;i<contextMenuItems.length;++i){const title=contextMenuItems[i];subMenuItem.defaultSection().appendItem(title,this._revealSourceLocation.bind(this,(uiLocations.get(title))));}
contextMenu.show();}
_revealSourceLocation(location){Common.Revealer.reveal(location);}
_scheduleMediaQueriesUpdate(){if(!this.isShowing())
return;this._mediaThrottler.schedule(this._refetchMediaQueries.bind(this));}
_refetchMediaQueries(){if(!this.isShowing()||!this._cssModel)
return Promise.resolve();return this._cssModel.mediaQueriesPromise().then(this._rebuildMediaQueries.bind(this));}
_squashAdjacentEqual(models){const filtered=[];for(let i=0;i<models.length;++i){const last=filtered.peekLast();if(!last||!last.equals(models[i]))
filtered.push(models[i]);}
return filtered;}
_rebuildMediaQueries(cssMedias){let queryModels=[];for(let i=0;i<cssMedias.length;++i){const cssMedia=cssMedias[i];if(!cssMedia.mediaList)
continue;for(let j=0;j<cssMedia.mediaList.length;++j){const mediaQuery=cssMedia.mediaList[j];const queryModel=Emulation.MediaQueryInspector.MediaQueryUIModel.createFromMediaQuery(cssMedia,mediaQuery);if(queryModel&&queryModel.rawLocation())
queryModels.push(queryModel);}}
queryModels.sort(compareModels);queryModels=this._squashAdjacentEqual(queryModels);let allEqual=this._cachedQueryModels&&this._cachedQueryModels.length===queryModels.length;for(let i=0;allEqual&&i<queryModels.length;++i)
allEqual=allEqual&&this._cachedQueryModels[i].equals(queryModels[i]);if(allEqual)
return;this._cachedQueryModels=queryModels;this._renderMediaQueries();function compareModels(model1,model2){return model1.compareTo(model2);}}
_renderMediaQueries(){if(!this._cachedQueryModels||!this.isShowing())
return;const markers=[];let lastMarker=null;for(let i=0;i<this._cachedQueryModels.length;++i){const model=this._cachedQueryModels[i];if(lastMarker&&lastMarker.model.dimensionsEqual(model)){lastMarker.locations.push(model.rawLocation());lastMarker.active=lastMarker.active||model.active();}else{lastMarker={active:model.active(),model:model,locations:[model.rawLocation()]};markers.push(lastMarker);}}
this.contentElement.removeChildren();let container=null;for(let i=0;i<markers.length;++i){if(!i||markers[i].model.section()!==markers[i-1].model.section())
container=this.contentElement.createChild('div','media-inspector-marker-container');const marker=markers[i];const bar=this._createElementFromMediaQueryModel(marker.model);bar._model=marker.model;bar._locations=marker.locations;bar.classList.toggle('media-inspector-marker-inactive',!marker.active);container.appendChild(bar);}}
_zoomFactor(){return UI.zoomManager.zoomFactor()/this._scale;}
wasShown(){this._scheduleMediaQueriesUpdate();}
_createElementFromMediaQueryModel(model){const zoomFactor=this._zoomFactor();const minWidthValue=model.minWidthExpression()?model.minWidthExpression().computedLength()/zoomFactor:0;const maxWidthValue=model.maxWidthExpression()?model.maxWidthExpression().computedLength()/zoomFactor:0;const result=createElementWithClass('div','media-inspector-bar');if(model.section()===Emulation.MediaQueryInspector.Section.Max){result.createChild('div','media-inspector-marker-spacer');const markerElement=result.createChild('div','media-inspector-marker media-inspector-marker-max-width');markerElement.style.width=maxWidthValue+'px';markerElement.title=model.mediaText();appendLabel(markerElement,model.maxWidthExpression(),false,false);appendLabel(markerElement,model.maxWidthExpression(),true,true);result.createChild('div','media-inspector-marker-spacer');}
if(model.section()===Emulation.MediaQueryInspector.Section.MinMax){result.createChild('div','media-inspector-marker-spacer');const leftElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-max-width');leftElement.style.width=(maxWidthValue-minWidthValue)*0.5+'px';leftElement.title=model.mediaText();appendLabel(leftElement,model.minWidthExpression(),true,false);appendLabel(leftElement,model.maxWidthExpression(),false,true);result.createChild('div','media-inspector-marker-spacer').style.flex='0 0 '+minWidthValue+'px';const rightElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-max-width');rightElement.style.width=(maxWidthValue-minWidthValue)*0.5+'px';rightElement.title=model.mediaText();appendLabel(rightElement,model.minWidthExpression(),true,false);appendLabel(rightElement,model.maxWidthExpression(),false,true);result.createChild('div','media-inspector-marker-spacer');}
if(model.section()===Emulation.MediaQueryInspector.Section.Min){const leftElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-width media-inspector-marker-min-width-left');leftElement.title=model.mediaText();appendLabel(leftElement,model.minWidthExpression(),false,false);result.createChild('div','media-inspector-marker-spacer').style.flex='0 0 '+minWidthValue+'px';const rightElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-width media-inspector-marker-min-width-right');rightElement.title=model.mediaText();appendLabel(rightElement,model.minWidthExpression(),true,true);}
function appendLabel(marker,expression,atLeft,leftAlign){marker.createChild('div','media-inspector-marker-label-container '+(atLeft?'media-inspector-marker-label-container-left':'media-inspector-marker-label-container-right')).createChild('span','media-inspector-marker-label '+
(leftAlign?'media-inspector-label-left':'media-inspector-label-right')).textContent=expression.value()+expression.unit();}
return result;}};Emulation.MediaQueryInspector.Section={Max:0,MinMax:1,Min:2};Emulation.MediaQueryInspector.MediaQueryUIModel=class{constructor(cssMedia,minWidthExpression,maxWidthExpression,active){this._cssMedia=cssMedia;this._minWidthExpression=minWidthExpression;this._maxWidthExpression=maxWidthExpression;this._active=active;if(maxWidthExpression&&!minWidthExpression)
this._section=Emulation.MediaQueryInspector.Section.Max;else if(minWidthExpression&&maxWidthExpression)
this._section=Emulation.MediaQueryInspector.Section.MinMax;else
this._section=Emulation.MediaQueryInspector.Section.Min;}
static createFromMediaQuery(cssMedia,mediaQuery){let maxWidthExpression=null;let maxWidthPixels=Number.MAX_VALUE;let minWidthExpression=null;let minWidthPixels=Number.MIN_VALUE;const expressions=mediaQuery.expressions();for(let i=0;i<expressions.length;++i){const expression=expressions[i];const feature=expression.feature();if(feature.indexOf('width')===-1)
continue;const pixels=expression.computedLength();if(feature.startsWith('max-')&&pixels<maxWidthPixels){maxWidthExpression=expression;maxWidthPixels=pixels;}else if(feature.startsWith('min-')&&pixels>minWidthPixels){minWidthExpression=expression;minWidthPixels=pixels;}}
if(minWidthPixels>maxWidthPixels||(!maxWidthExpression&&!minWidthExpression))
return null;return new Emulation.MediaQueryInspector.MediaQueryUIModel(cssMedia,minWidthExpression,maxWidthExpression,mediaQuery.active());}
equals(other){return this.compareTo(other)===0;}
dimensionsEqual(other){return this.section()===other.section()&&(!this.minWidthExpression()||(this.minWidthExpression().computedLength()===other.minWidthExpression().computedLength()))&&(!this.maxWidthExpression()||(this.maxWidthExpression().computedLength()===other.maxWidthExpression().computedLength()));}
compareTo(other){if(this.section()!==other.section())
return this.section()-other.section();if(this.dimensionsEqual(other)){const myLocation=this.rawLocation();const otherLocation=other.rawLocation();if(!myLocation&&!otherLocation)
return this.mediaText().compareTo(other.mediaText());if(myLocation&&!otherLocation)
return 1;if(!myLocation&&otherLocation)
return-1;if(this.active()!==other.active())
return this.active()?-1:1;return myLocation.url.compareTo(otherLocation.url)||myLocation.lineNumber-otherLocation.lineNumber||myLocation.columnNumber-otherLocation.columnNumber;}
if(this.section()===Emulation.MediaQueryInspector.Section.Max)
return other.maxWidthExpression().computedLength()-this.maxWidthExpression().computedLength();if(this.section()===Emulation.MediaQueryInspector.Section.Min)
return this.minWidthExpression().computedLength()-other.minWidthExpression().computedLength();return this.minWidthExpression().computedLength()-other.minWidthExpression().computedLength()||other.maxWidthExpression().computedLength()-this.maxWidthExpression().computedLength();}
section(){return this._section;}
mediaText(){return this._cssMedia.text;}
rawLocation(){if(!this._rawLocation)
this._rawLocation=this._cssMedia.rawLocation();return this._rawLocation;}
minWidthExpression(){return this._minWidthExpression;}
maxWidthExpression(){return this._maxWidthExpression;}
active(){return this._active;}};;Emulation.SensorsView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('emulation/sensors.css');this.contentElement.classList.add('sensors-view');this._geolocationSetting=Common.settings.createSetting('emulation.geolocationOverride','');this._geolocation=SDK.EmulationModel.Geolocation.parseSetting(this._geolocationSetting.get());this._geolocationOverrideEnabled=false;this._createGeolocationSection(this._geolocation);this.contentElement.createChild('div').classList.add('panel-section-separator');this._deviceOrientationSetting=Common.settings.createSetting('emulation.deviceOrientationOverride','');this._deviceOrientation=SDK.EmulationModel.DeviceOrientation.parseSetting(this._deviceOrientationSetting.get());this._deviceOrientationOverrideEnabled=false;this._createDeviceOrientationSection();this.contentElement.createChild('div').classList.add('panel-section-separator');this._appendTouchControl();}
static instance(){if(!Emulation.SensorsView._instanceObject)
Emulation.SensorsView._instanceObject=new Emulation.SensorsView();return Emulation.SensorsView._instanceObject;}
_createGeolocationSection(geolocation){const geogroup=this.contentElement.createChild('section','sensors-group');const geogroupTitle=UI.createLabel(ls`Geolocation`,'sensors-group-title');geogroup.appendChild(geogroupTitle);const fields=geogroup.createChild('div','geo-fields');const noOverrideOption={title:Common.UIString('No override'),location:Emulation.SensorsView.NonPresetOptions.NoOverride};this._locationSelectElement=fields.createChild('select','chrome-select');UI.bindLabelToControl(geogroupTitle,this._locationSelectElement);this._locationSelectElement.appendChild(new Option(noOverrideOption.title,noOverrideOption.location));this._customLocationsGroup=this._locationSelectElement.createChild('optgroup');this._customLocationsGroup.label=ls`Overrides`;const customGeolocations=Common.moduleSetting('emulation.geolocations');fields.appendChild(UI.createTextButton(ls`Manage`,()=>Common.Revealer.reveal(customGeolocations)));const fillCustomSettings=()=>{this._customLocationsGroup.removeChildren();for(const geolocation of customGeolocations.get())
this._customLocationsGroup.appendChild(new Option(geolocation.title,JSON.stringify(geolocation)));};customGeolocations.addChangeListener(fillCustomSettings);fillCustomSettings();const customLocationOption={title:Common.UIString('Other\u2026'),location:Emulation.SensorsView.NonPresetOptions.Custom};this._locationSelectElement.appendChild(new Option(customLocationOption.title,customLocationOption.location));const group=this._locationSelectElement.createChild('optgroup');group.label=ls`Error`;group.appendChild(new Option(ls`Location unavailable`,Emulation.SensorsView.NonPresetOptions.Unavailable));this._locationSelectElement.selectedIndex=0;this._locationSelectElement.addEventListener('change',this._geolocationSelectChanged.bind(this));this._fieldsetElement=fields.createChild('fieldset');this._fieldsetElement.disabled=!this._geolocationOverrideEnabled;this._fieldsetElement.id='geolocation-override-section';const latitudeGroup=this._fieldsetElement.createChild('div','latlong-group');const longitudeGroup=this._fieldsetElement.createChild('div','latlong-group');this._latitudeInput=UI.createInput('','number');latitudeGroup.appendChild(this._latitudeInput);this._latitudeInput.setAttribute('step','any');this._latitudeInput.value=0;this._latitudeSetter=UI.bindInput(this._latitudeInput,this._applyGeolocationUserInput.bind(this),SDK.EmulationModel.Geolocation.latitudeValidator,true,0.1);this._latitudeSetter(String(geolocation.latitude));this._longitudeInput=UI.createInput('','number');longitudeGroup.appendChild(this._longitudeInput);this._longitudeInput.setAttribute('step','any');this._longitudeInput.value=0;this._longitudeSetter=UI.bindInput(this._longitudeInput,this._applyGeolocationUserInput.bind(this),SDK.EmulationModel.Geolocation.longitudeValidator,true,0.1);this._longitudeSetter(String(geolocation.longitude));const cmdOrCtrl=Host.isMac()?'\u2318':'Ctrl';const modifierKeyMessage=ls`Adjust with mousewheel or up/down keys. ${cmdOrCtrl}: ±10, Shift: ±1, Alt: ±0.01`;this._latitudeInput.title=modifierKeyMessage;this._longitudeInput.title=modifierKeyMessage;latitudeGroup.appendChild(UI.createLabel(ls`Latitude`,'latlong-title',this._latitudeInput));longitudeGroup.appendChild(UI.createLabel(ls`Longitude`,'latlong-title',this._longitudeInput));}
_geolocationSelectChanged(){this._fieldsetElement.disabled=false;const value=this._locationSelectElement.options[this._locationSelectElement.selectedIndex].value;if(value===Emulation.SensorsView.NonPresetOptions.NoOverride){this._geolocationOverrideEnabled=false;this._fieldsetElement.disabled=true;}else if(value===Emulation.SensorsView.NonPresetOptions.Custom){this._geolocationOverrideEnabled=true;const geolocation=SDK.EmulationModel.Geolocation.parseUserInput(this._latitudeInput.value.trim(),this._longitudeInput.value.trim(),'');if(!geolocation)
return;this._geolocation=geolocation;}else if(value===Emulation.SensorsView.NonPresetOptions.Unavailable){this._geolocationOverrideEnabled=true;this._geolocation=new SDK.EmulationModel.Geolocation(0,0,true);}else{this._geolocationOverrideEnabled=true;const coordinates=JSON.parse(value);this._geolocation=new SDK.EmulationModel.Geolocation(coordinates.lat,coordinates.long,false);this._latitudeSetter(coordinates.lat);this._longitudeSetter(coordinates.long);}
this._applyGeolocation();if(value===Emulation.SensorsView.NonPresetOptions.Custom)
this._latitudeInput.focus();}
_applyGeolocationUserInput(){const geolocation=SDK.EmulationModel.Geolocation.parseUserInput(this._latitudeInput.value.trim(),this._longitudeInput.value.trim(),'');if(!geolocation)
return;this._setSelectElementLabel(this._locationSelectElement,Emulation.SensorsView.NonPresetOptions.Custom);this._geolocation=geolocation;this._applyGeolocation();}
_applyGeolocation(){if(this._geolocationOverrideEnabled)
this._geolocationSetting.set(this._geolocation.toSetting());for(const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
emulationModel.emulateGeolocation(this._geolocationOverrideEnabled?this._geolocation:null);}
_createDeviceOrientationSection(){const orientationGroup=this.contentElement.createChild('section','sensors-group');const orientationTitle=UI.createLabel(ls`Orientation`,'sensors-group-title');orientationGroup.appendChild(orientationTitle);const orientationContent=orientationGroup.createChild('div','orientation-content');const fields=orientationContent.createChild('div','orientation-fields');const orientationOffOption={title:Common.UIString('Off'),orientation:Emulation.SensorsView.NonPresetOptions.NoOverride};const customOrientationOption={title:Common.UIString('Custom orientation...'),orientation:Emulation.SensorsView.NonPresetOptions.Custom};this._orientationSelectElement=this.contentElement.createChild('select','chrome-select');UI.bindLabelToControl(orientationTitle,this._orientationSelectElement);this._orientationSelectElement.appendChild(new Option(orientationOffOption.title,orientationOffOption.orientation));this._orientationSelectElement.appendChild(new Option(customOrientationOption.title,customOrientationOption.orientation));const orientationGroups=Emulation.SensorsView.PresetOrientations;for(let i=0;i<orientationGroups.length;++i){const groupElement=this._orientationSelectElement.createChild('optgroup');groupElement.label=orientationGroups[i].title;const group=orientationGroups[i].value;for(let j=0;j<group.length;++j)
groupElement.appendChild(new Option(group[j].title,group[j].orientation));}
this._orientationSelectElement.selectedIndex=0;fields.appendChild(this._orientationSelectElement);this._orientationSelectElement.addEventListener('change',this._orientationSelectChanged.bind(this));this._deviceOrientationFieldset=this._createDeviceOrientationOverrideElement(this._deviceOrientation);this._stageElement=orientationContent.createChild('div','orientation-stage');this._orientationLayer=this._stageElement.createChild('div','orientation-layer');this._boxElement=this._orientationLayer.createChild('section','orientation-box orientation-element');this._boxElement.createChild('section','orientation-front orientation-element');this._boxElement.createChild('section','orientation-top orientation-element');this._boxElement.createChild('section','orientation-back orientation-element');this._boxElement.createChild('section','orientation-left orientation-element');this._boxElement.createChild('section','orientation-right orientation-element');this._boxElement.createChild('section','orientation-bottom orientation-element');UI.installDragHandle(this._stageElement,this._onBoxDragStart.bind(this),this._onBoxDrag.bind(this),null,'-webkit-grabbing','-webkit-grab');fields.appendChild(this._deviceOrientationFieldset);this._enableOrientationFields(true);this._setBoxOrientation(this._deviceOrientation,false);}
_enableOrientationFields(disable){if(disable){this._deviceOrientationFieldset.disabled=true;this._stageElement.classList.add('disabled');this._stageElement.title=ls`Enable orientation to rotate`;}else{this._deviceOrientationFieldset.disabled=false;this._stageElement.classList.remove('disabled');this._stageElement.title=ls`Shift+drag horizontally to rotate around the y-axis`;}}
_orientationSelectChanged(){const value=this._orientationSelectElement.options[this._orientationSelectElement.selectedIndex].value;this._enableOrientationFields(false);if(value===Emulation.SensorsView.NonPresetOptions.NoOverride){this._deviceOrientationOverrideEnabled=false;this._enableOrientationFields(true);}else if(value===Emulation.SensorsView.NonPresetOptions.Custom){this._deviceOrientationOverrideEnabled=true;this._alphaElement.focus();}else{const parsedValue=JSON.parse(value);this._deviceOrientationOverrideEnabled=true;this._deviceOrientation=new SDK.EmulationModel.DeviceOrientation(parsedValue[0],parsedValue[1],parsedValue[2]);this._setDeviceOrientation(this._deviceOrientation,Emulation.SensorsView.DeviceOrientationModificationSource.SelectPreset);}}
_applyDeviceOrientation(){if(this._deviceOrientationOverrideEnabled)
this._deviceOrientationSetting.set(this._deviceOrientation.toSetting());for(const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
emulationModel.emulateDeviceOrientation(this._deviceOrientationOverrideEnabled?this._deviceOrientation:null);}
_setSelectElementLabel(selectElement,labelValue){const optionValues=Array.prototype.map.call(selectElement.options,x=>x.value);selectElement.selectedIndex=optionValues.indexOf(labelValue);}
_applyDeviceOrientationUserInput(){this._setDeviceOrientation(SDK.EmulationModel.DeviceOrientation.parseUserInput(this._alphaElement.value.trim(),this._betaElement.value.trim(),this._gammaElement.value.trim()),Emulation.SensorsView.DeviceOrientationModificationSource.UserInput);this._setSelectElementLabel(this._orientationSelectElement,Emulation.SensorsView.NonPresetOptions.Custom);}
_resetDeviceOrientation(){this._setDeviceOrientation(new SDK.EmulationModel.DeviceOrientation(0,90,0),Emulation.SensorsView.DeviceOrientationModificationSource.ResetButton);this._setSelectElementLabel(this._orientationSelectElement,'[0, 90, 0]');}
_setDeviceOrientation(deviceOrientation,modificationSource){if(!deviceOrientation)
return;function roundAngle(angle){return Math.round(angle*10000)/10000;}
if(modificationSource!==Emulation.SensorsView.DeviceOrientationModificationSource.UserInput){this._alphaSetter(roundAngle(deviceOrientation.alpha));this._betaSetter(roundAngle(deviceOrientation.beta));this._gammaSetter(roundAngle(deviceOrientation.gamma));}
const animate=modificationSource!==Emulation.SensorsView.DeviceOrientationModificationSource.UserDrag;this._setBoxOrientation(deviceOrientation,animate);this._deviceOrientation=deviceOrientation;this._applyDeviceOrientation();}
_createAxisInput(parentElement,input,label){const div=parentElement.createChild('div','orientation-axis-input-container');div.appendChild(input);div.appendChild(UI.createLabel(label,'',input));input.type='number';return UI.bindInput(input,this._applyDeviceOrientationUserInput.bind(this),SDK.EmulationModel.DeviceOrientation.validator,true);}
_createDeviceOrientationOverrideElement(deviceOrientation){const fieldsetElement=createElement('fieldset');fieldsetElement.classList.add('device-orientation-override-section');const cellElement=fieldsetElement.createChild('td','orientation-inputs-cell');this._alphaElement=UI.createInput();this._alphaElement.setAttribute('step','any');this._alphaSetter=this._createAxisInput(cellElement,this._alphaElement,Common.UIString('\u03B1 (alpha)'));this._alphaSetter(String(deviceOrientation.alpha));this._betaElement=UI.createInput();this._betaElement.setAttribute('step','any');this._betaSetter=this._createAxisInput(cellElement,this._betaElement,Common.UIString('\u03B2 (beta)'));this._betaSetter(String(deviceOrientation.beta));this._gammaElement=UI.createInput();this._gammaElement.setAttribute('step','any');this._gammaSetter=this._createAxisInput(cellElement,this._gammaElement,Common.UIString('\u03B3 (gamma)'));this._gammaSetter(String(deviceOrientation.gamma));const resetButton=UI.createTextButton(Common.UIString('Reset'),this._resetDeviceOrientation.bind(this),'orientation-reset-button');resetButton.setAttribute('type','reset');cellElement.appendChild(resetButton);return fieldsetElement;}
_setBoxOrientation(deviceOrientation,animate){if(animate)
this._stageElement.classList.add('is-animating');else
this._stageElement.classList.remove('is-animating');const matrix=new WebKitCSSMatrix();this._boxMatrix=matrix.rotate(-deviceOrientation.beta,deviceOrientation.gamma,-deviceOrientation.alpha);const eulerAngles=new UI.Geometry.EulerAngles(deviceOrientation.alpha,deviceOrientation.beta,deviceOrientation.gamma);this._orientationLayer.style.transform=eulerAngles.toRotate3DString();}
_onBoxDrag(event){const mouseMoveVector=this._calculateRadiusVector(event.x,event.y);if(!mouseMoveVector)
return true;event.consume(true);let axis,angle;if(event.shiftKey){axis=new UI.Geometry.Vector(0,0,-1);angle=(this._mouseDownVector.x-mouseMoveVector.x)*Emulation.SensorsView.ShiftDragOrientationSpeed;}else{axis=UI.Geometry.crossProduct(this._mouseDownVector,mouseMoveVector);angle=UI.Geometry.calculateAngle(this._mouseDownVector,mouseMoveVector);}
let currentMatrix=new WebKitCSSMatrix();currentMatrix=currentMatrix.rotate(-90,0,0).rotateAxisAngle(axis.x,axis.y,axis.z,angle).rotate(90,0,0).multiply(this._originalBoxMatrix);const eulerAngles=UI.Geometry.EulerAngles.fromRotationMatrix(currentMatrix);const newOrientation=new SDK.EmulationModel.DeviceOrientation(-eulerAngles.alpha,-eulerAngles.beta,eulerAngles.gamma);this._setDeviceOrientation(newOrientation,Emulation.SensorsView.DeviceOrientationModificationSource.UserDrag);this._setSelectElementLabel(this._orientationSelectElement,Emulation.SensorsView.NonPresetOptions.Custom);return false;}
_onBoxDragStart(event){if(!this._deviceOrientationOverrideEnabled)
return false;this._mouseDownVector=this._calculateRadiusVector(event.x,event.y);this._originalBoxMatrix=this._boxMatrix;if(!this._mouseDownVector)
return false;event.consume(true);return true;}
_calculateRadiusVector(x,y){const rect=this._stageElement.getBoundingClientRect();const radius=Math.max(rect.width,rect.height)/2;const sphereX=(x-rect.left-rect.width/2)/radius;const sphereY=(y-rect.top-rect.height/2)/radius;const sqrSum=sphereX*sphereX+sphereY*sphereY;if(sqrSum>0.5)
return new UI.Geometry.Vector(sphereX,sphereY,0.5/Math.sqrt(sqrSum));return new UI.Geometry.Vector(sphereX,sphereY,Math.sqrt(1-sqrSum));}
_appendTouchControl(){const groupElement=this.contentElement.createChild('div','sensors-group');const title=UI.createLabel(ls`Touch`,'sensors-group-title');groupElement.appendChild(title);const fieldsElement=groupElement.createChild('div','sensors-group-fields');const select=fieldsElement.createChild('select','chrome-select');UI.bindLabelToControl(title,select);select.appendChild(new Option(Common.UIString('Device-based'),'auto'));select.appendChild(new Option(Common.UIString('Force enabled'),'enabled'));select.addEventListener('change',applyTouch,false);const reloadWarning=groupElement.createChild('div','reload-warning hidden');reloadWarning.textContent=Common.UIString('*Requires reload');function applyTouch(){for(const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
emulationModel.overrideEmulateTouch(select.value==='enabled');reloadWarning.classList.remove('hidden');const resourceTreeModel=SDK.targetManager.models(SDK.ResourceTreeModel)[0];if(resourceTreeModel){resourceTreeModel.once(SDK.ResourceTreeModel.Events.MainFrameNavigated).then(()=>reloadWarning.classList.add('hidden'));}}}};Emulation.SensorsView.DeviceOrientationModificationSource={UserInput:'userInput',UserDrag:'userDrag',ResetButton:'resetButton',SelectPreset:'selectPreset'};Emulation.SensorsView.NonPresetOptions={NoOverride:'noOverride',Custom:'custom',Unavailable:'unavailable'};Emulation.SensorsView.PresetOrientations=[{title:'Presets',value:[{title:Common.UIString('Portrait'),orientation:'[0, 90, 0]'},{title:Common.UIString('Portrait upside down'),orientation:'[180, -90, 0]'},{title:Common.UIString('Landscape left'),orientation:'[0, 90, -90]'},{title:Common.UIString('Landscape right'),orientation:'[0, 90, 90]'},{title:Common.UIString('Display up'),orientation:'[0, 0, 0]'},{title:Common.UIString('Display down'),orientation:'[0, 180, 0]'}]}];Emulation.SensorsView.ShowActionDelegate=class{handleAction(context,actionId){UI.viewManager.showView('sensors');return true;}};Emulation.SensorsView.ShiftDragOrientationSpeed=16;;Emulation.DeviceModeModel=class extends Common.Object{constructor(){super();this._screenRect=new UI.Rect(0,0,1,1);this._visiblePageRect=new UI.Rect(0,0,1,1);this._availableSize=new UI.Size(1,1);this._preferredSize=new UI.Size(1,1);this._initialized=false;this._appliedDeviceSize=new UI.Size(1,1);this._appliedDeviceScaleFactor=window.devicePixelRatio;this._appliedUserAgentType=Emulation.DeviceModeModel.UA.Desktop;this._scaleSetting=Common.settings.createSetting('emulation.deviceScale',1);if(!this._scaleSetting.get())
this._scaleSetting.set(1);this._scaleSetting.addChangeListener(this._scaleSettingChanged,this);this._widthSetting=Common.settings.createSetting('emulation.deviceWidth',400);if(this._widthSetting.get()<Emulation.DeviceModeModel.MinDeviceSize)
this._widthSetting.set(Emulation.DeviceModeModel.MinDeviceSize);if(this._widthSetting.get()>Emulation.DeviceModeModel.MaxDeviceSize)
this._widthSetting.set(Emulation.DeviceModeModel.MaxDeviceSize);this._widthSetting.addChangeListener(this._widthSettingChanged,this);this._heightSetting=Common.settings.createSetting('emulation.deviceHeight',0);if(this._heightSetting.get()&&this._heightSetting.get()<Emulation.DeviceModeModel.MinDeviceSize)
this._heightSetting.set(Emulation.DeviceModeModel.MinDeviceSize);if(this._heightSetting.get()>Emulation.DeviceModeModel.MaxDeviceSize)
this._heightSetting.set(Emulation.DeviceModeModel.MaxDeviceSize);this._heightSetting.addChangeListener(this._heightSettingChanged,this);this._uaSetting=Common.settings.createSetting('emulation.deviceUA',Emulation.DeviceModeModel.UA.Mobile);this._uaSetting.addChangeListener(this._uaSettingChanged,this);this._deviceScaleFactorSetting=Common.settings.createSetting('emulation.deviceScaleFactor',0);this._deviceScaleFactorSetting.addChangeListener(this._deviceScaleFactorSettingChanged,this);this._deviceOutlineSetting=Common.settings.moduleSetting('emulation.showDeviceOutline');this._deviceOutlineSetting.addChangeListener(this._deviceOutlineSettingChanged,this);this._toolbarControlsEnabledSetting=Common.settings.createSetting('emulation.toolbarControlsEnabled',true,Common.SettingStorageType.Session);this._type=Emulation.DeviceModeModel.Type.None;this._device=null;this._mode=null;this._fitScale=1;this._touchEnabled=false;this._touchMobile=false;this._emulationModel=null;this._onModelAvailable=null;SDK.targetManager.observeModels(SDK.EmulationModel,this);}
static deviceSizeValidator(value){if(/^[\d]+$/.test(value)&&value>=Emulation.DeviceModeModel.MinDeviceSize&&value<=Emulation.DeviceModeModel.MaxDeviceSize)
return true;return false;}
static deviceScaleFactorValidator(value){if(!value||(/^[\d]+(\.\d+)?|\.\d+$/.test(value)&&value>=0&&value<=10))
return true;return false;}
setAvailableSize(availableSize,preferredSize){this._availableSize=availableSize;this._preferredSize=preferredSize;this._initialized=true;this._calculateAndEmulate(false);}
emulate(type,device,mode,scale){const resetPageScaleFactor=this._type!==type||this._device!==device||this._mode!==mode;this._type=type;if(type===Emulation.DeviceModeModel.Type.Device){console.assert(device&&mode,'Must pass device and mode for device emulation');this._mode=mode;this._device=device;if(this._initialized){const orientation=device.orientationByName(mode.orientation);this._scaleSetting.set(scale||this._calculateFitScale(orientation.width,orientation.height,this._currentOutline(),this._currentInsets()));}}else{this._device=null;this._mode=null;}
if(type!==Emulation.DeviceModeModel.Type.None)
Host.userMetrics.actionTaken(Host.UserMetrics.Action.DeviceModeEnabled);this._calculateAndEmulate(resetPageScaleFactor);}
setWidth(width){const max=Math.min(Emulation.DeviceModeModel.MaxDeviceSize,this._preferredScaledWidth());width=Math.max(Math.min(width,max),1);this._widthSetting.set(width);}
setWidthAndScaleToFit(width){width=Math.max(Math.min(width,Emulation.DeviceModeModel.MaxDeviceSize),1);this._scaleSetting.set(this._calculateFitScale(width,this._heightSetting.get()));this._widthSetting.set(width);}
setHeight(height){const max=Math.min(Emulation.DeviceModeModel.MaxDeviceSize,this._preferredScaledHeight());height=Math.max(Math.min(height,max),0);if(height===this._preferredScaledHeight())
height=0;this._heightSetting.set(height);}
setHeightAndScaleToFit(height){height=Math.max(Math.min(height,Emulation.DeviceModeModel.MaxDeviceSize),0);this._scaleSetting.set(this._calculateFitScale(this._widthSetting.get(),height));this._heightSetting.set(height);}
setScale(scale){this._scaleSetting.set(scale);}
device(){return this._device;}
mode(){return this._mode;}
type(){return this._type;}
screenImage(){return(this._device&&this._mode)?this._device.modeImage(this._mode):'';}
outlineImage(){return(this._device&&this._mode&&this._deviceOutlineSetting.get())?this._device.outlineImage(this._mode):'';}
outlineRect(){return this._outlineRect;}
screenRect(){return this._screenRect;}
visiblePageRect(){return this._visiblePageRect;}
scale(){return this._scale;}
fitScale(){return this._fitScale;}
appliedDeviceSize(){return this._appliedDeviceSize;}
appliedDeviceScaleFactor(){return this._appliedDeviceScaleFactor;}
appliedUserAgentType(){return this._appliedUserAgentType;}
isFullHeight(){return!this._heightSetting.get();}
_isMobile(){switch(this._type){case Emulation.DeviceModeModel.Type.Device:return this._device.mobile();case Emulation.DeviceModeModel.Type.None:return false;case Emulation.DeviceModeModel.Type.Responsive:return this._uaSetting.get()===Emulation.DeviceModeModel.UA.Mobile||this._uaSetting.get()===Emulation.DeviceModeModel.UA.MobileNoTouch;}
return false;}
enabledSetting(){return Common.settings.createSetting('emulation.showDeviceMode',false);}
scaleSetting(){return this._scaleSetting;}
uaSetting(){return this._uaSetting;}
deviceScaleFactorSetting(){return this._deviceScaleFactorSetting;}
deviceOutlineSetting(){return this._deviceOutlineSetting;}
toolbarControlsEnabledSetting(){return this._toolbarControlsEnabledSetting;}
reset(){this._deviceScaleFactorSetting.set(0);this._scaleSetting.set(1);this.setWidth(400);this.setHeight(0);this._uaSetting.set(Emulation.DeviceModeModel.UA.Mobile);}
modelAdded(emulationModel){if(!this._emulationModel&&emulationModel.supportsDeviceEmulation()){this._emulationModel=emulationModel;if(this._onModelAvailable){const callback=this._onModelAvailable;this._onModelAvailable=null;callback();}}else{emulationModel.emulateTouch(this._touchEnabled,this._touchMobile);}}
modelRemoved(emulationModel){if(this._emulationModel===emulationModel)
this._emulationModel=null;}
inspectedURL(){return this._emulationModel?this._emulationModel.target().inspectedURL():null;}
_scaleSettingChanged(){this._calculateAndEmulate(false);}
_widthSettingChanged(){this._calculateAndEmulate(false);}
_heightSettingChanged(){this._calculateAndEmulate(false);}
_uaSettingChanged(){this._calculateAndEmulate(true);}
_deviceScaleFactorSettingChanged(){this._calculateAndEmulate(false);}
_deviceOutlineSettingChanged(){this._calculateAndEmulate(false);}
_preferredScaledWidth(){return Math.floor(this._preferredSize.width/(this._scaleSetting.get()||1));}
_preferredScaledHeight(){return Math.floor(this._preferredSize.height/(this._scaleSetting.get()||1));}
_currentOutline(){let outline=new UI.Insets(0,0,0,0);if(this._type!==Emulation.DeviceModeModel.Type.Device)
return outline;const orientation=this._device.orientationByName(this._mode.orientation);if(this._deviceOutlineSetting.get())
outline=orientation.outlineInsets||outline;return outline;}
_currentInsets(){if(this._type!==Emulation.DeviceModeModel.Type.Device)
return new UI.Insets(0,0,0,0);return this._mode.insets;}
_calculateAndEmulate(resetPageScaleFactor){if(!this._emulationModel)
this._onModelAvailable=this._calculateAndEmulate.bind(this,resetPageScaleFactor);const mobile=this._isMobile();if(this._type===Emulation.DeviceModeModel.Type.Device){const orientation=this._device.orientationByName(this._mode.orientation);const outline=this._currentOutline();const insets=this._currentInsets();this._fitScale=this._calculateFitScale(orientation.width,orientation.height,outline,insets);if(mobile){this._appliedUserAgentType=this._device.touch()?Emulation.DeviceModeModel.UA.Mobile:Emulation.DeviceModeModel.UA.MobileNoTouch;}else{this._appliedUserAgentType=this._device.touch()?Emulation.DeviceModeModel.UA.DesktopTouch:Emulation.DeviceModeModel.UA.Desktop;}
this._applyDeviceMetrics(new UI.Size(orientation.width,orientation.height),insets,outline,this._scaleSetting.get(),this._device.deviceScaleFactor,mobile,this._mode.orientation===Emulation.EmulatedDevice.Horizontal?Protocol.Emulation.ScreenOrientationType.LandscapePrimary:Protocol.Emulation.ScreenOrientationType.PortraitPrimary,resetPageScaleFactor);this._applyUserAgent(this._device.userAgent);this._applyTouch(this._device.touch(),mobile);}else if(this._type===Emulation.DeviceModeModel.Type.None){this._fitScale=this._calculateFitScale(this._availableSize.width,this._availableSize.height);this._appliedUserAgentType=Emulation.DeviceModeModel.UA.Desktop;this._applyDeviceMetrics(this._availableSize,new UI.Insets(0,0,0,0),new UI.Insets(0,0,0,0),1,0,mobile,null,resetPageScaleFactor);this._applyUserAgent('');this._applyTouch(false,false);}else if(this._type===Emulation.DeviceModeModel.Type.Responsive){let screenWidth=this._widthSetting.get();if(!screenWidth||screenWidth>this._preferredScaledWidth())
screenWidth=this._preferredScaledWidth();let screenHeight=this._heightSetting.get();if(!screenHeight||screenHeight>this._preferredScaledHeight())
screenHeight=this._preferredScaledHeight();const defaultDeviceScaleFactor=mobile?Emulation.DeviceModeModel.defaultMobileScaleFactor:0;this._fitScale=this._calculateFitScale(this._widthSetting.get(),this._heightSetting.get());this._appliedUserAgentType=this._uaSetting.get();this._applyDeviceMetrics(new UI.Size(screenWidth,screenHeight),new UI.Insets(0,0,0,0),new UI.Insets(0,0,0,0),this._scaleSetting.get(),this._deviceScaleFactorSetting.get()||defaultDeviceScaleFactor,mobile,screenHeight>=screenWidth?Protocol.Emulation.ScreenOrientationType.PortraitPrimary:Protocol.Emulation.ScreenOrientationType.LandscapePrimary,resetPageScaleFactor);this._applyUserAgent(mobile?Emulation.DeviceModeModel._defaultMobileUserAgent:'');this._applyTouch(this._uaSetting.get()===Emulation.DeviceModeModel.UA.DesktopTouch||this._uaSetting.get()===Emulation.DeviceModeModel.UA.Mobile,this._uaSetting.get()===Emulation.DeviceModeModel.UA.Mobile);}
const overlayModel=this._emulationModel?this._emulationModel.overlayModel():null;if(overlayModel)
overlayModel.setShowViewportSizeOnResize(this._type===Emulation.DeviceModeModel.Type.None);this.dispatchEventToListeners(Emulation.DeviceModeModel.Events.Updated);}
_calculateFitScale(screenWidth,screenHeight,outline,insets){const outlineWidth=outline?outline.left+outline.right:0;const outlineHeight=outline?outline.top+outline.bottom:0;const insetsWidth=insets?insets.left+insets.right:0;const insetsHeight=insets?insets.top+insets.bottom:0;let scale=Math.min(screenWidth?this._preferredSize.width/(screenWidth+outlineWidth):1,screenHeight?this._preferredSize.height/(screenHeight+outlineHeight):1);scale=Math.min(Math.floor(scale*100),100);let sharpScale=scale;while(sharpScale>scale*0.7){let sharp=true;if(screenWidth)
sharp=sharp&&Number.isInteger((screenWidth-insetsWidth)*sharpScale/100);if(screenHeight)
sharp=sharp&&Number.isInteger((screenHeight-insetsHeight)*sharpScale/100);if(sharp)
return sharpScale/100;sharpScale-=1;}
return scale/100;}
setSizeAndScaleToFit(width,height){this._scaleSetting.set(this._calculateFitScale(width,height));this.setWidth(width);this.setHeight(height);}
_applyUserAgent(userAgent){SDK.multitargetNetworkManager.setUserAgentOverride(userAgent);}
_applyDeviceMetrics(screenSize,insets,outline,scale,deviceScaleFactor,mobile,screenOrientation,resetPageScaleFactor){screenSize.width=Math.max(1,Math.floor(screenSize.width));screenSize.height=Math.max(1,Math.floor(screenSize.height));let pageWidth=screenSize.width-insets.left-insets.right;let pageHeight=screenSize.height-insets.top-insets.bottom;this._emulatedPageSize=new UI.Size(pageWidth,pageHeight);const positionX=insets.left;const positionY=insets.top;const screenOrientationAngle=screenOrientation===Protocol.Emulation.ScreenOrientationType.LandscapePrimary?90:0;this._appliedDeviceSize=screenSize;this._appliedDeviceScaleFactor=deviceScaleFactor||window.devicePixelRatio;this._screenRect=new UI.Rect(Math.max(0,(this._availableSize.width-screenSize.width*scale)/2),outline.top*scale,screenSize.width*scale,screenSize.height*scale);this._outlineRect=new UI.Rect(this._screenRect.left-outline.left*scale,0,(outline.left+screenSize.width+outline.right)*scale,(outline.top+screenSize.height+outline.bottom)*scale);this._visiblePageRect=new UI.Rect(positionX*scale,positionY*scale,Math.min(pageWidth*scale,this._availableSize.width-this._screenRect.left-positionX*scale),Math.min(pageHeight*scale,this._availableSize.height-this._screenRect.top-positionY*scale));this._scale=scale;if(scale===1&&this._availableSize.width>=screenSize.width&&this._availableSize.height>=screenSize.height){pageWidth=0;pageHeight=0;}
if(this._visiblePageRect.width===pageWidth*scale&&this._visiblePageRect.height===pageHeight*scale&&Number.isInteger(pageWidth*scale)&&Number.isInteger(pageHeight*scale)){pageWidth=0;pageHeight=0;}
if(!this._emulationModel)
return;if(resetPageScaleFactor)
this._emulationModel.resetPageScaleFactor();if(pageWidth||pageHeight||mobile||deviceScaleFactor||scale!==1||screenOrientation){const metrics={width:pageWidth,height:pageHeight,deviceScaleFactor:deviceScaleFactor,mobile:mobile,scale:scale,screenWidth:screenSize.width,screenHeight:screenSize.height,positionX:positionX,positionY:positionY,dontSetVisibleSize:true};if(screenOrientation)
metrics.screenOrientation={type:screenOrientation,angle:screenOrientationAngle};this._emulationModel.emulateDevice(metrics);}else{this._emulationModel.emulateDevice(null);}}
async captureScreenshot(fullSize,clip){const screenCaptureModel=this._emulationModel?this._emulationModel.target().model(SDK.ScreenCaptureModel):null;if(!screenCaptureModel)
return null;const overlayModel=this._emulationModel?this._emulationModel.overlayModel():null;if(overlayModel)
overlayModel.setShowViewportSizeOnResize(false);let deviceMetrics;if(fullSize){const metrics=await screenCaptureModel.fetchLayoutMetrics();if(!metrics)
return null;const contentHeight=Math.min((1<<14)/this._appliedDeviceScaleFactor,metrics.contentHeight);deviceMetrics={width:Math.floor(metrics.contentWidth),height:Math.floor(contentHeight),deviceScaleFactor:this._appliedDeviceScaleFactor,mobile:this._isMobile(),};clip={x:0,y:0,width:deviceMetrics.width,height:deviceMetrics.height,scale:1};if(this._device){const screenOrientation=this._mode.orientation===Emulation.EmulatedDevice.Horizontal?Protocol.Emulation.ScreenOrientationType.LandscapePrimary:Protocol.Emulation.ScreenOrientationType.PortraitPrimary;const screenOrientationAngle=screenOrientation===Protocol.Emulation.ScreenOrientationType.LandscapePrimary?90:0;deviceMetrics.screenOrientation={type:screenOrientation,angle:screenOrientationAngle};}
await this._emulationModel.resetPageScaleFactor();await this._emulationModel.emulateDevice(deviceMetrics);}
const screenshot=await screenCaptureModel.captureScreenshot('png',100,clip);if(fullSize){if(this._device){const orientation=this._device.orientationByName(this._mode.orientation);deviceMetrics.width=orientation.width;deviceMetrics.height=orientation.height;}else{deviceMetrics.width=0;deviceMetrics.height=0;}
await this._emulationModel.emulateDevice(deviceMetrics);}
this._calculateAndEmulate(false);return screenshot;}
_applyTouch(touchEnabled,mobile){this._touchEnabled=touchEnabled;this._touchMobile=mobile;for(const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
emulationModel.emulateTouch(touchEnabled,mobile);}};Emulation.DeviceModeModel.Events={Updated:'Updated'};Emulation.DeviceModeModel.Type={None:'None',Responsive:'Responsive',Device:'Device'};Emulation.DeviceModeModel.UA={Mobile:Common.UIString('Mobile'),MobileNoTouch:Common.UIString('Mobile (no touch)'),Desktop:Common.UIString('Desktop'),DesktopTouch:Common.UIString('Desktop (touch)')};Emulation.DeviceModeModel.MinDeviceSize=50;Emulation.DeviceModeModel.MaxDeviceSize=9999;Emulation.DeviceModeModel._defaultMobileUserAgent='Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36';Emulation.DeviceModeModel._defaultMobileUserAgent=SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(Emulation.DeviceModeModel._defaultMobileUserAgent);Emulation.DeviceModeModel.defaultMobileScaleFactor=2;;Emulation.DeviceModeToolbar=class{constructor(model,showMediaInspectorSetting,showRulersSetting){this._model=model;this._showMediaInspectorSetting=showMediaInspectorSetting;this._showRulersSetting=showRulersSetting;this._deviceOutlineSetting=this._model.deviceOutlineSetting();this._showDeviceScaleFactorSetting=Common.settings.createSetting('emulation.showDeviceScaleFactor',false);this._showDeviceScaleFactorSetting.addChangeListener(this._updateDeviceScaleFactorVisibility,this);this._showUserAgentTypeSetting=Common.settings.createSetting('emulation.showUserAgentType',false);this._showUserAgentTypeSetting.addChangeListener(this._updateUserAgentTypeVisibility,this);this._autoAdjustScaleSetting=Common.settings.createSetting('emulation.autoAdjustScale',true);this._lastMode=new Map();this._element=createElementWithClass('div','device-mode-toolbar');const leftContainer=this._element.createChild('div','device-mode-toolbar-spacer');leftContainer.createChild('div','device-mode-toolbar-spacer');const leftToolbar=new UI.Toolbar('',leftContainer);leftToolbar.makeWrappable();this._fillLeftToolbar(leftToolbar);const mainToolbar=new UI.Toolbar('',this._element);mainToolbar.makeWrappable();this._fillMainToolbar(mainToolbar);const rightContainer=this._element.createChild('div','device-mode-toolbar-spacer');const rightToolbar=new UI.Toolbar('device-mode-toolbar-fixed-size',rightContainer);rightToolbar.makeWrappable();this._fillRightToolbar(rightToolbar);const modeToolbar=new UI.Toolbar('device-mode-toolbar-fixed-size',rightContainer);modeToolbar.makeWrappable();this._fillModeToolbar(modeToolbar);rightContainer.createChild('div','device-mode-toolbar-spacer');const optionsToolbar=new UI.Toolbar('device-mode-toolbar-options',rightContainer);optionsToolbar.makeWrappable();this._fillOptionsToolbar(optionsToolbar);this._emulatedDevicesList=Emulation.EmulatedDevicesList.instance();this._emulatedDevicesList.addEventListener(Emulation.EmulatedDevicesList.Events.CustomDevicesUpdated,this._deviceListChanged,this);this._emulatedDevicesList.addEventListener(Emulation.EmulatedDevicesList.Events.StandardDevicesUpdated,this._deviceListChanged,this);this._persistenceSetting=Common.settings.createSetting('emulation.deviceModeValue',{device:'',orientation:'',mode:''});this._model.toolbarControlsEnabledSetting().addChangeListener(updateToolbarsEnabled);updateToolbarsEnabled();function updateToolbarsEnabled(){const enabled=model.toolbarControlsEnabledSetting().get();leftToolbar.setEnabled(enabled);mainToolbar.setEnabled(enabled);rightToolbar.setEnabled(enabled);modeToolbar.setEnabled(enabled);optionsToolbar.setEnabled(enabled);}}
_fillLeftToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._deviceSelectItem=new UI.ToolbarMenuButton(this._appendDeviceMenuItems.bind(this));this._deviceSelectItem.setGlyph('');this._deviceSelectItem.turnIntoSelect(95);this._deviceSelectItem.setDarkText();toolbar.appendToolbarItem(this._deviceSelectItem);}
_fillMainToolbar(toolbar){const widthInput=UI.createInput('device-mode-size-input','text');widthInput.maxLength=4;widthInput.title=Common.UIString('Width');this._updateWidthInput=UI.bindInput(widthInput,this._applyWidth.bind(this),Emulation.DeviceModeModel.deviceSizeValidator,true);this._widthInput=widthInput;this._widthItem=this._wrapToolbarItem(widthInput);toolbar.appendToolbarItem(this._widthItem);const xElement=createElementWithClass('div','device-mode-x');xElement.textContent='\u00D7';this._xItem=this._wrapToolbarItem(xElement);toolbar.appendToolbarItem(this._xItem);const heightInput=UI.createInput('device-mode-size-input','text');heightInput.maxLength=4;heightInput.title=Common.UIString('Height (leave empty for full)');this._updateHeightInput=UI.bindInput(heightInput,this._applyHeight.bind(this),validateHeight,true);this._heightInput=heightInput;this._heightItem=this._wrapToolbarItem(heightInput);toolbar.appendToolbarItem(this._heightItem);function validateHeight(value){return!value||Emulation.DeviceModeModel.deviceSizeValidator(value);}}
_applyWidth(value){const width=value?Number(value):0;this._model.setWidthAndScaleToFit(width);}
_applyHeight(value){const height=value?Number(value):0;this._model.setHeightAndScaleToFit(height);}
_fillRightToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._scaleItem=new UI.ToolbarMenuButton(this._appendScaleMenuItems.bind(this));this._scaleItem.setTitle(Common.UIString('Zoom'));this._scaleItem.setGlyph('');this._scaleItem.turnIntoSelect();this._scaleItem.setDarkText();toolbar.appendToolbarItem(this._scaleItem);toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._deviceScaleItem=new UI.ToolbarMenuButton(this._appendDeviceScaleMenuItems.bind(this));this._deviceScaleItem.setVisible(this._showDeviceScaleFactorSetting.get());this._deviceScaleItem.setTitle(Common.UIString('Device pixel ratio'));this._deviceScaleItem.setGlyph('');this._deviceScaleItem.turnIntoSelect();this._deviceScaleItem.setDarkText();toolbar.appendToolbarItem(this._deviceScaleItem);toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._uaItem=new UI.ToolbarMenuButton(this._appendUserAgentMenuItems.bind(this));this._uaItem.setVisible(this._showUserAgentTypeSetting.get());this._uaItem.setTitle(Common.UIString('Device type'));this._uaItem.setGlyph('');this._uaItem.turnIntoSelect();this._uaItem.setDarkText();toolbar.appendToolbarItem(this._uaItem);this._throttlingConditionsItem=MobileThrottling.throttlingManager().createMobileThrottlingButton();toolbar.appendToolbarItem(this._throttlingConditionsItem);}
_fillModeToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));this._modeButton=new UI.ToolbarButton('','largeicon-rotate-screen');this._modeButton.addEventListener(UI.ToolbarButton.Events.Click,this._modeMenuClicked,this);toolbar.appendToolbarItem(this._modeButton);}
_fillOptionsToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass('div','device-mode-empty-toolbar-element')));const moreOptionsButton=new UI.ToolbarMenuButton(this._appendOptionsMenuItems.bind(this));moreOptionsButton.setTitle(Common.UIString('More options'));toolbar.appendToolbarItem(moreOptionsButton);}
_appendScaleMenuItems(contextMenu){if(this._model.type()===Emulation.DeviceModeModel.Type.Device){contextMenu.footerSection().appendItem(Common.UIString('Fit to window (%.0f%%)',this._model.fitScale()*100),this._onScaleMenuChanged.bind(this,this._model.fitScale()),false);}
contextMenu.footerSection().appendCheckboxItem(ls`Auto-adjust zoom`,this._onAutoAdjustScaleChanged.bind(this),this._autoAdjustScaleSetting.get());const boundAppendScaleItem=appendScaleItem.bind(this);boundAppendScaleItem(Common.UIString('50%'),0.5);boundAppendScaleItem(Common.UIString('75%'),0.75);boundAppendScaleItem(Common.UIString('100%'),1);boundAppendScaleItem(Common.UIString('125%'),1.25);boundAppendScaleItem(Common.UIString('150%'),1.5);function appendScaleItem(title,value){contextMenu.defaultSection().appendCheckboxItem(title,this._onScaleMenuChanged.bind(this,value),this._model.scaleSetting().get()===value,false);}}
_onScaleMenuChanged(value){this._model.scaleSetting().set(value);}
_onAutoAdjustScaleChanged(){this._autoAdjustScaleSetting.set(!this._autoAdjustScaleSetting.get());}
_appendDeviceScaleMenuItems(contextMenu){const deviceScaleFactorSetting=this._model.deviceScaleFactorSetting();const defaultValue=this._model.uaSetting().get()===Emulation.DeviceModeModel.UA.Mobile||this._model.uaSetting().get()===Emulation.DeviceModeModel.UA.MobileNoTouch?Emulation.DeviceModeModel.defaultMobileScaleFactor:window.devicePixelRatio;appendDeviceScaleFactorItem(contextMenu.headerSection(),Common.UIString('Default: %.1f',defaultValue),0);appendDeviceScaleFactorItem(contextMenu.defaultSection(),Common.UIString('1'),1);appendDeviceScaleFactorItem(contextMenu.defaultSection(),Common.UIString('2'),2);appendDeviceScaleFactorItem(contextMenu.defaultSection(),Common.UIString('3'),3);function appendDeviceScaleFactorItem(section,title,value){section.appendCheckboxItem(title,deviceScaleFactorSetting.set.bind(deviceScaleFactorSetting,value),deviceScaleFactorSetting.get()===value);}}
_appendUserAgentMenuItems(contextMenu){const uaSetting=this._model.uaSetting();appendUAItem(Emulation.DeviceModeModel.UA.Mobile,Emulation.DeviceModeModel.UA.Mobile);appendUAItem(Emulation.DeviceModeModel.UA.MobileNoTouch,Emulation.DeviceModeModel.UA.MobileNoTouch);appendUAItem(Emulation.DeviceModeModel.UA.Desktop,Emulation.DeviceModeModel.UA.Desktop);appendUAItem(Emulation.DeviceModeModel.UA.DesktopTouch,Emulation.DeviceModeModel.UA.DesktopTouch);function appendUAItem(title,value){contextMenu.defaultSection().appendCheckboxItem(title,uaSetting.set.bind(uaSetting,value),uaSetting.get()===value);}}
_appendOptionsMenuItems(contextMenu){const model=this._model;appendToggleItem(contextMenu.headerSection(),this._deviceOutlineSetting,Common.UIString('Hide device frame'),Common.UIString('Show device frame'),model.type()!==Emulation.DeviceModeModel.Type.Device);appendToggleItem(contextMenu.headerSection(),this._showMediaInspectorSetting,Common.UIString('Hide media queries'),Common.UIString('Show media queries'));appendToggleItem(contextMenu.headerSection(),this._showRulersSetting,Common.UIString('Hide rulers'),Common.UIString('Show rulers'));appendToggleItem(contextMenu.defaultSection(),this._showDeviceScaleFactorSetting,Common.UIString('Remove device pixel ratio'),Common.UIString('Add device pixel ratio'));appendToggleItem(contextMenu.defaultSection(),this._showUserAgentTypeSetting,Common.UIString('Remove device type'),Common.UIString('Add device type'));contextMenu.appendItemsAtLocation('deviceModeMenu');contextMenu.footerSection().appendItem(Common.UIString('Reset to defaults'),this._reset.bind(this));contextMenu.footerSection().appendItem(ls`Close DevTools`,InspectorFrontendHost.closeWindow.bind(InspectorFrontendHost));function appendToggleItem(section,setting,title1,title2,disabled){if(typeof disabled==='undefined')
disabled=model.type()===Emulation.DeviceModeModel.Type.None;section.appendItem(setting.get()?title1:title2,setting.set.bind(setting,!setting.get()),disabled);}}
_reset(){this._deviceOutlineSetting.set(false);this._showDeviceScaleFactorSetting.set(false);this._showUserAgentTypeSetting.set(false);this._showMediaInspectorSetting.set(false);this._showRulersSetting.set(false);this._model.reset();}
_wrapToolbarItem(element){const container=createElement('div');const shadowRoot=UI.createShadowRootWithCoreStyles(container,'emulation/deviceModeToolbar.css');shadowRoot.appendChild(element);return new UI.ToolbarItem(container);}
_emulateDevice(device){const scale=this._autoAdjustScaleSetting.get()?undefined:this._model.scaleSetting().get();this._model.emulate(Emulation.DeviceModeModel.Type.Device,device,this._lastMode.get(device)||device.modes[0],scale);}
_switchToResponsive(){this._model.emulate(Emulation.DeviceModeModel.Type.Responsive,null,null);}
_filterDevices(devices){devices=devices.filter(function(d){return d.show();});devices.sort(Emulation.EmulatedDevice.deviceComparator);return devices;}
_standardDevices(){return this._filterDevices(this._emulatedDevicesList.standard());}
_customDevices(){return this._filterDevices(this._emulatedDevicesList.custom());}
_allDevices(){return this._standardDevices().concat(this._customDevices());}
_appendDeviceMenuItems(contextMenu){contextMenu.headerSection().appendCheckboxItem(Common.UIString('Responsive'),this._switchToResponsive.bind(this),this._model.type()===Emulation.DeviceModeModel.Type.Responsive,false);appendGroup.call(this,this._standardDevices());appendGroup.call(this,this._customDevices());contextMenu.footerSection().appendItem(Common.UIString('Edit\u2026'),this._emulatedDevicesList.revealCustomSetting.bind(this._emulatedDevicesList),false);function appendGroup(devices){if(!devices.length)
return;const section=contextMenu.section();for(const device of devices){section.appendCheckboxItem(device.title,this._emulateDevice.bind(this,device),this._model.device()===device,false);}}}
_deviceListChanged(){const device=this._model.device();if(!device)
return;const devices=this._allDevices();if(devices.indexOf(device)===-1){if(devices.length)
this._emulateDevice(devices[0]);else
this._model.emulate(Emulation.DeviceModeModel.Type.Responsive,null,null);}}
_updateDeviceScaleFactorVisibility(){this._deviceScaleItem.setVisible(this._showDeviceScaleFactorSetting.get());}
_updateUserAgentTypeVisibility(){this._uaItem.setVisible(this._showUserAgentTypeSetting.get());}
_modeMenuClicked(event){const device=this._model.device();const model=this._model;const autoAdjustScaleSetting=this._autoAdjustScaleSetting;if(model.type()===Emulation.DeviceModeModel.Type.Responsive){const appliedSize=model.appliedDeviceSize();if(autoAdjustScaleSetting.get()){model.setSizeAndScaleToFit(appliedSize.height,appliedSize.width);}else{model.setWidth(appliedSize.height);model.setHeight(appliedSize.width);}
return;}
if(device.modes.length===2&&device.modes[0].orientation!==device.modes[1].orientation){const scale=autoAdjustScaleSetting.get()?undefined:model.scaleSetting().get();model.emulate(model.type(),model.device(),model.mode()===device.modes[0]?device.modes[1]:device.modes[0],scale);return;}
const contextMenu=new UI.ContextMenu((event.data),false,this._modeButton.element.totalOffsetLeft(),this._modeButton.element.totalOffsetTop()+this._modeButton.element.offsetHeight);addOrientation(Emulation.EmulatedDevice.Vertical,Common.UIString('Portrait'));addOrientation(Emulation.EmulatedDevice.Horizontal,Common.UIString('Landscape'));contextMenu.show();function addOrientation(orientation,title){const modes=device.modesForOrientation(orientation);if(!modes.length)
return;if(modes.length===1){addMode(modes[0],title);}else{for(let index=0;index<modes.length;index++)
addMode(modes[index],title+' \u2013 '+modes[index].title);}}
function addMode(mode,title){contextMenu.defaultSection().appendCheckboxItem(title,applyMode.bind(null,mode),model.mode()===mode,false);}
function applyMode(mode){const scale=autoAdjustScaleSetting.get()?undefined:model.scaleSetting().get();model.emulate(model.type(),model.device(),mode,scale);}}
element(){return this._element;}
update(){if(this._model.type()!==this._cachedModelType){this._cachedModelType=this._model.type();this._widthInput.disabled=this._model.type()!==Emulation.DeviceModeModel.Type.Responsive;this._heightInput.disabled=this._model.type()!==Emulation.DeviceModeModel.Type.Responsive;this._deviceScaleItem.setEnabled(this._model.type()===Emulation.DeviceModeModel.Type.Responsive);this._uaItem.setEnabled(this._model.type()===Emulation.DeviceModeModel.Type.Responsive);if(this._model.type()===Emulation.DeviceModeModel.Type.Responsive){this._modeButton.setEnabled(true);this._modeButton.setTitle(ls`Rotate`);}else{this._modeButton.setEnabled(false);}}
const size=this._model.appliedDeviceSize();this._updateHeightInput(this._model.type()===Emulation.DeviceModeModel.Type.Responsive&&this._model.isFullHeight()?'':String(size.height));this._updateWidthInput(String(size.width));this._heightInput.placeholder=size.height;if(this._model.scale()!==this._cachedScale){this._scaleItem.setText(Common.UIString('%.0f%%',this._model.scale()*100));this._cachedScale=this._model.scale();}
const deviceScale=this._model.appliedDeviceScaleFactor();if(deviceScale!==this._cachedDeviceScale){this._deviceScaleItem.setText(Common.UIString('DPR: %.1f',deviceScale));this._cachedDeviceScale=deviceScale;}
const uaType=this._model.appliedUserAgentType();if(uaType!==this._cachedUaType){this._uaItem.setText(uaType);this._cachedUaType=uaType;}
let deviceItemTitle=Common.UIString('None');if(this._model.type()===Emulation.DeviceModeModel.Type.Responsive)
deviceItemTitle=Common.UIString('Responsive');if(this._model.type()===Emulation.DeviceModeModel.Type.Device)
deviceItemTitle=this._model.device().title;this._deviceSelectItem.setText(deviceItemTitle);if(this._model.device()!==this._cachedModelDevice){const device=this._model.device();if(device){const modeCount=device?device.modes.length:0;this._modeButton.setEnabled(modeCount>=2);this._modeButton.setTitle(modeCount===2?Common.UIString('Rotate'):Common.UIString('Screen options'));}
this._cachedModelDevice=device;}
if(this._model.type()===Emulation.DeviceModeModel.Type.Device){this._lastMode.set((this._model.device()),(this._model.mode()));}
if(this._model.mode()!==this._cachedModelMode&&this._model.type()!==Emulation.DeviceModeModel.Type.None){this._cachedModelMode=this._model.mode();const value=this._persistenceSetting.get();if(this._model.device()){value.device=this._model.device().title;value.orientation=this._model.mode()?this._model.mode().orientation:'';value.mode=this._model.mode()?this._model.mode().title:'';}else{value.device='';value.orientation='';value.mode='';}
this._persistenceSetting.set(value);}}
restore(){for(const device of this._allDevices()){if(device.title===this._persistenceSetting.get().device){for(const mode of device.modes){if(mode.orientation===this._persistenceSetting.get().orientation&&mode.title===this._persistenceSetting.get().mode){this._lastMode.set(device,mode);this._emulateDevice(device);return;}}}}
this._model.emulate(Emulation.DeviceModeModel.Type.Responsive,null,null);}};;Emulation.DeviceModeView=class extends UI.VBox{constructor(){super(true);this.setMinimumSize(150,150);this.element.classList.add('device-mode-view');this.registerRequiredCSS('emulation/deviceModeView.css');UI.Tooltip.addNativeOverrideContainer(this.contentElement);this._model=self.singleton(Emulation.DeviceModeModel);this._model.addEventListener(Emulation.DeviceModeModel.Events.Updated,this._updateUI,this);this._mediaInspector=new Emulation.MediaQueryInspector(()=>this._model.appliedDeviceSize().width,this._model.setWidth.bind(this._model));this._showMediaInspectorSetting=Common.settings.moduleSetting('showMediaQueryInspector');this._showMediaInspectorSetting.addChangeListener(this._updateUI,this);this._showRulersSetting=Common.settings.moduleSetting('emulation.showRulers');this._showRulersSetting.addChangeListener(this._updateUI,this);this._topRuler=new Emulation.DeviceModeView.Ruler(true,this._model.setWidthAndScaleToFit.bind(this._model));this._topRuler.element.classList.add('device-mode-ruler-top');this._leftRuler=new Emulation.DeviceModeView.Ruler(false,this._model.setHeightAndScaleToFit.bind(this._model));this._leftRuler.element.classList.add('device-mode-ruler-left');this._createUI();UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._zoomChanged,this);}
_createUI(){this._toolbar=new Emulation.DeviceModeToolbar(this._model,this._showMediaInspectorSetting,this._showRulersSetting);this.contentElement.appendChild(this._toolbar.element());this._contentClip=this.contentElement.createChild('div','device-mode-content-clip vbox');this._responsivePresetsContainer=this._contentClip.createChild('div','device-mode-presets-container');this._populatePresetsContainer();this._mediaInspectorContainer=this._contentClip.createChild('div','device-mode-media-container');this._contentArea=this._contentClip.createChild('div','device-mode-content-area');this._outlineImage=this._contentArea.createChild('img','device-mode-outline-image hidden fill');this._outlineImage.addEventListener('load',this._onImageLoaded.bind(this,this._outlineImage,true),false);this._outlineImage.addEventListener('error',this._onImageLoaded.bind(this,this._outlineImage,false),false);this._screenArea=this._contentArea.createChild('div','device-mode-screen-area');this._screenImage=this._screenArea.createChild('img','device-mode-screen-image hidden');this._screenImage.addEventListener('load',this._onImageLoaded.bind(this,this._screenImage,true),false);this._screenImage.addEventListener('error',this._onImageLoaded.bind(this,this._screenImage,false),false);this._bottomRightResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-bottom-right-resizer');this._bottomRightResizerElement.createChild('div','');this._createResizer(this._bottomRightResizerElement,2,1);this._bottomLeftResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-bottom-left-resizer');this._bottomLeftResizerElement.createChild('div','');this._createResizer(this._bottomLeftResizerElement,-2,1);this._rightResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-right-resizer');this._rightResizerElement.createChild('div','');this._createResizer(this._rightResizerElement,2,0);this._leftResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-left-resizer');this._leftResizerElement.createChild('div','');this._createResizer(this._leftResizerElement,-2,0);this._bottomResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-bottom-resizer');this._bottomResizerElement.createChild('div','');this._createResizer(this._bottomResizerElement,0,1);this._bottomResizerElement.addEventListener('dblclick',this._model.setHeight.bind(this._model,0),false);this._bottomResizerElement.title=Common.UIString('Double-click for full height');this._pageArea=this._screenArea.createChild('div','device-mode-page-area');this._pageArea.createChild('slot');}
_populatePresetsContainer(){const sizes=[320,375,425,768,1024,1440,2560];const titles=[Common.UIString('Mobile S'),Common.UIString('Mobile M'),Common.UIString('Mobile L'),Common.UIString('Tablet'),Common.UIString('Laptop'),Common.UIString('Laptop L'),Common.UIString('4K')];this._presetBlocks=[];const inner=this._responsivePresetsContainer.createChild('div','device-mode-presets-container-inner');for(let i=sizes.length-1;i>=0;--i){const outer=inner.createChild('div','fill device-mode-preset-bar-outer');const block=outer.createChild('div','device-mode-preset-bar');block.createChild('span').textContent=titles[i]+' \u2013 '+sizes[i]+'px';block.addEventListener('click',applySize.bind(this,sizes[i]),false);block.__width=sizes[i];this._presetBlocks.push(block);}
function applySize(width,e){this._model.emulate(Emulation.DeviceModeModel.Type.Responsive,null,null);this._model.setWidthAndScaleToFit(width);e.consume();}}
_createResizer(element,widthFactor,heightFactor){const resizer=new UI.ResizerWidget();resizer.addElement(element);let cursor=widthFactor?'ew-resize':'ns-resize';if(widthFactor*heightFactor>0)
cursor='nwse-resize';if(widthFactor*heightFactor<0)
cursor='nesw-resize';resizer.setCursor(cursor);resizer.addEventListener(UI.ResizerWidget.Events.ResizeStart,this._onResizeStart,this);resizer.addEventListener(UI.ResizerWidget.Events.ResizeUpdate,this._onResizeUpdate.bind(this,widthFactor,heightFactor));resizer.addEventListener(UI.ResizerWidget.Events.ResizeEnd,this._onResizeEnd,this);return resizer;}
_onResizeStart(event){this._slowPositionStart=null;this._resizeStart=this._model.screenRect().size();}
_onResizeUpdate(widthFactor,heightFactor,event){if(event.data.shiftKey!==!!this._slowPositionStart)
this._slowPositionStart=event.data.shiftKey?{x:event.data.currentX,y:event.data.currentY}:null;let cssOffsetX=event.data.currentX-event.data.startX;let cssOffsetY=event.data.currentY-event.data.startY;if(this._slowPositionStart){cssOffsetX=(event.data.currentX-this._slowPositionStart.x)/10+this._slowPositionStart.x-event.data.startX;cssOffsetY=(event.data.currentY-this._slowPositionStart.y)/10+this._slowPositionStart.y-event.data.startY;}
if(widthFactor){const dipOffsetX=cssOffsetX*UI.zoomManager.zoomFactor();let newWidth=this._resizeStart.width+dipOffsetX*widthFactor;newWidth=Math.round(newWidth/this._model.scale());if(newWidth>=Emulation.DeviceModeModel.MinDeviceSize&&newWidth<=Emulation.DeviceModeModel.MaxDeviceSize)
this._model.setWidth(newWidth);}
if(heightFactor){const dipOffsetY=cssOffsetY*UI.zoomManager.zoomFactor();let newHeight=this._resizeStart.height+dipOffsetY*heightFactor;newHeight=Math.round(newHeight/this._model.scale());if(newHeight>=Emulation.DeviceModeModel.MinDeviceSize&&newHeight<=Emulation.DeviceModeModel.MaxDeviceSize)
this._model.setHeight(newHeight);}}
_onResizeEnd(event){delete this._resizeStart;Host.userMetrics.actionTaken(Host.UserMetrics.Action.ResizedViewInResponsiveMode);}
_updateUI(){function applyRect(element,rect){element.style.left=rect.left+'px';element.style.top=rect.top+'px';element.style.width=rect.width+'px';element.style.height=rect.height+'px';}
if(!this.isShowing())
return;const zoomFactor=UI.zoomManager.zoomFactor();let callDoResize=false;const showRulers=this._showRulersSetting.get()&&this._model.type()!==Emulation.DeviceModeModel.Type.None;let contentAreaResized=false;let updateRulers=false;const cssScreenRect=this._model.screenRect().scale(1/zoomFactor);if(!cssScreenRect.isEqual(this._cachedCssScreenRect)){applyRect(this._screenArea,cssScreenRect);updateRulers=true;callDoResize=true;this._cachedCssScreenRect=cssScreenRect;}
const cssVisiblePageRect=this._model.visiblePageRect().scale(1/zoomFactor);if(!cssVisiblePageRect.isEqual(this._cachedCssVisiblePageRect)){applyRect(this._pageArea,cssVisiblePageRect);callDoResize=true;this._cachedCssVisiblePageRect=cssVisiblePageRect;}
const outlineRect=this._model.outlineRect().scale(1/zoomFactor);if(!outlineRect.isEqual(this._cachedOutlineRect)){applyRect(this._outlineImage,outlineRect);callDoResize=true;this._cachedOutlineRect=outlineRect;}
this._contentClip.classList.toggle('device-mode-outline-visible',!!this._model.outlineImage());const resizable=this._model.type()===Emulation.DeviceModeModel.Type.Responsive;if(resizable!==this._cachedResizable){this._rightResizerElement.classList.toggle('hidden',!resizable);this._leftResizerElement.classList.toggle('hidden',!resizable);this._bottomResizerElement.classList.toggle('hidden',!resizable);this._bottomRightResizerElement.classList.toggle('hidden',!resizable);this._bottomLeftResizerElement.classList.toggle('hidden',!resizable);this._cachedResizable=resizable;}
const mediaInspectorVisible=this._showMediaInspectorSetting.get()&&this._model.type()!==Emulation.DeviceModeModel.Type.None;if(mediaInspectorVisible!==this._cachedMediaInspectorVisible){if(mediaInspectorVisible)
this._mediaInspector.show(this._mediaInspectorContainer);else
this._mediaInspector.detach();contentAreaResized=true;callDoResize=true;this._cachedMediaInspectorVisible=mediaInspectorVisible;}
if(showRulers!==this._cachedShowRulers){this._contentClip.classList.toggle('device-mode-rulers-visible',showRulers);if(showRulers){this._topRuler.show(this._contentArea);this._leftRuler.show(this._contentArea);}else{this._topRuler.detach();this._leftRuler.detach();}
contentAreaResized=true;callDoResize=true;this._cachedShowRulers=showRulers;}
if(this._model.scale()!==this._cachedScale){updateRulers=true;callDoResize=true;for(const block of this._presetBlocks)
block.style.width=block.__width*this._model.scale()+'px';this._cachedScale=this._model.scale();}
this._toolbar.update();this._loadImage(this._screenImage,this._model.screenImage());this._loadImage(this._outlineImage,this._model.outlineImage());this._mediaInspector.setAxisTransform(this._model.scale());if(callDoResize)
this.doResize();if(updateRulers){this._topRuler.render(this._model.scale());this._leftRuler.render(this._model.scale());this._topRuler.element.positionAt(this._cachedCssScreenRect?this._cachedCssScreenRect.left:0,this._cachedCssScreenRect?this._cachedCssScreenRect.top:0);this._leftRuler.element.positionAt(this._cachedCssScreenRect?this._cachedCssScreenRect.left:0,this._cachedCssScreenRect?this._cachedCssScreenRect.top:0);}
if(contentAreaResized)
this._contentAreaResized();}
_loadImage(element,srcset){if(element.getAttribute('srcset')===srcset)
return;element.setAttribute('srcset',srcset);if(!srcset)
element.classList.toggle('hidden',true);}
_onImageLoaded(element,success){element.classList.toggle('hidden',!success);}
setNonEmulatedAvailableSize(element){if(this._model.type()!==Emulation.DeviceModeModel.Type.None)
return;const zoomFactor=UI.zoomManager.zoomFactor();const rect=element.getBoundingClientRect();const availableSize=new UI.Size(Math.max(rect.width*zoomFactor,1),Math.max(rect.height*zoomFactor,1));this._model.setAvailableSize(availableSize,availableSize);}
_contentAreaResized(){const zoomFactor=UI.zoomManager.zoomFactor();const rect=this._contentArea.getBoundingClientRect();const availableSize=new UI.Size(Math.max(rect.width*zoomFactor,1),Math.max(rect.height*zoomFactor,1));const preferredSize=new UI.Size(Math.max((rect.width-2*this._handleWidth)*zoomFactor,1),Math.max((rect.height-this._handleHeight)*zoomFactor,1));this._model.setAvailableSize(availableSize,preferredSize);}
_measureHandles(){const hidden=this._rightResizerElement.classList.contains('hidden');this._rightResizerElement.classList.toggle('hidden',false);this._bottomResizerElement.classList.toggle('hidden',false);this._handleWidth=this._rightResizerElement.offsetWidth;this._handleHeight=this._bottomResizerElement.offsetHeight;this._rightResizerElement.classList.toggle('hidden',hidden);this._bottomResizerElement.classList.toggle('hidden',hidden);}
_zoomChanged(){delete this._handleWidth;delete this._handleHeight;if(this.isShowing()){this._measureHandles();this._contentAreaResized();}}
onResize(){if(this.isShowing())
this._contentAreaResized();}
wasShown(){this._measureHandles();this._toolbar.restore();}
willHide(){this._model.emulate(Emulation.DeviceModeModel.Type.None,null,null);}
async captureScreenshot(){const screenshot=await this._model.captureScreenshot(false);if(screenshot===null)
return;const pageImage=new Image();pageImage.src='data:image/png;base64,'+screenshot;pageImage.onload=async()=>{const scale=pageImage.naturalWidth/this._model.screenRect().width;const outlineRect=this._model.outlineRect().scale(scale);const screenRect=this._model.screenRect().scale(scale);const visiblePageRect=this._model.visiblePageRect().scale(scale);const contentLeft=screenRect.left+visiblePageRect.left-outlineRect.left;const contentTop=screenRect.top+visiblePageRect.top-outlineRect.top;const canvas=createElement('canvas');canvas.width=Math.floor(outlineRect.width);canvas.height=Math.floor(outlineRect.height);const ctx=canvas.getContext('2d');ctx.imageSmoothingEnabled=false;if(this._model.outlineImage())
await this._paintImage(ctx,this._model.outlineImage(),outlineRect.relativeTo(outlineRect));if(this._model.screenImage())
await this._paintImage(ctx,this._model.screenImage(),screenRect.relativeTo(outlineRect));ctx.drawImage(pageImage,Math.floor(contentLeft),Math.floor(contentTop));this._saveScreenshot(canvas);};}
async captureFullSizeScreenshot(){const screenshot=await this._model.captureScreenshot(true);if(screenshot===null)
return;return this._saveScreenshotBase64(screenshot);}
async captureAreaScreenshot(clip){const screenshot=await this._model.captureScreenshot(false,clip);if(screenshot===null)
return;return this._saveScreenshotBase64(screenshot);}
_saveScreenshotBase64(screenshot){const pageImage=new Image();pageImage.src='data:image/png;base64,'+screenshot;pageImage.onload=()=>{const canvas=createElement('canvas');canvas.width=pageImage.naturalWidth;canvas.height=pageImage.naturalHeight;const ctx=canvas.getContext('2d');ctx.imageSmoothingEnabled=false;ctx.drawImage(pageImage,0,0);this._saveScreenshot(canvas);};}
_paintImage(ctx,src,rect){return new Promise(fulfill=>{const image=new Image();image.crossOrigin='Anonymous';image.srcset=src;image.onerror=fulfill;image.onload=()=>{ctx.drawImage(image,rect.left,rect.top,rect.width,rect.height);fulfill();};});}
_saveScreenshot(canvas){const url=this._model.inspectedURL();let fileName=url?url.trimURL().removeURLFragment():'';if(this._model.type()===Emulation.DeviceModeModel.Type.Device)
fileName+=Common.UIString('(%s)',this._model.device().title);const link=createElement('a');link.download=fileName+'.png';canvas.toBlob(blob=>{link.href=URL.createObjectURL(blob);link.click();});}};Emulation.DeviceModeView.Ruler=class extends UI.VBox{constructor(horizontal,applyCallback){super();this.element.classList.add('device-mode-ruler');this._contentElement=this.element.createChild('div','device-mode-ruler-content').createChild('div','device-mode-ruler-inner');this._horizontal=horizontal;this._scale=1;this._count=0;this._throttler=new Common.Throttler(0);this._applyCallback=applyCallback;}
render(scale){this._scale=scale;this._throttler.schedule(this._update.bind(this));}
onResize(){this._throttler.schedule(this._update.bind(this));}
_update(){const zoomFactor=UI.zoomManager.zoomFactor();const size=this._horizontal?this._contentElement.offsetWidth:this._contentElement.offsetHeight;if(this._scale!==this._renderedScale||zoomFactor!==this._renderedZoomFactor){this._contentElement.removeChildren();this._count=0;this._renderedScale=this._scale;this._renderedZoomFactor=zoomFactor;}
const dipSize=size*zoomFactor/this._scale;const count=Math.ceil(dipSize/5);let step=1;if(this._scale<0.8)
step=2;if(this._scale<0.6)
step=4;if(this._scale<0.4)
step=8;if(this._scale<0.2)
step=16;if(this._scale<0.1)
step=32;for(let i=count;i<this._count;i++){if(!(i%step))
this._contentElement.lastChild.remove();}
for(let i=this._count;i<count;i++){if(i%step)
continue;const marker=this._contentElement.createChild('div','device-mode-ruler-marker');if(i){if(this._horizontal)
marker.style.left=(5*i)*this._scale/zoomFactor+'px';else
marker.style.top=(5*i)*this._scale/zoomFactor+'px';if(!(i%20)){const text=marker.createChild('div','device-mode-ruler-text');text.textContent=i*5;text.addEventListener('click',this._onMarkerClick.bind(this,i*5),false);}}
if(!(i%10))
marker.classList.add('device-mode-ruler-marker-large');else if(!(i%5))
marker.classList.add('device-mode-ruler-marker-medium');}
this._count=count;return Promise.resolve();}
_onMarkerClick(size){this._applyCallback.call(null,size);}};;Emulation.DeviceModeWrapper=class extends UI.VBox{constructor(inspectedPagePlaceholder){super();Emulation.DeviceModeView._wrapperInstance=this;this._inspectedPagePlaceholder=inspectedPagePlaceholder;this._deviceModeView=null;this._toggleDeviceModeAction=UI.actionRegistry.action('emulation.toggle-device-mode');const model=self.singleton(Emulation.DeviceModeModel);this._showDeviceModeSetting=model.enabledSetting();this._showDeviceModeSetting.setRequiresUserAction(!!Runtime.queryParam('hasOtherClients'));this._showDeviceModeSetting.addChangeListener(this._update.bind(this,false));SDK.targetManager.addModelListener(SDK.OverlayModel,SDK.OverlayModel.Events.ScreenshotRequested,this._screenshotRequestedFromOverlay,this);this._update(true);}
_toggleDeviceMode(){this._showDeviceModeSetting.set(!this._showDeviceModeSetting.get());}
_captureScreenshot(fullSize,clip){if(!this._deviceModeView)
this._deviceModeView=new Emulation.DeviceModeView();this._deviceModeView.setNonEmulatedAvailableSize(this._inspectedPagePlaceholder.element);if(fullSize)
this._deviceModeView.captureFullSizeScreenshot();else if(clip)
this._deviceModeView.captureAreaScreenshot(clip);else
this._deviceModeView.captureScreenshot();return true;}
_screenshotRequestedFromOverlay(event){const clip=(event.data);this._captureScreenshot(false,clip);}
_update(force){this._toggleDeviceModeAction.setToggled(this._showDeviceModeSetting.get());if(!force){const showing=this._deviceModeView&&this._deviceModeView.isShowing();if(this._showDeviceModeSetting.get()===showing)
return;}
if(this._showDeviceModeSetting.get()){if(!this._deviceModeView)
this._deviceModeView=new Emulation.DeviceModeView();this._deviceModeView.show(this.element);this._inspectedPagePlaceholder.clearMinimumSize();this._inspectedPagePlaceholder.show(this._deviceModeView.element);}else{if(this._deviceModeView)
this._deviceModeView.detach();this._inspectedPagePlaceholder.restoreMinimumSize();this._inspectedPagePlaceholder.show(this.element);}}};Emulation.DeviceModeView._wrapperInstance;Emulation.DeviceModeWrapper.ActionDelegate=class{handleAction(context,actionId){if(Emulation.DeviceModeView._wrapperInstance){switch(actionId){case'emulation.capture-screenshot':return Emulation.DeviceModeView._wrapperInstance._captureScreenshot();case'emulation.capture-node-screenshot':{const node=UI.context.flavor(SDK.DOMNode);if(!node)
return true;async function captureClip(){const object=await node.resolveToObject();const result=await object.callFunction(function(){const rect=this.getBoundingClientRect();const docRect=this.ownerDocument.documentElement.getBoundingClientRect();return JSON.stringify({x:rect.left-docRect.left,y:rect.top-docRect.top,width:rect.width,height:rect.height,scale:1});});const clip=(JSON.parse(result.object.value));const response=await node.domModel().target().pageAgent().invoke_getLayoutMetrics({});const page_zoom=!response[Protocol.Error]&&response.visualViewport.zoom||1;clip.x*=page_zoom;clip.y*=page_zoom;clip.width*=page_zoom;clip.height*=page_zoom;Emulation.DeviceModeView._wrapperInstance._captureScreenshot(false,clip);}
captureClip();return true;}
case'emulation.capture-full-height-screenshot':return Emulation.DeviceModeView._wrapperInstance._captureScreenshot(true);case'emulation.toggle-device-mode':Emulation.DeviceModeView._wrapperInstance._toggleDeviceMode();return true;}}
return false;}};;Emulation.GeolocationsSettingsTab=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('emulation/geolocationsSettingsTab.css');this.contentElement.createChild('div','header').textContent=Common.UIString('Custom Geolocations');const addButton=UI.createTextButton(Common.UIString('Add location...'),this._addButtonClicked.bind(this),'add-geolocations-button');this.contentElement.appendChild(addButton);this._list=new UI.ListWidget(this);this._list.element.classList.add('geolocations-list');this._list.registerRequiredCSS('emulation/geolocationsSettingsTab.css');this._list.show(this.contentElement);this._customSetting=Common.moduleSetting('emulation.geolocations');this._customSetting.addChangeListener(this._geolocationsUpdated,this);this.setDefaultFocusedElement(addButton);this.contentElement.tabIndex=0;}
wasShown(){super.wasShown();this._geolocationsUpdated();}
_geolocationsUpdated(){this._list.clear();const conditions=this._customSetting.get();for(let i=0;i<conditions.length;++i)
this._list.appendItem(conditions[i],true);this._list.appendSeparator();}
_addButtonClicked(){this._list.addNewItem(this._customSetting.get().length,{title:'',lat:0,long:0});}
renderItem(item,editable){const geolocation=(item);const element=createElementWithClass('div','geolocations-list-item');const title=element.createChild('div','geolocations-list-text geolocations-list-title');const titleText=title.createChild('div','geolocations-list-title-text');titleText.textContent=geolocation.title;titleText.title=geolocation.title;element.createChild('div','geolocations-list-separator');element.createChild('div','geolocations-list-text').textContent=geolocation.lat;element.createChild('div','geolocations-list-separator');element.createChild('div','geolocations-list-text').textContent=geolocation.long;return element;}
removeItemRequested(item,index){const list=this._customSetting.get();list.splice(index,1);this._customSetting.set(list);}
commitEdit(item,editor,isNew){const geolocation=(item);geolocation.title=editor.control('title').value.trim();const lat=editor.control('lat').value.trim();geolocation.lat=lat?parseFloat(lat):0;const long=editor.control('long').value.trim();geolocation.long=long?parseFloat(long):0;const list=this._customSetting.get();if(isNew)
list.push(geolocation);this._customSetting.set(list);}
beginEdit(item){const geolocation=(item);const editor=this._createEditor();editor.control('title').value=geolocation.title;editor.control('lat').value=String(geolocation.lat);editor.control('long').value=String(geolocation.long);return editor;}
_createEditor(){if(this._editor)
return this._editor;const editor=new UI.ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const titles=content.createChild('div','geolocations-edit-row');titles.createChild('div','geolocations-list-text geolocations-list-title').textContent=Common.UIString('Location name');titles.createChild('div','geolocations-list-separator geolocations-list-separator-invisible');titles.createChild('div','geolocations-list-text').textContent=Common.UIString('Lat');titles.createChild('div','geolocations-list-separator geolocations-list-separator-invisible');titles.createChild('div','geolocations-list-text').textContent=Common.UIString('Long');const fields=content.createChild('div','geolocations-edit-row');fields.createChild('div','geolocations-list-text geolocations-list-title').appendChild(editor.createInput('title','text','',titleValidator));fields.createChild('div','geolocations-list-separator geolocations-list-separator-invisible');let cell=fields.createChild('div','geolocations-list-text');cell.appendChild(editor.createInput('lat','text','',latValidator));fields.createChild('div','geolocations-list-separator geolocations-list-separator-invisible');cell=fields.createChild('div','geolocations-list-text');cell.appendChild(editor.createInput('long','text','',longValidator));return editor;function titleValidator(item,index,input){const value=input.value.trim();return value.length>0&&value.length<50;}
function latValidator(item,index,input){const value=input.value.trim();return!value||(/^-?[\d]+(\.\d+)?|\.\d+$/.test(value)&&value>=-90&&value<=90);}
function longValidator(item,index,input){const value=input.value.trim();return!value||(/^-?[\d]+(\.\d+)?|\.\d+$/.test(value)&&value>=-180&&value<=180);}}};Emulation.GeolocationsSettingsTab.Item;;self['InspectorMain']=self['InspectorMain']||{};InspectorMain.RenderingOptionsView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('inspector_main/renderingOptions.css');this._appendCheckbox(Common.UIString('Paint flashing'),Common.UIString('Highlights areas of the page (green) that need to be repainted'),Common.moduleSetting('showPaintRects'));this._appendCheckbox(Common.UIString('Layer borders'),Common.UIString('Shows layer borders (orange/olive) and tiles (cyan)'),Common.moduleSetting('showDebugBorders'));this._appendCheckbox(Common.UIString('FPS meter'),Common.UIString('Plots frames per second, frame rate distribution, and GPU memory'),Common.moduleSetting('showFPSCounter'));this._appendCheckbox(Common.UIString('Scrolling performance issues'),Common.UIString('Highlights elements (teal) that can slow down scrolling, including touch & wheel event handlers and other main-thread scrolling situations.'),Common.moduleSetting('showScrollBottleneckRects'));this._appendCheckbox(Common.UIString('Highlight ad frames'),Common.UIString('Highlights frames (red) detected to be ads.'),Common.moduleSetting('showAdHighlights'));this._appendCheckbox(Common.UIString('Hit-test borders'),Common.UIString('Shows borders around hit-test regions'),Common.moduleSetting('showHitTestBorders'));this.contentElement.createChild('div').classList.add('panel-section-separator');const mediaSetting=Common.moduleSetting('emulatedCSSMedia');const mediaSelect=UI.SettingsUI.createControlForSetting(mediaSetting);if(mediaSelect){const mediaRow=this.contentElement.createChild('span','media-row');mediaRow.createChild('label').textContent=Common.UIString('Emulate CSS media');mediaRow.createChild('p').textContent=Common.UIString('Forces media type for testing print and screen styles');mediaRow.appendChild(mediaSelect);}}
_appendCheckbox(label,subtitle,setting){const checkboxLabel=UI.CheckboxLabel.create(label,false,subtitle);UI.SettingsUI.bindCheckbox(checkboxLabel.checkboxElement,setting);this.contentElement.appendChild(checkboxLabel);}};;InspectorMain.InspectorMain=class extends Common.Object{async run(){let firstCall=true;await SDK.initMainConnection(async()=>{const type=Runtime.queryParam('v8only')?SDK.Target.Type.Node:SDK.Target.Type.Frame;const waitForDebuggerInPage=type===SDK.Target.Type.Frame&&Runtime.queryParam('panel')==='sources';const target=SDK.targetManager.createTarget('main',Common.UIString('Main'),type,null,undefined,waitForDebuggerInPage);if(!firstCall)
return;firstCall=false;if(waitForDebuggerInPage){const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel.isReadyToPause())
await debuggerModel.once(SDK.DebuggerModel.Events.DebuggerIsReadyToPause);debuggerModel.pause();}
target.runtimeAgent().runIfWaitingForDebugger();},Components.TargetDetachedDialog.webSocketConnectionLost);new InspectorMain.SourcesPanelIndicator();new InspectorMain.BackendSettingsSync();new MobileThrottling.NetworkPanelIndicator();InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ReloadInspectedPage,event=>{const hard=(event.data);SDK.ResourceTreeModel.reloadAllPages(hard);});}};InspectorMain.ReloadActionDelegate=class{handleAction(context,actionId){switch(actionId){case'inspector_main.reload':SDK.ResourceTreeModel.reloadAllPages(false);return true;case'inspector_main.hard-reload':SDK.ResourceTreeModel.reloadAllPages(true);return true;}
return false;}};InspectorMain.FocusDebuggeeActionDelegate=class{handleAction(context,actionId){SDK.targetManager.mainTarget().pageAgent().bringToFront();return true;}};InspectorMain.NodeIndicator=class{constructor(){const element=createElement('div');const shadowRoot=UI.createShadowRootWithCoreStyles(element,'inspector_main/nodeIcon.css');this._element=shadowRoot.createChild('div','node-icon');element.addEventListener('click',()=>InspectorFrontendHost.openNodeFrontend(),false);this._button=new UI.ToolbarItem(element);this._button.setTitle(Common.UIString('Open dedicated DevTools for Node.js'));SDK.targetManager.addEventListener(SDK.TargetManager.Events.AvailableTargetsChanged,event=>this._update((event.data)));this._button.setVisible(false);this._update([]);}
_update(targetInfos){const hasNode=!!targetInfos.find(target=>target.type==='node'&&!target.attached);this._element.classList.toggle('inactive',!hasNode);if(hasNode)
this._button.setVisible(true);}
item(){return this._button;}};InspectorMain.SourcesPanelIndicator=class{constructor(){Common.moduleSetting('javaScriptDisabled').addChangeListener(javaScriptDisabledChanged);javaScriptDisabledChanged();function javaScriptDisabledChanged(){let icon=null;const javaScriptDisabled=Common.moduleSetting('javaScriptDisabled').get();if(javaScriptDisabled){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('JavaScript is disabled');}
UI.inspectorView.setPanelIcon('sources',icon);}}};InspectorMain.BackendSettingsSync=class{constructor(){this._autoAttachSetting=Common.settings.moduleSetting('autoAttachToCreatedPages');this._autoAttachSetting.addChangeListener(this._updateAutoAttach,this);this._updateAutoAttach();this._adBlockEnabledSetting=Common.settings.moduleSetting('network.adBlockingEnabled');this._adBlockEnabledSetting.addChangeListener(this._update,this);this._emulatePageFocusSetting=Common.settings.moduleSetting('emulatePageFocus');this._emulatePageFocusSetting.addChangeListener(this._update,this);SDK.targetManager.observeTargets(this);}
_updateTarget(target){if(target.type()!==SDK.Target.Type.Frame||target.parentTarget())
return;target.pageAgent().setAdBlockingEnabled(this._adBlockEnabledSetting.get());target.emulationAgent().setFocusEmulationEnabled(this._emulatePageFocusSetting.get());}
_updateAutoAttach(){InspectorFrontendHost.setOpenNewWindowForPopups(this._autoAttachSetting.get());}
_update(){for(const target of SDK.targetManager.targets())
this._updateTarget(target);}
targetAdded(target){this._updateTarget(target);}
targetRemoved(target){}};SDK.ChildTargetManager.install();;;Runtime.cachedResources["mobile_throttling/throttlingSettingsTab.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow:hidden;\n}\n\n.header {\n padding: 0 0 6px;\n border-bottom: 1px solid #EEEEEE;\n font-size: 18px;\n font-weight: normal;\n flex: none;\n}\n\n.add-conditions-button {\n flex: none;\n margin: 10px 2px;\n min-width: 140px;\n align-self: flex-start;\n}\n\n.conditions-list {\n max-width: 500px;\n min-width: 340px;\n flex: auto;\n}\n\n.conditions-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n position: relative;\n flex: auto 1 1;\n}\n\n.conditions-list-text {\n white-space: nowrap;\n text-overflow: ellipsis;\n flex: 0 0 70px;\n -webkit-user-select: none;\n color: #222;\n text-align: end;\n position: relative;\n}\n\n.conditions-list-title {\n text-align: start;\n flex: auto;\n display: flex;\n align-items: flex-start;\n}\n\n.conditions-list-title-text {\n overflow: hidden;\n flex: auto;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n\n.conditions-list-separator {\n flex: 0 0 1px;\n background-color: rgb(231, 231, 231);\n height: 30px;\n margin: 0 4px;\n}\n\n.conditions-list-separator-invisible {\n visibility: hidden;\n height: 100% !important;\n}\n\n.conditions-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 6px 5px;\n}\n\n.conditions-edit-row input {\n width: 100%;\n text-align: inherit;\n}\n\n.conditions-edit-optional {\n position: absolute;\n bottom: -20px;\n right: 0;\n color: rgb(128, 128, 128);\n}\n\n/*# sourceURL=mobile_throttling/throttlingSettingsTab.css */";Runtime.cachedResources["emulation/devicesSettingsTab.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.devices-settings-tab .settings-tab.settings-content {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n height: 100%;\n margin: 0;\n}\n\n.devices-settings-tab .devices-button-row {\n flex: none;\n display: flex;\n}\n\n.devices-settings-tab .devices-button-row button {\n margin-right: 10px;\n min-width: 120px;\n flex: none;\n}\n\n.devices-settings-tab .devices-list {\n width: 350px;\n margin-top: 10px;\n}\n\n.devices-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n flex: auto 1 1;\n cursor: pointer;\n}\n\n.devices-list-checkbox {\n height: 12px;\n width: 12px;\n margin: 3px 5px 2px 2px;\n flex: none;\n pointer-events: none;\n}\n\n.devices-list-checkbox:focus {\n outline: auto 5px -webkit-focus-ring-color;\n}\n\n.devices-list-title {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n flex: auto;\n -webkit-user-select: none;\n color: #222;\n}\n\n.devices-edit-fields {\n flex: auto;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n margin-bottom: 5px;\n}\n\n.devices-edit-fields input {\n flex: auto;\n margin: 8px 5px 0 5px;\n}\n\n.devices-edit-fields .device-edit-fixed {\n flex: 0 0 140px;\n}\n\n.devices-edit-fields select {\n margin: 8px 5px 0 5px;\n}\n\n/*# sourceURL=emulation/devicesSettingsTab.css */";Runtime.cachedResources["emulation/deviceModeToolbar.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.device-mode-size-input {\n width: 41px;\n max-height: 18px;\n margin: 0 2px;\n text-align: center;\n}\n\n.device-mode-size-input:focus::-webkit-input-placeholder {\n color: transparent;\n}\n\n.device-m
(function(){const baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();const REMOTE_MODULE_FALLBACK_REVISION='@010ddcfda246975d194964ccf20038ebbdec6084';var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(let i=0;i<descriptors.length;++i)
this._registerModule(descriptors[i]);}
static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){const xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE)
return;const status=/^HTTP\/1.1 404/.test(e.target.response)?404:xhr.status;if([0,200,304].indexOf(status)===-1)
reject(new Error('While loading from url '+url+' server responded with a status of '+status));else
fulfill(e.target.response);}
xhr.send(null);}}
static loadResourcePromiseWithFallback(url){return Runtime.loadResourcePromise(url).catch(err=>{const urlWithFallbackVersion=url.replace(/@[0-9a-f]{40}/,REMOTE_MODULE_FALLBACK_REVISION);if(urlWithFallbackVersion===url||!url.includes('audits2_worker_module'))
throw err;return Runtime.loadResourcePromise(urlWithFallbackVersion);});}
static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1)
return path;const normalizedSegments=[];const segments=path.split('/');for(let i=0;i<segments.length;i++){const segment=segments[i];if(segment==='.')
continue;else if(segment==='..')
normalizedSegments.pop();else if(segment)
normalizedSegments.push(segment);}
let normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/')
return normalizedPath;if(path[0]==='/'&&normalizedPath)
normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..'))
normalizedPath=normalizedPath+'/';return normalizedPath;}
static _loadScriptsPromise(scriptNames,base){const promises=[];const urls=[];const sources=new Array(scriptNames.length);let scriptToEval=0;for(let i=0;i<scriptNames.length;++i){const scriptName=scriptNames[i];let sourceURL=(base||self._importScriptPathPrefix)+scriptName;const schemaIndex=sourceURL.indexOf('://')+3;let pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1)
pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL])
continue;urls.push(sourceURL);const loadResourcePromise=base?Runtime.loadResourcePromiseWithFallback(sourceURL):Runtime.loadResourcePromise(sourceURL);promises.push(loadResourcePromise.then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));}
return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}}
function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;}
self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}}
static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;}
const sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}}
static async appStarted(){return Runtime._appStartedPromise;}
static async startApplication(appName){console.timeStamp('Runtime.startApplication');const allDescriptorsByName={};for(let i=0;i<allDescriptors.length;++i){const d=allDescriptors[i];allDescriptorsByName[d['name']]=d;}
if(!applicationDescriptor){let data=await Runtime.loadResourcePromise(appName+'.json');applicationDescriptor=JSON.parse(data);let descriptor=applicationDescriptor;while(descriptor.extends){data=await Runtime.loadResourcePromise(descriptor.extends+'.json');descriptor=JSON.parse(data);applicationDescriptor.modules=descriptor.modules.concat(applicationDescriptor.modules);}}
const configuration=applicationDescriptor.modules;const moduleJSONPromises=[];const coreModuleNames=[];for(let i=0;i<configuration.length;++i){const descriptor=configuration[i];const name=descriptor['name'];const moduleJSON=allDescriptorsByName[name];if(moduleJSON)
moduleJSONPromises.push(Promise.resolve(moduleJSON));else
moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart')
coreModuleNames.push(name);}
const moduleDescriptors=await Promise.all(moduleJSONPromises);for(let i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';}
self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames)
await self.runtime._loadAutoStartModules(coreModuleNames);Runtime._appStartedPromiseCallback();}
static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}}
static queryParam(name){return Runtime._queryParamsObject.get(name);}
static queryParamsString(){return location.search;}
static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}}
static _assert(value,message){if(value)
return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);}
static setPlatform(platform){Runtime._platform=platform;}
static _isDescriptorEnabled(descriptor){const activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*')
return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1)))
return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment))
return false;const condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition))
return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1)))
return false;return true;}
static resolveSourceURL(path){let sourceURL=self.location.href;if(self.location.search)
sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';}
static setL10nCallback(localizationFunction){Runtime._l10nCallback=localizationFunction;}
useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend'))
Runtime._remoteBase+='debug/';}
_registerModule(descriptor){const module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;}
loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();}
_loadAutoStartModules(moduleNames){const promises=[];for(let i=0;i<moduleNames.length;++i)
promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);}
_checkExtensionApplicability(extension,predicate){if(!predicate)
return false;const contextTypes=extension.descriptor().contextTypes;if(!contextTypes)
return true;for(let i=0;i<contextTypes.length;++i){const contextType=this._resolve(contextTypes[i]);const isMatching=!!contextType&&predicate(contextType);if(isMatching)
return true;}
return false;}
isExtensionApplicableToContext(extension,context){if(!context)
return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}}
isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes)
return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}}
extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type)
return false;if(!extension.enabled())
return false;return!context||extension.isApplicable(context);}
function orderComparator(extension1,extension2){const order1=extension1.descriptor()['order']||0;const order2=extension2.descriptor()['order']||0;return order1-order2;}
function titleComparator(extension1,extension2){const title1=extension1.title()||'';const title2=extension2.title()||'';return title1.localeCompare(title2);}}
extension(type,context){return this.extensions(type,context)[0]||null;}
allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));}
_resolve(typeName){if(!this._cachedTypeClasses[typeName]){const path=typeName.split('.');let object=self;for(let i=0;object&&(i<path.length);++i)
object=object[path[i]];if(object)
this._cachedTypeClasses[typeName]=(object);}
return this._cachedTypeClasses[typeName]||null;}
sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction&&Object.getOwnPropertySymbols(constructorFunction).includes(Runtime._instanceSymbol))
return constructorFunction[Runtime._instanceSymbol];const instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject=new URLSearchParams(Runtime.queryParamsString());Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();const extensions=(descriptor.extensions);for(let i=0;extensions&&i<extensions.length;++i){const extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);}
this._loadedForTest=false;}
name(){return this._name;}
enabled(){return Runtime._isDescriptorEnabled(this._descriptor);}
resource(name){const fullName=this._name+'/'+name;const content=Runtime.cachedResources[fullName];if(!content)
throw new Error(fullName+' not preloaded. Check module.json');return content;}
_loadPromise(){if(!this.enabled())
return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise)
return this._pendingLoadPromise;const dependencies=this._descriptor.dependencies;const dependencyPromises=[];for(let i=0;dependencies&&i<dependencies.length;++i)
dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;}
_loadResources(){const resources=this._descriptor['resources'];if(!resources||!resources.length)
return Promise.resolve();const promises=[];for(let i=0;i<resources.length;++i){const url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));}
return Promise.all(promises).then(undefined);}
_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length)
return Promise.resolve();const specialCases={'sdk':'SDK','js_sdk':'JSSDK','browser_sdk':'BrowserSDK','ui':'UI','object_ui':'ObjectUI','javascript_metadata':'JavaScriptMetadata','perf_ui':'PerfUI','har_importer':'HARImporter','sdk_test_runner':'SDKTestRunner','cpu_profiler_test_runner':'CPUProfilerTestRunner'};const namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());}
_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);}
_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;}
substituteURL(value){const base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;}
descriptor(){return this._descriptor;}
module(){return this._module;}
enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());}
_typeClass(){if(!this._hasTypeClass)
return null;return this._module._manager._resolve(this._type.substring(1));}
isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);}
instance(){return this._module._loadPromise().then(this._createInstance.bind(this));}
canInstantiate(){return!!(this._className||this._factoryName);}
_createInstance(){const className=this._className||this._factoryName;if(!className)
throw new Error('Could not instantiate extension with no class');const constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function))
throw new Error('Could not instantiate: '+className);if(this._className)
return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);}
title(){const title=this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];if(title&&Runtime._l10nCallback)
return Runtime._l10nCallback(title);return title;}
hasContextType(contextType){const contextTypes=this.descriptor().contextTypes;if(!contextTypes)
return false;for(let i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i]))
return true;}
return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
allConfigurableExperiments(){const result=[];for(let i=0;i<this._experiments.length;i++){const experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name])
result.push(experiment);}
return result;}
supportEnabled(){return this._supportEnabled;}
_setExperimentsSetting(value){if(!self.localStorage)
return;self.localStorage['experiments']=JSON.stringify(value);}
register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));}
isEnabled(experimentName){this._checkExperiment(experimentName);if(Runtime._experimentsSetting()[experimentName]===false)
return false;if(this._enabledTransiently[experimentName])
return true;if(!this.supportEnabled())
return false;return!!Runtime._experimentsSetting()[experimentName];}
setEnabled(experimentName,enabled){this._checkExperiment(experimentName);const experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);}
setDefaultExperiments(experimentNames){for(let i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}}
enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;}
clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
cleanUpStaleExperiments(){const experimentsSetting=Runtime._experimentsSetting();const cleanedUpExperimentSetting={};for(let i=0;i<this._experiments.length;++i){const experimentName=this._experiments[i].name;if(experimentsSetting[experimentName])
cleanedUpExperimentSetting[experimentName]=true;}
this._setExperimentsSetting(cleanedUpExperimentSetting);}
_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;}
isEnabled(){return this._experiments.isEnabled(this.name);}
setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._appStartedPromiseCallback;Runtime._appStartedPromise=new Promise(fulfil=>Runtime._appStartedPromiseCallback=fulfil);Runtime._l10nCallback;Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){const versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch)
Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){}
ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;allDescriptors.push(...[{"dependencies":[],"name":"platform"},{"skip_compilation":["acorn/acorn.js","acorn/acorn_loose.js","../cm_web_modes/css.js","../cm_web_modes/xml.js"],"dependencies":["platform","text_utils","cm_headless"],"name":"formatter_worker"},{"dependencies":["platform"],"name":"text_utils"},{"skip_compilation":["headlesscodemirror.js"],"name":"cm_headless"}]);applicationDescriptor={"has_html":false,"modules":[{"type":"autostart","name":"platform"},{"type":"autostart","name":"formatter_worker"},{"type":"autostart","name":"text_utils"},{"type":"autostart","name":"cm_headless"}]}
self['Platform']=self['Platform']||{};let ArrayLike;function mod(m,n){return((m%n)+n)%n;}
String.prototype.findAll=function(string){const matches=[];let i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);}
return matches;};String.prototype.reverse=function(){return this.split('').reverse().join('');};String.prototype.replaceControlCharacters=function(){return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,'<27>');};String.prototype.isWhitespace=function(){return/^\s*$/.test(this);};String.prototype.computeLineEndings=function(){const endings=this.findAll('\n');endings.push(this.length);return endings;};String.prototype.escapeCharacters=function(chars){let foundChar=false;for(let i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}}
if(!foundChar)
return String(this);let result='';for(let i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1)
result+='\\';result+=this.charAt(i);}
return result;};String.regexSpecialCharacters=function(){return'^[]{}()\\.^$*+?|-,';};String.prototype.escapeForRegExp=function(){return this.escapeCharacters(String.regexSpecialCharacters());};String.filterRegex=function(query){const toEscape=String.regexSpecialCharacters();let regexString='';for(let i=0;i<query.length;++i){let c=query.charAt(i);if(toEscape.indexOf(c)!==-1)
c='\\'+c;if(i)
regexString+='[^\\0'+c+']*';regexString+=c;}
return new RegExp(regexString,'i');};String.escapeInvalidUnicodeCharacters=function(text){if(!String._invalidCharactersRegExp){let invalidCharacters='';for(let i=0xfffe;i<=0x10ffff;i+=0x10000)
invalidCharacters+=String.fromCodePoint(i,i+1);String._invalidCharactersRegExp=new RegExp(`[${invalidCharacters}\uD800-\uDFFF\uFDD0-\uFDEF]`,'gu');}
let result='';let lastPos=0;while(true){const match=String._invalidCharactersRegExp.exec(text);if(!match)
break;result+=text.substring(lastPos,match.index)+'\\u'+text.charCodeAt(match.index).toString(16);if(match.index+1<String._invalidCharactersRegExp.lastIndex)
result+='\\u'+text.charCodeAt(match.index+1).toString(16);lastPos=String._invalidCharactersRegExp.lastIndex;}
return result+text.substring(lastPos);};String.prototype.escapeHTML=function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');};String.prototype.unescapeHTML=function(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&#58;/g,':').replace(/&quot;/g,'"').replace(/&#60;/g,'<').replace(/&#62;/g,'>').replace(/&amp;/g,'&');};String.prototype.collapseWhitespace=function(){return this.replace(/[\s\xA0]+/g,' ');};String.prototype.trimMiddle=function(maxLength){if(this.length<=maxLength)
return String(this);let leftHalf=maxLength>>1;let rightHalf=maxLength-leftHalf-1;if(this.codePointAt(this.length-rightHalf-1)>=0x10000){--rightHalf;++leftHalf;}
if(leftHalf>0&&this.codePointAt(leftHalf-1)>=0x10000)
--leftHalf;return this.substr(0,leftHalf)+'\u2026'+this.substr(this.length-rightHalf,rightHalf);};String.prototype.trimEnd=function(maxLength){if(this.length<=maxLength)
return String(this);return this.substr(0,maxLength-1)+'\u2026';};String.prototype.trimURL=function(baseURLDomain){let result=this.replace(/^(https|http|file):\/\//i,'');if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase()))
result=result.substr(baseURLDomain.length);}
return result;};String.prototype.toTitleCase=function(){return this.substring(0,1).toUpperCase()+this.substring(1);};String.prototype.compareTo=function(other){if(this>other)
return 1;if(this<other)
return-1;return 0;};String.prototype.removeURLFragment=function(){let fragmentIndex=this.indexOf('#');if(fragmentIndex===-1)
fragmentIndex=this.length;return this.substring(0,fragmentIndex);};String.hashCode=function(string){if(!string)
return 0;const p=((1<<30)*4-5);const z=0x5033d967;const z2=0x59d2f15d;let s=0;let zi=1;for(let i=0;i<string.length;i++){const xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;}
s=(s+zi*(p-1))%p;return Math.abs(s|0);};String.isDigitAt=function(string,index){const c=string.charCodeAt(index);return(48<=c&&c<=57);};String.prototype.toBase64=function(){function encodeBits(b){return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;}
const encoder=new TextEncoder();const data=encoder.encode(this.toString());const n=data.length;let encoded='';if(n===0)
return encoded;let shift;let v=0;for(let i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}}
if(shift===0)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);else if(shift===1)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);return encoded;};String.naturalOrderComparator=function(a,b){const chunk=/^\d+|^\D+/;let chunka,chunkb,anum,bnum;while(1){if(a){if(!b)
return 1;}else{if(b)
return-1;else
return 0;}
chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum)
return-1;if(bnum&&!anum)
return 1;if(anum&&bnum){const diff=chunka-chunkb;if(diff)
return diff;if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb)
return chunka.length-chunkb.length;else
return chunkb.length-chunka.length;}}else if(chunka!==chunkb){return(chunka<chunkb)?-1:1;}
a=a.substring(chunka.length);b=b.substring(chunkb.length);}};String.caseInsensetiveComparator=function(a,b){a=a.toUpperCase();b=b.toUpperCase();if(a===b)
return 0;return a>b?1:-1;};Number.constrain=function(num,min,max){if(num<min)
num=min;else if(num>max)
num=max;return num;};Number.gcd=function(a,b){if(b===0)
return a;else
return Number.gcd(b,a%b);};Number.toFixedIfFloating=function(value){if(!value||isNaN(value))
return value;const number=Number(value);return number%1?number.toFixed(3):String(number);};Date.prototype.isValid=function(){return!isNaN(this.getTime());};Date.prototype.toISO8601Compact=function(){function leadZero(x){return(x>9?'':'0')+x;}
return this.getFullYear()+leadZero(this.getMonth()+1)+leadZero(this.getDate())+'T'+
leadZero(this.getHours())+leadZero(this.getMinutes())+leadZero(this.getSeconds());};Object.defineProperty(Array.prototype,'remove',{value:function(value,firstOnly){let index=this.indexOf(value);if(index===-1)
return false;if(firstOnly){this.splice(index,1);return true;}
for(let i=index+1,n=this.length;i<n;++i){if(this[i]!==value)
this[index++]=this[i];}
this.length=index;return true;}});Object.defineProperty(Array.prototype,'pushAll',{value:function(array){for(let i=0;i<array.length;++i)
this.push(array[i]);}});Object.defineProperty(Array.prototype,'rotate',{value:function(index){const result=[];for(let i=index;i<index+this.length;++i)
result.push(this[i%this.length]);return result;}});Object.defineProperty(Array.prototype,'sortNumbers',{value:function(){function numericComparator(a,b){return a-b;}
this.sort(numericComparator);}});Object.defineProperty(Uint32Array.prototype,'sort',{value:Array.prototype.sort});(function(){const partition={value:function(comparator,left,right,pivotIndex){function swap(array,i1,i2){const temp=array[i1];array[i1]=array[i2];array[i2]=temp;}
const pivotValue=this[pivotIndex];swap(this,right,pivotIndex);let storeIndex=left;for(let i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}}
swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,'partition',partition);Object.defineProperty(Uint32Array.prototype,'partition',partition);const sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight){function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight){if(right<=left)
return;const pivotIndex=Math.floor(Math.random()*(right-left))+left;const pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex)
quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);if(pivotNewIndex<sortWindowRight)
quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);}
if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound)
this.sort(comparator);else
quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);return this;}};Object.defineProperty(Array.prototype,'sortRange',sortRange);Object.defineProperty(Uint32Array.prototype,'sortRange',sortRange);})();Object.defineProperty(Array.prototype,'stableSort',{value:function(comparator){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;const indices=new Array(this.length);for(let i=0;i<this.length;++i)
indices[i]=i;const self=this;function indexComparator(a,b){const result=comparator(self[a],self[b]);return result?result:a-b;}
indices.sort(indexComparator);for(let i=0;i<this.length;++i){if(indices[i]<0||i===indices[i])
continue;let cyclical=i;const saved=this[i];while(true){const next=indices[cyclical];indices[cyclical]=-1;if(next===i){this[cyclical]=saved;break;}else{this[cyclical]=this[next];cyclical=next;}}}
return this;}});Object.defineProperty(Array.prototype,'qselect',{value:function(k,comparator){if(k<0||k>=this.length)
return;if(!comparator){comparator=function(a,b){return a-b;};}
let low=0;let high=this.length-1;for(;;){const pivotPosition=this.partition(comparator,low,high,Math.floor((high+low)/2));if(pivotPosition===k)
return this[k];else if(pivotPosition>k)
high=pivotPosition-1;else
low=pivotPosition+1;}}});Object.defineProperty(Array.prototype,'lowerBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Array.prototype,'upperBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>=0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Uint32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Int32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Int32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,'binaryIndexOf',{value:function(value,comparator){const index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,'select',{value:function(field){const result=new Array(this.length);for(let i=0;i<this.length;++i)
result[i]=this[i][field];return result;}});Object.defineProperty(Array.prototype,'peekLast',{value:function(){return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect){const result=[];let i=0;let j=0;while(i<array1.length&&j<array2.length){const compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue)
result.push(compareValue<=0?array1[i]:array2[j]);if(compareValue<=0)
i++;if(compareValue>=0)
j++;}
if(mergeNotIntersect){while(i<array1.length)
result.push(array1[i++]);while(j<array2.length)
result.push(array2[j++]);}
return result;}
Object.defineProperty(Array.prototype,'intersectOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,'mergeOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg){return String.vsprintf(format,Array.prototype.slice.call(arguments,1));};String.tokenizeFormatString=function(format,formatters){const tokens=[];function addStringToken(str){if(!str)
return;if(tokens.length&&tokens[tokens.length-1].type==='string')
tokens[tokens.length-1].value+=str;else
tokens.push({type:'string',value:str});}
function addSpecifierToken(specifier,precision,substitutionIndex){tokens.push({type:'specifier',specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});}
function addAnsiColor(code){const types={3:'color',9:'colorLight',4:'bgColor',10:'bgColorLight'};const colorCodes=['black','red','green','yellow','blue','magenta','cyan','lightGray','','default'];const colorCodesLight=['darkGray','lightRed','lightGreen','lightYellow','lightBlue','lightMagenta','lightCyan','white',''];const colors={color:colorCodes,colorLight:colorCodesLight,bgColor:colorCodes,bgColorLight:colorCodesLight};const type=types[Math.floor(code/10)];if(!type)
return;const color=colors[type][code%10];if(!color)
return;tokens.push({type:'specifier',specifier:'c',value:{description:(type.startsWith('bg')?'background : ':'color: ')+color}});}
let textStart=0;let substitutionIndex=0;const re=new RegExp(`%%|%(?:(\\d+)\\$)?(?:\\.(\\d*))?([${Object.keys(formatters).join('')}])|\\u001b\\[(\\d+)m`,'g');for(let match=re.exec(format);!!match;match=re.exec(format)){const matchStart=match.index;if(matchStart>textStart)
addStringToken(format.substring(textStart,matchStart));if(match[0]==='%%'){addStringToken('%');}else if(match[0].startsWith('%')){const[_,substitionString,precisionString,specifierString]=match;if(substitionString&&Number(substitionString)>0)
substitutionIndex=Number(substitionString)-1;const precision=precisionString?Number(precisionString):-1;addSpecifierToken(specifierString,precision,substitutionIndex);++substitutionIndex;}else{const code=Number(match[4]);addAnsiColor(code);}
textStart=matchStart+match[0].length;}
addStringToken(format.substring(textStart));return tokens;};String.standardFormatters={d:function(substitution){return!isNaN(substitution)?substitution:0;},f:function(substitution,token){if(substitution&&token.precision>-1)
substitution=substitution.toFixed(token.precision);return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution){return substitution;}};String.vsprintf=function(format,substitutions){return String.format(format,substitutions,String.standardFormatters,'',function(a,b){return a+b;}).formattedResult;};String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat){if(!format||((!substitutions||!substitutions.length)&&format.search(/\u001b\[(\d+)m/)===-1))
return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName(){return'String.format("'+format+'", "'+Array.prototype.join.call(substitutions,'", "')+'")';}
function warn(msg){console.warn(prettyFunctionName()+': '+msg);}
function error(msg){console.error(prettyFunctionName()+': '+msg);}
let result=initialValue;const tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);const usedSubstitutionIndexes={};for(let i=0;i<tokens.length;++i){const token=tokens[i];if(token.type==='string'){result=append(result,token.value);continue;}
if(token.type!=='specifier'){error('Unknown token type "'+token.type+'" found.');continue;}
if(!token.value&&token.substitutionIndex>=substitutions.length){error('not enough substitution arguments. Had '+substitutions.length+' but needed '+
(token.substitutionIndex+1)+', so substitution was skipped.');result=append(result,'%'+(token.precision>-1?token.precision:'')+token.specifier);continue;}
if(!token.value)
usedSubstitutionIndexes[token.substitutionIndex]=true;if(!(token.specifier in formatters)){warn('unsupported format character \u201C'+token.specifier+'\u201D. Treating as a string.');result=append(result,token.value?'':substitutions[token.substitutionIndex]);continue;}
result=append(result,formatters[token.specifier](token.value||substitutions[token.substitutionIndex],token));}
const unusedSubstitutions=[];for(let i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes)
continue;unusedSubstitutions.push(substitutions[i]);}
return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};};function createSearchRegex(query,caseSensitive,isRegex){const regexFlags=caseSensitive?'g':'gi';let regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}}
if(!regexObject)
regexObject=createPlainTextSearchRegex(query,regexFlags);return regexObject;}
function createPlainTextSearchRegex(query,flags){const regexSpecialCharacters=String.regexSpecialCharacters();let regex='';for(let i=0;i<query.length;++i){const c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1)
regex+='\\';regex+=c;}
return new RegExp(regex,flags||'');}
function countRegexMatches(regex,content){let text=content;let result=0;let match;while(text&&(match=regex.exec(text))){if(match[0].length>0)
++result;text=text.substring(match.index+1);}
return result;}
function spacesPadding(spacesCount){return'\u00a0'.repeat(spacesCount);}
function numberToStringWithSpacesPadding(value,symbolsCount){const numberString=value.toString();const paddingLength=Math.max(0,symbolsCount-numberString.length);return spacesPadding(paddingLength)+numberString;}
Set.prototype.valuesArray=function(){return Array.from(this.values());};Set.prototype.firstValue=function(){if(!this.size)
return null;return this.values().next().value;};Set.prototype.addAll=function(iterable){for(const e of iterable)
this.add(e);};Set.prototype.containsAll=function(iterable){for(const e of iterable){if(!this.has(e))
return false;}
return true;};Map.prototype.remove=function(key){const value=this.get(key);this.delete(key);return value;};Map.prototype.valuesArray=function(){return Array.from(this.values());};Map.prototype.keysArray=function(){return Array.from(this.keys());};Map.prototype.inverse=function(){const result=new Multimap();for(const key of this.keys()){const value=this.get(key);result.set(value,key);}
return result;};var Multimap=function(){this._map=new Map();};Multimap.prototype={set:function(key,value){let set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);}
set.add(value);},get:function(key){return this._map.get(key)||new Set();},has:function(key){return this._map.has(key);},hasValue:function(key,value){const set=this._map.get(key);if(!set)
return false;return set.has(value);},get size(){return this._map.size;},delete:function(key,value){const values=this.get(key);if(!values)
return false;const result=values.delete(value);if(!values.size)
this._map.delete(key);return result;},deleteAll:function(key){this._map.delete(key);},keysArray:function(){return this._map.keysArray();},valuesArray:function(){const result=[];const keys=this.keysArray();for(let i=0;i<keys.length;++i)
result.pushAll(this.get(keys[i]).valuesArray());return result;},clear:function(){this._map.clear();}};function loadXHR(url){return new Promise(load);function load(successCallback,failureCallback){function onReadyStateChanged(){if(xhr.readyState!==XMLHttpRequest.DONE)
return;if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;}
xhr.onreadystatechange=null;successCallback(xhr.responseText);}
const xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open('GET',url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}}
function suppressUnused(value){}
self.setImmediate=function(callback){const args=[...arguments].slice(1);Promise.resolve().then(()=>callback(...args));return 0;};Promise.prototype.spread=function(callback){return this.then(spreadPromise);function spreadPromise(arg){return callback.apply(null,arg);}};Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});};Map.prototype.diff=function(other,isEqual){const leftKeys=this.keysArray();const rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);const removed=[];const added=[];const equal=[];let leftIndex=0;let rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){const leftKey=leftKeys[leftIndex];const rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;}
if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;}
added.push(other.get(rightKey));++rightIndex;}
while(leftIndex<leftKeys.length){const leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));}
while(rightIndex<rightKeys.length){const rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));}
return{added:added,removed:removed,equal:equal};};function runOnWindowLoad(callback){function windowLoaded(){self.removeEventListener('DOMContentLoaded',windowLoaded,false);callback();}
if(document.readyState==='complete'||document.readyState==='interactive')
callback();else
self.addEventListener('DOMContentLoaded',windowLoaded,false);}
const _singletonSymbol=Symbol('singleton');function singleton(constructorFunction){if(_singletonSymbol in constructorFunction)
return constructorFunction[_singletonSymbol];const instance=new constructorFunction();constructorFunction[_singletonSymbol]=instance;return instance;}
function base64ToSize(content){if(!content)
return 0;let size=content.length*3/4;if(content[content.length-1]==='=')
size--;if(content.length>1&&content[content.length-2]==='=')
size--;return size;};self['TextUtils']=self['TextUtils']||{};TextUtils.Text=class{constructor(value){this._value=value;}
lineEndings(){if(!this._lineEndings)
this._lineEndings=this._value.computeLineEndings();return this._lineEndings;}
value(){return this._value;}
lineCount(){const lineEndings=this.lineEndings();return lineEndings.length;}
offsetFromPosition(lineNumber,columnNumber){return(lineNumber?this.lineEndings()[lineNumber-1]+1:0)+columnNumber;}
positionFromOffset(offset){const lineEndings=this.lineEndings();const lineNumber=lineEndings.lowerBound(offset);return{lineNumber:lineNumber,columnNumber:offset-(lineNumber&&(lineEndings[lineNumber-1]+1))};}
lineAt(lineNumber){const lineEndings=this.lineEndings();const lineStart=lineNumber>0?lineEndings[lineNumber-1]+1:0;const lineEnd=lineEndings[lineNumber];let lineContent=this._value.substring(lineStart,lineEnd);if(lineContent.length>0&&lineContent.charAt(lineContent.length-1)==='\r')
lineContent=lineContent.substring(0,lineContent.length-1);return lineContent;}
toSourceRange(range){const start=this.offsetFromPosition(range.startLine,range.startColumn);const end=this.offsetFromPosition(range.endLine,range.endColumn);return new TextUtils.SourceRange(start,end-start);}
toTextRange(sourceRange){const cursor=new TextUtils.TextCursor(this.lineEndings());const result=TextUtils.TextRange.createFromLocation(0,0);cursor.resetTo(sourceRange.offset);result.startLine=cursor.lineNumber();result.startColumn=cursor.columnNumber();cursor.advance(sourceRange.offset+sourceRange.length);result.endLine=cursor.lineNumber();result.endColumn=cursor.columnNumber();return result;}
replaceRange(range,replacement){const sourceRange=this.toSourceRange(range);return this._value.substring(0,sourceRange.offset)+replacement+
this._value.substring(sourceRange.offset+sourceRange.length);}
extract(range){const sourceRange=this.toSourceRange(range);return this._value.substr(sourceRange.offset,sourceRange.length);}};TextUtils.Text.Position;TextUtils.TextCursor=class{constructor(lineEndings){this._lineEndings=lineEndings;this._offset=0;this._lineNumber=0;this._columnNumber=0;}
advance(offset){this._offset=offset;while(this._lineNumber<this._lineEndings.length&&this._lineEndings[this._lineNumber]<this._offset)
++this._lineNumber;this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
offset(){return this._offset;}
resetTo(offset){this._offset=offset;this._lineNumber=this._lineEndings.lowerBound(offset);this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
lineNumber(){return this._lineNumber;}
columnNumber(){return this._columnNumber;}};;TextUtils.TextUtils={isStopChar:function(char){return(char>' '&&char<'0')||(char>'9'&&char<'A')||(char>'Z'&&char<'_')||(char>'_'&&char<'a')||(char>'z'&&char<='~');},isWordChar:function(char){return!TextUtils.TextUtils.isStopChar(char)&&!TextUtils.TextUtils.isSpaceChar(char);},isSpaceChar:function(char){return TextUtils.TextUtils._SpaceCharRegex.test(char);},isWord:function(word){for(let i=0;i<word.length;++i){if(!TextUtils.TextUtils.isWordChar(word.charAt(i)))
return false;}
return true;},isOpeningBraceChar:function(char){return char==='('||char==='{';},isClosingBraceChar:function(char){return char===')'||char==='}';},isBraceChar:function(char){return TextUtils.TextUtils.isOpeningBraceChar(char)||TextUtils.TextUtils.isClosingBraceChar(char);},textToWords:function(text,isWordChar,wordCallback){let startWord=-1;for(let i=0;i<text.length;++i){if(!isWordChar(text.charAt(i))){if(startWord!==-1)
wordCallback(text.substring(startWord,i));startWord=-1;}else if(startWord===-1){startWord=i;}}
if(startWord!==-1)
wordCallback(text.substring(startWord));},lineIndent:function(line){let indentation=0;while(indentation<line.length&&TextUtils.TextUtils.isSpaceChar(line.charAt(indentation)))
++indentation;return line.substr(0,indentation);},isUpperCase:function(text){return text===text.toUpperCase();},isLowerCase:function(text){return text===text.toLowerCase();},splitStringByRegexes(text,regexes){const matches=[];const globalRegexes=[];for(let i=0;i<regexes.length;i++){const regex=regexes[i];if(!regex.global)
globalRegexes.push(new RegExp(regex.source,regex.flags?regex.flags+'g':'g'));else
globalRegexes.push(regex);}
doSplit(text,0,0);return matches;function doSplit(text,regexIndex,startIndex){if(regexIndex>=globalRegexes.length){matches.push({value:text,position:startIndex,regexIndex:-1,captureGroups:[]});return;}
const regex=globalRegexes[regexIndex];let currentIndex=0;let result;regex.lastIndex=0;while((result=regex.exec(text))!==null){const stringBeforeMatch=text.substring(currentIndex,result.index);if(stringBeforeMatch)
doSplit(stringBeforeMatch,regexIndex+1,startIndex+currentIndex);const match=result[0];matches.push({value:match,position:startIndex+result.index,regexIndex:regexIndex,captureGroups:result.slice(1)});currentIndex=result.index+match.length;}
const stringAfterMatches=text.substring(currentIndex);if(stringAfterMatches)
doSplit(stringAfterMatches,regexIndex+1,startIndex+currentIndex);}}};TextUtils.FilterParser=class{constructor(keys){this._keys=keys;}
static cloneFilter(filter){return{key:filter.key,text:filter.text,regex:filter.regex,negative:filter.negative};}
parse(query){const splitResult=TextUtils.TextUtils.splitStringByRegexes(query,[TextUtils.TextUtils._keyValueFilterRegex,TextUtils.TextUtils._regexFilterRegex,TextUtils.TextUtils._textFilterRegex]);const filters=[];for(let i=0;i<splitResult.length;i++){const regexIndex=splitResult[i].regexIndex;if(regexIndex===-1)
continue;const result=splitResult[i].captureGroups;if(regexIndex===0){if(this._keys.indexOf((result[1]))!==-1)
filters.push({key:result[1],text:result[2],negative:!!result[0]});else
filters.push({text:result[1]+':'+result[2],negative:!!result[0]});}else if(regexIndex===1){try{filters.push({regex:new RegExp(result[1],'i'),negative:!!result[0]});}catch(e){filters.push({text:'/'+result[1]+'/',negative:!!result[0]});}}else if(regexIndex===2){filters.push({text:result[1],negative:!!result[0]});}}
return filters;}};TextUtils.FilterParser.ParsedFilter;TextUtils.TextUtils._keyValueFilterRegex=/(?:^|\s)(\-)?([\w\-]+):([^\s]+)/;TextUtils.TextUtils._regexFilterRegex=/(?:^|\s)(\-)?\/([^\s]+)\//;TextUtils.TextUtils._textFilterRegex=/(?:^|\s)(\-)?([^\s]+)/;TextUtils.TextUtils._SpaceCharRegex=/\s/;TextUtils.TextUtils.Indent={TwoSpaces:' ',FourSpaces:' ',EightSpaces:' ',TabCharacter:'\t'};TextUtils.TextUtils.BalancedJSONTokenizer=class{constructor(callback,findMultiple){this._callback=callback;this._index=0;this._balance=0;this._buffer='';this._findMultiple=findMultiple||false;this._closingDoubleQuoteRegex=/[^\\](?:\\\\)*"/g;}
write(chunk){this._buffer+=chunk;const lastIndex=this._buffer.length;const buffer=this._buffer;let index;for(index=this._index;index<lastIndex;++index){const character=buffer[index];if(character==='"'){this._closingDoubleQuoteRegex.lastIndex=index;if(!this._closingDoubleQuoteRegex.test(buffer))
break;index=this._closingDoubleQuoteRegex.lastIndex-1;}else if(character==='{'){++this._balance;}else if(character==='}'){--this._balance;if(this._balance<0){this._reportBalanced();return false;}
if(!this._balance){this._lastBalancedIndex=index+1;if(!this._findMultiple)
break;}}else if(character===']'&&!this._balance){this._reportBalanced();return false;}}
this._index=index;this._reportBalanced();return true;}
_reportBalanced(){if(!this._lastBalancedIndex)
return;this._callback(this._buffer.slice(0,this._lastBalancedIndex));this._buffer=this._buffer.slice(this._lastBalancedIndex);this._index-=this._lastBalancedIndex;this._lastBalancedIndex=0;}
remainder(){return this._buffer;}};TextUtils.TokenizerFactory=function(){};TextUtils.TokenizerFactory.prototype={createTokenizer(mimeType){}};TextUtils.isMinified=function(text){const kMaxNonMinifiedLength=500;let linesToCheck=10;let lastPosition=0;do{let eolIndex=text.indexOf('\n',lastPosition);if(eolIndex<0)
eolIndex=text.length;if(eolIndex-lastPosition>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#')
return true;lastPosition=eolIndex+1;}while(--linesToCheck>=0&&lastPosition<text.length);linesToCheck=10;lastPosition=text.length;do{let eolIndex=text.lastIndexOf('\n',lastPosition);if(eolIndex<0)
eolIndex=0;if(lastPosition-eolIndex>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#')
return true;lastPosition=eolIndex-1;}while(--linesToCheck>=0&&lastPosition>0);return false;};;TextUtils.TextRange=class{constructor(startLine,startColumn,endLine,endColumn){this.startLine=startLine;this.startColumn=startColumn;this.endLine=endLine;this.endColumn=endColumn;}
static createFromLocation(line,column){return new TextUtils.TextRange(line,column,line,column);}
static fromObject(serializedTextRange){return new TextUtils.TextRange(serializedTextRange.startLine,serializedTextRange.startColumn,serializedTextRange.endLine,serializedTextRange.endColumn);}
static comparator(range1,range2){return range1.compareTo(range2);}
static fromEdit(oldRange,newText){let endLine=oldRange.startLine;let endColumn=oldRange.startColumn+newText.length;const lineEndings=newText.computeLineEndings();if(lineEndings.length>1){endLine=oldRange.startLine+lineEndings.length-1;const len=lineEndings.length;endColumn=lineEndings[len-1]-lineEndings[len-2]-1;}
return new TextUtils.TextRange(oldRange.startLine,oldRange.startColumn,endLine,endColumn);}
isEmpty(){return this.startLine===this.endLine&&this.startColumn===this.endColumn;}
immediatelyPrecedes(range){if(!range)
return false;return this.endLine===range.startLine&&this.endColumn===range.startColumn;}
immediatelyFollows(range){if(!range)
return false;return range.immediatelyPrecedes(this);}
follows(range){return(range.endLine===this.startLine&&range.endColumn<=this.startColumn)||range.endLine<this.startLine;}
get linesCount(){return this.endLine-this.startLine;}
collapseToEnd(){return new TextUtils.TextRange(this.endLine,this.endColumn,this.endLine,this.endColumn);}
collapseToStart(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.startLine,this.startColumn);}
normalize(){if(this.startLine>this.endLine||(this.startLine===this.endLine&&this.startColumn>this.endColumn))
return new TextUtils.TextRange(this.endLine,this.endColumn,this.startLine,this.startColumn);else
return this.clone();}
clone(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.endLine,this.endColumn);}
serializeToObject(){const serializedTextRange={};serializedTextRange.startLine=this.startLine;serializedTextRange.startColumn=this.startColumn;serializedTextRange.endLine=this.endLine;serializedTextRange.endColumn=this.endColumn;return serializedTextRange;}
compareTo(other){if(this.startLine>other.startLine)
return 1;if(this.startLine<other.startLine)
return-1;if(this.startColumn>other.startColumn)
return 1;if(this.startColumn<other.startColumn)
return-1;return 0;}
compareToPosition(lineNumber,columnNumber){if(lineNumber<this.startLine||(lineNumber===this.startLine&&columnNumber<this.startColumn))
return-1;if(lineNumber>this.endLine||(lineNumber===this.endLine&&columnNumber>this.endColumn))
return 1;return 0;}
equal(other){return this.startLine===other.startLine&&this.endLine===other.endLine&&this.startColumn===other.startColumn&&this.endColumn===other.endColumn;}
relativeTo(line,column){const relative=this.clone();if(this.startLine===line)
relative.startColumn-=column;if(this.endLine===line)
relative.endColumn-=column;relative.startLine-=line;relative.endLine-=line;return relative;}
relativeFrom(line,column){const relative=this.clone();if(this.startLine===0)
relative.startColumn+=column;if(this.endLine===0)
relative.endColumn+=column;relative.startLine+=line;relative.endLine+=line;return relative;}
rebaseAfterTextEdit(originalRange,editedRange){console.assert(originalRange.startLine===editedRange.startLine);console.assert(originalRange.startColumn===editedRange.startColumn);const rebase=this.clone();if(!this.follows(originalRange))
return rebase;const lineDelta=editedRange.endLine-originalRange.endLine;const columnDelta=editedRange.endColumn-originalRange.endColumn;rebase.startLine+=lineDelta;rebase.endLine+=lineDelta;if(rebase.startLine===editedRange.endLine)
rebase.startColumn+=columnDelta;if(rebase.endLine===editedRange.endLine)
rebase.endColumn+=columnDelta;return rebase;}
toString(){return JSON.stringify(this);}
containsLocation(lineNumber,columnNumber){if(this.startLine===this.endLine)
return this.startLine===lineNumber&&this.startColumn<=columnNumber&&columnNumber<=this.endColumn;if(this.startLine===lineNumber)
return this.startColumn<=columnNumber;if(this.endLine===lineNumber)
return columnNumber<=this.endColumn;return this.startLine<lineNumber&&lineNumber<this.endLine;}};TextUtils.SourceRange=class{constructor(offset,length){this.offset=offset;this.length=length;}};TextUtils.SourceEdit=class{constructor(sourceURL,oldRange,newText){this.sourceURL=sourceURL;this.oldRange=oldRange;this.newText=newText;}
static comparator(edit1,edit2){return TextUtils.TextRange.comparator(edit1.oldRange,edit2.oldRange);}
newRange(){return TextUtils.TextRange.fromEdit(this.oldRange,this.newText);}};;self['CmHeadless']=self['CmHeadless']||{};(function(window){window.CodeMirror={};(function(){"use strict";function splitLines(string){return string.split(/\r?\n|\r/);};function StringStream(string){this.pos=this.start=0;this.string=string;this.lineStart=0;}
StringStream.prototype={eol:function(){return this.pos>=this.string.length;},sol:function(){return this.pos==0;},peek:function(){return this.string.charAt(this.pos)||null;},next:function(){if(this.pos<this.string.length)
return this.string.charAt(this.pos++);},eat:function(match){var ch=this.string.charAt(this.pos);if(typeof match=="string")var ok=ch==match;else var ok=ch&&(match.test?match.test(ch):match(ch));if(ok){++this.pos;return ch;}},eatWhile:function(match){var start=this.pos;while(this.eat(match)){}
return this.pos>start;},eatSpace:function(){var start=this.pos;while(/[\s\u00a0]/.test(this.string.charAt(this.pos)))++this.pos;return this.pos>start;},skipToEnd:function(){this.pos=this.string.length;},skipTo:function(ch){var found=this.string.indexOf(ch,this.pos);if(found>-1){this.pos=found;return true;}},backUp:function(n){this.pos-=n;},column:function(){return this.start-this.lineStart;},indentation:function(){return 0;},match:function(pattern,consume,caseInsensitive){if(typeof pattern=="string"){var cased=function(str){return caseInsensitive?str.toLowerCase():str;};var substr=this.string.substr(this.pos,pattern.length);if(cased(substr)==cased(pattern)){if(consume!==false)this.pos+=pattern.length;return true;}}else{var match=this.string.slice(this.pos).match(pattern);if(match&&match.index>0)return null;if(match&&consume!==false)this.pos+=match[0].length;return match;}},current:function(){return this.string.slice(this.start,this.pos);},hideFirstChars:function(n,inner){this.lineStart+=n;try{return inner();}
finally{this.lineStart-=n;}},lookAhead:function(){return null}};CodeMirror.StringStream=StringStream;CodeMirror.startState=function(mode,a1,a2){return mode.startState?mode.startState(a1,a2):true;};var modes=CodeMirror.modes={},mimeModes=CodeMirror.mimeModes={};CodeMirror.defineMode=function(name,mode){if(arguments.length>2)
mode.dependencies=Array.prototype.slice.call(arguments,2);modes[name]=mode;};CodeMirror.defineMIME=function(mime,spec){mimeModes[mime]=spec;};CodeMirror.resolveMode=function(spec){if(typeof spec=="string"&&mimeModes.hasOwnProperty(spec)){spec=mimeModes[spec];}else if(spec&&typeof spec.name=="string"&&mimeModes.hasOwnProperty(spec.name)){spec=mimeModes[spec.name];}
if(typeof spec=="string")return{name:spec};else return spec||{name:"null"};};CodeMirror.getMode=function(options,spec){spec=CodeMirror.resolveMode(spec);var mfactory=modes[spec.name];if(!mfactory)throw new Error("Unknown mode: "+spec);return mfactory(options,spec);};CodeMirror.registerHelper=CodeMirror.registerGlobalHelper=Math.min;CodeMirror.defineMode("null",function(){return{token:function(stream){stream.skipToEnd();}};});CodeMirror.defineMIME("text/plain","null");CodeMirror.runMode=function(string,modespec,callback,options){var mode=CodeMirror.getMode({indentUnit:2},modespec);if(callback.nodeType==1){var tabSize=(options&&options.tabSize)||4;var node=callback,col=0;node.innerHTML="";callback=function(text,style){if(text=="\n"){node.appendChild(document.createElement("br"));col=0;return;}
var content="";for(var pos=0;;){var idx=text.indexOf("\t",pos);if(idx==-1){content+=text.slice(pos);col+=text.length-pos;break;}else{col+=idx-pos;content+=text.slice(pos,idx);var size=tabSize-col%tabSize;col+=size;for(var i=0;i<size;++i)content+=" ";pos=idx+1;}}
if(style){var sp=node.appendChild(document.createElement("span"));sp.className="cm-"+style.replace(/ +/g," cm-");sp.appendChild(document.createTextNode(content));}else{node.appendChild(document.createTextNode(content));}};}
var lines=splitLines(string),state=(options&&options.state)||CodeMirror.startState(mode);for(var i=0,e=lines.length;i<e;++i){if(i)callback("\n");var stream=new CodeMirror.StringStream(lines[i]);if(!stream.string&&mode.blankLine)mode.blankLine(state);while(!stream.eol()){var style=mode.token(stream,state);callback(stream.current(),style,i,stream.start,state);stream.start=stream.pos;}}};})();}(this));self['FormatterWorker']=self['FormatterWorker']||{};(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.defineMode("css",function(config,parserConfig){var inline=parserConfig.inline
if(!parserConfig.propertyKeywords)parserConfig=CodeMirror.resolveMode("text/css");var indentUnit=config.indentUnit,tokenHooks=parserConfig.tokenHooks,documentTypes=parserConfig.documentTypes||{},mediaTypes=parserConfig.mediaTypes||{},mediaFeatures=parserConfig.mediaFeatures||{},mediaValueKeywords=parserConfig.mediaValueKeywords||{},propertyKeywords=parserConfig.propertyKeywords||{},nonStandardPropertyKeywords=parserConfig.nonStandardPropertyKeywords||{},fontProperties=parserConfig.fontProperties||{},counterDescriptors=parserConfig.counterDescriptors||{},colorKeywords=parserConfig.colorKeywords||{},valueKeywords=parserConfig.valueKeywords||{},allowNested=parserConfig.allowNested,lineComment=parserConfig.lineComment,supportsAtComponent=parserConfig.supportsAtComponent===true;var type,override;function ret(style,tp){type=tp;return style;}
function tokenBase(stream,state){var ch=stream.next();if(tokenHooks[ch]){var result=tokenHooks[ch](stream,state);if(result!==false)return result;}
if(ch=="@"){stream.eatWhile(/[\w\\\-]/);return ret("def",stream.current());}else if(ch=="="||(ch=="~"||ch=="|")&&stream.eat("=")){return ret(null,"compare");}else if(ch=="\""||ch=="'"){state.tokenize=tokenString(ch);return state.tokenize(stream,state);}else if(ch=="#"){stream.eatWhile(/[\w\\\-]/);return ret("atom","hash");}else if(ch=="!"){stream.match(/^\s*\w*/);return ret("keyword","important");}else if(/\d/.test(ch)||ch=="."&&stream.eat(/\d/)){stream.eatWhile(/[\w.%]/);return ret("number","unit");}else if(ch==="-"){if(/[\d.]/.test(stream.peek())){stream.eatWhile(/[\w.%]/);return ret("number","unit");}else if(stream.match(/^-[\w\\\-]*/)){stream.eatWhile(/[\w\\\-]/);if(stream.match(/^\s*:/,false))
return ret("variable-2","variable-definition");return ret("variable-2","variable");}else if(stream.match(/^\w+-/)){return ret("meta","meta");}}else if(/[,+>*\/]/.test(ch)){return ret(null,"select-op");}else if(ch=="."&&stream.match(/^-?[_a-z][_a-z0-9-]*/i)){return ret("qualifier","qualifier");}else if(/[:;{}\[\]\(\)]/.test(ch)){return ret(null,ch);}else if(((ch=="u"||ch=="U")&&stream.match(/rl(-prefix)?\(/i))||((ch=="d"||ch=="D")&&stream.match("omain(",true,true))||((ch=="r"||ch=="R")&&stream.match("egexp(",true,true))){stream.backUp(1);state.tokenize=tokenParenthesized;return ret("property","word");}else if(/[\w\\\-]/.test(ch)){stream.eatWhile(/[\w\\\-]/);return ret("property","word");}else{return ret(null,null);}}
function tokenString(quote){return function(stream,state){var escaped=false,ch;while((ch=stream.next())!=null){if(ch==quote&&!escaped){if(quote==")")stream.backUp(1);break;}
escaped=!escaped&&ch=="\\";}
if(ch==quote||!escaped&&quote!=")")state.tokenize=null;return ret("string","string");};}
function tokenParenthesized(stream,state){stream.next();if(!stream.match(/\s*[\"\')]/,false))
state.tokenize=tokenString(")");else
state.tokenize=null;return ret(null,"(");}
function Context(type,indent,prev){this.type=type;this.indent=indent;this.prev=prev;}
function pushContext(state,stream,type,indent){state.context=new Context(type,stream.indentation()+(indent===false?0:indentUnit),state.context);return type;}
function popContext(state){if(state.context.prev)
state.context=state.context.prev;return state.context.type;}
function pass(type,stream,state){return states[state.context.type](type,stream,state);}
function popAndPass(type,stream,state,n){for(var i=n||1;i>0;i--)
state.context=state.context.prev;return pass(type,stream,state);}
function wordAsValue(stream){var word=stream.current().toLowerCase();if(valueKeywords.hasOwnProperty(word))
override="atom";else if(colorKeywords.hasOwnProperty(word))
override="keyword";else
override="variable";}
var states={};states.top=function(type,stream,state){if(type=="{"){return pushContext(state,stream,"block");}else if(type=="}"&&state.context.prev){return popContext(state);}else if(supportsAtComponent&&/@component/i.test(type)){return pushContext(state,stream,"atComponentBlock");}else if(/^@(-moz-)?document$/i.test(type)){return pushContext(state,stream,"documentTypes");}else if(/^@(media|supports|(-moz-)?document|import)$/i.test(type)){return pushContext(state,stream,"atBlock");}else if(/^@(font-face|counter-style)/i.test(type)){state.stateArg=type;return"restricted_atBlock_before";}else if(/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)){return"keyframes";}else if(type&&type.charAt(0)=="@"){return pushContext(state,stream,"at");}else if(type=="hash"){override="builtin";}else if(type=="word"){override="tag";}else if(type=="variable-definition"){return"maybeprop";}else if(type=="interpolation"){return pushContext(state,stream,"interpolation");}else if(type==":"){return"pseudo";}else if(allowNested&&type=="("){return pushContext(state,stream,"parens");}
return state.context.type;};states.block=function(type,stream,state){if(type=="word"){var word=stream.current().toLowerCase();if(propertyKeywords.hasOwnProperty(word)){override="property";return"maybeprop";}else if(nonStandardPropertyKeywords.hasOwnProperty(word)){override="string-2";return"maybeprop";}else if(allowNested){override=stream.match(/^\s*:(?:\s|$)/,false)?"property":"tag";return"block";}else{override+=" error";return"maybeprop";}}else if(type=="meta"){return"block";}else if(!allowNested&&(type=="hash"||type=="qualifier")){override="error";return"block";}else{return states.top(type,stream,state);}};states.maybeprop=function(type,stream,state){if(type==":")return pushContext(state,stream,"prop");return pass(type,stream,state);};states.prop=function(type,stream,state){if(type==";")return popContext(state);if(type=="{"&&allowNested)return pushContext(state,stream,"propBlock");if(type=="}"||type=="{")return popAndPass(type,stream,state);if(type=="(")return pushContext(state,stream,"parens");if(type=="hash"&&!/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())){override+=" error";}else if(type=="word"){wordAsValue(stream);}else if(type=="interpolation"){return pushContext(state,stream,"interpolation");}
return"prop";};states.propBlock=function(type,_stream,state){if(type=="}")return popContext(state);if(type=="word"){override="property";return"maybeprop";}
return state.context.type;};states.parens=function(type,stream,state){if(type=="{"||type=="}")return popAndPass(type,stream,state);if(type==")")return popContext(state);if(type=="(")return pushContext(state,stream,"parens");if(type=="interpolation")return pushContext(state,stream,"interpolation");if(type=="word")wordAsValue(stream);return"parens";};states.pseudo=function(type,stream,state){if(type=="meta")return"pseudo";if(type=="word"){override="variable-3";return state.context.type;}
return pass(type,stream,state);};states.documentTypes=function(type,stream,state){if(type=="word"&&documentTypes.hasOwnProperty(stream.current())){override="tag";return state.context.type;}else{return states.atBlock(type,stream,state);}};states.atBlock=function(type,stream,state){if(type=="(")return pushContext(state,stream,"atBlock_parens");if(type=="}"||type==";")return popAndPass(type,stream,state);if(type=="{")return popContext(state)&&pushContext(state,stream,allowNested?"block":"top");if(type=="interpolation")return pushContext(state,stream,"interpolation");if(type=="word"){var word=stream.current().toLowerCase();if(word=="only"||word=="not"||word=="and"||word=="or")
override="keyword";else if(mediaTypes.hasOwnProperty(word))
override="attribute";else if(mediaFeatures.hasOwnProperty(word))
override="property";else if(mediaValueKeywords.hasOwnProperty(word))
override="keyword";else if(propertyKeywords.hasOwnProperty(word))
override="property";else if(nonStandardPropertyKeywords.hasOwnProperty(word))
override="string-2";else if(valueKeywords.hasOwnProperty(word))
override="atom";else if(colorKeywords.hasOwnProperty(word))
override="keyword";else
override="error";}
return state.context.type;};states.atComponentBlock=function(type,stream,state){if(type=="}")
return popAndPass(type,stream,state);if(type=="{")
return popContext(state)&&pushContext(state,stream,allowNested?"block":"top",false);if(type=="word")
override="error";return state.context.type;};states.atBlock_parens=function(type,stream,state){if(type==")")return popContext(state);if(type=="{"||type=="}")return popAndPass(type,stream,state,2);return states.atBlock(type,stream,state);};states.restricted_atBlock_before=function(type,stream,state){if(type=="{")
return pushContext(state,stream,"restricted_atBlock");if(type=="word"&&state.stateArg=="@counter-style"){override="variable";return"restricted_atBlock_before";}
return pass(type,stream,state);};states.restricted_atBlock=function(type,stream,state){if(type=="}"){state.stateArg=null;return popContext(state);}
if(type=="word"){if((state.stateArg=="@font-face"&&!fontProperties.hasOwnProperty(stream.current().toLowerCase()))||(state.stateArg=="@counter-style"&&!counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
override="error";else
override="property";return"maybeprop";}
return"restricted_atBlock";};states.keyframes=function(type,stream,state){if(type=="word"){override="variable";return"keyframes";}
if(type=="{")return pushContext(state,stream,"top");return pass(type,stream,state);};states.at=function(type,stream,state){if(type==";")return popContext(state);if(type=="{"||type=="}")return popAndPass(type,stream,state);if(type=="word")override="tag";else if(type=="hash")override="builtin";return"at";};states.interpolation=function(type,stream,state){if(type=="}")return popContext(state);if(type=="{"||type==";")return popAndPass(type,stream,state);if(type=="word")override="variable";else if(type!="variable"&&type!="("&&type!=")")override="error";return"interpolation";};return{startState:function(base){return{tokenize:null,state:inline?"block":"top",stateArg:null,context:new Context(inline?"block":"top",base||0,null)};},token:function(stream,state){if(!state.tokenize&&stream.eatSpace())return null;var style=(state.tokenize||tokenBase)(stream,state);if(style&&typeof style=="object"){type=style[1];style=style[0];}
override=style;if(type!="comment")
state.state=states[state.state](type,stream,state);return override;},indent:function(state,textAfter){var cx=state.context,ch=textAfter&&textAfter.charAt(0);var indent=cx.indent;if(cx.type=="prop"&&(ch=="}"||ch==")"))cx=cx.prev;if(cx.prev){if(ch=="}"&&(cx.type=="block"||cx.type=="top"||cx.type=="interpolation"||cx.type=="restricted_atBlock")){cx=cx.prev;indent=cx.indent;}else if(ch==")"&&(cx.type=="parens"||cx.type=="atBlock_parens")||ch=="{"&&(cx.type=="at"||cx.type=="atBlock")){indent=Math.max(0,cx.indent-indentUnit);}}
return indent;},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:lineComment,fold:"brace"};});function keySet(array){var keys={};for(var i=0;i<array.length;++i){keys[array[i].toLowerCase()]=true;}
return keys;}
var documentTypes_=["domain","regexp","url","url-prefix"],documentTypes=keySet(documentTypes_);var mediaTypes_=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],mediaTypes=keySet(mediaTypes_);var mediaFeatures_=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover"],mediaFeatures=keySet(mediaFeatures_);var mediaValueKeywords_=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],mediaValueKeywords=keySet(mediaValueKeywords_);var propertyKeywords_=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","justify-items","justify-self","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-
maybeEnd=(ch=="*");}
return["comment","comment"];}
CodeMirror.defineMIME("text/css",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return false;state.tokenize=tokenCComment;return tokenCComment(stream,state);}},name:"css"});CodeMirror.defineMIME("text/x-scss",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:true,lineComment:"//",tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"];}else if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state);}else{return["operator","operator"];}},":":function(stream){if(stream.match(/\s*\{/,false))
return[null,null]
return false;},"$":function(stream){stream.match(/^[\w-]+/);if(stream.match(/^\s*:/,false))
return["variable-2","variable-definition"];return["variable-2","variable"];},"#":function(stream){if(!stream.eat("{"))return false;return[null,"interpolation"];}},name:"css",helperType:"scss"});CodeMirror.defineMIME("text/x-less",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:true,lineComment:"//",tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"];}else if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state);}else{return["operator","operator"];}},"@":function(stream){if(stream.eat("{"))return[null,"interpolation"];if(stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i,false))return false;stream.eatWhile(/[\w\\\-]/);if(stream.match(/^\s*:/,false))
return["variable-2","variable-definition"];return["variable-2","variable"];},"&":function(){return["atom","atom"];}},name:"css",helperType:"less"});CodeMirror.defineMIME("text/x-gss",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,supportsAtComponent:true,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return false;state.tokenize=tokenCComment;return tokenCComment(stream,state);}},name:"css",helperType:"gss"});});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";var htmlConfig={autoSelfClosers:{'area':true,'base':true,'br':true,'col':true,'command':true,'embed':true,'frame':true,'hr':true,'img':true,'input':true,'keygen':true,'link':true,'meta':true,'param':true,'source':true,'track':true,'wbr':true,'menuitem':true},implicitlyClosed:{'dd':true,'li':true,'optgroup':true,'option':true,'p':true,'rp':true,'rt':true,'tbody':true,'td':true,'tfoot':true,'th':true,'tr':true},contextGrabbers:{'dd':{'dd':true,'dt':true},'dt':{'dd':true,'dt':true},'li':{'li':true},'option':{'option':true,'optgroup':true},'optgroup':{'optgroup':true},'p':{'address':true,'article':true,'aside':true,'blockquote':true,'dir':true,'div':true,'dl':true,'fieldset':true,'footer':true,'form':true,'h1':true,'h2':true,'h3':true,'h4':true,'h5':true,'h6':true,'header':true,'hgroup':true,'hr':true,'menu':true,'nav':true,'ol':true,'p':true,'pre':true,'section':true,'table':true,'ul':true},'rp':{'rp':true,'rt':true},'rt':{'rp':true,'rt':true},'tbody':{'tbody':true,'tfoot':true},'td':{'td':true,'th':true},'tfoot':{'tbody':true},'th':{'td':true,'th':true},'thead':{'tbody':true,'tfoot':true},'tr':{'tr':true}},doNotIndent:{"pre":true},allowUnquoted:true,allowMissing:true,caseFold:true}
var xmlConfig={autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:false,allowMissing:false,allowMissingTagName:false,caseFold:false}
CodeMirror.defineMode("xml",function(editorConf,config_){var indentUnit=editorConf.indentUnit
var config={}
var defaults=config_.htmlMode?htmlConfig:xmlConfig
for(var prop in defaults)config[prop]=defaults[prop]
for(var prop in config_)config[prop]=config_[prop]
var type,setStyle;function inText(stream,state){function chain(parser){state.tokenize=parser;return parser(stream,state);}
var ch=stream.next();if(ch=="<"){if(stream.eat("!")){if(stream.eat("[")){if(stream.match("CDATA["))return chain(inBlock("atom","]]>"));else return null;}else if(stream.match("--")){return chain(inBlock("comment","-->"));}else if(stream.match("DOCTYPE",true,true)){stream.eatWhile(/[\w\._\-]/);return chain(doctype(1));}else{return null;}}else if(stream.eat("?")){stream.eatWhile(/[\w\._\-]/);state.tokenize=inBlock("meta","?>");return"meta";}else{type=stream.eat("/")?"closeTag":"openTag";state.tokenize=inTag;return"tag bracket";}}else if(ch=="&"){var ok;if(stream.eat("#")){if(stream.eat("x")){ok=stream.eatWhile(/[a-fA-F\d]/)&&stream.eat(";");}else{ok=stream.eatWhile(/[\d]/)&&stream.eat(";");}}else{ok=stream.eatWhile(/[\w\.\-:]/)&&stream.eat(";");}
return ok?"atom":"error";}else{stream.eatWhile(/[^&<]/);return null;}}
inText.isInText=true;function inTag(stream,state){var ch=stream.next();if(ch==">"||(ch=="/"&&stream.eat(">"))){state.tokenize=inText;type=ch==">"?"endTag":"selfcloseTag";return"tag bracket";}else if(ch=="="){type="equals";return null;}else if(ch=="<"){state.tokenize=inText;state.state=baseState;state.tagName=state.tagStart=null;var next=state.tokenize(stream,state);return next?next+" tag error":"tag error";}else if(/[\'\"]/.test(ch)){state.tokenize=inAttribute(ch);state.stringStartCol=stream.column();return state.tokenize(stream,state);}else{stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);return"word";}}
function inAttribute(quote){var closure=function(stream,state){while(!stream.eol()){if(stream.next()==quote){state.tokenize=inTag;break;}}
return"string";};closure.isInAttribute=true;return closure;}
function inBlock(style,terminator){return function(stream,state){while(!stream.eol()){if(stream.match(terminator)){state.tokenize=inText;break;}
stream.next();}
return style;}}
function doctype(depth){return function(stream,state){var ch;while((ch=stream.next())!=null){if(ch=="<"){state.tokenize=doctype(depth+1);return state.tokenize(stream,state);}else if(ch==">"){if(depth==1){state.tokenize=inText;break;}else{state.tokenize=doctype(depth-1);return state.tokenize(stream,state);}}}
return"meta";};}
function Context(state,tagName,startOfLine){this.prev=state.context;this.tagName=tagName;this.indent=state.indented;this.startOfLine=startOfLine;if(config.doNotIndent.hasOwnProperty(tagName)||(state.context&&state.context.noIndent))
this.noIndent=true;}
function popContext(state){if(state.context)state.context=state.context.prev;}
function maybePopContext(state,nextTagName){var parentTagName;while(true){if(!state.context){return;}
parentTagName=state.context.tagName;if(!config.contextGrabbers.hasOwnProperty(parentTagName)||!config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)){return;}
popContext(state);}}
function baseState(type,stream,state){if(type=="openTag"){state.tagStart=stream.column();return tagNameState;}else if(type=="closeTag"){return closeTagNameState;}else{return baseState;}}
function tagNameState(type,stream,state){if(type=="word"){state.tagName=stream.current();setStyle="tag";return attrState;}else if(config.allowMissingTagName&&type=="endTag"){setStyle="tag bracket";return attrState(type,stream,state);}else{setStyle="error";return tagNameState;}}
function closeTagNameState(type,stream,state){if(type=="word"){var tagName=stream.current();if(state.context&&state.context.tagName!=tagName&&config.implicitlyClosed.hasOwnProperty(state.context.tagName))
popContext(state);if((state.context&&state.context.tagName==tagName)||config.matchClosing===false){setStyle="tag";return closeState;}else{setStyle="tag error";return closeStateErr;}}else if(config.allowMissingTagName&&type=="endTag"){setStyle="tag bracket";return closeState(type,stream,state);}else{setStyle="error";return closeStateErr;}}
function closeState(type,_stream,state){if(type!="endTag"){setStyle="error";return closeState;}
popContext(state);return baseState;}
function closeStateErr(type,stream,state){setStyle="error";return closeState(type,stream,state);}
function attrState(type,_stream,state){if(type=="word"){setStyle="attribute";return attrEqState;}else if(type=="endTag"||type=="selfcloseTag"){var tagName=state.tagName,tagStart=state.tagStart;state.tagName=state.tagStart=null;if(type=="selfcloseTag"||config.autoSelfClosers.hasOwnProperty(tagName)){maybePopContext(state,tagName);}else{maybePopContext(state,tagName);state.context=new Context(state,tagName,tagStart==state.indented);}
return baseState;}
setStyle="error";return attrState;}
function attrEqState(type,stream,state){if(type=="equals")return attrValueState;if(!config.allowMissing)setStyle="error";return attrState(type,stream,state);}
function attrValueState(type,stream,state){if(type=="string")return attrContinuedState;if(type=="word"&&config.allowUnquoted){setStyle="string";return attrState;}
setStyle="error";return attrState(type,stream,state);}
function attrContinuedState(type,stream,state){if(type=="string")return attrContinuedState;return attrState(type,stream,state);}
return{startState:function(baseIndent){var state={tokenize:inText,state:baseState,indented:baseIndent||0,tagName:null,tagStart:null,context:null}
if(baseIndent!=null)state.baseIndent=baseIndent
return state},token:function(stream,state){if(!state.tagName&&stream.sol())
state.indented=stream.indentation();if(stream.eatSpace())return null;type=null;var style=state.tokenize(stream,state);if((style||type)&&style!="comment"){setStyle=null;state.state=state.state(type||style,stream,state);if(setStyle)
style=setStyle=="error"?style+" error":setStyle;}
return style;},indent:function(state,textAfter,fullLine){var context=state.context;if(state.tokenize.isInAttribute){if(state.tagStart==state.indented)
return state.stringStartCol+1;else
return state.indented+indentUnit;}
if(context&&context.noIndent)return CodeMirror.Pass;if(state.tokenize!=inTag&&state.tokenize!=inText)
return fullLine?fullLine.match(/^(\s*)/)[0].length:0;if(state.tagName){if(config.multilineTagIndentPastTag!==false)
return state.tagStart+state.tagName.length+2;else
return state.tagStart+indentUnit*(config.multilineTagIndentFactor||1);}
if(config.alignCDATA&&/<!\[CDATA\[/.test(textAfter))return 0;var tagAfter=textAfter&&/^<(\/)?([\w_:\.-]*)/.exec(textAfter);if(tagAfter&&tagAfter[1]){while(context){if(context.tagName==tagAfter[2]){context=context.prev;break;}else if(config.implicitlyClosed.hasOwnProperty(context.tagName)){context=context.prev;}else{break;}}}else if(tagAfter){while(context){var grabbers=config.contextGrabbers[context.tagName];if(grabbers&&grabbers.hasOwnProperty(tagAfter[2]))
context=context.prev;else
break;}}
while(context&&context.prev&&!context.startOfLine)
context=context.prev;if(context)return context.indent+indentUnit;else return state.baseIndent||0;},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:config.htmlMode?"html":"xml",helperType:config.htmlMode?"html":"xml",skipAttribute:function(state){if(state.state==attrValueState)
state.state=attrState}};});CodeMirror.defineMIME("text/xml","xml");CodeMirror.defineMIME("application/xml","xml");if(!CodeMirror.mimeModes.hasOwnProperty("text/html"))
CodeMirror.defineMIME("text/html",{name:"xml",htmlMode:true});});;FormatterWorker.ESTreeWalker=class{constructor(beforeVisit,afterVisit){this._beforeVisit=beforeVisit;this._afterVisit=afterVisit||new Function();this._walkNulls=false;}
setWalkNulls(value){this._walkNulls=value;}
walk(ast){this._innerWalk(ast,null);}
_innerWalk(node,parent){if(!node&&parent&&this._walkNulls){const result=({raw:'null',value:null});result.type='Literal';node=(result);}
if(!node)
return;node.parent=parent;if(this._beforeVisit.call(null,node)===FormatterWorker.ESTreeWalker.SkipSubtree){this._afterVisit.call(null,node);return;}
const walkOrder=FormatterWorker.ESTreeWalker._walkOrder[node.type];if(!walkOrder){console.error('Walk order not defined for '+node.type);return;}
if(node.type==='TemplateLiteral'){const templateLiteral=(node);const expressionsLength=templateLiteral.expressions.length;for(let i=0;i<expressionsLength;++i){this._innerWalk(templateLiteral.quasis[i],templateLiteral);this._innerWalk(templateLiteral.expressions[i],templateLiteral);}
this._innerWalk(templateLiteral.quasis[expressionsLength],templateLiteral);}else{for(let i=0;i<walkOrder.length;++i){const entity=node[walkOrder[i]];if(Array.isArray(entity))
this._walkArray(entity,node);else
this._innerWalk(entity,node);}}
this._afterVisit.call(null,node);}
_walkArray(nodeArray,parentNode){for(let i=0;i<nodeArray.length;++i)
this._innerWalk(nodeArray[i],parentNode);}};FormatterWorker.ESTreeWalker.SkipSubtree={};FormatterWorker.ESTreeWalker._walkOrder={'AwaitExpression':['arguments'],'ArrayExpression':['elements'],'ArrayPattern':['elements'],'ArrowFunctionExpression':['params','body'],'AssignmentExpression':['left','right'],'AssignmentPattern':['left','right'],'BinaryExpression':['left','right'],'BlockStatement':['body'],'BreakStatement':['label'],'CallExpression':['callee','arguments'],'CatchClause':['param','body'],'ClassBody':['body'],'ClassDeclaration':['id','superClass','body'],'ClassExpression':['id','superClass','body'],'ConditionalExpression':['test','consequent','alternate'],'ContinueStatement':['label'],'DebuggerStatement':[],'DoWhileStatement':['body','test'],'EmptyStatement':[],'ExpressionStatement':['expression'],'ForInStatement':['left','right','body'],'ForOfStatement':['left','right','body'],'ForStatement':['init','test','update','body'],'FunctionDeclaration':['id','params','body'],'FunctionExpression':['id','params','body'],'Identifier':[],'IfStatement':['test','consequent','alternate'],'LabeledStatement':['label','body'],'Literal':[],'LogicalExpression':['left','right'],'MemberExpression':['object','property'],'MethodDefinition':['key','value'],'NewExpression':['callee','arguments'],'ObjectExpression':['properties'],'ObjectPattern':['properties'],'ParenthesizedExpression':['expression'],'Program':['body'],'Property':['key','value'],'ReturnStatement':['argument'],'SequenceExpression':['expressions'],'SpreadElement':['argument'],'Super':[],'SwitchCase':['test','consequent'],'SwitchStatement':['discriminant','cases'],'TaggedTemplateExpression':['tag','quasi'],'TemplateElement':[],'TemplateLiteral':['quasis','expressions'],'ThisExpression':[],'ThrowStatement':['argument'],'TryStatement':['block','handler','finalizer'],'UnaryExpression':['argument'],'UpdateExpression':['argument'],'VariableDeclaration':['declarations'],'VariableDeclarator':['id','init'],'WhileStatement':['test','body'],'WithStatement':['object','body'],'YieldExpression':['argument']};;FormatterWorker.createTokenizer=function(mimeType){const mode=CodeMirror.getMode({indentUnit:2},mimeType);const state=CodeMirror.startState(mode);function tokenize(line,callback){const stream=new CodeMirror.StringStream(line);while(!stream.eol()){const style=mode.token(stream,state);const value=stream.current();if(callback(value,style,stream.start,stream.start+value.length)===FormatterWorker.AbortTokenization)
return;stream.start=stream.pos;}}
return tokenize;};FormatterWorker.AbortTokenization={};self.onmessage=function(event){const method=(event.data.method);const params=(event.data.params);if(!method)
return;switch(method){case'format':FormatterWorker.format(params.mimeType,params.content,params.indentString);break;case'parseCSS':FormatterWorker.parseCSS(params.content);break;case'parseSCSS':FormatterWorker.FormatterWorkerContentParser.parse(params.content,'text/x-scss');break;case'javaScriptOutline':FormatterWorker.javaScriptOutline(params.content);break;case'javaScriptIdentifiers':FormatterWorker.javaScriptIdentifiers(params.content);break;case'evaluatableJavaScriptSubstring':FormatterWorker.evaluatableJavaScriptSubstring(params.content);break;case'parseJSONRelaxed':FormatterWorker.parseJSONRelaxed(params.content);break;case'preprocessTopLevelAwaitExpressions':FormatterWorker.preprocessTopLevelAwaitExpressions(params.content);break;case'findLastExpression':postMessage(FormatterWorker.findLastExpression(params.content));break;case'findLastFunctionCall':postMessage(FormatterWorker.findLastFunctionCall(params.content));break;case'argumentsList':postMessage(FormatterWorker.argumentsList(params.content));break;default:console.error('Unsupport method name: '+method);}};FormatterWorker.parseJSONRelaxed=function(content){postMessage(FormatterWorker.RelaxedJSONParser.parse(content));};FormatterWorker.evaluatableJavaScriptSubstring=function(content){const tokenizer=acorn.tokenizer(content,{ecmaVersion:9});let result='';try{let token=tokenizer.getToken();while(token.type!==acorn.tokTypes.eof&&FormatterWorker.AcornTokenizer.punctuator(token))
token=tokenizer.getToken();const startIndex=token.start;let endIndex=token.end;let openBracketsCounter=0;while(token.type!==acorn.tokTypes.eof){const isIdentifier=FormatterWorker.AcornTokenizer.identifier(token);const isThis=FormatterWorker.AcornTokenizer.keyword(token,'this');const isString=token.type===acorn.tokTypes.string;if(!isThis&&!isIdentifier&&!isString)
break;endIndex=token.end;token=tokenizer.getToken();while(FormatterWorker.AcornTokenizer.punctuator(token,'.[]')){if(FormatterWorker.AcornTokenizer.punctuator(token,'['))
openBracketsCounter++;if(FormatterWorker.AcornTokenizer.punctuator(token,']')){endIndex=openBracketsCounter>0?token.end:endIndex;openBracketsCounter--;}
token=tokenizer.getToken();}}
result=content.substring(startIndex,endIndex);}catch(e){console.error(e);}
postMessage(result);};FormatterWorker.preprocessTopLevelAwaitExpressions=function(content){let wrapped='(async () => {'+content+'\n})()';let root;let body;try{root=acorn.parse(wrapped,{ecmaVersion:10});body=root.body[0].expression.callee.body;}catch(e){postMessage('');return;}
const changes=[];let containsAwait=false;let containsReturn=false;class Visitor{ClassDeclaration(node){if(node.parent===body)
changes.push({text:node.id.name+'=',start:node.start,end:node.start});}
FunctionDeclaration(node){changes.push({text:node.id.name+'=',start:node.start,end:node.start});return FormatterWorker.ESTreeWalker.SkipSubtree;}
FunctionExpression(node){return FormatterWorker.ESTreeWalker.SkipSubtree;}
ArrowFunctionExpression(node){return FormatterWorker.ESTreeWalker.SkipSubtree;}
MethodDefinition(node){return FormatterWorker.ESTreeWalker.SkipSubtree;}
AwaitExpression(node){containsAwait=true;}
ForOfStatement(node){if(node.await)
containsAwait=true;}
ReturnStatement(node){containsReturn=true;}
VariableDeclaration(node){if(node.kind!=='var'&&node.parent!==body)
return;if(node.parent.type==='ForOfStatement'&&node.parent.left===node)
return;const onlyOneDeclaration=node.declarations.length===1;changes.push({text:onlyOneDeclaration?'void':'void (',start:node.start,end:node.start+node.kind.length});for(const declaration of node.declarations){if(!declaration.init){changes.push({text:'(',start:declaration.start,end:declaration.start});changes.push({text:'=undefined)',start:declaration.end,end:declaration.end});continue;}
changes.push({text:'(',start:declaration.start,end:declaration.start});changes.push({text:')',start:declaration.end,end:declaration.end});}
if(!onlyOneDeclaration){const last=node.declarations.peekLast();changes.push({text:')',start:last.end,end:last.end});}}}
const walker=new FormatterWorker.ESTreeWalker(visit.bind(new Visitor()));walker.walk(body);function visit(node){if(node.type in this)
return this[node.type](node);}
if(!containsAwait||containsReturn){postMessage('');return;}
const last=body.body[body.body.length-1];if(last.type==='ExpressionStatement'){changes.push({text:'return (',start:last.start,end:last.start});if(wrapped[last.end-1]!==';')
changes.push({text:')',start:last.end,end:last.end});else
changes.push({text:')',start:last.end-1,end:last.end-1});}
while(changes.length){const change=changes.pop();wrapped=wrapped.substr(0,change.start)+change.text+wrapped.substr(change.end);}
postMessage(wrapped);};FormatterWorker.javaScriptIdentifiers=function(content){let root=null;try{root=acorn.parse(content,{ranges:false,ecmaVersion:9});}catch(e){}
const identifiers=[];const walker=new FormatterWorker.ESTreeWalker(beforeVisit);function isFunction(node){return node.type==='FunctionDeclaration'||node.type==='FunctionExpression'||node.type==='ArrowFunctionExpression';}
function beforeVisit(node){if(isFunction(node)){if(node.id)
identifiers.push(node.id);return FormatterWorker.ESTreeWalker.SkipSubtree;}
if(node.type!=='Identifier')
return;if(node.parent&&node.parent.type==='MemberExpression'&&node.parent.property===node&&!node.parent.computed)
return;identifiers.push(node);}
if(!root||root.type!=='Program'||root.body.length!==1||!isFunction(root.body[0])){postMessage([]);return;}
const functionNode=root.body[0];for(const param of functionNode.params)
walker.walk(param);walker.walk(functionNode.body);const reduced=identifiers.map(id=>({name:id.name,offset:id.start}));postMessage(reduced);};FormatterWorker.format=function(mimeType,text,indentString){indentString=indentString||' ';const result={};const builder=new FormatterWorker.FormattedContentBuilder(indentString);const lineEndings=text.computeLineEndings();try{switch(mimeType){case'text/html':{const formatter=new FormatterWorker.HTMLFormatter(builder);formatter.format(text,lineEndings);break;}
case'text/css':{const formatter=new FormatterWorker.CSSFormatter(builder);formatter.format(text,lineEndings,0,text.length);break;}
case'text/javascript':{const formatter=new FormatterWorker.JavaScriptFormatter(builder);formatter.format(text,lineEndings,0,text.length);break;}
default:{const formatter=new FormatterWorker.IdentityFormatter(builder);formatter.format(text,lineEndings,0,text.length);}}
result.mapping=builder.mapping();result.content=builder.content();}catch(e){console.error(e);result.mapping={original:[0],formatted:[0]};result.content=text;}
postMessage(result);};FormatterWorker.findLastFunctionCall=function(content){if(content.length>10000)
return null;try{const tokenizer=acorn.tokenizer(content,{ecmaVersion:9});while(tokenizer.getToken().type!==acorn.tokTypes.eof){}}catch(e){return null;}
const suffix='000)';const base=FormatterWorker._lastCompleteExpression(content,suffix,new Set(['CallExpression','NewExpression']));if(!base)
return null;const callee=base.baseNode['callee'];let functionName='';const functionProperty=callee.type==='Identifier'?callee:callee.property;if(functionProperty){if(functionProperty.type==='Identifier')
functionName=functionProperty.name;else if(functionProperty.type==='Literal')
functionName=functionProperty.value;}
const argumentIndex=base.baseNode['arguments'].length-1;const baseExpression=`(${base.baseExpression.substring(callee.start - base.baseNode.start, callee.end - base.baseNode.start)})`;const possibleSideEffects=FormatterWorker._nodeHasPossibleSideEffects(callee);let receiver='(function(){return this})()';if(callee.type==='MemberExpression'){const receiverBase=callee['object'];receiver=base.baseExpression.substring(receiverBase.start-base.baseNode.start,receiverBase.end-base.baseNode.start);}
return{baseExpression,receiver,possibleSideEffects,argumentIndex,functionName};};FormatterWorker.argumentsList=function(content){if(content.length>10000)
return[];let parsed=null;try{parsed=acorn.parse(`(${content})`,{ecmaVersion:9});}catch(e){}
if(!parsed){try{parsed=acorn.parse(`({${content}})`,{ecmaVersion:9});}catch(e){}}
if(!parsed||!parsed.body||!parsed.body[0]||!parsed.body[0].expression)
return[];const expression=parsed.body[0].expression;let params=null;switch(expression.type){case'ClassExpression':if(!expression.body.body)
break;const constructor=expression.body.body.find(method=>method.kind==='constructor');if(constructor)
params=constructor.value.params;break;case'ObjectExpression':if(!expression.properties[0]||!expression.properties[0].value)
break;params=expression.properties[0].value.params;break;case'FunctionExpression':case'ArrowFunctionExpression':params=expression.params;break;}
if(!params)
return[];return params.map(paramName);function paramName(param){switch(param.type){case'Identifier':return param.name;case'AssignmentPattern':return'?'+paramName(param.left);case'ObjectPattern':return'obj';case'ArrayPattern':return'arr';case'RestElement':return'...'+paramName(param.argument);}
return'?';}};FormatterWorker.findLastExpression=function(content){if(content.length>10000)
return null;try{const tokenizer=acorn.tokenizer(content,{ecmaVersion:9});while(tokenizer.getToken().type!==acorn.tokTypes.eof){}}catch(e){return null;}
const suffix='.DEVTOOLS';try{acorn.parse(content+suffix,{ecmaVersion:9});}catch(parseError){if(parseError.message.startsWith('Unexpected token')&&parseError.pos===content.length)
return null;}
const base=FormatterWorker._lastCompleteExpression(content,suffix,new Set(['MemberExpression','Identifier']));if(!base)
return null;const{baseExpression,baseNode}=base;const possibleSideEffects=FormatterWorker._nodeHasPossibleSideEffects(baseNode);return{baseExpression,possibleSideEffects};};FormatterWorker._lastCompleteExpression=function(content,suffix,types){let ast;let parsedContent='';for(let i=0;i<content.length;i++){try{parsedContent=content[i]==='{'?`(${content.substring(i)})${suffix}`:`${content.substring(i)}${suffix}`;ast=acorn.parse(parsedContent,{ecmaVersion:9});break;}catch(e){}}
if(!ast)
return null;let baseNode=null;const walker=new FormatterWorker.ESTreeWalker(node=>{if(baseNode||node.end<ast.end)
return FormatterWorker.ESTreeWalker.SkipSubtree;if(types.has(node.type))
baseNode=node;});walker.walk(ast);if(!baseNode)
return null;let baseExpression=parsedContent.substring(baseNode.start,parsedContent.length-suffix.length);if(baseExpression.startsWith('{'))
baseExpression=`(${baseExpression})`;return{baseNode,baseExpression};};FormatterWorker._nodeHasPossibleSideEffects=function(baseNode){const sideEffectFreeTypes=new Set(['MemberExpression','Identifier','BinaryExpression','Literal','TemplateLiteral','TemplateElement','ObjectExpression','ArrayExpression','Property','ThisExpression']);let possibleSideEffects=false;const sideEffectwalker=new FormatterWorker.ESTreeWalker(node=>{if(!possibleSideEffects&&!sideEffectFreeTypes.has(node.type))
possibleSideEffects=true;if(possibleSideEffects)
return FormatterWorker.ESTreeWalker.SkipSubtree;});sideEffectwalker.walk((baseNode));return possibleSideEffects;};FormatterWorker.FormatterWorkerContentParser=function(){};FormatterWorker.FormatterWorkerContentParser.prototype={parse(content){}};FormatterWorker.FormatterWorkerContentParser.parse=function(content,mimeType){const extension=self.runtime.extensions(FormatterWorker.FormatterWorkerContentParser).find(findExtension);console.assert(extension);extension.instance().then(instance=>instance.parse(content)).catchException(null).then(postMessage);function findExtension(extension){return extension.descriptor()['mimeType']===mimeType;}};(function disableLoggingForTest(){if(Runtime.queryParam('test'))
console.error=()=>undefined;})();;(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?factory(exports):typeof define==='function'&&define.amd?define(['exports'],factory):(factory((global.acorn={})));}(this,(function(exports){'use strict';var reservedWords={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var keywords={5:ecma5AndLessKeywords,6:ecma5AndLessKeywords+" const class extends export import super"};var keywordRelationalOperator=/^in(stanceof)?$/;var nonASCIIidentifierStartChars="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2
pos+=set[i+1];if(pos>=code){return true}}}
function isIdentifierStart(code,astral){if(code<65){return code===36}
if(code<91){return true}
if(code<97){return code===95}
if(code<123){return true}
if(code<=0xffff){return code>=0xaa&&nonASCIIidentifierStart.test(String.fromCharCode(code))}
if(astral===false){return false}
return isInAstralSet(code,astralIdentifierStartCodes)}
function isIdentifierChar(code,astral){if(code<48){return code===36}
if(code<58){return true}
if(code<65){return false}
if(code<91){return true}
if(code<97){return code===95}
if(code<123){return true}
if(code<=0xffff){return code>=0xaa&&nonASCIIidentifier.test(String.fromCharCode(code))}
if(astral===false){return false}
return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}
var TokenType=function TokenType(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null;};function binop(name,prec){return new TokenType(name,{beforeExpr:true,binop:prec})}
var beforeExpr={beforeExpr:true};var startsExpr={startsExpr:true};var keywords$1={};function kw(name,options){if(options===void 0)options={};options.keyword=name;return keywords$1[name]=new TokenType(name,options)}
var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("</>/<=/>=",7),bitShift:binop("<</>>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import"),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code,ecma2019String){return code===10||code===13||(!ecma2019String&&(code===0x2028||code===0x2029))}
var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}
var isArray=Array.isArray||(function(obj){return(toString.call(obj)==="[object Array]");});var Position=function Position(line,col){this.line=line;this.column=col;};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile;}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length;}else{return new Position(line,offset-cur)}}}
var defaultOptions={ecmaVersion:9,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:false,allowImportExportEverywhere:false,allowAwaitOutsideFunction:false,allowHashBang:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};function getOptions(opts){var options={};for(var opt in defaultOptions)
{options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];}
if(options.ecmaVersion>=2015)
{options.ecmaVersion-=2009;}
if(options.allowReserved==null)
{options.allowReserved=options.ecmaVersion<5;}
if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token);};}
if(isArray(options.onComment))
{options.onComment=pushComment(options,options.onComment);}
return options}
function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations)
{comment.loc=new SourceLocation(this,startLoc,endLoc);}
if(options.ranges)
{comment.range=[start,end];}
array.push(comment);}}
var SCOPE_TOP=1;var SCOPE_FUNCTION=2;var SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION;var SCOPE_ASYNC=4;var SCOPE_GENERATOR=8;var SCOPE_ARROW=16;var SCOPE_SIMPLE_CATCH=32;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}
var BIND_NONE=0;var BIND_VAR=1;var BIND_LEXICAL=2;var BIND_FUNCTION=3;var BIND_SIMPLE_CATCH=4;var BIND_OUTSIDE=5;function keywordRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}
var Parser=function Parser(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=keywordRegexp(keywords[options.ecmaVersion>=6?6:5]);var reserved="";if(!options.allowReserved){for(var v=options.ecmaVersion;;v--)
{if(reserved=reservedWords[v]){break}}
if(options.sourceType==="module"){reserved+=" await";}}
this.reservedWords=keywordRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=keywordRegexp(reservedStrict);this.reservedWordsStrictBind=keywordRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length;}else{this.pos=this.lineStart=0;this.curLine=1;}
this.type=types.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=0;this.labels=[];if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!")
{this.skipLineComment(2);}
this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null;};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true}};Parser.prototype.parse=function parse(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i<plugins.length;i++){cls=plugins[i](cls);}
return cls};Parser.parse=function parse(input,options){return new this(options,input).parse()};Parser.parseExpressionAt=function parseExpressionAt(input,pos,options){var parser=new this(options,input,pos);parser.nextToken();return parser.parseExpression()};Parser.tokenizer=function tokenizer(input,options){return new this(options,input)};Object.defineProperties(Parser.prototype,prototypeAccessors);var pp=Parser.prototype;var literal=/^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/;pp.strictDirective=function(start){var this$1=this;for(;;){skipWhiteSpace.lastIndex=start;start+=skipWhiteSpace.exec(this$1.input)[0].length;var match=literal.exec(this$1.input.slice(start));if(!match){return false}
if((match[1]||match[2])==="use strict"){return true}
start+=match[0].length;}};pp.eat=function(type){if(this.type===type){this.next();return true}else{return false}};pp.isContextual=function(name){return this.type===types.name&&this.value===name&&!this.containsEsc};pp.eatContextual=function(name){if(!this.isContextual(name)){return false}
this.next();return true};pp.expectContextual=function(name){if(!this.eatContextual(name)){this.unexpected();}};pp.canInsertSemicolon=function(){return this.type===types.eof||this.type===types.braceR||lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon)
{this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc);}
return true}};pp.semicolon=function(){if(!this.eat(types.semi)&&!this.insertSemicolon()){this.unexpected();}};pp.afterTrailingComma=function(tokType,notNext){if(this.type===tokType){if(this.options.onTrailingComma)
{this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc);}
if(!notNext)
{this.next();}
return true}};pp.expect=function(type){this.eat(type)||this.unexpected();};pp.unexpected=function(pos){this.raise(pos!=null?pos:this.start,"Unexpected token");};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1;}
pp.checkPatternErrors=function(refDestructuringErrors,isAssign){if(!refDestructuringErrors){return}
if(refDestructuringErrors.trailingComma>-1)
{this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element");}
var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern");}};pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}
var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}
if(shorthandAssign>=0)
{this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns");}
if(doubleProto>=0)
{this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property");}};pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos))
{this.raise(this.yieldPos,"Yield expression cannot be a default value");}
if(this.awaitPos)
{this.raise(this.awaitPos,"Await expression cannot be a default value");}};pp.isSimpleAssignTarget=function(expr){if(expr.type==="ParenthesizedExpression")
{return this.isSimpleAssignTarget(expr.expression)}
return expr.type==="Identifier"||expr.type==="MemberExpression"};var pp$1=Parser.prototype;pp$1.parseTopLevel=function(node){var this$1=this;var exports={};if(!node.body){node.body=[];}
while(this.type!==types.eof){var stmt=this$1.parseStatement(null,true,exports);node.body.push(stmt);}
this.adaptDirectivePrologue(node.body);this.next();if(this.options.ecmaVersion>=6){node.sourceType=this.options.sourceType;}
return this.finishNode(node,"Program")};var loopLabel={kind:"loop"};var switchLabel={kind:"switch"};pp$1.isLet=function(){if(this.options.ecmaVersion<6||!this.isContextual("let")){return false}
skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===91||nextCh===123){return true}
if(isIdentifierStart(nextCh,true)){var pos=next+1;while(isIdentifierChar(this.input.charCodeAt(pos),true)){++pos;}
var ident=this.input.slice(next,pos);if(!keywordRelationalOperator.test(ident)){return true}}
return false};pp$1.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))
{return false}
skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length;return!lineBreak.test(this.input.slice(this.pos,next))&&this.input.slice(next,next+8)==="function"&&(next+8===this.input.length||!isIdentifierChar(this.input.charAt(next+8)))};pp$1.parseStatement=function(context,topLevel,exports){var starttype=this.type,node=this.startNode(),kind;if(this.isLet()){starttype=types._var;kind="let";}
switch(starttype){case types._break:case types._continue:return this.parseBreakContinueStatement(node,starttype.keyword)
case types._debugger:return this.parseDebuggerStatement(node)
case types._do:return this.parseDoStatement(node)
case types._for:return this.parseForStatement(node)
case types._function:if((context&&(this.strict||context!=="if"))&&this.options.ecmaVersion>=6){this.unexpected();}
return this.parseFunctionStatement(node,false,!context)
case types._class:if(context){this.unexpected();}
return this.parseClass(node,true)
case types._if:return this.parseIfStatement(node)
case types._return:return this.parseReturnStatement(node)
case types._switch:return this.parseSwitchStatement(node)
case types._throw:return this.parseThrowStatement(node)
case types._try:return this.parseTryStatement(node)
case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected();}
return this.parseVarStatement(node,kind)
case types._while:return this.parseWhileStatement(node)
case types._with:return this.parseWithStatement(node)
case types.braceL:return this.parseBlock(true,node)
case types.semi:return this.parseEmptyStatement(node)
case types._export:case types._import:if(!this.options.allowImportExportEverywhere){if(!topLevel)
{this.raise(this.start,"'import' and 'export' may only appear at the top level");}
if(!this.inModule)
{this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'");}}
return starttype===types._import?this.parseImport(node):this.parseExport(node,exports)
default:if(this.isAsyncFunction()){if(context){this.unexpected();}
this.next();return this.parseFunctionStatement(node,true,!context)}
var maybeName=this.value,expr=this.parseExpression();if(starttype===types.name&&expr.type==="Identifier"&&this.eat(types.colon))
{return this.parseLabeledStatement(node,maybeName,expr,context)}
else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var this$1=this;var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null;}
else if(this.type!==types.name){this.unexpected();}
else{node.label=this.parseIdent();this.semicolon();}
var i=0;for(;i<this.labels.length;++i){var lab=this$1.labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop")){break}
if(node.label&&isBreak){break}}}
if(i===this.labels.length){this.raise(node.start,"Unsyntactic "+keyword);}
return this.finishNode(node,isBreak?"BreakStatement":"ContinueStatement")};pp$1.parseDebuggerStatement=function(node){this.next();this.semicolon();return this.finishNode(node,"DebuggerStatement")};pp$1.parseDoStatement=function(node){this.next();this.labels.push(loopLabel);node.body=this.parseStatement("do");this.labels.pop();this.expect(types._while);node.test=this.parseParenExpression();if(this.options.ecmaVersion>=6)
{this.eat(types.semi);}
else
{this.semicolon();}
return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=(this.options.ecmaVersion>=9&&(this.inAsync||(!this.inFunction&&this.options.allowAwaitOutsideFunction))&&this.eatContextual("await"))?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt);}
return this.parseFor(node,null)}
var isLet=this.isLet();if(this.type===types._var||this.type===types._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types._in||(this.options.ecmaVersion>=6&&this.isContextual("of")))&&init$1.declarations.length===1&&!(kind!=="var"&&init$1.declarations[0].init)){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt);}}else{node.await=awaitAt>-1;}}
return this.parseForIn(node,init$1)}
if(awaitAt>-1){this.unexpected(awaitAt);}
return this.parseFor(node,init$1)}
var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||(this.options.ecmaVersion>=6&&this.isContextual("of"))){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt);}}else{node.await=awaitAt>-1;}}
this.toAssignable(init,false,refDestructuringErrors);this.checkLVal(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true);}
if(awaitAt>-1){this.unexpected(awaitAt);}
return this.parseFor(node,init)};pp$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction)
{this.raise(this.start,"'return' outside of function");}
this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null;}
else{node.argument=this.parseExpression();this.semicolon();}
return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){var this$1=this;this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this$1.type===types._case||this$1.type===types._default){var isCase=this$1.type===types._case;if(cur){this$1.finishNode(cur,"SwitchCase");}
node.cases.push(cur=this$1.startNode());cur.consequent=[];this$1.next();if(isCase){cur.test=this$1.parseExpression();}else{if(sawDefault){this$1.raiseRecoverable(this$1.lastTokStart,"Multiple default clauses");}
sawDefault=true;cur.test=null;}
this$1.expect(types.colon);}else{if(!cur){this$1.unexpected();}
cur.consequent.push(this$1.parseStatement(null));}}
this.exitScope();if(cur){this.finishNode(cur,"SwitchCase");}
this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$1.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))
{this.raise(this.lastTokEnd,"Illegal newline after throw");}
node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLVal(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types.parenR);}else{if(this.options.ecmaVersion<10){this.unexpected();}
clause.param=null;this.enterScope(0);}
clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause");}
node.finalizer=this.eat(types._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer)
{this.raise(node.start,"Missing catch or finally clause");}
return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$1.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode");}
this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.parseLabeledStatement=function(node,maybeName,expr,context){var this$1=this;for(var i$1=0,list=this$1.labels;i$1<list.length;i$1+=1)
{var label=list[i$1];if(label.name===maybeName)
{this$1.raise(expr.start,"Label '"+maybeName+"' is already declared");}}
var kind=this.type.isLoop?"loop":this.type===types._switch?"switch":null;for(var i=this.labels.length-1;i>=0;i--){var label$1=this$1.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this$1.start;label$1.kind=kind;}else{break}}
this.labels.push({name:maybeName,kind:kind,statementStart:this.start});node.body=this.parseStatement(context);if(node.body.type==="ClassDeclaration"||node.body.type==="VariableDeclaration"&&node.body.kind!=="var"||node.body.type==="FunctionDeclaration"&&(this.strict||node.body.generator||node.body.async))
{this.raiseRecoverable(node.body.start,"Invalid labeled declaration");}
this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node){var this$1=this;if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0);}
while(!this.eat(types.braceR)){var stmt=this$1.parseStatement(null);node.body.push(stmt);}
if(createNewLexicalScope){this.exitScope();}
return this.finishNode(node,"BlockStatement")};pp$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);this.exitScope();node.body=this.parseStatement("for");this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var type=this.type===types._in?"ForInStatement":"ForOfStatement";this.next();if(type==="ForInStatement"){if(init.type==="AssignmentPattern"||(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(this.strict||init.declarations[0].id.type!=="Identifier")))
{this.raise(init.start,"Invalid assignment in for-in loop head");}}
node.left=init;node.right=type==="ForInStatement"?this.parseExpression():this.parseMaybeAssign();this.expect(types.parenR);this.exitScope();node.body=this.parseStatement("for");this.labels.pop();return this.finishNode(node,type)};pp$1.parseVar=function(node,isFor,kind){var this$1=this;node.declarations=[];node.kind=kind;for(;;){var decl=this$1.startNode();this$1.parseVarId(decl,kind);if(this$1.eat(types.eq)){decl.init=this$1.parseMaybeAssign(isFor);}else if(kind==="const"&&!(this$1.type===types._in||(this$1.options.ecmaVersion>=6&&this$1.isContextual("of")))){this$1.unexpected();}else if(decl.id.type!=="Identifier"&&!(isFor&&(this$1.type===types._in||this$1.isContextual("of")))){this$1.raise(this$1.lastTokEnd,"Complex binding patterns require an initialization value");}else{decl.init=null;}
node.declarations.push(this$1.finishNode(decl,"VariableDeclarator"));if(!this$1.eat(types.comma)){break}}
return node};pp$1.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom(kind);this.checkLVal(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false);};var FUNC_STATEMENT=1;var FUNC_HANGING_STATEMENT=2;var FUNC_NULLABLE_ID=4;pp$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync)
{node.generator=this.eat(types.star);}
if(this.options.ecmaVersion>=8)
{node.async=!!isAsync;}
if(statement&FUNC_STATEMENT){node.id=(statement&FUNC_NULLABLE_ID)&&this.type!==types.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT))
{this.checkLVal(node.id,this.inModule&&!this.inFunction?BIND_LEXICAL:BIND_FUNCTION);}}
var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos;this.yieldPos=0;this.awaitPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT))
{node.id=this.type===types.name?this.parseIdent():null;}
this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.finishNode(node,(statement&FUNC_STATEMENT)?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();};pp$1.parseClass=function(node,isStatement){var this$1=this;this.next();this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(!this.eat(types.braceR)){var element=this$1.parseClassElement();if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this$1.raise(element.start,"Duplicate constructor in the same class");}
hadConstructor=true;}}}
node.body=this.finishNode(classBody,"ClassBody");return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(){var this$1=this;if(this.eat(types.semi)){return null}
var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}
if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}
if(method.key){this$1.unexpected();}
method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);}else if(tryContextual("get")){method.kind="get";}else if(tryContextual("set")){method.kind="set";}}
if(!method.key){this.parsePropertyName(method);}
var key=method.key;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier");}
if(isGenerator){this.raise(key.start,"Constructor can't be a generator");}
if(isAsync){this.raise(key.start,"Constructor can't be an async method");}
method.kind="constructor";}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype");}
this.parseClassMethod(method,isGenerator,isAsync);if(method.kind==="get"&&method.value.params.length!==0)
{this.raiseRecoverable(method.value.start,"getter should have no params");}
if(method.kind==="set"&&method.value.params.length!==1)
{this.raiseRecoverable(method.value.start,"setter should have exactly one param");}
if(method.kind==="set"&&method.value.params[0].type==="RestElement")
{this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params");}
return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync){method.value=this.parseMethod(isGenerator,isAsync);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){node.id=this.type===types.name?this.parseIdent():isStatement===true?this.unexpected():null;};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null;};pp$1.parseExport=function(node,exports){var this$1=this;this.next();if(this.eat(types.star)){this.expectContextual("from");if(this.type!==types.string){this.unexpected();}
node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}
if(this.eat(types._default)){this.checkExport(exports,"default",this.lastTokStart);var isAsync;if(this.type===types._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next();}
node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync,true);}else if(this.type===types._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID");}else{node.declaration=this.parseMaybeAssign();this.semicolon();}
return this.finishNode(node,"ExportDefaultDeclaration")}
if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration")
{this.checkVariableExport(exports,node.declaration.declarations);}
else
{this.checkExport(exports,node.declaration.id.name,node.declaration.id.start);}
node.specifiers=[];node.source=null;}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports);if(this.eatContextual("from")){if(this.type!==types.string){this.unexpected();}
node.source=this.parseExprAtom();}else{for(var i=0,list=node.specifiers;i<list.length;i+=1){var spec=list[i];this$1.checkUnreserved(spec.local);}
node.source=null;}
this.semicolon();}
return this.finishNode(node,"ExportNamedDeclaration")};pp$1.checkExport=function(exports,name,pos){if(!exports){return}
if(has(exports,name))
{this.raiseRecoverable(pos,"Duplicate export '"+name+"'");}
exports[name]=true;};pp$1.checkPatternExport=function(exports,pat){var this$1=this;var type=pat.type;if(type==="Identifier")
{this.checkExport(exports,pat.name,pat.start);}
else if(type==="ObjectPattern")
{for(var i=0,list=pat.properties;i<list.length;i+=1)
{var prop=list[i];this$1.checkPatternExport(exports,prop);}}
else if(type==="ArrayPattern")
{for(var i$1=0,list$1=pat.elements;i$1<list$1.length;i$1+=1){var elt=list$1[i$1];if(elt){this$1.checkPatternExport(exports,elt);}}}
else if(type==="Property")
{this.checkPatternExport(exports,pat.value);}
else if(type==="AssignmentPattern")
{this.checkPatternExport(exports,pat.left);}
else if(type==="RestElement")
{this.checkPatternExport(exports,pat.argument);}
else if(type==="ParenthesizedExpression")
{this.checkPatternExport(exports,pat.expression);}};pp$1.checkVariableExport=function(exports,decls){var this$1=this;if(!exports){return}
for(var i=0,list=decls;i<list.length;i+=1)
{var decl=list[i];this$1.checkPatternExport(exports,decl.id);}};pp$1.shouldParseExportStatement=function(){return this.type.keyword==="var"||this.type.keyword==="const"||this.type.keyword==="class"||this.type.keyword==="function"||this.isLet()||this.isAsyncFunction()};pp$1.parseExportSpecifiers=function(exports){var this$1=this;var nodes=[],first=true;this.expect(types.braceL);while(!this.eat(types.braceR)){if(!first){this$1.expect(types.comma);if(this$1.afterTrailingComma(types.braceR)){break}}else{first=false;}
var node=this$1.startNode();node.local=this$1.parseIdent(true);node.exported=this$1.eatContextual("as")?this$1.parseIdent(true):node.local;this$1.checkExport(exports,node.exported.name,node.exported.start);nodes.push(this$1.finishNode(node,"ExportSpecifier"));}
return nodes};pp$1.parseImport=function(node){this.next();if(this.type===types.string){node.specifiers=empty;node.source=this.parseExprAtom();}else{node.specifiers=this.parseImportSpecifiers();this.expectContextual("from");node.source=this.type===types.string?this.parseExprAtom():this.unexpected();}
this.semicolon();return this.finishNode(node,"ImportDeclaration")};pp$1.parseImportSpecifiers=function(){var this$1=this;var nodes=[],first=true;if(this.type===types.name){var node=this.startNode();node.local=this.parseIdent();this.checkLVal(node.local,BIND_LEXICAL);nodes.push(this.finishNode(node,"ImportDefaultSpecifier"));if(!this.eat(types.comma)){return nodes}}
if(this.type===types.star){var node$1=this.startNode();this.next();this.expectContextual("as");node$1.local=this.parseIdent();this.checkLVal(node$1.local,BIND_LEXICAL);nodes.push(this.finishNode(node$1,"ImportNamespaceSpecifier"));return nodes}
this.expect(types.braceL);while(!this.eat(types.braceR)){if(!first){this$1.expect(types.comma);if(this$1.afterTrailingComma(types.braceR)){break}}else{first=false;}
var node$2=this$1.startNode();node$2.imported=this$1.parseIdent(true);if(this$1.eatContextual("as")){node$2.local=this$1.parseIdent();}else{this$1.checkUnreserved(node$2.imported);node$2.local=node$2.imported;}
this$1.checkLVal(node$2.local,BIND_LEXICAL);nodes.push(this$1.finishNode(node$2,"ImportSpecifier"));}
return nodes};pp$1.adaptDirectivePrologue=function(statements){for(var i=0;i<statements.length&&this.isDirectiveCandidate(statements[i]);++i){statements[i].directive=statements[i].expression.raw.slice(1,-1);}};pp$1.isDirectiveCandidate=function(statement){return(statement.type==="ExpressionStatement"&&statement.expression.type==="Literal"&&typeof statement.expression.value==="string"&&(this.input[statement.start]==="\""||this.input[statement.start]==="'"))};var pp$2=Parser.prototype;pp$2.toAssignable=function(node,isBinding,refDestructuringErrors){var this$1=this;if(this.options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await")
{this.raise(node.start,"Can not use 'await' as identifier inside an async function");}
break
case"ObjectPattern":case"ArrayPattern":case"RestElement":break
case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true);}
for(var i=0,list=node.properties;i<list.length;i+=1){var prop=list[i];this$1.toAssignable(prop,isBinding);if(prop.type==="RestElement"&&(prop.argument.type==="ArrayPattern"||prop.argument.type==="ObjectPattern")){this$1.raise(prop.argument.start,"Unexpected token");}}
break
case"Property":if(node.kind!=="init"){this.raise(node.key.start,"Object pattern can't contain getter or setter");}
this.toAssignable(node.value,isBinding);break
case"ArrayExpression":node.type="ArrayPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true);}
this.toAssignableList(node.elements,isBinding);break
case"SpreadElement":node.type="RestElement";this.toAssignable(node.argument,isBinding);if(node.argument.type==="AssignmentPattern")
{this.raise(node.argument.start,"Rest elements cannot have a default value");}
break
case"AssignmentExpression":if(node.operator!=="="){this.raise(node.left.end,"Only '=' operator can be used for specifying default value.");}
node.type="AssignmentPattern";delete node.operator;this.toAssignable(node.left,isBinding);case"AssignmentPattern":break
case"ParenthesizedExpression":this.toAssignable(node.expression,isBinding);break
case"MemberExpression":if(!isBinding){break}
default:this.raise(node.start,"Assigning to rvalue");}}else if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true);}
return node};pp$2.toAssignableList=function(exprList,isBinding){var this$1=this;var end=exprList.length;for(var i=0;i<end;i++){var elt=exprList[i];if(elt){this$1.toAssignable(elt,isBinding);}}
if(end){var last=exprList[end-1];if(this.options.ecmaVersion===6&&isBinding&&last&&last.type==="RestElement"&&last.argument.type!=="Identifier")
{this.unexpected(last.argument.start);}}
return exprList};pp$2.parseSpread=function(refDestructuringErrors){var node=this.startNode();this.next();node.argument=this.parseMaybeAssign(false,refDestructuringErrors);return this.finishNode(node,"SpreadElement")};pp$2.parseRestBinding=function(){var node=this.startNode();this.next();if(this.options.ecmaVersion===6&&this.type!==types.name)
{this.unexpected();}
node.argument=this.parseBindingAtom();return this.finishNode(node,"RestElement")};pp$2.parseBindingAtom=function(){if(this.options.ecmaVersion>=6){switch(this.type){case types.bracketL:var node=this.startNode();this.next();node.elements=this.parseBindingList(types.bracketR,true,true);return this.finishNode(node,"ArrayPattern")
case types.braceL:return this.parseObj(true)}}
return this.parseIdent()};pp$2.parseBindingList=function(close,allowEmpty,allowTrailingComma){var this$1=this;var elts=[],first=true;while(!this.eat(close)){if(first){first=false;}
else{this$1.expect(types.comma);}
if(allowEmpty&&this$1.type===types.comma){elts.push(null);}else if(allowTrailingComma&&this$1.afterTrailingComma(close)){break}else if(this$1.type===types.ellipsis){var rest=this$1.parseRestBinding();this$1.parseBindingListItem(rest);elts.push(rest);if(this$1.type===types.comma){this$1.raise(this$1.start,"Comma is not permitted after the rest element");}
this$1.expect(close);break}else{var elem=this$1.parseMaybeDefault(this$1.start,this$1.startLoc);this$1.parseBindingListItem(elem);elts.push(elem);}}
return elts};pp$2.parseBindingListItem=function(param){return param};pp$2.parseMaybeDefault=function(startPos,startLoc,left){left=left||this.parseBindingAtom();if(this.options.ecmaVersion<6||!this.eat(types.eq)){return left}
var node=this.startNodeAt(startPos,startLoc);node.left=left;node.right=this.parseMaybeAssign();return this.finishNode(node,"AssignmentPattern")};pp$2.checkLVal=function(expr,bindingType,checkClashes){var this$1=this;if(bindingType===void 0)bindingType=BIND_NONE;switch(expr.type){case"Identifier":if(this.strict&&this.reservedWordsStrictBind.test(expr.name))
{this.raiseRecoverable(expr.start,(bindingType?"Binding ":"Assigning to ")+expr.name+" in strict mode");}
if(checkClashes){if(has(checkClashes,expr.name))
{this.raiseRecoverable(expr.start,"Argument name clash");}
checkClashes[expr.name]=true;}
if(bindingType!==BIND_NONE&&bindingType!==BIND_OUTSIDE){this.declareName(expr.name,bindingType,expr.start);}
break
case"MemberExpression":if(bindingType){this.raiseRecoverable(expr.start,"Binding member expression");}
break
case"ObjectPattern":for(var i=0,list=expr.properties;i<list.length;i+=1)
{var prop=list[i];this$1.checkLVal(prop,bindingType,checkClashes);}
break
case"Property":this.checkLVal(expr.value,bindingType,checkClashes);break
case"ArrayPattern":for(var i$1=0,list$1=expr.elements;i$1<list$1.length;i$1+=1){var elem=list$1[i$1];if(elem){this$1.checkLVal(elem,bindingType,checkClashes);}}
break
case"AssignmentPattern":this.checkLVal(expr.left,bindingType,checkClashes);break
case"RestElement":this.checkLVal(expr.argument,bindingType,checkClashes);break
case"ParenthesizedExpression":this.checkLVal(expr.expression,bindingType,checkClashes);break
default:this.raise(expr.start,(bindingType?"Binding":"Assigning to")+" rvalue");}};var pp$3=Parser.prototype;pp$3.checkPropClash=function(prop,propHash,refDestructuringErrors){if(this.options.ecmaVersion>=9&&prop.type==="SpreadElement")
{return}
if(this.options.ecmaVersion>=6&&(prop.computed||prop.method||prop.shorthand))
{return}
var key=prop.key;var name;switch(key.type){case"Identifier":name=key.name;break
case"Literal":name=String(key.value);break
default:return}
var kind=prop.kind;if(this.options.ecmaVersion>=6){if(name==="__proto__"&&kind==="init"){if(propHash.proto){if(refDestructuringErrors&&refDestructuringErrors.doubleProto<0){refDestructuringErrors.doubleProto=key.start;}
else{this.raiseRecoverable(key.start,"Redefinition of __proto__ property");}}
propHash.proto=true;}
return}
name="$"+name;var other=propHash[name];if(other){var redefinition;if(kind==="init"){redefinition=this.strict&&other.init||other.get||other.set;}else{redefinition=other.init||other[kind];}
if(redefinition)
{this.raiseRecoverable(key.start,"Redefinition of property");}}else{other=propHash[name]={init:false,get:false,set:false};}
other[kind]=true;};pp$3.parseExpression=function(noIn,refDestructuringErrors){var this$1=this;var startPos=this.start,startLoc=this.startLoc;var expr=this.parseMaybeAssign(noIn,refDestructuringErrors);if(this.type===types.comma){var node=this.startNodeAt(startPos,startLoc);node.expressions=[expr];while(this.eat(types.comma)){node.expressions.push(this$1.parseMaybeAssign(noIn,refDestructuringErrors));}
return this.finishNode(node,"SequenceExpression")}
return expr};pp$3.parseMaybeAssign=function(noIn,refDestructuringErrors,afterLeftParse){if(this.isContextual("yield")){if(this.inGenerator){return this.parseYield()}
else{this.exprAllowed=false;}}
var ownDestructuringErrors=false,oldParenAssign=-1,oldTrailingComma=-1;if(refDestructuringErrors){oldParenAssign=refDestructuringErrors.parenthesizedAssign;oldTrailingComma=refDestructuringErrors.trailingComma;refDestructuringErrors.parenthesizedAssign=refDestructuringErrors.trailingComma=-1;}else{refDestructuringErrors=new DestructuringErrors;ownDestructuringErrors=true;}
var startPos=this.start,startLoc=this.startLoc;if(this.type===types.parenL||this.type===types.name)
{this.potentialArrowAt=this.start;}
var left=this.parseMaybeConditional(noIn,refDestructuringErrors);if(afterLeftParse){left=afterLeftParse.call(this,left,startPos,startLoc);}
if(this.type.isAssign){var node=this.startNodeAt(startPos,startLoc);node.operator=this.value;node.left=this.type===types.eq?this.toAssignable(left,false,refDestructuringErrors):left;if(!ownDestructuringErrors){DestructuringErrors.call(refDestructuringErrors);}
refDestructuringErrors.shorthandAssign=-1;this.checkLVal(left);this.next();node.right=this.parseMaybeAssign(noIn);return this.finishNode(node,"AssignmentExpression")}else{if(ownDestructuringErrors){this.checkExpressionErrors(refDestructuringErrors,true);}}
if(oldParenAssign>-1){refDestructuringErrors.parenthesizedAssign=oldParenAssign;}
if(oldTrailingComma>-1){refDestructuringErrors.trailingComma=oldTrailingComma;}
return left};pp$3.parseMaybeConditional=function(noIn,refDestructuringErrors){var startPos=this.start,startLoc=this.startLoc;var expr=this.parseExprOps(noIn,refDestructuringErrors);if(this.checkExpressionErrors(refDestructuringErrors)){return expr}
if(this.eat(types.question)){var node=this.startNodeAt(startPos,startLoc);node.test=expr;node.consequent=this.parseMaybeAssign();this.expect(types.colon);node.alternate=this.parseMaybeAssign(noIn);return this.finishNode(node,"ConditionalExpression")}
return expr};pp$3.parseExprOps=function(noIn,refDestructuringErrors){var startPos=this.start,startLoc=this.startLoc;var expr=this.parseMaybeUnary(refDestructuringErrors,false);if(this.checkExpressionErrors(refDestructuringErrors)){return expr}
return expr.start===startPos&&expr.type==="ArrowFunctionExpression"?expr:this.parseExprOp(expr,startPos,startLoc,-1,noIn)};pp$3.parseExprOp=function(left,leftStartPos,leftStartLoc,minPrec,noIn){var prec=this.type.binop;if(prec!=null&&(!noIn||this.type!==types._in)){if(prec>minPrec){var logical=this.type===types.logicalOR||this.type===types.logicalAND;var op=this.value;this.next();var startPos=this.start,startLoc=this.startLoc;var right=this.parseExprOp(this.parseMaybeUnary(null,false),startPos,startLoc,prec,noIn);var node=this.buildBinary(leftStartPos,leftStartLoc,left,right,op,logical);return this.parseExprOp(node,leftStartPos,leftStartLoc,minPrec,noIn)}}
return left};pp$3.buildBinary=function(startPos,startLoc,left,right,op,logical){var node=this.startNodeAt(startPos,startLoc);node.left=left;node.operator=op;node.right=right;return this.finishNode(node,logical?"LogicalExpression":"BinaryExpression")};pp$3.parseMaybeUnary=function(refDestructuringErrors,sawUnary){var this$1=this;var startPos=this.start,startLoc=this.startLoc,expr;if(this.isContextual("await")&&(this.inAsync||(!this.inFunction&&this.options.allowAwaitOutsideFunction))){expr=this.parseAwait();sawUnary=true;}else if(this.type.prefix){var node=this.startNode(),update=this.type===types.incDec;node.operator=this.value;node.prefix=true;this.next();node.argument=this.parseMaybeUnary(null,true);this.checkExpressionErrors(refDestructuringErrors,true);if(update){this.checkLVal(node.argument);}
else if(this.strict&&node.operator==="delete"&&node.argument.type==="Identifier")
{this.raiseRecoverable(node.start,"Deleting local variable in strict mode");}
else{sawUnary=true;}
expr=this.finishNode(node,update?"UpdateExpression":"UnaryExpression");}else{expr=this.parseExprSubscripts(refDestructuringErrors);if(this.checkExpressionErrors(refDestructuringErrors)){return expr}
while(this.type.postfix&&!this.canInsertSemicolon()){var node$1=this$1.startNodeAt(startPos,startLoc);node$1.operator=this$1.value;node$1.prefix=false;node$1.argument=expr;this$1.checkLVal(expr);this$1.next();expr=this$1.finishNode(node$1,"UpdateExpression");}}
if(!sawUnary&&this.eat(types.starstar))
{return this.buildBinary(startPos,startLoc,expr,this.parseMaybeUnary(null,false),"**",false)}
else
{return expr}};pp$3.parseExprSubscripts=function(refDestructuringErrors){var startPos=this.start,startLoc=this.startLoc;var expr=this.parseExprAtom(refDestructuringErrors);var skipArrowSubscripts=expr.type==="ArrowFunctionExpression"&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==")";if(this.checkExpressionErrors(refDestructuringErrors)||skipArrowSubscripts){return expr}
var result=this.parseSubscripts(expr,startPos,startLoc);if(refDestructuringErrors&&result.type==="MemberExpression"){if(refDestructuringErrors.parenthesizedAssign>=result.start){refDestructuringErrors.parenthesizedAssign=-1;}
if(refDestructuringErrors.parenthesizedBind>=result.start){refDestructuringErrors.parenthesizedBind=-1;}}
return result};pp$3.parseSubscripts=function(base,startPos,startLoc,noCalls){var this$1=this;var maybeAsyncArrow=this.options.ecmaVersion>=8&&base.type==="Identifier"&&base.name==="async"&&this.lastTokEnd===base.end&&!this.canInsertSemicolon()&&this.input.slice(base.start,base.end)==="async";for(var computed=(void 0);;){if((computed=this$1.eat(types.bracketL))||this$1.eat(types.dot)){var node=this$1.startNodeAt(startPos,startLoc);node.object=base;node.property=computed?this$1.parseExpression():this$1.parseIdent(true);node.computed=!!computed;if(computed){this$1.expect(types.bracketR);}
base=this$1.finishNode(node,"MemberExpression");}else if(!noCalls&&this$1.eat(types.parenL)){var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this$1.yieldPos,oldAwaitPos=this$1.awaitPos;this$1.yieldPos=0;this$1.awaitPos=0;var exprList=this$1.parseExprList(types.parenR,this$1.options.ecmaVersion>=8,false,refDestructuringErrors);if(maybeAsyncArrow&&!this$1.canInsertSemicolon()&&this$1.eat(types.arrow)){this$1.checkPatternErrors(refDestructuringErrors,false);this$1.checkYieldAwaitInDefaultParams();this$1.yieldPos=oldYieldPos;this$1.awaitPos=oldAwaitPos;return this$1.parseArrowExpression(this$1.startNodeAt(startPos,startLoc),exprList,true)}
this$1.checkExpressionErrors(refDestructuringErrors,true);this$1.yieldPos=oldYieldPos||this$1.yieldPos;this$1.awaitPos=oldAwaitPos||this$1.awaitPos;var node$1=this$1.startNodeAt(startPos,startLoc);node$1.callee=base;node$1.arguments=exprList;base=this$1.finishNode(node$1,"CallExpression");}else if(this$1.type===types.backQuote){var node$2=this$1.startNodeAt(startPos,startLoc);node$2.tag=base;node$2.quasi=this$1.parseTemplate({isTagged:true});base=this$1.finishNode(node$2,"TaggedTemplateExpression");}else{return base}}};pp$3.parseExprAtom=function(refDestructuringErrors){var node,canBeArrow=this.potentialArrowAt===this.start;switch(this.type){case types._super:if(!this.inFunction)
{this.raise(this.start,"'super' outside of function or class");}
node=this.startNode();this.next();if(this.type!==types.dot&&this.type!==types.bracketL&&this.type!==types.parenL)
{this.unexpected();}
return this.finishNode(node,"Super")
case types._this:node=this.startNode();this.next();return this.finishNode(node,"ThisExpression")
case types.name:var startPos=this.start,startLoc=this.startLoc,containsEsc=this.containsEsc;var id=this.parseIdent(this.type!==types.name);if(this.options.ecmaVersion>=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types._function))
{return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}
if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow))
{return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}
if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent();if(this.canInsertSemicolon()||!this.eat(types.arrow))
{this.unexpected();}
return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}
return id
case types.regexp:var value=this.value;node=this.parseLiteral(value.value);node.regex={pattern:value.pattern,flags:value.flags};return node
case types.num:case types.string:return this.parseLiteral(this.value)
case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal")
case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr))
{refDestructuringErrors.parenthesizedAssign=start;}
if(refDestructuringErrors.parenthesizedBind<0)
{refDestructuringErrors.parenthesizedBind=start;}}
return expr
case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression")
case types.braceL:return this.parseObj(false,refDestructuringErrors)
case types._function:node=this.startNode();this.next();return this.parseFunction(node,0)
case types._class:return this.parseClass(this.startNode(),false)
case types._new:return this.parseNew()
case types.backQuote:return this.parseTemplate()
default:this.unexpected();}};pp$3.parseLiteral=function(value){var node=this.startNode();node.value=value;node.raw=this.input.slice(this.start,this.end);this.next();return this.finishNode(node,"Literal")};pp$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var this$1=this;var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types.parenR){first?first=false:this$1.expect(types.comma);if(allowTrailingComma&&this$1.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this$1.type===types.ellipsis){spreadStart=this$1.start;exprList.push(this$1.parseParenItem(this$1.parseRestBinding()));if(this$1.type===types.comma){this$1.raise(this$1.start,"Comma is not permitted after the rest element");}
break}else{exprList.push(this$1.parseMaybeAssign(false,refDestructuringErrors,this$1.parseParenItem));}}
var innerEndPos=this.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}
if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart);}
if(spreadStart){this.unexpected(spreadStart);}
this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc);}else{val=exprList[0];}}else{val=this.parseParenExpression();}
if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.parseNew=function(){var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"||containsEsc)
{this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target");}
if(!this.inNonArrowFunction())
{this.raiseRecoverable(node.start,"new.target can only be used in functions");}
return this.finishNode(node,"MetaProperty")}
var startPos=this.start,startLoc=this.startLoc;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false);}
else{node.arguments=empty$1;}
return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref){var isTagged=ref.isTagged;var elem=this.startNode();if(this.type===types.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal");}
elem.value={raw:this.value,cooked:null};}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value};}
this.next();elem.tail=this.type===types.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.parseTemplate=function(ref){var this$1=this;if(ref===void 0)ref={};var isTagged=ref.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged:isTagged});node.quasis=[curElt];while(!curElt.tail){if(this$1.type===types.eof){this$1.raise(this$1.pos,"Unterminated template literal");}
this$1.expect(types.dollarBraceL);node.expressions.push(this$1.parseExpression());this$1.expect(types.braceR);node.quasis.push(curElt=this$1.parseTemplateElement({isTagged:isTagged}));}
this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||(this.options.ecmaVersion>=9&&this.type===types.star))&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var this$1=this;var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this$1.expect(types.comma);if(this$1.afterTrailingComma(types.braceR)){break}}else{first=false;}
var prop=this$1.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this$1.checkPropClash(prop,propHash,refDestructuringErrors);}
node.properties.push(prop);}
return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element");}
return this.finishNode(prop,"RestElement")}
if(this.type===types.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start;}
if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start;}}
prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start;}
return this.finishNode(prop,"SpreadElement")}
if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc;}
if(!isPattern)
{isGenerator=this.eat(types.star);}}
var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);this.parsePropertyName(prop,refDestructuringErrors);}else{isAsync=false;}
this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon)
{this.unexpected();}
if(this.eat(types.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init";}else if(this.options.ecmaVersion>=6&&this.type===types.parenL){if(isPattern){this.unexpected();}
prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync);}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types.comma&&this.type!==types.braceR)){if(isGenerator||isAsync){this.unexpected();}
prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get")
{this.raiseRecoverable(start,"getter should have no params");}
else
{this.raiseRecoverable(start,"setter should have exactly one param");}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement")
{this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params");}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){this.checkUnreserved(prop.key);prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key);}else if(this.type===types.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0)
{refDestructuringErrors.shorthandAssign=this.start;}
prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key);}else{prop.value=prop.key;}
prop.shorthand=true;}else{this.unexpected();}};pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false;}}
return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(true)};pp$3.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false;}
if(this.options.ecmaVersion>=8){node.async=false;}};pp$3.parseMethod=function(isGenerator,isAsync){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos;this.initFunction(node);if(this.options.ecmaVersion>=6)
{node.generator=isGenerator;}
if(this.options.ecmaVersion>=8)
{node.async=!!isAsync;}
this.yieldPos=0;this.awaitPos=0;this.enterScope(functionFlags(isAsync,node.generator));this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync;}
this.yieldPos=0;this.awaitPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();node.expression=true;this.checkParams(node,false);}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple)
{this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list");}}
var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true;}
this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&this.isSimpleParamList(node.params));node.body=this.parseBlock(false);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels;}
this.exitScope();if(this.strict&&node.id){this.checkLVal(node.id,BIND_OUTSIDE);}
this.strict=oldStrict;};pp$3.isSimpleParamList=function(params){for(var i=0,list=params;i<list.length;i+=1)
{var param=list[i];if(param.type!=="Identifier"){return false}}
return true};pp$3.checkParams=function(node,allowDuplicates){var this$1=this;var nameHash={};for(var i=0,list=node.params;i<list.length;i+=1)
{var param=list[i];this$1.checkLVal(param,BIND_VAR,allowDuplicates?null:nameHash);}};pp$3.parseExprList=function(close,allowTrailingComma,allowEmpty,refDestructuringErrors){var this$1=this;var elts=[],first=true;while(!this.eat(close)){if(!first){this$1.expect(types.comma);if(allowTrailingComma&&this$1.afterTrailingComma(close)){break}}else{first=false;}
var elt=(void 0);if(allowEmpty&&this$1.type===types.comma)
{elt=null;}
else if(this$1.type===types.ellipsis){elt=this$1.parseSpread(refDestructuringErrors);if(refDestructuringErrors&&this$1.type===types.comma&&refDestructuringErrors.trailingComma<0)
{refDestructuringErrors.trailingComma=this$1.start;}}else{elt=this$1.parseMaybeAssign(false,refDestructuringErrors);}
elts.push(elt);}
return elts};pp$3.checkUnreserved=function(ref){var start=ref.start;var end=ref.end;var name=ref.name;if(this.inGenerator&&name==="yield")
{this.raiseRecoverable(start,"Can not use 'yield' as identifier inside a generator");}
if(this.inAsync&&name==="await")
{this.raiseRecoverable(start,"Can not use 'await' as identifier inside an async function");}
if(this.keywords.test(name))
{this.raise(start,("Unexpected keyword '"+name+"'"));}
if(this.options.ecmaVersion<6&&this.input.slice(start,end).indexOf("\\")!==-1){return}
var re=this.strict?this.reservedWordsStrict:this.reservedWords;if(re.test(name)){if(!this.inAsync&&name==="await")
{this.raiseRecoverable(start,"Can not use keyword 'await' outside an async function");}
this.raiseRecoverable(start,("The keyword '"+name+"' is reserved"));}};pp$3.parseIdent=function(liberal,isBinding){var node=this.startNode();if(liberal&&this.options.allowReserved==="never"){liberal=false;}
if(this.type===types.name){node.name=this.value;}else if(this.type.keyword){node.name=this.type.keyword;if((node.name==="class"||node.name==="function")&&(this.lastTokEnd!==this.lastTokStart+1||this.input.charCodeAt(this.lastTokStart)!==46)){this.context.pop();}}else{this.unexpected();}
this.next();this.finishNode(node,"Identifier");if(!liberal){this.checkUnreserved(node);}
return node};pp$3.parseYield=function(){if(!this.yieldPos){this.yieldPos=this.start;}
var node=this.startNode();this.next();if(this.type===types.semi||this.canInsertSemicolon()||(this.type!==types.star&&!this.type.startsExpr)){node.delegate=false;node.argument=null;}else{node.delegate=this.eat(types.star);node.argument=this.parseMaybeAssign();}
return this.finishNode(node,"YieldExpression")};pp$3.parseAwait=function(){if(!this.awaitPos){this.awaitPos=this.start;}
var node=this.startNode();this.next();node.argument=this.parseMaybeUnary(null,true);return this.finishNode(node,"AwaitExpression")};var pp$4=Parser.prototype;pp$4.raise=function(pos,message){var loc=getLineInfo(this.input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=this.pos;throw err};pp$4.raiseRecoverable=pp$4.raise;pp$4.curPosition=function(){if(this.options.locations){return new Position(this.curLine,this.pos-this.lineStart)}};var pp$5=Parser.prototype;var Scope=function Scope(flags){this.flags=flags;this.var=[];this.lexical=[];};pp$5.enterScope=function(flags){this.scopeStack.push(new Scope(flags));};pp$5.exitScope=function(){this.scopeStack.pop();};pp$5.declareName=function(name,bindingType,pos){var this$1=this;var redeclared=false;if(bindingType===BIND_LEXICAL){var scope=this.currentScope();redeclared=scope.lexical.indexOf(name)>-1||scope.var.indexOf(name)>-1;scope.lexical.push(name);}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name);}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();redeclared=scope$2.lexical.indexOf(name)>-1;scope$2.var.push(name);}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this$1.scopeStack[i];if(scope$3.lexical.indexOf(name)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH)&&scope$3.lexical[0]===name){redeclared=true;}
scope$3.var.push(name);if(scope$3.flags&SCOPE_VAR){break}}}
if(redeclared){this.raiseRecoverable(pos,("Identifier '"+name+"' has already been declared"));}};pp$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){var this$1=this;for(var i=this.scopeStack.length-1;;i--){var scope=this$1.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.inNonArrowFunction=function(){var this$1=this;for(var i=this.scopeStack.length-1;i>=0;i--)
{if(this$1.scopeStack[i].flags&SCOPE_FUNCTION&&!(this$1.scopeStack[i].flags&SCOPE_ARROW)){return true}}
return false};var Node=function Node(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations)
{this.loc=new SourceLocation(parser,loc);}
if(parser.options.directSourceFile)
{this.sourceFile=parser.options.directSourceFile;}
if(parser.options.ranges)
{this.range=[pos,0];}};var pp$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations)
{node.loc.end=loc;}
if(this.options.ranges)
{node.range[1]=pos;}
return node}
pp$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};var TokContext=function TokContext(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator;};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.tryReadTemplateToken();}),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent=this.curContext();if(parent===types$1.f_expr||parent===types$1.f_stat)
{return true}
if(prevType===types.colon&&(parent===types$1.b_stat||parent===types$1.b_expr))
{return!parent.isExpr}
if(prevType===types._return||prevType===types.name&&this.exprAllowed)
{return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}
if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow)
{return true}
if(prevType===types.braceL)
{return parent===types$1.b_stat}
if(prevType===types._var||prevType===types.name)
{return false}
return!this.exprAllowed};pp$7.inGeneratorContext=function(){var this$1=this;for(var i=this.context.length-1;i>=1;i--){var context=this$1.context[i];if(context.token==="function")
{return context.generator}}
return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot)
{this.exprAllowed=false;}
else if(update=type.updateContext)
{update.call(this,prevType);}
else
{this.exprAllowed=type.beforeExpr;}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}
var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop();}
this.exprAllowed=!out.isExpr;};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true;};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true;};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true;};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types.semi&&prevType!==types._else&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat))
{this.context.push(types$1.f_expr);}
else
{this.context.push(types$1.f_stat);}
this.exprAllowed=false;};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl)
{this.context.pop();}
else
{this.context.push(types$1.q_tmpl);}
this.exprAllowed=false;};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr)
{this.context[index]=types$1.f_expr_gen;}
else
{this.context[index]=types$1.f_gen;}}
this.exprAllowed=true;};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext())
{allowed=true;}}
this.exprAllowed=allowed;};var data={"$LONE":["ASCII","ASCII_Hex_Digit","AHex","Alphabetic","Alpha","Any","Assigned","Bidi_Control","Bidi_C","Bidi_Mirrored","Bidi_M","Case_Ignorable","CI","Cased","Changes_When_Casefolded","CWCF","Changes_When_Casemapped","CWCM","Changes_When_Lowercased","CWL","Changes_When_NFKC_Casefolded","CWKCF","Changes_When_Titlecased","CWT","Changes_When_Uppercased","CWU","Dash","Default_Ignorable_Code_Point","DI","Deprecated","Dep","Diacritic","Dia","Emoji","Emoji_Component","Emoji_Modifier","Emoji_Modifier_Base","Emoji_Presentation","Extender","Ext","Grapheme_Base","Gr_Base","Grapheme_Extend","Gr_Ext","Hex_Digit","Hex","IDS_Binary_Operator","IDSB","IDS_Trinary_Operator","IDST","ID_Continue","IDC","ID_Start","IDS","Ideographic","Ideo","Join_Control","Join_C","Logical_Order_Exception","LOE","Lowercase","Lower","Math","Noncharacter_Code_Point","NChar","Pattern_Syntax","Pat_Syn","Pattern_White_Space","Pat_WS","Quotation_Mark","QMark","Radical","Regional_Indicator","RI","Sentence_Terminal","STerm","Soft_Dotted","SD","Terminal_Punctuation","Term","Unified_Ideograph","UIdeo","Uppercase","Upper","Variation_Selector","VS","White_Space","space","XID_Continue","XIDC","XID_Start","XIDS"],"General_Category":["Cased_Letter","LC","Close_Punctuation","Pe","Connector_Punctuation","Pc","Control","Cc","cntrl","Currency_Symbol","Sc","Dash_Punctuation","Pd","Decimal_Number","Nd","digit","Enclosing_Mark","Me","Final_Punctuation","Pf","Format","Cf","Initial_Punctuation","Pi","Letter","L","Letter_Number","Nl","Line_Separator","Zl","Lowercase_Letter","Ll","Mark","M","Combining_Mark","Math_Symbol","Sm","Modifier_Letter","Lm","Modifier_Symbol","Sk","Nonspacing_Mark","Mn","Number","N","Open_Punctuation","Ps","Other","C","Other_Letter","Lo","Other_Number","No","Other_Punctuation","Po","Other_Symbol","So","Paragraph_Separator","Zp","Private_Use","Co","Punctuation","P","punct","Separator","Z","Space_Separator","Zs","Spacing_Mark","Mc","Surrogate","Cs","Symbol","S","Titlecase_Letter","Lt","Unassigned","Cn","Uppercase_Letter","Lu"],"Script":["Adlam","Adlm","Ahom","Anatolian_Hieroglyphs","Hluw","Arabic","Arab","Armenian","Armn","Avestan","Avst","Balinese","Bali","Bamum","Bamu","Bassa_Vah","Bass","Batak","Batk","Bengali","Beng","Bhaiksuki","Bhks","Bopomofo","Bopo","Brahmi","Brah","Braille","Brai","Buginese","Bugi","Buhid","Buhd","Canadian_Aboriginal","Cans","Carian","Cari","Caucasian_Albanian","Aghb","Chakma","Cakm","Cham","Cherokee","Cher","Common","Zyyy","Coptic","Copt","Qaac","Cuneiform","Xsux","Cypriot","Cprt","Cyrillic","Cyrl","Deseret","Dsrt","Devanagari","Deva","Duployan","Dupl","Egyptian_Hieroglyphs","Egyp","Elbasan","Elba","Ethiopic","Ethi","Georgian","Geor","Glagolitic","Glag","Gothic","Goth","Grantha","Gran","Greek","Grek","Gujarati","Gujr","Gurmukhi","Guru","Han","Hani","Hangul","Hang","Hanunoo","Hano","Hatran","Hatr","Hebrew","Hebr","Hiragana","Hira","Imperial_Aramaic","Armi","Inherited","Zinh","Qaai","Inscriptional_Pahlavi","Phli","Inscriptional_Parthian","Prti","Javanese","Java","Kaithi","Kthi","Kannada","Knda","Katakana","Kana","Kayah_Li","Kali","Kharoshthi","Khar","Khmer","Khmr","Khojki","Khoj","Khudawadi","Sind","Lao","Laoo","Latin","Latn","Lepcha","Lepc","Limbu","Limb","Linear_A","Lina","Linear_B","Linb","Lisu","Lycian","Lyci","Lydian","Lydi","Mahajani","Mahj","Malayalam","Mlym","Mandaic","Mand","Manichaean","Mani","Marchen","Marc","Masaram_Gondi","Gonm","Meetei_Mayek","Mtei","Mende_Kikakui","Mend","Meroitic_Cursive","Merc","Meroitic_Hieroglyphs","Mero","Miao","Plrd","Modi","Mongolian","Mong","Mro","Mroo","Multani","Mult","Myanmar","Mymr","Nabataean","Nbat","New_Tai_Lue","Talu","Newa","Nko","Nkoo","Nushu","Nshu","Ogham","Ogam","Ol_Chiki","Olck","Old_Hungarian","Hung","Old_Italic","Ital","Old_North_Arabian","Narb","Old_Permic","Perm","Old_Persian","Xpeo","Old_South_Arabian","Sarb","Old_Turkic","Orkh","Oriya","Orya","Osage","Osge","Osmanya","Osma","Pahawh_Hmong","Hmng","Palmyrene","Palm","Pau_Cin_Hau","Pauc","Phags_Pa","Phag","Phoenician","Phnx","Psalter_Pahlavi","Phlp","Rejang","Rjng","Runic","Runr","Samaritan","
var c=s.charCodeAt(i);if(!this.switchU||c<=0xD7FF||c>=0xE000||i+1>=l){return c}
return(c<<10)+s.charCodeAt(i+1)-0x35FDC00};RegExpValidationState.prototype.nextIndex=function nextIndex(i){var s=this.source;var l=s.length;if(i>=l){return l}
var c=s.charCodeAt(i);if(!this.switchU||c<=0xD7FF||c>=0xE000||i+1>=l){return i+1}
return i+2};RegExpValidationState.prototype.current=function current(){return this.at(this.pos)};RegExpValidationState.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};RegExpValidationState.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos);};RegExpValidationState.prototype.eat=function eat(ch){if(this.current()===ch){this.advance();return true}
return false};function codePointToString$1(ch){if(ch<=0xFFFF){return String.fromCharCode(ch)}
ch-=0x10000;return String.fromCharCode((ch>>10)+0xD800,(ch&0x03FF)+0xDC00)}
pp$9.validateRegExpFlags=function(state){var this$1=this;var validFlags=state.validFlags;var flags=state.flags;for(var i=0;i<flags.length;i++){var flag=flags.charAt(i);if(validFlags.indexOf(flag)===-1){this$1.raise(state.start,"Invalid regular expression flag");}
if(flags.indexOf(flag,i+1)>-1){this$1.raise(state.start,"Duplicate regular expression flag");}}};pp$9.validateRegExpPattern=function(state){this.regexp_pattern(state);if(!state.switchN&&this.options.ecmaVersion>=9&&state.groupNames.length>0){state.switchN=true;this.regexp_pattern(state);}};pp$9.regexp_pattern=function(state){state.pos=0;state.lastIntValue=0;state.lastStringValue="";state.lastAssertionIsQuantifiable=false;state.numCapturingParens=0;state.maxBackReference=0;state.groupNames.length=0;state.backReferenceNames.length=0;this.regexp_disjunction(state);if(state.pos!==state.source.length){if(state.eat(0x29)){state.raise("Unmatched ')'");}
if(state.eat(0x5D)||state.eat(0x7D)){state.raise("Lone quantifier brackets");}}
if(state.maxBackReference>state.numCapturingParens){state.raise("Invalid escape");}
for(var i=0,list=state.backReferenceNames;i<list.length;i+=1){var name=list[i];if(state.groupNames.indexOf(name)===-1){state.raise("Invalid named capture referenced");}}};pp$9.regexp_disjunction=function(state){var this$1=this;this.regexp_alternative(state);while(state.eat(0x7C)){this$1.regexp_alternative(state);}
if(this.regexp_eatQuantifier(state,true)){state.raise("Nothing to repeat");}
if(state.eat(0x7B)){state.raise("Lone quantifier brackets");}};pp$9.regexp_alternative=function(state){while(state.pos<state.source.length&&this.regexp_eatTerm(state))
{}};pp$9.regexp_eatTerm=function(state){if(this.regexp_eatAssertion(state)){if(state.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(state)){if(state.switchU){state.raise("Invalid quantifier");}}
return true}
if(state.switchU?this.regexp_eatAtom(state):this.regexp_eatExtendedAtom(state)){this.regexp_eatQuantifier(state);return true}
return false};pp$9.regexp_eatAssertion=function(state){var start=state.pos;state.lastAssertionIsQuantifiable=false;if(state.eat(0x5E)||state.eat(0x24)){return true}
if(state.eat(0x5C)){if(state.eat(0x42)||state.eat(0x62)){return true}
state.pos=start;}
if(state.eat(0x28)&&state.eat(0x3F)){var lookbehind=false;if(this.options.ecmaVersion>=9){lookbehind=state.eat(0x3C);}
if(state.eat(0x3D)||state.eat(0x21)){this.regexp_disjunction(state);if(!state.eat(0x29)){state.raise("Unterminated group");}
state.lastAssertionIsQuantifiable=!lookbehind;return true}}
state.pos=start;return false};pp$9.regexp_eatQuantifier=function(state,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state,noError)){state.eat(0x3F);return true}
return false};pp$9.regexp_eatQuantifierPrefix=function(state,noError){return(state.eat(0x2A)||state.eat(0x2B)||state.eat(0x3F)||this.regexp_eatBracedQuantifier(state,noError))};pp$9.regexp_eatBracedQuantifier=function(state,noError){var start=state.pos;if(state.eat(0x7B)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state)){min=state.lastIntValue;if(state.eat(0x2C)&&this.regexp_eatDecimalDigits(state)){max=state.lastIntValue;}
if(state.eat(0x7D)){if(max!==-1&&max<min&&!noError){state.raise("numbers out of order in {} quantifier");}
return true}}
if(state.switchU&&!noError){state.raise("Incomplete quantifier");}
state.pos=start;}
return false};pp$9.regexp_eatAtom=function(state){return(this.regexp_eatPatternCharacters(state)||state.eat(0x2E)||this.regexp_eatReverseSolidusAtomEscape(state)||this.regexp_eatCharacterClass(state)||this.regexp_eatUncapturingGroup(state)||this.regexp_eatCapturingGroup(state))};pp$9.regexp_eatReverseSolidusAtomEscape=function(state){var start=state.pos;if(state.eat(0x5C)){if(this.regexp_eatAtomEscape(state)){return true}
state.pos=start;}
return false};pp$9.regexp_eatUncapturingGroup=function(state){var start=state.pos;if(state.eat(0x28)){if(state.eat(0x3F)&&state.eat(0x3A)){this.regexp_disjunction(state);if(state.eat(0x29)){return true}
state.raise("Unterminated group");}
state.pos=start;}
return false};pp$9.regexp_eatCapturingGroup=function(state){if(state.eat(0x28)){if(this.options.ecmaVersion>=9){this.regexp_groupSpecifier(state);}else if(state.current()===0x3F){state.raise("Invalid group");}
this.regexp_disjunction(state);if(state.eat(0x29)){state.numCapturingParens+=1;return true}
state.raise("Unterminated group");}
return false};pp$9.regexp_eatExtendedAtom=function(state){return(state.eat(0x2E)||this.regexp_eatReverseSolidusAtomEscape(state)||this.regexp_eatCharacterClass(state)||this.regexp_eatUncapturingGroup(state)||this.regexp_eatCapturingGroup(state)||this.regexp_eatInvalidBracedQuantifier(state)||this.regexp_eatExtendedPatternCharacter(state))};pp$9.regexp_eatInvalidBracedQuantifier=function(state){if(this.regexp_eatBracedQuantifier(state,true)){state.raise("Nothing to repeat");}
return false};pp$9.regexp_eatSyntaxCharacter=function(state){var ch=state.current();if(isSyntaxCharacter(ch)){state.lastIntValue=ch;state.advance();return true}
return false};function isSyntaxCharacter(ch){return(ch===0x24||ch>=0x28&&ch<=0x2B||ch===0x2E||ch===0x3F||ch>=0x5B&&ch<=0x5E||ch>=0x7B&&ch<=0x7D)}
pp$9.regexp_eatPatternCharacters=function(state){var start=state.pos;var ch=0;while((ch=state.current())!==-1&&!isSyntaxCharacter(ch)){state.advance();}
return state.pos!==start};pp$9.regexp_eatExtendedPatternCharacter=function(state){var ch=state.current();if(ch!==-1&&ch!==0x24&&!(ch>=0x28&&ch<=0x2B)&&ch!==0x2E&&ch!==0x3F&&ch!==0x5B&&ch!==0x5E&&ch!==0x7C){state.advance();return true}
return false};pp$9.regexp_groupSpecifier=function(state){if(state.eat(0x3F)){if(this.regexp_eatGroupName(state)){if(state.groupNames.indexOf(state.lastStringValue)!==-1){state.raise("Duplicate capture group name");}
state.groupNames.push(state.lastStringValue);return}
state.raise("Invalid group");}};pp$9.regexp_eatGroupName=function(state){state.lastStringValue="";if(state.eat(0x3C)){if(this.regexp_eatRegExpIdentifierName(state)&&state.eat(0x3E)){return true}
state.raise("Invalid capture group name");}
return false};pp$9.regexp_eatRegExpIdentifierName=function(state){state.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state)){state.lastStringValue+=codePointToString$1(state.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state)){state.lastStringValue+=codePointToString$1(state.lastIntValue);}
return true}
return false};pp$9.regexp_eatRegExpIdentifierStart=function(state){var start=state.pos;var ch=state.current();state.advance();if(ch===0x5C&&this.regexp_eatRegExpUnicodeEscapeSequence(state)){ch=state.lastIntValue;}
if(isRegExpIdentifierStart(ch)){state.lastIntValue=ch;return true}
state.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===0x24||ch===0x5F}
pp$9.regexp_eatRegExpIdentifierPart=function(state){var start=state.pos;var ch=state.current();state.advance();if(ch===0x5C&&this.regexp_eatRegExpUnicodeEscapeSequence(state)){ch=state.lastIntValue;}
if(isRegExpIdentifierPart(ch)){state.lastIntValue=ch;return true}
state.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===0x24||ch===0x5F||ch===0x200C||ch===0x200D}
pp$9.regexp_eatAtomEscape=function(state){if(this.regexp_eatBackReference(state)||this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state)||(state.switchN&&this.regexp_eatKGroupName(state))){return true}
if(state.switchU){if(state.current()===0x63){state.raise("Invalid unicode escape");}
state.raise("Invalid escape");}
return false};pp$9.regexp_eatBackReference=function(state){var start=state.pos;if(this.regexp_eatDecimalEscape(state)){var n=state.lastIntValue;if(state.switchU){if(n>state.maxBackReference){state.maxBackReference=n;}
return true}
if(n<=state.numCapturingParens){return true}
state.pos=start;}
return false};pp$9.regexp_eatKGroupName=function(state){if(state.eat(0x6B)){if(this.regexp_eatGroupName(state)){state.backReferenceNames.push(state.lastStringValue);return true}
state.raise("Invalid named reference");}
return false};pp$9.regexp_eatCharacterEscape=function(state){return(this.regexp_eatControlEscape(state)||this.regexp_eatCControlLetter(state)||this.regexp_eatZero(state)||this.regexp_eatHexEscapeSequence(state)||this.regexp_eatRegExpUnicodeEscapeSequence(state)||(!state.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state))||this.regexp_eatIdentityEscape(state))};pp$9.regexp_eatCControlLetter=function(state){var start=state.pos;if(state.eat(0x63)){if(this.regexp_eatControlLetter(state)){return true}
state.pos=start;}
return false};pp$9.regexp_eatZero=function(state){if(state.current()===0x30&&!isDecimalDigit(state.lookahead())){state.lastIntValue=0;state.advance();return true}
return false};pp$9.regexp_eatControlEscape=function(state){var ch=state.current();if(ch===0x74){state.lastIntValue=0x09;state.advance();return true}
if(ch===0x6E){state.lastIntValue=0x0A;state.advance();return true}
if(ch===0x76){state.lastIntValue=0x0B;state.advance();return true}
if(ch===0x66){state.lastIntValue=0x0C;state.advance();return true}
if(ch===0x72){state.lastIntValue=0x0D;state.advance();return true}
return false};pp$9.regexp_eatControlLetter=function(state){var ch=state.current();if(isControlLetter(ch)){state.lastIntValue=ch%0x20;state.advance();return true}
return false};function isControlLetter(ch){return((ch>=0x41&&ch<=0x5A)||(ch>=0x61&&ch<=0x7A))}
pp$9.regexp_eatRegExpUnicodeEscapeSequence=function(state){var start=state.pos;if(state.eat(0x75)){if(this.regexp_eatFixedHexDigits(state,4)){var lead=state.lastIntValue;if(state.switchU&&lead>=0xD800&&lead<=0xDBFF){var leadSurrogateEnd=state.pos;if(state.eat(0x5C)&&state.eat(0x75)&&this.regexp_eatFixedHexDigits(state,4)){var trail=state.lastIntValue;if(trail>=0xDC00&&trail<=0xDFFF){state.lastIntValue=(lead-0xD800)*0x400+(trail-0xDC00)+0x10000;return true}}
state.pos=leadSurrogateEnd;state.lastIntValue=lead;}
return true}
if(state.switchU&&state.eat(0x7B)&&this.regexp_eatHexDigits(state)&&state.eat(0x7D)&&isValidUnicode(state.lastIntValue)){return true}
if(state.switchU){state.raise("Invalid unicode escape");}
state.pos=start;}
return false};function isValidUnicode(ch){return ch>=0&&ch<=0x10FFFF}
pp$9.regexp_eatIdentityEscape=function(state){if(state.switchU){if(this.regexp_eatSyntaxCharacter(state)){return true}
if(state.eat(0x2F)){state.lastIntValue=0x2F;return true}
return false}
var ch=state.current();if(ch!==0x63&&(!state.switchN||ch!==0x6B)){state.lastIntValue=ch;state.advance();return true}
return false};pp$9.regexp_eatDecimalEscape=function(state){state.lastIntValue=0;var ch=state.current();if(ch>=0x31&&ch<=0x39){do{state.lastIntValue=10*state.lastIntValue+(ch-0x30);state.advance();}while((ch=state.current())>=0x30&&ch<=0x39)
return true}
return false};pp$9.regexp_eatCharacterClassEscape=function(state){var ch=state.current();if(isCharacterClassEscape(ch)){state.lastIntValue=-1;state.advance();return true}
if(state.switchU&&this.options.ecmaVersion>=9&&(ch===0x50||ch===0x70)){state.lastIntValue=-1;state.advance();if(state.eat(0x7B)&&this.regexp_eatUnicodePropertyValueExpression(state)&&state.eat(0x7D)){return true}
state.raise("Invalid property name");}
return false};function isCharacterClassEscape(ch){return(ch===0x64||ch===0x44||ch===0x73||ch===0x53||ch===0x77||ch===0x57)}
pp$9.regexp_eatUnicodePropertyValueExpression=function(state){var start=state.pos;if(this.regexp_eatUnicodePropertyName(state)&&state.eat(0x3D)){var name=state.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state)){var value=state.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state,name,value);return true}}
state.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state)){var nameOrValue=state.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state,nameOrValue);return true}
return false};pp$9.regexp_validateUnicodePropertyNameAndValue=function(state,name,value){if(!data.hasOwnProperty(name)||data[name].indexOf(value)===-1){state.raise("Invalid property name");}};pp$9.regexp_validateUnicodePropertyNameOrValue=function(state,nameOrValue){if(data.$LONE.indexOf(nameOrValue)===-1){state.raise("Invalid property name");}};pp$9.regexp_eatUnicodePropertyName=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state.current())){state.lastStringValue+=codePointToString$1(ch);state.advance();}
return state.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===0x5F}
pp$9.regexp_eatUnicodePropertyValue=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state.current())){state.lastStringValue+=codePointToString$1(ch);state.advance();}
return state.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}
pp$9.regexp_eatLoneUnicodePropertyNameOrValue=function(state){return this.regexp_eatUnicodePropertyValue(state)};pp$9.regexp_eatCharacterClass=function(state){if(state.eat(0x5B)){state.eat(0x5E);this.regexp_classRanges(state);if(state.eat(0x5D)){return true}
state.raise("Unterminated character class");}
return false};pp$9.regexp_classRanges=function(state){var this$1=this;while(this.regexp_eatClassAtom(state)){var left=state.lastIntValue;if(state.eat(0x2D)&&this$1.regexp_eatClassAtom(state)){var right=state.lastIntValue;if(state.switchU&&(left===-1||right===-1)){state.raise("Invalid character class");}
if(left!==-1&&right!==-1&&left>right){state.raise("Range out of order in character class");}}}};pp$9.regexp_eatClassAtom=function(state){var start=state.pos;if(state.eat(0x5C)){if(this.regexp_eatClassEscape(state)){return true}
if(state.switchU){var ch$1=state.current();if(ch$1===0x63||isOctalDigit(ch$1)){state.raise("Invalid class escape");}
state.raise("Invalid escape");}
state.pos=start;}
var ch=state.current();if(ch!==0x5D){state.lastIntValue=ch;state.advance();return true}
return false};pp$9.regexp_eatClassEscape=function(state){var start=state.pos;if(state.eat(0x62)){state.lastIntValue=0x08;return true}
if(state.switchU&&state.eat(0x2D)){state.lastIntValue=0x2D;return true}
if(!state.switchU&&state.eat(0x63)){if(this.regexp_eatClassControlLetter(state)){return true}
state.pos=start;}
return(this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state))};pp$9.regexp_eatClassControlLetter=function(state){var ch=state.current();if(isDecimalDigit(ch)||ch===0x5F){state.lastIntValue=ch%0x20;state.advance();return true}
return false};pp$9.regexp_eatHexEscapeSequence=function(state){var start=state.pos;if(state.eat(0x78)){if(this.regexp_eatFixedHexDigits(state,2)){return true}
if(state.switchU){state.raise("Invalid escape");}
state.pos=start;}
return false};pp$9.regexp_eatDecimalDigits=function(state){var start=state.pos;var ch=0;state.lastIntValue=0;while(isDecimalDigit(ch=state.current())){state.lastIntValue=10*state.lastIntValue+(ch-0x30);state.advance();}
return state.pos!==start};function isDecimalDigit(ch){return ch>=0x30&&ch<=0x39}
pp$9.regexp_eatHexDigits=function(state){var start=state.pos;var ch=0;state.lastIntValue=0;while(isHexDigit(ch=state.current())){state.lastIntValue=16*state.lastIntValue+hexToInt(ch);state.advance();}
return state.pos!==start};function isHexDigit(ch){return((ch>=0x30&&ch<=0x39)||(ch>=0x41&&ch<=0x46)||(ch>=0x61&&ch<=0x66))}
function hexToInt(ch){if(ch>=0x41&&ch<=0x46){return 10+(ch-0x41)}
if(ch>=0x61&&ch<=0x66){return 10+(ch-0x61)}
return ch-0x30}
pp$9.regexp_eatLegacyOctalEscapeSequence=function(state){if(this.regexp_eatOctalDigit(state)){var n1=state.lastIntValue;if(this.regexp_eatOctalDigit(state)){var n2=state.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state)){state.lastIntValue=n1*64+n2*8+state.lastIntValue;}else{state.lastIntValue=n1*8+n2;}}else{state.lastIntValue=n1;}
return true}
return false};pp$9.regexp_eatOctalDigit=function(state){var ch=state.current();if(isOctalDigit(ch)){state.lastIntValue=ch-0x30;state.advance();return true}
state.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=0x30&&ch<=0x37}
pp$9.regexp_eatFixedHexDigits=function(state,length){var start=state.pos;state.lastIntValue=0;for(var i=0;i<length;++i){var ch=state.current();if(!isHexDigit(ch)){state.pos=start;return false}
state.lastIntValue=16*state.lastIntValue+hexToInt(ch);state.advance();}
return true};var Token=function Token(p){this.type=p.type;this.value=p.value;this.start=p.start;this.end=p.end;if(p.options.locations)
{this.loc=new SourceLocation(p,p.startLoc,p.endLoc);}
if(p.options.ranges)
{this.range=[p.start,p.end];}};var pp$8=Parser.prototype;pp$8.next=function(){if(this.options.onToken)
{this.options.onToken(new Token(this));}
this.lastTokEnd=this.end;this.lastTokStart=this.start;this.lastTokEndLoc=this.endLoc;this.lastTokStartLoc=this.startLoc;this.nextToken();};pp$8.getToken=function(){this.next();return new Token(this)};if(typeof Symbol!=="undefined")
{pp$8[Symbol.iterator]=function(){var this$1=this;return{next:function(){var token=this$1.getToken();return{done:token.type===types.eof,value:token}}}};}
pp$8.curContext=function(){return this.context[this.context.length-1]};pp$8.nextToken=function(){var curContext=this.curContext();if(!curContext||!curContext.preserveSpace){this.skipSpace();}
this.start=this.pos;if(this.options.locations){this.startLoc=this.curPosition();}
if(this.pos>=this.input.length){return this.finishToken(types.eof)}
if(curContext.override){return curContext.override(this)}
else{this.readToken(this.fullCharCodeAtPos());}};pp$8.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92)
{return this.readWord()}
return this.getTokenFromCode(code)};pp$8.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=0xd7ff||code>=0xe000){return code}
var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-0x35fdc00};pp$8.skipBlockComment=function(){var this$1=this;var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment");}
this.pos=end+2;if(this.options.locations){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index<this.pos){++this$1.curLine;this$1.lineStart=match.index+match[0].length;}}
if(this.options.onComment)
{this.options.onComment(true,this.input.slice(start+2,end),start,this.pos,startLoc,this.curPosition());}};pp$8.skipLineComment=function(startSkip){var this$1=this;var start=this.pos;var startLoc=this.options.onComment&&this.curPosition();var ch=this.input.charCodeAt(this.pos+=startSkip);while(this.pos<this.input.length&&!isNewLine(ch)){ch=this$1.input.charCodeAt(++this$1.pos);}
if(this.options.onComment)
{this.options.onComment(false,this.input.slice(start+startSkip,this.pos),start,this.pos,startLoc,this.curPosition());}};pp$8.skipSpace=function(){var this$1=this;loop:while(this.pos<this.input.length){var ch=this$1.input.charCodeAt(this$1.pos);switch(ch){case 32:case 160:++this$1.pos;break
case 13:if(this$1.input.charCodeAt(this$1.pos+1)===10){++this$1.pos;}
case 10:case 8232:case 8233:++this$1.pos;if(this$1.options.locations){++this$1.curLine;this$1.lineStart=this$1.pos;}
break
case 47:switch(this$1.input.charCodeAt(this$1.pos+1)){case 42:this$1.skipBlockComment();break
case 47:this$1.skipLineComment(2);break
default:break loop}
break
default:if(ch>8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this$1.pos;}else{break loop}}}};pp$8.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition();}
var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType);};pp$8.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}
var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$8.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}
if(next===61){return this.finishOp(types.assign,2)}
return this.finishOp(types.slash,1)};pp$8.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2);}
if(next===61){return this.finishOp(types.assign,size+1)}
return this.finishOp(tokentype,size)};pp$8.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}
if(next===61){return this.finishOp(types.assign,2)}
return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$8.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}
return this.finishOp(types.bitwiseXOR,1)};pp$8.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}
return this.finishOp(types.incDec,2)}
if(next===61){return this.finishOp(types.assign,2)}
return this.finishOp(types.plusMin,1)};pp$8.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types.assign,size+1)}
return this.finishOp(types.bitShift,size)}
if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}
if(next===61){size=2;}
return this.finishOp(types.relational,size)};pp$8.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}
if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types.arrow)}
return this.finishOp(code===61?types.eq:types.prefix,1)};pp$8.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot()
case 40:++this.pos;return this.finishToken(types.parenL)
case 41:++this.pos;return this.finishToken(types.parenR)
case 59:++this.pos;return this.finishToken(types.semi)
case 44:++this.pos;return this.finishToken(types.comma)
case 91:++this.pos;return this.finishToken(types.bracketL)
case 93:++this.pos;return this.finishToken(types.bracketR)
case 123:++this.pos;return this.finishToken(types.braceL)
case 125:++this.pos;return this.finishToken(types.braceR)
case 58:++this.pos;return this.finishToken(types.colon)
case 63:++this.pos;return this.finishToken(types.question)
case 96:if(this.options.ecmaVersion<6){break}
++this.pos;return this.finishToken(types.backQuote)
case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}
if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}
if(next===98||next===66){return this.readRadixNumber(2)}}
case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false)
case 34:case 39:return this.readString(code)
case 47:return this.readToken_slash()
case 37:case 42:return this.readToken_mult_modulo_exp(code)
case 124:case 38:return this.readToken_pipe_amp(code)
case 94:return this.readToken_caret()
case 43:case 45:return this.readToken_plus_min(code)
case 60:case 62:return this.readToken_lt_gt(code)
case 61:case 33:return this.readToken_eq_excl(code)
case 126:return this.finishOp(types.prefix,1)}
this.raise(this.pos,"Unexpected character '"+codePointToString(code)+"'");};pp$8.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$8.readRegexp=function(){var this$1=this;var escaped,inClass,start=this.pos;for(;;){if(this$1.pos>=this$1.input.length){this$1.raise(start,"Unterminated regular expression");}
var ch=this$1.input.charAt(this$1.pos);if(lineBreak.test(ch)){this$1.raise(start,"Unterminated regular expression");}
if(!escaped){if(ch==="["){inClass=true;}
else if(ch==="]"&&inClass){inClass=false;}
else if(ch==="/"&&!inClass){break}
escaped=ch==="\\";}else{escaped=false;}
++this$1.pos;}
var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart);}
var state=this.regexpState||(this.regexpState=new RegExpValidationState(this));state.reset(start,pattern,flags);this.validateRegExpFlags(state);this.validateRegExpPattern(state);var value=null;try{value=new RegExp(pattern,flags);}catch(e){}
return this.finishToken(types.regexp,{pattern:pattern,flags:flags,value:value})};pp$8.readInt=function(radix,len){var this$1=this;var start=this.pos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=this$1.input.charCodeAt(this$1.pos),val=(void 0);if(code>=97){val=code-97+10;}
else if(code>=65){val=code-65+10;}
else if(code>=48&&code<=57){val=code-48;}
else{val=Infinity;}
if(val>=radix){break}
++this$1.pos;total=total*radix+val;}
if(this.pos===start||len!=null&&this.pos-start!==len){return null}
return total};pp$8.readRadixNumber=function(radix){this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix);}
if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number");}
return this.finishToken(types.num,val)};pp$8.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10)===null){this.raise(start,"Invalid number");}
var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number");}
if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false;}
var next=this.input.charCodeAt(this.pos);if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos);}
if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos;}
if(this.readInt(10)===null){this.raise(start,"Invalid number");}}
if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number");}
var str=this.input.slice(start,this.pos);var val=octal?parseInt(str,8):parseFloat(str);return this.finishToken(types.num,val)};pp$8.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected();}
var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>0x10FFFF){this.invalidStringToken(codePos,"Code point out of bounds");}}else{code=this.readHexChar(4);}
return code};function codePointToString(code){if(code<=0xFFFF){return String.fromCharCode(code)}
code-=0x10000;return String.fromCharCode((code>>10)+0xD800,(code&1023)+0xDC00)}
pp$8.readString=function(quote){var this$1=this;var out="",chunkStart=++this.pos;for(;;){if(this$1.pos>=this$1.input.length){this$1.raise(this$1.start,"Unterminated string constant");}
var ch=this$1.input.charCodeAt(this$1.pos);if(ch===quote){break}
if(ch===92){out+=this$1.input.slice(chunkStart,this$1.pos);out+=this$1.readEscapedChar(false);chunkStart=this$1.pos;}else{if(isNewLine(ch,this$1.options.ecmaVersion>=10)){this$1.raise(this$1.start,"Unterminated string constant");}
++this$1.pos;}}
out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$8.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken();}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken();}else{throw err}}
this.inTemplateElement=false;};pp$8.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message);}};pp$8.readTmplToken=function(){var this$1=this;var out="",chunkStart=this.pos;for(;;){if(this$1.pos>=this$1.input.length){this$1.raise(this$1.start,"Unterminated template");}
var ch=this$1.input.charCodeAt(this$1.pos);if(ch===96||ch===36&&this$1.input.charCodeAt(this$1.pos+1)===123){if(this$1.pos===this$1.start&&(this$1.type===types.template||this$1.type===types.invalidTemplate)){if(ch===36){this$1.pos+=2;return this$1.finishToken(types.dollarBraceL)}else{++this$1.pos;return this$1.finishToken(types.backQuote)}}
out+=this$1.input.slice(chunkStart,this$1.pos);return this$1.finishToken(types.template,out)}
if(ch===92){out+=this$1.input.slice(chunkStart,this$1.pos);out+=this$1.readEscapedChar(true);chunkStart=this$1.pos;}else if(isNewLine(ch)){out+=this$1.input.slice(chunkStart,this$1.pos);++this$1.pos;switch(ch){case 13:if(this$1.input.charCodeAt(this$1.pos)===10){++this$1.pos;}
case 10:out+="\n";break
default:out+=String.fromCharCode(ch);break}
if(this$1.options.locations){++this$1.curLine;this$1.lineStart=this$1.pos;}
chunkStart=this$1.pos;}else{++this$1.pos;}}};pp$8.readInvalidTemplateToken=function(){var this$1=this;for(;this.pos<this.input.length;this.pos++){switch(this$1.input[this$1.pos]){case"\\":++this$1.pos;break
case"$":if(this$1.input[this$1.pos+1]!=="{"){break}
case"`":return this$1.finishToken(types.invalidTemplate,this$1.input.slice(this$1.start,this$1.pos))}}
this.raise(this.start,"Unterminated template");};pp$8.readEscapedChar=function(inTemplate){var ch=this.input.charCodeAt(++this.pos);++this.pos;switch(ch){case 110:return"\n"
case 114:return"\r"
case 120:return String.fromCharCode(this.readHexChar(2))
case 117:return codePointToString(this.readCodePoint())
case 116:return"\t"
case 98:return"\b"
case 118:return"\u000b"
case 102:return"\f"
case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos;}
case 10:if(this.options.locations){this.lineStart=this.pos;++this.curLine;}
return""
default:if(ch>=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8);}
this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode");}
return String.fromCharCode(octal)}
return String.fromCharCode(ch)}};pp$8.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence");}
return n};pp$8.readWord1=function(){var this$1=this;this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos<this.input.length){var ch=this$1.fullCharCodeAtPos();if(isIdentifierChar(ch,astral)){this$1.pos+=ch<=0xffff?1:2;}else if(ch===92){this$1.containsEsc=true;word+=this$1.input.slice(chunkStart,this$1.pos);var escStart=this$1.pos;if(this$1.input.charCodeAt(++this$1.pos)!==117)
{this$1.invalidStringToken(this$1.pos,"Expecting Unicode escape sequence \\uXXXX");}
++this$1.pos;var esc=this$1.readCodePoint();if(!(first?isIdentifierStart:isIdentifierChar)(esc,astral))
{this$1.invalidStringToken(escStart,"Invalid Unicode escape");}
word+=codePointToString(esc);chunkStart=this$1.pos;}else{break}
first=false;}
return word+this.input.slice(chunkStart,this.pos)};pp$8.readWord=function(){var word=this.readWord1();var type=types.name;if(this.keywords.test(word)){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword "+word);}
type=keywords$1[word];}
return this.finishToken(type,word)};var version="6.0.1";function parse(input,options){return Parser.parse(input,options)}
function parseExpressionAt(input,pos,options){return Parser.parseExpressionAt(input,pos,options)}
function tokenizer(input,options){return Parser.tokenizer(input,options)}
exports.version=version;exports.parse=parse;exports.parseExpressionAt=parseExpressionAt;exports.tokenizer=tokenizer;exports.Parser=Parser;exports.defaultOptions=defaultOptions;exports.Position=Position;exports.SourceLocation=SourceLocation;exports.getLineInfo=getLineInfo;exports.Node=Node;exports.TokenType=TokenType;exports.tokTypes=types;exports.keywordTypes=keywords$1;exports.TokContext=TokContext;exports.tokContexts=types$1;exports.isIdentifierChar=isIdentifierChar;exports.isIdentifierStart=isIdentifierStart;exports.Token=Token;exports.isNewLine=isNewLine;exports.lineBreak=lineBreak;exports.lineBreakG=lineBreakG;exports.nonASCIIwhitespace=nonASCIIwhitespace;Object.defineProperty(exports,'__esModule',{value:true});})));;(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?factory(exports,require('acorn')):typeof define==='function'&&define.amd?define(['exports','acorn'],factory):(factory((global.acorn=global.acorn||{},global.acorn.loose={}),global.acorn));}(this,(function(exports,acorn){'use strict';function noop(){}
var LooseParser=function LooseParser(input,options){if(options===void 0)options={};this.toks=this.constructor.BaseParser.tokenizer(input,options);this.options=this.toks.options;this.input=this.toks.input;this.tok=this.last={type:acorn.tokTypes.eof,start:0,end:0};this.tok.validateRegExpFlags=noop;this.tok.validateRegExpPattern=noop;if(this.options.locations){var here=this.toks.curPosition();this.tok.loc=new acorn.SourceLocation(this.toks,here,here);}
this.ahead=[];this.context=[];this.curIndent=0;this.curLineStart=0;this.nextLineStart=this.lineEnd(this.curLineStart)+1;this.inAsync=false;this.inFunction=false;};LooseParser.prototype.startNode=function startNode(){return new acorn.Node(this.toks,this.tok.start,this.options.locations?this.tok.loc.start:null)};LooseParser.prototype.storeCurrentPos=function storeCurrentPos(){return this.options.locations?[this.tok.start,this.tok.loc.start]:this.tok.start};LooseParser.prototype.startNodeAt=function startNodeAt(pos){if(this.options.locations){return new acorn.Node(this.toks,pos[0],pos[1])}else{return new acorn.Node(this.toks,pos)}};LooseParser.prototype.finishNode=function finishNode(node,type){node.type=type;node.end=this.last.end;if(this.options.locations)
{node.loc.end=this.last.loc.end;}
if(this.options.ranges)
{node.range[1]=this.last.end;}
return node};LooseParser.prototype.dummyNode=function dummyNode(type){var dummy=this.startNode();dummy.type=type;dummy.end=dummy.start;if(this.options.locations)
{dummy.loc.end=dummy.loc.start;}
if(this.options.ranges)
{dummy.range[1]=dummy.start;}
this.last={type:acorn.tokTypes.name,start:dummy.start,end:dummy.start,loc:dummy.loc};return dummy};LooseParser.prototype.dummyIdent=function dummyIdent(){var dummy=this.dummyNode("Identifier");dummy.name="✖";return dummy};LooseParser.prototype.dummyString=function dummyString(){var dummy=this.dummyNode("Literal");dummy.value=dummy.raw="✖";return dummy};LooseParser.prototype.eat=function eat(type){if(this.tok.type===type){this.next();return true}else{return false}};LooseParser.prototype.isContextual=function isContextual(name){return this.tok.type===acorn.tokTypes.name&&this.tok.value===name};LooseParser.prototype.eatContextual=function eatContextual(name){return this.tok.value===name&&this.eat(acorn.tokTypes.name)};LooseParser.prototype.canInsertSemicolon=function canInsertSemicolon(){return this.tok.type===acorn.tokTypes.eof||this.tok.type===acorn.tokTypes.braceR||acorn.lineBreak.test(this.input.slice(this.last.end,this.tok.start))};LooseParser.prototype.semicolon=function semicolon(){return this.eat(acorn.tokTypes.semi)};LooseParser.prototype.expect=function expect(type){var this$1=this;if(this.eat(type)){return true}
for(var i=1;i<=2;i++){if(this$1.lookAhead(i).type===type){for(var j=0;j<i;j++){this$1.next();}
return true}}};LooseParser.prototype.pushCx=function pushCx(){this.context.push(this.curIndent);};LooseParser.prototype.popCx=function popCx(){this.curIndent=this.context.pop();};LooseParser.prototype.lineEnd=function lineEnd(pos){while(pos<this.input.length&&!acorn.isNewLine(this.input.charCodeAt(pos))){++pos;}
return pos};LooseParser.prototype.indentationAfter=function indentationAfter(pos){var this$1=this;for(var count=0;;++pos){var ch=this$1.input.charCodeAt(pos);if(ch===32){++count;}
else if(ch===9){count+=this$1.options.tabSize;}
else{return count}}};LooseParser.prototype.closes=function closes(closeTok,indent,line,blockHeuristic){if(this.tok.type===closeTok||this.tok.type===acorn.tokTypes.eof){return true}
return line!==this.curLineStart&&this.curIndent<indent&&this.tokenStartsLine()&&(!blockHeuristic||this.nextLineStart>=this.input.length||this.indentationAfter(this.nextLineStart)<indent)};LooseParser.prototype.tokenStartsLine=function tokenStartsLine(){var this$1=this;for(var p=this.tok.start-1;p>=this.curLineStart;--p){var ch=this$1.input.charCodeAt(p);if(ch!==9&&ch!==32){return false}}
return true};LooseParser.prototype.extend=function extend(name,f){this[name]=f(this[name]);};LooseParser.prototype.parse=function parse(){this.next();return this.parseTopLevel()};LooseParser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i<plugins.length;i++){cls=plugins[i](cls);}
return cls};LooseParser.parse=function parse(input,options){return new this(input,options).parse()};LooseParser.BaseParser=acorn.Parser;var lp=LooseParser.prototype;function isSpace(ch){return(ch<14&&ch>8)||ch===32||ch===160||acorn.isNewLine(ch)}
lp.next=function(){var this$1=this;this.last=this.tok;if(this.ahead.length)
{this.tok=this.ahead.shift();}
else
{this.tok=this.readToken();}
if(this.tok.start>=this.nextLineStart){while(this.tok.start>=this.nextLineStart){this$1.curLineStart=this$1.nextLineStart;this$1.nextLineStart=this$1.lineEnd(this$1.curLineStart)+1;}
this.curIndent=this.indentationAfter(this.curLineStart);}};lp.readToken=function(){var this$1=this;for(;;){try{this$1.toks.next();if(this$1.toks.type===acorn.tokTypes.dot&&this$1.input.substr(this$1.toks.end,1)==="."&&this$1.options.ecmaVersion>=6){this$1.toks.end++;this$1.toks.type=acorn.tokTypes.ellipsis;}
return new acorn.Token(this$1.toks)}catch(e){if(!(e instanceof SyntaxError)){throw e}
var msg=e.message,pos=e.raisedAt,replace=true;if(/unterminated/i.test(msg)){pos=this$1.lineEnd(e.pos+1);if(/string/.test(msg)){replace={start:e.pos,end:pos,type:acorn.tokTypes.string,value:this$1.input.slice(e.pos+1,pos)};}else if(/regular expr/i.test(msg)){var re=this$1.input.slice(e.pos,pos);try{re=new RegExp(re);}catch(e){}
replace={start:e.pos,end:pos,type:acorn.tokTypes.regexp,value:re};}else if(/template/.test(msg)){replace={start:e.pos,end:pos,type:acorn.tokTypes.template,value:this$1.input.slice(e.pos,pos)};}else{replace=false;}}else if(/invalid (unicode|regexp|number)|expecting unicode|octal literal|is reserved|directly after number|expected number in radix/i.test(msg)){while(pos<this.input.length&&!isSpace(this.input.charCodeAt(pos))){++pos;}}else if(/character escape|expected hexadecimal/i.test(msg)){while(pos<this.input.length){var ch=this$1.input.charCodeAt(pos++);if(ch===34||ch===39||acorn.isNewLine(ch)){break}}}else if(/unexpected character/i.test(msg)){pos++;replace=false;}else if(/regular expression/i.test(msg)){replace=true;}else{throw e}
this$1.resetTo(pos);if(replace===true){replace={start:pos,end:pos,type:acorn.tokTypes.name,value:"✖"};}
if(replace){if(this$1.options.locations)
{replace.loc=new acorn.SourceLocation(this$1.toks,acorn.getLineInfo(this$1.input,replace.start),acorn.getLineInfo(this$1.input,replace.end));}
return replace}}}};lp.resetTo=function(pos){var this$1=this;this.toks.pos=pos;var ch=this.input.charAt(pos-1);this.toks.exprAllowed=!ch||/[[{(,;:?/*=+\-~!|&%^<>]/.test(ch)||/[enwfd]/.test(ch)&&/\b(case|else|return|throw|new|in|(instance|type)?of|delete|void)$/.test(this.input.slice(pos-10,pos));if(this.options.locations){this.toks.curLine=1;this.toks.lineStart=acorn.lineBreakG.lastIndex=0;var match;while((match=acorn.lineBreakG.exec(this.input))&&match.index<pos){++this$1.toks.curLine;this$1.toks.lineStart=match.index+match[0].length;}}};lp.lookAhead=function(n){var this$1=this;while(n>this.ahead.length)
{this$1.ahead.push(this$1.readToken());}
return this.ahead[n-1]};function isDummy(node){return node.name==="✖"}
var lp$1=LooseParser.prototype;lp$1.parseTopLevel=function(){var this$1=this;var node=this.startNodeAt(this.options.locations?[0,acorn.getLineInfo(this.input,0)]:0);node.body=[];while(this.tok.type!==acorn.tokTypes.eof){node.body.push(this$1.parseStatement());}
this.toks.adaptDirectivePrologue(node.body);this.last=this.tok;if(this.options.ecmaVersion>=6){node.sourceType=this.options.sourceType;}
return this.finishNode(node,"Program")};lp$1.parseStatement=function(){var this$1=this;var starttype=this.tok.type,node=this.startNode(),kind;if(this.toks.isLet()){starttype=acorn.tokTypes._var;kind="let";}
switch(starttype){case acorn.tokTypes._break:case acorn.tokTypes._continue:this.next();var isBreak=starttype===acorn.tokTypes._break;if(this.semicolon()||this.canInsertSemicolon()){node.label=null;}else{node.label=this.tok.type===acorn.tokTypes.name?this.parseIdent():null;this.semicolon();}
return this.finishNode(node,isBreak?"BreakStatement":"ContinueStatement")
case acorn.tokTypes._debugger:this.next();this.semicolon();return this.finishNode(node,"DebuggerStatement")
case acorn.tokTypes._do:this.next();node.body=this.parseStatement();node.test=this.eat(acorn.tokTypes._while)?this.parseParenExpression():this.dummyIdent();this.semicolon();return this.finishNode(node,"DoWhileStatement")
case acorn.tokTypes._for:this.next();var isAwait=this.options.ecmaVersion>=9&&this.inAsync&&this.eatContextual("await");this.pushCx();this.expect(acorn.tokTypes.parenL);if(this.tok.type===acorn.tokTypes.semi){return this.parseFor(node,null)}
var isLet=this.toks.isLet();if(isLet||this.tok.type===acorn.tokTypes._var||this.tok.type===acorn.tokTypes._const){var init$1=this.parseVar(this.startNode(),true,isLet?"let":this.tok.value);if(init$1.declarations.length===1&&(this.tok.type===acorn.tokTypes._in||this.isContextual("of"))){if(this.options.ecmaVersion>=9&&this.tok.type!==acorn.tokTypes._in){node.await=isAwait;}
return this.parseForIn(node,init$1)}
return this.parseFor(node,init$1)}
var init=this.parseExpression(true);if(this.tok.type===acorn.tokTypes._in||this.isContextual("of")){if(this.options.ecmaVersion>=9&&this.tok.type!==acorn.tokTypes._in){node.await=isAwait;}
return this.parseForIn(node,this.toAssignable(init))}
return this.parseFor(node,init)
case acorn.tokTypes._function:this.next();return this.parseFunction(node,true)
case acorn.tokTypes._if:this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement();node.alternate=this.eat(acorn.tokTypes._else)?this.parseStatement():null;return this.finishNode(node,"IfStatement")
case acorn.tokTypes._return:this.next();if(this.eat(acorn.tokTypes.semi)||this.canInsertSemicolon()){node.argument=null;}
else{node.argument=this.parseExpression();this.semicolon();}
return this.finishNode(node,"ReturnStatement")
case acorn.tokTypes._switch:var blockIndent=this.curIndent,line=this.curLineStart;this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.pushCx();this.expect(acorn.tokTypes.braceL);var cur;while(!this.closes(acorn.tokTypes.braceR,blockIndent,line,true)){if(this$1.tok.type===acorn.tokTypes._case||this$1.tok.type===acorn.tokTypes._default){var isCase=this$1.tok.type===acorn.tokTypes._case;if(cur){this$1.finishNode(cur,"SwitchCase");}
node.cases.push(cur=this$1.startNode());cur.consequent=[];this$1.next();if(isCase){cur.test=this$1.parseExpression();}
else{cur.test=null;}
this$1.expect(acorn.tokTypes.colon);}else{if(!cur){node.cases.push(cur=this$1.startNode());cur.consequent=[];cur.test=null;}
cur.consequent.push(this$1.parseStatement());}}
if(cur){this.finishNode(cur,"SwitchCase");}
this.popCx();this.eat(acorn.tokTypes.braceR);return this.finishNode(node,"SwitchStatement")
case acorn.tokTypes._throw:this.next();node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")
case acorn.tokTypes._try:this.next();node.block=this.parseBlock();node.handler=null;if(this.tok.type===acorn.tokTypes._catch){var clause=this.startNode();this.next();if(this.eat(acorn.tokTypes.parenL)){clause.param=this.toAssignable(this.parseExprAtom(),true);this.expect(acorn.tokTypes.parenR);}else{clause.param=null;}
clause.body=this.parseBlock();node.handler=this.finishNode(clause,"CatchClause");}
node.finalizer=this.eat(acorn.tokTypes._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){return node.block}
return this.finishNode(node,"TryStatement")
case acorn.tokTypes._var:case acorn.tokTypes._const:return this.parseVar(node,false,kind||this.tok.value)
case acorn.tokTypes._while:this.next();node.test=this.parseParenExpression();node.body=this.parseStatement();return this.finishNode(node,"WhileStatement")
case acorn.tokTypes._with:this.next();node.object=this.parseParenExpression();node.body=this.parseStatement();return this.finishNode(node,"WithStatement")
case acorn.tokTypes.braceL:return this.parseBlock()
case acorn.tokTypes.semi:this.next();return this.finishNode(node,"EmptyStatement")
case acorn.tokTypes._class:return this.parseClass(true)
case acorn.tokTypes._import:return this.parseImport()
case acorn.tokTypes._export:return this.parseExport()
default:if(this.toks.isAsyncFunction()){this.next();this.next();return this.parseFunction(node,true,true)}
var expr=this.parseExpression();if(isDummy(expr)){this.next();if(this.tok.type===acorn.tokTypes.eof){return this.finishNode(node,"EmptyStatement")}
return this.parseStatement()}else if(starttype===acorn.tokTypes.name&&expr.type==="Identifier"&&this.eat(acorn.tokTypes.colon)){node.body=this.parseStatement();node.label=expr;return this.finishNode(node,"LabeledStatement")}else{node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")}}};lp$1.parseBlock=function(){var this$1=this;var node=this.startNode();this.pushCx();this.expect(acorn.tokTypes.braceL);var blockIndent=this.curIndent,line=this.curLineStart;node.body=[];while(!this.closes(acorn.tokTypes.braceR,blockIndent,line,true))
{node.body.push(this$1.parseStatement());}
this.popCx();this.eat(acorn.tokTypes.braceR);return this.finishNode(node,"BlockStatement")};lp$1.parseFor=function(node,init){node.init=init;node.test=node.update=null;if(this.eat(acorn.tokTypes.semi)&&this.tok.type!==acorn.tokTypes.semi){node.test=this.parseExpression();}
if(this.eat(acorn.tokTypes.semi)&&this.tok.type!==acorn.tokTypes.parenR){node.update=this.parseExpression();}
this.popCx();this.expect(acorn.tokTypes.parenR);node.body=this.parseStatement();return this.finishNode(node,"ForStatement")};lp$1.parseForIn=function(node,init){var type=this.tok.type===acorn.tokTypes._in?"ForInStatement":"ForOfStatement";this.next();node.left=init;node.right=this.parseExpression();this.popCx();this.expect(acorn.tokTypes.parenR);node.body=this.parseStatement();return this.finishNode(node,type)};lp$1.parseVar=function(node,noIn,kind){var this$1=this;node.kind=kind;this.next();node.declarations=[];do{var decl=this$1.startNode();decl.id=this$1.options.ecmaVersion>=6?this$1.toAssignable(this$1.parseExprAtom(),true):this$1.parseIdent();decl.init=this$1.eat(acorn.tokTypes.eq)?this$1.parseMaybeAssign(noIn):null;node.declarations.push(this$1.finishNode(decl,"VariableDeclarator"));}while(this.eat(acorn.tokTypes.comma))
if(!node.declarations.length){var decl$1=this.startNode();decl$1.id=this.dummyIdent();node.declarations.push(this.finishNode(decl$1,"VariableDeclarator"));}
if(!noIn){this.semicolon();}
return this.finishNode(node,"VariableDeclaration")};lp$1.parseClass=function(isStatement){var this$1=this;var node=this.startNode();this.next();if(this.tok.type===acorn.tokTypes.name){node.id=this.parseIdent();}
else if(isStatement===true){node.id=this.dummyIdent();}
else{node.id=null;}
node.superClass=this.eat(acorn.tokTypes._extends)?this.parseExpression():null;node.body=this.startNode();node.body.body=[];this.pushCx();var indent=this.curIndent+1,line=this.curLineStart;this.eat(acorn.tokTypes.braceL);if(this.curIndent+1<indent){indent=this.curIndent;line=this.curLineStart;}
while(!this.closes(acorn.tokTypes.braceR,indent,line)){if(this$1.semicolon()){continue}
var method=this$1.startNode(),isGenerator=(void 0),isAsync=(void 0);if(this$1.options.ecmaVersion>=6){method.static=false;isGenerator=this$1.eat(acorn.tokTypes.star);}
this$1.parsePropertyName(method);if(isDummy(method.key)){if(isDummy(this$1.parseMaybeAssign())){this$1.next();}this$1.eat(acorn.tokTypes.comma);continue}
if(method.key.type==="Identifier"&&!method.computed&&method.key.name==="static"&&(this$1.tok.type!==acorn.tokTypes.parenL&&this$1.tok.type!==acorn.tokTypes.braceL)){method.static=true;isGenerator=this$1.eat(acorn.tokTypes.star);this$1.parsePropertyName(method);}else{method.static=false;}
if(!method.computed&&method.key.type==="Identifier"&&method.key.name==="async"&&this$1.tok.type!==acorn.tokTypes.parenL&&!this$1.canInsertSemicolon()){isAsync=true;isGenerator=this$1.options.ecmaVersion>=9&&this$1.eat(acorn.tokTypes.star);this$1.parsePropertyName(method);}else{isAsync=false;}
if(this$1.options.ecmaVersion>=5&&method.key.type==="Identifier"&&!method.computed&&(method.key.name==="get"||method.key.name==="set")&&this$1.tok.type!==acorn.tokTypes.parenL&&this$1.tok.type!==acorn.tokTypes.braceL){method.kind=method.key.name;this$1.parsePropertyName(method);method.value=this$1.parseMethod(false);}else{if(!method.computed&&!method.static&&!isGenerator&&!isAsync&&(method.key.type==="Identifier"&&method.key.name==="constructor"||method.key.type==="Literal"&&method.key.value==="constructor")){method.kind="constructor";}else{method.kind="method";}
method.value=this$1.parseMethod(isGenerator,isAsync);}
node.body.body.push(this$1.finishNode(method,"MethodDefinition"));}
this.popCx();if(!this.eat(acorn.tokTypes.braceR)){this.last.end=this.tok.start;if(this.options.locations){this.last.loc.end=this.tok.loc.start;}}
this.semicolon();this.finishNode(node.body,"ClassBody");return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};lp$1.parseFunction=function(node,isStatement,isAsync){var oldInAsync=this.inAsync,oldInFunction=this.inFunction;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=this.eat(acorn.tokTypes.star);}
if(this.options.ecmaVersion>=8){node.async=!!isAsync;}
if(this.tok.type===acorn.tokTypes.name){node.id=this.parseIdent();}
else if(isStatement===true){node.id=this.dummyIdent();}
this.inAsync=node.async;this.inFunction=true;node.params=this.parseFunctionParams();node.body=this.parseBlock();this.toks.adaptDirectivePrologue(node.body.body);this.inAsync=oldInAsync;this.inFunction=oldInFunction;return this.finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")};lp$1.parseExport=function(){var node=this.startNode();this.next();if(this.eat(acorn.tokTypes.star)){node.source=this.eatContextual("from")?this.parseExprAtom():this.dummyString();return this.finishNode(node,"ExportAllDeclaration")}
if(this.eat(acorn.tokTypes._default)){var isAsync;if(this.tok.type===acorn.tokTypes._function||(isAsync=this.toks.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next();}
node.declaration=this.parseFunction(fNode,"nullableID",isAsync);}else if(this.tok.type===acorn.tokTypes._class){node.declaration=this.parseClass("nullableID");}else{node.declaration=this.parseMaybeAssign();this.semicolon();}
return this.finishNode(node,"ExportDefaultDeclaration")}
if(this.tok.type.keyword||this.toks.isLet()||this.toks.isAsyncFunction()){node.declaration=this.parseStatement();node.specifiers=[];node.source=null;}else{node.declaration=null;node.specifiers=this.parseExportSpecifierList();node.source=this.eatContextual("from")?this.parseExprAtom():null;this.semicolon();}
return this.finishNode(node,"ExportNamedDeclaration")};lp$1.parseImport=function(){var node=this.startNode();this.next();if(this.tok.type===acorn.tokTypes.string){node.specifiers=[];node.source=this.parseExprAtom();}else{var elt;if(this.tok.type===acorn.tokTypes.name&&this.tok.value!=="from"){elt=this.startNode();elt.local=this.parseIdent();this.finishNode(elt,"ImportDefaultSpecifier");this.eat(acorn.tokTypes.comma);}
node.specifiers=this.parseImportSpecifiers();node.source=this.eatContextual("from")&&this.tok.type===acorn.tokTypes.string?this.parseExprAtom():this.dummyString();if(elt){node.specifiers.unshift(elt);}}
this.semicolon();return this.finishNode(node,"ImportDeclaration")};lp$1.parseImportSpecifiers=function(){var this$1=this;var elts=[];if(this.tok.type===acorn.tokTypes.star){var elt=this.startNode();this.next();elt.local=this.eatContextual("as")?this.parseIdent():this.dummyIdent();elts.push(this.finishNode(elt,"ImportNamespaceSpecifier"));}else{var indent=this.curIndent,line=this.curLineStart,continuedLine=this.nextLineStart;this.pushCx();this.eat(acorn.tokTypes.braceL);if(this.curLineStart>continuedLine){continuedLine=this.curLineStart;}
while(!this.closes(acorn.tokTypes.braceR,indent+(this.curLineStart<=continuedLine?1:0),line)){var elt$1=this$1.startNode();if(this$1.eat(acorn.tokTypes.star)){elt$1.local=this$1.eatContextual("as")?this$1.parseIdent():this$1.dummyIdent();this$1.finishNode(elt$1,"ImportNamespaceSpecifier");}else{if(this$1.isContextual("from")){break}
elt$1.imported=this$1.parseIdent();if(isDummy(elt$1.imported)){break}
elt$1.local=this$1.eatContextual("as")?this$1.parseIdent():elt$1.imported;this$1.finishNode(elt$1,"ImportSpecifier");}
elts.push(elt$1);this$1.eat(acorn.tokTypes.comma);}
this.eat(acorn.tokTypes.braceR);this.popCx();}
return elts};lp$1.parseExportSpecifierList=function(){var this$1=this;var elts=[];var indent=this.curIndent,line=this.curLineStart,continuedLine=this.nextLineStart;this.pushCx();this.eat(acorn.tokTypes.braceL);if(this.curLineStart>continuedLine){continuedLine=this.curLineStart;}
while(!this.closes(acorn.tokTypes.braceR,indent+(this.curLineStart<=continuedLine?1:0),line)){if(this$1.isContextual("from")){break}
var elt=this$1.startNode();elt.local=this$1.parseIdent();if(isDummy(elt.local)){break}
elt.exported=this$1.eatContextual("as")?this$1.parseIdent():elt.local;this$1.finishNode(elt,"ExportSpecifier");elts.push(elt);this$1.eat(acorn.tokTypes.comma);}
this.eat(acorn.tokTypes.braceR);this.popCx();return elts};var lp$2=LooseParser.prototype;lp$2.checkLVal=function(expr){if(!expr){return expr}
switch(expr.type){case"Identifier":case"MemberExpression":return expr
case"ParenthesizedExpression":expr.expression=this.checkLVal(expr.expression);return expr
default:return this.dummyIdent()}};lp$2.parseExpression=function(noIn){var this$1=this;var start=this.storeCurrentPos();var expr=this.parseMaybeAssign(noIn);if(this.tok.type===acorn.tokTypes.comma){var node=this.startNodeAt(start);node.expressions=[expr];while(this.eat(acorn.tokTypes.comma)){node.expressions.push(this$1.parseMaybeAssign(noIn));}
return this.finishNode(node,"SequenceExpression")}
return expr};lp$2.parseParenExpression=function(){this.pushCx();this.expect(acorn.tokTypes.parenL);var val=this.parseExpression();this.popCx();this.expect(acorn.tokTypes.parenR);return val};lp$2.parseMaybeAssign=function(noIn){if(this.toks.isContextual("yield")){var node=this.startNode();this.next();if(this.semicolon()||this.canInsertSemicolon()||(this.tok.type!==acorn.tokTypes.star&&!this.tok.type.startsExpr)){node.delegate=false;node.argument=null;}else{node.delegate=this.eat(acorn.tokTypes.star);node.argument=this.parseMaybeAssign();}
return this.finishNode(node,"YieldExpression")}
var start=this.storeCurrentPos();var left=this.parseMaybeConditional(noIn);if(this.tok.type.isAssign){var node$1=this.startNodeAt(start);node$1.operator=this.tok.value;node$1.left=this.tok.type===acorn.tokTypes.eq?this.toAssignable(left):this.checkLVal(left);this.next();node$1.right=this.parseMaybeAssign(noIn);return this.finishNode(node$1,"AssignmentExpression")}
return left};lp$2.parseMaybeConditional=function(noIn){var start=this.storeCurrentPos();var expr=this.parseExprOps(noIn);if(this.eat(acorn.tokTypes.question)){var node=this.startNodeAt(start);node.test=expr;node.consequent=this.parseMaybeAssign();node.alternate=this.expect(acorn.tokTypes.colon)?this.parseMaybeAssign(noIn):this.dummyIdent();return this.finishNode(node,"ConditionalExpression")}
return expr};lp$2.parseExprOps=function(noIn){var start=this.storeCurrentPos();var indent=this.curIndent,line=this.curLineStart;return this.parseExprOp(this.parseMaybeUnary(false),start,-1,noIn,indent,line)};lp$2.parseExprOp=function(left,start,minPrec,noIn,indent,line){if(this.curLineStart!==line&&this.curIndent<indent&&this.tokenStartsLine()){return left}
var prec=this.tok.type.binop;if(prec!=null&&(!noIn||this.tok.type!==acorn.tokTypes._in)){if(prec>minPrec){var node=this.startNodeAt(start);node.left=left;node.operator=this.tok.value;this.next();if(this.curLineStart!==line&&this.curIndent<indent&&this.tokenStartsLine()){node.right=this.dummyIdent();}else{var rightStart=this.storeCurrentPos();node.right=this.parseExprOp(this.parseMaybeUnary(false),rightStart,prec,noIn,indent,line);}
this.finishNode(node,/&&|\|\|/.test(node.operator)?"LogicalExpression":"BinaryExpression");return this.parseExprOp(node,start,minPrec,noIn,indent,line)}}
return left};lp$2.parseMaybeUnary=function(sawUnary){var this$1=this;var start=this.storeCurrentPos(),expr;if(this.options.ecmaVersion>=8&&this.toks.isContextual("await")&&(this.inAsync||(!this.inFunction&&this.options.allowAwaitOutsideFunction))){expr=this.parseAwait();sawUnary=true;}else if(this.tok.type.prefix){var node=this.startNode(),update=this.tok.type===acorn.tokTypes.incDec;if(!update){sawUnary=true;}
node.operator=this.tok.value;node.prefix=true;this.next();node.argument=this.parseMaybeUnary(true);if(update){node.argument=this.checkLVal(node.argument);}
expr=this.finishNode(node,update?"UpdateExpression":"UnaryExpression");}else if(this.tok.type===acorn.tokTypes.ellipsis){var node$1=this.startNode();this.next();node$1.argument=this.parseMaybeUnary(sawUnary);expr=this.finishNode(node$1,"SpreadElement");}else{expr=this.parseExprSubscripts();while(this.tok.type.postfix&&!this.canInsertSemicolon()){var node$2=this$1.startNodeAt(start);node$2.operator=this$1.tok.value;node$2.prefix=false;node$2.argument=this$1.checkLVal(expr);this$1.next();expr=this$1.finishNode(node$2,"UpdateExpression");}}
if(!sawUnary&&this.eat(acorn.tokTypes.starstar)){var node$3=this.startNodeAt(start);node$3.operator="**";node$3.left=expr;node$3.right=this.parseMaybeUnary(false);return this.finishNode(node$3,"BinaryExpression")}
return expr};lp$2.parseExprSubscripts=function(){var start=this.storeCurrentPos();return this.parseSubscripts(this.parseExprAtom(),start,false,this.curIndent,this.curLineStart)};lp$2.parseSubscripts=function(base,start,noCalls,startIndent,line){var this$1=this;for(;;){if(this$1.curLineStart!==line&&this$1.curIndent<=startIndent&&this$1.tokenStartsLine()){if(this$1.tok.type===acorn.tokTypes.dot&&this$1.curIndent===startIndent)
{--startIndent;}
else
{return base}}
var maybeAsyncArrow=base.type==="Identifier"&&base.name==="async"&&!this$1.canInsertSemicolon();if(this$1.eat(acorn.tokTypes.dot)){var node=this$1.startNodeAt(start);node.object=base;if(this$1.curLineStart!==line&&this$1.curIndent<=startIndent&&this$1.tokenStartsLine())
{node.property=this$1.dummyIdent();}
else
{node.property=this$1.parsePropertyAccessor()||this$1.dummyIdent();}
node.computed=false;base=this$1.finishNode(node,"MemberExpression");}else if(this$1.tok.type===acorn.tokTypes.bracketL){this$1.pushCx();this$1.next();var node$1=this$1.startNodeAt(start);node$1.object=base;node$1.property=this$1.parseExpression();node$1.computed=true;this$1.popCx();this$1.expect(acorn.tokTypes.bracketR);base=this$1.finishNode(node$1,"MemberExpression");}else if(!noCalls&&this$1.tok.type===acorn.tokTypes.parenL){var exprList=this$1.parseExprList(acorn.tokTypes.parenR);if(maybeAsyncArrow&&this$1.eat(acorn.tokTypes.arrow))
{return this$1.parseArrowExpression(this$1.startNodeAt(start),exprList,true)}
var node$2=this$1.startNodeAt(start);node$2.callee=base;node$2.arguments=exprList;base=this$1.finishNode(node$2,"CallExpression");}else if(this$1.tok.type===acorn.tokTypes.backQuote){var node$3=this$1.startNodeAt(start);node$3.tag=base;node$3.quasi=this$1.parseTemplate();base=this$1.finishNode(node$3,"TaggedTemplateExpression");}else{return base}}};lp$2.parseExprAtom=function(){var node;switch(this.tok.type){case acorn.tokTypes._this:case acorn.tokTypes._super:var type=this.tok.type===acorn.tokTypes._this?"ThisExpression":"Super";node=this.startNode();this.next();return this.finishNode(node,type)
case acorn.tokTypes.name:var start=this.storeCurrentPos();var id=this.parseIdent();var isAsync=false;if(id.name==="async"&&!this.canInsertSemicolon()){if(this.eat(acorn.tokTypes._function))
{return this.parseFunction(this.startNodeAt(start),false,true)}
if(this.tok.type===acorn.tokTypes.name){id=this.parseIdent();isAsync=true;}}
return this.eat(acorn.tokTypes.arrow)?this.parseArrowExpression(this.startNodeAt(start),[id],isAsync):id
case acorn.tokTypes.regexp:node=this.startNode();var val=this.tok.value;node.regex={pattern:val.pattern,flags:val.flags};node.value=val.value;node.raw=this.input.slice(this.tok.start,this.tok.end);this.next();return this.finishNode(node,"Literal")
case acorn.tokTypes.num:case acorn.tokTypes.string:node=this.startNode();node.value=this.tok.value;node.raw=this.input.slice(this.tok.start,this.tok.end);this.next();return this.finishNode(node,"Literal")
case acorn.tokTypes._null:case acorn.tokTypes._true:case acorn.tokTypes._false:node=this.startNode();node.value=this.tok.type===acorn.tokTypes._null?null:this.tok.type===acorn.tokTypes._true;node.raw=this.tok.type.keyword;this.next();return this.finishNode(node,"Literal")
case acorn.tokTypes.parenL:var parenStart=this.storeCurrentPos();this.next();var inner=this.parseExpression();this.expect(acorn.tokTypes.parenR);if(this.eat(acorn.tokTypes.arrow)){var params=inner.expressions||[inner];if(params.length&&isDummy(params[params.length-1]))
{params.pop();}
return this.parseArrowExpression(this.startNodeAt(parenStart),params)}
if(this.options.preserveParens){var par=this.startNodeAt(parenStart);par.expression=inner;inner=this.finishNode(par,"ParenthesizedExpression");}
return inner
case acorn.tokTypes.bracketL:node=this.startNode();node.elements=this.parseExprList(acorn.tokTypes.bracketR,true);return this.finishNode(node,"ArrayExpression")
case acorn.tokTypes.braceL:return this.parseObj()
case acorn.tokTypes._class:return this.parseClass(false)
case acorn.tokTypes._function:node=this.startNode();this.next();return this.parseFunction(node,false)
case acorn.tokTypes._new:return this.parseNew()
case acorn.tokTypes.backQuote:return this.parseTemplate()
default:return this.dummyIdent()}};lp$2.parseNew=function(){var node=this.startNode(),startIndent=this.curIndent,line=this.curLineStart;var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(acorn.tokTypes.dot)){node.meta=meta;node.property=this.parseIdent(true);return this.finishNode(node,"MetaProperty")}
var start=this.storeCurrentPos();node.callee=this.parseSubscripts(this.parseExprAtom(),start,true,startIndent,line);if(this.tok.type===acorn.tokTypes.parenL){node.arguments=this.parseExprList(acorn.tokTypes.parenR);}else{node.arguments=[];}
return this.finishNode(node,"NewExpression")};lp$2.parseTemplateElement=function(){var elem=this.startNode();if(this.tok.type===acorn.tokTypes.invalidTemplate){elem.value={raw:this.tok.value,cooked:null};}else{elem.value={raw:this.input.slice(this.tok.start,this.tok.end).replace(/\r\n?/g,"\n"),cooked:this.tok.value};}
this.next();elem.tail=this.tok.type===acorn.tokTypes.backQuote;return this.finishNode(elem,"TemplateElement")};lp$2.parseTemplate=function(){var this$1=this;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement();node.quasis=[curElt];while(!curElt.tail){this$1.next();node.expressions.push(this$1.parseExpression());if(this$1.expect(acorn.tokTypes.braceR)){curElt=this$1.parseTemplateElement();}else{curElt=this$1.startNode();curElt.value={cooked:"",raw:""};curElt.tail=true;this$1.finishNode(curElt,"TemplateElement");}
node.quasis.push(curElt);}
this.expect(acorn.tokTypes.backQuote);return this.finishNode(node,"TemplateLiteral")};lp$2.parseObj=function(){var this$1=this;var node=this.startNode();node.properties=[];this.pushCx();var indent=this.curIndent+1,line=this.curLineStart;this.eat(acorn.tokTypes.braceL);if(this.curIndent+1<indent){indent=this.curIndent;line=this.curLineStart;}
while(!this.closes(acorn.tokTypes.braceR,indent,line)){var prop=this$1.startNode(),isGenerator=(void 0),isAsync=(void 0),start=(void 0);if(this$1.options.ecmaVersion>=9&&this$1.eat(acorn.tokTypes.ellipsis)){prop.argument=this$1.parseMaybeAssign();node.properties.push(this$1.finishNode(prop,"SpreadElement"));this$1.eat(acorn.tokTypes.comma);continue}
if(this$1.options.ecmaVersion>=6){start=this$1.storeCurrentPos();prop.method=false;prop.shorthand=false;isGenerator=this$1.eat(acorn.tokTypes.star);}
this$1.parsePropertyName(prop);if(this$1.toks.isAsyncProp(prop)){isAsync=true;isGenerator=this$1.options.ecmaVersion>=9&&this$1.eat(acorn.tokTypes.star);this$1.parsePropertyName(prop);}else{isAsync=false;}
if(isDummy(prop.key)){if(isDummy(this$1.parseMaybeAssign())){this$1.next();}this$1.eat(acorn.tokTypes.comma);continue}
if(this$1.eat(acorn.tokTypes.colon)){prop.kind="init";prop.value=this$1.parseMaybeAssign();}else if(this$1.options.ecmaVersion>=6&&(this$1.tok.type===acorn.tokTypes.parenL||this$1.tok.type===acorn.tokTypes.braceL)){prop.kind="init";prop.method=true;prop.value=this$1.parseMethod(isGenerator,isAsync);}else if(this$1.options.ecmaVersion>=5&&prop.key.type==="Identifier"&&!prop.computed&&(prop.key.name==="get"||prop.key.name==="set")&&(this$1.tok.type!==acorn.tokTypes.comma&&this$1.tok.type!==acorn.tokTypes.braceR&&this$1.tok.type!==acorn.tokTypes.eq)){prop.kind=prop.key.name;this$1.parsePropertyName(prop);prop.value=this$1.parseMethod(false);}else{prop.kind="init";if(this$1.options.ecmaVersion>=6){if(this$1.eat(acorn.tokTypes.eq)){var assign=this$1.startNodeAt(start);assign.operator="=";assign.left=prop.key;assign.right=this$1.parseMaybeAssign();prop.value=this$1.finishNode(assign,"AssignmentExpression");}else{prop.value=prop.key;}}else{prop.value=this$1.dummyIdent();}
prop.shorthand=true;}
node.properties.push(this$1.finishNode(prop,"Property"));this$1.eat(acorn.tokTypes.comma);}
this.popCx();if(!this.eat(acorn.tokTypes.braceR)){this.last.end=this.tok.start;if(this.options.locations){this.last.loc.end=this.tok.loc.start;}}
return this.finishNode(node,"ObjectExpression")};lp$2.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(acorn.tokTypes.bracketL)){prop.computed=true;prop.key=this.parseExpression();this.expect(acorn.tokTypes.bracketR);return}else{prop.computed=false;}}
var key=(this.tok.type===acorn.tokTypes.num||this.tok.type===acorn.tokTypes.string)?this.parseExprAtom():this.parseIdent();prop.key=key||this.dummyIdent();};lp$2.parsePropertyAccessor=function(){if(this.tok.type===acorn.tokTypes.name||this.tok.type.keyword){return this.parseIdent()}};lp$2.parseIdent=function(){var name=this.tok.type===acorn.tokTypes.name?this.tok.value:this.tok.type.keyword;if(!name){return this.dummyIdent()}
var node=this.startNode();this.next();node.name=name;return this.finishNode(node,"Identifier")};lp$2.initFunction=function(node){node.id=null;node.params=[];if(this.options.ecmaVersion>=6){node.generator=false;node.expression=false;}
if(this.options.ecmaVersion>=8)
{node.async=false;}};lp$2.toAssignable=function(node,binding){var this$1=this;if(!node||node.type==="Identifier"||(node.type==="MemberExpression"&&!binding)){}else if(node.type==="ParenthesizedExpression"){this.toAssignable(node.expression,binding);}else if(this.options.ecmaVersion<6){return this.dummyIdent()}else if(node.type==="ObjectExpression"){node.type="ObjectPattern";for(var i=0,list=node.properties;i<list.length;i+=1)
{var prop=list[i];this$1.toAssignable(prop,binding);}}else if(node.type==="ArrayExpression"){node.type="ArrayPattern";this.toAssignableList(node.elements,binding);}else if(node.type==="Property"){this.toAssignable(node.value,binding);}else if(node.type==="SpreadElement"){node.type="RestElement";this.toAssignable(node.argument,binding);}else if(node.type==="AssignmentExpression"){node.type="AssignmentPattern";delete node.operator;}else{return this.dummyIdent()}
return node};lp$2.toAssignableList=function(exprList,binding){var this$1=this;for(var i=0,list=exprList;i<list.length;i+=1)
{var expr=list[i];this$1.toAssignable(expr,binding);}
return exprList};lp$2.parseFunctionParams=function(params){params=this.parseExprList(acorn.tokTypes.parenR);return this.toAssignableList(params,true)};lp$2.parseMethod=function(isGenerator,isAsync){var node=this.startNode(),oldInAsync=this.inAsync,oldInFunction=this.inFunction;this.initFunction(node);if(this.options.ecmaVersion>=6)
{node.generator=!!isGenerator;}
if(this.options.ecmaVersion>=8)
{node.async=!!isAsync;}
this.inAsync=node.async;this.inFunction=true;node.params=this.parseFunctionParams();node.body=this.parseBlock();this.toks.adaptDirectivePrologue(node.body.body);this.inAsync=oldInAsync;this.inFunction=oldInFunction;return this.finishNode(node,"FunctionExpression")};lp$2.parseArrowExpression=function(node,params,isAsync){var oldInAsync=this.inAsync,oldInFunction=this.inFunction;this.initFunction(node);if(this.options.ecmaVersion>=8)
{node.async=!!isAsync;}
this.inAsync=node.async;this.inFunction=true;node.params=this.toAssignableList(params,true);node.expression=this.tok.type!==acorn.tokTypes.braceL;if(node.expression){node.body=this.parseMaybeAssign();}else{node.body=this.parseBlock();this.toks.adaptDirectivePrologue(node.body.body);}
this.inAsync=oldInAsync;this.inFunction=oldInFunction;return this.finishNode(node,"ArrowFunctionExpression")};lp$2.parseExprList=function(close,allowEmpty){var this$1=this;this.pushCx();var indent=this.curIndent,line=this.curLineStart,elts=[];this.next();while(!this.closes(close,indent+1,line)){if(this$1.eat(acorn.tokTypes.comma)){elts.push(allowEmpty?null:this$1.dummyIdent());continue}
var elt=this$1.parseMaybeAssign();if(isDummy(elt)){if(this$1.closes(close,indent,line)){break}
this$1.next();}else{elts.push(elt);}
this$1.eat(acorn.tokTypes.comma);}
this.popCx();if(!this.eat(close)){this.last.end=this.tok.start;if(this.options.locations){this.last.loc.end=this.tok.loc.start;}}
return elts};lp$2.parseAwait=function(){var node=this.startNode();this.next();node.argument=this.parseMaybeUnary();return this.finishNode(node,"AwaitExpression")};acorn.defaultOptions.tabSize=4;function parse(input,options){return LooseParser.parse(input,options)}
exports.parse=parse;exports.LooseParser=LooseParser;Object.defineProperty(exports,'__esModule',{value:true});})));;FormatterWorker.CSSFormatter=class{constructor(builder){this._builder=builder;}
format(text,lineEndings,fromOffset,toOffset){this._lineEndings=lineEndings;this._fromOffset=fromOffset;this._toOffset=toOffset;this._lastLine=-1;this._state={};const tokenize=FormatterWorker.createTokenizer('text/css');const oldEnforce=this._builder.setEnforceSpaceBetweenWords(false);tokenize(text.substring(this._fromOffset,this._toOffset),this._tokenCallback.bind(this));this._builder.setEnforceSpaceBetweenWords(oldEnforce);}
_tokenCallback(token,type,startPosition){startPosition+=this._fromOffset;const startLine=this._lineEndings.lowerBound(startPosition);if(startLine!==this._lastLine)
this._state.eatWhitespace=true;if(/^property/.test(type)&&!this._state.inPropertyValue)
this._state.seenProperty=true;this._lastLine=startLine;const isWhitespace=/^\s+$/.test(token);if(isWhitespace){if(!this._state.eatWhitespace)
this._builder.addSoftSpace();return;}
this._state.eatWhitespace=false;if(token==='\n')
return;if(token!=='}'){if(this._state.afterClosingBrace)
this._builder.addNewLine(true);this._state.afterClosingBrace=false;}
if(token==='}'){if(this._state.inPropertyValue)
this._builder.addNewLine();this._builder.decreaseNestingLevel();this._state.afterClosingBrace=true;this._state.inPropertyValue=false;}else if(token===':'&&!this._state.inPropertyValue&&this._state.seenProperty){this._builder.addToken(token,startPosition);this._builder.addSoftSpace();this._state.eatWhitespace=true;this._state.inPropertyValue=true;this._state.seenProperty=false;return;}else if(token==='{'){this._builder.addSoftSpace();this._builder.addToken(token,startPosition);this._builder.addNewLine();this._builder.increaseNestingLevel();return;}
this._builder.addToken(token,startPosition);if(type==='comment'&&!this._state.inPropertyValue&&!this._state.seenProperty)
this._builder.addNewLine();if(token===';'&&this._state.inPropertyValue){this._state.inPropertyValue=false;this._builder.addNewLine();}else if(token==='}'){this._builder.addNewLine();}}};;FormatterWorker.AcornTokenizer=class{constructor(content){this._content=content;this._comments=[];this._tokenizer=acorn.tokenizer(this._content,{ecmaVersion:8,onComment:this._comments});this._textCursor=new TextUtils.TextCursor(this._content.computeLineEndings());this._tokenLineStart=0;this._tokenLineEnd=0;this._nextTokenInternal();}
static punctuator(token,values){return token.type!==acorn.tokTypes.num&&token.type!==acorn.tokTypes.regexp&&token.type!==acorn.tokTypes.string&&token.type!==acorn.tokTypes.name&&!token.type.keyword&&(!values||(token.type.label.length===1&&values.indexOf(token.type.label)!==-1));}
static keyword(token,keyword){return!!token.type.keyword&&token.type!==acorn.tokTypes['_true']&&token.type!==acorn.tokTypes['_false']&&token.type!==acorn.tokTypes['_null']&&(!keyword||token.type.keyword===keyword);}
static identifier(token,identifier){return token.type===acorn.tokTypes.name&&(!identifier||token.value===identifier);}
static lineComment(token){return token.type==='Line';}
static blockComment(token){return token.type==='Block';}
_nextTokenInternal(){if(this._comments.length)
return this._comments.shift();const token=this._bufferedToken;this._bufferedToken=this._tokenizer.getToken();return token;}
nextToken(){const token=this._nextTokenInternal();if(token.type===acorn.tokTypes.eof)
return null;this._textCursor.advance(token.start);this._tokenLineStart=this._textCursor.lineNumber();this._tokenColumnStart=this._textCursor.columnNumber();this._textCursor.advance(token.end);this._tokenLineEnd=this._textCursor.lineNumber();return token;}
peekToken(){if(this._comments.length)
return this._comments[0];return this._bufferedToken.type!==acorn.tokTypes.eof?this._bufferedToken:null;}
tokenLineStart(){return this._tokenLineStart;}
tokenLineEnd(){return this._tokenLineEnd;}
tokenColumnStart(){return this._tokenColumnStart;}};;FormatterWorker.JavaScriptFormatter=class{constructor(builder){this._builder=builder;}
format(text,lineEndings,fromOffset,toOffset){this._fromOffset=fromOffset;this._toOffset=toOffset;this._content=text.substring(this._fromOffset,this._toOffset);this._lastLineNumber=0;this._tokenizer=new FormatterWorker.AcornTokenizer(this._content);const ast=acorn.parse(this._content,{ranges:false,ecmaVersion:8,preserveParens:true});const walker=new FormatterWorker.ESTreeWalker(this._beforeVisit.bind(this),this._afterVisit.bind(this));walker.walk(ast);}
_push(token,format){for(let i=0;i<format.length;++i){if(format[i]==='s'){this._builder.addSoftSpace();}else if(format[i]==='S'){this._builder.addHardSpace();}else if(format[i]==='n'){this._builder.addNewLine();}else if(format[i]==='>'){this._builder.increaseNestingLevel();}else if(format[i]==='<'){this._builder.decreaseNestingLevel();}else if(format[i]==='t'){if(this._tokenizer.tokenLineStart()-this._lastLineNumber>1)
this._builder.addNewLine(true);this._lastLineNumber=this._tokenizer.tokenLineEnd();this._builder.addToken(this._content.substring(token.start,token.end),this._fromOffset+token.start);}}}
_beforeVisit(node){if(!node.parent)
return;while(this._tokenizer.peekToken()&&this._tokenizer.peekToken().start<node.start){const token=(this._tokenizer.nextToken());const format=this._formatToken(node.parent,token);this._push(token,format);}}
_afterVisit(node){while(this._tokenizer.peekToken()&&this._tokenizer.peekToken().start<node.end){const token=(this._tokenizer.nextToken());const format=this._formatToken(node,token);this._push(token,format);}
this._push(null,this._finishNode(node));}
_inForLoopHeader(node){const parent=node.parent;if(!parent)
return false;if(parent.type==='ForStatement')
return node===parent.init||node===parent.test||node===parent.update;if(parent.type==='ForInStatement'||parent.type==='ForOfStatement')
return node===parent.left||parent.right;return false;}
_formatToken(node,token){const AT=FormatterWorker.AcornTokenizer;if(AT.lineComment(token))
return'tn';if(AT.blockComment(token))
return'tn';if(node.type==='ContinueStatement'||node.type==='BreakStatement'){return node.label&&AT.keyword(token)?'ts':'t';}else if(node.type==='Identifier'){return't';}else if(node.type==='ReturnStatement'){if(AT.punctuator(token,';'))
return't';return node.argument?'ts':'t';}else if(node.type==='Property'){if(AT.punctuator(token,':'))
return'ts';return't';}else if(node.type==='ArrayExpression'){if(AT.punctuator(token,','))
return'ts';return't';}else if(node.type==='LabeledStatement'){if(AT.punctuator(token,':'))
return'ts';}else if(node.type==='LogicalExpression'||node.type==='AssignmentExpression'||node.type==='BinaryExpression'){if(AT.punctuator(token)&&!AT.punctuator(token,'()'))
return'sts';}else if(node.type==='ConditionalExpression'){if(AT.punctuator(token,'?:'))
return'sts';}else if(node.type==='VariableDeclarator'){if(AT.punctuator(token,'='))
return'sts';}else if(node.type==='ObjectPattern'){if(node.parent&&node.parent.type==='VariableDeclarator'&&AT.punctuator(token,'{'))
return'st';if(AT.punctuator(token,','))
return'ts';}else if(node.type==='FunctionDeclaration'){if(AT.punctuator(token,',)'))
return'ts';}else if(node.type==='FunctionExpression'){if(AT.punctuator(token,',)'))
return'ts';if(AT.keyword(token,'function'))
return node.id?'ts':'t';}else if(node.type==='WithStatement'){if(AT.punctuator(token,')'))
return node.body&&node.body.type==='BlockStatement'?'ts':'tn>';}else if(node.type==='SwitchStatement'){if(AT.punctuator(token,'{'))
return'tn>';if(AT.punctuator(token,'}'))
return'n<tn';if(AT.punctuator(token,')'))
return'ts';}else if(node.type==='SwitchCase'){if(AT.keyword(token,'case'))
return'n<ts';if(AT.keyword(token,'default'))
return'n<t';if(AT.punctuator(token,':'))
return'tn>';}else if(node.type==='VariableDeclaration'){if(AT.punctuator(token,',')){let allVariablesInitialized=true;const declarations=(node.declarations);for(let i=0;i<declarations.length;++i)
allVariablesInitialized=allVariablesInitialized&&!!declarations[i].init;return!this._inForLoopHeader(node)&&allVariablesInitialized?'nSSts':'ts';}}else if(node.type==='BlockStatement'){if(AT.punctuator(token,'{'))
return node.body.length?'tn>':'t';if(AT.punctuator(token,'}'))
return node.body.length?'n<t':'t';}else if(node.type==='CatchClause'){if(AT.punctuator(token,')'))
return'ts';}else if(node.type==='ObjectExpression'){if(!node.properties.length)
return't';if(AT.punctuator(token,'{'))
return'tn>';if(AT.punctuator(token,'}'))
return'n<t';if(AT.punctuator(token,','))
return'tn';}else if(node.type==='IfStatement'){if(AT.punctuator(token,')'))
return node.consequent&&node.consequent.type==='BlockStatement'?'ts':'tn>';if(AT.keyword(token,'else')){const preFormat=node.consequent&&node.consequent.type==='BlockStatement'?'st':'n<t';let postFormat='n>';if(node.alternate&&(node.alternate.type==='BlockStatement'||node.alternate.type==='IfStatement'))
postFormat='s';return preFormat+postFormat;}}else if(node.type==='CallExpression'){if(AT.punctuator(token,','))
return'ts';}else if(node.type==='SequenceExpression'&&AT.punctuator(token,',')){return node.parent&&node.parent.type==='SwitchCase'?'ts':'tn';}else if(node.type==='ForStatement'||node.type==='ForOfStatement'||node.type==='ForInStatement'){if(AT.punctuator(token,';'))
return'ts';if(AT.keyword(token,'in')||AT.identifier(token,'of'))
return'sts';if(AT.punctuator(token,')'))
return node.body&&node.body.type==='BlockStatement'?'ts':'tn>';}else if(node.type==='WhileStatement'){if(AT.punctuator(token,')'))
return node.body&&node.body.type==='BlockStatement'?'ts':'tn>';}else if(node.type==='DoWhileStatement'){const blockBody=node.body&&node.body.type==='BlockStatement';if(AT.keyword(token,'do'))
return blockBody?'ts':'tn>';if(AT.keyword(token,'while'))
return blockBody?'sts':'n<ts';}else if(node.type==='ClassBody'){if(AT.punctuator(token,'{'))
return'stn>';if(AT.punctuator(token,'}'))
return'<ntn';return't';}else if(node.type==='YieldExpression'){return't';}else if(node.type==='Super'){return't';}
return AT.keyword(token)&&!AT.keyword(token,'this')?'ts':'t';}
_finishNode(node){if(node.type==='WithStatement'){if(node.body&&node.body.type!=='BlockStatement')
return'n<';}else if(node.type==='VariableDeclaration'){if(!this._inForLoopHeader(node))
return'n';}else if(node.type==='ForStatement'||node.type==='ForOfStatement'||node.type==='ForInStatement'){if(node.body&&node.body.type!=='BlockStatement')
return'n<';}else if(node.type==='BlockStatement'){if(node.parent&&node.parent.type==='IfStatement'&&node.parent.alternate&&node.parent.consequent===node)
return'';if(node.parent&&node.parent.type==='FunctionExpression'&&node.parent.parent&&node.parent.parent.type==='Property')
return'';if(node.parent&&node.parent.type==='FunctionExpression'&&node.parent.parent&&node.parent.parent.type==='VariableDeclarator')
return'';if(node.parent&&node.parent.type==='FunctionExpression'&&node.parent.parent&&node.parent.parent.type==='CallExpression')
return'';if(node.parent&&node.parent.type==='DoWhileStatement')
return'';if(node.parent&&node.parent.type==='TryStatement'&&node.parent.block===node)
return's';if(node.parent&&node.parent.type==='CatchClause'&&node.parent.parent.finalizer)
return's';return'n';}else if(node.type==='WhileStatement'){if(node.body&&node.body.type!=='BlockStatement')
return'n<';}else if(node.type==='IfStatement'){if(node.alternate){if(node.alternate.type!=='BlockStatement'&&node.alternate.type!=='IfStatement')
return'<';}else if(node.consequent){if(node.consequent.type!=='BlockStatement')
return'<';}}else if(node.type==='BreakStatement'||node.type==='ContinueStatement'||node.type==='ThrowStatement'||node.type==='ReturnStatement'||node.type==='ExpressionStatement'){return'n';}
return'';}};;FormatterWorker.FormattedContentBuilder=class{constructor(indentString){this._lastOriginalPosition=0;this._formattedContent=[];this._formattedContentLength=0;this._lastFormattedPosition=0;this._mapping={original:[0],formatted:[0]};this._nestingLevel=0;this._indentString=indentString;this._cachedIndents=new Map();this._newLines=0;this._softSpace=false;this._hardSpaces=0;this._enforceSpaceBetweenWords=true;}
setEnforceSpaceBetweenWords(value){const oldValue=this._enforceSpaceBetweenWords;this._enforceSpaceBetweenWords=value;return oldValue;}
addToken(token,offset){const last=this._formattedContent.peekLast();if(this._enforceSpaceBetweenWords&&last&&/\w/.test(last[last.length-1])&&/\w/.test(token))
this.addSoftSpace();this._appendFormatting();this._addMappingIfNeeded(offset);this._addText(token);}
addSoftSpace(){if(!this._hardSpaces)
this._softSpace=true;}
addHardSpace(){this._softSpace=false;++this._hardSpaces;}
addNewLine(noSquash){if(!this._formattedContentLength)
return;if(noSquash)
++this._newLines;else
this._newLines=this._newLines||1;}
increaseNestingLevel(){this._nestingLevel+=1;}
decreaseNestingLevel(){if(this._nestingLevel>0)
this._nestingLevel-=1;}
_appendFormatting(){if(this._newLines){for(let i=0;i<this._newLines;++i)
this._addText('\n');this._addText(this._indent());}else if(this._softSpace){this._addText(' ');}
if(this._hardSpaces){for(let i=0;i<this._hardSpaces;++i)
this._addText(' ');}
this._newLines=0;this._softSpace=false;this._hardSpaces=0;}
content(){return this._formattedContent.join('')+(this._newLines?'\n':'');}
mapping(){return this._mapping;}
_indent(){const cachedValue=this._cachedIndents.get(this._nestingLevel);if(cachedValue)
return cachedValue;let fullIndent='';for(let i=0;i<this._nestingLevel;++i)
fullIndent+=this._indentString;if(this._nestingLevel<=20)
this._cachedIndents.set(this._nestingLevel,fullIndent);return fullIndent;}
_addText(text){this._formattedContent.push(text);this._formattedContentLength+=text.length;}
_addMappingIfNeeded(originalPosition){if(originalPosition-this._lastOriginalPosition===this._formattedContentLength-this._lastFormattedPosition)
return;this._mapping.original.push(originalPosition);this._lastOriginalPosition=originalPosition;this._mapping.formatted.push(this._formattedContentLength);this._lastFormattedPosition=this._formattedContentLength;}};;FormatterWorker.CSSParserStates={Initial:'Initial',Selector:'Selector',Style:'Style',PropertyName:'PropertyName',PropertyValue:'PropertyValue',AtRule:'AtRule'};FormatterWorker.parseCSS=function(text){FormatterWorker._innerParseCSS(text,postMessage);};FormatterWorker._innerParseCSS=function(text,chunkCallback){const chunkSize=100000;const lines=text.split('\n');let rules=[];let processedChunkCharacters=0;let state=FormatterWorker.CSSParserStates.Initial;let rule;let property;const UndefTokenType=new Set();let disabledRules=[];function disabledRulesCallback(chunk){disabledRules=disabledRules.concat(chunk.chunk);}
function processToken(tokenValue,tokenTypes,column,newColumn){const tokenType=tokenTypes?new Set(tokenTypes.split(' ')):UndefTokenType;switch(state){case FormatterWorker.CSSParserStates.Initial:if(tokenType.has('qualifier')||tokenType.has('builtin')||tokenType.has('tag')){rule={selectorText:tokenValue,lineNumber:lineNumber,columnNumber:column,properties:[],};state=FormatterWorker.CSSParserStates.Selector;}else if(tokenType.has('def')){rule={atRule:tokenValue,lineNumber:lineNumber,columnNumber:column,};state=FormatterWorker.CSSParserStates.AtRule;}
break;case FormatterWorker.CSSParserStates.Selector:if(tokenValue==='{'&&tokenType===UndefTokenType){rule.selectorText=rule.selectorText.trim();rule.styleRange=createRange(lineNumber,newColumn);state=FormatterWorker.CSSParserStates.Style;}else{rule.selectorText+=tokenValue;}
break;case FormatterWorker.CSSParserStates.AtRule:if((tokenValue===';'||tokenValue==='{')&&tokenType===UndefTokenType){rule.atRule=rule.atRule.trim();rules.push(rule);state=FormatterWorker.CSSParserStates.Initial;}else{rule.atRule+=tokenValue;}
break;case FormatterWorker.CSSParserStates.Style:if(tokenType.has('meta')||tokenType.has('property')){property={name:tokenValue,value:'',range:createRange(lineNumber,column),nameRange:createRange(lineNumber,column)};state=FormatterWorker.CSSParserStates.PropertyName;}else if(tokenValue==='}'&&tokenType===UndefTokenType){rule.styleRange.endLine=lineNumber;rule.styleRange.endColumn=column;rules.push(rule);state=FormatterWorker.CSSParserStates.Initial;}else if(tokenType.has('comment')){if(tokenValue.substring(0,2)!=='/*'||tokenValue.substring(tokenValue.length-2)!=='*/')
break;const uncommentedText=tokenValue.substring(2,tokenValue.length-2);const fakeRule='a{\n'+uncommentedText+'}';disabledRules=[];FormatterWorker._innerParseCSS(fakeRule,disabledRulesCallback);if(disabledRules.length===1&&disabledRules[0].properties.length===1){const disabledProperty=disabledRules[0].properties[0];disabledProperty.disabled=true;disabledProperty.range=createRange(lineNumber,column);disabledProperty.range.endColumn=newColumn;const lineOffset=lineNumber-1;const columnOffset=column+2;disabledProperty.nameRange.startLine+=lineOffset;disabledProperty.nameRange.startColumn+=columnOffset;disabledProperty.nameRange.endLine+=lineOffset;disabledProperty.nameRange.endColumn+=columnOffset;disabledProperty.valueRange.startLine+=lineOffset;disabledProperty.valueRange.startColumn+=columnOffset;disabledProperty.valueRange.endLine+=lineOffset;disabledProperty.valueRange.endColumn+=columnOffset;rule.properties.push(disabledProperty);}}
break;case FormatterWorker.CSSParserStates.PropertyName:if(tokenValue===':'&&tokenType===UndefTokenType){property.name=property.name;property.nameRange.endLine=lineNumber;property.nameRange.endColumn=column;property.valueRange=createRange(lineNumber,newColumn);state=FormatterWorker.CSSParserStates.PropertyValue;}else if(tokenType.has('property')){property.name+=tokenValue;}
break;case FormatterWorker.CSSParserStates.PropertyValue:if((tokenValue===';'||tokenValue==='}')&&tokenType===UndefTokenType){property.value=property.value;property.valueRange.endLine=lineNumber;property.valueRange.endColumn=column;property.range.endLine=lineNumber;property.range.endColumn=tokenValue===';'?newColumn:column;rule.properties.push(property);if(tokenValue==='}'){rule.styleRange.endLine=lineNumber;rule.styleRange.endColumn=column;rules.push(rule);state=FormatterWorker.CSSParserStates.Initial;}else{state=FormatterWorker.CSSParserStates.Style;}}else if(!tokenType.has('comment')){property.value+=tokenValue;}
break;default:console.assert(false,'Unknown CSS parser state.');}
processedChunkCharacters+=newColumn-column;if(processedChunkCharacters>chunkSize){chunkCallback({chunk:rules,isLastChunk:false});rules=[];processedChunkCharacters=0;}}
const tokenizer=FormatterWorker.createTokenizer('text/css');let lineNumber;for(lineNumber=0;lineNumber<lines.length;++lineNumber){const line=lines[lineNumber];tokenizer(line,processToken);processToken('\n',null,line.length,line.length+1);}
chunkCallback({chunk:rules,isLastChunk:true});function createRange(lineNumber,columnNumber){return{startLine:lineNumber,startColumn:columnNumber,endLine:lineNumber,endColumn:columnNumber};}};;FormatterWorker.HTMLFormatter=class{constructor(builder){this._builder=builder;this._jsFormatter=new FormatterWorker.JavaScriptFormatter(builder);this._cssFormatter=new FormatterWorker.CSSFormatter(builder);}
format(text,lineEndings){this._text=text;this._lineEndings=lineEndings;this._model=new FormatterWorker.HTMLModel(text);this._walk(this._model.document());}
_formatTokensTill(element,offset){while(this._model.peekToken()&&this._model.peekToken().startOffset<offset){const token=this._model.nextToken();this._formatToken(element,token);}}
_walk(element){if(element.parent)
this._formatTokensTill(element.parent,element.openTag.startOffset);this._beforeOpenTag(element);this._formatTokensTill(element,element.openTag.endOffset);this._afterOpenTag(element);for(let i=0;i<element.children.length;++i)
this._walk(element.children[i]);this._formatTokensTill(element,element.closeTag.startOffset);this._beforeCloseTag(element);this._formatTokensTill(element,element.closeTag.endOffset);this._afterCloseTag(element);}
_beforeOpenTag(element){if(!element.children.length||element===this._model.document())
return;this._builder.addNewLine();}
_afterOpenTag(element){if(!element.children.length||element===this._model.document())
return;this._builder.increaseNestingLevel();this._builder.addNewLine();}
_beforeCloseTag(element){if(!element.children.length||element===this._model.document())
return;this._builder.decreaseNestingLevel();this._builder.addNewLine();}
_afterCloseTag(element){this._builder.addNewLine();}
_formatToken(element,token){if(token.value.isWhitespace())
return;if(token.type.has('comment')||token.type.has('meta')){this._builder.addNewLine();this._builder.addToken(token.value.trim(),token.startOffset);this._builder.addNewLine();return;}
const isBodyToken=element.openTag.endOffset<=token.startOffset&&token.startOffset<element.closeTag.startOffset;if(isBodyToken&&element.name==='style'){this._builder.addNewLine();this._builder.increaseNestingLevel();this._cssFormatter.format(this._text,this._lineEndings,token.startOffset,token.endOffset);this._builder.decreaseNestingLevel();return;}
if(isBodyToken&&element.name==='script'){this._builder.addNewLine();this._builder.increaseNestingLevel();if(this._scriptTagIsJavaScript(element)){this._jsFormatter.format(this._text,this._lineEndings,token.startOffset,token.endOffset);}else{this._builder.addToken(token.value,token.startOffset);this._builder.addNewLine();}
this._builder.decreaseNestingLevel();return;}
if(!isBodyToken&&token.type.has('attribute'))
this._builder.addSoftSpace();this._builder.addToken(token.value,token.startOffset);}
_scriptTagIsJavaScript(element){if(!element.openTag.attributes.has('type'))
return true;let type=element.openTag.attributes.get('type').toLowerCase();if(!type)
return true;const isWrappedInQuotes=/^(["\'])(.*)\1$/.exec(type.trim());if(isWrappedInQuotes)
type=isWrappedInQuotes[2];return FormatterWorker.HTMLFormatter.SupportedJavaScriptMimeTypes.has(type.trim());}};FormatterWorker.HTMLFormatter.SupportedJavaScriptMimeTypes=new Set(['application/ecmascript','application/javascript','application/x-ecmascript','application/x-javascript','text/ecmascript','text/javascript','text/javascript1.0','text/javascript1.1','text/javascript1.2','text/javascript1.3','text/javascript1.4','text/javascript1.5','text/jscript','text/livescript','text/x-ecmascript','text/x-javascript']);FormatterWorker.HTMLModel=class{constructor(text){this._state=FormatterWorker.HTMLModel.ParseState.Initial;this._document=new FormatterWorker.HTMLModel.Element('document');this._document.openTag=new FormatterWorker.HTMLModel.Tag('document',0,0,new Map(),true,false);this._document.closeTag=new FormatterWorker.HTMLModel.Tag('document',text.length,text.length,new Map(),false,false);this._stack=[this._document];this._tokens=[];this._tokenIndex=0;this._build(text);}
_build(text){const tokenizer=FormatterWorker.createTokenizer('text/html');let lastOffset=0;const lowerCaseText=text.toLowerCase();while(true){tokenizer(text.substring(lastOffset),processToken.bind(this,lastOffset));if(lastOffset>=text.length)
break;const element=this._stack.peekLast();lastOffset=lowerCaseText.indexOf('</'+element.name,lastOffset);if(lastOffset===-1)
lastOffset=text.length;const tokenStart=element.openTag.endOffset;const tokenEnd=lastOffset;const tokenValue=text.substring(tokenStart,tokenEnd);this._tokens.push(new FormatterWorker.HTMLModel.Token(tokenValue,new Set(),tokenStart,tokenEnd));}
while(this._stack.length>1){const element=this._stack.peekLast();this._popElement(new FormatterWorker.HTMLModel.Tag(element.name,text.length,text.length,new Map(),false,false));}
function processToken(baseOffset,tokenValue,type,tokenStart,tokenEnd){tokenStart+=baseOffset;tokenEnd+=baseOffset;lastOffset=tokenEnd;const tokenType=type?new Set(type.split(' ')):new Set();const token=new FormatterWorker.HTMLModel.Token(tokenValue,tokenType,tokenStart,tokenEnd);this._tokens.push(token);this._updateDOM(token);const element=this._stack.peekLast();if(element&&(element.name==='script'||element.name==='style')&&element.openTag.endOffset===lastOffset)
return FormatterWorker.AbortTokenization;}}
_updateDOM(token){const S=FormatterWorker.HTMLModel.ParseState;const value=token.value;const type=token.type;switch(this._state){case S.Initial:if(type.has('bracket')&&(value==='<'||value==='</')){this._onStartTag(token);this._state=S.Tag;}
return;case S.Tag:if(type.has('tag')&&!type.has('bracket')){this._tagName=value.trim().toLowerCase();}else if(type.has('attribute')){this._attributeName=value.trim().toLowerCase();this._attributes.set(this._attributeName,'');this._state=S.AttributeName;}else if(type.has('bracket')&&(value==='>'||value==='/>')){this._onEndTag(token);this._state=S.Initial;}
return;case S.AttributeName:if(!type.size&&value==='='){this._state=S.AttributeValue;}else if(type.has('bracket')&&(value==='>'||value==='/>')){this._onEndTag(token);this._state=S.Initial;}
return;case S.AttributeValue:if(type.has('string')){this._attributes.set(this._attributeName,value);this._state=S.Tag;}else if(type.has('bracket')&&(value==='>'||value==='/>')){this._onEndTag(token);this._state=S.Initial;}
return;}}
_onStartTag(token){this._tagName='';this._tagStartOffset=token.startOffset;this._tagEndOffset=null;this._attributes=new Map();this._attributeName='';this._isOpenTag=token.value==='<';}
_onEndTag(token){this._tagEndOffset=token.endOffset;const selfClosingTag=token.value==='/>'||FormatterWorker.HTMLModel.SelfClosingTags.has(this._tagName);const tag=new FormatterWorker.HTMLModel.Tag(this._tagName,this._tagStartOffset,this._tagEndOffset,this._attributes,this._isOpenTag,selfClosingTag);this._onTagComplete(tag);}
_onTagComplete(tag){if(tag.isOpenTag){const topElement=this._stack.peekLast();if(topElement!==this._document&&topElement.openTag.selfClosingTag)
this._popElement(autocloseTag(topElement,topElement.openTag.endOffset));else if((topElement.name in FormatterWorker.HTMLModel.AutoClosingTags)&&FormatterWorker.HTMLModel.AutoClosingTags[topElement.name].has(tag.name))
this._popElement(autocloseTag(topElement,tag.startOffset));this._pushElement(tag);return;}
while(this._stack.length>1&&this._stack.peekLast().name!==tag.name)
this._popElement(autocloseTag(this._stack.peekLast(),tag.startOffset));if(this._stack.length===1)
return;this._popElement(tag);function autocloseTag(element,offset){return new FormatterWorker.HTMLModel.Tag(element.name,offset,offset,new Map(),false,false);}}
_popElement(closeTag){const element=this._stack.pop();element.closeTag=closeTag;}
_pushElement(openTag){const topElement=this._stack.peekLast();const newElement=new FormatterWorker.HTMLModel.Element(openTag.name);newElement.parent=topElement;topElement.children.push(newElement);newElement.openTag=openTag;this._stack.push(newElement);}
peekToken(){return this._tokenIndex<this._tokens.length?this._tokens[this._tokenIndex]:null;}
nextToken(){return this._tokens[this._tokenIndex++];}
document(){return this._document;}};FormatterWorker.HTMLModel.SelfClosingTags=new Set(['area','base','br','col','command','embed','hr','img','input','keygen','link','meta','param','source','track','wbr']);FormatterWorker.HTMLModel.AutoClosingTags={'head':new Set(['body']),'li':new Set(['li']),'dt':new Set(['dt','dd']),'dd':new Set(['dt','dd']),'p':new Set(['address','article','aside','blockquote','div','dl','fieldset','footer','form','h1','h2','h3','h4','h5','h6','header','hgroup','hr','main','nav','ol','p','pre','section','table','ul']),'rb':new Set(['rb','rt','rtc','rp']),'rt':new Set(['rb','rt','rtc','rp']),'rtc':new Set(['rb','rtc','rp']),'rp':new Set(['rb','rt','rtc','rp']),'optgroup':new Set(['optgroup']),'option':new Set(['option','optgroup']),'colgroup':new Set(['colgroup']),'thead':new Set(['tbody','tfoot']),'tbody':new Set(['tbody','tfoot']),'tfoot':new Set(['tbody']),'tr':new Set(['tr']),'td':new Set(['td','th']),'th':new Set(['td','th']),};FormatterWorker.HTMLModel.ParseState={Initial:'Initial',Tag:'Tag',AttributeName:'AttributeName',AttributeValue:'AttributeValue'};FormatterWorker.HTMLModel.Token=class{constructor(value,type,startOffset,endOffset){this.value=value;this.type=type;this.startOffset=startOffset;this.endOffset=endOffset;}};FormatterWorker.HTMLModel.Tag=class{constructor(name,startOffset,endOffset,attributes,isOpenTag,selfClosingTag){this.name=name;this.startOffset=startOffset;this.endOffset=endOffset;this.attributes=attributes;this.isOpenTag=isOpenTag;this.selfClosingTag=selfClosingTag;}};FormatterWorker.HTMLModel.Element=class{constructor(name){this.name=name;this.children=[];this.parent=null;this.openTag=null;this.closeTag=null;}};;FormatterWorker.IdentityFormatter=class{constructor(builder){this._builder=builder;}
format(text,lineEndings,fromOffset,toOffset){const content=text.substring(fromOffset,toOffset);this._builder.addToken(content,fromOffset);}};;FormatterWorker.javaScriptOutline=function(content){const chunkSize=100000;let outlineChunk=[];let lastReportedOffset=0;let ast;try{ast=acorn.parse(content,{ranges:false,ecmaVersion:8});}catch(e){ast=acorn.loose.parse(content,{ranges:false,ecmaVersion:8});}
const textCursor=new TextUtils.TextCursor(content.computeLineEndings());const walker=new FormatterWorker.ESTreeWalker(beforeVisit);walker.walk(ast);postMessage({chunk:outlineChunk,isLastChunk:true});function beforeVisit(node){if(node.type==='ClassDeclaration'){reportClass((node.id));}else if(node.type==='VariableDeclarator'&&isClassNode(node.init)){reportClass((node.id));}else if(node.type==='AssignmentExpression'&&isNameNode(node.left)&&isClassNode(node.right)){reportClass((node.left));}else if(node.type==='Property'&&isNameNode(node.key)&&isClassNode(node.value)){reportClass((node.key));}else if(node.type==='FunctionDeclaration'){reportFunction((node.id),node);}else if(node.type==='VariableDeclarator'&&isFunctionNode(node.init)){reportFunction((node.id),(node.init));}else if(node.type==='AssignmentExpression'&&isNameNode(node.left)&&isFunctionNode(node.right)){reportFunction((node.left),(node.right));}else if((node.type==='MethodDefinition'||node.type==='Property')&&isNameNode(node.key)&&isFunctionNode(node.value)){const namePrefix=[];if(node.kind==='get'||node.kind==='set')
namePrefix.push(node.kind);if(node.static)
namePrefix.push('static');reportFunction(node.key,node.value,namePrefix.join(' '));}}
function reportClass(nameNode){const name='class '+stringifyNameNode(nameNode);textCursor.advance(nameNode.start);addOutlineItem({name:name,line:textCursor.lineNumber(),column:textCursor.columnNumber(),});}
function reportFunction(nameNode,functionNode,namePrefix){let name=stringifyNameNode(nameNode);if(functionNode.generator)
name='*'+name;if(namePrefix)
name=namePrefix+' '+name;if(functionNode.async)
name='async '+name;textCursor.advance(nameNode.start);addOutlineItem({name:name,line:textCursor.lineNumber(),column:textCursor.columnNumber(),arguments:stringifyArguments((functionNode.params))});}
function isNameNode(node){if(!node)
return false;if(node.type==='MemberExpression')
return!node.computed&&node.property.type==='Identifier';return node.type==='Identifier';}
function isFunctionNode(node){if(!node)
return false;return node.type==='FunctionExpression'||node.type==='ArrowFunctionExpression';}
function isClassNode(node){return!!node&&node.type==='ClassExpression';}
function stringifyNameNode(node){if(node.type==='MemberExpression')
node=(node.property);console.assert(node.type==='Identifier','Cannot extract identifier from unknown type: '+node.type);return(node.name);}
function stringifyArguments(params){const result=[];for(const param of params){if(param.type==='Identifier')
result.push(param.name);else if(param.type==='RestElement'&&param.argument.type==='Identifier')
result.push('...'+param.argument.name);else
console.error('Error: unexpected function parameter type: '+param.type);}
return'('+result.join(', ')+')';}
function addOutlineItem(item){outlineChunk.push(item);if(textCursor.offset()-lastReportedOffset<chunkSize)
return;postMessage({chunk:outlineChunk,isLastChunk:false});outlineChunk=[];lastReportedOffset=textCursor.offset();}};;FormatterWorker.RelaxedJSONParser={};FormatterWorker.RelaxedJSONParser.States={ExpectKey:'ExpectKey',ExpectValue:'ExpectValue'};FormatterWorker.RelaxedJSONParser.Keywords={'NaN':NaN,'true':true,'false':false,'Infinity':Infinity,'undefined':undefined,'null':null};FormatterWorker.RelaxedJSONParser.parse=function(content){const Keywords=FormatterWorker.RelaxedJSONParser.Keywords;const States=FormatterWorker.RelaxedJSONParser.States;content='('+content+')';let root;try{root=acorn.parse(content,{});}catch(e){return null;}
const walker=new FormatterWorker.ESTreeWalker(beforeVisit,afterVisit);const rootTip=[];const stack=[];let stackData=({key:0,tip:rootTip,state:States.ExpectValue,parentIsArray:true});walker.setWalkNulls(true);let hasExpression=false;walker.walk(root);if(hasExpression)
return null;return rootTip.length?rootTip[0]:null;function pushStack(newStack){stack.push(stackData);stackData=newStack;}
function popStack(){stackData=stack.pop();}
function applyValue(value){stackData.tip[stackData.key]=value;if(stackData.parentIsArray)
stackData.key++;else
stackData.state=null;}
function beforeVisit(node){switch(node.type){case'ObjectExpression':{const newTip={};applyValue(newTip);pushStack(({key:null,tip:newTip,state:null,parentIsArray:false}));break;}
case'ArrayExpression':{const newTip=[];applyValue(newTip);pushStack(({key:0,tip:newTip,state:States.ExpectValue,parentIsArray:true}));break;}
case'Property':stackData.state=States.ExpectKey;break;case'Literal':if(stackData.state===States.ExpectKey){stackData.key=node.value;stackData.state=States.ExpectValue;}else if(stackData.state===States.ExpectValue){applyValue(extractValue(node));return FormatterWorker.ESTreeWalker.SkipSubtree;}
break;case'Identifier':if(stackData.state===States.ExpectKey){stackData.key=(node.name);stackData.state=States.ExpectValue;}else if(stackData.state===States.ExpectValue){applyValue(extractValue(node));return FormatterWorker.ESTreeWalker.SkipSubtree;}
break;case'UnaryExpression':if(stackData.state===States.ExpectValue){applyValue(extractValue(node));return FormatterWorker.ESTreeWalker.SkipSubtree;}
break;case'Program':case'ExpressionStatement':break;default:if(stackData.state===States.ExpectValue)
applyValue(extractValue(node));return FormatterWorker.ESTreeWalker.SkipSubtree;}}
function afterVisit(node){if(node.type==='ObjectExpression'||node.type==='ArrayExpression')
popStack();}
function extractValue(node){let isNegative=false;const originalNode=node;let value;if(node.type==='UnaryExpression'&&(node.operator==='-'||node.operator==='+')){if(node.operator==='-')
isNegative=true;node=(node.argument);}
if(node.type==='Literal'){value=node.value;}else if(node.type==='Identifier'&&Keywords.hasOwnProperty(node.name)){value=Keywords[node.name];}else{hasExpression=true;return content.substring(originalNode.start,originalNode.end);}
if(isNegative){if(typeof value!=='number'){hasExpression=true;return content.substring(originalNode.start,originalNode.end);}
value=-(value);}
return value;}};FormatterWorker.RelaxedJSONParser.Context;;;;if(!self.Runtime)
self.importScripts('Runtime.js');Runtime.startWorker('formatter_worker');const allDescriptors=[];let applicationDescriptor;const _loadedScripts={};for(const k of[]){}
(function(){const baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();const REMOTE_MODULE_FALLBACK_REVISION='@010ddcfda246975d194964ccf20038ebbdec6084';var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(let i=0;i<descriptors.length;++i)
this._registerModule(descriptors[i]);}
static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){const xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE)
return;const status=/^HTTP\/1.1 404/.test(e.target.response)?404:xhr.status;if([0,200,304].indexOf(status)===-1)
reject(new Error('While loading from url '+url+' server responded with a status of '+status));else
fulfill(e.target.response);}
xhr.send(null);}}
static loadResourcePromiseWithFallback(url){return Runtime.loadResourcePromise(url).catch(err=>{const urlWithFallbackVersion=url.replace(/@[0-9a-f]{40}/,REMOTE_MODULE_FALLBACK_REVISION);if(urlWithFallbackVersion===url||!url.includes('audits2_worker_module'))
throw err;return Runtime.loadResourcePromise(urlWithFallbackVersion);});}
static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1)
return path;const normalizedSegments=[];const segments=path.split('/');for(let i=0;i<segments.length;i++){const segment=segments[i];if(segment==='.')
continue;else if(segment==='..')
normalizedSegments.pop();else if(segment)
normalizedSegments.push(segment);}
let normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/')
return normalizedPath;if(path[0]==='/'&&normalizedPath)
normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..'))
normalizedPath=normalizedPath+'/';return normalizedPath;}
static _loadScriptsPromise(scriptNames,base){const promises=[];const urls=[];const sources=new Array(scriptNames.length);let scriptToEval=0;for(let i=0;i<scriptNames.length;++i){const scriptName=scriptNames[i];let sourceURL=(base||self._importScriptPathPrefix)+scriptName;const schemaIndex=sourceURL.indexOf('://')+3;let pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1)
pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL])
continue;urls.push(sourceURL);const loadResourcePromise=base?Runtime.loadResourcePromiseWithFallback(sourceURL):Runtime.loadResourcePromise(sourceURL);promises.push(loadResourcePromise.then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));}
return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}}
function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;}
self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}}
static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;}
const sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}}
static async appStarted(){return Runtime._appStartedPromise;}
static async startApplication(appName){console.timeStamp('Runtime.startApplication');const allDescriptorsByName={};for(let i=0;i<allDescriptors.length;++i){const d=allDescriptors[i];allDescriptorsByName[d['name']]=d;}
if(!applicationDescriptor){let data=await Runtime.loadResourcePromise(appName+'.json');applicationDescriptor=JSON.parse(data);let descriptor=applicationDescriptor;while(descriptor.extends){data=await Runtime.loadResourcePromise(descriptor.extends+'.json');descriptor=JSON.parse(data);applicationDescriptor.modules=descriptor.modules.concat(applicationDescriptor.modules);}}
const configuration=applicationDescriptor.modules;const moduleJSONPromises=[];const coreModuleNames=[];for(let i=0;i<configuration.length;++i){const descriptor=configuration[i];const name=descriptor['name'];const moduleJSON=allDescriptorsByName[name];if(moduleJSON)
moduleJSONPromises.push(Promise.resolve(moduleJSON));else
moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart')
coreModuleNames.push(name);}
const moduleDescriptors=await Promise.all(moduleJSONPromises);for(let i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';}
self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames)
await self.runtime._loadAutoStartModules(coreModuleNames);Runtime._appStartedPromiseCallback();}
static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}}
static queryParam(name){return Runtime._queryParamsObject.get(name);}
static queryParamsString(){return location.search;}
static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}}
static _assert(value,message){if(value)
return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);}
static setPlatform(platform){Runtime._platform=platform;}
static _isDescriptorEnabled(descriptor){const activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*')
return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1)))
return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment))
return false;const condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition))
return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1)))
return false;return true;}
static resolveSourceURL(path){let sourceURL=self.location.href;if(self.location.search)
sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';}
static setL10nCallback(localizationFunction){Runtime._l10nCallback=localizationFunction;}
useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend'))
Runtime._remoteBase+='debug/';}
_registerModule(descriptor){const module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;}
loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();}
_loadAutoStartModules(moduleNames){const promises=[];for(let i=0;i<moduleNames.length;++i)
promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);}
_checkExtensionApplicability(extension,predicate){if(!predicate)
return false;const contextTypes=extension.descriptor().contextTypes;if(!contextTypes)
return true;for(let i=0;i<contextTypes.length;++i){const contextType=this._resolve(contextTypes[i]);const isMatching=!!contextType&&predicate(contextType);if(isMatching)
return true;}
return false;}
isExtensionApplicableToContext(extension,context){if(!context)
return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}}
isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes)
return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}}
extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type)
return false;if(!extension.enabled())
return false;return!context||extension.isApplicable(context);}
function orderComparator(extension1,extension2){const order1=extension1.descriptor()['order']||0;const order2=extension2.descriptor()['order']||0;return order1-order2;}
function titleComparator(extension1,extension2){const title1=extension1.title()||'';const title2=extension2.title()||'';return title1.localeCompare(title2);}}
extension(type,context){return this.extensions(type,context)[0]||null;}
allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));}
_resolve(typeName){if(!this._cachedTypeClasses[typeName]){const path=typeName.split('.');let object=self;for(let i=0;object&&(i<path.length);++i)
object=object[path[i]];if(object)
this._cachedTypeClasses[typeName]=(object);}
return this._cachedTypeClasses[typeName]||null;}
sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction&&Object.getOwnPropertySymbols(constructorFunction).includes(Runtime._instanceSymbol))
return constructorFunction[Runtime._instanceSymbol];const instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject=new URLSearchParams(Runtime.queryParamsString());Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();const extensions=(descriptor.extensions);for(let i=0;extensions&&i<extensions.length;++i){const extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);}
this._loadedForTest=false;}
name(){return this._name;}
enabled(){return Runtime._isDescriptorEnabled(this._descriptor);}
resource(name){const fullName=this._name+'/'+name;const content=Runtime.cachedResources[fullName];if(!content)
throw new Error(fullName+' not preloaded. Check module.json');return content;}
_loadPromise(){if(!this.enabled())
return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise)
return this._pendingLoadPromise;const dependencies=this._descriptor.dependencies;const dependencyPromises=[];for(let i=0;dependencies&&i<dependencies.length;++i)
dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;}
_loadResources(){const resources=this._descriptor['resources'];if(!resources||!resources.length)
return Promise.resolve();const promises=[];for(let i=0;i<resources.length;++i){const url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));}
return Promise.all(promises).then(undefined);}
_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length)
return Promise.resolve();const specialCases={'sdk':'SDK','js_sdk':'JSSDK','browser_sdk':'BrowserSDK','ui':'UI','object_ui':'ObjectUI','javascript_metadata':'JavaScriptMetadata','perf_ui':'PerfUI','har_importer':'HARImporter','sdk_test_runner':'SDKTestRunner','cpu_profiler_test_runner':'CPUProfilerTestRunner'};const namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());}
_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);}
_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;}
substituteURL(value){const base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;}
descriptor(){return this._descriptor;}
module(){return this._module;}
enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());}
_typeClass(){if(!this._hasTypeClass)
return null;return this._module._manager._resolve(this._type.substring(1));}
isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);}
instance(){return this._module._loadPromise().then(this._createInstance.bind(this));}
canInstantiate(){return!!(this._className||this._factoryName);}
_createInstance(){const className=this._className||this._factoryName;if(!className)
throw new Error('Could not instantiate extension with no class');const constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function))
throw new Error('Could not instantiate: '+className);if(this._className)
return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);}
title(){const title=this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];if(title&&Runtime._l10nCallback)
return Runtime._l10nCallback(title);return title;}
hasContextType(contextType){const contextTypes=this.descriptor().contextTypes;if(!contextTypes)
return false;for(let i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i]))
return true;}
return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
allConfigurableExperiments(){const result=[];for(let i=0;i<this._experiments.length;i++){const experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name])
result.push(experiment);}
return result;}
supportEnabled(){return this._supportEnabled;}
_setExperimentsSetting(value){if(!self.localStorage)
return;self.localStorage['experiments']=JSON.stringify(value);}
register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));}
isEnabled(experimentName){this._checkExperiment(experimentName);if(Runtime._experimentsSetting()[experimentName]===false)
return false;if(this._enabledTransiently[experimentName])
return true;if(!this.supportEnabled())
return false;return!!Runtime._experimentsSetting()[experimentName];}
setEnabled(experimentName,enabled){this._checkExperiment(experimentName);const experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);}
setDefaultExperiments(experimentNames){for(let i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}}
enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;}
clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
cleanUpStaleExperiments(){const experimentsSetting=Runtime._experimentsSetting();const cleanedUpExperimentSetting={};for(let i=0;i<this._experiments.length;++i){const experimentName=this._experiments[i].name;if(experimentsSetting[experimentName])
cleanedUpExperimentSetting[experimentName]=true;}
this._setExperimentsSetting(cleanedUpExperimentSetting);}
_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;}
isEnabled(){return this._experiments.isEnabled(this.name);}
setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._appStartedPromiseCallback;Runtime._appStartedPromise=new Promise(fulfil=>Runtime._appStartedPromiseCallback=fulfil);Runtime._l10nCallback;Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){const versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch)
Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){}
ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;allDescriptors.push(...[{"dependencies":[],"name":"heap_snapshot_model"},{"dependencies":[],"name":"platform"},{"dependencies":["heap_snapshot_model","platform","common"],"name":"heap_snapshot_worker"},{"dependencies":["platform"],"name":"text_utils"},{"dependencies":["text_utils","platform"],"name":"common"}]);applicationDescriptor={"has_html":false,"modules":[{"type":"autostart","name":"heap_snapshot_model"},{"type":"autostart","name":"platform"},{"type":"autostart","name":"heap_snapshot_worker"},{"type":"autostart","name":"text_utils"},{"type":"autostart","name":"common"}]}
self['HeapSnapshotModel']=self['HeapSnapshotModel']||{};HeapSnapshotModel.HeapSnapshotProgressEvent={Update:'ProgressUpdate',BrokenSnapshot:'BrokenSnapshot'};HeapSnapshotModel.baseSystemDistance=100000000;HeapSnapshotModel.AllocationNodeCallers=class{constructor(nodesWithSingleCaller,branchingCallers){this.nodesWithSingleCaller=nodesWithSingleCaller;this.branchingCallers=branchingCallers;}};HeapSnapshotModel.SerializedAllocationNode=class{constructor(nodeId,functionName,scriptName,scriptId,line,column,count,size,liveCount,liveSize,hasChildren){this.id=nodeId;this.name=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;this.count=count;this.size=size;this.liveCount=liveCount;this.liveSize=liveSize;this.hasChildren=hasChildren;}};HeapSnapshotModel.AllocationStackFrame=class{constructor(functionName,scriptName,scriptId,line,column){this.functionName=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;}};HeapSnapshotModel.Node=class{constructor(id,name,distance,nodeIndex,retainedSize,selfSize,type){this.id=id;this.name=name;this.distance=distance;this.nodeIndex=nodeIndex;this.retainedSize=retainedSize;this.selfSize=selfSize;this.type=type;this.canBeQueried=false;this.detachedDOMTreeNode=false;}};HeapSnapshotModel.Edge=class{constructor(name,node,type,edgeIndex){this.name=name;this.node=node;this.type=type;this.edgeIndex=edgeIndex;}};HeapSnapshotModel.Aggregate=class{constructor(){this.count;this.distance;this.self;this.maxRet;this.type;this.name;this.idxs;}};HeapSnapshotModel.AggregateForDiff=class{constructor(){this.indexes=[];this.ids=[];this.selfSizes=[];}};HeapSnapshotModel.Diff=class{constructor(){this.addedCount=0;this.removedCount=0;this.addedSize=0;this.removedSize=0;this.deletedIndexes=[];this.addedIndexes=[];}};HeapSnapshotModel.DiffForClass=class{constructor(){this.addedCount;this.removedCount;this.addedSize;this.removedSize;this.deletedIndexes;this.addedIndexes;this.countDelta;this.sizeDelta;}};HeapSnapshotModel.ComparatorConfig=class{constructor(){this.fieldName1;this.ascending1;this.fieldName2;this.ascending2;}};HeapSnapshotModel.WorkerCommand=class{constructor(){this.callId;this.disposition;this.objectId;this.newObjectId;this.methodName;this.methodArguments;this.source;}};HeapSnapshotModel.ItemsRange=class{constructor(startPosition,endPosition,totalLength,items){this.startPosition=startPosition;this.endPosition=endPosition;this.totalLength=totalLength;this.items=items;}};HeapSnapshotModel.StaticData=class{constructor(nodeCount,rootNodeIndex,totalSize,maxJSObjectId){this.nodeCount=nodeCount;this.rootNodeIndex=rootNodeIndex;this.totalSize=totalSize;this.maxJSObjectId=maxJSObjectId;}};HeapSnapshotModel.Statistics=class{constructor(){this.total;this.v8heap;this.native;this.code;this.jsArrays;this.strings;this.system;}};HeapSnapshotModel.NodeFilter=class{constructor(minNodeId,maxNodeId){this.minNodeId=minNodeId;this.maxNodeId=maxNodeId;this.allocationNodeId;}
equals(o){return this.minNodeId===o.minNodeId&&this.maxNodeId===o.maxNodeId&&this.allocationNodeId===o.allocationNodeId;}};HeapSnapshotModel.SearchConfig=class{constructor(query,caseSensitive,isRegex,shouldJump,jumpBackward){this.query=query;this.caseSensitive=caseSensitive;this.isRegex=isRegex;this.shouldJump=shouldJump;this.jumpBackward=jumpBackward;}};HeapSnapshotModel.Samples=class{constructor(timestamps,lastAssignedIds,sizes){this.timestamps=timestamps;this.lastAssignedIds=lastAssignedIds;this.sizes=sizes;}};HeapSnapshotModel.Location=class{constructor(scriptId,lineNumber,columnNumber){this.scriptId=scriptId;this.lineNumber=lineNumber;this.columnNumber=columnNumber;}};;self['Platform']=self['Platform']||{};let ArrayLike;function mod(m,n){return((m%n)+n)%n;}
String.prototype.findAll=function(string){const matches=[];let i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);}
return matches;};String.prototype.reverse=function(){return this.split('').reverse().join('');};String.prototype.replaceControlCharacters=function(){return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,'<27>');};String.prototype.isWhitespace=function(){return/^\s*$/.test(this);};String.prototype.computeLineEndings=function(){const endings=this.findAll('\n');endings.push(this.length);return endings;};String.prototype.escapeCharacters=function(chars){let foundChar=false;for(let i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}}
if(!foundChar)
return String(this);let result='';for(let i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1)
result+='\\';result+=this.charAt(i);}
return result;};String.regexSpecialCharacters=function(){return'^[]{}()\\.^$*+?|-,';};String.prototype.escapeForRegExp=function(){return this.escapeCharacters(String.regexSpecialCharacters());};String.filterRegex=function(query){const toEscape=String.regexSpecialCharacters();let regexString='';for(let i=0;i<query.length;++i){let c=query.charAt(i);if(toEscape.indexOf(c)!==-1)
c='\\'+c;if(i)
regexString+='[^\\0'+c+']*';regexString+=c;}
return new RegExp(regexString,'i');};String.escapeInvalidUnicodeCharacters=function(text){if(!String._invalidCharactersRegExp){let invalidCharacters='';for(let i=0xfffe;i<=0x10ffff;i+=0x10000)
invalidCharacters+=String.fromCodePoint(i,i+1);String._invalidCharactersRegExp=new RegExp(`[${invalidCharacters}\uD800-\uDFFF\uFDD0-\uFDEF]`,'gu');}
let result='';let lastPos=0;while(true){const match=String._invalidCharactersRegExp.exec(text);if(!match)
break;result+=text.substring(lastPos,match.index)+'\\u'+text.charCodeAt(match.index).toString(16);if(match.index+1<String._invalidCharactersRegExp.lastIndex)
result+='\\u'+text.charCodeAt(match.index+1).toString(16);lastPos=String._invalidCharactersRegExp.lastIndex;}
return result+text.substring(lastPos);};String.prototype.escapeHTML=function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');};String.prototype.unescapeHTML=function(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&#58;/g,':').replace(/&quot;/g,'"').replace(/&#60;/g,'<').replace(/&#62;/g,'>').replace(/&amp;/g,'&');};String.prototype.collapseWhitespace=function(){return this.replace(/[\s\xA0]+/g,' ');};String.prototype.trimMiddle=function(maxLength){if(this.length<=maxLength)
return String(this);let leftHalf=maxLength>>1;let rightHalf=maxLength-leftHalf-1;if(this.codePointAt(this.length-rightHalf-1)>=0x10000){--rightHalf;++leftHalf;}
if(leftHalf>0&&this.codePointAt(leftHalf-1)>=0x10000)
--leftHalf;return this.substr(0,leftHalf)+'\u2026'+this.substr(this.length-rightHalf,rightHalf);};String.prototype.trimEnd=function(maxLength){if(this.length<=maxLength)
return String(this);return this.substr(0,maxLength-1)+'\u2026';};String.prototype.trimURL=function(baseURLDomain){let result=this.replace(/^(https|http|file):\/\//i,'');if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase()))
result=result.substr(baseURLDomain.length);}
return result;};String.prototype.toTitleCase=function(){return this.substring(0,1).toUpperCase()+this.substring(1);};String.prototype.compareTo=function(other){if(this>other)
return 1;if(this<other)
return-1;return 0;};String.prototype.removeURLFragment=function(){let fragmentIndex=this.indexOf('#');if(fragmentIndex===-1)
fragmentIndex=this.length;return this.substring(0,fragmentIndex);};String.hashCode=function(string){if(!string)
return 0;const p=((1<<30)*4-5);const z=0x5033d967;const z2=0x59d2f15d;let s=0;let zi=1;for(let i=0;i<string.length;i++){const xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;}
s=(s+zi*(p-1))%p;return Math.abs(s|0);};String.isDigitAt=function(string,index){const c=string.charCodeAt(index);return(48<=c&&c<=57);};String.prototype.toBase64=function(){function encodeBits(b){return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;}
const encoder=new TextEncoder();const data=encoder.encode(this.toString());const n=data.length;let encoded='';if(n===0)
return encoded;let shift;let v=0;for(let i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}}
if(shift===0)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);else if(shift===1)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);return encoded;};String.naturalOrderComparator=function(a,b){const chunk=/^\d+|^\D+/;let chunka,chunkb,anum,bnum;while(1){if(a){if(!b)
return 1;}else{if(b)
return-1;else
return 0;}
chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum)
return-1;if(bnum&&!anum)
return 1;if(anum&&bnum){const diff=chunka-chunkb;if(diff)
return diff;if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb)
return chunka.length-chunkb.length;else
return chunkb.length-chunka.length;}}else if(chunka!==chunkb){return(chunka<chunkb)?-1:1;}
a=a.substring(chunka.length);b=b.substring(chunkb.length);}};String.caseInsensetiveComparator=function(a,b){a=a.toUpperCase();b=b.toUpperCase();if(a===b)
return 0;return a>b?1:-1;};Number.constrain=function(num,min,max){if(num<min)
num=min;else if(num>max)
num=max;return num;};Number.gcd=function(a,b){if(b===0)
return a;else
return Number.gcd(b,a%b);};Number.toFixedIfFloating=function(value){if(!value||isNaN(value))
return value;const number=Number(value);return number%1?number.toFixed(3):String(number);};Date.prototype.isValid=function(){return!isNaN(this.getTime());};Date.prototype.toISO8601Compact=function(){function leadZero(x){return(x>9?'':'0')+x;}
return this.getFullYear()+leadZero(this.getMonth()+1)+leadZero(this.getDate())+'T'+
leadZero(this.getHours())+leadZero(this.getMinutes())+leadZero(this.getSeconds());};Object.defineProperty(Array.prototype,'remove',{value:function(value,firstOnly){let index=this.indexOf(value);if(index===-1)
return false;if(firstOnly){this.splice(index,1);return true;}
for(let i=index+1,n=this.length;i<n;++i){if(this[i]!==value)
this[index++]=this[i];}
this.length=index;return true;}});Object.defineProperty(Array.prototype,'pushAll',{value:function(array){for(let i=0;i<array.length;++i)
this.push(array[i]);}});Object.defineProperty(Array.prototype,'rotate',{value:function(index){const result=[];for(let i=index;i<index+this.length;++i)
result.push(this[i%this.length]);return result;}});Object.defineProperty(Array.prototype,'sortNumbers',{value:function(){function numericComparator(a,b){return a-b;}
this.sort(numericComparator);}});Object.defineProperty(Uint32Array.prototype,'sort',{value:Array.prototype.sort});(function(){const partition={value:function(comparator,left,right,pivotIndex){function swap(array,i1,i2){const temp=array[i1];array[i1]=array[i2];array[i2]=temp;}
const pivotValue=this[pivotIndex];swap(this,right,pivotIndex);let storeIndex=left;for(let i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}}
swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,'partition',partition);Object.defineProperty(Uint32Array.prototype,'partition',partition);const sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight){function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight){if(right<=left)
return;const pivotIndex=Math.floor(Math.random()*(right-left))+left;const pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex)
quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);if(pivotNewIndex<sortWindowRight)
quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);}
if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound)
this.sort(comparator);else
quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);return this;}};Object.defineProperty(Array.prototype,'sortRange',sortRange);Object.defineProperty(Uint32Array.prototype,'sortRange',sortRange);})();Object.defineProperty(Array.prototype,'stableSort',{value:function(comparator){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;const indices=new Array(this.length);for(let i=0;i<this.length;++i)
indices[i]=i;const self=this;function indexComparator(a,b){const result=comparator(self[a],self[b]);return result?result:a-b;}
indices.sort(indexComparator);for(let i=0;i<this.length;++i){if(indices[i]<0||i===indices[i])
continue;let cyclical=i;const saved=this[i];while(true){const next=indices[cyclical];indices[cyclical]=-1;if(next===i){this[cyclical]=saved;break;}else{this[cyclical]=this[next];cyclical=next;}}}
return this;}});Object.defineProperty(Array.prototype,'qselect',{value:function(k,comparator){if(k<0||k>=this.length)
return;if(!comparator){comparator=function(a,b){return a-b;};}
let low=0;let high=this.length-1;for(;;){const pivotPosition=this.partition(comparator,low,high,Math.floor((high+low)/2));if(pivotPosition===k)
return this[k];else if(pivotPosition>k)
high=pivotPosition-1;else
low=pivotPosition+1;}}});Object.defineProperty(Array.prototype,'lowerBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Array.prototype,'upperBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>=0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Uint32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Int32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Int32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,'binaryIndexOf',{value:function(value,comparator){const index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,'select',{value:function(field){const result=new Array(this.length);for(let i=0;i<this.length;++i)
result[i]=this[i][field];return result;}});Object.defineProperty(Array.prototype,'peekLast',{value:function(){return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect){const result=[];let i=0;let j=0;while(i<array1.length&&j<array2.length){const compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue)
result.push(compareValue<=0?array1[i]:array2[j]);if(compareValue<=0)
i++;if(compareValue>=0)
j++;}
if(mergeNotIntersect){while(i<array1.length)
result.push(array1[i++]);while(j<array2.length)
result.push(array2[j++]);}
return result;}
Object.defineProperty(Array.prototype,'intersectOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,'mergeOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg){return String.vsprintf(format,Array.prototype.slice.call(arguments,1));};String.tokenizeFormatString=function(format,formatters){const tokens=[];function addStringToken(str){if(!str)
return;if(tokens.length&&tokens[tokens.length-1].type==='string')
tokens[tokens.length-1].value+=str;else
tokens.push({type:'string',value:str});}
function addSpecifierToken(specifier,precision,substitutionIndex){tokens.push({type:'specifier',specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});}
function addAnsiColor(code){const types={3:'color',9:'colorLight',4:'bgColor',10:'bgColorLight'};const colorCodes=['black','red','green','yellow','blue','magenta','cyan','lightGray','','default'];const colorCodesLight=['darkGray','lightRed','lightGreen','lightYellow','lightBlue','lightMagenta','lightCyan','white',''];const colors={color:colorCodes,colorLight:colorCodesLight,bgColor:colorCodes,bgColorLight:colorCodesLight};const type=types[Math.floor(code/10)];if(!type)
return;const color=colors[type][code%10];if(!color)
return;tokens.push({type:'specifier',specifier:'c',value:{description:(type.startsWith('bg')?'background : ':'color: ')+color}});}
let textStart=0;let substitutionIndex=0;const re=new RegExp(`%%|%(?:(\\d+)\\$)?(?:\\.(\\d*))?([${Object.keys(formatters).join('')}])|\\u001b\\[(\\d+)m`,'g');for(let match=re.exec(format);!!match;match=re.exec(format)){const matchStart=match.index;if(matchStart>textStart)
addStringToken(format.substring(textStart,matchStart));if(match[0]==='%%'){addStringToken('%');}else if(match[0].startsWith('%')){const[_,substitionString,precisionString,specifierString]=match;if(substitionString&&Number(substitionString)>0)
substitutionIndex=Number(substitionString)-1;const precision=precisionString?Number(precisionString):-1;addSpecifierToken(specifierString,precision,substitutionIndex);++substitutionIndex;}else{const code=Number(match[4]);addAnsiColor(code);}
textStart=matchStart+match[0].length;}
addStringToken(format.substring(textStart));return tokens;};String.standardFormatters={d:function(substitution){return!isNaN(substitution)?substitution:0;},f:function(substitution,token){if(substitution&&token.precision>-1)
substitution=substitution.toFixed(token.precision);return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution){return substitution;}};String.vsprintf=function(format,substitutions){return String.format(format,substitutions,String.standardFormatters,'',function(a,b){return a+b;}).formattedResult;};String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat){if(!format||((!substitutions||!substitutions.length)&&format.search(/\u001b\[(\d+)m/)===-1))
return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName(){return'String.format("'+format+'", "'+Array.prototype.join.call(substitutions,'", "')+'")';}
function warn(msg){console.warn(prettyFunctionName()+': '+msg);}
function error(msg){console.error(prettyFunctionName()+': '+msg);}
let result=initialValue;const tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);const usedSubstitutionIndexes={};for(let i=0;i<tokens.length;++i){const token=tokens[i];if(token.type==='string'){result=append(result,token.value);continue;}
if(token.type!=='specifier'){error('Unknown token type "'+token.type+'" found.');continue;}
if(!token.value&&token.substitutionIndex>=substitutions.length){error('not enough substitution arguments. Had '+substitutions.length+' but needed '+
(token.substitutionIndex+1)+', so substitution was skipped.');result=append(result,'%'+(token.precision>-1?token.precision:'')+token.specifier);continue;}
if(!token.value)
usedSubstitutionIndexes[token.substitutionIndex]=true;if(!(token.specifier in formatters)){warn('unsupported format character \u201C'+token.specifier+'\u201D. Treating as a string.');result=append(result,token.value?'':substitutions[token.substitutionIndex]);continue;}
result=append(result,formatters[token.specifier](token.value||substitutions[token.substitutionIndex],token));}
const unusedSubstitutions=[];for(let i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes)
continue;unusedSubstitutions.push(substitutions[i]);}
return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};};function createSearchRegex(query,caseSensitive,isRegex){const regexFlags=caseSensitive?'g':'gi';let regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}}
if(!regexObject)
regexObject=createPlainTextSearchRegex(query,regexFlags);return regexObject;}
function createPlainTextSearchRegex(query,flags){const regexSpecialCharacters=String.regexSpecialCharacters();let regex='';for(let i=0;i<query.length;++i){const c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1)
regex+='\\';regex+=c;}
return new RegExp(regex,flags||'');}
function countRegexMatches(regex,content){let text=content;let result=0;let match;while(text&&(match=regex.exec(text))){if(match[0].length>0)
++result;text=text.substring(match.index+1);}
return result;}
function spacesPadding(spacesCount){return'\u00a0'.repeat(spacesCount);}
function numberToStringWithSpacesPadding(value,symbolsCount){const numberString=value.toString();const paddingLength=Math.max(0,symbolsCount-numberString.length);return spacesPadding(paddingLength)+numberString;}
Set.prototype.valuesArray=function(){return Array.from(this.values());};Set.prototype.firstValue=function(){if(!this.size)
return null;return this.values().next().value;};Set.prototype.addAll=function(iterable){for(const e of iterable)
this.add(e);};Set.prototype.containsAll=function(iterable){for(const e of iterable){if(!this.has(e))
return false;}
return true;};Map.prototype.remove=function(key){const value=this.get(key);this.delete(key);return value;};Map.prototype.valuesArray=function(){return Array.from(this.values());};Map.prototype.keysArray=function(){return Array.from(this.keys());};Map.prototype.inverse=function(){const result=new Multimap();for(const key of this.keys()){const value=this.get(key);result.set(value,key);}
return result;};var Multimap=function(){this._map=new Map();};Multimap.prototype={set:function(key,value){let set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);}
set.add(value);},get:function(key){return this._map.get(key)||new Set();},has:function(key){return this._map.has(key);},hasValue:function(key,value){const set=this._map.get(key);if(!set)
return false;return set.has(value);},get size(){return this._map.size;},delete:function(key,value){const values=this.get(key);if(!values)
return false;const result=values.delete(value);if(!values.size)
this._map.delete(key);return result;},deleteAll:function(key){this._map.delete(key);},keysArray:function(){return this._map.keysArray();},valuesArray:function(){const result=[];const keys=this.keysArray();for(let i=0;i<keys.length;++i)
result.pushAll(this.get(keys[i]).valuesArray());return result;},clear:function(){this._map.clear();}};function loadXHR(url){return new Promise(load);function load(successCallback,failureCallback){function onReadyStateChanged(){if(xhr.readyState!==XMLHttpRequest.DONE)
return;if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;}
xhr.onreadystatechange=null;successCallback(xhr.responseText);}
const xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open('GET',url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}}
function suppressUnused(value){}
self.setImmediate=function(callback){const args=[...arguments].slice(1);Promise.resolve().then(()=>callback(...args));return 0;};Promise.prototype.spread=function(callback){return this.then(spreadPromise);function spreadPromise(arg){return callback.apply(null,arg);}};Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});};Map.prototype.diff=function(other,isEqual){const leftKeys=this.keysArray();const rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);const removed=[];const added=[];const equal=[];let leftIndex=0;let rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){const leftKey=leftKeys[leftIndex];const rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;}
if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;}
added.push(other.get(rightKey));++rightIndex;}
while(leftIndex<leftKeys.length){const leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));}
while(rightIndex<rightKeys.length){const rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));}
return{added:added,removed:removed,equal:equal};};function runOnWindowLoad(callback){function windowLoaded(){self.removeEventListener('DOMContentLoaded',windowLoaded,false);callback();}
if(document.readyState==='complete'||document.readyState==='interactive')
callback();else
self.addEventListener('DOMContentLoaded',windowLoaded,false);}
const _singletonSymbol=Symbol('singleton');function singleton(constructorFunction){if(_singletonSymbol in constructorFunction)
return constructorFunction[_singletonSymbol];const instance=new constructorFunction();constructorFunction[_singletonSymbol]=instance;return instance;}
function base64ToSize(content){if(!content)
return 0;let size=content.length*3/4;if(content[content.length-1]==='=')
size--;if(content.length>1&&content[content.length-2]==='=')
size--;return size;};self['TextUtils']=self['TextUtils']||{};TextUtils.Text=class{constructor(value){this._value=value;}
lineEndings(){if(!this._lineEndings)
this._lineEndings=this._value.computeLineEndings();return this._lineEndings;}
value(){return this._value;}
lineCount(){const lineEndings=this.lineEndings();return lineEndings.length;}
offsetFromPosition(lineNumber,columnNumber){return(lineNumber?this.lineEndings()[lineNumber-1]+1:0)+columnNumber;}
positionFromOffset(offset){const lineEndings=this.lineEndings();const lineNumber=lineEndings.lowerBound(offset);return{lineNumber:lineNumber,columnNumber:offset-(lineNumber&&(lineEndings[lineNumber-1]+1))};}
lineAt(lineNumber){const lineEndings=this.lineEndings();const lineStart=lineNumber>0?lineEndings[lineNumber-1]+1:0;const lineEnd=lineEndings[lineNumber];let lineContent=this._value.substring(lineStart,lineEnd);if(lineContent.length>0&&lineContent.charAt(lineContent.length-1)==='\r')
lineContent=lineContent.substring(0,lineContent.length-1);return lineContent;}
toSourceRange(range){const start=this.offsetFromPosition(range.startLine,range.startColumn);const end=this.offsetFromPosition(range.endLine,range.endColumn);return new TextUtils.SourceRange(start,end-start);}
toTextRange(sourceRange){const cursor=new TextUtils.TextCursor(this.lineEndings());const result=TextUtils.TextRange.createFromLocation(0,0);cursor.resetTo(sourceRange.offset);result.startLine=cursor.lineNumber();result.startColumn=cursor.columnNumber();cursor.advance(sourceRange.offset+sourceRange.length);result.endLine=cursor.lineNumber();result.endColumn=cursor.columnNumber();return result;}
replaceRange(range,replacement){const sourceRange=this.toSourceRange(range);return this._value.substring(0,sourceRange.offset)+replacement+
this._value.substring(sourceRange.offset+sourceRange.length);}
extract(range){const sourceRange=this.toSourceRange(range);return this._value.substr(sourceRange.offset,sourceRange.length);}};TextUtils.Text.Position;TextUtils.TextCursor=class{constructor(lineEndings){this._lineEndings=lineEndings;this._offset=0;this._lineNumber=0;this._columnNumber=0;}
advance(offset){this._offset=offset;while(this._lineNumber<this._lineEndings.length&&this._lineEndings[this._lineNumber]<this._offset)
++this._lineNumber;this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
offset(){return this._offset;}
resetTo(offset){this._offset=offset;this._lineNumber=this._lineEndings.lowerBound(offset);this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
lineNumber(){return this._lineNumber;}
columnNumber(){return this._columnNumber;}};;TextUtils.TextUtils={isStopChar:function(char){return(char>' '&&char<'0')||(char>'9'&&char<'A')||(char>'Z'&&char<'_')||(char>'_'&&char<'a')||(char>'z'&&char<='~');},isWordChar:function(char){return!TextUtils.TextUtils.isStopChar(char)&&!TextUtils.TextUtils.isSpaceChar(char);},isSpaceChar:function(char){return TextUtils.TextUtils._SpaceCharRegex.test(char);},isWord:function(word){for(let i=0;i<word.length;++i){if(!TextUtils.TextUtils.isWordChar(word.charAt(i)))
return false;}
return true;},isOpeningBraceChar:function(char){return char==='('||char==='{';},isClosingBraceChar:function(char){return char===')'||char==='}';},isBraceChar:function(char){return TextUtils.TextUtils.isOpeningBraceChar(char)||TextUtils.TextUtils.isClosingBraceChar(char);},textToWords:function(text,isWordChar,wordCallback){let startWord=-1;for(let i=0;i<text.length;++i){if(!isWordChar(text.charAt(i))){if(startWord!==-1)
wordCallback(text.substring(startWord,i));startWord=-1;}else if(startWord===-1){startWord=i;}}
if(startWord!==-1)
wordCallback(text.substring(startWord));},lineIndent:function(line){let indentation=0;while(indentation<line.length&&TextUtils.TextUtils.isSpaceChar(line.charAt(indentation)))
++indentation;return line.substr(0,indentation);},isUpperCase:function(text){return text===text.toUpperCase();},isLowerCase:function(text){return text===text.toLowerCase();},splitStringByRegexes(text,regexes){const matches=[];const globalRegexes=[];for(let i=0;i<regexes.length;i++){const regex=regexes[i];if(!regex.global)
globalRegexes.push(new RegExp(regex.source,regex.flags?regex.flags+'g':'g'));else
globalRegexes.push(regex);}
doSplit(text,0,0);return matches;function doSplit(text,regexIndex,startIndex){if(regexIndex>=globalRegexes.length){matches.push({value:text,position:startIndex,regexIndex:-1,captureGroups:[]});return;}
const regex=globalRegexes[regexIndex];let currentIndex=0;let result;regex.lastIndex=0;while((result=regex.exec(text))!==null){const stringBeforeMatch=text.substring(currentIndex,result.index);if(stringBeforeMatch)
doSplit(stringBeforeMatch,regexIndex+1,startIndex+currentIndex);const match=result[0];matches.push({value:match,position:startIndex+result.index,regexIndex:regexIndex,captureGroups:result.slice(1)});currentIndex=result.index+match.length;}
const stringAfterMatches=text.substring(currentIndex);if(stringAfterMatches)
doSplit(stringAfterMatches,regexIndex+1,startIndex+currentIndex);}}};TextUtils.FilterParser=class{constructor(keys){this._keys=keys;}
static cloneFilter(filter){return{key:filter.key,text:filter.text,regex:filter.regex,negative:filter.negative};}
parse(query){const splitResult=TextUtils.TextUtils.splitStringByRegexes(query,[TextUtils.TextUtils._keyValueFilterRegex,TextUtils.TextUtils._regexFilterRegex,TextUtils.TextUtils._textFilterRegex]);const filters=[];for(let i=0;i<splitResult.length;i++){const regexIndex=splitResult[i].regexIndex;if(regexIndex===-1)
continue;const result=splitResult[i].captureGroups;if(regexIndex===0){if(this._keys.indexOf((result[1]))!==-1)
filters.push({key:result[1],text:result[2],negative:!!result[0]});else
filters.push({text:result[1]+':'+result[2],negative:!!result[0]});}else if(regexIndex===1){try{filters.push({regex:new RegExp(result[1],'i'),negative:!!result[0]});}catch(e){filters.push({text:'/'+result[1]+'/',negative:!!result[0]});}}else if(regexIndex===2){filters.push({text:result[1],negative:!!result[0]});}}
return filters;}};TextUtils.FilterParser.ParsedFilter;TextUtils.TextUtils._keyValueFilterRegex=/(?:^|\s)(\-)?([\w\-]+):([^\s]+)/;TextUtils.TextUtils._regexFilterRegex=/(?:^|\s)(\-)?\/([^\s]+)\//;TextUtils.TextUtils._textFilterRegex=/(?:^|\s)(\-)?([^\s]+)/;TextUtils.TextUtils._SpaceCharRegex=/\s/;TextUtils.TextUtils.Indent={TwoSpaces:' ',FourSpaces:' ',EightSpaces:' ',TabCharacter:'\t'};TextUtils.TextUtils.BalancedJSONTokenizer=class{constructor(callback,findMultiple){this._callback=callback;this._index=0;this._balance=0;this._buffer='';this._findMultiple=findMultiple||false;this._closingDoubleQuoteRegex=/[^\\](?:\\\\)*"/g;}
write(chunk){this._buffer+=chunk;const lastIndex=this._buffer.length;const buffer=this._buffer;let index;for(index=this._index;index<lastIndex;++index){const character=buffer[index];if(character==='"'){this._closingDoubleQuoteRegex.lastIndex=index;if(!this._closingDoubleQuoteRegex.test(buffer))
break;index=this._closingDoubleQuoteRegex.lastIndex-1;}else if(character==='{'){++this._balance;}else if(character==='}'){--this._balance;if(this._balance<0){this._reportBalanced();return false;}
if(!this._balance){this._lastBalancedIndex=index+1;if(!this._findMultiple)
break;}}else if(character===']'&&!this._balance){this._reportBalanced();return false;}}
this._index=index;this._reportBalanced();return true;}
_reportBalanced(){if(!this._lastBalancedIndex)
return;this._callback(this._buffer.slice(0,this._lastBalancedIndex));this._buffer=this._buffer.slice(this._lastBalancedIndex);this._index-=this._lastBalancedIndex;this._lastBalancedIndex=0;}
remainder(){return this._buffer;}};TextUtils.TokenizerFactory=function(){};TextUtils.TokenizerFactory.prototype={createTokenizer(mimeType){}};TextUtils.isMinified=function(text){const kMaxNonMinifiedLength=500;let linesToCheck=10;let lastPosition=0;do{let eolIndex=text.indexOf('\n',lastPosition);if(eolIndex<0)
eolIndex=text.length;if(eolIndex-lastPosition>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#')
return true;lastPosition=eolIndex+1;}while(--linesToCheck>=0&&lastPosition<text.length);linesToCheck=10;lastPosition=text.length;do{let eolIndex=text.lastIndexOf('\n',lastPosition);if(eolIndex<0)
eolIndex=0;if(lastPosition-eolIndex>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#')
return true;lastPosition=eolIndex-1;}while(--linesToCheck>=0&&lastPosition>0);return false;};;TextUtils.TextRange=class{constructor(startLine,startColumn,endLine,endColumn){this.startLine=startLine;this.startColumn=startColumn;this.endLine=endLine;this.endColumn=endColumn;}
static createFromLocation(line,column){return new TextUtils.TextRange(line,column,line,column);}
static fromObject(serializedTextRange){return new TextUtils.TextRange(serializedTextRange.startLine,serializedTextRange.startColumn,serializedTextRange.endLine,serializedTextRange.endColumn);}
static comparator(range1,range2){return range1.compareTo(range2);}
static fromEdit(oldRange,newText){let endLine=oldRange.startLine;let endColumn=oldRange.startColumn+newText.length;const lineEndings=newText.computeLineEndings();if(lineEndings.length>1){endLine=oldRange.startLine+lineEndings.length-1;const len=lineEndings.length;endColumn=lineEndings[len-1]-lineEndings[len-2]-1;}
return new TextUtils.TextRange(oldRange.startLine,oldRange.startColumn,endLine,endColumn);}
isEmpty(){return this.startLine===this.endLine&&this.startColumn===this.endColumn;}
immediatelyPrecedes(range){if(!range)
return false;return this.endLine===range.startLine&&this.endColumn===range.startColumn;}
immediatelyFollows(range){if(!range)
return false;return range.immediatelyPrecedes(this);}
follows(range){return(range.endLine===this.startLine&&range.endColumn<=this.startColumn)||range.endLine<this.startLine;}
get linesCount(){return this.endLine-this.startLine;}
collapseToEnd(){return new TextUtils.TextRange(this.endLine,this.endColumn,this.endLine,this.endColumn);}
collapseToStart(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.startLine,this.startColumn);}
normalize(){if(this.startLine>this.endLine||(this.startLine===this.endLine&&this.startColumn>this.endColumn))
return new TextUtils.TextRange(this.endLine,this.endColumn,this.startLine,this.startColumn);else
return this.clone();}
clone(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.endLine,this.endColumn);}
serializeToObject(){const serializedTextRange={};serializedTextRange.startLine=this.startLine;serializedTextRange.startColumn=this.startColumn;serializedTextRange.endLine=this.endLine;serializedTextRange.endColumn=this.endColumn;return serializedTextRange;}
compareTo(other){if(this.startLine>other.startLine)
return 1;if(this.startLine<other.startLine)
return-1;if(this.startColumn>other.startColumn)
return 1;if(this.startColumn<other.startColumn)
return-1;return 0;}
compareToPosition(lineNumber,columnNumber){if(lineNumber<this.startLine||(lineNumber===this.startLine&&columnNumber<this.startColumn))
return-1;if(lineNumber>this.endLine||(lineNumber===this.endLine&&columnNumber>this.endColumn))
return 1;return 0;}
equal(other){return this.startLine===other.startLine&&this.endLine===other.endLine&&this.startColumn===other.startColumn&&this.endColumn===other.endColumn;}
relativeTo(line,column){const relative=this.clone();if(this.startLine===line)
relative.startColumn-=column;if(this.endLine===line)
relative.endColumn-=column;relative.startLine-=line;relative.endLine-=line;return relative;}
relativeFrom(line,column){const relative=this.clone();if(this.startLine===0)
relative.startColumn+=column;if(this.endLine===0)
relative.endColumn+=column;relative.startLine+=line;relative.endLine+=line;return relative;}
rebaseAfterTextEdit(originalRange,editedRange){console.assert(originalRange.startLine===editedRange.startLine);console.assert(originalRange.startColumn===editedRange.startColumn);const rebase=this.clone();if(!this.follows(originalRange))
return rebase;const lineDelta=editedRange.endLine-originalRange.endLine;const columnDelta=editedRange.endColumn-originalRange.endColumn;rebase.startLine+=lineDelta;rebase.endLine+=lineDelta;if(rebase.startLine===editedRange.endLine)
rebase.startColumn+=columnDelta;if(rebase.endLine===editedRange.endLine)
rebase.endColumn+=columnDelta;return rebase;}
toString(){return JSON.stringify(this);}
containsLocation(lineNumber,columnNumber){if(this.startLine===this.endLine)
return this.startLine===lineNumber&&this.startColumn<=columnNumber&&columnNumber<=this.endColumn;if(this.startLine===lineNumber)
return this.startColumn<=columnNumber;if(this.endLine===lineNumber)
return columnNumber<=this.endColumn;return this.startLine<lineNumber&&lineNumber<this.endLine;}};TextUtils.SourceRange=class{constructor(offset,length){this.offset=offset;this.length=length;}};TextUtils.SourceEdit=class{constructor(sourceURL,oldRange,newText){this.sourceURL=sourceURL;this.oldRange=oldRange;this.newText=newText;}
static comparator(edit1,edit2){return TextUtils.TextRange.comparator(edit1.oldRange,edit2.oldRange);}
newRange(){return TextUtils.TextRange.fromEdit(this.oldRange,this.newText);}};;self['Common']=self['Common']||{};Common.Worker=class{constructor(appName){let url=appName+'.js';url+=Runtime.queryParamsString();this._workerPromise=new Promise(fulfill=>{this._worker=new Worker(url);this._worker.onmessage=onMessage.bind(this);function onMessage(event){console.assert(event.data==='workerReady');this._worker.onmessage=null;fulfill(this._worker);this._worker=null;}});}
postMessage(message){this._workerPromise.then(worker=>{if(!this._disposed)
worker.postMessage(message);});}
dispose(){this._disposed=true;this._workerPromise.then(worker=>worker.terminate());}
terminate(){this.dispose();}
set onmessage(listener){this._workerPromise.then(worker=>worker.onmessage=listener);}
set onerror(listener){this._workerPromise.then(worker=>worker.onerror=listener);}};;Common.TextDictionary=class{constructor(){this._words=new Map();this._index=new Common.Trie();}
addWord(word){let count=this._words.get(word)||0;++count;this._words.set(word,count);this._index.add(word);}
removeWord(word){let count=this._words.get(word)||0;if(!count)
return;if(count===1){this._words.delete(word);this._index.remove(word);return;}
--count;this._words.set(word,count);}
wordsWithPrefix(prefix){return this._index.words(prefix);}
hasWord(word){return this._words.has(word);}
wordCount(word){return this._words.get(word)||0;}
reset(){this._words.clear();this._index.clear();}};;Common.Object=class{constructor(){this._listeners;}
addEventListener(eventType,listener,thisObject){if(!listener)
console.assert(false);if(!this._listeners)
this._listeners=new Map();if(!this._listeners.has(eventType))
this._listeners.set(eventType,[]);this._listeners.get(eventType).push({thisObject:thisObject,listener:listener});return{eventTarget:this,eventType:eventType,thisObject:thisObject,listener:listener};}
once(eventType){return new Promise(resolve=>{const descriptor=this.addEventListener(eventType,event=>{this.removeEventListener(eventType,descriptor.listener);resolve(event.data);});});}
removeEventListener(eventType,listener,thisObject){console.assert(listener);if(!this._listeners||!this._listeners.has(eventType))
return;const listeners=this._listeners.get(eventType);for(let i=0;i<listeners.length;++i){if(listeners[i].listener===listener&&listeners[i].thisObject===thisObject){listeners[i].disposed=true;listeners.splice(i--,1);}}
if(!listeners.length)
this._listeners.delete(eventType);}
hasEventListeners(eventType){return!!(this._listeners&&this._listeners.has(eventType));}
dispatchEventToListeners(eventType,eventData){if(!this._listeners||!this._listeners.has(eventType))
return;const event=({data:eventData});const listeners=this._listeners.get(eventType).slice(0);for(let i=0;i<listeners.length;++i){if(!listeners[i].disposed)
listeners[i].listener.call(listeners[i].thisObject,event);}}};Common.Event;Common.Object._listenerCallbackTuple;Common.EventTarget=function(){};Common.EventTarget.EventDescriptor;Common.EventTarget.removeEventListeners=function(eventList){for(const eventInfo of eventList)
eventInfo.eventTarget.removeEventListener(eventInfo.eventType,eventInfo.listener,eventInfo.thisObject);eventList.splice(0);};Common.EventTarget.prototype={addEventListener(eventType,listener,thisObject){},once(eventType){},removeEventListener(eventType,listener,thisObject){},hasEventListeners(eventType){},dispatchEventToListeners(eventType,eventData){},};;Common.Color=class{constructor(rgba,format,originalText){this._rgba=rgba;this._originalText=originalText||null;this._originalTextIsValid=!!this._originalText;this._format=format;if(typeof this._rgba[3]==='undefined')
this._rgba[3]=1;for(let i=0;i<4;++i){if(this._rgba[i]<0){this._rgba[i]=0;this._originalTextIsValid=false;}
if(this._rgba[i]>1){this._rgba[i]=1;this._originalTextIsValid=false;}}}
static parse(text){const value=text.toLowerCase().replace(/\s+/g,'');const simple=/^(?:#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(\w+))$/i;let match=value.match(simple);if(match){if(match[1]){let hex=match[1].toLowerCase();let format;if(hex.length===3){format=Common.Color.Format.ShortHEX;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2);}else if(hex.length===4){format=Common.Color.Format.ShortHEXA;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2)+
hex.charAt(3)+hex.charAt(3);}else if(hex.length===6){format=Common.Color.Format.HEX;}else{format=Common.Color.Format.HEXA;}
const r=parseInt(hex.substring(0,2),16);const g=parseInt(hex.substring(2,4),16);const b=parseInt(hex.substring(4,6),16);let a=1;if(hex.length===8)
a=parseInt(hex.substring(6,8),16)/255;return new Common.Color([r/255,g/255,b/255,a],format,text);}
if(match[2]){const nickname=match[2].toLowerCase();if(nickname in Common.Color.Nicknames){const rgba=Common.Color.Nicknames[nickname];const color=Common.Color.fromRGBA(rgba);color._format=Common.Color.Format.Nickname;color._originalText=text;return color;}
return null;}
return null;}
match=text.toLowerCase().match(/^\s*(?:(rgba?)|(hsla?))\((.*)\)\s*$/);if(match){const components=match[3].trim();let values=components.split(/\s*,\s*/);if(values.length===1){values=components.split(/\s+/);if(values[3]==='/'){values.splice(3,1);if(values.length!==4)
return null;}else if((values.length>2&&values[2].indexOf('/')!==-1)||(values.length>3&&values[3].indexOf('/')!==-1)){const alpha=values.slice(2,4).join('');values=values.slice(0,2).concat(alpha.split(/\//)).concat(values.slice(4));}else if(values.length>=4){return null;}}
if(values.length!==3&&values.length!==4||values.indexOf('')>-1)
return null;const hasAlpha=(values[3]!==undefined);if(match[1]){const rgba=[Common.Color._parseRgbNumeric(values[0]),Common.Color._parseRgbNumeric(values[1]),Common.Color._parseRgbNumeric(values[2]),hasAlpha?Common.Color._parseAlphaNumeric(values[3]):1];if(rgba.indexOf(null)>-1)
return null;return new Common.Color(rgba,hasAlpha?Common.Color.Format.RGBA:Common.Color.Format.RGB,text);}
if(match[2]){const hsla=[Common.Color._parseHueNumeric(values[0]),Common.Color._parseSatLightNumeric(values[1]),Common.Color._parseSatLightNumeric(values[2]),hasAlpha?Common.Color._parseAlphaNumeric(values[3]):1];if(hsla.indexOf(null)>-1)
return null;const rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,hasAlpha?Common.Color.Format.HSLA:Common.Color.Format.HSL,text);}}
return null;}
static fromRGBA(rgba){return new Common.Color([rgba[0]/255,rgba[1]/255,rgba[2]/255,rgba[3]],Common.Color.Format.RGBA);}
static fromHSVA(hsva){const rgba=[];Common.Color.hsva2rgba(hsva,rgba);return new Common.Color(rgba,Common.Color.Format.HSLA);}
static _parsePercentOrNumber(value){if(isNaN(value.replace('%','')))
return null;const parsed=parseFloat(value);if(value.indexOf('%')!==-1){if(value.indexOf('%')!==value.length-1)
return null;return parsed/100;}
return parsed;}
static _parseRgbNumeric(value){const parsed=Common.Color._parsePercentOrNumber(value);if(parsed===null)
return null;if(value.indexOf('%')!==-1)
return parsed;return parsed/255;}
static _parseHueNumeric(value){const angle=value.replace(/(deg|g?rad|turn)$/,'');if(isNaN(angle)||value.match(/\s+(deg|g?rad|turn)/))
return null;const number=parseFloat(angle);if(value.indexOf('turn')!==-1)
return number%1;else if(value.indexOf('grad')!==-1)
return(number/400)%1;else if(value.indexOf('rad')!==-1)
return(number/(2*Math.PI))%1;return(number/360)%1;}
static _parseSatLightNumeric(value){if(value.indexOf('%')!==value.length-1||isNaN(value.replace('%','')))
return null;const parsed=parseFloat(value);return Math.min(1,parsed/100);}
static _parseAlphaNumeric(value){return Common.Color._parsePercentOrNumber(value);}
static _hsva2hsla(hsva,out_hsla){const h=hsva[0];let s=hsva[1];const v=hsva[2];const t=(2-s)*v;if(v===0||s===0)
s=0;else
s*=v/(t<1?t:2-t);out_hsla[0]=h;out_hsla[1]=s;out_hsla[2]=t/2;out_hsla[3]=hsva[3];}
static hsl2rgb(hsl,out_rgb){const h=hsl[0];let s=hsl[1];const l=hsl[2];function hue2rgb(p,q,h){if(h<0)
h+=1;else if(h>1)
h-=1;if((h*6)<1)
return p+(q-p)*h*6;else if((h*2)<1)
return q;else if((h*3)<2)
return p+(q-p)*((2/3)-h)*6;else
return p;}
if(s<0)
s=0;let q;if(l<=0.5)
q=l*(1+s);else
q=l+s-(l*s);const p=2*l-q;const tr=h+(1/3);const tg=h;const tb=h-(1/3);out_rgb[0]=hue2rgb(p,q,tr);out_rgb[1]=hue2rgb(p,q,tg);out_rgb[2]=hue2rgb(p,q,tb);out_rgb[3]=hsl[3];}
static hsva2rgba(hsva,out_rgba){Common.Color._hsva2hsla(hsva,Common.Color.hsva2rgba._tmpHSLA);Common.Color.hsl2rgb(Common.Color.hsva2rgba._tmpHSLA,out_rgba);for(let i=0;i<Common.Color.hsva2rgba._tmpHSLA.length;i++)
Common.Color.hsva2rgba._tmpHSLA[i]=0;}
static luminance(rgba){const rSRGB=rgba[0];const gSRGB=rgba[1];const bSRGB=rgba[2];const r=rSRGB<=0.03928?rSRGB/12.92:Math.pow(((rSRGB+0.055)/1.055),2.4);const g=gSRGB<=0.03928?gSRGB/12.92:Math.pow(((gSRGB+0.055)/1.055),2.4);const b=bSRGB<=0.03928?bSRGB/12.92:Math.pow(((bSRGB+0.055)/1.055),2.4);return 0.2126*r+0.7152*g+0.0722*b;}
static blendColors(fgRGBA,bgRGBA,out_blended){const alpha=fgRGBA[3];out_blended[0]=((1-alpha)*bgRGBA[0])+(alpha*fgRGBA[0]);out_blended[1]=((1-alpha)*bgRGBA[1])+(alpha*fgRGBA[1]);out_blended[2]=((1-alpha)*bgRGBA[2])+(alpha*fgRGBA[2]);out_blended[3]=alpha+(bgRGBA[3]*(1-alpha));}
static calculateContrastRatio(fgRGBA,bgRGBA){Common.Color.blendColors(fgRGBA,bgRGBA,Common.Color.calculateContrastRatio._blendedFg);const fgLuminance=Common.Color.luminance(Common.Color.calculateContrastRatio._blendedFg);const bgLuminance=Common.Color.luminance(bgRGBA);const contrastRatio=(Math.max(fgLuminance,bgLuminance)+0.05)/(Math.min(fgLuminance,bgLuminance)+0.05);for(let i=0;i<Common.Color.calculateContrastRatio._blendedFg.length;i++)
Common.Color.calculateContrastRatio._blendedFg[i]=0;return contrastRatio;}
static desiredLuminance(luminance,contrast,lighter){function computeLuminance(){if(lighter)
return(luminance+0.05)*contrast-0.05;else
return(luminance+0.05)/contrast-0.05;}
let desiredLuminance=computeLuminance();if(desiredLuminance<0||desiredLuminance>1){lighter=!lighter;desiredLuminance=computeLuminance();}
return desiredLuminance;}
static detectColorFormat(color){const cf=Common.Color.Format;let format;const formatSetting=Common.moduleSetting('colorFormat').get();if(formatSetting===cf.Original)
format=cf.Original;else if(formatSetting===cf.RGB)
format=(color.hasAlpha()?cf.RGBA:cf.RGB);else if(formatSetting===cf.HSL)
format=(color.hasAlpha()?cf.HSLA:cf.HSL);else if(formatSetting===cf.HEX)
format=color.detectHEXFormat();else
format=cf.RGBA;return format;}
format(){return this._format;}
hsla(){if(this._hsla)
return this._hsla;const r=this._rgba[0];const g=this._rgba[1];const b=this._rgba[2];const max=Math.max(r,g,b);const min=Math.min(r,g,b);const diff=max-min;const add=max+min;let h;if(min===max)
h=0;else if(r===max)
h=((1/6*(g-b)/diff)+1)%1;else if(g===max)
h=(1/6*(b-r)/diff)+1/3;else
h=(1/6*(r-g)/diff)+2/3;const l=0.5*add;let s;if(l===0)
s=0;else if(l===1)
s=0;else if(l<=0.5)
s=diff/add;else
s=diff/(2-add);this._hsla=[h,s,l,this._rgba[3]];return this._hsla;}
canonicalHSLA(){const hsla=this.hsla();return[Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]];}
hsva(){const hsla=this.hsla();const h=hsla[0];let s=hsla[1];const l=hsla[2];s*=l<0.5?l:1-l;return[h,s!==0?2*s/(l+s):0,(l+s),hsla[3]];}
hasAlpha(){return this._rgba[3]!==1;}
detectHEXFormat(){let canBeShort=true;for(let i=0;i<4;++i){const c=Math.round(this._rgba[i]*255);if(c%17){canBeShort=false;break;}}
const hasAlpha=this.hasAlpha();const cf=Common.Color.Format;if(canBeShort)
return hasAlpha?cf.ShortHEXA:cf.ShortHEX;return hasAlpha?cf.HEXA:cf.HEX;}
asString(format){if(format===this._format&&this._originalTextIsValid)
return this._originalText;if(!format)
format=this._format;function toRgbValue(value){return Math.round(value*255);}
function toHexValue(value){const hex=Math.round(value*255).toString(16);return hex.length===1?'0'+hex:hex;}
function toShortHexValue(value){return(Math.round(value*255)/17).toString(16);}
switch(format){case Common.Color.Format.Original:return this._originalText;case Common.Color.Format.RGB:if(this.hasAlpha())
return null;return String.sprintf('rgb(%d, %d, %d)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]));case Common.Color.Format.RGBA:return String.sprintf('rgba(%d, %d, %d, %f)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]),this._rgba[3]);case Common.Color.Format.HSL:if(this.hasAlpha())
return null;const hsl=this.hsla();return String.sprintf('hsl(%d, %d%, %d%)',Math.round(hsl[0]*360),Math.round(hsl[1]*100),Math.round(hsl[2]*100));case Common.Color.Format.HSLA:const hsla=this.hsla();return String.sprintf('hsla(%d, %d%, %d%, %f)',Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]);case Common.Color.Format.HEXA:return String.sprintf('#%s%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2]),toHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.HEX:if(this.hasAlpha())
return null;return String.sprintf('#%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.ShortHEXA:const hexFormat=this.detectHEXFormat();if(hexFormat!==Common.Color.Format.ShortHEXA&&hexFormat!==Common.Color.Format.ShortHEX)
return null;return String.sprintf('#%s%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2]),toShortHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.ShortHEX:if(this.hasAlpha())
return null;if(this.detectHEXFormat()!==Common.Color.Format.ShortHEX)
return null;return String.sprintf('#%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.Nickname:return this.nickname();}
return this._originalText;}
rgba(){return this._rgba.slice();}
canonicalRGBA(){const rgba=new Array(4);for(let i=0;i<3;++i)
rgba[i]=Math.round(this._rgba[i]*255);rgba[3]=this._rgba[3];return rgba;}
nickname(){if(!Common.Color._rgbaToNickname){Common.Color._rgbaToNickname={};for(const nickname in Common.Color.Nicknames){let rgba=Common.Color.Nicknames[nickname];if(rgba.length!==4)
rgba=rgba.concat(1);Common.Color._rgbaToNickname[rgba]=nickname;}}
return Common.Color._rgbaToNickname[this.canonicalRGBA()]||null;}
toProtocolRGBA(){const rgba=this.canonicalRGBA();const result={r:rgba[0],g:rgba[1],b:rgba[2]};if(rgba[3]!==1)
result.a=rgba[3];return result;}
invert(){const rgba=[];rgba[0]=1-this._rgba[0];rgba[1]=1-this._rgba[1];rgba[2]=1-this._rgba[2];rgba[3]=this._rgba[3];return new Common.Color(rgba,Common.Color.Format.RGBA);}
setAlpha(alpha){const rgba=this._rgba.slice();rgba[3]=alpha;return new Common.Color(rgba,Common.Color.Format.RGBA);}
blendWith(fgColor){const rgba=[];Common.Color.blendColors(fgColor._rgba,this._rgba,rgba);return new Common.Color(rgba,Common.Color.Format.RGBA);}};Common.Color.Regex=/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g;Common.Color.Format={Original:'original',Nickname:'nickname',HEX:'hex',ShortHEX:'shorthex',HEXA:'hexa',ShortHEXA:'shorthexa',RGB:'rgb',RGBA:'rgba',HSL:'hsl',HSLA:'hsla'};Common.Color.hsva2rgba._tmpHSLA=[0,0,0,0];Common.Color.calculateContrastRatio._blendedFg=[0,0,0,0];Common.Color.Nicknames={'aliceblue':[240,248,255],'antiquewhite':[250,235,215],'aqua':[0,255,255],'aquamarine':[127,255,212],'azure':[240,255,255],'beige':[245,245,220],'bisque':[255,228,196],'black':[0,0,0],'blanchedalmond':[255,235,205],'blue':[0,0,255],'blueviolet':[138,43,226],'brown':[165,42,42],'burlywood':[222,184,135],'cadetblue':[95,158,160],'chartreuse':[127,255,0],'chocolate':[210,105,30],'coral':[255,127,80],'cornflowerblue':[100,149,237],'cornsilk':[255,248,220],'crimson':[237,20,61],'cyan':[0,255,255],'darkblue':[0,0,139],'darkcyan':[0,139,139],'darkgoldenrod':[184,134,11],'darkgray':[169,169,169],'darkgrey':[169,169,169],'darkgreen':[0,100,0],'darkkhaki':[189,183,107],'darkmagenta':[139,0,139],'darkolivegreen':[85,107,47],'darkorange':[255,140,0],'darkorchid':[153,50,204],'darkred':[139,0,0],'darksalmon':[233,150,122],'darkseagreen':[143,188,143],'darkslateblue':[72,61,139],'darkslategray':[47,79,79],'darkslategrey':[47,79,79],'darkturquoise':[0,206,209],'darkviolet':[148,0,211],'deeppink':[255,20,147],'deepskyblue':[0,191,255],'dimgray':[105,105,105],'dimgrey':[105,105,105],'dodgerblue':[30,144,255],'firebrick':[178,34,34],'floralwhite':[255,250,240],'forestgreen':[34,139,34],'fuchsia':[255,0,255],'gainsboro':[220,220,220],'ghostwhite':[248,248,255],'gold':[255,215,0],'goldenrod':[218,165,32],'gray':[128,128,128],'grey':[128,128,128],'green':[0,128,0],'greenyellow':[173,255,47],'honeydew':[240,255,240],'hotpink':[255,105,180],'indianred':[205,92,92],'indigo':[75,0,130],'ivory':[255,255,240],'khaki':[240,230,140],'lavender':[230,230,250],'lavenderblush':[255,240,245],'lawngreen':[124,252,0],'lemonchiffon':[255,250,205],'lightblue':[173,216,230],'lightcoral':[240,128,128],'lightcyan':[224,255,255],'lightgoldenrodyellow':[250,250,210],'lightgreen':[144,238,144],'lightgray':[211,211,211],'lightgrey':[211,211,211],'lightpink':[255,182,193],'lightsalmon':[255,160,122],'lightseagreen':[32,178,170],'lightskyblue':[135,206,250],'lightslategray':[119,136,153],'lightslategrey':[119,136,153],'lightsteelblue':[176,196,222],'lightyellow':[255,255,224],'lime':[0,255,0],'limegreen':[50,205,50],'linen':[250,240,230],'magenta':[255,0,255],'maroon':[128,0,0],'mediumaquamarine':[102,205,170],'mediumblue':[0,0,205],'mediumorchid':[186,85,211],'mediumpurple':[147,112,219],'mediumseagreen':[60,179,113],'mediumslateblue':[123,104,238],'mediumspringgreen':[0,250,154],'mediumturquoise':[72,209,204],'mediumvioletred':[199,21,133],'midnightblue':[25,25,112],'mintcream':[245,255,250],'mistyrose':[255,228,225],'moccasin':[255,228,181],'navajowhite':[255,222,173],'navy':[0,0,128],'oldlace':[253,245,230],'olive':[128,128,0],'olivedrab':[107,142,35],'orange':[255,165,0],'orangered':[255,69,0],'orchid':[218,112,214],'palegoldenrod':[238,232,170],'palegreen':[152,251,152],'paleturquoise':[175,238,238],'palevioletred':[219,112,147],'papayawhip':[255,239,213],'peachpuff':[255,218,185],'peru':[205,133,63],'pink':[255,192,203],'plum':[221,160,221],'powderblue':[176,224,230],'purple':[128,0,128],'rebeccapurple':[102,51,153],'red':[255,0,0],'rosybrown':[188,143,143],'royalblue':[65,105,225],'saddlebrown':[139,69,19],'salmon':[250,128,114],'sandybrown':[244,164,96],'seagreen':[46,139,87],'seashell':[255,245,238],'sienna':[160,82,45],'silver':[192,192,192],'skyblue':[135,206,235],'slateblue':[106,90,205],'slategray':[112,128,144],'slategrey':[112,128,144],'snow':[255,250,250],'springgreen':[0,255,127],'steelblue':[70,130,180],'tan':[210,180,140],'teal':[0,128,128],'thistle':[216,191,216],'tomato':[255,99,71],'turquoise':[64,
setColorForID(id,color){this._colors.set(id,color);}
colorForID(id){let color=this._colors.get(id);if(!color){color=this._generateColorForID(id);this._colors.set(id,color);}
return color;}
_generateColorForID(id){const hash=String.hashCode(id);const h=this._indexToValueInSpace(hash,this._hueSpace);const s=this._indexToValueInSpace(hash>>8,this._satSpace);const l=this._indexToValueInSpace(hash>>16,this._lightnessSpace);const a=this._indexToValueInSpace(hash>>24,this._alphaSpace);return`hsla(${h}, ${s}%, ${l}%, ${a})`;}
_indexToValueInSpace(index,space){if(typeof space==='number')
return space;const count=space.count||space.max-space.min;index%=count;return space.min+Math.floor(index/(count-1)*(space.max-space.min));}};;Common.Console=class extends Common.Object{constructor(){super();this._messages=[];}
addMessage(text,level,show){const message=new Common.Console.Message(text,level||Common.Console.MessageLevel.Info,Date.now(),show||false);this._messages.push(message);this.dispatchEventToListeners(Common.Console.Events.MessageAdded,message);}
log(text){this.addMessage(text,Common.Console.MessageLevel.Info);}
warn(text){this.addMessage(text,Common.Console.MessageLevel.Warning);}
error(text){this.addMessage(text,Common.Console.MessageLevel.Error,true);}
messages(){return this._messages;}
show(){this.showPromise();}
showPromise(){return Common.Revealer.reveal(this);}};Common.Console.Events={MessageAdded:Symbol('messageAdded')};Common.Console.MessageLevel={Info:'info',Warning:'warning',Error:'error'};Common.Console.Message=class{constructor(text,level,timestamp,show){this.text=text;this.level=level;this.timestamp=(typeof timestamp==='number')?timestamp:Date.now();this.show=show;}};Common.console=new Common.Console();;Common.ContentProvider=function(){};Common.ContentProvider.prototype={contentURL(){},contentType(){},contentEncoded(){},requestContent(){},searchInContent(query,caseSensitive,isRegex){}};Common.ContentProvider.SearchMatch=class{constructor(lineNumber,lineContent){this.lineNumber=lineNumber;this.lineContent=lineContent;}};Common.ContentProvider.performSearchInContent=function(content,query,caseSensitive,isRegex){const regex=createSearchRegex(query,caseSensitive,isRegex);const text=new TextUtils.Text(content);const result=[];for(let i=0;i<text.lineCount();++i){const lineContent=text.lineAt(i);regex.lastIndex=0;if(regex.exec(lineContent))
result.push(new Common.ContentProvider.SearchMatch(i,lineContent));}
return result;};Common.ContentProvider.contentAsDataURL=function(content,mimeType,contentEncoded,charset){const maxDataUrlSize=1024*1024;if(content===null||content.length>maxDataUrlSize)
return null;return'data:'+mimeType+(charset?';charset='+charset:'')+(contentEncoded?';base64':'')+','+
content;};;Common.ParsedURL=class{constructor(url){this.isValid=false;this.url=url;this.scheme='';this.user='';this.host='';this.port='';this.path='';this.queryParams='';this.fragment='';this.folderPathComponents='';this.lastPathComponent='';const isBlobUrl=this.url.startsWith('blob:');const urlToMatch=isBlobUrl?url.substring(5):url;const match=urlToMatch.match(Common.ParsedURL._urlRegex());if(match){this.isValid=true;if(isBlobUrl){this._blobInnerScheme=match[2].toLowerCase();this.scheme='blob';}else{this.scheme=match[2].toLowerCase();}
this.user=match[3];this.host=match[4];this.port=match[5];this.path=match[6]||'/';this.queryParams=match[7]||'';this.fragment=match[8];}else{if(this.url.startsWith('data:')){this.scheme='data';return;}
if(this.url.startsWith('blob:')){this.scheme='blob';return;}
if(this.url==='about:blank'){this.scheme='about';return;}
this.path=this.url;}
const lastSlashIndex=this.path.lastIndexOf('/');if(lastSlashIndex!==-1){this.folderPathComponents=this.path.substring(0,lastSlashIndex);this.lastPathComponent=this.path.substring(lastSlashIndex+1);}else{this.lastPathComponent=this.path;}}
static platformPathToURL(fileSystemPath){fileSystemPath=fileSystemPath.replace(/\\/g,'/');if(!fileSystemPath.startsWith('file://')){if(fileSystemPath.startsWith('/'))
fileSystemPath='file://'+fileSystemPath;else
fileSystemPath='file:///'+fileSystemPath;}
return fileSystemPath;}
static urlToPlatformPath(fileURL,isWindows){console.assert(fileURL.startsWith('file://'),'This must be a file URL.');if(isWindows)
return fileURL.substr('file:///'.length).replace(/\//g,'\\');return fileURL.substr('file://'.length);}
static urlWithoutHash(url){const hashIndex=url.indexOf('#');if(hashIndex!==-1)
return url.substr(0,hashIndex);return url;}
static _urlRegex(){if(Common.ParsedURL._urlRegexInstance)
return Common.ParsedURL._urlRegexInstance;const schemeRegex=/([A-Za-z][A-Za-z0-9+.-]*):\/\//;const userRegex=/(?:([A-Za-z0-9\-._~%!$&'()*+,;=:]*)@)?/;const hostRegex=/((?:\[::\d?\])|(?:[^\s\/:]*))/;const portRegex=/(?::([\d]+))?/;const pathRegex=/(\/[^#?]*)?/;const queryRegex=/(?:\?([^#]*))?/;const fragmentRegex=/(?:#(.*))?/;Common.ParsedURL._urlRegexInstance=new RegExp('^('+schemeRegex.source+userRegex.source+hostRegex.source+portRegex.source+')'+pathRegex.source+
queryRegex.source+fragmentRegex.source+'$');return Common.ParsedURL._urlRegexInstance;}
static extractPath(url){const parsedURL=url.asParsedURL();return parsedURL?parsedURL.path:'';}
static extractOrigin(url){const parsedURL=url.asParsedURL();return parsedURL?parsedURL.securityOrigin():'';}
static extractExtension(url){url=Common.ParsedURL.urlWithoutHash(url);const indexOfQuestionMark=url.indexOf('?');if(indexOfQuestionMark!==-1)
url=url.substr(0,indexOfQuestionMark);const lastIndexOfSlash=url.lastIndexOf('/');if(lastIndexOfSlash!==-1)
url=url.substr(lastIndexOfSlash+1);const lastIndexOfDot=url.lastIndexOf('.');if(lastIndexOfDot!==-1){url=url.substr(lastIndexOfDot+1);const lastIndexOfPercent=url.indexOf('%');if(lastIndexOfPercent!==-1)
return url.substr(0,lastIndexOfPercent);return url;}
return'';}
static extractName(url){let index=url.lastIndexOf('/');const pathAndQuery=index!==-1?url.substr(index+1):url;index=pathAndQuery.indexOf('?');return index<0?pathAndQuery:pathAndQuery.substr(0,index);}
static completeURL(baseURL,href){const trimmedHref=href.trim();if(trimmedHref.startsWith('data:')||trimmedHref.startsWith('blob:')||trimmedHref.startsWith('javascript:'))
return href;const parsedHref=trimmedHref.asParsedURL();if(parsedHref&&parsedHref.scheme)
return trimmedHref;const parsedURL=baseURL.asParsedURL();if(!parsedURL)
return null;if(parsedURL.isDataURL())
return href;if(href.length>1&&href.charAt(0)==='/'&&href.charAt(1)==='/'){return parsedURL.scheme+':'+href;}
const securityOrigin=parsedURL.securityOrigin();const pathText=parsedURL.path;const queryText=parsedURL.queryParams?'?'+parsedURL.queryParams:'';if(!href.length)
return securityOrigin+pathText+queryText;if(href.charAt(0)==='#')
return securityOrigin+pathText+queryText+href;if(href.charAt(0)==='?')
return securityOrigin+pathText+href;let hrefPath=href.match(/^[^#?]*/)[0];const hrefSuffix=href.substring(hrefPath.length);if(hrefPath.charAt(0)!=='/')
hrefPath=parsedURL.folderPathComponents+'/'+hrefPath;return securityOrigin+Runtime.normalizePath(hrefPath)+hrefSuffix;}
static splitLineAndColumn(string){const beforePathMatch=string.match(Common.ParsedURL._urlRegex());let beforePath='';let pathAndAfter=string;if(beforePathMatch){beforePath=beforePathMatch[1];pathAndAfter=string.substring(beforePathMatch[1].length);}
const lineColumnRegEx=/(?::(\d+))?(?::(\d+))?$/;const lineColumnMatch=lineColumnRegEx.exec(pathAndAfter);let lineNumber;let columnNumber;console.assert(lineColumnMatch);if(typeof(lineColumnMatch[1])==='string'){lineNumber=parseInt(lineColumnMatch[1],10);lineNumber=isNaN(lineNumber)?undefined:lineNumber-1;}
if(typeof(lineColumnMatch[2])==='string'){columnNumber=parseInt(lineColumnMatch[2],10);columnNumber=isNaN(columnNumber)?undefined:columnNumber-1;}
return{url:beforePath+pathAndAfter.substring(0,pathAndAfter.length-lineColumnMatch[0].length),lineNumber:lineNumber,columnNumber:columnNumber};}
static isRelativeURL(url){return!(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url));}
get displayName(){if(this._displayName)
return this._displayName;if(this.isDataURL())
return this.dataURLDisplayName();if(this.isBlobURL())
return this.url;if(this.isAboutBlank())
return this.url;this._displayName=this.lastPathComponent;if(!this._displayName)
this._displayName=(this.host||'')+'/';if(this._displayName==='/')
this._displayName=this.url;return this._displayName;}
dataURLDisplayName(){if(this._dataURLDisplayName)
return this._dataURLDisplayName;if(!this.isDataURL())
return'';this._dataURLDisplayName=this.url.trimEnd(20);return this._dataURLDisplayName;}
isAboutBlank(){return this.url==='about:blank';}
isDataURL(){return this.scheme==='data';}
isBlobURL(){return this.url.startsWith('blob:');}
lastPathComponentWithFragment(){return this.lastPathComponent+(this.fragment?'#'+this.fragment:'');}
domain(){if(this.isDataURL())
return'data:';return this.host+(this.port?':'+this.port:'');}
securityOrigin(){if(this.isDataURL())
return'data:';const scheme=this.isBlobURL()?this._blobInnerScheme:this.scheme;return scheme+'://'+this.domain();}
urlWithoutScheme(){if(this.scheme&&this.url.startsWith(this.scheme+'://'))
return this.url.substring(this.scheme.length+3);return this.url;}};String.prototype.asParsedURL=function(){const parsedURL=new Common.ParsedURL(this.toString());if(parsedURL.isValid)
return parsedURL;return null;};;Common.Progress=function(){};Common.Progress.prototype={setTotalWork(totalWork){},setTitle(title){},setWorked(worked,title){},worked(worked){},done(){},isCanceled(){return false;},};Common.CompositeProgress=class{constructor(parent){this._parent=parent;this._children=[];this._childrenDone=0;this._parent.setTotalWork(1);this._parent.setWorked(0);}
_childDone(){if(++this._childrenDone!==this._children.length)
return;this._parent.done();}
createSubProgress(weight){const child=new Common.SubProgress(this,weight);this._children.push(child);return child;}
_update(){let totalWeights=0;let done=0;for(let i=0;i<this._children.length;++i){const child=this._children[i];if(child._totalWork)
done+=child._weight*child._worked/child._totalWork;totalWeights+=child._weight;}
this._parent.setWorked(done/totalWeights);}};Common.SubProgress=class{constructor(composite,weight){this._composite=composite;this._weight=weight||1;this._worked=0;}
isCanceled(){return this._composite._parent.isCanceled();}
setTitle(title){this._composite._parent.setTitle(title);}
done(){this.setWorked(this._totalWork);this._composite._childDone();}
setTotalWork(totalWork){this._totalWork=totalWork;this._composite._update();}
setWorked(worked,title){this._worked=worked;if(typeof title!=='undefined')
this.setTitle(title);this._composite._update();}
worked(worked){this.setWorked(this._worked+(worked||1));}};Common.ProgressProxy=class{constructor(delegate,doneCallback){this._delegate=delegate;this._doneCallback=doneCallback;}
isCanceled(){return this._delegate?this._delegate.isCanceled():false;}
setTitle(title){if(this._delegate)
this._delegate.setTitle(title);}
done(){if(this._delegate)
this._delegate.done();if(this._doneCallback)
this._doneCallback();}
setTotalWork(totalWork){if(this._delegate)
this._delegate.setTotalWork(totalWork);}
setWorked(worked,title){if(this._delegate)
this._delegate.setWorked(worked,title);}
worked(worked){if(this._delegate)
this._delegate.worked(worked);}};;Common.ResourceType=class{constructor(name,title,category,isTextType){this._name=name;this._title=title;this._category=category;this._isTextType=isTextType;}
static fromMimeType(mimeType){if(mimeType.startsWith('text/html'))
return Common.resourceTypes.Document;if(mimeType.startsWith('text/css'))
return Common.resourceTypes.Stylesheet;if(mimeType.startsWith('image/'))
return Common.resourceTypes.Image;if(mimeType.startsWith('text/'))
return Common.resourceTypes.Script;if(mimeType.includes('font'))
return Common.resourceTypes.Font;if(mimeType.includes('script'))
return Common.resourceTypes.Script;if(mimeType.includes('octet'))
return Common.resourceTypes.Other;if(mimeType.includes('application'))
return Common.resourceTypes.Script;return Common.resourceTypes.Other;}
static fromURL(url){return Common.ResourceType._resourceTypeByExtension.get(Common.ParsedURL.extractExtension(url))||null;}
static fromName(name){for(const resourceTypeId in Common.resourceTypes){const resourceType=Common.resourceTypes[resourceTypeId];if(resourceType.name()===name)
return resourceType;}
return null;}
static mimeFromURL(url){const name=Common.ParsedURL.extractName(url);if(Common.ResourceType._mimeTypeByName.has(name))
return Common.ResourceType._mimeTypeByName.get(name);const ext=Common.ParsedURL.extractExtension(url).toLowerCase();return Common.ResourceType._mimeTypeByExtension.get(ext);}
static mimeFromExtension(ext){return Common.ResourceType._mimeTypeByExtension.get(ext);}
name(){return this._name;}
title(){return this._title;}
category(){return this._category;}
isTextType(){return this._isTextType;}
isScript(){return this._name==='script'||this._name==='sm-script';}
hasScripts(){return this.isScript()||this.isDocument();}
isStyleSheet(){return this._name==='stylesheet'||this._name==='sm-stylesheet';}
isDocument(){return this._name==='document';}
isDocumentOrScriptOrStyleSheet(){return this.isDocument()||this.isScript()||this.isStyleSheet();}
isFromSourceMap(){return this._name.startsWith('sm-');}
toString(){return this._name;}
canonicalMimeType(){if(this.isDocument())
return'text/html';if(this.isScript())
return'text/javascript';if(this.isStyleSheet())
return'text/css';return'';}};Common.ResourceCategory=class{constructor(title,shortTitle){this.title=title;this.shortTitle=shortTitle;}};Common.resourceCategories={XHR:new Common.ResourceCategory('XHR and Fetch','XHR'),Script:new Common.ResourceCategory('Scripts','JS'),Stylesheet:new Common.ResourceCategory('Stylesheets','CSS'),Image:new Common.ResourceCategory('Images','Img'),Media:new Common.ResourceCategory('Media','Media'),Font:new Common.ResourceCategory('Fonts','Font'),Document:new Common.ResourceCategory('Documents','Doc'),WebSocket:new Common.ResourceCategory('WebSockets','WS'),Manifest:new Common.ResourceCategory('Manifest','Manifest'),Other:new Common.ResourceCategory('Other','Other')};Common.resourceTypes={XHR:new Common.ResourceType('xhr','XHR',Common.resourceCategories.XHR,true),Fetch:new Common.ResourceType('fetch','Fetch',Common.resourceCategories.XHR,true),EventSource:new Common.ResourceType('eventsource','EventSource',Common.resourceCategories.XHR,true),Script:new Common.ResourceType('script','Script',Common.resourceCategories.Script,true),Stylesheet:new Common.ResourceType('stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,true),Image:new Common.ResourceType('image','Image',Common.resourceCategories.Image,false),Media:new Common.ResourceType('media','Media',Common.resourceCategories.Media,false),Font:new Common.ResourceType('font','Font',Common.resourceCategories.Font,false),Document:new Common.ResourceType('document','Document',Common.resourceCategories.Document,true),TextTrack:new Common.ResourceType('texttrack','TextTrack',Common.resourceCategories.Other,true),WebSocket:new Common.ResourceType('websocket','WebSocket',Common.resourceCategories.WebSocket,false),Other:new Common.ResourceType('other','Other',Common.resourceCategories.Other,false),SourceMapScript:new Common.ResourceType('sm-script','Script',Common.resourceCategories.Script,true),SourceMapStyleSheet:new Common.ResourceType('sm-stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,true),Manifest:new Common.ResourceType('manifest','Manifest',Common.resourceCategories.Manifest,true),SignedExchange:new Common.ResourceType('signed-exchange','SignedExchange',Common.resourceCategories.Other,false),};Common.ResourceType._mimeTypeByName=new Map([['Cakefile','text/x-coffeescript']]);Common.ResourceType._resourceTypeByExtension=new Map([['js',Common.resourceTypes.Script],['mjs',Common.resourceTypes.Script],['css',Common.resourceTypes.Stylesheet],['xsl',Common.resourceTypes.Stylesheet],['jpeg',Common.resourceTypes.Image],['jpg',Common.resourceTypes.Image],['svg',Common.resourceTypes.Image],['gif',Common.resourceTypes.Image],['png',Common.resourceTypes.Image],['ico',Common.resourceTypes.Image],['tiff',Common.resourceTypes.Image],['tif',Common.resourceTypes.Image],['bmp',Common.resourceTypes.Image],['webp',Common.resourceTypes.Media],['ttf',Common.resourceTypes.Font],['otf',Common.resourceTypes.Font],['ttc',Common.resourceTypes.Font],['woff',Common.resourceTypes.Font]]);Common.ResourceType._mimeTypeByExtension=new Map([['js','text/javascript'],['mjs','text/javascript'],['css','text/css'],['html','text/html'],['htm','text/html'],['xml','application/xml'],['xsl','application/xml'],['asp','application/x-aspx'],['aspx','application/x-aspx'],['jsp','application/x-jsp'],['c','text/x-c++src'],['cc','text/x-c++src'],['cpp','text/x-c++src'],['h','text/x-c++src'],['m','text/x-c++src'],['mm','text/x-c++src'],['coffee','text/x-coffeescript'],['dart','text/javascript'],['ts','text/typescript'],['tsx','text/typescript-jsx'],['json','application/json'],['gyp','application/json'],['gypi','application/json'],['cs','text/x-csharp'],['java','text/x-java'],['less','text/x-less'],['php','text/x-php'],['phtml','application/x-httpd-php'],['py','text/x-python'],['sh','text/x-sh'],['scss','text/x-scss'],['vtt','text/vtt'],['ls','text/x-livescript'],['md','text/markdown'],['cljs','text/x-clojure'],['cljc','text/x-clojure'],['cljx','text/x-clojure'],['styl','text/x-styl'],['jsx','text/jsx'],['jpeg','image/jpeg'],['jpg','image/jpeg'],['svg','image/svg+xml'],['g
_registerModuleSetting(extension){const descriptor=extension.descriptor();const settingName=descriptor['settingName'];const isRegex=descriptor['settingType']==='regex';const defaultValue=descriptor['defaultValue'];let storageType;switch(descriptor['storageType']){case('local'):storageType=Common.SettingStorageType.Local;break;case('session'):storageType=Common.SettingStorageType.Session;break;case('global'):storageType=Common.SettingStorageType.Global;break;default:storageType=Common.SettingStorageType.Global;}
const setting=isRegex?this.createRegExpSetting(settingName,defaultValue,undefined,storageType):this.createSetting(settingName,defaultValue,storageType);if(descriptor['title'])
setting.setTitle(descriptor['title']);if(descriptor['userActionCondition'])
setting.setRequiresUserAction(!!Runtime.queryParam(descriptor['userActionCondition']));setting._extension=extension;this._moduleSettings.set(settingName,setting);}
moduleSetting(settingName){const setting=this._moduleSettings.get(settingName);if(!setting)
throw new Error('No setting registered: '+settingName);return setting;}
settingForTest(settingName){const setting=this._registry.get(settingName);if(!setting)
throw new Error('No setting registered: '+settingName);return setting;}
createSetting(key,defaultValue,storageType){const storage=this._storageFromType(storageType);if(!this._registry.get(key))
this._registry.set(key,new Common.Setting(this,key,defaultValue,this._eventSupport,storage));return(this._registry.get(key));}
createLocalSetting(key,defaultValue){return this.createSetting(key,defaultValue,Common.SettingStorageType.Local);}
createRegExpSetting(key,defaultValue,regexFlags,storageType){if(!this._registry.get(key)){this._registry.set(key,new Common.RegExpSetting(this,key,defaultValue,this._eventSupport,this._storageFromType(storageType),regexFlags));}
return(this._registry.get(key));}
clearAll(){this._globalStorage.removeAll();this._localStorage.removeAll();const versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);versionSetting.set(Common.VersionController.currentVersion);}
_storageFromType(storageType){switch(storageType){case(Common.SettingStorageType.Local):return this._localStorage;case(Common.SettingStorageType.Session):return this._sessionStorage;case(Common.SettingStorageType.Global):return this._globalStorage;}
return this._globalStorage;}};Common.SettingsStorage=class{constructor(object,setCallback,removeCallback,removeAllCallback,storagePrefix){this._object=object;this._setCallback=setCallback||function(){};this._removeCallback=removeCallback||function(){};this._removeAllCallback=removeAllCallback||function(){};this._storagePrefix=storagePrefix||'';}
set(name,value){name=this._storagePrefix+name;this._object[name]=value;this._setCallback(name,value);}
has(name){name=this._storagePrefix+name;return name in this._object;}
get(name){name=this._storagePrefix+name;return this._object[name];}
remove(name){name=this._storagePrefix+name;delete this._object[name];this._removeCallback(name);}
removeAll(){this._object={};this._removeAllCallback();}
_dumpSizes(){Common.console.log('Ten largest settings: ');const sizes={__proto__:null};for(const key in this._object)
sizes[key]=this._object[key].length;const keys=Object.keys(sizes);function comparator(key1,key2){return sizes[key2]-sizes[key1];}
keys.sort(comparator);for(let i=0;i<10&&i<keys.length;++i)
Common.console.log('Setting: \''+keys[i]+'\', size: '+sizes[keys[i]]);}};Common.Setting=class{constructor(settings,name,defaultValue,eventSupport,storage){this._settings=settings;this._name=name;this._defaultValue=defaultValue;this._eventSupport=eventSupport;this._storage=storage;this._title='';this._extension=null;}
addChangeListener(listener,thisObject){return this._eventSupport.addEventListener(this._name,listener,thisObject);}
removeChangeListener(listener,thisObject){this._eventSupport.removeEventListener(this._name,listener,thisObject);}
get name(){return this._name;}
title(){return this._title;}
setTitle(title){this._title=title;}
setRequiresUserAction(requiresUserAction){this._requiresUserAction=requiresUserAction;}
get(){if(this._requiresUserAction&&!this._hadUserAction)
return this._defaultValue;if(typeof this._value!=='undefined')
return this._value;this._value=this._defaultValue;if(this._storage.has(this._name)){try{this._value=JSON.parse(this._storage.get(this._name));}catch(e){this._storage.remove(this._name);}}
return this._value;}
set(value){this._hadUserAction=true;this._value=value;try{const settingString=JSON.stringify(value);try{this._storage.set(this._name,settingString);}catch(e){this._printSettingsSavingError(e.message,this._name,settingString);}}catch(e){Common.console.error('Cannot stringify setting with name: '+this._name+', error: '+e.message);}
this._eventSupport.dispatchEventToListeners(this._name,value);}
remove(){this._settings._registry.delete(this._name);this._settings._moduleSettings.delete(this._name);this._storage.remove(this._name);}
extension(){return this._extension;}
_printSettingsSavingError(message,name,value){const errorMessage='Error saving setting with name: '+this._name+', value length: '+value.length+'. Error: '+message;console.error(errorMessage);Common.console.error(errorMessage);this._storage._dumpSizes();}};Common.RegExpSetting=class extends Common.Setting{constructor(settings,name,defaultValue,eventSupport,storage,regexFlags){super(settings,name,defaultValue?[{pattern:defaultValue}]:[],eventSupport,storage);this._regexFlags=regexFlags;}
get(){const result=[];const items=this.getAsArray();for(let i=0;i<items.length;++i){const item=items[i];if(item.pattern&&!item.disabled)
result.push(item.pattern);}
return result.join('|');}
getAsArray(){return super.get();}
set(value){this.setAsArray([{pattern:value}]);}
setAsArray(value){delete this._regex;super.set(value);}
asRegExp(){if(typeof this._regex!=='undefined')
return this._regex;this._regex=null;try{const pattern=this.get();if(pattern)
this._regex=new RegExp(pattern,this._regexFlags||'');}catch(e){}
return this._regex;}};Common.VersionController=class{updateVersion(){const localStorageVersion=window.localStorage?window.localStorage[Common.VersionController._currentVersionName]:0;const versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);const currentVersion=Common.VersionController.currentVersion;const oldVersion=versionSetting.get()||parseInt(localStorageVersion||'0',10);if(oldVersion===0){versionSetting.set(currentVersion);return;}
const methodsToRun=this._methodsToRunToUpdateVersion(oldVersion,currentVersion);for(let i=0;i<methodsToRun.length;++i)
this[methodsToRun[i]].call(this);versionSetting.set(currentVersion);}
_methodsToRunToUpdateVersion(oldVersion,currentVersion){const result=[];for(let i=oldVersion;i<currentVersion;++i)
result.push('_updateVersionFrom'+i+'To'+(i+1));return result;}
_updateVersionFrom0To1(){this._clearBreakpointsWhenTooMany(Common.settings.createLocalSetting('breakpoints',[]),500000);}
_updateVersionFrom1To2(){Common.settings.createSetting('previouslyViewedFiles',[]).set([]);}
_updateVersionFrom2To3(){Common.settings.createSetting('fileSystemMapping',{}).set({});Common.settings.createSetting('fileMappingEntries',[]).remove();}
_updateVersionFrom3To4(){const advancedMode=Common.settings.createSetting('showHeaSnapshotObjectsHiddenProperties',false);Common.moduleSetting('showAdvancedHeapSnapshotProperties').set(advancedMode.get());advancedMode.remove();}
_updateVersionFrom4To5(){const settingNames={'FileSystemViewSidebarWidth':'fileSystemViewSplitViewState','elementsSidebarWidth':'elementsPanelSplitViewState','StylesPaneSplitRatio':'stylesPaneSplitViewState','heapSnapshotRetainersViewSize':'heapSnapshotSplitViewState','InspectorView.splitView':'InspectorView.splitViewState','InspectorView.screencastSplitView':'InspectorView.screencastSplitViewState','Inspector.drawerSplitView':'Inspector.drawerSplitViewState','layerDetailsSplitView':'layerDetailsSplitViewState','networkSidebarWidth':'networkPanelSplitViewState','sourcesSidebarWidth':'sourcesPanelSplitViewState','scriptsPanelNavigatorSidebarWidth':'sourcesPanelNavigatorSplitViewState','sourcesPanelSplitSidebarRatio':'sourcesPanelDebuggerSidebarSplitViewState','timeline-details':'timelinePanelDetailsSplitViewState','timeline-split':'timelinePanelRecorsSplitViewState','timeline-view':'timelinePanelTimelineStackSplitViewState','auditsSidebarWidth':'auditsPanelSplitViewState','layersSidebarWidth':'layersPanelSplitViewState','profilesSidebarWidth':'profilesPanelSplitViewState','resourcesSidebarWidth':'resourcesPanelSplitViewState'};const empty={};for(const oldName in settingNames){const newName=settingNames[oldName];const oldNameH=oldName+'H';let newValue=null;const oldSetting=Common.settings.createSetting(oldName,empty);if(oldSetting.get()!==empty){newValue=newValue||{};newValue.vertical={};newValue.vertical.size=oldSetting.get();oldSetting.remove();}
const oldSettingH=Common.settings.createSetting(oldNameH,empty);if(oldSettingH.get()!==empty){newValue=newValue||{};newValue.horizontal={};newValue.horizontal.size=oldSettingH.get();oldSettingH.remove();}
if(newValue)
Common.settings.createSetting(newName,{}).set(newValue);}}
_updateVersionFrom5To6(){const settingNames={'debuggerSidebarHidden':'sourcesPanelSplitViewState','navigatorHidden':'sourcesPanelNavigatorSplitViewState','WebInspector.Drawer.showOnLoad':'Inspector.drawerSplitViewState'};for(const oldName in settingNames){const oldSetting=Common.settings.createSetting(oldName,null);if(oldSetting.get()===null){oldSetting.remove();continue;}
const newName=settingNames[oldName];const invert=oldName==='WebInspector.Drawer.showOnLoad';const hidden=oldSetting.get()!==invert;oldSetting.remove();const showMode=hidden?'OnlyMain':'Both';const newSetting=Common.settings.createSetting(newName,{});const newValue=newSetting.get()||{};newValue.vertical=newValue.vertical||{};newValue.vertical.showMode=showMode;newValue.horizontal=newValue.horizontal||{};newValue.horizontal.showMode=showMode;newSetting.set(newValue);}}
_updateVersionFrom6To7(){const settingNames={'sourcesPanelNavigatorSplitViewState':'sourcesPanelNavigatorSplitViewState','elementsPanelSplitViewState':'elementsPanelSplitViewState','stylesPaneSplitViewState':'stylesPaneSplitViewState','sourcesPanelDebuggerSidebarSplitViewState':'sourcesPanelDebuggerSidebarSplitViewState'};const empty={};for(const name in settingNames){const setting=Common.settings.createSetting(name,empty);const value=setting.get();if(value===empty)
continue;if(value.vertical&&value.vertical.size&&value.vertical.size<1)
value.vertical.size=0;if(value.horizontal&&value.horizontal.size&&value.horizontal.size<1)
value.horizontal.size=0;setting.set(value);}}
_updateVersionFrom7To8(){}
_updateVersionFrom8To9(){const settingNames=['skipStackFramesPattern','workspaceFolderExcludePattern'];for(let i=0;i<settingNames.length;++i){const setting=Common.settings.createSetting(settingNames[i],'');let value=setting.get();if(!value)
return;if(typeof value==='string')
value=[value];for(let j=0;j<value.length;++j){if(typeof value[j]==='string')
value[j]={pattern:value[j]};}
setting.set(value);}}
_updateVersionFrom9To10(){if(!window.localStorage)
return;for(const key in window.localStorage){if(key.startsWith('revision-history'))
window.localStorage.removeItem(key);}}
_updateVersionFrom10To11(){const oldSettingName='customDevicePresets';const newSettingName='customEmulatedDeviceList';const oldSetting=Common.settings.createSetting(oldSettingName,undefined);const list=oldSetting.get();if(!Array.isArray(list))
return;const newList=[];for(let i=0;i<list.length;++i){const value=list[i];const device={};device['title']=value['title'];device['type']='unknown';device['user-agent']=value['userAgent'];device['capabilities']=[];if(value['touch'])
device['capabilities'].push('touch');if(value['mobile'])
device['capabilities'].push('mobile');device['screen']={};device['screen']['vertical']={width:value['width'],height:value['height']};device['screen']['horizontal']={width:value['height'],height:value['width']};device['screen']['device-pixel-ratio']=value['deviceScaleFactor'];device['modes']=[];device['show-by-default']=true;device['show']='Default';newList.push(device);}
if(newList.length)
Common.settings.createSetting(newSettingName,[]).set(newList);oldSetting.remove();}
_updateVersionFrom11To12(){this._migrateSettingsFromLocalStorage();}
_updateVersionFrom12To13(){this._migrateSettingsFromLocalStorage();Common.settings.createSetting('timelineOverviewMode','').remove();}
_updateVersionFrom13To14(){const defaultValue={'throughput':-1,'latency':0};Common.settings.createSetting('networkConditions',defaultValue).set(defaultValue);}
_updateVersionFrom14To15(){const setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});const oldValue=setting.get();const newValue={};for(const fileSystemPath in oldValue){newValue[fileSystemPath]=[];for(const entry of oldValue[fileSystemPath])
newValue[fileSystemPath].push(entry.path);}
setting.set(newValue);}
_updateVersionFrom15To16(){const setting=Common.settings.createSetting('InspectorView.panelOrder',{});const tabOrders=setting.get();for(const key of Object.keys(tabOrders))
tabOrders[key]=(tabOrders[key]+1)*10;setting.set(tabOrders);}
_updateVersionFrom16To17(){const setting=Common.settings.createSetting('networkConditionsCustomProfiles',[]);const oldValue=setting.get();const newValue=[];if(Array.isArray(oldValue)){for(const preset of oldValue){if(typeof preset.title==='string'&&typeof preset.value==='object'&&typeof preset.value.throughput==='number'&&typeof preset.value.latency==='number'){newValue.push({title:preset.title,value:{download:preset.value.throughput,upload:preset.value.throughput,latency:preset.value.latency}});}}}
setting.set(newValue);}
_updateVersionFrom17To18(){const setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});const oldValue=setting.get();const newValue={};for(const oldKey in oldValue){let newKey=oldKey.replace(/\\/g,'/');if(!newKey.startsWith('file://')){if(newKey.startsWith('/'))
newKey='file://'+newKey;else
newKey='file:///'+newKey;}
newValue[newKey]=oldValue[oldKey];}
setting.set(newValue);}
_updateVersionFrom18To19(){const defaultColumns={status:true,type:true,initiator:true,size:true,time:true};const visibleColumnSettings=Common.settings.createSetting('networkLogColumnsVisibility',defaultColumns);const visibleColumns=visibleColumnSettings.get();visibleColumns.name=true;visibleColumns.timeline=true;const configs={};for(const columnId in visibleColumns){if(!visibleColumns.hasOwnProperty(columnId))
continue;configs[columnId.toLowerCase()]={visible:visibleColumns[columnId]};}
const newSetting=Common.settings.createSetting('networkLogColumns',{});newSetting.set(configs);visibleColumnSettings.remove();}
_updateVersionFrom19To20(){const oldSetting=Common.settings.createSetting('InspectorView.panelOrder',{});const newSetting=Common.settings.createSetting('panel-tabOrder',{});newSetting.set(oldSetting.get());oldSetting.remove();}
_updateVersionFrom20To21(){const networkColumns=Common.settings.createSetting('networkLogColumns',{});const columns=(networkColumns.get());delete columns['timeline'];delete columns['waterfall'];networkColumns.set(columns);}
_updateVersionFrom21To22(){const breakpointsSetting=Common.settings.createLocalSetting('breakpoints',[]);const breakpoints=breakpointsSetting.get();for(const breakpoint of breakpoints){breakpoint['url']=breakpoint['sourceFileId'];delete breakpoint['sourceFileId'];}
breakpointsSetting.set(breakpoints);}
_updateVersionFrom22To23(){}
_updateVersionFrom23To24(){const oldSetting=Common.settings.createSetting('searchInContentScripts',false);const newSetting=Common.settings.createSetting('searchInAnonymousAndContentScripts',false);newSetting.set(oldSetting.get());oldSetting.remove();}
_updateVersionFrom24To25(){const defaultColumns={status:true,type:true,initiator:true,size:true,time:true};const networkLogColumnsSetting=Common.settings.createSetting('networkLogColumns',defaultColumns);const columns=networkLogColumnsSetting.get();delete columns.product;networkLogColumnsSetting.set(columns);}
_updateVersionFrom25To26(){const oldSetting=Common.settings.createSetting('messageURLFilters',{});const urls=Object.keys(oldSetting.get());const textFilter=urls.map(url=>`-url:${url}`).join(' ');if(textFilter){const textFilterSetting=Common.settings.createSetting('console.textFilter','');const suffix=textFilterSetting.get()?` ${textFilterSetting.get()}`:'';textFilterSetting.set(`${textFilter}${suffix}`);}
oldSetting.remove();}
_migrateSettingsFromLocalStorage(){const localSettings=new Set(['advancedSearchConfig','breakpoints','consoleHistory','domBreakpoints','eventListenerBreakpoints','fileSystemMapping','lastSelectedSourcesSidebarPaneTab','previouslyViewedFiles','savedURLs','watchExpressions','workspaceExcludedFolders','xhrBreakpoints']);if(!window.localStorage)
return;for(const key in window.localStorage){if(localSettings.has(key))
continue;const value=window.localStorage[key];window.localStorage.removeItem(key);Common.settings._globalStorage[key]=value;}}
_clearBreakpointsWhenTooMany(breakpointsSetting,maxBreakpointsCount){if(breakpointsSetting.get().length>maxBreakpointsCount)
breakpointsSetting.set([]);}};Common.VersionController._currentVersionName='inspectorVersion';Common.VersionController.currentVersion=26;Common.settings;Common.SettingStorageType={Global:Symbol('Global'),Local:Symbol('Local'),Session:Symbol('Session')};Common.moduleSetting=function(settingName){return Common.settings.moduleSetting(settingName);};Common.settingForTest=function(settingName){return Common.settings.settingForTest(settingName);};;Common.StaticContentProvider=class{constructor(contentURL,contentType,lazyContent){this._contentURL=contentURL;this._contentType=contentType;this._lazyContent=lazyContent;}
static fromString(contentURL,contentType,content){const lazyContent=()=>Promise.resolve(content);return new Common.StaticContentProvider(contentURL,contentType,lazyContent);}
contentURL(){return this._contentURL;}
contentType(){return this._contentType;}
contentEncoded(){return Promise.resolve(false);}
requestContent(){return this._lazyContent();}
async searchInContent(query,caseSensitive,isRegex){const content=await this._lazyContent();return content?Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex):[];}};;Common.OutputStream=function(){};Common.OutputStream.prototype={write(data){},close(){}};Common.StringOutputStream=class{constructor(){this._data='';}
async write(chunk){this._data+=chunk;}
close(){}
data(){return this._data;}};;Common.Segment=class{constructor(begin,end,data){if(begin>end)
console.assert(false,'Invalid segment');this.begin=begin;this.end=end;this.data=data;}
intersects(that){return this.begin<that.end&&that.begin<this.end;}};Common.SegmentedRange=class{constructor(mergeCallback){this._segments=[];this._mergeCallback=mergeCallback;}
append(newSegment){let startIndex=this._segments.lowerBound(newSegment,(a,b)=>a.begin-b.begin);let endIndex=startIndex;let merged=null;if(startIndex>0){const precedingSegment=this._segments[startIndex-1];merged=this._tryMerge(precedingSegment,newSegment);if(merged){--startIndex;newSegment=merged;}else if(this._segments[startIndex-1].end>=newSegment.begin){if(newSegment.end<precedingSegment.end){this._segments.splice(startIndex,0,new Common.Segment(newSegment.end,precedingSegment.end,precedingSegment.data));}
precedingSegment.end=newSegment.begin;}}
while(endIndex<this._segments.length&&this._segments[endIndex].end<=newSegment.end)
++endIndex;if(endIndex<this._segments.length){merged=this._tryMerge(newSegment,this._segments[endIndex]);if(merged){endIndex++;newSegment=merged;}else if(newSegment.intersects(this._segments[endIndex])){this._segments[endIndex].begin=newSegment.end;}}
this._segments.splice(startIndex,endIndex-startIndex,newSegment);}
appendRange(that){that.segments().forEach(segment=>this.append(segment));}
segments(){return this._segments;}
_tryMerge(first,second){const merged=this._mergeCallback&&this._mergeCallback(first,second);if(!merged)
return null;merged.begin=first.begin;merged.end=Math.max(first.end,second.end);return merged;}};;Common.Throttler=class{constructor(timeout){this._timeout=timeout;this._isRunningProcess=false;this._asSoonAsPossible=false;this._process=null;this._lastCompleteTime=0;this._schedulePromise=new Promise(fulfill=>{this._scheduleResolve=fulfill;});}
_processCompleted(){this._lastCompleteTime=this._getTime();this._isRunningProcess=false;if(this._process)
this._innerSchedule(false);this._processCompletedForTests();}
_processCompletedForTests(){}
_onTimeout(){delete this._processTimeout;this._asSoonAsPossible=false;this._isRunningProcess=true;Promise.resolve().then(this._process).catch(console.error.bind(console)).then(this._processCompleted.bind(this)).then(this._scheduleResolve);this._schedulePromise=new Promise(fulfill=>{this._scheduleResolve=fulfill;});this._process=null;}
schedule(process,asSoonAsPossible){this._process=process;const hasScheduledTasks=!!this._processTimeout||this._isRunningProcess;const okToFire=this._getTime()-this._lastCompleteTime>this._timeout;asSoonAsPossible=!!asSoonAsPossible||(!hasScheduledTasks&&okToFire);const forceTimerUpdate=asSoonAsPossible&&!this._asSoonAsPossible;this._asSoonAsPossible=this._asSoonAsPossible||asSoonAsPossible;this._innerSchedule(forceTimerUpdate);return this._schedulePromise;}
_innerSchedule(forceTimerUpdate){if(this._isRunningProcess)
return;if(this._processTimeout&&!forceTimerUpdate)
return;if(this._processTimeout)
this._clearTimeout(this._processTimeout);const timeout=this._asSoonAsPossible?0:this._timeout;this._processTimeout=this._setTimeout(this._onTimeout.bind(this),timeout);}
_clearTimeout(timeoutId){clearTimeout(timeoutId);}
_setTimeout(operation,timeout){return setTimeout(operation,timeout);}
_getTime(){return window.performance.now();}};Common.Throttler.FinishCallback;;Common.Trie=class{constructor(){this.clear();}
add(word){let node=this._root;++this._wordsInSubtree[this._root];for(let i=0;i<word.length;++i){const edge=word[i];let next=this._edges[node][edge];if(!next){if(this._freeNodes.length){next=this._freeNodes.pop();}else{next=this._size++;this._isWord.push(false);this._wordsInSubtree.push(0);this._edges.push({__proto__:null});}
this._edges[node][edge]=next;}
++this._wordsInSubtree[next];node=next;}
this._isWord[node]=true;}
remove(word){if(!this.has(word))
return false;let node=this._root;--this._wordsInSubtree[this._root];for(let i=0;i<word.length;++i){const edge=word[i];const next=this._edges[node][edge];if(!--this._wordsInSubtree[next]){delete this._edges[node][edge];this._freeNodes.push(next);}
node=next;}
this._isWord[node]=false;return true;}
has(word){let node=this._root;for(let i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node)
return false;}
return this._isWord[node];}
words(prefix){prefix=prefix||'';let node=this._root;for(let i=0;i<prefix.length;++i){node=this._edges[node][prefix[i]];if(!node)
return[];}
const results=[];this._dfs(node,prefix,results);return results;}
_dfs(node,prefix,results){if(this._isWord[node])
results.push(prefix);const edges=this._edges[node];for(const edge in edges)
this._dfs(edges[edge],prefix+edge,results);}
longestPrefix(word,fullWordOnly){let node=this._root;let wordIndex=0;for(let i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node)
break;if(!fullWordOnly||this._isWord[node])
wordIndex=i+1;}
return word.substring(0,wordIndex);}
clear(){this._size=1;this._root=0;this._edges=[{__proto__:null}];this._isWord=[false];this._wordsInSubtree=[0];this._freeNodes=[];}};;self['Common']=self['Common']||{};Common.UIString=function(string,vararg){return String.vsprintf(Common.localize(string),Array.prototype.slice.call(arguments,1));};Common.localize=function(string){return string;};Common.UIStringFormat=class{constructor(format){this._localizedFormat=Common.localize(format);this._tokenizedFormat=String.tokenizeFormatString(this._localizedFormat,String.standardFormatters);}
static _append(a,b){return a+b;}
format(vararg){return String.format(this._localizedFormat,arguments,String.standardFormatters,'',Common.UIStringFormat._append,this._tokenizedFormat).formattedResult;}};Common._substitutionStrings=new WeakMap();self.ls=function(strings,vararg){if(typeof strings==='string')
return strings;let substitutionString=Common._substitutionStrings.get(strings);if(!substitutionString){substitutionString=strings.join('%s');Common._substitutionStrings.set(strings,substitutionString);}
return Common.UIString(substitutionString,...Array.prototype.slice.call(arguments,1));};;Common.Revealer=function(){};Common.Revealer.reveal=function(revealable,omitFocus){if(!revealable)
return Promise.reject(new Error('Can\'t reveal '+revealable));return self.runtime.allInstances(Common.Revealer,revealable).then(reveal);function reveal(revealers){const promises=[];for(let i=0;i<revealers.length;++i)
promises.push(revealers[i].reveal((revealable),omitFocus));return Promise.race(promises);}};Common.Revealer.revealDestination=function(revealable){const extension=self.runtime.extension(Common.Revealer,revealable);if(!extension)
return null;return extension.descriptor()['destination'];};Common.Revealer.prototype={reveal(object,omitFocus){}};Common.App=function(){};Common.App.prototype={presentUI(document){}};Common.AppProvider=function(){};Common.AppProvider.prototype={createApp(){}};Common.QueryParamHandler=function(){};Common.QueryParamHandler.prototype={handleQueryParam(value){}};Common.Runnable=function(){};Common.Runnable.prototype={run(){}};Common.Linkifier=function(){};Common.Linkifier.prototype={linkify(object,options){}};Common.Linkifier.linkify=function(object,options){if(!object)
return Promise.reject(new Error('Can\'t linkify '+object));return self.runtime.extension(Common.Linkifier,object).instance().then(linkifier=>linkifier.linkify(object,options));};Common.Linkifier.Options;Common.JavaScriptMetadata=function(){};Common.JavaScriptMetadata.prototype={signaturesForNativeFunction(name){},signaturesForInstanceMethod(name,receiverClassName){},signaturesForStaticMethod(name,receiverConstructorName){}};;Common.CharacterIdMap=class{constructor(){this._elementToCharacter=new Map();this._characterToElement=new Map();this._charCode=33;}
toChar(object){let character=this._elementToCharacter.get(object);if(!character){if(this._charCode>=0xFFFF)
throw new Error('CharacterIdMap ran out of capacity!');character=String.fromCharCode(this._charCode++);this._elementToCharacter.set(object,character);this._characterToElement.set(character,object);}
return character;}
fromChar(character){const object=this._characterToElement.get(character);if(object===undefined)
return null;return object;}};;self['HeapSnapshotWorker']=self['HeapSnapshotWorker']||{};HeapSnapshotWorker.AllocationProfile=class{constructor(profile,liveObjectStats){this._strings=profile.strings;this._liveObjectStats=liveObjectStats;this._nextNodeId=1;this._functionInfos=[];this._idToNode={};this._idToTopDownNode={};this._collapsedTopNodeIdToFunctionInfo={};this._traceTops=null;this._buildFunctionAllocationInfos(profile);this._traceTree=this._buildAllocationTree(profile,liveObjectStats);}
_buildFunctionAllocationInfos(profile){const strings=this._strings;const functionInfoFields=profile.snapshot.meta.trace_function_info_fields;const functionNameOffset=functionInfoFields.indexOf('name');const scriptNameOffset=functionInfoFields.indexOf('script_name');const scriptIdOffset=functionInfoFields.indexOf('script_id');const lineOffset=functionInfoFields.indexOf('line');const columnOffset=functionInfoFields.indexOf('column');const functionInfoFieldCount=functionInfoFields.length;const rawInfos=profile.trace_function_infos;const infoLength=rawInfos.length;const functionInfos=this._functionInfos=new Array(infoLength/functionInfoFieldCount);let index=0;for(let i=0;i<infoLength;i+=functionInfoFieldCount){functionInfos[index++]=new HeapSnapshotWorker.FunctionAllocationInfo(strings[rawInfos[i+functionNameOffset]],strings[rawInfos[i+scriptNameOffset]],rawInfos[i+scriptIdOffset],rawInfos[i+lineOffset],rawInfos[i+columnOffset]);}}
_buildAllocationTree(profile,liveObjectStats){const traceTreeRaw=profile.trace_tree;const functionInfos=this._functionInfos;const idToTopDownNode=this._idToTopDownNode;const traceNodeFields=profile.snapshot.meta.trace_node_fields;const nodeIdOffset=traceNodeFields.indexOf('id');const functionInfoIndexOffset=traceNodeFields.indexOf('function_info_index');const allocationCountOffset=traceNodeFields.indexOf('count');const allocationSizeOffset=traceNodeFields.indexOf('size');const childrenOffset=traceNodeFields.indexOf('children');const nodeFieldCount=traceNodeFields.length;function traverseNode(rawNodeArray,nodeOffset,parent){const functionInfo=functionInfos[rawNodeArray[nodeOffset+functionInfoIndexOffset]];const id=rawNodeArray[nodeOffset+nodeIdOffset];const stats=liveObjectStats[id];const liveCount=stats?stats.count:0;const liveSize=stats?stats.size:0;const result=new HeapSnapshotWorker.TopDownAllocationNode(id,functionInfo,rawNodeArray[nodeOffset+allocationCountOffset],rawNodeArray[nodeOffset+allocationSizeOffset],liveCount,liveSize,parent);idToTopDownNode[id]=result;functionInfo.addTraceTopNode(result);const rawChildren=rawNodeArray[nodeOffset+childrenOffset];for(let i=0;i<rawChildren.length;i+=nodeFieldCount)
result.children.push(traverseNode(rawChildren,i,result));return result;}
return traverseNode(traceTreeRaw,0,null);}
serializeTraceTops(){if(this._traceTops)
return this._traceTops;const result=this._traceTops=[];const functionInfos=this._functionInfos;for(let i=0;i<functionInfos.length;i++){const info=functionInfos[i];if(info.totalCount===0)
continue;const nodeId=this._nextNodeId++;const isRoot=i===0;result.push(this._serializeNode(nodeId,info,info.totalCount,info.totalSize,info.totalLiveCount,info.totalLiveSize,!isRoot));this._collapsedTopNodeIdToFunctionInfo[nodeId]=info;}
result.sort(function(a,b){return b.size-a.size;});return result;}
serializeCallers(nodeId){let node=this._ensureBottomUpNode(nodeId);const nodesWithSingleCaller=[];while(node.callers().length===1){node=node.callers()[0];nodesWithSingleCaller.push(this._serializeCaller(node));}
const branchingCallers=[];const callers=node.callers();for(let i=0;i<callers.length;i++)
branchingCallers.push(this._serializeCaller(callers[i]));return new HeapSnapshotModel.AllocationNodeCallers(nodesWithSingleCaller,branchingCallers);}
serializeAllocationStack(traceNodeId){let node=this._idToTopDownNode[traceNodeId];const result=[];while(node){const functionInfo=node.functionInfo;result.push(new HeapSnapshotModel.AllocationStackFrame(functionInfo.functionName,functionInfo.scriptName,functionInfo.scriptId,functionInfo.line,functionInfo.column));node=node.parent;}
return result;}
traceIds(allocationNodeId){return this._ensureBottomUpNode(allocationNodeId).traceTopIds;}
_ensureBottomUpNode(nodeId){let node=this._idToNode[nodeId];if(!node){const functionInfo=this._collapsedTopNodeIdToFunctionInfo[nodeId];node=functionInfo.bottomUpRoot();delete this._collapsedTopNodeIdToFunctionInfo[nodeId];this._idToNode[nodeId]=node;}
return node;}
_serializeCaller(node){const callerId=this._nextNodeId++;this._idToNode[callerId]=node;return this._serializeNode(callerId,node.functionInfo,node.allocationCount,node.allocationSize,node.liveCount,node.liveSize,node.hasCallers());}
_serializeNode(nodeId,functionInfo,count,size,liveCount,liveSize,hasChildren){return new HeapSnapshotModel.SerializedAllocationNode(nodeId,functionInfo.functionName,functionInfo.scriptName,functionInfo.scriptId,functionInfo.line,functionInfo.column,count,size,liveCount,liveSize,hasChildren);}};HeapSnapshotWorker.TopDownAllocationNode=class{constructor(id,functionInfo,count,size,liveCount,liveSize,parent){this.id=id;this.functionInfo=functionInfo;this.allocationCount=count;this.allocationSize=size;this.liveCount=liveCount;this.liveSize=liveSize;this.parent=parent;this.children=[];}};HeapSnapshotWorker.BottomUpAllocationNode=class{constructor(functionInfo){this.functionInfo=functionInfo;this.allocationCount=0;this.allocationSize=0;this.liveCount=0;this.liveSize=0;this.traceTopIds=[];this._callers=[];}
addCaller(traceNode){const functionInfo=traceNode.functionInfo;let result;for(let i=0;i<this._callers.length;i++){const caller=this._callers[i];if(caller.functionInfo===functionInfo){result=caller;break;}}
if(!result){result=new HeapSnapshotWorker.BottomUpAllocationNode(functionInfo);this._callers.push(result);}
return result;}
callers(){return this._callers;}
hasCallers(){return this._callers.length>0;}};HeapSnapshotWorker.FunctionAllocationInfo=class{constructor(functionName,scriptName,scriptId,line,column){this.functionName=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;this.totalCount=0;this.totalSize=0;this.totalLiveCount=0;this.totalLiveSize=0;this._traceTops=[];}
addTraceTopNode(node){if(node.allocationCount===0)
return;this._traceTops.push(node);this.totalCount+=node.allocationCount;this.totalSize+=node.allocationSize;this.totalLiveCount+=node.liveCount;this.totalLiveSize+=node.liveSize;}
bottomUpRoot(){if(!this._traceTops.length)
return null;if(!this._bottomUpTree)
this._buildAllocationTraceTree();return this._bottomUpTree;}
_buildAllocationTraceTree(){this._bottomUpTree=new HeapSnapshotWorker.BottomUpAllocationNode(this);for(let i=0;i<this._traceTops.length;i++){let node=this._traceTops[i];let bottomUpNode=this._bottomUpTree;const count=node.allocationCount;const size=node.allocationSize;const liveCount=node.liveCount;const liveSize=node.liveSize;const traceId=node.id;while(true){bottomUpNode.allocationCount+=count;bottomUpNode.allocationSize+=size;bottomUpNode.liveCount+=liveCount;bottomUpNode.liveSize+=liveSize;bottomUpNode.traceTopIds.push(traceId);node=node.parent;if(node===null)
break;bottomUpNode=bottomUpNode.addCaller(node);}}}};;HeapSnapshotWorker.HeapSnapshotItem=function(){};HeapSnapshotWorker.HeapSnapshotItem.prototype={itemIndex(){},serialize(){}};HeapSnapshotWorker.HeapSnapshotEdge=class{constructor(snapshot,edgeIndex){this._snapshot=snapshot;this._edges=snapshot.containmentEdges;this.edgeIndex=edgeIndex||0;}
clone(){return new HeapSnapshotWorker.HeapSnapshotEdge(this._snapshot,this.edgeIndex);}
hasStringName(){throw new Error('Not implemented');}
name(){throw new Error('Not implemented');}
node(){return this._snapshot.createNode(this.nodeIndex());}
nodeIndex(){return this._edges[this.edgeIndex+this._snapshot._edgeToNodeOffset];}
toString(){return'HeapSnapshotEdge: '+this.name();}
type(){return this._snapshot._edgeTypes[this.rawType()];}
itemIndex(){return this.edgeIndex;}
serialize(){return new HeapSnapshotModel.Edge(this.name(),this.node().serialize(),this.type(),this.edgeIndex);}
rawType(){return this._edges[this.edgeIndex+this._snapshot._edgeTypeOffset];}};HeapSnapshotWorker.HeapSnapshotItemIterator=function(){};HeapSnapshotWorker.HeapSnapshotItemIterator.prototype={hasNext(){},item(){},next(){}};HeapSnapshotWorker.HeapSnapshotItemIndexProvider=function(){};HeapSnapshotWorker.HeapSnapshotItemIndexProvider.prototype={itemForIndex(newIndex){},};HeapSnapshotWorker.HeapSnapshotNodeIndexProvider=class{constructor(snapshot){this._node=snapshot.createNode();}
itemForIndex(index){this._node.nodeIndex=index;return this._node;}};HeapSnapshotWorker.HeapSnapshotEdgeIndexProvider=class{constructor(snapshot){this._edge=snapshot.createEdge(0);}
itemForIndex(index){this._edge.edgeIndex=index;return this._edge;}};HeapSnapshotWorker.HeapSnapshotRetainerEdgeIndexProvider=class{constructor(snapshot){this._retainerEdge=snapshot.createRetainingEdge(0);}
itemForIndex(index){this._retainerEdge.setRetainerIndex(index);return this._retainerEdge;}};HeapSnapshotWorker.HeapSnapshotEdgeIterator=class{constructor(node){this._sourceNode=node;this.edge=node._snapshot.createEdge(node.edgeIndexesStart());}
hasNext(){return this.edge.edgeIndex<this._sourceNode.edgeIndexesEnd();}
item(){return this.edge;}
next(){this.edge.edgeIndex+=this.edge._snapshot._edgeFieldsCount;}};HeapSnapshotWorker.HeapSnapshotRetainerEdge=class{constructor(snapshot,retainerIndex){this._snapshot=snapshot;this.setRetainerIndex(retainerIndex);}
clone(){return new HeapSnapshotWorker.HeapSnapshotRetainerEdge(this._snapshot,this.retainerIndex());}
hasStringName(){return this._edge().hasStringName();}
name(){return this._edge().name();}
node(){return this._node();}
nodeIndex(){return this._retainingNodeIndex;}
retainerIndex(){return this._retainerIndex;}
setRetainerIndex(retainerIndex){if(retainerIndex===this._retainerIndex)
return;this._retainerIndex=retainerIndex;this._globalEdgeIndex=this._snapshot._retainingEdges[retainerIndex];this._retainingNodeIndex=this._snapshot._retainingNodes[retainerIndex];this._edgeInstance=null;this._nodeInstance=null;}
set edgeIndex(edgeIndex){this.setRetainerIndex(edgeIndex);}
_node(){if(!this._nodeInstance)
this._nodeInstance=this._snapshot.createNode(this._retainingNodeIndex);return this._nodeInstance;}
_edge(){if(!this._edgeInstance)
this._edgeInstance=this._snapshot.createEdge(this._globalEdgeIndex);return this._edgeInstance;}
toString(){return this._edge().toString();}
itemIndex(){return this._retainerIndex;}
serialize(){return new HeapSnapshotModel.Edge(this.name(),this.node().serialize(),this.type(),this._globalEdgeIndex);}
type(){return this._edge().type();}};HeapSnapshotWorker.HeapSnapshotRetainerEdgeIterator=class{constructor(retainedNode){const snapshot=retainedNode._snapshot;const retainedNodeOrdinal=retainedNode.ordinal();const retainerIndex=snapshot._firstRetainerIndex[retainedNodeOrdinal];this._retainersEnd=snapshot._firstRetainerIndex[retainedNodeOrdinal+1];this.retainer=snapshot.createRetainingEdge(retainerIndex);}
hasNext(){return this.retainer.retainerIndex()<this._retainersEnd;}
item(){return this.retainer;}
next(){this.retainer.setRetainerIndex(this.retainer.retainerIndex()+1);}};HeapSnapshotWorker.HeapSnapshotNode=class{constructor(snapshot,nodeIndex){this._snapshot=snapshot;this.nodeIndex=nodeIndex||0;}
distance(){return this._snapshot._nodeDistances[this.nodeIndex/this._snapshot._nodeFieldCount];}
className(){throw new Error('Not implemented');}
classIndex(){throw new Error('Not implemented');}
dominatorIndex(){const nodeFieldCount=this._snapshot._nodeFieldCount;return this._snapshot._dominatorsTree[this.nodeIndex/this._snapshot._nodeFieldCount]*nodeFieldCount;}
edges(){return new HeapSnapshotWorker.HeapSnapshotEdgeIterator(this);}
edgesCount(){return(this.edgeIndexesEnd()-this.edgeIndexesStart())/this._snapshot._edgeFieldsCount;}
id(){throw new Error('Not implemented');}
isRoot(){return this.nodeIndex===this._snapshot._rootNodeIndex;}
name(){return this._snapshot.strings[this._name()];}
retainedSize(){return this._snapshot._retainedSizes[this.ordinal()];}
retainers(){return new HeapSnapshotWorker.HeapSnapshotRetainerEdgeIterator(this);}
retainersCount(){const snapshot=this._snapshot;const ordinal=this.ordinal();return snapshot._firstRetainerIndex[ordinal+1]-snapshot._firstRetainerIndex[ordinal];}
selfSize(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeSelfSizeOffset];}
type(){return this._snapshot._nodeTypes[this.rawType()];}
traceNodeId(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeTraceNodeIdOffset];}
itemIndex(){return this.nodeIndex;}
serialize(){return new HeapSnapshotModel.Node(this.id(),this.name(),this.distance(),this.nodeIndex,this.retainedSize(),this.selfSize(),this.type());}
_name(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeNameOffset];}
edgeIndexesStart(){return this._snapshot._firstEdgeIndexes[this.ordinal()];}
edgeIndexesEnd(){return this._snapshot._firstEdgeIndexes[this.ordinal()+1];}
ordinal(){return this.nodeIndex/this._snapshot._nodeFieldCount;}
_nextNodeIndex(){return this.nodeIndex+this._snapshot._nodeFieldCount;}
rawType(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeTypeOffset];}};HeapSnapshotWorker.HeapSnapshotNodeIterator=class{constructor(node){this.node=node;this._nodesLength=node._snapshot.nodes.length;}
hasNext(){return this.node.nodeIndex<this._nodesLength;}
item(){return this.node;}
next(){this.node.nodeIndex=this.node._nextNodeIndex();}};HeapSnapshotWorker.HeapSnapshotIndexRangeIterator=class{constructor(itemProvider,indexes){this._itemProvider=itemProvider;this._indexes=indexes;this._position=0;}
hasNext(){return this._position<this._indexes.length;}
item(){const index=this._indexes[this._position];return this._itemProvider.itemForIndex(index);}
next(){++this._position;}};HeapSnapshotWorker.HeapSnapshotFilteredIterator=class{constructor(iterator,filter){this._iterator=iterator;this._filter=filter;this._skipFilteredItems();}
hasNext(){return this._iterator.hasNext();}
item(){return this._iterator.item();}
next(){this._iterator.next();this._skipFilteredItems();}
_skipFilteredItems(){while(this._iterator.hasNext()&&!this._filter(this._iterator.item()))
this._iterator.next();}};HeapSnapshotWorker.HeapSnapshotProgress=class{constructor(dispatcher){this._dispatcher=dispatcher;}
updateStatus(status){this._sendUpdateEvent(Common.UIString(status));}
updateProgress(title,value,total){const percentValue=((total?(value/total):0)*100).toFixed(0);this._sendUpdateEvent(Common.UIString(title,percentValue));}
reportProblem(error){if(this._dispatcher)
this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotProgressEvent.BrokenSnapshot,error);}
_sendUpdateEvent(text){if(this._dispatcher)
this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotProgressEvent.Update,text);}};HeapSnapshotWorker.HeapSnapshotProblemReport=class{constructor(title){this._errors=[title];}
addError(error){if(this._errors.length>100)
return;this._errors.push(error);}
toString(){return this._errors.join('\n ');}};HeapSnapshotWorker.HeapSnapshot=class{constructor(profile,progress){this.nodes=profile.nodes;this.containmentEdges=profile.edges;this._metaNode=profile.snapshot.meta;this._rawSamples=profile.samples;this._samples=null;this.strings=profile.strings;this._locations=profile.locations;this._progress=progress;this._noDistance=-5;this._rootNodeIndex=0;if(profile.snapshot.root_index)
this._rootNodeIndex=profile.snapshot.root_index;this._snapshotDiffs={};this._aggregatesForDiff=null;this._aggregates={};this._aggregatesSortedFlags={};this._profile=profile;}
initialize(){const meta=this._metaNode;this._nodeTypeOffset=meta.node_fields.indexOf('type');this._nodeNameOffset=meta.node_fields.indexOf('name');this._nodeIdOffset=meta.node_fields.indexOf('id');this._nodeSelfSizeOffset=meta.node_fields.indexOf('self_size');this._nodeEdgeCountOffset=meta.node_fields.indexOf('edge_count');this._nodeTraceNodeIdOffset=meta.node_fields.indexOf('trace_node_id');this._nodeFieldCount=meta.node_fields.length;this._nodeTypes=meta.node_types[this._nodeTypeOffset];this._nodeArrayType=this._nodeTypes.indexOf('array');this._nodeHiddenType=this._nodeTypes.indexOf('hidden');this._nodeObjectType=this._nodeTypes.indexOf('object');this._nodeNativeType=this._nodeTypes.indexOf('native');this._nodeConsStringType=this._nodeTypes.indexOf('concatenated string');this._nodeSlicedStringType=this._nodeTypes.indexOf('sliced string');this._nodeCodeType=this._nodeTypes.indexOf('code');this._nodeSyntheticType=this._nodeTypes.indexOf('synthetic');this._edgeFieldsCount=meta.edge_fields.length;this._edgeTypeOffset=meta.edge_fields.indexOf('type');this._edgeNameOffset=meta.edge_fields.indexOf('name_or_index');this._edgeToNodeOffset=meta.edge_fields.indexOf('to_node');this._edgeTypes=meta.edge_types[this._edgeTypeOffset];this._edgeTypes.push('invisible');this._edgeElementType=this._edgeTypes.indexOf('element');this._edgeHiddenType=this._edgeTypes.indexOf('hidden');this._edgeInternalType=this._edgeTypes.indexOf('internal');this._edgeShortcutType=this._edgeTypes.indexOf('shortcut');this._edgeWeakType=this._edgeTypes.indexOf('weak');this._edgeInvisibleType=this._edgeTypes.indexOf('invisible');const location_fields=meta.location_fields||[];this._locationIndexOffset=location_fields.indexOf('object_index');this._locationScriptIdOffset=location_fields.indexOf('script_id');this._locationLineOffset=location_fields.indexOf('line');this._locationColumnOffset=location_fields.indexOf('column');this._locationFieldCount=location_fields.length;this.nodeCount=this.nodes.length/this._nodeFieldCount;this._edgeCount=this.containmentEdges.length/this._edgeFieldsCount;this._retainedSizes=new Float64Array(this.nodeCount);this._firstEdgeIndexes=new Uint32Array(this.nodeCount+1);this._retainingNodes=new Uint32Array(this._edgeCount);this._retainingEdges=new Uint32Array(this._edgeCount);this._firstRetainerIndex=new Uint32Array(this.nodeCount+1);this._nodeDistances=new Int32Array(this.nodeCount);this._firstDominatedNodeIndex=new Uint32Array(this.nodeCount+1);this._dominatedNodes=new Uint32Array(this.nodeCount-1);this._progress.updateStatus('Building edge indexes\u2026');this._buildEdgeIndexes();this._progress.updateStatus('Building retainers\u2026');this._buildRetainers();this._progress.updateStatus('Calculating node flags\u2026');this.calculateFlags();this._progress.updateStatus('Calculating distances\u2026');this.calculateDistances();this._progress.updateStatus('Building postorder index\u2026');const result=this._buildPostOrderIndex();this._progress.updateStatus('Building dominator tree\u2026');this._dominatorsTree=this._buildDominatorTree(result.postOrderIndex2NodeOrdinal,result.nodeOrdinal2PostOrderIndex);this._progress.updateStatus('Calculating retained sizes\u2026');this._calculateRetainedSizes(result.postOrderIndex2NodeOrdinal);this._progress.updateStatus('Building dominated nodes\u2026');this._buildDominatedNodes();this._progress.updateStatus('Calculating statistics\u2026');this.calculateStatistics();this._progress.updateStatus('Calculating samples\u2026');this._buildSamples();this._progress.updateStatus('Building locations\u2026');this._buildLocationMap();this._progress.updateStatus('Finished processing.');if(this._profile.snapshot.trace_function_count){this._progress.updateStatus('Building allocation statistics\u2026');const nodes=this.nodes;const nodesLength=nodes.length;const nodeFieldCount=this._nodeFieldCount;const node=this.rootNode();const liveObjects={};for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;const traceNodeId=node.traceNodeId();let stats=liveObjects[traceNodeId];if(!stats)
liveObjects[traceNodeId]=stats={count:0,size:0,ids:[]};stats.count++;stats.size+=node.selfSize();stats.ids.push(node.id());}
this._allocationProfile=new HeapSnapshotWorker.AllocationProfile(this._profile,liveObjects);this._progress.updateStatus('Done');}}
_buildEdgeIndexes(){const nodes=this.nodes;const nodeCount=this.nodeCount;const firstEdgeIndexes=this._firstEdgeIndexes;const nodeFieldCount=this._nodeFieldCount;const edgeFieldsCount=this._edgeFieldsCount;const nodeEdgeCountOffset=this._nodeEdgeCountOffset;firstEdgeIndexes[nodeCount]=this.containmentEdges.length;for(let nodeOrdinal=0,edgeIndex=0;nodeOrdinal<nodeCount;++nodeOrdinal){firstEdgeIndexes[nodeOrdinal]=edgeIndex;edgeIndex+=nodes[nodeOrdinal*nodeFieldCount+nodeEdgeCountOffset]*edgeFieldsCount;}}
_buildRetainers(){const retainingNodes=this._retainingNodes;const retainingEdges=this._retainingEdges;const firstRetainerIndex=this._firstRetainerIndex;const containmentEdges=this.containmentEdges;const edgeFieldsCount=this._edgeFieldsCount;const nodeFieldCount=this._nodeFieldCount;const edgeToNodeOffset=this._edgeToNodeOffset;const firstEdgeIndexes=this._firstEdgeIndexes;const nodeCount=this.nodeCount;for(let toNodeFieldIndex=edgeToNodeOffset,l=containmentEdges.length;toNodeFieldIndex<l;toNodeFieldIndex+=edgeFieldsCount){const toNodeIndex=containmentEdges[toNodeFieldIndex];if(toNodeIndex%nodeFieldCount)
throw new Error('Invalid toNodeIndex '+toNodeIndex);++firstRetainerIndex[toNodeIndex/nodeFieldCount];}
for(let i=0,firstUnusedRetainerSlot=0;i<nodeCount;i++){const retainersCount=firstRetainerIndex[i];firstRetainerIndex[i]=firstUnusedRetainerSlot;retainingNodes[firstUnusedRetainerSlot]=retainersCount;firstUnusedRetainerSlot+=retainersCount;}
firstRetainerIndex[nodeCount]=retainingNodes.length;let nextNodeFirstEdgeIndex=firstEdgeIndexes[0];for(let srcNodeOrdinal=0;srcNodeOrdinal<nodeCount;++srcNodeOrdinal){const firstEdgeIndex=nextNodeFirstEdgeIndex;nextNodeFirstEdgeIndex=firstEdgeIndexes[srcNodeOrdinal+1];const srcNodeIndex=srcNodeOrdinal*nodeFieldCount;for(let edgeIndex=firstEdgeIndex;edgeIndex<nextNodeFirstEdgeIndex;edgeIndex+=edgeFieldsCount){const toNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];if(toNodeIndex%nodeFieldCount)
throw new Error('Invalid toNodeIndex '+toNodeIndex);const firstRetainerSlotIndex=firstRetainerIndex[toNodeIndex/nodeFieldCount];const nextUnusedRetainerSlotIndex=firstRetainerSlotIndex+(--retainingNodes[firstRetainerSlotIndex]);retainingNodes[nextUnusedRetainerSlotIndex]=srcNodeIndex;retainingEdges[nextUnusedRetainerSlotIndex]=edgeIndex;}}}
createNode(nodeIndex){throw new Error('Not implemented');}
createEdge(edgeIndex){throw new Error('Not implemented');}
createRetainingEdge(retainerIndex){throw new Error('Not implemented');}
_allNodes(){return new HeapSnapshotWorker.HeapSnapshotNodeIterator(this.rootNode());}
rootNode(){return this.createNode(this._rootNodeIndex);}
get rootNodeIndex(){return this._rootNodeIndex;}
get totalSize(){return this.rootNode().retainedSize();}
_getDominatedIndex(nodeIndex){if(nodeIndex%this._nodeFieldCount)
throw new Error('Invalid nodeIndex: '+nodeIndex);return this._firstDominatedNodeIndex[nodeIndex/this._nodeFieldCount];}
_createFilter(nodeFilter){const minNodeId=nodeFilter.minNodeId;const maxNodeId=nodeFilter.maxNodeId;const allocationNodeId=nodeFilter.allocationNodeId;let filter;if(typeof allocationNodeId==='number'){filter=this._createAllocationStackFilter(allocationNodeId);filter.key='AllocationNodeId: '+allocationNodeId;}else if(typeof minNodeId==='number'&&typeof maxNodeId==='number'){filter=this._createNodeIdFilter(minNodeId,maxNodeId);filter.key='NodeIdRange: '+minNodeId+'..'+maxNodeId;}
return filter;}
search(searchConfig,nodeFilter){const query=searchConfig.query;function filterString(matchedStringIndexes,string,index){if(string.indexOf(query)!==-1)
matchedStringIndexes.add(index);return matchedStringIndexes;}
const regexp=searchConfig.isRegex?new RegExp(query):createPlainTextSearchRegex(query,'i');function filterRegexp(matchedStringIndexes,string,index){if(regexp.test(string))
matchedStringIndexes.add(index);return matchedStringIndexes;}
const stringFilter=(searchConfig.isRegex||!searchConfig.caseSensitive)?filterRegexp:filterString;const stringIndexes=this.strings.reduce(stringFilter,new Set());if(!stringIndexes.size)
return[];const filter=this._createFilter(nodeFilter);const nodeIds=[];const nodesLength=this.nodes.length;const nodes=this.nodes;const nodeNameOffset=this._nodeNameOffset;const nodeIdOffset=this._nodeIdOffset;const nodeFieldCount=this._nodeFieldCount;const node=this.rootNode();for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;if(filter&&!filter(node))
continue;if(stringIndexes.has(nodes[nodeIndex+nodeNameOffset]))
nodeIds.push(nodes[nodeIndex+nodeIdOffset]);}
return nodeIds;}
aggregatesWithFilter(nodeFilter){const filter=this._createFilter(nodeFilter);const key=filter?filter.key:'allObjects';return this.aggregates(false,key,filter);}
_createNodeIdFilter(minNodeId,maxNodeId){function nodeIdFilter(node){const id=node.id();return id>minNodeId&&id<=maxNodeId;}
return nodeIdFilter;}
_createAllocationStackFilter(bottomUpAllocationNodeId){const traceIds=this._allocationProfile.traceIds(bottomUpAllocationNodeId);if(!traceIds.length)
return undefined;const set={};for(let i=0;i<traceIds.length;i++)
set[traceIds[i]]=true;function traceIdFilter(node){return!!set[node.traceNodeId()];}
return traceIdFilter;}
aggregates(sortedIndexes,key,filter){let aggregatesByClassName=key&&this._aggregates[key];if(!aggregatesByClassName){const aggregates=this._buildAggregates(filter);this._calculateClassesRetainedSize(aggregates.aggregatesByClassIndex,filter);aggregatesByClassName=aggregates.aggregatesByClassName;if(key)
this._aggregates[key]=aggregatesByClassName;}
if(sortedIndexes&&(!key||!this._aggregatesSortedFlags[key])){this._sortAggregateIndexes(aggregatesByClassName);if(key)
this._aggregatesSortedFlags[key]=sortedIndexes;}
return aggregatesByClassName;}
allocationTracesTops(){return this._allocationProfile.serializeTraceTops();}
allocationNodeCallers(nodeId){return this._allocationProfile.serializeCallers(nodeId);}
allocationStack(nodeIndex){const node=this.createNode(nodeIndex);const allocationNodeId=node.traceNodeId();if(!allocationNodeId)
return null;return this._allocationProfile.serializeAllocationStack(allocationNodeId);}
aggregatesForDiff(){if(this._aggregatesForDiff)
return this._aggregatesForDiff;const aggregatesByClassName=this.aggregates(true,'allObjects');this._aggregatesForDiff={};const node=this.createNode();for(const className in aggregatesByClassName){const aggregate=aggregatesByClassName[className];const indexes=aggregate.idxs;const ids=new Array(indexes.length);const selfSizes=new Array(indexes.length);for(let i=0;i<indexes.length;i++){node.nodeIndex=indexes[i];ids[i]=node.id();selfSizes[i]=node.selfSize();}
this._aggregatesForDiff[className]={indexes:indexes,ids:ids,selfSizes:selfSizes};}
return this._aggregatesForDiff;}
isUserRoot(node){return true;}
calculateDistances(filter){const nodeCount=this.nodeCount;const distances=this._nodeDistances;const noDistance=this._noDistance;for(let i=0;i<nodeCount;++i)
distances[i]=noDistance;const nodesToVisit=new Uint32Array(this.nodeCount);let nodesToVisitLength=0;for(let iter=this.rootNode().edges();iter.hasNext();iter.next()){const node=iter.edge.node();if(this.isUserRoot(node)){distances[node.ordinal()]=1;nodesToVisit[nodesToVisitLength++]=node.nodeIndex;}}
this._bfs(nodesToVisit,nodesToVisitLength,distances,filter);distances[this.rootNode().ordinal()]=nodesToVisitLength>0?HeapSnapshotModel.baseSystemDistance:0;nodesToVisit[0]=this.rootNode().nodeIndex;nodesToVisitLength=1;this._bfs(nodesToVisit,nodesToVisitLength,distances,filter);}
_bfs(nodesToVisit,nodesToVisitLength,distances,filter){const edgeFieldsCount=this._edgeFieldsCount;const nodeFieldCount=this._nodeFieldCount;const containmentEdges=this.containmentEdges;const firstEdgeIndexes=this._firstEdgeIndexes;const edgeToNodeOffset=this._edgeToNodeOffset;const edgeTypeOffset=this._edgeTypeOffset;const nodeCount=this.nodeCount;const edgeWeakType=this._edgeWeakType;const noDistance=this._noDistance;let index=0;const edge=this.createEdge(0);const node=this.createNode(0);while(index<nodesToVisitLength){const nodeIndex=nodesToVisit[index++];const nodeOrdinal=nodeIndex/nodeFieldCount;const distance=distances[nodeOrdinal]+1;const firstEdgeIndex=firstEdgeIndexes[nodeOrdinal];const edgesEnd=firstEdgeIndexes[nodeOrdinal+1];node.nodeIndex=nodeIndex;for(let edgeIndex=firstEdgeIndex;edgeIndex<edgesEnd;edgeIndex+=edgeFieldsCount){const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(edgeType===edgeWeakType)
continue;const childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];const childNodeOrdinal=childNodeIndex/nodeFieldCount;if(distances[childNodeOrdinal]!==noDistance)
continue;edge.edgeIndex=edgeIndex;if(filter&&!filter(node,edge))
continue;distances[childNodeOrdinal]=distance;nodesToVisit[nodesToVisitLength++]=childNodeIndex;}}
if(nodesToVisitLength>nodeCount){throw new Error('BFS failed. Nodes to visit ('+nodesToVisitLength+') is more than nodes count ('+nodeCount+')');}}
_buildAggregates(filter){const aggregates={};const aggregatesByClassName={};const classIndexes=[];const nodes=this.nodes;const nodesLength=nodes.length;const nodeNativeType=this._nodeNativeType;const nodeFieldCount=this._nodeFieldCount;const selfSizeOffset=this._nodeSelfSizeOffset;const nodeTypeOffset=this._nodeTypeOffset;const node=this.rootNode();const nodeDistances=this._nodeDistances;for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;if(filter&&!filter(node))
continue;const selfSize=nodes[nodeIndex+selfSizeOffset];if(!selfSize&&nodes[nodeIndex+nodeTypeOffset]!==nodeNativeType)
continue;const classIndex=node.classIndex();const nodeOrdinal=nodeIndex/nodeFieldCount;const distance=nodeDistances[nodeOrdinal];if(!(classIndex in aggregates)){const nodeType=node.type();const nameMatters=nodeType==='object'||nodeType==='native';const value={count:1,distance:distance,self:selfSize,maxRet:0,type:nodeType,name:nameMatters?node.name():null,idxs:[nodeIndex]};aggregates[classIndex]=value;classIndexes.push(classIndex);aggregatesByClassName[node.className()]=value;}else{const clss=aggregates[classIndex];clss.distance=Math.min(clss.distance,distance);++clss.count;clss.self+=selfSize;clss.idxs.push(nodeIndex);}}
for(let i=0,l=classIndexes.length;i<l;++i){const classIndex=classIndexes[i];aggregates[classIndex].idxs=aggregates[classIndex].idxs.slice();}
return{aggregatesByClassName:aggregatesByClassName,aggregatesByClassIndex:aggregates};}
_calculateClassesRetainedSize(aggregates,filter){const rootNodeIndex=this._rootNodeIndex;const node=this.createNode(rootNodeIndex);const list=[rootNodeIndex];const sizes=[-1];const classes=[];const seenClassNameIndexes={};const nodeFieldCount=this._nodeFieldCount;const nodeTypeOffset=this._nodeTypeOffset;const nodeNativeType=this._nodeNativeType;const dominatedNodes=this._dominatedNodes;const nodes=this.nodes;const firstDominatedNodeIndex=this._firstDominatedNodeIndex;while(list.length){const nodeIndex=list.pop();node.nodeIndex=nodeIndex;let classIndex=node.classIndex();const seen=!!seenClassNameIndexes[classIndex];const nodeOrdinal=nodeIndex/nodeFieldCount;const dominatedIndexFrom=firstDominatedNodeIndex[nodeOrdinal];const dominatedIndexTo=firstDominatedNodeIndex[nodeOrdinal+1];if(!seen&&(!filter||filter(node))&&(node.selfSize()||nodes[nodeIndex+nodeTypeOffset]===nodeNativeType)){aggregates[classIndex].maxRet+=node.retainedSize();if(dominatedIndexFrom!==dominatedIndexTo){seenClassNameIndexes[classIndex]=true;sizes.push(list.length);classes.push(classIndex);}}
for(let i=dominatedIndexFrom;i<dominatedIndexTo;i++)
list.push(dominatedNodes[i]);const l=list.length;while(sizes[sizes.length-1]===l){sizes.pop();classIndex=classes.pop();seenClassNameIndexes[classIndex]=false;}}}
_sortAggregateIndexes(aggregates){const nodeA=this.createNode();const nodeB=this.createNode();for(const clss in aggregates){aggregates[clss].idxs.sort((idxA,idxB)=>{nodeA.nodeIndex=idxA;nodeB.nodeIndex=idxB;return nodeA.id()<nodeB.id()?-1:1;});}}
_isEssentialEdge(nodeIndex,edgeType){return edgeType!==this._edgeWeakType&&(edgeType!==this._edgeShortcutType||nodeIndex===this._rootNodeIndex);}
_buildPostOrderIndex(){const nodeFieldCount=this._nodeFieldCount;const nodeCount=this.nodeCount;const rootNodeOrdinal=this._rootNodeIndex/nodeFieldCount;const edgeFieldsCount=this._edgeFieldsCount;const edgeTypeOffset=this._edgeTypeOffset;const edgeToNodeOffset=this._edgeToNodeOffset;const firstEdgeIndexes=this._firstEdgeIndexes;const containmentEdges=this.containmentEdges;const mapAndFlag=this.userObjectsMapAndFlag();const flags=mapAndFlag?mapAndFlag.map:null;const flag=mapAndFlag?mapAndFlag.flag:0;const stackNodes=new Uint32Array(nodeCount);const stackCurrentEdge=new Uint32Array(nodeCount);const postOrderIndex2NodeOrdinal=new Uint32Array(nodeCount);const nodeOrdinal2PostOrderIndex=new Uint32Array(nodeCount);const visited=new Uint8Array(nodeCount);let postOrderIndex=0;let stackTop=0;stackNodes[0]=rootNodeOrdinal;stackCurrentEdge[0]=firstEdgeIndexes[rootNodeOrdinal];visited[rootNodeOrdinal]=1;let iteration=0;while(true){++iteration;while(stackTop>=0){const nodeOrdinal=stackNodes[stackTop];const edgeIndex=stackCurrentEdge[stackTop];const edgesEnd=firstEdgeIndexes[nodeOrdinal+1];if(edgeIndex<edgesEnd){stackCurrentEdge[stackTop]+=edgeFieldsCount;const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(!this._isEssentialEdge(nodeOrdinal*nodeFieldCount,edgeType))
continue;const childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];const childNodeOrdinal=childNodeIndex/nodeFieldCount;if(visited[childNodeOrdinal])
continue;const nodeFlag=!flags||(flags[nodeOrdinal]&flag);const childNodeFlag=!flags||(flags[childNodeOrdinal]&flag);if(nodeOrdinal!==rootNodeOrdinal&&childNodeFlag&&!nodeFlag)
continue;++stackTop;stackNodes[stackTop]=childNodeOrdinal;stackCurrentEdge[stackTop]=firstEdgeIndexes[childNodeOrdinal];visited[childNodeOrdinal]=1;}else{nodeOrdinal2PostOrderIndex[nodeOrdinal]=postOrderIndex;postOrderIndex2NodeOrdinal[postOrderIndex++]=nodeOrdinal;--stackTop;}}
if(postOrderIndex===nodeCount||iteration>1)
break;const errors=new HeapSnapshotWorker.HeapSnapshotProblemReport(`Heap snapshot: ${
nodeCount - postOrderIndex
} nodes are unreachable from the root. Following nodes have only weak retainers:`);const dumpNode=this.rootNode();--postOrderIndex;stackTop=0;stackNodes[0]=rootNodeOrdinal;stackCurrentEdge[0]=firstEdgeIndexes[rootNodeOrdinal+1];for(let i=0;i<nodeCount;++i){if(visited[i]||!this._hasOnlyWeakRetainers(i))
continue;stackNodes[++stackTop]=i;stackCurrentEdge[stackTop]=firstEdgeIndexes[i];visited[i]=1;dumpNode.nodeIndex=i*nodeFieldCount;const retainers=[];for(let it=dumpNode.retainers();it.hasNext();it.next())
retainers.push(`${it.item().node().name()}@${it.item().node().id()}.${it.item().name()}`);errors.addError(`${dumpNode.name()} @${dumpNode.id()} weak retainers: ${retainers.join(', ')}`);}
console.warn(errors.toString());}
if(postOrderIndex!==nodeCount){const errors=new HeapSnapshotWorker.HeapSnapshotProblemReport('Still found '+(nodeCount-postOrderIndex)+' unreachable nodes in heap snapshot:');const dumpNode=this.rootNode();--postOrderIndex;for(let i=0;i<nodeCount;++i){if(visited[i])
continue;dumpNode.nodeIndex=i*nodeFieldCount;errors.addError(dumpNode.name()+' @'+dumpNode.id());nodeOrdinal2PostOrderIndex[i]=postOrderIndex;postOrderIndex2NodeOrdinal[postOrderIndex++]=i;}
nodeOrdinal2PostOrderIndex[rootNodeOrdinal]=postOrderIndex;postOrderIndex2NodeOrdinal[postOrderIndex++]=rootNodeOrdinal;console.warn(errors.toString());}
return{postOrderIndex2NodeOrdinal:postOrderIndex2NodeOrdinal,nodeOrdinal2PostOrderIndex:nodeOrdinal2PostOrderIndex};}
_hasOnlyWeakRetainers(nodeOrdinal){const edgeTypeOffset=this._edgeTypeOffset;const edgeWeakType=this._edgeWeakType;const edgeShortcutType=this._edgeShortcutType;const containmentEdges=this.containmentEdges;const retainingEdges=this._retainingEdges;const beginRetainerIndex=this._firstRetainerIndex[nodeOrdinal];const endRetainerIndex=this._firstRetainerIndex[nodeOrdinal+1];for(let retainerIndex=beginRetainerIndex;retainerIndex<endRetainerIndex;++retainerIndex){const retainerEdgeIndex=retainingEdges[retainerIndex];const retainerEdgeType=containmentEdges[retainerEdgeIndex+edgeTypeOffset];if(retainerEdgeType!==edgeWeakType&&retainerEdgeType!==edgeShortcutType)
return false;}
return true;}
_buildDominatorTree(postOrderIndex2NodeOrdinal,nodeOrdinal2PostOrderIndex){const nodeFieldCount=this._nodeFieldCount;const firstRetainerIndex=this._firstRetainerIndex;const retainingNodes=this._retainingNodes;const retainingEdges=this._retainingEdges;const edgeFieldsCount=this._edgeFieldsCount;const edgeTypeOffset=this._edgeTypeOffset;const edgeToNodeOffset=this._edgeToNodeOffset;const firstEdgeIndexes=this._firstEdgeIndexes;const containmentEdges=this.containmentEdges;const rootNodeIndex=this._rootNodeIndex;const mapAndFlag=this.userObjectsMapAndFlag();const flags=mapAndFlag?mapAndFlag.map:null;const flag=mapAndFlag?mapAndFlag.flag:0;const nodesCount=postOrderIndex2NodeOrdinal.length;const rootPostOrderedIndex=nodesCount-1;const noEntry=nodesCount;const dominators=new Uint32Array(nodesCount);for(let i=0;i<rootPostOrderedIndex;++i)
dominators[i]=noEntry;dominators[rootPostOrderedIndex]=rootPostOrderedIndex;const affected=new Uint8Array(nodesCount);let nodeOrdinal;{nodeOrdinal=this._rootNodeIndex/nodeFieldCount;const endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];for(let edgeIndex=firstEdgeIndexes[nodeOrdinal];edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(!this._isEssentialEdge(this._rootNodeIndex,edgeType))
continue;const childNodeOrdinal=containmentEdges[edgeIndex+edgeToNodeOffset]/nodeFieldCount;affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]]=1;}}
let changed=true;while(changed){changed=false;for(let postOrderIndex=rootPostOrderedIndex-1;postOrderIndex>=0;--postOrderIndex){if(affected[postOrderIndex]===0)
continue;affected[postOrderIndex]=0;if(dominators[postOrderIndex]===rootPostOrderedIndex)
continue;nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];const nodeFlag=!flags||(flags[nodeOrdinal]&flag);let newDominatorIndex=noEntry;const beginRetainerIndex=firstRetainerIndex[nodeOrdinal];const endRetainerIndex=firstRetainerIndex[nodeOrdinal+1];let orphanNode=true;for(let retainerIndex=beginRetainerIndex;retainerIndex<endRetainerIndex;++retainerIndex){const retainerEdgeIndex=retainingEdges[retainerIndex];const retainerEdgeType=containmentEdges[retainerEdgeIndex+edgeTypeOffset];const retainerNodeIndex=retainingNodes[retainerIndex];if(!this._isEssentialEdge(retainerNodeIndex,retainerEdgeType))
continue;orphanNode=false;const retainerNodeOrdinal=retainerNodeIndex/nodeFieldCount;const retainerNodeFlag=!flags||(flags[retainerNodeOrdinal]&flag);if(retainerNodeIndex!==rootNodeIndex&&nodeFlag&&!retainerNodeFlag)
continue;let retanerPostOrderIndex=nodeOrdinal2PostOrderIndex[retainerNodeOrdinal];if(dominators[retanerPostOrderIndex]!==noEntry){if(newDominatorIndex===noEntry){newDominatorIndex=retanerPostOrderIndex;}else{while(retanerPostOrderIndex!==newDominatorIndex){while(retanerPostOrderIndex<newDominatorIndex)
retanerPostOrderIndex=dominators[retanerPostOrderIndex];while(newDominatorIndex<retanerPostOrderIndex)
newDominatorIndex=dominators[newDominatorIndex];}}
if(newDominatorIndex===rootPostOrderedIndex)
break;}}
if(orphanNode)
newDominatorIndex=rootPostOrderedIndex;if(newDominatorIndex!==noEntry&&dominators[postOrderIndex]!==newDominatorIndex){dominators[postOrderIndex]=newDominatorIndex;changed=true;nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];const beginEdgeToNodeFieldIndex=firstEdgeIndexes[nodeOrdinal]+edgeToNodeOffset;const endEdgeToNodeFieldIndex=firstEdgeIndexes[nodeOrdinal+1];for(let toNodeFieldIndex=beginEdgeToNodeFieldIndex;toNodeFieldIndex<endEdgeToNodeFieldIndex;toNodeFieldIndex+=edgeFieldsCount){const childNodeOrdinal=containmentEdges[toNodeFieldIndex]/nodeFieldCount;affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]]=1;}}}}
const dominatorsTree=new Uint32Array(nodesCount);for(let postOrderIndex=0,l=dominators.length;postOrderIndex<l;++postOrderIndex){nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];dominatorsTree[nodeOrdinal]=postOrderIndex2NodeOrdinal[dominators[postOrderIndex]];}
return dominatorsTree;}
_calculateRetainedSizes(postOrderIndex2NodeOrdinal){const nodeCount=this.nodeCount;const nodes=this.nodes;const nodeSelfSizeOffset=this._nodeSelfSizeOffset;const nodeFieldCount=this._nodeFieldCount;const dominatorsTree=this._dominatorsTree;const retainedSizes=this._retainedSizes;for(let nodeOrdinal=0;nodeOrdinal<nodeCount;++nodeOrdinal)
retainedSizes[nodeOrdinal]=nodes[nodeOrdinal*nodeFieldCount+nodeSelfSizeOffset];for(let postOrderIndex=0;postOrderIndex<nodeCount-1;++postOrderIndex){const nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];const dominatorOrdinal=dominatorsTree[nodeOrdinal];retainedSizes[dominatorOrdinal]+=retainedSizes[nodeOrdinal];}}
_buildDominatedNodes(){const indexArray=this._firstDominatedNodeIndex;const dominatedNodes=this._dominatedNodes;const nodeFieldCount=this._nodeFieldCount;const dominatorsTree=this._dominatorsTree;let fromNodeOrdinal=0;let toNodeOrdinal=this.nodeCount;const rootNodeOrdinal=this._rootNodeIndex/nodeFieldCount;if(rootNodeOrdinal===fromNodeOrdinal)
fromNodeOrdinal=1;else if(rootNodeOrdinal===toNodeOrdinal-1)
toNodeOrdinal=toNodeOrdinal-1;else
throw new Error('Root node is expected to be either first or last');for(let nodeOrdinal=fromNodeOrdinal;nodeOrdinal<toNodeOrdinal;++nodeOrdinal)
++indexArray[dominatorsTree[nodeOrdinal]];let firstDominatedNodeIndex=0;for(let i=0,l=this.nodeCount;i<l;++i){const dominatedCount=dominatedNodes[firstDominatedNodeIndex]=indexArray[i];indexArray[i]=firstDominatedNodeIndex;firstDominatedNodeIndex+=dominatedCount;}
indexArray[this.nodeCount]=dominatedNodes.length;for(let nodeOrdinal=fromNodeOrdinal;nodeOrdinal<toNodeOrdinal;++nodeOrdinal){const dominatorOrdinal=dominatorsTree[nodeOrdinal];let dominatedRefIndex=indexArray[dominatorOrdinal];dominatedRefIndex+=(--dominatedNodes[dominatedRefIndex]);dominatedNodes[dominatedRefIndex]=nodeOrdinal*nodeFieldCount;}}
_buildSamples(){const samples=this._rawSamples;if(!samples||!samples.length)
return;const sampleCount=samples.length/2;const sizeForRange=new Array(sampleCount);const timestamps=new Array(sampleCount);const lastAssignedIds=new Array(sampleCount);const timestampOffset=this._metaNode.sample_fields.indexOf('timestamp_us');const lastAssignedIdOffset=this._metaNode.sample_fields.indexOf('last_assigned_id');for(let i=0;i<sampleCount;i++){sizeForRange[i]=0;timestamps[i]=(samples[2*i+timestampOffset])/1000;lastAssignedIds[i]=samples[2*i+lastAssignedIdOffset];}
const nodes=this.nodes;const nodesLength=nodes.length;const nodeFieldCount=this._nodeFieldCount;const node=this.rootNode();for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;const nodeId=node.id();if(nodeId%2===0)
continue;const rangeIndex=lastAssignedIds.lowerBound(nodeId);if(rangeIndex===sampleCount){continue;}
sizeForRange[rangeIndex]+=node.selfSize();}
this._samples=new HeapSnapshotModel.Samples(timestamps,lastAssignedIds,sizeForRange);}
_buildLocationMap(){const map=new Map();const locations=this._locations;for(let i=0;i<locations.length;i+=this._locationFieldCount){const nodeIndex=locations[i+this._locationIndexOffset];const scriptId=locations[i+this._locationScriptIdOffset];const line=locations[i+this._locationLineOffset];const col=locations[i+this._locationColumnOffset];map.set(nodeIndex,new HeapSnapshotModel.Location(scriptId,line,col));}
this._locationMap=map;}
getLocation(nodeIndex){return this._locationMap.get(nodeIndex)||null;}
getSamples(){return this._samples;}
calculateFlags(){throw new Error('Not implemented');}
calculateStatistics(){throw new Error('Not implemented');}
userObjectsMapAndFlag(){throw new Error('Not implemented');}
calculateSnapshotDiff(baseSnapshotId,baseSnapshotAggregates){let snapshotDiff=this._snapshotDiffs[baseSnapshotId];if(snapshotDiff)
return snapshotDiff;snapshotDiff={};const aggregates=this.aggregates(true,'allObjects');for(const className in baseSnapshotAggregates){const baseAggregate=baseSnapshotAggregates[className];const diff=this._calculateDiffForClass(baseAggregate,aggregates[className]);if(diff)
snapshotDiff[className]=diff;}
const emptyBaseAggregate=new HeapSnapshotModel.AggregateForDiff();for(const className in aggregates){if(className in baseSnapshotAggregates)
continue;snapshotDiff[className]=this._calculateDiffForClass(emptyBaseAggregate,aggregates[className]);}
this._snapshotDiffs[baseSnapshotId]=snapshotDiff;return snapshotDiff;}
_calculateDiffForClass(baseAggregate,aggregate){const baseIds=baseAggregate.ids;const baseIndexes=baseAggregate.indexes;const baseSelfSizes=baseAggregate.selfSizes;const indexes=aggregate?aggregate.idxs:[];let i=0;let j=0;const l=baseIds.length;const m=indexes.length;const diff=new HeapSnapshotModel.Diff();const nodeB=this.createNode(indexes[j]);while(i<l&&j<m){const nodeAId=baseIds[i];if(nodeAId<nodeB.id()){diff.deletedIndexes.push(baseIndexes[i]);diff.removedCount++;diff.removedSize+=baseSelfSizes[i];++i;}else if(nodeAId>nodeB.id()){diff.addedIndexes.push(indexes[j]);diff.addedCount++;diff.addedSize+=nodeB.selfSize();nodeB.nodeIndex=indexes[++j];}else{++i;nodeB.nodeIndex=indexes[++j];}}
while(i<l){diff.deletedIndexes.push(baseIndexes[i]);diff.removedCount++;diff.removedSize+=baseSelfSizes[i];++i;}
while(j<m){diff.addedIndexes.push(indexes[j]);diff.addedCount++;diff.addedSize+=nodeB.selfSize();nodeB.nodeIndex=indexes[++j];}
diff.countDelta=diff.addedCount-diff.removedCount;diff.sizeDelta=diff.addedSize-diff.removedSize;if(!diff.addedCount&&!diff.removedCount)
return null;return diff;}
_nodeForSnapshotObjectId(snapshotObjectId){for(let it=this._allNodes();it.hasNext();it.next()){if(it.node.id()===snapshotObjectId)
return it.node;}
return null;}
nodeClassName(snapshotObjectId){const node=this._nodeForSnapshotObjectId(snapshotObjectId);if(node)
return node.className();return null;}
idsOfObjectsWithName(name){const ids=[];for(let it=this._allNodes();it.hasNext();it.next()){if(it.item().name()===name)
ids.push(it.item().id());}
return ids;}
createEdgesProvider(nodeIndex){const node=this.createNode(nodeIndex);const filter=this.containmentEdgesFilter();const indexProvider=new HeapSnapshotWorker.HeapSnapshotEdgeIndexProvider(this);return new HeapSnapshotWorker.HeapSnapshotEdgesProvider(this,filter,node.edges(),indexProvider);}
createEdgesProviderForTest(nodeIndex,filter){const node=this.createNode(nodeIndex);const indexProvider=new HeapSnapshotWorker.HeapSnapshotEdgeIndexProvider(this);return new HeapSnapshotWorker.HeapSnapshotEdgesProvider(this,filter,node.edges(),indexProvider);}
retainingEdgesFilter(){return null;}
containmentEdgesFilter(){return null;}
createRetainingEdgesProvider(nodeIndex){const node=this.createNode(nodeIndex);const filter=this.retainingEdgesFilter();const indexProvider=new HeapSnapshotWorker.HeapSnapshotRetainerEdgeIndexProvider(this);return new HeapSnapshotWorker.HeapSnapshotEdgesProvider(this,filter,node.retainers(),indexProvider);}
createAddedNodesProvider(baseSnapshotId,className){const snapshotDiff=this._snapshotDiffs[baseSnapshotId];const diffForClass=snapshotDiff[className];return new HeapSnapshotWorker.HeapSnapshotNodesProvider(this,diffForClass.addedIndexes);}
createDeletedNodesProvider(nodeIndexes){return new HeapSnapshotWorker.HeapSnapshotNodesProvider(this,nodeIndexes);}
createNodesProviderForClass(className,nodeFilter){return new HeapSnapshotWorker.HeapSnapshotNodesProvider(this,this.aggregatesWithFilter(nodeFilter)[className].idxs);}
_maxJsNodeId(){const nodeFieldCount=this._nodeFieldCount;const nodes=this.nodes;const nodesLength=nodes.length;let id=0;for(let nodeIndex=this._nodeIdOffset;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){const nextId=nodes[nodeIndex];if(nextId%2===0)
continue;if(id<nextId)
id=nextId;}
return id;}
updateStaticData(){return new HeapSnapshotModel.StaticData(this.nodeCount,this._rootNodeIndex,this.totalSize,this._maxJsNodeId());}};HeapSnapshotWorker.HeapSnapshot.AggregatedInfo;const HeapSnapshotMetainfo=class{constructor(){this.node_fields=[];this.node_types=[];this.edge_fields=[];this.edge_types=[];this.trace_function_info_fields=[];this.trace_node_fields=[];this.sample_fields=[];this.type_strings={};}};const HeapSnapshotHeader=class{constructor(){this.title='';this.meta=new HeapSnapshotMetainfo();this.node_count=0;this.edge_count=0;this.trace_function_count=0;}};HeapSnapshotWorker.HeapSnapshotItemProvider=class{constructor(iterator,indexProvider){this._iterator=iterator;this._indexProvider=indexProvider;this._isEmpty=!iterator.hasNext();this._iterationOrder=null;this._currentComparator=null;this._sortedPrefixLength=0;this._sortedSuffixLength=0;}
_createIterationOrder(){if(this._iterationOrder)
return;this._iterationOrder=[];for(let iterator=this._iterator;iterator.hasNext();iterator.next())
this._iterationOrder.push(iterator.item().itemIndex());}
isEmpty(){return this._isEmpty;}
serializeItemsRange(begin,end){this._createIterationOrder();if(begin>end)
throw new Error('Start position > end position: '+begin+' > '+end);if(end>this._iterationOrder.length)
end=this._iterationOrder.length;if(this._sortedPrefixLength<end&&begin<this._iterationOrder.length-this._sortedSuffixLength){this.sort(this._currentComparator,this._sortedPrefixLength,this._iterationOrder.length-1-this._sortedSuffixLength,begin,end-1);if(begin<=this._sortedPrefixLength)
this._sortedPrefixLength=end;if(end>=this._iterationOrder.length-this._sortedSuffixLength)
this._sortedSuffixLength=this._iterationOrder.length-begin;}
let position=begin;const count=end-begin;const result=new Array(count);for(let i=0;i<count;++i){const itemIndex=this._iterationOrder[position++];const item=this._indexProvider.itemForIndex(itemIndex);result[i]=item.serialize();}
return new HeapSnapshotModel.ItemsRange(begin,end,this._iterationOrder.length,result);}
sortAndRewind(comparator){this._currentComparator=comparator;this._sortedPrefixLength=0;this._sortedSuffixLength=0;}};HeapSnapshotWorker.HeapSnapshotEdgesProvider=class extends HeapSnapshotWorker.HeapSnapshotItemProvider{constructor(snapshot,filter,edgesIter,indexProvider){const iter=filter?new HeapSnapshotWorker.HeapSnapshotFilteredIterator(edgesIter,(filter)):edgesIter;super(iter,indexProvider);this.snapshot=snapshot;}
sort(comparator,leftBound,rightBound,windowLeft,windowRight){const fieldName1=comparator.fieldName1;const fieldName2=comparator.fieldName2;const ascending1=comparator.ascending1;const ascending2=comparator.ascending2;const edgeA=this._iterator.item().clone();const edgeB=edgeA.clone();const nodeA=this.snapshot.createNode();const nodeB=this.snapshot.createNode();function compareEdgeFieldName(ascending,indexA,indexB){edgeA.edgeIndex=indexA;edgeB.edgeIndex=indexB;if(edgeB.name()==='__proto__')
return-1;if(edgeA.name()==='__proto__')
return 1;const result=edgeA.hasStringName()===edgeB.hasStringName()?(edgeA.name()<edgeB.name()?-1:(edgeA.name()>edgeB.name()?1:0)):(edgeA.hasStringName()?-1:1);return ascending?result:-result;}
function compareNodeField(fieldName,ascending,indexA,indexB){edgeA.edgeIndex=indexA;nodeA.nodeIndex=edgeA.nodeIndex();const valueA=nodeA[fieldName]();edgeB.edgeIndex=indexB;nodeB.nodeIndex=edgeB.nodeIndex();const valueB=nodeB[fieldName]();const result=valueA<valueB?-1:(valueA>valueB?1:0);return ascending?result:-result;}
function compareEdgeAndNode(indexA,indexB){let result=compareEdgeFieldName(ascending1,indexA,indexB);if(result===0)
result=compareNodeField(fieldName2,ascending2,indexA,indexB);if(result===0)
return indexA-indexB;return result;}
function compareNodeAndEdge(indexA,indexB){let result=compareNodeField(fieldName1,ascending1,indexA,indexB);if(result===0)
result=compareEdgeFieldName(ascending2,indexA,indexB);if(result===0)
return indexA-indexB;return result;}
function compareNodeAndNode(indexA,indexB){let result=compareNodeField(fieldName1,ascending1,indexA,indexB);if(result===0)
result=compareNodeField(fieldName2,ascending2,indexA,indexB);if(result===0)
return indexA-indexB;return result;}
if(fieldName1==='!edgeName')
this._iterationOrder.sortRange(compareEdgeAndNode,leftBound,rightBound,windowLeft,windowRight);else if(fieldName2==='!edgeName')
this._iterationOrder.sortRange(compareNodeAndEdge,leftBound,rightBound,windowLeft,windowRight);else
this._iterationOrder.sortRange(compareNodeAndNode,leftBound,rightBound,windowLeft,windowRight);}};HeapSnapshotWorker.HeapSnapshotNodesProvider=class extends HeapSnapshotWorker.HeapSnapshotItemProvider{constructor(snapshot,nodeIndexes){const indexProvider=new HeapSnapshotWorker.HeapSnapshotNodeIndexProvider(snapshot);const it=new HeapSnapshotWorker.HeapSnapshotIndexRangeIterator(indexProvider,nodeIndexes);super(it,indexProvider);this.snapshot=snapshot;}
nodePosition(snapshotObjectId){this._createIterationOrder();const node=this.snapshot.createNode();let i=0;for(;i<this._iterationOrder.length;i++){node.nodeIndex=this._iterationOrder[i];if(node.id()===snapshotObjectId)
break;}
if(i===this._iterationOrder.length)
return-1;const targetNodeIndex=this._iterationOrder[i];let smallerCount=0;const compare=this._buildCompareFunction(this._currentComparator);for(let i=0;i<this._iterationOrder.length;i++){if(compare(this._iterationOrder[i],targetNodeIndex)<0)
++smallerCount;}
return smallerCount;}
_buildCompareFunction(comparator){const nodeA=this.snapshot.createNode();const nodeB=this.snapshot.createNode();const fieldAccessor1=nodeA[comparator.fieldName1];const fieldAccessor2=nodeA[comparator.fieldName2];const ascending1=comparator.ascending1?1:-1;const ascending2=comparator.ascending2?1:-1;function sortByNodeField(fieldAccessor,ascending){const valueA=fieldAccessor.call(nodeA);const valueB=fieldAccessor.call(nodeB);return valueA<valueB?-ascending:(valueA>valueB?ascending:0);}
function sortByComparator(indexA,indexB){nodeA.nodeIndex=indexA;nodeB.nodeIndex=indexB;let result=sortByNodeField(fieldAccessor1,ascending1);if(result===0)
result=sortByNodeField(fieldAccessor2,ascending2);return result||indexA-indexB;}
return sortByComparator;}
sort(comparator,leftBound,rightBound,windowLeft,windowRight){this._iterationOrder.sortRange(this._buildCompareFunction(comparator),leftBound,rightBound,windowLeft,windowRight);}};HeapSnapshotWorker.JSHeapSnapshot=class extends HeapSnapshotWorker.HeapSnapshot{constructor(profile,progress){super(profile,progress);this._nodeFlags={canBeQueried:1,detachedDOMTreeNode:2,pageObject:4};this._lazyStringCache={};this.initialize();}
createNode(nodeIndex){return new HeapSnapshotWorker.JSHeapSnapshotNode(this,nodeIndex===undefined?-1:nodeIndex);}
createEdge(edgeIndex){return new HeapSnapshotWorker.JSHeapSnapshotEdge(this,edgeIndex);}
createRetainingEdge(retainerIndex){return new HeapSnapshotWorker.JSHeapSnapshotRetainerEdge(this,retainerIndex);}
containmentEdgesFilter(){return edge=>!edge.isInvisible();}
retainingEdgesFilter(){const containmentEdgesFilter=this.containmentEdgesFilter();function filter(edge){return containmentEdgesFilter(edge)&&!edge.node().isRoot()&&!edge.isWeak();}
return filter;}
calculateFlags(){this._flags=new Uint32Array(this.nodeCount);this._markDetachedDOMTreeNodes();this._markQueriableHeapObjects();this._markPageOwnedNodes();}
calculateDistances(){function filter(node,edge){if(node.isHidden())
return edge.name()!=='sloppy_function_map'||node.rawName()!=='system / NativeContext';if(node.isArray()){if(node.rawName()!=='(map descriptors)')
return true;const index=edge.name();return index<2||(index%3)!==1;}
return true;}
super.calculateDistances(filter);}
isUserRoot(node){return node.isUserRoot()||node.isDocumentDOMTreesRoot();}
userObjectsMapAndFlag(){return{map:this._flags,flag:this._nodeFlags.pageObject};}
_flagsOfNode(node){return this._flags[node.nodeIndex/this._nodeFieldCount];}
_markDetachedDOMTreeNodes(){const nodes=this.nodes;const nodesLength=nodes.length;const nodeFieldCount=this._nodeFieldCount;const nodeNativeType=this._nodeNativeType;const nodeTypeOffset=this._nodeTypeOffset;const flag=this._nodeFlags.detachedDOMTreeNode;const node=this.rootNode();for(let nodeIndex=0,ordinal=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount,ordinal++){const nodeType=nodes[nodeIndex+nodeTypeOffset];if(nodeType!==nodeNativeType)
continue;node.nodeIndex=nodeIndex;if(node.name().startsWith('Detached '))
this._flags[ordinal]|=flag;}}
_markQueriableHeapObjects(){const flag=this._nodeFlags.canBeQueried;const hiddenEdgeType=this._edgeHiddenType;const internalEdgeType=this._edgeInternalType;const invisibleEdgeType=this._edgeInvisibleType;const weakEdgeType=this._edgeWeakType;const edgeToNodeOffset=this._edgeToNodeOffset;const edgeTypeOffset=this._edgeTypeOffset;const edgeFieldsCount=this._edgeFieldsCount;const containmentEdges=this.containmentEdges;const nodeFieldCount=this._nodeFieldCount;const firstEdgeIndexes=this._firstEdgeIndexes;const flags=this._flags;const list=[];for(let iter=this.rootNode().edges();iter.hasNext();iter.next()){if(iter.edge.node().isUserRoot())
list.push(iter.edge.node().nodeIndex/nodeFieldCount);}
while(list.length){const nodeOrdinal=list.pop();if(flags[nodeOrdinal]&flag)
continue;flags[nodeOrdinal]|=flag;const beginEdgeIndex=firstEdgeIndexes[nodeOrdinal];const endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];for(let edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];const childNodeOrdinal=childNodeIndex/nodeFieldCount;if(flags[childNodeOrdinal]&flag)
continue;const type=containmentEdges[edgeIndex+edgeTypeOffset];if(type===hiddenEdgeType||type===invisibleEdgeType||type===internalEdgeType||type===weakEdgeType)
continue;list.push(childNodeOrdinal);}}}
_markPageOwnedNodes(){const edgeShortcutType=this._edgeShortcutType;const edgeElementType=this._edgeElementType;const edgeToNodeOffset=this._edgeToNodeOffset;const edgeTypeOffset=this._edgeTypeOffset;const edgeFieldsCount=this._edgeFieldsCount;const edgeWeakType=this._edgeWeakType;const firstEdgeIndexes=this._firstEdgeIndexes;const containmentEdges=this.containmentEdges;const nodeFieldCount=this._nodeFieldCount;const nodesCount=this.nodeCount;const flags=this._flags;const pageObjectFlag=this._nodeFlags.pageObject;const nodesToVisit=new Uint32Array(nodesCount);let nodesToVisitLength=0;const rootNodeOrdinal=this._rootNodeIndex/nodeFieldCount;const node=this.rootNode();for(let edgeIndex=firstEdgeIndexes[rootNodeOrdinal],endEdgeIndex=firstEdgeIndexes[rootNodeOrdinal+1];edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];const nodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];if(edgeType===edgeElementType){node.nodeIndex=nodeIndex;if(!node.isDocumentDOMTreesRoot())
continue;}else if(edgeType!==edgeShortcutType){continue;}
const nodeOrdinal=nodeIndex/nodeFieldCount;nodesToVisit[nodesToVisitLength++]=nodeOrdinal;flags[nodeOrdinal]|=pageObjectFlag;}
while(nodesToVisitLength){const nodeOrdinal=nodesToVisit[--nodesToVisitLength];const beginEdgeIndex=firstEdgeIndexes[nodeOrdinal];const endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];for(let edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];const childNodeOrdinal=childNodeIndex/nodeFieldCount;if(flags[childNodeOrdinal]&pageObjectFlag)
continue;const type=containmentEdges[edgeIndex+edgeTypeOffset];if(type===edgeWeakType)
continue;nodesToVisit[nodesToVisitLength++]=childNodeOrdinal;flags[childNodeOrdinal]|=pageObjectFlag;}}}
calculateStatistics(){const nodeFieldCount=this._nodeFieldCount;const nodes=this.nodes;const nodesLength=nodes.length;const nodeTypeOffset=this._nodeTypeOffset;const nodeSizeOffset=this._nodeSelfSizeOffset;const nodeNativeType=this._nodeNativeType;const nodeCodeType=this._nodeCodeType;const nodeConsStringType=this._nodeConsStringType;const nodeSlicedStringType=this._nodeSlicedStringType;const distances=this._nodeDistances;let sizeNative=0;let sizeCode=0;let sizeStrings=0;let sizeJSArrays=0;let sizeSystem=0;const node=this.rootNode();for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){const nodeSize=nodes[nodeIndex+nodeSizeOffset];const ordinal=nodeIndex/nodeFieldCount;if(distances[ordinal]>=HeapSnapshotModel.baseSystemDistance){sizeSystem+=nodeSize;continue;}
const nodeType=nodes[nodeIndex+nodeTypeOffset];node.nodeIndex=nodeIndex;if(nodeType===nodeNativeType)
sizeNative+=nodeSize;else if(nodeType===nodeCodeType)
sizeCode+=nodeSize;else if(nodeType===nodeConsStringType||nodeType===nodeSlicedStringType||node.type()==='string')
sizeStrings+=nodeSize;else if(node.name()==='Array')
sizeJSArrays+=this._calculateArraySize(node);}
this._statistics=new HeapSnapshotModel.Statistics();this._statistics.total=this.totalSize;this._statistics.v8heap=this.totalSize-sizeNative;this._statistics.native=sizeNative;this._statistics.code=sizeCode;this._statistics.jsArrays=sizeJSArrays;this._statistics.strings=sizeStrings;this._statistics.system=sizeSystem;}
_calculateArraySize(node){let size=node.selfSize();const beginEdgeIndex=node.edgeIndexesStart();const endEdgeIndex=node.edgeIndexesEnd();const containmentEdges=this.containmentEdges;const strings=this.strings;const edgeToNodeOffset=this._edgeToNodeOffset;const edgeTypeOffset=this._edgeTypeOffset;const edgeNameOffset=this._edgeNameOffset;const edgeFieldsCount=this._edgeFieldsCount;const edgeInternalType=this._edgeInternalType;for(let edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(edgeType!==edgeInternalType)
continue;const edgeName=strings[containmentEdges[edgeIndex+edgeNameOffset]];if(edgeName!=='elements')
continue;const elementsNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];node.nodeIndex=elementsNodeIndex;if(node.retainersCount()===1)
size+=node.selfSize();break;}
return size;}
getStatistics(){return this._statistics;}};HeapSnapshotWorker.JSHeapSnapshotNode=class extends HeapSnapshotWorker.HeapSnapshotNode{constructor(snapshot,nodeIndex){super(snapshot,nodeIndex);}
canBeQueried(){const flags=this._snapshot._flagsOfNode(this);return!!(flags&this._snapshot._nodeFlags.canBeQueried);}
rawName(){return super.name();}
name(){const snapshot=this._snapshot;if(this.rawType()===snapshot._nodeConsStringType){let string=snapshot._lazyStringCache[this.nodeIndex];if(typeof string==='undefined'){string=this._consStringName();snapshot._lazyStringCache[this.nodeIndex]=string;}
return string;}
return this.rawName();}
_consStringName(){const snapshot=this._snapshot;const consStringType=snapshot._nodeConsStringType;const edgeInternalType=snapshot._edgeInternalType;const edgeFieldsCount=snapshot._edgeFieldsCount;const edgeToNodeOffset=snapshot._edgeToNodeOffset;const edgeTypeOffset=snapshot._edgeTypeOffset;const edgeNameOffset=snapshot._edgeNameOffset;const strings=snapshot.strings;const edges=snapshot.containmentEdges;const firstEdgeIndexes=snapshot._firstEdgeIndexes;const nodeFieldCount=snapshot._nodeFieldCount;const nodeTypeOffset=snapshot._nodeTypeOffset;const nodeNameOffset=snapshot._nodeNameOffset;const nodes=snapshot.nodes;const nodesStack=[];nodesStack.push(this.nodeIndex);let name='';while(nodesStack.length&&name.length<1024){const nodeIndex=nodesStack.pop();if(nodes[nodeIndex+nodeTypeOffset]!==consStringType){name+=strings[nodes[nodeIndex+nodeNameOffset]];continue;}
const nodeOrdinal=nodeIndex/nodeFieldCount;const beginEdgeIndex=firstEdgeIndexes[nodeOrdinal];const endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];let firstNodeIndex=0;let secondNodeIndex=0;for(let edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex&&(!firstNodeIndex||!secondNodeIndex);edgeIndex+=edgeFieldsCount){const edgeType=edges[edgeIndex+edgeTypeOffset];if(edgeType===edgeInternalType){const edgeName=strings[edges[edgeIndex+edgeNameOffset]];if(edgeName==='first')
firstNodeIndex=edges[edgeIndex+edgeToNodeOffset];else if(edgeName==='second')
secondNodeIndex=edges[edgeIndex+edgeToNodeOffset];}}
nodesStack.push(secondNodeIndex);nodesStack.push(firstNodeIndex);}
return name;}
className(){const type=this.type();switch(type){case'hidden':return'(system)';case'object':case'native':return this.name();case'code':return'(compiled code)';default:return'('+type+')';}}
classIndex(){const snapshot=this._snapshot;const nodes=snapshot.nodes;const type=nodes[this.nodeIndex+snapshot._nodeTypeOffset];if(type===snapshot._nodeObjectType||type===snapshot._nodeNativeType)
return nodes[this.nodeIndex+snapshot._nodeNameOffset];return-1-type;}
id(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeIdOffset];}
isHidden(){return this.rawType()===this._snapshot._nodeHiddenType;}
isArray(){return this.rawType()===this._snapshot._nodeArrayType;}
isSynthetic(){return this.rawType()===this._snapshot._nodeSyntheticType;}
isUserRoot(){return!this.isSynthetic();}
isDocumentDOMTreesRoot(){return this.isSynthetic()&&this.name()==='(Document DOM trees)';}
serialize(){const result=super.serialize();const flags=this._snapshot._flagsOfNode(this);if(flags&this._snapshot._nodeFlags.canBeQueried)
result.canBeQueried=true;if(flags&this._snapshot._nodeFlags.detachedDOMTreeNode)
result.detachedDOMTreeNode=true;return result;}};HeapSnapshotWorker.JSHeapSnapshotEdge=class extends HeapSnapshotWorker.HeapSnapshotEdge{constructor(snapshot,edgeIndex){super(snapshot,edgeIndex);}
clone(){const snapshot=(this._snapshot);return new HeapSnapshotWorker.JSHeapSnapshotEdge(snapshot,this.edgeIndex);}
hasStringName(){if(!this.isShortcut())
return this._hasStringName();return isNaN(parseInt(this._name(),10));}
isElement(){return this.rawType()===this._snapshot._edgeElementType;}
isHidden(){return this.rawType()===this._snapshot._edgeHiddenType;}
isWeak(){return this.rawType()===this._snapshot._edgeWeakType;}
isInternal(){return this.rawType()===this._snapshot._edgeInternalType;}
isInvisible(){return this.rawType()===this._snapshot._edgeInvisibleType;}
isShortcut(){return this.rawType()===this._snapshot._edgeShortcutType;}
name(){const name=this._name();if(!this.isShortcut())
return String(name);const numName=parseInt(name,10);return String(isNaN(numName)?name:numName);}
toString(){const name=this.name();switch(this.type()){case'context':return'->'+name;case'element':return'['+name+']';case'weak':return'[['+name+']]';case'property':return name.indexOf(' ')===-1?'.'+name:'["'+name+'"]';case'shortcut':if(typeof name==='string')
return name.indexOf(' ')===-1?'.'+name:'["'+name+'"]';else
return'['+name+']';case'internal':case'hidden':case'invisible':return'{'+name+'}';}
return'?'+name+'?';}
_hasStringName(){const type=this.rawType();const snapshot=this._snapshot;return type!==snapshot._edgeElementType&&type!==snapshot._edgeHiddenType;}
_name(){return this._hasStringName()?this._snapshot.strings[this._nameOrIndex()]:this._nameOrIndex();}
_nameOrIndex(){return this._edges[this.edgeIndex+this._snapshot._edgeNameOffset];}
rawType(){return this._edges[this.edgeIndex+this._snapshot._edgeTypeOffset];}};HeapSnapshotWorker.JSHeapSnapshotRetainerEdge=class extends HeapSnapshotWorker.HeapSnapshotRetainerEdge{constructor(snapshot,retainerIndex){super(snapshot,retainerIndex);}
clone(){const snapshot=(this._snapshot);return new HeapSnapshotWorker.JSHeapSnapshotRetainerEdge(snapshot,this.retainerIndex());}
isHidden(){return this._edge().isHidden();}
isInternal(){return this._edge().isInternal();}
isInvisible(){return this._edge().isInvisible();}
isShortcut(){return this._edge().isShortcut();}
isWeak(){return this._edge().isWeak();}};(function disableLoggingForTest(){if(self.Runtime&&Runtime.queryParam('test'))
console.warn=()=>undefined;})();;HeapSnapshotWorker.HeapSnapshotLoader=class{constructor(dispatcher){this._reset();this._progress=new HeapSnapshotWorker.HeapSnapshotProgress(dispatcher);this._buffer='';this._dataCallback=null;this._done=false;this._parseInput();}
dispose(){this._reset();}
_reset(){this._json='';this._snapshot={};}
close(){this._done=true;if(this._dataCallback)
this._dataCallback('');}
buildSnapshot(){this._progress.updateStatus(ls`Processing snapshot\u2026`);const result=new HeapSnapshotWorker.JSHeapSnapshot(this._snapshot,this._progress);this._reset();return result;}
_parseUintArray(){let index=0;const char0='0'.charCodeAt(0);const char9='9'.charCodeAt(0);const closingBracket=']'.charCodeAt(0);const length=this._json.length;while(true){while(index<length){const code=this._json.charCodeAt(index);if(char0<=code&&code<=char9){break;}else if(code===closingBracket){this._json=this._json.slice(index+1);return false;}
++index;}
if(index===length){this._json='';return true;}
let nextNumber=0;const startIndex=index;while(index<length){const code=this._json.charCodeAt(index);if(char0>code||code>char9)
break;nextNumber*=10;nextNumber+=(code-char0);++index;}
if(index===length){this._json=this._json.slice(startIndex);return true;}
this._array[this._arrayIndex++]=nextNumber;}}
_parseStringsArray(){this._progress.updateStatus('Parsing strings\u2026');const closingBracketIndex=this._json.lastIndexOf(']');if(closingBracketIndex===-1)
throw new Error('Incomplete JSON');this._json=this._json.slice(0,closingBracketIndex+1);this._snapshot.strings=JSON.parse(this._json);}
write(chunk){this._buffer+=chunk;if(!this._dataCallback)
return;this._dataCallback(this._buffer);this._dataCallback=null;this._buffer='';}
_fetchChunk(){return this._done?Promise.resolve(this._buffer):new Promise(r=>this._dataCallback=r);}
async _findToken(token,startIndex){while(true){const pos=this._json.indexOf(token,startIndex||0);if(pos!==-1)
return pos;startIndex=this._json.length-token.length+1;this._json+=await this._fetchChunk();}}
async _parseArray(name,title,length){const nameIndex=await this._findToken(name);const bracketIndex=await this._findToken('[',nameIndex);this._json=this._json.slice(bracketIndex+1);this._array=length?new Uint32Array(length):[];this._arrayIndex=0;while(this._parseUintArray()){this._progress.updateProgress(title,this._arrayIndex,this._array.length);this._json+=await this._fetchChunk();}
const result=this._array;this._array=null;return result;}
async _parseInput(){const snapshotToken='"snapshot"';const snapshotTokenIndex=await this._findToken(snapshotToken);if(snapshotTokenIndex===-1)
throw new Error('Snapshot token not found');this._progress.updateStatus(ls`Loading snapshot info\u2026`);const json=this._json.slice(snapshotTokenIndex+snapshotToken.length+1);this._jsonTokenizer=new TextUtils.TextUtils.BalancedJSONTokenizer(metaJSON=>{this._json=this._jsonTokenizer.remainder();this._jsonTokenizer=null;this._snapshot.snapshot=(JSON.parse(metaJSON));});this._jsonTokenizer.write(json);while(this._jsonTokenizer)
this._jsonTokenizer.write(await this._fetchChunk());this._snapshot.nodes=await this._parseArray('"nodes"',ls`Loading nodes\u2026 %d%%`,this._snapshot.snapshot.meta.node_fields.length*this._snapshot.snapshot.node_count);this._snapshot.edges=await this._parseArray('"edges"',ls`Loading edges\u2026 %d%%`,this._snapshot.snapshot.meta.edge_fields.length*this._snapshot.snapshot.edge_count);if(this._snapshot.snapshot.trace_function_count){this._snapshot.trace_function_infos=await this._parseArray('"trace_function_infos"',ls`Loading allocation traces\u2026 %d%%`,this._snapshot.snapshot.meta.trace_function_info_fields.length*this._snapshot.snapshot.trace_function_count);const thisTokenEndIndex=await this._findToken(':');const nextTokenIndex=await this._findToken('"',thisTokenEndIndex);const openBracketIndex=this._json.indexOf('[');const closeBracketIndex=this._json.lastIndexOf(']',nextTokenIndex);this._snapshot.trace_tree=JSON.parse(this._json.substring(openBracketIndex,closeBracketIndex+1));this._json=this._json.slice(closeBracketIndex+1);}
if(this._snapshot.snapshot.meta.sample_fields)
this._snapshot.samples=await this._parseArray('"samples"',ls`Loading samples\u2026`);if(this._snapshot.snapshot.meta['location_fields'])
this._snapshot.locations=await this._parseArray('"locations"',ls`Loading locations\u2026`);else
this._snapshot.locations=[];this._progress.updateStatus(ls`Loading strings\u2026`);const stringsTokenIndex=await this._findToken('"strings"');const bracketIndex=await this._findToken('[',stringsTokenIndex);this._json=this._json.slice(bracketIndex);while(!this._done)
this._json+=await this._fetchChunk();this._parseStringsArray();}};;HeapSnapshotWorker.HeapSnapshotWorkerDispatcher=class{constructor(globalObject,postMessage){this._objects=[];this._global=globalObject;this._postMessage=postMessage;}
_findFunction(name){const path=name.split('.');let result=this._global;for(let i=0;i<path.length;++i)
result=result[path[i]];return result;}
sendEvent(name,data){this._postMessage({eventName:name,data:data});}
dispatchMessage(event){const data=(event.data);const response={callId:data.callId};try{switch(data.disposition){case'create':const constructorFunction=this._findFunction(data.methodName);this._objects[data.objectId]=new constructorFunction(this);break;case'dispose':delete this._objects[data.objectId];break;case'getter':{const object=this._objects[data.objectId];const result=object[data.methodName];response.result=result;break;}
case'factory':{const object=this._objects[data.objectId];const result=object[data.methodName].apply(object,data.methodArguments);if(result)
this._objects[data.newObjectId]=result;response.result=!!result;break;}
case'method':{const object=this._objects[data.objectId];response.result=object[data.methodName].apply(object,data.methodArguments);break;}
case'evaluateForTest':try{response.result=self.eval(data.source);}catch(e){response.result=e.toString();}
break;}}catch(e){response.error=e.toString();response.errorCallStack=e.stack;if(data.methodName)
response.errorMethodName=data.methodName;}
this._postMessage(response);}};;function postMessageWrapper(message){postMessage(message);}
const dispatcher=new HeapSnapshotWorker.HeapSnapshotWorkerDispatcher(this,postMessageWrapper);function installMessageEventListener(listener){self.addEventListener('message',listener,false);}
installMessageEventListener(dispatcher.dispatchMessage.bind(dispatcher));;;;if(!self.Runtime)
self.importScripts('Runtime.js');Runtime.startWorker('heap_snapshot_worker');<!--
* Copyright 2014 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
<meta name="referrer" content="no-referrer">
<script type="text/javascript" src="shell.js"></script>
<script type="text/javascript" src="devtools_app.js"></script>
<script type="text/javascript" src="inspector.js"></script>
<script>Runtime.startApplication('inspector');</script>
</head>
<body class="undocked" id="-blink-dev-tools"></body>
</html>
allDescriptors.push(...[{"dependencies":["components","emulation"],"extensions":[{"className":"Screencast.ScreencastAppProvider","type":"@Common.AppProvider","order":1},{"className":"Screencast.ScreencastApp.ToolbarButtonProvider","type":"@UI.ToolbarItem.Provider","order":1,"location":"main-toolbar-left"},{"actionId":"components.request-app-banner","type":"context-menu-item","location":"mainMenu","order":10}],"name":"screencast"}]);applicationDescriptor.modules.push(...[{"type":"autostart","name":"screencast"}])
self['Screencast']=self['Screencast']||{};Screencast.InputModel=class extends SDK.SDKModel{constructor(target){super(target);this._inputAgent=target.inputAgent();this._activeTouchOffsetTop=null;this._activeTouchParams=null;}
emitKeyEvent(event){let type;switch(event.type){case'keydown':type='keyDown';break;case'keyup':type='keyUp';break;case'keypress':type='char';break;default:return;}
const text=event.type==='keypress'?String.fromCharCode(event.charCode):undefined;this._inputAgent.invoke_dispatchKeyEvent({type:type,modifiers:this._modifiersForEvent(event),text:text,unmodifiedText:text?text.toLowerCase():undefined,keyIdentifier:event.keyIdentifier,code:event.code,key:event.key,windowsVirtualKeyCode:event.keyCode,nativeVirtualKeyCode:event.keyCode,autoRepeat:false,isKeypad:false,isSystemKey:false});}
emitTouchFromMouseEvent(event,offsetTop,zoom){const buttons={0:'none',1:'left',2:'middle',3:'right'};const types={'mousedown':'mousePressed','mouseup':'mouseReleased','mousemove':'mouseMoved','mousewheel':'mouseWheel'};if(!(event.type in types)||!(event.which in buttons))
return;if(event.type!=='mousewheel'&&buttons[event.which]==='none')
return;if(event.type==='mousedown'||this._activeTouchOffsetTop===null)
this._activeTouchOffsetTop=offsetTop;const x=Math.round(event.offsetX/zoom);let y=Math.round(event.offsetY/zoom);y=Math.round(y-this._activeTouchOffsetTop);const params={type:types[event.type],x:x,y:y,modifiers:this._modifiersForEvent(event),button:buttons[event.which],clickCount:0};if(event.type==='mousewheel'){params.deltaX=event.wheelDeltaX/zoom;params.deltaY=event.wheelDeltaY/zoom;}else{this._activeTouchParams=params;}
if(event.type==='mouseup')
this._activeTouchOffsetTop=null;this._inputAgent.invoke_emulateTouchFromMouseEvent(params);}
cancelTouch(){if(this._activeTouchParams!==null){const params=this._activeTouchParams;this._activeTouchParams=null;params.type='mouseReleased';this._inputAgent.invoke_emulateTouchFromMouseEvent(params);}}
_modifiersForEvent(event){return(event.altKey?1:0)|(event.ctrlKey?2:0)|(event.metaKey?4:0)|(event.shiftKey?8:0);}};SDK.SDKModel.register(Screencast.InputModel,SDK.Target.Capability.Input,false);;Screencast.ScreencastApp=class{constructor(){this._enabledSetting=Common.settings.createSetting('screencastEnabled',true);this._toggleButton=new UI.ToolbarToggle(Common.UIString('Toggle screencast'),'largeicon-phone');this._toggleButton.setToggled(this._enabledSetting.get());this._toggleButton.setEnabled(false);this._toggleButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleButtonClicked,this);SDK.targetManager.observeModels(SDK.ScreenCaptureModel,this);}
static _instance(){if(!Screencast.ScreencastApp._appInstance)
Screencast.ScreencastApp._appInstance=new Screencast.ScreencastApp();return Screencast.ScreencastApp._appInstance;}
presentUI(document){const rootView=new UI.RootView();this._rootSplitWidget=new UI.SplitWidget(false,true,'InspectorView.screencastSplitViewState',300,300);this._rootSplitWidget.setVertical(true);this._rootSplitWidget.setSecondIsSidebar(true);this._rootSplitWidget.show(rootView.element);this._rootSplitWidget.hideMain();this._rootSplitWidget.setSidebarWidget(UI.inspectorView);rootView.attachToDocument(document);rootView.focus();}
modelAdded(screenCaptureModel){if(this._screenCaptureModel)
return;this._screenCaptureModel=screenCaptureModel;this._toggleButton.setEnabled(true);this._screencastView=new Screencast.ScreencastView(screenCaptureModel);this._rootSplitWidget.setMainWidget(this._screencastView);this._screencastView.initialize();this._onScreencastEnabledChanged();}
modelRemoved(screenCaptureModel){if(this._screenCaptureModel!==screenCaptureModel)
return;delete this._screenCaptureModel;this._toggleButton.setEnabled(false);this._screencastView.detach();delete this._screencastView;this._onScreencastEnabledChanged();}
_toggleButtonClicked(){const enabled=!this._toggleButton.toggled();this._enabledSetting.set(enabled);this._onScreencastEnabledChanged();}
_onScreencastEnabledChanged(){if(!this._rootSplitWidget)
return;const enabled=this._enabledSetting.get()&&this._screencastView;this._toggleButton.setToggled(enabled);if(enabled)
this._rootSplitWidget.showBoth();else
this._rootSplitWidget.hideMain();}};Screencast.ScreencastApp._appInstance;Screencast.ScreencastApp.ToolbarButtonProvider=class{item(){return Screencast.ScreencastApp._instance()._toggleButton;}};Screencast.ScreencastAppProvider=class{createApp(){return Screencast.ScreencastApp._instance();}};;Screencast.ScreencastView=class extends UI.VBox{constructor(screenCaptureModel){super();this._screenCaptureModel=screenCaptureModel;this._domModel=screenCaptureModel.target().model(SDK.DOMModel);this._overlayModel=screenCaptureModel.target().model(SDK.OverlayModel);this._resourceTreeModel=screenCaptureModel.target().model(SDK.ResourceTreeModel);this._networkManager=screenCaptureModel.target().model(SDK.NetworkManager);this._inputModel=screenCaptureModel.target().model(Screencast.InputModel);this.setMinimumSize(150,150);this.registerRequiredCSS('screencast/screencastView.css');}
initialize(){this.element.classList.add('screencast');this._createNavigationBar();this._viewportElement=this.element.createChild('div','screencast-viewport hidden');this._canvasContainerElement=this._viewportElement.createChild('div','screencast-canvas-container');this._glassPaneElement=this._canvasContainerElement.createChild('div','screencast-glasspane fill hidden');this._canvasElement=this._canvasContainerElement.createChild('canvas');this._canvasElement.tabIndex=0;this._canvasElement.addEventListener('mousedown',this._handleMouseEvent.bind(this),false);this._canvasElement.addEventListener('mouseup',this._handleMouseEvent.bind(this),false);this._canvasElement.addEventListener('mousemove',this._handleMouseEvent.bind(this),false);this._canvasElement.addEventListener('mousewheel',this._handleMouseEvent.bind(this),false);this._canvasElement.addEventListener('click',this._handleMouseEvent.bind(this),false);this._canvasElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),false);this._canvasElement.addEventListener('keydown',this._handleKeyEvent.bind(this),false);this._canvasElement.addEventListener('keyup',this._handleKeyEvent.bind(this),false);this._canvasElement.addEventListener('keypress',this._handleKeyEvent.bind(this),false);this._canvasElement.addEventListener('blur',this._handleBlurEvent.bind(this),false);this._titleElement=this._canvasContainerElement.createChild('div','screencast-element-title monospace hidden');this._tagNameElement=this._titleElement.createChild('span','screencast-tag-name');this._nodeIdElement=this._titleElement.createChild('span','screencast-node-id');this._classNameElement=this._titleElement.createChild('span','screencast-class-name');this._titleElement.createTextChild(' ');this._nodeWidthElement=this._titleElement.createChild('span');this._titleElement.createChild('span','screencast-px').textContent='px';this._titleElement.createTextChild(' \u00D7 ');this._nodeHeightElement=this._titleElement.createChild('span');this._titleElement.createChild('span','screencast-px').textContent='px';this._titleElement.style.top='0';this._titleElement.style.left='0';this._imageElement=new Image();this._isCasting=false;this._context=this._canvasElement.getContext('2d');this._checkerboardPattern=this._createCheckerboardPattern(this._context);this._shortcuts=({});this._shortcuts[UI.KeyboardShortcut.makeKey('l',UI.KeyboardShortcut.Modifiers.Ctrl)]=this._focusNavigationBar.bind(this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._onSuspendStateChange,this);this._updateGlasspane();}
wasShown(){this._startCasting();}
willHide(){this._stopCasting();}
_startCasting(){if(SDK.targetManager.allTargetsSuspended())
return;if(this._isCasting)
return;this._isCasting=true;const maxImageDimension=2048;const dimensions=this._viewportDimensions();if(dimensions.width<0||dimensions.height<0){this._isCasting=false;return;}
dimensions.width*=window.devicePixelRatio;dimensions.height*=window.devicePixelRatio;this._screenCaptureModel.startScreencast('jpeg',80,Math.floor(Math.min(maxImageDimension,dimensions.width)),Math.floor(Math.min(maxImageDimension,dimensions.height)),undefined,this._screencastFrame.bind(this),this._screencastVisibilityChanged.bind(this));for(const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
emulationModel.overrideEmulateTouch(true);if(this._overlayModel)
this._overlayModel.setHighlighter(this);}
_stopCasting(){if(!this._isCasting)
return;this._isCasting=false;this._screenCaptureModel.stopScreencast();for(const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
emulationModel.overrideEmulateTouch(false);if(this._overlayModel)
this._overlayModel.setHighlighter(null);}
_screencastFrame(base64Data,metadata){this._imageElement.onload=()=>{this._pageScaleFactor=metadata.pageScaleFactor;this._screenOffsetTop=metadata.offsetTop;this._scrollOffsetX=metadata.scrollOffsetX;this._scrollOffsetY=metadata.scrollOffsetY;const deviceSizeRatio=metadata.deviceHeight/metadata.deviceWidth;const dimensionsCSS=this._viewportDimensions();this._imageZoom=Math.min(dimensionsCSS.width/this._imageElement.naturalWidth,dimensionsCSS.height/(this._imageElement.naturalWidth*deviceSizeRatio));this._viewportElement.classList.remove('hidden');const bordersSize=Screencast.ScreencastView._bordersSize;if(this._imageZoom<1.01/window.devicePixelRatio)
this._imageZoom=1/window.devicePixelRatio;this._screenZoom=this._imageElement.naturalWidth*this._imageZoom/metadata.deviceWidth;this._viewportElement.style.width=metadata.deviceWidth*this._screenZoom+bordersSize+'px';this._viewportElement.style.height=metadata.deviceHeight*this._screenZoom+bordersSize+'px';this.highlightInOverlay({node:this._highlightNode},this._highlightConfig);};this._imageElement.src='data:image/jpg;base64,'+base64Data;}
_isGlassPaneActive(){return!this._glassPaneElement.classList.contains('hidden');}
_screencastVisibilityChanged(visible){this._targetInactive=!visible;this._updateGlasspane();}
_onSuspendStateChange(event){if(SDK.targetManager.allTargetsSuspended())
this._stopCasting();else
this._startCasting();this._updateGlasspane();}
_updateGlasspane(){if(this._targetInactive){this._glassPaneElement.textContent=Common.UIString('The tab is inactive');this._glassPaneElement.classList.remove('hidden');}else if(SDK.targetManager.allTargetsSuspended()){this._glassPaneElement.textContent=Common.UIString('Profiling in progress');this._glassPaneElement.classList.remove('hidden');}else{this._glassPaneElement.classList.add('hidden');}}
async _handleMouseEvent(event){if(this._isGlassPaneActive()){event.consume();return;}
if(!this._pageScaleFactor||!this._domModel)
return;if(!this._inspectModeConfig||event.type==='mousewheel'){if(this._inputModel)
this._inputModel.emitTouchFromMouseEvent(event,this._screenOffsetTop,this._screenZoom);event.preventDefault();if(event.type==='mousedown')
this._canvasElement.focus();return;}
const position=this._convertIntoScreenSpace(event);const node=await this._domModel.nodeForLocation(Math.floor(position.x/this._pageScaleFactor+this._scrollOffsetX),Math.floor(position.y/this._pageScaleFactor+this._scrollOffsetY),Common.moduleSetting('showUAShadowDOM').get());if(!node)
return;if(event.type==='mousemove'){this.highlightInOverlay({node},this._inspectModeConfig);this._domModel.overlayModel().nodeHighlightRequested(node.id);}else if(event.type==='click'){this._domModel.overlayModel().inspectNodeRequested(node.backendNodeId());}}
_handleKeyEvent(event){if(this._isGlassPaneActive()){event.consume();return;}
const shortcutKey=UI.KeyboardShortcut.makeKeyFromEvent((event));const handler=this._shortcuts[shortcutKey];if(handler&&handler(event)){event.consume();return;}
if(this._inputModel)
this._inputModel.emitKeyEvent(event);event.consume();this._canvasElement.focus();}
_handleContextMenuEvent(event){event.consume(true);}
_handleBlurEvent(event){if(this._inputModel)
this._inputModel.cancelTouch();}
_convertIntoScreenSpace(event){const position={};position.x=Math.round(event.offsetX/this._screenZoom);position.y=Math.round(event.offsetY/this._screenZoom-this._screenOffsetTop);return position;}
onResize(){if(this._deferredCasting){clearTimeout(this._deferredCasting);delete this._deferredCasting;}
this._stopCasting();this._deferredCasting=setTimeout(this._startCasting.bind(this),100);}
highlightInOverlay(data,config){this._highlightInOverlay(data,config);}
async _highlightInOverlay(data,config){const{node:n,deferredNode,object}=data;let node=n;if(!node&&deferredNode)
node=await deferredNode.resolvePromise();if(!node&&object){const domModel=object.runtimeModel().target().model(SDK.DOMModel);if(domModel)
node=await domModel.pushObjectAsNodeToFrontend(object);}
this._highlightNode=node;this._highlightConfig=config;if(!node){this._model=null;this._config=null;this._node=null;this._titleElement.classList.add('hidden');this._repaint();return;}
this._node=node;node.boxModel().then(model=>{if(!model||!this._pageScaleFactor){this._repaint();return;}
this._model=this._scaleModel(model);this._config=config;this._repaint();});}
_scaleModel(model){function scaleQuad(quad){for(let i=0;i<quad.length;i+=2){quad[i]=quad[i]*this._pageScaleFactor*this._screenZoom;quad[i+1]=(quad[i+1]*this._pageScaleFactor+this._screenOffsetTop)*this._screenZoom;}}
scaleQuad.call(this,model.content);scaleQuad.call(this,model.padding);scaleQuad.call(this,model.border);scaleQuad.call(this,model.margin);return model;}
_repaint(){const model=this._model;const config=this._config;const canvasWidth=this._canvasElement.getBoundingClientRect().width;const canvasHeight=this._canvasElement.getBoundingClientRect().height;this._canvasElement.width=window.devicePixelRatio*canvasWidth;this._canvasElement.height=window.devicePixelRatio*canvasHeight;this._context.save();this._context.scale(window.devicePixelRatio,window.devicePixelRatio);this._context.save();this._context.fillStyle=this._checkerboardPattern;this._context.fillRect(0,0,canvasWidth,this._screenOffsetTop*this._screenZoom);this._context.fillRect(0,this._screenOffsetTop*this._screenZoom+this._imageElement.naturalHeight*this._imageZoom,canvasWidth,canvasHeight);this._context.restore();if(model&&config){this._context.save();const transparentColor='rgba(0, 0, 0, 0)';const quads=[];if(model.content&&config.contentColor!==transparentColor)
quads.push({quad:model.content,color:config.contentColor});if(model.padding&&config.paddingColor!==transparentColor)
quads.push({quad:model.padding,color:config.paddingColor});if(model.border&&config.borderColor!==transparentColor)
quads.push({quad:model.border,color:config.borderColor});if(model.margin&&config.marginColor!==transparentColor)
quads.push({quad:model.margin,color:config.marginColor});for(let i=quads.length-1;i>0;--i)
this._drawOutlinedQuadWithClip(quads[i].quad,quads[i-1].quad,quads[i].color);if(quads.length>0)
this._drawOutlinedQuad(quads[0].quad,quads[0].color);this._context.restore();this._drawElementTitle();this._context.globalCompositeOperation='destination-over';}
this._context.drawImage(this._imageElement,0,this._screenOffsetTop*this._screenZoom,this._imageElement.naturalWidth*this._imageZoom,this._imageElement.naturalHeight*this._imageZoom);this._context.restore();}
_cssColor(color){if(!color)
return'transparent';return Common.Color.fromRGBA([color.r,color.g,color.b,color.a]).asString(Common.Color.Format.RGBA)||'';}
_quadToPath(quad){this._context.beginPath();this._context.moveTo(quad[0],quad[1]);this._context.lineTo(quad[2],quad[3]);this._context.lineTo(quad[4],quad[5]);this._context.lineTo(quad[6],quad[7]);this._context.closePath();return this._context;}
_drawOutlinedQuad(quad,fillColor){this._context.save();this._context.lineWidth=2;this._quadToPath(quad).clip();this._context.fillStyle=this._cssColor(fillColor);this._context.fill();this._context.restore();}
_drawOutlinedQuadWithClip(quad,clipQuad,fillColor){this._context.fillStyle=this._cssColor(fillColor);this._context.save();this._context.lineWidth=0;this._quadToPath(quad).fill();this._context.globalCompositeOperation='destination-out';this._context.fillStyle='red';this._quadToPath(clipQuad).fill();this._context.restore();}
_drawElementTitle(){if(!this._node)
return;const canvasWidth=this._canvasElement.getBoundingClientRect().width;const canvasHeight=this._canvasElement.getBoundingClientRect().height;const lowerCaseName=this._node.localName()||this._node.nodeName().toLowerCase();this._tagNameElement.textContent=lowerCaseName;this._nodeIdElement.textContent=this._node.getAttribute('id')?'#'+this._node.getAttribute('id'):'';this._nodeIdElement.textContent=this._node.getAttribute('id')?'#'+this._node.getAttribute('id'):'';let className=this._node.getAttribute('class');if(className&&className.length>50)
className=className.substring(0,50)+'\u2026';this._classNameElement.textContent=className||'';this._nodeWidthElement.textContent=this._model.width;this._nodeHeightElement.textContent=this._model.height;this._titleElement.classList.remove('hidden');const titleWidth=this._titleElement.offsetWidth+6;const titleHeight=this._titleElement.offsetHeight+4;const anchorTop=this._model.margin[1];const anchorBottom=this._model.margin[7];const arrowHeight=7;let renderArrowUp=false;let renderArrowDown=false;let boxX=Math.max(2,this._model.margin[0]);if(boxX+titleWidth>canvasWidth)
boxX=canvasWidth-titleWidth-2;let boxY;if(anchorTop>canvasHeight){boxY=canvasHeight-titleHeight-arrowHeight;renderArrowDown=true;}else if(anchorBottom<0){boxY=arrowHeight;renderArrowUp=true;}else if(anchorBottom+titleHeight+arrowHeight<canvasHeight){boxY=anchorBottom+arrowHeight-4;renderArrowUp=true;}else if(anchorTop-titleHeight-arrowHeight>0){boxY=anchorTop-titleHeight-arrowHeight+3;renderArrowDown=true;}else{boxY=arrowHeight;}
this._context.save();this._context.translate(0.5,0.5);this._context.beginPath();this._context.moveTo(boxX,boxY);if(renderArrowUp){this._context.lineTo(boxX+2*arrowHeight,boxY);this._context.lineTo(boxX+3*arrowHeight,boxY-arrowHeight);this._context.lineTo(boxX+4*arrowHeight,boxY);}
this._context.lineTo(boxX+titleWidth,boxY);this._context.lineTo(boxX+titleWidth,boxY+titleHeight);if(renderArrowDown){this._context.lineTo(boxX+4*arrowHeight,boxY+titleHeight);this._context.lineTo(boxX+3*arrowHeight,boxY+titleHeight+arrowHeight);this._context.lineTo(boxX+2*arrowHeight,boxY+titleHeight);}
this._context.lineTo(boxX,boxY+titleHeight);this._context.closePath();this._context.fillStyle='rgb(255, 255, 194)';this._context.fill();this._context.strokeStyle='rgb(128, 128, 128)';this._context.stroke();this._context.restore();this._titleElement.style.top=(boxY+3)+'px';this._titleElement.style.left=(boxX+3)+'px';}
_viewportDimensions(){const gutterSize=30;const bordersSize=Screencast.ScreencastView._bordersSize;const width=this.element.offsetWidth-bordersSize-gutterSize;const height=this.element.offsetHeight-bordersSize-gutterSize-Screencast.ScreencastView._navBarHeight;return{width:width,height:height};}
setInspectMode(mode,config){this._inspectModeConfig=mode!==Protocol.Overlay.InspectMode.None?config:null;return Promise.resolve();}
highlightFrame(frameId){}
_createCheckerboardPattern(context){const pattern=(createElement('canvas'));const size=32;pattern.width=size*2;pattern.height=size*2;const pctx=pattern.getContext('2d');pctx.fillStyle='rgb(195, 195, 195)';pctx.fillRect(0,0,size*2,size*2);pctx.fillStyle='rgb(225, 225, 225)';pctx.fillRect(0,0,size,size);pctx.fillRect(size,size,size,size);return context.createPattern(pattern,'repeat');}
_createNavigationBar(){this._navigationBar=this.element.createChild('div','screencast-navigation');this._navigationBack=this._navigationBar.createChild('button','back');this._navigationBack.disabled=true;this._navigationForward=this._navigationBar.createChild('button','forward');this._navigationForward.disabled=true;this._navigationReload=this._navigationBar.createChild('button','reload');this._navigationUrl=UI.createInput();this._navigationBar.appendChild(this._navigationUrl);this._navigationUrl.type='text';this._navigationProgressBar=new Screencast.ScreencastView.ProgressTracker(this._resourceTreeModel,this._networkManager,this._navigationBar.createChild('div','progress'));if(this._resourceTreeModel){this._navigationBack.addEventListener('click',this._navigateToHistoryEntry.bind(this,-1),false);this._navigationForward.addEventListener('click',this._navigateToHistoryEntry.bind(this,1),false);this._navigationReload.addEventListener('click',this._navigateReload.bind(this),false);this._navigationUrl.addEventListener('keyup',this._navigationUrlKeyUp.bind(this),true);this._requestNavigationHistory();this._resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._requestNavigationHistory,this);this._resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded,this._requestNavigationHistory,this);}}
_navigateToHistoryEntry(offset){const newIndex=this._historyIndex+offset;if(newIndex<0||newIndex>=this._historyEntries.length)
return;this._resourceTreeModel.navigateToHistoryEntry(this._historyEntries[newIndex]);this._requestNavigationHistory();}
_navigateReload(){this._resourceTreeModel.reloadPage();}
_navigationUrlKeyUp(event){if(event.key!=='Enter')
return;let url=this._navigationUrl.value;if(!url)
return;if(!url.match(Screencast.ScreencastView._SchemeRegex))
url='http://'+url;this._resourceTreeModel.navigate(url);this._canvasElement.focus();}
async _requestNavigationHistory(){const history=await this._resourceTreeModel.navigationHistory();if(!history)
return;this._historyIndex=history.currentIndex;this._historyEntries=history.entries;this._navigationBack.disabled=this._historyIndex===0;this._navigationForward.disabled=this._historyIndex===(this._historyEntries.length-1);let url=this._historyEntries[this._historyIndex].url;const match=url.match(Screencast.ScreencastView._HttpRegex);if(match)
url=match[1];InspectorFrontendHost.inspectedURLChanged(url);this._navigationUrl.value=url;}
_focusNavigationBar(){this._navigationUrl.focus();this._navigationUrl.select();return true;}};Screencast.ScreencastView._bordersSize=44;Screencast.ScreencastView._navBarHeight=29;Screencast.ScreencastView._HttpRegex=/^http:\/\/(.+)/;Screencast.ScreencastView._SchemeRegex=/^(https?|about|chrome):/;Screencast.ScreencastView.ProgressTracker=class{constructor(resourceTreeModel,networkManager,element){this._element=element;if(resourceTreeModel){resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this);resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load,this._onLoad,this);}
if(networkManager){networkManager.addEventListener(SDK.NetworkManager.Events.RequestStarted,this._onRequestStarted,this);networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished,this._onRequestFinished,this);}}
_onMainFrameNavigated(){this._requestIds={};this._startedRequests=0;this._finishedRequests=0;this._maxDisplayedProgress=0;this._updateProgress(0.1);}
_onLoad(){delete this._requestIds;this._updateProgress(1);setTimeout(function(){if(!this._navigationProgressVisible())
this._displayProgress(0);}.bind(this),500);}
_navigationProgressVisible(){return!!this._requestIds;}
_onRequestStarted(event){if(!this._navigationProgressVisible())
return;const request=(event.data);if(request.type===Common.resourceTypes.WebSocket)
return;this._requestIds[request.requestId()]=request;++this._startedRequests;}
_onRequestFinished(event){if(!this._navigationProgressVisible())
return;const request=(event.data);if(!(request.requestId()in this._requestIds))
return;++this._finishedRequests;setTimeout(function(){this._updateProgress(this._finishedRequests/this._startedRequests*0.9);}.bind(this),500);}
_updateProgress(progress){if(!this._navigationProgressVisible())
return;if(this._maxDisplayedProgress>=progress)
return;this._maxDisplayedProgress=progress;this._displayProgress(progress);}
_displayProgress(progress){this._element.style.width=(100*progress)+'%';}};;;Runtime.cachedResources["screencast/screencastView.css"]="/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.screencast {\n overflow: hidden;\n}\n\n.screencast-navigation {\n flex-direction: row;\n display: flex;\n flex: 24px 0 0;\n position: relative;\n padding-left: 1px;\n border-bottom: 1px solid rgb(64%, 64%, 64%);\n background-origin: padding-box;\n background-clip: padding-box;\n}\n\n.screencast-navigation button {\n border-radius: 2px;\n background-color: transparent;\n background-image: -webkit-image-set(\n url(Images/navigationControls.png) 1x,\n url(Images/navigationControls_2x.png) 2x);\n background-clip: content-box;\n background-origin: content-box;\n background-repeat: no-repeat;\n border: 1px solid transparent;\n height: 23px;\n padding: 2px;\n width: 23px;\n}\n\n.screencast-navigation button:hover {\n border-color: #ccc;\n}\n\n.screencast-navigation button:active {\n border-color: #aaa;\n}\n\n.screencast-navigation button[disabled] {\n opacity: 0.5;\n}\n\n.screencast-navigation button.back {\n background-position-x: -1px;\n}\n\n.screencast-navigation button.forward {\n background-position-x: -18px;\n}\n\n.screencast-navigation button.reload {\n background-position-x: -37px;\n}\n\n.screencast-navigation input {\n -webkit-flex: 1;\n margin: 2px;\n max-height: 19px;\n}\n\n.screencast-navigation .progress {\n background-color: rgb(66, 129, 235);\n height: 3px;\n left: 0;\n position: absolute;\n top: 100%; /* Align with the bottom edge of the parent. */\n width: 0;\n z-index: 2; /* Above .screencast-glasspane. */\n}\n\n.screencast-viewport {\n display: flex;\n border: 1px solid #999;\n border-radius: 20px;\n flex: none;\n padding: 20px;\n margin: 10px;\n background-color: #eee;\n}\n\n.screencast-canvas-container {\n flex: auto;\n display: flex;\n border: 1px solid #999;\n position: relative;\n cursor: -webkit-image-set(url(Images/touchCursor.png) 1x, url(Images/touchCursor_2x.png) 2x), default;\n}\n\n.screencast canvas {\n flex: auto;\n position: relative;\n}\n\n.screencast-px {\n color: rgb(128, 128, 128);\n}\n\n.screencast-element-title {\n position: absolute;\n z-index: 10;\n}\n\n.screencast-tag-name {\n /* Keep this in sync with view-source.css (.webkit-html-tag) */\n color: rgb(136, 18, 128);\n}\n\n.screencast-node-id {\n /* Keep this
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
<meta name="referrer" content="no-referrer">
<script type="text/javascript" src="shell.js"></script>
<script type="text/javascript" src="js_app.js"></script>
<script>Runtime.startApplication('js_app');</script>
</head>
<body class="undocked" id="-blink-dev-tools"></body>
</html>
allDescriptors.push(...[{"dependencies":["components"],"extensions":[{"className":"JsMain.JsMain","type":"early-initialization"}],"name":"js_main"},{"dependencies":["profiler"],"extensions":[{"title":"Profiler","id":"js_profiler","className":"Profiler.JSProfilerPanel","location":"panel","type":"view","order":65}],"name":"js_profiler"}]);applicationDescriptor.modules.push(...[{"type":"autostart","name":"js_main"},{"name":"js_profiler"}])
self['JsMain']=self['JsMain']||{};JsMain.JsMain=class extends Common.Object{run(){Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConnectToNodeJSDirectly);SDK.initMainConnection(()=>{const target=SDK.targetManager.createTarget('main',ls`Main`,SDK.Target.Type.Node,null);target.runtimeAgent().runIfWaitingForDebugger();},Components.TargetDetachedDialog.webSocketConnectionLost);}};;;<!--
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
<meta name="referrer" content="no-referrer">
<script type="text/javascript" src="shell.js"></script>
<script type="text/javascript" src="node_app.js"></script>
<script>Runtime.startApplication('node_app');</script>
</head>
<body class="undocked" id="-blink-dev-tools"></body>
</html>
allDescriptors.push(...[{"dependencies":["sources"],"extensions":[{"title":"Node","id":"navigator-network","className":"Sources.NetworkNavigatorView","location":"navigator-view","type":"view","order":2,"persistence":"permanent"}],"name":"node_debugger"},{"dependencies":["profiler"],"extensions":[{"title":"Profiler","id":"js_profiler","className":"Profiler.JSProfilerPanel","location":"panel","type":"view","order":65}],"name":"js_profiler"},{"dependencies":["platform","ui","host","components"],"extensions":[{"className":"NodeMain.NodeMain","type":"early-initialization"},{"title":"Connection","tags":"node","id":"node-connection","className":"NodeMain.NodeConnectionsPanel","location":"panel","type":"view","order":0}],"name":"node_main"}]);applicationDescriptor.modules.push(...[{"name":"node_debugger"},{"name":"js_profiler"},{"type":"autostart","name":"node_main"}])
self['NodeMain']=self['NodeMain']||{};NodeMain.NodeConnectionsPanel=class extends UI.Panel{constructor(){super('node-connection');this.registerRequiredCSS('node_main/nodeConnectionsPanel.css');this.contentElement.classList.add('node-panel');const container=this.contentElement.createChild('div','node-panel-center');const image=container.createChild('img','node-panel-logo');image.src='https://nodejs.org/static/images/logos/nodejs-new-pantone-black.png';InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,this._devicesDiscoveryConfigChanged,this);this._config;this.contentElement.tabIndex=0;this.setDefaultFocusedElement(this.contentElement);InspectorFrontendHost.setDevicesUpdatesEnabled(false);InspectorFrontendHost.setDevicesUpdatesEnabled(true);this._networkDiscoveryView=new NodeMain.NodeConnectionsView(config=>{this._config.networkDiscoveryConfig=config;InspectorFrontendHost.setDevicesDiscoveryConfig(this._config);});this._networkDiscoveryView.show(container);}
_devicesDiscoveryConfigChanged(event){this._config=(event.data);this._networkDiscoveryView.discoveryConfigChanged(this._config.networkDiscoveryConfig);}};NodeMain.NodeConnectionsView=class extends UI.VBox{constructor(callback){super();this._callback=callback;this.element.classList.add('network-discovery-view');const networkDiscoveryFooter=this.element.createChild('div','network-discovery-footer');networkDiscoveryFooter.createChild('span').textContent=Common.UIString('Specify network endpoint and DevTools will connect to it automatically. ');const link=networkDiscoveryFooter.createChild('span','link');link.textContent=Common.UIString('Learn more');link.addEventListener('click',()=>InspectorFrontendHost.openInNewTab('https://nodejs.org/en/docs/inspector/'));this._list=new UI.ListWidget(this);this._list.registerRequiredCSS('node_main/nodeConnectionsPanel.css');this._list.element.classList.add('network-discovery-list');const placeholder=createElementWithClass('div','network-discovery-list-empty');placeholder.textContent=Common.UIString('No connections specified');this._list.setEmptyPlaceholder(placeholder);this._list.show(this.element);this._editor=null;const addButton=UI.createTextButton(Common.UIString('Add connection'),this._addNetworkTargetButtonClicked.bind(this),'add-network-target-button',true);this.element.appendChild(addButton);this._networkDiscoveryConfig=[];this.element.classList.add('node-frontend');}
_update(){const config=this._networkDiscoveryConfig.map(item=>item.address);this._callback.call(null,config);}
_addNetworkTargetButtonClicked(){this._list.addNewItem(this._networkDiscoveryConfig.length,{address:'',port:''});}
discoveryConfigChanged(networkDiscoveryConfig){this._networkDiscoveryConfig=[];this._list.clear();for(const address of networkDiscoveryConfig){const item={address:address,port:''};this._networkDiscoveryConfig.push(item);this._list.appendItem(item,true);}}
renderItem(rule,editable){const element=createElementWithClass('div','network-discovery-list-item');element.createChild('div','network-discovery-value network-discovery-address').textContent=rule.address;return element;}
removeItemRequested(rule,index){this._networkDiscoveryConfig.splice(index,1);this._list.removeItem(index);this._update();}
commitEdit(rule,editor,isNew){rule.address=editor.control('address').value.trim();if(isNew)
this._networkDiscoveryConfig.push(rule);this._update();}
beginEdit(rule){const editor=this._createEditor();editor.control('address').value=rule.address;return editor;}
_createEditor(){if(this._editor)
return this._editor;const editor=new UI.ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const fields=content.createChild('div','network-discovery-edit-row');const input=editor.createInput('address','text',ls`Network address (e.g. localhost:9229)`,addressValidator);fields.createChild('div','network-discovery-value network-discovery-address').appendChild(input);return editor;function addressValidator(rule,index,input){const match=input.value.trim().match(/^([a-zA-Z0-9\.\-_]+):(\d+)$/);if(!match)
return false;const port=parseInt(match[2],10);return port<=65535;}}};;NodeMain.NodeMain=class extends Common.Object{run(){Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConnectToNodeJSFromFrontend);SDK.initMainConnection(()=>{const target=SDK.targetManager.createTarget('main',Common.UIString('Main'),SDK.Target.Type.Browser,null);target.setInspectedURL('Node.js');},Components.TargetDetachedDialog.webSocketConnectionLost);}};NodeMain.NodeChildTargetManager=class extends SDK.SDKModel{constructor(parentTarget){super(parentTarget);this._targetManager=parentTarget.targetManager();this._parentTarget=parentTarget;this._targetAgent=parentTarget.targetAgent();this._childTargets=new Map();this._childConnections=new Map();parentTarget.registerTargetDispatcher(this);this._targetAgent.setDiscoverTargets(true);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,this._devicesDiscoveryConfigChanged,this);InspectorFrontendHost.setDevicesUpdatesEnabled(false);InspectorFrontendHost.setDevicesUpdatesEnabled(true);}
_devicesDiscoveryConfigChanged(event){const config=(event.data);const locations=[];for(const address of config.networkDiscoveryConfig){const parts=address.split(':');const port=parseInt(parts[1],10);if(parts[0]&&port)
locations.push({host:parts[0],port:port});}
this._targetAgent.setRemoteLocations(locations);}
dispose(){InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,this._devicesDiscoveryConfigChanged,this);for(const sessionId of this._childTargets.keys())
this.detachedFromTarget(sessionId,undefined);}
targetCreated(targetInfo){if(targetInfo.type==='node'&&!targetInfo.attached)
this._targetAgent.attachToTarget(targetInfo.targetId,false);}
targetInfoChanged(targetInfo){}
targetDestroyed(targetId){}
attachedToTarget(sessionId,targetInfo,waitingForDebugger){const name=ls`Node.js: ${targetInfo.url}`;const connection=new NodeMain.NodeConnection(this._targetAgent,sessionId);this._childConnections.set(sessionId,connection);const target=this._targetManager.createTarget(targetInfo.targetId,name,SDK.Target.Type.Node,this._parentTarget,undefined,undefined,connection);this._childTargets.set(sessionId,target);target.runtimeAgent().runIfWaitingForDebugger();}
detachedFromTarget(sessionId,childTargetId){this._childTargets.get(sessionId).dispose('target terminated');this._childTargets.delete(sessionId);this._childConnections.delete(sessionId);}
receivedMessageFromTarget(sessionId,message,childTargetId){const connection=this._childConnections.get(sessionId);const onMessage=connection?connection._onMessage:null;if(onMessage)
onMessage.call(null,message);}};NodeMain.NodeConnection=class{constructor(targetAgent,sessionId){this._targetAgent=targetAgent;this._sessionId=sessionId;this._onMessage=null;this._onDisconnect=null;}
setOnMessage(onMessage){this._onMessage=onMessage;}
setOnDisconnect(onDisconnect){this._onDisconnect=onDisconnect;}
sendRawMessage(message){this._targetAgent.sendMessageToTarget(message,this._sessionId);}
disconnect(){if(this._onDisconnect)
this._onDisconnect.call(null,'force disconnect');this._onDisconnect=null;this._onMessage=null;return this._targetAgent.detachFromTarget(this._sessionId);}};SDK.SDKModel.register(NodeMain.NodeChildTargetManager,SDK.Target.Capability.Target,true);;;Runtime.cachedResources["node_main/nodeConnectionsPanel.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.add-network-target-button {\n margin: 10px 25px;\n align-self: flex-start;\n}\n\n.network-discovery-list {\n margin: 10px 0 0 25px;\n max-width: 500px;\n flex: none;\n}\n\n.network-discovery-list-empty {\n flex: auto;\n height: 30px;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.network-discovery-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n position: relative;\n flex: auto 1 1;\n}\n\n.list-item .network-discovery-value {\n white-space: nowrap;\n text-overflow: ellipsis;\n -webkit-user-select: none;\n color: #222;\n overflow: hidden;\n}\n\n.network-discovery-value {\n flex: 3 1 0;\n}\n\n.network-discovery-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 6px 5px;\n align-items: center;\n}\n\n.network-discovery-edit-row input {\n width: 100%;\n text-align: inherit;\n}\n\n.network-discovery-footer {\n overflow: hidden;\n margin: 15px 0 0 25px;\n max-width: 500px;\n}\n\n.network-discovery-footer > * {\n white-space: pre-wrap;\n}\n\n.node-panel {\n align-items: center;\n justify-content: flex-start;\n}\n\n.network-discovery-view {\n min-width: 400px;\n flex: auto;\n}\n\n.add-network-target-button {\n align-self: center;\n}\n\n:host-context(.node-frontend) .network-discovery-list-empty {\n height: 40px;\n}\n\n:host-context(.node-frontend) .network-discovery-list-item {\n padding: 3px 15px;\n height: 40px;\n}\n\n.network-discovery-list {\n margin: 20px 0 5px 0;\n max-width: 600px;\n max-height: 202px;\n}\n\n.network-discovery-footer {\n margin: 0;\n}\n\n.node-panel-center {\n display: flex;\n align-items: stretch;\n justify-content: center;\n max-width: 600px;\n flex-direction: column;\n padding-top: 50px;\n}\n\n.node-panel-logo {\n align-self: center;\n width: 400px;\n margin-bottom: 50px;\n flex: none;\n}\n\n:host-context(.node-frontend) .network-discovery-edit-row input {\n height: 30px;\n padding-left: 5px;\n}\n\n:host-context(.node-frontend) .network-discovery-edit-row {\n margin: 6px 9px;\n}\n\n/*# sourceURL=node_main/nodeConnectionsPanel.css */";const allDescriptors=[];let applicationDescriptor;const _loadedScripts={};for(const k of[]){}
(function(){const baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();const REMOTE_MODULE_FALLBACK_REVISION='@010ddcfda246975d194964ccf20038ebbdec6084';var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(let i=0;i<descriptors.length;++i)
this._registerModule(descriptors[i]);}
static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){const xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE)
return;const status=/^HTTP\/1.1 404/.test(e.target.response)?404:xhr.status;if([0,200,304].indexOf(status)===-1)
reject(new Error('While loading from url '+url+' server responded with a status of '+status));else
fulfill(e.target.response);}
xhr.send(null);}}
static loadResourcePromiseWithFallback(url){return Runtime.loadResourcePromise(url).catch(err=>{const urlWithFallbackVersion=url.replace(/@[0-9a-f]{40}/,REMOTE_MODULE_FALLBACK_REVISION);if(urlWithFallbackVersion===url||!url.includes('audits2_worker_module'))
throw err;return Runtime.loadResourcePromise(urlWithFallbackVersion);});}
static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1)
return path;const normalizedSegments=[];const segments=path.split('/');for(let i=0;i<segments.length;i++){const segment=segments[i];if(segment==='.')
continue;else if(segment==='..')
normalizedSegments.pop();else if(segment)
normalizedSegments.push(segment);}
let normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/')
return normalizedPath;if(path[0]==='/'&&normalizedPath)
normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..'))
normalizedPath=normalizedPath+'/';return normalizedPath;}
static _loadScriptsPromise(scriptNames,base){const promises=[];const urls=[];const sources=new Array(scriptNames.length);let scriptToEval=0;for(let i=0;i<scriptNames.length;++i){const scriptName=scriptNames[i];let sourceURL=(base||self._importScriptPathPrefix)+scriptName;const schemaIndex=sourceURL.indexOf('://')+3;let pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1)
pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL])
continue;urls.push(sourceURL);const loadResourcePromise=base?Runtime.loadResourcePromiseWithFallback(sourceURL):Runtime.loadResourcePromise(sourceURL);promises.push(loadResourcePromise.then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));}
return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}}
function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;}
self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}}
static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;}
const sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}}
static async appStarted(){return Runtime._appStartedPromise;}
static async startApplication(appName){console.timeStamp('Runtime.startApplication');const allDescriptorsByName={};for(let i=0;i<allDescriptors.length;++i){const d=allDescriptors[i];allDescriptorsByName[d['name']]=d;}
if(!applicationDescriptor){let data=await Runtime.loadResourcePromise(appName+'.json');applicationDescriptor=JSON.parse(data);let descriptor=applicationDescriptor;while(descriptor.extends){data=await Runtime.loadResourcePromise(descriptor.extends+'.json');descriptor=JSON.parse(data);applicationDescriptor.modules=descriptor.modules.concat(applicationDescriptor.modules);}}
const configuration=applicationDescriptor.modules;const moduleJSONPromises=[];const coreModuleNames=[];for(let i=0;i<configuration.length;++i){const descriptor=configuration[i];const name=descriptor['name'];const moduleJSON=allDescriptorsByName[name];if(moduleJSON)
moduleJSONPromises.push(Promise.resolve(moduleJSON));else
moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart')
coreModuleNames.push(name);}
const moduleDescriptors=await Promise.all(moduleJSONPromises);for(let i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';}
self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames)
await self.runtime._loadAutoStartModules(coreModuleNames);Runtime._appStartedPromiseCallback();}
static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}}
static queryParam(name){return Runtime._queryParamsObject.get(name);}
static queryParamsString(){return location.search;}
static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}}
static _assert(value,message){if(value)
return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);}
static setPlatform(platform){Runtime._platform=platform;}
static _isDescriptorEnabled(descriptor){const activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*')
return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1)))
return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment))
return false;const condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition))
return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1)))
return false;return true;}
static resolveSourceURL(path){let sourceURL=self.location.href;if(self.location.search)
sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';}
static setL10nCallback(localizationFunction){Runtime._l10nCallback=localizationFunction;}
useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend'))
Runtime._remoteBase+='debug/';}
_registerModule(descriptor){const module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;}
loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();}
_loadAutoStartModules(moduleNames){const promises=[];for(let i=0;i<moduleNames.length;++i)
promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);}
_checkExtensionApplicability(extension,predicate){if(!predicate)
return false;const contextTypes=extension.descriptor().contextTypes;if(!contextTypes)
return true;for(let i=0;i<contextTypes.length;++i){const contextType=this._resolve(contextTypes[i]);const isMatching=!!contextType&&predicate(contextType);if(isMatching)
return true;}
return false;}
isExtensionApplicableToContext(extension,context){if(!context)
return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}}
isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes)
return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}}
extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type)
return false;if(!extension.enabled())
return false;return!context||extension.isApplicable(context);}
function orderComparator(extension1,extension2){const order1=extension1.descriptor()['order']||0;const order2=extension2.descriptor()['order']||0;return order1-order2;}
function titleComparator(extension1,extension2){const title1=extension1.title()||'';const title2=extension2.title()||'';return title1.localeCompare(title2);}}
extension(type,context){return this.extensions(type,context)[0]||null;}
allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));}
_resolve(typeName){if(!this._cachedTypeClasses[typeName]){const path=typeName.split('.');let object=self;for(let i=0;object&&(i<path.length);++i)
object=object[path[i]];if(object)
this._cachedTypeClasses[typeName]=(object);}
return this._cachedTypeClasses[typeName]||null;}
sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction&&Object.getOwnPropertySymbols(constructorFunction).includes(Runtime._instanceSymbol))
return constructorFunction[Runtime._instanceSymbol];const instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject=new URLSearchParams(Runtime.queryParamsString());Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();const extensions=(descriptor.extensions);for(let i=0;extensions&&i<extensions.length;++i){const extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);}
this._loadedForTest=false;}
name(){return this._name;}
enabled(){return Runtime._isDescriptorEnabled(this._descriptor);}
resource(name){const fullName=this._name+'/'+name;const content=Runtime.cachedResources[fullName];if(!content)
throw new Error(fullName+' not preloaded. Check module.json');return content;}
_loadPromise(){if(!this.enabled())
return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise)
return this._pendingLoadPromise;const dependencies=this._descriptor.dependencies;const dependencyPromises=[];for(let i=0;dependencies&&i<dependencies.length;++i)
dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;}
_loadResources(){const resources=this._descriptor['resources'];if(!resources||!resources.length)
return Promise.resolve();const promises=[];for(let i=0;i<resources.length;++i){const url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));}
return Promise.all(promises).then(undefined);}
_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length)
return Promise.resolve();const specialCases={'sdk':'SDK','js_sdk':'JSSDK','browser_sdk':'BrowserSDK','ui':'UI','object_ui':'ObjectUI','javascript_metadata':'JavaScriptMetadata','perf_ui':'PerfUI','har_importer':'HARImporter','sdk_test_runner':'SDKTestRunner','cpu_profiler_test_runner':'CPUProfilerTestRunner'};const namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());}
_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);}
_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;}
substituteURL(value){const base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;}
descriptor(){return this._descriptor;}
module(){return this._module;}
enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());}
_typeClass(){if(!this._hasTypeClass)
return null;return this._module._manager._resolve(this._type.substring(1));}
isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);}
instance(){return this._module._loadPromise().then(this._createInstance.bind(this));}
canInstantiate(){return!!(this._className||this._factoryName);}
_createInstance(){const className=this._className||this._factoryName;if(!className)
throw new Error('Could not instantiate extension with no class');const constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function))
throw new Error('Could not instantiate: '+className);if(this._className)
return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);}
title(){const title=this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];if(title&&Runtime._l10nCallback)
return Runtime._l10nCallback(title);return title;}
hasContextType(contextType){const contextTypes=this.descriptor().contextTypes;if(!contextTypes)
return false;for(let i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i]))
return true;}
return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
allConfigurableExperiments(){const result=[];for(let i=0;i<this._experiments.length;i++){const experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name])
result.push(experiment);}
return result;}
supportEnabled(){return this._supportEnabled;}
_setExperimentsSetting(value){if(!self.localStorage)
return;self.localStorage['experiments']=JSON.stringify(value);}
register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));}
isEnabled(experimentName){this._checkExperiment(experimentName);if(Runtime._experimentsSetting()[experimentName]===false)
return false;if(this._enabledTransiently[experimentName])
return true;if(!this.supportEnabled())
return false;return!!Runtime._experimentsSetting()[experimentName];}
setEnabled(experimentName,enabled){this._checkExperiment(experimentName);const experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);}
setDefaultExperiments(experimentNames){for(let i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}}
enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;}
clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
cleanUpStaleExperiments(){const experimentsSetting=Runtime._experimentsSetting();const cleanedUpExperimentSetting={};for(let i=0;i<this._experiments.length;++i){const experimentName=this._experiments[i].name;if(experimentsSetting[experimentName])
cleanedUpExperimentSetting[experimentName]=true;}
this._setExperimentsSetting(cleanedUpExperimentSetting);}
_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;}
isEnabled(){return this._experiments.isEnabled(this.name);}
setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._appStartedPromiseCallback;Runtime._appStartedPromise=new Promise(fulfil=>Runtime._appStartedPromiseCallback=fulfil);Runtime._l10nCallback;Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){const versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch)
Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){}
ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;allDescriptors.push(...[{"dependencies":["ui","platform","common","cm"],"extensions":[{"className":"TextEditor.CodeMirrorUtils.TokenizerFactory","type":"@TextUtils.TokenizerFactory"},{"className":"TextEditor.CodeMirrorTextEditorFactory","type":"@UI.TextEditorFactory"}],"name":"text_editor","scripts":["text_editor_module.js"],"skip_compilation":["acorn/acorn.js","../cm_web_modes/css.js","../cm_web_modes/javascript.js","../cm_web_modes/xml.js","../cm_web_modes/htmlmixed.js","../cm_web_modes/htmlembedded.js"]},{"skip_compilation":["../InspectorBackendCommands.js"],"dependencies":["common","host"],"name":"protocol"},{"skip_compilation":["codemirror.js","multiplex.js","matchbrackets.js","closebrackets.js","markselection.js","comment.js","overlay.js","activeline.js","foldcode.js","foldgutter.js","brace-fold.js"],"name":"cm","scripts":["cm_module.js"]},{"dependencies":["text_editor"],"extensions":[{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-csrc","text/x-c","text/x-chdr","text/x-c++src","text/x-c++hdr","text/x-java","text/x-csharp","text/x-scala","x-shader/x-vertex","x-shader/x-fragment"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"clike.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-coffeescript"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"coffeescript.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/markdown","text/x-markdown"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"markdown.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["application/x-httpd-php","application/x-httpd-php-open","text/x-php"],"dependencies":["clike.js"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"php.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-python","text/x-cython"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"python.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-sh"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"shell.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-livescript"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"livescript.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-clojure"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"clojure.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/jsx","text/typescript-jsx"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"jsx.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-styl"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"stylus.js"}],"name":"cm_modes","scripts":["cm_modes_module.js"]},{"dependencies":["components","search","source_frame","snippets","extensions","persistence","quick_open","inline_editor","color_picker","event_listeners","object_ui","formatter"],"extensions":[{"title":"Sources","id":"sources","className":"Sources.SourcesPanel","location":"panel","type":"view","order":30},{"className":"Sources.SourcesPanel","contextTypes":["Workspace.UISourceCode","Workspace.UILocation","SDK.RemoteObject","SDK.NetworkRequest","Sources.UISourceCodeFrame"],"type":"@UI.ContextMenu.Provider"},{"category":"Debugger","iconClass":"largeicon-pause","toggledIconClass":"largeicon-resume","className":"Sources.SourcesPanel.RevealingActionDelegate","contextTypes":["Sources.SourcesView","UI.ShortcutRegistry.ForwardedShortcut"],"actionId":"debugger.toggle-pause","bindings":[{"platform":"windows,linux","shortcut":"F8 Ctrl+\\"},{"platform":"mac","shortcut":"F8 Meta+\\"}],"type":"action","options":[{"value":true,"title":"Pause script execution"},{"value":false,"title":"Resume script execution"}]},{"category":"Debugger","iconClass":"largeicon-step-over","title":"Step over next function call","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["SDK.DebuggerPausedDetails"],"actionId":"debugger.step-over","bindings":[{"platform":"windows,linux","shortcut":"F10 Ctrl+'"},{"platform
self['Platform']=self['Platform']||{};let ArrayLike;function mod(m,n){return((m%n)+n)%n;}
String.prototype.findAll=function(string){const matches=[];let i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);}
return matches;};String.prototype.reverse=function(){return this.split('').reverse().join('');};String.prototype.replaceControlCharacters=function(){return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,'<27>');};String.prototype.isWhitespace=function(){return/^\s*$/.test(this);};String.prototype.computeLineEndings=function(){const endings=this.findAll('\n');endings.push(this.length);return endings;};String.prototype.escapeCharacters=function(chars){let foundChar=false;for(let i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}}
if(!foundChar)
return String(this);let result='';for(let i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1)
result+='\\';result+=this.charAt(i);}
return result;};String.regexSpecialCharacters=function(){return'^[]{}()\\.^$*+?|-,';};String.prototype.escapeForRegExp=function(){return this.escapeCharacters(String.regexSpecialCharacters());};String.filterRegex=function(query){const toEscape=String.regexSpecialCharacters();let regexString='';for(let i=0;i<query.length;++i){let c=query.charAt(i);if(toEscape.indexOf(c)!==-1)
c='\\'+c;if(i)
regexString+='[^\\0'+c+']*';regexString+=c;}
return new RegExp(regexString,'i');};String.escapeInvalidUnicodeCharacters=function(text){if(!String._invalidCharactersRegExp){let invalidCharacters='';for(let i=0xfffe;i<=0x10ffff;i+=0x10000)
invalidCharacters+=String.fromCodePoint(i,i+1);String._invalidCharactersRegExp=new RegExp(`[${invalidCharacters}\uD800-\uDFFF\uFDD0-\uFDEF]`,'gu');}
let result='';let lastPos=0;while(true){const match=String._invalidCharactersRegExp.exec(text);if(!match)
break;result+=text.substring(lastPos,match.index)+'\\u'+text.charCodeAt(match.index).toString(16);if(match.index+1<String._invalidCharactersRegExp.lastIndex)
result+='\\u'+text.charCodeAt(match.index+1).toString(16);lastPos=String._invalidCharactersRegExp.lastIndex;}
return result+text.substring(lastPos);};String.prototype.escapeHTML=function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');};String.prototype.unescapeHTML=function(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&#58;/g,':').replace(/&quot;/g,'"').replace(/&#60;/g,'<').replace(/&#62;/g,'>').replace(/&amp;/g,'&');};String.prototype.collapseWhitespace=function(){return this.replace(/[\s\xA0]+/g,' ');};String.prototype.trimMiddle=function(maxLength){if(this.length<=maxLength)
return String(this);let leftHalf=maxLength>>1;let rightHalf=maxLength-leftHalf-1;if(this.codePointAt(this.length-rightHalf-1)>=0x10000){--rightHalf;++leftHalf;}
if(leftHalf>0&&this.codePointAt(leftHalf-1)>=0x10000)
--leftHalf;return this.substr(0,leftHalf)+'\u2026'+this.substr(this.length-rightHalf,rightHalf);};String.prototype.trimEnd=function(maxLength){if(this.length<=maxLength)
return String(this);return this.substr(0,maxLength-1)+'\u2026';};String.prototype.trimURL=function(baseURLDomain){let result=this.replace(/^(https|http|file):\/\//i,'');if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase()))
result=result.substr(baseURLDomain.length);}
return result;};String.prototype.toTitleCase=function(){return this.substring(0,1).toUpperCase()+this.substring(1);};String.prototype.compareTo=function(other){if(this>other)
return 1;if(this<other)
return-1;return 0;};String.prototype.removeURLFragment=function(){let fragmentIndex=this.indexOf('#');if(fragmentIndex===-1)
fragmentIndex=this.length;return this.substring(0,fragmentIndex);};String.hashCode=function(string){if(!string)
return 0;const p=((1<<30)*4-5);const z=0x5033d967;const z2=0x59d2f15d;let s=0;let zi=1;for(let i=0;i<string.length;i++){const xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;}
s=(s+zi*(p-1))%p;return Math.abs(s|0);};String.isDigitAt=function(string,index){const c=string.charCodeAt(index);return(48<=c&&c<=57);};String.prototype.toBase64=function(){function encodeBits(b){return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;}
const encoder=new TextEncoder();const data=encoder.encode(this.toString());const n=data.length;let encoded='';if(n===0)
return encoded;let shift;let v=0;for(let i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}}
if(shift===0)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);else if(shift===1)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);return encoded;};String.naturalOrderComparator=function(a,b){const chunk=/^\d+|^\D+/;let chunka,chunkb,anum,bnum;while(1){if(a){if(!b)
return 1;}else{if(b)
return-1;else
return 0;}
chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum)
return-1;if(bnum&&!anum)
return 1;if(anum&&bnum){const diff=chunka-chunkb;if(diff)
return diff;if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb)
return chunka.length-chunkb.length;else
return chunkb.length-chunka.length;}}else if(chunka!==chunkb){return(chunka<chunkb)?-1:1;}
a=a.substring(chunka.length);b=b.substring(chunkb.length);}};String.caseInsensetiveComparator=function(a,b){a=a.toUpperCase();b=b.toUpperCase();if(a===b)
return 0;return a>b?1:-1;};Number.constrain=function(num,min,max){if(num<min)
num=min;else if(num>max)
num=max;return num;};Number.gcd=function(a,b){if(b===0)
return a;else
return Number.gcd(b,a%b);};Number.toFixedIfFloating=function(value){if(!value||isNaN(value))
return value;const number=Number(value);return number%1?number.toFixed(3):String(number);};Date.prototype.isValid=function(){return!isNaN(this.getTime());};Date.prototype.toISO8601Compact=function(){function leadZero(x){return(x>9?'':'0')+x;}
return this.getFullYear()+leadZero(this.getMonth()+1)+leadZero(this.getDate())+'T'+
leadZero(this.getHours())+leadZero(this.getMinutes())+leadZero(this.getSeconds());};Object.defineProperty(Array.prototype,'remove',{value:function(value,firstOnly){let index=this.indexOf(value);if(index===-1)
return false;if(firstOnly){this.splice(index,1);return true;}
for(let i=index+1,n=this.length;i<n;++i){if(this[i]!==value)
this[index++]=this[i];}
this.length=index;return true;}});Object.defineProperty(Array.prototype,'pushAll',{value:function(array){for(let i=0;i<array.length;++i)
this.push(array[i]);}});Object.defineProperty(Array.prototype,'rotate',{value:function(index){const result=[];for(let i=index;i<index+this.length;++i)
result.push(this[i%this.length]);return result;}});Object.defineProperty(Array.prototype,'sortNumbers',{value:function(){function numericComparator(a,b){return a-b;}
this.sort(numericComparator);}});Object.defineProperty(Uint32Array.prototype,'sort',{value:Array.prototype.sort});(function(){const partition={value:function(comparator,left,right,pivotIndex){function swap(array,i1,i2){const temp=array[i1];array[i1]=array[i2];array[i2]=temp;}
const pivotValue=this[pivotIndex];swap(this,right,pivotIndex);let storeIndex=left;for(let i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}}
swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,'partition',partition);Object.defineProperty(Uint32Array.prototype,'partition',partition);const sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight){function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight){if(right<=left)
return;const pivotIndex=Math.floor(Math.random()*(right-left))+left;const pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex)
quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);if(pivotNewIndex<sortWindowRight)
quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);}
if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound)
this.sort(comparator);else
quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);return this;}};Object.defineProperty(Array.prototype,'sortRange',sortRange);Object.defineProperty(Uint32Array.prototype,'sortRange',sortRange);})();Object.defineProperty(Array.prototype,'stableSort',{value:function(comparator){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;const indices=new Array(this.length);for(let i=0;i<this.length;++i)
indices[i]=i;const self=this;function indexComparator(a,b){const result=comparator(self[a],self[b]);return result?result:a-b;}
indices.sort(indexComparator);for(let i=0;i<this.length;++i){if(indices[i]<0||i===indices[i])
continue;let cyclical=i;const saved=this[i];while(true){const next=indices[cyclical];indices[cyclical]=-1;if(next===i){this[cyclical]=saved;break;}else{this[cyclical]=this[next];cyclical=next;}}}
return this;}});Object.defineProperty(Array.prototype,'qselect',{value:function(k,comparator){if(k<0||k>=this.length)
return;if(!comparator){comparator=function(a,b){return a-b;};}
let low=0;let high=this.length-1;for(;;){const pivotPosition=this.partition(comparator,low,high,Math.floor((high+low)/2));if(pivotPosition===k)
return this[k];else if(pivotPosition>k)
high=pivotPosition-1;else
low=pivotPosition+1;}}});Object.defineProperty(Array.prototype,'lowerBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Array.prototype,'upperBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>=0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Uint32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Int32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Int32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,'binaryIndexOf',{value:function(value,comparator){const index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,'select',{value:function(field){const result=new Array(this.length);for(let i=0;i<this.length;++i)
result[i]=this[i][field];return result;}});Object.defineProperty(Array.prototype,'peekLast',{value:function(){return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect){const result=[];let i=0;let j=0;while(i<array1.length&&j<array2.length){const compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue)
result.push(compareValue<=0?array1[i]:array2[j]);if(compareValue<=0)
i++;if(compareValue>=0)
j++;}
if(mergeNotIntersect){while(i<array1.length)
result.push(array1[i++]);while(j<array2.length)
result.push(array2[j++]);}
return result;}
Object.defineProperty(Array.prototype,'intersectOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,'mergeOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg){return String.vsprintf(format,Array.prototype.slice.call(arguments,1));};String.tokenizeFormatString=function(format,formatters){const tokens=[];function addStringToken(str){if(!str)
return;if(tokens.length&&tokens[tokens.length-1].type==='string')
tokens[tokens.length-1].value+=str;else
tokens.push({type:'string',value:str});}
function addSpecifierToken(specifier,precision,substitutionIndex){tokens.push({type:'specifier',specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});}
function addAnsiColor(code){const types={3:'color',9:'colorLight',4:'bgColor',10:'bgColorLight'};const colorCodes=['black','red','green','yellow','blue','magenta','cyan','lightGray','','default'];const colorCodesLight=['darkGray','lightRed','lightGreen','lightYellow','lightBlue','lightMagenta','lightCyan','white',''];const colors={color:colorCodes,colorLight:colorCodesLight,bgColor:colorCodes,bgColorLight:colorCodesLight};const type=types[Math.floor(code/10)];if(!type)
return;const color=colors[type][code%10];if(!color)
return;tokens.push({type:'specifier',specifier:'c',value:{description:(type.startsWith('bg')?'background : ':'color: ')+color}});}
let textStart=0;let substitutionIndex=0;const re=new RegExp(`%%|%(?:(\\d+)\\$)?(?:\\.(\\d*))?([${Object.keys(formatters).join('')}])|\\u001b\\[(\\d+)m`,'g');for(let match=re.exec(format);!!match;match=re.exec(format)){const matchStart=match.index;if(matchStart>textStart)
addStringToken(format.substring(textStart,matchStart));if(match[0]==='%%'){addStringToken('%');}else if(match[0].startsWith('%')){const[_,substitionString,precisionString,specifierString]=match;if(substitionString&&Number(substitionString)>0)
substitutionIndex=Number(substitionString)-1;const precision=precisionString?Number(precisionString):-1;addSpecifierToken(specifierString,precision,substitutionIndex);++substitutionIndex;}else{const code=Number(match[4]);addAnsiColor(code);}
textStart=matchStart+match[0].length;}
addStringToken(format.substring(textStart));return tokens;};String.standardFormatters={d:function(substitution){return!isNaN(substitution)?substitution:0;},f:function(substitution,token){if(substitution&&token.precision>-1)
substitution=substitution.toFixed(token.precision);return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution){return substitution;}};String.vsprintf=function(format,substitutions){return String.format(format,substitutions,String.standardFormatters,'',function(a,b){return a+b;}).formattedResult;};String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat){if(!format||((!substitutions||!substitutions.length)&&format.search(/\u001b\[(\d+)m/)===-1))
return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName(){return'String.format("'+format+'", "'+Array.prototype.join.call(substitutions,'", "')+'")';}
function warn(msg){console.warn(prettyFunctionName()+': '+msg);}
function error(msg){console.error(prettyFunctionName()+': '+msg);}
let result=initialValue;const tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);const usedSubstitutionIndexes={};for(let i=0;i<tokens.length;++i){const token=tokens[i];if(token.type==='string'){result=append(result,token.value);continue;}
if(token.type!=='specifier'){error('Unknown token type "'+token.type+'" found.');continue;}
if(!token.value&&token.substitutionIndex>=substitutions.length){error('not enough substitution arguments. Had '+substitutions.length+' but needed '+
(token.substitutionIndex+1)+', so substitution was skipped.');result=append(result,'%'+(token.precision>-1?token.precision:'')+token.specifier);continue;}
if(!token.value)
usedSubstitutionIndexes[token.substitutionIndex]=true;if(!(token.specifier in formatters)){warn('unsupported format character \u201C'+token.specifier+'\u201D. Treating as a string.');result=append(result,token.value?'':substitutions[token.substitutionIndex]);continue;}
result=append(result,formatters[token.specifier](token.value||substitutions[token.substitutionIndex],token));}
const unusedSubstitutions=[];for(let i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes)
continue;unusedSubstitutions.push(substitutions[i]);}
return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};};function createSearchRegex(query,caseSensitive,isRegex){const regexFlags=caseSensitive?'g':'gi';let regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}}
if(!regexObject)
regexObject=createPlainTextSearchRegex(query,regexFlags);return regexObject;}
function createPlainTextSearchRegex(query,flags){const regexSpecialCharacters=String.regexSpecialCharacters();let regex='';for(let i=0;i<query.length;++i){const c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1)
regex+='\\';regex+=c;}
return new RegExp(regex,flags||'');}
function countRegexMatches(regex,content){let text=content;let result=0;let match;while(text&&(match=regex.exec(text))){if(match[0].length>0)
++result;text=text.substring(match.index+1);}
return result;}
function spacesPadding(spacesCount){return'\u00a0'.repeat(spacesCount);}
function numberToStringWithSpacesPadding(value,symbolsCount){const numberString=value.toString();const paddingLength=Math.max(0,symbolsCount-numberString.length);return spacesPadding(paddingLength)+numberString;}
Set.prototype.valuesArray=function(){return Array.from(this.values());};Set.prototype.firstValue=function(){if(!this.size)
return null;return this.values().next().value;};Set.prototype.addAll=function(iterable){for(const e of iterable)
this.add(e);};Set.prototype.containsAll=function(iterable){for(const e of iterable){if(!this.has(e))
return false;}
return true;};Map.prototype.remove=function(key){const value=this.get(key);this.delete(key);return value;};Map.prototype.valuesArray=function(){return Array.from(this.values());};Map.prototype.keysArray=function(){return Array.from(this.keys());};Map.prototype.inverse=function(){const result=new Multimap();for(const key of this.keys()){const value=this.get(key);result.set(value,key);}
return result;};var Multimap=function(){this._map=new Map();};Multimap.prototype={set:function(key,value){let set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);}
set.add(value);},get:function(key){return this._map.get(key)||new Set();},has:function(key){return this._map.has(key);},hasValue:function(key,value){const set=this._map.get(key);if(!set)
return false;return set.has(value);},get size(){return this._map.size;},delete:function(key,value){const values=this.get(key);if(!values)
return false;const result=values.delete(value);if(!values.size)
this._map.delete(key);return result;},deleteAll:function(key){this._map.delete(key);},keysArray:function(){return this._map.keysArray();},valuesArray:function(){const result=[];const keys=this.keysArray();for(let i=0;i<keys.length;++i)
result.pushAll(this.get(keys[i]).valuesArray());return result;},clear:function(){this._map.clear();}};function loadXHR(url){return new Promise(load);function load(successCallback,failureCallback){function onReadyStateChanged(){if(xhr.readyState!==XMLHttpRequest.DONE)
return;if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;}
xhr.onreadystatechange=null;successCallback(xhr.responseText);}
const xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open('GET',url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}}
function suppressUnused(value){}
self.setImmediate=function(callback){const args=[...arguments].slice(1);Promise.resolve().then(()=>callback(...args));return 0;};Promise.prototype.spread=function(callback){return this.then(spreadPromise);function spreadPromise(arg){return callback.apply(null,arg);}};Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});};Map.prototype.diff=function(other,isEqual){const leftKeys=this.keysArray();const rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);const removed=[];const added=[];const equal=[];let leftIndex=0;let rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){const leftKey=leftKeys[leftIndex];const rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;}
if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;}
added.push(other.get(rightKey));++rightIndex;}
while(leftIndex<leftKeys.length){const leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));}
while(rightIndex<rightKeys.length){const rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));}
return{added:added,removed:removed,equal:equal};};function runOnWindowLoad(callback){function windowLoaded(){self.removeEventListener('DOMContentLoaded',windowLoaded,false);callback();}
if(document.readyState==='complete'||document.readyState==='interactive')
callback();else
self.addEventListener('DOMContentLoaded',windowLoaded,false);}
const _singletonSymbol=Symbol('singleton');function singleton(constructorFunction){if(_singletonSymbol in constructorFunction)
return constructorFunction[_singletonSymbol];const instance=new constructorFunction();constructorFunction[_singletonSymbol]=instance;return instance;}
function base64ToSize(content){if(!content)
return 0;let size=content.length*3/4;if(content[content.length-1]==='=')
size--;if(content.length>1&&content[content.length-2]==='=')
size--;return size;};self['DomExtension']=self['DomExtension']||{};Node.prototype.rangeOfWord=function(offset,stopCharacters,stayWithinNode,direction){let startNode;let startOffset=0;let endNode;let endOffset=0;if(!stayWithinNode)
stayWithinNode=this;if(!direction||direction==='backward'||direction==='both'){let node=this;while(node){if(node===stayWithinNode){if(!startNode)
startNode=stayWithinNode;break;}
if(node.nodeType===Node.TEXT_NODE){const start=(node===this?(offset-1):(node.nodeValue.length-1));for(let i=start;i>=0;--i){if(stopCharacters.indexOf(node.nodeValue[i])!==-1){startNode=node;startOffset=i+1;break;}}}
if(startNode)
break;node=node.traversePreviousNode(stayWithinNode);}
if(!startNode){startNode=stayWithinNode;startOffset=0;}}else{startNode=this;startOffset=offset;}
if(!direction||direction==='forward'||direction==='both'){let node=this;while(node){if(node===stayWithinNode){if(!endNode)
endNode=stayWithinNode;break;}
if(node.nodeType===Node.TEXT_NODE){const start=(node===this?offset:0);for(let i=start;i<node.nodeValue.length;++i){if(stopCharacters.indexOf(node.nodeValue[i])!==-1){endNode=node;endOffset=i;break;}}}
if(endNode)
break;node=node.traverseNextNode(stayWithinNode);}
if(!endNode){endNode=stayWithinNode;endOffset=stayWithinNode.nodeType===Node.TEXT_NODE?stayWithinNode.nodeValue.length:stayWithinNode.childNodes.length;}}else{endNode=this;endOffset=offset;}
const result=this.ownerDocument.createRange();result.setStart(startNode,startOffset);result.setEnd(endNode,endOffset);return result;};Node.prototype.traverseNextTextNode=function(stayWithin){let node=this.traverseNextNode(stayWithin);if(!node)
return null;const nonTextTags={'STYLE':1,'SCRIPT':1};while(node&&(node.nodeType!==Node.TEXT_NODE||nonTextTags[node.parentElement.nodeName]))
node=node.traverseNextNode(stayWithin);return node;};Element.prototype.positionAt=function(x,y,relativeTo){let shift={x:0,y:0};if(relativeTo)
shift=relativeTo.boxInWindow(this.ownerDocument.defaultView);if(typeof x==='number')
this.style.setProperty('left',(shift.x+x)+'px');else
this.style.removeProperty('left');if(typeof y==='number')
this.style.setProperty('top',(shift.y+y)+'px');else
this.style.removeProperty('top');if(typeof x==='number'||typeof y==='number')
this.style.setProperty('position','absolute');else
this.style.removeProperty('position');};Element.prototype.isScrolledToBottom=function(){return Math.abs(this.scrollTop+this.clientHeight-this.scrollHeight)<=2;};Node.prototype.enclosingNodeOrSelfWithNodeNameInArray=function(nameArray){for(let node=this;node&&node!==this.ownerDocument;node=node.parentNodeOrShadowHost()){for(let i=0;i<nameArray.length;++i){if(node.nodeName.toLowerCase()===nameArray[i].toLowerCase())
return node;}}
return null;};Node.prototype.enclosingNodeOrSelfWithNodeName=function(nodeName){return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);};Node.prototype.enclosingNodeOrSelfWithClass=function(className,stayWithin){return this.enclosingNodeOrSelfWithClassList([className],stayWithin);};Node.prototype.enclosingNodeOrSelfWithClassList=function(classNames,stayWithin){for(let node=this;node&&node!==stayWithin&&node!==this.ownerDocument;node=node.parentNodeOrShadowHost()){if(node.nodeType===Node.ELEMENT_NODE){let containsAll=true;for(let i=0;i<classNames.length&&containsAll;++i){if(!node.classList.contains(classNames[i]))
containsAll=false;}
if(containsAll)
return(node);}}
return null;};Node.prototype.parentElementOrShadowHost=function(){if(this.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&this.host)
return(this.host);const node=this.parentNode;if(!node)
return null;if(node.nodeType===Node.ELEMENT_NODE)
return(node);if(node.nodeType===Node.DOCUMENT_FRAGMENT_NODE)
return(node.host);return null;};Node.prototype.parentNodeOrShadowHost=function(){if(this.parentNode)
return this.parentNode;if(this.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&this.host)
return this.host;return null;};Node.prototype.getComponentSelection=function(){let parent=this.parentNode;while(parent&&parent.nodeType!==Node.DOCUMENT_FRAGMENT_NODE)
parent=parent.parentNode;return parent instanceof ShadowRoot?parent.getSelection():this.window().getSelection();};Node.prototype.hasSelection=function(){if(this instanceof Element){const slots=this.querySelectorAll('slot');for(const slot of slots){if(Array.prototype.some.call(slot.assignedNodes(),node=>node.hasSelection()))
return true;}}
const selection=this.getComponentSelection();if(selection.type!=='Range')
return false;return selection.containsNode(this,true)||selection.anchorNode.isSelfOrDescendant(this)||selection.focusNode.isSelfOrDescendant(this);};Node.prototype.window=function(){return(this.ownerDocument.defaultView);};Element.prototype.removeChildren=function(){if(this.firstChild)
this.textContent='';};function createElement(tagName,customElementType){return document.createElement(tagName,{is:customElementType});}
function createTextNode(data){return document.createTextNode(data);}
Document.prototype.createElementWithClass=function(elementName,className,customElementType){const element=this.createElement(elementName,{is:customElementType});if(className)
element.className=className;return element;};function createElementWithClass(elementName,className,customElementType){return document.createElementWithClass(elementName,className,customElementType);}
Document.prototype.createSVGElement=function(childType,className){const element=this.createElementNS('http://www.w3.org/2000/svg',childType);if(className)
element.setAttribute('class',className);return element;};function createSVGElement(childType,className){return document.createSVGElement(childType,className);}
function createDocumentFragment(){return document.createDocumentFragment();}
Element.prototype.createChild=function(elementName,className,customElementType){const element=this.ownerDocument.createElementWithClass(elementName,className,customElementType);this.appendChild(element);return element;};DocumentFragment.prototype.createChild=Element.prototype.createChild;Element.prototype.createTextChild=function(text){const element=this.ownerDocument.createTextNode(text);this.appendChild(element);return element;};DocumentFragment.prototype.createTextChild=Element.prototype.createTextChild;Element.prototype.createTextChildren=function(var_args){for(let i=0,n=arguments.length;i<n;++i)
this.createTextChild(arguments[i]);};DocumentFragment.prototype.createTextChildren=Element.prototype.createTextChildren;Element.prototype.totalOffsetLeft=function(){return this.totalOffset().left;};Element.prototype.totalOffsetTop=function(){return this.totalOffset().top;};Element.prototype.totalOffset=function(){const rect=this.getBoundingClientRect();return{left:rect.left,top:rect.top};};Element.prototype.createSVGChild=function(childType,className){const child=this.ownerDocument.createSVGElement(childType,className);this.appendChild(child);return child;};var AnchorBox=class{constructor(x,y,width,height){this.x=x||0;this.y=y||0;this.width=width||0;this.height=height||0;}
contains(x,y){return x>=this.x&&x<=this.x+this.width&&y>=this.y&&y<=this.y+this.height;}};AnchorBox.prototype.relativeTo=function(box){return new AnchorBox(this.x-box.x,this.y-box.y,this.width,this.height);};AnchorBox.prototype.relativeToElement=function(element){return this.relativeTo(element.boxInWindow(element.ownerDocument.defaultView));};AnchorBox.prototype.equals=function(anchorBox){return!!anchorBox&&this.x===anchorBox.x&&this.y===anchorBox.y&&this.width===anchorBox.width&&this.height===anchorBox.height;};Element.prototype.boxInWindow=function(targetWindow){targetWindow=targetWindow||this.ownerDocument.defaultView;const anchorBox=new AnchorBox();let curElement=this;let curWindow=this.ownerDocument.defaultView;while(curWindow&&curElement){anchorBox.x+=curElement.totalOffsetLeft();anchorBox.y+=curElement.totalOffsetTop();if(curWindow===targetWindow)
break;curElement=curWindow.frameElement;curWindow=curWindow.parent;}
anchorBox.width=Math.min(this.offsetWidth,targetWindow.innerWidth-anchorBox.x);anchorBox.height=Math.min(this.offsetHeight,targetWindow.innerHeight-anchorBox.y);return anchorBox;};Event.prototype.consume=function(preventDefault){this.stopImmediatePropagation();if(preventDefault)
this.preventDefault();this.handled=true;};Text.prototype.select=function(start,end){start=start||0;end=end||this.textContent.length;if(start<0)
start=end+start;const selection=this.getComponentSelection();selection.removeAllRanges();const range=this.ownerDocument.createRange();range.setStart(this,start);range.setEnd(this,end);selection.addRange(range);return this;};Element.prototype.selectionLeftOffset=function(){const selection=this.getComponentSelection();if(!selection.containsNode(this,true))
return null;let leftOffset=selection.anchorOffset;let node=selection.anchorNode;while(node!==this){while(node.previousSibling){node=node.previousSibling;leftOffset+=node.textContent.length;}
node=node.parentNodeOrShadowHost();}
return leftOffset;};Node.prototype.appendChildren=function(var_args){for(let i=0,n=arguments.length;i<n;++i)
this.appendChild(arguments[i]);};Node.prototype.deepTextContent=function(){return this.childTextNodes().map(function(node){return node.textContent;}).join('');};Node.prototype.childTextNodes=function(){let node=this.traverseNextTextNode(this);const result=[];const nonTextTags={'STYLE':1,'SCRIPT':1};while(node){if(!nonTextTags[node.parentElement.nodeName])
result.push(node);node=node.traverseNextTextNode(this);}
return result;};Node.prototype.isAncestor=function(node){if(!node)
return false;let currentNode=node.parentNodeOrShadowHost();while(currentNode){if(this===currentNode)
return true;currentNode=currentNode.parentNodeOrShadowHost();}
return false;};Node.prototype.isDescendant=function(descendant){return!!descendant&&descendant.isAncestor(this);};Node.prototype.isSelfOrAncestor=function(node){return!!node&&(node===this||this.isAncestor(node));};Node.prototype.isSelfOrDescendant=function(node){return!!node&&(node===this||this.isDescendant(node));};Node.prototype.traverseNextNode=function(stayWithin){if(this.shadowRoot)
return this.shadowRoot;const distributedNodes=this instanceof HTMLSlotElement?this.assignedNodes():[];if(distributedNodes.length)
return distributedNodes[0];if(this.firstChild)
return this.firstChild;let node=this;while(node){if(stayWithin&&node===stayWithin)
return null;const sibling=nextSibling(node);if(sibling)
return sibling;node=node.assignedSlot||node.parentNodeOrShadowHost();}
function nextSibling(node){if(!node.assignedSlot)
return node.nextSibling;const distributedNodes=node.assignedSlot.assignedNodes();const position=Array.prototype.indexOf.call(distributedNodes,node);if(position+1<distributedNodes.length)
return distributedNodes[position+1];return null;}
return null;};Node.prototype.traversePreviousNode=function(stayWithin){if(stayWithin&&this===stayWithin)
return null;let node=this.previousSibling;while(node&&node.lastChild)
node=node.lastChild;if(node)
return node;return this.parentNodeOrShadowHost();};Node.prototype.setTextContentTruncatedIfNeeded=function(text,placeholder){const maxTextContentLength=10000;if(typeof text==='string'&&text.length>maxTextContentLength){this.textContent=typeof placeholder==='string'?placeholder:text.trimMiddle(maxTextContentLength);return true;}
this.textContent=text;return false;};Event.prototype.deepElementFromPoint=function(){if(!this.which&&!this.pageX&&!this.pageY&&!this.clientX&&!this.clientY&&!this.movementX&&!this.movementY)
return null;const root=this.target&&this.target.getComponentRoot();return root?root.deepElementFromPoint(this.pageX,this.pageY):null;};Document.prototype.deepElementFromPoint=function(x,y){let container=this;let node=null;while(container){const innerNode=container.elementFromPoint(x,y);if(!innerNode||node===innerNode)
break;node=innerNode;container=node.shadowRoot;}
return node;};DocumentFragment.prototype.deepElementFromPoint=Document.prototype.deepElementFromPoint;Document.prototype.deepActiveElement=function(){let activeElement=this.activeElement;while(activeElement&&activeElement.shadowRoot&&activeElement.shadowRoot.activeElement)
activeElement=activeElement.shadowRoot.activeElement;return activeElement;};DocumentFragment.prototype.deepActiveElement=Document.prototype.deepActiveElement;Element.prototype.hasFocus=function(){const root=this.getComponentRoot();return!!root&&this.isSelfOrAncestor(root.activeElement);};Node.prototype.getComponentRoot=function(){let node=this;while(node&&node.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&node.nodeType!==Node.DOCUMENT_NODE)
node=node.parentNode;return(node);};function isEnterKey(event){return event.keyCode!==229&&event.key==='Enter';}
function isEscKey(event){return event.keyCode===27;}
(function(){const originalToggle=DOMTokenList.prototype.toggle;DOMTokenList.prototype['toggle']=function(token,force){if(arguments.length===1)
force=!this.contains(token);return originalToggle.call(this,token,!!force);};})();;self['TextUtils']=self['TextUtils']||{};TextUtils.Text=class{constructor(value){this._value=value;}
lineEndings(){if(!this._lineEndings)
this._lineEndings=this._value.computeLineEndings();return this._lineEndings;}
value(){return this._value;}
lineCount(){const lineEndings=this.lineEndings();return lineEndings.length;}
offsetFromPosition(lineNumber,columnNumber){return(lineNumber?this.lineEndings()[lineNumber-1]+1:0)+columnNumber;}
positionFromOffset(offset){const lineEndings=this.lineEndings();const lineNumber=lineEndings.lowerBound(offset);return{lineNumber:lineNumber,columnNumber:offset-(lineNumber&&(lineEndings[lineNumber-1]+1))};}
lineAt(lineNumber){const lineEndings=this.lineEndings();const lineStart=lineNumber>0?lineEndings[lineNumber-1]+1:0;const lineEnd=lineEndings[lineNumber];let lineContent=this._value.substring(lineStart,lineEnd);if(lineContent.length>0&&lineContent.charAt(lineContent.length-1)==='\r')
lineContent=lineContent.substring(0,lineContent.length-1);return lineContent;}
toSourceRange(range){const start=this.offsetFromPosition(range.startLine,range.startColumn);const end=this.offsetFromPosition(range.endLine,range.endColumn);return new TextUtils.SourceRange(start,end-start);}
toTextRange(sourceRange){const cursor=new TextUtils.TextCursor(this.lineEndings());const result=TextUtils.TextRange.createFromLocation(0,0);cursor.resetTo(sourceRange.offset);result.startLine=cursor.lineNumber();result.startColumn=cursor.columnNumber();cursor.advance(sourceRange.offset+sourceRange.length);result.endLine=cursor.lineNumber();result.endColumn=cursor.columnNumber();return result;}
replaceRange(range,replacement){const sourceRange=this.toSourceRange(range);return this._value.substring(0,sourceRange.offset)+replacement+
this._value.substring(sourceRange.offset+sourceRange.length);}
extract(range){const sourceRange=this.toSourceRange(range);return this._value.substr(sourceRange.offset,sourceRange.length);}};TextUtils.Text.Position;TextUtils.TextCursor=class{constructor(lineEndings){this._lineEndings=lineEndings;this._offset=0;this._lineNumber=0;this._columnNumber=0;}
advance(offset){this._offset=offset;while(this._lineNumber<this._lineEndings.length&&this._lineEndings[this._lineNumber]<this._offset)
++this._lineNumber;this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
offset(){return this._offset;}
resetTo(offset){this._offset=offset;this._lineNumber=this._lineEndings.lowerBound(offset);this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
lineNumber(){return this._lineNumber;}
columnNumber(){return this._columnNumber;}};;TextUtils.TextUtils={isStopChar:function(char){return(char>' '&&char<'0')||(char>'9'&&char<'A')||(char>'Z'&&char<'_')||(char>'_'&&char<'a')||(char>'z'&&char<='~');},isWordChar:function(char){return!TextUtils.TextUtils.isStopChar(char)&&!TextUtils.TextUtils.isSpaceChar(char);},isSpaceChar:function(char){return TextUtils.TextUtils._SpaceCharRegex.test(char);},isWord:function(word){for(let i=0;i<word.length;++i){if(!TextUtils.TextUtils.isWordChar(word.charAt(i)))
return false;}
return true;},isOpeningBraceChar:function(char){return char==='('||char==='{';},isClosingBraceChar:function(char){return char===')'||char==='}';},isBraceChar:function(char){return TextUtils.TextUtils.isOpeningBraceChar(char)||TextUtils.TextUtils.isClosingBraceChar(char);},textToWords:function(text,isWordChar,wordCallback){let startWord=-1;for(let i=0;i<text.length;++i){if(!isWordChar(text.charAt(i))){if(startWord!==-1)
wordCallback(text.substring(startWord,i));startWord=-1;}else if(startWord===-1){startWord=i;}}
if(startWord!==-1)
wordCallback(text.substring(startWord));},lineIndent:function(line){let indentation=0;while(indentation<line.length&&TextUtils.TextUtils.isSpaceChar(line.charAt(indentation)))
++indentation;return line.substr(0,indentation);},isUpperCase:function(text){return text===text.toUpperCase();},isLowerCase:function(text){return text===text.toLowerCase();},splitStringByRegexes(text,regexes){const matches=[];const globalRegexes=[];for(let i=0;i<regexes.length;i++){const regex=regexes[i];if(!regex.global)
globalRegexes.push(new RegExp(regex.source,regex.flags?regex.flags+'g':'g'));else
globalRegexes.push(regex);}
doSplit(text,0,0);return matches;function doSplit(text,regexIndex,startIndex){if(regexIndex>=globalRegexes.length){matches.push({value:text,position:startIndex,regexIndex:-1,captureGroups:[]});return;}
const regex=globalRegexes[regexIndex];let currentIndex=0;let result;regex.lastIndex=0;while((result=regex.exec(text))!==null){const stringBeforeMatch=text.substring(currentIndex,result.index);if(stringBeforeMatch)
doSplit(stringBeforeMatch,regexIndex+1,startIndex+currentIndex);const match=result[0];matches.push({value:match,position:startIndex+result.index,regexIndex:regexIndex,captureGroups:result.slice(1)});currentIndex=result.index+match.length;}
const stringAfterMatches=text.substring(currentIndex);if(stringAfterMatches)
doSplit(stringAfterMatches,regexIndex+1,startIndex+currentIndex);}}};TextUtils.FilterParser=class{constructor(keys){this._keys=keys;}
static cloneFilter(filter){return{key:filter.key,text:filter.text,regex:filter.regex,negative:filter.negative};}
parse(query){const splitResult=TextUtils.TextUtils.splitStringByRegexes(query,[TextUtils.TextUtils._keyValueFilterRegex,TextUtils.TextUtils._regexFilterRegex,TextUtils.TextUtils._textFilterRegex]);const filters=[];for(let i=0;i<splitResult.length;i++){const regexIndex=splitResult[i].regexIndex;if(regexIndex===-1)
continue;const result=splitResult[i].captureGroups;if(regexIndex===0){if(this._keys.indexOf((result[1]))!==-1)
filters.push({key:result[1],text:result[2],negative:!!result[0]});else
filters.push({text:result[1]+':'+result[2],negative:!!result[0]});}else if(regexIndex===1){try{filters.push({regex:new RegExp(result[1],'i'),negative:!!result[0]});}catch(e){filters.push({text:'/'+result[1]+'/',negative:!!result[0]});}}else if(regexIndex===2){filters.push({text:result[1],negative:!!result[0]});}}
return filters;}};TextUtils.FilterParser.ParsedFilter;TextUtils.TextUtils._keyValueFilterRegex=/(?:^|\s)(\-)?([\w\-]+):([^\s]+)/;TextUtils.TextUtils._regexFilterRegex=/(?:^|\s)(\-)?\/([^\s]+)\//;TextUtils.TextUtils._textFilterRegex=/(?:^|\s)(\-)?([^\s]+)/;TextUtils.TextUtils._SpaceCharRegex=/\s/;TextUtils.TextUtils.Indent={TwoSpaces:' ',FourSpaces:' ',EightSpaces:' ',TabCharacter:'\t'};TextUtils.TextUtils.BalancedJSONTokenizer=class{constructor(callback,findMultiple){this._callback=callback;this._index=0;this._balance=0;this._buffer='';this._findMultiple=findMultiple||false;this._closingDoubleQuoteRegex=/[^\\](?:\\\\)*"/g;}
write(chunk){this._buffer+=chunk;const lastIndex=this._buffer.length;const buffer=this._buffer;let index;for(index=this._index;index<lastIndex;++index){const character=buffer[index];if(character==='"'){this._closingDoubleQuoteRegex.lastIndex=index;if(!this._closingDoubleQuoteRegex.test(buffer))
break;index=this._closingDoubleQuoteRegex.lastIndex-1;}else if(character==='{'){++this._balance;}else if(character==='}'){--this._balance;if(this._balance<0){this._reportBalanced();return false;}
if(!this._balance){this._lastBalancedIndex=index+1;if(!this._findMultiple)
break;}}else if(character===']'&&!this._balance){this._reportBalanced();return false;}}
this._index=index;this._reportBalanced();return true;}
_reportBalanced(){if(!this._lastBalancedIndex)
return;this._callback(this._buffer.slice(0,this._lastBalancedIndex));this._buffer=this._buffer.slice(this._lastBalancedIndex);this._index-=this._lastBalancedIndex;this._lastBalancedIndex=0;}
remainder(){return this._buffer;}};TextUtils.TokenizerFactory=function(){};TextUtils.TokenizerFactory.prototype={createTokenizer(mimeType){}};TextUtils.isMinified=function(text){const kMaxNonMinifiedLength=500;let linesToCheck=10;let lastPosition=0;do{let eolIndex=text.indexOf('\n',lastPosition);if(eolIndex<0)
eolIndex=text.length;if(eolIndex-lastPosition>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#')
return true;lastPosition=eolIndex+1;}while(--linesToCheck>=0&&lastPosition<text.length);linesToCheck=10;lastPosition=text.length;do{let eolIndex=text.lastIndexOf('\n',lastPosition);if(eolIndex<0)
eolIndex=0;if(lastPosition-eolIndex>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#')
return true;lastPosition=eolIndex-1;}while(--linesToCheck>=0&&lastPosition>0);return false;};;TextUtils.TextRange=class{constructor(startLine,startColumn,endLine,endColumn){this.startLine=startLine;this.startColumn=startColumn;this.endLine=endLine;this.endColumn=endColumn;}
static createFromLocation(line,column){return new TextUtils.TextRange(line,column,line,column);}
static fromObject(serializedTextRange){return new TextUtils.TextRange(serializedTextRange.startLine,serializedTextRange.startColumn,serializedTextRange.endLine,serializedTextRange.endColumn);}
static comparator(range1,range2){return range1.compareTo(range2);}
static fromEdit(oldRange,newText){let endLine=oldRange.startLine;let endColumn=oldRange.startColumn+newText.length;const lineEndings=newText.computeLineEndings();if(lineEndings.length>1){endLine=oldRange.startLine+lineEndings.length-1;const len=lineEndings.length;endColumn=lineEndings[len-1]-lineEndings[len-2]-1;}
return new TextUtils.TextRange(oldRange.startLine,oldRange.startColumn,endLine,endColumn);}
isEmpty(){return this.startLine===this.endLine&&this.startColumn===this.endColumn;}
immediatelyPrecedes(range){if(!range)
return false;return this.endLine===range.startLine&&this.endColumn===range.startColumn;}
immediatelyFollows(range){if(!range)
return false;return range.immediatelyPrecedes(this);}
follows(range){return(range.endLine===this.startLine&&range.endColumn<=this.startColumn)||range.endLine<this.startLine;}
get linesCount(){return this.endLine-this.startLine;}
collapseToEnd(){return new TextUtils.TextRange(this.endLine,this.endColumn,this.endLine,this.endColumn);}
collapseToStart(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.startLine,this.startColumn);}
normalize(){if(this.startLine>this.endLine||(this.startLine===this.endLine&&this.startColumn>this.endColumn))
return new TextUtils.TextRange(this.endLine,this.endColumn,this.startLine,this.startColumn);else
return this.clone();}
clone(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.endLine,this.endColumn);}
serializeToObject(){const serializedTextRange={};serializedTextRange.startLine=this.startLine;serializedTextRange.startColumn=this.startColumn;serializedTextRange.endLine=this.endLine;serializedTextRange.endColumn=this.endColumn;return serializedTextRange;}
compareTo(other){if(this.startLine>other.startLine)
return 1;if(this.startLine<other.startLine)
return-1;if(this.startColumn>other.startColumn)
return 1;if(this.startColumn<other.startColumn)
return-1;return 0;}
compareToPosition(lineNumber,columnNumber){if(lineNumber<this.startLine||(lineNumber===this.startLine&&columnNumber<this.startColumn))
return-1;if(lineNumber>this.endLine||(lineNumber===this.endLine&&columnNumber>this.endColumn))
return 1;return 0;}
equal(other){return this.startLine===other.startLine&&this.endLine===other.endLine&&this.startColumn===other.startColumn&&this.endColumn===other.endColumn;}
relativeTo(line,column){const relative=this.clone();if(this.startLine===line)
relative.startColumn-=column;if(this.endLine===line)
relative.endColumn-=column;relative.startLine-=line;relative.endLine-=line;return relative;}
relativeFrom(line,column){const relative=this.clone();if(this.startLine===0)
relative.startColumn+=column;if(this.endLine===0)
relative.endColumn+=column;relative.startLine+=line;relative.endLine+=line;return relative;}
rebaseAfterTextEdit(originalRange,editedRange){console.assert(originalRange.startLine===editedRange.startLine);console.assert(originalRange.startColumn===editedRange.startColumn);const rebase=this.clone();if(!this.follows(originalRange))
return rebase;const lineDelta=editedRange.endLine-originalRange.endLine;const columnDelta=editedRange.endColumn-originalRange.endColumn;rebase.startLine+=lineDelta;rebase.endLine+=lineDelta;if(rebase.startLine===editedRange.endLine)
rebase.startColumn+=columnDelta;if(rebase.endLine===editedRange.endLine)
rebase.endColumn+=columnDelta;return rebase;}
toString(){return JSON.stringify(this);}
containsLocation(lineNumber,columnNumber){if(this.startLine===this.endLine)
return this.startLine===lineNumber&&this.startColumn<=columnNumber&&columnNumber<=this.endColumn;if(this.startLine===lineNumber)
return this.startColumn<=columnNumber;if(this.endLine===lineNumber)
return columnNumber<=this.endColumn;return this.startLine<lineNumber&&lineNumber<this.endLine;}};TextUtils.SourceRange=class{constructor(offset,length){this.offset=offset;this.length=length;}};TextUtils.SourceEdit=class{constructor(sourceURL,oldRange,newText){this.sourceURL=sourceURL;this.oldRange=oldRange;this.newText=newText;}
static comparator(edit1,edit2){return TextUtils.TextRange.comparator(edit1.oldRange,edit2.oldRange);}
newRange(){return TextUtils.TextRange.fromEdit(this.oldRange,this.newText);}};;self['Common']=self['Common']||{};Common.Worker=class{constructor(appName){let url=appName+'.js';url+=Runtime.queryParamsString();this._workerPromise=new Promise(fulfill=>{this._worker=new Worker(url);this._worker.onmessage=onMessage.bind(this);function onMessage(event){console.assert(event.data==='workerReady');this._worker.onmessage=null;fulfill(this._worker);this._worker=null;}});}
postMessage(message){this._workerPromise.then(worker=>{if(!this._disposed)
worker.postMessage(message);});}
dispose(){this._disposed=true;this._workerPromise.then(worker=>worker.terminate());}
terminate(){this.dispose();}
set onmessage(listener){this._workerPromise.then(worker=>worker.onmessage=listener);}
set onerror(listener){this._workerPromise.then(worker=>worker.onerror=listener);}};;Common.TextDictionary=class{constructor(){this._words=new Map();this._index=new Common.Trie();}
addWord(word){let count=this._words.get(word)||0;++count;this._words.set(word,count);this._index.add(word);}
removeWord(word){let count=this._words.get(word)||0;if(!count)
return;if(count===1){this._words.delete(word);this._index.remove(word);return;}
--count;this._words.set(word,count);}
wordsWithPrefix(prefix){return this._index.words(prefix);}
hasWord(word){return this._words.has(word);}
wordCount(word){return this._words.get(word)||0;}
reset(){this._words.clear();this._index.clear();}};;Common.Object=class{constructor(){this._listeners;}
addEventListener(eventType,listener,thisObject){if(!listener)
console.assert(false);if(!this._listeners)
this._listeners=new Map();if(!this._listeners.has(eventType))
this._listeners.set(eventType,[]);this._listeners.get(eventType).push({thisObject:thisObject,listener:listener});return{eventTarget:this,eventType:eventType,thisObject:thisObject,listener:listener};}
once(eventType){return new Promise(resolve=>{const descriptor=this.addEventListener(eventType,event=>{this.removeEventListener(eventType,descriptor.listener);resolve(event.data);});});}
removeEventListener(eventType,listener,thisObject){console.assert(listener);if(!this._listeners||!this._listeners.has(eventType))
return;const listeners=this._listeners.get(eventType);for(let i=0;i<listeners.length;++i){if(listeners[i].listener===listener&&listeners[i].thisObject===thisObject){listeners[i].disposed=true;listeners.splice(i--,1);}}
if(!listeners.length)
this._listeners.delete(eventType);}
hasEventListeners(eventType){return!!(this._listeners&&this._listeners.has(eventType));}
dispatchEventToListeners(eventType,eventData){if(!this._listeners||!this._listeners.has(eventType))
return;const event=({data:eventData});const listeners=this._listeners.get(eventType).slice(0);for(let i=0;i<listeners.length;++i){if(!listeners[i].disposed)
listeners[i].listener.call(listeners[i].thisObject,event);}}};Common.Event;Common.Object._listenerCallbackTuple;Common.EventTarget=function(){};Common.EventTarget.EventDescriptor;Common.EventTarget.removeEventListeners=function(eventList){for(const eventInfo of eventList)
eventInfo.eventTarget.removeEventListener(eventInfo.eventType,eventInfo.listener,eventInfo.thisObject);eventList.splice(0);};Common.EventTarget.prototype={addEventListener(eventType,listener,thisObject){},once(eventType){},removeEventListener(eventType,listener,thisObject){},hasEventListeners(eventType){},dispatchEventToListeners(eventType,eventData){},};;Common.Color=class{constructor(rgba,format,originalText){this._rgba=rgba;this._originalText=originalText||null;this._originalTextIsValid=!!this._originalText;this._format=format;if(typeof this._rgba[3]==='undefined')
this._rgba[3]=1;for(let i=0;i<4;++i){if(this._rgba[i]<0){this._rgba[i]=0;this._originalTextIsValid=false;}
if(this._rgba[i]>1){this._rgba[i]=1;this._originalTextIsValid=false;}}}
static parse(text){const value=text.toLowerCase().replace(/\s+/g,'');const simple=/^(?:#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(\w+))$/i;let match=value.match(simple);if(match){if(match[1]){let hex=match[1].toLowerCase();let format;if(hex.length===3){format=Common.Color.Format.ShortHEX;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2);}else if(hex.length===4){format=Common.Color.Format.ShortHEXA;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2)+
hex.charAt(3)+hex.charAt(3);}else if(hex.length===6){format=Common.Color.Format.HEX;}else{format=Common.Color.Format.HEXA;}
const r=parseInt(hex.substring(0,2),16);const g=parseInt(hex.substring(2,4),16);const b=parseInt(hex.substring(4,6),16);let a=1;if(hex.length===8)
a=parseInt(hex.substring(6,8),16)/255;return new Common.Color([r/255,g/255,b/255,a],format,text);}
if(match[2]){const nickname=match[2].toLowerCase();if(nickname in Common.Color.Nicknames){const rgba=Common.Color.Nicknames[nickname];const color=Common.Color.fromRGBA(rgba);color._format=Common.Color.Format.Nickname;color._originalText=text;return color;}
return null;}
return null;}
match=text.toLowerCase().match(/^\s*(?:(rgba?)|(hsla?))\((.*)\)\s*$/);if(match){const components=match[3].trim();let values=components.split(/\s*,\s*/);if(values.length===1){values=components.split(/\s+/);if(values[3]==='/'){values.splice(3,1);if(values.length!==4)
return null;}else if((values.length>2&&values[2].indexOf('/')!==-1)||(values.length>3&&values[3].indexOf('/')!==-1)){const alpha=values.slice(2,4).join('');values=values.slice(0,2).concat(alpha.split(/\//)).concat(values.slice(4));}else if(values.length>=4){return null;}}
if(values.length!==3&&values.length!==4||values.indexOf('')>-1)
return null;const hasAlpha=(values[3]!==undefined);if(match[1]){const rgba=[Common.Color._parseRgbNumeric(values[0]),Common.Color._parseRgbNumeric(values[1]),Common.Color._parseRgbNumeric(values[2]),hasAlpha?Common.Color._parseAlphaNumeric(values[3]):1];if(rgba.indexOf(null)>-1)
return null;return new Common.Color(rgba,hasAlpha?Common.Color.Format.RGBA:Common.Color.Format.RGB,text);}
if(match[2]){const hsla=[Common.Color._parseHueNumeric(values[0]),Common.Color._parseSatLightNumeric(values[1]),Common.Color._parseSatLightNumeric(values[2]),hasAlpha?Common.Color._parseAlphaNumeric(values[3]):1];if(hsla.indexOf(null)>-1)
return null;const rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,hasAlpha?Common.Color.Format.HSLA:Common.Color.Format.HSL,text);}}
return null;}
static fromRGBA(rgba){return new Common.Color([rgba[0]/255,rgba[1]/255,rgba[2]/255,rgba[3]],Common.Color.Format.RGBA);}
static fromHSVA(hsva){const rgba=[];Common.Color.hsva2rgba(hsva,rgba);return new Common.Color(rgba,Common.Color.Format.HSLA);}
static _parsePercentOrNumber(value){if(isNaN(value.replace('%','')))
return null;const parsed=parseFloat(value);if(value.indexOf('%')!==-1){if(value.indexOf('%')!==value.length-1)
return null;return parsed/100;}
return parsed;}
static _parseRgbNumeric(value){const parsed=Common.Color._parsePercentOrNumber(value);if(parsed===null)
return null;if(value.indexOf('%')!==-1)
return parsed;return parsed/255;}
static _parseHueNumeric(value){const angle=value.replace(/(deg|g?rad|turn)$/,'');if(isNaN(angle)||value.match(/\s+(deg|g?rad|turn)/))
return null;const number=parseFloat(angle);if(value.indexOf('turn')!==-1)
return number%1;else if(value.indexOf('grad')!==-1)
return(number/400)%1;else if(value.indexOf('rad')!==-1)
return(number/(2*Math.PI))%1;return(number/360)%1;}
static _parseSatLightNumeric(value){if(value.indexOf('%')!==value.length-1||isNaN(value.replace('%','')))
return null;const parsed=parseFloat(value);return Math.min(1,parsed/100);}
static _parseAlphaNumeric(value){return Common.Color._parsePercentOrNumber(value);}
static _hsva2hsla(hsva,out_hsla){const h=hsva[0];let s=hsva[1];const v=hsva[2];const t=(2-s)*v;if(v===0||s===0)
s=0;else
s*=v/(t<1?t:2-t);out_hsla[0]=h;out_hsla[1]=s;out_hsla[2]=t/2;out_hsla[3]=hsva[3];}
static hsl2rgb(hsl,out_rgb){const h=hsl[0];let s=hsl[1];const l=hsl[2];function hue2rgb(p,q,h){if(h<0)
h+=1;else if(h>1)
h-=1;if((h*6)<1)
return p+(q-p)*h*6;else if((h*2)<1)
return q;else if((h*3)<2)
return p+(q-p)*((2/3)-h)*6;else
return p;}
if(s<0)
s=0;let q;if(l<=0.5)
q=l*(1+s);else
q=l+s-(l*s);const p=2*l-q;const tr=h+(1/3);const tg=h;const tb=h-(1/3);out_rgb[0]=hue2rgb(p,q,tr);out_rgb[1]=hue2rgb(p,q,tg);out_rgb[2]=hue2rgb(p,q,tb);out_rgb[3]=hsl[3];}
static hsva2rgba(hsva,out_rgba){Common.Color._hsva2hsla(hsva,Common.Color.hsva2rgba._tmpHSLA);Common.Color.hsl2rgb(Common.Color.hsva2rgba._tmpHSLA,out_rgba);for(let i=0;i<Common.Color.hsva2rgba._tmpHSLA.length;i++)
Common.Color.hsva2rgba._tmpHSLA[i]=0;}
static luminance(rgba){const rSRGB=rgba[0];const gSRGB=rgba[1];const bSRGB=rgba[2];const r=rSRGB<=0.03928?rSRGB/12.92:Math.pow(((rSRGB+0.055)/1.055),2.4);const g=gSRGB<=0.03928?gSRGB/12.92:Math.pow(((gSRGB+0.055)/1.055),2.4);const b=bSRGB<=0.03928?bSRGB/12.92:Math.pow(((bSRGB+0.055)/1.055),2.4);return 0.2126*r+0.7152*g+0.0722*b;}
static blendColors(fgRGBA,bgRGBA,out_blended){const alpha=fgRGBA[3];out_blended[0]=((1-alpha)*bgRGBA[0])+(alpha*fgRGBA[0]);out_blended[1]=((1-alpha)*bgRGBA[1])+(alpha*fgRGBA[1]);out_blended[2]=((1-alpha)*bgRGBA[2])+(alpha*fgRGBA[2]);out_blended[3]=alpha+(bgRGBA[3]*(1-alpha));}
static calculateContrastRatio(fgRGBA,bgRGBA){Common.Color.blendColors(fgRGBA,bgRGBA,Common.Color.calculateContrastRatio._blendedFg);const fgLuminance=Common.Color.luminance(Common.Color.calculateContrastRatio._blendedFg);const bgLuminance=Common.Color.luminance(bgRGBA);const contrastRatio=(Math.max(fgLuminance,bgLuminance)+0.05)/(Math.min(fgLuminance,bgLuminance)+0.05);for(let i=0;i<Common.Color.calculateContrastRatio._blendedFg.length;i++)
Common.Color.calculateContrastRatio._blendedFg[i]=0;return contrastRatio;}
static desiredLuminance(luminance,contrast,lighter){function computeLuminance(){if(lighter)
return(luminance+0.05)*contrast-0.05;else
return(luminance+0.05)/contrast-0.05;}
let desiredLuminance=computeLuminance();if(desiredLuminance<0||desiredLuminance>1){lighter=!lighter;desiredLuminance=computeLuminance();}
return desiredLuminance;}
static detectColorFormat(color){const cf=Common.Color.Format;let format;const formatSetting=Common.moduleSetting('colorFormat').get();if(formatSetting===cf.Original)
format=cf.Original;else if(formatSetting===cf.RGB)
format=(color.hasAlpha()?cf.RGBA:cf.RGB);else if(formatSetting===cf.HSL)
format=(color.hasAlpha()?cf.HSLA:cf.HSL);else if(formatSetting===cf.HEX)
format=color.detectHEXFormat();else
format=cf.RGBA;return format;}
format(){return this._format;}
hsla(){if(this._hsla)
return this._hsla;const r=this._rgba[0];const g=this._rgba[1];const b=this._rgba[2];const max=Math.max(r,g,b);const min=Math.min(r,g,b);const diff=max-min;const add=max+min;let h;if(min===max)
h=0;else if(r===max)
h=((1/6*(g-b)/diff)+1)%1;else if(g===max)
h=(1/6*(b-r)/diff)+1/3;else
h=(1/6*(r-g)/diff)+2/3;const l=0.5*add;let s;if(l===0)
s=0;else if(l===1)
s=0;else if(l<=0.5)
s=diff/add;else
s=diff/(2-add);this._hsla=[h,s,l,this._rgba[3]];return this._hsla;}
canonicalHSLA(){const hsla=this.hsla();return[Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]];}
hsva(){const hsla=this.hsla();const h=hsla[0];let s=hsla[1];const l=hsla[2];s*=l<0.5?l:1-l;return[h,s!==0?2*s/(l+s):0,(l+s),hsla[3]];}
hasAlpha(){return this._rgba[3]!==1;}
detectHEXFormat(){let canBeShort=true;for(let i=0;i<4;++i){const c=Math.round(this._rgba[i]*255);if(c%17){canBeShort=false;break;}}
const hasAlpha=this.hasAlpha();const cf=Common.Color.Format;if(canBeShort)
return hasAlpha?cf.ShortHEXA:cf.ShortHEX;return hasAlpha?cf.HEXA:cf.HEX;}
asString(format){if(format===this._format&&this._originalTextIsValid)
return this._originalText;if(!format)
format=this._format;function toRgbValue(value){return Math.round(value*255);}
function toHexValue(value){const hex=Math.round(value*255).toString(16);return hex.length===1?'0'+hex:hex;}
function toShortHexValue(value){return(Math.round(value*255)/17).toString(16);}
switch(format){case Common.Color.Format.Original:return this._originalText;case Common.Color.Format.RGB:if(this.hasAlpha())
return null;return String.sprintf('rgb(%d, %d, %d)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]));case Common.Color.Format.RGBA:return String.sprintf('rgba(%d, %d, %d, %f)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]),this._rgba[3]);case Common.Color.Format.HSL:if(this.hasAlpha())
return null;const hsl=this.hsla();return String.sprintf('hsl(%d, %d%, %d%)',Math.round(hsl[0]*360),Math.round(hsl[1]*100),Math.round(hsl[2]*100));case Common.Color.Format.HSLA:const hsla=this.hsla();return String.sprintf('hsla(%d, %d%, %d%, %f)',Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]);case Common.Color.Format.HEXA:return String.sprintf('#%s%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2]),toHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.HEX:if(this.hasAlpha())
return null;return String.sprintf('#%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.ShortHEXA:const hexFormat=this.detectHEXFormat();if(hexFormat!==Common.Color.Format.ShortHEXA&&hexFormat!==Common.Color.Format.ShortHEX)
return null;return String.sprintf('#%s%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2]),toShortHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.ShortHEX:if(this.hasAlpha())
return null;if(this.detectHEXFormat()!==Common.Color.Format.ShortHEX)
return null;return String.sprintf('#%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.Nickname:return this.nickname();}
return this._originalText;}
rgba(){return this._rgba.slice();}
canonicalRGBA(){const rgba=new Array(4);for(let i=0;i<3;++i)
rgba[i]=Math.round(this._rgba[i]*255);rgba[3]=this._rgba[3];return rgba;}
nickname(){if(!Common.Color._rgbaToNickname){Common.Color._rgbaToNickname={};for(const nickname in Common.Color.Nicknames){let rgba=Common.Color.Nicknames[nickname];if(rgba.length!==4)
rgba=rgba.concat(1);Common.Color._rgbaToNickname[rgba]=nickname;}}
return Common.Color._rgbaToNickname[this.canonicalRGBA()]||null;}
toProtocolRGBA(){const rgba=this.canonicalRGBA();const result={r:rgba[0],g:rgba[1],b:rgba[2]};if(rgba[3]!==1)
result.a=rgba[3];return result;}
invert(){const rgba=[];rgba[0]=1-this._rgba[0];rgba[1]=1-this._rgba[1];rgba[2]=1-this._rgba[2];rgba[3]=this._rgba[3];return new Common.Color(rgba,Common.Color.Format.RGBA);}
setAlpha(alpha){const rgba=this._rgba.slice();rgba[3]=alpha;return new Common.Color(rgba,Common.Color.Format.RGBA);}
blendWith(fgColor){const rgba=[];Common.Color.blendColors(fgColor._rgba,this._rgba,rgba);return new Common.Color(rgba,Common.Color.Format.RGBA);}};Common.Color.Regex=/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g;Common.Color.Format={Original:'original',Nickname:'nickname',HEX:'hex',ShortHEX:'shorthex',HEXA:'hexa',ShortHEXA:'shorthexa',RGB:'rgb',RGBA:'rgba',HSL:'hsl',HSLA:'hsla'};Common.Color.hsva2rgba._tmpHSLA=[0,0,0,0];Common.Color.calculateContrastRatio._blendedFg=[0,0,0,0];Common.Color.Nicknames={'aliceblue':[240,248,255],'antiquewhite':[250,235,215],'aqua':[0,255,255],'aquamarine':[127,255,212],'azure':[240,255,255],'beige':[245,245,220],'bisque':[255,228,196],'black':[0,0,0],'blanchedalmond':[255,235,205],'blue':[0,0,255],'blueviolet':[138,43,226],'brown':[165,42,42],'burlywood':[222,184,135],'cadetblue':[95,158,160],'chartreuse':[127,255,0],'chocolate':[210,105,30],'coral':[255,127,80],'cornflowerblue':[100,149,237],'cornsilk':[255,248,220],'crimson':[237,20,61],'cyan':[0,255,255],'darkblue':[0,0,139],'darkcyan':[0,139,139],'darkgoldenrod':[184,134,11],'darkgray':[169,169,169],'darkgrey':[169,169,169],'darkgreen':[0,100,0],'darkkhaki':[189,183,107],'darkmagenta':[139,0,139],'darkolivegreen':[85,107,47],'darkorange':[255,140,0],'darkorchid':[153,50,204],'darkred':[139,0,0],'darksalmon':[233,150,122],'darkseagreen':[143,188,143],'darkslateblue':[72,61,139],'darkslategray':[47,79,79],'darkslategrey':[47,79,79],'darkturquoise':[0,206,209],'darkviolet':[148,0,211],'deeppink':[255,20,147],'deepskyblue':[0,191,255],'dimgray':[105,105,105],'dimgrey':[105,105,105],'dodgerblue':[30,144,255],'firebrick':[178,34,34],'floralwhite':[255,250,240],'forestgreen':[34,139,34],'fuchsia':[255,0,255],'gainsboro':[220,220,220],'ghostwhite':[248,248,255],'gold':[255,215,0],'goldenrod':[218,165,32],'gray':[128,128,128],'grey':[128,128,128],'green':[0,128,0],'greenyellow':[173,255,47],'honeydew':[240,255,240],'hotpink':[255,105,180],'indianred':[205,92,92],'indigo':[75,0,130],'ivory':[255,255,240],'khaki':[240,230,140],'lavender':[230,230,250],'lavenderblush':[255,240,245],'lawngreen':[124,252,0],'lemonchiffon':[255,250,205],'lightblue':[173,216,230],'lightcoral':[240,128,128],'lightcyan':[224,255,255],'lightgoldenrodyellow':[250,250,210],'lightgreen':[144,238,144],'lightgray':[211,211,211],'lightgrey':[211,211,211],'lightpink':[255,182,193],'lightsalmon':[255,160,122],'lightseagreen':[32,178,170],'lightskyblue':[135,206,250],'lightslategray':[119,136,153],'lightslategrey':[119,136,153],'lightsteelblue':[176,196,222],'lightyellow':[255,255,224],'lime':[0,255,0],'limegreen':[50,205,50],'linen':[250,240,230],'magenta':[255,0,255],'maroon':[128,0,0],'mediumaquamarine':[102,205,170],'mediumblue':[0,0,205],'mediumorchid':[186,85,211],'mediumpurple':[147,112,219],'mediumseagreen':[60,179,113],'mediumslateblue':[123,104,238],'mediumspringgreen':[0,250,154],'mediumturquoise':[72,209,204],'mediumvioletred':[199,21,133],'midnightblue':[25,25,112],'mintcream':[245,255,250],'mistyrose':[255,228,225],'moccasin':[255,228,181],'navajowhite':[255,222,173],'navy':[0,0,128],'oldlace':[253,245,230],'olive':[128,128,0],'olivedrab':[107,142,35],'orange':[255,165,0],'orangered':[255,69,0],'orchid':[218,112,214],'palegoldenrod':[238,232,170],'palegreen':[152,251,152],'paleturquoise':[175,238,238],'palevioletred':[219,112,147],'papayawhip':[255,239,213],'peachpuff':[255,218,185],'peru':[205,133,63],'pink':[255,192,203],'plum':[221,160,221],'powderblue':[176,224,230],'purple':[128,0,128],'rebeccapurple':[102,51,153],'red':[255,0,0],'rosybrown':[188,143,143],'royalblue':[65,105,225],'saddlebrown':[139,69,19],'salmon':[250,128,114],'sandybrown':[244,164,96],'seagreen':[46,139,87],'seashell':[255,245,238],'sienna':[160,82,45],'silver':[192,192,192],'skyblue':[135,206,235],'slateblue':[106,90,205],'slategray':[112,128,144],'slategrey':[112,128,144],'snow':[255,250,250],'springgreen':[0,255,127],'steelblue':[70,130,180],'tan':[210,180,140],'teal':[0,128,128],'thistle':[216,191,216],'tomato':[255,99,71],'turquoise':[64,
setColorForID(id,color){this._colors.set(id,color);}
colorForID(id){let color=this._colors.get(id);if(!color){color=this._generateColorForID(id);this._colors.set(id,color);}
return color;}
_generateColorForID(id){const hash=String.hashCode(id);const h=this._indexToValueInSpace(hash,this._hueSpace);const s=this._indexToValueInSpace(hash>>8,this._satSpace);const l=this._indexToValueInSpace(hash>>16,this._lightnessSpace);const a=this._indexToValueInSpace(hash>>24,this._alphaSpace);return`hsla(${h}, ${s}%, ${l}%, ${a})`;}
_indexToValueInSpace(index,space){if(typeof space==='number')
return space;const count=space.count||space.max-space.min;index%=count;return space.min+Math.floor(index/(count-1)*(space.max-space.min));}};;Common.Console=class extends Common.Object{constructor(){super();this._messages=[];}
addMessage(text,level,show){const message=new Common.Console.Message(text,level||Common.Console.MessageLevel.Info,Date.now(),show||false);this._messages.push(message);this.dispatchEventToListeners(Common.Console.Events.MessageAdded,message);}
log(text){this.addMessage(text,Common.Console.MessageLevel.Info);}
warn(text){this.addMessage(text,Common.Console.MessageLevel.Warning);}
error(text){this.addMessage(text,Common.Console.MessageLevel.Error,true);}
messages(){return this._messages;}
show(){this.showPromise();}
showPromise(){return Common.Revealer.reveal(this);}};Common.Console.Events={MessageAdded:Symbol('messageAdded')};Common.Console.MessageLevel={Info:'info',Warning:'warning',Error:'error'};Common.Console.Message=class{constructor(text,level,timestamp,show){this.text=text;this.level=level;this.timestamp=(typeof timestamp==='number')?timestamp:Date.now();this.show=show;}};Common.console=new Common.Console();;Common.ContentProvider=function(){};Common.ContentProvider.prototype={contentURL(){},contentType(){},contentEncoded(){},requestContent(){},searchInContent(query,caseSensitive,isRegex){}};Common.ContentProvider.SearchMatch=class{constructor(lineNumber,lineContent){this.lineNumber=lineNumber;this.lineContent=lineContent;}};Common.ContentProvider.performSearchInContent=function(content,query,caseSensitive,isRegex){const regex=createSearchRegex(query,caseSensitive,isRegex);const text=new TextUtils.Text(content);const result=[];for(let i=0;i<text.lineCount();++i){const lineContent=text.lineAt(i);regex.lastIndex=0;if(regex.exec(lineContent))
result.push(new Common.ContentProvider.SearchMatch(i,lineContent));}
return result;};Common.ContentProvider.contentAsDataURL=function(content,mimeType,contentEncoded,charset){const maxDataUrlSize=1024*1024;if(content===null||content.length>maxDataUrlSize)
return null;return'data:'+mimeType+(charset?';charset='+charset:'')+(contentEncoded?';base64':'')+','+
content;};;Common.ParsedURL=class{constructor(url){this.isValid=false;this.url=url;this.scheme='';this.user='';this.host='';this.port='';this.path='';this.queryParams='';this.fragment='';this.folderPathComponents='';this.lastPathComponent='';const isBlobUrl=this.url.startsWith('blob:');const urlToMatch=isBlobUrl?url.substring(5):url;const match=urlToMatch.match(Common.ParsedURL._urlRegex());if(match){this.isValid=true;if(isBlobUrl){this._blobInnerScheme=match[2].toLowerCase();this.scheme='blob';}else{this.scheme=match[2].toLowerCase();}
this.user=match[3];this.host=match[4];this.port=match[5];this.path=match[6]||'/';this.queryParams=match[7]||'';this.fragment=match[8];}else{if(this.url.startsWith('data:')){this.scheme='data';return;}
if(this.url.startsWith('blob:')){this.scheme='blob';return;}
if(this.url==='about:blank'){this.scheme='about';return;}
this.path=this.url;}
const lastSlashIndex=this.path.lastIndexOf('/');if(lastSlashIndex!==-1){this.folderPathComponents=this.path.substring(0,lastSlashIndex);this.lastPathComponent=this.path.substring(lastSlashIndex+1);}else{this.lastPathComponent=this.path;}}
static platformPathToURL(fileSystemPath){fileSystemPath=fileSystemPath.replace(/\\/g,'/');if(!fileSystemPath.startsWith('file://')){if(fileSystemPath.startsWith('/'))
fileSystemPath='file://'+fileSystemPath;else
fileSystemPath='file:///'+fileSystemPath;}
return fileSystemPath;}
static urlToPlatformPath(fileURL,isWindows){console.assert(fileURL.startsWith('file://'),'This must be a file URL.');if(isWindows)
return fileURL.substr('file:///'.length).replace(/\//g,'\\');return fileURL.substr('file://'.length);}
static urlWithoutHash(url){const hashIndex=url.indexOf('#');if(hashIndex!==-1)
return url.substr(0,hashIndex);return url;}
static _urlRegex(){if(Common.ParsedURL._urlRegexInstance)
return Common.ParsedURL._urlRegexInstance;const schemeRegex=/([A-Za-z][A-Za-z0-9+.-]*):\/\//;const userRegex=/(?:([A-Za-z0-9\-._~%!$&'()*+,;=:]*)@)?/;const hostRegex=/((?:\[::\d?\])|(?:[^\s\/:]*))/;const portRegex=/(?::([\d]+))?/;const pathRegex=/(\/[^#?]*)?/;const queryRegex=/(?:\?([^#]*))?/;const fragmentRegex=/(?:#(.*))?/;Common.ParsedURL._urlRegexInstance=new RegExp('^('+schemeRegex.source+userRegex.source+hostRegex.source+portRegex.source+')'+pathRegex.source+
queryRegex.source+fragmentRegex.source+'$');return Common.ParsedURL._urlRegexInstance;}
static extractPath(url){const parsedURL=url.asParsedURL();return parsedURL?parsedURL.path:'';}
static extractOrigin(url){const parsedURL=url.asParsedURL();return parsedURL?parsedURL.securityOrigin():'';}
static extractExtension(url){url=Common.ParsedURL.urlWithoutHash(url);const indexOfQuestionMark=url.indexOf('?');if(indexOfQuestionMark!==-1)
url=url.substr(0,indexOfQuestionMark);const lastIndexOfSlash=url.lastIndexOf('/');if(lastIndexOfSlash!==-1)
url=url.substr(lastIndexOfSlash+1);const lastIndexOfDot=url.lastIndexOf('.');if(lastIndexOfDot!==-1){url=url.substr(lastIndexOfDot+1);const lastIndexOfPercent=url.indexOf('%');if(lastIndexOfPercent!==-1)
return url.substr(0,lastIndexOfPercent);return url;}
return'';}
static extractName(url){let index=url.lastIndexOf('/');const pathAndQuery=index!==-1?url.substr(index+1):url;index=pathAndQuery.indexOf('?');return index<0?pathAndQuery:pathAndQuery.substr(0,index);}
static completeURL(baseURL,href){const trimmedHref=href.trim();if(trimmedHref.startsWith('data:')||trimmedHref.startsWith('blob:')||trimmedHref.startsWith('javascript:'))
return href;const parsedHref=trimmedHref.asParsedURL();if(parsedHref&&parsedHref.scheme)
return trimmedHref;const parsedURL=baseURL.asParsedURL();if(!parsedURL)
return null;if(parsedURL.isDataURL())
return href;if(href.length>1&&href.charAt(0)==='/'&&href.charAt(1)==='/'){return parsedURL.scheme+':'+href;}
const securityOrigin=parsedURL.securityOrigin();const pathText=parsedURL.path;const queryText=parsedURL.queryParams?'?'+parsedURL.queryParams:'';if(!href.length)
return securityOrigin+pathText+queryText;if(href.charAt(0)==='#')
return securityOrigin+pathText+queryText+href;if(href.charAt(0)==='?')
return securityOrigin+pathText+href;let hrefPath=href.match(/^[^#?]*/)[0];const hrefSuffix=href.substring(hrefPath.length);if(hrefPath.charAt(0)!=='/')
hrefPath=parsedURL.folderPathComponents+'/'+hrefPath;return securityOrigin+Runtime.normalizePath(hrefPath)+hrefSuffix;}
static splitLineAndColumn(string){const beforePathMatch=string.match(Common.ParsedURL._urlRegex());let beforePath='';let pathAndAfter=string;if(beforePathMatch){beforePath=beforePathMatch[1];pathAndAfter=string.substring(beforePathMatch[1].length);}
const lineColumnRegEx=/(?::(\d+))?(?::(\d+))?$/;const lineColumnMatch=lineColumnRegEx.exec(pathAndAfter);let lineNumber;let columnNumber;console.assert(lineColumnMatch);if(typeof(lineColumnMatch[1])==='string'){lineNumber=parseInt(lineColumnMatch[1],10);lineNumber=isNaN(lineNumber)?undefined:lineNumber-1;}
if(typeof(lineColumnMatch[2])==='string'){columnNumber=parseInt(lineColumnMatch[2],10);columnNumber=isNaN(columnNumber)?undefined:columnNumber-1;}
return{url:beforePath+pathAndAfter.substring(0,pathAndAfter.length-lineColumnMatch[0].length),lineNumber:lineNumber,columnNumber:columnNumber};}
static isRelativeURL(url){return!(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url));}
get displayName(){if(this._displayName)
return this._displayName;if(this.isDataURL())
return this.dataURLDisplayName();if(this.isBlobURL())
return this.url;if(this.isAboutBlank())
return this.url;this._displayName=this.lastPathComponent;if(!this._displayName)
this._displayName=(this.host||'')+'/';if(this._displayName==='/')
this._displayName=this.url;return this._displayName;}
dataURLDisplayName(){if(this._dataURLDisplayName)
return this._dataURLDisplayName;if(!this.isDataURL())
return'';this._dataURLDisplayName=this.url.trimEnd(20);return this._dataURLDisplayName;}
isAboutBlank(){return this.url==='about:blank';}
isDataURL(){return this.scheme==='data';}
isBlobURL(){return this.url.startsWith('blob:');}
lastPathComponentWithFragment(){return this.lastPathComponent+(this.fragment?'#'+this.fragment:'');}
domain(){if(this.isDataURL())
return'data:';return this.host+(this.port?':'+this.port:'');}
securityOrigin(){if(this.isDataURL())
return'data:';const scheme=this.isBlobURL()?this._blobInnerScheme:this.scheme;return scheme+'://'+this.domain();}
urlWithoutScheme(){if(this.scheme&&this.url.startsWith(this.scheme+'://'))
return this.url.substring(this.scheme.length+3);return this.url;}};String.prototype.asParsedURL=function(){const parsedURL=new Common.ParsedURL(this.toString());if(parsedURL.isValid)
return parsedURL;return null;};;Common.Progress=function(){};Common.Progress.prototype={setTotalWork(totalWork){},setTitle(title){},setWorked(worked,title){},worked(worked){},done(){},isCanceled(){return false;},};Common.CompositeProgress=class{constructor(parent){this._parent=parent;this._children=[];this._childrenDone=0;this._parent.setTotalWork(1);this._parent.setWorked(0);}
_childDone(){if(++this._childrenDone!==this._children.length)
return;this._parent.done();}
createSubProgress(weight){const child=new Common.SubProgress(this,weight);this._children.push(child);return child;}
_update(){let totalWeights=0;let done=0;for(let i=0;i<this._children.length;++i){const child=this._children[i];if(child._totalWork)
done+=child._weight*child._worked/child._totalWork;totalWeights+=child._weight;}
this._parent.setWorked(done/totalWeights);}};Common.SubProgress=class{constructor(composite,weight){this._composite=composite;this._weight=weight||1;this._worked=0;}
isCanceled(){return this._composite._parent.isCanceled();}
setTitle(title){this._composite._parent.setTitle(title);}
done(){this.setWorked(this._totalWork);this._composite._childDone();}
setTotalWork(totalWork){this._totalWork=totalWork;this._composite._update();}
setWorked(worked,title){this._worked=worked;if(typeof title!=='undefined')
this.setTitle(title);this._composite._update();}
worked(worked){this.setWorked(this._worked+(worked||1));}};Common.ProgressProxy=class{constructor(delegate,doneCallback){this._delegate=delegate;this._doneCallback=doneCallback;}
isCanceled(){return this._delegate?this._delegate.isCanceled():false;}
setTitle(title){if(this._delegate)
this._delegate.setTitle(title);}
done(){if(this._delegate)
this._delegate.done();if(this._doneCallback)
this._doneCallback();}
setTotalWork(totalWork){if(this._delegate)
this._delegate.setTotalWork(totalWork);}
setWorked(worked,title){if(this._delegate)
this._delegate.setWorked(worked,title);}
worked(worked){if(this._delegate)
this._delegate.worked(worked);}};;Common.ResourceType=class{constructor(name,title,category,isTextType){this._name=name;this._title=title;this._category=category;this._isTextType=isTextType;}
static fromMimeType(mimeType){if(mimeType.startsWith('text/html'))
return Common.resourceTypes.Document;if(mimeType.startsWith('text/css'))
return Common.resourceTypes.Stylesheet;if(mimeType.startsWith('image/'))
return Common.resourceTypes.Image;if(mimeType.startsWith('text/'))
return Common.resourceTypes.Script;if(mimeType.includes('font'))
return Common.resourceTypes.Font;if(mimeType.includes('script'))
return Common.resourceTypes.Script;if(mimeType.includes('octet'))
return Common.resourceTypes.Other;if(mimeType.includes('application'))
return Common.resourceTypes.Script;return Common.resourceTypes.Other;}
static fromURL(url){return Common.ResourceType._resourceTypeByExtension.get(Common.ParsedURL.extractExtension(url))||null;}
static fromName(name){for(const resourceTypeId in Common.resourceTypes){const resourceType=Common.resourceTypes[resourceTypeId];if(resourceType.name()===name)
return resourceType;}
return null;}
static mimeFromURL(url){const name=Common.ParsedURL.extractName(url);if(Common.ResourceType._mimeTypeByName.has(name))
return Common.ResourceType._mimeTypeByName.get(name);const ext=Common.ParsedURL.extractExtension(url).toLowerCase();return Common.ResourceType._mimeTypeByExtension.get(ext);}
static mimeFromExtension(ext){return Common.ResourceType._mimeTypeByExtension.get(ext);}
name(){return this._name;}
title(){return this._title;}
category(){return this._category;}
isTextType(){return this._isTextType;}
isScript(){return this._name==='script'||this._name==='sm-script';}
hasScripts(){return this.isScript()||this.isDocument();}
isStyleSheet(){return this._name==='stylesheet'||this._name==='sm-stylesheet';}
isDocument(){return this._name==='document';}
isDocumentOrScriptOrStyleSheet(){return this.isDocument()||this.isScript()||this.isStyleSheet();}
isFromSourceMap(){return this._name.startsWith('sm-');}
toString(){return this._name;}
canonicalMimeType(){if(this.isDocument())
return'text/html';if(this.isScript())
return'text/javascript';if(this.isStyleSheet())
return'text/css';return'';}};Common.ResourceCategory=class{constructor(title,shortTitle){this.title=title;this.shortTitle=shortTitle;}};Common.resourceCategories={XHR:new Common.ResourceCategory('XHR and Fetch','XHR'),Script:new Common.ResourceCategory('Scripts','JS'),Stylesheet:new Common.ResourceCategory('Stylesheets','CSS'),Image:new Common.ResourceCategory('Images','Img'),Media:new Common.ResourceCategory('Media','Media'),Font:new Common.ResourceCategory('Fonts','Font'),Document:new Common.ResourceCategory('Documents','Doc'),WebSocket:new Common.ResourceCategory('WebSockets','WS'),Manifest:new Common.ResourceCategory('Manifest','Manifest'),Other:new Common.ResourceCategory('Other','Other')};Common.resourceTypes={XHR:new Common.ResourceType('xhr','XHR',Common.resourceCategories.XHR,true),Fetch:new Common.ResourceType('fetch','Fetch',Common.resourceCategories.XHR,true),EventSource:new Common.ResourceType('eventsource','EventSource',Common.resourceCategories.XHR,true),Script:new Common.ResourceType('script','Script',Common.resourceCategories.Script,true),Stylesheet:new Common.ResourceType('stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,true),Image:new Common.ResourceType('image','Image',Common.resourceCategories.Image,false),Media:new Common.ResourceType('media','Media',Common.resourceCategories.Media,false),Font:new Common.ResourceType('font','Font',Common.resourceCategories.Font,false),Document:new Common.ResourceType('document','Document',Common.resourceCategories.Document,true),TextTrack:new Common.ResourceType('texttrack','TextTrack',Common.resourceCategories.Other,true),WebSocket:new Common.ResourceType('websocket','WebSocket',Common.resourceCategories.WebSocket,false),Other:new Common.ResourceType('other','Other',Common.resourceCategories.Other,false),SourceMapScript:new Common.ResourceType('sm-script','Script',Common.resourceCategories.Script,true),SourceMapStyleSheet:new Common.ResourceType('sm-stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,true),Manifest:new Common.ResourceType('manifest','Manifest',Common.resourceCategories.Manifest,true),SignedExchange:new Common.ResourceType('signed-exchange','SignedExchange',Common.resourceCategories.Other,false),};Common.ResourceType._mimeTypeByName=new Map([['Cakefile','text/x-coffeescript']]);Common.ResourceType._resourceTypeByExtension=new Map([['js',Common.resourceTypes.Script],['mjs',Common.resourceTypes.Script],['css',Common.resourceTypes.Stylesheet],['xsl',Common.resourceTypes.Stylesheet],['jpeg',Common.resourceTypes.Image],['jpg',Common.resourceTypes.Image],['svg',Common.resourceTypes.Image],['gif',Common.resourceTypes.Image],['png',Common.resourceTypes.Image],['ico',Common.resourceTypes.Image],['tiff',Common.resourceTypes.Image],['tif',Common.resourceTypes.Image],['bmp',Common.resourceTypes.Image],['webp',Common.resourceTypes.Media],['ttf',Common.resourceTypes.Font],['otf',Common.resourceTypes.Font],['ttc',Common.resourceTypes.Font],['woff',Common.resourceTypes.Font]]);Common.ResourceType._mimeTypeByExtension=new Map([['js','text/javascript'],['mjs','text/javascript'],['css','text/css'],['html','text/html'],['htm','text/html'],['xml','application/xml'],['xsl','application/xml'],['asp','application/x-aspx'],['aspx','application/x-aspx'],['jsp','application/x-jsp'],['c','text/x-c++src'],['cc','text/x-c++src'],['cpp','text/x-c++src'],['h','text/x-c++src'],['m','text/x-c++src'],['mm','text/x-c++src'],['coffee','text/x-coffeescript'],['dart','text/javascript'],['ts','text/typescript'],['tsx','text/typescript-jsx'],['json','application/json'],['gyp','application/json'],['gypi','application/json'],['cs','text/x-csharp'],['java','text/x-java'],['less','text/x-less'],['php','text/x-php'],['phtml','application/x-httpd-php'],['py','text/x-python'],['sh','text/x-sh'],['scss','text/x-scss'],['vtt','text/vtt'],['ls','text/x-livescript'],['md','text/markdown'],['cljs','text/x-clojure'],['cljc','text/x-clojure'],['cljx','text/x-clojure'],['styl','text/x-styl'],['jsx','text/jsx'],['jpeg','image/jpeg'],['jpg','image/jpeg'],['svg','image/svg+xml'],['g
_registerModuleSetting(extension){const descriptor=extension.descriptor();const settingName=descriptor['settingName'];const isRegex=descriptor['settingType']==='regex';const defaultValue=descriptor['defaultValue'];let storageType;switch(descriptor['storageType']){case('local'):storageType=Common.SettingStorageType.Local;break;case('session'):storageType=Common.SettingStorageType.Session;break;case('global'):storageType=Common.SettingStorageType.Global;break;default:storageType=Common.SettingStorageType.Global;}
const setting=isRegex?this.createRegExpSetting(settingName,defaultValue,undefined,storageType):this.createSetting(settingName,defaultValue,storageType);if(descriptor['title'])
setting.setTitle(descriptor['title']);if(descriptor['userActionCondition'])
setting.setRequiresUserAction(!!Runtime.queryParam(descriptor['userActionCondition']));setting._extension=extension;this._moduleSettings.set(settingName,setting);}
moduleSetting(settingName){const setting=this._moduleSettings.get(settingName);if(!setting)
throw new Error('No setting registered: '+settingName);return setting;}
settingForTest(settingName){const setting=this._registry.get(settingName);if(!setting)
throw new Error('No setting registered: '+settingName);return setting;}
createSetting(key,defaultValue,storageType){const storage=this._storageFromType(storageType);if(!this._registry.get(key))
this._registry.set(key,new Common.Setting(this,key,defaultValue,this._eventSupport,storage));return(this._registry.get(key));}
createLocalSetting(key,defaultValue){return this.createSetting(key,defaultValue,Common.SettingStorageType.Local);}
createRegExpSetting(key,defaultValue,regexFlags,storageType){if(!this._registry.get(key)){this._registry.set(key,new Common.RegExpSetting(this,key,defaultValue,this._eventSupport,this._storageFromType(storageType),regexFlags));}
return(this._registry.get(key));}
clearAll(){this._globalStorage.removeAll();this._localStorage.removeAll();const versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);versionSetting.set(Common.VersionController.currentVersion);}
_storageFromType(storageType){switch(storageType){case(Common.SettingStorageType.Local):return this._localStorage;case(Common.SettingStorageType.Session):return this._sessionStorage;case(Common.SettingStorageType.Global):return this._globalStorage;}
return this._globalStorage;}};Common.SettingsStorage=class{constructor(object,setCallback,removeCallback,removeAllCallback,storagePrefix){this._object=object;this._setCallback=setCallback||function(){};this._removeCallback=removeCallback||function(){};this._removeAllCallback=removeAllCallback||function(){};this._storagePrefix=storagePrefix||'';}
set(name,value){name=this._storagePrefix+name;this._object[name]=value;this._setCallback(name,value);}
has(name){name=this._storagePrefix+name;return name in this._object;}
get(name){name=this._storagePrefix+name;return this._object[name];}
remove(name){name=this._storagePrefix+name;delete this._object[name];this._removeCallback(name);}
removeAll(){this._object={};this._removeAllCallback();}
_dumpSizes(){Common.console.log('Ten largest settings: ');const sizes={__proto__:null};for(const key in this._object)
sizes[key]=this._object[key].length;const keys=Object.keys(sizes);function comparator(key1,key2){return sizes[key2]-sizes[key1];}
keys.sort(comparator);for(let i=0;i<10&&i<keys.length;++i)
Common.console.log('Setting: \''+keys[i]+'\', size: '+sizes[keys[i]]);}};Common.Setting=class{constructor(settings,name,defaultValue,eventSupport,storage){this._settings=settings;this._name=name;this._defaultValue=defaultValue;this._eventSupport=eventSupport;this._storage=storage;this._title='';this._extension=null;}
addChangeListener(listener,thisObject){return this._eventSupport.addEventListener(this._name,listener,thisObject);}
removeChangeListener(listener,thisObject){this._eventSupport.removeEventListener(this._name,listener,thisObject);}
get name(){return this._name;}
title(){return this._title;}
setTitle(title){this._title=title;}
setRequiresUserAction(requiresUserAction){this._requiresUserAction=requiresUserAction;}
get(){if(this._requiresUserAction&&!this._hadUserAction)
return this._defaultValue;if(typeof this._value!=='undefined')
return this._value;this._value=this._defaultValue;if(this._storage.has(this._name)){try{this._value=JSON.parse(this._storage.get(this._name));}catch(e){this._storage.remove(this._name);}}
return this._value;}
set(value){this._hadUserAction=true;this._value=value;try{const settingString=JSON.stringify(value);try{this._storage.set(this._name,settingString);}catch(e){this._printSettingsSavingError(e.message,this._name,settingString);}}catch(e){Common.console.error('Cannot stringify setting with name: '+this._name+', error: '+e.message);}
this._eventSupport.dispatchEventToListeners(this._name,value);}
remove(){this._settings._registry.delete(this._name);this._settings._moduleSettings.delete(this._name);this._storage.remove(this._name);}
extension(){return this._extension;}
_printSettingsSavingError(message,name,value){const errorMessage='Error saving setting with name: '+this._name+', value length: '+value.length+'. Error: '+message;console.error(errorMessage);Common.console.error(errorMessage);this._storage._dumpSizes();}};Common.RegExpSetting=class extends Common.Setting{constructor(settings,name,defaultValue,eventSupport,storage,regexFlags){super(settings,name,defaultValue?[{pattern:defaultValue}]:[],eventSupport,storage);this._regexFlags=regexFlags;}
get(){const result=[];const items=this.getAsArray();for(let i=0;i<items.length;++i){const item=items[i];if(item.pattern&&!item.disabled)
result.push(item.pattern);}
return result.join('|');}
getAsArray(){return super.get();}
set(value){this.setAsArray([{pattern:value}]);}
setAsArray(value){delete this._regex;super.set(value);}
asRegExp(){if(typeof this._regex!=='undefined')
return this._regex;this._regex=null;try{const pattern=this.get();if(pattern)
this._regex=new RegExp(pattern,this._regexFlags||'');}catch(e){}
return this._regex;}};Common.VersionController=class{updateVersion(){const localStorageVersion=window.localStorage?window.localStorage[Common.VersionController._currentVersionName]:0;const versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);const currentVersion=Common.VersionController.currentVersion;const oldVersion=versionSetting.get()||parseInt(localStorageVersion||'0',10);if(oldVersion===0){versionSetting.set(currentVersion);return;}
const methodsToRun=this._methodsToRunToUpdateVersion(oldVersion,currentVersion);for(let i=0;i<methodsToRun.length;++i)
this[methodsToRun[i]].call(this);versionSetting.set(currentVersion);}
_methodsToRunToUpdateVersion(oldVersion,currentVersion){const result=[];for(let i=oldVersion;i<currentVersion;++i)
result.push('_updateVersionFrom'+i+'To'+(i+1));return result;}
_updateVersionFrom0To1(){this._clearBreakpointsWhenTooMany(Common.settings.createLocalSetting('breakpoints',[]),500000);}
_updateVersionFrom1To2(){Common.settings.createSetting('previouslyViewedFiles',[]).set([]);}
_updateVersionFrom2To3(){Common.settings.createSetting('fileSystemMapping',{}).set({});Common.settings.createSetting('fileMappingEntries',[]).remove();}
_updateVersionFrom3To4(){const advancedMode=Common.settings.createSetting('showHeaSnapshotObjectsHiddenProperties',false);Common.moduleSetting('showAdvancedHeapSnapshotProperties').set(advancedMode.get());advancedMode.remove();}
_updateVersionFrom4To5(){const settingNames={'FileSystemViewSidebarWidth':'fileSystemViewSplitViewState','elementsSidebarWidth':'elementsPanelSplitViewState','StylesPaneSplitRatio':'stylesPaneSplitViewState','heapSnapshotRetainersViewSize':'heapSnapshotSplitViewState','InspectorView.splitView':'InspectorView.splitViewState','InspectorView.screencastSplitView':'InspectorView.screencastSplitViewState','Inspector.drawerSplitView':'Inspector.drawerSplitViewState','layerDetailsSplitView':'layerDetailsSplitViewState','networkSidebarWidth':'networkPanelSplitViewState','sourcesSidebarWidth':'sourcesPanelSplitViewState','scriptsPanelNavigatorSidebarWidth':'sourcesPanelNavigatorSplitViewState','sourcesPanelSplitSidebarRatio':'sourcesPanelDebuggerSidebarSplitViewState','timeline-details':'timelinePanelDetailsSplitViewState','timeline-split':'timelinePanelRecorsSplitViewState','timeline-view':'timelinePanelTimelineStackSplitViewState','auditsSidebarWidth':'auditsPanelSplitViewState','layersSidebarWidth':'layersPanelSplitViewState','profilesSidebarWidth':'profilesPanelSplitViewState','resourcesSidebarWidth':'resourcesPanelSplitViewState'};const empty={};for(const oldName in settingNames){const newName=settingNames[oldName];const oldNameH=oldName+'H';let newValue=null;const oldSetting=Common.settings.createSetting(oldName,empty);if(oldSetting.get()!==empty){newValue=newValue||{};newValue.vertical={};newValue.vertical.size=oldSetting.get();oldSetting.remove();}
const oldSettingH=Common.settings.createSetting(oldNameH,empty);if(oldSettingH.get()!==empty){newValue=newValue||{};newValue.horizontal={};newValue.horizontal.size=oldSettingH.get();oldSettingH.remove();}
if(newValue)
Common.settings.createSetting(newName,{}).set(newValue);}}
_updateVersionFrom5To6(){const settingNames={'debuggerSidebarHidden':'sourcesPanelSplitViewState','navigatorHidden':'sourcesPanelNavigatorSplitViewState','WebInspector.Drawer.showOnLoad':'Inspector.drawerSplitViewState'};for(const oldName in settingNames){const oldSetting=Common.settings.createSetting(oldName,null);if(oldSetting.get()===null){oldSetting.remove();continue;}
const newName=settingNames[oldName];const invert=oldName==='WebInspector.Drawer.showOnLoad';const hidden=oldSetting.get()!==invert;oldSetting.remove();const showMode=hidden?'OnlyMain':'Both';const newSetting=Common.settings.createSetting(newName,{});const newValue=newSetting.get()||{};newValue.vertical=newValue.vertical||{};newValue.vertical.showMode=showMode;newValue.horizontal=newValue.horizontal||{};newValue.horizontal.showMode=showMode;newSetting.set(newValue);}}
_updateVersionFrom6To7(){const settingNames={'sourcesPanelNavigatorSplitViewState':'sourcesPanelNavigatorSplitViewState','elementsPanelSplitViewState':'elementsPanelSplitViewState','stylesPaneSplitViewState':'stylesPaneSplitViewState','sourcesPanelDebuggerSidebarSplitViewState':'sourcesPanelDebuggerSidebarSplitViewState'};const empty={};for(const name in settingNames){const setting=Common.settings.createSetting(name,empty);const value=setting.get();if(value===empty)
continue;if(value.vertical&&value.vertical.size&&value.vertical.size<1)
value.vertical.size=0;if(value.horizontal&&value.horizontal.size&&value.horizontal.size<1)
value.horizontal.size=0;setting.set(value);}}
_updateVersionFrom7To8(){}
_updateVersionFrom8To9(){const settingNames=['skipStackFramesPattern','workspaceFolderExcludePattern'];for(let i=0;i<settingNames.length;++i){const setting=Common.settings.createSetting(settingNames[i],'');let value=setting.get();if(!value)
return;if(typeof value==='string')
value=[value];for(let j=0;j<value.length;++j){if(typeof value[j]==='string')
value[j]={pattern:value[j]};}
setting.set(value);}}
_updateVersionFrom9To10(){if(!window.localStorage)
return;for(const key in window.localStorage){if(key.startsWith('revision-history'))
window.localStorage.removeItem(key);}}
_updateVersionFrom10To11(){const oldSettingName='customDevicePresets';const newSettingName='customEmulatedDeviceList';const oldSetting=Common.settings.createSetting(oldSettingName,undefined);const list=oldSetting.get();if(!Array.isArray(list))
return;const newList=[];for(let i=0;i<list.length;++i){const value=list[i];const device={};device['title']=value['title'];device['type']='unknown';device['user-agent']=value['userAgent'];device['capabilities']=[];if(value['touch'])
device['capabilities'].push('touch');if(value['mobile'])
device['capabilities'].push('mobile');device['screen']={};device['screen']['vertical']={width:value['width'],height:value['height']};device['screen']['horizontal']={width:value['height'],height:value['width']};device['screen']['device-pixel-ratio']=value['deviceScaleFactor'];device['modes']=[];device['show-by-default']=true;device['show']='Default';newList.push(device);}
if(newList.length)
Common.settings.createSetting(newSettingName,[]).set(newList);oldSetting.remove();}
_updateVersionFrom11To12(){this._migrateSettingsFromLocalStorage();}
_updateVersionFrom12To13(){this._migrateSettingsFromLocalStorage();Common.settings.createSetting('timelineOverviewMode','').remove();}
_updateVersionFrom13To14(){const defaultValue={'throughput':-1,'latency':0};Common.settings.createSetting('networkConditions',defaultValue).set(defaultValue);}
_updateVersionFrom14To15(){const setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});const oldValue=setting.get();const newValue={};for(const fileSystemPath in oldValue){newValue[fileSystemPath]=[];for(const entry of oldValue[fileSystemPath])
newValue[fileSystemPath].push(entry.path);}
setting.set(newValue);}
_updateVersionFrom15To16(){const setting=Common.settings.createSetting('InspectorView.panelOrder',{});const tabOrders=setting.get();for(const key of Object.keys(tabOrders))
tabOrders[key]=(tabOrders[key]+1)*10;setting.set(tabOrders);}
_updateVersionFrom16To17(){const setting=Common.settings.createSetting('networkConditionsCustomProfiles',[]);const oldValue=setting.get();const newValue=[];if(Array.isArray(oldValue)){for(const preset of oldValue){if(typeof preset.title==='string'&&typeof preset.value==='object'&&typeof preset.value.throughput==='number'&&typeof preset.value.latency==='number'){newValue.push({title:preset.title,value:{download:preset.value.throughput,upload:preset.value.throughput,latency:preset.value.latency}});}}}
setting.set(newValue);}
_updateVersionFrom17To18(){const setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});const oldValue=setting.get();const newValue={};for(const oldKey in oldValue){let newKey=oldKey.replace(/\\/g,'/');if(!newKey.startsWith('file://')){if(newKey.startsWith('/'))
newKey='file://'+newKey;else
newKey='file:///'+newKey;}
newValue[newKey]=oldValue[oldKey];}
setting.set(newValue);}
_updateVersionFrom18To19(){const defaultColumns={status:true,type:true,initiator:true,size:true,time:true};const visibleColumnSettings=Common.settings.createSetting('networkLogColumnsVisibility',defaultColumns);const visibleColumns=visibleColumnSettings.get();visibleColumns.name=true;visibleColumns.timeline=true;const configs={};for(const columnId in visibleColumns){if(!visibleColumns.hasOwnProperty(columnId))
continue;configs[columnId.toLowerCase()]={visible:visibleColumns[columnId]};}
const newSetting=Common.settings.createSetting('networkLogColumns',{});newSetting.set(configs);visibleColumnSettings.remove();}
_updateVersionFrom19To20(){const oldSetting=Common.settings.createSetting('InspectorView.panelOrder',{});const newSetting=Common.settings.createSetting('panel-tabOrder',{});newSetting.set(oldSetting.get());oldSetting.remove();}
_updateVersionFrom20To21(){const networkColumns=Common.settings.createSetting('networkLogColumns',{});const columns=(networkColumns.get());delete columns['timeline'];delete columns['waterfall'];networkColumns.set(columns);}
_updateVersionFrom21To22(){const breakpointsSetting=Common.settings.createLocalSetting('breakpoints',[]);const breakpoints=breakpointsSetting.get();for(const breakpoint of breakpoints){breakpoint['url']=breakpoint['sourceFileId'];delete breakpoint['sourceFileId'];}
breakpointsSetting.set(breakpoints);}
_updateVersionFrom22To23(){}
_updateVersionFrom23To24(){const oldSetting=Common.settings.createSetting('searchInContentScripts',false);const newSetting=Common.settings.createSetting('searchInAnonymousAndContentScripts',false);newSetting.set(oldSetting.get());oldSetting.remove();}
_updateVersionFrom24To25(){const defaultColumns={status:true,type:true,initiator:true,size:true,time:true};const networkLogColumnsSetting=Common.settings.createSetting('networkLogColumns',defaultColumns);const columns=networkLogColumnsSetting.get();delete columns.product;networkLogColumnsSetting.set(columns);}
_updateVersionFrom25To26(){const oldSetting=Common.settings.createSetting('messageURLFilters',{});const urls=Object.keys(oldSetting.get());const textFilter=urls.map(url=>`-url:${url}`).join(' ');if(textFilter){const textFilterSetting=Common.settings.createSetting('console.textFilter','');const suffix=textFilterSetting.get()?` ${textFilterSetting.get()}`:'';textFilterSetting.set(`${textFilter}${suffix}`);}
oldSetting.remove();}
_migrateSettingsFromLocalStorage(){const localSettings=new Set(['advancedSearchConfig','breakpoints','consoleHistory','domBreakpoints','eventListenerBreakpoints','fileSystemMapping','lastSelectedSourcesSidebarPaneTab','previouslyViewedFiles','savedURLs','watchExpressions','workspaceExcludedFolders','xhrBreakpoints']);if(!window.localStorage)
return;for(const key in window.localStorage){if(localSettings.has(key))
continue;const value=window.localStorage[key];window.localStorage.removeItem(key);Common.settings._globalStorage[key]=value;}}
_clearBreakpointsWhenTooMany(breakpointsSetting,maxBreakpointsCount){if(breakpointsSetting.get().length>maxBreakpointsCount)
breakpointsSetting.set([]);}};Common.VersionController._currentVersionName='inspectorVersion';Common.VersionController.currentVersion=26;Common.settings;Common.SettingStorageType={Global:Symbol('Global'),Local:Symbol('Local'),Session:Symbol('Session')};Common.moduleSetting=function(settingName){return Common.settings.moduleSetting(settingName);};Common.settingForTest=function(settingName){return Common.settings.settingForTest(settingName);};;Common.StaticContentProvider=class{constructor(contentURL,contentType,lazyContent){this._contentURL=contentURL;this._contentType=contentType;this._lazyContent=lazyContent;}
static fromString(contentURL,contentType,content){const lazyContent=()=>Promise.resolve(content);return new Common.StaticContentProvider(contentURL,contentType,lazyContent);}
contentURL(){return this._contentURL;}
contentType(){return this._contentType;}
contentEncoded(){return Promise.resolve(false);}
requestContent(){return this._lazyContent();}
async searchInContent(query,caseSensitive,isRegex){const content=await this._lazyContent();return content?Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex):[];}};;Common.OutputStream=function(){};Common.OutputStream.prototype={write(data){},close(){}};Common.StringOutputStream=class{constructor(){this._data='';}
async write(chunk){this._data+=chunk;}
close(){}
data(){return this._data;}};;Common.Segment=class{constructor(begin,end,data){if(begin>end)
console.assert(false,'Invalid segment');this.begin=begin;this.end=end;this.data=data;}
intersects(that){return this.begin<that.end&&that.begin<this.end;}};Common.SegmentedRange=class{constructor(mergeCallback){this._segments=[];this._mergeCallback=mergeCallback;}
append(newSegment){let startIndex=this._segments.lowerBound(newSegment,(a,b)=>a.begin-b.begin);let endIndex=startIndex;let merged=null;if(startIndex>0){const precedingSegment=this._segments[startIndex-1];merged=this._tryMerge(precedingSegment,newSegment);if(merged){--startIndex;newSegment=merged;}else if(this._segments[startIndex-1].end>=newSegment.begin){if(newSegment.end<precedingSegment.end){this._segments.splice(startIndex,0,new Common.Segment(newSegment.end,precedingSegment.end,precedingSegment.data));}
precedingSegment.end=newSegment.begin;}}
while(endIndex<this._segments.length&&this._segments[endIndex].end<=newSegment.end)
++endIndex;if(endIndex<this._segments.length){merged=this._tryMerge(newSegment,this._segments[endIndex]);if(merged){endIndex++;newSegment=merged;}else if(newSegment.intersects(this._segments[endIndex])){this._segments[endIndex].begin=newSegment.end;}}
this._segments.splice(startIndex,endIndex-startIndex,newSegment);}
appendRange(that){that.segments().forEach(segment=>this.append(segment));}
segments(){return this._segments;}
_tryMerge(first,second){const merged=this._mergeCallback&&this._mergeCallback(first,second);if(!merged)
return null;merged.begin=first.begin;merged.end=Math.max(first.end,second.end);return merged;}};;Common.Throttler=class{constructor(timeout){this._timeout=timeout;this._isRunningProcess=false;this._asSoonAsPossible=false;this._process=null;this._lastCompleteTime=0;this._schedulePromise=new Promise(fulfill=>{this._scheduleResolve=fulfill;});}
_processCompleted(){this._lastCompleteTime=this._getTime();this._isRunningProcess=false;if(this._process)
this._innerSchedule(false);this._processCompletedForTests();}
_processCompletedForTests(){}
_onTimeout(){delete this._processTimeout;this._asSoonAsPossible=false;this._isRunningProcess=true;Promise.resolve().then(this._process).catch(console.error.bind(console)).then(this._processCompleted.bind(this)).then(this._scheduleResolve);this._schedulePromise=new Promise(fulfill=>{this._scheduleResolve=fulfill;});this._process=null;}
schedule(process,asSoonAsPossible){this._process=process;const hasScheduledTasks=!!this._processTimeout||this._isRunningProcess;const okToFire=this._getTime()-this._lastCompleteTime>this._timeout;asSoonAsPossible=!!asSoonAsPossible||(!hasScheduledTasks&&okToFire);const forceTimerUpdate=asSoonAsPossible&&!this._asSoonAsPossible;this._asSoonAsPossible=this._asSoonAsPossible||asSoonAsPossible;this._innerSchedule(forceTimerUpdate);return this._schedulePromise;}
_innerSchedule(forceTimerUpdate){if(this._isRunningProcess)
return;if(this._processTimeout&&!forceTimerUpdate)
return;if(this._processTimeout)
this._clearTimeout(this._processTimeout);const timeout=this._asSoonAsPossible?0:this._timeout;this._processTimeout=this._setTimeout(this._onTimeout.bind(this),timeout);}
_clearTimeout(timeoutId){clearTimeout(timeoutId);}
_setTimeout(operation,timeout){return setTimeout(operation,timeout);}
_getTime(){return window.performance.now();}};Common.Throttler.FinishCallback;;Common.Trie=class{constructor(){this.clear();}
add(word){let node=this._root;++this._wordsInSubtree[this._root];for(let i=0;i<word.length;++i){const edge=word[i];let next=this._edges[node][edge];if(!next){if(this._freeNodes.length){next=this._freeNodes.pop();}else{next=this._size++;this._isWord.push(false);this._wordsInSubtree.push(0);this._edges.push({__proto__:null});}
this._edges[node][edge]=next;}
++this._wordsInSubtree[next];node=next;}
this._isWord[node]=true;}
remove(word){if(!this.has(word))
return false;let node=this._root;--this._wordsInSubtree[this._root];for(let i=0;i<word.length;++i){const edge=word[i];const next=this._edges[node][edge];if(!--this._wordsInSubtree[next]){delete this._edges[node][edge];this._freeNodes.push(next);}
node=next;}
this._isWord[node]=false;return true;}
has(word){let node=this._root;for(let i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node)
return false;}
return this._isWord[node];}
words(prefix){prefix=prefix||'';let node=this._root;for(let i=0;i<prefix.length;++i){node=this._edges[node][prefix[i]];if(!node)
return[];}
const results=[];this._dfs(node,prefix,results);return results;}
_dfs(node,prefix,results){if(this._isWord[node])
results.push(prefix);const edges=this._edges[node];for(const edge in edges)
this._dfs(edges[edge],prefix+edge,results);}
longestPrefix(word,fullWordOnly){let node=this._root;let wordIndex=0;for(let i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node)
break;if(!fullWordOnly||this._isWord[node])
wordIndex=i+1;}
return word.substring(0,wordIndex);}
clear(){this._size=1;this._root=0;this._edges=[{__proto__:null}];this._isWord=[false];this._wordsInSubtree=[0];this._freeNodes=[];}};;self['Common']=self['Common']||{};Common.UIString=function(string,vararg){return String.vsprintf(Common.localize(string),Array.prototype.slice.call(arguments,1));};Common.localize=function(string){return string;};Common.UIStringFormat=class{constructor(format){this._localizedFormat=Common.localize(format);this._tokenizedFormat=String.tokenizeFormatString(this._localizedFormat,String.standardFormatters);}
static _append(a,b){return a+b;}
format(vararg){return String.format(this._localizedFormat,arguments,String.standardFormatters,'',Common.UIStringFormat._append,this._tokenizedFormat).formattedResult;}};Common._substitutionStrings=new WeakMap();self.ls=function(strings,vararg){if(typeof strings==='string')
return strings;let substitutionString=Common._substitutionStrings.get(strings);if(!substitutionString){substitutionString=strings.join('%s');Common._substitutionStrings.set(strings,substitutionString);}
return Common.UIString(substitutionString,...Array.prototype.slice.call(arguments,1));};;Common.Revealer=function(){};Common.Revealer.reveal=function(revealable,omitFocus){if(!revealable)
return Promise.reject(new Error('Can\'t reveal '+revealable));return self.runtime.allInstances(Common.Revealer,revealable).then(reveal);function reveal(revealers){const promises=[];for(let i=0;i<revealers.length;++i)
promises.push(revealers[i].reveal((revealable),omitFocus));return Promise.race(promises);}};Common.Revealer.revealDestination=function(revealable){const extension=self.runtime.extension(Common.Revealer,revealable);if(!extension)
return null;return extension.descriptor()['destination'];};Common.Revealer.prototype={reveal(object,omitFocus){}};Common.App=function(){};Common.App.prototype={presentUI(document){}};Common.AppProvider=function(){};Common.AppProvider.prototype={createApp(){}};Common.QueryParamHandler=function(){};Common.QueryParamHandler.prototype={handleQueryParam(value){}};Common.Runnable=function(){};Common.Runnable.prototype={run(){}};Common.Linkifier=function(){};Common.Linkifier.prototype={linkify(object,options){}};Common.Linkifier.linkify=function(object,options){if(!object)
return Promise.reject(new Error('Can\'t linkify '+object));return self.runtime.extension(Common.Linkifier,object).instance().then(linkifier=>linkifier.linkify(object,options));};Common.Linkifier.Options;Common.JavaScriptMetadata=function(){};Common.JavaScriptMetadata.prototype={signaturesForNativeFunction(name){},signaturesForInstanceMethod(name,receiverClassName){},signaturesForStaticMethod(name,receiverConstructorName){}};;Common.CharacterIdMap=class{constructor(){this._elementToCharacter=new Map();this._characterToElement=new Map();this._charCode=33;}
toChar(object){let character=this._elementToCharacter.get(object);if(!character){if(this._charCode>=0xFFFF)
throw new Error('CharacterIdMap ran out of capacity!');character=String.fromCharCode(this._charCode++);this._elementToCharacter.set(object,character);this._characterToElement.set(character,object);}
return character;}
fromChar(character){const object=this._characterToElement.get(character);if(object===undefined)
return null;return object;}};;self['Host']=self['Host']||{};function InspectorFrontendHostAPI(){}
window.InspectorFrontendHostAPI=InspectorFrontendHostAPI;InspectorFrontendHostAPI.ContextMenuDescriptor;InspectorFrontendHostAPI.LoadNetworkResourceResult;InspectorFrontendHostAPI.Events={AddExtensions:Symbol('addExtensions'),AppendedToURL:Symbol('appendedToURL'),CanceledSaveURL:Symbol('canceledSaveURL'),ContextMenuCleared:Symbol('contextMenuCleared'),ContextMenuItemSelected:Symbol('contextMenuItemSelected'),DeviceCountUpdated:Symbol('deviceCountUpdated'),DevicesDiscoveryConfigChanged:Symbol('devicesDiscoveryConfigChanged'),DevicesPortForwardingStatusChanged:Symbol('devicesPortForwardingStatusChanged'),DevicesUpdated:Symbol('devicesUpdated'),DispatchMessage:Symbol('dispatchMessage'),DispatchMessageChunk:Symbol('dispatchMessageChunk'),EnterInspectElementMode:Symbol('enterInspectElementMode'),EyeDropperPickedColor:Symbol('eyeDropperPickedColor'),FileSystemsLoaded:Symbol('fileSystemsLoaded'),FileSystemRemoved:Symbol('fileSystemRemoved'),FileSystemAdded:Symbol('fileSystemAdded'),FileSystemFilesChangedAddedRemoved:Symbol('FileSystemFilesChangedAddedRemoved'),IndexingTotalWorkCalculated:Symbol('indexingTotalWorkCalculated'),IndexingWorked:Symbol('indexingWorked'),IndexingDone:Symbol('indexingDone'),KeyEventUnhandled:Symbol('keyEventUnhandled'),ReloadInspectedPage:Symbol('reloadInspectedPage'),RevealSourceLine:Symbol('revealSourceLine'),SavedURL:Symbol('savedURL'),SearchCompleted:Symbol('searchCompleted'),SetInspectedTabId:Symbol('setInspectedTabId'),SetUseSoftMenu:Symbol('setUseSoftMenu'),ShowPanel:Symbol('showPanel')};InspectorFrontendHostAPI.EventDescriptors=[[InspectorFrontendHostAPI.Events.AddExtensions,'addExtensions',['extensions']],[InspectorFrontendHostAPI.Events.AppendedToURL,'appendedToURL',['url']],[InspectorFrontendHostAPI.Events.CanceledSaveURL,'canceledSaveURL',['url']],[InspectorFrontendHostAPI.Events.ContextMenuCleared,'contextMenuCleared',[]],[InspectorFrontendHostAPI.Events.ContextMenuItemSelected,'contextMenuItemSelected',['id']],[InspectorFrontendHostAPI.Events.DeviceCountUpdated,'deviceCountUpdated',['count']],[InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,'devicesDiscoveryConfigChanged',['config']],[InspectorFrontendHostAPI.Events.DevicesPortForwardingStatusChanged,'devicesPortForwardingStatusChanged',['status']],[InspectorFrontendHostAPI.Events.DevicesUpdated,'devicesUpdated',['devices']],[InspectorFrontendHostAPI.Events.DispatchMessage,'dispatchMessage',['messageObject']],[InspectorFrontendHostAPI.Events.DispatchMessageChunk,'dispatchMessageChunk',['messageChunk','messageSize']],[InspectorFrontendHostAPI.Events.EnterInspectElementMode,'enterInspectElementMode',[]],[InspectorFrontendHostAPI.Events.EyeDropperPickedColor,'eyeDropperPickedColor',['color']],[InspectorFrontendHostAPI.Events.FileSystemsLoaded,'fileSystemsLoaded',['fileSystems']],[InspectorFrontendHostAPI.Events.FileSystemRemoved,'fileSystemRemoved',['fileSystemPath']],[InspectorFrontendHostAPI.Events.FileSystemAdded,'fileSystemAdded',['errorMessage','fileSystem']],[InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,'fileSystemFilesChangedAddedRemoved',['changed','added','removed']],[InspectorFrontendHostAPI.Events.IndexingTotalWorkCalculated,'indexingTotalWorkCalculated',['requestId','fileSystemPath','totalWork']],[InspectorFrontendHostAPI.Events.IndexingWorked,'indexingWorked',['requestId','fileSystemPath','worked']],[InspectorFrontendHostAPI.Events.IndexingDone,'indexingDone',['requestId','fileSystemPath']],[InspectorFrontendHostAPI.Events.KeyEventUnhandled,'keyEventUnhandled',['event']],[InspectorFrontendHostAPI.Events.ReloadInspectedPage,'reloadInspectedPage',['hard']],[InspectorFrontendHostAPI.Events.RevealSourceLine,'revealSourceLine',['url','lineNumber','columnNumber']],[InspectorFrontendHostAPI.Events.SavedURL,'savedURL',['url','fileSystemPath']],[InspectorFrontendHostAPI.Events.SearchCompleted,'searchCompleted',['requestId','fileSystemPath','files']],[InspectorFrontendHostAPI.Events.SetInspectedTabId,'setInspectedTabId',['tabId']],[InspectorFrontendHostAPI.Events.SetUseSoftMenu,'setUseSoftMenu',['useSo
event.stopPropagation();}
document.addEventListener('keydown',stopEventPropagation,true);this._urlsBeingSaved=new Map();}
platform(){let match=navigator.userAgent.match(/Windows NT/);if(match)
return'windows';match=navigator.userAgent.match(/Mac OS X/);if(match)
return'mac';return'linux';}
loadCompleted(){}
bringToFront(){this._windowVisible=true;}
closeWindow(){this._windowVisible=false;}
setIsDocked(isDocked,callback){setTimeout(callback,0);}
setInspectedPageBounds(bounds){}
inspectElementCompleted(){}
setInjectedScriptForOrigin(origin,script){}
inspectedURLChanged(url){document.title=Common.UIString('DevTools - %s',url.replace(/^https?:\/\//,''));}
copyText(text){if(navigator.clipboard){navigator.clipboard.writeText(text);}else if(document.queryCommandSupported('copy')){const input=document.createElement('input');input.value=text;document.body.appendChild(input);input.select();document.execCommand('copy');document.body.removeChild(input);}else{Common.console.error('Clipboard is not enabled in hosted mode. Please inspect using chrome://inspect');}}
openInNewTab(url){window.open(url,'_blank');}
showItemInFolder(fileSystemPath){Common.console.error('Show item in folder is not enabled in hosted mode. Please inspect using chrome://inspect');}
save(url,content,forceSaveAs){let buffer=this._urlsBeingSaved.get(url);if(!buffer){buffer=[];this._urlsBeingSaved.set(url,buffer);}
buffer.push(content);this.events.dispatchEventToListeners(InspectorFrontendHostAPI.Events.SavedURL,{url,fileSystemPath:url});}
append(url,content){const buffer=this._urlsBeingSaved.get(url);buffer.push(content);this.events.dispatchEventToListeners(InspectorFrontendHostAPI.Events.AppendedToURL,url);}
close(url){const buffer=this._urlsBeingSaved.get(url);this._urlsBeingSaved.delete(url);const fileName=url?url.trimURL().removeURLFragment():'';const link=createElement('a');link.download=fileName;const blob=new Blob([buffer.join('')],{type:'text/plain'});link.href=URL.createObjectURL(blob);link.click();}
sendMessageToBackend(message){}
recordEnumeratedHistogram(actionName,actionCode,bucketSize){}
recordPerformanceHistogram(histogramName,duration){}
recordUserMetricsAction(umaName){}
requestFileSystems(){this.events.dispatchEventToListeners(InspectorFrontendHostAPI.Events.FileSystemsLoaded,[]);}
addFileSystem(type){}
removeFileSystem(fileSystemPath){}
isolatedFileSystem(fileSystemId,registeredName){return null;}
loadNetworkResource(url,headers,streamId,callback){Runtime.loadResourcePromise(url).then(function(text){Host.ResourceLoader.streamWrite(streamId,text);callback({statusCode:200});}).catch(function(){callback({statusCode:404});});}
getPreferences(callback){const prefs={};for(const name in window.localStorage)
prefs[name]=window.localStorage[name];callback(prefs);}
setPreference(name,value){window.localStorage[name]=value;}
removePreference(name){delete window.localStorage[name];}
clearPreferences(){window.localStorage.clear();}
upgradeDraggedFileSystemPermissions(fileSystem){}
indexPath(requestId,fileSystemPath,excludedFolders){}
stopIndexing(requestId){}
searchInPath(requestId,fileSystemPath,query){}
zoomFactor(){return 1;}
zoomIn(){}
zoomOut(){}
resetZoom(){}
setWhitelistedShortcuts(shortcuts){}
setEyeDropperActive(active){}
showCertificateViewer(certChain){}
reattach(callback){}
readyForTest(){}
connectionReady(){}
setOpenNewWindowForPopups(value){}
setDevicesDiscoveryConfig(config){}
setDevicesUpdatesEnabled(enabled){}
performActionOnRemotePage(pageId,action){}
openRemotePage(browserId,url){}
openNodeFrontend(){}
showContextMenuAtPoint(x,y,items,document){throw'Soft context menu should be used';}
isHostedMode(){return true;}};Host.InspectorFrontendAPIImpl=class{constructor(){this._debugFrontend=!!Runtime.queryParam('debugFrontend')||(window['InspectorTest']&&window['InspectorTest']['debugTest']);const descriptors=InspectorFrontendHostAPI.EventDescriptors;for(let i=0;i<descriptors.length;++i)
this[descriptors[i][1]]=this._dispatch.bind(this,descriptors[i][0],descriptors[i][2],descriptors[i][3]);}
_dispatch(name,signature,runOnceLoaded){const params=Array.prototype.slice.call(arguments,3);if(this._debugFrontend)
setImmediate(innerDispatch);else
innerDispatch();function innerDispatch(){if(signature.length<2){try{InspectorFrontendHost.events.dispatchEventToListeners(name,params[0]);}catch(e){console.error(e+' '+e.stack);}
return;}
const data={};for(let i=0;i<signature.length;++i)
data[signature[i]]=params[i];try{InspectorFrontendHost.events.dispatchEventToListeners(name,data);}catch(e){console.error(e+' '+e.stack);}}}
streamWrite(id,chunk){Host.ResourceLoader.streamWrite(id,chunk);}};let InspectorFrontendHost=window.InspectorFrontendHost;(function(){function initializeInspectorFrontendHost(){let proto;if(!InspectorFrontendHost){window.InspectorFrontendHost=InspectorFrontendHost=new Host.InspectorFrontendHostStub();}else{proto=Host.InspectorFrontendHostStub.prototype;for(const name of Object.getOwnPropertyNames(proto)){const stub=proto[name];if(typeof stub!=='function'||InspectorFrontendHost[name])
continue;console.error('Incompatible embedder: method InspectorFrontendHost.'+name+' is missing. Using stub instead.');InspectorFrontendHost[name]=stub;}}
InspectorFrontendHost.events=new Common.Object();}
initializeInspectorFrontendHost();window.InspectorFrontendAPI=new Host.InspectorFrontendAPIImpl();})();InspectorFrontendHost.events;Host.isUnderTest=function(prefs){if(Runtime.queryParam('test'))
return true;if(prefs)
return prefs['isUnderTest']==='true';return Common.settings&&Common.settings.createSetting('isUnderTest',false).get();};;Host.platform=function(){if(!Host._platform)
Host._platform=InspectorFrontendHost.platform();return Host._platform;};Host.isMac=function(){if(typeof Host._isMac==='undefined')
Host._isMac=Host.platform()==='mac';return Host._isMac;};Host.isWin=function(){if(typeof Host._isWin==='undefined')
Host._isWin=Host.platform()==='windows';return Host._isWin;};Host.isCustomDevtoolsFrontend=function(){if(typeof Host._isCustomDevtoolsFronend==='undefined')
Host._isCustomDevtoolsFronend=window.location.toString().startsWith('devtools://devtools/custom/');return Host._isCustomDevtoolsFronend;};Host.fontFamily=function(){if(Host._fontFamily)
return Host._fontFamily;switch(Host.platform()){case'linux':Host._fontFamily='Roboto, Ubuntu, Arial, sans-serif';break;case'mac':Host._fontFamily='\'Lucida Grande\', sans-serif';break;case'windows':Host._fontFamily='\'Segoe UI\', Tahoma, sans-serif';break;}
return Host._fontFamily;};;Host.ResourceLoader={};Host.ResourceLoader._lastStreamId=0;Host.ResourceLoader._boundStreams={};Host.ResourceLoader._bindOutputStream=function(stream){Host.ResourceLoader._boundStreams[++Host.ResourceLoader._lastStreamId]=stream;return Host.ResourceLoader._lastStreamId;};Host.ResourceLoader._discardOutputStream=function(id){Host.ResourceLoader._boundStreams[id].close();delete Host.ResourceLoader._boundStreams[id];};Host.ResourceLoader.streamWrite=function(id,chunk){Host.ResourceLoader._boundStreams[id].write(chunk);};Host.ResourceLoader.load=function(url,headers,callback){const stream=new Common.StringOutputStream();Host.ResourceLoader.loadAsStream(url,headers,stream,mycallback);function mycallback(statusCode,headers){callback(statusCode,headers,stream.data());}};Host.ResourceLoader.loadAsStream=function(url,headers,stream,callback){const streamId=Host.ResourceLoader._bindOutputStream(stream);const parsedURL=new Common.ParsedURL(url);if(parsedURL.isDataURL()){loadXHR(url).then(dataURLDecodeSuccessful).catch(dataURLDecodeFailed);return;}
const rawHeaders=[];if(headers){for(const key in headers)
rawHeaders.push(key+': '+headers[key]);}
InspectorFrontendHost.loadNetworkResource(url,rawHeaders.join('\r\n'),streamId,finishedCallback);function finishedCallback(response){if(callback)
callback(response.statusCode,response.headers||{});Host.ResourceLoader._discardOutputStream(streamId);}
function dataURLDecodeSuccessful(text){Host.ResourceLoader.streamWrite(streamId,text);finishedCallback(({statusCode:200}));}
function dataURLDecodeFailed(){finishedCallback(({statusCode:404}));}};;Host.UserMetrics=class{panelShown(panelName){const code=Host.UserMetrics._PanelCodes[panelName]||0;const size=Object.keys(Host.UserMetrics._PanelCodes).length+1;InspectorFrontendHost.recordEnumeratedHistogram('DevTools.PanelShown',code,size);this._panelChangedSinceLaunch=true;}
drawerShown(drawerId){this.panelShown('drawer-'+drawerId);}
actionTaken(action){const size=Object.keys(Host.UserMetrics.Action).length+1;InspectorFrontendHost.recordEnumeratedHistogram('DevTools.ActionTaken',action,size);}
panelLoaded(panelName,histogramName){if(this._firedLaunchHistogram||panelName!==this._launchPanelName)
return;this._firedLaunchHistogram=true;requestAnimationFrame(()=>{setTimeout(()=>{performance.mark(histogramName);if(this._panelChangedSinceLaunch)
return;InspectorFrontendHost.recordPerformanceHistogram(histogramName,performance.now());},0);});}
setLaunchPanel(panelName){this._launchPanelName=panelName;}};Host.UserMetrics.Action={WindowDocked:1,WindowUndocked:2,ScriptsBreakpointSet:3,TimelineStarted:4,ProfilesCPUProfileTaken:5,ProfilesHeapProfileTaken:6,AuditsStarted:7,ConsoleEvaluated:8,FileSavedInWorkspace:9,DeviceModeEnabled:10,AnimationsPlaybackRateChanged:11,RevisionApplied:12,FileSystemDirectoryContentReceived:13,StyleRuleEdited:14,CommandEvaluatedInConsolePanel:15,DOMPropertiesExpanded:16,ResizedViewInResponsiveMode:17,TimelinePageReloadStarted:18,ConnectToNodeJSFromFrontend:19,ConnectToNodeJSDirectly:20,CpuThrottlingEnabled:21,CpuProfileNodeFocused:22,CpuProfileNodeExcluded:23,SelectFileFromFilePicker:24,SelectCommandFromCommandMenu:25,ChangeInspectedNodeInElementsPanel:26,StyleRuleCopied:27,CoverageStarted:28,Audits2Started:29,Audits2Finished:30,ShowedThirdPartyBadges:31,Audits2ViewTrace:32,FilmStripStartedRecording:33,};Host.UserMetrics._PanelCodes={elements:1,resources:2,network:3,sources:4,timeline:5,heap_profiler:6,audits:7,console:8,layers:9,'drawer-console-view':10,'drawer-animations':11,'drawer-network.config':12,'drawer-rendering':13,'drawer-sensors':14,'drawer-sources.search':15,security:16,js_profiler:17,audits2:18,};Host.userMetrics=new Host.UserMetrics();;self['UI']=self['UI']||{};UI.XElement=class extends HTMLElement{static get observedAttributes(){return['flex','padding','padding-top','padding-bottom','padding-left','padding-right','margin','margin-top','margin-bottom','margin-left','margin-right','overflow','overflow-x','overflow-y','font-size','color','background','background-color','border','border-top','border-bottom','border-left','border-right','max-width','max-height'];}
attributeChangedCallback(attr,oldValue,newValue){if(attr==='flex'){if(newValue===null)
this.style.removeProperty('flex');else if(newValue==='initial'||newValue==='auto'||newValue==='none'||newValue.indexOf(' ')!==-1)
this.style.setProperty('flex',newValue);else
this.style.setProperty('flex','0 0 '+newValue);return;}
if(newValue===null){this.style.removeProperty(attr);if(attr.startsWith('padding-')||attr.startsWith('margin-')||attr.startsWith('border-')||attr.startsWith('background-')||attr.startsWith('overflow-')){const shorthand=attr.substring(0,attr.indexOf('-'));const shorthandValue=this.getAttribute(shorthand);if(shorthandValue!==null)
this.style.setProperty(shorthand,shorthandValue);}}else{this.style.setProperty(attr,newValue);}}};UI._XBox=class extends UI.XElement{constructor(direction){super();this.style.setProperty('display','flex');this.style.setProperty('flex-direction',direction);this.style.setProperty('justify-content','flex-start');}
static get observedAttributes(){return UI.XElement.observedAttributes.concat(['x-start','x-center','x-stretch','x-baseline','justify-content']);}
attributeChangedCallback(attr,oldValue,newValue){if(attr==='x-start'||attr==='x-center'||attr==='x-stretch'||attr==='x-baseline'){if(newValue===null)
this.style.removeProperty('align-items');else
this.style.setProperty('align-items',attr==='x-start'?'flex-start':attr.substr(2));return;}
super.attributeChangedCallback(attr,oldValue,newValue);}};UI.XVBox=class extends UI._XBox{constructor(){super('column');}};UI.XHBox=class extends UI._XBox{constructor(){super('row');}};UI.XCBox=class extends UI.XElement{constructor(){super();this.style.setProperty('display','flex');this.style.setProperty('flex-direction','column');this.style.setProperty('justify-content','center');this.style.setProperty('align-items','center');}};UI.XDiv=class extends UI.XElement{constructor(){super();this.style.setProperty('display','block');}};UI.XSpan=class extends UI.XElement{constructor(){super();this.style.setProperty('display','inline');}};UI.XText=class extends UI.XElement{constructor(){super();this.style.setProperty('display','inline');this.style.setProperty('white-space','pre');}};self.customElements.define('x-vbox',UI.XVBox);self.customElements.define('x-hbox',UI.XHBox);self.customElements.define('x-cbox',UI.XCBox);self.customElements.define('x-div',UI.XDiv);self.customElements.define('x-span',UI.XSpan);self.customElements.define('x-text',UI.XText);;UI.Widget=class extends Common.Object{constructor(isWebComponent,delegatesFocus){super();this.contentElement=createElementWithClass('div','widget');if(isWebComponent){this.element=createElementWithClass('div','vbox flex-auto');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,undefined,delegatesFocus);this._shadowRoot.appendChild(this.contentElement);}else{this.element=this.contentElement;}
this._isWebComponent=isWebComponent;this.element.__widget=this;this._visible=false;this._isRoot=false;this._isShowing=false;this._children=[];this._hideOnDetach=false;this._notificationDepth=0;this._invalidationsSuspended=0;this._defaultFocusedChild=null;}
static _incrementWidgetCounter(parentElement,childElement){const count=(childElement.__widgetCounter||0)+(childElement.__widget?1:0);if(!count)
return;while(parentElement){parentElement.__widgetCounter=(parentElement.__widgetCounter||0)+count;parentElement=parentElement.parentElementOrShadowHost();}}
static _decrementWidgetCounter(parentElement,childElement){const count=(childElement.__widgetCounter||0)+(childElement.__widget?1:0);if(!count)
return;while(parentElement){parentElement.__widgetCounter-=count;parentElement=parentElement.parentElementOrShadowHost();}}
static __assert(condition,message){if(!condition)
throw new Error(message);}
static focusWidgetForNode(node){while(node){if(node.__widget)
break;node=node.parentNodeOrShadowHost();}
if(!node)
return;let widget=node.__widget;while(widget._parentWidget){widget._parentWidget._defaultFocusedChild=widget;widget=widget._parentWidget;}}
markAsRoot(){UI.Widget.__assert(!this.element.parentElement,'Attempt to mark as root attached node');this._isRoot=true;}
parentWidget(){return this._parentWidget;}
children(){return this._children;}
childWasDetached(widget){}
isShowing(){return this._isShowing;}
shouldHideOnDetach(){if(!this.element.parentElement)
return false;if(this._hideOnDetach)
return true;for(const child of this._children){if(child.shouldHideOnDetach())
return true;}
return false;}
setHideOnDetach(){this._hideOnDetach=true;}
_inNotification(){return!!this._notificationDepth||(this._parentWidget&&this._parentWidget._inNotification());}
_parentIsShowing(){if(this._isRoot)
return true;return!!this._parentWidget&&this._parentWidget.isShowing();}
_callOnVisibleChildren(method){const copy=this._children.slice();for(let i=0;i<copy.length;++i){if(copy[i]._parentWidget===this&&copy[i]._visible)
method.call(copy[i]);}}
_processWillShow(){this._callOnVisibleChildren(this._processWillShow);this._isShowing=true;}
_processWasShown(){if(this._inNotification())
return;this.restoreScrollPositions();this._notify(this.wasShown);this._callOnVisibleChildren(this._processWasShown);}
_processWillHide(){if(this._inNotification())
return;this.storeScrollPositions();this._callOnVisibleChildren(this._processWillHide);this._notify(this.willHide);this._isShowing=false;}
_processWasHidden(){this._callOnVisibleChildren(this._processWasHidden);}
_processOnResize(){if(this._inNotification())
return;if(!this.isShowing())
return;this._notify(this.onResize);this._callOnVisibleChildren(this._processOnResize);}
_notify(notification){++this._notificationDepth;try{notification.call(this);}finally{--this._notificationDepth;}}
wasShown(){}
willHide(){}
onResize(){}
onLayout(){}
ownerViewDisposed(){}
show(parentElement,insertBefore){UI.Widget.__assert(parentElement,'Attempt to attach widget with no parent element');if(!this._isRoot){let currentParent=parentElement;while(currentParent&&!currentParent.__widget)
currentParent=currentParent.parentElementOrShadowHost();UI.Widget.__assert(currentParent,'Attempt to attach widget to orphan node');this._attach(currentParent.__widget);}
this._showWidget(parentElement,insertBefore);}
_attach(parentWidget){if(parentWidget===this._parentWidget)
return;if(this._parentWidget)
this.detach();this._parentWidget=parentWidget;this._parentWidget._children.push(this);this._isRoot=false;}
showWidget(){if(this._visible)
return;UI.Widget.__assert(this.element.parentElement,'Attempt to show widget that is not hidden using hideWidget().');this._showWidget((this.element.parentElement),this.element.nextSibling);}
_showWidget(parentElement,insertBefore){let currentParent=parentElement;while(currentParent&&!currentParent.__widget)
currentParent=currentParent.parentElementOrShadowHost();if(this._isRoot){UI.Widget.__assert(!currentParent,'Attempt to show root widget under another widget');}else{UI.Widget.__assert(currentParent&&currentParent.__widget===this._parentWidget,'Attempt to show under node belonging to alien widget');}
const wasVisible=this._visible;if(wasVisible&&this.element.parentElement===parentElement)
return;this._visible=true;if(!wasVisible&&this._parentIsShowing())
this._processWillShow();this.element.classList.remove('hidden');if(this.element.parentElement!==parentElement){UI.Widget._incrementWidgetCounter(parentElement,this.element);if(insertBefore)
UI.Widget._originalInsertBefore.call(parentElement,this.element,insertBefore);else
UI.Widget._originalAppendChild.call(parentElement,this.element);}
if(!wasVisible&&this._parentIsShowing())
this._processWasShown();if(this._parentWidget&&this._hasNonZeroConstraints())
this._parentWidget.invalidateConstraints();else
this._processOnResize();}
hideWidget(){if(!this._visible)
return;this._hideWidget(false);}
_hideWidget(removeFromDOM){this._visible=false;const parentElement=this.element.parentElement;if(this._parentIsShowing())
this._processWillHide();if(removeFromDOM){UI.Widget._decrementWidgetCounter(parentElement,this.element);UI.Widget._originalRemoveChild.call(parentElement,this.element);}else{this.element.classList.add('hidden');}
if(this._parentIsShowing())
this._processWasHidden();if(this._parentWidget&&this._hasNonZeroConstraints())
this._parentWidget.invalidateConstraints();}
detach(overrideHideOnDetach){if(!this._parentWidget&&!this._isRoot)
return;const removeFromDOM=overrideHideOnDetach||!this.shouldHideOnDetach();if(this._visible){this._hideWidget(removeFromDOM);}else if(removeFromDOM&&this.element.parentElement){const parentElement=this.element.parentElement;UI.Widget._decrementWidgetCounter(parentElement,this.element);UI.Widget._originalRemoveChild.call(parentElement,this.element);}
if(this._parentWidget){const childIndex=this._parentWidget._children.indexOf(this);UI.Widget.__assert(childIndex>=0,'Attempt to remove non-child widget');this._parentWidget._children.splice(childIndex,1);if(this._parentWidget._defaultFocusedChild===this)
this._parentWidget._defaultFocusedChild=null;this._parentWidget.childWasDetached(this);this._parentWidget=null;}else{UI.Widget.__assert(this._isRoot,'Removing non-root widget from DOM');}}
detachChildWidgets(){const children=this._children.slice();for(let i=0;i<children.length;++i)
children[i].detach();}
elementsToRestoreScrollPositionsFor(){return[this.element];}
storeScrollPositions(){const elements=this.elementsToRestoreScrollPositionsFor();for(let i=0;i<elements.length;++i){const container=elements[i];container._scrollTop=container.scrollTop;container._scrollLeft=container.scrollLeft;}}
restoreScrollPositions(){const elements=this.elementsToRestoreScrollPositionsFor();for(let i=0;i<elements.length;++i){const container=elements[i];if(container._scrollTop)
container.scrollTop=container._scrollTop;if(container._scrollLeft)
container.scrollLeft=container._scrollLeft;}}
doResize(){if(!this.isShowing())
return;if(!this._inNotification())
this._callOnVisibleChildren(this._processOnResize);}
doLayout(){if(!this.isShowing())
return;this._notify(this.onLayout);this.doResize();}
registerRequiredCSS(cssFile){UI.appendStyle(this._isWebComponent?this._shadowRoot:this.element,cssFile);}
printWidgetHierarchy(){const lines=[];this._collectWidgetHierarchy('',lines);console.log(lines.join('\n'));}
_collectWidgetHierarchy(prefix,lines){lines.push(prefix+'['+this.element.className+']'+(this._children.length?' {':''));for(let i=0;i<this._children.length;++i)
this._children[i]._collectWidgetHierarchy(prefix+' ',lines);if(this._children.length)
lines.push(prefix+'}');}
setDefaultFocusedElement(element){this._defaultFocusedElement=element;}
setDefaultFocusedChild(child){UI.Widget.__assert(child._parentWidget===this,'Attempt to set non-child widget as default focused.');this._defaultFocusedChild=child;}
focus(){if(!this.isShowing())
return;const element=this._defaultFocusedElement;if(element){if(!element.hasFocus())
element.focus();return;}
if(this._defaultFocusedChild&&this._defaultFocusedChild._visible){this._defaultFocusedChild.focus();}else{for(const child of this._children){if(child._visible){child.focus();return;}}
let child=this.contentElement.traverseNextNode(this.contentElement);while(child){if(child instanceof UI.XWidget){child.focus();return;}
child=child.traverseNextNode(this.contentElement);}}}
hasFocus(){return this.element.hasFocus();}
calculateConstraints(){return new UI.Constraints();}
constraints(){if(typeof this._constraints!=='undefined')
return this._constraints;if(typeof this._cachedConstraints==='undefined')
this._cachedConstraints=this.calculateConstraints();return this._cachedConstraints;}
setMinimumAndPreferredSizes(width,height,preferredWidth,preferredHeight){this._constraints=new UI.Constraints(new UI.Size(width,height),new UI.Size(preferredWidth,preferredHeight));this.invalidateConstraints();}
setMinimumSize(width,height){this._constraints=new UI.Constraints(new UI.Size(width,height));this.invalidateConstraints();}
_hasNonZeroConstraints(){const constraints=this.constraints();return!!(constraints.minimum.width||constraints.minimum.height||constraints.preferred.width||constraints.preferred.height);}
suspendInvalidations(){++this._invalidationsSuspended;}
resumeInvalidations(){--this._invalidationsSuspended;if(!this._invalidationsSuspended&&this._invalidationsRequested)
this.invalidateConstraints();}
invalidateConstraints(){if(this._invalidationsSuspended){this._invalidationsRequested=true;return;}
this._invalidationsRequested=false;const cached=this._cachedConstraints;delete this._cachedConstraints;const actual=this.constraints();if(!actual.isEqual(cached)&&this._parentWidget)
this._parentWidget.invalidateConstraints();else
this.doLayout();}};UI.Widget._originalAppendChild=Element.prototype.appendChild;UI.Widget._originalInsertBefore=Element.prototype.insertBefore;UI.Widget._originalRemoveChild=Element.prototype.removeChild;UI.Widget._originalRemoveChildren=Element.prototype.removeChildren;UI.VBox=class extends UI.Widget{constructor(isWebComponent,delegatesFocus){super(isWebComponent,delegatesFocus);this.contentElement.classList.add('vbox');}
calculateConstraints(){let constraints=new UI.Constraints();function updateForChild(){const child=this.constraints();constraints=constraints.widthToMax(child);constraints=constraints.addHeight(child);}
this._callOnVisibleChildren(updateForChild);return constraints;}};UI.HBox=class extends UI.Widget{constructor(isWebComponent){super(isWebComponent);this.contentElement.classList.add('hbox');}
calculateConstraints(){let constraints=new UI.Constraints();function updateForChild(){const child=this.constraints();constraints=constraints.addWidth(child);constraints=constraints.heightToMax(child);}
this._callOnVisibleChildren(updateForChild);return constraints;}};UI.VBoxWithResizeCallback=class extends UI.VBox{constructor(resizeCallback){super();this._resizeCallback=resizeCallback;}
onResize(){this._resizeCallback();}};UI.WidgetFocusRestorer=class{constructor(widget){this._widget=widget;this._previous=widget.element.ownerDocument.deepActiveElement();widget.focus();}
restore(){if(!this._widget)
return;if(this._widget.hasFocus()&&this._previous)
this._previous.focus();this._previous=null;this._widget=null;}};Element.prototype.appendChild=function(child){UI.Widget.__assert(!child.__widget||child.parentElement===this,'Attempt to add widget via regular DOM operation.');return UI.Widget._originalAppendChild.call(this,child);};Element.prototype.insertBefore=function(child,anchor){UI.Widget.__assert(!child.__widget||child.parentElement===this,'Attempt to add widget via regular DOM operation.');return UI.Widget._originalInsertBefore.call(this,child,anchor);};Element.prototype.removeChild=function(child){UI.Widget.__assert(!child.__widgetCounter&&!child.__widget,'Attempt to remove element containing widget via regular DOM operation');return UI.Widget._originalRemoveChild.call(this,child);};Element.prototype.removeChildren=function(){UI.Widget.__assert(!this.__widgetCounter,'Attempt to remove element containing widget via regular DOM operation');UI.Widget._originalRemoveChildren.call(this);};;UI.View=function(){};UI.View.prototype={viewId(){},title(){},isCloseable(){},isTransient(){},toolbarItems(){},widget(){},disposeView(){}};UI.View._symbol=Symbol('view');UI.View._widgetSymbol=Symbol('widget');UI.SimpleView=class extends UI.VBox{constructor(title,isWebComponent){super(isWebComponent);this._title=title;this._toolbarItems=[];this[UI.View._symbol]=this;}
viewId(){return this._title;}
title(){return this._title;}
isCloseable(){return false;}
isTransient(){return false;}
toolbarItems(){return Promise.resolve(this.syncToolbarItems());}
syncToolbarItems(){return this._toolbarItems;}
widget(){return(Promise.resolve(this));}
addToolbarItem(item){this._toolbarItems.push(item);}
revealView(){return UI.viewManager.revealView(this);}
disposeView(){}};UI.ProvidedView=class{constructor(extension){this._extension=extension;}
viewId(){return this._extension.descriptor()['id'];}
title(){return this._extension.title();}
isCloseable(){return this._extension.descriptor()['persistence']==='closeable';}
isTransient(){return this._extension.descriptor()['persistence']==='transient';}
toolbarItems(){const actionIds=this._extension.descriptor()['actionIds'];if(actionIds){const result=actionIds.split(',').map(id=>UI.Toolbar.createActionButtonForId(id.trim()));return Promise.resolve(result);}
if(this._extension.descriptor()['hasToolbar'])
return this.widget().then(widget=>(widget).toolbarItems());return Promise.resolve([]);}
async widget(){this._widgetRequested=true;const widget=await this._extension.instance();if(!(widget instanceof UI.Widget))
throw new Error('view className should point to a UI.Widget');widget[UI.View._symbol]=this;return(widget);}
async disposeView(){if(!this._widgetRequested)
return;const widget=await this.widget();widget.ownerViewDisposed();}};UI.ViewLocation=function(){};UI.ViewLocation.prototype={appendApplicableItems(locationName){},appendView(view,insertBefore){},showView(view,insertBefore,userGesture){},removeView(view){},widget(){}};UI.TabbedViewLocation=function(){};UI.TabbedViewLocation.prototype={tabbedPane(){},enableMoreTabsButton(){}};UI.ViewLocationResolver=function(){};UI.ViewLocationResolver.prototype={resolveLocation(location){}};UI.ViewManager=class{constructor(){this._views=new Map();this._locationNameByViewId=new Map();for(const extension of self.runtime.extensions('view')){const descriptor=extension.descriptor();this._views.set(descriptor['id'],new UI.ProvidedView(extension));this._locationNameByViewId.set(descriptor['id'],descriptor['location']);}}
static _populateToolbar(element,toolbarItems){if(!toolbarItems.length)
return;const toolbar=new UI.Toolbar('');element.insertBefore(toolbar.element,element.firstChild);for(const item of toolbarItems)
toolbar.appendToolbarItem(item);}
revealView(view){const location=(view[UI.ViewManager._Location.symbol]);if(!location)
return Promise.resolve();location._reveal();return location.showView(view);}
view(viewId){return this._views.get(viewId);}
materializedWidget(viewId){const view=this.view(viewId);return view?view[UI.View._widgetSymbol]:null;}
showView(viewId,userGesture,omitFocus){const view=this._views.get(viewId);if(!view){console.error('Could not find view for id: \''+viewId+'\' '+new Error().stack);return Promise.resolve();}
const locationName=this._locationNameByViewId.get(viewId);const location=view[UI.ViewManager._Location.symbol];if(location){location._reveal();return location.showView(view,undefined,userGesture,omitFocus);}
return this.resolveLocation(locationName).then(location=>{if(!location)
throw new Error('Could not resolve location for view: '+viewId);location._reveal();return location.showView(view,undefined,userGesture,omitFocus);});}
resolveLocation(location){if(!location)
return(Promise.resolve(null));const resolverExtensions=self.runtime.extensions(UI.ViewLocationResolver).filter(extension=>extension.descriptor()['name']===location);if(!resolverExtensions.length)
throw new Error('Unresolved location: '+location);const resolverExtension=resolverExtensions[0];return resolverExtension.instance().then(resolver=>(resolver.resolveLocation(location)));}
createTabbedLocation(revealCallback,location,restoreSelection,allowReorder,defaultTab){return new UI.ViewManager._TabbedLocation(this,revealCallback,location,restoreSelection,allowReorder,defaultTab);}
createStackLocation(revealCallback,location){return new UI.ViewManager._StackLocation(this,revealCallback,location);}
hasViewsForLocation(location){return!!this._viewsForLocation(location).length;}
_viewsForLocation(location){const result=[];for(const id of this._views.keys()){if(this._locationNameByViewId.get(id)===location)
result.push(this._views.get(id));}
return result;}};UI.ViewManager._ContainerWidget=class extends UI.VBox{constructor(view){super();this.element.classList.add('flex-auto','view-container','overflow-auto');this._view=view;this.element.tabIndex=-1;this.setDefaultFocusedElement(this.element);}
_materialize(){if(this._materializePromise)
return this._materializePromise;const promises=[];promises.push(this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager,this.element)));promises.push(this._view.widget().then(widget=>{const shouldFocus=this.element.hasFocus();this.setDefaultFocusedElement(null);this._view[UI.View._widgetSymbol]=widget;widget.show(this.element);if(shouldFocus)
widget.focus();}));this._materializePromise=Promise.all(promises);return this._materializePromise;}
wasShown(){this._materialize().then(()=>{this._wasShownForTest();});}
_wasShownForTest(){}};UI.ViewManager._ExpandableContainerWidget=class extends UI.VBox{constructor(view){super(true);this.element.classList.add('flex-none');this.registerRequiredCSS('ui/viewContainers.css');this._titleElement=createElementWithClass('div','expandable-view-title');UI.ARIAUtils.markAsLink(this._titleElement);this._titleExpandIcon=UI.Icon.create('smallicon-triangle-right','title-expand-icon');this._titleElement.appendChild(this._titleExpandIcon);this._titleElement.createTextChild(view.title());this._titleElement.tabIndex=0;this._titleElement.addEventListener('click',this._toggleExpanded.bind(this),false);this._titleElement.addEventListener('keydown',this._onTitleKeyDown.bind(this),false);this.contentElement.insertBefore(this._titleElement,this.contentElement.firstChild);this.contentElement.createChild('slot');this._view=view;view[UI.ViewManager._ExpandableContainerWidget._symbol]=this;}
_materialize(){if(this._materializePromise)
return this._materializePromise;const promises=[];promises.push(this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager,this._titleElement)));promises.push(this._view.widget().then(widget=>{this._widget=widget;this._view[UI.View._widgetSymbol]=widget;widget.show(this.element);}));this._materializePromise=Promise.all(promises);return this._materializePromise;}
_expand(){if(this._titleElement.classList.contains('expanded'))
return this._materialize();this._titleElement.classList.add('expanded');UI.ARIAUtils.setExpanded(this._titleElement,true);this._titleExpandIcon.setIconType('smallicon-triangle-down');return this._materialize().then(()=>this._widget.show(this.element));}
_collapse(){if(!this._titleElement.classList.contains('expanded'))
return;this._titleElement.classList.remove('expanded');UI.ARIAUtils.setExpanded(this._titleElement,false);this._titleExpandIcon.setIconType('smallicon-triangle-right');this._materialize().then(()=>this._widget.detach());}
_toggleExpanded(){if(this._titleElement.classList.contains('expanded'))
this._collapse();else
this._expand();}
_onTitleKeyDown(event){if(isEnterKey(event)||event.keyCode===UI.KeyboardShortcut.Keys.Space.code){this._toggleExpanded();}else if(event.key==='ArrowLeft'){this._collapse();}else if(event.key==='ArrowRight'){if(!this._titleElement.classList.contains('expanded'))
this._expand();else if(this._widget)
this._widget.focus();}}};UI.ViewManager._ExpandableContainerWidget._symbol=Symbol('container');UI.ViewManager._Location=class{constructor(manager,widget,revealCallback){this._manager=manager;this._revealCallback=revealCallback;this._widget=widget;}
widget(){return this._widget;}
_reveal(){if(this._revealCallback)
this._revealCallback();}};UI.ViewManager._Location.symbol=Symbol('location');UI.ViewManager._TabbedLocation=class extends UI.ViewManager._Location{constructor(manager,revealCallback,location,restoreSelection,allowReorder,defaultTab){const tabbedPane=new UI.TabbedPane();if(allowReorder)
tabbedPane.setAllowTabReorder(true);super(manager,tabbedPane,revealCallback);this._tabbedPane=tabbedPane;this._allowReorder=allowReorder;this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabClosed,this._tabClosed,this);this._closeableTabSetting=Common.settings.createSetting(location+'-closeableTabs',{});this._tabOrderSetting=Common.settings.createSetting(location+'-tabOrder',{});this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabOrderChanged,this._persistTabOrder,this);if(restoreSelection)
this._lastSelectedTabSetting=Common.settings.createSetting(location+'-selectedTab','');this._defaultTab=defaultTab;this._views=new Map();if(location)
this.appendApplicableItems(location);}
widget(){return this._tabbedPane;}
tabbedPane(){return this._tabbedPane;}
enableMoreTabsButton(){const moreTabsButton=new UI.ToolbarMenuButton(this._appendTabsToMenu.bind(this));this._tabbedPane.leftToolbar().appendToolbarItem(moreTabsButton);this._tabbedPane.disableOverflowMenu();return moreTabsButton;}
appendApplicableItems(locationName){const views=this._manager._viewsForLocation(locationName);if(this._allowReorder){let i=0;const persistedOrders=this._tabOrderSetting.get();const orders=new Map();for(const view of views)
orders.set(view.viewId(),persistedOrders[view.viewId()]||(++i)*UI.ViewManager._TabbedLocation.orderStep);views.sort((a,b)=>orders.get(a.viewId())-orders.get(b.viewId()));}
for(const view of views){const id=view.viewId();this._views.set(id,view);view[UI.ViewManager._Location.symbol]=this;if(view.isTransient())
continue;if(!view.isCloseable())
this._appendTab(view);else if(this._closeableTabSetting.get()[id])
this._appendTab(view);}
if(this._defaultTab&&this._tabbedPane.hasTab(this._defaultTab))
this._tabbedPane.selectTab(this._defaultTab);else if(this._lastSelectedTabSetting&&this._tabbedPane.hasTab(this._lastSelectedTabSetting.get()))
this._tabbedPane.selectTab(this._lastSelectedTabSetting.get());}
_appendTabsToMenu(contextMenu){const views=Array.from(this._views.values());views.sort((viewa,viewb)=>viewa.title().localeCompare(viewb.title()));for(const view of views){const title=Common.UIString(view.title());contextMenu.defaultSection().appendItem(title,this.showView.bind(this,view,undefined,true));}}
_appendTab(view,index){this._tabbedPane.appendTab(view.viewId(),view.title(),new UI.ViewManager._ContainerWidget(view),undefined,false,view.isCloseable()||view.isTransient(),index);}
appendView(view,insertBefore){if(this._tabbedPane.hasTab(view.viewId()))
return;const oldLocation=view[UI.ViewManager._Location.symbol];if(oldLocation&&oldLocation!==this)
oldLocation.removeView(view);view[UI.ViewManager._Location.symbol]=this;this._manager._views.set(view.viewId(),view);this._views.set(view.viewId(),view);let index=undefined;const tabIds=this._tabbedPane.tabIds();if(this._allowReorder){const orderSetting=this._tabOrderSetting.get();const order=orderSetting[view.viewId()];for(let i=0;order&&i<tabIds.length;++i){if(orderSetting[tabIds[i]]&&orderSetting[tabIds[i]]>order){index=i;break;}}}else if(insertBefore){for(let i=0;i<tabIds.length;++i){if(tabIds[i]===insertBefore.viewId()){index=i;break;}}}
this._appendTab(view,index);if(view.isCloseable()){const tabs=this._closeableTabSetting.get();const tabId=view.viewId();if(!tabs[tabId]){tabs[tabId]=true;this._closeableTabSetting.set(tabs);}}
this._persistTabOrder();}
showView(view,insertBefore,userGesture,omitFocus){this.appendView(view,insertBefore);this._tabbedPane.selectTab(view.viewId(),userGesture);if(!omitFocus)
this._tabbedPane.focus();const widget=(this._tabbedPane.tabView(view.viewId()));return widget._materialize();}
removeView(view){if(!this._tabbedPane.hasTab(view.viewId()))
return;delete view[UI.ViewManager._Location.symbol];this._manager._views.delete(view.viewId());this._tabbedPane.closeTab(view.viewId());this._views.delete(view.viewId());}
_tabSelected(event){const tabId=(event.data.tabId);if(this._lastSelectedTabSetting&&event.data['isUserGesture'])
this._lastSelectedTabSetting.set(tabId);}
_tabClosed(event){const id=(event.data['tabId']);const tabs=this._closeableTabSetting.get();if(tabs[id]){delete tabs[id];this._closeableTabSetting.set(tabs);}
this._views.get(id).disposeView();}
_persistTabOrder(){const tabIds=this._tabbedPane.tabIds();const tabOrders={};for(let i=0;i<tabIds.length;i++)
tabOrders[tabIds[i]]=(i+1)*UI.ViewManager._TabbedLocation.orderStep;const oldTabOrder=this._tabOrderSetting.get();const oldTabArray=Object.keys(oldTabOrder);oldTabArray.sort((a,b)=>oldTabOrder[a]-oldTabOrder[b]);let lastOrder=0;for(const key of oldTabArray){if(key in tabOrders){lastOrder=tabOrders[key];continue;}
tabOrders[key]=++lastOrder;}
this._tabOrderSetting.set(tabOrders);}};UI.ViewManager._TabbedLocation.orderStep=10;UI.ViewManager._StackLocation=class extends UI.ViewManager._Location{constructor(manager,revealCallback,location){const vbox=new UI.VBox();super(manager,vbox,revealCallback);this._vbox=vbox;this._expandableContainers=new Map();if(location)
this.appendApplicableItems(location);}
appendView(view,insertBefore){const oldLocation=view[UI.ViewManager._Location.symbol];if(oldLocation&&oldLocation!==this)
oldLocation.removeView(view);let container=this._expandableContainers.get(view.viewId());if(!container){view[UI.ViewManager._Location.symbol]=this;this._manager._views.set(view.viewId(),view);container=new UI.ViewManager._ExpandableContainerWidget(view);let beforeElement=null;if(insertBefore){const beforeContainer=insertBefore[UI.ViewManager._ExpandableContainerWidget._symbol];beforeElement=beforeContainer?beforeContainer.element:null;}
container.show(this._vbox.contentElement,beforeElement);this._expandableContainers.set(view.viewId(),container);}}
showView(view,insertBefore){this.appendView(view,insertBefore);const container=this._expandableContainers.get(view.viewId());return container._expand();}
removeView(view){const container=this._expandableContainers.get(view.viewId());if(!container)
return;container.detach();this._expandableContainers.delete(view.viewId());delete view[UI.ViewManager._Location.symbol];this._manager._views.delete(view.viewId());}
appendApplicableItems(locationName){for(const view of this._manager._viewsForLocation(locationName))
this.appendView(view);}};UI.viewManager;;UI.TreeOutline=class extends Common.Object{constructor(){super();this._createRootElement();this.selectedTreeElement=null;this.expandTreeElementsWhenArrowing=false;this._comparator=null;this.contentElement=this._rootElement._childrenListNode;this.contentElement.addEventListener('keydown',this._treeKeyDown.bind(this),false);this._preventTabOrder=false;this._showSelectionOnKeyboardFocus=false;this._focusable=true;this.setFocusable(this._focusable);if(this._focusable)
this.contentElement.setAttribute('tabIndex',-1);this.element=this.contentElement;UI.ARIAUtils.markAsTree(this.element);}
setShowSelectionOnKeyboardFocus(show,preventTabOrder){this.contentElement.classList.toggle('hide-selection-when-blurred',show);this._preventTabOrder=!!preventTabOrder;this._showSelectionOnKeyboardFocus=show;}
_createRootElement(){this._rootElement=new UI.TreeElement();this._rootElement.treeOutline=this;this._rootElement.root=true;this._rootElement.selectable=false;this._rootElement.expanded=true;this._rootElement._childrenListNode.classList.remove('children');}
rootElement(){return this._rootElement;}
firstChild(){return this._rootElement.firstChild();}
_lastDescendent(){let last=this._rootElement.lastChild();while(last.expanded&&last.childCount())
last=last.lastChild();return last;}
appendChild(child){this._rootElement.appendChild(child);}
insertChild(child,index){this._rootElement.insertChild(child,index);}
removeChild(child){this._rootElement.removeChild(child);}
removeChildren(){this._rootElement.removeChildren();}
treeElementFromPoint(x,y){const node=this.contentElement.ownerDocument.deepElementFromPoint(x,y);if(!node)
return null;const listNode=node.enclosingNodeOrSelfWithNodeNameInArray(['ol','li']);if(listNode)
return listNode.parentTreeElement||listNode.treeElement;return null;}
treeElementFromEvent(event){return event?this.treeElementFromPoint(event.pageX,event.pageY):null;}
setComparator(comparator){this._comparator=comparator;}
setFocusable(focusable){if(focusable){this._focusable=true;this.contentElement.setAttribute('tabIndex',-1);if(this.selectedTreeElement)
this.selectedTreeElement._setFocusable(true);}else{this._focusable=false;this.contentElement.removeAttribute('tabIndex');if(this.selectedTreeElement)
this.selectedTreeElement._setFocusable(false);}}
focus(){if(this.selectedTreeElement)
this.selectedTreeElement.listItemElement.focus();else
this.contentElement.focus();}
useLightSelectionColor(){this._useLightSelectionColor=true;}
_bindTreeElement(element){if(element.treeOutline)
console.error('Binding element for the second time: '+new Error().stack);element.treeOutline=this;element.onbind();}
_unbindTreeElement(element){if(!element.treeOutline)
console.error('Unbinding element that was not bound: '+new Error().stack);element.deselect();element.onunbind();element.treeOutline=null;}
selectPrevious(){let nextSelectedElement=this.selectedTreeElement.traversePreviousTreeElement(true);while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.traversePreviousTreeElement(!this.expandTreeElementsWhenArrowing);if(!nextSelectedElement)
return false;nextSelectedElement.select(false,true);return true;}
selectNext(){let nextSelectedElement=this.selectedTreeElement.traverseNextTreeElement(true);while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.traverseNextTreeElement(!this.expandTreeElementsWhenArrowing);if(!nextSelectedElement)
return false;nextSelectedElement.select(false,true);return true;}
forceSelect(){if(this.selectedTreeElement)
this.selectedTreeElement.deselect();this._selectFirst();}
_selectFirst(){let first=this.firstChild();while(first&&!first.selectable)
first=first.traverseNextTreeElement(true);if(!first)
return false;first.select(false,true);return true;}
_selectLast(){let last=this._lastDescendent();while(last&&!last.selectable)
last=last.traversePreviousTreeElement(true);if(!last)
return false;last.select(false,true);return true;}
_treeKeyDown(event){if(!this.selectedTreeElement||event.shiftKey||event.metaKey||event.ctrlKey||UI.isEditing())
return;let handled=false;if(event.key==='ArrowUp'&&!event.altKey){handled=this.selectPrevious();}else if(event.key==='ArrowDown'&&!event.altKey){handled=this.selectNext();}else if(event.key==='ArrowLeft'){handled=this.selectedTreeElement.collapseOrAscend(event.altKey);}else if(event.key==='ArrowRight'){if(!this.selectedTreeElement.revealed()){this.selectedTreeElement.reveal();handled=true;}else{handled=this.selectedTreeElement.descendOrExpand(event.altKey);}}else if(event.keyCode===8||event.keyCode===46){handled=this.selectedTreeElement.ondelete();}else if(isEnterKey(event)){handled=this.selectedTreeElement.onenter();}else if(event.keyCode===UI.KeyboardShortcut.Keys.Space.code){handled=this.selectedTreeElement.onspace();}else if(event.key==='Home'){handled=this._selectFirst();}else if(event.key==='End'){handled=this._selectLast();}
if(handled)
event.consume(true);}
_deferredScrollIntoView(treeElement,center){if(!this._treeElementToScrollIntoView)
this.element.window().requestAnimationFrame(deferredScrollIntoView.bind(this));this._treeElementToScrollIntoView=treeElement;this._centerUponScrollIntoView=center;function deferredScrollIntoView(){this._treeElementToScrollIntoView.listItemElement.scrollIntoViewIfNeeded(this._centerUponScrollIntoView);delete this._treeElementToScrollIntoView;delete this._centerUponScrollIntoView;}}};UI.TreeOutline.Events={ElementAttached:Symbol('ElementAttached'),ElementExpanded:Symbol('ElementExpanded'),ElementCollapsed:Symbol('ElementCollapsed'),ElementSelected:Symbol('ElementSelected')};UI.TreeOutlineInShadow=class extends UI.TreeOutline{constructor(){super();this.contentElement.classList.add('tree-outline');this.element=createElement('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/treeoutline.css');this._disclosureElement=this._shadowRoot.createChild('div','tree-outline-disclosure');this._disclosureElement.appendChild(this.contentElement);this._renderSelection=true;}
registerRequiredCSS(cssFile){UI.appendStyle(this._shadowRoot,cssFile);}
hideOverflow(){this._disclosureElement.classList.add('tree-outline-disclosure-hide-overflow');}
makeDense(){this.contentElement.classList.add('tree-outline-dense');}};UI.TreeElement=class{constructor(title,expandable){this.treeOutline=null;this.parent=null;this.previousSibling=null;this.nextSibling=null;this._boundOnFocus=this._onFocus.bind(this);this._boundOnBlur=this._onBlur.bind(this);this._listItemNode=createElement('li');this._titleElement=this._listItemNode.createChild('span','tree-element-title');this._listItemNode.treeElement=this;if(title)
this.title=title;this._listItemNode.addEventListener('mousedown',this._handleMouseDown.bind(this),false);this._listItemNode.addEventListener('click',this._treeElementToggled.bind(this),false);this._listItemNode.addEventListener('dblclick',this._handleDoubleClick.bind(this),false);UI.ARIAUtils.markAsTreeitem(this._listItemNode);this._childrenListNode=createElement('ol');this._childrenListNode.parentTreeElement=this;this._childrenListNode.classList.add('children');UI.ARIAUtils.markAsGroup(this._childrenListNode);this._hidden=false;this._selectable=true;this.expanded=false;this.selected=false;this.setExpandable(expandable||false);this._collapsible=true;}
hasAncestor(ancestor){if(!ancestor)
return false;let currentNode=this.parent;while(currentNode){if(ancestor===currentNode)
return true;currentNode=currentNode.parent;}
return false;}
hasAncestorOrSelf(ancestor){return this===ancestor||this.hasAncestor(ancestor);}
children(){return this._children||[];}
childCount(){return this._children?this._children.length:0;}
firstChild(){return this._children?this._children[0]:null;}
lastChild(){return this._children?this._children[this._children.length-1]:null;}
childAt(index){return this._children?this._children[index]:null;}
indexOfChild(child){return this._children?this._children.indexOf(child):-1;}
appendChild(child){if(!this._children)
this._children=[];let insertionIndex;if(this.treeOutline&&this.treeOutline._comparator)
insertionIndex=this._children.lowerBound(child,this.treeOutline._comparator);else
insertionIndex=this._children.length;this.insertChild(child,insertionIndex);}
insertChild(child,index){if(!this._children)
this._children=[];if(!child)
throw'child can\'t be undefined or null';console.assert(!child.parent,'Attempting to insert a child that is already in the tree, reparenting is not supported.');const previousChild=(index>0?this._children[index-1]:null);if(previousChild){previousChild.nextSibling=child;child.previousSibling=previousChild;}else{child.previousSibling=null;}
const nextChild=this._children[index];if(nextChild){nextChild.previousSibling=child;child.nextSibling=nextChild;}else{child.nextSibling=null;}
this._children.splice(index,0,child);this.setExpandable(true);child.parent=this;if(this.treeOutline)
this.treeOutline._bindTreeElement(child);for(let current=child.firstChild();this.treeOutline&&current;current=current.traverseNextTreeElement(false,child,true))
this.treeOutline._bindTreeElement(current);child.onattach();child._ensureSelection();if(this.treeOutline)
this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementAttached,child);const nextSibling=child.nextSibling?child.nextSibling._listItemNode:null;this._childrenListNode.insertBefore(child._listItemNode,nextSibling);this._childrenListNode.insertBefore(child._childrenListNode,nextSibling);if(child.selected)
child.select();if(child.expanded)
child.expand();}
removeChildAtIndex(childIndex){if(childIndex<0||childIndex>=this._children.length)
throw'childIndex out of range';const child=this._children[childIndex];this._children.splice(childIndex,1);const parent=child.parent;if(this.treeOutline&&this.treeOutline.selectedTreeElement&&this.treeOutline.selectedTreeElement.hasAncestorOrSelf(child)){if(child.nextSibling)
child.nextSibling.select(true);else if(child.previousSibling)
child.previousSibling.select(true);else if(parent)
parent.select(true);}
if(child.previousSibling)
child.previousSibling.nextSibling=child.nextSibling;if(child.nextSibling)
child.nextSibling.previousSibling=child.previousSibling;child.parent=null;if(this.treeOutline)
this.treeOutline._unbindTreeElement(child);for(let current=child.firstChild();this.treeOutline&&current;current=current.traverseNextTreeElement(false,child,true))
this.treeOutline._unbindTreeElement(current);child._detach();}
removeChild(child){if(!child)
throw'child can\'t be undefined or null';if(child.parent!==this)
return;const childIndex=this._children.indexOf(child);if(childIndex===-1)
throw'child not found in this node\'s children';this.removeChildAtIndex(childIndex);}
removeChildren(){if(!this.root&&this.treeOutline&&this.treeOutline.selectedTreeElement&&this.treeOutline.selectedTreeElement.hasAncestorOrSelf(this))
this.select(true);for(let i=0;this._children&&i<this._children.length;++i){const child=this._children[i];child.previousSibling=null;child.nextSibling=null;child.parent=null;if(this.treeOutline)
this.treeOutline._unbindTreeElement(child);for(let current=child.firstChild();this.treeOutline&&current;current=current.traverseNextTreeElement(false,child,true))
this.treeOutline._unbindTreeElement(current);child._detach();}
this._children=[];}
get selectable(){if(this._hidden)
return false;return this._selectable;}
set selectable(x){this._selectable=x;}
get listItemElement(){return this._listItemNode;}
titleElement(){return this._titleElement;}
get childrenListElement(){return this._childrenListNode;}
get title(){return this._title;}
set title(x){if(this._title===x)
return;this._title=x;if(typeof x==='string'){this._titleElement.textContent=x;this.tooltip=x;}else{this._titleElement=x;this.tooltip='';}
this._listItemNode.removeChildren();if(this._leadingIconsElement)
this._listItemNode.appendChild(this._leadingIconsElement);this._listItemNode.appendChild(this._titleElement);if(this._trailingIconsElement)
this._listItemNode.appendChild(this._trailingIconsElement);this._ensureSelection();}
titleAsText(){if(!this._title)
return'';if(typeof this._title==='string')
return this._title;return this._title.textContent;}
startEditingTitle(editingConfig){UI.InplaceEditor.startEditing(this._titleElement,editingConfig);this.treeOutline._shadowRoot.getSelection().selectAllChildren(this._titleElement);}
setLeadingIcons(icons){if(!this._leadingIconsElement&&!icons.length)
return;if(!this._leadingIconsElement){this._leadingIconsElement=createElementWithClass('div','leading-icons');this._leadingIconsElement.classList.add('icons-container');this._listItemNode.insertBefore(this._leadingIconsElement,this._titleElement);this._ensureSelection();}
this._leadingIconsElement.removeChildren();for(const icon of icons)
this._leadingIconsElement.appendChild(icon);}
setTrailingIcons(icons){if(!this._trailingIconsElement&&!icons.length)
return;if(!this._trailingIconsElement){this._trailingIconsElement=createElementWithClass('div','trailing-icons');this._trailingIconsElement.classList.add('icons-container');this._listItemNode.appendChild(this._trailingIconsElement);this._ensureSelection();}
this._trailingIconsElement.removeChildren();for(const icon of icons)
this._trailingIconsElement.appendChild(icon);}
get tooltip(){return this._tooltip||'';}
set tooltip(x){if(this._tooltip===x)
return;this._tooltip=x;this._listItemNode.title=x;}
isExpandable(){return this._expandable;}
setExpandable(expandable){if(this._expandable===expandable)
return;this._expandable=expandable;this._listItemNode.classList.toggle('parent',expandable);if(!expandable){this.collapse();UI.ARIAUtils.unsetExpanded(this._listItemNode);}else{UI.ARIAUtils.setExpanded(this._listItemNode,false);}}
setCollapsible(collapsible){if(this._collapsible===collapsible)
return;this._collapsible=collapsible;this._listItemNode.classList.toggle('always-parent',!collapsible);if(!collapsible)
this.expand();}
get hidden(){return this._hidden;}
set hidden(x){if(this._hidden===x)
return;this._hidden=x;this._listItemNode.classList.toggle('hidden',x);this._childrenListNode.classList.toggle('hidden',x);}
invalidateChildren(){if(this._children){this.removeChildren();this._children=null;}}
_ensureSelection(){if(!this.treeOutline||!this.treeOutline._renderSelection)
return;if(!this._selectionElement)
this._selectionElement=createElementWithClass('div','selection fill');this._listItemNode.insertBefore(this._selectionElement,this.listItemElement.firstChild);}
_treeElementToggled(event){const element=event.currentTarget;if(element.treeElement!==this||element.hasSelection())
return;console.assert(!!this.treeOutline);const showSelectionOnKeyboardFocus=this.treeOutline?this.treeOutline._showSelectionOnKeyboardFocus:false;const toggleOnClick=this.toggleOnClick&&(showSelectionOnKeyboardFocus||!this.selectable);const isInTriangle=this.isEventWithinDisclosureTriangle(event);if(!toggleOnClick&&!isInTriangle)
return;if(this.expanded){if(event.altKey)
this.collapseRecursively();else
this.collapse();}else{if(event.altKey)
this.expandRecursively();else
this.expand();}
event.consume();}
_handleMouseDown(event){const element=event.currentTarget;if(!element)
return;if(!this.selectable)
return;if(element.treeElement!==this)
return;if(this.isEventWithinDisclosureTriangle(event))
return;this.selectOnMouseDown(event);}
_handleDoubleClick(event){const element=event.currentTarget;if(!element||element.treeElement!==this)
return;const handled=this.ondblclick(event);if(handled)
return;if(this._expandable&&!this.expanded)
this.expand();}
_detach(){this._listItemNode.remove();this._childrenListNode.remove();}
collapse(){if(!this.expanded||!this._collapsible)
return;this._listItemNode.classList.remove('expanded');this._childrenListNode.classList.remove('expanded');UI.ARIAUtils.setExpanded(this._listItemNode,false);this.expanded=false;this.oncollapse();if(this.treeOutline)
this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementCollapsed,this);}
collapseRecursively(){let item=this;while(item){if(item.expanded)
item.collapse();item=item.traverseNextTreeElement(false,this,true);}}
collapseChildren(){if(!this._children)
return;for(const child of this._children)
child.collapseRecursively();}
expand(){if(!this._expandable||(this.expanded&&this._children))
return;this.expanded=true;this._populateIfNeeded();this._listItemNode.classList.add('expanded');this._childrenListNode.classList.add('expanded');UI.ARIAUtils.setExpanded(this._listItemNode,true);if(this.treeOutline){this.onexpand();this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementExpanded,this);}}
expandRecursively(maxDepth){let item=this;const info={};let depth=0;if(isNaN(maxDepth))
maxDepth=3;while(item){if(depth<maxDepth)
item.expand();item=item.traverseNextTreeElement(false,this,(depth>=maxDepth),info);depth+=info.depthChange;}}
collapseOrAscend(altKey){if(this.expanded&&this._collapsible){if(altKey)
this.collapseRecursively();else
this.collapse();return true;}
if(!this.parent||this.parent.root)
return false;if(!this.parent.selectable){this.parent.collapse();return true;}
let nextSelectedElement=this.parent;while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.parent;if(!nextSelectedElement)
return false;nextSelectedElement.select(false,true);return true;}
descendOrExpand(altKey){if(!this._expandable)
return false;if(!this.expanded){if(altKey)
this.expandRecursively();else
this.expand();return true;}
let nextSelectedElement=this.firstChild();while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.nextSibling;if(!nextSelectedElement)
return false;nextSelectedElement.select(false,true);return true;}
reveal(center){let currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded)
currentAncestor.expand();currentAncestor=currentAncestor.parent;}
this.treeOutline._deferredScrollIntoView(this,!!center);}
revealed(){let currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded)
return false;currentAncestor=currentAncestor.parent;}
return true;}
selectOnMouseDown(event){if(this.select(false,true))
event.consume(true);if(this._listItemNode.draggable&&this._selectionElement){const marginLeft=this.treeOutline.element.getBoundingClientRect().left-this._listItemNode.getBoundingClientRect().left;this._selectionElement.style.setProperty('margin-left',marginLeft+'px');}}
select(omitFocus,selectedByUser){if(!this.treeOutline||!this.selectable||this.selected){if(!omitFocus)
this.listItemElement.focus();return false;}
const lastSelected=this.treeOutline.selectedTreeElement;this.treeOutline.selectedTreeElement=null;if(this.treeOutline._rootElement===this){if(lastSelected)
lastSelected.deselect();if(!omitFocus)
this.listItemElement.focus();return false;}
this.selected=true;this.treeOutline.selectedTreeElement=this;if(this.treeOutline._focusable)
this._setFocusable(true);if(!omitFocus||this.treeOutline.contentElement.hasFocus())
this.listItemElement.focus();this._listItemNode.classList.add('selected');this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementSelected,this);if(lastSelected)
lastSelected.deselect();return this.onselect(selectedByUser);}
_setFocusable(focusable){if(focusable){this._listItemNode.setAttribute('tabIndex',this.treeOutline&&this.treeOutline._preventTabOrder?-1:0);this._listItemNode.addEventListener('focus',this._boundOnFocus,false);this._listItemNode.addEventListener('blur',this._boundOnBlur,false);}else{this._listItemNode.removeAttribute('tabIndex');this._listItemNode.removeEventListener('focus',this._boundOnFocus,false);this._listItemNode.removeEventListener('blur',this._boundOnBlur,false);}}
_onFocus(){if(this.treeOutline._useLightSelectionColor)
return;if(!this.treeOutline.contentElement.classList.contains('hide-selection-when-blurred'))
this._listItemNode.classList.add('force-white-icons');}
_onBlur(){if(this.treeOutline._useLightSelectionColor)
return;if(!this.treeOutline.contentElement.classList.contains('hide-selection-when-blurred'))
this._listItemNode.classList.remove('force-white-icons');}
revealAndSelect(omitFocus){this.reveal(true);this.select(omitFocus);}
deselect(){const hadFocus=this._listItemNode.hasFocus();this.selected=false;this._listItemNode.classList.remove('selected');this._setFocusable(false);if(this.treeOutline&&this.treeOutline.selectedTreeElement===this){this.treeOutline.selectedTreeElement=null;if(hadFocus)
this.treeOutline.focus();}}
_populateIfNeeded(){if(this.treeOutline&&this._expandable&&!this._children){this._children=[];this.onpopulate();}}
onpopulate(){}
onenter(){return false;}
ondelete(){return false;}
onspace(){return false;}
onbind(){}
onunbind(){}
onattach(){}
onexpand(){}
oncollapse(){}
ondblclick(e){return false;}
onselect(selectedByUser){return false;}
traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate,info){if(!dontPopulate)
this._populateIfNeeded();if(info)
info.depthChange=0;let element=skipUnrevealed?(this.revealed()?this.firstChild():null):this.firstChild();if(element&&(!skipUnrevealed||(skipUnrevealed&&this.expanded))){if(info)
info.depthChange=1;return element;}
if(this===stayWithin)
return null;element=skipUnrevealed?(this.revealed()?this.nextSibling:null):this.nextSibling;if(element)
return element;element=this;while(element&&!element.root&&!(skipUnrevealed?(element.revealed()?element.nextSibling:null):element.nextSibling)&&element.parent!==stayWithin){if(info)
info.depthChange-=1;element=element.parent;}
if(!element||element.root)
return null;return(skipUnrevealed?(element.revealed()?element.nextSibling:null):element.nextSibling);}
traversePreviousTreeElement(skipUnrevealed,dontPopulate){let element=skipUnrevealed?(this.revealed()?this.previousSibling:null):this.previousSibling;if(!dontPopulate&&element)
element._populateIfNeeded();while(element&&(skipUnrevealed?(element.revealed()&&element.expanded?element.lastChild():null):element.lastChild())){if(!dontPopulate)
element._populateIfNeeded();element=(skipUnrevealed?(element.revealed()&&element.expanded?element.lastChild():null):element.lastChild());}
if(element)
return element;if(!this.parent||this.parent.root)
return null;return this.parent;}
isEventWithinDisclosureTriangle(event){const paddingLeftValue=window.getComputedStyle(this._listItemNode).paddingLeft;console.assert(paddingLeftValue.endsWith('px'));const computedLeftPadding=parseFloat(paddingLeftValue);const left=this._listItemNode.totalOffsetLeft()+computedLeftPadding;return event.pageX>=left&&event.pageX<=left+UI.TreeElement._ArrowToggleWidth&&this._expandable;}};UI.TreeElement._ArrowToggleWidth=10;(function(){const img=new Image();if(window.devicePixelRatio>1)
img.src='Images/treeoutlineTriangles_2x.png';else
img.src='Images/treeoutlineTriangles.png';UI.TreeElement._imagePreload=img;})();;UI.InspectorView=class extends UI.VBox{constructor(){super();UI.GlassPane.setContainer(this.element);this.setMinimumSize(240,72);this._drawerSplitWidget=new UI.SplitWidget(false,true,'Inspector.drawerSplitViewState',200,200);this._drawerSplitWidget.hideSidebar();this._drawerSplitWidget.hideDefaultResizer();this._drawerSplitWidget.enableShowModeSaving();this._drawerSplitWidget.show(this.element);if(Runtime.experiments.isEnabled('splitInDrawer')){this._innerDrawerSplitWidget=new UI.SplitWidget(true,true,'Inspector.drawerSidebarSplitViewState',200,200);this._drawerSplitWidget.setSidebarWidget(this._innerDrawerSplitWidget);this._drawerSidebarTabbedLocation=UI.viewManager.createTabbedLocation(this._showDrawer.bind(this,false),'drawer-sidebar',true,true);this._drawerSidebarTabbedPane=this._drawerSidebarTabbedLocation.tabbedPane();this._drawerSidebarTabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._drawerTabSelected,this);this._innerDrawerSplitWidget.setSidebarWidget(this._drawerSidebarTabbedPane);}
this._drawerTabbedLocation=UI.viewManager.createTabbedLocation(this._showDrawer.bind(this,false),'drawer-view',true,true);const moreTabsButton=this._drawerTabbedLocation.enableMoreTabsButton();moreTabsButton.setTitle(ls`More Tools`);this._drawerTabbedPane=this._drawerTabbedLocation.tabbedPane();this._drawerTabbedPane.setMinimumSize(0,27);const closeDrawerButton=new UI.ToolbarButton(Common.UIString('Close drawer'),'largeicon-delete');closeDrawerButton.addEventListener(UI.ToolbarButton.Events.Click,this._closeDrawer,this);this._drawerSplitWidget.installResizer(this._drawerTabbedPane.headerElement());this._drawerTabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._drawerTabSelected,this);if(this._drawerSidebarTabbedPane){this._innerDrawerSplitWidget.setMainWidget(this._drawerTabbedPane);this._drawerSidebarTabbedPane.rightToolbar().appendToolbarItem(closeDrawerButton);this._drawerSplitWidget.installResizer(this._drawerSidebarTabbedPane.headerElement());}else{this._drawerSplitWidget.setSidebarWidget(this._drawerTabbedPane);this._drawerTabbedPane.rightToolbar().appendToolbarItem(closeDrawerButton);}
this._tabbedLocation=UI.viewManager.createTabbedLocation(InspectorFrontendHost.bringToFront.bind(InspectorFrontendHost),'panel',true,true,Runtime.queryParam('panel'));this._tabbedPane=this._tabbedLocation.tabbedPane();this._tabbedPane.registerRequiredCSS('ui/inspectorViewTabbedPane.css');this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);this._tabbedPane.setAccessibleName(Common.UIString('Panels'));Host.userMetrics.setLaunchPanel(this._tabbedPane.selectedTabId);if(Host.isUnderTest())
this._tabbedPane.setAutoSelectFirstItemOnShow(false);this._drawerSplitWidget.setMainWidget(this._tabbedPane);this._keyDownBound=this._keyDown.bind(this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ShowPanel,showPanel.bind(this));function showPanel(event){const panelName=(event.data);this.showPanel(panelName);}}
static instance(){return(self.runtime.sharedInstance(UI.InspectorView));}
wasShown(){this.element.ownerDocument.addEventListener('keydown',this._keyDownBound,false);}
willHide(){this.element.ownerDocument.removeEventListener('keydown',this._keyDownBound,false);}
resolveLocation(locationName){if(locationName==='drawer-view')
return this._drawerTabbedLocation;if(locationName==='panel')
return this._tabbedLocation;if(locationName==='drawer-sidebar')
return this._drawerSidebarTabbedLocation;return null;}
createToolbars(){this._tabbedPane.leftToolbar().appendItemsAtLocation('main-toolbar-left');this._tabbedPane.rightToolbar().appendItemsAtLocation('main-toolbar-right');}
addPanel(view){this._tabbedLocation.appendView(view);}
hasPanel(panelName){return this._tabbedPane.hasTab(panelName);}
panel(panelName){return(UI.viewManager.view(panelName).widget());}
onSuspendStateChanged(allTargetsSuspended){this._currentPanelLocked=allTargetsSuspended;this._tabbedPane.setCurrentTabLocked(this._currentPanelLocked);this._tabbedPane.leftToolbar().setEnabled(!this._currentPanelLocked);this._tabbedPane.rightToolbar().setEnabled(!this._currentPanelLocked);}
canSelectPanel(panelName){return!this._currentPanelLocked||this._tabbedPane.selectedTabId===panelName;}
showPanel(panelName){return UI.viewManager.showView(panelName);}
setPanelIcon(panelName,icon){this._tabbedPane.setTabIcon(panelName,icon);}
currentPanelDeprecated(){return(UI.viewManager.materializedWidget(this._tabbedPane.selectedTabId||''));}
_showDrawer(focus){if(this._drawerTabbedPane.isShowing())
return;this._drawerSplitWidget.showBoth();if(focus)
this._focusRestorer=new UI.WidgetFocusRestorer(this._drawerTabbedPane);else
this._focusRestorer=null;}
drawerVisible(){return this._drawerTabbedPane.isShowing();}
_closeDrawer(){if(!this._drawerTabbedPane.isShowing())
return;if(this._focusRestorer)
this._focusRestorer.restore();this._drawerSplitWidget.hideSidebar(true);}
setDrawerMinimized(minimized){this._drawerSplitWidget.setSidebarMinimized(minimized);this._drawerSplitWidget.setResizable(!minimized);}
isDrawerMinimized(){return this._drawerSplitWidget.isSidebarMinimized();}
closeDrawerTab(id,userGesture){this._drawerTabbedPane.closeTab(id,userGesture);}
_keyDown(event){const keyboardEvent=(event);if(!UI.KeyboardShortcut.eventHasCtrlOrMeta(keyboardEvent)||event.altKey||event.shiftKey)
return;const panelShortcutEnabled=Common.moduleSetting('shortcutPanelSwitch').get();if(panelShortcutEnabled){let panelIndex=-1;if(event.keyCode>0x30&&event.keyCode<0x3A)
panelIndex=event.keyCode-0x31;else if(event.keyCode>0x60&&event.keyCode<0x6A&&keyboardEvent.location===KeyboardEvent.DOM_KEY_LOCATION_NUMPAD)
panelIndex=event.keyCode-0x61;if(panelIndex!==-1){const panelName=this._tabbedPane.tabIds()[panelIndex];if(panelName){if(!UI.Dialog.hasInstance()&&!this._currentPanelLocked)
this.showPanel(panelName);event.consume(true);}}}}
onResize(){UI.GlassPane.containerMoved(this.element);}
topResizerElement(){return this._tabbedPane.headerElement();}
toolbarItemResized(){this._tabbedPane.headerResized();}
_tabSelected(event){const tabId=(event.data['tabId']);Host.userMetrics.panelShown(tabId);}
_drawerTabSelected(event){const tabId=(event.data['tabId']);Host.userMetrics.drawerShown(tabId);}
setOwnerSplit(splitWidget){this._ownerSplitWidget=splitWidget;}
minimize(){if(this._ownerSplitWidget)
this._ownerSplitWidget.setSidebarMinimized(true);}
restore(){if(this._ownerSplitWidget)
this._ownerSplitWidget.setSidebarMinimized(false);}};UI.inspectorView;UI.InspectorView.ActionDelegate=class{handleAction(context,actionId){switch(actionId){case'main.toggle-drawer':if(UI.inspectorView.drawerVisible())
UI.inspectorView._closeDrawer();else
UI.inspectorView._showDrawer(true);return true;case'main.next-tab':UI.inspectorView._tabbedPane.selectNextTab();UI.inspectorView._tabbedPane.focus();return true;case'main.previous-tab':UI.inspectorView._tabbedPane.selectPrevTab();UI.inspectorView._tabbedPane.focus();return true;}
return false;}};;UI.ActionRegistry=class{constructor(){this._actionsById=new Map();this._registerActions();}
_registerActions(){self.runtime.extensions('action').forEach(registerExtension,this);function registerExtension(extension){if(!extension.canInstantiate())
return;const actionId=extension.descriptor()['actionId'];console.assert(actionId);console.assert(!this._actionsById.get(actionId));const action=new UI.Action(extension);if(!action.category()||action.title())
this._actionsById.set(actionId,action);else
console.error(`Category actions require a title for command menu: ${actionId}`);}}
availableActions(){return this.applicableActions(this._actionsById.keysArray(),UI.context);}
applicableActions(actionIds,context){const extensions=[];actionIds.forEach(function(actionId){const action=this._actionsById.get(actionId);if(action)
extensions.push(action._extension);},this);return context.applicableExtensions(extensions).valuesArray().map(extensionToAction.bind(this));function extensionToAction(extension){return(this.action(extension.descriptor()['actionId']));}}
action(actionId){return this._actionsById.get(actionId)||null;}};UI.Action=class extends Common.Object{constructor(extension){super();this._extension=extension;this._enabled=true;this._toggled=false;}
id(){return this._extension.descriptor()['actionId'];}
execute(){return this._extension.instance().then(handleAction.bind(this));function handleAction(actionDelegate){const actionId=this._extension.descriptor()['actionId'];const delegate=(actionDelegate);return delegate.handleAction(UI.context,actionId);}}
icon(){return this._extension.descriptor()['iconClass']||'';}
toggledIcon(){return this._extension.descriptor()['toggledIconClass']||'';}
toggleWithRedColor(){return!!this._extension.descriptor()['toggleWithRedColor'];}
setEnabled(enabled){if(this._enabled===enabled)
return;this._enabled=enabled;this.dispatchEventToListeners(UI.Action.Events.Enabled,enabled);}
enabled(){return this._enabled;}
category(){return this._extension.descriptor()['category']||'';}
tags(){return this._extension.descriptor()['tags']||'';}
title(){let title=this._extension.title();const options=this._extension.descriptor()['options'];if(options){for(const pair of options){if(pair['value']!==this._toggled)
title=pair['title'];}}
return title;}
toggled(){return this._toggled;}
setToggled(toggled){if(this._toggled===toggled)
return;this._toggled=toggled;this.dispatchEventToListeners(UI.Action.Events.Toggled,toggled);}};UI.Action.Events={Enabled:Symbol('Enabled'),Toggled:Symbol('Toggled')};UI.ActionDelegate=function(){};UI.ActionDelegate.prototype={handleAction(context,actionId){}};UI.actionRegistry;;UI.ShortcutRegistry=class{constructor(actionRegistry,document){this._actionRegistry=actionRegistry;this._defaultKeyToActions=new Multimap();this._defaultActionToShortcut=new Multimap();this._registerBindings(document);}
_applicableActions(key){return this._actionRegistry.applicableActions(this._defaultActionsForKey(key).valuesArray(),UI.context);}
_defaultActionsForKey(key){return this._defaultKeyToActions.get(String(key));}
globalShortcutKeys(){const keys=[];for(const key of this._defaultKeyToActions.keysArray()){const actions=this._defaultKeyToActions.get(key).valuesArray();const applicableActions=this._actionRegistry.applicableActions(actions,new UI.Context());if(applicableActions.length)
keys.push(Number(key));}
return keys;}
shortcutDescriptorsForAction(actionId){return this._defaultActionToShortcut.get(actionId).valuesArray();}
keysForActions(actionIds){const result=[];for(let i=0;i<actionIds.length;++i){const descriptors=this.shortcutDescriptorsForAction(actionIds[i]);for(let j=0;j<descriptors.length;++j)
result.push(descriptors[j].key);}
return result;}
shortcutTitleForAction(actionId){const descriptors=this.shortcutDescriptorsForAction(actionId);if(descriptors.length)
return descriptors[0].name;}
handleShortcut(event){this.handleKey(UI.KeyboardShortcut.makeKeyFromEvent(event),event.key,event);}
eventMatchesAction(event,actionId){console.assert(this._defaultActionToShortcut.has(actionId),'Unknown action '+actionId);const key=UI.KeyboardShortcut.makeKeyFromEvent(event);return this._defaultActionToShortcut.get(actionId).valuesArray().some(descriptor=>descriptor.key===key);}
addShortcutListener(element,actionId,listener,capture){console.assert(this._defaultActionToShortcut.has(actionId),'Unknown action '+actionId);element.addEventListener('keydown',event=>{if(!this.eventMatchesAction((event),actionId)||!listener.call(null))
return;event.consume(true);},capture);}
async handleKey(key,domKey,event){const keyModifiers=key>>8;const actions=this._applicableActions(key);if(!actions.length||isPossiblyInputKey())
return;if(event)
event.consume(true);if(UI.Dialog.hasInstance())
return;for(const action of actions){if(await action.execute())
return;}
function isPossiblyInputKey(){if(!event||!UI.isEditing()||/^F\d+|Control|Shift|Alt|Meta|Escape|Win|U\+001B$/.test(domKey))
return false;if(!keyModifiers)
return true;const modifiers=UI.KeyboardShortcut.Modifiers;if(Host.isMac()){if(UI.KeyboardShortcut.makeKey('z',modifiers.Meta)===key)
return true;if(UI.KeyboardShortcut.makeKey('z',modifiers.Meta|modifiers.Shift)===key)
return true;}else{if(UI.KeyboardShortcut.makeKey('z',modifiers.Ctrl)===key)
return true;if(UI.KeyboardShortcut.makeKey('y',modifiers.Ctrl)===key)
return true;if(!Host.isWin()&&UI.KeyboardShortcut.makeKey('z',modifiers.Ctrl|modifiers.Shift)===key)
return true;}
if((keyModifiers&(modifiers.Ctrl|modifiers.Alt))===(modifiers.Ctrl|modifiers.Alt))
return Host.isWin();return!hasModifier(modifiers.Ctrl)&&!hasModifier(modifiers.Alt)&&!hasModifier(modifiers.Meta);}
function hasModifier(mod){return!!(keyModifiers&mod);}}
registerShortcut(actionId,shortcut){const descriptor=UI.KeyboardShortcut.makeDescriptorFromBindingShortcut(shortcut);if(!descriptor)
return;this._defaultActionToShortcut.set(actionId,descriptor);this._defaultKeyToActions.set(String(descriptor.key),actionId);}
_registerBindings(document){const extensions=self.runtime.extensions('action');extensions.forEach(registerExtension,this);function registerExtension(extension){const descriptor=extension.descriptor();const bindings=descriptor['bindings'];for(let i=0;bindings&&i<bindings.length;++i){if(!platformMatches(bindings[i].platform))
continue;const shortcuts=bindings[i]['shortcut'].split(/\s+/);shortcuts.forEach(this.registerShortcut.bind(this,descriptor['actionId']));}}
function platformMatches(platformsString){if(!platformsString)
return true;const platforms=platformsString.split(',');let isMatch=false;const currentPlatform=Host.platform();for(let i=0;!isMatch&&i<platforms.length;++i)
isMatch=platforms[i]===currentPlatform;return isMatch;}}};UI.ShortcutRegistry.ForwardedShortcut=class{};UI.ShortcutRegistry.ForwardedShortcut.instance=new UI.ShortcutRegistry.ForwardedShortcut();UI.shortcutRegistry;;UI.Context=class{constructor(){this._flavors=new Map();this._eventDispatchers=new Map();}
setFlavor(flavorType,flavorValue){const value=this._flavors.get(flavorType)||null;if(value===flavorValue)
return;if(flavorValue)
this._flavors.set(flavorType,flavorValue);else
this._flavors.remove(flavorType);this._dispatchFlavorChange(flavorType,flavorValue);}
_dispatchFlavorChange(flavorType,flavorValue){for(const extension of self.runtime.extensions(UI.ContextFlavorListener)){if(extension.hasContextType(flavorType)){extension.instance().then(instance=>(instance).flavorChanged(flavorValue));}}
const dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher)
return;dispatcher.dispatchEventToListeners(UI.Context.Events.FlavorChanged,flavorValue);}
addFlavorChangeListener(flavorType,listener,thisObject){let dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher){dispatcher=new Common.Object();this._eventDispatchers.set(flavorType,dispatcher);}
dispatcher.addEventListener(UI.Context.Events.FlavorChanged,listener,thisObject);}
removeFlavorChangeListener(flavorType,listener,thisObject){const dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher)
return;dispatcher.removeEventListener(UI.Context.Events.FlavorChanged,listener,thisObject);if(!dispatcher.hasEventListeners(UI.Context.Events.FlavorChanged))
this._eventDispatchers.remove(flavorType);}
flavor(flavorType){return this._flavors.get(flavorType)||null;}
flavors(){return new Set(this._flavors.keys());}
applicableExtensions(extensions){const targetExtensionSet=new Set();const availableFlavors=this.flavors();extensions.forEach(function(extension){if(self.runtime.isExtensionApplicableToContextTypes(extension,availableFlavors))
targetExtensionSet.add(extension);});return targetExtensionSet;}};UI.Context.Events={FlavorChanged:Symbol('FlavorChanged')};UI.ContextFlavorListener=function(){};UI.ContextFlavorListener.prototype={flavorChanged(object){}};UI.context=new UI.Context();;UI.ContextMenuItem=class{constructor(contextMenu,type,label,disabled,checked){this._type=type;this._label=label;this._disabled=disabled;this._checked=checked;this._contextMenu=contextMenu;if(type==='item'||type==='checkbox')
this._id=contextMenu?contextMenu._nextId():0;}
id(){return this._id;}
type(){return this._type;}
isEnabled(){return!this._disabled;}
setEnabled(enabled){this._disabled=!enabled;}
_buildDescriptor(){switch(this._type){case'item':const result={type:'item',id:this._id,label:this._label,enabled:!this._disabled};if(this._customElement)
result.element=this._customElement;if(this._shortcut)
result.shortcut=this._shortcut;return result;case'separator':return{type:'separator'};case'checkbox':return{type:'checkbox',id:this._id,label:this._label,checked:!!this._checked,enabled:!this._disabled};}
throw new Error('Invalid item type:'+this._type);}
setShortcut(shortcut){this._shortcut=shortcut;}};UI.ContextMenuSection=class{constructor(contextMenu){this._contextMenu=contextMenu;this._items=[];}
appendItem(label,handler,disabled){const item=new UI.ContextMenuItem(this._contextMenu,'item',label,disabled);this._items.push(item);this._contextMenu._setHandler(item.id(),handler);return item;}
appendCustomItem(element){const item=new UI.ContextMenuItem(this._contextMenu,'item','<custom>');item._customElement=element;this._items.push(item);return item;}
appendAction(actionId,label,optional){const action=UI.actionRegistry.action(actionId);if(!action){if(!optional)
console.error(`Action ${actionId} was not defined`);return;}
if(!label)
label=action.title();const result=this.appendItem(label,action.execute.bind(action));const shortcut=UI.shortcutRegistry.shortcutTitleForAction(actionId);if(shortcut)
result.setShortcut(shortcut);}
appendSubMenuItem(label,disabled){const item=new UI.ContextSubMenu(this._contextMenu,label,disabled);item._init();this._items.push(item);return item;}
appendCheckboxItem(label,handler,checked,disabled){const item=new UI.ContextMenuItem(this._contextMenu,'checkbox',label,disabled,checked);this._items.push(item);this._contextMenu._setHandler(item.id(),handler);return item;}};UI.ContextSubMenu=class extends UI.ContextMenuItem{constructor(contextMenu,label,disabled){super(contextMenu,'subMenu',label,disabled);this._sections=new Map();this._sectionList=[];}
_init(){UI.ContextMenu._groupWeights.forEach(name=>this.section(name));}
section(name){let section=name?this._sections.get(name):null;if(!section){section=new UI.ContextMenuSection(this._contextMenu);if(name){this._sections.set(name,section);this._sectionList.push(section);}else{this._sectionList.splice(UI.ContextMenu._groupWeights.indexOf('default'),0,section);}}
return section;}
headerSection(){return this.section('header');}
newSection(){return this.section('new');}
revealSection(){return this.section('reveal');}
clipboardSection(){return this.section('clipboard');}
editSection(){return this.section('edit');}
debugSection(){return this.section('debug');}
viewSection(){return this.section('view');}
defaultSection(){return this.section('default');}
saveSection(){return this.section('save');}
footerSection(){return this.section('footer');}
_buildDescriptor(){const result={type:'subMenu',label:this._label,enabled:!this._disabled,subItems:[]};const nonEmptySections=this._sectionList.filter(section=>!!section._items.length);for(const section of nonEmptySections){for(const item of section._items)
result.subItems.push(item._buildDescriptor());if(section!==nonEmptySections.peekLast())
result.subItems.push({type:'separator'});}
return result;}
appendItemsAtLocation(location){for(const extension of self.runtime.extensions('context-menu-item')){const itemLocation=extension.descriptor()['location']||'';if(!itemLocation.startsWith(location+'/'))
continue;const section=itemLocation.substr(location.length+1);if(!section||section.includes('/'))
continue;this.section(section).appendAction(extension.descriptor()['actionId']);}}};UI.ContextMenuItem._uniqueSectionName=0;UI.ContextMenu=class extends UI.ContextSubMenu{constructor(event,useSoftMenu,x,y){super(null);this._contextMenu=this;super._init();this._defaultSection=this.defaultSection();this._pendingPromises=[];this._pendingTargets=[];this._event=event;this._useSoftMenu=!!useSoftMenu;this._x=x===undefined?event.x:x;this._y=y===undefined?event.y:y;this._handlers={};this._id=0;const target=event.deepElementFromPoint();if(target)
this.appendApplicableItems((target));}
static initialize(){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetUseSoftMenu,setUseSoftMenu);function setUseSoftMenu(event){UI.ContextMenu._useSoftMenu=(event.data);}}
static installHandler(doc){doc.body.addEventListener('contextmenu',handler,false);function handler(event){const contextMenu=new UI.ContextMenu(event);contextMenu.show();}}
_nextId(){return this._id++;}
show(){Promise.all(this._pendingPromises).then(populate.bind(this)).then(this._innerShow.bind(this));UI.ContextMenu._pendingMenu=this;function populate(appendCallResults){if(UI.ContextMenu._pendingMenu!==this)
return;delete UI.ContextMenu._pendingMenu;for(let i=0;i<appendCallResults.length;++i){const providers=appendCallResults[i];const target=this._pendingTargets[i];for(let j=0;j<providers.length;++j){const provider=(providers[j]);provider.appendApplicableItems(this._event,this,target);}}
this._pendingPromises=[];this._pendingTargets=[];}
this._event.consume(true);}
discard(){if(this._softMenu)
this._softMenu.discard();}
_innerShow(){const menuObject=this._buildMenuDescriptors();if(this._useSoftMenu||UI.ContextMenu._useSoftMenu||InspectorFrontendHost.isHostedMode()){this._softMenu=new UI.SoftContextMenu(menuObject,this._itemSelected.bind(this));this._softMenu.show(this._event.target.ownerDocument,new AnchorBox(this._x,this._y,0,0));}else{InspectorFrontendHost.showContextMenuAtPoint(this._x,this._y,menuObject,this._event.target.ownerDocument);function listenToEvents(){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuCleared,this._menuCleared,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuItemSelected,this._onItemSelected,this);}
setImmediate(listenToEvents.bind(this));}}
_setHandler(id,handler){if(handler)
this._handlers[id]=handler;}
_buildMenuDescriptors(){return(super._buildDescriptor().subItems);}
_onItemSelected(event){this._itemSelected((event.data));}
_itemSelected(id){if(this._handlers[id])
this._handlers[id].call(this);this._menuCleared();}
_menuCleared(){InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.ContextMenuCleared,this._menuCleared,this);InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.ContextMenuItemSelected,this._onItemSelected,this);}
appendApplicableItems(target){this._pendingPromises.push(self.runtime.allInstances(UI.ContextMenu.Provider,target));this._pendingTargets.push(target);}};UI.ContextMenu._groupWeights=['header','new','reveal','edit','clipboard','debug','view','default','save','footer'];UI.ContextMenu.Provider=function(){};UI.ContextMenu.Provider.prototype={appendApplicableItems(event,contextMenu,target){}};;UI.GlassPane=class{constructor(){this._widget=new UI.Widget(true);this._widget.markAsRoot();this.element=this._widget.element;this.contentElement=this._widget.contentElement;this._arrowElement=UI.Icon.create('','arrow hidden');this.element.shadowRoot.appendChild(this._arrowElement);this.registerRequiredCSS('ui/glassPane.css');this.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.PierceGlassPane);this._onMouseDownBound=this._onMouseDown.bind(this);this._onClickOutsideCallback=null;this._maxSize=null;this._positionX=null;this._positionY=null;this._anchorBox=null;this._anchorBehavior=UI.GlassPane.AnchorBehavior.PreferTop;this._sizeBehavior=UI.GlassPane.SizeBehavior.SetExactSize;this._marginBehavior=UI.GlassPane.MarginBehavior.DefaultMargin;}
isShowing(){return this._widget.isShowing();}
registerRequiredCSS(cssFile){this._widget.registerRequiredCSS(cssFile);}
setDefaultFocusedElement(element){this._widget.setDefaultFocusedElement(element);}
setDimmed(dimmed){this.element.classList.toggle('dimmed-pane',dimmed);}
setPointerEventsBehavior(pointerEventsBehavior){this.element.classList.toggle('no-pointer-events',pointerEventsBehavior!==UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this.contentElement.classList.toggle('no-pointer-events',pointerEventsBehavior===UI.GlassPane.PointerEventsBehavior.PierceContents);}
setOutsideClickCallback(callback){this._onClickOutsideCallback=callback;}
setMaxContentSize(size){this._maxSize=size;this._positionContent();}
setSizeBehavior(sizeBehavior){this._sizeBehavior=sizeBehavior;this._positionContent();}
setContentPosition(x,y){this._positionX=x;this._positionY=y;this._positionContent();}
setContentAnchorBox(anchorBox){this._anchorBox=anchorBox;this._positionContent();}
setAnchorBehavior(behavior){this._anchorBehavior=behavior;}
setMarginBehavior(behavior){this._marginBehavior=behavior;this._arrowElement.classList.toggle('hidden',behavior!==UI.GlassPane.MarginBehavior.Arrow);}
show(document){if(this.isShowing())
return;this.element.style.zIndex=3000+1000*UI.GlassPane._panes.size;document.body.addEventListener('mousedown',this._onMouseDownBound,true);this._widget.show(document.body);UI.GlassPane._panes.add(this);this._positionContent();}
hide(){if(!this.isShowing())
return;UI.GlassPane._panes.delete(this);this.element.ownerDocument.body.removeEventListener('mousedown',this._onMouseDownBound,true);this._widget.detach();}
_onMouseDown(event){if(!this._onClickOutsideCallback)
return;const node=event.deepElementFromPoint();if(!node||this.contentElement.isSelfOrAncestor(node))
return;this._onClickOutsideCallback.call(null,event);}
_positionContent(){if(!this.isShowing())
return;const showArrow=this._marginBehavior===UI.GlassPane.MarginBehavior.Arrow;const gutterSize=showArrow?8:(this._marginBehavior===UI.GlassPane.MarginBehavior.NoMargin?0:3);const scrollbarSize=UI.measuredScrollbarWidth(this.element.ownerDocument);const arrowSize=10;const container=UI.GlassPane._containers.get((this.element.ownerDocument));if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){this.contentElement.positionAt(0,0);this.contentElement.style.width='';this.contentElement.style.maxWidth='';this.contentElement.style.height='';this.contentElement.style.maxHeight='';}
const containerWidth=container.offsetWidth;const containerHeight=container.offsetHeight;let width=containerWidth-gutterSize*2;let height=containerHeight-gutterSize*2;let positionX=gutterSize;let positionY=gutterSize;if(this._maxSize){width=Math.min(width,this._maxSize.width);height=Math.min(height,this._maxSize.height);}
if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){const measuredRect=this.contentElement.getBoundingClientRect();const widthOverflow=height<measuredRect.height?scrollbarSize:0;const heightOverflow=width<measuredRect.width?scrollbarSize:0;width=Math.min(width,measuredRect.width+widthOverflow);height=Math.min(height,measuredRect.height+heightOverflow);}
if(this._anchorBox){const anchorBox=this._anchorBox.relativeToElement(container);let behavior=this._anchorBehavior;this._arrowElement.classList.remove('arrow-none','arrow-top','arrow-bottom','arrow-left','arrow-right');if(behavior===UI.GlassPane.AnchorBehavior.PreferTop||behavior===UI.GlassPane.AnchorBehavior.PreferBottom){const top=anchorBox.y-2*gutterSize;const bottom=containerHeight-anchorBox.y-anchorBox.height-2*gutterSize;if(behavior===UI.GlassPane.AnchorBehavior.PreferTop&&top<height&&bottom>top)
behavior=UI.GlassPane.AnchorBehavior.PreferBottom;if(behavior===UI.GlassPane.AnchorBehavior.PreferBottom&&bottom<height&&top>bottom)
behavior=UI.GlassPane.AnchorBehavior.PreferTop;let arrowY;let enoughHeight=true;if(behavior===UI.GlassPane.AnchorBehavior.PreferTop){positionY=Math.max(gutterSize,anchorBox.y-height-gutterSize);const spaceTop=anchorBox.y-positionY-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(height>spaceTop){this._arrowElement.classList.add('arrow-none');enoughHeight=false;}}else{height=Math.min(height,spaceTop);}
this._arrowElement.setIconType('mediumicon-arrow-bottom');this._arrowElement.classList.add('arrow-bottom');arrowY=anchorBox.y-gutterSize;}else{positionY=anchorBox.y+anchorBox.height+gutterSize;const spaceBottom=containerHeight-positionY-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(height>spaceBottom){this._arrowElement.classList.add('arrow-none');positionY=containerHeight-gutterSize-height;enoughHeight=false;}}else{height=Math.min(height,spaceBottom);}
this._arrowElement.setIconType('mediumicon-arrow-top');this._arrowElement.classList.add('arrow-top');arrowY=anchorBox.y+anchorBox.height+gutterSize;}
positionX=Math.max(gutterSize,Math.min(anchorBox.x,containerWidth-width-gutterSize));if(!enoughHeight)
positionX=Math.min(positionX+arrowSize,containerWidth-width-gutterSize);else if(showArrow&&positionX-arrowSize>=gutterSize)
positionX-=arrowSize;width=Math.min(width,containerWidth-positionX-gutterSize);if(2*arrowSize>=width){this._arrowElement.classList.add('arrow-none');}else{let arrowX=anchorBox.x+Math.min(50,Math.floor(anchorBox.width/2));arrowX=Number.constrain(arrowX,positionX+arrowSize,positionX+width-arrowSize);this._arrowElement.positionAt(arrowX,arrowY,container);}}else{const left=anchorBox.x-2*gutterSize;const right=containerWidth-anchorBox.x-anchorBox.width-2*gutterSize;if(behavior===UI.GlassPane.AnchorBehavior.PreferLeft&&left<width&&right>left)
behavior=UI.GlassPane.AnchorBehavior.PreferRight;if(behavior===UI.GlassPane.AnchorBehavior.PreferRight&&right<width&&left>right)
behavior=UI.GlassPane.AnchorBehavior.PreferLeft;let arrowX;let enoughWidth=true;if(behavior===UI.GlassPane.AnchorBehavior.PreferLeft){positionX=Math.max(gutterSize,anchorBox.x-width-gutterSize);const spaceLeft=anchorBox.x-positionX-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(width>spaceLeft){this._arrowElement.classList.add('arrow-none');enoughWidth=false;}}else{width=Math.min(width,spaceLeft);}
this._arrowElement.setIconType('mediumicon-arrow-right');this._arrowElement.classList.add('arrow-right');arrowX=anchorBox.x-gutterSize;}else{positionX=anchorBox.x+anchorBox.width+gutterSize;const spaceRight=containerWidth-positionX-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(width>spaceRight){this._arrowElement.classList.add('arrow-none');positionX=containerWidth-gutterSize-width;enoughWidth=false;}}else{width=Math.min(width,spaceRight);}
this._arrowElement.setIconType('mediumicon-arrow-left');this._arrowElement.classList.add('arrow-left');arrowX=anchorBox.x+anchorBox.width+gutterSize;}
positionY=Math.max(gutterSize,Math.min(anchorBox.y,containerHeight-height-gutterSize));if(!enoughWidth)
positionY=Math.min(positionY+arrowSize,containerHeight-height-gutterSize);else if(showArrow&&positionY-arrowSize>=gutterSize)
positionY-=arrowSize;height=Math.min(height,containerHeight-positionY-gutterSize);if(2*arrowSize>=height){this._arrowElement.classList.add('arrow-none');}else{let arrowY=anchorBox.y+Math.min(50,Math.floor(anchorBox.height/2));arrowY=Number.constrain(arrowY,positionY+arrowSize,positionY+height-arrowSize);this._arrowElement.positionAt(arrowX,arrowY,container);}}}else{positionX=this._positionX!==null?this._positionX:(containerWidth-width)/2;positionY=this._positionY!==null?this._positionY:(containerHeight-height)/2;width=Math.min(width,containerWidth-positionX-gutterSize);height=Math.min(height,containerHeight-positionY-gutterSize);this._arrowElement.classList.add('arrow-none');}
this.contentElement.style.width=width+'px';if(this._sizeBehavior===UI.GlassPane.SizeBehavior.SetExactWidthMaxHeight)
this.contentElement.style.maxHeight=height+'px';else
this.contentElement.style.height=height+'px';this.contentElement.positionAt(positionX,positionY,container);this._widget.doResize();}
widget(){return this._widget;}
static setContainer(element){UI.GlassPane._containers.set((element.ownerDocument),element);UI.GlassPane.containerMoved(element);}
static container(document){return UI.GlassPane._containers.get(document);}
static containerMoved(element){for(const pane of UI.GlassPane._panes){if(pane.isShowing()&&pane.element.ownerDocument===element.ownerDocument)
pane._positionContent();}}};UI.GlassPane.PointerEventsBehavior={BlockedByGlassPane:Symbol('BlockedByGlassPane'),PierceGlassPane:Symbol('PierceGlassPane'),PierceContents:Symbol('PierceContents')};UI.GlassPane.AnchorBehavior={PreferTop:Symbol('PreferTop'),PreferBottom:Symbol('PreferBottom'),PreferLeft:Symbol('PreferLeft'),PreferRight:Symbol('PreferRight'),};UI.GlassPane.SizeBehavior={SetExactSize:Symbol('SetExactSize'),SetExactWidthMaxHeight:Symbol('SetExactWidthMaxHeight'),MeasureContent:Symbol('MeasureContent')};UI.GlassPane.MarginBehavior={Arrow:Symbol('Arrow'),DefaultMargin:Symbol('DefaultMargin'),NoMargin:Symbol('NoMargin')};UI.GlassPane._containers=new Map();UI.GlassPane._panes=new Set();;UI.Dialog=class extends UI.GlassPane{constructor(){super();this.registerRequiredCSS('ui/dialog.css');this.contentElement.tabIndex=0;this.contentElement.addEventListener('focus',()=>this.widget().focus(),false);this.contentElement.addEventListener('keydown',this._onKeyDown.bind(this),false);this.widget().setDefaultFocusedElement(this.contentElement);this.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this.setOutsideClickCallback(event=>{this.hide();event.consume(true);});this._tabIndexMap=new Map();this._focusRestorer=null;this._closeOnEscape=true;}
static hasInstance(){return!!UI.Dialog._instance;}
show(where){const document=(where instanceof Document?where:(where||UI.inspectorView.element).ownerDocument);if(UI.Dialog._instance)
UI.Dialog._instance.hide();UI.Dialog._instance=this;this._disableTabIndexOnElements(document);super.show(document);this._focusRestorer=new UI.WidgetFocusRestorer(this.widget());}
hide(){this._focusRestorer.restore();super.hide();this._restoreTabIndexOnElements();delete UI.Dialog._instance;}
setCloseOnEscape(close){this._closeOnEscape=close;}
addCloseButton(){const closeButton=this.contentElement.createChild('div','dialog-close-button','dt-close-button');closeButton.gray=true;closeButton.addEventListener('click',()=>this.hide(),false);}
_disableTabIndexOnElements(document){this._tabIndexMap.clear();for(let node=document;node;node=node.traverseNextNode(document)){if(node instanceof HTMLElement){const element=(node);const tabIndex=element.tabIndex;if(tabIndex>=0){this._tabIndexMap.set(element,tabIndex);element.tabIndex=-1;}}}}
_restoreTabIndexOnElements(){for(const element of this._tabIndexMap.keys())
element.tabIndex=(this._tabIndexMap.get(element));this._tabIndexMap.clear();}
_onKeyDown(event){if(this._closeOnEscape&&event.keyCode===UI.KeyboardShortcut.Keys.Esc.code&&UI.KeyboardShortcut.hasNoModifiers(event)){event.consume(true);this.hide();}}};;UI.SyntaxHighlighter=class{constructor(mimeType,stripExtraWhitespace){this._mimeType=mimeType;this._stripExtraWhitespace=stripExtraWhitespace;}
createSpan(content,className){const span=createElement('span');span.className='cm-'+className;if(this._stripExtraWhitespace&&className!=='whitespace')
content=content.replace(/^[\n\r]*/,'').replace(/\s*$/,'');span.createTextChild(content);return span;}
syntaxHighlightNode(node){const lines=node.textContent.split('\n');let plainTextStart;let line;return self.runtime.extension(TextUtils.TokenizerFactory).instance().then(processTokens.bind(this));function processTokens(tokenizerFactory){node.removeChildren();const tokenize=tokenizerFactory.createTokenizer(this._mimeType);for(let i=0;i<lines.length;++i){line=lines[i];plainTextStart=0;tokenize(line,processToken.bind(this));if(plainTextStart<line.length){const plainText=line.substring(plainTextStart,line.length);node.createTextChild(plainText);}
if(i<lines.length-1)
node.createTextChild('\n');}}
function processToken(token,tokenType,column,newColumn){if(!tokenType)
return;if(column>plainTextStart){const plainText=line.substring(plainTextStart,column);node.createTextChild(plainText);}
node.appendChild(this.createSpan(token,tokenType));plainTextStart=newColumn;}}};;UI.DropTarget=class{constructor(element,transferTypes,messageText,handleDrop){element.addEventListener('dragenter',this._onDragEnter.bind(this),true);element.addEventListener('dragover',this._onDragOver.bind(this),true);this._element=element;this._transferTypes=transferTypes;this._messageText=messageText;this._handleDrop=handleDrop;this._enabled=true;}
setEnabled(enabled){this._enabled=enabled;}
_onDragEnter(event){if(this._enabled&&this._hasMatchingType(event))
event.consume(true);}
_hasMatchingType(event){for(const transferType of this._transferTypes){const found=Array.from(event.dataTransfer.items).find(item=>{return transferType.kind===item.kind&&!!transferType.type.exec(item.type);});if(found)
return true;}
return false;}
_onDragOver(event){if(!this._enabled||!this._hasMatchingType(event))
return;event.dataTransfer.dropEffect='copy';event.consume(true);if(this._dragMaskElement)
return;this._dragMaskElement=this._element.createChild('div','');const shadowRoot=UI.createShadowRootWithCoreStyles(this._dragMaskElement,'ui/dropTarget.css');shadowRoot.createChild('div','drop-target-message').textContent=this._messageText;this._dragMaskElement.addEventListener('drop',this._onDrop.bind(this),true);this._dragMaskElement.addEventListener('dragleave',this._onDragLeave.bind(this),true);}
_onDrop(event){event.consume(true);this._removeMask();if(this._enabled)
this._handleDrop(event.dataTransfer);}
_onDragLeave(event){event.consume(true);this._removeMask();}
_removeMask(){this._dragMaskElement.remove();delete this._dragMaskElement;}};UI.DropTarget.Type={URI:{kind:'string',type:/text\/uri-list/},Folder:{kind:'file',type:/$^/},File:{kind:'file',type:/.*/},WebFile:{kind:'file',type:/[\w]+/},ImageFile:{kind:'file',type:/image\/.*/},};;UI.EmptyWidget=class extends UI.VBox{constructor(text){super();this.registerRequiredCSS('ui/emptyWidget.css');this.element.classList.add('empty-view-scroller');this._contentElement=this.element.createChild('div','empty-view');this._textElement=this._contentElement.createChild('h2');this._textElement.textContent=text;}
appendParagraph(){return this._contentElement.createChild('p');}
appendLink(link){return this._contentElement.appendChild(UI.XLink.create(link,'Learn more'));}
set text(text){this._textElement.textContent=text;}};;UI.FilterBar=class extends UI.HBox{constructor(name,visibleByDefault){super();this.registerRequiredCSS('ui/filter.css');this._enabled=true;this.element.classList.add('filter-bar');this._stateSetting=Common.settings.createSetting('filterBar-'+name+'-toggled',!!visibleByDefault);this._filterButton=new UI.ToolbarSettingToggle(this._stateSetting,'largeicon-filter',Common.UIString('Filter'));this._filters=[];this._updateFilterBar();this._stateSetting.addChangeListener(this._updateFilterBar.bind(this));}
filterButton(){return this._filterButton;}
addFilter(filter){this._filters.push(filter);this.element.appendChild(filter.element());filter.addEventListener(UI.FilterUI.Events.FilterChanged,this._filterChanged,this);this._updateFilterButton();}
setEnabled(enabled){this._enabled=enabled;this._filterButton.setEnabled(enabled);this._updateFilterBar();}
forceShowFilterBar(){this._alwaysShowFilters=true;this._updateFilterBar();}
showOnce(){this._stateSetting.set(true);}
_filterChanged(event){this._updateFilterButton();}
wasShown(){super.wasShown();this._updateFilterBar();}
_updateFilterBar(){if(!this.parentWidget()||this._showingWidget)
return;if(this.visible()){this._showingWidget=true;this.showWidget();this._showingWidget=false;}else{this.hideWidget();}}
focus(){for(let i=0;i<this._filters.length;++i){if(this._filters[i]instanceof UI.TextFilterUI){const textFilterUI=(this._filters[i]);textFilterUI.focus();break;}}}
_updateFilterButton(){let isActive=false;for(const filter of this._filters)
isActive=isActive||filter.isActive();this._filterButton.setDefaultWithRedColor(isActive);this._filterButton.setToggleWithRedColor(isActive);}
clear(){this.element.removeChildren();this._filters=[];this._updateFilterButton();}
setting(){return this._stateSetting;}
visible(){return this._alwaysShowFilters||(this._stateSetting.get()&&this._enabled);}};UI.FilterUI=function(){};UI.FilterUI.Events={FilterChanged:Symbol('FilterChanged')};UI.FilterUI.prototype={isActive(){},element(){}};UI.TextFilterUI=class extends Common.Object{constructor(){super();this._filterElement=createElement('div');this._filterElement.className='filter-text-filter';this._filterInputElement=this._filterElement.createChild('span','filter-input-field');this._prompt=new UI.TextPrompt();this._prompt.initialize(this._completions.bind(this),' ');this._proxyElement=this._prompt.attach(this._filterInputElement);this._proxyElement.title=Common.UIString('e.g. /small[\\d]+/ url:a.com/b');this._prompt.setPlaceholder(Common.UIString('Filter'));this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._valueChanged.bind(this));this._suggestionProvider=null;}
_completions(expression,prefix,force){if(this._suggestionProvider)
return this._suggestionProvider(expression,prefix,force);return Promise.resolve([]);}
isActive(){return!!this._prompt.text();}
element(){return this._filterElement;}
value(){return this._prompt.textWithCurrentSuggestion();}
setValue(value){this._prompt.setText(value);this._valueChanged();}
focus(){this._filterInputElement.focus();}
setSuggestionProvider(suggestionProvider){this._prompt.clearAutocomplete();this._suggestionProvider=suggestionProvider;}
_valueChanged(){this.dispatchEventToListeners(UI.FilterUI.Events.FilterChanged,null);}};UI.NamedBitSetFilterUI=class extends Common.Object{constructor(items,setting){super();this._filtersElement=createElementWithClass('div','filter-bitset-filter');this._filtersElement.title=Common.UIString('%sClick to select multiple types',UI.KeyboardShortcut.shortcutToString('',UI.KeyboardShortcut.Modifiers.CtrlOrMeta));this._allowedTypes={};this._typeFilterElements={};this._addBit(UI.NamedBitSetFilterUI.ALL_TYPES,Common.UIString('All'));this._filtersElement.createChild('div','filter-bitset-filter-divider');for(let i=0;i<items.length;++i)
this._addBit(items[i].name,items[i].label,items[i].title);if(setting){this._setting=setting;setting.addChangeListener(this._settingChanged.bind(this));this._settingChanged();}else{this._toggleTypeFilter(UI.NamedBitSetFilterUI.ALL_TYPES,false);}}
reset(){this._toggleTypeFilter(UI.NamedBitSetFilterUI.ALL_TYPES,false);}
isActive(){return!this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES];}
element(){return this._filtersElement;}
accept(typeName){return!!this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]||!!this._allowedTypes[typeName];}
_settingChanged(){const allowedTypes=this._setting.get();this._allowedTypes={};for(const typeName in this._typeFilterElements){if(allowedTypes[typeName])
this._allowedTypes[typeName]=true;}
this._update();}
_update(){if((Object.keys(this._allowedTypes).length===0)||this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]){this._allowedTypes={};this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]=true;}
for(const typeName in this._typeFilterElements)
this._typeFilterElements[typeName].classList.toggle('selected',!!this._allowedTypes[typeName]);this.dispatchEventToListeners(UI.FilterUI.Events.FilterChanged,null);}
_addBit(name,label,title){const typeFilterElement=this._filtersElement.createChild('span',name);typeFilterElement.typeName=name;typeFilterElement.createTextChild(label);if(title)
typeFilterElement.title=title;typeFilterElement.addEventListener('click',this._onTypeFilterClicked.bind(this),false);this._typeFilterElements[name]=typeFilterElement;}
_onTypeFilterClicked(e){let toggle;if(Host.isMac())
toggle=e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey;else
toggle=e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey;this._toggleTypeFilter(e.target.typeName,toggle);}
_toggleTypeFilter(typeName,allowMultiSelect){if(allowMultiSelect&&typeName!==UI.NamedBitSetFilterUI.ALL_TYPES)
this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]=false;else
this._allowedTypes={};this._allowedTypes[typeName]=!this._allowedTypes[typeName];if(this._setting)
this._setting.set(this._allowedTypes);else
this._update();}};UI.NamedBitSetFilterUI.Item;UI.NamedBitSetFilterUI.ALL_TYPES='all';UI.CheckboxFilterUI=class extends Common.Object{constructor(className,title,activeWhenChecked,setting){super();this._filterElement=createElementWithClass('div','filter-checkbox-filter');this._activeWhenChecked=!!activeWhenChecked;this._label=UI.CheckboxLabel.create(title);this._filterElement.appendChild(this._label);this._checkboxElement=this._label.checkboxElement;if(setting)
UI.SettingsUI.bindCheckbox(this._checkboxElement,setting);else
this._checkboxElement.checked=true;this._checkboxElement.addEventListener('change',this._fireUpdated.bind(this),false);}
isActive(){return this._activeWhenChecked===this._checkboxElement.checked;}
checked(){return this._checkboxElement.checked;}
setChecked(checked){this._checkboxElement.checked=checked;}
element(){return this._filterElement;}
labelElement(){return this._label;}
_fireUpdated(){this.dispatchEventToListeners(UI.FilterUI.Events.FilterChanged,null);}
setColor(backgroundColor,borderColor){this._label.backgroundColor=backgroundColor;this._label.borderColor=borderColor;}};;UI.FilterSuggestionBuilder=class{constructor(keys,valueSorter){this._keys=keys;this._valueSorter=valueSorter||((key,result)=>result.sort());this._valuesMap=new Map();}
completions(expression,prefix,force){if(!prefix&&!force)
return Promise.resolve([]);const negative=prefix.startsWith('-');if(negative)
prefix=prefix.substring(1);const modifier=negative?'-':'';const valueDelimiterIndex=prefix.indexOf(':');const suggestions=[];if(valueDelimiterIndex===-1){const matcher=new RegExp('^'+prefix.escapeForRegExp(),'i');for(const key of this._keys){if(matcher.test(key))
suggestions.push({text:modifier+key+':'});}}else{const key=prefix.substring(0,valueDelimiterIndex).toLowerCase();const value=prefix.substring(valueDelimiterIndex+1);const matcher=new RegExp('^'+value.escapeForRegExp(),'i');const values=Array.from(this._valuesMap.get(key)||new Set());this._valueSorter(key,values);for(const item of values){if(matcher.test(item)&&(item!==value))
suggestions.push({text:modifier+key+':'+item});}}
return Promise.resolve(suggestions);}
addItem(key,value){if(!value)
return;if(!this._valuesMap.get(key))
this._valuesMap.set(key,(new Set()));this._valuesMap.get(key).add(value);}
clear(){this._valuesMap.clear();}};;UI.ForwardedInputEventHandler=class{constructor(){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.KeyEventUnhandled,this._onKeyEventUnhandled,this);}
_onKeyEventUnhandled(event){const data=event.data;const type=(data.type);const key=(data.key);const keyCode=(data.keyCode);const modifiers=(data.modifiers);if(type!=='keydown')
return;UI.context.setFlavor(UI.ShortcutRegistry.ForwardedShortcut,UI.ShortcutRegistry.ForwardedShortcut.instance);UI.shortcutRegistry.handleKey(UI.KeyboardShortcut.makeKey(keyCode,modifiers),key);UI.context.setFlavor(UI.ShortcutRegistry.ForwardedShortcut,null);}};UI.forwardedEventHandler=new UI.ForwardedInputEventHandler();;UI.Fragment=class{constructor(element){this._element=element;this._elementsById=new Map();}
element(){return this._element;}
$(elementId){return this._elementsById.get(elementId);}
static build(strings,...values){return UI.Fragment._render(UI.Fragment._template(strings),values);}
static cached(strings,...values){let template=UI.Fragment._templateCache.get(strings);if(!template){template=UI.Fragment._template(strings);UI.Fragment._templateCache.set(strings,template);}
return UI.Fragment._render(template,values);}
static _template(strings){let html='';let insideText=true;for(let i=0;i<strings.length-1;i++){html+=strings[i];const close=strings[i].lastIndexOf('>');const open=strings[i].indexOf('<',close+1);if(close!==-1&&open===-1)
insideText=true;else if(open!==-1)
insideText=false;html+=insideText?UI.Fragment._textMarker:UI.Fragment._attributeMarker(i);}
html+=strings[strings.length-1];const template=window.document.createElement('template');template.innerHTML=html;const walker=template.ownerDocument.createTreeWalker(template.content,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,null,false);let valueIndex=0;const emptyTextNodes=[];const binds=[];const nodesToMark=[];while(walker.nextNode()){const node=walker.currentNode;if(node.nodeType===Node.ELEMENT_NODE&&node.hasAttributes()){if(node.hasAttribute('$')){nodesToMark.push(node);binds.push({elementId:node.getAttribute('$')});node.removeAttribute('$');}
const attributesToRemove=[];for(let i=0;i<node.attributes.length;i++){const name=node.attributes[i].name;if(!UI.Fragment._attributeMarkerRegex.test(name)&&!UI.Fragment._attributeMarkerRegex.test(node.attributes[i].value))
continue;attributesToRemove.push(name);nodesToMark.push(node);const bind={attr:{index:valueIndex}};bind.attr.names=name.split(UI.Fragment._attributeMarkerRegex);valueIndex+=bind.attr.names.length-1;bind.attr.values=node.attributes[i].value.split(UI.Fragment._attributeMarkerRegex);valueIndex+=bind.attr.values.length-1;binds.push(bind);}
for(let i=0;i<attributesToRemove.length;i++)
node.removeAttribute(attributesToRemove[i]);}
if(node.nodeType===Node.TEXT_NODE&&node.data.indexOf(UI.Fragment._textMarker)!==-1){const texts=node.data.split(UI.Fragment._textMarkerRegex);node.data=texts[texts.length-1];for(let i=0;i<texts.length-1;i++){if(texts[i])
node.parentNode.insertBefore(createTextNode(texts[i]),node);const nodeToReplace=createElement('span');nodesToMark.push(nodeToReplace);binds.push({replaceNodeIndex:valueIndex++});node.parentNode.insertBefore(nodeToReplace,node);}}
if(node.nodeType===Node.TEXT_NODE&&(!node.previousSibling||node.previousSibling.nodeType===Node.ELEMENT_NODE)&&(!node.nextSibling||node.nextSibling.nodeType===Node.ELEMENT_NODE)&&/^\s*$/.test(node.data))
emptyTextNodes.push(node);}
for(let i=0;i<nodesToMark.length;i++)
nodesToMark[i].classList.add(UI.Fragment._class(i));for(const emptyTextNode of emptyTextNodes)
emptyTextNode.remove();return{template:template,binds:binds};}
static _render(template,values){const content=template.template.ownerDocument.importNode(template.template.content,true);const resultElement=(content.firstChild===content.lastChild?content.firstChild:content);const result=new UI.Fragment(resultElement);const boundElements=[];for(let i=0;i<template.binds.length;i++){const className=UI.Fragment._class(i);const element=(content.querySelector('.'+className));element.classList.remove(className);boundElements.push(element);}
for(let bindIndex=0;bindIndex<template.binds.length;bindIndex++){const bind=template.binds[bindIndex];const element=boundElements[bindIndex];if('elementId'in bind){result._elementsById.set((bind.elementId),element);}else if('replaceNodeIndex'in bind){const value=values[(bind.replaceNodeIndex)];element.parentNode.replaceChild(this._nodeForValue(value),element);}else if('attr'in bind){if(bind.attr.names.length===2&&bind.attr.values.length===1&&typeof values[bind.attr.index]==='function'){values[bind.attr.index].call(null,element);}else{let name=bind.attr.names[0];for(let i=1;i<bind.attr.names.length;i++){name+=values[bind.attr.index+i-1];name+=bind.attr.names[i];}
if(name){let value=bind.attr.values[0];for(let i=1;i<bind.attr.values.length;i++){value+=values[bind.attr.index+bind.attr.names.length-1+i-1];value+=bind.attr.values[i];}
element.setAttribute(name,value);}}}else{throw new Error('Unexpected bind');}}
return result;}
static _nodeForValue(value){if(value instanceof Node)
return value;if(value instanceof UI.Fragment)
return value._element;if(Array.isArray(value)){const node=createDocumentFragment();for(const v of value)
node.appendChild(this._nodeForValue(v));return node;}
return createTextNode(''+value);}};UI.Fragment._Template;UI.Fragment._Bind;UI.Fragment._textMarker='{{template-text}}';UI.Fragment._textMarkerRegex=/{{template-text}}/;UI.Fragment._attributeMarker=index=>'template-attribute'+index;UI.Fragment._attributeMarkerRegex=/template-attribute\d+/;UI.Fragment._class=index=>'template-class-'+index;UI.Fragment._templateCache=new Map();UI.html=(strings,...vararg)=>{return UI.Fragment.cached(strings,...vararg).element();};;UI.HistoryInput=class extends HTMLInputElement{constructor(){super();this._history=[''];this._historyPosition=0;this.addEventListener('keydown',this._onKeyDown.bind(this),false);this.addEventListener('input',this._onInput.bind(this),false);}
static create(){if(!UI.HistoryInput._constructor)
UI.HistoryInput._constructor=UI.registerCustomElement('input','history-input',UI.HistoryInput);return(UI.HistoryInput._constructor());}
_onInput(event){if(this._history.length===this._historyPosition+1)
this._history[this._history.length-1]=this.value;}
_onKeyDown(event){if(event.keyCode===UI.KeyboardShortcut.Keys.Up.code){this._historyPosition=Math.max(this._historyPosition-1,0);this.value=this._history[this._historyPosition];this.dispatchEvent(new Event('input',{'bubbles':true,'cancelable':true}));event.consume(true);}else if(event.keyCode===UI.KeyboardShortcut.Keys.Down.code){this._historyPosition=Math.min(this._historyPosition+1,this._history.length-1);this.value=this._history[this._historyPosition];this.dispatchEvent(new Event('input',{'bubbles':true,'cancelable':true}));event.consume(true);}else if(event.keyCode===UI.KeyboardShortcut.Keys.Enter.code){this._saveToHistory();}}
_saveToHistory(){if(this._history.length>1&&this._history[this._history.length-2]===this.value)
return;this._history[this._history.length-1]=this.value;this._historyPosition=this._history.length-1;this._history.push('');}};;UI.Icon=class extends HTMLSpanElement{constructor(){super();this._descriptor=null;this._spriteSheet=null;this._iconType='';}
static create(iconType,className){if(!UI.Icon._constructor)
UI.Icon._constructor=UI.registerCustomElement('span','ui-icon',UI.Icon);const icon=(UI.Icon._constructor());if(className)
icon.className=className;if(iconType)
icon.setIconType(iconType);return icon;}
setIconType(iconType){if(this._descriptor){this.style.removeProperty('--spritesheet-position');this.style.removeProperty('width');this.style.removeProperty('height');this._toggleClasses(false);this._iconType='';this._descriptor=null;this._spriteSheet=null;}
const descriptor=UI.Icon.Descriptors[iconType]||null;if(descriptor){this._iconType=iconType;this._descriptor=descriptor;this._spriteSheet=UI.Icon.SpriteSheets[this._descriptor.spritesheet];console.assert(this._spriteSheet,`ERROR: icon ${this._iconType} has unknown spritesheet: ${this._descriptor.spritesheet}`);this.style.setProperty('--spritesheet-position',this._propertyValue());this.style.setProperty('width',this._spriteSheet.cellWidth+'px');this.style.setProperty('height',this._spriteSheet.cellHeight+'px');this._toggleClasses(true);}else if(iconType){throw new Error(`ERROR: failed to find icon descriptor for type: ${iconType}`);}}
_toggleClasses(value){this.classList.toggle('spritesheet-'+this._descriptor.spritesheet,value);this.classList.toggle(this._iconType,value);this.classList.toggle('icon-mask',value&&!!this._descriptor.isMask);this.classList.toggle('icon-invert',value&&!!this._descriptor.invert);}
_propertyValue(){if(!this._descriptor.coordinates){if(!this._descriptor.position||!UI.Icon._positionRegex.test(this._descriptor.position))
throw new Error(`ERROR: icon '${this._iconType}' has malformed position: '${this._descriptor.position}'`);const column=this._descriptor.position[0].toLowerCase().charCodeAt(0)-97;const row=parseInt(this._descriptor.position.substring(1),10)-1;this._descriptor.coordinates={x:-(this._spriteSheet.cellWidth+this._spriteSheet.padding)*column,y:(this._spriteSheet.cellHeight+this._spriteSheet.padding)*(row+1)-this._spriteSheet.padding};}
return`${this._descriptor.coordinates.x}px ${this._descriptor.coordinates.y}px`;}};UI.Icon._positionRegex=/^[a-z][1-9][0-9]*$/;UI.Icon.Descriptor;UI.Icon.SpriteSheet;UI.Icon.SpriteSheets={'smallicons':{cellWidth:10,cellHeight:10,padding:10},'mediumicons':{cellWidth:16,cellHeight:16,padding:0},'largeicons':{cellWidth:28,cellHeight:24,padding:0},'arrowicons':{cellWidth:19,cellHeight:19,padding:0}};UI.Icon.Descriptors={'smallicon-bezier':{position:'a5',spritesheet:'smallicons',isMask:true},'smallicon-checkmark':{position:'b5',spritesheet:'smallicons'},'smallicon-checkmark-square':{position:'b6',spritesheet:'smallicons',isMask:true},'smallicon-checkmark-behind':{position:'d6',spritesheet:'smallicons',isMask:true},'smallicon-command-result':{position:'a4',spritesheet:'smallicons'},'smallicon-contrast-ratio':{position:'a6',spritesheet:'smallicons',isMask:true},'smallicon-cross':{position:'b4',spritesheet:'smallicons'},'smallicon-device':{position:'c5',spritesheet:'smallicons'},'smallicon-error':{position:'c4',spritesheet:'smallicons'},'smallicon-expand-less':{position:'f5',spritesheet:'smallicons',isMask:true},'smallicon-expand-more':{position:'e6',spritesheet:'smallicons',isMask:true},'smallicon-green-arrow':{position:'a3',spritesheet:'smallicons'},'smallicon-green-ball':{position:'b3',spritesheet:'smallicons'},'smallicon-info':{position:'c3',spritesheet:'smallicons'},'smallicon-inline-breakpoint-conditional':{position:'d4',spritesheet:'smallicons'},'smallicon-inline-breakpoint':{position:'d5',spritesheet:'smallicons'},'smallicon-no':{position:'c6',spritesheet:'smallicons',isMask:true},'smallicon-orange-ball':{position:'d3',spritesheet:'smallicons'},'smallicon-red-ball':{position:'a2',spritesheet:'smallicons'},'smallicon-shadow':{position:'b2',spritesheet:'smallicons',isMask:true},'smallicon-step-in':{position:'c2',spritesheet:'smallicons'},'smallicon-step-out':{position:'d2',spritesheet:'smallicons'},'smallicon-text-prompt':{position:'e5',spritesheet:'smallicons'},'smallicon-thick-left-arrow':{position:'e4',spritesheet:'smallicons'},'smallicon-thick-right-arrow':{position:'e3',spritesheet:'smallicons'},'smallicon-triangle-down':{position:'e2',spritesheet:'smallicons',isMask:true},'smallicon-triangle-right':{position:'a1',spritesheet:'smallicons',isMask:true},'smallicon-triangle-up':{position:'b1',spritesheet:'smallicons',isMask:true},'smallicon-user-command':{position:'c1',spritesheet:'smallicons'},'smallicon-warning':{position:'d1',spritesheet:'smallicons'},'smallicon-network-product':{position:'e1',spritesheet:'smallicons'},'smallicon-clear-warning':{position:'f1',spritesheet:'smallicons',isMask:true},'smallicon-clear-info':{position:'f2',spritesheet:'smallicons'},'smallicon-clear-error':{position:'f3',spritesheet:'smallicons'},'smallicon-account-circle':{position:'f4',spritesheet:'smallicons'},'mediumicon-clear-storage':{position:'a4',spritesheet:'mediumicons',isMask:true},'mediumicon-cookie':{position:'b4',spritesheet:'mediumicons',isMask:true},'mediumicon-database':{position:'c4',spritesheet:'mediumicons',isMask:true},'mediumicon-info':{position:'c1',spritesheet:'mediumicons',isMask:true},'mediumicon-manifest':{position:'d4',spritesheet:'mediumicons',isMask:true},'mediumicon-service-worker':{position:'a3',spritesheet:'mediumicons',isMask:true},'mediumicon-table':{position:'b3',spritesheet:'mediumicons',isMask:true},'mediumicon-arrow-in-circle':{position:'c3',spritesheet:'mediumicons',isMask:true},'mediumicon-file-sync':{position:'d3',spritesheet:'mediumicons',invert:true},'mediumicon-file':{position:'a2',spritesheet:'mediumicons',invert:true},'mediumicon-gray-cross-active':{position:'b2',spritesheet:'mediumicons'},'mediumicon-gray-cross-hover':{position:'c2',spritesheet:'mediumicons'},'mediumicon-red-cross-active':{position:'d2',spritesheet:'mediumicons'},'mediumicon-red-cross-hover':{position:'a1',spritesheet:'mediumicons'},'mediumicon-search':{position:'b1',spritesheet:'mediumicons'},'mediumicon-replace':{position:'c5',spritesheet:'mediumicons',isMask:true},'mediumicon-account-circle':{position:'e4',spritesheet:'medi
this._closeButton=this._contentElement.createChild('div','close-button','dt-close-button');this._closeButton.addEventListener('click',this.dispose.bind(this),false);this._closeCallback=null;}
static create(type,text,disableSetting){if(disableSetting&&disableSetting.get())
return null;return new UI.Infobar(type,text,disableSetting);}
dispose(){this.element.remove();this._onResize();if(this._closeCallback)
this._closeCallback.call(null);}
setText(text){this._mainRowText.textContent=text;this._onResize();}
setCloseCallback(callback){this._closeCallback=callback;}
setParentView(parentView){this._parentView=parentView;}
_onResize(){if(this._parentView)
this._parentView.doResize();}
_onDisable(){this._disableSetting.set(true);this.dispose();}
_onToggleDetails(){this._detailsRows.classList.remove('hidden');this._toggleElement.remove();this._onResize();}
createDetailsRowMessage(message){this._toggleElement.classList.remove('hidden');const infobarDetailsRow=this._detailsRows.createChild('div','infobar-details-row');const detailsRowMessage=infobarDetailsRow.createChild('span','infobar-row-message');detailsRowMessage.textContent=message||'';return detailsRowMessage;}};UI.Infobar.Type={Warning:'warning',Info:'info'};;UI.InplaceEditor=class{static startEditing(element,config){if(!UI.InplaceEditor._defaultInstance)
UI.InplaceEditor._defaultInstance=new UI.InplaceEditor();return UI.InplaceEditor._defaultInstance.startEditing(element,config);}
editorContent(editingContext){const element=editingContext.element;if(element.tagName==='INPUT'&&element.type==='text')
return element.value;return element.textContent;}
setUpEditor(editingContext){const element=editingContext.element;element.classList.add('editing');element.setAttribute('contenteditable','plaintext-only');const oldRole=element.getAttribute('role');UI.ARIAUtils.markAsTextBox(element);editingContext.oldRole=oldRole;const oldTabIndex=element.getAttribute('tabIndex');if(typeof oldTabIndex!=='number'||oldTabIndex<0)
element.tabIndex=0;this._focusRestorer=new UI.ElementFocusRestorer(element);editingContext.oldTabIndex=oldTabIndex;}
closeEditor(editingContext){const element=editingContext.element;element.classList.remove('editing');element.removeAttribute('contenteditable');if(typeof editingContext.oldRole!=='string')
element.removeAttribute('role');else
element.role=editingContext.oldRole;if(typeof editingContext.oldTabIndex!=='number')
element.removeAttribute('tabIndex');else
element.tabIndex=editingContext.oldTabIndex;element.scrollTop=0;element.scrollLeft=0;}
cancelEditing(editingContext){const element=editingContext.element;if(element.tagName==='INPUT'&&element.type==='text')
element.value=editingContext.oldText;else
element.textContent=editingContext.oldText;}
augmentEditingHandle(editingContext,handle){}
startEditing(element,config){if(!UI.markBeingEdited(element,true))
return null;config=config||new UI.InplaceEditor.Config(function(){},function(){});const editingContext={element:element,config:config};const committedCallback=config.commitHandler;const cancelledCallback=config.cancelHandler;const pasteCallback=config.pasteHandler;const context=config.context;let moveDirection='';const self=this;this.setUpEditor(editingContext);editingContext.oldText=this.editorContent(editingContext);function blurEventListener(e){if(config.blurHandler&&!config.blurHandler(element,e))
return;editingCommitted.call(element);}
function cleanUpAfterEditing(){UI.markBeingEdited(element,false);element.removeEventListener('blur',blurEventListener,false);element.removeEventListener('keydown',keyDownEventListener,true);if(pasteCallback)
element.removeEventListener('paste',pasteEventListener,true);if(self._focusRestorer)
self._focusRestorer.restore();self.closeEditor(editingContext);}
function editingCancelled(){self.cancelEditing(editingContext);cleanUpAfterEditing();cancelledCallback(this,context);}
function editingCommitted(){cleanUpAfterEditing();committedCallback(this,self.editorContent(editingContext),editingContext.oldText,context,moveDirection);}
function defaultFinishHandler(event){if(isEnterKey(event))
return'commit';else if(event.keyCode===UI.KeyboardShortcut.Keys.Esc.code||event.key==='Escape')
return'cancel';else if(event.key==='Tab')
return'move-'+(event.shiftKey?'backward':'forward');return'';}
function handleEditingResult(result,event){if(result==='commit'){editingCommitted.call(element);event.consume(true);}else if(result==='cancel'){editingCancelled.call(element);event.consume(true);}else if(result&&result.startsWith('move-')){moveDirection=result.substring(5);if(event.key==='Tab')
event.consume(true);blurEventListener();}}
function pasteEventListener(event){const result=pasteCallback(event);handleEditingResult(result,event);}
function keyDownEventListener(event){let result=defaultFinishHandler(event);if(!result&&config.postKeydownFinishHandler)
result=config.postKeydownFinishHandler(event);handleEditingResult(result,event);}
element.addEventListener('blur',blurEventListener,false);element.addEventListener('keydown',keyDownEventListener,true);if(pasteCallback)
element.addEventListener('paste',pasteEventListener,true);const handle={cancel:editingCancelled.bind(element),commit:editingCommitted.bind(element)};this.augmentEditingHandle(editingContext,handle);return handle;}};UI.InplaceEditor.Controller;UI.InplaceEditor.Config=class{constructor(commitHandler,cancelHandler,context,blurHandler){this.commitHandler=commitHandler;this.cancelHandler=cancelHandler;this.context=context;this.blurHandler=blurHandler;this.pasteHandler;this.postKeydownFinishHandler;}
setPasteHandler(pasteHandler){this.pasteHandler=pasteHandler;}
setPostKeydownFinishHandler(postKeydownFinishHandler){this.postKeydownFinishHandler=postKeydownFinishHandler;}};;UI.TextEditorFactory=function(){};UI.TextEditorFactory.prototype={createEditor(options){}};UI.TextEditor=function(){};UI.TextEditor.prototype={widget(){},fullRange(){},selection(){},setSelection(selection){},text(textRange){},textWithCurrentSuggestion(){},setText(text){},line(lineNumber){},newlineAndIndent(){},addKeyDownHandler(handler){},configureAutocomplete(config){},clearAutocomplete(){},visualCoordinates(lineNumber,columnNumber){},tokenAtTextPosition(lineNumber,columnNumber){},setPlaceholder(placeholder){}};UI.TextEditor.Events={CursorChanged:Symbol('CursorChanged'),TextChanged:Symbol('TextChanged'),SuggestionChanged:Symbol('SuggestionChanged')};UI.TextEditor.Options;UI.AutocompleteConfig;;UI.KeyboardShortcut=class{static makeKey(keyCode,modifiers){if(typeof keyCode==='string')
keyCode=keyCode.charCodeAt(0)-(/^[a-z]/.test(keyCode)?32:0);modifiers=modifiers||UI.KeyboardShortcut.Modifiers.None;return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode,modifiers);}
static makeKeyFromEvent(keyboardEvent){let modifiers=UI.KeyboardShortcut.Modifiers.None;if(keyboardEvent.shiftKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Shift;if(keyboardEvent.ctrlKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Ctrl;if(keyboardEvent.altKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Alt;if(keyboardEvent.metaKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Meta;const keyCode=keyboardEvent.keyCode||keyboardEvent['__keyCode'];return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode,modifiers);}
static makeKeyFromEventIgnoringModifiers(keyboardEvent){const keyCode=keyboardEvent.keyCode||keyboardEvent['__keyCode'];return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode,UI.KeyboardShortcut.Modifiers.None);}
static eventHasCtrlOrMeta(event){return Host.isMac()?event.metaKey&&!event.ctrlKey:event.ctrlKey&&!event.metaKey;}
static hasNoModifiers(event){return!event.ctrlKey&&!event.shiftKey&&!event.altKey&&!event.metaKey;}
static makeDescriptor(key,modifiers){return{key:UI.KeyboardShortcut.makeKey(typeof key==='string'?key:key.code,modifiers),name:UI.KeyboardShortcut.shortcutToString(key,modifiers)};}
static makeDescriptorFromBindingShortcut(shortcut){const parts=shortcut.split(/\+(?!$)/);let modifiers=0;let keyString;for(let i=0;i<parts.length;++i){if(typeof UI.KeyboardShortcut.Modifiers[parts[i]]!=='undefined'){modifiers|=UI.KeyboardShortcut.Modifiers[parts[i]];continue;}
console.assert(i===parts.length-1,'Only one key other than modifier is allowed in shortcut <'+shortcut+'>');keyString=parts[i];break;}
console.assert(keyString,'Modifiers-only shortcuts are not allowed (encountered <'+shortcut+'>)');if(!keyString)
return null;const key=UI.KeyboardShortcut.Keys[keyString]||UI.KeyboardShortcut.KeyBindings[keyString];if(key&&key.shiftKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Shift;return UI.KeyboardShortcut.makeDescriptor(key?key:keyString,modifiers);}
static shortcutToString(key,modifiers){return UI.KeyboardShortcut._modifiersToString(modifiers)+UI.KeyboardShortcut._keyName(key);}
static _keyName(key){if(typeof key==='string')
return key.toUpperCase();if(typeof key.name==='string')
return key.name;return key.name[Host.platform()]||key.name.other||'';}
static _makeKeyFromCodeAndModifiers(keyCode,modifiers){return(keyCode&255)|(modifiers<<8);}
static keyCodeAndModifiersFromKey(key){return{keyCode:key&255,modifiers:key>>8};}
static _modifiersToString(modifiers){const isMac=Host.isMac();const m=UI.KeyboardShortcut.Modifiers;const modifierNames=new Map([[m.Ctrl,isMac?'Ctrl\u2004':'Ctrl\u200A+\u200A'],[m.Alt,isMac?'\u2325\u2004':'Alt\u200A+\u200A'],[m.Shift,isMac?'\u21e7\u2004':'Shift\u200A+\u200A'],[m.Meta,isMac?'\u2318\u2004':'Win\u200A+\u200A']]);return[m.Meta,m.Ctrl,m.Alt,m.Shift].map(mapModifiers).join('');function mapModifiers(m){return modifiers&m?(modifierNames.get(m)):'';}}};UI.KeyboardShortcut.Modifiers={None:0,Shift:1,Ctrl:2,Alt:4,Meta:8,get CtrlOrMeta(){return Host.isMac()?this.Meta:this.Ctrl;},get ShiftOrOption(){return Host.isMac()?this.Alt:this.Shift;}};UI.KeyboardShortcut.Key;UI.KeyboardShortcut.Keys={Backspace:{code:8,name:'\u21a4'},Tab:{code:9,name:{mac:'\u21e5',other:'Tab'}},Enter:{code:13,name:{mac:'\u21a9',other:'Enter'}},Shift:{code:16,name:{mac:'\u21e7',other:'Shift'}},Ctrl:{code:17,name:'Ctrl'},Esc:{code:27,name:'Esc'},Space:{code:32,name:'Space'},PageUp:{code:33,name:{mac:'\u21de',other:'PageUp'}},PageDown:{code:34,name:{mac:'\u21df',other:'PageDown'}},End:{code:35,name:{mac:'\u2197',other:'End'}},Home:{code:36,name:{mac:'\u2196',other:'Home'}},Left:{code:37,name:'\u2190'},Up:{code:38,name:'\u2191'},Right:{code:39,name:'\u2192'},Down:{code:40,name:'\u2193'},Delete:{code:46,name:'Del'},Zero:{code:48,name:'0'},H:{code:72,name:'H'},N:{code:78,name:'N'},P:{code:80,name:'P'},Meta:{code:91,name:'Meta'},F1:{code:112,name:'F1'},F2:{code:113,name:'F2'},F3:{code:114,name:'F3'},F4:{code:115,name:'F4'},F5:{code:116,name:'F5'},F6:{code:117,name:'F6'},F7:{code:118,name:'F7'},F8:{code:119,name:'F8'},F9:{code:120,name:'F9'},F10:{code:121,name:'F10'},F11:{code:122,name:'F11'},F12:{code:123,name:'F12'},Semicolon:{code:186,name:';'},NumpadPlus:{code:107,name:'Numpad +'},NumpadMinus:{code:109,name:'Numpad -'},Numpad0:{code:96,name:'Numpad 0'},Plus:{code:187,name:'+'},Comma:{code:188,name:','},Minus:{code:189,name:'-'},Period:{code:190,name:'.'},Slash:{code:191,name:'/'},QuestionMark:{code:191,name:'?'},Apostrophe:{code:192,name:'`'},Tilde:{code:192,name:'Tilde'},LeftSquareBracket:{code:219,name:'['},RightSquareBracket:{code:221,name:']'},Backslash:{code:220,name:'\\'},SingleQuote:{code:222,name:'\''},get CtrlOrMeta(){return Host.isMac()?this.Meta:this.Ctrl;},};UI.KeyboardShortcut.KeyBindings={};(function(){for(const key in UI.KeyboardShortcut.Keys){const descriptor=UI.KeyboardShortcut.Keys[key];if(typeof descriptor==='object'&&descriptor['code']){const name=typeof descriptor['name']==='string'?descriptor['name']:key;UI.KeyboardShortcut.KeyBindings[name]=descriptor;}}})();UI.KeyboardShortcut.Descriptor;;UI.ListDelegate=function(){};UI.ListDelegate.prototype={createElementForItem(item){},heightForItem(item){},isItemSelectable(item){},selectedItemChanged(from,to,fromElement,toElement){},};UI.ListMode={NonViewport:Symbol('UI.ListMode.NonViewport'),EqualHeightItems:Symbol('UI.ListMode.EqualHeightItems'),VariousHeightItems:Symbol('UI.ListMode.VariousHeightItems')};UI.ListControl=class{constructor(model,delegate,mode){this.element=createElement('div');this.element.style.overflowY='auto';this._topElement=this.element.createChild('div');this._bottomElement=this.element.createChild('div');this._firstIndex=0;this._lastIndex=0;this._renderedHeight=0;this._topHeight=0;this._bottomHeight=0;this._model=model;this._model.addEventListener(UI.ListModel.Events.ItemsReplaced,this._replacedItemsInRange,this);this._itemToElement=new Map();this._selectedIndex=-1;this._selectedItem=null;this.element.tabIndex=-1;this.element.addEventListener('click',this._onClick.bind(this),false);this.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this._delegate=delegate;this._mode=mode||UI.ListMode.EqualHeightItems;this._fixedHeight=0;this._variableOffsets=new Int32Array(0);this._clearContents();if(this._mode!==UI.ListMode.NonViewport){this.element.addEventListener('scroll',()=>{this._updateViewport(this.element.scrollTop,this.element.offsetHeight);},false);}}
setModel(model){this._itemToElement.clear();const length=this._model.length;this._model.removeEventListener(UI.ListModel.Events.ItemsReplaced,this._replacedItemsInRange,this);this._model=model;this._model.addEventListener(UI.ListModel.Events.ItemsReplaced,this._replacedItemsInRange,this);this.invalidateRange(0,length);}
_replacedItemsInRange(event){const data=(event.data);const from=data.index;const to=from+data.removed.length;const oldSelectedItem=this._selectedItem;const oldSelectedElement=oldSelectedItem?(this._itemToElement.get(oldSelectedItem)||null):null;for(let i=0;i<data.removed.length;i++)
this._itemToElement.delete(data.removed[i]);this._invalidate(from,to,data.inserted);if(this._selectedIndex>=to){this._selectedIndex+=data.inserted-(to-from);this._selectedItem=this._model.at(this._selectedIndex);}else if(this._selectedIndex>=from){let index=this._findFirstSelectable(from+data.inserted,+1,false);if(index===-1)
index=this._findFirstSelectable(from-1,-1,false);this._select(index,oldSelectedItem,oldSelectedElement);}}
refreshItem(item){const index=this._model.indexOf(item);if(index===-1){console.error('Item to refresh is not present');return;}
this.refreshItemByIndex(index);}
refreshItemByIndex(index){const item=this._model.at(index);this._itemToElement.delete(item);this.invalidateRange(index,index+1);if(this._selectedIndex!==-1)
this._select(this._selectedIndex,null,null);}
invalidateRange(from,to){this._invalidate(from,to,to-from);}
viewportResized(){if(this._mode===UI.ListMode.NonViewport)
return;const scrollTop=this.element.scrollTop;const viewportHeight=this.element.offsetHeight;this._clearViewport();this._updateViewport(Number.constrain(scrollTop,0,this._totalHeight()-viewportHeight),viewportHeight);}
invalidateItemHeight(){if(this._mode!==UI.ListMode.EqualHeightItems){console.error('Only supported in equal height items mode');return;}
this._fixedHeight=0;if(this._model.length){this._itemToElement.clear();this._invalidate(0,this._model.length,this._model.length);}}
itemForNode(node){while(node&&node.parentNodeOrShadowHost()!==this.element)
node=node.parentNodeOrShadowHost();if(!node)
return null;const element=(node);const index=this._model.findIndex(item=>this._itemToElement.get(item)===element);return index!==-1?this._model.at(index):null;}
scrollItemIntoView(item,center){const index=this._model.indexOf(item);if(index===-1){console.error('Attempt to scroll onto missing item');return;}
this._scrollIntoView(index,center);}
selectedItem(){return this._selectedItem;}
selectedIndex(){return this._selectedIndex;}
selectItem(item,center,dontScroll){let index=-1;if(item!==null){index=this._model.indexOf(item);if(index===-1){console.error('Attempt to select missing item');return;}
if(!this._delegate.isItemSelectable(item)){console.error('Attempt to select non-selectable item');return;}}
if(this._selectedIndex!==index)
this._select(index);if(index!==-1&&!dontScroll)
this._scrollIntoView(index,center);}
selectPreviousItem(canWrap,center){if(this._selectedIndex===-1&&!canWrap)
return false;let index=this._selectedIndex===-1?this._model.length-1:this._selectedIndex-1;index=this._findFirstSelectable(index,-1,!!canWrap);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;}
return false;}
selectNextItem(canWrap,center){if(this._selectedIndex===-1&&!canWrap)
return false;let index=this._selectedIndex===-1?0:this._selectedIndex+1;index=this._findFirstSelectable(index,+1,!!canWrap);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;}
return false;}
selectItemPreviousPage(center){if(this._mode===UI.ListMode.NonViewport)
return false;let index=this._selectedIndex===-1?this._model.length-1:this._selectedIndex;index=this._findPageSelectable(index,-1);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;}
return false;}
selectItemNextPage(center){if(this._mode===UI.ListMode.NonViewport)
return false;let index=this._selectedIndex===-1?0:this._selectedIndex;index=this._findPageSelectable(index,+1);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;}
return false;}
_scrollIntoView(index,center){if(this._mode===UI.ListMode.NonViewport){this._elementAtIndex(index).scrollIntoViewIfNeeded(!!center);return;}
const top=this._offsetAtIndex(index);const bottom=this._offsetAtIndex(index+1);const viewportHeight=this.element.offsetHeight;if(center){const scrollTo=(top+bottom)/2-viewportHeight/2;this._updateViewport(Number.constrain(scrollTo,0,this._totalHeight()-viewportHeight),viewportHeight);return;}
const scrollTop=this.element.scrollTop;if(top<scrollTop)
this._updateViewport(top,viewportHeight);else if(bottom>scrollTop+viewportHeight)
this._updateViewport(bottom-viewportHeight,viewportHeight);}
_onClick(event){const item=this.itemForNode((event.target));if(item&&this._delegate.isItemSelectable(item))
this.selectItem(item);}
_onKeyDown(event){let selected=false;switch(event.key){case'ArrowUp':selected=this.selectPreviousItem(true,false);break;case'ArrowDown':selected=this.selectNextItem(true,false);break;case'PageUp':selected=this.selectItemPreviousPage(false);break;case'PageDown':selected=this.selectItemNextPage(false);break;}
if(selected)
event.consume();}
_totalHeight(){return this._offsetAtIndex(this._model.length);}
_indexAtOffset(offset){if(this._mode===UI.ListMode.NonViewport)
throw'There should be no offset conversions in non-viewport mode';if(!this._model.length||offset<0)
return 0;if(this._mode===UI.ListMode.VariousHeightItems){return Math.min(this._model.length-1,this._variableOffsets.lowerBound(offset,undefined,0,this._model.length));}
if(!this._fixedHeight)
this._measureHeight();return Math.min(this._model.length-1,Math.floor(offset/this._fixedHeight));}
_elementAtIndex(index){const item=this._model.at(index);let element=this._itemToElement.get(item);if(!element){element=this._delegate.createElementForItem(item);this._itemToElement.set(item,element);}
return element;}
_offsetAtIndex(index){if(this._mode===UI.ListMode.NonViewport)
throw'There should be no offset conversions in non-viewport mode';if(!this._model.length)
return 0;if(this._mode===UI.ListMode.VariousHeightItems)
return this._variableOffsets[index];if(!this._fixedHeight)
this._measureHeight();return index*this._fixedHeight;}
_measureHeight(){this._fixedHeight=this._delegate.heightForItem(this._model.at(0));if(!this._fixedHeight)
this._fixedHeight=UI.measurePreferredSize(this._elementAtIndex(0),this.element).height;}
_select(index,oldItem,oldElement){if(oldItem===undefined)
oldItem=this._selectedItem;if(oldElement===undefined)
oldElement=this._itemToElement.get(oldItem)||null;this._selectedIndex=index;this._selectedItem=index===-1?null:this._model.at(index);const newItem=this._selectedItem;const newElement=this._selectedIndex!==-1?this._elementAtIndex(index):null;this._delegate.selectedItemChanged(oldItem,newItem,(oldElement),newElement);}
_findFirstSelectable(index,direction,canWrap){const length=this._model.length;if(!length)
return-1;for(let step=0;step<=length;step++){if(index<0||index>=length){if(!canWrap)
return-1;index=(index+length)%length;}
if(this._delegate.isItemSelectable(this._model.at(index)))
return index;index+=direction;}
return-1;}
_findPageSelectable(index,direction){let lastSelectable=-1;const startOffset=this._offsetAtIndex(index);const viewportHeight=this.element.offsetHeight-1;while(index>=0&&index<this._model.length){if(this._delegate.isItemSelectable(this._model.at(index))){if(Math.abs(this._offsetAtIndex(index)-startOffset)>=viewportHeight)
return index;lastSelectable=index;}
index+=direction;}
return lastSelectable;}
_reallocateVariableOffsets(length,copyTo){if(this._variableOffsets.length<length){const variableOffsets=new Int32Array(Math.max(length,this._variableOffsets.length*2));variableOffsets.set(this._variableOffsets.slice(0,copyTo),0);this._variableOffsets=variableOffsets;}else if(this._variableOffsets.length>=2*length){const variableOffsets=new Int32Array(length);variableOffsets.set(this._variableOffsets.slice(0,copyTo),0);this._variableOffsets=variableOffsets;}}
_invalidate(from,to,inserted){if(this._mode===UI.ListMode.NonViewport){this._invalidateNonViewportMode(from,to-from,inserted);return;}
if(this._mode===UI.ListMode.VariousHeightItems){this._reallocateVariableOffsets(this._model.length+1,from+1);for(let i=from+1;i<=this._model.length;i++)
this._variableOffsets[i]=this._variableOffsets[i-1]+this._delegate.heightForItem(this._model.at(i-1));}
const viewportHeight=this.element.offsetHeight;const totalHeight=this._totalHeight();const scrollTop=this.element.scrollTop;if(this._renderedHeight<viewportHeight||totalHeight<viewportHeight){this._clearViewport();this._updateViewport(Number.constrain(scrollTop,0,totalHeight-viewportHeight),viewportHeight);return;}
const heightDelta=totalHeight-this._renderedHeight;if(to<=this._firstIndex){const topHeight=this._topHeight+heightDelta;this._topElement.style.height=topHeight+'px';this.element.scrollTop=scrollTop+heightDelta;this._topHeight=topHeight;this._renderedHeight=totalHeight;const indexDelta=inserted-(to-from);this._firstIndex+=indexDelta;this._lastIndex+=indexDelta;return;}
if(from>=this._lastIndex){const bottomHeight=this._bottomHeight+heightDelta;this._bottomElement.style.height=bottomHeight+'px';this._bottomHeight=bottomHeight;this._renderedHeight=totalHeight;return;}
this._clearViewport();this._updateViewport(Number.constrain(scrollTop,0,totalHeight-viewportHeight),viewportHeight);}
_invalidateNonViewportMode(start,remove,add){let startElement=this._topElement;for(let index=0;index<start;index++)
startElement=startElement.nextElementSibling;while(remove--)
startElement.nextElementSibling.remove();while(add--)
this.element.insertBefore(this._elementAtIndex(start+add),startElement.nextElementSibling);}
_clearViewport(){if(this._mode===UI.ListMode.NonViewport){console.error('There should be no viewport updates in non-viewport mode');return;}
this._firstIndex=0;this._lastIndex=0;this._renderedHeight=0;this._topHeight=0;this._bottomHeight=0;this._clearContents();}
_clearContents(){this._topElement.style.height='0';this._bottomElement.style.height='0';this.element.removeChildren();this.element.appendChild(this._topElement);this.element.appendChild(this._bottomElement);}
_updateViewport(scrollTop,viewportHeight){if(this._mode===UI.ListMode.NonViewport){console.error('There should be no viewport updates in non-viewport mode');return;}
const totalHeight=this._totalHeight();if(!totalHeight){this._firstIndex=0;this._lastIndex=0;this._topHeight=0;this._bottomHeight=0;this._renderedHeight=0;this._topElement.style.height='0';this._bottomElement.style.height='0';return;}
const firstIndex=this._indexAtOffset(scrollTop-viewportHeight);const lastIndex=this._indexAtOffset(scrollTop+2*viewportHeight)+1;while(this._firstIndex<Math.min(firstIndex,this._lastIndex)){this._elementAtIndex(this._firstIndex).remove();this._firstIndex++;}
while(this._lastIndex>Math.max(lastIndex,this._firstIndex)){this._elementAtIndex(this._lastIndex-1).remove();this._lastIndex--;}
this._firstIndex=Math.min(this._firstIndex,lastIndex);this._lastIndex=Math.max(this._lastIndex,firstIndex);for(let index=this._firstIndex-1;index>=firstIndex;index--){const element=this._elementAtIndex(index);this.element.insertBefore(element,this._topElement.nextSibling);}
for(let index=this._lastIndex;index<lastIndex;index++){const element=this._elementAtIndex(index);this.element.insertBefore(element,this._bottomElement);}
this._firstIndex=firstIndex;this._lastIndex=lastIndex;this._topHeight=this._offsetAtIndex(firstIndex);this._topElement.style.height=this._topHeight+'px';this._bottomHeight=totalHeight-this._offsetAtIndex(lastIndex);this._bottomElement.style.height=this._bottomHeight+'px';this._renderedHeight=totalHeight;this.element.scrollTop=scrollTop;}};;UI.ListModel=class extends Common.Object{constructor(items){super();this._items=items||[];}
[Symbol.iterator](){return this._items[Symbol.iterator]();}
get length(){return this._items.length;}
at(index){return this._items[index];}
every(callback){return this._items.every(callback);}
filter(callback){return this._items.filter(callback);}
find(callback){return this._items.find(callback);}
findIndex(callback){return this._items.findIndex(callback);}
indexOf(value,fromIndex){return this._items.indexOf(value,fromIndex);}
insert(index,value){this._items.splice(index,0,value);this._replaced(index,[],1);}
insertWithComparator(value,comparator){this.insert(this._items.lowerBound(value,comparator),value);}
join(separator){return this._items.join(separator);}
remove(index){const result=this._items[index];this._items.splice(index,1);this._replaced(index,[result],0);return result;}
replace(index,value){const oldValue=this._items[index];this._items[index]=value;this._replaced(index,[oldValue],1);return oldValue;}
replaceRange(from,to,items){let removed;if(items.length<10000){removed=this._items.splice(from,to-from,...items);}else{removed=this._items.slice(from,to);const before=this._items.slice(0,from);const after=this._items.slice(to);this._items=[].concat(before,items,after);}
this._replaced(from,removed,items.length);return removed;}
replaceAll(items){const oldItems=this._items.slice();this._items=items;this._replaced(0,oldItems,items.length);return oldItems;}
slice(from,to){return this._items.slice(from,to);}
some(callback){return this._items.some(callback);}
_replaced(index,removed,inserted){this.dispatchEventToListeners(UI.ListModel.Events.ItemsReplaced,{index:index,removed:removed,inserted:inserted});}};UI.ListModel.Events={ItemsReplaced:Symbol('ItemsReplaced'),};;UI.ListWidget=class extends UI.VBox{constructor(delegate){super(true,true);this.registerRequiredCSS('ui/listWidget.css');this._delegate=delegate;this._list=this.contentElement.createChild('div','list');this._lastSeparator=false;this._focusRestorer=null;this._items=[];this._editable=[];this._elements=[];this._editor=null;this._editItem=null;this._editElement=null;this._emptyPlaceholder=null;this._updatePlaceholder();}
clear(){this._items=[];this._editable=[];this._elements=[];this._lastSeparator=false;this._list.removeChildren();this._updatePlaceholder();this._stopEditing();}
appendItem(item,editable){if(this._lastSeparator&&this._items.length)
this._list.appendChild(createElementWithClass('div','list-separator'));this._lastSeparator=false;this._items.push(item);this._editable.push(editable);const element=this._list.createChild('div','list-item');element.appendChild(this._delegate.renderItem(item,editable));if(editable){element.classList.add('editable');element.appendChild(this._createControls(item,element));}
this._elements.push(element);this._updatePlaceholder();}
appendSeparator(){this._lastSeparator=true;}
removeItem(index){if(this._editItem===this._items[index])
this._stopEditing();const element=this._elements[index];const previous=element.previousElementSibling;const previousIsSeparator=previous&&previous.classList.contains('list-separator');const next=element.nextElementSibling;const nextIsSeparator=next&&next.classList.contains('list-separator');if(previousIsSeparator&&(nextIsSeparator||!next))
previous.remove();if(nextIsSeparator&&!previous)
next.remove();element.remove();this._elements.splice(index,1);this._items.splice(index,1);this._editable.splice(index,1);this._updatePlaceholder();}
addNewItem(index,item){this._startEditing(item,null,this._elements[index]||null);}
setEmptyPlaceholder(element){this._emptyPlaceholder=element;this._updatePlaceholder();}
_createControls(item,element){const controls=createElementWithClass('div','controls-container fill');controls.createChild('div','controls-gradient');const buttons=controls.createChild('div','controls-buttons');const toolbar=new UI.Toolbar('',buttons);const editButton=new UI.ToolbarButton(Common.UIString('Edit'),'largeicon-edit');editButton.addEventListener(UI.ToolbarButton.Events.Click,onEditClicked.bind(this));toolbar.appendToolbarItem(editButton);const removeButton=new UI.ToolbarButton(Common.UIString('Remove'),'largeicon-trash-bin');removeButton.addEventListener(UI.ToolbarButton.Events.Click,onRemoveClicked.bind(this));toolbar.appendToolbarItem(removeButton);return controls;function onEditClicked(){const index=this._elements.indexOf(element);const insertionPoint=this._elements[index+1]||null;this._startEditing(item,element,insertionPoint);}
function onRemoveClicked(){const index=this._elements.indexOf(element);this.element.focus();this._delegate.removeItemRequested(this._items[index],index);}}
wasShown(){super.wasShown();this._stopEditing();}
_updatePlaceholder(){if(!this._emptyPlaceholder)
return;if(!this._elements.length&&!this._editor)
this._list.appendChild(this._emptyPlaceholder);else
this._emptyPlaceholder.remove();}
_startEditing(item,element,insertionPoint){if(element&&this._editElement===element)
return;this._stopEditing();this._focusRestorer=new UI.ElementFocusRestorer(this.element);this._list.classList.add('list-editing');this._editItem=item;this._editElement=element;if(element)
element.classList.add('hidden');const index=element?this._elements.indexOf(element):-1;this._editor=this._delegate.beginEdit(item);this._updatePlaceholder();this._list.insertBefore(this._editor.element,insertionPoint);this._editor.beginEdit(item,index,element?Common.UIString('Save'):Common.UIString('Add'),this._commitEditing.bind(this),this._stopEditing.bind(this));}
_commitEditing(){const editItem=this._editItem;const isNew=!this._editElement;const editor=(this._editor);this._stopEditing();this._delegate.commitEdit(editItem,editor,isNew);}
_stopEditing(){this._list.classList.remove('list-editing');if(this._focusRestorer)
this._focusRestorer.restore();if(this._editElement)
this._editElement.classList.remove('hidden');if(this._editor&&this._editor.element.parentElement)
this._editor.element.remove();this._editor=null;this._editItem=null;this._editElement=null;this._updatePlaceholder();}};UI.ListWidget.Delegate=function(){};UI.ListWidget.Delegate.prototype={renderItem(item,editable){},removeItemRequested(item,index){},beginEdit(item){},commitEdit(item,editor,isNew){}};UI.ListWidget.Editor=class{constructor(){this.element=createElementWithClass('div','editor-container');this.element.addEventListener('keydown',onKeyDown.bind(null,isEscKey,this._cancelClicked.bind(this)),false);this.element.addEventListener('keydown',onKeyDown.bind(null,isEnterKey,this._commitClicked.bind(this)),false);this._contentElement=this.element.createChild('div','editor-content');const buttonsRow=this.element.createChild('div','editor-buttons');this._commitButton=UI.createTextButton('',this._commitClicked.bind(this),'',true);buttonsRow.appendChild(this._commitButton);this._cancelButton=UI.createTextButton(Common.UIString('Cancel'),this._cancelClicked.bind(this));this._cancelButton.addEventListener('keydown',onKeyDown.bind(null,isEnterKey,this._cancelClicked.bind(this)),false);buttonsRow.appendChild(this._cancelButton);function onKeyDown(predicate,callback,event){if(predicate(event)){event.consume(true);callback();}}
this._controls=[];this._controlByName=new Map();this._validators=[];this._commit=null;this._cancel=null;this._item=null;this._index=-1;}
contentElement(){return this._contentElement;}
createInput(name,type,title,validator){const input=(UI.createInput('',type));input.placeholder=title;input.addEventListener('input',this._validateControls.bind(this,false),false);input.addEventListener('blur',this._validateControls.bind(this,false),false);this._controlByName.set(name,input);this._controls.push(input);this._validators.push(validator);return input;}
createSelect(name,options,validator){const select=(createElementWithClass('select','chrome-select'));for(let index=0;index<options.length;++index){const option=select.createChild('option');option.value=options[index];option.textContent=options[index];}
select.addEventListener('input',this._validateControls.bind(this,false),false);select.addEventListener('blur',this._validateControls.bind(this,false),false);this._controlByName.set(name,select);this._controls.push(select);this._validators.push(validator);return select;}
control(name){return(this._controlByName.get(name));}
_validateControls(forceValid){let allValid=true;for(let index=0;index<this._controls.length;++index){const input=this._controls[index];const valid=this._validators[index].call(null,this._item,this._index,input);input.classList.toggle('error-input',!valid&&!forceValid);allValid&=valid;}
this._commitButton.disabled=!allValid;}
beginEdit(item,index,commitButtonTitle,commit,cancel){this._commit=commit;this._cancel=cancel;this._item=item;this._index=index;this._commitButton.textContent=commitButtonTitle;this.element.scrollIntoViewIfNeeded(false);if(this._controls.length)
this._controls[0].focus();this._validateControls(true);}
_commitClicked(){if(this._commitButton.disabled)
return;const commit=this._commit;this._commit=null;this._cancel=null;this._item=null;this._index=-1;commit();}
_cancelClicked(){const cancel=this._cancel;this._commit=null;this._cancel=null;this._item=null;this._index=-1;cancel();}};;UI.panels={};UI.Panel=class extends UI.VBox{constructor(name){super();this.element.classList.add('panel');this.element.setAttribute('aria-label',name);this.element.classList.add(name);this._panelName=name;UI.panels[name]=this;}
get name(){return this._panelName;}
searchableView(){return null;}
elementsToRestoreScrollPositionsFor(){return[];}
showInfobar(infobar){infobar.setCloseCallback(this._onInfobarClosed.bind(this,infobar));if(this.element.firstChild)
this.element.insertBefore(infobar.element,this.element.firstChild);else
this.element.appendChild(infobar.element);infobar.setParentView(this);this.doResize();}
_onInfobarClosed(infobar){infobar.element.remove();this.doResize();}};UI.PanelWithSidebar=class extends UI.Panel{constructor(name,defaultWidth){super(name);this._panelSplitWidget=new UI.SplitWidget(true,false,this._panelName+'PanelSplitViewState',defaultWidth||200);this._panelSplitWidget.show(this.element);this._mainWidget=new UI.VBox();this._panelSplitWidget.setMainWidget(this._mainWidget);this._sidebarWidget=new UI.VBox();this._sidebarWidget.setMinimumSize(100,25);this._panelSplitWidget.setSidebarWidget(this._sidebarWidget);this._sidebarWidget.element.classList.add('panel-sidebar');}
panelSidebarElement(){return this._sidebarWidget.element;}
mainElement(){return this._mainWidget.element;}
splitWidget(){return this._panelSplitWidget;}};;UI.PopoverHelper=class{constructor(container,getRequest){this._disableOnClick=false;this._hasPadding=false;this._getRequest=getRequest;this._scheduledRequest=null;this._hidePopoverCallback=null;this._container=container;this._showTimeout=0;this._hideTimeout=0;this._hidePopoverTimer=null;this._showPopoverTimer=null;this._boundMouseDown=this._mouseDown.bind(this);this._boundMouseMove=this._mouseMove.bind(this);this._boundMouseOut=this._mouseOut.bind(this);this._container.addEventListener('mousedown',this._boundMouseDown,false);this._container.addEventListener('mousemove',this._boundMouseMove,false);this._container.addEventListener('mouseout',this._boundMouseOut,false);this.setTimeout(1000);}
setTimeout(showTimeout,hideTimeout){this._showTimeout=showTimeout;this._hideTimeout=typeof hideTimeout==='number'?hideTimeout:showTimeout/2;}
setHasPadding(hasPadding){this._hasPadding=hasPadding;}
setDisableOnClick(disableOnClick){this._disableOnClick=disableOnClick;}
_eventInScheduledContent(event){return this._scheduledRequest?this._scheduledRequest.box.contains(event.clientX,event.clientY):false;}
_mouseDown(event){if(this._disableOnClick){this.hidePopover();return;}
if(this._eventInScheduledContent(event))
return;this._startHidePopoverTimer(0);this._stopShowPopoverTimer();this._startShowPopoverTimer((event),0);}
_mouseMove(event){if(this._eventInScheduledContent(event))
return;this._startHidePopoverTimer(this._hideTimeout);this._stopShowPopoverTimer();if(event.which&&this._disableOnClick)
return;this._startShowPopoverTimer((event),this.isPopoverVisible()?this._showTimeout*0.6:this._showTimeout);}
_popoverMouseMove(event){this._stopHidePopoverTimer();}
_popoverMouseOut(popover,event){if(!popover.isShowing())
return;if(event.relatedTarget&&!event.relatedTarget.isSelfOrDescendant(popover.contentElement))
this._startHidePopoverTimer(this._hideTimeout);}
_mouseOut(event){if(!this.isPopoverVisible())
return;if(!this._eventInScheduledContent(event))
this._startHidePopoverTimer(this._hideTimeout);}
_startHidePopoverTimer(timeout){if(!this._hidePopoverCallback||this._hidePopoverTimer)
return;this._hidePopoverTimer=setTimeout(()=>{this._hidePopover();this._hidePopoverTimer=null;},timeout);}
_startShowPopoverTimer(event,timeout){this._scheduledRequest=this._getRequest.call(null,event);if(!this._scheduledRequest)
return;this._showPopoverTimer=setTimeout(()=>{this._showPopoverTimer=null;this._stopHidePopoverTimer();this._hidePopover();this._showPopover(event.target.ownerDocument);},timeout);}
_stopShowPopoverTimer(){if(!this._showPopoverTimer)
return;clearTimeout(this._showPopoverTimer);this._showPopoverTimer=null;}
isPopoverVisible(){return!!this._hidePopoverCallback;}
hidePopover(){this._stopShowPopoverTimer();this._hidePopover();}
_hidePopover(){if(!this._hidePopoverCallback)
return;this._hidePopoverCallback.call(null);this._hidePopoverCallback=null;}
_showPopover(document){const popover=new UI.GlassPane();popover.registerRequiredCSS('ui/popover.css');popover.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);popover.setMarginBehavior(UI.GlassPane.MarginBehavior.Arrow);const request=this._scheduledRequest;request.show.call(null,popover).then(success=>{if(!success)
return;if(this._scheduledRequest!==request){if(request.hide)
request.hide.call(null);return;}
if(UI.PopoverHelper._popoverHelper){console.error('One popover is already visible');UI.PopoverHelper._popoverHelper.hidePopover();}
UI.PopoverHelper._popoverHelper=this;popover.contentElement.classList.toggle('has-padding',this._hasPadding);popover.contentElement.addEventListener('mousemove',this._popoverMouseMove.bind(this),true);popover.contentElement.addEventListener('mouseout',this._popoverMouseOut.bind(this,popover),true);popover.setContentAnchorBox(request.box);popover.show(document);this._hidePopoverCallback=()=>{if(request.hide)
request.hide.call(null);popover.hide();delete UI.PopoverHelper._popoverHelper;};});}
_stopHidePopoverTimer(){if(!this._hidePopoverTimer)
return;clearTimeout(this._hidePopoverTimer);this._hidePopoverTimer=null;this._stopShowPopoverTimer();}
dispose(){this._container.removeEventListener('mousedown',this._boundMouseDown,false);this._container.removeEventListener('mousemove',this._boundMouseMove,false);this._container.removeEventListener('mouseout',this._boundMouseOut,false);}};UI.PopoverRequest;;UI.ProgressIndicator=class{constructor(){this.element=createElementWithClass('div','progress-indicator');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/progressIndicator.css');this._contentElement=this._shadowRoot.createChild('div','progress-indicator-shadow-container');this._labelElement=this._contentElement.createChild('div','title');this._progressElement=this._contentElement.createChild('progress');this._progressElement.value=0;this._stopButton=this._contentElement.createChild('button','progress-indicator-shadow-stop-button');this._stopButton.addEventListener('click',this.cancel.bind(this));this._isCanceled=false;this._worked=0;}
show(parent){parent.appendChild(this.element);}
done(){if(this._isDone)
return;this._isDone=true;this.element.remove();}
cancel(){this._isCanceled=true;}
isCanceled(){return this._isCanceled;}
setTitle(title){this._labelElement.textContent=title;}
setTotalWork(totalWork){this._progressElement.max=totalWork;}
setWorked(worked,title){this._worked=worked;this._progressElement.value=worked;if(title)
this.setTitle(title);}
worked(worked){this.setWorked(this._worked+(worked||1));}};;UI.ResizerWidget=class extends Common.Object{constructor(){super();this._isEnabled=true;this._elements=[];this._installDragOnMouseDownBound=this._installDragOnMouseDown.bind(this);this._cursor='nwse-resize';}
isEnabled(){return this._isEnabled;}
setEnabled(enabled){this._isEnabled=enabled;this.updateElementCursors();}
elements(){return this._elements.slice();}
addElement(element){if(this._elements.indexOf(element)!==-1)
return;this._elements.push(element);element.addEventListener('mousedown',this._installDragOnMouseDownBound,false);this._updateElementCursor(element);}
removeElement(element){if(this._elements.indexOf(element)===-1)
return;this._elements.remove(element);element.removeEventListener('mousedown',this._installDragOnMouseDownBound,false);element.style.removeProperty('cursor');}
updateElementCursors(){this._elements.forEach(this._updateElementCursor.bind(this));}
_updateElementCursor(element){if(this._isEnabled)
element.style.setProperty('cursor',this.cursor());else
element.style.removeProperty('cursor');}
cursor(){return this._cursor;}
setCursor(cursor){this._cursor=cursor;this.updateElementCursors();}
_installDragOnMouseDown(event){if(this._elements.indexOf(event.target)===-1)
return false;UI.elementDragStart((event.target),this._dragStart.bind(this),this._drag.bind(this),this._dragEnd.bind(this),this.cursor(),event);}
_dragStart(event){if(!this._isEnabled)
return false;this._startX=event.pageX;this._startY=event.pageY;this.sendDragStart(this._startX,this._startY);return true;}
sendDragStart(x,y){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeStart,{startX:x,currentX:x,startY:y,currentY:y});}
_drag(event){if(!this._isEnabled){this._dragEnd(event);return true;}
this.sendDragMove(this._startX,event.pageX,this._startY,event.pageY,event.shiftKey);event.preventDefault();return false;}
sendDragMove(startX,currentX,startY,currentY,shiftKey){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeUpdate,{startX:startX,currentX:currentX,startY:startY,currentY:currentY,shiftKey:shiftKey});}
_dragEnd(event){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeEnd);delete this._startX;delete this._startY;}};UI.ResizerWidget.Events={ResizeStart:Symbol('ResizeStart'),ResizeUpdate:Symbol('ResizeUpdate'),ResizeEnd:Symbol('ResizeEnd')};UI.SimpleResizerWidget=class extends UI.ResizerWidget{constructor(){super();this._isVertical=true;}
isVertical(){return this._isVertical;}
setVertical(vertical){this._isVertical=vertical;this.updateElementCursors();}
cursor(){return this._isVertical?'ns-resize':'ew-resize';}
sendDragStart(x,y){const position=this._isVertical?y:x;this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeStart,{startPosition:position,currentPosition:position});}
sendDragMove(startX,currentX,startY,currentY,shiftKey){if(this._isVertical){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeUpdate,{startPosition:startY,currentPosition:currentY,shiftKey:shiftKey});}else{this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeUpdate,{startPosition:startX,currentPosition:currentX,shiftKey:shiftKey});}}};;UI.RemoteDebuggingTerminatedScreen=class extends UI.VBox{constructor(reason){super(true);this.registerRequiredCSS('ui/remoteDebuggingTerminatedScreen.css');const message=this.contentElement.createChild('div','message');message.createChild('span').textContent=Common.UIString('Debugging connection was closed. Reason: ');message.createChild('span','reason').textContent=reason;this.contentElement.createChild('div','message').textContent=Common.UIString('Reconnect when ready by reopening DevTools.');const button=UI.createTextButton(Common.UIString('Reconnect DevTools'),()=>window.location.reload());this.contentElement.createChild('div','button').appendChild(button);}
static show(reason){const dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.addCloseButton();dialog.setDimmed(true);new UI.RemoteDebuggingTerminatedScreen(reason).show(dialog.contentElement);dialog.show();}};;UI.ReportView=class extends UI.VBox{constructor(title){super(true);this.registerRequiredCSS('ui/reportView.css');this._contentBox=this.contentElement.createChild('div','report-content-box');this._headerElement=this._contentBox.createChild('div','report-header vbox');this._titleElement=this._headerElement.createChild('div','report-title');this._titleElement.textContent=title;UI.ARIAUtils.markAsHeading(this._titleElement,1);this._sectionList=this._contentBox.createChild('div','vbox');}
setTitle(title){if(this._titleElement.textContent===title)
return;this._titleElement.textContent=title;}
setSubtitle(subtitle){if(this._subtitleElement&&this._subtitleElement.textContent===subtitle)
return;if(!this._subtitleElement)
this._subtitleElement=this._headerElement.createChild('div','report-subtitle');this._subtitleElement.textContent=subtitle;}
setURL(link){if(!this._urlElement)
this._urlElement=this._headerElement.createChild('div','report-url link');this._urlElement.removeChildren();if(link)
this._urlElement.appendChild(link);}
createToolbar(){const toolbar=new UI.Toolbar('');this._headerElement.appendChild(toolbar.element);return toolbar;}
appendSection(title,className){const section=new UI.ReportView.Section(title,className);section.show(this._sectionList);return section;}
sortSections(comparator){const sections=(this.children().slice());const sorted=sections.every((e,i,a)=>!i||comparator(a[i-1],a[i])<=0);if(sorted)
return;this.detachChildWidgets();sections.sort(comparator);for(const section of sections)
section.show(this._sectionList);}
setHeaderVisible(visible){this._headerElement.classList.toggle('hidden',!visible);}
setBodyScrollable(scrollable){this._contentBox.classList.toggle('no-scroll',!scrollable);}};UI.ReportView.Section=class extends UI.VBox{constructor(title,className){super();this.element.classList.add('report-section');if(className)
this.element.classList.add(className);this._headerElement=this.element.createChild('div','report-section-header');this._titleElement=this._headerElement.createChild('div','report-section-title');this.setTitle(title);UI.ARIAUtils.markAsHeading(this._titleElement,2);this._fieldList=this.element.createChild('div','vbox');this._fieldMap=new Map();}
title(){return this._titleElement.textContent;}
setTitle(title){if(this._titleElement.textContent!==title)
this._titleElement.textContent=title;this._titleElement.classList.toggle('hidden',!this._titleElement.textContent);}
createToolbar(){const toolbar=new UI.Toolbar('');this._headerElement.appendChild(toolbar.element);return toolbar;}
appendField(title,textValue){let row=this._fieldMap.get(title);if(!row){row=this._fieldList.createChild('div','report-field');row.createChild('div','report-field-name').textContent=title;this._fieldMap.set(title,row);row.createChild('div','report-field-value');}
if(textValue)
row.lastElementChild.textContent=textValue;return(row.lastElementChild);}
removeField(title){const row=this._fieldMap.get(title);if(row)
row.remove();this._fieldMap.delete(title);}
setFieldVisible(title,visible){const row=this._fieldMap.get(title);if(row)
row.classList.toggle('hidden',!visible);}
fieldValue(title){const row=this._fieldMap.get(title);return row?row.lastElementChild:null;}
appendRow(){return this._fieldList.createChild('div','report-row');}
appendSelectableRow(){return this._fieldList.createChild('div','report-row report-row-selectable');}
clearContent(){this._fieldList.removeChildren();this._fieldMap.clear();}
markFieldListAsGroup(){UI.ARIAUtils.markAsGroup(this._fieldList);UI.ARIAUtils.setAccessibleName(this._fieldList,this.title());}};;UI.RootView=class extends UI.VBox{constructor(){super();this.markAsRoot();this.element.classList.add('root-view');this.registerRequiredCSS('ui/rootView.css');this.element.setAttribute('spellcheck',false);}
attachToDocument(document){document.defaultView.addEventListener('resize',this.doResize.bind(this),false);this._window=document.defaultView;this.doResize();this.show((document.body));}
doResize(){if(this._window){const size=this.constraints().minimum;const zoom=UI.zoomManager.zoomFactor();const right=Math.min(0,this._window.innerWidth-size.width/zoom);this.element.style.marginRight=right+'px';const bottom=Math.min(0,this._window.innerHeight-size.height/zoom);this.element.style.marginBottom=bottom+'px';}
super.doResize();}};;UI.SearchableView=class extends UI.VBox{constructor(searchable,settingName){super(true);this.registerRequiredCSS('ui/searchableView.css');this.element[UI.SearchableView._symbol]=this;this._searchProvider=searchable;this._setting=settingName?Common.settings.createSetting(settingName,{}):null;this._replaceable=false;this.contentElement.createChild('slot');this._footerElementContainer=this.contentElement.createChild('div','search-bar hidden');this._footerElementContainer.style.order=100;this._footerElement=this._footerElementContainer.createChild('div','toolbar-search');const replaceToggleToolbar=new UI.Toolbar('replace-toggle-toolbar',this._footerElement);this._replaceToggleButton=new UI.ToolbarToggle(Common.UIString('Replace'),'mediumicon-replace');this._replaceToggleButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleReplace,this);replaceToggleToolbar.appendToolbarItem(this._replaceToggleButton);const searchInputElements=this._footerElement.createChild('div','toolbar-search-inputs');const searchControlElement=searchInputElements.createChild('div','toolbar-search-control');this._searchInputElement=UI.HistoryInput.create();this._searchInputElement.classList.add('search-replace');this._searchInputElement.id='search-input-field';this._searchInputElement.placeholder=Common.UIString('Find');searchControlElement.appendChild(this._searchInputElement);this._matchesElement=searchControlElement.createChild('label','search-results-matches');this._matchesElement.setAttribute('for','search-input-field');const searchNavigationElement=searchControlElement.createChild('div','toolbar-search-navigation-controls');this._searchNavigationPrevElement=searchNavigationElement.createChild('div','toolbar-search-navigation toolbar-search-navigation-prev');this._searchNavigationPrevElement.addEventListener('click',this._onPrevButtonSearch.bind(this),false);this._searchNavigationPrevElement.title=Common.UIString('Search previous');this._searchNavigationNextElement=searchNavigationElement.createChild('div','toolbar-search-navigation toolbar-search-navigation-next');this._searchNavigationNextElement.addEventListener('click',this._onNextButtonSearch.bind(this),false);this._searchNavigationNextElement.title=Common.UIString('Search next');this._searchInputElement.addEventListener('keydown',this._onSearchKeyDown.bind(this),true);this._searchInputElement.addEventListener('input',this._onInput.bind(this),false);this._replaceInputElement=searchInputElements.createChild('input','search-replace toolbar-replace-control hidden');this._replaceInputElement.addEventListener('keydown',this._onReplaceKeyDown.bind(this),true);this._replaceInputElement.placeholder=Common.UIString('Replace');this._buttonsContainer=this._footerElement.createChild('div','toolbar-search-buttons');const firstRowButtons=this._buttonsContainer.createChild('div','first-row-buttons');const toolbar=new UI.Toolbar('toolbar-search-options',firstRowButtons);if(this._searchProvider.supportsCaseSensitiveSearch()){this._caseSensitiveButton=new UI.ToolbarToggle(Common.UIString('Match Case'));this._caseSensitiveButton.setText('Aa');this._caseSensitiveButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleCaseSensitiveSearch,this);toolbar.appendToolbarItem(this._caseSensitiveButton);}
if(this._searchProvider.supportsRegexSearch()){this._regexButton=new UI.ToolbarToggle(Common.UIString('Use Regular Expression'));this._regexButton.setText('.*');this._regexButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleRegexSearch,this);toolbar.appendToolbarItem(this._regexButton);}
const cancelButtonElement=UI.createTextButton(Common.UIString('Cancel'),this.closeSearch.bind(this),'search-action-button');firstRowButtons.appendChild(cancelButtonElement);this._secondRowButtons=this._buttonsContainer.createChild('div','second-row-buttons hidden');this._replaceButtonElement=UI.createTextButton(Common.UIString('Replace'),this._replace.bind(this),'search-action-button');this._replaceButtonElement.disabled=true;this._secondRowButtons.appendChild(this._replaceButtonElement);this._replaceAllButtonElement=UI.createTextButton(Common.UIString('Replace all'),this._replaceAll.bind(this),'search-action-button');this._secondRowButtons.appendChild(this._replaceAllButtonElement);this._replaceAllButtonElement.disabled=true;this._minimalSearchQuerySize=3;this._loadSetting();}
static fromElement(element){let view=null;while(element&&!view){view=element[UI.SearchableView._symbol];element=element.parentElementOrShadowHost();}
return view;}
_toggleCaseSensitiveSearch(){this._caseSensitiveButton.setToggled(!this._caseSensitiveButton.toggled());this._saveSetting();this._performSearch(false,true);}
_toggleRegexSearch(){this._regexButton.setToggled(!this._regexButton.toggled());this._saveSetting();this._performSearch(false,true);}
_toggleReplace(){this._replaceToggleButton.setToggled(!this._replaceToggleButton.toggled());this._updateSecondRowVisibility();}
_saveSetting(){if(!this._setting)
return;const settingValue=this._setting.get()||{};settingValue.caseSensitive=this._caseSensitiveButton.toggled();settingValue.isRegex=this._regexButton.toggled();this._setting.set(settingValue);}
_loadSetting(){const settingValue=this._setting?(this._setting.get()||{}):{};if(this._searchProvider.supportsCaseSensitiveSearch())
this._caseSensitiveButton.setToggled(!!settingValue.caseSensitive);if(this._searchProvider.supportsRegexSearch())
this._regexButton.setToggled(!!settingValue.isRegex);}
setMinimalSearchQuerySize(minimalSearchQuerySize){this._minimalSearchQuerySize=minimalSearchQuerySize;}
setPlaceholder(placeholder){this._searchInputElement.placeholder=placeholder;}
setReplaceable(replaceable){this._replaceable=replaceable;}
updateSearchMatchesCount(matches){if(this._searchProvider.currentSearchMatches===matches)
return;this._searchProvider.currentSearchMatches=matches;this._updateSearchMatchesCountAndCurrentMatchIndex(this._searchProvider.currentQuery?matches:0,-1);}
updateCurrentMatchIndex(currentMatchIndex){this._updateSearchMatchesCountAndCurrentMatchIndex(this._searchProvider.currentSearchMatches,currentMatchIndex);}
isSearchVisible(){return this._searchIsVisible;}
closeSearch(){this.cancelSearch();if(this._footerElementContainer.hasFocus())
this.focus();}
_toggleSearchBar(toggled){this._footerElementContainer.classList.toggle('hidden',!toggled);this.doResize();}
cancelSearch(){if(!this._searchIsVisible)
return;this.resetSearch();delete this._searchIsVisible;this._toggleSearchBar(false);}
resetSearch(){this._clearSearch();this._updateReplaceVisibility();this._matchesElement.textContent='';}
refreshSearch(){if(!this._searchIsVisible)
return;this.resetSearch();this._performSearch(false,false);}
handleFindNextShortcut(){if(!this._searchIsVisible)
return false;this._searchProvider.jumpToNextSearchResult();return true;}
handleFindPreviousShortcut(){if(!this._searchIsVisible)
return false;this._searchProvider.jumpToPreviousSearchResult();return true;}
handleFindShortcut(){this.showSearchField();return true;}
handleCancelSearchShortcut(){if(!this._searchIsVisible)
return false;this.closeSearch();return true;}
_updateSearchNavigationButtonState(enabled){this._replaceButtonElement.disabled=!enabled;this._replaceAllButtonElement.disabled=!enabled;this._searchNavigationPrevElement.classList.toggle('enabled',enabled);this._searchNavigationNextElement.classList.toggle('enabled',enabled);}
_updateSearchMatchesCountAndCurrentMatchIndex(matches,currentMatchIndex){if(!this._currentQuery)
this._matchesElement.textContent='';else if(matches===0||currentMatchIndex>=0)
this._matchesElement.textContent=Common.UIString('%d of %d',currentMatchIndex+1,matches);else if(matches===1)
this._matchesElement.textContent=Common.UIString('1 match');else
this._matchesElement.textContent=Common.UIString('%d matches',matches);this._updateSearchNavigationButtonState(matches>0);}
showSearchField(){if(this._searchIsVisible)
this.cancelSearch();let queryCandidate;if(!this._searchInputElement.hasFocus()){const selection=UI.inspectorView.element.window().getSelection();if(selection.rangeCount)
queryCandidate=selection.toString().replace(/\r?\n.*/,'');}
this._toggleSearchBar(true);this._updateReplaceVisibility();if(queryCandidate)
this._searchInputElement.value=queryCandidate;this._performSearch(false,false);this._searchInputElement.focus();this._searchInputElement.select();this._searchIsVisible=true;}
_updateReplaceVisibility(){this._replaceToggleButton.setVisible(this._replaceable);if(!this._replaceable){this._replaceToggleButton.setToggled(false);this._updateSecondRowVisibility();}}
_onSearchKeyDown(event){if(isEscKey(event)){this.closeSearch();event.consume(true);return;}
if(!isEnterKey(event))
return;if(!this._currentQuery)
this._performSearch(true,true,event.shiftKey);else
this._jumpToNextSearchResult(event.shiftKey);}
_onReplaceKeyDown(event){if(isEnterKey(event))
this._replace();}
_jumpToNextSearchResult(isBackwardSearch){if(!this._currentQuery)
return;if(isBackwardSearch)
this._searchProvider.jumpToPreviousSearchResult();else
this._searchProvider.jumpToNextSearchResult();}
_onNextButtonSearch(event){if(!this._searchNavigationNextElement.classList.contains('enabled'))
return;this._jumpToNextSearchResult();this._searchInputElement.focus();}
_onPrevButtonSearch(event){if(!this._searchNavigationPrevElement.classList.contains('enabled'))
return;this._jumpToNextSearchResult(true);this._searchInputElement.focus();}
_onFindClick(event){if(!this._currentQuery)
this._performSearch(true,true);else
this._jumpToNextSearchResult();this._searchInputElement.focus();}
_onPreviousClick(event){if(!this._currentQuery)
this._performSearch(true,true,true);else
this._jumpToNextSearchResult(true);this._searchInputElement.focus();}
_clearSearch(){delete this._currentQuery;if(!!this._searchProvider.currentQuery){delete this._searchProvider.currentQuery;this._searchProvider.searchCanceled();}
this._updateSearchMatchesCountAndCurrentMatchIndex(0,-1);}
_performSearch(forceSearch,shouldJump,jumpBackwards){const query=this._searchInputElement.value;if(!query||(!forceSearch&&query.length<this._minimalSearchQuerySize&&!this._currentQuery)){this._clearSearch();return;}
this._currentQuery=query;this._searchProvider.currentQuery=query;const searchConfig=this._currentSearchConfig();this._searchProvider.performSearch(searchConfig,shouldJump,jumpBackwards);}
_currentSearchConfig(){const query=this._searchInputElement.value;const caseSensitive=this._caseSensitiveButton?this._caseSensitiveButton.toggled():false;const isRegex=this._regexButton?this._regexButton.toggled():false;return new UI.SearchableView.SearchConfig(query,caseSensitive,isRegex);}
_updateSecondRowVisibility(){const secondRowVisible=this._replaceToggleButton.toggled();this._footerElementContainer.classList.toggle('replaceable',secondRowVisible);this._secondRowButtons.classList.toggle('hidden',!secondRowVisible);this._replaceInputElement.classList.toggle('hidden',!secondRowVisible);if(secondRowVisible)
this._replaceInputElement.focus();else
this._searchInputElement.focus();this.doResize();}
_replace(){const searchConfig=this._currentSearchConfig();(this._searchProvider).replaceSelectionWith(searchConfig,this._replaceInputElement.value);delete this._currentQuery;this._performSearch(true,true);}
_replaceAll(){const searchConfig=this._currentSearchConfig();(this._searchProvider).replaceAllWith(searchConfig,this._replaceInputElement.value);}
_onInput(event){if(this._valueChangedTimeoutId)
clearTimeout(this._valueChangedTimeoutId);const timeout=this._searchInputElement.value.length<3?200:0;this._valueChangedTimeoutId=setTimeout(this._onValueChanged.bind(this),timeout);}
_onValueChanged(){if(!this._searchIsVisible)
return;delete this._valueChangedTimeoutId;this._performSearch(false,true);}};UI.SearchableView._symbol=Symbol('searchableView');UI.Searchable=function(){};UI.Searchable.prototype={searchCanceled(){},performSearch(searchConfig,shouldJump,jumpBackwards){},jumpToNextSearchResult(){},jumpToPreviousSearchResult(){},supportsCaseSensitiveSearch(){},supportsRegexSearch(){}};UI.Replaceable=function(){};UI.Replaceable.prototype={replaceSelectionWith(searchConfig,replacement){},replaceAllWith(searchConfig,replacement){}};UI.SearchableView.SearchConfig=class{constructor(query,caseSensitive,isRegex){this.query=query;this.caseSensitive=caseSensitive;this.isRegex=isRegex;}
toSearchRegex(global){let modifiers=this.caseSensitive?'':'i';if(global)
modifiers+='g';const query=this.isRegex?'/'+this.query+'/':this.query;let regex;try{if(/^\/.+\/$/.test(query)){regex=new RegExp(query.substring(1,query.length-1),modifiers);regex.__fromRegExpQuery=true;}}catch(e){}
if(!regex)
regex=createPlainTextSearchRegex(query,modifiers);return regex;}};;UI.SegmentedButton=class extends UI.HBox{constructor(){super(true);this._buttons=new Map();this._selected=null;this.registerRequiredCSS('ui/segmentedButton.css');this.contentElement.classList.add('segmented-button');}
addSegment(label,value,tooltip){const button=this.contentElement.createChild('button','segmented-button-segment');button.textContent=label;button.title=tooltip;this._buttons.set(value,button);button.addEventListener('click',()=>this.select(value));}
select(value){if(this._selected===value)
return;this._selected=value;for(const key of this._buttons.keys())
this._buttons.get(key).classList.toggle('segmented-button-segment-selected',key===this._selected);}
selected(){return this._selected;}};;UI.SettingsUI={};UI.SettingsUI.createSettingCheckbox=function(name,setting,omitParagraphElement,tooltip){const label=UI.CheckboxLabel.create(name);if(tooltip)
label.title=tooltip;const input=label.checkboxElement;input.name=name;UI.SettingsUI.bindCheckbox(input,setting);if(omitParagraphElement)
return label;const p=createElement('p');p.appendChild(label);return p;};UI.SettingsUI.createSettingSelect=function(name,options,setting){const p=createElement('p');p.createChild('label').textContent=name;const select=p.createChild('select','chrome-select');for(let i=0;i<options.length;++i){const option=options[i];const optionName=option.raw?option.text:Common.UIString(option.text);select.add(new Option(optionName,option.value));}
setting.addChangeListener(settingChanged);settingChanged();select.addEventListener('change',selectChanged,false);return p;function settingChanged(){const newValue=setting.get();for(let i=0;i<options.length;i++){if(options[i].value===newValue)
select.selectedIndex=i;}}
function selectChanged(){setting.set(options[select.selectedIndex].value);}};UI.SettingsUI.bindCheckbox=function(input,setting){function settingChanged(){if(input.checked!==setting.get())
input.checked=setting.get();}
setting.addChangeListener(settingChanged);settingChanged();function inputChanged(){if(setting.get()!==input.checked)
setting.set(input.checked);}
input.addEventListener('change',inputChanged,false);};UI.SettingsUI.createCustomSetting=function(name,element){const p=createElement('p');const fieldsetElement=p.createChild('fieldset');fieldsetElement.createChild('label').textContent=name;fieldsetElement.appendChild(element);return p;};UI.SettingsUI.createControlForSetting=function(setting){if(!setting.extension())
return null;const descriptor=setting.extension().descriptor();const uiTitle=Common.UIString(setting.title()||'');switch(descriptor['settingType']){case'boolean':return UI.SettingsUI.createSettingCheckbox(uiTitle,setting);case'enum':if(Array.isArray(descriptor['options']))
return UI.SettingsUI.createSettingSelect(uiTitle,descriptor['options'],setting);console.error('Enum setting defined without options');return null;default:console.error('Invalid setting type: '+descriptor['settingType']);return null;}};UI.SettingUI=function(){};UI.SettingUI.prototype={settingElement(){}};;UI.SoftContextMenu=class{constructor(items,itemSelectedCallback,parentMenu){this._items=items;this._itemSelectedCallback=itemSelectedCallback;this._parentMenu=parentMenu;this._highlightedMenuItemElement=null;}
show(document,anchorBox){if(!this._items.length)
return;this._document=document;this._glassPane=new UI.GlassPane();this._glassPane.setPointerEventsBehavior(this._parentMenu?UI.GlassPane.PointerEventsBehavior.PierceGlassPane:UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this._glassPane.registerRequiredCSS('ui/softContextMenu.css');this._glassPane.setContentAnchorBox(anchorBox);this._glassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);this._glassPane.setMarginBehavior(UI.GlassPane.MarginBehavior.NoMargin);this._glassPane.setAnchorBehavior(this._parentMenu?UI.GlassPane.AnchorBehavior.PreferRight:UI.GlassPane.AnchorBehavior.PreferBottom);this._contextMenuElement=this._glassPane.contentElement.createChild('div','soft-context-menu');this._contextMenuElement.tabIndex=-1;UI.ARIAUtils.markAsMenu(this._contextMenuElement);this._contextMenuElement.addEventListener('mouseup',e=>e.consume(),false);this._contextMenuElement.addEventListener('keydown',this._menuKeyDown.bind(this),false);for(let i=0;i<this._items.length;++i)
this._contextMenuElement.appendChild(this._createMenuItem(this._items[i]));this._glassPane.show(document);this._focusRestorer=new UI.ElementFocusRestorer(this._contextMenuElement);if(!this._parentMenu){this._hideOnUserGesture=event=>{this.discard();event.consume(true);};this._document.body.addEventListener('mousedown',this._hideOnUserGesture,false);this._document.defaultView.addEventListener('resize',this._hideOnUserGesture,false);}}
discard(){if(this._subMenu)
this._subMenu.discard();if(this._focusRestorer)
this._focusRestorer.restore();if(this._glassPane){this._glassPane.hide();delete this._glassPane;if(this._hideOnUserGesture){this._document.body.removeEventListener('mousedown',this._hideOnUserGesture,false);this._document.defaultView.removeEventListener('resize',this._hideOnUserGesture,false);delete this._hideOnUserGesture;}}
if(this._parentMenu)
delete this._parentMenu._subMenu;}
_createMenuItem(item){if(item.type==='separator')
return this._createSeparator();if(item.type==='subMenu')
return this._createSubMenu(item);const menuItemElement=createElementWithClass('div','soft-context-menu-item');menuItemElement.tabIndex=-1;UI.ARIAUtils.markAsMenuItem(menuItemElement);const checkMarkElement=UI.Icon.create('smallicon-checkmark','checkmark');menuItemElement.appendChild(checkMarkElement);if(!item.checked)
checkMarkElement.style.opacity='0';if(item.element){const wrapper=menuItemElement.createChild('div','soft-context-menu-custom-item');wrapper.appendChild(item.element);menuItemElement._customElement=item.element;return menuItemElement;}
if(!item.enabled)
menuItemElement.classList.add('soft-context-menu-disabled');menuItemElement.createTextChild(item.label);menuItemElement.createChild('span','soft-context-menu-shortcut').textContent=item.shortcut;menuItemElement.addEventListener('mousedown',this._menuItemMouseDown.bind(this),false);menuItemElement.addEventListener('mouseup',this._menuItemMouseUp.bind(this),false);menuItemElement.addEventListener('mouseover',this._menuItemMouseOver.bind(this),false);menuItemElement.addEventListener('mouseleave',this._menuItemMouseLeave.bind(this),false);menuItemElement._actionId=item.id;let accessibleName=item.label;if(item.checked&&item.shortcut)
accessibleName=ls`${item.label}, checked, ${item.shortcut}`;else if(item.shortcut)
accessibleName=ls`${item.label}, ${item.shortcut}`;else if(item.checked)
accessibleName=ls`${item.label}, checked`;UI.ARIAUtils.setAccessibleName(menuItemElement,accessibleName);return menuItemElement;}
_createSubMenu(item){const menuItemElement=createElementWithClass('div','soft-context-menu-item');menuItemElement._subItems=item.subItems;menuItemElement.tabIndex=-1;UI.ARIAUtils.markAsMenuItem(menuItemElement);const checkMarkElement=UI.Icon.create('smallicon-checkmark','soft-context-menu-item-checkmark');checkMarkElement.classList.add('checkmark');menuItemElement.appendChild(checkMarkElement);checkMarkElement.style.opacity='0';menuItemElement.createTextChild(item.label);if(Host.isMac()&&!UI.themeSupport.hasTheme()){const subMenuArrowElement=menuItemElement.createChild('span','soft-context-menu-item-submenu-arrow');subMenuArrowElement.textContent='\u25B6';}else{const subMenuArrowElement=UI.Icon.create('smallicon-triangle-right','soft-context-menu-item-submenu-arrow');menuItemElement.appendChild(subMenuArrowElement);}
menuItemElement.addEventListener('mousedown',this._menuItemMouseDown.bind(this),false);menuItemElement.addEventListener('mouseup',this._menuItemMouseUp.bind(this),false);menuItemElement.addEventListener('mouseover',this._menuItemMouseOver.bind(this),false);menuItemElement.addEventListener('mouseleave',this._menuItemMouseLeave.bind(this),false);return menuItemElement;}
_createSeparator(){const separatorElement=createElementWithClass('div','soft-context-menu-separator');separatorElement._isSeparator=true;separatorElement.createChild('div','separator-line');return separatorElement;}
_menuItemMouseDown(event){event.consume(true);}
_menuItemMouseUp(event){this._triggerAction(event.target,event);event.consume();}
_root(){let root=this;while(root._parentMenu)
root=root._parentMenu;return root;}
_triggerAction(menuItemElement,event){if(!menuItemElement._subItems){this._root().discard();event.consume(true);if(typeof menuItemElement._actionId!=='undefined'){this._itemSelectedCallback(menuItemElement._actionId);delete menuItemElement._actionId;}
return;}
this._showSubMenu(menuItemElement);event.consume();}
_showSubMenu(menuItemElement){if(menuItemElement._subMenuTimer){clearTimeout(menuItemElement._subMenuTimer);delete menuItemElement._subMenuTimer;}
if(this._subMenu)
return;this._subMenu=new UI.SoftContextMenu(menuItemElement._subItems,this._itemSelectedCallback,this);const anchorBox=menuItemElement.boxInWindow();anchorBox.y-=5;anchorBox.x+=3;anchorBox.width-=6;anchorBox.height+=10;this._subMenu.show(this._document,anchorBox);}
_menuItemMouseOver(event){this._highlightMenuItem(event.target,true);}
_menuItemMouseLeave(event){if(!this._subMenu||!event.relatedTarget){this._highlightMenuItem(null,true);return;}
const relatedTarget=event.relatedTarget;if(relatedTarget===this._contextMenuElement)
this._highlightMenuItem(null,true);}
_highlightMenuItem(menuItemElement,scheduleSubMenu){if(this._highlightedMenuItemElement===menuItemElement)
return;if(this._subMenu)
this._subMenu.discard();if(this._highlightedMenuItemElement){this._highlightedMenuItemElement.classList.remove('force-white-icons');this._highlightedMenuItemElement.classList.remove('soft-context-menu-item-mouse-over');if(this._highlightedMenuItemElement._subItems&&this._highlightedMenuItemElement._subMenuTimer){clearTimeout(this._highlightedMenuItemElement._subMenuTimer);delete this._highlightedMenuItemElement._subMenuTimer;}}
this._highlightedMenuItemElement=menuItemElement;if(this._highlightedMenuItemElement){if(UI.themeSupport.hasTheme()||Host.isMac())
this._highlightedMenuItemElement.classList.add('force-white-icons');this._highlightedMenuItemElement.classList.add('soft-context-menu-item-mouse-over');if(this._highlightedMenuItemElement._customElement)
this._highlightedMenuItemElement._customElement.focus();else
this._highlightedMenuItemElement.focus();if(scheduleSubMenu&&this._highlightedMenuItemElement._subItems&&!this._highlightedMenuItemElement._subMenuTimer){this._highlightedMenuItemElement._subMenuTimer=setTimeout(this._showSubMenu.bind(this,this._highlightedMenuItemElement),150);}}}
_highlightPrevious(){let menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.previousSibling:this._contextMenuElement.lastChild;while(menuItemElement&&(menuItemElement._isSeparator||menuItemElement.classList.contains('soft-context-menu-disabled')))
menuItemElement=menuItemElement.previousSibling;if(menuItemElement)
this._highlightMenuItem(menuItemElement,false);}
_highlightNext(){let menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.nextSibling:this._contextMenuElement.firstChild;while(menuItemElement&&(menuItemElement._isSeparator||menuItemElement.classList.contains('soft-context-menu-disabled')))
menuItemElement=menuItemElement.nextSibling;if(menuItemElement)
this._highlightMenuItem(menuItemElement,false);}
_menuKeyDown(event){switch(event.key){case'ArrowUp':this._highlightPrevious();break;case'ArrowDown':this._highlightNext();break;case'ArrowLeft':if(this._parentMenu){this._highlightMenuItem(null,false);this.discard();}
break;case'ArrowRight':if(!this._highlightedMenuItemElement)
break;if(this._highlightedMenuItemElement._subItems){this._showSubMenu(this._highlightedMenuItemElement);this._subMenu._highlightNext();}
break;case'Escape':this.discard();break;case'Enter':if(!isEnterKey(event))
return;case' ':if(!this._highlightedMenuItemElement||this._highlightedMenuItemElement._customElement)
return;this._triggerAction(this._highlightedMenuItemElement,event);if(this._highlightedMenuItemElement._subItems)
this._subMenu._highlightNext();break;}
event.consume(true);}};;UI.SoftDropDown=class{constructor(model,delegate){this._delegate=delegate;this._selectedItem=null;this._model=model;this._placeholderText=ls`(no item selected)`;this.element=createElementWithClass('button','soft-dropdown');UI.appendStyle(this.element,'ui/softDropDownButton.css');this._titleElement=this.element.createChild('span','title');const dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down');this.element.appendChild(dropdownArrowIcon);this._glassPane=new UI.GlassPane();this._glassPane.setMarginBehavior(UI.GlassPane.MarginBehavior.NoMargin);this._glassPane.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferBottom);this._glassPane.setOutsideClickCallback(this._hide.bind(this));this._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this._list=new UI.ListControl(model,this,UI.ListMode.EqualHeightItems);this._list.element.classList.add('item-list');this._rowHeight=36;this._width=315;UI.createShadowRootWithCoreStyles(this._glassPane.contentElement,'ui/softDropDown.css').appendChild(this._list.element);this._listWasShowing200msAgo=false;this.element.addEventListener('mousedown',event=>{if(this._listWasShowing200msAgo)
this._hide(event);else if(!this.element.disabled)
this._show(event);},false);this.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this.element.addEventListener('focusout',this._hide.bind(this),false);this._list.element.addEventListener('mousedown',event=>event.consume(true),false);this._list.element.addEventListener('mouseup',event=>{if(event.target===this._list.element)
return;if(!this._listWasShowing200msAgo)
return;this._selectHighlightedItem();this._hide(event);},false);model.addEventListener(UI.ListModel.Events.ItemsReplaced,this._itemsReplaced,this);}
_show(event){if(this._glassPane.isShowing())
return;this._glassPane.setContentAnchorBox(this.element.boxInWindow());this._glassPane.show((this.element.ownerDocument));this._updateGlasspaneSize();if(this._selectedItem)
this._list.selectItem(this._selectedItem);this.element.focus();event.consume(true);setTimeout(()=>this._listWasShowing200msAgo=true,200);}
_updateGlasspaneSize(){const maxHeight=this._rowHeight*(Math.min(this._model.length,9));this._glassPane.setMaxContentSize(new UI.Size(this._width,maxHeight));this._list.viewportResized();}
_hide(event){setTimeout(()=>this._listWasShowing200msAgo=false,200);this._glassPane.hide();this._list.selectItem(null);event.consume(true);}
_onKeyDown(event){let handled=false;switch(event.key){case'ArrowLeft':case'ArrowUp':handled=this._list.selectPreviousItem(false,false);break;case'ArrowRight':case'ArrowDown':handled=this._list.selectNextItem(false,false);break;case'PageUp':handled=this._list.selectItemPreviousPage(false);break;case'PageDown':handled=this._list.selectItemNextPage(false);break;case'Home':for(let i=0;i<this._model.length;i++){if(this.isItemSelectable(this._model.at(i))){this._list.selectItem(this._model.at(i));handled=true;break;}}
break;case'End':for(let i=this._model.length-1;i>=0;i--){if(this.isItemSelectable(this._model.at(i))){this._list.selectItem(this._model.at(i));handled=true;break;}}
break;case'Escape':this._hide(event);break;case'Tab':if(!this._glassPane.isShowing())
break;this._selectHighlightedItem();this._hide(event);break;case'Enter':if(!this._glassPane.isShowing()){this._show(event);break;}
this._selectHighlightedItem();this._hide(event);break;case' ':this._show(event);break;default:if(event.key.length===1){const selectedIndex=this._list.selectedIndex();const letter=event.key.toUpperCase();for(let i=0;i<this._model.length;i++){const item=this._model.at((selectedIndex+i+1)%this._model.length);if(this._delegate.titleFor(item).toUpperCase().startsWith(letter)){this._list.selectItem(item);break;}}
handled=true;}
break;}
if(handled){event.consume(true);this._selectHighlightedItem();}}
setWidth(width){this._width=width;this._updateGlasspaneSize();}
setRowHeight(rowHeight){this._rowHeight=rowHeight;}
setPlaceholderText(text){this._placeholderText=text;if(!this._selectedItem)
this._titleElement.textContent=this._placeholderText;}
_itemsReplaced(event){const removed=(event.data.removed);if(removed.indexOf(this._selectedItem)!==-1){this._selectedItem=null;this._selectHighlightedItem();}
this._updateGlasspaneSize();}
selectItem(item){this._selectedItem=item;if(this._selectedItem)
this._titleElement.textContent=this._delegate.titleFor(this._selectedItem);else
this._titleElement.textContent=this._placeholderText;this._delegate.itemSelected(this._selectedItem);}
createElementForItem(item){const element=createElementWithClass('div','item');element.addEventListener('mousemove',e=>{if((e.movementX||e.movementY)&&this._delegate.isItemSelectable(item))
this._list.selectItem(item,false,true);});element.classList.toggle('disabled',!this._delegate.isItemSelectable(item));element.classList.toggle('highlighted',this._list.selectedItem()===item);element.appendChild(this._delegate.createElementForItem(item));return element;}
heightForItem(item){return this._rowHeight;}
isItemSelectable(item){return this._delegate.isItemSelectable(item);}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('highlighted');if(toElement)
toElement.classList.add('highlighted');this._delegate.highlightedItemChanged(from,to,fromElement&&fromElement.firstElementChild,toElement&&toElement.firstElementChild);}
_selectHighlightedItem(){this.selectItem(this._list.selectedItem());}
refreshItem(item){this._list.refreshItem(item);}};UI.SoftDropDown.Delegate=class{titleFor(item){}
createElementForItem(item){}
isItemSelectable(item){}
itemSelected(item){}
highlightedItemChanged(from,to,fromElement,toElement){}};;UI.SplitWidget=class extends UI.Widget{constructor(isVertical,secondIsSidebar,settingName,defaultSidebarWidth,defaultSidebarHeight,constraintsInDip){super(true);this.element.classList.add('split-widget');this.registerRequiredCSS('ui/splitWidget.css');this.contentElement.classList.add('shadow-split-widget');this._sidebarElement=this.contentElement.createChild('div','shadow-split-widget-contents shadow-split-widget-sidebar vbox');this._mainElement=this.contentElement.createChild('div','shadow-split-widget-contents shadow-split-widget-main vbox');this._mainElement.createChild('slot').name='insertion-point-main';this._sidebarElement.createChild('slot').name='insertion-point-sidebar';this._resizerElement=this.contentElement.createChild('div','shadow-split-widget-resizer');this._resizerElementSize=null;this._resizerWidget=new UI.SimpleResizerWidget();this._resizerWidget.setEnabled(true);this._resizerWidget.addEventListener(UI.ResizerWidget.Events.ResizeStart,this._onResizeStart,this);this._resizerWidget.addEventListener(UI.ResizerWidget.Events.ResizeUpdate,this._onResizeUpdate,this);this._resizerWidget.addEventListener(UI.ResizerWidget.Events.ResizeEnd,this._onResizeEnd,this);this._defaultSidebarWidth=defaultSidebarWidth||200;this._defaultSidebarHeight=defaultSidebarHeight||this._defaultSidebarWidth;this._constraintsInDip=!!constraintsInDip;this._resizeStartSizeDIP=0;this._setting=settingName?Common.settings.createSetting(settingName,{}):null;this._totalSizeCSS=0;this._totalSizeOtherDimensionCSS=0;this._mainWidget=null;this._sidebarWidget=null;this._animationFrameHandle=0;this._animationCallback=null;this._showHideSidebarButtonTitle='';this._showHideSidebarButton=null;this._isVertical=false;this._sidebarMinimized=false;this._detaching=false;this._sidebarSizeDIP=-1;this._savedSidebarSizeDIP=this._sidebarSizeDIP;this._secondIsSidebar=false;this._shouldSaveShowMode=false;this._savedVerticalMainSize=null;this._savedHorizontalMainSize=null;this.setSecondIsSidebar(secondIsSidebar);this._innerSetVertical(isVertical);this._showMode=UI.SplitWidget.ShowMode.Both;this._savedShowMode=this._showMode;this.installResizer(this._resizerElement);}
isVertical(){return this._isVertical;}
setVertical(isVertical){if(this._isVertical===isVertical)
return;this._innerSetVertical(isVertical);if(this.isShowing())
this._updateLayout();}
_innerSetVertical(isVertical){this.contentElement.classList.toggle('vbox',!isVertical);this.contentElement.classList.toggle('hbox',isVertical);this._isVertical=isVertical;this._resizerElementSize=null;this._sidebarSizeDIP=-1;this._restoreSidebarSizeFromSettings();if(this._shouldSaveShowMode)
this._restoreAndApplyShowModeFromSettings();this._updateShowHideSidebarButton();this._resizerWidget.setVertical(!isVertical);this.invalidateConstraints();}
_updateLayout(animate){this._totalSizeCSS=0;this._totalSizeOtherDimensionCSS=0;this._mainElement.style.removeProperty('width');this._mainElement.style.removeProperty('height');this._sidebarElement.style.removeProperty('width');this._sidebarElement.style.removeProperty('height');this._innerSetSidebarSizeDIP(this._preferredSidebarSizeDIP(),!!animate);}
setMainWidget(widget){if(this._mainWidget===widget)
return;this.suspendInvalidations();if(this._mainWidget)
this._mainWidget.detach();this._mainWidget=widget;if(widget){widget.element.slot='insertion-point-main';if(this._showMode===UI.SplitWidget.ShowMode.OnlyMain||this._showMode===UI.SplitWidget.ShowMode.Both)
widget.show(this.element);}
this.resumeInvalidations();}
setSidebarWidget(widget){if(this._sidebarWidget===widget)
return;this.suspendInvalidations();if(this._sidebarWidget)
this._sidebarWidget.detach();this._sidebarWidget=widget;if(widget){widget.element.slot='insertion-point-sidebar';if(this._showMode===UI.SplitWidget.ShowMode.OnlySidebar||this._showMode===UI.SplitWidget.ShowMode.Both)
widget.show(this.element);}
this.resumeInvalidations();}
mainWidget(){return this._mainWidget;}
sidebarWidget(){return this._sidebarWidget;}
childWasDetached(widget){if(this._detaching)
return;if(this._mainWidget===widget)
this._mainWidget=null;if(this._sidebarWidget===widget)
this._sidebarWidget=null;this.invalidateConstraints();}
isSidebarSecond(){return this._secondIsSidebar;}
enableShowModeSaving(){this._shouldSaveShowMode=true;this._restoreAndApplyShowModeFromSettings();}
showMode(){return this._showMode;}
setSecondIsSidebar(secondIsSidebar){if(secondIsSidebar===this._secondIsSidebar)
return;this._secondIsSidebar=secondIsSidebar;if(!this._mainWidget||!this._mainWidget.shouldHideOnDetach()){if(secondIsSidebar)
this.contentElement.insertBefore(this._mainElement,this._sidebarElement);else
this.contentElement.insertBefore(this._mainElement,this._resizerElement);}else if(!this._sidebarWidget||!this._sidebarWidget.shouldHideOnDetach()){if(secondIsSidebar)
this.contentElement.insertBefore(this._sidebarElement,this._resizerElement);else
this.contentElement.insertBefore(this._sidebarElement,this._mainElement);}else{console.error('Could not swap split widget side. Both children widgets contain iframes.');this._secondIsSidebar=!secondIsSidebar;}}
sidebarSide(){if(this._showMode!==UI.SplitWidget.ShowMode.Both)
return null;return this._isVertical?(this._secondIsSidebar?'right':'left'):(this._secondIsSidebar?'bottom':'top');}
resizerElement(){return this._resizerElement;}
hideMain(animate){this._showOnly(this._sidebarWidget,this._mainWidget,this._sidebarElement,this._mainElement,animate);this._updateShowMode(UI.SplitWidget.ShowMode.OnlySidebar);}
hideSidebar(animate){this._showOnly(this._mainWidget,this._sidebarWidget,this._mainElement,this._sidebarElement,animate);this._updateShowMode(UI.SplitWidget.ShowMode.OnlyMain);}
setSidebarMinimized(minimized){this._sidebarMinimized=minimized;this.invalidateConstraints();}
isSidebarMinimized(){return this._sidebarMinimized;}
_showOnly(sideToShow,sideToHide,shadowToShow,shadowToHide,animate){this._cancelAnimation();function callback(){if(sideToShow){if(sideToShow===this._mainWidget)
this._mainWidget.show(this.element,this._sidebarWidget?this._sidebarWidget.element:null);else
this._sidebarWidget.show(this.element);}
if(sideToHide){this._detaching=true;sideToHide.detach();this._detaching=false;}
this._resizerElement.classList.add('hidden');shadowToShow.classList.remove('hidden');shadowToShow.classList.add('maximized');shadowToHide.classList.add('hidden');shadowToHide.classList.remove('maximized');this._removeAllLayoutProperties();this.doResize();this._showFinishedForTest();}
if(animate)
this._animate(true,callback.bind(this));else
callback.call(this);this._sidebarSizeDIP=-1;this.setResizable(false);}
_showFinishedForTest(){}
_removeAllLayoutProperties(){this._sidebarElement.style.removeProperty('flexBasis');this._mainElement.style.removeProperty('width');this._mainElement.style.removeProperty('height');this._sidebarElement.style.removeProperty('width');this._sidebarElement.style.removeProperty('height');this._resizerElement.style.removeProperty('left');this._resizerElement.style.removeProperty('right');this._resizerElement.style.removeProperty('top');this._resizerElement.style.removeProperty('bottom');this._resizerElement.style.removeProperty('margin-left');this._resizerElement.style.removeProperty('margin-right');this._resizerElement.style.removeProperty('margin-top');this._resizerElement.style.removeProperty('margin-bottom');}
showBoth(animate){if(this._showMode===UI.SplitWidget.ShowMode.Both)
animate=false;this._cancelAnimation();this._mainElement.classList.remove('maximized','hidden');this._sidebarElement.classList.remove('maximized','hidden');this._resizerElement.classList.remove('hidden');this.setResizable(true);this.suspendInvalidations();if(this._sidebarWidget)
this._sidebarWidget.show(this.element);if(this._mainWidget)
this._mainWidget.show(this.element,this._sidebarWidget?this._sidebarWidget.element:null);this.resumeInvalidations();this.setSecondIsSidebar(this._secondIsSidebar);this._sidebarSizeDIP=-1;this._updateShowMode(UI.SplitWidget.ShowMode.Both);this._updateLayout(animate);}
setResizable(resizable){this._resizerWidget.setEnabled(resizable);}
isResizable(){return this._resizerWidget.isEnabled();}
setSidebarSize(size){const sizeDIP=UI.zoomManager.cssToDIP(size);this._savedSidebarSizeDIP=sizeDIP;this._saveSetting();this._innerSetSidebarSizeDIP(sizeDIP,false,true);}
sidebarSize(){const sizeDIP=Math.max(0,this._sidebarSizeDIP);return UI.zoomManager.dipToCSS(sizeDIP);}
_totalSizeDIP(){if(!this._totalSizeCSS){this._totalSizeCSS=this._isVertical?this.contentElement.offsetWidth:this.contentElement.offsetHeight;this._totalSizeOtherDimensionCSS=this._isVertical?this.contentElement.offsetHeight:this.contentElement.offsetWidth;}
return UI.zoomManager.cssToDIP(this._totalSizeCSS);}
_updateShowMode(showMode){this._showMode=showMode;this._saveShowModeToSettings();this._updateShowHideSidebarButton();this.dispatchEventToListeners(UI.SplitWidget.Events.ShowModeChanged,showMode);this.invalidateConstraints();}
_innerSetSidebarSizeDIP(sizeDIP,animate,userAction){if(this._showMode!==UI.SplitWidget.ShowMode.Both||!this.isShowing())
return;sizeDIP=this._applyConstraints(sizeDIP,userAction);if(this._sidebarSizeDIP===sizeDIP)
return;if(!this._resizerElementSize){this._resizerElementSize=this._isVertical?this._resizerElement.offsetWidth:this._resizerElement.offsetHeight;}
this._removeAllLayoutProperties();const roundSizeCSS=Math.round(UI.zoomManager.dipToCSS(sizeDIP));const sidebarSizeValue=roundSizeCSS+'px';const mainSizeValue=(this._totalSizeCSS-roundSizeCSS)+'px';this._sidebarElement.style.flexBasis=sidebarSizeValue;if(this._isVertical){this._sidebarElement.style.width=sidebarSizeValue;this._mainElement.style.width=mainSizeValue;this._sidebarElement.style.height=this._totalSizeOtherDimensionCSS+'px';this._mainElement.style.height=this._totalSizeOtherDimensionCSS+'px';}else{this._sidebarElement.style.height=sidebarSizeValue;this._mainElement.style.height=mainSizeValue;this._sidebarElement.style.width=this._totalSizeOtherDimensionCSS+'px';this._mainElement.style.width=this._totalSizeOtherDimensionCSS+'px';}
if(this._isVertical){if(this._secondIsSidebar){this._resizerElement.style.right=sidebarSizeValue;this._resizerElement.style.marginRight=-this._resizerElementSize/2+'px';}else{this._resizerElement.style.left=sidebarSizeValue;this._resizerElement.style.marginLeft=-this._resizerElementSize/2+'px';}}else{if(this._secondIsSidebar){this._resizerElement.style.bottom=sidebarSizeValue;this._resizerElement.style.marginBottom=-this._resizerElementSize/2+'px';}else{this._resizerElement.style.top=sidebarSizeValue;this._resizerElement.style.marginTop=-this._resizerElementSize/2+'px';}}
this._sidebarSizeDIP=sizeDIP;if(animate){this._animate(false);}else{this.doResize();this.dispatchEventToListeners(UI.SplitWidget.Events.SidebarSizeChanged,this.sidebarSize());}}
_animate(reverse,callback){const animationTime=50;this._animationCallback=callback||null;let animatedMarginPropertyName;if(this._isVertical)
animatedMarginPropertyName=this._secondIsSidebar?'margin-right':'margin-left';else
animatedMarginPropertyName=this._secondIsSidebar?'margin-bottom':'margin-top';const marginFrom=reverse?'0':'-'+UI.zoomManager.dipToCSS(this._sidebarSizeDIP)+'px';const marginTo=reverse?'-'+UI.zoomManager.dipToCSS(this._sidebarSizeDIP)+'px':'0';this.contentElement.style.setProperty(animatedMarginPropertyName,marginFrom);if(!reverse){suppressUnused(this._mainElement.offsetWidth);suppressUnused(this._sidebarElement.offsetWidth);}
if(!reverse)
this._sidebarWidget.doResize();this.contentElement.style.setProperty('transition',animatedMarginPropertyName+' '+animationTime+'ms linear');const boundAnimationFrame=animationFrame.bind(this);let startTime;function animationFrame(){this._animationFrameHandle=0;if(!startTime){this.contentElement.style.setProperty(animatedMarginPropertyName,marginTo);startTime=window.performance.now();}else if(window.performance.now()<startTime+animationTime){if(this._mainWidget)
this._mainWidget.doResize();}else{this._cancelAnimation();if(this._mainWidget)
this._mainWidget.doResize();this.dispatchEventToListeners(UI.SplitWidget.Events.SidebarSizeChanged,this.sidebarSize());return;}
this._animationFrameHandle=this.contentElement.window().requestAnimationFrame(boundAnimationFrame);}
this._animationFrameHandle=this.contentElement.window().requestAnimationFrame(boundAnimationFrame);}
_cancelAnimation(){this.contentElement.style.removeProperty('margin-top');this.contentElement.style.removeProperty('margin-right');this.contentElement.style.removeProperty('margin-bottom');this.contentElement.style.removeProperty('margin-left');this.contentElement.style.removeProperty('transition');if(this._animationFrameHandle){this.contentElement.window().cancelAnimationFrame(this._animationFrameHandle);this._animationFrameHandle=0;}
if(this._animationCallback){this._animationCallback();this._animationCallback=null;}}
_applyConstraints(sidebarSize,userAction){const totalSize=this._totalSizeDIP();const zoomFactor=this._constraintsInDip?1:UI.zoomManager.zoomFactor();let constraints=this._sidebarWidget?this._sidebarWidget.constraints():new UI.Constraints();let minSidebarSize=this.isVertical()?constraints.minimum.width:constraints.minimum.height;if(!minSidebarSize)
minSidebarSize=UI.SplitWidget.MinPadding;minSidebarSize*=zoomFactor;if(this._sidebarMinimized)
sidebarSize=minSidebarSize;let preferredSidebarSize=this.isVertical()?constraints.preferred.width:constraints.preferred.height;if(!preferredSidebarSize)
preferredSidebarSize=UI.SplitWidget.MinPadding;preferredSidebarSize*=zoomFactor;if(sidebarSize<preferredSidebarSize)
preferredSidebarSize=Math.max(sidebarSize,minSidebarSize);preferredSidebarSize+=zoomFactor;constraints=this._mainWidget?this._mainWidget.constraints():new UI.Constraints();let minMainSize=this.isVertical()?constraints.minimum.width:constraints.minimum.height;if(!minMainSize)
minMainSize=UI.SplitWidget.MinPadding;minMainSize*=zoomFactor;let preferredMainSize=this.isVertical()?constraints.preferred.width:constraints.preferred.height;if(!preferredMainSize)
preferredMainSize=UI.SplitWidget.MinPadding;preferredMainSize*=zoomFactor;const savedMainSize=this.isVertical()?this._savedVerticalMainSize:this._savedHorizontalMainSize;if(savedMainSize!==null)
preferredMainSize=Math.min(preferredMainSize,savedMainSize*zoomFactor);if(userAction)
preferredMainSize=minMainSize;const totalPreferred=preferredMainSize+preferredSidebarSize;if(totalPreferred<=totalSize)
return Number.constrain(sidebarSize,preferredSidebarSize,totalSize-preferredMainSize);if(minMainSize+minSidebarSize<=totalSize){const delta=totalPreferred-totalSize;const sidebarDelta=delta*preferredSidebarSize/totalPreferred;sidebarSize=preferredSidebarSize-sidebarDelta;return Number.constrain(sidebarSize,minSidebarSize,totalSize-minMainSize);}
return Math.max(0,totalSize-minMainSize);}
wasShown(){this._forceUpdateLayout();UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._onZoomChanged,this);}
willHide(){UI.zoomManager.removeEventListener(UI.ZoomManager.Events.ZoomChanged,this._onZoomChanged,this);}
onResize(){this._updateLayout();}
onLayout(){this._updateLayout();}
calculateConstraints(){if(this._showMode===UI.SplitWidget.ShowMode.OnlyMain)
return this._mainWidget?this._mainWidget.constraints():new UI.Constraints();if(this._showMode===UI.SplitWidget.ShowMode.OnlySidebar)
return this._sidebarWidget?this._sidebarWidget.constraints():new UI.Constraints();let mainConstraints=this._mainWidget?this._mainWidget.constraints():new UI.Constraints();let sidebarConstraints=this._sidebarWidget?this._sidebarWidget.constraints():new UI.Constraints();const min=UI.SplitWidget.MinPadding;if(this._isVertical){mainConstraints=mainConstraints.widthToMax(min).addWidth(1);sidebarConstraints=sidebarConstraints.widthToMax(min);return mainConstraints.addWidth(sidebarConstraints).heightToMax(sidebarConstraints);}else{mainConstraints=mainConstraints.heightToMax(min).addHeight(1);sidebarConstraints=sidebarConstraints.heightToMax(min);return mainConstraints.widthToMax(sidebarConstraints).addHeight(sidebarConstraints);}}
_onResizeStart(event){this._resizeStartSizeDIP=this._sidebarSizeDIP;}
_onResizeUpdate(event){const offset=event.data.currentPosition-event.data.startPosition;const offsetDIP=UI.zoomManager.cssToDIP(offset);const newSizeDIP=this._secondIsSidebar?this._resizeStartSizeDIP-offsetDIP:this._resizeStartSizeDIP+offsetDIP;const constrainedSizeDIP=this._applyConstraints(newSizeDIP,true);this._savedSidebarSizeDIP=constrainedSizeDIP;this._saveSetting();this._innerSetSidebarSizeDIP(constrainedSizeDIP,false,true);if(this.isVertical())
this._savedVerticalMainSize=this._totalSizeDIP()-this._sidebarSizeDIP;else
this._savedHorizontalMainSize=this._totalSizeDIP()-this._sidebarSizeDIP;}
_onResizeEnd(event){this._resizeStartSizeDIP=0;}
hideDefaultResizer(noSplitter){this.uninstallResizer(this._resizerElement);this._sidebarElement.classList.toggle('no-default-splitter',!!noSplitter);}
installResizer(resizerElement){this._resizerWidget.addElement(resizerElement);}
uninstallResizer(resizerElement){this._resizerWidget.removeElement(resizerElement);}
hasCustomResizer(){const elements=this._resizerWidget.elements();return elements.length>1||(elements.length===1&&elements[0]!==this._resizerElement);}
toggleResizer(resizer,on){if(on)
this.installResizer(resizer);else
this.uninstallResizer(resizer);}
_settingForOrientation(){const state=this._setting?this._setting.get():{};return this._isVertical?state.vertical:state.horizontal;}
_preferredSidebarSizeDIP(){let size=this._savedSidebarSizeDIP;if(!size){size=this._isVertical?this._defaultSidebarWidth:this._defaultSidebarHeight;if(0<size&&size<1)
size*=this._totalSizeDIP();}
return size;}
_restoreSidebarSizeFromSettings(){const settingForOrientation=this._settingForOrientation();this._savedSidebarSizeDIP=settingForOrientation?settingForOrientation.size:0;}
_restoreAndApplyShowModeFromSettings(){const orientationState=this._settingForOrientation();this._savedShowMode=orientationState&&orientationState.showMode?orientationState.showMode:this._showMode;this._showMode=this._savedShowMode;switch(this._savedShowMode){case UI.SplitWidget.ShowMode.Both:this.showBoth();break;case UI.SplitWidget.ShowMode.OnlyMain:this.hideSidebar();break;case UI.SplitWidget.ShowMode.OnlySidebar:this.hideMain();break;}}
_saveShowModeToSettings(){this._savedShowMode=this._showMode;this._saveSetting();}
_saveSetting(){if(!this._setting)
return;const state=this._setting.get();const orientationState=(this._isVertical?state.vertical:state.horizontal)||{};orientationState.size=this._savedSidebarSizeDIP;if(this._shouldSaveShowMode)
orientationState.showMode=this._savedShowMode;if(this._isVertical)
state.vertical=orientationState;else
state.horizontal=orientationState;this._setting.set(state);}
_forceUpdateLayout(){this._sidebarSizeDIP=-1;this._updateLayout();}
_onZoomChanged(event){this._forceUpdateLayout();}
createShowHideSidebarButton(title){this._showHideSidebarButtonTitle=Common.UIString(title);this._showHideSidebarButton=new UI.ToolbarButton('','');this._showHideSidebarButton.addEventListener(UI.ToolbarButton.Events.Click,buttonClicked,this);this._updateShowHideSidebarButton();function buttonClicked(event){if(this._showMode!==UI.SplitWidget.ShowMode.Both)
this.showBoth(true);else
this.hideSidebar(true);}
return this._showHideSidebarButton;}
_updateShowHideSidebarButton(){if(!this._showHideSidebarButton)
return;const sidebarHidden=this._showMode===UI.SplitWidget.ShowMode.OnlyMain;let glyph='';if(sidebarHidden){glyph=this.isVertical()?(this.isSidebarSecond()?'largeicon-show-right-sidebar':'largeicon-show-left-sidebar'):(this.isSidebarSecond()?'largeicon-show-bottom-sidebar':'largeicon-show-top-sidebar');}else{glyph=this.isVertical()?(this.isSidebarSecond()?'largeicon-hide-right-sidebar':'largeicon-hide-left-sidebar'):(this.isSidebarSecond()?'largeicon-hide-bottom-sidebar':'largeicon-hide-top-sidebar');}
this._showHideSidebarButton.setGlyph(glyph);this._showHideSidebarButton.setTitle(sidebarHidden?Common.UIString('Show %s',this._showHideSidebarButtonTitle):Common.UIString('Hide %s',this._showHideSidebarButtonTitle));}};UI.SplitWidget.SettingForOrientation;UI.SplitWidget.ShowMode={Both:'Both',OnlyMain:'OnlyMain',OnlySidebar:'OnlySidebar'};UI.SplitWidget.Events={SidebarSizeChanged:Symbol('SidebarSizeChanged'),ShowModeChanged:Symbol('ShowModeChanged')};UI.SplitWidget.MinPadding=20;;UI.TargetCrashedScreen=class extends UI.VBox{constructor(hideCallback){super(true);this.registerRequiredCSS('ui/targetCrashedScreen.css');this.contentElement.createChild('div','message').textContent=Common.UIString('DevTools was disconnected from the page.');this.contentElement.createChild('div','message').textContent=Common.UIString('Once page is reloaded, DevTools will automatically reconnect.');this._hideCallback=hideCallback;}
willHide(){this._hideCallback.call(null);}};;UI.TextPrompt=class extends Common.Object{constructor(){super();this._proxyElement;this._proxyElementDisplay='inline-block';this._autocompletionTimeout=UI.TextPrompt.DefaultAutocompletionTimeout;this._title='';this._queryRange=null;this._previousText='';this._currentSuggestion=null;this._completionRequestId=0;this._ghostTextElement=createElementWithClass('span','auto-complete-text');this._ghostTextElement.setAttribute('contenteditable','false');UI.ARIAUtils.markAsHidden(this._ghostTextElement);}
initialize(completions,stopCharacters){this._loadCompletions=completions;this._completionStopCharacters=stopCharacters||' =:[({;,!+-*/&|^<>.';}
setAutocompletionTimeout(timeout){this._autocompletionTimeout=timeout;}
renderAsBlock(){this._proxyElementDisplay='block';}
attach(element){return this._attachInternal(element);}
attachAndStartEditing(element,blurListener){const proxyElement=this._attachInternal(element);this._startEditing(blurListener);return proxyElement;}
_attachInternal(element){if(this._proxyElement)
throw'Cannot attach an attached TextPrompt';this._element=element;this._boundOnKeyDown=this.onKeyDown.bind(this);this._boundOnInput=this.onInput.bind(this);this._boundOnMouseWheel=this.onMouseWheel.bind(this);this._boundClearAutocomplete=this.clearAutocomplete.bind(this);this._proxyElement=element.ownerDocument.createElement('span');UI.appendStyle(this._proxyElement,'ui/textPrompt.css');this._contentElement=this._proxyElement.createChild('div','text-prompt-root');this._proxyElement.style.display=this._proxyElementDisplay;element.parentElement.insertBefore(this._proxyElement,element);this._contentElement.appendChild(element);this._element.classList.add('text-prompt');UI.ARIAUtils.markAsTextBox(this._element);this._element.setAttribute('contenteditable','plaintext-only');this._element.addEventListener('keydown',this._boundOnKeyDown,false);this._element.addEventListener('input',this._boundOnInput,false);this._element.addEventListener('mousewheel',this._boundOnMouseWheel,false);this._element.addEventListener('selectstart',this._boundClearAutocomplete,false);this._element.addEventListener('blur',this._boundClearAutocomplete,false);this._suggestBox=new UI.SuggestBox(this,20);if(this._title)
this._proxyElement.title=this._title;return this._proxyElement;}
detach(){this._removeFromElement();this._focusRestorer.restore();this._proxyElement.parentElement.insertBefore(this._element,this._proxyElement);this._proxyElement.remove();delete this._proxyElement;this._element.classList.remove('text-prompt');this._element.removeAttribute('contenteditable');this._element.removeAttribute('role');}
textWithCurrentSuggestion(){const text=this.text();if(!this._queryRange||!this._currentSuggestion)
return text;const suggestion=this._currentSuggestion.text;return text.substring(0,this._queryRange.startColumn)+suggestion+text.substring(this._queryRange.endColumn);}
text(){let text=this._element.textContent;if(this._ghostTextElement.parentNode){const addition=this._ghostTextElement.textContent;text=text.substring(0,text.length-addition.length);}
return text;}
setText(text){this.clearAutocomplete();this._element.textContent=text;this._previousText=this.text();if(this._element.hasFocus()){this.moveCaretToEndOfPrompt();this._element.scrollIntoView();}}
focus(){this._element.focus();}
title(){return this._title;}
setTitle(title){this._title=title;if(this._proxyElement)
this._proxyElement.title=title;}
setPlaceholder(placeholder){if(placeholder){this._element.setAttribute('data-placeholder',placeholder);UI.ARIAUtils.setPlaceholder(this._element,placeholder);}else{this._element.removeAttribute('data-placeholder');UI.ARIAUtils.setPlaceholder(this._element,null);}}
setEnabled(enabled){if(enabled)
this._element.setAttribute('contenteditable','plaintext-only');else
this._element.removeAttribute('contenteditable');this._element.classList.toggle('disabled',!enabled);}
_removeFromElement(){this.clearAutocomplete();this._element.removeEventListener('keydown',this._boundOnKeyDown,false);this._element.removeEventListener('input',this._boundOnInput,false);this._element.removeEventListener('selectstart',this._boundClearAutocomplete,false);this._element.removeEventListener('blur',this._boundClearAutocomplete,false);if(this._isEditing)
this._stopEditing();if(this._suggestBox)
this._suggestBox.hide();}
_startEditing(blurListener){this._isEditing=true;this._contentElement.classList.add('text-prompt-editing');if(blurListener){this._blurListener=blurListener;this._element.addEventListener('blur',this._blurListener,false);}
this._oldTabIndex=this._element.tabIndex;if(this._element.tabIndex<0)
this._element.tabIndex=0;this._focusRestorer=new UI.ElementFocusRestorer(this._element);if(!this.text())
this.autoCompleteSoon();}
_stopEditing(){this._element.tabIndex=this._oldTabIndex;if(this._blurListener)
this._element.removeEventListener('blur',this._blurListener,false);this._contentElement.classList.remove('text-prompt-editing');delete this._isEditing;}
onMouseWheel(event){}
onKeyDown(event){let handled=false;if(this.isSuggestBoxVisible()&&this._suggestBox.keyPressed(event)){event.consume(true);return;}
switch(event.key){case'Tab':handled=this.tabKeyPressed(event);break;case'ArrowLeft':case'ArrowUp':case'PageUp':case'Home':this.clearAutocomplete();break;case'PageDown':case'ArrowRight':case'ArrowDown':case'End':if(this._isCaretAtEndOfPrompt())
handled=this.acceptAutoComplete();else
this.clearAutocomplete();break;case'Escape':if(this.isSuggestBoxVisible()){this.clearAutocomplete();handled=true;}
break;case' ':if(event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.shiftKey){this.autoCompleteSoon(true);handled=true;}
break;}
if(isEnterKey(event))
event.preventDefault();if(handled)
event.consume(true);}
_acceptSuggestionOnStopCharacters(key){if(!this._currentSuggestion||!this._queryRange||key.length!==1||!this._completionStopCharacters.includes(key))
return false;const query=this.text().substring(this._queryRange.startColumn,this._queryRange.endColumn);if(query&&this._currentSuggestion.text.startsWith(query+key)){this._queryRange.endColumn+=1;return this.acceptAutoComplete();}
return false;}
onInput(event){const text=this.text();if(event.data&&!this._acceptSuggestionOnStopCharacters(event.data)){const hasCommonPrefix=text.startsWith(this._previousText)||this._previousText.startsWith(text);if(this._queryRange&&hasCommonPrefix)
this._queryRange.endColumn+=text.length-this._previousText.length;}
this._refreshGhostText();this._previousText=text;this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);this.autoCompleteSoon();}
acceptAutoComplete(){let result=false;if(this.isSuggestBoxVisible())
result=this._suggestBox.acceptSuggestion();if(!result)
result=this._acceptSuggestionInternal();return result;}
clearAutocomplete(){const beforeText=this.textWithCurrentSuggestion();if(this.isSuggestBoxVisible())
this._suggestBox.hide();this._clearAutocompleteTimeout();this._queryRange=null;this._refreshGhostText();if(beforeText!==this.textWithCurrentSuggestion())
this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);}
_refreshGhostText(){if(this._currentSuggestion&&this._currentSuggestion.hideGhostText){this._ghostTextElement.remove();return;}
if(this._queryRange&&this._currentSuggestion&&this._isCaretAtEndOfPrompt()&&this._currentSuggestion.text.startsWith(this.text().substring(this._queryRange.startColumn))){this._ghostTextElement.textContent=this._currentSuggestion.text.substring(this._queryRange.endColumn-this._queryRange.startColumn);this._element.appendChild(this._ghostTextElement);}else{this._ghostTextElement.remove();}}
_clearAutocompleteTimeout(){if(this._completeTimeout){clearTimeout(this._completeTimeout);delete this._completeTimeout;}
this._completionRequestId++;}
autoCompleteSoon(force){const immediately=this.isSuggestBoxVisible()||force;if(!this._completeTimeout){this._completeTimeout=setTimeout(this.complete.bind(this,force),immediately?0:this._autocompletionTimeout);}}
async complete(force){this._clearAutocompleteTimeout();const selection=this._element.getComponentSelection();const selectionRange=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!selectionRange)
return;let shouldExit;if(!force&&!this._isCaretAtEndOfPrompt()&&!this.isSuggestBoxVisible())
shouldExit=true;else if(!selection.isCollapsed)
shouldExit=true;if(shouldExit){this.clearAutocomplete();return;}
const wordQueryRange=selectionRange.startContainer.rangeOfWord(selectionRange.startOffset,this._completionStopCharacters,this._element,'backward');const expressionRange=wordQueryRange.cloneRange();expressionRange.collapse(true);expressionRange.setStartBefore(this._element);const completionRequestId=++this._completionRequestId;const completions=await this._loadCompletions(expressionRange.toString(),wordQueryRange.toString(),!!force);this._completionsReady(completionRequestId,selection,wordQueryRange,!!force,completions);}
disableDefaultSuggestionForEmptyInput(){this._disableDefaultSuggestionForEmptyInput=true;}
_boxForAnchorAtStart(selection,textRange){const rangeCopy=selection.getRangeAt(0).cloneRange();const anchorElement=createElement('span');anchorElement.textContent='\u200B';textRange.insertNode(anchorElement);const box=anchorElement.boxInWindow(window);anchorElement.remove();selection.removeAllRanges();selection.addRange(rangeCopy);return box;}
_createRange(){return document.createRange();}
additionalCompletions(query){return[];}
_completionsReady(completionRequestId,selection,originalWordQueryRange,force,completions){if(this._completionRequestId!==completionRequestId)
return;const query=originalWordQueryRange.toString();const store=new Set();completions=completions.filter(item=>!store.has(item.text)&&!!store.add(item.text));if(query||force){if(query)
completions=completions.concat(this.additionalCompletions(query));else
completions=this.additionalCompletions(query).concat(completions);}
if(!completions.length){this.clearAutocomplete();return;}
const selectionRange=selection.getRangeAt(0);const fullWordRange=this._createRange();fullWordRange.setStart(originalWordQueryRange.startContainer,originalWordQueryRange.startOffset);fullWordRange.setEnd(selectionRange.endContainer,selectionRange.endOffset);if(query+selectionRange.toString()!==fullWordRange.toString())
return;const beforeRange=this._createRange();beforeRange.setStart(this._element,0);beforeRange.setEnd(fullWordRange.startContainer,fullWordRange.startOffset);this._queryRange=new TextUtils.TextRange(0,beforeRange.toString().length,0,beforeRange.toString().length+fullWordRange.toString().length);const shouldSelect=!this._disableDefaultSuggestionForEmptyInput||!!this.text();if(this._suggestBox){this._suggestBox.updateSuggestions(this._boxForAnchorAtStart(selection,fullWordRange),completions,shouldSelect,!this._isCaretAtEndOfPrompt(),this.text());}}
applySuggestion(suggestion,isIntermediateSuggestion){this._currentSuggestion=suggestion;this._refreshGhostText();if(isIntermediateSuggestion)
this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);}
acceptSuggestion(){this._acceptSuggestionInternal();}
_acceptSuggestionInternal(){if(!this._queryRange)
return false;const suggestionLength=this._currentSuggestion?this._currentSuggestion.text.length:0;const selectionRange=this._currentSuggestion?this._currentSuggestion.selectionRange:null;const endColumn=selectionRange?selectionRange.endColumn:suggestionLength;const startColumn=selectionRange?selectionRange.startColumn:suggestionLength;this._element.textContent=this.textWithCurrentSuggestion();this.setDOMSelection(this._queryRange.startColumn+startColumn,this._queryRange.startColumn+endColumn);this.clearAutocomplete();this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);return true;}
setDOMSelection(startColumn,endColumn){this._element.normalize();const node=this._element.childNodes[0];if(!node||node===this._ghostTextElement)
return;const range=this._createRange();range.setStart(node,startColumn);range.setEnd(node,endColumn);const selection=this._element.getComponentSelection();selection.removeAllRanges();selection.addRange(range);}
isSuggestBoxVisible(){return this._suggestBox&&this._suggestBox.visible();}
isCaretInsidePrompt(){const selection=this._element.getComponentSelection();const selectionRange=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!selectionRange||!selection.isCollapsed)
return false;return selectionRange.startContainer.isSelfOrDescendant(this._element);}
_isCaretAtEndOfPrompt(){const selection=this._element.getComponentSelection();const selectionRange=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!selectionRange||!selection.isCollapsed)
return false;let node=selectionRange.startContainer;if(!node.isSelfOrDescendant(this._element))
return false;if(this._ghostTextElement.isAncestor(node))
return true;if(node.nodeType===Node.TEXT_NODE&&selectionRange.startOffset<node.nodeValue.length)
return false;let foundNextText=false;while(node){if(node.nodeType===Node.TEXT_NODE&&node.nodeValue.length){if(foundNextText&&!this._ghostTextElement.isAncestor(node))
return false;foundNextText=true;}
node=node.traverseNextNode(this._element);}
return true;}
moveCaretToEndOfPrompt(){const selection=this._element.getComponentSelection();const selectionRange=this._createRange();let container=this._element;while(container.childNodes.length)
container=container.lastChild;const offset=container.nodeType===Node.TEXT_NODE?container.textContent.length:0;selectionRange.setStart(container,offset);selectionRange.setEnd(container,offset);selection.removeAllRanges();selection.addRange(selectionRange);}
tabKeyPressed(event){return this.acceptAutoComplete();}
proxyElementForTests(){return this._proxyElement||null;}};UI.TextPrompt.DefaultAutocompletionTimeout=250;UI.TextPrompt.Events={TextChanged:Symbol('TextChanged')};;UI.ThrottledWidget=class extends UI.VBox{constructor(isWebComponent,timeout){super(isWebComponent);this._updateThrottler=new Common.Throttler(timeout===undefined?100:timeout);this._updateWhenVisible=false;}
doUpdate(){return Promise.resolve();}
update(){this._updateWhenVisible=!this.isShowing();if(this._updateWhenVisible)
return;this._updateThrottler.schedule(innerUpdate.bind(this));function innerUpdate(){if(this.isShowing())
return this.doUpdate();this._updateWhenVisible=true;return Promise.resolve();}}
wasShown(){super.wasShown();if(this._updateWhenVisible)
this.update();}};;UI.Toolbar=class{constructor(className,parentElement){this._items=[];this.element=parentElement?parentElement.createChild('div'):createElement('div');this.element.className=className;this.element.classList.add('toolbar');this._enabled=true;this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/toolbar.css');this._contentElement=this._shadowRoot.createChild('div','toolbar-shadow');this._insertionPoint=this._contentElement.createChild('slot');}
static createActionButton(action,toggledOptions,untoggledOptions,showLabel){const button=new UI.ToolbarToggle(action.title(),action.icon(),action.toggledIcon());if(showLabel)
button.setText(action.title());button.setToggleWithRedColor(action.toggleWithRedColor());button.addEventListener(UI.ToolbarButton.Events.Click,action.execute,action);action.addEventListener(UI.Action.Events.Enabled,enabledChanged);action.addEventListener(UI.Action.Events.Toggled,toggled);let longClickController=null;let longClickButtons=null;let longClickGlyph=null;toggled();button.setEnabled(action.enabled());return button;function enabledChanged(event){button.setEnabled((event.data));}
function toggled(){button.setToggled(action.toggled());if(action.title())
UI.Tooltip.install(button.element,action.title(),action.id());updateOptions();}
function updateOptions(){const buttons=action.toggled()?(toggledOptions||null):(untoggledOptions||null);if(buttons&&buttons.length){if(!longClickController){longClickController=new UI.LongClickController(button.element,showOptions);longClickGlyph=UI.Icon.create('largeicon-longclick-triangle','long-click-glyph');button.element.appendChild(longClickGlyph);longClickButtons=buttons;}}else{if(longClickController){longClickController.dispose();longClickController=null;longClickGlyph.remove();longClickGlyph=null;longClickButtons=null;}}}
function showOptions(){let buttons=longClickButtons.slice();const mainButtonClone=new UI.ToolbarToggle(action.title(),action.icon(),action.toggledIcon());mainButtonClone.addEventListener(UI.ToolbarButton.Events.Click,clicked);function clicked(event){button._clicked((event.data));}
mainButtonClone.setToggled(action.toggled());buttons.push(mainButtonClone);const document=button.element.ownerDocument;document.documentElement.addEventListener('mouseup',mouseUp,false);const optionsGlassPane=new UI.GlassPane();optionsGlassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);optionsGlassPane.show(document);const optionsBar=new UI.Toolbar('fill',optionsGlassPane.contentElement);optionsBar._contentElement.classList.add('floating');const buttonHeight=26;const hostButtonPosition=button.element.boxInWindow().relativeToElement(UI.GlassPane.container(document));const topNotBottom=hostButtonPosition.y+buttonHeight*buttons.length<document.documentElement.offsetHeight;if(topNotBottom)
buttons=buttons.reverse();optionsBar.element.style.height=(buttonHeight*buttons.length)+'px';if(topNotBottom)
optionsBar.element.style.top=(hostButtonPosition.y-5)+'px';else
optionsBar.element.style.top=(hostButtonPosition.y-(buttonHeight*(buttons.length-1))-6)+'px';optionsBar.element.style.left=(hostButtonPosition.x-5)+'px';for(let i=0;i<buttons.length;++i){buttons[i].element.addEventListener('mousemove',mouseOver,false);buttons[i].element.addEventListener('mouseout',mouseOut,false);optionsBar.appendToolbarItem(buttons[i]);}
const hostButtonIndex=topNotBottom?0:buttons.length-1;buttons[hostButtonIndex].element.classList.add('emulate-active');function mouseOver(e){if(e.which!==1)
return;const buttonElement=e.target.enclosingNodeOrSelfWithClass('toolbar-item');buttonElement.classList.add('emulate-active');}
function mouseOut(e){if(e.which!==1)
return;const buttonElement=e.target.enclosingNodeOrSelfWithClass('toolbar-item');buttonElement.classList.remove('emulate-active');}
function mouseUp(e){if(e.which!==1)
return;optionsGlassPane.hide();document.documentElement.removeEventListener('mouseup',mouseUp,false);for(let i=0;i<buttons.length;++i){if(buttons[i].element.classList.contains('emulate-active')){buttons[i].element.classList.remove('emulate-active');buttons[i]._clicked(e);break;}}}}}
static createActionButtonForId(actionId,showLabel){const action=UI.actionRegistry.action(actionId);return UI.Toolbar.createActionButton((action),undefined,undefined,showLabel);}
gripElementForResize(){return this._contentElement;}
makeWrappable(growVertically){this._contentElement.classList.add('wrappable');if(growVertically)
this._contentElement.classList.add('toolbar-grow-vertical');}
makeVertical(){this._contentElement.classList.add('vertical');}
makeBlueOnHover(){this._contentElement.classList.add('toolbar-blue-on-hover');}
makeToggledGray(){this._contentElement.classList.add('toolbar-toggled-gray');}
renderAsLinks(){this._contentElement.classList.add('toolbar-render-as-links');}
empty(){return!this._items.length;}
setEnabled(enabled){this._enabled=enabled;for(const item of this._items)
item._applyEnabledState(this._enabled&&item._enabled);}
appendToolbarItem(item){this._items.push(item);item._toolbar=this;if(!this._enabled)
item._applyEnabledState(false);this._contentElement.insertBefore(item.element,this._insertionPoint);this._hideSeparatorDupes();}
appendSeparator(){this.appendToolbarItem(new UI.ToolbarSeparator());}
appendSpacer(){this.appendToolbarItem(new UI.ToolbarSeparator(true));}
appendText(text){this.appendToolbarItem(new UI.ToolbarText(text));}
removeToolbarItems(){for(const item of this._items)
delete item._toolbar;this._items=[];this._contentElement.removeChildren();this._insertionPoint=this._contentElement.createChild('slot');}
setColor(color){const style=createElement('style');style.textContent='.toolbar-glyph { background-color: '+color+' !important }';this._shadowRoot.appendChild(style);}
setToggledColor(color){const style=createElement('style');style.textContent='.toolbar-button.toolbar-state-on .toolbar-glyph { background-color: '+color+' !important }';this._shadowRoot.appendChild(style);}
_hideSeparatorDupes(){if(!this._items.length)
return;let previousIsSeparator=false;let lastSeparator;let nonSeparatorVisible=false;for(let i=0;i<this._items.length;++i){if(this._items[i]instanceof UI.ToolbarSeparator){this._items[i].setVisible(!previousIsSeparator);previousIsSeparator=true;lastSeparator=this._items[i];continue;}
if(this._items[i].visible()){previousIsSeparator=false;lastSeparator=null;nonSeparatorVisible=true;}}
if(lastSeparator&&lastSeparator!==this._items.peekLast())
lastSeparator.setVisible(false);this.element.classList.toggle('hidden',!!lastSeparator&&lastSeparator.visible()&&!nonSeparatorVisible);}
async appendItemsAtLocation(location){const extensions=self.runtime.extensions(UI.ToolbarItem.Provider);const filtered=extensions.filter(e=>e.descriptor()['location']===location);const items=await Promise.all(filtered.map(extension=>{const descriptor=extension.descriptor();if(descriptor['separator'])
return new UI.ToolbarSeparator();if(descriptor['actionId'])
return UI.Toolbar.createActionButtonForId(descriptor['actionId'],descriptor['showLabel']);return extension.instance().then(p=>p.item());}));items.filter(item=>item).forEach(item=>this.appendToolbarItem(item));}};UI.ToolbarItem=class extends Common.Object{constructor(element){super();this.element=element;this.element.classList.add('toolbar-item');this._visible=true;this._enabled=true;}
setTitle(title){if(this._title===title)
return;this._title=title;UI.ARIAUtils.setAccessibleName(this.element,title);UI.Tooltip.install(this.element,title);}
setEnabled(value){if(this._enabled===value)
return;this._enabled=value;this._applyEnabledState(this._enabled&&(!this._toolbar||this._toolbar._enabled));}
_applyEnabledState(enabled){this.element.disabled=!enabled;}
visible(){return this._visible;}
setVisible(x){if(this._visible===x)
return;this.element.classList.toggle('hidden',!x);this._visible=x;if(this._toolbar&&!(this instanceof UI.ToolbarSeparator))
this._toolbar._hideSeparatorDupes();}
setRightAligned(alignRight){this.element.classList.toggle('toolbar-item-right-aligned',alignRight);}};UI.ToolbarText=class extends UI.ToolbarItem{constructor(text){super(createElementWithClass('div','toolbar-text'));this.element.classList.add('toolbar-text');this.setText(text||'');}
text(){return this.element.textContent;}
setText(text){this.element.textContent=text;}};UI.ToolbarButton=class extends UI.ToolbarItem{constructor(title,glyph,text){super(createElementWithClass('button','toolbar-button'));this.element.addEventListener('click',this._clicked.bind(this),false);this.element.addEventListener('mousedown',this._mouseDown.bind(this),false);this._glyphElement=UI.Icon.create('','toolbar-glyph hidden');this.element.appendChild(this._glyphElement);this._textElement=this.element.createChild('div','toolbar-text hidden');this.setTitle(title);if(glyph)
this.setGlyph(glyph);this.setText(text||'');this._title='';}
setText(text){if(this._text===text)
return;this._textElement.textContent=text;this._textElement.classList.toggle('hidden',!text);this._text=text;}
setGlyph(glyph){if(this._glyph===glyph)
return;this._glyphElement.setIconType(glyph);this._glyphElement.classList.toggle('hidden',!glyph);this.element.classList.toggle('toolbar-has-glyph',!!glyph);this._glyph=glyph;}
setBackgroundImage(iconURL){this.element.style.backgroundImage='url('+iconURL+')';}
setDarkText(){this.element.classList.add('dark-text');}
turnIntoSelect(width){this.element.classList.add('toolbar-has-dropdown');const dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down','toolbar-dropdown-arrow');this.element.appendChild(dropdownArrowIcon);if(width)
this.element.style.width=width+'px';}
_clicked(event){if(!this._enabled)
return;this.dispatchEventToListeners(UI.ToolbarButton.Events.Click,event);event.consume();}
_mouseDown(event){if(!this._enabled)
return;this.dispatchEventToListeners(UI.ToolbarButton.Events.MouseDown,event);}};UI.ToolbarButton.Events={Click:Symbol('Click'),MouseDown:Symbol('MouseDown')};UI.ToolbarInput=class extends UI.ToolbarItem{constructor(placeholder,growFactor,shrinkFactor,tooltip,completions){super(createElementWithClass('div','toolbar-input'));const internalPromptElement=this.element.createChild('div','toolbar-input-prompt');internalPromptElement.addEventListener('focus',()=>this.element.classList.add('focused'));internalPromptElement.addEventListener('blur',()=>this.element.classList.remove('focused'));this._prompt=new UI.TextPrompt();this._proxyElement=this._prompt.attach(internalPromptElement);this._proxyElement.classList.add('toolbar-prompt-proxy');this._proxyElement.addEventListener('keydown',event=>this._onKeydownCallback(event));this._prompt.initialize(completions||(()=>Promise.resolve([])),' ');if(tooltip)
this._prompt.setTitle(tooltip);this._prompt.setPlaceholder(placeholder);this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._onChangeCallback.bind(this));if(growFactor)
this.element.style.flexGrow=growFactor;if(shrinkFactor)
this.element.style.flexShrink=shrinkFactor;const clearButton=this.element.createChild('div','toolbar-input-clear-button');clearButton.appendChild(UI.Icon.create('mediumicon-gray-cross-hover','search-cancel-button'));clearButton.addEventListener('click',()=>{this.setValue('',true);this._prompt.focus();});this._updateEmptyStyles();}
_applyEnabledState(enabled){this._prompt.setEnabled(enabled);}
setValue(value,notify){this._prompt.setText(value);if(notify)
this._onChangeCallback();this._updateEmptyStyles();}
value(){return this._prompt.textWithCurrentSuggestion();}
_onKeydownCallback(event){if(!isEscKey(event)||!this._prompt.text())
return;this.setValue('',true);event.consume(true);}
_onChangeCallback(){this._updateEmptyStyles();this.dispatchEventToListeners(UI.ToolbarInput.Event.TextChanged,this._prompt.text());}
_updateEmptyStyles(){this.element.classList.toggle('toolbar-input-empty',!this._prompt.text());}};UI.ToolbarInput.Event={TextChanged:Symbol('TextChanged')};UI.ToolbarToggle=class extends UI.ToolbarButton{constructor(title,glyph,toggledGlyph){super(title,glyph,'');this._toggled=false;this._untoggledGlyph=glyph;this._toggledGlyph=toggledGlyph;this.element.classList.add('toolbar-state-off');UI.ARIAUtils.setPressed(this.element,false);}
toggled(){return this._toggled;}
setToggled(toggled){if(this._toggled===toggled)
return;this._toggled=toggled;this.element.classList.toggle('toolbar-state-on',toggled);this.element.classList.toggle('toolbar-state-off',!toggled);UI.ARIAUtils.setPressed(this.element,toggled);if(this._toggledGlyph&&this._untoggledGlyph)
this.setGlyph(toggled?this._toggledGlyph:this._untoggledGlyph);}
setDefaultWithRedColor(withRedColor){this.element.classList.toggle('toolbar-default-with-red-color',withRedColor);}
setToggleWithRedColor(toggleWithRedColor){this.element.classList.toggle('toolbar-toggle-with-red-color',toggleWithRedColor);}};UI.ToolbarMenuButton=class extends UI.ToolbarButton{constructor(contextMenuHandler,useSoftMenu){super('','largeicon-menu');this._contextMenuHandler=contextMenuHandler;this._useSoftMenu=!!useSoftMenu;}
_mouseDown(event){if(event.buttons!==1){super._mouseDown(event);return;}
if(!this._triggerTimeout)
this._triggerTimeout=setTimeout(this._trigger.bind(this,event),200);}
_trigger(event){delete this._triggerTimeout;if(this._lastTriggerTime&&Date.now()-this._lastTriggerTime<300)
return;const contextMenu=new UI.ContextMenu(event,this._useSoftMenu,this.element.totalOffsetLeft(),this.element.totalOffsetTop()+this.element.offsetHeight);this._contextMenuHandler(contextMenu);contextMenu.show();this._lastTriggerTime=Date.now();}
_clicked(event){if(this._triggerTimeout)
clearTimeout(this._triggerTimeout);this._trigger(event);}};UI.ToolbarSettingToggle=class extends UI.ToolbarToggle{constructor(setting,glyph,title,toggledTitle){super(title,glyph);this._defaultTitle=title;this._toggledTitle=toggledTitle||title;this._setting=setting;this._settingChanged();this._setting.addChangeListener(this._settingChanged,this);}
_settingChanged(){const toggled=this._setting.get();this.setToggled(toggled);this.setTitle(toggled?this._toggledTitle:this._defaultTitle);}
_clicked(event){this._setting.set(!this.toggled());super._clicked(event);}};UI.ToolbarSeparator=class extends UI.ToolbarItem{constructor(spacer){super(createElementWithClass('div',spacer?'toolbar-spacer':'toolbar-divider'));}};UI.ToolbarItem.Provider=function(){};UI.ToolbarItem.Provider.prototype={item(){}};UI.ToolbarItem.ItemsProvider=function(){};UI.ToolbarItem.ItemsProvider.prototype={toolbarItems(){}};UI.ToolbarComboBox=class extends UI.ToolbarItem{constructor(changeHandler,className){super(createElementWithClass('span','toolbar-select-container'));this._selectElement=this.element.createChild('select','toolbar-item');const dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down','toolbar-dropdown-arrow');this.element.appendChild(dropdownArrowIcon);if(changeHandler)
this._selectElement.addEventListener('change',changeHandler,false);if(className)
this._selectElement.classList.add(className);}
setTitle(title){UI.ARIAUtils.setAccessibleName(this._selectElement,title);super.setTitle(title);}
selectElement(){return(this._selectElement);}
size(){return this._selectElement.childElementCount;}
options(){return Array.prototype.slice.call(this._selectElement.children,0);}
addOption(option){this._selectElement.appendChild(option);}
createOption(label,title,value){const option=this._selectElement.createChild('option');option.text=label;if(title)
option.title=title;if(typeof value!=='undefined')
option.value=value;return option;}
_applyEnabledState(enabled){super._applyEnabledState(enabled);this._selectElement.disabled=!enabled;}
removeOption(option){this._selectElement.removeChild(option);}
removeOptions(){this._selectElement.removeChildren();}
selectedOption(){if(this._selectElement.selectedIndex>=0)
return this._selectElement[this._selectElement.selectedIndex];return null;}
select(option){this._selectElement.selectedIndex=Array.prototype.indexOf.call((this._selectElement),option);}
setSelectedIndex(index){this._selectElement.selectedIndex=index;}
selectedIndex(){return this._selectElement.selectedIndex;}
setMaxWidth(width){this._selectElement.style.maxWidth=width+'px';}
setMinWidth(width){this._selectElement.style.minWidth=width+'px';}};UI.ToolbarSettingComboBox=class extends UI.ToolbarComboBox{constructor(options,setting,optGroup){super(null);this._setting=setting;this._options=options;this._selectElement.addEventListener('change',this._valueChanged.bind(this),false);if(optGroup){const optGroupElement=this._selectElement.createChild('optgroup');optGroupElement.label=optGroup;this._optionContainer=optGroupElement;}else{this._optionContainer=this._selectElement;}
this.setOptions(options);setting.addChangeListener(this._settingChanged,this);}
setOptions(options){this._options=options;this._optionContainer.removeChildren();for(let i=0;i<options.length;++i){const dataOption=options[i];const option=this.createOption(dataOption.label,dataOption.title,dataOption.value);this._optionContainer.appendChild(option);if(this._setting.get()===dataOption.value)
this.setSelectedIndex(i);}}
value(){return this._options[this.selectedIndex()].value;}
_settingChanged(){if(this._muteSettingListener)
return;const value=this._setting.get();for(let i=0;i<this._options.length;++i){if(value===this._options[i].value){this.setSelectedIndex(i);break;}}}
_valueChanged(event){const option=this._options[this.selectedIndex()];this._muteSettingListener=true;this._setting.set(option.value);this._muteSettingListener=false;}};UI.ToolbarCheckbox=class extends UI.ToolbarItem{constructor(text,tooltip,listener){super(UI.CheckboxLabel.create(text));this.element.classList.add('checkbox');this.inputElement=this.element.checkboxElement;if(tooltip)
this.element.title=tooltip;if(listener)
this.inputElement.addEventListener('click',listener,false);}
checked(){return this.inputElement.checked;}
setChecked(value){this.inputElement.checked=value;}
_applyEnabledState(enabled){super._applyEnabledState(enabled);this.inputElement.disabled=!enabled;}};UI.ToolbarSettingCheckbox=class extends UI.ToolbarCheckbox{constructor(setting,tooltip,alternateTitle){super(alternateTitle||setting.title()||'',tooltip);UI.SettingsUI.bindCheckbox(this.inputElement,setting);}};;UI.Tooltip=class{constructor(doc){this.element=doc.body.createChild('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/tooltip.css');this._tooltipElement=this._shadowRoot.createChild('div','tooltip');doc.addEventListener('mousemove',this._mouseMove.bind(this),true);doc.addEventListener('mousedown',this._hide.bind(this,true),true);doc.addEventListener('mouseleave',this._hide.bind(this,false),true);doc.addEventListener('keydown',this._hide.bind(this,true),true);UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._reset,this);doc.defaultView.addEventListener('resize',this._reset.bind(this),false);}
static installHandler(doc){new UI.Tooltip(doc);}
static install(element,tooltipContent,actionId,options){if(!tooltipContent){delete element[UI.Tooltip._symbol];return;}
element[UI.Tooltip._symbol]={content:tooltipContent,actionId:actionId,options:options||{}};}
static addNativeOverrideContainer(element){UI.Tooltip._nativeOverrideContainer.push(element);}
_mouseMove(event){const mouseEvent=(event);const path=mouseEvent.composedPath();if(!path||mouseEvent.buttons!==0||(mouseEvent.movementX===0&&mouseEvent.movementY===0))
return;if(this._anchorElement&&path.indexOf(this._anchorElement)===-1)
this._hide(false);for(const element of path){if(element===this._anchorElement)
return;if(!(element instanceof Element)||element.offsetParent===null)
continue;if(element[UI.Tooltip._symbol]){this._show(element,mouseEvent);return;}}}
_show(anchorElement,event){const tooltip=anchorElement[UI.Tooltip._symbol];this._anchorElement=anchorElement;this._tooltipElement.removeChildren();for(const element of UI.Tooltip._nativeOverrideContainer){if(this._anchorElement.isSelfOrDescendant(element)){Object.defineProperty(this._anchorElement,'title',UI.Tooltip._nativeTitle);this._anchorElement.title=tooltip.content;return;}}
if(typeof tooltip.content==='string')
this._tooltipElement.setTextContentTruncatedIfNeeded(tooltip.content);else
this._tooltipElement.appendChild(tooltip.content);if(tooltip.actionId){const shortcuts=UI.shortcutRegistry.shortcutDescriptorsForAction(tooltip.actionId);for(const shortcut of shortcuts){const shortcutElement=this._tooltipElement.createChild('div','tooltip-shortcut');shortcutElement.textContent=shortcut.name;}}
this._tooltipElement.classList.add('shown');this._tooltipElement.positionAt(0,0);const now=Date.now();const instant=(this._tooltipLastClosed&&now-this._tooltipLastClosed<UI.Tooltip.Timing.InstantThreshold);this._tooltipElement.classList.toggle('instant',instant);this._tooltipLastOpened=instant?now:now+UI.Tooltip.Timing.OpeningDelay;const container=UI.GlassPane.container((anchorElement.ownerDocument));const containerBox=container.boxInWindow(this.element.window());const anchorBox=this._anchorElement.boxInWindow(this.element.window());const anchorOffset=2;const pageMargin=2;const cursorOffset=10;this._tooltipElement.classList.toggle('tooltip-breakword',!this._tooltipElement.textContent.match('\\s'));this._tooltipElement.style.maxWidth=(containerBox.width-pageMargin*2)+'px';this._tooltipElement.style.maxHeight='';const tooltipWidth=this._tooltipElement.offsetWidth;const tooltipHeight=this._tooltipElement.offsetHeight;const anchorTooltipAtElement=this._anchorElement.nodeName==='BUTTON'||this._anchorElement.nodeName==='LABEL';let tooltipX=anchorTooltipAtElement?anchorBox.x:event.x+cursorOffset;tooltipX=Number.constrain(tooltipX,containerBox.x+pageMargin,containerBox.x+containerBox.width-tooltipWidth-pageMargin);let tooltipY;if(!anchorTooltipAtElement){tooltipY=event.y+cursorOffset+tooltipHeight<containerBox.y+containerBox.height?event.y+cursorOffset:event.y-tooltipHeight-1;}else{const onBottom=anchorBox.y+anchorOffset+anchorBox.height+tooltipHeight<containerBox.y+containerBox.height;tooltipY=onBottom?anchorBox.y+anchorBox.height+anchorOffset:anchorBox.y-tooltipHeight-anchorOffset;}
this._tooltipElement.positionAt(tooltipX,tooltipY);}
_hide(removeInstant){delete this._anchorElement;this._tooltipElement.classList.remove('shown');if(Date.now()>this._tooltipLastOpened)
this._tooltipLastClosed=Date.now();if(removeInstant)
delete this._tooltipLastClosed;}
_reset(){this._hide(true);this._tooltipElement.positionAt(0,0);this._tooltipElement.style.maxWidth='0';this._tooltipElement.style.maxHeight='0';}};UI.Tooltip.Timing={'InstantThreshold':300,'OpeningDelay':600};UI.Tooltip._symbol=Symbol('Tooltip');UI.Tooltip._nativeOverrideContainer=[];UI.Tooltip._nativeTitle=(Object.getOwnPropertyDescriptor(HTMLElement.prototype,'title'));Object.defineProperty(HTMLElement.prototype,'title',{get:function(){const tooltip=this[UI.Tooltip._symbol];return tooltip?tooltip.content:'';},set:function(x){UI.Tooltip.install(this,x);}});;UI.SuggestBoxDelegate=function(){};UI.SuggestBoxDelegate.prototype={applySuggestion(suggestion,isIntermediateSuggestion){},acceptSuggestion(){},};UI.SuggestBox=class{constructor(suggestBoxDelegate,maxItemsHeight){this._suggestBoxDelegate=suggestBoxDelegate;this._maxItemsHeight=maxItemsHeight;this._rowHeight=17;this._userEnteredText='';this._defaultSelectionIsDimmed=false;this._onlyCompletion=null;this._items=new UI.ListModel();this._list=new UI.ListControl(this._items,this,UI.ListMode.EqualHeightItems);this._element=this._list.element;this._element.classList.add('suggest-box');this._element.addEventListener('mousedown',event=>event.preventDefault(),true);this._element.addEventListener('click',this._onClick.bind(this),false);this._glassPane=new UI.GlassPane();this._glassPane.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferBottom);this._glassPane.setOutsideClickCallback(this.hide.bind(this));const shadowRoot=UI.createShadowRootWithCoreStyles(this._glassPane.contentElement,'ui/suggestBox.css');shadowRoot.appendChild(this._element);}
visible(){return this._glassPane.isShowing();}
setPosition(anchorBox){this._glassPane.setContentAnchorBox(anchorBox);}
setAnchorBehavior(behavior){this._glassPane.setAnchorBehavior(behavior);}
_updateMaxSize(items){const maxWidth=this._maxWidth(items);const length=this._maxItemsHeight?Math.min(this._maxItemsHeight,items.length):items.length;const maxHeight=length*this._rowHeight;this._glassPane.setMaxContentSize(new UI.Size(maxWidth,maxHeight));}
_maxWidth(items){const kMaxWidth=300;if(!items.length)
return kMaxWidth;let maxItem;let maxLength=-Infinity;for(let i=0;i<items.length;i++){const length=(items[i].title||items[i].text).length+(items[i].subtitle||'').length;if(length>maxLength){maxLength=length;maxItem=items[i];}}
const element=this.createElementForItem((maxItem));const preferredWidth=UI.measurePreferredSize(element,this._element).width+UI.measuredScrollbarWidth(this._element.ownerDocument);return Math.min(kMaxWidth,preferredWidth);}
_show(){if(this.visible())
return;this._glassPane.show(document);this._rowHeight=UI.measurePreferredSize(this.createElementForItem({text:'1',subtitle:'12'}),this._element).height;}
hide(){if(!this.visible())
return;this._glassPane.hide();}
_applySuggestion(isIntermediateSuggestion){if(this._onlyCompletion){UI.ARIAUtils.alert(ls`${this._onlyCompletion.text}, suggestion`,this._element);this._suggestBoxDelegate.applySuggestion(this._onlyCompletion,isIntermediateSuggestion);return true;}
const suggestion=this._list.selectedItem();if(suggestion&&suggestion.text)
UI.ARIAUtils.alert(ls`${suggestion.title || suggestion.text}, suggestion`,this._element);this._suggestBoxDelegate.applySuggestion(suggestion,isIntermediateSuggestion);return this.visible()&&!!suggestion;}
acceptSuggestion(){const result=this._applySuggestion();this.hide();if(!result)
return false;this._suggestBoxDelegate.acceptSuggestion();return true;}
createElementForItem(item){const query=this._userEnteredText;const element=createElementWithClass('div','suggest-box-content-item source-code');if(item.iconType){const icon=UI.Icon.create(item.iconType,'suggestion-icon');element.appendChild(icon);}
if(item.isSecondary)
element.classList.add('secondary');element.tabIndex=-1;const maxTextLength=50+query.length;const displayText=(item.title||item.text).trim().trimEnd(maxTextLength).replace(/\n/g,'\u21B5');const titleElement=element.createChild('span','suggestion-title');const index=displayText.toLowerCase().indexOf(query.toLowerCase());if(index>0)
titleElement.createChild('span').textContent=displayText.substring(0,index);if(index>-1)
titleElement.createChild('span','query').textContent=displayText.substring(index,index+query.length);titleElement.createChild('span').textContent=displayText.substring(index>-1?index+query.length:0);titleElement.createChild('span','spacer');if(item.subtitleRenderer){const subtitleElement=item.subtitleRenderer.call(null);subtitleElement.classList.add('suggestion-subtitle');element.appendChild(subtitleElement);}else if(item.subtitle){const subtitleElement=element.createChild('span','suggestion-subtitle');subtitleElement.textContent=item.subtitle.trimEnd(maxTextLength-displayText.length);}
return element;}
heightForItem(item){return this._rowHeight;}
isItemSelectable(item){return true;}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('selected','force-white-icons');if(toElement){toElement.classList.add('selected');toElement.classList.add('force-white-icons');}
this._applySuggestion(true);}
_onClick(event){const item=this._list.itemForNode((event.target));if(!item)
return;this._list.selectItem(item);this.acceptSuggestion();event.consume(true);}
_canShowBox(completions,highestPriorityItem,canShowForSingleItem,userEnteredText){if(!completions||!completions.length)
return false;if(completions.length>1)
return true;if(!highestPriorityItem||highestPriorityItem.isSecondary||!highestPriorityItem.text.startsWith(userEnteredText))
return true;return canShowForSingleItem&&highestPriorityItem.text!==userEnteredText;}
updateSuggestions(anchorBox,completions,selectHighestPriority,canShowForSingleItem,userEnteredText){this._onlyCompletion=null;const highestPriorityItem=selectHighestPriority?completions.reduce((a,b)=>(a.priority||0)>=(b.priority||0)?a:b):null;if(this._canShowBox(completions,highestPriorityItem,canShowForSingleItem,userEnteredText)){this._userEnteredText=userEnteredText;this._show();this._updateMaxSize(completions);this._glassPane.setContentAnchorBox(anchorBox);this._list.invalidateItemHeight();this._items.replaceAll(completions);if(highestPriorityItem&&!highestPriorityItem.isSecondary)
this._list.selectItem(highestPriorityItem,true);else
this._list.selectItem(null);}else{if(completions.length===1){this._onlyCompletion=completions[0];this._applySuggestion(true);}
this.hide();}}
keyPressed(event){switch(event.key){case'Enter':return this.enterKeyPressed();case'ArrowUp':return this._list.selectPreviousItem(true,false);case'ArrowDown':return this._list.selectNextItem(true,false);case'PageUp':return this._list.selectItemPreviousPage(false);case'PageDown':return this._list.selectItemNextPage(false);}
return false;}
enterKeyPressed(){const hasSelectedItem=!!this._list.selectedItem()||!!this._onlyCompletion;this.acceptSuggestion();return hasSelectedItem;}};UI.SuggestBox.Suggestion;UI.SuggestBox.Suggestions;;UI.TabbedPane=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('ui/tabbedPane.css');this.element.classList.add('tabbed-pane');this.contentElement.classList.add('tabbed-pane-shadow');this.contentElement.tabIndex=-1;this._headerElement=this.contentElement.createChild('div','tabbed-pane-header');this._headerContentsElement=this._headerElement.createChild('div','tabbed-pane-header-contents');this._tabSlider=createElementWithClass('div','tabbed-pane-tab-slider');this._tabsElement=this._headerContentsElement.createChild('div','tabbed-pane-header-tabs');this._tabsElement.setAttribute('role','tablist');this._tabsElement.addEventListener('keydown',this._keyDown.bind(this),false);this._contentElement=this.contentElement.createChild('div','tabbed-pane-content');this._contentElement.setAttribute('role','tabpanel');this._contentElement.createChild('slot');this._tabs=[];this._tabsHistory=[];this._tabsById=new Map();this._currentTabLocked=false;this._autoSelectFirstItemOnShow=true;this._triggerDropDownTimeout=null;this._dropDownButton=this._createDropDownButton();UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._zoomChanged,this);this.makeTabSlider();}
setAccessibleName(name){UI.ARIAUtils.setAccessibleName(this._tabsElement,name);}
setCurrentTabLocked(locked){this._currentTabLocked=locked;this._headerElement.classList.toggle('locked',this._currentTabLocked);}
setAutoSelectFirstItemOnShow(autoSelect){this._autoSelectFirstItemOnShow=autoSelect;}
get visibleView(){return this._currentTab?this._currentTab.view:null;}
tabIds(){return this._tabs.map(tab=>tab._id);}
tabIndex(tabId){return this._tabs.findIndex(tab=>tab.id===tabId);}
tabViews(){return this._tabs.map(tab=>tab.view);}
tabView(tabId){return this._tabsById.has(tabId)?this._tabsById.get(tabId).view:null;}
get selectedTabId(){return this._currentTab?this._currentTab.id:null;}
setShrinkableTabs(shrinkableTabs){this._shrinkableTabs=shrinkableTabs;}
makeVerticalTabLayout(){this._verticalTabLayout=true;this._setTabSlider(false);this.contentElement.classList.add('vertical-tab-layout');this.invalidateConstraints();}
setCloseableTabs(closeableTabs){this._closeableTabs=closeableTabs;}
focus(){if(this.visibleView)
this.visibleView.focus();else
this.contentElement.focus();}
headerElement(){return this._headerElement;}
isTabCloseable(id){const tab=this._tabsById.get(id);return tab?tab.isCloseable():false;}
setTabDelegate(delegate){const tabs=this._tabs.slice();for(let i=0;i<tabs.length;++i)
tabs[i].setDelegate(delegate);this._delegate=delegate;}
appendTab(id,tabTitle,view,tabTooltip,userGesture,isCloseable,index){isCloseable=typeof isCloseable==='boolean'?isCloseable:this._closeableTabs;const tab=new UI.TabbedPaneTab(this,id,tabTitle,isCloseable,view,tabTooltip);tab.setDelegate(this._delegate);console.assert(!this._tabsById.has(id),`Tabbed pane already contains a tab with id '${id}'`);this._tabsById.set(id,tab);if(index!==undefined)
this._tabs.splice(index,0,tab);else
this._tabs.push(tab);this._tabsHistory.push(tab);if(this._tabsHistory[0]===tab&&this.isShowing())
this.selectTab(tab.id,userGesture);this._updateTabElements();}
closeTab(id,userGesture){this.closeTabs([id],userGesture);}
closeTabs(ids,userGesture){const focused=this.hasFocus();for(let i=0;i<ids.length;++i)
this._innerCloseTab(ids[i],userGesture);this._updateTabElements();if(this._tabsHistory.length)
this.selectTab(this._tabsHistory[0].id,false);if(focused)
this.focus();}
_innerCloseTab(id,userGesture){if(!this._tabsById.has(id))
return;if(userGesture&&!this._tabsById.get(id)._closeable)
return;if(this._currentTab&&this._currentTab.id===id)
this._hideCurrentTab();const tab=this._tabsById.get(id);this._tabsById.delete(id);this._tabsHistory.splice(this._tabsHistory.indexOf(tab),1);this._tabs.splice(this._tabs.indexOf(tab),1);if(tab._shown)
this._hideTabElement(tab);const eventData={tabId:id,view:tab.view,isUserGesture:userGesture};this.dispatchEventToListeners(UI.TabbedPane.Events.TabClosed,eventData);return true;}
hasTab(tabId){return this._tabsById.has(tabId);}
otherTabs(id){const result=[];for(let i=0;i<this._tabs.length;++i){if(this._tabs[i].id!==id)
result.push(this._tabs[i].id);}
return result;}
_tabsToTheRight(id){let index=-1;for(let i=0;i<this._tabs.length;++i){if(this._tabs[i].id===id){index=i;break;}}
if(index===-1)
return[];return this._tabs.slice(index+1).map(function(tab){return tab.id;});}
_viewHasFocus(){if(this.visibleView&&this.visibleView.hasFocus())
return true;return this.contentElement===this.contentElement.getComponentRoot().activeElement;}
selectTab(id,userGesture){if(this._currentTabLocked)
return false;const focused=this._viewHasFocus();const tab=this._tabsById.get(id);if(!tab)
return false;if(this._currentTab&&this._currentTab.id===id)
return true;this.suspendInvalidations();this._hideCurrentTab();this._showTab(tab);this.resumeInvalidations();this._currentTab=tab;this._tabsHistory.splice(this._tabsHistory.indexOf(tab),1);this._tabsHistory.splice(0,0,tab);this._updateTabElements();if(focused)
this.focus();const eventData={tabId:id,view:tab.view,isUserGesture:userGesture};this.dispatchEventToListeners(UI.TabbedPane.Events.TabSelected,eventData);return true;}
selectNextTab(){const index=this._tabs.indexOf(this._currentTab);const nextIndex=mod(index+1,this._tabs.length);this.selectTab(this._tabs[nextIndex].id,true);}
selectPrevTab(){const index=this._tabs.indexOf(this._currentTab);const nextIndex=mod(index-1,this._tabs.length);this.selectTab(this._tabs[nextIndex].id,true);}
lastOpenedTabIds(tabsCount){function tabToTabId(tab){return tab.id;}
return this._tabsHistory.slice(0,tabsCount).map(tabToTabId);}
setTabIcon(id,icon){const tab=this._tabsById.get(id);tab._setIcon(icon);this._updateTabElements();}
setTabEnabled(id,enabled){const tab=this._tabsById.get(id);tab.tabElement.classList.toggle('disabled',!enabled);}
toggleTabClass(id,className,force){const tab=this._tabsById.get(id);if(tab._toggleClass(className,force))
this._updateTabElements();}
_zoomChanged(event){for(let i=0;i<this._tabs.length;++i)
delete this._tabs[i]._measuredWidth;if(this.isShowing())
this._updateTabElements();}
changeTabTitle(id,tabTitle,tabTooltip){const tab=this._tabsById.get(id);if(tabTooltip!==undefined)
tab.tooltip=tabTooltip;if(tab.title!==tabTitle){tab.title=tabTitle;this._updateTabElements();}}
changeTabView(id,view){const tab=this._tabsById.get(id);if(tab.view===view)
return;this.suspendInvalidations();const isSelected=this._currentTab&&this._currentTab.id===id;const shouldFocus=tab.view.hasFocus();if(isSelected)
this._hideTab(tab);tab.view=view;if(isSelected)
this._showTab(tab);if(shouldFocus)
tab.view.focus();this.resumeInvalidations();}
onResize(){this._updateTabElements();}
headerResized(){this._updateTabElements();}
wasShown(){const effectiveTab=this._currentTab||this._tabsHistory[0];if(effectiveTab&&this._autoSelectFirstItemOnShow)
this.selectTab(effectiveTab.id);}
makeTabSlider(){if(this._verticalTabLayout)
return;this._setTabSlider(true);}
_setTabSlider(enable){this._sliderEnabled=enable;this._tabSlider.classList.toggle('enabled',enable);}
calculateConstraints(){let constraints=super.calculateConstraints();const minContentConstraints=new UI.Constraints(new UI.Size(0,0),new UI.Size(50,50));constraints=constraints.widthToMax(minContentConstraints).heightToMax(minContentConstraints);if(this._verticalTabLayout)
constraints=constraints.addWidth(new UI.Constraints(new UI.Size(120,0)));else
constraints=constraints.addHeight(new UI.Constraints(new UI.Size(0,30)));return constraints;}
_updateTabElements(){UI.invokeOnceAfterBatchUpdate(this,this._innerUpdateTabElements);}
setPlaceholderElement(element){this._placeholderElement=element;if(this._placeholderContainerElement){this._placeholderContainerElement.removeChildren();this._placeholderContainerElement.appendChild(element);}}
_innerUpdateTabElements(){if(!this.isShowing())
return;if(!this._tabs.length){this._contentElement.classList.add('has-no-tabs');if(this._placeholderElement&&!this._placeholderContainerElement){this._placeholderContainerElement=this._contentElement.createChild('div','tabbed-pane-placeholder fill');this._placeholderContainerElement.appendChild(this._placeholderElement);}}else{this._contentElement.classList.remove('has-no-tabs');if(this._placeholderContainerElement){this._placeholderContainerElement.remove();delete this._placeholderContainerElement;}}
this._measureDropDownButton();this._updateWidths();this._updateTabsDropDown();this._updateTabSlider();}
_showTabElement(index,tab){if(index>=this._tabsElement.children.length)
this._tabsElement.appendChild(tab.tabElement);else
this._tabsElement.insertBefore(tab.tabElement,this._tabsElement.children[index]);tab._shown=true;}
_hideTabElement(tab){this._tabsElement.removeChild(tab.tabElement);tab._shown=false;}
_createDropDownButton(){const dropDownContainer=createElementWithClass('div','tabbed-pane-header-tabs-drop-down-container');const chevronIcon=UI.Icon.create('largeicon-chevron','chevron-icon');UI.ARIAUtils.markAsButton(dropDownContainer);UI.ARIAUtils.setAccessibleName(dropDownContainer,ls`More tabs`);dropDownContainer.appendChild(chevronIcon);dropDownContainer.addEventListener('click',this._dropDownClicked.bind(this));dropDownContainer.addEventListener('mousedown',event=>{if(event.which!==1||this._triggerDropDownTimeout)
return;this._triggerDropDownTimeout=setTimeout(this._dropDownClicked.bind(this,event),200);});return dropDownContainer;}
_dropDownClicked(event){if(event.which!==1)
return;if(this._triggerDropDownTimeout){clearTimeout(this._triggerDropDownTimeout);this._triggerDropDownTimeout=null;}
const rect=this._dropDownButton.getBoundingClientRect();const menu=new UI.ContextMenu(event,false,rect.left,rect.bottom);for(let i=0;i<this._tabs.length;++i){const tab=this._tabs[i];if(tab._shown)
continue;menu.defaultSection().appendCheckboxItem(tab.title,this._dropDownMenuItemSelected.bind(this,tab),this._tabsHistory[0]===tab);}
menu.show();}
_dropDownMenuItemSelected(tab){this._lastSelectedOverflowTab=tab;this.selectTab(tab.id,true);}
_totalWidth(){return this._headerContentsElement.getBoundingClientRect().width;}
_numberOfTabsShown(){let numTabsShown=0;for(const tab of this._tabs){if(tab._shown)
numTabsShown++;}
return numTabsShown;}
disableOverflowMenu(){this._overflowDisabled=true;}
_updateTabsDropDown(){const tabsToShowIndexes=this._tabsToShowIndexes(this._tabs,this._tabsHistory,this._totalWidth(),this._measuredDropDownButtonWidth||0);if(this._lastSelectedOverflowTab&&this._numberOfTabsShown()!==tabsToShowIndexes.length){delete this._lastSelectedOverflowTab;this._updateTabsDropDown();return;}
for(let i=0;i<this._tabs.length;++i){if(this._tabs[i]._shown&&tabsToShowIndexes.indexOf(i)===-1)
this._hideTabElement(this._tabs[i]);}
for(let i=0;i<tabsToShowIndexes.length;++i){const tab=this._tabs[tabsToShowIndexes[i]];if(!tab._shown)
this._showTabElement(i,tab);}
if(!this._overflowDisabled)
this._maybeShowDropDown(tabsToShowIndexes.length!==this._tabs.length);}
_maybeShowDropDown(hasMoreTabs){if(hasMoreTabs&&!this._dropDownButton.parentElement)
this._headerContentsElement.appendChild(this._dropDownButton);else if(!hasMoreTabs&&this._dropDownButton.parentElement)
this._headerContentsElement.removeChild(this._dropDownButton);}
_measureDropDownButton(){if(this._overflowDisabled||this._measuredDropDownButtonWidth)
return;this._dropDownButton.classList.add('measuring');this._headerContentsElement.appendChild(this._dropDownButton);this._measuredDropDownButtonWidth=this._dropDownButton.getBoundingClientRect().width;this._headerContentsElement.removeChild(this._dropDownButton);this._dropDownButton.classList.remove('measuring');}
_updateWidths(){const measuredWidths=this._measureWidths();const maxWidth=this._shrinkableTabs?this._calculateMaxWidth(measuredWidths.slice(),this._totalWidth()):Number.MAX_VALUE;let i=0;for(const tab of this._tabs)
tab.setWidth(this._verticalTabLayout?-1:Math.min(maxWidth,measuredWidths[i++]));}
_measureWidths(){this._tabsElement.style.setProperty('width','2000px');const measuringTabElements=[];for(const tab of this._tabs){if(typeof tab._measuredWidth==='number')
continue;const measuringTabElement=tab._createTabElement(true);measuringTabElement.__tab=tab;measuringTabElements.push(measuringTabElement);this._tabsElement.appendChild(measuringTabElement);}
for(let i=0;i<measuringTabElements.length;++i){const width=measuringTabElements[i].getBoundingClientRect().width;measuringTabElements[i].__tab._measuredWidth=Math.ceil(width);}
for(let i=0;i<measuringTabElements.length;++i)
measuringTabElements[i].remove();const measuredWidths=[];for(const tab of this._tabs)
measuredWidths.push(tab._measuredWidth);this._tabsElement.style.removeProperty('width');return measuredWidths;}
_calculateMaxWidth(measuredWidths,totalWidth){if(!measuredWidths.length)
return 0;measuredWidths.sort(function(x,y){return x-y;});let totalMeasuredWidth=0;for(let i=0;i<measuredWidths.length;++i)
totalMeasuredWidth+=measuredWidths[i];if(totalWidth>=totalMeasuredWidth)
return measuredWidths[measuredWidths.length-1];let totalExtraWidth=0;for(let i=measuredWidths.length-1;i>0;--i){const extraWidth=measuredWidths[i]-measuredWidths[i-1];totalExtraWidth+=(measuredWidths.length-i)*extraWidth;if(totalWidth+totalExtraWidth>=totalMeasuredWidth){return measuredWidths[i-1]+
(totalWidth+totalExtraWidth-totalMeasuredWidth)/(measuredWidths.length-i);}}
return totalWidth/measuredWidths.length;}
_tabsToShowIndexes(tabsOrdered,tabsHistory,totalWidth,measuredDropDownButtonWidth){const tabsToShowIndexes=[];let totalTabsWidth=0;const tabCount=tabsOrdered.length;const tabsToLookAt=tabsOrdered.slice(0);if(this._currentTab!==undefined)
tabsToLookAt.unshift(tabsToLookAt.splice(tabsToLookAt.indexOf(this._currentTab),1)[0]);if(this._lastSelectedOverflowTab!==undefined)
tabsToLookAt.unshift(tabsToLookAt.splice(tabsToLookAt.indexOf(this._lastSelectedOverflowTab),1)[0]);for(let i=0;i<tabCount;++i){const tab=this._automaticReorder?tabsHistory[i]:tabsToLookAt[i];totalTabsWidth+=tab.width();let minimalRequiredWidth=totalTabsWidth;if(i!==tabCount-1)
minimalRequiredWidth+=measuredDropDownButtonWidth;if(!this._verticalTabLayout&&minimalRequiredWidth>totalWidth)
break;tabsToShowIndexes.push(tabsOrdered.indexOf(tab));}
tabsToShowIndexes.sort(function(x,y){return x-y;});return tabsToShowIndexes;}
_hideCurrentTab(){if(!this._currentTab)
return;this._hideTab(this._currentTab);delete this._currentTab;}
_showTab(tab){tab.tabElement.tabIndex=0;tab.tabElement.classList.add('selected');UI.ARIAUtils.setSelected(tab.tabElement,true);tab.view.show(this.element);this._updateTabSlider();}
_updateTabSlider(){if(!this._sliderEnabled)
return;if(!this._currentTab){this._tabSlider.style.width=0;return;}
let left=0;for(let i=0;i<this._tabs.length&&this._currentTab!==this._tabs[i];i++){if(this._tabs[i]._shown)
left+=this._tabs[i]._measuredWidth;}
const sliderWidth=this._currentTab._shown?this._currentTab._measuredWidth:this._dropDownButton.offsetWidth;const scaleFactor=window.devicePixelRatio>=1.5?' scaleY(0.75)':'';this._tabSlider.style.transform='translateX('+left+'px)'+scaleFactor;this._tabSlider.style.width=sliderWidth+'px';if(this._tabSlider.parentElement!==this._headerContentsElement)
this._headerContentsElement.appendChild(this._tabSlider);}
_hideTab(tab){tab.tabElement.removeAttribute('tabIndex');tab.tabElement.classList.remove('selected');tab.tabElement.setAttribute('aria-selected','false');tab.view.detach();}
elementsToRestoreScrollPositionsFor(){return[this._contentElement];}
_insertBefore(tab,index){this._tabsElement.insertBefore(tab.tabElement,this._tabsElement.childNodes[index]);const oldIndex=this._tabs.indexOf(tab);this._tabs.splice(oldIndex,1);if(oldIndex<index)
--index;this._tabs.splice(index,0,tab);this.dispatchEventToListeners(UI.TabbedPane.Events.TabOrderChanged,{tabId:tab.id});}
leftToolbar(){if(!this._leftToolbar){this._leftToolbar=new UI.Toolbar('tabbed-pane-left-toolbar');this._headerElement.insertBefore(this._leftToolbar.element,this._headerElement.firstChild);}
return this._leftToolbar;}
rightToolbar(){if(!this._rightToolbar){this._rightToolbar=new UI.Toolbar('tabbed-pane-right-toolbar');this._headerElement.appendChild(this._rightToolbar.element);}
return this._rightToolbar;}
setAllowTabReorder(allow,automatic){this._allowTabReorder=allow;this._automaticReorder=automatic;}
_keyDown(event){if(!this._currentTab)
return;let nextTabElement=null;switch(event.key){case'ArrowUp':case'ArrowLeft':nextTabElement=this._currentTab.tabElement.previousElementSibling;if(!nextTabElement&&!this._dropDownButton.parentElement)
nextTabElement=this._currentTab.tabElement.parentElement.lastElementChild;break;case'ArrowDown':case'ArrowRight':nextTabElement=this._currentTab.tabElement.nextElementSibling;if(!nextTabElement&&!this._dropDownButton.parentElement)
nextTabElement=this._currentTab.tabElement.parentElement.firstElementChild;break;case'Enter':case' ':this._currentTab.view.focus();return;default:return;}
if(!nextTabElement){this._dropDownButton.click();return;}
const tab=this._tabs.find(tab=>tab.tabElement===nextTabElement);this.selectTab(tab.id,true);nextTabElement.focus();}};UI.TabbedPane.Events={TabSelected:Symbol('TabSelected'),TabClosed:Symbol('TabClosed'),TabOrderChanged:Symbol('TabOrderChanged')};UI.TabbedPaneTab=class{constructor(tabbedPane,id,title,closeable,view,tooltip){this._closeable=closeable;this._tabbedPane=tabbedPane;this._id=id;this._title=title;this._tooltip=tooltip;this._view=view;this._shown=false;this._measuredWidth;this._tabElement;this._iconContainer=null;}
get id(){return this._id;}
get title(){return this._title;}
set title(title){if(title===this._title)
return;this._title=title;if(this._titleElement)
this._titleElement.textContent=title;delete this._measuredWidth;}
isCloseable(){return this._closeable;}
_setIcon(icon){this._icon=icon;if(this._tabElement)
this._createIconElement(this._tabElement,this._titleElement,false);delete this._measuredWidth;}
_toggleClass(className,force){const element=this.tabElement;const hasClass=element.classList.contains(className);if(hasClass===force)
return false;element.classList.toggle(className,force);delete this._measuredWidth;return true;}
get view(){return this._view;}
set view(view){this._view=view;}
get tooltip(){return this._tooltip;}
set tooltip(tooltip){this._tooltip=tooltip;if(this._titleElement)
this._titleElement.title=tooltip||'';}
get tabElement(){if(!this._tabElement)
this._tabElement=this._createTabElement(false);return this._tabElement;}
width(){return this._width;}
setWidth(width){this.tabElement.style.width=width===-1?'':(width+'px');this._width=width;}
setDelegate(delegate){this._delegate=delegate;}
_createIconElement(tabElement,titleElement,measuring){if(tabElement.__iconElement){tabElement.__iconElement.remove();tabElement.__iconElement=null;}
if(!this._icon)
return;const iconContainer=createElementWithClass('span','tabbed-pane-header-tab-icon');const iconNode=measuring?this._icon.cloneNode(true):this._icon;iconContainer.appendChild(iconNode);tabElement.insertBefore(iconContainer,titleElement);tabElement.__iconElement=iconContainer;}
_createTabElement(measuring){const tabElement=createElementWithClass('div','tabbed-pane-header-tab');tabElement.id='tab-'+this._id;UI.ARIAUtils.markAsTab(tabElement);UI.ARIAUtils.setSelected(tabElement,false);UI.ARIAUtils.setAccessibleName(tabElement,this.title);const titleElement=tabElement.createChild('span','tabbed-pane-header-tab-title');titleElement.textContent=this.title;titleElement.title=this.tooltip||'';this._createIconElement(tabElement,titleElement,measuring);if(!measuring)
this._titleElement=titleElement;if(this._closeable){const closeButton=tabElement.createChild('div','tabbed-pane-close-button','dt-close-button');closeButton.gray=true;closeButton.setAccessibleName(ls`Close ${this.title}`);tabElement.classList.add('closeable');}
if(measuring){tabElement.classList.add('measuring');}else{tabElement.addEventListener('click',this._tabClicked.bind(this),false);tabElement.addEventListener('auxclick',this._tabClicked.bind(this),false);tabElement.addEventListener('mousedown',this._tabMouseDown.bind(this),false);tabElement.addEventListener('mouseup',this._tabMouseUp.bind(this),false);tabElement.addEventListener('contextmenu',this._tabContextMenu.bind(this),false);if(this._tabbedPane._allowTabReorder){UI.installDragHandle(tabElement,this._startTabDragging.bind(this),this._tabDragging.bind(this),this._endTabDragging.bind(this),'-webkit-grabbing','pointer',200);}}
return tabElement;}
_tabClicked(event){const middleButton=event.button===1;const shouldClose=this._closeable&&(middleButton||event.target.classList.contains('tabbed-pane-close-button'));if(!shouldClose){this._tabbedPane.focus();return;}
this._closeTabs([this.id]);event.consume(true);}
_tabMouseDown(event){if(event.target.classList.contains('tabbed-pane-close-button')||event.button===1)
return;this._tabbedPane.selectTab(this.id,true);}
_tabMouseUp(event){if(event.button===1)
event.consume(true);}
_closeTabs(ids){if(this._delegate){this._delegate.closeTabs(this._tabbedPane,ids);return;}
this._tabbedPane.closeTabs(ids,true);}
_tabContextMenu(event){function close(){this._closeTabs([this.id]);}
function closeOthers(){this._closeTabs(this._tabbedPane.otherTabs(this.id));}
function closeAll(){this._closeTabs(this._tabbedPane.tabIds());}
function closeToTheRight(){this._closeTabs(this._tabbedPane._tabsToTheRight(this.id));}
const contextMenu=new UI.ContextMenu(event);if(this._closeable){contextMenu.defaultSection().appendItem(Common.UIString('Close'),close.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Close others'),closeOthers.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Close tabs to the right'),closeToTheRight.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Close all'),closeAll.bind(this));}
if(this._delegate)
this._delegate.onContextMenu(this.id,contextMenu);contextMenu.show();}
_startTabDragging(event){if(event.target.classList.contains('tabbed-pane-close-button'))
return false;this._dragStartX=event.pageX;this._tabElement.classList.add('dragging');this._tabbedPane._tabSlider.remove();return true;}
_tabDragging(event){const tabElements=this._tabbedPane._tabsElement.childNodes;for(let i=0;i<tabElements.length;++i){let tabElement=tabElements[i];if(tabElement===this._tabElement)
continue;const intersects=tabElement.offsetLeft+tabElement.clientWidth>this._tabElement.offsetLeft&&this._tabElement.offsetLeft+this._tabElement.clientWidth>tabElement.offsetLeft;if(!intersects)
continue;if(Math.abs(event.pageX-this._dragStartX)<tabElement.clientWidth/2+5)
break;if(event.pageX-this._dragStartX>0){tabElement=tabElement.nextSibling;++i;}
const oldOffsetLeft=this._tabElement.offsetLeft;this._tabbedPane._insertBefore(this,i);this._dragStartX+=this._tabElement.offsetLeft-oldOffsetLeft;break;}
if(!this._tabElement.previousSibling&&event.pageX-this._dragStartX<0){this._tabElement.style.setProperty('left','0px');return;}
if(!this._tabElement.nextSibling&&event.pageX-this._dragStartX>0){this._tabElement.style.setProperty('left','0px');return;}
this._tabElement.style.setProperty('left',(event.pageX-this._dragStartX)+'px');}
_endTabDragging(event){this._tabElement.classList.remove('dragging');this._tabElement.style.removeProperty('left');delete this._dragStartX;this._tabbedPane._updateTabSlider();}};UI.TabbedPaneTabDelegate=function(){};UI.TabbedPaneTabDelegate.prototype={closeTabs(tabbedPane,ids){},onContextMenu(tabId,contextMenu){}};;UI.highlightedSearchResultClassName='highlighted-search-result';UI.highlightedCurrentSearchResultClassName='current-search-result';UI.installDragHandle=function(element,elementDragStart,elementDrag,elementDragEnd,cursor,hoverCursor,startDelay){function onMouseDown(event){const dragHandler=new UI.DragHandler();const dragStart=dragHandler.elementDragStart.bind(dragHandler,element,elementDragStart,elementDrag,elementDragEnd,cursor,event);if(startDelay)
startTimer=setTimeout(dragStart,startDelay);else
dragStart();}
function onMouseUp(){if(startTimer)
clearTimeout(startTimer);startTimer=null;}
let startTimer;element.addEventListener('mousedown',onMouseDown,false);if(startDelay)
element.addEventListener('mouseup',onMouseUp,false);if(hoverCursor!==null)
element.style.cursor=hoverCursor||cursor||'';};UI.elementDragStart=function(targetElement,elementDragStart,elementDrag,elementDragEnd,cursor,event){const dragHandler=new UI.DragHandler();dragHandler.elementDragStart(targetElement,elementDragStart,elementDrag,elementDragEnd,cursor,event);};UI.DragHandler=class{constructor(){this._elementDragMove=this._elementDragMove.bind(this);this._elementDragEnd=this._elementDragEnd.bind(this);this._mouseOutWhileDragging=this._mouseOutWhileDragging.bind(this);}
_createGlassPane(){this._glassPaneInUse=true;if(!UI.DragHandler._glassPaneUsageCount++){UI.DragHandler._glassPane=new UI.GlassPane();UI.DragHandler._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);UI.DragHandler._glassPane.show(UI.DragHandler._documentForMouseOut);}}
_disposeGlassPane(){if(!this._glassPaneInUse)
return;this._glassPaneInUse=false;if(--UI.DragHandler._glassPaneUsageCount)
return;UI.DragHandler._glassPane.hide();delete UI.DragHandler._glassPane;delete UI.DragHandler._documentForMouseOut;}
elementDragStart(targetElement,elementDragStart,elementDrag,elementDragEnd,cursor,event){if(event.button||(Host.isMac()&&event.ctrlKey))
return;if(this._elementDraggingEventListener)
return;if(elementDragStart&&!elementDragStart((event)))
return;const targetDocument=event.target.ownerDocument;this._elementDraggingEventListener=elementDrag;this._elementEndDraggingEventListener=elementDragEnd;console.assert((UI.DragHandler._documentForMouseOut||targetDocument)===targetDocument,'Dragging on multiple documents.');UI.DragHandler._documentForMouseOut=targetDocument;this._dragEventsTargetDocument=targetDocument;try{this._dragEventsTargetDocumentTop=targetDocument.defaultView.top.document;}catch(e){this._dragEventsTargetDocumentTop=this._dragEventsTargetDocument;}
targetDocument.addEventListener('mousemove',this._elementDragMove,true);targetDocument.addEventListener('mouseup',this._elementDragEnd,true);targetDocument.addEventListener('mouseout',this._mouseOutWhileDragging,true);if(targetDocument!==this._dragEventsTargetDocumentTop)
this._dragEventsTargetDocumentTop.addEventListener('mouseup',this._elementDragEnd,true);if(typeof cursor==='string'){this._restoreCursorAfterDrag=restoreCursor.bind(this,targetElement.style.cursor);targetElement.style.cursor=cursor;targetDocument.body.style.cursor=cursor;}
function restoreCursor(oldCursor){targetDocument.body.style.removeProperty('cursor');targetElement.style.cursor=oldCursor;this._restoreCursorAfterDrag=null;}
event.preventDefault();}
_mouseOutWhileDragging(){this._unregisterMouseOutWhileDragging();this._createGlassPane();}
_unregisterMouseOutWhileDragging(){if(!UI.DragHandler._documentForMouseOut)
return;UI.DragHandler._documentForMouseOut.removeEventListener('mouseout',this._mouseOutWhileDragging,true);}
_unregisterDragEvents(){if(!this._dragEventsTargetDocument)
return;this._dragEventsTargetDocument.removeEventListener('mousemove',this._elementDragMove,true);this._dragEventsTargetDocument.removeEventListener('mouseup',this._elementDragEnd,true);if(this._dragEventsTargetDocument!==this._dragEventsTargetDocumentTop)
this._dragEventsTargetDocumentTop.removeEventListener('mouseup',this._elementDragEnd,true);delete this._dragEventsTargetDocument;delete this._dragEventsTargetDocumentTop;}
_elementDragMove(event){if(event.buttons!==1){this._elementDragEnd(event);return;}
if(this._elementDraggingEventListener((event)))
this._cancelDragEvents(event);}
_cancelDragEvents(event){this._unregisterDragEvents();this._unregisterMouseOutWhileDragging();if(this._restoreCursorAfterDrag)
this._restoreCursorAfterDrag();this._disposeGlassPane();delete this._elementDraggingEventListener;delete this._elementEndDraggingEventListener;}
_elementDragEnd(event){const elementDragEnd=this._elementEndDraggingEventListener;this._cancelDragEvents((event));event.preventDefault();if(elementDragEnd)
elementDragEnd((event));}};UI.DragHandler._glassPaneUsageCount=0;UI.isBeingEdited=function(node){if(!node||node.nodeType!==Node.ELEMENT_NODE)
return false;let element=(node);if(element.classList.contains('text-prompt')||element.nodeName==='INPUT'||element.nodeName==='TEXTAREA')
return true;if(!UI.__editingCount)
return false;while(element){if(element.__editing)
return true;element=element.parentElementOrShadowHost();}
return false;};UI.isEditing=function(){if(UI.__editingCount)
return true;const focused=document.deepActiveElement();if(!focused)
return false;return focused.classList.contains('text-prompt')||focused.nodeName==='INPUT'||focused.nodeName==='TEXTAREA';};UI.markBeingEdited=function(element,value){if(value){if(element.__editing)
return false;element.classList.add('being-edited');element.__editing=true;UI.__editingCount=(UI.__editingCount||0)+1;}else{if(!element.__editing)
return false;element.classList.remove('being-edited');delete element.__editing;--UI.__editingCount;}
return true;};UI._numberRegex=/^(-?(?:\d+(?:\.\d+)?|\.\d+))$/;UI.StyleValueDelimiters=' \xA0\t\n"\':;,/()';UI._valueModificationDirection=function(event){let direction=null;if(event.type==='mousewheel'){if(event.wheelDeltaY>0||event.wheelDeltaX>0)
direction='Up';else if(event.wheelDeltaY<0||event.wheelDeltaX<0)
direction='Down';}else{if(event.key==='ArrowUp'||event.key==='PageUp')
direction='Up';else if(event.key==='ArrowDown'||event.key==='PageDown')
direction='Down';}
return direction;};UI._modifiedHexValue=function(hexString,event){const direction=UI._valueModificationDirection(event);if(!direction)
return null;const mouseEvent=(event);const number=parseInt(hexString,16);if(isNaN(number)||!isFinite(number))
return null;const hexStrLen=hexString.length;const channelLen=hexStrLen/3;if(channelLen!==1&&channelLen!==2)
return null;let delta=0;if(UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent))
delta+=Math.pow(16,channelLen*2);if(mouseEvent.shiftKey)
delta+=Math.pow(16,channelLen);if(mouseEvent.altKey)
delta+=1;if(delta===0)
delta=1;if(direction==='Down')
delta*=-1;const maxValue=Math.pow(16,hexStrLen)-1;const result=Number.constrain(number+delta,0,maxValue);let resultString=result.toString(16).toUpperCase();for(let i=0,lengthDelta=hexStrLen-resultString.length;i<lengthDelta;++i)
resultString='0'+resultString;return resultString;};UI._modifiedFloatNumber=function(number,event,modifierMultiplier){const direction=UI._valueModificationDirection(event);if(!direction)
return null;const mouseEvent=(event);let delta=1;if(UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent))
delta=100;else if(mouseEvent.shiftKey)
delta=10;else if(mouseEvent.altKey)
delta=0.1;if(direction==='Down')
delta*=-1;if(modifierMultiplier)
delta*=modifierMultiplier;const result=Number((number+delta).toFixed(6));if(!String(result).match(UI._numberRegex))
return null;return result;};UI.createReplacementString=function(wordString,event,customNumberHandler){let prefix;let suffix;let number;let replacementString=null;let matches=/(.*#)([\da-fA-F]+)(.*)/.exec(wordString);if(matches&&matches.length){prefix=matches[1];suffix=matches[3];number=UI._modifiedHexValue(matches[2],event);if(number!==null)
replacementString=prefix+number+suffix;}else{matches=/(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/.exec(wordString);if(matches&&matches.length){prefix=matches[1];suffix=matches[3];number=UI._modifiedFloatNumber(parseFloat(matches[2]),event);if(number!==null){replacementString=customNumberHandler?customNumberHandler(prefix,number,suffix):prefix+number+suffix;}}}
return replacementString;};UI.handleElementValueModifications=function(event,element,finishHandler,suggestionHandler,customNumberHandler){function createRange(){return document.createRange();}
const arrowKeyOrMouseWheelEvent=(event.key==='ArrowUp'||event.key==='ArrowDown'||event.type==='mousewheel');const pageKeyPressed=(event.key==='PageUp'||event.key==='PageDown');if(!arrowKeyOrMouseWheelEvent&&!pageKeyPressed)
return false;const selection=element.getComponentSelection();if(!selection.rangeCount)
return false;const selectionRange=selection.getRangeAt(0);if(!selectionRange.commonAncestorContainer.isSelfOrDescendant(element))
return false;const originalValue=element.textContent;const wordRange=selectionRange.startContainer.rangeOfWord(selectionRange.startOffset,UI.StyleValueDelimiters,element);const wordString=wordRange.toString();if(suggestionHandler&&suggestionHandler(wordString))
return false;const replacementString=UI.createReplacementString(wordString,event,customNumberHandler);if(replacementString){const replacementTextNode=createTextNode(replacementString);wordRange.deleteContents();wordRange.insertNode(replacementTextNode);const finalSelectionRange=createRange();finalSelectionRange.setStart(replacementTextNode,0);finalSelectionRange.setEnd(replacementTextNode,replacementString.length);selection.removeAllRanges();selection.addRange(finalSelectionRange);event.handled=true;event.preventDefault();if(finishHandler)
finishHandler(originalValue,replacementString);return true;}
return false;};Number.preciseMillisToString=function(ms,precision){precision=precision||0;const format='%.'+precision+'f\xa0ms';return Common.UIString(format,ms);};UI._microsFormat=new Common.UIStringFormat('%.0f\xa0\u03bcs');UI._subMillisFormat=new Common.UIStringFormat('%.2f\xa0ms');UI._millisFormat=new Common.UIStringFormat('%.0f\xa0ms');UI._secondsFormat=new Common.UIStringFormat('%.2f\xa0s');UI._minutesFormat=new Common.UIStringFormat('%.1f\xa0min');UI._hoursFormat=new Common.UIStringFormat('%.1f\xa0hrs');UI._daysFormat=new Common.UIStringFormat('%.1f\xa0days');Number.millisToString=function(ms,higherResolution){if(!isFinite(ms))
return'-';if(ms===0)
return'0';if(higherResolution&&ms<0.1)
return UI._microsFormat.format(ms*1000);if(higherResolution&&ms<1000)
return UI._subMillisFormat.format(ms);if(ms<1000)
return UI._millisFormat.format(ms);const seconds=ms/1000;if(seconds<60)
return UI._secondsFormat.format(seconds);const minutes=seconds/60;if(minutes<60)
return UI._minutesFormat.format(minutes);const hours=minutes/60;if(hours<24)
return UI._hoursFormat.format(hours);const days=hours/24;return UI._daysFormat.format(days);};Number.secondsToString=function(seconds,higherResolution){if(!isFinite(seconds))
return'-';return Number.millisToString(seconds*1000,higherResolution);};Number.bytesToString=function(bytes){if(bytes<1024)
return Common.UIString('%.0f\xa0B',bytes);const kilobytes=bytes/1024;if(kilobytes<100)
return Common.UIString('%.1f\xa0KB',kilobytes);if(kilobytes<1024)
return Common.UIString('%.0f\xa0KB',kilobytes);const megabytes=kilobytes/1024;if(megabytes<100)
return Common.UIString('%.1f\xa0MB',megabytes);else
return Common.UIString('%.0f\xa0MB',megabytes);};Number.withThousandsSeparator=function(num){let str=num+'';const re=/(\d+)(\d{3})/;while(str.match(re))
str=str.replace(re,'$1\xa0$2');return str;};UI.formatLocalized=function(format,substitutions){const formatters={s:substitution=>substitution};function append(a,b){a.appendChild(typeof b==='string'?createTextNode(b):b);return a;}
return String.format(Common.UIString(format),substitutions,formatters,createElement('span'),append).formattedResult;};UI.openLinkExternallyLabel=function(){return Common.UIString('Open in new tab');};UI.copyLinkAddressLabel=function(){return Common.UIString('Copy link address');};UI.anotherProfilerActiveLabel=function(){return Common.UIString('Another profiler is already active');};UI.asyncStackTraceLabel=function(description){if(description){if(description==='Promise.resolve')
description=Common.UIString('Promise resolved');else if(description==='Promise.reject')
description=Common.UIString('Promise rejected');return description+' '+Common.UIString('(async)');}
return Common.UIString('Async Call');};UI.installComponentRootStyles=function(element){UI._injectCoreStyles(element);element.classList.add('platform-'+Host.platform());if(!Host.isMac()&&UI.measuredScrollbarWidth(element.ownerDocument)===0)
element.classList.add('overlay-scrollbar-enabled');};UI.measuredScrollbarWidth=function(document){if(typeof UI._measuredScrollbarWidth==='number')
return UI._measuredScrollbarWidth;if(!document)
return 16;const scrollDiv=document.createElement('div');scrollDiv.setAttribute('style','width: 100px; height: 100px; overflow: scroll;');document.body.appendChild(scrollDiv);UI._measuredScrollbarWidth=scrollDiv.offsetWidth-scrollDiv.clientWidth;document.body.removeChild(scrollDiv);return UI._measuredScrollbarWidth;};UI.createShadowRootWithCoreStyles=function(element,cssFile,delegatesFocus){const shadowRoot=element.attachShadow({mode:'open',delegatesFocus});UI._injectCoreStyles(shadowRoot);if(cssFile)
UI.appendStyle(shadowRoot,cssFile);shadowRoot.addEventListener('focus',UI._focusChanged.bind(UI),true);return shadowRoot;};UI._injectCoreStyles=function(root){UI.appendStyle(root,'ui/inspectorCommon.css');UI.appendStyle(root,'ui/textButton.css');UI.themeSupport.injectHighlightStyleSheets(root);UI.themeSupport.injectCustomStyleSheets(root);};UI._windowFocused=function(document,event){if(event.target.document.nodeType===Node.DOCUMENT_NODE)
document.body.classList.remove('inactive');UI._keyboardFocus=true;const listener=()=>{const activeElement=document.deepActiveElement();if(activeElement)
activeElement.removeAttribute('data-keyboard-focus');UI._keyboardFocus=false;};document.defaultView.requestAnimationFrame(()=>{UI._keyboardFocus=false;document.removeEventListener('mousedown',listener,true);});document.addEventListener('mousedown',listener,true);};UI._windowBlurred=function(document,event){if(event.target.document.nodeType===Node.DOCUMENT_NODE)
document.body.classList.add('inactive');};UI._focusChanged=function(event){const document=event.target&&event.target.ownerDocument;const element=document?document.deepActiveElement():null;UI.Widget.focusWidgetForNode(element);UI.XWidget.focusWidgetForNode(element);if(!UI._keyboardFocus)
return;element.setAttribute('data-keyboard-focus','true');element.addEventListener('blur',()=>element.removeAttribute('data-keyboard-focus'),{once:true,capture:true});};UI.ElementFocusRestorer=class{constructor(element){this._element=element;this._previous=element.ownerDocument.deepActiveElement();element.focus();}
restore(){if(!this._element)
return;if(this._element.hasFocus()&&this._previous)
this._previous.focus();this._previous=null;this._element=null;}};UI.highlightSearchResult=function(element,offset,length,domChanges){const result=UI.highlightSearchResults(element,[new TextUtils.SourceRange(offset,length)],domChanges);return result.length?result[0]:null;};UI.highlightSearchResults=function(element,resultRanges,changes){return UI.highlightRangesWithStyleClass(element,resultRanges,UI.highlightedSearchResultClassName,changes);};UI.runCSSAnimationOnce=function(element,className){function animationEndCallback(){element.classList.remove(className);element.removeEventListener('webkitAnimationEnd',animationEndCallback,false);}
if(element.classList.contains(className))
element.classList.remove(className);element.addEventListener('webkitAnimationEnd',animationEndCallback,false);element.classList.add(className);};UI.highlightRangesWithStyleClass=function(element,resultRanges,styleClass,changes){changes=changes||[];const highlightNodes=[];const textNodes=element.childTextNodes();const lineText=textNodes.map(function(node){return node.textContent;}).join('');const ownerDocument=element.ownerDocument;if(textNodes.length===0)
return highlightNodes;const nodeRanges=[];let rangeEndOffset=0;for(let i=0;i<textNodes.length;++i){const range={};range.offset=rangeEndOffset;range.length=textNodes[i].textContent.length;rangeEndOffset=range.offset+range.length;nodeRanges.push(range);}
let startIndex=0;for(let i=0;i<resultRanges.length;++i){const startOffset=resultRanges[i].offset;const endOffset=startOffset+resultRanges[i].length;while(startIndex<textNodes.length&&nodeRanges[startIndex].offset+nodeRanges[startIndex].length<=startOffset)
startIndex++;let endIndex=startIndex;while(endIndex<textNodes.length&&nodeRanges[endIndex].offset+nodeRanges[endIndex].length<endOffset)
endIndex++;if(endIndex===textNodes.length)
break;const highlightNode=ownerDocument.createElement('span');highlightNode.className=styleClass;highlightNode.textContent=lineText.substring(startOffset,endOffset);const lastTextNode=textNodes[endIndex];const lastText=lastTextNode.textContent;lastTextNode.textContent=lastText.substring(endOffset-nodeRanges[endIndex].offset);changes.push({node:lastTextNode,type:'changed',oldText:lastText,newText:lastTextNode.textContent});if(startIndex===endIndex){lastTextNode.parentElement.insertBefore(highlightNode,lastTextNode);changes.push({node:highlightNode,type:'added',nextSibling:lastTextNode,parent:lastTextNode.parentElement});highlightNodes.push(highlightNode);const prefixNode=ownerDocument.createTextNode(lastText.substring(0,startOffset-nodeRanges[startIndex].offset));lastTextNode.parentElement.insertBefore(prefixNode,highlightNode);changes.push({node:prefixNode,type:'added',nextSibling:highlightNode,parent:lastTextNode.parentElement});}else{const firstTextNode=textNodes[startIndex];const firstText=firstTextNode.textContent;const anchorElement=firstTextNode.nextSibling;firstTextNode.parentElement.insertBefore(highlightNode,anchorElement);changes.push({node:highlightNode,type:'added',nextSibling:anchorElement,parent:firstTextNode.parentElement});highlightNodes.push(highlightNode);firstTextNode.textContent=firstText.substring(0,startOffset-nodeRanges[startIndex].offset);changes.push({node:firstTextNode,type:'changed',oldText:firstText,newText:firstTextNode.textContent});for(let j=startIndex+1;j<endIndex;j++){const textNode=textNodes[j];const text=textNode.textContent;textNode.textContent='';changes.push({node:textNode,type:'changed',oldText:text,newText:textNode.textContent});}}
startIndex=endIndex;nodeRanges[startIndex].offset=endOffset;nodeRanges[startIndex].length=lastTextNode.textContent.length;}
return highlightNodes;};UI.applyDomChanges=function(domChanges){for(let i=0,size=domChanges.length;i<size;++i){const entry=domChanges[i];switch(entry.type){case'added':entry.parent.insertBefore(entry.node,entry.nextSibling);break;case'changed':entry.node.textContent=entry.newText;break;}}};UI.revertDomChanges=function(domChanges){for(let i=domChanges.length-1;i>=0;--i){const entry=domChanges[i];switch(entry.type){case'added':entry.node.remove();break;case'changed':entry.node.textContent=entry.oldText;break;}}};UI.measurePreferredSize=function(element,containerElement){const oldParent=element.parentElement;const oldNextSibling=element.nextSibling;containerElement=containerElement||element.ownerDocument.body;containerElement.appendChild(element);element.positionAt(0,0);const result=element.getBoundingClientRect();element.positionAt(undefined,undefined);if(oldParent)
oldParent.insertBefore(element,oldNextSibling);else
element.remove();return new UI.Size(result.width,result.height);};UI.InvokeOnceHandlers=class{constructor(autoInvoke){this._handlers=null;this._autoInvoke=autoInvoke;}
add(object,method){if(!this._handlers){this._handlers=new Map();if(this._autoInvoke)
this.scheduleInvoke();}
let methods=this._handlers.get(object);if(!methods){methods=new Set();this._handlers.set(object,methods);}
methods.add(method);}
scheduleInvoke(){if(this._handlers)
requestAnimationFrame(this._invoke.bind(this));}
_invoke(){const handlers=this._handlers;this._handlers=null;const keys=handlers.keysArray();for(let i=0;i<keys.length;++i){const object=keys[i];const methods=handlers.get(object).valuesArray();for(let j=0;j<methods.length;++j)
methods[j].call(object);}}};UI._coalescingLevel=0;UI._postUpdateHandlers=null;UI.startBatchUpdate=function(){if(!UI._coalescingLevel++)
UI._postUpdateHandlers=new UI.InvokeOnceHandlers(false);};UI.endBatchUpdate=function(){if(--UI._coalescingLevel)
return;UI._postUpdateHandlers.scheduleInvoke();UI._postUpdateHandlers=null;};UI.invokeOnceAfterBatchUpdate=function(object,method){if(!UI._postUpdateHandlers)
UI._postUpdateHandlers=new UI.InvokeOnceHandlers(true);UI._postUpdateHandlers.add(object,method);};UI.animateFunction=function(window,func,params,duration,animationComplete){const start=window.performance.now();let raf=window.requestAnimationFrame(animationStep);function animationStep(timestamp){const progress=Number.constrain((timestamp-start)/duration,0,1);func(...params.map(p=>p.from+(p.to-p.from)*progress));if(progress<1)
raf=window.requestAnimationFrame(animationStep);else if(animationComplete)
animationComplete();}
return()=>window.cancelAnimationFrame(raf);};UI.LongClickController=class extends Common.Object{constructor(element,callback){super();this._element=element;this._callback=callback;this._enable();}
reset(){if(this._longClickInterval){clearInterval(this._longClickInterval);delete this._longClickInterval;}}
_enable(){if(this._longClickData)
return;const boundMouseDown=mouseDown.bind(this);const boundMouseUp=mouseUp.bind(this);const boundReset=this.reset.bind(this);this._element.addEventListener('mousedown',boundMouseDown,false);this._element.addEventListener('mouseout',boundReset,false);this._element.addEventListener('mouseup',boundMouseUp,false);this._element.addEventListener('click',boundReset,true);this._longClickData={mouseUp:boundMouseUp,mouseDown:boundMouseDown,reset:boundReset};function mouseDown(e){if(e.which!==1)
return;const callback=this._callback;this._longClickInterval=setTimeout(callback.bind(null,e),200);}
function mouseUp(e){if(e.which!==1)
return;this.reset();}}
dispose(){if(!this._longClickData)
return;this._element.removeEventListener('mousedown',this._longClickData.mouseDown,false);this._element.removeEventListener('mouseout',this._longClickData.reset,false);this._element.removeEventListener('mouseup',this._longClickData.mouseUp,false);this._element.addEventListener('click',this._longClickData.reset,true);delete this._longClickData;}};UI.initializeUIUtils=function(document,themeSetting){document.body.classList.toggle('inactive',!document.hasFocus());document.defaultView.addEventListener('focus',UI._windowFocused.bind(UI,document),false);document.defaultView.addEventListener('blur',UI._windowBlurred.bind(UI,document),false);document.addEventListener('focus',UI._focusChanged.bind(UI),true);document.addEventListener('keydown',event=>{UI._keyboardFocus=true;document.defaultView.requestAnimationFrame(()=>void(UI._keyboardFocus=false));},true);if(!UI.themeSupport)
UI.themeSupport=new UI.ThemeSupport(themeSetting);UI.themeSupport.applyTheme(document);const body=(document.body);UI.appendStyle(body,'ui/inspectorStyle.css');UI.GlassPane.setContainer((document.body));};UI.beautifyFunctionName=function(name){return name||Common.UIString('(anonymous)');};UI.bindLabelToControl=function(label,control){const controlId=UI.ARIAUtils.nextId('labelledControl');control.id=controlId;label.setAttribute('for',controlId);};UI.registerCustomElement=function(localName,typeExtension,definition){self.customElements.define(typeExtension,class extends definition{constructor(){super();this.setAttribute('is',typeExtension);}},{extends:localName});return()=>createElement(localName,typeExtension);};UI.createTextButton=function(text,clickHandler,className,primary){const element=createElementWithClass('button',className||'');element.textContent=text;element.classList.add('text-button');if(primary)
element.classList.add('primary-button');if(clickHandler)
element.addEventListener('click',clickHandler,false);element.type='button';return element;};UI.createInput=function(className,type){const element=createElementWithClass('input',className||'');element.spellcheck=false;element.classList.add('harmony-input');if(type)
element.type=type;return element;};UI.createLabel=function(title,className,associatedControl){const element=createElementWithClass('label',className||'');element.textContent=title;if(associatedControl)
UI.bindLabelToControl(element,associatedControl);return element;};UI.createRadioLabel=function(name,title,checked){const element=createElement('span','dt-radio');element.radioElement.name=name;element.radioElement.checked=!!checked;element.labelElement.createTextChild(title);return element;};UI.createIconLabel=function(title,iconClass){const element=createElement('span','dt-icon-label');element.createChild('span').textContent=title;element.type=iconClass;return element;};UI.createSlider=function(min,max,tabIndex){const element=createElement('span','dt-slider');element.sliderElement.min=min;element.sliderElement.max=max;element.sliderElement.step=1;element.sliderElement.tabIndex=tabIndex;return element;};UI.appendStyle=function(node,cssFile){const content=Runtime.cachedResources[cssFile]||'';if(!content)
console.error(cssFile+' not preloaded. Check module.json');let styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=content;node.appendChild(styleElement);const themeStyleSheet=UI.themeSupport.themeStyleSheet(cssFile,content);if(themeStyleSheet){styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=themeStyleSheet+'\n'+Runtime.resolveSourceURL(cssFile+'.theme');node.appendChild(styleElement);}};UI.CheckboxLabel=class extends HTMLSpanElement{constructor(){super();this._shadowRoot;this.checkboxElement;this.textElement;UI.CheckboxLabel._lastId=(UI.CheckboxLabel._lastId||0)+1;const id='ui-checkbox-label'+UI.CheckboxLabel._lastId;this._shadowRoot=UI.createShadowRootWithCoreStyles(this,'ui/checkboxTextLabel.css');this.checkboxElement=(this._shadowRoot.createChild('input'));this.checkboxElement.type='checkbox';this.checkboxElement.setAttribute('id',id);this.textElement=this._shadowRoot.createChild('label','dt-checkbox-text');this.textElement.setAttribute('for',id);this._shadowRoot.createChild('slot');}
static create(title,checked,subtitle){if(!UI.CheckboxLabel._constructor)
UI.CheckboxLabel._constructor=UI.registerCustomElement('span','dt-checkbox',UI.CheckboxLabel);const element=(UI.CheckboxLabel._constructor());element.checkboxElement.checked=!!checked;if(title!==undefined){element.textElement.textContent=title;if(subtitle!==undefined)
element.textElement.createChild('div','dt-checkbox-subtitle').textContent=subtitle;}
return element;}
set backgroundColor(color){this.checkboxElement.classList.add('dt-checkbox-themed');this.checkboxElement.style.backgroundColor=color;}
set checkColor(color){this.checkboxElement.classList.add('dt-checkbox-themed');const stylesheet=createElement('style');stylesheet.textContent='input.dt-checkbox-themed:checked:after { background-color: '+color+'}';this._shadowRoot.appendChild(stylesheet);}
set borderColor(color){this.checkboxElement.classList.add('dt-checkbox-themed');this.checkboxElement.style.borderColor=color;}};(function(){let labelId=0;UI.registerCustomElement('span','dt-radio',class extends HTMLSpanElement{constructor(){super();this.radioElement=this.createChild('input','dt-radio-button');this.labelElement=this.createChild('label');const id='dt-radio-button-id'+(++labelId);this.radioElement.id=id;this.radioElement.type='radio';this.labelElement.htmlFor=id;const root=UI.createShadowRootWithCoreStyles(this,'ui/radioButton.css');root.createChild('slot');this.addEventListener('click',radioClickHandler,false);}});function radioClickHandler(event){if(this.radioElement.checked||this.radioElement.disabled)
return;this.radioElement.checked=true;this.radioElement.dispatchEvent(new Event('change'));}
UI.registerCustomElement('span','dt-icon-label',class extends HTMLSpanElement{constructor(){super();const root=UI.createShadowRootWithCoreStyles(this);this._iconElement=UI.Icon.create();this._iconElement.style.setProperty('margin-right','4px');root.appendChild(this._iconElement);root.createChild('slot');}
set type(type){this._iconElement.setIconType(type);}});UI.registerCustomElement('span','dt-slider',class extends HTMLSpanElement{constructor(){super();const root=UI.createShadowRootWithCoreStyles(this,'ui/slider.css');this.sliderElement=createElementWithClass('input','dt-range-input');this.sliderElement.type='range';root.appendChild(this.sliderElement);}
set value(amount){this.sliderElement.value=amount;}
get value(){return this.sliderElement.value;}});UI.registerCustomElement('span','dt-small-bubble',class extends HTMLSpanElement{constructor(){super();const root=UI.createShadowRootWithCoreStyles(this,'ui/smallBubble.css');this._textElement=root.createChild('div');this._textElement.className='info';this._textElement.createChild('slot');}
set type(type){this._textElement.className=type;}});UI.registerCustomElement('div','dt-close-button',class extends HTMLDivElement{constructor(){super();const root=UI.createShadowRootWithCoreStyles(this,'ui/closeButton.css');this._buttonElement=root.createChild('div','close-button');UI.ARIAUtils.markAsButton(this._buttonElement);const regularIcon=UI.Icon.create('smallicon-cross','default-icon');this._hoverIcon=UI.Icon.create('mediumicon-red-cross-hover','hover-icon');this._activeIcon=UI.Icon.create('mediumicon-red-cross-active','active-icon');this._buttonElement.appendChild(regularIcon);this._buttonElement.appendChild(this._hoverIcon);this._buttonElement.appendChild(this._activeIcon);}
set gray(gray){if(gray){this._hoverIcon.setIconType('mediumicon-gray-cross-hover');this._activeIcon.setIconType('mediumicon-gray-cross-active');}else{this._hoverIcon.setIconType('mediumicon-red-cross-hover');this._activeIcon.setIconType('mediumicon-red-cross-active');}}
setAccessibleName(name){UI.ARIAUtils.setAccessibleName(this._buttonElement,name);}});})();UI.bindInput=function(input,apply,validate,numeric,modifierMultiplier){input.addEventListener('change',onChange,false);input.addEventListener('input',onInput,false);input.addEventListener('keydown',onKeyDown,false);input.addEventListener('focus',input.select.bind(input),false);function onInput(){input.classList.toggle('error-input',!validate(input.value));}
function onChange(){const valid=validate(input.value);input.classList.toggle('error-input',!valid);if(valid)
apply(input.value);}
function onKeyDown(event){if(isEnterKey(event)){if(validate(input.value))
apply(input.value);event.preventDefault();return;}
if(!numeric)
return;const value=UI._modifiedFloatNumber(parseFloat(input.value),event,modifierMultiplier);const stringValue=value?String(value):'';if(!validate(stringValue)||!value)
return;input.value=stringValue;apply(input.value);event.preventDefault();}
function setValue(value){if(value===input.value)
return;const valid=validate(value);input.classList.toggle('error-input',!valid);input.value=value;}
return setValue;};UI.trimText=function(context,text,maxWidth,trimFunction){const maxLength=200;if(maxWidth<=10)
return'';if(text.length>maxLength)
text=trimFunction(text,maxLength);const textWidth=UI.measureTextWidth(context,text);if(textWidth<=maxWidth)
return text;let l=0;let r=text.length;let lv=0;let rv=textWidth;while(l<r&&lv!==rv&&lv!==maxWidth){const m=Math.ceil(l+(r-l)*(maxWidth-lv)/(rv-lv));const mv=UI.measureTextWidth(context,trimFunction(text,m));if(mv<=maxWidth){l=m;lv=mv;}else{r=m-1;rv=mv;}}
text=trimFunction(text,l);return text!=='\u2026'?text:'';};UI.trimTextMiddle=function(context,text,maxWidth){return UI.trimText(context,text,maxWidth,(text,width)=>text.trimMiddle(width));};UI.trimTextEnd=function(context,text,maxWidth){return UI.trimText(context,text,maxWidth,(text,width)=>text.trimEnd(width));};UI.measureTextWidth=function(context,text){const maxCacheableLength=200;if(text.length>maxCacheableLength)
return context.measureText(text).width;let widthCache=UI.measureTextWidth._textWidthCache;if(!widthCache){widthCache=new Map();UI.measureTextWidth._textWidthCache=widthCache;}
const font=context.font;let textWidths=widthCache.get(font);if(!textWidths){textWidths=new Map();widthCache.set(font,textWidths);}
let width=textWidths.get(text);if(!width){width=context.measureText(text).width;textWidths.set(text,width);}
return width;};UI.ThemeSupport=class{constructor(setting){this._themeName=setting.get()||'default';this._themableProperties=new Set(['color','box-shadow','text-shadow','outline-color','background-image','background-color','border-left-color','border-right-color','border-top-color','border-bottom-color','-webkit-border-image','fill','stroke']);this._cachedThemePatches=new Map();this._setting=setting;this._customSheets=new Set();}
hasTheme(){return this._themeName!=='default';}
themeName(){return this._themeName;}
injectHighlightStyleSheets(element){this._injectingStyleSheet=true;UI.appendStyle(element,'ui/inspectorSyntaxHighlight.css');if(this._themeName==='dark')
UI.appendStyle(element,'ui/inspectorSyntaxHighlightDark.css');this._injectingStyleSheet=false;}
injectCustomStyleSheets(element){for(const sheet of this._customSheets){const styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=sheet;element.appendChild(styleElement);}}
addCustomStylesheet(sheetText){this._customSheets.add(sheetText);}
applyTheme(document){if(!this.hasTheme())
return;if(this._themeName==='dark')
document.documentElement.classList.add('-theme-with-dark-background');const styleSheets=document.styleSheets;const result=[];for(let i=0;i<styleSheets.length;++i)
result.push(this._patchForTheme(styleSheets[i].href,styleSheets[i]));result.push('/*# sourceURL=inspector.css.theme */');const styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=result.join('\n');document.head.appendChild(styleElement);}
themeStyleSheet(id,text){if(!this.hasTheme()||this._injectingStyleSheet)
return'';let patch=this._cachedThemePatches.get(id);if(!patch){const styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=text;document.body.appendChild(styleElement);patch=this._patchForTheme(id,styleElement.sheet);document.body.removeChild(styleElement);}
return patch;}
_patchForTheme(id,styleSheet){const cached=this._cachedThemePatches.get(id);if(cached)
return cached;try{const rules=styleSheet.cssRules;const result=[];for(let j=0;j<rules.length;++j){if(rules[j]instanceof CSSImportRule){result.push(this._patchForTheme(rules[j].styleSheet.href,rules[j].styleSheet));continue;}
const output=[];const style=rules[j].style;const selectorText=rules[j].selectorText;for(let i=0;style&&i<style.length;++i)
this._patchProperty(selectorText,style,style[i],output);if(output.length)
result.push(rules[j].selectorText+'{'+output.join('')+'}');}
const fullText=result.join('\n');this._cachedThemePatches.set(id,fullText);return fullText;}catch(e){this._setting.set('default');return'';}}
_patchProperty(selectorText,style,name,output){if(!this._themableProperties.has(name))
return;const value=style.getPropertyValue(name);if(!value||value==='none'||value==='inherit'||value==='initial'||value==='transparent')
return;if(name==='background-image'&&value.indexOf('gradient')===-1)
return;if(selectorText.indexOf('-theme-')!==-1)
return;let colorUsage=UI.ThemeSupport.ColorUsage.Unknown;if(name.indexOf('background')===0||name.indexOf('border')===0)
colorUsage|=UI.ThemeSupport.ColorUsage.Background;if(name.indexOf('background')===-1)
colorUsage|=UI.ThemeSupport.ColorUsage.Foreground;output.push(name);output.push(':');const items=value.replace(Common.Color.Regex,'\0$1\0').split('\0');for(let i=0;i<items.length;++i)
output.push(this.patchColorText(items[i],colorUsage));if(style.getPropertyPriority(name))
output.push(' !important');output.push(';');}
patchColorText(text,colorUsage){const color=Common.Color.parse(text);if(!color)
return text;const outColor=this.patchColor(color,colorUsage);let outText=outColor.asString(null);if(!outText)
outText=outColor.asString(outColor.hasAlpha()?Common.Color.Format.RGBA:Common.Color.Format.RGB);return outText||text;}
patchColor(color,colorUsage){const hsla=color.hsla();this._patchHSLA(hsla,colorUsage);const rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,color.format());}
_patchHSLA(hsla,colorUsage){const hue=hsla[0];const sat=hsla[1];let lit=hsla[2];const alpha=hsla[3];switch(this._themeName){case'dark':const minCap=colorUsage&UI.ThemeSupport.ColorUsage.Background?0.14:0;const maxCap=colorUsage&UI.ThemeSupport.ColorUsage.Foreground?0.9:1;lit=1-lit;if(lit<minCap*2)
lit=minCap+lit/2;else if(lit>2*maxCap-1)
lit=maxCap-1/2+lit/2;break;}
hsla[0]=Number.constrain(hue,0,1);hsla[1]=Number.constrain(sat,0,1);hsla[2]=Number.constrain(lit,0,1);hsla[3]=Number.constrain(alpha,0,1);}};UI.ThemeSupport.ColorUsage={Unknown:0,Foreground:1<<0,Background:1<<1,};UI.createDocumentationLink=function(article,title){return UI.XLink.create('https://developers.google.com/web/tools/chrome-devtools/'+article,title);};UI.loadImage=function(url){return new Promise(fulfill=>{const image=new Image();image.addEventListener('load',()=>fulfill(image));image.addEventListener('error',()=>fulfill(null));image.src=url;});};UI.loadImageFromData=function(data){return data?UI.loadImage('data:image/jpg;base64,'+data):Promise.resolve(null);};UI.themeSupport;UI.createFileSelectorElement=function(callback){const fileSelectorElement=createElement('input');fileSelectorElement.type='file';fileSelectorElement.style.display='none';fileSelectorElement.setAttribute('tabindex',-1);fileSelectorElement.onchange=onChange;function onChange(event){callback(fileSelectorElement.files[0]);}
return fileSelectorElement;};UI.MaxLengthForDisplayedURLs=150;UI.MessageDialog=class{static async show(message,where){const dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.setDimmed(true);const shadowRoot=UI.createShadowRootWithCoreStyles(dialog.contentElement,'ui/confirmDialog.css');const content=shadowRoot.createChild('div','widget');await new Promise(resolve=>{const okButton=UI.createTextButton(Common.UIString('OK'),resolve,'',true);content.createChild('div','message').createChild('span').textContent=message;content.createChild('div','button').appendChild(okButton);dialog.setOutsideClickCallback(event=>{event.consume();resolve();});dialog.show(where);okButton.focus();});dialog.hide();}};UI.ConfirmDialog=class{static async show(message,where){const dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.setDimmed(true);const shadowRoot=UI.createShadowRootWithCoreStyles(dialog.contentElement,'ui/confirmDialog.css');const content=shadowRoot.createChild('div','widget');content.createChild('div','message').createChild('span').textContent=message;const buttonsBar=content.createChild('div','button');const result=await new Promise(resolve=>{buttonsBar.appendChild(UI.createTextButton(Common.UIString('OK'),()=>resolve(true),'',true));buttonsBar.appendChild(UI.createTextButton(Common.UIString('Cancel'),()=>resolve(false)));dialog.setOutsideClickCallback(event=>{event.consume();resolve(false);});dialog.show(where);});dialog.hide();return result;}};UI.createInlineButton=function(toolbarButton){const element=createElement('span');const shadowRoot=UI.createShadowRootWithCoreStyles(element,'ui/inlineButton.css');element.classList.add('inline-button');const toolbar=new UI.Toolbar('');toolbar.appendToolbarItem(toolbarButton);shadowRoot.appendChild(toolbar.element);return element;};UI.createExpandableText=function(text,maxLength){const fragment=createDocumentFragment();fragment.textContent=text.slice(0,maxLength);const expandElement=fragment.createChild('span');const totalBytes=Number.bytesToString(2*text.length);if(text.length<10000000){expandElement.setAttribute('data-text',ls`Show more (${totalBytes})`);expandElement.classList.add('expandable-inline-button');expandElement.addEventListener('click',()=>{if(expandElement.parentElement)
expandElement.parentElement.insertBefore(createTextNode(text.slice(maxLength)),expandElement);expandElement.remove();});}else{expandElement.setAttribute('data-text',ls`long text was truncated (${totalBytes})`);expandElement.classList.add('undisplayable-text');}
const copyButton=fragment.createChild('span','expandable-inline-button');copyButton.setAttribute('data-text',ls`Copy`);copyButton.addEventListener('click',()=>{InspectorFrontendHost.copyText(text);});return fragment;};UI.Renderer=function(){};UI.Renderer.prototype={render(object,options){}};UI.Renderer.render=async function(object,options){if(!object)
throw new Error('Can\'t render '+object);const renderer=await self.runtime.extension(UI.Renderer,object).instance();return renderer?renderer.render(object,options||{}):null;};UI.Renderer.Options;UI.formatTimestamp=function(timestamp,full){const date=new Date(timestamp);const yymmdd=date.getFullYear()+'-'+leadZero(date.getMonth()+1,2)+'-'+leadZero(date.getDate(),2);const hhmmssfff=leadZero(date.getHours(),2)+':'+leadZero(date.getMinutes(),2)+':'+
leadZero(date.getSeconds(),2)+'.'+leadZero(date.getMilliseconds(),3);return full?(yymmdd+' '+hhmmssfff):hhmmssfff;function leadZero(value,length){const valueString=value.toString();const padding=length-valueString.length;return padding<=0?valueString:'0'.repeat(padding)+valueString;}};;UI.ARIAUtils={};UI.ARIAUtils._id=0;UI.ARIAUtils.markAsButton=function(element){element.setAttribute('role','button');};UI.ARIAUtils.markAsCheckbox=function(element){element.setAttribute('role','checkbox');};UI.ARIAUtils.markAsGroup=function(element){element.setAttribute('role','group');};UI.ARIAUtils.markAsLink=function(element){element.setAttribute('role','link');};UI.ARIAUtils.markAsTab=function(element){element.setAttribute('role','tab');};UI.ARIAUtils.markAsTree=function(element){element.setAttribute('role','tree');};UI.ARIAUtils.markAsTreeitem=function(element){element.setAttribute('role','treeitem');};UI.ARIAUtils.markAsTextBox=function(element){element.setAttribute('role','textbox');};UI.ARIAUtils.markAsMenu=function(element){element.setAttribute('role','menu');};UI.ARIAUtils.markAsMenuItem=function(element){element.setAttribute('role','menuitem');};UI.ARIAUtils.markAsHidden=function(element){element.setAttribute('aria-hidden','true');};UI.ARIAUtils.markAsHeading=function(element,level){element.setAttribute('role','heading');element.setAttribute('aria-level',level);};UI.ARIAUtils.setPlaceholder=function(element,placeholder){if(placeholder)
element.setAttribute('aria-placeholder',placeholder);else
element.removeAttribute('aria-placeholder');};UI.ARIAUtils.markAsPresentation=function(element){element.setAttribute('role','presentation');};UI.ARIAUtils.ensureId=function(element){if(!element.id)
element.id=UI.ARIAUtils.nextId('ariaElement');};UI.ARIAUtils.nextId=function(prefix){return(prefix||'')+ ++UI.ARIAUtils._id;};UI.ARIAUtils.setControls=function(element,controlledElement){if(!controlledElement){element.removeAttribute('aria-controls');return;}
if(controlledElement.id==='')
throw new Error('Controlled element must have ID');element.setAttribute('aria-controls',controlledElement.id);};UI.ARIAUtils.setChecked=function(element,value){element.setAttribute('aria-checked',!!value);};UI.ARIAUtils.setExpanded=function(element,value){element.setAttribute('aria-expanded',!!value);};UI.ARIAUtils.unsetExpanded=function(element){element.removeAttribute('aria-expanded');};UI.ARIAUtils.setSelected=function(element,value){element.setAttribute('aria-selected',!!value);};UI.ARIAUtils.setPressed=function(element,value){element.setAttribute('aria-pressed',!!value);};UI.ARIAUtils.setAccessibleName=function(element,name){element.setAttribute('aria-label',name);};UI.ARIAUtils.setLabelledBy=function(element,labelElement){UI.ARIAUtils.ensureId(labelElement);element.setAttribute('aria-labelledby',labelElement.id);};UI.ARIAUtils.alert=function(message,element){const document=element.ownerDocument;if(!document[UI.ARIAUtils.AlertElementSymbol]){const alertElement=document.body.createChild('div');alertElement.style.position='absolute';alertElement.style.left='-999em';alertElement.style.width='100em';alertElement.style.overflow='hidden';alertElement.setAttribute('role','alert');alertElement.setAttribute('aria-atomic','true');document[UI.ARIAUtils.AlertElementSymbol]=alertElement;}
document[UI.ARIAUtils.AlertElementSymbol].textContent=message.trimEnd(10000);};UI.ARIAUtils.AlertElementSymbol=Symbol('AlertElementSybmol');;UI.ZoomManager=class extends Common.Object{constructor(window,frontendHost){super();this._frontendHost=frontendHost;this._zoomFactor=this._frontendHost.zoomFactor();window.addEventListener('resize',this._onWindowResize.bind(this),true);}
zoomFactor(){return this._zoomFactor;}
cssToDIP(value){return value*this._zoomFactor;}
dipToCSS(valueDIP){return valueDIP/this._zoomFactor;}
_onWindowResize(){const oldZoomFactor=this._zoomFactor;this._zoomFactor=this._frontendHost.zoomFactor();if(oldZoomFactor!==this._zoomFactor)
this.dispatchEventToListeners(UI.ZoomManager.Events.ZoomChanged,{from:oldZoomFactor,to:this._zoomFactor});}};UI.ZoomManager.Events={ZoomChanged:Symbol('ZoomChanged')};UI.zoomManager;;UI.ShortcutsScreen=class{constructor(){this._sections={};}
static registerShortcuts(){const elementsSection=UI.shortcutsScreen.section(Common.UIString('Elements Panel'));const navigate=UI.ShortcutsScreen.ElementsPanelShortcuts.NavigateUp.concat(UI.ShortcutsScreen.ElementsPanelShortcuts.NavigateDown);elementsSection.addRelatedKeys(navigate,Common.UIString('Navigate elements'));const expandCollapse=UI.ShortcutsScreen.ElementsPanelShortcuts.Expand.concat(UI.ShortcutsScreen.ElementsPanelShortcuts.Collapse);elementsSection.addRelatedKeys(expandCollapse,Common.UIString('Expand/collapse'));elementsSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.EditAttribute,Common.UIString('Edit attribute'));elementsSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('elements.hide-element'),Common.UIString('Hide element'));elementsSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('elements.edit-as-html'),Common.UIString('Toggle edit as HTML'));const stylesPaneSection=UI.shortcutsScreen.section(Common.UIString('Styles Pane'));const nextPreviousProperty=UI.ShortcutsScreen.ElementsPanelShortcuts.NextProperty.concat(UI.ShortcutsScreen.ElementsPanelShortcuts.PreviousProperty);stylesPaneSection.addRelatedKeys(nextPreviousProperty,Common.UIString('Next/previous property'));stylesPaneSection.addRelatedKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementValue,Common.UIString('Increment value'));stylesPaneSection.addRelatedKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementValue,Common.UIString('Decrement value'));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy10,Common.UIString('Increment by %f',10));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy10,Common.UIString('Decrement by %f',10));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy100,Common.UIString('Increment by %f',100));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy100,Common.UIString('Decrement by %f',100));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy01,Common.UIString('Increment by %f',0.1));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy01,Common.UIString('Decrement by %f',0.1));const consoleSection=UI.shortcutsScreen.section(Common.UIString('Console'));consoleSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('console.clear'),Common.UIString('Clear console'));consoleSection.addRelatedKeys(UI.ShortcutsScreen.ConsolePanelShortcuts.AcceptSuggestion,Common.UIString('Accept suggestion'));consoleSection.addAlternateKeys(UI.ShortcutsScreen.ConsolePanelShortcuts.ClearConsolePrompt,Common.UIString('Clear console prompt'));consoleSection.addRelatedKeys(UI.ShortcutsScreen.ConsolePanelShortcuts.NextPreviousLine,Common.UIString('Next/previous line'));if(Host.isMac()){consoleSection.addRelatedKeys(UI.ShortcutsScreen.ConsolePanelShortcuts.NextPreviousCommand,Common.UIString('Next/previous command'));}
consoleSection.addKey(UI.ShortcutsScreen.ConsolePanelShortcuts.ExecuteCommand,Common.UIString('Execute command'));const debuggerSection=UI.shortcutsScreen.section(Common.UIString('Debugger'));debuggerSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-pause'),Common.UIString('Pause/ Continue'));debuggerSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-over'),Common.UIString('Step over'));debuggerSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-into'),Common.UIString('Step into'));debuggerSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-out'),Common.UIString('Step out'));const nextAndPrevFrameKeys=UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.next-call-frame').concat(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.previous-call-frame'));debuggerSection.addRelatedKeys(nextAndPrevFrameKeys,Common.UIString('Next/previous call frame'));debuggerSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.EvaluateSelectionInConsole,Common.UIString('Evaluate selection in console'));debuggerSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.AddSelectionToWatch,Common.UIString('Add selection to watch'));debuggerSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-breakpoint'),Common.UIString('Toggle breakpoint'));debuggerSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-breakpoint-enabled'),Common.UIString('Toggle breakpoint enabled'));debuggerSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-breakpoints-active'),Common.UIString('Toggle all breakpoints'));const editingSection=UI.shortcutsScreen.section(Common.UIString('Text Editor'));editingSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.go-to-member'),Common.UIString('Go to member'));editingSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.ToggleAutocompletion,Common.UIString('Autocompletion'));editingSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.go-to-line'),Common.UIString('Go to line'));editingSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.jump-to-previous-location'),Common.UIString('Jump to previous editing location'));editingSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.jump-to-next-location'),Common.UIString('Jump to next editing location'));editingSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.ToggleComment,Common.UIString('Toggle comment'));editingSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.IncreaseCSSUnitByOne,Common.UIString('Increment CSS unit by 1'));editingSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.DecreaseCSSUnitByOne,Common.UIString('Decrement CSS unit by 1'));editingSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.IncreaseCSSUnitByTen,Common.UIString('Increment CSS unit by 10'));editingSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.DecreaseCSSUnitByTen,Common.UIString('Decrement CSS unit by 10'));editingSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.SelectNextOccurrence,Common.UIString('Select next occurrence'));editingSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.SoftUndo,Common.UIString('Soft undo'));editingSection.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.GotoMatchingBracket,Common.UIString('Go to matching bracket'));editingSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.close-editor-tab'),Common.UIString('Close editor tab'));editingSection.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.switch-file'),Common.UIString('Switch between files with the same name and different extensions.'));const performanceSection=UI.shortcutsScreen.section(Common.UIString('Performance Panel'))
section(name){let section=this._sections[name];if(!section)
this._sections[name]=section=new UI.ShortcutsSection(name);return section;}
createShortcutsTabView(){const orderedSections=[];for(const section in this._sections)
orderedSections.push(this._sections[section]);function compareSections(a,b){return a.order-b.order;}
orderedSections.sort(compareSections);const widget=new UI.Widget();widget.element.className='settings-tab-container';widget.element.createChild('header').createChild('h3').createTextChild(Common.UIString('Shortcuts'));const scrollPane=widget.element.createChild('div','settings-container-wrapper');const container=scrollPane.createChild('div');container.className='settings-content settings-container';for(let i=0;i<orderedSections.length;++i)
orderedSections[i].renderSection(container);const note=scrollPane.createChild('p','settings-footnote');note.appendChild(UI.createDocumentationLink('iterate/inspect-styles/shortcuts',Common.UIString('Full list of DevTools keyboard shortcuts and gestures')));return widget;}};UI.shortcutsScreen;UI.ShortcutsSection=class{constructor(name){this.name=name;this._lines=([]);this.order=++UI.ShortcutsSection._sequenceNumber;}
addKey(key,description){this._addLine(this._renderKey(key),description);}
addRelatedKeys(keys,description){this._addLine(this._renderSequence(keys,'/'),description);}
addAlternateKeys(keys,description){this._addLine(this._renderSequence(keys,Common.UIString('or')),description);}
_addLine(keyElement,description){this._lines.push({key:keyElement,text:description});}
renderSection(container){const parent=container.createChild('div','settings-block');const headLine=parent.createChild('div','settings-line');headLine.createChild('div','settings-key-cell');headLine.createChild('div','settings-section-title settings-cell').textContent=this.name;for(let i=0;i<this._lines.length;++i){const line=parent.createChild('div','settings-line');const keyCell=line.createChild('div','settings-key-cell');keyCell.appendChild(this._lines[i].key);keyCell.appendChild(this._createSpan('settings-key-delimiter',':'));line.createChild('div','settings-cell').textContent=this._lines[i].text;}}
_renderSequence(sequence,delimiter){const delimiterSpan=this._createSpan('settings-key-delimiter',delimiter);return this._joinNodes(sequence.map(this._renderKey.bind(this)),delimiterSpan);}
_renderKey(key){const keyName=key.name;const plus=this._createSpan('settings-combine-keys','+');return this._joinNodes(keyName.split(' + ').map(this._createSpan.bind(this,'settings-key')),plus);}
_createSpan(className,textContent){const node=createElement('span');node.className=className;node.textContent=textContent;return node;}
_joinNodes(nodes,delimiter){const result=createDocumentFragment();for(let i=0;i<nodes.length;++i){if(i>0)
result.appendChild(delimiter.cloneNode(true));result.appendChild(nodes[i]);}
return result;}};UI.ShortcutsSection._sequenceNumber=0;UI.ShortcutsScreen.ElementsPanelShortcuts={NavigateUp:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up)],NavigateDown:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down)],Expand:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Right)],Collapse:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Left)],EditAttribute:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Enter)],NextProperty:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Tab)],PreviousProperty:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Tab,UI.KeyboardShortcut.Modifiers.Shift)],IncrementValue:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up)],DecrementValue:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down)],IncrementBy10:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up,UI.KeyboardShortcut.Modifiers.Shift)],DecrementBy10:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down,UI.KeyboardShortcut.Modifiers.Shift)],IncrementBy100:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp,UI.KeyboardShortcut.Modifiers.Shift)],DecrementBy100:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown,UI.KeyboardShortcut.Modifiers.Shift)],IncrementBy01:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up,UI.KeyboardShortcut.Modifiers.Alt)],DecrementBy01:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down,UI.KeyboardShortcut.Modifiers.Alt)]};UI.ShortcutsScreen.ConsolePanelShortcuts={AcceptSuggestion:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Tab),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Right)],ClearConsolePrompt:[UI.KeyboardShortcut.makeDescriptor('u',UI.KeyboardShortcut.Modifiers.Ctrl)],ExecuteCommand:UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Enter),NextPreviousLine:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up)],NextPreviousCommand:[UI.KeyboardShortcut.makeDescriptor('N',UI.KeyboardShortcut.Modifiers.Alt),UI.KeyboardShortcut.makeDescriptor('P',UI.KeyboardShortcut.Modifiers.Alt)],};UI.ShortcutsScreen.SourcesPanelShortcuts={SelectNextOccurrence:[UI.KeyboardShortcut.makeDescriptor('d',UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],SoftUndo:[UI.KeyboardShortcut.makeDescriptor('u',UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],GotoMatchingBracket:[UI.KeyboardShortcut.makeDescriptor('m',UI.KeyboardShortcut.Modifiers.Ctrl)],ToggleAutocompletion:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Space,UI.KeyboardShortcut.Modifiers.Ctrl)],IncreaseCSSUnitByOne:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up,UI.KeyboardShortcut.Modifiers.Alt)],DecreaseCSSUnitByOne:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down,UI.KeyboardShortcut.Modifiers.Alt)],IncreaseCSSUnitByTen:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp,UI.KeyboardShortcut.Modifiers.Alt)],DecreaseCSSUnitByTen:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown,UI.KeyboardShortcut.Modifiers.Alt)],EvaluateSelectionInConsole:[UI.KeyboardShortcut.makeDescriptor('e',UI.KeyboardShortcut.Modifiers.Shift|UI.KeyboardShortcut.Modifiers.Ctrl)],AddSelectionToWatch:[UI.KeyboardShortcut.makeDescriptor('a',UI.KeyboardShortcut.Modifiers.Shift|UI.KeyboardShortcut.Modifiers.Ctrl)],ToggleComment:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Slash,UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],};UI.ShortcutsScreen.LayersPanelShortcuts={ResetView:[UI.KeyboardShortcut.makeDescriptor('0')],PanMode:[UI.KeyboardShortcut.makeDescriptor('x')],RotateMode:[UI.KeyboardShortcut.makeDescriptor('v')],TogglePanRotate:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Shift)],ZoomIn:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.K
length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);}
normalize(){const length=this.length();if(length<=UI.Geometry._Eps)
return;this.x/=length;this.y/=length;this.z/=length;}};UI.Geometry.Point=class{constructor(x,y){this.x=x;this.y=y;}
distanceTo(p){return Math.sqrt(Math.pow(p.x-this.x,2)+Math.pow(p.y-this.y,2));}
projectOn(line){if(line.x===0&&line.y===0)
return new UI.Geometry.Point(0,0);return line.scale((this.x*line.x+this.y*line.y)/(Math.pow(line.x,2)+Math.pow(line.y,2)));}
scale(scalar){return new UI.Geometry.Point(this.x*scalar,this.y*scalar);}
toString(){return Math.round(this.x*100)/100+', '+Math.round(this.y*100)/100;}};UI.Geometry.CubicBezier=class{constructor(point1,point2){this.controlPoints=[point1,point2];}
static parse(text){const keywordValues=UI.Geometry.CubicBezier.KeywordValues;const value=text.toLowerCase().replace(/\s+/g,'');if(Object.keys(keywordValues).indexOf(value)!==-1)
return UI.Geometry.CubicBezier.parse(keywordValues[value]);const bezierRegex=/^cubic-bezier\(([^,]+),([^,]+),([^,]+),([^,]+)\)$/;const match=value.match(bezierRegex);if(match){const control1=new UI.Geometry.Point(parseFloat(match[1]),parseFloat(match[2]));const control2=new UI.Geometry.Point(parseFloat(match[3]),parseFloat(match[4]));return new UI.Geometry.CubicBezier(control1,control2);}
return null;}
evaluateAt(t){function evaluate(v1,v2,t){return 3*(1-t)*(1-t)*t*v1+3*(1-t)*t*t*v2+Math.pow(t,3);}
const x=evaluate(this.controlPoints[0].x,this.controlPoints[1].x,t);const y=evaluate(this.controlPoints[0].y,this.controlPoints[1].y,t);return new UI.Geometry.Point(x,y);}
asCSSText(){const raw='cubic-bezier('+this.controlPoints.join(', ')+')';const keywordValues=UI.Geometry.CubicBezier.KeywordValues;for(const keyword in keywordValues){if(raw===keywordValues[keyword])
return keyword;}
return raw;}};UI.Geometry.CubicBezier.Regex=/((cubic-bezier\([^)]+\))|\b(linear|ease-in-out|ease-in|ease-out|ease)\b)/g;UI.Geometry.CubicBezier.KeywordValues={'linear':'cubic-bezier(0, 0, 1, 1)','ease':'cubic-bezier(0.25, 0.1, 0.25, 1)','ease-in':'cubic-bezier(0.42, 0, 1, 1)','ease-in-out':'cubic-bezier(0.42, 0, 0.58, 1)','ease-out':'cubic-bezier(0, 0, 0.58, 1)'};UI.Geometry.EulerAngles=class{constructor(alpha,beta,gamma){this.alpha=alpha;this.beta=beta;this.gamma=gamma;}
static fromRotationMatrix(rotationMatrix){const beta=Math.atan2(rotationMatrix.m23,rotationMatrix.m33);const gamma=Math.atan2(-rotationMatrix.m13,Math.sqrt(rotationMatrix.m11*rotationMatrix.m11+rotationMatrix.m12*rotationMatrix.m12));const alpha=Math.atan2(rotationMatrix.m12,rotationMatrix.m11);return new UI.Geometry.EulerAngles(UI.Geometry.radiansToDegrees(alpha),UI.Geometry.radiansToDegrees(beta),UI.Geometry.radiansToDegrees(gamma));}
toRotate3DString(){const gammaAxisY=-Math.sin(UI.Geometry.degreesToRadians(this.beta));const gammaAxisZ=Math.cos(UI.Geometry.degreesToRadians(this.beta));const axis={alpha:[0,1,0],beta:[-1,0,0],gamma:[0,gammaAxisY,gammaAxisZ]};return'rotate3d('+axis.alpha.join(',')+','+this.alpha+'deg) '+'rotate3d('+axis.beta.join(',')+','+this.beta+'deg) '+'rotate3d('+axis.gamma.join(',')+','+this.gamma+'deg)';}};UI.Geometry.scalarProduct=function(u,v){return u.x*v.x+u.y*v.y+u.z*v.z;};UI.Geometry.crossProduct=function(u,v){const x=u.y*v.z-u.z*v.y;const y=u.z*v.x-u.x*v.z;const z=u.x*v.y-u.y*v.x;return new UI.Geometry.Vector(x,y,z);};UI.Geometry.subtract=function(u,v){const x=u.x-v.x;const y=u.y-v.y;const z=u.z-v.z;return new UI.Geometry.Vector(x,y,z);};UI.Geometry.multiplyVectorByMatrixAndNormalize=function(v,m){const t=v.x*m.m14+v.y*m.m24+v.z*m.m34+m.m44;const x=(v.x*m.m11+v.y*m.m21+v.z*m.m31+m.m41)/t;const y=(v.x*m.m12+v.y*m.m22+v.z*m.m32+m.m42)/t;const z=(v.x*m.m13+v.y*m.m23+v.z*m.m33+m.m43)/t;return new UI.Geometry.Vector(x,y,z);};UI.Geometry.calculateAngle=function(u,v){const uLength=u.length();const vLength=v.length();if(uLength<=UI.Geometry._Eps||vLength<=UI.Geometry._Eps)
return 0;const cos=UI.Geometry.scalarProduct(u,v)/uLength/vLength;if(Math.abs(cos)>1)
return 0;return UI.Geometry.radiansToDegrees(Math.acos(cos));};UI.Geometry.degreesToRadians=function(deg){return deg*Math.PI/180;};UI.Geometry.radiansToDegrees=function(rad){return rad*180/Math.PI;};UI.Geometry.boundsForTransformedPoints=function(matrix,points,aggregateBounds){if(!aggregateBounds)
aggregateBounds={minX:Infinity,maxX:-Infinity,minY:Infinity,maxY:-Infinity};if(points.length%3)
console.assert('Invalid size of points array');for(let p=0;p<points.length;p+=3){let vector=new UI.Geometry.Vector(points[p],points[p+1],points[p+2]);vector=UI.Geometry.multiplyVectorByMatrixAndNormalize(vector,matrix);aggregateBounds.minX=Math.min(aggregateBounds.minX,vector.x);aggregateBounds.maxX=Math.max(aggregateBounds.maxX,vector.x);aggregateBounds.minY=Math.min(aggregateBounds.minY,vector.y);aggregateBounds.maxY=Math.max(aggregateBounds.maxY,vector.y);}
return aggregateBounds;};UI.Size=class{constructor(width,height){this.width=width;this.height=height;}
clipTo(size){if(!size)
return this;return new UI.Size(Math.min(this.width,size.width),Math.min(this.height,size.height));}
scale(scale){return new UI.Size(this.width*scale,this.height*scale);}};UI.Size.prototype.isEqual=function(size){return!!size&&this.width===size.width&&this.height===size.height;};UI.Size.prototype.widthToMax=function(size){return new UI.Size(Math.max(this.width,(typeof size==='number'?size:size.width)),this.height);};UI.Size.prototype.addWidth=function(size){return new UI.Size(this.width+(typeof size==='number'?size:size.width),this.height);};UI.Size.prototype.heightToMax=function(size){return new UI.Size(this.width,Math.max(this.height,(typeof size==='number'?size:size.height)));};UI.Size.prototype.addHeight=function(size){return new UI.Size(this.width,this.height+(typeof size==='number'?size:size.height));};UI.Insets=class{constructor(left,top,right,bottom){this.left=left;this.top=top;this.right=right;this.bottom=bottom;}
isEqual(insets){return!!insets&&this.left===insets.left&&this.top===insets.top&&this.right===insets.right&&this.bottom===insets.bottom;}};UI.Rect=class{constructor(left,top,width,height){this.left=left;this.top=top;this.width=width;this.height=height;}
isEqual(rect){return!!rect&&this.left===rect.left&&this.top===rect.top&&this.width===rect.width&&this.height===rect.height;}
scale(scale){return new UI.Rect(this.left*scale,this.top*scale,this.width*scale,this.height*scale);}
size(){return new UI.Size(this.width,this.height);}
relativeTo(origin){return new UI.Rect(this.left-origin.left,this.top-origin.top,this.width,this.height);}
rebaseTo(origin){return new UI.Rect(this.left+origin.left,this.top+origin.top,this.width,this.height);}};UI.Constraints=class{constructor(minimum,preferred){this.minimum=minimum||new UI.Size(0,0);this.preferred=preferred||this.minimum;if(this.minimum.width>this.preferred.width||this.minimum.height>this.preferred.height)
throw new Error('Minimum size is greater than preferred.');}};UI.Constraints.prototype.isEqual=function(constraints){return!!constraints&&this.minimum.isEqual(constraints.minimum)&&this.preferred.isEqual(constraints.preferred);};UI.Constraints.prototype.widthToMax=function(value){if(typeof value==='number')
return new UI.Constraints(this.minimum.widthToMax(value),this.preferred.widthToMax(value));return new UI.Constraints(this.minimum.widthToMax(value.minimum),this.preferred.widthToMax(value.preferred));};UI.Constraints.prototype.addWidth=function(value){if(typeof value==='number')
return new UI.Constraints(this.minimum.addWidth(value),this.preferred.addWidth(value));return new UI.Constraints(this.minimum.addWidth(value.minimum),this.preferred.addWidth(value.preferred));};UI.Constraints.prototype.heightToMax=function(value){if(typeof value==='number')
return new UI.Constraints(this.minimum.heightToMax(value),this.preferred.heightToMax(value));return new UI.Constraints(this.minimum.heightToMax(value.minimum),this.preferred.heightToMax(value.preferred));};UI.Constraints.prototype.addHeight=function(value){if(typeof value==='number')
return new UI.Constraints(this.minimum.addHeight(value),this.preferred.addHeight(value));return new UI.Constraints(this.minimum.addHeight(value.minimum),this.preferred.addHeight(value.preferred));};;UI.XLink=class extends UI.XElement{static create(url,linkText,className,preventClick){if(!linkText)
linkText=url;className=className||'';return UI.html`
<x-link href='${url}' class='${className} devtools-link' ${preventClick ? 'no-click' : ''}
>${linkText.trimMiddle(UI.MaxLengthForDisplayedURLs)}</x-link>`;}
constructor(){super();this.style.setProperty('display','inline');UI.ARIAUtils.markAsLink(this);this.tabIndex=0;this.setAttribute('target','_blank');this._href=null;this._clickable=true;this._onClick=event=>{event.consume(true);InspectorFrontendHost.openInNewTab((this._href));};this._onKeyDown=event=>{if(event.key!==' '&&!isEnterKey(event))
return;event.consume(true);InspectorFrontendHost.openInNewTab((this._href));};}
static get observedAttributes(){return UI.XElement.observedAttributes.concat(['href','no-click']);}
attributeChangedCallback(attr,oldValue,newValue){if(attr==='no-click'){this._clickable=!newValue;this._updateClick();return;}
if(attr==='href'){let href=newValue;if(newValue.trim().toLowerCase().startsWith('javascript:'))
href=null;if(Common.ParsedURL.isRelativeURL(newValue))
href=null;this._href=href;this.title=newValue;this._updateClick();return;}
super.attributeChangedCallback(attr,oldValue,newValue);}
_updateClick(){if(this._href!==null&&this._clickable){this.addEventListener('click',this._onClick,false);this.addEventListener('keydown',this._onKeyDown,false);this.style.setProperty('cursor','pointer');}else{this.removeEventListener('click',this._onClick,false);this.removeEventListener('keydown',this._onKeyDown,false);this.style.removeProperty('cursor');}}};UI.XLink.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){let targetNode=(target);while(targetNode&&!(targetNode instanceof UI.XLink))
targetNode=targetNode.parentNodeOrShadowHost();if(!targetNode||!targetNode._href)
return;contextMenu.revealSection().appendItem(UI.openLinkExternallyLabel(),()=>InspectorFrontendHost.openInNewTab(targetNode._href));contextMenu.revealSection().appendItem(UI.copyLinkAddressLabel(),()=>InspectorFrontendHost.copyText(targetNode._href));}};self.customElements.define('x-link',UI.XLink);;UI.XWidget=class extends UI.XElement{constructor(){super();this.style.setProperty('display','flex');this.style.setProperty('flex-direction','column');this.style.setProperty('align-items','stretch');this.style.setProperty('justify-content','flex-start');this.style.setProperty('contain','layout style');this._visible=false;this._shadowRoot;this._defaultFocusedElement=null;this._elementsToRestoreScrollPositionsFor=[];this._onShownCallback;this._onHiddenCallback;this._onResizedCallback;if(!UI.XWidget._observer){UI.XWidget._observer=new ResizeObserver(entries=>{for(const entry of entries){if(entry.target._visible&&entry.target._onResizedCallback)
entry.target._onResizedCallback.call(null);}});}
UI.XWidget._observer.observe(this);this.setElementsToRestoreScrollPositionsFor([this]);}
static focusWidgetForNode(node){node=node&&node.parentNodeOrShadowHost();let widget=null;while(node){if(node instanceof UI.XWidget){if(widget)
node._defaultFocusedElement=widget;widget=node;}
node=node.parentNodeOrShadowHost();}}
isShowing(){return this._visible;}
registerRequiredCSS(cssFile){UI.appendStyle(this._shadowRoot||this,cssFile);}
setOnShown(callback){this._onShownCallback=callback;}
setOnHidden(callback){this._onHiddenCallback=callback;}
setOnResized(callback){this._onResizedCallback=callback;}
setElementsToRestoreScrollPositionsFor(elements){for(const element of this._elementsToRestoreScrollPositionsFor)
element.removeEventListener('scroll',UI.XWidget._storeScrollPosition,{passive:true,capture:false});this._elementsToRestoreScrollPositionsFor=elements;for(const element of this._elementsToRestoreScrollPositionsFor)
element.addEventListener('scroll',UI.XWidget._storeScrollPosition,{passive:true,capture:false});}
restoreScrollPositions(){for(const element of this._elementsToRestoreScrollPositionsFor){if(element._scrollTop)
element.scrollTop=element._scrollTop;if(element._scrollLeft)
element.scrollLeft=element._scrollLeft;}}
static _storeScrollPosition(event){const element=event.currentTarget;element._scrollTop=element.scrollTop;element._scrollLeft=element.scrollLeft;}
setDefaultFocusedElement(element){if(element&&!this.isSelfOrAncestor(element))
throw new Error('Default focus must be descendant');this._defaultFocusedElement=element;}
focus(){if(!this._visible)
return;let element;if(this._defaultFocusedElement&&this.isSelfOrAncestor(this._defaultFocusedElement)){element=this._defaultFocusedElement;}else if(this.tabIndex!==-1){element=this;}else{let child=this.traverseNextNode(this);while(child){if((child instanceof UI.XWidget)&&child._visible){element=child;break;}
child=child.traverseNextNode(this);}}
if(!element||element.hasFocus())
return;if(element===this)
HTMLElement.prototype.focus.call(this);else
element.focus();}
connectedCallback(){this._visible=true;this.restoreScrollPositions();if(this._onShownCallback)
this._onShownCallback.call(null);}
disconnectedCallback(){this._visible=false;if(this._onHiddenCallback)
this._onHiddenCallback.call(null);}};self.customElements.define('x-widget',UI.XWidget);;self['Protocol']=self['Protocol']||{};Protocol.NodeURL=class{static patch(object){process(object,'');function process(object,path){if(object.url&&Protocol.NodeURL._isPlatformPath(object.url,Host.isWin()))
object.url=Common.ParsedURL.platformPathToURL(object.url);for(const entry of Object.entries(object)){const key=entry[0];const value=entry[1];const entryPath=path+'.'+key;if(entryPath!=='.result.result.value'&&value!==null&&typeof value==='object')
process(value,entryPath);}}}
static _isPlatformPath(fileSystemPath,isWindows){if(isWindows){const re=/^([a-z]:[\/\\]|\\\\)/i;return re.test(fileSystemPath);}else{return fileSystemPath.length?fileSystemPath[0]==='/':false;}}};;Protocol.Error=Symbol('Protocol.Error');Protocol.InspectorBackend=class{constructor(){this._agentPrototypes=new Map();this._dispatcherPrototypes=new Map();this._initialized=false;}
static reportProtocolError(error,messageObject){console.error(error+': '+JSON.stringify(messageObject));}
isInitialized(){return this._initialized;}
_addAgentGetterMethodToProtocolTargetPrototype(domain){let upperCaseLength=0;while(upperCaseLength<domain.length&&domain[upperCaseLength].toLowerCase()!==domain[upperCaseLength])
++upperCaseLength;const methodName=domain.substr(0,upperCaseLength).toLowerCase()+domain.slice(upperCaseLength)+'Agent';function agentGetter(){return this._agents[domain];}
Protocol.TargetBase.prototype[methodName]=agentGetter;function registerDispatcher(dispatcher){this.registerDispatcher(domain,dispatcher);}
Protocol.TargetBase.prototype['register'+domain+'Dispatcher']=registerDispatcher;}
_agentPrototype(domain){if(!this._agentPrototypes.has(domain)){this._agentPrototypes.set(domain,new Protocol.InspectorBackend._AgentPrototype(domain));this._addAgentGetterMethodToProtocolTargetPrototype(domain);}
return this._agentPrototypes.get(domain);}
_dispatcherPrototype(domain){if(!this._dispatcherPrototypes.has(domain))
this._dispatcherPrototypes.set(domain,new Protocol.InspectorBackend._DispatcherPrototype());return this._dispatcherPrototypes.get(domain);}
registerCommand(method,signature,replyArgs,hasErrorData){const domainAndMethod=method.split('.');this._agentPrototype(domainAndMethod[0]).registerCommand(domainAndMethod[1],signature,replyArgs,hasErrorData);this._initialized=true;}
registerEnum(type,values){const domainAndName=type.split('.');const domain=domainAndName[0];if(!Protocol[domain])
Protocol[domain]={};Protocol[domain][domainAndName[1]]=values;this._initialized=true;}
registerEvent(eventName,params){const domain=eventName.split('.')[0];this._dispatcherPrototype(domain).registerEvent(eventName,params);this._initialized=true;}
wrapClientCallback(clientCallback,errorPrefix,constructor,defaultValue){function callbackWrapper(error,value){if(error){console.error(errorPrefix+error);clientCallback(defaultValue);return;}
if(constructor)
clientCallback(new constructor(value));else
clientCallback(value);}
return callbackWrapper;}};Protocol.DevToolsStubErrorCode=-32015;Protocol.inspectorBackend=new Protocol.InspectorBackend();Protocol.Connection=function(){};Protocol.Connection.prototype={setOnMessage(onMessage){},setOnDisconnect(onDisconnect){},sendRawMessage(message){},disconnect(){},};Protocol.test={dumpProtocol:null,deprecatedRunAfterPendingDispatches:null,sendRawMessage:null,suppressRequestErrors:false,onMessageSent:null,onMessageReceived:null,};Protocol.Connection.setFactory=function(factory){Protocol.Connection._factory=factory;};Protocol.Connection._factory;Protocol._Callback;Protocol._GenericError=-32000;Protocol._ConnectionClosedErrorCode=-32001;Protocol.SessionRouter=class{constructor(connection){this._connection=connection;this._lastMessageId=1;this._pendingResponsesCount=0;this._domainToLogger=new Map();this._sessions=new Map();this._pendingScripts=[];Protocol.test.deprecatedRunAfterPendingDispatches=this._deprecatedRunAfterPendingDispatches.bind(this);Protocol.test.sendRawMessage=this._sendRawMessageForTesting.bind(this);this._connection.setOnMessage(this._onMessage.bind(this));this._connection.setOnDisconnect(reason=>{const session=this._sessions.get('');if(session)
session.target.dispose(reason);});}
registerSession(target,sessionId){this._sessions.set(sessionId,{target,callbacks:new Map()});}
unregisterSession(sessionId){const session=this._sessions.get(sessionId);for(const callback of session.callbacks.values())
Protocol.SessionRouter.dispatchConnectionError(callback);this._sessions.delete(sessionId);}
_nextMessageId(){return this._lastMessageId++;}
sendMessage(sessionId,domain,method,params,callback){const messageObject={};const messageId=this._nextMessageId();messageObject.id=messageId;messageObject.method=method;if(params)
messageObject.params=params;if(sessionId)
messageObject.sessionId=sessionId;if(Protocol.test.dumpProtocol)
Protocol.test.dumpProtocol('frontend: '+JSON.stringify(messageObject));if(Protocol.test.onMessageSent){const paramsObject=JSON.parse(JSON.stringify(params||{}));Protocol.test.onMessageSent({domain,method,params:(paramsObject),id:messageId});}
++this._pendingResponsesCount;this._sessions.get(sessionId).callbacks.set(messageId,callback);this._connection.sendRawMessage(JSON.stringify(messageObject));}
_sendRawMessageForTesting(method,params,callback){const domain=method.split('.')[0];this.sendMessage('',domain,method,params,callback||(()=>{}));}
_onMessage(message){if(Protocol.test.dumpProtocol)
Protocol.test.dumpProtocol('backend: '+((typeof message==='string')?message:JSON.stringify(message)));if(Protocol.test.onMessageReceived){const messageObjectCopy=JSON.parse((typeof message==='string')?message:JSON.stringify(message));Protocol.test.onMessageReceived((messageObjectCopy));}
const messageObject=((typeof message==='string')?JSON.parse(message):message);const sessionId=messageObject.sessionId||'';const session=this._sessions.get(sessionId);if(!session){Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message with wrong session id',messageObject);return;}
if(session.target._needsNodeJSPatching)
Protocol.NodeURL.patch(messageObject);if('id'in messageObject){const callback=session.callbacks.get(messageObject.id);session.callbacks.delete(messageObject.id);if(!callback){Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message with wrong id',messageObject);return;}
callback(messageObject.error,messageObject.result);--this._pendingResponsesCount;if(this._pendingScripts.length&&!this._pendingResponsesCount)
this._deprecatedRunAfterPendingDispatches();}else{if(!('method'in messageObject)){Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message without method',messageObject);return;}
const method=messageObject.method.split('.');const domainName=method[0];if(!(domainName in session.target._dispatchers)){Protocol.InspectorBackend.reportProtocolError(`Protocol Error: the message ${messageObject.method} is for non-existing domain '${domainName}'`,messageObject);return;}
session.target._dispatchers[domainName].dispatch(method[1],messageObject);}}
_deprecatedRunAfterPendingDispatches(script){if(script)
this._pendingScripts.push(script);setTimeout(()=>{if(!this._pendingResponsesCount)
this._executeAfterPendingDispatches();else
this._deprecatedRunAfterPendingDispatches();},0);}
_executeAfterPendingDispatches(){if(!this._pendingResponsesCount){const scripts=this._pendingScripts;this._pendingScripts=[];for(let id=0;id<scripts.length;++id)
scripts[id]();}}
static dispatchConnectionError(callback){const error={message:'Connection is closed, can\'t dispatch pending call',code:Protocol._ConnectionClosedErrorCode,data:null};setTimeout(()=>callback(error,null),0);}};Protocol.TargetBase=class{constructor(needsNodeJSPatching,parentTarget,sessionId,connection){this._needsNodeJSPatching=needsNodeJSPatching;this._sessionId=sessionId;if((!parentTarget&&connection)||(!parentTarget&&sessionId)||(connection&&sessionId))
throw new Error('Either connection or sessionId (but not both) must be supplied for a child target');if(sessionId)
this._router=parentTarget._router;else if(connection)
this._router=new Protocol.SessionRouter(connection);else
this._router=new Protocol.SessionRouter(Protocol.Connection._factory());this._router.registerSession(this,this._sessionId);this._agents={};for(const[domain,agentPrototype]of Protocol.inspectorBackend._agentPrototypes){this._agents[domain]=Object.create((agentPrototype));this._agents[domain]._target=this;}
this._dispatchers={};for(const[domain,dispatcherPrototype]of Protocol.inspectorBackend._dispatcherPrototypes){this._dispatchers[domain]=Object.create((dispatcherPrototype));this._dispatchers[domain]._dispatchers=[];}}
registerDispatcher(domain,dispatcher){if(!this._dispatchers[domain])
return;this._dispatchers[domain].addDomainDispatcher(dispatcher);}
dispose(reason){this._router.unregisterSession(this._sessionId);this._router=null;}
isDisposed(){return!this._router;}
markAsNodeJSForTest(){this._needsNodeJSPatching=true;}};Protocol.InspectorBackend._AgentPrototype=class{constructor(domain){this._replyArgs={};this._hasErrorData={};this._domain=domain;}
registerCommand(methodName,signature,replyArgs,hasErrorData){const domainAndMethod=this._domain+'.'+methodName;function sendMessagePromise(vararg){const params=Array.prototype.slice.call(arguments);return Protocol.InspectorBackend._AgentPrototype.prototype._sendMessageToBackendPromise.call(this,domainAndMethod,signature,params);}
this[methodName]=sendMessagePromise;function invoke(request){return this._invoke(domainAndMethod,request);}
this['invoke_'+methodName]=invoke;this._replyArgs[domainAndMethod]=replyArgs;if(hasErrorData)
this._hasErrorData[domainAndMethod]=true;}
_prepareParameters(method,signature,args,errorCallback){const params={};let hasParams=false;for(const param of signature){const paramName=param['name'];const typeName=param['type'];const optionalFlag=param['optional'];if(!args.length&&!optionalFlag){errorCallback(`Protocol Error: Invalid number of arguments for method '${method}' call. `+`It must have the following arguments ${JSON.stringify(signature)}'.`);return null;}
const value=args.shift();if(optionalFlag&&typeof value==='undefined')
continue;if(typeof value!==typeName){errorCallback(`Protocol Error: Invalid type of argument '${paramName}' for method '${method}' call. `+`It must be '${typeName}' but it is '${typeof value}'.`);return null;}
params[paramName]=value;hasParams=true;}
if(args.length){errorCallback(`Protocol Error: Extra ${args.length} arguments in a call to method '${method}'.`);return null;}
return hasParams?params:null;}
_sendMessageToBackendPromise(method,signature,args){let errorMessage;function onError(message){console.error(message);errorMessage=message;}
const params=this._prepareParameters(method,signature,args,onError);if(errorMessage)
return Promise.resolve(null);return new Promise(resolve=>{const callback=(error,result)=>{if(error&&!Protocol.test.suppressRequestErrors&&error.code!==Protocol.DevToolsStubErrorCode&&error.code!==Protocol._GenericError&&error.code!==Protocol._ConnectionClosedErrorCode)
console.error('Request '+method+' failed. '+JSON.stringify(error));if(error){resolve(null);return;}
const args=this._replyArgs[method];resolve(result&&args.length?result[args[0]]:undefined);};if(!this._target._router)
Protocol.SessionRouter.dispatchConnectionError(callback);else
this._target._router.sendMessage(this._target._sessionId,this._domain,method,params,callback);});}
_invoke(method,request){return new Promise(fulfill=>{const callback=(error,result)=>{if(error&&!Protocol.test.suppressRequestErrors&&error.code!==Protocol.DevToolsStubErrorCode&&error.code!==Protocol._GenericError&&error.code!==Protocol._ConnectionClosedErrorCode)
console.error('Request '+method+' failed. '+JSON.stringify(error));if(!result)
result={};if(error)
result[Protocol.Error]=error.message;fulfill(result);};if(!this._target._router)
Protocol.SessionRouter.dispatchConnectionError(callback);else
this._target._router.sendMessage(this._target._sessionId,this._domain,method,request,callback);});}};Protocol.InspectorBackend._DispatcherPrototype=class{constructor(){this._eventArgs={};}
registerEvent(eventName,params){this._eventArgs[eventName]=params;}
addDomainDispatcher(dispatcher){this._dispatchers.push(dispatcher);}
dispatch(functionName,messageObject){if(!this._dispatchers.length)
return;if(!this._eventArgs[messageObject.method]){Protocol.InspectorBackend.reportProtocolError(`Protocol Error: Attempted to dispatch an unspecified method '${messageObject.method}'`,messageObject);return;}
const params=[];if(messageObject.params){const paramNames=this._eventArgs[messageObject.method];for(let i=0;i<paramNames.length;++i)
params.push(messageObject.params[paramNames[i]]);}
for(let index=0;index<this._dispatchers.length;++index){const dispatcher=this._dispatchers[index];if(functionName in dispatcher)
dispatcher[functionName].apply(dispatcher,params);}}};;Protocol.inspectorBackend.registerEnum("Accessibility.AXValueType",{Boolean:"boolean",Tristate:"tristate",BooleanOrUndefined:"booleanOrUndefined",Idref:"idref",IdrefList:"idrefList",Integer:"integer",Node:"node",NodeList:"nodeList",Number:"number",String:"string",ComputedString:"computedString",Token:"token",TokenList:"tokenList",DomRelation:"domRelation",Role:"role",InternalRole:"internalRole",ValueUndefined:"valueUndefined"});Protocol.inspectorBackend.registerEnum("Accessibility.AXValueSourceType",{Attribute:"attribute",Implicit:"implicit",Style:"style",Contents:"contents",Placeholder:"placeholder",RelatedElement:"relatedElement"});Protocol.inspectorBackend.registerEnum("Accessibility.AXValueNativeSourceType",{Figcaption:"figcaption",Label:"label",Labelfor:"labelfor",Labelwrapped:"labelwrapped",Legend:"legend",Tablecaption:"tablecaption",Title:"title",Other:"other"});Protocol.inspectorBackend.registerEnum("Accessibility.AXPropertyName",{Busy:"busy",Disabled:"disabled",Editable:"editable",Focusable:"focusable",Focused:"focused",Hidden:"hidden",HiddenRoot:"hiddenRoot",Invalid:"invalid",Keyshortcuts:"keyshortcuts",Settable:"settable",Roledescription:"roledescription",Live:"live",Atomic:"atomic",Relevant:"relevant",Root:"root",Autocomplete:"autocomplete",HasPopup:"hasPopup",Level:"level",Multiselectable:"multiselectable",Orientation:"orientation",Multiline:"multiline",Readonly:"readonly",Required:"required",Valuemin:"valuemin",Valuemax:"valuemax",Valuetext:"valuetext",Checked:"checked",Expanded:"expanded",Modal:"modal",Pressed:"pressed",Selected:"selected",Activedescendant:"activedescendant",Controls:"controls",Describedby:"describedby",Details:"details",Errormessage:"errormessage",Flowto:"flowto",Labelledby:"labelledby",Owns:"owns"});Protocol.inspectorBackend.registerCommand("Accessibility.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Accessibility.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Accessibility.getPartialAXTree",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true},{"name":"fetchRelatives","type":"boolean","optional":true}],["nodes"],false);Protocol.inspectorBackend.registerCommand("Accessibility.getFullAXTree",[],["nodes"],false);Protocol.inspectorBackend.registerEnum("Animation.AnimationType",{CSSTransition:"CSSTransition",CSSAnimation:"CSSAnimation",WebAnimation:"WebAnimation"});Protocol.inspectorBackend.registerEvent("Animation.animationCanceled",["id"]);Protocol.inspectorBackend.registerEvent("Animation.animationCreated",["id"]);Protocol.inspectorBackend.registerEvent("Animation.animationStarted",["animation"]);Protocol.inspectorBackend.registerCommand("Animation.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Animation.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Animation.getCurrentTime",[{"name":"id","type":"string","optional":false}],["currentTime"],false);Protocol.inspectorBackend.registerCommand("Animation.getPlaybackRate",[],["playbackRate"],false);Protocol.inspectorBackend.registerCommand("Animation.releaseAnimations",[{"name":"animations","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.resolveAnimation",[{"name":"animationId","type":"string","optional":false}],["remoteObject"],false);Protocol.inspectorBackend.registerCommand("Animation.seekAnimations",[{"name":"animations","type":"object","optional":false},{"name":"currentTime","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.setPaused",[{"name":"animations","type":"object","optional":false},{"name":"paused","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.setPlaybackRate",[{"name":"playbackRate","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.setTiming",[{"name":"animationId","type":"string","optional":false},{"name":"
break;case SDK.Target.Type.ServiceWorker:this._capabilitiesMask=SDK.Target.Capability.Log|SDK.Target.Capability.Network|SDK.Target.Capability.Target;if(!parentTarget)
this._capabilitiesMask|=SDK.Target.Capability.Browser|SDK.Target.Capability.Inspector;break;case SDK.Target.Type.Worker:this._capabilitiesMask=SDK.Target.Capability.JS|SDK.Target.Capability.Log|SDK.Target.Capability.Network|SDK.Target.Capability.Target;break;case SDK.Target.Type.Node:this._capabilitiesMask=SDK.Target.Capability.JS;break;case SDK.Target.Type.Browser:this._capabilitiesMask=SDK.Target.Capability.Target;break;}
this._type=type;this._parentTarget=parentTarget;this._id=id;this._modelByConstructor=new Map();this._isSuspended=suspended;}
createModels(required){this._creatingModels=true;this.model(SDK.ResourceTreeModel);const registered=Array.from(SDK.SDKModel._registeredModels.keys());for(const modelClass of registered){const info=SDK.SDKModel._registeredModels.get(modelClass);if(info.autostart||required.has(modelClass))
this.model(modelClass);}
this._creatingModels=false;}
id(){return this._id;}
name(){return this._name||this._inspectedURLName;}
type(){return this._type;}
markAsNodeJSForTest(){super.markAsNodeJSForTest();this._type=SDK.Target.Type.Node;}
targetManager(){return this._targetManager;}
hasAllCapabilities(capabilitiesMask){return(this._capabilitiesMask&capabilitiesMask)===capabilitiesMask;}
decorateLabel(label){return(this._type===SDK.Target.Type.Worker||this._type===SDK.Target.Type.ServiceWorker)?'\u2699 '+label:label;}
parentTarget(){return this._parentTarget;}
dispose(reason){super.dispose(reason);this._targetManager.removeTarget(this);for(const model of this._modelByConstructor.valuesArray())
model.dispose();}
model(modelClass){if(!this._modelByConstructor.get(modelClass)){const info=SDK.SDKModel._registeredModels.get(modelClass);if(info===undefined)
throw'Model class is not registered @'+new Error().stack;if((this._capabilitiesMask&info.capabilities)===info.capabilities){const model=new modelClass(this);this._modelByConstructor.set(modelClass,model);if(!this._creatingModels)
this._targetManager.modelAdded(this,modelClass,model);}}
return this._modelByConstructor.get(modelClass)||null;}
models(){return this._modelByConstructor;}
inspectedURL(){return this._inspectedURL;}
setInspectedURL(inspectedURL){this._inspectedURL=inspectedURL;const parsedURL=inspectedURL.asParsedURL();this._inspectedURLName=parsedURL?parsedURL.lastPathComponentWithFragment():'#'+this._id;if(!this.parentTarget())
InspectorFrontendHost.inspectedURLChanged(inspectedURL||'');this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.InspectedURLChanged,this);if(!this._name)
this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.NameChanged,this);}
suspend(){if(this._isSuspended)
return Promise.resolve();this._isSuspended=true;const promises=[];for(const model of this.models().values())
promises.push(model.suspendModel());return Promise.all(promises);}
resume(){if(!this._isSuspended)
return Promise.resolve();this._isSuspended=false;const promises=[];for(const model of this.models().values())
promises.push(model.resumeModel());return Promise.all(promises);}
suspended(){return this._isSuspended;}};SDK.Target.Capability={Browser:1<<0,DOM:1<<1,JS:1<<2,Log:1<<3,Network:1<<4,Target:1<<5,ScreenCapture:1<<6,Tracing:1<<7,Emulation:1<<8,Security:1<<9,Input:1<<10,Inspector:1<<11,DeviceEmulation:1<<12,None:0,};SDK.Target.Type={Frame:'frame',ServiceWorker:'service-worker',Worker:'worker',Node:'node',Browser:'browser',};SDK.SDKModel=class extends Common.Object{constructor(target){super();this._target=target;}
target(){return this._target;}
suspendModel(){return Promise.resolve();}
resumeModel(){return Promise.resolve();}
dispose(){}};SDK.SDKModel.register=function(modelClass,capabilities,autostart){if(!SDK.SDKModel._registeredModels)
SDK.SDKModel._registeredModels=new Map();SDK.SDKModel._registeredModels.set(modelClass,{capabilities:capabilities,autostart:autostart});};SDK.SDKModel._registeredModels;;SDK.TargetManager=class extends Common.Object{constructor(){super();this._targets=[];this._observers=[];this._modelListeners=new Multimap();this._modelObservers=new Multimap();this._isSuspended=false;}
suspendAllTargets(){if(this._isSuspended)
return Promise.resolve();this._isSuspended=true;this.dispatchEventToListeners(SDK.TargetManager.Events.SuspendStateChanged);return Promise.all(this._targets.map(target=>target.suspend()));}
resumeAllTargets(){if(!this._isSuspended)
return Promise.resolve();this._isSuspended=false;this.dispatchEventToListeners(SDK.TargetManager.Events.SuspendStateChanged);return Promise.all(this._targets.map(target=>target.resume()));}
allTargetsSuspended(){return this._isSuspended;}
models(modelClass){const result=[];for(let i=0;i<this._targets.length;++i){const model=this._targets[i].model(modelClass);if(model)
result.push(model);}
return result;}
inspectedURL(){return this._targets[0]?this._targets[0].inspectedURL():'';}
observeModels(modelClass,observer){const models=this.models(modelClass);this._modelObservers.set(modelClass,observer);for(const model of models)
observer.modelAdded(model);}
unobserveModels(modelClass,observer){this._modelObservers.delete(modelClass,observer);}
modelAdded(target,modelClass,model){for(const observer of this._modelObservers.get(modelClass).valuesArray())
observer.modelAdded(model);}
_modelRemoved(target,modelClass,model){for(const observer of this._modelObservers.get(modelClass).valuesArray())
observer.modelRemoved(model);}
addModelListener(modelClass,eventType,listener,thisObject){for(let i=0;i<this._targets.length;++i){const model=this._targets[i].model(modelClass);if(model)
model.addEventListener(eventType,listener,thisObject);}
this._modelListeners.set(eventType,{modelClass:modelClass,thisObject:thisObject,listener:listener});}
removeModelListener(modelClass,eventType,listener,thisObject){if(!this._modelListeners.has(eventType))
return;for(let i=0;i<this._targets.length;++i){const model=this._targets[i].model(modelClass);if(model)
model.removeEventListener(eventType,listener,thisObject);}
for(const info of this._modelListeners.get(eventType)){if(info.modelClass===modelClass&&info.listener===listener&&info.thisObject===thisObject)
this._modelListeners.delete(eventType,info);}}
observeTargets(targetObserver){if(this._observers.indexOf(targetObserver)!==-1)
throw new Error('Observer can only be registered once');for(const target of this._targets)
targetObserver.targetAdded(target);this._observers.push(targetObserver);}
unobserveTargets(targetObserver){this._observers.remove(targetObserver);}
createTarget(id,name,type,parentTarget,sessionId,waitForDebuggerInPage,connection){const target=new SDK.Target(this,id,name,type,parentTarget,sessionId||'',this._isSuspended,connection||null);if(waitForDebuggerInPage)
target.pageAgent().waitForDebugger();target.createModels(new Set(this._modelObservers.keysArray()));this._targets.push(target);const copy=this._observers.slice(0);for(const observer of copy)
observer.targetAdded(target);for(const modelClass of target.models().keys())
this.modelAdded(target,modelClass,target.models().get(modelClass));for(const key of this._modelListeners.keysArray()){for(const info of this._modelListeners.get(key)){const model=target.model(info.modelClass);if(model)
model.addEventListener(key,info.listener,info.thisObject);}}
return target;}
removeTarget(target){if(!this._targets.includes(target))
return;this._targets.remove(target);for(const modelClass of target.models().keys())
this._modelRemoved(target,modelClass,target.models().get(modelClass));const copy=this._observers.slice(0);for(const observer of copy)
observer.targetRemoved(target);for(const key of this._modelListeners.keysArray()){for(const info of this._modelListeners.get(key)){const model=target.model(info.modelClass);if(model)
model.removeEventListener(key,info.listener,info.thisObject);}}}
targets(){return this._targets.slice();}
targetById(id){for(let i=0;i<this._targets.length;++i){if(this._targets[i].id()===id)
return this._targets[i];}
return null;}
mainTarget(){return this._targets[0]||null;}};SDK.TargetManager.Events={AvailableTargetsChanged:Symbol('AvailableTargetsChanged'),InspectedURLChanged:Symbol('InspectedURLChanged'),NameChanged:Symbol('NameChanged'),SuspendStateChanged:Symbol('SuspendStateChanged')};SDK.TargetManager.Observer=function(){};SDK.TargetManager.Observer.prototype={targetAdded(target){},targetRemoved(target){},};SDK.SDKModelObserver=function(){};SDK.SDKModelObserver.prototype={modelAdded(model){},modelRemoved(model){},};SDK.targetManager=new SDK.TargetManager();;SDK.MainConnection=class{constructor(){this._onMessage=null;this._onDisconnect=null;this._messageBuffer='';this._messageSize=0;this._eventListeners=[InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DispatchMessage,this._dispatchMessage,this),InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DispatchMessageChunk,this._dispatchMessageChunk,this),];}
setOnMessage(onMessage){this._onMessage=onMessage;}
setOnDisconnect(onDisconnect){this._onDisconnect=onDisconnect;}
sendRawMessage(message){if(this._onMessage)
InspectorFrontendHost.sendMessageToBackend(message);}
_dispatchMessage(event){if(this._onMessage)
this._onMessage.call(null,(event.data));}
_dispatchMessageChunk(event){const messageChunk=(event.data['messageChunk']);const messageSize=(event.data['messageSize']);if(messageSize){this._messageBuffer='';this._messageSize=messageSize;}
this._messageBuffer+=messageChunk;if(this._messageBuffer.length===this._messageSize){this._onMessage.call(null,this._messageBuffer);this._messageBuffer='';this._messageSize=0;}}
disconnect(){const onDisconnect=this._onDisconnect;Common.EventTarget.removeEventListeners(this._eventListeners);this._onDisconnect=null;this._onMessage=null;let fulfill;const promise=new Promise(f=>fulfill=f);InspectorFrontendHost.reattach(()=>{if(onDisconnect)
onDisconnect.call(null,'force disconnect');fulfill();});return promise;}};SDK.WebSocketConnection=class{constructor(url,onWebSocketDisconnect){this._socket=new WebSocket(url);this._socket.onerror=this._onError.bind(this);this._socket.onopen=this._onOpen.bind(this);this._socket.onmessage=messageEvent=>{if(this._onMessage)
this._onMessage.call(null,(messageEvent.data));};this._socket.onclose=this._onClose.bind(this);this._onMessage=null;this._onDisconnect=null;this._onWebSocketDisconnect=onWebSocketDisconnect;this._connected=false;this._messages=[];}
setOnMessage(onMessage){this._onMessage=onMessage;}
setOnDisconnect(onDisconnect){this._onDisconnect=onDisconnect;}
_onError(){this._onWebSocketDisconnect.call(null);this._onDisconnect.call(null,'connection failed');this._close();}
_onOpen(){this._socket.onerror=console.error;this._connected=true;for(const message of this._messages)
this._socket.send(message);this._messages=[];}
_onClose(){this._onWebSocketDisconnect.call(null);this._onDisconnect.call(null,'websocket closed');this._close();}
_close(callback){this._socket.onerror=null;this._socket.onopen=null;this._socket.onclose=callback||null;this._socket.onmessage=null;this._socket.close();this._socket=null;this._onWebSocketDisconnect=null;}
sendRawMessage(message){if(this._connected)
this._socket.send(message);else
this._messages.push(message);}
disconnect(){let fulfill;const promise=new Promise(f=>fulfill=f);this._close(()=>{if(this._onDisconnect)
this._onDisconnect.call(null,'force disconnect');fulfill();});return promise;}};SDK.StubConnection=class{constructor(){this._onMessage=null;this._onDisconnect=null;}
setOnMessage(onMessage){this._onMessage=onMessage;}
setOnDisconnect(onDisconnect){this._onDisconnect=onDisconnect;}
sendRawMessage(message){setTimeout(this._respondWithError.bind(this,message),0);}
_respondWithError(message){const messageObject=JSON.parse(message);const error={message:'This is a stub connection, can\'t dispatch message.',code:Protocol.DevToolsStubErrorCode,data:messageObject};if(this._onMessage)
this._onMessage.call(null,{id:messageObject.id,error:error});}
disconnect(){if(this._onDisconnect)
this._onDisconnect.call(null,'force disconnect');this._onDisconnect=null;this._onMessage=null;return Promise.resolve();}};SDK.initMainConnection=async function(createMainTarget,websocketConnectionLost){SDK._websocketConnectionLost=websocketConnectionLost;SDK._createMainTarget=createMainTarget;Protocol.Connection.setFactory(SDK._createMainConnection);await SDK._createMainTarget();InspectorFrontendHost.connectionReady();return Promise.resolve();};SDK._createMainConnection=function(){const wsParam=Runtime.queryParam('ws');const wssParam=Runtime.queryParam('wss');if(wsParam||wssParam){const ws=wsParam?`ws://${wsParam}`:`wss://${wssParam}`;SDK._mainConnection=new SDK.WebSocketConnection(ws,SDK._websocketConnectionLost);}else if(InspectorFrontendHost.isHostedMode()){SDK._mainConnection=new SDK.StubConnection();}else{SDK._mainConnection=new SDK.MainConnection();}
return SDK._mainConnection;};SDK._mainConnection;SDK._createMainTarget;SDK._websocketConnectionLost;SDK.interceptMainConnection=async function(onMessage){await SDK._mainConnection.disconnect();const connection=SDK._createMainConnection();connection.setOnMessage(onMessage);connection.setOnDisconnect(SDK._createMainTarget);return connection;};;SDK.CompilerSourceMappingContentProvider=class{constructor(sourceURL,contentType){this._sourceURL=sourceURL;this._contentType=contentType;}
contentURL(){return this._sourceURL;}
contentType(){return this._contentType;}
contentEncoded(){return Promise.resolve(false);}
requestContent(){let callback;const promise=new Promise(fulfill=>callback=fulfill);SDK.multitargetNetworkManager.loadResource(this._sourceURL,contentLoaded.bind(this));return promise;function contentLoaded(statusCode,headers,content){if(statusCode>=400){console.error('Could not load content for '+this._sourceURL+' : '+'HTTP status code: '+statusCode);callback(null);return;}
callback(content);}}
async searchInContent(query,caseSensitive,isRegex){const content=await this.requestContent();if(typeof content!=='string')
return[];return Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex);}};;SDK.CookieModel=class extends SDK.SDKModel{constructor(target){super(target);}
static _parseProtocolCookie(protocolCookie){const cookie=new SDK.Cookie(protocolCookie.name,protocolCookie.value,null);cookie.addAttribute('domain',protocolCookie['domain']);cookie.addAttribute('path',protocolCookie['path']);cookie.addAttribute('port',protocolCookie['port']);if(protocolCookie['expires'])
cookie.addAttribute('expires',protocolCookie['expires']*1000);if(protocolCookie['httpOnly'])
cookie.addAttribute('httpOnly');if(protocolCookie['secure'])
cookie.addAttribute('secure');if(protocolCookie['sameSite'])
cookie.addAttribute('sameSite',protocolCookie['sameSite']);cookie.setSize(protocolCookie['size']);return cookie;}
static cookieMatchesResourceURL(cookie,resourceURL){const url=resourceURL.asParsedURL();if(!url||!SDK.CookieModel.cookieDomainMatchesResourceDomain(cookie.domain(),url.host))
return false;return(url.path.startsWith(cookie.path())&&(!cookie.port()||url.port===cookie.port())&&(!cookie.secure()||url.scheme==='https'));}
static cookieDomainMatchesResourceDomain(cookieDomain,resourceDomain){if(cookieDomain.charAt(0)!=='.')
return resourceDomain===cookieDomain;return!!resourceDomain.match(new RegExp('^([^\\.]+\\.)*'+cookieDomain.substring(1).escapeForRegExp()+'$','i'));}
getCookies(urls){return this.target().networkAgent().getCookies(urls).then(cookies=>(cookies||[]).map(cookie=>SDK.CookieModel._parseProtocolCookie(cookie)));}
deleteCookie(cookie,callback){this._deleteAll([cookie],callback);}
clear(domain,callback){this.getCookiesForDomain(domain||null).then(cookies=>this._deleteAll(cookies,callback));}
saveCookie(cookie){let domain=cookie.domain();if(!domain.startsWith('.'))
domain='';let expires=undefined;if(cookie.expires())
expires=Math.floor(Date.parse(cookie.expires())/1000);return this.target().networkAgent().setCookie(cookie.name(),cookie.value(),cookie.url(),domain,cookie.path(),cookie.secure(),cookie.httpOnly(),cookie.sameSite(),expires).then(success=>!!success);}
getCookiesForDomain(domain){const resourceURLs=[];function populateResourceURLs(resource){const documentURL=resource.documentURL.asParsedURL();if(documentURL&&(!domain||documentURL.securityOrigin()===domain))
resourceURLs.push(resource.url);}
const resourceTreeModel=this.target().model(SDK.ResourceTreeModel);if(resourceTreeModel)
resourceTreeModel.forAllResources(populateResourceURLs);return this.getCookies(resourceURLs);}
_deleteAll(cookies,callback){const networkAgent=this.target().networkAgent();Promise.all(cookies.map(cookie=>networkAgent.deleteCookies(cookie.name(),undefined,cookie.domain(),cookie.path()))).then(callback||function(){});}};SDK.SDKModel.register(SDK.CookieModel,SDK.Target.Capability.Network,false);;SDK.CookieParser=class{constructor(){}
static parseCookie(header){return(new SDK.CookieParser()).parseCookie(header);}
static parseSetCookie(header){return(new SDK.CookieParser()).parseSetCookie(header);}
cookies(){return this._cookies;}
parseCookie(cookieHeader){if(!this._initialize(cookieHeader))
return null;for(let kv=this._extractKeyValue();kv;kv=this._extractKeyValue()){if(kv.key.charAt(0)==='$'&&this._lastCookie)
this._lastCookie.addAttribute(kv.key.slice(1),kv.value);else if(kv.key.toLowerCase()!=='$version'&&typeof kv.value==='string')
this._addCookie(kv,SDK.Cookie.Type.Request);this._advanceAndCheckCookieDelimiter();}
this._flushCookie();return this._cookies;}
parseSetCookie(setCookieHeader){if(!this._initialize(setCookieHeader))
return null;for(let kv=this._extractKeyValue();kv;kv=this._extractKeyValue()){if(this._lastCookie)
this._lastCookie.addAttribute(kv.key,kv.value);else
this._addCookie(kv,SDK.Cookie.Type.Response);if(this._advanceAndCheckCookieDelimiter())
this._flushCookie();}
this._flushCookie();return this._cookies;}
_initialize(headerValue){this._input=headerValue;if(typeof headerValue!=='string')
return false;this._cookies=[];this._lastCookie=null;this._originalInputLength=this._input.length;return true;}
_flushCookie(){if(this._lastCookie)
this._lastCookie.setSize(this._originalInputLength-this._input.length-this._lastCookiePosition);this._lastCookie=null;}
_extractKeyValue(){if(!this._input||!this._input.length)
return null;const keyValueMatch=/^[ \t]*([^\s=;]+)[ \t]*(?:=[ \t]*([^;\n]*))?/.exec(this._input);if(!keyValueMatch){console.error('Failed parsing cookie header before: '+this._input);return null;}
const result=new SDK.CookieParser.KeyValue(keyValueMatch[1],keyValueMatch[2]&&keyValueMatch[2].trim(),this._originalInputLength-this._input.length);this._input=this._input.slice(keyValueMatch[0].length);return result;}
_advanceAndCheckCookieDelimiter(){const match=/^\s*[\n;]\s*/.exec(this._input);if(!match)
return false;this._input=this._input.slice(match[0].length);return match[0].match('\n')!==null;}
_addCookie(keyValue,type){if(this._lastCookie)
this._lastCookie.setSize(keyValue.position-this._lastCookiePosition);this._lastCookie=typeof keyValue.value==='string'?new SDK.Cookie(keyValue.key,keyValue.value,type):new SDK.Cookie('',keyValue.key,type);this._lastCookiePosition=keyValue.position;this._cookies.push(this._lastCookie);}};SDK.CookieParser.KeyValue=class{constructor(key,value,position){this.key=key;this.value=value;this.position=position;}};SDK.Cookie=class{constructor(name,value,type){this._name=name;this._value=value;this._type=type;this._attributes={};this._size=0;}
name(){return this._name;}
value(){return this._value;}
type(){return this._type;}
httpOnly(){return'httponly'in this._attributes;}
secure(){return'secure'in this._attributes;}
sameSite(){return(this._attributes['samesite']);}
session(){return!('expires'in this._attributes||'max-age'in this._attributes);}
path(){return this._attributes['path'];}
port(){return this._attributes['port'];}
domain(){return this._attributes['domain'];}
expires(){return this._attributes['expires'];}
maxAge(){return this._attributes['max-age'];}
size(){return this._size;}
url(){return(this.secure()?'https://':'http://')+this.domain()+this.path();}
setSize(size){this._size=size;}
expiresDate(requestDate){if(this.maxAge()){const targetDate=requestDate===null?new Date():requestDate;return new Date(targetDate.getTime()+1000*this.maxAge());}
if(this.expires())
return new Date(this.expires());return null;}
attributes(){return this._attributes;}
addAttribute(key,value){this._attributes[key.toLowerCase()]=value;}};SDK.Cookie.Type={Request:0,Response:1};;SDK.ProfileNode=class{constructor(callFrame){this.callFrame=callFrame;this.callUID=`${callFrame.functionName}@${callFrame.scriptId}:${callFrame.lineNumber}:${callFrame.columnNumber}`;this.self=0;this.total=0;this.id=0;this.parent=null;this.children=[];}
get functionName(){return this.callFrame.functionName;}
get scriptId(){return this.callFrame.scriptId;}
get url(){return this.callFrame.url;}
get lineNumber(){return this.callFrame.lineNumber;}
get columnNumber(){return this.callFrame.columnNumber;}};SDK.ProfileTreeModel=class{constructor(target){this._target=target||null;}
initialize(root){this.root=root;this._assignDepthsAndParents();this.total=this._calculateTotals(this.root);}
_assignDepthsAndParents(){const root=this.root;root.depth=-1;root.parent=null;this.maxDepth=0;const nodesToTraverse=[root];while(nodesToTraverse.length){const parent=nodesToTraverse.pop();const depth=parent.depth+1;if(depth>this.maxDepth)
this.maxDepth=depth;const children=parent.children;const length=children.length;for(let i=0;i<length;++i){const child=children[i];child.depth=depth;child.parent=parent;if(child.children.length)
nodesToTraverse.push(child);}}}
_calculateTotals(root){const nodesToTraverse=[root];const dfsList=[];while(nodesToTraverse.length){const node=nodesToTraverse.pop();node.total=node.self;dfsList.push(node);nodesToTraverse.push(...node.children);}
while(dfsList.length>1){const node=dfsList.pop();node.parent.total+=node.total;}
return root.total;}
target(){return this._target;}};;SDK.ServerTiming=class{constructor(metric,value,description){this.metric=metric;this.value=value;this.description=description;}
static parseHeaders(headers){const rawServerTimingHeaders=headers.filter(item=>item.name.toLowerCase()==='server-timing');if(!rawServerTimingHeaders.length)
return null;const serverTimings=rawServerTimingHeaders.reduce((memo,header)=>{const timing=this.createFromHeaderValue(header.value);memo.pushAll(timing.map(function(entry){return new SDK.ServerTiming(entry.name,entry.hasOwnProperty('dur')?entry.dur:null,entry.hasOwnProperty('desc')?entry.desc:'');}));return memo;},[]);serverTimings.sort((a,b)=>a.metric.toLowerCase().compareTo(b.metric.toLowerCase()));return serverTimings;}
static createFromHeaderValue(valueString){function trimLeadingWhiteSpace(){valueString=valueString.replace(/^\s*/,'');}
function consumeDelimiter(char){console.assert(char.length===1);trimLeadingWhiteSpace();if(valueString.charAt(0)!==char)
return false;valueString=valueString.substring(1);return true;}
function consumeToken(){const result=/^(?:\s*)([\w!#$%&'*+\-.^`|~]+)(?:\s*)(.*)/.exec(valueString);if(!result)
return null;valueString=result[2];return result[1];}
function consumeTokenOrQuotedString(){trimLeadingWhiteSpace();if(valueString.charAt(0)==='"')
return consumeQuotedString();return consumeToken();}
function consumeQuotedString(){console.assert(valueString.charAt(0)==='"');valueString=valueString.substring(1);let value='';while(valueString.length){const result=/^([^"\\]*)(.*)/.exec(valueString);value+=result[1];if(result[2].charAt(0)==='"'){valueString=result[2].substring(1);return value;}
console.assert(result[2].charAt(0)==='\\');value+=result[2].charAt(1);valueString=result[2].substring(2);}
return null;}
function consumeExtraneous(){const result=/([,;].*)/.exec(valueString);if(result)
valueString=result[1];}
const result=[];let name;while((name=consumeToken())!==null){const entry={name};if(valueString.charAt(0)==='=')
this.showWarning(ls`Deprecated syntax found. Please use: <name>;dur=<duration>;desc=<description>`);while(consumeDelimiter(';')){let paramName;if((paramName=consumeToken())===null)
continue;paramName=paramName.toLowerCase();const parseParameter=this.getParserForParameter(paramName);let paramValue=null;if(consumeDelimiter('=')){paramValue=consumeTokenOrQuotedString();consumeExtraneous();}
if(parseParameter){if(entry.hasOwnProperty(paramName)){this.showWarning(ls`Duplicate parameter \"${paramName}\" ignored.`);continue;}
if(paramValue===null)
this.showWarning(ls`No value found for parameter \"${paramName}\".`);parseParameter.call(this,entry,paramValue);}else{this.showWarning(ls`Unrecognized parameter \"${paramName}\".`);}}
result.push(entry);if(!consumeDelimiter(','))
break;}
if(valueString.length)
this.showWarning(ls`Extraneous trailing characters.`);return result;}
static getParserForParameter(paramName){switch(paramName){case'dur':return function(entry,paramValue){entry.dur=0;if(paramValue!==null){const duration=parseFloat(paramValue);if(isNaN(duration)){this.showWarning(ls`Unable to parse \"${paramName}\" value \"${paramValue}\".`);return;}
entry.dur=duration;}};case'desc':return function(entry,paramValue){entry.desc=paramValue||'';};default:return null;}}
static showWarning(msg){Common.console.warn(Common.UIString(`ServerTiming: ${msg}`));}};;SDK.CPUProfileNode=class extends SDK.ProfileNode{constructor(node,sampleTime){const callFrame=node.callFrame||({functionName:node['functionName'],scriptId:node['scriptId'],url:node['url'],lineNumber:node['lineNumber']-1,columnNumber:node['columnNumber']-1});super(callFrame);this.id=node.id;this.self=node.hitCount*sampleTime;this.positionTicks=node.positionTicks;this.deoptReason=node.deoptReason&&node.deoptReason!=='no reason'?node.deoptReason:null;}};SDK.CPUProfileDataModel=class extends SDK.ProfileTreeModel{constructor(profile,target){super(target);const isLegacyFormat=!!profile['head'];if(isLegacyFormat){this.profileStartTime=profile.startTime*1000;this.profileEndTime=profile.endTime*1000;this.timestamps=profile.timestamps;this._compatibilityConversionHeadToNodes(profile);}else{this.profileStartTime=profile.startTime/1000;this.profileEndTime=profile.endTime/1000;this.timestamps=this._convertTimeDeltas(profile);}
this.samples=profile.samples;this.lines=profile.lines;this.totalHitCount=0;this.profileHead=this._translateProfileTree(profile.nodes);this.initialize(this.profileHead);this._extractMetaNodes();if(this.samples){this._buildIdToNodeMap();this._sortSamples();this._normalizeTimestamps();this._fixMissingSamples();}}
_compatibilityConversionHeadToNodes(profile){if(!profile.head||profile.nodes)
return;const nodes=[];convertNodesTree(profile.head);profile.nodes=nodes;delete profile.head;function convertNodesTree(node){nodes.push(node);node.children=((node.children)).map(convertNodesTree);return node.id;}}
_convertTimeDeltas(profile){if(!profile.timeDeltas)
return null;let lastTimeUsec=profile.startTime;const timestamps=new Array(profile.timeDeltas.length);for(let i=0;i<profile.timeDeltas.length;++i){lastTimeUsec+=profile.timeDeltas[i];timestamps[i]=lastTimeUsec;}
return timestamps;}
_translateProfileTree(nodes){function isNativeNode(node){if(node.callFrame)
return!!node.callFrame.url&&node.callFrame.url.startsWith('native ');return!!node['url']&&node['url'].startsWith('native ');}
function buildChildrenFromParents(nodes){if(nodes[0].children)
return;nodes[0].children=[];for(let i=1;i<nodes.length;++i){const node=nodes[i];const parentNode=nodeByIdMap.get(node.parent);if(parentNode.children)
parentNode.children.push(node.id);else
parentNode.children=[node.id];}}
function buildHitCountFromSamples(nodes,samples){if(typeof(nodes[0].hitCount)==='number')
return;console.assert(samples,'Error: Neither hitCount nor samples are present in profile.');for(let i=0;i<nodes.length;++i)
nodes[i].hitCount=0;for(let i=0;i<samples.length;++i)
++nodeByIdMap.get(samples[i]).hitCount;}
const nodeByIdMap=new Map();for(let i=0;i<nodes.length;++i){const node=nodes[i];nodeByIdMap.set(node.id,node);}
buildHitCountFromSamples(nodes,this.samples);buildChildrenFromParents(nodes);this.totalHitCount=nodes.reduce((acc,node)=>acc+node.hitCount,0);const sampleTime=(this.profileEndTime-this.profileStartTime)/this.totalHitCount;const keepNatives=!!Common.moduleSetting('showNativeFunctionsInJSProfile').get();const root=nodes[0];const idMap=new Map([[root.id,root.id]]);const resultRoot=new SDK.CPUProfileNode(root,sampleTime);const parentNodeStack=root.children.map(()=>resultRoot);const sourceNodeStack=root.children.map(id=>nodeByIdMap.get(id));while(sourceNodeStack.length){let parentNode=parentNodeStack.pop();const sourceNode=sourceNodeStack.pop();if(!sourceNode.children)
sourceNode.children=[];const targetNode=new SDK.CPUProfileNode(sourceNode,sampleTime);if(keepNatives||!isNativeNode(sourceNode)){parentNode.children.push(targetNode);parentNode=targetNode;}else{parentNode.self+=targetNode.self;}
idMap.set(sourceNode.id,parentNode.id);parentNodeStack.push.apply(parentNodeStack,sourceNode.children.map(()=>parentNode));sourceNodeStack.push.apply(sourceNodeStack,sourceNode.children.map(id=>nodeByIdMap.get(id)));}
if(this.samples)
this.samples=this.samples.map(id=>idMap.get(id));return resultRoot;}
_sortSamples(){const timestamps=this.timestamps;if(!timestamps)
return;const samples=this.samples;const indices=timestamps.map((x,index)=>index);indices.stableSort((a,b)=>timestamps[a]-timestamps[b]);for(let i=0;i<timestamps.length;++i){let index=indices[i];if(index===i)
continue;const savedTimestamp=timestamps[i];const savedSample=samples[i];let currentIndex=i;while(index!==i){samples[currentIndex]=samples[index];timestamps[currentIndex]=timestamps[index];currentIndex=index;index=indices[index];indices[currentIndex]=currentIndex;}
samples[currentIndex]=savedSample;timestamps[currentIndex]=savedTimestamp;}}
_normalizeTimestamps(){let timestamps=this.timestamps;if(!timestamps){const profileStartTime=this.profileStartTime;const interval=(this.profileEndTime-profileStartTime)/this.samples.length;timestamps=new Float64Array(this.samples.length+1);for(let i=0;i<timestamps.length;++i)
timestamps[i]=profileStartTime+i*interval;this.timestamps=timestamps;return;}
for(let i=0;i<timestamps.length;++i)
timestamps[i]/=1000;if(this.samples.length===timestamps.length){const averageSample=(timestamps.peekLast()-timestamps[0])/(timestamps.length-1);this.timestamps.push(timestamps.peekLast()+averageSample);}
this.profileStartTime=timestamps[0];this.profileEndTime=timestamps.peekLast();}
_buildIdToNodeMap(){this._idToNode=new Map();const idToNode=this._idToNode;const stack=[this.profileHead];while(stack.length){const node=stack.pop();idToNode.set(node.id,node);stack.push.apply(stack,node.children);}}
_extractMetaNodes(){const topLevelNodes=this.profileHead.children;for(let i=0;i<topLevelNodes.length&&!(this.gcNode&&this.programNode&&this.idleNode);i++){const node=topLevelNodes[i];if(node.functionName==='(garbage collector)')
this.gcNode=node;else if(node.functionName==='(program)')
this.programNode=node;else if(node.functionName==='(idle)')
this.idleNode=node;}}
_fixMissingSamples(){const samples=this.samples;const samplesCount=samples.length;if(!this.programNode||samplesCount<3)
return;const idToNode=this._idToNode;const programNodeId=this.programNode.id;const gcNodeId=this.gcNode?this.gcNode.id:-1;const idleNodeId=this.idleNode?this.idleNode.id:-1;let prevNodeId=samples[0];let nodeId=samples[1];let count=0;for(let sampleIndex=1;sampleIndex<samplesCount-1;sampleIndex++){const nextNodeId=samples[sampleIndex+1];if(nodeId===programNodeId&&!isSystemNode(prevNodeId)&&!isSystemNode(nextNodeId)&&bottomNode(idToNode.get(prevNodeId))===bottomNode(idToNode.get(nextNodeId))){++count;samples[sampleIndex]=prevNodeId;}
prevNodeId=nodeId;nodeId=nextNodeId;}
if(count)
Common.console.warn(ls`DevTools: CPU profile parser is fixing ${count} missing samples.`);function bottomNode(node){while(node.parent&&node.parent.parent)
node=node.parent;return node;}
function isSystemNode(nodeId){return nodeId===programNodeId||nodeId===gcNodeId||nodeId===idleNodeId;}}
forEachFrame(openFrameCallback,closeFrameCallback,startTime,stopTime){if(!this.profileHead||!this.samples)
return;startTime=startTime||0;stopTime=stopTime||Infinity;const samples=this.samples;const timestamps=this.timestamps;const idToNode=this._idToNode;const gcNode=this.gcNode;const samplesCount=samples.length;const startIndex=timestamps.lowerBound(startTime);let stackTop=0;const stackNodes=[];let prevId=this.profileHead.id;let sampleTime;let gcParentNode=null;const stackDepth=this.maxDepth+3;if(!this._stackStartTimes)
this._stackStartTimes=new Float64Array(stackDepth);const stackStartTimes=this._stackStartTimes;if(!this._stackChildrenDuration)
this._stackChildrenDuration=new Float64Array(stackDepth);const stackChildrenDuration=this._stackChildrenDuration;let node;let sampleIndex;for(sampleIndex=startIndex;sampleIndex<samplesCount;sampleIndex++){sampleTime=timestamps[sampleIndex];if(sampleTime>=stopTime)
break;const id=samples[sampleIndex];if(id===prevId)
continue;node=idToNode.get(id);let prevNode=idToNode.get(prevId);if(node===gcNode){gcParentNode=prevNode;openFrameCallback(gcParentNode.depth+1,gcNode,sampleTime);stackStartTimes[++stackTop]=sampleTime;stackChildrenDuration[stackTop]=0;prevId=id;continue;}
if(prevNode===gcNode){const start=stackStartTimes[stackTop];const duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(gcParentNode.depth+1,gcNode,start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;prevNode=gcParentNode;prevId=prevNode.id;gcParentNode=null;}
while(node.depth>prevNode.depth){stackNodes.push(node);node=node.parent;}
while(prevNode!==node){const start=stackStartTimes[stackTop];const duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(prevNode.depth,(prevNode),start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;if(node.depth===prevNode.depth){stackNodes.push(node);node=node.parent;}
prevNode=prevNode.parent;}
while(stackNodes.length){node=stackNodes.pop();openFrameCallback(node.depth,node,sampleTime);stackStartTimes[++stackTop]=sampleTime;stackChildrenDuration[stackTop]=0;}
prevId=id;}
sampleTime=timestamps[sampleIndex]||this.profileEndTime;if(idToNode.get(prevId)===gcNode){const start=stackStartTimes[stackTop];const duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(gcParentNode.depth+1,node,start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;prevId=gcParentNode.id;}
for(let node=idToNode.get(prevId);node.parent;node=node.parent){const start=stackStartTimes[stackTop];const duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(node.depth,(node),start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;}}
nodeByIndex(index){return this._idToNode.get(this.samples[index])||null;}};;SDK.CPUProfilerModel=class extends SDK.SDKModel{constructor(target){super(target);this._isRecording=false;this._nextAnonymousConsoleProfileNumber=1;this._anonymousConsoleProfileIdToTitle=new Map();this._profilerAgent=target.profilerAgent();target.registerProfilerDispatcher(this);this._profilerAgent.enable();this._debuggerModel=(target.model(SDK.DebuggerModel));}
runtimeModel(){return this._debuggerModel.runtimeModel();}
debuggerModel(){return this._debuggerModel;}
consoleProfileStarted(id,scriptLocation,title){if(!title){title=Common.UIString('Profile %d',this._nextAnonymousConsoleProfileNumber++);this._anonymousConsoleProfileIdToTitle.set(id,title);}
this._dispatchProfileEvent(SDK.CPUProfilerModel.Events.ConsoleProfileStarted,id,scriptLocation,title);}
consoleProfileFinished(id,scriptLocation,cpuProfile,title){if(!title){title=this._anonymousConsoleProfileIdToTitle.get(id);this._anonymousConsoleProfileIdToTitle.delete(id);}
self.runtime.loadModulePromise('profiler').then(()=>{this._dispatchProfileEvent(SDK.CPUProfilerModel.Events.ConsoleProfileFinished,id,scriptLocation,title,cpuProfile);});}
_dispatchProfileEvent(eventName,id,scriptLocation,title,cpuProfile){const debuggerLocation=SDK.DebuggerModel.Location.fromPayload(this._debuggerModel,scriptLocation);const globalId=this.target().id()+'.'+id;const data=({id:globalId,scriptLocation:debuggerLocation,cpuProfile:cpuProfile,title:title,cpuProfilerModel:this});this.dispatchEventToListeners(eventName,data);}
isRecordingProfile(){return this._isRecording;}
startRecording(){this._isRecording=true;const intervalUs=Common.moduleSetting('highResolutionCpuProfiling').get()?100:1000;this._profilerAgent.setSamplingInterval(intervalUs);return this._profilerAgent.start();}
stopRecording(){this._isRecording=false;return this._profilerAgent.stop();}
startPreciseCoverage(){const callCount=false;const detailed=true;return this._profilerAgent.startPreciseCoverage(callCount,detailed);}
takePreciseCoverage(){return this._profilerAgent.takePreciseCoverage().then(result=>result||[]);}
stopPreciseCoverage(){return this._profilerAgent.stopPreciseCoverage();}
bestEffortCoverage(){return this._profilerAgent.getBestEffortCoverage().then(result=>result||[]);}};SDK.SDKModel.register(SDK.CPUProfilerModel,SDK.Target.Capability.JS,true);SDK.CPUProfilerModel.Events={ConsoleProfileStarted:Symbol('ConsoleProfileStarted'),ConsoleProfileFinished:Symbol('ConsoleProfileFinished')};SDK.CPUProfilerModel.EventData;;SDK.CSSMatchedStyles=class{constructor(cssModel,node,inlinePayload,attributesPayload,matchedPayload,pseudoPayload,inheritedPayload,animationsPayload){this._cssModel=cssModel;this._node=node;this._addedStyles=new Map();this._matchingSelectors=new Map();this._keyframes=[];if(animationsPayload)
this._keyframes=animationsPayload.map(rule=>new SDK.CSSKeyframesRule(cssModel,rule));this._nodeForStyle=new Map();this._inheritedStyles=new Set();matchedPayload=cleanUserAgentPayload(matchedPayload);for(const inheritedResult of inheritedPayload)
inheritedResult.matchedCSSRules=cleanUserAgentPayload(inheritedResult.matchedCSSRules);this._mainDOMCascade=this._buildMainCascade(inlinePayload,attributesPayload,matchedPayload,inheritedPayload);this._pseudoDOMCascades=this._buildPseudoCascades(pseudoPayload);this._styleToDOMCascade=new Map();for(const domCascade of Array.from(this._pseudoDOMCascades.values()).concat(this._mainDOMCascade)){for(const style of domCascade.styles())
this._styleToDOMCascade.set(style,domCascade);}
function cleanUserAgentPayload(payload){for(const ruleMatch of payload)
cleanUserAgentSelectors(ruleMatch);const cleanMatchedPayload=[];for(const ruleMatch of payload){const lastMatch=cleanMatchedPayload.peekLast();if(!lastMatch||ruleMatch.rule.origin!=='user-agent'||lastMatch.rule.origin!=='user-agent'||ruleMatch.rule.selectorList.text!==lastMatch.rule.selectorList.text||mediaText(ruleMatch)!==mediaText(lastMatch)){cleanMatchedPayload.push(ruleMatch);continue;}
mergeRule(ruleMatch,lastMatch);}
return cleanMatchedPayload;function mergeRule(from,to){const shorthands=(new Map());const properties=(new Map());for(const entry of to.rule.style.shorthandEntries)
shorthands.set(entry.name,entry.value);for(const entry of to.rule.style.cssProperties)
properties.set(entry.name,entry.value);for(const entry of from.rule.style.shorthandEntries)
shorthands.set(entry.name,entry.value);for(const entry of from.rule.style.cssProperties)
properties.set(entry.name,entry.value);to.rule.style.shorthandEntries=shorthands.keysArray().map(name=>({name,value:shorthands.get(name)}));to.rule.style.cssProperties=properties.keysArray().map(name=>({name,value:properties.get(name)}));}
function mediaText(ruleMatch){if(!ruleMatch.rule.media)
return null;return ruleMatch.rule.media.map(media=>media.text).join(', ');}
function cleanUserAgentSelectors(ruleMatch){const{matchingSelectors,rule}=ruleMatch;if(rule.origin!=='user-agent'||!matchingSelectors.length)
return;rule.selectorList.selectors=rule.selectorList.selectors.filter((item,i)=>matchingSelectors.includes(i));rule.selectorList.text=rule.selectorList.selectors.map(item=>item.text).join(', ');ruleMatch.matchingSelectors=matchingSelectors.map((item,i)=>i);}}}
_buildMainCascade(inlinePayload,attributesPayload,matchedPayload,inheritedPayload){const nodeCascades=[];const nodeStyles=[];function addAttributesStyle(){if(!attributesPayload)
return;const style=new SDK.CSSStyleDeclaration(this._cssModel,null,attributesPayload,SDK.CSSStyleDeclaration.Type.Attributes);this._nodeForStyle.set(style,this._node);nodeStyles.push(style);}
if(inlinePayload&&this._node.nodeType()===Node.ELEMENT_NODE){const style=new SDK.CSSStyleDeclaration(this._cssModel,null,inlinePayload,SDK.CSSStyleDeclaration.Type.Inline);this._nodeForStyle.set(style,this._node);nodeStyles.push(style);}
let addedAttributesStyle;for(let i=matchedPayload.length-1;i>=0;--i){const rule=new SDK.CSSStyleRule(this._cssModel,matchedPayload[i].rule);if((rule.isInjected()||rule.isUserAgent())&&!addedAttributesStyle){addedAttributesStyle=true;addAttributesStyle.call(this);}
this._nodeForStyle.set(rule.style,this._node);nodeStyles.push(rule.style);this._addMatchingSelectors(this._node,rule,matchedPayload[i].matchingSelectors);}
if(!addedAttributesStyle)
addAttributesStyle.call(this);nodeCascades.push(new SDK.CSSMatchedStyles.NodeCascade(this,nodeStyles,false));let parentNode=this._node.parentNode;for(let i=0;parentNode&&inheritedPayload&&i<inheritedPayload.length;++i){const inheritedStyles=[];const entryPayload=inheritedPayload[i];const inheritedInlineStyle=entryPayload.inlineStyle?new SDK.CSSStyleDeclaration(this._cssModel,null,entryPayload.inlineStyle,SDK.CSSStyleDeclaration.Type.Inline):null;if(inheritedInlineStyle&&this._containsInherited(inheritedInlineStyle)){this._nodeForStyle.set(inheritedInlineStyle,parentNode);inheritedStyles.push(inheritedInlineStyle);this._inheritedStyles.add(inheritedInlineStyle);}
const inheritedMatchedCSSRules=entryPayload.matchedCSSRules||[];for(let j=inheritedMatchedCSSRules.length-1;j>=0;--j){const inheritedRule=new SDK.CSSStyleRule(this._cssModel,inheritedMatchedCSSRules[j].rule);this._addMatchingSelectors(parentNode,inheritedRule,inheritedMatchedCSSRules[j].matchingSelectors);if(!this._containsInherited(inheritedRule.style))
continue;if(containsStyle(nodeStyles,inheritedRule.style)||containsStyle(this._inheritedStyles,inheritedRule.style))
continue;this._nodeForStyle.set(inheritedRule.style,parentNode);inheritedStyles.push(inheritedRule.style);this._inheritedStyles.add(inheritedRule.style);}
parentNode=parentNode.parentNode;nodeCascades.push(new SDK.CSSMatchedStyles.NodeCascade(this,inheritedStyles,true));}
return new SDK.CSSMatchedStyles.DOMInheritanceCascade(nodeCascades);function containsStyle(styles,query){if(!query.styleSheetId||!query.range)
return false;for(const style of styles){if(query.styleSheetId===style.styleSheetId&&style.range&&query.range.equal(style.range))
return true;}
return false;}}
_buildPseudoCascades(pseudoPayload){const pseudoCascades=new Map();if(!pseudoPayload)
return pseudoCascades;for(let i=0;i<pseudoPayload.length;++i){const entryPayload=pseudoPayload[i];const pseudoElement=this._node.pseudoElements().get(entryPayload.pseudoType)||null;const pseudoStyles=[];const rules=entryPayload.matches||[];for(let j=rules.length-1;j>=0;--j){const pseudoRule=new SDK.CSSStyleRule(this._cssModel,rules[j].rule);pseudoStyles.push(pseudoRule.style);this._nodeForStyle.set(pseudoRule.style,pseudoElement);if(pseudoElement)
this._addMatchingSelectors(pseudoElement,pseudoRule,rules[j].matchingSelectors);}
const nodeCascade=new SDK.CSSMatchedStyles.NodeCascade(this,pseudoStyles,false);pseudoCascades.set(entryPayload.pseudoType,new SDK.CSSMatchedStyles.DOMInheritanceCascade([nodeCascade]));}
return pseudoCascades;}
_addMatchingSelectors(node,rule,matchingSelectorIndices){for(const matchingSelectorIndex of matchingSelectorIndices){const selector=rule.selectors[matchingSelectorIndex];this._setSelectorMatches(node,selector.text,true);}}
node(){return this._node;}
cssModel(){return this._cssModel;}
hasMatchingSelectors(rule){const matchingSelectors=this.matchingSelectors(rule);return matchingSelectors.length>0&&this.mediaMatches(rule.style);}
matchingSelectors(rule){const node=this.nodeForStyle(rule.style);if(!node)
return[];const map=this._matchingSelectors.get(node.id);if(!map)
return[];const result=[];for(let i=0;i<rule.selectors.length;++i){if(map.get(rule.selectors[i].text))
result.push(i);}
return result;}
recomputeMatchingSelectors(rule){const node=this.nodeForStyle(rule.style);if(!node)
return Promise.resolve();const promises=[];for(const selector of rule.selectors)
promises.push(querySelector.call(this,node,selector.text));return Promise.all(promises);async function querySelector(node,selectorText){const ownerDocument=node.ownerDocument||null;const map=this._matchingSelectors.get(node.id);if((map&&map.has(selectorText))||!ownerDocument)
return;const matchingNodeIds=await this._node.domModel().querySelectorAll(ownerDocument.id,selectorText);if(matchingNodeIds)
this._setSelectorMatches(node,selectorText,matchingNodeIds.indexOf(node.id)!==-1);}}
addNewRule(rule,node){this._addedStyles.set(rule.style,node);return this.recomputeMatchingSelectors(rule);}
_setSelectorMatches(node,selectorText,value){let map=this._matchingSelectors.get(node.id);if(!map){map=new Map();this._matchingSelectors.set(node.id,map);}
map.set(selectorText,value);}
mediaMatches(style){const media=style.parentRule?style.parentRule.media:[];for(let i=0;media&&i<media.length;++i){if(!media[i].active())
return false;}
return true;}
nodeStyles(){return this._mainDOMCascade.styles();}
keyframes(){return this._keyframes;}
pseudoStyles(pseudoType){const domCascade=this._pseudoDOMCascades.get(pseudoType);return domCascade?domCascade.styles():[];}
pseudoTypes(){return new Set(this._pseudoDOMCascades.keys());}
_containsInherited(style){const properties=style.allProperties();for(let i=0;i<properties.length;++i){const property=properties[i];if(property.activeInStyle()&&SDK.cssMetadata().isPropertyInherited(property.name))
return true;}
return false;}
nodeForStyle(style){return this._addedStyles.get(style)||this._nodeForStyle.get(style)||null;}
availableCSSVariables(style){const domCascade=this._styleToDOMCascade.get(style)||null;return domCascade?domCascade.availableCSSVariables(style):[];}
computeCSSVariable(style,variableName){const domCascade=this._styleToDOMCascade.get(style)||null;return domCascade?domCascade.computeCSSVariable(style,variableName):null;}
computeValue(style,value){const domCascade=this._styleToDOMCascade.get(style)||null;return domCascade?domCascade.computeValue(style,value):null;}
isInherited(style){return this._inheritedStyles.has(style);}
propertyState(property){const domCascade=this._styleToDOMCascade.get(property.ownerStyle);return domCascade?domCascade.propertyState(property):null;}
resetActiveProperties(){this._mainDOMCascade.reset();for(const domCascade of this._pseudoDOMCascades.values())
domCascade.reset();}};SDK.CSSMatchedStyles.NodeCascade=class{constructor(matchedStyles,styles,isInherited){this._matchedStyles=matchedStyles;this._styles=styles;this._isInherited=isInherited;this._propertiesState=new Map();this._activeProperties=new Map();}
_computeActiveProperties(){this._propertiesState.clear();this._activeProperties.clear();for(const style of this._styles){const rule=style.parentRule;if(rule&&!(rule instanceof SDK.CSSStyleRule))
continue;if(rule&&!this._matchedStyles.hasMatchingSelectors(rule))
continue;for(const property of style.allProperties()){if(this._isInherited&&!SDK.cssMetadata().isPropertyInherited(property.name))
continue;if(!property.activeInStyle()){this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;}
const canonicalName=SDK.cssMetadata().canonicalPropertyName(property.name);const activeProperty=this._activeProperties.get(canonicalName);if(activeProperty&&(activeProperty.important||!property.important)){this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;}
if(activeProperty)
this._propertiesState.set(activeProperty,SDK.CSSMatchedStyles.PropertyState.Overloaded);this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Active);this._activeProperties.set(canonicalName,property);}}}};SDK.CSSMatchedStyles.DOMInheritanceCascade=class{constructor(nodeCascades){this._nodeCascades=nodeCascades;this._propertiesState=new Map();this._availableCSSVariables=new Map();this._computedCSSVariables=new Map();this._initialized=false;this._styleToNodeCascade=new Map();for(const nodeCascade of nodeCascades){for(const style of nodeCascade._styles)
this._styleToNodeCascade.set(style,nodeCascade);}}
availableCSSVariables(style){const nodeCascade=this._styleToNodeCascade.get(style);if(!nodeCascade)
return[];this._ensureInitialized();return Array.from(this._availableCSSVariables.get(nodeCascade).keys());}
computeCSSVariable(style,variableName){const nodeCascade=this._styleToNodeCascade.get(style);if(!nodeCascade)
return null;this._ensureInitialized();const availableCSSVariables=this._availableCSSVariables.get(nodeCascade);const computedCSSVariables=this._computedCSSVariables.get(nodeCascade);return this._innerComputeCSSVariable(availableCSSVariables,computedCSSVariables,variableName);}
computeValue(style,value){const nodeCascade=this._styleToNodeCascade.get(style);if(!nodeCascade)
return null;this._ensureInitialized();const availableCSSVariables=this._availableCSSVariables.get(nodeCascade);const computedCSSVariables=this._computedCSSVariables.get(nodeCascade);return this._innerComputeValue(availableCSSVariables,computedCSSVariables,value);}
_innerComputeCSSVariable(availableCSSVariables,computedCSSVariables,variableName){if(!availableCSSVariables.has(variableName))
return null;if(computedCSSVariables.has(variableName))
return computedCSSVariables.get(variableName);computedCSSVariables.set(variableName,null);const definedValue=availableCSSVariables.get(variableName);const computedValue=this._innerComputeValue(availableCSSVariables,computedCSSVariables,definedValue);computedCSSVariables.set(variableName,computedValue);return computedValue;}
_innerComputeValue(availableCSSVariables,computedCSSVariables,value){const results=TextUtils.TextUtils.splitStringByRegexes(value,[SDK.CSSMetadata.VariableRegex]);const tokens=[];for(const result of results){if(result.regexIndex===-1){tokens.push(result.value);continue;}
const regexMatch=result.value.match(/^var\((--[a-zA-Z0-9-_]+)[,]?\s*(.*)\)$/);if(!regexMatch)
return null;const cssVariable=regexMatch[1];const computedValue=this._innerComputeCSSVariable(availableCSSVariables,computedCSSVariables,cssVariable);if(computedValue===null&&!regexMatch[2])
return null;if(computedValue===null)
tokens.push(regexMatch[2]);else
tokens.push(computedValue);}
return tokens.map(token=>token.trim()).join(' ');}
styles(){return Array.from(this._styleToNodeCascade.keys());}
propertyState(property){this._ensureInitialized();return this._propertiesState.get(property)||null;}
reset(){this._initialized=false;this._propertiesState.clear();this._availableCSSVariables.clear();this._computedCSSVariables.clear();}
_ensureInitialized(){if(this._initialized)
return;this._initialized=true;const activeProperties=new Map();for(const nodeCascade of this._nodeCascades){nodeCascade._computeActiveProperties();for(const entry of nodeCascade._propertiesState.entries()){const property=(entry[0]);const state=(entry[1]);if(state===SDK.CSSMatchedStyles.PropertyState.Overloaded){this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;}
const canonicalName=SDK.cssMetadata().canonicalPropertyName(property.name);if(activeProperties.has(canonicalName)){this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;}
activeProperties.set(canonicalName,property);this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Active);}}
for(const entry of activeProperties.entries()){const canonicalName=(entry[0]);const shorthandProperty=(entry[1]);const shorthandStyle=shorthandProperty.ownerStyle;const longhands=shorthandStyle.longhandProperties(shorthandProperty.name);if(!longhands.length)
continue;let hasActiveLonghands=false;for(const longhand of longhands){const longhandCanonicalName=SDK.cssMetadata().canonicalPropertyName(longhand.name);const longhandActiveProperty=activeProperties.get(longhandCanonicalName);if(!longhandActiveProperty)
continue;if(longhandActiveProperty.ownerStyle===shorthandStyle){hasActiveLonghands=true;break;}}
if(hasActiveLonghands)
continue;activeProperties.delete(canonicalName);this._propertiesState.set(shorthandProperty,SDK.CSSMatchedStyles.PropertyState.Overloaded);}
const accumulatedCSSVariables=new Map();for(let i=this._nodeCascades.length-1;i>=0;--i){const nodeCascade=this._nodeCascades[i];for(const entry of nodeCascade._activeProperties.entries()){const propertyName=(entry[0]);const property=(entry[1]);if(propertyName.startsWith('--'))
accumulatedCSSVariables.set(propertyName,property.value);}
this._availableCSSVariables.set(nodeCascade,new Map(accumulatedCSSVariables));this._computedCSSVariables.set(nodeCascade,new Map());}}};SDK.CSSMatchedStyles.PropertyState={Active:'Active',Overloaded:'Overloaded'};;SDK.CSSMediaQuery=class{constructor(payload){this._active=payload.active;this._expressions=[];for(let j=0;j<payload.expressions.length;++j)
this._expressions.push(SDK.CSSMediaQueryExpression.parsePayload(payload.expressions[j]));}
static parsePayload(payload){return new SDK.CSSMediaQuery(payload);}
active(){return this._active;}
expressions(){return this._expressions;}};SDK.CSSMediaQueryExpression=class{constructor(payload){this._value=payload.value;this._unit=payload.unit;this._feature=payload.feature;this._valueRange=payload.valueRange?TextUtils.TextRange.fromObject(payload.valueRange):null;this._computedLength=payload.computedLength||null;}
static parsePayload(payload){return new SDK.CSSMediaQueryExpression(payload);}
value(){return this._value;}
unit(){return this._unit;}
feature(){return this._feature;}
valueRange(){return this._valueRange;}
computedLength(){return this._computedLength;}};SDK.CSSMedia=class{constructor(cssModel,payload){this._cssModel=cssModel;this._reinitialize(payload);}
static parsePayload(cssModel,payload){return new SDK.CSSMedia(cssModel,payload);}
static parseMediaArrayPayload(cssModel,payload){const result=[];for(let i=0;i<payload.length;++i)
result.push(SDK.CSSMedia.parsePayload(cssModel,payload[i]));return result;}
_reinitialize(payload){this.text=payload.text;this.source=payload.source;this.sourceURL=payload.sourceURL||'';this.range=payload.range?TextUtils.TextRange.fromObject(payload.range):null;this.styleSheetId=payload.styleSheetId;this.mediaList=null;if(payload.mediaList){this.mediaList=[];for(let i=0;i<payload.mediaList.length;++i)
this.mediaList.push(SDK.CSSMediaQuery.parsePayload(payload.mediaList[i]));}}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId||!this.range)
return;if(edit.oldRange.equal(this.range))
this._reinitialize((edit.payload));else
this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);}
equal(other){if(!this.styleSheetId||!this.range||!other.range)
return false;return this.styleSheetId===other.styleSheetId&&this.range.equal(other.range);}
active(){if(!this.mediaList)
return true;for(let i=0;i<this.mediaList.length;++i){if(this.mediaList[i].active())
return true;}
return false;}
lineNumberInSource(){if(!this.range)
return undefined;const header=this.header();if(!header)
return undefined;return header.lineNumberInSource(this.range.startLine);}
columnNumberInSource(){if(!this.range)
return undefined;const header=this.header();if(!header)
return undefined;return header.columnNumberInSource(this.range.startLine,this.range.startColumn);}
header(){return this.styleSheetId?this._cssModel.styleSheetHeaderForId(this.styleSheetId):null;}
rawLocation(){const header=this.header();if(!header||this.lineNumberInSource()===undefined)
return null;const lineNumber=Number(this.lineNumberInSource());return new SDK.CSSLocation(header,lineNumber,this.columnNumberInSource());}};SDK.CSSMedia.Source={LINKED_SHEET:'linkedSheet',INLINE_SHEET:'inlineSheet',MEDIA_RULE:'mediaRule',IMPORT_RULE:'importRule'};;SDK.CSSMetadata=class{constructor(properties){this._values=([]);this._longhands=new Map();this._shorthands=new Map();this._inherited=new Set();this._svgProperties=new Set();for(let i=0;i<properties.length;++i){const property=properties[i];const propertyName=property.name;if(!CSS.supports(propertyName,'initial'))
continue;this._values.push(propertyName);if(property.inherited)
this._inherited.add(propertyName);if(property.svg)
this._svgProperties.add(propertyName);const longhands=properties[i].longhands;if(longhands){this._longhands.set(propertyName,longhands);for(let j=0;j<longhands.length;++j){const longhandName=longhands[j];let shorthands=this._shorthands.get(longhandName);if(!shorthands){shorthands=[];this._shorthands.set(longhandName,shorthands);}
shorthands.push(propertyName);}}}
this._values.sort(SDK.CSSMetadata._sortPrefixesToEnd);this._valuesSet=new Set(this._values);this._nameValuePresets=[];this._nameValuePresetsIncludingSVG=[];for(const name of this._valuesSet){const values=this._specificPropertyValues(name).filter(value=>CSS.supports(name,value)).sort(SDK.CSSMetadata._sortPrefixesToEnd);const presets=values.map(value=>`${name}: ${value}`);if(!this.isSVGProperty(name))
this._nameValuePresets.pushAll(presets);this._nameValuePresetsIncludingSVG.pushAll(presets);}}
static _sortPrefixesToEnd(a,b){const aIsPrefixed=a.startsWith('-webkit-');const bIsPrefixed=b.startsWith('-webkit-');if(aIsPrefixed&&!bIsPrefixed)
return 1;if(!aIsPrefixed&&bIsPrefixed)
return-1;return a<b?-1:(a>b?1:0);}
allProperties(){return this._values;}
nameValuePresets(includeSVG){return includeSVG?this._nameValuePresetsIncludingSVG:this._nameValuePresets;}
isSVGProperty(name){name=name.toLowerCase();return this._svgProperties.has(name);}
longhands(shorthand){return this._longhands.get(shorthand)||null;}
shorthands(longhand){return this._shorthands.get(longhand)||null;}
isColorAwareProperty(propertyName){return!!SDK.CSSMetadata._colorAwareProperties.has(propertyName.toLowerCase())||this.isCustomProperty(propertyName.toLowerCase());}
isLengthProperty(propertyName){propertyName=propertyName.toLowerCase();if(propertyName==='line-height')
return false;return SDK.CSSMetadata._distanceProperties.has(propertyName)||propertyName.startsWith('margin')||propertyName.startsWith('padding')||propertyName.indexOf('width')!==-1||propertyName.indexOf('height')!==-1;}
isBezierAwareProperty(propertyName){propertyName=propertyName.toLowerCase();return!!SDK.CSSMetadata._bezierAwareProperties.has(propertyName)||this.isCustomProperty(propertyName);}
isCustomProperty(propertyName){return propertyName.startsWith('--');}
canonicalPropertyName(name){name=name.toLowerCase();if(!name||name.length<9||name.charAt(0)!=='-')
return name;const match=name.match(/(?:-webkit-)(.+)/);if(!match||!this._valuesSet.has(match[1]))
return name;return match[1];}
isCSSPropertyName(propertyName){propertyName=propertyName.toLowerCase();if(propertyName.startsWith('-moz-')||propertyName.startsWith('-o-')||propertyName.startsWith('-webkit-')||propertyName.startsWith('-ms-'))
return true;return this._valuesSet.has(propertyName);}
isPropertyInherited(propertyName){propertyName=propertyName.toLowerCase();return propertyName.startsWith('--')||this._inherited.has(this.canonicalPropertyName(propertyName))||this._inherited.has(propertyName);}
_specificPropertyValues(propertyName){const unprefixedName=propertyName.replace(/^-webkit-/,'');const entry=SDK.CSSMetadata._propertyDataMap[propertyName]||SDK.CSSMetadata._propertyDataMap[unprefixedName];const keywords=entry&&entry.values?entry.values.slice():[];for(const commonKeyword of['auto','none']){if(CSS.supports(propertyName,commonKeyword))
keywords.push(commonKeyword);}
return keywords;}
propertyValues(propertyName){const acceptedKeywords=['inherit','initial','unset'];propertyName=propertyName.toLowerCase();acceptedKeywords.pushAll(this._specificPropertyValues(propertyName));if(this.isColorAwareProperty(propertyName)){acceptedKeywords.push('currentColor');for(const color in Common.Color.Nicknames)
acceptedKeywords.push(color);}
return acceptedKeywords.sort(SDK.CSSMetadata._sortPrefixesToEnd);}
propertyUsageWeight(property){return SDK.CSSMetadata.Weight[property]||SDK.CSSMetadata.Weight[this.canonicalPropertyName(property)]||0;}
getValuePreset(key,value){const values=SDK.CSSMetadata._valuePresets.get(key);let text=values?values.get(value):null;if(!text)
return null;let startColumn=text.length;let endColumn=text.length;if(text){startColumn=text.indexOf('|');endColumn=text.lastIndexOf('|');endColumn=startColumn===endColumn?endColumn:endColumn-1;text=text.replace(/\|/g,'');}
return{text,startColumn,endColumn};}};SDK.CSSMetadata.VariableRegex=/(var\(--.*?\))/g;SDK.CSSMetadata.URLRegex=/url\(\s*('.+?'|".+?"|[^)]+)\s*\)/g;SDK.cssMetadata=function(){if(!SDK.CSSMetadata._instance)
SDK.CSSMetadata._instance=new SDK.CSSMetadata(SDK.CSSMetadata._generatedProperties||[]);return SDK.CSSMetadata._instance;};SDK.CSSMetadata._imageValuePresetMap=new Map([['linear-gradient','linear-gradient(|45deg, black, transparent|)'],['radial-gradient','radial-gradient(|black, transparent|)'],['repeating-linear-gradient','repeating-linear-gradient(|45deg, black, transparent 100px|)'],['repeating-radial-gradient','repeating-radial-gradient(|black, transparent 100px|)'],['url','url(||)'],]);SDK.CSSMetadata._valuePresets=new Map([['filter',new Map([['blur','blur(|1px|)'],['brightness','brightness(|0.5|)'],['contrast','contrast(|0.5|)'],['drop-shadow','drop-shadow(|2px 4px 6px black|)'],['grayscale','grayscale(|1|)'],['hue-rotate','hue-rotate(|45deg|)'],['invert','invert(|1|)'],['opacity','opacity(|0.5|)'],['saturate','saturate(|0.5|)'],['sepia','sepia(|1|)'],['url','url(||)'],])],['background',SDK.CSSMetadata._imageValuePresetMap],['background-image',SDK.CSSMetadata._imageValuePresetMap],['-webkit-mask-image',SDK.CSSMetadata._imageValuePresetMap],['transform',new Map([['scale','scale(|1.5|)'],['scaleX','scaleX(|1.5|)'],['scaleY','scaleY(|1.5|)'],['scale3d','scale3d(|1.5, 1.5, 1.5|)'],['rotate','rotate(|45deg|)'],['rotateX','rotateX(|45deg|)'],['rotateY','rotateY(|45deg|)'],['rotateZ','rotateZ(|45deg|)'],['rotate3d','rotate3d(|1, 1, 1, 45deg|)'],['skew','skew(|10deg, 10deg|)'],['skewX','skewX(|10deg|)'],['skewY','skewY(|10deg|)'],['translate','translate(|10px, 10px|)'],['translateX','translateX(|10px|)'],['translateY','translateY(|10px|)'],['translateZ','translateZ(|10px|)'],['translate3d','translate3d(|10px, 10px, 10px|)'],['matrix','matrix(|1, 0, 0, 1, 0, 0|)'],['matrix3d','matrix3d(|1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1|)'],['perspective','perspective(|10px|)']])]]);SDK.CSSMetadata._distanceProperties=new Set(['background-position','border-spacing','bottom','font-size','height','left','letter-spacing','max-height','max-width','min-height','min-width','right','text-indent','top','width','word-spacing','grid-row-gap','grid-column-gap','row-gap']);SDK.CSSMetadata._bezierAwareProperties=new Set(['animation','animation-timing-function','transition','transition-timing-function','-webkit-animation','-webkit-animation-timing-function','-webkit-transition','-webkit-transition-timing-function']);SDK.CSSMetadata._colorAwareProperties=new Set(['backdrop-filter','background','background-color','background-image','border','border-color','border-image','border-image-source','border-bottom','border-bottom-color','border-left','border-left-color','border-right','border-right-color','border-top','border-top-color','box-shadow','caret-color','color','column-rule','column-rule-color','fill','list-style','list-style-image','outline','outline-color','stroke','text-decoration-color','text-shadow','-webkit-border-after','-webkit-border-after-color','-webkit-border-before','-webkit-border-before-color','-webkit-border-end','-webkit-border-end-color','-webkit-border-start','-webkit-border-start-color','-webkit-box-reflect','-webkit-box-shadow','-webkit-column-rule-color','-webkit-filter','-webkit-mask','-webkit-mask-box-image','-webkit-mask-box-image-source','-webkit-mask-image','-webkit-tap-highlight-color','-webkit-text-decoration-color','-webkit-text-emphasis','-webkit-text-emphasis-color','-webkit-text-fill-color','-webkit-text-stroke','-webkit-text-stroke-color']);SDK.CSSMetadata._propertyDataMap={'table-layout':{values:['fixed']},'visibility':{values:['hidden','visible','collapse']},'background-repeat':{values:['repeat','repeat-x','repeat-y','no-repeat','space','round']},'content':{values:['normal','close-quote','no-close-quote','no-open-quote','open-quote']},'clear':{values:['left','right','both']},'overflow-x':{values:['hidden','visible','overlay','scroll']},'stroke-linejoin':{values:['round','miter','bevel']},'baseline-shift':{values:['baseline','sub','super']},'border-bottom-width':{values:['medium','thick','thin']},'margin-top-collapse':{values:['collapse','separate','discard']},'max-height':{values:['min-content','max-conte
target.registerCSSDispatcher(new SDK.CSSDispatcher(this));if(!target.suspended())
this._enable();this._styleSheetIdToHeader=new Map();this._styleSheetIdsForURL=new Map();this._originalStyleSheetText=new Map();this._sourceMapManager.setEnabled(Common.moduleSetting('cssSourceMapsEnabled').get());Common.moduleSetting('cssSourceMapsEnabled').addChangeListener(event=>this._sourceMapManager.setEnabled((event.data)));}
sourceMapManager(){return this._sourceMapManager;}
static trimSourceURL(text){let sourceURLIndex=text.lastIndexOf('/*# sourceURL=');if(sourceURLIndex===-1){sourceURLIndex=text.lastIndexOf('/*@ sourceURL=');if(sourceURLIndex===-1)
return text;}
const sourceURLLineIndex=text.lastIndexOf('\n',sourceURLIndex);if(sourceURLLineIndex===-1)
return text;const sourceURLLine=text.substr(sourceURLLineIndex+1).split('\n',1)[0];const sourceURLRegex=/[\040\t]*\/\*[#@] sourceURL=[\040\t]*([^\s]*)[\040\t]*\*\/[\040\t]*$/;if(sourceURLLine.search(sourceURLRegex)===-1)
return text;return text.substr(0,sourceURLLineIndex)+text.substr(sourceURLLineIndex+sourceURLLine.length+1);}
domModel(){return this._domModel;}
async setStyleText(styleSheetId,range,text,majorChange){try{await this._ensureOriginalStyleSheetText(styleSheetId);const stylePayloads=await this._agent.setStyleTexts([{styleSheetId:styleSheetId,range:range.serializeToObject(),text:text}]);if(!stylePayloads||stylePayloads.length!==1)
return false;this._domModel.markUndoableState(!majorChange);const edit=new SDK.CSSModel.Edit(styleSheetId,range,text,stylePayloads[0]);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}}
async setSelectorText(styleSheetId,range,text){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this._ensureOriginalStyleSheetText(styleSheetId);const selectorPayload=await this._agent.setRuleSelector(styleSheetId,range,text);if(!selectorPayload)
return false;this._domModel.markUndoableState();const edit=new SDK.CSSModel.Edit(styleSheetId,range,text,selectorPayload);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}}
async setKeyframeKey(styleSheetId,range,text){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this._ensureOriginalStyleSheetText(styleSheetId);const payload=await this._agent.setKeyframeKey(styleSheetId,range,text);if(!payload)
return false;this._domModel.markUndoableState();const edit=new SDK.CSSModel.Edit(styleSheetId,range,text,payload);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}}
startCoverage(){this._agent.startRuleUsageTracking();}
takeCoverageDelta(){return this._agent.takeCoverageDelta().then(ruleUsage=>ruleUsage||[]);}
stopCoverage(){return this._agent.stopRuleUsageTracking();}
async mediaQueriesPromise(){const payload=await this._agent.getMediaQueries();return payload?SDK.CSSMedia.parseMediaArrayPayload(this,payload):[];}
isEnabled(){return this._isEnabled;}
async _enable(){await this._agent.enable();this._isEnabled=true;this.dispatchEventToListeners(SDK.CSSModel.Events.ModelWasEnabled);}
async matchedStylesPromise(nodeId){const response=await this._agent.invoke_getMatchedStylesForNode({nodeId});if(response[Protocol.Error])
return null;const node=this._domModel.nodeForId(nodeId);if(!node)
return null;return new SDK.CSSMatchedStyles(this,(node),response.inlineStyle||null,response.attributesStyle||null,response.matchedCSSRules||[],response.pseudoElements||[],response.inherited||[],response.cssKeyframesRules||[]);}
classNamesPromise(styleSheetId){return this._agent.collectClassNames(styleSheetId).then(classNames=>classNames||[]);}
computedStylePromise(nodeId){return this._styleLoader.computedStylePromise(nodeId);}
async backgroundColorsPromise(nodeId){const response=this._agent.invoke_getBackgroundColors({nodeId});if(response[Protocol.Error])
return null;return response;}
platformFontsPromise(nodeId){return this._agent.getPlatformFontsForNode(nodeId);}
allStyleSheets(){const values=this._styleSheetIdToHeader.valuesArray();function styleSheetComparator(a,b){if(a.sourceURL<b.sourceURL)
return-1;else if(a.sourceURL>b.sourceURL)
return 1;return a.startLine-b.startLine||a.startColumn-b.startColumn;}
values.sort(styleSheetComparator);return values;}
async inlineStylesPromise(nodeId){const response=await this._agent.invoke_getInlineStylesForNode({nodeId});if(response[Protocol.Error]||!response.inlineStyle)
return null;const inlineStyle=new SDK.CSSStyleDeclaration(this,null,response.inlineStyle,SDK.CSSStyleDeclaration.Type.Inline);const attributesStyle=response.attributesStyle?new SDK.CSSStyleDeclaration(this,null,response.attributesStyle,SDK.CSSStyleDeclaration.Type.Attributes):null;return new SDK.CSSModel.InlineStyleResult(inlineStyle,attributesStyle);}
forcePseudoState(node,pseudoClass,enable){const pseudoClasses=node.marker(SDK.CSSModel.PseudoStateMarker)||[];if(enable){if(pseudoClasses.indexOf(pseudoClass)>=0)
return false;pseudoClasses.push(pseudoClass);node.setMarker(SDK.CSSModel.PseudoStateMarker,pseudoClasses);}else{if(pseudoClasses.indexOf(pseudoClass)<0)
return false;pseudoClasses.remove(pseudoClass);if(pseudoClasses.length)
node.setMarker(SDK.CSSModel.PseudoStateMarker,pseudoClasses);else
node.setMarker(SDK.CSSModel.PseudoStateMarker,null);}
this._agent.forcePseudoState(node.id,pseudoClasses);this.dispatchEventToListeners(SDK.CSSModel.Events.PseudoStateForced,{node:node,pseudoClass:pseudoClass,enable:enable});return true;}
pseudoState(node){return node.marker(SDK.CSSModel.PseudoStateMarker)||[];}
async setMediaText(styleSheetId,range,newMediaText){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this._ensureOriginalStyleSheetText(styleSheetId);const mediaPayload=await this._agent.setMediaText(styleSheetId,range,newMediaText);if(!mediaPayload)
return false;this._domModel.markUndoableState();const edit=new SDK.CSSModel.Edit(styleSheetId,range,newMediaText,mediaPayload);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}}
async addRule(styleSheetId,ruleText,ruleLocation){try{await this._ensureOriginalStyleSheetText(styleSheetId);const rulePayload=await this._agent.addRule(styleSheetId,ruleText,ruleLocation);if(!rulePayload)
return null;this._domModel.markUndoableState();const edit=new SDK.CSSModel.Edit(styleSheetId,ruleLocation,ruleText,rulePayload);this._fireStyleSheetChanged(styleSheetId,edit);return new SDK.CSSStyleRule(this,rulePayload);}catch(e){return null;}}
async requestViaInspectorStylesheet(node){const frameId=node.frameId()||(this._resourceTreeModel?this._resourceTreeModel.mainFrame.id:'');const headers=this._styleSheetIdToHeader.valuesArray();const styleSheetHeader=headers.find(header=>header.frameId===frameId&&header.isViaInspector());if(styleSheetHeader)
return styleSheetHeader;try{const styleSheetId=await this._agent.createStyleSheet(frameId);return styleSheetId&&this._styleSheetIdToHeader.get(styleSheetId)||null;}catch(e){return null;}}
mediaQueryResultChanged(){this.dispatchEventToListeners(SDK.CSSModel.Events.MediaQueryResultChanged);}
fontsUpdated(){this.dispatchEventToListeners(SDK.CSSModel.Events.FontsUpdated);}
styleSheetHeaderForId(id){return this._styleSheetIdToHeader.get(id)||null;}
styleSheetHeaders(){return this._styleSheetIdToHeader.valuesArray();}
_fireStyleSheetChanged(styleSheetId,edit){this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetChanged,{styleSheetId:styleSheetId,edit:edit});}
_ensureOriginalStyleSheetText(styleSheetId){const header=this.styleSheetHeaderForId(styleSheetId);if(!header)
return Promise.resolve((null));let promise=this._originalStyleSheetText.get(header);if(!promise){promise=this.getStyleSheetText(header.id);this._originalStyleSheetText.set(header,promise);this._originalContentRequestedForTest(header);}
return promise;}
_originalContentRequestedForTest(header){}
originalStyleSheetText(header){return this._ensureOriginalStyleSheetText(header.id);}
_styleSheetAdded(header){console.assert(!this._styleSheetIdToHeader.get(header.styleSheetId));const styleSheetHeader=new SDK.CSSStyleSheetHeader(this,header);this._styleSheetIdToHeader.set(header.styleSheetId,styleSheetHeader);const url=styleSheetHeader.resourceURL();if(!this._styleSheetIdsForURL.get(url))
this._styleSheetIdsForURL.set(url,{});const frameIdToStyleSheetIds=this._styleSheetIdsForURL.get(url);let styleSheetIds=frameIdToStyleSheetIds[styleSheetHeader.frameId];if(!styleSheetIds){styleSheetIds=[];frameIdToStyleSheetIds[styleSheetHeader.frameId]=styleSheetIds;}
styleSheetIds.push(styleSheetHeader.id);this._sourceMapManager.attachSourceMap(styleSheetHeader,styleSheetHeader.sourceURL,styleSheetHeader.sourceMapURL);this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetAdded,styleSheetHeader);}
_styleSheetRemoved(id){const header=this._styleSheetIdToHeader.get(id);console.assert(header);if(!header)
return;this._styleSheetIdToHeader.remove(id);const url=header.resourceURL();const frameIdToStyleSheetIds=(this._styleSheetIdsForURL.get(url));console.assert(frameIdToStyleSheetIds,'No frameId to styleSheetId map is available for given style sheet URL.');frameIdToStyleSheetIds[header.frameId].remove(id);if(!frameIdToStyleSheetIds[header.frameId].length){delete frameIdToStyleSheetIds[header.frameId];if(!Object.keys(frameIdToStyleSheetIds).length)
this._styleSheetIdsForURL.remove(url);}
this._originalStyleSheetText.remove(header);this._sourceMapManager.detachSourceMap(header);this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetRemoved,header);}
styleSheetIdsForURL(url){const frameIdToStyleSheetIds=this._styleSheetIdsForURL.get(url);if(!frameIdToStyleSheetIds)
return[];let result=[];for(const frameId in frameIdToStyleSheetIds)
result=result.concat(frameIdToStyleSheetIds[frameId]);return result;}
async setStyleSheetText(styleSheetId,newText,majorChange){const header=(this._styleSheetIdToHeader.get(styleSheetId));console.assert(header);newText=SDK.CSSModel.trimSourceURL(newText);if(header.hasSourceURL)
newText+='\n/*# sourceURL='+header.sourceURL+' */';await this._ensureOriginalStyleSheetText(styleSheetId);const response=await this._agent.invoke_setStyleSheetText({styleSheetId:header.id,text:newText});const sourceMapURL=response.sourceMapURL;this._sourceMapManager.detachSourceMap(header);header.setSourceMapURL(sourceMapURL);this._sourceMapManager.attachSourceMap(header,header.sourceURL,header.sourceMapURL);if(sourceMapURL===null)
return'Error in CSS.setStyleSheetText';this._domModel.markUndoableState(!majorChange);this._fireStyleSheetChanged(styleSheetId);return null;}
async getStyleSheetText(styleSheetId){try{const text=await this._agent.getStyleSheetText(styleSheetId);return text&&SDK.CSSModel.trimSourceURL(text);}catch(e){return null;}}
_resetStyleSheets(){const headers=this._styleSheetIdToHeader.valuesArray();this._styleSheetIdsForURL.clear();this._styleSheetIdToHeader.clear();for(let i=0;i<headers.length;++i){this._sourceMapManager.detachSourceMap(headers[i]);this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetRemoved,headers[i]);}}
suspendModel(){this._isEnabled=false;return this._agent.disable().then(this._resetStyleSheets.bind(this));}
async resumeModel(){return this._enable();}
setEffectivePropertyValueForNode(nodeId,name,value){this._agent.setEffectivePropertyValueForNode(nodeId,name,value);}
cachedMatchedCascadeForNode(node){if(this._cachedMatchedCascadeNode!==node)
this.discardCachedMatchedCascade();this._cachedMatchedCascadeNode=node;if(!this._cachedMatchedCascadePromise)
this._cachedMatchedCascadePromise=this.matchedStylesPromise(node.id);return this._cachedMatchedCascadePromise;}
discardCachedMatchedCascade(){delete this._cachedMatchedCascadeNode;delete this._cachedMatchedCascadePromise;}
dispose(){super.dispose();this._sourceMapManager.dispose();}};SDK.SDKModel.register(SDK.CSSModel,SDK.Target.Capability.DOM,true);SDK.CSSModel.RuleUsage;SDK.CSSModel.ContrastInfo;SDK.CSSModel.Events={FontsUpdated:Symbol('FontsUpdated'),MediaQueryResultChanged:Symbol('MediaQueryResultChanged'),ModelWasEnabled:Symbol('ModelWasEnabled'),PseudoStateForced:Symbol('PseudoStateForced'),StyleSheetAdded:Symbol('StyleSheetAdded'),StyleSheetChanged:Symbol('StyleSheetChanged'),StyleSheetRemoved:Symbol('StyleSheetRemoved')};SDK.CSSModel.MediaTypes=['all','braille','embossed','handheld','print','projection','screen','speech','tty','tv'];SDK.CSSModel.PseudoStateMarker='pseudo-state-marker';SDK.CSSModel.Edit=class{constructor(styleSheetId,oldRange,newText,payload){this.styleSheetId=styleSheetId;this.oldRange=oldRange;this.newRange=TextUtils.TextRange.fromEdit(oldRange,newText);this.newText=newText;this.payload=payload;}};SDK.CSSLocation=class{constructor(header,lineNumber,columnNumber){this._cssModel=header.cssModel();this.styleSheetId=header.id;this.url=header.resourceURL();this.lineNumber=lineNumber;this.columnNumber=columnNumber||0;}
cssModel(){return this._cssModel;}
header(){return this._cssModel.styleSheetHeaderForId(this.styleSheetId);}};SDK.CSSDispatcher=class{constructor(cssModel){this._cssModel=cssModel;}
mediaQueryResultChanged(){this._cssModel.mediaQueryResultChanged();}
fontsUpdated(){this._cssModel.fontsUpdated();}
styleSheetChanged(styleSheetId){this._cssModel._fireStyleSheetChanged(styleSheetId);}
styleSheetAdded(header){this._cssModel._styleSheetAdded(header);}
styleSheetRemoved(id){this._cssModel._styleSheetRemoved(id);}};SDK.CSSModel.ComputedStyleLoader=class{constructor(cssModel){this._cssModel=cssModel;this._nodeIdToPromise=new Map();}
computedStylePromise(nodeId){let promise=this._nodeIdToPromise.get(nodeId);if(promise)
return promise;promise=this._cssModel._agent.getComputedStyleForNode(nodeId).then(parsePayload.bind(this));this._nodeIdToPromise.set(nodeId,promise);return promise;function parsePayload(computedPayload){this._nodeIdToPromise.delete(nodeId);if(!computedPayload||!computedPayload.length)
return null;const result=new Map();for(const property of computedPayload)
result.set(property.name,property.value);return result;}}};SDK.CSSModel.InlineStyleResult=class{constructor(inlineStyle,attributesStyle){this.inlineStyle=inlineStyle;this.attributesStyle=attributesStyle;}};;SDK.CSSProperty=class{constructor(ownerStyle,index,name,value,important,disabled,parsedOk,implicit,text,range){this.ownerStyle=ownerStyle;this.index=index;this.name=name;this.value=value;this.important=important;this.disabled=disabled;this.parsedOk=parsedOk;this.implicit=implicit;this.text=text;this.range=range?TextUtils.TextRange.fromObject(range):null;this._active=true;this._nameRange=null;this._valueRange=null;}
static parsePayload(ownerStyle,index,payload){const result=new SDK.CSSProperty(ownerStyle,index,payload.name,payload.value,payload.important||false,payload.disabled||false,('parsedOk'in payload)?!!payload.parsedOk:true,!!payload.implicit,payload.text,payload.range);return result;}
_ensureRanges(){if(this._nameRange&&this._valueRange)
return;const range=this.range;const text=this.text?new TextUtils.Text(this.text):null;if(!range||!text)
return;const nameIndex=text.value().indexOf(this.name);const valueIndex=text.value().lastIndexOf(this.value);if(nameIndex===-1||valueIndex===-1||nameIndex>valueIndex)
return;const nameSourceRange=new TextUtils.SourceRange(nameIndex,this.name.length);const valueSourceRange=new TextUtils.SourceRange(valueIndex,this.value.length);this._nameRange=rebase(text.toTextRange(nameSourceRange),range.startLine,range.startColumn);this._valueRange=rebase(text.toTextRange(valueSourceRange),range.startLine,range.startColumn);function rebase(oneLineRange,lineOffset,columnOffset){if(oneLineRange.startLine===0){oneLineRange.startColumn+=columnOffset;oneLineRange.endColumn+=columnOffset;}
oneLineRange.startLine+=lineOffset;oneLineRange.endLine+=lineOffset;return oneLineRange;}}
nameRange(){this._ensureRanges();return this._nameRange;}
valueRange(){this._ensureRanges();return this._valueRange;}
rebase(edit){if(this.ownerStyle.styleSheetId!==edit.styleSheetId)
return;if(this.range)
this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);}
setActive(active){this._active=active;}
get propertyText(){if(this.text!==undefined)
return this.text;if(this.name==='')
return'';return this.name+': '+this.value+(this.important?' !important':'')+';';}
activeInStyle(){return this._active;}
async setText(propertyText,majorChange,overwrite){if(!this.ownerStyle)
return Promise.reject(new Error('No ownerStyle for property'));if(!this.ownerStyle.styleSheetId)
return Promise.reject(new Error('No owner style id'));if(!this.range||!this.ownerStyle.range)
return Promise.reject(new Error('Style not editable'));if(majorChange)
Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);if(overwrite&&propertyText===this.propertyText){this.ownerStyle.cssModel().domModel().markUndoableState(!majorChange);return Promise.resolve(true);}
const range=this.range.relativeTo(this.ownerStyle.range.startLine,this.ownerStyle.range.startColumn);const indentation=this.ownerStyle.cssText?this._detectIndentation(this.ownerStyle.cssText):Common.moduleSetting('textEditorIndent').get();const endIndentation=this.ownerStyle.cssText?indentation.substring(0,this.ownerStyle.range.endColumn):'';const text=new TextUtils.Text(this.ownerStyle.cssText||'');const newStyleText=text.replaceRange(range,String.sprintf(';%s;',propertyText));const tokenizerFactory=await self.runtime.extension(TextUtils.TokenizerFactory).instance();const styleText=SDK.CSSProperty._formatStyle(newStyleText,indentation,endIndentation,tokenizerFactory);return this.ownerStyle.setText(styleText,majorChange);}
static _formatStyle(styleText,indentation,endIndentation,tokenizerFactory){if(indentation)
indentation='\n'+indentation;let result='';let propertyText;let insideProperty=false;let needsSemi=false;const tokenize=tokenizerFactory.createTokenizer('text/css');tokenize('*{'+styleText+'}',processToken);if(insideProperty)
result+=propertyText;result=result.substring(2,result.length-1).trimRight();return result+(indentation?'\n'+endIndentation:'');function processToken(token,tokenType,column,newColumn){if(!insideProperty){const disabledProperty=tokenType&&tokenType.includes('css-comment')&&isDisabledProperty(token);const isPropertyStart=tokenType&&(tokenType.includes('css-string')||tokenType.includes('css-meta')||tokenType.includes('css-property')||tokenType.includes('css-variable-2'));if(disabledProperty){result=result.trimRight()+indentation+token;}else if(isPropertyStart){insideProperty=true;propertyText=token;}else if(token!==';'||needsSemi){result+=token;if(token.trim()&&!(tokenType&&tokenType.includes('css-comment')))
needsSemi=token!==';';}
if(token==='{'&&!tokenType)
needsSemi=false;return;}
if(token==='}'||token===';'){result=result.trimRight()+indentation+propertyText.trim()+';';needsSemi=false;insideProperty=false;if(token==='}')
result+='}';}else{propertyText+=token;}}
function isDisabledProperty(text){const colon=text.indexOf(':');if(colon===-1)
return false;const propertyName=text.substring(2,colon).trim();return SDK.cssMetadata().isCSSPropertyName(propertyName);}}
_detectIndentation(text){const lines=text.split('\n');if(lines.length<2)
return'';return TextUtils.TextUtils.lineIndent(lines[1]);}
setValue(newValue,majorChange,overwrite,userCallback){const text=this.name+': '+newValue+(this.important?' !important':'')+';';this.setText(text,majorChange,overwrite).then(userCallback);}
setDisabled(disabled){if(!this.ownerStyle)
return Promise.resolve(false);if(disabled===this.disabled)
return Promise.resolve(true);const propertyText=this.text.trim();const text=disabled?'/* '+propertyText+' */':this.text.substring(2,propertyText.length-2).trim();return this.setText(text,true,true);}};;SDK.CSSValue=class{constructor(payload){this.text=payload.text;if(payload.range)
this.range=TextUtils.TextRange.fromObject(payload.range);}
rebase(edit){if(!this.range)
return;this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);}};SDK.CSSRule=class{constructor(cssModel,payload){this._cssModel=cssModel;this.styleSheetId=payload.styleSheetId;if(this.styleSheetId){const styleSheetHeader=cssModel.styleSheetHeaderForId(this.styleSheetId);this.sourceURL=styleSheetHeader.sourceURL;}
this.origin=payload.origin;this.style=new SDK.CSSStyleDeclaration(this._cssModel,this,payload.style,SDK.CSSStyleDeclaration.Type.Regular);}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId)
return;this.style.rebase(edit);}
resourceURL(){if(!this.styleSheetId)
return'';const styleSheetHeader=this._cssModel.styleSheetHeaderForId(this.styleSheetId);return styleSheetHeader.resourceURL();}
isUserAgent(){return this.origin===Protocol.CSS.StyleSheetOrigin.UserAgent;}
isInjected(){return this.origin===Protocol.CSS.StyleSheetOrigin.Injected;}
isViaInspector(){return this.origin===Protocol.CSS.StyleSheetOrigin.Inspector;}
isRegular(){return this.origin===Protocol.CSS.StyleSheetOrigin.Regular;}
cssModel(){return this._cssModel;}};SDK.CSSStyleRule=class extends SDK.CSSRule{constructor(cssModel,payload,wasUsed){super(cssModel,payload);this._reinitializeSelectors(payload.selectorList);this.media=payload.media?SDK.CSSMedia.parseMediaArrayPayload(cssModel,payload.media):[];this.wasUsed=wasUsed||false;}
static createDummyRule(cssModel,selectorText){const dummyPayload={selectorList:{selectors:[{text:selectorText}],},style:{styleSheetId:'0',range:new TextUtils.TextRange(0,0,0,0),shorthandEntries:[],cssProperties:[]}};return new SDK.CSSStyleRule(cssModel,(dummyPayload));}
_reinitializeSelectors(selectorList){this.selectors=[];for(let i=0;i<selectorList.selectors.length;++i)
this.selectors.push(new SDK.CSSValue(selectorList.selectors[i]));}
setSelectorText(newSelector){const styleSheetId=this.styleSheetId;if(!styleSheetId)
throw'No rule stylesheet id';const range=this.selectorRange();if(!range)
throw'Rule selector is not editable';return this._cssModel.setSelectorText(styleSheetId,range,newSelector);}
selectorText(){return this.selectors.select('text').join(', ');}
selectorRange(){const firstRange=this.selectors[0].range;if(!firstRange)
return null;const lastRange=this.selectors.peekLast().range;return new TextUtils.TextRange(firstRange.startLine,firstRange.startColumn,lastRange.endLine,lastRange.endColumn);}
lineNumberInSource(selectorIndex){const selector=this.selectors[selectorIndex];if(!selector||!selector.range||!this.styleSheetId)
return 0;const styleSheetHeader=this._cssModel.styleSheetHeaderForId(this.styleSheetId);return styleSheetHeader.lineNumberInSource(selector.range.startLine);}
columnNumberInSource(selectorIndex){const selector=this.selectors[selectorIndex];if(!selector||!selector.range||!this.styleSheetId)
return undefined;const styleSheetHeader=this._cssModel.styleSheetHeaderForId(this.styleSheetId);console.assert(styleSheetHeader);return styleSheetHeader.columnNumberInSource(selector.range.startLine,selector.range.startColumn);}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId)
return;if(this.selectorRange().equal(edit.oldRange)){this._reinitializeSelectors((edit.payload));}else{for(let i=0;i<this.selectors.length;++i)
this.selectors[i].rebase(edit);}
for(const media of this.media)
media.rebase(edit);super.rebase(edit);}};SDK.CSSKeyframesRule=class{constructor(cssModel,payload){this._cssModel=cssModel;this._animationName=new SDK.CSSValue(payload.animationName);this._keyframes=payload.keyframes.map(keyframeRule=>new SDK.CSSKeyframeRule(cssModel,keyframeRule));}
name(){return this._animationName;}
keyframes(){return this._keyframes;}};SDK.CSSKeyframeRule=class extends SDK.CSSRule{constructor(cssModel,payload){super(cssModel,payload);this._reinitializeKey(payload.keyText);}
key(){return this._keyText;}
_reinitializeKey(payload){this._keyText=new SDK.CSSValue(payload);}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId||!this._keyText.range)
return;if(edit.oldRange.equal(this._keyText.range))
this._reinitializeKey((edit.payload));else
this._keyText.rebase(edit);super.rebase(edit);}
setKeyText(newKeyText){const styleSheetId=this.styleSheetId;if(!styleSheetId)
throw'No rule stylesheet id';const range=this._keyText.range;if(!range)
throw'Keyframe key is not editable';return this._cssModel.setKeyframeKey(styleSheetId,range,newKeyText);}};;SDK.CSSStyleDeclaration=class{constructor(cssModel,parentRule,payload,type){this._cssModel=cssModel;this.parentRule=parentRule;this._allProperties;this.styleSheetId;this.range;this.cssText;this._shorthandValues;this._shorthandIsImportant;this._activePropertyMap;this._leadingProperties;this._reinitialize(payload);this.type=type;}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId||!this.range)
return;if(edit.oldRange.equal(this.range)){this._reinitialize((edit.payload));}else{this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);for(let i=0;i<this._allProperties.length;++i)
this._allProperties[i].rebase(edit);}}
_reinitialize(payload){this.styleSheetId=payload.styleSheetId;this.range=payload.range?TextUtils.TextRange.fromObject(payload.range):null;const shorthandEntries=payload.shorthandEntries;this._shorthandValues=new Map();this._shorthandIsImportant=new Set();for(let i=0;i<shorthandEntries.length;++i){this._shorthandValues.set(shorthandEntries[i].name,shorthandEntries[i].value);if(shorthandEntries[i].important)
this._shorthandIsImportant.add(shorthandEntries[i].name);}
this._allProperties=[];if(payload.cssText&&this.range){const cssText=new TextUtils.Text(payload.cssText);let start={line:this.range.startLine,column:this.range.startColumn};for(const cssProperty of payload.cssProperties){const range=cssProperty.range;if(range){parseUnusedText.call(this,cssText,start.line,start.column,range.startLine,range.startColumn);start={line:range.endLine,column:range.endColumn};}
this._allProperties.push(SDK.CSSProperty.parsePayload(this,this._allProperties.length,cssProperty));}
parseUnusedText.call(this,cssText,start.line,start.column,this.range.endLine,this.range.endColumn);}else{for(const cssProperty of payload.cssProperties)
this._allProperties.push(SDK.CSSProperty.parsePayload(this,this._allProperties.length,cssProperty));}
this._generateSyntheticPropertiesIfNeeded();this._computeInactiveProperties();this._activePropertyMap=new Map();for(const property of this._allProperties){if(!property.activeInStyle())
continue;this._activePropertyMap.set(property.name,property);}
this.cssText=payload.cssText;this._leadingProperties=null;function parseUnusedText(cssText,startLine,startColumn,endLine,endColumn){const tr=new TextUtils.TextRange(startLine,startColumn,endLine,endColumn);const missingText=cssText.extract(tr.relativeTo(this.range.startLine,this.range.startColumn));const lines=missingText.split('\n');let lineNumber=0;let inComment=false;for(const line of lines){let column=0;for(const property of line.split(';')){const strippedProperty=stripComments(property,inComment);const trimmedProperty=strippedProperty.text.trim();inComment=strippedProperty.inComment;if(trimmedProperty){let name;let value;const colonIndex=trimmedProperty.indexOf(':');if(colonIndex===-1){name=trimmedProperty;value='';}else{name=trimmedProperty.substring(0,colonIndex).trim();value=trimmedProperty.substring(colonIndex+1).trim();}
const range=new TextUtils.TextRange(lineNumber,column,lineNumber,column+property.length);this._allProperties.push(new SDK.CSSProperty(this,this._allProperties.length,name,value,false,false,false,false,property,range.relativeFrom(startLine,startColumn)));}
column+=property.length+1;}
lineNumber++;}}
function stripComments(text,inComment){let output='';for(let i=0;i<text.length;i++){if(!inComment&&text.substring(i,i+2)==='/*'){inComment=true;i++;}else if(inComment&&text.substring(i,i+2)==='*/'){inComment=false;i++;}else if(!inComment){output+=text[i];}}
return{text:output,inComment};}}
_generateSyntheticPropertiesIfNeeded(){if(this.range)
return;if(!this._shorthandValues.size)
return;const propertiesSet=new Set();for(const property of this._allProperties)
propertiesSet.add(property.name);const generatedProperties=[];for(const property of this._allProperties){const shorthands=SDK.cssMetadata().shorthands(property.name)||[];for(const shorthand of shorthands){if(propertiesSet.has(shorthand))
continue;const shorthandValue=this._shorthandValues.get(shorthand);if(!shorthandValue)
continue;const shorthandImportance=!!this._shorthandIsImportant.has(shorthand);const shorthandProperty=new SDK.CSSProperty(this,this.allProperties().length,shorthand,shorthandValue,shorthandImportance,false,true,false);generatedProperties.push(shorthandProperty);propertiesSet.add(shorthand);}}
this._allProperties=this._allProperties.concat(generatedProperties);}
_computeLeadingProperties(){function propertyHasRange(property){return!!property.range;}
if(this.range)
return this._allProperties.filter(propertyHasRange);const leadingProperties=[];for(const property of this._allProperties){const shorthands=SDK.cssMetadata().shorthands(property.name)||[];let belongToAnyShorthand=false;for(const shorthand of shorthands){if(this._shorthandValues.get(shorthand)){belongToAnyShorthand=true;break;}}
if(!belongToAnyShorthand)
leadingProperties.push(property);}
return leadingProperties;}
leadingProperties(){if(!this._leadingProperties)
this._leadingProperties=this._computeLeadingProperties();return this._leadingProperties;}
target(){return this._cssModel.target();}
cssModel(){return this._cssModel;}
_computeInactiveProperties(){const activeProperties={};for(let i=0;i<this._allProperties.length;++i){const property=this._allProperties[i];if(property.disabled||!property.parsedOk){property.setActive(false);continue;}
const canonicalName=SDK.cssMetadata().canonicalPropertyName(property.name);const activeProperty=activeProperties[canonicalName];if(!activeProperty){activeProperties[canonicalName]=property;}else if(!activeProperty.important||property.important){activeProperty.setActive(false);activeProperties[canonicalName]=property;}else{property.setActive(false);}}}
allProperties(){return this._allProperties;}
getPropertyValue(name){const property=this._activePropertyMap.get(name);return property?property.value:'';}
isPropertyImplicit(name){const property=this._activePropertyMap.get(name);return property?property.implicit:false;}
longhandProperties(name){const longhands=SDK.cssMetadata().longhands(name);const result=[];for(let i=0;longhands&&i<longhands.length;++i){const property=this._activePropertyMap.get(longhands[i]);if(property)
result.push(property);}
return result;}
propertyAt(index){return(index<this.allProperties().length)?this.allProperties()[index]:null;}
pastLastSourcePropertyIndex(){for(let i=this.allProperties().length-1;i>=0;--i){if(this.allProperties()[i].range)
return i+1;}
return 0;}
_insertionRange(index){const property=this.propertyAt(index);return property&&property.range?property.range.collapseToStart():this.range.collapseToEnd();}
newBlankProperty(index){index=(typeof index==='undefined')?this.pastLastSourcePropertyIndex():index;const property=new SDK.CSSProperty(this,index,'','',false,false,true,false,'',this._insertionRange(index));return property;}
setText(text,majorChange){if(!this.range||!this.styleSheetId)
return Promise.resolve(false);return this._cssModel.setStyleText(this.styleSheetId,this.range,text,majorChange);}
insertPropertyAt(index,name,value,userCallback){this.newBlankProperty(index).setText(name+': '+value+';',false,true).then(userCallback);}
appendProperty(name,value,userCallback){this.insertPropertyAt(this.allProperties().length,name,value,userCallback);}};SDK.CSSStyleDeclaration.Type={Regular:'Regular',Inline:'Inline',Attributes:'Attributes'};;SDK.CSSStyleSheetHeader=class{constructor(cssModel,payload){this._cssModel=cssModel;this.id=payload.styleSheetId;this.frameId=payload.frameId;this.sourceURL=payload.sourceURL;this.hasSourceURL=!!payload.hasSourceURL;this.origin=payload.origin;this.title=payload.title;this.disabled=payload.disabled;this.isInline=payload.isInline;this.startLine=payload.startLine;this.startColumn=payload.startColumn;this.contentLength=payload.length;if(payload.ownerNode)
this.ownerNode=new SDK.DeferredDOMNode(cssModel.target(),payload.ownerNode);this.setSourceMapURL(payload.sourceMapURL);}
originalContentProvider(){if(!this._originalContentProvider){const lazyContent=this._cssModel.originalStyleSheetText.bind(this._cssModel,this);this._originalContentProvider=new Common.StaticContentProvider(this.contentURL(),this.contentType(),(lazyContent));}
return this._originalContentProvider;}
setSourceMapURL(sourceMapURL){this.sourceMapURL=sourceMapURL;}
cssModel(){return this._cssModel;}
isAnonymousInlineStyleSheet(){return!this.resourceURL()&&!this._cssModel.sourceMapManager().sourceMapForClient(this);}
resourceURL(){return this.isViaInspector()?this._viaInspectorResourceURL():this.sourceURL;}
_viaInspectorResourceURL(){const frame=this._cssModel.target().model(SDK.ResourceTreeModel).frameForId(this.frameId);console.assert(frame);const parsedURL=new Common.ParsedURL(frame.url);let fakeURL='inspector://'+parsedURL.host+parsedURL.folderPathComponents;if(!fakeURL.endsWith('/'))
fakeURL+='/';fakeURL+='inspector-stylesheet';return fakeURL;}
lineNumberInSource(lineNumberInStyleSheet){return this.startLine+lineNumberInStyleSheet;}
columnNumberInSource(lineNumberInStyleSheet,columnNumberInStyleSheet){return(lineNumberInStyleSheet?0:this.startColumn)+columnNumberInStyleSheet;}
contentURL(){return this.resourceURL();}
contentType(){return Common.resourceTypes.Stylesheet;}
contentEncoded(){return Promise.resolve(false);}
requestContent(){return this._cssModel.getStyleSheetText(this.id);}
async searchInContent(query,caseSensitive,isRegex){const content=await this.requestContent();return Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex);}
isViaInspector(){return this.origin==='inspector';}};;SDK.ChildTargetManager=class extends SDK.SDKModel{constructor(parentTarget){super(parentTarget);this._targetManager=parentTarget.targetManager();this._parentTarget=parentTarget;this._targetAgent=parentTarget.targetAgent();this._targetInfos=new Map();this._childTargets=new Map();parentTarget.registerTargetDispatcher(this);this._targetAgent.invoke_setAutoAttach({autoAttach:true,waitForDebuggerOnStart:true,flatten:true});if(!parentTarget.parentTarget()&&!Host.isUnderTest()){this._targetAgent.setDiscoverTargets(true);this._targetAgent.setRemoteLocations([{host:'localhost',port:9229}]);}}
static install(attachCallback){SDK.ChildTargetManager._attachCallback=attachCallback;SDK.SDKModel.register(SDK.ChildTargetManager,SDK.Target.Capability.Target,true);}
suspendModel(){return this._targetAgent.invoke_setAutoAttach({autoAttach:true,waitForDebuggerOnStart:false,flatten:true});}
resumeModel(){return this._targetAgent.invoke_setAutoAttach({autoAttach:true,waitForDebuggerOnStart:true,flatten:true});}
dispose(){for(const sessionId of this._childTargets.keys())
this.detachedFromTarget(sessionId,undefined);}
targetCreated(targetInfo){this._targetInfos.set(targetInfo.targetId,targetInfo);this._fireAvailableTargetsChanged();}
targetInfoChanged(targetInfo){this._targetInfos.set(targetInfo.targetId,targetInfo);this._fireAvailableTargetsChanged();}
targetDestroyed(targetId){this._targetInfos.delete(targetId);this._fireAvailableTargetsChanged();}
targetCrashed(targetId,status,errorCode){}
_fireAvailableTargetsChanged(){SDK.targetManager.dispatchEventToListeners(SDK.TargetManager.Events.AvailableTargetsChanged,this._targetInfos.valuesArray());}
attachedToTarget(sessionId,targetInfo,waitingForDebugger){let targetName='';if(targetInfo.type==='worker'&&targetInfo.title&&targetInfo.title!==targetInfo.url){targetName=targetInfo.title;}else if(targetInfo.type!=='iframe'){const parsedURL=targetInfo.url.asParsedURL();targetName=parsedURL?parsedURL.lastPathComponentWithFragment():'#'+(++SDK.ChildTargetManager._lastAnonymousTargetId);}
let type=SDK.Target.Type.Browser;if(targetInfo.type==='iframe')
type=SDK.Target.Type.Frame;else if(targetInfo.type==='page')
type=SDK.Target.Type.Frame;else if(targetInfo.type==='worker')
type=SDK.Target.Type.Worker;else if(targetInfo.type==='service_worker')
type=SDK.Target.Type.ServiceWorker;const target=this._targetManager.createTarget(targetInfo.targetId,targetName,type,this._parentTarget,sessionId);this._childTargets.set(sessionId,target);if(SDK.ChildTargetManager._attachCallback){SDK.ChildTargetManager._attachCallback({target,waitingForDebugger}).then(()=>{target.runtimeAgent().runIfWaitingForDebugger();});}else{target.runtimeAgent().runIfWaitingForDebugger();}}
detachedFromTarget(sessionId,childTargetId){this._childTargets.get(sessionId).dispose('target terminated');this._childTargets.delete(sessionId);}
receivedMessageFromTarget(sessionId,message,childTargetId){}};SDK.ChildTargetManager._lastAnonymousTargetId=0;SDK.ChildTargetManager._attachCallback;;SDK.DOMDebuggerModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.domdebuggerAgent();this._runtimeModel=(target.model(SDK.RuntimeModel));this._domModel=(target.model(SDK.DOMModel));this._domModel.addEventListener(SDK.DOMModel.Events.DocumentUpdated,this._documentUpdated,this);this._domModel.addEventListener(SDK.DOMModel.Events.NodeRemoved,this._nodeRemoved,this);this._domBreakpoints=[];this._domBreakpointsSetting=Common.settings.createLocalSetting('domBreakpoints',[]);if(this._domModel.existingDocument())
this._documentUpdated();}
runtimeModel(){return this._runtimeModel;}
async eventListeners(remoteObject){console.assert(remoteObject.runtimeModel()===this._runtimeModel);if(!remoteObject.objectId)
return[];const payloads=await this._agent.getEventListeners((remoteObject.objectId));const eventListeners=[];for(const payload of payloads||[]){const location=this._runtimeModel.debuggerModel().createRawLocationByScriptId(payload.scriptId,payload.lineNumber,payload.columnNumber);if(!location)
continue;eventListeners.push(new SDK.EventListener(this,remoteObject,payload.type,payload.useCapture,payload.passive,payload.once,payload.handler?this._runtimeModel.createRemoteObject(payload.handler):null,payload.originalHandler?this._runtimeModel.createRemoteObject(payload.originalHandler):null,location,null));}
return eventListeners;}
retrieveDOMBreakpoints(){this._domModel.requestDocument();}
domBreakpoints(){return this._domBreakpoints.slice();}
hasDOMBreakpoint(node,type){return this._domBreakpoints.some(breakpoint=>(breakpoint.node===node&&breakpoint.type===type));}
setDOMBreakpoint(node,type){for(const breakpoint of this._domBreakpoints){if(breakpoint.node===node&&breakpoint.type===type){this.toggleDOMBreakpoint(breakpoint,true);return breakpoint;}}
const breakpoint=new SDK.DOMDebuggerModel.DOMBreakpoint(this,node,type,true);this._domBreakpoints.push(breakpoint);this._saveDOMBreakpoints();this._enableDOMBreakpoint(breakpoint);this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointAdded,breakpoint);return breakpoint;}
removeDOMBreakpoint(node,type){this._removeDOMBreakpoints(breakpoint=>breakpoint.node===node&&breakpoint.type===type);}
removeAllDOMBreakpoints(){this._removeDOMBreakpoints(breakpoint=>true);}
toggleDOMBreakpoint(breakpoint,enabled){if(enabled===breakpoint.enabled)
return;breakpoint.enabled=enabled;if(enabled)
this._enableDOMBreakpoint(breakpoint);else
this._disableDOMBreakpoint(breakpoint);this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointToggled,breakpoint);}
_enableDOMBreakpoint(breakpoint){this._agent.setDOMBreakpoint(breakpoint.node.id,breakpoint.type);breakpoint.node.setMarker(SDK.DOMDebuggerModel.DOMBreakpoint.Marker,true);}
_disableDOMBreakpoint(breakpoint){this._agent.removeDOMBreakpoint(breakpoint.node.id,breakpoint.type);breakpoint.node.setMarker(SDK.DOMDebuggerModel.DOMBreakpoint.Marker,this._nodeHasBreakpoints(breakpoint.node)?true:null);}
_nodeHasBreakpoints(node){for(const breakpoint of this._domBreakpoints){if(breakpoint.node===node&&breakpoint.enabled)
return true;}
return false;}
resolveDOMBreakpointData(auxData){const type=auxData['type'];const node=this._domModel.nodeForId(auxData['nodeId']);if(!type||!node)
return null;let targetNode=null;let insertion=false;if(type===SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified){insertion=auxData['insertion']||false;targetNode=this._domModel.nodeForId(auxData['targetNodeId']);}
return{type:type,node:node,targetNode:targetNode,insertion:insertion};}
_currentURL(){const domDocument=this._domModel.existingDocument();return domDocument?domDocument.documentURL:'';}
_documentUpdated(){const removed=this._domBreakpoints;this._domBreakpoints=[];this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointsRemoved,removed);const currentURL=this._currentURL();for(const breakpoint of this._domBreakpointsSetting.get()){if(breakpoint.url===currentURL)
this._domModel.pushNodeByPathToFrontend(breakpoint.path).then(appendBreakpoint.bind(this,breakpoint));}
function appendBreakpoint(breakpoint,nodeId){const node=nodeId?this._domModel.nodeForId(nodeId):null;if(!node)
return;const domBreakpoint=new SDK.DOMDebuggerModel.DOMBreakpoint(this,node,breakpoint.type,breakpoint.enabled);this._domBreakpoints.push(domBreakpoint);if(breakpoint.enabled)
this._enableDOMBreakpoint(domBreakpoint);this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointAdded,domBreakpoint);}}
_removeDOMBreakpoints(filter){const removed=[];const left=[];for(const breakpoint of this._domBreakpoints){if(filter(breakpoint)){removed.push(breakpoint);if(breakpoint.enabled){breakpoint.enabled=false;this._disableDOMBreakpoint(breakpoint);}}else{left.push(breakpoint);}}
if(!removed.length)
return;this._domBreakpoints=left;this._saveDOMBreakpoints();this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointsRemoved,removed);}
_nodeRemoved(event){const node=(event.data.node);const children=node.children()||[];this._removeDOMBreakpoints(breakpoint=>breakpoint.node===node||children.indexOf(breakpoint.node)!==-1);}
_saveDOMBreakpoints(){const currentURL=this._currentURL();const breakpoints=this._domBreakpointsSetting.get().filter(breakpoint=>breakpoint.url!==currentURL);for(const breakpoint of this._domBreakpoints){breakpoints.push({url:currentURL,path:breakpoint.node.path(),type:breakpoint.type,enabled:breakpoint.enabled});}
this._domBreakpointsSetting.set(breakpoints);}};SDK.SDKModel.register(SDK.DOMDebuggerModel,SDK.Target.Capability.DOM,false);SDK.DOMDebuggerModel.Events={DOMBreakpointAdded:Symbol('DOMBreakpointAdded'),DOMBreakpointToggled:Symbol('DOMBreakpointToggled'),DOMBreakpointsRemoved:Symbol('DOMBreakpointsRemoved'),};SDK.DOMDebuggerModel.DOMBreakpoint=class{constructor(domDebuggerModel,node,type,enabled){this.domDebuggerModel=domDebuggerModel;this.node=node;this.type=type;this.enabled=enabled;}};SDK.DOMDebuggerModel.DOMBreakpoint.Type=Protocol.DOMDebugger.DOMBreakpointType;SDK.DOMDebuggerModel.DOMBreakpoint.Marker='breakpoint-marker';SDK.EventListener=class{constructor(domDebuggerModel,eventTarget,type,useCapture,passive,once,handler,originalHandler,location,customRemoveFunction,origin){this._domDebuggerModel=domDebuggerModel;this._eventTarget=eventTarget;this._type=type;this._useCapture=useCapture;this._passive=passive;this._once=once;this._handler=handler;this._originalHandler=originalHandler||handler;this._location=location;const script=location.script();this._sourceURL=script?script.contentURL():'';this._customRemoveFunction=customRemoveFunction;this._origin=origin||SDK.EventListener.Origin.Raw;}
domDebuggerModel(){return this._domDebuggerModel;}
type(){return this._type;}
useCapture(){return this._useCapture;}
passive(){return this._passive;}
once(){return this._once;}
handler(){return this._handler;}
location(){return this._location;}
sourceURL(){return this._sourceURL;}
originalHandler(){return this._originalHandler;}
canRemove(){return!!this._customRemoveFunction||this._origin!==SDK.EventListener.Origin.FrameworkUser;}
remove(){if(!this.canRemove())
return Promise.resolve();if(this._origin!==SDK.EventListener.Origin.FrameworkUser){function removeListener(type,listener,useCapture){this.removeEventListener(type,listener,useCapture);if(this['on'+type])
this['on'+type]=undefined;}
return(this._eventTarget.callFunction(removeListener,[SDK.RemoteObject.toCallArgument(this._type),SDK.RemoteObject.toCallArgument(this._originalHandler),SDK.RemoteObject.toCallArgument(this._useCapture)]));}
return this._customRemoveFunction.callFunction(callCustomRemove,[SDK.RemoteObject.toCallArgument(this._type),SDK.RemoteObject.toCallArgument(this._originalHandler),SDK.RemoteObject.toCallArgument(this._useCapture),SDK.RemoteObject.toCallArgument(this._passive),]).then(()=>undefined);function callCustomRemove(type,listener,useCapture,passive){this.call(null,type,listener,useCapture,passive);}}
canTogglePassive(){return this._origin!==SDK.EventListener.Origin.FrameworkUser;}
togglePassive(){return(this._eventTarget.callFunction(callTogglePassive,[SDK.RemoteObject.toCallArgument(this._type),SDK.RemoteObject.toCallArgument(this._originalHandler),SDK.RemoteObject.toCallArgument(this._useCapture),SDK.RemoteObject.toCallArgument(this._passive),]));function callTogglePassive(type,listener,useCapture,passive){this.removeEventListener(type,listener,{capture:useCapture});this.addEventListener(type,listener,{capture:useCapture,passive:!passive});}}
origin(){return this._origin;}
markAsFramework(){this._origin=SDK.EventListener.Origin.Framework;}
isScrollBlockingType(){return this._type==='touchstart'||this._type==='touchmove'||this._type==='mousewheel'||this._type==='wheel';}};SDK.EventListener.Origin={Raw:'Raw',Framework:'Framework',FrameworkUser:'FrameworkUser'};SDK.DOMDebuggerModel.EventListenerBreakpoint=class{constructor(instrumentationName,eventName,eventTargetNames,category,title){this._instrumentationName=instrumentationName;this._eventName=eventName;this._eventTargetNames=eventTargetNames;this._category=category;this._title=title;this._enabled=false;}
category(){return this._category;}
enabled(){return this._enabled;}
setEnabled(enabled){if(this._enabled===enabled)
return;this._enabled=enabled;for(const model of SDK.targetManager.models(SDK.DOMDebuggerModel))
this._updateOnModel(model);}
_updateOnModel(model){if(this._instrumentationName){if(this._enabled)
model._agent.setInstrumentationBreakpoint(this._instrumentationName);else
model._agent.removeInstrumentationBreakpoint(this._instrumentationName);}else{for(const eventTargetName of this._eventTargetNames){if(this._enabled)
model._agent.setEventListenerBreakpoint(this._eventName,eventTargetName);else
model._agent.removeEventListenerBreakpoint(this._eventName,eventTargetName);}}}
title(){return this._title;}};SDK.DOMDebuggerModel.EventListenerBreakpoint._listener='listener:';SDK.DOMDebuggerModel.EventListenerBreakpoint._instrumentation='instrumentation:';SDK.DOMDebuggerManager=class{constructor(){this._xhrBreakpointsSetting=Common.settings.createLocalSetting('xhrBreakpoints',[]);this._xhrBreakpoints=new Map();for(const breakpoint of this._xhrBreakpointsSetting.get())
this._xhrBreakpoints.set(breakpoint.url,breakpoint.enabled);this._eventListenerBreakpoints=[];this._createInstrumentationBreakpoints(Common.UIString('Animation'),['requestAnimationFrame','cancelAnimationFrame','requestAnimationFrame.callback']);this._createInstrumentationBreakpoints(Common.UIString('Canvas'),['canvasContextCreated','webglErrorFired','webglWarningFired']);this._createInstrumentationBreakpoints(Common.UIString('Geolocation'),['Geolocation.getCurrentPosition','Geolocation.watchPosition']);this._createInstrumentationBreakpoints(Common.UIString('Notification'),['Notification.requestPermission']);this._createInstrumentationBreakpoints(Common.UIString('Parse'),['Element.setInnerHTML','Document.write']);this._createInstrumentationBreakpoints(Common.UIString('Script'),['scriptFirstStatement','scriptBlockedByCSP']);this._createInstrumentationBreakpoints(Common.UIString('Timer'),['setTimeout','clearTimeout','setInterval','clearInterval','setTimeout.callback','setInterval.callback']);this._createInstrumentationBreakpoints(Common.UIString('Window'),['DOMWindow.close']);this._createInstrumentationBreakpoints(Common.UIString('WebAudio'),['audioContextCreated','audioContextClosed','audioContextResumed','audioContextSuspended']);this._createEventListenerBreakpoints(Common.UIString('Media'),['play','pause','playing','canplay','canplaythrough','seeking','seeked','timeupdate','ended','ratechange','durationchange','volumechange','loadstart','progress','suspend','abort','error','emptied','stalled','loadedmetadata','loadeddata','waiting'],['audio','video']);this._createEventListenerBreakpoints(Common.UIString('Picture-in-Picture'),['enterpictureinpicture','leavepictureinpicture'],['video']);this._createEventListenerBreakpoints(Common.UIString('Picture-in-Picture'),['resize'],['PictureInPictureWindow']);this._createEventListenerBreakpoints(Common.UIString('Clipboard'),['copy','cut','paste','beforecopy','beforecut','beforepaste'],['*']);this._createEventListenerBreakpoints(Common.UIString('Control'),['resize','scroll','zoom','focus','blur','select','change','submit','reset'],['*']);this._createEventListenerBreakpoints(Common.UIString('Device'),['deviceorientation','devicemotion'],['*']);this._createEventListenerBreakpoints(Common.UIString('DOM Mutation'),['DOMActivate','DOMFocusIn','DOMFocusOut','DOMAttrModified','DOMCharacterDataModified','DOMNodeInserted','DOMNodeInsertedIntoDocument','DOMNodeRemoved','DOMNodeRemovedFromDocument','DOMSubtreeModified','DOMContentLoaded'],['*']);this._createEventListenerBreakpoints(Common.UIString('Drag / drop'),['drag','dragstart','dragend','dragenter','dragover','dragleave','drop'],['*']);this._createEventListenerBreakpoints(Common.UIString('Keyboard'),['keydown','keyup','keypress','input'],['*']);this._createEventListenerBreakpoints(Common.UIString('Load'),['load','beforeunload','unload','abort','error','hashchange','popstate'],['*']);this._createEventListenerBreakpoints(Common.UIString('Mouse'),['auxclick','click','dblclick','mousedown','mouseup','mouseover','mousemove','mouseout','mouseenter','mouseleave','mousewheel','wheel','contextmenu'],['*']);this._createEventListenerBreakpoints(Common.UIString('Pointer'),['pointerover','pointerout','pointerenter','pointerleave','pointerdown','pointerup','pointermove','pointercancel','gotpointercapture','lostpointercapture'],['*']);this._createEventListenerBreakpoints(Common.UIString('Touch'),['touchstart','touchmove','touchend','touchcancel'],['*']);this._createEventListenerBreakpoints(Common.UIString('Worker'),['message','messageerror'],['*']);this._createEventListenerBreakpoints(Common.UIString('XHR'),['readystatechange','load','loadstart','loadend','abort','error','progress','timeout'],['xmlhttprequest','xmlhttprequestupload']);this._resolveEventListenerBreakpoint('instrumentation:setTimeout.callback')._title=Common.UIString('setTimeout fired');this._resolveEventListenerBreakpoint('instrumentation:setInterval.callback')._title=Common.UIString('setInterval fired');this._resolveEventListenerBreakpoint('instrumentation:scriptFirstStatement')._title=C
_createInstrumentationBreakpoints(category,instrumentationNames){for(const instrumentationName of instrumentationNames){this._eventListenerBreakpoints.push(new SDK.DOMDebuggerModel.EventListenerBreakpoint(instrumentationName,'',[],category,instrumentationName));}}
_createEventListenerBreakpoints(category,eventNames,eventTargetNames){for(const eventName of eventNames){this._eventListenerBreakpoints.push(new SDK.DOMDebuggerModel.EventListenerBreakpoint('',eventName,eventTargetNames,category,eventName));}}
_resolveEventListenerBreakpoint(eventName,eventTargetName){const instrumentationPrefix='instrumentation:';const listenerPrefix='listener:';let instrumentationName='';if(eventName.startsWith(instrumentationPrefix)){instrumentationName=eventName.substring(instrumentationPrefix.length);eventName='';}else if(eventName.startsWith(listenerPrefix)){eventName=eventName.substring(listenerPrefix.length);}else{return null;}
eventTargetName=(eventTargetName||'*').toLowerCase();let result=null;for(const breakpoint of this._eventListenerBreakpoints){if(instrumentationName&&breakpoint._instrumentationName===instrumentationName)
result=breakpoint;if(eventName&&breakpoint._eventName===eventName&&breakpoint._eventTargetNames.indexOf(eventTargetName)!==-1)
result=breakpoint;if(!result&&eventName&&breakpoint._eventName===eventName&&breakpoint._eventTargetNames.indexOf('*')!==-1)
result=breakpoint;}
return result;}
eventListenerBreakpoints(){return this._eventListenerBreakpoints.slice();}
resolveEventListenerBreakpointTitle(auxData){const id=auxData['eventName'];if(id==='instrumentation:webglErrorFired'&&auxData['webglErrorName']){let errorName=auxData['webglErrorName'];errorName=errorName.replace(/^.*(0x[0-9a-f]+).*$/i,'$1');return Common.UIString('WebGL Error Fired (%s)',errorName);}
if(id==='instrumentation:scriptBlockedByCSP'&&auxData['directiveText'])
return Common.UIString('Script blocked due to Content Security Policy directive: %s',auxData['directiveText']);const breakpoint=this._resolveEventListenerBreakpoint(id,auxData['targetName']);if(!breakpoint)
return'';if(auxData['targetName'])
return auxData['targetName']+'.'+breakpoint._title;return breakpoint._title;}
resolveEventListenerBreakpoint(auxData){return this._resolveEventListenerBreakpoint(auxData['eventName'],auxData['targetName']);}
xhrBreakpoints(){return this._xhrBreakpoints;}
_saveXHRBreakpoints(){const breakpoints=[];for(const url of this._xhrBreakpoints.keys())
breakpoints.push({url:url,enabled:this._xhrBreakpoints.get(url)});this._xhrBreakpointsSetting.set(breakpoints);}
addXHRBreakpoint(url,enabled){this._xhrBreakpoints.set(url,enabled);if(enabled){for(const model of SDK.targetManager.models(SDK.DOMDebuggerModel))
model._agent.setXHRBreakpoint(url);}
this._saveXHRBreakpoints();}
removeXHRBreakpoint(url){const enabled=this._xhrBreakpoints.get(url);this._xhrBreakpoints.delete(url);if(enabled){for(const model of SDK.targetManager.models(SDK.DOMDebuggerModel))
model._agent.removeXHRBreakpoint(url);}
this._saveXHRBreakpoints();}
toggleXHRBreakpoint(url,enabled){this._xhrBreakpoints.set(url,enabled);for(const model of SDK.targetManager.models(SDK.DOMDebuggerModel)){if(enabled)
model._agent.setXHRBreakpoint(url);else
model._agent.removeXHRBreakpoint(url);}
this._saveXHRBreakpoints();}
modelAdded(domDebuggerModel){for(const url of this._xhrBreakpoints.keys()){if(this._xhrBreakpoints.get(url))
domDebuggerModel._agent.setXHRBreakpoint(url);}
for(const breakpoint of this._eventListenerBreakpoints){if(breakpoint._enabled)
breakpoint._updateOnModel(domDebuggerModel);}}
modelRemoved(domDebuggerModel){}};SDK.domDebuggerManager;;SDK.DOMNode=class{constructor(domModel){this._domModel=domModel;}
static create(domModel,doc,isInShadowTree,payload){const node=new SDK.DOMNode(domModel);node._init(doc,isInShadowTree,payload);return node;}
_init(doc,isInShadowTree,payload){this._agent=this._domModel._agent;this.ownerDocument=doc;this._isInShadowTree=isInShadowTree;this.id=payload.nodeId;this._backendNodeId=payload.backendNodeId;this._domModel._idToDOMNode[this.id]=this;this._nodeType=payload.nodeType;this._nodeName=payload.nodeName;this._localName=payload.localName;this._nodeValue=payload.nodeValue;this._pseudoType=payload.pseudoType;this._shadowRootType=payload.shadowRootType;this._frameOwnerFrameId=payload.frameId||null;this._xmlVersion=payload.xmlVersion;this._isSVGNode=!!payload.isSVG;this._shadowRoots=[];this._attributes=[];this._attributesMap={};if(payload.attributes)
this._setAttributesPayload(payload.attributes);this._markers=new Map();this._subtreeMarkerCount=0;this._childNodeCount=payload.childNodeCount||0;this._children=null;this.nextSibling=null;this.previousSibling=null;this.firstChild=null;this.lastChild=null;this.parentNode=null;if(payload.shadowRoots){for(let i=0;i<payload.shadowRoots.length;++i){const root=payload.shadowRoots[i];const node=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,root);this._shadowRoots.push(node);node.parentNode=this;}}
if(payload.templateContent){this._templateContent=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,payload.templateContent);this._templateContent.parentNode=this;this._children=[];}
if(payload.contentDocument){this._contentDocument=new SDK.DOMDocument(this._domModel,payload.contentDocument);this._contentDocument.parentNode=this;this._children=[];}else if((payload.nodeName==='IFRAME'||payload.nodeName==='PORTAL')&&payload.frameId){const childTarget=SDK.targetManager.targetById(payload.frameId);const childModel=childTarget?childTarget.model(SDK.DOMModel):null;if(childModel)
this._childDocumentPromiseForTesting=childModel.requestDocument();this._children=[];}
if(payload.importedDocument){this._importedDocument=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,payload.importedDocument);this._importedDocument.parentNode=this;this._children=[];}
if(payload.distributedNodes)
this._setDistributedNodePayloads(payload.distributedNodes);if(payload.children)
this._setChildrenPayload(payload.children);this._setPseudoElements(payload.pseudoElements);if(this._nodeType===Node.ELEMENT_NODE){if(this.ownerDocument&&!this.ownerDocument.documentElement&&this._nodeName==='HTML')
this.ownerDocument.documentElement=this;if(this.ownerDocument&&!this.ownerDocument.body&&this._nodeName==='BODY')
this.ownerDocument.body=this;}else if(this._nodeType===Node.DOCUMENT_TYPE_NODE){this.publicId=payload.publicId;this.systemId=payload.systemId;this.internalSubset=payload.internalSubset;}else if(this._nodeType===Node.ATTRIBUTE_NODE){this.name=payload.name;this.value=payload.value;}}
isSVGNode(){return this._isSVGNode;}
domModel(){return this._domModel;}
backendNodeId(){return this._backendNodeId;}
children(){return this._children?this._children.slice():null;}
hasAttributes(){return this._attributes.length>0;}
childNodeCount(){return this._childNodeCount;}
hasShadowRoots(){return!!this._shadowRoots.length;}
shadowRoots(){return this._shadowRoots.slice();}
templateContent(){return this._templateContent||null;}
contentDocument(){return this._contentDocument||null;}
isIframe(){return this._nodeName==='IFRAME';}
isPortal(){return this._nodeName==='PORTAL';}
importedDocument(){return this._importedDocument||null;}
nodeType(){return this._nodeType;}
nodeName(){return this._nodeName;}
pseudoType(){return this._pseudoType;}
hasPseudoElements(){return this._pseudoElements.size>0;}
pseudoElements(){return this._pseudoElements;}
beforePseudoElement(){if(!this._pseudoElements)
return null;return this._pseudoElements.get(SDK.DOMNode.PseudoElementNames.Before);}
afterPseudoElement(){if(!this._pseudoElements)
return null;return this._pseudoElements.get(SDK.DOMNode.PseudoElementNames.After);}
isInsertionPoint(){return!this.isXMLNode()&&(this._nodeName==='SHADOW'||this._nodeName==='CONTENT'||this._nodeName==='SLOT');}
distributedNodes(){return this._distributedNodes||[];}
isInShadowTree(){return this._isInShadowTree;}
ancestorShadowHost(){const ancestorShadowRoot=this.ancestorShadowRoot();return ancestorShadowRoot?ancestorShadowRoot.parentNode:null;}
ancestorShadowRoot(){if(!this._isInShadowTree)
return null;let current=this;while(current&&!current.isShadowRoot())
current=current.parentNode;return current;}
ancestorUserAgentShadowRoot(){const ancestorShadowRoot=this.ancestorShadowRoot();if(!ancestorShadowRoot)
return null;return ancestorShadowRoot.shadowRootType()===SDK.DOMNode.ShadowRootTypes.UserAgent?ancestorShadowRoot:null;}
isShadowRoot(){return!!this._shadowRootType;}
shadowRootType(){return this._shadowRootType||null;}
nodeNameInCorrectCase(){const shadowRootType=this.shadowRootType();if(shadowRootType)
return'#shadow-root ('+shadowRootType+')';if(!this.localName())
return this.nodeName();if(this.localName().length!==this.nodeName().length)
return this.nodeName();return this.localName();}
setNodeName(name,callback){this._agent.invoke_setNodeName({nodeId:this.id,name}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null,this._domModel.nodeForId(response.nodeId));});}
localName(){return this._localName;}
nodeValue(){return this._nodeValue;}
setNodeValue(value,callback){this._agent.invoke_setNodeValue({nodeId:this.id,value}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
getAttribute(name){const attr=this._attributesMap[name];return attr?attr.value:undefined;}
setAttribute(name,text,callback){this._agent.invoke_setAttributesAsText({nodeId:this.id,text,name}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
setAttributeValue(name,value,callback){this._agent.invoke_setAttributeValue({nodeId:this.id,name,value}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
setAttributeValuePromise(name,value){return new Promise(fulfill=>this.setAttributeValue(name,value,fulfill));}
attributes(){return this._attributes;}
async removeAttribute(name){const response=await this._agent.invoke_removeAttribute({nodeId:this.id,name});if(response[Protocol.Error])
return;delete this._attributesMap[name];const index=this._attributes.findIndex(attr=>attr.name===name);if(index!==-1)
this._attributes.splice(index,1);this._domModel.markUndoableState();}
getChildNodes(callback){if(this._children){callback(this.children());return;}
this._agent.invoke_requestChildNodes({nodeId:this.id}).then(response=>{callback(response[Protocol.Error]?null:this.children());});}
async getSubtree(depth,pierce){const response=await this._agent.invoke_requestChildNodes({nodeId:this.id,depth:depth,pierce:pierce});return response[Protocol.Error]?null:this._children;}
getOuterHTML(){return this._agent.getOuterHTML(this.id);}
setOuterHTML(html,callback){this._agent.invoke_setOuterHTML({nodeId:this.id,outerHTML:html}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
removeNode(callback){this._agent.invoke_removeNode({nodeId:this.id}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
async copyNode(){const text=await this._agent.getOuterHTML(this.id);if(text!==null)
InspectorFrontendHost.copyText(text);return text;}
path(){function canPush(node){return node&&('index'in node||(node.isShadowRoot()&&node.parentNode))&&node._nodeName.length;}
const path=[];let node=this;while(canPush(node)){const index=typeof node.index==='number'?node.index:(node.shadowRootType()===SDK.DOMNode.ShadowRootTypes.UserAgent?'u':'a');path.push([index,node._nodeName]);node=node.parentNode;}
path.reverse();return path.join(',');}
isAncestor(node){if(!node)
return false;let currentNode=node.parentNode;while(currentNode){if(this===currentNode)
return true;currentNode=currentNode.parentNode;}
return false;}
isDescendant(descendant){return descendant!==null&&descendant.isAncestor(this);}
frameId(){let node=this.parentNode||this;while(!node._frameOwnerFrameId&&node.parentNode)
node=node.parentNode;return node._frameOwnerFrameId;}
_setAttributesPayload(attrs){let attributesChanged=!this._attributes||attrs.length!==this._attributes.length*2;const oldAttributesMap=this._attributesMap||{};this._attributes=[];this._attributesMap={};for(let i=0;i<attrs.length;i+=2){const name=attrs[i];const value=attrs[i+1];this._addAttribute(name,value);if(attributesChanged)
continue;if(!oldAttributesMap[name]||oldAttributesMap[name].value!==value)
attributesChanged=true;}
return attributesChanged;}
_insertChild(prev,payload){const node=SDK.DOMNode.create(this._domModel,this.ownerDocument,this._isInShadowTree,payload);this._children.splice(this._children.indexOf(prev)+1,0,node);this._renumber();return node;}
_removeChild(node){if(node.pseudoType()){this._pseudoElements.delete(node.pseudoType());}else{const shadowRootIndex=this._shadowRoots.indexOf(node);if(shadowRootIndex!==-1){this._shadowRoots.splice(shadowRootIndex,1);}else{console.assert(this._children.indexOf(node)!==-1);this._children.splice(this._children.indexOf(node),1);}}
node.parentNode=null;this._subtreeMarkerCount-=node._subtreeMarkerCount;if(node._subtreeMarkerCount)
this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged,this);this._renumber();}
_setChildrenPayload(payloads){this._children=[];for(let i=0;i<payloads.length;++i){const payload=payloads[i];const node=SDK.DOMNode.create(this._domModel,this.ownerDocument,this._isInShadowTree,payload);this._children.push(node);}
this._renumber();}
_setPseudoElements(payloads){this._pseudoElements=new Map();if(!payloads)
return;for(let i=0;i<payloads.length;++i){const node=SDK.DOMNode.create(this._domModel,this.ownerDocument,this._isInShadowTree,payloads[i]);node.parentNode=this;this._pseudoElements.set(node.pseudoType(),node);}}
_setDistributedNodePayloads(payloads){this._distributedNodes=[];for(const payload of payloads){this._distributedNodes.push(new SDK.DOMNodeShortcut(this._domModel.target(),payload.backendNodeId,payload.nodeType,payload.nodeName));}}
_renumber(){this._childNodeCount=this._children.length;if(this._childNodeCount===0){this.firstChild=null;this.lastChild=null;return;}
this.firstChild=this._children[0];this.lastChild=this._children[this._childNodeCount-1];for(let i=0;i<this._childNodeCount;++i){const child=this._children[i];child.index=i;child.nextSibling=i+1<this._childNodeCount?this._children[i+1]:null;child.previousSibling=i-1>=0?this._children[i-1]:null;child.parentNode=this;}}
_addAttribute(name,value){const attr={name:name,value:value,_node:this};this._attributesMap[name]=attr;this._attributes.push(attr);}
_setAttribute(name,value){const attr=this._attributesMap[name];if(attr)
attr.value=value;else
this._addAttribute(name,value);}
_removeAttribute(name){const attr=this._attributesMap[name];if(attr){this._attributes.remove(attr);delete this._attributesMap[name];}}
copyTo(targetNode,anchorNode,callback){this._agent.invoke_copyTo({nodeId:this.id,targetNodeId:targetNode.id,insertBeforeNodeId:anchorNode?anchorNode.id:undefined}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null,response.nodeId);});}
moveTo(targetNode,anchorNode,callback){this._agent.invoke_moveTo({nodeId:this.id,targetNodeId:targetNode.id,insertBeforeNodeId:anchorNode?anchorNode.id:undefined}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null,this._domModel.nodeForId(response.nodeId));});}
isXMLNode(){return!!this._xmlVersion;}
setMarker(name,value){if(value===null){if(!this._markers.has(name))
return;this._markers.delete(name);for(let node=this;node;node=node.parentNode)
--node._subtreeMarkerCount;for(let node=this;node;node=node.parentNode)
this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged,node);return;}
if(this.parentNode&&!this._markers.has(name)){for(let node=this;node;node=node.parentNode)
++node._subtreeMarkerCount;}
this._markers.set(name,value);for(let node=this;node;node=node.parentNode)
this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged,node);}
marker(name){return this._markers.get(name)||null;}
traverseMarkers(visitor){function traverse(node){if(!node._subtreeMarkerCount)
return;for(const marker of node._markers.keys())
visitor(node,marker);if(!node._children)
return;for(const child of node._children)
traverse(child);}
traverse(this);}
resolveURL(url){if(!url)
return url;for(let frameOwnerCandidate=this;frameOwnerCandidate;frameOwnerCandidate=frameOwnerCandidate.parentNode){if(frameOwnerCandidate.baseURL)
return Common.ParsedURL.completeURL(frameOwnerCandidate.baseURL,url);}
return null;}
highlight(mode){this._domModel.overlayModel().highlightInOverlay({node:this},mode);}
highlightForTwoSeconds(){this._domModel.overlayModel().highlightInOverlayForTwoSeconds({node:this});}
async resolveToObject(objectGroup){const object=await this._agent.resolveNode(this.id,undefined,objectGroup);return object&&this._domModel._runtimeModel.createRemoteObject(object);}
boxModel(){return this._agent.getBoxModel(this.id);}
setAsInspectedNode(){let node=this;while(true){let ancestor=node.ancestorUserAgentShadowRoot();if(!ancestor)
break;ancestor=node.ancestorShadowHost();if(!ancestor)
break;node=ancestor;}
this._agent.setInspectedNode(node.id);}
enclosingElementOrSelf(){let node=this;if(node&&node.nodeType()===Node.TEXT_NODE&&node.parentNode)
node=node.parentNode;if(node&&node.nodeType()!==Node.ELEMENT_NODE)
node=null;return node;}
async scrollIntoView(){const node=this.enclosingElementOrSelf();const object=await node.resolveToObject();if(!object)
return;object.callFunction(scrollIntoView);object.release();node.highlightForTwoSeconds();function scrollIntoView(){this.scrollIntoViewIfNeeded(true);}}
async focus(){const node=this.enclosingElementOrSelf();const object=await node.resolveToObject();if(!object)
return;await object.callFunction(focusInPage);object.release();node.highlightForTwoSeconds();this._domModel.target().pageAgent().bringToFront();function focusInPage(){this.focus();}}
simpleSelector(){const lowerCaseName=this.localName()||this.nodeName().toLowerCase();if(this.nodeType()!==Node.ELEMENT_NODE)
return lowerCaseName;if(lowerCaseName==='input'&&this.getAttribute('type')&&!this.getAttribute('id')&&!this.getAttribute('class'))
return lowerCaseName+'[type="'+this.getAttribute('type')+'"]';if(this.getAttribute('id'))
return lowerCaseName+'#'+this.getAttribute('id');if(this.getAttribute('class')){return(lowerCaseName==='div'?'':lowerCaseName)+'.'+
this.getAttribute('class').trim().replace(/\s+/g,'.');}
return lowerCaseName;}};SDK.DOMNode.PseudoElementNames={Before:'before',After:'after'};SDK.DOMNode.ShadowRootTypes={UserAgent:'user-agent',Open:'open',Closed:'closed'};SDK.DOMNode.Attribute;SDK.DeferredDOMNode=class{constructor(target,backendNodeId){this._domModel=(target.model(SDK.DOMModel));this._backendNodeId=backendNodeId;}
resolve(callback){this.resolvePromise().then(callback);}
async resolvePromise(){const nodeIds=await this._domModel.pushNodesByBackendIdsToFrontend(new Set([this._backendNodeId]));return nodeIds&&nodeIds.get(this._backendNodeId)||null;}
backendNodeId(){return this._backendNodeId;}
domModel(){return this._domModel;}
highlight(){this._domModel.overlayModel().highlightInOverlay({deferredNode:this});}};SDK.DOMNodeShortcut=class{constructor(target,backendNodeId,nodeType,nodeName){this.nodeType=nodeType;this.nodeName=nodeName;this.deferredNode=new SDK.DeferredDOMNode(target,backendNodeId);}};SDK.DOMDocument=class extends SDK.DOMNode{constructor(domModel,payload){super(domModel);this._init(this,false,payload);this.documentURL=payload.documentURL||'';this.baseURL=payload.baseURL||'';}};SDK.DOMModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.domAgent();this._idToDOMNode={};this._document=null;this._attributeLoadNodeIds=new Set();target.registerDOMDispatcher(new SDK.DOMDispatcher(this));this._runtimeModel=(target.model(SDK.RuntimeModel));if(!target.suspended())
this._agent.enable();}
runtimeModel(){return this._runtimeModel;}
cssModel(){return(this.target().model(SDK.CSSModel));}
overlayModel(){return(this.target().model(SDK.OverlayModel));}
static cancelSearch(){for(const domModel of SDK.targetManager.models(SDK.DOMModel))
domModel._cancelSearch();}
_scheduleMutationEvent(node){if(!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated))
return;this._lastMutationId=(this._lastMutationId||0)+1;Promise.resolve().then(callObserve.bind(this,node,this._lastMutationId));function callObserve(node,mutationId){if(!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated)||this._lastMutationId!==mutationId)
return;this.dispatchEventToListeners(SDK.DOMModel.Events.DOMMutated,node);}}
requestDocument(){if(this._document)
return Promise.resolve(this._document);if(!this._pendingDocumentRequestPromise)
this._pendingDocumentRequestPromise=this._requestDocument();return this._pendingDocumentRequestPromise;}
async _requestDocument(){const documentPayload=await this._agent.getDocument();delete this._pendingDocumentRequestPromise;if(documentPayload)
this._setDocument(documentPayload);if(!this._document){console.error('No document');return null;}
const parentModel=this.parentModel();if(parentModel&&!this._frameOwnerNode){await parentModel.requestDocument();const response=await parentModel._agent.invoke_getFrameOwner({frameId:this.target().id()});if(!response[Protocol.Error])
this._frameOwnerNode=parentModel.nodeForId(response.nodeId);}
if(this._frameOwnerNode){const oldDocument=this._frameOwnerNode._contentDocument;this._frameOwnerNode._contentDocument=this._document;this._frameOwnerNode._children=[];if(this._document){this._document.parentNode=this._frameOwnerNode;this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,this._document);}else if(oldDocument){this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:oldDocument,parent:this._frameOwnerNode});}}
return this._document;}
existingDocument(){return this._document;}
async pushNodeToFrontend(objectId){await this.requestDocument();const nodeId=await this._agent.requestNode(objectId);return nodeId?this.nodeForId(nodeId):null;}
pushNodeByPathToFrontend(path){return this.requestDocument().then(()=>this._agent.pushNodeByPathToFrontend(path));}
async pushNodesByBackendIdsToFrontend(backendNodeIds){await this.requestDocument();const backendNodeIdsArray=backendNodeIds.valuesArray();const nodeIds=await this._agent.pushNodesByBackendIdsToFrontend(backendNodeIdsArray);if(!nodeIds)
return null;const map=new Map();for(let i=0;i<nodeIds.length;++i){if(nodeIds[i])
map.set(backendNodeIdsArray[i],this.nodeForId(nodeIds[i]));}
return map;}
_wrapClientCallback(callback){function wrapper(error,result){callback(error?null:result||null);}
return wrapper;}
_attributeModified(nodeId,name,value){const node=this._idToDOMNode[nodeId];if(!node)
return;node._setAttribute(name,value);this.dispatchEventToListeners(SDK.DOMModel.Events.AttrModified,{node:node,name:name});this._scheduleMutationEvent(node);}
_attributeRemoved(nodeId,name){const node=this._idToDOMNode[nodeId];if(!node)
return;node._removeAttribute(name);this.dispatchEventToListeners(SDK.DOMModel.Events.AttrRemoved,{node:node,name:name});this._scheduleMutationEvent(node);}
_inlineStyleInvalidated(nodeIds){this._attributeLoadNodeIds.addAll(nodeIds);if(!this._loadNodeAttributesTimeout)
this._loadNodeAttributesTimeout=setTimeout(this._loadNodeAttributes.bind(this),20);}
_loadNodeAttributes(){delete this._loadNodeAttributesTimeout;for(const nodeId of this._attributeLoadNodeIds){this._agent.getAttributes(nodeId).then(attributes=>{if(!attributes){return;}
const node=this._idToDOMNode[nodeId];if(!node)
return;if(node._setAttributesPayload(attributes)){this.dispatchEventToListeners(SDK.DOMModel.Events.AttrModified,{node:node,name:'style'});this._scheduleMutationEvent(node);}});}
this._attributeLoadNodeIds.clear();}
_characterDataModified(nodeId,newValue){const node=this._idToDOMNode[nodeId];node._nodeValue=newValue;this.dispatchEventToListeners(SDK.DOMModel.Events.CharacterDataModified,node);this._scheduleMutationEvent(node);}
nodeForId(nodeId){return this._idToDOMNode[nodeId]||null;}
_documentUpdated(){const documentWasRequested=this._document||this._pendingDocumentRequestPromise;this._setDocument(null);if(this.parentModel()&&documentWasRequested)
this.requestDocument();}
_setDocument(payload){this._idToDOMNode={};if(payload&&'nodeId'in payload)
this._document=new SDK.DOMDocument(this,payload);else
this._document=null;SDK.domModelUndoStack._dispose(this);if(!this.parentModel())
this.dispatchEventToListeners(SDK.DOMModel.Events.DocumentUpdated,this);}
_setDetachedRoot(payload){if(payload.nodeName==='#document')
new SDK.DOMDocument(this,payload);else
SDK.DOMNode.create(this,null,false,payload);}
_setChildNodes(parentId,payloads){if(!parentId&&payloads.length){this._setDetachedRoot(payloads[0]);return;}
const parent=this._idToDOMNode[parentId];parent._setChildrenPayload(payloads);}
_childNodeCountUpdated(nodeId,newValue){const node=this._idToDOMNode[nodeId];node._childNodeCount=newValue;this.dispatchEventToListeners(SDK.DOMModel.Events.ChildNodeCountUpdated,node);this._scheduleMutationEvent(node);}
_childNodeInserted(parentId,prevId,payload){const parent=this._idToDOMNode[parentId];const prev=this._idToDOMNode[prevId];const node=parent._insertChild(prev,payload);this._idToDOMNode[node.id]=node;this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,node);this._scheduleMutationEvent(node);}
_childNodeRemoved(parentId,nodeId){const parent=this._idToDOMNode[parentId];const node=this._idToDOMNode[nodeId];parent._removeChild(node);this._unbind(node);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:node,parent:parent});this._scheduleMutationEvent(node);}
_shadowRootPushed(hostId,root){const host=this._idToDOMNode[hostId];if(!host)
return;const node=SDK.DOMNode.create(this,host.ownerDocument,true,root);node.parentNode=host;this._idToDOMNode[node.id]=node;host._shadowRoots.unshift(node);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,node);this._scheduleMutationEvent(node);}
_shadowRootPopped(hostId,rootId){const host=this._idToDOMNode[hostId];if(!host)
return;const root=this._idToDOMNode[rootId];if(!root)
return;host._removeChild(root);this._unbind(root);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:root,parent:host});this._scheduleMutationEvent(root);}
_pseudoElementAdded(parentId,pseudoElement){const parent=this._idToDOMNode[parentId];if(!parent)
return;const node=SDK.DOMNode.create(this,parent.ownerDocument,false,pseudoElement);node.parentNode=parent;this._idToDOMNode[node.id]=node;console.assert(!parent._pseudoElements.get(node.pseudoType()));parent._pseudoElements.set(node.pseudoType(),node);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,node);this._scheduleMutationEvent(node);}
_pseudoElementRemoved(parentId,pseudoElementId){const parent=this._idToDOMNode[parentId];if(!parent)
return;const pseudoElement=this._idToDOMNode[pseudoElementId];if(!pseudoElement)
return;parent._removeChild(pseudoElement);this._unbind(pseudoElement);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:pseudoElement,parent:parent});this._scheduleMutationEvent(pseudoElement);}
_distributedNodesUpdated(insertionPointId,distributedNodes){const insertionPoint=this._idToDOMNode[insertionPointId];if(!insertionPoint)
return;insertionPoint._setDistributedNodePayloads(distributedNodes);this.dispatchEventToListeners(SDK.DOMModel.Events.DistributedNodesChanged,insertionPoint);this._scheduleMutationEvent(insertionPoint);}
_unbind(node){delete this._idToDOMNode[node.id];for(let i=0;node._children&&i<node._children.length;++i)
this._unbind(node._children[i]);for(let i=0;i<node._shadowRoots.length;++i)
this._unbind(node._shadowRoots[i]);const pseudoElements=node.pseudoElements();for(const value of pseudoElements.values())
this._unbind(value);if(node._templateContent)
this._unbind(node._templateContent);}
async performSearch(query,includeUserAgentShadowDOM){const response=await this._agent.invoke_performSearch({query,includeUserAgentShadowDOM});if(!response[Protocol.Error])
this._searchId=response.searchId;return response[Protocol.Error]?0:response.resultCount;}
async searchResult(index){if(!this._searchId)
return null;const nodeIds=await this._agent.getSearchResults(this._searchId,index,index+1);return nodeIds&&nodeIds.length===1?this.nodeForId(nodeIds[0]):null;}
_cancelSearch(){if(!this._searchId)
return;this._agent.discardSearchResults(this._searchId);delete this._searchId;}
classNamesPromise(nodeId){return this._agent.collectClassNamesFromSubtree(nodeId).then(classNames=>classNames||[]);}
querySelector(nodeId,selectors){return this._agent.querySelector(nodeId,selectors);}
querySelectorAll(nodeId,selectors){return this._agent.querySelectorAll(nodeId,selectors);}
markUndoableState(minorChange){SDK.domModelUndoStack._markUndoableState(this,minorChange||false);}
async nodeForLocation(x,y,includeUserAgentShadowDOM){const response=await this._agent.invoke_getNodeForLocation({x,y,includeUserAgentShadowDOM});if(response[Protocol.Error]||!response.nodeId)
return null;return this.nodeForId(response.nodeId);}
pushObjectAsNodeToFrontend(object){return object.isNode()?this.pushNodeToFrontend((object.objectId)):Promise.resolve(null);}
suspendModel(){return this._agent.disable().then(()=>this._setDocument(null));}
resumeModel(){return this._agent.enable();}
dispose(){SDK.domModelUndoStack._dispose(this);}
parentModel(){const parentTarget=this.target().parentTarget();return parentTarget?parentTarget.model(SDK.DOMModel):null;}};SDK.SDKModel.register(SDK.DOMModel,SDK.Target.Capability.DOM,true);SDK.DOMModel.Events={AttrModified:Symbol('AttrModified'),AttrRemoved:Symbol('AttrRemoved'),CharacterDataModified:Symbol('CharacterDataModified'),DOMMutated:Symbol('DOMMutated'),NodeInserted:Symbol('NodeInserted'),NodeRemoved:Symbol('NodeRemoved'),DocumentUpdated:Symbol('DocumentUpdated'),ChildNodeCountUpdated:Symbol('ChildNodeCountUpdated'),DistributedNodesChanged:Symbol('DistributedNodesChanged'),MarkersChanged:Symbol('MarkersChanged')};SDK.DOMDispatcher=class{constructor(domModel){this._domModel=domModel;}
documentUpdated(){this._domModel._documentUpdated();}
attributeModified(nodeId,name,value){this._domModel._attributeModified(nodeId,name,value);}
attributeRemoved(nodeId,name){this._domModel._attributeRemoved(nodeId,name);}
inlineStyleInvalidated(nodeIds){this._domModel._inlineStyleInvalidated(nodeIds);}
characterDataModified(nodeId,characterData){this._domModel._characterDataModified(nodeId,characterData);}
setChildNodes(parentId,payloads){this._domModel._setChildNodes(parentId,payloads);}
childNodeCountUpdated(nodeId,childNodeCount){this._domModel._childNodeCountUpdated(nodeId,childNodeCount);}
childNodeInserted(parentNodeId,previousNodeId,payload){this._domModel._childNodeInserted(parentNodeId,previousNodeId,payload);}
childNodeRemoved(parentNodeId,nodeId){this._domModel._childNodeRemoved(parentNodeId,nodeId);}
shadowRootPushed(hostId,root){this._domModel._shadowRootPushed(hostId,root);}
shadowRootPopped(hostId,rootId){this._domModel._shadowRootPopped(hostId,rootId);}
pseudoElementAdded(parentId,pseudoElement){this._domModel._pseudoElementAdded(parentId,pseudoElement);}
pseudoElementRemoved(parentId,pseudoElementId){this._domModel._pseudoElementRemoved(parentId,pseudoElementId);}
distributedNodesUpdated(insertionPointId,distributedNodes){this._domModel._distributedNodesUpdated(insertionPointId,distributedNodes);}};SDK.DOMModelUndoStack=class{constructor(){this._stack=[];this._index=0;this._lastModelWithMinorChange=null;}
_markUndoableState(model,minorChange){if(this._lastModelWithMinorChange&&model!==this._lastModelWithMinorChange){this._lastModelWithMinorChange.markUndoableState();this._lastModelWithMinorChange=null;}
if(minorChange&&this._lastModelWithMinorChange===model)
return;this._stack=this._stack.slice(0,this._index);this._stack.push(model);this._index=this._stack.length;if(minorChange){this._lastModelWithMinorChange=model;}else{model._agent.markUndoableState();this._lastModelWithMinorChange=null;}}
undo(){if(this._index===0)
return Promise.resolve();--this._index;this._lastModelWithMinorChange=null;return this._stack[this._index]._agent.undo();}
redo(){if(this._index>=this._stack.length)
return Promise.resolve();++this._index;this._lastModelWithMinorChange=null;return this._stack[this._index-1]._agent.redo();}
_dispose(model){let shift=0;for(let i=0;i<this._index;++i){if(this._stack[i]===model)
++shift;}
this._stack.remove(model);this._index-=shift;if(this._lastModelWithMinorChange===model)
this._lastModelWithMinorChange=null;}};SDK.domModelUndoStack=new SDK.DOMModelUndoStack();;SDK.DebuggerModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerDebuggerDispatcher(new SDK.DebuggerDispatcher(this));this._agent=target.debuggerAgent();this._runtimeModel=(target.model(SDK.RuntimeModel));this._sourceMapManager=new SDK.SourceMapManager(target);this._sourceMapIdToScript=new Map();this._debuggerPausedDetails=null;this._scripts=new Map();this._scriptsBySourceURL=new Map();this._discardableScripts=[];this._breakpointResolvedEventTarget=new Common.Object();this._isPausing=false;Common.moduleSetting('pauseOnExceptionEnabled').addChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('pauseOnCaughtException').addChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('disableAsyncStackTraces').addChangeListener(this._asyncStackTracesStateChanged,this);Common.moduleSetting('breakpointsActive').addChangeListener(this._breakpointsActiveChanged,this);if(!target.suspended())
this._enableDebugger();this._stringMap=new Map();this._sourceMapManager.setEnabled(Common.moduleSetting('jsSourceMapsEnabled').get());Common.moduleSetting('jsSourceMapsEnabled').addChangeListener(event=>this._sourceMapManager.setEnabled((event.data)));}
static _sourceMapId(executionContextId,sourceURL,sourceMapURL){if(!sourceMapURL)
return null;return executionContextId+':'+sourceURL+':'+sourceMapURL;}
sourceMapManager(){return this._sourceMapManager;}
runtimeModel(){return this._runtimeModel;}
debuggerEnabled(){return!!this._debuggerEnabled;}
_enableDebugger(){if(this._debuggerEnabled)
return Promise.resolve();this._debuggerEnabled=true;const isRemoteFrontend=Runtime.queryParam('remoteFrontend')||Runtime.queryParam('ws');const maxScriptsCacheSize=isRemoteFrontend?10e6:100e6;const enablePromise=this._agent.enable(maxScriptsCacheSize);enablePromise.then(this._registerDebugger.bind(this));this._pauseOnExceptionStateChanged();this._asyncStackTracesStateChanged();if(!Common.moduleSetting('breakpointsActive').get())
this._breakpointsActiveChanged();if(SDK.DebuggerModel._scheduledPauseOnAsyncCall)
this._pauseOnAsyncCall(SDK.DebuggerModel._scheduledPauseOnAsyncCall);this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerWasEnabled,this);return enablePromise;}
_registerDebugger(debuggerId){if(!debuggerId)
return;SDK.DebuggerModel._debuggerIdToModel.set(debuggerId,this);this._debuggerId=debuggerId;this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerIsReadyToPause,this);}
isReadyToPause(){return!!this._debuggerId;}
static modelForDebuggerId(debuggerId){return SDK.DebuggerModel._debuggerIdToModel.get(debuggerId)||null;}
_disableDebugger(){if(!this._debuggerEnabled)
return Promise.resolve();this._debuggerEnabled=false;const disablePromise=this._agent.disable();this._isPausing=false;this._asyncStackTracesStateChanged();this.globalObjectCleared();this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerWasDisabled);SDK.DebuggerModel._debuggerIdToModel.delete(this._debuggerId);return disablePromise;}
_skipAllPauses(skip){if(this._skipAllPausesTimeout){clearTimeout(this._skipAllPausesTimeout);delete this._skipAllPausesTimeout;}
this._agent.setSkipAllPauses(skip);}
skipAllPausesUntilReloadOrTimeout(timeout){if(this._skipAllPausesTimeout)
clearTimeout(this._skipAllPausesTimeout);this._agent.setSkipAllPauses(true);this._skipAllPausesTimeout=setTimeout(this._skipAllPauses.bind(this,false),timeout);}
_pauseOnExceptionStateChanged(){let state;if(!Common.moduleSetting('pauseOnExceptionEnabled').get())
state=SDK.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions;else if(Common.moduleSetting('pauseOnCaughtException').get())
state=SDK.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions;else
state=SDK.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions;this._agent.setPauseOnExceptions(state);}
_asyncStackTracesStateChanged(){const maxAsyncStackChainDepth=32;const enabled=!Common.moduleSetting('disableAsyncStackTraces').get()&&this._debuggerEnabled;this._agent.setAsyncCallStackDepth(enabled?maxAsyncStackChainDepth:0);}
_breakpointsActiveChanged(){this._agent.setBreakpointsActive(Common.moduleSetting('breakpointsActive').get());}
stepInto(){this._agent.stepInto();}
stepOver(){this._agent.stepOver();}
stepOut(){this._agent.stepOut();}
scheduleStepIntoAsync(){this._agent.invoke_stepInto({breakOnAsyncCall:true});}
resume(){this._agent.resume();this._isPausing=false;}
pause(){this._isPausing=true;this._skipAllPauses(false);this._agent.pause();}
_pauseOnAsyncCall(parentStackTraceId){return this._agent.invoke_pauseOnAsyncCall({parentStackTraceId:parentStackTraceId});}
async setBreakpointByURL(url,lineNumber,columnNumber,condition){let urlRegex;if(this.target().type()===SDK.Target.Type.Node){const platformPath=Common.ParsedURL.urlToPlatformPath(url,Host.isWin());urlRegex=`${platformPath.escapeForRegExp()}|${url.escapeForRegExp()}`;}
let minColumnNumber=0;const scripts=this._scriptsBySourceURL.get(url)||[];for(let i=0,l=scripts.length;i<l;++i){const script=scripts[i];if(lineNumber===script.lineOffset)
minColumnNumber=minColumnNumber?Math.min(minColumnNumber,script.columnOffset):script.columnOffset;}
columnNumber=Math.max(columnNumber,minColumnNumber);const response=await this._agent.invoke_setBreakpointByUrl({lineNumber:lineNumber,url:urlRegex?undefined:url,urlRegex:urlRegex,columnNumber:columnNumber,condition:condition});if(response[Protocol.Error])
return{locations:[],breakpointId:null};let locations;if(response.locations)
locations=response.locations.map(payload=>SDK.DebuggerModel.Location.fromPayload(this,payload));return{locations:locations,breakpointId:response.breakpointId};}
async setBreakpointInAnonymousScript(scriptId,scriptHash,lineNumber,columnNumber,condition){const response=await this._agent.invoke_setBreakpointByUrl({lineNumber:lineNumber,scriptHash:scriptHash,columnNumber:columnNumber,condition:condition});const error=response[Protocol.Error];if(error){if(error!=='Either url or urlRegex must be specified.')
return{locations:[],breakpointId:null};return this._setBreakpointBySourceId(scriptId,lineNumber,columnNumber,condition);}
let locations;if(response.locations)
locations=response.locations.map(payload=>SDK.DebuggerModel.Location.fromPayload(this,payload));return{locations:locations,breakpointId:response.breakpointId};}
async _setBreakpointBySourceId(scriptId,lineNumber,columnNumber,condition){const response=await this._agent.invoke_setBreakpoint({location:{scriptId:scriptId,lineNumber:lineNumber,columnNumber:columnNumber},condition:condition});if(response[Protocol.Error])
return{breakpointId:null,locations:[]};let actualLocation=[];if(response.actualLocation)
actualLocation=[SDK.DebuggerModel.Location.fromPayload(this,response.actualLocation)];return{locations:actualLocation,breakpointId:response.breakpointId};}
async removeBreakpoint(breakpointId){const response=await this._agent.invoke_removeBreakpoint({breakpointId});if(response[Protocol.Error])
console.error('Failed to remove breakpoint: '+response[Protocol.Error]);}
async getPossibleBreakpoints(startLocation,endLocation,restrictToFunction){const response=await this._agent.invoke_getPossibleBreakpoints({start:startLocation.payload(),end:endLocation?endLocation.payload():undefined,restrictToFunction:restrictToFunction});if(response[Protocol.Error]||!response.locations)
return[];return response.locations.map(location=>SDK.DebuggerModel.BreakLocation.fromPayload(this,location));}
async fetchAsyncStackTrace(stackId){const response=await this._agent.invoke_getStackTrace({stackTraceId:stackId});return response[Protocol.Error]?null:response.stackTrace;}
_breakpointResolved(breakpointId,location){this._breakpointResolvedEventTarget.dispatchEventToListeners(breakpointId,SDK.DebuggerModel.Location.fromPayload(this,location));}
globalObjectCleared(){this._setDebuggerPausedDetails(null);this._reset();this.dispatchEventToListeners(SDK.DebuggerModel.Events.GlobalObjectCleared,this);}
_reset(){for(const scriptWithSourceMap of this._sourceMapIdToScript.values())
this._sourceMapManager.detachSourceMap(scriptWithSourceMap);this._sourceMapIdToScript.clear();this._scripts.clear();this._scriptsBySourceURL.clear();this._stringMap.clear();this._discardableScripts=[];}
scripts(){return Array.from(this._scripts.values());}
scriptForId(scriptId){return this._scripts.get(scriptId)||null;}
scriptsForSourceURL(sourceURL){if(!sourceURL)
return[];return this._scriptsBySourceURL.get(sourceURL)||[];}
scriptsForExecutionContext(executionContext){const result=[];for(const script of this._scripts.values()){if(script.executionContextId===executionContext.id)
result.push(script);}
return result;}
setScriptSource(scriptId,newSource,callback){this._scripts.get(scriptId).editSource(newSource,this._didEditScriptSource.bind(this,scriptId,newSource,callback));}
_didEditScriptSource(scriptId,newSource,callback,error,exceptionDetails,callFrames,asyncStackTrace,asyncStackTraceId,needsStepIn){callback(error,exceptionDetails);if(needsStepIn){this.stepInto();return;}
if(!error&&callFrames&&callFrames.length){this._pausedScript(callFrames,this._debuggerPausedDetails.reason,this._debuggerPausedDetails.auxData,this._debuggerPausedDetails.breakpointIds,asyncStackTrace,asyncStackTraceId);}}
get callFrames(){return this._debuggerPausedDetails?this._debuggerPausedDetails.callFrames:null;}
debuggerPausedDetails(){return this._debuggerPausedDetails;}
_setDebuggerPausedDetails(debuggerPausedDetails){this._isPausing=false;this._debuggerPausedDetails=debuggerPausedDetails;if(this._debuggerPausedDetails){if(Runtime.experiments.isEnabled('emptySourceMapAutoStepping')&&this._beforePausedCallback){if(!this._beforePausedCallback.call(null,this._debuggerPausedDetails))
return false;}
this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerPaused,this);}
if(debuggerPausedDetails)
this.setSelectedCallFrame(debuggerPausedDetails.callFrames[0]);else
this.setSelectedCallFrame(null);return true;}
setBeforePausedCallback(callback){this._beforePausedCallback=callback;}
async _pausedScript(callFrames,reason,auxData,breakpointIds,asyncStackTrace,asyncStackTraceId,asyncCallStackTraceId){if(asyncCallStackTraceId){SDK.DebuggerModel._scheduledPauseOnAsyncCall=asyncCallStackTraceId;const promises=[];for(const model of SDK.DebuggerModel._debuggerIdToModel.values())
promises.push(model._pauseOnAsyncCall(asyncCallStackTraceId));await Promise.all(promises);this.resume();return;}
const pausedDetails=new SDK.DebuggerPausedDetails(this,callFrames,reason,auxData,breakpointIds,asyncStackTrace,asyncStackTraceId);if(pausedDetails&&this._continueToLocationCallback){const callback=this._continueToLocationCallback;delete this._continueToLocationCallback;if(callback(pausedDetails))
return;}
if(!this._setDebuggerPausedDetails(pausedDetails))
this._agent.stepInto();SDK.DebuggerModel._scheduledPauseOnAsyncCall=null;}
_resumedScript(){this._setDebuggerPausedDetails(null);this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerResumed,this);}
_parsedScriptSource(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,isLiveEdit,sourceMapURL,hasSourceURLComment,hasSyntaxError,length,originStackTrace){if(this._scripts.has(scriptId))
return this._scripts.get(scriptId);let isContentScript=false;if(executionContextAuxData&&('isDefault'in executionContextAuxData))
isContentScript=!executionContextAuxData['isDefault'];sourceURL=this._internString(sourceURL);const script=new SDK.Script(this,scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,this._internString(hash),isContentScript,isLiveEdit,sourceMapURL,hasSourceURLComment,length,originStackTrace);this._registerScript(script);this.dispatchEventToListeners(SDK.DebuggerModel.Events.ParsedScriptSource,script);const sourceMapId=SDK.DebuggerModel._sourceMapId(script.executionContextId,script.sourceURL,script.sourceMapURL);if(sourceMapId&&!hasSyntaxError){const previousScript=this._sourceMapIdToScript.get(sourceMapId);if(previousScript)
this._sourceMapManager.detachSourceMap(previousScript);this._sourceMapIdToScript.set(sourceMapId,script);this._sourceMapManager.attachSourceMap(script,script.sourceURL,script.sourceMapURL);}
const isDiscardable=hasSyntaxError&&script.isAnonymousScript();if(isDiscardable){this._discardableScripts.push(script);this._collectDiscardedScripts();}
return script;}
setSourceMapURL(script,newSourceMapURL){let sourceMapId=SDK.DebuggerModel._sourceMapId(script.executionContextId,script.sourceURL,script.sourceMapURL);if(sourceMapId&&this._sourceMapIdToScript.get(sourceMapId)===script)
this._sourceMapIdToScript.delete(sourceMapId);this._sourceMapManager.detachSourceMap(script);script.sourceMapURL=newSourceMapURL;sourceMapId=SDK.DebuggerModel._sourceMapId(script.executionContextId,script.sourceURL,script.sourceMapURL);if(!sourceMapId)
return;this._sourceMapIdToScript.set(sourceMapId,script);this._sourceMapManager.attachSourceMap(script,script.sourceURL,script.sourceMapURL);}
executionContextDestroyed(executionContext){const sourceMapIds=Array.from(this._sourceMapIdToScript.keys());for(const sourceMapId of sourceMapIds){const script=this._sourceMapIdToScript.get(sourceMapId);if(script.executionContextId===executionContext.id){this._sourceMapIdToScript.delete(sourceMapId);this._sourceMapManager.detachSourceMap(script);}}}
_registerScript(script){this._scripts.set(script.scriptId,script);if(script.isAnonymousScript())
return;let scripts=this._scriptsBySourceURL.get(script.sourceURL);if(!scripts){scripts=[];this._scriptsBySourceURL.set(script.sourceURL,scripts);}
scripts.push(script);}
_unregisterScript(script){console.assert(script.isAnonymousScript());this._scripts.delete(script.scriptId);}
_collectDiscardedScripts(){if(this._discardableScripts.length<1000)
return;const scriptsToDiscard=this._discardableScripts.splice(0,100);for(const script of scriptsToDiscard){this._unregisterScript(script);this.dispatchEventToListeners(SDK.DebuggerModel.Events.DiscardedAnonymousScriptSource,script);}}
createRawLocation(script,lineNumber,columnNumber){return new SDK.DebuggerModel.Location(this,script.scriptId,lineNumber,columnNumber);}
createRawLocationByURL(sourceURL,lineNumber,columnNumber){let closestScript=null;const scripts=this._scriptsBySourceURL.get(sourceURL)||[];for(let i=0,l=scripts.length;i<l;++i){const script=scripts[i];if(!closestScript)
closestScript=script;if(script.lineOffset>lineNumber||(script.lineOffset===lineNumber&&script.columnOffset>columnNumber))
continue;if(script.endLine<lineNumber||(script.endLine===lineNumber&&script.endColumn<=columnNumber))
continue;closestScript=script;break;}
return closestScript?new SDK.DebuggerModel.Location(this,closestScript.scriptId,lineNumber,columnNumber):null;}
createRawLocationByScriptId(scriptId,lineNumber,columnNumber){const script=this.scriptForId(scriptId);return script?this.createRawLocation(script,lineNumber,columnNumber):null;}
createRawLocationsByStackTrace(stackTrace){const frames=[];while(stackTrace){for(const frame of stackTrace.callFrames)
frames.push(frame);stackTrace=stackTrace.parent;}
const rawLocations=[];for(const frame of frames){const rawLocation=this.createRawLocationByScriptId(frame.scriptId,frame.lineNumber,frame.columnNumber);if(rawLocation)
rawLocations.push(rawLocation);}
return rawLocations;}
isPaused(){return!!this.debuggerPausedDetails();}
isPausing(){return this._isPausing;}
setSelectedCallFrame(callFrame){if(this._selectedCallFrame===callFrame)
return;this._selectedCallFrame=callFrame;this.dispatchEventToListeners(SDK.DebuggerModel.Events.CallFrameSelected,this);}
selectedCallFrame(){return this._selectedCallFrame;}
evaluateOnSelectedCallFrame(options){return this.selectedCallFrame().evaluate(options);}
functionDetailsPromise(remoteObject){return remoteObject.getAllProperties(false,false).then(buildDetails.bind(this));function buildDetails(response){if(!response)
return null;let location=null;if(response.internalProperties){for(const prop of response.internalProperties){if(prop.name==='[[FunctionLocation]]')
location=prop.value;}}
let functionName=null;if(response.properties){for(const prop of response.properties){if(prop.name==='name'&&prop.value&&prop.value.type==='string')
functionName=prop.value;if(prop.name==='displayName'&&prop.value&&prop.value.type==='string'){functionName=prop.value;break;}}}
let debuggerLocation=null;if(location){debuggerLocation=this.createRawLocationByScriptId(location.value.scriptId,location.value.lineNumber,location.value.columnNumber);}
return{location:debuggerLocation,functionName:functionName?functionName.value:''};}}
async setVariableValue(scopeNumber,variableName,newValue,callFrameId){const response=await this._agent.invoke_setVariableValue({scopeNumber,variableName,newValue,callFrameId});const error=response[Protocol.Error];if(error)
console.error(error);return error;}
addBreakpointListener(breakpointId,listener,thisObject){this._breakpointResolvedEventTarget.addEventListener(breakpointId,listener,thisObject);}
removeBreakpointListener(breakpointId,listener,thisObject){this._breakpointResolvedEventTarget.removeEventListener(breakpointId,listener,thisObject);}
async setBlackboxPatterns(patterns){const response=await this._agent.invoke_setBlackboxPatterns({patterns});const error=response[Protocol.Error];if(error)
console.error(error);return!error;}
dispose(){this._sourceMapManager.dispose();SDK.DebuggerModel._debuggerIdToModel.delete(this._debuggerId);Common.moduleSetting('pauseOnExceptionEnabled').removeChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('pauseOnCaughtException').removeChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('disableAsyncStackTraces').removeChangeListener(this._asyncStackTracesStateChanged,this);}
async suspendModel(){await this._disableDebugger();}
async resumeModel(){await this._enableDebugger();}
_internString(string){if(!this._stringMap.has(string))
this._stringMap.set(string,string);return this._stringMap.get(string);}};SDK.DebuggerModel._debuggerIdToModel=new Map();SDK.DebuggerModel._scheduledPauseOnAsyncCall=null;SDK.SDKModel.register(SDK.DebuggerModel,SDK.Target.Capability.JS,true);SDK.DebuggerModel.FunctionDetails;SDK.DebuggerModel.PauseOnExceptionsState={DontPauseOnExceptions:'none',PauseOnAllExceptions:'all',PauseOnUncaughtExceptions:'uncaught'};SDK.DebuggerModel.Events={DebuggerWasEnabled:Symbol('DebuggerWasEnabled'),DebuggerWasDisabled:Symbol('DebuggerWasDisabled'),DebuggerPaused:Symbol('DebuggerPaused'),DebuggerResumed:Symbol('DebuggerResumed'),ParsedScriptSource:Symbol('ParsedScriptSource'),FailedToParseScriptSource:Symbol('FailedToParseScriptSource'),DiscardedAnonymousScriptSource:Symbol('DiscardedAnonymousScriptSource'),GlobalObjectCleared:Symbol('GlobalObjectCleared'),CallFrameSelected:Symbol('CallFrameSelected'),ConsoleCommandEvaluatedInSelectedCallFrame:Symbol('ConsoleCommandEvaluatedInSelectedCallFrame'),DebuggerIsReadyToPause:Symbol('DebuggerIsReadyToPause'),};SDK.DebuggerModel.BreakReason={DOM:'DOM',EventListener:'EventListener',XHR:'XHR',Exception:'exception',PromiseRejection:'promiseRejection',Assert:'assert',DebugCommand:'debugCommand',OOM:'OOM',Other:'other'};SDK.DebuggerModel.BreakLocationType={Return:'return',Call:'call',DebuggerStatement:'debuggerStatement'};SDK.DebuggerEventTypes={JavaScriptPause:0,JavaScriptBreakpoint:1,NativeBreakpoint:2};SDK.DebuggerModel.ContinueToLocationTargetCallFrames={Any:'any',Current:'current'};SDK.DebuggerModel.SetBreakpointResult;SDK.DebuggerDispatcher=class{constructor(debuggerModel){this._debuggerModel=debuggerModel;}
paused(callFrames,reason,auxData,breakpointIds,asyncStackTrace,asyncStackTraceId,asyncCallStackTraceId){this._debuggerModel._pausedScript(callFrames,reason,auxData,breakpointIds||[],asyncStackTrace,asyncStackTraceId,asyncCallStackTraceId);}
resumed(){this._debuggerModel._resumedScript();}
scriptParsed(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,isLiveEdit,sourceMapURL,hasSourceURL,isModule,length,stackTrace){this._debuggerModel._parsedScriptSource(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,!!isLiveEdit,sourceMapURL,!!hasSourceURL,false,length||0,stackTrace||null);}
scriptFailedToParse(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,sourceMapURL,hasSourceURL,isModule,length,stackTrace){this._debuggerModel._parsedScriptSource(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,false,sourceMapURL,!!hasSourceURL,true,length||0,stackTrace||null);}
breakpointResolved(breakpointId,location){this._debuggerModel._breakpointResolved(breakpointId,location);}};SDK.DebuggerModel.Location=class{constructor(debuggerModel,scriptId,lineNumber,columnNumber){this.debuggerModel=debuggerModel;this.scriptId=scriptId;this.lineNumber=lineNumber;this.columnNumber=columnNumber||0;}
static fromPayload(debuggerModel,payload){return new SDK.DebuggerModel.Location(debuggerModel,payload.scriptId,payload.lineNumber,payload.columnNumber);}
payload(){return{scriptId:this.scriptId,lineNumber:this.lineNumber,columnNumber:this.columnNumber};}
script(){return this.debuggerModel.scriptForId(this.scriptId);}
continueToLocation(pausedCallback){if(pausedCallback)
this.debuggerModel._continueToLocationCallback=this._paused.bind(this,pausedCallback);this.debuggerModel._agent.continueToLocation(this.payload(),SDK.DebuggerModel.ContinueToLocationTargetCallFrames.Current);}
_paused(pausedCallback,debuggerPausedDetails){const location=debuggerPausedDetails.callFrames[0].location();if(location.scriptId===this.scriptId&&location.lineNumber===this.lineNumber&&location.columnNumber===this.columnNumber){pausedCallback();return true;}
return false;}
id(){return this.debuggerModel.target().id()+':'+this.scriptId+':'+this.lineNumber+':'+this.columnNumber;}};SDK.DebuggerModel.BreakLocation=class extends SDK.DebuggerModel.Location{constructor(debuggerModel,scriptId,lineNumber,columnNumber,type){super(debuggerModel,scriptId,lineNumber,columnNumber);if(type)
this.type=type;}
static fromPayload(debuggerModel,payload){return new SDK.DebuggerModel.BreakLocation(debuggerModel,payload.scriptId,payload.lineNumber,payload.columnNumber,payload.type);}};SDK.DebuggerModel.CallFrame=class{constructor(debuggerModel,script,payload){this.debuggerModel=debuggerModel;this._script=script;this._payload=payload;this._location=SDK.DebuggerModel.Location.fromPayload(debuggerModel,payload.location);this._scopeChain=[];this._localScope=null;for(let i=0;i<payload.scopeChain.length;++i){const scope=new SDK.DebuggerModel.Scope(this,i);this._scopeChain.push(scope);if(scope.type()===Protocol.Debugger.ScopeType.Local)
this._localScope=scope;}
if(payload.functionLocation)
this._functionLocation=SDK.DebuggerModel.Location.fromPayload(debuggerModel,payload.functionLocation);this._returnValue=payload.returnValue?this.debuggerModel._runtimeModel.createRemoteObject(payload.returnValue):null;}
static fromPayloadArray(debuggerModel,callFrames){const result=[];for(let i=0;i<callFrames.length;++i){const callFrame=callFrames[i];const script=debuggerModel.scriptForId(callFrame.location.scriptId);if(script)
result.push(new SDK.DebuggerModel.CallFrame(debuggerModel,script,callFrame));}
return result;}
get script(){return this._script;}
get id(){return this._payload.callFrameId;}
scopeChain(){return this._scopeChain;}
localScope(){return this._localScope;}
thisObject(){return this._payload.this?this.debuggerModel._runtimeModel.createRemoteObject(this._payload.this):null;}
returnValue(){return this._returnValue;}
async setReturnValue(expression){if(!this._returnValue)
return null;const evaluateResponse=await this.debuggerModel._agent.invoke_evaluateOnCallFrame({callFrameId:this.id,expression:expression,silent:true,objectGroup:'backtrace'});if(evaluateResponse[Protocol.Error]||evaluateResponse.exceptionDetails)
return null;const response=await this.debuggerModel._agent.invoke_setReturnValue({newValue:evaluateResponse.result});if(response[Protocol.Error])
return null;this._returnValue=this.debuggerModel._runtimeModel.createRemoteObject(evaluateResponse.result);return this._returnValue;}
get functionName(){return this._payload.functionName;}
location(){return this._location;}
functionLocation(){return this._functionLocation||null;}
async evaluate(options){const runtimeModel=this.debuggerModel.runtimeModel();const needsTerminationOptions=!!options.throwOnSideEffect||options.timeout!==undefined;if(needsTerminationOptions&&(runtimeModel.hasSideEffectSupport()===false||(runtimeModel.hasSideEffectSupport()===null&&!await runtimeModel.checkSideEffectSupport())))
return{error:'Side-effect checks not supported by backend.'};const response=await this.debuggerModel._agent.invoke_evaluateOnCallFrame({callFrameId:this.id,expression:options.expression,objectGroup:options.objectGroup,includeCommandLineAPI:options.includeCommandLineAPI,silent:options.silent,returnByValue:options.returnByValue,generatePreview:options.generatePreview,throwOnSideEffect:options.throwOnSideEffect,timeout:options.timeout});const error=response[Protocol.Error];if(error){console.error(error);return{error:error};}
return{object:runtimeModel.createRemoteObject(response.result),exceptionDetails:response.exceptionDetails};}
async restart(){const response=await this.debuggerModel._agent.invoke_restartFrame({callFrameId:this._payload.callFrameId});if(!response[Protocol.Error])
this.debuggerModel.stepInto();}};SDK.DebuggerModel.Scope=class{constructor(callFrame,ordinal){this._callFrame=callFrame;this._payload=callFrame._payload.scopeChain[ordinal];this._type=this._payload.type;this._name=this._payload.name;this._ordinal=ordinal;this._startLocation=this._payload.startLocation?SDK.DebuggerModel.Location.fromPayload(callFrame.debuggerModel,this._payload.startLocation):null;this._endLocation=this._payload.endLocation?SDK.DebuggerModel.Location.fromPayload(callFrame.debuggerModel,this._payload.endLocation):null;}
callFrame(){return this._callFrame;}
type(){return this._type;}
typeName(){switch(this._type){case Protocol.Debugger.ScopeType.Local:return Common.UIString('Local');case Protocol.Debugger.ScopeType.Closure:return Common.UIString('Closure');case Protocol.Debugger.ScopeType.Catch:return Common.UIString('Catch');case Protocol.Debugger.ScopeType.Block:return Common.UIString('Block');case Protocol.Debugger.ScopeType.Script:return Common.UIString('Script');case Protocol.Debugger.ScopeType.With:return Common.UIString('With Block');case Protocol.Debugger.ScopeType.Global:return Common.UIString('Global');case Protocol.Debugger.ScopeType.Module:return Common.UIString('Module');}
return'';}
name(){return this._name;}
startLocation(){return this._startLocation;}
endLocation(){return this._endLocation;}
object(){if(this._object)
return this._object;const runtimeModel=this._callFrame.debuggerModel._runtimeModel;const declarativeScope=this._type!==Protocol.Debugger.ScopeType.With&&this._type!==Protocol.Debugger.ScopeType.Global;if(declarativeScope){this._object=runtimeModel.createScopeRemoteObject(this._payload.object,new SDK.ScopeRef(this._ordinal,this._callFrame.id));}else{this._object=runtimeModel.createRemoteObject(this._payload.object);}
return this._object;}
description(){const declarativeScope=this._type!==Protocol.Debugger.ScopeType.With&&this._type!==Protocol.Debugger.ScopeType.Global;return declarativeScope?'':(this._payload.object.description||'');}};SDK.DebuggerPausedDetails=class{constructor(debuggerModel,callFrames,reason,auxData,breakpointIds,asyncStackTrace,asyncStackTraceId){this.debuggerModel=debuggerModel;this.callFrames=SDK.DebuggerModel.CallFrame.fromPayloadArray(debuggerModel,callFrames);this.reason=reason;this.auxData=auxData;this.breakpointIds=breakpointIds;if(asyncStackTrace)
this.asyncStackTrace=this._cleanRedundantFrames(asyncStackTrace);this.asyncStackTraceId=asyncStackTraceId;}
exception(){if(this.reason!==SDK.DebuggerModel.BreakReason.Exception&&this.reason!==SDK.DebuggerModel.BreakReason.PromiseRejection)
return null;return this.debuggerModel._runtimeModel.createRemoteObject((this.auxData));}
_cleanRedundantFrames(asyncStackTrace){let stack=asyncStackTrace;let previous=null;while(stack){if(stack.description==='async function'&&stack.callFrames.length)
stack.callFrames.shift();if(previous&&!stack.callFrames.length)
previous.parent=stack.parent;else
previous=stack;stack=stack.parent;}
return asyncStackTrace;}};;SDK.EmulationModel=class extends SDK.SDKModel{constructor(target){super(target);this._emulationAgent=target.emulationAgent();this._pageAgent=target.pageAgent();this._deviceOrientationAgent=target.deviceOrientationAgent();this._cssModel=target.model(SDK.CSSModel);this._overlayModel=target.model(SDK.OverlayModel);if(this._overlayModel)
this._overlayModel.addEventListener(SDK.OverlayModel.Events.InspectModeWillBeToggled,this._updateTouch,this);const disableJavascriptSetting=Common.settings.moduleSetting('javaScriptDisabled');disableJavascriptSetting.addChangeListener(()=>this._emulationAgent.setScriptExecutionDisabled(disableJavascriptSetting.get()));if(disableJavascriptSetting.get())
this._emulationAgent.setScriptExecutionDisabled(true);const mediaSetting=Common.moduleSetting('emulatedCSSMedia');mediaSetting.addChangeListener(()=>this._emulateCSSMedia(mediaSetting.get()));if(mediaSetting.get())
this._emulateCSSMedia(mediaSetting.get());this._touchEnabled=false;this._touchMobile=false;this._customTouchEnabled=false;this._touchConfiguration={enabled:false,configuration:'mobile',scriptId:''};}
supportsDeviceEmulation(){return this.target().hasAllCapabilities(SDK.Target.Capability.DeviceEmulation);}
resetPageScaleFactor(){return this._emulationAgent.resetPageScaleFactor();}
emulateDevice(metrics){if(metrics)
return this._emulationAgent.invoke_setDeviceMetricsOverride(metrics);else
return this._emulationAgent.clearDeviceMetricsOverride();}
overlayModel(){return this._overlayModel;}
emulateGeolocation(geolocation){if(!geolocation){this._emulationAgent.clearGeolocationOverride();return;}
if(geolocation.error){this._emulationAgent.setGeolocationOverride();}else{this._emulationAgent.setGeolocationOverride(geolocation.latitude,geolocation.longitude,SDK.EmulationModel.Geolocation.DefaultMockAccuracy);}}
emulateDeviceOrientation(deviceOrientation){if(deviceOrientation){this._deviceOrientationAgent.setDeviceOrientationOverride(deviceOrientation.alpha,deviceOrientation.beta,deviceOrientation.gamma);}else{this._deviceOrientationAgent.clearDeviceOrientationOverride();}}
_emulateCSSMedia(media){this._emulationAgent.setEmulatedMedia(media);if(this._cssModel)
this._cssModel.mediaQueryResultChanged();}
setCPUThrottlingRate(rate){this._emulationAgent.setCPUThrottlingRate(rate);}
emulateTouch(enabled,mobile){this._touchEnabled=enabled;this._touchMobile=mobile;this._updateTouch();}
overrideEmulateTouch(enabled){this._customTouchEnabled=enabled;this._updateTouch();}
_updateTouch(){let configuration={enabled:this._touchEnabled,configuration:this._touchMobile?'mobile':'desktop',};if(this._customTouchEnabled)
configuration={enabled:true,configuration:'mobile'};if(this._overlayModel&&this._overlayModel.inspectModeEnabled())
configuration={enabled:false,configuration:'mobile'};if(!this._touchConfiguration.enabled&&!configuration.enabled)
return;if(this._touchConfiguration.enabled&&configuration.enabled&&this._touchConfiguration.configuration===configuration.configuration)
return;this._touchConfiguration=configuration;this._emulationAgent.setTouchEmulationEnabled(configuration.enabled,1);this._emulationAgent.setEmitTouchEventsForMouse(configuration.enabled,configuration.configuration);}};SDK.SDKModel.register(SDK.EmulationModel,SDK.Target.Capability.Emulation,true);SDK.EmulationModel.Geolocation=class{constructor(latitude,longitude,error){this.latitude=latitude;this.longitude=longitude;this.error=error;}
static parseSetting(value){if(value){const splitError=value.split(':');if(splitError.length===2){const splitPosition=splitError[0].split('@');if(splitPosition.length===2){return new SDK.EmulationModel.Geolocation(parseFloat(splitPosition[0]),parseFloat(splitPosition[1]),!!splitError[1]);}}}
return new SDK.EmulationModel.Geolocation(0,0,false);}
static parseUserInput(latitudeString,longitudeString,errorStatus){if(!latitudeString&&!longitudeString)
return null;const isLatitudeValid=SDK.EmulationModel.Geolocation.latitudeValidator(latitudeString);const isLongitudeValid=SDK.EmulationModel.Geolocation.longitudeValidator(longitudeString);if(!isLatitudeValid&&!isLongitudeValid)
return null;const latitude=isLatitudeValid?parseFloat(latitudeString):-1;const longitude=isLongitudeValid?parseFloat(longitudeString):-1;return new SDK.EmulationModel.Geolocation(latitude,longitude,!!errorStatus);}
static latitudeValidator(value){const numValue=parseFloat(value);return/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(value)&&numValue>=-90&&numValue<=90;}
static longitudeValidator(value){const numValue=parseFloat(value);return/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(value)&&numValue>=-180&&numValue<=180;}
toSetting(){return this.latitude+'@'+this.longitude+':'+(this.error||'');}};SDK.EmulationModel.Geolocation.DefaultMockAccuracy=150;SDK.EmulationModel.DeviceOrientation=class{constructor(alpha,beta,gamma){this.alpha=alpha;this.beta=beta;this.gamma=gamma;}
static parseSetting(value){if(value){const jsonObject=JSON.parse(value);return new SDK.EmulationModel.DeviceOrientation(jsonObject.alpha,jsonObject.beta,jsonObject.gamma);}
return new SDK.EmulationModel.DeviceOrientation(0,0,0);}
static parseUserInput(alphaString,betaString,gammaString){if(!alphaString&&!betaString&&!gammaString)
return null;const isAlphaValid=SDK.EmulationModel.DeviceOrientation.validator(alphaString);const isBetaValid=SDK.EmulationModel.DeviceOrientation.validator(betaString);const isGammaValid=SDK.EmulationModel.DeviceOrientation.validator(gammaString);if(!isAlphaValid&&!isBetaValid&&!isGammaValid)
return null;const alpha=isAlphaValid?parseFloat(alphaString):-1;const beta=isBetaValid?parseFloat(betaString):-1;const gamma=isGammaValid?parseFloat(gammaString):-1;return new SDK.EmulationModel.DeviceOrientation(alpha,beta,gamma);}
static validator(value){return/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(value);}
toSetting(){return JSON.stringify(this);}};;SDK.HARLog=class{static pseudoWallTime(request,monotonicTime){return new Date(request.pseudoWallTime(monotonicTime)*1000);}
static async build(requests){const log=new SDK.HARLog();const entryPromises=[];for(const request of requests)
entryPromises.push(SDK.HARLog.Entry.build(request));const entries=await Promise.all(entryPromises);return{version:'1.2',creator:log._creator(),pages:log._buildPages(requests),entries:entries};}
_creator(){const webKitVersion=/AppleWebKit\/([^ ]+)/.exec(window.navigator.userAgent);return{name:'WebInspector',version:webKitVersion?webKitVersion[1]:'n/a'};}
_buildPages(requests){const seenIdentifiers={};const pages=[];for(let i=0;i<requests.length;++i){const request=requests[i];const page=SDK.NetworkLog.PageLoad.forRequest(request);if(!page||seenIdentifiers[page.id])
continue;seenIdentifiers[page.id]=true;pages.push(this._convertPage(page,request));}
return pages;}
_convertPage(page,request){return{startedDateTime:SDK.HARLog.pseudoWallTime(request,page.startTime).toJSON(),id:'page_'+page.id,title:page.url,pageTimings:{onContentLoad:this._pageEventTime(page,page.contentLoadTime),onLoad:this._pageEventTime(page,page.loadTime)}};}
_pageEventTime(page,time){const startTime=page.startTime;if(time===-1||startTime===-1)
return-1;return SDK.HARLog.Entry._toMilliseconds(time-startTime);}};SDK.HARLog.Entry=class{constructor(request){this._request=request;}
static _toMilliseconds(time){return time===-1?-1:time*1000;}
static async build(request){const harEntry=new SDK.HARLog.Entry(request);let ipAddress=harEntry._request.remoteAddress();const portPositionInString=ipAddress.lastIndexOf(':');if(portPositionInString!==-1)
ipAddress=ipAddress.substr(0,portPositionInString);const timings=harEntry._buildTimings();let time=0;for(const t of[timings.blocked,timings.dns,timings.connect,timings.send,timings.wait,timings.receive])
time+=Math.max(t,0);const initiator=harEntry._request.initiator();const exportedInitiator={};exportedInitiator.type=initiator.type;if(initiator.url!==undefined)
exportedInitiator.url=initiator.url;if(initiator.lineNumber!==undefined)
exportedInitiator.lineNumber=initiator.lineNumber;if(initiator.stack)
exportedInitiator.stack=initiator.stack;const entry={startedDateTime:SDK.HARLog.pseudoWallTime(harEntry._request,harEntry._request.issueTime()).toJSON(),time:time,request:await harEntry._buildRequest(),response:harEntry._buildResponse(),cache:{},timings:timings,serverIPAddress:ipAddress.replace(/\[\]/g,''),_initiator:exportedInitiator,_priority:harEntry._request.priority(),_resourceType:harEntry._request.resourceType().name()};if(harEntry._request.cached())
entry._fromCache=harEntry._request.cachedInMemory()?'memory':'disk';if(harEntry._request.connectionId!=='0')
entry.connection=harEntry._request.connectionId;const page=SDK.NetworkLog.PageLoad.forRequest(harEntry._request);if(page)
entry.pageref='page_'+page.id;if(harEntry._request.resourceType()===Common.resourceTypes.WebSocket){const messages=[];for(const message of harEntry._request.frames())
messages.push({type:message.type,time:message.time,opcode:message.opCode,data:message.text});entry._webSocketMessages=messages;}
return entry;}
async _buildRequest(){const headersText=this._request.requestHeadersText();const res={method:this._request.requestMethod,url:this._buildRequestURL(this._request.url()),httpVersion:this._request.requestHttpVersion(),headers:this._request.requestHeaders(),queryString:this._buildParameters(this._request.queryParameters||[]),cookies:this._buildCookies(this._request.requestCookies||[]),headersSize:headersText?headersText.length:-1,bodySize:await this._requestBodySize()};const postData=await this._buildPostData();if(postData)
res.postData=postData;return res;}
_buildResponse(){const headersText=this._request.responseHeadersText;return{status:this._request.statusCode,statusText:this._request.statusText,httpVersion:this._request.responseHttpVersion(),headers:this._request.responseHeaders,cookies:this._buildCookies(this._request.responseCookies||[]),content:this._buildContent(),redirectURL:this._request.responseHeaderValue('Location')||'',headersSize:headersText?headersText.length:-1,bodySize:this.responseBodySize,_transferSize:this._request.transferSize,_error:this._request.localizedFailDescription};}
_buildContent(){const content={size:this._request.resourceSize,mimeType:this._request.mimeType||'x-unknown',};const compression=this.responseCompression;if(typeof compression==='number')
content.compression=compression;return content;}
_buildTimings(){const timing=this._request.timing;const issueTime=this._request.issueTime();const startTime=this._request.startTime;const result={blocked:-1,dns:-1,ssl:-1,connect:-1,send:0,wait:0,receive:0,_blocked_queueing:-1};const queuedTime=(issueTime<startTime)?startTime-issueTime:-1;result.blocked=SDK.HARLog.Entry._toMilliseconds(queuedTime);result._blocked_queueing=SDK.HARLog.Entry._toMilliseconds(queuedTime);let highestTime=0;if(timing){const blockedStart=leastNonNegative([timing.dnsStart,timing.connectStart,timing.sendStart]);if(blockedStart!==Infinity)
result.blocked+=blockedStart;if(timing.proxyEnd!==-1)
result._blocked_proxy=timing.proxyEnd-timing.proxyStart;if(result._blocked_proxy&&result._blocked_proxy>result.blocked)
result.blocked=result._blocked_proxy;const dnsStart=timing.dnsEnd>=0?blockedStart:0;const dnsEnd=timing.dnsEnd>=0?timing.dnsEnd:-1;result.dns=dnsEnd-dnsStart;const sslStart=timing.sslEnd>0?timing.sslStart:0;const sslEnd=timing.sslEnd>0?timing.sslEnd:-1;result.ssl=sslEnd-sslStart;const connectStart=timing.connectEnd>=0?leastNonNegative([dnsEnd,blockedStart]):0;const connectEnd=timing.connectEnd>=0?timing.connectEnd:-1;result.connect=connectEnd-connectStart;const sendStart=timing.sendEnd>=0?Math.max(connectEnd,dnsEnd,blockedStart):0;const sendEnd=timing.sendEnd>=0?timing.sendEnd:0;result.send=sendEnd-sendStart;if(result.send<0)
result.send=0;highestTime=Math.max(sendEnd,connectEnd,sslEnd,dnsEnd,blockedStart,0);}else if(this._request.responseReceivedTime===-1){result.blocked=this._request.endTime-issueTime;return result;}
const requestTime=timing?timing.requestTime:startTime;const waitStart=highestTime;const waitEnd=SDK.HARLog.Entry._toMilliseconds(this._request.responseReceivedTime-requestTime);result.wait=waitEnd-waitStart;const receiveStart=waitEnd;const receiveEnd=SDK.HARLog.Entry._toMilliseconds(this._request.endTime-requestTime);result.receive=Math.max(receiveEnd-receiveStart,0);return result;function leastNonNegative(values){return values.reduce((best,value)=>(value>=0&&value<best)?value:best,Infinity);}}
async _buildPostData(){const postData=await this._request.requestFormData();if(!postData)
return null;const res={mimeType:this._request.requestContentType()||'',text:postData};const formParameters=await this._request.formParameters();if(formParameters)
res.params=this._buildParameters(formParameters);return res;}
_buildParameters(parameters){return parameters.slice();}
_buildRequestURL(url){return url.split('#',2)[0];}
_buildCookies(cookies){return cookies.map(this._buildCookie.bind(this));}
_buildCookie(cookie){const c={name:cookie.name(),value:cookie.value(),path:cookie.path(),domain:cookie.domain(),expires:cookie.expiresDate(SDK.HARLog.pseudoWallTime(this._request,this._request.startTime)),httpOnly:cookie.httpOnly(),secure:cookie.secure()};if(cookie.sameSite())
c.sameSite=cookie.sameSite();return c;}
async _requestBodySize(){const postData=await this._request.requestFormData();if(!postData)
return 0;return new TextEncoder('utf-8').encode(postData).length;}
get responseBodySize(){if(this._request.cached()||this._request.statusCode===304)
return 0;if(!this._request.responseHeadersText)
return-1;return this._request.transferSize-this._request.responseHeadersText.length;}
get responseCompression(){if(this._request.cached()||this._request.statusCode===304||this._request.statusCode===206)
return;if(!this._request.responseHeadersText)
return;return this._request.resourceSize-this.responseBodySize;}};SDK.HARLog.Entry.Timing;;SDK.SnapshotWithRect;SDK.Layer=function(){};SDK.Layer.prototype={id(){},parentId(){},parent(){},isRoot(){},children(){},addChild(child){},node(){},nodeForSelfOrAncestor(){},offsetX(){},offsetY(){},width(){},height(){},transform(){},quad(){},anchorPoint(){},invisible(){},paintCount(){},lastPaintRect(){},scrollRects(){},stickyPositionConstraint(){},gpuMemoryUsage(){},requestCompositingReasons(){},drawsContent(){},snapshots(){}};SDK.Layer.ScrollRectType={NonFastScrollable:'NonFastScrollable',TouchEventHandler:'TouchEventHandler',WheelEventHandler:'WheelEventHandler',RepaintsOnScroll:'RepaintsOnScroll'};SDK.Layer.StickyPositionConstraint=class{constructor(layerTree,constraint){this._stickyBoxRect=constraint.stickyBoxRect;this._containingBlockRect=constraint.containingBlockRect;this._nearestLayerShiftingStickyBox=null;if(layerTree&&constraint.nearestLayerShiftingStickyBox)
this._nearestLayerShiftingStickyBox=layerTree.layerById(constraint.nearestLayerShiftingStickyBox);this._nearestLayerShiftingContainingBlock=null;if(layerTree&&constraint.nearestLayerShiftingContainingBlock)
this._nearestLayerShiftingContainingBlock=layerTree.layerById(constraint.nearestLayerShiftingContainingBlock);}
stickyBoxRect(){return this._stickyBoxRect;}
containingBlockRect(){return this._containingBlockRect;}
nearestLayerShiftingStickyBox(){return this._nearestLayerShiftingStickyBox;}
nearestLayerShiftingContainingBlock(){return this._nearestLayerShiftingContainingBlock;}};SDK.LayerTreeBase=class{constructor(target){this._target=target;this._domModel=target?target.model(SDK.DOMModel):null;this._layersById={};this._root=null;this._contentRoot=null;this._backendNodeIdToNode=new Map();}
target(){return this._target;}
root(){return this._root;}
setRoot(root){this._root=root;}
contentRoot(){return this._contentRoot;}
setContentRoot(contentRoot){this._contentRoot=contentRoot;}
forEachLayer(callback,root){if(!root){root=this.root();if(!root)
return false;}
return callback(root)||root.children().some(this.forEachLayer.bind(this,callback));}
layerById(id){return this._layersById[id]||null;}
async resolveBackendNodeIds(requestedNodeIds){if(!requestedNodeIds.size||!this._domModel)
return;const nodesMap=await this._domModel.pushNodesByBackendIdsToFrontend(requestedNodeIds);if(!nodesMap)
return;for(const nodeId of nodesMap.keysArray())
this._backendNodeIdToNode.set(nodeId,nodesMap.get(nodeId)||null);}
backendNodeIdToNode(){return this._backendNodeIdToNode;}
setViewportSize(viewportSize){this._viewportSize=viewportSize;}
viewportSize(){return this._viewportSize;}
_nodeForId(id){return this._domModel?this._domModel.nodeForId(id):null;}};;SDK.LogModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerLogDispatcher(this);this._logAgent=target.logAgent();this._logAgent.enable();if(!Host.isUnderTest()){this._logAgent.startViolationsReport([{name:'longTask',threshold:200},{name:'longLayout',threshold:30},{name:'blockedEvent',threshold:100},{name:'blockedParser',threshold:-1},{name:'handler',threshold:150},{name:'recurringHandler',threshold:50},{name:'discouragedAPIUse',threshold:-1}]);}}
entryAdded(payload){this.dispatchEventToListeners(SDK.LogModel.Events.EntryAdded,{logModel:this,entry:payload});}
requestClear(){this._logAgent.clear();}};SDK.SDKModel.register(SDK.LogModel,SDK.Target.Capability.Log,true);SDK.LogModel.Events={EntryAdded:Symbol('EntryAdded')};;SDK.ServiceWorkerManager=class extends SDK.SDKModel{constructor(target){super(target);target.registerServiceWorkerDispatcher(new SDK.ServiceWorkerDispatcher(this));this._lastAnonymousTargetId=0;this._agent=target.serviceWorkerAgent();this._registrations=new Map();this.enable();this._forceUpdateSetting=Common.settings.createSetting('serviceWorkerUpdateOnReload',false);if(this._forceUpdateSetting.get())
this._forceUpdateSettingChanged();this._forceUpdateSetting.addChangeListener(this._forceUpdateSettingChanged,this);new SDK.ServiceWorkerContextNamer(target,this);}
enable(){if(this._enabled)
return;this._enabled=true;this._agent.enable();}
disable(){if(!this._enabled)
return;this._enabled=false;this._registrations.clear();this._agent.disable();}
registrations(){return this._registrations;}
hasRegistrationForURLs(urls){for(const registration of this._registrations.values()){if(urls.filter(url=>url&&url.startsWith(registration.scopeURL)).length===urls.length)
return true;}
return false;}
findVersion(versionId){for(const registration of this.registrations().values()){const version=registration.versions.get(versionId);if(version)
return version;}
return null;}
deleteRegistration(registrationId){const registration=this._registrations.get(registrationId);if(!registration)
return;if(registration._isRedundant()){this._registrations.delete(registrationId);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted,registration);return;}
registration._deleting=true;for(const version of registration.versions.values())
this.stopWorker(version.id);this._unregister(registration.scopeURL);}
updateRegistration(registrationId){const registration=this._registrations.get(registrationId);if(!registration)
return;this._agent.updateRegistration(registration.scopeURL);}
deliverPushMessage(registrationId,data){const registration=this._registrations.get(registrationId);if(!registration)
return;const origin=Common.ParsedURL.extractOrigin(registration.scopeURL);this._agent.deliverPushMessage(origin,registrationId,data);}
dispatchSyncEvent(registrationId,tag,lastChance){const registration=this._registrations.get(registrationId);if(!registration)
return;const origin=Common.ParsedURL.extractOrigin(registration.scopeURL);this._agent.dispatchSyncEvent(origin,registrationId,tag,lastChance);}
_unregister(scope){this._agent.unregister(scope);}
startWorker(scope){this._agent.startWorker(scope);}
skipWaiting(scope){this._agent.skipWaiting(scope);}
stopWorker(versionId){this._agent.stopWorker(versionId);}
inspectWorker(versionId){this._agent.inspectWorker(versionId);}
_workerRegistrationUpdated(registrations){for(const payload of registrations){let registration=this._registrations.get(payload.registrationId);if(!registration){registration=new SDK.ServiceWorkerRegistration(payload);this._registrations.set(payload.registrationId,registration);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationUpdated,registration);continue;}
registration._update(payload);if(registration._shouldBeRemoved()){this._registrations.delete(registration.id);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted,registration);}else{this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationUpdated,registration);}}}
_workerVersionUpdated(versions){const registrations=new Set();for(const payload of versions){const registration=this._registrations.get(payload.registrationId);if(!registration)
continue;registration._updateVersion(payload);registrations.add(registration);}
for(const registration of registrations){if(registration._shouldBeRemoved()){this._registrations.delete(registration.id);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted,registration);}else{this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationUpdated,registration);}}}
_workerErrorReported(payload){const registration=this._registrations.get(payload.registrationId);if(!registration)
return;registration.errors.push(payload);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationErrorAdded,{registration:registration,error:payload});}
forceUpdateOnReloadSetting(){return this._forceUpdateSetting;}
_forceUpdateSettingChanged(){this._agent.setForceUpdateOnPageLoad(this._forceUpdateSetting.get());}};SDK.SDKModel.register(SDK.ServiceWorkerManager,SDK.Target.Capability.Target|SDK.Target.Capability.Browser,true);SDK.ServiceWorkerManager.Events={RegistrationUpdated:Symbol('RegistrationUpdated'),RegistrationErrorAdded:Symbol('RegistrationErrorAdded'),RegistrationDeleted:Symbol('RegistrationDeleted')};SDK.ServiceWorkerDispatcher=class{constructor(manager){this._manager=manager;}
workerRegistrationUpdated(registrations){this._manager._workerRegistrationUpdated(registrations);}
workerVersionUpdated(versions){this._manager._workerVersionUpdated(versions);}
workerErrorReported(errorMessage){this._manager._workerErrorReported(errorMessage);}};SDK.ServiceWorkerVersion=class{constructor(registration,payload){this.registration=registration;this._update(payload);}
_update(payload){this.id=payload.versionId;this.scriptURL=payload.scriptURL;const parsedURL=new Common.ParsedURL(payload.scriptURL);this.securityOrigin=parsedURL.securityOrigin();this.runningStatus=payload.runningStatus;this.status=payload.status;this.scriptLastModified=payload.scriptLastModified;this.scriptResponseTime=payload.scriptResponseTime;this.controlledClients=[];for(let i=0;i<payload.controlledClients.length;++i)
this.controlledClients.push(payload.controlledClients[i]);this.targetId=payload.targetId||null;}
isStartable(){return!this.registration.isDeleted&&this.isActivated()&&this.isStopped();}
isStoppedAndRedundant(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Stopped&&this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Redundant;}
isStopped(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Stopped;}
isStarting(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Starting;}
isRunning(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Running;}
isStopping(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Stopping;}
isNew(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.New;}
isInstalling(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Installing;}
isInstalled(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Installed;}
isActivating(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activating;}
isActivated(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activated;}
isRedundant(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Redundant;}
mode(){if(this.isNew()||this.isInstalling())
return SDK.ServiceWorkerVersion.Modes.Installing;else if(this.isInstalled())
return SDK.ServiceWorkerVersion.Modes.Waiting;else if(this.isActivating()||this.isActivated())
return SDK.ServiceWorkerVersion.Modes.Active;return SDK.ServiceWorkerVersion.Modes.Redundant;}};SDK.ServiceWorkerVersion.Modes={Installing:'installing',Waiting:'waiting',Active:'active',Redundant:'redundant'};SDK.ServiceWorkerRegistration=class{constructor(payload){this._update(payload);this.versions=new Map();this._deleting=false;this.errors=[];}
_update(payload){this._fingerprint=Symbol('fingerprint');this.id=payload.registrationId;this.scopeURL=payload.scopeURL;const parsedURL=new Common.ParsedURL(payload.scopeURL);this.securityOrigin=parsedURL.securityOrigin();this.isDeleted=payload.isDeleted;this.forceUpdateOnPageLoad=payload.forceUpdateOnPageLoad;}
fingerprint(){return this._fingerprint;}
versionsByMode(){const result=new Map();for(const version of this.versions.values())
result.set(version.mode(),version);return result;}
_updateVersion(payload){this._fingerprint=Symbol('fingerprint');let version=this.versions.get(payload.versionId);if(!version){version=new SDK.ServiceWorkerVersion(this,payload);this.versions.set(payload.versionId,version);return version;}
version._update(payload);return version;}
_isRedundant(){for(const version of this.versions.values()){if(!version.isStoppedAndRedundant())
return false;}
return true;}
_shouldBeRemoved(){return this._isRedundant()&&(!this.errors.length||this._deleting);}
canBeRemoved(){return this.isDeleted||this._deleting;}
clearErrors(){this._fingerprint=Symbol('fingerprint');this.errors=[];}};SDK.ServiceWorkerContextNamer=class{constructor(target,serviceWorkerManager){this._target=target;this._serviceWorkerManager=serviceWorkerManager;this._versionByTargetId=new Map();serviceWorkerManager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationUpdated,this._registrationsUpdated,this);serviceWorkerManager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationDeleted,this._registrationsUpdated,this);SDK.targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextCreated,this._executionContextCreated,this);}
_registrationsUpdated(event){this._versionByTargetId.clear();const registrations=this._serviceWorkerManager.registrations().valuesArray();for(const registration of registrations){const versions=registration.versions.valuesArray();for(const version of versions){if(version.targetId)
this._versionByTargetId.set(version.targetId,version);}}
this._updateAllContextLabels();}
_executionContextCreated(event){const executionContext=(event.data);const serviceWorkerTargetId=this._serviceWorkerTargetIdForWorker(executionContext.target());if(!serviceWorkerTargetId)
return;this._updateContextLabel(executionContext,this._versionByTargetId.get(serviceWorkerTargetId)||null);}
_serviceWorkerTargetIdForWorker(target){const parent=target.parentTarget();if(!parent||parent.parentTarget()!==this._target)
return null;return parent.type()===SDK.Target.Type.ServiceWorker?parent.id():null;}
_updateAllContextLabels(){for(const target of SDK.targetManager.targets()){const serviceWorkerTargetId=this._serviceWorkerTargetIdForWorker(target);if(!serviceWorkerTargetId)
continue;const version=this._versionByTargetId.get(serviceWorkerTargetId)||null;const runtimeModel=target.model(SDK.RuntimeModel);const executionContexts=runtimeModel?runtimeModel.executionContexts():[];for(const context of executionContexts)
this._updateContextLabel(context,version);}}
_updateContextLabel(context,version){if(!version){context.setLabel('');return;}
const parsedUrl=context.origin.asParsedURL();const label=parsedUrl?parsedUrl.lastPathComponentWithFragment():context.name;context.setLabel(label+' #'+version.id+' ('+version.status+')');}};;SDK.TracingManagerClient=function(){};SDK.TracingManagerClient.prototype={traceEventsCollected(events){},tracingComplete(){},tracingBufferUsage(usage){},eventsRetrievalProgress(progress){}};SDK.TracingManager=class extends SDK.SDKModel{constructor(target){super(target);this._tracingAgent=target.tracingAgent();target.registerTracingDispatcher(new SDK.TracingDispatcher(this));this._activeClient=null;this._eventBufferSize=0;this._eventsRetrieved=0;}
_bufferUsage(usage,eventCount,percentFull){this._eventBufferSize=eventCount;this._activeClient.tracingBufferUsage(usage||percentFull||0);}
_eventsCollected(events){this._activeClient.traceEventsCollected(events);this._eventsRetrieved+=events.length;if(!this._eventBufferSize){this._activeClient.eventsRetrievalProgress(0);return;}
if(this._eventsRetrieved>this._eventBufferSize)
this._eventsRetrieved=this._eventBufferSize;this._activeClient.eventsRetrievalProgress(this._eventsRetrieved/this._eventBufferSize);}
_tracingComplete(){this._eventBufferSize=0;this._eventsRetrieved=0;this._activeClient.tracingComplete();this._activeClient=null;this._finishing=false;}
start(client,categoryFilter,options){if(this._activeClient)
throw new Error('Tracing is already started');const bufferUsageReportingIntervalMs=500;this._activeClient=client;return this._tracingAgent.start(categoryFilter,options,bufferUsageReportingIntervalMs,SDK.TracingManager.TransferMode.ReportEvents);}
stop(){if(!this._activeClient)
throw new Error('Tracing is not started');if(this._finishing)
throw new Error('Tracing is already being stopped');this._finishing=true;this._tracingAgent.end();}};SDK.SDKModel.register(SDK.TracingManager,SDK.Target.Capability.Tracing,false);SDK.TracingManager.EventPayload;SDK.TracingManager.TransferMode={ReportEvents:'ReportEvents',ReturnAsStream:'ReturnAsStream'};SDK.TracingDispatcher=class{constructor(tracingManager){this._tracingManager=tracingManager;}
bufferUsage(usage,eventCount,percentFull){this._tracingManager._bufferUsage(usage,eventCount,percentFull);}
dataCollected(data){this._tracingManager._eventsCollected(data);}
tracingComplete(){this._tracingManager._tracingComplete();}};;SDK.TracingModel=class{constructor(backingStorage){this._backingStorage=backingStorage;this._firstWritePending=true;this._processById=new Map();this._processByName=new Map();this._minimumRecordTime=0;this._maximumRecordTime=0;this._devToolsMetadataEvents=[];this._asyncEvents=[];this._openAsyncEvents=new Map();this._openNestableAsyncEvents=new Map();this._profileGroups=new Map();this._parsedCategories=new Map();}
static isNestableAsyncPhase(phase){return phase==='b'||phase==='e'||phase==='n';}
static isAsyncBeginPhase(phase){return phase==='S'||phase==='b';}
static isAsyncPhase(phase){return SDK.TracingModel.isNestableAsyncPhase(phase)||phase==='S'||phase==='T'||phase==='F'||phase==='p';}
static isFlowPhase(phase){return phase==='s'||phase==='t'||phase==='f';}
static isTopLevelEvent(event){return event.hasCategory(SDK.TracingModel.DevToolsTimelineEventCategory)&&event.name==='RunTask'||event.hasCategory(SDK.TracingModel.LegacyTopLevelEventCategory)||event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory)&&event.name==='Program';}
static _extractId(payload){const scope=payload.scope||'';if(typeof payload.id2==='undefined')
return scope&&payload.id?`${scope}@${payload.id}`:payload.id;const id2=payload.id2;if(typeof id2==='object'&&('global'in id2)!==('local'in id2)){return typeof id2['global']!=='undefined'?`:${scope}:${id2['global']}`:`:${scope}:${payload.pid}:${id2['local']}`;}
console.error(`Unexpected id2 field at ${payload.ts / 1000}, one and only one of 'local' and 'global' should be present.`);}
static browserMainThread(tracingModel){const processes=tracingModel.sortedProcesses();if(!processes.length)
return null;const browserMainThreadName='CrBrowserMain';const browserProcesses=[];const browserMainThreads=[];for(const process of processes){if(process.name().toLowerCase().endsWith('browser'))
browserProcesses.push(process);browserMainThreads.push(...process.sortedThreads().filter(t=>t.name()===browserMainThreadName));}
if(browserMainThreads.length===1)
return browserMainThreads[0];if(browserProcesses.length===1)
return browserProcesses[0].threadByName(browserMainThreadName);const tracingStartedInBrowser=tracingModel.devToolsMetadataEvents().filter(e=>e.name==='TracingStartedInBrowser');if(tracingStartedInBrowser.length===1)
return tracingStartedInBrowser[0].thread;Common.console.error('Failed to find browser main thread in trace, some timeline features may be unavailable');return null;}
devToolsMetadataEvents(){return this._devToolsMetadataEvents;}
addEvents(events){for(let i=0;i<events.length;++i)
this._addEvent(events[i]);}
tracingComplete(){this._processPendingAsyncEvents();this._backingStorage.appendString(this._firstWritePending?'[]':']');this._backingStorage.finishWriting();this._firstWritePending=false;for(const process of this._processById.values()){for(const thread of process._threads.values())
thread.tracingComplete();}}
dispose(){if(!this._firstWritePending)
this._backingStorage.reset();}
adjustTime(offset){this._minimumRecordTime+=offset;this._maximumRecordTime+=offset;for(const process of this._processById.values()){for(const thread of process._threads.values()){for(const event of thread.events()){event.startTime+=offset;if(typeof event.endTime==='number')
event.endTime+=offset;}
for(const event of thread.asyncEvents()){event.startTime+=offset;if(typeof event.endTime==='number')
event.endTime+=offset;}}}}
_addEvent(payload){let process=this._processById.get(payload.pid);if(!process){process=new SDK.TracingModel.Process(this,payload.pid);this._processById.set(payload.pid,process);}
const phase=SDK.TracingModel.Phase;const eventsDelimiter=',\n';this._backingStorage.appendString(this._firstWritePending?'[':eventsDelimiter);this._firstWritePending=false;const stringPayload=JSON.stringify(payload);const isAccessible=payload.ph===phase.SnapshotObject;let backingStorage=null;const keepStringsLessThan=10000;if(isAccessible&&stringPayload.length>keepStringsLessThan)
backingStorage=this._backingStorage.appendAccessibleString(stringPayload);else
this._backingStorage.appendString(stringPayload);const timestamp=payload.ts/1000;if(timestamp&&(!this._minimumRecordTime||timestamp<this._minimumRecordTime)&&(payload.ph===phase.Begin||payload.ph===phase.Complete||payload.ph===phase.Instant))
this._minimumRecordTime=timestamp;const endTimeStamp=(payload.ts+(payload.dur||0))/1000;this._maximumRecordTime=Math.max(this._maximumRecordTime,endTimeStamp);const event=process._addEvent(payload);if(!event)
return;if(payload.ph===phase.Sample){this._addSampleEvent(event);return;}
if(SDK.TracingModel.isAsyncPhase(payload.ph))
this._asyncEvents.push(event);event._setBackingStorage(backingStorage);if(event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory))
this._devToolsMetadataEvents.push(event);if(payload.ph!==phase.Metadata)
return;switch(payload.name){case SDK.TracingModel.MetadataEvent.ProcessSortIndex:process._setSortIndex(payload.args['sort_index']);break;case SDK.TracingModel.MetadataEvent.ProcessName:const processName=payload.args['name'];process._setName(processName);this._processByName.set(processName,process);break;case SDK.TracingModel.MetadataEvent.ThreadSortIndex:process.threadById(payload.tid)._setSortIndex(payload.args['sort_index']);break;case SDK.TracingModel.MetadataEvent.ThreadName:process.threadById(payload.tid)._setName(payload.args['name']);break;}}
_addSampleEvent(event){const id=`${event.thread.process().id()}:${event.id}`;const group=this._profileGroups.get(id);if(group)
group._addChild(event);else
this._profileGroups.set(id,new SDK.TracingModel.ProfileEventsGroup(event));}
profileGroup(event){return this._profileGroups.get(`${event.thread.process().id()}:${event.id}`)||null;}
minimumRecordTime(){return this._minimumRecordTime;}
maximumRecordTime(){return this._maximumRecordTime;}
sortedProcesses(){return SDK.TracingModel.NamedObject._sort(this._processById.valuesArray());}
processByName(name){return this._processByName.get(name);}
processById(pid){return this._processById.get(pid)||null;}
threadByName(processName,threadName){const process=this.processByName(processName);return process&&process.threadByName(threadName);}
_processPendingAsyncEvents(){this._asyncEvents.stableSort(SDK.TracingModel.Event.compareStartTime);for(let i=0;i<this._asyncEvents.length;++i){const event=this._asyncEvents[i];if(SDK.TracingModel.isNestableAsyncPhase(event.phase))
this._addNestableAsyncEvent(event);else
this._addAsyncEvent(event);}
this._asyncEvents=[];this._closeOpenAsyncEvents();}
_closeOpenAsyncEvents(){for(const event of this._openAsyncEvents.values()){event.setEndTime(this._maximumRecordTime);event.steps[0].setEndTime(this._maximumRecordTime);}
this._openAsyncEvents.clear();for(const eventStack of this._openNestableAsyncEvents.values()){while(eventStack.length)
eventStack.pop().setEndTime(this._maximumRecordTime);}
this._openNestableAsyncEvents.clear();}
_addNestableAsyncEvent(event){const phase=SDK.TracingModel.Phase;const key=event.categoriesString+'.'+event.id;let openEventsStack=this._openNestableAsyncEvents.get(key);switch(event.phase){case phase.NestableAsyncBegin:if(!openEventsStack){openEventsStack=[];this._openNestableAsyncEvents.set(key,openEventsStack);}
const asyncEvent=new SDK.TracingModel.AsyncEvent(event);openEventsStack.push(asyncEvent);event.thread._addAsyncEvent(asyncEvent);break;case phase.NestableAsyncInstant:if(openEventsStack&&openEventsStack.length)
openEventsStack.peekLast()._addStep(event);break;case phase.NestableAsyncEnd:if(!openEventsStack||!openEventsStack.length)
break;const top=openEventsStack.pop();if(top.name!==event.name){console.error(`Begin/end event mismatch for nestable async event, ${top.name} vs. ${event.name}, key: ${key}`);break;}
top._addStep(event);}}
_addAsyncEvent(event){const phase=SDK.TracingModel.Phase;const key=event.categoriesString+'.'+event.name+'.'+event.id;let asyncEvent=this._openAsyncEvents.get(key);if(event.phase===phase.AsyncBegin){if(asyncEvent){console.error(`Event ${event.name} has already been started`);return;}
asyncEvent=new SDK.TracingModel.AsyncEvent(event);this._openAsyncEvents.set(key,asyncEvent);event.thread._addAsyncEvent(asyncEvent);return;}
if(!asyncEvent){return;}
if(event.phase===phase.AsyncEnd){asyncEvent._addStep(event);this._openAsyncEvents.delete(key);return;}
if(event.phase===phase.AsyncStepInto||event.phase===phase.AsyncStepPast){const lastStep=asyncEvent.steps.peekLast();if(lastStep.phase!==phase.AsyncBegin&&lastStep.phase!==event.phase){console.assert(false,'Async event step phase mismatch: '+lastStep.phase+' at '+lastStep.startTime+' vs. '+
event.phase+' at '+event.startTime);return;}
asyncEvent._addStep(event);return;}
console.assert(false,'Invalid async event phase');}
backingStorage(){return this._backingStorage;}
_parsedCategoriesForString(str){let parsedCategories=this._parsedCategories.get(str);if(!parsedCategories){parsedCategories=new Set(str?str.split(','):[]);this._parsedCategories.set(str,parsedCategories);}
return parsedCategories;}};SDK.TracingModel.Phase={Begin:'B',End:'E',Complete:'X',Instant:'I',AsyncBegin:'S',AsyncStepInto:'T',AsyncStepPast:'p',AsyncEnd:'F',NestableAsyncBegin:'b',NestableAsyncEnd:'e',NestableAsyncInstant:'n',FlowBegin:'s',FlowStep:'t',FlowEnd:'f',Metadata:'M',Counter:'C',Sample:'P',CreateObject:'N',SnapshotObject:'O',DeleteObject:'D'};SDK.TracingModel.MetadataEvent={ProcessSortIndex:'process_sort_index',ProcessName:'process_name',ThreadSortIndex:'thread_sort_index',ThreadName:'thread_name'};SDK.TracingModel.LegacyTopLevelEventCategory='toplevel';SDK.TracingModel.DevToolsMetadataEventCategory='disabled-by-default-devtools.timeline';SDK.TracingModel.DevToolsTimelineEventCategory='disabled-by-default-devtools.timeline';SDK.TracingModel.FrameLifecycleEventCategory='cc,devtools';SDK.BackingStorage=function(){};SDK.BackingStorage.prototype={appendString(string){},appendAccessibleString(string){},finishWriting(){},reset(){}};SDK.TracingModel.Event=class{constructor(categories,name,phase,startTime,thread){this.categoriesString=categories||'';this._parsedCategories=thread._model._parsedCategoriesForString(this.categoriesString);this.name=name;this.phase=phase;this.startTime=startTime;this.thread=thread;this.args={};this.selfTime=0;}
static fromPayload(payload,thread){const event=new SDK.TracingModel.Event(payload.cat,payload.name,(payload.ph),payload.ts/1000,thread);if(payload.args)
event.addArgs(payload.args);if(typeof payload.dur==='number')
event.setEndTime((payload.ts+payload.dur)/1000);const id=SDK.TracingModel._extractId(payload);if(typeof id!=='undefined')
event.id=id;if(payload.bind_id)
event.bind_id=payload.bind_id;return event;}
static compareStartTime(a,b){return a.startTime-b.startTime;}
static orderedCompareStartTime(a,b){return a.startTime-b.startTime||a.ordinal-b.ordinal||-1;}
hasCategory(categoryName){return this._parsedCategories.has(categoryName);}
setEndTime(endTime){if(endTime<this.startTime){console.assert(false,'Event out of order: '+this.name);return;}
this.endTime=endTime;this.duration=endTime-this.startTime;}
addArgs(args){for(const name in args){if(name in this.args)
console.error('Same argument name ('+name+') is used for begin and end phases of '+this.name);this.args[name]=args[name];}}
_complete(endEvent){if(endEvent.args)
this.addArgs(endEvent.args);else
console.error('Missing mandatory event argument \'args\' at '+endEvent.startTime);this.setEndTime(endEvent.startTime);}
_setBackingStorage(backingStorage){}};SDK.TracingModel.ObjectSnapshot=class extends SDK.TracingModel.Event{constructor(category,name,startTime,thread){super(category,name,SDK.TracingModel.Phase.SnapshotObject,startTime,thread);this._backingStorage=null;this.id;this._objectPromise=null;}
static fromPayload(payload,thread){const snapshot=new SDK.TracingModel.ObjectSnapshot(payload.cat,payload.name,payload.ts/1000,thread);const id=SDK.TracingModel._extractId(payload);if(typeof id!=='undefined')
snapshot.id=id;if(!payload.args||!payload.args['snapshot']){console.error('Missing mandatory \'snapshot\' argument at '+payload.ts/1000);return snapshot;}
if(payload.args)
snapshot.addArgs(payload.args);return snapshot;}
requestObject(callback){const snapshot=this.args['snapshot'];if(snapshot){callback(snapshot);return;}
this._backingStorage().then(onRead,callback.bind(null,null));function onRead(result){if(!result){callback(null);return;}
try{const payload=JSON.parse(result);callback(payload['args']['snapshot']);}catch(e){Common.console.error('Malformed event data in backing storage');callback(null);}}}
objectPromise(){if(!this._objectPromise)
this._objectPromise=new Promise(this.requestObject.bind(this));return this._objectPromise;}
_setBackingStorage(backingStorage){if(!backingStorage)
return;this._backingStorage=backingStorage;this.args={};}};SDK.TracingModel.AsyncEvent=class extends SDK.TracingModel.Event{constructor(startEvent){super(startEvent.categoriesString,startEvent.name,startEvent.phase,startEvent.startTime,startEvent.thread);this.addArgs(startEvent.args);this.steps=[startEvent];}
_addStep(event){this.steps.push(event);if(event.phase===SDK.TracingModel.Phase.AsyncEnd||event.phase===SDK.TracingModel.Phase.NestableAsyncEnd){this.setEndTime(event.startTime);this.steps[0].setEndTime(event.startTime);}}};SDK.TracingModel.ProfileEventsGroup=class{constructor(event){this.children=[event];}
_addChild(event){this.children.push(event);}};SDK.TracingModel.NamedObject=class{constructor(model,id){this._model=model;this._id=id;this._name='';this._sortIndex=0;}
static _sort(array){function comparator(a,b){return a._sortIndex!==b._sortIndex?a._sortIndex-b._sortIndex:a.name().localeCompare(b.name());}
return array.sort(comparator);}
_setName(name){this._name=name;}
name(){return this._name;}
_setSortIndex(sortIndex){this._sortIndex=sortIndex;}};SDK.TracingModel.Process=class extends SDK.TracingModel.NamedObject{constructor(model,id){super(model,id);this._threads=new Map();this._threadByName=new Map();}
id(){return this._id;}
threadById(id){let thread=this._threads.get(id);if(!thread){thread=new SDK.TracingModel.Thread(this,id);this._threads.set(id,thread);}
return thread;}
threadByName(name){return this._threadByName.get(name)||null;}
_setThreadByName(name,thread){this._threadByName.set(name,thread);}
_addEvent(payload){return this.threadById(payload.tid)._addEvent(payload);}
sortedThreads(){return SDK.TracingModel.NamedObject._sort(this._threads.valuesArray());}};SDK.TracingModel.Thread=class extends SDK.TracingModel.NamedObject{constructor(process,id){super(process._model,id);this._process=process;this._events=[];this._asyncEvents=[];this._lastTopLevelEvent=null;}
tracingComplete(){this._asyncEvents.stableSort(SDK.TracingModel.Event.compareStartTime);this._events.stableSort(SDK.TracingModel.Event.compareStartTime);const phases=SDK.TracingModel.Phase;const stack=[];for(let i=0;i<this._events.length;++i){const e=this._events[i];e.ordinal=i;switch(e.phase){case phases.End:this._events[i]=null;if(!stack.length)
continue;const top=stack.pop();if(top.name!==e.name||top.categoriesString!==e.categoriesString){console.error('B/E events mismatch at '+top.startTime+' ('+top.name+') vs. '+e.startTime+' ('+e.name+')');}else{top._complete(e);}
break;case phases.Begin:stack.push(e);break;}}
while(stack.length)
stack.pop().setEndTime(this._model.maximumRecordTime());this._events.remove(null,false);}
_addEvent(payload){const event=payload.ph===SDK.TracingModel.Phase.SnapshotObject?SDK.TracingModel.ObjectSnapshot.fromPayload(payload,this):SDK.TracingModel.Event.fromPayload(payload,this);if(SDK.TracingModel.isTopLevelEvent(event)){if(this._lastTopLevelEvent&&this._lastTopLevelEvent.endTime>event.startTime)
return null;this._lastTopLevelEvent=event;}
this._events.push(event);return event;}
_addAsyncEvent(asyncEvent){this._asyncEvents.push(asyncEvent);}
_setName(name){super._setName(name);this._process._setThreadByName(name,this);}
id(){return this._id;}
process(){return this._process;}
events(){return this._events;}
asyncEvents(){return this._asyncEvents;}};;SDK.OverlayModel=class extends SDK.SDKModel{constructor(target){super(target);this._domModel=(target.model(SDK.DOMModel));target.registerOverlayDispatcher(this);this._overlayAgent=target.overlayAgent();this._debuggerModel=target.model(SDK.DebuggerModel);if(this._debuggerModel){Common.moduleSetting('disablePausedStateOverlay').addChangeListener(this._updatePausedInDebuggerMessage,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerPaused,this._updatePausedInDebuggerMessage,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerResumed,this._updatePausedInDebuggerMessage,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._updatePausedInDebuggerMessage,this);}
this._inspectModeEnabled=false;this._hideHighlightTimeout=null;this._defaultHighlighter=new SDK.OverlayModel.DefaultHighlighter(this);this._highlighter=this._defaultHighlighter;this._showPaintRectsSetting=Common.moduleSetting('showPaintRects');this._showAdHighlightsSetting=Common.moduleSetting('showAdHighlights');this._showDebugBordersSetting=Common.moduleSetting('showDebugBorders');this._showFPSCounterSetting=Common.moduleSetting('showFPSCounter');this._showScrollBottleneckRectsSetting=Common.moduleSetting('showScrollBottleneckRects');this._showHitTestBordersSetting=Common.moduleSetting('showHitTestBorders');this._registeredListeners=[];this._showViewportSizeOnResize=true;if(!target.suspended()){this._overlayAgent.enable();this._wireAgentToSettings();}}
static highlightObjectAsDOMNode(object){const domModel=object.runtimeModel().target().model(SDK.DOMModel);if(domModel)
domModel.overlayModel().highlightInOverlay({object});}
static hideDOMNodeHighlight(){for(const overlayModel of SDK.targetManager.models(SDK.OverlayModel))
overlayModel._delayedHideHighlight(0);}
static async muteHighlight(){return Promise.all(SDK.targetManager.models(SDK.OverlayModel).map(model=>model.suspendModel()));}
static async unmuteHighlight(){return Promise.all(SDK.targetManager.models(SDK.OverlayModel).map(model=>model.resumeModel()));}
_wireAgentToSettings(){this._registeredListeners=[this._showPaintRectsSetting.addChangeListener(()=>this._overlayAgent.setShowPaintRects(this._showPaintRectsSetting.get())),this._showAdHighlightsSetting.addChangeListener(()=>this._overlayAgent.setShowAdHighlights(this._showAdHighlightsSetting.get())),this._showDebugBordersSetting.addChangeListener(()=>this._overlayAgent.setShowDebugBorders(this._showDebugBordersSetting.get())),this._showFPSCounterSetting.addChangeListener(()=>this._overlayAgent.setShowFPSCounter(this._showFPSCounterSetting.get())),this._showScrollBottleneckRectsSetting.addChangeListener(()=>this._overlayAgent.setShowScrollBottleneckRects(this._showScrollBottleneckRectsSetting.get())),this._showHitTestBordersSetting.addChangeListener(()=>this._overlayAgent.setShowHitTestBorders(this._showHitTestBordersSetting.get()))];if(this._showPaintRectsSetting.get())
this._overlayAgent.setShowPaintRects(true);if(this._showAdHighlightsSetting.get())
this._overlayAgent.setShowAdHighlights(true);if(this._showDebugBordersSetting.get())
this._overlayAgent.setShowDebugBorders(true);if(this._showFPSCounterSetting.get())
this._overlayAgent.setShowFPSCounter(true);if(this._showScrollBottleneckRectsSetting.get())
this._overlayAgent.setShowScrollBottleneckRects(true);if(this._showHitTestBordersSetting.get())
this._overlayAgent.setShowHitTestBorders(true);if(this._debuggerModel.isPaused())
this._updatePausedInDebuggerMessage();return this._overlayAgent.setShowViewportSizeOnResize(this._showViewportSizeOnResize);}
suspendModel(){Common.EventTarget.removeEventListeners(this._registeredListeners);return this._overlayAgent.disable();}
resumeModel(){this._overlayAgent.enable();return this._wireAgentToSettings();}
setShowViewportSizeOnResize(show){this._showViewportSizeOnResize=show;if(this.target().suspended())
return;this._overlayAgent.setShowViewportSizeOnResize(show);}
_updatePausedInDebuggerMessage(){if(this.target().suspended())
return Promise.resolve();const message=this._debuggerModel.isPaused()&&!Common.moduleSetting('disablePausedStateOverlay').get()?Common.UIString('Paused in debugger'):undefined;return this._overlayAgent.setPausedInDebuggerMessage(message);}
setHighlighter(highlighter){this._highlighter=highlighter||this._defaultHighlighter;}
async setInspectMode(mode,showStyles=true){await this._domModel.requestDocument();this._inspectModeEnabled=mode!==Protocol.Overlay.InspectMode.None;this.dispatchEventToListeners(SDK.OverlayModel.Events.InspectModeWillBeToggled,this);this._highlighter.setInspectMode(mode,this._buildHighlightConfig('all',showStyles));}
inspectModeEnabled(){return this._inspectModeEnabled;}
highlightInOverlay(data,mode,showInfo){if(this._hideHighlightTimeout){clearTimeout(this._hideHighlightTimeout);this._hideHighlightTimeout=null;}
const highlightConfig=this._buildHighlightConfig(mode);if(typeof showInfo!=='undefined')
highlightConfig.showInfo=showInfo;this._highlighter.highlightInOverlay(data,highlightConfig);}
highlightInOverlayForTwoSeconds(data){this.highlightInOverlay(data);this._delayedHideHighlight(2000);}
_delayedHideHighlight(delay){if(this._hideHighlightTimeout===null)
this._hideHighlightTimeout=setTimeout(()=>this.highlightInOverlay({}),delay);}
highlightFrame(frameId){if(this._hideHighlightTimeout){clearTimeout(this._hideHighlightTimeout);this._hideHighlightTimeout=null;}
this._highlighter.highlightFrame(frameId);}
_buildHighlightConfig(mode='all',showStyles=false){const showRulers=Common.moduleSetting('showMetricsRulers').get();const highlightConfig={showInfo:mode==='all',showRulers:showRulers,showStyles,showExtensionLines:showRulers};if(mode==='all'||mode==='content')
highlightConfig.contentColor=Common.Color.PageHighlight.Content.toProtocolRGBA();if(mode==='all'||mode==='padding')
highlightConfig.paddingColor=Common.Color.PageHighlight.Padding.toProtocolRGBA();if(mode==='all'||mode==='border')
highlightConfig.borderColor=Common.Color.PageHighlight.Border.toProtocolRGBA();if(mode==='all'||mode==='margin')
highlightConfig.marginColor=Common.Color.PageHighlight.Margin.toProtocolRGBA();if(mode==='all'){highlightConfig.eventTargetColor=Common.Color.PageHighlight.EventTarget.toProtocolRGBA();highlightConfig.shapeColor=Common.Color.PageHighlight.Shape.toProtocolRGBA();highlightConfig.shapeMarginColor=Common.Color.PageHighlight.ShapeMargin.toProtocolRGBA();}
if(mode==='all')
highlightConfig.cssGridColor=Common.Color.PageHighlight.CssGrid.toProtocolRGBA();return highlightConfig;}
nodeHighlightRequested(nodeId){const node=this._domModel.nodeForId(nodeId);if(node)
this.dispatchEventToListeners(SDK.OverlayModel.Events.HighlightNodeRequested,node);}
static setInspectNodeHandler(handler){SDK.OverlayModel._inspectNodeHandler=handler;}
inspectNodeRequested(backendNodeId){const deferredNode=new SDK.DeferredDOMNode(this.target(),backendNodeId);if(SDK.OverlayModel._inspectNodeHandler){deferredNode.resolvePromise().then(node=>{if(node)
SDK.OverlayModel._inspectNodeHandler(node);});}else{Common.Revealer.reveal(deferredNode);}
this.dispatchEventToListeners(SDK.OverlayModel.Events.ExitedInspectMode);}
screenshotRequested(viewport){this.dispatchEventToListeners(SDK.OverlayModel.Events.ScreenshotRequested,viewport);this.dispatchEventToListeners(SDK.OverlayModel.Events.ExitedInspectMode);}
inspectModeCanceled(){this.dispatchEventToListeners(SDK.OverlayModel.Events.ExitedInspectMode);}};SDK.SDKModel.register(SDK.OverlayModel,SDK.Target.Capability.DOM,true);SDK.OverlayModel.Events={InspectModeWillBeToggled:Symbol('InspectModeWillBeToggled'),ExitedInspectMode:Symbol('InspectModeExited'),HighlightNodeRequested:Symbol('HighlightNodeRequested'),ScreenshotRequested:Symbol('ScreenshotRequested'),};SDK.OverlayModel.Highlighter=function(){};SDK.OverlayModel.HighlightData;SDK.OverlayModel.Highlighter.prototype={highlightInOverlay(data,config){},setInspectMode(mode,config){},highlightFrame(frameId){}};SDK.OverlayModel.DefaultHighlighter=class{constructor(model){this._model=model;}
highlightInOverlay(data,config){const{node,deferredNode,object,selectorList}=data;const nodeId=node?node.id:undefined;const backendNodeId=deferredNode?deferredNode.backendNodeId():undefined;const objectId=object?object.objectId:undefined;if(nodeId||backendNodeId||objectId)
this._model._overlayAgent.highlightNode(config,nodeId,backendNodeId,objectId,selectorList);else
this._model._overlayAgent.hideHighlight();}
setInspectMode(mode,config){return this._model._overlayAgent.setInspectMode(mode,config);}
highlightFrame(frameId){this._model._overlayAgent.highlightFrame(frameId,Common.Color.PageHighlight.Content.toProtocolRGBA(),Common.Color.PageHighlight.ContentOutline.toProtocolRGBA());}};;SDK.RuntimeModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.runtimeAgent();this.target().registerRuntimeDispatcher(new SDK.RuntimeDispatcher(this));this._agent.enable();this._executionContextById=new Map();this._executionContextComparator=SDK.ExecutionContext.comparator;this._hasSideEffectSupport=null;if(Common.moduleSetting('customFormatters').get())
this._agent.setCustomObjectFormatterEnabled(true);Common.moduleSetting('customFormatters').addChangeListener(this._customFormattersStateChanged.bind(this));}
static isSideEffectFailure(response){const exceptionDetails=!response[Protocol.Error]&&response.exceptionDetails;return!!(exceptionDetails&&exceptionDetails.exception&&exceptionDetails.exception.description&&exceptionDetails.exception.description.startsWith('EvalError: Possible side-effect in debug-evaluate'));}
debuggerModel(){return(this.target().model(SDK.DebuggerModel));}
heapProfilerModel(){return(this.target().model(SDK.HeapProfilerModel));}
executionContexts(){return this._executionContextById.valuesArray().sort(this.executionContextComparator());}
setExecutionContextComparator(comparator){this._executionContextComparator=comparator;}
executionContextComparator(){return this._executionContextComparator;}
defaultExecutionContext(){for(const context of this.executionContexts()){if(context.isDefault)
return context;}
return null;}
executionContext(id){return this._executionContextById.get(id)||null;}
_executionContextCreated(context){const data=context.auxData||{isDefault:true};const executionContext=new SDK.ExecutionContext(this,context.id,context.name,context.origin,data['isDefault'],data['frameId']);this._executionContextById.set(executionContext.id,executionContext);this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextCreated,executionContext);}
_executionContextDestroyed(executionContextId){const executionContext=this._executionContextById.get(executionContextId);if(!executionContext)
return;this.debuggerModel().executionContextDestroyed(executionContext);this._executionContextById.delete(executionContextId);this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextDestroyed,executionContext);}
fireExecutionContextOrderChanged(){this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextOrderChanged,this);}
_executionContextsCleared(){this.debuggerModel().globalObjectCleared();const contexts=this.executionContexts();this._executionContextById.clear();for(let i=0;i<contexts.length;++i)
this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextDestroyed,contexts[i]);}
createRemoteObject(payload){console.assert(typeof payload==='object','Remote object payload should only be an object');return new SDK.RemoteObjectImpl(this,payload.objectId,payload.type,payload.subtype,payload.value,payload.unserializableValue,payload.description,payload.preview,payload.customPreview,payload.className);}
createScopeRemoteObject(payload,scopeRef){return new SDK.ScopeRemoteObject(this,payload.objectId,scopeRef,payload.type,payload.subtype,payload.value,payload.unserializableValue,payload.description,payload.preview);}
createRemoteObjectFromPrimitiveValue(value){const type=typeof value;let unserializableValue=undefined;const unserializableDescription=SDK.RemoteObject.unserializableDescription(value);if(unserializableDescription!==null)
unserializableValue=(unserializableDescription);if(typeof unserializableValue!=='undefined')
value=undefined;return new SDK.RemoteObjectImpl(this,undefined,type,undefined,value,unserializableValue);}
createRemotePropertyFromPrimitiveValue(name,value){return new SDK.RemoteObjectProperty(name,this.createRemoteObjectFromPrimitiveValue(value));}
discardConsoleEntries(){this._agent.discardConsoleEntries();}
releaseObjectGroup(objectGroupName){this._agent.releaseObjectGroup(objectGroupName);}
releaseEvaluationResult(result){if(result.object)
result.object.release();if(result.exceptionDetails&&result.exceptionDetails.exception){const exception=result.exceptionDetails.exception;const exceptionObject=this.createRemoteObject({type:exception.type,objectId:exception.objectId});exceptionObject.release();}}
runIfWaitingForDebugger(){this._agent.runIfWaitingForDebugger();}
_customFormattersStateChanged(event){const enabled=(event.data);this._agent.setCustomObjectFormatterEnabled(enabled);}
async compileScript(expression,sourceURL,persistScript,executionContextId){const response=await this._agent.invoke_compileScript({expression:String.escapeInvalidUnicodeCharacters(expression),sourceURL:sourceURL,persistScript:persistScript,executionContextId:executionContextId});if(response[Protocol.Error]){console.error(response[Protocol.Error]);return null;}
return{scriptId:response.scriptId,exceptionDetails:response.exceptionDetails};}
async runScript(scriptId,executionContextId,objectGroup,silent,includeCommandLineAPI,returnByValue,generatePreview,awaitPromise){const response=await this._agent.invoke_runScript({scriptId,executionContextId,objectGroup,silent,includeCommandLineAPI,returnByValue,generatePreview,awaitPromise});const error=response[Protocol.Error];if(error){console.error(error);return{error:error};}
return{object:this.createRemoteObject(response.result),exceptionDetails:response.exceptionDetails};}
async queryObjects(prototype){if(!prototype.objectId)
return{error:'Prototype should be an Object.'};const response=await this._agent.invoke_queryObjects({prototypeObjectId:(prototype.objectId),objectGroup:'console'});const error=response[Protocol.Error];if(error){console.error(error);return{error:error};}
return{objects:this.createRemoteObject(response.objects)};}
async isolateId(){return(await this._agent.getIsolateId())||this.target().id();}
async heapUsage(){const result=await this._agent.invoke_getHeapUsage({});return result[Protocol.Error]?null:result;}
_inspectRequested(payload,hints){const object=this.createRemoteObject(payload);if(hints.copyToClipboard){this._copyRequested(object);return;}
if(hints.queryObjects){this._queryObjectsRequested(object);return;}
if(object.isNode()){Common.Revealer.reveal(object).then(object.release.bind(object));return;}
if(object.type==='function'){SDK.RemoteFunction.objectAsFunction(object).targetFunctionDetails().then(didGetDetails);return;}
function didGetDetails(response){object.release();if(!response||!response.location)
return;Common.Revealer.reveal(response.location);}
object.release();}
_copyRequested(object){if(!object.objectId){InspectorFrontendHost.copyText(object.unserializableValue()||object.value);return;}
object.callFunctionJSON(toStringForClipboard,[{value:object.subtype}]).then(InspectorFrontendHost.copyText.bind(InspectorFrontendHost));function toStringForClipboard(subtype){if(subtype==='node')
return this.outerHTML;if(subtype&&typeof this==='undefined')
return subtype+'';try{return JSON.stringify(this,null,' ');}catch(e){return''+this;}}}
async _queryObjectsRequested(object){const result=await this.queryObjects(object);object.release();if(result.error){Common.console.error(result.error);return;}
this.dispatchEventToListeners(SDK.RuntimeModel.Events.QueryObjectRequested,{objects:result.objects});}
static simpleTextFromException(exceptionDetails){let text=exceptionDetails.text;if(exceptionDetails.exception&&exceptionDetails.exception.description){let description=exceptionDetails.exception.description;if(description.indexOf('\n')!==-1)
description=description.substring(0,description.indexOf('\n'));text+=' '+description;}
return text;}
exceptionThrown(timestamp,exceptionDetails){const exceptionWithTimestamp={timestamp:timestamp,details:exceptionDetails};this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExceptionThrown,exceptionWithTimestamp);}
_exceptionRevoked(exceptionId){this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExceptionRevoked,exceptionId);}
_consoleAPICalled(type,args,executionContextId,timestamp,stackTrace,context){const consoleAPICall={type:type,args:args,executionContextId:executionContextId,timestamp:timestamp,stackTrace:stackTrace,context:context};this.dispatchEventToListeners(SDK.RuntimeModel.Events.ConsoleAPICalled,consoleAPICall);}
executionContextIdForScriptId(scriptId){const script=this.debuggerModel().scriptForId(scriptId);return script?script.executionContextId:0;}
executionContextForStackTrace(stackTrace){while(stackTrace&&!stackTrace.callFrames.length)
stackTrace=stackTrace.parent;if(!stackTrace||!stackTrace.callFrames.length)
return 0;return this.executionContextIdForScriptId(stackTrace.callFrames[0].scriptId);}
hasSideEffectSupport(){return this._hasSideEffectSupport;}
async checkSideEffectSupport(){const testContext=this.executionContexts().peekLast();if(!testContext)
return false;const response=await this._agent.invoke_evaluate({expression:String.escapeInvalidUnicodeCharacters(SDK.RuntimeModel._sideEffectTestExpression),contextId:testContext.id,throwOnSideEffect:true});this._hasSideEffectSupport=SDK.RuntimeModel.isSideEffectFailure(response);return this._hasSideEffectSupport;}
terminateExecution(){return this._agent.invoke_terminateExecution({});}};SDK.SDKModel.register(SDK.RuntimeModel,SDK.Target.Capability.JS,true);SDK.RuntimeModel._sideEffectTestExpression='(async function(){ await 1; })()';SDK.RuntimeModel.Events={ExecutionContextCreated:Symbol('ExecutionContextCreated'),ExecutionContextDestroyed:Symbol('ExecutionContextDestroyed'),ExecutionContextChanged:Symbol('ExecutionContextChanged'),ExecutionContextOrderChanged:Symbol('ExecutionContextOrderChanged'),ExceptionThrown:Symbol('ExceptionThrown'),ExceptionRevoked:Symbol('ExceptionRevoked'),ConsoleAPICalled:Symbol('ConsoleAPICalled'),QueryObjectRequested:Symbol('QueryObjectRequested'),};SDK.RuntimeModel.ExceptionWithTimestamp;SDK.RuntimeModel.CompileScriptResult;SDK.RuntimeModel.EvaluationOptions;SDK.RuntimeModel.EvaluationResult;SDK.RuntimeModel.QueryObjectResult;SDK.RuntimeModel.ConsoleAPICall;SDK.RuntimeDispatcher=class{constructor(runtimeModel){this._runtimeModel=runtimeModel;}
executionContextCreated(context){this._runtimeModel._executionContextCreated(context);}
executionContextDestroyed(executionContextId){this._runtimeModel._executionContextDestroyed(executionContextId);}
executionContextsCleared(){this._runtimeModel._executionContextsCleared();}
exceptionThrown(timestamp,exceptionDetails){this._runtimeModel.exceptionThrown(timestamp,exceptionDetails);}
exceptionRevoked(reason,exceptionId){this._runtimeModel._exceptionRevoked(exceptionId);}
consoleAPICalled(type,args,executionContextId,timestamp,stackTrace,context){this._runtimeModel._consoleAPICalled(type,args,executionContextId,timestamp,stackTrace,context);}
inspectRequested(payload,hints){this._runtimeModel._inspectRequested(payload,hints);}};SDK.ExecutionContext=class{constructor(runtimeModel,id,name,origin,isDefault,frameId){this.id=id;this.name=name;this.origin=origin;this.isDefault=isDefault;this.runtimeModel=runtimeModel;this.debuggerModel=runtimeModel.debuggerModel();this.frameId=frameId;this._setLabel('');}
target(){return this.runtimeModel.target();}
static comparator(a,b){function targetWeight(target){if(!target.parentTarget())
return 5;if(target.type()===SDK.Target.Type.Frame)
return 4;if(target.type()===SDK.Target.Type.ServiceWorker)
return 3;if(target.type()===SDK.Target.Type.Worker)
return 2;return 1;}
function targetPath(target){let currentTarget=target;const parents=[];while(currentTarget){parents.push(currentTarget);currentTarget=currentTarget.parentTarget();}
return parents.reverse();}
const tagetsA=targetPath(a.target());const targetsB=targetPath(b.target());let targetA;let targetB;for(let i=0;;i++){if(!tagetsA[i]||!targetsB[i]||(tagetsA[i]!==targetsB[i])){targetA=tagetsA[i];targetB=targetsB[i];break;}}
if(!targetA&&targetB)
return-1;if(!targetB&&targetA)
return 1;if(targetA&&targetB){const weightDiff=targetWeight(targetA)-targetWeight(targetB);if(weightDiff)
return-weightDiff;return targetA.id().localeCompare(targetB.id());}
if(a.isDefault)
return-1;if(b.isDefault)
return+1;return a.name.localeCompare(b.name);}
evaluate(options,userGesture,awaitPromise){if(this.debuggerModel.selectedCallFrame())
return this.debuggerModel.evaluateOnSelectedCallFrame(options);const needsTerminationOptions=!!options.throwOnSideEffect||options.timeout!==undefined;if(!needsTerminationOptions||this.runtimeModel.hasSideEffectSupport())
return this._evaluateGlobal(options,userGesture,awaitPromise);const unsupportedError={error:'Side-effect checks not supported by backend.'};if(this.runtimeModel.hasSideEffectSupport()===false)
return Promise.resolve(unsupportedError);return this.runtimeModel.checkSideEffectSupport().then(()=>{if(this.runtimeModel.hasSideEffectSupport())
return this._evaluateGlobal(options,userGesture,awaitPromise);return Promise.resolve(unsupportedError);});}
globalObject(objectGroup,generatePreview){return this._evaluateGlobal({expression:'this',objectGroup:objectGroup,includeCommandLineAPI:false,silent:true,returnByValue:false,generatePreview:generatePreview},false,false);}
async _evaluateGlobal(options,userGesture,awaitPromise){if(!options.expression){options.expression='this';}
const response=await this.runtimeModel._agent.invoke_evaluate({expression:String.escapeInvalidUnicodeCharacters(options.expression),objectGroup:options.objectGroup,includeCommandLineAPI:options.includeCommandLineAPI,silent:options.silent,contextId:this.id,returnByValue:options.returnByValue,generatePreview:options.generatePreview,userGesture:userGesture,awaitPromise:awaitPromise,throwOnSideEffect:options.throwOnSideEffect,timeout:options.timeout});const error=response[Protocol.Error];if(error){console.error(error);return{error:error};}
return{object:this.runtimeModel.createRemoteObject(response.result),exceptionDetails:response.exceptionDetails};}
async globalLexicalScopeNames(){const response=await this.runtimeModel._agent.invoke_globalLexicalScopeNames({executionContextId:this.id});return response[Protocol.Error]?[]:response.names;}
label(){return this._label;}
setLabel(label){this._setLabel(label);this.runtimeModel.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextChanged,this);}
_setLabel(label){if(label){this._label=label;return;}
if(this.name){this._label=this.name;return;}
const parsedUrl=this.origin.asParsedURL();this._label=parsedUrl?parsedUrl.lastPathComponentWithFragment():'';}};;SDK.IsolateManager=class extends Common.Object{constructor(){super();console.assert(!SDK.isolateManager,'Use SDK.isolateManager singleton.');this._isolates=new Map();this._isolateIdByModel=new Map();this._observers=new Set();SDK.targetManager.observeModels(SDK.RuntimeModel,this);this._poll();}
observeIsolates(observer){if(this._observers.has(observer))
throw new Error('Observer can only be registered once');this._observers.add(observer);for(const isolate of this._isolates.values())
observer.isolateAdded(isolate);}
unobserveIsolates(observer){this._observers.delete(observer);}
modelAdded(model){this._modelAdded(model);}
async _modelAdded(model){this._isolateIdByModel.set(model,null);const isolateId=await model.isolateId();if(!this._isolateIdByModel.has(model)){return;}
if(!isolateId){this._isolateIdByModel.delete(model);return;}
this._isolateIdByModel.set(model,isolateId);let isolate=this._isolates.get(isolateId);if(!isolate){isolate=new SDK.IsolateManager.Isolate(isolateId);this._isolates.set(isolateId,isolate);}
isolate._models.add(model);if(isolate._models.size===1){for(const observer of this._observers)
observer.isolateAdded(isolate);}else{for(const observer of this._observers)
observer.isolateChanged(isolate);}}
modelRemoved(model){const isolateId=this._isolateIdByModel.get(model);this._isolateIdByModel.delete(model);if(!isolateId)
return;const isolate=this._isolates.get(isolateId);isolate._models.delete(model);if(isolate._models.size){for(const observer of this._observers)
observer.isolateChanged(isolate);return;}
for(const observer of this._observers)
observer.isolateRemoved(isolate);this._isolates.delete(isolateId);}
isolateByModel(model){return this._isolates.get(this._isolateIdByModel.get(model)||'')||null;}
isolates(){return this._isolates.values();}
async _poll(){while(true){await Promise.all(Array.from(this.isolates(),isolate=>isolate._update()));await new Promise(r=>setTimeout(r,SDK.IsolateManager.PollIntervalMs));}}};SDK.IsolateManager.Observer=function(){};SDK.IsolateManager.Observer.prototype={isolateAdded(isolate){},isolateRemoved(isolate){},isolateChanged(isolate){},};SDK.IsolateManager.Events={MemoryChanged:Symbol('MemoryChanged')};SDK.IsolateManager.MemoryTrendWindowMs=120e3;SDK.IsolateManager.PollIntervalMs=2e3;SDK.IsolateManager.Isolate=class{constructor(id){this._id=id;this._models=new Set();this._usedHeapSize=0;const count=SDK.IsolateManager.MemoryTrendWindowMs/SDK.IsolateManager.PollIntervalMs;this._memoryTrend=new SDK.IsolateManager.MemoryTrend(count);}
id(){return this._id;}
models(){return this._models;}
runtimeModel(){return this._models.values().next().value||null;}
heapProfilerModel(){const runtimeModel=this.runtimeModel();return runtimeModel&&runtimeModel.heapProfilerModel();}
async _update(){const model=this.runtimeModel();const usage=model&&await model.heapUsage();if(!usage)
return;this._usedHeapSize=usage.usedSize;this._memoryTrend.add(this._usedHeapSize);SDK.isolateManager.dispatchEventToListeners(SDK.IsolateManager.Events.MemoryChanged,this);}
samplesCount(){return this._memoryTrend.count();}
usedHeapSize(){return this._usedHeapSize;}
usedHeapSizeGrowRate(){return this._memoryTrend.fitSlope();}};SDK.IsolateManager.MemoryTrend=class{constructor(maxCount){this._maxCount=maxCount|0;this.reset();}
reset(){this._base=Date.now();this._index=0;this._x=[];this._y=[];this._sx=0;this._sy=0;this._sxx=0;this._sxy=0;}
count(){return this._x.length;}
add(heapSize,timestamp){const x=typeof timestamp==='number'?timestamp:Date.now()-this._base;const y=heapSize;if(this._x.length===this._maxCount){const x0=this._x[this._index];const y0=this._y[this._index];this._sx-=x0;this._sy-=y0;this._sxx-=x0*x0;this._sxy-=x0*y0;}
this._sx+=x;this._sy+=y;this._sxx+=x*x;this._sxy+=x*y;this._x[this._index]=x;this._y[this._index]=y;this._index=(this._index+1)%this._maxCount;}
fitSlope(){const n=this.count();return n<2?0:(this._sxy-this._sx*this._sy/n)/(this._sxx-this._sx*this._sx/n);}};SDK.isolateManager=new SDK.IsolateManager();;SDK.ScreenCaptureModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.pageAgent();this._onScreencastFrame=null;this._onScreencastVisibilityChanged=null;target.registerPageDispatcher(this);}
startScreencast(format,quality,width,height,everyNthFrame,onFrame,onVisibilityChanged){this._onScreencastFrame=onFrame;this._onScreencastVisibilityChanged=onVisibilityChanged;this._agent.startScreencast(format,quality,width,height,everyNthFrame);}
stopScreencast(){this._onScreencastFrame=null;this._onScreencastVisibilityChanged=null;this._agent.stopScreencast();}
async captureScreenshot(format,quality,clip){await SDK.OverlayModel.muteHighlight();const result=await this._agent.captureScreenshot(format,quality,clip,true);await SDK.OverlayModel.unmuteHighlight();return result;}
async fetchLayoutMetrics(){const response=await this._agent.invoke_getLayoutMetrics({});if(response[Protocol.Error])
return null;return{viewportX:response.visualViewport.pageX,viewportY:response.visualViewport.pageY,viewportScale:response.visualViewport.scale,contentWidth:response.contentSize.width,contentHeight:response.contentSize.height};}
screencastFrame(data,metadata,sessionId){this._agent.screencastFrameAck(sessionId);if(this._onScreencastFrame)
this._onScreencastFrame.call(null,data,metadata);}
screencastVisibilityChanged(visible){if(this._onScreencastVisibilityChanged)
this._onScreencastVisibilityChanged.call(null,visible);}
domContentEventFired(time){}
loadEventFired(time){}
lifecycleEvent(frameId,loaderId,name,time){}
navigatedWithinDocument(frameId,url){}
frameAttached(frameId,parentFrameId){}
frameNavigated(frame){}
frameDetached(frameId){}
frameStartedLoading(frameId){}
frameStoppedLoading(frameId){}
frameRequestedNavigation(frameId){}
frameScheduledNavigation(frameId,delay){}
frameClearedScheduledNavigation(frameId){}
frameResized(){}
javascriptDialogOpening(url,message,dialogType,hasBrowserHandler,prompt){}
javascriptDialogClosed(result,userInput){}
interstitialShown(){}
interstitialHidden(){}
windowOpen(url,windowName,windowFeatures,userGesture){}
compilationCacheProduced(url,data){}
downloadWillBegin(frameId,url){}};SDK.SDKModel.register(SDK.ScreenCaptureModel,SDK.Target.Capability.ScreenCapture,false);;SDK.Script=class{constructor(debuggerModel,scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,isContentScript,isLiveEdit,sourceMapURL,hasSourceURL,length,originStackTrace){this.debuggerModel=debuggerModel;this.scriptId=scriptId;this.sourceURL=sourceURL;this.lineOffset=startLine;this.columnOffset=startColumn;this.endLine=endLine;this.endColumn=endColumn;this.executionContextId=executionContextId;this.hash=hash;this._isContentScript=isContentScript;this._isLiveEdit=isLiveEdit;this.sourceMapURL=sourceMapURL;this.hasSourceURL=hasSourceURL;this.contentLength=length;this._originalContentProvider=null;this._originalSource=null;this.originStackTrace=originStackTrace;}
static _trimSourceURLComment(source){let sourceURLIndex=source.lastIndexOf('//# sourceURL=');if(sourceURLIndex===-1){sourceURLIndex=source.lastIndexOf('//@ sourceURL=');if(sourceURLIndex===-1)
return source;}
const sourceURLLineIndex=source.lastIndexOf('\n',sourceURLIndex);if(sourceURLLineIndex===-1)
return source;const sourceURLLine=source.substr(sourceURLLineIndex+1).split('\n',1)[0];if(sourceURLLine.search(SDK.Script.sourceURLRegex)===-1)
return source;return source.substr(0,sourceURLLineIndex)+source.substr(sourceURLLineIndex+sourceURLLine.length+1);}
isContentScript(){return this._isContentScript;}
executionContext(){return this.debuggerModel.runtimeModel().executionContext(this.executionContextId);}
isLiveEdit(){return this._isLiveEdit;}
contentURL(){return this.sourceURL;}
contentType(){return Common.resourceTypes.Script;}
contentEncoded(){return Promise.resolve(false);}
async requestContent(){if(this._source)
return this._source;if(!this.scriptId)
return'';const source=await this.debuggerModel.target().debuggerAgent().getScriptSource(this.scriptId);if(source&&this.hasSourceURL)
this._source=SDK.Script._trimSourceURLComment(source);else
this._source=source||'';if(this._originalSource===null)
this._originalSource=this._source;return this._source;}
originalContentProvider(){if(!this._originalContentProvider){const lazyContent=()=>this.requestContent().then(()=>this._originalSource);this._originalContentProvider=new Common.StaticContentProvider(this.contentURL(),this.contentType(),lazyContent);}
return this._originalContentProvider;}
async searchInContent(query,caseSensitive,isRegex){if(!this.scriptId)
return[];const matches=await this.debuggerModel.target().debuggerAgent().searchInContent(this.scriptId,query,caseSensitive,isRegex);return(matches||[]).map(match=>new Common.ContentProvider.SearchMatch(match.lineNumber,match.lineContent));}
_appendSourceURLCommentIfNeeded(source){if(!this.hasSourceURL)
return source;return source+'\n //# sourceURL='+this.sourceURL;}
async editSource(newSource,callback){newSource=SDK.Script._trimSourceURLComment(newSource);newSource=this._appendSourceURLCommentIfNeeded(newSource);if(!this.scriptId){callback('Script failed to parse');return;}
await this.requestContent();if(this._source===newSource){callback(null);return;}
const response=await this.debuggerModel.target().debuggerAgent().invoke_setScriptSource({scriptId:this.scriptId,scriptSource:newSource});if(!response[Protocol.Error]&&!response.exceptionDetails)
this._source=newSource;const needsStepIn=!!response.stackChanged;callback(response[Protocol.Error],response.exceptionDetails,response.callFrames,response.asyncStackTrace,response.asyncStackTraceId,needsStepIn);}
rawLocation(lineNumber,columnNumber){return new SDK.DebuggerModel.Location(this.debuggerModel,this.scriptId,lineNumber,columnNumber||0);}
isInlineScript(){const startsAtZero=!this.lineOffset&&!this.columnOffset;return!!this.sourceURL&&!startsAtZero;}
isAnonymousScript(){return!this.sourceURL;}
isInlineScriptWithSourceURL(){return!!this.hasSourceURL&&this.isInlineScript();}
async setBlackboxedRanges(positions){const response=await this.debuggerModel.target().debuggerAgent().invoke_setBlackboxedRanges({scriptId:this.scriptId,positions});return!response[Protocol.Error];}};SDK.Script.sourceURLRegex=/^[\040\t]*\/\/[@#] sourceURL=\s*(\S*?)\s*$/m;;SDK.ServiceWorkerCacheModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerStorageDispatcher(this);this._caches=new Map();this._cacheAgent=target.cacheStorageAgent();this._storageAgent=target.storageAgent();this._securityOriginManager=target.model(SDK.SecurityOriginManager);this._originsUpdated=new Set();this._throttler=new Common.Throttler(2000);this._enabled=false;}
enable(){if(this._enabled)
return;this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);for(const securityOrigin of this._securityOriginManager.securityOrigins())
this._addOrigin(securityOrigin);this._enabled=true;}
clearForOrigin(origin){this._removeOrigin(origin);this._addOrigin(origin);}
refreshCacheNames(){for(const cache of this._caches.values())
this._cacheRemoved(cache);this._caches.clear();const securityOrigins=this._securityOriginManager.securityOrigins();for(const securityOrigin of securityOrigins)
this._loadCacheNames(securityOrigin);}
async deleteCache(cache){const response=await this._cacheAgent.invoke_deleteCache({cacheId:cache.cacheId});if(response[Protocol.Error]){console.error(`ServiceWorkerCacheAgent error deleting cache ${cache.toString()}: ${response[Protocol.Error]}`);return;}
this._caches.delete(cache.cacheId);this._cacheRemoved(cache);}
async deleteCacheEntry(cache,request){const response=await this._cacheAgent.invoke_deleteEntry({cacheId:cache.cacheId,request});if(!response[Protocol.Error])
return;Common.console.error(Common.UIString('ServiceWorkerCacheAgent error deleting cache entry %s in cache: %s',cache.toString(),response[Protocol.Error]));}
loadCacheData(cache,skipCount,pageSize,pathFilter,callback){this._requestEntries(cache,skipCount,pageSize,pathFilter,callback);}
caches(){const caches=new Array();for(const cache of this._caches.values())
caches.push(cache);return caches;}
dispose(){for(const cache of this._caches.values())
this._cacheRemoved(cache);this._caches.clear();if(this._enabled){this._securityOriginManager.removeEventListener(SDK.SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.removeEventListener(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);}}
_addOrigin(securityOrigin){this._loadCacheNames(securityOrigin);if(this._isValidSecurityOrigin(securityOrigin))
this._storageAgent.trackCacheStorageForOrigin(securityOrigin);}
_removeOrigin(securityOrigin){for(const opaqueId of this._caches.keys()){const cache=this._caches.get(opaqueId);if(cache.securityOrigin===securityOrigin){this._caches.delete(opaqueId);this._cacheRemoved(cache);}}
if(this._isValidSecurityOrigin(securityOrigin))
this._storageAgent.untrackCacheStorageForOrigin(securityOrigin);}
_isValidSecurityOrigin(securityOrigin){const parsedURL=securityOrigin.asParsedURL();return!!parsedURL&&parsedURL.scheme.startsWith('http');}
async _loadCacheNames(securityOrigin){const caches=await this._cacheAgent.requestCacheNames(securityOrigin);if(!caches)
return;this._updateCacheNames(securityOrigin,caches);}
_updateCacheNames(securityOrigin,cachesJson){function deleteAndSaveOldCaches(cache){if(cache.securityOrigin===securityOrigin&&!updatingCachesIds.has(cache.cacheId)){oldCaches.set(cache.cacheId,cache);this._caches.delete(cache.cacheId);}}
const updatingCachesIds=new Set();const newCaches=new Map();const oldCaches=new Map();for(const cacheJson of cachesJson){const cache=new SDK.ServiceWorkerCacheModel.Cache(this,cacheJson.securityOrigin,cacheJson.cacheName,cacheJson.cacheId);updatingCachesIds.add(cache.cacheId);if(this._caches.has(cache.cacheId))
continue;newCaches.set(cache.cacheId,cache);this._caches.set(cache.cacheId,cache);}
this._caches.forEach(deleteAndSaveOldCaches,this);newCaches.forEach(this._cacheAdded,this);oldCaches.forEach(this._cacheRemoved,this);}
_securityOriginAdded(event){const securityOrigin=(event.data);this._addOrigin(securityOrigin);}
_securityOriginRemoved(event){const securityOrigin=(event.data);this._removeOrigin(securityOrigin);}
_cacheAdded(cache){this.dispatchEventToListeners(SDK.ServiceWorkerCacheModel.Events.CacheAdded,{model:this,cache:cache});}
_cacheRemoved(cache){this.dispatchEventToListeners(SDK.ServiceWorkerCacheModel.Events.CacheRemoved,{model:this,cache:cache});}
async _requestEntries(cache,skipCount,pageSize,pathFilter,callback){const response=await this._cacheAgent.invoke_requestEntries({cacheId:cache.cacheId,skipCount,pageSize,pathFilter});if(response[Protocol.Error]){console.error('ServiceWorkerCacheAgent error while requesting entries: ',response[Protocol.Error]);return;}
callback(response.cacheDataEntries,response.returnCount);}
cacheStorageListUpdated(origin){this._originsUpdated.add(origin);this._throttler.schedule(()=>{const promises=Array.from(this._originsUpdated,origin=>this._loadCacheNames(origin));this._originsUpdated.clear();return Promise.all(promises);});}
cacheStorageContentUpdated(origin,cacheName){this.dispatchEventToListeners(SDK.ServiceWorkerCacheModel.Events.CacheStorageContentUpdated,{origin:origin,cacheName:cacheName});}
indexedDBListUpdated(origin){}
indexedDBContentUpdated(origin,databaseName,objectStoreName){}};SDK.SDKModel.register(SDK.ServiceWorkerCacheModel,SDK.Target.Capability.Browser,false);SDK.ServiceWorkerCacheModel.Events={CacheAdded:Symbol('CacheAdded'),CacheRemoved:Symbol('CacheRemoved'),CacheStorageContentUpdated:Symbol('CacheStorageContentUpdated')};SDK.ServiceWorkerCacheModel.Cache=class{constructor(model,securityOrigin,cacheName,cacheId){this._model=model;this.securityOrigin=securityOrigin;this.cacheName=cacheName;this.cacheId=cacheId;}
equals(cache){return this.cacheId===cache.cacheId;}
toString(){return this.securityOrigin+this.cacheName;}
requestCachedResponse(url,requestHeaders){return this._model._cacheAgent.requestCachedResponse(this.cacheId,url,requestHeaders);}};;SDK.CallFunctionResult;SDK.GetPropertiesResult;SDK.RemoteObject=class{static fromLocalObject(value){return new SDK.LocalJSONObject(value);}
static type(remoteObject){if(remoteObject===null)
return'null';const type=typeof remoteObject;if(type!=='object'&&type!=='function')
return type;return remoteObject.type;}
static arrayNameFromDescription(description){return description.replace(SDK.RemoteObject._descriptionLengthParenRegex,'').replace(SDK.RemoteObject._descriptionLengthSquareRegex,'');}
static arrayLength(object){if(object.subtype!=='array'&&object.subtype!=='typedarray')
return 0;const parenMatches=object.description.match(SDK.RemoteObject._descriptionLengthParenRegex);const squareMatches=object.description.match(SDK.RemoteObject._descriptionLengthSquareRegex);return parenMatches?parseInt(parenMatches[1],10):(squareMatches?parseInt(squareMatches[1],10):0);}
static unserializableDescription(object){const type=typeof object;if(type==='number'){const description=String(object);if(object===0&&1/object<0)
return SDK.RemoteObject.UnserializableNumber.Negative0;if(description===SDK.RemoteObject.UnserializableNumber.NaN||description===SDK.RemoteObject.UnserializableNumber.Infinity||description===SDK.RemoteObject.UnserializableNumber.NegativeInfinity)
return description;}
if(type==='bigint')
return object+'n';return null;}
static toCallArgument(object){const type=typeof object;if(type==='undefined')
return{};const unserializableDescription=SDK.RemoteObject.unserializableDescription(object);if(type==='number'){if(unserializableDescription!==null)
return{unserializableValue:unserializableDescription};return{value:object};}
if(type==='bigint')
return{unserializableValue:(unserializableDescription)};if(type==='string'||type==='boolean')
return{value:object};if(!object)
return{value:null};if(object instanceof SDK.RemoteObject){const unserializableValue=object.unserializableValue();if(unserializableValue!==undefined)
return{unserializableValue:unserializableValue};}else if(object.unserializableValue!==undefined){return{unserializableValue:object.unserializableValue};}
if(typeof object.objectId!=='undefined')
return{objectId:object.objectId};return{value:object.value};}
static async loadFromObjectPerProto(object,generatePreview){const result=await Promise.all([object.getAllProperties(true,generatePreview),object.getOwnProperties(generatePreview)]);const accessorProperties=result[0].properties;const ownProperties=result[1].properties;const internalProperties=result[1].internalProperties;if(!ownProperties||!accessorProperties)
return({properties:null,internalProperties:null});const propertiesMap=new Map();const propertySymbols=[];for(let i=0;i<accessorProperties.length;i++){const property=accessorProperties[i];if(property.symbol)
propertySymbols.push(property);else
propertiesMap.set(property.name,property);}
for(let i=0;i<ownProperties.length;i++){const property=ownProperties[i];if(property.isAccessorProperty())
continue;if(property.symbol)
propertySymbols.push(property);else
propertiesMap.set(property.name,property);}
return{properties:propertiesMap.valuesArray().concat(propertySymbols),internalProperties:internalProperties?internalProperties:null};}
customPreview(){return null;}
get objectId(){return'Not implemented';}
get type(){throw'Not implemented';}
get subtype(){throw'Not implemented';}
get value(){throw'Not implemented';}
unserializableValue(){throw'Not implemented';}
get description(){throw'Not implemented';}
get hasChildren(){throw'Not implemented';}
get preview(){return undefined;}
get className(){return null;}
arrayLength(){throw'Not implemented';}
getOwnProperties(generatePreview){throw'Not implemented';}
getAllProperties(accessorPropertiesOnly,generatePreview){throw'Not implemented';}
async deleteProperty(name){throw'Not implemented';}
async setPropertyValue(name,value){throw'Not implemented';}
callFunction(functionDeclaration,args){throw'Not implemented';}
callFunctionJSON(functionDeclaration,args){throw'Not implemented';}
release(){}
debuggerModel(){throw new Error('DebuggerModel-less object');}
runtimeModel(){throw new Error('RuntimeModel-less object');}
isNode(){return false;}};SDK.RemoteObjectImpl=class extends SDK.RemoteObject{constructor(runtimeModel,objectId,type,subtype,value,unserializableValue,description,preview,customPreview,className){super();this._runtimeModel=runtimeModel;this._runtimeAgent=runtimeModel.target().runtimeAgent();this._type=type;this._subtype=subtype;if(objectId){this._objectId=objectId;this._description=description;this._hasChildren=(type!=='symbol');this._preview=preview;}else{this._description=description;if(!this.description&&unserializableValue)
this._description=unserializableValue;if(!this._description&&(typeof value!=='object'||value===null))
this._description=value+'';this._hasChildren=false;if(typeof unserializableValue==='string'){this._unserializableValue=unserializableValue;if(unserializableValue===SDK.RemoteObject.UnserializableNumber.Infinity||unserializableValue===SDK.RemoteObject.UnserializableNumber.NegativeInfinity||unserializableValue===SDK.RemoteObject.UnserializableNumber.Negative0||unserializableValue===SDK.RemoteObject.UnserializableNumber.NaN)
this._value=Number(unserializableValue);else if(type==='bigint'&&unserializableValue.endsWith('n'))
this._value=BigInt(unserializableValue.substring(0,unserializableValue.length-1));else
this._value=unserializableValue;}else{this._value=value;}}
this._customPreview=customPreview||null;this._className=typeof className==='string'?className:null;}
customPreview(){return this._customPreview;}
get objectId(){return this._objectId;}
get type(){return this._type;}
get subtype(){return this._subtype;}
get value(){return this._value;}
unserializableValue(){return this._unserializableValue;}
get description(){return this._description;}
get hasChildren(){return this._hasChildren;}
get preview(){return this._preview;}
get className(){return this._className;}
getOwnProperties(generatePreview){return this.doGetProperties(true,false,generatePreview);}
getAllProperties(accessorPropertiesOnly,generatePreview){return this.doGetProperties(false,accessorPropertiesOnly,generatePreview);}
async doGetProperties(ownProperties,accessorPropertiesOnly,generatePreview){if(!this._objectId)
return({properties:null,internalProperties:null});const response=await this._runtimeAgent.invoke_getProperties({objectId:this._objectId,ownProperties,accessorPropertiesOnly,generatePreview});if(response[Protocol.Error])
return({properties:null,internalProperties:null});if(response.exceptionDetails){this._runtimeModel.exceptionThrown(Date.now(),response.exceptionDetails);return({properties:null,internalProperties:null});}
const properties=response.result;const internalProperties=response.internalProperties;const result=[];for(let i=0;properties&&i<properties.length;++i){const property=properties[i];const propertyValue=property.value?this._runtimeModel.createRemoteObject(property.value):null;const propertySymbol=property.symbol?this._runtimeModel.createRemoteObject(property.symbol):null;const remoteProperty=new SDK.RemoteObjectProperty(property.name,propertyValue,!!property.enumerable,!!property.writable,!!property.isOwn,!!property.wasThrown,propertySymbol);if(typeof property.value==='undefined'){if(property.get&&property.get.type!=='undefined')
remoteProperty.getter=this._runtimeModel.createRemoteObject(property.get);if(property.set&&property.set.type!=='undefined')
remoteProperty.setter=this._runtimeModel.createRemoteObject(property.set);}
result.push(remoteProperty);}
let internalPropertiesResult=null;if(internalProperties){internalPropertiesResult=[];for(let i=0;i<internalProperties.length;i++){const property=internalProperties[i];if(!property.value)
continue;if(property.name==='[[StableObjectId]]')
continue;const propertyValue=this._runtimeModel.createRemoteObject(property.value);internalPropertiesResult.push(new SDK.RemoteObjectProperty(property.name,propertyValue,true,false,undefined,undefined,undefined,true));}}
return{properties:result,internalProperties:internalPropertiesResult};}
async setPropertyValue(name,value){if(!this._objectId)
return`Can't set a property of non-object.`;const response=await this._runtimeAgent.invoke_evaluate({expression:value,silent:true});if(response[Protocol.Error]||response.exceptionDetails){return response[Protocol.Error]||(response.result.type!=='string'?response.result.description:(response.result.value));}
if(typeof name==='string')
name=SDK.RemoteObject.toCallArgument(name);const resultPromise=this.doSetObjectPropertyValue(response.result,name);if(response.result.objectId)
this._runtimeAgent.releaseObject(response.result.objectId);return resultPromise;}
async doSetObjectPropertyValue(result,name){const setPropertyValueFunction='function(a, b) { this[a] = b; }';const argv=[name,SDK.RemoteObject.toCallArgument(result)];const response=await this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:setPropertyValueFunction,arguments:argv,silent:true});const error=response[Protocol.Error];return error||response.exceptionDetails?error||response.result.description:undefined;}
async deleteProperty(name){if(!this._objectId)
return`Can't delete a property of non-object.`;const deletePropertyFunction='function(a) { delete this[a]; return !(a in this); }';const response=await this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:deletePropertyFunction,arguments:[name],silent:true});if(response[Protocol.Error]||response.exceptionDetails)
return response[Protocol.Error]||response.result.description;if(!response.result.value)
return'Failed to delete property.';}
async callFunction(functionDeclaration,args){const response=await this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:functionDeclaration.toString(),arguments:args,silent:true});if(response[Protocol.Error])
return{object:null,wasThrown:false};return{object:this._runtimeModel.createRemoteObject(response.result),wasThrown:!!response.exceptionDetails};}
async callFunctionJSON(functionDeclaration,args){const response=await this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:functionDeclaration.toString(),arguments:args,silent:true,returnByValue:true});return response[Protocol.Error]||response.exceptionDetails?null:response.result.value;}
release(){if(!this._objectId)
return;this._runtimeAgent.releaseObject(this._objectId);}
arrayLength(){return SDK.RemoteObject.arrayLength(this);}
debuggerModel(){return this._runtimeModel.debuggerModel();}
runtimeModel(){return this._runtimeModel;}
isNode(){return!!this._objectId&&this.type==='object'&&this.subtype==='node';}};SDK.ScopeRemoteObject=class extends SDK.RemoteObjectImpl{constructor(runtimeModel,objectId,scopeRef,type,subtype,value,unserializableValue,description,preview){super(runtimeModel,objectId,type,subtype,value,unserializableValue,description,preview);this._scopeRef=scopeRef;this._savedScopeProperties=undefined;}
async doGetProperties(ownProperties,accessorPropertiesOnly,generatePreview){if(accessorPropertiesOnly)
return({properties:[],internalProperties:[]});if(this._savedScopeProperties){return{properties:this._savedScopeProperties.slice(),internalProperties:null};}
const allProperties=await super.doGetProperties(ownProperties,accessorPropertiesOnly,true);if(this._scopeRef&&Array.isArray(allProperties.properties)){this._savedScopeProperties=allProperties.properties.slice();if(!this._scopeRef.callFrameId){for(const property of this._savedScopeProperties)
property.writable=false;}}
return allProperties;}
async doSetObjectPropertyValue(result,argumentName){const name=(argumentName.value);const error=await this.debuggerModel().setVariableValue(this._scopeRef.number,name,SDK.RemoteObject.toCallArgument(result),this._scopeRef.callFrameId);if(error)
return error;if(this._savedScopeProperties){for(const property of this._savedScopeProperties){if(property.name===name)
property.value=this._runtimeModel.createRemoteObject(result);}}}};SDK.ScopeRef=class{constructor(number,callFrameId){this.number=number;this.callFrameId=callFrameId;}};SDK.RemoteObjectProperty=class{constructor(name,value,enumerable,writable,isOwn,wasThrown,symbol,synthetic,syntheticSetter){this.name=name;if(value!==null)
this.value=value;this.enumerable=typeof enumerable!=='undefined'?enumerable:true;const isNonSyntheticOrSyntheticWritable=!synthetic||!!syntheticSetter;this.writable=typeof writable!=='undefined'?writable:isNonSyntheticOrSyntheticWritable;this.isOwn=!!isOwn;this.wasThrown=!!wasThrown;if(symbol)
this.symbol=symbol;this.synthetic=!!synthetic;if(syntheticSetter)
this.syntheticSetter=syntheticSetter;}
async setSyntheticValue(expression){if(!this.syntheticSetter)
return false;const result=await this.syntheticSetter(expression);if(result)
this.value=result;return!!result;}
isAccessorProperty(){return!!(this.getter||this.setter);}};SDK.LocalJSONObject=class extends SDK.RemoteObject{constructor(value){super();this._value=value;this._cachedDescription;this._cachedChildren;}
get objectId(){return undefined;}
get value(){return this._value;}
unserializableValue(){const unserializableDescription=SDK.RemoteObject.unserializableDescription(this._value);return unserializableDescription||undefined;}
get description(){if(this._cachedDescription)
return this._cachedDescription;function formatArrayItem(property){return this._formatValue(property.value);}
function formatObjectItem(property){let name=property.name;if(/^\s|\s$|^$|\n/.test(name))
name='"'+name.replace(/\n/g,'\u21B5')+'"';return name+': '+this._formatValue(property.value);}
if(this.type==='object'){switch(this.subtype){case'array':this._cachedDescription=this._concatenate('[',']',formatArrayItem.bind(this));break;case'date':this._cachedDescription=''+this._value;break;case'null':this._cachedDescription='null';break;default:this._cachedDescription=this._concatenate('{','}',formatObjectItem.bind(this));}}else{this._cachedDescription=String(this._value);}
return this._cachedDescription;}
_formatValue(value){if(!value)
return'undefined';const description=value.description||'';if(value.type==='string')
return'"'+description.replace(/\n/g,'\u21B5')+'"';return description;}
_concatenate(prefix,suffix,formatProperty){const previewChars=100;let buffer=prefix;const children=this._children();for(let i=0;i<children.length;++i){const itemDescription=formatProperty(children[i]);if(buffer.length+itemDescription.length>previewChars){buffer+=',\u2026';break;}
if(i)
buffer+=', ';buffer+=itemDescription;}
buffer+=suffix;return buffer;}
get type(){return typeof this._value;}
get subtype(){if(this._value===null)
return'null';if(Array.isArray(this._value))
return'array';if(this._value instanceof Date)
return'date';return undefined;}
get hasChildren(){if((typeof this._value!=='object')||(this._value===null))
return false;return!!Object.keys((this._value)).length;}
getOwnProperties(generatePreview){return Promise.resolve(({properties:this._children(),internalProperties:null}));}
getAllProperties(accessorPropertiesOnly,generatePreview){if(accessorPropertiesOnly){return Promise.resolve(({properties:[],internalProperties:null}));}else{return Promise.resolve(({properties:this._children(),internalProperties:null}));}}
_children(){if(!this.hasChildren)
return[];const value=(this._value);function buildProperty(propName){let propValue=value[propName];if(!(propValue instanceof SDK.RemoteObject))
propValue=SDK.RemoteObject.fromLocalObject(propValue);return new SDK.RemoteObjectProperty(propName,propValue);}
if(!this._cachedChildren)
this._cachedChildren=Object.keys(value).map(buildProperty);return this._cachedChildren;}
arrayLength(){return Array.isArray(this._value)?this._value.length:0;}
callFunction(functionDeclaration,args){const target=(this._value);const rawArgs=args?args.map(arg=>arg.value):[];let result;let wasThrown=false;try{result=functionDeclaration.apply(target,rawArgs);}catch(e){wasThrown=true;}
return Promise.resolve(({object:SDK.RemoteObject.fromLocalObject(result),wasThrown:wasThrown}));}
callFunctionJSON(functionDeclaration,args){const target=(this._value);const rawArgs=args?args.map(arg=>arg.value):[];let result;try{result=functionDeclaration.apply(target,rawArgs);}catch(e){result=null;}
return Promise.resolve(result);}};SDK.RemoteArray=class{constructor(object){this._object=object;}
static objectAsArray(object){if(!object||object.type!=='object'||(object.subtype!=='array'&&object.subtype!=='typedarray'))
throw new Error('Object is empty or not an array');return new SDK.RemoteArray(object);}
static createFromRemoteObjects(objects){if(!objects.length)
throw new Error('Input array is empty');const objectArguments=[];for(let i=0;i<objects.length;++i)
objectArguments.push(SDK.RemoteObject.toCallArgument(objects[i]));return objects[0].callFunction(createArray,objectArguments).then(returnRemoteArray);function createArray(){if(arguments.length>1)
return new Array(arguments);return[arguments[0]];}
function returnRemoteArray(result){if(result.wasThrown||!result.object)
throw new Error('Call function throws exceptions or returns empty value');return SDK.RemoteArray.objectAsArray(result.object);}}
at(index){if(index<0||index>this._object.arrayLength())
throw new Error('Out of range');return this._object.callFunction(at,[SDK.RemoteObject.toCallArgument(index)]).then(assertCallFunctionResult);function at(index){return this[index];}
function assertCallFunctionResult(result){if(result.wasThrown||!result.object)
throw new Error('Exception in callFunction or result value is empty');return result.object;}}
length(){return this._object.arrayLength();}
map(func){const promises=[];for(let i=0;i<this.length();++i)
promises.push(this.at(i).then(func));return Promise.all(promises);}
object(){return this._object;}};SDK.RemoteFunction=class{constructor(object){this._object=object;}
static objectAsFunction(object){if(!object||object.type!=='function')
throw new Error('Object is empty or not a function');return new SDK.RemoteFunction(object);}
targetFunction(){return this._object.getOwnProperties(false).then(targetFunction.bind(this));function targetFunction(ownProperties){if(!ownProperties.internalProperties)
return this._object;const internalProperties=ownProperties.internalProperties;for(const property of internalProperties){if(property.name==='[[TargetFunction]]')
return property.value;}
return this._object;}}
targetFunctionDetails(){return this.targetFunction().then(functionDetails.bind(this));function functionDetails(targetFunction){const boundReleaseFunctionDetails=releaseTargetFunction.bind(null,this._object!==targetFunction?targetFunction:null);return targetFunction.debuggerModel().functionDetailsPromise(targetFunction).then(boundReleaseFunctionDetails);}
function releaseTargetFunction(targetFunction,functionDetails){if(targetFunction)
targetFunction.release();return functionDetails;}}
object(){return this._object;}};SDK.RemoteObject._descriptionLengthParenRegex=/\(([0-9]+)\)/;SDK.RemoteObject._descriptionLengthSquareRegex=/\[([0-9]+)\]/;SDK.RemoteObject.UnserializableNumber={Negative0:('-0'),NaN:('NaN'),Infinity:('Infinity'),NegativeInfinity:('-Infinity')};;SDK.Resource=class{constructor(resourceTreeModel,request,url,documentURL,frameId,loaderId,type,mimeType,lastModified,contentSize){this._resourceTreeModel=resourceTreeModel;this._request=request;this.url=url;this._documentURL=documentURL;this._frameId=frameId;this._loaderId=loaderId;this._type=type||Common.resourceTypes.Other;this._mimeType=mimeType;this._lastModified=lastModified&&lastModified.isValid()?lastModified:null;this._contentSize=contentSize;this._content;this._contentEncoded;this._pendingContentCallbacks=[];if(this._request&&!this._request.finished)
this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._requestFinished,this);}
lastModified(){if(this._lastModified||!this._request)
return this._lastModified;const lastModifiedHeader=this._request.responseLastModified();const date=lastModifiedHeader?new Date(lastModifiedHeader):null;this._lastModified=date&&date.isValid()?date:null;return this._lastModified;}
contentSize(){if(typeof this._contentSize==='number'||!this._request)
return this._contentSize;return this._request.resourceSize;}
get request(){return this._request;}
get url(){return this._url;}
set url(x){this._url=x;this._parsedURL=new Common.ParsedURL(x);}
get parsedURL(){return this._parsedURL;}
get documentURL(){return this._documentURL;}
get frameId(){return this._frameId;}
get loaderId(){return this._loaderId;}
get displayName(){return this._parsedURL.displayName;}
resourceType(){return this._request?this._request.resourceType():this._type;}
get mimeType(){return this._request?this._request.mimeType:this._mimeType;}
get content(){return this._content;}
contentURL(){return this._url;}
contentType(){if(this.resourceType()===Common.resourceTypes.Document&&this.mimeType.indexOf('javascript')!==-1)
return Common.resourceTypes.Script;return this.resourceType();}
async contentEncoded(){await this.requestContent();return this._contentEncoded;}
requestContent(){if(typeof this._content!=='undefined')
return Promise.resolve(this._content);let callback;const promise=new Promise(fulfill=>callback=fulfill);this._pendingContentCallbacks.push(callback);if(!this._request||this._request.finished)
this._innerRequestContent();return promise;}
canonicalMimeType(){return this.contentType().canonicalMimeType()||this.mimeType;}
async searchInContent(query,caseSensitive,isRegex){if(!this.frameId)
return[];if(this.request)
return this.request.searchInContent(query,caseSensitive,isRegex);const result=await this._resourceTreeModel.target().pageAgent().searchInResource(this.frameId,this.url,query,caseSensitive,isRegex);return result||[];}
async populateImageSource(image){const content=await this.requestContent();const encoded=this._contentEncoded;image.src=Common.ContentProvider.contentAsDataURL(content,this._mimeType,encoded)||this._url;}
_requestFinished(){this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._requestFinished,this);if(this._pendingContentCallbacks.length)
this._innerRequestContent();}
async _innerRequestContent(){if(this._contentRequested)
return;this._contentRequested=true;if(this.request){const contentData=await this.request.contentData();this._content=contentData.content;this._contentEncoded=contentData.encoded;}else{const response=await this._resourceTreeModel.target().pageAgent().invoke_getResourceContent({frameId:this.frameId,url:this.url});this._content=response[Protocol.Error]?null:response.content;this._contentEncoded=response.base64Encoded;}
if(this._content===null)
this._contentEncoded=false;for(const callback of this._pendingContentCallbacks.splice(0))
callback(this._content);delete this._contentRequested;}
hasTextContent(){if(this._type.isTextType())
return true;if(this._type===Common.resourceTypes.Other)
return!!this._content&&!this._contentEncoded;return false;}
frame(){return this._resourceTreeModel.frameForId(this._frameId);}};;SDK.ResourceTreeModel=class extends SDK.SDKModel{constructor(target){super(target);const networkManager=target.model(SDK.NetworkManager);if(networkManager){networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished,this._onRequestFinished,this);networkManager.addEventListener(SDK.NetworkManager.Events.RequestUpdateDropped,this._onRequestUpdateDropped,this);}
this._agent=target.pageAgent();this._agent.enable();this._securityOriginManager=target.model(SDK.SecurityOriginManager);target.registerPageDispatcher(new SDK.PageDispatcher(this));this._frames=new Map();this._cachedResourcesProcessed=false;this._pendingReloadOptions=null;this._reloadSuspensionCount=0;this._isInterstitialShowing=false;this.mainFrame=null;this._agent.getResourceTree().then(this._processCachedResources.bind(this));}
static frameForRequest(request){const networkManager=SDK.NetworkManager.forRequest(request);const resourceTreeModel=networkManager?networkManager.target().model(SDK.ResourceTreeModel):null;if(!resourceTreeModel)
return null;return resourceTreeModel.frameForId(request.frameId);}
static frames(){let result=[];for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel))
result=result.concat(resourceTreeModel._frames.valuesArray());return result;}
static resourceForURL(url){for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)){const mainFrame=resourceTreeModel.mainFrame;const result=mainFrame?mainFrame.resourceForURL(url):null;if(result)
return result;}
return null;}
static reloadAllPages(bypassCache,scriptToEvaluateOnLoad){for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)){if(!resourceTreeModel.target().parentTarget())
resourceTreeModel.reloadPage(bypassCache,scriptToEvaluateOnLoad);}}
domModel(){return(this.target().model(SDK.DOMModel));}
_processCachedResources(mainFramePayload){if(mainFramePayload){this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.WillLoadCachedResources);this._addFramesRecursively(null,mainFramePayload);this.target().setInspectedURL(mainFramePayload.frame.url);}
this._cachedResourcesProcessed=true;const runtimeModel=this.target().model(SDK.RuntimeModel);if(runtimeModel){runtimeModel.setExecutionContextComparator(this._executionContextComparator.bind(this));runtimeModel.fireExecutionContextOrderChanged();}
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.CachedResourcesLoaded,this);}
cachedResourcesLoaded(){return this._cachedResourcesProcessed;}
isInterstitialShowing(){return this._isInterstitialShowing;}
_addFrame(frame,aboutToNavigate){this._frames.set(frame.id,frame);if(frame.isMainFrame())
this.mainFrame=frame;this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameAdded,frame);this._updateSecurityOrigins();}
_frameAttached(frameId,parentFrameId,stackTrace){const parentFrame=parentFrameId?(this._frames.get(parentFrameId)||null):null;if(!this._cachedResourcesProcessed&&parentFrame)
return null;if(this._frames.has(frameId))
return null;const frame=new SDK.ResourceTreeFrame(this,parentFrame,frameId,null,stackTrace||null);if(parentFrameId&&!parentFrame)
frame._crossTargetParentFrameId=parentFrameId;if(frame.isMainFrame()&&this.mainFrame){this._frameDetached(this.mainFrame.id);}
this._addFrame(frame,true);return frame;}
_frameNavigated(framePayload){const parentFrame=framePayload.parentId?(this._frames.get(framePayload.parentId)||null):null;if(!this._cachedResourcesProcessed&&parentFrame)
return;let frame=this._frames.get(framePayload.id);if(!frame){frame=this._frameAttached(framePayload.id,framePayload.parentId||'');console.assert(frame);}
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameWillNavigate,frame);frame._navigate(framePayload);this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameNavigated,frame);if(frame.isMainFrame())
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.MainFrameNavigated,frame);const resources=frame.resources();for(let i=0;i<resources.length;++i)
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded,resources[i]);if(frame.isMainFrame())
this.target().setInspectedURL(frame.url);this._updateSecurityOrigins();}
_frameDetached(frameId){if(!this._cachedResourcesProcessed)
return;const frame=this._frames.get(frameId);if(!frame)
return;if(frame.parentFrame)
frame.parentFrame._removeChildFrame(frame);else
frame._remove();this._updateSecurityOrigins();}
_onRequestFinished(event){if(!this._cachedResourcesProcessed)
return;const request=(event.data);if(request.failed||request.resourceType()===Common.resourceTypes.XHR)
return;const frame=this._frames.get(request.frameId);if(frame)
frame._addRequest(request);}
_onRequestUpdateDropped(event){if(!this._cachedResourcesProcessed)
return;const frameId=event.data.frameId;const frame=this._frames.get(frameId);if(!frame)
return;const url=event.data.url;if(frame._resourcesMap[url])
return;const resource=new SDK.Resource(this,null,url,frame.url,frameId,event.data.loaderId,Common.resourceTypes[event.data.resourceType],event.data.mimeType,event.data.lastModified,null);frame.addResource(resource);}
frameForId(frameId){return this._frames.get(frameId);}
forAllResources(callback){if(this.mainFrame)
return this.mainFrame._callForFrameResources(callback);return false;}
frames(){return this._frames.valuesArray();}
resourceForURL(url){return this.mainFrame?this.mainFrame.resourceForURL(url):null;}
_addFramesRecursively(parentFrame,frameTreePayload){const framePayload=frameTreePayload.frame;const frame=new SDK.ResourceTreeFrame(this,parentFrame,framePayload.id,framePayload,null);if(!parentFrame&&framePayload.parentId)
frame._crossTargetParentFrameId=framePayload.parentId;this._addFrame(frame);for(let i=0;frameTreePayload.childFrames&&i<frameTreePayload.childFrames.length;++i)
this._addFramesRecursively(frame,frameTreePayload.childFrames[i]);for(let i=0;i<frameTreePayload.resources.length;++i){const subresource=frameTreePayload.resources[i];const resource=this._createResourceFromFramePayload(framePayload,subresource.url,Common.resourceTypes[subresource.type],subresource.mimeType,subresource.lastModified||null,subresource.contentSize||null);frame.addResource(resource);}
if(!frame._resourcesMap[framePayload.url]){const frameResource=this._createResourceFromFramePayload(framePayload,framePayload.url,Common.resourceTypes.Document,framePayload.mimeType,null,null);frame.addResource(frameResource);}}
_createResourceFromFramePayload(frame,url,type,mimeType,lastModifiedTime,contentSize){const lastModified=typeof lastModifiedTime==='number'?new Date(lastModifiedTime*1000):null;return new SDK.Resource(this,null,url,frame.url,frame.id,frame.loaderId,type,mimeType,lastModified,contentSize);}
suspendReload(){this._reloadSuspensionCount++;}
resumeReload(){this._reloadSuspensionCount--;console.assert(this._reloadSuspensionCount>=0,'Unbalanced call to ResourceTreeModel.resumeReload()');if(!this._reloadSuspensionCount&&this._pendingReloadOptions)
this.reloadPage.apply(this,this._pendingReloadOptions);}
reloadPage(bypassCache,scriptToEvaluateOnLoad){if(!this._pendingReloadOptions)
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.PageReloadRequested,this);if(this._reloadSuspensionCount){this._pendingReloadOptions=[bypassCache,scriptToEvaluateOnLoad];return;}
this._pendingReloadOptions=null;this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.WillReloadPage);this._agent.reload(bypassCache,scriptToEvaluateOnLoad);}
navigate(url){return this._agent.navigate(url);}
async navigationHistory(){const response=await this._agent.invoke_getNavigationHistory({});if(response[Protocol.Error])
return null;return{currentIndex:response.currentIndex,entries:response.entries};}
navigateToHistoryEntry(entry){this._agent.navigateToHistoryEntry(entry.id);}
async fetchAppManifest(){const response=await this._agent.invoke_getAppManifest({});if(response[Protocol.Error])
return{url:response.url,data:null,errors:[]};return{url:response.url,data:response.data||null,errors:response.errors};}
async getInstallabilityErrors(){const response=await this._agent.invoke_getInstallabilityErrors({});return response.errors||[];}
_executionContextComparator(a,b){function framePath(frame){let currentFrame=frame;const parents=[];while(currentFrame){parents.push(currentFrame);currentFrame=currentFrame.parentFrame;}
return parents.reverse();}
if(a.target()!==b.target())
return SDK.ExecutionContext.comparator(a,b);const framesA=a.frameId?framePath(this.frameForId(a.frameId)):[];const framesB=b.frameId?framePath(this.frameForId(b.frameId)):[];let frameA;let frameB;for(let i=0;;i++){if(!framesA[i]||!framesB[i]||(framesA[i]!==framesB[i])){frameA=framesA[i];frameB=framesB[i];break;}}
if(!frameA&&frameB)
return-1;if(!frameB&&frameA)
return 1;if(frameA&&frameB)
return frameA.id.localeCompare(frameB.id);return SDK.ExecutionContext.comparator(a,b);}
_getSecurityOriginData(){const securityOrigins=new Set();let mainSecurityOrigin=null;let unreachableMainSecurityOrigin=null;for(const frame of this._frames.values()){const origin=frame.securityOrigin;if(!origin)
continue;securityOrigins.add(origin);if(frame.isMainFrame()){mainSecurityOrigin=origin;if(frame.unreachableUrl()){const unreachableParsed=new Common.ParsedURL(frame.unreachableUrl());unreachableMainSecurityOrigin=unreachableParsed.securityOrigin();}}}
return{securityOrigins:securityOrigins,mainSecurityOrigin:mainSecurityOrigin,unreachableMainSecurityOrigin:unreachableMainSecurityOrigin};}
_updateSecurityOrigins(){const data=this._getSecurityOriginData();this._securityOriginManager.setMainSecurityOrigin(data.mainSecurityOrigin||'',data.unreachableMainSecurityOrigin||'');this._securityOriginManager.updateSecurityOrigins(data.securityOrigins);}
getMainSecurityOrigin(){const data=this._getSecurityOriginData();return data.mainSecurityOrigin||data.unreachableMainSecurityOrigin;}};SDK.SDKModel.register(SDK.ResourceTreeModel,SDK.Target.Capability.DOM,true);SDK.ResourceTreeModel.SecurityOriginData;SDK.ResourceTreeModel.Events={FrameAdded:Symbol('FrameAdded'),FrameNavigated:Symbol('FrameNavigated'),FrameDetached:Symbol('FrameDetached'),FrameResized:Symbol('FrameResized'),FrameWillNavigate:Symbol('FrameWillNavigate'),MainFrameNavigated:Symbol('MainFrameNavigated'),ResourceAdded:Symbol('ResourceAdded'),WillLoadCachedResources:Symbol('WillLoadCachedResources'),CachedResourcesLoaded:Symbol('CachedResourcesLoaded'),DOMContentLoaded:Symbol('DOMContentLoaded'),LifecycleEvent:Symbol('LifecycleEvent'),Load:Symbol('Load'),PageReloadRequested:Symbol('PageReloadRequested'),WillReloadPage:Symbol('WillReloadPage'),InterstitialShown:Symbol('InterstitialShown'),InterstitialHidden:Symbol('InterstitialHidden')};SDK.ResourceTreeFrame=class{constructor(model,parentFrame,frameId,payload,creationStackTrace){this._model=model;this._parentFrame=parentFrame;this._id=frameId;this._url='';this._crossTargetParentFrameId=null;if(payload){this._loaderId=payload.loaderId;this._name=payload.name;this._url=payload.url;this._securityOrigin=payload.securityOrigin;this._mimeType=payload.mimeType;this._unreachableUrl=payload.unreachableUrl||'';}
this._creationStackTrace=creationStackTrace;this._childFrames=[];this._resourcesMap={};if(this._parentFrame)
this._parentFrame._childFrames.push(this);}
_navigate(framePayload){this._loaderId=framePayload.loaderId;this._name=framePayload.name;this._url=framePayload.url;this._securityOrigin=framePayload.securityOrigin;this._mimeType=framePayload.mimeType;this._unreachableUrl=framePayload.unreachableUrl||'';const mainResource=this._resourcesMap[this._url];this._resourcesMap={};this._removeChildFrames();if(mainResource&&mainResource.loaderId===this._loaderId)
this.addResource(mainResource);}
resourceTreeModel(){return this._model;}
get id(){return this._id;}
get name(){return this._name||'';}
get url(){return this._url;}
get securityOrigin(){return this._securityOrigin;}
unreachableUrl(){return this._unreachableUrl;}
get loaderId(){return this._loaderId;}
get parentFrame(){return this._parentFrame;}
get childFrames(){return this._childFrames;}
crossTargetParentFrame(){if(!this._crossTargetParentFrameId)
return null;if(!this._model.target().parentTarget())
return null;const parentModel=this._model.target().parentTarget().model(SDK.ResourceTreeModel);if(!parentModel)
return null;return parentModel._frames.get(this._crossTargetParentFrameId)||null;}
findCreationCallFrame(searchFn){let stackTrace=this._creationStackTrace;while(stackTrace){const foundEntry=stackTrace.callFrames.find(searchFn);if(foundEntry)
return foundEntry;stackTrace=this.parent;}
return null;}
isMainFrame(){return!this._parentFrame;}
isTopFrame(){return!this._parentFrame&&!this._crossTargetParentFrameId;}
get mainResource(){return this._resourcesMap[this._url];}
_removeChildFrame(frame){this._childFrames.remove(frame);frame._remove();}
_removeChildFrames(){const frames=this._childFrames;this._childFrames=[];for(let i=0;i<frames.length;++i)
frames[i]._remove();}
_remove(){this._removeChildFrames();this._model._frames.delete(this.id);this._model.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameDetached,this);}
addResource(resource){if(this._resourcesMap[resource.url]===resource){return;}
this._resourcesMap[resource.url]=resource;this._model.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded,resource);}
_addRequest(request){let resource=this._resourcesMap[request.url()];if(resource&&resource.request===request){return;}
resource=new SDK.Resource(this._model,request,request.url(),request.documentURL,request.frameId,request.loaderId,request.resourceType(),request.mimeType,null,null);this._resourcesMap[resource.url]=resource;this._model.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded,resource);}
resources(){const result=[];for(const url in this._resourcesMap)
result.push(this._resourcesMap[url]);return result;}
resourceForURL(url){let resource=this._resourcesMap[url]||null;if(resource)
return resource;for(let i=0;!resource&&i<this._childFrames.length;++i)
resource=this._childFrames[i].resourceForURL(url);return resource;}
_callForFrameResources(callback){for(const url in this._resourcesMap){if(callback(this._resourcesMap[url]))
return true;}
for(let i=0;i<this._childFrames.length;++i){if(this._childFrames[i]._callForFrameResources(callback))
return true;}
return false;}
displayName(){if(this.isTopFrame())
return Common.UIString('top');const subtitle=new Common.ParsedURL(this._url).displayName;if(subtitle){if(!this._name)
return subtitle;return this._name+' ('+subtitle+')';}
return Common.UIString('<iframe>');}};SDK.PageDispatcher=class{constructor(resourceTreeModel){this._resourceTreeModel=resourceTreeModel;}
domContentEventFired(time){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.DOMContentLoaded,time);}
loadEventFired(time){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.Load,{resourceTreeModel:this._resourceTreeModel,loadTime:time});}
lifecycleEvent(frameId,loaderId,name,time){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.LifecycleEvent,{frameId,name});}
frameAttached(frameId,parentFrameId,stackTrace){this._resourceTreeModel._frameAttached(frameId,parentFrameId,stackTrace);}
frameNavigated(frame){this._resourceTreeModel._frameNavigated(frame);}
frameDetached(frameId){this._resourceTreeModel._frameDetached(frameId);}
frameStartedLoading(frameId){}
frameStoppedLoading(frameId){}
frameRequestedNavigation(frameId){}
frameScheduledNavigation(frameId,delay){}
frameClearedScheduledNavigation(frameId){}
navigatedWithinDocument(frameId,url){}
frameResized(){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameResized,null);}
javascriptDialogOpening(url,message,dialogType,hasBrowserHandler,prompt){if(!hasBrowserHandler)
this._resourceTreeModel._agent.handleJavaScriptDialog(false);}
javascriptDialogClosed(result,userInput){}
screencastFrame(data,metadata,sessionId){}
screencastVisibilityChanged(visible){}
interstitialShown(){this._resourceTreeModel._isInterstitialShowing=true;this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.InterstitialShown);}
interstitialHidden(){this._resourceTreeModel._isInterstitialShowing=false;this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.InterstitialHidden);}
windowOpen(url,windowName,windowFeatures,userGesture){}
compilationCacheProduced(url,data){}
downloadWillBegin(frameId,url){}};;SDK.SecurityOriginManager=class extends SDK.SDKModel{constructor(target){super(target);this._mainSecurityOrigin='';this._unreachableMainSecurityOrigin='';this._securityOrigins=new Set();}
updateSecurityOrigins(securityOrigins){const oldOrigins=this._securityOrigins;this._securityOrigins=securityOrigins;for(const origin of oldOrigins){if(!this._securityOrigins.has(origin))
this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,origin);}
for(const origin of this._securityOrigins){if(!oldOrigins.has(origin))
this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.SecurityOriginAdded,origin);}}
securityOrigins(){return this._securityOrigins.valuesArray();}
mainSecurityOrigin(){return this._mainSecurityOrigin;}
unreachableMainSecurityOrigin(){return this._unreachableMainSecurityOrigin;}
setMainSecurityOrigin(securityOrigin,unreachableSecurityOrigin){this._mainSecurityOrigin=securityOrigin;this._unreachableMainSecurityOrigin=unreachableSecurityOrigin||null;this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.MainSecurityOriginChanged,{mainSecurityOrigin:this._mainSecurityOrigin,unreachableMainSecurityOrigin:this._unreachableMainSecurityOrigin});}};SDK.SDKModel.register(SDK.SecurityOriginManager,SDK.Target.Capability.None,false);SDK.SecurityOriginManager.Events={SecurityOriginAdded:Symbol('SecurityOriginAdded'),SecurityOriginRemoved:Symbol('SecurityOriginRemoved'),MainSecurityOriginChanged:Symbol('MainSecurityOriginChanged')};;SDK.SourceMapV3=class{constructor(){this.version;this.file;this.sources;this.sections;this.mappings;this.sourceRoot;this.names;}};SDK.SourceMapV3.Section=class{constructor(){this.map;this.offset;}};SDK.SourceMapV3.Offset=class{constructor(){this.line;this.column;}};SDK.SourceMapEntry=class{constructor(lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber,name){this.lineNumber=lineNumber;this.columnNumber=columnNumber;this.sourceURL=sourceURL;this.sourceLineNumber=sourceLineNumber;this.sourceColumnNumber=sourceColumnNumber;this.name=name;}
static compare(entry1,entry2){if(entry1.lineNumber!==entry2.lineNumber)
return entry1.lineNumber-entry2.lineNumber;return entry1.columnNumber-entry2.columnNumber;}};SDK.SourceMap=function(){};SDK.SourceMap.prototype={compiledURL(){},url(){},sourceURLs(){},sourceContentProvider(sourceURL,contentType){},embeddedContentByURL(sourceURL){},findEntry(lineNumber,columnNumber){},};SDK.SourceMap.EditResult=class{constructor(map,compiledEdits,newSources){this.map=map;this.compiledEdits=compiledEdits;this.newSources=newSources;}};SDK.TextSourceMap=class{constructor(compiledURL,sourceMappingURL,payload){if(!SDK.TextSourceMap._base64Map){const base64Digits='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';SDK.TextSourceMap._base64Map={};for(let i=0;i<base64Digits.length;++i)
SDK.TextSourceMap._base64Map[base64Digits.charAt(i)]=i;}
this._json=payload;this._compiledURL=compiledURL;this._sourceMappingURL=sourceMappingURL;this._baseURL=sourceMappingURL.startsWith('data:')?compiledURL:sourceMappingURL;this._mappings=null;this._sourceInfos=new Map();if(this._json.sections){const sectionWithURL=!!this._json.sections.find(section=>!!section.url);if(sectionWithURL)
Common.console.warn(`SourceMap "${sourceMappingURL}" contains unsupported "URL" field in one of its sections.`);}
this._eachSection(this._parseSources.bind(this));}
static load(sourceMapURL,compiledURL){let callback;const promise=new Promise(fulfill=>callback=fulfill);SDK.multitargetNetworkManager.loadResource(sourceMapURL,contentLoaded);return promise;function contentLoaded(statusCode,headers,content){if(!content||statusCode>=400){callback(null);return;}
if(content.slice(0,3)===')]}')
content=content.substring(content.indexOf('\n'));try{const payload=(JSON.parse(content));callback(new SDK.TextSourceMap(compiledURL,sourceMapURL,payload));}catch(e){console.error(e);Common.console.warn('DevTools failed to parse SourceMap: '+sourceMapURL);callback(null);}}}
compiledURL(){return this._compiledURL;}
url(){return this._sourceMappingURL;}
sourceURLs(){return this._sourceInfos.keysArray();}
sourceContentProvider(sourceURL,contentType){const info=this._sourceInfos.get(sourceURL);if(info.content)
return Common.StaticContentProvider.fromString(sourceURL,contentType,info.content);return new SDK.CompilerSourceMappingContentProvider(sourceURL,contentType);}
embeddedContentByURL(sourceURL){if(!this._sourceInfos.has(sourceURL))
return null;return this._sourceInfos.get(sourceURL).content;}
findEntry(lineNumber,columnNumber){const mappings=this.mappings();const index=mappings.upperBound(undefined,(unused,entry)=>lineNumber-entry.lineNumber||columnNumber-entry.columnNumber);return index?mappings[index-1]:null;}
sourceLineMapping(sourceURL,lineNumber,columnNumber){const mappings=this._reversedMappings(sourceURL);const first=mappings.lowerBound(lineNumber,lineComparator);const last=mappings.upperBound(lineNumber,lineComparator);if(first>=mappings.length||mappings[first].sourceLineNumber!==lineNumber)
return null;const columnMappings=mappings.slice(first,last);if(!columnMappings.length)
return null;const index=columnMappings.lowerBound(columnNumber,(columnNumber,mapping)=>columnNumber-mapping.sourceColumnNumber);return index>=columnMappings.length?columnMappings[columnMappings.length-1]:columnMappings[index];function lineComparator(lineNumber,mapping){return lineNumber-mapping.sourceLineNumber;}}
findReverseEntries(sourceURL,lineNumber,columnNumber){const mappings=this._reversedMappings(sourceURL);const endIndex=mappings.upperBound(undefined,(unused,entry)=>lineNumber-entry.sourceLineNumber||columnNumber-entry.sourceColumnNumber);let startIndex=endIndex;while(startIndex>0&&mappings[startIndex-1].sourceLineNumber===mappings[endIndex-1].sourceLineNumber&&mappings[startIndex-1].sourceColumnNumber===mappings[endIndex-1].sourceColumnNumber)
--startIndex;return mappings.slice(startIndex,endIndex);}
mappings(){if(this._mappings===null){this._mappings=[];this._eachSection(this._parseMap.bind(this));this._json=null;}
return(this._mappings);}
_reversedMappings(sourceURL){if(!this._sourceInfos.has(sourceURL))
return[];const mappings=this.mappings();const info=this._sourceInfos.get(sourceURL);if(info.reverseMappings===null)
info.reverseMappings=mappings.filter(mapping=>mapping.sourceURL===sourceURL).sort(sourceMappingComparator);return info.reverseMappings;function sourceMappingComparator(a,b){if(a.sourceLineNumber!==b.sourceLineNumber)
return a.sourceLineNumber-b.sourceLineNumber;if(a.sourceColumnNumber!==b.sourceColumnNumber)
return a.sourceColumnNumber-b.sourceColumnNumber;if(a.lineNumber!==b.lineNumber)
return a.lineNumber-b.lineNumber;return a.columnNumber-b.columnNumber;}}
_eachSection(callback){if(!this._json.sections){callback(this._json,0,0);return;}
for(const section of this._json.sections)
callback(section.map,section.offset.line,section.offset.column);}
_parseSources(sourceMap){const sourcesList=[];let sourceRoot=sourceMap.sourceRoot||'';if(sourceRoot&&!sourceRoot.endsWith('/'))
sourceRoot+='/';for(let i=0;i<sourceMap.sources.length;++i){const href=sourceRoot+sourceMap.sources[i];let url=Common.ParsedURL.completeURL(this._baseURL,href)||href;const source=sourceMap.sourcesContent&&sourceMap.sourcesContent[i];if(url===this._compiledURL&&source)
url+=Common.UIString('? [sm]');this._sourceInfos.set(url,new SDK.TextSourceMap.SourceInfo(source,null));sourcesList.push(url);}
sourceMap[SDK.TextSourceMap._sourcesListSymbol]=sourcesList;}
_parseMap(map,lineNumber,columnNumber){let sourceIndex=0;let sourceLineNumber=0;let sourceColumnNumber=0;let nameIndex=0;const sources=map[SDK.TextSourceMap._sourcesListSymbol];const names=map.names||[];const stringCharIterator=new SDK.TextSourceMap.StringCharIterator(map.mappings);let sourceURL=sources[sourceIndex];while(true){if(stringCharIterator.peek()===','){stringCharIterator.next();}else{while(stringCharIterator.peek()===';'){lineNumber+=1;columnNumber=0;stringCharIterator.next();}
if(!stringCharIterator.hasNext())
break;}
columnNumber+=this._decodeVLQ(stringCharIterator);if(!stringCharIterator.hasNext()||this._isSeparator(stringCharIterator.peek())){this._mappings.push(new SDK.SourceMapEntry(lineNumber,columnNumber));continue;}
const sourceIndexDelta=this._decodeVLQ(stringCharIterator);if(sourceIndexDelta){sourceIndex+=sourceIndexDelta;sourceURL=sources[sourceIndex];}
sourceLineNumber+=this._decodeVLQ(stringCharIterator);sourceColumnNumber+=this._decodeVLQ(stringCharIterator);if(!stringCharIterator.hasNext()||this._isSeparator(stringCharIterator.peek())){this._mappings.push(new SDK.SourceMapEntry(lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber));continue;}
nameIndex+=this._decodeVLQ(stringCharIterator);this._mappings.push(new SDK.SourceMapEntry(lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber,names[nameIndex]));}
this._mappings.stableSort(SDK.SourceMapEntry.compare);}
_isSeparator(char){return char===','||char===';';}
_decodeVLQ(stringCharIterator){let result=0;let shift=0;let digit;do{digit=SDK.TextSourceMap._base64Map[stringCharIterator.next()];result+=(digit&SDK.TextSourceMap._VLQ_BASE_MASK)<<shift;shift+=SDK.TextSourceMap._VLQ_BASE_SHIFT;}while(digit&SDK.TextSourceMap._VLQ_CONTINUATION_MASK);const negative=result&1;result>>=1;return negative?-result:result;}
reverseMapTextRange(url,textRange){function comparator(position,mapping){if(position.lineNumber!==mapping.sourceLineNumber)
return position.lineNumber-mapping.sourceLineNumber;return position.columnNumber-mapping.sourceColumnNumber;}
const mappings=this._reversedMappings(url);const startIndex=mappings.lowerBound({lineNumber:textRange.startLine,columnNumber:textRange.startColumn},comparator);const endIndex=mappings.upperBound({lineNumber:textRange.endLine,columnNumber:textRange.endColumn},comparator);const startMapping=mappings[startIndex];const endMapping=mappings[endIndex];return new TextUtils.TextRange(startMapping.lineNumber,startMapping.columnNumber,endMapping.lineNumber,endMapping.columnNumber);}};SDK.TextSourceMap._VLQ_BASE_SHIFT=5;SDK.TextSourceMap._VLQ_BASE_MASK=(1<<5)-1;SDK.TextSourceMap._VLQ_CONTINUATION_MASK=1<<5;SDK.TextSourceMap.StringCharIterator=class{constructor(string){this._string=string;this._position=0;}
next(){return this._string.charAt(this._position++);}
peek(){return this._string.charAt(this._position);}
hasNext(){return this._position<this._string.length;}};SDK.TextSourceMap.SourceInfo=class{constructor(content,reverseMappings){this.content=content;this.reverseMappings=reverseMappings;}};SDK.TextSourceMap._sourcesListSymbol=Symbol('sourcesList');;SDK.SourceMapManager=class extends Common.Object{constructor(target){super();this._target=target;this._isEnabled=true;this._relativeSourceURL=new Map();this._relativeSourceMapURL=new Map();this._resolvedSourceMapURL=new Map();this._sourceMapByURL=new Map();this._sourceMapURLToLoadingClients=new Multimap();this._sourceMapURLToClients=new Multimap();SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);}
setEnabled(isEnabled){if(isEnabled===this._isEnabled)
return;this._isEnabled=isEnabled;const clients=Array.from(this._resolvedSourceMapURL.keys());for(const client of clients){const relativeSourceURL=this._relativeSourceURL.get(client);const relativeSourceMapURL=this._relativeSourceMapURL.get(client);this.detachSourceMap(client);this.attachSourceMap(client,relativeSourceURL,relativeSourceMapURL);}}
_inspectedURLChanged(event){if(event.data!==this._target)
return;const clients=Array.from(this._resolvedSourceMapURL.keys());for(const client of clients){const relativeSourceURL=this._relativeSourceURL.get(client);const relativeSourceMapURL=this._relativeSourceMapURL.get(client);const resolvedSourceMapURL=this._resolvedSourceMapURL.get(client);const sourceMapURL=this._resolveRelativeURLs(relativeSourceURL,relativeSourceMapURL).sourceMapURL;if(sourceMapURL!==resolvedSourceMapURL){this.detachSourceMap(client);this.attachSourceMap(client,relativeSourceURL,relativeSourceMapURL);}}}
sourceMapForClient(client){const sourceMapURL=this._resolvedSourceMapURL.get(client);return sourceMapURL?this._sourceMapByURL.get(sourceMapURL)||null:null;}
clientsForSourceMap(sourceMap){if(this._sourceMapURLToClients.has(sourceMap.url()))
return this._sourceMapURLToClients.get(sourceMap.url()).valuesArray();return this._sourceMapURLToLoadingClients.get(sourceMap.url()).valuesArray();}
applySourceMapEdit(editResult){console.assert(this._sourceMapByURL.has(editResult.map.url()),'Cannot apply edit result for non-existing source map');this._sourceMapByURL.set(editResult.map.url(),editResult.map);this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapChanged,{sourceMap:editResult.map,newSources:editResult.newSources});}
_resolveRelativeURLs(sourceURL,sourceMapURL){const resolvedSourceURL=Common.ParsedURL.completeURL(this._target.inspectedURL(),sourceURL);const resolvedSourceMapURL=resolvedSourceURL?Common.ParsedURL.completeURL(resolvedSourceURL,sourceMapURL):null;return{sourceURL:resolvedSourceURL,sourceMapURL:resolvedSourceMapURL};}
attachSourceMap(client,sourceURL,sourceMapURL){if(!sourceMapURL)
return;console.assert(!this._resolvedSourceMapURL.has(client),'SourceMap is already attached to client');const resolvedURLs=this._resolveRelativeURLs(sourceURL,sourceMapURL);if(!resolvedURLs.sourceURL||!resolvedURLs.sourceMapURL)
return;this._relativeSourceURL.set(client,sourceURL);this._relativeSourceMapURL.set(client,sourceMapURL);this._resolvedSourceMapURL.set(client,resolvedURLs.sourceMapURL);sourceURL=resolvedURLs.sourceURL;sourceMapURL=resolvedURLs.sourceMapURL;if(!this._isEnabled)
return;this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapWillAttach,client);if(this._sourceMapByURL.has(sourceMapURL)){attach.call(this,sourceMapURL,client);return;}
if(!this._sourceMapURLToLoadingClients.has(sourceMapURL)){SDK.TextSourceMap.load(sourceMapURL,sourceURL).then(onSourceMap.bind(this,sourceMapURL));}
this._sourceMapURLToLoadingClients.set(sourceMapURL,client);function onSourceMap(sourceMapURL,sourceMap){this._sourceMapLoadedForTest();const clients=this._sourceMapURLToLoadingClients.get(sourceMapURL);this._sourceMapURLToLoadingClients.deleteAll(sourceMapURL);if(!clients.size)
return;if(!sourceMap){for(const client of clients)
this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapFailedToAttach,client);return;}
this._sourceMapByURL.set(sourceMapURL,sourceMap);for(const client of clients)
attach.call(this,sourceMapURL,client);}
function attach(sourceMapURL,client){this._sourceMapURLToClients.set(sourceMapURL,client);const sourceMap=this._sourceMapByURL.get(sourceMapURL);this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapAttached,{client:client,sourceMap:sourceMap});}}
detachSourceMap(client){const sourceMapURL=this._resolvedSourceMapURL.get(client);this._relativeSourceURL.delete(client);this._relativeSourceMapURL.delete(client);this._resolvedSourceMapURL.delete(client);if(!sourceMapURL)
return;if(!this._sourceMapURLToClients.hasValue(sourceMapURL,client)){if(this._sourceMapURLToLoadingClients.delete(sourceMapURL,client))
this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapFailedToAttach,client);return;}
this._sourceMapURLToClients.delete(sourceMapURL,client);const sourceMap=this._sourceMapByURL.get(sourceMapURL);if(!this._sourceMapURLToClients.has(sourceMapURL))
this._sourceMapByURL.delete(sourceMapURL);this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapDetached,{client:client,sourceMap:sourceMap});}
_sourceMapLoadedForTest(){}
dispose(){SDK.targetManager.removeEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);}};SDK.SourceMapManager.Events={SourceMapWillAttach:Symbol('SourceMapWillAttach'),SourceMapFailedToAttach:Symbol('SourceMapFailedToAttach'),SourceMapAttached:Symbol('SourceMapAttached'),SourceMapDetached:Symbol('SourceMapDetached'),SourceMapChanged:Symbol('SourceMapChanged')};;SDK.NetworkManager=class extends SDK.SDKModel{constructor(target){super(target);this._dispatcher=new SDK.NetworkDispatcher(this);this._networkAgent=target.networkAgent();target.registerNetworkDispatcher(this._dispatcher);if(Common.moduleSetting('cacheDisabled').get())
this._networkAgent.setCacheDisabled(true);this._networkAgent.enable(undefined,undefined,SDK.NetworkManager.MAX_EAGER_POST_REQUEST_BODY_LENGTH);this._bypassServiceWorkerSetting=Common.settings.createSetting('bypassServiceWorker',false);if(this._bypassServiceWorkerSetting.get())
this._bypassServiceWorkerChanged();this._bypassServiceWorkerSetting.addChangeListener(this._bypassServiceWorkerChanged,this);Common.moduleSetting('cacheDisabled').addChangeListener(this._cacheDisabledSettingChanged,this);}
static forRequest(request){return request[SDK.NetworkManager._networkManagerForRequestSymbol];}
static canReplayRequest(request){return!!request[SDK.NetworkManager._networkManagerForRequestSymbol]&&request.resourceType()===Common.resourceTypes.XHR;}
static replayRequest(request){const manager=request[SDK.NetworkManager._networkManagerForRequestSymbol];if(!manager)
return;manager._networkAgent.replayXHR(request.requestId());}
static async searchInRequest(request,query,caseSensitive,isRegex){const manager=SDK.NetworkManager.forRequest(request);if(!manager)
return[];const response=await manager._networkAgent.invoke_searchInResponseBody({requestId:request.requestId(),query:query,caseSensitive:caseSensitive,isRegex:isRegex});return response.result||[];}
static async requestContentData(request){if(request.resourceType()===Common.resourceTypes.WebSocket)
return{error:'Content for WebSockets is currently not supported',content:null,encoded:false};if(!request.finished)
await request.once(SDK.NetworkRequest.Events.FinishedLoading);const manager=SDK.NetworkManager.forRequest(request);if(!manager)
return{error:'No network manager for request',content:null,encoded:false};const response=await manager._networkAgent.invoke_getResponseBody({requestId:request.requestId()});const error=response[Protocol.Error]||null;return{error:error,content:error?null:response.body,encoded:response.base64Encoded};}
static requestPostData(request){const manager=SDK.NetworkManager.forRequest(request);if(manager)
return manager._networkAgent.getRequestPostData(request.backendRequestId());console.error('No network manager for request');return(Promise.resolve(null));}
static _connectionType(conditions){if(!conditions.download&&!conditions.upload)
return Protocol.Network.ConnectionType.None;let types=SDK.NetworkManager._connectionTypes;if(!types){SDK.NetworkManager._connectionTypes=[];types=SDK.NetworkManager._connectionTypes;types.push(['2g',Protocol.Network.ConnectionType.Cellular2g]);types.push(['3g',Protocol.Network.ConnectionType.Cellular3g]);types.push(['4g',Protocol.Network.ConnectionType.Cellular4g]);types.push(['bluetooth',Protocol.Network.ConnectionType.Bluetooth]);types.push(['wifi',Protocol.Network.ConnectionType.Wifi]);types.push(['wimax',Protocol.Network.ConnectionType.Wimax]);}
for(const type of types){if(conditions.title.toLowerCase().indexOf(type[0])!==-1)
return type[1];}
return Protocol.Network.ConnectionType.Other;}
static lowercaseHeaders(headers){const newHeaders={};for(const headerName in headers)
newHeaders[headerName.toLowerCase()]=headers[headerName];return newHeaders;}
inflightRequestForURL(url){return this._dispatcher._inflightRequestsByURL[url];}
_cacheDisabledSettingChanged(event){const enabled=(event.data);this._networkAgent.setCacheDisabled(enabled);}
dispose(){Common.moduleSetting('cacheDisabled').removeChangeListener(this._cacheDisabledSettingChanged,this);}
_bypassServiceWorkerChanged(){this._networkAgent.setBypassServiceWorker(this._bypassServiceWorkerSetting.get());}};SDK.SDKModel.register(SDK.NetworkManager,SDK.Target.Capability.Network,true);SDK.NetworkManager.Events={RequestStarted:Symbol('RequestStarted'),RequestUpdated:Symbol('RequestUpdated'),RequestFinished:Symbol('RequestFinished'),RequestUpdateDropped:Symbol('RequestUpdateDropped'),ResponseReceived:Symbol('ResponseReceived'),MessageGenerated:Symbol('MessageGenerated'),RequestRedirected:Symbol('RequestRedirected'),};SDK.NetworkManager.Message;SDK.NetworkManager._MIMETypes={'text/html':{'document':true},'text/xml':{'document':true},'text/plain':{'document':true},'application/xhtml+xml':{'document':true},'image/svg+xml':{'document':true},'text/css':{'stylesheet':true},'text/xsl':{'stylesheet':true},'text/vtt':{'texttrack':true},};SDK.NetworkManager.Conditions;SDK.NetworkManager.NoThrottlingConditions={title:ls`Online`,download:-1,upload:-1,latency:0};SDK.NetworkManager.OfflineConditions={title:Common.UIString('Offline'),download:0,upload:0,latency:0,};SDK.NetworkManager.Slow3GConditions={title:Common.UIString('Slow 3G'),download:500*1024/8*.8,upload:500*1024/8*.8,latency:400*5,};SDK.NetworkManager.Fast3GConditions={title:Common.UIString('Fast 3G'),download:1.6*1024*1024/8*.9,upload:750*1024/8*.9,latency:150*3.75,};SDK.NetworkManager.BlockedPattern;SDK.NetworkManager._networkManagerForRequestSymbol=Symbol('NetworkManager');SDK.NetworkManager.MAX_EAGER_POST_REQUEST_BODY_LENGTH=64*1024;SDK.NetworkDispatcher=class{constructor(manager){this._manager=manager;this._inflightRequestsById={};this._inflightRequestsByURL={};}
_headersMapToHeadersArray(headersMap){const result=[];for(const name in headersMap){const values=headersMap[name].split('\n');for(let i=0;i<values.length;++i)
result.push({name:name,value:values[i]});}
return result;}
_updateNetworkRequestWithRequest(networkRequest,request){networkRequest.requestMethod=request.method;networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));networkRequest.setRequestFormData(!!request.hasPostData,request.postData||null);networkRequest.setInitialPriority(request.initialPriority);networkRequest.mixedContentType=request.mixedContentType||Protocol.Security.MixedContentType.None;networkRequest.setReferrerPolicy(request.referrerPolicy);}
_updateNetworkRequestWithResponse(networkRequest,response){if(response.url&&networkRequest.url()!==response.url)
networkRequest.setUrl(response.url);networkRequest.mimeType=response.mimeType;networkRequest.statusCode=response.status;networkRequest.statusText=response.statusText;networkRequest.responseHeaders=this._headersMapToHeadersArray(response.headers);if(response.encodedDataLength>=0)
networkRequest.setTransferSize(response.encodedDataLength);if(response.headersText)
networkRequest.responseHeadersText=response.headersText;if(response.requestHeaders){networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));networkRequest.setRequestHeadersText(response.requestHeadersText||'');}
networkRequest.connectionReused=response.connectionReused;networkRequest.connectionId=String(response.connectionId);if(response.remoteIPAddress)
networkRequest.setRemoteAddress(response.remoteIPAddress,response.remotePort||-1);if(response.fromServiceWorker)
networkRequest.fetchedViaServiceWorker=true;if(response.fromDiskCache)
networkRequest.setFromDiskCache();if(response.fromPrefetchCache)
networkRequest.setFromPrefetchCache();networkRequest.timing=response.timing;networkRequest.protocol=response.protocol;networkRequest.setSecurityState(response.securityState);if(!this._mimeTypeIsConsistentWithType(networkRequest)){const message=Common.UIString('Resource interpreted as %s but transferred with MIME type %s: "%s".',networkRequest.resourceType().title(),networkRequest.mimeType,networkRequest.url());this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:networkRequest.requestId(),warning:true});}
if(response.securityDetails)
networkRequest.setSecurityDetails(response.securityDetails);}
_mimeTypeIsConsistentWithType(networkRequest){if(networkRequest.hasErrorStatusCode()||networkRequest.statusCode===304||networkRequest.statusCode===204)
return true;const resourceType=networkRequest.resourceType();if(resourceType!==Common.resourceTypes.Stylesheet&&resourceType!==Common.resourceTypes.Document&&resourceType!==Common.resourceTypes.TextTrack)
return true;if(!networkRequest.mimeType)
return true;if(networkRequest.mimeType in SDK.NetworkManager._MIMETypes)
return resourceType.name()in SDK.NetworkManager._MIMETypes[networkRequest.mimeType];return false;}
resourceChangedPriority(requestId,newPriority,timestamp){const networkRequest=this._inflightRequestsById[requestId];if(networkRequest)
networkRequest.setPriority(newPriority);}
signedExchangeReceived(requestId,info){let networkRequest=this._inflightRequestsById[requestId];if(!networkRequest){networkRequest=this._inflightRequestsByURL[info.outerResponse.url];if(!networkRequest)
return;}
networkRequest.setSignedExchangeInfo(info);networkRequest.setResourceType(Common.resourceTypes.SignedExchange);this._updateNetworkRequestWithResponse(networkRequest,info.outerResponse);this._updateNetworkRequest(networkRequest);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.ResponseReceived,networkRequest);}
requestWillBeSent(requestId,loaderId,documentURL,request,time,wallTime,initiator,redirectResponse,resourceType,frameId){let networkRequest=this._inflightRequestsById[requestId];if(networkRequest){if(!redirectResponse)
return;if(!networkRequest.signedExchangeInfo()){this.responseReceived(requestId,loaderId,time,Protocol.Network.ResourceType.Other,redirectResponse,frameId);}
networkRequest=this._appendRedirect(requestId,time,request.url);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestRedirected,networkRequest);}else{networkRequest=this._createNetworkRequest(requestId,frameId||'',loaderId,request.url,documentURL,initiator);}
networkRequest.hasNetworkData=true;this._updateNetworkRequestWithRequest(networkRequest,request);networkRequest.setIssueTime(time,wallTime);networkRequest.setResourceType(resourceType?Common.resourceTypes[resourceType]:Protocol.Network.ResourceType.Other);this._startNetworkRequest(networkRequest);}
requestServedFromCache(requestId){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.setFromMemoryCache();}
responseReceived(requestId,loaderId,time,resourceType,response,frameId){const networkRequest=this._inflightRequestsById[requestId];const lowercaseHeaders=SDK.NetworkManager.lowercaseHeaders(response.headers);if(!networkRequest){const eventData={};eventData.url=response.url;eventData.frameId=frameId||'';eventData.loaderId=loaderId;eventData.resourceType=resourceType;eventData.mimeType=response.mimeType;const lastModifiedHeader=lowercaseHeaders['last-modified'];eventData.lastModified=lastModifiedHeader?new Date(lastModifiedHeader):null;this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestUpdateDropped,eventData);return;}
networkRequest.responseReceivedTime=time;networkRequest.setResourceType(Common.resourceTypes[resourceType]);if('set-cookie'in lowercaseHeaders&&lowercaseHeaders['set-cookie'].length>4096){const values=lowercaseHeaders['set-cookie'].split('\n');for(let i=0;i<values.length;++i){if(values[i].length<=4096)
continue;const message=Common.UIString('Set-Cookie header is ignored in response from url: %s. Cookie length should be less than or equal to 4096 characters.',response.url);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:requestId,warning:true});}}
this._updateNetworkRequestWithResponse(networkRequest,response);this._updateNetworkRequest(networkRequest);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.ResponseReceived,networkRequest);}
dataReceived(requestId,time,dataLength,encodedDataLength){let networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
networkRequest=this._maybeAdoptMainResourceRequest(requestId);if(!networkRequest)
return;networkRequest.resourceSize+=dataLength;if(encodedDataLength!==-1)
networkRequest.increaseTransferSize(encodedDataLength);networkRequest.endTime=time;this._updateNetworkRequest(networkRequest);}
loadingFinished(requestId,finishTime,encodedDataLength,shouldReportCorbBlocking){let networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
networkRequest=this._maybeAdoptMainResourceRequest(requestId);if(!networkRequest)
return;this._finishNetworkRequest(networkRequest,finishTime,encodedDataLength,shouldReportCorbBlocking);}
loadingFailed(requestId,time,resourceType,localizedDescription,canceled,blockedReason){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.failed=true;networkRequest.setResourceType(Common.resourceTypes[resourceType]);networkRequest.canceled=!!canceled;if(blockedReason){networkRequest.setBlockedReason(blockedReason);if(blockedReason===Protocol.Network.BlockedReason.Inspector){const message=Common.UIString('Request was blocked by DevTools: "%s".',networkRequest.url());this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:requestId,warning:true});}}
networkRequest.localizedFailDescription=localizedDescription;this._finishNetworkRequest(networkRequest,time,-1);}
webSocketCreated(requestId,requestURL,initiator){const networkRequest=new SDK.NetworkRequest(requestId,requestURL,'','','',initiator||null);networkRequest[SDK.NetworkManager._networkManagerForRequestSymbol]=this._manager;networkRequest.setResourceType(Common.resourceTypes.WebSocket);this._startNetworkRequest(networkRequest);}
webSocketWillSendHandshakeRequest(requestId,time,wallTime,request){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.requestMethod='GET';networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));networkRequest.setIssueTime(time,wallTime);this._updateNetworkRequest(networkRequest);}
webSocketHandshakeResponseReceived(requestId,time,response){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.statusCode=response.status;networkRequest.statusText=response.statusText;networkRequest.responseHeaders=this._headersMapToHeadersArray(response.headers);networkRequest.responseHeadersText=response.headersText||'';if(response.requestHeaders)
networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));if(response.requestHeadersText)
networkRequest.setRequestHeadersText(response.requestHeadersText);networkRequest.responseReceivedTime=time;networkRequest.protocol='websocket';this._updateNetworkRequest(networkRequest);}
webSocketFrameReceived(requestId,time,response){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addProtocolFrame(response,time,false);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);}
webSocketFrameSent(requestId,time,response){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addProtocolFrame(response,time,true);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);}
webSocketFrameError(requestId,time,errorMessage){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addProtocolFrameError(errorMessage,time);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);}
webSocketClosed(requestId,time){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;this._finishNetworkRequest(networkRequest,time,-1);}
eventSourceMessageReceived(requestId,time,eventName,eventId,data){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addEventSourceMessage(time,eventName,eventId,data);}
requestIntercepted(interceptionId,request,frameId,resourceType,isNavigationRequest,isDownload,redirectUrl,authChallenge,responseErrorReason,responseStatusCode,responseHeaders,requestId){SDK.multitargetNetworkManager._requestIntercepted(new SDK.MultitargetNetworkManager.InterceptedRequest(this._manager.target().networkAgent(),interceptionId,request,frameId,resourceType,isNavigationRequest,isDownload,redirectUrl,authChallenge,responseErrorReason,responseStatusCode,responseHeaders,requestId));}
_appendRedirect(requestId,time,redirectURL){const originalNetworkRequest=this._inflightRequestsById[requestId];let redirectCount=0;for(let redirect=originalNetworkRequest.redirectSource();redirect;redirect=redirect.redirectSource())
redirectCount++;originalNetworkRequest.markAsRedirect(redirectCount);this._finishNetworkRequest(originalNetworkRequest,time,-1);const newNetworkRequest=this._createNetworkRequest(requestId,originalNetworkRequest.frameId,originalNetworkRequest.loaderId,redirectURL,originalNetworkRequest.documentURL,originalNetworkRequest.initiator());newNetworkRequest.setRedirectSource(originalNetworkRequest);originalNetworkRequest.setRedirectDestination(newNetworkRequest);return newNetworkRequest;}
_maybeAdoptMainResourceRequest(requestId){const request=SDK.multitargetNetworkManager._inflightMainResourceRequests.get(requestId);if(!request)
return null;const oldDispatcher=SDK.NetworkManager.forRequest(request)._dispatcher;delete oldDispatcher._inflightRequestsById[requestId];delete oldDispatcher._inflightRequestsByURL[request.url()];this._inflightRequestsById[requestId]=request;this._inflightRequestsByURL[request.url()]=request;request[SDK.NetworkManager._networkManagerForRequestSymbol]=this._manager;return request;}
_startNetworkRequest(networkRequest){this._inflightRequestsById[networkRequest.requestId()]=networkRequest;this._inflightRequestsByURL[networkRequest.url()]=networkRequest;if(networkRequest.loaderId===networkRequest.requestId())
SDK.multitargetNetworkManager._inflightMainResourceRequests.set(networkRequest.requestId(),networkRequest);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestStarted,networkRequest);}
_updateNetworkRequest(networkRequest){this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestUpdated,networkRequest);}
_finishNetworkRequest(networkRequest,finishTime,encodedDataLength,shouldReportCorbBlocking){networkRequest.endTime=finishTime;networkRequest.finished=true;if(encodedDataLength>=0){const redirectSource=networkRequest.redirectSource();if(redirectSource&&redirectSource.signedExchangeInfo()){networkRequest.setTransferSize(0);redirectSource.setTransferSize(encodedDataLength);this._updateNetworkRequest(redirectSource);}else{networkRequest.setTransferSize(encodedDataLength);}}
this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestFinished,networkRequest);delete this._inflightRequestsById[networkRequest.requestId()];delete this._inflightRequestsByURL[networkRequest.url()];SDK.multitargetNetworkManager._inflightMainResourceRequests.delete(networkRequest.requestId());if(shouldReportCorbBlocking){const message=Common.UIString(`Cross-Origin Read Blocking (CORB) blocked cross-origin response %s with MIME type %s. See https://www.chromestatus.com/feature/5629709824032768 for more details.`,networkRequest.url(),networkRequest.mimeType);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:networkRequest.requestId(),warning:true});}
if(Common.moduleSetting('monitoringXHREnabled').get()&&networkRequest.resourceType().category()===Common.resourceCategories.XHR){let message;const failedToLoad=networkRequest.failed||networkRequest.hasErrorStatusCode();if(failedToLoad){message=Common.UIString('%s failed loading: %s "%s".',networkRequest.resourceType().title(),networkRequest.requestMethod,networkRequest.url());}else{message=Common.UIString('%s finished loading: %s "%s".',networkRequest.resourceType().title(),networkRequest.requestMethod,networkRequest.url());}
this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:networkRequest.requestId(),warning:false});}}
_createNetworkRequest(requestId,frameId,loaderId,url,documentURL,initiator){const request=new SDK.NetworkRequest(requestId,url,documentURL,frameId,loaderId,initiator);request[SDK.NetworkManager._networkManagerForRequestSymbol]=this._manager;return request;}};SDK.MultitargetNetworkManager=class extends Common.Object{constructor(){super();this._userAgentOverride='';this._agents=new Set();this._inflightMainResourceRequests=new Map();this._networkConditions=SDK.NetworkManager.NoThrottlingConditions;this._updatingInterceptionPatternsPromise=null;this._blockingEnabledSetting=Common.moduleSetting('requestBlockingEnabled');this._blockedPatternsSetting=Common.settings.createSetting('networkBlockedPatterns',[]);this._effectiveBlockedURLs=[];this._updateBlockedPatterns();this._urlsForRequestInterceptor=new Multimap();SDK.targetManager.observeModels(SDK.NetworkManager,this);}
static patchUserAgentWithChromeVersion(uaString){const chromeRegex=new RegExp('(?:^|\\W)Chrome/(\\S+)');const chromeMatch=navigator.userAgent.match(chromeRegex);if(chromeMatch&&chromeMatch.length>1)
return String.sprintf(uaString,chromeMatch[1]);return uaString;}
modelAdded(networkManager){const networkAgent=networkManager.target().networkAgent();if(this._extraHeaders)
networkAgent.setExtraHTTPHeaders(this._extraHeaders);if(this._currentUserAgent())
networkAgent.setUserAgentOverride(this._currentUserAgent());if(this._effectiveBlockedURLs.length)
networkAgent.setBlockedURLs(this._effectiveBlockedURLs);if(this.isIntercepting())
networkAgent.setRequestInterception(this._urlsForRequestInterceptor.valuesArray());this._agents.add(networkAgent);if(this.isThrottling())
this._updateNetworkConditions(networkAgent);}
modelRemoved(networkManager){for(const entry of this._inflightMainResourceRequests){const manager=SDK.NetworkManager.forRequest((entry[1]));if(manager!==networkManager)
continue;this._inflightMainResourceRequests.delete((entry[0]));}
this._agents.delete(networkManager.target().networkAgent());}
isThrottling(){return this._networkConditions.download>=0||this._networkConditions.upload>=0||this._networkConditions.latency>0;}
isOffline(){return!this._networkConditions.download&&!this._networkConditions.upload;}
setNetworkConditions(conditions){this._networkConditions=conditions;for(const agent of this._agents)
this._updateNetworkConditions(agent);this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.ConditionsChanged);}
networkConditions(){return this._networkConditions;}
_updateNetworkConditions(networkAgent){const conditions=this._networkConditions;if(!this.isThrottling()){networkAgent.emulateNetworkConditions(false,0,0,0);}else{networkAgent.emulateNetworkConditions(this.isOffline(),conditions.latency,conditions.download<0?0:conditions.download,conditions.upload<0?0:conditions.upload,SDK.NetworkManager._connectionType(conditions));}}
setExtraHTTPHeaders(headers){this._extraHeaders=headers;for(const agent of this._agents)
agent.setExtraHTTPHeaders(this._extraHeaders);}
_currentUserAgent(){return this._customUserAgent?this._customUserAgent:this._userAgentOverride;}
_updateUserAgentOverride(){const userAgent=this._currentUserAgent();for(const agent of this._agents)
agent.setUserAgentOverride(userAgent);}
setUserAgentOverride(userAgent){if(this._userAgentOverride===userAgent)
return;this._userAgentOverride=userAgent;if(!this._customUserAgent)
this._updateUserAgentOverride();this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.UserAgentChanged);}
userAgentOverride(){return this._userAgentOverride;}
setCustomUserAgentOverride(userAgent){this._customUserAgent=userAgent;this._updateUserAgentOverride();}
blockedPatterns(){return this._blockedPatternsSetting.get().slice();}
blockingEnabled(){return this._blockingEnabledSetting.get();}
isBlocking(){return!!this._effectiveBlockedURLs.length;}
setBlockedPatterns(patterns){this._blockedPatternsSetting.set(patterns);this._updateBlockedPatterns();this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged);}
setBlockingEnabled(enabled){if(this._blockingEnabledSetting.get()===enabled)
return;this._blockingEnabledSetting.set(enabled);this._updateBlockedPatterns();this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged);}
_updateBlockedPatterns(){const urls=[];if(this._blockingEnabledSetting.get()){for(const pattern of this._blockedPatternsSetting.get()){if(pattern.enabled)
urls.push(pattern.url);}}
if(!urls.length&&!this._effectiveBlockedURLs.length)
return;this._effectiveBlockedURLs=urls;for(const agent of this._agents)
agent.setBlockedURLs(this._effectiveBlockedURLs);}
isIntercepting(){return!!this._urlsForRequestInterceptor.size;}
setInterceptionHandlerForPatterns(patterns,requestInterceptor){this._urlsForRequestInterceptor.deleteAll(requestInterceptor);for(const newPattern of patterns)
this._urlsForRequestInterceptor.set(requestInterceptor,newPattern);return this._updateInterceptionPatternsOnNextTick();}
_updateInterceptionPatternsOnNextTick(){if(!this._updatingInterceptionPatternsPromise)
this._updatingInterceptionPatternsPromise=Promise.resolve().then(this._updateInterceptionPatterns.bind(this));return this._updatingInterceptionPatternsPromise;}
_updateInterceptionPatterns(){if(!Common.moduleSetting('cacheDisabled').get())
Common.moduleSetting('cacheDisabled').set(true);this._updatingInterceptionPatternsPromise=null;const promises=([]);for(const agent of this._agents)
promises.push(agent.setRequestInterception(this._urlsForRequestInterceptor.valuesArray()));this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.InterceptorsChanged);return Promise.all(promises);}
async _requestIntercepted(interceptedRequest){for(const requestInterceptor of this._urlsForRequestInterceptor.keysArray()){await requestInterceptor(interceptedRequest);if(interceptedRequest.hasResponded())
return;}
if(!interceptedRequest.hasResponded())
interceptedRequest.continueRequestWithoutChange();}
clearBrowserCache(){for(const agent of this._agents)
agent.clearBrowserCache();}
clearBrowserCookies(){for(const agent of this._agents)
agent.clearBrowserCookies();}
getCertificate(origin){const target=SDK.targetManager.mainTarget();return target.networkAgent().getCertificate(origin).then(certificate=>certificate||[]);}
loadResource(url,callback){const headers={};const currentUserAgent=this._currentUserAgent();if(currentUserAgent)
headers['User-Agent']=currentUserAgent;if(Common.moduleSetting('cacheDisabled').get())
headers['Cache-Control']='no-cache';Host.ResourceLoader.load(url,headers,callback);}};SDK.MultitargetNetworkManager.Events={BlockedPatternsChanged:Symbol('BlockedPatternsChanged'),ConditionsChanged:Symbol('ConditionsChanged'),UserAgentChanged:Symbol('UserAgentChanged'),InterceptorsChanged:Symbol('InterceptorsChanged')};SDK.MultitargetNetworkManager.InterceptedRequest=class{constructor(networkAgent,interceptionId,request,frameId,resourceType,isNavigationRequest,isDownload,redirectUrl,authChallenge,responseErrorReason,responseStatusCode,responseHeaders,requestId){this._networkAgent=networkAgent;this._interceptionId=interceptionId;this._hasResponded=false;this.request=request;this.frameId=frameId;this.resourceType=resourceType;this.isNavigationRequest=isNavigationRequest;this.isDownload=!!isDownload;this.redirectUrl=redirectUrl;this.authChallenge=authChallenge;this.responseErrorReason=responseErrorReason;this.responseStatusCode=responseStatusCode;this.responseHeaders=responseHeaders;this.requestId=requestId;}
hasResponded(){return this._hasResponded;}
async continueRequestWithContent(contentBlob){this._hasResponded=true;const headers=['HTTP/1.1 200 OK','Date: '+(new Date()).toUTCString(),'Server: Chrome Devtools Request Interceptor','Connection: closed','Content-Length: '+contentBlob.size,'Content-Type: '+contentBlob.type||'text/x-unknown',];const encodedResponse=await blobToBase64(new Blob([headers.join('\r\n'),'\r\n\r\n',contentBlob]));this._networkAgent.continueInterceptedRequest(this._interceptionId,undefined,encodedResponse);async function blobToBase64(blob){const reader=new FileReader();const fileContentsLoadedPromise=new Promise(resolve=>reader.onloadend=resolve);reader.readAsDataURL(blob);await fileContentsLoadedPromise;if(reader.error){console.error('Could not convert blob to base64.',reader.error);return'';}
const result=reader.result;if(result===undefined){console.error('Could not convert blob to base64.');return'';}
return result.substring(result.indexOf(',')+1);}}
continueRequestWithoutChange(){console.assert(!this._hasResponded);this._hasResponded=true;this._networkAgent.continueInterceptedRequest(this._interceptionId);}
continueRequestWithError(errorReason){console.assert(!this._hasResponded);this._hasResponded=true;this._networkAgent.continueInterceptedRequest(this._interceptionId,errorReason);}
async responseBody(){const response=await this._networkAgent.invoke_getResponseBodyForInterception({interceptionId:this._interceptionId});const error=response[Protocol.Error]||null;return{error:error,content:error?null:response.body,encoded:response.base64Encoded};}};SDK.MultitargetNetworkManager.InterceptionPattern;SDK.MultitargetNetworkManager.RequestInterceptor;SDK.multitargetNetworkManager;;SDK.NetworkLog=class extends Common.Object{constructor(){super();this._requests=[];this._requestsSet=new Set();this._pageLoadForManager=new Map();this._isRecording=true;SDK.targetManager.observeModels(SDK.NetworkManager,this);}
modelAdded(networkManager){const eventListeners=[];eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestStarted,this._onRequestStarted,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestUpdated,this._onRequestUpdated,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestRedirected,this._onRequestRedirect,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished,this._onRequestUpdated,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.MessageGenerated,this._networkMessageGenerated.bind(this,networkManager)));const resourceTreeModel=networkManager.target().model(SDK.ResourceTreeModel);if(resourceTreeModel){eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.WillReloadPage,this._willReloadPage,this));eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this));eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load,this._onLoad,this));eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,this._onDOMContentLoaded.bind(this,resourceTreeModel)));}
networkManager[SDK.NetworkLog._events]=eventListeners;}
modelRemoved(networkManager){this._removeNetworkManagerListeners(networkManager);}
_removeNetworkManagerListeners(networkManager){Common.EventTarget.removeEventListeners(networkManager[SDK.NetworkLog._events]);}
setIsRecording(enabled){if(this._isRecording===enabled)
return;this._isRecording=enabled;if(enabled){SDK.targetManager.observeModels(SDK.NetworkManager,this);}else{SDK.targetManager.unobserveModels(SDK.NetworkManager,this);SDK.targetManager.models(SDK.NetworkManager).forEach(this._removeNetworkManagerListeners.bind(this));}}
requestForURL(url){return this._requests.find(request=>request.url()===url)||null;}
requests(){return this._requests;}
requestByManagerAndId(networkManager,requestId){for(let i=this._requests.length-1;i>=0;i--){const request=this._requests[i];if(requestId===request.requestId()&&networkManager===SDK.NetworkManager.forRequest(request))
return request;}
return null;}
_requestByManagerAndURL(networkManager,url){for(const request of this._requests){if(url===request.url()&&networkManager===SDK.NetworkManager.forRequest(request))
return request;}
return null;}
_initializeInitiatorSymbolIfNeeded(request){if(!request[SDK.NetworkLog._initiatorDataSymbol]){request[SDK.NetworkLog._initiatorDataSymbol]={info:null,chain:null,request:undefined,};}}
initiatorInfoForRequest(request){this._initializeInitiatorSymbolIfNeeded(request);if(request[SDK.NetworkLog._initiatorDataSymbol].info)
return request[SDK.NetworkLog._initiatorDataSymbol].info;let type=SDK.NetworkRequest.InitiatorType.Other;let url='';let lineNumber=-Infinity;let columnNumber=-Infinity;let scriptId=null;let initiatorStack=null;const initiator=request.initiator();const redirectSource=request.redirectSource();if(redirectSource){type=SDK.NetworkRequest.InitiatorType.Redirect;url=redirectSource.url();}else if(initiator){if(initiator.type===Protocol.Network.InitiatorType.Parser){type=SDK.NetworkRequest.InitiatorType.Parser;url=initiator.url?initiator.url:url;lineNumber=initiator.lineNumber?initiator.lineNumber:lineNumber;}else if(initiator.type===Protocol.Network.InitiatorType.Script){for(let stack=initiator.stack;stack;stack=stack.parent){const topFrame=stack.callFrames.length?stack.callFrames[0]:null;if(!topFrame)
continue;type=SDK.NetworkRequest.InitiatorType.Script;url=topFrame.url||Common.UIString('<anonymous>');lineNumber=topFrame.lineNumber;columnNumber=topFrame.columnNumber;scriptId=topFrame.scriptId;break;}
if(!initiator.stack&&initiator.url){type=SDK.NetworkRequest.InitiatorType.Script;url=initiator.url;lineNumber=initiator.lineNumber||0;}
if(initiator.stack&&initiator.stack.callFrames&&initiator.stack.callFrames.length)
initiatorStack=initiator.stack||null;}else if(initiator.type===Protocol.Network.InitiatorType.Preload){type=SDK.NetworkRequest.InitiatorType.Preload;}else if(initiator.type===Protocol.Network.InitiatorType.SignedExchange){type=SDK.NetworkRequest.InitiatorType.SignedExchange;url=initiator.url;}}
request[SDK.NetworkLog._initiatorDataSymbol].info={type:type,url:url,lineNumber:lineNumber,columnNumber:columnNumber,scriptId:scriptId,stack:initiatorStack};return request[SDK.NetworkLog._initiatorDataSymbol].info;}
initiatorGraphForRequest(request){const initiated=new Set();const networkManager=SDK.NetworkManager.forRequest(request);for(const otherRequest of this._requests){const otherRequestManager=SDK.NetworkManager.forRequest(request);if(networkManager===otherRequestManager&&this._initiatorChain(otherRequest).has(request))
initiated.add(otherRequest);}
return{initiators:this._initiatorChain(request),initiated:initiated};}
_initiatorChain(request){this._initializeInitiatorSymbolIfNeeded(request);let initiatorChainCache=(request[SDK.NetworkLog._initiatorDataSymbol].chain);if(initiatorChainCache)
return initiatorChainCache;initiatorChainCache=new Set();let checkRequest=request;do{if(checkRequest[SDK.NetworkLog._initiatorDataSymbol].chain){initiatorChainCache.addAll(checkRequest[SDK.NetworkLog._initiatorDataSymbol].chain);break;}
if(initiatorChainCache.has(checkRequest))
break;initiatorChainCache.add(checkRequest);checkRequest=this._initiatorRequest(checkRequest);}while(checkRequest);request[SDK.NetworkLog._initiatorDataSymbol].chain=initiatorChainCache;return initiatorChainCache;}
_initiatorRequest(request){this._initializeInitiatorSymbolIfNeeded(request);if(request[SDK.NetworkLog._initiatorDataSymbol].request!==undefined)
return request[SDK.NetworkLog._initiatorDataSymbol].request;const url=this.initiatorInfoForRequest(request).url;const networkManager=SDK.NetworkManager.forRequest(request);request[SDK.NetworkLog._initiatorDataSymbol].request=networkManager?this._requestByManagerAndURL(networkManager,url):null;return request[SDK.NetworkLog._initiatorDataSymbol].request;}
_willReloadPage(){if(!Common.moduleSetting('network_log.preserve-log').get())
this.reset();}
_onMainFrameNavigated(event){const mainFrame=(event.data);const manager=mainFrame.resourceTreeModel().target().model(SDK.NetworkManager);if(!manager||mainFrame.resourceTreeModel().target().parentTarget())
return;const oldRequests=this._requests;const oldManagerRequests=this._requests.filter(request=>SDK.NetworkManager.forRequest(request)===manager);const oldRequestsSet=this._requestsSet;this._requests=[];this._requestsSet=new Set();this.dispatchEventToListeners(SDK.NetworkLog.Events.Reset);let currentPageLoad=null;const requestsToAdd=[];for(const request of oldManagerRequests){if(request.loaderId!==mainFrame.loaderId)
continue;if(!currentPageLoad){currentPageLoad=new SDK.NetworkLog.PageLoad(request);let redirectSource=request.redirectSource();while(redirectSource){requestsToAdd.push(redirectSource);redirectSource=redirectSource.redirectSource();}}
requestsToAdd.push(request);}
const serviceWorkerRequestsToAdd=[];for(const swRequest of oldRequests){const networkManager=SDK.NetworkManager.forRequest(swRequest);if(!networkManager)
continue;const target=networkManager.target();if(!(target.type()===SDK.Target.Type.Worker&&target.parentTarget()&&target.parentTarget().type()===SDK.Target.Type.ServiceWorker))
continue;const keepRequest=requestsToAdd.some(request=>request.url()===swRequest.url()&&request.issueTime()<=swRequest.issueTime());if(keepRequest)
serviceWorkerRequestsToAdd.push(swRequest);}
requestsToAdd.push(...serviceWorkerRequestsToAdd);for(const request of requestsToAdd){oldRequestsSet.delete(request);this._requests.push(request);this._requestsSet.add(request);currentPageLoad.bindRequest(request);this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestAdded,request);}
if(Common.moduleSetting('network_log.preserve-log').get()){for(const request of oldRequestsSet){this._requests.push(request);this._requestsSet.add(request);this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestAdded,request);}}
if(currentPageLoad)
this._pageLoadForManager.set(manager,currentPageLoad);}
importRequests(requests){this.reset();this._requests=[];this._requestsSet.clear();for(const request of requests){this._requests.push(request);this._requestsSet.add(request);this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestAdded,request);}}
_onRequestStarted(event){const request=(event.data);this._requests.push(request);this._requestsSet.add(request);const manager=SDK.NetworkManager.forRequest(request);const pageLoad=manager?this._pageLoadForManager.get(manager):null;if(pageLoad)
pageLoad.bindRequest(request);this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestAdded,request);}
_onRequestUpdated(event){const request=(event.data);if(!this._requestsSet.has(request))
return;this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestUpdated,request);}
_onRequestRedirect(event){const request=(event.data);delete request[SDK.NetworkLog._initiatorDataSymbol];}
_onDOMContentLoaded(resourceTreeModel,event){const networkManager=resourceTreeModel.target().model(SDK.NetworkManager);const pageLoad=networkManager?this._pageLoadForManager.get(networkManager):null;if(pageLoad)
pageLoad.contentLoadTime=(event.data);}
_onLoad(event){const networkManager=event.data.resourceTreeModel.target().model(SDK.NetworkManager);const pageLoad=networkManager?this._pageLoadForManager.get(networkManager):null;if(pageLoad)
pageLoad.loadTime=(event.data.loadTime);}
reset(){this._requests=[];this._requestsSet.clear();const managers=new Set(SDK.targetManager.models(SDK.NetworkManager));for(const manager of this._pageLoadForManager.keys()){if(!managers.has(manager))
this._pageLoadForManager.delete(manager);}
this.dispatchEventToListeners(SDK.NetworkLog.Events.Reset);}
_networkMessageGenerated(networkManager,event){const message=(event.data);const consoleMessage=new SDK.ConsoleMessage(networkManager.target().model(SDK.RuntimeModel),SDK.ConsoleMessage.MessageSource.Network,message.warning?SDK.ConsoleMessage.MessageLevel.Warning:SDK.ConsoleMessage.MessageLevel.Info,message.message);this.associateConsoleMessageWithRequest(consoleMessage,message.requestId);SDK.consoleModel.addMessage(consoleMessage);}
associateConsoleMessageWithRequest(consoleMessage,requestId){const target=consoleMessage.target();const networkManager=target?target.model(SDK.NetworkManager):null;if(!networkManager)
return;const request=this.requestByManagerAndId(networkManager,requestId);if(!request)
return;consoleMessage[SDK.NetworkLog._requestSymbol]=request;const initiator=request.initiator();if(initiator){consoleMessage.stackTrace=initiator.stack||undefined;if(initiator.url){consoleMessage.url=initiator.url;consoleMessage.line=initiator.lineNumber||0;}}}
static requestForConsoleMessage(consoleMessage){return consoleMessage[SDK.NetworkLog._requestSymbol]||null;}};SDK.NetworkLog.PageLoad=class{constructor(mainRequest){this.id=++SDK.NetworkLog.PageLoad._lastIdentifier;this.url=mainRequest.url();this.startTime=mainRequest.startTime;this.loadTime;this.contentLoadTime;this.mainRequest=mainRequest;this._showDataSaverWarningIfNeeded();}
async _showDataSaverWarningIfNeeded(){const manager=SDK.NetworkManager.forRequest(this.mainRequest);if(!manager)
return;if(!this.mainRequest.finished)
await this.mainRequest.once(SDK.NetworkRequest.Events.FinishedLoading);const saveDataHeader=this.mainRequest.requestHeaderValue('Save-Data');if(!SDK.NetworkLog.PageLoad._dataSaverMessageWasShown&&saveDataHeader&&saveDataHeader==='on'){const message=Common.UIString('Consider disabling %s while debugging. For more info see: %s',Common.UIString('Chrome Data Saver'),'https://support.google.com/chrome/?p=datasaver');manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:this.mainRequest.requestId(),warning:true});SDK.NetworkLog.PageLoad._dataSaverMessageWasShown=true;}}
static forRequest(request){return request[SDK.NetworkLog.PageLoad._pageLoadForRequestSymbol]||null;}
bindRequest(request){request[SDK.NetworkLog.PageLoad._pageLoadForRequestSymbol]=this;}};SDK.NetworkLog.PageLoad._lastIdentifier=0;SDK.NetworkLog.PageLoad._pageLoadForRequestSymbol=Symbol('PageLoadForRequest');SDK.NetworkLog._requestSymbol=Symbol('_request');SDK.NetworkLog.PageLoad._dataSaverMessageWasShown=false;SDK.NetworkLog.InitiatorGraph;SDK.NetworkLog.Events={Reset:Symbol('Reset'),RequestAdded:Symbol('RequestAdded'),RequestUpdated:Symbol('RequestUpdated')};SDK.NetworkLog._InitiatorInfo;SDK.NetworkLog._initiatorDataSymbol=Symbol('InitiatorData');SDK.NetworkLog._events=Symbol('SDK.NetworkLog.events');SDK.networkLog=new SDK.NetworkLog();;SDK.NetworkRequest=class extends Common.Object{constructor(requestId,url,documentURL,frameId,loaderId,initiator){super();this._requestId=requestId;this._backendRequestId=requestId;this.setUrl(url);this._documentURL=documentURL;this._frameId=frameId;this._loaderId=loaderId;this._initiator=initiator;this._redirectSource=null;this._redirectDestination=null;this._issueTime=-1;this._startTime=-1;this._endTime=-1;this._blockedReason=undefined;this.statusCode=0;this.statusText='';this.requestMethod='';this.requestTime=0;this.protocol='';this.mixedContentType=Protocol.Security.MixedContentType.None;this._initialPriority=null;this._currentPriority=null;this._signedExchangeInfo=null;this._resourceType=Common.resourceTypes.Other;this._contentData=null;this._frames=[];this._eventSourceMessages=[];this._responseHeaderValues={};this._responseHeadersText='';this._requestHeaders=[];this._requestHeaderValues={};this._remoteAddress='';this._referrerPolicy=null;this._securityState=Protocol.Security.SecurityState.Unknown;this._securityDetails=null;this.connectionId='0';this._formParametersPromise=null;this._requestFormDataPromise=(Promise.resolve(null));}
indentityCompare(other){const thisId=this.requestId();const thatId=other.requestId();if(thisId>thatId)
return 1;if(thisId<thatId)
return-1;return 0;}
requestId(){return this._requestId;}
backendRequestId(){return this._backendRequestId;}
url(){return this._url;}
isBlobRequest(){return this._url.startsWith('blob:');}
setUrl(x){if(this._url===x)
return;this._url=x;this._parsedURL=new Common.ParsedURL(x);delete this._queryString;delete this._parsedQueryParameters;delete this._name;delete this._path;}
get documentURL(){return this._documentURL;}
get parsedURL(){return this._parsedURL;}
get frameId(){return this._frameId;}
get loaderId(){return this._loaderId;}
setRemoteAddress(ip,port){this._remoteAddress=ip+':'+port;this.dispatchEventToListeners(SDK.NetworkRequest.Events.RemoteAddressChanged,this);}
remoteAddress(){return this._remoteAddress;}
setReferrerPolicy(referrerPolicy){this._referrerPolicy=referrerPolicy;}
referrerPolicy(){return this._referrerPolicy;}
securityState(){return this._securityState;}
setSecurityState(securityState){this._securityState=securityState;}
securityDetails(){return this._securityDetails;}
setSecurityDetails(securityDetails){this._securityDetails=securityDetails;}
get startTime(){return this._startTime||-1;}
setIssueTime(monotonicTime,wallTime){this._issueTime=monotonicTime;this._wallIssueTime=wallTime;this._startTime=monotonicTime;}
issueTime(){return this._issueTime;}
pseudoWallTime(monotonicTime){return this._wallIssueTime?this._wallIssueTime-this._issueTime+monotonicTime:monotonicTime;}
get responseReceivedTime(){return this._responseReceivedTime||-1;}
set responseReceivedTime(x){this._responseReceivedTime=x;}
get endTime(){return this._endTime||-1;}
set endTime(x){if(this.timing&&this.timing.requestTime){this._endTime=Math.max(x,this.responseReceivedTime);}else{this._endTime=x;if(this._responseReceivedTime>x)
this._responseReceivedTime=x;}
this.dispatchEventToListeners(SDK.NetworkRequest.Events.TimingChanged,this);}
get duration(){if(this._endTime===-1||this._startTime===-1)
return-1;return this._endTime-this._startTime;}
get latency(){if(this._responseReceivedTime===-1||this._startTime===-1)
return-1;return this._responseReceivedTime-this._startTime;}
get resourceSize(){return this._resourceSize||0;}
set resourceSize(x){this._resourceSize=x;}
get transferSize(){return this._transferSize||0;}
increaseTransferSize(x){this._transferSize=(this._transferSize||0)+x;}
setTransferSize(x){this._transferSize=x;}
get finished(){return this._finished;}
set finished(x){if(this._finished===x)
return;this._finished=x;if(x)
this.dispatchEventToListeners(SDK.NetworkRequest.Events.FinishedLoading,this);}
get failed(){return this._failed;}
set failed(x){this._failed=x;}
get canceled(){return this._canceled;}
set canceled(x){this._canceled=x;}
blockedReason(){return this._blockedReason;}
setBlockedReason(reason){this._blockedReason=reason;}
wasBlocked(){return!!this._blockedReason;}
cached(){return(!!this._fromMemoryCache||!!this._fromDiskCache)&&!this._transferSize;}
cachedInMemory(){return!!this._fromMemoryCache&&!this._transferSize;}
fromPrefetchCache(){return!!this._fromPrefetchCache;}
setFromMemoryCache(){this._fromMemoryCache=true;delete this._timing;}
setFromDiskCache(){this._fromDiskCache=true;}
setFromPrefetchCache(){this._fromPrefetchCache=true;}
get fetchedViaServiceWorker(){return!!this._fetchedViaServiceWorker;}
set fetchedViaServiceWorker(x){this._fetchedViaServiceWorker=x;}
initiatedByServiceWorker(){const networkManager=SDK.NetworkManager.forRequest(this);if(!networkManager)
return false;return networkManager.target().type()===SDK.Target.Type.Worker&&!!networkManager.target().parentTarget()&&networkManager.target().parentTarget().type()===SDK.Target.Type.ServiceWorker;}
get timing(){return this._timing;}
set timing(timingInfo){if(!timingInfo||this._fromMemoryCache)
return;this._startTime=timingInfo.requestTime;const headersReceivedTime=timingInfo.requestTime+timingInfo.receiveHeadersEnd/1000.0;if((this._responseReceivedTime||-1)<0||this._responseReceivedTime>headersReceivedTime)
this._responseReceivedTime=headersReceivedTime;if(this._startTime>this._responseReceivedTime)
this._responseReceivedTime=this._startTime;this._timing=timingInfo;this.dispatchEventToListeners(SDK.NetworkRequest.Events.TimingChanged,this);}
get mimeType(){return this._mimeType;}
set mimeType(x){this._mimeType=x;}
get displayName(){return this._parsedURL.displayName;}
name(){if(this._name)
return this._name;this._parseNameAndPathFromURL();return this._name;}
path(){if(this._path)
return this._path;this._parseNameAndPathFromURL();return this._path;}
_parseNameAndPathFromURL(){if(this._parsedURL.isDataURL()){this._name=this._parsedURL.dataURLDisplayName();this._path='';}else if(this._parsedURL.isBlobURL()){this._name=this._parsedURL.url;this._path='';}else if(this._parsedURL.isAboutBlank()){this._name=this._parsedURL.url;this._path='';}else{this._path=this._parsedURL.host+this._parsedURL.folderPathComponents;const networkManager=SDK.NetworkManager.forRequest(this);const inspectedURL=networkManager?networkManager.target().inspectedURL().asParsedURL():null;this._path=this._path.trimURL(inspectedURL?inspectedURL.host:'');if(this._parsedURL.lastPathComponent||this._parsedURL.queryParams){this._name=this._parsedURL.lastPathComponent+(this._parsedURL.queryParams?'?'+this._parsedURL.queryParams:'');}else if(this._parsedURL.folderPathComponents){this._name=this._parsedURL.folderPathComponents.substring(this._parsedURL.folderPathComponents.lastIndexOf('/')+1)+'/';this._path=this._path.substring(0,this._path.lastIndexOf('/'));}else{this._name=this._parsedURL.host;this._path='';}}}
get folder(){let path=this._parsedURL.path;const indexOfQuery=path.indexOf('?');if(indexOfQuery!==-1)
path=path.substring(0,indexOfQuery);const lastSlashIndex=path.lastIndexOf('/');return lastSlashIndex!==-1?path.substring(0,lastSlashIndex):'';}
resourceType(){return this._resourceType;}
setResourceType(resourceType){this._resourceType=resourceType;}
get domain(){return this._parsedURL.host;}
get scheme(){return this._parsedURL.scheme;}
redirectSource(){return this._redirectSource;}
setRedirectSource(originatingRequest){this._redirectSource=originatingRequest;}
redirectDestination(){return this._redirectDestination;}
setRedirectDestination(redirectDestination){this._redirectDestination=redirectDestination;}
requestHeaders(){return this._requestHeaders;}
setRequestHeaders(headers){this._requestHeaders=headers;delete this._requestCookies;this.dispatchEventToListeners(SDK.NetworkRequest.Events.RequestHeadersChanged);}
requestHeadersText(){return this._requestHeadersText;}
setRequestHeadersText(text){this._requestHeadersText=text;this.dispatchEventToListeners(SDK.NetworkRequest.Events.RequestHeadersChanged);}
requestHeaderValue(headerName){if(headerName in this._requestHeaderValues)
return this._requestHeaderValues[headerName];this._requestHeaderValues[headerName]=this._computeHeaderValue(this.requestHeaders(),headerName);return this._requestHeaderValues[headerName];}
get requestCookies(){if(!this._requestCookies)
this._requestCookies=SDK.CookieParser.parseCookie(this.requestHeaderValue('Cookie'));return this._requestCookies;}
requestFormData(){if(!this._requestFormDataPromise)
this._requestFormDataPromise=SDK.NetworkManager.requestPostData(this);return this._requestFormDataPromise;}
setRequestFormData(hasData,data){this._requestFormDataPromise=(hasData&&data===null)?null:Promise.resolve(data);this._formParametersPromise=null;}
_filteredProtocolName(){const protocol=this.protocol.toLowerCase();if(protocol==='h2')
return'http/2.0';return protocol.replace(/^http\/2(\.0)?\+/,'http/2.0+');}
requestHttpVersion(){const headersText=this.requestHeadersText();if(!headersText){const version=this.requestHeaderValue('version')||this.requestHeaderValue(':version');if(version)
return version;return this._filteredProtocolName();}
const firstLine=headersText.split(/\r\n/)[0];const match=firstLine.match(/(HTTP\/\d+\.\d+)$/);return match?match[1]:'HTTP/0.9';}
get responseHeaders(){return this._responseHeaders||[];}
set responseHeaders(x){this._responseHeaders=x;delete this._sortedResponseHeaders;delete this._serverTimings;delete this._responseCookies;this._responseHeaderValues={};this.dispatchEventToListeners(SDK.NetworkRequest.Events.ResponseHeadersChanged);}
get responseHeadersText(){return this._responseHeadersText;}
set responseHeadersText(x){this._responseHeadersText=x;this.dispatchEventToListeners(SDK.NetworkRequest.Events.ResponseHeadersChanged);}
get sortedResponseHeaders(){if(this._sortedResponseHeaders!==undefined)
return this._sortedResponseHeaders;this._sortedResponseHeaders=this.responseHeaders.slice();this._sortedResponseHeaders.sort(function(a,b){return a.name.toLowerCase().compareTo(b.name.toLowerCase());});return this._sortedResponseHeaders;}
responseHeaderValue(headerName){if(headerName in this._responseHeaderValues)
return this._responseHeaderValues[headerName];this._responseHeaderValues[headerName]=this._computeHeaderValue(this.responseHeaders,headerName);return this._responseHeaderValues[headerName];}
get responseCookies(){if(!this._responseCookies)
this._responseCookies=SDK.CookieParser.parseSetCookie(this.responseHeaderValue('Set-Cookie'));return this._responseCookies;}
responseLastModified(){return this.responseHeaderValue('last-modified');}
get serverTimings(){if(typeof this._serverTimings==='undefined')
this._serverTimings=SDK.ServerTiming.parseHeaders(this.responseHeaders);return this._serverTimings;}
queryString(){if(this._queryString!==undefined)
return this._queryString;let queryString=null;const url=this.url();const questionMarkPosition=url.indexOf('?');if(questionMarkPosition!==-1){queryString=url.substring(questionMarkPosition+1);const hashSignPosition=queryString.indexOf('#');if(hashSignPosition!==-1)
queryString=queryString.substring(0,hashSignPosition);}
this._queryString=queryString;return this._queryString;}
get queryParameters(){if(this._parsedQueryParameters)
return this._parsedQueryParameters;const queryString=this.queryString();if(!queryString)
return null;this._parsedQueryParameters=this._parseParameters(queryString);return this._parsedQueryParameters;}
async _parseFormParameters(){const requestContentType=this.requestContentType();if(!requestContentType)
return null;if(requestContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)){const formData=await this.requestFormData();if(!formData)
return null;return this._parseParameters(formData);}
const multipartDetails=requestContentType.match(/^multipart\/form-data\s*;\s*boundary\s*=\s*(\S+)\s*$/);if(!multipartDetails)
return null;const boundary=multipartDetails[1];if(!boundary)
return null;const formData=await this.requestFormData();if(!formData)
return null;return this._parseMultipartFormDataParameters(formData,boundary);}
formParameters(){if(!this._formParametersPromise)
this._formParametersPromise=this._parseFormParameters();return this._formParametersPromise;}
responseHttpVersion(){const headersText=this._responseHeadersText;if(!headersText){const version=this.responseHeaderValue('version')||this.responseHeaderValue(':version');if(version)
return version;return this._filteredProtocolName();}
const firstLine=headersText.split(/\r\n/)[0];const match=firstLine.match(/^(HTTP\/\d+\.\d+)/);return match?match[1]:'HTTP/0.9';}
_parseParameters(queryString){function parseNameValue(pair){const position=pair.indexOf('=');if(position===-1)
return{name:pair,value:''};else
return{name:pair.substring(0,position),value:pair.substring(position+1)};}
return queryString.split('&').map(parseNameValue);}
_parseMultipartFormDataParameters(data,boundary){const sanitizedBoundary=boundary.escapeForRegExp();const keyValuePattern=new RegExp('^\\r\\ncontent-disposition\\s*:\\s*form-data\\s*;\\s*name="([^"]*)"(?:\\s*;\\s*filename="([^"]*)")?'+'(?:\\r\\ncontent-type\\s*:\\s*([^\\r\\n]*))?'+'\\r\\n\\r\\n'+'(.*)'+'\\r\\n$','is');const fields=data.split(new RegExp(`--${sanitizedBoundary}(?:--\s*$)?`,'g'));return fields.reduce(parseMultipartField,[]);function parseMultipartField(result,field){const[match,name,filename,contentType,value]=field.match(keyValuePattern)||[];if(!match)
return result;const processedValue=(filename||contentType)?ls`(binary)`:value;result.push({name,value:processedValue});return result;}}
_computeHeaderValue(headers,headerName){headerName=headerName.toLowerCase();const values=[];for(let i=0;i<headers.length;++i){if(headers[i].name.toLowerCase()===headerName)
values.push(headers[i].value);}
if(!values.length)
return undefined;if(headerName==='set-cookie')
return values.join('\n');return values.join(', ');}
contentData(){if(this._contentData)
return this._contentData;if(this._contentDataProvider)
this._contentData=this._contentDataProvider();else
this._contentData=SDK.NetworkManager.requestContentData(this);return this._contentData;}
setContentDataProvider(dataProvider){console.assert(!this._contentData,'contentData can only be set once.');this._contentDataProvider=dataProvider;}
contentURL(){return this._url;}
contentType(){return this._resourceType;}
async contentEncoded(){return(await this.contentData()).encoded;}
async requestContent(){return(await this.contentData()).content;}
async searchInContent(query,caseSensitive,isRegex){if(!this._contentDataProvider)
return SDK.NetworkManager.searchInRequest(this,query,caseSensitive,isRegex);const contentData=await this.contentData();let content=contentData.content;if(!content)
return[];if(contentData.encoded)
content=window.atob(content);return Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex);}
isHttpFamily(){return!!this.url().match(/^https?:/i);}
requestContentType(){return this.requestHeaderValue('Content-Type');}
hasErrorStatusCode(){return this.statusCode>=400;}
setInitialPriority(priority){this._initialPriority=priority;}
initialPriority(){return this._initialPriority;}
setPriority(priority){this._currentPriority=priority;}
priority(){return this._currentPriority||this._initialPriority||null;}
setSignedExchangeInfo(info){this._signedExchangeInfo=info;}
signedExchangeInfo(){return this._signedExchangeInfo;}
async populateImageSource(image){const{content,encoded}=await this.contentData();let imageSrc=Common.ContentProvider.contentAsDataURL(content,this._mimeType,encoded);if(imageSrc===null&&!this._failed){const cacheControl=this.responseHeaderValue('cache-control')||'';if(!cacheControl.includes('no-cache'))
imageSrc=this._url;}
if(imageSrc!==null)
image.src=imageSrc;}
initiator(){return this._initiator;}
frames(){return this._frames;}
addProtocolFrameError(errorMessage,time){this.addFrame({type:SDK.NetworkRequest.WebSocketFrameType.Error,text:errorMessage,time:this.pseudoWallTime(time),opCode:-1,mask:false});}
addProtocolFrame(response,time,sent){const type=sent?SDK.NetworkRequest.WebSocketFrameType.Send:SDK.NetworkRequest.WebSocketFrameType.Receive;this.addFrame({type:type,text:response.payloadData,time:this.pseudoWallTime(time),opCode:response.opcode,mask:response.mask});}
addFrame(frame){this._frames.push(frame);this.dispatchEventToListeners(SDK.NetworkRequest.Events.WebsocketFrameAdded,frame);}
eventSourceMessages(){return this._eventSourceMessages;}
addEventSourceMessage(time,eventName,eventId,data){const message={time:this.pseudoWallTime(time),eventName:eventName,eventId:eventId,data:data};this._eventSourceMessages.push(message);this.dispatchEventToListeners(SDK.NetworkRequest.Events.EventSourceMessageAdded,message);}
markAsRedirect(redirectCount){this._requestId=`${this._backendRequestId}:redirected.${redirectCount}`;}
setRequestIdForTest(requestId){this._backendRequestId=requestId;this._requestId=requestId;}
charset(){const contentTypeHeader=this.responseHeaderValue('content-type');if(!contentTypeHeader)
return null;const responseCharsets=contentTypeHeader.replace(/ /g,'').split(';').filter(parameter=>parameter.toLowerCase().startsWith('charset=')).map(parameter=>parameter.slice('charset='.length));if(responseCharsets.length)
return responseCharsets[0];return null;}};SDK.NetworkRequest.Events={FinishedLoading:Symbol('FinishedLoading'),TimingChanged:Symbol('TimingChanged'),RemoteAddressChanged:Symbol('RemoteAddressChanged'),RequestHeadersChanged:Symbol('RequestHeadersChanged'),ResponseHeadersChanged:Symbol('ResponseHeadersChanged'),WebsocketFrameAdded:Symbol('WebsocketFrameAdded'),EventSourceMessageAdded:Symbol('EventSourceMessageAdded')};SDK.NetworkRequest.InitiatorType={Other:'other',Parser:'parser',Redirect:'redirect',Script:'script',Preload:'preload',SignedExchange:'signedExchange'};SDK.NetworkRequest.NameValue;SDK.NetworkRequest.WebSocketFrameType={Send:'send',Receive:'receive',Error:'error'};SDK.NetworkRequest.WebSocketFrame;SDK.NetworkRequest.EventSourceMessage;SDK.NetworkRequest.ContentData;;SDK.PaintProfilerModel=class extends SDK.SDKModel{constructor(target){super(target);this._layerTreeAgent=target.layerTreeAgent();}
async loadSnapshotFromFragments(fragments){const snapshotId=await this._layerTreeAgent.loadSnapshot(fragments);return snapshotId&&new SDK.PaintProfilerSnapshot(this,snapshotId);}
loadSnapshot(encodedPicture){const fragment={x:0,y:0,picture:encodedPicture};return this.loadSnapshotFromFragments([fragment]);}
async makeSnapshot(layerId){const snapshotId=await this._layerTreeAgent.makeSnapshot(layerId);return snapshotId&&new SDK.PaintProfilerSnapshot(this,snapshotId);}};SDK.SDKModel.register(SDK.PaintProfilerModel,SDK.Target.Capability.DOM,false);SDK.PictureFragment;SDK.PaintProfilerSnapshot=class{constructor(paintProfilerModel,snapshotId){this._paintProfilerModel=paintProfilerModel;this._id=snapshotId;this._refCount=1;}
release(){console.assert(this._refCount>0,'release is already called on the object');if(!--this._refCount)
this._paintProfilerModel._layerTreeAgent.releaseSnapshot(this._id);}
addReference(){++this._refCount;console.assert(this._refCount>0,'Referencing a dead object');}
replay(scale,firstStep,lastStep){return this._paintProfilerModel._layerTreeAgent.replaySnapshot(this._id,firstStep,lastStep,scale||1.0);}
profile(clipRect){return this._paintProfilerModel._layerTreeAgent.profileSnapshot(this._id,5,1,clipRect||undefined);}
async commandLog(){const log=await this._paintProfilerModel._layerTreeAgent.snapshotCommandLog(this._id);return log&&log.map((entry,index)=>new SDK.PaintProfilerLogItem(entry,index));}};SDK.RawPaintProfilerLogItem;SDK.PaintProfilerLogItem=class{constructor(rawEntry,commandIndex){this.method=rawEntry.method;this.params=rawEntry.params;this.commandIndex=commandIndex;}};;SDK.HeapProfilerModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerHeapProfilerDispatcher(new SDK.HeapProfilerDispatcher(this));this._enabled=false;this._heapProfilerAgent=target.heapProfilerAgent();this._memoryAgent=target.memoryAgent();this._runtimeModel=(target.model(SDK.RuntimeModel));this._samplingProfilerDepth=0;}
debuggerModel(){return this._runtimeModel.debuggerModel();}
runtimeModel(){return this._runtimeModel;}
enable(){if(this._enabled)
return;this._enabled=true;this._heapProfilerAgent.enable();}
startSampling(samplingRateInBytes){if(this._samplingProfilerDepth++)
return;const defaultSamplingIntervalInBytes=16384;this._heapProfilerAgent.startSampling(samplingRateInBytes||defaultSamplingIntervalInBytes);}
stopSampling(){if(!this._samplingProfilerDepth)
throw new Error('Sampling profiler is not running.');if(--this._samplingProfilerDepth)
return this.getSamplingProfile();return this._heapProfilerAgent.stopSampling();}
getSamplingProfile(){return this._heapProfilerAgent.getSamplingProfile();}
startNativeSampling(){const defaultSamplingIntervalInBytes=65536;this._memoryAgent.startSampling(defaultSamplingIntervalInBytes);}
async stopNativeSampling(){const rawProfile=await this._memoryAgent.getSamplingProfile();this._memoryAgent.stopSampling();return this._convertNativeProfile(rawProfile);}
async takeNativeSnapshot(){const rawProfile=await this._memoryAgent.getAllTimeSamplingProfile();return this._convertNativeProfile(rawProfile);}
async takeNativeBrowserSnapshot(){const rawProfile=await this._memoryAgent.getBrowserSamplingProfile();return this._convertNativeProfile(rawProfile);}
_convertNativeProfile(rawProfile){const head=({children:new Map(),selfSize:0,callFrame:{functionName:'(root)',url:''}});for(const sample of rawProfile.samples){const node=sample.stack.reverse().reduce((node,name)=>{let child=node.children.get(name);if(child)
return child;const namespace=/^([^:]*)::/.exec(name);child={children:new Map(),callFrame:{functionName:name,url:namespace&&namespace[1]||''},selfSize:0};node.children.set(name,child);return child;},head);node.selfSize+=sample.total;}
function convertChildren(node){node.children=Array.from(node.children.values());node.children.forEach(convertChildren);}
convertChildren(head);return new SDK.HeapProfilerModel.NativeHeapProfile(head,rawProfile.modules);}
collectGarbage(){return this._heapProfilerAgent.collectGarbage();}
snapshotObjectIdForObjectId(objectId){return this._heapProfilerAgent.getHeapObjectId(objectId);}
async objectForSnapshotObjectId(snapshotObjectId,objectGroupName){const result=await this._heapProfilerAgent.getObjectByHeapObjectId(snapshotObjectId,objectGroupName);return result&&result.type&&this._runtimeModel.createRemoteObject(result)||null;}
addInspectedHeapObject(snapshotObjectId){return this._heapProfilerAgent.addInspectedHeapObject(snapshotObjectId);}
takeHeapSnapshot(reportProgress){return this._heapProfilerAgent.takeHeapSnapshot(reportProgress);}
startTrackingHeapObjects(recordAllocationStacks){return this._heapProfilerAgent.startTrackingHeapObjects(recordAllocationStacks);}
stopTrackingHeapObjects(reportProgress){return this._heapProfilerAgent.stopTrackingHeapObjects(reportProgress);}
heapStatsUpdate(samples){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.HeapStatsUpdate,samples);}
lastSeenObjectId(lastSeenObjectId,timestamp){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.LastSeenObjectId,{lastSeenObjectId:lastSeenObjectId,timestamp:timestamp});}
addHeapSnapshotChunk(chunk){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.AddHeapSnapshotChunk,chunk);}
reportHeapSnapshotProgress(done,total,finished){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.ReportHeapSnapshotProgress,{done:done,total:total,finished:finished});}
resetProfiles(){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.ResetProfiles,this);}};SDK.SDKModel.register(SDK.HeapProfilerModel,SDK.Target.Capability.JS,false);SDK.HeapProfilerModel.Events={HeapStatsUpdate:Symbol('HeapStatsUpdate'),LastSeenObjectId:Symbol('LastSeenObjectId'),AddHeapSnapshotChunk:Symbol('AddHeapSnapshotChunk'),ReportHeapSnapshotProgress:Symbol('ReportHeapSnapshotProgress'),ResetProfiles:Symbol('ResetProfiles')};SDK.HeapProfilerModel.NativeHeapProfile=class{constructor(head,modules){this.head=head;this.modules=modules;}};SDK.HeapProfilerDispatcher=class{constructor(model){this._heapProfilerModel=model;}
heapStatsUpdate(samples){this._heapProfilerModel.heapStatsUpdate(samples);}
lastSeenObjectId(lastSeenObjectId,timestamp){this._heapProfilerModel.lastSeenObjectId(lastSeenObjectId,timestamp);}
addHeapSnapshotChunk(chunk){this._heapProfilerModel.addHeapSnapshotChunk(chunk);}
reportHeapSnapshotProgress(done,total,finished){this._heapProfilerModel.reportHeapSnapshotProgress(done,total,finished);}
resetProfiles(){this._heapProfilerModel.resetProfiles();}};;SDK.PerformanceMetricsModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.performanceAgent();const mode=SDK.PerformanceMetricsModel.MetricMode;this._metricModes=new Map([['TaskDuration',mode.CumulativeTime],['ScriptDuration',mode.CumulativeTime],['LayoutDuration',mode.CumulativeTime],['RecalcStyleDuration',mode.CumulativeTime],['LayoutCount',mode.CumulativeCount],['RecalcStyleCount',mode.CumulativeCount]]);this._metricData=new Map();}
enable(){return this._agent.enable();}
disable(){return this._agent.disable();}
async requestMetrics(){const rawMetrics=await this._agent.getMetrics()||[];const metrics=new Map();const timestamp=performance.now();for(const metric of rawMetrics){let data=this._metricData.get(metric.name);if(!data){data={};this._metricData.set(metric.name,data);}
let value;switch(this._metricModes.get(metric.name)){case SDK.PerformanceMetricsModel.MetricMode.CumulativeTime:value=data.lastTimestamp?Number.constrain((metric.value-data.lastValue)*1000/(timestamp-data.lastTimestamp),0,1):0;data.lastValue=metric.value;data.lastTimestamp=timestamp;break;case SDK.PerformanceMetricsModel.MetricMode.CumulativeCount:value=data.lastTimestamp?Math.max(0,(metric.value-data.lastValue)*1000/(timestamp-data.lastTimestamp)):0;data.lastValue=metric.value;data.lastTimestamp=timestamp;break;default:value=metric.value;break;}
metrics.set(metric.name,value);}
return{metrics:metrics,timestamp:timestamp};}};SDK.PerformanceMetricsModel.MetricMode={CumulativeTime:Symbol('CumulativeTime'),CumulativeCount:Symbol('CumulativeCount'),};SDK.SDKModel.register(SDK.PerformanceMetricsModel,SDK.Target.Capability.Browser,false);;SDK.CSSMetadata._generatedProperties=[{"name":"-webkit-app-region"},{"name":"-webkit-appearance"},{"name":"-webkit-border-horizontal-spacing","inherited":true},{"name":"-webkit-border-image"},{"name":"-webkit-border-vertical-spacing","inherited":true},{"name":"-webkit-box-align"},{"name":"-webkit-box-decoration-break"},{"name":"-webkit-box-direction","inherited":true},{"name":"-webkit-box-flex"},{"name":"-webkit-box-ordinal-group"},{"name":"-webkit-box-orient"},{"name":"-webkit-box-pack"},{"name":"-webkit-box-reflect"},{"longhands":["break-after"],"name":"-webkit-column-break-after"},{"longhands":["break-before"],"name":"-webkit-column-break-before"},{"longhands":["break-inside"],"name":"-webkit-column-break-inside"},{"name":"-webkit-font-size-delta"},{"name":"-webkit-font-smoothing","inherited":true},{"name":"-webkit-highlight","inherited":true},{"name":"-webkit-hyphenate-character","inherited":true},{"name":"-webkit-line-break","inherited":true},{"name":"-webkit-line-clamp"},{"name":"-webkit-locale","inherited":true},{"name":"-webkit-margin-after-collapse"},{"name":"-webkit-margin-before-collapse"},{"name":"-webkit-margin-bottom-collapse"},{"longhands":["-webkit-margin-before-collapse","-webkit-margin-after-collapse"],"name":"-webkit-margin-collapse"},{"name":"-webkit-margin-top-collapse"},{"longhands":["-webkit-mask-image","-webkit-mask-position-x","-webkit-mask-position-y","-webkit-mask-size","-webkit-mask-repeat-x","-webkit-mask-repeat-y","-webkit-mask-origin","-webkit-mask-clip"],"name":"-webkit-mask"},{"longhands":["-webkit-mask-box-image-source","-webkit-mask-box-image-slice","-webkit-mask-box-image-width","-webkit-mask-box-image-outset","-webkit-mask-box-image-repeat"],"name":"-webkit-mask-box-image"},{"name":"-webkit-mask-box-image-outset"},{"name":"-webkit-mask-box-image-repeat"},{"name":"-webkit-mask-box-image-slice"},{"name":"-webkit-mask-box-image-source"},{"name":"-webkit-mask-box-image-width"},{"name":"-webkit-mask-clip"},{"name":"-webkit-mask-composite"},{"name":"-webkit-mask-image"},{"name":"-webkit-mask-origin"},{"longhands":["-webkit-mask-position-x","-webkit-mask-position-y"],"name":"-webkit-mask-position"},{"name":"-webkit-mask-position-x"},{"name":"-webkit-mask-position-y"},{"longhands":["-webkit-mask-repeat-x","-webkit-mask-repeat-y"],"name":"-webkit-mask-repeat"},{"name":"-webkit-mask-repeat-x"},{"name":"-webkit-mask-repeat-y"},{"name":"-webkit-mask-size"},{"name":"-webkit-perspective-origin-x"},{"name":"-webkit-perspective-origin-y"},{"name":"-webkit-print-color-adjust","inherited":true},{"name":"-webkit-rtl-ordering","inherited":true},{"name":"-webkit-ruby-position","inherited":true},{"name":"-webkit-tap-highlight-color","inherited":true},{"name":"-webkit-text-combine","inherited":true},{"name":"-webkit-text-decorations-in-effect","inherited":true},{"longhands":["-webkit-text-emphasis-style","-webkit-text-emphasis-color"],"name":"-webkit-text-emphasis","inherited":true},{"name":"-webkit-text-emphasis-color","inherited":true},{"name":"-webkit-text-emphasis-position","inherited":true},{"name":"-webkit-text-emphasis-style","inherited":true},{"name":"-webkit-text-fill-color","inherited":true},{"name":"-webkit-text-orientation","inherited":true},{"name":"-webkit-text-security","inherited":true},{"longhands":["-webkit-text-stroke-width","-webkit-text-stroke-color"],"name":"-webkit-text-stroke","inherited":true},{"name":"-webkit-text-stroke-color","inherited":true},{"name":"-webkit-text-stroke-width","inherited":true},{"name":"-webkit-transform-origin-x"},{"name":"-webkit-transform-origin-y"},{"name":"-webkit-transform-origin-z"},{"name":"-webkit-user-drag"},{"name":"-webkit-user-modify","inherited":true},{"name":"-webkit-writing-mode","inherited":true},{"name":"align-content"},{"name":"align-items"},{"name":"align-self"},{"svg":true,"name":"alig
reset(tracingModel,zeroTime){this._zeroTime=zeroTime||tracingModel.minimumRecordTime();this._spanTime=tracingModel.maximumRecordTime()-this._zeroTime;this._frames=[];const browserMain=SDK.TracingModel.browserMainThread(tracingModel);if(!browserMain)
return;const events=browserMain.events();for(let i=0;i<events.length;++i){const event=events[i];if(event.startTime<this._zeroTime)
continue;if(!event.hasCategory(SDK.FilmStripModel._category))
continue;if(event.name===SDK.FilmStripModel.TraceEvents.CaptureFrame){const data=event.args['data'];if(data)
this._frames.push(SDK.FilmStripModel.Frame._fromEvent(this,event,this._frames.length));}else if(event.name===SDK.FilmStripModel.TraceEvents.Screenshot){this._frames.push(SDK.FilmStripModel.Frame._fromSnapshot(this,(event),this._frames.length));}}}
frames(){return this._frames;}
zeroTime(){return this._zeroTime;}
spanTime(){return this._spanTime;}
frameByTimestamp(timestamp){const index=this._frames.upperBound(timestamp,(timestamp,frame)=>timestamp-frame.timestamp)-1;return index>=0?this._frames[index]:null;}};SDK.FilmStripModel._category='disabled-by-default-devtools.screenshot';SDK.FilmStripModel.TraceEvents={CaptureFrame:'CaptureFrame',Screenshot:'Screenshot'};SDK.FilmStripModel.Frame=class{constructor(model,timestamp,index){this._model=model;this.timestamp=timestamp;this.index=index;this._imageData=null;this._snapshot=null;}
static _fromEvent(model,event,index){const frame=new SDK.FilmStripModel.Frame(model,event.startTime,index);frame._imageData=event.args['data'];return frame;}
static _fromSnapshot(model,snapshot,index){const frame=new SDK.FilmStripModel.Frame(model,snapshot.startTime,index);frame._snapshot=snapshot;return frame;}
model(){return this._model;}
imageDataPromise(){if(this._imageData||!this._snapshot)
return Promise.resolve(this._imageData);return(this._snapshot.objectPromise());}};;SDK.ConsoleModel=class extends Common.Object{constructor(){super();this._messages=[];this._messageByExceptionId=new Map();this._warnings=0;this._errors=0;this._violations=0;this._pageLoadSequenceNumber=0;SDK.targetManager.observeTargets(this);}
targetAdded(target){const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel||resourceTreeModel.cachedResourcesLoaded()){this._initTarget(target);return;}
const eventListener=resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded,()=>{Common.EventTarget.removeEventListeners([eventListener]);this._initTarget(target);});}
_initTarget(target){const eventListeners=[];const cpuProfilerModel=target.model(SDK.CPUProfilerModel);if(cpuProfilerModel){eventListeners.push(cpuProfilerModel.addEventListener(SDK.CPUProfilerModel.Events.ConsoleProfileStarted,this._consoleProfileStarted.bind(this,cpuProfilerModel)));eventListeners.push(cpuProfilerModel.addEventListener(SDK.CPUProfilerModel.Events.ConsoleProfileFinished,this._consoleProfileFinished.bind(this,cpuProfilerModel)));}
const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(resourceTreeModel&&!target.parentTarget()){eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._mainFrameNavigated,this));}
const runtimeModel=target.model(SDK.RuntimeModel);if(runtimeModel){eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ExceptionThrown,this._exceptionThrown.bind(this,runtimeModel)));eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ExceptionRevoked,this._exceptionRevoked.bind(this,runtimeModel)));eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ConsoleAPICalled,this._consoleAPICalled.bind(this,runtimeModel)));if(!target.parentTarget()){eventListeners.push(runtimeModel.debuggerModel().addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._clearIfNecessary,this));}
eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.QueryObjectRequested,this._queryObjectRequested.bind(this,runtimeModel)));}
target[SDK.ConsoleModel._events]=eventListeners;}
targetRemoved(target){const runtimeModel=target.model(SDK.RuntimeModel);if(runtimeModel)
this._messageByExceptionId.delete(runtimeModel);Common.EventTarget.removeEventListeners(target[SDK.ConsoleModel._events]||[]);}
async evaluateCommandInConsole(executionContext,originatingMessage,expression,useCommandLineAPI,awaitPromise){const result=await executionContext.evaluate({expression:expression,objectGroup:'console',includeCommandLineAPI:useCommandLineAPI,silent:false,returnByValue:false,generatePreview:true},Common.settings.moduleSetting('consoleUserActivationEval').get(),awaitPromise);Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConsoleEvaluated);if(result.error)
return;await Common.console.showPromise();this.dispatchEventToListeners(SDK.ConsoleModel.Events.CommandEvaluated,{result:result.object,commandMessage:originatingMessage,exceptionDetails:result.exceptionDetails});}
addCommandMessage(executionContext,text){const commandMessage=new SDK.ConsoleMessage(executionContext.runtimeModel,SDK.ConsoleMessage.MessageSource.JS,null,text,SDK.ConsoleMessage.MessageType.Command);commandMessage.setExecutionContextId(executionContext.id);this.addMessage(commandMessage);return commandMessage;}
addMessage(msg){msg._pageLoadSequenceNumber=this._pageLoadSequenceNumber;if(msg.source===SDK.ConsoleMessage.MessageSource.ConsoleAPI&&msg.type===SDK.ConsoleMessage.MessageType.Clear)
this._clearIfNecessary();this._messages.push(msg);const runtimeModel=msg.runtimeModel();if(msg._exceptionId&&runtimeModel){let modelMap=this._messageByExceptionId.get(runtimeModel);if(!modelMap){modelMap=new Map();this._messageByExceptionId.set(runtimeModel,modelMap);}
modelMap.set(msg._exceptionId,msg);}
this._incrementErrorWarningCount(msg);this.dispatchEventToListeners(SDK.ConsoleModel.Events.MessageAdded,msg);}
_exceptionThrown(runtimeModel,event){const exceptionWithTimestamp=(event.data);const consoleMessage=SDK.ConsoleMessage.fromException(runtimeModel,exceptionWithTimestamp.details,undefined,exceptionWithTimestamp.timestamp,undefined);consoleMessage.setExceptionId(exceptionWithTimestamp.details.exceptionId);this.addMessage(consoleMessage);}
_exceptionRevoked(runtimeModel,event){const exceptionId=(event.data);const modelMap=this._messageByExceptionId.get(runtimeModel);const exceptionMessage=modelMap?modelMap.get(exceptionId):null;if(!exceptionMessage)
return;this._errors--;exceptionMessage.level=SDK.ConsoleMessage.MessageLevel.Verbose;this.dispatchEventToListeners(SDK.ConsoleModel.Events.MessageUpdated,exceptionMessage);}
_consoleAPICalled(runtimeModel,event){const call=(event.data);let level=SDK.ConsoleMessage.MessageLevel.Info;if(call.type===SDK.ConsoleMessage.MessageType.Debug)
level=SDK.ConsoleMessage.MessageLevel.Verbose;else if(call.type===SDK.ConsoleMessage.MessageType.Error||call.type===SDK.ConsoleMessage.MessageType.Assert)
level=SDK.ConsoleMessage.MessageLevel.Error;else if(call.type===SDK.ConsoleMessage.MessageType.Warning)
level=SDK.ConsoleMessage.MessageLevel.Warning;else if(call.type===SDK.ConsoleMessage.MessageType.Info||call.type===SDK.ConsoleMessage.MessageType.Log)
level=SDK.ConsoleMessage.MessageLevel.Info;let message='';if(call.args.length&&call.args[0].unserializableValue)
message=call.args[0].unserializableValue;else if(call.args.length&&(typeof call.args[0].value!=='object'||call.args[0].value===null))
message=call.args[0].value+'';else if(call.args.length&&call.args[0].description)
message=call.args[0].description;const callFrame=call.stackTrace&&call.stackTrace.callFrames.length?call.stackTrace.callFrames[0]:null;const consoleMessage=new SDK.ConsoleMessage(runtimeModel,SDK.ConsoleMessage.MessageSource.ConsoleAPI,level,(message),call.type,callFrame?callFrame.url:undefined,callFrame?callFrame.lineNumber:undefined,callFrame?callFrame.columnNumber:undefined,call.args,call.stackTrace,call.timestamp,call.executionContextId,undefined,undefined,call.context);this.addMessage(consoleMessage);}
_queryObjectRequested(runtimeModel,event){const consoleMessage=new SDK.ConsoleMessage(runtimeModel,SDK.ConsoleMessage.MessageSource.ConsoleAPI,SDK.ConsoleMessage.MessageLevel.Info,'',SDK.ConsoleMessage.MessageType.QueryObjectResult,undefined,undefined,undefined,[event.data.objects]);this.addMessage(consoleMessage);}
_clearIfNecessary(){if(!Common.moduleSetting('preserveConsoleLog').get())
this._clear();++this._pageLoadSequenceNumber;}
_mainFrameNavigated(event){if(Common.moduleSetting('preserveConsoleLog').get())
Common.console.log(Common.UIString('Navigated to %s',event.data.url));}
_consoleProfileStarted(cpuProfilerModel,event){const data=(event.data);this._addConsoleProfileMessage(cpuProfilerModel,SDK.ConsoleMessage.MessageType.Profile,data.scriptLocation,Common.UIString('Profile \'%s\' started.',data.title));}
_consoleProfileFinished(cpuProfilerModel,event){const data=(event.data);this._addConsoleProfileMessage(cpuProfilerModel,SDK.ConsoleMessage.MessageType.ProfileEnd,data.scriptLocation,Common.UIString('Profile \'%s\' finished.',data.title));}
_addConsoleProfileMessage(cpuProfilerModel,type,scriptLocation,messageText){const stackTrace=[{functionName:'',scriptId:scriptLocation.scriptId,url:scriptLocation.script()?scriptLocation.script().contentURL():'',lineNumber:scriptLocation.lineNumber,columnNumber:scriptLocation.columnNumber||0}];this.addMessage(new SDK.ConsoleMessage(cpuProfilerModel.runtimeModel(),SDK.ConsoleMessage.MessageSource.ConsoleAPI,SDK.ConsoleMessage.MessageLevel.Info,messageText,type,undefined,undefined,undefined,stackTrace));}
_incrementErrorWarningCount(msg){if(msg.source===SDK.ConsoleMessage.MessageSource.Violation){this._violations++;return;}
switch(msg.level){case SDK.ConsoleMessage.MessageLevel.Warning:this._warnings++;break;case SDK.ConsoleMessage.MessageLevel.Error:this._errors++;break;}}
messages(){return this._messages;}
requestClearMessages(){for(const logModel of SDK.targetManager.models(SDK.LogModel))
logModel.requestClear();for(const runtimeModel of SDK.targetManager.models(SDK.RuntimeModel))
runtimeModel.discardConsoleEntries();this._clear();}
_clear(){this._messages=[];this._messageByExceptionId.clear();this._errors=0;this._warnings=0;this._violations=0;this.dispatchEventToListeners(SDK.ConsoleModel.Events.ConsoleCleared);}
errors(){return this._errors;}
warnings(){return this._warnings;}
violations(){return this._violations;}
async saveToTempVariable(currentExecutionContext,remoteObject){if(!remoteObject||!currentExecutionContext){failedToSave(null);return;}
const executionContext=(currentExecutionContext);const result=await executionContext.globalObject('',false);if(!!result.exceptionDetails||!result.object){failedToSave(result.object||null);return;}
const globalObject=result.object;const callFunctionResult=await globalObject.callFunction(saveVariable,[SDK.RemoteObject.toCallArgument(remoteObject)]);globalObject.release();if(callFunctionResult.wasThrown||!callFunctionResult.object||callFunctionResult.object.type!=='string'){failedToSave(callFunctionResult.object||null);}else{const text=(callFunctionResult.object.value);const message=this.addCommandMessage(executionContext,text);this.evaluateCommandInConsole(executionContext,message,text,false,false);}
if(callFunctionResult.object)
callFunctionResult.object.release();function saveVariable(value){const prefix='temp';let index=1;while((prefix+index)in this)
++index;const name=prefix+index;this[name]=value;return name;}
function failedToSave(result){let message=Common.UIString('Failed to save to temp variable.');if(result)
message+=' '+result.description;Common.console.error(message);}}};SDK.ConsoleModel.Events={ConsoleCleared:Symbol('ConsoleCleared'),MessageAdded:Symbol('MessageAdded'),MessageUpdated:Symbol('MessageUpdated'),CommandEvaluated:Symbol('CommandEvaluated')};SDK.ConsoleMessage=class{constructor(runtimeModel,source,level,messageText,type,url,line,column,parameters,stackTrace,timestamp,executionContextId,scriptId,workerId,context){this._runtimeModel=runtimeModel;this.source=source;this.level=(level);this.messageText=messageText;this.type=type||SDK.ConsoleMessage.MessageType.Log;this.url=url||undefined;this.line=line||0;this.column=column||0;this.parameters=parameters;this.stackTrace=stackTrace;this.timestamp=timestamp||Date.now();this.executionContextId=executionContextId||0;this.scriptId=scriptId||null;this.workerId=workerId||null;if(!this.executionContextId&&this._runtimeModel){if(this.scriptId)
this.executionContextId=this._runtimeModel.executionContextIdForScriptId(this.scriptId);else if(this.stackTrace)
this.executionContextId=this._runtimeModel.executionContextForStackTrace(this.stackTrace);}
if(context)
this.context=context.match(/[^#]*/)[0];}
static fromException(runtimeModel,exceptionDetails,messageType,timestamp,forceUrl){return new SDK.ConsoleMessage(runtimeModel,SDK.ConsoleMessage.MessageSource.JS,SDK.ConsoleMessage.MessageLevel.Error,SDK.RuntimeModel.simpleTextFromException(exceptionDetails),messageType,forceUrl||exceptionDetails.url,exceptionDetails.lineNumber,exceptionDetails.columnNumber,exceptionDetails.exception?[SDK.RemoteObject.fromLocalObject(exceptionDetails.text),exceptionDetails.exception]:undefined,exceptionDetails.stackTrace,timestamp,exceptionDetails.executionContextId,exceptionDetails.scriptId);}
runtimeModel(){return this._runtimeModel;}
target(){return this._runtimeModel?this._runtimeModel.target():null;}
setOriginatingMessage(originatingMessage){this._originatingConsoleMessage=originatingMessage;this.executionContextId=originatingMessage.executionContextId;}
setExecutionContextId(executionContextId){this.executionContextId=executionContextId;}
setExceptionId(exceptionId){this._exceptionId=exceptionId;}
originatingMessage(){return this._originatingConsoleMessage;}
isGroupMessage(){return this.type===SDK.ConsoleMessage.MessageType.StartGroup||this.type===SDK.ConsoleMessage.MessageType.StartGroupCollapsed||this.type===SDK.ConsoleMessage.MessageType.EndGroup;}
isGroupStartMessage(){return this.type===SDK.ConsoleMessage.MessageType.StartGroup||this.type===SDK.ConsoleMessage.MessageType.StartGroupCollapsed;}
isErrorOrWarning(){return(this.level===SDK.ConsoleMessage.MessageLevel.Warning||this.level===SDK.ConsoleMessage.MessageLevel.Error);}
isGroupable(){const isUngroupableError=this.level===SDK.ConsoleMessage.MessageLevel.Error&&(this.source===SDK.ConsoleMessage.MessageSource.JS||this.source===SDK.ConsoleMessage.MessageSource.Network);return(this.source!==SDK.ConsoleMessage.MessageSource.ConsoleAPI&&this.type!==SDK.ConsoleMessage.MessageType.Command&&this.type!==SDK.ConsoleMessage.MessageType.Result&&this.type!==SDK.ConsoleMessage.MessageType.System&&!isUngroupableError);}
groupCategoryKey(){return[this.source,this.level,this.type,this._pageLoadSequenceNumber].join(':');}
isEqual(msg){if(!msg)
return false;if(!this._isEqualStackTraces(this.stackTrace,msg.stackTrace))
return false;if(this.parameters){if(!msg.parameters||this.parameters.length!==msg.parameters.length)
return false;for(let i=0;i<msg.parameters.length;++i){if(msg.parameters[i].type==='object'&&msg.parameters[i].subtype!=='error')
return false;if(this.parameters[i].type!==msg.parameters[i].type||this.parameters[i].value!==msg.parameters[i].value||this.parameters[i].description!==msg.parameters[i].description)
return false;}}
return(this.runtimeModel()===msg.runtimeModel())&&(this.source===msg.source)&&(this.type===msg.type)&&(this.level===msg.level)&&(this.line===msg.line)&&(this.url===msg.url)&&(this.messageText===msg.messageText)&&(this.request===msg.request)&&(this.executionContextId===msg.executionContextId);}
_isEqualStackTraces(stackTrace1,stackTrace2){if(!stackTrace1!==!stackTrace2)
return false;if(!stackTrace1)
return true;const callFrames1=stackTrace1.callFrames;const callFrames2=stackTrace2.callFrames;if(callFrames1.length!==callFrames2.length)
return false;for(let i=0,n=callFrames1.length;i<n;++i){if(callFrames1[i].url!==callFrames2[i].url||callFrames1[i].functionName!==callFrames2[i].functionName||callFrames1[i].lineNumber!==callFrames2[i].lineNumber||callFrames1[i].columnNumber!==callFrames2[i].columnNumber)
return false;}
return this._isEqualStackTraces(stackTrace1.parent,stackTrace2.parent);}};SDK.ConsoleMessage.MessageSource={XML:'xml',JS:'javascript',Network:'network',ConsoleAPI:'console-api',Storage:'storage',AppCache:'appcache',Rendering:'rendering',CSS:'css',Security:'security',Deprecation:'deprecation',Worker:'worker',Violation:'violation',Intervention:'intervention',Recommendation:'recommendation',Other:'other'};SDK.ConsoleMessage.MessageType={Log:'log',Debug:'debug',Info:'info',Error:'error',Warning:'warning',Dir:'dir',DirXML:'dirxml',Table:'table',Trace:'trace',Clear:'clear',StartGroup:'startGroup',StartGroupCollapsed:'startGroupCollapsed',EndGroup:'endGroup',Assert:'assert',Result:'result',Profile:'profile',ProfileEnd:'profileEnd',Command:'command',System:'system',QueryObjectResult:'queryObjectResult'};SDK.ConsoleMessage.MessageLevel={Verbose:'verbose',Info:'info',Warning:'warning',Error:'error'};SDK.ConsoleMessage.MessageSourceDisplayName=new Map([[SDK.ConsoleMessage.MessageSource.XML,'xml'],[SDK.ConsoleMessage.MessageSource.JS,'javascript'],[SDK.ConsoleMessage.MessageSource.Network,'network'],[SDK.ConsoleMessage.MessageSource.ConsoleAPI,'console-api'],[SDK.ConsoleMessage.MessageSource.Storage,'storage'],[SDK.ConsoleMessage.MessageSource.AppCache,'appcache'],[SDK.ConsoleMessage.MessageSource.Rendering,'rendering'],[SDK.ConsoleMessage.MessageSource.CSS,'css'],[SDK.ConsoleMessage.MessageSource.Security,'security'],[SDK.ConsoleMessage.MessageSource.Deprecation,'deprecation'],[SDK.ConsoleMessage.MessageSource.Worker,'worker'],[SDK.ConsoleMessage.MessageSource.Violation,'violation'],[SDK.ConsoleMessage.MessageSource.Intervention,'intervention'],[SDK.ConsoleMessage.MessageSource.Recommendation,'recommendation'],[SDK.ConsoleMessage.MessageSource.Other,'other']]);SDK.ConsoleModel._events=Symbol('SDK.ConsoleModel.events');SDK.consoleModel;;self['Services']=self['Services']||{};Services.ServiceManager=class{createRemoteService(serviceName){if(!this._remoteConnection){const url=Runtime.queryParam('service-backend');if(!url){console.error('No endpoint address specified');return(Promise.resolve(null));}
this._remoteConnection=new Services.ServiceManager.Connection(new Services.ServiceManager.RemoteServicePort(url));}
return this._remoteConnection._createService(serviceName);}
createAppService(appName,serviceName){let url=appName+'.js';const remoteBase=Runtime.queryParam('remoteBase');const debugFrontend=Runtime.queryParam('debugFrontend');const isUnderTest=Host.isUnderTest();const queryParams=[];if(remoteBase)
queryParams.push('remoteBase='+remoteBase);if(debugFrontend)
queryParams.push('debugFrontend='+debugFrontend);if(isUnderTest)
queryParams.push('isUnderTest=true');if(queryParams.length)
url+=`?${queryParams.join('&')}`;const worker=new Worker(url);const connection=new Services.ServiceManager.Connection(new Services.ServiceManager.WorkerServicePort(worker));return connection._createService(serviceName);}};Services.ServiceManager.Connection=class{constructor(port){this._port=port;this._port.setHandlers(this._onMessage.bind(this),this._connectionClosed.bind(this));this._lastId=1;this._callbacks=new Map();this._services=new Map();}
_createService(serviceName){return this._sendCommand(serviceName+'.create').then(result=>{if(!result){console.error('Could not initialize service: '+serviceName);return null;}
const service=new Services.ServiceManager.Service(this,serviceName,result.id);this._services.set(serviceName+':'+result.id,service);return service;});}
_serviceDisposed(service){this._services.delete(service._serviceName+':'+service._objectId);if(!this._services.size){this._port.close();}}
_sendCommand(method,params){const id=this._lastId++;const message=JSON.stringify({id:id,method:method,params:params||{}});return this._port.send(message).then(success=>{if(!success)
return Promise.resolve(null);return new Promise(fulfill=>this._callbacks.set(id,fulfill));});}
_onMessage(data){let object;try{object=JSON.parse(data);}catch(e){console.error(e);return;}
if(object.id){if(object.error)
console.error('Service error: '+object.error);this._callbacks.get(object.id)(object.error?null:object.result);this._callbacks.delete(object.id);return;}
const tokens=object.method.split('.');const serviceName=tokens[0];const methodName=tokens[1];const service=this._services.get(serviceName+':'+object.params.id);if(!service){console.error('Unable to lookup stub for '+serviceName+':'+object.params.id);return;}
service._dispatchNotification(methodName,object.params);}
_connectionClosed(){for(const callback of this._callbacks.values())
callback(null);this._callbacks.clear();for(const service of this._services.values())
service._dispatchNotification('disposed');this._services.clear();}};Services.ServiceManager.Service=class{constructor(connection,serviceName,objectId){this._connection=connection;this._serviceName=serviceName;this._objectId=objectId;this._notificationHandlers=new Map();}
dispose(){const params={id:this._objectId};return this._connection._sendCommand(this._serviceName+'.dispose',params).then(()=>{this._connection._serviceDisposed(this);});}
on(methodName,handler){this._notificationHandlers.set(methodName,handler);}
send(methodName,params){params=params||{};params.id=this._objectId;return this._connection._sendCommand(this._serviceName+'.'+methodName,params);}
_dispatchNotification(methodName,params){const handler=this._notificationHandlers.get(methodName);if(!handler){console.error('Could not report notification \''+methodName+'\' on \''+this._objectId+'\'');return;}
handler(params);}};Services.ServiceManager.RemoteServicePort=class{constructor(url){this._url=url;}
setHandlers(messageHandler,closeHandler){this._messageHandler=messageHandler;this._closeHandler=closeHandler;}
_open(){if(!this._connectionPromise)
this._connectionPromise=new Promise(promiseBody.bind(this));return this._connectionPromise;function promiseBody(fulfill){let socket;try{socket=new WebSocket((this._url));socket.onmessage=onMessage.bind(this);socket.onclose=onClose.bind(this);socket.onopen=onConnect.bind(this);}catch(e){fulfill(false);}
function onConnect(){this._socket=socket;fulfill(true);}
function onMessage(event){this._messageHandler(event.data);}
function onClose(){if(!this._socket)
fulfill(false);this._socketClosed(!!this._socket);}}}
send(message){return this._open().then(()=>{if(this._socket){this._socket.send(message);return true;}
return false;});}
close(){return this._open().then(()=>{if(this._socket){this._socket.close();this._socketClosed(true);}
return true;});}
_socketClosed(notifyClient){this._socket=null;delete this._connectionPromise;if(notifyClient)
this._closeHandler();}};Services.ServiceManager.WorkerServicePort=class{constructor(worker){this._worker=worker;let fulfill;this._workerPromise=new Promise(resolve=>fulfill=resolve);this._worker.onmessage=onMessage.bind(this);this._worker.onclose=this._closeHandler;function onMessage(event){if(event.data==='workerReady'){fulfill(true);return;}
this._messageHandler(event.data);}}
setHandlers(messageHandler,closeHandler){this._messageHandler=messageHandler;this._closeHandler=closeHandler;}
send(message){return this._workerPromise.then(()=>{try{this._worker.postMessage(message);return true;}catch(e){return false;}});}
close(){return this._workerPromise.then(()=>{if(this._worker)
this._worker.terminate();return false;});}};Services.serviceManager=new Services.ServiceManager();;self['Workspace']=self['Workspace']||{};Workspace.FileManager=class extends Common.Object{constructor(){super();this._saveCallbacks=new Map();InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SavedURL,this._savedURL,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.CanceledSaveURL,this._canceledSavedURL,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.AppendedToURL,this._appendedToURL,this);}
save(url,content,forceSaveAs){const result=new Promise(resolve=>this._saveCallbacks.set(url,resolve));InspectorFrontendHost.save(url,content,forceSaveAs);return result;}
_savedURL(event){const url=(event.data.url);const callback=this._saveCallbacks.get(url);this._saveCallbacks.delete(url);if(callback)
callback({fileSystemPath:(event.data.fileSystemPath)});}
_canceledSavedURL(event){const url=(event.data);const callback=this._saveCallbacks.get(url);this._saveCallbacks.delete(url);if(callback)
callback(null);}
append(url,content){InspectorFrontendHost.append(url,content);}
close(url){InspectorFrontendHost.close(url);}
_appendedToURL(event){const url=(event.data);this.dispatchEventToListeners(Workspace.FileManager.Events.AppendedToURL,url);}};Workspace.FileManager.Events={AppendedToURL:Symbol('AppendedToURL')};Workspace.fileManager;;Workspace.UISourceCode=class extends Common.Object{constructor(project,url,contentType){super();this._project=project;this._url=url;const parsedURL=url.asParsedURL();if(parsedURL){this._origin=parsedURL.securityOrigin();this._parentURL=this._origin+parsedURL.folderPathComponents;this._name=parsedURL.lastPathComponent;if(parsedURL.queryParams)
this._name+='?'+parsedURL.queryParams;}else{this._origin='';this._parentURL='';this._name=url;}
this._contentType=contentType;this._requestContentPromise=null;this._decorations=null;this._hasCommits=false;this._messages=null;this._contentLoaded=false;this._content=null;this._contentEncoded;this._forceLoadOnCheckContent=false;this._checkingContent=false;this._lastAcceptedContent=null;this._workingCopy=null;this._workingCopyGetter=null;}
requestMetadata(){return this._project.requestMetadata(this);}
name(){return this._name;}
mimeType(){return this._project.mimeType(this);}
url(){return this._url;}
parentURL(){return this._parentURL;}
origin(){return this._origin;}
fullDisplayName(){return this._project.fullDisplayName(this);}
displayName(skipTrim){if(!this._name)
return Common.UIString('(index)');let name=this._name;try{if(this.project().type()===Workspace.projectTypes.FileSystem)
name=unescape(name);else
name=decodeURI(name);}catch(e){}
return skipTrim?name:name.trimEnd(100);}
canRename(){return this._project.canRename();}
rename(newName){let fulfill;const promise=new Promise(x=>fulfill=x);this._project.rename(this,newName,innerCallback.bind(this));return promise;function innerCallback(success,newName,newURL,newContentType){if(success){this._updateName((newName),(newURL),(newContentType));}
fulfill(success);}}
remove(){this._project.deleteFile(this);}
_updateName(name,url,contentType){const oldURL=this._url;this._url=this._url.substring(0,this._url.length-this._name.length)+name;this._name=name;if(url)
this._url=url;if(contentType)
this._contentType=contentType;this.dispatchEventToListeners(Workspace.UISourceCode.Events.TitleChanged,this);this.project().workspace().dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeRenamed,{oldURL:oldURL,uiSourceCode:this});}
contentURL(){return this.url();}
contentType(){return this._contentType;}
async contentEncoded(){await this.requestContent();return this._contentEncoded||false;}
project(){return this._project;}
requestContent(){if(this._requestContentPromise)
return this._requestContentPromise;if(this._contentLoaded){this._requestContentPromise=Promise.resolve(this._content);}else{let fulfill;this._requestContentPromise=new Promise(x=>fulfill=x);this._project.requestFileContent(this,(content,encoded)=>{if(!this._contentLoaded){this._contentLoaded=true;this._content=content;this._contentEncoded=encoded;}
fulfill(this._content);});}
return this._requestContentPromise;}
checkContentUpdated(){if(!this._contentLoaded&&!this._forceLoadOnCheckContent)
return;if(!this._project.canSetFileContent()||this._checkingContent)
return;this._checkingContent=true;this._project.requestFileContent(this,contentLoaded.bind(this));async function contentLoaded(updatedContent,encoded){this._checkingContent=false;if(updatedContent===null){const workingCopy=this.workingCopy();this._contentCommitted('',false);this.setWorkingCopy(workingCopy);return;}
if(this._lastAcceptedContent===updatedContent)
return;if(this._content===updatedContent){this._lastAcceptedContent=null;return;}
if(!this.isDirty()||this._workingCopy===updatedContent){this._contentCommitted((updatedContent),false);return;}
await Common.Revealer.reveal(this);await new Promise(resolve=>setTimeout(resolve,0));const shouldUpdate=window.confirm(Common.UIString('This file was changed externally. Would you like to reload it?'));if(shouldUpdate)
this._contentCommitted((updatedContent),false);else
this._lastAcceptedContent=updatedContent;}}
forceLoadOnCheckContent(){this._forceLoadOnCheckContent=true;}
_commitContent(content){if(this._project.canSetFileContent())
this._project.setFileContent(this,content,false);this._contentCommitted(content,true);}
_contentCommitted(content,committedByUser){this._lastAcceptedContent=null;this._content=content;this._contentLoaded=true;this._requestContentPromise=null;this._hasCommits=true;this._innerResetWorkingCopy();const data={uiSourceCode:this,content,encoded:this._contentEncoded};this.dispatchEventToListeners(Workspace.UISourceCode.Events.WorkingCopyCommitted,data);this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyCommitted,data);if(committedByUser)
this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyCommittedByUser,data);}
addRevision(content){this._commitContent(content);}
hasCommits(){return this._hasCommits;}
workingCopy(){if(this._workingCopyGetter){this._workingCopy=this._workingCopyGetter();this._workingCopyGetter=null;}
if(this.isDirty())
return(this._workingCopy);return this._content||'';}
resetWorkingCopy(){this._innerResetWorkingCopy();this._workingCopyChanged();}
_innerResetWorkingCopy(){this._workingCopy=null;this._workingCopyGetter=null;}
setWorkingCopy(newWorkingCopy){this._workingCopy=newWorkingCopy;this._workingCopyGetter=null;this._workingCopyChanged();}
setContent(content,isBase64){this._contentEncoded=isBase64;if(this._project.canSetFileContent())
this._project.setFileContent(this,content,isBase64);this._contentCommitted(content,true);}
setWorkingCopyGetter(workingCopyGetter){this._workingCopyGetter=workingCopyGetter;this._workingCopyChanged();}
_workingCopyChanged(){this._removeAllMessages();this.dispatchEventToListeners(Workspace.UISourceCode.Events.WorkingCopyChanged,this);this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyChanged,{uiSourceCode:this});}
removeWorkingCopyGetter(){if(!this._workingCopyGetter)
return;this._workingCopy=this._workingCopyGetter();this._workingCopyGetter=null;}
commitWorkingCopy(){if(this.isDirty())
this._commitContent(this.workingCopy());}
isDirty(){return this._workingCopy!==null||this._workingCopyGetter!==null;}
extension(){return Common.ParsedURL.extractExtension(this._name);}
content(){return this._content;}
searchInContent(query,caseSensitive,isRegex){const content=this.content();if(!content)
return this._project.searchInFileContent(this,query,caseSensitive,isRegex);return Promise.resolve(Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex));}
contentLoaded(){return this._contentLoaded;}
uiLocation(lineNumber,columnNumber){if(typeof columnNumber==='undefined')
columnNumber=0;return new Workspace.UILocation(this,lineNumber,columnNumber);}
messages(){return this._messages?new Set(this._messages):new Set();}
addLineMessage(level,text,lineNumber,columnNumber){return this.addMessage(level,text,new TextUtils.TextRange(lineNumber,columnNumber||0,lineNumber,columnNumber||0));}
addMessage(level,text,range){const message=new Workspace.UISourceCode.Message(this,level,text,range);if(!this._messages)
this._messages=new Set();this._messages.add(message);this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageAdded,message);return message;}
removeMessage(message){if(this._messages&&this._messages.delete(message))
this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageRemoved,message);}
_removeAllMessages(){if(!this._messages)
return;for(const message of this._messages)
this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageRemoved,message);this._messages=null;}
addLineDecoration(lineNumber,type,data){this.addDecoration(TextUtils.TextRange.createFromLocation(lineNumber,0),type,data);}
addDecoration(range,type,data){const marker=new Workspace.UISourceCode.LineMarker(range,type,data);if(!this._decorations)
this._decorations=new Multimap();this._decorations.set(type,marker);this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationAdded,marker);}
removeDecorationsForType(type){if(!this._decorations)
return;const markers=this._decorations.get(type);this._decorations.deleteAll(type);markers.forEach(marker=>{this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationRemoved,marker);});}
allDecorations(){return this._decorations?this._decorations.valuesArray():[];}
removeAllDecorations(){if(!this._decorations)
return;const decorationList=this._decorations.valuesArray();this._decorations.clear();decorationList.forEach(marker=>this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationRemoved,marker));}
decorationsForType(type){return this._decorations?this._decorations.get(type):null;}};Workspace.UISourceCode.Events={WorkingCopyChanged:Symbol('WorkingCopyChanged'),WorkingCopyCommitted:Symbol('WorkingCopyCommitted'),TitleChanged:Symbol('TitleChanged'),MessageAdded:Symbol('MessageAdded'),MessageRemoved:Symbol('MessageRemoved'),LineDecorationAdded:Symbol('LineDecorationAdded'),LineDecorationRemoved:Symbol('LineDecorationRemoved')};Workspace.UILocation=class{constructor(uiSourceCode,lineNumber,columnNumber){this.uiSourceCode=uiSourceCode;this.lineNumber=lineNumber;this.columnNumber=columnNumber;}
linkText(skipTrim){let linkText=this.uiSourceCode.displayName(skipTrim);if(typeof this.lineNumber==='number')
linkText+=':'+(this.lineNumber+1);return linkText;}
id(){return this.uiSourceCode.project().id()+':'+this.uiSourceCode.url()+':'+this.lineNumber+':'+
this.columnNumber;}
toUIString(){return this.uiSourceCode.url()+':'+(this.lineNumber+1);}
static comparator(location1,location2){return location1.compareTo(location2);}
compareTo(other){if(this.uiSourceCode.url()!==other.uiSourceCode.url())
return this.uiSourceCode.url()>other.uiSourceCode.url()?1:-1;if(this.lineNumber!==other.lineNumber)
return this.lineNumber-other.lineNumber;return this.columnNumber-other.columnNumber;}};Workspace.UISourceCode.Message=class{constructor(uiSourceCode,level,text,range){this._uiSourceCode=uiSourceCode;this._level=level;this._text=text;this._range=range;}
uiSourceCode(){return this._uiSourceCode;}
level(){return this._level;}
text(){return this._text;}
range(){return this._range;}
lineNumber(){return this._range.startLine;}
columnNumber(){return this._range.startColumn;}
isEqual(another){return this._uiSourceCode===another._uiSourceCode&&this.text()===another.text()&&this.level()===another.level()&&this.range().equal(another.range());}
remove(){this._uiSourceCode.removeMessage(this);}};Workspace.UISourceCode.Message.Level={Error:'Error',Warning:'Warning'};Workspace.UISourceCode.LineMarker=class{constructor(range,type,data){this._range=range;this._type=type;this._data=data;}
range(){return this._range;}
type(){return this._type;}
data(){return this._data;}};Workspace.UISourceCodeMetadata=class{constructor(modificationTime,contentSize){this.modificationTime=modificationTime;this.contentSize=contentSize;}};;Workspace.ProjectSearchConfig=function(){};Workspace.ProjectSearchConfig.prototype={query(){},ignoreCase(){},isRegex(){},queries(){},filePathMatchesFileQuery(filePath){}};Workspace.Project=function(){};Workspace.Project.prototype={workspace(){},id(){},type(){},isServiceProject(){},displayName(){},requestMetadata(uiSourceCode){},requestFileContent(uiSourceCode,callback){},canSetFileContent(){},setFileContent(uiSourceCode,newContent,isBase64){},fullDisplayName(uiSourceCode){},mimeType(uiSourceCode){},canRename(){},rename(uiSourceCode,newName,callback){},excludeFolder(path){},canExcludeFolder(path){},createFile(path,name,content,isBase64){},canCreateFile(){},deleteFile(uiSourceCode){},remove(){},searchInFileContent(uiSourceCode,query,caseSensitive,isRegex){},findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,progress){},indexContent(progress){},uiSourceCodeForURL(url){},uiSourceCodes(){}};Workspace.projectTypes={Debugger:'debugger',Formatter:'formatter',Network:'network',FileSystem:'filesystem',ContentScripts:'contentscripts',Service:'service'};Workspace.ProjectStore=class{constructor(workspace,id,type,displayName){this._workspace=workspace;this._id=id;this._type=type;this._displayName=displayName;this._uiSourceCodesMap=new Map();this._uiSourceCodesList=[];this._project=(this);}
id(){return this._id;}
type(){return this._type;}
displayName(){return this._displayName;}
workspace(){return this._workspace;}
createUISourceCode(url,contentType){return new Workspace.UISourceCode(this._project,url,contentType);}
addUISourceCode(uiSourceCode){const url=uiSourceCode.url();if(this.uiSourceCodeForURL(url))
return false;this._uiSourceCodesMap.set(url,{uiSourceCode:uiSourceCode,index:this._uiSourceCodesList.length});this._uiSourceCodesList.push(uiSourceCode);this._workspace.dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeAdded,uiSourceCode);return true;}
removeUISourceCode(url){const uiSourceCode=this.uiSourceCodeForURL(url);if(!uiSourceCode)
return;const entry=this._uiSourceCodesMap.get(url);const movedUISourceCode=this._uiSourceCodesList[this._uiSourceCodesList.length-1];this._uiSourceCodesList[entry.index]=movedUISourceCode;const movedEntry=this._uiSourceCodesMap.get(movedUISourceCode.url());movedEntry.index=entry.index;this._uiSourceCodesList.splice(this._uiSourceCodesList.length-1,1);this._uiSourceCodesMap.delete(url);this._workspace.dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeRemoved,entry.uiSourceCode);}
removeProject(){this._workspace._removeProject(this._project);this._uiSourceCodesMap=new Map();this._uiSourceCodesList=[];}
uiSourceCodeForURL(url){const entry=this._uiSourceCodesMap.get(url);return entry?entry.uiSourceCode:null;}
uiSourceCodes(){return this._uiSourceCodesList;}
renameUISourceCode(uiSourceCode,newName){const oldPath=uiSourceCode.url();const newPath=uiSourceCode.parentURL()?uiSourceCode.parentURL()+'/'+newName:newName;const value=(this._uiSourceCodesMap.get(oldPath));this._uiSourceCodesMap.set(newPath,value);this._uiSourceCodesMap.delete(oldPath);}};Workspace.Workspace=class extends Common.Object{constructor(){super();this._projects=new Map();this._hasResourceContentTrackingExtensions=false;}
uiSourceCode(projectId,url){const project=this._projects.get(projectId);return project?project.uiSourceCodeForURL(url):null;}
uiSourceCodeForURL(url){for(const project of this._projects.values()){const uiSourceCode=project.uiSourceCodeForURL(url);if(uiSourceCode)
return uiSourceCode;}
return null;}
uiSourceCodesForProjectType(type){let result=[];for(const project of this._projects.values()){if(project.type()===type)
result=result.concat(project.uiSourceCodes());}
return result;}
addProject(project){console.assert(!this._projects.has(project.id()),`A project with id ${project.id()} already exists!`);this._projects.set(project.id(),project);this.dispatchEventToListeners(Workspace.Workspace.Events.ProjectAdded,project);}
_removeProject(project){this._projects.delete(project.id());this.dispatchEventToListeners(Workspace.Workspace.Events.ProjectRemoved,project);}
project(projectId){return this._projects.get(projectId)||null;}
projects(){return this._projects.valuesArray();}
projectsForType(type){function filterByType(project){return project.type()===type;}
return this.projects().filter(filterByType);}
uiSourceCodes(){let result=[];for(const project of this._projects.values())
result=result.concat(project.uiSourceCodes());return result;}
setHasResourceContentTrackingExtensions(hasExtensions){this._hasResourceContentTrackingExtensions=hasExtensions;}
hasResourceContentTrackingExtensions(){return this._hasResourceContentTrackingExtensions;}};Workspace.Workspace.Events={UISourceCodeAdded:Symbol('UISourceCodeAdded'),UISourceCodeRemoved:Symbol('UISourceCodeRemoved'),UISourceCodeRenamed:Symbol('UISourceCodeRenamed'),WorkingCopyChanged:Symbol('WorkingCopyChanged'),WorkingCopyCommitted:Symbol('WorkingCopyCommitted'),WorkingCopyCommittedByUser:Symbol('WorkingCopyCommittedByUser'),ProjectAdded:Symbol('ProjectAdded'),ProjectRemoved:Symbol('ProjectRemoved')};Workspace.workspace;;self['Bindings']=self['Bindings']||{};Bindings.LiveLocation=function(){};Bindings.LiveLocation.prototype={update(){},uiLocation(){},dispose(){},isBlackboxed(){}};Bindings.LiveLocationWithPool=class{constructor(updateDelegate,locationPool){this._updateDelegate=updateDelegate;this._locationPool=locationPool;this._locationPool._add(this);}
update(){this._updateDelegate(this);}
uiLocation(){throw'Not implemented';}
dispose(){this._locationPool._delete(this);this._updateDelegate=null;}
isBlackboxed(){throw'Not implemented';}};Bindings.LiveLocationPool=class{constructor(){this._locations=new Set();}
_add(location){this._locations.add(location);}
_delete(location){this._locations.delete(location);}
disposeAll(){for(const location of this._locations)
location.dispose();}};;Bindings.ResourceMapping=class{constructor(targetManager,workspace){this._workspace=workspace;this._modelToInfo=new Map();targetManager.observeModels(SDK.ResourceTreeModel,this);}
modelAdded(resourceTreeModel){const info=new Bindings.ResourceMapping.ModelInfo(this._workspace,resourceTreeModel);this._modelToInfo.set(resourceTreeModel,info);}
modelRemoved(resourceTreeModel){const info=this._modelToInfo.get(resourceTreeModel);info.dispose();this._modelToInfo.delete(resourceTreeModel);}
_infoForTarget(target){const resourceTreeModel=target.model(SDK.ResourceTreeModel);return resourceTreeModel?this._modelToInfo.get(resourceTreeModel):null;}
cssLocationToUILocation(cssLocation){const header=cssLocation.header();if(!header)
return null;const info=this._infoForTarget(cssLocation.cssModel().target());if(!info)
return null;const uiSourceCode=info._project.uiSourceCodeForURL(cssLocation.url);if(!uiSourceCode)
return null;const offset=header[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(header.startLine,header.startColumn);const lineNumber=cssLocation.lineNumber+offset.startLine-header.startLine;let columnNumber=cssLocation.columnNumber;if(cssLocation.lineNumber===header.startLine)
columnNumber+=offset.startColumn-header.startColumn;return uiSourceCode.uiLocation(lineNumber,columnNumber);}
jsLocationToUILocation(jsLocation){const script=jsLocation.script();if(!script)
return null;const info=this._infoForTarget(jsLocation.debuggerModel.target());if(!info)
return null;const uiSourceCode=info._project.uiSourceCodeForURL(script.sourceURL);if(!uiSourceCode)
return null;const offset=script[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(script.lineOffset,script.columnOffset);const lineNumber=jsLocation.lineNumber+offset.startLine-script.lineOffset;let columnNumber=jsLocation.columnNumber;if(jsLocation.lineNumber===script.lineOffset)
columnNumber+=offset.startColumn-script.columnOffset;return uiSourceCode.uiLocation(lineNumber,columnNumber);}
uiLocationToJSLocations(uiSourceCode,lineNumber,columnNumber){if(!uiSourceCode[Bindings.ResourceMapping._symbol])
return[];const target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);if(!target)
return[];const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel)
return[];const location=debuggerModel.createRawLocationByURL(uiSourceCode.url(),lineNumber,columnNumber);return location?[location]:[];}
_resetForTest(target){const resourceTreeModel=target.model(SDK.ResourceTreeModel);const info=resourceTreeModel?this._modelToInfo.get(resourceTreeModel):null;if(info)
info._resetForTest();}};Bindings.ResourceMapping.ModelInfo=class{constructor(workspace,resourceTreeModel){const target=resourceTreeModel.target();this._project=new Bindings.ContentProviderBasedProject(workspace,'resources:'+target.id(),Workspace.projectTypes.Network,'',false);Bindings.NetworkProject.setTargetForProject(this._project,target);this._bindings=new Map();const cssModel=target.model(SDK.CSSModel);this._cssModel=cssModel;this._eventListeners=[resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.ResourceAdded,this._resourceAdded,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameWillNavigate,this._frameWillNavigate,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameDetached,this._frameDetached,this),cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._styleSheetChanged,this)];}
_styleSheetChanged(event){const header=this._cssModel.styleSheetHeaderForId(event.data.styleSheetId);if(!header||!header.isInline)
return;const binding=this._bindings.get(header.resourceURL());if(!binding)
return;binding._styleSheetChanged(header,event.data.edit);}
_acceptsResource(resource){const resourceType=resource.resourceType();if(resourceType!==Common.resourceTypes.Image&&resourceType!==Common.resourceTypes.Font&&resourceType!==Common.resourceTypes.Document&&resourceType!==Common.resourceTypes.Manifest)
return false;if(resourceType===Common.resourceTypes.Image&&resource.mimeType&&!resource.mimeType.startsWith('image'))
return false;if(resourceType===Common.resourceTypes.Font&&resource.mimeType&&!resource.mimeType.includes('font'))
return false;if((resourceType===Common.resourceTypes.Image||resourceType===Common.resourceTypes.Font)&&resource.contentURL().startsWith('data:'))
return false;return true;}
_resourceAdded(event){const resource=(event.data);if(!this._acceptsResource(resource))
return;let binding=this._bindings.get(resource.url);if(!binding){binding=new Bindings.ResourceMapping.Binding(this._project,resource);this._bindings.set(resource.url,binding);}else{binding.addResource(resource);}}
_removeFrameResources(frame){for(const resource of frame.resources()){if(!this._acceptsResource(resource))
continue;const binding=this._bindings.get(resource.url);if(binding._resources.size===1){binding.dispose();this._bindings.delete(resource.url);}else{binding.removeResource(resource);}}}
_frameWillNavigate(event){const frame=(event.data);this._removeFrameResources(frame);}
_frameDetached(event){const frame=(event.data);this._removeFrameResources(frame);}
_resetForTest(){for(const binding of this._bindings.valuesArray())
binding.dispose();this._bindings.clear();}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);for(const binding of this._bindings.valuesArray())
binding.dispose();this._bindings.clear();this._project.removeProject();}};Bindings.ResourceMapping.Binding=class{constructor(project,resource){this._resources=new Set([resource]);this._project=project;this._uiSourceCode=this._project.createUISourceCode(resource.url,resource.contentType());this._uiSourceCode[Bindings.ResourceMapping._symbol]=true;Bindings.NetworkProject.setInitialFrameAttribution(this._uiSourceCode,resource.frameId);this._project.addUISourceCodeWithProvider(this._uiSourceCode,this,Bindings.resourceMetadata(resource),resource.mimeType);this._edits=[];}
_inlineStyles(){const target=Bindings.NetworkProject.targetForUISourceCode(this._uiSourceCode);const cssModel=target.model(SDK.CSSModel);const stylesheets=[];if(cssModel){for(const headerId of cssModel.styleSheetIdsForURL(this._uiSourceCode.url())){const header=cssModel.styleSheetHeaderForId(headerId);if(header)
stylesheets.push(header);}}
return stylesheets;}
_inlineScripts(){const target=Bindings.NetworkProject.targetForUISourceCode(this._uiSourceCode);const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel)
return[];return debuggerModel.scriptsForSourceURL(this._uiSourceCode.url());}
async _styleSheetChanged(stylesheet,edit){this._edits.push({stylesheet,edit});if(this._edits.length>1)
return;const content=await this._uiSourceCode.requestContent();if(content!==null)
this._innerStyleSheetChanged(content);this._edits=[];}
_innerStyleSheetChanged(content){const scripts=this._inlineScripts();const styles=this._inlineStyles();let text=new TextUtils.Text(content);for(const data of this._edits){const edit=data.edit;const stylesheet=data.stylesheet;const startLocation=stylesheet[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(stylesheet.startLine,stylesheet.startColumn);const oldRange=edit.oldRange.relativeFrom(startLocation.startLine,startLocation.startColumn);const newRange=edit.newRange.relativeFrom(startLocation.startLine,startLocation.startColumn);text=new TextUtils.Text(text.replaceRange(oldRange,edit.newText));for(const script of scripts){const scriptOffset=script[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(script.lineOffset,script.columnOffset);if(!scriptOffset.follows(oldRange))
continue;script[Bindings.ResourceMapping._offsetSymbol]=scriptOffset.rebaseAfterTextEdit(oldRange,newRange);Bindings.debuggerWorkspaceBinding.updateLocations(script);}
for(const style of styles){const styleOffset=style[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(style.startLine,style.startColumn);if(!styleOffset.follows(oldRange))
continue;style[Bindings.ResourceMapping._offsetSymbol]=styleOffset.rebaseAfterTextEdit(oldRange,newRange);Bindings.cssWorkspaceBinding.updateLocations(style);}}
this._uiSourceCode.addRevision(text.value());}
addResource(resource){this._resources.add(resource);Bindings.NetworkProject.addFrameAttribution(this._uiSourceCode,resource.frameId);}
removeResource(resource){this._resources.delete(resource);Bindings.NetworkProject.removeFrameAttribution(this._uiSourceCode,resource.frameId);}
dispose(){this._project.removeFile(this._uiSourceCode.url());}
contentURL(){return this._resources.firstValue().contentURL();}
contentType(){return this._resources.firstValue().contentType();}
contentEncoded(){return this._resources.firstValue().contentEncoded();}
requestContent(){return this._resources.firstValue().requestContent();}
searchInContent(query,caseSensitive,isRegex){return this._resources.firstValue().searchInContent(query,caseSensitive,isRegex);}};Bindings.ResourceMapping._symbol=Symbol('Bindings.ResourceMapping._symbol');Bindings.ResourceMapping._offsetSymbol=Symbol('Bindings.ResourceMapping._offsetSymbol');;Bindings.CompilerScriptMapping=class{constructor(debuggerModel,workspace,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._sourceMapManager=this._debuggerModel.sourceMapManager();this._workspace=workspace;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;const target=debuggerModel.target();this._regularProject=new Bindings.ContentProviderBasedProject(workspace,'jsSourceMaps::'+target.id(),Workspace.projectTypes.Network,'',false);this._contentScriptsProject=new Bindings.ContentProviderBasedProject(workspace,'jsSourceMaps:extensions:'+target.id(),Workspace.projectTypes.ContentScripts,'',false);Bindings.NetworkProject.setTargetForProject(this._regularProject,target);Bindings.NetworkProject.setTargetForProject(this._contentScriptsProject,target);this._regularBindings=new Map();this._contentScriptsBindings=new Map();this._stubUISourceCodes=new Map();this._stubProject=new Bindings.ContentProviderBasedProject(workspace,'jsSourceMaps:stub:'+target.id(),Workspace.projectTypes.Service,'',true);this._eventListeners=[this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapWillAttach,this._sourceMapWillAttach,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapFailedToAttach,this._sourceMapFailedToAttach,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapAttached,this._sourceMapAttached,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapDetached,this._sourceMapDetached,this),];}
_addStubUISourceCode(script){const stubUISourceCode=this._stubProject.addContentProvider(script.sourceURL+':sourcemap',Common.StaticContentProvider.fromString(script.sourceURL,Common.resourceTypes.Script,'\n\n\n\n\n// Please wait a bit.\n// Compiled script is not shown while source map is being loaded!'),'text/javascript');this._stubUISourceCodes.set(script,stubUISourceCode);}
_removeStubUISourceCode(script){const uiSourceCode=this._stubUISourceCodes.get(script);this._stubUISourceCodes.delete(script);this._stubProject.removeFile(uiSourceCode.url());this._debuggerWorkspaceBinding.updateLocations(script);}
static uiSourceCodeOrigin(uiSourceCode){const sourceMap=uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol];if(!sourceMap)
return null;return sourceMap.compiledURL();}
mapsToSourceCode(rawLocation){const script=rawLocation.script();const sourceMap=script?this._sourceMapManager.sourceMapForClient(script):null;if(!sourceMap)
return true;return!!sourceMap.findEntry(rawLocation.lineNumber,rawLocation.columnNumber);}
uiSourceCodeForURL(url,isContentScript){return isContentScript?this._contentScriptsProject.uiSourceCodeForURL(url):this._regularProject.uiSourceCodeForURL(url);}
rawLocationToUILocation(rawLocation){const script=rawLocation.script();if(!script)
return null;const lineNumber=rawLocation.lineNumber-script.lineOffset;let columnNumber=rawLocation.columnNumber;if(!lineNumber)
columnNumber-=script.columnOffset;const stubUISourceCode=this._stubUISourceCodes.get(script);if(stubUISourceCode)
return new Workspace.UILocation(stubUISourceCode,lineNumber,columnNumber);const sourceMap=this._sourceMapManager.sourceMapForClient(script);if(!sourceMap)
return null;const entry=sourceMap.findEntry(lineNumber,columnNumber);if(!entry||!entry.sourceURL)
return null;const uiSourceCode=script.isContentScript()?this._contentScriptsProject.uiSourceCodeForURL(entry.sourceURL):this._regularProject.uiSourceCodeForURL(entry.sourceURL);if(!uiSourceCode)
return null;return uiSourceCode.uiLocation((entry.sourceLineNumber),(entry.sourceColumnNumber));}
uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber){const sourceMap=uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol];if(!sourceMap)
return[];const scripts=this._sourceMapManager.clientsForSourceMap(sourceMap);if(!scripts.length)
return[];const entry=sourceMap.sourceLineMapping(uiSourceCode.url(),lineNumber,columnNumber);if(!entry)
return[];return scripts.map(script=>this._debuggerModel.createRawLocation(script,entry.lineNumber+script.lineOffset,!entry.lineNumber?entry.columnNumber+script.columnOffset:entry.columnNumber));}
_sourceMapWillAttach(event){const script=(event.data);this._addStubUISourceCode(script);this._debuggerWorkspaceBinding.updateLocations(script);}
_sourceMapFailedToAttach(event){const script=(event.data);this._removeStubUISourceCode(script);}
_sourceMapAttached(event){const script=(event.data.client);const sourceMap=(event.data.sourceMap);this._removeStubUISourceCode(script);if(Bindings.blackboxManager.isBlackboxedURL(script.sourceURL,script.isContentScript())){this._sourceMapAttachedForTest(sourceMap);return;}
this._populateSourceMapSources(script,sourceMap);this._sourceMapAttachedForTest(sourceMap);}
_sourceMapDetached(event){const script=(event.data.client);const frameId=script[Bindings.CompilerScriptMapping._frameIdSymbol];const sourceMap=(event.data.sourceMap);const bindings=script.isContentScript()?this._contentScriptsBindings:this._regularBindings;for(const sourceURL of sourceMap.sourceURLs()){const binding=bindings.get(sourceURL);if(binding){binding.removeSourceMap(sourceMap,frameId);if(!binding._uiSourceCode)
bindings.delete(sourceURL);}}
this._debuggerWorkspaceBinding.updateLocations(script);}
sourceMapForScript(script){return this._sourceMapManager.sourceMapForClient(script);}
_sourceMapAttachedForTest(sourceMap){}
_populateSourceMapSources(script,sourceMap){const frameId=Bindings.frameIdForScript(script);script[Bindings.CompilerScriptMapping._frameIdSymbol]=frameId;const project=script.isContentScript()?this._contentScriptsProject:this._regularProject;const bindings=script.isContentScript()?this._contentScriptsBindings:this._regularBindings;for(const sourceURL of sourceMap.sourceURLs()){let binding=bindings.get(sourceURL);if(!binding){binding=new Bindings.CompilerScriptMapping.Binding(project,sourceURL);bindings.set(sourceURL,binding);}
binding.addSourceMap(sourceMap,frameId);}
this._debuggerWorkspaceBinding.updateLocations(script);}
static uiLineHasMapping(uiSourceCode,lineNumber){const sourceMap=uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol];if(!sourceMap)
return true;return!!sourceMap.sourceLineMapping(uiSourceCode.url(),lineNumber,0);}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._regularProject.dispose();this._contentScriptsProject.dispose();this._stubProject.dispose();}};Bindings.CompilerScriptMapping._frameIdSymbol=Symbol('Bindings.CompilerScriptMapping._frameIdSymbol');Bindings.CompilerScriptMapping._sourceMapSymbol=Symbol('Bindings.CompilerScriptMapping._sourceMapSymbol');Bindings.CompilerScriptMapping.Binding=class{constructor(project,url){this._project=project;this._url=url;this._referringSourceMaps=[];this._activeSourceMap=null;this._uiSourceCode=null;}
_recreateUISourceCodeIfNeeded(frameId){const sourceMap=this._referringSourceMaps.peekLast();if(this._activeSourceMap===sourceMap)
return;this._activeSourceMap=sourceMap;const newUISourceCode=this._project.createUISourceCode(this._url,Common.resourceTypes.SourceMapScript);newUISourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol]=sourceMap;const contentProvider=sourceMap.sourceContentProvider(this._url,Common.resourceTypes.SourceMapScript);const mimeType=Common.ResourceType.mimeFromURL(this._url)||'text/javascript';const embeddedContent=sourceMap.embeddedContentByURL(this._url);const metadata=typeof embeddedContent==='string'?new Workspace.UISourceCodeMetadata(null,embeddedContent.length):null;if(this._uiSourceCode){Bindings.NetworkProject.cloneInitialFrameAttribution(this._uiSourceCode,newUISourceCode);this._project.removeFile(this._uiSourceCode.url());}else{Bindings.NetworkProject.setInitialFrameAttribution(newUISourceCode,frameId);}
this._uiSourceCode=newUISourceCode;this._project.addUISourceCodeWithProvider(this._uiSourceCode,contentProvider,metadata,mimeType);}
addSourceMap(sourceMap,frameId){if(this._uiSourceCode)
Bindings.NetworkProject.addFrameAttribution(this._uiSourceCode,frameId);this._referringSourceMaps.push(sourceMap);this._recreateUISourceCodeIfNeeded(frameId);}
removeSourceMap(sourceMap,frameId){Bindings.NetworkProject.removeFrameAttribution((this._uiSourceCode),frameId);const lastIndex=this._referringSourceMaps.lastIndexOf(sourceMap);if(lastIndex!==-1)
this._referringSourceMaps.splice(lastIndex,1);if(!this._referringSourceMaps.length){this._project.removeFile(this._uiSourceCode.url());this._uiSourceCode=null;}else{this._recreateUISourceCodeIfNeeded(frameId);}}};;Bindings.ResourceScriptMapping=class{constructor(debuggerModel,workspace,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._workspace=workspace;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._uiSourceCodeToScriptFile=new Map();this._projects=new Map();this._acceptedScripts=new Set();const runtimeModel=debuggerModel.runtimeModel();this._eventListeners=[this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource,this._parsedScriptSource,this),this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._globalObjectCleared,this),runtimeModel.addEventListener(SDK.RuntimeModel.Events.ExecutionContextDestroyed,this._executionContextDestroyed,this),];}
_project(script){const frameId=script[Bindings.ResourceScriptMapping._frameIdSymbol];const prefix=script.isContentScript()?'js:extensions:':'js::';const projectId=prefix+this._debuggerModel.target().id()+':'+frameId;let project=this._projects.get(projectId);if(!project){const projectType=script.isContentScript()?Workspace.projectTypes.ContentScripts:Workspace.projectTypes.Network;project=new Bindings.ContentProviderBasedProject(this._workspace,projectId,projectType,'',false);Bindings.NetworkProject.setTargetForProject(project,this._debuggerModel.target());this._projects.set(projectId,project);}
return project;}
rawLocationToUILocation(rawLocation){const script=rawLocation.script();if(!script)
return null;const project=this._project(script);const uiSourceCode=project.uiSourceCodeForURL(script.sourceURL);if(!uiSourceCode)
return null;const scriptFile=this._uiSourceCodeToScriptFile.get(uiSourceCode);if(!scriptFile)
return null;if((scriptFile.hasDivergedFromVM()&&!scriptFile.isMergingToVM())||scriptFile.isDivergingFromVM())
return null;if(!scriptFile._hasScripts([script]))
return null;const lineNumber=rawLocation.lineNumber-(script.isInlineScriptWithSourceURL()?script.lineOffset:0);let columnNumber=rawLocation.columnNumber||0;if(script.isInlineScriptWithSourceURL()&&!lineNumber&&columnNumber)
columnNumber-=script.columnOffset;return uiSourceCode.uiLocation(lineNumber,columnNumber);}
uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber){const scriptFile=this._uiSourceCodeToScriptFile.get(uiSourceCode);if(!scriptFile)
return[];const script=scriptFile._script;if(script.isInlineScriptWithSourceURL()){return[this._debuggerModel.createRawLocation(script,lineNumber+script.lineOffset,lineNumber?columnNumber:columnNumber+script.columnOffset)];}
return[this._debuggerModel.createRawLocation(script,lineNumber,columnNumber)];}
_acceptsScript(script){if(!script.sourceURL||script.isLiveEdit()||(script.isInlineScript()&&!script.hasSourceURL))
return false;if(script.isContentScript()&&!script.hasSourceURL){const parsedURL=new Common.ParsedURL(script.sourceURL);if(!parsedURL.isValid)
return false;}
return true;}
_parsedScriptSource(event){const script=(event.data);if(!this._acceptsScript(script))
return;this._acceptedScripts.add(script);const originalContentProvider=script.originalContentProvider();const frameId=Bindings.frameIdForScript(script);script[Bindings.ResourceScriptMapping._frameIdSymbol]=frameId;const url=script.sourceURL;const project=this._project(script);const oldUISourceCode=project.uiSourceCodeForURL(url);if(oldUISourceCode){const scriptFile=this._uiSourceCodeToScriptFile.get(oldUISourceCode);this._removeScript(scriptFile._script);}
const uiSourceCode=project.createUISourceCode(url,originalContentProvider.contentType());Bindings.NetworkProject.setInitialFrameAttribution(uiSourceCode,frameId);const metadata=Bindings.metadataForURL(this._debuggerModel.target(),frameId,url);const scriptFile=new Bindings.ResourceScriptFile(this,uiSourceCode,[script]);this._uiSourceCodeToScriptFile.set(uiSourceCode,scriptFile);project.addUISourceCodeWithProvider(uiSourceCode,originalContentProvider,metadata,'text/javascript');this._debuggerWorkspaceBinding.updateLocations(script);}
scriptFile(uiSourceCode){return this._uiSourceCodeToScriptFile.get(uiSourceCode)||null;}
_removeScript(script){if(!this._acceptedScripts.has(script))
return;this._acceptedScripts.delete(script);const project=this._project(script);const uiSourceCode=(project.uiSourceCodeForURL(script.sourceURL));const scriptFile=this._uiSourceCodeToScriptFile.get(uiSourceCode);scriptFile.dispose();this._uiSourceCodeToScriptFile.delete(uiSourceCode);project.removeFile(script.sourceURL);this._debuggerWorkspaceBinding.updateLocations(script);}
_executionContextDestroyed(event){const executionContext=(event.data);const scripts=this._debuggerModel.scriptsForExecutionContext(executionContext);for(const script of scripts)
this._removeScript(script);}
_globalObjectCleared(event){const scripts=Array.from(this._acceptedScripts);for(const script of scripts)
this._removeScript(script);}
resetForTest(){const scripts=Array.from(this._acceptedScripts);for(const script of scripts)
this._removeScript(script);}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);const scripts=Array.from(this._acceptedScripts);for(const script of scripts)
this._removeScript(script);for(const project of this._projects.values())
project.removeProject();this._projects.clear();}};Bindings.ResourceScriptFile=class extends Common.Object{constructor(resourceScriptMapping,uiSourceCode,scripts){super();console.assert(scripts.length);this._resourceScriptMapping=resourceScriptMapping;this._uiSourceCode=uiSourceCode;if(this._uiSourceCode.contentType().isScript())
this._script=scripts[scripts.length-1];this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this);this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);}
_hasScripts(scripts){return this._script&&this._script===scripts[0];}
_isDiverged(){if(this._uiSourceCode.isDirty())
return true;if(!this._script)
return false;if(typeof this._scriptSource==='undefined')
return false;const workingCopy=this._uiSourceCode.workingCopy();if(!workingCopy)
return false;if(!workingCopy.startsWith(this._scriptSource.trimRight()))
return true;const suffix=this._uiSourceCode.workingCopy().substr(this._scriptSource.length);return!!suffix.length&&!suffix.match(SDK.Script.sourceURLRegex);}
_workingCopyChanged(event){this._update();}
_workingCopyCommitted(event){if(this._uiSourceCode.project().canSetFileContent())
return;if(!this._script)
return;const debuggerModel=this._resourceScriptMapping._debuggerModel;const breakpoints=Bindings.breakpointManager.breakpointLocationsForUISourceCode(this._uiSourceCode).map(breakpointLocation=>breakpointLocation.breakpoint);const source=this._uiSourceCode.workingCopy();debuggerModel.setScriptSource(this._script.scriptId,source,scriptSourceWasSet.bind(this));async function scriptSourceWasSet(error,exceptionDetails){if(!error&&!exceptionDetails)
this._scriptSource=source;this._update();if(!error&&!exceptionDetails){breakpoints.map(breakpoint=>breakpoint.refreshInDebugger());return;}
if(!exceptionDetails){Common.console.addMessage(Common.UIString('LiveEdit failed: %s',error),Common.Console.MessageLevel.Warning);return;}
const messageText=Common.UIString('LiveEdit compile failed: %s',exceptionDetails.text);this._uiSourceCode.addLineMessage(Workspace.UISourceCode.Message.Level.Error,messageText,exceptionDetails.lineNumber,exceptionDetails.columnNumber);}}
_update(){if(this._isDiverged()&&!this._hasDivergedFromVM)
this._divergeFromVM();else if(!this._isDiverged()&&this._hasDivergedFromVM)
this._mergeToVM();}
_divergeFromVM(){this._isDivergingFromVM=true;this._resourceScriptMapping._debuggerWorkspaceBinding.updateLocations(this._script);delete this._isDivergingFromVM;this._hasDivergedFromVM=true;this.dispatchEventToListeners(Bindings.ResourceScriptFile.Events.DidDivergeFromVM,this._uiSourceCode);}
_mergeToVM(){delete this._hasDivergedFromVM;this._isMergingToVM=true;this._resourceScriptMapping._debuggerWorkspaceBinding.updateLocations(this._script);delete this._isMergingToVM;this.dispatchEventToListeners(Bindings.ResourceScriptFile.Events.DidMergeToVM,this._uiSourceCode);}
hasDivergedFromVM(){return this._hasDivergedFromVM;}
isDivergingFromVM(){return this._isDivergingFromVM;}
isMergingToVM(){return this._isMergingToVM;}
checkMapping(){if(!this._script||typeof this._scriptSource!=='undefined'){this._mappingCheckedForTest();return;}
this._script.requestContent().then(callback.bind(this));function callback(source){this._scriptSource=source;this._update();this._mappingCheckedForTest();}}
_mappingCheckedForTest(){}
dispose(){this._uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this);this._uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);}
addSourceMapURL(sourceMapURL){if(!this._script)
return;this._script.debuggerModel.setSourceMapURL(this._script,sourceMapURL);}
hasSourceMapURL(){return this._script&&!!this._script.sourceMapURL;}};Bindings.ResourceScriptMapping._frameIdSymbol=Symbol('frameid');Bindings.ResourceScriptFile.Events={DidMergeToVM:Symbol('DidMergeToVM'),DidDivergeFromVM:Symbol('DidDivergeFromVM'),};;Bindings.SASSSourceMapping=class{constructor(target,sourceMapManager,workspace){this._sourceMapManager=sourceMapManager;this._project=new Bindings.ContentProviderBasedProject(workspace,'cssSourceMaps:'+target.id(),Workspace.projectTypes.Network,'',false);Bindings.NetworkProject.setTargetForProject(this._project,target);this._eventListeners=[this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapAttached,this._sourceMapAttached,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapDetached,this._sourceMapDetached,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapChanged,this._sourceMapChanged,this)];}
_sourceMapAttachedForTest(sourceMap){}
_sourceMapAttached(event){const header=(event.data.client);const sourceMap=(event.data.sourceMap);for(const sassURL of sourceMap.sourceURLs()){let uiSourceCode=this._project.uiSourceCodeForURL(sassURL);if(uiSourceCode){Bindings.NetworkProject.addFrameAttribution(uiSourceCode,header.frameId);continue;}
const contentProvider=sourceMap.sourceContentProvider(sassURL,Common.resourceTypes.SourceMapStyleSheet);const mimeType=Common.ResourceType.mimeFromURL(sassURL)||contentProvider.contentType().canonicalMimeType();const embeddedContent=sourceMap.embeddedContentByURL(sassURL);const metadata=typeof embeddedContent==='string'?new Workspace.UISourceCodeMetadata(null,embeddedContent.length):null;uiSourceCode=this._project.createUISourceCode(sassURL,contentProvider.contentType());Bindings.NetworkProject.setInitialFrameAttribution(uiSourceCode,header.frameId);uiSourceCode[Bindings.SASSSourceMapping._sourceMapSymbol]=sourceMap;this._project.addUISourceCodeWithProvider(uiSourceCode,contentProvider,metadata,mimeType);}
Bindings.cssWorkspaceBinding.updateLocations(header);this._sourceMapAttachedForTest(sourceMap);}
_sourceMapDetached(event){const header=(event.data.client);const sourceMap=(event.data.sourceMap);const headers=this._sourceMapManager.clientsForSourceMap(sourceMap);for(const sassURL of sourceMap.sourceURLs()){if(headers.length){const uiSourceCode=(this._project.uiSourceCodeForURL(sassURL));Bindings.NetworkProject.removeFrameAttribution(uiSourceCode,header.frameId);}else{this._project.removeFile(sassURL);}}
Bindings.cssWorkspaceBinding.updateLocations(header);}
_sourceMapChanged(event){const sourceMap=(event.data.sourceMap);const newSources=(event.data.newSources);const headers=this._sourceMapManager.clientsForSourceMap(sourceMap);for(const sourceURL of newSources.keys()){const uiSourceCode=this._project.uiSourceCodeForURL(sourceURL);if(!uiSourceCode){console.error('Failed to update source for '+sourceURL);continue;}
const sassText=(newSources.get(sourceURL));uiSourceCode.setWorkingCopy(sassText);}
for(const header of headers)
Bindings.cssWorkspaceBinding.updateLocations(header);}
rawLocationToUILocation(rawLocation){const header=rawLocation.header();if(!header)
return null;const sourceMap=this._sourceMapManager.sourceMapForClient(header);if(!sourceMap)
return null;const entry=sourceMap.findEntry(rawLocation.lineNumber,rawLocation.columnNumber);if(!entry||!entry.sourceURL)
return null;const uiSourceCode=this._project.uiSourceCodeForURL(entry.sourceURL);if(!uiSourceCode)
return null;return uiSourceCode.uiLocation(entry.sourceLineNumber||0,entry.sourceColumnNumber);}
uiLocationToRawLocations(uiLocation){const sourceMap=uiLocation.uiSourceCode[Bindings.SASSSourceMapping._sourceMapSymbol];if(!sourceMap)
return[];const entries=sourceMap.findReverseEntries(uiLocation.uiSourceCode.url(),uiLocation.lineNumber,uiLocation.columnNumber);const locations=[];for(const header of this._sourceMapManager.clientsForSourceMap(sourceMap))
locations.pushAll(entries.map(entry=>new SDK.CSSLocation(header,entry.lineNumber,entry.columnNumber)));return locations;}
dispose(){this._project.dispose();Common.EventTarget.removeEventListeners(this._eventListeners);}};Bindings.SASSSourceMapping._sourceMapSymbol=Symbol('sourceMap');;Bindings.StylesSourceMapping=class{constructor(cssModel,workspace){this._cssModel=cssModel;const target=this._cssModel.target();this._project=new Bindings.ContentProviderBasedProject(workspace,'css:'+target.id(),Workspace.projectTypes.Network,'',false);Bindings.NetworkProject.setTargetForProject(this._project,target);this._styleFiles=new Map();this._eventListeners=[this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._styleSheetAdded,this),this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._styleSheetRemoved,this),this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._styleSheetChanged,this),];}
rawLocationToUILocation(rawLocation){const header=rawLocation.header();if(!header||!this._acceptsHeader(header))
return null;const styleFile=this._styleFiles.get(header.resourceURL());if(!styleFile)
return null;let lineNumber=rawLocation.lineNumber;let columnNumber=rawLocation.columnNumber;if(header.isInline&&header.hasSourceURL){lineNumber-=header.lineNumberInSource(0);columnNumber-=header.columnNumberInSource(lineNumber,0);}
return styleFile._uiSourceCode.uiLocation(lineNumber,columnNumber);}
uiLocationToRawLocations(uiLocation){const styleFile=uiLocation.uiSourceCode[Bindings.StyleFile._symbol];if(!styleFile)
return[];const rawLocations=[];for(const header of styleFile._headers){let lineNumber=uiLocation.lineNumber;let columnNumber=uiLocation.columnNumber;if(header.isInline&&header.hasSourceURL){columnNumber=header.columnNumberInSource(lineNumber,columnNumber);lineNumber=header.lineNumberInSource(lineNumber);}
rawLocations.push(new SDK.CSSLocation(header,lineNumber,columnNumber));}
return rawLocations;}
_acceptsHeader(header){if(header.isInline&&!header.hasSourceURL&&header.origin!=='inspector')
return false;if(!header.resourceURL())
return false;return true;}
_styleSheetAdded(event){const header=(event.data);if(!this._acceptsHeader(header))
return;const url=header.resourceURL();let styleFile=this._styleFiles.get(url);if(!styleFile){styleFile=new Bindings.StyleFile(this._cssModel,this._project,header);this._styleFiles.set(url,styleFile);}else{styleFile.addHeader(header);}}
_styleSheetRemoved(event){const header=(event.data);if(!this._acceptsHeader(header))
return;const url=header.resourceURL();const styleFile=this._styleFiles.get(url);if(styleFile._headers.size===1){styleFile.dispose();this._styleFiles.delete(url);}else{styleFile.removeHeader(header);}}
_styleSheetChanged(event){const header=this._cssModel.styleSheetHeaderForId(event.data.styleSheetId);if(!header||!this._acceptsHeader(header))
return;const styleFile=this._styleFiles.get(header.resourceURL());styleFile._styleSheetChanged(header);}
dispose(){for(const styleFile of this._styleFiles.values())
styleFile.dispose();this._styleFiles.clear();Common.EventTarget.removeEventListeners(this._eventListeners);this._project.removeProject();}};Bindings.StyleFile=class{constructor(cssModel,project,header){this._cssModel=cssModel;this._project=project;this._headers=new Set([header]);const target=cssModel.target();const url=header.resourceURL();const metadata=Bindings.metadataForURL(target,header.frameId,url);this._uiSourceCode=this._project.createUISourceCode(url,header.contentType());this._uiSourceCode[Bindings.StyleFile._symbol]=this;Bindings.NetworkProject.setInitialFrameAttribution(this._uiSourceCode,header.frameId);this._project.addUISourceCodeWithProvider(this._uiSourceCode,this,metadata,'text/css');this._eventListeners=[this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this)];this._throttler=new Common.Throttler(Bindings.StyleFile.updateTimeout);this._terminated=false;}
addHeader(header){this._headers.add(header);Bindings.NetworkProject.addFrameAttribution(this._uiSourceCode,header.frameId);}
removeHeader(header){this._headers.delete(header);Bindings.NetworkProject.removeFrameAttribution(this._uiSourceCode,header.frameId);}
_styleSheetChanged(header){console.assert(this._headers.has(header));if(this._isUpdatingHeaders||!this._headers.has(header))
return;const mirrorContentBound=this._mirrorContent.bind(this,header,true);this._throttler.schedule(mirrorContentBound,false);}
_workingCopyCommitted(event){if(this._isAddingRevision)
return;const mirrorContentBound=this._mirrorContent.bind(this,this._uiSourceCode,true);this._throttler.schedule(mirrorContentBound,true);}
_workingCopyChanged(event){if(this._isAddingRevision)
return;const mirrorContentBound=this._mirrorContent.bind(this,this._uiSourceCode,false);this._throttler.schedule(mirrorContentBound,false);}
async _mirrorContent(fromProvider,majorChange){if(this._terminated){this._styleFileSyncedForTest();return;}
let newContent=null;if(fromProvider===this._uiSourceCode){newContent=this._uiSourceCode.workingCopy();}else{newContent=await fromProvider.requestContent();}
if(newContent===null||this._terminated){this._styleFileSyncedForTest();return;}
if(fromProvider!==this._uiSourceCode){this._isAddingRevision=true;this._uiSourceCode.addRevision(newContent);this._isAddingRevision=false;}
this._isUpdatingHeaders=true;const promises=[];for(const header of this._headers){if(header===fromProvider)
continue;promises.push(this._cssModel.setStyleSheetText(header.id,newContent,majorChange));}
await Promise.all(promises);this._isUpdatingHeaders=false;this._styleFileSyncedForTest();}
_styleFileSyncedForTest(){}
dispose(){if(this._terminated)
return;this._terminated=true;this._project.removeFile(this._uiSourceCode.url());Common.EventTarget.removeEventListeners(this._eventListeners);}
contentURL(){return this._headers.firstValue().originalContentProvider().contentURL();}
contentType(){return this._headers.firstValue().originalContentProvider().contentType();}
contentEncoded(){return this._headers.firstValue().originalContentProvider().contentEncoded();}
requestContent(){return this._headers.firstValue().originalContentProvider().requestContent();}
searchInContent(query,caseSensitive,isRegex){return this._headers.firstValue().originalContentProvider().searchInContent(query,caseSensitive,isRegex);}};Bindings.StyleFile._symbol=Symbol('Bindings.StyleFile._symbol');Bindings.StyleFile.updateTimeout=200;;Bindings.CSSWorkspaceBinding=class{constructor(targetManager,workspace){this._workspace=workspace;this._modelToInfo=new Map();this._sourceMappings=[];targetManager.observeModels(SDK.CSSModel,this);}
modelAdded(cssModel){this._modelToInfo.set(cssModel,new Bindings.CSSWorkspaceBinding.ModelInfo(cssModel,this._workspace));}
modelRemoved(cssModel){this._modelToInfo.get(cssModel)._dispose();this._modelToInfo.delete(cssModel);}
updateLocations(header){this._modelToInfo.get(header.cssModel())._updateLocations(header);}
createLiveLocation(rawLocation,updateDelegate,locationPool){return this._modelToInfo.get(rawLocation.cssModel())._createLiveLocation(rawLocation,updateDelegate,locationPool);}
propertyUILocation(cssProperty,forName){const style=cssProperty.ownerStyle;if(!style||style.type!==SDK.CSSStyleDeclaration.Type.Regular||!style.styleSheetId)
return null;const header=style.cssModel().styleSheetHeaderForId(style.styleSheetId);if(!header)
return null;const range=forName?cssProperty.nameRange():cssProperty.valueRange();if(!range)
return null;const lineNumber=range.startLine;const columnNumber=range.startColumn;const rawLocation=new SDK.CSSLocation(header,header.lineNumberInSource(lineNumber),header.columnNumberInSource(lineNumber,columnNumber));return this.rawLocationToUILocation(rawLocation);}
rawLocationToUILocation(rawLocation){for(let i=this._sourceMappings.length-1;i>=0;--i){const uiLocation=this._sourceMappings[i].rawLocationToUILocation(rawLocation);if(uiLocation)
return uiLocation;}
return this._modelToInfo.get(rawLocation.cssModel())._rawLocationToUILocation(rawLocation);}
uiLocationToRawLocations(uiLocation){for(let i=this._sourceMappings.length-1;i>=0;--i){const rawLocations=this._sourceMappings[i].uiLocationToRawLocations(uiLocation);if(rawLocations.length)
return rawLocations;}
const rawLocations=[];for(const modelInfo of this._modelToInfo.values())
rawLocations.pushAll(modelInfo._uiLocationToRawLocations(uiLocation));return rawLocations;}
addSourceMapping(sourceMapping){this._sourceMappings.push(sourceMapping);}};Bindings.CSSWorkspaceBinding.SourceMapping=function(){};Bindings.CSSWorkspaceBinding.SourceMapping.prototype={rawLocationToUILocation(rawLocation){},uiLocationToRawLocations(uiLocation){},};Bindings.CSSWorkspaceBinding.ModelInfo=class{constructor(cssModel,workspace){this._eventListeners=[cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._styleSheetAdded,this),cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._styleSheetRemoved,this)];this._stylesSourceMapping=new Bindings.StylesSourceMapping(cssModel,workspace);const sourceMapManager=cssModel.sourceMapManager();this._sassSourceMapping=new Bindings.SASSSourceMapping(cssModel.target(),sourceMapManager,workspace);this._locations=new Multimap();this._unboundLocations=new Multimap();}
_createLiveLocation(rawLocation,updateDelegate,locationPool){const location=new Bindings.CSSWorkspaceBinding.LiveLocation(rawLocation,this,updateDelegate,locationPool);const header=rawLocation.header();if(header){location._header=header;this._locations.set(header,location);location.update();}else{this._unboundLocations.set(rawLocation.url,location);}
return location;}
_disposeLocation(location){if(location._header)
this._locations.delete(location._header,location);else
this._unboundLocations.delete(location._url,location);}
_updateLocations(header){for(const location of this._locations.get(header))
location.update();}
_styleSheetAdded(event){const header=(event.data);if(!header.sourceURL)
return;for(const location of this._unboundLocations.get(header.sourceURL)){location._header=header;this._locations.set(header,location);location.update();}
this._unboundLocations.deleteAll(header.sourceURL);}
_styleSheetRemoved(event){const header=(event.data);for(const location of this._locations.get(header)){location._header=null;this._unboundLocations.set(location._url,location);location.update();}
this._locations.deleteAll(header);}
_rawLocationToUILocation(rawLocation){let uiLocation=null;uiLocation=uiLocation||this._sassSourceMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||this._stylesSourceMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||Bindings.resourceMapping.cssLocationToUILocation(rawLocation);return uiLocation;}
_uiLocationToRawLocations(uiLocation){const rawLocations=this._sassSourceMapping.uiLocationToRawLocations(uiLocation);if(rawLocations.length)
return rawLocations;return this._stylesSourceMapping.uiLocationToRawLocations(uiLocation);}
_dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._stylesSourceMapping.dispose();this._sassSourceMapping.dispose();}};Bindings.CSSWorkspaceBinding.LiveLocation=class extends Bindings.LiveLocationWithPool{constructor(rawLocation,info,updateDelegate,locationPool){super(updateDelegate,locationPool);this._url=rawLocation.url;this._lineNumber=rawLocation.lineNumber;this._columnNumber=rawLocation.columnNumber;this._info=info;this._header=null;}
uiLocation(){if(!this._header)
return null;const rawLocation=new SDK.CSSLocation(this._header,this._lineNumber,this._columnNumber);return Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation);}
dispose(){super.dispose();this._info._disposeLocation(this);}
isBlackboxed(){return false;}};Bindings.cssWorkspaceBinding;;Bindings.DebuggerWorkspaceBinding=class{constructor(targetManager,workspace){this._workspace=workspace;this._sourceMappings=[];this._debuggerModelToData=new Map();targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.GlobalObjectCleared,this._globalObjectCleared,this);targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerResumed,this._debuggerResumed,this);targetManager.observeModels(SDK.DebuggerModel,this);}
addSourceMapping(sourceMapping){this._sourceMappings.push(sourceMapping);}
modelAdded(debuggerModel){this._debuggerModelToData.set(debuggerModel,new Bindings.DebuggerWorkspaceBinding.ModelData(debuggerModel,this));}
modelRemoved(debuggerModel){const modelData=this._debuggerModelToData.get(debuggerModel);modelData._dispose();this._debuggerModelToData.remove(debuggerModel);}
updateLocations(script){const modelData=this._debuggerModelToData.get(script.debuggerModel);if(modelData)
modelData._updateLocations(script);}
createLiveLocation(rawLocation,updateDelegate,locationPool){const modelData=this._debuggerModelToData.get(rawLocation.script().debuggerModel);return modelData._createLiveLocation(rawLocation,updateDelegate,locationPool);}
createStackTraceTopFrameLiveLocation(rawLocations,updateDelegate,locationPool){console.assert(rawLocations.length);const location=new Bindings.DebuggerWorkspaceBinding.StackTraceTopFrameLocation(rawLocations,this,updateDelegate,locationPool);location.update();return location;}
createCallFrameLiveLocation(location,updateDelegate,locationPool){const script=location.script();if(!script)
return null;const debuggerModel=location.debuggerModel;const liveLocation=this.createLiveLocation(location,updateDelegate,locationPool);this._registerCallFrameLiveLocation(debuggerModel,liveLocation);return liveLocation;}
rawLocationToUILocation(rawLocation){for(let i=0;i<this._sourceMappings.length;++i){const uiLocation=this._sourceMappings[i].rawLocationToUILocation(rawLocation);if(uiLocation)
return uiLocation;}
const modelData=this._debuggerModelToData.get(rawLocation.debuggerModel);return modelData._rawLocationToUILocation(rawLocation);}
uiSourceCodeForSourceMapSourceURL(debuggerModel,url,isContentScript){const modelData=this._debuggerModelToData.get(debuggerModel);if(!modelData)
return null;return modelData._compilerMapping.uiSourceCodeForURL(url,isContentScript);}
uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber){let locations=[];for(let i=0;i<this._sourceMappings.length&&!locations.length;++i)
locations=this._sourceMappings[i].uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber);if(locations.length)
return locations;for(const modelData of this._debuggerModelToData.values())
locations.push(...modelData._uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber));return locations;}
normalizeUILocation(uiLocation){const rawLocations=this.uiLocationToRawLocations(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber);for(const location of rawLocations){const uiLocationCandidate=this.rawLocationToUILocation(location);if(uiLocationCandidate)
return uiLocationCandidate;}
return uiLocation;}
scriptFile(uiSourceCode,debuggerModel){const modelData=this._debuggerModelToData.get(debuggerModel);return modelData?modelData._resourceMapping.scriptFile(uiSourceCode):null;}
sourceMapForScript(script){const modelData=this._debuggerModelToData.get(script.debuggerModel);if(!modelData)
return null;return modelData._compilerMapping.sourceMapForScript(script);}
_globalObjectCleared(event){const debuggerModel=(event.data);this._reset(debuggerModel);}
_reset(debuggerModel){const modelData=this._debuggerModelToData.get(debuggerModel);modelData.callFrameLocations.valuesArray().forEach(location=>this._removeLiveLocation(location));modelData.callFrameLocations.clear();}
_resetForTest(target){const debuggerModel=(target.model(SDK.DebuggerModel));const modelData=this._debuggerModelToData.get(debuggerModel);modelData._resourceMapping.resetForTest();}
_registerCallFrameLiveLocation(debuggerModel,location){const locations=this._debuggerModelToData.get(debuggerModel).callFrameLocations;locations.add(location);}
_removeLiveLocation(location){const modelData=this._debuggerModelToData.get(location._script.debuggerModel);if(modelData)
modelData._disposeLocation(location);}
_debuggerResumed(event){const debuggerModel=(event.data);this._reset(debuggerModel);}};Bindings.DebuggerWorkspaceBinding.ModelData=class{constructor(debuggerModel,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this.callFrameLocations=new Set();const workspace=debuggerWorkspaceBinding._workspace;this._defaultMapping=new Bindings.DefaultScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding);this._resourceMapping=new Bindings.ResourceScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding);this._compilerMapping=new Bindings.CompilerScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding);this._locations=new Multimap();debuggerModel.setBeforePausedCallback(this._beforePaused.bind(this));}
_createLiveLocation(rawLocation,updateDelegate,locationPool){const script=(rawLocation.script());console.assert(script);const location=new Bindings.DebuggerWorkspaceBinding.Location(script,rawLocation,this._debuggerWorkspaceBinding,updateDelegate,locationPool);this._locations.set(script,location);location.update();return location;}
_disposeLocation(location){this._locations.delete(location._script,location);}
_updateLocations(script){for(const location of this._locations.get(script))
location.update();}
_rawLocationToUILocation(rawLocation){let uiLocation=null;uiLocation=uiLocation||this._compilerMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||this._resourceMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||Bindings.resourceMapping.jsLocationToUILocation(rawLocation);uiLocation=uiLocation||this._defaultMapping.rawLocationToUILocation(rawLocation);return(uiLocation);}
_uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber){let locations=this._compilerMapping.uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber);locations=locations.length?locations:this._resourceMapping.uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber);locations=locations.length?locations:Bindings.resourceMapping.uiLocationToJSLocations(uiSourceCode,lineNumber,columnNumber);locations=locations.length?locations:this._defaultMapping.uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber);return locations;}
_beforePaused(debuggerPausedDetails){return!!this._compilerMapping.mapsToSourceCode(debuggerPausedDetails.callFrames[0].location());}
_dispose(){this._debuggerModel.setBeforePausedCallback(null);this._compilerMapping.dispose();this._resourceMapping.dispose();this._defaultMapping.dispose();}};Bindings.DebuggerWorkspaceBinding.Location=class extends Bindings.LiveLocationWithPool{constructor(script,rawLocation,binding,updateDelegate,locationPool){super(updateDelegate,locationPool);this._script=script;this._rawLocation=rawLocation;this._binding=binding;}
uiLocation(){const debuggerModelLocation=this._rawLocation;return this._binding.rawLocationToUILocation(debuggerModelLocation);}
dispose(){super.dispose();this._binding._removeLiveLocation(this);}
isBlackboxed(){const uiLocation=this.uiLocation();return uiLocation?Bindings.blackboxManager.isBlackboxedUISourceCode(uiLocation.uiSourceCode):false;}};Bindings.DebuggerWorkspaceBinding.StackTraceTopFrameLocation=class extends Bindings.LiveLocationWithPool{constructor(rawLocations,binding,updateDelegate,locationPool){super(updateDelegate,locationPool);this._updateScheduled=true;this._current=null;this._locations=rawLocations.map(location=>binding.createLiveLocation(location,this._scheduleUpdate.bind(this),locationPool));this._updateLocation();}
uiLocation(){return this._current.uiLocation();}
isBlackboxed(){return this._current.isBlackboxed();}
dispose(){super.dispose();for(const location of this._locations)
location.dispose();this._locations=null;this._current=null;}
_scheduleUpdate(){if(this._updateScheduled)
return;this._updateScheduled=true;setImmediate(this._updateLocation.bind(this));}
_updateLocation(){this._updateScheduled=false;if(!this._locations)
return;this._current=this._locations.find(location=>!location.isBlackboxed())||this._locations[0];this.update();}};Bindings.DebuggerSourceMapping=function(){};Bindings.DebuggerSourceMapping.prototype={rawLocationToUILocation(rawLocation){},uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber){},};Bindings.debuggerWorkspaceBinding;;Bindings.BreakpointManager=class extends Common.Object{constructor(workspace,targetManager,debuggerWorkspaceBinding){super();this._storage=new Bindings.BreakpointManager.Storage();this._workspace=workspace;this._targetManager=targetManager;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._breakpointsForUISourceCode=new Map();this._breakpointByStorageId=new Map();this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._uiSourceCodeAdded,this);}
static _breakpointStorageId(url,lineNumber,columnNumber){if(!url)
return'';return url+':'+lineNumber+':'+columnNumber;}
copyBreakpoints(fromURL,toSourceCode){const breakpointItems=this._storage.breakpointItems(fromURL);for(const item of breakpointItems)
this.setBreakpoint(toSourceCode,item.lineNumber,item.columnNumber,item.condition,item.enabled);}
_restoreBreakpoints(uiSourceCode){const url=uiSourceCode.url();if(!url)
return;this._storage.mute();const breakpointItems=this._storage.breakpointItems(url);for(const item of breakpointItems)
this._innerSetBreakpoint(uiSourceCode,item.lineNumber,item.columnNumber,item.condition,item.enabled);this._storage.unmute();}
_uiSourceCodeAdded(event){const uiSourceCode=(event.data);this._restoreBreakpoints(uiSourceCode);}
setBreakpoint(uiSourceCode,lineNumber,columnNumber,condition,enabled){let uiLocation=new Workspace.UILocation(uiSourceCode,lineNumber,columnNumber);const normalizedLocation=this._debuggerWorkspaceBinding.normalizeUILocation(uiLocation);if(normalizedLocation.id()!==uiLocation.id()){Common.Revealer.reveal(normalizedLocation);uiLocation=normalizedLocation;}
return this._innerSetBreakpoint(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber,condition,enabled);}
_innerSetBreakpoint(uiSourceCode,lineNumber,columnNumber,condition,enabled){const itemId=Bindings.BreakpointManager._breakpointStorageId(uiSourceCode.url(),lineNumber,columnNumber);let breakpoint=this._breakpointByStorageId.get(itemId);if(breakpoint){breakpoint._updateState(condition,enabled);breakpoint.setPrimaryUISourceCode(uiSourceCode);breakpoint._updateBreakpoint();return breakpoint;}
breakpoint=new Bindings.BreakpointManager.Breakpoint(this,uiSourceCode,uiSourceCode.url(),lineNumber,columnNumber,condition,enabled);this._breakpointByStorageId.set(itemId,breakpoint);return breakpoint;}
findBreakpoint(uiLocation){const breakpoints=this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode);return breakpoints?(breakpoints.get(uiLocation.id()))||null:null;}
possibleBreakpoints(uiSourceCode,textRange){const startLocations=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode,textRange.startLine,textRange.startColumn);const endLocations=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode,textRange.endLine,textRange.endColumn);const endLocationByModel=new Map();for(const location of endLocations)
endLocationByModel.set(location.debuggerModel,location);let startLocation=null;let endLocation=null;for(const location of startLocations){const endLocationCandidate=endLocationByModel.get(location.debuggerModel);if(endLocationCandidate){startLocation=location;endLocation=endLocationCandidate;break;}}
if(!startLocation||!endLocation)
return Promise.resolve([]);return startLocation.debuggerModel.getPossibleBreakpoints(startLocation,endLocation,false).then(toUILocations.bind(this));function toUILocations(locations){let sortedLocations=locations.map(location=>this._debuggerWorkspaceBinding.rawLocationToUILocation(location));sortedLocations=sortedLocations.filter(location=>location&&location.uiSourceCode===uiSourceCode);sortedLocations.sort(Workspace.UILocation.comparator);if(!sortedLocations.length)
return[];const result=[sortedLocations[0]];let lastLocation=sortedLocations[0];for(let i=1;i<sortedLocations.length;++i){if(sortedLocations[i].id()===lastLocation.id())
continue;result.push(sortedLocations[i]);lastLocation=sortedLocations[i];}
return result;}}
breakpointLocationsForUISourceCode(uiSourceCode){const breakpoints=this._breakpointsForUISourceCode.get(uiSourceCode);return breakpoints?Array.from(breakpoints.values()):[];}
allBreakpointLocations(){let result=[];for(const breakpoints of this._breakpointsForUISourceCode.values())
result=result.concat(Array.from(breakpoints.values()));return result;}
_removeBreakpoint(breakpoint,removeFromStorage){if(removeFromStorage)
this._storage._removeBreakpoint(breakpoint);this._breakpointByStorageId.delete(breakpoint._breakpointStorageId());}
_uiLocationAdded(breakpoint,uiLocation){let breakpoints=this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode);if(!breakpoints){breakpoints=new Map();this._breakpointsForUISourceCode.set(uiLocation.uiSourceCode,breakpoints);}
const breakpointLocation={breakpoint:breakpoint,uiLocation:uiLocation};breakpoints.set(uiLocation.id(),breakpointLocation);this.dispatchEventToListeners(Bindings.BreakpointManager.Events.BreakpointAdded,breakpointLocation);}
_uiLocationRemoved(breakpoint,uiLocation){const breakpoints=this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode);if(!breakpoints)
return;const breakpointLocation=breakpoints.get(uiLocation.id())||null;if(!breakpointLocation)
return;breakpoints.delete(uiLocation.id());if(breakpoints.size===0)
this._breakpointsForUISourceCode.delete(uiLocation.uiSourceCode);this.dispatchEventToListeners(Bindings.BreakpointManager.Events.BreakpointRemoved,{breakpoint:breakpoint,uiLocation:uiLocation});}};Bindings.BreakpointManager.Events={BreakpointAdded:Symbol('breakpoint-added'),BreakpointRemoved:Symbol('breakpoint-removed')};Bindings.BreakpointManager.BreakpointLocation;Bindings.BreakpointManager.Breakpoint=class{constructor(breakpointManager,primaryUISourceCode,url,lineNumber,columnNumber,condition,enabled){this._breakpointManager=breakpointManager;this._url=url;this._lineNumber=lineNumber;this._columnNumber=columnNumber;this._defaultUILocation=null;this._uiLocations=new Set();this._condition;this._enabled;this._isRemoved;this._currentState=null;this._modelBreakpoints=new Map();this._updateState(condition,enabled);this.setPrimaryUISourceCode(primaryUISourceCode);this._breakpointManager._targetManager.observeModels(SDK.DebuggerModel,this);}
refreshInDebugger(){if(this._isRemoved)
return;for(const breakpoint of this._modelBreakpoints.values())
breakpoint._refreshBreakpoint();}
modelAdded(debuggerModel){const debuggerWorkspaceBinding=this._breakpointManager._debuggerWorkspaceBinding;this._modelBreakpoints.set(debuggerModel,new Bindings.BreakpointManager.ModelBreakpoint(debuggerModel,this,debuggerWorkspaceBinding));}
modelRemoved(debuggerModel){const modelBreakpoint=this._modelBreakpoints.remove(debuggerModel);modelBreakpoint._cleanUpAfterDebuggerIsGone();modelBreakpoint._removeEventListeners();}
setPrimaryUISourceCode(primaryUISourceCode){if(this._uiLocations.size===0&&this._defaultUILocation)
this._breakpointManager._uiLocationRemoved(this,this._defaultUILocation);if(primaryUISourceCode)
this._defaultUILocation=primaryUISourceCode.uiLocation(this._lineNumber,this._columnNumber);else
this._defaultUILocation=null;if(this._uiLocations.size===0&&this._defaultUILocation&&!this._isRemoved)
this._breakpointManager._uiLocationAdded(this,this._defaultUILocation);}
url(){return this._url;}
lineNumber(){return this._lineNumber;}
columnNumber(){return this._columnNumber;}
_uiLocationAdded(uiLocation){if(this._isRemoved)
return;if(this._uiLocations.size===0&&this._defaultUILocation)
this._breakpointManager._uiLocationRemoved(this,this._defaultUILocation);this._uiLocations.add(uiLocation);this._breakpointManager._uiLocationAdded(this,uiLocation);}
_uiLocationRemoved(uiLocation){this._uiLocations.delete(uiLocation);this._breakpointManager._uiLocationRemoved(this,uiLocation);if(this._uiLocations.size===0&&this._defaultUILocation&&!this._isRemoved)
this._breakpointManager._uiLocationAdded(this,this._defaultUILocation);}
enabled(){return this._enabled;}
setEnabled(enabled){this._updateState(this._condition,enabled);}
condition(){return this._condition;}
setCondition(condition){this._updateState(condition,this._enabled);}
_updateState(condition,enabled){if(this._enabled===enabled&&this._condition===condition)
return;this._enabled=enabled;this._condition=condition;this._breakpointManager._storage._updateBreakpoint(this);this._updateBreakpoint();}
_updateBreakpoint(){if(this._uiLocations.size===0&&this._defaultUILocation)
this._breakpointManager._uiLocationRemoved(this,this._defaultUILocation);if(this._uiLocations.size===0&&this._defaultUILocation&&!this._isRemoved)
this._breakpointManager._uiLocationAdded(this,this._defaultUILocation);const modelBreakpoints=this._modelBreakpoints.valuesArray();for(let i=0;i<modelBreakpoints.length;++i)
modelBreakpoints[i]._scheduleUpdateInDebugger();}
remove(keepInStorage){this._isRemoved=true;const removeFromStorage=!keepInStorage;const modelBreakpoints=this._modelBreakpoints.valuesArray();for(let i=0;i<modelBreakpoints.length;++i){modelBreakpoints[i]._scheduleUpdateInDebugger();modelBreakpoints[i]._removeEventListeners();}
this._breakpointManager._removeBreakpoint(this,removeFromStorage);this._breakpointManager._targetManager.unobserveModels(SDK.DebuggerModel,this);this.setPrimaryUISourceCode(null);}
_breakpointStorageId(){return Bindings.BreakpointManager._breakpointStorageId(this._url,this._lineNumber,this._columnNumber);}
_resetLocations(){this.setPrimaryUISourceCode(null);const modelBreakpoints=this._modelBreakpoints.valuesArray();for(let i=0;i<modelBreakpoints.length;++i)
modelBreakpoints[i]._resetLocations();}};Bindings.BreakpointManager.ModelBreakpoint=class{constructor(debuggerModel,breakpoint,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._breakpoint=breakpoint;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._liveLocations=new Bindings.LiveLocationPool();this._uiLocations=new Map();this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerWasDisabled,this._cleanUpAfterDebuggerIsGone,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerWasEnabled,this._scheduleUpdateInDebugger,this);this._hasPendingUpdate=false;this._isUpdating=false;this._cancelCallback=false;this._currentState=null;if(this._debuggerModel.debuggerEnabled())
this._scheduleUpdateInDebugger();}
_resetLocations(){for(const uiLocation of this._uiLocations.values())
this._breakpoint._uiLocationRemoved(uiLocation);this._uiLocations.clear();this._liveLocations.disposeAll();}
_scheduleUpdateInDebugger(){if(this._isUpdating){this._hasPendingUpdate=true;return;}
this._isUpdating=true;this._updateInDebugger(this._didUpdateInDebugger.bind(this));}
_didUpdateInDebugger(){this._isUpdating=false;if(this._hasPendingUpdate){this._hasPendingUpdate=false;this._scheduleUpdateInDebugger();}}
_scriptDiverged(){const uiLocation=this._breakpoint._defaultUILocation;const uiSourceCode=uiLocation?uiLocation.uiSourceCode:null;if(!uiSourceCode)
return false;const scriptFile=this._debuggerWorkspaceBinding.scriptFile(uiSourceCode,this._debuggerModel);return!!scriptFile&&scriptFile.hasDivergedFromVM();}
async _updateInDebugger(callback){if(this._debuggerModel.target().isDisposed()){this._cleanUpAfterDebuggerIsGone();callback();return;}
const uiLocation=this._breakpoint._defaultUILocation;const uiSourceCode=uiLocation?uiLocation.uiSourceCode:null;const lineNumber=this._breakpoint._lineNumber;const columnNumber=this._breakpoint._columnNumber;const condition=this._breakpoint.condition();let debuggerLocation=null;if(uiSourceCode){const locations=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber);debuggerLocation=locations.find(location=>location.debuggerModel===this._debuggerModel);}
let newState;if(this._breakpoint._isRemoved||!this._breakpoint.enabled()||this._scriptDiverged()){newState=null;}else if(debuggerLocation){const script=debuggerLocation.script();if(script.sourceURL){newState=new Bindings.BreakpointManager.Breakpoint.State(script.sourceURL,null,null,debuggerLocation.lineNumber,debuggerLocation.columnNumber,condition);}else{newState=new Bindings.BreakpointManager.Breakpoint.State(null,script.scriptId,script.hash,debuggerLocation.lineNumber,debuggerLocation.columnNumber,condition);}}else if(this._breakpoint._currentState&&this._breakpoint._currentState.url){const position=this._breakpoint._currentState;newState=new Bindings.BreakpointManager.Breakpoint.State(position.url,null,null,position.lineNumber,position.columnNumber,condition);}else if(uiSourceCode){newState=new Bindings.BreakpointManager.Breakpoint.State(uiSourceCode.url(),null,null,lineNumber,columnNumber,condition);}
if(this._debuggerId&&Bindings.BreakpointManager.Breakpoint.State.equals(newState,this._currentState)){callback();return;}
this._breakpoint._currentState=newState;if(this._debuggerId){await this._refreshBreakpoint();callback();return;}
if(!newState){callback();return;}
let result;this._currentState=newState;if(newState.url){result=await this._debuggerModel.setBreakpointByURL(newState.url,newState.lineNumber,newState.columnNumber,newState.condition);}else if(newState.scriptId&&newState.scriptHash){result=await this._debuggerModel.setBreakpointInAnonymousScript(newState.scriptId,newState.scriptHash,newState.lineNumber,newState.columnNumber,newState.condition);}
if(result&&result.breakpointId)
this._didSetBreakpointInDebugger(callback,result.breakpointId,result.locations);else
this._didSetBreakpointInDebugger(callback,null,[]);}
async _refreshBreakpoint(){if(!this._debuggerId)
return;this._resetLocations();await this._debuggerModel.removeBreakpoint(this._debuggerId);this._didRemoveFromDebugger();this._currentState=null;this._scheduleUpdateInDebugger();}
_didSetBreakpointInDebugger(callback,breakpointId,locations){if(this._cancelCallback){this._cancelCallback=false;callback();return;}
if(!breakpointId){this._breakpoint.remove(true);callback();return;}
this._debuggerId=breakpointId;this._debuggerModel.addBreakpointListener(this._debuggerId,this._breakpointResolved,this);for(let i=0;i<locations.length;++i){if(!this._addResolvedLocation(locations[i]))
break;}
callback();}
_didRemoveFromDebugger(){if(this._cancelCallback){this._cancelCallback=false;return;}
this._resetLocations();this._debuggerModel.removeBreakpointListener(this._debuggerId,this._breakpointResolved,this);delete this._debuggerId;}
_breakpointResolved(event){this._addResolvedLocation((event.data));}
_locationUpdated(liveLocation){const oldUILocation=this._uiLocations.get(liveLocation);if(oldUILocation)
this._breakpoint._uiLocationRemoved(oldUILocation);let uiLocation=liveLocation.uiLocation();if(uiLocation){const breakpointLocation=this._breakpoint._breakpointManager.findBreakpoint(uiLocation);if(breakpointLocation&&breakpointLocation.uiLocation!==breakpointLocation.breakpoint._defaultUILocation)
uiLocation=null;}
if(uiLocation){this._uiLocations.set(liveLocation,uiLocation);this._breakpoint._uiLocationAdded(uiLocation);}else{this._uiLocations.delete(liveLocation);}}
_addResolvedLocation(location){const uiLocation=this._debuggerWorkspaceBinding.rawLocationToUILocation(location);if(!uiLocation)
return false;const breakpointLocation=this._breakpoint._breakpointManager.findBreakpoint(uiLocation);if(breakpointLocation&&breakpointLocation.breakpoint!==this._breakpoint){this._breakpoint.remove(false);return false;}
this._debuggerWorkspaceBinding.createLiveLocation(location,this._locationUpdated.bind(this),this._liveLocations);return true;}
_cleanUpAfterDebuggerIsGone(){if(this._isUpdating)
this._cancelCallback=true;this._resetLocations();this._currentState=null;if(this._debuggerId)
this._didRemoveFromDebugger();}
_removeEventListeners(){this._debuggerModel.removeEventListener(SDK.DebuggerModel.Events.DebuggerWasDisabled,this._cleanUpAfterDebuggerIsGone,this);this._debuggerModel.removeEventListener(SDK.DebuggerModel.Events.DebuggerWasEnabled,this._scheduleUpdateInDebugger,this);}};Bindings.BreakpointManager.Breakpoint.State=class{constructor(url,scriptId,scriptHash,lineNumber,columnNumber,condition){this.url=url;this.scriptId=scriptId;this.scriptHash=scriptHash;this.lineNumber=lineNumber;this.columnNumber=columnNumber;this.condition=condition;}
static equals(stateA,stateB){if(!stateA||!stateB)
return false;return stateA.url===stateB.url&&stateA.scriptId===stateB.scriptId&&stateA.scriptHash===stateB.scriptHash&&stateA.lineNumber===stateB.lineNumber&&stateA.columnNumber===stateB.columnNumber&&stateA.condition===stateB.condition;}};Bindings.BreakpointManager.Storage=class{constructor(){this._setting=Common.settings.createLocalSetting('breakpoints',[]);this._breakpoints=new Map();const items=(this._setting.get());for(const item of items){item.columnNumber=item.columnNumber||0;this._breakpoints.set(Bindings.BreakpointManager._breakpointStorageId(item.url,item.lineNumber,item.columnNumber),item);}
this._muted;}
mute(){this._muted=true;}
unmute(){delete this._muted;}
breakpointItems(url){return Array.from(this._breakpoints.values()).filter(item=>item.url===url);}
_updateBreakpoint(breakpoint){if(this._muted||!breakpoint._breakpointStorageId())
return;this._breakpoints.set(breakpoint._breakpointStorageId(),new Bindings.BreakpointManager.Storage.Item(breakpoint));this._save();}
_removeBreakpoint(breakpoint){if(this._muted)
return;this._breakpoints.delete(breakpoint._breakpointStorageId());this._save();}
_save(){this._setting.set(Array.from(this._breakpoints.values()));}};Bindings.BreakpointManager.Storage.Item=class{constructor(breakpoint){this.url=breakpoint._url;this.lineNumber=breakpoint.lineNumber();this.columnNumber=breakpoint.columnNumber();this.condition=breakpoint.condition();this.enabled=breakpoint.enabled();}};Bindings.breakpointManager;;Bindings.ContentProviderBasedProject=class extends Workspace.ProjectStore{constructor(workspace,id,type,displayName,isServiceProject){super(workspace,id,type,displayName);this._contentProviders={};this._isServiceProject=isServiceProject;workspace.addProject(this);}
requestFileContent(uiSourceCode,callback){const contentProvider=this._contentProviders[uiSourceCode.url()];(async()=>{callback(await contentProvider.requestContent(),await contentProvider.contentEncoded());})();}
isServiceProject(){return this._isServiceProject;}
requestMetadata(uiSourceCode){return Promise.resolve(uiSourceCode[Bindings.ContentProviderBasedProject._metadata]);}
canSetFileContent(){return false;}
async setFileContent(uiSourceCode,newContent,isBase64){}
fullDisplayName(uiSourceCode){let parentPath=uiSourceCode.parentURL().replace(/^(?:https?|file)\:\/\//,'');try{parentPath=decodeURI(parentPath);}catch(e){}
return parentPath+'/'+uiSourceCode.displayName(true);}
mimeType(uiSourceCode){return(uiSourceCode[Bindings.ContentProviderBasedProject._mimeType]);}
canRename(){return false;}
rename(uiSourceCode,newName,callback){const path=uiSourceCode.url();this.performRename(path,newName,innerCallback.bind(this));function innerCallback(success,newName){if(success&&newName){const copyOfPath=path.split('/');copyOfPath[copyOfPath.length-1]=newName;const newPath=copyOfPath.join('/');this._contentProviders[newPath]=this._contentProviders[path];delete this._contentProviders[path];this.renameUISourceCode(uiSourceCode,newName);}
callback(success,newName);}}
excludeFolder(path){}
canExcludeFolder(path){return false;}
createFile(path,name,content,isBase64){}
canCreateFile(){return false;}
deleteFile(uiSourceCode){}
remove(){}
performRename(path,newName,callback){callback(false);}
searchInFileContent(uiSourceCode,query,caseSensitive,isRegex){const contentProvider=this._contentProviders[uiSourceCode.url()];return contentProvider.searchInContent(query,caseSensitive,isRegex);}
async findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,progress){const result=[];progress.setTotalWork(filesMathingFileQuery.length);await Promise.all(filesMathingFileQuery.map(searchInContent.bind(this)));progress.done();return result;async function searchInContent(path){const provider=this._contentProviders[path];let allMatchesFound=true;for(const query of searchConfig.queries().slice()){const searchMatches=await provider.searchInContent(query,!searchConfig.ignoreCase(),searchConfig.isRegex());if(!searchMatches.length){allMatchesFound=false;break;}}
if(allMatchesFound)
result.push(path);progress.worked(1);}}
indexContent(progress){setImmediate(progress.done.bind(progress));}
addUISourceCodeWithProvider(uiSourceCode,contentProvider,metadata,mimeType){uiSourceCode[Bindings.ContentProviderBasedProject._mimeType]=mimeType;this._contentProviders[uiSourceCode.url()]=contentProvider;uiSourceCode[Bindings.ContentProviderBasedProject._metadata]=metadata;this.addUISourceCode(uiSourceCode);}
addContentProvider(url,contentProvider,mimeType){const uiSourceCode=this.createUISourceCode(url,contentProvider.contentType());this.addUISourceCodeWithProvider(uiSourceCode,contentProvider,null,mimeType);return uiSourceCode;}
removeFile(path){delete this._contentProviders[path];this.removeUISourceCode(path);}
reset(){this._contentProviders={};this.removeProject();this.workspace().addProject(this);}
dispose(){this._contentProviders={};this.removeProject();}};Bindings.ContentProviderBasedProject._metadata=Symbol('ContentProviderBasedProject.Metadata');Bindings.ContentProviderBasedProject._mimeType=Symbol('Bindings.ContentProviderBasedProject._mimeType');;Bindings.DefaultScriptMapping=class{constructor(debuggerModel,workspace,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._project=new Bindings.ContentProviderBasedProject(workspace,'debugger:'+debuggerModel.target().id(),Workspace.projectTypes.Debugger,'',true);this._eventListeners=[debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._debuggerReset,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource,this._parsedScriptSource,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.DiscardedAnonymousScriptSource,this._discardedScriptSource,this)];this._scriptSymbol=Symbol('symbol');}
static scriptForUISourceCode(uiSourceCode){const scripts=uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol];return scripts?scripts.values().next().value:null;}
rawLocationToUILocation(rawLocation){const script=rawLocation.script();if(!script)
return null;const uiSourceCode=script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol];const lineNumber=rawLocation.lineNumber-(script.isInlineScriptWithSourceURL()?script.lineOffset:0);let columnNumber=rawLocation.columnNumber||0;if(script.isInlineScriptWithSourceURL()&&!lineNumber&&columnNumber)
columnNumber-=script.columnOffset;return uiSourceCode.uiLocation(lineNumber,columnNumber);}
uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber){const script=uiSourceCode[this._scriptSymbol];if(!script)
return[];if(script.isInlineScriptWithSourceURL()){return[this._debuggerModel.createRawLocation(script,lineNumber+script.lineOffset,lineNumber?columnNumber:columnNumber+script.columnOffset)];}
return[this._debuggerModel.createRawLocation(script,lineNumber,columnNumber)];}
_parsedScriptSource(event){const script=(event.data);const name=Common.ParsedURL.extractName(script.sourceURL);const url='debugger:///VM'+script.scriptId+(name?' '+name:'');const uiSourceCode=this._project.createUISourceCode(url,Common.resourceTypes.Script);uiSourceCode[this._scriptSymbol]=script;if(!uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol])
uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol]=new Set([script]);else
uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol].add(script);script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol]=uiSourceCode;this._project.addUISourceCodeWithProvider(uiSourceCode,script,null,'text/javascript');this._debuggerWorkspaceBinding.updateLocations(script);}
_discardedScriptSource(event){const script=(event.data);const uiSourceCode=script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol];if(!uiSourceCode)
return;delete script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol];delete uiSourceCode[this._scriptSymbol];uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol].delete(script);if(!uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol].size)
delete uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol];this._project.removeUISourceCode(uiSourceCode.url());}
_debuggerReset(){this._project.reset();}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._debuggerReset();this._project.dispose();}};Bindings.DefaultScriptMapping._scriptsSymbol=Symbol('symbol');Bindings.DefaultScriptMapping._uiSourceCodeSymbol=Symbol('uiSourceCodeSymbol');;Bindings.ChunkedReader=function(){};Bindings.ChunkedReader.prototype={fileSize(){},loadedSize(){},fileName(){},cancel(){},error(){}};Bindings.ChunkedFileReader=class{constructor(blob,chunkSize,chunkTransferredCallback){this._file=blob;this._fileSize=blob.size;this._loadedSize=0;this._chunkSize=chunkSize;this._chunkTransferredCallback=chunkTransferredCallback;this._decoder=new TextDecoder();this._isCanceled=false;this._error=null;}
read(output){if(this._chunkTransferredCallback)
this._chunkTransferredCallback(this);this._output=output;this._reader=new FileReader();this._reader.onload=this._onChunkLoaded.bind(this);this._reader.onerror=this._onError.bind(this);this._loadChunk();return new Promise(resolve=>this._transferFinished=resolve);}
cancel(){this._isCanceled=true;}
loadedSize(){return this._loadedSize;}
fileSize(){return this._fileSize;}
fileName(){return this._file.name;}
error(){return this._error;}
_onChunkLoaded(event){if(this._isCanceled)
return;if(event.target.readyState!==FileReader.DONE)
return;const buffer=this._reader.result;this._loadedSize+=buffer.byteLength;const endOfFile=this._loadedSize===this._fileSize;const decodedString=this._decoder.decode(buffer,{stream:!endOfFile});this._output.write(decodedString);if(this._isCanceled)
return;if(this._chunkTransferredCallback)
this._chunkTransferredCallback(this);if(endOfFile){this._file=null;this._reader=null;this._output.close();this._transferFinished(!this._error);return;}
this._loadChunk();}
_loadChunk(){const chunkStart=this._loadedSize;const chunkEnd=Math.min(this._fileSize,chunkStart+this._chunkSize);const nextPart=this._file.slice(chunkStart,chunkEnd);this._reader.readAsArrayBuffer(nextPart);}
_onError(event){this._error=event.target.error;this._transferFinished(false);}};Bindings.FileOutputStream=class{async open(fileName){this._closed=false;this._writeCallbacks=[];this._fileName=fileName;const saveResponse=await Workspace.fileManager.save(this._fileName,'',true);if(saveResponse)
Workspace.fileManager.addEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this);return!!saveResponse;}
write(data){return new Promise(resolve=>{this._writeCallbacks.push(resolve);Workspace.fileManager.append(this._fileName,data);});}
close(){this._closed=true;if(this._writeCallbacks.length)
return;Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this);Workspace.fileManager.close(this._fileName);}
_onAppendDone(event){if(event.data!==this._fileName)
return;this._writeCallbacks.shift()();if(this._writeCallbacks.length)
return;if(!this._closed)
return;Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this);Workspace.fileManager.close(this._fileName);}};;Bindings.BlackboxManager=class{constructor(debuggerWorkspaceBinding){this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.GlobalObjectCleared,this._clearCacheIfNeeded.bind(this),this);Common.moduleSetting('skipStackFramesPattern').addChangeListener(this._patternChanged.bind(this));Common.moduleSetting('skipContentScripts').addChangeListener(this._patternChanged.bind(this));this._listeners=new Set();this._isBlackboxedURLCache=new Map();SDK.targetManager.observeModels(SDK.DebuggerModel,this);}
addChangeListener(listener){this._listeners.add(listener);}
removeChangeListener(listener){this._listeners.delete(listener);}
modelAdded(debuggerModel){this._setBlackboxPatterns(debuggerModel);const sourceMapManager=debuggerModel.sourceMapManager();sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapAttached,this._sourceMapAttached,this);sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapDetached,this._sourceMapDetached,this);}
modelRemoved(debuggerModel){this._clearCacheIfNeeded();const sourceMapManager=debuggerModel.sourceMapManager();sourceMapManager.removeEventListener(SDK.SourceMapManager.Events.SourceMapAttached,this._sourceMapAttached,this);sourceMapManager.removeEventListener(SDK.SourceMapManager.Events.SourceMapDetached,this._sourceMapDetached,this);}
_clearCacheIfNeeded(){if(this._isBlackboxedURLCache.size>1024)
this._isBlackboxedURLCache.clear();}
_setBlackboxPatterns(debuggerModel){const regexPatterns=Common.moduleSetting('skipStackFramesPattern').getAsArray();const patterns=([]);for(const item of regexPatterns){if(!item.disabled&&item.pattern)
patterns.push(item.pattern);}
return debuggerModel.setBlackboxPatterns(patterns);}
isBlackboxedUISourceCode(uiSourceCode){const projectType=uiSourceCode.project().type();const isContentScript=projectType===Workspace.projectTypes.ContentScripts;if(isContentScript&&Common.moduleSetting('skipContentScripts').get())
return true;const url=this._uiSourceCodeURL(uiSourceCode);return url?this.isBlackboxedURL(url):false;}
isBlackboxedURL(url,isContentScript){if(this._isBlackboxedURLCache.has(url))
return!!this._isBlackboxedURLCache.get(url);if(isContentScript&&Common.moduleSetting('skipContentScripts').get())
return true;const regex=Common.moduleSetting('skipStackFramesPattern').asRegExp();const isBlackboxed=(regex&&regex.test(url))||false;this._isBlackboxedURLCache.set(url,isBlackboxed);return isBlackboxed;}
_sourceMapAttached(event){const script=(event.data.client);const sourceMap=(event.data.sourceMap);this._updateScriptRanges(script,sourceMap);}
_sourceMapDetached(event){const script=(event.data.client);this._updateScriptRanges(script,null);}
async _updateScriptRanges(script,sourceMap){let hasBlackboxedMappings=false;if(!Bindings.blackboxManager.isBlackboxedURL(script.sourceURL,script.isContentScript()))
hasBlackboxedMappings=sourceMap?sourceMap.sourceURLs().some(url=>this.isBlackboxedURL(url)):false;if(!hasBlackboxedMappings){if(script[Bindings.BlackboxManager._blackboxedRanges]&&await script.setBlackboxedRanges([]))
delete script[Bindings.BlackboxManager._blackboxedRanges];this._debuggerWorkspaceBinding.updateLocations(script);return;}
const mappings=sourceMap.mappings();const newRanges=[];let currentBlackboxed=false;if(mappings[0].lineNumber!==0||mappings[0].columnNumber!==0){newRanges.push({lineNumber:0,columnNumber:0});currentBlackboxed=true;}
for(const mapping of mappings){if(mapping.sourceURL&&currentBlackboxed!==this.isBlackboxedURL(mapping.sourceURL)){newRanges.push({lineNumber:mapping.lineNumber,columnNumber:mapping.columnNumber});currentBlackboxed=!currentBlackboxed;}}
const oldRanges=script[Bindings.BlackboxManager._blackboxedRanges]||[];if(!isEqual(oldRanges,newRanges)&&await script.setBlackboxedRanges(newRanges))
script[Bindings.BlackboxManager._blackboxedRanges]=newRanges;this._debuggerWorkspaceBinding.updateLocations(script);function isEqual(rangesA,rangesB){if(rangesA.length!==rangesB.length)
return false;for(let i=0;i<rangesA.length;++i){if(rangesA[i].lineNumber!==rangesB[i].lineNumber||rangesA[i].columnNumber!==rangesB[i].columnNumber)
return false;}
return true;}}
_uiSourceCodeURL(uiSourceCode){return uiSourceCode.project().type()===Workspace.projectTypes.Debugger?null:uiSourceCode.url();}
canBlackboxUISourceCode(uiSourceCode){const url=this._uiSourceCodeURL(uiSourceCode);return url?!!this._urlToRegExpString(url):false;}
blackboxUISourceCode(uiSourceCode){const url=this._uiSourceCodeURL(uiSourceCode);if(url)
this._blackboxURL(url);}
unblackboxUISourceCode(uiSourceCode){const url=this._uiSourceCodeURL(uiSourceCode);if(url)
this._unblackboxURL(url);}
blackboxContentScripts(){Common.moduleSetting('skipContentScripts').set(true);}
unblackboxContentScripts(){Common.moduleSetting('skipContentScripts').set(false);}
_blackboxURL(url){const regexPatterns=Common.moduleSetting('skipStackFramesPattern').getAsArray();const regexValue=this._urlToRegExpString(url);if(!regexValue)
return;let found=false;for(let i=0;i<regexPatterns.length;++i){const item=regexPatterns[i];if(item.pattern===regexValue){item.disabled=false;found=true;break;}}
if(!found)
regexPatterns.push({pattern:regexValue});Common.moduleSetting('skipStackFramesPattern').setAsArray(regexPatterns);}
_unblackboxURL(url){let regexPatterns=Common.moduleSetting('skipStackFramesPattern').getAsArray();const regexValue=Bindings.blackboxManager._urlToRegExpString(url);if(!regexValue)
return;regexPatterns=regexPatterns.filter(function(item){return item.pattern!==regexValue;});for(let i=0;i<regexPatterns.length;++i){const item=regexPatterns[i];if(item.disabled)
continue;try{const regex=new RegExp(item.pattern);if(regex.test(url))
item.disabled=true;}catch(e){}}
Common.moduleSetting('skipStackFramesPattern').setAsArray(regexPatterns);}
async _patternChanged(){this._isBlackboxedURLCache.clear();const promises=[];for(const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)){promises.push(this._setBlackboxPatterns(debuggerModel));const sourceMapManager=debuggerModel.sourceMapManager();for(const script of debuggerModel.scripts())
promises.push(this._updateScriptRanges(script,sourceMapManager.sourceMapForClient(script)));}
await Promise.all(promises);const listeners=Array.from(this._listeners);for(const listener of listeners)
listener();this._patternChangeFinishedForTests();}
_patternChangeFinishedForTests(){}
_urlToRegExpString(url){const parsedURL=new Common.ParsedURL(url);if(parsedURL.isAboutBlank()||parsedURL.isDataURL())
return'';if(!parsedURL.isValid)
return'^'+url.escapeForRegExp()+'$';let name=parsedURL.lastPathComponent;if(name)
name='/'+name;else if(parsedURL.folderPathComponents)
name=parsedURL.folderPathComponents+'/';if(!name)
name=parsedURL.host;if(!name)
return'';const scheme=parsedURL.scheme;let prefix='';if(scheme&&scheme!=='http'&&scheme!=='https'){prefix='^'+scheme+'://';if(scheme==='chrome-extension')
prefix+=parsedURL.host+'\\b';prefix+='.*';}
return prefix+name.escapeForRegExp()+(url.endsWith(name)?'$':'\\b');}};Bindings.BlackboxManager._blackboxedRanges=Symbol('blackboxedRanged');Bindings.blackboxManager;;Bindings.NetworkProjectManager=class extends Common.Object{};Bindings.NetworkProjectManager.Events={FrameAttributionAdded:Symbol('FrameAttributionAdded'),FrameAttributionRemoved:Symbol('FrameAttributionRemoved')};Bindings.NetworkProject=class{static _resolveFrame(uiSourceCode,frameId){const target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);const resourceTreeModel=target&&target.model(SDK.ResourceTreeModel);return resourceTreeModel?resourceTreeModel.frameForId(frameId):null;}
static setInitialFrameAttribution(uiSourceCode,frameId){const frame=Bindings.NetworkProject._resolveFrame(uiSourceCode,frameId);if(!frame)
return;const attribution=new Map();attribution.set(frameId,{frame:frame,count:1});uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol]=attribution;}
static cloneInitialFrameAttribution(fromUISourceCode,toUISourceCode){const fromAttribution=fromUISourceCode[Bindings.NetworkProject._frameAttributionSymbol];if(!fromAttribution)
return;const toAttribution=new Map();toUISourceCode[Bindings.NetworkProject._frameAttributionSymbol]=toAttribution;for(const frameId of fromAttribution.keys()){const value=fromAttribution.get(frameId);toAttribution.set(frameId,{frame:value.frame,count:value.count});}}
static addFrameAttribution(uiSourceCode,frameId){const frame=Bindings.NetworkProject._resolveFrame(uiSourceCode,frameId);if(!frame)
return;const frameAttribution=uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol];const attributionInfo=frameAttribution.get(frameId)||{frame:frame,count:0};attributionInfo.count+=1;frameAttribution.set(frameId,attributionInfo);if(attributionInfo.count!==1)
return;const data={uiSourceCode:uiSourceCode,frame:frame};Bindings.networkProjectManager.dispatchEventToListeners(Bindings.NetworkProjectManager.Events.FrameAttributionAdded,data);}
static removeFrameAttribution(uiSourceCode,frameId){const frameAttribution=uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol];if(!frameAttribution)
return;const attributionInfo=frameAttribution.get(frameId);console.assert(attributionInfo,'Failed to remove frame attribution for url: '+uiSourceCode.url());attributionInfo.count-=1;if(attributionInfo.count>0)
return;frameAttribution.delete(frameId);const data={uiSourceCode:uiSourceCode,frame:attributionInfo.frame};Bindings.networkProjectManager.dispatchEventToListeners(Bindings.NetworkProjectManager.Events.FrameAttributionRemoved,data);}
static targetForUISourceCode(uiSourceCode){return uiSourceCode.project()[Bindings.NetworkProject._targetSymbol]||null;}
static setTargetForProject(project,target){project[Bindings.NetworkProject._targetSymbol]=target;}
static framesForUISourceCode(uiSourceCode){const target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);const resourceTreeModel=target&&target.model(SDK.ResourceTreeModel);const attribution=uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol];if(!resourceTreeModel||!attribution)
return[];const frames=Array.from(attribution.keys()).map(frameId=>resourceTreeModel.frameForId(frameId));return frames.filter(frame=>!!frame);}};Bindings.NetworkProject._targetSymbol=Symbol('target');Bindings.NetworkProject._frameAttributionSymbol=Symbol('Bindings.NetworkProject._frameAttributionSymbol');;Bindings.PresentationConsoleMessageManager=class{constructor(){SDK.targetManager.observeModels(SDK.DebuggerModel,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.ConsoleCleared,this._consoleCleared,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded,event=>this._consoleMessageAdded((event.data)));SDK.consoleModel.messages().forEach(this._consoleMessageAdded,this);}
modelAdded(debuggerModel){debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]=new Bindings.PresentationConsoleMessageHelper(debuggerModel);}
modelRemoved(debuggerModel){debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]._consoleCleared();}
_consoleMessageAdded(message){if(!message.isErrorOrWarning()||!message.runtimeModel()||message.source===SDK.ConsoleMessage.MessageSource.Violation)
return;const debuggerModel=message.runtimeModel().debuggerModel();debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]._consoleMessageAdded(message);}
_consoleCleared(){for(const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel))
debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]._consoleCleared();}};Bindings.PresentationConsoleMessageManager._symbol=Symbol('PresentationConsoleMessageHelper');Bindings.PresentationConsoleMessageHelper=class{constructor(debuggerModel){this._debuggerModel=debuggerModel;this._pendingConsoleMessages={};this._presentationConsoleMessages=[];debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource,event=>setImmediate(this._parsedScriptSource.bind(this,event)));debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._debuggerReset,this);this._locationPool=new Bindings.LiveLocationPool();}
_consoleMessageAdded(message){const rawLocation=this._rawLocation(message);if(rawLocation)
this._addConsoleMessageToScript(message,rawLocation);else
this._addPendingConsoleMessage(message);}
_rawLocation(message){if(message.scriptId)
return this._debuggerModel.createRawLocationByScriptId(message.scriptId,message.line,message.column);const callFrame=message.stackTrace&&message.stackTrace.callFrames?message.stackTrace.callFrames[0]:null;if(callFrame){return this._debuggerModel.createRawLocationByScriptId(callFrame.scriptId,callFrame.lineNumber,callFrame.columnNumber);}
if(message.url)
return this._debuggerModel.createRawLocationByURL(message.url,message.line,message.column);return null;}
_addConsoleMessageToScript(message,rawLocation){this._presentationConsoleMessages.push(new Bindings.PresentationConsoleMessage(message,rawLocation,this._locationPool));}
_addPendingConsoleMessage(message){if(!message.url)
return;if(!this._pendingConsoleMessages[message.url])
this._pendingConsoleMessages[message.url]=[];this._pendingConsoleMessages[message.url].push(message);}
_parsedScriptSource(event){const script=(event.data);const messages=this._pendingConsoleMessages[script.sourceURL];if(!messages)
return;const pendingMessages=[];for(let i=0;i<messages.length;i++){const message=messages[i];const rawLocation=this._rawLocation(message);if(!rawLocation)
continue;if(script.scriptId===rawLocation.scriptId)
this._addConsoleMessageToScript(message,rawLocation);else
pendingMessages.push(message);}
if(pendingMessages.length)
this._pendingConsoleMessages[script.sourceURL]=pendingMessages;else
delete this._pendingConsoleMessages[script.sourceURL];}
_consoleCleared(){this._pendingConsoleMessages={};this._debuggerReset();}
_debuggerReset(){for(const message of this._presentationConsoleMessages)
message.dispose();this._presentationConsoleMessages=[];this._locationPool.disposeAll();}};Bindings.PresentationConsoleMessage=class{constructor(message,rawLocation,locationPool){this._text=message.messageText;this._level=message.level===SDK.ConsoleMessage.MessageLevel.Error?Workspace.UISourceCode.Message.Level.Error:Workspace.UISourceCode.Message.Level.Warning;Bindings.debuggerWorkspaceBinding.createLiveLocation(rawLocation,this._updateLocation.bind(this),locationPool);}
_updateLocation(liveLocation){if(this._uiMessage)
this._uiMessage.remove();const uiLocation=liveLocation.uiLocation();if(!uiLocation)
return;this._uiMessage=uiLocation.uiSourceCode.addLineMessage(this._level,this._text,uiLocation.lineNumber,uiLocation.columnNumber);}
dispose(){if(this._uiMessage)
this._uiMessage.remove();}};;Bindings.resourceForURL=function(url){for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)){const resource=resourceTreeModel.resourceForURL(url);if(resource)
return resource;}
return null;};Bindings.forAllResources=function(callback){for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel))
resourceTreeModel.forAllResources(callback);};Bindings.displayNameForURL=function(url){if(!url)
return'';const resource=Bindings.resourceForURL(url);if(resource)
return resource.displayName;const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(uiSourceCode)
return uiSourceCode.displayName();const mainTarget=SDK.targetManager.mainTarget();const inspectedURL=mainTarget&&mainTarget.inspectedURL();if(!inspectedURL)
return url.trimURL('');const parsedURL=inspectedURL.asParsedURL();const lastPathComponent=parsedURL?parsedURL.lastPathComponent:parsedURL;const index=inspectedURL.indexOf(lastPathComponent);if(index!==-1&&index+lastPathComponent.length===inspectedURL.length){const baseURL=inspectedURL.substring(0,index);if(url.startsWith(baseURL))
return url.substring(index);}
if(!parsedURL)
return url;const displayName=url.trimURL(parsedURL.host);return displayName==='/'?parsedURL.host+'/':displayName;};Bindings.metadataForURL=function(target,frameId,url){const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel)
return null;const frame=resourceTreeModel.frameForId(frameId);if(!frame)
return null;return Bindings.resourceMetadata(frame.resourceForURL(url));};Bindings.resourceMetadata=function(resource){if(!resource||(typeof resource.contentSize()!=='number'&&!resource.lastModified()))
return null;return new Workspace.UISourceCodeMetadata(resource.lastModified(),resource.contentSize());};Bindings.frameIdForScript=function(script){const executionContext=script.executionContext();if(executionContext)
return executionContext.frameId||'';const resourceTreeModel=script.debuggerModel.target().model(SDK.ResourceTreeModel);if(!resourceTreeModel||!resourceTreeModel.mainFrame)
return'';return resourceTreeModel.mainFrame.id;};;Bindings.TempFile=class{constructor(){this._lastBlob=null;}
write(pieces){if(this._lastBlob)
pieces.unshift(this._lastBlob);this._lastBlob=new Blob(pieces,{type:'text/plain'});}
read(){return this.readRange();}
size(){return this._lastBlob?this._lastBlob.size:0;}
async readRange(startOffset,endOffset){if(!this._lastBlob){Common.console.error('Attempt to read a temp file that was never written');return Promise.resolve('');}
const blob=typeof startOffset==='number'||typeof endOffset==='number'?this._lastBlob.slice((startOffset),(endOffset)):this._lastBlob;const reader=new FileReader();try{await new Promise((resolve,reject)=>{reader.onloadend=resolve;reader.onerror=reject;reader.readAsText(blob);});}catch(error){Common.console.error('Failed to read from temp file: '+error.message);}
return reader.result;}
copyToOutputStream(outputStream,progress){if(!this._lastBlob){outputStream.close();return Promise.resolve((null));}
const reader=new Bindings.ChunkedFileReader((this._lastBlob),10*1000*1000,progress);return reader.read(outputStream).then(success=>success?null:reader.error());}
remove(){this._lastBlob=null;}};Bindings.TempFileBackingStorage=class{constructor(){this._file=null;this._strings;this._stringsLength;this.reset();}
appendString(string){this._strings.push(string);this._stringsLength+=string.length;const flushStringLength=10*1024*1024;if(this._stringsLength>flushStringLength)
this._flush();}
appendAccessibleString(string){this._flush();const startOffset=this._file.size();this._strings.push(string);this._flush();return this._file.readRange.bind(this._file,startOffset,this._file.size());}
_flush(){if(!this._strings.length)
return;if(!this._file)
this._file=new Bindings.TempFile();this._stringsLength=0;this._file.write(this._strings.splice(0));}
finishWriting(){this._flush();}
reset(){if(this._file)
this._file.remove();this._file=null;this._strings=[];this._stringsLength=0;}
writeToStream(outputStream){return this._file?this._file.copyToOutputStream(outputStream):Promise.resolve(null);}};Bindings.TempFileBackingStorage.Chunk;;self['Components']=self['Components']||{};Components.JSPresentationUtils={};Components.JSPresentationUtils.buildStackTracePreviewContents=function(target,linkifier,stackTrace,contentUpdated){const element=createElement('span');element.style.display='inline-block';const shadowRoot=UI.createShadowRootWithCoreStyles(element,'components/jsUtils.css');const contentElement=shadowRoot.createChild('table','stack-preview-container');let totalHiddenCallFramesCount=0;let totalCallFramesCount=0;const links=[];function appendStackTrace(stackTrace){let hiddenCallFrames=0;for(const stackFrame of stackTrace.callFrames){totalCallFramesCount++;let shouldHide=totalCallFramesCount>30&&stackTrace.callFrames.length>31;const row=createElement('tr');row.createChild('td').textContent='\n';row.createChild('td','function-name').textContent=UI.beautifyFunctionName(stackFrame.functionName);const link=linkifier.maybeLinkifyConsoleCallFrame(target,stackFrame);if(link){link.addEventListener('contextmenu',populateContextMenu.bind(null,link));const uiLocation=Components.Linkifier.uiLocation(link);if(uiLocation&&Bindings.blackboxManager.isBlackboxedUISourceCode(uiLocation.uiSourceCode))
shouldHide=true;row.createChild('td').textContent=' @ ';row.createChild('td').appendChild(link);links.push(link);}
if(shouldHide){row.classList.add('blackboxed');++hiddenCallFrames;}
contentElement.appendChild(row);}
totalHiddenCallFramesCount+=hiddenCallFrames;return stackTrace.callFrames.length===hiddenCallFrames;}
function populateContextMenu(link,event){const contextMenu=new UI.ContextMenu(event);event.consume(true);const uiLocation=Components.Linkifier.uiLocation(link);if(uiLocation&&Bindings.blackboxManager.canBlackboxUISourceCode(uiLocation.uiSourceCode)){if(Bindings.blackboxManager.isBlackboxedUISourceCode(uiLocation.uiSourceCode)){contextMenu.debugSection().appendItem(ls`Stop blackboxing`,()=>Bindings.blackboxManager.unblackboxUISourceCode(uiLocation.uiSourceCode));}else{contextMenu.debugSection().appendItem(ls`Blackbox script`,()=>Bindings.blackboxManager.blackboxUISourceCode(uiLocation.uiSourceCode));}}
contextMenu.appendApplicableItems(event);contextMenu.show();}
if(!stackTrace)
return{element,links};appendStackTrace(stackTrace);let asyncStackTrace=stackTrace.parent;while(asyncStackTrace){if(!asyncStackTrace.callFrames.length){asyncStackTrace=asyncStackTrace.parent;continue;}
const row=contentElement.createChild('tr');row.createChild('td').textContent='\n';row.createChild('td','stack-preview-async-description').textContent=UI.asyncStackTraceLabel(asyncStackTrace.description);row.createChild('td');row.createChild('td');if(appendStackTrace(asyncStackTrace))
row.classList.add('blackboxed');asyncStackTrace=asyncStackTrace.parent;}
if(totalHiddenCallFramesCount){const row=contentElement.createChild('tr','show-blackboxed-link');row.createChild('td').textContent='\n';const cell=row.createChild('td');cell.colSpan=4;const showAllLink=cell.createChild('span','link');if(totalHiddenCallFramesCount===1)
showAllLink.textContent=ls`Show 1 more frame`;else
showAllLink.textContent=ls`Show ${totalHiddenCallFramesCount} more frames`;showAllLink.addEventListener('click',()=>{contentElement.classList.add('show-blackboxed');if(contentUpdated)
contentUpdated();},false);}
return{element,links};};;Components.DockController=class extends Common.Object{constructor(canDock){super();this._canDock=canDock;this._closeButton=new UI.ToolbarButton(Common.UIString('Close'),'largeicon-delete');this._closeButton.addEventListener(UI.ToolbarButton.Events.Click,InspectorFrontendHost.closeWindow.bind(InspectorFrontendHost));if(!canDock){this._dockSide=Components.DockController.State.Undocked;this._closeButton.setVisible(false);return;}
this._states=[Components.DockController.State.DockedToRight,Components.DockController.State.DockedToBottom,Components.DockController.State.DockedToLeft,Components.DockController.State.Undocked];this._currentDockStateSetting=Common.settings.moduleSetting('currentDockState');this._currentDockStateSetting.addChangeListener(this._dockSideChanged,this);this._lastDockStateSetting=Common.settings.createSetting('lastDockState','bottom');if(this._states.indexOf(this._currentDockStateSetting.get())===-1)
this._currentDockStateSetting.set('right');if(this._states.indexOf(this._lastDockStateSetting.get())===-1)
this._currentDockStateSetting.set('bottom');}
initialize(){if(!this._canDock)
return;this._titles=[Common.UIString('Dock to right'),Common.UIString('Dock to bottom'),Common.UIString('Dock to left'),Common.UIString('Undock into separate window')];this._dockSideChanged();}
_dockSideChanged(){this.setDockSide(this._currentDockStateSetting.get());}
dockSide(){return this._dockSide;}
canDock(){return this._canDock;}
isVertical(){return this._dockSide===Components.DockController.State.DockedToRight||this._dockSide===Components.DockController.State.DockedToLeft;}
setDockSide(dockSide){if(this._states.indexOf(dockSide)===-1)
dockSide=this._states[0];if(this._dockSide===dockSide)
return;if(this._dockSide)
this._lastDockStateSetting.set(this._dockSide);this._savedFocus=document.deepActiveElement();const eventData={from:this._dockSide,to:dockSide};this.dispatchEventToListeners(Components.DockController.Events.BeforeDockSideChanged,eventData);console.timeStamp('DockController.setIsDocked');this._dockSide=dockSide;this._currentDockStateSetting.set(dockSide);InspectorFrontendHost.setIsDocked(dockSide!==Components.DockController.State.Undocked,this._setIsDockedResponse.bind(this,eventData));this._closeButton.setVisible(this._dockSide!==Components.DockController.State.Undocked);this.dispatchEventToListeners(Components.DockController.Events.DockSideChanged,eventData);}
_setIsDockedResponse(eventData){this.dispatchEventToListeners(Components.DockController.Events.AfterDockSideChanged,eventData);if(this._savedFocus){this._savedFocus.focus();this._savedFocus=null;}}
_toggleDockSide(){if(this._lastDockStateSetting.get()===this._currentDockStateSetting.get()){const index=this._states.indexOf(this._currentDockStateSetting.get())||0;this._lastDockStateSetting.set(this._states[(index+1)%this._states.length]);}
this.setDockSide(this._lastDockStateSetting.get());}};Components.DockController.State={DockedToBottom:'bottom',DockedToRight:'right',DockedToLeft:'left',Undocked:'undocked'};Components.DockController.Events={BeforeDockSideChanged:Symbol('BeforeDockSideChanged'),DockSideChanged:Symbol('DockSideChanged'),AfterDockSideChanged:Symbol('AfterDockSideChanged')};Components.DockController.ToggleDockActionDelegate=class{handleAction(context,actionId){Components.dockController._toggleDockSide();return true;}};Components.DockController.CloseButtonProvider=class{item(){return Components.dockController._closeButton;}};Components.dockController;;Components.ImagePreview=class{static build(target,originalImageURL,showDimensions,precomputedFeatures){const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel)
return Promise.resolve((null));let resource=resourceTreeModel.resourceForURL(originalImageURL);let imageURL=originalImageURL;if(!isImageResource(resource)&&precomputedFeatures&&precomputedFeatures.currentSrc){imageURL=precomputedFeatures.currentSrc;resource=resourceTreeModel.resourceForURL(imageURL);}
if(!isImageResource(resource))
return Promise.resolve((null));let fulfill;const promise=new Promise(x=>fulfill=x);const imageElement=createElement('img');imageElement.addEventListener('load',buildContent,false);imageElement.addEventListener('error',()=>fulfill(null),false);resource.populateImageSource(imageElement);return promise;function isImageResource(resource){return!!resource&&resource.resourceType()===Common.resourceTypes.Image;}
function buildContent(){const container=createElement('table');UI.appendStyle(container,'components/imagePreview.css');container.className='image-preview-container';const intrinsicWidth=imageElement.naturalWidth;const intrinsicHeight=imageElement.naturalHeight;const renderedWidth=precomputedFeatures?precomputedFeatures.renderedWidth:intrinsicWidth;const renderedHeight=precomputedFeatures?precomputedFeatures.renderedHeight:intrinsicHeight;let description;if(showDimensions){description=ls`${renderedWidth} \xd7 ${renderedHeight} pixels`;if(renderedHeight!==intrinsicHeight||renderedWidth!==intrinsicWidth)
description+=ls` (intrinsic: ${intrinsicWidth} \xd7 ${intrinsicHeight} pixels)`;}
container.createChild('tr').createChild('td','image-container').appendChild(imageElement);if(description)
container.createChild('tr').createChild('td').createChild('span','description').textContent=description;if(imageURL!==originalImageURL){container.createChild('tr').createChild('td').createChild('span','description').textContent=String.sprintf('currentSrc: %s',imageURL.trimMiddle(100));}
fulfill(container);}}
static async loadDimensionsForNode(node){if(!node.nodeName()||node.nodeName().toLowerCase()!=='img')
return;const object=await node.resolveToObject('');if(!object)
return;const featuresObject=object.callFunctionJSON(features,undefined);object.release();return featuresObject;function features(){return{renderedWidth:this.width,renderedHeight:this.height,currentSrc:this.currentSrc};}}};;Components.Linkifier=class{constructor(maxLengthForDisplayedURLs,useLinkDecorator){this._maxLength=maxLengthForDisplayedURLs||UI.MaxLengthForDisplayedURLs;this._anchorsByTarget=new Map();this._locationPoolByTarget=new Map();this._useLinkDecorator=!!useLinkDecorator;Components.Linkifier._instances.add(this);SDK.targetManager.observeTargets(this);}
static setLinkDecorator(decorator){console.assert(!Components.Linkifier._decorator,'Cannot re-register link decorator.');Components.Linkifier._decorator=decorator;decorator.addEventListener(Components.LinkDecorator.Events.LinkIconChanged,onLinkIconChanged);for(const linkifier of Components.Linkifier._instances)
linkifier._updateAllAnchorDecorations();function onLinkIconChanged(event){const uiSourceCode=(event.data);const links=uiSourceCode[Components.Linkifier._sourceCodeAnchors]||[];for(const link of links)
Components.Linkifier._updateLinkDecorations(link);}}
_updateAllAnchorDecorations(){for(const anchors of this._anchorsByTarget.values()){for(const anchor of anchors)
Components.Linkifier._updateLinkDecorations(anchor);}}
static _bindUILocation(anchor,uiLocation){Components.Linkifier._linkInfo(anchor).uiLocation=uiLocation;if(!uiLocation)
return;const uiSourceCode=uiLocation.uiSourceCode;let sourceCodeAnchors=uiSourceCode[Components.Linkifier._sourceCodeAnchors];if(!sourceCodeAnchors){sourceCodeAnchors=new Set();uiSourceCode[Components.Linkifier._sourceCodeAnchors]=sourceCodeAnchors;}
sourceCodeAnchors.add(anchor);}
static _unbindUILocation(anchor){const info=Components.Linkifier._linkInfo(anchor);if(!info.uiLocation)
return;const uiSourceCode=info.uiLocation.uiSourceCode;info.uiLocation=null;const sourceCodeAnchors=uiSourceCode[Components.Linkifier._sourceCodeAnchors];if(sourceCodeAnchors)
sourceCodeAnchors.delete(anchor);}
targetAdded(target){this._anchorsByTarget.set(target,[]);this._locationPoolByTarget.set(target,new Bindings.LiveLocationPool());}
targetRemoved(target){const locationPool=(this._locationPoolByTarget.remove(target));locationPool.disposeAll();const anchors=this._anchorsByTarget.remove(target);for(const anchor of anchors){const info=Components.Linkifier._linkInfo(anchor);info.liveLocation=null;Components.Linkifier._unbindUILocation(anchor);if(info.fallback){anchor.href=info.fallback.href;anchor.title=info.fallback.title;anchor.className=info.fallback.className;anchor.textContent=info.fallback.textContent;anchor[Components.Linkifier._infoSymbol]=info.fallback[Components.Linkifier._infoSymbol];}}}
maybeLinkifyScriptLocation(target,scriptId,sourceURL,lineNumber,columnNumber,classes){let fallbackAnchor=null;if(sourceURL){fallbackAnchor=Components.Linkifier.linkifyURL(sourceURL,{className:classes,lineNumber:lineNumber,columnNumber:columnNumber,maxLength:this._maxLength});}
if(!target||target.isDisposed())
return fallbackAnchor;const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel)
return fallbackAnchor;const rawLocation=(scriptId?debuggerModel.createRawLocationByScriptId(scriptId,lineNumber,columnNumber||0):null)||debuggerModel.createRawLocationByURL(sourceURL,lineNumber,columnNumber||0);if(!rawLocation)
return fallbackAnchor;const anchor=Components.Linkifier._createLink('',classes||'');const info=Components.Linkifier._linkInfo(anchor);info.enableDecorator=this._useLinkDecorator;info.fallback=fallbackAnchor;info.liveLocation=Bindings.debuggerWorkspaceBinding.createLiveLocation(rawLocation,this._updateAnchor.bind(this,anchor),(this._locationPoolByTarget.get(rawLocation.debuggerModel.target())));const anchors=(this._anchorsByTarget.get(rawLocation.debuggerModel.target()));anchors.push(anchor);return anchor;}
linkifyScriptLocation(target,scriptId,sourceURL,lineNumber,columnNumber,classes){const scriptLink=this.maybeLinkifyScriptLocation(target,scriptId,sourceURL,lineNumber,columnNumber,classes);return scriptLink||Components.Linkifier.linkifyURL(sourceURL,{className:classes,lineNumber:lineNumber,columnNumber:columnNumber,maxLength:this._maxLength});}
linkifyRawLocation(rawLocation,fallbackUrl,classes){return this.linkifyScriptLocation(rawLocation.debuggerModel.target(),rawLocation.scriptId,fallbackUrl,rawLocation.lineNumber,rawLocation.columnNumber,classes);}
maybeLinkifyConsoleCallFrame(target,callFrame,classes){return this.maybeLinkifyScriptLocation(target,callFrame.scriptId,callFrame.url,callFrame.lineNumber,callFrame.columnNumber,classes);}
linkifyStackTraceTopFrame(target,stackTrace,classes){console.assert(stackTrace.callFrames&&stackTrace.callFrames.length);const topFrame=stackTrace.callFrames[0];const fallbackAnchor=Components.Linkifier.linkifyURL(topFrame.url,{className:classes,lineNumber:topFrame.lineNumber,columnNumber:topFrame.columnNumber,maxLength:this._maxLength});if(target.isDisposed())
return fallbackAnchor;const debuggerModel=target.model(SDK.DebuggerModel);const rawLocations=debuggerModel.createRawLocationsByStackTrace(stackTrace);if(rawLocations.length===0)
return fallbackAnchor;const anchor=Components.Linkifier._createLink('',classes||'');const info=Components.Linkifier._linkInfo(anchor);info.enableDecorator=this._useLinkDecorator;info.fallback=fallbackAnchor;info.liveLocation=Bindings.debuggerWorkspaceBinding.createStackTraceTopFrameLiveLocation(rawLocations,this._updateAnchor.bind(this,anchor),(this._locationPoolByTarget.get(target)));const anchors=(this._anchorsByTarget.get(target));anchors.push(anchor);return anchor;}
linkifyCSSLocation(rawLocation,classes){const anchor=Components.Linkifier._createLink('',classes||'');const info=Components.Linkifier._linkInfo(anchor);info.enableDecorator=this._useLinkDecorator;info.liveLocation=Bindings.cssWorkspaceBinding.createLiveLocation(rawLocation,this._updateAnchor.bind(this,anchor),(this._locationPoolByTarget.get(rawLocation.cssModel().target())));const anchors=(this._anchorsByTarget.get(rawLocation.cssModel().target()));anchors.push(anchor);return anchor;}
reset(){for(const target of this._anchorsByTarget.keysArray()){this.targetRemoved(target);this.targetAdded(target);}}
dispose(){for(const target of this._anchorsByTarget.keysArray())
this.targetRemoved(target);SDK.targetManager.unobserveTargets(this);Components.Linkifier._instances.delete(this);}
_updateAnchor(anchor,liveLocation){Components.Linkifier._unbindUILocation(anchor);const uiLocation=liveLocation.uiLocation();if(!uiLocation)
return;Components.Linkifier._bindUILocation(anchor,uiLocation);const text=uiLocation.linkText(true);Components.Linkifier._setTrimmedText(anchor,text,this._maxLength);let titleText=uiLocation.uiSourceCode.url();if(typeof uiLocation.lineNumber==='number')
titleText+=':'+(uiLocation.lineNumber+1);anchor.title=titleText;anchor.classList.toggle('webkit-html-blackbox-link',liveLocation.isBlackboxed());Components.Linkifier._updateLinkDecorations(anchor);}
static _updateLinkDecorations(anchor){const info=Components.Linkifier._linkInfo(anchor);if(!info||!info.enableDecorator)
return;if(!Components.Linkifier._decorator||!info.uiLocation)
return;if(info.icon&&info.icon.parentElement)
anchor.removeChild(info.icon);const icon=Components.Linkifier._decorator.linkIcon(info.uiLocation.uiSourceCode);if(icon){icon.style.setProperty('margin-right','2px');anchor.insertBefore(icon,anchor.firstChild);}
info.icon=icon;}
static linkifyURL(url,options){options=options||{};const text=options.text;const className=options.className||'';const lineNumber=options.lineNumber;const columnNumber=options.columnNumber;const preventClick=options.preventClick;const maxLength=options.maxLength||UI.MaxLengthForDisplayedURLs;if(!url||url.trim().toLowerCase().startsWith('javascript:')){const element=createElementWithClass('span',className);element.textContent=text||url||Common.UIString('(unknown)');return element;}
let linkText=text||Bindings.displayNameForURL(url);if(typeof lineNumber==='number'&&!text)
linkText+=':'+(lineNumber+1);const title=linkText!==url?url:'';const link=Components.Linkifier._createLink(linkText,className,maxLength,title,url,preventClick);const info=Components.Linkifier._linkInfo(link);if(typeof lineNumber==='number')
info.lineNumber=lineNumber;if(typeof columnNumber==='number')
info.columnNumber=columnNumber;return link;}
static linkifyRevealable(revealable,text,fallbackHref){const link=Components.Linkifier._createLink(text,'',UI.MaxLengthForDisplayedURLs,undefined,fallbackHref);Components.Linkifier._linkInfo(link).revealable=revealable;return link;}
static _createLink(text,className,maxLength,title,href,preventClick){const link=createElementWithClass('span',className);link.classList.add('devtools-link');if(title)
link.title=title;if(href)
link.href=href;Components.Linkifier._setTrimmedText(link,text,maxLength);link[Components.Linkifier._infoSymbol]={icon:null,enableDecorator:false,uiLocation:null,liveLocation:null,url:href||null,lineNumber:null,columnNumber:null,revealable:null,fallback:null};if(!preventClick){link.addEventListener('click',event=>{if(Components.Linkifier._handleClick(event))
event.consume(true);},false);link.addEventListener('keydown',event=>{if(isEnterKey(event)&&Components.Linkifier._handleClick(event))
event.consume(true);},false);}else{link.classList.add('devtools-link-prevent-click');}
UI.ARIAUtils.markAsLink(link);return link;}
static _setTrimmedText(link,text,maxLength){link.removeChildren();if(maxLength&&text.length>maxLength){const middleSplit=splitMiddle(text,maxLength);appendTextWithoutHashes(middleSplit[0]);appendHiddenText(middleSplit[1]);appendTextWithoutHashes(middleSplit[2]);}else{appendTextWithoutHashes(text);}
function appendHiddenText(string){const ellipsisNode=link.createChild('span','devtools-link-ellipsis').createTextChild('\u2026');ellipsisNode[Components.Linkifier._untruncatedNodeTextSymbol]=string;}
function appendTextWithoutHashes(string){const hashSplit=TextUtils.TextUtils.splitStringByRegexes(string,[/[a-f0-9]{20,}/g]);for(const match of hashSplit){if(match.regexIndex===-1){link.createTextChild(match.value);}else{link.createTextChild(match.value.substring(0,7));appendHiddenText(match.value.substring(7));}}}
function splitMiddle(string,maxLength){let leftIndex=Math.floor(maxLength/2);let rightIndex=string.length-Math.ceil(maxLength/2)+1;if(string.codePointAt(rightIndex-1)>=0x10000){rightIndex++;leftIndex++;}
if(leftIndex>0&&string.codePointAt(leftIndex-1)>=0x10000)
leftIndex--;return[string.substring(0,leftIndex),string.substring(leftIndex,rightIndex),string.substring(rightIndex)];}}
static untruncatedNodeText(node){return node[Components.Linkifier._untruncatedNodeTextSymbol]||node.textContent;}
static _linkInfo(link){return(link?link[Components.Linkifier._infoSymbol]||null:null);}
static _handleClick(event){const link=(event.currentTarget);if(UI.isBeingEdited((event.target))||link.hasSelection())
return false;const actions=Components.Linkifier._linkActions(link);if(actions.length){actions[0].handler.call(null);return true;}
return false;}
static _linkHandlerSetting(){if(!Components.Linkifier._linkHandlerSettingInstance){Components.Linkifier._linkHandlerSettingInstance=Common.settings.createSetting('openLinkHandler',Common.UIString('auto'));}
return Components.Linkifier._linkHandlerSettingInstance;}
static registerLinkHandler(title,handler){Components.Linkifier._linkHandlers.set(title,handler);self.runtime.sharedInstance(Components.Linkifier.LinkHandlerSettingUI)._update();}
static unregisterLinkHandler(title){Components.Linkifier._linkHandlers.delete(title);self.runtime.sharedInstance(Components.Linkifier.LinkHandlerSettingUI)._update();}
static uiLocation(link){const info=Components.Linkifier._linkInfo(link);return info?info.uiLocation:null;}
static _linkActions(link){const info=Components.Linkifier._linkInfo(link);const result=[];if(!info)
return result;let url='';let uiLocation=null;if(info.uiLocation){uiLocation=info.uiLocation;url=uiLocation.uiSourceCode.contentURL();}else if(info.url){url=info.url;const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url)||Workspace.workspace.uiSourceCodeForURL(Common.ParsedURL.urlWithoutHash(url));uiLocation=uiSourceCode?uiSourceCode.uiLocation(info.lineNumber||0,info.columnNumber||0):null;}
const resource=url?Bindings.resourceForURL(url):null;const contentProvider=uiLocation?uiLocation.uiSourceCode:resource;const revealable=info.revealable||uiLocation||resource;if(revealable){const destination=Common.Revealer.revealDestination(revealable);result.push({section:'reveal',title:destination?ls`Reveal in ${destination}`:ls`Reveal`,handler:()=>Common.Revealer.reveal(revealable)});}
if(contentProvider){const lineNumber=uiLocation?uiLocation.lineNumber:info.lineNumber||0;for(const title of Components.Linkifier._linkHandlers.keys()){const handler=Components.Linkifier._linkHandlers.get(title);const action={section:'reveal',title:Common.UIString('Open using %s',title),handler:handler.bind(null,contentProvider,lineNumber)};if(title===Components.Linkifier._linkHandlerSetting().get())
result.unshift(action);else
result.push(action);}}
if(resource||info.url){result.push({section:'reveal',title:UI.openLinkExternallyLabel(),handler:()=>InspectorFrontendHost.openInNewTab(url)});result.push({section:'clipboard',title:UI.copyLinkAddressLabel(),handler:()=>InspectorFrontendHost.copyText(url)});}
return result;}};Components.Linkifier._instances=new Set();Components.Linkifier._decorator=null;Components.Linkifier._sourceCodeAnchors=Symbol('Linkifier.anchors');Components.Linkifier._infoSymbol=Symbol('Linkifier.info');Components.Linkifier._untruncatedNodeTextSymbol=Symbol('Linkifier.untruncatedNodeText');Components._LinkInfo;Components.LinkifyURLOptions;Components.Linkifier.MaxLengthToIgnoreLinkifier=10000;Components.Linkifier.LinkHandler;Components.Linkifier._linkHandlers=new Map();Components.LinkDecorator=function(){};Components.LinkDecorator.prototype={linkIcon(uiSourceCode){}};Components.LinkDecorator.Events={LinkIconChanged:Symbol('LinkIconChanged')};Components.Linkifier.LinkContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){let targetNode=(target);while(targetNode&&!targetNode[Components.Linkifier._infoSymbol])
targetNode=targetNode.parentNodeOrShadowHost();const link=(targetNode);const actions=Components.Linkifier._linkActions(link);for(const action of actions)
contextMenu.section(action.section).appendItem(action.title,action.handler);}};Components.Linkifier.LinkHandlerSettingUI=class{constructor(){this._element=createElementWithClass('select','chrome-select');this._element.addEventListener('change',this._onChange.bind(this),false);this._update();}
_update(){this._element.removeChildren();const names=Components.Linkifier._linkHandlers.keysArray();names.unshift(Common.UIString('auto'));for(const name of names){const option=createElement('option');option.textContent=name;option.selected=name===Components.Linkifier._linkHandlerSetting().get();this._element.appendChild(option);}
this._element.disabled=names.length<=1;}
_onChange(event){const value=event.target.value;Components.Linkifier._linkHandlerSetting().set(value);}
settingElement(){return UI.SettingsUI.createCustomSetting(Common.UIString('Link handling:'),this._element);}};Components.Linkifier.ContentProviderContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){const contentProvider=(target);if(!contentProvider.contentURL())
return;contextMenu.revealSection().appendItem(UI.openLinkExternallyLabel(),()=>InspectorFrontendHost.openInNewTab(contentProvider.contentURL()));for(const title of Components.Linkifier._linkHandlers.keys()){const handler=Components.Linkifier._linkHandlers.get(title);contextMenu.revealSection().appendItem(Common.UIString('Open using %s',title),handler.bind(null,contentProvider,0));}
if(contentProvider instanceof SDK.NetworkRequest)
return;contextMenu.clipboardSection().appendItem(UI.copyLinkAddressLabel(),()=>InspectorFrontendHost.copyText(contentProvider.contentURL()));}};;Components.reload=function(){if(Components.dockController.canDock()&&Components.dockController.dockSide()===Components.DockController.State.Undocked)
InspectorFrontendHost.setIsDocked(true,function(){});window.location.reload();};;Components.TargetDetachedDialog=class extends SDK.SDKModel{constructor(target){super(target);if(target.parentTarget())
return;target.registerInspectorDispatcher(this);target.inspectorAgent().enable();this._hideCrashedDialog=null;Components.TargetDetachedDialog._disconnectedScreenWithReasonWasShown=false;}
detached(reason){Components.TargetDetachedDialog._disconnectedScreenWithReasonWasShown=true;UI.RemoteDebuggingTerminatedScreen.show(reason);}
static webSocketConnectionLost(){UI.RemoteDebuggingTerminatedScreen.show('WebSocket disconnected');}
targetCrashed(){const dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.addCloseButton();dialog.setDimmed(true);this._hideCrashedDialog=dialog.hide.bind(dialog);new UI.TargetCrashedScreen(()=>this._hideCrashedDialog=null).show(dialog.contentElement);dialog.show();}
targetReloadedAfterCrash(){if(this._hideCrashedDialog){this._hideCrashedDialog.call(null);this._hideCrashedDialog=null;}}};SDK.SDKModel.register(Components.TargetDetachedDialog,SDK.Target.Capability.Inspector,true);;self['Persistence']=self['Persistence']||{};Persistence.PlatformFileSystem=class{constructor(path,type){this._path=path;this._type=type;}
getMetadata(path){return Promise.resolve((null));}
initialFilePaths(){return[];}
initialGitFolders(){return[];}
path(){return this._path;}
embedderPath(){throw new Error('Not implemented');}
type(){return this._type;}
async createFile(path,name){return Promise.resolve(null);}
deleteFile(path){return Promise.resolve(false);}
requestFileBlob(path){return Promise.resolve((null));}
requestFileContent(path,callback){callback(null,false);}
setFileContent(path,content,isBase64){throw new Error('Not implemented');}
renameFile(path,newName,callback){callback(false);}
addExcludedFolder(path){}
removeExcludedFolder(path){}
fileSystemRemoved(){}
isFileExcluded(folderPath){return false;}
excludedFolders(){return new Set();}
searchInPath(query,progress){return Promise.resolve([]);}
indexContent(progress){setImmediate(()=>progress.done());}
mimeFromPath(path){throw new Error('Not implemented');}
canExcludeFolder(path){return false;}
contentType(path){throw new Error('Not implemented');}
tooltipForURL(url){throw new Error('Not implemented');}
supportsAutomapping(){throw new Error('Not implemented');}};;Persistence.IsolatedFileSystem=class extends Persistence.PlatformFileSystem{constructor(manager,path,embedderPath,domFileSystem,type){super(path,type);this._manager=manager;this._embedderPath=embedderPath;this._domFileSystem=domFileSystem;this._excludedFoldersSetting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});this._excludedFolders=new Set(this._excludedFoldersSetting.get()[path]||[]);this._excludedEmbedderFolders=[];this._initialFilePaths=new Set();this._initialGitFolders=new Set();this._fileLocks=new Map();}
static create(manager,path,embedderPath,type,name,rootURL){const domFileSystem=InspectorFrontendHost.isolatedFileSystem(name,rootURL);if(!domFileSystem)
return Promise.resolve((null));const fileSystem=new Persistence.IsolatedFileSystem(manager,path,embedderPath,domFileSystem,type);return fileSystem._initializeFilePaths().then(()=>fileSystem).catchException((null));}
static errorMessage(error){return Common.UIString('File system error: %s',error.message);}
_serializedFileOperation(path,operation){const promise=Promise.resolve(this._fileLocks.get(path)).then(()=>operation.call(null));this._fileLocks.set(path,promise);return promise;}
getMetadata(path){let fulfill;const promise=new Promise(f=>fulfill=f);this._domFileSystem.root.getFile(path,undefined,fileEntryLoaded,errorHandler);return promise;function fileEntryLoaded(entry){entry.getMetadata(fulfill,errorHandler);}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when getting file metadata \''+path);fulfill(null);}}
initialFilePaths(){return this._initialFilePaths.valuesArray();}
initialGitFolders(){return this._initialGitFolders.valuesArray();}
embedderPath(){return this._embedderPath;}
_initializeFilePaths(){let fulfill;const promise=new Promise(x=>fulfill=x);let pendingRequests=1;const boundInnerCallback=innerCallback.bind(this);this._requestEntries('',boundInnerCallback);return promise;function innerCallback(entries){for(let i=0;i<entries.length;++i){const entry=entries[i];if(!entry.isDirectory){if(this.isFileExcluded(entry.fullPath))
continue;this._initialFilePaths.add(entry.fullPath.substr(1));}else{if(entry.fullPath.endsWith('/.git')){const lastSlash=entry.fullPath.lastIndexOf('/');const parentFolder=entry.fullPath.substring(1,lastSlash);this._initialGitFolders.add(parentFolder);}
if(this.isFileExcluded(entry.fullPath+'/')){this._excludedEmbedderFolders.push(Common.ParsedURL.urlToPlatformPath(this.path()+entry.fullPath,Host.isWin()));continue;}
++pendingRequests;this._requestEntries(entry.fullPath,boundInnerCallback);}}
if((--pendingRequests===0))
fulfill();}}
async _createFoldersIfNotExist(folderPath){let dirEntry=await new Promise(resolve=>this._domFileSystem.root.getDirectory(folderPath,undefined,resolve,()=>resolve(null)));if(dirEntry)
return dirEntry;const paths=folderPath.split('/');let activePath='';for(const path of paths){activePath=activePath+'/'+path;dirEntry=await this._innerCreateFolderIfNeeded(activePath);if(!dirEntry)
return null;}
return dirEntry;}
_innerCreateFolderIfNeeded(path){return new Promise(resolve=>{this._domFileSystem.root.getDirectory(path,{create:true},dirEntry=>resolve(dirEntry),error=>{const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' trying to create directory \''+path+'\'');resolve(null);});});}
async createFile(path,name){const dirEntry=await this._createFoldersIfNotExist(path);if(!dirEntry)
return null;const fileEntry=await this._serializedFileOperation(path,createFileCandidate.bind(this,name||'NewFile'));if(!fileEntry)
return null;return fileEntry.fullPath.substr(1);function createFileCandidate(name,newFileIndex){return new Promise(resolve=>{const nameCandidate=name+(newFileIndex||'');dirEntry.getFile(nameCandidate,{create:true,exclusive:true},resolve,error=>{if(error.name==='InvalidModificationError'){resolve(createFileCandidate.call(this,name,(newFileIndex?newFileIndex+1:1)));return;}
const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when testing if file exists \''+(this.path()+'/'+path+'/'+nameCandidate)+'\'');resolve(null);});});}}
deleteFile(path){let resolveCallback;const promise=new Promise(resolve=>resolveCallback=resolve);this._domFileSystem.root.getFile(path,undefined,fileEntryLoaded.bind(this),errorHandler.bind(this));return promise;function fileEntryLoaded(fileEntry){fileEntry.remove(fileEntryRemoved,errorHandler.bind(this));}
function fileEntryRemoved(){resolveCallback(true);}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when deleting file \''+(this.path()+'/'+path)+'\'');resolveCallback(false);}}
requestFileBlob(path){return new Promise(resolve=>{this._domFileSystem.root.getFile(path,undefined,entry=>{entry.file(resolve,errorHandler.bind(this));},errorHandler.bind(this));function errorHandler(error){if(error.name==='NotFoundError'){resolve(null);return;}
const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when getting content for file \''+(this.path()+'/'+path)+'\'');resolve(null);}});}
requestFileContent(path,callback){const innerRequestFileContent=async()=>{const blob=await this.requestFileBlob(path);if(!blob){callback(null,false);return;}
const reader=new FileReader();const extension=Common.ParsedURL.extractExtension(path);const encoded=Persistence.IsolatedFileSystem.BinaryExtensions.has(extension);const readPromise=new Promise(x=>reader.onloadend=x);if(encoded)
reader.readAsBinaryString(blob);else
reader.readAsText(blob);await readPromise;if(reader.error){console.error('Can\'t read file: '+path+': '+reader.error);callback(null,false);return;}
let result;try{result=reader.result;}catch(e){result=null;console.error('Can\'t read file: '+path+': '+e);}
if(result===undefined||result===null){callback(null,false);return;}
callback(encoded?btoa(result):result,encoded);};this._serializedFileOperation(path,innerRequestFileContent);}
async setFileContent(path,content,isBase64){Host.userMetrics.actionTaken(Host.UserMetrics.Action.FileSavedInWorkspace);let callback;const innerSetFileContent=()=>{const promise=new Promise(x=>callback=x);this._domFileSystem.root.getFile(path,{create:true},fileEntryLoaded.bind(this),errorHandler.bind(this));return promise;};this._serializedFileOperation(path,innerSetFileContent);function fileEntryLoaded(entry){entry.createWriter(fileWriterCreated.bind(this),errorHandler.bind(this));}
async function fileWriterCreated(fileWriter){fileWriter.onerror=errorHandler.bind(this);fileWriter.onwriteend=fileWritten;let blob;if(isBase64)
blob=await(await fetch(`data:application/octet-stream;base64,${content}`)).blob();else
blob=new Blob([content],{type:'text/plain'});fileWriter.write(blob);function fileWritten(){fileWriter.onwriteend=callback;fileWriter.truncate(blob.size);}}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when setting content for file \''+(this.path()+'/'+path)+'\'');callback();}}
renameFile(path,newName,callback){newName=newName?newName.trim():newName;if(!newName||newName.indexOf('/')!==-1){callback(false);return;}
let fileEntry;let dirEntry;this._domFileSystem.root.getFile(path,undefined,fileEntryLoaded.bind(this),errorHandler.bind(this));function fileEntryLoaded(entry){if(entry.name===newName){callback(false);return;}
fileEntry=entry;fileEntry.getParent(dirEntryLoaded.bind(this),errorHandler.bind(this));}
function dirEntryLoaded(entry){dirEntry=entry;dirEntry.getFile(newName,null,newFileEntryLoaded,newFileEntryLoadErrorHandler.bind(this));}
function newFileEntryLoaded(entry){callback(false);}
function newFileEntryLoadErrorHandler(error){if(error.name!=='NotFoundError'){callback(false);return;}
fileEntry.moveTo(dirEntry,newName,fileRenamed,errorHandler.bind(this));}
function fileRenamed(entry){callback(true,entry.name);}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when renaming file \''+(this.path()+'/'+path)+'\' to \''+newName+'\'');callback(false);}}
_readDirectory(dirEntry,callback){const dirReader=dirEntry.createReader();let entries=[];function innerCallback(results){if(!results.length){callback(entries.sort());}else{entries=entries.concat(toArray(results));dirReader.readEntries(innerCallback,errorHandler);}}
function toArray(list){return Array.prototype.slice.call(list||[],0);}
dirReader.readEntries(innerCallback,errorHandler);function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when reading directory \''+dirEntry.fullPath+'\'');callback([]);}}
_requestEntries(path,callback){this._domFileSystem.root.getDirectory(path,undefined,innerCallback.bind(this),errorHandler);function innerCallback(dirEntry){this._readDirectory(dirEntry,callback);}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when requesting entry \''+path+'\'');callback([]);}}
_saveExcludedFolders(){const settingValue=this._excludedFoldersSetting.get();settingValue[this.path()]=this._excludedFolders.valuesArray();this._excludedFoldersSetting.set(settingValue);}
addExcludedFolder(path){this._excludedFolders.add(path);this._saveExcludedFolders();this._manager.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderAdded,path);}
removeExcludedFolder(path){this._excludedFolders.delete(path);this._saveExcludedFolders();this._manager.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderRemoved,path);}
fileSystemRemoved(){const settingValue=this._excludedFoldersSetting.get();delete settingValue[this.path()];this._excludedFoldersSetting.set(settingValue);}
isFileExcluded(folderPath){if(this._excludedFolders.has(folderPath))
return true;const regex=this._manager.workspaceFolderExcludePatternSetting().asRegExp();return!!(regex&&regex.test(folderPath));}
excludedFolders(){return this._excludedFolders;}
searchInPath(query,progress){return new Promise(resolve=>{const requestId=this._manager.registerCallback(innerCallback);InspectorFrontendHost.searchInPath(requestId,this._embedderPath,query);function innerCallback(files){resolve(files.map(path=>Common.ParsedURL.platformPathToURL(path)));progress.worked(1);}});}
indexContent(progress){progress.setTotalWork(1);const requestId=this._manager.registerProgress(progress);InspectorFrontendHost.indexPath(requestId,this._embedderPath,JSON.stringify(this._excludedEmbedderFolders));}
mimeFromPath(path){return Common.ResourceType.mimeFromURL(path)||'text/plain';}
canExcludeFolder(path){return!!path&&this.type()!=='overrides';}
contentType(path){const extension=Common.ParsedURL.extractExtension(path);if(Persistence.IsolatedFileSystem._styleSheetExtensions.has(extension))
return Common.resourceTypes.Stylesheet;if(Persistence.IsolatedFileSystem._documentExtensions.has(extension))
return Common.resourceTypes.Document;if(Persistence.IsolatedFileSystem.ImageExtensions.has(extension))
return Common.resourceTypes.Image;if(Persistence.IsolatedFileSystem._scriptExtensions.has(extension))
return Common.resourceTypes.Script;return Persistence.IsolatedFileSystem.BinaryExtensions.has(extension)?Common.resourceTypes.Other:Common.resourceTypes.Document;}
tooltipForURL(url){const path=Common.ParsedURL.urlToPlatformPath(url,Host.isWin()).trimMiddle(150);return ls`Linked to ${path}`;}
supportsAutomapping(){return this.type()!=='overrides';}};Persistence.IsolatedFileSystem._styleSheetExtensions=new Set(['css','scss','sass','less']);Persistence.IsolatedFileSystem._documentExtensions=new Set(['htm','html','asp','aspx','phtml','jsp']);Persistence.IsolatedFileSystem._scriptExtensions=new Set(['asp','aspx','c','cc','cljs','coffee','cpp','cs','dart','java','js','jsp','jsx','h','m','mjs','mm','py','sh','ts','tsx','ls']);Persistence.IsolatedFileSystem.ImageExtensions=new Set(['jpeg','jpg','svg','gif','webp','png','ico','tiff','tif','bmp']);Persistence.IsolatedFileSystem.BinaryExtensions=new Set(['cmd','com','exe','a','ar','iso','tar','bz2','gz','lz','lzma','z','7z','apk','arc','cab','dmg','jar','pak','rar','zip','3gp','aac','aiff','flac','m4a','mmf','mp3','ogg','oga','raw','sln','wav','wma','webm','mkv','flv','vob','ogv','gifv','avi','mov','qt','mp4','m4p','m4v','mpg','mpeg','jpeg','jpg','gif','webp','png','ico','tiff','tif','bmp']);;Persistence.IsolatedFileSystemManager=class extends Common.Object{constructor(){super();this._fileSystems=new Map();this._callbacks=new Map();this._progresses=new Map();InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemRemoved,this._onFileSystemRemoved,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemAdded,this._onFileSystemAdded,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,this._onFileSystemFilesChanged,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingTotalWorkCalculated,this._onIndexingTotalWorkCalculated,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingWorked,this._onIndexingWorked,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingDone,this._onIndexingDone,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SearchCompleted,this._onSearchCompleted,this);this._initExcludePatterSetting();this._fileSystemRequestResolve=null;this._fileSystemsLoadedPromise=this._requestFileSystems();}
_requestFileSystems(){let fulfill;const promise=new Promise(f=>fulfill=f);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemsLoaded,onFileSystemsLoaded,this);InspectorFrontendHost.requestFileSystems();return promise;function onFileSystemsLoaded(event){const fileSystems=(event.data);const promises=[];for(let i=0;i<fileSystems.length;++i)
promises.push(this._innerAddFileSystem(fileSystems[i],false));Promise.all(promises).then(onFileSystemsAdded);}
function onFileSystemsAdded(fileSystems){fulfill(fileSystems.filter(fs=>!!fs));}}
addFileSystem(type){return new Promise(resolve=>{this._fileSystemRequestResolve=resolve;InspectorFrontendHost.addFileSystem(type||'');});}
removeFileSystem(fileSystem){InspectorFrontendHost.removeFileSystem(fileSystem.embedderPath());}
waitForFileSystems(){return this._fileSystemsLoadedPromise;}
_innerAddFileSystem(fileSystem,dispatchEvent){const embedderPath=fileSystem.fileSystemPath;const fileSystemURL=Common.ParsedURL.platformPathToURL(fileSystem.fileSystemPath);const promise=Persistence.IsolatedFileSystem.create(this,fileSystemURL,embedderPath,fileSystem.type,fileSystem.fileSystemName,fileSystem.rootURL);return promise.then(storeFileSystem.bind(this));function storeFileSystem(fileSystem){if(!fileSystem)
return null;this._fileSystems.set(fileSystemURL,fileSystem);if(dispatchEvent)
this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,fileSystem);return fileSystem;}}
addPlatformFileSystem(fileSystemURL,fileSystem){this._fileSystems.set(fileSystemURL,fileSystem);this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,fileSystem);}
async _onFileSystemAdded(event){const errorMessage=(event.data['errorMessage']);let fileSystem=(event.data['fileSystem']);if(errorMessage){Common.console.error(Common.UIString('Unable to add filesystem: %s',errorMessage));if(!this._fileSystemRequestResolve)
return;this._fileSystemRequestResolve.call(null,null);this._fileSystemRequestResolve=null;}else if(fileSystem){fileSystem=await this._innerAddFileSystem(fileSystem,true);if(this._fileSystemRequestResolve){this._fileSystemRequestResolve.call(null,fileSystem);this._fileSystemRequestResolve=null;}}}
_onFileSystemRemoved(event){const embedderPath=(event.data);const fileSystemPath=Common.ParsedURL.platformPathToURL(embedderPath);const isolatedFileSystem=this._fileSystems.get(fileSystemPath);if(!isolatedFileSystem)
return;this._fileSystems.delete(fileSystemPath);isolatedFileSystem.fileSystemRemoved();this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,isolatedFileSystem);}
_onFileSystemFilesChanged(event){const urlPaths={changed:groupFilePathsIntoFileSystemPaths.call(this,event.data.changed),added:groupFilePathsIntoFileSystemPaths.call(this,event.data.added),removed:groupFilePathsIntoFileSystemPaths.call(this,event.data.removed)};this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemFilesChanged,urlPaths);function groupFilePathsIntoFileSystemPaths(embedderPaths){const paths=new Multimap();for(const embedderPath of embedderPaths){const filePath=Common.ParsedURL.platformPathToURL(embedderPath);for(const fileSystemPath of this._fileSystems.keys()){if(this._fileSystems.get(fileSystemPath).isFileExcluded(embedderPath))
continue;const pathPrefix=fileSystemPath.endsWith('/')?fileSystemPath:fileSystemPath+'/';if(!filePath.startsWith(pathPrefix))
continue;paths.set(fileSystemPath,filePath);}}
return paths;}}
fileSystems(){return this._fileSystems.valuesArray();}
fileSystem(fileSystemPath){return this._fileSystems.get(fileSystemPath)||null;}
_initExcludePatterSetting(){const defaultCommonExcludedFolders=['/node_modules/','/bower_components/','/\\.devtools','/\\.git/','/\\.sass-cache/','/\\.hg/','/\\.idea/','/\\.svn/','/\\.cache/','/\\.project/'];const defaultWinExcludedFolders=['/Thumbs.db$','/ehthumbs.db$','/Desktop.ini$','/\\$RECYCLE.BIN/'];const defaultMacExcludedFolders=['/\\.DS_Store$','/\\.Trashes$','/\\.Spotlight-V100$','/\\.AppleDouble$','/\\.LSOverride$','/Icon$','/\\._.*$'];const defaultLinuxExcludedFolders=['/.*~$'];let defaultExcludedFolders=defaultCommonExcludedFolders;if(Host.isWin())
defaultExcludedFolders=defaultExcludedFolders.concat(defaultWinExcludedFolders);else if(Host.isMac())
defaultExcludedFolders=defaultExcludedFolders.concat(defaultMacExcludedFolders);else
defaultExcludedFolders=defaultExcludedFolders.concat(defaultLinuxExcludedFolders);const defaultExcludedFoldersPattern=defaultExcludedFolders.join('|');this._workspaceFolderExcludePatternSetting=Common.settings.createRegExpSetting('workspaceFolderExcludePattern',defaultExcludedFoldersPattern,Host.isWin()?'i':'');}
workspaceFolderExcludePatternSetting(){return this._workspaceFolderExcludePatternSetting;}
registerCallback(callback){const requestId=++Persistence.IsolatedFileSystemManager._lastRequestId;this._callbacks.set(requestId,callback);return requestId;}
registerProgress(progress){const requestId=++Persistence.IsolatedFileSystemManager._lastRequestId;this._progresses.set(requestId,progress);return requestId;}
_onIndexingTotalWorkCalculated(event){const requestId=(event.data['requestId']);const totalWork=(event.data['totalWork']);const progress=this._progresses.get(requestId);if(!progress)
return;progress.setTotalWork(totalWork);}
_onIndexingWorked(event){const requestId=(event.data['requestId']);const worked=(event.data['worked']);const progress=this._progresses.get(requestId);if(!progress)
return;progress.worked(worked);if(progress.isCanceled()){InspectorFrontendHost.stopIndexing(requestId);this._onIndexingDone(event);}}
_onIndexingDone(event){const requestId=(event.data['requestId']);const progress=this._progresses.get(requestId);if(!progress)
return;progress.done();this._progresses.delete(requestId);}
_onSearchCompleted(event){const requestId=(event.data['requestId']);const files=(event.data['files']);const callback=this._callbacks.get(requestId);if(!callback)
return;callback.call(null,files);this._callbacks.delete(requestId);}};Persistence.IsolatedFileSystemManager.FileSystem;Persistence.IsolatedFileSystemManager.FilesChangedData;Persistence.IsolatedFileSystemManager.Events={FileSystemAdded:Symbol('FileSystemAdded'),FileSystemRemoved:Symbol('FileSystemRemoved'),FileSystemFilesChanged:Symbol('FileSystemFilesChanged'),ExcludedFolderAdded:Symbol('ExcludedFolderAdded'),ExcludedFolderRemoved:Symbol('ExcludedFolderRemoved')};Persistence.IsolatedFileSystemManager._lastRequestId=0;Persistence.isolatedFileSystemManager;;Persistence.FileSystemWorkspaceBinding=class{constructor(isolatedFileSystemManager,workspace){this._isolatedFileSystemManager=isolatedFileSystemManager;this._workspace=workspace;this._eventListeners=[this._isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,this._onFileSystemAdded,this),this._isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,this._onFileSystemRemoved,this),this._isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemFilesChanged,this._fileSystemFilesChanged,this)];this._boundFileSystems=new Map();this._isolatedFileSystemManager.waitForFileSystems().then(this._onFileSystemsLoaded.bind(this));}
static projectId(fileSystemPath){return fileSystemPath;}
static relativePath(uiSourceCode){const baseURL=(uiSourceCode.project())._fileSystemBaseURL;return uiSourceCode.url().substring(baseURL.length).split('/');}
static tooltipForUISourceCode(uiSourceCode){const fileSystem=(uiSourceCode.project())._fileSystem;return fileSystem.tooltipForURL(uiSourceCode.url());}
static fileSystemType(project){const fileSystem=(project)._fileSystem;return fileSystem.type();}
static fileSystemSupportsAutomapping(project){const fileSystem=(project)._fileSystem;return fileSystem.supportsAutomapping();}
static completeURL(project,relativePath){const fsProject=(project);return fsProject._fileSystemBaseURL+relativePath;}
static fileSystemPath(projectId){return projectId;}
fileSystemManager(){return this._isolatedFileSystemManager;}
_onFileSystemsLoaded(fileSystems){for(const fileSystem of fileSystems)
this._addFileSystem(fileSystem);}
_onFileSystemAdded(event){const fileSystem=(event.data);this._addFileSystem(fileSystem);}
_addFileSystem(fileSystem){const boundFileSystem=new Persistence.FileSystemWorkspaceBinding.FileSystem(this,fileSystem,this._workspace);this._boundFileSystems.set(fileSystem.path(),boundFileSystem);}
_onFileSystemRemoved(event){const fileSystem=(event.data);const boundFileSystem=this._boundFileSystems.get(fileSystem.path());boundFileSystem.dispose();this._boundFileSystems.remove(fileSystem.path());}
_fileSystemFilesChanged(event){const paths=(event.data);for(const fileSystemPath of paths.changed.keysArray()){const fileSystem=this._boundFileSystems.get(fileSystemPath);if(!fileSystem)
continue;paths.changed.get(fileSystemPath).forEach(path=>fileSystem._fileChanged(path));}
for(const fileSystemPath of paths.added.keysArray()){const fileSystem=this._boundFileSystems.get(fileSystemPath);if(!fileSystem)
continue;paths.added.get(fileSystemPath).forEach(path=>fileSystem._fileChanged(path));}
for(const fileSystemPath of paths.removed.keysArray()){const fileSystem=this._boundFileSystems.get(fileSystemPath);if(!fileSystem)
continue;paths.removed.get(fileSystemPath).forEach(path=>fileSystem.removeUISourceCode(path));}}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);for(const fileSystem of this._boundFileSystems.values()){fileSystem.dispose();this._boundFileSystems.remove(fileSystem._fileSystem.path());}}};Persistence.FileSystemWorkspaceBinding.FileSystem=class extends Workspace.ProjectStore{constructor(fileSystemWorkspaceBinding,isolatedFileSystem,workspace){const fileSystemPath=isolatedFileSystem.path();const id=Persistence.FileSystemWorkspaceBinding.projectId(fileSystemPath);console.assert(!workspace.project(id));const displayName=fileSystemPath.substr(fileSystemPath.lastIndexOf('/')+1);super(workspace,id,Workspace.projectTypes.FileSystem,displayName);this._fileSystem=isolatedFileSystem;this._fileSystemBaseURL=this._fileSystem.path()+'/';this._fileSystemParentURL=this._fileSystemBaseURL.substr(0,fileSystemPath.lastIndexOf('/')+1);this._fileSystemWorkspaceBinding=fileSystemWorkspaceBinding;this._fileSystemPath=fileSystemPath;this._creatingFilesGuard=new Set();workspace.addProject(this);this.populate();}
fileSystemPath(){return this._fileSystemPath;}
mimeType(uiSourceCode){return this._fileSystem.mimeFromPath(uiSourceCode.url());}
initialGitFolders(){return this._fileSystem.initialGitFolders().map(folder=>this._fileSystemPath+'/'+folder);}
_filePathForUISourceCode(uiSourceCode){return uiSourceCode.url().substring(this._fileSystemPath.length);}
isServiceProject(){return false;}
requestMetadata(uiSourceCode){if(uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata])
return uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata];const relativePath=this._filePathForUISourceCode(uiSourceCode);const promise=this._fileSystem.getMetadata(relativePath).then(onMetadata);uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]=promise;return promise;function onMetadata(metadata){if(!metadata)
return null;return new Workspace.UISourceCodeMetadata(metadata.modificationTime,metadata.size);}}
requestFileBlob(uiSourceCode){return this._fileSystem.requestFileBlob(this._filePathForUISourceCode(uiSourceCode));}
requestFileContent(uiSourceCode,callback){const filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.requestFileContent(filePath,callback);}
canSetFileContent(){return true;}
async setFileContent(uiSourceCode,newContent,isBase64){const filePath=this._filePathForUISourceCode(uiSourceCode);await this._fileSystem.setFileContent(filePath,newContent,isBase64);}
fullDisplayName(uiSourceCode){const baseURL=(uiSourceCode.project())._fileSystemParentURL;return uiSourceCode.url().substring(baseURL.length);}
canRename(){return true;}
rename(uiSourceCode,newName,callback){if(newName===uiSourceCode.name()){callback(true,uiSourceCode.name(),uiSourceCode.url(),uiSourceCode.contentType());return;}
let filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.renameFile(filePath,newName,innerCallback.bind(this));function innerCallback(success,newName){if(!success||!newName){callback(false,newName);return;}
console.assert(newName);const slash=filePath.lastIndexOf('/');const parentPath=filePath.substring(0,slash);filePath=parentPath+'/'+newName;filePath=filePath.substr(1);const newURL=this._fileSystemBaseURL+filePath;const newContentType=this._fileSystem.contentType(newName);this.renameUISourceCode(uiSourceCode,newName);callback(true,newName,newURL,newContentType);}}
searchInFileContent(uiSourceCode,query,caseSensitive,isRegex){return new Promise(resolve=>{const filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.requestFileContent(filePath,contentCallback);function contentCallback(content){resolve(content?Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex):[]);}});}
async findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,progress){let result=filesMathingFileQuery;const queriesToRun=searchConfig.queries().slice();if(!queriesToRun.length)
queriesToRun.push('');progress.setTotalWork(queriesToRun.length);for(const query of queriesToRun){const files=await this._fileSystem.searchInPath(searchConfig.isRegex()?'':query,progress);result=result.intersectOrdered(files.sort(),String.naturalOrderComparator);progress.worked(1);}
progress.done();return result;}
indexContent(progress){this._fileSystem.indexContent(progress);}
populate(){const chunkSize=1000;const filePaths=this._fileSystem.initialFilePaths();reportFileChunk.call(this,0);function reportFileChunk(from){const to=Math.min(from+chunkSize,filePaths.length);for(let i=from;i<to;++i)
this._addFile(filePaths[i]);if(to<filePaths.length)
setTimeout(reportFileChunk.bind(this,to),100);}}
excludeFolder(url){let relativeFolder=url.substring(this._fileSystemBaseURL.length);if(!relativeFolder.startsWith('/'))
relativeFolder='/'+relativeFolder;if(!relativeFolder.endsWith('/'))
relativeFolder+='/';this._fileSystem.addExcludedFolder(relativeFolder);const uiSourceCodes=this.uiSourceCodes().slice();for(let i=0;i<uiSourceCodes.length;++i){const uiSourceCode=uiSourceCodes[i];if(uiSourceCode.url().startsWith(url))
this.removeUISourceCode(uiSourceCode.url());}}
canExcludeFolder(path){return this._fileSystem.canExcludeFolder(path);}
canCreateFile(){return true;}
async createFile(path,name,content,isBase64){const guardFileName=this._fileSystemPath+path+(!path.endsWith('/')?'/':'')+name;this._creatingFilesGuard.add(guardFileName);const filePath=await this._fileSystem.createFile(path,name);if(!filePath)
return null;const uiSourceCode=this._addFile(filePath);uiSourceCode.setContent(content,!!isBase64);this._creatingFilesGuard.delete(guardFileName);return uiSourceCode;}
deleteFile(uiSourceCode){const relativePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.deleteFile(relativePath).then(success=>{if(success)
this.removeUISourceCode(uiSourceCode.url());});}
remove(){this._fileSystemWorkspaceBinding._isolatedFileSystemManager.removeFileSystem(this._fileSystem);}
_addFile(filePath){const contentType=this._fileSystem.contentType(filePath);const uiSourceCode=this.createUISourceCode(this._fileSystemBaseURL+filePath,contentType);this.addUISourceCode(uiSourceCode);return uiSourceCode;}
_fileChanged(path){if(this._creatingFilesGuard.has(path))
return;const uiSourceCode=this.uiSourceCodeForURL(path);if(!uiSourceCode){const contentType=this._fileSystem.contentType(path);this.addUISourceCode(this.createUISourceCode(path,contentType));return;}
uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]=null;uiSourceCode.checkContentUpdated();}
tooltipForURL(url){return this._fileSystem.tooltipForURL(url);}
dispose(){this.removeProject();}};Persistence.FileSystemWorkspaceBinding._metadata=Symbol('FileSystemWorkspaceBinding.Metadata');;Persistence.Automapping=class{constructor(workspace,onStatusAdded,onStatusRemoved){this._workspace=workspace;this._onStatusAdded=onStatusAdded;this._onStatusRemoved=onStatusRemoved;this._statuses=new Set();this._fileSystemUISourceCodes=new Map();this._sweepThrottler=new Common.Throttler(100);const pathEncoder=new Persistence.PathEncoder();this._filesIndex=new Persistence.Automapping.FilePathIndex(pathEncoder);this._projectFoldersIndex=new Persistence.Automapping.FolderIndex(pathEncoder);this._activeFoldersIndex=new Persistence.Automapping.FolderIndex(pathEncoder);this._eventListeners=[this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,event=>this._onUISourceCodeAdded((event.data))),this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,event=>this._onUISourceCodeRemoved((event.data))),this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRenamed,this._onUISourceCodeRenamed,this),this._workspace.addEventListener(Workspace.Workspace.Events.ProjectAdded,event=>this._onProjectAdded((event.data)),this),this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,event=>this._onProjectRemoved((event.data)),this),];for(const fileSystem of workspace.projects())
this._onProjectAdded(fileSystem);for(const uiSourceCode of workspace.uiSourceCodes())
this._onUISourceCodeAdded(uiSourceCode);}
_scheduleRemap(){for(const status of this._statuses.valuesArray())
this._clearNetworkStatus(status.network);this._scheduleSweep();}
_scheduleSweep(){this._sweepThrottler.schedule(sweepUnmapped.bind(this));function sweepUnmapped(){const networkProjects=this._workspace.projectsForType(Workspace.projectTypes.Network);for(const networkProject of networkProjects){for(const uiSourceCode of networkProject.uiSourceCodes())
this._computeNetworkStatus(uiSourceCode);}
this._onSweepHappenedForTest();return Promise.resolve();}}
_onSweepHappenedForTest(){}
_onProjectRemoved(project){for(const uiSourceCode of project.uiSourceCodes())
this._onUISourceCodeRemoved(uiSourceCode);if(project.type()!==Workspace.projectTypes.FileSystem)
return;const fileSystem=(project);for(const gitFolder of fileSystem.initialGitFolders())
this._projectFoldersIndex.removeFolder(gitFolder);this._projectFoldersIndex.removeFolder(fileSystem.fileSystemPath());this._scheduleRemap();}
_onProjectAdded(project){if(project.type()!==Workspace.projectTypes.FileSystem)
return;const fileSystem=(project);for(const gitFolder of fileSystem.initialGitFolders())
this._projectFoldersIndex.addFolder(gitFolder);this._projectFoldersIndex.addFolder(fileSystem.fileSystemPath());project.uiSourceCodes().forEach(this._onUISourceCodeAdded.bind(this));this._scheduleRemap();}
_onUISourceCodeAdded(uiSourceCode){const project=uiSourceCode.project();if(project.type()===Workspace.projectTypes.FileSystem){if(!Persistence.FileSystemWorkspaceBinding.fileSystemSupportsAutomapping(project))
return;this._filesIndex.addPath(uiSourceCode.url());this._fileSystemUISourceCodes.set(uiSourceCode.url(),uiSourceCode);this._scheduleSweep();}else if(project.type()===Workspace.projectTypes.Network){this._computeNetworkStatus(uiSourceCode);}}
_onUISourceCodeRemoved(uiSourceCode){if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem){this._filesIndex.removePath(uiSourceCode.url());this._fileSystemUISourceCodes.delete(uiSourceCode.url());const status=uiSourceCode[Persistence.Automapping._status];if(status)
this._clearNetworkStatus(status.network);}else if(uiSourceCode.project().type()===Workspace.projectTypes.Network){this._clearNetworkStatus(uiSourceCode);}}
_onUISourceCodeRenamed(event){const uiSourceCode=(event.data.uiSourceCode);const oldURL=(event.data.oldURL);if(uiSourceCode.project().type()!==Workspace.projectTypes.FileSystem)
return;this._filesIndex.removePath(oldURL);this._fileSystemUISourceCodes.delete(oldURL);const status=uiSourceCode[Persistence.Automapping._status];if(status)
this._clearNetworkStatus(status.network);this._filesIndex.addPath(uiSourceCode.url());this._fileSystemUISourceCodes.set(uiSourceCode.url(),uiSourceCode);this._scheduleSweep();}
_computeNetworkStatus(networkSourceCode){if(networkSourceCode[Persistence.Automapping._processingPromise]||networkSourceCode[Persistence.Automapping._status])
return;if(networkSourceCode.url().startsWith('wasm://'))
return;const createBindingPromise=this._createBinding(networkSourceCode).then(validateStatus.bind(this)).then(onStatus.bind(this));networkSourceCode[Persistence.Automapping._processingPromise]=createBindingPromise;async function validateStatus(status){if(!status)
return null;if(networkSourceCode[Persistence.Automapping._processingPromise]!==createBindingPromise)
return null;if(status.network.contentType().isFromSourceMap()||!status.fileSystem.contentType().isTextType())
return status;if(status.fileSystem.isDirty()&&(status.network.isDirty()||status.network.hasCommits()))
return null;const contents=await Promise.all([status.fileSystem.requestContent(),new Promise(x=>status.network.project().requestFileContent(status.network,x))]);const fileSystemContent=contents[0];const networkContent=contents[1];if(fileSystemContent===null||networkContent===null)
return null;if(networkSourceCode[Persistence.Automapping._processingPromise]!==createBindingPromise)
return null;const target=Bindings.NetworkProject.targetForUISourceCode(status.network);let isValid=false;if(target&&target.type()===SDK.Target.Type.Node){const rewrappedNetworkContent=Persistence.Persistence.rewrapNodeJSContent(status.fileSystem,fileSystemContent,networkContent);isValid=fileSystemContent===rewrappedNetworkContent;}else{isValid=fileSystemContent.trimRight()===networkContent.trimRight();}
if(!isValid){this._prevalidationFailedForTest(status);return null;}
return status;}
function onStatus(status){if(networkSourceCode[Persistence.Automapping._processingPromise]!==createBindingPromise)
return;networkSourceCode[Persistence.Automapping._processingPromise]=null;if(!status||this._disposed){this._onBindingFailedForTest();return;}
if(status.network[Persistence.Automapping._status]||status.fileSystem[Persistence.Automapping._status])
return;this._statuses.add(status);status.network[Persistence.Automapping._status]=status;status.fileSystem[Persistence.Automapping._status]=status;if(status.exactMatch){const projectFolder=this._projectFoldersIndex.closestParentFolder(status.fileSystem.url());const newFolderAdded=projectFolder?this._activeFoldersIndex.addFolder(projectFolder):false;if(newFolderAdded)
this._scheduleSweep();}
this._onStatusAdded.call(null,status);}}
_prevalidationFailedForTest(binding){}
_onBindingFailedForTest(){}
_clearNetworkStatus(networkSourceCode){if(networkSourceCode[Persistence.Automapping._processingPromise]){networkSourceCode[Persistence.Automapping._processingPromise]=null;return;}
const status=networkSourceCode[Persistence.Automapping._status];if(!status)
return;this._statuses.delete(status);status.network[Persistence.Automapping._status]=null;status.fileSystem[Persistence.Automapping._status]=null;if(status.exactMatch){const projectFolder=this._projectFoldersIndex.closestParentFolder(status.fileSystem.url());if(projectFolder)
this._activeFoldersIndex.removeFolder(projectFolder);}
this._onStatusRemoved.call(null,status);}
_createBinding(networkSourceCode){if(networkSourceCode.url().startsWith('file://')||networkSourceCode.url().startsWith('snippet://')){const fileSourceCode=this._fileSystemUISourceCodes.get(networkSourceCode.url());const status=fileSourceCode?new Persistence.AutomappingStatus(networkSourceCode,fileSourceCode,false):null;return Promise.resolve(status);}
let networkPath=Common.ParsedURL.extractPath(networkSourceCode.url());if(networkPath===null)
return Promise.resolve((null));if(networkPath.endsWith('/'))
networkPath+='index.html';const similarFiles=this._filesIndex.similarFiles(networkPath).map(path=>this._fileSystemUISourceCodes.get(path));if(!similarFiles.length)
return Promise.resolve((null));return this._pullMetadatas(similarFiles.concat(networkSourceCode)).then(onMetadatas.bind(this));function onMetadatas(){const activeFiles=similarFiles.filter(file=>!!this._activeFoldersIndex.closestParentFolder(file.url()));const networkMetadata=networkSourceCode[Persistence.Automapping._metadata];if(!networkMetadata||(!networkMetadata.modificationTime&&typeof networkMetadata.contentSize!=='number')){if(activeFiles.length!==1)
return null;return new Persistence.AutomappingStatus(networkSourceCode,activeFiles[0],false);}
let exactMatches=this._filterWithMetadata(activeFiles,networkMetadata);if(!exactMatches.length)
exactMatches=this._filterWithMetadata(similarFiles,networkMetadata);if(exactMatches.length!==1)
return null;return new Persistence.AutomappingStatus(networkSourceCode,exactMatches[0],true);}}
_pullMetadatas(uiSourceCodes){const promises=uiSourceCodes.map(file=>fetchMetadata(file));return Promise.all(promises);function fetchMetadata(file){return file.requestMetadata().then(metadata=>file[Persistence.Automapping._metadata]=metadata);}}
_filterWithMetadata(files,networkMetadata){return files.filter(file=>{const fileMetadata=file[Persistence.Automapping._metadata];if(!fileMetadata)
return false;const timeMatches=!networkMetadata.modificationTime||Math.abs(networkMetadata.modificationTime-fileMetadata.modificationTime)<1000;const contentMatches=!networkMetadata.contentSize||fileMetadata.contentSize===networkMetadata.contentSize;return timeMatches&&contentMatches;});}
dispose(){if(this._disposed)
return;this._disposed=true;Common.EventTarget.removeEventListeners(this._eventListeners);for(const status of this._statuses.valuesArray())
this._clearNetworkStatus(status.network);}};Persistence.Automapping._status=Symbol('Automapping.Status');Persistence.Automapping._processingPromise=Symbol('Automapping.ProcessingPromise');Persistence.Automapping._metadata=Symbol('Automapping.Metadata');Persistence.Automapping.FilePathIndex=class{constructor(encoder){this._encoder=encoder;this._reversedIndex=new Common.Trie();}
addPath(path){const encodedPath=this._encoder.encode(path);this._reversedIndex.add(encodedPath.reverse());}
removePath(path){const encodedPath=this._encoder.encode(path);this._reversedIndex.remove(encodedPath.reverse());}
similarFiles(networkPath){const encodedPath=this._encoder.encode(networkPath);const longestCommonPrefix=this._reversedIndex.longestPrefix(encodedPath.reverse(),false);if(!longestCommonPrefix)
return[];return this._reversedIndex.words(longestCommonPrefix).map(encodedPath=>this._encoder.decode(encodedPath.reverse()));}};Persistence.Automapping.FolderIndex=class{constructor(encoder){this._encoder=encoder;this._index=new Common.Trie();this._folderCount=new Map();}
addFolder(path){if(path.endsWith('/'))
path=path.substring(0,path.length-1);const encodedPath=this._encoder.encode(path);this._index.add(encodedPath);const count=this._folderCount.get(encodedPath)||0;this._folderCount.set(encodedPath,count+1);return count===0;}
removeFolder(path){if(path.endsWith('/'))
path=path.substring(0,path.length-1);const encodedPath=this._encoder.encode(path);const count=this._folderCount.get(encodedPath)||0;if(!count)
return false;if(count>1){this._folderCount.set(encodedPath,count-1);return false;}
this._index.remove(encodedPath);this._folderCount.delete(encodedPath);return true;}
closestParentFolder(path){const encodedPath=this._encoder.encode(path);const commonPrefix=this._index.longestPrefix(encodedPath,true);return this._encoder.decode(commonPrefix);}};Persistence.AutomappingStatus=class{constructor(network,fileSystem,exactMatch){this.network=network;this.fileSystem=fileSystem;this.exactMatch=exactMatch;}};;Persistence.NetworkPersistenceManager=class extends Common.Object{constructor(workspace){super();this._bindingSymbol=Symbol('NetworkPersistenceBinding');this._originalResponseContentPromiseSymbol=Symbol('OriginalResponsePromise');this._savingSymbol=Symbol('SavingForOverrides');this._enabledSetting=Common.settings.moduleSetting('persistenceNetworkOverridesEnabled');this._enabledSetting.addChangeListener(this._enabledChanged,this);this._workspace=workspace;this._networkUISourceCodeForEncodedPath=new Map();this._interceptionHandlerBound=this._interceptionHandler.bind(this);this._updateInterceptionThrottler=new Common.Throttler(50);this._project=null;this._activeProject=null;this._active=false;this._enabled=false;this._workspace.addEventListener(Workspace.Workspace.Events.ProjectAdded,event=>this._onProjectAdded((event.data)));this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,event=>this._onProjectRemoved((event.data)));this._eventDescriptors=[];this._enabledChanged();}
active(){return this._active;}
project(){return this._project;}
originalContentForUISourceCode(uiSourceCode){if(!uiSourceCode[this._bindingSymbol])
return null;const fileSystemUISourceCode=uiSourceCode[this._bindingSymbol].fileSystem;return fileSystemUISourceCode[this._originalResponseContentPromiseSymbol]||null;}
_enabledChanged(){if(this._enabled===this._enabledSetting.get())
return;this._enabled=this._enabledSetting.get();if(this._enabled){this._eventDescriptors=[Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRenamed,event=>{const uiSourceCode=(event.data.uiSourceCode);this._onUISourceCodeRemoved(uiSourceCode);this._onUISourceCodeAdded(uiSourceCode);}),Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,event=>this._onUISourceCodeAdded((event.data))),Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,event=>this._onUISourceCodeRemoved((event.data))),Workspace.workspace.addEventListener(Workspace.Workspace.Events.WorkingCopyCommitted,event=>this._onUISourceCodeWorkingCopyCommitted((event.data.uiSourceCode)))];this._updateActiveProject();}else{Common.EventTarget.removeEventListeners(this._eventDescriptors);this._updateActiveProject();}}
_updateActiveProject(){const wasActive=this._active;this._active=!!(this._enabledSetting.get()&&SDK.targetManager.mainTarget()&&this._project);if(this._active===wasActive)
return;if(this._active){this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeAdded.bind(this));const networkProjects=this._workspace.projectsForType(Workspace.projectTypes.Network);for(const networkProject of networkProjects)
networkProject.uiSourceCodes().forEach(this._networkUISourceCodeAdded.bind(this));}else if(this._project){this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeRemoved.bind(this));this._networkUISourceCodeForEncodedPath.clear();}
Persistence.persistence.setAutomappingEnabled(!this._active);}
_encodedPathFromUrl(url){if(!this._active)
return'';let urlPath=Common.ParsedURL.urlWithoutHash(url.replace(/^https?:\/\//,''));if(urlPath.endsWith('/')&&urlPath.indexOf('?')===-1)
urlPath=urlPath+'index.html';let encodedPathParts=encodeUrlPathToLocalPathParts(urlPath);const projectPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(this._project.id());const encodedPath=encodedPathParts.join('/');if(projectPath.length+encodedPath.length>200){const domain=encodedPathParts[0];const encodedFileName=encodedPathParts[encodedPathParts.length-1];const shortFileName=encodedFileName?encodedFileName.substr(0,10)+'-':'';const extension=Common.ParsedURL.extractExtension(urlPath);const extensionPart=extension?'.'+extension.substr(0,10):'';encodedPathParts=[domain,'longurls',shortFileName+String.hashCode(encodedPath).toString(16)+extensionPart];}
return encodedPathParts.join('/');function encodeUrlPathToLocalPathParts(urlPath){const encodedParts=[];for(const pathPart of fileNamePartsFromUrlPath(urlPath)){if(!pathPart)
continue;let encodedName=encodeURI(pathPart).replace(/[\/:\?\*]/g,match=>'%'+match[0].charCodeAt(0).toString(16));if(Persistence.NetworkPersistenceManager._reservedFileNames.has(encodedName.toLowerCase()))
encodedName=encodedName.split('').map(char=>'%'+char.charCodeAt(0).toString(16)).join('');const lastChar=encodedName.charAt(encodedName.length-1);if(lastChar==='.')
encodedName=encodedName.substr(0,encodedName.length-1)+'%2e';encodedParts.push(encodedName);}
return encodedParts;}
function fileNamePartsFromUrlPath(urlPath){urlPath=Common.ParsedURL.urlWithoutHash(urlPath);const queryIndex=urlPath.indexOf('?');if(queryIndex===-1)
return urlPath.split('/');if(queryIndex===0)
return[urlPath];const endSection=urlPath.substr(queryIndex);const parts=urlPath.substr(0,urlPath.length-endSection.length).split('/');parts[parts.length-1]+=endSection;return parts;}}
_decodeLocalPathToUrlPath(path){try{return unescape(path);}catch(e){console.error(e);}
return path;}
_unbind(uiSourceCode){const binding=uiSourceCode[this._bindingSymbol];if(!binding)
return;delete binding.network[this._bindingSymbol];delete binding.fileSystem[this._bindingSymbol];Persistence.persistence.removeBinding(binding);}
async _bind(networkUISourceCode,fileSystemUISourceCode){if(networkUISourceCode[this._bindingSymbol])
this._unbind(networkUISourceCode);if(fileSystemUISourceCode[this._bindingSymbol])
this._unbind(fileSystemUISourceCode);const binding=new Persistence.PersistenceBinding(networkUISourceCode,fileSystemUISourceCode);networkUISourceCode[this._bindingSymbol]=binding;fileSystemUISourceCode[this._bindingSymbol]=binding;Persistence.persistence.addBinding(binding);const uiSourceCodeOfTruth=networkUISourceCode[this._savingSymbol]?networkUISourceCode:fileSystemUISourceCode;const[content,encoded]=await Promise.all([uiSourceCodeOfTruth.requestContent(),uiSourceCodeOfTruth.contentEncoded()]);Persistence.persistence.syncContent(uiSourceCodeOfTruth,content,encoded);}
_onUISourceCodeWorkingCopyCommitted(uiSourceCode){this.saveUISourceCodeForOverrides(uiSourceCode);}
canSaveUISourceCodeForOverrides(uiSourceCode){return this._active&&uiSourceCode.project().type()===Workspace.projectTypes.Network&&!uiSourceCode[this._bindingSymbol]&&!uiSourceCode[this._savingSymbol];}
async saveUISourceCodeForOverrides(uiSourceCode){if(!this.canSaveUISourceCodeForOverrides(uiSourceCode))
return;uiSourceCode[this._savingSymbol]=true;let encodedPath=this._encodedPathFromUrl(uiSourceCode.url());const content=await uiSourceCode.requestContent();const encoded=await uiSourceCode.contentEncoded();const lastIndexOfSlash=encodedPath.lastIndexOf('/');const encodedFileName=encodedPath.substr(lastIndexOfSlash+1);encodedPath=encodedPath.substr(0,lastIndexOfSlash);await this._project.createFile(encodedPath,encodedFileName,content,encoded);this._fileCreatedForTest(encodedPath,encodedFileName);uiSourceCode[this._savingSymbol]=false;}
_fileCreatedForTest(path,fileName){}
_patternForFileSystemUISourceCode(uiSourceCode){const relativePathParts=Persistence.FileSystemWorkspaceBinding.relativePath(uiSourceCode);if(relativePathParts.length<2)
return'';if(relativePathParts[1]==='longurls'&&relativePathParts.length!==2)
return'http?://'+relativePathParts[0]+'/*';return'http?://'+this._decodeLocalPathToUrlPath(relativePathParts.join('/'));}
_onUISourceCodeAdded(uiSourceCode){this._networkUISourceCodeAdded(uiSourceCode);this._filesystemUISourceCodeAdded(uiSourceCode);}
_networkUISourceCodeAdded(uiSourceCode){if(!this._active||uiSourceCode.project().type()!==Workspace.projectTypes.Network)
return;const url=Common.ParsedURL.urlWithoutHash(uiSourceCode.url());this._networkUISourceCodeForEncodedPath.set(this._encodedPathFromUrl(url),uiSourceCode);const fileSystemUISourceCode=this._project.uiSourceCodeForURL(this._project.fileSystemPath()+'/'+this._encodedPathFromUrl(url));if(!fileSystemUISourceCode)
return;this._bind(uiSourceCode,fileSystemUISourceCode);}
_filesystemUISourceCodeAdded(uiSourceCode){if(!this._active||uiSourceCode.project()!==this._project)
return;this._updateInterceptionPatterns();const relativePath=Persistence.FileSystemWorkspaceBinding.relativePath(uiSourceCode);const networkUISourceCode=this._networkUISourceCodeForEncodedPath.get(relativePath.join('/'));if(networkUISourceCode)
this._bind(networkUISourceCode,uiSourceCode);}
_updateInterceptionPatterns(){this._updateInterceptionThrottler.schedule(innerUpdateInterceptionPatterns.bind(this));function innerUpdateInterceptionPatterns(){if(!this._active)
return SDK.multitargetNetworkManager.setInterceptionHandlerForPatterns([],this._interceptionHandlerBound);const patterns=new Set();const indexFileName='index.html';for(const uiSourceCode of this._project.uiSourceCodes()){const pattern=this._patternForFileSystemUISourceCode(uiSourceCode);patterns.add(pattern);if(pattern.endsWith('/'+indexFileName))
patterns.add(pattern.substr(0,pattern.length-indexFileName.length));}
return SDK.multitargetNetworkManager.setInterceptionHandlerForPatterns(Array.from(patterns).map(pattern=>({urlPattern:pattern,interceptionStage:Protocol.Network.InterceptionStage.HeadersReceived})),this._interceptionHandlerBound);}}
_onUISourceCodeRemoved(uiSourceCode){this._networkUISourceCodeRemoved(uiSourceCode);this._filesystemUISourceCodeRemoved(uiSourceCode);}
_networkUISourceCodeRemoved(uiSourceCode){if(uiSourceCode.project().type()!==Workspace.projectTypes.Network)
return;this._unbind(uiSourceCode);this._networkUISourceCodeForEncodedPath.delete(this._encodedPathFromUrl(uiSourceCode.url()));}
_filesystemUISourceCodeRemoved(uiSourceCode){if(uiSourceCode.project()!==this._project)
return;this._updateInterceptionPatterns();delete uiSourceCode[this._originalResponseContentPromiseSymbol];this._unbind(uiSourceCode);}
_setProject(project){if(project===this._project)
return;if(this._project)
this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeRemoved.bind(this));this._project=project;if(this._project)
this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeAdded.bind(this));this._updateActiveProject();this.dispatchEventToListeners(Persistence.NetworkPersistenceManager.Events.ProjectChanged,this._project);}
_onProjectAdded(project){if(project.type()!==Workspace.projectTypes.FileSystem||Persistence.FileSystemWorkspaceBinding.fileSystemType(project)!=='overrides')
return;const fileSystemPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(project.id());if(!fileSystemPath)
return;if(this._project)
this._project.remove();this._setProject(project);}
_onProjectRemoved(project){if(project!==this._project)
return;this._setProject(null);}
async _interceptionHandler(interceptedRequest){const method=interceptedRequest.request.method;if(!this._active||(method!=='GET'&&method!=='POST'))
return;const path=this._project.fileSystemPath()+'/'+this._encodedPathFromUrl(interceptedRequest.request.url);const fileSystemUISourceCode=this._project.uiSourceCodeForURL(path);if(!fileSystemUISourceCode)
return;let mimeType='';if(interceptedRequest.responseHeaders){const responseHeaders=SDK.NetworkManager.lowercaseHeaders(interceptedRequest.responseHeaders);mimeType=responseHeaders['content-type'];}
if(!mimeType){const expectedResourceType=Common.resourceTypes[interceptedRequest.resourceType]||Common.resourceTypes.Other;mimeType=fileSystemUISourceCode.mimeType();if(Common.ResourceType.fromMimeType(mimeType)!==expectedResourceType)
mimeType=expectedResourceType.canonicalMimeType();}
const project=(fileSystemUISourceCode.project());fileSystemUISourceCode[this._originalResponseContentPromiseSymbol]=interceptedRequest.responseBody().then(response=>{if(response.error||response.content===null)
return null;return response.encoded?atob(response.content):response.content;});const blob=await project.requestFileBlob(fileSystemUISourceCode);interceptedRequest.continueRequestWithContent(new Blob([blob],{type:mimeType}));}};Persistence.NetworkPersistenceManager._reservedFileNames=new Set(['con','prn','aux','nul','com1','com2','com3','com4','com5','com6','com7','com8','com9','lpt1','lpt2','lpt3','lpt4','lpt5','lpt6','lpt7','lpt8','lpt9']);Persistence.NetworkPersistenceManager.Events={ProjectChanged:Symbol('ProjectChanged')};Persistence.networkPersistenceManager;;Persistence.Persistence=class extends Common.Object{constructor(workspace,breakpointManager){super();this._workspace=workspace;this._breakpointManager=breakpointManager;this._filePathPrefixesToBindingCount=new Map();this._subscribedBindingEventListeners=new Multimap();const linkDecorator=new Persistence.PersistenceUtils.LinkDecorator(this);Components.Linkifier.setLinkDecorator(linkDecorator);this._mapping=null;this.setAutomappingEnabled(true);}
setAutomappingEnabled(enabled){if(enabled===!!this._mapping)
return;if(!enabled){this._mapping.dispose();this._mapping=null;}else{this._mapping=new Persistence.Automapping(this._workspace,this._onStatusAdded.bind(this),this._onStatusRemoved.bind(this));}}
addBinding(binding){this._innerAddBinding(binding);}
addBindingForTest(binding){this._innerAddBinding(binding);}
removeBinding(binding){this._innerRemoveBinding(binding);}
removeBindingForTest(binding){this._innerRemoveBinding(binding);}
_innerAddBinding(binding){binding.network[Persistence.Persistence._binding]=binding;binding.fileSystem[Persistence.Persistence._binding]=binding;binding.fileSystem.forceLoadOnCheckContent();binding.network.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.fileSystem.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.network.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);binding.fileSystem.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);this._addFilePathBindingPrefixes(binding.fileSystem.url());this._moveBreakpoints(binding.fileSystem,binding.network);console.assert(!binding.fileSystem.isDirty()||!binding.network.isDirty());if(binding.fileSystem.isDirty()){this._syncWorkingCopy(binding.fileSystem);}else if(binding.network.isDirty()){this._syncWorkingCopy(binding.network);}else if(binding.network.hasCommits()&&binding.network.content()!==binding.fileSystem.content()){binding.network.setWorkingCopy(binding.network.content());this._syncWorkingCopy(binding.network);}
this._notifyBindingEvent(binding.network);this._notifyBindingEvent(binding.fileSystem);this.dispatchEventToListeners(Persistence.Persistence.Events.BindingCreated,binding);}
_innerRemoveBinding(binding){if(binding.network[Persistence.Persistence._binding]!==binding)
return;console.assert(binding.network[Persistence.Persistence._binding]===binding.fileSystem[Persistence.Persistence._binding],'ERROR: inconsistent binding for networkURL '+binding.network.url());binding.network[Persistence.Persistence._binding]=null;binding.fileSystem[Persistence.Persistence._binding]=null;binding.network.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.fileSystem.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.network.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);binding.fileSystem.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);this._removeFilePathBindingPrefixes(binding.fileSystem.url());this._breakpointManager.copyBreakpoints(binding.network.url(),binding.fileSystem);this._notifyBindingEvent(binding.network);this._notifyBindingEvent(binding.fileSystem);this.dispatchEventToListeners(Persistence.Persistence.Events.BindingRemoved,binding);}
_onStatusAdded(status){const binding=new Persistence.PersistenceBinding(status.network,status.fileSystem);status[Persistence.Persistence._binding]=binding;this._innerAddBinding(binding);}
_onStatusRemoved(status){const binding=(status[Persistence.Persistence._binding]);this._innerRemoveBinding(binding);}
_onWorkingCopyChanged(event){const uiSourceCode=(event.data);this._syncWorkingCopy(uiSourceCode);}
_syncWorkingCopy(uiSourceCode){const binding=uiSourceCode[Persistence.Persistence._binding];if(!binding||binding[Persistence.Persistence._muteWorkingCopy])
return;const other=binding.network===uiSourceCode?binding.fileSystem:binding.network;if(!uiSourceCode.isDirty()){binding[Persistence.Persistence._muteWorkingCopy]=true;other.resetWorkingCopy();binding[Persistence.Persistence._muteWorkingCopy]=false;this._contentSyncedForTest();return;}
const target=Bindings.NetworkProject.targetForUISourceCode(binding.network);if(target.type()===SDK.Target.Type.Node){const newContent=uiSourceCode.workingCopy();other.requestContent().then(()=>{const nodeJSContent=Persistence.Persistence.rewrapNodeJSContent(other,other.workingCopy(),newContent);setWorkingCopy.call(this,()=>nodeJSContent);});return;}
setWorkingCopy.call(this,()=>uiSourceCode.workingCopy());function setWorkingCopy(workingCopyGetter){binding[Persistence.Persistence._muteWorkingCopy]=true;other.setWorkingCopyGetter(workingCopyGetter);binding[Persistence.Persistence._muteWorkingCopy]=false;this._contentSyncedForTest();}}
_onWorkingCopyCommitted(event){const uiSourceCode=(event.data.uiSourceCode);const newContent=(event.data.content);this.syncContent(uiSourceCode,newContent,event.data.encoded);}
syncContent(uiSourceCode,newContent,encoded){const binding=uiSourceCode[Persistence.Persistence._binding];if(!binding||binding[Persistence.Persistence._muteCommit])
return;const other=binding.network===uiSourceCode?binding.fileSystem:binding.network;const target=Bindings.NetworkProject.targetForUISourceCode(binding.network);if(target.type()===SDK.Target.Type.Node){other.requestContent().then(currentContent=>{const nodeJSContent=Persistence.Persistence.rewrapNodeJSContent(other,currentContent,newContent);setContent.call(this,nodeJSContent);});return;}
setContent.call(this,newContent);function setContent(newContent){binding[Persistence.Persistence._muteCommit]=true;other.setContent(newContent,encoded);binding[Persistence.Persistence._muteCommit]=false;this._contentSyncedForTest();}}
static rewrapNodeJSContent(uiSourceCode,currentContent,newContent){if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem){if(newContent.startsWith(Persistence.Persistence._NodePrefix)&&newContent.endsWith(Persistence.Persistence._NodeSuffix)){newContent=newContent.substring(Persistence.Persistence._NodePrefix.length,newContent.length-Persistence.Persistence._NodeSuffix.length);}
if(currentContent.startsWith(Persistence.Persistence._NodeShebang))
newContent=Persistence.Persistence._NodeShebang+newContent;}else{if(newContent.startsWith(Persistence.Persistence._NodeShebang))
newContent=newContent.substring(Persistence.Persistence._NodeShebang.length);if(currentContent.startsWith(Persistence.Persistence._NodePrefix)&&currentContent.endsWith(Persistence.Persistence._NodeSuffix))
newContent=Persistence.Persistence._NodePrefix+newContent+Persistence.Persistence._NodeSuffix;}
return newContent;}
_contentSyncedForTest(){}
_moveBreakpoints(from,to){const breakpoints=this._breakpointManager.breakpointLocationsForUISourceCode(from).map(breakpointLocation=>breakpointLocation.breakpoint);for(const breakpoint of breakpoints){breakpoint.remove(false);this._breakpointManager.setBreakpoint(to,breakpoint.lineNumber(),breakpoint.columnNumber(),breakpoint.condition(),breakpoint.enabled());}}
hasUnsavedCommittedChanges(uiSourceCode){if(this._workspace.hasResourceContentTrackingExtensions())
return false;if(uiSourceCode.project().canSetFileContent())
return false;if(uiSourceCode[Persistence.Persistence._binding])
return false;return!!uiSourceCode.hasCommits();}
binding(uiSourceCode){return uiSourceCode[Persistence.Persistence._binding]||null;}
subscribeForBindingEvent(uiSourceCode,listener){this._subscribedBindingEventListeners.set(uiSourceCode,listener);}
unsubscribeFromBindingEvent(uiSourceCode,listener){this._subscribedBindingEventListeners.delete(uiSourceCode,listener);}
_notifyBindingEvent(uiSourceCode){if(!this._subscribedBindingEventListeners.has(uiSourceCode))
return;const listeners=Array.from(this._subscribedBindingEventListeners.get(uiSourceCode));for(const listener of listeners)
listener.call(null);}
fileSystem(uiSourceCode){const binding=this.binding(uiSourceCode);return binding?binding.fileSystem:null;}
network(uiSourceCode){const binding=this.binding(uiSourceCode);return binding?binding.network:null;}
_addFilePathBindingPrefixes(filePath){let relative='';for(const token of filePath.split('/')){relative+=token+'/';const count=this._filePathPrefixesToBindingCount.get(relative)||0;this._filePathPrefixesToBindingCount.set(relative,count+1);}}
_removeFilePathBindingPrefixes(filePath){let relative='';for(const token of filePath.split('/')){relative+=token+'/';const count=this._filePathPrefixesToBindingCount.get(relative);if(count===1)
this._filePathPrefixesToBindingCount.delete(relative);else
this._filePathPrefixesToBindingCount.set(relative,count-1);}}
filePathHasBindings(filePath){if(!filePath.endsWith('/'))
filePath+='/';return this._filePathPrefixesToBindingCount.has(filePath);}
dispose(){if(this._mapping){this._mapping.dispose();this._mapping=null;}}};Persistence.Persistence._binding=Symbol('Persistence.Binding');Persistence.Persistence._muteCommit=Symbol('Persistence.MuteCommit');Persistence.Persistence._muteWorkingCopy=Symbol('Persistence.MuteWorkingCopy');Persistence.Persistence._NodePrefix='(function (exports, require, module, __filename, __dirname) { ';Persistence.Persistence._NodeSuffix='\n});';Persistence.Persistence._NodeShebang='#!/usr/bin/env node';Persistence.Persistence.Events={BindingCreated:Symbol('BindingCreated'),BindingRemoved:Symbol('BindingRemoved')};Persistence.PathEncoder=class{constructor(){this._encoder=new Common.CharacterIdMap();}
encode(path){return path.split('/').map(token=>this._encoder.toChar(token)).join('');}
decode(path){return path.split('').map(token=>this._encoder.fromChar(token)).join('/');}};Persistence.PersistenceBinding=class{constructor(network,fileSystem){this.network=network;this.fileSystem=fileSystem;}};Persistence.MappingSystem=function(){};Persistence.MappingSystem.prototype={dispose:function(){}};Persistence.persistence;;Persistence.PersistenceActions={};Persistence.PersistenceActions.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){const contentProvider=(target);async function saveAs(){if(contentProvider instanceof Workspace.UISourceCode)
(contentProvider).commitWorkingCopy();let content=await contentProvider.requestContent();if(await contentProvider.contentEncoded())
content=window.atob(content);const url=contentProvider.contentURL();Workspace.fileManager.save(url,(content),true);Workspace.fileManager.close(url);}
if(contentProvider.contentType().isDocumentOrScriptOrStyleSheet())
contextMenu.saveSection().appendItem(Common.UIString('Save as...'),saveAs);const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(contentProvider.contentURL());if(uiSourceCode&&Persistence.networkPersistenceManager.canSaveUISourceCodeForOverrides(uiSourceCode)){contextMenu.saveSection().appendItem(Common.UIString('Save for overrides'),()=>{uiSourceCode.commitWorkingCopy();Persistence.networkPersistenceManager.saveUISourceCodeForOverrides((uiSourceCode));Common.Revealer.reveal(uiSourceCode);});}
const binding=uiSourceCode&&Persistence.persistence.binding(uiSourceCode);const fileURL=binding?binding.fileSystem.contentURL():contentProvider.contentURL();if(fileURL.startsWith('file://')){const path=Common.ParsedURL.urlToPlatformPath(fileURL,Host.isWin());contextMenu.revealSection().appendItem(Common.UIString('Open in containing folder'),()=>InspectorFrontendHost.showItemInFolder(path));}}};;Persistence.PersistenceUtils=class{static tooltipForUISourceCode(uiSourceCode){const binding=Persistence.persistence.binding(uiSourceCode);if(!binding)
return'';if(uiSourceCode===binding.network)
return Persistence.FileSystemWorkspaceBinding.tooltipForUISourceCode(binding.fileSystem);if(binding.network.contentType().isFromSourceMap())
return Common.UIString('Linked to source map: %s',binding.network.url().trimMiddle(150));return Common.UIString('Linked to %s',binding.network.url().trimMiddle(150));}
static iconForUISourceCode(uiSourceCode){const binding=Persistence.persistence.binding(uiSourceCode);if(binding){if(!binding.fileSystem.url().startsWith('file://'))
return null;const icon=UI.Icon.create('mediumicon-file-sync');icon.title=Persistence.PersistenceUtils.tooltipForUISourceCode(binding.network);if(Persistence.networkPersistenceManager.project()===binding.fileSystem.project())
icon.style.filter='hue-rotate(160deg)';return icon;}
if(uiSourceCode.project().type()!==Workspace.projectTypes.FileSystem||!uiSourceCode.url().startsWith('file://'))
return null;const icon=UI.Icon.create('mediumicon-file');icon.title=Persistence.PersistenceUtils.tooltipForUISourceCode(uiSourceCode);return icon;}};Persistence.PersistenceUtils.LinkDecorator=class extends Common.Object{constructor(persistence){super();persistence.addEventListener(Persistence.Persistence.Events.BindingCreated,this._bindingChanged,this);persistence.addEventListener(Persistence.Persistence.Events.BindingRemoved,this._bindingChanged,this);}
_bindingChanged(event){const binding=(event.data);this.dispatchEventToListeners(Components.LinkDecorator.Events.LinkIconChanged,binding.network);}
linkIcon(uiSourceCode){return Persistence.PersistenceUtils.iconForUISourceCode(uiSourceCode);}};;Persistence.EditFileSystemView=class extends UI.VBox{constructor(fileSystemPath){super(true);this.registerRequiredCSS('persistence/editFileSystemView.css');this._fileSystemPath=fileSystemPath;this._eventListeners=[Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderAdded,this._update,this),Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderRemoved,this._update,this)];const excludedFoldersHeader=this.contentElement.createChild('div','file-system-header');excludedFoldersHeader.createChild('div','file-system-header-text').textContent=Common.UIString('Excluded folders');excludedFoldersHeader.appendChild(UI.createTextButton(Common.UIString('Add'),this._addExcludedFolderButtonClicked.bind(this),'add-button'));this._excludedFoldersList=new UI.ListWidget(this);this._excludedFoldersList.element.classList.add('file-system-list');this._excludedFoldersList.registerRequiredCSS('persistence/editFileSystemView.css');const excludedFoldersPlaceholder=createElementWithClass('div','file-system-list-empty');excludedFoldersPlaceholder.textContent=Common.UIString('None');this._excludedFoldersList.setEmptyPlaceholder(excludedFoldersPlaceholder);this._excludedFoldersList.show(this.contentElement);this.contentElement.tabIndex=0;this._update();}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);}
_update(){if(this._muteUpdate)
return;this._excludedFoldersList.clear();this._excludedFolders=[];for(const folder of Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).excludedFolders().values()){this._excludedFolders.push(folder);this._excludedFoldersList.appendItem(folder,true);}}
_addExcludedFolderButtonClicked(){this._excludedFoldersList.addNewItem(0,'');}
renderItem(item,editable){const element=createElementWithClass('div','file-system-list-item');const pathPrefix=(editable?item:Common.UIString('%s (via .devtools)',item));const pathPrefixElement=element.createChild('div','file-system-value');pathPrefixElement.textContent=pathPrefix;pathPrefixElement.title=pathPrefix;return element;}
removeItemRequested(item,index){Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).removeExcludedFolder(this._excludedFolders[index]);}
commitEdit(item,editor,isNew){this._muteUpdate=true;if(!isNew){Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).removeExcludedFolder((item));}
Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).addExcludedFolder(this._normalizePrefix(editor.control('pathPrefix').value));this._muteUpdate=false;this._update();}
beginEdit(item){const editor=this._createExcludedFolderEditor();editor.control('pathPrefix').value=item;return editor;}
_createExcludedFolderEditor(){if(this._excludedFolderEditor)
return this._excludedFolderEditor;const editor=new UI.ListWidget.Editor();this._excludedFolderEditor=editor;const content=editor.contentElement();const titles=content.createChild('div','file-system-edit-row');titles.createChild('div','file-system-value').textContent=Common.UIString('Folder path');const fields=content.createChild('div','file-system-edit-row');fields.createChild('div','file-system-value').appendChild(editor.createInput('pathPrefix','text','/path/to/folder/',pathPrefixValidator.bind(this)));return editor;function pathPrefixValidator(item,index,input){const prefix=this._normalizePrefix(input.value);const configurableCount=Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).excludedFolders().size;for(let i=0;i<configurableCount;++i){if(i!==index&&this._excludedFolders[i]===prefix)
return false;}
return!!prefix;}}
_normalizePrefix(prefix){if(!prefix)
return'';return prefix+(prefix[prefix.length-1]==='/'?'':'/');}};;Persistence.WorkspaceSettingsTab=class extends UI.VBox{constructor(){super();this.registerRequiredCSS('persistence/workspaceSettingsTab.css');const header=this.element.createChild('header');header.createChild('h3').createTextChild(Common.UIString('Workspace'));this.containerElement=this.element.createChild('div','settings-container-wrapper').createChild('div','settings-tab settings-content settings-container');Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,event=>this._fileSystemAdded((event.data)),this);Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,event=>this._fileSystemRemoved((event.data)),this);const folderExcludePatternInput=this._createFolderExcludePatternInput();folderExcludePatternInput.classList.add('folder-exclude-pattern');this.containerElement.appendChild(folderExcludePatternInput);const div=this.containerElement.createChild('div','settings-info-message');div.createTextChild(Common.UIString('Mappings are inferred automatically.'));this._fileSystemsListContainer=this.containerElement.createChild('div','');const addButton=UI.createTextButton(ls`Add folder\u2026`,this._addFileSystemClicked.bind(this));this.containerElement.appendChild(addButton);this.setDefaultFocusedElement(addButton);this._elementByPath=new Map();this._mappingViewByPath=new Map();const fileSystems=Persistence.isolatedFileSystemManager.fileSystems();for(let i=0;i<fileSystems.length;++i)
this._addItem(fileSystems[i]);}
_createFolderExcludePatternInput(){const p=createElement('p');const labelElement=p.createChild('label');labelElement.textContent=Common.UIString('Folder exclude pattern');const inputElement=UI.createInput('','text');p.appendChild(inputElement);inputElement.style.width='270px';const folderExcludeSetting=Persistence.isolatedFileSystemManager.workspaceFolderExcludePatternSetting();const setValue=UI.bindInput(inputElement,folderExcludeSetting.set.bind(folderExcludeSetting),regexValidator,false);folderExcludeSetting.addChangeListener(()=>setValue.call(null,folderExcludeSetting.get()));setValue(folderExcludeSetting.get());return p;function regexValidator(value){let regex;try{regex=new RegExp(value);}catch(e){}
return!!regex;}}
_addItem(fileSystem){if(!(fileSystem instanceof Persistence.IsolatedFileSystem))
return;const networkPersistenceProject=Persistence.networkPersistenceManager.project();if(networkPersistenceProject&&Persistence.isolatedFileSystemManager.fileSystem(networkPersistenceProject.fileSystemPath())===fileSystem)
return;const element=this._renderFileSystem(fileSystem);this._elementByPath.set(fileSystem.path(),element);this._fileSystemsListContainer.appendChild(element);const mappingView=new Persistence.EditFileSystemView(fileSystem.path());this._mappingViewByPath.set(fileSystem.path(),mappingView);mappingView.element.classList.add('file-system-mapping-view');mappingView.show(element);}
_renderFileSystem(fileSystem){const fileSystemPath=fileSystem.path();const lastIndexOfSlash=fileSystemPath.lastIndexOf(Host.isWin()?'\\':'/');const folderName=fileSystemPath.substr(lastIndexOfSlash+1);const element=createElementWithClass('div','file-system-container');const header=element.createChild('div','file-system-header');header.createChild('div','file-system-name').textContent=folderName;const path=header.createChild('div','file-system-path');path.textContent=fileSystemPath;path.title=fileSystemPath;const toolbar=new UI.Toolbar('');const button=new UI.ToolbarButton(Common.UIString('Remove'),'largeicon-delete');button.addEventListener(UI.ToolbarButton.Events.Click,this._removeFileSystemClicked.bind(this,fileSystem));toolbar.appendToolbarItem(button);header.appendChild(toolbar.element);return element;}
_removeFileSystemClicked(fileSystem){Persistence.isolatedFileSystemManager.removeFileSystem(fileSystem);}
_addFileSystemClicked(){Persistence.isolatedFileSystemManager.addFileSystem();}
_fileSystemAdded(fileSystem){this._addItem(fileSystem);}
_fileSystemRemoved(fileSystem){const mappingView=this._mappingViewByPath.get(fileSystem.path());if(mappingView){mappingView.dispose();this._mappingViewByPath.delete(fileSystem.path());}
const element=this._elementByPath.get(fileSystem.path());if(element){this._elementByPath.delete(fileSystem.path());element.remove();}}};;self['BrowserSDK']=self['BrowserSDK']||{};BrowserSDK.LogManager=class{constructor(){SDK.targetManager.observeModels(SDK.LogModel,this);}
modelAdded(logModel){const eventListeners=[];eventListeners.push(logModel.addEventListener(SDK.LogModel.Events.EntryAdded,this._logEntryAdded,this));logModel[BrowserSDK.LogManager._eventSymbol]=eventListeners;}
modelRemoved(logModel){Common.EventTarget.removeEventListeners(logModel[BrowserSDK.LogManager._eventSymbol]);}
_logEntryAdded(event){const data=(event.data);const target=data.logModel.target();const consoleMessage=new SDK.ConsoleMessage(target.model(SDK.RuntimeModel),data.entry.source,data.entry.level,data.entry.text,undefined,data.entry.url,data.entry.lineNumber,undefined,[data.entry.text,...(data.entry.args||[])],data.entry.stackTrace,data.entry.timestamp,undefined,undefined,data.entry.workerId);if(data.entry.networkRequestId)
SDK.networkLog.associateConsoleMessageWithRequest(consoleMessage,data.entry.networkRequestId);if(consoleMessage.source===SDK.ConsoleMessage.MessageSource.Worker){const workerId=consoleMessage.workerId||'';if(SDK.targetManager.targetById(workerId))
return;setTimeout(()=>{if(!SDK.targetManager.targetById(workerId))
SDK.consoleModel.addMessage(consoleMessage);},1000);}else{SDK.consoleModel.addMessage(consoleMessage);}}};BrowserSDK.LogManager._eventSymbol=Symbol('_events');new BrowserSDK.LogManager();;self['Extensions']=self['Extensions']||{};function defineCommonExtensionSymbols(apiPrivate){if(!apiPrivate.panels)
apiPrivate.panels={};apiPrivate.panels.SearchAction={CancelSearch:'cancelSearch',PerformSearch:'performSearch',NextSearchResult:'nextSearchResult',PreviousSearchResult:'previousSearchResult'};apiPrivate.Events={ButtonClicked:'button-clicked-',PanelObjectSelected:'panel-objectSelected-',NetworkRequestFinished:'network-request-finished',OpenResource:'open-resource',PanelSearch:'panel-search-',RecordingStarted:'trace-recording-started-',RecordingStopped:'trace-recording-stopped-',ResourceAdded:'resource-added',ResourceContentCommitted:'resource-content-committed',ViewShown:'view-shown-',ViewHidden:'view-hidden-'};apiPrivate.Commands={AddRequestHeaders:'addRequestHeaders',AddTraceProvider:'addTraceProvider',ApplyStyleSheet:'applyStyleSheet',CompleteTraceSession:'completeTraceSession',CreatePanel:'createPanel',CreateSidebarPane:'createSidebarPane',CreateToolbarButton:'createToolbarButton',EvaluateOnInspectedPage:'evaluateOnInspectedPage',ForwardKeyboardEvent:'_forwardKeyboardEvent',GetHAR:'getHAR',GetPageResources:'getPageResources',GetRequestContent:'getRequestContent',GetResourceContent:'getResourceContent',InspectedURLChanged:'inspectedURLChanged',OpenResource:'openResource',Reload:'Reload',Subscribe:'subscribe',SetOpenResourceHandler:'setOpenResourceHandler',SetResourceContent:'setResourceContent',SetSidebarContent:'setSidebarContent',SetSidebarHeight:'setSidebarHeight',SetSidebarPage:'setSidebarPage',ShowPanel:'showPanel',Unsubscribe:'unsubscribe',UpdateButton:'updateButton'};}
function injectedExtensionAPI(extensionInfo,inspectedTabId,themeName,keysToForward,testHook,injectedScriptId){const keysToForwardSet=new Set(keysToForward);const chrome=window.chrome||{};const devtools_descriptor=Object.getOwnPropertyDescriptor(chrome,'devtools');if(devtools_descriptor)
return;const apiPrivate={};defineCommonExtensionSymbols(apiPrivate);const commands=apiPrivate.Commands;const events=apiPrivate.Events;let userAction=false;function EventSinkImpl(type,customDispatch){this._type=type;this._listeners=[];this._customDispatch=customDispatch;}
EventSinkImpl.prototype={addListener:function(callback){if(typeof callback!=='function')
throw'addListener: callback is not a function';if(this._listeners.length===0)
extensionServer.sendRequest({command:commands.Subscribe,type:this._type});this._listeners.push(callback);extensionServer.registerHandler('notify-'+this._type,this._dispatch.bind(this));},removeListener:function(callback){const listeners=this._listeners;for(let i=0;i<listeners.length;++i){if(listeners[i]===callback){listeners.splice(i,1);break;}}
if(this._listeners.length===0)
extensionServer.sendRequest({command:commands.Unsubscribe,type:this._type});},_fire:function(vararg){const listeners=this._listeners.slice();for(let i=0;i<listeners.length;++i)
listeners[i].apply(null,arguments);},_dispatch:function(request){if(this._customDispatch)
this._customDispatch.call(this,request);else
this._fire.apply(this,request.arguments);}};function InspectorExtensionAPI(){this.inspectedWindow=new InspectedWindow();this.panels=new Panels();this.network=new Network();this.timeline=new Timeline();defineDeprecatedProperty(this,'webInspector','resources','network');}
function Network(){function dispatchRequestEvent(message){const request=message.arguments[1];request.__proto__=new Request(message.arguments[0]);this._fire(request);}
this.onRequestFinished=new EventSink(events.NetworkRequestFinished,dispatchRequestEvent);defineDeprecatedProperty(this,'network','onFinished','onRequestFinished');this.onNavigated=new EventSink(events.InspectedURLChanged);}
Network.prototype={getHAR:function(callback){function callbackWrapper(result){const entries=(result&&result.entries)||[];for(let i=0;i<entries.length;++i){entries[i].__proto__=new Request(entries[i]._requestId);delete entries[i]._requestId;}
callback(result);}
extensionServer.sendRequest({command:commands.GetHAR},callback&&callbackWrapper);},addRequestHeaders:function(headers){extensionServer.sendRequest({command:commands.AddRequestHeaders,headers:headers,extensionId:window.location.hostname});}};function RequestImpl(id){this._id=id;}
RequestImpl.prototype={getContent:function(callback){function callbackWrapper(response){callback(response.content,response.encoding);}
extensionServer.sendRequest({command:commands.GetRequestContent,id:this._id},callback&&callbackWrapper);}};function Panels(){const panels={elements:new ElementsPanel(),sources:new SourcesPanel(),};function panelGetter(name){return panels[name];}
for(const panel in panels)
this.__defineGetter__(panel,panelGetter.bind(null,panel));this.applyStyleSheet=function(styleSheet){extensionServer.sendRequest({command:commands.ApplyStyleSheet,styleSheet:styleSheet});};}
Panels.prototype={create:function(title,icon,page,callback){const id='extension-panel-'+extensionServer.nextObjectId();const request={command:commands.CreatePanel,id:id,title:title,icon:icon,page:page};extensionServer.sendRequest(request,callback&&callback.bind(this,new ExtensionPanel(id)));},setOpenResourceHandler:function(callback){const hadHandler=extensionServer.hasHandler(events.OpenResource);function callbackWrapper(message){userAction=true;try{callback.call(null,new Resource(message.resource),message.lineNumber);}finally{userAction=false;}}
if(!callback)
extensionServer.unregisterHandler(events.OpenResource);else
extensionServer.registerHandler(events.OpenResource,callbackWrapper);if(hadHandler===!callback)
extensionServer.sendRequest({command:commands.SetOpenResourceHandler,'handlerPresent':!!callback});},openResource:function(url,lineNumber,callback){extensionServer.sendRequest({command:commands.OpenResource,'url':url,'lineNumber':lineNumber},callback);},get SearchAction(){return apiPrivate.panels.SearchAction;}};function ExtensionViewImpl(id){this._id=id;function dispatchShowEvent(message){const frameIndex=message.arguments[0];if(typeof frameIndex==='number')
this._fire(window.parent.frames[frameIndex]);else
this._fire();}
if(id){this.onShown=new EventSink(events.ViewShown+id,dispatchShowEvent);this.onHidden=new EventSink(events.ViewHidden+id);}}
function PanelWithSidebarImpl(hostPanelName){ExtensionViewImpl.call(this,null);this._hostPanelName=hostPanelName;this.onSelectionChanged=new EventSink(events.PanelObjectSelected+hostPanelName);}
PanelWithSidebarImpl.prototype={createSidebarPane:function(title,callback){const id='extension-sidebar-'+extensionServer.nextObjectId();const request={command:commands.CreateSidebarPane,panel:this._hostPanelName,id:id,title:title};function callbackWrapper(){callback(new ExtensionSidebarPane(id));}
extensionServer.sendRequest(request,callback&&callbackWrapper);},__proto__:ExtensionViewImpl.prototype};function declareInterfaceClass(implConstructor){return function(){const impl={__proto__:implConstructor.prototype};implConstructor.apply(impl,arguments);populateInterfaceClass(this,impl);};}
function defineDeprecatedProperty(object,className,oldName,newName){let warningGiven=false;function getter(){if(!warningGiven){console.warn(className+'.'+oldName+' is deprecated. Use '+className+'.'+newName+' instead');warningGiven=true;}
return object[newName];}
object.__defineGetter__(oldName,getter);}
function extractCallbackArgument(args){const lastArgument=args[args.length-1];return typeof lastArgument==='function'?lastArgument:undefined;}
const Button=declareInterfaceClass(ButtonImpl);const EventSink=declareInterfaceClass(EventSinkImpl);const ExtensionPanel=declareInterfaceClass(ExtensionPanelImpl);const ExtensionSidebarPane=declareInterfaceClass(ExtensionSidebarPaneImpl);const PanelWithSidebar=declareInterfaceClass(PanelWithSidebarImpl);const Request=declareInterfaceClass(RequestImpl);const Resource=declareInterfaceClass(ResourceImpl);const TraceSession=declareInterfaceClass(TraceSessionImpl);function ElementsPanel(){PanelWithSidebar.call(this,'elements');}
ElementsPanel.prototype={__proto__:PanelWithSidebar.prototype};function SourcesPanel(){PanelWithSidebar.call(this,'sources');}
SourcesPanel.prototype={__proto__:PanelWithSidebar.prototype};function ExtensionPanelImpl(id){ExtensionViewImpl.call(this,id);this.onSearch=new EventSink(events.PanelSearch+id);}
ExtensionPanelImpl.prototype={createStatusBarButton:function(iconPath,tooltipText,disabled){const id='button-'+extensionServer.nextObjectId();const request={command:commands.CreateToolbarButton,panel:this._id,id:id,icon:iconPath,tooltip:tooltipText,disabled:!!disabled};extensionServer.sendRequest(request);return new Button(id);},show:function(){if(!userAction)
return;const request={command:commands.ShowPanel,id:this._id};extensionServer.sendRequest(request);},__proto__:ExtensionViewImpl.prototype};function ExtensionSidebarPaneImpl(id){ExtensionViewImpl.call(this,id);}
ExtensionSidebarPaneImpl.prototype={setHeight:function(height){extensionServer.sendRequest({command:commands.SetSidebarHeight,id:this._id,height:height});},setExpression:function(expression,rootTitle,evaluateOptions){const request={command:commands.SetSidebarContent,id:this._id,expression:expression,rootTitle:rootTitle,evaluateOnPage:true,};if(typeof evaluateOptions==='object')
request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,extractCallbackArgument(arguments));},setObject:function(jsonObject,rootTitle,callback){extensionServer.sendRequest({command:commands.SetSidebarContent,id:this._id,expression:jsonObject,rootTitle:rootTitle},callback);},setPage:function(page){extensionServer.sendRequest({command:commands.SetSidebarPage,id:this._id,page:page});},__proto__:ExtensionViewImpl.prototype};function ButtonImpl(id){this._id=id;this.onClicked=new EventSink(events.ButtonClicked+id);}
ButtonImpl.prototype={update:function(iconPath,tooltipText,disabled){const request={command:commands.UpdateButton,id:this._id,icon:iconPath,tooltip:tooltipText,disabled:!!disabled};extensionServer.sendRequest(request);}};function Timeline(){}
Timeline.prototype={addTraceProvider:function(categoryName,categoryTooltip){const id='extension-trace-provider-'+extensionServer.nextObjectId();extensionServer.sendRequest({command:commands.AddTraceProvider,id:id,categoryName:categoryName,categoryTooltip:categoryTooltip});return new TraceProvider(id);}};function TraceSessionImpl(id){this._id=id;}
TraceSessionImpl.prototype={complete:function(url,timeOffset){const request={command:commands.CompleteTraceSession,id:this._id,url:url||'',timeOffset:timeOffset||0};extensionServer.sendRequest(request);}};function TraceProvider(id){function dispatchRecordingStarted(message){const sessionId=message.arguments[0];this._fire(new TraceSession(sessionId));}
this.onRecordingStarted=new EventSink(events.RecordingStarted+id,dispatchRecordingStarted);this.onRecordingStopped=new EventSink(events.RecordingStopped+id);}
function InspectedWindow(){function dispatchResourceEvent(message){this._fire(new Resource(message.arguments[0]));}
function dispatchResourceContentEvent(message){this._fire(new Resource(message.arguments[0]),message.arguments[1]);}
this.onResourceAdded=new EventSink(events.ResourceAdded,dispatchResourceEvent);this.onResourceContentCommitted=new EventSink(events.ResourceContentCommitted,dispatchResourceContentEvent);}
InspectedWindow.prototype={reload:function(optionsOrUserAgent){let options=null;if(typeof optionsOrUserAgent==='object'){options=optionsOrUserAgent;}else if(typeof optionsOrUserAgent==='string'){options={userAgent:optionsOrUserAgent};console.warn('Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. '+'Use inspectedWindow.reload({ userAgent: value}) instead.');}
extensionServer.sendRequest({command:commands.Reload,options:options});},eval:function(expression,evaluateOptions){const callback=extractCallbackArgument(arguments);function callbackWrapper(result){if(result.isError||result.isException)
callback(undefined,result);else
callback(result.value);}
const request={command:commands.EvaluateOnInspectedPage,expression:expression};if(typeof evaluateOptions==='object')
request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,callback&&callbackWrapper);return null;},getResources:function(callback){function wrapResource(resourceData){return new Resource(resourceData);}
function callbackWrapper(resources){callback(resources.map(wrapResource));}
extensionServer.sendRequest({command:commands.GetPageResources},callback&&callbackWrapper);}};function ResourceImpl(resourceData){this._url=resourceData.url;this._type=resourceData.type;}
ResourceImpl.prototype={get url(){return this._url;},get type(){return this._type;},getContent:function(callback){function callbackWrapper(response){callback(response.content,response.encoding);}
extensionServer.sendRequest({command:commands.GetResourceContent,url:this._url},callback&&callbackWrapper);},setContent:function(content,commit,callback){extensionServer.sendRequest({command:commands.SetResourceContent,url:this._url,content:content,commit:commit},callback);}};function getTabId(){return inspectedTabId;}
let keyboardEventRequestQueue=[];let forwardTimer=null;function forwardKeyboardEvent(event){let modifiers=0;if(event.shiftKey)
modifiers|=1;if(event.ctrlKey)
modifiers|=2;if(event.altKey)
modifiers|=4;if(event.metaKey)
modifiers|=8;const num=(event.keyCode&255)|(modifiers<<8);if(!keysToForwardSet.has(num))
return;event.preventDefault();const requestPayload={eventType:event.type,ctrlKey:event.ctrlKey,altKey:event.altKey,metaKey:event.metaKey,shiftKey:event.shiftKey,keyIdentifier:event.keyIdentifier,key:event.key,code:event.code,location:event.location,keyCode:event.keyCode};keyboardEventRequestQueue.push(requestPayload);if(!forwardTimer)
forwardTimer=setTimeout(forwardEventQueue,0);}
function forwardEventQueue(){forwardTimer=null;const request={command:commands.ForwardKeyboardEvent,entries:keyboardEventRequestQueue};extensionServer.sendRequest(request);keyboardEventRequestQueue=[];}
document.addEventListener('keydown',forwardKeyboardEvent,false);function ExtensionServerClient(){this._callbacks={};this._handlers={};this._lastRequestId=0;this._lastObjectId=0;this.registerHandler('callback',this._onCallback.bind(this));const channel=new MessageChannel();this._port=channel.port1;this._port.addEventListener('message',this._onMessage.bind(this),false);this._port.start();window.parent.postMessage('registerExtension','*',[channel.port2]);}
ExtensionServerClient.prototype={sendRequest:function(message,callback){if(typeof callback==='function')
message.requestId=this._registerCallback(callback);this._port.postMessage(message);},hasHandler:function(command){return!!this._handlers[command];},registerHandler:function(command,handler){this._handlers[command]=handler;},unregisterHandler:function(command){delete this._handlers[command];},nextObjectId:function(){return injectedScriptId.toString()+'_'+ ++this._lastObjectId;},_registerCallback:function(callback){const id=++this._lastRequestId;this._callbacks[id]=callback;return id;},_onCallback:function(request){if(request.requestId in this._callbacks){const callback=this._callbacks[request.requestId];delete this._callbacks[request.requestId];callback(request.result);}},_onMessage:function(event){const request=event.data;const handler=this._handlers[request.command];if(handler)
handler.call(this,request);}};function populateInterfaceClass(interfaze,implementation){for(const member in implementation){if(member.charAt(0)==='_')
continue;let descriptor=null;for(let owner=implementation;owner&&!descriptor;owner=owner.__proto__)
descriptor=Object.getOwnPropertyDescriptor(owner,member);if(!descriptor)
continue;if(typeof descriptor.value==='function')
interfaze[member]=descriptor.value.bind(implementation);else if(typeof descriptor.get==='function')
interfaze.__defineGetter__(member,descriptor.get.bind(implementation));else
Object.defineProperty(interfaze,member,descriptor);}}
const extensionServer=new ExtensionServerClient();const coreAPI=new InspectorExtensionAPI();Object.defineProperty(chrome,'devtools',{value:{},enumerable:true});chrome.devtools.inspectedWindow={};chrome.devtools.inspectedWindow.__defineGetter__('tabId',getTabId);chrome.devtools.inspectedWindow.__proto__=coreAPI.inspectedWindow;chrome.devtools.network=coreAPI.network;chrome.devtools.panels=coreAPI.panels;chrome.devtools.panels.themeName=themeName;if(extensionInfo.exposeExperimentalAPIs!==false){chrome.experimental=chrome.experimental||{};chrome.experimental.devtools=chrome.experimental.devtools||{};const properties=Object.getOwnPropertyNames(coreAPI);for(let i=0;i<properties.length;++i){const descriptor=Object.getOwnPropertyDescriptor(coreAPI,properties[i]);if(descriptor)
Object.defineProperty(chrome.experimental.devtools,properties[i],descriptor);}
chrome.experimental.devtools.inspectedWindow=chrome.devtools.inspectedWindow;}
if(extensionInfo.exposeWebInspectorNamespace)
window.webInspector=coreAPI;testHook(extensionServer,coreAPI);}
function buildExtensionAPIInjectedScript(extensionInfo,inspectedTabId,themeName,keysToForward,testHook){const argumentsJSON=[extensionInfo,inspectedTabId||null,themeName,keysToForward].map(_=>JSON.stringify(_)).join(',');if(!testHook)
testHook=()=>{};return'(function(injectedScriptId){ '+defineCommonExtensionSymbols.toString()+';'+'('+injectedExtensionAPI.toString()+')('+argumentsJSON+','+testHook+', injectedScriptId);'+'})';};if(!window.InspectorExtensionRegistry){Extensions.InspectorExtensionRegistryStub=class{getExtensionsAsync(){}};self.InspectorExtensionRegistry=new Extensions.InspectorExtensionRegistryStub();};Extensions.ExtensionTraceProvider=class{constructor(extensionOrigin,id,categoryName,categoryTooltip){this._extensionOrigin=extensionOrigin;this._id=id;this._categoryName=categoryName;this._categoryTooltip=categoryTooltip;}
start(session){const sessionId=String(++Extensions.ExtensionTraceProvider._lastSessionId);Extensions.extensionServer.startTraceRecording(this._id,sessionId,session);}
stop(){Extensions.extensionServer.stopTraceRecording(this._id);}
shortDisplayName(){return this._categoryName;}
longDisplayName(){return this._categoryTooltip;}
persistentIdentifier(){return`${this._extensionOrigin}/${this._categoryName}`;}};Extensions.ExtensionTraceProvider._lastSessionId=0;Extensions.TracingSession=function(){};Extensions.TracingSession.prototype={complete:function(url,timeOffsetMicroseconds){}};;Extensions.ExtensionServer=class extends Common.Object{constructor(){super();this._clientObjects={};this._handlers={};this._subscribers={};this._subscriptionStartHandlers={};this._subscriptionStopHandlers={};this._extraHeaders={};this._requests={};this._lastRequestId=0;this._registeredExtensions={};this._status=new Extensions.ExtensionStatus();this._sidebarPanes=[];this._traceProviders=[];this._traceSessions=new Map();const commands=Extensions.extensionAPI.Commands;this._registerHandler(commands.AddRequestHeaders,this._onAddRequestHeaders.bind(this));this._registerHandler(commands.AddTraceProvider,this._onAddTraceProvider.bind(this));this._registerHandler(commands.ApplyStyleSheet,this._onApplyStyleSheet.bind(this));this._registerHandler(commands.CompleteTraceSession,this._onCompleteTraceSession.bind(this));this._registerHandler(commands.CreatePanel,this._onCreatePanel.bind(this));this._registerHandler(commands.CreateSidebarPane,this._onCreateSidebarPane.bind(this));this._registerHandler(commands.CreateToolbarButton,this._onCreateToolbarButton.bind(this));this._registerHandler(commands.EvaluateOnInspectedPage,this._onEvaluateOnInspectedPage.bind(this));this._registerHandler(commands.ForwardKeyboardEvent,this._onForwardKeyboardEvent.bind(this));this._registerHandler(commands.GetHAR,this._onGetHAR.bind(this));this._registerHandler(commands.GetPageResources,this._onGetPageResources.bind(this));this._registerHandler(commands.GetRequestContent,this._onGetRequestContent.bind(this));this._registerHandler(commands.GetResourceContent,this._onGetResourceContent.bind(this));this._registerHandler(commands.Reload,this._onReload.bind(this));this._registerHandler(commands.SetOpenResourceHandler,this._onSetOpenResourceHandler.bind(this));this._registerHandler(commands.SetResourceContent,this._onSetResourceContent.bind(this));this._registerHandler(commands.SetSidebarHeight,this._onSetSidebarHeight.bind(this));this._registerHandler(commands.SetSidebarContent,this._onSetSidebarContent.bind(this));this._registerHandler(commands.SetSidebarPage,this._onSetSidebarPage.bind(this));this._registerHandler(commands.ShowPanel,this._onShowPanel.bind(this));this._registerHandler(commands.Subscribe,this._onSubscribe.bind(this));this._registerHandler(commands.OpenResource,this._onOpenResource.bind(this));this._registerHandler(commands.Unsubscribe,this._onUnsubscribe.bind(this));this._registerHandler(commands.UpdateButton,this._onUpdateButton.bind(this));window.addEventListener('message',this._onWindowMessage.bind(this),false);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.AddExtensions,this._addExtensions,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetInspectedTabId,this._setInspectedTabId,this);this._initExtensions();}
initializeExtensions(){this._initializeCommandIssued=true;if(this._pendingExtensionInfos){this._pendingExtensionInfos.forEach(this._addExtension,this);delete this._pendingExtensionInfos;}}
hasExtensions(){return!!Object.keys(this._registeredExtensions).length;}
notifySearchAction(panelId,action,searchString){this._postNotification(Extensions.extensionAPI.Events.PanelSearch+panelId,action,searchString);}
notifyViewShown(identifier,frameIndex){this._postNotification(Extensions.extensionAPI.Events.ViewShown+identifier,frameIndex);}
notifyViewHidden(identifier){this._postNotification(Extensions.extensionAPI.Events.ViewHidden+identifier);}
notifyButtonClicked(identifier){this._postNotification(Extensions.extensionAPI.Events.ButtonClicked+identifier);}
_inspectedURLChanged(event){if(event.data!==SDK.targetManager.mainTarget())
return;this._requests={};const url=event.data.inspectedURL();this._postNotification(Extensions.extensionAPI.Events.InspectedURLChanged,url);}
startTraceRecording(providerId,sessionId,session){this._traceSessions.set(sessionId,session);this._postNotification('trace-recording-started-'+providerId,sessionId);}
stopTraceRecording(providerId){this._postNotification('trace-recording-stopped-'+providerId);}
hasSubscribers(type){return!!this._subscribers[type];}
_postNotification(type,vararg){const subscribers=this._subscribers[type];if(!subscribers)
return;const message={command:'notify-'+type,arguments:Array.prototype.slice.call(arguments,1)};for(let i=0;i<subscribers.length;++i)
subscribers[i].postMessage(message);}
_onSubscribe(message,port){const subscribers=this._subscribers[message.type];if(subscribers){subscribers.push(port);}else{this._subscribers[message.type]=[port];if(this._subscriptionStartHandlers[message.type])
this._subscriptionStartHandlers[message.type]();}}
_onUnsubscribe(message,port){const subscribers=this._subscribers[message.type];if(!subscribers)
return;subscribers.remove(port);if(!subscribers.length){delete this._subscribers[message.type];if(this._subscriptionStopHandlers[message.type])
this._subscriptionStopHandlers[message.type]();}}
_onAddRequestHeaders(message){const id=message.extensionId;if(typeof id!=='string')
return this._status.E_BADARGTYPE('extensionId',typeof id,'string');let extensionHeaders=this._extraHeaders[id];if(!extensionHeaders){extensionHeaders={};this._extraHeaders[id]=extensionHeaders;}
for(const name in message.headers)
extensionHeaders[name]=message.headers[name];const allHeaders=({});for(const extension in this._extraHeaders){const headers=this._extraHeaders[extension];for(const name in headers){if(typeof headers[name]==='string')
allHeaders[name]=headers[name];}}
SDK.multitargetNetworkManager.setExtraHTTPHeaders(allHeaders);}
_onApplyStyleSheet(message){if(!Runtime.experiments.isEnabled('applyCustomStylesheet'))
return;const styleSheet=createElement('style');styleSheet.textContent=message.styleSheet;document.head.appendChild(styleSheet);UI.themeSupport.addCustomStylesheet(message.styleSheet);for(let node=document.body;node;node=node.traverseNextNode(document.body)){if(node instanceof ShadowRoot)
UI.themeSupport.injectCustomStyleSheets(node);}}
_onCreatePanel(message,port){const id=message.id;if(id in this._clientObjects||UI.inspectorView.hasPanel(id))
return this._status.E_EXISTS(id);const page=this._expandResourcePath(port._extensionOrigin,message.page);let persistentId=port._extensionOrigin+message.title;persistentId=persistentId.replace(/\s/g,'');const panelView=new Extensions.ExtensionServerPanelView(persistentId,message.title,new Extensions.ExtensionPanel(this,persistentId,id,page));this._clientObjects[id]=panelView;UI.inspectorView.addPanel(panelView);return this._status.OK();}
_onShowPanel(message){let panelViewId=message.id;const panelView=this._clientObjects[message.id];if(panelView&&panelView instanceof Extensions.ExtensionServerPanelView)
panelViewId=panelView.viewId();UI.inspectorView.showPanel(panelViewId);}
_onCreateToolbarButton(message,port){const panelView=this._clientObjects[message.panel];if(!panelView||!(panelView instanceof Extensions.ExtensionServerPanelView))
return this._status.E_NOTFOUND(message.panel);const button=new Extensions.ExtensionButton(this,message.id,this._expandResourcePath(port._extensionOrigin,message.icon),message.tooltip,message.disabled);this._clientObjects[message.id]=button;panelView.widget().then(appendButton);function appendButton(panel){(panel).addToolbarItem(button.toolbarButton());}
return this._status.OK();}
_onUpdateButton(message,port){const button=this._clientObjects[message.id];if(!button||!(button instanceof Extensions.ExtensionButton))
return this._status.E_NOTFOUND(message.id);button.update(this._expandResourcePath(port._extensionOrigin,message.icon),message.tooltip,message.disabled);return this._status.OK();}
_onCompleteTraceSession(message){const session=this._traceSessions.get(message.id);if(!session)
return this._status.E_NOTFOUND(message.id);this._traceSessions.delete(message.id);session.complete(message.url,message.timeOffset);}
_onCreateSidebarPane(message){if(message.panel!=='elements'&&message.panel!=='sources')
return this._status.E_NOTFOUND(message.panel);const id=message.id;const sidebar=new Extensions.ExtensionSidebarPane(this,message.panel,message.title,id);this._sidebarPanes.push(sidebar);this._clientObjects[id]=sidebar;this.dispatchEventToListeners(Extensions.ExtensionServer.Events.SidebarPaneAdded,sidebar);return this._status.OK();}
sidebarPanes(){return this._sidebarPanes;}
_onSetSidebarHeight(message){const sidebar=this._clientObjects[message.id];if(!sidebar)
return this._status.E_NOTFOUND(message.id);sidebar.setHeight(message.height);return this._status.OK();}
_onSetSidebarContent(message,port){const sidebar=this._clientObjects[message.id];if(!sidebar)
return this._status.E_NOTFOUND(message.id);function callback(error){const result=error?this._status.E_FAILED(error):this._status.OK();this._dispatchCallback(message.requestId,port,result);}
if(message.evaluateOnPage){return sidebar.setExpression(message.expression,message.rootTitle,message.evaluateOptions,port._extensionOrigin,callback.bind(this));}
sidebar.setObject(message.expression,message.rootTitle,callback.bind(this));}
_onSetSidebarPage(message,port){const sidebar=this._clientObjects[message.id];if(!sidebar)
return this._status.E_NOTFOUND(message.id);sidebar.setPage(this._expandResourcePath(port._extensionOrigin,message.page));}
_onOpenResource(message){const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(message.url);if(uiSourceCode){Common.Revealer.reveal(uiSourceCode.uiLocation(message.lineNumber,0));return this._status.OK();}
const resource=Bindings.resourceForURL(message.url);if(resource){Common.Revealer.reveal(resource);return this._status.OK();}
const request=SDK.networkLog.requestForURL(message.url);if(request){Common.Revealer.reveal(request);return this._status.OK();}
return this._status.E_NOTFOUND(message.url);}
_onSetOpenResourceHandler(message,port){const name=this._registeredExtensions[port._extensionOrigin].name||('Extension '+port._extensionOrigin);if(message.handlerPresent)
Components.Linkifier.registerLinkHandler(name,this._handleOpenURL.bind(this,port));else
Components.Linkifier.unregisterLinkHandler(name);}
_handleOpenURL(port,contentProvider,lineNumber){port.postMessage({command:'open-resource',resource:this._makeResource(contentProvider),lineNumber:lineNumber+1});}
_onReload(message){const options=(message.options||{});SDK.multitargetNetworkManager.setUserAgentOverride(typeof options.userAgent==='string'?options.userAgent:'');let injectedScript;if(options.injectedScript)
injectedScript='(function(){'+options.injectedScript+'})()';SDK.ResourceTreeModel.reloadAllPages(!!options.ignoreCache,injectedScript);return this._status.OK();}
_onEvaluateOnInspectedPage(message,port){function callback(error,object,wasThrown){let result;if(error||!object)
result=this._status.E_PROTOCOLERROR(error.toString());else if(wasThrown)
result={isException:true,value:object.description};else
result={value:object.value};this._dispatchCallback(message.requestId,port,result);}
return this.evaluate(message.expression,true,true,message.evaluateOptions,port._extensionOrigin,callback.bind(this));}
async _onGetHAR(){const requests=SDK.networkLog.requests();const harLog=await SDK.HARLog.build(requests);for(let i=0;i<harLog.entries.length;++i)
harLog.entries[i]._requestId=this._requestId(requests[i]);return harLog;}
_makeResource(contentProvider){return{url:contentProvider.contentURL(),type:contentProvider.contentType().name()};}
_onGetPageResources(){const resources=new Map();function pushResourceData(contentProvider){if(!resources.has(contentProvider.contentURL()))
resources.set(contentProvider.contentURL(),this._makeResource(contentProvider));}
let uiSourceCodes=Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.Network);uiSourceCodes=uiSourceCodes.concat(Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.ContentScripts));uiSourceCodes.forEach(pushResourceData.bind(this));for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel))
resourceTreeModel.forAllResources(pushResourceData.bind(this));return resources.valuesArray();}
async _getResourceContent(contentProvider,message,port){const content=await contentProvider.requestContent();const encoded=await contentProvider.contentEncoded();this._dispatchCallback(message.requestId,port,{encoding:encoded?'base64':'',content:content});}
_onGetRequestContent(message,port){const request=this._requestById(message.id);if(!request)
return this._status.E_NOTFOUND(message.id);this._getResourceContent(request,message,port);}
_onGetResourceContent(message,port){const url=(message.url);const contentProvider=Workspace.workspace.uiSourceCodeForURL(url)||Bindings.resourceForURL(url);if(!contentProvider)
return this._status.E_NOTFOUND(url);this._getResourceContent(contentProvider,message,port);}
_onSetResourceContent(message,port){function callbackWrapper(error){const response=error?this._status.E_FAILED(error):this._status.OK();this._dispatchCallback(message.requestId,port,response);}
const url=(message.url);const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(!uiSourceCode||!uiSourceCode.contentType().isDocumentOrScriptOrStyleSheet()){const resource=SDK.ResourceTreeModel.resourceForURL(url);if(!resource)
return this._status.E_NOTFOUND(url);return this._status.E_NOTSUPPORTED('Resource is not editable');}
uiSourceCode.setWorkingCopy(message.content);if(message.commit)
uiSourceCode.commitWorkingCopy();callbackWrapper.call(this,null);}
_requestId(request){if(!request._extensionRequestId){request._extensionRequestId=++this._lastRequestId;this._requests[request._extensionRequestId]=request;}
return request._extensionRequestId;}
_requestById(id){return this._requests[id];}
_onAddTraceProvider(message,port){const provider=new Extensions.ExtensionTraceProvider(port._extensionOrigin,message.id,message.categoryName,message.categoryTooltip);this._clientObjects[message.id]=provider;this._traceProviders.push(provider);this.dispatchEventToListeners(Extensions.ExtensionServer.Events.TraceProviderAdded,provider);}
traceProviders(){return this._traceProviders;}
_onForwardKeyboardEvent(message){message.entries.forEach(handleEventEntry);function handleEventEntry(entry){const event=new window.KeyboardEvent(entry.eventType,{key:entry.key,code:entry.code,keyCode:entry.keyCode,location:entry.location,ctrlKey:entry.ctrlKey,altKey:entry.altKey,shiftKey:entry.shiftKey,metaKey:entry.metaKey});event.__keyCode=keyCodeForEntry(entry);document.dispatchEvent(event);}
function keyCodeForEntry(entry){let keyCode=entry.keyCode;if(!keyCode){if(entry.key==='Escape')
keyCode=27;}
return keyCode||0;}}
_dispatchCallback(requestId,port,result){if(requestId)
port.postMessage({command:'callback',requestId:requestId,result:result});}
_initExtensions(){this._registerAutosubscriptionHandler(Extensions.extensionAPI.Events.ResourceAdded,Workspace.workspace,Workspace.Workspace.Events.UISourceCodeAdded,this._notifyResourceAdded);this._registerAutosubscriptionTargetManagerHandler(Extensions.extensionAPI.Events.NetworkRequestFinished,SDK.NetworkManager,SDK.NetworkManager.Events.RequestFinished,this._notifyRequestFinished);function onElementsSubscriptionStarted(){UI.context.addFlavorChangeListener(SDK.DOMNode,this._notifyElementsSelectionChanged,this);}
function onElementsSubscriptionStopped(){UI.context.removeFlavorChangeListener(SDK.DOMNode,this._notifyElementsSelectionChanged,this);}
this._registerSubscriptionHandler(Extensions.extensionAPI.Events.PanelObjectSelected+'elements',onElementsSubscriptionStarted.bind(this),onElementsSubscriptionStopped.bind(this));this._registerResourceContentCommittedHandler(this._notifyUISourceCodeContentCommitted);SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);self.InspectorExtensionRegistry.getExtensionsAsync();}
_notifyResourceAdded(event){const uiSourceCode=(event.data);this._postNotification(Extensions.extensionAPI.Events.ResourceAdded,this._makeResource(uiSourceCode));}
_notifyUISourceCodeContentCommitted(event){const uiSourceCode=(event.data.uiSourceCode);const content=(event.data.content);this._postNotification(Extensions.extensionAPI.Events.ResourceContentCommitted,this._makeResource(uiSourceCode),content);}
async _notifyRequestFinished(event){const request=(event.data);const entry=await SDK.HARLog.Entry.build(request);this._postNotification(Extensions.extensionAPI.Events.NetworkRequestFinished,this._requestId(request),entry);}
_notifyElementsSelectionChanged(){this._postNotification(Extensions.extensionAPI.Events.PanelObjectSelected+'elements');}
sourceSelectionChanged(url,range){this._postNotification(Extensions.extensionAPI.Events.PanelObjectSelected+'sources',{startLine:range.startLine,startColumn:range.startColumn,endLine:range.endLine,endColumn:range.endColumn,url:url,});}
_addExtensions(event){if(Extensions.extensionServer._overridePlatformExtensionAPIForTest)
window.buildPlatformExtensionAPI=Extensions.extensionServer._overridePlatformExtensionAPIForTest;const extensionInfos=(event.data);if(this._initializeCommandIssued)
extensionInfos.forEach(this._addExtension,this);else
this._pendingExtensionInfos=extensionInfos;}
_setInspectedTabId(event){this._inspectedTabId=(event.data);}
_addExtension(extensionInfo){const urlOriginRegExp=new RegExp('([^:]+:\/\/[^/]*)\/');const startPage=extensionInfo.startPage;const name=extensionInfo.name;try{const originMatch=urlOriginRegExp.exec(startPage);if(!originMatch){console.error('Skipping extension with invalid URL: '+startPage);return false;}
const extensionOrigin=originMatch[1];if(!this._registeredExtensions[extensionOrigin]){const injectedAPI=buildExtensionAPIInjectedScript(extensionInfo,this._inspectedTabId,UI.themeSupport.themeName(),UI.shortcutRegistry.globalShortcutKeys(),Extensions.extensionServer['_extensionAPITestHook']);InspectorFrontendHost.setInjectedScriptForOrigin(extensionOrigin,injectedAPI);this._registeredExtensions[extensionOrigin]={name:name};}
const iframe=createElement('iframe');iframe.src=startPage;iframe.style.display='none';document.body.appendChild(iframe);}catch(e){console.error('Failed to initialize extension '+startPage+':'+e);return false;}
return true;}
_registerExtension(origin,port){if(!this._registeredExtensions.hasOwnProperty(origin)){if(origin!==window.location.origin)
console.error('Ignoring unauthorized client request from '+origin);return;}
port._extensionOrigin=origin;port.addEventListener('message',this._onmessage.bind(this),false);port.start();}
_onWindowMessage(event){if(event.data==='registerExtension')
this._registerExtension(event.origin,event.ports[0]);}
async _onmessage(event){const message=event.data;let result;if(message.command in this._handlers)
result=await this._handlers[message.command](message,event.target);else
result=this._status.E_NOTSUPPORTED(message.command);if(result&&message.requestId)
this._dispatchCallback(message.requestId,event.target,result);}
_registerHandler(command,callback){console.assert(command);this._handlers[command]=callback;}
_registerSubscriptionHandler(eventTopic,onSubscribeFirst,onUnsubscribeLast){this._subscriptionStartHandlers[eventTopic]=onSubscribeFirst;this._subscriptionStopHandlers[eventTopic]=onUnsubscribeLast;}
_registerAutosubscriptionHandler(eventTopic,eventTarget,frontendEventType,handler){this._registerSubscriptionHandler(eventTopic,eventTarget.addEventListener.bind(eventTarget,frontendEventType,handler,this),eventTarget.removeEventListener.bind(eventTarget,frontendEventType,handler,this));}
_registerAutosubscriptionTargetManagerHandler(eventTopic,modelClass,frontendEventType,handler){this._registerSubscriptionHandler(eventTopic,SDK.targetManager.addModelListener.bind(SDK.targetManager,modelClass,frontendEventType,handler,this),SDK.targetManager.removeModelListener.bind(SDK.targetManager,modelClass,frontendEventType,handler,this));}
_registerResourceContentCommittedHandler(handler){function addFirstEventListener(){Workspace.workspace.addEventListener(Workspace.Workspace.Events.WorkingCopyCommittedByUser,handler,this);Workspace.workspace.setHasResourceContentTrackingExtensions(true);}
function removeLastEventListener(){Workspace.workspace.setHasResourceContentTrackingExtensions(false);Workspace.workspace.removeEventListener(Workspace.Workspace.Events.WorkingCopyCommittedByUser,handler,this);}
this._registerSubscriptionHandler(Extensions.extensionAPI.Events.ResourceContentCommitted,addFirstEventListener.bind(this),removeLastEventListener.bind(this));}
_expandResourcePath(extensionPath,resourcePath){if(!resourcePath)
return;return extensionPath+this._normalizePath(resourcePath);}
_normalizePath(path){const source=path.split('/');const result=[];for(let i=0;i<source.length;++i){if(source[i]==='.')
continue;if(source[i]==='')
continue;if(source[i]==='..')
result.pop();else
result.push(source[i]);}
return'/'+result.join('/');}
evaluate(expression,exposeCommandLineAPI,returnByValue,options,securityOrigin,callback){let context;function resolveURLToFrame(url){let found;function hasMatchingURL(frame){found=(frame.url===url)?frame:null;return found;}
SDK.ResourceTreeModel.frames().some(hasMatchingURL);return found;}
options=options||{};let frame;if(options.frameURL){frame=resolveURLToFrame(options.frameURL);}else{const target=SDK.targetManager.mainTarget();const resourceTreeModel=target&&target.model(SDK.ResourceTreeModel);frame=resourceTreeModel&&resourceTreeModel.mainFrame;}
if(!frame){if(options.frameURL)
console.warn('evaluate: there is no frame with URL '+options.frameURL);else
console.warn('evaluate: the main frame is not yet available');return this._status.E_NOTFOUND(options.frameURL||'<top>');}
let contextSecurityOrigin;if(options.useContentScriptContext)
contextSecurityOrigin=securityOrigin;else if(options.scriptExecutionContext)
contextSecurityOrigin=options.scriptExecutionContext;const runtimeModel=frame.resourceTreeModel().target().model(SDK.RuntimeModel);const executionContexts=runtimeModel?runtimeModel.executionContexts():[];if(contextSecurityOrigin){for(let i=0;i<executionContexts.length;++i){const executionContext=executionContexts[i];if(executionContext.frameId===frame.id&&executionContext.origin===contextSecurityOrigin&&!executionContext.isDefault)
context=executionContext;}
if(!context){console.warn('The JavaScript context '+contextSecurityOrigin+' was not found in the frame '+frame.url);return this._status.E_NOTFOUND(contextSecurityOrigin);}}else{for(let i=0;i<executionContexts.length;++i){const executionContext=executionContexts[i];if(executionContext.frameId===frame.id&&executionContext.isDefault)
context=executionContext;}
if(!context)
return this._status.E_FAILED(frame.url+' has no execution context');}
context.evaluate({expression:expression,objectGroup:'extension',includeCommandLineAPI:exposeCommandLineAPI,silent:true,returnByValue:returnByValue,generatePreview:false},false,false).then(onEvaluate);function onEvaluate(result){if(result.error){callback(result.error,null,false);return;}
callback(null,result.object||null,!!result.exceptionDetails);}}};Extensions.ExtensionServer.Events={SidebarPaneAdded:Symbol('SidebarPaneAdded'),TraceProviderAdded:Symbol('TraceProviderAdded')};Extensions.ExtensionServerPanelView=class extends UI.SimpleView{constructor(name,title,panel){super(title);this._name=name;this._panel=panel;}
viewId(){return this._name;}
widget(){return(Promise.resolve(this._panel));}};Extensions.ExtensionStatus=class{constructor(){function makeStatus(code,description){const details=Array.prototype.slice.call(arguments,2);const status={code:code,description:description,details:details};if(code!=='OK'){status.isError=true;console.error('Extension server error: '+String.vsprintf(description,details));}
return status;}
this.OK=makeStatus.bind(null,'OK','OK');this.E_EXISTS=makeStatus.bind(null,'E_EXISTS','Object already exists: %s');this.E_BADARG=makeStatus.bind(null,'E_BADARG','Invalid argument %s: %s');this.E_BADARGTYPE=makeStatus.bind(null,'E_BADARGTYPE','Invalid type for argument %s: got %s, expected %s');this.E_NOTFOUND=makeStatus.bind(null,'E_NOTFOUND','Object not found: %s');this.E_NOTSUPPORTED=makeStatus.bind(null,'E_NOTSUPPORTED','Object does not support requested operation: %s');this.E_PROTOCOLERROR=makeStatus.bind(null,'E_PROTOCOLERROR','Inspector protocol error: %s');this.E_FAILED=makeStatus.bind(null,'E_FAILED','Operation failed: %s');}};Extensions.ExtensionStatus.Record;Extensions.extensionAPI={};defineCommonExtensionSymbols(Extensions.extensionAPI);Extensions.extensionServer;;Extensions.ExtensionPanel=class extends UI.Panel{constructor(server,panelName,id,pageURL){super(panelName);this._server=server;this._id=id;this.setHideOnDetach();this._panelToolbar=new UI.Toolbar('hidden',this.element);this._searchableView=new UI.SearchableView(this);this._searchableView.show(this.element);const extensionView=new Extensions.ExtensionView(server,this._id,pageURL,'extension');extensionView.show(this._searchableView.element);}
addToolbarItem(item){this._panelToolbar.element.classList.remove('hidden');this._panelToolbar.appendToolbarItem(item);}
searchCanceled(){this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.CancelSearch);this._searchableView.updateSearchMatchesCount(0);}
searchableView(){return this._searchableView;}
performSearch(searchConfig,shouldJump,jumpBackwards){const query=searchConfig.query;this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.PerformSearch,query);}
jumpToNextSearchResult(){this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.NextSearchResult);}
jumpToPreviousSearchResult(){this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.PreviousSearchResult);}
supportsCaseSensitiveSearch(){return false;}
supportsRegexSearch(){return false;}};Extensions.ExtensionButton=class{constructor(server,id,iconURL,tooltip,disabled){this._id=id;this._toolbarButton=new UI.ToolbarButton('','');this._toolbarButton.addEventListener(UI.ToolbarButton.Events.Click,server.notifyButtonClicked.bind(server,this._id));this.update(iconURL,tooltip,disabled);}
update(iconURL,tooltip,disabled){if(typeof iconURL==='string')
this._toolbarButton.setBackgroundImage(iconURL);if(typeof tooltip==='string')
this._toolbarButton.setTitle(tooltip);if(typeof disabled==='boolean')
this._toolbarButton.setEnabled(!disabled);}
toolbarButton(){return this._toolbarButton;}};Extensions.ExtensionSidebarPane=class extends UI.SimpleView{constructor(server,panelName,title,id){super(title);this.element.classList.add('fill');this._panelName=panelName;this._server=server;this._id=id;}
id(){return this._id;}
panelName(){return this._panelName;}
setObject(object,title,callback){this._createObjectPropertiesView();this._setObject(SDK.RemoteObject.fromLocalObject(object),title,callback);}
setExpression(expression,title,evaluateOptions,securityOrigin,callback){this._createObjectPropertiesView();this._server.evaluate(expression,true,false,evaluateOptions,securityOrigin,this._onEvaluate.bind(this,title,callback));}
setPage(url){if(this._objectPropertiesView){this._objectPropertiesView.detach();delete this._objectPropertiesView;}
if(this._extensionView)
this._extensionView.detach(true);this._extensionView=new Extensions.ExtensionView(this._server,this._id,url,'extension fill');this._extensionView.show(this.element);if(!this.element.style.height)
this.setHeight('150px');}
setHeight(height){this.element.style.height=height;}
_onEvaluate(title,callback,error,result,wasThrown){if(error||!result)
callback(error.toString());else
this._setObject(result,title,callback);}
_createObjectPropertiesView(){if(this._objectPropertiesView)
return;if(this._extensionView){this._extensionView.detach(true);delete this._extensionView;}
this._objectPropertiesView=new Extensions.ExtensionNotifierView(this._server,this._id);this._objectPropertiesView.show(this.element);}
_setObject(object,title,callback){if(!this._objectPropertiesView){callback('operation cancelled');return;}
this._objectPropertiesView.element.removeChildren();UI.Renderer.render(object,{title,editable:false}).then(result=>{if(!result){callback();return;}
if(result.tree&&result.tree.firstChild())
result.tree.firstChild().expand();this._objectPropertiesView.element.appendChild(result.node);callback();});}};;Extensions.ExtensionView=class extends UI.Widget{constructor(server,id,src,className){super();this.setHideOnDetach();this.element.className='vbox flex-auto';this.element.tabIndex=-1;this._server=server;this._id=id;this._iframe=createElement('iframe');this._iframe.addEventListener('load',this._onLoad.bind(this),false);this._iframe.src=src;this._iframe.className=className;this.setDefaultFocusedElement(this.element);this.element.appendChild(this._iframe);}
wasShown(){if(typeof this._frameIndex==='number')
this._server.notifyViewShown(this._id,this._frameIndex);}
willHide(){if(typeof this._frameIndex==='number')
this._server.notifyViewHidden(this._id);}
_onLoad(){const frames=(window.frames);this._frameIndex=Array.prototype.indexOf.call(frames,this._iframe.contentWindow);if(this.isShowing())
this._server.notifyViewShown(this._id,this._frameIndex);}};Extensions.ExtensionNotifierView=class extends UI.VBox{constructor(server,id){super();this._server=server;this._id=id;}
wasShown(){this._server.notifyViewShown(this._id);}
willHide(){this._server.notifyViewHidden(this._id);}};;self['ProductRegistry']=self['ProductRegistry']||{};ProductRegistry.BadgePool=class{constructor(forceShow){this._showTitles=false;this._badgeElements=new Map();if(!forceShow){this._setting=Common.settings.moduleSetting('product_registry.badges-visible');this._setting.addChangeListener(this._settingUpdated.bind(this));if(this._setting.get())
Host.userMetrics.actionTaken(Host.UserMetrics.Action.ShowedThirdPartyBadges);}}
setShowTitles(value){this._showTitles=value;}
badgeForFrame(frame){return this._badgeForFrameOrUrl(this._resolveUrl.bind(this,frame));}
badgeForURL(parsedUrl){return this._badgeForFrameOrUrl(()=>Promise.resolve(parsedUrl));}
reset(){this._badgeElements.clear();}
_badgeForFrameOrUrl(urlResolver){const element=createElementWithClass('span','hidden');const root=UI.createShadowRootWithCoreStyles(element,'product_registry/badge.css');const badgeElement=root.createChild('span');badgeElement.classList.toggle('hide-badge-title',!this._showTitles);badgeElement.addEventListener('mousedown',event=>event.consume());badgeElement.addEventListener('click',event=>{this._showPopup(badgeElement);event.consume();},false);this._badgeElements.set(badgeElement,urlResolver);this._renderBadge(badgeElement);return element;}
async _resolveUrl(frame){const registry=await ProductRegistry.instance();let parsedUrl=new Common.ParsedURL(frame.url);const entry=registry.entryForUrl(parsedUrl);if(!entry){frame.findCreationCallFrame(callFrame=>{if(!callFrame.url)
return false;parsedUrl=new Common.ParsedURL(callFrame.url);return!!registry.entryForUrl(parsedUrl);});}
return parsedUrl;}
async _renderBadge(badgeElement){if(badgeElement.children.length||!this._isVisible(badgeElement)){this._updateBadgeElementVisibility(badgeElement);return;}
const parsedUrl=await this._badgeElements.get(badgeElement)();const registry=await ProductRegistry.instance();const entryName=parsedUrl&&registry.nameForUrl(parsedUrl);if(!entryName)
return;const tokens=entryName.replace(/[a-z]*/g,'').split(' ');let label;if(tokens.length>1)
label=tokens[0][0]+tokens[1][0];else
label=entryName;const iconElement=badgeElement.createChild('span','product-registry-badge monospace');iconElement.setAttribute('data-initial',label.substring(0,2).toUpperCase());iconElement.title=entryName;iconElement.style.backgroundColor=ProductRegistry.BadgePool.colorForEntryName(entryName);badgeElement.createChild('span','product-registry-badge-title').textContent=entryName;this._updateBadgeElementVisibility(badgeElement);}
_settingUpdated(){for(const badgeElement of this._badgeElements.keys())
this._renderBadge(badgeElement);}
_isVisible(badgeElement){return!this._setting||this._setting.get();}
_updateBadgeElementVisibility(badgeElement){badgeElement.parentNodeOrShadowHost().parentNodeOrShadowHost().classList.toggle('hidden',!this._isVisible(badgeElement));}
async _showPopup(badgeElement){if(!this._badgeElements.has(badgeElement))
return;const registry=await ProductRegistry.instance();const parsedUrl=await this._badgeElements.get(badgeElement)();const entryName=registry.nameForUrl(parsedUrl);const element=createElement('div');const root=UI.createShadowRootWithCoreStyles(element,'product_registry/popup.css');const popupElement=root.createChild('div','product-registry-popup');const domainElement=popupElement.createChild('div','product-registry-domain');domainElement.textContent=parsedUrl.domain();const entryNameElement=popupElement.createChild('div','product-registry-name');entryNameElement.textContent=entryName;const reportLink='https://docs.google.com/forms/d/e/1FAIpQLSchz2FdcQ-rRllzl8BbhWaTRRY-12BpPjW6Hr9e1-BpCA083w/viewform'+'?entry_1425918171='+encodeURIComponent((parsedUrl.domain()+parsedUrl.path).substr(0,100));popupElement.appendChild(UI.XLink.create(reportLink,'Report mismatch','product-registry-link'));const dialog=new UI.Dialog();dialog.setContentAnchorBox(badgeElement.boxInWindow());dialog.contentElement.appendChild(element);dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferTop);dialog.addCloseButton();dialog.show((badgeElement.ownerDocument));}
static colorForEntryName(entryName){if(!ProductRegistry.BadgePool._colorGenerator){ProductRegistry.BadgePool._colorGenerator=new Common.Color.Generator({min:30,max:330},{min:50,max:80,count:3},80);}
return ProductRegistry.BadgePool._colorGenerator.colorForID(entryName);}};;ProductRegistry.instance=function(){const extension=self.runtime.extension(ProductRegistry.Registry);if(extension)
return extension.instance();return Promise.resolve(self.singleton(ProductRegistry.RegistryStub));};ProductRegistry.Registry=function(){};ProductRegistry.Registry.prototype={nameForUrl:function(parsedUrl){},entryForUrl:function(parsedUrl){},typeForUrl:function(parsedUrl){}};ProductRegistry.RegistryStub=class{nameForUrl(parsedUrl){return null;}
entryForUrl(parsedUrl){return null;}
typeForUrl(parsedUrl){return null;}};ProductRegistry.Registry.ProductEntry;;self['Main']=self['Main']||{};Main.SimpleApp=class{presentUI(document){const rootView=new UI.RootView();UI.inspectorView.show(rootView.element);rootView.attachToDocument(document);rootView.focus();}};Main.SimpleAppProvider=class{createApp(){return new Main.SimpleApp();}};;Main.ExecutionContextSelector=class{constructor(targetManager,context){context.addFlavorChangeListener(SDK.ExecutionContext,this._executionContextChanged,this);context.addFlavorChangeListener(SDK.Target,this._targetChanged,this);targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextCreated,this._onExecutionContextCreated,this);targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextDestroyed,this._onExecutionContextDestroyed,this);targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextOrderChanged,this._onExecutionContextOrderChanged,this);this._targetManager=targetManager;this._context=context;targetManager.observeModels(SDK.RuntimeModel,this);}
modelAdded(runtimeModel){setImmediate(deferred.bind(this));function deferred(){if(!this._context.flavor(SDK.Target))
this._context.setFlavor(SDK.Target,runtimeModel.target());}}
modelRemoved(runtimeModel){const currentExecutionContext=this._context.flavor(SDK.ExecutionContext);if(currentExecutionContext&&currentExecutionContext.runtimeModel===runtimeModel)
this._currentExecutionContextGone();const models=this._targetManager.models(SDK.RuntimeModel);if(this._context.flavor(SDK.Target)===runtimeModel.target()&&models.length)
this._context.setFlavor(SDK.Target,models[0].target());}
_executionContextChanged(event){const newContext=(event.data);if(newContext){this._context.setFlavor(SDK.Target,newContext.target());if(!this._ignoreContextChanged)
this._lastSelectedContextId=this._contextPersistentId(newContext);}}
_contextPersistentId(executionContext){return executionContext.isDefault?executionContext.target().name()+':'+executionContext.frameId:'';}
_targetChanged(event){const newTarget=(event.data);const currentContext=this._context.flavor(SDK.ExecutionContext);if(!newTarget||(currentContext&&currentContext.target()===newTarget))
return;const runtimeModel=newTarget.model(SDK.RuntimeModel);const executionContexts=runtimeModel?runtimeModel.executionContexts():[];if(!executionContexts.length)
return;let newContext=null;for(let i=0;i<executionContexts.length&&!newContext;++i){if(this._shouldSwitchToContext(executionContexts[i]))
newContext=executionContexts[i];}
for(let i=0;i<executionContexts.length&&!newContext;++i){if(this._isDefaultContext(executionContexts[i]))
newContext=executionContexts[i];}
this._ignoreContextChanged=true;this._context.setFlavor(SDK.ExecutionContext,newContext||executionContexts[0]);this._ignoreContextChanged=false;}
_shouldSwitchToContext(executionContext){if(this._lastSelectedContextId&&this._lastSelectedContextId===this._contextPersistentId(executionContext))
return true;if(!this._lastSelectedContextId&&this._isDefaultContext(executionContext))
return true;return false;}
_isDefaultContext(executionContext){if(!executionContext.isDefault||!executionContext.frameId)
return false;if(executionContext.target().parentTarget())
return false;const resourceTreeModel=executionContext.target().model(SDK.ResourceTreeModel);const frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);if(frame&&frame.isTopFrame())
return true;return false;}
_onExecutionContextCreated(event){this._switchContextIfNecessary((event.data));}
_onExecutionContextDestroyed(event){const executionContext=(event.data);if(this._context.flavor(SDK.ExecutionContext)===executionContext)
this._currentExecutionContextGone();}
_onExecutionContextOrderChanged(event){const runtimeModel=(event.data);const executionContexts=runtimeModel.executionContexts();for(let i=0;i<executionContexts.length;i++){if(this._switchContextIfNecessary(executionContexts[i]))
break;}}
_switchContextIfNecessary(executionContext){if(!this._context.flavor(SDK.ExecutionContext)||this._shouldSwitchToContext(executionContext)){this._ignoreContextChanged=true;this._context.setFlavor(SDK.ExecutionContext,executionContext);this._ignoreContextChanged=false;return true;}
return false;}
_currentExecutionContextGone(){const runtimeModels=this._targetManager.models(SDK.RuntimeModel);let newContext=null;for(let i=0;i<runtimeModels.length&&!newContext;++i){const executionContexts=runtimeModels[i].executionContexts();for(const executionContext of executionContexts){if(this._isDefaultContext(executionContext)){newContext=executionContext;break;}}}
if(!newContext){for(let i=0;i<runtimeModels.length&&!newContext;++i){const executionContexts=runtimeModels[i].executionContexts();if(executionContexts.length){newContext=executionContexts[0];break;}}}
this._ignoreContextChanged=true;this._context.setFlavor(SDK.ExecutionContext,newContext);this._ignoreContextChanged=false;}};;Main.Main=class{constructor(){Main.Main._instanceForTest=this;runOnWindowLoad(this._loaded.bind(this));}
static time(label){if(Host.isUnderTest())
return;console.time(label);}
static timeEnd(label){if(Host.isUnderTest())
return;console.timeEnd(label);}
async _loaded(){console.timeStamp('Main._loaded');await Runtime.appStarted();Runtime.setPlatform(Host.platform());Runtime.setL10nCallback(ls);InspectorFrontendHost.getPreferences(this._gotPreferences.bind(this));}
_gotPreferences(prefs){console.timeStamp('Main._gotPreferences');if(Host.isUnderTest(prefs))
self.runtime.useTestBase();this._createSettings(prefs);this._createAppUI();}
_createSettings(prefs){this._initializeExperiments();let storagePrefix='';if(Host.isCustomDevtoolsFrontend())
storagePrefix='__custom__';else if(!Runtime.queryParam('can_dock')&&!!Runtime.queryParam('debugFrontend')&&!Host.isUnderTest())
storagePrefix='__bundled__';let localStorage;if(!Host.isUnderTest()&&window.localStorage){localStorage=new Common.SettingsStorage(window.localStorage,undefined,undefined,()=>window.localStorage.clear(),storagePrefix);}else{localStorage=new Common.SettingsStorage({},undefined,undefined,undefined,storagePrefix);}
const globalStorage=new Common.SettingsStorage(prefs,InspectorFrontendHost.setPreference,InspectorFrontendHost.removePreference,InspectorFrontendHost.clearPreferences,storagePrefix);Common.settings=new Common.Settings(globalStorage,localStorage);if(!Host.isUnderTest())
new Common.VersionController().updateVersion();}
_initializeExperiments(){Runtime.experiments.register('applyCustomStylesheet','Allow custom UI themes');Runtime.experiments.register('sourcesPrettyPrint','Automatically pretty print in the Sources Panel');Runtime.experiments.register('backgroundServices','Background web platform feature events',true);Runtime.experiments.register('backgroundServicesNotifications','Background services section for Notifications');Runtime.experiments.register('backgroundServicesPushMessaging','Background services section for Push Messaging');Runtime.experiments.register('blackboxJSFramesOnTimeline','Blackbox JavaScript frames on Timeline',true);Runtime.experiments.register('emptySourceMapAutoStepping','Empty sourcemap auto-stepping');Runtime.experiments.register('inputEventsOnTimelineOverview','Input events on Timeline overview',true);Runtime.experiments.register('liveHeapProfile','Live heap profile',true);Runtime.experiments.register('nativeHeapProfiler','Native memory sampling heap profiler',true);Runtime.experiments.register('protocolMonitor','Protocol Monitor');Runtime.experiments.register('samplingHeapProfilerTimeline','Sampling heap profiler timeline',true);Runtime.experiments.register('sourceDiff','Source diff');Runtime.experiments.register('splitInDrawer','Split in drawer',true);Runtime.experiments.register('spotlight','Spotlight',true);Runtime.experiments.register('terminalInDrawer','Terminal in drawer',true);Runtime.experiments.register('timelineEventInitiators','Timeline: event initiators');Runtime.experiments.register('timelineFlowEvents','Timeline: flow events',true);Runtime.experiments.register('timelineInvalidationTracking','Timeline: invalidation tracking',true);Runtime.experiments.register('timelineShowAllEvents','Timeline: show all events',true);Runtime.experiments.register('timelineV8RuntimeCallStats','Timeline: V8 Runtime Call Stats on Timeline',true);Runtime.experiments.register('timelineWebGL','Timeline: WebGL-based flamechart');Runtime.experiments.cleanUpStaleExperiments();Runtime.experiments.setDefaultExperiments(['backgroundServices']);if(Host.isUnderTest()&&Runtime.queryParam('test').includes('live-line-level-heap-profile.js'))
Runtime.experiments.enableForTest('liveHeapProfile');}
async _createAppUI(){Main.Main.time('Main._createAppUI');UI.viewManager=new UI.ViewManager();Persistence.isolatedFileSystemManager=new Persistence.IsolatedFileSystemManager();const themeSetting=Common.settings.createSetting('uiTheme','default');UI.initializeUIUtils(document,themeSetting);themeSetting.addChangeListener(Components.reload.bind(Components));UI.installComponentRootStyles((document.body));this._addMainEventListeners(document);const canDock=!!Runtime.queryParam('can_dock');UI.zoomManager=new UI.ZoomManager(window,InspectorFrontendHost);UI.inspectorView=UI.InspectorView.instance();UI.ContextMenu.initialize();UI.ContextMenu.installHandler(document);UI.Tooltip.installHandler(document);Components.dockController=new Components.DockController(canDock);SDK.consoleModel=new SDK.ConsoleModel();SDK.multitargetNetworkManager=new SDK.MultitargetNetworkManager();SDK.domDebuggerManager=new SDK.DOMDebuggerManager();SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._onSuspendStateChanged.bind(this));UI.shortcutsScreen=new UI.ShortcutsScreen();UI.shortcutsScreen.section(Common.UIString('Elements Panel'));UI.shortcutsScreen.section(Common.UIString('Styles Pane'));UI.shortcutsScreen.section(Common.UIString('Debugger'));UI.shortcutsScreen.section(Common.UIString('Console'));Workspace.fileManager=new Workspace.FileManager();Workspace.workspace=new Workspace.Workspace();Bindings.networkProjectManager=new Bindings.NetworkProjectManager();Bindings.resourceMapping=new Bindings.ResourceMapping(SDK.targetManager,Workspace.workspace);new Bindings.PresentationConsoleMessageManager();Bindings.cssWorkspaceBinding=new Bindings.CSSWorkspaceBinding(SDK.targetManager,Workspace.workspace);Bindings.debuggerWorkspaceBinding=new Bindings.DebuggerWorkspaceBinding(SDK.targetManager,Workspace.workspace);Bindings.breakpointManager=new Bindings.BreakpointManager(Workspace.workspace,SDK.targetManager,Bindings.debuggerWorkspaceBinding);Extensions.extensionServer=new Extensions.ExtensionServer();new Persistence.FileSystemWorkspaceBinding(Persistence.isolatedFileSystemManager,Workspace.workspace);Persistence.persistence=new Persistence.Persistence(Workspace.workspace,Bindings.breakpointManager);Persistence.networkPersistenceManager=new Persistence.NetworkPersistenceManager(Workspace.workspace);new Main.ExecutionContextSelector(SDK.targetManager,UI.context);Bindings.blackboxManager=new Bindings.BlackboxManager(Bindings.debuggerWorkspaceBinding);new Main.Main.PauseListener();UI.actionRegistry=new UI.ActionRegistry();UI.shortcutRegistry=new UI.ShortcutRegistry(UI.actionRegistry,document);UI.ShortcutsScreen.registerShortcuts();this._registerForwardedShortcuts();this._registerMessageSinkListener();Main.Main.timeEnd('Main._createAppUI');this._showAppUI(await self.runtime.extension(Common.AppProvider).instance());}
_showAppUI(appProvider){Main.Main.time('Main._showAppUI');const app=(appProvider).createApp();Components.dockController.initialize();app.presentUI(document);const toggleSearchNodeAction=UI.actionRegistry.action('elements.toggle-element-search');if(toggleSearchNodeAction){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EnterInspectElementMode,toggleSearchNodeAction.execute.bind(toggleSearchNodeAction),this);}
InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.RevealSourceLine,this._revealSourceLine,this);UI.inspectorView.createToolbars();InspectorFrontendHost.loadCompleted();const extensions=self.runtime.extensions(Common.QueryParamHandler);for(const extension of extensions){const value=Runtime.queryParam(extension.descriptor()['name']);if(value!==null)
extension.instance().then(handleQueryParam.bind(null,value));}
function handleQueryParam(value,handler){handler.handleQueryParam(value);}
setTimeout(this._initializeTarget.bind(this),0);Main.Main.timeEnd('Main._showAppUI');}
async _initializeTarget(){Main.Main.time('Main._initializeTarget');const instances=await Promise.all(self.runtime.extensions('early-initialization').map(extension=>extension.instance()));for(const instance of instances)
await(instance).run();InspectorFrontendHost.readyForTest();setTimeout(this._lateInitialization.bind(this),100);Main.Main.timeEnd('Main._initializeTarget');}
_lateInitialization(){Main.Main.time('Main._lateInitialization');this._registerShortcuts();Extensions.extensionServer.initializeExtensions();const extensions=self.runtime.extensions('late-initialization');const promises=[];for(const extension of extensions){const setting=extension.descriptor()['setting'];if(!setting||Common.settings.moduleSetting(setting).get()){promises.push(extension.instance().then(instance=>((instance)).run()));continue;}
async function changeListener(event){if(!event.data)
return;Common.settings.moduleSetting(setting).removeChangeListener(changeListener);((await extension.instance())).run();}
Common.settings.moduleSetting(setting).addChangeListener(changeListener);}
this._lateInitDonePromise=Promise.all(promises);Main.Main.timeEnd('Main._lateInitialization');}
lateInitDonePromiseForTest(){return this._lateInitDonePromise;}
_registerForwardedShortcuts(){const forwardedActions=['main.toggle-dock','debugger.toggle-breakpoints-active','debugger.toggle-pause','commandMenu.show','console.show'];const actionKeys=UI.shortcutRegistry.keysForActions(forwardedActions).map(UI.KeyboardShortcut.keyCodeAndModifiersFromKey);InspectorFrontendHost.setWhitelistedShortcuts(JSON.stringify(actionKeys));}
_registerMessageSinkListener(){Common.console.addEventListener(Common.Console.Events.MessageAdded,messageAdded);function messageAdded(event){const message=(event.data);if(message.show)
Common.console.show();}}
_revealSourceLine(event){const url=(event.data['url']);const lineNumber=(event.data['lineNumber']);const columnNumber=(event.data['columnNumber']);const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(uiSourceCode){Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber,columnNumber));return;}
function listener(event){const uiSourceCode=(event.data);if(uiSourceCode.url()===url){Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber,columnNumber));Workspace.workspace.removeEventListener(Workspace.Workspace.Events.UISourceCodeAdded,listener);}}
Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,listener);}
_registerShortcuts(){const shortcut=UI.KeyboardShortcut;const section=UI.shortcutsScreen.section(Common.UIString('All Panels'));let keys=[shortcut.makeDescriptor('[',shortcut.Modifiers.CtrlOrMeta),shortcut.makeDescriptor(']',shortcut.Modifiers.CtrlOrMeta)];section.addRelatedKeys(keys,Common.UIString('Go to the panel to the left/right'));const toggleConsoleLabel=Common.UIString('Show console');section.addKey(shortcut.makeDescriptor(shortcut.Keys.Tilde,shortcut.Modifiers.Ctrl),toggleConsoleLabel);section.addKey(shortcut.makeDescriptor(shortcut.Keys.Esc),Common.UIString('Toggle drawer'));if(Components.dockController.canDock()){section.addKey(shortcut.makeDescriptor('M',shortcut.Modifiers.CtrlOrMeta|shortcut.Modifiers.Shift),Common.UIString('Toggle device mode'));section.addKey(shortcut.makeDescriptor('D',shortcut.Modifiers.CtrlOrMeta|shortcut.Modifiers.Shift),Common.UIString('Toggle dock side'));}
section.addKey(shortcut.makeDescriptor('f',shortcut.Modifiers.CtrlOrMeta),Common.UIString('Search'));const advancedSearchShortcutModifier=Host.isMac()?UI.KeyboardShortcut.Modifiers.Meta|UI.KeyboardShortcut.Modifiers.Alt:UI.KeyboardShortcut.Modifiers.Ctrl|UI.KeyboardShortcut.Modifiers.Shift;const advancedSearchShortcut=shortcut.makeDescriptor('f',advancedSearchShortcutModifier);section.addKey(advancedSearchShortcut,Common.UIString('Search across all sources'));const inspectElementModeShortcuts=UI.shortcutRegistry.shortcutDescriptorsForAction('elements.toggle-element-search');if(inspectElementModeShortcuts.length)
section.addKey(inspectElementModeShortcuts[0],Common.UIString('Select node to inspect'));const openResourceShortcut=UI.KeyboardShortcut.makeDescriptor('p',UI.KeyboardShortcut.Modifiers.CtrlOrMeta);section.addKey(openResourceShortcut,Common.UIString('Go to source'));if(Host.isMac()){keys=[shortcut.makeDescriptor('g',shortcut.Modifiers.Meta),shortcut.makeDescriptor('g',shortcut.Modifiers.Meta|shortcut.Modifiers.Shift)];section.addRelatedKeys(keys,Common.UIString('Find next/previous'));}}
_postDocumentKeyDown(event){if(!event.handled)
UI.shortcutRegistry.handleShortcut(event);}
_redispatchClipboardEvent(event){const eventCopy=new CustomEvent('clipboard-'+event.type,{bubbles:true});eventCopy['original']=event;const document=event.target&&event.target.ownerDocument;const target=document?document.deepActiveElement():null;if(target)
target.dispatchEvent(eventCopy);if(eventCopy.handled)
event.preventDefault();}
_contextMenuEventFired(event){if(event.handled||event.target.classList.contains('popup-glasspane'))
event.preventDefault();}
_addMainEventListeners(document){document.addEventListener('keydown',this._postDocumentKeyDown.bind(this),false);document.addEventListener('beforecopy',this._redispatchClipboardEvent.bind(this),true);document.addEventListener('copy',this._redispatchClipboardEvent.bind(this),false);document.addEventListener('cut',this._redispatchClipboardEvent.bind(this),false);document.addEventListener('paste',this._redispatchClipboardEvent.bind(this),false);document.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),true);}
_onSuspendStateChanged(){const suspended=SDK.targetManager.allTargetsSuspended();UI.inspectorView.onSuspendStateChanged(suspended);}};Main.Main.ZoomActionDelegate=class{handleAction(context,actionId){if(InspectorFrontendHost.isHostedMode())
return false;switch(actionId){case'main.zoom-in':InspectorFrontendHost.zoomIn();return true;case'main.zoom-out':InspectorFrontendHost.zoomOut();return true;case'main.zoom-reset':InspectorFrontendHost.resetZoom();return true;}
return false;}};Main.Main.SearchActionDelegate=class{handleAction(context,actionId){const searchableView=UI.SearchableView.fromElement(document.deepActiveElement())||UI.inspectorView.currentPanelDeprecated().searchableView();if(!searchableView)
return false;switch(actionId){case'main.search-in-panel.find':return searchableView.handleFindShortcut();case'main.search-in-panel.cancel':return searchableView.handleCancelSearchShortcut();case'main.search-in-panel.find-next':return searchableView.handleFindNextShortcut();case'main.search-in-panel.find-previous':return searchableView.handleFindPreviousShortcut();}
return false;}};Main.Main.MainMenuItem=class{constructor(){this._item=new UI.ToolbarMenuButton(this._handleContextMenu.bind(this),true);this._item.setTitle(Common.UIString('Customize and control DevTools'));}
item(){return this._item;}
_handleContextMenu(contextMenu){if(Components.dockController.canDock()){const dockItemElement=createElementWithClass('div','flex-centered flex-auto');dockItemElement.tabIndex=-1;const titleElement=dockItemElement.createChild('span','flex-auto');titleElement.textContent=Common.UIString('Dock side');const toggleDockSideShorcuts=UI.shortcutRegistry.shortcutDescriptorsForAction('main.toggle-dock');titleElement.title=Common.UIString('Placement of DevTools relative to the page. (%s to restore last position)',toggleDockSideShorcuts[0].name);dockItemElement.appendChild(titleElement);const dockItemToolbar=new UI.Toolbar('',dockItemElement);if(Host.isMac()&&!UI.themeSupport.hasTheme())
dockItemToolbar.makeBlueOnHover();const undock=new UI.ToolbarToggle(Common.UIString('Undock into separate window'),'largeicon-undock');const bottom=new UI.ToolbarToggle(Common.UIString('Dock to bottom'),'largeicon-dock-to-bottom');const right=new UI.ToolbarToggle(Common.UIString('Dock to right'),'largeicon-dock-to-right');const left=new UI.ToolbarToggle(Common.UIString('Dock to left'),'largeicon-dock-to-left');undock.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());bottom.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());right.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());left.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());undock.addEventListener(UI.ToolbarButton.Events.Click,setDockSide.bind(null,Components.DockController.State.Undocked));bottom.addEventListener(UI.ToolbarButton.Events.Click,setDockSide.bind(null,Components.DockController.State.DockedToBottom));right.addEventListener(UI.ToolbarButton.Events.Click,setDockSide.bind(null,Components.DockController.State.DockedToRight));left.addEventListener(UI.ToolbarButton.Events.Click,setDockSide.bind(null,Components.DockController.State.DockedToLeft));undock.setToggled(Components.dockController.dockSide()===Components.DockController.State.Undocked);bottom.setToggled(Components.dockController.dockSide()===Components.DockController.State.DockedToBottom);right.setToggled(Components.dockController.dockSide()===Components.DockController.State.DockedToRight);left.setToggled(Components.dockController.dockSide()===Components.DockController.State.DockedToLeft);dockItemToolbar.appendToolbarItem(undock);dockItemToolbar.appendToolbarItem(left);dockItemToolbar.appendToolbarItem(bottom);dockItemToolbar.appendToolbarItem(right);dockItemElement.addEventListener('keydown',event=>{let dir=0;if(event.key==='ArrowLeft')
dir=-1;else if(event.key==='ArrowRight')
dir=1;else
return;const buttons=[undock,left,bottom,right];let index=buttons.findIndex(button=>button.element.hasFocus());index=Number.constrain(index+dir,0,buttons.length-1);buttons[index].element.focus();event.consume(true);});contextMenu.headerSection().appendCustomItem(dockItemElement);}
function setDockSide(side){Components.dockController.setDockSide(side);contextMenu.discard();}
if(Components.dockController.dockSide()===Components.DockController.State.Undocked&&SDK.targetManager.mainTarget()&&SDK.targetManager.mainTarget().type()===SDK.Target.Type.Frame)
contextMenu.defaultSection().appendAction('inspector_main.focus-debuggee',Common.UIString('Focus debuggee'));contextMenu.defaultSection().appendAction('main.toggle-drawer',UI.inspectorView.drawerVisible()?Common.UIString('Hide console drawer'):Common.UIString('Show console drawer'));contextMenu.appendItemsAtLocation('mainMenu');const moreTools=contextMenu.defaultSection().appendSubMenuItem(Common.UIString('More tools'));const extensions=self.runtime.extensions('view',undefined,true);for(const extension of extensions){const descriptor=extension.descriptor();if(descriptor['persistence']!=='closeable')
continue;if(descriptor['location']!=='drawer-view'&&descriptor['location']!=='panel')
continue;moreTools.defaultSection().appendItem(extension.title(),UI.viewManager.showView.bind(UI.viewManager,descriptor['id']));}
const helpSubMenu=contextMenu.footerSection().appendSubMenuItem(Common.UIString('Help'));helpSubMenu.appendItemsAtLocation('mainMenuHelp');}};Main.Main.PauseListener=class{constructor(){SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerPaused,this._debuggerPaused,this);}
_debuggerPaused(event){SDK.targetManager.removeModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerPaused,this._debuggerPaused,this);const debuggerModel=(event.data);const debuggerPausedDetails=debuggerModel.debuggerPausedDetails();UI.context.setFlavor(SDK.Target,debuggerModel.target());Common.Revealer.reveal(debuggerPausedDetails);}};Main.sendOverProtocol=function(method,params){return new Promise((resolve,reject)=>{Protocol.test.sendRawMessage(method,params,(err,...results)=>{if(err)
return reject(err);return resolve(results);});});};Main.ReloadActionDelegate=class{handleAction(context,actionId){switch(actionId){case'main.debug-reload':Components.reload();return true;}
return false;}};new Main.Main();;self['ConsoleCounters']=self['ConsoleCounters']||{};ConsoleCounters.WarningErrorCounter=class{constructor(){ConsoleCounters.WarningErrorCounter._instanceForTest=this;const countersWrapper=createElement('div');this._toolbarItem=new UI.ToolbarItem(countersWrapper);this._counter=createElement('div');this._counter.addEventListener('click',Common.console.show.bind(Common.console),false);const shadowRoot=UI.createShadowRootWithCoreStyles(this._counter,'console_counters/errorWarningCounter.css');countersWrapper.appendChild(this._counter);this._violationCounter=createElement('div');this._violationCounter.addEventListener('click',()=>{UI.viewManager.showView('audits2');});const violationShadowRoot=UI.createShadowRootWithCoreStyles(this._violationCounter,'console_counters/errorWarningCounter.css');if(Runtime.experiments.isEnabled('spotlight'))
countersWrapper.appendChild(this._violationCounter);this._errors=this._createItem(shadowRoot,'smallicon-error');this._warnings=this._createItem(shadowRoot,'smallicon-warning');if(Runtime.experiments.isEnabled('spotlight'))
this._violations=this._createItem(violationShadowRoot,'smallicon-info');this._titles=[];this._errorCount=-1;this._warningCount=-1;this._violationCount=-1;this._throttler=new Common.Throttler(100);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.ConsoleCleared,this._update,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded,this._update,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageUpdated,this._update,this);this._update();}
_updatedForTest(){}
_createItem(shadowRoot,iconType){const item=createElementWithClass('span','counter-item');const icon=item.createChild('span','','dt-icon-label');icon.type=iconType;const text=icon.createChild('span');shadowRoot.appendChild(item);return{item:item,text:text};}
_updateItem(item,count,first){item.item.classList.toggle('hidden',!count);item.item.classList.toggle('counter-item-first',first);item.text.textContent=count;}
_update(){this._updatingForTest=true;this._throttler.schedule(this._updateThrottled.bind(this));}
_updateThrottled(){const errors=SDK.consoleModel.errors();const warnings=SDK.consoleModel.warnings();const violations=SDK.consoleModel.violations();if(errors===this._errorCount&&warnings===this._warningCount&&violations===this._violationCount)
return Promise.resolve();this._errorCount=errors;this._warningCount=warnings;this._violationCount=violations;this._titles=[];this._counter.classList.toggle('hidden',!(errors||warnings));this._violationCounter.classList.toggle('hidden',!violations);this._toolbarItem.setVisible(!!(errors||warnings||violations));let errorCountTitle='';if(errors===1)
errorCountTitle=ls`${errors} error`;else
errorCountTitle=ls`${errors} errors`;this._updateItem(this._errors,errors,false);if(errors)
this._titles.push(errorCountTitle);let warningCountTitle='';if(warnings===1)
warningCountTitle=ls`${warnings} warning`;else
warningCountTitle=ls`${warnings} warnings`;this._updateItem(this._warnings,warnings,!errors);if(warnings)
this._titles.push(warningCountTitle);if(Runtime.experiments.isEnabled('spotlight')){let violationCountTitle='';if(violations===1)
violationCountTitle=ls`${violations} violation`;else
violationCountTitle=ls`${violations} violations`;this._updateItem(this._violations,violations,true);this._violationCounter.title=violationCountTitle;}
this._counter.title=this._titles.join(', ');UI.inspectorView.toolbarItemResized();this._updatingForTest=false;this._updatedForTest();return Promise.resolve();}
item(){return this._toolbarItem;}};;;Runtime.cachedResources["ui/checkboxTextLabel.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n padding: 0;\n margin: 0;\n display: inline-flex;\n flex-shrink: 0;\n align-items: center !important;\n}\n\ninput {\n height: 12px;\n width: 12px;\n flex-shrink: 0;\n}\n\ninput:focus {\n outline: auto 5px -webkit-focus-ring-color;\n}\n\ninput.dt-checkbox-themed {\n -webkit-appearance: none;\n margin: auto 5px auto 2px;\n border: 1px solid rgb(45, 45, 45);\n border-radius: 3px;\n background-color: rgb(102, 102, 102);\n}\n\ninput.dt-checkbox-themed:after {\n content: '';\n line-height: 10px;\n position: absolute;\n cursor: pointer;\n width: 12px;\n height: 12px;\n background: none;\n}\n\ninput.dt-checkbox-themed:checked:after {\n background-color: #333;\n}\n\ninput.dt-checkbox-themed:after {\n -webkit-mask-image: url(Images/checkboxCheckmark.png);\n -webkit-mask-size: 11px 11px;\n -webkit-mask-position: 0 0;\n}\n\n:host-context(.-theme-with-dark-background) input:not(.dt-checkbox-themed) {\n filter: invert(80%);\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\ninput.dt-checkbox-themed:after {\n -webkit-mask-image: url(Images/checkboxCheckmark_2x.png);\n}\n\n} /* media */\n\n.dt-checkbox-text {\n margin-left: 3px;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.dt-checkbox-subtitle {\n color: gray;\n}\n\n/*# sourceURL=ui/checkboxTextLabel.css */";Runtime.cachedResources["ui/closeButton.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.close-button {\n width: 14px;\n height: 14px;\n cursor: default;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.hover-icon, .active-icon {\n display: none;\n}\n\n.close-button:hover .default-icon, .close-button:active .default-icon {\n display: none;\n}\n\n.close-button:hover .hover-icon {\n display: block;\n}\n\n.close-button:active .hover-icon {\n display: none !important;\n}\n\n.close-button:active .active-icon {\n display: block;\n}\n\n/*# sourceURL=ui/closeButton.css */";Runtime.cachedResources["ui/confirmDialog.css"]="/*\n * Copyright (c) 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n padding: 20px;\n}\n\n.message, .button {\n font-size: larger;\n white-space: pre;\n margin: 5px;\n}\n\n.button {\n text-align: center;\n margin-top: 10px;\n}\n\n.button button {\n min-width: 80px;\n}\n\n.reason {\n color: #8b0000;\n}\n\n/*# sourceURL=ui/confirmDialog.css */";Runtime.cachedResources["ui/dialog.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n box-shadow: var(--drop-shadow);\n background: white;\n justify-content: flex-start;\n align-items: stretch;\n display: flex;\n}\n\n.dialog-close-button {\n position: absolute;\n right: 9px;\n top: 9px;\n z-index: 1;\n}\n/*# sourceURL=ui/dialog.css */";Runtime.cachedResources["ui/dropTarget.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n display: flex;\n background-color: rgba(255,255,255,0.8);\n z-index: 1000;\n}\n\n.drop-target-message {\n flex: auto;\n font-size: 30px;\n color: #999;\n display: flex;\n justify-content: center;\n align-items: center;\n margin: 20px;\n border: 4px dashed #d
* Copyright 2014 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' ">
<script type="text/javascript" src="toolbox.js"></script>
<script>Runtime.startApplication('toolbox');</script>
</head>
<body class="undocked" id="-blink-dev-tools"></body>
</html>
const allDescriptors=[];let applicationDescriptor;const _loadedScripts={};for(const k of[]){}
(function(){const baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();const REMOTE_MODULE_FALLBACK_REVISION='@010ddcfda246975d194964ccf20038ebbdec6084';var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(let i=0;i<descriptors.length;++i)
this._registerModule(descriptors[i]);}
static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){const xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE)
return;const status=/^HTTP\/1.1 404/.test(e.target.response)?404:xhr.status;if([0,200,304].indexOf(status)===-1)
reject(new Error('While loading from url '+url+' server responded with a status of '+status));else
fulfill(e.target.response);}
xhr.send(null);}}
static loadResourcePromiseWithFallback(url){return Runtime.loadResourcePromise(url).catch(err=>{const urlWithFallbackVersion=url.replace(/@[0-9a-f]{40}/,REMOTE_MODULE_FALLBACK_REVISION);if(urlWithFallbackVersion===url||!url.includes('audits2_worker_module'))
throw err;return Runtime.loadResourcePromise(urlWithFallbackVersion);});}
static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1)
return path;const normalizedSegments=[];const segments=path.split('/');for(let i=0;i<segments.length;i++){const segment=segments[i];if(segment==='.')
continue;else if(segment==='..')
normalizedSegments.pop();else if(segment)
normalizedSegments.push(segment);}
let normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/')
return normalizedPath;if(path[0]==='/'&&normalizedPath)
normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..'))
normalizedPath=normalizedPath+'/';return normalizedPath;}
static _loadScriptsPromise(scriptNames,base){const promises=[];const urls=[];const sources=new Array(scriptNames.length);let scriptToEval=0;for(let i=0;i<scriptNames.length;++i){const scriptName=scriptNames[i];let sourceURL=(base||self._importScriptPathPrefix)+scriptName;const schemaIndex=sourceURL.indexOf('://')+3;let pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1)
pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL])
continue;urls.push(sourceURL);const loadResourcePromise=base?Runtime.loadResourcePromiseWithFallback(sourceURL):Runtime.loadResourcePromise(sourceURL);promises.push(loadResourcePromise.then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));}
return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}}
function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;}
self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}}
static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;}
const sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}}
static async appStarted(){return Runtime._appStartedPromise;}
static async startApplication(appName){console.timeStamp('Runtime.startApplication');const allDescriptorsByName={};for(let i=0;i<allDescriptors.length;++i){const d=allDescriptors[i];allDescriptorsByName[d['name']]=d;}
if(!applicationDescriptor){let data=await Runtime.loadResourcePromise(appName+'.json');applicationDescriptor=JSON.parse(data);let descriptor=applicationDescriptor;while(descriptor.extends){data=await Runtime.loadResourcePromise(descriptor.extends+'.json');descriptor=JSON.parse(data);applicationDescriptor.modules=descriptor.modules.concat(applicationDescriptor.modules);}}
const configuration=applicationDescriptor.modules;const moduleJSONPromises=[];const coreModuleNames=[];for(let i=0;i<configuration.length;++i){const descriptor=configuration[i];const name=descriptor['name'];const moduleJSON=allDescriptorsByName[name];if(moduleJSON)
moduleJSONPromises.push(Promise.resolve(moduleJSON));else
moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart')
coreModuleNames.push(name);}
const moduleDescriptors=await Promise.all(moduleJSONPromises);for(let i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';}
self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames)
await self.runtime._loadAutoStartModules(coreModuleNames);Runtime._appStartedPromiseCallback();}
static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}}
static queryParam(name){return Runtime._queryParamsObject.get(name);}
static queryParamsString(){return location.search;}
static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}}
static _assert(value,message){if(value)
return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);}
static setPlatform(platform){Runtime._platform=platform;}
static _isDescriptorEnabled(descriptor){const activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*')
return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1)))
return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment))
return false;const condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition))
return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1)))
return false;return true;}
static resolveSourceURL(path){let sourceURL=self.location.href;if(self.location.search)
sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';}
static setL10nCallback(localizationFunction){Runtime._l10nCallback=localizationFunction;}
useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend'))
Runtime._remoteBase+='debug/';}
_registerModule(descriptor){const module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;}
loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();}
_loadAutoStartModules(moduleNames){const promises=[];for(let i=0;i<moduleNames.length;++i)
promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);}
_checkExtensionApplicability(extension,predicate){if(!predicate)
return false;const contextTypes=extension.descriptor().contextTypes;if(!contextTypes)
return true;for(let i=0;i<contextTypes.length;++i){const contextType=this._resolve(contextTypes[i]);const isMatching=!!contextType&&predicate(contextType);if(isMatching)
return true;}
return false;}
isExtensionApplicableToContext(extension,context){if(!context)
return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}}
isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes)
return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}}
extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type)
return false;if(!extension.enabled())
return false;return!context||extension.isApplicable(context);}
function orderComparator(extension1,extension2){const order1=extension1.descriptor()['order']||0;const order2=extension2.descriptor()['order']||0;return order1-order2;}
function titleComparator(extension1,extension2){const title1=extension1.title()||'';const title2=extension2.title()||'';return title1.localeCompare(title2);}}
extension(type,context){return this.extensions(type,context)[0]||null;}
allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));}
_resolve(typeName){if(!this._cachedTypeClasses[typeName]){const path=typeName.split('.');let object=self;for(let i=0;object&&(i<path.length);++i)
object=object[path[i]];if(object)
this._cachedTypeClasses[typeName]=(object);}
return this._cachedTypeClasses[typeName]||null;}
sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction&&Object.getOwnPropertySymbols(constructorFunction).includes(Runtime._instanceSymbol))
return constructorFunction[Runtime._instanceSymbol];const instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject=new URLSearchParams(Runtime.queryParamsString());Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();const extensions=(descriptor.extensions);for(let i=0;extensions&&i<extensions.length;++i){const extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);}
this._loadedForTest=false;}
name(){return this._name;}
enabled(){return Runtime._isDescriptorEnabled(this._descriptor);}
resource(name){const fullName=this._name+'/'+name;const content=Runtime.cachedResources[fullName];if(!content)
throw new Error(fullName+' not preloaded. Check module.json');return content;}
_loadPromise(){if(!this.enabled())
return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise)
return this._pendingLoadPromise;const dependencies=this._descriptor.dependencies;const dependencyPromises=[];for(let i=0;dependencies&&i<dependencies.length;++i)
dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;}
_loadResources(){const resources=this._descriptor['resources'];if(!resources||!resources.length)
return Promise.resolve();const promises=[];for(let i=0;i<resources.length;++i){const url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));}
return Promise.all(promises).then(undefined);}
_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length)
return Promise.resolve();const specialCases={'sdk':'SDK','js_sdk':'JSSDK','browser_sdk':'BrowserSDK','ui':'UI','object_ui':'ObjectUI','javascript_metadata':'JavaScriptMetadata','perf_ui':'PerfUI','har_importer':'HARImporter','sdk_test_runner':'SDKTestRunner','cpu_profiler_test_runner':'CPUProfilerTestRunner'};const namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());}
_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);}
_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;}
substituteURL(value){const base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;}
descriptor(){return this._descriptor;}
module(){return this._module;}
enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());}
_typeClass(){if(!this._hasTypeClass)
return null;return this._module._manager._resolve(this._type.substring(1));}
isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);}
instance(){return this._module._loadPromise().then(this._createInstance.bind(this));}
canInstantiate(){return!!(this._className||this._factoryName);}
_createInstance(){const className=this._className||this._factoryName;if(!className)
throw new Error('Could not instantiate extension with no class');const constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function))
throw new Error('Could not instantiate: '+className);if(this._className)
return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);}
title(){const title=this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];if(title&&Runtime._l10nCallback)
return Runtime._l10nCallback(title);return title;}
hasContextType(contextType){const contextTypes=this.descriptor().contextTypes;if(!contextTypes)
return false;for(let i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i]))
return true;}
return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
allConfigurableExperiments(){const result=[];for(let i=0;i<this._experiments.length;i++){const experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name])
result.push(experiment);}
return result;}
supportEnabled(){return this._supportEnabled;}
_setExperimentsSetting(value){if(!self.localStorage)
return;self.localStorage['experiments']=JSON.stringify(value);}
register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));}
isEnabled(experimentName){this._checkExperiment(experimentName);if(Runtime._experimentsSetting()[experimentName]===false)
return false;if(this._enabledTransiently[experimentName])
return true;if(!this.supportEnabled())
return false;return!!Runtime._experimentsSetting()[experimentName];}
setEnabled(experimentName,enabled){this._checkExperiment(experimentName);const experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);}
setDefaultExperiments(experimentNames){for(let i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}}
enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;}
clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
cleanUpStaleExperiments(){const experimentsSetting=Runtime._experimentsSetting();const cleanedUpExperimentSetting={};for(let i=0;i<this._experiments.length;++i){const experimentName=this._experiments[i].name;if(experimentsSetting[experimentName])
cleanedUpExperimentSetting[experimentName]=true;}
this._setExperimentsSetting(cleanedUpExperimentSetting);}
_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;}
isEnabled(){return this._experiments.isEnabled(this.name);}
setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._appStartedPromiseCallback;Runtime._appStartedPromise=new Promise(fulfil=>Runtime._appStartedPromiseCallback=fulfil);Runtime._l10nCallback;Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){const versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch)
Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){}
ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;allDescriptors.push(...[{"dependencies":[],"name":"platform"},{"dependencies":["platform","dom_extension"],"name":"toolbox_bootstrap"},{"dependencies":["platform"],"name":"dom_extension"}]);applicationDescriptor={"has_html":true,"modules":[{"type":"autostart","name":"platform"},{"type":"autostart","name":"toolbox_bootstrap"},{"type":"autostart","name":"dom_extension"}]}
self['Platform']=self['Platform']||{};let ArrayLike;function mod(m,n){return((m%n)+n)%n;}
String.prototype.findAll=function(string){const matches=[];let i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);}
return matches;};String.prototype.reverse=function(){return this.split('').reverse().join('');};String.prototype.replaceControlCharacters=function(){return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,'<27>');};String.prototype.isWhitespace=function(){return/^\s*$/.test(this);};String.prototype.computeLineEndings=function(){const endings=this.findAll('\n');endings.push(this.length);return endings;};String.prototype.escapeCharacters=function(chars){let foundChar=false;for(let i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}}
if(!foundChar)
return String(this);let result='';for(let i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1)
result+='\\';result+=this.charAt(i);}
return result;};String.regexSpecialCharacters=function(){return'^[]{}()\\.^$*+?|-,';};String.prototype.escapeForRegExp=function(){return this.escapeCharacters(String.regexSpecialCharacters());};String.filterRegex=function(query){const toEscape=String.regexSpecialCharacters();let regexString='';for(let i=0;i<query.length;++i){let c=query.charAt(i);if(toEscape.indexOf(c)!==-1)
c='\\'+c;if(i)
regexString+='[^\\0'+c+']*';regexString+=c;}
return new RegExp(regexString,'i');};String.escapeInvalidUnicodeCharacters=function(text){if(!String._invalidCharactersRegExp){let invalidCharacters='';for(let i=0xfffe;i<=0x10ffff;i+=0x10000)
invalidCharacters+=String.fromCodePoint(i,i+1);String._invalidCharactersRegExp=new RegExp(`[${invalidCharacters}\uD800-\uDFFF\uFDD0-\uFDEF]`,'gu');}
let result='';let lastPos=0;while(true){const match=String._invalidCharactersRegExp.exec(text);if(!match)
break;result+=text.substring(lastPos,match.index)+'\\u'+text.charCodeAt(match.index).toString(16);if(match.index+1<String._invalidCharactersRegExp.lastIndex)
result+='\\u'+text.charCodeAt(match.index+1).toString(16);lastPos=String._invalidCharactersRegExp.lastIndex;}
return result+text.substring(lastPos);};String.prototype.escapeHTML=function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');};String.prototype.unescapeHTML=function(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&#58;/g,':').replace(/&quot;/g,'"').replace(/&#60;/g,'<').replace(/&#62;/g,'>').replace(/&amp;/g,'&');};String.prototype.collapseWhitespace=function(){return this.replace(/[\s\xA0]+/g,' ');};String.prototype.trimMiddle=function(maxLength){if(this.length<=maxLength)
return String(this);let leftHalf=maxLength>>1;let rightHalf=maxLength-leftHalf-1;if(this.codePointAt(this.length-rightHalf-1)>=0x10000){--rightHalf;++leftHalf;}
if(leftHalf>0&&this.codePointAt(leftHalf-1)>=0x10000)
--leftHalf;return this.substr(0,leftHalf)+'\u2026'+this.substr(this.length-rightHalf,rightHalf);};String.prototype.trimEnd=function(maxLength){if(this.length<=maxLength)
return String(this);return this.substr(0,maxLength-1)+'\u2026';};String.prototype.trimURL=function(baseURLDomain){let result=this.replace(/^(https|http|file):\/\//i,'');if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase()))
result=result.substr(baseURLDomain.length);}
return result;};String.prototype.toTitleCase=function(){return this.substring(0,1).toUpperCase()+this.substring(1);};String.prototype.compareTo=function(other){if(this>other)
return 1;if(this<other)
return-1;return 0;};String.prototype.removeURLFragment=function(){let fragmentIndex=this.indexOf('#');if(fragmentIndex===-1)
fragmentIndex=this.length;return this.substring(0,fragmentIndex);};String.hashCode=function(string){if(!string)
return 0;const p=((1<<30)*4-5);const z=0x5033d967;const z2=0x59d2f15d;let s=0;let zi=1;for(let i=0;i<string.length;i++){const xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;}
s=(s+zi*(p-1))%p;return Math.abs(s|0);};String.isDigitAt=function(string,index){const c=string.charCodeAt(index);return(48<=c&&c<=57);};String.prototype.toBase64=function(){function encodeBits(b){return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;}
const encoder=new TextEncoder();const data=encoder.encode(this.toString());const n=data.length;let encoded='';if(n===0)
return encoded;let shift;let v=0;for(let i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}}
if(shift===0)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);else if(shift===1)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);return encoded;};String.naturalOrderComparator=function(a,b){const chunk=/^\d+|^\D+/;let chunka,chunkb,anum,bnum;while(1){if(a){if(!b)
return 1;}else{if(b)
return-1;else
return 0;}
chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum)
return-1;if(bnum&&!anum)
return 1;if(anum&&bnum){const diff=chunka-chunkb;if(diff)
return diff;if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb)
return chunka.length-chunkb.length;else
return chunkb.length-chunka.length;}}else if(chunka!==chunkb){return(chunka<chunkb)?-1:1;}
a=a.substring(chunka.length);b=b.substring(chunkb.length);}};String.caseInsensetiveComparator=function(a,b){a=a.toUpperCase();b=b.toUpperCase();if(a===b)
return 0;return a>b?1:-1;};Number.constrain=function(num,min,max){if(num<min)
num=min;else if(num>max)
num=max;return num;};Number.gcd=function(a,b){if(b===0)
return a;else
return Number.gcd(b,a%b);};Number.toFixedIfFloating=function(value){if(!value||isNaN(value))
return value;const number=Number(value);return number%1?number.toFixed(3):String(number);};Date.prototype.isValid=function(){return!isNaN(this.getTime());};Date.prototype.toISO8601Compact=function(){function leadZero(x){return(x>9?'':'0')+x;}
return this.getFullYear()+leadZero(this.getMonth()+1)+leadZero(this.getDate())+'T'+
leadZero(this.getHours())+leadZero(this.getMinutes())+leadZero(this.getSeconds());};Object.defineProperty(Array.prototype,'remove',{value:function(value,firstOnly){let index=this.indexOf(value);if(index===-1)
return false;if(firstOnly){this.splice(index,1);return true;}
for(let i=index+1,n=this.length;i<n;++i){if(this[i]!==value)
this[index++]=this[i];}
this.length=index;return true;}});Object.defineProperty(Array.prototype,'pushAll',{value:function(array){for(let i=0;i<array.length;++i)
this.push(array[i]);}});Object.defineProperty(Array.prototype,'rotate',{value:function(index){const result=[];for(let i=index;i<index+this.length;++i)
result.push(this[i%this.length]);return result;}});Object.defineProperty(Array.prototype,'sortNumbers',{value:function(){function numericComparator(a,b){return a-b;}
this.sort(numericComparator);}});Object.defineProperty(Uint32Array.prototype,'sort',{value:Array.prototype.sort});(function(){const partition={value:function(comparator,left,right,pivotIndex){function swap(array,i1,i2){const temp=array[i1];array[i1]=array[i2];array[i2]=temp;}
const pivotValue=this[pivotIndex];swap(this,right,pivotIndex);let storeIndex=left;for(let i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}}
swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,'partition',partition);Object.defineProperty(Uint32Array.prototype,'partition',partition);const sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight){function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight){if(right<=left)
return;const pivotIndex=Math.floor(Math.random()*(right-left))+left;const pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex)
quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);if(pivotNewIndex<sortWindowRight)
quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);}
if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound)
this.sort(comparator);else
quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);return this;}};Object.defineProperty(Array.prototype,'sortRange',sortRange);Object.defineProperty(Uint32Array.prototype,'sortRange',sortRange);})();Object.defineProperty(Array.prototype,'stableSort',{value:function(comparator){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;const indices=new Array(this.length);for(let i=0;i<this.length;++i)
indices[i]=i;const self=this;function indexComparator(a,b){const result=comparator(self[a],self[b]);return result?result:a-b;}
indices.sort(indexComparator);for(let i=0;i<this.length;++i){if(indices[i]<0||i===indices[i])
continue;let cyclical=i;const saved=this[i];while(true){const next=indices[cyclical];indices[cyclical]=-1;if(next===i){this[cyclical]=saved;break;}else{this[cyclical]=this[next];cyclical=next;}}}
return this;}});Object.defineProperty(Array.prototype,'qselect',{value:function(k,comparator){if(k<0||k>=this.length)
return;if(!comparator){comparator=function(a,b){return a-b;};}
let low=0;let high=this.length-1;for(;;){const pivotPosition=this.partition(comparator,low,high,Math.floor((high+low)/2));if(pivotPosition===k)
return this[k];else if(pivotPosition>k)
high=pivotPosition-1;else
low=pivotPosition+1;}}});Object.defineProperty(Array.prototype,'lowerBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Array.prototype,'upperBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>=0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Uint32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Int32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Int32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,'binaryIndexOf',{value:function(value,comparator){const index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,'select',{value:function(field){const result=new Array(this.length);for(let i=0;i<this.length;++i)
result[i]=this[i][field];return result;}});Object.defineProperty(Array.prototype,'peekLast',{value:function(){return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect){const result=[];let i=0;let j=0;while(i<array1.length&&j<array2.length){const compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue)
result.push(compareValue<=0?array1[i]:array2[j]);if(compareValue<=0)
i++;if(compareValue>=0)
j++;}
if(mergeNotIntersect){while(i<array1.length)
result.push(array1[i++]);while(j<array2.length)
result.push(array2[j++]);}
return result;}
Object.defineProperty(Array.prototype,'intersectOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,'mergeOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg){return String.vsprintf(format,Array.prototype.slice.call(arguments,1));};String.tokenizeFormatString=function(format,formatters){const tokens=[];function addStringToken(str){if(!str)
return;if(tokens.length&&tokens[tokens.length-1].type==='string')
tokens[tokens.length-1].value+=str;else
tokens.push({type:'string',value:str});}
function addSpecifierToken(specifier,precision,substitutionIndex){tokens.push({type:'specifier',specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});}
function addAnsiColor(code){const types={3:'color',9:'colorLight',4:'bgColor',10:'bgColorLight'};const colorCodes=['black','red','green','yellow','blue','magenta','cyan','lightGray','','default'];const colorCodesLight=['darkGray','lightRed','lightGreen','lightYellow','lightBlue','lightMagenta','lightCyan','white',''];const colors={color:colorCodes,colorLight:colorCodesLight,bgColor:colorCodes,bgColorLight:colorCodesLight};const type=types[Math.floor(code/10)];if(!type)
return;const color=colors[type][code%10];if(!color)
return;tokens.push({type:'specifier',specifier:'c',value:{description:(type.startsWith('bg')?'background : ':'color: ')+color}});}
let textStart=0;let substitutionIndex=0;const re=new RegExp(`%%|%(?:(\\d+)\\$)?(?:\\.(\\d*))?([${Object.keys(formatters).join('')}])|\\u001b\\[(\\d+)m`,'g');for(let match=re.exec(format);!!match;match=re.exec(format)){const matchStart=match.index;if(matchStart>textStart)
addStringToken(format.substring(textStart,matchStart));if(match[0]==='%%'){addStringToken('%');}else if(match[0].startsWith('%')){const[_,substitionString,precisionString,specifierString]=match;if(substitionString&&Number(substitionString)>0)
substitutionIndex=Number(substitionString)-1;const precision=precisionString?Number(precisionString):-1;addSpecifierToken(specifierString,precision,substitutionIndex);++substitutionIndex;}else{const code=Number(match[4]);addAnsiColor(code);}
textStart=matchStart+match[0].length;}
addStringToken(format.substring(textStart));return tokens;};String.standardFormatters={d:function(substitution){return!isNaN(substitution)?substitution:0;},f:function(substitution,token){if(substitution&&token.precision>-1)
substitution=substitution.toFixed(token.precision);return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution){return substitution;}};String.vsprintf=function(format,substitutions){return String.format(format,substitutions,String.standardFormatters,'',function(a,b){return a+b;}).formattedResult;};String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat){if(!format||((!substitutions||!substitutions.length)&&format.search(/\u001b\[(\d+)m/)===-1))
return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName(){return'String.format("'+format+'", "'+Array.prototype.join.call(substitutions,'", "')+'")';}
function warn(msg){console.warn(prettyFunctionName()+': '+msg);}
function error(msg){console.error(prettyFunctionName()+': '+msg);}
let result=initialValue;const tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);const usedSubstitutionIndexes={};for(let i=0;i<tokens.length;++i){const token=tokens[i];if(token.type==='string'){result=append(result,token.value);continue;}
if(token.type!=='specifier'){error('Unknown token type "'+token.type+'" found.');continue;}
if(!token.value&&token.substitutionIndex>=substitutions.length){error('not enough substitution arguments. Had '+substitutions.length+' but needed '+
(token.substitutionIndex+1)+', so substitution was skipped.');result=append(result,'%'+(token.precision>-1?token.precision:'')+token.specifier);continue;}
if(!token.value)
usedSubstitutionIndexes[token.substitutionIndex]=true;if(!(token.specifier in formatters)){warn('unsupported format character \u201C'+token.specifier+'\u201D. Treating as a string.');result=append(result,token.value?'':substitutions[token.substitutionIndex]);continue;}
result=append(result,formatters[token.specifier](token.value||substitutions[token.substitutionIndex],token));}
const unusedSubstitutions=[];for(let i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes)
continue;unusedSubstitutions.push(substitutions[i]);}
return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};};function createSearchRegex(query,caseSensitive,isRegex){const regexFlags=caseSensitive?'g':'gi';let regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}}
if(!regexObject)
regexObject=createPlainTextSearchRegex(query,regexFlags);return regexObject;}
function createPlainTextSearchRegex(query,flags){const regexSpecialCharacters=String.regexSpecialCharacters();let regex='';for(let i=0;i<query.length;++i){const c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1)
regex+='\\';regex+=c;}
return new RegExp(regex,flags||'');}
function countRegexMatches(regex,content){let text=content;let result=0;let match;while(text&&(match=regex.exec(text))){if(match[0].length>0)
++result;text=text.substring(match.index+1);}
return result;}
function spacesPadding(spacesCount){return'\u00a0'.repeat(spacesCount);}
function numberToStringWithSpacesPadding(value,symbolsCount){const numberString=value.toString();const paddingLength=Math.max(0,symbolsCount-numberString.length);return spacesPadding(paddingLength)+numberString;}
Set.prototype.valuesArray=function(){return Array.from(this.values());};Set.prototype.firstValue=function(){if(!this.size)
return null;return this.values().next().value;};Set.prototype.addAll=function(iterable){for(const e of iterable)
this.add(e);};Set.prototype.containsAll=function(iterable){for(const e of iterable){if(!this.has(e))
return false;}
return true;};Map.prototype.remove=function(key){const value=this.get(key);this.delete(key);return value;};Map.prototype.valuesArray=function(){return Array.from(this.values());};Map.prototype.keysArray=function(){return Array.from(this.keys());};Map.prototype.inverse=function(){const result=new Multimap();for(const key of this.keys()){const value=this.get(key);result.set(value,key);}
return result;};var Multimap=function(){this._map=new Map();};Multimap.prototype={set:function(key,value){let set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);}
set.add(value);},get:function(key){return this._map.get(key)||new Set();},has:function(key){return this._map.has(key);},hasValue:function(key,value){const set=this._map.get(key);if(!set)
return false;return set.has(value);},get size(){return this._map.size;},delete:function(key,value){const values=this.get(key);if(!values)
return false;const result=values.delete(value);if(!values.size)
this._map.delete(key);return result;},deleteAll:function(key){this._map.delete(key);},keysArray:function(){return this._map.keysArray();},valuesArray:function(){const result=[];const keys=this.keysArray();for(let i=0;i<keys.length;++i)
result.pushAll(this.get(keys[i]).valuesArray());return result;},clear:function(){this._map.clear();}};function loadXHR(url){return new Promise(load);function load(successCallback,failureCallback){function onReadyStateChanged(){if(xhr.readyState!==XMLHttpRequest.DONE)
return;if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;}
xhr.onreadystatechange=null;successCallback(xhr.responseText);}
const xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open('GET',url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}}
function suppressUnused(value){}
self.setImmediate=function(callback){const args=[...arguments].slice(1);Promise.resolve().then(()=>callback(...args));return 0;};Promise.prototype.spread=function(callback){return this.then(spreadPromise);function spreadPromise(arg){return callback.apply(null,arg);}};Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});};Map.prototype.diff=function(other,isEqual){const leftKeys=this.keysArray();const rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);const removed=[];const added=[];const equal=[];let leftIndex=0;let rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){const leftKey=leftKeys[leftIndex];const rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;}
if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;}
added.push(other.get(rightKey));++rightIndex;}
while(leftIndex<leftKeys.length){const leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));}
while(rightIndex<rightKeys.length){const rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));}
return{added:added,removed:removed,equal:equal};};function runOnWindowLoad(callback){function windowLoaded(){self.removeEventListener('DOMContentLoaded',windowLoaded,false);callback();}
if(document.readyState==='complete'||document.readyState==='interactive')
callback();else
self.addEventListener('DOMContentLoaded',windowLoaded,false);}
const _singletonSymbol=Symbol('singleton');function singleton(constructorFunction){if(_singletonSymbol in constructorFunction)
return constructorFunction[_singletonSymbol];const instance=new constructorFunction();constructorFunction[_singletonSymbol]=instance;return instance;}
function base64ToSize(content){if(!content)
return 0;let size=content.length*3/4;if(content[content.length-1]==='=')
size--;if(content.length>1&&content[content.length-2]==='=')
size--;return size;};self['DomExtension']=self['DomExtension']||{};Node.prototype.rangeOfWord=function(offset,stopCharacters,stayWithinNode,direction){let startNode;let startOffset=0;let endNode;let endOffset=0;if(!stayWithinNode)
stayWithinNode=this;if(!direction||direction==='backward'||direction==='both'){let node=this;while(node){if(node===stayWithinNode){if(!startNode)
startNode=stayWithinNode;break;}
if(node.nodeType===Node.TEXT_NODE){const start=(node===this?(offset-1):(node.nodeValue.length-1));for(let i=start;i>=0;--i){if(stopCharacters.indexOf(node.nodeValue[i])!==-1){startNode=node;startOffset=i+1;break;}}}
if(startNode)
break;node=node.traversePreviousNode(stayWithinNode);}
if(!startNode){startNode=stayWithinNode;startOffset=0;}}else{startNode=this;startOffset=offset;}
if(!direction||direction==='forward'||direction==='both'){let node=this;while(node){if(node===stayWithinNode){if(!endNode)
endNode=stayWithinNode;break;}
if(node.nodeType===Node.TEXT_NODE){const start=(node===this?offset:0);for(let i=start;i<node.nodeValue.length;++i){if(stopCharacters.indexOf(node.nodeValue[i])!==-1){endNode=node;endOffset=i;break;}}}
if(endNode)
break;node=node.traverseNextNode(stayWithinNode);}
if(!endNode){endNode=stayWithinNode;endOffset=stayWithinNode.nodeType===Node.TEXT_NODE?stayWithinNode.nodeValue.length:stayWithinNode.childNodes.length;}}else{endNode=this;endOffset=offset;}
const result=this.ownerDocument.createRange();result.setStart(startNode,startOffset);result.setEnd(endNode,endOffset);return result;};Node.prototype.traverseNextTextNode=function(stayWithin){let node=this.traverseNextNode(stayWithin);if(!node)
return null;const nonTextTags={'STYLE':1,'SCRIPT':1};while(node&&(node.nodeType!==Node.TEXT_NODE||nonTextTags[node.parentElement.nodeName]))
node=node.traverseNextNode(stayWithin);return node;};Element.prototype.positionAt=function(x,y,relativeTo){let shift={x:0,y:0};if(relativeTo)
shift=relativeTo.boxInWindow(this.ownerDocument.defaultView);if(typeof x==='number')
this.style.setProperty('left',(shift.x+x)+'px');else
this.style.removeProperty('left');if(typeof y==='number')
this.style.setProperty('top',(shift.y+y)+'px');else
this.style.removeProperty('top');if(typeof x==='number'||typeof y==='number')
this.style.setProperty('position','absolute');else
this.style.removeProperty('position');};Element.prototype.isScrolledToBottom=function(){return Math.abs(this.scrollTop+this.clientHeight-this.scrollHeight)<=2;};Node.prototype.enclosingNodeOrSelfWithNodeNameInArray=function(nameArray){for(let node=this;node&&node!==this.ownerDocument;node=node.parentNodeOrShadowHost()){for(let i=0;i<nameArray.length;++i){if(node.nodeName.toLowerCase()===nameArray[i].toLowerCase())
return node;}}
return null;};Node.prototype.enclosingNodeOrSelfWithNodeName=function(nodeName){return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);};Node.prototype.enclosingNodeOrSelfWithClass=function(className,stayWithin){return this.enclosingNodeOrSelfWithClassList([className],stayWithin);};Node.prototype.enclosingNodeOrSelfWithClassList=function(classNames,stayWithin){for(let node=this;node&&node!==stayWithin&&node!==this.ownerDocument;node=node.parentNodeOrShadowHost()){if(node.nodeType===Node.ELEMENT_NODE){let containsAll=true;for(let i=0;i<classNames.length&&containsAll;++i){if(!node.classList.contains(classNames[i]))
containsAll=false;}
if(containsAll)
return(node);}}
return null;};Node.prototype.parentElementOrShadowHost=function(){if(this.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&this.host)
return(this.host);const node=this.parentNode;if(!node)
return null;if(node.nodeType===Node.ELEMENT_NODE)
return(node);if(node.nodeType===Node.DOCUMENT_FRAGMENT_NODE)
return(node.host);return null;};Node.prototype.parentNodeOrShadowHost=function(){if(this.parentNode)
return this.parentNode;if(this.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&this.host)
return this.host;return null;};Node.prototype.getComponentSelection=function(){let parent=this.parentNode;while(parent&&parent.nodeType!==Node.DOCUMENT_FRAGMENT_NODE)
parent=parent.parentNode;return parent instanceof ShadowRoot?parent.getSelection():this.window().getSelection();};Node.prototype.hasSelection=function(){if(this instanceof Element){const slots=this.querySelectorAll('slot');for(const slot of slots){if(Array.prototype.some.call(slot.assignedNodes(),node=>node.hasSelection()))
return true;}}
const selection=this.getComponentSelection();if(selection.type!=='Range')
return false;return selection.containsNode(this,true)||selection.anchorNode.isSelfOrDescendant(this)||selection.focusNode.isSelfOrDescendant(this);};Node.prototype.window=function(){return(this.ownerDocument.defaultView);};Element.prototype.removeChildren=function(){if(this.firstChild)
this.textContent='';};function createElement(tagName,customElementType){return document.createElement(tagName,{is:customElementType});}
function createTextNode(data){return document.createTextNode(data);}
Document.prototype.createElementWithClass=function(elementName,className,customElementType){const element=this.createElement(elementName,{is:customElementType});if(className)
element.className=className;return element;};function createElementWithClass(elementName,className,customElementType){return document.createElementWithClass(elementName,className,customElementType);}
Document.prototype.createSVGElement=function(childType,className){const element=this.createElementNS('http://www.w3.org/2000/svg',childType);if(className)
element.setAttribute('class',className);return element;};function createSVGElement(childType,className){return document.createSVGElement(childType,className);}
function createDocumentFragment(){return document.createDocumentFragment();}
Element.prototype.createChild=function(elementName,className,customElementType){const element=this.ownerDocument.createElementWithClass(elementName,className,customElementType);this.appendChild(element);return element;};DocumentFragment.prototype.createChild=Element.prototype.createChild;Element.prototype.createTextChild=function(text){const element=this.ownerDocument.createTextNode(text);this.appendChild(element);return element;};DocumentFragment.prototype.createTextChild=Element.prototype.createTextChild;Element.prototype.createTextChildren=function(var_args){for(let i=0,n=arguments.length;i<n;++i)
this.createTextChild(arguments[i]);};DocumentFragment.prototype.createTextChildren=Element.prototype.createTextChildren;Element.prototype.totalOffsetLeft=function(){return this.totalOffset().left;};Element.prototype.totalOffsetTop=function(){return this.totalOffset().top;};Element.prototype.totalOffset=function(){const rect=this.getBoundingClientRect();return{left:rect.left,top:rect.top};};Element.prototype.createSVGChild=function(childType,className){const child=this.ownerDocument.createSVGElement(childType,className);this.appendChild(child);return child;};var AnchorBox=class{constructor(x,y,width,height){this.x=x||0;this.y=y||0;this.width=width||0;this.height=height||0;}
contains(x,y){return x>=this.x&&x<=this.x+this.width&&y>=this.y&&y<=this.y+this.height;}};AnchorBox.prototype.relativeTo=function(box){return new AnchorBox(this.x-box.x,this.y-box.y,this.width,this.height);};AnchorBox.prototype.relativeToElement=function(element){return this.relativeTo(element.boxInWindow(element.ownerDocument.defaultView));};AnchorBox.prototype.equals=function(anchorBox){return!!anchorBox&&this.x===anchorBox.x&&this.y===anchorBox.y&&this.width===anchorBox.width&&this.height===anchorBox.height;};Element.prototype.boxInWindow=function(targetWindow){targetWindow=targetWindow||this.ownerDocument.defaultView;const anchorBox=new AnchorBox();let curElement=this;let curWindow=this.ownerDocument.defaultView;while(curWindow&&curElement){anchorBox.x+=curElement.totalOffsetLeft();anchorBox.y+=curElement.totalOffsetTop();if(curWindow===targetWindow)
break;curElement=curWindow.frameElement;curWindow=curWindow.parent;}
anchorBox.width=Math.min(this.offsetWidth,targetWindow.innerWidth-anchorBox.x);anchorBox.height=Math.min(this.offsetHeight,targetWindow.innerHeight-anchorBox.y);return anchorBox;};Event.prototype.consume=function(preventDefault){this.stopImmediatePropagation();if(preventDefault)
this.preventDefault();this.handled=true;};Text.prototype.select=function(start,end){start=start||0;end=end||this.textContent.length;if(start<0)
start=end+start;const selection=this.getComponentSelection();selection.removeAllRanges();const range=this.ownerDocument.createRange();range.setStart(this,start);range.setEnd(this,end);selection.addRange(range);return this;};Element.prototype.selectionLeftOffset=function(){const selection=this.getComponentSelection();if(!selection.containsNode(this,true))
return null;let leftOffset=selection.anchorOffset;let node=selection.anchorNode;while(node!==this){while(node.previousSibling){node=node.previousSibling;leftOffset+=node.textContent.length;}
node=node.parentNodeOrShadowHost();}
return leftOffset;};Node.prototype.appendChildren=function(var_args){for(let i=0,n=arguments.length;i<n;++i)
this.appendChild(arguments[i]);};Node.prototype.deepTextContent=function(){return this.childTextNodes().map(function(node){return node.textContent;}).join('');};Node.prototype.childTextNodes=function(){let node=this.traverseNextTextNode(this);const result=[];const nonTextTags={'STYLE':1,'SCRIPT':1};while(node){if(!nonTextTags[node.parentElement.nodeName])
result.push(node);node=node.traverseNextTextNode(this);}
return result;};Node.prototype.isAncestor=function(node){if(!node)
return false;let currentNode=node.parentNodeOrShadowHost();while(currentNode){if(this===currentNode)
return true;currentNode=currentNode.parentNodeOrShadowHost();}
return false;};Node.prototype.isDescendant=function(descendant){return!!descendant&&descendant.isAncestor(this);};Node.prototype.isSelfOrAncestor=function(node){return!!node&&(node===this||this.isAncestor(node));};Node.prototype.isSelfOrDescendant=function(node){return!!node&&(node===this||this.isDescendant(node));};Node.prototype.traverseNextNode=function(stayWithin){if(this.shadowRoot)
return this.shadowRoot;const distributedNodes=this instanceof HTMLSlotElement?this.assignedNodes():[];if(distributedNodes.length)
return distributedNodes[0];if(this.firstChild)
return this.firstChild;let node=this;while(node){if(stayWithin&&node===stayWithin)
return null;const sibling=nextSibling(node);if(sibling)
return sibling;node=node.assignedSlot||node.parentNodeOrShadowHost();}
function nextSibling(node){if(!node.assignedSlot)
return node.nextSibling;const distributedNodes=node.assignedSlot.assignedNodes();const position=Array.prototype.indexOf.call(distributedNodes,node);if(position+1<distributedNodes.length)
return distributedNodes[position+1];return null;}
return null;};Node.prototype.traversePreviousNode=function(stayWithin){if(stayWithin&&this===stayWithin)
return null;let node=this.previousSibling;while(node&&node.lastChild)
node=node.lastChild;if(node)
return node;return this.parentNodeOrShadowHost();};Node.prototype.setTextContentTruncatedIfNeeded=function(text,placeholder){const maxTextContentLength=10000;if(typeof text==='string'&&text.length>maxTextContentLength){this.textContent=typeof placeholder==='string'?placeholder:text.trimMiddle(maxTextContentLength);return true;}
this.textContent=text;return false;};Event.prototype.deepElementFromPoint=function(){if(!this.which&&!this.pageX&&!this.pageY&&!this.clientX&&!this.clientY&&!this.movementX&&!this.movementY)
return null;const root=this.target&&this.target.getComponentRoot();return root?root.deepElementFromPoint(this.pageX,this.pageY):null;};Document.prototype.deepElementFromPoint=function(x,y){let container=this;let node=null;while(container){const innerNode=container.elementFromPoint(x,y);if(!innerNode||node===innerNode)
break;node=innerNode;container=node.shadowRoot;}
return node;};DocumentFragment.prototype.deepElementFromPoint=Document.prototype.deepElementFromPoint;Document.prototype.deepActiveElement=function(){let activeElement=this.activeElement;while(activeElement&&activeElement.shadowRoot&&activeElement.shadowRoot.activeElement)
activeElement=activeElement.shadowRoot.activeElement;return activeElement;};DocumentFragment.prototype.deepActiveElement=Document.prototype.deepActiveElement;Element.prototype.hasFocus=function(){const root=this.getComponentRoot();return!!root&&this.isSelfOrAncestor(root.activeElement);};Node.prototype.getComponentRoot=function(){let node=this;while(node&&node.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&node.nodeType!==Node.DOCUMENT_NODE)
node=node.parentNode;return(node);};function isEnterKey(event){return event.keyCode!==229&&event.key==='Enter';}
function isEscKey(event){return event.keyCode===27;}
(function(){const originalToggle=DOMTokenList.prototype.toggle;DOMTokenList.prototype['toggle']=function(token,force){if(arguments.length===1)
force=!this.contains(token);return originalToggle.call(this,token,!!force);};})();;self['ToolboxBootstrap']=self['ToolboxBootstrap']||{};(function(){function toolboxLoaded(){if(!window.opener)
return;const app=window.opener['Emulation']['AdvancedApp']['_instance']();app['toolboxLoaded'](document);}
runOnWindowLoad(toolboxLoaded);})();;;<!--
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
<meta name="referrer" content="no-referrer">
<script type="text/javascript" src="shell.js"></script>
<script type="text/javascript" src="worker_app.js"></script>
<script>Runtime.startApplication('worker_app');</script>
</head>
<body class="undocked" id="-blink-dev-tools"></body>
</html>
allDescriptors.push(...[{"dependencies":["common","sdk","ui","protocol"],"extensions":[{"defaultValue":[],"type":"setting","settingName":"customNetworkConditions","settingType":"array"},{"category":"Network","tags":"device, throttling","title":"Go offline","className":"MobileThrottling.ThrottlingManager.ActionDelegate","actionId":"network-conditions.network-offline","type":"action"},{"category":"Network","tags":"device, throttling","title":"Enable slow 3G throttling","className":"MobileThrottling.ThrottlingManager.ActionDelegate","actionId":"network-conditions.network-low-end-mobile","type":"action"},{"category":"Network","tags":"device, throttling","title":"Enable fast 3G throttling","className":"MobileThrottling.ThrottlingManager.ActionDelegate","actionId":"network-conditions.network-mid-tier-mobile","type":"action"},{"category":"Network","tags":"device, throttling","title":"Go online","className":"MobileThrottling.ThrottlingManager.ActionDelegate","actionId":"network-conditions.network-online","type":"action"},{"title":"Throttling","settings":["customNetworkConditions"],"id":"throttling-conditions","className":"MobileThrottling.ThrottlingSettingsTab","location":"settings-view","type":"view","order":35}],"name":"mobile_throttling"},{"dependencies":["common","browser_sdk"],"name":"har_importer","scripts":["har_importer_module.js"]},{"dependencies":["components","extensions","inline_editor","color_picker","event_listeners"],"extensions":[{"title":"Elements","id":"elements","className":"Elements.ElementsPanel","location":"panel","type":"view","order":10},{"className":"Elements.ElementsPanel.ContextMenuProvider","contextTypes":["SDK.RemoteObject","SDK.DOMNode","SDK.DeferredDOMNode"],"type":"@UI.ContextMenu.Provider"},{"className":"Elements.ElementsTreeOutline.Renderer","contextTypes":["SDK.DOMNode","SDK.DeferredDOMNode"],"type":"@UI.Renderer"},{"className":"Elements.ElementsPanel.DOMNodeRevealer","contextTypes":["SDK.DOMNode","SDK.DeferredDOMNode","SDK.RemoteObject"],"destination":"Elements panel","type":"@Common.Revealer"},{"className":"Elements.DOMLinkifier.Linkifier","contextTypes":["SDK.DOMNode","SDK.DeferredDOMNode"],"type":"@Common.Linkifier"},{"className":"Elements.ElementsPanel.CSSPropertyRevealer","contextTypes":["SDK.CSSProperty"],"destination":"styles sidebar","type":"@Common.Revealer"},{"category":"Elements","title":"Color format:","defaultValue":"original","options":[{"text":"As authored","value":"original","title":"Set color format as authored"},{"raw":true,"text":"HEX: #dac0de","value":"hex","title":"Set color format to HEX"},{"raw":true,"text":"RGB: rgb(128, 255, 255)","value":"rgb","title":"Set color format to RGB"},{"raw":true,"text":"HSL: hsl(300, 80%, 90%)","value":"hsl","title":"Set color format to HSL"}],"settingName":"colorFormat","settingType":"enum","type":"setting","order":0},{"category":"Elements","title":"Show user agent shadow DOM","defaultValue":false,"settingName":"showUAShadowDOM","settingType":"boolean","type":"setting","order":1},{"category":"Elements","title":"Word wrap","defaultValue":true,"options":[{"value":true,"title":"Enable DOM word wrap"},{"value":false,"title":"Disable DOM word wrap"}],"settingName":"domWordWrap","settingType":"boolean","type":"setting","order":2},{"category":"Elements","title":"Show HTML comments","defaultValue":true,"options":[{"value":true,"title":"Show HTML comments"},{"value":false,"title":"Hide HTML comments"}],"settingName":"showHTMLComments","settingType":"boolean","type":"setting","order":3},{"category":"Elements","title":"Reveal DOM node on hover","defaultValue":true,"settingName":"highlightNodeOnHoverInOverlay","settingType":"boolean","type":"setting","order":4},{"category":"Elements","title":"Show detailed inspect tooltip","defaultValue":true,"settingName":"showDetailedInspectTooltip","settingType":"boolean","type":"setting","order":5},{"defaultValue":true,"type":"setting","settingName":"showEventListenersForAncestors","settingType":"boolean"},{"className":"Elements.ElementStatePaneWidget.ButtonProvider","type":"@UI.ToolbarItem.Provider","order":1,"l
self['MobileThrottling']=self['MobileThrottling']||{};MobileThrottling.CPUThrottlingRates={NoThrottling:1,MidTierMobile:4,LowEndMobile:6,};MobileThrottling.Conditions;MobileThrottling.NoThrottlingConditions={title:SDK.NetworkManager.NoThrottlingConditions.title,description:Common.UIString('No throttling'),network:SDK.NetworkManager.NoThrottlingConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.NoThrottling,};MobileThrottling.OfflineConditions={title:SDK.NetworkManager.OfflineConditions.title,description:Common.UIString('No internet connectivity'),network:SDK.NetworkManager.OfflineConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.NoThrottling,};MobileThrottling.LowEndMobileConditions={title:Common.UIString('Low-end mobile'),description:Common.UIString('Slow 3G & 6x CPU slowdown'),network:SDK.NetworkManager.Slow3GConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.LowEndMobile,};MobileThrottling.MidTierMobileConditions={title:Common.UIString('Mid-tier mobile'),description:Common.UIString('Fast 3G & 4x CPU slowdown'),network:SDK.NetworkManager.Fast3GConditions,cpuThrottlingRate:MobileThrottling.CPUThrottlingRates.MidTierMobile,};MobileThrottling.PlaceholderConditions;MobileThrottling.CustomConditions={title:Common.UIString('Custom'),description:Common.UIString('Check Network and Performance panels'),};MobileThrottling.NetworkThrottlingConditionsGroup;MobileThrottling.MobileThrottlingConditionsGroup;MobileThrottling.ConditionsList;MobileThrottling.mobilePresets=[MobileThrottling.MidTierMobileConditions,MobileThrottling.LowEndMobileConditions,MobileThrottling.CustomConditions];MobileThrottling.advancedMobilePresets=[MobileThrottling.OfflineConditions,];MobileThrottling.networkPresets=[SDK.NetworkManager.Fast3GConditions,SDK.NetworkManager.Slow3GConditions,SDK.NetworkManager.OfflineConditions,];MobileThrottling.cpuThrottlingPresets=[MobileThrottling.CPUThrottlingRates.NoThrottling,MobileThrottling.CPUThrottlingRates.MidTierMobile,MobileThrottling.CPUThrottlingRates.LowEndMobile,];;MobileThrottling.MobileThrottlingSelector=class{constructor(populateCallback,selectCallback){this._populateCallback=populateCallback;this._selectCallback=selectCallback;MobileThrottling.throttlingManager().addEventListener(MobileThrottling.ThrottlingManager.Events.RateChanged,this._conditionsChanged,this);SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,this._conditionsChanged,this);this._options=this._populateOptions();this._conditionsChanged();}
optionSelected(conditions){SDK.multitargetNetworkManager.setNetworkConditions(conditions.network);MobileThrottling.throttlingManager().setCPUThrottlingRate(conditions.cpuThrottlingRate);}
_populateOptions(){const disabledGroup={title:Common.UIString('Disabled'),items:[MobileThrottling.NoThrottlingConditions]};const presetsGroup={title:Common.UIString('Presets'),items:MobileThrottling.mobilePresets};const advancedGroup={title:Common.UIString('Advanced'),items:MobileThrottling.advancedMobilePresets};return this._populateCallback([disabledGroup,presetsGroup,advancedGroup]);}
_conditionsChanged(){const networkConditions=SDK.multitargetNetworkManager.networkConditions();const cpuThrottlingRate=MobileThrottling.throttlingManager().cpuThrottlingRate();for(let index=0;index<this._options.length;++index){const option=this._options[index];if(option&&option.network===networkConditions&&option.cpuThrottlingRate===cpuThrottlingRate){this._selectCallback(index);return;}}
this._selectCallback(this._options.indexOf(MobileThrottling.CustomConditions));}};;MobileThrottling.NetworkPanelIndicator=class{constructor(){if(!UI.inspectorView.hasPanel('network'))
return;const manager=SDK.multitargetNetworkManager;manager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,updateVisibility);manager.addEventListener(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged,updateVisibility);manager.addEventListener(SDK.MultitargetNetworkManager.Events.InterceptorsChanged,updateVisibility);updateVisibility();function updateVisibility(){let icon=null;if(manager.isThrottling()){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Network throttling is enabled');}else if(SDK.multitargetNetworkManager.isIntercepting()){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Requests may be rewritten by local overrides');}else if(manager.isBlocking()){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Requests may be blocked');}
UI.inspectorView.setPanelIcon('network',icon);}}};;MobileThrottling.NetworkThrottlingSelector=class{constructor(populateCallback,selectCallback,customNetworkConditionsSetting){this._populateCallback=populateCallback;this._selectCallback=selectCallback;this._customNetworkConditionsSetting=customNetworkConditionsSetting;this._customNetworkConditionsSetting.addChangeListener(this._populateOptions,this);SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,this._networkConditionsChanged,this);this._options;this._populateOptions();}
revealAndUpdate(){Common.Revealer.reveal(this._customNetworkConditionsSetting);this._networkConditionsChanged();}
optionSelected(conditions){SDK.multitargetNetworkManager.setNetworkConditions(conditions);}
_populateOptions(){const disabledGroup={title:Common.UIString('Disabled'),items:[SDK.NetworkManager.NoThrottlingConditions]};const presetsGroup={title:Common.UIString('Presets'),items:MobileThrottling.networkPresets};const customGroup={title:Common.UIString('Custom'),items:this._customNetworkConditionsSetting.get()};this._options=this._populateCallback([disabledGroup,presetsGroup,customGroup]);if(!this._networkConditionsChanged()){for(let i=this._options.length-1;i>=0;i--){if(this._options[i]){this.optionSelected((this._options[i]));break;}}}}
_networkConditionsChanged(){const value=SDK.multitargetNetworkManager.networkConditions();for(let index=0;index<this._options.length;++index){const option=this._options[index];if(option&&option.download===value.download&&option.upload===value.upload&&option.latency===value.latency&&option.title===value.title){this._selectCallback(index);return true;}}
return false;}};;MobileThrottling.ThrottlingSettingsTab=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('mobile_throttling/throttlingSettingsTab.css');this.contentElement.createChild('div','header').textContent=Common.UIString('Network Throttling Profiles');const addButton=UI.createTextButton(Common.UIString('Add custom profile...'),this._addButtonClicked.bind(this),'add-conditions-button');this.contentElement.appendChild(addButton);this._list=new UI.ListWidget(this);this._list.element.classList.add('conditions-list');this._list.registerRequiredCSS('mobile_throttling/throttlingSettingsTab.css');this._list.show(this.contentElement);this._customSetting=Common.moduleSetting('customNetworkConditions');this._customSetting.addChangeListener(this._conditionsUpdated,this);this.setDefaultFocusedElement(addButton);this.contentElement.tabIndex=0;}
wasShown(){super.wasShown();this._conditionsUpdated();}
_conditionsUpdated(){this._list.clear();const conditions=this._customSetting.get();for(let i=0;i<conditions.length;++i)
this._list.appendItem(conditions[i],true);this._list.appendSeparator();}
_addButtonClicked(){this._list.addNewItem(this._customSetting.get().length,{title:'',download:-1,upload:-1,latency:0});}
renderItem(item,editable){const conditions=(item);const element=createElementWithClass('div','conditions-list-item');const title=element.createChild('div','conditions-list-text conditions-list-title');const titleText=title.createChild('div','conditions-list-title-text');titleText.textContent=conditions.title;titleText.title=conditions.title;element.createChild('div','conditions-list-separator');element.createChild('div','conditions-list-text').textContent=MobileThrottling.throughputText(conditions.download);element.createChild('div','conditions-list-separator');element.createChild('div','conditions-list-text').textContent=MobileThrottling.throughputText(conditions.upload);element.createChild('div','conditions-list-separator');element.createChild('div','conditions-list-text').textContent=Common.UIString('%dms',conditions.latency);return element;}
removeItemRequested(item,index){const list=this._customSetting.get();list.splice(index,1);this._customSetting.set(list);}
commitEdit(item,editor,isNew){const conditions=(item);conditions.title=editor.control('title').value.trim();const download=editor.control('download').value.trim();conditions.download=download?parseInt(download,10)*(1024/8):-1;const upload=editor.control('upload').value.trim();conditions.upload=upload?parseInt(upload,10)*(1024/8):-1;const latency=editor.control('latency').value.trim();conditions.latency=latency?parseInt(latency,10):0;const list=this._customSetting.get();if(isNew)
list.push(conditions);this._customSetting.set(list);}
beginEdit(item){const conditions=(item);const editor=this._createEditor();editor.control('title').value=conditions.title;editor.control('download').value=conditions.download<=0?'':String(conditions.download/(1024/8));editor.control('upload').value=conditions.upload<=0?'':String(conditions.upload/(1024/8));editor.control('latency').value=conditions.latency?String(conditions.latency):'';return editor;}
_createEditor(){if(this._editor)
return this._editor;const editor=new UI.ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const titles=content.createChild('div','conditions-edit-row');titles.createChild('div','conditions-list-text conditions-list-title').textContent=Common.UIString('Profile Name');titles.createChild('div','conditions-list-separator conditions-list-separator-invisible');titles.createChild('div','conditions-list-text').textContent=Common.UIString('Download');titles.createChild('div','conditions-list-separator conditions-list-separator-invisible');titles.createChild('div','conditions-list-text').textContent=Common.UIString('Upload');titles.createChild('div','conditions-list-separator conditions-list-separator-invisible');titles.createChild('div','conditions-list-text').textContent=Common.UIString('Latency');const fields=content.createChild('div','conditions-edit-row');fields.createChild('div','conditions-list-text conditions-list-title').appendChild(editor.createInput('title','text','',titleValidator));fields.createChild('div','conditions-list-separator conditions-list-separator-invisible');let cell=fields.createChild('div','conditions-list-text');cell.appendChild(editor.createInput('download','text',Common.UIString('kb/s'),throughputValidator));cell.createChild('div','conditions-edit-optional').textContent=Common.UIString('optional');fields.createChild('div','conditions-list-separator conditions-list-separator-invisible');cell=fields.createChild('div','conditions-list-text');cell.appendChild(editor.createInput('upload','text',Common.UIString('kb/s'),throughputValidator));cell.createChild('div','conditions-edit-optional').textContent=Common.UIString('optional');fields.createChild('div','conditions-list-separator conditions-list-separator-invisible');cell=fields.createChild('div','conditions-list-text');cell.appendChild(editor.createInput('latency','text',Common.UIString('ms'),latencyValidator));cell.createChild('div','conditions-edit-optional').textContent=Common.UIString('optional');return editor;function titleValidator(item,index,input){const value=input.value.trim();return value.length>0&&value.length<50;}
function throughputValidator(item,index,input){const value=input.value.trim();return!value||(/^[\d]+(\.\d+)?|\.\d+$/.test(value)&&value>=0&&value<=10000000);}
function latencyValidator(item,index,input){const value=input.value.trim();return!value||(/^[\d]+$/.test(value)&&value>=0&&value<=1000000);}}};MobileThrottling.throughputText=function(throughput,plainText){if(throughput<0)
return'';const throughputInKbps=throughput/(1024/8);const delimiter=plainText?'':' ';if(throughputInKbps<1024)
return Common.UIString('%d%skb/s',throughputInKbps,delimiter);if(throughputInKbps<1024*10)
return Common.UIString('%.1f%sMb/s',throughputInKbps/1024,delimiter);return Common.UIString('%d%sMb/s',(throughputInKbps/1024)|0,delimiter);};;MobileThrottling.ThrottlingManager=class extends Common.Object{constructor(){super();this._cpuThrottlingRate=MobileThrottling.CPUThrottlingRates.NoThrottling;this._cpuThrottlingControls=new Set();this._cpuThrottlingRates=MobileThrottling.cpuThrottlingPresets;this._customNetworkConditionsSetting=Common.moduleSetting('customNetworkConditions');this._currentNetworkThrottlingConditions=SDK.NetworkManager.NoThrottlingConditions;this._lastNetworkThrottlingConditions;SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,()=>{this._lastNetworkThrottlingConditions=this._currentNetworkThrottlingConditions;this._currentNetworkThrottlingConditions=SDK.multitargetNetworkManager.networkConditions();});SDK.targetManager.observeModels(SDK.EmulationModel,this);}
decorateSelectWithNetworkThrottling(selectElement){let options=[];const selector=new MobileThrottling.NetworkThrottlingSelector(populate,select,this._customNetworkConditionsSetting);selectElement.addEventListener('change',optionSelected,false);return selector;function populate(groups){selectElement.removeChildren();options=[];for(let i=0;i<groups.length;++i){const group=groups[i];const groupElement=selectElement.createChild('optgroup');groupElement.label=group.title;for(const conditions of group.items){const title=conditions.title;const option=new Option(title,title);groupElement.appendChild(option);options.push(conditions);}
if(i===groups.length-1){groupElement.appendChild(new Option(Common.UIString('Add\u2026'),Common.UIString('Add\u2026')));options.push(null);}}
return options;}
function optionSelected(){if(selectElement.selectedIndex===selectElement.options.length-1)
selector.revealAndUpdate();else
selector.optionSelected(options[selectElement.selectedIndex]);}
function select(index){if(selectElement.selectedIndex!==index)
selectElement.selectedIndex=index;}}
createOfflineToolbarCheckbox(){const checkbox=new UI.ToolbarCheckbox(Common.UIString('Offline'),Common.UIString('Force disconnected from network'),forceOffline.bind(this));SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,networkConditionsChanged);checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions()===SDK.NetworkManager.OfflineConditions);function forceOffline(){if(checkbox.checked())
SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);else
SDK.multitargetNetworkManager.setNetworkConditions(this._lastNetworkThrottlingConditions);}
function networkConditionsChanged(){checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions()===SDK.NetworkManager.OfflineConditions);}
return checkbox;}
createMobileThrottlingButton(){const button=new UI.ToolbarMenuButton(appendItems);button.setTitle(Common.UIString('Throttling'));button.setGlyph('');button.turnIntoSelect();button.setDarkText();let options=[];let selectedIndex=-1;const selector=new MobileThrottling.MobileThrottlingSelector(populate,select);return button;function appendItems(contextMenu){for(let index=0;index<options.length;++index){const conditions=options[index];if(!conditions)
continue;if(conditions.title===MobileThrottling.CustomConditions.title&&conditions.description===MobileThrottling.CustomConditions.description)
continue;contextMenu.defaultSection().appendCheckboxItem(Common.UIString(conditions.title),selector.optionSelected.bind(selector,(conditions)),selectedIndex===index);}}
function populate(groups){options=[];for(const group of groups){for(const conditions of group.items)
options.push(conditions);options.push(null);}
return options;}
function select(index){selectedIndex=index;button.setText(options[index].title);button.setTitle(options[index].description);}}
cpuThrottlingRate(){return this._cpuThrottlingRate;}
setCPUThrottlingRate(rate){this._cpuThrottlingRate=rate;for(const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate);let icon=null;if(this._cpuThrottlingRate!==MobileThrottling.CPUThrottlingRates.NoThrottling){Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuThrottlingEnabled);icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('CPU throttling is enabled');}
const index=this._cpuThrottlingRates.indexOf(this._cpuThrottlingRate);for(const control of this._cpuThrottlingControls)
control.setSelectedIndex(index);UI.inspectorView.setPanelIcon('timeline',icon);this.dispatchEventToListeners(MobileThrottling.ThrottlingManager.Events.RateChanged,this._cpuThrottlingRate);}
modelAdded(emulationModel){if(this._cpuThrottlingRate!==MobileThrottling.CPUThrottlingRates.NoThrottling)
emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate);}
modelRemoved(emulationModel){}
createCPUThrottlingSelector(){const control=new UI.ToolbarComboBox(event=>this.setCPUThrottlingRate(this._cpuThrottlingRates[event.target.selectedIndex]));this._cpuThrottlingControls.add(control);const currentRate=this._cpuThrottlingRate;for(let i=0;i<this._cpuThrottlingRates.length;++i){const rate=this._cpuThrottlingRates[i];const title=rate===1?Common.UIString('No throttling'):Common.UIString('%d\xD7 slowdown',rate);const option=control.createOption(title);control.addOption(option);if(currentRate===rate)
control.setSelectedIndex(i);}
return control;}};MobileThrottling.ThrottlingManager.Events={RateChanged:Symbol('RateChanged')};MobileThrottling.ThrottlingManager.ActionDelegate=class{handleAction(context,actionId){if(actionId==='network-conditions.network-online'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.NoThrottlingConditions);return true;}
if(actionId==='network-conditions.network-low-end-mobile'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.Slow3GConditions);return true;}
if(actionId==='network-conditions.network-mid-tier-mobile'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.Fast3GConditions);return true;}
if(actionId==='network-conditions.network-offline'){SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);return true;}
return false;}};MobileThrottling.throttlingManager=function(){return self.singleton(MobileThrottling.ThrottlingManager);};;self['WorkerMain']=self['WorkerMain']||{};WorkerMain.WorkerMain=class extends Common.Object{run(){SDK.initMainConnection(()=>{SDK.targetManager.createTarget('main',ls`Main`,SDK.Target.Type.ServiceWorker,null);},Components.TargetDetachedDialog.webSocketConnectionLost);new MobileThrottling.NetworkPanelIndicator();}};SDK.ChildTargetManager.install(async({target,waitingForDebugger})=>{if(target.parentTarget().type()!==SDK.Target.Type.ServiceWorker||!waitingForDebugger)
return;const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel)
return;if(!debuggerModel.isReadyToPause())
await debuggerModel.once(SDK.DebuggerModel.Events.DebuggerIsReadyToPause);debuggerModel.pause();});;;Runtime.cachedResources["mobile_throttling/throttlingSettingsTab.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow:hidden;\n}\n\n.header {\n padding: 0 0 6px;\n border-bottom: 1px solid #EEEEEE;\n font-size: 18px;\n font-weight: normal;\n flex: none;\n}\n\n.add-conditions-button {\n flex: none;\n margin: 10px 2px;\n min-width: 140px;\n align-self: flex-start;\n}\n\n.conditions-list {\n max-width: 500px;\n min-width: 340px;\n flex: auto;\n}\n\n.conditions-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n position: relative;\n flex: auto 1 1;\n}\n\n.conditions-list-text {\n white-space: nowrap;\n text-overflow: ellipsis;\n flex: 0 0 70px;\n -webkit-user-select: none;\n color: #222;\n text-align: end;\n position: relative;\n}\n\n.conditions-list-title {\n text-align: start;\n flex: auto;\n display: flex;\n align-items: flex-start;\n}\n\n.conditions-list-title-text {\n overflow: hidden;\n flex: auto;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n\n.conditions-list-separator {\n flex: 0 0 1px;\n background-color: rgb(231, 231, 231);\n height: 30px;\n margin: 0 4px;\n}\n\n.conditions-list-separator-invisible {\n visibility: hidden;\n height: 100% !important;\n}\n\n.conditions-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 6px 5px;\n}\n\n.conditions-edit-row input {\n width: 100%;\n text-align: inherit;\n}\n\n.conditions-edit-optional {\n position: absolute;\n bottom: -20px;\n right: 0;\n color: rgb(128, 128, 128);\n}\n\n/*# sourceURL=mobile_throttling/throttlingSettingsTab.css */";Animation.AnimationModel=class extends SDK.SDKModel{constructor(target){super(target);this._runtimeModel=(target.model(SDK.RuntimeModel));this._agent=target.animationAgent();target.registerAnimationDispatcher(new Animation.AnimationDispatcher(this));this._animationsById=new Map();this._animationGroups=new Map();this._pendingAnimations=[];this._playbackRate=1;const resourceTreeModel=(target.model(SDK.ResourceTreeModel));resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._reset,this);const screenCaptureModel=target.model(SDK.ScreenCaptureModel);if(screenCaptureModel)
this._screenshotCapture=new Animation.AnimationModel.ScreenshotCapture(this,screenCaptureModel);}
_reset(){this._animationsById.clear();this._animationGroups.clear();this._pendingAnimations=[];this.dispatchEventToListeners(Animation.AnimationModel.Events.ModelReset);}
animationCreated(id){this._pendingAnimations.push(id);}
_animationCanceled(id){this._pendingAnimations.remove(id);this._flushPendingAnimationsIfNeeded();}
animationStarted(payload){if(!payload.source||!payload.source.backendNodeId)
return;const animation=Animation.AnimationModel.Animation.parsePayload(this,payload);if(animation.type()==='WebAnimation'&&animation.source().keyframesRule().keyframes().length===0){this._pendingAnimations.remove(animation.id());}else{this._animationsById.set(animation.id(),animation);if(this._pendingAnimations.indexOf(animation.id())===-1)
this._pendingAnimations.push(animation.id());}
this._flushPendingAnimationsIfNeeded();}
_flushPendingAnimationsIfNeeded(){for(const id of this._pendingAnimations){if(!this._animationsById.get(id))
return;}
while(this._pendingAnimations.length)
this._matchExistingGroups(this._createGroupFromPendingAnimations());}
_matchExistingGroups(incomingGroup){let matchedGroup=null;for(const group of this._animationGroups.values()){if(group._matches(incomingGroup)){matchedGroup=group;group._update(incomingGroup);break;}}
if(!matchedGroup){this._animationGroups.set(incomingGroup.id(),incomingGroup);if(this._screenshotCapture)
this._screenshotCapture.captureScreenshots(incomingGroup.finiteDuration(),incomingGroup._screenshots);}
this.dispatchEventToListeners(Animation.AnimationModel.Events.AnimationGroupStarted,matchedGroup||incomingGroup);return!!matchedGroup;}
_createGroupFromPendingAnimations(){console.assert(this._pendingAnimations.length);const groupedAnimations=[this._animationsById.get(this._pendingAnimations.shift())];const remainingAnimations=[];for(const id of this._pendingAnimations){const anim=this._animationsById.get(id);if(anim.startTime()===groupedAnimations[0].startTime())
groupedAnimations.push(anim);else
remainingAnimations.push(id);}
this._pendingAnimations=remainingAnimations;return new Animation.AnimationModel.AnimationGroup(this,groupedAnimations[0].id(),groupedAnimations);}
setPlaybackRate(playbackRate){this._playbackRate=playbackRate;this._agent.setPlaybackRate(playbackRate);}
_releaseAnimations(animations){this._agent.releaseAnimations(animations);}
suspendModel(){this._reset();return this._agent.disable();}
resumeModel(){if(!this._enabled)
return Promise.resolve();return this._agent.enable();}
ensureEnabled(){if(this._enabled)
return;this._agent.enable();this._enabled=true;}};SDK.SDKModel.register(Animation.AnimationModel,SDK.Target.Capability.DOM,false);Animation.AnimationModel.Events={AnimationGroupStarted:Symbol('AnimationGroupStarted'),ModelReset:Symbol('ModelReset')};Animation.AnimationModel.Animation=class{constructor(animationModel,payload){this._animationModel=animationModel;this._payload=payload;this._source=new Animation.AnimationModel.AnimationEffect(animationModel,(this._payload.source));}
static parsePayload(animationModel,payload){return new Animation.AnimationModel.Animation(animationModel,payload);}
payload(){return this._payload;}
id(){return this._payload.id;}
name(){return this._payload.name;}
paused(){return this._payload.pausedState;}
playState(){return this._playState||this._payload.playState;}
setPlayState(playState){this._playState=playState;}
playbackRate(){return this._payload.playbackRate;}
startTime(){return this._payload.startTime;}
endTime(){if(!this.source().iterations)
return Infinity;return this.startTime()+this.source().delay()+this.source().duration()*this.source().iterations()+
this.source().endDelay();}
_finiteDuration(){const iterations=Math.min(this.source().iterations(),3);return this.source().delay()+this.source().duration()*iterations;}
currentTime(){return this._payload.currentTime;}
source(){return this._source;}
type(){return(this._payload.type);}
overlaps(animation){if(!this.source().iterations()||!animation.source().iterations())
return true;const firstAnimation=this.startTime()<animation.startTime()?this:animation;const secondAnimation=firstAnimation===this?animation:this;return firstAnimation.endTime()>=secondAnimation.startTime();}
setTiming(duration,delay){this._source.node().then(this._updateNodeStyle.bind(this,duration,delay));this._source._duration=duration;this._source._delay=delay;this._animationModel._agent.setTiming(this.id(),duration,delay);}
_updateNodeStyle(duration,delay,node){let animationPrefix;if(this.type()===Animation.AnimationModel.Animation.Type.CSSTransition)
animationPrefix='transition-';else if(this.type()===Animation.AnimationModel.Animation.Type.CSSAnimation)
animationPrefix='animation-';else
return;const cssModel=node.domModel().cssModel();cssModel.setEffectivePropertyValueForNode(node.id,animationPrefix+'duration',duration+'ms');cssModel.setEffectivePropertyValueForNode(node.id,animationPrefix+'delay',delay+'ms');}
remoteObjectPromise(){return this._animationModel._agent.resolveAnimation(this.id()).then(payload=>payload&&this._animationModel._runtimeModel.createRemoteObject(payload));}
_cssId(){return this._payload.cssId||'';}};Animation.AnimationModel.Animation.Type={CSSTransition:'CSSTransition',CSSAnimation:'CSSAnimation',WebAnimation:'WebAnimation'};Animation.AnimationModel.AnimationEffect=class{constructor(animationModel,payload){this._animationModel=animationModel;this._payload=payload;if(payload.keyframesRule)
this._keyframesRule=new Animation.AnimationModel.KeyframesRule(payload.keyframesRule);this._delay=this._payload.delay;this._duration=this._payload.duration;}
delay(){return this._delay;}
endDelay(){return this._payload.endDelay;}
iterationStart(){return this._payload.iterationStart;}
iterations(){if(!this.delay()&&!this.endDelay()&&!this.duration())
return 0;return this._payload.iterations||Infinity;}
duration(){return this._duration;}
direction(){return this._payload.direction;}
fill(){return this._payload.fill;}
node(){if(!this._deferredNode)
this._deferredNode=new SDK.DeferredDOMNode(this._animationModel.target(),this.backendNodeId());return this._deferredNode.resolvePromise();}
deferredNode(){return new SDK.DeferredDOMNode(this._animationModel.target(),this.backendNodeId());}
backendNodeId(){return(this._payload.backendNodeId);}
keyframesRule(){return this._keyframesRule;}
easing(){return this._payload.easing;}};Animation.AnimationModel.KeyframesRule=class{constructor(payload){this._payload=payload;this._keyframes=this._payload.keyframes.map(function(keyframeStyle){return new Animation.AnimationModel.KeyframeStyle(keyframeStyle);});}
_setKeyframesPayload(payload){this._keyframes=payload.map(function(keyframeStyle){return new Animation.AnimationModel.KeyframeStyle(keyframeStyle);});}
name(){return this._payload.name;}
keyframes(){return this._keyframes;}};Animation.AnimationModel.KeyframeStyle=class{constructor(payload){this._payload=payload;this._offset=this._payload.offset;}
offset(){return this._offset;}
setOffset(offset){this._offset=offset*100+'%';}
offsetAsNumber(){return parseFloat(this._offset)/100;}
easing(){return this._payload.easing;}};Animation.AnimationModel.AnimationGroup=class{constructor(animationModel,id,animations){this._animationModel=animationModel;this._id=id;this._animations=animations;this._paused=false;this._screenshots=[];this._screenshotImages=[];}
id(){return this._id;}
animations(){return this._animations;}
release(){this._animationModel._animationGroups.remove(this.id());this._animationModel._releaseAnimations(this._animationIds());}
_animationIds(){function extractId(animation){return animation.id();}
return this._animations.map(extractId);}
startTime(){return this._animations[0].startTime();}
finiteDuration(){let maxDuration=0;for(let i=0;i<this._animations.length;++i)
maxDuration=Math.max(maxDuration,this._animations[i]._finiteDuration());return maxDuration;}
seekTo(currentTime){this._animationModel._agent.seekAnimations(this._animationIds(),currentTime);}
paused(){return this._paused;}
togglePause(paused){if(paused===this._paused)
return;this._paused=paused;this._animationModel._agent.setPaused(this._animationIds(),paused);}
currentTimePromise(){let longestAnim=null;for(const anim of this._animations){if(!longestAnim||anim.endTime()>longestAnim.endTime())
longestAnim=anim;}
return this._animationModel._agent.getCurrentTime(longestAnim.id()).then(currentTime=>currentTime||0);}
_matches(group){function extractId(anim){if(anim.type()===Animation.AnimationModel.Animation.Type.WebAnimation)
return anim.type()+anim.id();else
return anim._cssId();}
if(this._animations.length!==group._animations.length)
return false;const left=this._animations.map(extractId).sort();const right=group._animations.map(extractId).sort();for(let i=0;i<left.length;i++){if(left[i]!==right[i])
return false;}
return true;}
_update(group){this._animationModel._releaseAnimations(this._animationIds());this._animations=group._animations;}
screenshots(){for(let i=0;i<this._screenshots.length;++i){const image=new Image();image.src='data:image/jpeg;base64,'+this._screenshots[i];this._screenshotImages.push(image);}
this._screenshots=[];return this._screenshotImages;}};Animation.AnimationDispatcher=class{constructor(animationModel){this._animationModel=animationModel;}
animationCreated(id){this._animationModel.animationCreated(id);}
animationCanceled(id){this._animationModel._animationCanceled(id);}
animationStarted(payload){this._animationModel.animationStarted(payload);}};Animation.AnimationModel.ScreenshotCapture=class{constructor(animationModel,screenCaptureModel){this._requests=[];this._screenCaptureModel=screenCaptureModel;this._animationModel=animationModel;this._animationModel.addEventListener(Animation.AnimationModel.Events.ModelReset,this._stopScreencast,this);}
captureScreenshots(duration,screenshots){const screencastDuration=Math.min(duration/this._animationModel._playbackRate,3000);const endTime=screencastDuration+window.performance.now();this._requests.push({endTime:endTime,screenshots:screenshots});if(!this._endTime||endTime>this._endTime){clearTimeout(this._stopTimer);this._stopTimer=setTimeout(this._stopScreencast.bind(this),screencastDuration);this._endTime=endTime;}
if(this._capturing)
return;this._capturing=true;this._screenCaptureModel.startScreencast('jpeg',80,undefined,300,2,this._screencastFrame.bind(this),visible=>{});}
_screencastFrame(base64Data,metadata){function isAnimating(request){return request.endTime>=now;}
if(!this._capturing)
return;const now=window.performance.now();this._requests=this._requests.filter(isAnimating);for(const request of this._requests)
request.screenshots.push(base64Data);}
_stopScreencast(){if(!this._capturing)
return;delete this._stopTimer;delete this._endTime;this._requests=[];this._capturing=false;this._screenCaptureModel.stopScreencast();}};Animation.AnimationModel.ScreenshotCapture.Request;;Animation.AnimationGroupPreviewUI=class{constructor(model){this._model=model;this.element=createElementWithClass('div','animation-buffer-preview');this.element.createChild('div','animation-paused fill');this._removeButton=this.element.createChild('div','animation-remove-button');this._removeButton.textContent='\u2715';this._replayOverlayElement=this.element.createChild('div','animation-buffer-preview-animation');this._svg=this.element.createSVGChild('svg');this._svg.setAttribute('width','100%');this._svg.setAttribute('preserveAspectRatio','none');this._svg.setAttribute('height','100%');this._viewBoxHeight=32;this._svg.setAttribute('viewBox','0 0 100 '+this._viewBoxHeight);this._svg.setAttribute('shape-rendering','crispEdges');this._render();}
_groupDuration(){let duration=0;for(const anim of this._model.animations()){const animDuration=anim.source().delay()+anim.source().duration();if(animDuration>duration)
duration=animDuration;}
return duration;}
removeButton(){return this._removeButton;}
replay(){this._replayOverlayElement.animate([{offset:0,width:'0%',opacity:1},{offset:0.9,width:'100%',opacity:1},{offset:1,width:'100%',opacity:0}],{duration:200,easing:'cubic-bezier(0, 0, 0.2, 1)'});}
_render(){this._svg.removeChildren();const maxToShow=10;const numberOfAnimations=Math.min(this._model.animations().length,maxToShow);const timeToPixelRatio=100/Math.max(this._groupDuration(),750);for(let i=0;i<numberOfAnimations;i++){const effect=this._model.animations()[i].source();const line=this._svg.createSVGChild('line');line.setAttribute('x1',effect.delay()*timeToPixelRatio);line.setAttribute('x2',(effect.delay()+effect.duration())*timeToPixelRatio);const y=Math.floor(this._viewBoxHeight/Math.max(6,numberOfAnimations)*i+1);line.setAttribute('y1',y);line.setAttribute('y2',y);line.style.stroke=Animation.AnimationUI.Color(this._model.animations()[i]);}}};;Animation.AnimationScreenshotPopover=class extends UI.VBox{constructor(images){super(true);console.assert(images.length);this.registerRequiredCSS('animation/animationScreenshotPopover.css');this.contentElement.classList.add('animation-screenshot-popover');this._frames=images;for(const image of images){this.contentElement.appendChild(image);image.style.display='none';}
this._currentFrame=0;this._frames[0].style.display='block';this._progressBar=this.contentElement.createChild('div','animation-progress');}
wasShown(){this._rafId=this.contentElement.window().requestAnimationFrame(this._changeFrame.bind(this));}
willHide(){this.contentElement.window().cancelAnimationFrame(this._rafId);delete this._endDelay;}
_changeFrame(){this._rafId=this.contentElement.window().requestAnimationFrame(this._changeFrame.bind(this));if(this._endDelay){this._endDelay--;return;}
this._showFrame=!this._showFrame;if(!this._showFrame)
return;const numFrames=this._frames.length;this._frames[this._currentFrame%numFrames].style.display='none';this._currentFrame++;this._frames[(this._currentFrame)%numFrames].style.display='block';if(this._currentFrame%numFrames===numFrames-1)
this._endDelay=50;this._progressBar.style.width=(this._currentFrame%numFrames+1)/numFrames*100+'%';}};;Animation.AnimationTimeline=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('animation/animationTimeline.css');this.element.classList.add('animations-timeline');this._grid=this.contentElement.createSVGChild('svg','animation-timeline-grid');this._playbackRate=1;this._allPaused=false;this._createHeader();this._animationsContainer=this.contentElement.createChild('div','animation-timeline-rows');const timelineHint=this.contentElement.createChild('div','animation-timeline-rows-hint');timelineHint.textContent=ls`Select an effect above to inspect and modify.`;this._defaultDuration=100;this._duration=this._defaultDuration;this._timelineControlsWidth=150;this._nodesMap=new Map();this._uiAnimations=[];this._groupBuffer=[];this._previewMap=new Map();this._symbol=Symbol('animationTimeline');this._animationsMap=new Map();SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.NodeRemoved,this._nodeRemoved,this);SDK.targetManager.observeModels(Animation.AnimationModel,this);UI.context.addFlavorChangeListener(SDK.DOMNode,this._nodeChanged,this);}
wasShown(){for(const animationModel of SDK.targetManager.models(Animation.AnimationModel))
this._addEventListeners(animationModel);}
willHide(){for(const animationModel of SDK.targetManager.models(Animation.AnimationModel))
this._removeEventListeners(animationModel);this._popoverHelper.hidePopover();}
modelAdded(animationModel){if(this.isShowing())
this._addEventListeners(animationModel);}
modelRemoved(animationModel){this._removeEventListeners(animationModel);}
_addEventListeners(animationModel){animationModel.ensureEnabled();animationModel.addEventListener(Animation.AnimationModel.Events.AnimationGroupStarted,this._animationGroupStarted,this);animationModel.addEventListener(Animation.AnimationModel.Events.ModelReset,this._reset,this);}
_removeEventListeners(animationModel){animationModel.removeEventListener(Animation.AnimationModel.Events.AnimationGroupStarted,this._animationGroupStarted,this);animationModel.removeEventListener(Animation.AnimationModel.Events.ModelReset,this._reset,this);}
_nodeChanged(){for(const nodeUI of this._nodesMap.values())
nodeUI._nodeChanged();}
_createScrubber(){this._timelineScrubber=createElementWithClass('div','animation-scrubber hidden');this._timelineScrubberLine=this._timelineScrubber.createChild('div','animation-scrubber-line');this._timelineScrubberLine.createChild('div','animation-scrubber-head');this._timelineScrubber.createChild('div','animation-time-overlay');return this._timelineScrubber;}
_createHeader(){const toolbarContainer=this.contentElement.createChild('div','animation-timeline-toolbar-container');const topToolbar=new UI.Toolbar('animation-timeline-toolbar',toolbarContainer);const clearButton=new UI.ToolbarButton(ls`Clear all`,'largeicon-clear');clearButton.addEventListener(UI.ToolbarButton.Events.Click,this._reset.bind(this));topToolbar.appendToolbarItem(clearButton);topToolbar.appendSeparator();this._pauseButton=new UI.ToolbarToggle(ls`Pause all`,'largeicon-pause','largeicon-resume');this._pauseButton.addEventListener(UI.ToolbarButton.Events.Click,this._togglePauseAll.bind(this));topToolbar.appendToolbarItem(this._pauseButton);const playbackRateControl=toolbarContainer.createChild('div','animation-playback-rate-control');this._playbackRateButtons=[];for(const playbackRate of Animation.AnimationTimeline.GlobalPlaybackRates){const button=playbackRateControl.createChild('div','animation-playback-rate-button');button.textContent=playbackRate?ls`${playbackRate * 100}%`:ls`Pause`;button.playbackRate=playbackRate;button.addEventListener('click',this._setPlaybackRate.bind(this,playbackRate));button.title=ls`Set speed to ${button.textContent}`;this._playbackRateButtons.push(button);}
this._updatePlaybackControls();this._previewContainer=this.contentElement.createChild('div','animation-timeline-buffer');this._popoverHelper=new UI.PopoverHelper(this._previewContainer,this._getPopoverRequest.bind(this));this._popoverHelper.setDisableOnClick(true);this._popoverHelper.setTimeout(0);const emptyBufferHint=this.contentElement.createChild('div','animation-timeline-buffer-hint');emptyBufferHint.textContent=ls`Listening for animations...`;const container=this.contentElement.createChild('div','animation-timeline-header');const controls=container.createChild('div','animation-controls');this._currentTime=controls.createChild('div','animation-timeline-current-time monospace');const toolbar=new UI.Toolbar('animation-controls-toolbar',controls);this._controlButton=new UI.ToolbarToggle(ls`Replay timeline`,'largeicon-replay-animation');this._controlState=Animation.AnimationTimeline._ControlState.Replay;this._controlButton.setToggled(true);this._controlButton.addEventListener(UI.ToolbarButton.Events.Click,this._controlButtonToggle.bind(this));toolbar.appendToolbarItem(this._controlButton);const gridHeader=container.createChild('div','animation-grid-header');UI.installDragHandle(gridHeader,this._repositionScrubber.bind(this),this._scrubberDragMove.bind(this),this._scrubberDragEnd.bind(this),'text');container.appendChild(this._createScrubber());UI.installDragHandle(this._timelineScrubberLine,this._scrubberDragStart.bind(this),this._scrubberDragMove.bind(this),this._scrubberDragEnd.bind(this),'col-resize');this._currentTime.textContent='';return container;}
_getPopoverRequest(event){const element=event.target;if(!element.isDescendant(this._previewContainer))
return null;return{box:event.target.boxInWindow(),show:popover=>{let animGroup;for(const group of this._previewMap.keysArray()){if(this._previewMap.get(group).element===element.parentElement)
animGroup=group;}
console.assert(animGroup);const screenshots=animGroup.screenshots();if(!screenshots.length)
return Promise.resolve(false);let fulfill;const promise=new Promise(x=>fulfill=x);if(!screenshots[0].complete)
screenshots[0].onload=onFirstScreenshotLoaded.bind(null,screenshots);else
onFirstScreenshotLoaded(screenshots);return promise;function onFirstScreenshotLoaded(screenshots){new Animation.AnimationScreenshotPopover(screenshots).show(popover.contentElement);fulfill(true);}}};}
_togglePauseAll(){this._allPaused=!this._allPaused;this._pauseButton.setToggled(this._allPaused);this._setPlaybackRate(this._playbackRate);this._pauseButton.setTitle(this._allPaused?ls`Resume all`:ls`Pause all`);}
_setPlaybackRate(playbackRate){this._playbackRate=playbackRate;for(const animationModel of SDK.targetManager.models(Animation.AnimationModel))
animationModel.setPlaybackRate(this._allPaused?0:this._playbackRate);Host.userMetrics.actionTaken(Host.UserMetrics.Action.AnimationsPlaybackRateChanged);if(this._scrubberPlayer)
this._scrubberPlayer.playbackRate=this._effectivePlaybackRate();this._updatePlaybackControls();}
_updatePlaybackControls(){for(const button of this._playbackRateButtons){const selected=this._playbackRate===button.playbackRate;button.classList.toggle('selected',selected);}}
_controlButtonToggle(){if(this._controlState===Animation.AnimationTimeline._ControlState.Play)
this._togglePause(false);else if(this._controlState===Animation.AnimationTimeline._ControlState.Replay)
this._replay();else
this._togglePause(true);}
_updateControlButton(){this._controlButton.setEnabled(!!this._selectedGroup);if(this._selectedGroup&&this._selectedGroup.paused()){this._controlState=Animation.AnimationTimeline._ControlState.Play;this._controlButton.setToggled(true);this._controlButton.setTitle(ls`Play timeline`);this._controlButton.setGlyph('largeicon-play-animation');}else if(!this._scrubberPlayer||this._scrubberPlayer.currentTime>=this.duration()){this._controlState=Animation.AnimationTimeline._ControlState.Replay;this._controlButton.setToggled(true);this._controlButton.setTitle(ls`Replay timeline`);this._controlButton.setGlyph('largeicon-replay-animation');}else{this._controlState=Animation.AnimationTimeline._ControlState.Pause;this._controlButton.setToggled(false);this._controlButton.setTitle(ls`Pause timeline`);this._controlButton.setGlyph('largeicon-pause-animation');}}
_effectivePlaybackRate(){return(this._allPaused||(this._selectedGroup&&this._selectedGroup.paused()))?0:this._playbackRate;}
_togglePause(pause){this._selectedGroup.togglePause(pause);if(this._scrubberPlayer)
this._scrubberPlayer.playbackRate=this._effectivePlaybackRate();this._previewMap.get(this._selectedGroup).element.classList.toggle('paused',pause);this._updateControlButton();}
_replay(){if(!this._selectedGroup)
return;this._selectedGroup.seekTo(0);this._animateTime(0);this._updateControlButton();}
duration(){return this._duration;}
setDuration(duration){this._duration=duration;this.scheduleRedraw();}
_clearTimeline(){this._uiAnimations=[];this._nodesMap.clear();this._animationsMap.clear();this._animationsContainer.removeChildren();this._duration=this._defaultDuration;this._timelineScrubber.classList.add('hidden');delete this._selectedGroup;if(this._scrubberPlayer)
this._scrubberPlayer.cancel();delete this._scrubberPlayer;this._currentTime.textContent='';this._updateControlButton();}
_reset(){this._clearTimeline();if(this._allPaused)
this._togglePauseAll();else
this._setPlaybackRate(this._playbackRate);for(const group of this._groupBuffer)
group.release();this._groupBuffer=[];this._previewMap.clear();this._previewContainer.removeChildren();this._popoverHelper.hidePopover();this._renderGrid();}
_animationGroupStarted(event){this._addAnimationGroup((event.data));}
_addAnimationGroup(group){function startTimeComparator(left,right){return left.startTime()>right.startTime();}
if(this._previewMap.get(group)){if(this._selectedGroup===group)
this._syncScrubber();else
this._previewMap.get(group).replay();return;}
this._groupBuffer.sort(startTimeComparator);const groupsToDiscard=[];const bufferSize=this.width()/50;while(this._groupBuffer.length>bufferSize){const toDiscard=this._groupBuffer.splice(this._groupBuffer[0]===this._selectedGroup?1:0,1);groupsToDiscard.push(toDiscard[0]);}
for(const g of groupsToDiscard){this._previewMap.get(g).element.remove();this._previewMap.delete(g);g.release();}
const preview=new Animation.AnimationGroupPreviewUI(group);this._groupBuffer.push(group);this._previewMap.set(group,preview);this._previewContainer.appendChild(preview.element);preview.removeButton().addEventListener('click',this._removeAnimationGroup.bind(this,group));preview.element.addEventListener('click',this._selectAnimationGroup.bind(this,group));}
_removeAnimationGroup(group,event){this._groupBuffer.remove(group);this._previewMap.get(group).element.remove();this._previewMap.delete(group);group.release();event.consume(true);if(this._selectedGroup===group){this._clearTimeline();this._renderGrid();}}
_selectAnimationGroup(group){function applySelectionClass(ui,group){ui.element.classList.toggle('selected',this._selectedGroup===group);}
if(this._selectedGroup===group){this._togglePause(false);this._replay();return;}
this._clearTimeline();this._selectedGroup=group;this._previewMap.forEach(applySelectionClass,this);this.setDuration(Math.max(500,group.finiteDuration()+100));for(const anim of group.animations())
this._addAnimation(anim);this.scheduleRedraw();this._timelineScrubber.classList.remove('hidden');this._togglePause(false);this._replay();}
_addAnimation(animation){function nodeResolved(node){nodeUI.nodeResolved(node);uiAnimation.setNode(node);if(node)
node[this._symbol]=nodeUI;}
let nodeUI=this._nodesMap.get(animation.source().backendNodeId());if(!nodeUI){nodeUI=new Animation.AnimationTimeline.NodeUI(animation.source());this._animationsContainer.appendChild(nodeUI.element);this._nodesMap.set(animation.source().backendNodeId(),nodeUI);}
const nodeRow=nodeUI.createNewRow();const uiAnimation=new Animation.AnimationUI(animation,this,nodeRow);animation.source().deferredNode().resolve(nodeResolved.bind(this));this._uiAnimations.push(uiAnimation);this._animationsMap.set(animation.id(),animation);}
_nodeRemoved(event){const node=event.data.node;if(node[this._symbol])
node[this._symbol].nodeRemoved();}
_renderGrid(){const gridSize=250;this._grid.setAttribute('width',this.width()+10);this._grid.setAttribute('height',this._cachedTimelineHeight+30);this._grid.setAttribute('shape-rendering','crispEdges');this._grid.removeChildren();let lastDraw=undefined;for(let time=0;time<this.duration();time+=gridSize){const line=this._grid.createSVGChild('rect','animation-timeline-grid-line');line.setAttribute('x',time*this.pixelMsRatio()+10);line.setAttribute('y',23);line.setAttribute('height','100%');line.setAttribute('width',1);}
for(let time=0;time<this.duration();time+=gridSize){const gridWidth=time*this.pixelMsRatio();if(lastDraw===undefined||gridWidth-lastDraw>50){lastDraw=gridWidth;const label=this._grid.createSVGChild('text','animation-timeline-grid-label');label.textContent=Number.millisToString(time);label.setAttribute('x',gridWidth+10);label.setAttribute('y',16);}}}
scheduleRedraw(){this._renderQueue=[];for(const ui of this._uiAnimations)
this._renderQueue.push(ui);if(this._redrawing)
return;this._redrawing=true;this._renderGrid();this._animationsContainer.window().requestAnimationFrame(this._render.bind(this));}
_render(timestamp){while(this._renderQueue.length&&(!timestamp||window.performance.now()-timestamp<50))
this._renderQueue.shift().redraw();if(this._renderQueue.length)
this._animationsContainer.window().requestAnimationFrame(this._render.bind(this));else
delete this._redrawing;}
onResize(){this._cachedTimelineWidth=Math.max(0,this._animationsContainer.offsetWidth-this._timelineControlsWidth)||0;this._cachedTimelineHeight=this._animationsContainer.offsetHeight;this.scheduleRedraw();if(this._scrubberPlayer)
this._syncScrubber();delete this._gridOffsetLeft;}
width(){return this._cachedTimelineWidth||0;}
_resizeWindow(animation){let resized=false;const duration=animation.source().duration()*Math.min(2,animation.source().iterations());const requiredDuration=animation.source().delay()+duration+animation.source().endDelay();if(requiredDuration>this._duration){resized=true;this._duration=requiredDuration+200;}
return resized;}
_syncScrubber(){if(!this._selectedGroup)
return;this._selectedGroup.currentTimePromise().then(this._animateTime.bind(this)).then(this._updateControlButton.bind(this));}
_animateTime(currentTime){if(this._scrubberPlayer)
this._scrubberPlayer.cancel();this._scrubberPlayer=this._timelineScrubber.animate([{transform:'translateX(0px)'},{transform:'translateX('+this.width()+'px)'}],{duration:this.duration(),fill:'forwards'});this._scrubberPlayer.playbackRate=this._effectivePlaybackRate();this._scrubberPlayer.onfinish=this._updateControlButton.bind(this);this._scrubberPlayer.currentTime=currentTime;this.element.window().requestAnimationFrame(this._updateScrubber.bind(this));}
pixelMsRatio(){return this.width()/this.duration()||0;}
_updateScrubber(timestamp){if(!this._scrubberPlayer)
return;this._currentTime.textContent=Number.millisToString(this._scrubberPlayer.currentTime);if(this._scrubberPlayer.playState==='pending'||this._scrubberPlayer.playState==='running')
this.element.window().requestAnimationFrame(this._updateScrubber.bind(this));else if(this._scrubberPlayer.playState==='finished')
this._currentTime.textContent='';}
_repositionScrubber(event){if(!this._selectedGroup)
return false;if(!this._gridOffsetLeft)
this._gridOffsetLeft=this._grid.totalOffsetLeft()+10;const seekTime=Math.max(0,event.x-this._gridOffsetLeft)/this.pixelMsRatio();this._selectedGroup.seekTo(seekTime);this._togglePause(true);this._animateTime(seekTime);this._originalScrubberTime=seekTime;this._originalMousePosition=event.x;return true;}
_scrubberDragStart(event){if(!this._scrubberPlayer||!this._selectedGroup)
return false;this._originalScrubberTime=this._scrubberPlayer.currentTime;this._timelineScrubber.classList.remove('animation-timeline-end');this._scrubberPlayer.pause();this._originalMousePosition=event.x;this._togglePause(true);return true;}
_scrubberDragMove(event){const delta=event.x-this._originalMousePosition;const currentTime=Math.max(0,Math.min(this._originalScrubberTime+delta/this.pixelMsRatio(),this.duration()));this._scrubberPlayer.currentTime=currentTime;this._currentTime.textContent=Number.millisToString(Math.round(currentTime));this._selectedGroup.seekTo(currentTime);}
_scrubberDragEnd(event){const currentTime=Math.max(0,this._scrubberPlayer.currentTime);this._scrubberPlayer.play();this._scrubberPlayer.currentTime=currentTime;this._currentTime.window().requestAnimationFrame(this._updateScrubber.bind(this));}};Animation.AnimationTimeline.GlobalPlaybackRates=[1,0.25,0.1];Animation.AnimationTimeline._ControlState={Play:'play-outline',Replay:'replay-outline',Pause:'pause-outline'};Animation.AnimationTimeline.NodeUI=class{constructor(animationEffect){this.element=createElementWithClass('div','animation-node-row');this._description=this.element.createChild('div','animation-node-description');this._timelineElement=this.element.createChild('div','animation-node-timeline');}
async nodeResolved(node){if(!node){this._description.createTextChild('<node>');return;}
this._node=node;this._nodeChanged();Common.Linkifier.linkify(node).then(link=>this._description.appendChild(link));if(!node.ownerDocument)
this.nodeRemoved();}
createNewRow(){return this._timelineElement.createChild('div','animation-timeline-row');}
nodeRemoved(){this.element.classList.add('animation-node-removed');this._node=null;}
_nodeChanged(){this.element.classList.toggle('animation-node-selected',this._node&&this._node===UI.context.flavor(SDK.DOMNode));}};Animation.AnimationTimeline.StepTimingFunction=class{constructor(steps,stepAtPosition){this.steps=steps;this.stepAtPosition=stepAtPosition;}
static parse(text){let match=text.match(/^steps\((\d+), (start|middle)\)$/);if(match)
return new Animation.AnimationTimeline.StepTimingFunction(parseInt(match[1],10),match[2]);match=text.match(/^steps\((\d+)\)$/);if(match)
return new Animation.AnimationTimeline.StepTimingFunction(parseInt(match[1],10),'end');return null;}};;Animation.AnimationUI=class{constructor(animation,timeline,parentElement){this._animation=animation;this._timeline=timeline;this._parentElement=parentElement;if(this._animation.source().keyframesRule())
this._keyframes=this._animation.source().keyframesRule().keyframes();this._nameElement=parentElement.createChild('div','animation-name');this._nameElement.textContent=this._animation.name();this._svg=parentElement.createSVGChild('svg','animation-ui');this._svg.setAttribute('height',Animation.AnimationUI.Options.AnimationSVGHeight);this._svg.style.marginLeft='-'+Animation.AnimationUI.Options.AnimationMargin+'px';this._svg.addEventListener('contextmenu',this._onContextMenu.bind(this));this._activeIntervalGroup=this._svg.createSVGChild('g');UI.installDragHandle(this._activeIntervalGroup,this._mouseDown.bind(this,Animation.AnimationUI.MouseEvents.AnimationDrag,null),this._mouseMove.bind(this),this._mouseUp.bind(this),'-webkit-grabbing','-webkit-grab');this._cachedElements=[];this._movementInMs=0;this._color=Animation.AnimationUI.Color(this._animation);}
static Color(animation){const names=Object.keys(Animation.AnimationUI.Colors);const color=Animation.AnimationUI.Colors[names[String.hashCode(animation.name()||animation.id())%names.length]];return color.asString(Common.Color.Format.RGB);}
animation(){return this._animation;}
setNode(node){this._node=node;}
_createLine(parentElement,className){const line=parentElement.createSVGChild('line',className);line.setAttribute('x1',Animation.AnimationUI.Options.AnimationMargin);line.setAttribute('y1',Animation.AnimationUI.Options.AnimationHeight);line.setAttribute('y2',Animation.AnimationUI.Options.AnimationHeight);line.style.stroke=this._color;return line;}
_drawAnimationLine(iteration,parentElement){const cache=this._cachedElements[iteration];if(!cache.animationLine)
cache.animationLine=this._createLine(parentElement,'animation-line');cache.animationLine.setAttribute('x2',(this._duration()*this._timeline.pixelMsRatio()+Animation.AnimationUI.Options.AnimationMargin).toFixed(2));}
_drawDelayLine(parentElement){if(!this._delayLine){this._delayLine=this._createLine(parentElement,'animation-delay-line');this._endDelayLine=this._createLine(parentElement,'animation-delay-line');}
const fill=this._animation.source().fill();this._delayLine.classList.toggle('animation-fill',fill==='backwards'||fill==='both');const margin=Animation.AnimationUI.Options.AnimationMargin;this._delayLine.setAttribute('x1',margin);this._delayLine.setAttribute('x2',(this._delay()*this._timeline.pixelMsRatio()+margin).toFixed(2));const forwardsFill=fill==='forwards'||fill==='both';this._endDelayLine.classList.toggle('animation-fill',forwardsFill);const leftMargin=Math.min(this._timeline.width(),(this._delay()+this._duration()*this._animation.source().iterations())*this._timeline.pixelMsRatio());this._endDelayLine.style.transform='translateX('+leftMargin.toFixed(2)+'px)';this._endDelayLine.setAttribute('x1',margin);this._endDelayLine.setAttribute('x2',forwardsFill?(this._timeline.width()-leftMargin+margin).toFixed(2):(this._animation.source().endDelay()*this._timeline.pixelMsRatio()+margin).toFixed(2));}
_drawPoint(iteration,parentElement,x,keyframeIndex,attachEvents){if(this._cachedElements[iteration].keyframePoints[keyframeIndex]){this._cachedElements[iteration].keyframePoints[keyframeIndex].setAttribute('cx',x.toFixed(2));return;}
const circle=parentElement.createSVGChild('circle',keyframeIndex<=0?'animation-endpoint':'animation-keyframe-point');circle.setAttribute('cx',x.toFixed(2));circle.setAttribute('cy',Animation.AnimationUI.Options.AnimationHeight);circle.style.stroke=this._color;circle.setAttribute('r',Animation.AnimationUI.Options.AnimationMargin/2);if(keyframeIndex<=0)
circle.style.fill=this._color;this._cachedElements[iteration].keyframePoints[keyframeIndex]=circle;if(!attachEvents)
return;let eventType;if(keyframeIndex===0)
eventType=Animation.AnimationUI.MouseEvents.StartEndpointMove;else if(keyframeIndex===-1)
eventType=Animation.AnimationUI.MouseEvents.FinishEndpointMove;else
eventType=Animation.AnimationUI.MouseEvents.KeyframeMove;UI.installDragHandle(circle,this._mouseDown.bind(this,eventType,keyframeIndex),this._mouseMove.bind(this),this._mouseUp.bind(this),'ew-resize');}
_renderKeyframe(iteration,keyframeIndex,parentElement,leftDistance,width,easing){function createStepLine(parentElement,x,strokeColor){const line=parentElement.createSVGChild('line');line.setAttribute('x1',x);line.setAttribute('x2',x);line.setAttribute('y1',Animation.AnimationUI.Options.AnimationMargin);line.setAttribute('y2',Animation.AnimationUI.Options.AnimationHeight);line.style.stroke=strokeColor;}
const bezier=UI.Geometry.CubicBezier.parse(easing);const cache=this._cachedElements[iteration].keyframeRender;if(!cache[keyframeIndex]){cache[keyframeIndex]=bezier?parentElement.createSVGChild('path','animation-keyframe'):parentElement.createSVGChild('g','animation-keyframe-step');}
const group=cache[keyframeIndex];group.style.transform='translateX('+leftDistance.toFixed(2)+'px)';if(easing==='linear'){group.style.fill=this._color;const height=InlineEditor.BezierUI.Height;group.setAttribute('d',['M',0,height,'L',0,5,'L',width.toFixed(2),5,'L',width.toFixed(2),height,'Z'].join(' '));}else if(bezier){group.style.fill=this._color;InlineEditor.BezierUI.drawVelocityChart(bezier,group,width);}else{const stepFunction=Animation.AnimationTimeline.StepTimingFunction.parse(easing);group.removeChildren();const offsetMap={'start':0,'middle':0.5,'end':1};const offsetWeight=offsetMap[stepFunction.stepAtPosition];for(let i=0;i<stepFunction.steps;i++)
createStepLine(group,(i+offsetWeight)*width/stepFunction.steps,this._color);}}
redraw(){const maxWidth=this._timeline.width()-Animation.AnimationUI.Options.AnimationMargin;this._svg.setAttribute('width',(maxWidth+2*Animation.AnimationUI.Options.AnimationMargin).toFixed(2));this._activeIntervalGroup.style.transform='translateX('+(this._delay()*this._timeline.pixelMsRatio()).toFixed(2)+'px)';this._nameElement.style.transform='translateX('+
(this._delay()*this._timeline.pixelMsRatio()+Animation.AnimationUI.Options.AnimationMargin).toFixed(2)+'px)';this._nameElement.style.width=(this._duration()*this._timeline.pixelMsRatio()).toFixed(2)+'px';this._drawDelayLine(this._svg);if(this._animation.type()==='CSSTransition'){this._renderTransition();return;}
this._renderIteration(this._activeIntervalGroup,0);if(!this._tailGroup)
this._tailGroup=this._activeIntervalGroup.createSVGChild('g','animation-tail-iterations');const iterationWidth=this._duration()*this._timeline.pixelMsRatio();let iteration;for(iteration=1;iteration<this._animation.source().iterations()&&iterationWidth*(iteration-1)<this._timeline.width();iteration++)
this._renderIteration(this._tailGroup,iteration);while(iteration<this._cachedElements.length)
this._cachedElements.pop().group.remove();}
_renderTransition(){if(!this._cachedElements[0])
this._cachedElements[0]={animationLine:null,keyframePoints:{},keyframeRender:{},group:null};this._drawAnimationLine(0,this._activeIntervalGroup);this._renderKeyframe(0,0,this._activeIntervalGroup,Animation.AnimationUI.Options.AnimationMargin,this._duration()*this._timeline.pixelMsRatio(),this._animation.source().easing());this._drawPoint(0,this._activeIntervalGroup,Animation.AnimationUI.Options.AnimationMargin,0,true);this._drawPoint(0,this._activeIntervalGroup,this._duration()*this._timeline.pixelMsRatio()+Animation.AnimationUI.Options.AnimationMargin,-1,true);}
_renderIteration(parentElement,iteration){if(!this._cachedElements[iteration]){this._cachedElements[iteration]={animationLine:null,keyframePoints:{},keyframeRender:{},group:parentElement.createSVGChild('g')};}
const group=this._cachedElements[iteration].group;group.style.transform='translateX('+(iteration*this._duration()*this._timeline.pixelMsRatio()).toFixed(2)+'px)';this._drawAnimationLine(iteration,group);console.assert(this._keyframes.length>1);for(let i=0;i<this._keyframes.length-1;i++){const leftDistance=this._offset(i)*this._duration()*this._timeline.pixelMsRatio()+
Animation.AnimationUI.Options.AnimationMargin;const width=this._duration()*(this._offset(i+1)-this._offset(i))*this._timeline.pixelMsRatio();this._renderKeyframe(iteration,i,group,leftDistance,width,this._keyframes[i].easing());if(i||(!i&&iteration===0))
this._drawPoint(iteration,group,leftDistance,i,iteration===0);}
this._drawPoint(iteration,group,this._duration()*this._timeline.pixelMsRatio()+Animation.AnimationUI.Options.AnimationMargin,-1,iteration===0);}
_delay(){let delay=this._animation.source().delay();if(this._mouseEventType===Animation.AnimationUI.MouseEvents.AnimationDrag||this._mouseEventType===Animation.AnimationUI.MouseEvents.StartEndpointMove)
delay+=this._movementInMs;return Math.max(0,delay);}
_duration(){let duration=this._animation.source().duration();if(this._mouseEventType===Animation.AnimationUI.MouseEvents.FinishEndpointMove)
duration+=this._movementInMs;else if(this._mouseEventType===Animation.AnimationUI.MouseEvents.StartEndpointMove)
duration-=Math.max(this._movementInMs,-this._animation.source().delay());return Math.max(0,duration);}
_offset(i){let offset=this._keyframes[i].offsetAsNumber();if(this._mouseEventType===Animation.AnimationUI.MouseEvents.KeyframeMove&&i===this._keyframeMoved){console.assert(i>0&&i<this._keyframes.length-1,'First and last keyframe cannot be moved');offset+=this._movementInMs/this._animation.source().duration();offset=Math.max(offset,this._keyframes[i-1].offsetAsNumber());offset=Math.min(offset,this._keyframes[i+1].offsetAsNumber());}
return offset;}
_mouseDown(mouseEventType,keyframeIndex,event){if(event.buttons===2)
return false;if(this._svg.enclosingNodeOrSelfWithClass('animation-node-removed'))
return false;this._mouseEventType=mouseEventType;this._keyframeMoved=keyframeIndex;this._downMouseX=event.clientX;event.consume(true);if(this._node)
Common.Revealer.reveal(this._node);return true;}
_mouseMove(event){this._movementInMs=(event.clientX-this._downMouseX)/this._timeline.pixelMsRatio();if(this._delay()+this._duration()>this._timeline.duration()*0.8)
this._timeline.setDuration(this._timeline.duration()*1.2);this.redraw();}
_mouseUp(event){this._movementInMs=(event.clientX-this._downMouseX)/this._timeline.pixelMsRatio();if(this._mouseEventType===Animation.AnimationUI.MouseEvents.KeyframeMove)
this._keyframes[this._keyframeMoved].setOffset(this._offset(this._keyframeMoved));else
this._animation.setTiming(this._duration(),this._delay());this._movementInMs=0;this.redraw();delete this._mouseEventType;delete this._downMouseX;delete this._keyframeMoved;}
_onContextMenu(event){function showContextMenu(remoteObject){if(!remoteObject)
return;const contextMenu=new UI.ContextMenu(event);contextMenu.appendApplicableItems(remoteObject);contextMenu.show();}
this._animation.remoteObjectPromise().then(showContextMenu);event.consume(true);}};Animation.AnimationUI.MouseEvents={AnimationDrag:'AnimationDrag',KeyframeMove:'KeyframeMove',StartEndpointMove:'StartEndpointMove',FinishEndpointMove:'FinishEndpointMove'};Animation.AnimationUI.Options={AnimationHeight:26,AnimationSVGHeight:50,AnimationMargin:7,EndpointsClickRegionSize:10,GridCanvasHeight:40};Animation.AnimationUI.Colors={'Purple':Common.Color.parse('#9C27B0'),'Light Blue':Common.Color.parse('#03A9F4'),'Deep Orange':Common.Color.parse('#FF5722'),'Blue':Common.Color.parse('#5677FC'),'Lime':Common.Color.parse('#CDDC39'),'Blue Grey':Common.Color.parse('#607D8B'),'Pink':Common.Color.parse('#E91E63'),'Green':Common.Color.parse('#0F9D58'),'Brown':Common.Color.parse('#795548'),'Cyan':Common.Color.parse('#00BCD4')};;Runtime.cachedResources["animation/animationScreenshotPopover.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\nimg {\n max-height: 300px;\n border-radius: 2px;\n}\n\n.animation-progress {\n position: absolute;\n height: 2px;\n bottom: 0;\n left: 0;\n background: var(--selection-bg-color);\n}\n\n/*# sourceURL=animation/animationScreenshotPopover.css */";Runtime.cachedResources["animation/animationTimeline.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow: hidden;\n}\n\n.animation-node-row {\n width: 100%;\n display: flex;\n border-bottom: 1px dashed hsla(0,0%,94%,1);\n}\n\n.animation-node-description {\n width: 150px;\n padding-left: 8px;\n overflow: hidden;\n position: relative;\n transform-style: preserve-3d;\n border-bottom: 1px solid hsl(0, 0%, 90%);\n margin-bottom: -1px;\n background-color: hsl(0, 0%, 98%);\n display: flex;\n align-items: center;\n flex: 0 0 150px;\n}\n\n.animation-node-description > * {\n flex: 0 0 auto;\n}\n\n.animation-timeline-row {\n height: 32px;\n position: relative;\n}\n\npath.animation-keyframe {\n fill-opacity: 0.2;\n}\n\nsvg.animation-ui g:first-child:hover path.animation-keyframe {\n fill-opacity: 0.4;\n}\n\n.animation-node-selected path.animation-keyframe {\n fill-opacity: 0.4;\n}\n\nline.animation-line {\n stroke-width: 2px;\n stroke-linecap: round;\n fill: none;\n}\n\nline.animation-delay-line {\n stroke-width: 2px;\n stroke-dasharray: 6, 4;\n}\n\nline.animation-delay-line.animation-fill {\n stroke-dasharray: none;\n}\n\ncircle.animation-endpoint, circle.animation-keyframe-point {\n stroke-width: 2px;\n transition: transform 100ms cubic-bezier(0, 0, 0.2, 1);\n transform: scale(1);\n transform-box: fill-box;\n transform-origin: 50% 50%;\n}\n\n.animation-ui circle.animation-endpoint:hover, .animation-ui circle.animation-keyframe-point:hover {\n transform: scale(1.2);\n}\n\ncircle.animation-endpoint:active, circle.animation-keyframe-point:active {\n transform: scale(1);\n}\n\ncircle.animation-keyframe-point {\n fill: white;\n}\n\n.animation-name {\n position: absolute;\n top: 8px;\n color: #333;\n text-align: center;\n margin-left: -8px;\n white-space: nowrap;\n}\n\n.animation-timeline-toolbar-container {\n display: flex;\n background-color: var(--toolbar-bg-color);\n border-bottom: var(--divider-border);\n flex: 0 0 auto;\n}\n\n.animation-timeline-toolbar {\n display: inline-block;\n}\n\n.animation-timeline-header {\n height: 28px;\n border-bottom: 1px solid #ccc;\n flex-shrink: 0;\n display: flex;\n}\n\n.animation-timeline-header:after {\n content: \"\";\n height: calc(100% - 48px - 28px);\n position: absolute;\n width: 150px;\n left: 0;\n margin-top: 28px;\n background-color: hsl(0, 0%, 98%);\n z-index: 0;\n border-right: 1px solid hsl(0, 0%, 90%);\n}\n\n.animation-controls {\n flex: 0 0 15
static get MS_DISPLAY_VALUE(){return`%10d${NBSP}ms`;}
static prepareReportResult(result){const clone=(JSON.parse(JSON.stringify(result)));if(!clone.configSettings.locale){clone.configSettings.locale='en';}
for(const audit of Object.values(clone.audits)){if(audit.scoreDisplayMode==='not_applicable'||audit.scoreDisplayMode==='not-applicable'){audit.scoreDisplayMode='notApplicable';}
if(audit.details){if(audit.details.type===undefined||audit.details.type==='diagnostic'){audit.details.type='debugdata';}
if(audit.details.type==='filmstrip'){for(const screenshot of audit.details.items){if(!screenshot.data.startsWith(SCREENSHOT_PREFIX)){screenshot.data=SCREENSHOT_PREFIX+screenshot.data;}}}}}
Util.setNumberDateLocale(clone.configSettings.locale);if(clone.i18n&&clone.i18n.rendererFormattedStrings){Util.updateAllUIStrings(clone.i18n.rendererFormattedStrings);}
if(typeof clone.categories!=='object')throw new Error('No categories provided.');for(const category of Object.values(clone.categories)){category.auditRefs.forEach(auditRef=>{const result=clone.audits[auditRef.id];auditRef.result=result;if(clone.stackPacks){clone.stackPacks.forEach(pack=>{if(pack.descriptions[auditRef.id]){auditRef.stackPacks=auditRef.stackPacks||[];auditRef.stackPacks.push({title:pack.title,iconDataURL:pack.iconDataURL,description:pack.descriptions[auditRef.id],});}});}});}
return clone;}
static updateAllUIStrings(rendererFormattedStrings){for(const[key,value]of Object.entries(rendererFormattedStrings)){Util.UIStrings[key]=value;}}
static showAsPassed(audit){switch(audit.scoreDisplayMode){case'manual':case'notApplicable':return true;case'error':case'informative':return false;case'numeric':case'binary':default:return Number(audit.score)>=RATINGS.PASS.minScore;}}
static calculateRating(score,scoreDisplayMode){if(scoreDisplayMode==='manual'||scoreDisplayMode==='notApplicable'){return RATINGS.PASS.label;}else if(scoreDisplayMode==='error'){return RATINGS.ERROR.label;}else if(score===null){return RATINGS.FAIL.label;}
let rating=RATINGS.FAIL.label;if(score>=RATINGS.PASS.minScore){rating=RATINGS.PASS.label;}else if(score>=RATINGS.AVERAGE.minScore){rating=RATINGS.AVERAGE.label;}
return rating;}
static formatNumber(number,granularity=0.1){const coarseValue=Math.round(number/granularity)*granularity;return coarseValue.toLocaleString(Util.numberDateLocale);}
static formatBytesToKB(size,granularity=0.1){const kbs=(Math.round(size/1024/granularity)*granularity).toLocaleString(Util.numberDateLocale);return`${kbs}${NBSP}KB`;}
static formatMilliseconds(ms,granularity=10){const coarseTime=Math.round(ms/granularity)*granularity;return`${coarseTime.toLocaleString(Util.numberDateLocale)}${NBSP}ms`;}
static formatSeconds(ms,granularity=0.1){const coarseTime=Math.round(ms/1000/granularity)*granularity;return`${coarseTime.toLocaleString(Util.numberDateLocale)}${NBSP}s`;}
static formatDateTime(date){const options={month:'short',day:'numeric',year:'numeric',hour:'numeric',minute:'numeric',timeZoneName:'short',};let formatter=new Intl.DateTimeFormat(Util.numberDateLocale,options);const tz=formatter.resolvedOptions().timeZone;if(!tz||tz.toLowerCase()==='etc/unknown'){options.timeZone='UTC';formatter=new Intl.DateTimeFormat(Util.numberDateLocale,options);}
return formatter.format(new Date(date));}
static formatDuration(timeInMilliseconds){let timeInSeconds=timeInMilliseconds/1000;if(Math.round(timeInSeconds)===0){return'None';}
const parts=[];const unitLabels=({d:60*60*24,h:60*60,m:60,s:1,});Object.keys(unitLabels).forEach(label=>{const unit=unitLabels[label];const numberOfUnits=Math.floor(timeInSeconds/unit);if(numberOfUnits>0){timeInSeconds-=numberOfUnits*unit;parts.push(`${numberOfUnits}\xa0${label}`);}});return parts.join(' ');}
static getURLDisplayName(parsedUrl,options){options=options||{numPathParts:undefined,preserveQuery:undefined,preserveHost:undefined};const numPathParts=options.numPathParts!==undefined?options.numPathParts:2;const preserveQuery=options.preserveQuery!==undefined?options.preserveQuery:true;const preserveHost=options.preserveHost||false;let name;if(parsedUrl.protocol==='about:'||parsedUrl.protocol==='data:'){name=parsedUrl.href;}else{name=parsedUrl.pathname;const parts=name.split('/').filter(part=>part.length);if(numPathParts&&parts.length>numPathParts){name=ELLIPSIS+parts.slice(-1*numPathParts).join('/');}
if(preserveHost){name=`${parsedUrl.host}/${name.replace(/^\//, '')}`;}
if(preserveQuery){name=`${name}${parsedUrl.search}`;}}
const MAX_LENGTH=64;name=name.replace(/([a-f0-9]{7})[a-f0-9]{13}[a-f0-9]*/g,`$1${ELLIPSIS}`);name=name.replace(/([a-zA-Z0-9-_]{9})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9-_]{10,}/g,`$1${ELLIPSIS}`);name=name.replace(/(\d{3})\d{6,}/g,`$1${ELLIPSIS}`);name=name.replace(/\u2026+/g,ELLIPSIS);if(name.length>MAX_LENGTH&&name.includes('?')){name=name.replace(/\?([^=]*)(=)?.*/,`?$1$2${ELLIPSIS}`);if(name.length>MAX_LENGTH){name=name.replace(/\?.*/,`?${ELLIPSIS}`);}}
if(name.length>MAX_LENGTH){const dotIndex=name.lastIndexOf('.');if(dotIndex>=0){name=name.slice(0,MAX_LENGTH-1-(name.length-dotIndex))+`${ELLIPSIS}${name.slice(dotIndex)}`;}else{name=name.slice(0,MAX_LENGTH-1)+ELLIPSIS;}}
return name;}
static parseURL(url){const parsedUrl=new URL(url);return{file:Util.getURLDisplayName(parsedUrl),hostname:parsedUrl.hostname,origin:parsedUrl.origin,};}
static createOrReturnURL(value){if(value instanceof URL){return value;}
return new URL(value);}
static getTld(hostname){const tlds=hostname.split('.').slice(-2);if(!listOfTlds.includes(tlds[0])){return`.${tlds[tlds.length - 1]}`;}
return`.${tlds.join('.')}`;}
static getRootDomain(url){const hostname=Util.createOrReturnURL(url).hostname;const tld=Util.getTld(hostname);const splitTld=tld.split('.');return hostname.split('.').slice(-splitTld.length).join('.');}
static getEnvironmentDisplayValues(settings){const emulationDesc=Util.getEmulationDescriptions(settings);return[{name:'Device',description:emulationDesc.deviceEmulation,},{name:'Network throttling',description:emulationDesc.networkThrottling,},{name:'CPU throttling',description:emulationDesc.cpuThrottling,},];}
static getEmulationDescriptions(settings){let cpuThrottling;let networkThrottling;let summary;const throttling=settings.throttling;switch(settings.throttlingMethod){case'provided':cpuThrottling='Provided by environment';networkThrottling='Provided by environment';summary='No throttling applied';break;case'devtools':{const{cpuSlowdownMultiplier,requestLatencyMs}=throttling;cpuThrottling=`${Util.formatNumber(cpuSlowdownMultiplier)}x slowdown (DevTools)`;networkThrottling=`${Util.formatNumber(requestLatencyMs)}${NBSP}ms HTTP RTT, `+`${Util.formatNumber(throttling.downloadThroughputKbps)}${NBSP}Kbps down, `+`${Util.formatNumber(throttling.uploadThroughputKbps)}${NBSP}Kbps up (DevTools)`;summary='Throttled Slow 4G network';break;}
case'simulate':{const{cpuSlowdownMultiplier,rttMs,throughputKbps}=throttling;cpuThrottling=`${Util.formatNumber(cpuSlowdownMultiplier)}x slowdown (Simulated)`;networkThrottling=`${Util.formatNumber(rttMs)}${NBSP}ms TCP RTT, `+`${Util.formatNumber(throughputKbps)}${NBSP}Kbps throughput (Simulated)`;summary='Simulated Slow 4G network';break;}
default:cpuThrottling='Unknown';networkThrottling='Unknown';summary='Unknown';}
let deviceEmulation='No emulation';if(settings.emulatedFormFactor==='mobile')deviceEmulation='Emulated Nexus 5X';if(settings.emulatedFormFactor==='desktop')deviceEmulation='Emulated Desktop';return{deviceEmulation,cpuThrottling,networkThrottling,summary:`${deviceEmulation}, ${summary}`,};}
static setNumberDateLocale(locale){Util.numberDateLocale=locale;if(Util.numberDateLocale==='en-XA')Util.numberDateLocale='de';}
static filterRelevantLines(lines,lineMessages,surroundingLineCount){if(lineMessages.length===0){return lines.slice(0,surroundingLineCount*2+1);}
const minGapSize=3;const lineNumbersToKeep=new Set();lineMessages=lineMessages.sort((a,b)=>(a.lineNumber||0)-(b.lineNumber||0));lineMessages.forEach(({lineNumber})=>{let firstSurroundingLineNumber=lineNumber-surroundingLineCount;let lastSurroundingLineNumber=lineNumber+surroundingLineCount;while(firstSurroundingLineNumber<1){firstSurroundingLineNumber++;lastSurroundingLineNumber++;}
if(lineNumbersToKeep.has(firstSurroundingLineNumber-minGapSize-1)){firstSurroundingLineNumber-=minGapSize;}
for(let i=firstSurroundingLineNumber;i<=lastSurroundingLineNumber;i++){const surroundingLineNumber=i;lineNumbersToKeep.add(surroundingLineNumber);}});return lines.filter(line=>lineNumbersToKeep.has(line.lineNumber));}
static isPluginCategory(categoryId){return categoryId.startsWith('lighthouse-plugin-');}}
Util.numberDateLocale='en';Util.UIStrings={varianceDisclaimer:'Values are estimated and may vary.',opportunityResourceColumnLabel:'Opportunity',opportunitySavingsColumnLabel:'Estimated Savings',errorMissingAuditInfo:'Report error: no audit information',errorLabel:'Error!',warningHeader:'Warnings: ',auditGroupExpandTooltip:'Show audits',warningAuditsGroupTitle:'Passed audits but with warnings',passedAuditsGroupTitle:'Passed audits',notApplicableAuditsGroupTitle:'Not applicable',manualAuditsGroupTitle:'Additional items to manually check',toplevelWarningsMessage:'There were issues affecting this run of Lighthouse:',crcInitialNavigation:'Initial Navigation',crcLongestDurationLabel:'Maximum critical path latency:',snippetExpandButtonLabel:'Expand snippet',snippetCollapseButtonLabel:'Collapse snippet',lsPerformanceCategoryDescription:'[Lighthouse](https://developers.google.com/web/tools/lighthouse/) analysis of the current page on an emulated mobile network. Values are estimated and may vary.',labDataTitle:'Lab Data',thirdPartyResourcesLabel:'Show 3rd-party resources',};if(typeof module!=='undefined'&&module.exports){module.exports=Util;}else{self.Util=Util;};'use strict';class DOM{constructor(document){this._document=document;this._lighthouseChannel='unknown';}
createElement(name,className,attrs={}){const element=this._document.createElement(name);if(className){element.className=className;}
Object.keys(attrs).forEach(key=>{const value=attrs[key];if(typeof value!=='undefined'){element.setAttribute(key,value);}});return element;}
createFragment(){return this._document.createDocumentFragment();}
createChildOf(parentElem,elementName,className,attrs){const element=this.createElement(elementName,className,attrs);parentElem.appendChild(element);return element;}
cloneTemplate(selector,context){const template=(context.querySelector(selector));if(!template){throw new Error(`Template not found: template${selector}`);}
const clone=this._document.importNode(template.content,true);if(template.hasAttribute('data-stamped')){this.findAll('style',clone).forEach(style=>style.remove());}
template.setAttribute('data-stamped','true');return clone;}
resetTemplates(){this.findAll('template[data-stamped]',this._document).forEach(t=>{t.removeAttribute('data-stamped');});}
convertMarkdownLinkSnippets(text){const element=this.createElement('span');const parts=text.split(/\[([^\]]*?)\]\((https?:\/\/.*?)\)/g);while(parts.length){const[preambleText,linkText,linkHref]=parts.splice(0,3);element.appendChild(this._document.createTextNode(preambleText));if(linkText&&linkHref){const url=new URL(linkHref);const DEVELOPERS_GOOGLE_ORIGIN='https://developers.google.com';if(url.origin===DEVELOPERS_GOOGLE_ORIGIN){url.searchParams.set('utm_source','lighthouse');url.searchParams.set('utm_medium',this._lighthouseChannel);}
const a=this.createElement('a');a.rel='noopener';a.target='_blank';a.textContent=linkText;a.href=url.href;element.appendChild(a);}}
return element;}
convertMarkdownCodeSnippets(text){const element=this.createElement('span');const parts=text.split(/`(.*?)`/g);while(parts.length){const[preambleText,codeText]=parts.splice(0,2);element.appendChild(this._document.createTextNode(preambleText));if(codeText){const pre=this.createElement('code');pre.textContent=codeText;element.appendChild(pre);}}
return element;}
setLighthouseChannel(lighthouseChannel){this._lighthouseChannel=lighthouseChannel;}
document(){return this._document;}
isDevTools(){return!!this._document.querySelector('.lh-devtools');}
find(query,context){const result=context.querySelector(query);if(result===null){throw new Error(`query ${query} not found`);}
return result;}
findAll(query,context){return Array.from(context.querySelectorAll(query));}}
if(typeof module!=='undefined'&&module.exports){module.exports=DOM;}else{self.DOM=DOM;};(function(){"use strict";var element=document.createElement("details");element.innerHTML="<summary>a</summary>b";element.setAttribute("style","position: absolute; left: -9999px");var support={open:"open"in element&&elementExpands(),toggle:"ontoggle"in element};function elementExpands(){(document.body||document.documentElement).appendChild(element);var closedHeight=element.offsetHeight;element.open=true;var openedHeight=element.offsetHeight;element.parentNode.removeChild(element);return closedHeight!=openedHeight;}
var styles='\ndetails, summary {\n display: block;\n}\ndetails:not([open]) > *:not(summary) {\n display: none;\n}\ndetails > summary::before {\n content: "►";\n padding-right: 0.3rem;\n font-size: 0.6rem;\n cursor: default;\n}\ndetails[open] > summary::before {\n content: "▼";\n}\n';var _ref=[],forEach=_ref.forEach,slice=_ref.slice;if(!support.open){polyfillStyles();polyfillProperties();polyfillToggle();polyfillAccessibility();}
if(support.open&&!support.toggle){polyfillToggleEvent();}
function polyfillStyles(){document.head.insertAdjacentHTML("afterbegin","<style>"+styles+"</style>");}
function polyfillProperties(){var prototype=document.createElement("details").constructor.prototype;var setAttribute=prototype.setAttribute,removeAttribute=prototype.removeAttribute;var open=Object.getOwnPropertyDescriptor(prototype,"open");Object.defineProperties(prototype,{open:{get:function get(){if(this.tagName=="DETAILS"){return this.hasAttribute("open");}else{if(open&&open.get){return open.get.call(this);}}},set:function set(value){if(this.tagName=="DETAILS"){return value?this.setAttribute("open",""):this.removeAttribute("open");}else{if(open&&open.set){return open.set.call(this,value);}}}},setAttribute:{value:function value(name,_value){var _this=this;var call=function call(){return setAttribute.call(_this,name,_value);};if(name=="open"&&this.tagName=="DETAILS"){var wasOpen=this.hasAttribute("open");var result=call();if(!wasOpen){var summary=this.querySelector("summary");if(summary)summary.setAttribute("aria-expanded",true);triggerToggle(this);}
return result;}
return call();}},removeAttribute:{value:function value(name){var _this2=this;var call=function call(){return removeAttribute.call(_this2,name);};if(name=="open"&&this.tagName=="DETAILS"){var wasOpen=this.hasAttribute("open");var result=call();if(wasOpen){var summary=this.querySelector("summary");if(summary)summary.setAttribute("aria-expanded",false);triggerToggle(this);}
return result;}
return call();}}});}
function polyfillToggle(){onTogglingTrigger(function(element){element.hasAttribute("open")?element.removeAttribute("open"):element.setAttribute("open","");});}
function polyfillToggleEvent(){if(window.MutationObserver){new MutationObserver(function(mutations){forEach.call(mutations,function(mutation){var target=mutation.target,attributeName=mutation.attributeName;if(target.tagName=="DETAILS"&&attributeName=="open"){triggerToggle(toggle);}});}).observe(document.documentElement,{attributes:true,subtree:true});}else{onTogglingTrigger(function(element){var wasOpen=element.getAttribute("open");setTimeout(function(){var isOpen=element.getAttribute("open");if(wasOpen!=isOpen){triggerToggle(element);}},1);});}}
function polyfillAccessibility(){setAccessibilityAttributes(document);if(window.MutationObserver){new MutationObserver(function(mutations){forEach.call(mutations,function(mutation){forEach.call(mutation.addedNodes,setAccessibilityAttributes);});}).observe(document.documentElement,{subtree:true,childList:true});}else{document.addEventListener("DOMNodeInserted",function(event){setAccessibilityAttributes(event.target);});}}
function setAccessibilityAttributes(root){findElementsWithTagName(root,"SUMMARY").forEach(function(summary){var details=findClosestElementWithTagName(summary,"DETAILS");summary.setAttribute("aria-expanded",details.hasAttribute("open"));if(!summary.hasAttribute("tabindex"))summary.setAttribute("tabindex","0");if(!summary.hasAttribute("role"))summary.setAttribute("role","button");});}
function eventIsSignificant(event){return!(event.defaultPrevented||event.ctrlKey||event.metaKey||event.shiftKey||event.target.isContentEditable);}
function onTogglingTrigger(callback){addEventListener("click",function(event){if(eventIsSignificant(event)){if(event.which<=1){var element=findClosestElementWithTagName(event.target,"SUMMARY");if(element&&element.parentNode&&element.parentNode.tagName=="DETAILS"){callback(element.parentNode);}}}},false);addEventListener("keydown",function(event){if(eventIsSignificant(event)){if(event.keyCode==13||event.keyCode==32){var element=findClosestElementWithTagName(event.target,"SUMMARY");if(element&&element.parentNode&&element.parentNode.tagName=="DETAILS"){callback(element.parentNode);event.preventDefault();}}}},false);}
function triggerToggle(element){var event=document.createEvent("Event");event.initEvent("toggle",true,false);element.dispatchEvent(event);}
function findElementsWithTagName(root,tagName){return(root.tagName==tagName?[root]:[]).concat(typeof root.getElementsByTagName=="function"?slice.call(root.getElementsByTagName(tagName)):[]);}
function findClosestElementWithTagName(element,tagName){if(typeof element.closest=="function"){return element.closest(tagName);}else{while(element){if(element.tagName==tagName){return element;}else{element=element.parentNode;}}}}})();;'use strict';const URL_PREFIXES=['http://','https://','data:'];class DetailsRenderer{constructor(dom){this._dom=dom;this._templateContext;}
setTemplateContext(context){this._templateContext=context;}
render(details){switch(details.type){case'filmstrip':return this._renderFilmstrip(details);case'list':return this._renderList(details);case'table':return this._renderTable(details);case'criticalrequestchain':return CriticalRequestChainRenderer.render(this._dom,this._templateContext,details);case'opportunity':return this._renderTable(details);case'screenshot':case'debugdata':return null;default:{const detailsType=details.type;throw new Error(`Unknown type: ${detailsType}`);}}}
_renderBytes(details){const value=Util.formatBytesToKB(details.value,details.granularity);return this._renderText(value);}
_renderMilliseconds(details){let value=Util.formatMilliseconds(details.value,details.granularity);if(details.displayUnit==='duration'){value=Util.formatDuration(details.value);}
return this._renderText(value);}
_renderTextURL(text){const url=text;let displayedPath;let displayedHost;let title;try{const parsed=Util.parseURL(url);displayedPath=parsed.file==='/'?parsed.origin:parsed.file;displayedHost=parsed.file==='/'?'':`(${parsed.hostname})`;title=url;}catch(e){displayedPath=url;}
const element=this._dom.createElement('div','lh-text__url');element.appendChild(this._renderText(displayedPath));if(displayedHost){const hostElem=this._renderText(displayedHost);hostElem.classList.add('lh-text__url-host');element.appendChild(hostElem);}
if(title){element.title=url;element.dataset.url=url;}
return element;}
_renderLink(details){const allowedProtocols=['https:','http:'];const url=new URL(details.url);if(!allowedProtocols.includes(url.protocol)){return this._renderText(details.text);}
const a=this._dom.createElement('a');a.rel='noopener';a.target='_blank';a.textContent=details.text;a.href=url.href;return a;}
_renderText(text){const element=this._dom.createElement('div','lh-text');element.textContent=text;return element;}
_renderNumeric(text){const element=this._dom.createElement('div','lh-numeric');element.textContent=text;return element;}
_renderThumbnail(details){const element=this._dom.createElement('img','lh-thumbnail');const strValue=details;element.src=strValue;element.title=strValue;element.alt='';return element;}
_renderTableValue(value,heading){if(typeof value==='undefined'||value===null){return null;}
if(typeof value==='object'){switch(value.type){case'code':{return this._renderCode(value.value);}
case'link':{return this._renderLink(value);}
case'node':{return this.renderNode(value);}
case'url':{return this._renderTextURL(value.value);}
default:{throw new Error(`Unknown valueType: ${value.type}`);}}}
switch(heading.valueType){case'bytes':{const numValue=Number(value);return this._renderBytes({value:numValue,granularity:1});}
case'code':{const strValue=String(value);return this._renderCode(strValue);}
case'ms':{const msValue={value:Number(value),granularity:heading.granularity,displayUnit:heading.displayUnit,};return this._renderMilliseconds(msValue);}
case'numeric':{const strValue=String(value);return this._renderNumeric(strValue);}
case'text':{const strValue=String(value);return this._renderText(strValue);}
case'thumbnail':{const strValue=String(value);return this._renderThumbnail(strValue);}
case'timespanMs':{const numValue=Number(value);return this._renderMilliseconds({value:numValue});}
case'url':{const strValue=String(value);if(URL_PREFIXES.some(prefix=>strValue.startsWith(prefix))){return this._renderTextURL(strValue);}else{return this._renderCode(strValue);}}
default:{throw new Error(`Unknown valueType: ${heading.valueType}`);}}}
_getCanonicalizedTableHeadings(tableLike){if(tableLike.type==='opportunity'){return tableLike.headings;}
return tableLike.headings.map(heading=>{return{key:heading.key,label:heading.text,valueType:heading.itemType,displayUnit:heading.displayUnit,granularity:heading.granularity,};});}
_renderTable(details){if(!details.items.length)return this._dom.createElement('span');const tableElem=this._dom.createElement('table','lh-table');const theadElem=this._dom.createChildOf(tableElem,'thead');const theadTrElem=this._dom.createChildOf(theadElem,'tr');const headings=this._getCanonicalizedTableHeadings(details);for(const heading of headings){const valueType=heading.valueType||'text';const classes=`lh-table-column--${valueType}`;const labelEl=this._dom.createElement('div','lh-text');labelEl.textContent=heading.label;this._dom.createChildOf(theadTrElem,'th',classes).appendChild(labelEl);}
const tbodyElem=this._dom.createChildOf(tableElem,'tbody');for(const row of details.items){const rowElem=this._dom.createChildOf(tbodyElem,'tr');for(const heading of headings){const value=row[heading.key];const valueElement=this._renderTableValue(value,heading);if(valueElement){const classes=`lh-table-column--${heading.valueType}`;this._dom.createChildOf(rowElem,'td',classes).appendChild(valueElement);}else{this._dom.createChildOf(rowElem,'td','lh-table-column--empty');}}}
return tableElem;}
_renderList(details){const listContainer=this._dom.createElement('div','lh-list');details.items.forEach(item=>{const snippetEl=SnippetRenderer.render(this._dom,this._templateContext,item,this);listContainer.appendChild(snippetEl);});return listContainer;}
renderNode(item){const element=this._dom.createElement('span','lh-node');if(item.nodeLabel){const nodeLabelEl=this._dom.createElement('div');nodeLabelEl.textContent=item.nodeLabel;element.appendChild(nodeLabelEl);}
if(item.snippet){const snippetEl=this._dom.createElement('div');snippetEl.classList.add('lh-node__snippet');snippetEl.textContent=item.snippet;element.appendChild(snippetEl);}
if(item.selector){element.title=item.selector;}
if(item.path)element.setAttribute('data-path',item.path);if(item.selector)element.setAttribute('data-selector',item.selector);if(item.snippet)element.setAttribute('data-snippet',item.snippet);return element;}
_renderFilmstrip(details){const filmstripEl=this._dom.createElement('div','lh-filmstrip');for(const thumbnail of details.items){const frameEl=this._dom.createChildOf(filmstripEl,'div','lh-filmstrip__frame');this._dom.createChildOf(frameEl,'img','lh-filmstrip__thumbnail',{src:thumbnail.data,alt:`Screenshot`,});}
return filmstripEl;}
_renderCode(text){const pre=this._dom.createElement('pre','lh-code');pre.textContent=text;return pre;}}
if(typeof module!=='undefined'&&module.exports){module.exports=DetailsRenderer;}else{self.DetailsRenderer=DetailsRenderer;};'use strict';class CriticalRequestChainRenderer{static initTree(tree){let startTime=0;const rootNodes=Object.keys(tree);if(rootNodes.length>0){const node=tree[rootNodes[0]];startTime=node.request.startTime;}
return{tree,startTime,transferSize:0};}
static createSegment(parent,id,startTime,transferSize,treeMarkers,parentIsLastChild){const node=parent[id];const siblings=Object.keys(parent);const isLastChild=siblings.indexOf(id)===(siblings.length-1);const hasChildren=!!node.children&&Object.keys(node.children).length>0;const newTreeMarkers=Array.isArray(treeMarkers)?treeMarkers.slice(0):[];if(typeof parentIsLastChild!=='undefined'){newTreeMarkers.push(!parentIsLastChild);}
return{node,isLastChild,hasChildren,startTime,transferSize:transferSize+node.request.transferSize,treeMarkers:newTreeMarkers,};}
static createChainNode(dom,tmpl,segment){const chainsEl=dom.cloneTemplate('#tmpl-lh-crc__chains',tmpl);dom.find('.crc-node',chainsEl).setAttribute('title',segment.node.request.url);const treeMarkeEl=dom.find('.crc-node__tree-marker',chainsEl);segment.treeMarkers.forEach(separator=>{if(separator){treeMarkeEl.appendChild(dom.createElement('span','tree-marker vert'));treeMarkeEl.appendChild(dom.createElement('span','tree-marker'));}else{treeMarkeEl.appendChild(dom.createElement('span','tree-marker'));treeMarkeEl.appendChild(dom.createElement('span','tree-marker'));}});if(segment.isLastChild){treeMarkeEl.appendChild(dom.createElement('span','tree-marker up-right'));treeMarkeEl.appendChild(dom.createElement('span','tree-marker right'));}else{treeMarkeEl.appendChild(dom.createElement('span','tree-marker vert-right'));treeMarkeEl.appendChild(dom.createElement('span','tree-marker right'));}
if(segment.hasChildren){treeMarkeEl.appendChild(dom.createElement('span','tree-marker horiz-down'));}else{treeMarkeEl.appendChild(dom.createElement('span','tree-marker right'));}
const{file,hostname}=Util.parseURL(segment.node.request.url);const treevalEl=dom.find('.crc-node__tree-value',chainsEl);dom.find('.crc-node__tree-file',treevalEl).textContent=`${file}`;dom.find('.crc-node__tree-hostname',treevalEl).textContent=hostname?`(${hostname})`:'';if(!segment.hasChildren){const{startTime,endTime,transferSize}=segment.node.request;const span=dom.createElement('span','crc-node__chain-duration');span.textContent=' - '+Util.formatMilliseconds((endTime-startTime)*1000)+', ';const span2=dom.createElement('span','crc-node__chain-duration');span2.textContent=Util.formatBytesToKB(transferSize,0.01);treevalEl.appendChild(span);treevalEl.appendChild(span2);}
return chainsEl;}
static buildTree(dom,tmpl,segment,elem,details){elem.appendChild(CriticalRequestChainRenderer.createChainNode(dom,tmpl,segment));if(segment.node.children){for(const key of Object.keys(segment.node.children)){const childSegment=CriticalRequestChainRenderer.createSegment(segment.node.children,key,segment.startTime,segment.transferSize,segment.treeMarkers,segment.isLastChild);CriticalRequestChainRenderer.buildTree(dom,tmpl,childSegment,elem,details);}}}
static render(dom,templateContext,details){const tmpl=dom.cloneTemplate('#tmpl-lh-crc',templateContext);const containerEl=dom.find('.lh-crc',tmpl);dom.find('.crc-initial-nav',tmpl).textContent=Util.UIStrings.crcInitialNavigation;dom.find('.lh-crc__longest_duration_label',tmpl).textContent=Util.UIStrings.crcLongestDurationLabel;dom.find('.lh-crc__longest_duration',tmpl).textContent=Util.formatMilliseconds(details.longestChain.duration);const root=CriticalRequestChainRenderer.initTree(details.chains);for(const key of Object.keys(root.tree)){const segment=CriticalRequestChainRenderer.createSegment(root.tree,key,root.startTime,root.transferSize);CriticalRequestChainRenderer.buildTree(dom,tmpl,segment,containerEl,details);}
return dom.find('.lh-crc-container',tmpl);}}
if(typeof module!=='undefined'&&module.exports){module.exports=CriticalRequestChainRenderer;}else{self.CriticalRequestChainRenderer=CriticalRequestChainRenderer;};'use strict';const LineVisibility={ALWAYS:0,WHEN_COLLAPSED:1,WHEN_EXPANDED:2,};const LineContentType={CONTENT_NORMAL:0,CONTENT_HIGHLIGHTED:1,PLACEHOLDER:2,MESSAGE:3,};const classNamesByContentType={[LineContentType.CONTENT_NORMAL]:['lh-snippet__line--content'],[LineContentType.CONTENT_HIGHLIGHTED]:['lh-snippet__line--content','lh-snippet__line--content-highlighted',],[LineContentType.PLACEHOLDER]:['lh-snippet__line--placeholder'],[LineContentType.MESSAGE]:['lh-snippet__line--message'],};function getLineAndPreviousLine(lines,lineNumber){return{line:lines.find(l=>l.lineNumber===lineNumber),previousLine:lines.find(l=>l.lineNumber===lineNumber-1),};}
function getMessagesForLineNumber(messages,lineNumber){return messages.filter(h=>h.lineNumber===lineNumber);}
function getLinesWhenCollapsed(details){const SURROUNDING_LINES_TO_SHOW_WHEN_COLLAPSED=2;return Util.filterRelevantLines(details.lines,details.lineMessages,SURROUNDING_LINES_TO_SHOW_WHEN_COLLAPSED);}
class SnippetRenderer{static renderHeader(dom,tmpl,details,detailsRenderer,toggleExpandedFn){const linesWhenCollapsed=getLinesWhenCollapsed(details);const canExpand=linesWhenCollapsed.length<details.lines.length;const header=dom.cloneTemplate('#tmpl-lh-snippet__header',tmpl);dom.find('.lh-snippet__title',header).textContent=details.title;const{snippetCollapseButtonLabel,snippetExpandButtonLabel,}=Util.UIStrings;dom.find('.lh-snippet__btn-label-collapse',header).textContent=snippetCollapseButtonLabel;dom.find('.lh-snippet__btn-label-expand',header).textContent=snippetExpandButtonLabel;const toggleExpandButton=dom.find('.lh-snippet__toggle-expand',header);if(!canExpand){toggleExpandButton.remove();}else{toggleExpandButton.addEventListener('click',()=>toggleExpandedFn());}
if(details.node&&dom.isDevTools()){const nodeContainer=dom.find('.lh-snippet__node',header);nodeContainer.appendChild(detailsRenderer.renderNode(details.node));}
return header;}
static renderSnippetLine(dom,tmpl,{content,lineNumber,truncated,contentType,visibility}){const clonedTemplate=dom.cloneTemplate('#tmpl-lh-snippet__line',tmpl);const contentLine=dom.find('.lh-snippet__line',clonedTemplate);const{classList}=contentLine;classNamesByContentType[contentType].forEach(typeClass=>classList.add(typeClass));if(visibility===LineVisibility.WHEN_COLLAPSED){classList.add('lh-snippet__show-if-collapsed');}else if(visibility===LineVisibility.WHEN_EXPANDED){classList.add('lh-snippet__show-if-expanded');}
const lineContent=content+(truncated?'…':'');const lineContentEl=dom.find('.lh-snippet__line code',contentLine);if(contentType===LineContentType.MESSAGE){lineContentEl.appendChild(dom.convertMarkdownLinkSnippets(lineContent));}else{lineContentEl.textContent=lineContent;}
dom.find('.lh-snippet__line-number',contentLine).textContent=lineNumber.toString();return contentLine;}
static renderMessage(dom,tmpl,message){return SnippetRenderer.renderSnippetLine(dom,tmpl,{lineNumber:' ',content:message.message,contentType:LineContentType.MESSAGE,});}
static renderOmittedLinesPlaceholder(dom,tmpl,visibility){return SnippetRenderer.renderSnippetLine(dom,tmpl,{lineNumber:'…',content:'',visibility,contentType:LineContentType.PLACEHOLDER,});}
static renderSnippetContent(dom,tmpl,details){const template=dom.cloneTemplate('#tmpl-lh-snippet__content',tmpl);const snippetEl=dom.find('.lh-snippet__snippet-inner',template);details.generalMessages.forEach(m=>snippetEl.append(SnippetRenderer.renderMessage(dom,tmpl,m)));snippetEl.append(SnippetRenderer.renderSnippetLines(dom,tmpl,details));return template;}
static renderSnippetLines(dom,tmpl,details){const{lineMessages,generalMessages,lineCount,lines}=details;const linesWhenCollapsed=getLinesWhenCollapsed(details);const hasOnlyGeneralMessages=generalMessages.length>0&&lineMessages.length===0;const lineContainer=dom.createFragment();let hasPendingOmittedLinesPlaceholderForCollapsedState=false;for(let lineNumber=1;lineNumber<=lineCount;lineNumber++){const{line,previousLine}=getLineAndPreviousLine(lines,lineNumber);const{line:lineWhenCollapsed,previousLine:previousLineWhenCollapsed,}=getLineAndPreviousLine(linesWhenCollapsed,lineNumber);const showLineWhenCollapsed=!!lineWhenCollapsed;const showPreviousLineWhenCollapsed=!!previousLineWhenCollapsed;if(showPreviousLineWhenCollapsed&&!showLineWhenCollapsed){hasPendingOmittedLinesPlaceholderForCollapsedState=true;}
if(showLineWhenCollapsed&&hasPendingOmittedLinesPlaceholderForCollapsedState){lineContainer.append(SnippetRenderer.renderOmittedLinesPlaceholder(dom,tmpl,LineVisibility.WHEN_COLLAPSED));hasPendingOmittedLinesPlaceholderForCollapsedState=false;}
const isFirstOmittedLineWhenExpanded=!line&&!!previousLine;const isFirstLineOverallAndIsOmittedWhenExpanded=!line&&lineNumber===1;if(isFirstOmittedLineWhenExpanded||isFirstLineOverallAndIsOmittedWhenExpanded){const hasRenderedAllLinesVisibleWhenCollapsed=!linesWhenCollapsed.some(l=>l.lineNumber>lineNumber);const onlyShowWhenExpanded=hasRenderedAllLinesVisibleWhenCollapsed||lineNumber===1;lineContainer.append(SnippetRenderer.renderOmittedLinesPlaceholder(dom,tmpl,onlyShowWhenExpanded?LineVisibility.WHEN_EXPANDED:LineVisibility.ALWAYS));hasPendingOmittedLinesPlaceholderForCollapsedState=false;}
if(!line){continue;}
const messages=getMessagesForLineNumber(lineMessages,lineNumber);const highlightLine=messages.length>0||hasOnlyGeneralMessages;const contentLineDetails=Object.assign({},line,{contentType:highlightLine?LineContentType.CONTENT_HIGHLIGHTED:LineContentType.CONTENT_NORMAL,visibility:lineWhenCollapsed?LineVisibility.ALWAYS:LineVisibility.WHEN_EXPANDED,});lineContainer.append(SnippetRenderer.renderSnippetLine(dom,tmpl,contentLineDetails));messages.forEach(message=>{lineContainer.append(SnippetRenderer.renderMessage(dom,tmpl,message));});}
return lineContainer;}
static render(dom,templateContext,details,detailsRenderer){const tmpl=dom.cloneTemplate('#tmpl-lh-snippet',templateContext);const snippetEl=dom.find('.lh-snippet',tmpl);const header=SnippetRenderer.renderHeader(dom,tmpl,details,detailsRenderer,()=>snippetEl.classList.toggle('lh-snippet--expanded'));const content=SnippetRenderer.renderSnippetContent(dom,tmpl,details);snippetEl.append(header,content);return snippetEl;}}
if(typeof module!=='undefined'&&module.exports){module.exports=SnippetRenderer;}else{self.SnippetRenderer=SnippetRenderer;};'use strict';function getFilenamePrefix(lhr){const hostname=new URL(lhr.finalUrl).hostname;const date=(lhr.fetchTime&&new Date(lhr.fetchTime))||new Date();const timeStr=date.toLocaleTimeString('en-US',{hour12:false});const dateParts=date.toLocaleDateString('en-US',{year:'numeric',month:'2-digit',day:'2-digit',}).split('/');dateParts.unshift(dateParts.pop());const dateStr=dateParts.join('-');const filenamePrefix=`${hostname}_${dateStr}_${timeStr}`;return filenamePrefix.replace(/[/?<>\\:*|":]/g,'-');}
if(typeof module!=='undefined'&&module.exports){module.exports={getFilenamePrefix};};'use strict';class Logger{constructor(element){this.el=element;this._id=undefined;}
log(msg,autoHide=true){this._id&&clearTimeout(this._id);this.el.textContent=msg;this.el.classList.add('show');if(autoHide){this._id=setTimeout(_=>{this.el.classList.remove('show');},7000);}}
warn(msg){this.log('Warning: '+msg);}
error(msg){this.log(msg);setTimeout(_=>{throw new Error(msg);},0);}
hide(){this._id&&clearTimeout(this._id);this.el.classList.remove('show');}}
if(typeof module!=='undefined'&&module.exports){module.exports=Logger;};'use strict';function getTableRows(tableEl){return Array.from(tableEl.tBodies[0].rows);}
class ReportUIFeatures{constructor(dom){this.json;this._dom=dom;this._document=this._dom.document();this._templateContext=this._dom.document();this._copyAttempt=false;this.exportButton;this.topbarEl;this.scoreScaleEl;this.stickyHeaderEl;this.highlightEl;this.onMediaQueryChange=this.onMediaQueryChange.bind(this);this.onCopy=this.onCopy.bind(this);this.onExportButtonClick=this.onExportButtonClick.bind(this);this.onExport=this.onExport.bind(this);this.onKeyDown=this.onKeyDown.bind(this);this.onKeyUp=this.onKeyUp.bind(this);this.onChevronClick=this.onChevronClick.bind(this);this.collapseAllDetails=this.collapseAllDetails.bind(this);this.expandAllDetails=this.expandAllDetails.bind(this);this._toggleDarkTheme=this._toggleDarkTheme.bind(this);this._updateStickyHeaderOnScroll=this._updateStickyHeaderOnScroll.bind(this);}
initFeatures(report){this.json=report;this._setupMediaQueryListeners();this._setupExportButton();this._setupThirdPartyFilter();this._setUpCollapseDetailsAfterPrinting();this._resetUIState();this._document.addEventListener('keyup',this.onKeyUp);this._document.addEventListener('copy',this.onCopy);const topbarLogo=this._dom.find('.lh-topbar__logo',this._document);topbarLogo.addEventListener('click',()=>this._toggleDarkTheme());let turnOffTheLights=false;if(window.matchMedia('(prefers-color-scheme: dark)').matches){turnOffTheLights=true;}
const scoresAll100=Object.values(report.categories).every(cat=>cat.score===1);const hasAllCoreCategories=Object.keys(report.categories).filter(id=>!Util.isPluginCategory(id)).length>=5;if(scoresAll100&&hasAllCoreCategories){turnOffTheLights=true;this._enableFireworks();}
if(turnOffTheLights){this._toggleDarkTheme(true);}
if(Object.keys(this.json.categories).length>=2){this._setupStickyHeaderElements();const containerEl=this._dom.find('.lh-container',this._document);const elToAddScrollListener=this._getScrollParent(containerEl);elToAddScrollListener.addEventListener('scroll',this._updateStickyHeaderOnScroll);if(this._dom.isDevTools()){const resizeObserver=new window.ResizeObserver(this._updateStickyHeaderOnScroll);resizeObserver.observe(containerEl);}else{window.addEventListener('resize',this._updateStickyHeaderOnScroll);}}
const hasMetricError=report.categories.performance&&report.categories.performance.auditRefs.some(audit=>Boolean(audit.group==='metrics'&&report.audits[audit.id].errorMessage));if(hasMetricError){const toggleInputEl=(this._dom.find('.lh-metrics-toggle__input',this._document));toggleInputEl.checked=true;}}
setTemplateContext(context){this._templateContext=context;}
_getScrollParent(element){const{overflowY}=window.getComputedStyle(element);const isScrollable=overflowY!=='visible'&&overflowY!=='hidden';if(isScrollable){return element;}
if(element.parentElement){return this._getScrollParent(element.parentElement);}
return document;}
_enableFireworks(){const scoresContainer=this._dom.find('.lh-scores-container',this._document);scoresContainer.classList.add('score100');scoresContainer.addEventListener('click',_=>{scoresContainer.classList.toggle('fireworks-paused');});}
_fireEventOn(name,target=this._document,detail){const event=new CustomEvent(name,detail?{detail}:undefined);target.dispatchEvent(event);}
_setupMediaQueryListeners(){const mediaQuery=self.matchMedia('(max-width: 500px)');mediaQuery.addListener(this.onMediaQueryChange);this.onMediaQueryChange(mediaQuery);}
onMediaQueryChange(mql){const root=this._dom.find('.lh-root',this._document);root.classList.toggle('lh-narrow',mql.matches);}
_setupExportButton(){this.exportButton=this._dom.find('.lh-export__button',this._document);this.exportButton.addEventListener('click',this.onExportButtonClick);const dropdown=this._dom.find('.lh-export__dropdown',this._document);dropdown.addEventListener('click',this.onExport);}
_setupThirdPartyFilter(){const thirdPartyFilterAuditExclusions=['uses-rel-preconnect',];const tables=Array.from(this._document.querySelectorAll('.lh-table'));const tablesWithUrls=tables.filter(el=>el.querySelector('td.lh-table-column--url')).filter(el=>{const containingAudit=el.closest('.lh-audit');if(!containingAudit)throw new Error('.lh-table not within audit');return!thirdPartyFilterAuditExclusions.includes(containingAudit.id);});tablesWithUrls.forEach((tableEl,index)=>{const urlItems=this._getUrlItems(tableEl);const thirdPartyRows=this._getThirdPartyRows(tableEl,urlItems,this.json.finalUrl);if(thirdPartyRows.size===urlItems.length||!thirdPartyRows.size)return;const filterTemplate=this._dom.cloneTemplate('#tmpl-lh-3p-filter',this._templateContext);const filterInput=this._dom.find('input',filterTemplate);const id=`lh-3p-filter-label--${index}`;filterInput.id=id;filterInput.addEventListener('change',e=>{if(e.target instanceof HTMLInputElement&&!e.target.checked){for(const row of thirdPartyRows.values()){row.remove();}}else{for(const[position,row]of thirdPartyRows.entries()){const childrenArr=getTableRows(tableEl);tableEl.tBodies[0].insertBefore(row,childrenArr[position]);}}});this._dom.find('label',filterTemplate).setAttribute('for',id);this._dom.find('.lh-3p-filter-count',filterTemplate).textContent=`${thirdPartyRows.size}`;this._dom.find('.lh-3p-ui-string',filterTemplate).textContent=Util.UIStrings.thirdPartyResourcesLabel;if(!tableEl.parentNode)return;tableEl.parentNode.insertBefore(filterTemplate,tableEl);});}
_getThirdPartyRows(el,urlItems,finalUrl){const finalUrlRootDomain=Util.getRootDomain(finalUrl);const thirdPartyRows=new Map();for(const urlItem of urlItems){const datasetUrl=urlItem.dataset.url;if(!datasetUrl)continue;const isThirdParty=Util.getRootDomain(datasetUrl)!==finalUrlRootDomain;if(!isThirdParty)continue;const urlRowEl=urlItem.closest('tr');if(urlRowEl){const rowPosition=getTableRows(el).indexOf(urlRowEl);thirdPartyRows.set(rowPosition,urlRowEl);}}
return thirdPartyRows;}
_getUrlItems(tableEl){return this._dom.findAll('.lh-text__url',tableEl);}
_setupStickyHeaderElements(){this.topbarEl=this._dom.find('.lh-topbar',this._document);this.scoreScaleEl=this._dom.find('.lh-scorescale',this._document);this.stickyHeaderEl=this._dom.find('.lh-sticky-header',this._document);const firstGauge=this._dom.find('.lh-gauge__wrapper',this.stickyHeaderEl);this.highlightEl=this._dom.createChildOf(firstGauge,'div','lh-highlighter');}
onCopy(e){if(this._copyAttempt){e.preventDefault();e.clipboardData.setData('text/plain',JSON.stringify(this.json,null,2));this._fireEventOn('lh-log',this._document,{cmd:'log',msg:'Report JSON copied to clipboard',});}
this._copyAttempt=false;}
onCopyButtonClick(){this._fireEventOn('lh-analytics',this._document,{cmd:'send',fields:{hitType:'event',eventCategory:'report',eventAction:'copy'},});try{if(this._document.queryCommandSupported('copy')){this._copyAttempt=true;if(!this._document.execCommand('copy')){this._copyAttempt=false;this._fireEventOn('lh-log',this._document,{cmd:'warn',msg:'Your browser does not support copy to clipboard.',});}}}catch(e){this._copyAttempt=false;this._fireEventOn('lh-log',this._document,{cmd:'log',msg:e.message});}}
onChevronClick(){const toggle=this._dom.find('.lh-config__settings-toggle',this._document);if(toggle.hasAttribute('open')){toggle.removeAttribute('open');}else{toggle.setAttribute('open','true');}}
closeExportDropdown(){this.exportButton.classList.remove('active');}
onExportButtonClick(e){e.preventDefault();this.exportButton.classList.toggle('active');this._document.addEventListener('keydown',this.onKeyDown);}
_resetUIState(){this.closeExportDropdown();this._dom.resetTemplates();}
onExport(e){e.preventDefault();const el=(e.target);if(!el||!el.hasAttribute('data-action')){return;}
switch(el.getAttribute('data-action')){case'copy':this.onCopyButtonClick();break;case'print-summary':this.collapseAllDetails();this.closeExportDropdown();self.print();break;case'print-expanded':this.expandAllDetails();this.closeExportDropdown();self.print();break;case'save-json':{const jsonStr=JSON.stringify(this.json,null,2);this._saveFile(new Blob([jsonStr],{type:'application/json'}));break;}
case'save-html':{const htmlStr=this.getReportHtml();try{this._saveFile(new Blob([htmlStr],{type:'text/html'}));}catch(e){this._fireEventOn('lh-log',this._document,{cmd:'error',msg:'Could not export as HTML. '+e.message,});}
break;}
case'open-viewer':{const viewerPath='/lighthouse/viewer/';ReportUIFeatures.openTabAndSendJsonReport(this.json,viewerPath);break;}
case'save-gist':{this.saveAsGist();break;}
case'toggle-dark':{this._toggleDarkTheme();break;}}
this.closeExportDropdown();this._document.removeEventListener('keydown',this.onKeyDown);}
onKeyDown(e){if(e.keyCode===27){this.closeExportDropdown();}}
onKeyUp(e){if((e.ctrlKey||e.metaKey)&&e.keyCode===80){this.closeExportDropdown();}}
static openTabAndSendJsonReport(reportJson,viewerPath){const VIEWER_ORIGIN='https://googlechrome.github.io';const json=reportJson;window.addEventListener('message',function msgHandler(messageEvent){if(messageEvent.origin!==VIEWER_ORIGIN){return;}
if(popup&&messageEvent.data.opened){popup.postMessage({lhresults:json},VIEWER_ORIGIN);window.removeEventListener('message',msgHandler);}});const fallbackFetchTime=(json.generatedTime);const fetchTime=json.fetchTime||fallbackFetchTime;const windowName=`${json.lighthouseVersion}-${json.requestedUrl}-${fetchTime}`;const popup=window.open(`${VIEWER_ORIGIN}${viewerPath}`,windowName);}
expandAllDetails(){const details=(this._dom.findAll('.lh-categories details',this._document));details.map(detail=>detail.open=true);}
collapseAllDetails(){const details=(this._dom.findAll('.lh-categories details',this._document));details.map(detail=>detail.open=false);}
_setUpCollapseDetailsAfterPrinting(){if('onbeforeprint'in self){self.addEventListener('afterprint',this.collapseAllDetails);}else{const win=(self);win.matchMedia('print').addListener(mql=>{if(mql.matches){this.expandAllDetails();}else{this.collapseAllDetails();}});}}
getReportHtml(){this._resetUIState();return this._document.documentElement.outerHTML;}
saveAsGist(){throw new Error('Cannot save as gist from base report');}
_saveFile(blob){const filename=getFilenamePrefix({finalUrl:this.json.finalUrl,fetchTime:this.json.fetchTime,});const ext=blob.type.match('json')?'.json':'.html';const href=URL.createObjectURL(blob);const a=this._dom.createElement('a');a.download=`${filename}${ext}`;a.href=href;this._document.body.appendChild(a);a.click();this._document.body.removeChild(a);setTimeout(_=>URL.revokeObjectURL(href),500);}
_toggleDarkTheme(force){const el=this._dom.find('.lh-vars',this._document);if(typeof force==='undefined'){el.classList.toggle('dark');}else{el.classList.toggle('dark',force);}}
_updateStickyHeaderOnScroll(){const topbarBottom=this.topbarEl.getBoundingClientRect().bottom;const scoreScaleTop=this.scoreScaleEl.getBoundingClientRect().top;const showStickyHeader=topbarBottom>=scoreScaleTop;const categoryEls=Array.from(this._document.querySelectorAll('.lh-category'));const categoriesAboveTheMiddle=categoryEls.filter(el=>el.getBoundingClientRect().top-window.innerHeight/2<0);const highlightIndex=categoriesAboveTheMiddle.length>0?categoriesAboveTheMiddle.length-1:0;const gaugeWrapperEls=this.stickyHeaderEl.querySelectorAll('.lh-gauge__wrapper');const gaugeToHighlight=gaugeWrapperEls[highlightIndex];const origin=gaugeWrapperEls[0].getBoundingClientRect().left;const offset=gaugeToHighlight.getBoundingClientRect().left-origin;this.highlightEl.style.transform=`translate(${offset}px)`;this.stickyHeaderEl.classList.toggle('lh-sticky-header--visible',showStickyHeader);}}
if(typeof module!=='undefined'&&module.exports){module.exports=ReportUIFeatures;}else{self.ReportUIFeatures=ReportUIFeatures;};'use strict';class CategoryRenderer{constructor(dom,detailsRenderer){this.dom=dom;this.detailsRenderer=detailsRenderer;this.templateContext=this.dom.document();this.detailsRenderer.setTemplateContext(this.templateContext);}
get _clumpTitles(){return{warning:Util.UIStrings.warningAuditsGroupTitle,manual:Util.UIStrings.manualAuditsGroupTitle,passed:Util.UIStrings.passedAuditsGroupTitle,notApplicable:Util.UIStrings.notApplicableAuditsGroupTitle,};}
renderAudit(audit){const tmpl=this.dom.cloneTemplate('#tmpl-lh-audit',this.templateContext);return this.populateAuditValues(audit,tmpl);}
populateAuditValues(audit,tmpl){const auditEl=this.dom.find('.lh-audit',tmpl);auditEl.id=audit.result.id;const scoreDisplayMode=audit.result.scoreDisplayMode;if(audit.result.displayValue){this.dom.find('.lh-audit__display-text',auditEl).textContent=audit.result.displayValue;}
const titleEl=this.dom.find('.lh-audit__title',auditEl);titleEl.appendChild(this.dom.convertMarkdownCodeSnippets(audit.result.title));this.dom.find('.lh-audit__description',auditEl).appendChild(this.dom.convertMarkdownLinkSnippets(audit.result.description));if(audit.stackPacks){audit.stackPacks.forEach(pack=>{const packElm=this.dom.createElement('div');packElm.classList.add('lh-audit__stackpack');const packElmImg=this.dom.createElement('img');packElmImg.classList.add('lh-audit__stackpack__img');packElmImg.src=pack.iconDataURL;packElmImg.alt=pack.title;packElm.appendChild(packElmImg);packElm.appendChild(this.dom.convertMarkdownLinkSnippets(pack.description));this.dom.find('.lh-audit__stackpacks',auditEl).appendChild(packElm);});}
const header=(this.dom.find('details',auditEl));if(audit.result.details){const elem=this.detailsRenderer.render(audit.result.details);if(elem){elem.classList.add('lh-details');header.appendChild(elem);}}
this.dom.find('.lh-chevron-container',auditEl).appendChild(this._createChevron());this._setRatingClass(auditEl,audit.result.score,scoreDisplayMode);if(audit.result.scoreDisplayMode==='error'){auditEl.classList.add(`lh-audit--error`);const textEl=this.dom.find('.lh-audit__display-text',auditEl);textEl.textContent=Util.UIStrings.errorLabel;textEl.classList.add('tooltip-boundary');const tooltip=this.dom.createChildOf(textEl,'div','tooltip tooltip--error');tooltip.textContent=audit.result.errorMessage||Util.UIStrings.errorMissingAuditInfo;}else if(audit.result.explanation){const explEl=this.dom.createChildOf(titleEl,'div','lh-audit-explanation');explEl.textContent=audit.result.explanation;}
const warnings=audit.result.warnings;if(!warnings||warnings.length===0)return auditEl;const warningsEl=this.dom.createChildOf(titleEl,'div','lh-warnings');this.dom.createChildOf(warningsEl,'span').textContent=Util.UIStrings.warningHeader;if(warnings.length===1){warningsEl.appendChild(this.dom.document().createTextNode(warnings.join('')));}else{const warningsUl=this.dom.createChildOf(warningsEl,'ul');for(const warning of warnings){const item=this.dom.createChildOf(warningsUl,'li');item.textContent=warning;}}
return auditEl;}
_createChevron(){const chevronTmpl=this.dom.cloneTemplate('#tmpl-lh-chevron',this.templateContext);const chevronEl=this.dom.find('.lh-chevron',chevronTmpl);return chevronEl;}
_setRatingClass(element,score,scoreDisplayMode){const rating=Util.calculateRating(score,scoreDisplayMode);element.classList.add(`lh-audit--${scoreDisplayMode.toLowerCase()}`);if(scoreDisplayMode!=='informative'){element.classList.add(`lh-audit--${rating}`);}
return element;}
renderCategoryHeader(category,groupDefinitions){const tmpl=this.dom.cloneTemplate('#tmpl-lh-category-header',this.templateContext);const gaugeContainerEl=this.dom.find('.lh-score__gauge',tmpl);const gaugeEl=this.renderScoreGauge(category,groupDefinitions);gaugeContainerEl.appendChild(gaugeEl);if(category.description){const descEl=this.dom.convertMarkdownLinkSnippets(category.description);this.dom.find('.lh-category-header__description',tmpl).appendChild(descEl);}
return(tmpl.firstElementChild);}
renderAuditGroup(group){const groupEl=this.dom.createElement('div','lh-audit-group');const auditGroupHeader=this.dom.createElement('div','lh-audit-group__header');this.dom.createChildOf(auditGroupHeader,'span','lh-audit-group__title').textContent=group.title;if(group.description){const descriptionEl=this.dom.convertMarkdownLinkSnippets(group.description);descriptionEl.classList.add('lh-audit-group__description');auditGroupHeader.appendChild(descriptionEl);}
groupEl.appendChild(auditGroupHeader);return groupEl;}
_renderGroupedAudits(auditRefs,groupDefinitions){const grouped=new Map();const notAGroup='NotAGroup';grouped.set(notAGroup,[]);for(const auditRef of auditRefs){const groupId=auditRef.group||notAGroup;const groupAuditRefs=grouped.get(groupId)||[];groupAuditRefs.push(auditRef);grouped.set(groupId,groupAuditRefs);}
const auditElements=[];for(const[groupId,groupAuditRefs]of grouped){if(groupId===notAGroup){for(const auditRef of groupAuditRefs){auditElements.push(this.renderAudit(auditRef));}
continue;}
const groupDef=groupDefinitions[groupId];const auditGroupElem=this.renderAuditGroup(groupDef);for(const auditRef of groupAuditRefs){auditGroupElem.appendChild(this.renderAudit(auditRef));}
auditGroupElem.classList.add(`lh-audit-group--${groupId}`);auditElements.push(auditGroupElem);}
return auditElements;}
renderUnexpandableClump(auditRefs,groupDefinitions){const clumpElement=this.dom.createElement('div');const elements=this._renderGroupedAudits(auditRefs,groupDefinitions);elements.forEach(elem=>clumpElement.appendChild(elem));return clumpElement;}
renderClump(clumpId,{auditRefs,description}){const clumpTmpl=this.dom.cloneTemplate('#tmpl-lh-clump',this.templateContext);const clumpElement=this.dom.find('.lh-clump',clumpTmpl);if(clumpId==='warning'){clumpElement.setAttribute('open','');}
const summaryInnerEl=this.dom.find('.lh-audit-group__summary',clumpElement);const chevronEl=summaryInnerEl.appendChild(this._createChevron());chevronEl.title=Util.UIStrings.auditGroupExpandTooltip;const headerEl=this.dom.find('.lh-audit-group__header',clumpElement);const title=this._clumpTitles[clumpId];this.dom.find('.lh-audit-group__title',headerEl).textContent=title;if(description){const descriptionEl=this.dom.convertMarkdownLinkSnippets(description);descriptionEl.classList.add('lh-audit-group__description');headerEl.appendChild(descriptionEl);}
const itemCountEl=this.dom.find('.lh-audit-group__itemcount',clumpElement);itemCountEl.textContent=`(${auditRefs.length})`;const auditElements=auditRefs.map(this.renderAudit.bind(this));clumpElement.append(...auditElements);clumpElement.classList.add(`lh-clump--${clumpId.toLowerCase()}`);return clumpElement;}
setTemplateContext(context){this.templateContext=context;this.detailsRenderer.setTemplateContext(context);}
renderScoreGauge(category,groupDefinitions){const tmpl=this.dom.cloneTemplate('#tmpl-lh-gauge',this.templateContext);const wrapper=(this.dom.find('.lh-gauge__wrapper',tmpl));wrapper.href=`#${category.id}`;wrapper.classList.add(`lh-gauge__wrapper--${Util.calculateRating(category.score)}`);if(Util.isPluginCategory(category.id)){wrapper.classList.add('lh-gauge__wrapper--plugin');}
const numericScore=Number(category.score);const gauge=this.dom.find('.lh-gauge',tmpl);const gaugeArc=gauge.querySelector('.lh-gauge-arc');if(gaugeArc){gaugeArc.style.strokeDasharray=`${numericScore * 352} 352`;}
const scoreOutOf100=Math.round(numericScore*100);const percentageEl=this.dom.find('.lh-gauge__percentage',tmpl);percentageEl.textContent=scoreOutOf100.toString();if(category.score===null){percentageEl.textContent='?';percentageEl.title=Util.UIStrings.errorLabel;}
this.dom.find('.lh-gauge__label',tmpl).textContent=category.title;return tmpl;}
_auditHasWarning(audit){return Boolean(audit.result.warnings&&audit.result.warnings.length);}
_getClumpIdForAuditRef(auditRef){const scoreDisplayMode=auditRef.result.scoreDisplayMode;if(scoreDisplayMode==='manual'||scoreDisplayMode==='notApplicable'){return scoreDisplayMode;}
if(Util.showAsPassed(auditRef.result)){if(this._auditHasWarning(auditRef)){return'warning';}else{return'passed';}}else{return'failed';}}
render(category,groupDefinitions={}){const element=this.dom.createElement('div','lh-category');this.createPermalinkSpan(element,category.id);element.appendChild(this.renderCategoryHeader(category,groupDefinitions));const clumps=new Map();clumps.set('failed',[]);clumps.set('warning',[]);clumps.set('manual',[]);clumps.set('passed',[]);clumps.set('notApplicable',[]);for(const auditRef of category.auditRefs){const clumpId=this._getClumpIdForAuditRef(auditRef);const clump=(clumps.get(clumpId));clump.push(auditRef);clumps.set(clumpId,clump);}
for(const[clumpId,auditRefs]of clumps){if(auditRefs.length===0)continue;if(clumpId==='failed'){const clumpElem=this.renderUnexpandableClump(auditRefs,groupDefinitions);clumpElem.classList.add(`lh-clump--failed`);element.appendChild(clumpElem);continue;}
const description=clumpId==='manual'?category.manualDescription:undefined;const clumpElem=this.renderClump(clumpId,{auditRefs,description});element.appendChild(clumpElem);}
return element;}
createPermalinkSpan(element,id){const permalinkEl=this.dom.createChildOf(element,'span','lh-permalink');permalinkEl.id=id;}}
if(typeof module!=='undefined'&&module.exports){module.exports=CategoryRenderer;}else{self.CategoryRenderer=CategoryRenderer;};'use strict';class PerformanceCategoryRenderer extends CategoryRenderer{_renderMetric(audit){const tmpl=this.dom.cloneTemplate('#tmpl-lh-metric',this.templateContext);const element=this.dom.find('.lh-metric',tmpl);element.id=audit.result.id;const rating=Util.calculateRating(audit.result.score,audit.result.scoreDisplayMode);element.classList.add(`lh-metric--${rating}`);const titleEl=this.dom.find('.lh-metric__title',tmpl);titleEl.textContent=audit.result.title;const valueEl=this.dom.find('.lh-metric__value',tmpl);valueEl.textContent=audit.result.displayValue||'';const descriptionEl=this.dom.find('.lh-metric__description',tmpl);descriptionEl.appendChild(this.dom.convertMarkdownLinkSnippets(audit.result.description));if(audit.result.scoreDisplayMode==='error'){descriptionEl.textContent='';valueEl.textContent='Error!';const tooltip=this.dom.createChildOf(descriptionEl,'span');tooltip.textContent=audit.result.errorMessage||'Report error: no metric information';}
return element;}
_renderOpportunity(audit,scale){const oppTmpl=this.dom.cloneTemplate('#tmpl-lh-opportunity',this.templateContext);const element=this.populateAuditValues(audit,oppTmpl);element.id=audit.result.id;if(!audit.result.details||audit.result.scoreDisplayMode==='error'){return element;}
const details=audit.result.details;if(details.type!=='opportunity'){return element;}
const displayEl=this.dom.find('.lh-audit__display-text',element);const sparklineWidthPct=`${details.overallSavingsMs / scale * 100}%`;this.dom.find('.lh-sparkline__bar',element).style.width=sparklineWidthPct;displayEl.textContent=Util.formatSeconds(details.overallSavingsMs,0.01);if(audit.result.displayValue){const displayValue=audit.result.displayValue;this.dom.find('.lh-load-opportunity__sparkline',element).title=displayValue;displayEl.title=displayValue;}
return element;}
_getWastedMs(audit){if(audit.result.details&&audit.result.details.type==='opportunity'){const details=audit.result.details;if(typeof details.overallSavingsMs!=='number'){throw new Error('non-opportunity details passed to _getWastedMs');}
return details.overallSavingsMs;}else{return Number.MIN_VALUE;}}
render(category,groups,environment){const element=this.dom.createElement('div','lh-category');if(environment==='PSI'){const gaugeEl=this.dom.createElement('div','lh-score__gauge');gaugeEl.appendChild(this.renderScoreGauge(category,groups));element.appendChild(gaugeEl);}else{this.createPermalinkSpan(element,category.id);element.appendChild(this.renderCategoryHeader(category,groups));}
const metricAudits=category.auditRefs.filter(audit=>audit.group==='metrics');const metricAuditsEl=this.renderAuditGroup(groups.metrics);const toggleTmpl=this.dom.cloneTemplate('#tmpl-lh-metrics-toggle',this.templateContext);const toggleEl=this.dom.find('.lh-metrics-toggle',toggleTmpl);metricAuditsEl.prepend(...toggleEl.childNodes);const keyMetrics=metricAudits.filter(a=>a.weight>=3);const otherMetrics=metricAudits.filter(a=>a.weight<3);const metricsBoxesEl=this.dom.createChildOf(metricAuditsEl,'div','lh-columns');const metricsColumn1El=this.dom.createChildOf(metricsBoxesEl,'div','lh-column');const metricsColumn2El=this.dom.createChildOf(metricsBoxesEl,'div','lh-column');keyMetrics.forEach(item=>{metricsColumn1El.appendChild(this._renderMetric(item));});otherMetrics.forEach(item=>{metricsColumn2El.appendChild(this._renderMetric(item));});if(environment!=='PSI'){const estValuesEl=this.dom.createChildOf(metricAuditsEl,'div','lh-metrics__disclaimer');estValuesEl.textContent=Util.UIStrings.varianceDisclaimer;}
metricAuditsEl.classList.add('lh-audit-group--metrics');element.appendChild(metricAuditsEl);const timelineEl=this.dom.createChildOf(element,'div','lh-filmstrip-container');const thumbnailAudit=category.auditRefs.find(audit=>audit.id==='screenshot-thumbnails');const thumbnailResult=thumbnailAudit&&thumbnailAudit.result;if(thumbnailResult&&thumbnailResult.details){timelineEl.id=thumbnailResult.id;const filmstripEl=this.detailsRenderer.render(thumbnailResult.details);filmstripEl&&timelineEl.appendChild(filmstripEl);}
const budgetAudit=category.auditRefs.find(audit=>audit.id==='performance-budget');if(budgetAudit&&budgetAudit.result.details){const table=this.detailsRenderer.render(budgetAudit.result.details);if(table){table.id=budgetAudit.id;table.classList.add('lh-audit');const budgetsGroupEl=this.renderAuditGroup(groups.budgets);budgetsGroupEl.appendChild(table);budgetsGroupEl.classList.add('lh-audit-group--budgets');element.appendChild(budgetsGroupEl);}}
const opportunityAudits=category.auditRefs.filter(audit=>audit.group==='load-opportunities'&&!Util.showAsPassed(audit.result)).sort((auditA,auditB)=>this._getWastedMs(auditB)-this._getWastedMs(auditA));if(opportunityAudits.length){const minimumScale=2000;const wastedMsValues=opportunityAudits.map(audit=>this._getWastedMs(audit));const maxWaste=Math.max(...wastedMsValues);const scale=Math.max(Math.ceil(maxWaste/1000)*1000,minimumScale);const groupEl=this.renderAuditGroup(groups['load-opportunities']);const tmpl=this.dom.cloneTemplate('#tmpl-lh-opportunity-header',this.templateContext);this.dom.find('.lh-load-opportunity__col--one',tmpl).textContent=Util.UIStrings.opportunityResourceColumnLabel;this.dom.find('.lh-load-opportunity__col--two',tmpl).textContent=Util.UIStrings.opportunitySavingsColumnLabel;const headerEl=this.dom.find('.lh-load-opportunity__header',tmpl);groupEl.appendChild(headerEl);opportunityAudits.forEach(item=>groupEl.appendChild(this._renderOpportunity(item,scale)));groupEl.classList.add('lh-audit-group--load-opportunities');element.appendChild(groupEl);}
const diagnosticAudits=category.auditRefs.filter(audit=>audit.group==='diagnostics'&&!Util.showAsPassed(audit.result)).sort((a,b)=>{const scoreA=a.result.scoreDisplayMode==='informative'?100:Number(a.result.score);const scoreB=b.result.scoreDisplayMode==='informative'?100:Number(b.result.score);return scoreA-scoreB;});if(diagnosticAudits.length){const groupEl=this.renderAuditGroup(groups['diagnostics']);diagnosticAudits.forEach(item=>groupEl.appendChild(this.renderAudit(item)));groupEl.classList.add('lh-audit-group--diagnostics');element.appendChild(groupEl);}
const passedAudits=category.auditRefs.filter(audit=>(audit.group==='load-opportunities'||audit.group==='diagnostics')&&Util.showAsPassed(audit.result));if(!passedAudits.length)return element;const clumpOpts={auditRefs:passedAudits,groupDefinitions:groups,};const passedElem=this.renderClump('passed',clumpOpts);element.appendChild(passedElem);return element;}}
if(typeof module!=='undefined'&&module.exports){module.exports=PerformanceCategoryRenderer;}else{self.PerformanceCategoryRenderer=PerformanceCategoryRenderer;};'use strict';class PwaCategoryRenderer extends CategoryRenderer{render(category,groupDefinitions={}){const categoryElem=this.dom.createElement('div','lh-category');this.createPermalinkSpan(categoryElem,category.id);categoryElem.appendChild(this.renderCategoryHeader(category,groupDefinitions));const auditRefs=category.auditRefs;const regularAuditRefs=auditRefs.filter(ref=>ref.result.scoreDisplayMode!=='manual');const auditsElem=this._renderAudits(regularAuditRefs,groupDefinitions);categoryElem.appendChild(auditsElem);const manualAuditRefs=auditRefs.filter(ref=>ref.result.scoreDisplayMode==='manual');const manualElem=this.renderClump('manual',{auditRefs:manualAuditRefs,description:category.manualDescription});categoryElem.appendChild(manualElem);return categoryElem;}
renderScoreGauge(category,groupDefinitions){if(category.score===null){return super.renderScoreGauge(category,groupDefinitions);}
const tmpl=this.dom.cloneTemplate('#tmpl-lh-gauge--pwa',this.templateContext);const wrapper=(this.dom.find('.lh-gauge--pwa__wrapper',tmpl));wrapper.href=`#${category.id}`;const allGroups=this._getGroupIds(category.auditRefs);const passingGroupIds=this._getPassingGroupIds(category.auditRefs);if(passingGroupIds.size===allGroups.size){wrapper.classList.add('lh-badged--all');}else{for(const passingGroupId of passingGroupIds){wrapper.classList.add(`lh-badged--${passingGroupId}`);}}
this.dom.find('.lh-gauge__label',tmpl).textContent=category.title;wrapper.title=this._getGaugeTooltip(category.auditRefs,groupDefinitions);return tmpl;}
_getGroupIds(auditRefs){const groupIds=auditRefs.map(ref=>ref.group).filter(g=>!!g);return new Set(groupIds);}
_getPassingGroupIds(auditRefs){const uniqueGroupIds=this._getGroupIds(auditRefs);for(const auditRef of auditRefs){if(!Util.showAsPassed(auditRef.result)&&auditRef.group){uniqueGroupIds.delete(auditRef.group);}}
return uniqueGroupIds;}
_getGaugeTooltip(auditRefs,groupDefinitions){const groupIds=this._getGroupIds(auditRefs);const tips=[];for(const groupId of groupIds){const groupAuditRefs=auditRefs.filter(ref=>ref.group===groupId);const auditCount=groupAuditRefs.length;const passedCount=groupAuditRefs.filter(ref=>Util.showAsPassed(ref.result)).length;const title=groupDefinitions[groupId].title;tips.push(`${title}: ${passedCount}/${auditCount}`);}
return tips.join(', ');}
_renderAudits(auditRefs,groupDefinitions){const auditsElem=this.renderUnexpandableClump(auditRefs,groupDefinitions);const passsingGroupIds=this._getPassingGroupIds(auditRefs);for(const groupId of passsingGroupIds){const groupElem=this.dom.find(`.lh-audit-group--${groupId}`,auditsElem);groupElem.classList.add('lh-badged');}
return auditsElem;}}
if(typeof module!=='undefined'&&module.exports){module.exports=PwaCategoryRenderer;}else{self.PwaCategoryRenderer=PwaCategoryRenderer;};'use strict';class ReportRenderer{constructor(dom){this._dom=dom;this._templateContext=this._dom.document();}
renderReport(result,container){const originalUIStrings=JSON.parse(JSON.stringify(Util.UIStrings));this._dom.setLighthouseChannel(result.configSettings.channel||'unknown');const report=Util.prepareReportResult(result);container.textContent='';container.appendChild(this._renderReport(report));Util.updateAllUIStrings(originalUIStrings);return container;}
setTemplateContext(context){this._templateContext=context;}
_renderReportTopbar(report){const el=this._dom.cloneTemplate('#tmpl-lh-topbar',this._templateContext);const metadataUrl=(this._dom.find('.lh-topbar__url',el));metadataUrl.href=metadataUrl.textContent=report.finalUrl;return el;}
_renderReportHeader(){const el=this._dom.cloneTemplate('#tmpl-lh-heading',this._templateContext);const domFragment=this._dom.cloneTemplate('#tmpl-lh-scores-wrapper',this._templateContext);const placeholder=this._dom.find('.lh-scores-wrapper-placeholder',el);(placeholder.parentNode).replaceChild(domFragment,placeholder);return el;}
_renderReportFooter(report){const footer=this._dom.cloneTemplate('#tmpl-lh-footer',this._templateContext);const env=this._dom.find('.lh-env__items',footer);env.id='runtime-settings';const envValues=Util.getEnvironmentDisplayValues(report.configSettings||{});[{name:'URL',description:report.finalUrl},{name:'Fetch time',description:Util.formatDateTime(report.fetchTime)},...envValues,{name:'User agent (host)',description:report.userAgent},{name:'User agent (network)',description:report.environment&&report.environment.networkUserAgent},{name:'CPU/Memory Power',description:report.environment&&report.environment.benchmarkIndex.toFixed(0)},].forEach(runtime=>{if(!runtime.description)return;const item=this._dom.cloneTemplate('#tmpl-lh-env__items',env);this._dom.find('.lh-env__name',item).textContent=runtime.name;this._dom.find('.lh-env__description',item).textContent=runtime.description;env.appendChild(item);});this._dom.find('.lh-footer__version',footer).textContent=report.lighthouseVersion;return footer;}
_renderReportWarnings(report){if(!report.runWarnings||report.runWarnings.length===0){return this._dom.createElement('div');}
const container=this._dom.cloneTemplate('#tmpl-lh-warnings--toplevel',this._templateContext);const message=this._dom.find('.lh-warnings__msg',container);message.textContent=Util.UIStrings.toplevelWarningsMessage;const warnings=this._dom.find('ul',container);for(const warningString of report.runWarnings){const warning=warnings.appendChild(this._dom.createElement('li'));warning.textContent=warningString;}
return container;}
_renderScoreGauges(report,categoryRenderer,specificCategoryRenderers){const defaultGauges=[];const customGauges=[];const pluginGauges=[];for(const category of Object.values(report.categories)){const renderer=specificCategoryRenderers[category.id]||categoryRenderer;const categoryGauge=renderer.renderScoreGauge(category,report.categoryGroups||{});if(Util.isPluginCategory(category.id)){pluginGauges.push(categoryGauge);}else if(renderer.renderScoreGauge===categoryRenderer.renderScoreGauge){defaultGauges.push(categoryGauge);}else{customGauges.push(categoryGauge);}}
return[...defaultGauges,...customGauges,...pluginGauges];}
_renderReport(report){const detailsRenderer=new DetailsRenderer(this._dom);const categoryRenderer=new CategoryRenderer(this._dom,detailsRenderer);categoryRenderer.setTemplateContext(this._templateContext);const specificCategoryRenderers={performance:new PerformanceCategoryRenderer(this._dom,detailsRenderer),pwa:new PwaCategoryRenderer(this._dom,detailsRenderer),};Object.values(specificCategoryRenderers).forEach(renderer=>{renderer.setTemplateContext(this._templateContext);});const headerContainer=this._dom.createElement('div');headerContainer.appendChild(this._renderReportHeader());const container=this._dom.createElement('div','lh-container');const reportSection=this._dom.createElement('div','lh-report');reportSection.appendChild(this._renderReportWarnings(report));let scoreHeader;const isSoloCategory=Object.keys(report.categories).length===1;if(!isSoloCategory){scoreHeader=this._dom.createElement('div','lh-scores-header');}else{headerContainer.classList.add('lh-header--solo-category');}
if(scoreHeader){const scoreScale=this._dom.cloneTemplate('#tmpl-lh-scorescale',this._templateContext);const scoresContainer=this._dom.find('.lh-scores-container',headerContainer);scoreHeader.append(...this._renderScoreGauges(report,categoryRenderer,specificCategoryRenderers));scoresContainer.appendChild(scoreHeader);scoresContainer.appendChild(scoreScale);const stickyHeader=this._dom.createElement('div','lh-sticky-header');stickyHeader.append(...this._renderScoreGauges(report,categoryRenderer,specificCategoryRenderers));container.appendChild(stickyHeader);}
const categories=reportSection.appendChild(this._dom.createElement('div','lh-categories'));for(const category of Object.values(report.categories)){const renderer=specificCategoryRenderers[category.id]||categoryRenderer;const wrapper=renderer.dom.createChildOf(categories,'div','lh-category-wrapper');wrapper.appendChild(renderer.render(category,report.categoryGroups));}
const reportFragment=this._dom.createFragment();const topbarDocumentFragment=this._renderReportTopbar(report);reportFragment.appendChild(topbarDocumentFragment);reportFragment.appendChild(container);container.appendChild(headerContainer);container.appendChild(reportSection);reportSection.appendChild(this._renderReportFooter(report));return reportFragment;}}
ReportRenderer._UIStringsStash={};if(typeof module!=='undefined'&&module.exports){module.exports=ReportRenderer;}else{self.ReportRenderer=ReportRenderer;};Audits2.RadioSetting=class{constructor(options,setting){this._setting=setting;this._options=options;this.element=createElement('div','audits2-radio-group');this._radioElements=[];for(const option of this._options){const fragment=UI.Fragment.build`
<label $="label" class="audits2-radio">
<input $="input" type="radio" value=${option.value} name=${setting.name}>
${option.label}
</label>
`;this.element.appendChild(fragment.element());if(option.title)
UI.Tooltip.install(fragment.$('label'),option.title);const radioElement=fragment.$('input');radioElement.addEventListener('change',this._valueChanged.bind(this));this._radioElements.push(radioElement);}
this._ignoreChangeEvents=false;this._selectedIndex=-1;setting.addChangeListener(this._settingChanged,this);this._settingChanged();}
_updateUI(){this._ignoreChangeEvents=true;this._radioElements[this._selectedIndex].checked=true;this._ignoreChangeEvents=false;}
_settingChanged(){const value=this._setting.get();this._selectedIndex=this._options.findIndex(option=>option.value===value);this._updateUI();}
_valueChanged(event){if(this._ignoreChangeEvents)
return;const selectedRadio=this._radioElements.find(radio=>radio.checked);this._setting.set(selectedRadio.value);}};;Audits2.Audits2Panel=class extends UI.Panel{constructor(){super('audits2');this.registerRequiredCSS('audits2/lighthouse/report.css');this.registerRequiredCSS('audits2/audits2Panel.css');this._protocolService=new Audits2.ProtocolService();this._controller=new Audits2.AuditController(this._protocolService);this._startView=new Audits2.StartView(this._controller);this._statusView=new Audits2.StatusView(this._controller);this._unauditableExplanation=null;this._cachedRenderedReports=new Map();this._dropTarget=new UI.DropTarget(this.contentElement,[UI.DropTarget.Type.File],Common.UIString('Drop audit file here'),this._handleDrop.bind(this));this._controller.addEventListener(Audits2.Events.PageAuditabilityChanged,this._refreshStartAuditUI.bind(this));this._controller.addEventListener(Audits2.Events.AuditProgressChanged,this._refreshStatusUI.bind(this));this._controller.addEventListener(Audits2.Events.RequestAuditStart,this._startAudit.bind(this));this._controller.addEventListener(Audits2.Events.RequestAuditCancel,this._cancelAudit.bind(this));this._renderToolbar();this._auditResultsElement=this.contentElement.createChild('div','audits2-results-container');this._renderStartView();this._controller.recomputePageAuditability();}
_refreshStartAuditUI(evt){this._unauditableExplanation=evt.data.helpText;this._startView.setUnauditableExplanation(evt.data.helpText);this._startView.setStartButtonEnabled(!evt.data.helpText);}
_refreshStatusUI(evt){this._statusView.updateStatus(evt.data.message);}
_refreshToolbarUI(){this._downloadButton.setEnabled(this._reportSelector.hasCurrentSelection());this._clearButton.setEnabled(this._reportSelector.hasItems());}
_clearAll(){this._reportSelector.clearAll();this._renderStartView();this._refreshToolbarUI();}
_downloadSelected(){this._reportSelector.downloadSelected();}
_renderToolbar(){const toolbar=new UI.Toolbar('',this.element);this._newButton=new UI.ToolbarButton(Common.UIString('Perform an audit\u2026'),'largeicon-add');toolbar.appendToolbarItem(this._newButton);this._newButton.addEventListener(UI.ToolbarButton.Events.Click,this._renderStartView.bind(this));this._downloadButton=new UI.ToolbarButton(Common.UIString('Download report'),'largeicon-download');toolbar.appendToolbarItem(this._downloadButton);this._downloadButton.addEventListener(UI.ToolbarButton.Events.Click,this._downloadSelected.bind(this));toolbar.appendSeparator();this._reportSelector=new Audits2.ReportSelector(()=>this._renderStartView());toolbar.appendToolbarItem(this._reportSelector.comboBox());this._clearButton=new UI.ToolbarButton(Common.UIString('Clear all'),'largeicon-clear');toolbar.appendToolbarItem(this._clearButton);this._clearButton.addEventListener(UI.ToolbarButton.Events.Click,this._clearAll.bind(this));this._refreshToolbarUI();}
_renderStartView(){this._auditResultsElement.removeChildren();this._statusView.hide();this._reportSelector.selectNewAudit();this.contentElement.classList.toggle('in-progress',false);this._startView.show(this.contentElement);this._startView.setUnauditableExplanation(this._unauditableExplanation);this._startView.setStartButtonEnabled(!this._unauditableExplanation);if(!this._unauditableExplanation)
this._startView.focusStartButton();this._newButton.setEnabled(false);this._refreshToolbarUI();this.setDefaultFocusedChild(this._startView);}
_renderStatusView(inspectedURL){this.contentElement.classList.toggle('in-progress',true);this._statusView.setInspectedURL(inspectedURL);this._statusView.show(this.contentElement);}
_renderReport(lighthouseResult,artifacts){this.contentElement.classList.toggle('in-progress',false);this._startView.hideWidget();this._statusView.hide();this._auditResultsElement.removeChildren();this._newButton.setEnabled(true);this._refreshToolbarUI();const cachedRenderedReport=this._cachedRenderedReports.get(lighthouseResult);if(cachedRenderedReport){this._auditResultsElement.appendChild(cachedRenderedReport);return;}
const reportContainer=this._auditResultsElement.createChild('div','lh-vars lh-root lh-devtools');const dom=new DOM((this._auditResultsElement.ownerDocument));const renderer=new Audits2.ReportRenderer(dom);const templatesHTML=Runtime.cachedResources['audits2/lighthouse/templates.html'];const templatesDOM=new DOMParser().parseFromString(templatesHTML,'text/html');if(!templatesDOM)
return;renderer.setTemplateContext(templatesDOM);const el=renderer.renderReport(lighthouseResult,reportContainer);Audits2.ReportRenderer.addViewTraceButton(el,artifacts);Audits2.ReportRenderer.linkifyNodeDetails(el);Audits2.ReportRenderer.handleDarkMode(el);const features=new ReportUIFeatures(dom);features.setTemplateContext(templatesDOM);features.initFeatures(lighthouseResult);this._cachedRenderedReports.set(lighthouseResult,reportContainer);}
_buildReportUI(lighthouseResult,artifacts){if(lighthouseResult===null)
return;const optionElement=new Audits2.ReportSelector.Item(lighthouseResult,()=>this._renderReport(lighthouseResult,artifacts),this._renderStartView.bind(this));this._reportSelector.prepend(optionElement);this._refreshToolbarUI();this._renderReport(lighthouseResult);}
_handleDrop(dataTransfer){const items=dataTransfer.items;if(!items.length)
return;const item=items[0];if(item.kind==='file'){const entry=items[0].webkitGetAsEntry();if(!entry.isFile)
return;entry.file(file=>{const reader=new FileReader();reader.onload=()=>this._loadedFromFile((reader.result));reader.readAsText(file);});}}
_loadedFromFile(report){const data=JSON.parse(report);if(!data['lighthouseVersion'])
return;this._buildReportUI((data));}
async _startAudit(){Host.userMetrics.actionTaken(Host.UserMetrics.Action.Audits2Started);try{const inspectedURL=await this._controller.getInspectedURL({force:true});const categoryIDs=this._controller.getCategoryIDs();const flags=this._controller.getFlags();await this._setupEmulationAndProtocolConnection();this._renderStatusView(inspectedURL);const lighthouseResponse=await this._protocolService.startLighthouse(inspectedURL,categoryIDs,flags);if(lighthouseResponse&&lighthouseResponse.fatal){const error=new Error(lighthouseResponse.message);error.stack=lighthouseResponse.stack;throw error;}
if(!lighthouseResponse)
throw new Error('Auditing failed to produce a result');Host.userMetrics.actionTaken(Host.UserMetrics.Action.Audits2Finished);await this._resetEmulationAndProtocolConnection();this._buildReportUI(lighthouseResponse.lhr,lighthouseResponse.artifacts);}catch(err){await this._resetEmulationAndProtocolConnection();if(err instanceof Error)
this._statusView.renderBugReport(err);}}
async _cancelAudit(){this._statusView.updateStatus(ls`Cancelling`);await this._resetEmulationAndProtocolConnection();this._renderStartView();}
async _setupEmulationAndProtocolConnection(){const flags=this._controller.getFlags();const emulationModel=self.singleton(Emulation.DeviceModeModel);this._emulationEnabledBefore=emulationModel.enabledSetting().get();this._emulationOutlineEnabledBefore=emulationModel.deviceOutlineSetting().get();emulationModel.toolbarControlsEnabledSetting().set(false);if(flags._devtoolsEmulationType==='desktop'){emulationModel.enabledSetting().set(false);emulationModel.emulate(Emulation.DeviceModeModel.Type.None,null,null);}else if(flags._devtoolsEmulationType==='mobile'){emulationModel.enabledSetting().set(true);emulationModel.deviceOutlineSetting().set(true);for(const device of Emulation.EmulatedDevicesList.instance().standard()){if(device.title==='Nexus 5X')
emulationModel.emulate(Emulation.DeviceModeModel.Type.Device,device,device.modes[0],1);}}
await this._protocolService.attach();this._isLHAttached=true;}
async _resetEmulationAndProtocolConnection(){if(!this._isLHAttached)
return;this._isLHAttached=false;await this._protocolService.detach();const emulationModel=self.singleton(Emulation.DeviceModeModel);emulationModel.enabledSetting().set(this._emulationEnabledBefore);emulationModel.deviceOutlineSetting().set(this._emulationOutlineEnabledBefore);emulationModel.toolbarControlsEnabledSetting().set(true);Emulation.InspectedPagePlaceholder.instance().update(true);const resourceTreeModel=SDK.targetManager.mainTarget().model(SDK.ResourceTreeModel);const inspectedURL=await this._controller.getInspectedURL();await resourceTreeModel.navigate(inspectedURL);}};;Audits2.AuditController=class extends Common.Object{constructor(protocolService){super();protocolService.registerStatusCallback(message=>this.dispatchEventToListeners(Audits2.Events.AuditProgressChanged,{message}));for(const preset of Audits2.Presets)
preset.setting.addChangeListener(this.recomputePageAuditability.bind(this));SDK.targetManager.observeModels(SDK.ServiceWorkerManager,this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this.recomputePageAuditability,this);}
modelAdded(serviceWorkerManager){if(this._manager)
return;this._manager=serviceWorkerManager;this._serviceWorkerListeners=[this._manager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationUpdated,this.recomputePageAuditability,this),this._manager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationDeleted,this.recomputePageAuditability,this),];this.recomputePageAuditability();}
modelRemoved(serviceWorkerManager){if(this._manager!==serviceWorkerManager)
return;Common.EventTarget.removeEventListeners(this._serviceWorkerListeners);this._manager=null;this.recomputePageAuditability();}
_hasActiveServiceWorker(){if(!this._manager)
return false;const mainTarget=this._manager.target();if(!mainTarget)
return false;const inspectedURL=mainTarget.inspectedURL().asParsedURL();const inspectedOrigin=inspectedURL&&inspectedURL.securityOrigin();for(const registration of this._manager.registrations().values()){if(registration.securityOrigin!==inspectedOrigin)
continue;for(const version of registration.versions.values()){if(version.controlledClients.length>1)
return true;}}
return false;}
_hasAtLeastOneCategory(){return Audits2.Presets.some(preset=>preset.setting.get());}
_unauditablePageMessage(){if(!this._manager)
return null;const mainTarget=this._manager.target();const inspectedURL=mainTarget&&mainTarget.inspectedURL();if(inspectedURL&&!/^(http|chrome-extension)/.test(inspectedURL)){return Common.UIString('Can only audit HTTP/HTTPS pages and Chrome extensions. Navigate to a different page to start an audit.');}
return null;}
async _evaluateInspectedURL(){const mainTarget=this._manager.target();const runtimeModel=mainTarget.model(SDK.RuntimeModel);const executionContext=runtimeModel&&runtimeModel.defaultExecutionContext();let inspectedURL=mainTarget.inspectedURL();if(!executionContext)
return inspectedURL;try{const result=await executionContext.evaluate({expression:'window.location.href',objectGroup:'audits',includeCommandLineAPI:false,silent:false,returnByValue:true,generatePreview:false},false,false);if(!result.exceptionDetails&&result.object){inspectedURL=result.object.value;result.object.release();}}catch(err){console.error(err);}
return inspectedURL;}
getFlags(){const flags={};for(const runtimeSetting of Audits2.RuntimeSettings)
runtimeSetting.setFlags(flags,runtimeSetting.setting.get());return flags;}
getCategoryIDs(){const categoryIDs=[];for(const preset of Audits2.Presets){if(preset.setting.get())
categoryIDs.push(preset.configID);}
return categoryIDs;}
async getInspectedURL(options){if(options&&options.force||!this._inspectedURL)
this._inspectedURL=await this._evaluateInspectedURL();return this._inspectedURL;}
recomputePageAuditability(){const hasActiveServiceWorker=this._hasActiveServiceWorker();const hasAtLeastOneCategory=this._hasAtLeastOneCategory();const unauditablePageMessage=this._unauditablePageMessage();let helpText='';if(hasActiveServiceWorker){helpText=Common.UIString('Multiple tabs are being controlled by the same service worker. Close your other tabs on the same origin to audit this page.');}else if(!hasAtLeastOneCategory){helpText=Common.UIString('At least one category must be selected.');}else if(unauditablePageMessage){helpText=unauditablePageMessage;}
this.dispatchEventToListeners(Audits2.Events.PageAuditabilityChanged,{helpText});}};Audits2.Preset;Audits2.Presets=[{setting:Common.settings.createSetting('audits2.cat_perf',true),configID:'performance',title:ls`Performance`,description:ls`How long does this app take to show content and become usable`},{setting:Common.settings.createSetting('audits2.cat_pwa',true),configID:'pwa',title:ls`Progressive Web App`,description:ls`Does this page meet the standard of a Progressive Web App`},{setting:Common.settings.createSetting('audits2.cat_best_practices',true),configID:'best-practices',title:ls`Best practices`,description:ls`Does this page follow best practices for modern web development`},{setting:Common.settings.createSetting('audits2.cat_a11y',true),configID:'accessibility',title:ls`Accessibility`,description:ls`Is this page usable by people with disabilities or impairments`},{setting:Common.settings.createSetting('audits2.cat_seo',true),configID:'seo',title:ls`SEO`,description:ls`Is this page optimized for search engine results ranking`},];Audits2.RuntimeSetting;Audits2.RuntimeSettings=[{setting:Common.settings.createSetting('audits2.device_type','mobile'),description:ls`Apply mobile emulation during auditing`,setFlags:(flags,value)=>{flags._devtoolsEmulationType=value;flags.emulatedFormFactor='none';},options:[{label:ls`Mobile`,value:'mobile'},{label:ls`Desktop`,value:'desktop'},],},{setting:Common.settings.createSetting('audits2.throttling','default'),setFlags:(flags,value)=>{switch(value){case'devtools':flags.throttlingMethod='devtools';break;case'off':flags.throttlingMethod='provided';break;default:flags.throttlingMethod='simulate';}},options:[{label:ls`Simulated Slow 4G, 4x CPU Slowdown`,value:'default',title:ls`Throttling is simulated, resulting in faster audit runs with similar measurement accuracy`},{label:ls`Applied Slow 4G, 4x CPU Slowdown`,value:'devtools',title:ls`Typical DevTools throttling, with actual traffic shaping and CPU slowdown applied`},{label:ls`No throttling`,value:'off',title:ls`No network or CPU throttling used. (Useful when not evaluating performance)`},],},{setting:Common.settings.createSetting('audits2.clear_storage',true),title:ls`Clear storage`,description:ls`Reset storage (localStorage, IndexedDB, etc) before auditing. (Good for performance & PWA testing)`,setFlags:(flags,value)=>{flags.disableStorageReset=!value;},},];Audits2.Events={PageAuditabilityChanged:Symbol('PageAuditabilityChanged'),AuditProgressChanged:Symbol('AuditProgressChanged'),RequestAuditStart:Symbol('RequestAuditStart'),RequestAuditCancel:Symbol('RequestAuditCancel'),};;Audits2.ReportSelector=class{constructor(renderNewAuditView){this._renderNewAuditView=renderNewAuditView;this._newAuditItem=createElement('option');this._comboBox=new UI.ToolbarComboBox(this._handleChange.bind(this),'audits2-report');this._comboBox.setTitle(ls`Reports`);this._comboBox.setMaxWidth(180);this._comboBox.setMinWidth(140);this._itemByOptionElement=new Map();this._setEmptyState();}
_setEmptyState(){this._comboBox.selectElement().removeChildren();this._comboBox.setEnabled(false);this._newAuditItem=createElement('option');this._newAuditItem.label=Common.UIString('(new audit)');this._comboBox.selectElement().appendChild(this._newAuditItem);this._comboBox.select(this._newAuditItem);}
_handleChange(event){const item=this._selectedItem();if(item)
item.select();else
this._renderNewAuditView();}
_selectedItem(){const option=this._comboBox.selectedOption();return this._itemByOptionElement.get(option);}
hasCurrentSelection(){return!!this._selectedItem();}
hasItems(){return this._itemByOptionElement.size>0;}
comboBox(){return this._comboBox;}
prepend(item){const optionEl=item.optionElement();const selectEl=this._comboBox.selectElement();this._itemByOptionElement.set(optionEl,item);selectEl.insertBefore(optionEl,selectEl.firstElementChild);this._comboBox.setEnabled(true);this._comboBox.select(optionEl);item.select();}
clearAll(){for(const elem of this._comboBox.options()){if(elem===this._newAuditItem)
continue;this._itemByOptionElement.get(elem).delete();this._itemByOptionElement.delete(elem);}
this._setEmptyState();}
downloadSelected(){const item=this._selectedItem();if(item)
item.download();}
selectNewAudit(){this._comboBox.select(this._newAuditItem);}};Audits2.ReportSelector.Item=class{constructor(lighthouseResult,renderReport,showLandingCallback){this._lighthouseResult=lighthouseResult;this._renderReport=renderReport;this._showLandingCallback=showLandingCallback;const url=new Common.ParsedURL(lighthouseResult.finalUrl);const timestamp=lighthouseResult.fetchTime;this._element=createElement('option');this._element.label=`${new Date(timestamp).toLocaleTimeString()} - ${url.domain()}`;}
select(){this._renderReport();}
optionElement(){return this._element;}
delete(){if(this._element)
this._element.remove();this._showLandingCallback();}
download(){const domain=new Common.ParsedURL(this._lighthouseResult.finalUrl).domain();const sanitizedDomain=domain.replace(/[^a-z0-9.-]+/gi,'_');const timestamp=this._lighthouseResult.fetchTime;const fileName=`${sanitizedDomain}-${new Date(timestamp).toISO8601Compact()}.json`;Workspace.fileManager.save(fileName,JSON.stringify(this._lighthouseResult),true);}};;Audits2.ReportRenderer=class extends ReportRenderer{static addViewTraceButton(el,artifacts){if(!artifacts||!artifacts.traces||!artifacts.traces.defaultPass)
return;const defaultPassTrace=artifacts.traces.defaultPass;const timelineButton=UI.createTextButton(Common.UIString('View Trace'),onViewTraceClick,'view-trace');el.querySelector('.lh-column').appendChild(timelineButton);return el;async function onViewTraceClick(){Host.userMetrics.actionTaken(Host.UserMetrics.Action.Audits2ViewTrace);await UI.inspectorView.showPanel('timeline');Timeline.TimelinePanel.instance().loadFromEvents(defaultPassTrace.traceEvents);}}
static async linkifyNodeDetails(el){const mainTarget=SDK.targetManager.mainTarget();const resourceTreeModel=mainTarget.model(SDK.ResourceTreeModel);await resourceTreeModel.once(SDK.ResourceTreeModel.Events.Load);const domModel=mainTarget.model(SDK.DOMModel);for(const origElement of el.getElementsByClassName('lh-node')){const detailsItem=origElement.dataset;if(!detailsItem.path)
continue;const nodeId=await domModel.pushNodeByPathToFrontend(detailsItem.path);if(!nodeId)
continue;const node=domModel.nodeForId(nodeId);if(!node)
continue;const element=await Common.Linkifier.linkify(node,({title:detailsItem.snippet}));origElement.title='';origElement.textContent='';origElement.appendChild(element);}}
static handleDarkMode(el){if(UI.themeSupport.themeName()==='dark')
el.classList.add('dark');}};;Audits2.StartView=class extends UI.Widget{constructor(controller){super();this.registerRequiredCSS('audits2/audits2StartView.css');this._controller=controller;this._render();}
_populateRuntimeSettingAsRadio(settingName,parentElement){const runtimeSetting=Audits2.RuntimeSettings.find(item=>item.setting.name===settingName);if(!runtimeSetting||!runtimeSetting.options)
throw new Error(`${settingName} is not a setting with options`);const control=new Audits2.RadioSetting(runtimeSetting.options,runtimeSetting.setting);control.element.title=runtimeSetting.description;parentElement.appendChild(control.element);}
_populateRuntimeSettingAsCheckbox(settingName,parentElement){const runtimeSetting=Audits2.RuntimeSettings.find(item=>item.setting.name===settingName);if(!runtimeSetting||!runtimeSetting.title)
throw new Error(`${settingName} is not a setting with a title`);runtimeSetting.setting.setTitle(runtimeSetting.title);const control=new UI.ToolbarSettingCheckbox(runtimeSetting.setting,runtimeSetting.description);parentElement.appendChild(control.element);}
_populateFormControls(fragment){const deviceTypeFormElements=fragment.$('device-type-form-elements');this._populateRuntimeSettingAsRadio('audits2.device_type',deviceTypeFormElements);const categoryFormElements=fragment.$('categories-form-elements');for(const preset of Audits2.Presets){preset.setting.setTitle(preset.title);const checkbox=new UI.ToolbarSettingCheckbox(preset.setting);const row=categoryFormElements.createChild('div','vbox audits2-launcher-row');row.title=preset.description;row.appendChild(checkbox.element);}
const throttlingFormElements=fragment.$('throttling-form-elements');this._populateRuntimeSettingAsRadio('audits2.throttling',throttlingFormElements);const otherFormElements=fragment.$('other-form-elements');this._populateRuntimeSettingAsCheckbox('audits2.clear_storage',otherFormElements);}
_render(){this._startButton=UI.createTextButton(ls`Run audits`,()=>this._controller.dispatchEventToListeners(Audits2.Events.RequestAuditStart),'audits2-start-button',true);this.setDefaultFocusedElement(this._startButton);const deviceIcon=UI.Icon.create('largeicon-phone');const categoriesIcon=UI.Icon.create('largeicon-checkmark');const throttlingIcon=UI.Icon.create('largeicon-settings-gear');const fragment=UI.Fragment.build`
<div class="vbox audits2-start-view">
<header>
<div class="audits2-logo"></div>
<div class="audits2-start-view-text">
<h2>${ls`Audits`}</h2>
<p>
${ls`Identify and fix common problems that affect your site's performance,accessibility,and user experience.`}
<span class="link" $="learn-more">${ls`Learn more`}</a>
</p>
</div>
</header>
<form>
<div class="audits2-form-section">
<div class="audits2-form-section-label">
<i>${deviceIcon}</i>
<div class="audits2-icon-label">${ls`Device`}</div>
</div>
<div class="audits2-form-elements" $="device-type-form-elements"></div>
</div>
<div class="audits2-form-section">
<div class="audits2-form-section-label">
<i>${categoriesIcon}</i>
<div class="audits2-icon-label">${ls`Audits`}</div>
</div>
<div class="audits2-form-elements" $="categories-form-elements"></div>
</div>
<div class="audits2-form-section">
<div class="audits2-form-section-label">
<i>${throttlingIcon}</i>
<div class="audits2-icon-label">${ls`Throttling`}</div>
</div>
<div class="audits2-form-elements" $="throttling-form-elements"></div>
</div>
<div class="audits2-form-section">
<div class="audits2-form-section-label"></div>
<div class="audits2-form-elements" $="other-form-elements"></div>
</div>
<div class="audits2-form-section">
<div class="audits2-form-section-label"></div>
<div class="audits2-form-elements audits2-start-button-container hbox">
${this._startButton}
<div $="help-text" class="audits2-help-text hidden"></div>
</div>
</div>
</form>
</div>
`;this._helpText=fragment.$('help-text');const learnMoreLink=fragment.$('learn-more');learnMoreLink.addEventListener('click',()=>InspectorFrontendHost.openInNewTab('https://developers.google.com/web/tools/lighthouse/'));this._populateFormControls(fragment);this.contentElement.appendChild(fragment.element());this.contentElement.style.overflow='auto';}
focusStartButton(){this._startButton.focus();}
setStartButtonEnabled(isEnabled){if(this._helpText)
this._helpText.classList.toggle('hidden',isEnabled);if(this._startButton)
this._startButton.disabled=!isEnabled;}
setUnauditableExplanation(text){if(this._helpText)
this._helpText.textContent=text;}};;Audits2.StatusView=class{constructor(controller){this._controller=controller;this._statusView=null;this._statusHeader=null;this._progressWrapper=null;this._progressBar=null;this._statusText=null;this._inspectedURL='';this._textChangedAt=0;this._fastFactsQueued=Audits2.StatusView.FastFacts.slice();this._currentPhase=null;this._scheduledTextChangeTimeout=null;this._scheduledFastFactTimeout=null;this._dialog=new UI.Dialog();this._dialog.setDimmed(true);this._dialog.setCloseOnEscape(false);this._dialog.setOutsideClickCallback(event=>event.consume(true));this._render();}
_render(){const dialogRoot=UI.createShadowRootWithCoreStyles(this._dialog.contentElement,'audits2/audits2Dialog.css');const auditsViewElement=dialogRoot.createChild('div','audits2-view vbox');const cancelButton=UI.createTextButton(ls`Cancel`,this._cancel.bind(this));const fragment=UI.Fragment.build`
<div class="audits2-view vbox">
<h2 $="status-header">Auditing your web page\u2026</h2>
<div class="audits2-status vbox" $="status-view">
<div class="audits2-progress-wrapper" $="progress-wrapper">
<div class="audits2-progress-bar" $="progress-bar"></div>
</div>
<div class="audits2-status-text" $="status-text"></div>
</div>
${cancelButton}
</div>
`;auditsViewElement.appendChild(fragment.element());auditsViewElement.tabIndex=0;this._statusView=fragment.$('status-view');this._statusHeader=fragment.$('status-header');this._progressWrapper=fragment.$('progress-wrapper');this._progressBar=fragment.$('progress-bar');this._statusText=fragment.$('status-text');this._dialog.setDefaultFocusedElement(cancelButton);this._dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.SetExactWidthMaxHeight);this._dialog.setMaxContentSize(new UI.Size(500,400));}
_reset(){this._resetProgressBarClasses();clearTimeout(this._scheduledFastFactTimeout);this._textChangedAt=0;this._fastFactsQueued=Audits2.StatusView.FastFacts.slice();this._currentPhase=null;this._scheduledTextChangeTimeout=null;this._scheduledFastFactTimeout=null;}
show(dialogRenderElement){this._reset();this.updateStatus(ls`Loading\u2026`);const parsedURL=this._inspectedURL.asParsedURL();const pageHost=parsedURL&&parsedURL.host;const statusHeader=pageHost?ls`Auditing ${pageHost}`:ls`Auditing your web page`;this._statusHeader.textContent=`${statusHeader}\u2026`;this._dialog.show(dialogRenderElement);}
hide(){if(this._dialog.isShowing())
this._dialog.hide();}
setInspectedURL(url=''){this._inspectedURL=url;}
updateStatus(message){if(!message||!this._statusText)
return;if(message.startsWith('Cancel')){this._commitTextChange(Common.UIString('Cancelling\u2026'));clearTimeout(this._scheduledFastFactTimeout);return;}
const nextPhase=this._getPhaseForMessage(message);if(!nextPhase&&!this._currentPhase){this._commitTextChange(Common.UIString('Lighthouse is warming up\u2026'));clearTimeout(this._scheduledFastFactTimeout);}else if(nextPhase&&(!this._currentPhase||this._currentPhase.order<nextPhase.order)){this._currentPhase=nextPhase;this._scheduleTextChange(this._getMessageForPhase(nextPhase));this._scheduleFastFactCheck();this._resetProgressBarClasses();this._progressBar.classList.add(nextPhase.progressBarClass);}}
_cancel(){this._controller.dispatchEventToListeners(Audits2.Events.RequestAuditCancel);}
_getMessageForPhase(phase){if(phase.message)
return Common.UIString(phase.message);const deviceType=Audits2.RuntimeSettings.find(item=>item.setting.name==='audits2.device_type').setting.get();const throttling=Audits2.RuntimeSettings.find(item=>item.setting.name==='audits2.throttling').setting.get();const match=Audits2.StatusView.LoadingMessages.find(item=>{return item.deviceType===deviceType&&item.throttling===throttling;});return match?ls`${match.message}`:ls`Lighthouse is loading your page`;}
_getPhaseForMessage(message){return Audits2.StatusView.StatusPhases.find(phase=>message.startsWith(phase.statusMessagePrefix));}
_resetProgressBarClasses(){if(!this._progressBar)
return;this._progressBar.className='audits2-progress-bar';}
_scheduleFastFactCheck(){if(!this._currentPhase||this._scheduledFastFactTimeout)
return;this._scheduledFastFactTimeout=setTimeout(()=>{this._updateFastFactIfNecessary();this._scheduledFastFactTimeout=null;this._scheduleFastFactCheck();},100);}
_updateFastFactIfNecessary(){const now=performance.now();if(now-this._textChangedAt<Audits2.StatusView.fastFactRotationInterval)
return;if(!this._fastFactsQueued.length)
return;const fastFactIndex=Math.floor(Math.random()*this._fastFactsQueued.length);this._scheduleTextChange(ls`\ud83d\udca1 ${this._fastFactsQueued[fastFactIndex]}`);this._fastFactsQueued.splice(fastFactIndex,1);}
_commitTextChange(text){if(!this._statusText)
return;this._textChangedAt=performance.now();this._statusText.textContent=text;}
_scheduleTextChange(text){if(this._scheduledTextChangeTimeout)
clearTimeout(this._scheduledTextChangeTimeout);const msSinceLastChange=performance.now()-this._textChangedAt;const msToTextChange=Audits2.StatusView.minimumTextVisibilityDuration-msSinceLastChange;this._scheduledTextChangeTimeout=setTimeout(()=>{this._commitTextChange(text);},Math.max(msToTextChange,0));}
renderBugReport(err){console.error(err);clearTimeout(this._scheduledFastFactTimeout);clearTimeout(this._scheduledTextChangeTimeout);this._resetProgressBarClasses();this._progressBar.classList.add('errored');this._commitTextChange('');this._statusText.createChild('p').createTextChild(Common.UIString('Ah, sorry! We ran into an error.'));if(Audits2.StatusView.KnownBugPatterns.some(pattern=>pattern.test(err.message))){const message=Common.UIString('Try to navigate to the URL in a fresh Chrome profile without any other tabs or extensions open and try again.');this._statusText.createChild('p').createTextChild(message);}else{this._renderBugReportBody(err,this._inspectedURL);}}
_renderBugReportBody(err,auditURL){const issueBody=`
${err.message}
\`\`\`
Channel: DevTools
Initial URL: ${auditURL}
Chrome Version: ${navigator.userAgent.match(/Chrome\/(\S+)/)[1]}
Stack Trace: ${err.stack}
\`\`\`
`;this._statusText.createChild('p').createTextChild(ls`If this issue is reproducible, please report it at the Lighthouse GitHub repo.`);this._statusText.createChild('code','monospace').createTextChild(issueBody.trim());}};Audits2.StatusView.KnownBugPatterns=[/PARSING_PROBLEM/,/DOCUMENT_REQUEST/,/READ_FAILED/,/TRACING_ALREADY_STARTED/,/^You must provide a url to the runner/,/^You probably have multiple tabs open/,];Audits2.StatusView.StatusPhases=[{id:'loading',progressBarClass:'loading',statusMessagePrefix:'Loading page',order:10,},{id:'gathering',progressBarClass:'gathering',message:'Lighthouse is gathering information about the page to compute your score.',statusMessagePrefix:'Gathering',order:20,},{id:'auditing',progressBarClass:'auditing',message:'Almost there! Lighthouse is now generating your report.',statusMessagePrefix:'Auditing',order:30,}];Audits2.StatusView.LoadingMessages=[{deviceType:'mobile',throttling:'on',message:'Lighthouse is loading your page with throttling to measure performance on a mobile device on 3G.',},{deviceType:'desktop',throttling:'on',message:'Lighthouse is loading your page with throttling to measure performance on a slow desktop on 3G.',},{deviceType:'mobile',throttling:'off',message:'Lighthouse is loading your page with mobile emulation.',},{deviceType:'desktop',throttling:'off',message:'Lighthouse is loading your page.',},];Audits2.StatusView.FastFacts=['1MB takes a minimum of 5 seconds to download on a typical 3G connection [Source: WebPageTest and DevTools 3G definition].','Rebuilding Pinterest pages for performance increased conversion rates by 15% [Source: WPO Stats]','BBC has seen a loss of 10% of their users for every extra second of page load [Source: WPO Stats]','By reducing the response size of JSON needed for displaying comments, Instagram saw increased impressions [Source: WPO Stats]','Walmart saw a 1% increase in revenue for every 100ms improvement in page load [Source: WPO Stats]','If a site takes >1 second to become interactive, users lose attention, and their perception of completing the page task is broken [Source: Google Developers Blog]','75% of global mobile users in 2016 were on 2G or 3G [Source: GSMA Mobile]','The average user device costs less than 200 USD. [Source: International Data Corporation]','53% of all site visits are abandoned if page load takes more than 3 seconds [Source: Google DoubleClick blog]','19 seconds is the average time a mobile web page takes to load on a 3G connection [Source: Google DoubleClick blog]','14 seconds is the average time a mobile web page takes to load on a 4G connection [Source: Google DoubleClick blog]','70% of mobile pages take nearly 7 seconds for the visual content above the fold to display on the screen. [Source: Think with Google]','As page load time increases from one second to seven seconds, the probability of a mobile site visitor bouncing increases 113%. [Source: Think with Google]','As the number of elements on a page increases from 400 to 6,000, the probability of conversion drops 95%. [Source: Think with Google]','70% of mobile pages weigh over 1MB, 36% over 2MB, and 12% over 4MB. [Source: Think with Google]','Lighthouse only simulates mobile performance; to measure performance on a real device, try WebPageTest.org [Source: Lighthouse team]',];Audits2.StatusView.fastFactRotationInterval=6000;Audits2.StatusView.minimumTextVisibilityDuration=3000;;Audits2.ProtocolService=class extends Common.Object{constructor(){super();this._rawConnection=null;this._backend=null;this._backendPromise=null;this._status=null;}
attach(){return SDK.interceptMainConnection(this._dispatchProtocolMessage.bind(this)).then(rawConnection=>{this._rawConnection=rawConnection;});}
startLighthouse(auditURL,categoryIDs,flags){return this._send('start',{url:auditURL,categoryIDs,flags});}
detach(){return Promise.resolve().then(()=>this._send('stop')).then(()=>this._backend.dispose()).then(()=>{delete this._backend;delete this._backendPromise;return this._rawConnection.disconnect();});}
registerStatusCallback(callback){this._status=callback;}
_dispatchProtocolMessage(message){this._send('dispatchProtocolMessage',{message:message});}
_initWorker(){this._backendPromise=Services.serviceManager.createAppService('audits2_worker','Audits2Service').then(backend=>{if(this._backend)
return;this._backend=backend;this._backend.on('statusUpdate',result=>this._status(result.message));this._backend.on('sendProtocolMessage',result=>this._sendProtocolMessage(result.message));});}
_sendProtocolMessage(message){this._rawConnection.sendRawMessage(message);}
_send(method,params){if(!this._backendPromise)
this._initWorker();return this._backendPromise.then(_=>this._backend.send(method,params));}};;Runtime.cachedResources["audits2/audits2Dialog.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.audits2-view {\n --view-horizontal-margin: 20px;\n margin: 7px var(--view-horizontal-margin);\n flex: auto;\n align-items: center;\n width: 100%;\n max-width: 500px;\n}\n\n.audits2-view h2 {\n color: #666;\n font-weight: bold;\n font-size: 14px;\n flex: none;\n width: 100%;\n text-align: left;\n}\n\n.audits2-view button {\n z-index: 10;\n margin-left: auto;\n margin-right: 0px;\n}\n\n.audits2-status {\n width: 100%;\n flex: auto;\n align-items: center;\n color: #666;\n}\n\n.audits2-status-text {\n text-align: center;\n min-height: 50px;\n margin-bottom: 10px;\n display: flex;\n justify-content: center;\n flex-direction: column;\n}\n\n.audits2-status-text code {\n user-select: text;\n text-align: left;\n white-space: pre-wrap;\n overflow: auto;\n}\n\n.audits2-progress-wrapper {\n width: calc(100% + 2 * var(--view-horizontal-margin));\n height: 2px;\n background-color: #E1F5FE;\n position: relative;\n margin: 10px;\n}\n\n.audits2-progress-bar {\n width: 0%;\n height: 100%;\n background: #039BE5;\n position: absolute;\n transform-origin: left;\n animation-fill-mode: forwards;\n animation-timing-function: ease-out;\n --progress-bar-loading-duration: 45s;\n --progress-bar-gathering-duration: 12s;\n --progress-bar-gathering-percent: 70%;\n --progress-bar-auditing-duration: 5s;\n --progress-bar-auditing-percent: 95%;\n}\n\n.audits2-progress-bar.errored {\n width: 100%;\n background: #E50303;\n}\n\n.audits2-progress-bar.loading {\n animation-duration: var(--progress-bar-loading-duration);\n animation-name: progressBarLoading;\n}\n\n@keyframes progressBarLoading {\n 0% { width: 0%; }\n 100% { width: var(--progress-bar-gathering-percent); }\n}\n\n.audits2-progress-bar.gathering {\n animation-duration: var(--progress-bar-gathering-duration);\n animation-name: progressBarGathering;\n}\n\n@keyframes progressBarGathering {\n 0% { width: var(--progress-bar-gathering-percent); }\n 100% { width: var(--progress-bar-auditing-percent); }\n}\n\n.audits2-progress-bar.auditing {\n animation-duration: var(--progress-bar-auditing-duration);\n animation-name: progressBarAuditing;\n}\n\n@keyframes progressBarAuditing {\n 0% { width: var(--progress-bar-auditing-percent); }\n 100% { width: 99%; }\n}\n\n/*# sourceURL=audits2/audits2Dialog.css */";Runtime.cachedResources["audits2/audits2Panel.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.toolbar {\n background-color: var(--toolbar-bg-color);\n border-bottom: var(--divider-border);\n}\n\n.lh-root {\n --report-menu-width: 0;\n user-select: text;\n}\n\n/* for View Trace button */\n.lh-audit-group {\n position: relative;\n}\nbutton.view-trace {\n margin: 10px;\n}\n\n.audits2-results-container {\n position: relative;\n}\n\n/*# sourceURL=audits2/audits2Panel.css */";Runtime.cachedResources["audits2/audits2StartView.css"]="/*\n * Copyright 2018 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.audits2-start-view {\n font-family: Roboto, sans-serif;\n font-size: 13px;\n line-height: 18px;\n}\n\n.audits2-start-view header {\n padding: 0 16px;\n display: flex;\n}\n\n.audits2-logo {\n width: 150px;\n height: 150px;\n flex-shrink: 0;\n background-repeat: no-repeat;\n background-size: contain;\n margin-right: 20px;\n background-image: url(Images/audits_logo.svg);\n}\n\n.audits2-start-view-text {\n color: #757575;\n margin-top: 24px;\n}\n\n.au
this._addBreakpoint(breakpoint);}
this._highlightedElement=null;this._update();}
_breakpointAdded(event){this._addBreakpoint((event.data));}
_breakpointToggled(event){const breakpoint=(event.data);const item=this._items.get(breakpoint);if(item)
item.checkbox.checked=breakpoint.enabled;}
_breakpointsRemoved(event){const breakpoints=(event.data);for(const breakpoint of breakpoints){const item=this._items.get(breakpoint);if(item){this._items.delete(breakpoint);this._listElement.removeChild(item.element);}}
if(!this._listElement.firstChild){this._emptyElement.classList.remove('hidden');this._listElement.classList.add('hidden');}}
_addBreakpoint(breakpoint){const element=createElementWithClass('div','breakpoint-entry');element.addEventListener('contextmenu',this._contextMenu.bind(this,breakpoint),true);const checkboxLabel=UI.CheckboxLabel.create('',breakpoint.enabled);const checkboxElement=checkboxLabel.checkboxElement;checkboxElement.addEventListener('click',this._checkboxClicked.bind(this,breakpoint),false);element.appendChild(checkboxLabel);const labelElement=createElementWithClass('div','dom-breakpoint');element.appendChild(labelElement);const linkifiedNode=createElementWithClass('monospace');linkifiedNode.style.display='block';labelElement.appendChild(linkifiedNode);Common.Linkifier.linkify(breakpoint.node).then(linkified=>linkifiedNode.appendChild(linkified));const description=createElement('div');description.textContent=BrowserDebugger.DOMBreakpointsSidebarPane.BreakpointTypeLabels.get(breakpoint.type);labelElement.appendChild(description);const item={breakpoint:breakpoint,element:element,checkbox:checkboxElement};element._item=item;this._items.set(breakpoint,item);let currentElement=this._listElement.firstChild;while(currentElement){if(currentElement._item&&currentElement._item.breakpoint.type<breakpoint.type)
break;currentElement=currentElement.nextSibling;}
this._listElement.insertBefore(element,currentElement);this._emptyElement.classList.add('hidden');this._listElement.classList.remove('hidden');}
_contextMenu(breakpoint,event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Remove breakpoint'),()=>{breakpoint.domDebuggerModel.removeDOMBreakpoint(breakpoint.node,breakpoint.type);});contextMenu.defaultSection().appendItem(Common.UIString('Remove all DOM breakpoints'),()=>{breakpoint.domDebuggerModel.removeAllDOMBreakpoints();});contextMenu.show();}
_checkboxClicked(breakpoint){const item=this._items.get(breakpoint);if(!item)
return;breakpoint.domDebuggerModel.toggleDOMBreakpoint(breakpoint,item.checkbox.checked);}
flavorChanged(object){this._update();}
_update(){const details=UI.context.flavor(SDK.DebuggerPausedDetails);if(!details||!details.auxData||details.reason!==SDK.DebuggerModel.BreakReason.DOM){if(this._highlightedElement){this._highlightedElement.classList.remove('breakpoint-hit');delete this._highlightedElement;}
return;}
const domDebuggerModel=details.debuggerModel.target().model(SDK.DOMDebuggerModel);if(!domDebuggerModel)
return;const data=domDebuggerModel.resolveDOMBreakpointData((details.auxData));if(!data)
return;let element=null;for(const item of this._items.values()){if(item.breakpoint.node===data.node&&item.breakpoint.type===data.type)
element=item.element;}
if(!element)
return;UI.viewManager.showView('sources.domBreakpoints');element.classList.add('breakpoint-hit');this._highlightedElement=element;}};BrowserDebugger.DOMBreakpointsSidebarPane.Item;BrowserDebugger.DOMBreakpointsSidebarPane.BreakpointTypeLabels=new Map([[SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified,Common.UIString('Subtree modified')],[SDK.DOMDebuggerModel.DOMBreakpoint.Type.AttributeModified,Common.UIString('Attribute modified')],[SDK.DOMDebuggerModel.DOMBreakpoint.Type.NodeRemoved,Common.UIString('Node removed')],]);BrowserDebugger.DOMBreakpointsSidebarPane.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,object){const node=(object);if(node.pseudoType())
return;const domDebuggerModel=node.domModel().target().model(SDK.DOMDebuggerModel);if(!domDebuggerModel)
return;function toggleBreakpoint(type){if(domDebuggerModel.hasDOMBreakpoint(node,type))
domDebuggerModel.removeDOMBreakpoint(node,type);else
domDebuggerModel.setDOMBreakpoint(node,type);}
const breakpointsMenu=contextMenu.debugSection().appendSubMenuItem(Common.UIString('Break on'));for(const key in SDK.DOMDebuggerModel.DOMBreakpoint.Type){const type=SDK.DOMDebuggerModel.DOMBreakpoint.Type[key];const label=Sources.DebuggerPausedMessage.BreakpointTypeNouns.get(type);breakpointsMenu.defaultSection().appendCheckboxItem(label,toggleBreakpoint.bind(null,type),domDebuggerModel.hasDOMBreakpoint(node,type));}}};;BrowserDebugger.EventListenerBreakpointsSidebarPane=class extends UI.VBox{constructor(){super(true);this._categoriesTreeOutline=new UI.TreeOutlineInShadow();this._categoriesTreeOutline.element.tabIndex=0;this._categoriesTreeOutline.registerRequiredCSS('browser_debugger/eventListenerBreakpoints.css');this.contentElement.appendChild(this._categoriesTreeOutline.element);this._categories=new Map();const categories=SDK.domDebuggerManager.eventListenerBreakpoints().map(breakpoint=>breakpoint.category());categories.sort();for(const category of categories){if(!this._categories.has(category))
this._createCategory(category);}
this._breakpoints=new Map();for(const breakpoint of SDK.domDebuggerManager.eventListenerBreakpoints())
this._createBreakpoint(breakpoint);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerPaused,this._update,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerResumed,this._update,this);UI.context.addFlavorChangeListener(SDK.Target,this._update,this);}
_createCategory(name){const labelNode=UI.CheckboxLabel.create(name);labelNode.checkboxElement.addEventListener('click',this._categoryCheckboxClicked.bind(this,name),true);const treeElement=new UI.TreeElement(labelNode);treeElement.selectable=false;this._categoriesTreeOutline.appendChild(treeElement);this._categories.set(name,{element:treeElement,checkbox:labelNode.checkboxElement});}
_createBreakpoint(breakpoint){const labelNode=UI.CheckboxLabel.create(breakpoint.title());labelNode.classList.add('source-code');labelNode.checkboxElement.addEventListener('click',this._breakpointCheckboxClicked.bind(this,breakpoint),true);const treeElement=new UI.TreeElement(labelNode);treeElement.listItemElement.createChild('div','breakpoint-hit-marker');treeElement.selectable=false;this._categories.get(breakpoint.category()).element.appendChild(treeElement);this._breakpoints.set(breakpoint,{element:treeElement,checkbox:labelNode.checkboxElement});}
_update(){const target=UI.context.flavor(SDK.Target);const debuggerModel=target?target.model(SDK.DebuggerModel):null;const details=debuggerModel?debuggerModel.debuggerPausedDetails():null;if(!details||details.reason!==SDK.DebuggerModel.BreakReason.EventListener||!details.auxData){if(this._highlightedElement){this._highlightedElement.classList.remove('breakpoint-hit');delete this._highlightedElement;}
return;}
const breakpoint=SDK.domDebuggerManager.resolveEventListenerBreakpoint((details.auxData));if(!breakpoint)
return;UI.viewManager.showView('sources.eventListenerBreakpoints');this._categories.get(breakpoint.category()).element.expand();this._highlightedElement=this._breakpoints.get(breakpoint).element.listItemElement;this._highlightedElement.classList.add('breakpoint-hit');}
_categoryCheckboxClicked(category){const item=this._categories.get(category);const enabled=item.checkbox.checked;for(const breakpoint of this._breakpoints.keys()){if(breakpoint.category()===category){breakpoint.setEnabled(enabled);this._breakpoints.get(breakpoint).checkbox.checked=enabled;}}}
_breakpointCheckboxClicked(breakpoint){const item=this._breakpoints.get(breakpoint);breakpoint.setEnabled(item.checkbox.checked);let hasEnabled=false;let hasDisabled=false;for(const other of this._breakpoints.keys()){if(other.category()===breakpoint.category()){if(other.enabled())
hasEnabled=true;else
hasDisabled=true;}}
const checkbox=this._categories.get(breakpoint.category()).checkbox;checkbox.checked=hasEnabled;checkbox.indeterminate=hasEnabled&&hasDisabled;}};BrowserDebugger.EventListenerBreakpointsSidebarPane.Item;;BrowserDebugger.ObjectEventListenersSidebarPane=class extends UI.VBox{constructor(){super();this._refreshButton=new UI.ToolbarButton(Common.UIString('Refresh'),'largeicon-refresh');this._refreshButton.addEventListener(UI.ToolbarButton.Events.Click,this._refreshClick,this);this._refreshButton.setEnabled(false);this._eventListenersView=new EventListeners.EventListenersView(this.update.bind(this));this._eventListenersView.show(this.element);}
toolbarItems(){return[this._refreshButton];}
update(){if(this._lastRequestedContext){this._lastRequestedContext.runtimeModel.releaseObjectGroup(BrowserDebugger.ObjectEventListenersSidebarPane._objectGroupName);delete this._lastRequestedContext;}
const executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext){this._eventListenersView.reset();this._eventListenersView.addEmptyHolderIfNeeded();return;}
this._lastRequestedContext=executionContext;Promise.all([this._windowObjectInContext(executionContext)]).then(this._eventListenersView.addObjects.bind(this._eventListenersView));}
wasShown(){super.wasShown();UI.context.addFlavorChangeListener(SDK.ExecutionContext,this.update,this);this._refreshButton.setEnabled(true);this.update();}
willHide(){super.willHide();UI.context.removeFlavorChangeListener(SDK.ExecutionContext,this.update,this);this._refreshButton.setEnabled(false);}
_windowObjectInContext(executionContext){return executionContext.evaluate({expression:'self',objectGroup:BrowserDebugger.ObjectEventListenersSidebarPane._objectGroupName,includeCommandLineAPI:false,silent:true,returnByValue:false,generatePreview:false},false,false).then(result=>result.object&&!result.exceptionDetails?result.object:null);}
_refreshClick(event){event.data.consume();this.update();}};BrowserDebugger.ObjectEventListenersSidebarPane._objectGroupName='object-event-listeners-sidebar-pane';;BrowserDebugger.XHRBreakpointsSidebarPane=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('browser_debugger/xhrBreakpointsSidebarPane.css');this._listElement=this.contentElement.createChild('div','breakpoint-list hidden');this._emptyElement=this.contentElement.createChild('div','gray-info-message');this._emptyElement.textContent=Common.UIString('No breakpoints');this._breakpointElements=new Map();this._addButton=new UI.ToolbarButton(Common.UIString('Add breakpoint'),'largeicon-add');this._addButton.addEventListener(UI.ToolbarButton.Events.Click,this._addButtonClicked.bind(this));this._emptyElement.addEventListener('contextmenu',this._emptyElementContextMenu.bind(this),true);this._restoreBreakpoints();this._update();}
toolbarItems(){return[this._addButton];}
_emptyElementContextMenu(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Add breakpoint'),this._addButtonClicked.bind(this));contextMenu.show();}
async _addButtonClicked(){await UI.viewManager.showView('sources.xhrBreakpoints');const inputElementContainer=createElementWithClass('p','breakpoint-condition');inputElementContainer.textContent=Common.UIString('Break when URL contains:');const inputElement=inputElementContainer.createChild('span','breakpoint-condition-input');this._addListElement(inputElementContainer,(this._listElement.firstChild));function finishEditing(accept,e,text){this._removeListElement(inputElementContainer);if(accept){SDK.domDebuggerManager.addXHRBreakpoint(text,true);this._setBreakpoint(text,true);}}
const config=new UI.InplaceEditor.Config(finishEditing.bind(this,true),finishEditing.bind(this,false));UI.InplaceEditor.startEditing(inputElement,config);}
_setBreakpoint(url,enabled){if(this._breakpointElements.has(url)){this._breakpointElements.get(url)._checkboxElement.checked=enabled;return;}
const element=createElementWithClass('div','breakpoint-entry');element._url=url;element.addEventListener('contextmenu',this._contextMenu.bind(this,url),true);const title=url?Common.UIString('URL contains "%s"',url):Common.UIString('Any XHR or fetch');const label=UI.CheckboxLabel.create(title,enabled);element.appendChild(label);label.checkboxElement.addEventListener('click',this._checkboxClicked.bind(this,url),false);element._checkboxElement=label.checkboxElement;label.classList.add('cursor-auto');label.textElement.addEventListener('dblclick',this._labelClicked.bind(this,url),false);let currentElement=(this._listElement.firstChild);while(currentElement){if(currentElement._url&&currentElement._url<element._url)
break;currentElement=(currentElement.nextSibling);}
this._addListElement(element,currentElement);this._breakpointElements.set(url,element);}
_removeBreakpoint(url){const element=this._breakpointElements.get(url);if(!element)
return;this._removeListElement(element);this._breakpointElements.delete(url);}
_addListElement(element,beforeNode){this._listElement.insertBefore(element,beforeNode);this._emptyElement.classList.add('hidden');this._listElement.classList.remove('hidden');}
_removeListElement(element){this._listElement.removeChild(element);if(!this._listElement.firstChild){this._emptyElement.classList.remove('hidden');this._listElement.classList.add('hidden');}}
_contextMenu(url,event){const contextMenu=new UI.ContextMenu(event);function removeBreakpoint(){SDK.domDebuggerManager.removeXHRBreakpoint(url);this._removeBreakpoint(url);}
function removeAllBreakpoints(){for(const url of this._breakpointElements.keys()){SDK.domDebuggerManager.removeXHRBreakpoint(url);this._removeBreakpoint(url);}}
const removeAllTitle=Common.UIString('Remove all breakpoints');contextMenu.defaultSection().appendItem(Common.UIString('Add breakpoint'),this._addButtonClicked.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Remove breakpoint'),removeBreakpoint.bind(this));contextMenu.defaultSection().appendItem(removeAllTitle,removeAllBreakpoints.bind(this));contextMenu.show();}
_checkboxClicked(url,event){SDK.domDebuggerManager.toggleXHRBreakpoint(url,event.target.checked);}
_labelClicked(url){const element=this._breakpointElements.get(url)||null;const inputElement=createElementWithClass('span','breakpoint-condition');inputElement.textContent=url;this._listElement.insertBefore(inputElement,element);element.classList.add('hidden');function finishEditing(accept,e,text){this._removeListElement(inputElement);if(accept){SDK.domDebuggerManager.removeXHRBreakpoint(url);this._removeBreakpoint(url);const enabled=element?element._checkboxElement.checked:true;SDK.domDebuggerManager.addXHRBreakpoint(text,enabled);this._setBreakpoint(text,enabled);}else{element.classList.remove('hidden');}}
UI.InplaceEditor.startEditing(inputElement,new UI.InplaceEditor.Config(finishEditing.bind(this,true),finishEditing.bind(this,false)));}
flavorChanged(object){this._update();}
_update(){const details=UI.context.flavor(SDK.DebuggerPausedDetails);if(!details||details.reason!==SDK.DebuggerModel.BreakReason.XHR){if(this._highlightedElement){this._highlightedElement.classList.remove('breakpoint-hit');delete this._highlightedElement;}
return;}
const url=details.auxData['breakpointURL'];const element=this._breakpointElements.get(url);if(!element)
return;UI.viewManager.showView('sources.xhrBreakpoints');element.classList.add('breakpoint-hit');this._highlightedElement=element;}
_restoreBreakpoints(){const breakpoints=SDK.domDebuggerManager.xhrBreakpoints();for(const url of breakpoints.keys())
this._setBreakpoint(url,breakpoints.get(url));}};;Runtime.cachedResources["browser_debugger/domBreakpointsSidebarPane.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.breakpoint-list {\n padding-bottom: 3px;\n}\n\n.breakpoint-list .dom-breakpoint > div {\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.breakpoint-entry {\n display: flex;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n padding: 2px 0;\n}\n\n.breakpoint-list .breakpoint-entry:hover {\n background-color: #eee;\n}\n\n.breakpoint-hit {\n background-color: rgb(255, 255, 194);\n}\n\n:host-context(.-theme-with-dark-background) .breakpoint-hit {\n background-color: hsl(46, 98%, 22%);\n color: #ccc;\n}\n\n/*# sourceURL=browser_debugger/domBreakpointsSidebarPane.css */";Runtime.cachedResources["browser_debugger/eventListenerBreakpoints.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n margin: 0;\n padding: 2px 4px;\n min-height: 18px;\n}\n\n.tree-outline {\n padding: 0;\n}\n\n.tree-outline li {\n margin-left: 14px;\n -webkit-user-select: text;\n cursor: default;\n}\n\n.tree-outline li.parent {\n margin-left: 1px;\n}\n\n.tree-outline li:not(.parent)::before {\n display: none;\n}\n\n.breakpoint-hit {\n background-color: rgb(255, 255, 194);\n}\n\n:host-context(.-theme-with-dark-background) .breakpoint-hit {\n background-color: hsl(46, 98%, 22%);\n color: #ccc;\n}\n\n.breakpoint-hit .breakpoint-hit-marker {\n background-color: rgb(255, 255, 194);\n height: 18px;\n left: 0;\n margin-left: -30px;\n position: absolute;\n right: -4px;\n z-index: -1;\n}\n\n/*# sourceURL=browser_debugger/eventListenerBreakpoints.css */";Runtime.cachedResources["browser_debugger/xhrBreakpointsSidebarPane.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.breakpoint-list {\n padding-bottom: 3px;\n}\n\n.breakpoint-list .editing.being-edited {\n overflow: hidden;\n white-space: nowrap;\n}\n\n.breakpoint-condition {\n display: block;\n margin-top: 4px;\n margin-bottom: 4px;\n margin-left: 23px;\n margin-right: 8px;\n}\n\n.breakpoint-condition-input {\n display: block;\n margin-left: 0;\n margin-right: 0;\n outline: none !important;\n border: 1px solid rgb(66%, 66%, 66%);\n}\n\n.breakpoint-entry {\n white-space: nowrap;\n padding: 2px 0;\n}\n\n.breakpoint-list .breakpoint-entry:hover {\n background-color: #eee;\n}\n\n.breakpoint-entry [is=dt-checkbox] {\n max-width: 100%;\n}\n\n.breakpoint-hit {\n background-color: rgb(255, 255, 194);\n}\n\n:host-context(.-theme-with-dark-background) .breakpoint-hit {\n background-color: hsl(46, 98%, 22%);\n color: #ccc;\n}\n\n/*# sourceURL=browser_debugger/xhrBreakpointsSidebarPane.css */";Changes.ChangesHighlighter=function(config,parserConfig){const diffRows=parserConfig.diffRows;const baselineLines=parserConfig.baselineLines;const currentLines=parserConfig.currentLines;const syntaxHighlightMode=CodeMirror.getMode({},parserConfig.mimeType);function fastForward(state,baselineLineNumber,currentLineNumber){if(baselineLineNumber>state.baselineLineNumber){fastForwardSyntaxHighlighter(state.baselineSyntaxState,state.baselineLineNumber,baselineLineNumber,baselineLines);state.baselineLineNumber=baselineLineNumber;}
if(currentLineNumber>state.currentLineNumber){fastForwardSyntaxHighlighter(state.currentSyntaxState,state.currentLineNumber,currentLineNumber,currentLines);state.currentLineNumber=currentLineNumber;}}
function fastForwardSyntaxHighlighter(syntaxState,from,to,lines){let lineNumber=from;while(lineNumber<to&&lineNumber<lines.length){const stream=new CodeMirror.StringStream(lines[lineNumber]);if(stream.eol()&&syntaxHighlightMode.blankLine)
syntaxHighlightMode.blankLine(syntaxState);while(!stream.eol()){syntaxHighlightMode.token(stream,syntaxState);stream.start=stream.pos;}
lineNumber++;}}
return{startState:function(){return{rowNumber:0,diffTokenIndex:0,currentLineNumber:0,baselineLineNumber:0,currentSyntaxState:CodeMirror.startState(syntaxHighlightMode),baselineSyntaxState:CodeMirror.startState(syntaxHighlightMode),syntaxPosition:0,diffPosition:0,syntaxStyle:'',diffStyle:''};},token:function(stream,state){const diffRow=diffRows[state.rowNumber];if(!diffRow){stream.next();return'';}
fastForward(state,diffRow.baselineLineNumber-1,diffRow.currentLineNumber-1);let classes='';if(stream.pos===0)
classes+=' line-background-'+diffRow.type+' line-'+diffRow.type;const syntaxHighlighterNeedsRefresh=state.diffPosition>=state.syntaxPosition;if(state.diffPosition<=state.syntaxPosition){state.diffPosition+=diffRow.tokens[state.diffTokenIndex].text.length;state.diffStyle=diffRow.tokens[state.diffTokenIndex].className;state.diffTokenIndex++;}
if(syntaxHighlighterNeedsRefresh){if(diffRow.type===Changes.ChangesView.RowType.Deletion||diffRow.type===Changes.ChangesView.RowType.Addition||diffRow.type===Changes.ChangesView.RowType.Equal){state.syntaxStyle=syntaxHighlightMode.token(stream,diffRow.type===Changes.ChangesView.RowType.Deletion?state.baselineSyntaxState:state.currentSyntaxState);state.syntaxPosition=stream.pos;}else{state.syntaxStyle='';state.syntaxPosition=Infinity;}}
stream.pos=Math.min(state.syntaxPosition,state.diffPosition);classes+=' '+state.syntaxStyle;classes+=' '+state.diffStyle;if(stream.eol()){state.rowNumber++;if(diffRow.type===Changes.ChangesView.RowType.Deletion)
state.baselineLineNumber++;else
state.currentLineNumber++;state.diffPosition=0;state.syntaxPosition=0;state.diffTokenIndex=0;}
return classes;},blankLine:function(state){const diffRow=diffRows[state.rowNumber];state.rowNumber++;state.syntaxPosition=0;state.diffPosition=0;state.diffTokenIndex=0;if(!diffRow)
return'';let style='';if(syntaxHighlightMode.blankLine){if(diffRow.type===Changes.ChangesView.RowType.Equal||diffRow.type===Changes.ChangesView.RowType.Addition){style=syntaxHighlightMode.blankLine(state.currentSyntaxState);state.currentLineNumber++;}else if(diffRow.type===Changes.ChangesView.RowType.Deletion){style=syntaxHighlightMode.blankLine(state.baselineSyntaxState);state.baselineLineNumber++;}}
return style+' line-background-'+diffRow.type+' line-'+diffRow.type;},copyState:function(state){const newState=Object.assign({},state);newState.currentSyntaxState=CodeMirror.copyState(syntaxHighlightMode,state.currentSyntaxState);newState.baselineSyntaxState=CodeMirror.copyState(syntaxHighlightMode,state.baselineSyntaxState);return(newState);}};};Changes.ChangesHighlighter.DiffState;CodeMirror.defineMode('devtools-diff',Changes.ChangesHighlighter);;Changes.ChangesView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('changes/changesView.css');const splitWidget=new UI.SplitWidget(true,false);const mainWidget=new UI.Widget();splitWidget.setMainWidget(mainWidget);splitWidget.show(this.contentElement);this._emptyWidget=new UI.EmptyWidget('');this._emptyWidget.show(mainWidget.element);this._workspaceDiff=WorkspaceDiff.workspaceDiff();this._changesSidebar=new Changes.ChangesSidebar(this._workspaceDiff);this._changesSidebar.addEventListener(Changes.ChangesSidebar.Events.SelectedUISourceCodeChanged,this._selectedUISourceCodeChanged,this);splitWidget.setSidebarWidget(this._changesSidebar);this._selectedUISourceCode=null;this._diffRows=[];this._maxLineDigits=1;this._editor=new TextEditor.CodeMirrorTextEditor({lineNumbers:true,lineWrapping:false,maxHighlightLength:Infinity});this._editor.setReadOnly(true);this._editor.show(mainWidget.element.createChild('div','editor-container'));this._editor.hideWidget();this._editor.element.addEventListener('click',this._click.bind(this),false);this._toolbar=new UI.Toolbar('changes-toolbar',mainWidget.element);const revertButton=new UI.ToolbarButton(Common.UIString('Revert all changes'),'largeicon-undo');revertButton.addEventListener(UI.ToolbarButton.Events.Click,this._revert.bind(this));this._toolbar.appendToolbarItem(revertButton);this._diffStats=new UI.ToolbarText('');this._toolbar.appendToolbarItem(this._diffStats);this._toolbar.setEnabled(false);this._hideDiff(ls`No changes`);this._selectedUISourceCodeChanged();}
_selectedUISourceCodeChanged(){this._revealUISourceCode(this._changesSidebar.selectedUISourceCode());}
_revert(){const uiSourceCode=this._selectedUISourceCode;if(!uiSourceCode)
return;this._workspaceDiff.revertToOriginal(uiSourceCode);}
_click(event){const selection=this._editor.selection();if(!selection.isEmpty())
return;const row=this._diffRows[selection.startLine];Common.Revealer.reveal(this._selectedUISourceCode.uiLocation(row.currentLineNumber-1,selection.startColumn),false);event.consume(true);}
_revealUISourceCode(uiSourceCode){if(this._selectedUISourceCode===uiSourceCode)
return;if(this._selectedUISourceCode)
this._workspaceDiff.unsubscribeFromDiffChange(this._selectedUISourceCode,this._refreshDiff,this);if(uiSourceCode&&this.isShowing())
this._workspaceDiff.subscribeToDiffChange(uiSourceCode,this._refreshDiff,this);this._selectedUISourceCode=uiSourceCode;this._refreshDiff();}
wasShown(){this._refreshDiff();}
_refreshDiff(){if(!this.isShowing())
return;if(!this._selectedUISourceCode){this._renderDiffRows(null);return;}
const uiSourceCode=this._selectedUISourceCode;if(!uiSourceCode.contentType().isTextType()){this._hideDiff(ls`Binary data`);return;}
this._workspaceDiff.requestDiff(uiSourceCode).then(diff=>{if(this._selectedUISourceCode!==uiSourceCode)
return;this._renderDiffRows(diff);});}
_hideDiff(message){this._diffStats.setText('');this._toolbar.setEnabled(false);this._editor.hideWidget();this._emptyWidget.text=message;this._emptyWidget.showWidget();}
_renderDiffRows(diff){this._diffRows=[];if(!diff||(diff.length===1&&diff[0][0]===Diff.Diff.Operation.Equal)){this._hideDiff(ls`No changes`);return;}
let insertions=0;let deletions=0;let currentLineNumber=0;let baselineLineNumber=0;const paddingLines=3;const originalLines=[];const currentLines=[];for(let i=0;i<diff.length;++i){const token=diff[i];switch(token[0]){case Diff.Diff.Operation.Equal:this._diffRows.pushAll(createEqualRows(token[1],i===0,i===diff.length-1));originalLines.pushAll(token[1]);currentLines.pushAll(token[1]);break;case Diff.Diff.Operation.Insert:for(const line of token[1])
this._diffRows.push(createRow(line,Changes.ChangesView.RowType.Addition));insertions+=token[1].length;currentLines.pushAll(token[1]);break;case Diff.Diff.Operation.Delete:deletions+=token[1].length;originalLines.pushAll(token[1]);if(diff[i+1]&&diff[i+1][0]===Diff.Diff.Operation.Insert){i++;this._diffRows.pushAll(createModifyRows(token[1].join('\n'),diff[i][1].join('\n')));insertions+=diff[i][1].length;currentLines.pushAll(diff[i][1]);}else{for(const line of token[1])
this._diffRows.push(createRow(line,Changes.ChangesView.RowType.Deletion));}
break;}}
this._maxLineDigits=Math.ceil(Math.log10(Math.max(currentLineNumber,baselineLineNumber)));let insertionText='';if(insertions===1)
insertionText=ls`${insertions} insertion (+),`;else
insertionText=ls`${insertions} insertions (+),`;let deletionText='';if(deletions===1)
deletionText=ls`${deletions} deletion (-)`;else
deletionText=ls`${deletions} deletions (-)`;this._diffStats.setText(`${insertionText} ${deletionText}`);this._toolbar.setEnabled(true);this._emptyWidget.hideWidget();this._editor.operation(()=>{this._editor.showWidget();this._editor.setHighlightMode({name:'devtools-diff',diffRows:this._diffRows,mimeType:(this._selectedUISourceCode).mimeType(),baselineLines:originalLines,currentLines:currentLines});this._editor.setText(this._diffRows.map(row=>row.tokens.map(t=>t.text).join('')).join('\n'));this._editor.setLineNumberFormatter(this._lineFormatter.bind(this));});function createEqualRows(lines,atStart,atEnd){const equalRows=[];if(!atStart){for(let i=0;i<paddingLines&&i<lines.length;i++)
equalRows.push(createRow(lines[i],Changes.ChangesView.RowType.Equal));if(lines.length>paddingLines*2+1&&!atEnd){equalRows.push(createRow(Common.UIString('( \u2026 Skipping %d matching lines \u2026 )',lines.length-paddingLines*2),Changes.ChangesView.RowType.Spacer));}}
if(!atEnd){const start=Math.max(lines.length-paddingLines-1,atStart?0:paddingLines);let skip=lines.length-paddingLines-1;if(!atStart)
skip-=paddingLines;if(skip>0){baselineLineNumber+=skip;currentLineNumber+=skip;}
for(let i=start;i<lines.length;i++)
equalRows.push(createRow(lines[i],Changes.ChangesView.RowType.Equal));}
return equalRows;}
function createModifyRows(before,after){const internalDiff=Diff.Diff.charDiff(before,after,true);const deletionRows=[createRow('',Changes.ChangesView.RowType.Deletion)];const insertionRows=[createRow('',Changes.ChangesView.RowType.Addition)];for(const token of internalDiff){const text=token[1];const type=token[0];const className=type===Diff.Diff.Operation.Equal?'':'inner-diff';const lines=text.split('\n');for(let i=0;i<lines.length;i++){if(i>0&&type!==Diff.Diff.Operation.Insert)
deletionRows.push(createRow('',Changes.ChangesView.RowType.Deletion));if(i>0&&type!==Diff.Diff.Operation.Delete)
insertionRows.push(createRow('',Changes.ChangesView.RowType.Addition));if(!lines[i])
continue;if(type!==Diff.Diff.Operation.Insert)
deletionRows[deletionRows.length-1].tokens.push({text:lines[i],className});if(type!==Diff.Diff.Operation.Delete)
insertionRows[insertionRows.length-1].tokens.push({text:lines[i],className});}}
return deletionRows.concat(insertionRows);}
function createRow(text,type){if(type===Changes.ChangesView.RowType.Addition)
currentLineNumber++;if(type===Changes.ChangesView.RowType.Deletion)
baselineLineNumber++;if(type===Changes.ChangesView.RowType.Equal){baselineLineNumber++;currentLineNumber++;}
return{baselineLineNumber,currentLineNumber,tokens:text?[{text,className:'inner-diff'}]:[],type};}}
_lineFormatter(lineNumber){const row=this._diffRows[lineNumber-1];let showBaseNumber=row.type===Changes.ChangesView.RowType.Deletion;let showCurrentNumber=row.type===Changes.ChangesView.RowType.Addition;if(row.type===Changes.ChangesView.RowType.Equal){showBaseNumber=true;showCurrentNumber=true;}
const base=showBaseNumber?numberToStringWithSpacesPadding(row.baselineLineNumber,this._maxLineDigits):spacesPadding(this._maxLineDigits);const current=showCurrentNumber?numberToStringWithSpacesPadding(row.currentLineNumber,this._maxLineDigits):spacesPadding(this._maxLineDigits);return base+spacesPadding(1)+current;}};Changes.ChangesView.Row;Changes.ChangesView.RowType={Deletion:'deletion',Addition:'addition',Equal:'equal',Spacer:'spacer'};Changes.ChangesView.DiffUILocationRevealer=class{async reveal(diffUILocation,omitFocus){if(!(diffUILocation instanceof WorkspaceDiff.DiffUILocation))
throw new Error('Internal error: not a diff ui location');const changesView=self.runtime.sharedInstance(Changes.ChangesView);await UI.viewManager.showView('changes.changes');changesView._changesSidebar.selectUISourceCode(diffUILocation.uiSourceCode,omitFocus);}};;Changes.ChangesSidebar=class extends UI.Widget{constructor(workspaceDiff){super();this._treeoutline=new UI.TreeOutlineInShadow();this._treeoutline.registerRequiredCSS('changes/changesSidebar.css');this._treeoutline.setComparator((a,b)=>a.titleAsText().compareTo(b.titleAsText()));this._treeoutline.addEventListener(UI.TreeOutline.Events.ElementSelected,this._selectionChanged,this);this.element.appendChild(this._treeoutline.element);this._treeElements=new Map();this._workspaceDiff=workspaceDiff;this._workspaceDiff.modifiedUISourceCodes().forEach(this._addUISourceCode.bind(this));this._workspaceDiff.addEventListener(WorkspaceDiff.Events.ModifiedStatusChanged,this._uiSourceCodeMofiedStatusChanged,this);}
selectUISourceCode(uiSourceCode,omitFocus){const treeElement=this._treeElements.get(uiSourceCode);if(!treeElement)
return;treeElement.select(omitFocus);}
selectedUISourceCode(){return this._treeoutline.selectedTreeElement?this._treeoutline.selectedTreeElement.uiSourceCode:null;}
_selectionChanged(){this.dispatchEventToListeners(Changes.ChangesSidebar.Events.SelectedUISourceCodeChanged);}
_uiSourceCodeMofiedStatusChanged(event){if(event.data.isModified)
this._addUISourceCode(event.data.uiSourceCode);else
this._removeUISourceCode(event.data.uiSourceCode);}
_removeUISourceCode(uiSourceCode){const treeElement=this._treeElements.get(uiSourceCode);this._treeElements.delete(uiSourceCode);if(this._treeoutline.selectedTreeElement===treeElement){const nextElementToSelect=treeElement.previousSibling||treeElement.nextSibling;if(nextElementToSelect){nextElementToSelect.select(true);}else{treeElement.deselect();this._selectionChanged();}}
this._treeoutline.removeChild(treeElement);treeElement.dispose();}
_addUISourceCode(uiSourceCode){const treeElement=new Changes.ChangesSidebar.UISourceCodeTreeElement(uiSourceCode);this._treeElements.set(uiSourceCode,treeElement);this._treeoutline.appendChild(treeElement);if(!this._treeoutline.selectedTreeElement)
treeElement.select(true);}};Changes.ChangesSidebar.Events={SelectedUISourceCodeChanged:Symbol('SelectedUISourceCodeChanged')};Changes.ChangesSidebar.UISourceCodeTreeElement=class extends UI.TreeElement{constructor(uiSourceCode){super();this.uiSourceCode=uiSourceCode;this.listItemElement.classList.add('navigator-'+uiSourceCode.contentType().name()+'-tree-item');let iconType='largeicon-navigator-file';if(Snippets.isSnippetsUISourceCode(this.uiSourceCode))
iconType='largeicon-navigator-snippet';const defaultIcon=UI.Icon.create(iconType,'icon');this.setLeadingIcons([defaultIcon]);this._eventListeners=[uiSourceCode.addEventListener(Workspace.UISourceCode.Events.TitleChanged,this._updateTitle,this),uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._updateTitle,this),uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._updateTitle,this)];this._updateTitle();}
_updateTitle(){let titleText=this.uiSourceCode.displayName();if(this.uiSourceCode.isDirty())
titleText='*'+titleText;this.title=titleText;let tooltip=this.uiSourceCode.url();if(this.uiSourceCode.contentType().isFromSourceMap())
tooltip=Common.UIString('%s (from source map)',this.uiSourceCode.displayName());this.tooltip=tooltip;}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);}};;Runtime.cachedResources["changes/changesView.css"]="/*\n * Copyright (c) 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n[slot=insertion-point-main]{\n flex-direction: column;\n display: flex;\n}\n\n[slot=insertion-point-sidebar] {\n overflow: auto;\n}\n\n.editor-container{\n flex: 1;\n}\n\n:focus.selected {\n background-color: var(--selection-bg-color);\n color: #FFF;\n}\n\n.CodeMirror-lines:not(:active) {\n cursor: default !important;\n}\n\n.CodeMirror-line:hover {\n cursor: default !important;\n background-color: rgba(0,0,255,0.05);\n}\n\n.CodeMirror .CodeMirror-linebackground.spacer {\n text-align: center;\n color: rgba(0, 0, 0, 0.5);\n background-color: rgba(0, 0, 255, 0.1);\n}\n\n.CodeMirror .equal > span > span {\n opacity: .5;\n}\n\n.CodeMirror .CodeMirror-selectedtext:not(.CodeMirror-persist-highlight) {\n opacity: 1.0;\n}\n\n.CodeMirror .CodeMirror-linebackground.addition, -theme-preserve {\n background-color: hsla(144, 55%, 49%, .2);\n}\n\n.CodeMirror .CodeMirror-linebackground.deletion, -theme-preserve {\n background-color: rgba(255, 0, 0, .2);\n}\n\n.CodeMirror .addition .cm-inner-diff:not(.CodeMirror-selectedtext), -theme-preserve {\n background-color: hsla(144, 55%, 49%, .3);\n}\n\n.CodeMirror .deletion .cm-inner-diff:not(.CodeMirror-selectedtext), -theme-preserve {\n background-color: rgba(255, 0, 0, .3);\n}\n\n.changes-toolbar {\n background-color: var(--toolbar-bg-color);\n border-top: var(--divider-border);\n}\n\n/*# sourceURL=changes/changesView.css */";Runtime.cachedResources["changes/changesSidebar.css"]="li .icon {\n margin: -3px -5px -3px -5px;\n background: linear-gradient(45deg, hsl(0, 0%, 50%), hsl(0, 0%, 70%));\n}\n\n.tree-outline li {\n min-height: 20px;\n}\n\n.tree-outline li:hover:not(.selected) .selection {\n display: block;\n background-color: rgba(56, 121, 217, 0.1);\n}\n\n.navigator-fs-tree-item .icon{\n background: linear-gradient(45deg, hsl(28, 75%, 50%), hsl(28, 75%, 70%));\n}\n\n.navigator-sm-script-tree-item .icon,\n.navigator-script-tree-item .icon,\n.navigator-snippet-tree-item .icon {\n background: linear-gradient(45deg, hsl(48, 70%, 50%), hsl(48, 70%, 70%));\n}\n\n.navigator-sm-stylesheet-tree-item .icon,\n.navigator-stylesheet-tree-item .icon {\n background: linear-gradient(45deg, hsl(256, 50%, 50%), hsl(256, 50%, 70%));\n}\n\n.navigator-image-tree-item .icon,\n.navigator-font-tree-item .icon {\n background: linear-gradient(45deg, hsl(109, 33%, 50%), hsl(109, 33%, 70%));\n}\n/*# sourceURL=changes/changesSidebar.css */";ProtocolMonitor.ProtocolMonitor=class extends UI.VBox{constructor(){super(true);this._nodes=[];this._started=false;this._startTime=0;this._nodeForId={};this._filter=node=>true;this._columns=[{id:'method',title:ls`Method`,visible:true,sortable:true,weight:60},{id:'direction',title:ls`Direction`,visible:false,sortable:true,hideable:true,weight:30},{id:'request',title:ls`Request`,visible:true,hideable:true,weight:60},{id:'response',title:ls`Response`,visible:true,hideable:true,weight:60},{id:'timestamp',title:ls`Timestamp`,visible:false,sortable:true,hideable:true,weight:30}];this.registerRequiredCSS('protocol_monitor/protocolMonitor.css');const topToolbar=new UI.Toolbar('protocol-monitor-toolbar',this.contentElement);const recordButton=new UI.ToolbarToggle(ls`Record`,'largeicon-start-recording','largeicon-stop-recording');recordButton.addEventListener(UI.ToolbarButton.Events.Click,()=>{recordButton.setToggled(!recordButton.toggled());this._setRecording(recordButton.toggled());});recordButton.setToggleWithRedColor(true);topToolbar.appendToolbarItem(recordButton);recordButton.setToggled(true);const clearButton=new UI.ToolbarButton(ls`Clear all`,'largeicon-clear');clearButton.addEventListener(UI.ToolbarButton.Events.Click,()=>{this._dataGrid.rootNode().removeChildren();this._nodes=[];this._nodeForId={};});topToolb
continue;const data=key?node.data[key]:node.data;if(!data)
continue;const found=JSON.stringify(data).toLowerCase().indexOf(text.toLowerCase())!==-1;if(found===negative)
return false;}
return true;};this._filterNodes();});topToolbar.appendToolbarItem(this._textFilterUI);}
_filterNodes(){for(const node of this._nodes){if(this._filter(node)){if(!node.parent)
this._dataGrid.insertChild(node);}else{node.remove();}}}
_innerHeaderContextMenu(contextMenu){const columnConfigs=this._columns.filter(columnConfig=>columnConfig.hideable);for(const columnConfig of columnConfigs){contextMenu.headerSection().appendCheckboxItem(columnConfig.title,this._toggleColumnVisibility.bind(this,columnConfig),columnConfig.visible);}
contextMenu.show();}
_innerRowContextMenu(contextMenu,node){contextMenu.defaultSection().appendItem(ls`Filter`,()=>{this._textFilterUI.setValue(`method:${node.data.method}`,true);});contextMenu.defaultSection().appendItem(ls`Documentation`,()=>{const[domain,method]=node.data.method.split('.');const type=node.data.direction==='sent'?'method':'event';InspectorFrontendHost.openInNewTab(`https://chromedevtools.github.io/devtools-protocol/tot/${domain}#${type}-${method}`);});}
_toggleColumnVisibility(columnConfig){columnConfig.visible=!columnConfig.visible;this._updateColumnVisibility();}
_updateColumnVisibility(){const visibleColumns=({});for(const columnConfig of this._columns)
visibleColumns[columnConfig.id]=columnConfig.visible;this._dataGrid.setColumnsVisiblity(visibleColumns);}
_sortDataGrid(){const sortColumnId=this._dataGrid.sortColumnId();if(!sortColumnId)
return;let columnIsNumeric=true;switch(sortColumnId){case'method':case'direction':columnIsNumeric=false;break;}
const comparator=columnIsNumeric?DataGrid.SortableDataGrid.NumericComparator:DataGrid.SortableDataGrid.StringComparator;this._dataGrid.sortNodes(comparator.bind(null,sortColumnId),!this._dataGrid.isSortOrderAscending());}
wasShown(){if(this._started)
return;this._started=true;this._startTime=Date.now();this._setRecording(true);}
_setRecording(recording){if(recording){Protocol.test.onMessageSent=this._messageSent.bind(this);Protocol.test.onMessageReceived=this._messageRecieved.bind(this);}else{Protocol.test.onMessageSent=null;Protocol.test.onMessageReceived=null;}}
_messageRecieved(message){if('id'in message){const node=this._nodeForId[message.id];if(!node)
return;node.data.response=message.result||message.error;node.hasError=!!message.error;node.refresh();if(this._dataGrid.selectedNode===node)
this._infoWidget.render(node.data);return;}
const node=new ProtocolMonitor.ProtocolMonitor.ProtocolNode({method:message.method,direction:'recieved',response:message.params,timestamp:Date.now()-this._startTime,request:''});this._nodes.push(node);if(this._filter(node))
this._dataGrid.insertChild(node);}
_messageSent(message){const node=new ProtocolMonitor.ProtocolMonitor.ProtocolNode({method:message.method,direction:'sent',request:message.params,timestamp:Date.now()-this._startTime,response:'(pending)',id:message.id});this._nodeForId[message.id]=node;this._nodes.push(node);if(this._filter(node))
this._dataGrid.insertChild(node);}};ProtocolMonitor.ProtocolMonitor.ProtocolNode=class extends DataGrid.SortableDataGridNode{constructor(data){super(data);this.hasError=false;}
createCell(columnId){switch(columnId){case'response':if(!this.data[columnId]&&this.data.direction==='send'){const cell=this.createTD(columnId);cell.textContent='(pending)';return cell;}
case'request':{const cell=this.createTD(columnId);const obj=SDK.RemoteObject.fromLocalObject(this.data[columnId]);cell.textContent=obj.description.trimEnd(50);cell.classList.add('source-code');return cell;}
case'timestamp':{const cell=this.createTD(columnId);cell.textContent=ls`${this.data[columnId]} ms`;return cell;}}
return super.createCell(columnId);}
element(){const element=super.element();element.classList.toggle('protocol-message-sent',this.data.direction==='sent');element.classList.toggle('protocol-message-recieved',this.data.direction!=='sent');element.classList.toggle('error',this.hasError);return element;}};ProtocolMonitor.ProtocolMonitor.InfoWidget=class extends UI.VBox{constructor(){super();this._tabbedPane=new UI.TabbedPane();this._tabbedPane.appendTab('request','Request',new UI.Widget());this._tabbedPane.appendTab('response','Response',new UI.Widget());this._tabbedPane.show(this.contentElement);this._tabbedPane.selectTab('response');this.render(null);}
render(data){const requestEnabled=data&&data.direction==='sent';this._tabbedPane.setTabEnabled('request',!!requestEnabled);if(!data){this._tabbedPane.changeTabView('request',new UI.EmptyWidget(ls`No message selected`));this._tabbedPane.changeTabView('response',new UI.EmptyWidget(ls`No message selected`));return;}
if(!requestEnabled)
this._tabbedPane.selectTab('response');this._tabbedPane.changeTabView('request',SourceFrame.JSONView.createViewSync(data.request));this._tabbedPane.changeTabView('response',SourceFrame.JSONView.createViewSync(data.response));}};;Runtime.cachedResources["protocol_monitor/protocolMonitor.css"]=".data-grid {\n border: none;\n}\n.data-grid {\n flex: auto;\n border: none;\n}\n\n.data-grid .data {\n background-image: none;\n}\n\n.data-grid td {\n /* border-bottom: 1px solid #ccc; */\n border-left-color: #ccc;\n}\n\n.data-grid tr.selected {\n background-color: #def;\n}\n\n.data-grid th {\n border-left-color: #ccc;\n}\n\n.protocol-message-sent {\n background-color: hsl(281, 64%, 95%);\n}\n\n.protocol-monitor-toolbar {\n border-bottom:var(--divider-border);\n}\n\n.error {\n background-color: hsl(0, 100%, 97%);\n color: red;\n}\n/*# sourceURL=protocol_monitor/protocolMonitor.css */";(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global.CodeMirror=factory());}(this,(function(){'use strict';var userAgent=navigator.userAgent;var platform=navigator.platform;var gecko=/gecko\/\d/i.test(userAgent);var ie_upto10=/MSIE \d/.test(userAgent);var ie_11up=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);var edge=/Edge\/(\d+)/.exec(userAgent);var ie=ie_upto10||ie_11up||edge;var ie_version=ie&&(ie_upto10?document.documentMode||6:+(edge||ie_11up)[1]);var webkit=!edge&&/WebKit\//.test(userAgent);var qtwebkit=webkit&&/Qt\/\d+\.\d+/.test(userAgent);var chrome=!edge&&/Chrome\//.test(userAgent);var presto=/Opera\//.test(userAgent);var safari=/Apple Computer/.test(navigator.vendor);var mac_geMountainLion=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);var phantom=/PhantomJS/.test(userAgent);var ios=!edge&&/AppleWebKit/.test(userAgent)&&/Mobile\/\w+/.test(userAgent);var android=/Android/.test(userAgent);var mobile=ios||android||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);var mac=ios||/Mac/.test(platform);var chromeOS=/\bCrOS\b/.test(userAgent);var windows=/win/i.test(platform);var presto_version=presto&&userAgent.match(/Version\/(\d*\.\d*)/);if(presto_version){presto_version=Number(presto_version[1]);}
if(presto_version&&presto_version>=15){presto=false;webkit=true;}
var flipCtrlCmd=mac&&(qtwebkit||presto&&(presto_version==null||presto_version<12.11));var captureRightClick=gecko||(ie&&ie_version>=9);function classTest(cls){return new RegExp("(^|\\s)"+cls+"(?:$|\\s)\\s*")}
var rmClass=function(node,cls){var current=node.className;var match=classTest(cls).exec(current);if(match){var after=current.slice(match.index+match[0].length);node.className=current.slice(0,match.index)+(after?match[1]+after:"");}};function removeChildren(e){for(var count=e.childNodes.length;count>0;--count)
{e.removeChild(e.firstChild);}
return e}
function removeChildrenAndAdd(parent,e){return removeChildren(parent).appendChild(e)}
function elt(tag,content,className,style){var e=document.createElement(tag);if(className){e.className=className;}
if(style){e.style.cssText=style;}
if(typeof content=="string"){e.appendChild(document.createTextNode(content));}
else if(content){for(var i=0;i<content.length;++i){e.appendChild(content[i]);}}
return e}
function eltP(tag,content,className,style){var e=elt(tag,content,className,style);e.setAttribute("role","presentation");return e}
var range;if(document.createRange){range=function(node,start,end,endNode){var r=document.createRange();r.setEnd(endNode||node,end);r.setStart(node,start);return r};}
else{range=function(node,start,end){var r=document.body.createTextRange();try{r.moveToElementText(node.parentNode);}
catch(e){return r}
r.collapse(true);r.moveEnd("character",end);r.moveStart("character",start);return r};}
function contains(parent,child){if(child.nodeType==3)
{child=child.parentNode;}
if(parent.contains)
{return parent.contains(child)}
do{if(child.nodeType==11){child=child.host;}
if(child==parent){return true}}while(child=child.parentNode)}
function activeElt(){var activeElement;try{activeElement=document.activeElement;}catch(e){activeElement=document.body||null;}
while(activeElement&&activeElement.shadowRoot&&activeElement.shadowRoot.activeElement)
{activeElement=activeElement.shadowRoot.activeElement;}
return activeElement}
function addClass(node,cls){var current=node.className;if(!classTest(cls).test(current)){node.className+=(current?" ":"")+cls;}}
function joinClasses(a,b){var as=a.split(" ");for(var i=0;i<as.length;i++)
{if(as[i]&&!classTest(as[i]).test(b)){b+=" "+as[i];}}
return b}
var selectInput=function(node){node.select();};if(ios)
{selectInput=function(node){node.selectionStart=0;node.selectionEnd=node.value.length;};}
else if(ie)
{selectInput=function(node){try{node.select();}catch(_e){}};}
function bind(f){var args=Array.prototype.slice.call(arguments,1);return function(){return f.apply(null,args)}}
function copyObj(obj,target,overwrite){if(!target){target={};}
for(var prop in obj)
{if(obj.hasOwnProperty(prop)&&(overwrite!==false||!target.hasOwnProperty(prop)))
{target[prop]=obj[prop];}}
return target}
function countColumn(string,end,tabSize,startIndex,startValue){if(end==null){end=string.search(/[^\s\u00a0]/);if(end==-1){end=string.length;}}
for(var i=startIndex||0,n=startValue||0;;){var nextTab=string.indexOf("\t",i);if(nextTab<0||nextTab>=end)
{return n+(end-i)}
n+=nextTab-i;n+=tabSize-(n%tabSize);i=nextTab+1;}}
var Delayed=function(){this.id=null;};Delayed.prototype.set=function(ms,f){clearTimeout(this.id);this.id=setTimeout(f,ms);};function indexOf(array,elt){for(var i=0;i<array.length;++i)
{if(array[i]==elt){return i}}
return-1}
var scrollerGap=30;var Pass={toString:function(){return"CodeMirror.Pass"}};var sel_dontScroll={scroll:false},sel_mouse={origin:"*mouse"},sel_move={origin:"+move"};function findColumn(string,goal,tabSize){for(var pos=0,col=0;;){var nextTab=string.indexOf("\t",pos);if(nextTab==-1){nextTab=string.length;}
var skipped=nextTab-pos;if(nextTab==string.length||col+skipped>=goal)
{return pos+Math.min(skipped,goal-col)}
col+=nextTab-pos;col+=tabSize-(col%tabSize);pos=nextTab+1;if(col>=goal){return pos}}}
var spaceStrs=[""];function spaceStr(n){while(spaceStrs.length<=n)
{spaceStrs.push(lst(spaceStrs)+" ");}
return spaceStrs[n]}
function lst(arr){return arr[arr.length-1]}
function map(array,f){var out=[];for(var i=0;i<array.length;i++){out[i]=f(array[i],i);}
return out}
function insertSorted(array,value,score){var pos=0,priority=score(value);while(pos<array.length&&score(array[pos])<=priority){pos++;}
array.splice(pos,0,value);}
function nothing(){}
function createObj(base,props){var inst;if(Object.create){inst=Object.create(base);}else{nothing.prototype=base;inst=new nothing();}
if(props){copyObj(props,inst);}
return inst}
var nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;function isWordCharBasic(ch){return/\w/.test(ch)||ch>"\x80"&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch))}
function isWordChar(ch,helper){if(!helper){return isWordCharBasic(ch)}
if(helper.source.indexOf("\\w")>-1&&isWordCharBasic(ch)){return true}
return helper.test(ch)}
function isEmpty(obj){for(var n in obj){if(obj.hasOwnProperty(n)&&obj[n]){return false}}
return true}
var extendingChars=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function isExtendingChar(ch){return ch.charCodeAt(0)>=768&&extendingChars.test(ch)}
function skipExtendingChars(str,pos,dir){while((dir<0?pos>0:pos<str.length)&&isExtendingChar(str.charAt(pos))){pos+=dir;}
return pos}
function findFirst(pred,from,to){var dir=from>to?-1:1;for(;;){if(from==to){return from}
var midF=(from+to)/2,mid=dir<0?Math.ceil(midF):Math.floor(midF);if(mid==from){return pred(mid)?from:to}
if(pred(mid)){to=mid;}
else{from=mid+dir;}}}
function Display(place,doc,input){var d=this;this.input=input;d.scrollbarFiller=elt("div",null,"CodeMirror-scrollbar-filler");d.scrollbarFiller.setAttribute("cm-not-content","true");d.gutterFiller=elt("div",null,"CodeMirror-gutter-filler");d.gutterFiller.setAttribute("cm-not-content","true");d.lineDiv=eltP("div",null,"CodeMirror-code");d.selectionDiv=elt("div",null,null,"position: relative; z-index: 1");d.cursorDiv=elt("div",null,"CodeMirror-cursors");d.measure=elt("div",null,"CodeMirror-measure");d.lineMeasure=elt("div",null,"CodeMirror-measure");d.lineSpace=eltP("div",[d.measure,d.lineMeasure,d.selectionDiv,d.cursorDiv,d.lineDiv],null,"position: relative; outline: none");var lines=eltP("div",[d.lineSpace],"CodeMirror-lines");d.mover=elt("div",[lines],null,"position: relative");d.sizer=elt("div",[d.mover],"CodeMirror-sizer");d.sizerWidth=null;d.heightForcer=elt("div",null,null,"position: absolute; height: "+scrollerGap+"px; width: 1px;");d.gutters=elt("div",null,"CodeMirror-gutters");d.lineGutter=null;d.scroller=elt("div",[d.sizer,d.heightForcer,d.gutters],"CodeMirror-scroll");d.scroller.setAttribute("tabIndex","-1");d.wrapper=elt("div",[d.scrollbarFiller,d.gutterFiller,d.scroller],"CodeMirror");if(ie&&ie_version<8){d.gutters.style.zIndex=-1;d.scroller.style.paddingRight=0;}
if(!webkit&&!(gecko&&mobile)){d.scroller.draggable=true;}
if(place){if(place.appendChild){place.appendChild(d.wrapper);}
else{place(d.wrapper);}}
d.viewFrom=d.viewTo=doc.first;d.reportedViewFrom=d.reportedViewTo=doc.first;d.view=[];d.renderedView=null;d.externalMeasured=null;d.viewOffset=0;d.lastWrapHeight=d.lastWrapWidth=0;d.updateLineNumbers=null;d.nativeBarWidth=d.barHeight=d.barWidth=0;d.scrollbarsClipped=false;d.lineNumWidth=d.lineNumInnerWidth=d.lineNumChars=null;d.alignWidgets=false;d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null;d.maxLine=null;d.maxLineLength=0;d.maxLineChanged=false;d.wheelDX=d.wheelDY=d.wheelStartX=d.wheelStartY=null;d.shift=false;d.selForContextMenu=null;d.activeTouch=null;input.init(d);}
function getLine(doc,n){n-=doc.first;if(n<0||n>=doc.size){throw new Error("There is no line "+(n+doc.first)+" in the document.")}
var chunk=doc;while(!chunk.lines){for(var i=0;;++i){var child=chunk.children[i],sz=child.chunkSize();if(n<sz){chunk=child;break}
n-=sz;}}
return chunk.lines[n]}
function getBetween(doc,start,end){var out=[],n=start.line;doc.iter(start.line,end.line+1,function(line){var text=line.text;if(n==end.line){text=text.slice(0,end.ch);}
if(n==start.line){text=text.slice(start.ch);}
out.push(text);++n;});return out}
function getLines(doc,from,to){var out=[];doc.iter(from,to,function(line){out.push(line.text);});return out}
function updateLineHeight(line,height){var diff=height-line.height;if(diff){for(var n=line;n;n=n.parent){n.height+=diff;}}}
function lineNo(line){if(line.parent==null){return null}
var cur=line.parent,no=indexOf(cur.lines,line);for(var chunk=cur.parent;chunk;cur=chunk,chunk=chunk.parent){for(var i=0;;++i){if(chunk.children[i]==cur){break}
no+=chunk.children[i].chunkSize();}}
return no+cur.first}
function lineAtHeight(chunk,h){var n=chunk.first;outer:do{for(var i$1=0;i$1<chunk.children.length;++i$1){var child=chunk.children[i$1],ch=child.height;if(h<ch){chunk=child;continue outer}
h-=ch;n+=child.chunkSize();}
return n}while(!chunk.lines)
var i=0;for(;i<chunk.lines.length;++i){var line=chunk.lines[i],lh=line.height;if(h<lh){break}
h-=lh;}
return n+i}
function isLine(doc,l){return l>=doc.first&&l<doc.first+doc.size}
function lineNumberFor(options,i){return String(options.lineNumberFormatter(i+options.firstLineNumber))}
function Pos(line,ch,sticky){if(sticky===void 0)sticky=null;if(!(this instanceof Pos)){return new Pos(line,ch,sticky)}
this.line=line;this.ch=ch;this.sticky=sticky;}
function cmp(a,b){return a.line-b.line||a.ch-b.ch}
function equalCursorPos(a,b){return a.sticky==b.sticky&&cmp(a,b)==0}
function copyPos(x){return Pos(x.line,x.ch)}
function maxPos(a,b){return cmp(a,b)<0?b:a}
function minPos(a,b){return cmp(a,b)<0?a:b}
function clipLine(doc,n){return Math.max(doc.first,Math.min(n,doc.first+doc.size-1))}
function clipPos(doc,pos){if(pos.line<doc.first){return Pos(doc.first,0)}
var last=doc.first+doc.size-1;if(pos.line>last){return Pos(last,getLine(doc,last).text.length)}
return clipToLen(pos,getLine(doc,pos.line).text.length)}
function clipToLen(pos,linelen){var ch=pos.ch;if(ch==null||ch>linelen){return Pos(pos.line,linelen)}
else if(ch<0){return Pos(pos.line,0)}
else{return pos}}
function clipPosArray(doc,array){var out=[];for(var i=0;i<array.length;i++){out[i]=clipPos(doc,array[i]);}
return out}
var sawReadOnlySpans=false,sawCollapsedSpans=false;function seeReadOnlySpans(){sawReadOnlySpans=true;}
function seeCollapsedSpans(){sawCollapsedSpans=true;}
function MarkedSpan(marker,from,to){this.marker=marker;this.from=from;this.to=to;}
function getMarkedSpanFor(spans,marker){if(spans){for(var i=0;i<spans.length;++i){var span=spans[i];if(span.marker==marker){return span}}}}
function removeMarkedSpan(spans,span){var r;for(var i=0;i<spans.length;++i)
{if(spans[i]!=span){(r||(r=[])).push(spans[i]);}}
return r}
function addMarkedSpan(line,span){line.markedSpans=line.markedSpans?line.markedSpans.concat([span]):[span];span.marker.attachLine(line);}
function markedSpansBefore(old,startCh,isInsert){var nw;if(old){for(var i=0;i<old.length;++i){var span=old[i],marker=span.marker;var startsBefore=span.from==null||(marker.inclusiveLeft?span.from<=startCh:span.from<startCh);if(startsBefore||span.from==startCh&&marker.type=="bookmark"&&(!isInsert||!span.marker.insertLeft)){var endsAfter=span.to==null||(marker.inclusiveRight?span.to>=startCh:span.to>startCh);(nw||(nw=[])).push(new MarkedSpan(marker,span.from,endsAfter?null:span.to));}}}
return nw}
function markedSpansAfter(old,endCh,isInsert){var nw;if(old){for(var i=0;i<old.length;++i){var span=old[i],marker=span.marker;var endsAfter=span.to==null||(marker.inclusiveRight?span.to>=endCh:span.to>endCh);if(endsAfter||span.from==endCh&&marker.type=="bookmark"&&(!isInsert||span.marker.insertLeft)){var startsBefore=span.from==null||(marker.inclusiveLeft?span.from<=endCh:span.from<endCh);(nw||(nw=[])).push(new MarkedSpan(marker,startsBefore?null:span.from-endCh,span.to==null?null:span.to-endCh));}}}
return nw}
function stretchSpansOverChange(doc,change){if(change.full){return null}
var oldFirst=isLine(doc,change.from.line)&&getLine(doc,change.from.line).markedSpans;var oldLast=isLine(doc,change.to.line)&&getLine(doc,change.to.line).markedSpans;if(!oldFirst&&!oldLast){return null}
var startCh=change.from.ch,endCh=change.to.ch,isInsert=cmp(change.from,change.to)==0;var first=markedSpansBefore(oldFirst,startCh,isInsert);var last=markedSpansAfter(oldLast,endCh,isInsert);var sameLine=change.text.length==1,offset=lst(change.text).length+(sameLine?startCh:0);if(first){for(var i=0;i<first.length;++i){var span=first[i];if(span.to==null){var found=getMarkedSpanFor(last,span.marker);if(!found){span.to=startCh;}
else if(sameLine){span.to=found.to==null?null:found.to+offset;}}}}
if(last){for(var i$1=0;i$1<last.length;++i$1){var span$1=last[i$1];if(span$1.to!=null){span$1.to+=offset;}
if(span$1.from==null){var found$1=getMarkedSpanFor(first,span$1.marker);if(!found$1){span$1.from=offset;if(sameLine){(first||(first=[])).push(span$1);}}}else{span$1.from+=offset;if(sameLine){(first||(first=[])).push(span$1);}}}}
if(first){first=clearEmptySpans(first);}
if(last&&last!=first){last=clearEmptySpans(last);}
var newMarkers=[first];if(!sameLine){var gap=change.text.length-2,gapMarkers;if(gap>0&&first)
{for(var i$2=0;i$2<first.length;++i$2)
{if(first[i$2].to==null)
{(gapMarkers||(gapMarkers=[])).push(new MarkedSpan(first[i$2].marker,null,null));}}}
for(var i$3=0;i$3<gap;++i$3)
{newMarkers.push(gapMarkers);}
newMarkers.push(last);}
return newMarkers}
function clearEmptySpans(spans){for(var i=0;i<spans.length;++i){var span=spans[i];if(span.from!=null&&span.from==span.to&&span.marker.clearWhenEmpty!==false)
{spans.splice(i--,1);}}
if(!spans.length){return null}
return spans}
function removeReadOnlyRanges(doc,from,to){var markers=null;doc.iter(from.line,to.line+1,function(line){if(line.markedSpans){for(var i=0;i<line.markedSpans.length;++i){var mark=line.markedSpans[i].marker;if(mark.readOnly&&(!markers||indexOf(markers,mark)==-1))
{(markers||(markers=[])).push(mark);}}}});if(!markers){return null}
var parts=[{from:from,to:to}];for(var i=0;i<markers.length;++i){var mk=markers[i],m=mk.find(0);for(var j=0;j<parts.length;++j){var p=parts[j];if(cmp(p.to,m.from)<0||cmp(p.from,m.to)>0){continue}
var newParts=[j,1],dfrom=cmp(p.from,m.from),dto=cmp(p.to,m.to);if(dfrom<0||!mk.inclusiveLeft&&!dfrom)
{newParts.push({from:p.from,to:m.from});}
if(dto>0||!mk.inclusiveRight&&!dto)
{newParts.push({from:m.to,to:p.to});}
parts.splice.apply(parts,newParts);j+=newParts.length-3;}}
return parts}
function detachMarkedSpans(line){var spans=line.markedSpans;if(!spans){return}
for(var i=0;i<spans.length;++i)
{spans[i].marker.detachLine(line);}
line.markedSpans=null;}
function attachMarkedSpans(line,spans){if(!spans){return}
for(var i=0;i<spans.length;++i)
{spans[i].marker.attachLine(line);}
line.markedSpans=spans;}
function extraLeft(marker){return marker.inclusiveLeft?-1:0}
function extraRight(marker){return marker.inclusiveRight?1:0}
function compareCollapsedMarkers(a,b){var lenDiff=a.lines.length-b.lines.length;if(lenDiff!=0){return lenDiff}
var aPos=a.find(),bPos=b.find();var fromCmp=cmp(aPos.from,bPos.from)||extraLeft(a)-extraLeft(b);if(fromCmp){return-fromCmp}
var toCmp=cmp(aPos.to,bPos.to)||extraRight(a)-extraRight(b);if(toCmp){return toCmp}
return b.id-a.id}
function collapsedSpanAtSide(line,start){var sps=sawCollapsedSpans&&line.markedSpans,found;if(sps){for(var sp=(void 0),i=0;i<sps.length;++i){sp=sps[i];if(sp.marker.collapsed&&(start?sp.from:sp.to)==null&&(!found||compareCollapsedMarkers(found,sp.marker)<0))
{found=sp.marker;}}}
return found}
function collapsedSpanAtStart(line){return collapsedSpanAtSide(line,true)}
function collapsedSpanAtEnd(line){return collapsedSpanAtSide(line,false)}
function collapsedSpanAround(line,ch){var sps=sawCollapsedSpans&&line.markedSpans,found;if(sps){for(var i=0;i<sps.length;++i){var sp=sps[i];if(sp.marker.collapsed&&(sp.from==null||sp.from<ch)&&(sp.to==null||sp.to>ch)&&(!found||compareCollapsedMarkers(found,sp.marker)<0)){found=sp.marker;}}}
return found}
function conflictingCollapsedRange(doc,lineNo$$1,from,to,marker){var line=getLine(doc,lineNo$$1);var sps=sawCollapsedSpans&&line.markedSpans;if(sps){for(var i=0;i<sps.length;++i){var sp=sps[i];if(!sp.marker.collapsed){continue}
var found=sp.marker.find(0);var fromCmp=cmp(found.from,from)||extraLeft(sp.marker)-extraLeft(marker);var toCmp=cmp(found.to,to)||extraRight(sp.marker)-extraRight(marker);if(fromCmp>=0&&toCmp<=0||fromCmp<=0&&toCmp>=0){continue}
if(fromCmp<=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.to,from)>=0:cmp(found.to,from)>0)||fromCmp>=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.from,to)<=0:cmp(found.from,to)<0))
{return true}}}}
function visualLine(line){var merged;while(merged=collapsedSpanAtStart(line))
{line=merged.find(-1,true).line;}
return line}
function visualLineEnd(line){var merged;while(merged=collapsedSpanAtEnd(line))
{line=merged.find(1,true).line;}
return line}
function visualLineContinued(line){var merged,lines;while(merged=collapsedSpanAtEnd(line)){line=merged.find(1,true).line;(lines||(lines=[])).push(line);}
return lines}
function visualLineNo(doc,lineN){var line=getLine(doc,lineN),vis=visualLine(line);if(line==vis){return lineN}
return lineNo(vis)}
function visualLineEndNo(doc,lineN){if(lineN>doc.lastLine()){return lineN}
var line=getLine(doc,lineN),merged;if(!lineIsHidden(doc,line)){return lineN}
while(merged=collapsedSpanAtEnd(line))
{line=merged.find(1,true).line;}
return lineNo(line)+1}
function lineIsHidden(doc,line){var sps=sawCollapsedSpans&&line.markedSpans;if(sps){for(var sp=(void 0),i=0;i<sps.length;++i){sp=sps[i];if(!sp.marker.collapsed){continue}
if(sp.from==null){return true}
if(sp.marker.widgetNode){continue}
if(sp.from==0&&sp.marker.inclusiveLeft&&lineIsHiddenInner(doc,line,sp))
{return true}}}}
function lineIsHiddenInner(doc,line,span){if(span.to==null){var end=span.marker.find(1,true);return lineIsHiddenInner(doc,end.line,getMarkedSpanFor(end.line.markedSpans,span.marker))}
if(span.marker.inclusiveRight&&span.to==line.text.length)
{return true}
for(var sp=(void 0),i=0;i<line.markedSpans.length;++i){sp=line.markedSpans[i];if(sp.marker.collapsed&&!sp.marker.widgetNode&&sp.from==span.to&&(sp.to==null||sp.to!=span.from)&&(sp.marker.inclusiveLeft||span.marker.inclusiveRight)&&lineIsHiddenInner(doc,line,sp)){return true}}}
function heightAtLine(lineObj){lineObj=visualLine(lineObj);var h=0,chunk=lineObj.parent;for(var i=0;i<chunk.lines.length;++i){var line=chunk.lines[i];if(line==lineObj){break}
else{h+=line.height;}}
for(var p=chunk.parent;p;chunk=p,p=chunk.parent){for(var i$1=0;i$1<p.children.length;++i$1){var cur=p.children[i$1];if(cur==chunk){break}
else{h+=cur.height;}}}
return h}
function lineLength(line){if(line.height==0){return 0}
var len=line.text.length,merged,cur=line;while(merged=collapsedSpanAtStart(cur)){var found=merged.find(0,true);cur=found.from.line;len+=found.from.ch-found.to.ch;}
cur=line;while(merged=collapsedSpanAtEnd(cur)){var found$1=merged.find(0,true);len-=cur.text.length-found$1.from.ch;cur=found$1.to.line;len+=cur.text.length-found$1.to.ch;}
return len}
function findMaxLine(cm){var d=cm.display,doc=cm.doc;d.maxLine=getLine(doc,doc.first);d.maxLineLength=lineLength(d.maxLine);d.maxLineChanged=true;doc.iter(function(line){var len=lineLength(line);if(len>d.maxLineLength){d.maxLineLength=len;d.maxLine=line;}});}
function iterateBidiSections(order,from,to,f){if(!order){return f(from,to,"ltr",0)}
var found=false;for(var i=0;i<order.length;++i){var part=order[i];if(part.from<to&&part.to>from||from==to&&part.to==from){f(Math.max(part.from,from),Math.min(part.to,to),part.level==1?"rtl":"ltr",i);found=true;}}
if(!found){f(from,to,"ltr");}}
var bidiOther=null;function getBidiPartAt(order,ch,sticky){var found;bidiOther=null;for(var i=0;i<order.length;++i){var cur=order[i];if(cur.from<ch&&cur.to>ch){return i}
if(cur.to==ch){if(cur.from!=cur.to&&sticky=="before"){found=i;}
else{bidiOther=i;}}
if(cur.from==ch){if(cur.from!=cur.to&&sticky!="before"){found=i;}
else{bidiOther=i;}}}
return found!=null?found:bidiOther}
var bidiOrdering=(function(){var lowTypes="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";var arabicTypes="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";function charType(code){if(code<=0xf7){return lowTypes.charAt(code)}
else if(0x590<=code&&code<=0x5f4){return"R"}
else if(0x600<=code&&code<=0x6f9){return arabicTypes.charAt(code-0x600)}
else if(0x6ee<=code&&code<=0x8ac){return"r"}
else if(0x2000<=code&&code<=0x200b){return"w"}
else if(code==0x200c){return"b"}
else{return"L"}}
var bidiRE=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;var isNeutral=/[stwN]/,isStrong=/[LRr]/,countsAsLeft=/[Lb1n]/,countsAsNum=/[1n]/;function BidiSpan(level,from,to){this.level=level;this.from=from;this.to=to;}
return function(str,direction){var outerType=direction=="ltr"?"L":"R";if(str.length==0||direction=="ltr"&&!bidiRE.test(str)){return false}
var len=str.length,types=[];for(var i=0;i<len;++i)
{types.push(charType(str.charCodeAt(i)));}
for(var i$1=0,prev=outerType;i$1<len;++i$1){var type=types[i$1];if(type=="m"){types[i$1]=prev;}
else{prev=type;}}
for(var i$2=0,cur=outerType;i$2<len;++i$2){var type$1=types[i$2];if(type$1=="1"&&cur=="r"){types[i$2]="n";}
else if(isStrong.test(type$1)){cur=type$1;if(type$1=="r"){types[i$2]="R";}}}
for(var i$3=1,prev$1=types[0];i$3<len-1;++i$3){var type$2=types[i$3];if(type$2=="+"&&prev$1=="1"&&types[i$3+1]=="1"){types[i$3]="1";}
else if(type$2==","&&prev$1==types[i$3+1]&&(prev$1=="1"||prev$1=="n")){types[i$3]=prev$1;}
prev$1=type$2;}
for(var i$4=0;i$4<len;++i$4){var type$3=types[i$4];if(type$3==","){types[i$4]="N";}
else if(type$3=="%"){var end=(void 0);for(end=i$4+1;end<len&&types[end]=="%";++end){}
var replace=(i$4&&types[i$4-1]=="!")||(end<len&&types[end]=="1")?"1":"N";for(var j=i$4;j<end;++j){types[j]=replace;}
i$4=end-1;}}
for(var i$5=0,cur$1=outerType;i$5<len;++i$5){var type$4=types[i$5];if(cur$1=="L"&&type$4=="1"){types[i$5]="L";}
else if(isStrong.test(type$4)){cur$1=type$4;}}
for(var i$6=0;i$6<len;++i$6){if(isNeutral.test(types[i$6])){var end$1=(void 0);for(end$1=i$6+1;end$1<len&&isNeutral.test(types[end$1]);++end$1){}
var before=(i$6?types[i$6-1]:outerType)=="L";var after=(end$1<len?types[end$1]:outerType)=="L";var replace$1=before==after?(before?"L":"R"):outerType;for(var j$1=i$6;j$1<end$1;++j$1){types[j$1]=replace$1;}
i$6=end$1-1;}}
var order=[],m;for(var i$7=0;i$7<len;){if(countsAsLeft.test(types[i$7])){var start=i$7;for(++i$7;i$7<len&&countsAsLeft.test(types[i$7]);++i$7){}
order.push(new BidiSpan(0,start,i$7));}else{var pos=i$7,at=order.length;for(++i$7;i$7<len&&types[i$7]!="L";++i$7){}
for(var j$2=pos;j$2<i$7;){if(countsAsNum.test(types[j$2])){if(pos<j$2){order.splice(at,0,new BidiSpan(1,pos,j$2));}
var nstart=j$2;for(++j$2;j$2<i$7&&countsAsNum.test(types[j$2]);++j$2){}
order.splice(at,0,new BidiSpan(2,nstart,j$2));pos=j$2;}else{++j$2;}}
if(pos<i$7){order.splice(at,0,new BidiSpan(1,pos,i$7));}}}
if(direction=="ltr"){if(order[0].level==1&&(m=str.match(/^\s+/))){order[0].from=m[0].length;order.unshift(new BidiSpan(0,0,m[0].length));}
if(lst(order).level==1&&(m=str.match(/\s+$/))){lst(order).to-=m[0].length;order.push(new BidiSpan(0,len-m[0].length,len));}}
return direction=="rtl"?order.reverse():order}})();function getOrder(line,direction){var order=line.order;if(order==null){order=line.order=bidiOrdering(line.text,direction);}
return order}
var noHandlers=[];var on=function(emitter,type,f){if(emitter.addEventListener){emitter.addEventListener(type,f,false);}else if(emitter.attachEvent){emitter.attachEvent("on"+type,f);}else{var map$$1=emitter._handlers||(emitter._handlers={});map$$1[type]=(map$$1[type]||noHandlers).concat(f);}};function getHandlers(emitter,type){return emitter._handlers&&emitter._handlers[type]||noHandlers}
function off(emitter,type,f){if(emitter.removeEventListener){emitter.removeEventListener(type,f,false);}else if(emitter.detachEvent){emitter.detachEvent("on"+type,f);}else{var map$$1=emitter._handlers,arr=map$$1&&map$$1[type];if(arr){var index=indexOf(arr,f);if(index>-1)
{map$$1[type]=arr.slice(0,index).concat(arr.slice(index+1));}}}}
function signal(emitter,type){var handlers=getHandlers(emitter,type);if(!handlers.length){return}
var args=Array.prototype.slice.call(arguments,2);for(var i=0;i<handlers.length;++i){handlers[i].apply(null,args);}}
function signalDOMEvent(cm,e,override){if(typeof e=="string")
{e={type:e,preventDefault:function(){this.defaultPrevented=true;}};}
signal(cm,override||e.type,cm,e);return e_defaultPrevented(e)||e.codemirrorIgnore}
function signalCursorActivity(cm){var arr=cm._handlers&&cm._handlers.cursorActivity;if(!arr){return}
var set=cm.curOp.cursorActivityHandlers||(cm.curOp.cursorActivityHandlers=[]);for(var i=0;i<arr.length;++i){if(indexOf(set,arr[i])==-1)
{set.push(arr[i]);}}}
function hasHandler(emitter,type){return getHandlers(emitter,type).length>0}
function eventMixin(ctor){ctor.prototype.on=function(type,f){on(this,type,f);};ctor.prototype.off=function(type,f){off(this,type,f);};}
function e_preventDefault(e){if(e.preventDefault){e.preventDefault();}
else{e.returnValue=false;}}
function e_stopPropagation(e){if(e.stopPropagation){e.stopPropagation();}
else{e.cancelBubble=true;}}
function e_defaultPrevented(e){return e.defaultPrevented!=null?e.defaultPrevented:e.returnValue==false}
function e_stop(e){e_preventDefault(e);e_stopPropagation(e);}
function e_target(e){return e.target||e.srcElement}
function e_button(e){var b=e.which;if(b==null){if(e.button&1){b=1;}
else if(e.button&2){b=3;}
else if(e.button&4){b=2;}}
if(mac&&e.ctrlKey&&b==1){b=3;}
return b}
var dragAndDrop=function(){if(ie&&ie_version<9){return false}
var div=elt('div');return"draggable"in div||"dragDrop"in div}();var zwspSupported;function zeroWidthElement(measure){if(zwspSupported==null){var test=elt("span","\u200b");removeChildrenAndAdd(measure,elt("span",[test,document.createTextNode("x")]));if(measure.firstChild.offsetHeight!=0)
{zwspSupported=test.offsetWidth<=1&&test.offsetHeight>2&&!(ie&&ie_version<8);}}
var node=zwspSupported?elt("span","\u200b"):elt("span","\u00a0",null,"display: inline-block; width: 1px; margin-right: -1px");node.setAttribute("cm-text","");return node}
var badBidiRects;function hasBadBidiRects(measure){if(badBidiRects!=null){return badBidiRects}
var txt=removeChildrenAndAdd(measure,document.createTextNode("A\u062eA"));var r0=range(txt,0,1).getBoundingClientRect();var r1=range(txt,1,2).getBoundingClientRect();removeChildren(measure);if(!r0||r0.left==r0.right){return false}
return badBidiRects=(r1.right-r0.right<3)}
var splitLinesAuto="\n\nb".split(/\n/).length!=3?function(string){var pos=0,result=[],l=string.length;while(pos<=l){var nl=string.indexOf("\n",pos);if(nl==-1){nl=string.length;}
var line=string.slice(pos,string.charAt(nl-1)=="\r"?nl-1:nl);var rt=line.indexOf("\r");if(rt!=-1){result.push(line.slice(0,rt));pos+=rt+1;}else{result.push(line);pos=nl+1;}}
return result}:function(string){return string.split(/\r\n?|\n/);};var hasSelection=window.getSelection?function(te){try{return te.selectionStart!=te.selectionEnd}
catch(e){return false}}:function(te){var range$$1;try{range$$1=te.ownerDocument.selection.createRange();}
catch(e){}
if(!range$$1||range$$1.parentElement()!=te){return false}
return range$$1.compareEndPoints("StartToEnd",range$$1)!=0};var hasCopyEvent=(function(){var e=elt("div");if("oncopy"in e){return true}
e.setAttribute("oncopy","return;");return typeof e.oncopy=="function"})();var badZoomedRects=null;function hasBadZoomedRects(measure){if(badZoomedRects!=null){return badZoomedRects}
var node=removeChildrenAndAdd(measure,elt("span","x"));var normal=node.getBoundingClientRect();var fromRange=range(node,0,1).getBoundingClientRect();return badZoomedRects=Math.abs(normal.left-fromRange.left)>1}
var modes={},mimeModes={};function defineMode(name,mode){if(arguments.length>2)
{mode.dependencies=Array.prototype.slice.call(arguments,2);}
modes[name]=mode;}
function defineMIME(mime,spec){mimeModes[mime]=spec;}
function resolveMode(spec){if(typeof spec=="string"&&mimeModes.hasOwnProperty(spec)){spec=mimeModes[spec];}else if(spec&&typeof spec.name=="string"&&mimeModes.hasOwnProperty(spec.name)){var found=mimeModes[spec.name];if(typeof found=="string"){found={name:found};}
spec=createObj(found,spec);spec.name=found.name;}else if(typeof spec=="string"&&/^[\w\-]+\/[\w\-]+\+xml$/.test(spec)){return resolveMode("application/xml")}else if(typeof spec=="string"&&/^[\w\-]+\/[\w\-]+\+json$/.test(spec)){return resolveMode("application/json")}
if(typeof spec=="string"){return{name:spec}}
else{return spec||{name:"null"}}}
function getMode(options,spec){spec=resolveMode(spec);var mfactory=modes[spec.name];if(!mfactory){return getMode(options,"text/plain")}
var modeObj=mfactory(options,spec);if(modeExtensions.hasOwnProperty(spec.name)){var exts=modeExtensions[spec.name];for(var prop in exts){if(!exts.hasOwnProperty(prop)){continue}
if(modeObj.hasOwnProperty(prop)){modeObj["_"+prop]=modeObj[prop];}
modeObj[prop]=exts[prop];}}
modeObj.name=spec.name;if(spec.helperType){modeObj.helperType=spec.helperType;}
if(spec.modeProps){for(var prop$1 in spec.modeProps)
{modeObj[prop$1]=spec.modeProps[prop$1];}}
return modeObj}
var modeExtensions={};function extendMode(mode,properties){var exts=modeExtensions.hasOwnProperty(mode)?modeExtensions[mode]:(modeExtensions[mode]={});copyObj(properties,exts);}
function copyState(mode,state){if(state===true){return state}
if(mode.copyState){return mode.copyState(state)}
var nstate={};for(var n in state){var val=state[n];if(val instanceof Array){val=val.concat([]);}
nstate[n]=val;}
return nstate}
function innerMode(mode,state){var info;while(mode.innerMode){info=mode.innerMode(state);if(!info||info.mode==mode){break}
state=info.state;mode=info.mode;}
return info||{mode:mode,state:state}}
function startState(mode,a1,a2){return mode.startState?mode.startState(a1,a2):true}
var StringStream=function(string,tabSize,lineOracle){this.pos=this.start=0;this.string=string;this.tabSize=tabSize||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0;this.lineOracle=lineOracle;};StringStream.prototype.eol=function(){return this.pos>=this.string.length};StringStream.prototype.sol=function(){return this.pos==this.lineStart};StringStream.prototype.peek=function(){return this.string.charAt(this.pos)||undefined};StringStream.prototype.next=function(){if(this.pos<this.string.length)
{return this.string.charAt(this.pos++)}};StringStream.prototype.eat=function(match){var ch=this.string.charAt(this.pos);var ok;if(typeof match=="string"){ok=ch==match;}
else{ok=ch&&(match.test?match.test(ch):match(ch));}
if(ok){++this.pos;return ch}};StringStream.prototype.eatWhile=function(match){var start=this.pos;while(this.eat(match)){}
return this.pos>start};StringStream.prototype.eatSpace=function(){var start=this.pos;while(/[\s\u00a0]/.test(this.string.charAt(this.pos))){++this.pos;}
return this.pos>start};StringStream.prototype.skipToEnd=function(){this.pos=this.string.length;};StringStream.prototype.skipTo=function(ch){var found=this.string.indexOf(ch,this.pos);if(found>-1){this.pos=found;return true}};StringStream.prototype.backUp=function(n){this.pos-=n;};StringStream.prototype.column=function(){if(this.lastColumnPos<this.start){this.lastColumnValue=countColumn(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start;}
return this.lastColumnValue-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)};StringStream.prototype.indentation=function(){return countColumn(this.string,null,this.tabSize)-
(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)};StringStream.prototype.match=function(pattern,consume,caseInsensitive){if(typeof pattern=="string"){var cased=function(str){return caseInsensitive?str.toLowerCase():str;};var substr=this.string.substr(this.pos,pattern.length);if(cased(substr)==cased(pattern)){if(consume!==false){this.pos+=pattern.length;}
return true}}else{var match=this.string.slice(this.pos).match(pattern);if(match&&match.index>0){return null}
if(match&&consume!==false){this.pos+=match[0].length;}
return match}};StringStream.prototype.current=function(){return this.string.slice(this.start,this.pos)};StringStream.prototype.hideFirstChars=function(n,inner){this.lineStart+=n;try{return inner()}
finally{this.lineStart-=n;}};StringStream.prototype.lookAhead=function(n){var oracle=this.lineOracle;return oracle&&oracle.lookAhead(n)};StringStream.prototype.baseToken=function(){var oracle=this.lineOracle;return oracle&&oracle.baseToken(this.pos)};var SavedContext=function(state,lookAhead){this.state=state;this.lookAhead=lookAhead;};var Context=function(doc,state,line,lookAhead){this.state=state;this.doc=doc;this.line=line;this.maxLookAhead=lookAhead||0;this.baseTokens=null;this.baseTokenPos=1;};Context.prototype.lookAhead=function(n){var line=this.doc.getLine(this.line+n);if(line!=null&&n>this.maxLookAhead){this.maxLookAhead=n;}
return line};Context.prototype.baseToken=function(n){if(!this.baseTokens){return null}
while(this.baseTokens[this.baseTokenPos]<=n)
{this.baseTokenPos+=2;}
var type=this.baseTokens[this.baseTokenPos+1];return{type:type&&type.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-n}};Context.prototype.nextLine=function(){this.line++;if(this.maxLookAhead>0){this.maxLookAhead--;}};Context.fromSaved=function(doc,saved,line){if(saved instanceof SavedContext)
{return new Context(doc,copyState(doc.mode,saved.state),line,saved.lookAhead)}
else
{return new Context(doc,copyState(doc.mode,saved),line)}};Context.prototype.save=function(copy){var state=copy!==false?copyState(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new SavedContext(state,this.maxLookAhead):state};function highlightLine(cm,line,context,forceToEnd){var st=[cm.state.modeGen],lineClasses={};runMode(cm,line.text,cm.doc.mode,context,function(end,style){return st.push(end,style);},lineClasses,forceToEnd);var state=context.state;var loop=function(o){context.baseTokens=st;var overlay=cm.state.overlays[o],i=1,at=0;context.state=true;runMode(cm,line.text,overlay.mode,context,function(end,style){var start=i;while(at<end){var i_end=st[i];if(i_end>end)
{st.splice(i,1,end,st[i+1],i_end);}
i+=2;at=Math.min(end,i_end);}
if(!style){return}
if(overlay.opaque){st.splice(start,i-start,end,"overlay "+style);i=start+2;}else{for(;start<i;start+=2){var cur=st[start+1];st[start+1]=(cur?cur+" ":"")+"overlay "+style;}}},lineClasses);context.state=state;context.baseTokens=null;context.baseTokenPos=1;};for(var o=0;o<cm.state.overlays.length;++o)loop(o);return{styles:st,classes:lineClasses.bgClass||lineClasses.textClass?lineClasses:null}}
function getLineStyles(cm,line,updateFrontier){if(!line.styles||line.styles[0]!=cm.state.modeGen){var context=getContextBefore(cm,lineNo(line));var resetState=line.text.length>cm.options.maxHighlightLength&&copyState(cm.doc.mode,context.state);var result=highlightLine(cm,line,context);if(resetState){context.state=resetState;}
line.stateAfter=context.save(!resetState);line.styles=result.styles;if(result.classes){line.styleClasses=result.classes;}
else if(line.styleClasses){line.styleClasses=null;}
if(updateFrontier===cm.doc.highlightFrontier)
{cm.doc.modeFrontier=Math.max(cm.doc.modeFrontier,++cm.doc.highlightFrontier);}}
return line.styles}
function getContextBefore(cm,n,precise){var doc=cm.doc,display=cm.display;if(!doc.mode.startState){return new Context(doc,true,n)}
var start=findStartLine(cm,n,precise);var saved=start>doc.first&&getLine(doc,start-1).stateAfter;var context=saved?Context.fromSaved(doc,saved,start):new Context(doc,startState(doc.mode),start);doc.iter(start,n,function(line){processLine(cm,line.text,context);var pos=context.line;line.stateAfter=pos==n-1||pos%5==0||pos>=display.viewFrom&&pos<display.viewTo?context.save():null;context.nextLine();});if(precise){doc.modeFrontier=context.line;}
return context}
function processLine(cm,text,context,startAt){var mode=cm.doc.mode;var stream=new StringStream(text,cm.options.tabSize,context);stream.start=stream.pos=startAt||0;if(text==""){callBlankLine(mode,context.state);}
while(!stream.eol()){readToken(mode,stream,context.state);stream.start=stream.pos;}}
function callBlankLine(mode,state){if(mode.blankLine){return mode.blankLine(state)}
if(!mode.innerMode){return}
var inner=innerMode(mode,state);if(inner.mode.blankLine){return inner.mode.blankLine(inner.state)}}
function readToken(mode,stream,state,inner){for(var i=0;i<10;i++){if(inner){inner[0]=innerMode(mode,state).mode;}
var style=mode.token(stream,state);if(stream.pos>stream.start){return style}}
throw new Error("Mode "+mode.name+" failed to advance stream.")}
var Token=function(stream,type,state){this.start=stream.start;this.end=stream.pos;this.string=stream.current();this.type=type||null;this.state=state;};function takeToken(cm,pos,precise,asArray){var doc=cm.doc,mode=doc.mode,style;pos=clipPos(doc,pos);var line=getLine(doc,pos.line),context=getContextBefore(cm,pos.line,precise);var stream=new StringStream(line.text,cm.options.tabSize,context),tokens;if(asArray){tokens=[];}
while((asArray||stream.pos<pos.ch)&&!stream.eol()){stream.start=stream.pos;style=readToken(mode,stream,context.state);if(asArray){tokens.push(new Token(stream,style,copyState(doc.mode,context.state)));}}
return asArray?tokens:new Token(stream,style,context.state)}
function extractLineClasses(type,output){if(type){for(;;){var lineClass=type.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!lineClass){break}
type=type.slice(0,lineClass.index)+type.slice(lineClass.index+lineClass[0].length);var prop=lineClass[1]?"bgClass":"textClass";if(output[prop]==null)
{output[prop]=lineClass[2];}
else if(!(new RegExp("(?:^|\s)"+lineClass[2]+"(?:$|\s)")).test(output[prop]))
{output[prop]+=" "+lineClass[2];}}}
return type}
function runMode(cm,text,mode,context,f,lineClasses,forceToEnd){var flattenSpans=mode.flattenSpans;if(flattenSpans==null){flattenSpans=cm.options.flattenSpans;}
var curStart=0,curStyle=null;var stream=new StringStream(text,cm.options.tabSize,context),style;var inner=cm.options.addModeClass&&[null];if(text==""){extractLineClasses(callBlankLine(mode,context.state),lineClasses);}
while(!stream.eol()){if(stream.pos>cm.options.maxHighlightLength){flattenSpans=false;if(forceToEnd){processLine(cm,text,context,stream.pos);}
stream.pos=text.length;style=null;}else{style=extractLineClasses(readToken(mode,stream,context.state,inner),lineClasses);}
if(inner){var mName=inner[0].name;if(mName){style="m-"+(style?mName+" "+style:mName);}}
if(!flattenSpans||curStyle!=style){while(curStart<stream.start){curStart=Math.min(stream.start,curStart+5000);f(curStart,curStyle);}
curStyle=style;}
stream.start=stream.pos;}
while(curStart<stream.pos){var pos=Math.min(stream.pos,curStart+5000);f(pos,curStyle);curStart=pos;}}
function findStartLine(cm,n,precise){var minindent,minline,doc=cm.doc;var lim=precise?-1:n-(cm.doc.mode.innerMode?1000:100);for(var search=n;search>lim;--search){if(search<=doc.first){return doc.first}
var line=getLine(doc,search-1),after=line.stateAfter;if(after&&(!precise||search+(after instanceof SavedContext?after.lookAhead:0)<=doc.modeFrontier))
{return search}
var indented=countColumn(line.text,null,cm.options.tabSize);if(minline==null||minindent>indented){minline=search-1;minindent=indented;}}
return minline}
function retreatFrontier(doc,n){doc.modeFrontier=Math.min(doc.modeFrontier,n);if(doc.highlightFrontier<n-10){return}
var start=doc.first;for(var line=n-1;line>start;line--){var saved=getLine(doc,line).stateAfter;if(saved&&(!(saved instanceof SavedContext)||line+saved.lookAhead<n)){start=line+1;break}}
doc.highlightFrontier=Math.min(doc.highlightFrontier,start);}
var Line=function(text,markedSpans,estimateHeight){this.text=text;attachMarkedSpans(this,markedSpans);this.height=estimateHeight?estimateHeight(this):1;};Line.prototype.lineNo=function(){return lineNo(this)};eventMixin(Line);function updateLine(line,text,markedSpans,estimateHeight){line.text=text;if(line.stateAfter){line.stateAfter=null;}
if(line.styles){line.styles=null;}
if(line.order!=null){line.order=null;}
detachMarkedSpans(line);attachMarkedSpans(line,markedSpans);var estHeight=estimateHeight?estimateHeight(line):1;if(estHeight!=line.height){updateLineHeight(line,estHeight);}}
function cleanUpLine(line){line.parent=null;detachMarkedSpans(line);}
var styleToClassCache={},styleToClassCacheWithMode={};function interpretTokenStyle(style,options){if(!style||/^\s*$/.test(style)){return null}
var cache=options.addModeClass?styleToClassCacheWithMode:styleToClassCache;return cache[style]||(cache[style]=style.replace(/\S+/g,"cm-$&"))}
function buildLineContent(cm,lineView){var content=eltP("span",null,null,webkit?"padding-right: .1px":null);var builder={pre:eltP("pre",[content],"CodeMirror-line"),content:content,col:0,pos:0,cm:cm,trailingSpace:false,splitSpaces:cm.getOption("lineWrapping")};lineView.measure={};for(var i=0;i<=(lineView.rest?lineView.rest.length:0);i++){var line=i?lineView.rest[i-1]:lineView.line,order=(void 0);builder.pos=0;builder.addToken=buildToken;if(hasBadBidiRects(cm.display.measure)&&(order=getOrder(line,cm.doc.direction)))
{builder.addToken=buildTokenBadBidi(builder.addToken,order);}
builder.map=[];var allowFrontierUpdate=lineView!=cm.display.externalMeasured&&lineNo(line);insertLineContent(line,builder,getLineStyles(cm,line,allowFrontierUpdate));if(line.styleClasses){if(line.styleClasses.bgClass)
{builder.bgClass=joinClasses(line.styleClasses.bgClass,builder.bgClass||"");}
if(line.styleClasses.textClass)
{builder.textClass=joinClasses(line.styleClasses.textClass,builder.textClass||"");}}
if(builder.map.length==0)
{builder.map.push(0,0,builder.content.appendChild(zeroWidthElement(cm.display.measure)));}
if(i==0){lineView.measure.map=builder.map;lineView.measure.cache={};}else{(lineView.measure.maps||(lineView.measure.maps=[])).push(builder.map);(lineView.measure.caches||(lineView.measure.caches=[])).push({});}}
if(webkit){var last=builder.content.lastChild;if(/\bcm-tab\b/.test(last.className)||(last.querySelector&&last.querySelector(".cm-tab")))
{builder.content.className="cm-tab-wrap-hack";}}
signal(cm,"renderLine",cm,lineView.line,builder.pre);if(builder.pre.className)
{builder.textClass=joinClasses(builder.pre.className,builder.textClass||"");}
return builder}
function defaultSpecialCharPlaceholder(ch){var token=elt("span","\u2022","cm-invalidchar");token.title="\\u"+ch.charCodeAt(0).toString(16);token.setAttribute("aria-label",token.title);return token}
function buildToken(builder,text,style,startStyle,endStyle,css,attributes){if(!text){return}
var displayText=builder.splitSpaces?splitSpaces(text,builder.trailingSpace):text;var special=builder.cm.state.specialChars,mustWrap=false;var content;if(!special.test(text)){builder.col+=text.length;content=document.createTextNode(displayText);builder.map.push(builder.pos,builder.pos+text.length,content);if(ie&&ie_version<9){mustWrap=true;}
builder.pos+=text.length;}else{content=document.createDocumentFragment();var pos=0;while(true){special.lastIndex=pos;var m=special.exec(text);var skipped=m?m.index-pos:text.length-pos;if(skipped){var txt=document.createTextNode(displayText.slice(pos,pos+skipped));if(ie&&ie_version<9){content.appendChild(elt("span",[txt]));}
else{content.appendChild(txt);}
builder.map.push(builder.pos,builder.pos+skipped,txt);builder.col+=skipped;builder.pos+=skipped;}
if(!m){break}
pos+=skipped+1;var txt$1=(void 0);if(m[0]=="\t"){var tabSize=builder.cm.options.tabSize,tabWidth=tabSize-builder.col%tabSize;txt$1=content.appendChild(elt("span",spaceStr(tabWidth),"cm-tab"));txt$1.setAttribute("role","presentation");txt$1.setAttribute("cm-text","\t");builder.col+=tabWidth;}else if(m[0]=="\r"||m[0]=="\n"){txt$1=content.appendChild(elt("span",m[0]=="\r"?"\u240d":"\u2424","cm-invalidchar"));txt$1.setAttribute("cm-text",m[0]);builder.col+=1;}else{txt$1=builder.cm.options.specialCharPlaceholder(m[0]);txt$1.setAttribute("cm-text",m[0]);if(ie&&ie_version<9){content.appendChild(elt("span",[txt$1]));}
else{content.appendChild(txt$1);}
builder.col+=1;}
builder.map.push(builder.pos,builder.pos+1,txt$1);builder.pos++;}}
builder.trailingSpace=displayText.charCodeAt(text.length-1)==32;if(style||startStyle||endStyle||mustWrap||css){var fullStyle=style||"";if(startStyle){fullStyle+=startStyle;}
if(endStyle){fullStyle+=endStyle;}
var token=elt("span",[content],fullStyle,css);if(attributes){for(var attr in attributes){if(attributes.hasOwnProperty(attr)&&attr!="style"&&attr!="class")
{token.setAttribute(attr,attributes[attr]);}}}
return builder.content.appendChild(token)}
builder.content.appendChild(content);}
function splitSpaces(text,trailingBefore){if(text.length>1&&!/ /.test(text)){return text}
var spaceBefore=trailingBefore,result="";for(var i=0;i<text.length;i++){var ch=text.charAt(i);if(ch==" "&&spaceBefore&&(i==text.length-1||text.charCodeAt(i+1)==32))
{ch="\u00a0";}
result+=ch;spaceBefore=ch==" ";}
return result}
function buildTokenBadBidi(inner,order){return function(builder,text,style,startStyle,endStyle,css,attributes){style=style?style+" cm-force-border":"cm-force-border";var start=builder.pos,end=start+text.length;for(;;){var part=(void 0);for(var i=0;i<order.length;i++){part=order[i];if(part.to>start&&part.from<=start){break}}
if(part.to>=end){return inner(builder,text,style,startStyle,endStyle,css,attributes)}
inner(builder,text.slice(0,part.to-start),style,startStyle,null,css,attributes);startStyle=null;text=text.slice(part.to-start);start=part.to;}}}
function buildCollapsedSpan(builder,size,marker,ignoreWidget){var widget=!ignoreWidget&&marker.widgetNode;if(widget){builder.map.push(builder.pos,builder.pos+size,widget);}
if(!ignoreWidget&&builder.cm.display.input.needsContentAttribute){if(!widget)
{widget=builder.content.appendChild(document.createElement("span"));}
widget.setAttribute("cm-marker",marker.id);}
if(widget){builder.cm.display.input.setUneditable(widget);builder.content.appendChild(widget);}
builder.pos+=size;builder.trailingSpace=false;}
function insertLineContent(line,builder,styles){var spans=line.markedSpans,allText=line.text,at=0;if(!spans){for(var i$1=1;i$1<styles.length;i$1+=2)
{builder.addToken(builder,allText.slice(at,at=styles[i$1]),interpretTokenStyle(styles[i$1+1],builder.cm.options));}
return}
var len=allText.length,pos=0,i=1,text="",style,css;var nextChange=0,spanStyle,spanEndStyle,spanStartStyle,collapsed,attributes;for(;;){if(nextChange==pos){spanStyle=spanEndStyle=spanStartStyle=css="";attributes=null;collapsed=null;nextChange=Infinity;var foundBookmarks=[],endStyles=(void 0);for(var j=0;j<spans.length;++j){var sp=spans[j],m=sp.marker;if(m.type=="bookmark"&&sp.from==pos&&m.widgetNode){foundBookmarks.push(m);}else if(sp.from<=pos&&(sp.to==null||sp.to>pos||m.collapsed&&sp.to==pos&&sp.from==pos)){if(sp.to!=null&&sp.to!=pos&&nextChange>sp.to){nextChange=sp.to;spanEndStyle="";}
if(m.className){spanStyle+=" "+m.className;}
if(m.css){css=(css?css+";":"")+m.css;}
if(m.startStyle&&sp.from==pos){spanStartStyle+=" "+m.startStyle;}
if(m.endStyle&&sp.to==nextChange){(endStyles||(endStyles=[])).push(m.endStyle,sp.to);}
if(m.title){(attributes||(attributes={})).title=m.title;}
if(m.attributes){for(var attr in m.attributes)
{(attributes||(attributes={}))[attr]=m.attributes[attr];}}
if(m.collapsed&&(!collapsed||compareCollapsedMarkers(collapsed.marker,m)<0))
{collapsed=sp;}}else if(sp.from>pos&&nextChange>sp.from){nextChange=sp.from;}}
if(endStyles){for(var j$1=0;j$1<endStyles.length;j$1+=2)
{if(endStyles[j$1+1]==nextChange){spanEndStyle+=" "+endStyles[j$1];}}}
if(!collapsed||collapsed.from==pos){for(var j$2=0;j$2<foundBookmarks.length;++j$2)
{buildCollapsedSpan(builder,0,foundBookmarks[j$2]);}}
if(collapsed&&(collapsed.from||0)==pos){buildCollapsedSpan(builder,(collapsed.to==null?len+1:collapsed.to)-pos,collapsed.marker,collapsed.from==null);if(collapsed.to==null){return}
if(collapsed.to==pos){collapsed=false;}}}
if(pos>=len){break}
var upto=Math.min(len,nextChange);while(true){if(text){var end=pos+text.length;if(!collapsed){var tokenText=end>upto?text.slice(0,upto-pos):text;builder.addToken(builder,tokenText,style?style+spanStyle:spanStyle,spanStartStyle,pos+tokenText.length==nextChange?spanEndStyle:"",css,attributes);}
if(end>=upto){text=text.slice(upto-pos);pos=upto;break}
pos=end;spanStartStyle="";}
text=allText.slice(at,at=styles[i++]);style=interpretTokenStyle(styles[i++],builder.cm.options);}}}
function LineView(doc,line,lineN){this.line=line;this.rest=visualLineContinued(line);this.size=this.rest?lineNo(lst(this.rest))-lineN+1:1;this.node=this.text=null;this.hidden=lineIsHidden(doc,line);}
function buildViewArray(cm,from,to){var array=[],nextPos;for(var pos=from;pos<to;pos=nextPos){var view=new LineView(cm.doc,getLine(cm.doc,pos),pos);nextPos=pos+view.size;array.push(view);}
return array}
var operationGroup=null;function pushOperation(op){if(operationGroup){operationGroup.ops.push(op);}else{op.ownsGroup=operationGroup={ops:[op],delayedCallbacks:[]};}}
function fireCallbacksForOps(group){var callbacks=group.delayedCallbacks,i=0;do{for(;i<callbacks.length;i++)
{callbacks[i].call(null);}
for(var j=0;j<group.ops.length;j++){var op=group.ops[j];if(op.cursorActivityHandlers)
{while(op.cursorActivityCalled<op.cursorActivityHandlers.length)
{op.cursorActivityHandlers[op.cursorActivityCalled++].call(null,op.cm);}}}}while(i<callbacks.length)}
function finishOperation(op,endCb){var group=op.ownsGroup;if(!group){return}
try{fireCallbacksForOps(group);}
finally{operationGroup=null;endCb(group);}}
var orphanDelayedCallbacks=null;function signalLater(emitter,type){var arr=getHandlers(emitter,type);if(!arr.length){return}
var args=Array.prototype.slice.call(arguments,2),list;if(operationGroup){list=operationGroup.delayedCallbacks;}else if(orphanDelayedCallbacks){list=orphanDelayedCallbacks;}else{list=orphanDelayedCallbacks=[];setTimeout(fireOrphanDelayed,0);}
var loop=function(i){list.push(function(){return arr[i].apply(null,args);});};for(var i=0;i<arr.length;++i)
loop(i);}
function fireOrphanDelayed(){var delayed=orphanDelayedCallbacks;orphanDelayedCallbacks=null;for(var i=0;i<delayed.length;++i){delayed[i]();}}
function updateLineForChanges(cm,lineView,lineN,dims){for(var j=0;j<lineView.changes.length;j++){var type=lineView.changes[j];if(type=="text"){updateLineText(cm,lineView);}
else if(type=="gutter"){updateLineGutter(cm,lineView,lineN,dims);}
else if(type=="class"){updateLineClasses(cm,lineView);}
else if(type=="widget"){updateLineWidgets(cm,lineView,dims);}}
lineView.changes=null;}
function ensureLineWrapped(lineView){if(lineView.node==lineView.text){lineView.node=elt("div",null,null,"position: relative");if(lineView.text.parentNode)
{lineView.text.parentNode.replaceChild(lineView.node,lineView.text);}
lineView.node.appendChild(lineView.text);if(ie&&ie_version<8){lineView.node.style.zIndex=2;}}
return lineView.node}
function updateLineBackground(cm,lineView){var cls=lineView.bgClass?lineView.bgClass+" "+(lineView.line.bgClass||""):lineView.line.bgClass;if(cls){cls+=" CodeMirror-linebackground";}
if(lineView.background){if(cls){lineView.background.className=cls;}
else{lineView.background.parentNode.removeChild(lineView.background);lineView.background=null;}}else if(cls){var wrap=ensureLineWrapped(lineView);lineView.background=wrap.insertBefore(elt("div",null,cls),wrap.firstChild);cm.display.input.setUneditable(lineView.background);}}
function getLineContent(cm,lineView){var ext=cm.display.externalMeasured;if(ext&&ext.line==lineView.line){cm.display.externalMeasured=null;lineView.measure=ext.measure;return ext.built}
return buildLineContent(cm,lineView)}
function updateLineText(cm,lineView){var cls=lineView.text.className;var built=getLineContent(cm,lineView);if(lineView.text==lineView.node){lineView.node=built.pre;}
lineView.text.parentNode.replaceChild(built.pre,lineView.text);lineView.text=built.pre;if(built.bgClass!=lineView.bgClass||built.textClass!=lineView.textClass){lineView.bgClass=built.bgClass;lineView.textClass=built.textClass;updateLineClasses(cm,lineView);}else if(cls){lineView.text.className=cls;}}
function updateLineClasses(cm,lineView){updateLineBackground(cm,lineView);if(lineView.line.wrapClass)
{ensureLineWrapped(lineView).className=lineView.line.wrapClass;}
else if(lineView.node!=lineView.text)
{lineView.node.className="";}
var textClass=lineView.textClass?lineView.textClass+" "+(lineView.line.textClass||""):lineView.line.textClass;lineView.text.className=textClass||"";}
function updateLineGutter(cm,lineView,lineN,dims){if(lineView.gutter){lineView.node.removeChild(lineView.gutter);lineView.gutter=null;}
if(lineView.gutterBackground){lineView.node.removeChild(lineView.gutterBackground);lineView.gutterBackground=null;}
if(lineView.line.gutterClass){var wrap=ensureLineWrapped(lineView);lineView.gutterBackground=elt("div",null,"CodeMirror-gutter-background "+lineView.line.gutterClass,("left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px; width: "+(dims.gutterTotalWidth)+"px"));cm.display.input.setUneditable(lineView.gutterBackground);wrap.insertBefore(lineView.gutterBackground,lineView.text);}
var markers=lineView.line.gutterMarkers;if(cm.options.lineNumbers||markers){var wrap$1=ensureLineWrapped(lineView);var gutterWrap=lineView.gutter=elt("div",null,"CodeMirror-gutter-wrapper",("left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px"));cm.display.input.setUneditable(gutterWrap);wrap$1.insertBefore(gutterWrap,lineView.text);if(lineView.line.gutterClass)
{gutterWrap.className+=" "+lineView.line.gutterClass;}
if(cm.options.lineNumbers&&(!markers||!markers["CodeMirror-linenumbers"]))
{lineView.lineNumber=gutterWrap.appendChild(elt("div",lineNumberFor(cm.options,lineN),"CodeMirror-linenumber CodeMirror-gutter-elt",("left: "+(dims.gutterLeft["CodeMirror-linenumbers"])+"px; width: "+(cm.display.lineNumInnerWidth)+"px")));}
if(markers){for(var k=0;k<cm.options.gutters.length;++k){var id=cm.options.gutters[k],found=markers.hasOwnProperty(id)&&markers[id];if(found)
{gutterWrap.appendChild(elt("div",[found],"CodeMirror-gutter-elt",("left: "+(dims.gutterLeft[id])+"px; width: "+(dims.gutterWidth[id])+"px")));}}}}}
function updateLineWidgets(cm,lineView,dims){if(lineView.alignable){lineView.alignable=null;}
for(var node=lineView.node.firstChild,next=(void 0);node;node=next){next=node.nextSibling;if(node.className=="CodeMirror-linewidget")
{lineView.node.removeChild(node);}}
insertLineWidgets(cm,lineView,dims);}
function buildLineElement(cm,lineView,lineN,dims){var built=getLineContent(cm,lineView);lineView.text=lineView.node=built.pre;if(built.bgClass){lineView.bgClass=built.bgClass;}
if(built.textClass){lineView.textClass=built.textClass;}
updateLineClasses(cm,lineView);updateLineGutter(cm,lineView,lineN,dims);insertLineWidgets(cm,lineView,dims);return lineView.node}
function insertLineWidgets(cm,lineView,dims){insertLineWidgetsFor(cm,lineView.line,lineView,dims,true);if(lineView.rest){for(var i=0;i<lineView.rest.length;i++)
{insertLineWidgetsFor(cm,lineView.rest[i],lineView,dims,false);}}}
function insertLineWidgetsFor(cm,line,lineView,dims,allowAbove){if(!line.widgets){return}
var wrap=ensureLineWrapped(lineView);for(var i=0,ws=line.widgets;i<ws.length;++i){var widget=ws[i],node=elt("div",[widget.node],"CodeMirror-linewidget");if(!widget.handleMouseEvents){node.setAttribute("cm-ignore-events","true");}
positionLineWidget(widget,node,lineView,dims);cm.display.input.setUneditable(node);if(allowAbove&&widget.above)
{wrap.insertBefore(node,lineView.gutter||lineView.text);}
else
{wrap.appendChild(node);}
signalLater(widget,"redraw");}}
function positionLineWidget(widget,node,lineView,dims){if(widget.noHScroll){(lineView.alignable||(lineView.alignable=[])).push(node);var width=dims.wrapperWidth;node.style.left=dims.fixedPos+"px";if(!widget.coverGutter){width-=dims.gutterTotalWidth;node.style.paddingLeft=dims.gutterTotalWidth+"px";}
node.style.width=width+"px";}
if(widget.coverGutter){node.style.zIndex=5;node.style.position="relative";if(!widget.noHScroll){node.style.marginLeft=-dims.gutterTotalWidth+"px";}}}
function widgetHeight(widget){if(widget.height!=null){return widget.height}
var cm=widget.doc.cm;if(!cm){return 0}
if(!contains(document.body,widget.node)){var parentStyle="position: relative;";if(widget.coverGutter)
{parentStyle+="margin-left: -"+cm.display.gutters.offsetWidth+"px;";}
if(widget.noHScroll)
{parentStyle+="width: "+cm.display.wrapper.clientWidth+"px;";}
removeChildrenAndAdd(cm.display.measure,elt("div",[widget.node],null,parentStyle));}
return widget.height=widget.node.parentNode.offsetHeight}
function eventInWidget(display,e){for(var n=e_target(e);n!=display.wrapper;n=n.parentNode){if(!n||(n.nodeType==1&&n.getAttribute("cm-ignore-events")=="true")||(n.parentNode==display.sizer&&n!=display.mover))
{return true}}}
function paddingTop(display){return display.lineSpace.offsetTop}
function paddingVert(display){return display.mover.offsetHeight-display.lineSpace.offsetHeight}
function paddingH(display){if(display.cachedPaddingH){return display.cachedPaddingH}
var e=removeChildrenAndAdd(display.measure,elt("pre","x"));var style=window.getComputedStyle?window.getComputedStyle(e):e.currentStyle;var data={left:parseInt(style.paddingLeft),right:parseInt(style.paddingRight)};if(!isNaN(data.left)&&!isNaN(data.right)){display.cachedPaddingH=data;}
return data}
function scrollGap(cm){return scrollerGap-cm.display.nativeBarWidth}
function displayWidth(cm){return cm.display.scroller.clientWidth-scrollGap(cm)-cm.display.barWidth}
function displayHeight(cm){return cm.display.scroller.clientHeight-scrollGap(cm)-cm.display.barHeight}
function ensureLineHeights(cm,lineView,rect){var wrapping=cm.options.lineWrapping;var curWidth=wrapping&&displayWidth(cm);if(!lineView.measure.heights||wrapping&&lineView.measure.width!=curWidth){var heights=lineView.measure.heights=[];if(wrapping){lineView.measure.width=curWidth;var rects=lineView.text.firstChild.getClientRects();for(var i=0;i<rects.length-1;i++){var cur=rects[i],next=rects[i+1];if(Math.abs(cur.bottom-next.bottom)>2)
{heights.push((cur.bottom+next.top)/2-rect.top);}}}
heights.push(rect.bottom-rect.top);}}
function mapFromLineView(lineView,line,lineN){if(lineView.line==line)
{return{map:lineView.measure.map,cache:lineView.measure.cache}}
for(var i=0;i<lineView.rest.length;i++)
{if(lineView.rest[i]==line)
{return{map:lineView.measure.maps[i],cache:lineView.measure.caches[i]}}}
for(var i$1=0;i$1<lineView.rest.length;i$1++)
{if(lineNo(lineView.rest[i$1])>lineN)
{return{map:lineView.measure.maps[i$1],cache:lineView.measure.caches[i$1],before:true}}}}
function updateExternalMeasurement(cm,line){line=visualLine(line);var lineN=lineNo(line);var view=cm.display.externalMeasured=new LineView(cm.doc,line,lineN);view.lineN=lineN;var built=view.built=buildLineContent(cm,view);view.text=built.pre;removeChildrenAndAdd(cm.display.lineMeasure,built.pre);return view}
function measureChar(cm,line,ch,bias){return measureCharPrepared(cm,prepareMeasureForLine(cm,line),ch,bias)}
function findViewForLine(cm,lineN){if(lineN>=cm.display.viewFrom&&lineN<cm.display.viewTo)
{return cm.display.view[findViewIndex(cm,lineN)]}
var ext=cm.display.externalMeasured;if(ext&&lineN>=ext.lineN&&lineN<ext.lineN+ext.size)
{return ext}}
function prepareMeasureForLine(cm,line){var lineN=lineNo(line);var view=findViewForLine(cm,lineN);if(view&&!view.text){view=null;}else if(view&&view.changes){updateLineForChanges(cm,view,lineN,getDimensions(cm));cm.curOp.forceUpdate=true;}
if(!view)
{view=updateExternalMeasurement(cm,line);}
var info=mapFromLineView(view,line,lineN);return{line:line,view:view,rect:null,map:info.map,cache:info.cache,before:info.before,hasHeights:false}}
function measureCharPrepared(cm,prepared,ch,bias,varHeight){if(prepared.before){ch=-1;}
var key=ch+(bias||""),found;if(prepared.cache.hasOwnProperty(key)){found=prepared.cache[key];}else{if(!prepared.rect)
{prepared.rect=prepared.view.text.getBoundingClientRect();}
if(!prepared.hasHeights){ensureLineHeights(cm,prepared.view,prepared.rect);prepared.hasHeights=true;}
found=measureCharInner(cm,prepared,ch,bias);if(!found.bogus){prepared.cache[key]=found;}}
return{left:found.left,right:found.right,top:varHeight?found.rtop:found.top,bottom:varHeight?found.rbottom:found.bottom}}
var nullRect={left:0,right:0,top:0,bottom:0};function nodeAndOffsetInLineMap(map$$1,ch,bias){var node,start,end,collapse,mStart,mEnd;for(var i=0;i<map$$1.length;i+=3){mStart=map$$1[i];mEnd=map$$1[i+1];if(ch<mStart){start=0;end=1;collapse="left";}else if(ch<mEnd){start=ch-mStart;end=start+1;}else if(i==map$$1.length-3||ch==mEnd&&map$$1[i+3]>ch){end=mEnd-mStart;start=end-1;if(ch>=mEnd){collapse="right";}}
if(start!=null){node=map$$1[i+2];if(mStart==mEnd&&bias==(node.insertLeft?"left":"right"))
{collapse=bias;}
if(bias=="left"&&start==0)
{while(i&&map$$1[i-2]==map$$1[i-3]&&map$$1[i-1].insertLeft){node=map$$1[(i-=3)+2];collapse="left";}}
if(bias=="right"&&start==mEnd-mStart)
{while(i<map$$1.length-3&&map$$1[i+3]==map$$1[i+4]&&!map$$1[i+5].insertLeft){node=map$$1[(i+=3)+2];collapse="right";}}
break}}
return{node:node,start:start,end:end,collapse:collapse,coverStart:mStart,coverEnd:mEnd}}
function getUsefulRect(rects,bias){var rect=nullRect;if(bias=="left"){for(var i=0;i<rects.length;i++){if((rect=rects[i]).left!=rect.right){break}}}else{for(var i$1=rects.length-1;i$1>=0;i$1--){if((rect=rects[i$1]).left!=rect.right){break}}}
return rect}
function measureCharInner(cm,prepared,ch,bias){var place=nodeAndOffsetInLineMap(prepared.map,ch,bias);var node=place.node,start=place.start,end=place.end,collapse=place.collapse;var rect;if(node.nodeType==3){for(var i$1=0;i$1<4;i$1++){while(start&&isExtendingChar(prepared.line.text.charAt(place.coverStart+start))){--start;}
while(place.coverStart+end<place.coverEnd&&isExtendingChar(prepared.line.text.charAt(place.coverStart+end))){++end;}
if(ie&&ie_version<9&&start==0&&end==place.coverEnd-place.coverStart)
{rect=node.parentNode.getBoundingClientRect();}
else
{rect=getUsefulRect(range(node,start,end).getClientRects(),bias);}
if(rect.left||rect.right||start==0){break}
end=start;start=start-1;collapse="right";}
if(ie&&ie_version<11){rect=maybeUpdateRectForZooming(cm.display.measure,rect);}}else{if(start>0){collapse=bias="right";}
var rects;if(cm.options.lineWrapping&&(rects=node.getClientRects()).length>1)
{rect=rects[bias=="right"?rects.length-1:0];}
else
{rect=node.getBoundingClientRect();}}
if(ie&&ie_version<9&&!start&&(!rect||!rect.left&&!rect.right)){var rSpan=node.parentNode.getClientRects()[0];if(rSpan)
{rect={left:rSpan.left,right:rSpan.left+charWidth(cm.display),top:rSpan.top,bottom:rSpan.bottom};}
else
{rect=nullRect;}}
var rtop=rect.top-prepared.rect.top,rbot=rect.bottom-prepared.rect.top;var mid=(rtop+rbot)/2;var heights=prepared.view.measure.heights;var i=0;for(;i<heights.length-1;i++)
{if(mid<heights[i]){break}}
var top=i?heights[i-1]:0,bot=heights[i];var result={left:(collapse=="right"?rect.right:rect.left)-prepared.rect.left,right:(collapse=="left"?rect.left:rect.right)-prepared.rect.left,top:top,bottom:bot};if(!rect.left&&!rect.right){result.bogus=true;}
if(!cm.options.singleCursorHeightPerLine){result.rtop=rtop;result.rbottom=rbot;}
return result}
function maybeUpdateRectForZooming(measure,rect){if(!window.screen||screen.logicalXDPI==null||screen.logicalXDPI==screen.deviceXDPI||!hasBadZoomedRects(measure))
{return rect}
var scaleX=screen.logicalXDPI/screen.deviceXDPI;var scaleY=screen.logicalYDPI/screen.deviceYDPI;return{left:rect.left*scaleX,right:rect.right*scaleX,top:rect.top*scaleY,bottom:rect.bottom*scaleY}}
function clearLineMeasurementCacheFor(lineView){if(lineView.measure){lineView.measure.cache={};lineView.measure.heights=null;if(lineView.rest){for(var i=0;i<lineView.rest.length;i++)
{lineView.measure.caches[i]={};}}}}
function clearLineMeasurementCache(cm){cm.display.externalMeasure=null;removeChildren(cm.display.lineMeasure);for(var i=0;i<cm.display.view.length;i++)
{clearLineMeasurementCacheFor(cm.display.view[i]);}}
function clearCaches(cm){clearLineMeasurementCache(cm);cm.display.cachedCharWidth=cm.display.cachedTextHeight=cm.display.cachedPaddingH=null;if(!cm.options.lineWrapping){cm.display.maxLineChanged=true;}
cm.display.lineNumChars=null;}
function pageScrollX(){if(chrome&&android){return-(document.body.getBoundingClientRect().left-parseInt(getComputedStyle(document.body).marginLeft))}
return window.pageXOffset||(document.documentElement||document.body).scrollLeft}
function pageScrollY(){if(chrome&&android){return-(document.body.getBoundingClientRect().top-parseInt(getComputedStyle(document.body).marginTop))}
return window.pageYOffset||(document.documentElement||document.body).scrollTop}
function widgetTopHeight(lineObj){var height=0;if(lineObj.widgets){for(var i=0;i<lineObj.widgets.length;++i){if(lineObj.widgets[i].above)
{height+=widgetHeight(lineObj.widgets[i]);}}}
return height}
function intoCoordSystem(cm,lineObj,rect,context,includeWidgets){if(!includeWidgets){var height=widgetTopHeight(lineObj);rect.top+=height;rect.bottom+=height;}
if(context=="line"){return rect}
if(!context){context="local";}
var yOff=heightAtLine(lineObj);if(context=="local"){yOff+=paddingTop(cm.display);}
else{yOff-=cm.display.viewOffset;}
if(context=="page"||context=="window"){var lOff=cm.display.lineSpace.getBoundingClientRect();yOff+=lOff.top+(context=="window"?0:pageScrollY());var xOff=lOff.left+(context=="window"?0:pageScrollX());rect.left+=xOff;rect.right+=xOff;}
rect.top+=yOff;rect.bottom+=yOff;return rect}
function fromCoordSystem(cm,coords,context){if(context=="div"){return coords}
var left=coords.left,top=coords.top;if(context=="page"){left-=pageScrollX();top-=pageScrollY();}else if(context=="local"||!context){var localBox=cm.display.sizer.getBoundingClientRect();left+=localBox.left;top+=localBox.top;}
var lineSpaceBox=cm.display.lineSpace.getBoundingClientRect();return{left:left-lineSpaceBox.left,top:top-lineSpaceBox.top}}
function charCoords(cm,pos,context,lineObj,bias){if(!lineObj){lineObj=getLine(cm.doc,pos.line);}
return intoCoordSystem(cm,lineObj,measureChar(cm,lineObj,pos.ch,bias),context)}
function cursorCoords(cm,pos,context,lineObj,preparedMeasure,varHeight){lineObj=lineObj||getLine(cm.doc,pos.line);if(!preparedMeasure){preparedMeasure=prepareMeasureForLine(cm,lineObj);}
function get(ch,right){var m=measureCharPrepared(cm,preparedMeasure,ch,right?"right":"left",varHeight);if(right){m.left=m.right;}else{m.right=m.left;}
return intoCoordSystem(cm,lineObj,m,context)}
var order=getOrder(lineObj,cm.doc.direction),ch=pos.ch,sticky=pos.sticky;if(ch>=lineObj.text.length){ch=lineObj.text.length;sticky="before";}else if(ch<=0){ch=0;sticky="after";}
if(!order){return get(sticky=="before"?ch-1:ch,sticky=="before")}
function getBidi(ch,partPos,invert){var part=order[partPos],right=part.level==1;return get(invert?ch-1:ch,right!=invert)}
var partPos=getBidiPartAt(order,ch,sticky);var other=bidiOther;var val=getBidi(ch,partPos,sticky=="before");if(other!=null){val.other=getBidi(ch,other,sticky!="before");}
return val}
function estimateCoords(cm,pos){var left=0;pos=clipPos(cm.doc,pos);if(!cm.options.lineWrapping){left=charWidth(cm.display)*pos.ch;}
var lineObj=getLine(cm.doc,pos.line);var top=heightAtLine(lineObj)+paddingTop(cm.display);return{left:left,right:left,top:top,bottom:top+lineObj.height}}
function PosWithInfo(line,ch,sticky,outside,xRel){var pos=Pos(line,ch,sticky);pos.xRel=xRel;if(outside){pos.outside=true;}
return pos}
function coordsChar(cm,x,y){var doc=cm.doc;y+=cm.display.viewOffset;if(y<0){return PosWithInfo(doc.first,0,null,true,-1)}
var lineN=lineAtHeight(doc,y),last=doc.first+doc.size-1;if(lineN>last)
{return PosWithInfo(doc.first+doc.size-1,getLine(doc,last).text.length,null,true,1)}
if(x<0){x=0;}
var lineObj=getLine(doc,lineN);for(;;){var found=coordsCharInner(cm,lineObj,lineN,x,y);var collapsed=collapsedSpanAround(lineObj,found.ch+(found.xRel>0?1:0));if(!collapsed){return found}
var rangeEnd=collapsed.find(1);if(rangeEnd.line==lineN){return rangeEnd}
lineObj=getLine(doc,lineN=rangeEnd.line);}}
function wrappedLineExtent(cm,lineObj,preparedMeasure,y){y-=widgetTopHeight(lineObj);var end=lineObj.text.length;var begin=findFirst(function(ch){return measureCharPrepared(cm,preparedMeasure,ch-1).bottom<=y;},end,0);end=findFirst(function(ch){return measureCharPrepared(cm,preparedMeasure,ch).top>y;},begin,end);return{begin:begin,end:end}}
function wrappedLineExtentChar(cm,lineObj,preparedMeasure,target){if(!preparedMeasure){preparedMeasure=prepareMeasureForLine(cm,lineObj);}
var targetTop=intoCoordSystem(cm,lineObj,measureCharPrepared(cm,preparedMeasure,target),"line").top;return wrappedLineExtent(cm,lineObj,preparedMeasure,targetTop)}
function boxIsAfter(box,x,y,left){return box.bottom<=y?false:box.top>y?true:(left?box.left:box.right)>x}
function coordsCharInner(cm,lineObj,lineNo$$1,x,y){y-=heightAtLine(lineObj);var preparedMeasure=prepareMeasureForLine(cm,lineObj);var widgetHeight$$1=widgetTopHeight(lineObj);var begin=0,end=lineObj.text.length,ltr=true;var order=getOrder(lineObj,cm.doc.direction);if(order){var part=(cm.options.lineWrapping?coordsBidiPartWrapped:coordsBidiPart)
(cm,lineObj,lineNo$$1,preparedMeasure,order,x,y);ltr=part.level!=1;begin=ltr?part.from:part.to-1;end=ltr?part.to:part.from-1;}
var chAround=null,boxAround=null;var ch=findFirst(function(ch){var box=measureCharPrepared(cm,preparedMeasure,ch);box.top+=widgetHeight$$1;box.bottom+=widgetHeight$$1;if(!boxIsAfter(box,x,y,false)){return false}
if(box.top<=y&&box.left<=x){chAround=ch;boxAround=box;}
return true},begin,end);var baseX,sticky,outside=false;if(boxAround){var atLeft=x-boxAround.left<boxAround.right-x,atStart=atLeft==ltr;ch=chAround+(atStart?0:1);sticky=atStart?"after":"before";baseX=atLeft?boxAround.left:boxAround.right;}else{if(!ltr&&(ch==end||ch==begin)){ch++;}
sticky=ch==0?"after":ch==lineObj.text.length?"before":(measureCharPrepared(cm,preparedMeasure,ch-(ltr?1:0)).bottom+widgetHeight$$1<=y)==ltr?"after":"before";var coords=cursorCoords(cm,Pos(lineNo$$1,ch,sticky),"line",lineObj,preparedMeasure);baseX=coords.left;outside=y<coords.top||y>=coords.bottom;}
ch=skipExtendingChars(lineObj.text,ch,1);return PosWithInfo(lineNo$$1,ch,sticky,outside,x-baseX)}
function coordsBidiPart(cm,lineObj,lineNo$$1,preparedMeasure,order,x,y){var index=findFirst(function(i){var part=order[i],ltr=part.level!=1;return boxIsAfter(cursorCoords(cm,Pos(lineNo$$1,ltr?part.to:part.from,ltr?"before":"after"),"line",lineObj,preparedMeasure),x,y,true)},0,order.length-1);var part=order[index];if(index>0){var ltr=part.level!=1;var start=cursorCoords(cm,Pos(lineNo$$1,ltr?part.from:part.to,ltr?"after":"before"),"line",lineObj,preparedMeasure);if(boxIsAfter(start,x,y,true)&&start.top>y)
{part=order[index-1];}}
return part}
function coordsBidiPartWrapped(cm,lineObj,_lineNo,preparedMeasure,order,x,y){var ref=wrappedLineExtent(cm,lineObj,preparedMeasure,y);var begin=ref.begin;var end=ref.end;if(/\s/.test(lineObj.text.charAt(end-1))){end--;}
var part=null,closestDist=null;for(var i=0;i<order.length;i++){var p=order[i];if(p.from>=end||p.to<=begin){continue}
var ltr=p.level!=1;var endX=measureCharPrepared(cm,preparedMeasure,ltr?Math.min(end,p.to)-1:Math.max(begin,p.from)).right;var dist=endX<x?x-endX+1e9:endX-x;if(!part||closestDist>dist){part=p;closestDist=dist;}}
if(!part){part=order[order.length-1];}
if(part.from<begin){part={from:begin,to:part.to,level:part.level};}
if(part.to>end){part={from:part.from,to:end,level:part.level};}
return part}
var measureText;function textHeight(display){if(display.cachedTextHeight!=null){return display.cachedTextHeight}
if(measureText==null){measureText=elt("pre");for(var i=0;i<49;++i){measureText.appendChild(document.createTextNode("x"));measureText.appendChild(elt("br"));}
measureText.appendChild(document.createTextNode("x"));}
removeChildrenAndAdd(display.measure,measureText);var height=measureText.offsetHeight/50;if(height>3){display.cachedTextHeight=height;}
removeChildren(display.measure);return height||1}
function charWidth(display){if(display.cachedCharWidth!=null){return display.cachedCharWidth}
var anchor=elt("span","xxxxxxxxxx");var pre=elt("pre",[anchor]);removeChildrenAndAdd(display.measure,pre);var rect=anchor.getBoundingClientRect(),width=(rect.right-rect.left)/10;if(width>2){display.cachedCharWidth=width;}
return width||10}
function getDimensions(cm){var d=cm.display,left={},width={};var gutterLeft=d.gutters.clientLeft;for(var n=d.gutters.firstChild,i=0;n;n=n.nextSibling,++i){left[cm.options.gutters[i]]=n.offsetLeft+n.clientLeft+gutterLeft;width[cm.options.gutters[i]]=n.clientWidth;}
return{fixedPos:compensateForHScroll(d),gutterTotalWidth:d.gutters.offsetWidth,gutterLeft:left,gutterWidth:width,wrapperWidth:d.wrapper.clientWidth}}
function compensateForHScroll(display){return display.scroller.getBoundingClientRect().left-display.sizer.getBoundingClientRect().left}
function estimateHeight(cm){var th=textHeight(cm.display),wrapping=cm.options.lineWrapping;var perLine=wrapping&&Math.max(5,cm.display.scroller.clientWidth/charWidth(cm.display)-3);return function(line){if(lineIsHidden(cm.doc,line)){return 0}
var widgetsHeight=0;if(line.widgets){for(var i=0;i<line.widgets.length;i++){if(line.widgets[i].height){widgetsHeight+=line.widgets[i].height;}}}
if(wrapping)
{return widgetsHeight+(Math.ceil(line.text.length/perLine)||1)*th}
else
{return widgetsHeight+th}}}
function estimateLineHeights(cm){var doc=cm.doc,est=estimateHeight(cm);doc.iter(function(line){var estHeight=est(line);if(estHeight!=line.height){updateLineHeight(line,estHeight);}});}
function posFromMouse(cm,e,liberal,forRect){var display=cm.display;if(!liberal&&e_target(e).getAttribute("cm-not-content")=="true"){return null}
var x,y,space=display.lineSpace.getBoundingClientRect();try{x=e.clientX-space.left;y=e.clientY-space.top;}
catch(e){return null}
var coords=coordsChar(cm,x,y),line;if(forRect&&coords.xRel==1&&(line=getLine(cm.doc,coords.line).text).length==coords.ch){var colDiff=countColumn(line,line.length,cm.options.tabSize)-line.length;coords=Pos(coords.line,Math.max(0,Math.round((x-paddingH(cm.display).left)/charWidth(cm.display))-colDiff));}
return coords}
function findViewIndex(cm,n){if(n>=cm.display.viewTo){return null}
n-=cm.display.viewFrom;if(n<0){return null}
var view=cm.display.view;for(var i=0;i<view.length;i++){n-=view[i].size;if(n<0){return i}}}
function updateSelection(cm){cm.display.input.showSelection(cm.display.input.prepareSelection());}
function prepareSelection(cm,primary){if(primary===void 0)primary=true;var doc=cm.doc,result={};var curFragment=result.cursors=document.createDocumentFragment();var selFragment=result.selection=document.createDocumentFragment();for(var i=0;i<doc.sel.ranges.length;i++){if(!primary&&i==doc.sel.primIndex){continue}
var range$$1=doc.sel.ranges[i];if(range$$1.from().line>=cm.display.viewTo||range$$1.to().line<cm.display.viewFrom){continue}
var collapsed=range$$1.empty();if(collapsed||cm.options.showCursorWhenSelecting)
{drawSelectionCursor(cm,range$$1.head,curFragment);}
if(!collapsed)
{drawSelectionRange(cm,range$$1,selFragment);}}
return result}
function drawSelectionCursor(cm,head,output){var pos=cursorCoords(cm,head,"div",null,null,!cm.options.singleCursorHeightPerLine);var cursor=output.appendChild(elt("div","\u00a0","CodeMirror-cursor"));cursor.style.left=pos.left+"px";cursor.style.top=pos.top+"px";cursor.style.height=Math.max(0,pos.bottom-pos.top)*cm.options.cursorHeight+"px";if(pos.other){var otherCursor=output.appendChild(elt("div","\u00a0","CodeMirror-cursor CodeMirror-secondarycursor"));otherCursor.style.display="";otherCursor.style.left=pos.other.left+"px";otherCursor.style.top=pos.other.top+"px";otherCursor.style.height=(pos.other.bottom-pos.other.top)*.85+"px";}}
function cmpCoords(a,b){return a.top-b.top||a.left-b.left}
function drawSelectionRange(cm,range$$1,output){var display=cm.display,doc=cm.doc;var fragment=document.createDocumentFragment();var padding=paddingH(cm.display),leftSide=padding.left;var rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right;var docLTR=doc.direction=="ltr";function add(left,top,width,bottom){if(top<0){top=0;}
top=Math.round(top);bottom=Math.round(bottom);fragment.appendChild(elt("div",null,"CodeMirror-selected",("position: absolute; left: "+left+"px;\n top: "+top+"px; width: "+(width==null?rightSide-left:width)+"px;\n height: "+(bottom-top)+"px")));}
function drawForLine(line,fromArg,toArg){var lineObj=getLine(doc,line);var lineLen=lineObj.text.length;var start,end;function coords(ch,bias){return charCoords(cm,Pos(line,ch),"div",lineObj,bias)}
function wrapX(pos,dir,side){var extent=wrappedLineExtentChar(cm,lineObj,null,pos);var prop=(dir=="ltr")==(side=="after")?"left":"right";var ch=side=="after"?extent.begin:extent.end-(/\s/.test(lineObj.text.charAt(extent.end-1))?2:1);return coords(ch,prop)[prop]}
var order=getOrder(lineObj,doc.direction);iterateBidiSections(order,fromArg||0,toArg==null?lineLen:toArg,function(from,to,dir,i){var ltr=dir=="ltr";var fromPos=coords(from,ltr?"left":"right");var toPos=coords(to-1,ltr?"right":"left");var openStart=fromArg==null&&from==0,openEnd=toArg==null&&to==lineLen;var first=i==0,last=!order||i==order.length-1;if(toPos.top-fromPos.top<=3){var openLeft=(docLTR?openStart:openEnd)&&first;var openRight=(docLTR?openEnd:openStart)&&last;var left=openLeft?leftSide:(ltr?fromPos:toPos).left;var right=openRight?rightSide:(ltr?toPos:fromPos).right;add(left,fromPos.top,right-left,fromPos.bottom);}else{var topLeft,topRight,botLeft,botRight;if(ltr){topLeft=docLTR&&openStart&&first?leftSide:fromPos.left;topRight=docLTR?rightSide:wrapX(from,dir,"before");botLeft=docLTR?leftSide:wrapX(to,dir,"after");botRight=docLTR&&openEnd&&last?rightSide:toPos.right;}else{topLeft=!docLTR?leftSide:wrapX(from,dir,"before");topRight=!docLTR&&openStart&&first?rightSide:fromPos.right;botLeft=!docLTR&&openEnd&&last?leftSide:toPos.left;botRight=!docLTR?rightSide:wrapX(to,dir,"after");}
add(topLeft,fromPos.top,topRight-topLeft,fromPos.bottom);if(fromPos.bottom<toPos.top){add(leftSide,fromPos.bottom,null,toPos.top);}
add(botLeft,toPos.top,botRight-botLeft,toPos.bottom);}
if(!start||cmpCoords(fromPos,start)<0){start=fromPos;}
if(cmpCoords(toPos,start)<0){start=toPos;}
if(!end||cmpCoords(fromPos,end)<0){end=fromPos;}
if(cmpCoords(toPos,end)<0){end=toPos;}});return{start:start,end:end}}
var sFrom=range$$1.from(),sTo=range$$1.to();if(sFrom.line==sTo.line){drawForLine(sFrom.line,sFrom.ch,sTo.ch);}else{var fromLine=getLine(doc,sFrom.line),toLine=getLine(doc,sTo.line);var singleVLine=visualLine(fromLine)==visualLine(toLine);var leftEnd=drawForLine(sFrom.line,sFrom.ch,singleVLine?fromLine.text.length+1:null).end;var rightStart=drawForLine(sTo.line,singleVLine?0:null,sTo.ch).start;if(singleVLine){if(leftEnd.top<rightStart.top-2){add(leftEnd.right,leftEnd.top,null,leftEnd.bottom);add(leftSide,rightStart.top,rightStart.left,rightStart.bottom);}else{add(leftEnd.right,leftEnd.top,rightStart.left-leftEnd.right,leftEnd.bottom);}}
if(leftEnd.bottom<rightStart.top)
{add(leftSide,leftEnd.bottom,null,rightStart.top);}}
output.appendChild(fragment);}
function restartBlink(cm){if(!cm.state.focused){return}
var display=cm.display;clearInterval(display.blinker);var on=true;display.cursorDiv.style.visibility="";if(cm.options.cursorBlinkRate>0)
{display.blinker=setInterval(function(){return display.cursorDiv.style.visibility=(on=!on)?"":"hidden";},cm.options.cursorBlinkRate);}
else if(cm.options.cursorBlinkRate<0)
{display.cursorDiv.style.visibility="hidden";}}
function ensureFocus(cm){if(!cm.state.focused){cm.display.input.focus();onFocus(cm);}}
function delayBlurEvent(cm){cm.state.delayingBlurEvent=true;setTimeout(function(){if(cm.state.delayingBlurEvent){cm.state.delayingBlurEvent=false;onBlur(cm);}},100);}
function onFocus(cm,e){if(cm.state.delayingBlurEvent){cm.state.delayingBlurEvent=false;}
if(cm.options.readOnly=="nocursor"){return}
if(!cm.state.focused){signal(cm,"focus",cm,e);cm.state.focused=true;addClass(cm.display.wrapper,"CodeMirror-focused");if(!cm.curOp&&cm.display.selForContextMenu!=cm.doc.sel){cm.display.input.reset();if(webkit){setTimeout(function(){return cm.display.input.reset(true);},20);}}
cm.display.input.receivedFocus();}
restartBlink(cm);}
function onBlur(cm,e){if(cm.state.delayingBlurEvent){return}
if(cm.state.focused){signal(cm,"blur",cm,e);cm.state.focused=false;rmClass(cm.display.wrapper,"CodeMirror-focused");}
clearInterval(cm.display.blinker);setTimeout(function(){if(!cm.state.focused){cm.display.shift=false;}},150);}
function updateHeightsInViewport(cm){var display=cm.display;var prevBottom=display.lineDiv.offsetTop;for(var i=0;i<display.view.length;i++){var cur=display.view[i],wrapping=cm.options.lineWrapping;var height=(void 0),width=0;if(cur.hidden){continue}
if(ie&&ie_version<8){var bot=cur.node.offsetTop+cur.node.offsetHeight;height=bot-prevBottom;prevBottom=bot;}else{var box=cur.node.getBoundingClientRect();height=box.bottom-box.top;if(!wrapping&&cur.text.firstChild)
{width=cur.text.firstChild.getBoundingClientRect().right-box.left-1;}}
var diff=cur.line.height-height;if(height<2){height=textHeight(display);}
if(diff>.005||diff<-.005){updateLineHeight(cur.line,height);updateWidgetHeight(cur.line);if(cur.rest){for(var j=0;j<cur.rest.length;j++)
{updateWidgetHeight(cur.rest[j]);}}}
if(width>cm.display.sizerWidth){var chWidth=Math.ceil(width/charWidth(cm.display));if(chWidth>cm.display.maxLineLength){cm.display.maxLineLength=chWidth;cm.display.maxLine=cur.line;cm.display.maxLineChanged=true;}}}}
function updateWidgetHeight(line){if(line.widgets){for(var i=0;i<line.widgets.length;++i){var w=line.widgets[i],parent=w.node.parentNode;if(parent){w.height=parent.offsetHeight;}}}}
function visibleLines(display,doc,viewport){var top=viewport&&viewport.top!=null?Math.max(0,viewport.top):display.scroller.scrollTop;top=Math.floor(top-paddingTop(display));var bottom=viewport&&viewport.bottom!=null?viewport.bottom:top+display.wrapper.clientHeight;var from=lineAtHeight(doc,top),to=lineAtHeight(doc,bottom);if(viewport&&viewport.ensure){var ensureFrom=viewport.ensure.from.line,ensureTo=viewport.ensure.to.line;if(ensureFrom<from){from=ensureFrom;to=lineAtHeight(doc,heightAtLine(getLine(doc,ensureFrom))+display.wrapper.clientHeight);}else if(Math.min(ensureTo,doc.lastLine())>=to){from=lineAtHeight(doc,heightAtLine(getLine(doc,ensureTo))-display.wrapper.clientHeight);to=ensureTo;}}
return{from:from,to:Math.max(to,from+1)}}
function alignHorizontally(cm){var display=cm.display,view=display.view;if(!display.alignWidgets&&(!display.gutters.firstChild||!cm.options.fixedGutter)){return}
var comp=compensateForHScroll(display)-display.scroller.scrollLeft+cm.doc.scrollLeft;var gutterW=display.gutters.offsetWidth,left=comp+"px";for(var i=0;i<view.length;i++){if(!view[i].hidden){if(cm.options.fixedGutter){if(view[i].gutter)
{view[i].gutter.style.left=left;}
if(view[i].gutterBackground)
{view[i].gutterBackground.style.left=left;}}
var align=view[i].alignable;if(align){for(var j=0;j<align.length;j++)
{align[j].style.left=left;}}}}
if(cm.options.fixedGutter)
{display.gutters.style.left=(comp+gutterW)+"px";}}
function maybeUpdateLineNumberWidth(cm){if(!cm.options.lineNumbers){return false}
var doc=cm.doc,last=lineNumberFor(cm.options,doc.first+doc.size-1),display=cm.display;if(last.length!=display.lineNumChars){var test=display.measure.appendChild(elt("div",[elt("div",last)],"CodeMirror-linenumber CodeMirror-gutter-elt"));var innerW=test.firstChild.offsetWidth,padding=test.offsetWidth-innerW;display.lineGutter.style.width="";display.lineNumInnerWidth=Math.max(innerW,display.lineGutter.offsetWidth-padding)+1;display.lineNumWidth=display.lineNumInnerWidth+padding;display.lineNumChars=display.lineNumInnerWidth?last.length:-1;display.lineGutter.style.width=display.lineNumWidth+"px";updateGutterSpace(cm);return true}
return false}
function maybeScrollWindow(cm,rect){if(signalDOMEvent(cm,"scrollCursorIntoView")){return}
var display=cm.display,box=display.sizer.getBoundingClientRect(),doScroll=null;if(rect.top+box.top<0){doScroll=true;}
else if(rect.bottom+box.top>(window.innerHeight||document.documentElement.clientHeight)){doScroll=false;}
if(doScroll!=null&&!phantom){var scrollNode=elt("div","\u200b",null,("position: absolute;\n top: "+(rect.top-display.viewOffset-paddingTop(cm.display))+"px;\n height: "+(rect.bottom-rect.top+scrollGap(cm)+display.barHeight)+"px;\n left: "+(rect.left)+"px; width: "+(Math.max(2,rect.right-rect.left))+"px;"));cm.display.lineSpace.appendChild(scrollNode);scrollNode.scrollIntoView(doScroll);cm.display.lineSpace.removeChild(scrollNode);}}
function scrollPosIntoView(cm,pos,end,margin){if(margin==null){margin=0;}
var rect;if(!cm.options.lineWrapping&&pos==end){pos=pos.ch?Pos(pos.line,pos.sticky=="before"?pos.ch-1:pos.ch,"after"):pos;end=pos.sticky=="before"?Pos(pos.line,pos.ch+1,"before"):pos;}
for(var limit=0;limit<5;limit++){var changed=false;var coords=cursorCoords(cm,pos);var endCoords=!end||end==pos?coords:cursorCoords(cm,end);rect={left:Math.min(coords.left,endCoords.left),top:Math.min(coords.top,endCoords.top)-margin,right:Math.max(coords.left,endCoords.left),bottom:Math.max(coords.bottom,endCoords.bottom)+margin};var scrollPos=calculateScrollPos(cm,rect);var startTop=cm.doc.scrollTop,startLeft=cm.doc.scrollLeft;if(scrollPos.scrollTop!=null){updateScrollTop(cm,scrollPos.scrollTop);if(Math.abs(cm.doc.scrollTop-startTop)>1){changed=true;}}
if(scrollPos.scrollLeft!=null){setScrollLeft(cm,scrollPos.scrollLeft);if(Math.abs(cm.doc.scrollLeft-startLeft)>1){changed=true;}}
if(!changed){break}}
return rect}
function scrollIntoView(cm,rect){var scrollPos=calculateScrollPos(cm,rect);if(scrollPos.scrollTop!=null){updateScrollTop(cm,scrollPos.scrollTop);}
if(scrollPos.scrollLeft!=null){setScrollLeft(cm,scrollPos.scrollLeft);}}
function calculateScrollPos(cm,rect){var display=cm.display,snapMargin=textHeight(cm.display);if(rect.top<0){rect.top=0;}
var screentop=cm.curOp&&cm.curOp.scrollTop!=null?cm.curOp.scrollTop:display.scroller.scrollTop;var screen=displayHeight(cm),result={};if(rect.bottom-rect.top>screen){rect.bottom=rect.top+screen;}
var docBottom=cm.doc.height+paddingVert(display);var atTop=rect.top<snapMargin,atBottom=rect.bottom>docBottom-snapMargin;if(rect.top<screentop){result.scrollTop=atTop?0:rect.top;}else if(rect.bottom>screentop+screen){var newTop=Math.min(rect.top,(atBottom?docBottom:rect.bottom)-screen);if(newTop!=screentop){result.scrollTop=newTop;}}
var screenleft=cm.curOp&&cm.curOp.scrollLeft!=null?cm.curOp.scrollLeft:display.scroller.scrollLeft;var screenw=displayWidth(cm)-(cm.options.fixedGutter?display.gutters.offsetWidth:0);var tooWide=rect.right-rect.left>screenw;if(tooWide){rect.right=rect.left+screenw;}
if(rect.left<10)
{result.scrollLeft=0;}
else if(rect.left<screenleft)
{result.scrollLeft=Math.max(0,rect.left-(tooWide?0:10));}
else if(rect.right>screenw+screenleft-3)
{result.scrollLeft=rect.right+(tooWide?0:10)-screenw;}
return result}
function addToScrollTop(cm,top){if(top==null){return}
resolveScrollToPos(cm);cm.curOp.scrollTop=(cm.curOp.scrollTop==null?cm.doc.scrollTop:cm.curOp.scrollTop)+top;}
function ensureCursorVisible(cm){resolveScrollToPos(cm);var cur=cm.getCursor();cm.curOp.scrollToPos={from:cur,to:cur,margin:cm.options.cursorScrollMargin};}
function scrollToCoords(cm,x,y){if(x!=null||y!=null){resolveScrollToPos(cm);}
if(x!=null){cm.curOp.scrollLeft=x;}
if(y!=null){cm.curOp.scrollTop=y;}}
function scrollToRange(cm,range$$1){resolveScrollToPos(cm);cm.curOp.scrollToPos=range$$1;}
function resolveScrollToPos(cm){var range$$1=cm.curOp.scrollToPos;if(range$$1){cm.curOp.scrollToPos=null;var from=estimateCoords(cm,range$$1.from),to=estimateCoords(cm,range$$1.to);scrollToCoordsRange(cm,from,to,range$$1.margin);}}
function scrollToCoordsRange(cm,from,to,margin){var sPos=calculateScrollPos(cm,{left:Math.min(from.left,to.left),top:Math.min(from.top,to.top)-margin,right:Math.max(from.right,to.right),bottom:Math.max(from.bottom,to.bottom)+margin});scrollToCoords(cm,sPos.scrollLeft,sPos.scrollTop);}
function updateScrollTop(cm,val){if(Math.abs(cm.doc.scrollTop-val)<2){return}
if(!gecko){updateDisplaySimple(cm,{top:val});}
setScrollTop(cm,val,true);if(gecko){updateDisplaySimple(cm);}
startWorker(cm,100);}
function setScrollTop(cm,val,forceScroll){val=Math.min(cm.display.scroller.scrollHeight-cm.display.scroller.clientHeight,val);if(cm.display.scroller.scrollTop==val&&!forceScroll){return}
cm.doc.scrollTop=val;cm.display.scrollbars.setScrollTop(val);if(cm.display.scroller.scrollTop!=val){cm.display.scroller.scrollTop=val;}}
function setScrollLeft(cm,val,isScroller,forceScroll){val=Math.min(val,cm.display.scroller.scrollWidth-cm.display.scroller.clientWidth);if((isScroller?val==cm.doc.scrollLeft:Math.abs(cm.doc.scrollLeft-val)<2)&&!forceScroll){return}
cm.doc.scrollLeft=val;alignHorizontally(cm);if(cm.display.scroller.scrollLeft!=val){cm.display.scroller.scrollLeft=val;}
cm.display.scrollbars.setScrollLeft(val);}
function measureForScrollbars(cm){var d=cm.display,gutterW=d.gutters.offsetWidth;var docH=Math.round(cm.doc.height+paddingVert(cm.display));return{clientHeight:d.scroller.clientHeight,viewHeight:d.wrapper.clientHeight,scrollWidth:d.scroller.scrollWidth,clientWidth:d.scroller.clientWidth,viewWidth:d.wrapper.clientWidth,barLeft:cm.options.fixedGutter?gutterW:0,docHeight:docH,scrollHeight:docH+scrollGap(cm)+d.barHeight,nativeBarWidth:d.nativeBarWidth,gutterWidth:gutterW}}
var NativeScrollbars=function(place,scroll,cm){this.cm=cm;var vert=this.vert=elt("div",[elt("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar");var horiz=this.horiz=elt("div",[elt("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");vert.tabIndex=horiz.tabIndex=-1;place(vert);place(horiz);on(vert,"scroll",function(){if(vert.clientHeight){scroll(vert.scrollTop,"vertical");}});on(horiz,"scroll",function(){if(horiz.clientWidth){scroll(horiz.scrollLeft,"horizontal");}});this.checkedZeroWidth=false;if(ie&&ie_version<8){this.horiz.style.minHeight=this.vert.style.minWidth="18px";}};NativeScrollbars.prototype.update=function(measure){var needsH=measure.scrollWidth>measure.clientWidth+1;var needsV=measure.scrollHeight>measure.clientHeight+1;var sWidth=measure.nativeBarWidth;if(needsV){this.vert.style.display="block";this.vert.style.bottom=needsH?sWidth+"px":"0";var totalHeight=measure.viewHeight-(needsH?sWidth:0);this.vert.firstChild.style.height=Math.max(0,measure.scrollHeight-measure.clientHeight+totalHeight)+"px";}else{this.vert.style.display="";this.vert.firstChild.style.height="0";}
if(needsH){this.horiz.style.display="block";this.horiz.style.right=needsV?sWidth+"px":"0";this.horiz.style.left=measure.barLeft+"px";var totalWidth=measure.viewWidth-measure.barLeft-(needsV?sWidth:0);this.horiz.firstChild.style.width=Math.max(0,measure.scrollWidth-measure.clientWidth+totalWidth)+"px";}else{this.horiz.style.display="";this.horiz.firstChild.style.width="0";}
if(!this.checkedZeroWidth&&measure.clientHeight>0){if(sWidth==0){this.zeroWidthHack();}
this.checkedZeroWidth=true;}
return{right:needsV?sWidth:0,bottom:needsH?sWidth:0}};NativeScrollbars.prototype.setScrollLeft=function(pos){if(this.horiz.scrollLeft!=pos){this.horiz.scrollLeft=pos;}
if(this.disableHoriz){this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz");}};NativeScrollbars.prototype.setScrollTop=function(pos){if(this.vert.scrollTop!=pos){this.vert.scrollTop=pos;}
if(this.disableVert){this.enableZeroWidthBar(this.vert,this.disableVert,"vert");}};NativeScrollbars.prototype.zeroWidthHack=function(){var w=mac&&!mac_geMountainLion?"12px":"18px";this.horiz.style.height=this.vert.style.width=w;this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none";this.disableHoriz=new Delayed;this.disableVert=new Delayed;};NativeScrollbars.prototype.enableZeroWidthBar=function(bar,delay,type){bar.style.pointerEvents="auto";function maybeDisable(){var box=bar.getBoundingClientRect();var elt$$1=type=="vert"?document.elementFromPoint(box.right-1,(box.top+box.bottom)/2):document.elementFromPoint((box.right+box.left)/2,box.bottom-1);if(elt$$1!=bar){bar.style.pointerEvents="none";}
else{delay.set(1000,maybeDisable);}}
delay.set(1000,maybeDisable);};NativeScrollbars.prototype.clear=function(){var parent=this.horiz.parentNode;parent.removeChild(this.horiz);parent.removeChild(this.vert);};var NullScrollbars=function(){};NullScrollbars.prototype.update=function(){return{bottom:0,right:0}};NullScrollbars.prototype.setScrollLeft=function(){};NullScrollbars.prototype.setScrollTop=function(){};NullScrollbars.prototype.clear=function(){};function updateScrollbars(cm,measure){if(!measure){measure=measureForScrollbars(cm);}
var startWidth=cm.display.barWidth,startHeight=cm.display.barHeight;updateScrollbarsInner(cm,measure);for(var i=0;i<4&&startWidth!=cm.display.barWidth||startHeight!=cm.display.barHeight;i++){if(startWidth!=cm.display.barWidth&&cm.options.lineWrapping)
{updateHeightsInViewport(cm);}
updateScrollbarsInner(cm,measureForScrollbars(cm));startWidth=cm.display.barWidth;startHeight=cm.display.barHeight;}}
function updateScrollbarsInner(cm,measure){var d=cm.display;var sizes=d.scrollbars.update(measure);d.sizer.style.paddingRight=(d.barWidth=sizes.right)+"px";d.sizer.style.paddingBottom=(d.barHeight=sizes.bottom)+"px";d.heightForcer.style.borderBottom=sizes.bottom+"px solid transparent";if(sizes.right&&sizes.bottom){d.scrollbarFiller.style.display="block";d.scrollbarFiller.style.height=sizes.bottom+"px";d.scrollbarFiller.style.width=sizes.right+"px";}else{d.scrollbarFiller.style.display="";}
if(sizes.bottom&&cm.options.coverGutterNextToScrollbar&&cm.options.fixedGutter){d.gutterFiller.style.display="block";d.gutterFiller.style.height=sizes.bottom+"px";d.gutterFiller.style.width=measure.gutterWidth+"px";}else{d.gutterFiller.style.display="";}}
var scrollbarModel={"native":NativeScrollbars,"null":NullScrollbars};function initScrollbars(cm){if(cm.display.scrollbars){cm.display.scrollbars.clear();if(cm.display.scrollbars.addClass)
{rmClass(cm.display.wrapper,cm.display.scrollbars.addClass);}}
cm.display.scrollbars=new scrollbarModel[cm.options.scrollbarStyle](function(node){cm.display.wrapper.insertBefore(node,cm.display.scrollbarFiller);on(node,"mousedown",function(){if(cm.state.focused){setTimeout(function(){return cm.display.input.focus();},0);}});node.setAttribute("cm-not-content","true");},function(pos,axis){if(axis=="horizontal"){setScrollLeft(cm,pos);}
else{updateScrollTop(cm,pos);}},cm);if(cm.display.scrollbars.addClass)
{addClass(cm.display.wrapper,cm.display.scrollbars.addClass);}}
var nextOpId=0;function startOperation(cm){cm.curOp={cm:cm,viewChanged:false,startHeight:cm.doc.height,forceUpdate:false,updateInput:0,typing:false,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:false,updateMaxLine:false,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:false,id:++nextOpId};pushOperation(cm.curOp);}
function endOperation(cm){var op=cm.curOp;if(op){finishOperation(op,function(group){for(var i=0;i<group.ops.length;i++)
{group.ops[i].cm.curOp=null;}
endOperations(group);});}}
function endOperations(group){var ops=group.ops;for(var i=0;i<ops.length;i++)
{endOperation_R1(ops[i]);}
for(var i$1=0;i$1<ops.length;i$1++)
{endOperation_W1(ops[i$1]);}
for(var i$2=0;i$2<ops.length;i$2++)
{endOperation_R2(ops[i$2]);}
for(var i$3=0;i$3<ops.length;i$3++)
{endOperation_W2(ops[i$3]);}
for(var i$4=0;i$4<ops.length;i$4++)
{endOperation_finish(ops[i$4]);}}
function endOperation_R1(op){var cm=op.cm,display=cm.display;maybeClipScrollbars(cm);if(op.updateMaxLine){findMaxLine(cm);}
op.mustUpdate=op.viewChanged||op.forceUpdate||op.scrollTop!=null||op.scrollToPos&&(op.scrollToPos.from.line<display.viewFrom||op.scrollToPos.to.line>=display.viewTo)||display.maxLineChanged&&cm.options.lineWrapping;op.update=op.mustUpdate&&new DisplayUpdate(cm,op.mustUpdate&&{top:op.scrollTop,ensure:op.scrollToPos},op.forceUpdate);}
function endOperation_W1(op){op.updatedDisplay=op.mustUpdate&&updateDisplayIfNeeded(op.cm,op.update);}
function endOperation_R2(op){var cm=op.cm,display=cm.display;if(op.updatedDisplay){updateHeightsInViewport(cm);}
op.barMeasure=measureForScrollbars(cm);if(display.maxLineChanged&&!cm.options.lineWrapping){op.adjustWidthTo=measureChar(cm,display.maxLine,display.maxLine.text.length).left+3;cm.display.sizerWidth=op.adjustWidthTo;op.barMeasure.scrollWidth=Math.max(display.scroller.clientWidth,display.sizer.offsetLeft+op.adjustWidthTo+scrollGap(cm)+cm.display.barWidth);op.maxScrollLeft=Math.max(0,display.sizer.offsetLeft+op.adjustWidthTo-displayWidth(cm));}
if(op.updatedDisplay||op.selectionChanged)
{op.preparedSelection=display.input.prepareSelection();}}
function endOperation_W2(op){var cm=op.cm;if(op.adjustWidthTo!=null){cm.display.sizer.style.minWidth=op.adjustWidthTo+"px";if(op.maxScrollLeft<cm.doc.scrollLeft)
{setScrollLeft(cm,Math.min(cm.display.scroller.scrollLeft,op.maxScrollLeft),true);}
cm.display.maxLineChanged=false;}
var takeFocus=op.focus&&op.focus==activeElt();if(op.preparedSelection)
{cm.display.input.showSelection(op.preparedSelection,takeFocus);}
if(op.updatedDisplay||op.startHeight!=cm.doc.height)
{updateScrollbars(cm,op.barMeasure);}
if(op.updatedDisplay)
{setDocumentHeight(cm,op.barMeasure);}
if(op.selectionChanged){restartBlink(cm);}
if(cm.state.focused&&op.updateInput)
{cm.display.input.reset(op.typing);}
if(takeFocus){ensureFocus(op.cm);}}
function endOperation_finish(op){var cm=op.cm,display=cm.display,doc=cm.doc;if(op.updatedDisplay){postUpdateDisplay(cm,op.update);}
if(display.wheelStartX!=null&&(op.scrollTop!=null||op.scrollLeft!=null||op.scrollToPos))
{display.wheelStartX=display.wheelStartY=null;}
if(op.scrollTop!=null){setScrollTop(cm,op.scrollTop,op.forceScroll);}
if(op.scrollLeft!=null){setScrollLeft(cm,op.scrollLeft,true,true);}
if(op.scrollToPos){var rect=scrollPosIntoView(cm,clipPos(doc,op.scrollToPos.from),clipPos(doc,op.scrollToPos.to),op.scrollToPos.margin);maybeScrollWindow(cm,rect);}
var hidden=op.maybeHiddenMarkers,unhidden=op.maybeUnhiddenMarkers;if(hidden){for(var i=0;i<hidden.length;++i)
{if(!hidden[i].lines.length){signal(hidden[i],"hide");}}}
if(unhidden){for(var i$1=0;i$1<unhidden.length;++i$1)
{if(unhidden[i$1].lines.length){signal(unhidden[i$1],"unhide");}}}
if(display.wrapper.offsetHeight)
{doc.scrollTop=cm.display.scroller.scrollTop;}
if(op.changeObjs)
{signal(cm,"changes",cm,op.changeObjs);}
if(op.update)
{op.update.finish();}}
function runInOp(cm,f){if(cm.curOp){return f()}
startOperation(cm);try{return f()}
finally{endOperation(cm);}}
function operation(cm,f){return function(){if(cm.curOp){return f.apply(cm,arguments)}
startOperation(cm);try{return f.apply(cm,arguments)}
finally{endOperation(cm);}}}
function methodOp(f){return function(){if(this.curOp){return f.apply(this,arguments)}
startOperation(this);try{return f.apply(this,arguments)}
finally{endOperation(this);}}}
function docMethodOp(f){return function(){var cm=this.cm;if(!cm||cm.curOp){return f.apply(this,arguments)}
startOperation(cm);try{return f.apply(this,arguments)}
finally{endOperation(cm);}}}
function regChange(cm,from,to,lendiff){if(from==null){from=cm.doc.first;}
if(to==null){to=cm.doc.first+cm.doc.size;}
if(!lendiff){lendiff=0;}
var display=cm.display;if(lendiff&&to<display.viewTo&&(display.updateLineNumbers==null||display.updateLineNumbers>from))
{display.updateLineNumbers=from;}
cm.curOp.viewChanged=true;if(from>=display.viewTo){if(sawCollapsedSpans&&visualLineNo(cm.doc,from)<display.viewTo)
{resetView(cm);}}else if(to<=display.viewFrom){if(sawCollapsedSpans&&visualLineEndNo(cm.doc,to+lendiff)>display.viewFrom){resetView(cm);}else{display.viewFrom+=lendiff;display.viewTo+=lendiff;}}else if(from<=display.viewFrom&&to>=display.viewTo){resetView(cm);}else if(from<=display.viewFrom){var cut=viewCuttingPoint(cm,to,to+lendiff,1);if(cut){display.view=display.view.slice(cut.index);display.viewFrom=cut.lineN;display.viewTo+=lendiff;}else{resetView(cm);}}else if(to>=display.viewTo){var cut$1=viewCuttingPoint(cm,from,from,-1);if(cut$1){display.view=display.view.slice(0,cut$1.index);display.viewTo=cut$1.lineN;}else{resetView(cm);}}else{var cutTop=viewCuttingPoint(cm,from,from,-1);var cutBot=viewCuttingPoint(cm,to,to+lendiff,1);if(cutTop&&cutBot){display.view=display.view.slice(0,cutTop.index).concat(buildViewArray(cm,cutTop.lineN,cutBot.lineN)).concat(display.view.slice(cutBot.index));display.viewTo+=lendiff;}else{resetView(cm);}}
var ext=display.externalMeasured;if(ext){if(to<ext.lineN)
{ext.lineN+=lendiff;}
else if(from<ext.lineN+ext.size)
{display.externalMeasured=null;}}}
function regLineChange(cm,line,type){cm.curOp.viewChanged=true;var display=cm.display,ext=cm.display.externalMeasured;if(ext&&line>=ext.lineN&&line<ext.lineN+ext.size)
{display.externalMeasured=null;}
if(line<display.viewFrom||line>=display.viewTo){return}
var lineView=display.view[findViewIndex(cm,line)];if(lineView.node==null){return}
var arr=lineView.changes||(lineView.changes=[]);if(indexOf(arr,type)==-1){arr.push(type);}}
function resetView(cm){cm.display.viewFrom=cm.display.viewTo=cm.doc.first;cm.display.view=[];cm.display.viewOffset=0;}
function viewCuttingPoint(cm,oldN,newN,dir){var index=findViewIndex(cm,oldN),diff,view=cm.display.view;if(!sawCollapsedSpans||newN==cm.doc.first+cm.doc.size)
{return{index:index,lineN:newN}}
var n=cm.display.viewFrom;for(var i=0;i<index;i++)
{n+=view[i].size;}
if(n!=oldN){if(dir>0){if(index==view.length-1){return null}
diff=(n+view[index].size)-oldN;index++;}else{diff=n-oldN;}
oldN+=diff;newN+=diff;}
while(visualLineNo(cm.doc,newN)!=newN){if(index==(dir<0?0:view.length-1)){return null}
newN+=dir*view[index-(dir<0?1:0)].size;index+=dir;}
return{index:index,lineN:newN}}
function adjustView(cm,from,to){var display=cm.display,view=display.view;if(view.length==0||from>=display.viewTo||to<=display.viewFrom){display.view=buildViewArray(cm,from,to);display.viewFrom=from;}else{if(display.viewFrom>from)
{display.view=buildViewArray(cm,from,display.viewFrom).concat(display.view);}
else if(display.viewFrom<from)
{display.view=display.view.slice(findViewIndex(cm,from));}
display.viewFrom=from;if(display.viewTo<to)
{display.view=display.view.concat(buildViewArray(cm,display.viewTo,to));}
else if(display.viewTo>to)
{display.view=display.view.slice(0,findViewIndex(cm,to));}}
display.viewTo=to;}
function countDirtyView(cm){var view=cm.display.view,dirty=0;for(var i=0;i<view.length;i++){var lineView=view[i];if(!lineView.hidden&&(!lineView.node||lineView.changes)){++dirty;}}
return dirty}
function startWorker(cm,time){if(cm.doc.highlightFrontier<cm.display.viewTo)
{cm.state.highlight.set(time,bind(highlightWorker,cm));}}
function highlightWorker(cm){var doc=cm.doc;if(doc.highlightFrontier>=cm.display.viewTo){return}
var end=+new Date+cm.options.workTime;var context=getContextBefore(cm,doc.highlightFrontier);var changedLines=[];doc.iter(context.line,Math.min(doc.first+doc.size,cm.display.viewTo+500),function(line){if(context.line>=cm.display.viewFrom){var oldStyles=line.styles;var resetState=line.text.length>cm.options.maxHighlightLength?copyState(doc.mode,context.state):null;var highlighted=highlightLine(cm,line,context,true);if(resetState){context.state=resetState;}
line.styles=highlighted.styles;var oldCls=line.styleClasses,newCls=highlighted.classes;if(newCls){line.styleClasses=newCls;}
else if(oldCls){line.styleClasses=null;}
var ischange=!oldStyles||oldStyles.length!=line.styles.length||oldCls!=newCls&&(!oldCls||!newCls||oldCls.bgClass!=newCls.bgClass||oldCls.textClass!=newCls.textClass);for(var i=0;!ischange&&i<oldStyles.length;++i){ischange=oldStyles[i]!=line.styles[i];}
if(ischange){changedLines.push(context.line);}
line.stateAfter=context.save();context.nextLine();}else{if(line.text.length<=cm.options.maxHighlightLength)
{processLine(cm,line.text,context);}
line.stateAfter=context.line%5==0?context.save():null;context.nextLine();}
if(+new Date>end){startWorker(cm,cm.options.workDelay);return true}});doc.highlightFrontier=context.line;doc.modeFrontier=Math.max(doc.modeFrontier,context.line);if(changedLines.length){runInOp(cm,function(){for(var i=0;i<changedLines.length;i++)
{regLineChange(cm,changedLines[i],"text");}});}}
var DisplayUpdate=function(cm,viewport,force){var display=cm.display;this.viewport=viewport;this.visible=visibleLines(display,cm.doc,viewport);this.editorIsHidden=!display.wrapper.offsetWidth;this.wrapperHeight=display.wrapper.clientHeight;this.wrapperWidth=display.wrapper.clientWidth;this.oldDisplayWidth=displayWidth(cm);this.force=force;this.dims=getDimensions(cm);this.events=[];};DisplayUpdate.prototype.signal=function(emitter,type){if(hasHandler(emitter,type))
{this.events.push(arguments);}};DisplayUpdate.prototype.finish=function(){for(var i=0;i<this.events.length;i++)
{signal.apply(null,this.events[i]);}};function maybeClipScrollbars(cm){var display=cm.display;if(!display.scrollbarsClipped&&display.scroller.offsetWidth){display.nativeBarWidth=display.scroller.offsetWidth-display.scroller.clientWidth;display.heightForcer.style.height=scrollGap(cm)+"px";display.sizer.style.marginBottom=-display.nativeBarWidth+"px";display.sizer.style.borderRightWidth=scrollGap(cm)+"px";display.scrollbarsClipped=true;}}
function selectionSnapshot(cm){if(cm.hasFocus()){return null}
var active=activeElt();if(!active||!contains(cm.display.lineDiv,active)){return null}
var result={activeElt:active};if(window.getSelection){var sel=window.getSelection();if(sel.anchorNode&&sel.extend&&contains(cm.display.lineDiv,sel.anchorNode)){result.anchorNode=sel.anchorNode;result.anchorOffset=sel.anchorOffset;result.focusNode=sel.focusNode;result.focusOffset=sel.focusOffset;}}
return result}
function restoreSelection(snapshot){if(!snapshot||!snapshot.activeElt||snapshot.activeElt==activeElt()){return}
snapshot.activeElt.focus();if(snapshot.anchorNode&&contains(document.body,snapshot.anchorNode)&&contains(document.body,snapshot.focusNode)){var sel=window.getSelection(),range$$1=document.createRange();range$$1.setEnd(snapshot.anchorNode,snapshot.anchorOffset);range$$1.collapse(false);sel.removeAllRanges();sel.addRange(range$$1);sel.extend(snapshot.focusNode,snapshot.focusOffset);}}
function updateDisplayIfNeeded(cm,update){var display=cm.display,doc=cm.doc;if(update.editorIsHidden){resetView(cm);return false}
if(!update.force&&update.visible.from>=display.viewFrom&&update.visible.to<=display.viewTo&&(display.updateLineNumbers==null||display.updateLineNumbers>=display.viewTo)&&display.renderedView==display.view&&countDirtyView(cm)==0)
{return false}
if(maybeUpdateLineNumberWidth(cm)){resetView(cm);update.dims=getDimensions(cm);}
var end=doc.first+doc.size;var from=Math.max(update.visible.from-cm.options.viewportMargin,doc.first);var to=Math.min(end,update.visible.to+cm.options.viewportMargin);if(display.viewFrom<from&&from-display.viewFrom<20){from=Math.max(doc.first,display.viewFrom);}
if(display.viewTo>to&&display.viewTo-to<20){to=Math.min(end,display.viewTo);}
if(sawCollapsedSpans){from=visualLineNo(cm.doc,from);to=visualLineEndNo(cm.doc,to);}
var different=from!=display.viewFrom||to!=display.viewTo||display.lastWrapHeight!=update.wrapperHeight||display.lastWrapWidth!=update.wrapperWidth;adjustView(cm,from,to);display.viewOffset=heightAtLine(getLine(cm.doc,display.viewFrom));cm.display.mover.style.top=display.viewOffset+"px";var toUpdate=countDirtyView(cm);if(!different&&toUpdate==0&&!update.force&&display.renderedView==display.view&&(display.updateLineNumbers==null||display.updateLineNumbers>=display.viewTo))
{return false}
var selSnapshot=selectionSnapshot(cm);if(toUpdate>4){display.lineDiv.style.display="none";}
patchDisplay(cm,display.updateLineNumbers,update.dims);if(toUpdate>4){display.lineDiv.style.display="";}
display.renderedView=display.view;restoreSelection(selSnapshot);removeChildren(display.cursorDiv);removeChildren(display.selectionDiv);display.gutters.style.height=display.sizer.style.minHeight=0;if(different){display.lastWrapHeight=update.wrapperHeight;display.lastWrapWidth=update.wrapperWidth;startWorker(cm,400);}
display.updateLineNumbers=null;return true}
function postUpdateDisplay(cm,update){var viewport=update.viewport;for(var first=true;;first=false){if(!first||!cm.options.lineWrapping||update.oldDisplayWidth==displayWidth(cm)){if(viewport&&viewport.top!=null)
{viewport={top:Math.min(cm.doc.height+paddingVert(cm.display)-displayHeight(cm),viewport.top)};}
update.visible=visibleLines(cm.display,cm.doc,viewport);if(update.visible.from>=cm.display.viewFrom&&update.visible.to<=cm.display.viewTo)
{break}}
if(!updateDisplayIfNeeded(cm,update)){break}
updateHeightsInViewport(cm);var barMeasure=measureForScrollbars(cm);updateSelection(cm);updateScrollbars(cm,barMeasure);setDocumentHeight(cm,barMeasure);update.force=false;}
update.signal(cm,"update",cm);if(cm.display.viewFrom!=cm.display.reportedViewFrom||cm.display.viewTo!=cm.display.reportedViewTo){update.signal(cm,"viewportChange",cm,cm.display.viewFrom,cm.display.viewTo);cm.display.reportedViewFrom=cm.display.viewFrom;cm.display.reportedViewTo=cm.display.viewTo;}}
function updateDisplaySimple(cm,viewport){var update=new DisplayUpdate(cm,viewport);if(updateDisplayIfNeeded(cm,update)){updateHeightsInViewport(cm);postUpdateDisplay(cm,update);var barMeasure=measureForScrollbars(cm);updateSelection(cm);updateScrollbars(cm,barMeasure);setDocumentHeight(cm,barMeasure);update.finish();}}
function patchDisplay(cm,updateNumbersFrom,dims){var display=cm.display,lineNumbers=cm.options.lineNumbers;var container=display.lineDiv,cur=container.firstChild;function rm(node){var next=node.nextSibling;if(webkit&&mac&&cm.display.currentWheelTarget==node)
{node.style.display="none";}
else
{node.parentNode.removeChild(node);}
return next}
var view=display.view,lineN=display.viewFrom;for(var i=0;i<view.length;i++){var lineView=view[i];if(lineView.hidden);else if(!lineView.node||lineView.node.parentNode!=container){var node=buildLineElement(cm,lineView,lineN,dims);container.insertBefore(node,cur);}else{while(cur!=lineView.node){cur=rm(cur);}
var updateNumber=lineNumbers&&updateNumbersFrom!=null&&updateNumbersFrom<=lineN&&lineView.lineNumber;if(lineView.changes){if(indexOf(lineView.changes,"gutter")>-1){updateNumber=false;}
updateLineForChanges(cm,lineView,lineN,dims);}
if(updateNumber){removeChildren(lineView.lineNumber);lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options,lineN)));}
cur=lineView.node.nextSibling;}
lineN+=lineView.size;}
while(cur){cur=rm(cur);}}
function updateGutterSpace(cm){var width=cm.display.gutters.offsetWidth;cm.display.sizer.style.marginLeft=width+"px";}
function setDocumentHeight(cm,measure){cm.display.sizer.style.minHeight=measure.docHeight+"px";cm.display.heightForcer.style.top=measure.docHeight+"px";cm.display.gutters.style.height=(measure.docHeight+cm.display.barHeight+scrollGap(cm))+"px";}
function updateGutters(cm){var gutters=cm.display.gutters,specs=cm.options.gutters;removeChildren(gutters);var i=0;for(;i<specs.length;++i){var gutterClass=specs[i];var gElt=gutters.appendChild(elt("div",null,"CodeMirror-gutter "+gutterClass));if(gutterClass=="CodeMirror-linenumbers"){cm.display.lineGutter=gElt;gElt.style.width=(cm.display.lineNumWidth||1)+"px";}}
gutters.style.display=i?"":"none";updateGutterSpace(cm);}
function setGuttersForLineNumbers(options){var found=indexOf(options.gutters,"CodeMirror-linenumbers");if(found==-1&&options.lineNumbers){options.gutters=options.gutters.concat(["CodeMirror-linenumbers"]);}else if(found>-1&&!options.lineNumbers){options.gutters=options.gutters.slice(0);options.gutters.splice(found,1);}}
var wheelSamples=0,wheelPixelsPerUnit=null;if(ie){wheelPixelsPerUnit=-.53;}
else if(gecko){wheelPixelsPerUnit=15;}
else if(chrome){wheelPixelsPerUnit=-.7;}
else if(safari){wheelPixelsPerUnit=-1/3;}
function wheelEventDelta(e){var dx=e.wheelDeltaX,dy=e.wheelDeltaY;if(dx==null&&e.detail&&e.axis==e.HORIZONTAL_AXIS){dx=e.detail;}
if(dy==null&&e.detail&&e.axis==e.VERTICAL_AXIS){dy=e.detail;}
else if(dy==null){dy=e.wheelDelta;}
return{x:dx,y:dy}}
function wheelEventPixels(e){var delta=wheelEventDelta(e);delta.x*=wheelPixelsPerUnit;delta.y*=wheelPixelsPerUnit;return delta}
function onScrollWheel(cm,e){var delta=wheelEventDelta(e),dx=delta.x,dy=delta.y;var display=cm.display,scroll=display.scroller;var canScrollX=scroll.scrollWidth>scroll.clientWidth;var canScrollY=scroll.scrollHeight>scroll.clientHeight;if(!(dx&&canScrollX||dy&&canScrollY)){return}
if(dy&&mac&&webkit){outer:for(var cur=e.target,view=display.view;cur!=scroll;cur=cur.parentNode){for(var i=0;i<view.length;i++){if(view[i].node==cur){cm.display.currentWheelTarget=cur;break outer}}}}
if(dx&&!gecko&&!presto&&wheelPixelsPerUnit!=null){if(dy&&canScrollY)
{updateScrollTop(cm,Math.max(0,scroll.scrollTop+dy*wheelPixelsPerUnit));}
setScrollLeft(cm,Math.max(0,scroll.scrollLeft+dx*wheelPixelsPerUnit));if(!dy||(dy&&canScrollY))
{e_preventDefault(e);}
display.wheelStartX=null;return}
if(dy&&wheelPixelsPerUnit!=null){var pixels=dy*wheelPixelsPerUnit;var top=cm.doc.scrollTop,bot=top+display.wrapper.clientHeight;if(pixels<0){top=Math.max(0,top+pixels-50);}
else{bot=Math.min(cm.doc.height,bot+pixels+50);}
updateDisplaySimple(cm,{top:top,bottom:bot});}
if(wheelSamples<20){if(display.wheelStartX==null){display.wheelStartX=scroll.scrollLeft;display.wheelStartY=scroll.scrollTop;display.wheelDX=dx;display.wheelDY=dy;setTimeout(function(){if(display.wheelStartX==null){return}
var movedX=scroll.scrollLeft-display.wheelStartX;var movedY=scroll.scrollTop-display.wheelStartY;var sample=(movedY&&display.wheelDY&&movedY/display.wheelDY)||(movedX&&display.wheelDX&&movedX/display.wheelDX);display.wheelStartX=display.wheelStartY=null;if(!sample){return}
wheelPixelsPerUnit=(wheelPixelsPerUnit*wheelSamples+sample)/(wheelSamples+1);++wheelSamples;},200);}else{display.wheelDX+=dx;display.wheelDY+=dy;}}}
var Selection=function(ranges,primIndex){this.ranges=ranges;this.primIndex=primIndex;};Selection.prototype.primary=function(){return this.ranges[this.primIndex]};Selection.prototype.equals=function(other){if(other==this){return true}
if(other.primIndex!=this.primIndex||other.ranges.length!=this.ranges.length){return false}
for(var i=0;i<this.ranges.length;i++){var here=this.ranges[i],there=other.ranges[i];if(!equalCursorPos(here.anchor,there.anchor)||!equalCursorPos(here.head,there.head)){return false}}
return true};Selection.prototype.deepCopy=function(){var out=[];for(var i=0;i<this.ranges.length;i++)
{out[i]=new Range(copyPos(this.ranges[i].anchor),copyPos(this.ranges[i].head));}
return new Selection(out,this.primIndex)};Selection.prototype.somethingSelected=function(){for(var i=0;i<this.ranges.length;i++)
{if(!this.ranges[i].empty()){return true}}
return false};Selection.prototype.contains=function(pos,end){if(!end){end=pos;}
for(var i=0;i<this.ranges.length;i++){var range=this.ranges[i];if(cmp(end,range.from())>=0&&cmp(pos,range.to())<=0)
{return i}}
return-1};var Range=function(anchor,head){this.anchor=anchor;this.head=head;};Range.prototype.from=function(){return minPos(this.anchor,this.head)};Range.prototype.to=function(){return maxPos(this.anchor,this.head)};Range.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch};function normalizeSelection(cm,ranges,primIndex){var mayTouch=cm&&cm.options.selectionsMayTouch;var prim=ranges[primIndex];ranges.sort(function(a,b){return cmp(a.from(),b.from());});primIndex=indexOf(ranges,prim);for(var i=1;i<ranges.length;i++){var cur=ranges[i],prev=ranges[i-1];var diff=cmp(prev.to(),cur.from());if(mayTouch&&!cur.empty()?diff>0:diff>=0){var from=minPos(prev.from(),cur.from()),to=maxPos(prev.to(),cur.to());var inv=prev.empty()?cur.from()==cur.head:prev.from()==prev.head;if(i<=primIndex){--primIndex;}
ranges.splice(--i,2,new Range(inv?to:from,inv?from:to));}}
return new Selection(ranges,primIndex)}
function simpleSelection(anchor,head){return new Selection([new Range(anchor,head||anchor)],0)}
function changeEnd(change){if(!change.text){return change.to}
return Pos(change.from.line+change.text.length-1,lst(change.text).length+(change.text.length==1?change.from.ch:0))}
function adjustForChange(pos,change){if(cmp(pos,change.from)<0){return pos}
if(cmp(pos,change.to)<=0){return changeEnd(change)}
var line=pos.line+change.text.length-(change.to.line-change.from.line)-1,ch=pos.ch;if(pos.line==change.to.line){ch+=changeEnd(change).ch-change.to.ch;}
return Pos(line,ch)}
function computeSelAfterChange(doc,change){var out=[];for(var i=0;i<doc.sel.ranges.length;i++){var range=doc.sel.ranges[i];out.push(new Range(adjustForChange(range.anchor,change),adjustForChange(range.head,change)));}
return normalizeSelection(doc.cm,out,doc.sel.primIndex)}
function offsetPos(pos,old,nw){if(pos.line==old.line)
{return Pos(nw.line,pos.ch-old.ch+nw.ch)}
else
{return Pos(nw.line+(pos.line-old.line),pos.ch)}}
function computeReplacedSel(doc,changes,hint){var out=[];var oldPrev=Pos(doc.first,0),newPrev=oldPrev;for(var i=0;i<changes.length;i++){var change=changes[i];var from=offsetPos(change.from,oldPrev,newPrev);var to=offsetPos(changeEnd(change),oldPrev,newPrev);oldPrev=change.to;newPrev=to;if(hint=="around"){var range=doc.sel.ranges[i],inv=cmp(range.head,range.anchor)<0;out[i]=new Range(inv?to:from,inv?from:to);}else{out[i]=new Range(from,from);}}
return new Selection(out,doc.sel.primIndex)}
function loadMode(cm){cm.doc.mode=getMode(cm.options,cm.doc.modeOption);resetModeState(cm);}
function resetModeState(cm){cm.doc.iter(function(line){if(line.stateAfter){line.stateAfter=null;}
if(line.styles){line.styles=null;}});cm.doc.modeFrontier=cm.doc.highlightFrontier=cm.doc.first;startWorker(cm,100);cm.state.modeGen++;if(cm.curOp){regChange(cm);}}
function isWholeLineUpdate(doc,change){return change.from.ch==0&&change.to.ch==0&&lst(change.text)==""&&(!doc.cm||doc.cm.options.wholeLineUpdateBefore)}
function updateDoc(doc,change,markedSpans,estimateHeight$$1){function spansFor(n){return markedSpans?markedSpans[n]:null}
function update(line,text,spans){updateLine(line,text,spans,estimateHeight$$1);signalLater(line,"change",line,change);}
function linesFor(start,end){var result=[];for(var i=start;i<end;++i)
{result.push(new Line(text[i],spansFor(i),estimateHeight$$1));}
return result}
var from=change.from,to=change.to,text=change.text;var firstLine=getLine(doc,from.line),lastLine=getLine(doc,to.line);var lastText=lst(text),lastSpans=spansFor(text.length-1),nlines=to.line-from.line;if(change.full){doc.insert(0,linesFor(0,text.length));doc.remove(text.length,doc.size-text.length);}else if(isWholeLineUpdate(doc,change)){var added=linesFor(0,text.length-1);update(lastLine,lastLine.text,lastSpans);if(nlines){doc.remove(from.line,nlines);}
if(added.length){doc.insert(from.line,added);}}else if(firstLine==lastLine){if(text.length==1){update(firstLine,firstLine.text.slice(0,from.ch)+lastText+firstLine.text.slice(to.ch),lastSpans);}else{var added$1=linesFor(1,text.length-1);added$1.push(new Line(lastText+firstLine.text.slice(to.ch),lastSpans,estimateHeight$$1));update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0));doc.insert(from.line+1,added$1);}}else if(text.length==1){update(firstLine,firstLine.text.slice(0,from.ch)+text[0]+lastLine.text.slice(to.ch),spansFor(0));doc.remove(from.line+1,nlines);}else{update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0));update(lastLine,lastText+lastLine.text.slice(to.ch),lastSpans);var added$2=linesFor(1,text.length-1);if(nlines>1){doc.remove(from.line+1,nlines-1);}
doc.insert(from.line+1,added$2);}
signalLater(doc,"change",doc,change);}
function linkedDocs(doc,f,sharedHistOnly){function propagate(doc,skip,sharedHist){if(doc.linked){for(var i=0;i<doc.linked.length;++i){var rel=doc.linked[i];if(rel.doc==skip){continue}
var shared=sharedHist&&rel.sharedHist;if(sharedHistOnly&&!shared){continue}
f(rel.doc,shared);propagate(rel.doc,doc,shared);}}}
propagate(doc,null,true);}
function attachDoc(cm,doc){if(doc.cm){throw new Error("This document is already in use.")}
cm.doc=doc;doc.cm=cm;estimateLineHeights(cm);loadMode(cm);setDirectionClass(cm);if(!cm.options.lineWrapping){findMaxLine(cm);}
cm.options.mode=doc.modeOption;regChange(cm);}
function setDirectionClass(cm){(cm.doc.direction=="rtl"?addClass:rmClass)(cm.display.lineDiv,"CodeMirror-rtl");}
function directionChanged(cm){runInOp(cm,function(){setDirectionClass(cm);regChange(cm);});}
function History(startGen){this.done=[];this.undone=[];this.undoDepth=Infinity;this.lastModTime=this.lastSelTime=0;this.lastOp=this.lastSelOp=null;this.lastOrigin=this.lastSelOrigin=null;this.generation=this.maxGeneration=startGen||1;}
function historyChangeFromChange(doc,change){var histChange={from:copyPos(change.from),to:changeEnd(change),text:getBetween(doc,change.from,change.to)};attachLocalSpans(doc,histChange,change.from.line,change.to.line+1);linkedDocs(doc,function(doc){return attachLocalSpans(doc,histChange,change.from.line,change.to.line+1);},true);return histChange}
function clearSelectionEvents(array){while(array.length){var last=lst(array);if(last.ranges){array.pop();}
else{break}}}
function lastChangeEvent(hist,force){if(force){clearSelectionEvents(hist.done);return lst(hist.done)}else if(hist.done.length&&!lst(hist.done).ranges){return lst(hist.done)}else if(hist.done.length>1&&!hist.done[hist.done.length-2].ranges){hist.done.pop();return lst(hist.done)}}
function addChangeToHistory(doc,change,selAfter,opId){var hist=doc.history;hist.undone.length=0;var time=+new Date,cur;var last;if((hist.lastOp==opId||hist.lastOrigin==change.origin&&change.origin&&((change.origin.charAt(0)=="+"&&hist.lastModTime>time-(doc.cm?doc.cm.options.historyEventDelay:500))||change.origin.charAt(0)=="*"))&&(cur=lastChangeEvent(hist,hist.lastOp==opId))){last=lst(cur.changes);if(cmp(change.from,change.to)==0&&cmp(change.from,last.to)==0){last.to=changeEnd(change);}else{cur.changes.push(historyChangeFromChange(doc,change));}}else{var before=lst(hist.done);if(!before||!before.ranges)
{pushSelectionToHistory(doc.sel,hist.done);}
cur={changes:[historyChangeFromChange(doc,change)],generation:hist.generation};hist.done.push(cur);while(hist.done.length>hist.undoDepth){hist.done.shift();if(!hist.done[0].ranges){hist.done.shift();}}}
hist.done.push(selAfter);hist.generation=++hist.maxGeneration;hist.lastModTime=hist.lastSelTime=time;hist.lastOp=hist.lastSelOp=opId;hist.lastOrigin=hist.lastSelOrigin=change.origin;if(!last){signal(doc,"historyAdded");}}
function selectionEventCanBeMerged(doc,origin,prev,sel){var ch=origin.charAt(0);return ch=="*"||ch=="+"&&prev.ranges.length==sel.ranges.length&&prev.somethingSelected()==sel.somethingSelected()&&new Date-doc.history.lastSelTime<=(doc.cm?doc.cm.options.historyEventDelay:500)}
function addSelectionToHistory(doc,sel,opId,options){var hist=doc.history,origin=options&&options.origin;if(opId==hist.lastSelOp||(origin&&hist.lastSelOrigin==origin&&(hist.lastModTime==hist.lastSelTime&&hist.lastOrigin==origin||selectionEventCanBeMerged(doc,origin,lst(hist.done),sel))))
{hist.done[hist.done.length-1]=sel;}
else
{pushSelectionToHistory(sel,hist.done);}
hist.lastSelTime=+new Date;hist.lastSelOrigin=origin;hist.lastSelOp=opId;if(options&&options.clearRedo!==false)
{clearSelectionEvents(hist.undone);}}
function pushSelectionToHistory(sel,dest){var top=lst(dest);if(!(top&&top.ranges&&top.equals(sel)))
{dest.push(sel);}}
function attachLocalSpans(doc,change,from,to){var existing=change["spans_"+doc.id],n=0;doc.iter(Math.max(doc.first,from),Math.min(doc.first+doc.size,to),function(line){if(line.markedSpans)
{(existing||(existing=change["spans_"+doc.id]={}))[n]=line.markedSpans;}
++n;});}
function removeClearedSpans(spans){if(!spans){return null}
var out;for(var i=0;i<spans.length;++i){if(spans[i].marker.explicitlyCleared){if(!out){out=spans.slice(0,i);}}
else if(out){out.push(spans[i]);}}
return!out?spans:out.length?out:null}
function getOldSpans(doc,change){var found=change["spans_"+doc.id];if(!found){return null}
var nw=[];for(var i=0;i<change.text.length;++i)
{nw.push(removeClearedSpans(found[i]));}
return nw}
function mergeOldSpans(doc,change){var old=getOldSpans(doc,change);var stretched=stretchSpansOverChange(doc,change);if(!old){return stretched}
if(!stretched){return old}
for(var i=0;i<old.length;++i){var oldCur=old[i],stretchCur=stretched[i];if(oldCur&&stretchCur){spans:for(var j=0;j<stretchCur.length;++j){var span=stretchCur[j];for(var k=0;k<oldCur.length;++k)
{if(oldCur[k].marker==span.marker){continue spans}}
oldCur.push(span);}}else if(stretchCur){old[i]=stretchCur;}}
return old}
function copyHistoryArray(events,newGroup,instantiateSel){var copy=[];for(var i=0;i<events.length;++i){var event=events[i];if(event.ranges){copy.push(instantiateSel?Selection.prototype.deepCopy.call(event):event);continue}
var changes=event.changes,newChanges=[];copy.push({changes:newChanges});for(var j=0;j<changes.length;++j){var change=changes[j],m=(void 0);newChanges.push({from:change.from,to:change.to,text:change.text});if(newGroup){for(var prop in change){if(m=prop.match(/^spans_(\d+)$/)){if(indexOf(newGroup,Number(m[1]))>-1){lst(newChanges)[prop]=change[prop];delete change[prop];}}}}}}
return copy}
function extendRange(range,head,other,extend){if(extend){var anchor=range.anchor;if(other){var posBefore=cmp(head,anchor)<0;if(posBefore!=(cmp(other,anchor)<0)){anchor=head;head=other;}else if(posBefore!=(cmp(head,other)<0)){head=other;}}
return new Range(anchor,head)}else{return new Range(other||head,head)}}
function extendSelection(doc,head,other,options,extend){if(extend==null){extend=doc.cm&&(doc.cm.display.shift||doc.extend);}
setSelection(doc,new Selection([extendRange(doc.sel.primary(),head,other,extend)],0),options);}
function extendSelections(doc,heads,options){var out=[];var extend=doc.cm&&(doc.cm.display.shift||doc.extend);for(var i=0;i<doc.sel.ranges.length;i++)
{out[i]=extendRange(doc.sel.ranges[i],heads[i],null,extend);}
var newSel=normalizeSelection(doc.cm,out,doc.sel.primIndex);setSelection(doc,newSel,options);}
function replaceOneSelection(doc,i,range,options){var ranges=doc.sel.ranges.slice(0);ranges[i]=range;setSelection(doc,normalizeSelection(doc.cm,ranges,doc.sel.primIndex),options);}
function setSimpleSelection(doc,anchor,head,options){setSelection(doc,simpleSelection(anchor,head),options);}
function filterSelectionChange(doc,sel,options){var obj={ranges:sel.ranges,update:function(ranges){this.ranges=[];for(var i=0;i<ranges.length;i++)
{this.ranges[i]=new Range(clipPos(doc,ranges[i].anchor),clipPos(doc,ranges[i].head));}},origin:options&&options.origin};signal(doc,"beforeSelectionChange",doc,obj);if(doc.cm){signal(doc.cm,"beforeSelectionChange",doc.cm,obj);}
if(obj.ranges!=sel.ranges){return normalizeSelection(doc.cm,obj.ranges,obj.ranges.length-1)}
else{return sel}}
function setSelectionReplaceHistory(doc,sel,options){var done=doc.history.done,last=lst(done);if(last&&last.ranges){done[done.length-1]=sel;setSelectionNoUndo(doc,sel,options);}else{setSelection(doc,sel,options);}}
function setSelection(doc,sel,options){setSelectionNoUndo(doc,sel,options);addSelectionToHistory(doc,doc.sel,doc.cm?doc.cm.curOp.id:NaN,options);}
function setSelectionNoUndo(doc,sel,options){if(hasHandler(doc,"beforeSelectionChange")||doc.cm&&hasHandler(doc.cm,"beforeSelectionChange"))
{sel=filterSelectionChange(doc,sel,options);}
var bias=options&&options.bias||(cmp(sel.primary().head,doc.sel.primary().head)<0?-1:1);setSelectionInner(doc,skipAtomicInSelection(doc,sel,bias,true));if(!(options&&options.scroll===false)&&doc.cm)
{ensureCursorVisible(doc.cm);}}
function setSelectionInner(doc,sel){if(sel.equals(doc.sel)){return}
doc.sel=sel;if(doc.cm){doc.cm.curOp.updateInput=1;doc.cm.curOp.selectionChanged=true;signalCursorActivity(doc.cm);}
signalLater(doc,"cursorActivity",doc);}
function reCheckSelection(doc){setSelectionInner(doc,skipAtomicInSelection(doc,doc.sel,null,false));}
function skipAtomicInSelection(doc,sel,bias,mayClear){var out;for(var i=0;i<sel.ranges.length;i++){var range=sel.ranges[i];var old=sel.ranges.length==doc.sel.ranges.length&&doc.sel.ranges[i];var newAnchor=skipAtomic(doc,range.anchor,old&&old.anchor,bias,mayClear);var newHead=skipAtomic(doc,range.head,old&&old.head,bias,mayClear);if(out||newAnchor!=range.anchor||newHead!=range.head){if(!out){out=sel.ranges.slice(0,i);}
out[i]=new Range(newAnchor,newHead);}}
return out?normalizeSelection(doc.cm,out,sel.primIndex):sel}
function skipAtomicInner(doc,pos,oldPos,dir,mayClear){var line=getLine(doc,pos.line);if(line.markedSpans){for(var i=0;i<line.markedSpans.length;++i){var sp=line.markedSpans[i],m=sp.marker;if((sp.from==null||(m.inclusiveLeft?sp.from<=pos.ch:sp.from<pos.ch))&&(sp.to==null||(m.inclusiveRight?sp.to>=pos.ch:sp.to>pos.ch))){if(mayClear){signal(m,"beforeCursorEnter");if(m.explicitlyCleared){if(!line.markedSpans){break}
else{--i;continue}}}
if(!m.atomic){continue}
if(oldPos){var near=m.find(dir<0?1:-1),diff=(void 0);if(dir<0?m.inclusiveRight:m.inclusiveLeft)
{near=movePos(doc,near,-dir,near&&near.line==pos.line?line:null);}
if(near&&near.line==pos.line&&(diff=cmp(near,oldPos))&&(dir<0?diff<0:diff>0))
{return skipAtomicInner(doc,near,pos,dir,mayClear)}}
var far=m.find(dir<0?-1:1);if(dir<0?m.inclusiveLeft:m.inclusiveRight)
{far=movePos(doc,far,dir,far.line==pos.line?line:null);}
return far?skipAtomicInner(doc,far,pos,dir,mayClear):null}}}
return pos}
function skipAtomic(doc,pos,oldPos,bias,mayClear){var dir=bias||1;var found=skipAtomicInner(doc,pos,oldPos,dir,mayClear)||(!mayClear&&skipAtomicInner(doc,pos,oldPos,dir,true))||skipAtomicInner(doc,pos,oldPos,-dir,mayClear)||(!mayClear&&skipAtomicInner(doc,pos,oldPos,-dir,true));if(!found){doc.cantEdit=true;return Pos(doc.first,0)}
return found}
function movePos(doc,pos,dir,line){if(dir<0&&pos.ch==0){if(pos.line>doc.first){return clipPos(doc,Pos(pos.line-1))}
else{return null}}else if(dir>0&&pos.ch==(line||getLine(doc,pos.line)).text.length){if(pos.line<doc.first+doc.size-1){return Pos(pos.line+1,0)}
else{return null}}else{return new Pos(pos.line,pos.ch+dir)}}
function selectAll(cm){cm.setSelection(Pos(cm.firstLine(),0),Pos(cm.lastLine()),sel_dontScroll);}
function filterChange(doc,change,update){var obj={canceled:false,from:change.from,to:change.to,text:change.text,origin:change.origin,cancel:function(){return obj.canceled=true;}};if(update){obj.update=function(from,to,text,origin){if(from){obj.from=clipPos(doc,from);}
if(to){obj.to=clipPos(doc,to);}
if(text){obj.text=text;}
if(origin!==undefined){obj.origin=origin;}};}
signal(doc,"beforeChange",doc,obj);if(doc.cm){signal(doc.cm,"beforeChange",doc.cm,obj);}
if(obj.canceled){if(doc.cm){doc.cm.curOp.updateInput=2;}
return null}
return{from:obj.from,to:obj.to,text:obj.text,origin:obj.origin}}
function makeChange(doc,change,ignoreReadOnly){if(doc.cm){if(!doc.cm.curOp){return operation(doc.cm,makeChange)(doc,change,ignoreReadOnly)}
if(doc.cm.state.suppressEdits){return}}
if(hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange")){change=filterChange(doc,change,true);if(!change){return}}
var split=sawReadOnlySpans&&!ignoreReadOnly&&removeReadOnlyRanges(doc,change.from,change.to);if(split){for(var i=split.length-1;i>=0;--i)
{makeChangeInner(doc,{from:split[i].from,to:split[i].to,text:i?[""]:change.text,origin:change.origin});}}else{makeChangeInner(doc,change);}}
function makeChangeInner(doc,change){if(change.text.length==1&&change.text[0]==""&&cmp(change.from,change.to)==0){return}
var selAfter=computeSelAfterChange(doc,change);addChangeToHistory(doc,change,selAfter,doc.cm?doc.cm.curOp.id:NaN);makeChangeSingleDoc(doc,change,selAfter,stretchSpansOverChange(doc,change));var rebased=[];linkedDocs(doc,function(doc,sharedHist){if(!sharedHist&&indexOf(rebased,doc.history)==-1){rebaseHist(doc.history,change);rebased.push(doc.history);}
makeChangeSingleDoc(doc,change,null,stretchSpansOverChange(doc,change));});}
function makeChangeFromHistory(doc,type,allowSelectionOnly){var suppress=doc.cm&&doc.cm.state.suppressEdits;if(suppress&&!allowSelectionOnly){return}
var hist=doc.history,event,selAfter=doc.sel;var source=type=="undo"?hist.done:hist.undone,dest=type=="undo"?hist.undone:hist.done;var i=0;for(;i<source.length;i++){event=source[i];if(allowSelectionOnly?event.ranges&&!event.equals(doc.sel):!event.ranges)
{break}}
if(i==source.length){return}
hist.lastOrigin=hist.lastSelOrigin=null;for(;;){event=source.pop();if(event.ranges){pushSelectionToHistory(event,dest);if(allowSelectionOnly&&!event.equals(doc.sel)){setSelection(doc,event,{clearRedo:false});return}
selAfter=event;}else if(suppress){source.push(event);return}else{break}}
var antiChanges=[];pushSelectionToHistory(selAfter,dest);dest.push({changes:antiChanges,generation:hist.generation});hist.generation=event.generation||++hist.maxGeneration;var filter=hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange");var loop=function(i){var change=event.changes[i];change.origin=type;if(filter&&!filterChange(doc,change,false)){source.length=0;return{}}
antiChanges.push(historyChangeFromChange(doc,change));var after=i?computeSelAfterChange(doc,change):lst(source);makeChangeSingleDoc(doc,change,after,mergeOldSpans(doc,change));if(!i&&doc.cm){doc.cm.scrollIntoView({from:change.from,to:changeEnd(change)});}
var rebased=[];linkedDocs(doc,function(doc,sharedHist){if(!sharedHist&&indexOf(rebased,doc.history)==-1){rebaseHist(doc.history,change);rebased.push(doc.history);}
makeChangeSingleDoc(doc,change,null,mergeOldSpans(doc,change));});};for(var i$1=event.changes.length-1;i$1>=0;--i$1){var returned=loop(i$1);if(returned)return returned.v;}}
function shiftDoc(doc,distance){if(distance==0){return}
doc.first+=distance;doc.sel=new Selection(map(doc.sel.ranges,function(range){return new Range(Pos(range.anchor.line+distance,range.anchor.ch),Pos(range.head.line+distance,range.head.ch));}),doc.sel.primIndex);if(doc.cm){regChange(doc.cm,doc.first,doc.first-distance,distance);for(var d=doc.cm.display,l=d.viewFrom;l<d.viewTo;l++)
{regLineChange(doc.cm,l,"gutter");}}}
function makeChangeSingleDoc(doc,change,selAfter,spans){if(doc.cm&&!doc.cm.curOp)
{return operation(doc.cm,makeChangeSingleDoc)(doc,change,selAfter,spans)}
if(change.to.line<doc.first){shiftDoc(doc,change.text.length-1-(change.to.line-change.from.line));return}
if(change.from.line>doc.lastLine()){return}
if(change.from.line<doc.first){var shift=change.text.length-1-(doc.first-change.from.line);shiftDoc(doc,shift);change={from:Pos(doc.first,0),to:Pos(change.to.line+shift,change.to.ch),text:[lst(change.text)],origin:change.origin};}
var last=doc.lastLine();if(change.to.line>last){change={from:change.from,to:Pos(last,getLine(doc,last).text.length),text:[change.text[0]],origin:change.origin};}
change.removed=getBetween(doc,change.from,change.to);if(!selAfter){selAfter=computeSelAfterChange(doc,change);}
if(doc.cm){makeChangeSingleDocInEditor(doc.cm,change,spans);}
else{updateDoc(doc,change,spans);}
setSelectionNoUndo(doc,selAfter,sel_dontScroll);}
function makeChangeSingleDocInEditor(cm,change,spans){var doc=cm.doc,display=cm.display,from=change.from,to=change.to;var recomputeMaxLength=false,checkWidthStart=from.line;if(!cm.options.lineWrapping){checkWidthStart=lineNo(visualLine(getLine(doc,from.line)));doc.iter(checkWidthStart,to.line+1,function(line){if(line==display.maxLine){recomputeMaxLength=true;return true}});}
if(doc.sel.contains(change.from,change.to)>-1)
{signalCursorActivity(cm);}
updateDoc(doc,change,spans,estimateHeight(cm));if(!cm.options.lineWrapping){doc.iter(checkWidthStart,from.line+change.text.length,function(line){var len=lineLength(line);if(len>display.maxLineLength){display.maxLine=line;display.maxLineLength=len;display.maxLineChanged=true;recomputeMaxLength=false;}});if(recomputeMaxLength){cm.curOp.updateMaxLine=true;}}
retreatFrontier(doc,from.line);startWorker(cm,400);var lendiff=change.text.length-(to.line-from.line)-1;if(change.full)
{regChange(cm);}
else if(from.line==to.line&&change.text.length==1&&!isWholeLineUpdate(cm.doc,change))
{regLineChange(cm,from.line,"text");}
else
{regChange(cm,from.line,to.line+1,lendiff);}
var changesHandler=hasHandler(cm,"changes"),changeHandler=hasHandler(cm,"change");if(changeHandler||changesHandler){var obj={from:from,to:to,text:change.text,removed:change.removed,origin:change.origin};if(changeHandler){signalLater(cm,"change",cm,obj);}
if(changesHandler){(cm.curOp.changeObjs||(cm.curOp.changeObjs=[])).push(obj);}}
cm.display.selForContextMenu=null;}
function replaceRange(doc,code,from,to,origin){var assign;if(!to){to=from;}
if(cmp(to,from)<0){(assign=[to,from],from=assign[0],to=assign[1]);}
if(typeof code=="string"){code=doc.splitLines(code);}
makeChange(doc,{from:from,to:to,text:code,origin:origin});}
function rebaseHistSelSingle(pos,from,to,diff){if(to<pos.line){pos.line+=diff;}else if(from<pos.line){pos.line=from;pos.ch=0;}}
function rebaseHistArray(array,from,to,diff){for(var i=0;i<array.length;++i){var sub=array[i],ok=true;if(sub.ranges){if(!sub.copied){sub=array[i]=sub.deepCopy();sub.copied=true;}
for(var j=0;j<sub.ranges.length;j++){rebaseHistSelSingle(sub.ranges[j].anchor,from,to,diff);rebaseHistSelSingle(sub.ranges[j].head,from,to,diff);}
continue}
for(var j$1=0;j$1<sub.changes.length;++j$1){var cur=sub.changes[j$1];if(to<cur.from.line){cur.from=Pos(cur.from.line+diff,cur.from.ch);cur.to=Pos(cur.to.line+diff,cur.to.ch);}else if(from<=cur.to.line){ok=false;break}}
if(!ok){array.splice(0,i+1);i=0;}}}
function rebaseHist(hist,change){var from=change.from.line,to=change.to.line,diff=change.text.length-(to-from)-1;rebaseHistArray(hist.done,from,to,diff);rebaseHistArray(hist.undone,from,to,diff);}
function changeLine(doc,handle,changeType,op){var no=handle,line=handle;if(typeof handle=="number"){line=getLine(doc,clipLine(doc,handle));}
else{no=lineNo(handle);}
if(no==null){return null}
if(op(line,no)&&doc.cm){regLineChange(doc.cm,no,changeType);}
return line}
function LeafChunk(lines){this.lines=lines;this.parent=null;var height=0;for(var i=0;i<lines.length;++i){lines[i].parent=this;height+=lines[i].height;}
this.height=height;}
LeafChunk.prototype={chunkSize:function(){return this.lines.length},removeInner:function(at,n){for(var i=at,e=at+n;i<e;++i){var line=this.lines[i];this.height-=line.height;cleanUpLine(line);signalLater(line,"delete");}
this.lines.splice(at,n);},collapse:function(lines){lines.push.apply(lines,this.lines);},insertInner:function(at,lines,height){this.height+=height;this.lines=this.lines.slice(0,at).concat(lines).concat(this.lines.slice(at));for(var i=0;i<lines.length;++i){lines[i].parent=this;}},iterN:function(at,n,op){for(var e=at+n;at<e;++at)
{if(op(this.lines[at])){return true}}}};function BranchChunk(children){this.children=children;var size=0,height=0;for(var i=0;i<children.length;++i){var ch=children[i];size+=ch.chunkSize();height+=ch.height;ch.parent=this;}
this.size=size;this.height=height;this.parent=null;}
BranchChunk.prototype={chunkSize:function(){return this.size},removeInner:function(at,n){this.size-=n;for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(at<sz){var rm=Math.min(n,sz-at),oldHeight=child.height;child.removeInner(at,rm);this.height-=oldHeight-child.height;if(sz==rm){this.children.splice(i--,1);child.parent=null;}
if((n-=rm)==0){break}
at=0;}else{at-=sz;}}
if(this.size-n<25&&(this.children.length>1||!(this.children[0]instanceof LeafChunk))){var lines=[];this.collapse(lines);this.children=[new LeafChunk(lines)];this.children[0].parent=this;}},collapse:function(lines){for(var i=0;i<this.children.length;++i){this.children[i].collapse(lines);}},insertInner:function(at,lines,height){this.size+=lines.length;this.height+=height;for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(at<=sz){child.insertInner(at,lines,height);if(child.lines&&child.lines.length>50){var remaining=child.lines.length%25+25;for(var pos=remaining;pos<child.lines.length;){var leaf=new LeafChunk(child.lines.slice(pos,pos+=25));child.height-=leaf.height;this.children.splice(++i,0,leaf);leaf.parent=this;}
child.lines=child.lines.slice(0,remaining);this.maybeSpill();}
break}
at-=sz;}},maybeSpill:function(){if(this.children.length<=10){return}
var me=this;do{var spilled=me.children.splice(me.children.length-5,5);var sibling=new BranchChunk(spilled);if(!me.parent){var copy=new BranchChunk(me.children);copy.parent=me;me.children=[copy,sibling];me=copy;}else{me.size-=sibling.size;me.height-=sibling.height;var myIndex=indexOf(me.parent.children,me);me.parent.children.splice(myIndex+1,0,sibling);}
sibling.parent=me.parent;}while(me.children.length>10)
me.parent.maybeSpill();},iterN:function(at,n,op){for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(at<sz){var used=Math.min(n,sz-at);if(child.iterN(at,used,op)){return true}
if((n-=used)==0){break}
at=0;}else{at-=sz;}}}};var LineWidget=function(doc,node,options){if(options){for(var opt in options){if(options.hasOwnProperty(opt))
{this[opt]=options[opt];}}}
this.doc=doc;this.node=node;};LineWidget.prototype.clear=function(){var cm=this.doc.cm,ws=this.line.widgets,line=this.line,no=lineNo(line);if(no==null||!ws){return}
for(var i=0;i<ws.length;++i){if(ws[i]==this){ws.splice(i--,1);}}
if(!ws.length){line.widgets=null;}
var height=widgetHeight(this);updateLineHeight(line,Math.max(0,line.height-height));if(cm){runInOp(cm,function(){adjustScrollWhenAboveVisible(cm,line,-height);regLineChange(cm,no,"widget");});signalLater(cm,"lineWidgetCleared",cm,this,no);}};LineWidget.prototype.changed=function(){var this$1=this;var oldH=this.height,cm=this.doc.cm,line=this.line;this.height=null;var diff=widgetHeight(this)-oldH;if(!diff){return}
if(!lineIsHidden(this.doc,line)){updateLineHeight(line,line.height+diff);}
if(cm){runInOp(cm,function(){cm.curOp.forceUpdate=true;adjustScrollWhenAboveVisible(cm,line,diff);signalLater(cm,"lineWidgetChanged",cm,this$1,lineNo(line));});}};eventMixin(LineWidget);function adjustScrollWhenAboveVisible(cm,line,diff){if(heightAtLine(line)<((cm.curOp&&cm.curOp.scrollTop)||cm.doc.scrollTop))
{addToScrollTop(cm,diff);}}
function addLineWidget(doc,handle,node,options){var widget=new LineWidget(doc,node,options);var cm=doc.cm;if(cm&&widget.noHScroll){cm.display.alignWidgets=true;}
changeLine(doc,handle,"widget",function(line){var widgets=line.widgets||(line.widgets=[]);if(widget.insertAt==null){widgets.push(widget);}
else{widgets.splice(Math.min(widgets.length-1,Math.max(0,widget.insertAt)),0,widget);}
widget.line=line;if(cm&&!lineIsHidden(doc,line)){var aboveVisible=heightAtLine(line)<doc.scrollTop;updateLineHeight(line,line.height+widgetHeight(widget));if(aboveVisible){addToScrollTop(cm,widget.height);}
cm.curOp.forceUpdate=true;}
return true});if(cm){signalLater(cm,"lineWidgetAdded",cm,widget,typeof handle=="number"?handle:lineNo(handle));}
return widget}
var nextMarkerId=0;var TextMarker=function(doc,type){this.lines=[];this.type=type;this.doc=doc;this.id=++nextMarkerId;};TextMarker.prototype.clear=function(){if(this.explicitlyCleared){return}
var cm=this.doc.cm,withOp=cm&&!cm.curOp;if(withOp){startOperation(cm);}
if(hasHandler(this,"clear")){var found=this.find();if(found){signalLater(this,"clear",found.from,found.to);}}
var min=null,max=null;for(var i=0;i<this.lines.length;++i){var line=this.lines[i];var span=getMarkedSpanFor(line.markedSpans,this);if(cm&&!this.collapsed){regLineChange(cm,lineNo(line),"text");}
else if(cm){if(span.to!=null){max=lineNo(line);}
if(span.from!=null){min=lineNo(line);}}
line.markedSpans=removeMarkedSpan(line.markedSpans,span);if(span.from==null&&this.collapsed&&!lineIsHidden(this.doc,line)&&cm)
{updateLineHeight(line,textHeight(cm.display));}}
if(cm&&this.collapsed&&!cm.options.lineWrapping){for(var i$1=0;i$1<this.lines.length;++i$1){var visual=visualLine(this.lines[i$1]),len=lineLength(visual);if(len>cm.display.maxLineLength){cm.display.maxLine=visual;cm.display.maxLineLength=len;cm.display.maxLineChanged=true;}}}
if(min!=null&&cm&&this.collapsed){regChange(cm,min,max+1);}
this.lines.length=0;this.explicitlyCleared=true;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=false;if(cm){reCheckSelection(cm.doc);}}
if(cm){signalLater(cm,"markerCleared",cm,this,min,max);}
if(withOp){endOperation(cm);}
if(this.parent){this.parent.clear();}};TextMarker.prototype.find=function(side,lineObj){if(side==null&&this.type=="bookmark"){side=1;}
var from,to;for(var i=0;i<this.lines.length;++i){var line=this.lines[i];var span=getMarkedSpanFor(line.markedSpans,this);if(span.from!=null){from=Pos(lineObj?line:lineNo(line),span.from);if(side==-1){return from}}
if(span.to!=null){to=Pos(lineObj?line:lineNo(line),span.to);if(side==1){return to}}}
return from&&{from:from,to:to}};TextMarker.prototype.changed=function(){var this$1=this;var pos=this.find(-1,true),widget=this,cm=this.doc.cm;if(!pos||!cm){return}
runInOp(cm,function(){var line=pos.line,lineN=lineNo(pos.line);var view=findViewForLine(cm,lineN);if(view){clearLineMeasurementCacheFor(view);cm.curOp.selectionChanged=cm.curOp.forceUpdate=true;}
cm.curOp.updateMaxLine=true;if(!lineIsHidden(widget.doc,line)&&widget.height!=null){var oldHeight=widget.height;widget.height=null;var dHeight=widgetHeight(widget)-oldHeight;if(dHeight)
{updateLineHeight(line,line.height+dHeight);}}
signalLater(cm,"markerChanged",cm,this$1);});};TextMarker.prototype.attachLine=function(line){if(!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp;if(!op.maybeHiddenMarkers||indexOf(op.maybeHiddenMarkers,this)==-1)
{(op.maybeUnhiddenMarkers||(op.maybeUnhiddenMarkers=[])).push(this);}}
this.lines.push(line);};TextMarker.prototype.detachLine=function(line){this.lines.splice(indexOf(this.lines,line),1);if(!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp;(op.maybeHiddenMarkers||(op.maybeHiddenMarkers=[])).push(this);}};eventMixin(TextMarker);function markText(doc,from,to,options,type){if(options&&options.shared){return markTextShared(doc,from,to,options,type)}
if(doc.cm&&!doc.cm.curOp){return operation(doc.cm,markText)(doc,from,to,options,type)}
var marker=new TextMarker(doc,type),diff=cmp(from,to);if(options){copyObj(options,marker,false);}
if(diff>0||diff==0&&marker.clearWhenEmpty!==false)
{return marker}
if(marker.replacedWith){marker.collapsed=true;marker.widgetNode=eltP("span",[marker.replacedWith],"CodeMirror-widget");if(!options.handleMouseEvents){marker.widgetNode.setAttribute("cm-ignore-events","true");}
if(options.insertLeft){marker.widgetNode.insertLeft=true;}}
if(marker.collapsed){if(conflictingCollapsedRange(doc,from.line,from,to,marker)||from.line!=to.line&&conflictingCollapsedRange(doc,to.line,from,to,marker))
{throw new Error("Inserting collapsed marker partially overlapping an existing one")}
seeCollapsedSpans();}
if(marker.addToHistory)
{addChangeToHistory(doc,{from:from,to:to,origin:"markText"},doc.sel,NaN);}
var curLine=from.line,cm=doc.cm,updateMaxLine;doc.iter(curLine,to.line+1,function(line){if(cm&&marker.collapsed&&!cm.options.lineWrapping&&visualLine(line)==cm.display.maxLine)
{updateMaxLine=true;}
if(marker.collapsed&&curLine!=from.line){updateLineHeight(line,0);}
addMarkedSpan(line,new MarkedSpan(marker,curLine==from.line?from.ch:null,curLine==to.line?to.ch:null));++curLine;});if(marker.collapsed){doc.iter(from.line,to.line+1,function(line){if(lineIsHidden(doc,line)){updateLineHeight(line,0);}});}
if(marker.clearOnEnter){on(marker,"beforeCursorEnter",function(){return marker.clear();});}
if(marker.readOnly){seeReadOnlySpans();if(doc.history.done.length||doc.history.undone.length)
{doc.clearHistory();}}
if(marker.collapsed){marker.id=++nextMarkerId;marker.atomic=true;}
if(cm){if(updateMaxLine){cm.curOp.updateMaxLine=true;}
if(marker.collapsed)
{regChange(cm,from.line,to.line+1);}
else if(marker.className||marker.startStyle||marker.endStyle||marker.css||marker.attributes||marker.title)
{for(var i=from.line;i<=to.line;i++){regLineChange(cm,i,"text");}}
if(marker.atomic){reCheckSelection(cm.doc);}
signalLater(cm,"markerAdded",cm,marker);}
return marker}
var SharedTextMarker=function(markers,primary){this.markers=markers;this.primary=primary;for(var i=0;i<markers.length;++i)
{markers[i].parent=this;}};SharedTextMarker.prototype.clear=function(){if(this.explicitlyCleared){return}
this.explicitlyCleared=true;for(var i=0;i<this.markers.length;++i)
{this.markers[i].clear();}
signalLater(this,"clear");};SharedTextMarker.prototype.find=function(side,lineObj){return this.primary.find(side,lineObj)};eventMixin(SharedTextMarker);function markTextShared(doc,from,to,options,type){options=copyObj(options);options.shared=false;var markers=[markText(doc,from,to,options,type)],primary=markers[0];var widget=options.widgetNode;linkedDocs(doc,function(doc){if(widget){options.widgetNode=widget.cloneNode(true);}
markers.push(markText(doc,clipPos(doc,from),clipPos(doc,to),options,type));for(var i=0;i<doc.linked.length;++i)
{if(doc.linked[i].isParent){return}}
primary=lst(markers);});return new SharedTextMarker(markers,primary)}
function findSharedMarkers(doc){return doc.findMarks(Pos(doc.first,0),doc.clipPos(Pos(doc.lastLine())),function(m){return m.parent;})}
function copySharedMarkers(doc,markers){for(var i=0;i<markers.length;i++){var marker=markers[i],pos=marker.find();var mFrom=doc.clipPos(pos.from),mTo=doc.clipPos(pos.to);if(cmp(mFrom,mTo)){var subMark=markText(doc,mFrom,mTo,marker.primary,marker.primary.type);marker.markers.push(subMark);subMark.parent=marker;}}}
function detachSharedMarkers(markers){var loop=function(i){var marker=markers[i],linked=[marker.primary.doc];linkedDocs(marker.primary.doc,function(d){return linked.push(d);});for(var j=0;j<marker.markers.length;j++){var subMarker=marker.markers[j];if(indexOf(linked,subMarker.doc)==-1){subMarker.parent=null;marker.markers.splice(j--,1);}}};for(var i=0;i<markers.length;i++)loop(i);}
var nextDocId=0;var Doc=function(text,mode,firstLine,lineSep,direction){if(!(this instanceof Doc)){return new Doc(text,mode,firstLine,lineSep,direction)}
if(firstLine==null){firstLine=0;}
BranchChunk.call(this,[new LeafChunk([new Line("",null)])]);this.first=firstLine;this.scrollTop=this.scrollLeft=0;this.cantEdit=false;this.cleanGeneration=1;this.modeFrontier=this.highlightFrontier=firstLine;var start=Pos(firstLine,0);this.sel=simpleSelection(start);this.history=new History(null);this.id=++nextDocId;this.modeOption=mode;this.lineSep=lineSep;this.direction=(direction=="rtl")?"rtl":"ltr";this.extend=false;if(typeof text=="string"){text=this.splitLines(text);}
updateDoc(this,{from:start,to:start,text:text});setSelection(this,simpleSelection(start),sel_dontScroll);};Doc.prototype=createObj(BranchChunk.prototype,{constructor:Doc,iter:function(from,to,op){if(op){this.iterN(from-this.first,to-from,op);}
else{this.iterN(this.first,this.first+this.size,from);}},insert:function(at,lines){var height=0;for(var i=0;i<lines.length;++i){height+=lines[i].height;}
this.insertInner(at-this.first,lines,height);},remove:function(at,n){this.removeInner(at-this.first,n);},getValue:function(lineSep){var lines=getLines(this,this.first,this.first+this.size);if(lineSep===false){return lines}
return lines.join(lineSep||this.lineSeparator())},setValue:docMethodOp(function(code){var top=Pos(this.first,0),last=this.first+this.size-1;makeChange(this,{from:top,to:Pos(last,getLine(this,last).text.length),text:this.splitLines(code),origin:"setValue",full:true},true);if(this.cm){scrollToCoords(this.cm,0,0);}
setSelection(this,simpleSelection(top),sel_dontScroll);}),replaceRange:function(code,from,to,origin){from=clipPos(this,from);to=to?clipPos(this,to):from;replaceRange(this,code,from,to,origin);},getRange:function(from,to,lineSep){var lines=getBetween(this,clipPos(this,from),clipPos(this,to));if(lineSep===false){return lines}
return lines.join(lineSep||this.lineSeparator())},getLine:function(line){var l=this.getLineHandle(line);return l&&l.text},getLineHandle:function(line){if(isLine(this,line)){return getLine(this,line)}},getLineNumber:function(line){return lineNo(line)},getLineHandleVisualStart:function(line){if(typeof line=="number"){line=getLine(this,line);}
return visualLine(line)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(pos){return clipPos(this,pos)},getCursor:function(start){var range$$1=this.sel.primary(),pos;if(start==null||start=="head"){pos=range$$1.head;}
else if(start=="anchor"){pos=range$$1.anchor;}
else if(start=="end"||start=="to"||start===false){pos=range$$1.to();}
else{pos=range$$1.from();}
return pos},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:docMethodOp(function(line,ch,options){setSimpleSelection(this,clipPos(this,typeof line=="number"?Pos(line,ch||0):line),null,options);}),setSelection:docMethodOp(function(anchor,head,options){setSimpleSelection(this,clipPos(this,anchor),clipPos(this,head||anchor),options);}),extendSelection:docMethodOp(function(head,other,options){extendSelection(this,clipPos(this,head),other&&clipPos(this,other),options);}),extendSelections:docMethodOp(function(heads,options){extendSelections(this,clipPosArray(this,heads),options);}),extendSelectionsBy:docMethodOp(function(f,options){var heads=map(this.sel.ranges,f);extendSelections(this,clipPosArray(this,heads),options);}),setSelections:docMethodOp(function(ranges,primary,options){if(!ranges.length){return}
var out=[];for(var i=0;i<ranges.length;i++)
{out[i]=new Range(clipPos(this,ranges[i].anchor),clipPos(this,ranges[i].head));}
if(primary==null){primary=Math.min(ranges.length-1,this.sel.primIndex);}
setSelection(this,normalizeSelection(this.cm,out,primary),options);}),addSelection:docMethodOp(function(anchor,head,options){var ranges=this.sel.ranges.slice(0);ranges.push(new Range(clipPos(this,anchor),clipPos(this,head||anchor)));setSelection(this,normalizeSelection(this.cm,ranges,ranges.length-1),options);}),getSelection:function(lineSep){var ranges=this.sel.ranges,lines;for(var i=0;i<ranges.length;i++){var sel=getBetween(this,ranges[i].from(),ranges[i].to());lines=lines?lines.concat(sel):sel;}
if(lineSep===false){return lines}
else{return lines.join(lineSep||this.lineSeparator())}},getSelections:function(lineSep){var parts=[],ranges=this.sel.ranges;for(var i=0;i<ranges.length;i++){var sel=getBetween(this,ranges[i].from(),ranges[i].to());if(lineSep!==false){sel=sel.join(lineSep||this.lineSeparator());}
parts[i]=sel;}
return parts},replaceSelection:function(code,collapse,origin){var dup=[];for(var i=0;i<this.sel.ranges.length;i++)
{dup[i]=code;}
this.replaceSelections(dup,collapse,origin||"+input");},replaceSelections:docMethodOp(function(code,collapse,origin){var changes=[],sel=this.sel;for(var i=0;i<sel.ranges.length;i++){var range$$1=sel.ranges[i];changes[i]={from:range$$1.from(),to:range$$1.to(),text:this.splitLines(code[i]),origin:origin};}
var newSel=collapse&&collapse!="end"&&computeReplacedSel(this,changes,collapse);for(var i$1=changes.length-1;i$1>=0;i$1--)
{makeChange(this,changes[i$1]);}
if(newSel){setSelectionReplaceHistory(this,newSel);}
else if(this.cm){ensureCursorVisible(this.cm);}}),undo:docMethodOp(function(){makeChangeFromHistory(this,"undo");}),redo:docMethodOp(function(){makeChangeFromHistory(this,"redo");}),undoSelection:docMethodOp(function(){makeChangeFromHistory(this,"undo",true);}),redoSelection:docMethodOp(function(){makeChangeFromHistory(this,"redo",true);}),setExtending:function(val){this.extend=val;},getExtending:function(){return this.extend},historySize:function(){var hist=this.history,done=0,undone=0;for(var i=0;i<hist.done.length;i++){if(!hist.done[i].ranges){++done;}}
for(var i$1=0;i$1<hist.undone.length;i$1++){if(!hist.undone[i$1].ranges){++undone;}}
return{undo:done,redo:undone}},clearHistory:function(){this.history=new History(this.history.maxGeneration);},markClean:function(){this.cleanGeneration=this.changeGeneration(true);},changeGeneration:function(forceSplit){if(forceSplit)
{this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null;}
return this.history.generation},isClean:function(gen){return this.history.generation==(gen||this.cleanGeneration)},getHistory:function(){return{done:copyHistoryArray(this.history.done),undone:copyHistoryArray(this.history.undone)}},setHistory:function(histData){var hist=this.history=new History(this.history.maxGeneration);hist.done=copyHistoryArray(histData.done.slice(0),null,true);hist.undone=copyHistoryArray(histData.undone.slice(0),null,true);},setGutterMarker:docMethodOp(function(line,gutterID,value){return changeLine(this,line,"gutter",function(line){var markers=line.gutterMarkers||(line.gutterMarkers={});markers[gutterID]=value;if(!value&&isEmpty(markers)){line.gutterMarkers=null;}
return true})}),clearGutter:docMethodOp(function(gutterID){var this$1=this;this.iter(function(line){if(line.gutterMarkers&&line.gutterMarkers[gutterID]){changeLine(this$1,line,"gutter",function(){line.gutterMarkers[gutterID]=null;if(isEmpty(line.gutterMarkers)){line.gutterMarkers=null;}
return true});}});}),lineInfo:function(line){var n;if(typeof line=="number"){if(!isLine(this,line)){return null}
n=line;line=getLine(this,line);if(!line){return null}}else{n=lineNo(line);if(n==null){return null}}
return{line:n,handle:line,text:line.text,gutterMarkers:line.gutterMarkers,textClass:line.textClass,bgClass:line.bgClass,wrapClass:line.wrapClass,widgets:line.widgets}},addLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,where=="gutter"?"gutter":"class",function(line){var prop=where=="text"?"textClass":where=="background"?"bgClass":where=="gutter"?"gutterClass":"wrapClass";if(!line[prop]){line[prop]=cls;}
else if(classTest(cls).test(line[prop])){return false}
else{line[prop]+=" "+cls;}
return true})}),removeLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,where=="gutter"?"gutter":"class",function(line){var prop=where=="text"?"textClass":where=="background"?"bgClass":where=="gutter"?"gutterClass":"wrapClass";var cur=line[prop];if(!cur){return false}
else if(cls==null){line[prop]=null;}
else{var found=cur.match(classTest(cls));if(!found){return false}
var end=found.index+found[0].length;line[prop]=cur.slice(0,found.index)+(!found.index||end==cur.length?"":" ")+cur.slice(end)||null;}
return true})}),addLineWidget:docMethodOp(function(handle,node,options){return addLineWidget(this,handle,node,options)}),removeLineWidget:function(widget){widget.clear();},markText:function(from,to,options){return markText(this,clipPos(this,from),clipPos(this,to),options,options&&options.type||"range")},setBookmark:function(pos,options){var realOpts={replacedWith:options&&(options.nodeType==null?options.widget:options),insertLeft:options&&options.insertLeft,clearWhenEmpty:false,shared:options&&options.shared,handleMouseEvents:options&&options.handleMouseEvents};pos=clipPos(this,pos);return markText(this,pos,pos,realOpts,"bookmark")},findMarksAt:function(pos){pos=clipPos(this,pos);var markers=[],spans=getLine(this,pos.line).markedSpans;if(spans){for(var i=0;i<spans.length;++i){var span=spans[i];if((span.from==null||span.from<=pos.ch)&&(span.to==null||span.to>=pos.ch))
{markers.push(span.marker.parent||span.marker);}}}
return markers},findMarks:function(from,to,filter){from=clipPos(this,from);to=clipPos(this,to);var found=[],lineNo$$1=from.line;this.iter(from.line,to.line+1,function(line){var spans=line.markedSpans;if(spans){for(var i=0;i<spans.length;i++){var span=spans[i];if(!(span.to!=null&&lineNo$$1==from.line&&from.ch>=span.to||span.from==null&&lineNo$$1!=from.line||span.from!=null&&lineNo$$1==to.line&&span.from>=to.ch)&&(!filter||filter(span.marker)))
{found.push(span.marker.parent||span.marker);}}}
++lineNo$$1;});return found},getAllMarks:function(){var markers=[];this.iter(function(line){var sps=line.markedSpans;if(sps){for(var i=0;i<sps.length;++i)
{if(sps[i].from!=null){markers.push(sps[i].marker);}}}});return markers},posFromIndex:function(off){var ch,lineNo$$1=this.first,sepSize=this.lineSeparator().length;this.iter(function(line){var sz=line.text.length+sepSize;if(sz>off){ch=off;return true}
off-=sz;++lineNo$$1;});return clipPos(this,Pos(lineNo$$1,ch))},indexFromPos:function(coords){coords=clipPos(this,coords);var index=coords.ch;if(coords.line<this.first||coords.ch<0){return 0}
var sepSize=this.lineSeparator().length;this.iter(this.first,coords.line,function(line){index+=line.text.length+sepSize;});return index},copy:function(copyHistory){var doc=new Doc(getLines(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);doc.scrollTop=this.scrollTop;doc.scrollLeft=this.scrollLeft;doc.sel=this.sel;doc.extend=false;if(copyHistory){doc.history.undoDepth=this.history.undoDepth;doc.setHistory(this.getHistory());}
return doc},linkedDoc:function(options){if(!options){options={};}
var from=this.first,to=this.first+this.size;if(options.from!=null&&options.from>from){from=options.from;}
if(options.to!=null&&options.to<to){to=options.to;}
var copy=new Doc(getLines(this,from,to),options.mode||this.modeOption,from,this.lineSep,this.direction);if(options.sharedHist){copy.history=this.history;}(this.linked||(this.linked=[])).push({doc:copy,sharedHist:options.sharedHist});copy.linked=[{doc:this,isParent:true,sharedHist:options.sharedHist}];copySharedMarkers(copy,findSharedMarkers(this));return copy},unlinkDoc:function(other){if(other instanceof CodeMirror){other=other.doc;}
if(this.linked){for(var i=0;i<this.linked.length;++i){var link=this.linked[i];if(link.doc!=other){continue}
this.linked.splice(i,1);other.unlinkDoc(this);detachSharedMarkers(findSharedMarkers(this));break}}
if(other.history==this.history){var splitIds=[other.id];linkedDocs(other,function(doc){return splitIds.push(doc.id);},true);other.history=new History(null);other.history.done=copyHistoryArray(this.history.done,splitIds);other.history.undone=copyHistoryArray(this.history.undone,splitIds);}},iterLinkedDocs:function(f){linkedDocs(this,f);},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(str){if(this.lineSep){return str.split(this.lineSep)}
return splitLinesAuto(str)},lineSeparator:function(){return this.lineSep||"\n"},setDirection:docMethodOp(function(dir){if(dir!="rtl"){dir="ltr";}
if(dir==this.direction){return}
this.direction=dir;this.iter(function(line){return line.order=null;});if(this.cm){directionChanged(this.cm);}})});Doc.prototype.eachLine=Doc.prototype.iter;var lastDrop=0;function onDrop(e){var cm=this;clearDragCursor(cm);if(signalDOMEvent(cm,e)||eventInWidget(cm.display,e))
{return}
e_preventDefault(e);if(ie){lastDrop=+new Date;}
var pos=posFromMouse(cm,e,true),files=e.dataTransfer.files;if(!pos||cm.isReadOnly()){return}
if(files&&files.length&&window.FileReader&&window.File){var n=files.length,text=Array(n),read=0;var loadFile=function(file,i){if(cm.options.allowDropFileTypes&&indexOf(cm.options.allowDropFileTypes,file.type)==-1)
{return}
var reader=new FileReader;reader.onload=operation(cm,function(){var content=reader.result;if(/[\x00-\x08\x0e-\x1f]{2}/.test(content)){content="";}
text[i]=content;if(++read==n){pos=clipPos(cm.doc,pos);var change={from:pos,to:pos,text:cm.doc.splitLines(text.join(cm.doc.lineSeparator())),origin:"paste"};makeChange(cm.doc,change);setSelectionReplaceHistory(cm.doc,simpleSelection(pos,changeEnd(change)));}});reader.readAsText(file);};for(var i=0;i<n;++i){loadFile(files[i],i);}}else{if(cm.state.draggingText&&cm.doc.sel.contains(pos)>-1){cm.state.draggingText(e);setTimeout(function(){return cm.display.input.focus();},20);return}
try{var text$1=e.dataTransfer.getData("Text");if(text$1){var selected;if(cm.state.draggingText&&!cm.state.draggingText.copy)
{selected=cm.listSelections();}
setSelectionNoUndo(cm.doc,simpleSelection(pos,pos));if(selected){for(var i$1=0;i$1<selected.length;++i$1)
{replaceRange(cm.doc,"",selected[i$1].anchor,selected[i$1].head,"drag");}}
cm.replaceSelection(text$1,"around","paste");cm.display.input.focus();}}
catch(e){}}}
function onDragStart(cm,e){if(ie&&(!cm.state.draggingText||+new Date-lastDrop<100)){e_stop(e);return}
if(signalDOMEvent(cm,e)||eventInWidget(cm.display,e)){return}
e.dataTransfer.setData("Text",cm.getSelection());e.dataTransfer.effectAllowed="copyMove";if(e.dataTransfer.setDragImage&&!safari){var img=elt("img",null,null,"position: fixed; left: 0; top: 0;");img.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(presto){img.width=img.height=1;cm.display.wrapper.appendChild(img);img._top=img.offsetTop;}
e.dataTransfer.setDragImage(img,0,0);if(presto){img.parentNode.removeChild(img);}}}
function onDragOver(cm,e){var pos=posFromMouse(cm,e);if(!pos){return}
var frag=document.createDocumentFragment();drawSelectionCursor(cm,pos,frag);if(!cm.display.dragCursor){cm.display.dragCursor=elt("div",null,"CodeMirror-cursors CodeMirror-dragcursors");cm.display.lineSpace.insertBefore(cm.display.dragCursor,cm.display.cursorDiv);}
removeChildrenAndAdd(cm.display.dragCursor,frag);}
function clearDragCursor(cm){if(cm.display.dragCursor){cm.display.lineSpace.removeChild(cm.display.dragCursor);cm.display.dragCursor=null;}}
function forEachCodeMirror(f){if(!document.getElementsByClassName){return}
var byClass=document.getElementsByClassName("CodeMirror"),editors=[];for(var i=0;i<byClass.length;i++){var cm=byClass[i].CodeMirror;if(cm){editors.push(cm);}}
if(editors.length){editors[0].operation(function(){for(var i=0;i<editors.length;i++){f(editors[i]);}});}}
var globalsRegistered=false;function ensureGlobalHandlers(){if(globalsRegistered){return}
registerGlobalHandlers();globalsRegistered=true;}
function registerGlobalHandlers(){var resizeTimer;on(window,"resize",function(){if(resizeTimer==null){resizeTimer=setTimeout(function(){resizeTimer=null;forEachCodeMirror(onResize);},100);}});on(window,"blur",function(){return forEachCodeMirror(onBlur);});}
function onResize(cm){var d=cm.display;d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null;d.scrollbarsClipped=false;cm.setSize();}
var keyNames={3:"Pause",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",127:"Delete",145:"ScrollLock",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};for(var i=0;i<10;i++){keyNames[i+48]=keyNames[i+96]=String(i);}
for(var i$1=65;i$1<=90;i$1++){keyNames[i$1]=String.fromCharCode(i$1);}
for(var i$2=1;i$2<=12;i$2++){keyNames[i$2+111]=keyNames[i$2+63235]="F"+i$2;}
var keyMap={};keyMap.basic={"Left":"goCharLeft","Right":"goCharRight","Up":"goLineUp","Down":"goLineDown","End":"goLineEnd","Home":"goLineStartSmart","PageUp":"goPageUp","PageDown":"goPageDown","Delete":"delCharAfter","Backspace":"delCharBefore","Shift-Backspace":"delCharBefore","Tab":"defaultTab","Shift-Tab":"indentAuto","Enter":"newlineAndIndent","Insert":"toggleOverwrite","Esc":"singleSelection"};keyMap.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection","fallthrough":"basic"};keyMap.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"};keyMap.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd","fallthrough":["basic","emacsy"]};keyMap["default"]=mac?keyMap.macDefault:keyMap.pcDefault;function normalizeKeyName(name){var parts=name.split(/-(?!$)/);name=parts[parts.length-1];var alt,ctrl,shift,cmd;for(var i=0;i<parts.length-1;i++){var mod=parts[i];if(/^(cmd|meta|m)$/i.test(mod)){cmd=true;}
else if(/^a(lt)?$/i.test(mod)){alt=true;}
else if(/^(c|ctrl|control)$/i.test(mod)){ctrl=true;}
else if(/^s(hift)?$/i.test(mod)){shift=true;}
else{throw new Error("Unrecognized modifier name: "+mod)}}
if(alt){name="Alt-"+name;}
if(ctrl){name="Ctrl-"+name;}
if(cmd){name="Cmd-"+name;}
if(shift){name="Shift-"+name;}
return name}
function normalizeKeyMap(keymap){var copy={};for(var keyname in keymap){if(keymap.hasOwnProperty(keyname)){var value=keymap[keyname];if(/^(name|fallthrough|(de|at)tach)$/.test(keyname)){continue}
if(value=="..."){delete keymap[keyname];continue}
var keys=map(keyname.split(" "),normalizeKeyName);for(var i=0;i<keys.length;i++){var val=(void 0),name=(void 0);if(i==keys.length-1){name=keys.join(" ");val=value;}else{name=keys.slice(0,i+1).join(" ");val="...";}
var prev=copy[name];if(!prev){copy[name]=val;}
else if(prev!=val){throw new Error("Inconsistent bindings for "+name)}}
delete keymap[keyname];}}
for(var prop in copy){keymap[prop]=copy[prop];}
return keymap}
function lookupKey(key,map$$1,handle,context){map$$1=getKeyMap(map$$1);var found=map$$1.call?map$$1.call(key,context):map$$1[key];if(found===false){return"nothing"}
if(found==="..."){return"multi"}
if(found!=null&&handle(found)){return"handled"}
if(map$$1.fallthrough){if(Object.prototype.toString.call(map$$1.fallthrough)!="[object Array]")
{return lookupKey(key,map$$1.fallthrough,handle,context)}
for(var i=0;i<map$$1.fallthrough.length;i++){var result=lookupKey(key,map$$1.fallthrough[i],handle,context);if(result){return result}}}}
function isModifierKey(value){var name=typeof value=="string"?value:keyNames[value.keyCode];return name=="Ctrl"||name=="Alt"||name=="Shift"||name=="Mod"}
function addModifierNames(name,event,noShift){var base=name;if(event.altKey&&base!="Alt"){name="Alt-"+name;}
if((flipCtrlCmd?event.metaKey:event.ctrlKey)&&base!="Ctrl"){name="Ctrl-"+name;}
if((flipCtrlCmd?event.ctrlKey:event.metaKey)&&base!="Cmd"){name="Cmd-"+name;}
if(!noShift&&event.shiftKey&&base!="Shift"){name="Shift-"+name;}
return name}
function keyName(event,noShift){if(presto&&event.keyCode==34&&event["char"]){return false}
var name=keyNames[event.keyCode];if(name==null||event.altGraphKey){return false}
if(event.keyCode==3&&event.code){name=event.code;}
return addModifierNames(name,event,noShift)}
function getKeyMap(val){return typeof val=="string"?keyMap[val]:val}
function deleteNearSelection(cm,compute){var ranges=cm.doc.sel.ranges,kill=[];for(var i=0;i<ranges.length;i++){var toKill=compute(ranges[i]);while(kill.length&&cmp(toKill.from,lst(kill).to)<=0){var replaced=kill.pop();if(cmp(replaced.from,toKill.from)<0){toKill.from=replaced.from;break}}
kill.push(toKill);}
runInOp(cm,function(){for(var i=kill.length-1;i>=0;i--)
{replaceRange(cm.doc,"",kill[i].from,kill[i].to,"+delete");}
ensureCursorVisible(cm);});}
function moveCharLogically(line,ch,dir){var target=skipExtendingChars(line.text,ch+dir,dir);return target<0||target>line.text.length?null:target}
function moveLogically(line,start,dir){var ch=moveCharLogically(line,start.ch,dir);return ch==null?null:new Pos(start.line,ch,dir<0?"after":"before")}
function endOfLine(visually,cm,lineObj,lineNo,dir){if(visually){var order=getOrder(lineObj,cm.doc.direction);if(order){var part=dir<0?lst(order):order[0];var moveInStorageOrder=(dir<0)==(part.level==1);var sticky=moveInStorageOrder?"after":"before";var ch;if(part.level>0||cm.doc.direction=="rtl"){var prep=prepareMeasureForLine(cm,lineObj);ch=dir<0?lineObj.text.length-1:0;var targetTop=measureCharPrepared(cm,prep,ch).top;ch=findFirst(function(ch){return measureCharPrepared(cm,prep,ch).top==targetTop;},(dir<0)==(part.level==1)?part.from:part.to-1,ch);if(sticky=="before"){ch=moveCharLogically(lineObj,ch,1);}}else{ch=dir<0?part.to:part.from;}
return new Pos(lineNo,ch,sticky)}}
return new Pos(lineNo,dir<0?lineObj.text.length:0,dir<0?"before":"after")}
function moveVisually(cm,line,start,dir){var bidi=getOrder(line,cm.doc.direction);if(!bidi){return moveLogically(line,start,dir)}
if(start.ch>=line.text.length){start.ch=line.text.length;start.sticky="before";}else if(start.ch<=0){start.ch=0;start.sticky="after";}
var partPos=getBidiPartAt(bidi,start.ch,start.sticky),part=bidi[partPos];if(cm.doc.direction=="ltr"&&part.level%2==0&&(dir>0?part.to>start.ch:part.from<start.ch)){return moveLogically(line,start,dir)}
var mv=function(pos,dir){return moveCharLogically(line,pos instanceof Pos?pos.ch:pos,dir);};var prep;var getWrappedLineExtent=function(ch){if(!cm.options.lineWrapping){return{begin:0,end:line.text.length}}
prep=prep||prepareMeasureForLine(cm,line);return wrappedLineExtentChar(cm,line,prep,ch)};var wrappedLineExtent=getWrappedLineExtent(start.sticky=="before"?mv(start,-1):start.ch);if(cm.doc.direction=="rtl"||part.level==1){var moveInStorageOrder=(part.level==1)==(dir<0);var ch=mv(start,moveInStorageOrder?1:-1);if(ch!=null&&(!moveInStorageOrder?ch>=part.from&&ch>=wrappedLineExtent.begin:ch<=part.to&&ch<=wrappedLineExtent.end)){var sticky=moveInStorageOrder?"before":"after";return new Pos(start.line,ch,sticky)}}
var searchInVisualLine=function(partPos,dir,wrappedLineExtent){var getRes=function(ch,moveInStorageOrder){return moveInStorageOrder?new Pos(start.line,mv(ch,1),"before"):new Pos(start.line,ch,"after");};for(;partPos>=0&&partPos<bidi.length;partPos+=dir){var part=bidi[partPos];var moveInStorageOrder=(dir>0)==(part.level!=1);var ch=moveInStorageOrder?wrappedLineExtent.begin:mv(wrappedLineExtent.end,-1);if(part.from<=ch&&ch<part.to){return getRes(ch,moveInStorageOrder)}
ch=moveInStorageOrder?part.from:mv(part.to,-1);if(wrappedLineExtent.begin<=ch&&ch<wrappedLineExtent.end){return getRes(ch,moveInStorageOrder)}}};var res=searchInVisualLine(partPos+dir,dir,wrappedLineExtent);if(res){return res}
var nextCh=dir>0?wrappedLineExtent.end:mv(wrappedLineExtent.begin,-1);if(nextCh!=null&&!(dir>0&&nextCh==line.text.length)){res=searchInVisualLine(dir>0?0:bidi.length-1,dir,getWrappedLineExtent(nextCh));if(res){return res}}
return null}
var commands={selectAll:selectAll,singleSelection:function(cm){return cm.setSelection(cm.getCursor("anchor"),cm.getCursor("head"),sel_dontScroll);},killLine:function(cm){return deleteNearSelection(cm,function(range){if(range.empty()){var len=getLine(cm.doc,range.head.line).text.length;if(range.head.ch==len&&range.head.line<cm.lastLine())
{return{from:range.head,to:Pos(range.head.line+1,0)}}
else
{return{from:range.head,to:Pos(range.head.line,len)}}}else{return{from:range.from(),to:range.to()}}});},deleteLine:function(cm){return deleteNearSelection(cm,function(range){return({from:Pos(range.from().line,0),to:clipPos(cm.doc,Pos(range.to().line+1,0))});});},delLineLeft:function(cm){return deleteNearSelection(cm,function(range){return({from:Pos(range.from().line,0),to:range.from()});});},delWrappedLineLeft:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5;var leftPos=cm.coordsChar({left:0,top:top},"div");return{from:leftPos,to:range.from()}});},delWrappedLineRight:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5;var rightPos=cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div");return{from:range.from(),to:rightPos}});},undo:function(cm){return cm.undo();},redo:function(cm){return cm.redo();},undoSelection:function(cm){return cm.undoSelection();},redoSelection:function(cm){return cm.redoSelection();},goDocStart:function(cm){return cm.extendSelection(Pos(cm.firstLine(),0));},goDocEnd:function(cm){return cm.extendSelection(Pos(cm.lastLine()));},goLineStart:function(cm){return cm.extendSelectionsBy(function(range){return lineStart(cm,range.head.line);},{origin:"+move",bias:1});},goLineStartSmart:function(cm){return cm.extendSelectionsBy(function(range){return lineStartSmart(cm,range.head);},{origin:"+move",bias:1});},goLineEnd:function(cm){return cm.extendSelectionsBy(function(range){return lineEnd(cm,range.head.line);},{origin:"+move",bias:-1});},goLineRight:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.cursorCoords(range.head,"div").top+5;return cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div")},sel_move);},goLineLeft:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.cursorCoords(range.head,"div").top+5;return cm.coordsChar({left:0,top:top},"div")},sel_move);},goLineLeftSmart:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.cursorCoords(range.head,"div").top+5;var pos=cm.coordsChar({left:0,top:top},"div");if(pos.ch<cm.getLine(pos.line).search(/\S/)){return lineStartSmart(cm,range.head)}
return pos},sel_move);},goLineUp:function(cm){return cm.moveV(-1,"line");},goLineDown:function(cm){return cm.moveV(1,"line");},goPageUp:function(cm){return cm.moveV(-1,"page");},goPageDown:function(cm){return cm.moveV(1,"page");},goCharLeft:function(cm){return cm.moveH(-1,"char");},goCharRight:function(cm){return cm.moveH(1,"char");},goColumnLeft:function(cm){return cm.moveH(-1,"column");},goColumnRight:function(cm){return cm.moveH(1,"column");},goWordLeft:function(cm){return cm.moveH(-1,"word");},goGroupRight:function(cm){return cm.moveH(1,"group");},goGroupLeft:function(cm){return cm.moveH(-1,"group");},goWordRight:function(cm){return cm.moveH(1,"word");},delCharBefore:function(cm){return cm.deleteH(-1,"char");},delCharAfter:function(cm){return cm.deleteH(1,"char");},delWordBefore:function(cm){return cm.deleteH(-1,"word");},delWordAfter:function(cm){return cm.deleteH(1,"word");},delGroupBefore:function(cm){return cm.deleteH(-1,"group");},delGroupAfter:function(cm){return cm.deleteH(1,"group");},indentAuto:function(cm){return cm.indentSelection("smart");},indentMore:function(cm){return cm.indentSelection("add");},indentLess:function(cm){return cm.indentSelection("subtract");},insertTab:function(cm){return cm.replaceSelection("\t");},insertSoftTab:function(cm){var spaces=[],ranges=cm.listSelections(),tabSize=cm.options.tabSize;for(var i=0;i<ranges.length;i++){var pos=ranges[i].from();var col=countColumn(cm.getLine(pos.line),pos.ch,tabSize);spaces.push(spaceStr(tabSize-col%tabSize));}
cm.replaceSelections(spaces);},defaultTab:function(cm){if(cm.somethingSelected()){cm.indentSelection("add");}
else{cm.execCommand("insertTab");}},transposeChars:function(cm){return runInOp(cm,function(){var ranges=cm.listSelections(),newSel=[];for(var i=0;i<ranges.length;i++){if(!ranges[i].empty()){continue}
var cur=ranges[i].head,line=getLine(cm.doc,cur.line).text;if(line){if(cur.ch==line.length){cur=new Pos(cur.line,cur.ch-1);}
if(cur.ch>0){cur=new Pos(cur.line,cur.ch+1);cm.replaceRange(line.charAt(cur.ch-1)+line.charAt(cur.ch-2),Pos(cur.line,cur.ch-2),cur,"+transpose");}else if(cur.line>cm.doc.first){var prev=getLine(cm.doc,cur.line-1).text;if(prev){cur=new Pos(cur.line,1);cm.replaceRange(line.charAt(0)+cm.doc.lineSeparator()+
prev.charAt(prev.length-1),Pos(cur.line-1,prev.length-1),cur,"+transpose");}}}
newSel.push(new Range(cur,cur));}
cm.setSelections(newSel);});},newlineAndIndent:function(cm){return runInOp(cm,function(){var sels=cm.listSelections();for(var i=sels.length-1;i>=0;i--)
{cm.replaceRange(cm.doc.lineSeparator(),sels[i].anchor,sels[i].head,"+input");}
sels=cm.listSelections();for(var i$1=0;i$1<sels.length;i$1++)
{cm.indentLine(sels[i$1].from().line,null,true);}
ensureCursorVisible(cm);});},openLine:function(cm){return cm.replaceSelection("\n","start");},toggleOverwrite:function(cm){return cm.toggleOverwrite();}};function lineStart(cm,lineN){var line=getLine(cm.doc,lineN);var visual=visualLine(line);if(visual!=line){lineN=lineNo(visual);}
return endOfLine(true,cm,visual,lineN,1)}
function lineEnd(cm,lineN){var line=getLine(cm.doc,lineN);var visual=visualLineEnd(line);if(visual!=line){lineN=lineNo(visual);}
return endOfLine(true,cm,line,lineN,-1)}
function lineStartSmart(cm,pos){var start=lineStart(cm,pos.line);var line=getLine(cm.doc,start.line);var order=getOrder(line,cm.doc.direction);if(!order||order[0].level==0){var firstNonWS=Math.max(0,line.text.search(/\S/));var inWS=pos.line==start.line&&pos.ch<=firstNonWS&&pos.ch;return Pos(start.line,inWS?0:firstNonWS,start.sticky)}
return start}
function doHandleBinding(cm,bound,dropShift){if(typeof bound=="string"){bound=commands[bound];if(!bound){return false}}
cm.display.input.ensurePolled();var prevShift=cm.display.shift,done=false;try{if(cm.isReadOnly()){cm.state.suppressEdits=true;}
if(dropShift){cm.display.shift=false;}
done=bound(cm)!=Pass;}finally{cm.display.shift=prevShift;cm.state.suppressEdits=false;}
return done}
function lookupKeyForEditor(cm,name,handle){for(var i=0;i<cm.state.keyMaps.length;i++){var result=lookupKey(name,cm.state.keyMaps[i],handle,cm);if(result){return result}}
return(cm.options.extraKeys&&lookupKey(name,cm.options.extraKeys,handle,cm))||lookupKey(name,cm.options.keyMap,handle,cm)}
var stopSeq=new Delayed;function dispatchKey(cm,name,e,handle){var seq=cm.state.keySeq;if(seq){if(isModifierKey(name)){return"handled"}
if(/\'$/.test(name))
{cm.state.keySeq=null;}
else
{stopSeq.set(50,function(){if(cm.state.keySeq==seq){cm.state.keySeq=null;cm.display.input.reset();}});}
if(dispatchKeyInner(cm,seq+" "+name,e,handle)){return true}}
return dispatchKeyInner(cm,name,e,handle)}
function dispatchKeyInner(cm,name,e,handle){var result=lookupKeyForEditor(cm,name,handle);if(result=="multi")
{cm.state.keySeq=name;}
if(result=="handled")
{signalLater(cm,"keyHandled",cm,name,e);}
if(result=="handled"||result=="multi"){e_preventDefault(e);restartBlink(cm);}
return!!result}
function handleKeyBinding(cm,e){var name=keyName(e,true);if(!name){return false}
if(e.shiftKey&&!cm.state.keySeq){return dispatchKey(cm,"Shift-"+name,e,function(b){return doHandleBinding(cm,b,true);})||dispatchKey(cm,name,e,function(b){if(typeof b=="string"?/^go[A-Z]/.test(b):b.motion)
{return doHandleBinding(cm,b)}})}else{return dispatchKey(cm,name,e,function(b){return doHandleBinding(cm,b);})}}
function handleCharBinding(cm,e,ch){return dispatchKey(cm,"'"+ch+"'",e,function(b){return doHandleBinding(cm,b,true);})}
var lastStoppedKey=null;function onKeyDown(e){var cm=this;cm.curOp.focus=activeElt();if(signalDOMEvent(cm,e)){return}
if(ie&&ie_version<11&&e.keyCode==27){e.returnValue=false;}
var code=e.keyCode;cm.display.shift=code==16||e.shiftKey;var handled=handleKeyBinding(cm,e);if(presto){lastStoppedKey=handled?code:null;if(!handled&&code==88&&!hasCopyEvent&&(mac?e.metaKey:e.ctrlKey))
{cm.replaceSelection("",null,"cut");}}
if(code==18&&!/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
{showCrossHair(cm);}}
function showCrossHair(cm){var lineDiv=cm.display.lineDiv;addClass(lineDiv,"CodeMirror-crosshair");function up(e){if(e.keyCode==18||!e.altKey){rmClass(lineDiv,"CodeMirror-crosshair");off(document,"keyup",up);off(document,"mouseover",up);}}
on(document,"keyup",up);on(document,"mouseover",up);}
function onKeyUp(e){if(e.keyCode==16){this.doc.sel.shift=false;}
signalDOMEvent(this,e);}
function onKeyPress(e){var cm=this;if(eventInWidget(cm.display,e)||signalDOMEvent(cm,e)||e.ctrlKey&&!e.altKey||mac&&e.metaKey){return}
var keyCode=e.keyCode,charCode=e.charCode;if(presto&&keyCode==lastStoppedKey){lastStoppedKey=null;e_preventDefault(e);return}
if((presto&&(!e.which||e.which<10))&&handleKeyBinding(cm,e)){return}
var ch=String.fromCharCode(charCode==null?keyCode:charCode);if(ch=="\x08"){return}
if(handleCharBinding(cm,e,ch)){return}
cm.display.input.onKeyPress(e);}
var DOUBLECLICK_DELAY=400;var PastClick=function(time,pos,button){this.time=time;this.pos=pos;this.button=button;};PastClick.prototype.compare=function(time,pos,button){return this.time+DOUBLECLICK_DELAY>time&&cmp(pos,this.pos)==0&&button==this.button};var lastClick,lastDoubleClick;function clickRepeat(pos,button){var now=+new Date;if(lastDoubleClick&&lastDoubleClick.compare(now,pos,button)){lastClick=lastDoubleClick=null;return"triple"}else if(lastClick&&lastClick.compare(now,pos,button)){lastDoubleClick=new PastClick(now,pos,button);lastClick=null;return"double"}else{lastClick=new PastClick(now,pos,button);lastDoubleClick=null;return"single"}}
function onMouseDown(e){var cm=this,display=cm.display;if(signalDOMEvent(cm,e)||display.activeTouch&&display.input.supportsTouch()){return}
display.input.ensurePolled();display.shift=e.shiftKey;if(eventInWidget(display,e)){if(!webkit){display.scroller.draggable=false;setTimeout(function(){return display.scroller.draggable=true;},100);}
return}
if(clickInGutter(cm,e)){return}
var pos=posFromMouse(cm,e),button=e_button(e),repeat=pos?clickRepeat(pos,button):"single";window.focus();if(button==1&&cm.state.selectingText)
{cm.state.selectingText(e);}
if(pos&&handleMappedButton(cm,button,pos,repeat,e)){return}
if(button==1){if(pos){leftButtonDown(cm,pos,repeat,e);}
else if(e_target(e)==display.scroller){e_preventDefault(e);}}else if(button==2){if(pos){extendSelection(cm.doc,pos);}
setTimeout(function(){return display.input.focus();},20);}else if(button==3){if(captureRightClick){cm.display.input.onContextMenu(e);}
else{delayBlurEvent(cm);}}}
function handleMappedButton(cm,button,pos,repeat,event){var name="Click";if(repeat=="double"){name="Double"+name;}
else if(repeat=="triple"){name="Triple"+name;}
name=(button==1?"Left":button==2?"Middle":"Right")+name;return dispatchKey(cm,addModifierNames(name,event),event,function(bound){if(typeof bound=="string"){bound=commands[bound];}
if(!bound){return false}
var done=false;try{if(cm.isReadOnly()){cm.state.suppressEdits=true;}
done=bound(cm,pos)!=Pass;}finally{cm.state.suppressEdits=false;}
return done})}
function configureMouse(cm,repeat,event){var option=cm.getOption("configureMouse");var value=option?option(cm,repeat,event):{};if(value.unit==null){var rect=chromeOS?event.shiftKey&&event.metaKey:event.altKey;value.unit=rect?"rectangle":repeat=="single"?"char":repeat=="double"?"word":"line";}
if(value.extend==null||cm.doc.extend){value.extend=cm.doc.extend||event.shiftKey;}
if(value.addNew==null){value.addNew=mac?event.metaKey:event.ctrlKey;}
if(value.moveOnDrag==null){value.moveOnDrag=!(mac?event.altKey:event.ctrlKey);}
return value}
function leftButtonDown(cm,pos,repeat,event){if(ie){setTimeout(bind(ensureFocus,cm),0);}
else{cm.curOp.focus=activeElt();}
var behavior=configureMouse(cm,repeat,event);var sel=cm.doc.sel,contained;if(cm.options.dragDrop&&dragAndDrop&&!cm.isReadOnly()&&repeat=="single"&&(contained=sel.contains(pos))>-1&&(cmp((contained=sel.ranges[contained]).from(),pos)<0||pos.xRel>0)&&(cmp(contained.to(),pos)>0||pos.xRel<0))
{leftButtonStartDrag(cm,event,pos,behavior);}
else
{leftButtonSelect(cm,event,pos,behavior);}}
function leftButtonStartDrag(cm,event,pos,behavior){var display=cm.display,moved=false;var dragEnd=operation(cm,function(e){if(webkit){display.scroller.draggable=false;}
cm.state.draggingText=false;off(display.wrapper.ownerDocument,"mouseup",dragEnd);off(display.wrapper.ownerDocument,"mousemove",mouseMove);off(display.scroller,"dragstart",dragStart);off(display.scroller,"drop",dragEnd);if(!moved){e_preventDefault(e);if(!behavior.addNew)
{extendSelection(cm.doc,pos,null,null,behavior.extend);}
if(webkit||ie&&ie_version==9)
{setTimeout(function(){display.wrapper.ownerDocument.body.focus();display.input.focus();},20);}
else
{display.input.focus();}}});var mouseMove=function(e2){moved=moved||Math.abs(event.clientX-e2.clientX)+Math.abs(event.clientY-e2.clientY)>=10;};var dragStart=function(){return moved=true;};if(webkit){display.scroller.draggable=true;}
cm.state.draggingText=dragEnd;dragEnd.copy=!behavior.moveOnDrag;if(display.scroller.dragDrop){display.scroller.dragDrop();}
on(display.wrapper.ownerDocument,"mouseup",dragEnd);on(display.wrapper.ownerDocument,"mousemove",mouseMove);on(display.scroller,"dragstart",dragStart);on(display.scroller,"drop",dragEnd);delayBlurEvent(cm);setTimeout(function(){return display.input.focus();},20);}
function rangeForUnit(cm,pos,unit){if(unit=="char"){return new Range(pos,pos)}
if(unit=="word"){return cm.findWordAt(pos)}
if(unit=="line"){return new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0)))}
var result=unit(cm,pos);return new Range(result.from,result.to)}
function leftButtonSelect(cm,event,start,behavior){var display=cm.display,doc=cm.doc;e_preventDefault(event);var ourRange,ourIndex,startSel=doc.sel,ranges=startSel.ranges;if(behavior.addNew&&!behavior.extend){ourIndex=doc.sel.contains(start);if(ourIndex>-1)
{ourRange=ranges[ourIndex];}
else
{ourRange=new Range(start,start);}}else{ourRange=doc.sel.primary();ourIndex=doc.sel.primIndex;}
if(behavior.unit=="rectangle"){if(!behavior.addNew){ourRange=new Range(start,start);}
start=posFromMouse(cm,event,true,true);ourIndex=-1;}else{var range$$1=rangeForUnit(cm,start,behavior.unit);if(behavior.extend)
{ourRange=extendRange(ourRange,range$$1.anchor,range$$1.head,behavior.extend);}
else
{ourRange=range$$1;}}
if(!behavior.addNew){ourIndex=0;setSelection(doc,new Selection([ourRange],0),sel_mouse);startSel=doc.sel;}else if(ourIndex==-1){ourIndex=ranges.length;setSelection(doc,normalizeSelection(cm,ranges.concat([ourRange]),ourIndex),{scroll:false,origin:"*mouse"});}else if(ranges.length>1&&ranges[ourIndex].empty()&&behavior.unit=="char"&&!behavior.extend){setSelection(doc,normalizeSelection(cm,ranges.slice(0,ourIndex).concat(ranges.slice(ourIndex+1)),0),{scroll:false,origin:"*mouse"});startSel=doc.sel;}else{replaceOneSelection(doc,ourIndex,ourRange,sel_mouse);}
var lastPos=start;function extendTo(pos){if(cmp(lastPos,pos)==0){return}
lastPos=pos;if(behavior.unit=="rectangle"){var ranges=[],tabSize=cm.options.tabSize;var startCol=countColumn(getLine(doc,start.line).text,start.ch,tabSize);var posCol=countColumn(getLine(doc,pos.line).text,pos.ch,tabSize);var left=Math.min(startCol,posCol),right=Math.max(startCol,posCol);for(var line=Math.min(start.line,pos.line),end=Math.min(cm.lastLine(),Math.max(start.line,pos.line));line<=end;line++){var text=getLine(doc,line).text,leftPos=findColumn(text,left,tabSize);if(left==right)
{ranges.push(new Range(Pos(line,leftPos),Pos(line,leftPos)));}
else if(text.length>leftPos)
{ranges.push(new Range(Pos(line,leftPos),Pos(line,findColumn(text,right,tabSize))));}}
if(!ranges.length){ranges.push(new Range(start,start));}
setSelection(doc,normalizeSelection(cm,startSel.ranges.slice(0,ourIndex).concat(ranges),ourIndex),{origin:"*mouse",scroll:false});cm.scrollIntoView(pos);}else{var oldRange=ourRange;var range$$1=rangeForUnit(cm,pos,behavior.unit);var anchor=oldRange.anchor,head;if(cmp(range$$1.anchor,anchor)>0){head=range$$1.head;anchor=minPos(oldRange.from(),range$$1.anchor);}else{head=range$$1.anchor;anchor=maxPos(oldRange.to(),range$$1.head);}
var ranges$1=startSel.ranges.slice(0);ranges$1[ourIndex]=bidiSimplify(cm,new Range(clipPos(doc,anchor),head));setSelection(doc,normalizeSelection(cm,ranges$1,ourIndex),sel_mouse);}}
var editorSize=display.wrapper.getBoundingClientRect();var counter=0;function extend(e){var curCount=++counter;var cur=posFromMouse(cm,e,true,behavior.unit=="rectangle");if(!cur){return}
if(cmp(cur,lastPos)!=0){cm.curOp.focus=activeElt();extendTo(cur);var visible=visibleLines(display,doc);if(cur.line>=visible.to||cur.line<visible.from)
{setTimeout(operation(cm,function(){if(counter==curCount){extend(e);}}),150);}}else{var outside=e.clientY<editorSize.top?-20:e.clientY>editorSize.bottom?20:0;if(outside){setTimeout(operation(cm,function(){if(counter!=curCount){return}
display.scroller.scrollTop+=outside;extend(e);}),50);}}}
function done(e){cm.state.selectingText=false;counter=Infinity;e_preventDefault(e);display.input.focus();off(display.wrapper.ownerDocument,"mousemove",move);off(display.wrapper.ownerDocument,"mouseup",up);doc.history.lastSelOrigin=null;}
var move=operation(cm,function(e){if(e.buttons===0||!e_button(e)){done(e);}
else{extend(e);}});var up=operation(cm,done);cm.state.selectingText=up;on(display.wrapper.ownerDocument,"mousemove",move);on(display.wrapper.ownerDocument,"mouseup",up);}
function bidiSimplify(cm,range$$1){var anchor=range$$1.anchor;var head=range$$1.head;var anchorLine=getLine(cm.doc,anchor.line);if(cmp(anchor,head)==0&&anchor.sticky==head.sticky){return range$$1}
var order=getOrder(anchorLine);if(!order){return range$$1}
var index=getBidiPartAt(order,anchor.ch,anchor.sticky),part=order[index];if(part.from!=anchor.ch&&part.to!=anchor.ch){return range$$1}
var boundary=index+((part.from==anchor.ch)==(part.level!=1)?0:1);if(boundary==0||boundary==order.length){return range$$1}
var leftSide;if(head.line!=anchor.line){leftSide=(head.line-anchor.line)*(cm.doc.direction=="ltr"?1:-1)>0;}else{var headIndex=getBidiPartAt(order,head.ch,head.sticky);var dir=headIndex-index||(head.ch-anchor.ch)*(part.level==1?-1:1);if(headIndex==boundary-1||headIndex==boundary)
{leftSide=dir<0;}
else
{leftSide=dir>0;}}
var usePart=order[boundary+(leftSide?-1:0)];var from=leftSide==(usePart.level==1);var ch=from?usePart.from:usePart.to,sticky=from?"after":"before";return anchor.ch==ch&&anchor.sticky==sticky?range$$1:new Range(new Pos(anchor.line,ch,sticky),head)}
function gutterEvent(cm,e,type,prevent){var mX,mY;if(e.touches){mX=e.touches[0].clientX;mY=e.touches[0].clientY;}else{try{mX=e.clientX;mY=e.clientY;}
catch(e){return false}}
if(mX>=Math.floor(cm.display.gutters.getBoundingClientRect().right)){return false}
if(prevent){e_preventDefault(e);}
var display=cm.display;var lineBox=display.lineDiv.getBoundingClientRect();if(mY>lineBox.bottom||!hasHandler(cm,type)){return e_defaultPrevented(e)}
mY-=lineBox.top-display.viewOffset;for(var i=0;i<cm.options.gutters.length;++i){var g=display.gutters.childNodes[i];if(g&&g.getBoundingClientRect().right>=mX){var line=lineAtHeight(cm.doc,mY);var gutter=cm.options.gutters[i];signal(cm,type,cm,line,gutter,e);return e_defaultPrevented(e)}}}
function clickInGutter(cm,e){return gutterEvent(cm,e,"gutterClick",true)}
function onContextMenu(cm,e){if(eventInWidget(cm.display,e)||contextMenuInGutter(cm,e)){return}
if(signalDOMEvent(cm,e,"contextmenu")){return}
if(!captureRightClick){cm.display.input.onContextMenu(e);}}
function contextMenuInGutter(cm,e){if(!hasHandler(cm,"gutterContextMenu")){return false}
return gutterEvent(cm,e,"gutterContextMenu",false)}
function themeChanged(cm){cm.display.wrapper.className=cm.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+
cm.options.theme.replace(/(^|\s)\s*/g," cm-s-");clearCaches(cm);}
var Init={toString:function(){return"CodeMirror.Init"}};var defaults={};var optionHandlers={};function defineOptions(CodeMirror){var optionHandlers=CodeMirror.optionHandlers;function option(name,deflt,handle,notOnInit){CodeMirror.defaults[name]=deflt;if(handle){optionHandlers[name]=notOnInit?function(cm,val,old){if(old!=Init){handle(cm,val,old);}}:handle;}}
CodeMirror.defineOption=option;CodeMirror.Init=Init;option("value","",function(cm,val){return cm.setValue(val);},true);option("mode",null,function(cm,val){cm.doc.modeOption=val;loadMode(cm);},true);option("indentUnit",2,loadMode,true);option("indentWithTabs",false);option("smartIndent",true);option("tabSize",4,function(cm){resetModeState(cm);clearCaches(cm);regChange(cm);},true);option("lineSeparator",null,function(cm,val){cm.doc.lineSep=val;if(!val){return}
var newBreaks=[],lineNo=cm.doc.first;cm.doc.iter(function(line){for(var pos=0;;){var found=line.text.indexOf(val,pos);if(found==-1){break}
pos=found+val.length;newBreaks.push(Pos(lineNo,found));}
lineNo++;});for(var i=newBreaks.length-1;i>=0;i--)
{replaceRange(cm.doc,val,newBreaks[i],Pos(newBreaks[i].line,newBreaks[i].ch+val.length));}});option("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g,function(cm,val,old){cm.state.specialChars=new RegExp(val.source+(val.test("\t")?"":"|\t"),"g");if(old!=Init){cm.refresh();}});option("specialCharPlaceholder",defaultSpecialCharPlaceholder,function(cm){return cm.refresh();},true);option("electricChars",true);option("inputStyle",mobile?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},true);option("spellcheck",false,function(cm,val){return cm.getInputField().spellcheck=val;},true);option("rtlMoveVisually",!windows);option("wholeLineUpdateBefore",true);option("theme","default",function(cm){themeChanged(cm);guttersChanged(cm);},true);option("keyMap","default",function(cm,val,old){var next=getKeyMap(val);var prev=old!=Init&&getKeyMap(old);if(prev&&prev.detach){prev.detach(cm,next);}
if(next.attach){next.attach(cm,prev||null);}});option("extraKeys",null);option("configureMouse",null);option("lineWrapping",false,wrappingChanged,true);option("gutters",[],function(cm){setGuttersForLineNumbers(cm.options);guttersChanged(cm);},true);option("fixedGutter",true,function(cm,val){cm.display.gutters.style.left=val?compensateForHScroll(cm.display)+"px":"0";cm.refresh();},true);option("coverGutterNextToScrollbar",false,function(cm){return updateScrollbars(cm);},true);option("scrollbarStyle","native",function(cm){initScrollbars(cm);updateScrollbars(cm);cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);},true);option("lineNumbers",false,function(cm){setGuttersForLineNumbers(cm.options);guttersChanged(cm);},true);option("firstLineNumber",1,guttersChanged,true);option("lineNumberFormatter",function(integer){return integer;},guttersChanged,true);option("showCursorWhenSelecting",false,updateSelection,true);option("resetSelectionOnContextMenu",true);option("lineWiseCopyCut",true);option("pasteLinesPerSelection",true);option("selectionsMayTouch",false);option("readOnly",false,function(cm,val){if(val=="nocursor"){onBlur(cm);cm.display.input.blur();}
cm.display.input.readOnlyChanged(val);});option("disableInput",false,function(cm,val){if(!val){cm.display.input.reset();}},true);option("dragDrop",true,dragDropChanged);option("allowDropFileTypes",null);option("cursorBlinkRate",530);option("cursorScrollMargin",0);option("cursorHeight",1,updateSelection,true);option("singleCursorHeightPerLine",true,updateSelection,true);option("workTime",100);option("workDelay",100);option("flattenSpans",true,resetModeState,true);option("addModeClass",false,resetModeState,true);option("pollInterval",100);option("undoDepth",200,function(cm,val){return cm.doc.history.undoDepth=val;});option("historyEventDelay",1250);option("viewportMargin",10,function(cm){return cm.refresh();},true);option("maxHighlightLength",10000,resetModeState,true);option("moveInputWithCursor",true,function(cm,val){if(!val){cm.display.input.resetPosition();}});option("tabindex",null,function(cm,val){return cm.display.input.getField().tabIndex=val||"";});option("autofocus",null);option("direction","ltr",function(cm,val){return cm.doc.setDirection(val);},true);option("phrases",null);}
function guttersChanged(cm){updateGutters(cm);regChange(cm);alignHorizontally(cm);}
function dragDropChanged(cm,value,old){var wasOn=old&&old!=Init;if(!value!=!wasOn){var funcs=cm.display.dragFunctions;var toggle=value?on:off;toggle(cm.display.scroller,"dragstart",funcs.start);toggle(cm.display.scroller,"dragenter",funcs.enter);toggle(cm.display.scroller,"dragover",funcs.over);toggle(cm.display.scroller,"dragleave",funcs.leave);toggle(cm.display.scroller,"drop",funcs.drop);}}
function wrappingChanged(cm){if(cm.options.lineWrapping){addClass(cm.display.wrapper,"CodeMirror-wrap");cm.display.sizer.style.minWidth="";cm.display.sizerWidth=null;}else{rmClass(cm.display.wrapper,"CodeMirror-wrap");findMaxLine(cm);}
estimateLineHeights(cm);regChange(cm);clearCaches(cm);setTimeout(function(){return updateScrollbars(cm);},100);}
function CodeMirror(place,options){var this$1=this;if(!(this instanceof CodeMirror)){return new CodeMirror(place,options)}
this.options=options=options?copyObj(options):{};copyObj(defaults,options,false);setGuttersForLineNumbers(options);var doc=options.value;if(typeof doc=="string"){doc=new Doc(doc,options.mode,null,options.lineSeparator,options.direction);}
else if(options.mode){doc.modeOption=options.mode;}
this.doc=doc;var input=new CodeMirror.inputStyles[options.inputStyle](this);var display=this.display=new Display(place,doc,input);display.wrapper.CodeMirror=this;updateGutters(this);themeChanged(this);if(options.lineWrapping)
{this.display.wrapper.className+=" CodeMirror-wrap";}
initScrollbars(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:false,delayingBlurEvent:false,focused:false,suppressEdits:false,pasteIncoming:false,cutIncoming:false,selectingText:false,draggingText:false,highlight:new Delayed(),keySeq:null,specialChars:null};if(options.autofocus&&!mobile){display.input.focus();}
if(ie&&ie_version<11){setTimeout(function(){return this$1.display.input.reset(true);},20);}
registerEventHandlers(this);ensureGlobalHandlers();startOperation(this);this.curOp.forceUpdate=true;attachDoc(this,doc);if((options.autofocus&&!mobile)||this.hasFocus())
{setTimeout(bind(onFocus,this),20);}
else
{onBlur(this);}
for(var opt in optionHandlers){if(optionHandlers.hasOwnProperty(opt))
{optionHandlers[opt](this,options[opt],Init);}}
maybeUpdateLineNumberWidth(this);if(options.finishInit){options.finishInit(this);}
for(var i=0;i<initHooks.length;++i){initHooks[i](this);}
endOperation(this);if(webkit&&options.lineWrapping&&getComputedStyle(display.lineDiv).textRendering=="optimizelegibility")
{display.lineDiv.style.textRendering="auto";}}
CodeMirror.defaults=defaults;CodeMirror.optionHandlers=optionHandlers;function registerEventHandlers(cm){var d=cm.display;on(d.scroller,"mousedown",operation(cm,onMouseDown));if(ie&&ie_version<11)
{on(d.scroller,"dblclick",operation(cm,function(e){if(signalDOMEvent(cm,e)){return}
var pos=posFromMouse(cm,e);if(!pos||clickInGutter(cm,e)||eventInWidget(cm.display,e)){return}
e_preventDefault(e);var word=cm.findWordAt(pos);extendSelection(cm.doc,word.anchor,word.head);}));}
else
{on(d.scroller,"dblclick",function(e){return signalDOMEvent(cm,e)||e_preventDefault(e);});}
on(d.scroller,"contextmenu",function(e){return onContextMenu(cm,e);});var touchFinished,prevTouch={end:0};function finishTouch(){if(d.activeTouch){touchFinished=setTimeout(function(){return d.activeTouch=null;},1000);prevTouch=d.activeTouch;prevTouch.end=+new Date;}}
function isMouseLikeTouchEvent(e){if(e.touches.length!=1){return false}
var touch=e.touches[0];return touch.radiusX<=1&&touch.radiusY<=1}
function farAway(touch,other){if(other.left==null){return true}
var dx=other.left-touch.left,dy=other.top-touch.top;return dx*dx+dy*dy>20*20}
on(d.scroller,"touchstart",function(e){if(!signalDOMEvent(cm,e)&&!isMouseLikeTouchEvent(e)&&!clickInGutter(cm,e)){d.input.ensurePolled();clearTimeout(touchFinished);var now=+new Date;d.activeTouch={start:now,moved:false,prev:now-prevTouch.end<=300?prevTouch:null};if(e.touches.length==1){d.activeTouch.left=e.touches[0].pageX;d.activeTouch.top=e.touches[0].pageY;}}});on(d.scroller,"touchmove",function(){if(d.activeTouch){d.activeTouch.moved=true;}});on(d.scroller,"touchend",function(e){var touch=d.activeTouch;if(touch&&!eventInWidget(d,e)&&touch.left!=null&&!touch.moved&&new Date-touch.start<300){var pos=cm.coordsChar(d.activeTouch,"page"),range;if(!touch.prev||farAway(touch,touch.prev))
{range=new Range(pos,pos);}
else if(!touch.prev.prev||farAway(touch,touch.prev.prev))
{range=cm.findWordAt(pos);}
else
{range=new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0)));}
cm.setSelection(range.anchor,range.head);cm.focus();e_preventDefault(e);}
finishTouch();});on(d.scroller,"touchcancel",finishTouch);on(d.scroller,"scroll",function(){if(d.scroller.clientHeight){updateScrollTop(cm,d.scroller.scrollTop);setScrollLeft(cm,d.scroller.scrollLeft,true);signal(cm,"scroll",cm);}});on(d.scroller,"mousewheel",function(e){return onScrollWheel(cm,e);});on(d.scroller,"DOMMouseScroll",function(e){return onScrollWheel(cm,e);});on(d.wrapper,"scroll",function(){return d.wrapper.scrollTop=d.wrapper.scrollLeft=0;});d.dragFunctions={enter:function(e){if(!signalDOMEvent(cm,e)){e_stop(e);}},over:function(e){if(!signalDOMEvent(cm,e)){onDragOver(cm,e);e_stop(e);}},start:function(e){return onDragStart(cm,e);},drop:operation(cm,onDrop),leave:function(e){if(!signalDOMEvent(cm,e)){clearDragCursor(cm);}}};var inp=d.input.getField();on(inp,"keyup",function(e){return onKeyUp.call(cm,e);});on(inp,"keydown",operation(cm,onKeyDown));on(inp,"keypress",operation(cm,onKeyPress));on(inp,"focus",function(e){return onFocus(cm,e);});on(inp,"blur",function(e){return onBlur(cm,e);});}
var initHooks=[];CodeMirror.defineInitHook=function(f){return initHooks.push(f);};function indentLine(cm,n,how,aggressive){var doc=cm.doc,state;if(how==null){how="add";}
if(how=="smart"){if(!doc.mode.indent){how="prev";}
else{state=getContextBefore(cm,n).state;}}
var tabSize=cm.options.tabSize;var line=getLine(doc,n),curSpace=countColumn(line.text,null,tabSize);if(line.stateAfter){line.stateAfter=null;}
var curSpaceString=line.text.match(/^\s*/)[0],indentation;if(!aggressive&&!/\S/.test(line.text)){indentation=0;how="not";}else if(how=="smart"){indentation=doc.mode.indent(state,line.text.slice(curSpaceString.length),line.text);if(indentation==Pass||indentation>150){if(!aggressive){return}
how="prev";}}
if(how=="prev"){if(n>doc.first){indentation=countColumn(getLine(doc,n-1).text,null,tabSize);}
else{indentation=0;}}else if(how=="add"){indentation=curSpace+cm.options.indentUnit;}else if(how=="subtract"){indentation=curSpace-cm.options.indentUnit;}else if(typeof how=="number"){indentation=curSpace+how;}
indentation=Math.max(0,indentation);var indentString="",pos=0;if(cm.options.indentWithTabs)
{for(var i=Math.floor(indentation/tabSize);i;--i){pos+=tabSize;indentString+="\t";}}
if(pos<indentation){indentString+=spaceStr(indentation-pos);}
if(indentString!=curSpaceString){replaceRange(doc,indentString,Pos(n,0),Pos(n,curSpaceString.length),"+input");line.stateAfter=null;return true}else{for(var i$1=0;i$1<doc.sel.ranges.length;i$1++){var range=doc.sel.ranges[i$1];if(range.head.line==n&&range.head.ch<curSpaceString.length){var pos$1=Pos(n,curSpaceString.length);replaceOneSelection(doc,i$1,new Range(pos$1,pos$1));break}}}}
var lastCopied=null;function setLastCopied(newLastCopied){lastCopied=newLastCopied;}
function applyTextInput(cm,inserted,deleted,sel,origin){var doc=cm.doc;cm.display.shift=false;if(!sel){sel=doc.sel;}
var paste=cm.state.pasteIncoming||origin=="paste";var textLines=splitLinesAuto(inserted),multiPaste=null;if(paste&&sel.ranges.length>1){if(lastCopied&&lastCopied.text.join("\n")==inserted){if(sel.ranges.length%lastCopied.text.length==0){multiPaste=[];for(var i=0;i<lastCopied.text.length;i++)
{multiPaste.push(doc.splitLines(lastCopied.text[i]));}}}else if(textLines.length==sel.ranges.length&&cm.options.pasteLinesPerSelection){multiPaste=map(textLines,function(l){return[l];});}}
var updateInput=cm.curOp.updateInput;for(var i$1=sel.ranges.length-1;i$1>=0;i$1--){var range$$1=sel.ranges[i$1];var from=range$$1.from(),to=range$$1.to();if(range$$1.empty()){if(deleted&&deleted>0)
{from=Pos(from.line,from.ch-deleted);}
else if(cm.state.overwrite&&!paste)
{to=Pos(to.line,Math.min(getLine(doc,to.line).text.length,to.ch+lst(textLines).length));}
else if(paste&&lastCopied&&lastCopied.lineWise&&lastCopied.text.join("\n")==inserted)
{from=to=Pos(from.line,0);}}
var changeEvent={from:from,to:to,text:multiPaste?multiPaste[i$1%multiPaste.length]:textLines,origin:origin||(paste?"paste":cm.state.cutIncoming?"cut":"+input")};makeChange(cm.doc,changeEvent);signalLater(cm,"inputRead",cm,changeEvent);}
if(inserted&&!paste)
{triggerElectric(cm,inserted);}
ensureCursorVisible(cm);if(cm.curOp.updateInput<2){cm.curOp.updateInput=updateInput;}
cm.curOp.typing=true;cm.state.pasteIncoming=cm.state.cutIncoming=false;}
function handlePaste(e,cm){var pasted=e.clipboardData&&e.clipboardData.getData("Text");if(pasted){e.preventDefault();if(!cm.isReadOnly()&&!cm.options.disableInput)
{runInOp(cm,function(){return applyTextInput(cm,pasted,0,null,"paste");});}
return true}}
function triggerElectric(cm,inserted){if(!cm.options.electricChars||!cm.options.smartIndent){return}
var sel=cm.doc.sel;for(var i=sel.ranges.length-1;i>=0;i--){var range$$1=sel.ranges[i];if(range$$1.head.ch>100||(i&&sel.ranges[i-1].head.line==range$$1.head.line)){continue}
var mode=cm.getModeAt(range$$1.head);var indented=false;if(mode.electricChars){for(var j=0;j<mode.electricChars.length;j++)
{if(inserted.indexOf(mode.electricChars.charAt(j))>-1){indented=indentLine(cm,range$$1.head.line,"smart");break}}}else if(mode.electricInput){if(mode.electricInput.test(getLine(cm.doc,range$$1.head.line).text.slice(0,range$$1.head.ch)))
{indented=indentLine(cm,range$$1.head.line,"smart");}}
if(indented){signalLater(cm,"electricInput",cm,range$$1.head.line);}}}
function copyableRanges(cm){var text=[],ranges=[];for(var i=0;i<cm.doc.sel.ranges.length;i++){var line=cm.doc.sel.ranges[i].head.line;var lineRange={anchor:Pos(line,0),head:Pos(line+1,0)};ranges.push(lineRange);text.push(cm.getRange(lineRange.anchor,lineRange.head));}
return{text:text,ranges:ranges}}
function disableBrowserMagic(field,spellcheck){field.setAttribute("autocorrect","off");field.setAttribute("autocapitalize","off");field.setAttribute("spellcheck",!!spellcheck);}
function hiddenTextarea(){var te=elt("textarea",null,null,"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");var div=elt("div",[te],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");if(webkit){te.style.width="1000px";}
else{te.setAttribute("wrap","off");}
if(ios){te.style.border="1px solid black";}
disableBrowserMagic(te);return div}
function addEditorMethods(CodeMirror){var optionHandlers=CodeMirror.optionHandlers;var helpers=CodeMirror.helpers={};CodeMirror.prototype={constructor:CodeMirror,focus:function(){window.focus();this.display.input.focus();},setOption:function(option,value){var options=this.options,old=options[option];if(options[option]==value&&option!="mode"){return}
options[option]=value;if(optionHandlers.hasOwnProperty(option))
{operation(this,optionHandlers[option])(this,value,old);}
signal(this,"optionChange",this,option);},getOption:function(option){return this.options[option]},getDoc:function(){return this.doc},addKeyMap:function(map$$1,bottom){this.state.keyMaps[bottom?"push":"unshift"](getKeyMap(map$$1));},removeKeyMap:function(map$$1){var maps=this.state.keyMaps;for(var i=0;i<maps.length;++i)
{if(maps[i]==map$$1||maps[i].name==map$$1){maps.splice(i,1);return true}}},addOverlay:methodOp(function(spec,options){var mode=spec.token?spec:CodeMirror.getMode(this.options,spec);if(mode.startState){throw new Error("Overlays may not be stateful.")}
insertSorted(this.state.overlays,{mode:mode,modeSpec:spec,opaque:options&&options.opaque,priority:(options&&options.priority)||0},function(overlay){return overlay.priority;});this.state.modeGen++;regChange(this);}),removeOverlay:methodOp(function(spec){var overlays=this.state.overlays;for(var i=0;i<overlays.length;++i){var cur=overlays[i].modeSpec;if(cur==spec||typeof spec=="string"&&cur.name==spec){overlays.splice(i,1);this.state.modeGen++;regChange(this);return}}}),indentLine:methodOp(function(n,dir,aggressive){if(typeof dir!="string"&&typeof dir!="number"){if(dir==null){dir=this.options.smartIndent?"smart":"prev";}
else{dir=dir?"add":"subtract";}}
if(isLine(this.doc,n)){indentLine(this,n,dir,aggressive);}}),indentSelection:methodOp(function(how){var ranges=this.doc.sel.ranges,end=-1;for(var i=0;i<ranges.length;i++){var range$$1=ranges[i];if(!range$$1.empty()){var from=range$$1.from(),to=range$$1.to();var start=Math.max(end,from.line);end=Math.min(this.lastLine(),to.line-(to.ch?0:1))+1;for(var j=start;j<end;++j)
{indentLine(this,j,how);}
var newRanges=this.doc.sel.ranges;if(from.ch==0&&ranges.length==newRanges.length&&newRanges[i].from().ch>0)
{replaceOneSelection(this.doc,i,new Range(from,newRanges[i].to()),sel_dontScroll);}}else if(range$$1.head.line>end){indentLine(this,range$$1.head.line,how,true);end=range$$1.head.line;if(i==this.doc.sel.primIndex){ensureCursorVisible(this);}}}}),getTokenAt:function(pos,precise){return takeToken(this,pos,precise)},getLineTokens:function(line,precise){return takeToken(this,Pos(line),precise,true)},getTokenTypeAt:function(pos){pos=clipPos(this.doc,pos);var styles=getLineStyles(this,getLine(this.doc,pos.line));var before=0,after=(styles.length-1)/2,ch=pos.ch;var type;if(ch==0){type=styles[2];}
else{for(;;){var mid=(before+after)>>1;if((mid?styles[mid*2-1]:0)>=ch){after=mid;}
else if(styles[mid*2+1]<ch){before=mid+1;}
else{type=styles[mid*2+2];break}}}
var cut=type?type.indexOf("overlay "):-1;return cut<0?type:cut==0?null:type.slice(0,cut-1)},getModeAt:function(pos){var mode=this.doc.mode;if(!mode.innerMode){return mode}
return CodeMirror.innerMode(mode,this.getTokenAt(pos).state).mode},getHelper:function(pos,type){return this.getHelpers(pos,type)[0]},getHelpers:function(pos,type){var found=[];if(!helpers.hasOwnProperty(type)){return found}
var help=helpers[type],mode=this.getModeAt(pos);if(typeof mode[type]=="string"){if(help[mode[type]]){found.push(help[mode[type]]);}}else if(mode[type]){for(var i=0;i<mode[type].length;i++){var val=help[mode[type][i]];if(val){found.push(val);}}}else if(mode.helperType&&help[mode.helperType]){found.push(help[mode.helperType]);}else if(help[mode.name]){found.push(help[mode.name]);}
for(var i$1=0;i$1<help._global.length;i$1++){var cur=help._global[i$1];if(cur.pred(mode,this)&&indexOf(found,cur.val)==-1)
{found.push(cur.val);}}
return found},getStateAfter:function(line,precise){var doc=this.doc;line=clipLine(doc,line==null?doc.first+doc.size-1:line);return getContextBefore(this,line+1,precise).state},cursorCoords:function(start,mode){var pos,range$$1=this.doc.sel.primary();if(start==null){pos=range$$1.head;}
else if(typeof start=="object"){pos=clipPos(this.doc,start);}
else{pos=start?range$$1.from():range$$1.to();}
return cursorCoords(this,pos,mode||"page")},charCoords:function(pos,mode){return charCoords(this,clipPos(this.doc,pos),mode||"page")},coordsChar:function(coords,mode){coords=fromCoordSystem(this,coords,mode||"page");return coordsChar(this,coords.left,coords.top)},lineAtHeight:function(height,mode){height=fromCoordSystem(this,{top:height,left:0},mode||"page").top;return lineAtHeight(this.doc,height+this.display.viewOffset)},heightAtLine:function(line,mode,includeWidgets){var end=false,lineObj;if(typeof line=="number"){var last=this.doc.first+this.doc.size-1;if(line<this.doc.first){line=this.doc.first;}
else if(line>last){line=last;end=true;}
lineObj=getLine(this.doc,line);}else{lineObj=line;}
return intoCoordSystem(this,lineObj,{top:0,left:0},mode||"page",includeWidgets||end).top+
(end?this.doc.height-heightAtLine(lineObj):0)},defaultTextHeight:function(){return textHeight(this.display)},defaultCharWidth:function(){return charWidth(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(pos,node,scroll,vert,horiz){var display=this.display;pos=cursorCoords(this,clipPos(this.doc,pos));var top=pos.bottom,left=pos.left;node.style.position="absolute";node.setAttribute("cm-ignore-events","true");this.display.input.setUneditable(node);display.sizer.appendChild(node);if(vert=="over"){top=pos.top;}else if(vert=="above"||vert=="near"){var vspace=Math.max(display.wrapper.clientHeight,this.doc.height),hspace=Math.max(display.sizer.clientWidth,display.lineSpace.clientWidth);if((vert=='above'||pos.bottom+node.offsetHeight>vspace)&&pos.top>node.offsetHeight)
{top=pos.top-node.offsetHeight;}
else if(pos.bottom+node.offsetHeight<=vspace)
{top=pos.bottom;}
if(left+node.offsetWidth>hspace)
{left=hspace-node.offsetWidth;}}
node.style.top=top+"px";node.style.left=node.style.right="";if(horiz=="right"){left=display.sizer.clientWidth-node.offsetWidth;node.style.right="0px";}else{if(horiz=="left"){left=0;}
else if(horiz=="middle"){left=(display.sizer.clientWidth-node.offsetWidth)/2;}
node.style.left=left+"px";}
if(scroll)
{scrollIntoView(this,{left:left,top:top,right:left+node.offsetWidth,bottom:top+node.offsetHeight});}},triggerOnKeyDown:methodOp(onKeyDown),triggerOnKeyPress:methodOp(onKeyPress),triggerOnKeyUp:onKeyUp,triggerOnMouseDown:methodOp(onMouseDown),execCommand:function(cmd){if(commands.hasOwnProperty(cmd))
{return commands[cmd].call(null,this)}},triggerElectric:methodOp(function(text){triggerElectric(this,text);}),findPosH:function(from,amount,unit,visually){var dir=1;if(amount<0){dir=-1;amount=-amount;}
var cur=clipPos(this.doc,from);for(var i=0;i<amount;++i){cur=findPosH(this.doc,cur,dir,unit,visually);if(cur.hitSide){break}}
return cur},moveH:methodOp(function(dir,unit){var this$1=this;this.extendSelectionsBy(function(range$$1){if(this$1.display.shift||this$1.doc.extend||range$$1.empty())
{return findPosH(this$1.doc,range$$1.head,dir,unit,this$1.options.rtlMoveVisually)}
else
{return dir<0?range$$1.from():range$$1.to()}},sel_move);}),deleteH:methodOp(function(dir,unit){var sel=this.doc.sel,doc=this.doc;if(sel.somethingSelected())
{doc.replaceSelection("",null,"+delete");}
else
{deleteNearSelection(this,function(range$$1){var other=findPosH(doc,range$$1.head,dir,unit,false);return dir<0?{from:other,to:range$$1.head}:{from:range$$1.head,to:other}});}}),findPosV:function(from,amount,unit,goalColumn){var dir=1,x=goalColumn;if(amount<0){dir=-1;amount=-amount;}
var cur=clipPos(this.doc,from);for(var i=0;i<amount;++i){var coords=cursorCoords(this,cur,"div");if(x==null){x=coords.left;}
else{coords.left=x;}
cur=findPosV(this,coords,dir,unit);if(cur.hitSide){break}}
return cur},moveV:methodOp(function(dir,unit){var this$1=this;var doc=this.doc,goals=[];var collapse=!this.display.shift&&!doc.extend&&doc.sel.somethingSelected();doc.extendSelectionsBy(function(range$$1){if(collapse)
{return dir<0?range$$1.from():range$$1.to()}
var headPos=cursorCoords(this$1,range$$1.head,"div");if(range$$1.goalColumn!=null){headPos.left=range$$1.goalColumn;}
goals.push(headPos.left);var pos=findPosV(this$1,headPos,dir,unit);if(unit=="page"&&range$$1==doc.sel.primary())
{addToScrollTop(this$1,charCoords(this$1,pos,"div").top-headPos.top);}
return pos},sel_move);if(goals.length){for(var i=0;i<doc.sel.ranges.length;i++)
{doc.sel.ranges[i].goalColumn=goals[i];}}}),findWordAt:function(pos){var doc=this.doc,line=getLine(doc,pos.line).text;var start=pos.ch,end=pos.ch;if(line){var helper=this.getHelper(pos,"wordChars");if((pos.sticky=="before"||end==line.length)&&start){--start;}else{++end;}
var startChar=line.charAt(start);var check=isWordChar(startChar,helper)?function(ch){return isWordChar(ch,helper);}:/\s/.test(startChar)?function(ch){return/\s/.test(ch);}:function(ch){return(!/\s/.test(ch)&&!isWordChar(ch));};while(start>0&&check(line.charAt(start-1))){--start;}
while(end<line.length&&check(line.charAt(end))){++end;}}
return new Range(Pos(pos.line,start),Pos(pos.line,end))},toggleOverwrite:function(value){if(value!=null&&value==this.state.overwrite){return}
if(this.state.overwrite=!this.state.overwrite)
{addClass(this.display.cursorDiv,"CodeMirror-overwrite");}
else
{rmClass(this.display.cursorDiv,"CodeMirror-overwrite");}
signal(this,"overwriteToggle",this,this.state.overwrite);},hasFocus:function(){return this.display.input.getField()==activeElt()},isReadOnly:function(){return!!(this.options.readOnly||this.doc.cantEdit)},scrollTo:methodOp(function(x,y){scrollToCoords(this,x,y);}),getScrollInfo:function(){var scroller=this.display.scroller;return{left:scroller.scrollLeft,top:scroller.scrollTop,height:scroller.scrollHeight-scrollGap(this)-this.display.barHeight,width:scroller.scrollWidth-scrollGap(this)-this.display.barWidth,clientHeight:displayHeight(this),clientWidth:displayWidth(this)}},scrollIntoView:methodOp(function(range$$1,margin){if(range$$1==null){range$$1={from:this.doc.sel.primary().head,to:null};if(margin==null){margin=this.options.cursorScrollMargin;}}else if(typeof range$$1=="number"){range$$1={from:Pos(range$$1,0),to:null};}else if(range$$1.from==null){range$$1={from:range$$1,to:null};}
if(!range$$1.to){range$$1.to=range$$1.from;}
range$$1.margin=margin||0;if(range$$1.from.line!=null){scrollToRange(this,range$$1);}else{scrollToCoordsRange(this,range$$1.from,range$$1.to,range$$1.margin);}}),setSize:methodOp(function(width,height){var this$1=this;var interpret=function(val){return typeof val=="number"||/^\d+$/.test(String(val))?val+"px":val;};if(width!=null){this.display.wrapper.style.width=interpret(width);}
if(height!=null){this.display.wrapper.style.height=interpret(height);}
if(this.options.lineWrapping){clearLineMeasurementCache(this);}
var lineNo$$1=this.display.viewFrom;this.doc.iter(lineNo$$1,this.display.viewTo,function(line){if(line.widgets){for(var i=0;i<line.widgets.length;i++)
{if(line.widgets[i].noHScroll){regLineChange(this$1,lineNo$$1,"widget");break}}}
++lineNo$$1;});this.curOp.forceUpdate=true;signal(this,"refresh",this);}),operation:function(f){return runInOp(this,f)},startOperation:function(){return startOperation(this)},endOperation:function(){return endOperation(this)},refresh:methodOp(function(){var oldHeight=this.display.cachedTextHeight;regChange(this);this.curOp.forceUpdate=true;clearCaches(this);scrollToCoords(this,this.doc.scrollLeft,this.doc.scrollTop);updateGutterSpace(this);if(oldHeight==null||Math.abs(oldHeight-textHeight(this.display))>.5)
{estimateLineHeights(this);}
signal(this,"refresh",this);}),swapDoc:methodOp(function(doc){var old=this.doc;old.cm=null;attachDoc(this,doc);clearCaches(this);this.display.input.reset();scrollToCoords(this,doc.scrollLeft,doc.scrollTop);this.curOp.forceScroll=true;signalLater(this,"swapDoc",this,old);return old}),phrase:function(phraseText){var phrases=this.options.phrases;return phrases&&Object.prototype.hasOwnProperty.call(phrases,phraseText)?phrases[phraseText]:phraseText},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};eventMixin(CodeMirror);CodeMirror.registerHelper=function(type,name,value){if(!helpers.hasOwnProperty(type)){helpers[type]=CodeMirror[type]={_global:[]};}
helpers[type][name]=value;};CodeMirror.registerGlobalHelper=function(type,name,predicate,value){CodeMirror.registerHelper(type,name,value);helpers[type]._global.push({pred:predicate,val:value});};}
function findPosH(doc,pos,dir,unit,visually){var oldPos=pos;var origDir=dir;var lineObj=getLine(doc,pos.line);function findNextLine(){var l=pos.line+dir;if(l<doc.first||l>=doc.first+doc.size){return false}
pos=new Pos(l,pos.ch,pos.sticky);return lineObj=getLine(doc,l)}
function moveOnce(boundToLine){var next;if(visually){next=moveVisually(doc.cm,lineObj,pos,dir);}else{next=moveLogically(lineObj,pos,dir);}
if(next==null){if(!boundToLine&&findNextLine())
{pos=endOfLine(visually,doc.cm,lineObj,pos.line,dir);}
else
{return false}}else{pos=next;}
return true}
if(unit=="char"){moveOnce();}else if(unit=="column"){moveOnce(true);}else if(unit=="word"||unit=="group"){var sawType=null,group=unit=="group";var helper=doc.cm&&doc.cm.getHelper(pos,"wordChars");for(var first=true;;first=false){if(dir<0&&!moveOnce(!first)){break}
var cur=lineObj.text.charAt(pos.ch)||"\n";var type=isWordChar(cur,helper)?"w":group&&cur=="\n"?"n":!group||/\s/.test(cur)?null:"p";if(group&&!first&&!type){type="s";}
if(sawType&&sawType!=type){if(dir<0){dir=1;moveOnce();pos.sticky="after";}
break}
if(type){sawType=type;}
if(dir>0&&!moveOnce(!first)){break}}}
var result=skipAtomic(doc,pos,oldPos,origDir,true);if(equalCursorPos(oldPos,result)){result.hitSide=true;}
return result}
function findPosV(cm,pos,dir,unit){var doc=cm.doc,x=pos.left,y;if(unit=="page"){var pageSize=Math.min(cm.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);var moveAmount=Math.max(pageSize-.5*textHeight(cm.display),3);y=(dir>0?pos.bottom:pos.top)+dir*moveAmount;}else if(unit=="line"){y=dir>0?pos.bottom+3:pos.top-3;}
var target;for(;;){target=coordsChar(cm,x,y);if(!target.outside){break}
if(dir<0?y<=0:y>=doc.height){target.hitSide=true;break}
y+=dir*5;}
return target}
var ContentEditableInput=function(cm){this.cm=cm;this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null;this.polling=new Delayed();this.composing=null;this.gracePeriod=false;this.readDOMTimeout=null;};ContentEditableInput.prototype.init=function(display){var this$1=this;var input=this,cm=input.cm;var div=input.div=display.lineDiv;disableBrowserMagic(div,cm.options.spellcheck);on(div,"paste",function(e){if(signalDOMEvent(cm,e)||handlePaste(e,cm)){return}
if(ie_version<=11){setTimeout(operation(cm,function(){return this$1.updateFromDOM();}),20);}});on(div,"compositionstart",function(e){this$1.composing={data:e.data,done:false};});on(div,"compositionupdate",function(e){if(!this$1.composing){this$1.composing={data:e.data,done:false};}});on(div,"compositionend",function(e){if(this$1.composing){if(e.data!=this$1.composing.data){this$1.readFromDOMSoon();}
this$1.composing.done=true;}});on(div,"touchstart",function(){return input.forceCompositionEnd();});on(div,"input",function(){if(!this$1.composing){this$1.readFromDOMSoon();}});function onCopyCut(e){if(signalDOMEvent(cm,e)){return}
if(cm.somethingSelected()){setLastCopied({lineWise:false,text:cm.getSelections()});if(e.type=="cut"){cm.replaceSelection("",null,"cut");}}else if(!cm.options.lineWiseCopyCut){return}else{var ranges=copyableRanges(cm);setLastCopied({lineWise:true,text:ranges.text});if(e.type=="cut"){cm.operation(function(){cm.setSelections(ranges.ranges,0,sel_dontScroll);cm.replaceSelection("",null,"cut");});}}
if(e.clipboardData){e.clipboardData.clearData();var content=lastCopied.text.join("\n");e.clipboardData.setData("Text",content);if(e.clipboardData.getData("Text")==content){e.preventDefault();return}}
var kludge=hiddenTextarea(),te=kludge.firstChild;cm.display.lineSpace.insertBefore(kludge,cm.display.lineSpace.firstChild);te.value=lastCopied.text.join("\n");var hadFocus=document.activeElement;selectInput(te);setTimeout(function(){cm.display.lineSpace.removeChild(kludge);hadFocus.focus();if(hadFocus==div){input.showPrimarySelection();}},50);}
on(div,"copy",onCopyCut);on(div,"cut",onCopyCut);};ContentEditableInput.prototype.prepareSelection=function(){var result=prepareSelection(this.cm,false);result.focus=this.cm.state.focused;return result};ContentEditableInput.prototype.showSelection=function(info,takeFocus){if(!info||!this.cm.display.view.length){return}
if(info.focus||takeFocus){this.showPrimarySelection();}
this.showMultipleSelections(info);};ContentEditableInput.prototype.getSelection=function(){return this.cm.display.wrapper.ownerDocument.getSelection()};ContentEditableInput.prototype.showPrimarySelection=function(){var sel=this.getSelection(),cm=this.cm,prim=cm.doc.sel.primary();var from=prim.from(),to=prim.to();if(cm.display.viewTo==cm.display.viewFrom||from.line>=cm.display.viewTo||to.line<cm.display.viewFrom){sel.removeAllRanges();return}
var curAnchor=domToPos(cm,sel.anchorNode,sel.anchorOffset);var curFocus=domToPos(cm,sel.focusNode,sel.focusOffset);if(curAnchor&&!curAnchor.bad&&curFocus&&!curFocus.bad&&cmp(minPos(curAnchor,curFocus),from)==0&&cmp(maxPos(curAnchor,curFocus),to)==0)
{return}
var view=cm.display.view;var start=(from.line>=cm.display.viewFrom&&posToDOM(cm,from))||{node:view[0].measure.map[2],offset:0};var end=to.line<cm.display.viewTo&&posToDOM(cm,to);if(!end){var measure=view[view.length-1].measure;var map$$1=measure.maps?measure.maps[measure.maps.length-1]:measure.map;end={node:map$$1[map$$1.length-1],offset:map$$1[map$$1.length-2]-map$$1[map$$1.length-3]};}
if(!start||!end){sel.removeAllRanges();return}
var old=sel.rangeCount&&sel.getRangeAt(0),rng;try{rng=range(start.node,start.offset,end.offset,end.node);}
catch(e){}
if(rng){if(!gecko&&cm.state.focused){sel.collapse(start.node,start.offset);if(!rng.collapsed){sel.removeAllRanges();sel.addRange(rng);}}else{sel.removeAllRanges();sel.addRange(rng);}
if(old&&sel.anchorNode==null){sel.addRange(old);}
else if(gecko){this.startGracePeriod();}}
this.rememberSelection();};ContentEditableInput.prototype.startGracePeriod=function(){var this$1=this;clearTimeout(this.gracePeriod);this.gracePeriod=setTimeout(function(){this$1.gracePeriod=false;if(this$1.selectionChanged())
{this$1.cm.operation(function(){return this$1.cm.curOp.selectionChanged=true;});}},20);};ContentEditableInput.prototype.showMultipleSelections=function(info){removeChildrenAndAdd(this.cm.display.cursorDiv,info.cursors);removeChildrenAndAdd(this.cm.display.selectionDiv,info.selection);};ContentEditableInput.prototype.rememberSelection=function(){var sel=this.getSelection();this.lastAnchorNode=sel.anchorNode;this.lastAnchorOffset=sel.anchorOffset;this.lastFocusNode=sel.focusNode;this.lastFocusOffset=sel.focusOffset;};ContentEditableInput.prototype.selectionInEditor=function(){var sel=this.getSelection();if(!sel.rangeCount){return false}
var node=sel.getRangeAt(0).commonAncestorContainer;return contains(this.div,node)};ContentEditableInput.prototype.focus=function(){if(this.cm.options.readOnly!="nocursor"){if(!this.selectionInEditor())
{this.showSelection(this.prepareSelection(),true);}
this.div.focus();}};ContentEditableInput.prototype.blur=function(){this.div.blur();};ContentEditableInput.prototype.getField=function(){return this.div};ContentEditableInput.prototype.supportsTouch=function(){return true};ContentEditableInput.prototype.receivedFocus=function(){var input=this;if(this.selectionInEditor())
{this.pollSelection();}
else
{runInOp(this.cm,function(){return input.cm.curOp.selectionChanged=true;});}
function poll(){if(input.cm.state.focused){input.pollSelection();input.polling.set(input.cm.options.pollInterval,poll);}}
this.polling.set(this.cm.options.pollInterval,poll);};ContentEditableInput.prototype.selectionChanged=function(){var sel=this.getSelection();return sel.anchorNode!=this.lastAnchorNode||sel.anchorOffset!=this.lastAnchorOffset||sel.focusNode!=this.lastFocusNode||sel.focusOffset!=this.lastFocusOffset};ContentEditableInput.prototype.pollSelection=function(){if(this.readDOMTimeout!=null||this.gracePeriod||!this.selectionChanged()){return}
var sel=this.getSelection(),cm=this.cm;if(android&&chrome&&this.cm.options.gutters.length&&isInGutter(sel.anchorNode)){this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs});this.blur();this.focus();return}
if(this.composing){return}
this.rememberSelection();var anchor=domToPos(cm,sel.anchorNode,sel.anchorOffset);var head=domToPos(cm,sel.focusNode,sel.focusOffset);if(anchor&&head){runInOp(cm,function(){setSelection(cm.doc,simpleSelection(anchor,head),sel_dontScroll);if(anchor.bad||head.bad){cm.curOp.selectionChanged=true;}});}};ContentEditableInput.prototype.pollContent=function(){if(this.readDOMTimeout!=null){clearTimeout(this.readDOMTimeout);this.readDOMTimeout=null;}
var cm=this.cm,display=cm.display,sel=cm.doc.sel.primary();var from=sel.from(),to=sel.to();if(from.ch==0&&from.line>cm.firstLine())
{from=Pos(from.line-1,getLine(cm.doc,from.line-1).length);}
if(to.ch==getLine(cm.doc,to.line).text.length&&to.line<cm.lastLine())
{to=Pos(to.line+1,0);}
if(from.line<display.viewFrom||to.line>display.viewTo-1){return false}
var fromIndex,fromLine,fromNode;if(from.line==display.viewFrom||(fromIndex=findViewIndex(cm,from.line))==0){fromLine=lineNo(display.view[0].line);fromNode=display.view[0].node;}else{fromLine=lineNo(display.view[fromIndex].line);fromNode=display.view[fromIndex-1].node.nextSibling;}
var toIndex=findViewIndex(cm,to.line);var toLine,toNode;if(toIndex==display.view.length-1){toLine=display.viewTo-1;toNode=display.lineDiv.lastChild;}else{toLine=lineNo(display.view[toIndex+1].line)-1;toNode=display.view[toIndex+1].node.previousSibling;}
if(!fromNode){return false}
var newText=cm.doc.splitLines(domTextBetween(cm,fromNode,toNode,fromLine,toLine));var oldText=getBetween(cm.doc,Pos(fromLine,0),Pos(toLine,getLine(cm.doc,toLine).text.length));while(newText.length>1&&oldText.length>1){if(lst(newText)==lst(oldText)){newText.pop();oldText.pop();toLine--;}
else if(newText[0]==oldText[0]){newText.shift();oldText.shift();fromLine++;}
else{break}}
var cutFront=0,cutEnd=0;var newTop=newText[0],oldTop=oldText[0],maxCutFront=Math.min(newTop.length,oldTop.length);while(cutFront<maxCutFront&&newTop.charCodeAt(cutFront)==oldTop.charCodeAt(cutFront))
{++cutFront;}
var newBot=lst(newText),oldBot=lst(oldText);var maxCutEnd=Math.min(newBot.length-(newText.length==1?cutFront:0),oldBot.length-(oldText.length==1?cutFront:0));while(cutEnd<maxCutEnd&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1))
{++cutEnd;}
if(newText.length==1&&oldText.length==1&&fromLine==from.line){while(cutFront&&cutFront>from.ch&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1)){cutFront--;cutEnd++;}}
newText[newText.length-1]=newBot.slice(0,newBot.length-cutEnd).replace(/^\u200b+/,"");newText[0]=newText[0].slice(cutFront).replace(/\u200b+$/,"");var chFrom=Pos(fromLine,cutFront);var chTo=Pos(toLine,oldText.length?lst(oldText).length-cutEnd:0);if(newText.length>1||newText[0]||cmp(chFrom,chTo)){replaceRange(cm.doc,newText,chFrom,chTo,"+input");return true}};ContentEditableInput.prototype.ensurePolled=function(){this.forceCompositionEnd();};ContentEditableInput.prototype.reset=function(){this.forceCompositionEnd();};ContentEditableInput.prototype.forceCompositionEnd=function(){if(!this.composing){return}
clearTimeout(this.readDOMTimeout);this.composing=null;this.updateFromDOM();this.div.blur();this.div.focus();};ContentEditableInput.prototype.readFromDOMSoon=function(){var this$1=this;if(this.readDOMTimeout!=null){return}
this.readDOMTimeout=setTimeout(function(){this$1.readDOMTimeout=null;if(this$1.composing){if(this$1.composing.done){this$1.composing=null;}
else{return}}
this$1.updateFromDOM();},80);};ContentEditableInput.prototype.updateFromDOM=function(){var this$1=this;if(this.cm.isReadOnly()||!this.pollContent())
{runInOp(this.cm,function(){return regChange(this$1.cm);});}};ContentEditableInput.prototype.setUneditable=function(node){node.contentEditable="false";};ContentEditableInput.prototype.onKeyPress=function(e){if(e.charCode==0||this.composing){return}
e.preventDefault();if(!this.cm.isReadOnly())
{operation(this.cm,applyTextInput)(this.cm,String.fromCharCode(e.charCode==null?e.keyCode:e.charCode),0);}};ContentEditableInput.prototype.readOnlyChanged=function(val){this.div.contentEditable=String(val!="nocursor");};ContentEditableInput.prototype.onContextMenu=function(){};ContentEditableInput.prototype.resetPosition=function(){};ContentEditableInput.prototype.needsContentAttribute=true;function posToDOM(cm,pos){var view=findViewForLine(cm,pos.line);if(!view||view.hidden){return null}
var line=getLine(cm.doc,pos.line);var info=mapFromLineView(view,line,pos.line);var order=getOrder(line,cm.doc.direction),side="left";if(order){var partPos=getBidiPartAt(order,pos.ch);side=partPos%2?"right":"left";}
var result=nodeAndOffsetInLineMap(info.map,pos.ch,side);result.offset=result.collapse=="right"?result.end:result.start;return result}
function isInGutter(node){for(var scan=node;scan;scan=scan.parentNode)
{if(/CodeMirror-gutter-wrapper/.test(scan.className)){return true}}
return false}
function badPos(pos,bad){if(bad){pos.bad=true;}return pos}
function domTextBetween(cm,from,to,fromLine,toLine){var text="",closing=false,lineSep=cm.doc.lineSeparator(),extraLinebreak=false;function recognizeMarker(id){return function(marker){return marker.id==id;}}
function close(){if(closing){text+=lineSep;if(extraLinebreak){text+=lineSep;}
closing=extraLinebreak=false;}}
function addText(str){if(str){close();text+=str;}}
function walk(node){if(node.nodeType==1){var cmText=node.getAttribute("cm-text");if(cmText){addText(cmText);return}
var markerID=node.getAttribute("cm-marker"),range$$1;if(markerID){var found=cm.findMarks(Pos(fromLine,0),Pos(toLine+1,0),recognizeMarker(+markerID));if(found.length&&(range$$1=found[0].find(0)))
{addText(getBetween(cm.doc,range$$1.from,range$$1.to).join(lineSep));}
return}
if(node.getAttribute("contenteditable")=="false"){return}
var isBlock=/^(pre|div|p|li|table|br)$/i.test(node.nodeName);if(!/^br$/i.test(node.nodeName)&&node.textContent.length==0){return}
if(isBlock){close();}
for(var i=0;i<node.childNodes.length;i++)
{walk(node.childNodes[i]);}
if(/^(pre|p)$/i.test(node.nodeName)){extraLinebreak=true;}
if(isBlock){closing=true;}}else if(node.nodeType==3){addText(node.nodeValue.replace(/\u200b/g,"").replace(/\u00a0/g," "));}}
for(;;){walk(from);if(from==to){break}
from=from.nextSibling;extraLinebreak=false;}
return text}
function domToPos(cm,node,offset){var lineNode;if(node==cm.display.lineDiv){lineNode=cm.display.lineDiv.childNodes[offset];if(!lineNode){return badPos(cm.clipPos(Pos(cm.display.viewTo-1)),true)}
node=null;offset=0;}else{for(lineNode=node;;lineNode=lineNode.parentNode){if(!lineNode||lineNode==cm.display.lineDiv){return null}
if(lineNode.parentNode&&lineNode.parentNode==cm.display.lineDiv){break}}}
for(var i=0;i<cm.display.view.length;i++){var lineView=cm.display.view[i];if(lineView.node==lineNode)
{return locateNodeInLineView(lineView,node,offset)}}}
function locateNodeInLineView(lineView,node,offset){var wrapper=lineView.text.firstChild,bad=false;if(!node||!contains(wrapper,node)){return badPos(Pos(lineNo(lineView.line),0),true)}
if(node==wrapper){bad=true;node=wrapper.childNodes[offset];offset=0;if(!node){var line=lineView.rest?lst(lineView.rest):lineView.line;return badPos(Pos(lineNo(line),line.text.length),bad)}}
var textNode=node.nodeType==3?node:null,topNode=node;if(!textNode&&node.childNodes.length==1&&node.firstChild.nodeType==3){textNode=node.firstChild;if(offset){offset=textNode.nodeValue.length;}}
while(topNode.parentNode!=wrapper){topNode=topNode.parentNode;}
var measure=lineView.measure,maps=measure.maps;function find(textNode,topNode,offset){for(var i=-1;i<(maps?maps.length:0);i++){var map$$1=i<0?measure.map:maps[i];for(var j=0;j<map$$1.length;j+=3){var curNode=map$$1[j+2];if(curNode==textNode||curNode==topNode){var line=lineNo(i<0?lineView.line:lineView.rest[i]);var ch=map$$1[j]+offset;if(offset<0||curNode!=textNode){ch=map$$1[j+(offset?1:0)];}
return Pos(line,ch)}}}}
var found=find(textNode,topNode,offset);if(found){return badPos(found,bad)}
for(var after=topNode.nextSibling,dist=textNode?textNode.nodeValue.length-offset:0;after;after=after.nextSibling){found=find(after,after.firstChild,0);if(found)
{return badPos(Pos(found.line,found.ch-dist),bad)}
else
{dist+=after.textContent.length;}}
for(var before=topNode.previousSibling,dist$1=offset;before;before=before.previousSibling){found=find(before,before.firstChild,-1);if(found)
{return badPos(Pos(found.line,found.ch+dist$1),bad)}
else
{dist$1+=before.textContent.length;}}}
var TextareaInput=function(cm){this.cm=cm;this.prevInput="";this.pollingFast=false;this.polling=new Delayed();this.hasSelection=false;this.composing=null;};TextareaInput.prototype.init=function(display){var this$1=this;var input=this,cm=this.cm;this.createField(display);var te=this.textarea;display.wrapper.insertBefore(this.wrapper,display.wrapper.firstChild);if(ios){te.style.width="0px";}
on(te,"input",function(){if(ie&&ie_version>=9&&this$1.hasSelection){this$1.hasSelection=null;}
input.poll();});on(te,"paste",function(e){if(signalDOMEvent(cm,e)||handlePaste(e,cm)){return}
cm.state.pasteIncoming=true;input.fastPoll();});function prepareCopyCut(e){if(signalDOMEvent(cm,e)){return}
if(cm.somethingSelected()){setLastCopied({lineWise:false,text:cm.getSelections()});}else if(!cm.options.lineWiseCopyCut){return}else{var ranges=copyableRanges(cm);setLastCopied({lineWise:true,text:ranges.text});if(e.type=="cut"){cm.setSelections(ranges.ranges,null,sel_dontScroll);}else{input.prevInput="";te.value=ranges.text.join("\n");selectInput(te);}}
if(e.type=="cut"){cm.state.cutIncoming=true;}}
on(te,"cut",prepareCopyCut);on(te,"copy",prepareCopyCut);on(display.scroller,"paste",function(e){if(eventInWidget(display,e)||signalDOMEvent(cm,e)){return}
cm.state.pasteIncoming=true;input.focus();});on(display.lineSpace,"selectstart",function(e){if(!eventInWidget(display,e)){e_preventDefault(e);}});on(te,"compositionstart",function(){var start=cm.getCursor("from");if(input.composing){input.composing.range.clear();}
input.composing={start:start,range:cm.markText(start,cm.getCursor("to"),{className:"CodeMirror-composing"})};});on(te,"compositionend",function(){if(input.composing){input.poll();input.composing.range.clear();input.composing=null;}});};TextareaInput.prototype.createField=function(_display){this.wrapper=hiddenTextarea();this.textarea=this.wrapper.firstChild;};TextareaInput.prototype.prepareSelection=function(){var cm=this.cm,display=cm.display,doc=cm.doc;var result=prepareSelection(cm);if(cm.options.moveInputWithCursor){var headPos=cursorCoords(cm,doc.sel.primary().head,"div");var wrapOff=display.wrapper.getBoundingClientRect(),lineOff=display.lineDiv.getBoundingClientRect();result.teTop=Math.max(0,Math.min(display.wrapper.clientHeight-10,headPos.top+lineOff.top-wrapOff.top));result.teLeft=Math.max(0,Math.min(display.wrapper.clientWidth-10,headPos.left+lineOff.left-wrapOff.left));}
return result};TextareaInput.prototype.showSelection=function(drawn){var cm=this.cm,display=cm.display;removeChildrenAndAdd(display.cursorDiv,drawn.cursors);removeChildrenAndAdd(display.selectionDiv,drawn.selection);if(drawn.teTop!=null){this.wrapper.style.top=drawn.teTop+"px";this.wrapper.style.left=drawn.teLeft+"px";}};TextareaInput.prototype.reset=function(typing){if(this.contextMenuPending||this.composing){return}
var cm=this.cm;if(cm.somethingSelected()){this.prevInput="";var content=cm.getSelection();this.textarea.value=content;if(cm.state.focused){selectInput(this.textarea);}
if(ie&&ie_version>=9){this.hasSelection=content;}}else if(!typing){this.prevInput=this.textarea.value="";if(ie&&ie_version>=9){this.hasSelection=null;}}};TextareaInput.prototype.getField=function(){return this.textarea};TextareaInput.prototype.supportsTouch=function(){return false};TextareaInput.prototype.focus=function(){if(this.cm.options.readOnly!="nocursor"&&(!mobile||activeElt()!=this.textarea)){try{this.textarea.focus();}
catch(e){}}};TextareaInput.prototype.blur=function(){this.textarea.blur();};TextareaInput.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0;};TextareaInput.prototype.receivedFocus=function(){this.slowPoll();};TextareaInput.prototype.slowPoll=function(){var this$1=this;if(this.pollingFast){return}
this.polling.set(this.cm.options.pollInterval,function(){this$1.poll();if(this$1.cm.state.focused){this$1.slowPoll();}});};TextareaInput.prototype.fastPoll=function(){var missed=false,input=this;input.pollingFast=true;function p(){var changed=input.poll();if(!changed&&!missed){missed=true;input.polling.set(60,p);}
else{input.pollingFast=false;input.slowPoll();}}
input.polling.set(20,p);};TextareaInput.prototype.poll=function(){var this$1=this;var cm=this.cm,input=this.textarea,prevInput=this.prevInput;if(this.contextMenuPending||!cm.state.focused||(hasSelection(input)&&!prevInput&&!this.composing)||cm.isReadOnly()||cm.options.disableInput||cm.state.keySeq)
{return false}
var text=input.value;if(text==prevInput&&!cm.somethingSelected()){return false}
if(ie&&ie_version>=9&&this.hasSelection===text||mac&&/[\uf700-\uf7ff]/.test(text)){cm.display.input.reset();return false}
if(cm.doc.sel==cm.display.selForContextMenu){var first=text.charCodeAt(0);if(first==0x200b&&!prevInput){prevInput="\u200b";}
if(first==0x21da){this.reset();return this.cm.execCommand("undo")}}
var same=0,l=Math.min(prevInput.length,text.length);while(same<l&&prevInput.charCodeAt(same)==text.charCodeAt(same)){++same;}
runInOp(cm,function(){applyTextInput(cm,text.slice(same),prevInput.length-same,null,this$1.composing?"*compose":null);if(text.length>1000||text.indexOf("\n")>-1){input.value=this$1.prevInput="";}
else{this$1.prevInput=text;}
if(this$1.composing){this$1.composing.range.clear();this$1.composing.range=cm.markText(this$1.composing.start,cm.getCursor("to"),{className:"CodeMirror-composing"});}});return true};TextareaInput.prototype.ensurePolled=function(){if(this.pollingFast&&this.poll()){this.pollingFast=false;}};TextareaInput.prototype.onKeyPress=function(){if(ie&&ie_version>=9){this.hasSelection=null;}
this.fastPoll();};TextareaInput.prototype.onContextMenu=function(e){var input=this,cm=input.cm,display=cm.display,te=input.textarea;var pos=posFromMouse(cm,e),scrollPos=display.scroller.scrollTop;if(!pos||presto){return}
var reset=cm.options.resetSelectionOnContextMenu;if(reset&&cm.doc.sel.contains(pos)==-1)
{operation(cm,setSelection)(cm.doc,simpleSelection(pos),sel_dontScroll);}
var oldCSS=te.style.cssText,oldWrapperCSS=input.wrapper.style.cssText;input.wrapper.style.cssText="position: absolute";var wrapperBox=input.wrapper.getBoundingClientRect();te.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-wrapperBox.top-5)+"px; left: "+(e.clientX-wrapperBox.left-5)+"px;\n z-index: 1000; background: "+(ie?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";var oldScrollY;if(webkit){oldScrollY=window.scrollY;}
display.input.focus();if(webkit){window.scrollTo(null,oldScrollY);}
display.input.reset();if(!cm.somethingSelected()){te.value=input.prevInput=" ";}
input.contextMenuPending=true;display.selForContextMenu=cm.doc.sel;clearTimeout(display.detectingSelectAll);function prepareSelectAllHack(){if(te.selectionStart!=null){var selected=cm.somethingSelected();var extval="\u200b"+(selected?te.value:"");te.value="\u21da";te.value=extval;input.prevInput=selected?"":"\u200b";te.selectionStart=1;te.selectionEnd=extval.length;display.selForContextMenu=cm.doc.sel;}}
function rehide(){input.contextMenuPending=false;input.wrapper.style.cssText=oldWrapperCSS;te.style.cssText=oldCSS;if(ie&&ie_version<9){display.scrollbars.setScrollTop(display.scroller.scrollTop=scrollPos);}
if(te.selectionStart!=null){if(!ie||(ie&&ie_version<9)){prepareSelectAllHack();}
var i=0,poll=function(){if(display.selForContextMenu==cm.doc.sel&&te.selectionStart==0&&te.selectionEnd>0&&input.prevInput=="\u200b"){operation(cm,selectAll)(cm);}else if(i++<10){display.detectingSelectAll=setTimeout(poll,500);}else{display.selForContextMenu=null;display.input.reset();}};display.detectingSelectAll=setTimeout(poll,200);}}
if(ie&&ie_version>=9){prepareSelectAllHack();}
if(captureRightClick){e_stop(e);var mouseup=function(){off(window,"mouseup",mouseup);setTimeout(rehide,20);};on(window,"mouseup",mouseup);}else{setTimeout(rehide,50);}};TextareaInput.prototype.readOnlyChanged=function(val){if(!val){this.reset();}
this.textarea.disabled=val=="nocursor";};TextareaInput.prototype.setUneditable=function(){};TextareaInput.prototype.needsContentAttribute=false;function fromTextArea(textarea,options){options=options?copyObj(options):{};options.value=textarea.value;if(!options.tabindex&&textarea.tabIndex)
{options.tabindex=textarea.tabIndex;}
if(!options.placeholder&&textarea.placeholder)
{options.placeholder=textarea.placeholder;}
if(options.autofocus==null){var hasFocus=activeElt();options.autofocus=hasFocus==textarea||textarea.getAttribute("autofocus")!=null&&hasFocus==document.body;}
function save(){textarea.value=cm.getValue();}
var realSubmit;if(textarea.form){on(textarea.form,"submit",save);if(!options.leaveSubmitMethodAlone){var form=textarea.form;realSubmit=form.submit;try{var wrappedSubmit=form.submit=function(){save();form.submit=realSubmit;form.submit();form.submit=wrappedSubmit;};}catch(e){}}}
options.finishInit=function(cm){cm.save=save;cm.getTextArea=function(){return textarea;};cm.toTextArea=function(){cm.toTextArea=isNaN;save();textarea.parentNode.removeChild(cm.getWrapperElement());textarea.style.display="";if(textarea.form){off(textarea.form,"submit",save);if(typeof textarea.form.submit=="function")
{textarea.form.submit=realSubmit;}}};};textarea.style.display="none";var cm=CodeMirror(function(node){return textarea.parentNode.insertBefore(node,textarea.nextSibling);},options);return cm}
function addLegacyProps(CodeMirror){CodeMirror.off=off;CodeMirror.on=on;CodeMirror.wheelEventPixels=wheelEventPixels;CodeMirror.Doc=Doc;CodeMirror.splitLines=splitLinesAuto;CodeMirror.countColumn=countColumn;CodeMirror.findColumn=findColumn;CodeMirror.isWordChar=isWordCharBasic;CodeMirror.Pass=Pass;CodeMirror.signal=signal;CodeMirror.Line=Line;CodeMirror.changeEnd=changeEnd;CodeMirror.scrollbarModel=scrollbarModel;CodeMirror.Pos=Pos;CodeMirror.cmpPos=cmp;CodeMirror.modes=modes;CodeMirror.mimeModes=mimeModes;CodeMirror.resolveMode=resolveMode;CodeMirror.getMode=getMode;CodeMirror.modeExtensions=modeExtensions;CodeMirror.extendMode=extendMode;CodeMirror.copyState=copyState;CodeMirror.startState=startState;CodeMirror.innerMode=innerMode;CodeMirror.commands=commands;CodeMirror.keyMap=keyMap;CodeMirror.keyName=keyName;CodeMirror.isModifierKey=isModifierKey;CodeMirror.lookupKey=lookupKey;CodeMirror.normalizeKeyMap=normalizeKeyMap;CodeMirror.StringStream=StringStream;CodeMirror.SharedTextMarker=SharedTextMarker;CodeMirror.TextMarker=TextMarker;CodeMirror.LineWidget=LineWidget;CodeMirror.e_preventDefault=e_preventDefault;CodeMirror.e_stopPropagation=e_stopPropagation;CodeMirror.e_stop=e_stop;CodeMirror.addClass=addClass;CodeMirror.contains=contains;CodeMirror.rmClass=rmClass;CodeMirror.keyNames=keyNames;}
defineOptions(CodeMirror);addEditorMethods(CodeMirror);var dontDelegate="iter insert remove copy getEditor constructor".split(" ");for(var prop in Doc.prototype){if(Doc.prototype.hasOwnProperty(prop)&&indexOf(dontDelegate,prop)<0)
{CodeMirror.prototype[prop]=(function(method){return function(){return method.apply(this.doc,arguments)}})(Doc.prototype[prop]);}}
eventMixin(Doc);CodeMirror.inputStyles={"textarea":TextareaInput,"contenteditable":ContentEditableInput};CodeMirror.defineMode=function(name){if(!CodeMirror.defaults.mode&&name!="null"){CodeMirror.defaults.mode=name;}
defineMode.apply(this,arguments);};CodeMirror.defineMIME=defineMIME;CodeMirror.defineMode("null",function(){return({token:function(stream){return stream.skipToEnd();}});});CodeMirror.defineMIME("text/plain","null");CodeMirror.defineExtension=function(name,func){CodeMirror.prototype[name]=func;};CodeMirror.defineDocExtension=function(name,func){Doc.prototype[name]=func;};CodeMirror.fromTextArea=fromTextArea;addLegacyProps(CodeMirror);CodeMirror.version="5.42.1";return CodeMirror;})));;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.multiplexingMode=function(outer){var others=Array.prototype.slice.call(arguments,1);function indexOf(string,pattern,from,returnEnd){if(typeof pattern=="string"){var found=string.indexOf(pattern,from);return returnEnd&&found>-1?found+pattern.length:found;}
var m=pattern.exec(from?string.slice(from):string);return m?m.index+from+(returnEnd?m[0].length:0):-1;}
return{startState:function(){return{outer:CodeMirror.startState(outer),innerActive:null,inner:null};},copyState:function(state){return{outer:CodeMirror.copyState(outer,state.outer),innerActive:state.innerActive,inner:state.innerActive&&CodeMirror.copyState(state.innerActive.mode,state.inner)};},token:function(stream,state){if(!state.innerActive){var cutOff=Infinity,oldContent=stream.string;for(var i=0;i<others.length;++i){var other=others[i];var found=indexOf(oldContent,other.open,stream.pos);if(found==stream.pos){if(!other.parseDelimiters)stream.match(other.open);state.innerActive=other;var outerIndent=0;if(outer.indent){var possibleOuterIndent=outer.indent(state.outer,"");if(possibleOuterIndent!==CodeMirror.Pass)outerIndent=possibleOuterIndent;}
state.inner=CodeMirror.startState(other.mode,outerIndent);return other.delimStyle&&(other.delimStyle+" "+other.delimStyle+"-open");}else if(found!=-1&&found<cutOff){cutOff=found;}}
if(cutOff!=Infinity)stream.string=oldContent.slice(0,cutOff);var outerToken=outer.token(stream,state.outer);if(cutOff!=Infinity)stream.string=oldContent;return outerToken;}else{var curInner=state.innerActive,oldContent=stream.string;if(!curInner.close&&stream.sol()){state.innerActive=state.inner=null;return this.token(stream,state);}
var found=curInner.close?indexOf(oldContent,curInner.close,stream.pos,curInner.parseDelimiters):-1;if(found==stream.pos&&!curInner.parseDelimiters){stream.match(curInner.close);state.innerActive=state.inner=null;return curInner.delimStyle&&(curInner.delimStyle+" "+curInner.delimStyle+"-close");}
if(found>-1)stream.string=oldContent.slice(0,found);var innerToken=curInner.mode.token(stream,state.inner);if(found>-1)stream.string=oldContent;if(found==stream.pos&&curInner.parseDelimiters)
state.innerActive=state.inner=null;if(curInner.innerStyle){if(innerToken)innerToken=innerToken+" "+curInner.innerStyle;else innerToken=curInner.innerStyle;}
return innerToken;}},indent:function(state,textAfter){var mode=state.innerActive?state.innerActive.mode:outer;if(!mode.indent)return CodeMirror.Pass;return mode.indent(state.innerActive?state.inner:state.outer,textAfter);},blankLine:function(state){var mode=state.innerActive?state.innerActive.mode:outer;if(mode.blankLine){mode.blankLine(state.innerActive?state.inner:state.outer);}
if(!state.innerActive){for(var i=0;i<others.length;++i){var other=others[i];if(other.open==="\n"){state.innerActive=other;state.inner=CodeMirror.startState(other.mode,mode.indent?mode.indent(state.outer,""):0);}}}else if(state.innerActive.close==="\n"){state.innerActive=state.inner=null;}},electricChars:outer.electricChars,innerMode:function(state){return state.inner?{state:state.inner,mode:state.innerActive.mode}:{state:state.outer,mode:outer};}};};});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){var ie_lt8=/MSIE \d/.test(navigator.userAgent)&&(document.documentMode==null||document.documentMode<8);var Pos=CodeMirror.Pos;var matching={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<","<":">>",">":"<<"};function findMatchingBracket(cm,where,config){var line=cm.getLineHandle(where.line),pos=where.ch-1;var afterCursor=config&&config.afterCursor
if(afterCursor==null)
afterCursor=/(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)
var match=(!afterCursor&&pos>=0&&matching[line.text.charAt(pos)])||matching[line.text.charAt(++pos)];if(!match)return null;var dir=match.charAt(1)==">"?1:-1;if(config&&config.strict&&(dir>0)!=(pos==where.ch))return null;var style=cm.getTokenTypeAt(Pos(where.line,pos+1));var found=scanForBracket(cm,Pos(where.line,pos+(dir>0?1:0)),dir,style||null,config);if(found==null)return null;return{from:Pos(where.line,pos),to:found&&found.pos,match:found&&found.ch==match.charAt(0),forward:dir>0};}
function scanForBracket(cm,where,dir,style,config){var maxScanLen=(config&&config.maxScanLineLength)||10000;var maxScanLines=(config&&config.maxScanLines)||1000;var stack=[];var re=config&&config.bracketRegex?config.bracketRegex:/[(){}[\]<>]/;var lineEnd=dir>0?Math.min(where.line+maxScanLines,cm.lastLine()+1):Math.max(cm.firstLine()-1,where.line-maxScanLines);for(var lineNo=where.line;lineNo!=lineEnd;lineNo+=dir){var line=cm.getLine(lineNo);if(!line)continue;var pos=dir>0?0:line.length-1,end=dir>0?line.length:-1;if(line.length>maxScanLen)continue;if(lineNo==where.line)pos=where.ch-(dir<0?1:0);for(;pos!=end;pos+=dir){var ch=line.charAt(pos);if(re.test(ch)&&(style===undefined||cm.getTokenTypeAt(Pos(lineNo,pos+1))==style)){var match=matching[ch];if((match.charAt(1)==">")==(dir>0))stack.push(ch);else if(!stack.length)return{pos:Pos(lineNo,pos),ch:ch};else stack.pop();}}}
return lineNo-dir==(dir>0?cm.lastLine():cm.firstLine())?false:null;}
function matchBrackets(cm,autoclear,config){var maxHighlightLen=cm.state.matchBrackets.maxHighlightLineLength||1000;var marks=[],ranges=cm.listSelections();for(var i=0;i<ranges.length;i++){var match=ranges[i].empty()&&findMatchingBracket(cm,ranges[i].head,config);if(match&&cm.getLine(match.from.line).length<=maxHighlightLen){var style=match.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";marks.push(cm.markText(match.from,Pos(match.from.line,match.from.ch+1),{className:style}));if(match.to&&cm.getLine(match.to.line).length<=maxHighlightLen)
marks.push(cm.markText(match.to,Pos(match.to.line,match.to.ch+1),{className:style}));}}
if(marks.length){if(ie_lt8&&cm.state.focused)cm.focus();var clear=function(){cm.operation(function(){for(var i=0;i<marks.length;i++)marks[i].clear();});};if(autoclear)setTimeout(clear,800);else return clear;}}
function doMatchBrackets(cm){cm.operation(function(){if(cm.state.matchBrackets.currentlyHighlighted){cm.state.matchBrackets.currentlyHighlighted();cm.state.matchBrackets.currentlyHighlighted=null;}
cm.state.matchBrackets.currentlyHighlighted=matchBrackets(cm,false,cm.state.matchBrackets);});}
CodeMirror.defineOption("matchBrackets",false,function(cm,val,old){if(old&&old!=CodeMirror.Init){cm.off("cursorActivity",doMatchBrackets);if(cm.state.matchBrackets&&cm.state.matchBrackets.currentlyHighlighted){cm.state.matchBrackets.currentlyHighlighted();cm.state.matchBrackets.currentlyHighlighted=null;}}
if(val){cm.state.matchBrackets=typeof val=="object"?val:{};cm.on("cursorActivity",doMatchBrackets);}});CodeMirror.defineExtension("matchBrackets",function(){matchBrackets(this,true);});CodeMirror.defineExtension("findMatchingBracket",function(pos,config,oldConfig){if(oldConfig||typeof config=="boolean"){if(!oldConfig){config=config?{strict:true}:null}else{oldConfig.strict=config
config=oldConfig}}
return findMatchingBracket(this,pos,config)});CodeMirror.defineExtension("scanForBracket",function(pos,dir,style,config){return scanForBracket(this,pos,dir,style,config);});});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){var defaults={pairs:"()[]{}''\"\"",triples:"",explode:"[]{}"};var Pos=CodeMirror.Pos;CodeMirror.defineOption("autoCloseBrackets",false,function(cm,val,old){if(old&&old!=CodeMirror.Init){cm.removeKeyMap(keyMap);cm.state.closeBrackets=null;}
if(val){ensureBound(getOption(val,"pairs"))
cm.state.closeBrackets=val;cm.addKeyMap(keyMap);}});function getOption(conf,name){if(name=="pairs"&&typeof conf=="string")return conf;if(typeof conf=="object"&&conf[name]!=null)return conf[name];return defaults[name];}
var keyMap={Backspace:handleBackspace,Enter:handleEnter};function ensureBound(chars){for(var i=0;i<chars.length;i++){var ch=chars.charAt(i),key="'"+ch+"'"
if(!keyMap[key])keyMap[key]=handler(ch)}}
ensureBound(defaults.pairs+"`")
function handler(ch){return function(cm){return handleChar(cm,ch);};}
function getConfig(cm){var deflt=cm.state.closeBrackets;if(!deflt||deflt.override)return deflt;var mode=cm.getModeAt(cm.getCursor());return mode.closeBrackets||deflt;}
function handleBackspace(cm){var conf=getConfig(cm);if(!conf||cm.getOption("disableInput"))return CodeMirror.Pass;var pairs=getOption(conf,"pairs");var ranges=cm.listSelections();for(var i=0;i<ranges.length;i++){if(!ranges[i].empty())return CodeMirror.Pass;var around=charsAround(cm,ranges[i].head);if(!around||pairs.indexOf(around)%2!=0)return CodeMirror.Pass;}
for(var i=ranges.length-1;i>=0;i--){var cur=ranges[i].head;cm.replaceRange("",Pos(cur.line,cur.ch-1),Pos(cur.line,cur.ch+1),"+delete");}}
function handleEnter(cm){var conf=getConfig(cm);var explode=conf&&getOption(conf,"explode");if(!explode||cm.getOption("disableInput"))return CodeMirror.Pass;var ranges=cm.listSelections();for(var i=0;i<ranges.length;i++){if(!ranges[i].empty())return CodeMirror.Pass;var around=charsAround(cm,ranges[i].head);if(!around||explode.indexOf(around)%2!=0)return CodeMirror.Pass;}
cm.operation(function(){var linesep=cm.lineSeparator()||"\n";cm.replaceSelection(linesep+linesep,null);cm.execCommand("goCharLeft");ranges=cm.listSelections();for(var i=0;i<ranges.length;i++){var line=ranges[i].head.line;cm.indentLine(line,null,true);cm.indentLine(line+1,null,true);}});}
function contractSelection(sel){var inverted=CodeMirror.cmpPos(sel.anchor,sel.head)>0;return{anchor:new Pos(sel.anchor.line,sel.anchor.ch+(inverted?-1:1)),head:new Pos(sel.head.line,sel.head.ch+(inverted?1:-1))};}
function handleChar(cm,ch){var conf=getConfig(cm);if(!conf||cm.getOption("disableInput"))return CodeMirror.Pass;var pairs=getOption(conf,"pairs");var pos=pairs.indexOf(ch);if(pos==-1)return CodeMirror.Pass;var triples=getOption(conf,"triples");var identical=pairs.charAt(pos+1)==ch;var ranges=cm.listSelections();var opening=pos%2==0;var type;for(var i=0;i<ranges.length;i++){var range=ranges[i],cur=range.head,curType;var next=cm.getRange(cur,Pos(cur.line,cur.ch+1));if(opening&&!range.empty()){curType="surround";}else if((identical||!opening)&&next==ch){if(identical&&stringStartsAfter(cm,cur))
curType="both";else if(triples.indexOf(ch)>=0&&cm.getRange(cur,Pos(cur.line,cur.ch+3))==ch+ch+ch)
curType="skipThree";else
curType="skip";}else if(identical&&cur.ch>1&&triples.indexOf(ch)>=0&&cm.getRange(Pos(cur.line,cur.ch-2),cur)==ch+ch){if(cur.ch>2&&/\bstring/.test(cm.getTokenTypeAt(Pos(cur.line,cur.ch-2))))return CodeMirror.Pass;curType="addFour";}else if(identical){var prev=cur.ch==0?" ":cm.getRange(Pos(cur.line,cur.ch-1),cur)
if(!CodeMirror.isWordChar(next)&&prev!=ch&&!CodeMirror.isWordChar(prev))curType="both";else return CodeMirror.Pass;}else if(opening){curType="both";}else{return CodeMirror.Pass;}
if(!type)type=curType;else if(type!=curType)return CodeMirror.Pass;}
var left=pos%2?pairs.charAt(pos-1):ch;var right=pos%2?ch:pairs.charAt(pos+1);cm.operation(function(){if(type=="skip"){cm.execCommand("goCharRight");}else if(type=="skipThree"){for(var i=0;i<3;i++)
cm.execCommand("goCharRight");}else if(type=="surround"){var sels=cm.getSelections();for(var i=0;i<sels.length;i++)
sels[i]=left+sels[i]+right;cm.replaceSelections(sels,"around");sels=cm.listSelections().slice();for(var i=0;i<sels.length;i++)
sels[i]=contractSelection(sels[i]);cm.setSelections(sels);}else if(type=="both"){cm.replaceSelection(left+right,null);cm.triggerElectric(left+right);cm.execCommand("goCharLeft");}else if(type=="addFour"){cm.replaceSelection(left+left+left+left,"before");cm.execCommand("goCharRight");}});}
function charsAround(cm,pos){var str=cm.getRange(Pos(pos.line,pos.ch-1),Pos(pos.line,pos.ch+1));return str.length==2?str:null;}
function stringStartsAfter(cm,pos){var token=cm.getTokenAt(Pos(pos.line,pos.ch+1))
return/\bstring/.test(token.type)&&token.start==pos.ch&&(pos.ch==0||!/\bstring/.test(cm.getTokenTypeAt(pos)))}});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.defineOption("styleSelectedText",false,function(cm,val,old){var prev=old&&old!=CodeMirror.Init;if(val&&!prev){cm.state.markedSelection=[];cm.state.markedSelectionStyle=typeof val=="string"?val:"CodeMirror-selectedtext";reset(cm);cm.on("cursorActivity",onCursorActivity);cm.on("change",onChange);}else if(!val&&prev){cm.off("cursorActivity",onCursorActivity);cm.off("change",onChange);clear(cm);cm.state.markedSelection=cm.state.markedSelectionStyle=null;}});function onCursorActivity(cm){if(cm.state.markedSelection)
cm.operation(function(){update(cm);});}
function onChange(cm){if(cm.state.markedSelection&&cm.state.markedSelection.length)
cm.operation(function(){clear(cm);});}
var CHUNK_SIZE=8;var Pos=CodeMirror.Pos;var cmp=CodeMirror.cmpPos;function coverRange(cm,from,to,addAt){if(cmp(from,to)==0)return;var array=cm.state.markedSelection;var cls=cm.state.markedSelectionStyle;for(var line=from.line;;){var start=line==from.line?from:Pos(line,0);var endLine=line+CHUNK_SIZE,atEnd=endLine>=to.line;var end=atEnd?to:Pos(endLine,0);var mark=cm.markText(start,end,{className:cls});if(addAt==null)array.push(mark);else array.splice(addAt++,0,mark);if(atEnd)break;line=endLine;}}
function clear(cm){var array=cm.state.markedSelection;for(var i=0;i<array.length;++i)array[i].clear();array.length=0;}
function reset(cm){clear(cm);var ranges=cm.listSelections();for(var i=0;i<ranges.length;i++)
coverRange(cm,ranges[i].from(),ranges[i].to());}
function update(cm){if(!cm.somethingSelected())return clear(cm);if(cm.listSelections().length>1)return reset(cm);var from=cm.getCursor("start"),to=cm.getCursor("end");var array=cm.state.markedSelection;if(!array.length)return coverRange(cm,from,to);var coverStart=array[0].find(),coverEnd=array[array.length-1].find();if(!coverStart||!coverEnd||to.line-from.line<=CHUNK_SIZE||cmp(from,coverEnd.to)>=0||cmp(to,coverStart.from)<=0)
return reset(cm);while(cmp(from,coverStart.from)>0){array.shift().clear();coverStart=array[0].find();}
if(cmp(from,coverStart.from)<0){if(coverStart.to.line-from.line<CHUNK_SIZE){array.shift().clear();coverRange(cm,from,coverStart.to,0);}else{coverRange(cm,from,coverStart.from,0);}}
while(cmp(to,coverEnd.to)<0){array.pop().clear();coverEnd=array[array.length-1].find();}
if(cmp(to,coverEnd.to)>0){if(to.line-coverEnd.from.line<CHUNK_SIZE){array.pop().clear();coverRange(cm,coverEnd.from,to);}else{coverRange(cm,coverEnd.to,to);}}}});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";var noOptions={};var nonWS=/[^\s\u00a0]/;var Pos=CodeMirror.Pos;function firstNonWS(str){var found=str.search(nonWS);return found==-1?0:found;}
CodeMirror.commands.toggleComment=function(cm){cm.toggleComment();};CodeMirror.defineExtension("toggleComment",function(options){if(!options)options=noOptions;var cm=this;var minLine=Infinity,ranges=this.listSelections(),mode=null;for(var i=ranges.length-1;i>=0;i--){var from=ranges[i].from(),to=ranges[i].to();if(from.line>=minLine)continue;if(to.line>=minLine)to=Pos(minLine,0);minLine=from.line;if(mode==null){if(cm.uncomment(from,to,options))mode="un";else{cm.lineComment(from,to,options);mode="line";}}else if(mode=="un"){cm.uncomment(from,to,options);}else{cm.lineComment(from,to,options);}}});function probablyInsideString(cm,pos,line){return/\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line,0)))&&!/^[\'\"\`]/.test(line)}
function getMode(cm,pos){var mode=cm.getMode()
return mode.useInnerComments===false||!mode.innerMode?mode:cm.getModeAt(pos)}
CodeMirror.defineExtension("lineComment",function(from,to,options){if(!options)options=noOptions;var self=this,mode=getMode(self,from);var firstLine=self.getLine(from.line);if(firstLine==null||probablyInsideString(self,from,firstLine))return;var commentString=options.lineComment||mode.lineComment;if(!commentString){if(options.blockCommentStart||mode.blockCommentStart){options.fullLines=true;self.blockComment(from,to,options);}
return;}
var end=Math.min(to.ch!=0||to.line==from.line?to.line+1:to.line,self.lastLine()+1);var pad=options.padding==null?" ":options.padding;var blankLines=options.commentBlankLines||from.line==to.line;self.operation(function(){if(options.indent){var baseString=null;for(var i=from.line;i<end;++i){var line=self.getLine(i);var whitespace=line.slice(0,firstNonWS(line));if(baseString==null||baseString.length>whitespace.length){baseString=whitespace;}}
for(var i=from.line;i<end;++i){var line=self.getLine(i),cut=baseString.length;if(!blankLines&&!nonWS.test(line))continue;if(line.slice(0,cut)!=baseString)cut=firstNonWS(line);self.replaceRange(baseString+commentString+pad,Pos(i,0),Pos(i,cut));}}else{for(var i=from.line;i<end;++i){if(blankLines||nonWS.test(self.getLine(i)))
self.replaceRange(commentString+pad,Pos(i,0));}}});});CodeMirror.defineExtension("blockComment",function(from,to,options){if(!options)options=noOptions;var self=this,mode=getMode(self,from);var startString=options.blockCommentStart||mode.blockCommentStart;var endString=options.blockCommentEnd||mode.blockCommentEnd;if(!startString||!endString){if((options.lineComment||mode.lineComment)&&options.fullLines!=false)
self.lineComment(from,to,options);return;}
if(/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line,0))))return
var end=Math.min(to.line,self.lastLine());if(end!=from.line&&to.ch==0&&nonWS.test(self.getLine(end)))--end;var pad=options.padding==null?" ":options.padding;if(from.line>end)return;self.operation(function(){if(options.fullLines!=false){var lastLineHasText=nonWS.test(self.getLine(end));self.replaceRange(pad+endString,Pos(end));self.replaceRange(startString+pad,Pos(from.line,0));var lead=options.blockCommentLead||mode.blockCommentLead;if(lead!=null)for(var i=from.line+1;i<=end;++i)
if(i!=end||lastLineHasText)
self.replaceRange(lead+pad,Pos(i,0));}else{self.replaceRange(endString,to);self.replaceRange(startString,from);}});});CodeMirror.defineExtension("uncomment",function(from,to,options){if(!options)options=noOptions;var self=this,mode=getMode(self,from);var end=Math.min(to.ch!=0||to.line==from.line?to.line:to.line-1,self.lastLine()),start=Math.min(from.line,end);var lineString=options.lineComment||mode.lineComment,lines=[];var pad=options.padding==null?" ":options.padding,didSomething;lineComment:{if(!lineString)break lineComment;for(var i=start;i<=end;++i){var line=self.getLine(i);var found=line.indexOf(lineString);if(found>-1&&!/comment/.test(self.getTokenTypeAt(Pos(i,found+1))))found=-1;if(found==-1&&nonWS.test(line))break lineComment;if(found>-1&&nonWS.test(line.slice(0,found)))break lineComment;lines.push(line);}
self.operation(function(){for(var i=start;i<=end;++i){var line=lines[i-start];var pos=line.indexOf(lineString),endPos=pos+lineString.length;if(pos<0)continue;if(line.slice(endPos,endPos+pad.length)==pad)endPos+=pad.length;didSomething=true;self.replaceRange("",Pos(i,pos),Pos(i,endPos));}});if(didSomething)return true;}
var startString=options.blockCommentStart||mode.blockCommentStart;var endString=options.blockCommentEnd||mode.blockCommentEnd;if(!startString||!endString)return false;var lead=options.blockCommentLead||mode.blockCommentLead;var startLine=self.getLine(start),open=startLine.indexOf(startString)
if(open==-1)return false
var endLine=end==start?startLine:self.getLine(end)
var close=endLine.indexOf(endString,end==start?open+startString.length:0);var insideStart=Pos(start,open+1),insideEnd=Pos(end,close+1)
if(close==-1||!/comment/.test(self.getTokenTypeAt(insideStart))||!/comment/.test(self.getTokenTypeAt(insideEnd))||self.getRange(insideStart,insideEnd,"\n").indexOf(endString)>-1)
return false;var lastStart=startLine.lastIndexOf(startString,from.ch);var firstEnd=lastStart==-1?-1:startLine.slice(0,from.ch).indexOf(endString,lastStart+startString.length);if(lastStart!=-1&&firstEnd!=-1&&firstEnd+endString.length!=from.ch)return false;firstEnd=endLine.indexOf(endString,to.ch);var almostLastStart=endLine.slice(to.ch).lastIndexOf(startString,firstEnd-to.ch);lastStart=(firstEnd==-1||almostLastStart==-1)?-1:to.ch+almostLastStart;if(firstEnd!=-1&&lastStart!=-1&&lastStart!=to.ch)return false;self.operation(function(){self.replaceRange("",Pos(end,close-(pad&&endLine.slice(close-pad.length,close)==pad?pad.length:0)),Pos(end,close+endString.length));var openEnd=open+startString.length;if(pad&&startLine.slice(openEnd,openEnd+pad.length)==pad)openEnd+=pad.length;self.replaceRange("",Pos(start,open),Pos(start,openEnd));if(lead)for(var i=start+1;i<=end;++i){var line=self.getLine(i),found=line.indexOf(lead);if(found==-1||nonWS.test(line.slice(0,found)))continue;var foundEnd=found+lead.length;if(pad&&line.slice(foundEnd,foundEnd+pad.length)==pad)foundEnd+=pad.length;self.replaceRange("",Pos(i,found),Pos(i,foundEnd));}});return true;});});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.overlayMode=function(base,overlay,combine){return{startState:function(){return{base:CodeMirror.startState(base),overlay:CodeMirror.startState(overlay),basePos:0,baseCur:null,overlayPos:0,overlayCur:null,streamSeen:null};},copyState:function(state){return{base:CodeMirror.copyState(base,state.base),overlay:CodeMirror.copyState(overlay,state.overlay),basePos:state.basePos,baseCur:null,overlayPos:state.overlayPos,overlayCur:null};},token:function(stream,state){if(stream!=state.streamSeen||Math.min(state.basePos,state.overlayPos)<stream.start){state.streamSeen=stream;state.basePos=state.overlayPos=stream.start;}
if(stream.start==state.basePos){state.baseCur=base.token(stream,state.base);state.basePos=stream.pos;}
if(stream.start==state.overlayPos){stream.pos=stream.start;state.overlayCur=overlay.token(stream,state.overlay);state.overlayPos=stream.pos;}
stream.pos=Math.min(state.basePos,state.overlayPos);if(state.overlayCur==null)return state.baseCur;else if(state.baseCur!=null&&state.overlay.combineTokens||combine&&state.overlay.combineTokens==null)
return state.baseCur+" "+state.overlayCur;else return state.overlayCur;},indent:base.indent&&function(state,textAfter){return base.indent(state.base,textAfter);},electricChars:base.electricChars,innerMode:function(state){return{state:state.base,mode:base};},blankLine:function(state){var baseToken,overlayToken;if(base.blankLine)baseToken=base.blankLine(state.base);if(overlay.blankLine)overlayToken=overlay.blankLine(state.overlay);return overlayToken==null?baseToken:(combine&&baseToken!=null?baseToken+" "+overlayToken:overlayToken);}};};});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";var WRAP_CLASS="CodeMirror-activeline";var BACK_CLASS="CodeMirror-activeline-background";var GUTT_CLASS="CodeMirror-activeline-gutter";CodeMirror.defineOption("styleActiveLine",false,function(cm,val,old){var prev=old==CodeMirror.Init?false:old;if(val==prev)return
if(prev){cm.off("beforeSelectionChange",selectionChange);clearActiveLines(cm);delete cm.state.activeLines;}
if(val){cm.state.activeLines=[];updateActiveLines(cm,cm.listSelections());cm.on("beforeSelectionChange",selectionChange);}});function clearActiveLines(cm){for(var i=0;i<cm.state.activeLines.length;i++){cm.removeLineClass(cm.state.activeLines[i],"wrap",WRAP_CLASS);cm.removeLineClass(cm.state.activeLines[i],"background",BACK_CLASS);cm.removeLineClass(cm.state.activeLines[i],"gutter",GUTT_CLASS);}}
function sameArray(a,b){if(a.length!=b.length)return false;for(var i=0;i<a.length;i++)
if(a[i]!=b[i])return false;return true;}
function updateActiveLines(cm,ranges){var active=[];for(var i=0;i<ranges.length;i++){var range=ranges[i];var option=cm.getOption("styleActiveLine");if(typeof option=="object"&&option.nonEmpty?range.anchor.line!=range.head.line:!range.empty())
continue
var line=cm.getLineHandleVisualStart(range.head.line);if(active[active.length-1]!=line)active.push(line);}
if(sameArray(cm.state.activeLines,active))return;cm.operation(function(){clearActiveLines(cm);for(var i=0;i<active.length;i++){cm.addLineClass(active[i],"wrap",WRAP_CLASS);cm.addLineClass(active[i],"background",BACK_CLASS);cm.addLineClass(active[i],"gutter",GUTT_CLASS);}
cm.state.activeLines=active;});}
function selectionChange(cm,sel){updateActiveLines(cm,sel.ranges);}});;(function(mod){if(typeof exports=='object'&&typeof module=='object')
mod(require('../../lib/codemirror'));else if(typeof define=='function'&&define.amd)
define(['../../lib/codemirror'],mod);else
mod(CodeMirror);})(function(CodeMirror){'use strict';function doFold(cm,pos,options,force){if(options&&options.call){var finder=options;options=null;}else{var finder=getOption(cm,options,'rangeFinder');}
if(typeof pos=='number')
pos=CodeMirror.Pos(pos,0);var minSize=getOption(cm,options,'minFoldSize');function getRange(allowFolded){var range=finder(cm,pos);if(!range||range.to.line-range.from.line<minSize)
return null;var marks=cm.findMarksAt(range.from);for(var i=0;i<marks.length;++i){if(marks[i].__isFold&&force!=='fold'){if(!allowFolded)
return null;range.cleared=true;marks[i].clear();}}
return range;}
var range=getRange(true);if(getOption(cm,options,'scanUp'))
while(!range&&pos.line>cm.firstLine()){pos=CodeMirror.Pos(pos.line-1,0);range=getRange(false);}
if(!range||range.cleared||force==='unfold')
return;var myWidget=makeWidget(cm,options);CodeMirror.on(myWidget,'mousedown',function(e){myRange.clear();CodeMirror.e_preventDefault(e);});var myRange=cm.markText(range.from,range.to,{replacedWith:myWidget,clearOnEnter:getOption(cm,options,'clearOnEnter'),__isFold:true});myRange.on('clear',function(from,to){CodeMirror.signal(cm,'unfold',cm,from,to);});CodeMirror.signal(cm,'fold',cm,range.from,range.to);}
function makeWidget(cm,options){var widget=getOption(cm,options,'widget');if(typeof widget=='string'){var text=document.createTextNode(widget);widget=document.createElement('span');widget.appendChild(text);widget.className='CodeMirror-foldmarker';}else if(widget){widget=widget.cloneNode(true)}
return widget;}
CodeMirror.newFoldFunction=function(rangeFinder,widget){return function(cm,pos){doFold(cm,pos,{rangeFinder:rangeFinder,widget:widget});};};CodeMirror.defineExtension('foldCode',function(pos,options,force){doFold(this,pos,options,force);});CodeMirror.defineExtension('isFolded',function(pos){var marks=this.findMarksAt(pos);for(var i=0;i<marks.length;++i)
if(marks[i].__isFold)
return true;});CodeMirror.commands.toggleFold=function(cm){cm.foldCode(cm.getCursor());};CodeMirror.commands.fold=function(cm){cm.foldCode(cm.getCursor(),null,'fold');};CodeMirror.commands.unfold=function(cm){cm.foldCode(cm.getCursor(),null,'unfold');};CodeMirror.commands.foldAll=function(cm){cm.operation(function(){for(var i=cm.firstLine(),e=cm.lastLine();i<=e;i++)
cm.foldCode(CodeMirror.Pos(i,0),null,'fold');});};CodeMirror.commands.unfoldAll=function(cm){cm.operation(function(){for(var i=cm.firstLine(),e=cm.lastLine();i<=e;i++)
cm.foldCode(CodeMirror.Pos(i,0),null,'unfold');});};CodeMirror.registerHelper('fold','combine',function(){var funcs=Array.prototype.slice.call(arguments,0);return function(cm,start){for(var i=0;i<funcs.length;++i){var found=funcs[i](cm,start);if(found)
return found;}};});CodeMirror.registerHelper('fold','auto',function(cm,start){var helpers=cm.getHelpers(start,'fold');for(var i=0;i<helpers.length;i++){var cur=helpers[i](cm,start);if(cur)
return cur;}});var defaultOptions={rangeFinder:CodeMirror.fold.auto,widget:'\u2194',minFoldSize:0,scanUp:false,clearOnEnter:true};CodeMirror.defineOption('foldOptions',null);function getOption(cm,options,name){if(options&&options[name]!==undefined)
return options[name];var editorOptions=cm.options.foldOptions;if(editorOptions&&editorOptions[name]!==undefined)
return editorOptions[name];return defaultOptions[name];}
CodeMirror.defineExtension('foldOption',function(options,name){return getOption(this,options,name);});});;(function(mod){if(typeof exports=='object'&&typeof module=='object')
mod(require('../../lib/codemirror'),require('./foldcode'));else if(typeof define=='function'&&define.amd)
define(['../../lib/codemirror','./foldcode'],mod);else
mod(CodeMirror);})(function(CodeMirror){'use strict';CodeMirror.defineOption('foldGutter',false,function(cm,val,old){if(old&&old!=CodeMirror.Init){cm.clearGutter(cm.state.foldGutter.options.gutter);cm.state.foldGutter=null;cm.off('gutterClick',onGutterClick);cm.off('change',onChange);cm.off('viewportChange',onViewportChange);cm.off('fold',onFold);cm.off('unfold',onFold);cm.off('swapDoc',onChange);}
if(val){cm.state.foldGutter=new State(parseOptions(val));updateInViewport(cm);cm.on('gutterClick',onGutterClick);cm.on('change',onChange);cm.on('viewportChange',onViewportChange);cm.on('fold',onFold);cm.on('unfold',onFold);cm.on('swapDoc',onChange);}});var Pos=CodeMirror.Pos;function State(options){this.options=options;this.from=this.to=0;}
function parseOptions(opts){if(opts===true)
opts={};if(opts.gutter==null)
opts.gutter='CodeMirror-foldgutter';if(opts.indicatorOpen==null)
opts.indicatorOpen='CodeMirror-foldgutter-open';if(opts.indicatorFolded==null)
opts.indicatorFolded='CodeMirror-foldgutter-folded';return opts;}
function isFolded(cm,line){var marks=cm.findMarks(Pos(line,0),Pos(line+1,0));for(var i=0;i<marks.length;++i)
if(marks[i].__isFold&&marks[i].find().from.line==line)
return marks[i];}
function marker(spec){if(typeof spec=='string'){var elt=document.createElement('div');elt.className=spec+' CodeMirror-guttermarker-subtle';return elt;}else{return spec.cloneNode(true);}}
function updateFoldInfo(cm,from,to){var opts=cm.state.foldGutter.options,cur=from;var minSize=cm.foldOption(opts,'minFoldSize');var func=cm.foldOption(opts,'rangeFinder');cm.eachLine(from,to,function(line){var mark=null;if(isFolded(cm,cur)){mark=marker(opts.indicatorFolded);}else{var pos=Pos(cur,0);var range=func&&func(cm,pos);if(range&&range.to.line-range.from.line>=minSize)
mark=marker(opts.indicatorOpen);}
cm.setGutterMarker(line,opts.gutter,mark);++cur;});}
function updateInViewport(cm){var vp=cm.getViewport(),state=cm.state.foldGutter;if(!state)
return;cm.operation(function(){updateFoldInfo(cm,vp.from,vp.to);});state.from=vp.from;state.to=vp.to;}
function onGutterClick(cm,line,gutter){var state=cm.state.foldGutter;if(!state)
return;var opts=state.options;if(gutter!=opts.gutter)
return;var folded=isFolded(cm,line);if(folded)
folded.clear();else
cm.foldCode(Pos(line,0),opts.rangeFinder);}
function onChange(cm){var state=cm.state.foldGutter;if(!state)
return;var opts=state.options;state.from=state.to=0;clearTimeout(state.changeUpdate);state.changeUpdate=setTimeout(function(){updateInViewport(cm);},opts.foldOnChangeTimeSpan||600);}
function onViewportChange(cm){var state=cm.state.foldGutter;if(!state)
return;var opts=state.options;clearTimeout(state.changeUpdate);state.changeUpdate=setTimeout(function(){var vp=cm.getViewport();if(state.from==state.to||vp.from-state.to>20||state.from-vp.to>20){updateInViewport(cm);}else{cm.operation(function(){if(vp.from<state.from){updateFoldInfo(cm,vp.from,state.from);state.from=vp.from;}
if(vp.to>state.to){updateFoldInfo(cm,state.to,vp.to);state.to=vp.to;}});}},opts.updateViewportTimeSpan||400);}
function onFold(cm,from){var state=cm.state.foldGutter;if(!state)
return;var line=from.line;if(line>=state.from&&line<state.to)
updateFoldInfo(cm,line,line+1);}});;(function(mod){if(typeof exports=='object'&&typeof module=='object')
mod(require('../../lib/codemirror'));else if(typeof define=='function'&&define.amd)
define(['../../lib/codemirror'],mod);else
mod(CodeMirror);})(function(CodeMirror){'use strict';CodeMirror.registerHelper('fold','brace',function(cm,start){var line=start.line,lineText=cm.getLine(line);var tokenType;function findOpening(openCh){for(var at=start.ch,pass=0;;){var found=at<=0?-1:lineText.lastIndexOf(openCh,at-1);if(found==-1){if(pass==1)
break;pass=1;at=lineText.length;continue;}
if(pass==1&&found<start.ch)
break;tokenType=cm.getTokenTypeAt(CodeMirror.Pos(line,found+1));if(!/^(comment|string)/.test(tokenType))
return found+1;at=found-1;}}
var startToken='{',endToken='}',startCh=findOpening('{');if(startCh==null){startToken='[',endToken=']';startCh=findOpening('[');}
if(startCh==null)
return;var count=1,lastLine=cm.lastLine(),end,endCh;outer:for(var i=line;i<=lastLine;++i){var text=cm.getLine(i),pos=i==line?startCh:0;for(;;){var nextOpen=text.indexOf(startToken,pos),nextClose=text.indexOf(endToken,pos);if(nextOpen<0)
nextOpen=text.length;if(nextClose<0)
nextClose=text.length;pos=Math.min(nextOpen,nextClose);if(pos==text.length)
break;if(cm.getTokenTypeAt(CodeMirror.Pos(i,pos+1))==tokenType){if(pos==nextOpen)
++count;else if(!--count){end=i;endCh=pos;break outer;}}
++pos;}}
if(end==null||line==end&&endCh==startCh)
return;return{from:CodeMirror.Pos(line,startCh),to:CodeMirror.Pos(end,endCh)};});CodeMirror.registerHelper('fold','import',function(cm,start){function hasImport(line){if(line<cm.firstLine()||line>cm.lastLine())
return null;var start=cm.getTokenAt(CodeMirror.Pos(line,1));if(!/\S/.test(start.string))
start=cm.getTokenAt(CodeMirror.Pos(line,start.end+1));if(start.type!='keyword'||start.string!='import')
return null;for(var i=line,e=Math.min(cm.lastLine(),line+10);i<=e;++i){var text=cm.getLine(i),semi=text.indexOf(';');if(semi!=-1)
return{startCh:start.end,end:CodeMirror.Pos(i,semi)};}}
var startLine=start.line,has=hasImport(startLine),prev;if(!has||hasImport(startLine-1)||((prev=hasImport(startLine-2))&&prev.end.line==startLine-1))
return null;for(var end=has.end;;){var next=hasImport(end.line+1);if(next==null)
break;end=next.end;}
return{from:cm.clipPos(CodeMirror.Pos(startLine,has.startCh+1)),to:end};});CodeMirror.registerHelper('fold','include',function(cm,start){function hasInclude(line){if(line<cm.firstLine()||line>cm.lastLine())
return null;var start=cm.getTokenAt(CodeMirror.Pos(line,1));if(!/\S/.test(start.string))
start=cm.getTokenAt(CodeMirror.Pos(line,start.end+1));if(start.type=='meta'&&start.string.slice(0,8)=='#include')
return start.start+8;}
var startLine=start.line,has=hasInclude(startLine);if(has==null||hasInclude(startLine-1)!=null)
return null;for(var end=startLine;;){var next=hasInclude(end+1);if(next==null)
break;++end;}
return{from:CodeMirror.Pos(startLine,has+1),to:cm.clipPos(CodeMirror.Pos(end))};});});;Runtime.cachedResources["cm/codemirror.css"]="/* STOP */\n\n/* The rest of this file contains styles related to the mechanics of\n the editor. You probably shouldn't touch them. */\n\n.CodeMirror {\n position: relative;\n overflow: hidden;\n background: white;\n}\n\n.CodeMirror-scroll {\n overflow: scroll !important; /* Things will break if this is overridden */\n /* 30px is the magic margin used to hide the element's real scrollbars */\n /* See overflow: hidden in .CodeMirror */\n margin-bottom: -30px; margin-right: -30px;\n padding-bottom: 30px;\n height: 100%;\n outline: none; /* Prevent dragging from highlighting the element */\n position: relative;\n}\n.CodeMirror-sizer {\n position: relative;\n border-right: 30px solid transparent;\n}\n\n/* The fake, visible scrollbars. Used to force redraw during scrolling\n before actual scrolling happens, thus preventing shaking and\n flickering artifacts. */\n.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n position: absolute;\n z-index: 6;\n display: none;\n}\n.CodeMirror-vscrollbar {\n right: 0; top: 0;\n overflow-x: hidden;\n overflow-y: scroll;\n}\n.CodeMirror-hscrollbar {\n bottom: 0; left: 0;\n overflow-y: hidden;\n overflow-x: scroll;\n}\n.CodeMirror-scrollbar-filler {\n right: 0; bottom: 0;\n}\n.CodeMirror-gutter-filler {\n left: 0; bottom: 0;\n}\n\n.CodeMirror-gutters {\n position: absolute; left: 0; top: 0;\n min-height: 100%;\n z-index: 3;\n}\n.CodeMirror-gutter {\n white-space: normal;\n height: 100%;\n display: inline-block;\n vertical-align: top;\n margin-bottom: -30px;\n}\n.CodeMirror-gutter-wrapper {\n position: absolute;\n z-index: 4;\n background: none !important;\n border: none !important;\n}\n.CodeMirror-gutter-background {\n position: absolute;\n top: 0; bottom: 0;\n z-index: 4;\n}\n.CodeMirror-gutter-elt {\n position: absolute;\n cursor: default;\n z-index: 4;\n}\n.CodeMirror-gutter-wrapper ::selection { background-color: transparent }\n.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }\n\n.CodeMirror-lines {\n cursor: text;\n min-height: 1px; /* prevents collapsing before first draw */\n}\n.CodeMirror pre {\n /* Reset some styles that the rest of the page might have set */\n -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;\n border-width: 0;\n background: transparent;\n font-family: inherit;\n font-size: inherit;\n margin: 0;\n white-space: pre;\n word-wrap: normal;\n line-height: inherit;\n color: inherit;\n z-index: 2;\n position: relative;\n overflow: visible;\n -webkit-tap-highlight-color: transparent;\n -webkit-font-variant-ligatures: contextual;\n font-variant-ligatures: contextual;\n}\n.CodeMirror-wrap pre {\n word-wrap: break-word;\n white-space: pre-wrap;\n word-break: normal;\n}\n\n.CodeMirror-linebackground {\n position: absolute;\n left: 0; right: 0; top: 0; bottom: 0;\n z-index: 0;\n}\n\n.CodeMirror-linewidget {\n position: relative;\n z-index: 2;\n padding: 0.1px; /* Force widget margins to stay inside of the container */\n}\n\n.CodeMirror-widget {}\n\n.CodeMirror-rtl pre { direction: rtl; }\n\n.CodeMirror-code {\n outline: none;\n}\n\n/* Force content-box sizing for the elements where we expect it */\n.CodeMirror-scroll,\n.CodeMirror-sizer,\n.CodeMirror-gutter,\n.CodeMirror-gutters,\n.CodeMirror-linenumber {\n -moz-box-sizing: content-box;\n box-sizing: content-box;\n}\n\n.CodeMirror-measure {\n position: absolute;\n width: 100%;\n height: 0;\n overflow: hidden;\n visibility: hidden;\n}\n\n.CodeMirror-cursor {\n position: absolute;\n pointer-events: none;\n}\n.CodeMirror-measure pre { position: static; }\n\ndiv.CodeMirror-cursors {\n visibility: hidden;\n position: relative;\n z-index: 3;\n}\ndiv.CodeMirror-dragcursors {\n visibility: visible;\n}\n\n.CodeMirror-focused div.CodeMirror-cursors {\n visibility: visible;\n}\n\n.CodeMirror-selected { background: #d9d9d
return;if(!contrastInfo.computedFontSize||!contrastInfo.computedFontWeight||!contrastInfo.backgroundColors||contrastInfo.backgroundColors.length!==1)
return;this._isNull=false;const isLargeFont=ColorPicker.ContrastInfo.computeIsLargeFont(contrastInfo.computedFontSize,contrastInfo.computedFontWeight);this._contrastRatioThresholds=ColorPicker.ContrastInfo._ContrastThresholds[(isLargeFont?'largeFont':'normalFont')];const bgColorText=contrastInfo.backgroundColors[0];const bgColor=Common.Color.parse(bgColorText);if(bgColor)
this._setBgColorInternal(bgColor);}
isNull(){return this._isNull;}
setColor(fgColor){this._fgColor=fgColor;this._updateContrastRatio();this.dispatchEventToListeners(ColorPicker.ContrastInfo.Events.ContrastInfoUpdated);}
color(){return this._fgColor;}
contrastRatio(){return this._contrastRatio;}
setBgColor(bgColor){this._setBgColorInternal(bgColor);this.dispatchEventToListeners(ColorPicker.ContrastInfo.Events.ContrastInfoUpdated);}
_setBgColorInternal(bgColor){this._bgColor=bgColor;if(!this._fgColor)
return;const fgRGBA=this._fgColor.rgba();if(bgColor.hasAlpha()){const blendedRGBA=[];Common.Color.blendColors(bgColor.rgba(),fgRGBA,blendedRGBA);this._bgColor=new Common.Color(blendedRGBA,Common.Color.Format.RGBA);}
this._contrastRatio=Common.Color.calculateContrastRatio(fgRGBA,this._bgColor.rgba());}
bgColor(){return this._bgColor;}
_updateContrastRatio(){if(!this._bgColor||!this._fgColor)
return;this._contrastRatio=Common.Color.calculateContrastRatio(this._fgColor.rgba(),this._bgColor.rgba());}
contrastRatioThreshold(level){if(!this._contrastRatioThresholds)
return null;return this._contrastRatioThresholds[level];}
static computeIsLargeFont(fontSize,fontWeight){const boldWeights=['bold','bolder','600','700','800','900'];const fontSizePx=parseFloat(fontSize.replace('px',''));const isBold=(boldWeights.indexOf(fontWeight)!==-1);const fontSizePt=fontSizePx*72/96;if(isBold)
return fontSizePt>=14;else
return fontSizePt>=18;}};ColorPicker.ContrastInfo.Events={ContrastInfoUpdated:Symbol('ContrastInfoUpdated')};ColorPicker.ContrastInfo._ContrastThresholds={largeFont:{aa:3.0,aaa:4.5},normalFont:{aa:4.5,aaa:7.0}};;ColorPicker.ContrastOverlay=class{constructor(contrastInfo,colorElement){this._contrastInfo=contrastInfo;this._visible=false;this._contrastRatioSVG=colorElement.createSVGChild('svg','spectrum-contrast-container fill');this._contrastRatioLines={aa:this._contrastRatioSVG.createSVGChild('path','spectrum-contrast-line'),aaa:this._contrastRatioSVG.createSVGChild('path','spectrum-contrast-line')};this._width=0;this._height=0;this._contrastRatioLineBuilder=new ColorPicker.ContrastRatioLineBuilder(this._contrastInfo);this._contrastRatioLinesThrottler=new Common.Throttler(0);this._drawContrastRatioLinesBound=this._drawContrastRatioLines.bind(this);this._contrastInfo.addEventListener(ColorPicker.ContrastInfo.Events.ContrastInfoUpdated,this._update.bind(this));}
_update(){if(!this._visible||this._contrastInfo.isNull()||!this._contrastInfo.contrastRatio())
return;this._contrastRatioLinesThrottler.schedule(this._drawContrastRatioLinesBound);}
setDimensions(width,height){this._width=width;this._height=height;this._update();}
setVisible(visible){this._visible=visible;this._contrastRatioSVG.classList.toggle('hidden',!visible);this._update();}
async _drawContrastRatioLines(){for(const level in this._contrastRatioLines){const path=this._contrastRatioLineBuilder.drawContrastRatioLine(this._width,this._height,level);if(path)
this._contrastRatioLines[level].setAttribute('d',path);else
this._contrastRatioLines[level].removeAttribute('d');}}};ColorPicker.ContrastRatioLineBuilder=class{constructor(contrastInfo){this._contrastInfo=contrastInfo;}
drawContrastRatioLine(width,height,level){const requiredContrast=this._contrastInfo.contrastRatioThreshold(level);if(!width||!height||!requiredContrast)
return null;const dS=0.02;const epsilon=0.0002;const H=0;const S=1;const V=2;const A=3;const color=this._contrastInfo.color();const bgColor=this._contrastInfo.bgColor();if(!color||!bgColor)
return null;const fgRGBA=color.rgba();const fgHSVA=color.hsva();const bgRGBA=bgColor.rgba();const bgLuminance=Common.Color.luminance(bgRGBA);const blendedRGBA=[];Common.Color.blendColors(fgRGBA,bgRGBA,blendedRGBA);const fgLuminance=Common.Color.luminance(blendedRGBA);const fgIsLighter=fgLuminance>bgLuminance;const desiredLuminance=Common.Color.desiredLuminance(bgLuminance,requiredContrast,fgIsLighter);let lastV=fgHSVA[V];let currentSlope=0;const candidateHSVA=[fgHSVA[H],0,0,fgHSVA[A]];let pathBuilder=[];const candidateRGBA=[];Common.Color.hsva2rgba(candidateHSVA,candidateRGBA);Common.Color.blendColors(candidateRGBA,bgRGBA,blendedRGBA);function updateCandidateAndComputeDelta(index,x){candidateHSVA[index]=x;Common.Color.hsva2rgba(candidateHSVA,candidateRGBA);Common.Color.blendColors(candidateRGBA,bgRGBA,blendedRGBA);return Common.Color.luminance(blendedRGBA)-desiredLuminance;}
function approach(index){let x=candidateHSVA[index];let multiplier=1;let dLuminance=updateCandidateAndComputeDelta(index,x);let previousSign=Math.sign(dLuminance);for(let guard=100;guard;guard--){if(Math.abs(dLuminance)<epsilon)
return x;const sign=Math.sign(dLuminance);if(sign!==previousSign){multiplier/=2;previousSign=sign;}else if(x<0||x>1){return null;}
x+=multiplier*(index===V?-dLuminance:dLuminance);dLuminance=updateCandidateAndComputeDelta(index,x);}
console.error('Loop exited unexpectedly');return null;}
let s;for(s=0;s<1+dS;s+=dS){s=Math.min(1,s);candidateHSVA[S]=s;candidateHSVA[V]=lastV+currentSlope*dS;const v=approach(V);if(v===null)
break;currentSlope=s===0?0:(v-lastV)/dS;lastV=v;pathBuilder.push(pathBuilder.length?'L':'M');pathBuilder.push((s*width).toFixed(2));pathBuilder.push(((1-v)*height).toFixed(2));}
if(s<1+dS){s-=dS;candidateHSVA[V]=1;s=approach(S);if(s!==null)
pathBuilder=pathBuilder.concat(['L',(s*width).toFixed(2),'-0.1']);}
if(pathBuilder.length===0)
return null;return pathBuilder.join(' ');}};;ColorPicker.ContrastDetails=class{constructor(contrastInfo,contentElement,toggleMainColorPickerCallback,expandedChangedCallback){this._contrastInfo=contrastInfo;this._element=contentElement.createChild('div','spectrum-contrast-details collapsed');this._toggleMainColorPicker=toggleMainColorPickerCallback;this._expandedChangedCallback=expandedChangedCallback;this._expanded=false;this._passesAA=true;this._contrastUnknown=false;this._visible=false;const contrastValueRow=this._element.createChild('div');contrastValueRow.addEventListener('click',this._topRowClicked.bind(this));const contrastValueRowContents=contrastValueRow.createChild('div','container');contrastValueRowContents.createTextChild(Common.UIString('Contrast ratio'));this._contrastValueBubble=contrastValueRowContents.createChild('span','contrast-details-value');this._contrastValue=this._contrastValueBubble.createChild('span');this._contrastValueBubbleIcons=[];this._contrastValueBubbleIcons.push(this._contrastValueBubble.appendChild(UI.Icon.create('smallicon-checkmark-square')));this._contrastValueBubbleIcons.push(this._contrastValueBubble.appendChild(UI.Icon.create('smallicon-checkmark-behind')));this._contrastValueBubbleIcons.push(this._contrastValueBubble.appendChild(UI.Icon.create('smallicon-no')));this._contrastValueBubbleIcons.forEach(button=>button.addEventListener('click',event=>{ColorPicker.ContrastDetails._showHelp();event.consume(false);}));const expandToolbar=new UI.Toolbar('expand',contrastValueRowContents);this._expandButton=new UI.ToolbarButton(Common.UIString('Show more'),'smallicon-expand-more');this._expandButton.addEventListener(UI.ToolbarButton.Events.Click,this._expandButtonClicked.bind(this));UI.ARIAUtils.setExpanded(this._expandButton.element,false);expandToolbar.appendToolbarItem(this._expandButton);this._expandedDetails=this._element.createChild('div','expanded-details');this._expandedDetails.id='expanded-contrast-details';UI.ARIAUtils.setControls(this._expandButton.element,this._expandedDetails);this._contrastThresholds=this._expandedDetails.createChild('div','contrast-thresholds');this._contrastAA=this._contrastThresholds.createChild('div','contrast-threshold');this._contrastPassFailAA=this._contrastAA.createChild('span','contrast-pass-fail');this._contrastAAA=this._contrastThresholds.createChild('div','contrast-threshold');this._contrastPassFailAAA=this._contrastAAA.createChild('span','contrast-pass-fail');this._chooseBgColor=this._expandedDetails.createChild('div','contrast-choose-bg-color');this._chooseBgColor.textContent=Common.UIString('Pick background color');const bgColorContainer=this._expandedDetails.createChild('div','background-color');const pickerToolbar=new UI.Toolbar('spectrum-eye-dropper',bgColorContainer);this._bgColorPickerButton=new UI.ToolbarToggle(Common.UIString('Toggle background color picker'),'largeicon-eyedropper');this._bgColorPickerButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleBackgroundColorPicker.bind(this,undefined));pickerToolbar.appendToolbarItem(this._bgColorPickerButton);this._bgColorPickedBound=this._bgColorPicked.bind(this);this._bgColorSwatch=new ColorPicker.ContrastDetails.Swatch(bgColorContainer);this._contrastInfo.addEventListener(ColorPicker.ContrastInfo.Events.ContrastInfoUpdated,this._update.bind(this));}
_update(){if(this._contrastInfo.isNull()){this.setVisible(false);return;}
this.setVisible(true);const contrastRatio=this._contrastInfo.contrastRatio();const fgColor=this._contrastInfo.color();const bgColor=this._contrastInfo.bgColor();if(!contrastRatio||!bgColor||!fgColor){this._contrastUnknown=true;this._contrastValue.textContent='';this._contrastValueBubble.classList.add('contrast-unknown');this._chooseBgColor.classList.remove('hidden');this._contrastThresholds.classList.add('hidden');return;}
this._contrastUnknown=false;this._chooseBgColor.classList.add('hidden');this._contrastThresholds.classList.remove('hidden');this._contrastValueBubble.classList.remove('contrast-unknown');this._contrastValue.textContent=contrastRatio.toFixed(2);this._bgColorSwatch.setColors(fgColor,bgColor);const aa=this._contrastInfo.contrastRatioThreshold('aa');this._passesAA=this._contrastInfo.contrastRatio()>=aa;this._contrastPassFailAA.removeChildren();const labelAA=this._contrastPassFailAA.createChild('span','contrast-link-label');labelAA.textContent=Common.UIString('AA');this._contrastPassFailAA.createChild('span').textContent=Common.UIString(': %s',aa.toFixed(1));if(this._passesAA)
this._contrastPassFailAA.appendChild(UI.Icon.create('smallicon-checkmark-square'));else
this._contrastPassFailAA.appendChild(UI.Icon.create('smallicon-no'));const aaa=this._contrastInfo.contrastRatioThreshold('aaa');const passesAAA=this._contrastInfo.contrastRatio()>=aaa;this._contrastPassFailAAA.removeChildren();const labelAAA=this._contrastPassFailAAA.createChild('span','contrast-link-label');labelAAA.textContent=Common.UIString('AAA');this._contrastPassFailAAA.createChild('span').textContent=Common.UIString(': %s',aaa.toFixed(1));if(passesAAA)
this._contrastPassFailAAA.appendChild(UI.Icon.create('smallicon-checkmark-square'));else
this._contrastPassFailAAA.appendChild(UI.Icon.create('smallicon-no'));[labelAA,labelAAA].forEach(e=>e.addEventListener('click',event=>ColorPicker.ContrastDetails._showHelp()));this._element.classList.toggle('contrast-fail',!this._passesAA);this._contrastValueBubble.classList.toggle('contrast-aa',this._passesAA);this._contrastValueBubble.classList.toggle('contrast-aaa',passesAAA);}
static _showHelp(){InspectorFrontendHost.openInNewTab('https://developers.google.com/web/fundamentals/accessibility/accessible-styles#color_and_contrast');}
setVisible(visible){this._visible=visible;this._element.classList.toggle('hidden',!visible);}
visible(){return this._visible;}
element(){return this._element;}
_expandButtonClicked(event){this._contrastValueBubble.getComponentSelection().empty();this._toggleExpanded();}
_topRowClicked(event){this._contrastValueBubble.getComponentSelection().empty();this._toggleExpanded();event.consume(true);}
_toggleExpanded(){this._expanded=!this._expanded;UI.ARIAUtils.setExpanded(this._expandButton.element,this._expanded);this._element.classList.toggle('collapsed',!this._expanded);if(this._expanded){this._toggleMainColorPicker(false);this._expandButton.setGlyph('smallicon-expand-less');this._expandButton.setTitle(Common.UIString('Show less'));if(this._contrastUnknown)
this._toggleBackgroundColorPicker(true);}else{this._toggleBackgroundColorPicker(false);this._expandButton.setGlyph('smallicon-expand-more');this._expandButton.setTitle(Common.UIString('Show more'));}
this._expandedChangedCallback();}
collapse(){this._element.classList.remove('expanded');this._toggleBackgroundColorPicker(false);this._toggleMainColorPicker(false);}
expanded(){return this._expanded;}
_toggleBackgroundColorPicker(enabled){if(enabled===undefined)
enabled=!this._bgColorPickerButton.toggled();this._bgColorPickerButton.setToggled(enabled);InspectorFrontendHost.setEyeDropperActive(enabled);if(enabled){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._bgColorPickedBound);}else{InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._bgColorPickedBound);}}
_bgColorPicked(event){const rgbColor=(event.data);const rgba=[rgbColor.r,rgbColor.g,rgbColor.b,(rgbColor.a/2.55|0)/100];const color=Common.Color.fromRGBA(rgba);this._contrastInfo.setBgColor(color);this._toggleBackgroundColorPicker(false);InspectorFrontendHost.bringToFront();}};ColorPicker.ContrastDetails.Swatch=class{constructor(parentElement){this._parentElement=parentElement;this._swatchElement=parentElement.createChild('span','swatch contrast swatch-inner-white');this._swatchInnerElement=this._swatchElement.createChild('span','swatch-inner');this._textPreview=this._swatchElement.createChild('div','text-preview');this._textPreview.textContent='Aa';}
setColors(fgColor,bgColor){this._textPreview.style.color=(fgColor.asString(Common.Color.Format.RGBA));this._swatchInnerElement.style.backgroundColor=(bgColor.asString(Common.Color.Format.RGBA));this._swatchElement.classList.toggle('swatch-inner-white',bgColor.hsla()[2]>0.9);}};;ColorPicker.Spectrum=class extends UI.VBox{constructor(contrastInfo){function appendSwitcherIcon(parentElement){const icon=parentElement.createSVGChild('svg');icon.setAttribute('height',16);icon.setAttribute('width',16);const path=icon.createSVGChild('path');path.setAttribute('d','M5,6 L11,6 L8,2 Z M5,10 L11,10 L8,14 Z');return icon;}
super(true);this.registerRequiredCSS('color_picker/spectrum.css');this.contentElement.tabIndex=0;this.setDefaultFocusedElement(this.contentElement);this._colorElement=this.contentElement.createChild('div','spectrum-color');this._colorDragElement=this._colorElement.createChild('div','spectrum-sat fill').createChild('div','spectrum-val fill').createChild('div','spectrum-dragger');this._dragX=0;this._dragY=0;const toolsContainer=this.contentElement.createChild('div','spectrum-tools');const toolbar=new UI.Toolbar('spectrum-eye-dropper',toolsContainer);this._colorPickerButton=new UI.ToolbarToggle(Common.UIString('Toggle color picker'),'largeicon-eyedropper');this._colorPickerButton.setToggled(true);this._colorPickerButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleColorPicker.bind(this,undefined));toolbar.appendToolbarItem(this._colorPickerButton);this._swatch=new ColorPicker.Spectrum.Swatch(toolsContainer);this._hueElement=toolsContainer.createChild('div','spectrum-hue');this._hueSlider=this._hueElement.createChild('div','spectrum-slider');this._alphaElement=toolsContainer.createChild('div','spectrum-alpha');this._alphaElementBackground=this._alphaElement.createChild('div','spectrum-alpha-background');this._alphaSlider=this._alphaElement.createChild('div','spectrum-slider');const displaySwitcher=toolsContainer.createChild('div','spectrum-display-switcher spectrum-switcher');appendSwitcherIcon(displaySwitcher);displaySwitcher.addEventListener('click',this._formatViewSwitch.bind(this));this._displayContainer=toolsContainer.createChild('div','spectrum-text source-code');this._textValues=[];for(let i=0;i<4;++i){const inputValue=UI.createInput('spectrum-text-value');this._displayContainer.appendChild(inputValue);inputValue.maxLength=4;this._textValues.push(inputValue);inputValue.addEventListener('keydown',this._inputChanged.bind(this),false);inputValue.addEventListener('input',this._inputChanged.bind(this),false);inputValue.addEventListener('mousewheel',this._inputChanged.bind(this),false);}
this._textLabels=this._displayContainer.createChild('div','spectrum-text-label');this._hexContainer=toolsContainer.createChild('div','spectrum-text spectrum-text-hex source-code');this._hexValue=UI.createInput('spectrum-text-value');this._hexContainer.appendChild(this._hexValue);this._hexValue.maxLength=9;this._hexValue.addEventListener('keydown',this._inputChanged.bind(this),false);this._hexValue.addEventListener('input',this._inputChanged.bind(this),false);this._hexValue.addEventListener('mousewheel',this._inputChanged.bind(this),false);const label=this._hexContainer.createChild('div','spectrum-text-label');label.textContent='HEX';UI.installDragHandle(this._hueElement,dragStart.bind(this,positionHue.bind(this)),positionHue.bind(this),null,'pointer','default');UI.installDragHandle(this._alphaElement,dragStart.bind(this,positionAlpha.bind(this)),positionAlpha.bind(this),null,'pointer','default');UI.installDragHandle(this._colorElement,dragStart.bind(this,positionColor.bind(this)),positionColor.bind(this),null,'pointer','default');if(contrastInfo){this._contrastInfo=contrastInfo;this._contrastOverlay=new ColorPicker.ContrastOverlay(this._contrastInfo,this._colorElement);this._contrastDetails=new ColorPicker.ContrastDetails(this._contrastInfo,this.contentElement,this._toggleColorPicker.bind(this),this._contrastPanelExpanded.bind(this));}
this.element.classList.add('flex-none');this._palettes=new Map();this._palettePanel=this.contentElement.createChild('div','palette-panel');this._palettePanel.tabIndex=-1;this._palettePanelShowing=false;this._paletteSectionContainer=this.contentElement.createChild('div','spectrum-palette-container');this._paletteContainer=this._paletteSectionContainer.createChild('div','spectrum-palette');this._paletteContainer.addEventListener('contextmenu',this._showPaletteColorContextMenu.bind(this,-1));this._shadesContainer=this.contentElement.createChild('div','palette-color-shades hidden');UI.installDragHandle(this._paletteContainer,this._paletteDragStart.bind(this),this._paletteDrag.bind(this),this._paletteDragEnd.bind(this),'default');const paletteSwitcher=this._paletteSectionContainer.createChild('div','spectrum-palette-switcher spectrum-switcher');appendSwitcherIcon(paletteSwitcher);paletteSwitcher.addEventListener('click',this._togglePalettePanel.bind(this,true));this._deleteIconToolbar=new UI.Toolbar('delete-color-toolbar');this._deleteButton=new UI.ToolbarButton('','largeicon-trash-bin');this._deleteIconToolbar.appendToolbarItem(this._deleteButton);const overlay=this.contentElement.createChild('div','spectrum-overlay fill');overlay.addEventListener('click',this._togglePalettePanel.bind(this,false));this._addColorToolbar=new UI.Toolbar('add-color-toolbar');const addColorButton=new UI.ToolbarButton(Common.UIString('Add to palette'),'largeicon-add');addColorButton.addEventListener(UI.ToolbarButton.Events.Click,this._addColorToCustomPalette,this);this._addColorToolbar.appendToolbarItem(addColorButton);this._colorPickedBound=this._colorPicked.bind(this);this._loadPalettes();new ColorPicker.Spectrum.PaletteGenerator(palette=>{if(palette.colors.length)
this.addPalette(palette);else if(this._selectedColorPalette.get()===palette.title)
this._paletteSelected(ColorPicker.Spectrum.MaterialPalette);});function dragStart(callback,event){this._hueAlphaLeft=this._hueElement.totalOffsetLeft();this._colorOffset=this._colorElement.totalOffset();callback(event);return true;}
function positionHue(event){const hsva=this._hsv.slice();hsva[0]=Number.constrain(1-(event.x-this._hueAlphaLeft)/this._hueAlphaWidth,0,1);this._innerSetColor(hsva,'',undefined,undefined,ColorPicker.Spectrum._ChangeSource.Other);}
function positionAlpha(event){const newAlpha=Math.round((event.x-this._hueAlphaLeft)/this._hueAlphaWidth*100)/100;const hsva=this._hsv.slice();hsva[3]=Number.constrain(newAlpha,0,1);this._innerSetColor(hsva,'',undefined,undefined,ColorPicker.Spectrum._ChangeSource.Other);}
function positionColor(event){const hsva=this._hsv.slice();hsva[1]=Number.constrain((event.x-this._colorOffset.left)/this.dragWidth,0,1);hsva[2]=Number.constrain(1-(event.y-this._colorOffset.top)/this.dragHeight,0,1);this._innerSetColor(hsva,'',undefined,undefined,ColorPicker.Spectrum._ChangeSource.Other);}}
_contrastPanelExpanded(){this._contrastOverlay.setVisible(this._contrastDetails.expanded());this._resizeForSelectedPalette(true);}
_updatePalettePanel(){this._palettePanel.removeChildren();const title=this._palettePanel.createChild('div','palette-title');title.textContent=Common.UIString('Color Palettes');const toolbar=new UI.Toolbar('',this._palettePanel);const closeButton=new UI.ToolbarButton('Return to color picker','largeicon-delete');closeButton.addEventListener(UI.ToolbarButton.Events.Click,this._togglePalettePanel.bind(this,false));toolbar.appendToolbarItem(closeButton);for(const palette of this._palettes.values())
this._palettePanel.appendChild(this._createPreviewPaletteElement(palette));}
_togglePalettePanel(show){if(this._palettePanelShowing===show)
return;if(show)
this._updatePalettePanel();this._palettePanelShowing=show;this.contentElement.classList.toggle('palette-panel-showing',show);this._focus();}
_focus(){if(!this.isShowing())
return;if(this._palettePanelShowing)
this._palettePanel.focus({preventScroll:true});else
this.contentElement.focus();}
_createPaletteColor(colorText,colorName,animationDelay){const element=createElementWithClass('div','spectrum-palette-color');element.style.background=String.sprintf('linear-gradient(%s, %s), url(Images/checker.png)',colorText,colorText);if(animationDelay)
element.animate([{opacity:0},{opacity:1}],{duration:100,delay:animationDelay,fill:'backwards'});element.title=colorName||colorText;return element;}
_showPalette(palette,animate,event){this._resizeForSelectedPalette();this._paletteContainer.removeChildren();for(let i=0;i<palette.colors.length;i++){const animationDelay=animate?i*100/palette.colors.length:0;const colorElement=this._createPaletteColor(palette.colors[i],palette.colorNames[i],animationDelay);colorElement.addEventListener('mousedown',this._paletteColorSelected.bind(this,palette.colors[i],palette.colorNames[i],palette.matchUserFormat));if(palette.mutable){colorElement.__mutable=true;colorElement.__color=palette.colors[i];colorElement.addEventListener('contextmenu',this._showPaletteColorContextMenu.bind(this,i));}else if(palette===ColorPicker.Spectrum.MaterialPalette){colorElement.classList.add('has-material-shades');let shadow=colorElement.createChild('div','spectrum-palette-color spectrum-palette-color-shadow');shadow.style.background=palette.colors[i];shadow=colorElement.createChild('div','spectrum-palette-color spectrum-palette-color-shadow');shadow.style.background=palette.colors[i];colorElement.title=ls`${palette.colors[i]}. Long-click to show alternate shades.`;new UI.LongClickController(colorElement,this._showLightnessShades.bind(this,colorElement,palette.colors[i]));}
this._paletteContainer.appendChild(colorElement);}
this._paletteContainerMutable=palette.mutable;if(palette.mutable){this._paletteContainer.appendChild(this._addColorToolbar.element);this._paletteContainer.appendChild(this._deleteIconToolbar.element);}else{this._addColorToolbar.element.remove();this._deleteIconToolbar.element.remove();}
this._togglePalettePanel(false);this._focus();}
_showLightnessShades(colorElement,colorText,event){function closeLightnessShades(element){this._shadesContainer.classList.add('hidden');element.classList.remove('spectrum-shades-shown');this._shadesContainer.ownerDocument.removeEventListener('mousedown',this._shadesCloseHandler,true);delete this._shadesCloseHandler;}
if(this._shadesCloseHandler)
this._shadesCloseHandler();this._shadesContainer.classList.remove('hidden');this._shadesContainer.removeChildren();this._shadesContainer.animate([{transform:'scaleY(0)',opacity:'0'},{transform:'scaleY(1)',opacity:'1'}],{duration:200,easing:'cubic-bezier(0.4, 0, 0.2, 1)'});let shadesTop=this._paletteContainer.offsetTop+colorElement.offsetTop+colorElement.parentElement.offsetTop;if(this._contrastDetails)
shadesTop+=this._contrastDetails.element().offsetHeight;this._shadesContainer.style.top=shadesTop+'px';this._shadesContainer.style.left=colorElement.offsetLeft+'px';colorElement.classList.add('spectrum-shades-shown');const shades=ColorPicker.Spectrum.MaterialPaletteShades[colorText];for(let i=shades.length-1;i>=0;i--){const shadeElement=this._createPaletteColor(shades[i],undefined,i*200/shades.length+100);shadeElement.addEventListener('mousedown',this._paletteColorSelected.bind(this,shades[i],shades[i],false));this._shadesContainer.appendChild(shadeElement);}
this._shadesContainer.focus();this._shadesCloseHandler=closeLightnessShades.bind(this,colorElement);this._shadesContainer.ownerDocument.addEventListener('mousedown',this._shadesCloseHandler,true);}
_slotIndexForEvent(e){const localX=e.pageX-this._paletteContainer.totalOffsetLeft();const localY=e.pageY-this._paletteContainer.totalOffsetTop();const col=Math.min(localX/ColorPicker.Spectrum._colorChipSize|0,ColorPicker.Spectrum._itemsPerPaletteRow-1);const row=(localY/ColorPicker.Spectrum._colorChipSize)|0;return Math.min(row*ColorPicker.Spectrum._itemsPerPaletteRow+col,this._customPaletteSetting.get().colors.length-1);}
_isDraggingToBin(e){return e.pageX>this._deleteIconToolbar.element.totalOffsetLeft();}
_paletteDragStart(e){const element=e.deepElementFromPoint();if(!element||!element.__mutable)
return false;const index=this._slotIndexForEvent(e);this._dragElement=element;this._dragHotSpotX=e.pageX-(index%ColorPicker.Spectrum._itemsPerPaletteRow)*ColorPicker.Spectrum._colorChipSize;this._dragHotSpotY=e.pageY-(index/ColorPicker.Spectrum._itemsPerPaletteRow|0)*ColorPicker.Spectrum._colorChipSize;return true;}
_paletteDrag(e){if(e.pageX<this._paletteContainer.totalOffsetLeft()||e.pageY<this._paletteContainer.totalOffsetTop())
return;const newIndex=this._slotIndexForEvent(e);const offsetX=e.pageX-(newIndex%ColorPicker.Spectrum._itemsPerPaletteRow)*ColorPicker.Spectrum._colorChipSize;const offsetY=e.pageY-(newIndex/ColorPicker.Spectrum._itemsPerPaletteRow|0)*ColorPicker.Spectrum._colorChipSize;const isDeleting=this._isDraggingToBin(e);this._deleteIconToolbar.element.classList.add('dragging');this._deleteIconToolbar.element.classList.toggle('delete-color-toolbar-active',isDeleting);const dragElementTransform='translateX('+(offsetX-this._dragHotSpotX)+'px) translateY('+(offsetY-this._dragHotSpotY)+'px)';this._dragElement.style.transform=isDeleting?dragElementTransform+' scale(0.8)':dragElementTransform;const children=Array.prototype.slice.call(this._paletteContainer.children);const index=children.indexOf(this._dragElement);const swatchOffsets=new Map();for(const swatch of children)
swatchOffsets.set(swatch,swatch.totalOffset());if(index!==newIndex)
this._paletteContainer.insertBefore(this._dragElement,children[newIndex>index?newIndex+1:newIndex]);for(const swatch of children){if(swatch===this._dragElement)
continue;const before=swatchOffsets.get(swatch);const after=swatch.totalOffset();if(before.left!==after.left||before.top!==after.top){swatch.animate([{transform:'translateX('+(before.left-after.left)+'px) translateY('+(before.top-after.top)+'px)'},{transform:'none'}],{duration:100,easing:'cubic-bezier(0, 0, 0.2, 1)'});}}}
_paletteDragEnd(e){if(this._isDraggingToBin(e))
this._dragElement.remove();this._dragElement.style.removeProperty('transform');const children=this._paletteContainer.children;const colors=[];for(let i=0;i<children.length;++i){if(children[i].__color)
colors.push(children[i].__color);}
const palette=this._customPaletteSetting.get();palette.colors=colors;this._customPaletteSetting.set(palette);this._showPalette(this._customPaletteSetting.get(),false);this._deleteIconToolbar.element.classList.remove('dragging');this._deleteIconToolbar.element.classList.remove('delete-color-toolbar-active');}
_loadPalettes(){this._palettes.set(ColorPicker.Spectrum.MaterialPalette.title,ColorPicker.Spectrum.MaterialPalette);const defaultCustomPalette={title:'Custom',colors:[],colorNames:[],mutable:true};this._customPaletteSetting=Common.settings.createSetting('customColorPalette',defaultCustomPalette);const customPalette=this._customPaletteSetting.get();customPalette.colorNames=customPalette.colorNames||[];this._palettes.set(customPalette.title,customPalette);this._selectedColorPalette=Common.settings.createSetting('selectedColorPalette',ColorPicker.Spectrum.GeneratedPaletteTitle);const palette=this._palettes.get(this._selectedColorPalette.get());if(palette)
this._showPalette(palette,true);}
addPalette(palette){this._palettes.set(palette.title,palette);if(this._selectedColorPalette.get()===palette.title)
this._showPalette(palette,true);}
_createPreviewPaletteElement(palette){const colorsPerPreviewRow=5;const previewElement=createElementWithClass('div','palette-preview');const titleElement=previewElement.createChild('div','palette-preview-title');titleElement.textContent=palette.title;let i;for(i=0;i<colorsPerPreviewRow&&i<palette.colors.length;i++)
previewElement.appendChild(this._createPaletteColor(palette.colors[i],palette.colorNames[i]));for(;i<colorsPerPreviewRow;i++)
previewElement.createChild('div','spectrum-palette-color empty-color');previewElement.addEventListener('click',this._paletteSelected.bind(this,palette));return previewElement;}
_paletteSelected(palette){this._selectedColorPalette.set(palette.title);this._showPalette(palette,true);}
_resizeForSelectedPalette(force){const palette=this._palettes.get(this._selectedColorPalette.get());if(!palette)
return;let numColors=palette.colors.length;if(palette===this._customPaletteSetting.get())
numColors++;const rowsNeeded=Math.max(1,Math.ceil(numColors/ColorPicker.Spectrum._itemsPerPaletteRow));if(this._numPaletteRowsShown===rowsNeeded&&!force)
return;this._numPaletteRowsShown=rowsNeeded;const paletteColorHeight=12;const paletteMargin=12;let paletteTop=236;if(this._contrastDetails){if(this._contrastDetails.expanded())
paletteTop+=78;else
paletteTop+=36;}
this.element.style.height=(paletteTop+paletteMargin+(paletteColorHeight+paletteMargin)*rowsNeeded)+'px';this.dispatchEventToListeners(ColorPicker.Spectrum.Events.SizeChanged);}
_paletteColorSelected(colorText,colorName,matchUserFormat){const color=Common.Color.parse(colorText);if(!color)
return;this._innerSetColor(color.hsva(),colorText,colorName,matchUserFormat?this._colorFormat:color.format(),ColorPicker.Spectrum._ChangeSource.Other);}
_addColorToCustomPalette(event){const palette=this._customPaletteSetting.get();palette.colors.push(this.colorString());this._customPaletteSetting.set(palette);this._showPalette(this._customPaletteSetting.get(),false);}
_showPaletteColorContextMenu(colorIndex,event){if(!this._paletteContainerMutable)
return;const contextMenu=new UI.ContextMenu(event);if(colorIndex!==-1){contextMenu.defaultSection().appendItem(Common.UIString('Remove color'),this._deletePaletteColors.bind(this,colorIndex,false));contextMenu.defaultSection().appendItem(Common.UIString('Remove all to the right'),this._deletePaletteColors.bind(this,colorIndex,true));}
contextMenu.defaultSection().appendItem(Common.UIString('Clear palette'),this._deletePaletteColors.bind(this,-1,true));contextMenu.show();}
_deletePaletteColors(colorIndex,toRight){const palette=this._customPaletteSetting.get();if(toRight)
palette.colors.splice(colorIndex+1,palette.colors.length-colorIndex-1);else
palette.colors.splice(colorIndex,1);this._customPaletteSetting.set(palette);this._showPalette(this._customPaletteSetting.get(),false);}
setColor(color,colorFormat){this._originalFormat=colorFormat;this._innerSetColor(color.hsva(),'',undefined,colorFormat,ColorPicker.Spectrum._ChangeSource.Model);}
_innerSetColor(hsva,colorString,colorName,colorFormat,changeSource){if(hsva!==undefined)
this._hsv=hsva;this._colorName=colorName;if(colorString!==undefined)
this._colorString=colorString;if(colorFormat!==undefined){const cf=Common.Color.Format;console.assert(colorFormat!==cf.Original,'Spectrum\'s color format cannot be Original');if(colorFormat===cf.RGBA)
colorFormat=cf.RGB;else if(colorFormat===cf.HSLA)
colorFormat=cf.HSL;else if(colorFormat===cf.HEXA)
colorFormat=cf.HEX;else if(colorFormat===cf.ShortHEXA)
colorFormat=cf.ShortHEX;this._colorFormat=colorFormat;}
if(hsva&&this._contrastInfo)
this._contrastInfo.setColor(Common.Color.fromHSVA(hsva));this._updateHelperLocations();this._updateUI();if(changeSource!==ColorPicker.Spectrum._ChangeSource.Input)
this._updateInput();if(changeSource!==ColorPicker.Spectrum._ChangeSource.Model)
this.dispatchEventToListeners(ColorPicker.Spectrum.Events.ColorChanged,this.colorString());}
_color(){return Common.Color.fromHSVA(this._hsv);}
colorName(){return this._colorName;}
colorString(){if(this._colorString)
return this._colorString;const cf=Common.Color.Format;const color=this._color();let colorString=color.asString(this._colorFormat);if(colorString)
return colorString;if(this._colorFormat===cf.Nickname)
colorString=color.asString(color.hasAlpha()?cf.HEXA:cf.HEX);else if(this._colorFormat===cf.ShortHEX)
colorString=color.asString(color.detectHEXFormat());else if(this._colorFormat===cf.HEX)
colorString=color.asString(cf.HEXA);else if(this._colorFormat===cf.HSL)
colorString=color.asString(cf.HSLA);else
colorString=color.asString(cf.RGBA);console.assert(colorString);return colorString||'';}
_updateHelperLocations(){const h=this._hsv[0];const s=this._hsv[1];const v=this._hsv[2];const alpha=this._hsv[3];this._dragX=s*this.dragWidth;this._dragY=this.dragHeight-(v*this.dragHeight);const dragX=Math.max(-this._colorDragElementHeight,Math.min(this.dragWidth-this._colorDragElementHeight,this._dragX-this._colorDragElementHeight));const dragY=Math.max(-this._colorDragElementHeight,Math.min(this.dragHeight-this._colorDragElementHeight,this._dragY-this._colorDragElementHeight));this._colorDragElement.positionAt(dragX,dragY);const hueSlideX=(1-h)*this._hueAlphaWidth-this.slideHelperWidth;this._hueSlider.style.left=hueSlideX+'px';const alphaSlideX=alpha*this._hueAlphaWidth-this.slideHelperWidth;this._alphaSlider.style.left=alphaSlideX+'px';}
_updateInput(){const cf=Common.Color.Format;if(this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX||this._colorFormat===cf.Nickname){this._hexContainer.hidden=false;this._displayContainer.hidden=true;if(this._colorFormat===cf.ShortHEX){this._hexValue.value=this._color().asString(this._color().detectHEXFormat());}else{this._hexValue.value=this._color().asString(this._color().hasAlpha()?cf.HEXA:cf.HEX);}}else{this._hexContainer.hidden=true;this._displayContainer.hidden=false;const isRgb=this._colorFormat===cf.RGB;this._textLabels.textContent=isRgb?'RGBA':'HSLA';const colorValues=isRgb?this._color().canonicalRGBA():this._color().canonicalHSLA();for(let i=0;i<3;++i){this._textValues[i].value=colorValues[i];if(!isRgb&&(i===1||i===2))
this._textValues[i].value+='%';}
this._textValues[3].value=Math.round(colorValues[3]*100)/100;}}
_updateUI(){const h=Common.Color.fromHSVA([this._hsv[0],1,1,1]);this._colorElement.style.backgroundColor=(h.asString(Common.Color.Format.RGB));if(this._contrastOverlay)
this._contrastOverlay.setDimensions(this.dragWidth,this.dragHeight);this._swatch.setColor(this._color(),this.colorString());this._colorDragElement.style.backgroundColor=(this._color().asString(Common.Color.Format.RGBA));const noAlpha=Common.Color.fromHSVA(this._hsv.slice(0,3).concat(1));this._alphaElementBackground.style.backgroundImage=String.sprintf('linear-gradient(to right, rgba(0,0,0,0), %s)',noAlpha.asString(Common.Color.Format.RGB));}
_formatViewSwitch(){const cf=Common.Color.Format;let format=cf.RGB;if(this._colorFormat===cf.RGB)
format=cf.HSL;else if(this._colorFormat===cf.HSL)
format=(this._originalFormat===cf.ShortHEX||this._originalFormat===cf.ShortHEXA)?cf.ShortHEX:cf.HEX;this._innerSetColor(undefined,'',undefined,format,ColorPicker.Spectrum._ChangeSource.Other);}
_inputChanged(event){function elementValue(element){return element.value;}
const inputElement=(event.currentTarget);const newValue=UI.createReplacementString(inputElement.value,event);if(newValue){inputElement.value=newValue;inputElement.selectionStart=0;inputElement.selectionEnd=newValue.length;event.consume(true);}
const cf=Common.Color.Format;let colorString;if(this._colorFormat===cf.Nickname||this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX){colorString=this._hexValue.value;}else{const format=this._colorFormat===cf.RGB?'rgba':'hsla';const values=this._textValues.map(elementValue).join(', ');colorString=String.sprintf('%s(%s)',format,values);}
const color=Common.Color.parse(colorString);if(!color)
return;let colorFormat=undefined;if(this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX)
colorFormat=color.detectHEXFormat();this._innerSetColor(color.hsva(),colorString,undefined,colorFormat,ColorPicker.Spectrum._ChangeSource.Input);}
wasShown(){this._hueAlphaWidth=this._hueElement.offsetWidth;this.slideHelperWidth=this._hueSlider.offsetWidth/2;this.dragWidth=this._colorElement.offsetWidth;this.dragHeight=this._colorElement.offsetHeight;this._colorDragElementHeight=this._colorDragElement.offsetHeight/2;this._innerSetColor(undefined,undefined,undefined,undefined,ColorPicker.Spectrum._ChangeSource.Model);this._toggleColorPicker(true);}
willHide(){this._toggleColorPicker(false);}
_toggleColorPicker(enabled,event){if(enabled===undefined)
enabled=!this._colorPickerButton.toggled();this._colorPickerButton.setToggled(enabled);InspectorFrontendHost.setEyeDropperActive(enabled);if(enabled){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._colorPickedBound);}else{InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._colorPickedBound);}}
_colorPicked(event){const rgbColor=(event.data);const rgba=[rgbColor.r,rgbColor.g,rgbColor.b,(rgbColor.a/2.55|0)/100];const color=Common.Color.fromRGBA(rgba);this._innerSetColor(color.hsva(),'',undefined,undefined,ColorPicker.Spectrum._ChangeSource.Other);InspectorFrontendHost.bringToFront();}};ColorPicker.Spectrum._ChangeSource={Input:'Input',Model:'Model',Other:'Other'};ColorPicker.Spectrum.Events={ColorChanged:Symbol('ColorChanged'),SizeChanged:Symbol('SizeChanged')};ColorPicker.Spectrum._colorChipSize=24;ColorPicker.Spectrum._itemsPerPaletteRow=8;ColorPicker.Spectrum.Palette;ColorPicker.Spectrum.GeneratedPaletteTitle='Page colors';ColorPicker.Spectrum.PaletteGenerator=class{constructor(callback){this._callback=callback;this._frequencyMap=new Map();const stylesheetPromises=[];for(const cssModel of SDK.targetManager.models(SDK.CSSModel)){for(const stylesheet of cssModel.allStyleSheets())
stylesheetPromises.push(this._processStylesheet(stylesheet));}
Promise.all(stylesheetPromises).catchException(null).then(this._finish.bind(this));}
_frequencyComparator(a,b){return this._frequencyMap.get(b)-this._frequencyMap.get(a);}
_finish(){function hueComparator(a,b){const hsva=paletteColors.get(a).hsva();const hsvb=paletteColors.get(b).hsva();if(hsvb[1]<0.12&&hsva[1]<0.12)
return hsvb[2]*hsvb[3]-hsva[2]*hsva[3];if(hsvb[1]<0.12)
return-1;if(hsva[1]<0.12)
return 1;if(hsvb[0]===hsva[0])
return hsvb[1]*hsvb[3]-hsva[1]*hsva[3];return(hsvb[0]+0.94)%1-(hsva[0]+0.94)%1;}
let colors=this._frequencyMap.keysArray();colors=colors.sort(this._frequencyComparator.bind(this));const paletteColors=new Map();const colorsPerRow=24;while(paletteColors.size<colorsPerRow&&colors.length){const colorText=colors.shift();const color=Common.Color.parse(colorText);if(!color||color.nickname()==='white'||color.nickname()==='black')
continue;paletteColors.set(colorText,color);}
this._callback({title:ColorPicker.Spectrum.GeneratedPaletteTitle,colors:paletteColors.keysArray().sort(hueComparator),colorNames:[],mutable:false});}
async _processStylesheet(stylesheet){let text=await stylesheet.requestContent()||'';text=text.toLowerCase();const regexResult=text.match(/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-f]{6}|#[0-9a-f]{3})/g)||[];for(const c of regexResult){let frequency=this._frequencyMap.get(c)||0;this._frequencyMap.set(c,++frequency);}}};ColorPicker.Spectrum.MaterialPaletteShades={'#F44336':['#FFEBEE','#FFCDD2','#EF9A9A','#E57373','#EF5350','#F44336','#E53935','#D32F2F','#C62828','#B71C1C'],'#E91E63':['#FCE4EC','#F8BBD0','#F48FB1','#F06292','#EC407A','#E91E63','#D81B60','#C2185B','#AD1457','#880E4F'],'#9C27B0':['#F3E5F5','#E1BEE7','#CE93D8','#BA68C8','#AB47BC','#9C27B0','#8E24AA','#7B1FA2','#6A1B9A','#4A148C'],'#673AB7':['#EDE7F6','#D1C4E9','#B39DDB','#9575CD','#7E57C2','#673AB7','#5E35B1','#512DA8','#4527A0','#311B92'],'#3F51B5':['#E8EAF6','#C5CAE9','#9FA8DA','#7986CB','#5C6BC0','#3F51B5','#3949AB','#303F9F','#283593','#1A237E'],'#2196F3':['#E3F2FD','#BBDEFB','#90CAF9','#64B5F6','#42A5F5','#2196F3','#1E88E5','#1976D2','#1565C0','#0D47A1'],'#03A9F4':['#E1F5FE','#B3E5FC','#81D4FA','#4FC3F7','#29B6F6','#03A9F4','#039BE5','#0288D1','#0277BD','#01579B'],'#00BCD4':['#E0F7FA','#B2EBF2','#80DEEA','#4DD0E1','#26C6DA','#00BCD4','#00ACC1','#0097A7','#00838F','#006064'],'#009688':['#E0F2F1','#B2DFDB','#80CBC4','#4DB6AC','#26A69A','#009688','#00897B','#00796B','#00695C','#004D40'],'#4CAF50':['#E8F5E9','#C8E6C9','#A5D6A7','#81C784','#66BB6A','#4CAF50','#43A047','#388E3C','#2E7D32','#1B5E20'],'#8BC34A':['#F1F8E9','#DCEDC8','#C5E1A5','#AED581','#9CCC65','#8BC34A','#7CB342','#689F38','#558B2F','#33691E'],'#CDDC39':['#F9FBE7','#F0F4C3','#E6EE9C','#DCE775','#D4E157','#CDDC39','#C0CA33','#AFB42B','#9E9D24','#827717'],'#FFEB3B':['#FFFDE7','#FFF9C4','#FFF59D','#FFF176','#FFEE58','#FFEB3B','#FDD835','#FBC02D','#F9A825','#F57F17'],'#FFC107':['#FFF8E1','#FFECB3','#FFE082','#FFD54F','#FFCA28','#FFC107','#FFB300','#FFA000','#FF8F00','#FF6F00'],'#FF9800':['#FFF3E0','#FFE0B2','#FFCC80','#FFB74D','#FFA726','#FF9800','#FB8C00','#F57C00','#EF6C00','#E65100'],'#FF5722':['#FBE9E7','#FFCCBC','#FFAB91','#FF8A65','#FF7043','#FF5722','#F4511E','#E64A19','#D84315','#BF360C'],'#795548':['#EFEBE9','#D7CCC8','#BCAAA4','#A1887F','#8D6E63','#795548','#6D4C41','#5D4037','#4E342E','#3E2723'],'#9E9E9E':['#FAFAFA','#F5F5F5','#EEEEEE','#E0E0E0','#BDBDBD','#9E9E9E','#757575','#616161','#424242','#212121'],'#607D8B':['#ECEFF1','#CFD8DC','#B0BEC5','#90A4AE','#78909C','#607D8B','#546E7A','#455A64','#37474F','#263238']};ColorPicker.Spectrum.MaterialPalette={title:'Material',mutable:false,matchUserFormat:true,colors:Object.keys(ColorPicker.Spectrum.MaterialPaletteShades),colorNames:[]};ColorPicker.Spectrum.Swatch=class{constructor(parentElement){this._colorString;const swatchElement=parentElement.createChild('span','swatch');this._swatchInnerElement=swatchElement.createChild('span','swatch-inner');this._swatchOverlayElement=swatchElement.createChild('span','swatch-overlay');this._swatchOverlayElement.addEventListener('click',this._onCopyIconClick.bind(this));this._swatchOverlayElement.addEventListener('mouseout',this._onCopyIconMouseout.bind(this));this._swatchCopyIcon=UI.Icon.create('largeicon-copy','copy-color-icon');this._swatchCopyIcon.title=Common.UIString('Copy color to clipboard');this._swatchOverlayElement.appendChild(this._swatchCopyIcon);}
setColor(color,colorString){this._swatchInnerElement.style.backgroundColor=(color.asString(Common.Color.Format.RGBA));this._swatchInnerElement.classList.toggle('swatch-inner-white',color.hsla()[2]>0.9);this._colorString=colorString||null;if(colorString)
this._swatchOverlayElement.hidden=false;else
this._swatchOverlayElement.hidden=true;}
_onCopyIconClick(){this._swatchCopyIcon.setIconType('largeicon-checkmark');InspectorFrontendHost.copyText(this._colorString);}
_onCopyIconMouseout(){this._swatchCopyIcon.setIconType('largeicon-copy');}};;Runtime.cachedResources["color_picker/spectrum.css"]="/* https://github.com/bgrins/spectrum */\n:host {\n width: 232px;\n height: 319px;\n -webkit-user-select: none;\n overflow: hidden;\n}\n\n:selection {\n background-color: blue;\n color: white;\n}\n\n.spectrum-color {\n position: relative;\n width: 232px;\n height: 124px;\n border-radius: 2px 2px 0 0;\n overflow: hidden;\n flex: none;\n}\n\n.spectrum-tools {\n position: relative;\n height: 111px;\n width: 100%;\n flex: none;\n}\n\n.spectrum-hue {\n top: 16px;\n}\n\n.spectrum-alpha {\n top: 35px;\n background-image: url(Images/checker.png);\n background-size: 12px 11px;\n}\n\n.spectrum-alpha-background {\n height: 100%;\n border-radius: 2px;\n}\n\n.spectrum-hue, .spectrum-alpha {\n position: absolute;\n left: 86px;\n width: 130px;\n height: 11px;\n border-radius: 2px;\n}\n\n.spectrum-dragger,\n.spectrum-slider {\n -webkit-user-select: none;\n}\n\n.spectrum-sat,\n.-theme-preserve {\n background-image: linear-gradient(to right, white, rgba(204, 154, 129, 0));\n}\n\n.spectrum-val,\n.-theme-preserve {\n background-image: linear-gradient(to top, black, rgba(204, 154, 129, 0));\n}\n\n.spectrum-hue {\n background: linear-gradient(to left, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);\n}\n\n.spectrum-dragger {\n border-radius: 12px;\n height: 12px;\n width: 12px;\n border: 1px solid white;\n cursor: pointer;\n position: absolute;\n top: 0;\n left: 0;\n background: black;\n box-shadow: 0 0 2px 0px rgba(0, 0, 0, 0.24);\n}\n\n.spectrum-slider {\n position: absolute;\n top: -1px;\n cursor: pointer;\n width: 13px;\n height: 13px;\n border-radius: 13px;\n background-color: rgb(248, 248, 248);\n box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.37);\n}\n\n.spectrum-contrast-details {\n position: relative;\n background-color: white;\n width: 100%;\n height: 111px;\n top: 0;\n font-size: 13px;\n color: #333;\n border-top: var(--divider-border);\n line-height: initial;\n overflow: hidden;\n flex: none;\n}\n\n.spectrum-contrast-details {\n height: 78px;\n flex: none;\n}\n\n.spectrum-contrast-details.collapsed {\n height: 36px;\n flex: none;\n}\n\n.spectrum-contrast-details div.toolbar.expand {\n position: absolute;\n right: 6px;\n top: 6px;\n margin: 0;\n}\n\n.spectrum-contrast-details .toolbar-state-on [is=ui-icon] {\n background-color: rgb(110, 110, 110);\n}\n\n.spectrum-contrast-details.visible {\n display: initial;\n}\n\n.spectrum-contrast-details div.container {\n margin: 10px;\n}\n\n.spectrum-contrast-details.collapsed .expanded-details {\n display: none;\n}\n\n.spectrum-contrast-details .expanded-details {\n display: flex;\n margin: 12px 12px 0 4px;\n}\n\n.contrast-pass-fail {\n margin-left: 0.5em;\n}\n\n.spectrum-contrast-details .contrast-choose-bg-color,\n.spectrum-contrast-details .contrast-thresholds {\n width: 145px;\n}\n\n.contrast-choose-bg-color {\n margin: 8px 0 0 5px;\n font-style: italic;\n}\n\n.contrast-link-label {\n cursor: pointer;\n}\n\n.contrast-link-label:hover {\n text-decoration: underline;\n}\n\n.spectrum-contrast-details .background-color {\n position: absolute;\n flex: none;\n right: 12px;\n}\n\n.spectrum-contrast-details .spectrum-eye-dropper {\n top: 2px;\n right: 34px;\n position: absolute;\n left: auto;\n}\n\n.contrast-details-value {\n color: #333;\n margin: 1px 5px;\n user-select: text;\n}\n\n.contrast-details-value [is=ui-icon] {\n display: none;\n margin-left: 5px;\n background-color: #333;\n}\n\n[is=ui-icon].smallicon-no {\n background-color: red;\n}\n\n.contrast-pass-fail span[is=ui-icon] {\n margin-left: 5px;\n}\n\n[is=ui-icon].smallicon-checkmark-square,\n[is=ui-icon].smallicon-checkmark-behind {\n background-color: #00b06f;\n}\n\n.spectrum-contrast-de
toolbarItem(){return this._toolbarItem;}
highlightedItemChanged(from,to,fromElement,toElement){SDK.OverlayModel.hideDOMNodeHighlight();if(to&&to.frameId){const overlayModel=to.target().model(SDK.OverlayModel);if(overlayModel)
overlayModel.highlightFrame(to.frameId);}
if(fromElement)
fromElement.classList.remove('highlighted');if(toElement)
toElement.classList.add('highlighted');}
titleFor(executionContext){const target=executionContext.target();let label=executionContext.label()?target.decorateLabel(executionContext.label()):'';if(executionContext.frameId){const resourceTreeModel=target.model(SDK.ResourceTreeModel);const frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);if(frame)
label=label||frame.displayName();}
label=label||executionContext.origin;return label;}
_depthFor(executionContext){let target=executionContext.target();let depth=0;if(!executionContext.isDefault)
depth++;if(executionContext.frameId){const resourceTreeModel=target.model(SDK.ResourceTreeModel);let frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);while(frame){frame=frame.parentFrame||frame.crossTargetParentFrame();if(frame){depth++;target=frame.resourceTreeModel().target();}}}
let targetDepth=0;while(target.parentTarget()){if(target.parentTarget().type()===SDK.Target.Type.ServiceWorker){targetDepth=0;break;}
targetDepth++;target=target.parentTarget();}
depth+=targetDepth;return depth;}
_badgeFor(executionContext){if(!executionContext.frameId||!executionContext.isDefault)
return null;const resourceTreeModel=executionContext.target().model(SDK.ResourceTreeModel);const frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);if(!frame)
return null;const badgePool=new ProductRegistry.BadgePool();this._badgePoolForExecutionContext.set(executionContext,badgePool);return badgePool.badgeForFrame(frame);}
_disposeExecutionContextBadge(executionContext){const badgePool=this._badgePoolForExecutionContext.get(executionContext);if(!badgePool)
return;badgePool.reset();this._badgePoolForExecutionContext.delete(executionContext);}
_executionContextCreated(executionContext){if(executionContext.target().type()===SDK.Target.Type.ServiceWorker)
return;this._items.insertWithComparator(executionContext,executionContext.runtimeModel.executionContextComparator());if(executionContext===UI.context.flavor(SDK.ExecutionContext))
this._dropDown.selectItem(executionContext);}
_onExecutionContextCreated(event){const executionContext=(event.data);this._executionContextCreated(executionContext);}
_onExecutionContextChanged(event){const executionContext=(event.data);if(this._items.indexOf(executionContext)===-1)
return;this._executionContextDestroyed(executionContext);this._executionContextCreated(executionContext);}
_executionContextDestroyed(executionContext){const index=this._items.indexOf(executionContext);if(index===-1)
return;this._disposeExecutionContextBadge(executionContext);this._items.remove(index);}
_onExecutionContextDestroyed(event){const executionContext=(event.data);this._executionContextDestroyed(executionContext);}
_executionContextChangedExternally(event){const executionContext=(event.data);this._dropDown.selectItem(executionContext);}
_isTopContext(executionContext){if(!executionContext||!executionContext.isDefault)
return false;const resourceTreeModel=executionContext.target().model(SDK.ResourceTreeModel);const frame=executionContext.frameId&&resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);if(!frame)
return false;return frame.isTopFrame();}
_hasTopContext(){return this._items.some(executionContext=>this._isTopContext(executionContext));}
modelAdded(runtimeModel){runtimeModel.executionContexts().forEach(this._executionContextCreated,this);}
modelRemoved(runtimeModel){for(let i=this._items.length-1;i>=0;i--){if(this._items.at(i).runtimeModel===runtimeModel)
this._executionContextDestroyed(this._items.at(i));}}
createElementForItem(item){const element=createElementWithClass('div');const shadowRoot=UI.createShadowRootWithCoreStyles(element,'console/consoleContextSelector.css');const title=shadowRoot.createChild('div','title');title.createTextChild(this.titleFor(item).trimEnd(100));const subTitle=shadowRoot.createChild('div','subtitle');const badgeElement=this._badgeFor(item);if(badgeElement){badgeElement.classList.add('badge');subTitle.appendChild(badgeElement);}
subTitle.createTextChild(this._subtitleFor(item));element.style.paddingLeft=(8+this._depthFor(item)*15)+'px';return element;}
_subtitleFor(executionContext){const target=executionContext.target();let frame;if(executionContext.frameId){const resourceTreeModel=target.model(SDK.ResourceTreeModel);frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);}
if(executionContext.origin.startsWith('chrome-extension://'))
return Common.UIString('Extension');if(!frame||!frame.parentFrame||frame.parentFrame.securityOrigin!==executionContext.origin){const url=executionContext.origin.asParsedURL();if(url)
return url.domain();}
if(frame){const callFrame=frame.findCreationCallFrame(callFrame=>!!callFrame.url);if(callFrame)
return new Common.ParsedURL(callFrame.url).domain();return Common.UIString('IFrame');}
return'';}
isItemSelectable(item){const callFrame=item.debuggerModel.selectedCallFrame();const callFrameContext=callFrame&&callFrame.script.executionContext();return!callFrameContext||item===callFrameContext;}
itemSelected(item){this._toolbarItem.element.classList.toggle('warning',!this._isTopContext(item)&&this._hasTopContext());UI.context.setFlavor(SDK.ExecutionContext,item);}
_callFrameSelectedInUI(){const callFrame=UI.context.flavor(SDK.DebuggerModel.CallFrame);const callFrameContext=callFrame&&callFrame.script.executionContext();if(callFrameContext)
UI.context.setFlavor(SDK.ExecutionContext,callFrameContext);}
_callFrameSelectedInModel(event){const debuggerModel=(event.data);for(const executionContext of this._items){if(executionContext.debuggerModel===debuggerModel){this._disposeExecutionContextBadge(executionContext);this._dropDown.refreshItem(executionContext);}}}
_frameNavigated(event){const frame=(event.data);const runtimeModel=frame.resourceTreeModel().target().model(SDK.RuntimeModel);if(!runtimeModel)
return;for(const executionContext of runtimeModel.executionContexts()){if(frame.id===executionContext.frameId){this._disposeExecutionContextBadge(executionContext);this._dropDown.refreshItem(executionContext);}}}};;Console.ConsoleFilter=class{constructor(name,parsedFilters,executionContext,levelsMask){this.name=name;this.parsedFilters=parsedFilters;this.executionContext=executionContext;this.levelsMask=levelsMask||Console.ConsoleFilter.defaultLevelsFilterValue();}
static allLevelsFilterValue(){const result={};for(const name of Object.values(SDK.ConsoleMessage.MessageLevel))
result[name]=true;return result;}
static defaultLevelsFilterValue(){const result=Console.ConsoleFilter.allLevelsFilterValue();result[SDK.ConsoleMessage.MessageLevel.Verbose]=false;return result;}
static singleLevelMask(level){const result={};result[level]=true;return result;}
clone(){const parsedFilters=this.parsedFilters.map(TextUtils.FilterParser.cloneFilter);const levelsMask=Object.assign({},this.levelsMask);return new Console.ConsoleFilter(this.name,parsedFilters,this.executionContext,levelsMask);}
shouldBeVisible(viewMessage){const message=viewMessage.consoleMessage();if(this.executionContext&&(this.executionContext.runtimeModel!==message.runtimeModel()||this.executionContext.id!==message.executionContextId))
return false;if(message.type===SDK.ConsoleMessage.MessageType.Command||message.type===SDK.ConsoleMessage.MessageType.Result||message.isGroupMessage())
return true;if(message.level&&!this.levelsMask[(message.level)])
return false;for(const filter of this.parsedFilters){if(!filter.key){if(filter.regex&&viewMessage.matchesFilterRegex(filter.regex)===filter.negative)
return false;if(filter.text&&viewMessage.matchesFilterText(filter.text)===filter.negative)
return false;}else{switch(filter.key){case Console.ConsoleFilter.FilterType.Context:if(!passesFilter(filter,message.context,false))
return false;break;case Console.ConsoleFilter.FilterType.Source:const sourceNameForMessage=message.source?SDK.ConsoleMessage.MessageSourceDisplayName.get((message.source)):message.source;if(!passesFilter(filter,sourceNameForMessage,true))
return false;break;case Console.ConsoleFilter.FilterType.Url:if(!passesFilter(filter,message.url,false))
return false;break;}}}
return true;function passesFilter(filter,value,exactMatch){if(!filter.text)
return!!value===filter.negative;if(!value)
return!filter.text===!filter.negative;const filterText=(filter.text).toLowerCase();const lowerCaseValue=value.toLowerCase();if(exactMatch&&(lowerCaseValue===filterText)===filter.negative)
return false;if(!exactMatch&&lowerCaseValue.includes(filterText)===filter.negative)
return false;return true;}}};Console.ConsoleFilter.FilterType={Context:'context',Source:'source',Url:'url'};;Console.ConsolePinPane=class extends UI.ThrottledWidget{constructor(){super(true,250);this.registerRequiredCSS('console/consolePinPane.css');this.registerRequiredCSS('object_ui/objectValue.css');this.contentElement.classList.add('console-pins','monospace');this.contentElement.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),false);this._pins=new Set();this._pinsSetting=Common.settings.createLocalSetting('consolePins',[]);for(const expression of this._pinsSetting.get())
this.addPin(expression);}
willHide(){for(const pin of this._pins)
pin.setHovered(false);}
_savePins(){const toSave=Array.from(this._pins).map(pin=>pin.expression());this._pinsSetting.set(toSave);}
_contextMenuEventFired(event){const contextMenu=new UI.ContextMenu(event);const target=event.deepElementFromPoint();if(target){const targetPinElement=target.enclosingNodeOrSelfWithClass('console-pin');if(targetPinElement){const targetPin=targetPinElement[Console.ConsolePin._PinSymbol];contextMenu.editSection().appendItem(ls`Edit expression`,targetPin.focus.bind(targetPin));contextMenu.editSection().appendItem(ls`Remove expression`,this._removePin.bind(this,targetPin));targetPin.appendToContextMenu(contextMenu);}}
contextMenu.editSection().appendItem(ls`Remove all expressions`,this._removeAllPins.bind(this));contextMenu.show();}
_removeAllPins(){for(const pin of this._pins)
this._removePin(pin);}
_removePin(pin){pin.element().remove();this._pins.delete(pin);this._savePins();}
addPin(expression,userGesture){const pin=new Console.ConsolePin(expression,this);this.contentElement.appendChild(pin.element());this._pins.add(pin);this._savePins();if(userGesture)
pin.focus();this.update();}
doUpdate(){if(!this._pins.size||!this.isShowing())
return Promise.resolve();if(this.isShowing())
this.update();const updatePromises=Array.from(this._pins,pin=>pin.updatePreview());return Promise.all(updatePromises).then(this._updatedForTest.bind(this));}
_updatedForTest(){}};Console.ConsolePin=class extends Common.Object{constructor(expression,pinPane){super();const deletePinIcon=UI.Icon.create('smallicon-cross','console-delete-pin');deletePinIcon.addEventListener('click',()=>pinPane._removePin(this));const fragment=UI.Fragment.build`
<div class='console-pin'>
${deletePinIcon}
<div class='console-pin-name' $='name'></div>
<div class='console-pin-preview' $='preview'>${ls`not available`}</div>
</div>`;this._pinElement=fragment.element();this._pinPreview=fragment.$('preview');const nameElement=fragment.$('name');nameElement.title=expression;this._pinElement[Console.ConsolePin._PinSymbol]=this;this._lastResult=null;this._lastExecutionContext=null;this._editor=null;this._committedExpression=expression;this._hovered=false;this._lastNode=null;this._pinPreview.addEventListener('mouseenter',this.setHovered.bind(this,true),false);this._pinPreview.addEventListener('mouseleave',this.setHovered.bind(this,false),false);this._pinPreview.addEventListener('click',event=>{if(this._lastNode){Common.Revealer.reveal(this._lastNode);event.consume();}},false);this._editorPromise=self.runtime.extension(UI.TextEditorFactory).instance().then(factory=>{this._editor=factory.createEditor({lineNumbers:false,lineWrapping:true,mimeType:'javascript',autoHeight:true,placeholder:ls`Expression`});this._editor.configureAutocomplete(ObjectUI.JavaScriptAutocompleteConfig.createConfigForEditor(this._editor));this._editor.widget().show(nameElement);this._editor.widget().element.classList.add('console-pin-editor');this._editor.widget().element.tabIndex=-1;this._editor.setText(expression);this._editor.widget().element.addEventListener('keydown',event=>{if(event.key==='Tab'&&!this._editor.text()){event.consume();return;}
if(event.keyCode===UI.KeyboardShortcut.Keys.Esc.code)
this._editor.setText(this._committedExpression);},true);this._editor.widget().element.addEventListener('focusout',event=>{const text=this._editor.text();const trimmedText=text.trim();if(text.length!==trimmedText.length)
this._editor.setText(trimmedText);this._committedExpression=trimmedText;pinPane._savePins();this._editor.setSelection(TextUtils.TextRange.createFromLocation(Infinity,Infinity));});});}
setHovered(hovered){if(this._hovered===hovered)
return;this._hovered=hovered;if(!hovered&&this._lastNode)
SDK.OverlayModel.hideDOMNodeHighlight();}
expression(){return this._committedExpression;}
element(){return this._pinElement;}
async focus(){await this._editorPromise;this._editor.widget().focus();this._editor.setSelection(TextUtils.TextRange.createFromLocation(Infinity,Infinity));}
appendToContextMenu(contextMenu){if(this._lastResult&&this._lastResult.object){contextMenu.appendApplicableItems(this._lastResult.object);this._lastResult=null;}}
async updatePreview(){if(!this._editor)
return;const text=this._editor.textWithCurrentSuggestion().trim();const isEditing=this._pinElement.hasFocus();const throwOnSideEffect=isEditing&&text!==this._committedExpression;const timeout=throwOnSideEffect?250:undefined;const executionContext=UI.context.flavor(SDK.ExecutionContext);const{preview,result}=await ObjectUI.JavaScriptREPL.evaluateAndBuildPreview(text,throwOnSideEffect,timeout,!isEditing,'console');if(this._lastResult&&this._lastExecutionContext)
this._lastExecutionContext.runtimeModel.releaseEvaluationResult(this._lastResult);this._lastResult=result||null;this._lastExecutionContext=executionContext||null;const previewText=preview.deepTextContent();if(!previewText||previewText!==this._pinPreview.deepTextContent()){this._pinPreview.removeChildren();if(result&&SDK.RuntimeModel.isSideEffectFailure(result)){const sideEffectLabel=this._pinPreview.createChild('span','object-value-calculate-value-button');sideEffectLabel.textContent=`(...)`;sideEffectLabel.title=ls`Evaluate, allowing side effects`;}else if(previewText){this._pinPreview.appendChild(preview);}else if(!isEditing){this._pinPreview.createTextChild(ls`not available`);}
this._pinPreview.title=previewText;}
let node=null;if(result&&result.object&&result.object.type==='object'&&result.object.subtype==='node')
node=result.object;if(this._hovered){if(node)
SDK.OverlayModel.highlightObjectAsDOMNode(node);else if(this._lastNode)
SDK.OverlayModel.hideDOMNodeHighlight();}
this._lastNode=node||null;const isError=result&&result.exceptionDetails&&!SDK.RuntimeModel.isSideEffectFailure(result);this._pinElement.classList.toggle('error-level',isError);}};Console.ConsolePin._PinSymbol=Symbol('pinSymbol');;Console.ConsoleSidebar=class extends UI.VBox{constructor(badgePool){super(true);this.setMinimumSize(125,0);this._tree=new UI.TreeOutlineInShadow();this._tree.registerRequiredCSS('console/consoleSidebar.css');this._tree.addEventListener(UI.TreeOutline.Events.ElementSelected,this._selectionChanged.bind(this));this.contentElement.appendChild(this._tree.element);this._selectedTreeElement=null;this._treeElements=[];const selectedFilterSetting=Common.settings.createSetting('console.sidebarSelectedFilter',null);const Levels=SDK.ConsoleMessage.MessageLevel;const consoleAPIParsedFilters=[{key:Console.ConsoleFilter.FilterType.Source,text:SDK.ConsoleMessage.MessageSource.ConsoleAPI,negative:false}];this._appendGroup(Console.ConsoleSidebar._groupSingularName.All,[],Console.ConsoleFilter.allLevelsFilterValue(),UI.Icon.create('mediumicon-list'),badgePool,selectedFilterSetting);this._appendGroup(Console.ConsoleSidebar._groupSingularName.ConsoleAPI,consoleAPIParsedFilters,Console.ConsoleFilter.allLevelsFilterValue(),UI.Icon.create('mediumicon-account-circle'),badgePool,selectedFilterSetting);this._appendGroup(Console.ConsoleSidebar._groupSingularName.Error,[],Console.ConsoleFilter.singleLevelMask(Levels.Error),UI.Icon.create('mediumicon-error-circle'),badgePool,selectedFilterSetting);this._appendGroup(Console.ConsoleSidebar._groupSingularName.Warning,[],Console.ConsoleFilter.singleLevelMask(Levels.Warning),UI.Icon.create('mediumicon-warning-triangle'),badgePool,selectedFilterSetting);this._appendGroup(Console.ConsoleSidebar._groupSingularName.Info,[],Console.ConsoleFilter.singleLevelMask(Levels.Info),UI.Icon.create('mediumicon-info-circle'),badgePool,selectedFilterSetting);this._appendGroup(Console.ConsoleSidebar._groupSingularName.Verbose,[],Console.ConsoleFilter.singleLevelMask(Levels.Verbose),UI.Icon.create('mediumicon-bug'),badgePool,selectedFilterSetting);const selectedTreeElementName=selectedFilterSetting.get();const defaultTreeElement=this._treeElements.find(x=>x.name()===selectedTreeElementName)||this._treeElements[0];defaultTreeElement.select();}
_appendGroup(name,parsedFilters,levelsMask,icon,badgePool,selectedFilterSetting){const filter=new Console.ConsoleFilter(name,parsedFilters,null,levelsMask);const treeElement=new Console.ConsoleSidebar.FilterTreeElement(filter,icon,badgePool,selectedFilterSetting);this._tree.appendChild(treeElement);this._treeElements.push(treeElement);}
clear(){for(const treeElement of this._treeElements)
treeElement.clear();}
onMessageAdded(viewMessage){for(const treeElement of this._treeElements)
treeElement.onMessageAdded(viewMessage);}
shouldBeVisible(viewMessage){if(!this._selectedTreeElement)
return true;return this._selectedTreeElement._filter.shouldBeVisible(viewMessage);}
_selectionChanged(event){this._selectedTreeElement=(event.data);this.dispatchEventToListeners(Console.ConsoleSidebar.Events.FilterSelected);}};Console.ConsoleSidebar.Events={FilterSelected:Symbol('FilterSelected')};Console.ConsoleSidebar.URLGroupTreeElement=class extends UI.TreeElement{constructor(filter,badge){super(filter.name);this._filter=filter;this._countElement=this.listItemElement.createChild('span','count');const leadingIcons=[UI.Icon.create('largeicon-navigator-file')];if(badge)
leadingIcons.push(badge);this.setLeadingIcons(leadingIcons);this._messageCount=0;}
incrementAndUpdateCounter(){this._messageCount++;this._countElement.textContent=this._messageCount;}};Console.ConsoleSidebar.FilterTreeElement=class extends UI.TreeElement{constructor(filter,icon,badgePool,selectedFilterSetting){super(filter.name);this._filter=filter;this._badgePool=badgePool;this._selectedFilterSetting=selectedFilterSetting;this._urlTreeElements=new Map();this.setLeadingIcons([icon]);this._messageCount=0;this._updateCounter();}
clear(){this._urlTreeElements.clear();this.removeChildren();this._messageCount=0;this._updateCounter();}
name(){return this._filter.name;}
onselect(selectedByUser){this._selectedFilterSetting.set(this._filter.name);return super.onselect(selectedByUser);}
_updateCounter(){const prefix=this._messageCount?this._messageCount:Common.UIString('No');const pluralizedName=this._messageCount===1?this._filter.name:Console.ConsoleSidebar._groupPluralNameMap.get(this._filter.name);this.title=`${prefix} ${pluralizedName}`;this.setExpandable(!!this.childCount());}
onMessageAdded(viewMessage){const message=viewMessage.consoleMessage();const shouldIncrementCounter=message.type!==SDK.ConsoleMessage.MessageType.Command&&message.type!==SDK.ConsoleMessage.MessageType.Result&&!message.isGroupMessage();if(!this._filter.shouldBeVisible(viewMessage)||!shouldIncrementCounter)
return;const child=this._childElement(message.url);child.incrementAndUpdateCounter();this._messageCount++;this._updateCounter();}
_childElement(url){const urlValue=url||null;let child=this._urlTreeElements.get(urlValue);if(child)
return child;const filter=this._filter.clone();const parsedURL=urlValue?urlValue.asParsedURL():null;if(urlValue)
filter.name=parsedURL?parsedURL.displayName:urlValue;else
filter.name=Common.UIString('<other>');filter.parsedFilters.push({key:Console.ConsoleFilter.FilterType.Url,text:urlValue,negative:false});const badge=parsedURL?this._badgePool.badgeForURL(parsedURL):null;child=new Console.ConsoleSidebar.URLGroupTreeElement(filter,badge);if(urlValue)
child.tooltip=urlValue;this._urlTreeElements.set(urlValue,child);this.appendChild(child);return child;}};Console.ConsoleSidebar._groupSingularName={ConsoleAPI:Common.UIString('user message'),All:Common.UIString('message'),Error:Common.UIString('error'),Warning:Common.UIString('warning'),Info:Common.UIString('info'),Verbose:Common.UIString('verbose')};Console.ConsoleSidebar._groupPluralNameMap=new Map([[Console.ConsoleSidebar._groupSingularName.ConsoleAPI,Common.UIString('user messages')],[Console.ConsoleSidebar._groupSingularName.All,Common.UIString('messages')],[Console.ConsoleSidebar._groupSingularName.Error,Common.UIString('errors')],[Console.ConsoleSidebar._groupSingularName.Warning,Common.UIString('warnings')],[Console.ConsoleSidebar._groupSingularName.Info,Common.UIString('info')],[Console.ConsoleSidebar._groupSingularName.Verbose,Common.UIString('verbose')]]);;Console.ConsoleViewport=class{constructor(provider){this.element=createElement('div');this.element.style.overflow='auto';this._topGapElement=this.element.createChild('div');this._topGapElement.style.height='0px';this._topGapElement.style.color='transparent';this._contentElement=this.element.createChild('div');this._bottomGapElement=this.element.createChild('div');this._bottomGapElement.style.height='0px';this._bottomGapElement.style.color='transparent';this._topGapElement.textContent='\uFEFF';this._bottomGapElement.textContent='\uFEFF';UI.ARIAUtils.markAsHidden(this._topGapElement);UI.ARIAUtils.markAsHidden(this._bottomGapElement);this._provider=provider;this.element.addEventListener('scroll',this._onScroll.bind(this),false);this.element.addEventListener('copy',this._onCopy.bind(this),false);this.element.addEventListener('dragstart',this._onDragStart.bind(this),false);this._contentElement.addEventListener('focusin',this._onFocusIn.bind(this),false);this._contentElement.addEventListener('focusout',this._onFocusOut.bind(this),false);this._contentElement.addEventListener('keydown',this._onKeyDown.bind(this),false);this._virtualSelectedIndex=-1;this._contentElement.tabIndex=-1;this._firstActiveIndex=-1;this._lastActiveIndex=-1;this._renderedItems=[];this._anchorSelection=null;this._headSelection=null;this._itemCount=0;this._cumulativeHeights=new Int32Array(0);this._muteCopyHandler=false;this._observer=new MutationObserver(this.refresh.bind(this));this._observerConfig={childList:true,subtree:true};}
stickToBottom(){return this._stickToBottom;}
setStickToBottom(value){this._stickToBottom=value;if(this._stickToBottom)
this._observer.observe(this._contentElement,this._observerConfig);else
this._observer.disconnect();}
hasVirtualSelection(){return this._virtualSelectedIndex!==-1;}
copyWithStyles(){this._muteCopyHandler=true;this.element.ownerDocument.execCommand('copy');this._muteCopyHandler=false;}
_onCopy(event){if(this._muteCopyHandler)
return;const text=this._selectedText();if(!text)
return;event.preventDefault();event.clipboardData.setData('text/plain',text);}
_onFocusIn(event){const renderedIndex=this._renderedItems.findIndex(item=>item.element().isSelfOrAncestor(event.target));if(renderedIndex!==-1)
this._virtualSelectedIndex=this._firstActiveIndex+renderedIndex;let focusLastChild=false;if(this._virtualSelectedIndex===-1&&this._isOutsideViewport((event.relatedTarget))&&event.target===this._contentElement&&this._itemCount){focusLastChild=true;this._virtualSelectedIndex=this._itemCount-1;this.refresh();this.scrollItemIntoView(this._virtualSelectedIndex);}
this._updateFocusedItem(focusLastChild);}
_onFocusOut(event){if(this._isOutsideViewport((event.relatedTarget)))
this._virtualSelectedIndex=-1;this._updateFocusedItem();}
_isOutsideViewport(element){return!!element&&!element.isSelfOrDescendant(this._contentElement);}
_onDragStart(event){const text=this._selectedText();if(!text)
return false;event.dataTransfer.clearData();event.dataTransfer.setData('text/plain',text);event.dataTransfer.effectAllowed='copy';return true;}
_onKeyDown(event){if(UI.isEditing()||!this._itemCount||event.shiftKey)
return;let isArrowUp=false;switch(event.key){case'ArrowUp':if(this._virtualSelectedIndex>0){isArrowUp=true;this._virtualSelectedIndex--;}else{return;}
break;case'ArrowDown':if(this._virtualSelectedIndex<this._itemCount-1)
this._virtualSelectedIndex++;else
return;break;case'Home':this._virtualSelectedIndex=0;break;case'End':this._virtualSelectedIndex=this._itemCount-1;break;default:return;}
event.consume(true);this.scrollItemIntoView(this._virtualSelectedIndex);this._updateFocusedItem(isArrowUp);}
_updateFocusedItem(focusLastChild){const selectedElement=this.renderedElementAt(this._virtualSelectedIndex);const changed=this._lastSelectedElement!==selectedElement;const containerHasFocus=this._contentElement===this.element.ownerDocument.deepActiveElement();if(this._lastSelectedElement&&changed)
this._lastSelectedElement.classList.remove('console-selected');if(selectedElement&&(focusLastChild||changed||containerHasFocus)&&this.element.hasFocus()){selectedElement.classList.add('console-selected');if(focusLastChild){this.setStickToBottom(false);this._renderedItems[this._virtualSelectedIndex-this._firstActiveIndex].focusLastChildOrSelf();}else if(!selectedElement.hasFocus()){focusWithoutScroll(selectedElement);}}
if(this._itemCount&&!this._contentElement.hasFocus())
this._contentElement.tabIndex=0;else
this._contentElement.tabIndex=-1;this._lastSelectedElement=selectedElement;function focusWithoutScroll(element){element.focus({preventScroll:true});}}
contentElement(){return this._contentElement;}
invalidate(){delete this._cachedProviderElements;this._itemCount=this._provider.itemCount();if(this._virtualSelectedIndex>this._itemCount-1)
this._virtualSelectedIndex=this._itemCount-1;this._rebuildCumulativeHeights();this.refresh();}
_providerElement(index){if(!this._cachedProviderElements)
this._cachedProviderElements=new Array(this._itemCount);let element=this._cachedProviderElements[index];if(!element){element=this._provider.itemElement(index);this._cachedProviderElements[index]=element;}
return element;}
_rebuildCumulativeHeights(){const firstActiveIndex=this._firstActiveIndex;const lastActiveIndex=this._lastActiveIndex;let height=0;this._cumulativeHeights=new Int32Array(this._itemCount);for(let i=0;i<this._itemCount;++i){if(firstActiveIndex<=i&&i-firstActiveIndex<this._renderedItems.length&&i<=lastActiveIndex)
height+=this._renderedItems[i-firstActiveIndex].element().offsetHeight;else
height+=this._provider.fastHeight(i);this._cumulativeHeights[i]=height;}}
_rebuildCumulativeHeightsIfNeeded(){let totalCachedHeight=0;let totalMeasuredHeight=0;for(let i=0;i<this._renderedItems.length;++i){const cachedItemHeight=this._cachedItemHeight(this._firstActiveIndex+i);const measuredHeight=this._renderedItems[i].element().offsetHeight;if(Math.abs(cachedItemHeight-measuredHeight)>1){this._rebuildCumulativeHeights();return;}
totalMeasuredHeight+=measuredHeight;totalCachedHeight+=cachedItemHeight;if(Math.abs(totalCachedHeight-totalMeasuredHeight)>1){this._rebuildCumulativeHeights();return;}}}
_cachedItemHeight(index){return index===0?this._cumulativeHeights[0]:this._cumulativeHeights[index]-this._cumulativeHeights[index-1];}
_isSelectionBackwards(selection){if(!selection||!selection.rangeCount)
return false;const range=document.createRange();range.setStart(selection.anchorNode,selection.anchorOffset);range.setEnd(selection.focusNode,selection.focusOffset);return range.collapsed;}
_createSelectionModel(itemIndex,node,offset){return{item:itemIndex,node:node,offset:offset};}
_updateSelectionModel(selection){const range=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!range||selection.isCollapsed||!this.element.hasSelection()){this._headSelection=null;this._anchorSelection=null;return false;}
let firstSelected=Number.MAX_VALUE;let lastSelected=-1;let hasVisibleSelection=false;for(let i=0;i<this._renderedItems.length;++i){if(range.intersectsNode(this._renderedItems[i].element())){const index=i+this._firstActiveIndex;firstSelected=Math.min(firstSelected,index);lastSelected=Math.max(lastSelected,index);hasVisibleSelection=true;}}
if(hasVisibleSelection){firstSelected=this._createSelectionModel(firstSelected,(range.startContainer),range.startOffset);lastSelected=this._createSelectionModel(lastSelected,(range.endContainer),range.endOffset);}
const topOverlap=range.intersectsNode(this._topGapElement)&&this._topGapElement._active;const bottomOverlap=range.intersectsNode(this._bottomGapElement)&&this._bottomGapElement._active;if(!topOverlap&&!bottomOverlap&&!hasVisibleSelection){this._headSelection=null;this._anchorSelection=null;return false;}
if(!this._anchorSelection||!this._headSelection){this._anchorSelection=this._createSelectionModel(0,this.element,0);this._headSelection=this._createSelectionModel(this._itemCount-1,this.element,this.element.children.length);this._selectionIsBackward=false;}
const isBackward=this._isSelectionBackwards(selection);const startSelection=this._selectionIsBackward?this._headSelection:this._anchorSelection;const endSelection=this._selectionIsBackward?this._anchorSelection:this._headSelection;if(topOverlap&&bottomOverlap&&hasVisibleSelection){firstSelected=firstSelected.item<startSelection.item?firstSelected:startSelection;lastSelected=lastSelected.item>endSelection.item?lastSelected:endSelection;}else if(!hasVisibleSelection){firstSelected=startSelection;lastSelected=endSelection;}else if(topOverlap){firstSelected=isBackward?this._headSelection:this._anchorSelection;}else if(bottomOverlap){lastSelected=isBackward?this._anchorSelection:this._headSelection;}
if(isBackward){this._anchorSelection=lastSelected;this._headSelection=firstSelected;}else{this._anchorSelection=firstSelected;this._headSelection=lastSelected;}
this._selectionIsBackward=isBackward;return true;}
_restoreSelection(selection){let anchorElement=null;let anchorOffset;if(this._firstActiveIndex<=this._anchorSelection.item&&this._anchorSelection.item<=this._lastActiveIndex){anchorElement=this._anchorSelection.node;anchorOffset=this._anchorSelection.offset;}else{if(this._anchorSelection.item<this._firstActiveIndex)
anchorElement=this._topGapElement;else if(this._anchorSelection.item>this._lastActiveIndex)
anchorElement=this._bottomGapElement;anchorOffset=this._selectionIsBackward?1:0;}
let headElement=null;let headOffset;if(this._firstActiveIndex<=this._headSelection.item&&this._headSelection.item<=this._lastActiveIndex){headElement=this._headSelection.node;headOffset=this._headSelection.offset;}else{if(this._headSelection.item<this._firstActiveIndex)
headElement=this._topGapElement;else if(this._headSelection.item>this._lastActiveIndex)
headElement=this._bottomGapElement;headOffset=this._selectionIsBackward?0:1;}
selection.setBaseAndExtent(anchorElement,anchorOffset,headElement,headOffset);}
refresh(){this._observer.disconnect();this._innerRefresh();if(this._stickToBottom)
this._observer.observe(this._contentElement,this._observerConfig);}
_innerRefresh(){if(!this._visibleHeight())
return;if(!this._itemCount){for(let i=0;i<this._renderedItems.length;++i)
this._renderedItems[i].willHide();this._renderedItems=[];this._contentElement.removeChildren();this._topGapElement.style.height='0px';this._bottomGapElement.style.height='0px';this._firstActiveIndex=-1;this._lastActiveIndex=-1;this._updateFocusedItem();return;}
const selection=this.element.getComponentSelection();const shouldRestoreSelection=this._updateSelectionModel(selection);const visibleFrom=this.element.scrollTop;const visibleHeight=this._visibleHeight();const activeHeight=visibleHeight*2;this._rebuildCumulativeHeightsIfNeeded();if(this._stickToBottom){this._firstActiveIndex=Math.max(this._itemCount-Math.ceil(activeHeight/this._provider.minimumRowHeight()),0);this._lastActiveIndex=this._itemCount-1;}else{this._firstActiveIndex=Math.max(this._cumulativeHeights.lowerBound(visibleFrom+1-(activeHeight-visibleHeight)/2),0);this._lastActiveIndex=this._firstActiveIndex+Math.ceil(activeHeight/this._provider.minimumRowHeight())-1;this._lastActiveIndex=Math.min(this._lastActiveIndex,this._itemCount-1);}
const topGapHeight=this._cumulativeHeights[this._firstActiveIndex-1]||0;const bottomGapHeight=this._cumulativeHeights[this._cumulativeHeights.length-1]-this._cumulativeHeights[this._lastActiveIndex];function prepare(){this._topGapElement.style.height=topGapHeight+'px';this._bottomGapElement.style.height=bottomGapHeight+'px';this._topGapElement._active=!!topGapHeight;this._bottomGapElement._active=!!bottomGapHeight;this._contentElement.style.setProperty('height','10000000px');}
this._partialViewportUpdate(prepare.bind(this));this._contentElement.style.removeProperty('height');if(shouldRestoreSelection)
this._restoreSelection(selection);if(this._stickToBottom)
this.element.scrollTop=10000000;}
_partialViewportUpdate(prepare){const itemsToRender=new Set();for(let i=this._firstActiveIndex;i<=this._lastActiveIndex;++i)
itemsToRender.add(this._providerElement(i));const willBeHidden=this._renderedItems.filter(item=>!itemsToRender.has(item));for(let i=0;i<willBeHidden.length;++i)
willBeHidden[i].willHide();prepare();let hadFocus=false;for(let i=0;i<willBeHidden.length;++i){hadFocus=hadFocus||willBeHidden[i].element().hasFocus();willBeHidden[i].element().remove();}
const wasShown=[];let anchor=this._contentElement.firstChild;for(const viewportElement of itemsToRender){const element=viewportElement.element();if(element!==anchor){const shouldCallWasShown=!element.parentElement;if(shouldCallWasShown)
wasShown.push(viewportElement);this._contentElement.insertBefore(element,anchor);}else{anchor=anchor.nextSibling;}}
for(let i=0;i<wasShown.length;++i)
wasShown[i].wasShown();this._renderedItems=Array.from(itemsToRender);if(hadFocus)
this._contentElement.focus();this._updateFocusedItem();}
_selectedText(){this._updateSelectionModel(this.element.getComponentSelection());if(!this._headSelection||!this._anchorSelection)
return null;let startSelection=null;let endSelection=null;if(this._selectionIsBackward){startSelection=this._headSelection;endSelection=this._anchorSelection;}else{startSelection=this._anchorSelection;endSelection=this._headSelection;}
const textLines=[];for(let i=startSelection.item;i<=endSelection.item;++i){const element=this._providerElement(i).element();const lineContent=element.childTextNodes().map(Components.Linkifier.untruncatedNodeText).join('');textLines.push(lineContent);}
const endSelectionElement=this._providerElement(endSelection.item).element();if(endSelection.node&&endSelection.node.isSelfOrDescendant(endSelectionElement)){const itemTextOffset=this._textOffsetInNode(endSelectionElement,endSelection.node,endSelection.offset);textLines[textLines.length-1]=textLines.peekLast().substring(0,itemTextOffset);}
const startSelectionElement=this._providerElement(startSelection.item).element();if(startSelection.node&&startSelection.node.isSelfOrDescendant(startSelectionElement)){const itemTextOffset=this._textOffsetInNode(startSelectionElement,startSelection.node,startSelection.offset);textLines[0]=textLines[0].substring(itemTextOffset);}
return textLines.join('\n');}
_textOffsetInNode(itemElement,selectionNode,offset){if(selectionNode.nodeType!==Node.TEXT_NODE){if(offset<selectionNode.childNodes.length){selectionNode=(selectionNode.childNodes.item(offset));offset=0;}else{offset=selectionNode.textContent.length;}}
let chars=0;let node=itemElement;while((node=node.traverseNextNode(itemElement))&&node!==selectionNode){if(node.nodeType!==Node.TEXT_NODE||node.parentElement.nodeName==='STYLE'||node.parentElement.nodeName==='SCRIPT')
continue;chars+=Components.Linkifier.untruncatedNodeText(node).length;}
const untruncatedContainerLength=Components.Linkifier.untruncatedNodeText(selectionNode).length;if(offset>0&&untruncatedContainerLength!==selectionNode.textContent.length)
offset=untruncatedContainerLength;return chars+offset;}
_onScroll(event){this.refresh();}
firstVisibleIndex(){if(!this._cumulativeHeights.length)
return-1;this._rebuildCumulativeHeightsIfNeeded();return this._cumulativeHeights.lowerBound(this.element.scrollTop+1);}
lastVisibleIndex(){if(!this._cumulativeHeights.length)
return-1;this._rebuildCumulativeHeightsIfNeeded();const scrollBottom=this.element.scrollTop+this.element.clientHeight;const right=this._itemCount-1;return this._cumulativeHeights.lowerBound(scrollBottom,undefined,undefined,right);}
renderedElementAt(index){if(index===-1||index<this._firstActiveIndex||index>this._lastActiveIndex)
return null;return this._renderedItems[index-this._firstActiveIndex].element();}
scrollItemIntoView(index,makeLast){const firstVisibleIndex=this.firstVisibleIndex();const lastVisibleIndex=this.lastVisibleIndex();if(index>firstVisibleIndex&&index<lastVisibleIndex)
return;if(index===lastVisibleIndex&&this._cumulativeHeights[index]<=this.element.scrollTop+this._visibleHeight())
return;if(makeLast)
this.forceScrollItemToBeLast(index);else if(index<=firstVisibleIndex)
this.forceScrollItemToBeFirst(index);else if(index>=lastVisibleIndex)
this.forceScrollItemToBeLast(index);}
forceScrollItemToBeFirst(index){console.assert(index>=0&&index<this._itemCount,'Cannot scroll item at invalid index');this.setStickToBottom(false);this._rebuildCumulativeHeightsIfNeeded();this.element.scrollTop=index>0?this._cumulativeHeights[index-1]:0;if(this.element.isScrolledToBottom())
this.setStickToBottom(true);this.refresh();this.renderedElementAt(index).scrollIntoView(true);}
forceScrollItemToBeLast(index){console.assert(index>=0&&index<this._itemCount,'Cannot scroll item at invalid index');this.setStickToBottom(false);this._rebuildCumulativeHeightsIfNeeded();this.element.scrollTop=this._cumulativeHeights[index]-this._visibleHeight();if(this.element.isScrolledToBottom())
this.setStickToBottom(true);this.refresh();this.renderedElementAt(index).scrollIntoView(false);}
_visibleHeight(){return this.element.offsetHeight;}};Console.ConsoleViewportProvider=function(){};Console.ConsoleViewportProvider.prototype={fastHeight(index){return 0;},itemCount(){return 0;},minimumRowHeight(){return 0;},itemElement(index){return null;}};Console.ConsoleViewportElement=function(){};Console.ConsoleViewportElement.prototype={willHide(){},wasShown(){},element(){},};;Console.ConsoleViewMessage=class{constructor(consoleMessage,linkifier,badgePool,nestingLevel,onResize){this._message=consoleMessage;this._linkifier=linkifier;this._badgePool=badgePool;this._repeatCount=1;this._closeGroupDecorationCount=0;this._nestingLevel=nestingLevel;this._selectableChildren=[];this._messageResized=onResize;this._dataGrid=null;this._previewFormatter=new ObjectUI.RemoteObjectPreviewFormatter();this._searchRegex=null;this._messageLevelIcon=null;this._traceExpanded=false;this._expandTrace=null;}
element(){return this.toMessageElement();}
wasShown(){if(this._dataGrid)
this._dataGrid.updateWidths();this._isVisible=true;}
onResize(){if(!this._isVisible)
return;if(this._dataGrid)
this._dataGrid.onResize();}
willHide(){this._isVisible=false;this._cachedHeight=this.element().offsetHeight;}
fastHeight(){if(this._cachedHeight)
return this._cachedHeight;const defaultConsoleRowHeight=19;if(this._message.type===SDK.ConsoleMessage.MessageType.Table){const table=this._message.parameters[0];if(table&&table.preview)
return defaultConsoleRowHeight*table.preview.properties.length;}
return defaultConsoleRowHeight;}
consoleMessage(){return this._message;}
_buildTableMessage(){const formattedMessage=createElementWithClass('span','source-code');this._anchorElement=this._buildMessageAnchor();if(this._anchorElement)
formattedMessage.appendChild(this._anchorElement);const badgeElement=this._buildMessageBadge();if(badgeElement)
formattedMessage.appendChild(badgeElement);let table=this._message.parameters&&this._message.parameters.length?this._message.parameters[0]:null;if(table)
table=this._parameterToRemoteObject(table);if(!table||!table.preview)
return this._buildMessage();const rawValueColumnSymbol=Symbol('rawValueColumn');const columnNames=[];const preview=table.preview;const rows=[];for(let i=0;i<preview.properties.length;++i){const rowProperty=preview.properties[i];let rowSubProperties;if(rowProperty.valuePreview)
rowSubProperties=rowProperty.valuePreview.properties;else if(rowProperty.value)
rowSubProperties=[{name:rawValueColumnSymbol,type:rowProperty.type,value:rowProperty.value}];else
continue;const rowValue={};const maxColumnsToRender=20;for(let j=0;j<rowSubProperties.length;++j){const cellProperty=rowSubProperties[j];let columnRendered=columnNames.indexOf(cellProperty.name)!==-1;if(!columnRendered){if(columnNames.length===maxColumnsToRender)
continue;columnRendered=true;columnNames.push(cellProperty.name);}
if(columnRendered){const cellElement=this._renderPropertyPreviewOrAccessor(table,[rowProperty,cellProperty]);cellElement.classList.add('console-message-nowrap-below');rowValue[cellProperty.name]=cellElement;}}
rows.push([rowProperty.name,rowValue]);}
const flatValues=[];for(let i=0;i<rows.length;++i){const rowName=rows[i][0];const rowValue=rows[i][1];flatValues.push(rowName);for(let j=0;j<columnNames.length;++j)
flatValues.push(rowValue[columnNames[j]]);}
columnNames.unshift(Common.UIString('(index)'));const columnDisplayNames=columnNames.map(name=>name===rawValueColumnSymbol?Common.UIString('Value'):name);if(flatValues.length){this._dataGrid=DataGrid.SortableDataGrid.create(columnDisplayNames,flatValues);this._dataGrid.setStriped(true);const formattedResult=createElementWithClass('span','console-message-text');const tableElement=formattedResult.createChild('div','console-message-formatted-table');const dataGridContainer=tableElement.createChild('span');tableElement.appendChild(this._formatParameter(table,true,false));dataGridContainer.appendChild(this._dataGrid.element);formattedMessage.appendChild(formattedResult);this._dataGrid.renderInline();}
return formattedMessage;}
_buildMessage(){let messageElement;let messageText=this._message.messageText;if(this._message.source===SDK.ConsoleMessage.MessageSource.ConsoleAPI){switch(this._message.type){case SDK.ConsoleMessage.MessageType.Trace:messageElement=this._format(this._message.parameters||['console.trace']);break;case SDK.ConsoleMessage.MessageType.Clear:messageElement=createElementWithClass('span','console-info');if(Common.moduleSetting('preserveConsoleLog').get())
messageElement.textContent=Common.UIString('console.clear() was prevented due to \'Preserve log\'');else
messageElement.textContent=Common.UIString('Console was cleared');messageElement.title=ls`Clear all messages with ${UI.shortcutRegistry.shortcutTitleForAction('console.clear')}`;break;case SDK.ConsoleMessage.MessageType.Dir:{const obj=this._message.parameters?this._message.parameters[0]:undefined;const args=['%O',obj];messageElement=this._format(args);break;}
case SDK.ConsoleMessage.MessageType.Profile:case SDK.ConsoleMessage.MessageType.ProfileEnd:messageElement=this._format([messageText]);break;case SDK.ConsoleMessage.MessageType.Assert:this._messagePrefix=ls`Assertion failed: `;default:{if(this._message.parameters&&this._message.parameters.length===1&&this._message.parameters[0].type==='string')
messageElement=this._tryFormatAsError((this._message.parameters[0].value));const args=this._message.parameters||[messageText];messageElement=messageElement||this._format(args);}}}else{if(this._message.source===SDK.ConsoleMessage.MessageSource.Network){messageElement=this._formatAsNetworkRequest()||this._format([messageText]);}else{const messageInParameters=this._message.parameters&&messageText===(this._message.parameters[0]);if(this._message.source===SDK.ConsoleMessage.MessageSource.Violation)
messageText=Common.UIString('[Violation] %s',messageText);else if(this._message.source===SDK.ConsoleMessage.MessageSource.Intervention)
messageText=Common.UIString('[Intervention] %s',messageText);else if(this._message.source===SDK.ConsoleMessage.MessageSource.Deprecation)
messageText=Common.UIString('[Deprecation] %s',messageText);const args=this._message.parameters||[messageText];if(messageInParameters)
args[0]=messageText;messageElement=this._format(args);}}
messageElement.classList.add('console-message-text');const formattedMessage=createElementWithClass('span','source-code');this._anchorElement=this._buildMessageAnchor();if(this._anchorElement)
formattedMessage.appendChild(this._anchorElement);const badgeElement=this._buildMessageBadge();if(badgeElement)
formattedMessage.appendChild(badgeElement);formattedMessage.appendChild(messageElement);return formattedMessage;}
_formatAsNetworkRequest(){const request=SDK.NetworkLog.requestForConsoleMessage(this._message);if(!request)
return null;const messageElement=createElement('span');if(this._message.level===SDK.ConsoleMessage.MessageLevel.Error){messageElement.createTextChild(request.requestMethod+' ');const linkElement=Components.Linkifier.linkifyRevealable(request,request.url(),request.url());linkElement.tabIndex=-1;this._selectableChildren.push({element:linkElement,forceSelect:()=>linkElement.focus()});messageElement.appendChild(linkElement);if(request.failed)
messageElement.createTextChildren(' ',request.localizedFailDescription);if(request.statusCode!==0)
messageElement.createTextChildren(' ',String(request.statusCode));if(request.statusText)
messageElement.createTextChildren(' (',request.statusText,')');}else{const messageText=this._message.messageText;const fragment=this._linkifyWithCustomLinkifier(messageText,(text,url,lineNumber,columnNumber)=>{let linkElement;if(url===request.url()){linkElement=Components.Linkifier.linkifyRevealable((request),url,request.url());}else{linkElement=Components.Linkifier.linkifyURL(url,{text,lineNumber,columnNumber});}
linkElement.tabIndex=-1;this._selectableChildren.push({element:linkElement,forceSelect:()=>linkElement.focus()});return linkElement;});messageElement.appendChild(fragment);}
return messageElement;}
_buildMessageAnchor(){let anchorElement=null;if(this._message.scriptId){anchorElement=this._linkifyScriptId(this._message.scriptId,this._message.url||'',this._message.line,this._message.column);}else if(this._message.stackTrace&&this._message.stackTrace.callFrames.length){anchorElement=this._linkifyStackTraceTopFrame(this._message.stackTrace);}else if(this._message.url&&this._message.url!=='undefined'){anchorElement=this._linkifyLocation(this._message.url,this._message.line,this._message.column);}
if(anchorElement){const anchorWrapperElement=createElementWithClass('span','console-message-anchor');anchorWrapperElement.appendChild(anchorElement);anchorWrapperElement.createTextChild(' ');return anchorWrapperElement;}
return null;}
_buildMessageBadge(){const badgeElement=this._badgeElement();if(!badgeElement)
return null;badgeElement.classList.add('console-message-badge');return badgeElement;}
_badgeElement(){if(this._message._url)
return this._badgePool.badgeForURL(new Common.ParsedURL(this._message._url));if(this._message.stackTrace){let stackTrace=this._message.stackTrace;while(stackTrace){for(const callFrame of this._message.stackTrace.callFrames){if(callFrame.url)
return this._badgePool.badgeForURL(new Common.ParsedURL(callFrame.url));}
stackTrace=stackTrace.parent;}}
if(!this._message.executionContextId)
return null;const runtimeModel=this._message.runtimeModel();if(!runtimeModel)
return null;const executionContext=runtimeModel.executionContext(this._message.executionContextId);if(!executionContext||!executionContext.frameId)
return null;const resourceTreeModel=executionContext.target().model(SDK.ResourceTreeModel);if(!resourceTreeModel)
return null;const frame=resourceTreeModel.frameForId(executionContext.frameId);if(!frame||!frame.parentFrame)
return null;return this._badgePool.badgeForFrame(frame);}
_buildMessageWithStackTrace(){const toggleElement=createElementWithClass('div','console-message-stack-trace-toggle');const contentElement=toggleElement.createChild('div','console-message-stack-trace-wrapper');const messageElement=this._buildMessage();const icon=UI.Icon.create('smallicon-triangle-right','console-message-expand-icon');const clickableElement=contentElement.createChild('div');clickableElement.appendChild(icon);clickableElement.tabIndex=-1;clickableElement.appendChild(messageElement);const stackTraceElement=contentElement.createChild('div');const stackTracePreview=Components.JSPresentationUtils.buildStackTracePreviewContents(this._message.runtimeModel().target(),this._linkifier,this._message.stackTrace);stackTraceElement.appendChild(stackTracePreview.element);for(const linkElement of stackTracePreview.links){linkElement.tabIndex=-1;this._selectableChildren.push({element:linkElement,forceSelect:()=>linkElement.focus()});}
stackTraceElement.classList.add('hidden');this._expandTrace=expand=>{icon.setIconType(expand?'smallicon-triangle-down':'smallicon-triangle-right');stackTraceElement.classList.toggle('hidden',!expand);this._traceExpanded=expand;};function toggleStackTrace(event){if(UI.isEditing()||contentElement.hasSelection())
return;this._expandTrace(stackTraceElement.classList.contains('hidden'));event.consume();}
clickableElement.addEventListener('click',toggleStackTrace.bind(this),false);if(this._message.type===SDK.ConsoleMessage.MessageType.Trace)
this._expandTrace(true);toggleElement._expandStackTraceForTest=this._expandTrace.bind(this,true);return toggleElement;}
_linkifyLocation(url,lineNumber,columnNumber){if(!this._message.runtimeModel())
return null;return this._linkifier.linkifyScriptLocation(this._message.runtimeModel().target(),null,url,lineNumber,columnNumber);}
_linkifyStackTraceTopFrame(stackTrace){if(!this._message.runtimeModel())
return null;return this._linkifier.linkifyStackTraceTopFrame(this._message.runtimeModel().target(),stackTrace);}
_linkifyScriptId(scriptId,url,lineNumber,columnNumber){if(!this._message.runtimeModel())
return null;return this._linkifier.linkifyScriptLocation(this._message.runtimeModel().target(),scriptId,url,lineNumber,columnNumber);}
_parameterToRemoteObject(parameter){if(parameter instanceof SDK.RemoteObject)
return parameter;const runtimeModel=this._message.runtimeModel();if(!runtimeModel)
return SDK.RemoteObject.fromLocalObject(parameter);if(typeof parameter==='object')
return runtimeModel.createRemoteObject(parameter);return runtimeModel.createRemoteObjectFromPrimitiveValue(parameter);}
_format(rawParameters){const formattedResult=createElement('span');if(this._messagePrefix)
formattedResult.createChild('span').textContent=this._messagePrefix;if(!rawParameters.length)
return formattedResult;let parameters=[];for(let i=0;i<rawParameters.length;++i)
parameters[i]=this._parameterToRemoteObject(rawParameters[i]);const shouldFormatMessage=SDK.RemoteObject.type(((parameters))[0])==='string'&&(this._message.type!==SDK.ConsoleMessage.MessageType.Result||this._message.level===SDK.ConsoleMessage.MessageLevel.Error);if(shouldFormatMessage){const result=this._formatWithSubstitutionString((parameters[0].description),parameters.slice(1),formattedResult);parameters=result.unusedSubstitutions;if(parameters.length)
formattedResult.createTextChild(' ');}
for(let i=0;i<parameters.length;++i){if(shouldFormatMessage&&parameters[i].type==='string')
formattedResult.appendChild(this._linkifyStringAsFragment(parameters[i].description));else
formattedResult.appendChild(this._formatParameter(parameters[i],false,true));if(i<parameters.length-1)
formattedResult.createTextChild(' ');}
return formattedResult;}
_formatParameter(output,forceObjectFormat,includePreview){if(output.customPreview())
return(new ObjectUI.CustomPreviewComponent(output)).element;const type=forceObjectFormat?'object':(output.subtype||output.type);let element;switch(type){case'error':element=this._formatParameterAsError(output);break;case'function':element=this._formatParameterAsFunction(output,includePreview);break;case'array':case'arraybuffer':case'blob':case'dataview':case'generator':case'iterator':case'map':case'object':case'promise':case'proxy':case'set':case'typedarray':case'weakmap':case'weakset':element=this._formatParameterAsObject(output,includePreview);break;case'node':element=output.isNode()?this._formatParameterAsNode(output):this._formatParameterAsObject(output,false);break;case'string':element=this._formatParameterAsString(output);break;case'boolean':case'date':case'null':case'number':case'regexp':case'symbol':case'undefined':case'bigint':element=this._formatParameterAsValue(output);break;default:element=this._formatParameterAsValue(output);console.error('Tried to format remote object of unknown type.');}
element.classList.add('object-value-'+type);element.classList.add('source-code');return element;}
_formatParameterAsValue(obj){const result=createElement('span');const description=obj.description||'';if(description.length>Console.ConsoleViewMessage._MaxTokenizableStringLength)
result.appendChild(UI.createExpandableText(description,Console.ConsoleViewMessage._LongStringVisibleLength));else
result.createTextChild(description);if(obj.objectId)
result.addEventListener('contextmenu',this._contextMenuEventFired.bind(this,obj),false);return result;}
_formatParameterAsObject(obj,includePreview){const titleElement=createElementWithClass('span','console-object');if(includePreview&&obj.preview){titleElement.classList.add('console-object-preview');this._previewFormatter.appendObjectPreview(titleElement,obj.preview,false);}else if(obj.type==='function'){const functionElement=titleElement.createChild('span');ObjectUI.ObjectPropertiesSection.formatObjectAsFunction(obj,functionElement,false);titleElement.classList.add('object-value-function');}else{titleElement.createTextChild(obj.description||'');}
if(!obj.hasChildren||obj.customPreview())
return titleElement;const note=titleElement.createChild('span','object-state-note info-note');if(this._message.type===SDK.ConsoleMessage.MessageType.QueryObjectResult)
note.title=ls`This value will not be collected until console is cleared.`;else
note.title=ls`Value below was evaluated just now.`;const section=new ObjectUI.ObjectPropertiesSection(obj,titleElement,this._linkifier);section.element.classList.add('console-view-object-properties-section');section.enableContextMenu();section.setShowSelectionOnKeyboardFocus(true,true);this._selectableChildren.push(section);section.addEventListener(UI.TreeOutline.Events.ElementAttached,this._messageResized);section.addEventListener(UI.TreeOutline.Events.ElementExpanded,this._messageResized);section.addEventListener(UI.TreeOutline.Events.ElementCollapsed,this._messageResized);return section.element;}
_formatParameterAsFunction(func,includePreview){const result=createElement('span');SDK.RemoteFunction.objectAsFunction(func).targetFunction().then(formatTargetFunction.bind(this));return result;function formatTargetFunction(targetFunction){const functionElement=createElement('span');const promise=ObjectUI.ObjectPropertiesSection.formatObjectAsFunction(targetFunction,functionElement,true,includePreview);result.appendChild(functionElement);if(targetFunction!==func){const note=result.createChild('span','object-info-state-note');note.title=Common.UIString('Function was resolved from bound function.');}
result.addEventListener('contextmenu',this._contextMenuEventFired.bind(this,targetFunction),false);promise.then(()=>this._formattedParameterAsFunctionForTest());}}
_formattedParameterAsFunctionForTest(){}
_contextMenuEventFired(obj,event){const contextMenu=new UI.ContextMenu(event);contextMenu.appendApplicableItems(obj);contextMenu.show();}
_renderPropertyPreviewOrAccessor(object,propertyPath){const property=propertyPath.peekLast();if(property.type==='accessor')
return this._formatAsAccessorProperty(object,propertyPath.map(property=>property.name),false);return this._previewFormatter.renderPropertyPreview(property.type,(property.subtype),property.value);}
_formatParameterAsNode(remoteObject){const result=createElement('span');const domModel=remoteObject.runtimeModel().target().model(SDK.DOMModel);if(!domModel)
return result;domModel.pushObjectAsNodeToFrontend(remoteObject).then(async node=>{if(!node){result.appendChild(this._formatParameterAsObject(remoteObject,false));return;}
const renderResult=await UI.Renderer.render((node));if(renderResult){if(renderResult.tree){this._selectableChildren.push(renderResult.tree);renderResult.tree.addEventListener(UI.TreeOutline.Events.ElementAttached,this._messageResized);renderResult.tree.addEventListener(UI.TreeOutline.Events.ElementExpanded,this._messageResized);renderResult.tree.addEventListener(UI.TreeOutline.Events.ElementCollapsed,this._messageResized);}
result.appendChild(renderResult.node);}else{result.appendChild(this._formatParameterAsObject(remoteObject,false));}
this._formattedParameterAsNodeForTest();});return result;}
_formattedParameterAsNodeForTest(){}
_formatParameterAsString(output){const span=createElement('span');span.appendChild(this._linkifyStringAsFragment(output.description||''));const result=createElement('span');result.createChild('span','object-value-string-quote').textContent='"';result.appendChild(span);result.createChild('span','object-value-string-quote').textContent='"';return result;}
_formatParameterAsError(output){const result=createElement('span');const errorSpan=this._tryFormatAsError(output.description||'');result.appendChild(errorSpan?errorSpan:this._linkifyStringAsFragment(output.description||''));return result;}
_formatAsArrayEntry(output){return this._previewFormatter.renderPropertyPreview(output.type,output.subtype,output.description);}
_formatAsAccessorProperty(object,propertyPath,isArrayEntry){const rootElement=ObjectUI.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(object,propertyPath,onInvokeGetterClick.bind(this));function onInvokeGetterClick(result){const wasThrown=result.wasThrown;const object=result.object;if(!object)
return;rootElement.removeChildren();if(wasThrown){const element=rootElement.createChild('span');element.textContent=Common.UIString('<exception>');element.title=(object.description);}else if(isArrayEntry){rootElement.appendChild(this._formatAsArrayEntry(object));}else{const maxLength=100;const type=object.type;const subtype=object.subtype;let description='';if(type!=='function'&&object.description){if(type==='string'||subtype==='regexp')
description=object.description.trimMiddle(maxLength);else
description=object.description.trimEnd(maxLength);}
rootElement.appendChild(this._previewFormatter.renderPropertyPreview(type,subtype,description));}}
return rootElement;}
_formatWithSubstitutionString(format,parameters,formattedResult){const formatters={};function parameterFormatter(force,includePreview,obj){return this._formatParameter(obj,force,includePreview);}
function stringFormatter(obj){return obj.description;}
function floatFormatter(obj){if(typeof obj.value!=='number')
return'NaN';return obj.value;}
function integerFormatter(obj){if(obj.type==='bigint')
return obj.description;if(typeof obj.value!=='number')
return'NaN';return Math.floor(obj.value);}
function bypassFormatter(obj){return(obj instanceof Node)?obj:'';}
let currentStyle=null;function styleFormatter(obj){currentStyle={};const buffer=createElement('span');buffer.setAttribute('style',obj.description);for(let i=0;i<buffer.style.length;i++){const property=buffer.style[i];if(isWhitelistedProperty(property))
currentStyle[property]=buffer.style[property];}}
function isWhitelistedProperty(property){const prefixes=['background','border','color','font','line','margin','padding','text','-webkit-background','-webkit-border','-webkit-font','-webkit-margin','-webkit-padding','-webkit-text'];for(let i=0;i<prefixes.length;i++){if(property.startsWith(prefixes[i]))
return true;}
return false;}
formatters.o=parameterFormatter.bind(this,false,true);formatters.s=stringFormatter;formatters.f=floatFormatter;formatters.i=integerFormatter;formatters.d=integerFormatter;formatters.c=styleFormatter;formatters.O=parameterFormatter.bind(this,true,false);formatters._=bypassFormatter;function append(a,b){if(b instanceof Node){a.appendChild(b);return a;}
if(typeof b==='undefined')
return a;if(!currentStyle){a.appendChild(this._linkifyStringAsFragment(String(b)));return a;}
const lines=String(b).split('\n');for(let i=0;i<lines.length;i++){const line=lines[i];const lineFragment=this._linkifyStringAsFragment(line);const wrapper=createElement('span');wrapper.style.setProperty('contain','paint');wrapper.style.setProperty('display','inline-block');wrapper.style.setProperty('max-width','100%');wrapper.appendChild(lineFragment);applyCurrentStyle(wrapper);for(const child of wrapper.children){if(child.classList.contains('devtools-link'))
this._applyForcedVisibleStyle(child);}
a.appendChild(wrapper);if(i<lines.length-1)
a.appendChild(createElement('br'));}
return a;}
function applyCurrentStyle(element){for(const key in currentStyle)
element.style[key]=currentStyle[key];}
return String.format(format,parameters,formatters,formattedResult,append.bind(this));}
_applyForcedVisibleStyle(element){element.style.setProperty('-webkit-text-stroke','0','important');element.style.setProperty('text-decoration','underline','important');const themedColor=UI.themeSupport.patchColorText('rgb(33%, 33%, 33%)',UI.ThemeSupport.ColorUsage.Foreground);element.style.setProperty('color',themedColor,'important');let backgroundColor='hsl(0, 0%, 100%)';if(this._message.level===SDK.ConsoleMessage.MessageLevel.Error)
backgroundColor='hsl(0, 100%, 97%)';else if(this._message.level===SDK.ConsoleMessage.MessageLevel.Warning||this._shouldRenderAsWarning())
backgroundColor='hsl(50, 100%, 95%)';const themedBackgroundColor=UI.themeSupport.patchColorText(backgroundColor,UI.ThemeSupport.ColorUsage.Background);element.style.setProperty('background-color',themedBackgroundColor,'important');}
matchesFilterRegex(regexObject){regexObject.lastIndex=0;const contentElement=this.contentElement();const anchorText=this._anchorElement?this._anchorElement.deepTextContent():'';return(anchorText&&regexObject.test(anchorText.trim()))||regexObject.test(contentElement.deepTextContent().slice(anchorText.length));}
matchesFilterText(filter){const text=this.contentElement().deepTextContent();return text.toLowerCase().includes(filter.toLowerCase());}
updateTimestamp(){if(!this._contentElement)
return;if(Common.moduleSetting('consoleTimestampsEnabled').get()){if(!this._timestampElement)
this._timestampElement=createElementWithClass('span','console-timestamp');this._timestampElement.textContent=UI.formatTimestamp(this._message.timestamp,false)+' ';this._timestampElement.title=UI.formatTimestamp(this._message.timestamp,true);this._contentElement.insertBefore(this._timestampElement,this._contentElement.firstChild);}else if(this._timestampElement){this._timestampElement.remove();delete this._timestampElement;}}
nestingLevel(){return this._nestingLevel;}
setInSimilarGroup(inSimilarGroup,isLast){this._inSimilarGroup=inSimilarGroup;this._lastInSimilarGroup=inSimilarGroup&&!!isLast;if(this._similarGroupMarker&&!inSimilarGroup){this._similarGroupMarker.remove();this._similarGroupMarker=null;}else if(this._element&&!this._similarGroupMarker&&inSimilarGroup){this._similarGroupMarker=createElementWithClass('div','nesting-level-marker');this._element.insertBefore(this._similarGroupMarker,this._element.firstChild);this._similarGroupMarker.classList.toggle('group-closed',this._lastInSimilarGroup);}}
isLastInSimilarGroup(){return this._inSimilarGroup&&this._lastInSimilarGroup;}
resetCloseGroupDecorationCount(){if(!this._closeGroupDecorationCount)
return;this._closeGroupDecorationCount=0;this._updateCloseGroupDecorations();}
incrementCloseGroupDecorationCount(){++this._closeGroupDecorationCount;this._updateCloseGroupDecorations();}
_updateCloseGroupDecorations(){if(!this._nestingLevelMarkers)
return;for(let i=0,n=this._nestingLevelMarkers.length;i<n;++i){const marker=this._nestingLevelMarkers[i];marker.classList.toggle('group-closed',n-i<=this._closeGroupDecorationCount);}}
_focusedChildIndex(){if(!this._selectableChildren.length)
return-1;return this._selectableChildren.findIndex(child=>child.element.hasFocus());}
_onKeyDown(event){if(UI.isEditing()||!this._element.hasFocus()||this._element.hasSelection())
return;if(this.maybeHandleOnKeyDown(event))
event.consume(true);}
maybeHandleOnKeyDown(event){const focusedChildIndex=this._focusedChildIndex();const isWrapperFocused=focusedChildIndex===-1;if(this._expandTrace&&isWrapperFocused){if((event.key==='ArrowLeft'&&this._traceExpanded)||(event.key==='ArrowRight'&&!this._traceExpanded)){this._expandTrace(!this._traceExpanded);return true;}}
if(!this._selectableChildren.length)
return false;if(event.key==='ArrowLeft'){this._element.focus();return true;}
if(event.key==='ArrowRight'){if(isWrapperFocused&&this._selectNearestVisibleChild(0))
return true;}
if(event.key==='ArrowUp'){const firstVisibleChild=this._nearestVisibleChild(0);if(this._selectableChildren[focusedChildIndex]===firstVisibleChild&&firstVisibleChild){this._element.focus();return true;}else if(this._selectNearestVisibleChild(focusedChildIndex-1,true)){return true;}}
if(event.key==='ArrowDown'){if(isWrapperFocused&&this._selectNearestVisibleChild(0))
return true;if(!isWrapperFocused&&this._selectNearestVisibleChild(focusedChildIndex+1))
return true;}
return false;}
_selectNearestVisibleChild(fromIndex,backwards){const nearestChild=this._nearestVisibleChild(fromIndex,backwards);if(nearestChild){nearestChild.forceSelect();return true;}
return false;}
_nearestVisibleChild(fromIndex,backwards){const childCount=this._selectableChildren.length;if(fromIndex<0||fromIndex>=childCount)
return null;const direction=backwards?-1:1;let index=fromIndex;while(!this._selectableChildren[index].element.offsetParent){index+=direction;if(index<0||index>=childCount)
return null;}
return this._selectableChildren[index];}
focusLastChildOrSelf(){if(this._element&&!this._selectNearestVisibleChild(this._selectableChildren.length-1,true))
this._element.focus();}
contentElement(){if(this._contentElement)
return this._contentElement;const contentElement=createElementWithClass('div','console-message');if(this._messageLevelIcon)
contentElement.appendChild(this._messageLevelIcon);this._contentElement=contentElement;let formattedMessage;const shouldIncludeTrace=!!this._message.stackTrace&&(this._message.source===SDK.ConsoleMessage.MessageSource.Network||this._message.source===SDK.ConsoleMessage.MessageSource.Violation||this._message.level===SDK.ConsoleMessage.MessageLevel.Error||this._message.level===SDK.ConsoleMessage.MessageLevel.Warning||this._message.type===SDK.ConsoleMessage.MessageType.Trace);if(this._message.runtimeModel()&&shouldIncludeTrace)
formattedMessage=this._buildMessageWithStackTrace();else if(this._message.type===SDK.ConsoleMessage.MessageType.Table)
formattedMessage=this._buildTableMessage();else
formattedMessage=this._buildMessage();contentElement.appendChild(formattedMessage);this.updateTimestamp();return this._contentElement;}
toMessageElement(){if(this._element)
return this._element;this._element=createElement('div');this._element.tabIndex=-1;this._element.addEventListener('keydown',this._onKeyDown.bind(this));this.updateMessageElement();return this._element;}
updateMessageElement(){if(!this._element)
return;this._element.className='console-message-wrapper';this._element.removeChildren();if(this._message.isGroupStartMessage())
this._element.classList.add('console-group-title');if(this._message.source===SDK.ConsoleMessage.MessageSource.ConsoleAPI)
this._element.classList.add('console-from-api');if(this._inSimilarGroup){this._similarGroupMarker=this._element.createChild('div','nesting-level-marker');this._similarGroupMarker.classList.toggle('group-closed',this._lastInSimilarGroup);}
this._nestingLevelMarkers=[];for(let i=0;i<this._nestingLevel;++i)
this._nestingLevelMarkers.push(this._element.createChild('div','nesting-level-marker'));this._updateCloseGroupDecorations();this._element.message=this;switch(this._message.level){case SDK.ConsoleMessage.MessageLevel.Verbose:this._element.classList.add('console-verbose-level');break;case SDK.ConsoleMessage.MessageLevel.Info:this._element.classList.add('console-info-level');if(this._message.type===SDK.ConsoleMessage.MessageType.System)
this._element.classList.add('console-system-type');break;case SDK.ConsoleMessage.MessageLevel.Warning:this._element.classList.add('console-warning-level');break;case SDK.ConsoleMessage.MessageLevel.Error:this._element.classList.add('console-error-level');break;}
this._updateMessageLevelIcon();if(this._shouldRenderAsWarning())
this._element.classList.add('console-warning-level');this._element.appendChild(this.contentElement());if(this._repeatCount>1)
this._showRepeatCountElement();}
_shouldRenderAsWarning(){return(this._message.level===SDK.ConsoleMessage.MessageLevel.Verbose||this._message.level===SDK.ConsoleMessage.MessageLevel.Info)&&(this._message.source===SDK.ConsoleMessage.MessageSource.Violation||this._message.source===SDK.ConsoleMessage.MessageSource.Deprecation||this._message.source===SDK.ConsoleMessage.MessageSource.Intervention||this._message.source===SDK.ConsoleMessage.MessageSource.Recommendation);}
_updateMessageLevelIcon(){let iconType='';let accessibleName='';if(this._message.level===SDK.ConsoleMessage.MessageLevel.Warning){iconType='smallicon-warning';accessibleName=ls`Warning`;}else if(this._message.level===SDK.ConsoleMessage.MessageLevel.Error){iconType='smallicon-error';accessibleName=ls`Error`;}
if(!iconType&&!this._messageLevelIcon)
return;if(iconType&&!this._messageLevelIcon){this._messageLevelIcon=UI.Icon.create('','message-level-icon');if(this._contentElement)
this._contentElement.insertBefore(this._messageLevelIcon,this._contentElement.firstChild);}
this._messageLevelIcon.setIconType(iconType);UI.ARIAUtils.setAccessibleName(this._messageLevelIcon,accessibleName);}
repeatCount(){return this._repeatCount||1;}
resetIncrementRepeatCount(){this._repeatCount=1;if(!this._repeatCountElement)
return;this._repeatCountElement.remove();if(this._contentElement)
this._contentElement.classList.remove('repeated-message');delete this._repeatCountElement;}
incrementRepeatCount(){this._repeatCount++;this._showRepeatCountElement();}
setRepeatCount(repeatCount){this._repeatCount=repeatCount;this._showRepeatCountElement();}
_showRepeatCountElement(){if(!this._element)
return;if(!this._repeatCountElement){this._repeatCountElement=createElementWithClass('span','console-message-repeat-count','dt-small-bubble');switch(this._message.level){case SDK.ConsoleMessage.MessageLevel.Warning:this._repeatCountElement.type='warning';break;case SDK.ConsoleMessage.MessageLevel.Error:this._repeatCountElement.type='error';break;case SDK.ConsoleMessage.MessageLevel.Verbose:this._repeatCountElement.type='verbose';break;default:this._repeatCountElement.type='info';}
if(this._shouldRenderAsWarning())
this._repeatCountElement.type='warning';this._element.insertBefore(this._repeatCountElement,this._contentElement);this._contentElement.classList.add('repeated-message');}
this._repeatCountElement.textContent=this._repeatCount;let accessibleName=ls`Repeat ${this._repeatCount}`;if(this._message.level===SDK.ConsoleMessage.MessageLevel.Warning)
accessibleName=ls`Warning ${accessibleName}`;else if(this._message.level===SDK.ConsoleMessage.MessageLevel.Error)
accessibleName=ls`Error ${accessibleName}`;UI.ARIAUtils.setAccessibleName(this._repeatCountElement,accessibleName);}
get text(){return this._message.messageText;}
toExportString(){const lines=[];const nodes=this.contentElement().childTextNodes();const messageContent=nodes.map(Components.Linkifier.untruncatedNodeText).join('');for(let i=0;i<this.repeatCount();++i)
lines.push(messageContent);return lines.join('\n');}
setSearchRegex(regex){if(this._searchHiglightNodeChanges&&this._searchHiglightNodeChanges.length)
UI.revertDomChanges(this._searchHiglightNodeChanges);this._searchRegex=regex;this._searchHighlightNodes=[];this._searchHiglightNodeChanges=[];if(!this._searchRegex)
return;const text=this.contentElement().deepTextContent();let match;this._searchRegex.lastIndex=0;const sourceRanges=[];while((match=this._searchRegex.exec(text))&&match[0])
sourceRanges.push(new TextUtils.SourceRange(match.index,match[0].length));if(sourceRanges.length){this._searchHighlightNodes=UI.highlightSearchResults(this.contentElement(),sourceRanges,this._searchHiglightNodeChanges);}}
searchRegex(){return this._searchRegex;}
searchCount(){return this._searchHighlightNodes.length;}
searchHighlightNode(index){return this._searchHighlightNodes[index];}
_tryFormatAsError(string){function startsWith(prefix){return string.startsWith(prefix);}
const errorPrefixes=['EvalError','ReferenceError','SyntaxError','TypeError','RangeError','Error','URIError'];if(!this._message.runtimeModel()||!errorPrefixes.some(startsWith))
return null;const debuggerModel=this._message.runtimeModel().debuggerModel();const baseURL=this._message.runtimeModel().target().inspectedURL();const lines=string.split('\n');const links=[];let position=0;for(let i=0;i<lines.length;++i){position+=i>0?lines[i-1].length+1:0;const isCallFrameLine=/^\s*at\s/.test(lines[i]);if(!isCallFrameLine&&links.length)
return null;if(!isCallFrameLine)
continue;let openBracketIndex=-1;let closeBracketIndex=-1;const match=/\([^\)\(]+\)/.exec(lines[i]);if(match){openBracketIndex=match.index;closeBracketIndex=match.index+match[0].length-1;}
const hasOpenBracket=openBracketIndex!==-1;const left=hasOpenBracket?openBracketIndex+1:lines[i].indexOf('at')+3;const right=hasOpenBracket?closeBracketIndex:lines[i].length;const linkCandidate=lines[i].substring(left,right);const splitResult=Common.ParsedURL.splitLineAndColumn(linkCandidate);if(!splitResult)
return null;if(splitResult.url==='<anonymous>')
continue;let url=parseOrScriptMatch(splitResult.url);if(!url&&Common.ParsedURL.isRelativeURL(splitResult.url))
url=parseOrScriptMatch(Common.ParsedURL.completeURL(baseURL,splitResult.url));if(!url)
return null;links.push({url:url,positionLeft:position+left,positionRight:position+right,lineNumber:splitResult.lineNumber,columnNumber:splitResult.columnNumber});}
if(!links.length)
return null;const formattedResult=createElement('span');let start=0;for(let i=0;i<links.length;++i){formattedResult.appendChild(this._linkifyStringAsFragment(string.substring(start,links[i].positionLeft)));const scriptLocationLink=this._linkifier.linkifyScriptLocation(debuggerModel.target(),null,links[i].url,links[i].lineNumber,links[i].columnNumber);scriptLocationLink.tabIndex=-1;this._selectableChildren.push({element:scriptLocationLink,forceSelect:()=>scriptLocationLink.focus()});formattedResult.appendChild(scriptLocationLink);start=links[i].positionRight;}
if(start!==string.length)
formattedResult.appendChild(this._linkifyStringAsFragment(string.substring(start)));return formattedResult;function parseOrScriptMatch(url){if(!url)
return null;const parsedURL=url.asParsedURL();if(parsedURL)
return parsedURL.url;if(debuggerModel.scriptsForSourceURL(url).length)
return url;return null;}}
_linkifyWithCustomLinkifier(string,linkifier){if(string.length>Console.ConsoleViewMessage._MaxTokenizableStringLength)
return UI.createExpandableText(string,Console.ConsoleViewMessage._LongStringVisibleLength);const container=createDocumentFragment();const tokens=Console.ConsoleViewMessage._tokenizeMessageText(string);for(const token of tokens){if(!token.text)
continue;switch(token.type){case'url':{const realURL=(token.text.startsWith('www.')?'http://'+token.text:token.text);const splitResult=Common.ParsedURL.splitLineAndColumn(realURL);let linkNode;if(splitResult)
linkNode=linkifier(token.text,splitResult.url,splitResult.lineNumber,splitResult.columnNumber);else
linkNode=linkifier(token.text,token.value);container.appendChild(linkNode);break;}
default:container.appendChild(createTextNode(token.text));break;}}
return container;}
_linkifyStringAsFragment(string){return this._linkifyWithCustomLinkifier(string,(text,url,lineNumber,columnNumber)=>{const linkElement=Components.Linkifier.linkifyURL(url,{text,lineNumber,columnNumber});linkElement.tabIndex=-1;this._selectableChildren.push({element:linkElement,forceSelect:()=>linkElement.focus()});return linkElement;});}
static _tokenizeMessageText(string){if(!Console.ConsoleViewMessage._tokenizerRegexes){const controlCodes='\\u0000-\\u0020\\u007f-\\u009f';const linkStringRegex=new RegExp('(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\\/\\/|data:|www\\.)[^\\s'+controlCodes+'"]{2,}[^\\s'+controlCodes+'"\')}\\],:;.!?]','u');const pathLineRegex=/(?:\/[\w\.-]*)+\:[\d]+/;const timeRegex=/took [\d]+ms/;const eventRegex=/'\w+' event/;const milestoneRegex=/\sM[6-7]\d/;const autofillRegex=/\(suggested: \"[\w-]+\"\)/;const handlers=new Map();handlers.set(linkStringRegex,'url');handlers.set(pathLineRegex,'url');handlers.set(timeRegex,'time');handlers.set(eventRegex,'event');handlers.set(milestoneRegex,'milestone');handlers.set(autofillRegex,'autofill');Console.ConsoleViewMessage._tokenizerRegexes=Array.from(handlers.keys());Console.ConsoleViewMessage._tokenizerTypes=Array.from(handlers.values());}
if(string.length>Console.ConsoleViewMessage._MaxTokenizableStringLength)
return[{text:string,type:undefined}];const results=TextUtils.TextUtils.splitStringByRegexes(string,Console.ConsoleViewMessage._tokenizerRegexes);return results.map(result=>({text:result.value,type:Console.ConsoleViewMessage._tokenizerTypes[result.regexIndex]}));}
groupKey(){if(!this._groupKey)
this._groupKey=this._message.groupCategoryKey()+':'+this.groupTitle();return this._groupKey;}
groupTitle(){const tokens=Console.ConsoleViewMessage._tokenizeMessageText(this._message.messageText);const result=tokens.reduce((acc,token)=>{let text=token.text;if(token.type==='url')
text=Common.UIString('<URL>');else if(token.type==='time')
text=Common.UIString('took <N>ms');else if(token.type==='event')
text=Common.UIString('<some> event');else if(token.type==='milestone')
text=Common.UIString(' M<XX>');else if(token.type==='autofill')
text=Common.UIString('<attribute>');return acc+text;},'');return result.replace(/[%]o/g,'');}};Console.ConsoleGroupViewMessage=class extends Console.ConsoleViewMessage{constructor(consoleMessage,linkifier,badgePool,nestingLevel,onToggle,onResize){console.assert(consoleMessage.isGroupStartMessage());super(consoleMessage,linkifier,badgePool,nestingLevel,onResize);this._collapsed=consoleMessage.type===SDK.ConsoleMessage.MessageType.StartGroupCollapsed;this._expandGroupIcon=null;this._onToggle=onToggle;}
_setCollapsed(collapsed){this._collapsed=collapsed;if(this._expandGroupIcon)
this._expandGroupIcon.setIconType(this._collapsed?'smallicon-triangle-right':'smallicon-triangle-down');this._onToggle.call(null);}
collapsed(){return this._collapsed;}
maybeHandleOnKeyDown(event){const focusedChildIndex=this._focusedChildIndex();if(focusedChildIndex===-1){if((event.key==='ArrowLeft'&&!this._collapsed)||(event.key==='ArrowRight'&&this._collapsed)){this._setCollapsed(!this._collapsed);return true;}}
return super.maybeHandleOnKeyDown(event);}
toMessageElement(){if(!this._element){super.toMessageElement();const iconType=this._collapsed?'smallicon-triangle-right':'smallicon-triangle-down';this._expandGroupIcon=UI.Icon.create(iconType,'expand-group-icon');this._contentElement.tabIndex=-1;if(this._repeatCountElement)
this._repeatCountElement.insertBefore(this._expandGroupIcon,this._repeatCountElement.firstChild);else
this._element.insertBefore(this._expandGroupIcon,this._contentElement);this._element.addEventListener('click',()=>this._setCollapsed(!this._collapsed));}
return this._element;}
_showRepeatCountElement(){super._showRepeatCountElement();if(this._repeatCountElement&&this._expandGroupIcon)
this._repeatCountElement.insertBefore(this._expandGroupIcon,this._repeatCountElement.firstChild);}};Console.ConsoleViewMessage.MaxLengthForLinks=40;Console.ConsoleViewMessage._MaxTokenizableStringLength=10000;Console.ConsoleViewMessage._LongStringVisibleLength=5000;;Console.ConsolePrompt=class extends UI.Widget{constructor(){super();this.registerRequiredCSS('console/consolePrompt.css');this._addCompletionsFromHistory=true;this._history=new Console.ConsoleHistoryManager();this._initialText='';this._editor=null;this._eagerPreviewElement=createElementWithClass('div','console-eager-preview');this._textChangeThrottler=new Common.Throttler(150);this._formatter=new ObjectUI.RemoteObjectPreviewFormatter();this._requestPreviewBound=this._requestPreview.bind(this);this._innerPreviewElement=this._eagerPreviewElement.createChild('div','console-eager-inner-preview');this._eagerPreviewElement.appendChild(UI.Icon.create('smallicon-command-result','preview-result-icon'));const editorContainerElement=this.element.createChild('div','console-prompt-editor-container');this.element.appendChild(this._eagerPreviewElement);this._promptIcon=UI.Icon.create('smallicon-text-prompt','console-prompt-icon');this.element.appendChild(this._promptIcon);this._iconThrottler=new Common.Throttler(0);this._eagerEvalSetting=Common.settings.moduleSetting('consoleEagerEval');this._eagerEvalSetting.addChangeListener(this._eagerSettingChanged.bind(this));this._eagerPreviewElement.classList.toggle('hidden',!this._eagerEvalSetting.get());this.element.tabIndex=0;this._previewRequestForTest=null;this._defaultAutocompleteConfig=null;this._highlightingNode=false;self.runtime.extension(UI.TextEditorFactory).instance().then(gotFactory.bind(this));function gotFactory(factory){this._editor=factory.createEditor({lineNumbers:false,lineWrapping:true,mimeType:'javascript',autoHeight:true});this._defaultAutocompleteConfig=ObjectUI.JavaScriptAutocompleteConfig.createConfigForEditor(this._editor);this._editor.configureAutocomplete(Object.assign({},this._defaultAutocompleteConfig,{suggestionsCallback:this._wordsWithQuery.bind(this),anchorBehavior:UI.GlassPane.AnchorBehavior.PreferTop}));this._editor.widget().element.addEventListener('keydown',this._editorKeyDown.bind(this),true);this._editor.widget().show(editorContainerElement);this._editor.addEventListener(UI.TextEditor.Events.CursorChanged,this._updatePromptIcon,this);this._editor.addEventListener(UI.TextEditor.Events.TextChanged,this._onTextChanged,this);this._editor.addEventListener(UI.TextEditor.Events.SuggestionChanged,this._onTextChanged,this);this.setText(this._initialText);delete this._initialText;if(this.hasFocus())
this.focus();this.element.removeAttribute('tabindex');this._editor.widget().element.tabIndex=-1;this._editorSetForTest();Host.userMetrics.panelLoaded('console','DevTools.Launch.Console');}}
_eagerSettingChanged(){const enabled=this._eagerEvalSetting.get();this._eagerPreviewElement.classList.toggle('hidden',!enabled);if(enabled)
this._requestPreview();}
belowEditorElement(){return this._eagerPreviewElement;}
_onTextChanged(){if(this._eagerEvalSetting.get()){const asSoonAsPossible=!this._editor.textWithCurrentSuggestion();this._previewRequestForTest=this._textChangeThrottler.schedule(this._requestPreviewBound,asSoonAsPossible);}
this._updatePromptIcon();this.dispatchEventToListeners(Console.ConsolePrompt.Events.TextChanged);}
async _requestPreview(){const text=this._editor.textWithCurrentSuggestion().trim();const executionContext=UI.context.flavor(SDK.ExecutionContext);const{preview,result}=await ObjectUI.JavaScriptREPL.evaluateAndBuildPreview(text,true,500);this._innerPreviewElement.removeChildren();if(preview.deepTextContent()!==this._editor.textWithCurrentSuggestion().trim())
this._innerPreviewElement.appendChild(preview);if(result&&result.object&&result.object.subtype==='node'){this._highlightingNode=true;SDK.OverlayModel.highlightObjectAsDOMNode(result.object);}else if(this._highlightingNode){this._highlightingNode=false;SDK.OverlayModel.hideDOMNodeHighlight();}
if(result)
executionContext.runtimeModel.releaseEvaluationResult(result);}
willHide(){if(this._highlightingNode){this._highlightingNode=false;SDK.OverlayModel.hideDOMNodeHighlight();}}
history(){return this._history;}
clearAutocomplete(){if(this._editor)
this._editor.clearAutocomplete();}
_isCaretAtEndOfPrompt(){return!!this._editor&&this._editor.selection().collapseToEnd().equal(this._editor.fullRange().collapseToEnd());}
moveCaretToEndOfPrompt(){if(this._editor)
this._editor.setSelection(TextUtils.TextRange.createFromLocation(Infinity,Infinity));}
setText(text){if(this._editor)
this._editor.setText(text);else
this._initialText=text;this.dispatchEventToListeners(Console.ConsolePrompt.Events.TextChanged);}
text(){return this._editor?this._editor.text():this._initialText;}
setAddCompletionsFromHistory(value){this._addCompletionsFromHistory=value;}
_editorKeyDown(event){const keyboardEvent=(event);let newText;let isPrevious;const selection=this._editor.selection();const cursorY=this._editor.visualCoordinates(selection.endLine,selection.endColumn).y;switch(keyboardEvent.keyCode){case UI.KeyboardShortcut.Keys.Up.code:const startY=this._editor.visualCoordinates(0,0).y;if(keyboardEvent.shiftKey||!selection.isEmpty()||cursorY!==startY)
break;newText=this._history.previous(this.text());isPrevious=true;break;case UI.KeyboardShortcut.Keys.Down.code:const fullRange=this._editor.fullRange();const endY=this._editor.visualCoordinates(fullRange.endLine,fullRange.endColumn).y;if(keyboardEvent.shiftKey||!selection.isEmpty()||cursorY!==endY)
break;newText=this._history.next();break;case UI.KeyboardShortcut.Keys.P.code:if(Host.isMac()&&keyboardEvent.ctrlKey&&!keyboardEvent.metaKey&&!keyboardEvent.altKey&&!keyboardEvent.shiftKey){newText=this._history.previous(this.text());isPrevious=true;}
break;case UI.KeyboardShortcut.Keys.N.code:if(Host.isMac()&&keyboardEvent.ctrlKey&&!keyboardEvent.metaKey&&!keyboardEvent.altKey&&!keyboardEvent.shiftKey)
newText=this._history.next();break;case UI.KeyboardShortcut.Keys.Enter.code:this._enterKeyPressed(keyboardEvent);break;case UI.KeyboardShortcut.Keys.Tab.code:if(!this.text())
keyboardEvent.consume();break;}
if(newText===undefined)
return;keyboardEvent.consume(true);this.setText(newText);if(isPrevious)
this._editor.setSelection(TextUtils.TextRange.createFromLocation(0,Infinity));else
this.moveCaretToEndOfPrompt();}
async _enterWillEvaluate(){if(!this._isCaretAtEndOfPrompt())
return true;return await ObjectUI.JavaScriptAutocomplete.isExpressionComplete(this.text());}
_updatePromptIcon(){this._iconThrottler.schedule(async()=>{const canComplete=await this._enterWillEvaluate();this._promptIcon.classList.toggle('console-prompt-incomplete',!canComplete);});}
async _enterKeyPressed(event){if(event.altKey||event.ctrlKey||event.shiftKey)
return;event.consume(true);this.element.scrollIntoView();this.clearAutocomplete();const str=this.text();if(!str.length)
return;if(await this._enterWillEvaluate())
await this._appendCommand(str,true);else
this._editor.newlineAndIndent();this._enterProcessedForTest();}
async _appendCommand(text,useCommandLineAPI){this.setText('');const currentExecutionContext=UI.context.flavor(SDK.ExecutionContext);if(currentExecutionContext){const executionContext=currentExecutionContext;const message=SDK.consoleModel.addCommandMessage(executionContext,text);const wrappedResult=await ObjectUI.JavaScriptREPL.preprocessExpression(text);SDK.consoleModel.evaluateCommandInConsole(executionContext,message,wrappedResult.text,useCommandLineAPI,wrappedResult.preprocessed);if(Console.ConsolePanel.instance().isShowing())
Host.userMetrics.actionTaken(Host.UserMetrics.Action.CommandEvaluatedInConsolePanel);}}
_enterProcessedForTest(){}
_historyCompletions(prefix,force){const text=this.text();if(!this._addCompletionsFromHistory||!this._isCaretAtEndOfPrompt()||(!text&&!force))
return[];const result=[];const set=new Set();const data=this._history.historyData();for(let i=data.length-1;i>=0&&result.length<50;--i){const item=data[i];if(!item.startsWith(text))
continue;if(set.has(item))
continue;set.add(item);result.push({text:item.substring(text.length-prefix.length),iconType:'smallicon-text-prompt',isSecondary:true});}
return result;}
focus(){if(this._editor)
this._editor.widget().focus();else
this.element.focus();}
async _wordsWithQuery(queryRange,substituteRange,force){const query=this._editor.text(queryRange);const words=await this._defaultAutocompleteConfig.suggestionsCallback(queryRange,substituteRange,force);const historyWords=this._historyCompletions(query,force);return words.concat(historyWords);}
_editorSetForTest(){}};Console.ConsoleHistoryManager=class{constructor(){this._data=[];this._historyOffset=1;}
historyData(){return this._data;}
setHistoryData(data){this._data=data.slice();this._historyOffset=1;}
pushHistoryItem(text){if(this._uncommittedIsTop){this._data.pop();delete this._uncommittedIsTop;}
this._historyOffset=1;if(text===this._currentHistoryItem())
return;this._data.push(text);}
_pushCurrentText(currentText){if(this._uncommittedIsTop)
this._data.pop();this._uncommittedIsTop=true;this._data.push(currentText);}
previous(currentText){if(this._historyOffset>this._data.length)
return undefined;if(this._historyOffset===1)
this._pushCurrentText(currentText);++this._historyOffset;return this._currentHistoryItem();}
next(){if(this._historyOffset===1)
return undefined;--this._historyOffset;return this._currentHistoryItem();}
_currentHistoryItem(){return this._data[this._data.length-this._historyOffset];}};Console.ConsolePrompt.Events={TextChanged:Symbol('TextChanged')};;Console.ConsoleView=class extends UI.VBox{constructor(){super();this.setMinimumSize(0,35);this.registerRequiredCSS('console/consoleView.css');this.registerRequiredCSS('object_ui/objectValue.css');this._searchableView=new UI.SearchableView(this);this._searchableView.element.classList.add('console-searchable-view');this._searchableView.setPlaceholder(Common.UIString('Find string in logs'));this._searchableView.setMinimalSearchQuerySize(0);this._badgePool=new ProductRegistry.BadgePool();this._sidebar=new Console.ConsoleSidebar(this._badgePool);this._sidebar.addEventListener(Console.ConsoleSidebar.Events.FilterSelected,this._onFilterChanged.bind(this));this._isSidebarOpen=false;this._filter=new Console.ConsoleViewFilter(this._onFilterChanged.bind(this));const consoleToolbarContainer=this.element.createChild('div','console-toolbar-container');this._splitWidget=new UI.SplitWidget(true,false,'console.sidebar.width',100);this._splitWidget.setMainWidget(this._searchableView);this._splitWidget.setSidebarWidget(this._sidebar);this._splitWidget.show(this.element);this._splitWidget.hideSidebar();this._splitWidget.enableShowModeSaving();this._isSidebarOpen=this._splitWidget.showMode()===UI.SplitWidget.ShowMode.Both;if(this._isSidebarOpen)
this._filter._levelMenuButton.setEnabled(false);this._splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged,event=>{this._isSidebarOpen=event.data===UI.SplitWidget.ShowMode.Both;this._filter._levelMenuButton.setEnabled(!this._isSidebarOpen);this._onFilterChanged();});this._contentsElement=this._searchableView.element;this.element.classList.add('console-view');this._visibleViewMessages=[];this._hiddenByFilterCount=0;this._shouldBeHiddenCache=new Set();this._groupableMessages=new Map();this._groupableMessageTitle=new Map();this._regexMatchRanges=[];this._consoleContextSelector=new Console.ConsoleContextSelector();this._filterStatusText=new UI.ToolbarText();this._filterStatusText.element.classList.add('dimmed');this._showSettingsPaneSetting=Common.settings.createSetting('consoleShowSettingsToolbar',false);this._showSettingsPaneButton=new UI.ToolbarSettingToggle(this._showSettingsPaneSetting,'largeicon-settings-gear',Common.UIString('Console settings'));this._progressToolbarItem=new UI.ToolbarItem(createElement('div'));this._groupSimilarSetting=Common.settings.moduleSetting('consoleGroupSimilar');this._groupSimilarSetting.addChangeListener(()=>this._updateMessageList());const groupSimilarToggle=new UI.ToolbarSettingCheckbox(this._groupSimilarSetting,Common.UIString('Group similar'));const toolbar=new UI.Toolbar('console-main-toolbar',consoleToolbarContainer);const rightToolbar=new UI.Toolbar('',consoleToolbarContainer);toolbar.appendToolbarItem(this._splitWidget.createShowHideSidebarButton('console sidebar'));toolbar.appendToolbarItem(UI.Toolbar.createActionButton((UI.actionRegistry.action('console.clear'))));toolbar.appendSeparator();toolbar.appendToolbarItem(this._consoleContextSelector.toolbarItem());toolbar.appendSeparator();toolbar.appendToolbarItem(UI.Toolbar.createActionButton((UI.actionRegistry.action('console.create-pin'))));toolbar.appendSeparator();toolbar.appendToolbarItem(this._filter._textFilterUI);toolbar.appendToolbarItem(this._filter._levelMenuButton);toolbar.appendToolbarItem(this._progressToolbarItem);rightToolbar.appendSeparator();rightToolbar.appendToolbarItem(this._filterStatusText);rightToolbar.appendToolbarItem(this._showSettingsPaneButton);this._preserveLogCheckbox=new UI.ToolbarSettingCheckbox(Common.moduleSetting('preserveConsoleLog'),Common.UIString('Do not clear log on page reload / navigation'),Common.UIString('Preserve log'));this._hideNetworkMessagesCheckbox=new UI.ToolbarSettingCheckbox(this._filter._hideNetworkMessagesSetting,this._filter._hideNetworkMessagesSetting.title(),Common.UIString('Hide network'));const filterByExecutionContextCheckbox=new UI.ToolbarSettingCheckbox(this._filter._filterByExecutionContextSetting,Common.UIString('Only show messages from the current context (top, iframe, worker, extension)'),Common.UIString('Selected context only'));const monitoringXHREnabledSetting=Common.moduleSetting('monitoringXHREnabled');this._timestampsSetting=Common.moduleSetting('consoleTimestampsEnabled');this._consoleHistoryAutocompleteSetting=Common.moduleSetting('consoleHistoryAutocomplete');const settingsPane=new UI.HBox();settingsPane.show(this._contentsElement);settingsPane.element.classList.add('console-settings-pane');const settingsToolbarLeft=new UI.Toolbar('',settingsPane.element);settingsToolbarLeft.makeVertical();settingsToolbarLeft.appendToolbarItem(this._hideNetworkMessagesCheckbox);settingsToolbarLeft.appendToolbarItem(this._preserveLogCheckbox);settingsToolbarLeft.appendToolbarItem(filterByExecutionContextCheckbox);settingsToolbarLeft.appendToolbarItem(groupSimilarToggle);const settingsToolbarRight=new UI.Toolbar('',settingsPane.element);settingsToolbarRight.makeVertical();settingsToolbarRight.appendToolbarItem(new UI.ToolbarSettingCheckbox(monitoringXHREnabledSetting));const eagerEvalCheckbox=new UI.ToolbarSettingCheckbox(Common.settings.moduleSetting('consoleEagerEval'),ls`Eagerly evaluate text in the prompt`);settingsToolbarRight.appendToolbarItem(eagerEvalCheckbox);settingsToolbarRight.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._consoleHistoryAutocom
settingsPane.element.classList.add('hidden');this._showSettingsPaneSetting.addChangeListener(()=>settingsPane.element.classList.toggle('hidden',!this._showSettingsPaneSetting.get()));this._pinPane=new Console.ConsolePinPane();this._pinPane.element.classList.add('console-view-pinpane');this._pinPane.show(this._contentsElement);this._pinPane.element.addEventListener('keydown',event=>{if((event.key==='Enter'&&UI.KeyboardShortcut.eventHasCtrlOrMeta((event)))||event.keyCode===UI.KeyboardShortcut.Keys.Esc.code){this._prompt.focus();event.consume();}});this._viewport=new Console.ConsoleViewport(this);this._viewport.setStickToBottom(true);this._viewport.contentElement().classList.add('console-group','console-group-messages');this._contentsElement.appendChild(this._viewport.element);this._messagesElement=this._viewport.element;this._messagesElement.id='console-messages';this._messagesElement.classList.add('monospace');this._messagesElement.addEventListener('click',this._messagesClicked.bind(this),false);this._messagesElement.addEventListener('paste',this._messagesPasted.bind(this),true);this._messagesElement.addEventListener('clipboard-paste',this._messagesPasted.bind(this),true);this._viewportThrottler=new Common.Throttler(50);this._pendingBatchResize=false;this._onMessageResizedBound=this._onMessageResized.bind(this);this._topGroup=Console.ConsoleGroup.createTopGroup();this._currentGroup=this._topGroup;this._promptElement=this._messagesElement.createChild('div','source-code');this._promptElement.id='console-prompt';const selectAllFixer=this._messagesElement.createChild('div','console-view-fix-select-all');selectAllFixer.textContent='.';UI.ARIAUtils.markAsHidden(selectAllFixer);this._registerShortcuts();this._messagesElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),false);this._linkifier=new Components.Linkifier(Console.ConsoleViewMessage.MaxLengthForLinks);this._consoleMessages=[];this._viewMessageSymbol=Symbol('viewMessage');this._consoleHistorySetting=Common.settings.createLocalSetting('consoleHistory',[]);this._prompt=new Console.ConsolePrompt();this._prompt.show(this._promptElement);this._prompt.element.addEventListener('keydown',this._promptKeyDown.bind(this),true);this._prompt.addEventListener(Console.ConsolePrompt.Events.TextChanged,this._promptTextChanged,this);this._messagesElement.addEventListener('keydown',this._messagesKeyDown.bind(this),false);this._prompt.element.addEventListener('focusin',()=>{if(this._isScrolledToBottom())
this._viewport.setStickToBottom(true);});this._consoleHistoryAutocompleteSetting.addChangeListener(this._consoleHistoryAutocompleteChanged,this);const historyData=this._consoleHistorySetting.get();this._prompt.history().setHistoryData(historyData);this._consoleHistoryAutocompleteChanged();this._updateFilterStatus();this._timestampsSetting.addChangeListener(this._consoleTimestampsSettingChanged,this);this._registerWithMessageSink();UI.context.addFlavorChangeListener(SDK.ExecutionContext,this._executionContextChanged,this);this._messagesElement.addEventListener('mousedown',event=>this._updateStickToBottomOnPointerDown(event.button===2),false);this._messagesElement.addEventListener('mouseup',this._updateStickToBottomOnPointerUp.bind(this),false);this._messagesElement.addEventListener('mouseleave',this._updateStickToBottomOnPointerUp.bind(this),false);this._messagesElement.addEventListener('wheel',this._updateStickToBottomOnWheel.bind(this),false);this._messagesElement.addEventListener('touchstart',this._updateStickToBottomOnPointerDown.bind(this,false),false);this._messagesElement.addEventListener('touchend',this._updateStickToBottomOnPointerUp.bind(this),false);this._messagesElement.addEventListener('touchcancel',this._updateStickToBottomOnPointerUp.bind(this),false);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.ConsoleCleared,this._consoleCleared,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded,this._onConsoleMessageAdded,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageUpdated,this._onConsoleMessageUpdated,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.CommandEvaluated,this._commandEvaluated,this);SDK.consoleModel.messages().forEach(this._addConsoleMessage,this);}
static instance(){if(!Console.ConsoleView._instance)
Console.ConsoleView._instance=new Console.ConsoleView();return Console.ConsoleView._instance;}
static clearConsole(){SDK.consoleModel.requestClearMessages();}
_onFilterChanged(){this._filter._currentFilter.levelsMask=this._isSidebarOpen?Console.ConsoleFilter.allLevelsFilterValue():this._filter._messageLevelFiltersSetting.get();this._cancelBuildHiddenCache();if(this._immediatelyFilterMessagesForTest){for(const viewMessage of this._consoleMessages)
this._computeShouldMessageBeVisible(viewMessage);this._updateMessageList();return;}
this._buildHiddenCache(0,this._consoleMessages.slice());}
_setImmediatelyFilterMessagesForTest(){this._immediatelyFilterMessagesForTest=true;}
searchableView(){return this._searchableView;}
_clearHistory(){this._consoleHistorySetting.set([]);this._prompt.history().setHistoryData([]);}
_consoleHistoryAutocompleteChanged(){this._prompt.setAddCompletionsFromHistory(this._consoleHistoryAutocompleteSetting.get());}
itemCount(){return this._visibleViewMessages.length;}
itemElement(index){return this._visibleViewMessages[index];}
fastHeight(index){return this._visibleViewMessages[index].fastHeight();}
minimumRowHeight(){return 16;}
_registerWithMessageSink(){Common.console.messages().forEach(this._addSinkMessage,this);Common.console.addEventListener(Common.Console.Events.MessageAdded,messageAdded,this);function messageAdded(event){this._addSinkMessage((event.data));}}
_addSinkMessage(message){let level=SDK.ConsoleMessage.MessageLevel.Verbose;switch(message.level){case Common.Console.MessageLevel.Info:level=SDK.ConsoleMessage.MessageLevel.Info;break;case Common.Console.MessageLevel.Error:level=SDK.ConsoleMessage.MessageLevel.Error;break;case Common.Console.MessageLevel.Warning:level=SDK.ConsoleMessage.MessageLevel.Warning;break;}
const consoleMessage=new SDK.ConsoleMessage(null,SDK.ConsoleMessage.MessageSource.Other,level,message.text,SDK.ConsoleMessage.MessageType.System,undefined,undefined,undefined,undefined,undefined,message.timestamp);this._addConsoleMessage(consoleMessage);}
_consoleTimestampsSettingChanged(){this._updateMessageList();this._consoleMessages.forEach(viewMessage=>viewMessage.updateTimestamp());this._groupableMessageTitle.forEach(viewMessage=>viewMessage.updateTimestamp());}
_executionContextChanged(){this._prompt.clearAutocomplete();}
willHide(){this._hidePromptSuggestBox();}
wasShown(){this._viewport.refresh();}
focus(){if(this._viewport.hasVirtualSelection())
this._viewport.contentElement().focus();else
this._focusPrompt();}
_focusPrompt(){if(!this._prompt.hasFocus()){const oldStickToBottom=this._viewport.stickToBottom();const oldScrollTop=this._viewport.element.scrollTop;this._prompt.focus();this._viewport.setStickToBottom(oldStickToBottom);this._viewport.element.scrollTop=oldScrollTop;}}
restoreScrollPositions(){if(this._viewport.stickToBottom())
this._immediatelyScrollToBottom();else
super.restoreScrollPositions();}
onResize(){this._scheduleViewportRefresh();this._hidePromptSuggestBox();if(this._viewport.stickToBottom())
this._immediatelyScrollToBottom();for(let i=0;i<this._visibleViewMessages.length;++i)
this._visibleViewMessages[i].onResize();}
_hidePromptSuggestBox(){this._prompt.clearAutocomplete();}
_invalidateViewport(){if(this._muteViewportUpdates){this._maybeDirtyWhileMuted=true;return Promise.resolve();}
if(this._needsFullUpdate){this._updateMessageList();delete this._needsFullUpdate;}else{this._viewport.invalidate();}
return Promise.resolve();}
_scheduleViewportRefresh(){if(this._muteViewportUpdates){this._maybeDirtyWhileMuted=true;this._scheduleViewportRefreshForTest(true);return;}else{this._scheduleViewportRefreshForTest(false);}
this._scheduledRefreshPromiseForTest=this._viewportThrottler.schedule(this._invalidateViewport.bind(this));}
_scheduleViewportRefreshForTest(muted){}
_immediatelyScrollToBottom(){this._viewport.setStickToBottom(true);this._promptElement.scrollIntoView(true);}
_updateFilterStatus(){if(this._hiddenByFilterCount===this._lastShownHiddenByFilterCount)
return;this._filterStatusText.setText(ls`${this._hiddenByFilterCount} hidden`);this._filterStatusText.setVisible(!!this._hiddenByFilterCount);this._lastShownHiddenByFilterCount=this._hiddenByFilterCount;}
_onConsoleMessageAdded(event){const message=(event.data);this._addConsoleMessage(message);}
_addConsoleMessage(message){const viewMessage=this._createViewMessage(message);message[this._viewMessageSymbol]=viewMessage;if(message.type===SDK.ConsoleMessage.MessageType.Command||message.type===SDK.ConsoleMessage.MessageType.Result){const lastMessage=this._consoleMessages.peekLast();viewMessage[Console.ConsoleView._messageSortingTimeSymbol]=lastMessage?lastMessage[Console.ConsoleView._messageSortingTimeSymbol]:0;}else{viewMessage[Console.ConsoleView._messageSortingTimeSymbol]=viewMessage.consoleMessage().timestamp;}
let insertAt;if(!this._consoleMessages.length||timeComparator(viewMessage,this._consoleMessages[this._consoleMessages.length-1])>0)
insertAt=this._consoleMessages.length;else
insertAt=this._consoleMessages.upperBound(viewMessage,timeComparator);const insertedInMiddle=insertAt<this._consoleMessages.length;this._consoleMessages.splice(insertAt,0,viewMessage);this._filter.onMessageAdded(message);this._sidebar.onMessageAdded(viewMessage);let shouldGoIntoGroup=false;if(message.isGroupable()){const groupKey=viewMessage.groupKey();shouldGoIntoGroup=this._groupSimilarSetting.get()&&this._groupableMessages.has(groupKey);let list=this._groupableMessages.get(groupKey);if(!list){list=[];this._groupableMessages.set(groupKey,list);}
list.push(viewMessage);}
this._computeShouldMessageBeVisible(viewMessage);if(!shouldGoIntoGroup&&!insertedInMiddle){this._appendMessageToEnd(viewMessage);this._updateFilterStatus();this._searchableView.updateSearchMatchesCount(this._regexMatchRanges.length);}else{this._needsFullUpdate=true;}
this._scheduleViewportRefresh();this._consoleMessageAddedForTest(viewMessage);function timeComparator(viewMessage1,viewMessage2){return viewMessage1[Console.ConsoleView._messageSortingTimeSymbol]-
viewMessage2[Console.ConsoleView._messageSortingTimeSymbol];}}
_onConsoleMessageUpdated(event){const message=(event.data);const viewMessage=message[this._viewMessageSymbol];if(viewMessage){viewMessage.updateMessageElement();this._computeShouldMessageBeVisible(viewMessage);this._updateMessageList();}}
_consoleMessageAddedForTest(viewMessage){}
_shouldMessageBeVisible(viewMessage){return!this._shouldBeHiddenCache.has(viewMessage);}
_computeShouldMessageBeVisible(viewMessage){if(this._filter.shouldBeVisible(viewMessage)&&(!this._isSidebarOpen||this._sidebar.shouldBeVisible(viewMessage)))
this._shouldBeHiddenCache.delete(viewMessage);else
this._shouldBeHiddenCache.add(viewMessage);}
_appendMessageToEnd(viewMessage,preventCollapse){if(!this._shouldMessageBeVisible(viewMessage)){this._hiddenByFilterCount++;return;}
if(!preventCollapse&&this._tryToCollapseMessages(viewMessage,this._visibleViewMessages.peekLast()))
return;const lastMessage=this._visibleViewMessages.peekLast();if(viewMessage.consoleMessage().type===SDK.ConsoleMessage.MessageType.EndGroup){if(lastMessage&&!this._currentGroup.messagesHidden())
lastMessage.incrementCloseGroupDecorationCount();this._currentGroup=this._currentGroup.parentGroup()||this._currentGroup;return;}
if(!this._currentGroup.messagesHidden()){const originatingMessage=viewMessage.consoleMessage().originatingMessage();if(lastMessage&&originatingMessage&&lastMessage.consoleMessage()===originatingMessage)
viewMessage.toMessageElement().classList.add('console-adjacent-user-command-result');this._visibleViewMessages.push(viewMessage);this._searchMessage(this._visibleViewMessages.length-1);}
if(viewMessage.consoleMessage().isGroupStartMessage())
this._currentGroup=new Console.ConsoleGroup(this._currentGroup,viewMessage);this._messageAppendedForTests();}
_messageAppendedForTests(){}
_createViewMessage(message){const nestingLevel=this._currentGroup.nestingLevel();switch(message.type){case SDK.ConsoleMessage.MessageType.Command:return new Console.ConsoleCommand(message,this._linkifier,this._badgePool,nestingLevel,this._onMessageResizedBound);case SDK.ConsoleMessage.MessageType.Result:return new Console.ConsoleCommandResult(message,this._linkifier,this._badgePool,nestingLevel,this._onMessageResizedBound);case SDK.ConsoleMessage.MessageType.StartGroupCollapsed:case SDK.ConsoleMessage.MessageType.StartGroup:return new Console.ConsoleGroupViewMessage(message,this._linkifier,this._badgePool,nestingLevel,this._updateMessageList.bind(this),this._onMessageResizedBound);default:return new Console.ConsoleViewMessage(message,this._linkifier,this._badgePool,nestingLevel,this._onMessageResizedBound);}}
async _onMessageResized(event){const treeElement=(event.data);if(this._pendingBatchResize||!treeElement.treeOutline)
return;this._pendingBatchResize=true;await Promise.resolve();const treeOutlineElement=treeElement.treeOutline.element;this._viewport.setStickToBottom(this._isScrolledToBottom());if(treeOutlineElement.offsetHeight<=this._messagesElement.offsetHeight)
treeOutlineElement.scrollIntoViewIfNeeded();this._pendingBatchResize=false;}
_consoleCleared(){const hadFocus=this._viewport.element.hasFocus();this._cancelBuildHiddenCache();this._currentMatchRangeIndex=-1;this._consoleMessages=[];this._groupableMessages.clear();this._groupableMessageTitle.clear();this._sidebar.clear();this._updateMessageList();this._hidePromptSuggestBox();this._viewport.setStickToBottom(true);this._linkifier.reset();this._badgePool.reset();this._filter.clear();if(hadFocus)
this._prompt.focus();}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);if(event.target.isSelfOrDescendant(this._promptElement)){contextMenu.show();return;}
const sourceElement=event.target.enclosingNodeOrSelfWithClass('console-message-wrapper');const consoleMessage=sourceElement?sourceElement.message.consoleMessage():null;if(consoleMessage&&consoleMessage.url){const menuTitle=ls`Hide messages from ${new Common.ParsedURL(consoleMessage.url).displayName}`;contextMenu.headerSection().appendItem(menuTitle,this._filter.addMessageURLFilter.bind(this._filter,consoleMessage.url));}
contextMenu.defaultSection().appendAction('console.clear');contextMenu.defaultSection().appendAction('console.clear.history');contextMenu.saveSection().appendItem(Common.UIString('Save as...'),this._saveConsole.bind(this));if(this.element.hasSelection()){contextMenu.clipboardSection().appendItem(Common.UIString('Copy visible styled selection'),this._viewport.copyWithStyles.bind(this._viewport));}
if(consoleMessage){const request=SDK.NetworkLog.requestForConsoleMessage(consoleMessage);if(request&&SDK.NetworkManager.canReplayRequest(request))
contextMenu.debugSection().appendItem(ls`Replay XHR`,SDK.NetworkManager.replayRequest.bind(null,request));}
contextMenu.show();}
async _saveConsole(){const url=SDK.targetManager.mainTarget().inspectedURL();const parsedURL=url.asParsedURL();const filename=String.sprintf('%s-%d.log',parsedURL?parsedURL.host:'console',Date.now());const stream=new Bindings.FileOutputStream();const progressIndicator=new UI.ProgressIndicator();progressIndicator.setTitle(Common.UIString('Writing file…'));progressIndicator.setTotalWork(this.itemCount());const chunkSize=350;if(!await stream.open(filename))
return;this._progressToolbarItem.element.appendChild(progressIndicator.element);let messageIndex=0;while(messageIndex<this.itemCount()&&!progressIndicator.isCanceled()){const messageContents=[];let i;for(i=0;i<chunkSize&&i+messageIndex<this.itemCount();++i){const message=this.itemElement(messageIndex+i);messageContents.push(message.toExportString());}
messageIndex+=i;await stream.write(messageContents.join('\n')+'\n');progressIndicator.setWorked(messageIndex);}
stream.close();progressIndicator.done();}
_tryToCollapseMessages(viewMessage,lastMessage){const timestampsShown=this._timestampsSetting.get();if(!timestampsShown&&lastMessage&&!viewMessage.consoleMessage().isGroupMessage()&&viewMessage.consoleMessage().type!==SDK.ConsoleMessage.MessageType.Command&&viewMessage.consoleMessage().type!==SDK.ConsoleMessage.MessageType.Result&&viewMessage.consoleMessage().isEqual(lastMessage.consoleMessage())){lastMessage.incrementRepeatCount();if(viewMessage.isLastInSimilarGroup())
lastMessage.setInSimilarGroup(true,true);return true;}
return false;}
_buildHiddenCache(startIndex,viewMessages){const startTime=Date.now();let i;for(i=startIndex;i<viewMessages.length;++i){this._computeShouldMessageBeVisible(viewMessages[i]);if(i%10===0&&Date.now()-startTime>12)
break;}
if(i===viewMessages.length){this._updateMessageList();return;}
this._buildHiddenCacheTimeout=this.element.window().requestAnimationFrame(this._buildHiddenCache.bind(this,i,viewMessages));}
_cancelBuildHiddenCache(){this._shouldBeHiddenCache.clear();if(this._buildHiddenCacheTimeout){this.element.window().cancelAnimationFrame(this._buildHiddenCacheTimeout);delete this._buildHiddenCacheTimeout;}}
_updateMessageList(){this._topGroup=Console.ConsoleGroup.createTopGroup();this._currentGroup=this._topGroup;this._regexMatchRanges=[];this._hiddenByFilterCount=0;for(let i=0;i<this._visibleViewMessages.length;++i){this._visibleViewMessages[i].resetCloseGroupDecorationCount();this._visibleViewMessages[i].resetIncrementRepeatCount();}
this._visibleViewMessages=[];if(this._groupSimilarSetting.get()){this._addGroupableMessagesToEnd();}else{for(let i=0;i<this._consoleMessages.length;++i){this._consoleMessages[i].setInSimilarGroup(false);this._appendMessageToEnd(this._consoleMessages[i]);}}
this._updateFilterStatus();this._searchableView.updateSearchMatchesCount(this._regexMatchRanges.length);this._viewport.invalidate();}
_addGroupableMessagesToEnd(){const alreadyAdded=new Set();const processedGroupKeys=new Set();for(let i=0;i<this._consoleMessages.length;++i){const viewMessage=this._consoleMessages[i];const message=viewMessage.consoleMessage();if(alreadyAdded.has(message))
continue;if(!message.isGroupable()){this._appendMessageToEnd(viewMessage);alreadyAdded.add(message);continue;}
const key=viewMessage.groupKey();const viewMessagesInGroup=this._groupableMessages.get(key);if(!viewMessagesInGroup||viewMessagesInGroup.length<5){viewMessage.setInSimilarGroup(false);this._appendMessageToEnd(viewMessage);alreadyAdded.add(message);continue;}
if(processedGroupKeys.has(key))
continue;if(!viewMessagesInGroup.find(x=>this._shouldMessageBeVisible(x))){alreadyAdded.addAll(viewMessagesInGroup);processedGroupKeys.add(key);continue;}
let startGroupViewMessage=this._groupableMessageTitle.get(key);if(!startGroupViewMessage){const startGroupMessage=new SDK.ConsoleMessage(null,message.source,message.level,viewMessage.groupTitle(),SDK.ConsoleMessage.MessageType.StartGroupCollapsed);startGroupViewMessage=this._createViewMessage(startGroupMessage);this._groupableMessageTitle.set(key,startGroupViewMessage);}
startGroupViewMessage.setRepeatCount(viewMessagesInGroup.length);this._appendMessageToEnd(startGroupViewMessage);for(const viewMessageInGroup of viewMessagesInGroup){viewMessageInGroup.setInSimilarGroup(true,viewMessagesInGroup.peekLast()===viewMessageInGroup);this._appendMessageToEnd(viewMessageInGroup,true);alreadyAdded.add(viewMessageInGroup.consoleMessage());}
const endGroupMessage=new SDK.ConsoleMessage(null,message.source,message.level,message.messageText,SDK.ConsoleMessage.MessageType.EndGroup);this._appendMessageToEnd(this._createViewMessage(endGroupMessage));}}
_messagesClicked(event){const target=(event.target);if(!this._messagesElement.hasSelection()){const clickedOutsideMessageList=target===this._messagesElement||this._prompt.belowEditorElement().isSelfOrAncestor(target);if(clickedOutsideMessageList){this._prompt.moveCaretToEndOfPrompt();this._focusPrompt();}}}
_messagesKeyDown(event){const hasActionModifier=event.ctrlKey||event.altKey||event.metaKey;if(hasActionModifier||event.key.length!==1||UI.isEditing()||this._messagesElement.hasSelection())
return;this._prompt.moveCaretToEndOfPrompt();this._focusPrompt();}
_messagesPasted(event){if(UI.isEditing())
return;this._prompt.focus();}
_registerShortcuts(){this._shortcuts={};this._shortcuts[UI.KeyboardShortcut.makeKey('u',UI.KeyboardShortcut.Modifiers.Ctrl)]=this._clearPromptBackwards.bind(this);}
_clearPromptBackwards(){this._prompt.setText('');}
_promptKeyDown(event){const keyboardEvent=(event);if(keyboardEvent.key==='PageUp'){this._updateStickToBottomOnWheel();return;}
const shortcut=UI.KeyboardShortcut.makeKeyFromEvent(keyboardEvent);const handler=this._shortcuts[shortcut];if(handler){handler();keyboardEvent.preventDefault();}}
_printResult(result,originatingConsoleMessage,exceptionDetails){if(!result)
return;const level=!!exceptionDetails?SDK.ConsoleMessage.MessageLevel.Error:SDK.ConsoleMessage.MessageLevel.Info;let message;if(!exceptionDetails){message=new SDK.ConsoleMessage(result.runtimeModel(),SDK.ConsoleMessage.MessageSource.JS,level,'',SDK.ConsoleMessage.MessageType.Result,undefined,undefined,undefined,[result]);}else{message=SDK.ConsoleMessage.fromException(result.runtimeModel(),exceptionDetails,SDK.ConsoleMessage.MessageType.Result,undefined,undefined);}
message.setOriginatingMessage(originatingConsoleMessage);SDK.consoleModel.addMessage(message);}
_commandEvaluated(event){const data=(event.data);this._prompt.history().pushHistoryItem(data.commandMessage.messageText);this._consoleHistorySetting.set(this._prompt.history().historyData().slice(-Console.ConsoleView.persistedHistorySize));this._printResult(data.result,data.commandMessage,data.exceptionDetails);}
elementsToRestoreScrollPositionsFor(){return[this._messagesElement];}
searchCanceled(){this._cleanupAfterSearch();for(let i=0;i<this._visibleViewMessages.length;++i){const message=this._visibleViewMessages[i];message.setSearchRegex(null);}
this._currentMatchRangeIndex=-1;this._regexMatchRanges=[];delete this._searchRegex;this._viewport.refresh();}
performSearch(searchConfig,shouldJump,jumpBackwards){this.searchCanceled();this._searchableView.updateSearchMatchesCount(0);this._searchRegex=searchConfig.toSearchRegex(true);this._regexMatchRanges=[];this._currentMatchRangeIndex=-1;if(shouldJump)
this._searchShouldJumpBackwards=!!jumpBackwards;this._searchProgressIndicator=new UI.ProgressIndicator();this._searchProgressIndicator.setTitle(Common.UIString('Searching…'));this._searchProgressIndicator.setTotalWork(this._visibleViewMessages.length);this._progressToolbarItem.element.appendChild(this._searchProgressIndicator.element);this._innerSearch(0);}
_cleanupAfterSearch(){delete this._searchShouldJumpBackwards;if(this._innerSearchTimeoutId){clearTimeout(this._innerSearchTimeoutId);delete this._innerSearchTimeoutId;}
if(this._searchProgressIndicator){this._searchProgressIndicator.done();delete this._searchProgressIndicator;}}
_searchFinishedForTests(){}
_innerSearch(index){delete this._innerSearchTimeoutId;if(this._searchProgressIndicator.isCanceled()){this._cleanupAfterSearch();return;}
const startTime=Date.now();for(;index<this._visibleViewMessages.length&&Date.now()-startTime<100;++index)
this._searchMessage(index);this._searchableView.updateSearchMatchesCount(this._regexMatchRanges.length);if(typeof this._searchShouldJumpBackwards!=='undefined'&&this._regexMatchRanges.length){this._jumpToMatch(this._searchShouldJumpBackwards?-1:0);delete this._searchShouldJumpBackwards;}
if(index===this._visibleViewMessages.length){this._cleanupAfterSearch();setTimeout(this._searchFinishedForTests.bind(this),0);return;}
this._innerSearchTimeoutId=setTimeout(this._innerSearch.bind(this,index),100);this._searchProgressIndicator.setWorked(index);}
_searchMessage(index){const message=this._visibleViewMessages[index];message.setSearchRegex(this._searchRegex);for(let i=0;i<message.searchCount();++i)
this._regexMatchRanges.push({messageIndex:index,matchIndex:i});}
jumpToNextSearchResult(){this._jumpToMatch(this._currentMatchRangeIndex+1);}
jumpToPreviousSearchResult(){this._jumpToMatch(this._currentMatchRangeIndex-1);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}
_jumpToMatch(index){if(!this._regexMatchRanges.length)
return;let matchRange;if(this._currentMatchRangeIndex>=0){matchRange=this._regexMatchRanges[this._currentMatchRangeIndex];const message=this._visibleViewMessages[matchRange.messageIndex];message.searchHighlightNode(matchRange.matchIndex).classList.remove(UI.highlightedCurrentSearchResultClassName);}
index=mod(index,this._regexMatchRanges.length);this._currentMatchRangeIndex=index;this._searchableView.updateCurrentMatchIndex(index);matchRange=this._regexMatchRanges[index];const message=this._visibleViewMessages[matchRange.messageIndex];const highlightNode=message.searchHighlightNode(matchRange.matchIndex);highlightNode.classList.add(UI.highlightedCurrentSearchResultClassName);this._viewport.scrollItemIntoView(matchRange.messageIndex);highlightNode.scrollIntoViewIfNeeded();}
_updateStickToBottomOnPointerDown(isRightClick){this._muteViewportUpdates=!isRightClick;this._viewport.setStickToBottom(false);if(this._waitForScrollTimeout){clearTimeout(this._waitForScrollTimeout);delete this._waitForScrollTimeout;}}
_updateStickToBottomOnPointerUp(){if(!this._muteViewportUpdates)
return;this._waitForScrollTimeout=setTimeout(updateViewportState.bind(this),200);function updateViewportState(){this._muteViewportUpdates=false;if(this.isShowing())
this._viewport.setStickToBottom(this._isScrolledToBottom());if(this._maybeDirtyWhileMuted){this._scheduleViewportRefresh();delete this._maybeDirtyWhileMuted;}
delete this._waitForScrollTimeout;this._updateViewportStickinessForTest();}}
_updateViewportStickinessForTest(){}
_updateStickToBottomOnWheel(){this._updateStickToBottomOnPointerDown();this._updateStickToBottomOnPointerUp();}
_promptTextChanged(){const oldStickToBottom=this._viewport.stickToBottom();const willStickToBottom=this._isScrolledToBottom();this._viewport.setStickToBottom(willStickToBottom);if(willStickToBottom&&!oldStickToBottom)
this._scheduleViewportRefresh();this._promptTextChangedForTest();}
_promptTextChangedForTest(){}
_isScrolledToBottom(){const distanceToPromptEditorBottom=this._messagesElement.scrollHeight-this._messagesElement.scrollTop-
this._messagesElement.clientHeight-this._prompt.belowEditorElement().offsetHeight;return distanceToPromptEditorBottom<=2;}};Console.ConsoleView.persistedHistorySize=300;Console.ConsoleViewFilter=class{constructor(filterChangedCallback){this._filterChanged=filterChangedCallback;this._messageLevelFiltersSetting=Console.ConsoleViewFilter.levelFilterSetting();this._hideNetworkMessagesSetting=Common.moduleSetting('hideNetworkMessages');this._filterByExecutionContextSetting=Common.moduleSetting('selectedContextFilterEnabled');this._messageLevelFiltersSetting.addChangeListener(this._onFilterChanged.bind(this));this._hideNetworkMessagesSetting.addChangeListener(this._onFilterChanged.bind(this));this._filterByExecutionContextSetting.addChangeListener(this._onFilterChanged.bind(this));UI.context.addFlavorChangeListener(SDK.ExecutionContext,this._onFilterChanged,this);const filterKeys=Object.values(Console.ConsoleFilter.FilterType);this._suggestionBuilder=new UI.FilterSuggestionBuilder(filterKeys);this._textFilterUI=new UI.ToolbarInput(Common.UIString('Filter'),0.2,1,Common.UIString('e.g. /event\\d/ -cdn url:a.com'),this._suggestionBuilder.completions.bind(this._suggestionBuilder));this._textFilterSetting=Common.settings.createSetting('console.textFilter','');if(this._textFilterSetting.get())
this._textFilterUI.setValue(this._textFilterSetting.get());this._textFilterUI.addEventListener(UI.ToolbarInput.Event.TextChanged,()=>{this._textFilterSetting.set(this._textFilterUI.value());this._onFilterChanged();});this._filterParser=new TextUtils.FilterParser(filterKeys);this._currentFilter=new Console.ConsoleFilter('',[],null,this._messageLevelFiltersSetting.get());this._updateCurrentFilter();this._levelLabels={};this._levelLabels[SDK.ConsoleMessage.MessageLevel.Verbose]=Common.UIString('Verbose');this._levelLabels[SDK.ConsoleMessage.MessageLevel.Info]=Common.UIString('Info');this._levelLabels[SDK.ConsoleMessage.MessageLevel.Warning]=Common.UIString('Warnings');this._levelLabels[SDK.ConsoleMessage.MessageLevel.Error]=Common.UIString('Errors');this._levelMenuButton=new UI.ToolbarButton(ls`Log levels`);this._levelMenuButton.turnIntoSelect();this._levelMenuButton.addEventListener(UI.ToolbarButton.Events.Click,this._showLevelContextMenu.bind(this));this._updateLevelMenuButtonText();this._messageLevelFiltersSetting.addChangeListener(this._updateLevelMenuButtonText.bind(this));}
onMessageAdded(message){if(message.type===SDK.ConsoleMessage.MessageType.Command||message.type===SDK.ConsoleMessage.MessageType.Result||message.isGroupMessage())
return;if(message.context)
this._suggestionBuilder.addItem(Console.ConsoleFilter.FilterType.Context,message.context);if(message.source)
this._suggestionBuilder.addItem(Console.ConsoleFilter.FilterType.Source,message.source);if(message.url)
this._suggestionBuilder.addItem(Console.ConsoleFilter.FilterType.Url,message.url);}
static levelFilterSetting(){return Common.settings.createSetting('messageLevelFilters',Console.ConsoleFilter.defaultLevelsFilterValue());}
_updateCurrentFilter(){const parsedFilters=this._filterParser.parse(this._textFilterUI.value());if(this._hideNetworkMessagesSetting.get()){parsedFilters.push({key:Console.ConsoleFilter.FilterType.Source,text:SDK.ConsoleMessage.MessageSource.Network,negative:true});}
this._currentFilter.executionContext=this._filterByExecutionContextSetting.get()?UI.context.flavor(SDK.ExecutionContext):null;this._currentFilter.parsedFilters=parsedFilters;this._currentFilter.levelsMask=this._messageLevelFiltersSetting.get();}
_onFilterChanged(){this._updateCurrentFilter();this._filterChanged();}
_updateLevelMenuButtonText(){let isAll=true;let isDefault=true;const allValue=Console.ConsoleFilter.allLevelsFilterValue();const defaultValue=Console.ConsoleFilter.defaultLevelsFilterValue();let text=null;const levels=this._messageLevelFiltersSetting.get();for(const name of Object.values(SDK.ConsoleMessage.MessageLevel)){isAll=isAll&&levels[name]===allValue[name];isDefault=isDefault&&levels[name]===defaultValue[name];if(levels[name])
text=text?Common.UIString('Custom levels'):Common.UIString('%s only',this._levelLabels[name]);}
if(isAll)
text=Common.UIString('All levels');else if(isDefault)
text=Common.UIString('Default levels');else
text=text||Common.UIString('Hide all');this._levelMenuButton.element.classList.toggle('warning',!isAll&&!isDefault);this._levelMenuButton.setText(text);}
_showLevelContextMenu(event){const mouseEvent=(event.data);const setting=this._messageLevelFiltersSetting;const levels=setting.get();const contextMenu=new UI.ContextMenu(mouseEvent,true,this._levelMenuButton.element.totalOffsetLeft(),this._levelMenuButton.element.totalOffsetTop()+this._levelMenuButton.element.offsetHeight);contextMenu.headerSection().appendItem(Common.UIString('Default'),()=>setting.set(Console.ConsoleFilter.defaultLevelsFilterValue()));for(const level in this._levelLabels){contextMenu.defaultSection().appendCheckboxItem(this._levelLabels[level],toggleShowLevel.bind(null,level),levels[level]);}
contextMenu.show();function toggleShowLevel(level){levels[level]=!levels[level];setting.set(levels);}}
addMessageURLFilter(url){if(!url)
return;const suffix=this._textFilterUI.value()?` ${this._textFilterUI.value()}`:'';this._textFilterUI.setValue(`-url:${url}${suffix}`);this._textFilterSetting.set(this._textFilterUI.value());this._onFilterChanged();}
shouldBeVisible(viewMessage){return this._currentFilter.shouldBeVisible(viewMessage);}
clear(){this._suggestionBuilder.clear();}
reset(){this._messageLevelFiltersSetting.set(Console.ConsoleFilter.defaultLevelsFilterValue());this._filterByExecutionContextSetting.set(false);this._hideNetworkMessagesSetting.set(false);this._textFilterUI.setValue('');this._onFilterChanged();}};Console.ConsoleCommand=class extends Console.ConsoleViewMessage{contentElement(){if(!this._contentElement){this._contentElement=createElementWithClass('div','console-user-command');const icon=UI.Icon.create('smallicon-user-command','command-result-icon');this._contentElement.appendChild(icon);this._contentElement.message=this;this._formattedCommand=createElementWithClass('span','source-code');this._formattedCommand.textContent=this.text.replaceControlCharacters();this._contentElement.appendChild(this._formattedCommand);if(this._formattedCommand.textContent.length<Console.ConsoleCommand.MaxLengthToIgnoreHighlighter){const javascriptSyntaxHighlighter=new UI.SyntaxHighlighter('text/javascript',true);javascriptSyntaxHighlighter.syntaxHighlightNode(this._formattedCommand).then(this._updateSearch.bind(this));}else{this._updateSearch();}
this.updateTimestamp();}
return this._contentElement;}
_updateSearch(){this.setSearchRegex(this.searchRegex());}};Console.ConsoleCommand.MaxLengthToIgnoreHighlighter=10000;Console.ConsoleCommandResult=class extends Console.ConsoleViewMessage{contentElement(){const element=super.contentElement();if(!element.classList.contains('console-user-command-result')){element.classList.add('console-user-command-result');if(this.consoleMessage().level===SDK.ConsoleMessage.MessageLevel.Info){const icon=UI.Icon.create('smallicon-command-result','command-result-icon');element.insertBefore(icon,element.firstChild);}}
return element;}};Console.ConsoleGroup=class{constructor(parentGroup,groupMessage){this._parentGroup=parentGroup;this._nestingLevel=parentGroup?parentGroup.nestingLevel()+1:0;this._messagesHidden=groupMessage&&groupMessage.collapsed()||this._parentGroup&&this._parentGroup.messagesHidden();}
static createTopGroup(){return new Console.ConsoleGroup(null,null);}
messagesHidden(){return this._messagesHidden;}
nestingLevel(){return this._nestingLevel;}
parentGroup(){return this._parentGroup;}};Console.ConsoleView.ActionDelegate=class{handleAction(context,actionId){switch(actionId){case'console.show':InspectorFrontendHost.bringToFront();Common.console.show();Console.ConsoleView.instance()._focusPrompt();return true;case'console.clear':Console.ConsoleView.clearConsole();return true;case'console.clear.history':Console.ConsoleView.instance()._clearHistory();return true;case'console.create-pin':Console.ConsoleView.instance()._pinPane.addPin('',true);return true;}
return false;}};Console.ConsoleView.RegexMatchRange;Console.ConsoleView._messageSortingTimeSymbol=Symbol('messageSortingTime');;Console.ConsolePanel=class extends UI.Panel{constructor(){super('console');this._view=Console.ConsoleView.instance();}
static instance(){return(self.runtime.sharedInstance(Console.ConsolePanel));}
static _updateContextFlavor(){const consoleView=Console.ConsolePanel.instance()._view;UI.context.setFlavor(Console.ConsoleView,consoleView.isShowing()?consoleView:null);}
wasShown(){super.wasShown();const wrapper=Console.ConsolePanel.WrapperView._instance;if(wrapper&&wrapper.isShowing())
UI.inspectorView.setDrawerMinimized(true);this._view.show(this.element);Console.ConsolePanel._updateContextFlavor();}
willHide(){super.willHide();UI.inspectorView.setDrawerMinimized(false);if(Console.ConsolePanel.WrapperView._instance)
Console.ConsolePanel.WrapperView._instance._showViewInWrapper();Console.ConsolePanel._updateContextFlavor();}
searchableView(){return Console.ConsoleView.instance().searchableView();}};Console.ConsolePanel.WrapperView=class extends UI.VBox{constructor(){super();this.element.classList.add('console-view-wrapper');Console.ConsolePanel.WrapperView._instance=this;this._view=Console.ConsoleView.instance();}
wasShown(){if(!Console.ConsolePanel.instance().isShowing())
this._showViewInWrapper();else
UI.inspectorView.setDrawerMinimized(true);Console.ConsolePanel._updateContextFlavor();}
willHide(){UI.inspectorView.setDrawerMinimized(false);Console.ConsolePanel._updateContextFlavor();}
_showViewInWrapper(){this._view.show(this.element);}};Console.ConsolePanel.ConsoleRevealer=class{reveal(object){const consoleView=Console.ConsoleView.instance();if(consoleView.isShowing()){consoleView.focus();return Promise.resolve();}
UI.viewManager.showView('console-view');return Promise.resolve();}};;Runtime.cachedResources["console/consoleContextSelector.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n padding: 2px 1px 2px 2px;\n white-space: nowrap;\n display: flex;\n flex-direction: column;\n height: 36px;\n justify-content: center;\n}\n\n.title {\n overflow: hidden;\n text-overflow: ellipsis;\n flex-grow: 0;\n}\n\n.badge {\n pointer-events: none;\n margin-right: 4px;\n display: inline-block;\n height: 15px;\n}\n\n.subtitle {\n color: #999;\n margin-right: 3px;\n overflow: hidden;\n text-overflow: ellipsis;\n flex-grow: 0;\n}\n\n:host(.highlighted) .subtitle {\n color: inherit;\n}\n\n/*# sourceURL=console/consoleContextSelector.css */";Runtime.cachedResources["console/consolePinPane.css"]="/*\n * Copyright 2018 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.console-pins {\n overflow-y: auto;\n background: var(--toolbar-bg-color);\n --error-background-color: hsl(0, 100%, 97%);\n --error-border-color: hsl(0, 100%, 92%);\n --error-text-color: red;\n}\n\n:host-context(.-theme-with-dark-background) .console-pins {\n --error-background-color: hsl(0, 100%, 8%);\n --error-border-color: rgb(92, 0, 0);\n --error-text-color: hsl(0, 100%, 75%);\n}\n\n.console-pins:not(:empty) {\n border-bottom: 1px solid var(--divider-color);\n}\n\n.console-pin {\n position: relative;\n user-select: text;\n flex: none;\n padding: 2px 0 6px 24px;\n}\n\n.console-pin:not(:last-child) {\n border-bottom: 1px solid #e4e4e4;\n}\n\n.console-pin:not(:last-child).error-level:not(:focus-within) {\n border-top: 1px solid var(--error-border-color);\n border-bottom: 1px solid var(--error-border-color);\n margin-top: -1px;\n}\n\n.console-pin.error-level:not(:focus-within) {\n background-color: var(--error-background-color);\n color: var(--error-text-color);\n}\n\n.console-pin-name {\n margin-left: -4px;\n margin-bottom: 1px;\n height: auto;\n}\n\n.console-pin-name,\n.console-pin-preview {\n width: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n min-height: 13px;\n}\n\n:host-context(.-theme-with-dark-background) .console-delete-pin {\n filter: brightness(2);\n}\n\n.console-delete-pin {\n position: absolute;\n top: 8px;\n left: 8px;\n opacity: 0.7;\n cursor: pointer;\n}\n\n.console-delete-pin:hover {\n opacity: 1;\n}\n\n.console-pin-name:focus-within {\n background: #fff;\n box-shadow: var(--focus-ring-active-shadow) inset;\n}\n\n.console-pin:focus-within .console-pin-preview,\n.console-pin-name:not(:focus-within):not(:hover) {\n opacity: 0.6;\n}\n\n/*# sourceURL=console/consolePinPane.css */";Runtime.cachedResources["console/consolePrompt.css"]="/*\n * Copyright 2018 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n#console-prompt .CodeMirror {\n padding: 3px 0 1px 0;\n}\n\n#console-prompt .CodeMirror-line {\n padding-top: 0;\n}\n\n#console-prompt .CodeMirror-lines {\n padding-top: 0;\n}\n\n#console-prompt .console-prompt-icon {\n position: absolute;\n left: -13px;\n top: 5px;\n -webkit-user-select: none;\n}\n\n.console-eager-preview {\n padding-bottom: 2px;\n opacity: 0.6;\n position: relative;\n height: 15px;\n}\n\n.console-eager-inner-preview {\n text-overflow: ellipsis;\n overflow: hidden;\n margin-left: 4px;\n height: 100%;\n}\n\n.console-eager-inner-preview {\n white-space: nowrap;\n}\n\n.console-eager-inner-preview:empty,\n.console-eager-inner-preview:empty + .preview-result-icon {\n opacity: 0;\n}\n\n.preview-result-icon {\n position: absolute;\n left: -13px;\n top: 1px;\n}\n\n.console-prompt-icon.console-prompt-incomplete {\n opacity: 0.65;\n}\n\n/*# sourceURL=console/consoleProm
this._dataGrid.setStriped(true);this._dataGrid.setName('cookiesTable');this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._rebuildTable,this);if(selectedCallback)
this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,selectedCallback,this);this._lastEditedColumnId=null;this._dataGrid.asWidget().show(this.element);this._data=[];this._cookieDomain='';}
setCookies(cookies){this.setCookieFolders([{cookies:cookies}]);}
setCookieFolders(cookieFolders){this._data=cookieFolders;this._rebuildTable();}
setCookieDomain(cookieDomain){this._cookieDomain=cookieDomain;}
selectedCookie(){const node=this._dataGrid.selectedNode;return node?node.cookie:null;}
_getSelectionCookies(){const node=this._dataGrid.selectedNode;const nextNeighbor=node&&node.traverseNextNode(true);const previousNeighbor=node&&node.traversePreviousNode(true);return{current:node&&node.cookie,neighbor:(nextNeighbor&&nextNeighbor.cookie)||(previousNeighbor&&previousNeighbor.cookie)};}
willHide(){this._lastEditedColumnId=null;}
_findSelectedCookie(selectionCookies,cookies){if(!cookies)
return null;const current=selectionCookies.current;const foundCurrent=cookies.find(cookie=>this._isSameCookie(cookie,current));if(foundCurrent)
return foundCurrent;const neighbor=selectionCookies.neighbor;const foundNeighbor=cookies.find(cookie=>this._isSameCookie(cookie,neighbor));if(foundNeighbor)
return foundNeighbor;return null;}
_isSameCookie(cookieA,cookieB){return!!cookieB&&cookieB.name()===cookieA.name()&&cookieB.domain()===cookieA.domain()&&cookieB.path()===cookieA.path();}
_rebuildTable(){const selectionCookies=this._getSelectionCookies();const lastEditedColumnId=this._lastEditedColumnId;this._lastEditedColumnId=null;this._dataGrid.rootNode().removeChildren();for(let i=0;i<this._data.length;++i){const item=this._data[i];const selectedCookie=this._findSelectedCookie(selectionCookies,item.cookies);if(item.folderName){const groupData={name:item.folderName,value:'',domain:'',path:'',expires:'',size:this._totalSize(item.cookies),httpOnly:'',secure:'',sameSite:''};const groupNode=new DataGrid.DataGridNode(groupData);groupNode.selectable=true;this._dataGrid.rootNode().appendChild(groupNode);groupNode.element().classList.add('row-group');this._populateNode(groupNode,item.cookies,selectedCookie,lastEditedColumnId);groupNode.expand();}else{this._populateNode(this._dataGrid.rootNode(),item.cookies,selectedCookie,lastEditedColumnId);}}
if(selectionCookies.current&&lastEditedColumnId&&!this._dataGrid.selectedNode)
this._addInactiveNode(this._dataGrid.rootNode(),selectionCookies.current,lastEditedColumnId);if(this._saveCallback)
this._dataGrid.addCreationNode(false);}
_populateNode(parentNode,cookies,selectedCookie,lastEditedColumnId){parentNode.removeChildren();if(!cookies)
return;this._sortCookies(cookies);for(let i=0;i<cookies.length;++i){const cookie=cookies[i];const cookieNode=this._createGridNode(cookie);parentNode.appendChild(cookieNode);if(this._isSameCookie(cookie,selectedCookie)){cookieNode.select();if(lastEditedColumnId!==null)
this._dataGrid.startEditingNextEditableColumnOfDataGridNode(cookieNode,lastEditedColumnId);}}}
_addInactiveNode(parentNode,cookie,editedColumnId){const cookieNode=this._createGridNode(cookie);parentNode.appendChild(cookieNode);cookieNode.select();cookieNode.setInactive(true);if(editedColumnId!==null)
this._dataGrid.startEditingNextEditableColumnOfDataGridNode(cookieNode,editedColumnId);}
_totalSize(cookies){let totalSize=0;for(let i=0;cookies&&i<cookies.length;++i)
totalSize+=cookies[i].size();return totalSize;}
_sortCookies(cookies){const sortDirection=this._dataGrid.isSortOrderAscending()?1:-1;function getValue(cookie,property){return typeof cookie[property]==='function'?String(cookie[property]()):String(cookie.name());}
function compareTo(property,cookie1,cookie2){return sortDirection*getValue(cookie1,property).compareTo(getValue(cookie2,property));}
function numberCompare(cookie1,cookie2){return sortDirection*(cookie1.size()-cookie2.size());}
function expiresCompare(cookie1,cookie2){if(cookie1.session()!==cookie2.session())
return sortDirection*(cookie1.session()?1:-1);if(cookie1.session())
return 0;if(cookie1.maxAge()&&cookie2.maxAge())
return sortDirection*(cookie1.maxAge()-cookie2.maxAge());if(cookie1.expires()&&cookie2.expires())
return sortDirection*(cookie1.expires()-cookie2.expires());return sortDirection*(cookie1.expires()?1:-1);}
let comparator;const columnId=this._dataGrid.sortColumnId()||'name';if(columnId==='expires')
comparator=expiresCompare;else if(columnId==='size')
comparator=numberCompare;else
comparator=compareTo.bind(null,columnId);cookies.sort(comparator);}
_createGridNode(cookie){const data={};data.name=cookie.name();data.value=cookie.value();if(cookie.type()===SDK.Cookie.Type.Request){data.domain=Common.UIString('N/A');data.path=Common.UIString('N/A');data.expires=Common.UIString('N/A');}else{data.domain=cookie.domain()||'';data.path=cookie.path()||'';if(cookie.maxAge()){data.expires=Number.secondsToString(parseInt(cookie.maxAge(),10));}else if(cookie.expires()){if(cookie.expires()<0)
data.expires=CookieTable.CookiesTable._expiresSessionValue;else
data.expires=new Date(cookie.expires()).toISOString();}else{data.expires=CookieTable.CookiesTable._expiresSessionValue;}}
data.size=cookie.size();const checkmark='\u2713';data.httpOnly=(cookie.httpOnly()?checkmark:'');data.secure=(cookie.secure()?checkmark:'');data.sameSite=cookie.sameSite()||'';const node=new DataGrid.DataGridNode(data);node.cookie=cookie;node.selectable=true;return node;}
_onDeleteCookie(node){if(node.cookie&&this._deleteCallback)
this._deleteCallback(node.cookie,()=>this._refresh());}
_onUpdateCookie(editingNode,columnIdentifier,oldText,newText){this._lastEditedColumnId=columnIdentifier;this._setDefaults(editingNode);if(this._isValidCookieData(editingNode.data))
this._saveNode(editingNode);else
editingNode.setDirty(true);}
_setDefaults(node){if(node.data.name===null)
node.data.name='';if(node.data.value===null)
node.data.value='';if(node.data.domain===null)
node.data.domain=this._cookieDomain;if(node.data.path===null)
node.data.path='/';if(node.data.expires===null)
node.data.expires=CookieTable.CookiesTable._expiresSessionValue;}
_saveNode(node){const oldCookie=node.cookie;const newCookie=this._createCookieFromData(node.data);node.cookie=newCookie;this._saveCallback(newCookie,oldCookie).then(success=>{if(success)
this._refresh();else
node.setDirty(true);});}
_createCookieFromData(data){const cookie=new SDK.Cookie(data.name,data.value,null);cookie.addAttribute('domain',data.domain);cookie.addAttribute('path',data.path);if(data.expires&&data.expires!==CookieTable.CookiesTable._expiresSessionValue)
cookie.addAttribute('expires',(new Date(data.expires)).toUTCString());if(data.httpOnly)
cookie.addAttribute('httpOnly');if(data.secure)
cookie.addAttribute('secure');if(data.sameSite)
cookie.addAttribute('sameSite',data.sameSite);cookie.setSize(data.name.length+data.value.length);return cookie;}
_isValidCookieData(data){return(data.name||data.value)&&this._isValidDomain(data.domain)&&this._isValidPath(data.path)&&this._isValidDate(data.expires);}
_isValidDomain(domain){if(!domain)
return true;const parsedURL=('http://'+domain).asParsedURL();return!!parsedURL&&parsedURL.domain()===domain;}
_isValidPath(path){const parsedURL=('http://example.com'+path).asParsedURL();return!!parsedURL&&parsedURL.path===path;}
_isValidDate(date){return date===''||date===CookieTable.CookiesTable._expiresSessionValue||!isNaN(Date.parse(date));}
_refresh(){if(this._refreshCallback)
this._refreshCallback();}};CookieTable.CookiesTable._expiresSessionValue=Common.UIString('Session');;Coverage.RangeUseCount;Coverage.CoverageSegment;Coverage.CoverageType={CSS:(1<<0),JavaScript:(1<<1),JavaScriptCoarse:(1<<2),};Coverage.CoverageModel=class extends SDK.SDKModel{constructor(target){super(target);this._cpuProfilerModel=target.model(SDK.CPUProfilerModel);this._cssModel=target.model(SDK.CSSModel);this._debuggerModel=target.model(SDK.DebuggerModel);this._coverageByURL=new Map();this._coverageByContentProvider=new Map();this._bestEffortCoveragePromise=null;}
start(){if(this._cssModel){this._clearCSS();this._cssModel.startCoverage();}
if(this._cpuProfilerModel){this._bestEffortCoveragePromise=this._cpuProfilerModel.bestEffortCoverage();this._cpuProfilerModel.startPreciseCoverage();}
return!!(this._cssModel||this._cpuProfilerModel);}
stop(){const pollPromise=this.poll();if(this._cpuProfilerModel)
this._cpuProfilerModel.stopPreciseCoverage();if(this._cssModel)
this._cssModel.stopCoverage();return pollPromise;}
reset(){this._coverageByURL=new Map();this._coverageByContentProvider=new Map();}
async poll(){const updates=await Promise.all([this._takeCSSCoverage(),this._takeJSCoverage()]);return updates[0].concat(updates[1]);}
entries(){return Array.from(this._coverageByURL.values());}
usageForRange(contentProvider,startOffset,endOffset){const coverageInfo=this._coverageByContentProvider.get(contentProvider);return coverageInfo&&coverageInfo.usageForRange(startOffset,endOffset);}
_clearCSS(){for(const entry of this._coverageByContentProvider.values()){if(entry.type()!==Coverage.CoverageType.CSS)
continue;const contentProvider=(entry.contentProvider());this._coverageByContentProvider.delete(contentProvider);const key=`${contentProvider.startLine}:${contentProvider.startColumn}`;const urlEntry=this._coverageByURL.get(entry.url());if(!urlEntry||!urlEntry._coverageInfoByLocation.delete(key))
continue;urlEntry._size-=entry._size;urlEntry._usedSize-=entry._usedSize;if(!urlEntry._coverageInfoByLocation.size)
this._coverageByURL.delete(entry.url());}}
async _takeJSCoverage(){if(!this._cpuProfilerModel)
return[];let rawCoverageData=await this._cpuProfilerModel.takePreciseCoverage();if(this._bestEffortCoveragePromise){const bestEffortCoverage=await this._bestEffortCoveragePromise;this._bestEffortCoveragePromise=null;rawCoverageData=bestEffortCoverage.concat(rawCoverageData);}
return this._processJSCoverage(rawCoverageData);}
_processJSCoverage(scriptsCoverage){const updatedEntries=[];for(const entry of scriptsCoverage){const script=this._debuggerModel.scriptForId(entry.scriptId);if(!script)
continue;const ranges=[];let type=Coverage.CoverageType.JavaScript;for(const func of entry.functions){if(func.isBlockCoverage===false&&!(func.ranges.length===1&&!func.ranges[0].count))
type|=Coverage.CoverageType.JavaScriptCoarse;for(const range of func.ranges)
ranges.push(range);}
const subentry=this._addCoverage(script,script.contentLength,script.lineOffset,script.columnOffset,ranges,type);if(subentry)
updatedEntries.push(subentry);}
return updatedEntries;}
async _takeCSSCoverage(){if(!this._cssModel)
return[];const rawCoverageData=await this._cssModel.takeCoverageDelta();return this._processCSSCoverage(rawCoverageData);}
_processCSSCoverage(ruleUsageList){const updatedEntries=[];const rulesByStyleSheet=new Map();for(const rule of ruleUsageList){const styleSheetHeader=this._cssModel.styleSheetHeaderForId(rule.styleSheetId);if(!styleSheetHeader)
continue;let ranges=rulesByStyleSheet.get(styleSheetHeader);if(!ranges){ranges=[];rulesByStyleSheet.set(styleSheetHeader,ranges);}
ranges.push({startOffset:rule.startOffset,endOffset:rule.endOffset,count:Number(rule.used)});}
for(const entry of rulesByStyleSheet){const styleSheetHeader=(entry[0]);const ranges=(entry[1]);const subentry=this._addCoverage(styleSheetHeader,styleSheetHeader.contentLength,styleSheetHeader.startLine,styleSheetHeader.startColumn,ranges,Coverage.CoverageType.CSS);if(subentry)
updatedEntries.push(subentry);}
return updatedEntries;}
static _convertToDisjointSegments(ranges){ranges.sort((a,b)=>a.startOffset-b.startOffset);const result=[];const stack=[];for(const entry of ranges){let top=stack.peekLast();while(top&&top.endOffset<=entry.startOffset){append(top.endOffset,top.count);stack.pop();top=stack.peekLast();}
append(entry.startOffset,top?top.count:undefined);stack.push(entry);}
while(stack.length){const top=stack.pop();append(top.endOffset,top.count);}
function append(end,count){const last=result.peekLast();if(last){if(last.end===end)
return;if(last.count===count){last.end=end;return;}}
result.push({end:end,count:count});}
return result;}
_addCoverage(contentProvider,contentLength,startLine,startColumn,ranges,type){const url=contentProvider.contentURL();if(!url)
return null;let urlCoverage=this._coverageByURL.get(url);if(!urlCoverage){urlCoverage=new Coverage.URLCoverageInfo(url);this._coverageByURL.set(url,urlCoverage);}
const coverageInfo=urlCoverage._ensureEntry(contentProvider,contentLength,startLine,startColumn,type);this._coverageByContentProvider.set(contentProvider,coverageInfo);const segments=Coverage.CoverageModel._convertToDisjointSegments(ranges);if(segments.length&&segments.peekLast().end<contentLength)
segments.push({end:contentLength});const oldUsedSize=coverageInfo._usedSize;coverageInfo.mergeCoverage(segments);if(coverageInfo._usedSize===oldUsedSize)
return null;urlCoverage._usedSize+=coverageInfo._usedSize-oldUsedSize;return coverageInfo;}
async exportReport(fos){const result=[];for(const urlInfo of this._coverageByURL.values()){const url=urlInfo.url();if(url.startsWith('extensions::')||url.startsWith('chrome-extension://'))
continue;let useFullText=false;for(const info of urlInfo._coverageInfoByLocation.values()){if(info._lineOffset||info._columnOffset){useFullText=!!url;break;}}
let fullText=null;if(useFullText){const resource=SDK.ResourceTreeModel.resourceForURL(url);fullText=resource?new TextUtils.Text(await resource.requestContent()):null;}
if(fullText){const entry={url,ranges:[],text:fullText.value()};for(const info of urlInfo._coverageInfoByLocation.values()){const offset=fullText?fullText.offsetFromPosition(info._lineOffset,info._columnOffset):0;let start=0;for(const segment of info._segments){if(segment.count)
entry.ranges.push({start:start+offset,end:segment.end+offset});else
start=segment.end;}}
result.push(entry);continue;}
for(const info of urlInfo._coverageInfoByLocation.values()){const entry={url,ranges:[],text:await info.contentProvider().requestContent()};let start=0;for(const segment of info._segments){if(segment.count)
entry.ranges.push({start:start,end:segment.end});else
start=segment.end;}
result.push(entry);}}
await fos.write(JSON.stringify(result,undefined,2));fos.close();}};Coverage.URLCoverageInfo=class{constructor(url){this._url=url;this._coverageInfoByLocation=new Map();this._size=0;this._usedSize=0;this._type;this._isContentScript=false;}
url(){return this._url;}
type(){return this._type;}
size(){return this._size;}
usedSize(){return this._usedSize;}
unusedSize(){return this._size-this._usedSize;}
isContentScript(){return this._isContentScript;}
_ensureEntry(contentProvider,contentLength,lineOffset,columnOffset,type){const key=`${lineOffset}:${columnOffset}`;let entry=this._coverageInfoByLocation.get(key);if((type&Coverage.CoverageType.JavaScript)&&!this._coverageInfoByLocation.size)
this._isContentScript=(contentProvider).isContentScript();this._type|=type;if(entry){entry._coverageType|=type;return entry;}
if((type&Coverage.CoverageType.JavaScript)&&!this._coverageInfoByLocation.size)
this._isContentScript=(contentProvider).isContentScript();entry=new Coverage.CoverageInfo(contentProvider,contentLength,lineOffset,columnOffset,type);this._coverageInfoByLocation.set(key,entry);this._size+=contentLength;return entry;}};Coverage.CoverageInfo=class{constructor(contentProvider,size,lineOffset,columnOffset,type){this._contentProvider=contentProvider;this._size=size;this._usedSize=0;this._lineOffset=lineOffset;this._columnOffset=columnOffset;this._coverageType=type;this._segments=[];}
contentProvider(){return this._contentProvider;}
url(){return this._contentProvider.contentURL();}
type(){return this._coverageType;}
mergeCoverage(segments){this._segments=Coverage.CoverageInfo._mergeCoverage(this._segments,segments);this._updateStats();}
usageForRange(start,end){let index=this._segments.upperBound(start,(position,segment)=>position-segment.end);for(;index<this._segments.length&&this._segments[index].end<end;++index){if(this._segments[index].count)
return true;}
return index<this._segments.length&&!!this._segments[index].count;}
static _mergeCoverage(segmentsA,segmentsB){const result=[];let indexA=0;let indexB=0;while(indexA<segmentsA.length&&indexB<segmentsB.length){const a=segmentsA[indexA];const b=segmentsB[indexB];const count=typeof a.count==='number'||typeof b.count==='number'?(a.count||0)+(b.count||0):undefined;const end=Math.min(a.end,b.end);const last=result.peekLast();if(!last||last.count!==count)
result.push({end:end,count:count});else
last.end=end;if(a.end<=b.end)
indexA++;if(a.end>=b.end)
indexB++;}
for(;indexA<segmentsA.length;indexA++)
result.push(segmentsA[indexA]);for(;indexB<segmentsB.length;indexB++)
result.push(segmentsB[indexB]);return result;}
_updateStats(){this._usedSize=0;let last=0;for(const segment of this._segments){if(segment.count)
this._usedSize+=segment.end-last;last=segment.end;}}};;Coverage.CoverageListView=class extends UI.VBox{constructor(filterCallback){super(true);this._nodeForCoverageInfo=new Map();this._filterCallback=filterCallback;this._highlightRegExp=null;this.registerRequiredCSS('coverage/coverageListView.css');const columns=[{id:'url',title:Common.UIString('URL'),width:'250px',fixedWidth:false,sortable:true},{id:'type',title:Common.UIString('Type'),width:'45px',fixedWidth:true,sortable:true},{id:'size',title:Common.UIString('Total Bytes'),width:'60px',fixedWidth:true,sortable:true,align:DataGrid.DataGrid.Align.Right},{id:'unusedSize',title:Common.UIString('Unused Bytes'),width:'100px',fixedWidth:true,sortable:true,align:DataGrid.DataGrid.Align.Right,sort:DataGrid.DataGrid.Order.Descending},{id:'bars',title:'',width:'250px',fixedWidth:false,sortable:true}];this._dataGrid=new DataGrid.SortableDataGrid(columns);this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);this._dataGrid.element.classList.add('flex-auto');this._dataGrid.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.OpenedNode,this._onOpenedNode,this);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortingChanged,this);const dataGridWidget=this._dataGrid.asWidget();dataGridWidget.show(this.contentElement);}
update(coverageInfo){let hadUpdates=false;const maxSize=coverageInfo.reduce((acc,entry)=>Math.max(acc,entry.size()),0);const rootNode=this._dataGrid.rootNode();for(const entry of coverageInfo){let node=this._nodeForCoverageInfo.get(entry);if(node){if(this._filterCallback(node._coverageInfo))
hadUpdates=node._refreshIfNeeded(maxSize)||hadUpdates;continue;}
node=new Coverage.CoverageListView.GridNode(entry,maxSize);this._nodeForCoverageInfo.set(entry,node);if(this._filterCallback(node._coverageInfo)){rootNode.appendChild(node);hadUpdates=true;}}
if(hadUpdates)
this._sortingChanged();}
reset(){this._nodeForCoverageInfo.clear();this._dataGrid.rootNode().removeChildren();}
updateFilterAndHighlight(highlightRegExp){this._highlightRegExp=highlightRegExp;let hadTreeUpdates=false;for(const node of this._nodeForCoverageInfo.values()){const shouldBeVisible=this._filterCallback(node._coverageInfo);const isVisible=!!node.parent;if(shouldBeVisible)
node._setHighlight(this._highlightRegExp);if(shouldBeVisible===isVisible)
continue;hadTreeUpdates=true;if(!shouldBeVisible)
node.remove();else
this._dataGrid.rootNode().appendChild(node);}
if(hadTreeUpdates)
this._sortingChanged();}
_onOpenedNode(){this._revealSourceForSelectedNode();}
_onKeyDown(event){if(!isEnterKey(event))
return;event.consume(true);this._revealSourceForSelectedNode();}
async _revealSourceForSelectedNode(){const node=this._dataGrid.selectedNode;if(!node)
return;const coverageInfo=(node)._coverageInfo;let sourceCode=Workspace.workspace.uiSourceCodeForURL(coverageInfo.url());if(!sourceCode)
return;const content=await sourceCode.requestContent();if(TextUtils.isMinified(content)){const formatData=await Sources.sourceFormatter.format(sourceCode);sourceCode=formatData.formattedSourceCode;}
if(this._dataGrid.selectedNode!==node)
return;Common.Revealer.reveal(sourceCode);}
_sortingChanged(){const columnId=this._dataGrid.sortColumnId();if(!columnId)
return;let sortFunction;switch(columnId){case'url':sortFunction=compareURL;break;case'type':sortFunction=compareType;break;case'size':sortFunction=compareNumericField.bind(null,'size');break;case'bars':case'unusedSize':sortFunction=compareNumericField.bind(null,'unusedSize');break;default:console.assert(false,'Unknown sort field: '+columnId);return;}
this._dataGrid.sortNodes(sortFunction,!this._dataGrid.isSortOrderAscending());function compareURL(a,b){const nodeA=(a);const nodeB=(b);return nodeA._url.localeCompare(nodeB._url);}
function compareNumericField(fieldName,a,b){const nodeA=(a);const nodeB=(b);return nodeA._coverageInfo[fieldName]()-nodeB._coverageInfo[fieldName]()||compareURL(a,b);}
function compareType(a,b){const nodeA=(a);const nodeB=(b);const typeA=Coverage.CoverageListView._typeToString(nodeA._coverageInfo.type());const typeB=Coverage.CoverageListView._typeToString(nodeB._coverageInfo.type());return typeA.localeCompare(typeB)||compareURL(a,b);}}
static _typeToString(type){const types=[];if(type&Coverage.CoverageType.CSS)
types.push(Common.UIString('CSS'));if(type&Coverage.CoverageType.JavaScriptCoarse)
types.push(Common.UIString('JS (coarse)'));else if(type&Coverage.CoverageType.JavaScript)
types.push(Common.UIString('JS'));return types.join('+');}};Coverage.CoverageListView.GridNode=class extends DataGrid.SortableDataGridNode{constructor(coverageInfo,maxSize){super();this._coverageInfo=coverageInfo;this._lastUsedSize;this._url=coverageInfo.url();this._maxSize=maxSize;this._highlightDOMChanges=[];this._highlightRegExp=null;}
_setHighlight(highlightRegExp){if(this._highlightRegExp===highlightRegExp)
return;this._highlightRegExp=highlightRegExp;this.refresh();}
_refreshIfNeeded(maxSize){if(this._lastUsedSize===this._coverageInfo.usedSize()&&maxSize===this._maxSize)
return false;this._lastUsedSize=this._coverageInfo.usedSize();this._maxSize=maxSize;this.refresh();return true;}
createCell(columnId){const cell=this.createTD(columnId);switch(columnId){case'url':cell.title=this._url;const outer=cell.createChild('div','url-outer');const prefix=outer.createChild('div','url-prefix');const suffix=outer.createChild('div','url-suffix');const splitURL=/^(.*)(\/[^/]*)$/.exec(this._url);prefix.textContent=splitURL?splitURL[1]:this._url;suffix.textContent=splitURL?splitURL[2]:'';if(this._highlightRegExp)
this._highlight(outer,this._url);break;case'type':cell.textContent=Coverage.CoverageListView._typeToString(this._coverageInfo.type());if(this._coverageInfo.type()&Coverage.CoverageType.JavaScriptCoarse)
cell.title=Common.UIString('JS coverage is function-level only. Reload the page for block-level coverage.');break;case'size':cell.textContent=Number.withThousandsSeparator(this._coverageInfo.size()||0);break;case'unusedSize':const unusedSize=this._coverageInfo.unusedSize()||0;const unusedSizeSpan=cell.createChild('span');const unusedPercentsSpan=cell.createChild('span','percent-value');unusedSizeSpan.textContent=Number.withThousandsSeparator(unusedSize);unusedPercentsSpan.textContent=Common.UIString('%.1f\xa0%%',unusedSize/this._coverageInfo.size()*100);break;case'bars':const barContainer=cell.createChild('div','bar-container');const unusedSizeBar=barContainer.createChild('div','bar bar-unused-size');unusedSizeBar.style.width=(100*this._coverageInfo.unusedSize()/this._maxSize).toFixed(4)+'%';const usedSizeBar=barContainer.createChild('div','bar bar-used-size');usedSizeBar.style.width=(100*this._coverageInfo.usedSize()/this._maxSize).toFixed(4)+'%';}
return cell;}
_highlight(element,textContent){const matches=this._highlightRegExp.exec(textContent);if(!matches||!matches.length)
return;const range=new TextUtils.SourceRange(matches.index,matches[0].length);UI.highlightRangesWithStyleClass(element,[range],'filter-highlight');}};;Coverage.CoverageView=class extends UI.VBox{constructor(){super(true);this._model=null;this._pollTimer;this._decorationManager=null;this._resourceTreeModel=null;this.registerRequiredCSS('coverage/coverageView.css');const toolbarContainer=this.contentElement.createChild('div','coverage-toolbar-container');const toolbar=new UI.Toolbar('coverage-toolbar',toolbarContainer);this._toggleRecordAction=(UI.actionRegistry.action('coverage.toggle-recording'));this._toggleRecordButton=UI.Toolbar.createActionButton(this._toggleRecordAction);toolbar.appendToolbarItem(this._toggleRecordButton);const mainTarget=SDK.targetManager.mainTarget();if(mainTarget&&mainTarget.model(SDK.ResourceTreeModel)){const startWithReloadAction=(UI.actionRegistry.action('coverage.start-with-reload'));this._startWithReloadButton=UI.Toolbar.createActionButton(startWithReloadAction);toolbar.appendToolbarItem(this._startWithReloadButton);}
this._clearButton=new UI.ToolbarButton(Common.UIString('Clear all'),'largeicon-clear');this._clearButton.addEventListener(UI.ToolbarButton.Events.Click,this._clear.bind(this));toolbar.appendToolbarItem(this._clearButton);toolbar.appendSeparator();const saveButton=new UI.ToolbarButton(Common.UIString('Export...'),'largeicon-download');saveButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._exportReport());toolbar.appendToolbarItem(saveButton);this._textFilterRegExp=null;toolbar.appendSeparator();this._filterInput=new UI.ToolbarInput(Common.UIString('URL filter'),0.4,1);this._filterInput.setEnabled(false);this._filterInput.addEventListener(UI.ToolbarInput.Event.TextChanged,this._onFilterChanged,this);toolbar.appendToolbarItem(this._filterInput);toolbar.appendSeparator();this._showContentScriptsSetting=Common.settings.createSetting('showContentScripts',false);this._showContentScriptsSetting.addChangeListener(this._onFilterChanged,this);const contentScriptsCheckbox=new UI.ToolbarSettingCheckbox(this._showContentScriptsSetting,Common.UIString('Include extension content scripts'),Common.UIString('Content scripts'));toolbar.appendToolbarItem(contentScriptsCheckbox);this._coverageResultsElement=this.contentElement.createChild('div','coverage-results');this._landingPage=this._buildLandingPage();this._listView=new Coverage.CoverageListView(this._isVisible.bind(this,false));this._statusToolbarElement=this.contentElement.createChild('div','coverage-toolbar-summary');this._statusMessageElement=this._statusToolbarElement.createChild('div','coverage-message');this._landingPage.show(this._coverageResultsElement);}
_buildLandingPage(){const recordButton=UI.createInlineButton(UI.Toolbar.createActionButton(this._toggleRecordAction));const widget=new UI.VBox();let message;if(this._startWithReloadButton){const reloadButton=UI.createInlineButton(UI.Toolbar.createActionButtonForId('coverage.start-with-reload'));message=UI.formatLocalized('Click the record button %s to start capturing coverage.\nClick the reload button %s to reload and start capturing coverage.',[recordButton,reloadButton]);}else{message=UI.formatLocalized('Click the record button %s to start capturing coverage.',[recordButton]);}
message.classList.add('message');widget.contentElement.appendChild(message);widget.element.classList.add('landing-page');return widget;}
_clear(){this._model=null;this._reset();}
_reset(){if(this._decorationManager){this._decorationManager.dispose();this._decorationManager=null;}
this._listView.reset();this._listView.detach();this._landingPage.show(this._coverageResultsElement);this._statusMessageElement.textContent='';this._filterInput.setEnabled(false);}
_toggleRecording(){const enable=!this._toggleRecordAction.toggled();if(enable)
this._startRecording(false);else
this._stopRecording();}
_startRecording(reload){this._reset();const mainTarget=SDK.targetManager.mainTarget();if(!mainTarget)
return;if(!this._model||reload)
this._model=new Coverage.CoverageModel(mainTarget);Host.userMetrics.actionTaken(Host.UserMetrics.Action.CoverageStarted);if(!this._model.start())
return;this._resourceTreeModel=(mainTarget.model(SDK.ResourceTreeModel));if(this._resourceTreeModel){this._resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this);}
this._decorationManager=new Coverage.CoverageDecorationManager(this._model);this._toggleRecordAction.setToggled(true);this._clearButton.setEnabled(false);if(this._startWithReloadButton)
this._startWithReloadButton.setEnabled(false);this._filterInput.setEnabled(true);if(this._landingPage.isShowing())
this._landingPage.detach();this._listView.show(this._coverageResultsElement);if(reload&&this._resourceTreeModel)
this._resourceTreeModel.reloadPage();else
this._poll();}
async _poll(){delete this._pollTimer;const updates=await this._model.poll();this._updateViews(updates);this._pollTimer=setTimeout(()=>this._poll(),700);}
async _stopRecording(){if(this._pollTimer){clearTimeout(this._pollTimer);delete this._pollTimer;}
if(this._resourceTreeModel){this._resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this);this._resourceTreeModel=null;}
const updatedEntries=await this._model.stop();this._updateViews(updatedEntries);this._toggleRecordAction.setToggled(false);if(this._startWithReloadButton)
this._startWithReloadButton.setEnabled(true);this._clearButton.setEnabled(true);}
_onMainFrameNavigated(){this._model.reset();this._decorationManager.reset();this._listView.reset();this._poll();}
async _updateViews(updatedEntries){this._updateStats();this._listView.update(this._model.entries());this._decorationManager.update(updatedEntries);}
_updateStats(){let total=0;let unused=0;for(const info of this._model.entries()){if(!this._isVisible(true,info))
continue;total+=info.size();unused+=info.unusedSize();}
const percentUnused=total?Math.round(100*unused/total):0;this._statusMessageElement.textContent=Common.UIString('%s of %s bytes are not used. (%d%%)',Number.bytesToString(unused),Number.bytesToString(total),percentUnused);}
_onFilterChanged(){if(!this._listView)
return;const text=this._filterInput.value();this._textFilterRegExp=text?createPlainTextSearchRegex(text,'i'):null;this._listView.updateFilterAndHighlight(this._textFilterRegExp);this._updateStats();}
_isVisible(ignoreTextFilter,coverageInfo){const url=coverageInfo.url();if(url.startsWith(Coverage.CoverageView._extensionBindingsURLPrefix))
return false;if(coverageInfo.isContentScript()&&!this._showContentScriptsSetting.get())
return false;return ignoreTextFilter||!this._textFilterRegExp||this._textFilterRegExp.test(url);}
async _exportReport(){const fos=new Bindings.FileOutputStream();const fileName=`Coverage-${new Date().toISO8601Compact()}.json`;const accepted=await fos.open(fileName);if(!accepted)
return;this._model.exportReport(fos);}};Coverage.CoverageView._extensionBindingsURLPrefix='extensions::';Coverage.CoverageView.ActionDelegate=class{handleAction(context,actionId){const coverageViewId='coverage';UI.viewManager.showView(coverageViewId).then(()=>UI.viewManager.view(coverageViewId).widget()).then(widget=>this._innerHandleAction((widget),actionId));return true;}
_innerHandleAction(coverageView,actionId){switch(actionId){case'coverage.toggle-recording':coverageView._toggleRecording();break;case'coverage.start-with-reload':coverageView._startRecording(true);break;default:console.assert(false,`Unknown action: ${actionId}`);}}};;Coverage.RawLocation;Coverage.CoverageDecorationManager=class{constructor(coverageModel){this._coverageModel=coverageModel;this._textByProvider=new Map();this._uiSourceCodeByContentProvider=new Multimap();this._documentUISouceCodeToStylesheets=new WeakMap();for(const uiSourceCode of Workspace.workspace.uiSourceCodes())
uiSourceCode.addLineDecoration(0,Coverage.CoverageDecorationManager._decoratorType,this);Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._onUISourceCodeAdded,this);}
reset(){for(const uiSourceCode of Workspace.workspace.uiSourceCodes())
uiSourceCode.removeDecorationsForType(Coverage.CoverageDecorationManager._decoratorType);}
dispose(){this.reset();Workspace.workspace.removeEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._onUISourceCodeAdded,this);}
update(updatedEntries){for(const entry of updatedEntries){for(const uiSourceCode of this._uiSourceCodeByContentProvider.get(entry.contentProvider())){uiSourceCode.removeDecorationsForType(Coverage.CoverageDecorationManager._decoratorType);uiSourceCode.addLineDecoration(0,Coverage.CoverageDecorationManager._decoratorType,this);}}}
async usageByLine(uiSourceCode){const result=[];const sourceText=new TextUtils.Text(uiSourceCode.content()||'');await this._updateTexts(uiSourceCode,sourceText);const lineEndings=sourceText.lineEndings();for(let line=0;line<sourceText.lineCount();++line){const lineLength=lineEndings[line]-(line?lineEndings[line-1]:0)-1;if(!lineLength){result.push(undefined);continue;}
const startLocations=this._rawLocationsForSourceLocation(uiSourceCode,line,0);const endLocations=this._rawLocationsForSourceLocation(uiSourceCode,line,lineLength);let used=undefined;for(let startIndex=0,endIndex=0;startIndex<startLocations.length;++startIndex){const start=startLocations[startIndex];while(endIndex<endLocations.length&&Coverage.CoverageDecorationManager._compareLocations(start,endLocations[endIndex])>=0)
++endIndex;if(endIndex>=endLocations.length||endLocations[endIndex].id!==start.id)
continue;const end=endLocations[endIndex++];const text=this._textByProvider.get(end.contentProvider);if(!text)
continue;const textValue=text.value();let startOffset=Math.min(text.offsetFromPosition(start.line,start.column),textValue.length-1);let endOffset=Math.min(text.offsetFromPosition(end.line,end.column),textValue.length-1);while(startOffset<=endOffset&&/\s/.test(textValue[startOffset]))
++startOffset;while(startOffset<=endOffset&&/\s/.test(textValue[endOffset]))
--endOffset;if(startOffset<=endOffset)
used=this._coverageModel.usageForRange(end.contentProvider,startOffset,endOffset);if(used)
break;}
result.push(used);}
return result;}
_updateTexts(uiSourceCode,text){const promises=[];for(let line=0;line<text.lineCount();++line){for(const entry of this._rawLocationsForSourceLocation(uiSourceCode,line,0)){if(this._textByProvider.has(entry.contentProvider))
continue;this._textByProvider.set(entry.contentProvider,null);this._uiSourceCodeByContentProvider.set(entry.contentProvider,uiSourceCode);promises.push(this._updateTextForProvider(entry.contentProvider));}}
return Promise.all(promises);}
async _updateTextForProvider(contentProvider){const content=await contentProvider.requestContent();this._textByProvider.set(contentProvider,new TextUtils.Text(content));}
_rawLocationsForSourceLocation(uiSourceCode,line,column){const result=[];const contentType=uiSourceCode.contentType();if(contentType.hasScripts()){let locations=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode,line,column);locations=locations.filter(location=>!!location.script());for(let location of locations){const script=location.script();if(script.isInlineScript()&&contentType.isDocument()){if(comparePositions(script.lineOffset,script.columnOffset,location.lineNumber,location.columnNumber)>0||comparePositions(script.endLine,script.endColumn,location.lineNumber,location.columnNumber)<=0){location=null;}else{location.lineNumber-=script.lineOffset;if(!location.lineNumber)
location.columnNumber-=script.columnOffset;}}
if(location){result.push({id:`js:${location.scriptId}`,contentProvider:location.script(),line:location.lineNumber,column:location.columnNumber});}}}
if(contentType.isStyleSheet()||contentType.isDocument()){const rawStyleLocations=contentType.isDocument()?this._documentUILocationToCSSRawLocations(uiSourceCode,line,column):Bindings.cssWorkspaceBinding.uiLocationToRawLocations(new Workspace.UILocation(uiSourceCode,line,column));for(const location of rawStyleLocations){const header=location.header();if(!header)
continue;if(header.isInline&&contentType.isDocument()){location.lineNumber-=header.startLine;if(!location.lineNumber)
location.columnNumber-=header.startColumn;}
result.push({id:`css:${location.styleSheetId}`,contentProvider:location.header(),line:location.lineNumber,column:location.columnNumber});}}
result.sort(Coverage.CoverageDecorationManager._compareLocations);function comparePositions(aLine,aColumn,bLine,bColumn){return aLine-bLine||aColumn-bColumn;}
return result;}
_documentUILocationToCSSRawLocations(uiSourceCode,line,column){let stylesheets=this._documentUISouceCodeToStylesheets.get(uiSourceCode);if(!stylesheets){stylesheets=[];const cssModel=this._coverageModel.target().model(SDK.CSSModel);if(!cssModel)
return[];for(const headerId of cssModel.styleSheetIdsForURL(uiSourceCode.url())){const header=cssModel.styleSheetHeaderForId(headerId);if(header)
stylesheets.push(header);}
stylesheets.sort(stylesheetComparator);this._documentUISouceCodeToStylesheets.set(uiSourceCode,stylesheets);}
const endIndex=stylesheets.upperBound(undefined,(unused,header)=>line-header.startLine||column-header.startColumn);if(!endIndex)
return[];const locations=[];const last=stylesheets[endIndex-1];for(let index=endIndex-1;index>=0&&stylesheets[index].startLine===last.startLine&&stylesheets[index].startColumn===last.startColumn;--index)
locations.push(new SDK.CSSLocation(stylesheets[index],line,column));return locations;function stylesheetComparator(a,b){return a.startLine-b.startLine||a.startColumn-b.startColumn||a.id.localeCompare(b.id);}}
static _compareLocations(a,b){return a.id.localeCompare(b.id)||a.line-b.line||a.column-b.column;}
_onUISourceCodeAdded(event){const uiSourceCode=(event.data);uiSourceCode.addLineDecoration(0,Coverage.CoverageDecorationManager._decoratorType,this);}};Coverage.CoverageDecorationManager._decoratorType='coverage';Coverage.CoverageView.LineDecorator=class{decorate(uiSourceCode,textEditor){const decorations=uiSourceCode.decorationsForType(Coverage.CoverageDecorationManager._decoratorType);if(!decorations||!decorations.size){textEditor.uninstallGutter(Coverage.CoverageView.LineDecorator._gutterType);return;}
const decorationManager=(decorations.values().next().value.data());decorationManager.usageByLine(uiSourceCode).then(lineUsage=>{textEditor.operation(()=>this._innerDecorate(textEditor,lineUsage));});}
_innerDecorate(textEditor,lineUsage){const gutterType=Coverage.CoverageView.LineDecorator._gutterType;textEditor.uninstallGutter(gutterType);textEditor.installGutter(gutterType,false);for(let line=0;line<lineUsage.length;++line){if(typeof lineUsage[line]!=='boolean')
continue;const className=lineUsage[line]?'text-editor-coverage-used-marker':'text-editor-coverage-unused-marker';textEditor.setGutterDecoration(line,gutterType,createElementWithClass('div',className));}}};Coverage.CoverageView.LineDecorator._gutterType='CodeMirror-gutter-coverage';;Runtime.cachedResources["coverage/coverageListView.css"]=".data-grid {\n border: none;\n}\n\n.data-grid td .url-outer {\n width: 100%;\n display: inline-flex;\n justify-content: flex-start;\n}\n\n.data-grid td .url-outer .filter-highlight {\n font-weight: bold;\n}\n\n.data-grid td .url-prefix {\n overflow-x: hidden;\n text-overflow: ellipsis;\n}\n\n.data-grid td .url-suffix {\n flex: none;\n}\n\n.data-grid td .bar {\n display: inline-block;\n height: 8px;\n}\n\n.data-grid .selected td .bar {\n border-top: 1px white solid;\n border-bottom: 1px white solid;\n}\n\n.data-grid .selected td .bar:last-child {\n border-right: 1px white solid;\n}\n\n.data-grid .selected td .bar:first-child {\n border-left: 1px white solid;\n}\n\n.data-grid td .bar-container {\n}\n\n.data-grid td .bar-unused-size {\n background-color: #E57373;\n}\n\n.data-grid td .bar-used-size {\n background-color: #81C784;\n}\n\n.data-grid td .percent-value {\n color: #888;\n width: 45px;\n display: inline-block;\n}\n\n.data-grid:focus tr.selected span.percent-value {\n color: #eee;\n}\n\n/*# sourceURL=coverage/coverageListView.css */";Runtime.cachedResources["coverage/coverageView.css"]="/*\n * Copyright (c) 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow: hidden;\n}\n\n.coverage-toolbar-container {\n display: flex;\n border-bottom: 1px solid #ccc;\n flex: 0 0 auto;\n}\n\n.coverage-toolbar {\n display: inline-block;\n}\n\n.coverage-toolbar-summary {\n background-color: #eee;\n border-top: 1px solid #ccc;\n padding-left: 5px;\n flex: 0 0 19px;\n display: flex;\n padding-right: 5px;\n}\n\n.coverage-toolbar-summary .coverage-message {\n padding-top: 2px;\n padding-left: 1ex;\n text-overflow: ellipsis;\n white-space: nowrap;\n overflow: hidden;\n}\n\n.coverage-results {\n overflow-y: auto;\n display: flex;\n flex: auto;\n}\n\n.landing-page {\n justify-content: center;\n align-items: center;\n padding: 20px;\n}\n\n.landing-page .message {\n white-space: pre-line;\n}\n\n/*# sourceURL=coverage/coverageView.css */";DataGrid.DataGrid=class extends Common.Object{constructor(columnsArray,editCallback,deleteCallback,refreshCallback){super();this.element=createElementWithClass('div','data-grid');UI.appendStyle(this.element,'data_grid/dataGrid.css');this.element.tabIndex=0;this.element.addEventListener('keydown',this._keyDown.bind(this),false);this.element.addEventListener('contextmenu',this._contextMenu.bind(this),true);this._editCallback=editCallback;this._deleteCallback=deleteCallback;this._refreshCallback=refreshCallback;const headerContainer=this.element.createChild('div','header-container');this._headerTable=headerContainer.createChild('table','header');this._headerTableHeaders={};this._scrollContainer=this.element.createChild('div','data-container');this._dataTable=this._scrollContainer.createChild('table','data');if(editCallback)
this._dataTable.addEventListener('dblclick',this._ondblclick.bind(this),false);this._dataTable.addEventListener('mousedown',this._mouseDownInDataTable.bind(this));this._dataTable.addEventListener('click',this._clickInDataTable.bind(this),true);this._inline=false;this._columnsArray=[];this._columns={};this._visibleColumnsArray=columnsArray;columnsArray.forEach(column=>this._innerAddColumn(column));this._cellClass=null;this._headerTableColumnGroup=this._headerTable.createChild('colgroup');this._headerTableBody=this._headerTable.createChild('tbody');this._headerRow=this._headerTableBody.createChild('tr');this._dataTableColumnGroup=this._dataTable.createChild('colgroup');this.dataTableBody=this._dataTable.createChild('tbody');this._topFillerRow=this.dataTableBody.createChild('tr','data-grid-filler-row revealed');this._bottomFillerRow=this.dataTableBody.createChild('tr','data-grid-filler-row revealed');this.setVerticalPadding(0,0);this._refreshHeader();this._editing=false;this.selectedNode=null;this.expandNodesWhenArrowing=false;this.setRootNode((new DataGrid.DataGridNode()));this.indentWidth=15;this._resizers=[];this._columnWidthsInitialized=false;this._cornerWidth=DataGrid.DataGrid.CornerWidth;this._resizeMethod=DataGrid.DataGrid.ResizeMethod.Nearest;this._headerContextMenuCallback=null;this._rowContextMenuCallback=null;}
static setElementText(element,newText,longText){if(longText&&newText.length>1000){element.textContent=newText.trimEnd(1000);element.title=newText;element[DataGrid.DataGrid._longTextSymbol]=newText;}else{element.textContent=newText;element.title='';element[DataGrid.DataGrid._longTextSymbol]=undefined;}}
setStriped(isStriped){this.element.classList.toggle('striped-data-grid',isStriped);}
headerTableBody(){return this._headerTableBody;}
_innerAddColumn(column,position){const columnId=column.id;if(columnId in this._columns)
this._innerRemoveColumn(columnId);if(position===undefined)
position=this._columnsArray.length;this._columnsArray.splice(position,0,column);this._columns[columnId]=column;if(column.disclosure)
this.disclosureColumnId=columnId;const cell=createElement('th');cell.className=columnId+'-column';cell[DataGrid.DataGrid._columnIdSymbol]=columnId;this._headerTableHeaders[columnId]=cell;const div=createElement('div');if(column.titleDOMFragment)
div.appendChild(column.titleDOMFragment);else
div.textContent=column.title;cell.appendChild(div);if(column.sort){cell.classList.add(column.sort);this._sortColumnCell=cell;}
if(column.sortable){cell.addEventListener('click',this._clickInHeaderCell.bind(this),false);cell.classList.add('sortable');const icon=UI.Icon.create('','sort-order-icon');cell.createChild('div','sort-order-icon-container').appendChild(icon);cell[DataGrid.DataGrid._sortIconSymbol]=icon;}}
addColumn(column,position){this._innerAddColumn(column,position);}
_innerRemoveColumn(columnId){const column=this._columns[columnId];if(!column)
return;delete this._columns[columnId];const index=this._columnsArray.findIndex(columnConfig=>columnConfig.id===columnId);this._columnsArray.splice(index,1);const cell=this._headerTableHeaders[columnId];if(cell.parentElement)
cell.parentElement.removeChild(cell);delete this._headerTableHeaders[columnId];}
removeColumn(columnId){this._innerRemoveColumn(columnId);}
setCellClass(cellClass){this._cellClass=cellClass;}
_refreshHeader(){this._headerTableColumnGroup.removeChildren();this._dataTableColumnGroup.removeChildren();this._headerRow.removeChildren();this._topFillerRow.removeChildren();this._bottomFillerRow.removeChildren();for(let i=0;i<this._visibleColumnsArray.length;++i){const column=this._visibleColumnsArray[i];const columnId=column.id;const headerColumn=this._headerTableColumnGroup.createChild('col');const dataColumn=this._dataTableColumnGroup.createChild('col');if(column.width){headerColumn.style.width=column.width;dataColumn.style.width=column.width;}
this._headerRow.appendChild(this._headerTableHeaders[columnId]);this._topFillerRow.createChild('td','top-filler-td');this._bottomFillerRow.createChild('td','bottom-filler-td')[DataGrid.DataGrid._columnIdSymbol]=columnId;}
this._headerRow.createChild('th','corner');this._topFillerRow.createChild('td','corner').classList.add('top-filler-td');this._bottomFillerRow.createChild('td','corner').classList.add('bottom-filler-td');this._headerTableColumnGroup.createChild('col','corner');this._dataTableColumnGroup.createChild('col','corner');}
setVerticalPadding(top,bottom){const topPx=top+'px';const bottomPx=(top||bottom)?bottom+'px':'auto';if(this._topFillerRow.style.height===topPx&&this._bottomFillerRow.style.height===bottomPx)
return;this._topFillerRow.style.height=topPx;this._bottomFillerRow.style.height=bottomPx;this.dispatchEventToListeners(DataGrid.DataGrid.Events.PaddingChanged);}
setRootNode(rootNode){if(this._rootNode){this._rootNode.removeChildren();this._rootNode.dataGrid=null;this._rootNode._isRoot=false;}
this._rootNode=rootNode;rootNode._isRoot=true;rootNode.setHasChildren(false);rootNode._expanded=true;rootNode._revealed=true;rootNode.selectable=false;rootNode.dataGrid=this;}
rootNode(){return this._rootNode;}
_ondblclick(event){if(this._editing||this._editingNode)
return;const columnId=this.columnIdFromNode((event.target));if(!columnId||!this._columns[columnId].editable)
return;this._startEditing((event.target));}
_startEditingColumnOfDataGridNode(node,cellIndex){this._editing=true;this._editingNode=node;this._editingNode.select();const element=this._editingNode._element.children[cellIndex];UI.InplaceEditor.startEditing(element,this._startEditingConfig(element));element.getComponentSelection().selectAllChildren(element);}
startEditingNextEditableColumnOfDataGridNode(node,columnIdentifier){const column=this._columns[columnIdentifier];const cellIndex=this._visibleColumnsArray.indexOf(column);const nextEditableColumn=this._nextEditableColumn(cellIndex);if(nextEditableColumn!==-1)
this._startEditingColumnOfDataGridNode(node,nextEditableColumn);}
_startEditing(target){const element=(target.enclosingNodeOrSelfWithNodeName('td'));if(!element)
return;this._editingNode=this.dataGridNodeFromNode(target);if(!this._editingNode){if(!this.creationNode)
return;this._editingNode=this.creationNode;}
if(this._editingNode.isCreationNode){this._startEditingColumnOfDataGridNode(this._editingNode,this._nextEditableColumn(-1));return;}
this._editing=true;if(element[DataGrid.DataGrid._longTextSymbol])
element.textContent=element[DataGrid.DataGrid._longTextSymbol];UI.InplaceEditor.startEditing(element,this._startEditingConfig(element));element.getComponentSelection().selectAllChildren(element);}
renderInline(){this.element.classList.add('inline');this._cornerWidth=0;this._inline=true;this.updateWidths();}
_startEditingConfig(element){return new UI.InplaceEditor.Config(this._editingCommitted.bind(this),this._editingCancelled.bind(this));}
_editingCommitted(element,newText,oldText,context,moveDirection){const columnId=this.columnIdFromNode(element);if(!columnId){this._editingCancelled(element);return;}
const column=this._columns[columnId];const cellIndex=this._visibleColumnsArray.indexOf(column);const textBeforeEditing=(this._editingNode.data[columnId]||'');const currentEditingNode=this._editingNode;function moveToNextIfNeeded(wasChange){if(!moveDirection)
return;if(moveDirection==='forward'){const firstEditableColumn=this._nextEditableColumn(-1);if(currentEditingNode.isCreationNode&&cellIndex===firstEditableColumn&&!wasChange)
return;const nextEditableColumn=this._nextEditableColumn(cellIndex);if(nextEditableColumn!==-1){this._startEditingColumnOfDataGridNode(currentEditingNode,nextEditableColumn);return;}
const nextDataGridNode=currentEditingNode.traverseNextNode(true,null,true);if(nextDataGridNode){this._startEditingColumnOfDataGridNode(nextDataGridNode,firstEditableColumn);return;}
if(currentEditingNode.isCreationNode&&wasChange){this.addCreationNode(false);this._startEditingColumnOfDataGridNode(this.creationNode,firstEditableColumn);return;}
return;}
if(moveDirection==='backward'){const prevEditableColumn=this._nextEditableColumn(cellIndex,true);if(prevEditableColumn!==-1){this._startEditingColumnOfDataGridNode(currentEditingNode,prevEditableColumn);return;}
const lastEditableColumn=this._nextEditableColumn(this._visibleColumnsArray.length,true);const nextDataGridNode=currentEditingNode.traversePreviousNode(true,true);if(nextDataGridNode)
this._startEditingColumnOfDataGridNode(nextDataGridNode,lastEditableColumn);return;}}
DataGrid.DataGrid.setElementText(element,newText,!!column.longText);if(textBeforeEditing===newText){this._editingCancelled(element);moveToNextIfNeeded.call(this,false);return;}
this._editingNode.data[columnId]=newText;this._editCallback(this._editingNode,columnId,textBeforeEditing,newText);if(this._editingNode.isCreationNode)
this.addCreationNode(false);this._editingCancelled(element);moveToNextIfNeeded.call(this,true);}
_editingCancelled(element){this._editing=false;this._editingNode=null;}
_nextEditableColumn(cellIndex,moveBackward){const increment=moveBackward?-1:1;const columns=this._visibleColumnsArray;for(let i=cellIndex+increment;(i>=0)&&(i<columns.length);i+=increment){if(columns[i].editable)
return i;}
return-1;}
sortColumnId(){if(!this._sortColumnCell)
return null;return this._sortColumnCell[DataGrid.DataGrid._columnIdSymbol];}
sortOrder(){if(!this._sortColumnCell||this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Ascending))
return DataGrid.DataGrid.Order.Ascending;if(this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Descending))
return DataGrid.DataGrid.Order.Descending;return null;}
isSortOrderAscending(){return!this._sortColumnCell||this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Ascending);}
_autoSizeWidths(widths,minPercent,maxPercent){if(minPercent)
minPercent=Math.min(minPercent,Math.floor(100/widths.length));let totalWidth=0;for(let i=0;i<widths.length;++i)
totalWidth+=widths[i];let totalPercentWidth=0;for(let i=0;i<widths.length;++i){let width=Math.round(100*widths[i]/totalWidth);if(minPercent&&width<minPercent)
width=minPercent;else if(maxPercent&&width>maxPercent)
width=maxPercent;totalPercentWidth+=width;widths[i]=width;}
let recoupPercent=totalPercentWidth-100;while(minPercent&&recoupPercent>0){for(let i=0;i<widths.length;++i){if(widths[i]>minPercent){--widths[i];--recoupPercent;if(!recoupPercent)
break;}}}
while(maxPercent&&recoupPercent<0){for(let i=0;i<widths.length;++i){if(widths[i]<maxPercent){++widths[i];++recoupPercent;if(!recoupPercent)
break;}}}
return widths;}
autoSizeColumns(minPercent,maxPercent,maxDescentLevel){let widths=[];for(let i=0;i<this._columnsArray.length;++i)
widths.push((this._columnsArray[i].title||'').length);maxDescentLevel=maxDescentLevel||0;const children=this._enumerateChildren(this._rootNode,[],maxDescentLevel+1);for(let i=0;i<children.length;++i){const node=children[i];for(let j=0;j<this._columnsArray.length;++j){const text=String(node.data[this._columnsArray[j].id]);if(text.length>widths[j])
widths[j]=text.length;}}
widths=this._autoSizeWidths(widths,minPercent,maxPercent);for(let i=0;i<this._columnsArray.length;++i)
this._columnsArray[i].weight=widths[i];this._columnWidthsInitialized=false;this.updateWidths();}
_enumerateChildren(rootNode,result,maxLevel){if(!rootNode._isRoot)
result.push(rootNode);if(!maxLevel)
return[];for(let i=0;i<rootNode.children.length;++i)
this._enumerateChildren(rootNode.children[i],result,maxLevel-1);return result;}
onResize(){this.updateWidths();}
updateWidths(){if(!this._columnWidthsInitialized&&this.element.offsetWidth){const tableWidth=this.element.offsetWidth-this._cornerWidth;const cells=this._headerTableBody.rows[0].cells;const numColumns=cells.length-1;for(let i=0;i<numColumns;i++){const column=this._visibleColumnsArray[i];if(!column.weight)
column.weight=100*cells[i].offsetWidth/tableWidth||10;}
this._columnWidthsInitialized=true;}
this._applyColumnWeights();}
setName(name){this._columnWeightsSetting=Common.settings.createSetting('dataGrid-'+name+'-columnWeights',{});this._loadColumnWeights();}
_loadColumnWeights(){if(!this._columnWeightsSetting)
return;const weights=this._columnWeightsSetting.get();for(let i=0;i<this._columnsArray.length;++i){const column=this._columnsArray[i];const weight=weights[column.id];if(weight)
column.weight=weight;}
this._applyColumnWeights();}
_saveColumnWeights(){if(!this._columnWeightsSetting)
return;const weights={};for(let i=0;i<this._columnsArray.length;++i){const column=this._columnsArray[i];weights[column.id]=column.weight;}
this._columnWeightsSetting.set(weights);}
wasShown(){this._loadColumnWeights();}
willHide(){}
_applyColumnWeights(){let tableWidth=this.element.offsetWidth-this._cornerWidth;if(tableWidth<=0)
return;let sumOfWeights=0.0;const fixedColumnWidths=[];for(let i=0;i<this._visibleColumnsArray.length;++i){const column=this._visibleColumnsArray[i];if(column.fixedWidth){const width=this._headerTableColumnGroup.children[i][DataGrid.DataGrid._preferredWidthSymbol]||this._headerTableBody.rows[0].cells[i].offsetWidth;fixedColumnWidths[i]=width;tableWidth-=width;}else{sumOfWeights+=this._visibleColumnsArray[i].weight;}}
let sum=0;let lastOffset=0;for(let i=0;i<this._visibleColumnsArray.length;++i){const column=this._visibleColumnsArray[i];let width;if(column.fixedWidth){width=fixedColumnWidths[i];}else{sum+=column.weight;const offset=(sum*tableWidth/sumOfWeights)|0;width=offset-lastOffset;lastOffset=offset;}
this._setPreferredWidth(i,width);}
this._positionResizers();}
setColumnsVisiblity(columnsVisibility){this._visibleColumnsArray=[];for(let i=0;i<this._columnsArray.length;++i){const column=this._columnsArray[i];if(columnsVisibility[column.id])
this._visibleColumnsArray.push(column);}
this._refreshHeader();this._applyColumnWeights();const nodes=this._enumerateChildren(this.rootNode(),[],-1);for(let i=0;i<nodes.length;++i)
nodes[i].refresh();}
get scrollContainer(){return this._scrollContainer;}
_positionResizers(){const headerTableColumns=this._headerTableColumnGroup.children;const numColumns=headerTableColumns.length-1;const left=[];const resizers=this._resizers;while(resizers.length>numColumns-1)
resizers.pop().remove();for(let i=0;i<numColumns-1;i++){left[i]=(left[i-1]||0)+this._headerTableBody.rows[0].cells[i].offsetWidth;}
for(let i=0;i<numColumns-1;i++){let resizer=resizers[i];if(!resizer){resizer=createElement('div');resizer.__index=i;resizer.classList.add('data-grid-resizer');UI.installDragHandle(resizer,this._startResizerDragging.bind(this),this._resizerDragging.bind(this),this._endResizerDragging.bind(this),'col-resize');this.element.appendChild(resizer);resizers.push(resizer);}
if(resizer.__position!==left[i]){resizer.__position=left[i];resizer.style.left=left[i]+'px';}}}
addCreationNode(hasChildren){if(this.creationNode)
this.creationNode.makeNormal();const emptyData={};for(const column in this._columns)
emptyData[column]=null;this.creationNode=new DataGrid.CreationDataGridNode(emptyData,hasChildren);this.rootNode().appendChild(this.creationNode);}
_keyDown(event){if(!this.selectedNode||event.shiftKey||event.metaKey||event.ctrlKey||this._editing||UI.isEditing())
return;let handled=false;let nextSelectedNode;if(event.key==='ArrowUp'&&!event.altKey){nextSelectedNode=this.selectedNode.traversePreviousNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable)
nextSelectedNode=nextSelectedNode.traversePreviousNode(true);handled=nextSelectedNode?true:false;}else if(event.key==='ArrowDown'&&!event.altKey){nextSelectedNode=this.selectedNode.traverseNextNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable)
nextSelectedNode=nextSelectedNode.traverseNextNode(true);handled=nextSelectedNode?true:false;}else if(event.key==='ArrowLeft'){if(this.selectedNode.expanded){if(event.altKey)
this.selectedNode.collapseRecursively();else
this.selectedNode.collapse();handled=true;}else if(this.selectedNode.parent&&!this.selectedNode.parent._isRoot){handled=true;if(this.selectedNode.parent.selectable){nextSelectedNode=this.selectedNode.parent;handled=nextSelectedNode?true:false;}else if(this.selectedNode.parent){this.selectedNode.parent.collapse();}}}else if(event.key==='ArrowRight'){if(!this.selectedNode.revealed){this.selectedNode.reveal();handled=true;}else if(this.selectedNode.hasChildren()){handled=true;if(this.selectedNode.expanded){nextSelectedNode=this.selectedNode.children[0];handled=nextSelectedNode?true:false;}else{if(event.altKey)
this.selectedNode.expandRecursively();else
this.selectedNode.expand();}}}else if(event.keyCode===8||event.keyCode===46){if(this._deleteCallback){handled=true;this._deleteCallback(this.selectedNode);}}else if(isEnterKey(event)){if(this._editCallback){handled=true;this._startEditing(this.selectedNode._element.children[this._nextEditableColumn(-1)]);}else{this.dispatchEventToListeners(DataGrid.DataGrid.Events.OpenedNode,this.selectedNode);}}
if(nextSelectedNode){nextSelectedNode.reveal();nextSelectedNode.select();}
if(handled)
event.consume(true);}
updateSelectionBeforeRemoval(root,onlyAffectsSubtree){let ancestor=this.selectedNode;while(ancestor&&ancestor!==root)
ancestor=ancestor.parent;if(!ancestor)
return;let nextSelectedNode;for(ancestor=root;ancestor&&!ancestor.nextSibling;ancestor=ancestor.parent){}
if(ancestor)
nextSelectedNode=ancestor.nextSibling;while(nextSelectedNode&&!nextSelectedNode.selectable)
nextSelectedNode=nextSelectedNode.traverseNextNode(true);if(!nextSelectedNode||nextSelectedNode.isCreationNode){nextSelectedNode=root.traversePreviousNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable)
nextSelectedNode=nextSelectedNode.traversePreviousNode(true);}
if(nextSelectedNode){nextSelectedNode.reveal();nextSelectedNode.select();}else{this.selectedNode.deselect();}}
dataGridNodeFromNode(target){const rowElement=target.enclosingNodeOrSelfWithNodeName('tr');return rowElement&&rowElement._dataGridNode;}
columnIdFromNode(target){const cellElement=target.enclosingNodeOrSelfWithNodeName('td');return cellElement&&cellElement[DataGrid.DataGrid._columnIdSymbol];}
_clickInHeaderCell(event){const cell=event.target.enclosingNodeOrSelfWithNodeName('th');if(!cell||(cell[DataGrid.DataGrid._columnIdSymbol]===undefined)||!cell.classList.contains('sortable'))
return;let sortOrder=DataGrid.DataGrid.Order.Ascending;if((cell===this._sortColumnCell)&&this.isSortOrderAscending())
sortOrder=DataGrid.DataGrid.Order.Descending;if(this._sortColumnCell)
this._sortColumnCell.classList.remove(DataGrid.DataGrid.Order.Ascending,DataGrid.DataGrid.Order.Descending);this._sortColumnCell=cell;cell.classList.add(sortOrder);const icon=cell[DataGrid.DataGrid._sortIconSymbol];icon.setIconType(sortOrder===DataGrid.DataGrid.Order.Ascending?'smallicon-triangle-up':'smallicon-triangle-down');this.dispatchEventToListeners(DataGrid.DataGrid.Events.SortingChanged);}
markColumnAsSortedBy(columnId,sortOrder){if(this._sortColumnCell)
this._sortColumnCell.classList.remove(DataGrid.DataGrid.Order.Ascending,DataGrid.DataGrid.Order.Descending);this._sortColumnCell=this._headerTableHeaders[columnId];this._sortColumnCell.classList.add(sortOrder);}
headerTableHeader(columnId){return this._headerTableHeaders[columnId];}
_mouseDownInDataTable(event){const target=(event.target);const gridNode=this.dataGridNodeFromNode(target);if(!gridNode||!gridNode.selectable||gridNode.isEventWithinDisclosureTriangle(event))
return;const columnId=this.columnIdFromNode(target);if(columnId&&this._columns[columnId].nonSelectable)
return;if(event.metaKey){if(gridNode.selected)
gridNode.deselect();else
gridNode.select();}else{gridNode.select();this.dispatchEventToListeners(DataGrid.DataGrid.Events.OpenedNode,gridNode);}}
setHeaderContextMenuCallback(callback){this._headerContextMenuCallback=callback;}
setRowContextMenuCallback(callback){this._rowContextMenuCallback=callback;}
_contextMenu(event){const contextMenu=new UI.ContextMenu(event);const target=(event.target);if(target.isSelfOrDescendant(this._headerTableBody)){if(this._headerContextMenuCallback)
this._headerContextMenuCallback(contextMenu);return;}
const gridNode=this.dataGridNodeFromNode(target);if(this._refreshCallback&&(!gridNode||gridNode!==this.creationNode))
contextMenu.defaultSection().appendItem(Common.UIString('Refresh'),this._refreshCallback.bind(this));if(gridNode&&gridNode.selectable&&!gridNode.isEventWithinDisclosureTriangle(event)){if(this._editCallback){if(gridNode===this.creationNode){contextMenu.defaultSection().appendItem(Common.UIString('Add new'),this._startEditing.bind(this,target));}else{const columnId=this.columnIdFromNode(target);if(columnId&&this._columns[columnId].editable){contextMenu.defaultSection().appendItem(Common.UIString('Edit "%s"',this._columns[columnId].title),this._startEditing.bind(this,target));}}}
if(this._deleteCallback&&gridNode!==this.creationNode)
contextMenu.defaultSection().appendItem(Common.UIString('Delete'),this._deleteCallback.bind(this,gridNode));if(this._rowContextMenuCallback)
this._rowContextMenuCallback(contextMenu,gridNode);}
contextMenu.show();}
_clickInDataTable(event){const gridNode=this.dataGridNodeFromNode((event.target));if(!gridNode||!gridNode.hasChildren()||!gridNode.isEventWithinDisclosureTriangle(event))
return;if(gridNode.expanded){if(event.altKey)
gridNode.collapseRecursively();else
gridNode.collapse();}else{if(event.altKey)
gridNode.expandRecursively();else
gridNode.expand();}}
setResizeMethod(method){this._resizeMethod=method;}
_startResizerDragging(event){this._currentResizer=event.target;return true;}
_endResizerDragging(){this._currentResizer=null;this._saveColumnWeights();}
_resizerDragging(event){const resizer=this._currentResizer;if(!resizer)
return;let dragPoint=event.clientX-this.element.totalOffsetLeft();const firstRowCells=this._headerTableBody.rows[0].cells;let leftEdgeOfPreviousColumn=0;let leftCellIndex=resizer.__index;let rightCellIndex=leftCellIndex+1;for(let i=0;i<leftCellIndex;i++)
leftEdgeOfPreviousColumn+=firstRowCells[i].offsetWidth;if(this._resizeMethod===DataGrid.DataGrid.ResizeMethod.Last){rightCellIndex=this._resizers.length;}else if(this._resizeMethod===DataGrid.DataGrid.ResizeMethod.First){leftEdgeOfPreviousColumn+=firstRowCells[leftCellIndex].offsetWidth-firstRowCells[0].offsetWidth;leftCellIndex=0;}
const rightEdgeOfNextColumn=leftEdgeOfPreviousColumn+firstRowCells[leftCellIndex].offsetWidth+firstRowCells[rightCellIndex].offsetWidth;const leftMinimum=leftEdgeOfPreviousColumn+DataGrid.DataGrid.ColumnResizePadding;const rightMaximum=rightEdgeOfNextColumn-DataGrid.DataGrid.ColumnResizePadding;if(leftMinimum>rightMaximum)
return;dragPoint=Number.constrain(dragPoint,leftMinimum,rightMaximum);const position=(dragPoint-DataGrid.DataGrid.CenterResizerOverBorderAdjustment);resizer.__position=position;resizer.style.left=position+'px';this._setPreferredWidth(leftCellIndex,dragPoint-leftEdgeOfPreviousColumn);this._setPreferredWidth(rightCellIndex,rightEdgeOfNextColumn-dragPoint);const leftColumn=this._visibleColumnsArray[leftCellIndex];const rightColumn=this._visibleColumnsArray[rightCellIndex];if(leftColumn.weight||rightColumn.weight){const sumOfWeights=leftColumn.weight+rightColumn.weight;const delta=rightEdgeOfNextColumn-leftEdgeOfPreviousColumn;leftColumn.weight=(dragPoint-leftEdgeOfPreviousColumn)*sumOfWeights/delta;rightColumn.weight=(rightEdgeOfNextColumn-dragPoint)*sumOfWeights/delta;}
this._positionResizers();event.preventDefault();}
_setPreferredWidth(columnIndex,width){const pxWidth=width+'px';this._headerTableColumnGroup.children[columnIndex][DataGrid.DataGrid._preferredWidthSymbol]=width;this._headerTableColumnGroup.children[columnIndex].style.width=pxWidth;this._dataTableColumnGroup.children[columnIndex].style.width=pxWidth;}
columnOffset(columnId){if(!this.element.offsetWidth)
return 0;for(let i=1;i<this._visibleColumnsArray.length;++i){if(columnId===this._visibleColumnsArray[i].id){if(this._resizers[i-1])
return this._resizers[i-1].__position;}}
return 0;}
asWidget(){if(!this._dataGridWidget)
this._dataGridWidget=new DataGrid.DataGridWidget(this);return this._dataGridWidget;}
topFillerRowElement(){return this._topFillerRow;}};DataGrid.DataGrid.CornerWidth=14;DataGrid.DataGrid.ColumnDescriptor;DataGrid.DataGrid.Events={SelectedNode:Symbol('SelectedNode'),DeselectedNode:Symbol('DeselectedNode'),OpenedNode:Symbol('OpenedNode'),SortingChanged:Symbol('SortingChanged'),PaddingChanged:Symbol('PaddingChanged'),};DataGrid.DataGrid.Order={Ascending:'sort-ascending',Descending:'sort-descending'};DataGrid.DataGrid.Align={Center:'center',Right:'right'};DataGrid.DataGrid._preferredWidthSymbol=Symbol('preferredWidth');DataGrid.DataGrid._columnIdSymbol=Symbol('columnId');DataGrid.DataGrid._sortIconSymbol=Symbol('sortIcon');DataGrid.DataGrid._longTextSymbol=Symbol('longText');DataGrid.DataGrid.ColumnResizePadding=24;DataGrid.DataGrid.CenterResizerOverBorderAdjustment=3;DataGrid.DataGrid.ResizeMethod={Nearest:'nearest',First:'first',Last:'last'};DataGrid.DataGridNode=class extends Common.Object{constructor(data,hasChildren){super();this._element=null;this._expanded=false;this._selected=false;this._dirty=false;this._inactive=false;this._depth;this._revealed;this._attached=false;this._savedPosition=null;this._shouldRefreshChildren=true;this._data=data||{};this._hasChildren=hasChildren||false;this.children=[];this.dataGrid=null;this.parent=null;this.previousSibling=null;this.nextSibling=null;this.disclosureToggleWidth=10;this.selectable=true;this._isRoot=false;}
element(){if(!this._element){const element=this.createElement();this.createCells(element);}
return(this._element);}
createElement(){this._element=createElementWithClass('tr','data-grid-data-grid-node');this._element._dataGridNode=this;if(this._hasChildren)
this._element.classList.add('parent');if(this.expanded)
this._element.classList.add('expanded');if(this.selected)
this._element.classList.add('selected');if(this.revealed)
this._element.classList.add('revealed');if(this.dirty)
this._element.classList.add('dirty');if(this.inactive)
this._element.classList.add('inactive');return this._element;}
existingElement(){return this._element||null;}
resetElement(){this._element=null;}
createCells(element){element.removeChildren();const columnsArray=this.dataGrid._visibleColumnsArray;for(let i=0;i<columnsArray.length;++i)
element.appendChild(this.createCell(columnsArray[i].id));element.appendChild(this._createTDWithClass('corner'));}
get data(){return this._data;}
set data(x){this._data=x||{};this.refresh();}
get revealed(){if(this._revealed!==undefined)
return this._revealed;let currentAncestor=this.parent;while(currentAncestor&&!currentAncestor._isRoot){if(!currentAncestor.expanded){this._revealed=false;return false;}
currentAncestor=currentAncestor.parent;}
this.revealed=true;return true;}
set revealed(x){if(this._revealed===x)
return;this._revealed=x;if(this._element)
this._element.classList.toggle('revealed',this._revealed);for(let i=0;i<this.children.length;++i)
this.children[i].revealed=x&&this.expanded;}
isDirty(){return this._dirty;}
setDirty(dirty){if(this._dirty===dirty)
return;this._dirty=dirty;if(!this._element)
return;if(dirty)
this._element.classList.add('dirty');else
this._element.classList.remove('dirty');}
isInactive(){return this._inactive;}
setInactive(inactive){if(this._inactive===inactive)
return;this._inactive=inactive;if(!this._element)
return;if(inactive)
this._element.classList.add('inactive');else
this._element.classList.remove('inactive');}
hasChildren(){return this._hasChildren;}
setHasChildren(x){if(this._hasChildren===x)
return;this._hasChildren=x;if(!this._element)
return;this._element.classList.toggle('parent',this._hasChildren);this._element.classList.toggle('expanded',this._hasChildren&&this.expanded);}
get depth(){if(this._depth!==undefined)
return this._depth;if(this.parent&&!this.parent._isRoot)
this._depth=this.parent.depth+1;else
this._depth=0;return this._depth;}
get leftPadding(){return this.depth*this.dataGrid.indentWidth;}
get shouldRefreshChildren(){return this._shouldRefreshChildren;}
set shouldRefreshChildren(x){this._shouldRefreshChildren=x;if(x&&this.expanded)
this.expand();}
get selected(){return this._selected;}
set selected(x){if(x)
this.select();else
this.deselect();}
get expanded(){return this._expanded;}
set expanded(x){if(x)
this.expand();else
this.collapse();}
refresh(){if(!this.dataGrid)
this._element=null;if(!this._element)
return;this.createCells(this._element);}
_createTDWithClass(className){const cell=createElementWithClass('td',className);const cellClass=this.dataGrid._cellClass;if(cellClass)
cell.classList.add(cellClass);return cell;}
createTD(columnId){const cell=this._createTDWithClass(columnId+'-column');cell[DataGrid.DataGrid._columnIdSymbol]=columnId;const alignment=this.dataGrid._columns[columnId].align;if(alignment)
cell.classList.add(alignment);if(columnId===this.dataGrid.disclosureColumnId){cell.classList.add('disclosure');if(this.leftPadding)
cell.style.setProperty('padding-left',this.leftPadding+'px');}
return cell;}
createCell(columnId){const cell=this.createTD(columnId);const data=this.data[columnId];if(data instanceof Node)
cell.appendChild(data);else if(data!==null)
DataGrid.DataGrid.setElementText(cell,(data),!!this.dataGrid._columns[columnId].longText);return cell;}
nodeSelfHeight(){return 20;}
appendChild(child){this.insertChild(child,this.children.length);}
resetNode(onlyCaches){delete this._depth;delete this._revealed;if(onlyCaches)
return;if(this.previousSibling)
this.previousSibling.nextSibling=this.nextSibling;if(this.nextSibling)
this.nextSibling.previousSibling=this.previousSibling;this.dataGrid=null;this.parent=null;this.nextSibling=null;this.previousSibling=null;this._attached=false;}
insertChild(child,index){if(!child)
throw'insertChild: Node can\'t be undefined or null.';if(child.parent===this){const currentIndex=this.children.indexOf(child);if(currentIndex<0)
console.assert(false,'Inconsistent DataGrid state');if(currentIndex===index)
return;if(currentIndex<index)
--index;}
child.remove();this.children.splice(index,0,child);this.setHasChildren(true);child.parent=this;child.dataGrid=this.dataGrid;child.recalculateSiblings(index);child._shouldRefreshChildren=true;let current=child.children[0];while(current){current.resetNode(true);current.dataGrid=this.dataGrid;current._attached=false;current._shouldRefreshChildren=true;current=current.traverseNextNode(false,child,true);}
if(this.expanded)
child._attach();if(!this.revealed)
child.revealed=false;}
remove(){if(this.parent)
this.parent.removeChild(this);}
removeChild(child){if(!child)
throw'removeChild: Node can\'t be undefined or null.';if(child.parent!==this)
throw'removeChild: Node is not a child of this node.';if(this.dataGrid)
this.dataGrid.updateSelectionBeforeRemoval(child,false);child._detach();child.resetNode();this.children.remove(child,true);if(this.children.length<=0)
this.setHasChildren(false);}
removeChildren(){if(this.dataGrid)
this.dataGrid.updateSelectionBeforeRemoval(this,true);for(let i=0;i<this.children.length;++i){const child=this.children[i];child._detach();child.resetNode();}
this.children=[];this.setHasChildren(false);}
recalculateSiblings(myIndex){if(!this.parent)
return;const previousChild=this.parent.children[myIndex-1]||null;if(previousChild)
previousChild.nextSibling=this;this.previousSibling=previousChild;const nextChild=this.parent.children[myIndex+1]||null;if(nextChild)
nextChild.previousSibling=this;this.nextSibling=nextChild;}
collapse(){if(this._isRoot)
return;if(this._element)
this._element.classList.remove('expanded');this._expanded=false;for(let i=0;i<this.children.length;++i)
this.children[i].revealed=false;}
collapseRecursively(){let item=this;while(item){if(item.expanded)
item.collapse();item=item.traverseNextNode(false,this,true);}}
populate(){}
expand(){if(!this._hasChildren||this.expanded)
return;if(this._isRoot)
return;if(this.revealed&&!this._shouldRefreshChildren){for(let i=0;i<this.children.length;++i)
this.children[i].revealed=true;}
if(this._shouldRefreshChildren){for(let i=0;i<this.children.length;++i)
this.children[i]._detach();this.populate();if(this._attached){for(let i=0;i<this.children.length;++i){const child=this.children[i];if(this.revealed)
child.revealed=true;child._attach();}}
this._shouldRefreshChildren=false;}
if(this._element)
this._element.classList.add('expanded');this._expanded=true;}
expandRecursively(){let item=this;while(item){item.expand();item=item.traverseNextNode(false,this);}}
reveal(){if(this._isRoot)
return;let currentAncestor=this.parent;while(currentAncestor&&!currentAncestor._isRoot){if(!currentAncestor.expanded)
currentAncestor.expand();currentAncestor=currentAncestor.parent;}
this.element().scrollIntoViewIfNeeded(false);}
select(supressSelectedEvent){if(!this.dataGrid||!this.selectable||this.selected)
return;if(this.dataGrid.selectedNode)
this.dataGrid.selectedNode.deselect();this._selected=true;this.dataGrid.selectedNode=this;if(this._element)
this._element.classList.add('selected');if(!supressSelectedEvent)
this.dataGrid.dispatchEventToListeners(DataGrid.DataGrid.Events.SelectedNode,this);}
revealAndSelect(){if(this._isRoot)
return;this.reveal();this.select();}
deselect(supressDeselectedEvent){if(!this.dataGrid||this.dataGrid.selectedNode!==this||!this.selected)
return;this._selected=false;this.dataGrid.selectedNode=null;if(this._element)
this._element.classList.remove('selected');if(!supressDeselectedEvent)
this.dataGrid.dispatchEventToListeners(DataGrid.DataGrid.Events.DeselectedNode);}
traverseNextNode(skipHidden,stayWithin,dontPopulate,info){if(!dontPopulate&&this._hasChildren)
this.populate();if(info)
info.depthChange=0;let node=(!skipHidden||this.revealed)?this.children[0]:null;if(node&&(!skipHidden||this.expanded)){if(info)
info.depthChange=1;return node;}
if(this===stayWithin)
return null;node=(!skipHidden||this.revealed)?this.nextSibling:null;if(node)
return node;node=this;while(node&&!node._isRoot&&!((!skipHidden||node.revealed)?node.nextSibling:null)&&node.parent!==stayWithin){if(info)
info.depthChange-=1;node=node.parent;}
if(!node)
return null;return(!skipHidden||node.revealed)?node.nextSibling:null;}
traversePreviousNode(skipHidden,dontPopulate){let node=(!skipHidden||this.revealed)?this.previousSibling:null;if(!dontPopulate&&node&&node._hasChildren)
node.populate();while(node&&((!skipHidden||(node.revealed&&node.expanded))?node.children[node.children.length-1]:null)){if(!dontPopulate&&node._hasChildren)
node.populate();node=((!skipHidden||(node.revealed&&node.expanded))?node.children[node.children.length-1]:null);}
if(node)
return node;if(!this.parent||this.parent._isRoot)
return null;return this.parent;}
isEventWithinDisclosureTriangle(event){if(!this._hasChildren)
return false;const cell=event.target.enclosingNodeOrSelfWithNodeName('td');if(!cell||!cell.classList.contains('disclosure'))
return false;const left=cell.totalOffsetLeft()+this.leftPadding;return event.pageX>=left&&event.pageX<=left+this.disclosureToggleWidth;}
_attach(){if(!this.dataGrid||this._attached)
return;this._attached=true;const previousNode=this.traversePreviousNode(true,true);const previousElement=previousNode?previousNode.element():this.dataGrid._topFillerRow;this.dataGrid.dataTableBody.insertBefore(this.element(),previousElement.nextSibling);if(this.expanded){for(let i=0;i<this.children.length;++i)
this.children[i]._attach();}}
_detach(){if(!this._attached)
return;this._attached=false;if(this._element)
this._element.remove();for(let i=0;i<this.children.length;++i)
this.children[i]._detach();}
savePosition(){if(this._savedPosition)
return;if(!this.parent)
throw'savePosition: Node must have a parent.';this._savedPosition={parent:this.parent,index:this.parent.children.indexOf(this)};}
restorePosition(){if(!this._savedPosition)
return;if(this.parent!==this._savedPosition.parent)
this._savedPosition.parent.insertChild(this,this._savedPosition.index);this._savedPosition=null;}};DataGrid.CreationDataGridNode=class extends DataGrid.DataGridNode{constructor(data,hasChildren){super(data,hasChildren);this.isCreationNode=true;}
makeNormal(){this.isCreationNode=false;}};DataGrid.DataGridWidget=class extends UI.VBox{constructor(dataGrid){super();this._dataGrid=dataGrid;this.element.appendChild(dataGrid.element);}
wasShown(){this._dataGrid.wasShown();}
willHide(){this._dataGrid.willHide();}
onResize(){this._dataGrid.onResize();}
elementsToRestoreScrollPositionsFor(){return[this._dataGrid._scrollContainer];}
detachChildWidgets(){super.detachChildWidgets();for(const dataGrid of this._dataGrids)
this.element.removeChild(dataGrid.element);this._dataGrids=[];}};;DataGrid.ViewportDataGrid=class extends DataGrid.DataGrid{constructor(columnsArray,editCallback,deleteCallback,refreshCallback){super(columnsArray,editCallback,deleteCallback,refreshCallback);this._onScrollBound=this._onScroll.bind(this);this._scrollContainer.addEventListener('scroll',this._onScrollBound,true);this._visibleNodes=[];this._inline=false;this._stickToBottom=false;this._updateIsFromUser=false;this._lastScrollTop=0;this._firstVisibleIsStriped=false;this._isStriped=false;this.setRootNode(new DataGrid.ViewportDataGridNode());}
setStriped(striped){this._isStriped=striped;let startsWithOdd=true;if(this._visibleNodes.length){const allChildren=this.rootNode().flatChildren();startsWithOdd=!!(allChildren.indexOf(this._visibleNodes[0]));}
this._updateStripesClass(startsWithOdd);}
_updateStripesClass(startsWithOdd){this.element.classList.toggle('striped-data-grid',!startsWithOdd&&this._isStriped);this.element.classList.toggle('striped-data-grid-starts-with-odd',startsWithOdd&&this._isStriped);}
setScrollContainer(scrollContainer){this._scrollContainer.removeEventListener('scroll',this._onScrollBound,true);this._scrollContainer=scrollContainer;this._scrollContainer.addEventListener('scroll',this._onScrollBound,true);}
onResize(){if(this._stickToBottom)
this._scrollContainer.scrollTop=this._scrollContainer.scrollHeight-this._scrollContainer.clientHeight;this.scheduleUpdate();super.onResize();}
setStickToBottom(stick){this._stickToBottom=stick;}
_onScroll(event){this._stickToBottom=this._scrollContainer.isScrolledToBottom();if(this._lastScrollTop!==this._scrollContainer.scrollTop)
this.scheduleUpdate(true);}
scheduleUpdateStructure(){this.scheduleUpdate();}
scheduleUpdate(isFromUser){if(this._stickToBottom&&isFromUser)
this._stickToBottom=this._scrollContainer.isScrolledToBottom();this._updateIsFromUser=this._updateIsFromUser||isFromUser;if(this._updateAnimationFrameId)
return;this._updateAnimationFrameId=this.element.window().requestAnimationFrame(this._update.bind(this));}
updateInstantly(){this._update();}
renderInline(){this._inline=true;super.renderInline();this._update();}
_calculateVisibleNodes(clientHeight,scrollTop){const nodes=this.rootNode().flatChildren();if(this._inline)
return{topPadding:0,bottomPadding:0,contentHeight:0,visibleNodes:nodes,offset:0};const size=nodes.length;let i=0;let y=0;for(;i<size&&y+nodes[i].nodeSelfHeight()<scrollTop;++i)
y+=nodes[i].nodeSelfHeight();const start=i;const topPadding=y;for(;i<size&&y<scrollTop+clientHeight;++i)
y+=nodes[i].nodeSelfHeight();const end=i;let bottomPadding=0;for(;i<size;++i)
bottomPadding+=nodes[i].nodeSelfHeight();return{topPadding:topPadding,bottomPadding:bottomPadding,contentHeight:y-topPadding,visibleNodes:nodes.slice(start,end),offset:start};}
_contentHeight(){const nodes=this.rootNode().flatChildren();let result=0;for(let i=0,size=nodes.length;i<size;++i)
result+=nodes[i].nodeSelfHeight();return result;}
_update(){if(this._updateAnimationFrameId){this.element.window().cancelAnimationFrame(this._updateAnimationFrameId);delete this._updateAnimationFrameId;}
const clientHeight=this._scrollContainer.clientHeight;let scrollTop=this._scrollContainer.scrollTop;const currentScrollTop=scrollTop;const maxScrollTop=Math.max(0,this._contentHeight()-clientHeight);if(!this._updateIsFromUser&&this._stickToBottom)
scrollTop=maxScrollTop;this._updateIsFromUser=false;scrollTop=Math.min(maxScrollTop,scrollTop);const viewportState=this._calculateVisibleNodes(clientHeight,scrollTop);const visibleNodes=viewportState.visibleNodes;const visibleNodesSet=new Set(visibleNodes);for(let i=0;i<this._visibleNodes.length;++i){const oldNode=this._visibleNodes[i];if(!visibleNodesSet.has(oldNode)&&oldNode.attached()){const element=oldNode.existingElement();element.remove();}}
let previousElement=this.topFillerRowElement();const tBody=this.dataTableBody;let offset=viewportState.offset;if(visibleNodes.length){const nodes=this.rootNode().flatChildren();const index=nodes.indexOf(visibleNodes[0]);this._updateStripesClass(!!(index%2));if(this._stickToBottom&&index!==-1&&!!(index%2)!==this._firstVisibleIsStriped)
offset+=1;}
this._firstVisibleIsStriped=!!(offset%2);for(let i=0;i<visibleNodes.length;++i){const node=visibleNodes[i];const element=node.element();node.setStriped((offset+i)%2===0);if(element!==previousElement.nextSibling)
tBody.insertBefore(element,previousElement.nextSibling);node.revealed=true;previousElement=element;}
this.setVerticalPadding(viewportState.topPadding,viewportState.bottomPadding);this._lastScrollTop=scrollTop;if(scrollTop!==currentScrollTop)
this._scrollContainer.scrollTop=scrollTop;const contentFits=viewportState.contentHeight<=clientHeight&&viewportState.topPadding+viewportState.bottomPadding===0;if(contentFits!==this.element.classList.contains('data-grid-fits-viewport')){this.element.classList.toggle('data-grid-fits-viewport',contentFits);this.updateWidths();}
this._visibleNodes=visibleNodes;this.dispatchEventToListeners(DataGrid.ViewportDataGrid.Events.ViewportCalculated);}
_revealViewportNode(node){const nodes=this.rootNode().flatChildren();const index=nodes.indexOf(node);if(index===-1)
return;let fromY=0;for(let i=0;i<index;++i)
fromY+=nodes[i].nodeSelfHeight();const toY=fromY+node.nodeSelfHeight();let scrollTop=this._scrollContainer.scrollTop;if(scrollTop>fromY){scrollTop=fromY;this._stickToBottom=false;}else if(scrollTop+this._scrollContainer.offsetHeight<toY){scrollTop=toY-this._scrollContainer.offsetHeight;}
this._scrollContainer.scrollTop=scrollTop;}};DataGrid.ViewportDataGrid.Events={ViewportCalculated:Symbol('ViewportCalculated')};DataGrid.ViewportDataGridNode=class extends DataGrid.DataGridNode{constructor(data,hasChildren){super(data,hasChildren);this._stale=false;this._flatNodes=null;this._isStriped=false;}
element(){const existingElement=this.existingElement();const element=existingElement||this.createElement();if(!existingElement||this._stale){this.createCells(element);this._stale=false;}
return element;}
setStriped(isStriped){this._isStriped=isStriped;this.element().classList.toggle('odd',isStriped);}
isStriped(){return this._isStriped;}
clearFlatNodes(){this._flatNodes=null;const parent=(this.parent);if(parent)
parent.clearFlatNodes();}
flatChildren(){if(this._flatNodes)
return this._flatNodes;const flatNodes=[];const children=[this.children];const counters=[0];let depth=0;while(depth>=0){if(children[depth].length<=counters[depth]){depth--;continue;}
const node=children[depth][counters[depth]++];flatNodes.push(node);if(node._expanded&&node.children.length){depth++;children[depth]=node.children;counters[depth]=0;}}
this._flatNodes=flatNodes;return flatNodes;}
insertChild(child,index){this.clearFlatNodes();if(child.parent===this){const currentIndex=this.children.indexOf(child);if(currentIndex<0)
console.assert(false,'Inconsistent DataGrid state');if(currentIndex===index)
return;if(currentIndex<index)
--index;}
child.remove();child.parent=this;child.dataGrid=this.dataGrid;if(!this.children.length)
this.setHasChildren(true);this.children.splice(index,0,child);child.recalculateSiblings(index);if(this._expanded)
this.dataGrid.scheduleUpdateStructure();}
removeChild(child){this.clearFlatNodes();if(this.dataGrid)
this.dataGrid.updateSelectionBeforeRemoval(child,false);if(child.previousSibling)
child.previousSibling.nextSibling=child.nextSibling;if(child.nextSibling)
child.nextSibling.previousSibling=child.previousSibling;if(child.parent!==this)
throw'removeChild: Node is not a child of this node.';this.children.remove(child,true);child._unlink();if(!this.children.length)
this.setHasChildren(false);if(this._expanded)
this.dataGrid.scheduleUpdateStructure();}
removeChildren(){this.clearFlatNodes();if(this.dataGrid)
this.dataGrid.updateSelectionBeforeRemoval(this,true);for(let i=0;i<this.children.length;++i)
this.children[i]._unlink();this.children=[];if(this._expanded)
this.dataGrid.scheduleUpdateStructure();}
_unlink(){if(this.attached())
this.existingElement().remove();this.resetNode();}
collapse(){if(!this._expanded)
return;this.clearFlatNodes();this._expanded=false;if(this.existingElement())
this.existingElement().classList.remove('expanded');this.dataGrid.scheduleUpdateStructure();}
expand(){if(this._expanded)
return;this.dataGrid._stickToBottom=false;this.clearFlatNodes();super.expand();this.dataGrid.scheduleUpdateStructure();}
attached(){return!!(this.dataGrid&&this.existingElement()&&this.existingElement().parentElement);}
refresh(){if(this.attached()){this._stale=true;this.dataGrid.scheduleUpdate();}else{this.resetElement();}}
reveal(){this.dataGrid._revealViewportNode(this);}
recalculateSiblings(index){this.clearFlatNodes();super.recalculateSiblings(index);}};;DataGrid.SortableDataGrid=class extends DataGrid.ViewportDataGrid{constructor(columnsArray,editCallback,deleteCallback,refreshCallback){super(columnsArray,editCallback,deleteCallback,refreshCallback);this._sortingFunction=DataGrid.SortableDataGrid.TrivialComparator;this.setRootNode((new DataGrid.SortableDataGridNode()));}
static TrivialComparator(a,b){return 0;}
static NumericComparator(columnId,a,b){const aValue=a.data[columnId];const bValue=b.data[columnId];const aNumber=Number(aValue instanceof Node?aValue.textContent:aValue);const bNumber=Number(bValue instanceof Node?bValue.textContent:bValue);return aNumber<bNumber?-1:(aNumber>bNumber?1:0);}
static StringComparator(columnId,a,b){const aValue=a.data[columnId];const bValue=b.data[columnId];const aString=aValue instanceof Node?aValue.textContent:String(aValue);const bString=bValue instanceof Node?bValue.textContent:String(bValue);return aString<bString?-1:(aString>bString?1:0);}
static Comparator(comparator,reverseMode,a,b){return reverseMode?comparator(b,a):comparator(a,b);}
static create(columnNames,values){const numColumns=columnNames.length;if(!numColumns)
return null;const columns=([]);for(let i=0;i<columnNames.length;++i)
columns.push({id:String(i),title:columnNames[i],width:columnNames[i].length,sortable:true});const nodes=[];for(let i=0;i<values.length/numColumns;++i){const data={};for(let j=0;j<columnNames.length;++j)
data[j]=values[numColumns*i+j];const node=new DataGrid.SortableDataGridNode(data);node.selectable=false;nodes.push(node);}
const dataGrid=new DataGrid.SortableDataGrid(columns);const length=nodes.length;const rootNode=dataGrid.rootNode();for(let i=0;i<length;++i)
rootNode.appendChild(nodes[i]);dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,sortDataGrid);function sortDataGrid(){const nodes=dataGrid.rootNode().children;const sortColumnId=dataGrid.sortColumnId();if(!sortColumnId)
return;let columnIsNumeric=true;for(let i=0;i<nodes.length;i++){const value=nodes[i].data[sortColumnId];if(isNaN(value instanceof Node?value.textContent:value)){columnIsNumeric=false;break;}}
const comparator=columnIsNumeric?DataGrid.SortableDataGrid.NumericComparator:DataGrid.SortableDataGrid.StringComparator;dataGrid.sortNodes(comparator.bind(null,sortColumnId),!dataGrid.isSortOrderAscending());}
return dataGrid;}
insertChild(node){const root=(this.rootNode());root.insertChildOrdered(node);}
sortNodes(comparator,reverseMode){this._sortingFunction=DataGrid.SortableDataGrid.Comparator.bind(null,comparator,reverseMode);this.rootNode().recalculateSiblings(0);this.rootNode()._sortChildren(reverseMode);this.scheduleUpdateStructure();}};DataGrid.SortableDataGridNode=class extends DataGrid.ViewportDataGridNode{constructor(data,hasChildren){super(data,hasChildren);}
insertChildOrdered(node){this.insertChild(node,this.children.upperBound(node,this.dataGrid._sortingFunction));}
_sortChildren(){this.children.sort(this.dataGrid._sortingFunction);for(let i=0;i<this.children.length;++i)
this.children[i].recalculateSiblings(i);for(const child of this.children)
child._sortChildren();}};;DataGrid.ShowMoreDataGridNode=class extends DataGrid.DataGridNode{constructor(callback,startPosition,endPosition,chunkSize){super({summaryRow:true},false);this._callback=callback;this._startPosition=startPosition;this._endPosition=endPosition;this._chunkSize=chunkSize;this.showNext=createElement('button');this.showNext.setAttribute('type','button');this.showNext.addEventListener('click',this._showNextChunk.bind(this),false);this.showNext.textContent=Common.UIString('Show %d before',this._chunkSize);this.showAll=createElement('button');this.showAll.setAttribute('type','button');this.showAll.addEventListener('click',this._showAll.bind(this),false);this.showLast=createElement('button');this.showLast.setAttribute('type','button');this.showLast.addEventListener('click',this._showLastChunk.bind(this),false);this.showLast.textContent=Common.UIString('Show %d after',this._chunkSize);this._updateLabels();this.selectable=false;}
_showNextChunk(){this._callback(this._startPosition,this._startPosition+this._chunkSize);}
_showAll(){this._callback(this._startPosition,this._endPosition);}
_showLastChunk(){this._callback(this._endPosition-this._chunkSize,this._endPosition);}
_updateLabels(){const totalSize=this._endPosition-this._startPosition;if(totalSize>this._chunkSize){this.showNext.classList.remove('hidden');this.showLast.classList.remove('hidden');}else{this.showNext.classList.add('hidden');this.showLast.classList.add('hidden');}
this.showAll.textContent=Common.UIString('Show all %d',totalSize);}
createCells(element){this._hasCells=false;super.createCells(element);}
createCell(columnIdentifier){const cell=this.createTD(columnIdentifier);if(!this._hasCells){this._hasCells=true;if(this.depth)
cell.style.setProperty('padding-left',(this.depth*this.dataGrid.indentWidth)+'px');cell.appendChild(this.showNext);cell.appendChild(this.showAll);cell.appendChild(this.showLast);}
return cell;}
setStartPosition(from){this._startPosition=from;this._updateLabels();}
setEndPosition(to){this._endPosition=to;this._updateLabels();}
nodeSelfHeight(){return 40;}
dispose(){}};;Runtime.cachedResources["data_grid/dataGrid.css"]=".data-grid {\n position: relative;\n border: 1px solid #aaa;\n line-height: 120%;\n}\n\n.data-grid table {\n table-layout: fixed;\n border-spacing: 0;\n border-collapse: separate;\n height: 100%;\n width: 100%;\n}\n\n.data-grid .header-container,\n.data-grid .data-container {\n position: absolute;\n left: 0;\n right: 0;\n overflow-x: hidden;\n}\n\n.data-grid .header-container {\n top: 0;\n height: 21px;\n}\n\n.data-grid .data-container {\n top: 21px;\n bottom: 0;\n overflow-y: overlay;\n transform: translateZ(0);\n}\n\n.data-grid.inline .header-container,\n.data-grid.inline .data-container {\n position: static;\n}\n\n.data-grid.inline .corner {\n display: none;\n}\n\n.platform-mac .data-grid .corner,\n.data-grid.data-grid-fits-viewport .corner {\n display: none;\n}\n\n.data-grid .corner {\n width: 14px;\n padding-right: 0;\n padding-left: 0;\n border-left: 0 none transparent !important;\n}\n\n.data-grid .top-filler-td,\n.data-grid .bottom-filler-td {\n height: auto !important;\n padding: 0 !important;\n}\n\n.data-grid table.data {\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n border-top: 0 none transparent;\n table-layout: fixed;\n}\n\n.data-grid.inline table.data {\n position: static;\n}\n\n.data-grid table.data tr {\n display: none;\n height: 20px;\n}\n\n.data-grid table.data tr.revealed {\n display: table-row;\n}\n\n.striped-data-grid .revealed.data-grid-data-grid-node:nth-child(odd),\n.striped-data-grid-starts-with-odd .revealed.data-grid-data-grid-node:nth-child(even) {\n background-color: hsl(214, 70%, 97%);\n}\n\n.data-grid td,\n.data-grid th {\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n line-height: 18px;\n height: 18px;\n border-left: 1px solid #aaa;\n padding: 1px 4px;\n}\n\n.data-grid th:first-child,\n.data-grid td:first-child {\n border-left: none !important;\n}\n\n.data-grid td {\n vertical-align: top;\n -webkit-user-select: text;\n}\n\n.data-grid th {\n text-align: left;\n background-color: var(--toolbar-bg-color);\n border-bottom: 1px solid #aaa;\n font-weight: normal;\n vertical-align: middle;\n}\n\n.data-grid td > div,\n.data-grid th > div {\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.data-grid td.editing > div {\n text-overflow: clip;\n}\n\n.data-grid .center {\n text-align: center;\n}\n\n.data-grid .right {\n text-align: right;\n}\n\n.data-grid th.sortable {\n position: relative;\n}\n\n.data-grid th.sortable:active::after {\n content: \"\";\n position: absolute;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.15);\n}\n\n.data-grid th .sort-order-icon-container {\n position: absolute;\n top: 1px;\n right: 0;\n bottom: 1px;\n display: flex;\n align-items: center;\n}\n\n.data-grid th .sort-order-icon {\n margin-right: 4px;\n margin-bottom: -2px;\n display: none;\n}\n\n.data-grid th.sort-ascending .sort-order-icon,\n.data-grid th.sort-descending .sort-order-icon {\n display: block;\n}\n\n.data-grid th.sortable:hover {\n background-color: hsla(0, 0%, 90%, 1);\n}\n\n.data-grid button {\n line-height: 18px;\n color: inherit;\n}\n\n.data-grid td.disclosure::before {\n -webkit-user-select: none;\n -webkit-mask-image: url(Images/treeoutlineTriangles.png);\n -webkit-mask-position: 0 0;\n -webkit-mask-size: 32px 24px;\n float: left;\n width: 8px;\n height: 12px;\n margin-right: 2px;\n content: \"\";\n position: relative;\n top: 3px;\n background-color: rgb(110, 110, 110);\n}\n\n.data-grid tr:not(.parent) td.disclosure::before {\n background-color: transparent;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n.data-grid tr.parent td.disclosure::before {\n -webkit-mask-image: url(Images/treeoutlineTriangles_2x.png);\n}\n} /* media */\n\n.data-grid tr
static _instance(){if(!Devices.DevicesView._instanceObject)
Devices.DevicesView._instanceObject=new Devices.DevicesView();return Devices.DevicesView._instanceObject;}
_selectSidebarListItem(listItem,view){if(this._selectedListItem===listItem)
return;if(this._selectedListItem){this._selectedListItem.classList.remove('selected');this._visibleView.detach();}
this._visibleView=view;this._selectedListItem=listItem;this._visibleView.show(this._viewContainer);this._selectedListItem.classList.add('selected');}
_devicesUpdated(event){this._devices=(event.data).slice().filter(d=>d.adbSerial.toUpperCase()!=='WEBRTC'&&d.adbSerial.toUpperCase()!=='LOCALHOST');for(const device of this._devices){if(!device.adbConnected)
device.adbModel=Common.UIString('Unknown');}
const ids=new Set();for(const device of this._devices)
ids.add(device.id);let selectedRemoved=false;for(const deviceId of this._viewById.keys()){if(!ids.has(deviceId)){const listItem=(this._listItemById.get(deviceId));this._listItemById.remove(deviceId);this._viewById.remove(deviceId);listItem.remove();if(listItem===this._selectedListItem)
selectedRemoved=true;}}
for(const device of this._devices){let view=this._viewById.get(device.id);let listItem=this._listItemById.get(device.id);if(!view){view=new Devices.DevicesView.DeviceView();this._viewById.set(device.id,view);listItem=this._createSidebarListItem(view);this._listItemById.set(device.id,listItem);this._sidebarList.insertBefore(listItem,this._sidebarListSpacer);}
listItem._title.textContent=device.adbModel;listItem._status.textContent=device.adbConnected?Common.UIString('Connected'):Common.UIString('Pending Authorization');listItem.classList.toggle('device-connected',device.adbConnected);view.update(device);}
if(selectedRemoved)
this._selectSidebarListItem(this._discoveryListItem,this._discoveryView);this._updateFooter();}
_createSidebarListItem(view){const listItem=createElementWithClass('div','devices-sidebar-item');listItem.addEventListener('click',this._selectSidebarListItem.bind(this,listItem,view));listItem._title=listItem.createChild('div','devices-sidebar-item-title');listItem._status=listItem.createChild('div','devices-sidebar-item-status');return listItem;}
_devicesDiscoveryConfigChanged(event){const config=(event.data);this._discoveryView.discoveryConfigChanged(config);}
_devicesPortForwardingStatusChanged(event){const status=(event.data);for(const deviceId in status){const view=this._viewById.get(deviceId);if(view)
view.portForwardingStatusChanged(status[deviceId]);}
for(const deviceId of this._viewById.keys()){const view=this._viewById.get(deviceId);if(view&&!(deviceId in status))
view.portForwardingStatusChanged({ports:{},browserId:''});}}
_updateFooter(){this._deviceCountSpan.textContent=!this._devices.length?Common.UIString('No devices detected.'):this._devices.length===1?Common.UIString('1 device detected.'):Common.UIString('%d devices detected.',this._devices.length);}
wasShown(){super.wasShown();InspectorFrontendHost.setDevicesUpdatesEnabled(true);}
willHide(){super.willHide();InspectorFrontendHost.setDevicesUpdatesEnabled(false);}};Devices.DevicesView.DiscoveryView=class extends UI.VBox{constructor(){super();this.setMinimumSize(100,100);this.element.classList.add('discovery-view');this.contentElement.createChild('div','hbox device-text-row').createChild('div','view-title').textContent=Common.UIString('Settings');const discoverUsbDevicesCheckbox=UI.CheckboxLabel.create(Common.UIString('Discover USB devices'));discoverUsbDevicesCheckbox.classList.add('usb-checkbox');this.element.appendChild(discoverUsbDevicesCheckbox);this._discoverUsbDevicesCheckbox=discoverUsbDevicesCheckbox.checkboxElement;this._discoverUsbDevicesCheckbox.addEventListener('click',()=>{this._config.discoverUsbDevices=this._discoverUsbDevicesCheckbox.checked;InspectorFrontendHost.setDevicesDiscoveryConfig(this._config);},false);const help=this.element.createChild('div','discovery-help');help.createChild('span').textContent=Common.UIString('Need help? Read Chrome ');help.appendChild(UI.XLink.create('https://developers.google.com/chrome-developer-tools/docs/remote-debugging',Common.UIString('remote debugging documentation.')));this._config;this._portForwardingView=new Devices.DevicesView.PortForwardingView((enabled,config)=>{this._config.portForwardingEnabled=enabled;this._config.portForwardingConfig={};for(const rule of config)
this._config.portForwardingConfig[rule.port]=rule.address;InspectorFrontendHost.setDevicesDiscoveryConfig(this._config);});this._portForwardingView.show(this.element);}
discoveryConfigChanged(config){this._config=config;this._discoverUsbDevicesCheckbox.checked=config.discoverUsbDevices;this._portForwardingView.discoveryConfigChanged(config.portForwardingEnabled,config.portForwardingConfig);}};Devices.DevicesView.PortForwardingView=class extends UI.VBox{constructor(callback){super();this._callback=callback;this.element.classList.add('port-forwarding-view');const portForwardingHeader=this.element.createChild('div','port-forwarding-header');const portForwardingEnabledCheckbox=UI.CheckboxLabel.create(Common.UIString('Port forwarding'));portForwardingEnabledCheckbox.classList.add('port-forwarding-checkbox');portForwardingHeader.appendChild(portForwardingEnabledCheckbox);this._portForwardingEnabledCheckbox=portForwardingEnabledCheckbox.checkboxElement;this._portForwardingEnabledCheckbox.addEventListener('click',this._update.bind(this),false);const portForwardingFooter=this.element.createChild('div','port-forwarding-footer');portForwardingFooter.createChild('span').textContent=Common.UIString('Define the listening port on your device that maps to a port accessible from your development machine. ');portForwardingFooter.appendChild(UI.XLink.create('https://developer.chrome.com/devtools/docs/remote-debugging#port-forwarding',Common.UIString('Learn more')));this._list=new UI.ListWidget(this);this._list.registerRequiredCSS('devices/devicesView.css');this._list.element.classList.add('port-forwarding-list');const placeholder=createElementWithClass('div','port-forwarding-list-empty');placeholder.textContent=Common.UIString('No rules');this._list.setEmptyPlaceholder(placeholder);this._list.show(this.element);this._editor=null;this.element.appendChild(UI.createTextButton(Common.UIString('Add rule'),this._addRuleButtonClicked.bind(this),'add-rule-button'));this._portForwardingConfig=[];}
_update(){this._callback.call(null,this._portForwardingEnabledCheckbox.checked,this._portForwardingConfig);}
_addRuleButtonClicked(){this._list.addNewItem(this._portForwardingConfig.length,{port:'',address:''});}
discoveryConfigChanged(portForwardingEnabled,portForwardingConfig){this._portForwardingEnabledCheckbox.checked=portForwardingEnabled;this._portForwardingConfig=[];this._list.clear();for(const key of Object.keys(portForwardingConfig)){const rule=({port:key,address:portForwardingConfig[key]});this._portForwardingConfig.push(rule);this._list.appendItem(rule,true);}}
renderItem(rule,editable){const element=createElementWithClass('div','port-forwarding-list-item');const port=element.createChild('div','port-forwarding-value port-forwarding-port');port.createChild('span','port-localhost').textContent=Common.UIString('localhost:');port.createTextChild(rule.port);element.createChild('div','port-forwarding-separator');element.createChild('div','port-forwarding-value').textContent=rule.address;return element;}
removeItemRequested(rule,index){this._portForwardingConfig.splice(index,1);this._list.removeItem(index);this._update();}
commitEdit(rule,editor,isNew){rule.port=editor.control('port').value.trim();rule.address=editor.control('address').value.trim();if(isNew)
this._portForwardingConfig.push(rule);this._update();}
beginEdit(rule){const editor=this._createEditor();editor.control('port').value=rule.port;editor.control('address').value=rule.address;return editor;}
_createEditor(){if(this._editor)
return this._editor;const editor=new UI.ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const fields=content.createChild('div','port-forwarding-edit-row');fields.createChild('div','port-forwarding-value port-forwarding-port').appendChild(editor.createInput('port','text',ls`Device port (3333)`,portValidator.bind(this)));fields.createChild('div','port-forwarding-separator port-forwarding-separator-invisible');fields.createChild('div','port-forwarding-value').appendChild(editor.createInput('address','text',ls`Local address (dev.example.corp:3333)`,addressValidator));return editor;function portValidator(rule,index,input){const value=input.value.trim();const match=value.match(/^(\d+)$/);if(!match)
return false;const port=parseInt(match[1],10);if(port<1024||port>65535)
return false;for(let i=0;i<this._portForwardingConfig.length;++i){if(i!==index&&this._portForwardingConfig[i].port===value)
return false;}
return true;}
function addressValidator(rule,index,input){const match=input.value.trim().match(/^([a-zA-Z0-9\.\-_]+):(\d+)$/);if(!match)
return false;const port=parseInt(match[2],10);return port<=65535;}}};Devices.DevicesView.DeviceView=class extends UI.VBox{constructor(){super();this.setMinimumSize(100,100);this.contentElement.classList.add('device-view');const topRow=this.contentElement.createChild('div','hbox device-text-row');this._deviceTitle=topRow.createChild('div','view-title');this._deviceSerial=topRow.createChild('div','device-serial');this._portStatus=this.contentElement.createChild('div','device-port-status hidden');this._deviceOffline=this.contentElement.createChild('div');this._deviceOffline.textContent=Common.UIString('Pending authentication: please accept debugging session on the device.');this._noBrowsers=this.contentElement.createChild('div');this._noBrowsers.textContent=Common.UIString('No browsers detected.');this._browsers=this.contentElement.createChild('div','device-browser-list vbox');this._browserById=new Map();this._cachedPortStatus=null;this._device=null;}
update(device){if(!this._device||this._device.adbModel!==device.adbModel)
this._deviceTitle.textContent=device.adbModel;if(!this._device||this._device.adbSerial!==device.adbSerial)
this._deviceSerial.textContent='#'+device.adbSerial;this._deviceOffline.classList.toggle('hidden',device.adbConnected);this._noBrowsers.classList.toggle('hidden',!device.adbConnected||!!device.browsers.length);this._browsers.classList.toggle('hidden',!device.adbConnected||!device.browsers.length);const browserIds=new Set();for(const browser of device.browsers)
browserIds.add(browser.id);for(const browserId of this._browserById.keys()){if(!browserIds.has(browserId)){this._browserById.get(browserId).element.remove();this._browserById.remove(browserId);}}
for(const browser of device.browsers){let section=this._browserById.get(browser.id);if(!section){section=this._createBrowserSection();this._browserById.set(browser.id,section);this._browsers.appendChild(section.element);}
this._updateBrowserSection(section,browser);}
this._device=device;}
_createBrowserSection(){const element=createElementWithClass('div','vbox flex-none');const topRow=element.createChild('div','');const title=topRow.createChild('div','device-browser-title');const newTabRow=element.createChild('div','device-browser-new-tab');newTabRow.createChild('div','').textContent=Common.UIString('New tab:');const newTabInput=UI.createInput('','text');newTabRow.appendChild(newTabInput);newTabInput.placeholder=Common.UIString('Enter URL');newTabInput.addEventListener('keydown',newTabKeyDown,false);const newTabButton=UI.createTextButton(Common.UIString('Open'),openNewTab);newTabRow.appendChild(newTabButton);const pages=element.createChild('div','device-page-list vbox');const viewMore=element.createChild('div','device-view-more');viewMore.addEventListener('click',viewMoreClick,false);updateViewMoreTitle();const section={browser:null,element:element,title:title,pages:pages,viewMore:viewMore,newTab:newTabRow,pageSections:new Map()};return section;function viewMoreClick(){pages.classList.toggle('device-view-more-toggled');updateViewMoreTitle();}
function updateViewMoreTitle(){viewMore.textContent=pages.classList.contains('device-view-more-toggled')?Common.UIString('View less tabs\u2026'):Common.UIString('View more tabs\u2026');}
function newTabKeyDown(event){if(event.key==='Enter'){event.consume(true);openNewTab();}}
function openNewTab(){if(section.browser){InspectorFrontendHost.openRemotePage(section.browser.id,newTabInput.value.trim()||'about:blank');newTabInput.value='';}}}
_updateBrowserSection(section,browser){if(!section.browser||section.browser.adbBrowserName!==browser.adbBrowserName||section.browser.adbBrowserVersion!==browser.adbBrowserVersion){if(browser.adbBrowserVersion)
section.title.textContent=String.sprintf('%s (%s)',browser.adbBrowserName,browser.adbBrowserVersion);else
section.title.textContent=browser.adbBrowserName;}
const pageIds=new Set();for(const page of browser.pages)
pageIds.add(page.id);for(const pageId of section.pageSections.keys()){if(!pageIds.has(pageId)){section.pageSections.get(pageId).element.remove();section.pageSections.remove(pageId);}}
for(let index=0;index<browser.pages.length;++index){const page=browser.pages[index];let pageSection=section.pageSections.get(page.id);if(!pageSection){pageSection=this._createPageSection();section.pageSections.set(page.id,pageSection);section.pages.appendChild(pageSection.element);}
this._updatePageSection(pageSection,page);if(!index&&section.pages.firstChild!==pageSection.element)
section.pages.insertBefore(pageSection.element,section.pages.firstChild);}
const kViewMoreCount=3;for(let index=0,element=section.pages.firstChild;element;element=element.nextSibling,++index)
element.classList.toggle('device-view-more-page',index>=kViewMoreCount);section.viewMore.classList.toggle('device-needs-view-more',browser.pages.length>kViewMoreCount);section.newTab.classList.toggle('hidden',!browser.adbBrowserChromeVersion);section.browser=browser;}
_createPageSection(){const element=createElementWithClass('div','vbox');const titleRow=element.createChild('div','device-page-title-row');const title=titleRow.createChild('div','device-page-title');const inspect=UI.createTextButton(Common.UIString('Inspect'),doAction.bind(null,'inspect'));titleRow.appendChild(inspect);const toolbar=new UI.Toolbar('');toolbar.appendToolbarItem(new UI.ToolbarMenuButton(appendActions));titleRow.appendChild(toolbar.element);const url=element.createChild('div','device-page-url');const section={page:null,element:element,title:title,url:url,inspect:inspect};return section;function appendActions(contextMenu){contextMenu.defaultSection().appendItem(Common.UIString('Reload'),doAction.bind(null,'reload'));contextMenu.defaultSection().appendItem(Common.UIString('Focus'),doAction.bind(null,'activate'));contextMenu.defaultSection().appendItem(Common.UIString('Close'),doAction.bind(null,'close'));}
function doAction(action){if(section.page)
InspectorFrontendHost.performActionOnRemotePage(section.page.id,action);}}
_updatePageSection(section,page){if(!section.page||section.page.name!==page.name){section.title.textContent=page.name;section.title.title=page.name;}
if(!section.page||section.page.url!==page.url){section.url.textContent='';section.url.appendChild(UI.XLink.create(page.url));}
section.inspect.disabled=page.attached;section.page=page;}
portForwardingStatusChanged(status){const json=JSON.stringify(status);if(json===this._cachedPortStatus)
return;this._cachedPortStatus=json;this._portStatus.removeChildren();this._portStatus.createChild('div','device-port-status-text').textContent=Common.UIString('Port Forwarding:');const connected=[];const transient=[];const error=[];let empty=true;for(const port in status.ports){if(!status.ports.hasOwnProperty(port))
continue;empty=false;const portStatus=status.ports[port];const portNumber=createElementWithClass('div','device-view-port-number monospace');portNumber.textContent=':'+port;if(portStatus>=0)
this._portStatus.appendChild(portNumber);else
this._portStatus.insertBefore(portNumber,this._portStatus.firstChild);const portIcon=createElementWithClass('div','device-view-port-icon');if(portStatus>=0){connected.push(port);}else if(portStatus===-1||portStatus===-2){portIcon.classList.add('device-view-port-icon-transient');transient.push(port);}else if(portStatus<0){portIcon.classList.add('device-view-port-icon-error');error.push(port);}
this._portStatus.insertBefore(portIcon,portNumber);}
const title=[];if(connected.length)
title.push(Common.UIString('Connected: %s',connected.join(', ')));if(transient.length)
title.push(Common.UIString('Transient: %s',transient.join(', ')));if(error.length)
title.push(Common.UIString('Error: %s',error.join(', ')));this._portStatus.title=title.join('; ');this._portStatus.classList.toggle('hidden',empty);}};Devices.DevicesView.BrowserSection;Devices.DevicesView.PageSection;;Runtime.cachedResources["devices/devicesView.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.devices-container {\n overflow: hidden;\n flex: auto;\n}\n\n.devices-sidebar {\n flex: 0 0 150px;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n margin: 15px 10px 0 0;\n}\n\n.devices-sidebar-list {\n flex: auto;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n overflow: auto;\n}\n\n.devices-sidebar-item {\n color: #222 !important;\n padding: 6px 6px 6px 16px;\n flex: auto;\n display: flex;\n flex-direction: column;\n justify-content: center;\n font-size: 14px;\n flex: none;\n}\n\n.devices-sidebar-item.selected {\n border-left: 6px solid #666 !important;\n padding-left: 10px;\n}\n\n.devices-sidebar-item-status:before {\n content: \"\\25cf\";\n font-size: 16px;\n color: red;\n position: relative;\n top: 1px;\n margin-right: 2px;\n}\n\n.devices-sidebar-item.device-connected .devices-sidebar-item-status:before {\n color: green;\n}\n\n.devices-sidebar-spacer {\n flex: none;\n}\n\n.devices-view-title {\n font-size: 16px;\n margin: 0 0 15px 15px;\n padding-top: 1px;\n flex: none;\n}\n\n.view-title {\n font-size: 16px;\n flex: none;\n}\n\n.devices-footer {\n border-top: 1px solid #cdcdcd;\n background-color: var(--toolbar-bg-color);\n flex: none;\n padding: 3px 10px;\n overflow: hidden;\n}\n\n.devices-footer > span {\n white-space: pre;\n}\n\n.discovery-view {\n overflow-x: hidden;\n overflow-y: auto;\n padding: 15px 15px 0px 0px;\n}\n\n.discovery-view > * {\n flex: none;\n}\n\n.usb-checkbox {\n padding-bottom: 8px;\n margin-top: 20px;\n}\n\n.port-forwarding-header {\n display: flex;\n align-items: center;\n flex-direction: row;\n margin-top: 5px;\n}\n\n.add-rule-button {\n margin: 10px 25px;\n align-self: flex-start;\n}\n\n.discovery-help {\n margin: 5px 0 25px 25px;\n}\n\n.discovery-help > span {\n white-space: pre;\n}\n\n.port-forwarding-list {\n margin: 10px 0 0 25px;\n max-width: 500px;\n flex: none;\n}\n\n.port-forwarding-list-empty {\n flex: auto;\n height: 30px;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.port-forwarding-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n position: relative;\n flex: auto 1 1;\n}\n\n.list-item .port-forwarding-value {\n white-space: nowrap;\n text-overflow: ellipsis;\n -webkit-user-select: none;\n color: #222;\n overflow: hidden;\n}\n\n.port-forwarding-value {\n flex: 3 1 0;\n}\n\n.port-forwarding-value.port-forwarding-port {\n flex: 1 1 0;\n}\n\n.port-localhost {\n color: #aaa;\n}\n\n.port-forwarding-separator {\n flex: 0 0 1px;\n background-color: rgb(231, 231, 231);\n height: 30px;\n margin: 0 4px;\n}\n\n.port-forwarding-separator-invisible {\n visibility: hidden;\n height: 100% !important;\n}\n\n.port-forwarding-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 6px 5px;\n align-items: center;\n}\n\n.port-forwarding-edit-row input {\n width: 100%;\n text-align: inherit;\n}\n\n.port-forwarding-footer {\n overflow: hidden;\n margin: 15px 0 0 25px;\n max-width: 500px;\n}\n\n.port-forwarding-footer > * {\n white-space: pre-wrap;\n}\n\n.add-network-target-button {\n margin: 10px 25px;\n align-self: flex-start;\n}\n\n.network-discovery-list {\n margin: 10px 0 0 25px;\n max-width: 500px;\n flex: none;\n}\n\n.network-discovery-list-empty {\n flex: auto;\n height: 30px;\n display: flex;\n align-items:
differ.diff_cleanupSemantic(diff);return diff;},lineDiff:function(lines1,lines2){const idMap=new Common.CharacterIdMap();const text1=lines1.map(line=>idMap.toChar(line)).join('');const text2=lines2.map(line=>idMap.toChar(line)).join('');const diff=Diff.Diff.charDiff(text1,text2);const lineDiff=[];for(let i=0;i<diff.length;i++){const lines=[];for(let j=0;j<diff[i][1].length;j++)
lines.push(idMap.fromChar(diff[i][1][j]));lineDiff.push({0:diff[i][0],1:lines});}
return lineDiff;},convertToEditDiff:function(diff){const normalized=[];let added=0;let removed=0;for(let i=0;i<diff.length;++i){const token=diff[i];if(token[0]===Diff.Diff.Operation.Equal){flush();normalized.push([Diff.Diff.Operation.Equal,token[1].length]);}else if(token[0]===Diff.Diff.Operation.Delete){removed+=token[1].length;}else{added+=token[1].length;}}
flush();return normalized;function flush(){if(added&&removed){const min=Math.min(added,removed);normalized.push([Diff.Diff.Operation.Edit,min]);added-=min;removed-=min;}
if(added||removed){const balance=added-removed;const type=balance<0?Diff.Diff.Operation.Delete:Diff.Diff.Operation.Insert;normalized.push([type,Math.abs(balance)]);added=0;removed=0;}}}};Diff.Diff.Operation={Equal:0,Insert:1,Delete:-1,Edit:2};Diff.Diff.DiffArray;;(function(){function diff_match_patch(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=0.5;this.Match_Distance=1E3;this.Patch_DeleteThreshold=0.5;this.Patch_Margin=4;this.Match_MaxBits=32}
diff_match_patch.prototype.diff_main=function(a,b,c,d){"undefined"==typeof d&&(d=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1E3*this.Diff_Timeout);if(null==a||null==b)throw Error("Null input. (diff_main)");if(a==b)return a?[[0,a]]:[];"undefined"==typeof c&&(c=!0);var e=c,f=this.diff_commonPrefix(a,b);c=a.substring(0,f);a=a.substring(f);b=b.substring(f);var f=this.diff_commonSuffix(a,b),g=a.substring(a.length-f);a=a.substring(0,a.length-f);b=b.substring(0,b.length-f);a=this.diff_compute_(a,b,e,d);c&&a.unshift([0,c]);g&&a.push([0,g]);this.diff_cleanupMerge(a);return a};diff_match_patch.prototype.diff_compute_=function(a,b,c,d){if(!a)return[[1,b]];if(!b)return[[-1,a]];var e=a.length>b.length?a:b,f=a.length>b.length?b:a,g=e.indexOf(f);return-1!=g?(c=[[1,e.substring(0,g)],[0,f],[1,e.substring(g+f.length)]],a.length>b.length&&(c[0][0]=c[2][0]=-1),c):1==f.length?[[-1,a],[1,b]]:(e=this.diff_halfMatch_(a,b))?(f=e[0],a=e[1],g=e[2],b=e[3],e=e[4],f=this.diff_main(f,g,c,d),c=this.diff_main(a,b,c,d),f.concat([[0,e]],c)):c&&100<a.length&&100<b.length?this.diff_lineMode_(a,b,d):this.diff_bisect_(a,b,d)};diff_match_patch.prototype.diff_lineMode_=function(a,b,c){var d=this.diff_linesToChars_(a,b);a=d.chars1;b=d.chars2;d=d.lineArray;a=this.diff_main(a,b,!1,c);this.diff_charsToLines_(a,d);this.diff_cleanupSemantic(a);a.push([0,""]);for(var e=d=b=0,f="",g="";b<a.length;){switch(a[b][0]){case 1:e++;g+=a[b][1];break;case-1:d++;f+=a[b][1];break;case 0:if(1<=d&&1<=e){a.splice(b-d-e,d+e);b=b-d-e;d=this.diff_main(f,g,!1,c);for(e=d.length-1;0<=e;e--)a.splice(b,0,d[e]);b+=d.length}d=e=0;g=f=""}b++}a.pop();return a};diff_match_patch.prototype.diff_bisect_=function(a,b,c){for(var d=a.length,e=b.length,f=Math.ceil((d+e)/2),g=f,h=2*f,j=Array(h),i=Array(h),k=0;k<h;k++)j[k]=-1,i[k]=-1;j[g+1]=0;i[g+1]=0;for(var k=d-e,q=0!=k%2,r=0,t=0,p=0,w=0,v=0;v<f&&!((new Date).getTime()>c);v++){for(var n=-v+r;n<=v-t;n+=2){var l=g+n,m;m=n==-v||n!=v&&j[l-1]<j[l+1]?j[l+1]:j[l-1]+1;for(var s=m-n;m<d&&s<e&&a.charAt(m)==b.charAt(s);)m++,s++;j[l]=m;if(m>d)t+=2;else if(s>e)r+=2;else if(q&&(l=g+k-n,0<=l&&l<h&&-1!=i[l])){var u=d-i[l];if(m>=u)return this.diff_bisectSplit_(a,b,m,s,c)}}for(n=-v+p;n<=v-w;n+=2){l=g+n;u=n==-v||n!=v&&i[l-1]<i[l+1]?i[l+1]:i[l-1]+1;for(m=u-n;u<d&&m<e&&a.charAt(d-u-1)==b.charAt(e-m-1);)u++,m++;i[l]=u;if(u>d)w+=2;else if(m>e)p+=2;else if(!q&&(l=g+k-n,0<=l&&(l<h&&-1!=j[l])&&(m=j[l],s=g+m-l,u=d-u,m>=u)))return this.diff_bisectSplit_(a,b,m,s,c)}}return[[-1,a],[1,b]]};diff_match_patch.prototype.diff_bisectSplit_=function(a,b,c,d,e){var f=a.substring(0,c),g=b.substring(0,d);a=a.substring(c);b=b.substring(d);f=this.diff_main(f,g,!1,e);e=this.diff_main(a,b,!1,e);return f.concat(e)};diff_match_patch.prototype.diff_linesToChars_=function(a,b){function c(a){for(var b="",c=0,f=-1,g=d.length;f<a.length-1;){f=a.indexOf("\n",c);-1==f&&(f=a.length-1);var r=a.substring(c,f+1),c=f+1;(e.hasOwnProperty?e.hasOwnProperty(r):void 0!==e[r])?b+=String.fromCharCode(e[r]):(b+=String.fromCharCode(g),e[r]=g,d[g++]=r)}return b}var d=[],e={};d[0]="";var f=c(a),g=c(b);return{chars1:f,chars2:g,lineArray:d}};diff_match_patch.prototype.diff_charsToLines_=function(a,b){for(var c=0;c<a.length;c++){for(var d=a[c][1],e=[],f=0;f<d.length;f++)e[f]=b[d.charCodeAt(f)];a[c][1]=e.join("")}};diff_match_patch.prototype.diff_commonPrefix=function(a,b){if(!a||!b||a.charAt(0)!=b.charAt(0))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(f,e)==b.substring(f,e)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};diff_match_patch.prototype.diff_commonSuffix=function(a,b){if(!a||!b||a.charAt(a.length-1)!=b.charAt(b.length-1))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(a.length-e,a.length-f)==b.substring(b.length-e,b.length-f)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};diff_match_patch.prototype.diff_commonOverlap_=function(a,b){var c=a.length,d=b.length;if(0==c||0==d)return 0;c>d?a=a.substring(c-d):c<d&&(b=b.substring(0,c));c=Math.min(c,d);if(a==b)return c;for(var d=0,e=1;;){var f=a.substring(c-e),f=b.indexOf(f);if(-1==f)return d;e+=f;if(0==
g),e=e.substring(0,e.length-g))),0===c?a.splice(b-d,c+d,[1,f]):0===d?a.splice(b-c,c+d,[-1,e]):a.splice(b-c-d,c+d,[-1,e],[1,f]),b=b-c-d+(c?1:0)+(d?1:0)+1):0!==b&&0==a[b-1][0]?(a[b-1][1]+=a[b][1],a.splice(b,1)):b++,c=d=0,f=e=""}""===a[a.length-1][1]&&a.pop();c=!1;for(b=1;b<a.length-1;)0==a[b-1][0]&&0==a[b+1][0]&&(a[b][1].substring(a[b][1].length-a[b-1][1].length)==a[b-1][1]?(a[b][1]=a[b-1][1]+a[b][1].substring(0,a[b][1].length-a[b-1][1].length),a[b+1][1]=a[b-1][1]+a[b+1][1],a.splice(b-1,1),c=!0):a[b][1].substring(0,a[b+1][1].length)==a[b+1][1]&&(a[b-1][1]+=a[b+1][1],a[b][1]=a[b][1].substring(a[b+1][1].length)+a[b+1][1],a.splice(b+1,1),c=!0)),b++;c&&this.diff_cleanupMerge(a)};diff_match_patch.prototype.diff_xIndex=function(a,b){var c=0,d=0,e=0,f=0,g;for(g=0;g<a.length;g++){1!==a[g][0]&&(c+=a[g][1].length);-1!==a[g][0]&&(d+=a[g][1].length);if(c>b)break;e=c;f=d}return a.length!=g&&-1===a[g][0]?f:f+(b-e)};diff_match_patch.prototype.diff_prettyHtml=function(a){for(var b=[],c=/&/g,d=/</g,e=/>/g,f=/\n/g,g=0;g<a.length;g++){var h=a[g][0],j=a[g][1],j=j.replace(c,"&amp;").replace(d,"&lt;").replace(e,"&gt;").replace(f,"&para;<br>");switch(h){case 1:b[g]='<ins style="background:#e6ffe6;">'+j+"</ins>";break;case-1:b[g]='<del style="background:#ffe6e6;">'+j+"</del>";break;case 0:b[g]="<span>"+j+"</span>"}}return b.join("")};diff_match_patch.prototype.diff_text1=function(a){for(var b=[],c=0;c<a.length;c++)1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_text2=function(a){for(var b=[],c=0;c<a.length;c++)-1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_levenshtein=function(a){for(var b=0,c=0,d=0,e=0;e<a.length;e++){var f=a[e][0],g=a[e][1];switch(f){case 1:c+=g.length;break;case-1:d+=g.length;break;case 0:b+=Math.max(c,d),d=c=0}}return b+=Math.max(c,d)};diff_match_patch.prototype.diff_toDelta=function(a){for(var b=[],c=0;c<a.length;c++)switch(a[c][0]){case 1:b[c]="+"+encodeURI(a[c][1]);break;case-1:b[c]="-"+a[c][1].length;break;case 0:b[c]="="+a[c][1].length}return b.join("\t").replace(/%20/g," ")};diff_match_patch.prototype.diff_fromDelta=function(a,b){for(var c=[],d=0,e=0,f=b.split(/\t/g),g=0;g<f.length;g++){var h=f[g].substring(1);switch(f[g].charAt(0)){case"+":try{c[d++]=[1,decodeURI(h)]}catch(j){throw Error("Illegal escape in diff_fromDelta: "+h);}break;case"-":case"=":var i=parseInt(h,10);if(isNaN(i)||0>i)throw Error("Invalid number in diff_fromDelta: "+h);h=a.substring(e,e+=i);"="==f[g].charAt(0)?c[d++]=[0,h]:c[d++]=[-1,h];break;default:if(f[g])throw Error("Invalid diff operation in diff_fromDelta: "+
f[g]);}}if(e!=a.length)throw Error("Delta length ("+e+") does not equal source text length ("+a.length+").");return c};diff_match_patch.prototype.match_main=function(a,b,c){if(null==a||null==b||null==c)throw Error("Null input. (match_main)");c=Math.max(0,Math.min(c,a.length));return a==b?0:a.length?a.substring(c,c+b.length)==b?c:this.match_bitap_(a,b,c):-1};diff_match_patch.prototype.match_bitap_=function(a,b,c){function d(a,d){var e=a/b.length,g=Math.abs(c-d);return!f.Match_Distance?g?1:e:e+g/f.Match_Distance}if(b.length>this.Match_MaxBits)throw Error("Pattern too long for this browser.");var e=this.match_alphabet_(b),f=this,g=this.Match_Threshold,h=a.indexOf(b,c);-1!=h&&(g=Math.min(d(0,h),g),h=a.lastIndexOf(b,c+b.length),-1!=h&&(g=Math.min(d(0,h),g)));for(var j=1<<b.length-1,h=-1,i,k,q=b.length+a.length,r,t=0;t<b.length;t++){i=0;for(k=q;i<k;)d(t,c+
k)<=g?i=k:q=k,k=Math.floor((q-i)/2+i);q=k;i=Math.max(1,c-k+1);var p=Math.min(c+k,a.length)+b.length;k=Array(p+2);for(k[p+1]=(1<<t)-1;p>=i;p--){var w=e[a.charAt(p-1)];k[p]=0===t?(k[p+1]<<1|1)&w:(k[p+1]<<1|1)&w|((r[p+1]|r[p])<<1|1)|r[p+1];if(k[p]&j&&(w=d(t,p-1),w<=g))if(g=w,h=p-1,h>c)i=Math.max(1,2*c-h);else break}if(d(t+1,c)>g)break;r=k}return h};diff_match_patch.prototype.match_alphabet_=function(a){for(var b={},c=0;c<a.length;c++)b[a.charAt(c)]=0;for(c=0;c<a.length;c++)b[a.charAt(c)]|=1<<a.length-c-1;return b};diff_match_patch.prototype.patch_addContext_=function(a,b){if(0!=b.length){for(var c=b.substring(a.start2,a.start2+a.length1),d=0;b.indexOf(c)!=b.lastIndexOf(c)&&c.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)d+=this.Patch_Margin,c=b.substring(a.start2-d,a.start2+a.length1+d);d+=this.Patch_Margin;(c=b.substring(a.start2-d,a.start2))&&a.diffs.unshift([0,c]);(d=b.substring(a.start2+a.length1,a.start2+a.length1+d))&&a.diffs.push([0,d]);a.start1-=c.length;a.start2-=c.length;a.length1+=c.length+d.length;a.length2+=c.length+d.length}};diff_match_patch.prototype.patch_make=function(a,b,c){var d;if("string"==typeof a&&"string"==typeof b&&"undefined"==typeof c)d=a,b=this.diff_main(d,b,!0),2<b.length&&(this.diff_cleanupSemantic(b),this.diff_cleanupEfficiency(b));else if(a&&"object"==typeof a&&"undefined"==typeof b&&"undefined"==typeof c)b=a,d=this.diff_text1(b);else if("string"==typeof a&&b&&"object"==typeof b&&"undefined"==typeof c)d=a;else if("string"==typeof a&&"string"==typeof b&&c&&"object"==typeof c)d=a,b=c;else throw Error("Unknown call format to patch_make.");if(0===b.length)return[];c=[];a=new diff_match_patch.patch_obj;for(var e=0,f=0,g=0,h=d,j=0;j<b.length;j++){var i=b[j][0],k=b[j][1];!e&&0!==i&&(a.start1=f,a.start2=g);switch(i){case 1:a.diffs[e++]=b[j];a.length2+=k.length;d=d.substring(0,g)+k+d.substring(g);break;case-1:a.length1+=k.length;a.diffs[e++]=b[j];d=d.substring(0,g)+d.substring(g+k.length);break;case 0:k.length<=2*this.Patch_Margin&&e&&b.length!=j+1?(a.diffs[e++]=b[j],a.length1+=k.length,a.length2+=k.length):k.length>=2*this.Patch_Margin&&e&&(this.patch_addContext_(a,h),c.push(a),a=new diff_match_patch.patch_obj,e=0,h=d,f=g)}1!==i&&(f+=k.length);-1!==i&&(g+=k.length)}e&&(this.patch_addContext_(a,h),c.push(a));return c};diff_match_patch.prototype.patch_deepCopy=function(a){for(var b=[],c=0;c<a.length;c++){var d=a[c],e=new diff_match_patch.patch_obj;e.diffs=[];for(var f=0;f<d.diffs.length;f++)e.diffs[f]=d.diffs[f].slice();e.start1=d.start1;e.start2=d.start2;e.length1=d.length1;e.length2=d.length2;b[c]=e}return b};diff_match_patch.prototype.patch_apply=function(a,b){if(0==a.length)return[b,[]];a=this.patch_deepCopy(a);var c=this.patch_addPadding(a);b=c+b+c;this.patch_splitMax(a);for(var d=0,e=[],f=0;f<a.length;f++){var g=a[f].start2+d,h=this.diff_text1(a[f].diffs),j,i=-1;if(h.length>this.Match_MaxBits){if(j=this.match_main(b,h.substring(0,this.Match_MaxBits),g),-1!=j&&(i=this.match_main(b,h.substring(h.length-this.Match_MaxBits),g+h.length-this.Match_MaxBits),-1==i||j>=i))j=-1}else j=this.match_main(b,h,g);if(-1==j)e[f]=!1,d-=a[f].length2-a[f].length1;else if(e[f]=!0,d=j-g,g=-1==i?b.substring(j,j+h.length):b.substring(j,i+this.Match_MaxBits),h==g)b=b.substring(0,j)+this.diff_text2(a[f].diffs)+b.substring(j+h.length);else if(g=this.diff_main(h,g,!1),h.length>this.Match_MaxBits&&this.diff_levenshtein(g)/h.length>this.Patch_DeleteThreshold)e[f]=!1;else{this.diff_cleanupSemanticLossless(g);for(var h=0,k,i=0;i<a[f].diffs.length;i++){var q=a[f].diffs[i];0!==q[0]&&(k=this.diff_xIndex(g,h));1===q[0]?b=b.substring(0,j+k)+q[1]+b.substring(j+k):-1===q[0]&&(b=b.substring(0,j+k)+b.substring(j+this.diff_xIndex(g,h+q[1].length)));-1!==q[0]&&(h+=q[1].length)}}}b=b.substring(c.length,b.length-c.length);return[b,e]};diff_match_patch.prototype.patch_addPadding=function(a){for(var b=this.Patch_Margin,c="",d=1;d<=b;d++)c+=String.fromCharCode(d);for(d=0;d<a.length;d++)a[d].start1+=b,a[d].start2+=b;var d=a[0],e=d.diffs;if(0==e.length||0!=e[0][0])e.unshift([0,c]),d.start1-=b,d.start2-=b,d.length1+=b,d.length2+
return;if(!this._isInInspectElementMode())
return;this._setMode(Protocol.Overlay.InspectMode.None);event.consume(true);},true);}
modelAdded(overlayModel){if(this._mode===Protocol.Overlay.InspectMode.None)
return;overlayModel.setInspectMode(this._mode,this._showDetailedInspectTooltipSetting.get());}
modelRemoved(overlayModel){}
_isInInspectElementMode(){return this._mode!==Protocol.Overlay.InspectMode.None;}
_toggleInspectMode(){let mode;if(this._isInInspectElementMode()){mode=Protocol.Overlay.InspectMode.None;}else{mode=Common.moduleSetting('showUAShadowDOM').get()?Protocol.Overlay.InspectMode.SearchForUAShadowDOM:Protocol.Overlay.InspectMode.SearchForNode;}
this._setMode(mode);}
_captureScreenshotMode(){this._setMode(Protocol.Overlay.InspectMode.CaptureAreaScreenshot);}
_setMode(mode){if(SDK.targetManager.allTargetsSuspended())
return;this._mode=mode;for(const overlayModel of SDK.targetManager.models(SDK.OverlayModel))
overlayModel.setInspectMode(mode,this._showDetailedInspectTooltipSetting.get());this._toggleSearchAction.setToggled(this._isInInspectElementMode());}
_suspendStateChanged(){if(!SDK.targetManager.allTargetsSuspended())
return;this._mode=Protocol.Overlay.InspectMode.None;this._toggleSearchAction.setToggled(false);}
async _inspectNode(node){Elements.ElementsPanel.instance().revealAndSelectNode(node,true,true);}
_showDetailedInspectTooltipChanged(){this._setMode(this._mode);}};Elements.InspectElementModeController.ToggleSearchActionDelegate=class{handleAction(context,actionId){if(!Elements.inspectElementModeController)
return false;if(actionId==='elements.toggle-element-search')
Elements.inspectElementModeController._toggleInspectMode();else if(actionId==='elements.capture-area-screenshot')
Elements.inspectElementModeController._captureScreenshotMode();return true;}};Elements.inspectElementModeController=Runtime.queryParam('isSharedWorker')?null:new Elements.InspectElementModeController();;Elements.BezierPopoverIcon=class{constructor(treeElement,swatchPopoverHelper,swatch){this._treeElement=treeElement;this._swatchPopoverHelper=swatchPopoverHelper;this._swatch=swatch;this._swatch.iconElement().title=Common.UIString('Open cubic bezier editor.');this._swatch.iconElement().addEventListener('click',this._iconClick.bind(this),false);this._swatch.iconElement().addEventListener('mousedown',event=>event.consume(),false);this._boundBezierChanged=this._bezierChanged.bind(this);this._boundOnScroll=this._onScroll.bind(this);}
_iconClick(event){event.consume(true);if(this._swatchPopoverHelper.isShowing()){this._swatchPopoverHelper.hide(true);return;}
this._bezierEditor=new InlineEditor.BezierEditor();let cubicBezier=UI.Geometry.CubicBezier.parse(this._swatch.bezierText());if(!cubicBezier){cubicBezier=(UI.Geometry.CubicBezier.parse('linear'));}
this._bezierEditor.setBezier(cubicBezier);this._bezierEditor.addEventListener(InlineEditor.BezierEditor.Events.BezierChanged,this._boundBezierChanged);this._swatchPopoverHelper.show(this._bezierEditor,this._swatch.iconElement(),this._onPopoverHidden.bind(this));this._scrollerElement=this._swatch.enclosingNodeOrSelfWithClass('style-panes-wrapper');if(this._scrollerElement)
this._scrollerElement.addEventListener('scroll',this._boundOnScroll,false);this._originalPropertyText=this._treeElement.property.propertyText;this._treeElement.parentPane().setEditingStyle(true);const uiLocation=Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property,false);if(uiLocation)
Common.Revealer.reveal(uiLocation,true);}
_bezierChanged(event){this._swatch.setBezierText((event.data));this._treeElement.applyStyleText(this._treeElement.renderedPropertyText(),false);}
_onScroll(event){this._swatchPopoverHelper.reposition();}
_onPopoverHidden(commitEdit){if(this._scrollerElement)
this._scrollerElement.removeEventListener('scroll',this._boundOnScroll,false);this._bezierEditor.removeEventListener(InlineEditor.BezierEditor.Events.BezierChanged,this._boundBezierChanged);delete this._bezierEditor;const propertyText=commitEdit?this._treeElement.renderedPropertyText():this._originalPropertyText;this._treeElement.applyStyleText(propertyText,true);this._treeElement.parentPane().setEditingStyle(false);delete this._originalPropertyText;}};Elements.ColorSwatchPopoverIcon=class{constructor(treeElement,swatchPopoverHelper,swatch){this._treeElement=treeElement;this._treeElement[Elements.ColorSwatchPopoverIcon._treeElementSymbol]=this;this._swatchPopoverHelper=swatchPopoverHelper;this._swatch=swatch;const shiftClickMessage=Common.UIString('Shift + Click to change color format.');this._swatch.iconElement().title=Common.UIString('Open color picker. %s',shiftClickMessage);this._swatch.iconElement().addEventListener('click',this._iconClick.bind(this));this._swatch.iconElement().addEventListener('mousedown',event=>event.consume(),false);this._contrastInfo=null;this._boundSpectrumChanged=this._spectrumChanged.bind(this);this._boundOnScroll=this._onScroll.bind(this);}
_generateCSSVariablesPalette(){const matchedStyles=this._treeElement.matchedStyles();const style=this._treeElement.property.ownerStyle;const cssVariables=matchedStyles.availableCSSVariables(style);const colors=[];const colorNames=[];for(const cssVariable of cssVariables){if(cssVariable===this._treeElement.property.name)
continue;const value=matchedStyles.computeCSSVariable(style,cssVariable);if(!value)
continue;const color=Common.Color.parse(value);if(!color)
continue;colors.push(value);colorNames.push(cssVariable);}
return{title:'CSS Variables',mutable:false,matchUserFormat:true,colors:colors,colorNames:colorNames};}
static forTreeElement(treeElement){return treeElement[Elements.ColorSwatchPopoverIcon._treeElementSymbol]||null;}
setContrastInfo(contrastInfo){this._contrastInfo=contrastInfo;}
_iconClick(event){event.consume(true);this.showPopover();}
showPopover(){if(this._swatchPopoverHelper.isShowing()){this._swatchPopoverHelper.hide(true);return;}
const color=this._swatch.color();let format=this._swatch.format();if(format===Common.Color.Format.Original)
format=color.format();this._spectrum=new ColorPicker.Spectrum(this._contrastInfo);this._spectrum.setColor(color,format);this._spectrum.addPalette(this._generateCSSVariablesPalette());this._spectrum.addEventListener(ColorPicker.Spectrum.Events.SizeChanged,this._spectrumResized,this);this._spectrum.addEventListener(ColorPicker.Spectrum.Events.ColorChanged,this._boundSpectrumChanged);this._swatchPopoverHelper.show(this._spectrum,this._swatch.iconElement(),this._onPopoverHidden.bind(this));this._scrollerElement=this._swatch.enclosingNodeOrSelfWithClass('style-panes-wrapper');if(this._scrollerElement)
this._scrollerElement.addEventListener('scroll',this._boundOnScroll,false);this._originalPropertyText=this._treeElement.property.propertyText;this._treeElement.parentPane().setEditingStyle(true);const uiLocation=Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property,false);if(uiLocation)
Common.Revealer.reveal(uiLocation,true);}
_spectrumResized(event){this._swatchPopoverHelper.reposition();}
_spectrumChanged(event){const color=Common.Color.parse((event.data));if(!color)
return;this._swatch.setColor(color);const colorName=this._spectrum.colorName();if(colorName&&colorName.startsWith('--'))
this._swatch.setText(`var(${colorName})`);this._treeElement.applyStyleText(this._treeElement.renderedPropertyText(),false);}
_onScroll(event){this._swatchPopoverHelper.reposition();}
_onPopoverHidden(commitEdit){if(this._scrollerElement)
this._scrollerElement.removeEventListener('scroll',this._boundOnScroll,false);this._spectrum.removeEventListener(ColorPicker.Spectrum.Events.ColorChanged,this._boundSpectrumChanged);delete this._spectrum;const propertyText=commitEdit?this._treeElement.renderedPropertyText():this._originalPropertyText;this._treeElement.applyStyleText(propertyText,true);this._treeElement.parentPane().setEditingStyle(false);delete this._originalPropertyText;}};Elements.ColorSwatchPopoverIcon._treeElementSymbol=Symbol('Elements.ColorSwatchPopoverIcon._treeElementSymbol');Elements.ShadowSwatchPopoverHelper=class{constructor(treeElement,swatchPopoverHelper,shadowSwatch){this._treeElement=treeElement;this._treeElement[Elements.ShadowSwatchPopoverHelper._treeElementSymbol]=this;this._swatchPopoverHelper=swatchPopoverHelper;this._shadowSwatch=shadowSwatch;this._iconElement=shadowSwatch.iconElement();this._iconElement.title=Common.UIString('Open shadow editor.');this._iconElement.addEventListener('click',this._iconClick.bind(this),false);this._iconElement.addEventListener('mousedown',event=>event.consume(),false);this._boundShadowChanged=this._shadowChanged.bind(this);this._boundOnScroll=this._onScroll.bind(this);}
static forTreeElement(treeElement){return treeElement[Elements.ShadowSwatchPopoverHelper._treeElementSymbol]||null;}
_iconClick(event){event.consume(true);this.showPopover();}
showPopover(){if(this._swatchPopoverHelper.isShowing()){this._swatchPopoverHelper.hide(true);return;}
this._cssShadowEditor=new InlineEditor.CSSShadowEditor();this._cssShadowEditor.setModel(this._shadowSwatch.model());this._cssShadowEditor.addEventListener(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._boundShadowChanged);this._swatchPopoverHelper.show(this._cssShadowEditor,this._iconElement,this._onPopoverHidden.bind(this));this._scrollerElement=this._iconElement.enclosingNodeOrSelfWithClass('style-panes-wrapper');if(this._scrollerElement)
this._scrollerElement.addEventListener('scroll',this._boundOnScroll,false);this._originalPropertyText=this._treeElement.property.propertyText;this._treeElement.parentPane().setEditingStyle(true);const uiLocation=Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property,false);if(uiLocation)
Common.Revealer.reveal(uiLocation,true);}
_shadowChanged(event){this._shadowSwatch.setCSSShadow((event.data));this._treeElement.applyStyleText(this._treeElement.renderedPropertyText(),false);}
_onScroll(event){this._swatchPopoverHelper.reposition();}
_onPopoverHidden(commitEdit){if(this._scrollerElement)
this._scrollerElement.removeEventListener('scroll',this._boundOnScroll,false);this._cssShadowEditor.removeEventListener(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._boundShadowChanged);delete this._cssShadowEditor;const propertyText=commitEdit?this._treeElement.renderedPropertyText():this._originalPropertyText;this._treeElement.applyStyleText(propertyText,true);this._treeElement.parentPane().setEditingStyle(false);delete this._originalPropertyText;}};Elements.ShadowSwatchPopoverHelper._treeElementSymbol=Symbol('Elements.ShadowSwatchPopoverHelper._treeElementSymbol');;Elements.ComputedStyleModel=class extends Common.Object{constructor(){super();this._node=UI.context.flavor(SDK.DOMNode);this._cssModel=null;this._eventListeners=[];UI.context.addFlavorChangeListener(SDK.DOMNode,this._onNodeChanged,this);}
node(){return this._node;}
cssModel(){return this._cssModel&&this._cssModel.isEnabled()?this._cssModel:null;}
_onNodeChanged(event){this._node=(event.data);this._updateModel(this._node?this._node.domModel().cssModel():null);this._onComputedStyleChanged(null);}
_updateModel(cssModel){if(this._cssModel===cssModel)
return;Common.EventTarget.removeEventListeners(this._eventListeners);this._cssModel=cssModel;const domModel=cssModel?cssModel.domModel():null;const resourceTreeModel=cssModel?cssModel.target().model(SDK.ResourceTreeModel):null;if(cssModel&&domModel&&resourceTreeModel){this._eventListeners=[cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.FontsUpdated,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.MediaQueryResultChanged,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.PseudoStateForced,this._onComputedStyleChanged,this),cssModel.addEventListener(SDK.CSSModel.Events.ModelWasEnabled,this._onComputedStyleChanged,this),domModel.addEventListener(SDK.DOMModel.Events.DOMMutated,this._onDOMModelChanged,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameResized,this._onFrameResized,this),];}}
_onComputedStyleChanged(event){delete this._computedStylePromise;this.dispatchEventToListeners(Elements.ComputedStyleModel.Events.ComputedStyleChanged,event?event.data:null);}
_onDOMModelChanged(event){const node=(event.data);if(!this._node||this._node!==node&&node.parentNode!==this._node.parentNode&&!node.isAncestor(this._node))
return;this._onComputedStyleChanged(null);}
_onFrameResized(event){function refreshContents(){this._onComputedStyleChanged(null);delete this._frameResizedTimer;}
if(this._frameResizedTimer)
clearTimeout(this._frameResizedTimer);this._frameResizedTimer=setTimeout(refreshContents.bind(this),100);}
_elementNode(){return this.node()?this.node().enclosingElementOrSelf():null;}
fetchComputedStyle(){const elementNode=this._elementNode();const cssModel=this.cssModel();if(!elementNode||!cssModel)
return Promise.resolve((null));if(!this._computedStylePromise){this._computedStylePromise=cssModel.computedStylePromise(elementNode.id).then(verifyOutdated.bind(this,elementNode));}
return this._computedStylePromise;function verifyOutdated(elementNode,style){return elementNode===this._elementNode()&&style?new Elements.ComputedStyleModel.ComputedStyle(elementNode,style):(null);}}};Elements.ComputedStyleModel.Events={ComputedStyleChanged:Symbol('ComputedStyleChanged')};Elements.ComputedStyleModel.ComputedStyle=class{constructor(node,computedStyle){this.node=node;this.computedStyle=computedStyle;}};;Elements.DOMLinkifier={};Elements.DOMLinkifier.decorateNodeLabel=function(node,parentElement,tooltipContent){const originalNode=node;const isPseudo=node.nodeType()===Node.ELEMENT_NODE&&node.pseudoType();if(isPseudo&&node.parentNode)
node=node.parentNode;let title=node.nodeNameInCorrectCase();const nameElement=parentElement.createChild('span','node-label-name');nameElement.textContent=title;const idAttribute=node.getAttribute('id');if(idAttribute){const idElement=parentElement.createChild('span','node-label-id');const part='#'+idAttribute;title+=part;idElement.createTextChild(part);nameElement.classList.add('extra');}
const classAttribute=node.getAttribute('class');if(classAttribute){const classes=classAttribute.split(/\s+/);const foundClasses={};if(classes.length){const classesElement=parentElement.createChild('span','extra node-label-class');for(let i=0;i<classes.length;++i){const className=classes[i];if(className&&!(className in foundClasses)){const part='.'+className;title+=part;classesElement.createTextChild(part);foundClasses[className]=true;}}}}
if(isPseudo){const pseudoElement=parentElement.createChild('span','extra node-label-pseudo');const pseudoText='::'+originalNode.pseudoType();pseudoElement.createTextChild(pseudoText);title+=pseudoText;}
parentElement.title=tooltipContent||title;};Elements.DOMLinkifier.linkifyNodeReference=function(node,tooltipContent){if(!node)
return createTextNode(Common.UIString('<node>'));const root=createElementWithClass('span','monospace');const shadowRoot=UI.createShadowRootWithCoreStyles(root,'elements/domLinkifier.css');const link=shadowRoot.createChild('div','node-link');Elements.DOMLinkifier.decorateNodeLabel(node,link,tooltipContent);link.addEventListener('click',()=>Common.Revealer.reveal(node,false)&&false,false);link.addEventListener('mouseover',node.highlight.bind(node,undefined),false);link.addEventListener('mouseleave',()=>SDK.OverlayModel.hideDOMNodeHighlight(),false);return root;};Elements.DOMLinkifier.linkifyDeferredNodeReference=function(deferredNode){const root=createElement('div');const shadowRoot=UI.createShadowRootWithCoreStyles(root,'elements/domLinkifier.css');const link=shadowRoot.createChild('div','node-link');link.createChild('slot');link.addEventListener('click',deferredNode.resolve.bind(deferredNode,onDeferredNodeResolved),false);link.addEventListener('mousedown',e=>e.consume(),false);function onDeferredNodeResolved(node){Common.Revealer.reveal(node);}
return root;};Elements.DOMLinkifier.Linkifier=class{linkify(object,options){if(object instanceof SDK.DOMNode)
return Elements.DOMLinkifier.linkifyNodeReference(object,options?options.title:undefined);if(object instanceof SDK.DeferredDOMNode)
return Elements.DOMLinkifier.linkifyDeferredNodeReference(object);throw new Error('Can\'t linkify non-node');}};;Elements.DOMPath={};Elements.DOMPath.fullQualifiedSelector=function(node,justSelector){if(node.nodeType()!==Node.ELEMENT_NODE)
return node.localName()||node.nodeName().toLowerCase();return Elements.DOMPath.cssPath(node,justSelector);};Elements.DOMPath.cssPath=function(node,optimized){if(node.nodeType()!==Node.ELEMENT_NODE)
return'';const steps=[];let contextNode=node;while(contextNode){const step=Elements.DOMPath._cssPathStep(contextNode,!!optimized,contextNode===node);if(!step)
break;steps.push(step);if(step.optimized)
break;contextNode=contextNode.parentNode;}
steps.reverse();return steps.join(' > ');};Elements.DOMPath.canGetJSPath=function(node){let wp=node;while(wp){if(wp.ancestorShadowRoot()&&wp.ancestorShadowRoot().shadowRootType()!==SDK.DOMNode.ShadowRootTypes.Open)
return false;wp=wp.ancestorShadowHost();}
return true;};Elements.DOMPath.jsPath=function(node,optimized){if(node.nodeType()!==Node.ELEMENT_NODE)
return'';const path=[];let wp=node;while(wp){path.push(Elements.DOMPath.cssPath(wp,optimized));wp=wp.ancestorShadowHost();}
path.reverse();let result='';for(let i=0;i<path.length;++i){const string=JSON.stringify(path[i]);if(i)
result+=`.shadowRoot.querySelector(${string})`;else
result+=`document.querySelector(${string})`;}
return result;};Elements.DOMPath._cssPathStep=function(node,optimized,isTargetNode){if(node.nodeType()!==Node.ELEMENT_NODE)
return null;const id=node.getAttribute('id');if(optimized){if(id)
return new Elements.DOMPath.Step(idSelector(id),true);const nodeNameLower=node.nodeName().toLowerCase();if(nodeNameLower==='body'||nodeNameLower==='head'||nodeNameLower==='html')
return new Elements.DOMPath.Step(node.nodeNameInCorrectCase(),true);}
const nodeName=node.nodeNameInCorrectCase();if(id)
return new Elements.DOMPath.Step(nodeName+idSelector(id),true);const parent=node.parentNode;if(!parent||parent.nodeType()===Node.DOCUMENT_NODE)
return new Elements.DOMPath.Step(nodeName,true);function prefixedElementClassNames(node){const classAttribute=node.getAttribute('class');if(!classAttribute)
return[];return classAttribute.split(/\s+/g).filter(Boolean).map(function(name){return'$'+name;});}
function idSelector(id){return'#'+CSS.escape(id);}
const prefixedOwnClassNamesArray=prefixedElementClassNames(node);let needsClassNames=false;let needsNthChild=false;let ownIndex=-1;let elementIndex=-1;const siblings=parent.children();for(let i=0;(ownIndex===-1||!needsNthChild)&&i<siblings.length;++i){const sibling=siblings[i];if(sibling.nodeType()!==Node.ELEMENT_NODE)
continue;elementIndex+=1;if(sibling===node){ownIndex=elementIndex;continue;}
if(needsNthChild)
continue;if(sibling.nodeNameInCorrectCase()!==nodeName)
continue;needsClassNames=true;const ownClassNames=new Set(prefixedOwnClassNamesArray);if(!ownClassNames.size){needsNthChild=true;continue;}
const siblingClassNamesArray=prefixedElementClassNames(sibling);for(let j=0;j<siblingClassNamesArray.length;++j){const siblingClass=siblingClassNamesArray[j];if(!ownClassNames.has(siblingClass))
continue;ownClassNames.delete(siblingClass);if(!ownClassNames.size){needsNthChild=true;break;}}}
let result=nodeName;if(isTargetNode&&nodeName.toLowerCase()==='input'&&node.getAttribute('type')&&!node.getAttribute('id')&&!node.getAttribute('class'))
result+='[type='+CSS.escape(node.getAttribute('type'))+']';if(needsNthChild){result+=':nth-child('+(ownIndex+1)+')';}else if(needsClassNames){for(const prefixedName of prefixedOwnClassNamesArray)
result+='.'+CSS.escape(prefixedName.slice(1));}
return new Elements.DOMPath.Step(result,false);};Elements.DOMPath.xPath=function(node,optimized){if(node.nodeType()===Node.DOCUMENT_NODE)
return'/';const steps=[];let contextNode=node;while(contextNode){const step=Elements.DOMPath._xPathValue(contextNode,optimized);if(!step)
break;steps.push(step);if(step.optimized)
break;contextNode=contextNode.parentNode;}
steps.reverse();return(steps.length&&steps[0].optimized?'':'/')+steps.join('/');};Elements.DOMPath._xPathValue=function(node,optimized){let ownValue;const ownIndex=Elements.DOMPath._xPathIndex(node);if(ownIndex===-1)
return null;switch(node.nodeType()){case Node.ELEMENT_NODE:if(optimized&&node.getAttribute('id'))
return new Elements.DOMPath.Step('//*[@id="'+node.getAttribute('id')+'"]',true);ownValue=node.localName();break;case Node.ATTRIBUTE_NODE:ownValue='@'+node.nodeName();break;case Node.TEXT_NODE:case Node.CDATA_SECTION_NODE:ownValue='text()';break;case Node.PROCESSING_INSTRUCTION_NODE:ownValue='processing-instruction()';break;case Node.COMMENT_NODE:ownValue='comment()';break;case Node.DOCUMENT_NODE:ownValue='';break;default:ownValue='';break;}
if(ownIndex>0)
ownValue+='['+ownIndex+']';return new Elements.DOMPath.Step(ownValue,node.nodeType()===Node.DOCUMENT_NODE);};Elements.DOMPath._xPathIndex=function(node){function areNodesSimilar(left,right){if(left===right)
return true;if(left.nodeType()===Node.ELEMENT_NODE&&right.nodeType()===Node.ELEMENT_NODE)
return left.localName()===right.localName();if(left.nodeType()===right.nodeType())
return true;const leftType=left.nodeType()===Node.CDATA_SECTION_NODE?Node.TEXT_NODE:left.nodeType();const rightType=right.nodeType()===Node.CDATA_SECTION_NODE?Node.TEXT_NODE:right.nodeType();return leftType===rightType;}
const siblings=node.parentNode?node.parentNode.children():null;if(!siblings)
return 0;let hasSameNamedElements;for(let i=0;i<siblings.length;++i){if(areNodesSimilar(node,siblings[i])&&siblings[i]!==node){hasSameNamedElements=true;break;}}
if(!hasSameNamedElements)
return 0;let ownIndex=1;for(let i=0;i<siblings.length;++i){if(areNodesSimilar(node,siblings[i])){if(siblings[i]===node)
return ownIndex;++ownIndex;}}
return-1;};Elements.DOMPath.Step=class{constructor(value,optimized){this.value=value;this.optimized=optimized||false;}
toString(){return this.value;}};;Elements.ElementsBreadcrumbs=class extends UI.HBox{constructor(){super(true);this.registerRequiredCSS('elements/breadcrumbs.css');this.crumbsElement=this.contentElement.createChild('div','crumbs');this.crumbsElement.addEventListener('mousemove',this._mouseMovedInCrumbs.bind(this),false);this.crumbsElement.addEventListener('mouseleave',this._mouseMovedOutOfCrumbs.bind(this),false);this._nodeSymbol=Symbol('node');UI.ARIAUtils.markAsHidden(this.element);}
wasShown(){this.update();}
updateNodes(nodes){if(!nodes.length)
return;const crumbs=this.crumbsElement;for(let crumb=crumbs.firstChild;crumb;crumb=crumb.nextSibling){if(nodes.indexOf(crumb[this._nodeSymbol])!==-1){this.update(true);return;}}}
setSelectedNode(node){this._currentDOMNode=node;this.crumbsElement.window().requestAnimationFrame(()=>this.update());}
_mouseMovedInCrumbs(event){const nodeUnderMouse=event.target;const crumbElement=nodeUnderMouse.enclosingNodeOrSelfWithClass('crumb');const node=(crumbElement?crumbElement[this._nodeSymbol]:null);if(node)
node.highlight();}
_mouseMovedOutOfCrumbs(event){if(this._currentDOMNode)
SDK.OverlayModel.hideDOMNodeHighlight();}
_onClickCrumb(event){event.preventDefault();let crumb=(event.currentTarget);if(!crumb.classList.contains('collapsed')){this.dispatchEventToListeners(Elements.ElementsBreadcrumbs.Events.NodeSelected,crumb[this._nodeSymbol]);return;}
if(crumb===this.crumbsElement.firstChild){let currentCrumb=crumb;while(currentCrumb){const hidden=currentCrumb.classList.contains('hidden');const collapsed=currentCrumb.classList.contains('collapsed');if(!hidden&&!collapsed)
break;crumb=currentCrumb;currentCrumb=currentCrumb.nextSiblingElement;}}
this.updateSizes(crumb);}
_determineElementTitle(domNode){switch(domNode.nodeType()){case Node.ELEMENT_NODE:if(domNode.pseudoType())
return'::'+domNode.pseudoType();return null;case Node.TEXT_NODE:return Common.UIString('(text)');case Node.COMMENT_NODE:return'<!-->';case Node.DOCUMENT_TYPE_NODE:return'<!doctype>';case Node.DOCUMENT_FRAGMENT_NODE:return domNode.shadowRootType()?'#shadow-root':domNode.nodeNameInCorrectCase();default:return domNode.nodeNameInCorrectCase();}}
update(force){if(!this.isShowing())
return;const currentDOMNode=this._currentDOMNode;const crumbs=this.crumbsElement;let handled=false;let crumb=crumbs.firstChild;while(crumb){if(crumb[this._nodeSymbol]===currentDOMNode){crumb.classList.add('selected');handled=true;}else{crumb.classList.remove('selected');}
crumb=crumb.nextSibling;}
if(handled&&!force){this.updateSizes();return;}
crumbs.removeChildren();for(let current=currentDOMNode;current;current=current.parentNode){if(current.nodeType()===Node.DOCUMENT_NODE)
continue;crumb=createElementWithClass('span','crumb');crumb[this._nodeSymbol]=current;crumb.addEventListener('mousedown',this._onClickCrumb.bind(this),false);const crumbTitle=this._determineElementTitle(current);if(crumbTitle){const nameElement=createElement('span');nameElement.textContent=crumbTitle;crumb.appendChild(nameElement);crumb.title=crumbTitle;}else{Elements.DOMLinkifier.decorateNodeLabel(current,crumb);}
if(current===currentDOMNode)
crumb.classList.add('selected');crumbs.insertBefore(crumb,crumbs.firstChild);}
this.updateSizes();}
_resetCrumbStylesAndFindSelections(focusedCrumb){const crumbs=this.crumbsElement;let selectedIndex=0;let focusedIndex=0;let selectedCrumb=null;for(let i=0;i<crumbs.childNodes.length;++i){const crumb=crumbs.children[i];if(!selectedCrumb&&crumb.classList.contains('selected')){selectedCrumb=crumb;selectedIndex=i;}
if(crumb===focusedCrumb)
focusedIndex=i;crumb.classList.remove('compact','collapsed','hidden');}
return{selectedIndex:selectedIndex,focusedIndex:focusedIndex,selectedCrumb:selectedCrumb};}
_measureElementSizes(){const crumbs=this.crumbsElement;const collapsedElement=createElementWithClass('span','crumb collapsed');crumbs.insertBefore(collapsedElement,crumbs.firstChild);const available=crumbs.offsetWidth;const collapsed=collapsedElement.offsetWidth;const normalSizes=[];for(let i=1;i<crumbs.childNodes.length;++i){const crumb=crumbs.childNodes[i];normalSizes[i-1]=crumb.offsetWidth;}
crumbs.removeChild(collapsedElement);const compactSizes=[];for(let i=0;i<crumbs.childNodes.length;++i){const crumb=crumbs.childNodes[i];crumb.classList.add('compact');}
for(let i=0;i<crumbs.childNodes.length;++i){const crumb=crumbs.childNodes[i];compactSizes[i]=crumb.offsetWidth;}
for(let i=0;i<crumbs.childNodes.length;++i){const crumb=crumbs.childNodes[i];crumb.classList.remove('compact','collapsed');}
return{normal:normalSizes,compact:compactSizes,collapsed:collapsed,available:available};}
updateSizes(focusedCrumb){if(!this.isShowing())
return;const crumbs=this.crumbsElement;if(!crumbs.firstChild)
return;const selections=this._resetCrumbStylesAndFindSelections(focusedCrumb);const sizes=this._measureElementSizes();const selectedIndex=selections.selectedIndex;const focusedIndex=selections.focusedIndex;const selectedCrumb=selections.selectedCrumb;function crumbsAreSmallerThanContainer(){let totalSize=0;for(let i=0;i<crumbs.childNodes.length;++i){const crumb=crumbs.childNodes[i];if(crumb.classList.contains('hidden'))
continue;if(crumb.classList.contains('collapsed')){totalSize+=sizes.collapsed;continue;}
totalSize+=crumb.classList.contains('compact')?sizes.compact[i]:sizes.normal[i];}
const rightPadding=10;return totalSize+rightPadding<sizes.available;}
if(crumbsAreSmallerThanContainer())
return;const BothSides=0;const AncestorSide=-1;const ChildSide=1;function makeCrumbsSmaller(shrinkingFunction,direction){const significantCrumb=focusedCrumb||selectedCrumb;const significantIndex=significantCrumb===selectedCrumb?selectedIndex:focusedIndex;function shrinkCrumbAtIndex(index){const shrinkCrumb=crumbs.children[index];if(shrinkCrumb&&shrinkCrumb!==significantCrumb)
shrinkingFunction(shrinkCrumb);if(crumbsAreSmallerThanContainer())
return true;return false;}
if(direction){let index=(direction>0?0:crumbs.childNodes.length-1);while(index!==significantIndex){if(shrinkCrumbAtIndex(index))
return true;index+=(direction>0?1:-1);}}else{let startIndex=0;let endIndex=crumbs.childNodes.length-1;while(startIndex!==significantIndex||endIndex!==significantIndex){const startDistance=significantIndex-startIndex;const endDistance=endIndex-significantIndex;let index;if(startDistance>=endDistance)
index=startIndex++;else
index=endIndex--;if(shrinkCrumbAtIndex(index))
return true;}}
return false;}
function coalesceCollapsedCrumbs(){let crumb=crumbs.firstChild;let collapsedRun=false;let newStartNeeded=false;let newEndNeeded=false;while(crumb){const hidden=crumb.classList.contains('hidden');if(!hidden){const collapsed=crumb.classList.contains('collapsed');if(collapsedRun&&collapsed){crumb.classList.add('hidden');crumb.classList.remove('compact');crumb.classList.remove('collapsed');if(crumb.classList.contains('start')){crumb.classList.remove('start');newStartNeeded=true;}
if(crumb.classList.contains('end')){crumb.classList.remove('end');newEndNeeded=true;}
continue;}
collapsedRun=collapsed;if(newEndNeeded){newEndNeeded=false;crumb.classList.add('end');}}else{collapsedRun=true;}
crumb=crumb.nextSibling;}
if(newStartNeeded){crumb=crumbs.lastChild;while(crumb){if(!crumb.classList.contains('hidden')){crumb.classList.add('start');break;}
crumb=crumb.previousSibling;}}}
function compact(crumb){if(crumb.classList.contains('hidden'))
return;crumb.classList.add('compact');}
function collapse(crumb,dontCoalesce){if(crumb.classList.contains('hidden'))
return;crumb.classList.add('collapsed');crumb.classList.remove('compact');if(!dontCoalesce)
coalesceCollapsedCrumbs();}
if(!focusedCrumb){if(makeCrumbsSmaller(compact,ChildSide))
return;if(makeCrumbsSmaller(collapse,ChildSide))
return;}
if(makeCrumbsSmaller(compact,focusedCrumb?BothSides:AncestorSide))
return;if(makeCrumbsSmaller(collapse,focusedCrumb?BothSides:AncestorSide))
return;if(!selectedCrumb)
return;compact(selectedCrumb);if(crumbsAreSmallerThanContainer())
return;collapse(selectedCrumb,true);}};Elements.ElementsBreadcrumbs.Events={NodeSelected:Symbol('NodeSelected')};;Elements.ElementsSidebarPane=class extends UI.VBox{constructor(delegatesFocus){super(true,delegatesFocus);this.element.classList.add('flex-none');this._computedStyleModel=new Elements.ComputedStyleModel();this._computedStyleModel.addEventListener(Elements.ComputedStyleModel.Events.ComputedStyleChanged,this.onCSSModelChanged,this);this._updateThrottler=new Common.Throttler(100);this._updateWhenVisible=false;}
node(){return this._computedStyleModel.node();}
cssModel(){return this._computedStyleModel.cssModel();}
doUpdate(){return Promise.resolve();}
update(){this._updateWhenVisible=!this.isShowing();if(this._updateWhenVisible)
return;this._updateThrottler.schedule(innerUpdate.bind(this));function innerUpdate(){return this.isShowing()?this.doUpdate():Promise.resolve();}}
wasShown(){super.wasShown();if(this._updateWhenVisible)
this.update();}
onCSSModelChanged(event){}};;Elements.ElementsTreeElement=class extends UI.TreeElement{constructor(node,elementCloseTag){super();this._node=node;this._gutterContainer=this.listItemElement.createChild('div','gutter-container');this._gutterContainer.addEventListener('click',this._showContextMenu.bind(this));const gutterMenuIcon=UI.Icon.create('largeicon-menu','gutter-menu-icon');this._gutterContainer.appendChild(gutterMenuIcon);this._decorationsElement=this._gutterContainer.createChild('div','hidden');this._elementCloseTag=elementCloseTag;if(this._node.nodeType()===Node.ELEMENT_NODE&&!elementCloseTag)
this._canAddAttributes=true;this._searchQuery=null;this._expandedChildrenLimit=Elements.ElementsTreeElement.InitialChildrenLimit;this._decorationsThrottler=new Common.Throttler(100);}
static animateOnDOMUpdate(treeElement){const tagName=treeElement.listItemElement.querySelector('.webkit-html-tag-name');UI.runCSSAnimationOnce(tagName||treeElement.listItemElement,'dom-update-highlight');}
static visibleShadowRoots(node){let roots=node.shadowRoots();if(roots.length&&!Common.moduleSetting('showUAShadowDOM').get())
roots=roots.filter(filter);function filter(root){return root.shadowRootType()!==SDK.DOMNode.ShadowRootTypes.UserAgent;}
return roots;}
static canShowInlineText(node){if(node.contentDocument()||node.importedDocument()||node.templateContent()||Elements.ElementsTreeElement.visibleShadowRoots(node).length||node.hasPseudoElements())
return false;if(node.nodeType()!==Node.ELEMENT_NODE)
return false;if(!node.firstChild||node.firstChild!==node.lastChild||node.firstChild.nodeType()!==Node.TEXT_NODE)
return false;const textChild=node.firstChild;const maxInlineTextChildLength=80;if(textChild.nodeValue().length<maxInlineTextChildLength)
return true;return false;}
static populateForcedPseudoStateItems(contextMenu,node){const pseudoClasses=['active','hover','focus','visited','focus-within'];try{document.querySelector(':focus-visible');pseudoClasses.push('focus-visible');}catch(e){}
const forcedPseudoState=node.domModel().cssModel().pseudoState(node);const stateMenu=contextMenu.debugSection().appendSubMenuItem(Common.UIString('Force state'));for(let i=0;i<pseudoClasses.length;++i){const pseudoClassForced=forcedPseudoState.indexOf(pseudoClasses[i])>=0;stateMenu.defaultSection().appendCheckboxItem(':'+pseudoClasses[i],setPseudoStateCallback.bind(null,pseudoClasses[i],!pseudoClassForced),pseudoClassForced,false);}
function setPseudoStateCallback(pseudoState,enabled){node.domModel().cssModel().forcePseudoState(node,pseudoState,enabled);}}
isClosingTag(){return!!this._elementCloseTag;}
node(){return this._node;}
isEditing(){return!!this._editing;}
highlightSearchResults(searchQuery){if(this._searchQuery!==searchQuery)
this._hideSearchHighlight();this._searchQuery=searchQuery;this._searchHighlightsVisible=true;this.updateTitle(null,true);}
hideSearchHighlights(){delete this._searchHighlightsVisible;this._hideSearchHighlight();}
_hideSearchHighlight(){if(!this._highlightResult)
return;function updateEntryHide(entry){switch(entry.type){case'added':entry.node.remove();break;case'changed':entry.node.textContent=entry.oldText;break;}}
for(let i=(this._highlightResult.length-1);i>=0;--i)
updateEntryHide(this._highlightResult[i]);delete this._highlightResult;}
setInClipboard(inClipboard){if(this._inClipboard===inClipboard)
return;this._inClipboard=inClipboard;this.listItemElement.classList.toggle('in-clipboard',inClipboard);}
get hovered(){return this._hovered;}
set hovered(x){if(this._hovered===x)
return;this._hovered=x;if(this.listItemElement){if(x){this._createSelection();this.listItemElement.classList.add('hovered');}else{this.listItemElement.classList.remove('hovered');}}}
expandedChildrenLimit(){return this._expandedChildrenLimit;}
setExpandedChildrenLimit(expandedChildrenLimit){this._expandedChildrenLimit=expandedChildrenLimit;}
_createSelection(){const listItemElement=this.listItemElement;if(!listItemElement)
return;if(!this.selectionElement){this.selectionElement=createElement('div');this.selectionElement.className='selection fill';this.selectionElement.style.setProperty('margin-left',(-this._computeLeftIndent())+'px');listItemElement.insertBefore(this.selectionElement,listItemElement.firstChild);}}
_createHint(){if(this.listItemElement&&!this._hintElement){this._hintElement=this.listItemElement.createChild('span','selected-hint');const selectedElementCommand='$0';this._hintElement.title=ls`Use ${selectedElementCommand} in the console to refer to this element.`;UI.ARIAUtils.markAsHidden(this._hintElement);}}
onbind(){if(!this._elementCloseTag)
this._node[this.treeOutline.treeElementSymbol()]=this;}
onunbind(){if(this._node[this.treeOutline.treeElementSymbol()]===this)
this._node[this.treeOutline.treeElementSymbol()]=null;}
onattach(){if(this._hovered){this._createSelection();this.listItemElement.classList.add('hovered');}
this.updateTitle();this.listItemElement.draggable=true;}
onpopulate(){this.treeOutline.populateTreeElement(this);}
expandRecursively(){this._node.getSubtree(-1,true).then(UI.TreeElement.prototype.expandRecursively.bind(this,Number.MAX_VALUE));}
onexpand(){if(this._elementCloseTag)
return;this.updateTitle();}
oncollapse(){if(this._elementCloseTag)
return;this.updateTitle();}
select(omitFocus,selectedByUser){if(this._editing)
return false;return super.select(omitFocus,selectedByUser);}
onselect(selectedByUser){this.treeOutline.suppressRevealAndSelect=true;this.treeOutline.selectDOMNode(this._node,selectedByUser);if(selectedByUser){this._node.highlight();Host.userMetrics.actionTaken(Host.UserMetrics.Action.ChangeInspectedNodeInElementsPanel);}
this._createSelection();this._createHint();this.treeOutline.suppressRevealAndSelect=false;return true;}
ondelete(){const startTagTreeElement=this.treeOutline.findTreeElement(this._node);startTagTreeElement?startTagTreeElement.remove():this.remove();return true;}
onenter(){if(this._editing)
return false;this._startEditing();return true;}
selectOnMouseDown(event){super.selectOnMouseDown(event);if(this._editing)
return;if(event.detail>=2)
event.preventDefault();}
ondblclick(event){if(this._editing||this._elementCloseTag)
return false;if(this._startEditingTarget((event.target)))
return false;if(this.isExpandable()&&!this.expanded)
this.expand();return false;}
hasEditableNode(){return!this._node.isShadowRoot()&&!this._node.ancestorUserAgentShadowRoot();}
_insertInLastAttributePosition(tag,node){if(tag.getElementsByClassName('webkit-html-attribute').length>0){tag.insertBefore(node,tag.lastChild);}else{const nodeName=tag.textContent.match(/^<(.*?)>$/)[1];tag.textContent='';tag.createTextChild('<'+nodeName);tag.appendChild(node);tag.createTextChild('>');}}
_startEditingTarget(eventTarget){if(this.treeOutline.selectedDOMNode()!==this._node)
return false;if(this._node.nodeType()!==Node.ELEMENT_NODE&&this._node.nodeType()!==Node.TEXT_NODE)
return false;const textNode=eventTarget.enclosingNodeOrSelfWithClass('webkit-html-text-node');if(textNode)
return this._startEditingTextNode(textNode);const attribute=eventTarget.enclosingNodeOrSelfWithClass('webkit-html-attribute');if(attribute)
return this._startEditingAttribute(attribute,eventTarget);const tagName=eventTarget.enclosingNodeOrSelfWithClass('webkit-html-tag-name');if(tagName)
return this._startEditingTagName(tagName);const newAttribute=eventTarget.enclosingNodeOrSelfWithClass('add-attribute');if(newAttribute)
return this._addNewAttribute();return false;}
_showContextMenu(event){this.treeOutline.showContextMenu(this,event);}
populateTagContextMenu(contextMenu,event){const treeElement=this._elementCloseTag?this.treeOutline.findTreeElement(this._node):this;contextMenu.editSection().appendItem(Common.UIString('Add attribute'),treeElement._addNewAttribute.bind(treeElement));const attribute=event.target.enclosingNodeOrSelfWithClass('webkit-html-attribute');const newAttribute=event.target.enclosingNodeOrSelfWithClass('add-attribute');if(attribute&&!newAttribute){contextMenu.editSection().appendItem(Common.UIString('Edit attribute'),this._startEditingAttribute.bind(this,attribute,event.target));}
this.populateNodeContextMenu(contextMenu);Elements.ElementsTreeElement.populateForcedPseudoStateItems(contextMenu,treeElement.node());this.populateScrollIntoView(contextMenu);contextMenu.viewSection().appendItem(Common.UIString('Focus'),async()=>{await this._node.focus();});}
populateScrollIntoView(contextMenu){contextMenu.viewSection().appendItem(Common.UIString('Scroll into view'),()=>this._node.scrollIntoView());}
populateTextContextMenu(contextMenu,textNode){if(!this._editing){contextMenu.editSection().appendItem(Common.UIString('Edit text'),this._startEditingTextNode.bind(this,textNode));}
this.populateNodeContextMenu(contextMenu);}
populateNodeContextMenu(contextMenu){const isEditable=this.hasEditableNode();if(isEditable&&!this._editing)
contextMenu.editSection().appendItem(Common.UIString('Edit as HTML'),this._editAsHTML.bind(this));const isShadowRoot=this._node.isShadowRoot();const copyMenu=contextMenu.clipboardSection().appendSubMenuItem(Common.UIString('Copy'));const createShortcut=UI.KeyboardShortcut.shortcutToString;const modifier=UI.KeyboardShortcut.Modifiers.CtrlOrMeta;const treeOutline=this.treeOutline;let menuItem;let section;if(!isShadowRoot){section=copyMenu.section();menuItem=section.appendItem(Common.UIString('Copy outerHTML'),treeOutline.performCopyOrCut.bind(treeOutline,false,this._node));menuItem.setShortcut(createShortcut('V',modifier));}
if(this._node.nodeType()===Node.ELEMENT_NODE){section.appendItem(Common.UIString('Copy selector'),this._copyCSSPath.bind(this));section.appendItem(Common.UIString('Copy JS path'),this._copyJSPath.bind(this),!Elements.DOMPath.canGetJSPath(this._node));}
if(!isShadowRoot)
section.appendItem(Common.UIString('Copy XPath'),this._copyXPath.bind(this));if(!isShadowRoot){menuItem=copyMenu.clipboardSection().appendItem(Common.UIString('Cut element'),treeOutline.performCopyOrCut.bind(treeOutline,true,this._node),!this.hasEditableNode());menuItem.setShortcut(createShortcut('X',modifier));menuItem=copyMenu.clipboardSection().appendItem(Common.UIString('Copy element'),treeOutline.performCopyOrCut.bind(treeOutline,false,this._node));menuItem.setShortcut(createShortcut('C',modifier));menuItem=copyMenu.clipboardSection().appendItem(Common.UIString('Paste element'),treeOutline.pasteNode.bind(treeOutline,this._node),!treeOutline.canPaste(this._node));menuItem.setShortcut(createShortcut('V',modifier));}
menuItem=contextMenu.debugSection().appendCheckboxItem(Common.UIString('Hide element'),treeOutline.toggleHideElement.bind(treeOutline,this._node),treeOutline.isToggledToHidden(this._node));menuItem.setShortcut(UI.shortcutRegistry.shortcutTitleForAction('elements.hide-element'));if(isEditable)
contextMenu.editSection().appendItem(Common.UIString('Delete element'),this.remove.bind(this));contextMenu.viewSection().appendItem(ls`Expand recursively`,this.expandRecursively.bind(this));contextMenu.viewSection().appendItem(ls`Collapse children`,this.collapseChildren.bind(this));}
_startEditing(){if(this.treeOutline.selectedDOMNode()!==this._node)
return;const listItem=this.listItemElement;if(this._canAddAttributes){const attribute=listItem.getElementsByClassName('webkit-html-attribute')[0];if(attribute){return this._startEditingAttribute(attribute,attribute.getElementsByClassName('webkit-html-attribute-value')[0]);}
return this._addNewAttribute();}
if(this._node.nodeType()===Node.TEXT_NODE){const textNode=listItem.getElementsByClassName('webkit-html-text-node')[0];if(textNode)
return this._startEditingTextNode(textNode);return;}}
_addNewAttribute(){const container=createElement('span');this._buildAttributeDOM(container,' ','',null);const attr=container.firstElementChild;attr.style.marginLeft='2px';attr.style.marginRight='2px';const tag=this.listItemElement.getElementsByClassName('webkit-html-tag')[0];this._insertInLastAttributePosition(tag,attr);attr.scrollIntoViewIfNeeded(true);return this._startEditingAttribute(attr,attr);}
_triggerEditAttribute(attributeName){const attributeElements=this.listItemElement.getElementsByClassName('webkit-html-attribute-name');for(let i=0,len=attributeElements.length;i<len;++i){if(attributeElements[i].textContent===attributeName){for(let elem=attributeElements[i].nextSibling;elem;elem=elem.nextSibling){if(elem.nodeType!==Node.ELEMENT_NODE)
continue;if(elem.classList.contains('webkit-html-attribute-value'))
return this._startEditingAttribute(elem.parentNode,elem);}}}}
_startEditingAttribute(attribute,elementForSelection){console.assert(this.listItemElement.isAncestor(attribute));if(UI.isBeingEdited(attribute))
return true;const attributeNameElement=attribute.getElementsByClassName('webkit-html-attribute-name')[0];if(!attributeNameElement)
return false;const attributeName=attributeNameElement.textContent;const attributeValueElement=attribute.getElementsByClassName('webkit-html-attribute-value')[0];elementForSelection=attributeValueElement.isAncestor(elementForSelection)?attributeValueElement:elementForSelection;function removeZeroWidthSpaceRecursive(node){if(node.nodeType===Node.TEXT_NODE){node.nodeValue=node.nodeValue.replace(/\u200B/g,'');return;}
if(node.nodeType!==Node.ELEMENT_NODE)
return;for(let child=node.firstChild;child;child=child.nextSibling)
removeZeroWidthSpaceRecursive(child);}
const attributeValue=attributeName&&attributeValueElement?this._node.getAttribute(attributeName):undefined;if(attributeValue!==undefined){attributeValueElement.setTextContentTruncatedIfNeeded(attributeValue,Common.UIString('<value is too large to edit>'));}
removeZeroWidthSpaceRecursive(attribute);const config=new UI.InplaceEditor.Config(this._attributeEditingCommitted.bind(this),this._editingCancelled.bind(this),attributeName);function postKeyDownFinishHandler(event){UI.handleElementValueModifications(event,attribute);return'';}
if(!attributeValueElement.textContent.asParsedURL())
config.setPostKeydownFinishHandler(postKeyDownFinishHandler);this._editing=UI.InplaceEditor.startEditing(attribute,config);this.listItemElement.getComponentSelection().selectAllChildren(elementForSelection);return true;}
_startEditingTextNode(textNodeElement){if(UI.isBeingEdited(textNodeElement))
return true;let textNode=this._node;if(textNode.nodeType()===Node.ELEMENT_NODE&&textNode.firstChild)
textNode=textNode.firstChild;const container=textNodeElement.enclosingNodeOrSelfWithClass('webkit-html-text-node');if(container)
container.textContent=textNode.nodeValue();const config=new UI.InplaceEditor.Config(this._textNodeEditingCommitted.bind(this,textNode),this._editingCancelled.bind(this));this._editing=UI.InplaceEditor.startEditing(textNodeElement,config);this.listItemElement.getComponentSelection().selectAllChildren(textNodeElement);return true;}
_startEditingTagName(tagNameElement){if(!tagNameElement){tagNameElement=this.listItemElement.getElementsByClassName('webkit-html-tag-name')[0];if(!tagNameElement)
return false;}
const tagName=tagNameElement.textContent;if(Elements.ElementsTreeElement.EditTagBlacklist.has(tagName.toLowerCase()))
return false;if(UI.isBeingEdited(tagNameElement))
return true;const closingTagElement=this._distinctClosingTagElement();function keyupListener(event){if(closingTagElement)
closingTagElement.textContent='</'+tagNameElement.textContent+'>';}
const keydownListener=event=>{if(event.key!==' ')
return;this._editing.commit();event.consume(true);};function editingComitted(element,newTagName){tagNameElement.removeEventListener('keyup',keyupListener,false);tagNameElement.removeEventListener('keydown',keydownListener,false);this._tagNameEditingCommitted.apply(this,arguments);}
function editingCancelled(){tagNameElement.removeEventListener('keyup',keyupListener,false);tagNameElement.removeEventListener('keydown',keydownListener,false);this._editingCancelled.apply(this,arguments);}
tagNameElement.addEventListener('keyup',keyupListener,false);tagNameElement.addEventListener('keydown',keydownListener,false);const config=new UI.InplaceEditor.Config(editingComitted.bind(this),editingCancelled.bind(this),tagName);this._editing=UI.InplaceEditor.startEditing(tagNameElement,config);this.listItemElement.getComponentSelection().selectAllChildren(tagNameElement);return true;}
_startEditingAsHTML(commitCallback,disposeCallback,maybeInitialValue){if(maybeInitialValue===null)
return;let initialValue=maybeInitialValue;if(this._editing)
return;initialValue=this._convertWhitespaceToEntities(initialValue).text;this._htmlEditElement=createElement('div');this._htmlEditElement.className='source-code elements-tree-editor';let child=this.listItemElement.firstChild;while(child){child.style.display='none';child=child.nextSibling;}
if(this.childrenListElement)
this.childrenListElement.style.display='none';this.listItemElement.appendChild(this._htmlEditElement);self.runtime.extension(UI.TextEditorFactory).instance().then(gotFactory.bind(this));function gotFactory(factory){const editor=factory.createEditor({lineNumbers:false,lineWrapping:Common.moduleSetting('domWordWrap').get(),mimeType:'text/html',autoHeight:false,padBottom:false});this._editing={commit:commit.bind(this),cancel:dispose.bind(this),editor:editor,resize:resize.bind(this)};resize.call(this);editor.widget().show(this._htmlEditElement);editor.setText(initialValue);editor.widget().focus();editor.widget().element.addEventListener('focusout',event=>{if(event.relatedTarget&&!event.relatedTarget.isSelfOrDescendant(editor.widget().element))
this._editing.commit();},false);editor.widget().element.addEventListener('keydown',keydown.bind(this),true);this.treeOutline.setMultilineEditing(this._editing);}
function resize(){this._htmlEditElement.style.width=this.treeOutline.visibleWidth()-this._computeLeftIndent()-30+'px';this._editing.editor.onResize();}
function commit(){commitCallback(initialValue,this._editing.editor.text());dispose.call(this);}
function dispose(){this._editing.editor.widget().element.removeEventListener('blur',this._editing.commit,true);this._editing.editor.widget().detach();delete this._editing;this.listItemElement.removeChild(this._htmlEditElement);delete this._htmlEditElement;if(this.childrenListElement)
this.childrenListElement.style.removeProperty('display');let child=this.listItemElement.firstChild;while(child){child.style.removeProperty('display');child=child.nextSibling;}
if(this.treeOutline){this.treeOutline.setMultilineEditing(null);this.treeOutline.focus();}
disposeCallback();}
function keydown(event){const isMetaOrCtrl=UI.KeyboardShortcut.eventHasCtrlOrMeta((event))&&!event.altKey&&!event.shiftKey;if(isEnterKey(event)&&(isMetaOrCtrl||event.isMetaOrCtrlForTest)){event.consume(true);this._editing.commit();}else if(event.keyCode===UI.KeyboardShortcut.Keys.Esc.code||event.key==='Escape'){event.consume(true);this._editing.cancel();}}}
_attributeEditingCommitted(element,newText,oldText,attributeName,moveDirection){delete this._editing;const treeOutline=this.treeOutline;function moveToNextAttributeIfNeeded(error){if(error)
this._editingCancelled(element,attributeName);if(!moveDirection)
return;treeOutline.runPendingUpdates();treeOutline.focus();const attributes=this._node.attributes();for(let i=0;i<attributes.length;++i){if(attributes[i].name!==attributeName)
continue;if(moveDirection==='backward'){if(i===0)
this._startEditingTagName();else
this._triggerEditAttribute(attributes[i-1].name);}else{if(i===attributes.length-1)
this._addNewAttribute();else
this._triggerEditAttribute(attributes[i+1].name);}
return;}
if(moveDirection==='backward'){if(newText===' '){if(attributes.length>0)
this._triggerEditAttribute(attributes[attributes.length-1].name);}else{if(attributes.length>1)
this._triggerEditAttribute(attributes[attributes.length-2].name);}}else if(moveDirection==='forward'){if(!newText.isWhitespace())
this._addNewAttribute();else
this._startEditingTagName();}}
if((attributeName.trim()||newText.trim())&&oldText!==newText){this._node.setAttribute(attributeName,newText,moveToNextAttributeIfNeeded.bind(this));return;}
this.updateTitle();moveToNextAttributeIfNeeded.call(this);}
_tagNameEditingCommitted(element,newText,oldText,tagName,moveDirection){delete this._editing;const self=this;function cancel(){const closingTagElement=self._distinctClosingTagElement();if(closingTagElement)
closingTagElement.textContent='</'+tagName+'>';self._editingCancelled(element,tagName);moveToNextAttributeIfNeeded.call(self);}
function moveToNextAttributeIfNeeded(){if(moveDirection!=='forward'){this._addNewAttribute();return;}
const attributes=this._node.attributes();if(attributes.length>0)
this._triggerEditAttribute(attributes[0].name);else
this._addNewAttribute();}
newText=newText.trim();if(newText===oldText){cancel();return;}
const treeOutline=this.treeOutline;const wasExpanded=this.expanded;this._node.setNodeName(newText,(error,newNode)=>{if(error||!newNode){cancel();return;}
const newTreeItem=treeOutline.selectNodeAfterEdit(wasExpanded,error,newNode);moveToNextAttributeIfNeeded.call(newTreeItem);});}
_textNodeEditingCommitted(textNode,element,newText){delete this._editing;function callback(){this.updateTitle();}
textNode.setNodeValue(newText,callback.bind(this));}
_editingCancelled(element,context){delete this._editing;this.updateTitle();}
_distinctClosingTagElement(){if(this.expanded){const closers=this.childrenListElement.querySelectorAll('.close');return closers[closers.length-1];}
const tags=this.listItemElement.getElementsByClassName('webkit-html-tag');return(tags.length===1?null:tags[tags.length-1]);}
updateTitle(updateRecord,onlySearchQueryChanged){if(this._editing)
return;if(onlySearchQueryChanged){this._hideSearchHighlight();}else{const nodeInfo=this._nodeTitleInfo(updateRecord||null);if(this._node.nodeType()===Node.DOCUMENT_FRAGMENT_NODE&&this._node.isInShadowTree()&&this._node.shadowRootType()){this.childrenListElement.classList.add('shadow-root');let depth=4;for(let node=this._node;depth&&node;node=node.parentNode){if(node.nodeType()===Node.DOCUMENT_FRAGMENT_NODE)
depth--;}
if(!depth)
this.childrenListElement.classList.add('shadow-root-deep');else
this.childrenListElement.classList.add('shadow-root-depth-'+depth);}
const highlightElement=createElement('span');highlightElement.className='highlight';highlightElement.appendChild(nodeInfo);this.title=highlightElement;this.updateDecorations();this.listItemElement.insertBefore(this._gutterContainer,this.listItemElement.firstChild);delete this._highlightResult;delete this.selectionElement;delete this._hintElement;if(this.selected){this._createSelection();this._createHint();}}
this._highlightSearchResults();}
_computeLeftIndent(){let treeElement=this.parent;let depth=0;while(treeElement!==null){depth++;treeElement=treeElement.parent;}
return 12*(depth-2)+(this.isExpandable()?1:12);}
updateDecorations(){this._gutterContainer.style.left=(-this._computeLeftIndent())+'px';if(this.isClosingTag())
return;if(this._node.nodeType()!==Node.ELEMENT_NODE)
return;this._decorationsThrottler.schedule(this._updateDecorationsInternal.bind(this));}
_updateDecorationsInternal(){if(!this.treeOutline)
return Promise.resolve();const node=this._node;if(!this.treeOutline._decoratorExtensions)
this.treeOutline._decoratorExtensions=self.runtime.extensions(Elements.MarkerDecorator);const markerToExtension=new Map();for(let i=0;i<this.treeOutline._decoratorExtensions.length;++i){markerToExtension.set(this.treeOutline._decoratorExtensions[i].descriptor()['marker'],this.treeOutline._decoratorExtensions[i]);}
const promises=[];const decorations=[];const descendantDecorations=[];node.traverseMarkers(visitor);function visitor(n,marker){const extension=markerToExtension.get(marker);if(!extension)
return;promises.push(extension.instance().then(collectDecoration.bind(null,n)));}
function collectDecoration(n,decorator){const decoration=decorator.decorate(n);if(!decoration)
return;(n===node?decorations:descendantDecorations).push(decoration);}
return Promise.all(promises).then(updateDecorationsUI.bind(this));function updateDecorationsUI(){this._decorationsElement.removeChildren();this._decorationsElement.classList.add('hidden');this._gutterContainer.classList.toggle('has-decorations',decorations.length||descendantDecorations.length);if(!decorations.length&&!descendantDecorations.length)
return;const colors=new Set();const titles=createElement('div');for(const decoration of decorations){const titleElement=titles.createChild('div');titleElement.textContent=decoration.title;colors.add(decoration.color);}
if(this.expanded&&!decorations.length)
return;const descendantColors=new Set();if(descendantDecorations.length){let element=titles.createChild('div');element.textContent=Common.UIString('Children:');for(const decoration of descendantDecorations){element=titles.createChild('div');element.style.marginLeft='15px';element.textContent=decoration.title;descendantColors.add(decoration.color);}}
let offset=0;processColors.call(this,colors,'elements-gutter-decoration');if(!this.expanded)
processColors.call(this,descendantColors,'elements-gutter-decoration elements-has-decorated-children');UI.Tooltip.install(this._decorationsElement,titles);function processColors(colors,className){for(const color of colors){const child=this._decorationsElement.createChild('div',className);this._decorationsElement.classList.remove('hidden');child.style.backgroundColor=color;child.style.borderColor=color;if(offset)
child.style.marginLeft=offset+'px';offset+=3;}}}}
_buildAttributeDOM(parentElement,name,value,updateRecord,forceValue,node){const closingPunctuationRegex=/[\/;:\)\]\}]/g;let highlightIndex=0;let highlightCount;let additionalHighlightOffset=0;let result;function replacer(match,replaceOffset){while(highlightIndex<highlightCount&&result.entityRanges[highlightIndex].offset<replaceOffset){result.entityRanges[highlightIndex].offset+=additionalHighlightOffset;++highlightIndex;}
additionalHighlightOffset+=1;return match+'\u200B';}
function setValueWithEntities(element,value){result=this._convertWhitespaceToEntities(value);highlightCount=result.entityRanges.length;value=result.text.replace(closingPunctuationRegex,replacer);while(highlightIndex<highlightCount){result.entityRanges[highlightIndex].offset+=additionalHighlightOffset;++highlightIndex;}
element.setTextContentTruncatedIfNeeded(value);UI.highlightRangesWithStyleClass(element,result.entityRanges,'webkit-html-entity-value');}
const hasText=(forceValue||value.length>0);const attrSpanElement=parentElement.createChild('span','webkit-html-attribute');const attrNameElement=attrSpanElement.createChild('span','webkit-html-attribute-name');attrNameElement.textContent=name;if(hasText)
attrSpanElement.createTextChild('=\u200B"');const attrValueElement=attrSpanElement.createChild('span','webkit-html-attribute-value');if(updateRecord&&updateRecord.isAttributeModified(name))
UI.runCSSAnimationOnce(hasText?attrValueElement:attrNameElement,'dom-update-highlight');function linkifyValue(value){const rewrittenHref=node.resolveURL(value);if(rewrittenHref===null){const span=createElement('span');setValueWithEntities.call(this,span,value);return span;}
value=value.replace(closingPunctuationRegex,'$&\u200B');if(value.startsWith('data:'))
value=value.trimMiddle(60);const link=node.nodeName().toLowerCase()==='a'?UI.XLink.create(rewrittenHref,value,'',true):Components.Linkifier.linkifyURL(rewrittenHref,{text:value,preventClick:true});link[Elements.ElementsTreeElement.HrefSymbol]=rewrittenHref;return link;}
const nodeName=node?node.nodeName().toLowerCase():'';if(nodeName&&(name==='src'||name==='href'))
attrValueElement.appendChild(linkifyValue.call(this,value));else if((nodeName==='img'||nodeName==='source')&&name==='srcset')
attrValueElement.appendChild(linkifySrcset.call(this,value));else
setValueWithEntities.call(this,attrValueElement,value);if(hasText)
attrSpanElement.createTextChild('"');function linkifySrcset(value){const fragment=createDocumentFragment();let i=0;while(value.length){if(i++>0)
fragment.createTextChild(' ');value=value.trim();let url='';let descriptor='';const indexOfSpace=value.search(/\s/);if(indexOfSpace===-1){url=value;}else if(indexOfSpace>0&&value[indexOfSpace-1]===','){url=value.substring(0,indexOfSpace);}else{url=value.substring(0,indexOfSpace);const indexOfComma=value.indexOf(',',indexOfSpace);if(indexOfComma!==-1)
descriptor=value.substring(indexOfSpace,indexOfComma+1);else
descriptor=value.substring(indexOfSpace);}
if(url){if(url.endsWith(',')){fragment.appendChild(linkifyValue.call(this,url.substring(0,url.length-1)));fragment.createTextChild(',');}else{fragment.appendChild(linkifyValue.call(this,url));}}
if(descriptor)
fragment.createTextChild(descriptor);value=value.substring(url.length+descriptor.length);}
return fragment;}}
_buildPseudoElementDOM(parentElement,pseudoElementName){const pseudoElement=parentElement.createChild('span','webkit-html-pseudo-element');pseudoElement.textContent='::'+pseudoElementName;parentElement.createTextChild('\u200B');}
_buildTagDOM(parentElement,tagName,isClosingTag,isDistinctTreeElement,updateRecord){const node=this._node;const classes=['webkit-html-tag'];if(isClosingTag&&isDistinctTreeElement)
classes.push('close');const tagElement=parentElement.createChild('span',classes.join(' '));tagElement.createTextChild('<');const tagNameElement=tagElement.createChild('span',isClosingTag?'webkit-html-close-tag-name':'webkit-html-tag-name');tagNameElement.textContent=(isClosingTag?'/':'')+tagName;if(!isClosingTag){if(node.hasAttributes()){const attributes=node.attributes();for(let i=0;i<attributes.length;++i){const attr=attributes[i];tagElement.createTextChild(' ');this._buildAttributeDOM(tagElement,attr.name,attr.value,updateRecord,false,node);}}
if(updateRecord){let hasUpdates=updateRecord.hasRemovedAttributes()||updateRecord.hasRemovedChildren();hasUpdates|=!this.expanded&&updateRecord.hasChangedChildren();if(hasUpdates)
UI.runCSSAnimationOnce(tagNameElement,'dom-update-highlight');}}
tagElement.createTextChild('>');parentElement.createTextChild('\u200B');}
_convertWhitespaceToEntities(text){let result='';let lastIndexAfterEntity=0;const entityRanges=[];const charToEntity=Elements.ElementsTreeOutline.MappedCharToEntity;for(let i=0,size=text.length;i<size;++i){const char=text.charAt(i);if(charToEntity[char]){result+=text.substring(lastIndexAfterEntity,i);const entityValue='&'+charToEntity[char]+';';entityRanges.push({offset:result.length,length:entityValue.length});result+=entityValue;lastIndexAfterEntity=i+1;}}
if(result)
result+=text.substring(lastIndexAfterEntity);return{text:result||text,entityRanges:entityRanges};}
_nodeTitleInfo(updateRecord){const node=this._node;const titleDOM=createDocumentFragment();switch(node.nodeType()){case Node.ATTRIBUTE_NODE:this._buildAttributeDOM(titleDOM,(node.name),(node.value),updateRecord,true);break;case Node.ELEMENT_NODE:const pseudoType=node.pseudoType();if(pseudoType){this._buildPseudoElementDOM(titleDOM,pseudoType);break;}
const tagName=node.nodeNameInCorrectCase();if(this._elementCloseTag){this._buildTagDOM(titleDOM,tagName,true,true,updateRecord);break;}
this._buildTagDOM(titleDOM,tagName,false,false,updateRecord);if(this.isExpandable()){if(!this.expanded){const textNodeElement=titleDOM.createChild('span','webkit-html-text-node bogus');textNodeElement.textContent='\u2026';titleDOM.createTextChild('\u200B');this._buildTagDOM(titleDOM,tagName,true,false,updateRecord);}
break;}
if(Elements.ElementsTreeElement.canShowInlineText(node)){const textNodeElement=titleDOM.createChild('span','webkit-html-text-node');const result=this._convertWhitespaceToEntities(node.firstChild.nodeValue());textNodeElement.textContent=result.text;UI.highlightRangesWithStyleClass(textNodeElement,result.entityRanges,'webkit-html-entity-value');titleDOM.createTextChild('\u200B');this._buildTagDOM(titleDOM,tagName,true,false,updateRecord);if(updateRecord&&updateRecord.hasChangedChildren())
UI.runCSSAnimationOnce(textNodeElement,'dom-update-highlight');if(updateRecord&&updateRecord.isCharDataModified())
UI.runCSSAnimationOnce(textNodeElement,'dom-update-highlight');break;}
if(this.treeOutline.isXMLMimeType||!Elements.ElementsTreeElement.ForbiddenClosingTagElements.has(tagName))
this._buildTagDOM(titleDOM,tagName,true,false,updateRecord);break;case Node.TEXT_NODE:if(node.parentNode&&node.parentNode.nodeName().toLowerCase()==='script'){const newNode=titleDOM.createChild('span','webkit-html-text-node webkit-html-js-node');const text=node.nodeValue();newNode.textContent=text.startsWith('\n')?text.substring(1):text;const javascriptSyntaxHighlighter=new UI.SyntaxHighlighter('text/javascript',true);javascriptSyntaxHighlighter.syntaxHighlightNode(newNode).then(updateSearchHighlight.bind(this));}else if(node.parentNode&&node.parentNode.nodeName().toLowerCase()==='style'){const newNode=titleDOM.createChild('span','webkit-html-text-node webkit-html-css-node');const text=node.nodeValue();newNode.textContent=text.startsWith('\n')?text.substring(1):text;const cssSyntaxHighlighter=new UI.SyntaxHighlighter('text/css',true);cssSyntaxHighlighter.syntaxHighlightNode(newNode).then(updateSearchHighlight.bind(this));}else{titleDOM.createTextChild('"');const textNodeElement=titleDOM.createChild('span','webkit-html-text-node');const result=this._convertWhitespaceToEntities(node.nodeValue());textNodeElement.textContent=result.text;UI.highlightRangesWithStyleClass(textNodeElement,result.entityRanges,'webkit-html-entity-value');titleDOM.createTextChild('"');if(updateRecord&&updateRecord.isCharDataModified())
UI.runCSSAnimationOnce(textNodeElement,'dom-update-highlight');}
break;case Node.COMMENT_NODE:const commentElement=titleDOM.createChild('span','webkit-html-comment');commentElement.createTextChild('<!--'+node.nodeValue()+'-->');break;case Node.DOCUMENT_TYPE_NODE:const docTypeElement=titleDOM.createChild('span','webkit-html-doctype');docTypeElement.createTextChild('<!doctype '+node.nodeName());if(node.publicId){docTypeElement.createTextChild(' PUBLIC "'+node.publicId+'"');if(node.systemId)
docTypeElement.createTextChild(' "'+node.systemId+'"');}else if(node.systemId){docTypeElement.createTextChild(' SYSTEM "'+node.systemId+'"');}
if(node.internalSubset)
docTypeElement.createTextChild(' ['+node.internalSubset+']');docTypeElement.createTextChild('>');break;case Node.CDATA_SECTION_NODE:const cdataElement=titleDOM.createChild('span','webkit-html-text-node');cdataElement.createTextChild('<![CDATA['+node.nodeValue()+']]>');break;case Node.DOCUMENT_FRAGMENT_NODE:const fragmentElement=titleDOM.createChild('span','webkit-html-fragment');fragmentElement.textContent=node.nodeNameInCorrectCase().collapseWhitespace();break;default:titleDOM.createTextChild(node.nodeNameInCorrectCase().collapseWhitespace());}
function updateSearchHighlight(){delete this._highlightResult;this._highlightSearchResults();}
return titleDOM;}
remove(){if(this._node.pseudoType())
return;const parentElement=this.parent;if(!parentElement)
return;if(!this._node.parentNode||this._node.parentNode.nodeType()===Node.DOCUMENT_NODE)
return;this._node.removeNode();}
toggleEditAsHTML(callback,startEditing){if(this._editing&&this._htmlEditElement){this._editing.commit();return;}
if(startEditing===false)
return;function selectNode(error){if(callback)
callback(!error);}
function commitChange(initialValue,value){if(initialValue!==value)
node.setOuterHTML(value,selectNode);}
function disposeCallback(){if(callback)
callback(false);}
const node=this._node;node.getOuterHTML().then(this._startEditingAsHTML.bind(this,commitChange,disposeCallback));}
_copyCSSPath(){InspectorFrontendHost.copyText(Elements.DOMPath.cssPath(this._node,true));}
_copyJSPath(){InspectorFrontendHost.copyText(Elements.DOMPath.jsPath(this._node,true));}
_copyXPath(){InspectorFrontendHost.copyText(Elements.DOMPath.xPath(this._node,true));}
_highlightSearchResults(){if(!this._searchQuery||!this._searchHighlightsVisible)
return;this._hideSearchHighlight();const text=this.listItemElement.textContent;const regexObject=createPlainTextSearchRegex(this._searchQuery,'gi');let match=regexObject.exec(text);const matchRanges=[];while(match){matchRanges.push(new TextUtils.SourceRange(match.index,match[0].length));match=regexObject.exec(text);}
if(!matchRanges.length)
matchRanges.push(new TextUtils.SourceRange(0,text.length));this._highlightResult=[];UI.highlightSearchResults(this.listItemElement,matchRanges,this._highlightResult);}
_editAsHTML(){const promise=Common.Revealer.reveal(this.node());promise.then(()=>UI.actionRegistry.action('elements.edit-as-html').execute());}};Elements.ElementsTreeElement.HrefSymbol=Symbol('ElementsTreeElement.Href');Elements.ElementsTreeElement.InitialChildrenLimit=500;Elements.ElementsTreeElement.ForbiddenClosingTagElements=new Set(['area','base','basefont','br','canvas','col','command','embed','frame','hr','img','input','keygen','link','menuitem','meta','param','source','track','wbr']);Elements.ElementsTreeElement.EditTagBlacklist=new Set(['html','head','body']);Elements.MultilineEditorController;;Elements.ElementsTreeOutline=class extends UI.TreeOutline{constructor(omitRootDOMNode,selectEnabled,hideGutter){super();this._treeElementSymbol=Symbol('treeElement');const shadowContainer=createElement('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(shadowContainer,'elements/elementsTreeOutline.css');const outlineDisclosureElement=this._shadowRoot.createChild('div','elements-disclosure');this._element=this.element;this._element.classList.add('elements-tree-outline','source-code');if(hideGutter)
this._element.classList.add('elements-hide-gutter');UI.ARIAUtils.setAccessibleName(this._element,Common.UIString('Page DOM'));this._element.addEventListener('focusout',this._onfocusout.bind(this),false);this._element.addEventListener('mousedown',this._onmousedown.bind(this),false);this._element.addEventListener('mousemove',this._onmousemove.bind(this),false);this._element.addEventListener('mouseleave',this._onmouseleave.bind(this),false);this._element.addEventListener('dragstart',this._ondragstart.bind(this),false);this._element.addEventListener('dragover',this._ondragover.bind(this),false);this._element.addEventListener('dragleave',this._ondragleave.bind(this),false);this._element.addEventListener('drop',this._ondrop.bind(this),false);this._element.addEventListener('dragend',this._ondragend.bind(this),false);this._element.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),false);this._element.addEventListener('clipboard-beforecopy',this._onBeforeCopy.bind(this),false);this._element.addEventListener('clipboard-copy',this._onCopyOrCut.bind(this,false),false);this._element.addEventListener('clipboard-cut',this._onCopyOrCut.bind(this,true),false);this._element.addEventListener('clipboard-paste',this._onPaste.bind(this),false);this._element.addEventListener('keydown',this._onKeyDown.bind(this),false);outlineDisclosureElement.appendChild(this._element);this.element=shadowContainer;this._includeRootDOMNode=!omitRootDOMNode;this._selectEnabled=selectEnabled;this._rootDOMNode=null;this._selectedDOMNode=null;this._visible=false;this._popoverHelper=new UI.PopoverHelper(this._element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(0,100);this._updateRecords=new Map();this._treeElementsBeingUpdated=new Set();this._showHTMLCommentsSetting=Common.moduleSetting('showHTMLComments');this._showHTMLCommentsSetting.addChangeListener(this._onShowHTMLCommentsChange.bind(this));this.useLightSelectionColor();}
static forDOMModel(domModel){return domModel[Elements.ElementsTreeOutline._treeOutlineSymbol]||null;}
_onShowHTMLCommentsChange(){const selectedNode=this.selectedDOMNode();if(selectedNode&&selectedNode.nodeType()===Node.COMMENT_NODE&&!this._showHTMLCommentsSetting.get())
this.selectDOMNode(selectedNode.parentNode);this.update();}
treeElementSymbol(){return this._treeElementSymbol;}
setWordWrap(wrap){this._element.classList.toggle('elements-tree-nowrap',!wrap);}
setMultilineEditing(multilineEditing){this._multilineEditing=multilineEditing;}
visibleWidth(){return this._visibleWidth;}
setVisibleWidth(width){this._visibleWidth=width;if(this._multilineEditing)
this._multilineEditing.resize();}
_setClipboardData(data){if(this._clipboardNodeData){const treeElement=this.findTreeElement(this._clipboardNodeData.node);if(treeElement)
treeElement.setInClipboard(false);delete this._clipboardNodeData;}
if(data){const treeElement=this.findTreeElement(data.node);if(treeElement)
treeElement.setInClipboard(true);this._clipboardNodeData=data;}}
resetClipboardIfNeeded(removedNode){if(this._clipboardNodeData&&this._clipboardNodeData.node===removedNode)
this._setClipboardData(null);}
_onBeforeCopy(event){event.handled=true;}
_onCopyOrCut(isCut,event){this._setClipboardData(null);const originalEvent=event['original'];if(originalEvent.target.hasSelection())
return;if(UI.isEditing())
return;const targetNode=this.selectedDOMNode();if(!targetNode)
return;originalEvent.clipboardData.clearData();event.handled=true;this.performCopyOrCut(isCut,targetNode);}
performCopyOrCut(isCut,node){if(isCut&&(node.isShadowRoot()||node.ancestorUserAgentShadowRoot()))
return;node.copyNode();this._setClipboardData({node:node,isCut:isCut});}
canPaste(targetNode){if(targetNode.isShadowRoot()||targetNode.ancestorUserAgentShadowRoot())
return false;if(!this._clipboardNodeData)
return false;const node=this._clipboardNodeData.node;if(this._clipboardNodeData.isCut&&(node===targetNode||node.isAncestor(targetNode)))
return false;if(targetNode.domModel()!==node.domModel())
return false;return true;}
pasteNode(targetNode){if(this.canPaste(targetNode))
this._performPaste(targetNode);}
_onPaste(event){if(UI.isEditing())
return;const targetNode=this.selectedDOMNode();if(!targetNode||!this.canPaste(targetNode))
return;event.handled=true;this._performPaste(targetNode);}
_performPaste(targetNode){if(this._clipboardNodeData.isCut){this._clipboardNodeData.node.moveTo(targetNode,null,expandCallback.bind(this));this._setClipboardData(null);}else{this._clipboardNodeData.node.copyTo(targetNode,null,expandCallback.bind(this));}
function expandCallback(error,nodeId){if(error)
return;const pastedNode=targetNode.domModel().nodeForId(nodeId);if(!pastedNode)
return;this.selectDOMNode(pastedNode);}}
setVisible(visible){if(visible===this._visible)
return;this._visible=visible;if(!this._visible){this._popoverHelper.hidePopover();if(this._multilineEditing)
this._multilineEditing.cancel();return;}
this.runPendingUpdates();if(this._selectedDOMNode)
this._revealAndSelectNode(this._selectedDOMNode,false);}
get rootDOMNode(){return this._rootDOMNode;}
set rootDOMNode(x){if(this._rootDOMNode===x)
return;this._rootDOMNode=x;this._isXMLMimeType=x&&x.isXMLNode();this.update();}
get isXMLMimeType(){return this._isXMLMimeType;}
selectedDOMNode(){return this._selectedDOMNode;}
selectDOMNode(node,focus){if(this._selectedDOMNode===node){this._revealAndSelectNode(node,!focus);return;}
this._selectedDOMNode=node;this._revealAndSelectNode(node,!focus);if(this._selectedDOMNode===node)
this._selectedNodeChanged(!!focus);}
editing(){const node=this.selectedDOMNode();if(!node)
return false;const treeElement=this.findTreeElement(node);if(!treeElement)
return false;return treeElement.isEditing()||false;}
update(){const selectedNode=this.selectedDOMNode();this.removeChildren();if(!this.rootDOMNode)
return;if(this._includeRootDOMNode){const treeElement=this._createElementTreeElement(this.rootDOMNode);this.appendChild(treeElement);}else{const children=this._visibleChildren(this.rootDOMNode);for(const child of children){const treeElement=this._createElementTreeElement(child);this.appendChild(treeElement);}}
if(selectedNode)
this._revealAndSelectNode(selectedNode,true);}
_selectedNodeChanged(focus){this.dispatchEventToListeners(Elements.ElementsTreeOutline.Events.SelectedNodeChanged,{node:this._selectedDOMNode,focus:focus});}
_fireElementsTreeUpdated(nodes){this.dispatchEventToListeners(Elements.ElementsTreeOutline.Events.ElementsTreeUpdated,nodes);}
findTreeElement(node){let treeElement=this._lookUpTreeElement(node);if(!treeElement&&node.nodeType()===Node.TEXT_NODE){treeElement=this._lookUpTreeElement(node.parentNode);}
return(treeElement);}
_lookUpTreeElement(node){if(!node)
return null;const cachedElement=node[this._treeElementSymbol];if(cachedElement)
return cachedElement;const ancestors=[];let currentNode;for(currentNode=node.parentNode;currentNode;currentNode=currentNode.parentNode){ancestors.push(currentNode);if(currentNode[this._treeElementSymbol])
break;}
if(!currentNode)
return null;for(let i=ancestors.length-1;i>=0;--i){const child=ancestors[i-1]||node;const treeElement=ancestors[i][this._treeElementSymbol];if(treeElement){treeElement.onpopulate();if(child.index>=treeElement.expandedChildrenLimit())
this.setExpandedChildrenLimit(treeElement,child.index+1);}}
return node[this._treeElementSymbol];}
createTreeElementFor(node){let treeElement=this.findTreeElement(node);if(treeElement)
return treeElement;if(!node.parentNode)
return null;treeElement=this.createTreeElementFor(node.parentNode);return treeElement?this._showChild(treeElement,node):null;}
set suppressRevealAndSelect(x){if(this._suppressRevealAndSelect===x)
return;this._suppressRevealAndSelect=x;}
_revealAndSelectNode(node,omitFocus){if(this._suppressRevealAndSelect)
return;if(!this._includeRootDOMNode&&node===this.rootDOMNode&&this.rootDOMNode)
node=this.rootDOMNode.firstChild;if(!node)
return;const treeElement=this.createTreeElementFor(node);if(!treeElement)
return;treeElement.revealAndSelect(omitFocus);}
_treeElementFromEvent(event){const scrollContainer=this.element.parentElement;const x=scrollContainer.totalOffsetLeft()+scrollContainer.offsetWidth-36;const y=event.pageY;const elementUnderMouse=this.treeElementFromPoint(x,y);const elementAboveMouse=this.treeElementFromPoint(x,y-2);let element;if(elementUnderMouse===elementAboveMouse)
element=elementUnderMouse;else
element=this.treeElementFromPoint(x,y+2);return element;}
_getPopoverRequest(event){let link=event.target;while(link&&!link[Elements.ElementsTreeElement.HrefSymbol])
link=link.parentElementOrShadowHost();if(!link)
return null;return{box:link.boxInWindow(),show:async popover=>{const listItem=link.enclosingNodeOrSelfWithNodeName('li');const node=(listItem.treeElement).node();const precomputedFeatures=await Components.ImagePreview.loadDimensionsForNode(node);const preview=await Components.ImagePreview.build(node.domModel().target(),link[Elements.ElementsTreeElement.HrefSymbol],true,precomputedFeatures);if(preview)
popover.contentElement.appendChild(preview);return!!preview;}};}
_onfocusout(event){SDK.OverlayModel.hideDOMNodeHighlight();}
_onmousedown(event){const element=this._treeElementFromEvent(event);if(!element||element.isEventWithinDisclosureTriangle(event))
return;element.select();}
setHoverEffect(treeElement){if(this._previousHoveredElement===treeElement)
return;if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;delete this._previousHoveredElement;}
if(treeElement){treeElement.hovered=true;this._previousHoveredElement=treeElement;}}
_onmousemove(event){const element=this._treeElementFromEvent(event);if(element&&this._previousHoveredElement===element)
return;this.setHoverEffect(element);this._highlightTreeElement((element),!UI.KeyboardShortcut.eventHasCtrlOrMeta(event));}
_highlightTreeElement(element,showInfo){if(element instanceof Elements.ElementsTreeElement){element.node().domModel().overlayModel().highlightInOverlay({node:element.node()},'all',showInfo);return;}
if(element instanceof Elements.ElementsTreeOutline.ShortcutTreeElement)
element.domModel().overlayModel().highlightInOverlay({deferredNode:element.deferredNode()},'all',showInfo);}
_onmouseleave(event){this.setHoverEffect(null);SDK.OverlayModel.hideDOMNodeHighlight();}
_ondragstart(event){if(event.target.hasSelection())
return false;if(event.target.nodeName==='A')
return false;const treeElement=this._validDragSourceOrTarget(this._treeElementFromEvent(event));if(!treeElement)
return false;if(treeElement.node().nodeName()==='BODY'||treeElement.node().nodeName()==='HEAD')
return false;event.dataTransfer.setData('text/plain',treeElement.listItemElement.textContent.replace(/\u200b/g,''));event.dataTransfer.effectAllowed='copyMove';this._treeElementBeingDragged=treeElement;SDK.OverlayModel.hideDOMNodeHighlight();return true;}
_ondragover(event){if(!this._treeElementBeingDragged)
return false;const treeElement=this._validDragSourceOrTarget(this._treeElementFromEvent(event));if(!treeElement)
return false;let node=treeElement.node();while(node){if(node===this._treeElementBeingDragged._node)
return false;node=node.parentNode;}
treeElement.listItemElement.classList.add('elements-drag-over');this._dragOverTreeElement=treeElement;event.preventDefault();event.dataTransfer.dropEffect='move';return false;}
_ondragleave(event){this._clearDragOverTreeElementMarker();event.preventDefault();return false;}
_validDragSourceOrTarget(treeElement){if(!treeElement)
return null;if(!(treeElement instanceof Elements.ElementsTreeElement))
return null;const elementsTreeElement=(treeElement);const node=elementsTreeElement.node();if(!node.parentNode||node.parentNode.nodeType()!==Node.ELEMENT_NODE)
return null;return elementsTreeElement;}
_ondrop(event){event.preventDefault();const treeElement=this._treeElementFromEvent(event);if(treeElement instanceof Elements.ElementsTreeElement)
this._doMove(treeElement);}
_doMove(treeElement){if(!this._treeElementBeingDragged)
return;let parentNode;let anchorNode;if(treeElement.isClosingTag()){parentNode=treeElement.node();}else{const dragTargetNode=treeElement.node();parentNode=dragTargetNode.parentNode;anchorNode=dragTargetNode;}
const wasExpanded=this._treeElementBeingDragged.expanded;this._treeElementBeingDragged._node.moveTo(parentNode,anchorNode,this.selectNodeAfterEdit.bind(this,wasExpanded));delete this._treeElementBeingDragged;}
_ondragend(event){event.preventDefault();this._clearDragOverTreeElementMarker();delete this._treeElementBeingDragged;}
_clearDragOverTreeElementMarker(){if(this._dragOverTreeElement){this._dragOverTreeElement.listItemElement.classList.remove('elements-drag-over');delete this._dragOverTreeElement;}}
_contextMenuEventFired(event){const treeElement=this._treeElementFromEvent(event);if(treeElement instanceof Elements.ElementsTreeElement)
this.showContextMenu(treeElement,event);}
showContextMenu(treeElement,event){if(UI.isEditing())
return;const contextMenu=new UI.ContextMenu(event);const isPseudoElement=!!treeElement.node().pseudoType();const isTag=treeElement.node().nodeType()===Node.ELEMENT_NODE&&!isPseudoElement;let textNode=event.target.enclosingNodeOrSelfWithClass('webkit-html-text-node');if(textNode&&textNode.classList.contains('bogus'))
textNode=null;const commentNode=event.target.enclosingNodeOrSelfWithClass('webkit-html-comment');contextMenu.saveSection().appendItem(ls`Store as global variable`,this._saveNodeToTempVariable.bind(this,treeElement.node()));if(textNode)
treeElement.populateTextContextMenu(contextMenu,textNode);else if(isTag)
treeElement.populateTagContextMenu(contextMenu,event);else if(commentNode)
treeElement.populateNodeContextMenu(contextMenu);else if(isPseudoElement)
treeElement.populateScrollIntoView(contextMenu);contextMenu.appendApplicableItems(treeElement.node());contextMenu.show();}
async _saveNodeToTempVariable(node){const remoteObjectForConsole=await node.resolveToObject();await SDK.consoleModel.saveToTempVariable(UI.context.flavor(SDK.ExecutionContext),remoteObjectForConsole);}
runPendingUpdates(){this._updateModifiedNodes();}
_onKeyDown(event){const keyboardEvent=(event);if(UI.isEditing())
return;const node=this.selectedDOMNode();if(!node)
return;const treeElement=node[this._treeElementSymbol];if(!treeElement)
return;if(UI.KeyboardShortcut.eventHasCtrlOrMeta(keyboardEvent)&&node.parentNode){if(keyboardEvent.key==='ArrowUp'&&node.previousSibling){node.moveTo(node.parentNode,node.previousSibling,this.selectNodeAfterEdit.bind(this,treeElement.expanded));keyboardEvent.consume(true);return;}
if(keyboardEvent.key==='ArrowDown'&&node.nextSibling){node.moveTo(node.parentNode,node.nextSibling.nextSibling,this.selectNodeAfterEdit.bind(this,treeElement.expanded));keyboardEvent.consume(true);return;}}}
toggleEditAsHTML(node,startEditing,callback){const treeElement=node[this._treeElementSymbol];if(!treeElement||!treeElement.hasEditableNode())
return;if(node.pseudoType())
return;const parentNode=node.parentNode;const index=node.index;const wasExpanded=treeElement.expanded;treeElement.toggleEditAsHTML(editingFinished.bind(this),startEditing);function editingFinished(success){if(callback)
callback();if(!success)
return;this.runPendingUpdates();const newNode=parentNode?parentNode.children()[index]||parentNode:null;if(!newNode)
return;this.selectDOMNode(newNode,true);if(wasExpanded){const newTreeItem=this.findTreeElement(newNode);if(newTreeItem)
newTreeItem.expand();}}}
selectNodeAfterEdit(wasExpanded,error,newNode){if(error)
return null;this.runPendingUpdates();if(!newNode)
return null;this.selectDOMNode(newNode,true);const newTreeItem=this.findTreeElement(newNode);if(wasExpanded){if(newTreeItem)
newTreeItem.expand();}
return newTreeItem;}
async toggleHideElement(node){const pseudoType=node.pseudoType();const effectiveNode=pseudoType?node.parentNode:node;if(!effectiveNode)
return;const hidden=node.marker('hidden-marker');const object=await effectiveNode.resolveToObject('');if(!object)
return;await object.callFunction(toggleClassAndInjectStyleRule,[{value:pseudoType},{value:!hidden}]);object.release();node.setMarker('hidden-marker',hidden?null:true);function toggleClassAndInjectStyleRule(pseudoType,hidden){const classNamePrefix='__web-inspector-hide';const classNameSuffix='-shortcut__';const styleTagId='__web-inspector-hide-shortcut-style__';const selectors=[];selectors.push('.__web-inspector-hide-shortcut__');selectors.push('.__web-inspector-hide-shortcut__ *');selectors.push('.__web-inspector-hidebefore-shortcut__::before');selectors.push('.__web-inspector-hideafter-shortcut__::after');const selector=selectors.join(', ');const ruleBody=' visibility: hidden !important;';const rule='\n'+selector+'\n{\n'+ruleBody+'\n}\n';const className=classNamePrefix+(pseudoType||'')+classNameSuffix;this.classList.toggle(className,hidden);let localRoot=this;while(localRoot.parentNode)
localRoot=localRoot.parentNode;if(localRoot.nodeType===Node.DOCUMENT_NODE)
localRoot=document.head;let style=localRoot.querySelector('style#'+styleTagId);if(style)
return;style=document.createElement('style');style.id=styleTagId;style.type='text/css';style.textContent=rule;localRoot.appendChild(style);}}
isToggledToHidden(node){return!!node.marker('hidden-marker');}
_reset(){this.rootDOMNode=null;this.selectDOMNode(null,false);this._popoverHelper.hidePopover();delete this._clipboardNodeData;SDK.OverlayModel.hideDOMNodeHighlight();this._updateRecords.clear();}
wireToDOMModel(domModel){domModel[Elements.ElementsTreeOutline._treeOutlineSymbol]=this;domModel.addEventListener(SDK.DOMModel.Events.MarkersChanged,this._markersChanged,this);domModel.addEventListener(SDK.DOMModel.Events.NodeInserted,this._nodeInserted,this);domModel.addEventListener(SDK.DOMModel.Events.NodeRemoved,this._nodeRemoved,this);domModel.addEventListener(SDK.DOMModel.Events.AttrModified,this._attributeModified,this);domModel.addEventListener(SDK.DOMModel.Events.AttrRemoved,this._attributeRemoved,this);domModel.addEventListener(SDK.DOMModel.Events.CharacterDataModified,this._characterDataModified,this);domModel.addEventListener(SDK.DOMModel.Events.DocumentUpdated,this._documentUpdated,this);domModel.addEventListener(SDK.DOMModel.Events.ChildNodeCountUpdated,this._childNodeCountUpdated,this);domModel.addEventListener(SDK.DOMModel.Events.DistributedNodesChanged,this._distributedNodesChanged,this);}
unwireFromDOMModel(domModel){domModel.removeEventListener(SDK.DOMModel.Events.MarkersChanged,this._markersChanged,this);domModel.removeEventListener(SDK.DOMModel.Events.NodeInserted,this._nodeInserted,this);domModel.removeEventListener(SDK.DOMModel.Events.NodeRemoved,this._nodeRemoved,this);domModel.removeEventListener(SDK.DOMModel.Events.AttrModified,this._attributeModified,this);domModel.removeEventListener(SDK.DOMModel.Events.AttrRemoved,this._attributeRemoved,this);domModel.removeEventListener(SDK.DOMModel.Events.CharacterDataModified,this._characterDataModified,this);domModel.removeEventListener(SDK.DOMModel.Events.DocumentUpdated,this._documentUpdated,this);domModel.removeEventListener(SDK.DOMModel.Events.ChildNodeCountUpdated,this._childNodeCountUpdated,this);domModel.removeEventListener(SDK.DOMModel.Events.DistributedNodesChanged,this._distributedNodesChanged,this);delete domModel[Elements.ElementsTreeOutline._treeOutlineSymbol];}
_addUpdateRecord(node){let record=this._updateRecords.get(node);if(!record){record=new Elements.ElementsTreeOutline.UpdateRecord();this._updateRecords.set(node,record);}
return record;}
_updateRecordForHighlight(node){if(!this._visible)
return null;return this._updateRecords.get(node)||null;}
_documentUpdated(event){const domModel=(event.data);this._reset();if(domModel.existingDocument())
this.rootDOMNode=domModel.existingDocument();}
_attributeModified(event){const node=(event.data.node);this._addUpdateRecord(node).attributeModified(event.data.name);this._updateModifiedNodesSoon();}
_attributeRemoved(event){const node=(event.data.node);this._addUpdateRecord(node).attributeRemoved(event.data.name);this._updateModifiedNodesSoon();}
_characterDataModified(event){const node=(event.data);this._addUpdateRecord(node).charDataModified();if(node.parentNode&&node.parentNode.firstChild===node.parentNode.lastChild)
this._addUpdateRecord(node.parentNode).childrenModified();this._updateModifiedNodesSoon();}
_nodeInserted(event){const node=(event.data);this._addUpdateRecord((node.parentNode)).nodeInserted(node);this._updateModifiedNodesSoon();}
_nodeRemoved(event){const node=(event.data.node);const parentNode=(event.data.parent);this.resetClipboardIfNeeded(node);this._addUpdateRecord(parentNode).nodeRemoved(node);this._updateModifiedNodesSoon();}
_childNodeCountUpdated(event){const node=(event.data);this._addUpdateRecord(node).childrenModified();this._updateModifiedNodesSoon();}
_distributedNodesChanged(event){const node=(event.data);this._addUpdateRecord(node).childrenModified();this._updateModifiedNodesSoon();}
_updateModifiedNodesSoon(){if(!this._updateRecords.size)
return;if(this._updateModifiedNodesTimeout)
return;this._updateModifiedNodesTimeout=setTimeout(this._updateModifiedNodes.bind(this),50);}
_updateModifiedNodes(){if(this._updateModifiedNodesTimeout){clearTimeout(this._updateModifiedNodesTimeout);delete this._updateModifiedNodesTimeout;}
const updatedNodes=this._updateRecords.keysArray();const hidePanelWhileUpdating=updatedNodes.length>10;let treeOutlineContainerElement;let originalScrollTop;if(hidePanelWhileUpdating){treeOutlineContainerElement=this.element.parentNode;originalScrollTop=treeOutlineContainerElement?treeOutlineContainerElement.scrollTop:0;this._element.classList.add('hidden');}
if(this._rootDOMNode&&this._updateRecords.get(this._rootDOMNode)&&this._updateRecords.get(this._rootDOMNode).hasChangedChildren()){this.update();}else{for(const node of this._updateRecords.keys()){if(this._updateRecords.get(node).hasChangedChildren())
this._updateModifiedParentNode(node);else
this._updateModifiedNode(node);}}
if(hidePanelWhileUpdating){this._element.classList.remove('hidden');if(originalScrollTop)
treeOutlineContainerElement.scrollTop=originalScrollTop;}
this._updateRecords.clear();this._fireElementsTreeUpdated(updatedNodes);}
_updateModifiedNode(node){const treeElement=this.findTreeElement(node);if(treeElement)
treeElement.updateTitle(this._updateRecordForHighlight(node));}
_updateModifiedParentNode(node){const parentTreeElement=this.findTreeElement(node);if(parentTreeElement){parentTreeElement.setExpandable(this._hasVisibleChildren(node));parentTreeElement.updateTitle(this._updateRecordForHighlight(node));if(parentTreeElement.populated)
this._updateChildren(parentTreeElement);}}
populateTreeElement(treeElement){if(treeElement.childCount()||!treeElement.isExpandable())
return;treeElement.node().getChildNodes(()=>{treeElement.populated=true;this._updateModifiedParentNode(treeElement.node());});}
_createElementTreeElement(node,closingTag){const treeElement=new Elements.ElementsTreeElement(node,closingTag);treeElement.setExpandable(!closingTag&&this._hasVisibleChildren(node));if(node.nodeType()===Node.ELEMENT_NODE&&node.parentNode&&node.parentNode.nodeType()===Node.DOCUMENT_NODE&&!node.parentNode.parentNode)
treeElement.setCollapsible(false);treeElement.selectable=this._selectEnabled;return treeElement;}
_showChild(treeElement,child){if(treeElement.isClosingTag())
return null;const index=this._visibleChildren(treeElement.node()).indexOf(child);if(index===-1)
return null;if(index>=treeElement.expandedChildrenLimit())
this.setExpandedChildrenLimit(treeElement,index+1);return(treeElement.childAt(index));}
_visibleChildren(node){let visibleChildren=Elements.ElementsTreeElement.visibleShadowRoots(node);const contentDocument=node.contentDocument();if(contentDocument)
visibleChildren.push(contentDocument);const importedDocument=node.importedDocument();if(importedDocument)
visibleChildren.push(importedDocument);const templateContent=node.templateContent();if(templateContent)
visibleChildren.push(templateContent);const beforePseudoElement=node.beforePseudoElement();if(beforePseudoElement)
visibleChildren.push(beforePseudoElement);if(node.childNodeCount()){let children=node.children()||[];if(!this._showHTMLCommentsSetting.get())
children=children.filter(n=>n.nodeType()!==Node.COMMENT_NODE);visibleChildren=visibleChildren.concat(children);}
const afterPseudoElement=node.afterPseudoElement();if(afterPseudoElement)
visibleChildren.push(afterPseudoElement);return visibleChildren;}
_hasVisibleChildren(node){if(node.isIframe())
return true;if(node.isPortal())
return true;if(node.contentDocument())
return true;if(node.importedDocument())
return true;if(node.templateContent())
return true;if(Elements.ElementsTreeElement.visibleShadowRoots(node).length)
return true;if(node.hasPseudoElements())
return true;if(node.isInsertionPoint())
return true;return!!node.childNodeCount()&&!Elements.ElementsTreeElement.canShowInlineText(node);}
_createExpandAllButtonTreeElement(treeElement){const button=UI.createTextButton('',handleLoadAllChildren.bind(this));button.value='';const expandAllButtonElement=new UI.TreeElement(button);expandAllButtonElement.selectable=false;expandAllButtonElement.expandAllButton=true;expandAllButtonElement.button=button;return expandAllButtonElement;function handleLoadAllChildren(event){const visibleChildCount=this._visibleChildren(treeElement.node()).length;this.setExpandedChildrenLimit(treeElement,Math.max(visibleChildCount,treeElement.expandedChildrenLimit()+Elements.ElementsTreeElement.InitialChildrenLimit));event.consume();}}
setExpandedChildrenLimit(treeElement,expandedChildrenLimit){if(treeElement.expandedChildrenLimit()===expandedChildrenLimit)
return;treeElement.setExpandedChildrenLimit(expandedChildrenLimit);if(treeElement.treeOutline&&!this._treeElementsBeingUpdated.has(treeElement))
this._updateModifiedParentNode(treeElement.node());}
_updateChildren(treeElement){if(!treeElement.isExpandable()){const selectedTreeElement=treeElement.treeOutline.selectedTreeElement;if(selectedTreeElement&&selectedTreeElement.hasAncestor(treeElement))
treeElement.select(true);treeElement.removeChildren();return;}
console.assert(!treeElement.isClosingTag());this._innerUpdateChildren(treeElement);}
insertChildElement(treeElement,child,index,closingTag){const newElement=this._createElementTreeElement(child,closingTag);treeElement.insertChild(newElement,index);return newElement;}
_moveChild(treeElement,child,targetIndex){if(treeElement.indexOfChild(child)===targetIndex)
return;const wasSelected=child.selected;if(child.parent)
child.parent.removeChild(child);treeElement.insertChild(child,targetIndex);if(wasSelected)
child.select();}
_innerUpdateChildren(treeElement){if(this._treeElementsBeingUpdated.has(treeElement))
return;this._treeElementsBeingUpdated.add(treeElement);const node=treeElement.node();const visibleChildren=this._visibleChildren(node);const visibleChildrenSet=new Set(visibleChildren);const existingTreeElements=new Map();for(let i=treeElement.childCount()-1;i>=0;--i){const existingTreeElement=treeElement.childAt(i);if(!(existingTreeElement instanceof Elements.ElementsTreeElement)){treeElement.removeChildAtIndex(i);continue;}
const elementsTreeElement=(existingTreeElement);const existingNode=elementsTreeElement.node();if(visibleChildrenSet.has(existingNode)){existingTreeElements.set(existingNode,existingTreeElement);continue;}
treeElement.removeChildAtIndex(i);}
for(let i=0;i<visibleChildren.length&&i<treeElement.expandedChildrenLimit();++i){const child=visibleChildren[i];const existingTreeElement=existingTreeElements.get(child)||this.findTreeElement(child);if(existingTreeElement&&existingTreeElement!==treeElement){this._moveChild(treeElement,existingTreeElement,i);}else{const newElement=this.insertChildElement(treeElement,child,i);if(this._updateRecordForHighlight(node)&&treeElement.expanded)
Elements.ElementsTreeElement.animateOnDOMUpdate(newElement);if(treeElement.childCount()>treeElement.expandedChildrenLimit())
this.setExpandedChildrenLimit(treeElement,treeElement.expandedChildrenLimit()+1);}}
const expandedChildCount=treeElement.childCount();if(visibleChildren.length>expandedChildCount){const targetButtonIndex=expandedChildCount;if(!treeElement.expandAllButtonElement)
treeElement.expandAllButtonElement=this._createExpandAllButtonTreeElement(treeElement);treeElement.insertChild(treeElement.expandAllButtonElement,targetButtonIndex);treeElement.expandAllButtonElement.button.textContent=Common.UIString('Show All Nodes (%d More)',visibleChildren.length-expandedChildCount);}else if(treeElement.expandAllButtonElement){delete treeElement.expandAllButtonElement;}
if(node.isInsertionPoint()){for(const distributedNode of node.distributedNodes())
treeElement.appendChild(new Elements.ElementsTreeOutline.ShortcutTreeElement(distributedNode));}
if(node.nodeType()===Node.ELEMENT_NODE&&treeElement.isExpandable())
this.insertChildElement(treeElement,node,treeElement.childCount(),true);this._treeElementsBeingUpdated.delete(treeElement);}
_markersChanged(event){const node=(event.data);const treeElement=node[this._treeElementSymbol];if(treeElement)
treeElement.updateDecorations();}};Elements.ElementsTreeOutline._treeOutlineSymbol=Symbol('treeOutline');Elements.ElementsTreeOutline.ClipboardData;Elements.ElementsTreeOutline.Events={SelectedNodeChanged:Symbol('SelectedNodeChanged'),ElementsTreeUpdated:Symbol('ElementsTreeUpdated')};Elements.ElementsTreeOutline.MappedCharToEntity={'\u00a0':'nbsp','\u0093':'#147','\u00ad':'shy','\u2002':'ensp','\u2003':'emsp','\u2009':'thinsp','\u200a':'#8202','\u200b':'#8203','\u200c':'zwnj','\u200d':'zwj','\u200e':'lrm','\u200f':'rlm','\u202a':'#8234','\u202b':'#8235','\u202c':'#8236','\u202d':'#8237','\u202e':'#8238','\ufeff':'#65279'};Elements.ElementsTreeOutline.UpdateRecord=class{attributeModified(attrName){if(this._removedAttributes&&this._removedAttributes.has(attrName))
this._removedAttributes.delete(attrName);if(!this._modifiedAttributes)
this._modifiedAttributes=(new Set());this._modifiedAttributes.add(attrName);}
attributeRemoved(attrName){if(this._modifiedAttributes&&this._modifiedAttributes.has(attrName))
this._modifiedAttributes.delete(attrName);if(!this._removedAttributes)
this._removedAttributes=(new Set());this._removedAttributes.add(attrName);}
nodeInserted(node){this._hasChangedChildren=true;}
nodeRemoved(node){this._hasChangedChildren=true;this._hasRemovedChildren=true;}
charDataModified(){this._charDataModified=true;}
childrenModified(){this._hasChangedChildren=true;}
isAttributeModified(attributeName){return this._modifiedAttributes&&this._modifiedAttributes.has(attributeName);}
hasRemovedAttributes(){return!!this._removedAttributes&&!!this._removedAttributes.size;}
isCharDataModified(){return!!this._charDataModified;}
hasChangedChildren(){return!!this._hasChangedChildren;}
hasRemovedChildren(){return!!this._hasRemovedChildren;}};Elements.ElementsTreeOutline.Renderer=class{render(object){return new Promise(renderPromise);function renderPromise(resolve,reject){if(object instanceof SDK.DOMNode)
onNodeResolved((object));else if(object instanceof SDK.DeferredDOMNode)
((object)).resolve(onNodeResolved);else
reject(new Error('Can\'t reveal not a node.'));function onNodeResolved(node){if(!node){reject(new Error('Could not resolve node.'));return;}
const treeOutline=new Elements.ElementsTreeOutline(false,true,true);treeOutline.rootDOMNode=node;if(!treeOutline.firstChild().isExpandable())
treeOutline._element.classList.add('single-node');treeOutline.setVisible(true);treeOutline.element.treeElementForTest=treeOutline.firstChild();treeOutline.setShowSelectionOnKeyboardFocus(true,true);resolve({node:treeOutline.element,tree:treeOutline});}}}};Elements.ElementsTreeOutline.ShortcutTreeElement=class extends UI.TreeElement{constructor(nodeShortcut){super('');this.listItemElement.createChild('div','selection fill');const title=this.listItemElement.createChild('span','elements-tree-shortcut-title');let text=nodeShortcut.nodeName.toLowerCase();if(nodeShortcut.nodeType===Node.ELEMENT_NODE)
text='<'+text+'>';title.textContent='\u21AA '+text;const link=Elements.DOMLinkifier.linkifyDeferredNodeReference(nodeShortcut.deferredNode);this.listItemElement.createTextChild(' ');link.classList.add('elements-tree-shortcut-link');link.textContent=Common.UIString('reveal');this.listItemElement.appendChild(link);this._nodeShortcut=nodeShortcut;}
get hovered(){return this._hovered;}
set hovered(x){if(this._hovered===x)
return;this._hovered=x;this.listItemElement.classList.toggle('hovered',x);}
deferredNode(){return this._nodeShortcut.deferredNode;}
domModel(){return this._nodeShortcut.deferredNode.domModel();}
onselect(selectedByUser){if(!selectedByUser)
return true;this._nodeShortcut.deferredNode.highlight();this._nodeShortcut.deferredNode.resolve(resolved.bind(this));function resolved(node){if(node){this.treeOutline._selectedDOMNode=node;this.treeOutline._selectedNodeChanged();}}
return true;}};;Elements.EventListenersWidget=class extends UI.ThrottledWidget{constructor(){super();this._toolbarItems=[];this._showForAncestorsSetting=Common.settings.moduleSetting('showEventListenersForAncestors');this._showForAncestorsSetting.addChangeListener(this.update.bind(this));this._dispatchFilterBySetting=Common.settings.createSetting('eventListenerDispatchFilterType',Elements.EventListenersWidget.DispatchFilterBy.All);this._dispatchFilterBySetting.addChangeListener(this.update.bind(this));this._showFrameworkListenersSetting=Common.settings.createSetting('showFrameowkrListeners',true);this._showFrameworkListenersSetting.setTitle(Common.UIString('Framework listeners'));this._showFrameworkListenersSetting.addChangeListener(this._showFrameworkListenersChanged.bind(this));this._eventListenersView=new EventListeners.EventListenersView(this.update.bind(this));this._eventListenersView.show(this.element);const refreshButton=new UI.ToolbarButton(Common.UIString('Refresh'),'largeicon-refresh');refreshButton.addEventListener(UI.ToolbarButton.Events.Click,this.update.bind(this));this._toolbarItems.push(refreshButton);this._toolbarItems.push(new UI.ToolbarSettingCheckbox(this._showForAncestorsSetting,Common.UIString('Show listeners on the ancestors'),Common.UIString('Ancestors')));const dispatchFilter=new UI.ToolbarComboBox(this._onDispatchFilterTypeChanged.bind(this));dispatchFilter.setTitle(ls`Event listeners category`);function addDispatchFilterOption(name,value){const option=dispatchFilter.createOption(name,'',value);if(value===this._dispatchFilterBySetting.get())
dispatchFilter.select(option);}
addDispatchFilterOption.call(this,Common.UIString('All'),Elements.EventListenersWidget.DispatchFilterBy.All);addDispatchFilterOption.call(this,Common.UIString('Passive'),Elements.EventListenersWidget.DispatchFilterBy.Passive);addDispatchFilterOption.call(this,Common.UIString('Blocking'),Elements.EventListenersWidget.DispatchFilterBy.Blocking);dispatchFilter.setMaxWidth(200);this._toolbarItems.push(dispatchFilter);this._toolbarItems.push(new UI.ToolbarSettingCheckbox(this._showFrameworkListenersSetting,Common.UIString('Resolve event listeners bound with framework')));UI.context.addFlavorChangeListener(SDK.DOMNode,this.update,this);this.update();}
doUpdate(){if(this._lastRequestedNode){this._lastRequestedNode.domModel().runtimeModel().releaseObjectGroup(Elements.EventListenersWidget._objectGroupName);delete this._lastRequestedNode;}
const node=UI.context.flavor(SDK.DOMNode);if(!node){this._eventListenersView.reset();this._eventListenersView.addEmptyHolderIfNeeded();return Promise.resolve();}
this._lastRequestedNode=node;const selectedNodeOnly=!this._showForAncestorsSetting.get();const promises=[];promises.push(node.resolveToObject(Elements.EventListenersWidget._objectGroupName));if(!selectedNodeOnly){let currentNode=node.parentNode;while(currentNode){promises.push(currentNode.resolveToObject(Elements.EventListenersWidget._objectGroupName));currentNode=currentNode.parentNode;}
promises.push(this._windowObjectInNodeContext(node));}
return Promise.all(promises).then(this._eventListenersView.addObjects.bind(this._eventListenersView)).then(this._showFrameworkListenersChanged.bind(this));}
toolbarItems(){return this._toolbarItems;}
_onDispatchFilterTypeChanged(event){this._dispatchFilterBySetting.set(event.target.value);}
_showFrameworkListenersChanged(){const dispatchFilter=this._dispatchFilterBySetting.get();const showPassive=dispatchFilter===Elements.EventListenersWidget.DispatchFilterBy.All||dispatchFilter===Elements.EventListenersWidget.DispatchFilterBy.Passive;const showBlocking=dispatchFilter===Elements.EventListenersWidget.DispatchFilterBy.All||dispatchFilter===Elements.EventListenersWidget.DispatchFilterBy.Blocking;this._eventListenersView.showFrameworkListeners(this._showFrameworkListenersSetting.get(),showPassive,showBlocking);}
_windowObjectInNodeContext(node){const executionContexts=node.domModel().runtimeModel().executionContexts();let context=null;if(node.frameId()){for(let i=0;i<executionContexts.length;++i){const executionContext=executionContexts[i];if(executionContext.frameId===node.frameId()&&executionContext.isDefault)
context=executionContext;}}else{context=executionContexts[0];}
return context.evaluate({expression:'self',objectGroup:Elements.EventListenersWidget._objectGroupName,includeCommandLineAPI:false,silent:true,returnByValue:false,generatePreview:false},false,false).then(result=>result.object||null);}
_eventListenersArrivedForTest(){}};Elements.EventListenersWidget.DispatchFilterBy={All:'All',Blocking:'Blocking',Passive:'Passive'};Elements.EventListenersWidget._objectGroupName='event-listeners-panel';;Elements.MarkerDecorator=function(){};Elements.MarkerDecorator.prototype={decorate(node){}};Elements.GenericDecorator=class{constructor(extension){this._title=Common.UIString(extension.title());this._color=extension.descriptor()['color'];}
decorate(node){return{title:this._title,color:this._color};}};;Elements.MetricsSidebarPane=class extends Elements.ElementsSidebarPane{constructor(){super();this.registerRequiredCSS('elements/metricsSidebarPane.css');this._inlineStyle=null;}
doUpdate(){if(this._isEditingMetrics)
return Promise.resolve();const node=this.node();const cssModel=this.cssModel();if(!node||node.nodeType()!==Node.ELEMENT_NODE||!cssModel){this.contentElement.removeChildren();return Promise.resolve();}
function callback(style){if(!style||this.node()!==node)
return;this._updateMetrics(style);}
function inlineStyleCallback(inlineStyleResult){if(inlineStyleResult&&this.node()===node)
this._inlineStyle=inlineStyleResult.inlineStyle;}
const promises=[cssModel.computedStylePromise(node.id).then(callback.bind(this)),cssModel.inlineStylesPromise(node.id).then(inlineStyleCallback.bind(this))];return Promise.all(promises);}
onCSSModelChanged(){this.update();}
_getPropertyValueAsPx(style,propertyName){return Number(style.get(propertyName).replace(/px$/,'')||0);}
_getBox(computedStyle,componentName){const suffix=componentName==='border'?'-width':'';const left=this._getPropertyValueAsPx(computedStyle,componentName+'-left'+suffix);const top=this._getPropertyValueAsPx(computedStyle,componentName+'-top'+suffix);const right=this._getPropertyValueAsPx(computedStyle,componentName+'-right'+suffix);const bottom=this._getPropertyValueAsPx(computedStyle,componentName+'-bottom'+suffix);return{left:left,top:top,right:right,bottom:bottom};}
_highlightDOMNode(showHighlight,mode,event){event.consume();if(showHighlight&&this.node()){if(this._highlightMode===mode)
return;this._highlightMode=mode;this.node().highlight(mode);}else{delete this._highlightMode;SDK.OverlayModel.hideDOMNodeHighlight();}
for(let i=0;this._boxElements&&i<this._boxElements.length;++i){const element=this._boxElements[i];if(!this.node()||mode==='all'||element._name===mode)
element.style.backgroundColor=element._backgroundColor;else
element.style.backgroundColor='';}}
_updateMetrics(style){const metricsElement=createElement('div');metricsElement.className='metrics';const self=this;function createBoxPartElement(style,name,side,suffix){const propertyName=(name!=='position'?name+'-':'')+side+suffix;let value=style.get(propertyName);if(value===''||(name!=='position'&&value==='0px'))
value='\u2012';else if(name==='position'&&value==='auto')
value='\u2012';value=value.replace(/px$/,'');value=Number.toFixedIfFloating(value);const element=createElement('div');element.className=side;element.textContent=value;element.addEventListener('dblclick',this.startEditing.bind(this,element,name,propertyName,style),false);return element;}
function getContentAreaWidthPx(style){let width=style.get('width').replace(/px$/,'');if(!isNaN(width)&&style.get('box-sizing')==='border-box'){const borderBox=self._getBox(style,'border');const paddingBox=self._getBox(style,'padding');width=width-borderBox.left-borderBox.right-paddingBox.left-paddingBox.right;}
return Number.toFixedIfFloating(width.toString());}
function getContentAreaHeightPx(style){let height=style.get('height').replace(/px$/,'');if(!isNaN(height)&&style.get('box-sizing')==='border-box'){const borderBox=self._getBox(style,'border');const paddingBox=self._getBox(style,'padding');height=height-borderBox.top-borderBox.bottom-paddingBox.top-paddingBox.bottom;}
return Number.toFixedIfFloating(height.toString());}
const noMarginDisplayType={'table-cell':true,'table-column':true,'table-column-group':true,'table-footer-group':true,'table-header-group':true,'table-row':true,'table-row-group':true};const noPaddingDisplayType={'table-column':true,'table-column-group':true,'table-footer-group':true,'table-header-group':true,'table-row':true,'table-row-group':true};const noPositionType={'static':true};const boxes=['content','padding','border','margin','position'];const boxColors=[Common.Color.PageHighlight.Content,Common.Color.PageHighlight.Padding,Common.Color.PageHighlight.Border,Common.Color.PageHighlight.Margin,Common.Color.fromRGBA([0,0,0,0])];const boxLabels=[Common.UIString('content'),Common.UIString('padding'),Common.UIString('border'),Common.UIString('margin'),Common.UIString('position')];let previousBox=null;this._boxElements=[];for(let i=0;i<boxes.length;++i){const name=boxes[i];if(name==='margin'&&noMarginDisplayType[style.get('display')])
continue;if(name==='padding'&&noPaddingDisplayType[style.get('display')])
continue;if(name==='position'&&noPositionType[style.get('position')])
continue;const boxElement=createElement('div');boxElement.className=name;boxElement._backgroundColor=boxColors[i].asString(Common.Color.Format.RGBA);boxElement._name=name;boxElement.style.backgroundColor=boxElement._backgroundColor;boxElement.addEventListener('mouseover',this._highlightDOMNode.bind(this,true,name==='position'?'all':name),false);this._boxElements.push(boxElement);if(name==='content'){const widthElement=createElement('span');widthElement.textContent=getContentAreaWidthPx(style);widthElement.addEventListener('dblclick',this.startEditing.bind(this,widthElement,'width','width',style),false);const heightElement=createElement('span');heightElement.textContent=getContentAreaHeightPx(style);heightElement.addEventListener('dblclick',this.startEditing.bind(this,heightElement,'height','height',style),false);boxElement.appendChild(widthElement);boxElement.createTextChild(' \u00D7 ');boxElement.appendChild(heightElement);}else{const suffix=(name==='border'?'-width':'');const labelElement=createElement('div');labelElement.className='label';labelElement.textContent=boxLabels[i];boxElement.appendChild(labelElement);boxElement.appendChild(createBoxPartElement.call(this,style,name,'top',suffix));boxElement.appendChild(createElement('br'));boxElement.appendChild(createBoxPartElement.call(this,style,name,'left',suffix));if(previousBox)
boxElement.appendChild(previousBox);boxElement.appendChild(createBoxPartElement.call(this,style,name,'right',suffix));boxElement.appendChild(createElement('br'));boxElement.appendChild(createBoxPartElement.call(this,style,name,'bottom',suffix));}
previousBox=boxElement;}
metricsElement.appendChild(previousBox);metricsElement.addEventListener('mouseover',this._highlightDOMNode.bind(this,false,'all'),false);this.contentElement.removeChildren();this.contentElement.appendChild(metricsElement);Host.userMetrics.panelLoaded('elements','DevTools.Launch.Elements');}
startEditing(targetElement,box,styleProperty,computedStyle){if(UI.isBeingEdited(targetElement))
return;const context={box:box,styleProperty:styleProperty,computedStyle:computedStyle};const boundKeyDown=this._handleKeyDown.bind(this,context,styleProperty);context.keyDownHandler=boundKeyDown;targetElement.addEventListener('keydown',boundKeyDown,false);this._isEditingMetrics=true;const config=new UI.InplaceEditor.Config(this._editingCommitted.bind(this),this.editingCancelled.bind(this),context);UI.InplaceEditor.startEditing(targetElement,config);targetElement.getComponentSelection().selectAllChildren(targetElement);}
_handleKeyDown(context,styleProperty,event){const element=event.currentTarget;function finishHandler(originalValue,replacementString){this._applyUserInput(element,replacementString,originalValue,context,false);}
function customNumberHandler(prefix,number,suffix){if(styleProperty!=='margin'&&number<0)
number=0;return prefix+number+suffix;}
UI.handleElementValueModifications(event,element,finishHandler.bind(this),undefined,customNumberHandler);}
editingEnded(element,context){delete this.originalPropertyData;delete this.previousPropertyDataCandidate;element.removeEventListener('keydown',context.keyDownHandler,false);delete this._isEditingMetrics;}
editingCancelled(element,context){if('originalPropertyData'in this&&this._inlineStyle){if(!this.originalPropertyData){const pastLastSourcePropertyIndex=this._inlineStyle.pastLastSourcePropertyIndex();if(pastLastSourcePropertyIndex)
this._inlineStyle.allProperties()[pastLastSourcePropertyIndex-1].setText('',false);}else{this._inlineStyle.allProperties()[this.originalPropertyData.index].setText(this.originalPropertyData.propertyText,false);}}
this.editingEnded(element,context);this.update();}
_applyUserInput(element,userInput,previousContent,context,commitEditor){if(!this._inlineStyle){return this.editingCancelled(element,context);}
if(commitEditor&&userInput===previousContent)
return this.editingCancelled(element,context);if(context.box!=='position'&&(!userInput||userInput==='\u2012'))
userInput='0px';else if(context.box==='position'&&(!userInput||userInput==='\u2012'))
userInput='auto';userInput=userInput.toLowerCase();if(/^\d+$/.test(userInput))
userInput+='px';const styleProperty=context.styleProperty;const computedStyle=context.computedStyle;if(computedStyle.get('box-sizing')==='border-box'&&(styleProperty==='width'||styleProperty==='height')){if(!userInput.match(/px$/)){Common.console.error('For elements with box-sizing: border-box, only absolute content area dimensions can be applied');return;}
const borderBox=this._getBox(computedStyle,'border');const paddingBox=this._getBox(computedStyle,'padding');let userValuePx=Number(userInput.replace(/px$/,''));if(isNaN(userValuePx))
return;if(styleProperty==='width')
userValuePx+=borderBox.left+borderBox.right+paddingBox.left+paddingBox.right;else
userValuePx+=borderBox.top+borderBox.bottom+paddingBox.top+paddingBox.bottom;userInput=userValuePx+'px';}
this.previousPropertyDataCandidate=null;const allProperties=this._inlineStyle.allProperties();for(let i=0;i<allProperties.length;++i){const property=allProperties[i];if(property.name!==context.styleProperty||!property.activeInStyle())
continue;this.previousPropertyDataCandidate=property;property.setValue(userInput,commitEditor,true,callback.bind(this));return;}
this._inlineStyle.appendProperty(context.styleProperty,userInput,callback.bind(this));function callback(success){if(!success)
return;if(!('originalPropertyData'in this))
this.originalPropertyData=this.previousPropertyDataCandidate;if(typeof this._highlightMode!=='undefined')
this.node().highlight(this._highlightMode);if(commitEditor)
this.update();}}
_editingCommitted(element,userInput,previousContent,context){this.editingEnded(element,context);this._applyUserInput(element,userInput,previousContent,context,true);}};;Elements.PlatformFontsWidget=class extends UI.ThrottledWidget{constructor(sharedModel){super(true);this.registerRequiredCSS('elements/platformFontsWidget.css');this._sharedModel=sharedModel;this._sharedModel.addEventListener(Elements.ComputedStyleModel.Events.ComputedStyleChanged,this.update,this);this._sectionTitle=createElementWithClass('div','title');this.contentElement.classList.add('platform-fonts');this.contentElement.appendChild(this._sectionTitle);this._sectionTitle.textContent=Common.UIString('Rendered Fonts');this._fontStatsSection=this.contentElement.createChild('div','stats-section');}
doUpdate(){const cssModel=this._sharedModel.cssModel();const node=this._sharedModel.node();if(!node||!cssModel)
return Promise.resolve();return cssModel.platformFontsPromise(node.id).then(this._refreshUI.bind(this,node));}
_refreshUI(node,platformFonts){if(this._sharedModel.node()!==node)
return;this._fontStatsSection.removeChildren();const isEmptySection=!platformFonts||!platformFonts.length;this._sectionTitle.classList.toggle('hidden',isEmptySection);if(isEmptySection)
return;platformFonts.sort(function(a,b){return b.glyphCount-a.glyphCount;});for(let i=0;i<platformFonts.length;++i){const fontStatElement=this._fontStatsSection.createChild('div','font-stats-item');const fontNameElement=fontStatElement.createChild('span','font-name');fontNameElement.textContent=platformFonts[i].familyName;const fontDelimeterElement=fontStatElement.createChild('span','font-delimeter');fontDelimeterElement.textContent='\u2014';const fontOrigin=fontStatElement.createChild('span');fontOrigin.textContent=platformFonts[i].isCustomFont?Common.UIString('Network resource'):Common.UIString('Local file');const fontUsageElement=fontStatElement.createChild('span','font-usage');const usage=platformFonts[i].glyphCount;fontUsageElement.textContent=usage===1?Common.UIString('(%d glyph)',usage):Common.UIString('(%d glyphs)',usage);}}};;Elements.PropertiesWidget=class extends UI.ThrottledWidget{constructor(){super(true);this.registerRequiredCSS('elements/propertiesWidget.css');SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.AttrModified,this._onNodeChange,this);SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.AttrRemoved,this._onNodeChange,this);SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.CharacterDataModified,this._onNodeChange,this);SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.ChildNodeCountUpdated,this._onNodeChange,this);UI.context.addFlavorChangeListener(SDK.DOMNode,this._setNode,this);this._node=UI.context.flavor(SDK.DOMNode);this.update();}
_setNode(event){this._node=(event.data);this.update();}
async doUpdate(){if(this._lastRequestedNode){this._lastRequestedNode.domModel().runtimeModel().releaseObjectGroup(Elements.PropertiesWidget._objectGroupName);delete this._lastRequestedNode;}
if(!this._node){this.contentElement.removeChildren();this.sections=[];return;}
this._lastRequestedNode=this._node;const object=await this._node.resolveToObject(Elements.PropertiesWidget._objectGroupName);if(!object)
return;const result=await object.callFunction(protoList);object.release();if(!result.object||result.wasThrown)
return;const propertiesResult=await result.object.getOwnProperties(false);result.object.release();if(!propertiesResult||!propertiesResult.properties)
return;const properties=propertiesResult.properties;const expanded=[];const sections=this.sections||[];for(let i=0;i<sections.length;++i)
expanded.push(sections[i].expanded);this.contentElement.removeChildren();this.sections=[];for(let i=0;i<properties.length;++i){if(!parseInt(properties[i].name,10))
continue;const property=properties[i].value;let title=property.description;title=title.replace(/Prototype$/,'');const section=new ObjectUI.ObjectPropertiesSection(property,title);section.element.classList.add('properties-widget-section');this.sections.push(section);this.contentElement.appendChild(section.element);if(expanded[this.sections.length-1])
section.expand();section.addEventListener(UI.TreeOutline.Events.ElementExpanded,this._propertyExpanded,this);}
function protoList(){let proto=this;const result={__proto__:null};let counter=1;while(proto){result[counter++]=proto;proto=proto.__proto__;}
return result;}}
_propertyExpanded(event){Host.userMetrics.actionTaken(Host.UserMetrics.Action.DOMPropertiesExpanded);for(const section of this.sections)
section.removeEventListener(UI.TreeOutline.Events.ElementExpanded,this._propertyExpanded,this);}
_onNodeChange(event){if(!this._node)
return;const data=event.data;const node=(data instanceof SDK.DOMNode?data:data.node);if(this._node!==node)
return;this.update();}};Elements.PropertiesWidget._objectGroupName='properties-sidebar-pane';;Elements.StylePropertyHighlighter=class{constructor(ssp,cssProperty){this._styleSidebarPane=ssp;this._cssProperty=cssProperty;}
perform(){for(const section of this._styleSidebarPane.allSections()){for(let treeElement=section.propertiesTreeOutline.firstChild();treeElement;treeElement=treeElement.nextSibling)
treeElement.onpopulate();}
let highlightTreeElement=null;for(const section of this._styleSidebarPane.allSections()){let treeElement=section.propertiesTreeOutline.firstChild();while(treeElement&&!highlightTreeElement){if(treeElement.property===this._cssProperty){highlightTreeElement=treeElement;break;}
treeElement=treeElement.traverseNextTreeElement(false,null,true);}
if(highlightTreeElement)
break;}
if(!highlightTreeElement)
return;highlightTreeElement.parent.expand();highlightTreeElement.listItemElement.scrollIntoViewIfNeeded();highlightTreeElement.listItemElement.animate([{offset:0,backgroundColor:'rgba(255, 255, 0, 0.2)'},{offset:0.1,backgroundColor:'rgba(255, 255, 0, 0.7)'},{offset:1,backgroundColor:'transparent'}],{duration:2000,easing:'cubic-bezier(0, 0, 0.2, 1)'});}};;Elements.StylesSidebarPane=class extends Elements.ElementsSidebarPane{constructor(){super(true);this.setMinimumSize(96,26);this.registerRequiredCSS('elements/stylesSidebarPane.css');Common.moduleSetting('colorFormat').addChangeListener(this.update.bind(this));Common.moduleSetting('textEditorIndent').addChangeListener(this.update.bind(this));this._currentToolbarPane=null;this._animatedToolbarPane=null;this._pendingWidget=null;this._pendingWidgetToggle=null;this._toolbarPaneElement=this._createStylesSidebarToolbar();this._noMatchesElement=this.contentElement.createChild('div','gray-info-message hidden');this._noMatchesElement.textContent=ls`No matching selector or style`;this._sectionsContainer=this.contentElement.createChild('div');UI.ARIAUtils.markAsTree(this._sectionsContainer);this._sectionsContainer.addEventListener('keydown',this._sectionsContainerKeyDown.bind(this),false);this._sectionsContainer.addEventListener('focusin',this._sectionsContainerFocusChanged.bind(this),false);this._sectionsContainer.addEventListener('focusout',this._sectionsContainerFocusChanged.bind(this),false);this._swatchPopoverHelper=new InlineEditor.SwatchPopoverHelper();this._linkifier=new Components.Linkifier(Elements.StylesSidebarPane._maxLinkLength,true);this._decorator=null;this._userOperation=false;this._isEditingStyle=false;this._filterRegex=null;this._isActivePropertyHighlighted=false;this.contentElement.classList.add('styles-pane');this._sectionBlocks=[];this._needsForceUpdate=false;Elements.StylesSidebarPane._instance=this;UI.context.addFlavorChangeListener(SDK.DOMNode,this.forceUpdate,this);this.contentElement.addEventListener('copy',this._clipboardCopy.bind(this));this._resizeThrottler=new Common.Throttler(100);}
swatchPopoverHelper(){return this._swatchPopoverHelper;}
setUserOperation(userOperation){this._userOperation=userOperation;}
static createExclamationMark(property){const exclamationElement=createElement('span','dt-icon-label');exclamationElement.className='exclamation-mark';if(!Elements.StylesSidebarPane.ignoreErrorsForProperty(property))
exclamationElement.type='smallicon-warning';exclamationElement.title=SDK.cssMetadata().isCSSPropertyName(property.name)?Common.UIString('Invalid property value'):Common.UIString('Unknown property name');return exclamationElement;}
static ignoreErrorsForProperty(property){function hasUnknownVendorPrefix(string){return!string.startsWith('-webkit-')&&/^[-_][\w\d]+-\w/.test(string);}
const name=property.name.toLowerCase();if(name.charAt(0)==='_')
return true;if(name==='filter')
return true;if(name.startsWith('scrollbar-'))
return true;if(hasUnknownVendorPrefix(name))
return true;const value=property.value.toLowerCase();if(value.endsWith('\\9'))
return true;if(hasUnknownVendorPrefix(value))
return true;return false;}
static createPropertyFilterElement(placeholder,container,filterCallback){const input=createElementWithClass('input');input.placeholder=placeholder;function searchHandler(){const regex=input.value?new RegExp(input.value.escapeForRegExp(),'i'):null;filterCallback(regex);}
input.addEventListener('input',searchHandler,false);function keydownHandler(event){if(event.key!=='Escape'||!input.value)
return;event.consume(true);input.value='';searchHandler();}
input.addEventListener('keydown',keydownHandler,false);input.setFilterValue=setFilterValue;function setFilterValue(value){input.value=value;input.focus();searchHandler();}
return input;}
revealProperty(cssProperty){this._decorator=new Elements.StylePropertyHighlighter(this,cssProperty);this._decorator.perform();this.update();}
forceUpdate(){this._needsForceUpdate=true;this._swatchPopoverHelper.hide();this._resetCache();this.update();}
_sectionsContainerKeyDown(event){const activeElement=this._sectionsContainer.ownerDocument.deepActiveElement();if(!activeElement)
return;const section=activeElement._section;if(!section)
return;switch(event.key){case'ArrowUp':case'ArrowLeft':const sectionToFocus=section.previousSibling()||section.lastSibling();sectionToFocus.element.focus();event.consume(true);break;case'ArrowDown':case'ArrowRight':{const sectionToFocus=section.nextSibling()||section.firstSibling();sectionToFocus.element.focus();event.consume(true);break;}
case'Home':section.firstSibling().element.focus();event.consume(true);break;case'End':section.lastSibling().element.focus();event.consume(true);break;}}
_sectionsContainerFocusChanged(){if(this._sectionBlocks[0]&&this._sectionBlocks[0].sections[0])
this._sectionBlocks[0].sections[0].element.tabIndex=this._sectionsContainer.hasFocus()?-1:0;}
_onAddButtonLongClick(event){const cssModel=this.cssModel();if(!cssModel)
return;const headers=cssModel.styleSheetHeaders().filter(styleSheetResourceHeader);const contextMenuDescriptors=[];for(let i=0;i<headers.length;++i){const header=headers[i];const handler=this._createNewRuleInStyleSheet.bind(this,header);contextMenuDescriptors.push({text:Bindings.displayNameForURL(header.resourceURL()),handler:handler});}
contextMenuDescriptors.sort(compareDescriptors);const contextMenu=new UI.ContextMenu(event);for(let i=0;i<contextMenuDescriptors.length;++i){const descriptor=contextMenuDescriptors[i];contextMenu.defaultSection().appendItem(descriptor.text,descriptor.handler);}
contextMenu.footerSection().appendItem('inspector-stylesheet',this._createNewRuleInViaInspectorStyleSheet.bind(this));contextMenu.show();function compareDescriptors(descriptor1,descriptor2){return String.naturalOrderComparator(descriptor1.text,descriptor2.text);}
function styleSheetResourceHeader(header){return!header.isViaInspector()&&!header.isInline&&!!header.resourceURL();}}
_onFilterChanged(regex){this._filterRegex=regex;this._updateFilter();}
_refreshUpdate(editedSection,editedTreeElement){if(editedTreeElement){for(const section of this.allSections()){if(section.isBlank)
continue;section._updateVarFunctions(editedTreeElement);}}
if(this._isEditingStyle)
return;const node=this.node();if(!node)
return;for(const section of this.allSections()){if(section.isBlank)
continue;section.update(section===editedSection);}
if(this._filterRegex)
this._updateFilter();this._nodeStylesUpdatedForTest(node,false);}
doUpdate(){return this._fetchMatchedCascade().then(this._innerRebuildUpdate.bind(this));}
onResize(){this._resizeThrottler.schedule(this._innerResize.bind(this));}
_innerResize(){const width=this.contentElement.getBoundingClientRect().width+'px';this.allSections().forEach(section=>section.propertiesTreeOutline.element.style.width=width);return Promise.resolve();}
_resetCache(){if(this.cssModel())
this.cssModel().discardCachedMatchedCascade();}
_fetchMatchedCascade(){const node=this.node();if(!node||!this.cssModel())
return Promise.resolve((null));return this.cssModel().cachedMatchedCascadeForNode(node).then(validateStyles.bind(this));function validateStyles(matchedStyles){return matchedStyles&&matchedStyles.node()===this.node()?matchedStyles:null;}}
setEditingStyle(editing,treeElement){if(this._isEditingStyle===editing)
return;this.contentElement.classList.toggle('is-editing-style',editing);this._isEditingStyle=editing;this._setActiveProperty(null);}
_setActiveProperty(treeElement){if(this._isActivePropertyHighlighted)
SDK.OverlayModel.hideDOMNodeHighlight();this._isActivePropertyHighlighted=false;if(!this.node())
return;if(!treeElement||treeElement.overloaded()||treeElement.inherited())
return;const rule=treeElement.property.ownerStyle.parentRule;const selectorList=rule?rule.selectorText():undefined;for(const mode of['padding','border','margin']){if(!treeElement.name.startsWith(mode))
continue;this.node().domModel().overlayModel().highlightInOverlay({node:(this.node()),selectorList},mode);this._isActivePropertyHighlighted=true;break;}}
onCSSModelChanged(event){const edit=event&&event.data?(event.data.edit):null;if(edit){for(const section of this.allSections())
section._styleSheetEdited(edit);return;}
if(this._userOperation||this._isEditingStyle)
return;this._resetCache();this.update();}
_focusedSectionIndex(){let index=0;for(const block of this._sectionBlocks){for(const section of block.sections){if(section.element.hasFocus())
return index;index++;}}
return-1;}
async _innerRebuildUpdate(matchedStyles){if(this._needsForceUpdate)
this._needsForceUpdate=false;else if(this._isEditingStyle||this._userOperation)
return;const focusedIndex=this._focusedSectionIndex();this._linkifier.reset();this._sectionsContainer.removeChildren();this._sectionBlocks=[];const node=this.node();if(!matchedStyles||!node){this._noMatchesElement.classList.remove('hidden');return;}
this._sectionBlocks=await this._rebuildSectionsForMatchedStyleRules((matchedStyles));let pseudoTypes=[];const keys=matchedStyles.pseudoTypes();if(keys.delete(Protocol.DOM.PseudoType.Before))
pseudoTypes.push(Protocol.DOM.PseudoType.Before);pseudoTypes=pseudoTypes.concat(keys.valuesArray().sort());for(const pseudoType of pseudoTypes){const block=Elements.SectionBlock.createPseudoTypeBlock(pseudoType);for(const style of matchedStyles.pseudoStyles(pseudoType)){const section=new Elements.StylePropertiesSection(this,matchedStyles,style);block.sections.push(section);}
this._sectionBlocks.push(block);}
for(const keyframesRule of matchedStyles.keyframes()){const block=Elements.SectionBlock.createKeyframesBlock(keyframesRule.name().text);for(const keyframe of keyframesRule.keyframes())
block.sections.push(new Elements.KeyframePropertiesSection(this,matchedStyles,keyframe.style));this._sectionBlocks.push(block);}
let index=0;for(const block of this._sectionBlocks){const titleElement=block.titleElement();if(titleElement)
this._sectionsContainer.appendChild(titleElement);for(const section of block.sections){this._sectionsContainer.appendChild(section.element);if(index===focusedIndex)
section.element.focus();index++;}}
if(focusedIndex>=index)
this._sectionBlocks[0].sections[0].element.focus();this._sectionsContainerFocusChanged();if(this._filterRegex)
this._updateFilter();else
this._noMatchesElement.classList.toggle('hidden',this._sectionBlocks.length>0);this._nodeStylesUpdatedForTest((node),true);if(this._decorator){this._decorator.perform();this._decorator=null;}}
_nodeStylesUpdatedForTest(node,rebuild){}
async _rebuildSectionsForMatchedStyleRules(matchedStyles){const blocks=[new Elements.SectionBlock(null)];let lastParentNode=null;for(const style of matchedStyles.nodeStyles()){const parentNode=matchedStyles.isInherited(style)?matchedStyles.nodeForStyle(style):null;if(parentNode&&parentNode!==lastParentNode){lastParentNode=parentNode;const block=await Elements.SectionBlock._createInheritedNodeBlock(lastParentNode);blocks.push(block);}
const section=new Elements.StylePropertiesSection(this,matchedStyles,style);blocks.peekLast().sections.push(section);}
return blocks;}
async _createNewRuleInViaInspectorStyleSheet(){const cssModel=this.cssModel();const node=this.node();if(!cssModel||!node)
return;this.setUserOperation(true);const styleSheetHeader=await cssModel.requestViaInspectorStylesheet((node));this.setUserOperation(false);await this._createNewRuleInStyleSheet(styleSheetHeader);}
async _createNewRuleInStyleSheet(styleSheetHeader){if(!styleSheetHeader)
return;const text=await styleSheetHeader.requestContent()||'';const lines=text.split('\n');const range=TextUtils.TextRange.createFromLocation(lines.length-1,lines[lines.length-1].length);this._addBlankSection(this._sectionBlocks[0].sections[0],styleSheetHeader.id,range);}
_addBlankSection(insertAfterSection,styleSheetId,ruleLocation){const node=this.node();const blankSection=new Elements.BlankStylePropertiesSection(this,insertAfterSection._matchedStyles,node?node.simpleSelector():'',styleSheetId,ruleLocation,insertAfterSection._style);this._sectionsContainer.insertBefore(blankSection.element,insertAfterSection.element.nextSibling);for(const block of this._sectionBlocks){const index=block.sections.indexOf(insertAfterSection);if(index===-1)
continue;block.sections.splice(index+1,0,blankSection);blankSection.startEditingSelector();}}
removeSection(section){for(const block of this._sectionBlocks){const index=block.sections.indexOf(section);if(index===-1)
continue;block.sections.splice(index,1);section.element.remove();}}
filterRegex(){return this._filterRegex;}
_updateFilter(){let hasAnyVisibleBlock=false;for(const block of this._sectionBlocks)
hasAnyVisibleBlock|=block.updateFilter();this._noMatchesElement.classList.toggle('hidden',hasAnyVisibleBlock);}
willHide(){this._swatchPopoverHelper.hide();super.willHide();}
allSections(){let sections=[];for(const block of this._sectionBlocks)
sections=sections.concat(block.sections);return sections;}
_clipboardCopy(event){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleCopied);}
_createStylesSidebarToolbar(){const container=this.contentElement.createChild('div','styles-sidebar-pane-toolbar-container');const hbox=container.createChild('div','hbox styles-sidebar-pane-toolbar');const filterContainerElement=hbox.createChild('div','styles-sidebar-pane-filter-box');const filterInput=Elements.StylesSidebarPane.createPropertyFilterElement(ls`Filter`,hbox,this._onFilterChanged.bind(this));UI.ARIAUtils.setAccessibleName(filterInput,Common.UIString('Filter Styles'));filterContainerElement.appendChild(filterInput);const toolbar=new UI.Toolbar('styles-pane-toolbar',hbox);toolbar.makeToggledGray();toolbar.appendItemsAtLocation('styles-sidebarpane-toolbar');const toolbarPaneContainer=container.createChild('div','styles-sidebar-toolbar-pane-container');const toolbarPaneContent=toolbarPaneContainer.createChild('div','styles-sidebar-toolbar-pane');return toolbarPaneContent;}
showToolbarPane(widget,toggle){if(this._pendingWidgetToggle)
this._pendingWidgetToggle.setToggled(false);this._pendingWidgetToggle=toggle;if(this._animatedToolbarPane)
this._pendingWidget=widget;else
this._startToolbarPaneAnimation(widget);if(widget&&toggle)
toggle.setToggled(true);}
_startToolbarPaneAnimation(widget){if(widget===this._currentToolbarPane)
return;if(widget&&this._currentToolbarPane){this._currentToolbarPane.detach();widget.show(this._toolbarPaneElement);this._currentToolbarPane=widget;this._currentToolbarPane.focus();return;}
this._animatedToolbarPane=widget;if(this._currentToolbarPane)
this._toolbarPaneElement.style.animationName='styles-element-state-pane-slideout';else if(widget)
this._toolbarPaneElement.style.animationName='styles-element-state-pane-slidein';if(widget)
widget.show(this._toolbarPaneElement);const listener=onAnimationEnd.bind(this);this._toolbarPaneElement.addEventListener('animationend',listener,false);function onAnimationEnd(){this._toolbarPaneElement.style.removeProperty('animation-name');this._toolbarPaneElement.removeEventListener('animationend',listener,false);if(this._currentToolbarPane)
this._currentToolbarPane.detach();this._currentToolbarPane=this._animatedToolbarPane;if(this._currentToolbarPane)
this._currentToolbarPane.focus();this._animatedToolbarPane=null;if(this._pendingWidget){this._startToolbarPaneAnimation(this._pendingWidget);this._pendingWidget=null;}}}};Elements.StylesSidebarPane._maxLinkLength=23;Elements.SectionBlock=class{constructor(titleElement){this._titleElement=titleElement;this.sections=[];}
static createPseudoTypeBlock(pseudoType){const separatorElement=createElement('div');separatorElement.className='sidebar-separator';separatorElement.textContent=Common.UIString('Pseudo ::%s element',pseudoType);return new Elements.SectionBlock(separatorElement);}
static createKeyframesBlock(keyframesName){const separatorElement=createElement('div');separatorElement.className='sidebar-separator';separatorElement.textContent=`@keyframes ${keyframesName}`;return new Elements.SectionBlock(separatorElement);}
static async _createInheritedNodeBlock(node){const separatorElement=createElement('div');separatorElement.className='sidebar-separator';separatorElement.createTextChild(ls`Inherited from${' '}`);const link=await Common.Linkifier.linkify(node);separatorElement.appendChild(link);return new Elements.SectionBlock(separatorElement);}
updateFilter(){let hasAnyVisibleSection=false;for(const section of this.sections)
hasAnyVisibleSection|=section._updateFilter();if(this._titleElement)
this._titleElement.classList.toggle('hidden',!hasAnyVisibleSection);return hasAnyVisibleSection;}
titleElement(){return this._titleElement;}};Elements.StylePropertiesSection=class{constructor(parentPane,matchedStyles,style){this._parentPane=parentPane;this._style=style;this._matchedStyles=matchedStyles;this.editable=!!(style.styleSheetId&&style.range);this._hoverTimer=null;this._willCauseCancelEditing=false;this._forceShowAll=false;this._originalPropertiesCount=style.leadingProperties().length;const rule=style.parentRule;this.element=createElementWithClass('div','styles-section matched-styles monospace');this.element.tabIndex=-1;UI.ARIAUtils.markAsTreeitem(this.element);this.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this.element._section=this;this._innerElement=this.element.createChild('div');this._titleElement=this._innerElement.createChild('div','styles-section-title '+(rule?'styles-selector':''));this.propertiesTreeOutline=new UI.TreeOutlineInShadow();this.propertiesTreeOutline.setFocusable(false);this.propertiesTreeOutline.registerRequiredCSS('elements/stylesSectionTree.css');this.propertiesTreeOutline.element.classList.add('style-properties','matched-styles','monospace');this.propertiesTreeOutline.section=this;this._innerElement.appendChild(this.propertiesTreeOutline.element);this._showAllButton=UI.createTextButton('',this._showAllItems.bind(this),'styles-show-all');this._innerElement.appendChild(this._showAllButton);const selectorContainer=createElement('div');this._selectorElement=createElementWithClass('span','selector');this._selectorElement.textContent=this._headerText();selectorContainer.appendChild(this._selectorElement);this._selectorElement.addEventListener('mouseenter',this._onMouseEnterSelector.bind(this),false);this._selectorElement.addEventListener('mousemove',event=>event.consume(),false);this._selectorElement.addEventListener('mouseleave',this._onMouseOutSelector.bind(this),false);const openBrace=selectorContainer.createChild('span','sidebar-pane-open-brace');openBrace.textContent=' {';selectorContainer.addEventListener('mousedown',this._handleEmptySpaceMouseDown.bind(this),false);selectorContainer.addEventListener('click',this._handleSelectorContainerClick.bind(this),false);const closeBrace=this._innerElement.createChild('div','sidebar-pane-closing-brace');closeBrace.textContent='}';this._createHoverMenuToolbar(closeBrace);this._selectorElement.addEventListener('click',this._handleSelectorClick.bind(this),false);this.element.addEventListener('mousedown',this._handleEmptySpaceMouseDown.bind(this),false);this.element.addEventListener('click',this._handleEmptySpaceClick.bind(this),false);this.element.addEventListener('mousemove',this._onMouseMove.bind(this),false);this.element.addEventListener('mouseleave',this._onMouseLeave.bind(this),false);this._selectedSinceMouseDown=false;if(rule){if(rule.isUserAgent()||rule.isInjected()){this.editable=false;}else{if(rule.styleSheetId){const header=rule.cssModel().styleSheetHeaderForId(rule.styleSheetId);this.navigable=!header.isAnonymousInlineStyleSheet();}}}
this._mediaListElement=this._titleElement.createChild('div','media-list media-matches');this._selectorRefElement=this._titleElement.createChild('div','styles-section-subtitle');this._updateMediaList();this._updateRuleOrigin();this._titleElement.appendChild(selectorContainer);this._selectorContainer=selectorContainer;if(this.navigable)
this.element.classList.add('navigable');if(!this.editable){this.element.classList.add('read-only');this.propertiesTreeOutline.element.classList.add('read-only');}
this._hoverableSelectorsMode=false;this._markSelectorMatches();this.onpopulate();}
static createRuleOriginNode(matchedStyles,linkifier,rule){if(!rule)
return createTextNode('');let ruleLocation;if(rule instanceof SDK.CSSStyleRule)
ruleLocation=rule.style.range;else if(rule instanceof SDK.CSSKeyframeRule)
ruleLocation=rule.key().range;const header=rule.styleSheetId?matchedStyles.cssModel().styleSheetHeaderForId(rule.styleSheetId):null;if(ruleLocation&&rule.styleSheetId&&header&&!header.isAnonymousInlineStyleSheet()){return Elements.StylePropertiesSection._linkifyRuleLocation(matchedStyles.cssModel(),linkifier,rule.styleSheetId,ruleLocation);}
if(rule.isUserAgent())
return createTextNode(Common.UIString('user agent stylesheet'));if(rule.isInjected())
return createTextNode(Common.UIString('injected stylesheet'));if(rule.isViaInspector())
return createTextNode(Common.UIString('via inspector'));if(header&&header.ownerNode){const link=Elements.DOMLinkifier.linkifyDeferredNodeReference(header.ownerNode);link.textContent='<style>';return link;}
return createTextNode('');}
static _linkifyRuleLocation(cssModel,linkifier,styleSheetId,ruleLocation){const styleSheetHeader=cssModel.styleSheetHeaderForId(styleSheetId);const lineNumber=styleSheetHeader.lineNumberInSource(ruleLocation.startLine);const columnNumber=styleSheetHeader.columnNumberInSource(ruleLocation.startLine,ruleLocation.startColumn);const matchingSelectorLocation=new SDK.CSSLocation(styleSheetHeader,lineNumber,columnNumber);return linkifier.linkifyCSSLocation(matchingSelectorLocation);}
_onKeyDown(event){if(UI.isEditing()||!this.editable||event.altKey||event.ctrlKey||event.metaKey)
return;switch(event.key){case'Enter':case' ':this._startEditingAtFirstPosition();event.consume(true);break;default:if(event.key.length===1)
this.addNewBlankProperty(0).startEditing();break;}}
_setSectionHovered(isHovered){this.element.classList.toggle('styles-panel-hovered',isHovered);this.propertiesTreeOutline.element.classList.toggle('styles-panel-hovered',isHovered);if(this._hoverableSelectorsMode!==isHovered){this._hoverableSelectorsMode=isHovered;this._markSelectorMatches();}}
_onMouseLeave(event){this._setSectionHovered(false);this._parentPane._setActiveProperty(null);}
_onMouseMove(event){const hasCtrlOrMeta=UI.KeyboardShortcut.eventHasCtrlOrMeta((event));this._setSectionHovered(hasCtrlOrMeta);const treeElement=this.propertiesTreeOutline.treeElementFromEvent(event);if(treeElement instanceof Elements.StylePropertyTreeElement)
this._parentPane._setActiveProperty((treeElement));else
this._parentPane._setActiveProperty(null);if(!this._selectedSinceMouseDown&&this.element.getComponentSelection().toString())
this._selectedSinceMouseDown=true;}
_createHoverMenuToolbar(container){if(!this.editable)
return;const items=[];const textShadowButton=new UI.ToolbarButton(Common.UIString('Add text-shadow'),'largeicon-text-shadow');textShadowButton.addEventListener(UI.ToolbarButton.Events.Click,this._onInsertShadowPropertyClick.bind(this,'text-shadow'));textShadowButton.element.tabIndex=-1;items.push(textShadowButton);const boxShadowButton=new UI.ToolbarButton(Common.UIString('Add box-shadow'),'largeicon-box-shadow');boxShadowButton.addEventListener(UI.ToolbarButton.Events.Click,this._onInsertShadowPropertyClick.bind(this,'box-shadow'));boxShadowButton.element.tabIndex=-1;items.push(boxShadowButton);const colorButton=new UI.ToolbarButton(Common.UIString('Add color'),'largeicon-foreground-color');colorButton.addEventListener(UI.ToolbarButton.Events.Click,this._onInsertColorPropertyClick,this);colorButton.element.tabIndex=-1;items.push(colorButton);const backgroundButton=new UI.ToolbarButton(Common.UIString('Add background-color'),'largeicon-background-color');backgroundButton.addEventListener(UI.ToolbarButton.Events.Click,this._onInsertBackgroundColorPropertyClick,this);backgroundButton.element.tabIndex=-1;items.push(backgroundButton);let newRuleButton=null;if(this._style.parentRule){newRuleButton=new UI.ToolbarButton(Common.UIString('Insert Style Rule Below'),'largeicon-add');newRuleButton.addEventListener(UI.ToolbarButton.Events.Click,this._onNewRuleClick,this);newRuleButton.element.tabIndex=-1;items.push(newRuleButton);}
const sectionToolbar=new UI.Toolbar('sidebar-pane-section-toolbar',container);for(let i=0;i<items.length;++i)
sectionToolbar.appendToolbarItem(items[i]);const menuButton=new UI.ToolbarButton('','largeicon-menu');menuButton.element.tabIndex=-1;sectionToolbar.appendToolbarItem(menuButton);setItemsVisibility(items,false);sectionToolbar.element.addEventListener('mouseenter',setItemsVisibility.bind(null,items,true));sectionToolbar.element.addEventListener('mouseleave',setItemsVisibility.bind(null,items,false));UI.ARIAUtils.markAsHidden(sectionToolbar.element);function setItemsVisibility(items,value){for(let i=0;i<items.length;++i)
items[i].setVisible(value);menuButton.setVisible(!value);}}
style(){return this._style;}
_headerText(){const node=this._matchedStyles.nodeForStyle(this._style);if(this._style.type===SDK.CSSStyleDeclaration.Type.Inline)
return this._matchedStyles.isInherited(this._style)?Common.UIString('Style Attribute'):'element.style';if(this._style.type===SDK.CSSStyleDeclaration.Type.Attributes)
return ls`${node.nodeNameInCorrectCase()}[Attributes Style]`;return this._style.parentRule.selectorText();}
_onMouseOutSelector(){if(this._hoverTimer)
clearTimeout(this._hoverTimer);SDK.OverlayModel.hideDOMNodeHighlight();}
_onMouseEnterSelector(){if(this._hoverTimer)
clearTimeout(this._hoverTimer);this._hoverTimer=setTimeout(this._highlight.bind(this),300);}
_highlight(mode='all'){SDK.OverlayModel.hideDOMNodeHighlight();const node=this._parentPane.node();if(!node)
return;const selectorList=this._style.parentRule?this._style.parentRule.selectorText():undefined;node.domModel().overlayModel().highlightInOverlay({node,selectorList},mode);}
firstSibling(){const parent=this.element.parentElement;if(!parent)
return null;let childElement=parent.firstChild;while(childElement){if(childElement._section)
return childElement._section;childElement=childElement.nextSibling;}
return null;}
lastSibling(){const parent=this.element.parentElement;if(!parent)
return null;let childElement=parent.lastChild;while(childElement){if(childElement._section)
return childElement._section;childElement=childElement.previousSibling;}
return null;}
nextSibling(){let curElement=this.element;do
curElement=curElement.nextSibling;while(curElement&&!curElement._section);return curElement?curElement._section:null;}
previousSibling(){let curElement=this.element;do
curElement=curElement.previousSibling;while(curElement&&!curElement._section);return curElement?curElement._section:null;}
_onNewRuleClick(event){event.data.consume();const rule=this._style.parentRule;const range=TextUtils.TextRange.createFromLocation(rule.style.range.endLine,rule.style.range.endColumn+1);this._parentPane._addBlankSection(this,(rule.styleSheetId),range);}
_onInsertShadowPropertyClick(propertyName,event){event.data.consume(true);const treeElement=this.addNewBlankProperty();treeElement.property.name=propertyName;treeElement.property.value='0 0 black';treeElement.updateTitle();const shadowSwatchPopoverHelper=Elements.ShadowSwatchPopoverHelper.forTreeElement(treeElement);if(shadowSwatchPopoverHelper)
shadowSwatchPopoverHelper.showPopover();}
_onInsertColorPropertyClick(event){event.data.consume(true);const treeElement=this.addNewBlankProperty();treeElement.property.name='color';treeElement.property.value='black';treeElement.updateTitle();const colorSwatch=Elements.ColorSwatchPopoverIcon.forTreeElement(treeElement);if(colorSwatch)
colorSwatch.showPopover();}
_onInsertBackgroundColorPropertyClick(event){event.data.consume(true);const treeElement=this.addNewBlankProperty();treeElement.property.name='background-color';treeElement.property.value='white';treeElement.updateTitle();const colorSwatch=Elements.ColorSwatchPopoverIcon.forTreeElement(treeElement);if(colorSwatch)
colorSwatch.showPopover();}
_styleSheetEdited(edit){const rule=this._style.parentRule;if(rule)
rule.rebase(edit);else
this._style.rebase(edit);this._updateMediaList();this._updateRuleOrigin();}
_createMediaList(mediaRules){for(let i=mediaRules.length-1;i>=0;--i){const media=mediaRules[i];if(!media.text.includes('(')&&media.text!=='print')
continue;const mediaDataElement=this._mediaListElement.createChild('div','media');const mediaContainerElement=mediaDataElement.createChild('span');const mediaTextElement=mediaContainerElement.createChild('span','media-text');switch(media.source){case SDK.CSSMedia.Source.LINKED_SHEET:case SDK.CSSMedia.Source.INLINE_SHEET:mediaTextElement.textContent='media="'+media.text+'"';break;case SDK.CSSMedia.Source.MEDIA_RULE:const decoration=mediaContainerElement.createChild('span');mediaContainerElement.insertBefore(decoration,mediaTextElement);decoration.textContent='@media ';mediaTextElement.textContent=media.text;if(media.styleSheetId){mediaDataElement.classList.add('editable-media');mediaTextElement.addEventListener('click',this._handleMediaRuleClick.bind(this,media,mediaTextElement),false);}
break;case SDK.CSSMedia.Source.IMPORT_RULE:mediaTextElement.textContent='@import '+media.text;break;}}}
_updateMediaList(){this._mediaListElement.removeChildren();if(this._style.parentRule&&this._style.parentRule instanceof SDK.CSSStyleRule)
this._createMediaList(this._style.parentRule.media);}
isPropertyInherited(propertyName){if(this._matchedStyles.isInherited(this._style)){return!SDK.cssMetadata().isPropertyInherited(propertyName);}
return false;}
nextEditableSibling(){let curSection=this;do
curSection=curSection.nextSibling();while(curSection&&!curSection.editable);if(!curSection){curSection=this.firstSibling();while(curSection&&!curSection.editable)
curSection=curSection.nextSibling();}
return(curSection&&curSection.editable)?curSection:null;}
previousEditableSibling(){let curSection=this;do
curSection=curSection.previousSibling();while(curSection&&!curSection.editable);if(!curSection){curSection=this.lastSibling();while(curSection&&!curSection.editable)
curSection=curSection.previousSibling();}
return(curSection&&curSection.editable)?curSection:null;}
refreshUpdate(editedTreeElement){this._parentPane._refreshUpdate(this,editedTreeElement);}
_updateVarFunctions(editedTreeElement){let child=this.propertiesTreeOutline.firstChild();while(child){if(child!==editedTreeElement)
child.updateTitleIfComputedValueChanged();child=child.traverseNextTreeElement(false,null,true);}}
update(full){this._selectorElement.textContent=this._headerText();this._markSelectorMatches();if(full){this.onpopulate();}else{let child=this.propertiesTreeOutline.firstChild();while(child){child.setOverloaded(this._isPropertyOverloaded(child.property));child=child.traverseNextTreeElement(false,null,true);}}}
_showAllItems(event){if(event)
event.consume();if(this._forceShowAll)
return;this._forceShowAll=true;this.onpopulate();}
onpopulate(){this._parentPane._setActiveProperty(null);this.propertiesTreeOutline.removeChildren();const style=this._style;let count=0;const properties=style.leadingProperties();const maxProperties=Elements.StylePropertiesSection.MaxProperties+properties.length-this._originalPropertiesCount;for(const property of properties){if(!this._forceShowAll&&count>=maxProperties)
break;count++;const isShorthand=!!style.longhandProperties(property.name).length;const inherited=this.isPropertyInherited(property.name);const overloaded=this._isPropertyOverloaded(property);if(style.parentRule&&style.parentRule.isUserAgent()&&inherited)
continue;const item=new Elements.StylePropertyTreeElement(this._parentPane,this._matchedStyles,property,isShorthand,inherited,overloaded,false);this.propertiesTreeOutline.appendChild(item);}
if(count<properties.length){this._showAllButton.classList.remove('hidden');this._showAllButton.textContent=ls`Show All Properties (${properties.length - count} more)`;}else{this._showAllButton.classList.add('hidden');}}
_isPropertyOverloaded(property){return this._matchedStyles.propertyState(property)===SDK.CSSMatchedStyles.PropertyState.Overloaded;}
_updateFilter(){let hasMatchingChild=false;this._showAllItems();for(const child of this.propertiesTreeOutline.rootElement().children())
hasMatchingChild|=child._updateFilter();const regex=this._parentPane.filterRegex();const hideRule=!hasMatchingChild&&!!regex&&!regex.test(this.element.deepTextContent());this.element.classList.toggle('hidden',hideRule);if(!hideRule&&this._style.parentRule)
this._markSelectorHighlights();return!hideRule;}
_markSelectorMatches(){const rule=this._style.parentRule;if(!rule)
return;this._mediaListElement.classList.toggle('media-matches',this._matchedStyles.mediaMatches(this._style));const selectorTexts=rule.selectors.map(selector=>selector.text);const matchingSelectorIndexes=this._matchedStyles.matchingSelectors((rule));const matchingSelectors=(new Array(selectorTexts.length).fill(false));for(const matchingIndex of matchingSelectorIndexes)
matchingSelectors[matchingIndex]=true;if(this._parentPane._isEditingStyle)
return;const fragment=this._hoverableSelectorsMode?this._renderHoverableSelectors(selectorTexts,matchingSelectors):this._renderSimplifiedSelectors(selectorTexts,matchingSelectors);this._selectorElement.removeChildren();this._selectorElement.appendChild(fragment);this._markSelectorHighlights();}
_renderHoverableSelectors(selectors,matchingSelectors){const fragment=createDocumentFragment();for(let i=0;i<selectors.length;++i){if(i)
fragment.createTextChild(', ');fragment.appendChild(this._createSelectorElement(selectors[i],matchingSelectors[i],i));}
return fragment;}
_createSelectorElement(text,isMatching,navigationIndex){const element=createElementWithClass('span','simple-selector');element.classList.toggle('selector-matches',isMatching);if(typeof navigationIndex==='number')
element._selectorIndex=navigationIndex;element.textContent=text;return element;}
_renderSimplifiedSelectors(selectors,matchingSelectors){const fragment=createDocumentFragment();let currentMatching=false;let text='';for(let i=0;i<selectors.length;++i){if(currentMatching!==matchingSelectors[i]&&text){fragment.appendChild(this._createSelectorElement(text,currentMatching));text='';}
currentMatching=matchingSelectors[i];text+=selectors[i]+(i===selectors.length-1?'':', ');}
if(text)
fragment.appendChild(this._createSelectorElement(text,currentMatching));return fragment;}
_markSelectorHighlights(){const selectors=this._selectorElement.getElementsByClassName('simple-selector');const regex=this._parentPane.filterRegex();for(let i=0;i<selectors.length;++i){const selectorMatchesFilter=!!regex&&regex.test(selectors[i].textContent);selectors[i].classList.toggle('filter-match',selectorMatchesFilter);}}
_checkWillCancelEditing(){const willCauseCancelEditing=this._willCauseCancelEditing;this._willCauseCancelEditing=false;return willCauseCancelEditing;}
_handleSelectorContainerClick(event){if(this._checkWillCancelEditing()||!this.editable)
return;if(event.target===this._selectorContainer){this.addNewBlankProperty(0).startEditing();event.consume(true);}}
addNewBlankProperty(index=this.propertiesTreeOutline.rootElement().childCount()){const property=this._style.newBlankProperty(index);const item=new Elements.StylePropertyTreeElement(this._parentPane,this._matchedStyles,property,false,false,false,true);this.propertiesTreeOutline.insertChild(item,property.index);return item;}
_handleEmptySpaceMouseDown(){this._willCauseCancelEditing=this._parentPane._isEditingStyle;this._selectedSinceMouseDown=false;}
_handleEmptySpaceClick(event){if(!this.editable||this.element.hasSelection()||this._checkWillCancelEditing()||this._selectedSinceMouseDown)
return;if(event.target.classList.contains('header')||this.element.classList.contains('read-only')||event.target.enclosingNodeOrSelfWithClass('media')){event.consume();return;}
const deepTarget=event.deepElementFromPoint();if(deepTarget.treeElement)
this.addNewBlankProperty(deepTarget.treeElement.property.index+1).startEditing();else
this.addNewBlankProperty().startEditing();event.consume(true);}
_handleMediaRuleClick(media,element,event){if(UI.isBeingEdited(element))
return;if(UI.KeyboardShortcut.eventHasCtrlOrMeta((event))&&this.navigable){const location=media.rawLocation();if(!location){event.consume(true);return;}
const uiLocation=Bindings.cssWorkspaceBinding.rawLocationToUILocation(location);if(uiLocation)
Common.Revealer.reveal(uiLocation);event.consume(true);return;}
if(!this.editable)
return;const config=new UI.InplaceEditor.Config(this._editingMediaCommitted.bind(this,media),this._editingMediaCancelled.bind(this,element),undefined,this._editingMediaBlurHandler.bind(this));UI.InplaceEditor.startEditing(element,config);element.getComponentSelection().selectAllChildren(element);this._parentPane.setEditingStyle(true);const parentMediaElement=element.enclosingNodeOrSelfWithClass('media');parentMediaElement.classList.add('editing-media');event.consume(true);}
_editingMediaFinished(element){this._parentPane.setEditingStyle(false);const parentMediaElement=element.enclosingNodeOrSelfWithClass('media');parentMediaElement.classList.remove('editing-media');}
_editingMediaCancelled(element){this._editingMediaFinished(element);this._markSelectorMatches();element.getComponentSelection().collapse(element,0);}
_editingMediaBlurHandler(editor,blurEvent){return true;}
_editingMediaCommitted(media,element,newContent,oldContent,context,moveDirection){this._parentPane.setEditingStyle(false);this._editingMediaFinished(element);if(newContent)
newContent=newContent.trim();function userCallback(success){if(success){this._matchedStyles.resetActiveProperties();this._parentPane._refreshUpdate(this);}
this._parentPane.setUserOperation(false);this._editingMediaTextCommittedForTest();}
this._parentPane.setUserOperation(true);this._parentPane.cssModel().setMediaText(media.styleSheetId,media.range,newContent).then(userCallback.bind(this));}
_editingMediaTextCommittedForTest(){}
_handleSelectorClick(event){if(UI.KeyboardShortcut.eventHasCtrlOrMeta((event))&&this.navigable&&event.target.classList.contains('simple-selector')){this._navigateToSelectorSource(event.target._selectorIndex,true);event.consume(true);return;}
if(this.element.hasSelection())
return;this._startEditingAtFirstPosition();event.consume(true);}
_navigateToSelectorSource(index,focus){const cssModel=this._parentPane.cssModel();const rule=this._style.parentRule;const header=cssModel.styleSheetHeaderForId((rule.styleSheetId));if(!header)
return;const rawLocation=new SDK.CSSLocation(header,rule.lineNumberInSource(index),rule.columnNumberInSource(index));const uiLocation=Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation);if(uiLocation)
Common.Revealer.reveal(uiLocation,!focus);}
_startEditingAtFirstPosition(){if(!this.editable)
return;if(!this._style.parentRule){this.moveEditorFromSelector('forward');return;}
this.startEditingSelector();}
startEditingSelector(){const element=this._selectorElement;if(UI.isBeingEdited(element))
return;element.scrollIntoViewIfNeeded(false);element.textContent=element.textContent.replace(/\s+/g,' ').trim();const config=new UI.InplaceEditor.Config(this.editingSelectorCommitted.bind(this),this.editingSelectorCancelled.bind(this));UI.InplaceEditor.startEditing(this._selectorElement,config);element.getComponentSelection().selectAllChildren(element);this._parentPane.setEditingStyle(true);if(element.classList.contains('simple-selector'))
this._navigateToSelectorSource(0,false);}
moveEditorFromSelector(moveDirection){this._markSelectorMatches();if(!moveDirection)
return;if(moveDirection==='forward'){let firstChild=this.propertiesTreeOutline.firstChild();while(firstChild&&firstChild.inherited())
firstChild=firstChild.nextSibling;if(!firstChild)
this.addNewBlankProperty().startEditing();else
firstChild.startEditing(firstChild.nameElement);}else{const previousSection=this.previousEditableSibling();if(!previousSection)
return;previousSection.addNewBlankProperty().startEditing();}}
editingSelectorCommitted(element,newContent,oldContent,context,moveDirection){this._editingSelectorEnded();if(newContent)
newContent=newContent.trim();if(newContent===oldContent){this._selectorElement.textContent=newContent;this.moveEditorFromSelector(moveDirection);return;}
const rule=this._style.parentRule;if(!rule)
return;function headerTextCommitted(){this._parentPane.setUserOperation(false);this.moveEditorFromSelector(moveDirection);this._editingSelectorCommittedForTest();}
this._parentPane.setUserOperation(true);this._setHeaderText(rule,newContent).then(headerTextCommitted.bind(this));}
_setHeaderText(rule,newContent){function onSelectorsUpdated(rule,success){if(!success)
return Promise.resolve();return this._matchedStyles.recomputeMatchingSelectors(rule).then(updateSourceRanges.bind(this,rule));}
function updateSourceRanges(rule){const doesAffectSelectedNode=this._matchedStyles.matchingSelectors(rule).length>0;this.propertiesTreeOutline.element.classList.toggle('no-affect',!doesAffectSelectedNode);this._matchedStyles.resetActiveProperties();this._parentPane._refreshUpdate(this);}
console.assert(rule instanceof SDK.CSSStyleRule);const oldSelectorRange=rule.selectorRange();if(!oldSelectorRange)
return Promise.resolve();return rule.setSelectorText(newContent).then(onSelectorsUpdated.bind(this,(rule),oldSelectorRange));}
_editingSelectorCommittedForTest(){}
_updateRuleOrigin(){this._selectorRefElement.removeChildren();this._selectorRefElement.appendChild(Elements.StylePropertiesSection.createRuleOriginNode(this._matchedStyles,this._parentPane._linkifier,this._style.parentRule));}
_editingSelectorEnded(){this._parentPane.setEditingStyle(false);}
editingSelectorCancelled(){this._editingSelectorEnded();this._markSelectorMatches();}};Elements.BlankStylePropertiesSection=class extends Elements.StylePropertiesSection{constructor(stylesPane,matchedStyles,defaultSelectorText,styleSheetId,ruleLocation,insertAfterStyle){const cssModel=(stylesPane.cssModel());const rule=SDK.CSSStyleRule.createDummyRule(cssModel,defaultSelectorText);super(stylesPane,matchedStyles,rule.style);this._normal=false;this._ruleLocation=ruleLocation;this._styleSheetId=styleSheetId;this._selectorRefElement.removeChildren();this._selectorRefElement.appendChild(Elements.StylePropertiesSection._linkifyRuleLocation(cssModel,this._parentPane._linkifier,styleSheetId,this._actualRuleLocation()));if(insertAfterStyle&&insertAfterStyle.parentRule)
this._createMediaList(insertAfterStyle.parentRule.media);this.element.classList.add('blank-section');}
_actualRuleLocation(){const prefix=this._rulePrefix();const lines=prefix.split('\n');const editRange=new TextUtils.TextRange(0,0,lines.length-1,lines.peekLast().length);return this._ruleLocation.rebaseAfterTextEdit(TextUtils.TextRange.createFromLocation(0,0),editRange);}
_rulePrefix(){return this._ruleLocation.startLine===0&&this._ruleLocation.startColumn===0?'':'\n\n';}
get isBlank(){return!this._normal;}
editingSelectorCommitted(element,newContent,oldContent,context,moveDirection){if(!this.isBlank){super.editingSelectorCommitted(element,newContent,oldContent,context,moveDirection);return;}
function onRuleAdded(newRule){if(!newRule){this.editingSelectorCancelled();this._editingSelectorCommittedForTest();return Promise.resolve();}
return this._matchedStyles.addNewRule(newRule,this._matchedStyles.node()).then(onAddedToCascade.bind(this,newRule));}
function onAddedToCascade(newRule){const doesSelectorAffectSelectedNode=this._matchedStyles.matchingSelectors(newRule).length>0;this._makeNormal(newRule);if(!doesSelectorAffectSelectedNode)
this.propertiesTreeOutline.element.classList.add('no-affect');this._updateRuleOrigin();this._parentPane.setUserOperation(false);this._editingSelectorEnded();if(this.element.parentElement)
this.moveEditorFromSelector(moveDirection);this._markSelectorMatches();this._editingSelectorCommittedForTest();}
if(newContent)
newContent=newContent.trim();this._parentPane.setUserOperation(true);const cssModel=this._parentPane.cssModel();const ruleText=this._rulePrefix()+newContent+' {}';cssModel.addRule(this._styleSheetId,ruleText,this._ruleLocation).then(onRuleAdded.bind(this));}
editingSelectorCancelled(){this._parentPane.setUserOperation(false);if(!this.isBlank){super.editingSelectorCancelled();return;}
this._editingSelectorEnded();this._parentPane.removeSection(this);}
_makeNormal(newRule){this.element.classList.remove('blank-section');this._style=newRule.style;this._normal=true;}};Elements.StylePropertiesSection.MaxProperties=50;Elements.KeyframePropertiesSection=class extends Elements.StylePropertiesSection{constructor(stylesPane,matchedStyles,style){super(stylesPane,matchedStyles,style);this._selectorElement.className='keyframe-key';}
_headerText(){return this._style.parentRule.key().text;}
_setHeaderText(rule,newContent){function updateSourceRanges(success){if(!success)
return;this._parentPane._refreshUpdate(this);}
console.assert(rule instanceof SDK.CSSKeyframeRule);const oldRange=rule.key().range;if(!oldRange)
return Promise.resolve();return rule.setKeyText(newContent).then(updateSourceRanges.bind(this));}
isPropertyInherited(propertyName){return false;}
_isPropertyOverloaded(property){return false;}
_markSelectorHighlights(){}
_markSelectorMatches(){this._selectorElement.textContent=this._style.parentRule.key().text;}
_highlight(){}};Elements.StylesSidebarPane.CSSPropertyPrompt=class extends UI.TextPrompt{constructor(treeElement,isEditingName){super();this.initialize(this._buildPropertyCompletions.bind(this),UI.StyleValueDelimiters);this._isColorAware=SDK.cssMetadata().isColorAwareProperty(treeElement.property.name);this._cssCompletions=[];if(isEditingName){this._cssCompletions=SDK.cssMetadata().allProperties();if(!treeElement.node().isSVGNode())
this._cssCompletions=this._cssCompletions.filter(property=>!SDK.cssMetadata().isSVGProperty(property));}else{this._cssCompletions=SDK.cssMetadata().propertyValues(treeElement.nameElement.textContent);}
this._treeElement=treeElement;this._isEditingName=isEditingName;this._cssVariables=treeElement.matchedStyles().availableCSSVariables(treeElement.property.ownerStyle);if(this._cssVariables.length<1000)
this._cssVariables.sort(String.naturalOrderComparator);else
this._cssVariables.sort();if(!isEditingName){this.disableDefaultSuggestionForEmptyInput();if(treeElement&&treeElement.valueElement){const cssValueText=treeElement.valueElement.textContent;const cmdOrCtrl=Host.isMac()?'Cmd':'Ctrl';if(cssValueText.match(/#[\da-f]{3,6}$/i)){this.setTitle(ls`Increment/decrement with mousewheel or up/down keys. ${cmdOrCtrl}: R ±1, Shift: G ±1, Alt: B ±1`);}else if(cssValueText.match(/\d+/)){this.setTitle(ls`Increment/decrement with mousewheel or up/down keys. ${cmdOrCtrl}: ±100, Shift: ±10, Alt: ±0.1`);}}}}
onKeyDown(event){switch(event.key){case'ArrowUp':case'ArrowDown':case'PageUp':case'PageDown':if(!this.isSuggestBoxVisible()&&this._handleNameOrValueUpDown(event)){event.preventDefault();return;}
break;case'Enter':this.tabKeyPressed();event.preventDefault();return;}
super.onKeyDown(event);}
onMouseWheel(event){if(this._handleNameOrValueUpDown(event)){event.consume(true);return;}
super.onMouseWheel(event);}
tabKeyPressed(){this.acceptAutoComplete();return false;}
_handleNameOrValueUpDown(event){function finishHandler(originalValue,replacementString){this._treeElement.applyStyleText(this._treeElement.nameElement.textContent+': '+this._treeElement.valueElement.textContent,false);}
function customNumberHandler(prefix,number,suffix){if(number!==0&&!suffix.length&&SDK.cssMetadata().isLengthProperty(this._treeElement.property.name))
suffix='px';return prefix+number+suffix;}
if(!this._isEditingName&&this._treeElement.valueElement&&UI.handleElementValueModifications(event,this._treeElement.valueElement,finishHandler.bind(this),this._isValueSuggestion.bind(this),customNumberHandler.bind(this)))
return true;return false;}
_isValueSuggestion(word){if(!word)
return false;word=word.toLowerCase();return this._cssCompletions.indexOf(word)!==-1||word.startsWith('--');}
_buildPropertyCompletions(expression,query,force){const lowerQuery=query.toLowerCase();const editingVariable=!this._isEditingName&&expression.trim().endsWith('var(');if(!query&&!force&&!editingVariable&&(this._isEditingName||expression))
return Promise.resolve([]);const prefixResults=[];const anywhereResults=[];if(!editingVariable)
this._cssCompletions.forEach(completion=>filterCompletions.call(this,completion,false));if(this._isEditingName){const nameValuePresets=SDK.cssMetadata().nameValuePresets(this._treeElement.node().isSVGNode());nameValuePresets.forEach(preset=>filterCompletions.call(this,preset,false,true));}
if(this._isEditingName||editingVariable)
this._cssVariables.forEach(variable=>filterCompletions.call(this,variable,true));const results=prefixResults.concat(anywhereResults);if(!this._isEditingName&&!results.length&&query.length>1&&'!important'.startsWith(lowerQuery))
results.push({text:'!important'});const userEnteredText=query.replace('-','');if(userEnteredText&&(userEnteredText===userEnteredText.toUpperCase())){for(let i=0;i<results.length;++i){if(!results[i].text.startsWith('--'))
results[i].text=results[i].text.toUpperCase();}}
results.forEach(result=>{if(editingVariable){result.title=result.text;result.text+=')';return;}
const valuePreset=SDK.cssMetadata().getValuePreset(this._treeElement.name,result.text);if(!this._isEditingName&&valuePreset){result.title=result.text;result.text=valuePreset.text;result.selectionRange={startColumn:valuePreset.startColumn,endColumn:valuePreset.endColumn};}});if(this._isColorAware&&!this._isEditingName){results.stableSort((a,b)=>{if(!!a.subtitleRenderer===!!b.subtitleRenderer)
return 0;return a.subtitleRenderer?-1:1;});}
return Promise.resolve(results);function filterCompletions(completion,variable,nameValue){const index=completion.toLowerCase().indexOf(lowerQuery);const result={text:completion};if(variable){const computedValue=this._treeElement.matchedStyles().computeCSSVariable(this._treeElement.property.ownerStyle,completion);if(computedValue){const color=Common.Color.parse(computedValue);if(color)
result.subtitleRenderer=swatchRenderer.bind(null,color);}}
if(nameValue)
result.hideGhostText=true;if(index===0){result.priority=this._isEditingName?SDK.cssMetadata().propertyUsageWeight(completion):1;prefixResults.push(result);}else if(index>-1){anywhereResults.push(result);}}
function swatchRenderer(color){const swatch=InlineEditor.ColorSwatch.create();swatch.hideText(true);swatch.setColor(color);swatch.style.pointerEvents='none';return swatch;}}};Elements.StylesSidebarPropertyRenderer=class{constructor(rule,node,name,value){this._rule=rule;this._node=node;this._propertyName=name;this._propertyValue=value;this._colorHandler=null;this._bezierHandler=null;this._shadowHandler=null;this._varHandler=createTextNode;}
setColorHandler(handler){this._colorHandler=handler;}
setBezierHandler(handler){this._bezierHandler=handler;}
setShadowHandler(handler){this._shadowHandler=handler;}
setVarHandler(handler){this._varHandler=handler;}
renderName(){const nameElement=createElement('span');nameElement.className='webkit-css-property';nameElement.textContent=this._propertyName;nameElement.normalize();return nameElement;}
renderValue(){const valueElement=createElement('span');valueElement.className='value';if(!this._propertyValue)
return valueElement;if(this._shadowHandler&&(this._propertyName==='box-shadow'||this._propertyName==='text-shadow'||this._propertyName==='-webkit-box-shadow')&&!SDK.CSSMetadata.VariableRegex.test(this._propertyValue)){valueElement.appendChild(this._shadowHandler(this._propertyValue,this._propertyName));valueElement.normalize();return valueElement;}
const regexes=[SDK.CSSMetadata.VariableRegex,SDK.CSSMetadata.URLRegex];const processors=[this._varHandler,this._processURL.bind(this)];if(this._bezierHandler&&SDK.cssMetadata().isBezierAwareProperty(this._propertyName)){regexes.push(UI.Geometry.CubicBezier.Regex);processors.push(this._bezierHandler);}
if(this._colorHandler&&SDK.cssMetadata().isColorAwareProperty(this._propertyName)){regexes.push(Common.Color.Regex);processors.push(this._colorHandler);}
const results=TextUtils.TextUtils.splitStringByRegexes(this._propertyValue,regexes);for(let i=0;i<results.length;i++){const result=results[i];const processor=result.regexIndex===-1?createTextNode:processors[result.regexIndex];valueElement.appendChild(processor(result.value));}
valueElement.normalize();return valueElement;}
_processURL(text){let url=text.substring(4,text.length-1).trim();const isQuoted=/^'.*'$/.test(url)||/^".*"$/.test(url);if(isQuoted)
url=url.substring(1,url.length-1);const container=createDocumentFragment();container.createTextChild('url(');let hrefUrl=null;if(this._rule&&this._rule.resourceURL())
hrefUrl=Common.ParsedURL.completeURL(this._rule.resourceURL(),url);else if(this._node)
hrefUrl=this._node.resolveURL(url);container.appendChild(Components.Linkifier.linkifyURL(hrefUrl||url,{text:url,preventClick:true}));container.createTextChild(')');return container;}};Elements.StylesSidebarPane.ButtonProvider=class{constructor(){this._button=new UI.ToolbarButton(Common.UIString('New Style Rule'),'largeicon-add');this._button.addEventListener(UI.ToolbarButton.Events.Click,this._clicked,this);const longclickTriangle=UI.Icon.create('largeicon-longclick-triangle','long-click-glyph');this._button.element.appendChild(longclickTriangle);new UI.LongClickController(this._button.element,this._longClicked.bind(this));UI.context.addFlavorChangeListener(SDK.DOMNode,onNodeChanged.bind(this));onNodeChanged.call(this);function onNodeChanged(){let node=UI.context.flavor(SDK.DOMNode);node=node?node.enclosingElementOrSelf():null;this._button.setEnabled(!!node);}}
_clicked(event){Elements.StylesSidebarPane._instance._createNewRuleInViaInspectorStyleSheet();}
_longClicked(e){Elements.StylesSidebarPane._instance._onAddButtonLongClick(e);}
item(){return this._button;}};;Elements.StylePropertyTreeElement=class extends UI.TreeElement{constructor(stylesPane,matchedStyles,property,isShorthand,inherited,overloaded,newProperty){super('',isShorthand);this._style=property.ownerStyle;this._matchedStyles=matchedStyles;this.property=property;this._inherited=inherited;this._overloaded=overloaded;this.selectable=false;this._parentPane=stylesPane;this.isShorthand=isShorthand;this._applyStyleThrottler=new Common.Throttler(0);this._newProperty=newProperty;if(this._newProperty)
this.listItemElement.textContent='';this._expandedDueToFilter=false;this.valueElement=null;this.nameElement=null;this._expandElement=null;this._originalPropertyText='';this._hasBeenEditedIncrementally=false;this._prompt=null;this._lastComputedValue=null;this._contextForTest;}
matchedStyles(){return this._matchedStyles;}
_editable(){return!!(this._style.styleSheetId&&this._style.range);}
inherited(){return this._inherited;}
overloaded(){return this._overloaded;}
setOverloaded(x){if(x===this._overloaded)
return;this._overloaded=x;this._updateState();}
get name(){return this.property.name;}
get value(){return this.property.value;}
_updateFilter(){const regex=this._parentPane.filterRegex();const matches=!!regex&&(regex.test(this.property.name)||regex.test(this.property.value));this.listItemElement.classList.toggle('filter-match',matches);this.onpopulate();let hasMatchingChildren=false;for(let i=0;i<this.childCount();++i)
hasMatchingChildren|=this.childAt(i)._updateFilter();if(!regex){if(this._expandedDueToFilter)
this.collapse();this._expandedDueToFilter=false;}else if(hasMatchingChildren&&!this.expanded){this.expand();this._expandedDueToFilter=true;}else if(!hasMatchingChildren&&this.expanded&&this._expandedDueToFilter){this.collapse();this._expandedDueToFilter=false;}
return matches;}
_processColor(text){const color=Common.Color.parse(text);if(!color)
return createTextNode(text);if(!this._editable()){const swatch=InlineEditor.ColorSwatch.create();swatch.setColor(color);return swatch;}
const swatch=InlineEditor.ColorSwatch.create();swatch.setColor(color);swatch.setFormat(Common.Color.detectColorFormat(swatch.color()));this._addColorContrastInfo(swatch);return swatch;}
_processVar(text){const computedValue=this._matchedStyles.computeValue(this._style,text);if(!computedValue)
return createTextNode(text);const color=Common.Color.parse(computedValue);if(!color){const node=createElement('span');node.textContent=text;node.title=computedValue;return node;}
if(!this._editable()){const swatch=InlineEditor.ColorSwatch.create();swatch.setText(text,computedValue);swatch.setColor(color);return swatch;}
const swatch=InlineEditor.ColorSwatch.create();swatch.setColor(color);swatch.setFormat(Common.Color.detectColorFormat(swatch.color()));swatch.setText(text,computedValue);this._addColorContrastInfo(swatch);return swatch;}
async _addColorContrastInfo(swatch){const swatchPopoverHelper=this._parentPane.swatchPopoverHelper();const swatchIcon=new Elements.ColorSwatchPopoverIcon(this,swatchPopoverHelper,swatch);if(this.property.name!=='color'||!this._parentPane.cssModel()||!this.node())
return;const cssModel=this._parentPane.cssModel();const contrastInfo=new ColorPicker.ContrastInfo(await cssModel.backgroundColorsPromise(this.node().id));swatchIcon.setContrastInfo(contrastInfo);}
renderedPropertyText(){return this.nameElement.textContent+': '+this.valueElement.textContent;}
_processBezier(text){if(!this._editable()||!UI.Geometry.CubicBezier.parse(text))
return createTextNode(text);const swatchPopoverHelper=this._parentPane.swatchPopoverHelper();const swatch=InlineEditor.BezierSwatch.create();swatch.setBezierText(text);new Elements.BezierPopoverIcon(this,swatchPopoverHelper,swatch);return swatch;}
_processShadow(propertyValue,propertyName){if(!this._editable())
return createTextNode(propertyValue);let shadows;if(propertyName==='text-shadow')
shadows=InlineEditor.CSSShadowModel.parseTextShadow(propertyValue);else
shadows=InlineEditor.CSSShadowModel.parseBoxShadow(propertyValue);if(!shadows.length)
return createTextNode(propertyValue);const container=createDocumentFragment();const swatchPopoverHelper=this._parentPane.swatchPopoverHelper();for(let i=0;i<shadows.length;i++){if(i!==0)
container.appendChild(createTextNode(', '));const cssShadowSwatch=InlineEditor.CSSShadowSwatch.create();cssShadowSwatch.setCSSShadow(shadows[i]);new Elements.ShadowSwatchPopoverHelper(this,swatchPopoverHelper,cssShadowSwatch);const colorSwatch=cssShadowSwatch.colorSwatch();if(colorSwatch)
new Elements.ColorSwatchPopoverIcon(this,swatchPopoverHelper,colorSwatch);container.appendChild(cssShadowSwatch);}
return container;}
_updateState(){if(!this.listItemElement)
return;if(this._style.isPropertyImplicit(this.name))
this.listItemElement.classList.add('implicit');else
this.listItemElement.classList.remove('implicit');const hasIgnorableError=!this.property.parsedOk&&Elements.StylesSidebarPane.ignoreErrorsForProperty(this.property);if(hasIgnorableError)
this.listItemElement.classList.add('has-ignorable-error');else
this.listItemElement.classList.remove('has-ignorable-error');if(this.inherited())
this.listItemElement.classList.add('inherited');else
this.listItemElement.classList.remove('inherited');if(this.overloaded())
this.listItemElement.classList.add('overloaded');else
this.listItemElement.classList.remove('overloaded');if(this.property.disabled)
this.listItemElement.classList.add('disabled');else
this.listItemElement.classList.remove('disabled');}
node(){return this._parentPane.node();}
parentPane(){return this._parentPane;}
section(){return this.treeOutline&&this.treeOutline.section;}
_updatePane(){const section=this.section();if(section)
section.refreshUpdate(this);}
_toggleEnabled(event){const disabled=!event.target.checked;const oldStyleRange=this._style.range;if(!oldStyleRange)
return;function callback(success){this._parentPane.setUserOperation(false);if(!success)
return;this._matchedStyles.resetActiveProperties();this._updatePane();this.styleTextAppliedForTest();}
event.consume();this._parentPane.setUserOperation(true);this.property.setDisabled(disabled).then(callback.bind(this));}
onpopulate(){if(this.childCount()||!this.isShorthand)
return;const longhandProperties=this._style.longhandProperties(this.name);for(let i=0;i<longhandProperties.length;++i){const name=longhandProperties[i].name;let inherited=false;let overloaded=false;const section=this.section();if(section){inherited=section.isPropertyInherited(name);overloaded=this._matchedStyles.propertyState(longhandProperties[i])===SDK.CSSMatchedStyles.PropertyState.Overloaded;}
const item=new Elements.StylePropertyTreeElement(this._parentPane,this._matchedStyles,longhandProperties[i],false,inherited,overloaded,false);this.appendChild(item);}}
onattach(){this.updateTitle();this.listItemElement.addEventListener('mousedown',event=>{if(event.which===1)
this._parentPane[Elements.StylePropertyTreeElement.ActiveSymbol]=this;},false);this.listItemElement.addEventListener('mouseup',this._mouseUp.bind(this));this.listItemElement.addEventListener('click',event=>{if(!event.target.hasSelection()&&event.target!==this.listItemElement)
event.consume(true);});}
onexpand(){this._updateExpandElement();}
oncollapse(){this._updateExpandElement();}
_updateExpandElement(){if(!this._expandElement)
return;if(this.expanded)
this._expandElement.setIconType('smallicon-triangle-down');else
this._expandElement.setIconType('smallicon-triangle-right');}
updateTitleIfComputedValueChanged(){const computedValue=this._matchedStyles.computeValue(this.property.ownerStyle,this.property.value);if(computedValue===this._lastComputedValue)
return;this._lastComputedValue=computedValue;this._innerUpdateTitle();}
updateTitle(){this._lastComputedValue=this._matchedStyles.computeValue(this.property.ownerStyle,this.property.value);this._innerUpdateTitle();}
_innerUpdateTitle(){this._updateState();if(this.isExpandable())
this._expandElement=UI.Icon.create('smallicon-triangle-right','expand-icon');else
this._expandElement=null;const propertyRenderer=new Elements.StylesSidebarPropertyRenderer(this._style.parentRule,this.node(),this.name,this.value);if(this.property.parsedOk){propertyRenderer.setVarHandler(this._processVar.bind(this));propertyRenderer.setColorHandler(this._processColor.bind(this));propertyRenderer.setBezierHandler(this._processBezier.bind(this));propertyRenderer.setShadowHandler(this._processShadow.bind(this));}
this.listItemElement.removeChildren();this.nameElement=propertyRenderer.renderName();if(this.property.name.startsWith('--'))
this.nameElement.title=this._matchedStyles.computeCSSVariable(this._style,this.property.name)||'';this.valueElement=propertyRenderer.renderValue();if(!this.treeOutline)
return;const indent=Common.moduleSetting('textEditorIndent').get();this.listItemElement.createChild('span','styles-clipboard-only').createTextChild(indent+(this.property.disabled?'/* ':''));this.listItemElement.appendChild(this.nameElement);this.listItemElement.createTextChild(': ');if(this._expandElement)
this.listItemElement.appendChild(this._expandElement);this.listItemElement.appendChild(this.valueElement);this.listItemElement.createTextChild(';');if(this.property.disabled)
this.listItemElement.createChild('span','styles-clipboard-only').createTextChild(' */');if(!this.property.parsedOk){this.listItemElement.classList.add('not-parsed-ok');this.listItemElement.insertBefore(Elements.StylesSidebarPane.createExclamationMark(this.property),this.listItemElement.firstChild);}
if(!this.property.activeInStyle())
this.listItemElement.classList.add('inactive');this._updateFilter();if(this.property.parsedOk&&this.section()&&this.parent.root){const enabledCheckboxElement=createElement('input');enabledCheckboxElement.className='enabled-button';enabledCheckboxElement.type='checkbox';enabledCheckboxElement.checked=!this.property.disabled;enabledCheckboxElement.addEventListener('mousedown',event=>event.consume(),false);enabledCheckboxElement.addEventListener('click',this._toggleEnabled.bind(this),false);this.listItemElement.insertBefore(enabledCheckboxElement,this.listItemElement.firstChild);}}
_mouseUp(event){const activeTreeElement=this._parentPane[Elements.StylePropertyTreeElement.ActiveSymbol];this._parentPane[Elements.StylePropertyTreeElement.ActiveSymbol]=null;if(activeTreeElement!==this)
return;if(this.listItemElement.hasSelection())
return;if(UI.isBeingEdited((event.target)))
return;event.consume(true);if(event.target===this.listItemElement)
return;if(UI.KeyboardShortcut.eventHasCtrlOrMeta((event))&&this.section().navigable){this._navigateToSource((event.target));return;}
this.startEditing((event.target));}
_navigateToSource(element,omitFocus){if(!this.section().navigable)
return;const propertyNameClicked=element===this.nameElement;const uiLocation=Bindings.cssWorkspaceBinding.propertyUILocation(this.property,propertyNameClicked);if(uiLocation)
Common.Revealer.reveal(uiLocation,omitFocus);}
startEditing(selectElement){if(this.parent.isShorthand)
return;if(this._expandElement&&selectElement===this._expandElement)
return;const section=this.section();if(section&&!section.editable)
return;if(selectElement){selectElement=selectElement.enclosingNodeOrSelfWithClass('webkit-css-property')||selectElement.enclosingNodeOrSelfWithClass('value');}
if(!selectElement)
selectElement=this.nameElement;if(UI.isBeingEdited(selectElement))
return;const isEditingName=selectElement===this.nameElement;if(!isEditingName)
this.valueElement.textContent=restoreURLs(this.valueElement.textContent,this.value);function restoreURLs(fieldValue,modelValue){const urlRegex=/\b(url\([^)]*\))/g;const splitFieldValue=fieldValue.split(urlRegex);if(splitFieldValue.length===1)
return fieldValue;const modelUrlRegex=new RegExp(urlRegex);for(let i=1;i<splitFieldValue.length;i+=2){const match=modelUrlRegex.exec(modelValue);if(match)
splitFieldValue[i]=match[0];}
return splitFieldValue.join('');}
const context={expanded:this.expanded,hasChildren:this.isExpandable(),isEditingName:isEditingName,originalProperty:this.property,previousContent:selectElement.textContent};this._contextForTest=context;this.setExpandable(false);if(selectElement.parentElement)
selectElement.parentElement.classList.add('child-editing');selectElement.textContent=selectElement.textContent;function pasteHandler(context,event){const data=event.clipboardData.getData('Text');if(!data)
return;const colonIdx=data.indexOf(':');if(colonIdx<0)
return;const name=data.substring(0,colonIdx).trim();const value=data.substring(colonIdx+1).trim();event.preventDefault();if(!('originalName'in context)){context.originalName=this.nameElement.textContent;context.originalValue=this.valueElement.textContent;}
this.property.name=name;this.property.value=value;this.nameElement.textContent=name;this.valueElement.textContent=value;this.nameElement.normalize();this.valueElement.normalize();this._editingCommitted(event.target.textContent,context,'forward');}
function blurListener(context,event){let text=event.target.textContent;if(!context.isEditingName)
text=this.value||text;this._editingCommitted(text,context,'');}
this._originalPropertyText=this.property.propertyText;this._parentPane.setEditingStyle(true,this);if(selectElement.parentElement)
selectElement.parentElement.scrollIntoViewIfNeeded(false);this._prompt=new Elements.StylesSidebarPane.CSSPropertyPrompt(this,isEditingName);this._prompt.setAutocompletionTimeout(0);this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._applyFreeFlowStyleTextEdit.bind(this,context));const proxyElement=this._prompt.attachAndStartEditing(selectElement,blurListener.bind(this,context));this._navigateToSource(selectElement,true);proxyElement.addEventListener('keydown',this._editingNameValueKeyDown.bind(this,context),false);proxyElement.addEventListener('keypress',this._editingNameValueKeyPress.bind(this,context),false);if(isEditingName)
proxyElement.addEventListener('paste',pasteHandler.bind(this,context),false);selectElement.getComponentSelection().selectAllChildren(selectElement);}
_editingNameValueKeyDown(context,event){if(event.handled)
return;let result;if(isEnterKey(event)){result='forward';}else if(event.keyCode===UI.KeyboardShortcut.Keys.Esc.code||event.key==='Escape'){result='cancel';}else if(!context.isEditingName&&this._newProperty&&event.keyCode===UI.KeyboardShortcut.Keys.Backspace.code){const selection=event.target.getComponentSelection();if(selection.isCollapsed&&!selection.focusOffset){event.preventDefault();result='backward';}}else if(event.key==='Tab'){result=event.shiftKey?'backward':'forward';event.preventDefault();}
if(result){switch(result){case'cancel':this.editingCancelled(null,context);break;case'forward':case'backward':this._editingCommitted(event.target.textContent,context,result);break;}
event.consume();return;}}
_editingNameValueKeyPress(context,event){function shouldCommitValueSemicolon(text,cursorPosition){let openQuote='';for(let i=0;i<cursorPosition;++i){const ch=text[i];if(ch==='\\'&&openQuote!=='')
++i;else if(!openQuote&&(ch==='"'||ch==='\''))
openQuote=ch;else if(openQuote===ch)
openQuote='';}
return!openQuote;}
const keyChar=String.fromCharCode(event.charCode);const isFieldInputTerminated=(context.isEditingName?keyChar===':':keyChar===';'&&shouldCommitValueSemicolon(event.target.textContent,event.target.selectionLeftOffset()));if(isFieldInputTerminated){event.consume(true);this._editingCommitted(event.target.textContent,context,'forward');return;}}
async _applyFreeFlowStyleTextEdit(context){if(!this._prompt||!this._parentPane.node())
return;const enteredText=this._prompt.text();if(context.isEditingName&&enteredText.includes(':')){this._editingCommitted(enteredText,context,'forward');return;}
const valueText=this._prompt.textWithCurrentSuggestion();if(valueText.includes(';'))
return;const isPseudo=!!this._parentPane.node().pseudoType();if(isPseudo){if(this.name.toLowerCase()==='content')
return;const lowerValueText=valueText.trim().toLowerCase();if(lowerValueText.startsWith('content:')||lowerValueText==='display: none')
return;}
if(context.isEditingName){if(valueText.includes(':'))
await this.applyStyleText(valueText,false);else if(this._hasBeenEditedIncrementally)
await this._applyOriginalStyle(context);}else{await this.applyStyleText(`${this.nameElement.textContent}: ${valueText}`,false);}}
kickFreeFlowStyleEditForTest(){const context=this._contextForTest;return this._applyFreeFlowStyleTextEdit((context));}
editingEnded(context){this.setExpandable(context.hasChildren);if(context.expanded)
this.expand();const editedElement=context.isEditingName?this.nameElement:this.valueElement;if(editedElement.parentElement)
editedElement.parentElement.classList.remove('child-editing');this._parentPane.setEditingStyle(false);}
editingCancelled(element,context){this._removePrompt();if(this._hasBeenEditedIncrementally)
this._applyOriginalStyle(context);else if(this._newProperty)
this.treeOutline.removeChild(this);this.updateTitle();this.editingEnded(context);}
async _applyOriginalStyle(context){await this.applyStyleText(this._originalPropertyText,false,context.originalProperty);}
_findSibling(moveDirection){let target=this;do
target=(moveDirection==='forward'?target.nextSibling:target.previousSibling);while(target&&target.inherited());return target;}
async _editingCommitted(userInput,context,moveDirection){this._removePrompt();this.editingEnded(context);const isEditingName=context.isEditingName;const nameValueEntered=isEditingName&&this.nameElement.textContent.includes(':');let createNewProperty,moveToSelector;const isDataPasted='originalName'in context;const isDirtyViaPaste=isDataPasted&&(this.nameElement.textContent!==context.originalName||this.valueElement.textContent!==context.originalValue);const isPropertySplitPaste=isDataPasted&&isEditingName&&this.valueElement.textContent!==context.originalValue;let moveTo=this;const moveToOther=(isEditingName^(moveDirection==='forward'));const abandonNewProperty=this._newProperty&&!userInput&&(moveToOther||isEditingName);if(moveDirection==='forward'&&(!isEditingName||isPropertySplitPaste)||moveDirection==='backward'&&isEditingName){moveTo=moveTo._findSibling(moveDirection);if(!moveTo){if(moveDirection==='forward'&&(!this._newProperty||userInput))
createNewProperty=true;else if(moveDirection==='backward')
moveToSelector=true;}}
let moveToIndex=moveTo&&this.treeOutline?this.treeOutline.rootElement().indexOfChild(moveTo):-1;const blankInput=userInput.isWhitespace();const shouldCommitNewProperty=this._newProperty&&(isPropertySplitPaste||moveToOther||(!moveDirection&&!isEditingName)||(isEditingName&&blankInput)||nameValueEntered);const section=(this.section());if(((userInput!==context.previousContent||isDirtyViaPaste)&&!this._newProperty)||shouldCommitNewProperty){let propertyText;if(nameValueEntered){propertyText=this.nameElement.textContent;}else if(blankInput||(this._newProperty&&this.valueElement.textContent.isWhitespace())){propertyText='';}else{if(isEditingName)
propertyText=userInput+': '+this.property.value;else
propertyText=this.property.name+': '+userInput;}
await this.applyStyleText(propertyText,true);moveToNextCallback.call(this,this._newProperty,!blankInput,section);}else{if(isEditingName)
this.property.name=userInput;else
this.property.value=userInput;if(!isDataPasted&&!this._newProperty)
this.updateTitle();moveToNextCallback.call(this,this._newProperty,false,section);}
function moveToNextCallback(alreadyNew,valueChanged,section){if(!moveDirection)
return;if(moveTo&&moveTo.parent){moveTo.startEditing(!isEditingName?moveTo.nameElement:moveTo.valueElement);return;}
if(moveTo&&!moveTo.parent){const rootElement=section.propertiesTreeOutline.rootElement();if(moveDirection==='forward'&&blankInput&&!isEditingName)
--moveToIndex;if(moveToIndex>=rootElement.childCount()&&!this._newProperty){createNewProperty=true;}else{const treeElement=moveToIndex>=0?rootElement.childAt(moveToIndex):null;if(treeElement){let elementToEdit=!isEditingName||isPropertySplitPaste?treeElement.nameElement:treeElement.valueElement;if(alreadyNew&&blankInput)
elementToEdit=moveDirection==='forward'?treeElement.nameElement:treeElement.valueElement;treeElement.startEditing(elementToEdit);return;}else if(!alreadyNew){moveToSelector=true;}}}
if(createNewProperty){if(alreadyNew&&!valueChanged&&(isEditingName^(moveDirection==='backward')))
return;section.addNewBlankProperty().startEditing();return;}
if(abandonNewProperty){moveTo=this._findSibling(moveDirection);const sectionToEdit=(moveTo||moveDirection==='backward')?section:section.nextEditableSibling();if(sectionToEdit){if(sectionToEdit.style().parentRule)
sectionToEdit.startEditingSelector();else
sectionToEdit.moveEditorFromSelector(moveDirection);}
return;}
if(moveToSelector){if(section.style().parentRule)
section.startEditingSelector();else
section.moveEditorFromSelector(moveDirection);}}}
_removePrompt(){if(this._prompt){this._prompt.detach();this._prompt=null;}}
styleTextAppliedForTest(){}
applyStyleText(styleText,majorChange,property){return this._applyStyleThrottler.schedule(this._innerApplyStyleText.bind(this,styleText,majorChange,property));}
async _innerApplyStyleText(styleText,majorChange,property){if(!this.treeOutline)
return;const oldStyleRange=this._style.range;if(!oldStyleRange)
return;const hasBeenEditedIncrementally=this._hasBeenEditedIncrementally;styleText=styleText.replace(/\s/g,' ').trim();if(!styleText.length&&majorChange&&this._newProperty&&!hasBeenEditedIncrementally){this.parent.removeChild(this);return;}
const currentNode=this._parentPane.node();this._parentPane.setUserOperation(true);if(styleText.length&&!/;\s*$/.test(styleText))
styleText+=';';const overwriteProperty=!this._newProperty||hasBeenEditedIncrementally;let success=await this.property.setText(styleText,majorChange,overwriteProperty);if(hasBeenEditedIncrementally&&majorChange&&!success){majorChange=false;success=await this.property.setText(this._originalPropertyText,majorChange,overwriteProperty);}
this._parentPane.setUserOperation(false);if(!success){if(majorChange){if(this._newProperty)
this.treeOutline.removeChild(this);else
this.updateTitle();}
this.styleTextAppliedForTest();return;}
this._matchedStyles.resetActiveProperties();this._hasBeenEditedIncrementally=true;this.property=property||this._style.propertyAt(this.property.index);if(currentNode===this.node())
this._updatePane();this.styleTextAppliedForTest();}
ondblclick(){return true;}
isEventWithinDisclosureTriangle(event){return event.target===this._expandElement;}};Elements.StylePropertyTreeElement.Context;Elements.StylePropertyTreeElement.ActiveSymbol=Symbol('ActiveSymbol');;Elements.ComputedStyleWidget=class extends UI.ThrottledWidget{constructor(){super(true);this.registerRequiredCSS('elements/computedStyleSidebarPane.css');this._alwaysShowComputedProperties={'display':true,'height':true,'width':true};this._computedStyleModel=new Elements.ComputedStyleModel();this._computedStyleModel.addEventListener(Elements.ComputedStyleModel.Events.ComputedStyleChanged,this.update,this);this._showInheritedComputedStylePropertiesSetting=Common.settings.createSetting('showInheritedComputedStyleProperties',false);this._showInheritedComputedStylePropertiesSetting.addChangeListener(this._showInheritedComputedStyleChanged.bind(this));const hbox=this.contentElement.createChild('div','hbox styles-sidebar-pane-toolbar');const filterContainerElement=hbox.createChild('div','styles-sidebar-pane-filter-box');const filterInput=Elements.StylesSidebarPane.createPropertyFilterElement(ls`Filter`,hbox,filterCallback.bind(this));UI.ARIAUtils.setAccessibleName(filterInput,Common.UIString('Filter Computed Styles'));filterContainerElement.appendChild(filterInput);this.setDefaultFocusedElement(filterInput);const toolbar=new UI.Toolbar('styles-pane-toolbar',hbox);toolbar.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._showInheritedComputedStylePropertiesSetting,undefined,Common.UIString('Show all')));this._noMatchesElement=this.contentElement.createChild('div','gray-info-message');this._noMatchesElement.textContent=ls`No matching property`;this._propertiesOutline=new UI.TreeOutlineInShadow();this._propertiesOutline.hideOverflow();this._propertiesOutline.setShowSelectionOnKeyboardFocus(true);this._propertiesOutline.setFocusable(true);this._propertiesOutline.registerRequiredCSS('elements/computedStyleWidgetTree.css');this._propertiesOutline.element.classList.add('monospace','computed-properties');this.contentElement.appendChild(this._propertiesOutline.element);this._linkifier=new Components.Linkifier(Elements.ComputedStyleWidget._maxLinkLength);function filterCallback(regex){this._filterRegex=regex;this._updateFilter(regex);}
const fontsWidget=new Elements.PlatformFontsWidget(this._computedStyleModel);fontsWidget.show(this.contentElement);}
onResize(){const isNarrow=this.contentElement.offsetWidth<260;this._propertiesOutline.contentElement.classList.toggle('computed-narrow',isNarrow);}
_showInheritedComputedStyleChanged(){this.update();}
doUpdate(){const promises=[this._computedStyleModel.fetchComputedStyle(),this._fetchMatchedCascade()];return Promise.all(promises).spread(this._innerRebuildUpdate.bind(this));}
_fetchMatchedCascade(){const node=this._computedStyleModel.node();if(!node||!this._computedStyleModel.cssModel())
return Promise.resolve((null));return this._computedStyleModel.cssModel().cachedMatchedCascadeForNode(node).then(validateStyles.bind(this));function validateStyles(matchedStyles){return matchedStyles&&matchedStyles.node()===this._computedStyleModel.node()?matchedStyles:null;}}
_processColor(text){const color=Common.Color.parse(text);if(!color)
return createTextNode(text);const swatch=InlineEditor.ColorSwatch.create();swatch.setColor(color);swatch.setFormat(Common.Color.detectColorFormat(color));return swatch;}
_innerRebuildUpdate(nodeStyle,matchedStyles){const expandedProperties=new Set();for(const treeElement of this._propertiesOutline.rootElement().children()){if(!treeElement.expanded)
continue;const propertyName=treeElement[Elements.ComputedStyleWidget._propertySymbol].name;expandedProperties.add(propertyName);}
const hadFocus=this._propertiesOutline.element.hasFocus();this._propertiesOutline.removeChildren();this._linkifier.reset();const cssModel=this._computedStyleModel.cssModel();if(!nodeStyle||!matchedStyles||!cssModel){this._noMatchesElement.classList.remove('hidden');return;}
const uniqueProperties=nodeStyle.computedStyle.keysArray();uniqueProperties.sort(propertySorter);const propertyTraces=this._computePropertyTraces(matchedStyles);const inhertiedProperties=this._computeInheritedProperties(matchedStyles);const showInherited=this._showInheritedComputedStylePropertiesSetting.get();for(let i=0;i<uniqueProperties.length;++i){const propertyName=uniqueProperties[i];const propertyValue=nodeStyle.computedStyle.get(propertyName);const canonicalName=SDK.cssMetadata().canonicalPropertyName(propertyName);const inherited=!inhertiedProperties.has(canonicalName);if(!showInherited&&inherited&&!(propertyName in this._alwaysShowComputedProperties))
continue;if(!showInherited&&propertyName.startsWith('--'))
continue;if(propertyName!==canonicalName&&propertyValue===nodeStyle.computedStyle.get(canonicalName))
continue;const propertyElement=createElement('div');propertyElement.classList.add('computed-style-property');propertyElement.classList.toggle('computed-style-property-inherited',inherited);const renderer=new Elements.StylesSidebarPropertyRenderer(null,nodeStyle.node,propertyName,(propertyValue));renderer.setColorHandler(this._processColor.bind(this));const propertyNameElement=renderer.renderName();propertyNameElement.classList.add('property-name');propertyElement.appendChild(propertyNameElement);const colon=createElementWithClass('span','delimeter');colon.textContent=': ';propertyNameElement.appendChild(colon);const propertyValueElement=propertyElement.createChild('span','property-value');const propertyValueText=renderer.renderValue();propertyValueText.classList.add('property-value-text');propertyValueElement.appendChild(propertyValueText);const semicolon=createElementWithClass('span','delimeter');semicolon.textContent=';';propertyValueElement.appendChild(semicolon);const treeElement=new UI.TreeElement();treeElement.title=propertyElement;treeElement[Elements.ComputedStyleWidget._propertySymbol]={name:propertyName,value:propertyValue};const isOdd=this._propertiesOutline.rootElement().children().length%2===0;treeElement.listItemElement.classList.toggle('odd-row',isOdd);this._propertiesOutline.appendChild(treeElement);if(!this._propertiesOutline.selectedTreeElement)
treeElement.select(!hadFocus);const trace=propertyTraces.get(propertyName);if(trace){const activeProperty=this._renderPropertyTrace(cssModel,matchedStyles,nodeStyle.node,treeElement,trace);treeElement.listItemElement.addEventListener('mousedown',e=>e.consume(),false);treeElement.listItemElement.addEventListener('dblclick',e=>e.consume(),false);treeElement.listItemElement.addEventListener('click',handleClick.bind(null,treeElement),false);const gotoSourceElement=UI.Icon.create('mediumicon-arrow-in-circle','goto-source-icon');gotoSourceElement.addEventListener('click',this._navigateToSource.bind(this,activeProperty));propertyValueElement.appendChild(gotoSourceElement);if(expandedProperties.has(propertyName))
treeElement.expand();}}
this._updateFilter(this._filterRegex);function propertySorter(a,b){if(a.startsWith('--')^b.startsWith('--'))
return a.startsWith('--')?1:-1;if(a.startsWith('-webkit')^b.startsWith('-webkit'))
return a.startsWith('-webkit')?1:-1;const canonical1=SDK.cssMetadata().canonicalPropertyName(a);const canonical2=SDK.cssMetadata().canonicalPropertyName(b);return canonical1.compareTo(canonical2);}
function handleClick(treeElement,event){if(!treeElement.expanded)
treeElement.expand();else
treeElement.collapse();event.consume();}}
_navigateToSource(cssProperty,event){Common.Revealer.reveal(cssProperty);event.consume(true);}
_renderPropertyTrace(cssModel,matchedStyles,node,rootTreeElement,tracedProperties){let activeProperty=null;for(const property of tracedProperties){const trace=createElement('div');trace.classList.add('property-trace');if(matchedStyles.propertyState(property)===SDK.CSSMatchedStyles.PropertyState.Overloaded)
trace.classList.add('property-trace-inactive');else
activeProperty=property;const renderer=new Elements.StylesSidebarPropertyRenderer(null,node,property.name,(property.value));renderer.setColorHandler(this._processColor.bind(this));const valueElement=renderer.renderValue();valueElement.classList.add('property-trace-value');valueElement.addEventListener('click',this._navigateToSource.bind(this,property),false);const gotoSourceElement=UI.Icon.create('mediumicon-arrow-in-circle','goto-source-icon');gotoSourceElement.addEventListener('click',this._navigateToSource.bind(this,property));valueElement.insertBefore(gotoSourceElement,valueElement.firstChild);trace.appendChild(valueElement);const rule=property.ownerStyle.parentRule;const selectorElement=trace.createChild('span','property-trace-selector');selectorElement.textContent=rule?rule.selectorText():'element.style';selectorElement.title=selectorElement.textContent;if(rule){const linkSpan=trace.createChild('span','trace-link');linkSpan.appendChild(Elements.StylePropertiesSection.createRuleOriginNode(matchedStyles,this._linkifier,rule));}
const traceTreeElement=new UI.TreeElement();traceTreeElement.title=trace;rootTreeElement.appendChild(traceTreeElement);}
return(activeProperty);}
_computePropertyTraces(matchedStyles){const result=new Map();for(const style of matchedStyles.nodeStyles()){const allProperties=style.allProperties();for(const property of allProperties){if(!property.activeInStyle()||!matchedStyles.propertyState(property))
continue;if(!result.has(property.name))
result.set(property.name,[]);result.get(property.name).push(property);}}
return result;}
_computeInheritedProperties(matchedStyles){const result=new Set();for(const style of matchedStyles.nodeStyles()){for(const property of style.allProperties()){if(!matchedStyles.propertyState(property))
continue;result.add(SDK.cssMetadata().canonicalPropertyName(property.name));}}
return result;}
_updateFilter(regex){const children=this._propertiesOutline.rootElement().children();let hasMatch=false;for(const child of children){const property=child[Elements.ComputedStyleWidget._propertySymbol];const matched=!regex||regex.test(property.name)||regex.test(property.value);child.hidden=!matched;hasMatch|=matched;}
this._noMatchesElement.classList.toggle('hidden',hasMatch);}};Elements.ComputedStyleWidget._maxLinkLength=30;Elements.ComputedStyleWidget._propertySymbol=Symbol('property');;Elements.ElementsPanel=class extends UI.Panel{constructor(){super('elements');this.registerRequiredCSS('elements/elementsPanel.css');this._splitWidget=new UI.SplitWidget(true,true,'elementsPanelSplitViewState',325,325);this._splitWidget.addEventListener(UI.SplitWidget.Events.SidebarSizeChanged,this._updateTreeOutlineVisibleWidth.bind(this));this._splitWidget.show(this.element);this._searchableView=new UI.SearchableView(this);this._searchableView.setMinimumSize(25,28);this._searchableView.setPlaceholder(Common.UIString('Find by string, selector, or XPath'));const stackElement=this._searchableView.element;this._contentElement=createElement('div');const crumbsContainer=createElement('div');stackElement.appendChild(this._contentElement);stackElement.appendChild(crumbsContainer);this._splitWidget.setMainWidget(this._searchableView);this._splitMode=null;this._contentElement.id='elements-content';if(Common.moduleSetting('domWordWrap').get())
this._contentElement.classList.add('elements-wrap');Common.moduleSetting('domWordWrap').addChangeListener(this._domWordWrapSettingChanged.bind(this));crumbsContainer.id='elements-crumbs';this._breadcrumbs=new Elements.ElementsBreadcrumbs();this._breadcrumbs.show(crumbsContainer);this._breadcrumbs.addEventListener(Elements.ElementsBreadcrumbs.Events.NodeSelected,this._crumbNodeSelected,this);this._stylesWidget=new Elements.StylesSidebarPane();this._computedStyleWidget=new Elements.ComputedStyleWidget();this._metricsWidget=new Elements.MetricsSidebarPane();Common.moduleSetting('sidebarPosition').addChangeListener(this._updateSidebarPosition.bind(this));this._updateSidebarPosition();this._treeOutlines=[];this._treeOutlineHeaders=new Map();SDK.targetManager.observeModels(SDK.DOMModel,this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.NameChanged,event=>this._targetNameChanged((event.data)));Common.moduleSetting('showUAShadowDOM').addChangeListener(this._showUAShadowDOMChanged.bind(this));SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.DocumentUpdated,this._documentUpdatedEvent,this);Extensions.extensionServer.addEventListener(Extensions.ExtensionServer.Events.SidebarPaneAdded,this._extensionSidebarPaneAdded,this);}
static instance(){return(self.runtime.sharedInstance(Elements.ElementsPanel));}
_revealProperty(cssProperty){return this.sidebarPaneView.showView(this._stylesViewToReveal).then(()=>{this._stylesWidget.revealProperty((cssProperty));});}
resolveLocation(locationName){return this.sidebarPaneView;}
showToolbarPane(widget,toggle){this._stylesWidget.showToolbarPane(widget,toggle);}
modelAdded(domModel){const parentModel=domModel.parentModel();let treeOutline=parentModel?Elements.ElementsTreeOutline.forDOMModel(parentModel):null;if(!treeOutline){treeOutline=new Elements.ElementsTreeOutline(true,true);treeOutline.setWordWrap(Common.moduleSetting('domWordWrap').get());treeOutline.addEventListener(Elements.ElementsTreeOutline.Events.SelectedNodeChanged,this._selectedNodeChanged,this);treeOutline.addEventListener(Elements.ElementsTreeOutline.Events.ElementsTreeUpdated,this._updateBreadcrumbIfNeeded,this);new Elements.ElementsTreeElementHighlighter(treeOutline);this._treeOutlines.push(treeOutline);if(domModel.target().parentTarget()){this._treeOutlineHeaders.set(treeOutline,createElementWithClass('div','elements-tree-header'));this._targetNameChanged(domModel.target());}}
treeOutline.wireToDOMModel(domModel);if(this.isShowing())
this.wasShown();}
modelRemoved(domModel){const treeOutline=Elements.ElementsTreeOutline.forDOMModel(domModel);treeOutline.unwireFromDOMModel(domModel);if(domModel.parentModel())
return;this._treeOutlines.remove(treeOutline);const header=this._treeOutlineHeaders.get(treeOutline);if(header)
header.remove();this._treeOutlineHeaders.delete(treeOutline);treeOutline.element.remove();}
_targetNameChanged(target){const domModel=target.model(SDK.DOMModel);if(!domModel)
return;const treeOutline=Elements.ElementsTreeOutline.forDOMModel(domModel);if(!treeOutline)
return;const header=this._treeOutlineHeaders.get(treeOutline);if(!header)
return;header.removeChildren();header.createChild('div','elements-tree-header-frame').textContent=Common.UIString('Frame');header.appendChild(Components.Linkifier.linkifyURL(target.inspectedURL(),{text:target.name()}));}
_updateTreeOutlineVisibleWidth(){if(!this._treeOutlines.length)
return;let width=this._splitWidget.element.offsetWidth;if(this._splitWidget.isVertical())
width-=this._splitWidget.sidebarSize();for(let i=0;i<this._treeOutlines.length;++i)
this._treeOutlines[i].setVisibleWidth(width);this._breadcrumbs.updateSizes();}
focus(){if(this._treeOutlines.length)
this._treeOutlines[0].focus();}
searchableView(){return this._searchableView;}
wasShown(){UI.context.setFlavor(Elements.ElementsPanel,this);for(let i=0;i<this._treeOutlines.length;++i){const treeOutline=this._treeOutlines[i];if(treeOutline.element.parentElement!==this._contentElement){const header=this._treeOutlineHeaders.get(treeOutline);if(header)
this._contentElement.appendChild(header);this._contentElement.appendChild(treeOutline.element);}}
super.wasShown();this._breadcrumbs.update();const domModels=SDK.targetManager.models(SDK.DOMModel);for(const domModel of domModels){if(domModel.parentModel())
continue;const treeOutline=Elements.ElementsTreeOutline.forDOMModel(domModel);treeOutline.setVisible(true);if(!treeOutline.rootDOMNode){if(domModel.existingDocument()){treeOutline.rootDOMNode=domModel.existingDocument();this._documentUpdated(domModel);}else{domModel.requestDocument();}}}}
willHide(){SDK.OverlayModel.hideDOMNodeHighlight();for(let i=0;i<this._treeOutlines.length;++i){const treeOutline=this._treeOutlines[i];treeOutline.setVisible(false);this._contentElement.removeChild(treeOutline.element);const header=this._treeOutlineHeaders.get(treeOutline);if(header)
this._contentElement.removeChild(header);}
if(this._popoverHelper)
this._popoverHelper.hidePopover();super.willHide();UI.context.setFlavor(Elements.ElementsPanel,null);}
onResize(){this.element.window().requestAnimationFrame(this._updateSidebarPosition.bind(this));this._updateTreeOutlineVisibleWidth();}
_selectedNodeChanged(event){const selectedNode=(event.data.node);const focus=(event.data.focus);for(const treeOutline of this._treeOutlines){if(!selectedNode||Elements.ElementsTreeOutline.forDOMModel(selectedNode.domModel())!==treeOutline)
treeOutline.selectDOMNode(null);}
this._breadcrumbs.setSelectedNode(selectedNode);UI.context.setFlavor(SDK.DOMNode,selectedNode);if(!selectedNode)
return;selectedNode.setAsInspectedNode();if(focus){this._selectedNodeOnReset=selectedNode;this._hasNonDefaultSelectedNode=true;}
const executionContexts=selectedNode.domModel().runtimeModel().executionContexts();const nodeFrameId=selectedNode.frameId();for(const context of executionContexts){if(context.frameId===nodeFrameId){UI.context.setFlavor(SDK.ExecutionContext,context);break;}}}
_documentUpdatedEvent(event){const domModel=(event.data);this._documentUpdated(domModel);}
_documentUpdated(domModel){this._searchableView.resetSearch();if(!domModel.existingDocument()){if(this.isShowing())
domModel.requestDocument();return;}
this._hasNonDefaultSelectedNode=false;if(this._omitDefaultSelection)
return;const savedSelectedNodeOnReset=this._selectedNodeOnReset;restoreNode.call(this,domModel,this._selectedNodeOnReset);async function restoreNode(domModel,staleNode){const nodePath=staleNode?staleNode.path():null;const restoredNodeId=nodePath?await domModel.pushNodeByPathToFrontend(nodePath):null;if(savedSelectedNodeOnReset!==this._selectedNodeOnReset)
return;let node=restoredNodeId?domModel.nodeForId(restoredNodeId):null;if(!node){const inspectedDocument=domModel.existingDocument();node=inspectedDocument?inspectedDocument.body||inspectedDocument.documentElement:null;}
this._setDefaultSelectedNode(node);this._lastSelectedNodeSelectedForTest();}}
_lastSelectedNodeSelectedForTest(){}
_setDefaultSelectedNode(node){if(!node||this._hasNonDefaultSelectedNode||this._pendingNodeReveal)
return;const treeOutline=Elements.ElementsTreeOutline.forDOMModel(node.domModel());if(!treeOutline)
return;this.selectDOMNode(node);if(treeOutline.selectedTreeElement)
treeOutline.selectedTreeElement.expand();}
searchCanceled(){delete this._searchConfig;this._hideSearchHighlights();this._searchableView.updateSearchMatchesCount(0);delete this._currentSearchResultIndex;delete this._searchResults;SDK.DOMModel.cancelSearch();}
performSearch(searchConfig,shouldJump,jumpBackwards){const query=searchConfig.query;const whitespaceTrimmedQuery=query.trim();if(!whitespaceTrimmedQuery.length)
return;if(!this._searchConfig||this._searchConfig.query!==query)
this.searchCanceled();else
this._hideSearchHighlights();this._searchConfig=searchConfig;const showUAShadowDOM=Common.moduleSetting('showUAShadowDOM').get();const domModels=SDK.targetManager.models(SDK.DOMModel);const promises=domModels.map(domModel=>domModel.performSearch(whitespaceTrimmedQuery,showUAShadowDOM));Promise.all(promises).then(resultCountCallback.bind(this));function resultCountCallback(resultCounts){this._searchResults=[];for(let i=0;i<resultCounts.length;++i){const resultCount=resultCounts[i];for(let j=0;j<resultCount;++j)
this._searchResults.push({domModel:domModels[i],index:j,node:undefined});}
this._searchableView.updateSearchMatchesCount(this._searchResults.length);if(!this._searchResults.length)
return;if(this._currentSearchResultIndex>=this._searchResults.length)
this._currentSearchResultIndex=undefined;let index=this._currentSearchResultIndex;if(shouldJump){if(this._currentSearchResultIndex===undefined)
index=jumpBackwards?-1:0;else
index=jumpBackwards?index-1:index+1;this._jumpToSearchResult(index);}}}
_domWordWrapSettingChanged(event){this._contentElement.classList.toggle('elements-wrap',event.data);for(let i=0;i<this._treeOutlines.length;++i)
this._treeOutlines[i].setWordWrap((event.data));}
switchToAndFocus(node){this._searchableView.cancelSearch();UI.viewManager.showView('elements').then(()=>this.selectDOMNode(node,true));}
_getPopoverRequest(event){let link=event.target;while(link&&!link[Elements.ElementsTreeElement.HrefSymbol])
link=link.parentElementOrShadowHost();if(!link)
return null;return{box:link.boxInWindow(),show:async popover=>{const node=this.selectedDOMNode();if(!node)
return false;const preview=await Components.ImagePreview.build(node.domModel().target(),link[Elements.ElementsTreeElement.HrefSymbol],true);if(preview)
popover.contentElement.appendChild(preview);return!!preview;}};}
_jumpToSearchResult(index){this._currentSearchResultIndex=(index+this._searchResults.length)%this._searchResults.length;this._highlightCurrentSearchResult();}
jumpToNextSearchResult(){if(!this._searchResults)
return;this.performSearch(this._searchConfig,true);}
jumpToPreviousSearchResult(){if(!this._searchResults)
return;this.performSearch(this._searchConfig,true,true);}
supportsCaseSensitiveSearch(){return false;}
supportsRegexSearch(){return false;}
_highlightCurrentSearchResult(){const index=this._currentSearchResultIndex;const searchResults=this._searchResults;const searchResult=searchResults[index];this._searchableView.updateCurrentMatchIndex(index);if(searchResult.node===null)
return;if(typeof searchResult.node==='undefined'){searchResult.domModel.searchResult(searchResult.index).then(node=>{searchResult.node=node;this._highlightCurrentSearchResult();});return;}
const treeElement=this._treeElementForNode(searchResult.node);searchResult.node.scrollIntoView();if(treeElement){treeElement.highlightSearchResults(this._searchConfig.query);treeElement.reveal();const matches=treeElement.listItemElement.getElementsByClassName(UI.highlightedSearchResultClassName);if(matches.length)
matches[0].scrollIntoViewIfNeeded(false);}}
_hideSearchHighlights(){if(!this._searchResults||!this._searchResults.length||this._currentSearchResultIndex===undefined)
return;const searchResult=this._searchResults[this._currentSearchResultIndex];if(!searchResult.node)
return;const treeOutline=Elements.ElementsTreeOutline.forDOMModel(searchResult.node.domModel());const treeElement=treeOutline.findTreeElement(searchResult.node);if(treeElement)
treeElement.hideSearchHighlights();}
selectedDOMNode(){for(let i=0;i<this._treeOutlines.length;++i){const treeOutline=this._treeOutlines[i];if(treeOutline.selectedDOMNode())
return treeOutline.selectedDOMNode();}
return null;}
selectDOMNode(node,focus){for(const treeOutline of this._treeOutlines){const outline=Elements.ElementsTreeOutline.forDOMModel(node.domModel());if(outline===treeOutline)
treeOutline.selectDOMNode(node,focus);else
treeOutline.selectDOMNode(null);}}
_updateBreadcrumbIfNeeded(event){const nodes=(event.data);this._breadcrumbs.updateNodes(nodes);}
_crumbNodeSelected(event){const node=(event.data);this.selectDOMNode(node,true);}
_treeOutlineForNode(node){if(!node)
return null;return Elements.ElementsTreeOutline.forDOMModel(node.domModel());}
_treeElementForNode(node){const treeOutline=this._treeOutlineForNode(node);return(treeOutline.findTreeElement(node));}
_leaveUserAgentShadowDOM(node){let userAgentShadowRoot;while((userAgentShadowRoot=node.ancestorUserAgentShadowRoot())&&userAgentShadowRoot.parentNode)
node=userAgentShadowRoot.parentNode;return node;}
revealAndSelectNode(node,focus,omitHighlight){this._omitDefaultSelection=true;node=Common.moduleSetting('showUAShadowDOM').get()?node:this._leaveUserAgentShadowDOM(node);if(!omitHighlight)
node.highlightForTwoSeconds();return UI.viewManager.showView('elements',false,!focus).then(()=>{this.selectDOMNode(node,focus);delete this._omitDefaultSelection;if(!this._notFirstInspectElement){Elements.ElementsPanel._firstInspectElementNodeNameForTest=node.nodeName();Elements.ElementsPanel._firstInspectElementCompletedForTest();InspectorFrontendHost.inspectElementCompleted();}
this._notFirstInspectElement=true;});}
_showUAShadowDOMChanged(){for(let i=0;i<this._treeOutlines.length;++i)
this._treeOutlines[i].update();}
_setupTextSelectionHack(stylePaneWrapperElement){const uninstallHackBound=uninstallHack.bind(this);const uninstallHackOnMousemove=event=>{if(event.buttons===0)
uninstallHack.call(this);};stylePaneWrapperElement.addEventListener('mousedown',event=>{if(event.which!==1)
return;this._splitWidget.element.classList.add('disable-resizer-for-elements-hack');stylePaneWrapperElement.style.setProperty('height',`${stylePaneWrapperElement.offsetHeight}px`);const largeLength=1000000;stylePaneWrapperElement.style.setProperty('left',`${- 1 * largeLength}px`);stylePaneWrapperElement.style.setProperty('padding-left',`${largeLength}px`);stylePaneWrapperElement.style.setProperty('width',`calc(100% + ${largeLength}px)`);stylePaneWrapperElement.style.setProperty('position',`fixed`);stylePaneWrapperElement.window().addEventListener('blur',uninstallHackBound);stylePaneWrapperElement.window().addEventListener('contextmenu',uninstallHackBound,true);stylePaneWrapperElement.window().addEventListener('dragstart',uninstallHackBound,true);stylePaneWrapperElement.window().addEventListener('mousemove',uninstallHackOnMousemove,true);stylePaneWrapperElement.window().addEventListener('mouseup',uninstallHackBound,true);stylePaneWrapperElement.window().addEventListener('visibilitychange',uninstallHackBound);},true);function uninstallHack(){this._splitWidget.element.classList.remove('disable-resizer-for-elements-hack');stylePaneWrapperElement.style.removeProperty('left');stylePaneWrapperElement.style.removeProperty('padding-left');stylePaneWrapperElement.style.removeProperty('width');stylePaneWrapperElement.style.removeProperty('position');stylePaneWrapperElement.window().removeEventListener('blur',uninstallHackBound);stylePaneWrapperElement.window().removeEventListener('contextmenu',uninstallHackBound,true);stylePaneWrapperElement.window().removeEventListener('dragstart',uninstallHackBound,true);stylePaneWrapperElement.window().removeEventListener('mousemove',uninstallHackOnMousemove,true);stylePaneWrapperElement.window().removeEventListener('mouseup',uninstallHackBound,true);stylePaneWrapperElement.window().removeEventListener('visibilitychange',uninstallHackBound);}}
_updateSidebarPosition(){if(this.sidebarPaneView&&this.sidebarPaneView.tabbedPane().shouldHideOnDetach())
return;let splitMode;const position=Common.moduleSetting('sidebarPosition').get();if(position==='right'||(position==='auto'&&UI.inspectorView.element.offsetWidth>680))
splitMode=Elements.ElementsPanel._splitMode.Vertical;else if(UI.inspectorView.element.offsetWidth>415)
splitMode=Elements.ElementsPanel._splitMode.Horizontal;else
splitMode=Elements.ElementsPanel._splitMode.Slim;if(this.sidebarPaneView&&splitMode===this._splitMode)
return;this._splitMode=splitMode;const extensionSidebarPanes=Extensions.extensionServer.sidebarPanes();let lastSelectedTabId=null;if(this.sidebarPaneView){lastSelectedTabId=this.sidebarPaneView.tabbedPane().selectedTabId;this.sidebarPaneView.tabbedPane().detach();this._splitWidget.uninstallResizer(this.sidebarPaneView.tabbedPane().headerElement());}
this._splitWidget.setVertical(this._splitMode===Elements.ElementsPanel._splitMode.Vertical);this.showToolbarPane(null,null);const matchedStylePanesWrapper=new UI.VBox();matchedStylePanesWrapper.element.classList.add('style-panes-wrapper');this._stylesWidget.show(matchedStylePanesWrapper.element);this._setupTextSelectionHack(matchedStylePanesWrapper.element);const computedStylePanesWrapper=new UI.VBox();computedStylePanesWrapper.element.classList.add('style-panes-wrapper');this._computedStyleWidget.show(computedStylePanesWrapper.element);function showMetrics(inComputedStyle){if(inComputedStyle)
this._metricsWidget.show(computedStylePanesWrapper.element,this._computedStyleWidget.element);else
this._metricsWidget.show(matchedStylePanesWrapper.element);}
function tabSelected(event){const tabId=(event.data.tabId);if(tabId===Common.UIString('Computed'))
showMetrics.call(this,true);else if(tabId===Common.UIString('Styles'))
showMetrics.call(this,false);}
this.sidebarPaneView=UI.viewManager.createTabbedLocation(()=>UI.viewManager.showView('elements'));const tabbedPane=this.sidebarPaneView.tabbedPane();if(this._popoverHelper)
this._popoverHelper.hidePopover();this._popoverHelper=new UI.PopoverHelper(tabbedPane.element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(0);if(this._splitMode!==Elements.ElementsPanel._splitMode.Vertical)
this._splitWidget.installResizer(tabbedPane.headerElement());const stylesView=new UI.SimpleView(Common.UIString('Styles'));this.sidebarPaneView.appendView(stylesView);if(splitMode===Elements.ElementsPanel._splitMode.Horizontal){stylesView.element.classList.add('flex-auto');const splitWidget=new UI.SplitWidget(true,true,'stylesPaneSplitViewState',215);splitWidget.show(stylesView.element);splitWidget.setMainWidget(matchedStylePanesWrapper);splitWidget.setSidebarWidget(computedStylePanesWrapper);}else{stylesView.element.classList.add('flex-auto');matchedStylePanesWrapper.show(stylesView.element);const computedView=new UI.SimpleView(Common.UIString('Computed'));computedView.element.classList.add('composite','fill');computedStylePanesWrapper.show(computedView.element);tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,tabSelected,this);this.sidebarPaneView.appendView(computedView);}
this._stylesViewToReveal=stylesView;showMetrics.call(this,this._splitMode===Elements.ElementsPanel._splitMode.Horizontal);this.sidebarPaneView.appendApplicableItems('elements-sidebar');for(let i=0;i<extensionSidebarPanes.length;++i)
this._addExtensionSidebarPane(extensionSidebarPanes[i]);if(lastSelectedTabId)
this.sidebarPaneView.tabbedPane().selectTab(lastSelectedTabId);this._splitWidget.setSidebarWidget(this.sidebarPaneView.tabbedPane());}
_extensionSidebarPaneAdded(event){const pane=(event.data);this._addExtensionSidebarPane(pane);}
_addExtensionSidebarPane(pane){if(pane.panelName()===this.name)
this.sidebarPaneView.appendView(pane);}};Elements.ElementsPanel._elementsSidebarViewTitleSymbol=Symbol('title');Elements.ElementsPanel._splitMode={Vertical:Symbol('Vertical'),Horizontal:Symbol('Horizontal'),Slim:Symbol('Slim'),};Elements.ElementsPanel._firstInspectElementCompletedForTest=function(){};Elements.ElementsPanel.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,object){if(!(object instanceof SDK.RemoteObject&&((object)).isNode())&&!(object instanceof SDK.DOMNode)&&!(object instanceof SDK.DeferredDOMNode))
return;if(Elements.ElementsPanel.instance().element.isAncestor((event.target)))
return;const commandCallback=Common.Revealer.reveal.bind(Common.Revealer,object);contextMenu.revealSection().appendItem(Common.UIString('Reveal in Elements panel'),commandCallback);}};Elements.ElementsPanel.DOMNodeRevealer=class{reveal(node,omitFocus){const panel=Elements.ElementsPanel.instance();panel._pendingNodeReveal=true;return new Promise(revealPromise);function revealPromise(resolve,reject){if(node instanceof SDK.DOMNode){onNodeResolved((node));}else if(node instanceof SDK.DeferredDOMNode){((node)).resolve(onNodeResolved);}else if(node instanceof SDK.RemoteObject){const domModel=(node).runtimeModel().target().model(SDK.DOMModel);if(domModel)
domModel.pushObjectAsNodeToFrontend(node).then(onNodeResolved);else
reject(new Error('Could not resolve a node to reveal.'));}else{reject(new Error('Can\'t reveal a non-node.'));panel._pendingNodeReveal=false;}
function onNodeResolved(resolvedNode){panel._pendingNodeReveal=false;if(resolvedNode){panel.revealAndSelectNode(resolvedNode,!omitFocus).then(resolve);return;}
reject(new Error('Could not resolve node to reveal.'));}}}};Elements.ElementsPanel.CSSPropertyRevealer=class{reveal(property){const panel=Elements.ElementsPanel.instance();return panel._revealProperty((property));}};Elements.ElementsActionDelegate=class{handleAction(context,actionId){const node=UI.context.flavor(SDK.DOMNode);if(!node)
return true;const treeOutline=Elements.ElementsTreeOutline.forDOMModel(node.domModel());if(!treeOutline)
return true;switch(actionId){case'elements.hide-element':treeOutline.toggleHideElement(node);return true;case'elements.edit-as-html':treeOutline.toggleEditAsHTML(node);return true;case'elements.undo':SDK.domModelUndoStack.undo();Elements.ElementsPanel.instance()._stylesWidget.forceUpdate();return true;case'elements.redo':SDK.domModelUndoStack.redo();Elements.ElementsPanel.instance()._stylesWidget.forceUpdate();return true;}
return false;}};Elements.ElementsPanel.PseudoStateMarkerDecorator=class{decorate(node){return{color:'orange',title:Common.UIString('Element state: %s',':'+node.domModel().cssModel().pseudoState(node).join(', :'))};}};;Elements.ClassesPaneWidget=class extends UI.Widget{constructor(){super(true);this.registerRequiredCSS('elements/classesPaneWidget.css');this.contentElement.className='styles-element-classes-pane';const container=this.contentElement.createChild('div','title-container');this._input=container.createChild('div','new-class-input monospace');this.setDefaultFocusedElement(this._input);this._classesContainer=this.contentElement.createChild('div','source-code');this._classesContainer.classList.add('styles-element-classes-container');this._prompt=new Elements.ClassesPaneWidget.ClassNamePrompt(this._nodeClasses.bind(this));this._prompt.setAutocompletionTimeout(0);this._prompt.renderAsBlock();const proxyElement=this._prompt.attach(this._input);this._prompt.setPlaceholder(Common.UIString('Add new class'));this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._onTextChanged,this);proxyElement.addEventListener('keydown',this._onKeyDown.bind(this),false);SDK.targetManager.addModelListener(SDK.DOMModel,SDK.DOMModel.Events.DOMMutated,this._onDOMMutated,this);this._mutatingNodes=new Set();this._pendingNodeClasses=new Map();this._updateNodeThrottler=new Common.Throttler(0);this._previousTarget=null;UI.context.addFlavorChangeListener(SDK.DOMNode,this._onSelectedNodeChanged,this);}
_splitTextIntoClasses(text){return text.split(/[.,\s]/).map(className=>className.trim()).filter(className=>className.length);}
_onKeyDown(event){if(!isEnterKey(event)&&!isEscKey(event))
return;if(isEnterKey(event)){event.consume();if(this._prompt.acceptAutoComplete())
return;}
let text=event.target.textContent;if(isEscKey(event)){if(!text.isWhitespace())
event.consume(true);text='';}
this._prompt.clearAutocomplete();event.target.textContent='';const node=UI.context.flavor(SDK.DOMNode);if(!node)
return;const classNames=this._splitTextIntoClasses(text);for(const className of classNames)
this._toggleClass(node,className,true);this._installNodeClasses(node);this._update();}
_onTextChanged(){const node=UI.context.flavor(SDK.DOMNode);if(!node)
return;this._installNodeClasses(node);}
_onDOMMutated(event){const node=(event.data);if(this._mutatingNodes.has(node))
return;delete node[Elements.ClassesPaneWidget._classesSymbol];this._update();}
_onSelectedNodeChanged(event){if(this._previousTarget&&this._prompt.text()){this._input.textContent='';this._installNodeClasses(this._previousTarget);}
this._previousTarget=(event.data);this._update();}
wasShown(){this._update();}
_update(){if(!this.isShowing())
return;let node=UI.context.flavor(SDK.DOMNode);if(node)
node=node.enclosingElementOrSelf();this._classesContainer.removeChildren();this._input.disabled=!node;if(!node)
return;const classes=this._nodeClasses(node);const keys=classes.keysArray();keys.sort(String.caseInsensetiveComparator);for(let i=0;i<keys.length;++i){const className=keys[i];const label=UI.CheckboxLabel.create(className,classes.get(className));label.classList.add('monospace');label.checkboxElement.addEventListener('click',this._onClick.bind(this,className),false);this._classesContainer.appendChild(label);}}
_onClick(className,event){const node=UI.context.flavor(SDK.DOMNode);if(!node)
return;const enabled=event.target.checked;this._toggleClass(node,className,enabled);this._installNodeClasses(node);}
_nodeClasses(node){let result=node[Elements.ClassesPaneWidget._classesSymbol];if(!result){const classAttribute=node.getAttribute('class')||'';const classes=classAttribute.split(/\s/);result=new Map();for(let i=0;i<classes.length;++i){const className=classes[i].trim();if(!className.length)
continue;result.set(className,true);}
node[Elements.ClassesPaneWidget._classesSymbol]=result;}
return result;}
_toggleClass(node,className,enabled){const classes=this._nodeClasses(node);classes.set(className,enabled);}
_installNodeClasses(node){const classes=this._nodeClasses(node);const activeClasses=new Set();for(const className of classes.keys()){if(classes.get(className))
activeClasses.add(className);}
const additionalClasses=this._splitTextIntoClasses(this._prompt.textWithCurrentSuggestion());for(const className of additionalClasses)
activeClasses.add(className);const newClasses=activeClasses.valuesArray();newClasses.sort();this._pendingNodeClasses.set(node,newClasses.join(' '));this._updateNodeThrottler.schedule(this._flushPendingClasses.bind(this));}
_flushPendingClasses(){const promises=[];for(const node of this._pendingNodeClasses.keys()){this._mutatingNodes.add(node);const promise=node.setAttributeValuePromise('class',this._pendingNodeClasses.get(node)).then(onClassValueUpdated.bind(this,node));promises.push(promise);}
this._pendingNodeClasses.clear();return Promise.all(promises);function onClassValueUpdated(node){this._mutatingNodes.delete(node);}}};Elements.ClassesPaneWidget._classesSymbol=Symbol('Elements.ClassesPaneWidget._classesSymbol');Elements.ClassesPaneWidget.ButtonProvider=class{constructor(){this._button=new UI.ToolbarToggle(Common.UIString('Element Classes'),'');this._button.setText('.cls');this._button.element.classList.add('monospace');this._button.addEventListener(UI.ToolbarButton.Events.Click,this._clicked,this);this._view=new Elements.ClassesPaneWidget();}
_clicked(){Elements.ElementsPanel.instance().showToolbarPane(!this._view.isShowing()?this._view:null,this._button);}
item(){return this._button;}};Elements.ClassesPaneWidget.ClassNamePrompt=class extends UI.TextPrompt{constructor(nodeClasses){super();this._nodeClasses=nodeClasses;this.initialize(this._buildClassNameCompletions.bind(this),' ');this.disableDefaultSuggestionForEmptyInput();this._selectedFrameId='';this._classNamesPromise=null;}
_getClassNames(selectedNode){const promises=[];const completions=new Set();this._selectedFrameId=selectedNode.frameId();const cssModel=selectedNode.domModel().cssModel();const allStyleSheets=cssModel.allStyleSheets();for(const stylesheet of allStyleSheets){if(stylesheet.frameId!==this._selectedFrameId)
continue;const cssPromise=cssModel.classNamesPromise(stylesheet.id).then(classes=>completions.addAll(classes));promises.push(cssPromise);}
const domPromise=selectedNode.domModel().classNamesPromise(selectedNode.ownerDocument.id).then(classes=>completions.addAll(classes));promises.push(domPromise);return Promise.all(promises).then(()=>completions.valuesArray());}
_buildClassNameCompletions(expression,prefix,force){if(!prefix||force)
this._classNamesPromise=null;const selectedNode=UI.context.flavor(SDK.DOMNode);if(!selectedNode||(!prefix&&!force&&!expression.trim()))
return Promise.resolve([]);if(!this._classNamesPromise||this._selectedFrameId!==selectedNode.frameId())
this._classNamesPromise=this._getClassNames(selectedNode);return this._classNamesPromise.then(completions=>{const classesMap=this._nodeClasses((selectedNode));completions=completions.filter(value=>!classesMap.get(value));if(prefix[0]==='.')
completions=completions.map(value=>'.'+value);return completions.filter(value=>value.startsWith(prefix)).sort().map(completion=>({text:completion}));});}};;Elements.ElementStatePaneWidget=class extends UI.Widget{constructor(){super(true);this.registerRequiredCSS('elements/elementStatePaneWidget.css');this.contentElement.className='styles-element-state-pane';this.contentElement.createChild('div').createTextChild(Common.UIString('Force element state'));const table=createElementWithClass('table','source-code');const inputs=[];this._inputs=inputs;function clickListener(event){const node=UI.context.flavor(SDK.DOMNode);if(!node)
return;node.domModel().cssModel().forcePseudoState(node,event.target.state,event.target.checked);}
function createCheckbox(state){const td=createElement('td');const label=UI.CheckboxLabel.create(':'+state);const input=label.checkboxElement;input.state=state;input.addEventListener('click',clickListener,false);inputs.push(input);td.appendChild(label);return td;}
let tr=table.createChild('tr');tr.appendChild(createCheckbox.call(null,'active'));tr.appendChild(createCheckbox.call(null,'hover'));tr=table.createChild('tr');tr.appendChild(createCheckbox.call(null,'focus'));tr.appendChild(createCheckbox.call(null,'visited'));tr=table.createChild('tr');tr.appendChild(createCheckbox.call(null,'focus-within'));try{tr.querySelector(':focus-visible');tr.appendChild(createCheckbox.call(null,'focus-visible'));}catch(e){}
this.contentElement.appendChild(table);UI.context.addFlavorChangeListener(SDK.DOMNode,this._update,this);}
_updateModel(cssModel){if(this._cssModel===cssModel)
return;if(this._cssModel)
this._cssModel.removeEventListener(SDK.CSSModel.Events.PseudoStateForced,this._update,this);this._cssModel=cssModel;if(this._cssModel)
this._cssModel.addEventListener(SDK.CSSModel.Events.PseudoStateForced,this._update,this);}
wasShown(){this._update();}
_update(){if(!this.isShowing())
return;let node=UI.context.flavor(SDK.DOMNode);if(node)
node=node.enclosingElementOrSelf();this._updateModel(node?node.domModel().cssModel():null);if(node){const nodePseudoState=node.domModel().cssModel().pseudoState(node);for(const input of this._inputs){input.disabled=!!node.pseudoType();input.checked=nodePseudoState.indexOf(input.state)>=0;}}else{for(const input of this._inputs){input.disabled=true;input.checked=false;}}}};Elements.ElementStatePaneWidget.ButtonProvider=class{constructor(){this._button=new UI.ToolbarToggle(Common.UIString('Toggle Element State'),'');this._button.setText(Common.UIString(':hov'));this._button.addEventListener(UI.ToolbarButton.Events.Click,this._clicked,this);this._button.element.classList.add('monospace');this._view=new Elements.ElementStatePaneWidget();}
_clicked(){Elements.ElementsPanel.instance().showToolbarPane(!this._view.isShowing()?this._view:null,this._button);}
item(){return this._button;}};;Elements.ElementsTreeElementHighlighter=class{constructor(treeOutline){this._throttler=new Common.Throttler(100);this._treeOutline=treeOutline;this._treeOutline.addEventListener(UI.TreeOutline.Events.ElementExpanded,this._clearState,this);this._treeOutline.addEventListener(UI.TreeOutline.Events.ElementCollapsed,this._clearState,this);this._treeOutline.addEventListener(Elements.ElementsTreeOutline.Events.SelectedNodeChanged,this._clearState,this);SDK.targetManager.addModelListener(SDK.OverlayModel,SDK.OverlayModel.Events.HighlightNodeRequested,this._highlightNode,this);SDK.targetManager.addModelListener(SDK.OverlayModel,SDK.OverlayModel.Events.InspectModeWillBeToggled,this._clearState,this);}
_highlightNode(event){if(!Common.moduleSetting('highlightNodeOnHoverInOverlay').get())
return;const domNode=(event.data);this._throttler.schedule(callback.bind(this));this._pendingHighlightNode=this._treeOutline===Elements.ElementsTreeOutline.forDOMModel(domNode.domModel())?domNode:null;function callback(){this._highlightNodeInternal(this._pendingHighlightNode);delete this._pendingHighlightNode;return Promise.resolve();}}
_highlightNodeInternal(node){this._isModifyingTreeOutline=true;let treeElement=null;if(this._currentHighlightedElement){let currentTreeElement=this._currentHighlightedElement;while(currentTreeElement!==this._alreadyExpandedParentElement){if(currentTreeElement.expanded)
currentTreeElement.collapse();currentTreeElement=currentTreeElement.parent;}}
delete this._currentHighlightedElement;delete this._alreadyExpandedParentElement;if(node){let deepestExpandedParent=node;const treeElementSymbol=this._treeOutline.treeElementSymbol();while(deepestExpandedParent&&(!deepestExpandedParent[treeElementSymbol]||!deepestExpandedParent[treeElementSymbol].expanded))
deepestExpandedParent=deepestExpandedParent.parentNode;this._alreadyExpandedParentElement=deepestExpandedParent?deepestExpandedParent[treeElementSymbol]:this._treeOutline.rootElement();treeElement=this._treeOutline.createTreeElementFor(node);}
this._currentHighlightedElement=treeElement;this._treeOutline.setHoverEffect(treeElement);if(treeElement)
treeElement.reveal(true);this._isModifyingTreeOutline=false;}
_clearState(){if(this._isModifyingTreeOutline)
return;delete this._currentHighlightedElement;delete this._alreadyExpandedParentElement;delete this._pendingHighlightNode;}};;Runtime.cachedResources["elements/breadcrumbs.css"]="/*\n * Copyright 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.crumbs {\n display: inline-block;\n pointer-events: auto;\n cursor: default;\n white-space: nowrap;\n}\n\n.crumbs .crumb {\n display: inline-block;\n padding: 0 7px;\n line-height: 23px;\n white-space: nowrap;\n}\n\n.crumbs .crumb.collapsed > * {\n display: none;\n}\n\n.crumbs .crumb.collapsed::before {\n content: \"\\2026\";\n font-weight: bold;\n}\n\n.crumbs .crumb.compact .extra {\n display: none;\n}\n\n.crumb.selected, .crumb:hover {\n background-color: var(--toolbar-bg-color);\n}\n\n.crumb:not(.selected) .node-label-name {\n color: var(--dom-tag-name-color);\n}\n\n.crumb:not(.selected) .node-label-class {\n color: var(--dom-attribute-name-color);\n}\n\n/*# sourceURL=elements/breadcrumbs.css */";Runtime.cachedResources["elements/classesPaneWidget.css"]="/**\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.styles-element-classes-pane {\n background-color: var(--toolbar-bg-color);\n border-bottom: 1px solid rgb(189, 189, 189);\n padding: 6px 2px 2px;\n}\n\n.styles-element-classes-container {\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-start;\n}\n\n.styles-element-classes-pane [is=dt-checkbox] {\n margin-right: 15px;\n}\n\n.styles-element-classes-pane .title-container {\n padding-bottom: 2px;\n}\n\n.styles-element-classes-pane .new-class-input {\n padding-left: 3px;\n padding-right: 3px;\n overflow: hidden;\n border: 1px solid #ddd;\n line-height: 15px;\n margin-left: 3px;\n width: calc(100% - 7px);\n background-color: #fff;\n cursor: text;\n}\n\n/*# sourceURL=elements/classesPaneWidget.css */";Runtime.cachedResources["elements/computedStyleSidebarPane.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.computed-properties {\n -webkit-user-select: text;\n flex-shrink: 0;\n}\n\n.styles-sidebar-pane-toolbar {\n border-bottom: 1px solid #eee;\n flex-shrink: 0;\n}\n\n.styles-sidebar-pane-filter-box {\n flex: auto;\n display: flex;\n}\n\n.styles-sidebar-pane-filter-box > input {\n outline: none !important;\n border: none;\n width: 100%;\n background: white;\n padding-left: 4px;\n margin: 3px;\n}\n\n.styles-sidebar-pane-filter-box > input:focus,\n.styles-sidebar-pane-filter-box > input:not(:placeholder-shown) {\n box-shadow: var(--focus-ring-active-shadow);\n}\n\n/*# sourceURL=elements/computedStyleSidebarPane.css */";Runtime.cachedResources["elements/computedStyleWidgetTree.css"]="/*\n * Copyright (c) 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.computed-style-property {\n overflow: hidden;\n flex: auto;\n text-overflow: ellipsis;\n}\n\n.computed-style-property .property-name {\n width: 16em;\n text-overflow: ellipsis;\n overflow: hidden;\n max-width: 52%;\n display: inline-block;\n vertical-align: text-top;\n}\n\n.computed-style-property .property-value {\n margin-left: 2em;\n position: relative;\n}\n\n.computed-style-property .property-value-text {\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.tree-outline li:hover .goto-source-icon {\n display: block;\n margin-top: -2px;\n}\n\n.goto-source-icon {\n background-color: #5a5a5a;\n display: none;\n position: absolute;\n left: -16px;\n top: 0;\n}\n\n.goto-source-icon:hover {\n background-color: #333;\n}\n\n.computed-style-propert
async addObjects(objects){this.reset();await Promise.all(objects.map(obj=>obj?this._addObject(obj):Promise.resolve()));this.addEmptyHolderIfNeeded();this._eventListenersArrivedForTest();}
_addObject(object){let eventListeners;let frameworkEventListenersObject=null;const promises=[];const domDebuggerModel=object.runtimeModel().target().model(SDK.DOMDebuggerModel);if(domDebuggerModel)
promises.push(domDebuggerModel.eventListeners(object).then(storeEventListeners));promises.push(EventListeners.frameworkEventListeners(object).then(storeFrameworkEventListenersObject));return Promise.all(promises).then(markInternalEventListeners).then(addEventListeners.bind(this));function storeEventListeners(result){eventListeners=result;}
function storeFrameworkEventListenersObject(result){frameworkEventListenersObject=result;}
function markInternalEventListeners(){if(!frameworkEventListenersObject.internalHandlers)
return Promise.resolve(undefined);return frameworkEventListenersObject.internalHandlers.object().callFunctionJSON(isInternalEventListener,eventListeners.map(handlerArgument)).then(setIsInternal);function handlerArgument(listener){return SDK.RemoteObject.toCallArgument(listener.handler());}
function isInternalEventListener(){const isInternal=[];const internalHandlersSet=new Set(this);for(const handler of arguments)
isInternal.push(internalHandlersSet.has(handler));return isInternal;}
function setIsInternal(isInternal){for(let i=0;i<eventListeners.length;++i){if(isInternal[i])
eventListeners[i].markAsFramework();}}}
function addEventListeners(){this._addObjectEventListeners(object,eventListeners);this._addObjectEventListeners(object,frameworkEventListenersObject.eventListeners);}}
_addObjectEventListeners(object,eventListeners){if(!eventListeners)
return;for(const eventListener of eventListeners){const treeItem=this._getOrCreateTreeElementForType(eventListener.type());treeItem.addObjectEventListener(eventListener,object);}}
showFrameworkListeners(showFramework,showPassive,showBlocking){const eventTypes=this._treeOutline.rootElement().children();for(const eventType of eventTypes){let hiddenEventType=true;for(const listenerElement of eventType.children()){const listenerOrigin=listenerElement.eventListener().origin();let hidden=false;if(listenerOrigin===SDK.EventListener.Origin.FrameworkUser&&!showFramework)
hidden=true;if(listenerOrigin===SDK.EventListener.Origin.Framework&&showFramework)
hidden=true;if(!showPassive&&listenerElement.eventListener().passive())
hidden=true;if(!showBlocking&&!listenerElement.eventListener().passive())
hidden=true;listenerElement.hidden=hidden;hiddenEventType=hiddenEventType&&hidden;}
eventType.hidden=hiddenEventType;}}
_getOrCreateTreeElementForType(type){let treeItem=this._treeItemMap.get(type);if(!treeItem){treeItem=new EventListeners.EventListenersTreeElement(type,this._linkifier,this._changeCallback);this._treeItemMap.set(type,treeItem);treeItem.hidden=true;this._treeOutline.appendChild(treeItem);}
this._emptyHolder.remove();return treeItem;}
addEmptyHolderIfNeeded(){let allHidden=true;let firstVisibleChild=null;for(const eventType of this._treeOutline.rootElement().children()){eventType.hidden=!eventType.firstChild();allHidden=allHidden&&eventType.hidden;if(!firstVisibleChild&&!eventType.hidden)
firstVisibleChild=eventType;}
if(allHidden&&!this._emptyHolder.parentNode)
this.element.appendChild(this._emptyHolder);if(firstVisibleChild)
firstVisibleChild.select(true);}
reset(){const eventTypes=this._treeOutline.rootElement().children();for(const eventType of eventTypes)
eventType.removeChildren();this._linkifier.reset();}
_eventListenersArrivedForTest(){}};EventListeners.EventListenersTreeElement=class extends UI.TreeElement{constructor(type,linkifier,changeCallback){super(type);this.toggleOnClick=true;this._linkifier=linkifier;this._changeCallback=changeCallback;}
static comparator(element1,element2){if(element1.title===element2.title)
return 0;return element1.title>element2.title?1:-1;}
addObjectEventListener(eventListener,object){const treeElement=new EventListeners.ObjectEventListenerBar(eventListener,object,this._linkifier,this._changeCallback);this.appendChild((treeElement));}};EventListeners.ObjectEventListenerBar=class extends UI.TreeElement{constructor(eventListener,object,linkifier,changeCallback){super('',true);this._eventListener=eventListener;this.editable=false;this._setTitle(object,linkifier);this._changeCallback=changeCallback;}
onpopulate(){const properties=[];const eventListener=this._eventListener;const runtimeModel=eventListener.domDebuggerModel().runtimeModel();properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue('useCapture',eventListener.useCapture()));properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue('passive',eventListener.passive()));properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue('once',eventListener.once()));if(typeof eventListener.handler()!=='undefined')
properties.push(new SDK.RemoteObjectProperty('handler',eventListener.handler()));ObjectUI.ObjectPropertyTreeElement.populateWithProperties(this,properties,[],true,null);}
_setTitle(object,linkifier){const title=this.listItemElement.createChild('span');const subtitle=this.listItemElement.createChild('span','event-listener-tree-subtitle');subtitle.appendChild(linkifier.linkifyRawLocation(this._eventListener.location(),this._eventListener.sourceURL()));title.appendChild(ObjectUI.ObjectPropertiesSection.createValueElement(object,false,false));if(this._eventListener.canRemove()){const deleteButton=title.createChild('span','event-listener-button');deleteButton.textContent=Common.UIString('Remove');deleteButton.title=Common.UIString('Delete event listener');deleteButton.addEventListener('click',removeListener.bind(this),false);title.appendChild(deleteButton);}
if(this._eventListener.isScrollBlockingType()&&this._eventListener.canTogglePassive()){const passiveButton=title.createChild('span','event-listener-button');passiveButton.textContent=Common.UIString('Toggle Passive');passiveButton.title=Common.UIString('Toggle whether event listener is passive or blocking');passiveButton.addEventListener('click',togglePassiveListener.bind(this),false);title.appendChild(passiveButton);}
function removeListener(event){event.consume();this._removeListenerBar();this._eventListener.remove();}
function togglePassiveListener(event){event.consume();this._eventListener.togglePassive().then(this._changeCallback());}}
_removeListenerBar(){const parent=this.parent;parent.removeChild(this);if(!parent.childCount())
parent.collapse();let allHidden=true;for(let i=0;i<parent.childCount();++i){if(!parent.childAt(i).hidden)
allHidden=false;}
parent.hidden=allHidden;}
eventListener(){return this._eventListener;}};;EventListeners.FrameworkEventListenersObject;EventListeners.EventListenerObjectInInspectedPage;EventListeners.frameworkEventListeners=function(object){const domDebuggerModel=object.runtimeModel().target().model(SDK.DOMDebuggerModel);if(!domDebuggerModel){return Promise.resolve(({eventListeners:[],internalHandlers:null}));}
const listenersResult=({eventListeners:[]});return object.callFunction(frameworkEventListeners,undefined).then(assertCallFunctionResult).then(getOwnProperties).then(createEventListeners).then(returnResult).catchException(listenersResult);function getOwnProperties(object){return object.getOwnProperties(false);}
function createEventListeners(result){if(!result.properties)
throw new Error('Object properties is empty');const promises=[];for(const property of result.properties){if(property.name==='eventListeners'&&property.value)
promises.push(convertToEventListeners(property.value).then(storeEventListeners));if(property.name==='internalHandlers'&&property.value)
promises.push(convertToInternalHandlers(property.value).then(storeInternalHandlers));if(property.name==='errorString'&&property.value)
printErrorString(property.value);}
return(Promise.all(promises));}
function convertToEventListeners(pageEventListenersObject){return SDK.RemoteArray.objectAsArray(pageEventListenersObject).map(toEventListener).then(filterOutEmptyObjects);function toEventListener(listenerObject){let type;let useCapture;let passive;let once;let handler=null;let originalHandler=null;let location=null;let removeFunctionObject=null;const promises=[];promises.push(listenerObject.callFunctionJSON(truncatePageEventListener,undefined).then(storeTruncatedListener));function truncatePageEventListener(){return{type:this.type,useCapture:this.useCapture,passive:this.passive,once:this.once};}
function storeTruncatedListener(truncatedListener){type=truncatedListener.type;useCapture=truncatedListener.useCapture;passive=truncatedListener.passive;once=truncatedListener.once;}
promises.push(listenerObject.callFunction(handlerFunction).then(assertCallFunctionResult).then(storeOriginalHandler).then(toTargetFunction).then(storeFunctionWithDetails));function handlerFunction(){return this.handler;}
function storeOriginalHandler(functionObject){originalHandler=functionObject;return originalHandler;}
function storeFunctionWithDetails(functionObject){handler=functionObject;return(functionObject.debuggerModel().functionDetailsPromise(functionObject).then(storeFunctionDetails));}
function storeFunctionDetails(functionDetails){location=functionDetails?functionDetails.location:null;}
promises.push(listenerObject.callFunction(getRemoveFunction).then(assertCallFunctionResult).then(storeRemoveFunction));function getRemoveFunction(){return this.remove;}
function storeRemoveFunction(functionObject){if(functionObject.type!=='function')
return;removeFunctionObject=functionObject;}
return Promise.all(promises).then(createEventListener).catchException((null));function createEventListener(){if(!location)
throw new Error('Empty event listener\'s location');return new SDK.EventListener((domDebuggerModel),object,type,useCapture,passive,once,handler,originalHandler,location,removeFunctionObject,SDK.EventListener.Origin.FrameworkUser);}}}
function convertToInternalHandlers(pageInternalHandlersObject){return SDK.RemoteArray.objectAsArray(pageInternalHandlersObject).map(toTargetFunction).then(SDK.RemoteArray.createFromRemoteObjects);}
function toTargetFunction(functionObject){return SDK.RemoteFunction.objectAsFunction(functionObject).targetFunction();}
function storeEventListeners(eventListeners){listenersResult.eventListeners=eventListeners;}
function storeInternalHandlers(internalHandlers){listenersResult.internalHandlers=internalHandlers;}
function printErrorString(errorString){Common.console.error(String(errorString.value));}
function returnResult(){return listenersResult;}
function assertCallFunctionResult(result){if(result.wasThrown||!result.object)
throw new Error('Exception in callFunction or empty result');return result.object;}
function filterOutEmptyObjects(objects){return objects.filter(filterOutEmpty);function filterOutEmpty(object){return!!object;}}
function frameworkEventListeners(){const errorLines=[];let eventListeners=[];let internalHandlers=[];let fetchers=[jQueryFetcher];try{if(self.devtoolsFrameworkEventListeners&&isArrayLike(self.devtoolsFrameworkEventListeners))
fetchers=fetchers.concat(self.devtoolsFrameworkEventListeners);}catch(e){errorLines.push('devtoolsFrameworkEventListeners call produced error: '+toString(e));}
for(let i=0;i<fetchers.length;++i){try{const fetcherResult=fetchers[i](this);if(fetcherResult.eventListeners&&isArrayLike(fetcherResult.eventListeners)){eventListeners=eventListeners.concat(fetcherResult.eventListeners.map(checkEventListener).filter(nonEmptyObject));}
if(fetcherResult.internalHandlers&&isArrayLike(fetcherResult.internalHandlers)){internalHandlers=internalHandlers.concat(fetcherResult.internalHandlers.map(checkInternalHandler).filter(nonEmptyObject));}}catch(e){errorLines.push('fetcher call produced error: '+toString(e));}}
const result={eventListeners:eventListeners};if(internalHandlers.length)
result.internalHandlers=internalHandlers;if(errorLines.length){let errorString='Framework Event Listeners API Errors:\n\t'+errorLines.join('\n\t');errorString=errorString.substr(0,errorString.length-1);result.errorString=errorString;}
return result;function isArrayLike(obj){if(!obj||typeof obj!=='object')
return false;try{if(typeof obj.splice==='function'){const len=obj.length;return typeof len==='number'&&(len>>>0===len&&(len>0||1/len>0));}}catch(e){}
return false;}
function checkEventListener(eventListener){try{let errorString='';if(!eventListener)
errorString+='empty event listener, ';const type=eventListener.type;if(!type||(typeof type!=='string'))
errorString+='event listener\'s type isn\'t string or empty, ';const useCapture=eventListener.useCapture;if(typeof useCapture!=='boolean')
errorString+='event listener\'s useCapture isn\'t boolean or undefined, ';const passive=eventListener.passive;if(typeof passive!=='boolean')
errorString+='event listener\'s passive isn\'t boolean or undefined, ';const once=eventListener.once;if(typeof once!=='boolean')
errorString+='event listener\'s once isn\'t boolean or undefined, ';const handler=eventListener.handler;if(!handler||(typeof handler!=='function'))
errorString+='event listener\'s handler isn\'t a function or empty, ';const remove=eventListener.remove;if(remove&&(typeof remove!=='function'))
errorString+='event listener\'s remove isn\'t a function, ';if(!errorString){return{type:type,useCapture:useCapture,passive:passive,once:once,handler:handler,remove:remove};}else{errorLines.push(errorString.substr(0,errorString.length-2));return null;}}catch(e){errorLines.push(toString(e));return null;}}
function checkInternalHandler(handler){if(handler&&(typeof handler==='function'))
return handler;errorLines.push('internal handler isn\'t a function or empty');return null;}
function toString(obj){try{return''+obj;}catch(e){return'<error>';}}
function nonEmptyObject(obj){return!!obj;}
function jQueryFetcher(node){if(!node||!(node instanceof Node))
return{eventListeners:[]};const jQuery=(window['jQuery']);if(!jQuery||!jQuery.fn)
return{eventListeners:[]};const jQueryFunction=(jQuery);const data=jQuery._data||jQuery.data;const eventListeners=[];const internalHandlers=[];if(typeof data==='function'){const events=data(node,'events');for(const type in events){for(const key in events[type]){const frameworkListener=events[type][key];if(typeof frameworkListener==='object'||typeof frameworkListener==='function'){const listener={handler:frameworkListener.handler||frameworkListener,useCapture:true,passive:false,once:false,type:type};listener.remove=jQueryRemove.bind(node,frameworkListener.selector);eventListeners.push(listener);}}}
const nodeData=data(node);if(nodeData&&typeof nodeData.handle==='function')
internalHandlers.push(nodeData.handle);}
const entry=jQueryFunction(node)[0];if(entry){const entryEvents=entry['$events'];for(const type in entryEvents){const events=entryEvents[type];for(const key in events){if(typeof events[key]==='function'){const listener={handler:events[key],useCapture:true,passive:false,once:false,type:type};eventListeners.push(listener);}}}
if(entry&&entry['$handle'])
internalHandlers.push(entry['$handle']);}
return{eventListeners:eventListeners,internalHandlers:internalHandlers};}
function jQueryRemove(selector,type,handler){if(!this||!(this instanceof Node))
return;const node=(this);const jQuery=(window['jQuery']);if(!jQuery||!jQuery.fn)
return;const jQueryFunction=(jQuery);jQueryFunction(node).off(type,selector,handler);}}};;Runtime.cachedResources["event_listeners/eventListenersView.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tree-outline-disclosure li {\n padding: 2px 0 0 5px;\n overflow: hidden;\n display: list-item;\n min-height: 17px;\n}\n\n.tree-outline-disclosure > li {\n border-top: 1px solid #f0f0f0;\n}\n\n.tree-outline-disclosure > li:first-of-type {\n border-top: none;\n}\n\n.tree-outline-disclosure {\n padding-left: 0 !important;\n padding-right: 3px;\n}\n\n.tree-outline-disclosure li.parent::before {\n top: 0 !important;\n}\n\n.tree-outline-disclosure .name {\n color: rgb(136, 19, 145);\n}\n\n.event-listener-tree-subtitle {\n float: right;\n margin-left: 5px;\n}\n\n.event-listener-button {\n padding: 0 3px;\n background-color: #f2f2f2;\n border-radius: 3px;\n border: 1px solid #c3c3c3;\n margin-left: 10px;\n display: none;\n cursor: pointer;\n}\n\n.event-listener-button:hover {\n background-color: #e0e0e0;\n}\n\n.tree-outline-disclosure li:hover .event-listener-button {\n display: inline;\n}\n\n/*# sourceURL=event_listeners/eventListenersView.css */";Formatter.FormatterWorkerPool=class{constructor(){this._taskQueue=[];this._workerTasks=new Map();}
_createWorker(){const worker=new Common.Worker('formatter_worker');worker.onmessage=this._onWorkerMessage.bind(this,worker);worker.onerror=this._onWorkerError.bind(this,worker);return worker;}
_processNextTask(){if(!this._taskQueue.length)
return;let freeWorker=this._workerTasks.keysArray().find(worker=>!this._workerTasks.get(worker));if(!freeWorker&&this._workerTasks.size<Formatter.FormatterWorkerPool.MaxWorkers)
freeWorker=this._createWorker();if(!freeWorker)
return;const task=this._taskQueue.shift();this._workerTasks.set(freeWorker,task);freeWorker.postMessage({method:task.method,params:task.params});}
_onWorkerMessage(worker,event){const task=this._workerTasks.get(worker);if(task.isChunked&&event.data&&!event.data['isLastChunk']){task.callback(event.data);return;}
this._workerTasks.set(worker,null);this._processNextTask();task.callback(event.data?event.data:null);}
_onWorkerError(worker,event){console.error(event);const task=this._workerTasks.get(worker);worker.terminate();this._workerTasks.delete(worker);const newWorker=this._createWorker();this._workerTasks.set(newWorker,null);this._processNextTask();task.callback(null);}
_runChunkedTask(methodName,params,callback){const task=new Formatter.FormatterWorkerPool.Task(methodName,params,onData,true);this._taskQueue.push(task);this._processNextTask();function onData(data){if(!data){callback(true,null);return;}
const isLastChunk=!!data['isLastChunk'];const chunk=data['chunk'];callback(isLastChunk,chunk);}}
_runTask(methodName,params){let callback;const promise=new Promise(fulfill=>callback=fulfill);const task=new Formatter.FormatterWorkerPool.Task(methodName,params,callback,false);this._taskQueue.push(task);this._processNextTask();return promise;}
parseJSONRelaxed(content){return this._runTask('parseJSONRelaxed',{content:content});}
parseSCSS(content){return this._runTask('parseSCSS',{content:content}).then(rules=>rules||[]);}
format(mimeType,content,indentString){const parameters={mimeType:mimeType,content:content,indentString:indentString};return(this._runTask('format',parameters));}
javaScriptIdentifiers(content){return this._runTask('javaScriptIdentifiers',{content:content}).then(ids=>ids||[]);}
evaluatableJavaScriptSubstring(content){return this._runTask('evaluatableJavaScriptSubstring',{content:content}).then(text=>text||'');}
preprocessTopLevelAwaitExpressions(content){return this._runTask('preprocessTopLevelAwaitExpressions',{content:content}).then(text=>text||'');}
parseCSS(content,callback){this._runChunkedTask('parseCSS',{content:content},onDataChunk);function onDataChunk(isLastChunk,data){const rules=(data||[]);callback(isLastChunk,rules);}}
javaScriptOutline(content,callback){this._runChunkedTask('javaScriptOutline',{content:content},onDataChunk);function onDataChunk(isLastChunk,data){const items=(data||[]);callback(isLastChunk,items);}}
outlineForMimetype(content,mimeType,callback){switch(mimeType){case'text/html':case'text/javascript':this.javaScriptOutline(content,javaScriptCallback);return true;case'text/css':this.parseCSS(content,cssCallback);return true;}
return false;function javaScriptCallback(isLastChunk,items){callback(isLastChunk,items.map(item=>({line:item.line,column:item.column,title:item.name,subtitle:item.arguments})));}
function cssCallback(isLastChunk,rules){callback(isLastChunk,rules.map(rule=>({line:rule.lineNumber,column:rule.columnNumber,title:rule.selectorText||rule.atRule})));}}
findLastExpression(content){return(this._runTask('findLastExpression',{content}));}
findLastFunctionCall(content){return(this._runTask('findLastFunctionCall',{content}));}
argumentsList(content){return(this._runTask('argumentsList',{content}));}};Formatter.FormatterWorkerPool.MaxWorkers=2;Formatter.FormatterWorkerPool.Task=class{constructor(method,params,callback,isChunked){this.method=method;this.params=params;this.callback=callback;this.isChunked=isChunked;}};Formatter.FormatterWorkerPool.FormatResult=class{constructor(){this.content;this.mapping;}};Formatter.FormatterWorkerPool.FormatMapping;Formatter.FormatterWorkerPool.OutlineItem;Formatter.FormatterWorkerPool.JSOutlineItem=class{constructor(){this.name;this.arguments;this.line;this.column;}};Formatter.FormatterWorkerPool.TextRange;Formatter.FormatterWorkerPool.CSSProperty=class{constructor(){this.name;this.nameRange;this.value;this.valueRange;this.range;this.disabled;}};Formatter.FormatterWorkerPool.CSSStyleRule=class{constructor(){this.selectorText;this.styleRange;this.lineNumber;this.columnNumber;this.properties;}};Formatter.FormatterWorkerPool.CSSAtRule;Formatter.FormatterWorkerPool.CSSRule;Formatter.FormatterWorkerPool.SCSSProperty=class{constructor(){this.range;this.name;this.value;this.disabled;}};Formatter.FormatterWorkerPool.SCSSRule=class{constructor(){this.selectors;this.properties;this.styleRange;}};Formatter.formatterWorkerPool=function(){if(!Formatter._formatterWorkerPool)
Formatter._formatterWorkerPool=new Formatter.FormatterWorkerPool();return Formatter._formatterWorkerPool;};;Formatter.Formatter=function(){};Formatter.Formatter.format=function(contentType,mimeType,content,callback){if(contentType.isDocumentOrScriptOrStyleSheet())
new Formatter.ScriptFormatter(mimeType,content,callback);else
new Formatter.ScriptIdentityFormatter(mimeType,content,callback);};Formatter.Formatter.locationToPosition=function(lineEndings,lineNumber,columnNumber){const position=lineNumber?lineEndings[lineNumber-1]+1:0;return position+columnNumber;};Formatter.Formatter.positionToLocation=function(lineEndings,position){const lineNumber=lineEndings.upperBound(position-1);let columnNumber;if(!lineNumber)
columnNumber=position;else
columnNumber=position-lineEndings[lineNumber-1]-1;return[lineNumber,columnNumber];};Formatter.ScriptFormatter=class{constructor(mimeType,content,callback){content=content.replace(/\r\n?|[\n\u2028\u2029]/g,'\n').replace(/^\uFEFF/,'');this._callback=callback;this._originalContent=content;Formatter.formatterWorkerPool().format(mimeType,content,Common.moduleSetting('textEditorIndent').get()).then(this._didFormatContent.bind(this));}
_didFormatContent(formatResult){const sourceMapping=new Formatter.FormatterSourceMappingImpl(this._originalContent.computeLineEndings(),formatResult.content.computeLineEndings(),formatResult.mapping);this._callback(formatResult.content,sourceMapping);}};Formatter.ScriptIdentityFormatter=class{constructor(mimeType,content,callback){callback(content,new Formatter.IdentityFormatterSourceMapping());}};Formatter.FormatterSourceMapping=function(){};Formatter.FormatterSourceMapping.prototype={originalToFormatted(lineNumber,columnNumber){},formattedToOriginal(lineNumber,columnNumber){}};Formatter.IdentityFormatterSourceMapping=class{originalToFormatted(lineNumber,columnNumber){return[lineNumber,columnNumber||0];}
formattedToOriginal(lineNumber,columnNumber){return[lineNumber,columnNumber||0];}};Formatter.FormatterSourceMappingImpl=class{constructor(originalLineEndings,formattedLineEndings,mapping){this._originalLineEndings=originalLineEndings;this._formattedLineEndings=formattedLineEndings;this._mapping=mapping;}
originalToFormatted(lineNumber,columnNumber){const originalPosition=Formatter.Formatter.locationToPosition(this._originalLineEndings,lineNumber,columnNumber||0);const formattedPosition=this._convertPosition(this._mapping.original,this._mapping.formatted,originalPosition||0);return Formatter.Formatter.positionToLocation(this._formattedLineEndings,formattedPosition);}
formattedToOriginal(lineNumber,columnNumber){const formattedPosition=Formatter.Formatter.locationToPosition(this._formattedLineEndings,lineNumber,columnNumber||0);const originalPosition=this._convertPosition(this._mapping.formatted,this._mapping.original,formattedPosition);return Formatter.Formatter.positionToLocation(this._originalLineEndings,originalPosition||0);}
_convertPosition(positions1,positions2,position){const index=positions1.upperBound(position)-1;let convertedPosition=positions2[index]+position-positions1[index];if(index<positions2.length-1&&convertedPosition>positions2[index+1])
convertedPosition=positions2[index+1];return convertedPosition;}};;HARImporter.HARBase=class{constructor(data){if(!data||typeof data!=='object')
throw'First parameter is expected to be an object';}
static _safeDate(data){const date=new Date(data);if(!Number.isNaN(date.getTime()))
return date;throw'Invalid date format';}
static _safeNumber(data){const result=Number(data);if(!Number.isNaN(result))
return result;throw'Casting to number results in NaN';}
static _optionalNumber(data){return data!==undefined?HARImporter.HARBase._safeNumber(data):undefined;}
static _optionalString(data){return data!==undefined?String(data):undefined;}
customAsString(name){const value=(this)['_'+name];return value!==undefined?String(value):undefined;}
customAsNumber(name){let value=(this)['_'+name];if(value===undefined)
return;value=Number(value);if(Number.isNaN(value))
return;return value;}
customAsArray(name){const value=(this)['_'+name];return Array.isArray(value)?value:undefined;}};HARImporter.HARRoot=class extends HARImporter.HARBase{constructor(data){super(data);this.log=new HARImporter.HARLog(data['log']);}};HARImporter.HARLog=class extends HARImporter.HARBase{constructor(data){super(data);this.version=String(data['version']);this.creator=new HARImporter.HARCreator(data['creator']);this.browser=data['browser']?new HARImporter.HARCreator(data['browser']):undefined;this.pages=Array.isArray(data['pages'])?data['pages'].map(page=>new HARImporter.HARPage(page)):[];if(!Array.isArray(data['entries']))
throw'log.entries is expected to be an array';this.entries=data['entries'].map(entry=>new HARImporter.HAREntry(entry));this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARCreator=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.version=String(data['version']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARPage=class extends HARImporter.HARBase{constructor(data){super(data);this.startedDateTime=HARImporter.HARBase._safeDate(data['startedDateTime']);this.id=String(data['id']);this.title=String(data['title']);this.pageTimings=new HARImporter.HARPageTimings(data['pageTimings']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARPageTimings=class extends HARImporter.HARBase{constructor(data){super(data);this.onContentLoad=HARImporter.HARBase._optionalNumber(data['onContentLoad']);this.onLoad=HARImporter.HARBase._optionalNumber(data['onLoad']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HAREntry=class extends HARImporter.HARBase{constructor(data){super(data);this.pageref=HARImporter.HARBase._optionalString(data['pageref']);this.startedDateTime=HARImporter.HARBase._safeDate(data['startedDateTime']);this.time=HARImporter.HARBase._safeNumber(data['time']);this.request=new HARImporter.HARRequest(data['request']);this.response=new HARImporter.HARResponse(data['response']);this.cache={};this.timings=new HARImporter.HARTimings(data['timings']);this.serverIPAddress=HARImporter.HARBase._optionalString(data['serverIPAddress']);this.connection=HARImporter.HARBase._optionalString(data['connection']);this.comment=HARImporter.HARBase._optionalString(data['comment']);this._fromCache=HARImporter.HARBase._optionalString(data['_fromCache']);if(data['_initiator'])
this._initiator=new HARImporter.HARInitiator(data['_initiator']);this._priority=HARImporter.HARBase._optionalString(data['_priority']);this._resourceType=HARImporter.HARBase._optionalString(data['_resourceType']);if(Array.isArray(data['_webSocketMessages']))
this._webSocketMessages=data['_webSocketMessages'].map(message=>new HARImporter.HARWebSocketMessage(message));}};HARImporter.HARRequest=class extends HARImporter.HARBase{constructor(data){super(data);this.method=String(data['method']);this.url=String(data['url']);this.httpVersion=String(data['httpVersion']);this.cookies=Array.isArray(data['cookies'])?data['cookies'].map(cookie=>new HARImporter.HARCookie(cookie)):[];this.headers=Array.isArray(data['headers'])?data['headers'].map(header=>new HARImporter.HARHeader(header)):[];this.queryString=Array.isArray(data['queryString'])?data['queryString'].map(qs=>new HARImporter.HARQueryString(qs)):[];this.postData=data['postData']?new HARImporter.HARPostData(data['postData']):undefined;this.headersSize=HARImporter.HARBase._safeNumber(data['headersSize']);this.bodySize=HARImporter.HARBase._safeNumber(data['bodySize']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARResponse=class extends HARImporter.HARBase{constructor(data){super(data);this.status=HARImporter.HARBase._safeNumber(data['status']);this.statusText=String(data['statusText']);this.httpVersion=String(data['httpVersion']);this.cookies=Array.isArray(data['cookies'])?data['cookies'].map(cookie=>new HARImporter.HARCookie(cookie)):[];this.headers=Array.isArray(data['headers'])?data['headers'].map(header=>new HARImporter.HARHeader(header)):[];this.content=new HARImporter.HARContent(data['content']);this.redirectURL=String(data['redirectURL']);this.headersSize=HARImporter.HARBase._safeNumber(data['headersSize']);this.bodySize=HARImporter.HARBase._safeNumber(data['bodySize']);this.comment=HARImporter.HARBase._optionalString(data['comment']);this._transferSize=HARImporter.HARBase._optionalNumber(data['_transferSize']);this._error=HARImporter.HARBase._optionalString(data['_error']);}};HARImporter.HARCookie=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.value=String(data['value']);this.path=HARImporter.HARBase._optionalString(data['path']);this.domain=HARImporter.HARBase._optionalString(data['domain']);this.expires=data['expires']?HARImporter.HARBase._safeDate(data['expires']):undefined;this.httpOnly=data['httpOnly']!==undefined?!!data['httpOnly']:undefined;this.secure=data['secure']!==undefined?!!data['secure']:undefined;this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARHeader=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.value=String(data['value']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARQueryString=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.value=String(data['value']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARPostData=class extends HARImporter.HARBase{constructor(data){super(data);this.mimeType=String(data['mimeType']);this.params=Array.isArray(data['params'])?data['params'].map(param=>new HARImporter.HARParam(param)):[];this.text=String(data['text']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARParam=class extends HARImporter.HARBase{constructor(data){super(data);this.name=String(data['name']);this.value=HARImporter.HARBase._optionalString(data['value']);this.fileName=HARImporter.HARBase._optionalString(data['fileName']);this.contentType=HARImporter.HARBase._optionalString(data['contentType']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARContent=class extends HARImporter.HARBase{constructor(data){super(data);this.size=HARImporter.HARBase._safeNumber(data['size']);this.compression=HARImporter.HARBase._optionalNumber(data['compression']);this.mimeType=String(data['mimeType']);this.text=HARImporter.HARBase._optionalString(data['text']);this.encoding=HARImporter.HARBase._optionalString(data['encoding']);this.comment=HARImporter.HARBase._optionalString(data['comment']);}};HARImporter.HARTimings=class extends HARImporter.HARBase{constructor(da
pages.set(page.id,page);log.entries.sort((a,b)=>a.startedDateTime-b.startedDateTime);const pageLoads=new Map();const requests=[];for(const entry of log.entries){let pageLoad=pageLoads.get(entry.pageref);const documentURL=pageLoad?pageLoad.mainRequest.url():entry.request.url;let initiator=null;if(entry._initiator){initiator={type:entry._initiator.type,url:entry._initiator.url,lineNumber:entry._initiator.lineNumber};}
const request=new SDK.NetworkRequest('har-'+requests.length,entry.request.url,documentURL,'','',initiator);const page=pages.get(entry.pageref);if(!pageLoad&&page){pageLoad=HARImporter.Importer._buildPageLoad(page,request);pageLoads.set(entry.pageref,pageLoad);}
HARImporter.Importer._fillRequestFromHAREntry(request,entry,pageLoad);if(pageLoad)
pageLoad.bindRequest(request);requests.push(request);}
return requests;}
static _buildPageLoad(page,mainRequest){const pageLoad=new SDK.NetworkLog.PageLoad(mainRequest);pageLoad.startTime=page.startedDateTime;pageLoad.contentLoadTime=page.pageTimings.onContentLoad*1000;pageLoad.loadTime=page.pageTimings.onLoad*1000;return pageLoad;}
static _fillRequestFromHAREntry(request,entry,pageLoad){if(entry.request.postData)
request.setRequestFormData(true,entry.request.postData.text);else
request.setRequestFormData(false,null);request.connectionId=entry.connection||'';request.requestMethod=entry.request.method;request.setRequestHeaders(entry.request.headers);if(entry.response.content.mimeType&&entry.response.content.mimeType!=='x-unknown')
request.mimeType=entry.response.content.mimeType;request.responseHeaders=entry.response.headers;request.statusCode=entry.response.status;request.statusText=entry.response.statusText;let protocol=entry.response.httpVersion.toLowerCase();if(protocol==='http/2.0')
protocol='h2';request.protocol=protocol.replace(/^http\/2\.0?\+quic/,'http/2+quic');const issueTime=entry.startedDateTime.getTime()/1000;request.setIssueTime(issueTime,issueTime);const contentSize=entry.response.content.size>0?entry.response.content.size:0;const headersSize=entry.response.headersSize>0?entry.response.headersSize:0;const bodySize=entry.response.bodySize>0?entry.response.bodySize:0;request.resourceSize=contentSize||(headersSize+bodySize);let transferSize=entry.response.customAsNumber('transferSize');if(transferSize===undefined)
transferSize=entry.response.headersSize+entry.response.bodySize;request.setTransferSize(transferSize>=0?transferSize:0);const fromCache=entry.customAsString('fromCache');if(fromCache==='memory')
request.setFromMemoryCache();else if(fromCache==='disk')
request.setFromDiskCache();const contentData={error:null,content:null,encoded:entry.response.content.encoding==='base64'};if(entry.response.content.text!==undefined)
contentData.content=entry.response.content.text;request.setContentDataProvider(async()=>contentData);HARImporter.Importer._setupTiming(request,issueTime,entry.time,entry.timings);request.setRemoteAddress(entry.serverIPAddress||'',80);request.setResourceType(HARImporter.Importer._getResourceType(request,entry,pageLoad));const priority=entry.customAsString('priority');if(Protocol.Network.ResourcePriority.hasOwnProperty(priority))
request.setPriority((priority));const messages=entry.customAsArray('webSocketMessages');if(messages){for(const message of messages){if(message.time===undefined)
continue;if(!Object.values(SDK.NetworkRequest.WebSocketFrameType).includes(message.type))
continue;if(message.opcode===undefined)
continue;if(message.data===undefined)
continue;const mask=message.type===SDK.NetworkRequest.WebSocketFrameType.Send;request.addFrame({time:message.time,text:message.data,opCode:message.opcode,mask:mask,type:message.type});}}
request.finished=true;}
static _getResourceType(request,entry,pageLoad){const customResourceTypeName=entry.customAsString('resourceType');if(customResourceTypeName){const customResourceType=Common.ResourceType.fromName(customResourceTypeName);if(customResourceType)
return customResourceType;}
if(pageLoad&&pageLoad.mainRequest===request)
return Common.resourceTypes.Document;const resourceTypeFromMime=Common.ResourceType.fromMimeType(entry.response.content.mimeType);if(resourceTypeFromMime!==Common.resourceTypes.Other)
return resourceTypeFromMime;const resourceTypeFromUrl=Common.ResourceType.fromURL(entry.request.url);if(resourceTypeFromUrl)
return resourceTypeFromUrl;return Common.resourceTypes.Other;}
static _setupTiming(request,issueTime,entryTotalDuration,timings){function accumulateTime(timing){if(timing===undefined||timing<0)
return-1;lastEntry+=timing;return lastEntry;}
let lastEntry=timings.blocked>=0?timings.blocked:0;const proxy=timings.customAsNumber('blocked_proxy')||-1;const queueing=timings.customAsNumber('blocked_queueing')||-1;const ssl=timings.ssl>=0?timings.ssl:0;if(timings.connect>0)
timings.connect-=ssl;const timing={proxyStart:proxy>0?lastEntry-proxy:-1,proxyEnd:proxy>0?lastEntry:-1,requestTime:issueTime+(queueing>0?queueing:0)/1000,dnsStart:timings.dns>=0?lastEntry:-1,dnsEnd:accumulateTime(timings.dns),connectStart:timings.connect>=0?lastEntry:-1,connectEnd:accumulateTime(timings.connect)+ssl,sslStart:timings.ssl>=0?lastEntry:-1,sslEnd:accumulateTime(timings.ssl),workerStart:-1,workerReady:-1,sendStart:timings.send>=0?lastEntry:-1,sendEnd:accumulateTime(timings.send),pushStart:0,pushEnd:0,receiveHeadersEnd:accumulateTime(timings.wait)};accumulateTime(timings.receive);request.timing=timing;request.endTime=issueTime+Math.max(entryTotalDuration,lastEntry)/1000;}};;HeapSnapshotModel.HeapSnapshotProgressEvent={Update:'ProgressUpdate',BrokenSnapshot:'BrokenSnapshot'};HeapSnapshotModel.baseSystemDistance=100000000;HeapSnapshotModel.AllocationNodeCallers=class{constructor(nodesWithSingleCaller,branchingCallers){this.nodesWithSingleCaller=nodesWithSingleCaller;this.branchingCallers=branchingCallers;}};HeapSnapshotModel.SerializedAllocationNode=class{constructor(nodeId,functionName,scriptName,scriptId,line,column,count,size,liveCount,liveSize,hasChildren){this.id=nodeId;this.name=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;this.count=count;this.size=size;this.liveCount=liveCount;this.liveSize=liveSize;this.hasChildren=hasChildren;}};HeapSnapshotModel.AllocationStackFrame=class{constructor(functionName,scriptName,scriptId,line,column){this.functionName=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;}};HeapSnapshotModel.Node=class{constructor(id,name,distance,nodeIndex,retainedSize,selfSize,type){this.id=id;this.name=name;this.distance=distance;this.nodeIndex=nodeIndex;this.retainedSize=retainedSize;this.selfSize=selfSize;this.type=type;this.canBeQueried=false;this.detachedDOMTreeNode=false;}};HeapSnapshotModel.Edge=class{constructor(name,node,type,edgeIndex){this.name=name;this.node=node;this.type=type;this.edgeIndex=edgeIndex;}};HeapSnapshotModel.Aggregate=class{constructor(){this.count;this.distance;this.self;this.maxRet;this.type;this.name;this.idxs;}};HeapSnapshotModel.AggregateForDiff=class{constructor(){this.indexes=[];this.ids=[];this.selfSizes=[];}};HeapSnapshotModel.Diff=class{constructor(){this.addedCount=0;this.removedCount=0;this.addedSize=0;this.removedSize=0;this.deletedIndexes=[];this.addedIndexes=[];}};HeapSnapshotModel.DiffForClass=class{constructor(){this.addedCount;this.removedCount;this.addedSize;this.removedSize;this.deletedIndexes;this.addedIndexes;this.countDelta;this.sizeDelta;}};HeapSnapshotModel.ComparatorConfig=class{constructor(){this.fieldName1;this.ascending1;this.fieldName2;this.ascending2;}};HeapSnapshotModel.WorkerCommand=class{constructor(){this.callId;this.disposition;this.objectId;this.newObjectId;this.methodName;this.methodArguments;this.source;}};HeapSnapshotModel.ItemsRange=class{constructor(startPosition,endPosition,totalLength,items){this.startPosition=startPosition;this.endPosition=endPosition;this.totalLength=totalLength;this.items=items;}};HeapSnapshotModel.StaticData=class{constructor(nodeCount,rootNodeIndex,totalSize,maxJSObjectId){this.nodeCount=nodeCount;this.rootNodeIndex=rootNodeIndex;this.totalSize=totalSize;this.maxJSObjectId=maxJSObjectId;}};HeapSnapshotModel.Statistics=class{constructor(){this.total;this.v8heap;this.native;this.code;this.jsArrays;this.strings;this.system;}};HeapSnapshotModel.NodeFilter=class{constructor(minNodeId,maxNodeId){this.minNodeId=minNodeId;this.maxNodeId=maxNodeId;this.allocationNodeId;}
equals(o){return this.minNodeId===o.minNodeId&&this.maxNodeId===o.maxNodeId&&this.allocationNodeId===o.allocationNodeId;}};HeapSnapshotModel.SearchConfig=class{constructor(query,caseSensitive,isRegex,shouldJump,jumpBackward){this.query=query;this.caseSensitive=caseSensitive;this.isRegex=isRegex;this.shouldJump=shouldJump;this.jumpBackward=jumpBackward;}};HeapSnapshotModel.Samples=class{constructor(timestamps,lastAssignedIds,sizes){this.timestamps=timestamps;this.lastAssignedIds=lastAssignedIds;this.sizes=sizes;}};HeapSnapshotModel.Location=class{constructor(scriptId,lineNumber,columnNumber){this.scriptId=scriptId;this.lineNumber=lineNumber;this.columnNumber=columnNumber;}};;Help.latestReleaseNote=function(){if(!Help._latestReleaseNote){Help._latestReleaseNote=Help.releaseNoteText.reduce((acc,note)=>note.version>acc.version?note:acc);}
return Help._latestReleaseNote;};Help._showReleaseNoteIfNeeded=function(){Help._innerShowReleaseNoteIfNeeded(Help._releaseNoteVersionSetting.get(),Help.latestReleaseNote().version,Common.settings.moduleSetting('help.show-release-note').get());};Help._innerShowReleaseNoteIfNeeded=function(lastSeenVersion,latestVersion,showReleaseNote){if(!lastSeenVersion){Help._releaseNoteVersionSetting.set(latestVersion);return;}
if(!showReleaseNote)
return;if(lastSeenVersion>=latestVersion)
return;Help._releaseNoteVersionSetting.set(latestVersion);UI.viewManager.showView(Help.releaseNoteViewId,true);};Help.releaseNoteViewId='release-note';Help.ReleaseNoteHighlight;Help.ReleaseNote;Help.HelpLateInitialization=class{run(){if(!Host.isUnderTest())
Help._showReleaseNoteIfNeeded();}};Help.ReleaseNotesActionDelegate=class{handleAction(context,actionId){InspectorFrontendHost.openInNewTab(Help.latestReleaseNote().link);return true;}};Help._releaseNoteVersionSetting=Common.settings.createSetting('releaseNoteVersionSeen',0);;Help.ReleaseNoteView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('help/releaseNote.css');const releaseNoteElement=this._createReleaseNoteElement(Help.latestReleaseNote());const topSection=this.contentElement.createChild('div','release-note-top-section');topSection.textContent=Common.UIString(Help.latestReleaseNote().header);this.contentElement.appendChild(releaseNoteElement);}
_createReleaseNoteElement(releaseNote){const hbox=createElementWithClass('div','hbox');const container=hbox.createChild('div','release-note-container');const contentContainer=container.createChild('ul');for(const highlight of releaseNote.highlights){const listItem=contentContainer.createChild('li');const title=UI.XLink.create(highlight.link,highlight.title+' ','release-note-title');title.title='';listItem.appendChild(title);const subtitle=UI.XLink.create(highlight.link,highlight.subtitle+' ','release-note-subtitle');subtitle.title='';listItem.appendChild(subtitle);}
const actionContainer=container.createChild('div','release-note-action-container');actionContainer.appendChild(UI.createTextButton(Common.UIString('Learn more'),event=>{event.consume(true);InspectorFrontendHost.openInNewTab(releaseNote.link);}));actionContainer.appendChild(UI.createTextButton(Common.UIString('Close'),event=>{event.consume(true);UI.inspectorView.closeDrawerTab(Help.releaseNoteViewId,true);},'close-release-note'));const imageLink=UI.XLink.create(releaseNote.link,' ');imageLink.classList.add('release-note-image');imageLink.title='';hbox.appendChild(imageLink);const image=imageLink.createChild('img');image.src='Images/whatsnew.png';return hbox;}};;const continueToHereShortcut=Host.isMac()?'Command':'Control';const networkSearchShortcut=Host.isMac()?'Command + F':'Control + F';const commandMenuShortcut=Host.isMac()?'Command + Shift + P':'Control + Shift + P';Help.releaseNoteText=[{version:18,header:'Highlights from the Chrome 76 update',highlights:[{title:'Autocomplete with CSS keyword values',subtitle:'Typing a keyword value like "bold" in the Styles pane now autocompletes to "font-weight: bold".',link:'https://developers.google.com/web/updates/2019/05/devtools#values',},{title:'A new UI for network settings',subtitle:'The "Use large request rows", "Group by frame", "Show overview", and "Capture screenshots" options have moved to the new Network Settings pane.',link:'https://developers.google.com/web/updates/2019/05/devtools#settings',},{title:'WebSocket messages in HAR exports',subtitle:'Network logs downloaded from the Network panel now include WebSocket messages.',link:'https://developers.google.com/web/updates/2019/05/devtools#websocket',},],link:'https://developers.google.com/web/updates/2019/05/devtools',},{version:17,header:'Highlights from the Chrome 75 update',highlights:[{title:'Meaningful preset values when autocompleting CSS functions',subtitle:'Properties like "filter" that take functions for values now autocomplete to previewable values in the Styles pane.',link:'https://developers.google.com/web/updates/2019/04/devtools#presets',},{title:'Clear site data from the Command Menu',subtitle:`Press ${commandMenuShortcut} and run the "Clear Site Data" command to clear cookies, storage, and more.`,link:'https://developers.google.com/web/updates/2019/04/devtools#clear',},{title:'View all IndexedDB databases',subtitle:'The IndexedDB pane now shows databases for all origins rather than just the main origin.',link:'https://developers.google.com/web/updates/2019/04/devtools#indexeddb',},{title:'View a resource\'s uncompressed size on hover',subtitle:'Hover over the Size column in the Network panel to view a resource\'s full size.',link:'https://developers.google.com/web/updates/2019/04/devtools#uncompressed',},{title:'Inline breakpoints in the Breakpoints pane',subtitle:'When you\'ve got multiple breakpoints on a single line of code, the Breakpoints pane now lets you manage each one independently.',link:'https://developers.google.com/web/updates/2019/04/devtools#inline',},],link:'https://developers.google.com/web/updates/2019/04/devtools',},{version:16,header:'Highlights from the Chrome 74 update',highlights:[{title:'Highlight all nodes affected by CSS property',subtitle:'Hover over a CSS property like padding or margin in the Styles pane to highlight all nodes affected by that declaration.',link:'https://developers.google.com/web/updates/2019/03/devtools#highlight',},{title:'Lighthouse v4 in the Audits panel',subtitle:'Featuring a new "tap targets" audit for checking that mobile links and buttons are properly sized, and a new UI for PWA reports.',link:'https://developers.google.com/web/updates/2019/03/devtools#lighthouse',},{title:'WebSocket binary message viewer',subtitle:'Click a WebSocket connection in the Network Log, go to the Messages tab, then click a binary message to view its contents.',link:'https://developers.google.com/web/updates/2019/03/devtools#binary',},{title:'Capture area screenshot in the Command Menu',subtitle:'Press '+commandMenuShortcut+', run the "Capture area screenshot" command,
this._curveUI=new InlineEditor.BezierUI(150,250,50,7,true);this._curve=this._outerContainer.createSVGChild('svg','bezier-curve');UI.installDragHandle(this._curve,this._dragStart.bind(this),this._dragMove.bind(this),this._dragEnd.bind(this),'default');this._header=this.contentElement.createChild('div','bezier-header');const minus=this._createPresetModifyIcon(this._header,'bezier-preset-minus','M 12 6 L 8 10 L 12 14');const plus=this._createPresetModifyIcon(this._header,'bezier-preset-plus','M 8 6 L 12 10 L 8 14');minus.addEventListener('click',this._presetModifyClicked.bind(this,false));plus.addEventListener('click',this._presetModifyClicked.bind(this,true));this._label=this._header.createChild('span','source-code bezier-display-value');}
setBezier(bezier){if(!bezier)
return;this._bezier=bezier;this._updateUI();}
bezier(){return this._bezier;}
wasShown(){this._unselectPresets();for(const category of this._presetCategories){for(let i=0;i<category.presets.length;i++){if(this._bezier.asCSSText()===category.presets[i].value){category.presetIndex=i;this._presetCategorySelected(category);}}}
this._updateUI();this._startPreviewAnimation();}
_onchange(){this._updateUI();this.dispatchEventToListeners(InlineEditor.BezierEditor.Events.BezierChanged,this._bezier.asCSSText());}
_updateUI(){const labelText=this._selectedCategory?this._selectedCategory.presets[this._selectedCategory.presetIndex].name:this._bezier.asCSSText().replace(/\s(-\d\.\d)/g,'$1');this._label.textContent=Common.UIString(labelText);this._curveUI.drawCurve(this._bezier,this._curve);this._previewOnion.removeChildren();}
_dragStart(event){this._mouseDownPosition=new UI.Geometry.Point(event.x,event.y);const ui=this._curveUI;this._controlPosition=new UI.Geometry.Point(Number.constrain((event.offsetX-ui.radius)/ui.curveWidth(),0,1),(ui.curveHeight()+ui.marginTop+ui.radius-event.offsetY)/ui.curveHeight());const firstControlPointIsCloser=this._controlPosition.distanceTo(this._bezier.controlPoints[0])<this._controlPosition.distanceTo(this._bezier.controlPoints[1]);this._selectedPoint=firstControlPointIsCloser?0:1;this._bezier.controlPoints[this._selectedPoint]=this._controlPosition;this._unselectPresets();this._onchange();event.consume(true);return true;}
_updateControlPosition(mouseX,mouseY){const deltaX=(mouseX-this._mouseDownPosition.x)/this._curveUI.curveWidth();const deltaY=(mouseY-this._mouseDownPosition.y)/this._curveUI.curveHeight();const newPosition=new UI.Geometry.Point(Number.constrain(this._controlPosition.x+deltaX,0,1),this._controlPosition.y-deltaY);this._bezier.controlPoints[this._selectedPoint]=newPosition;}
_dragMove(event){this._updateControlPosition(event.x,event.y);this._onchange();}
_dragEnd(event){this._updateControlPosition(event.x,event.y);this._onchange();this._startPreviewAnimation();}
_createCategory(presetGroup){const presetElement=createElementWithClass('div','bezier-preset-category');const iconElement=presetElement.createSVGChild('svg','bezier-preset monospace');const category={presets:presetGroup,presetIndex:0,icon:presetElement};this._presetUI.drawCurve(UI.Geometry.CubicBezier.parse(category.presets[0].value),iconElement);iconElement.addEventListener('click',this._presetCategorySelected.bind(this,category));return category;}
_createPresetModifyIcon(parentElement,className,drawPath){const icon=parentElement.createSVGChild('svg','bezier-preset-modify '+className);icon.setAttribute('width',20);icon.setAttribute('height',20);const path=icon.createSVGChild('path');path.setAttribute('d',drawPath);return icon;}
_unselectPresets(){for(const category of this._presetCategories)
category.icon.classList.remove('bezier-preset-selected');delete this._selectedCategory;this._header.classList.remove('bezier-header-active');}
_presetCategorySelected(category,event){if(this._selectedCategory===category)
return;this._unselectPresets();this._header.classList.add('bezier-header-active');this._selectedCategory=category;this._selectedCategory.icon.classList.add('bezier-preset-selected');this.setBezier(UI.Geometry.CubicBezier.parse(category.presets[category.presetIndex].value));this._onchange();this._startPreviewAnimation();if(event)
event.consume(true);}
_presetModifyClicked(intensify,event){if(!this._selectedCategory)
return;const length=this._selectedCategory.presets.length;this._selectedCategory.presetIndex=(this._selectedCategory.presetIndex+(intensify?1:-1)+length)%length;this.setBezier(UI.Geometry.CubicBezier.parse(this._selectedCategory.presets[this._selectedCategory.presetIndex].value));this._onchange();this._startPreviewAnimation();}
_startPreviewAnimation(){if(this._previewAnimation)
this._previewAnimation.cancel();const animationDuration=1600;const numberOnionSlices=20;const keyframes=[{offset:0,transform:'translateX(0px)',easing:this._bezier.asCSSText(),opacity:1},{offset:0.9,transform:'translateX(218px)',opacity:1},{offset:1,transform:'translateX(218px)',opacity:0}];this._previewAnimation=this._previewElement.animate(keyframes,animationDuration);this._previewOnion.removeChildren();for(let i=0;i<=numberOnionSlices;i++){const slice=this._previewOnion.createChild('div','bezier-preview-animation');const player=slice.animate([{transform:'translateX(0px)',easing:this._bezier.asCSSText()},{transform:'translateX(218px)'}],{duration:animationDuration,fill:'forwards'});player.pause();player.currentTime=animationDuration*i/numberOnionSlices;}}};InlineEditor.BezierEditor.Events={BezierChanged:Symbol('BezierChanged')};InlineEditor.BezierEditor.Presets=[[{name:'ease-in-out',value:'ease-in-out'},{name:'In Out · Sine',value:'cubic-bezier(0.45, 0.05, 0.55, 0.95)'},{name:'In Out · Quadratic',value:'cubic-bezier(0.46, 0.03, 0.52, 0.96)'},{name:'In Out · Cubic',value:'cubic-bezier(0.65, 0.05, 0.36, 1)'},{name:'Fast Out, Slow In',value:'cubic-bezier(0.4, 0, 0.2, 1)'},{name:'In Out · Back',value:'cubic-bezier(0.68, -0.55, 0.27, 1.55)'}],[{name:'Fast Out, Linear In',value:'cubic-bezier(0.4, 0, 1, 1)'},{name:'ease-in',value:'ease-in'},{name:'In · Sine',value:'cubic-bezier(0.47, 0, 0.75, 0.72)'},{name:'In · Quadratic',value:'cubic-bezier(0.55, 0.09, 0.68, 0.53)'},{name:'In · Cubic',value:'cubic-bezier(0.55, 0.06, 0.68, 0.19)'},{name:'In · Back',value:'cubic-bezier(0.6, -0.28, 0.74, 0.05)'}],[{name:'ease-out',value:'ease-out'},{name:'Out · Sine',value:'cubic-bezier(0.39, 0.58, 0.57, 1)'},{name:'Out · Quadratic',value:'cubic-bezier(0.25, 0.46, 0.45, 0.94)'},{name:'Out · Cubic',value:'cubic-bezier(0.22, 0.61, 0.36, 1)'},{name:'Linear Out, Slow In',value:'cubic-bezier(0, 0, 0.2, 1)'},{name:'Out · Back',value:'cubic-bezier(0.18, 0.89, 0.32, 1.28)'}]];InlineEditor.BezierEditor.PresetCategory;;InlineEditor.BezierUI=class{constructor(width,height,marginTop,controlPointRadius,linearLine){this.width=width;this.height=height;this.marginTop=marginTop;this.radius=controlPointRadius;this.linearLine=linearLine;}
static drawVelocityChart(bezier,path,width){const height=InlineEditor.BezierUI.Height;let pathBuilder=['M',0,height];const sampleSize=1/40;let prev=bezier.evaluateAt(0);for(let t=sampleSize;t<1+sampleSize;t+=sampleSize){const current=bezier.evaluateAt(t);let slope=(current.y-prev.y)/(current.x-prev.x);const weightedX=prev.x*(1-t)+current.x*t;slope=Math.tanh(slope/1.5);pathBuilder=pathBuilder.concat(['L',(weightedX*width).toFixed(2),(height-slope*height).toFixed(2)]);prev=current;}
pathBuilder=pathBuilder.concat(['L',width.toFixed(2),height,'Z']);path.setAttribute('d',pathBuilder.join(' '));}
curveWidth(){return this.width-this.radius*2;}
curveHeight(){return this.height-this.radius*2-this.marginTop*2;}
_drawLine(parentElement,className,x1,y1,x2,y2){const line=parentElement.createSVGChild('line',className);line.setAttribute('x1',x1+this.radius);line.setAttribute('y1',y1+this.radius+this.marginTop);line.setAttribute('x2',x2+this.radius);line.setAttribute('y2',y2+this.radius+this.marginTop);}
_drawControlPoints(parentElement,startX,startY,controlX,controlY){this._drawLine(parentElement,'bezier-control-line',startX,startY,controlX,controlY);const circle=parentElement.createSVGChild('circle','bezier-control-circle');circle.setAttribute('cx',controlX+this.radius);circle.setAttribute('cy',controlY+this.radius+this.marginTop);circle.setAttribute('r',this.radius);}
drawCurve(bezier,svg){if(!bezier)
return;const width=this.curveWidth();const height=this.curveHeight();svg.setAttribute('width',this.width);svg.setAttribute('height',this.height);svg.removeChildren();const group=svg.createSVGChild('g');if(this.linearLine)
this._drawLine(group,'linear-line',0,height,width,0);const curve=group.createSVGChild('path','bezier-path');const curvePoints=[new UI.Geometry.Point(bezier.controlPoints[0].x*width+this.radius,(1-bezier.controlPoints[0].y)*height+this.radius+this.marginTop),new UI.Geometry.Point(bezier.controlPoints[1].x*width+this.radius,(1-bezier.controlPoints[1].y)*height+this.radius+this.marginTop),new UI.Geometry.Point(width+this.radius,this.marginTop+this.radius)];curve.setAttribute('d','M'+this.radius+','+(height+this.radius+this.marginTop)+' C'+curvePoints.join(' '));this._drawControlPoints(group,0,height,bezier.controlPoints[0].x*width,(1-bezier.controlPoints[0].y)*height);this._drawControlPoints(group,width,0,bezier.controlPoints[1].x*width,(1-bezier.controlPoints[1].y)*height);}};InlineEditor.BezierUI.Height=26;;InlineEditor.ColorSwatch=class extends HTMLSpanElement{constructor(){super();const root=UI.createShadowRootWithCoreStyles(this,'inline_editor/colorSwatch.css');this._iconElement=root.createChild('span','color-swatch');this._iconElement.title=Common.UIString('Shift-click to change color format');this._swatchInner=this._iconElement.createChild('span','color-swatch-inner');this._swatchInner.addEventListener('dblclick',e=>e.consume(),false);this._swatchInner.addEventListener('mousedown',e=>e.consume(),false);this._swatchInner.addEventListener('click',this._handleClick.bind(this),true);root.createChild('slot');this._colorValueElement=this.createChild('span');}
static create(){if(!InlineEditor.ColorSwatch._constructor){InlineEditor.ColorSwatch._constructor=UI.registerCustomElement('span','color-swatch',InlineEditor.ColorSwatch);}
return(InlineEditor.ColorSwatch._constructor());}
static _nextColorFormat(color,curFormat){const cf=Common.Color.Format;switch(curFormat){case cf.Original:return!color.hasAlpha()?cf.RGB:cf.RGBA;case cf.RGB:case cf.RGBA:return!color.hasAlpha()?cf.HSL:cf.HSLA;case cf.HSL:case cf.HSLA:if(color.nickname())
return cf.Nickname;return color.detectHEXFormat();case cf.ShortHEX:return cf.HEX;case cf.ShortHEXA:return cf.HEXA;case cf.HEXA:case cf.HEX:return cf.Original;case cf.Nickname:return color.detectHEXFormat();default:return cf.RGBA;}}
color(){return this._color;}
setColor(color){this._color=color;this._format=this._color.format();const colorString=(this._color.asString(this._format));this.setText(colorString);this._swatchInner.style.backgroundColor=colorString;}
hideText(hide){this._colorValueElement.hidden=hide;}
setText(text,tooltip){this._colorValueElement.textContent=text;this._colorValueElement.title=tooltip;}
format(){return this._format;}
setFormat(format){this._format=format;this.setText(this._color.asString(this._format));}
toggleNextFormat(){let currentValue;do{this._format=InlineEditor.ColorSwatch._nextColorFormat(this._color,this._format);currentValue=this._color.asString(this._format);}while(currentValue===this._colorValueElement.textContent);this.setText(currentValue);}
iconElement(){return this._iconElement;}
_handleClick(event){if(!event.shiftKey)
return;event.target.parentNode.parentNode.host.toggleNextFormat();event.consume(true);}};InlineEditor.BezierSwatch=class extends HTMLSpanElement{constructor(){super();const root=UI.createShadowRootWithCoreStyles(this,'inline_editor/bezierSwatch.css');this._iconElement=UI.Icon.create('smallicon-bezier','bezier-swatch-icon');root.appendChild(this._iconElement);this._textElement=this.createChild('span');root.createChild('slot');}
static create(){if(!InlineEditor.BezierSwatch._constructor){InlineEditor.BezierSwatch._constructor=UI.registerCustomElement('span','bezier-swatch',InlineEditor.BezierSwatch);}
return(InlineEditor.BezierSwatch._constructor());}
bezierText(){return this._textElement.textContent;}
setBezierText(text){this._textElement.textContent=text;}
hideText(hide){this._textElement.hidden=hide;}
iconElement(){return this._iconElement;}};InlineEditor.CSSShadowSwatch=class extends HTMLSpanElement{constructor(){super();const root=UI.createShadowRootWithCoreStyles(this,'inline_editor/cssShadowSwatch.css');this._iconElement=UI.Icon.create('smallicon-shadow','shadow-swatch-icon');root.appendChild(this._iconElement);root.createChild('slot');this._contentElement=this.createChild('span');}
static create(){if(!InlineEditor.CSSShadowSwatch._constructor){InlineEditor.CSSShadowSwatch._constructor=UI.registerCustomElement('span','css-shadow-swatch',InlineEditor.CSSShadowSwatch);}
return(InlineEditor.CSSShadowSwatch._constructor());}
model(){return this._model;}
setCSSShadow(model){this._model=model;this._contentElement.removeChildren();const results=TextUtils.TextUtils.splitStringByRegexes(model.asCSSText(),[/inset/g,Common.Color.Regex]);for(let i=0;i<results.length;i++){const result=results[i];if(result.regexIndex===1){if(!this._colorSwatch)
this._colorSwatch=InlineEditor.ColorSwatch.create();this._colorSwatch.setColor(model.color());this._contentElement.appendChild(this._colorSwatch);}else{this._contentElement.appendChild(createTextNode(result.value));}}}
hideText(hide){this._contentElement.hidden=hide;}
iconElement(){return this._iconElement;}
colorSwatch(){return this._colorSwatch;}};;InlineEditor.CSSShadowEditor=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('inline_editor/cssShadowEditor.css');this.contentElement.tabIndex=0;this.setDefaultFocusedElement(this.contentElement);this._typeField=this.contentElement.createChild('div','shadow-editor-field shadow-editor-flex-field');this._typeField.createChild('label','shadow-editor-label').textContent=Common.UIString('Type');this._outsetButton=this._typeField.createChild('button','shadow-editor-button-left');this._outsetButton.textContent=Common.UIString('Outset');this._outsetButton.addEventListener('click',this._onButtonClick.bind(this),false);this._insetButton=this._typeField.createChild('button','shadow-editor-button-right');this._insetButton.textContent=Common.UIString('Inset');this._insetButton.addEventListener('click',this._onButtonClick.bind(this),false);const xField=this.contentElement.createChild('div','shadow-editor-field');this._xInput=this._createTextInput(xField,Common.UIString('X offset'));const yField=this.contentElement.createChild('div','shadow-editor-field');this._yInput=this._createTextInput(yField,Common.UIString('Y offset'));this._xySlider=xField.createChild('canvas','shadow-editor-2D-slider');this._xySlider.width=InlineEditor.CSSShadowEditor.canvasSize;this._xySlider.height=InlineEditor.CSSShadowEditor.canvasSize;this._xySlider.tabIndex=-1;this._halfCanvasSize=InlineEditor.CSSShadowEditor.canvasSize/2;this._innerCanvasSize=this._halfCanvasSize-InlineEditor.CSSShadowEditor.sliderThumbRadius;UI.installDragHandle(this._xySlider,this._dragStart.bind(this),this._dragMove.bind(this),null,'default');this._xySlider.addEventListener('keydown',this._onCanvasArrowKey.bind(this),false);this._xySlider.addEventListener('blur',this._onCanvasBlur.bind(this),false);const blurField=this.contentElement.createChild('div','shadow-editor-field shadow-editor-flex-field shadow-editor-blur-field');this._blurInput=this._createTextInput(blurField,Common.UIString('Blur'));this._blurSlider=this._createSlider(blurField);this._spreadField=this.contentElement.createChild('div','shadow-editor-field shadow-editor-flex-field');this._spreadInput=this._createTextInput(this._spreadField,Common.UIString('Spread'));this._spreadSlider=this._createSlider(this._spreadField);}
_createTextInput(field,propertyName){const label=field.createChild('label','shadow-editor-label');label.textContent=propertyName;label.setAttribute('for',propertyName);const textInput=UI.createInput('shadow-editor-text-input','text');field.appendChild(textInput);textInput.id=propertyName;textInput.addEventListener('keydown',this._handleValueModification.bind(this),false);textInput.addEventListener('mousewheel',this._handleValueModification.bind(this),false);textInput.addEventListener('input',this._onTextInput.bind(this),false);textInput.addEventListener('blur',this._onTextBlur.bind(this),false);return textInput;}
_createSlider(field){const slider=UI.createSlider(0,InlineEditor.CSSShadowEditor.maxRange,-1);slider.addEventListener('input',this._onSliderInput.bind(this),false);field.appendChild(slider);return slider;}
wasShown(){this._updateUI();}
setModel(model){this._model=model;this._typeField.classList.toggle('hidden',!model.isBoxShadow());this._spreadField.classList.toggle('hidden',!model.isBoxShadow());this._updateUI();}
_updateUI(){this._updateButtons();this._xInput.value=this._model.offsetX().asCSSText();this._yInput.value=this._model.offsetY().asCSSText();this._blurInput.value=this._model.blurRadius().asCSSText();this._spreadInput.value=this._model.spreadRadius().asCSSText();this._blurSlider.value=this._model.blurRadius().amount;this._spreadSlider.value=this._model.spreadRadius().amount;this._updateCanvas(false);}
_updateButtons(){this._insetButton.classList.toggle('enabled',this._model.inset());this._outsetButton.classList.toggle('enabled',!this._model.inset());}
_updateCanvas(drawFocus){const context=this._xySlider.getContext('2d');context.clearRect(0,0,this._xySlider.width,this._xySlider.height);context.save();context.setLineDash([1,1]);context.strokeStyle='rgba(210, 210, 210, 0.8)';context.beginPath();context.moveTo(this._halfCanvasSize,0);context.lineTo(this._halfCanvasSize,InlineEditor.CSSShadowEditor.canvasSize);context.moveTo(0,this._halfCanvasSize);context.lineTo(InlineEditor.CSSShadowEditor.canvasSize,this._halfCanvasSize);context.stroke();context.restore();const thumbPoint=this._sliderThumbPosition();context.save();context.translate(this._halfCanvasSize,this._halfCanvasSize);context.lineWidth=2;context.strokeStyle='rgba(130, 130, 130, 0.75)';context.beginPath();context.moveTo(0,0);context.lineTo(thumbPoint.x,thumbPoint.y);context.stroke();if(drawFocus){context.beginPath();context.fillStyle='rgba(66, 133, 244, 0.4)';context.arc(thumbPoint.x,thumbPoint.y,InlineEditor.CSSShadowEditor.sliderThumbRadius+2,0,2*Math.PI);context.fill();}
context.beginPath();context.fillStyle='#4285F4';context.arc(thumbPoint.x,thumbPoint.y,InlineEditor.CSSShadowEditor.sliderThumbRadius,0,2*Math.PI);context.fill();context.restore();}
_onButtonClick(event){const insetClicked=(event.currentTarget===this._insetButton);if(insetClicked&&this._model.inset()||!insetClicked&&!this._model.inset())
return;this._model.setInset(insetClicked);this._updateButtons();this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);}
_handleValueModification(event){const modifiedValue=UI.createReplacementString(event.currentTarget.value,event,customNumberHandler);if(!modifiedValue)
return;const length=InlineEditor.CSSLength.parse(modifiedValue);if(!length)
return;if(event.currentTarget===this._blurInput&&length.amount<0)
length.amount=0;event.currentTarget.value=length.asCSSText();event.currentTarget.selectionStart=0;event.currentTarget.selectionEnd=event.currentTarget.value.length;this._onTextInput(event);event.consume(true);function customNumberHandler(prefix,number,suffix){if(!suffix.length)
suffix=InlineEditor.CSSShadowEditor.defaultUnit;return prefix+number+suffix;}}
_onTextInput(event){this._changedElement=event.currentTarget;this._changedElement.classList.remove('invalid');const length=InlineEditor.CSSLength.parse(event.currentTarget.value);if(!length||event.currentTarget===this._blurInput&&length.amount<0)
return;if(event.currentTarget===this._xInput){this._model.setOffsetX(length);this._updateCanvas(false);}else if(event.currentTarget===this._yInput){this._model.setOffsetY(length);this._updateCanvas(false);}else if(event.currentTarget===this._blurInput){this._model.setBlurRadius(length);this._blurSlider.value=length.amount;}else if(event.currentTarget===this._spreadInput){this._model.setSpreadRadius(length);this._spreadSlider.value=length.amount;}
this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);}
_onTextBlur(){if(!this._changedElement)
return;let length=!this._changedElement.value.trim()?InlineEditor.CSSLength.zero():InlineEditor.CSSLength.parse(this._changedElement.value);if(!length)
length=InlineEditor.CSSLength.parse(this._changedElement.value+InlineEditor.CSSShadowEditor.defaultUnit);if(!length){this._changedElement.classList.add('invalid');this._changedElement=null;return;}
if(this._changedElement===this._xInput){this._model.setOffsetX(length);this._xInput.value=length.asCSSText();this._updateCanvas(false);}else if(this._changedElement===this._yInput){this._model.setOffsetY(length);this._yInput.value=length.asCSSText();this._updateCanvas(false);}else if(this._changedElement===this._blurInput){if(length.amount<0)
length=InlineEditor.CSSLength.zero();this._model.setBlurRadius(length);this._blurInput.value=length.asCSSText();this._blurSlider.value=length.amount;}else if(this._changedElement===this._spreadInput){this._model.setSpreadRadius(length);this._spreadInput.value=length.asCSSText();this._spreadSlider.value=length.amount;}
this._changedElement=null;this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);}
_onSliderInput(event){if(event.currentTarget===this._blurSlider){this._model.setBlurRadius(new InlineEditor.CSSLength(this._blurSlider.value,this._model.blurRadius().unit||InlineEditor.CSSShadowEditor.defaultUnit));this._blurInput.value=this._model.blurRadius().asCSSText();this._blurInput.classList.remove('invalid');}else if(event.currentTarget===this._spreadSlider){this._model.setSpreadRadius(new InlineEditor.CSSLength(this._spreadSlider.value,this._model.spreadRadius().unit||InlineEditor.CSSShadowEditor.defaultUnit));this._spreadInput.value=this._model.spreadRadius().asCSSText();this._spreadInput.classList.remove('invalid');}
this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);}
_dragStart(event){this._xySlider.focus();this._updateCanvas(true);this._canvasOrigin=new UI.Geometry.Point(this._xySlider.totalOffsetLeft()+this._halfCanvasSize,this._xySlider.totalOffsetTop()+this._halfCanvasSize);const clickedPoint=new UI.Geometry.Point(event.x-this._canvasOrigin.x,event.y-this._canvasOrigin.y);const thumbPoint=this._sliderThumbPosition();if(clickedPoint.distanceTo(thumbPoint)>=InlineEditor.CSSShadowEditor.sliderThumbRadius)
this._dragMove(event);return true;}
_dragMove(event){let point=new UI.Geometry.Point(event.x-this._canvasOrigin.x,event.y-this._canvasOrigin.y);if(event.shiftKey)
point=this._snapToClosestDirection(point);const constrainedPoint=this._constrainPoint(point,this._innerCanvasSize);const newX=Math.round((constrainedPoint.x/this._innerCanvasSize)*InlineEditor.CSSShadowEditor.maxRange);const newY=Math.round((constrainedPoint.y/this._innerCanvasSize)*InlineEditor.CSSShadowEditor.maxRange);if(event.shiftKey){this._model.setOffsetX(new InlineEditor.CSSLength(newX,this._model.offsetX().unit||InlineEditor.CSSShadowEditor.defaultUnit));this._model.setOffsetY(new InlineEditor.CSSLength(newY,this._model.offsetY().unit||InlineEditor.CSSShadowEditor.defaultUnit));}else{if(!event.altKey){this._model.setOffsetX(new InlineEditor.CSSLength(newX,this._model.offsetX().unit||InlineEditor.CSSShadowEditor.defaultUnit));}
if(!UI.KeyboardShortcut.eventHasCtrlOrMeta(event)){this._model.setOffsetY(new InlineEditor.CSSLength(newY,this._model.offsetY().unit||InlineEditor.CSSShadowEditor.defaultUnit));}}
this._xInput.value=this._model.offsetX().asCSSText();this._yInput.value=this._model.offsetY().asCSSText();this._xInput.classList.remove('invalid');this._yInput.classList.remove('invalid');this._updateCanvas(true);this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);}
_onCanvasBlur(){this._updateCanvas(false);}
_onCanvasArrowKey(event){let shiftX=0;let shiftY=0;if(event.key==='ArrowRight')
shiftX=1;else if(event.key==='ArrowLeft')
shiftX=-1;else if(event.key==='ArrowUp')
shiftY=-1;else if(event.key==='ArrowDown')
shiftY=1;if(!shiftX&&!shiftY)
return;event.consume(true);if(shiftX){const offsetX=this._model.offsetX();const newAmount=Number.constrain(offsetX.amount+shiftX,-InlineEditor.CSSShadowEditor.maxRange,InlineEditor.CSSShadowEditor.maxRange);if(newAmount===offsetX.amount)
return;this._model.setOffsetX(new InlineEditor.CSSLength(newAmount,offsetX.unit||InlineEditor.CSSShadowEditor.defaultUnit));this._xInput.value=this._model.offsetX().asCSSText();this._xInput.classList.remove('invalid');}
if(shiftY){const offsetY=this._model.offsetY();const newAmount=Number.constrain(offsetY.amount+shiftY,-InlineEditor.CSSShadowEditor.maxRange,InlineEditor.CSSShadowEditor.maxRange);if(newAmount===offsetY.amount)
return;this._model.setOffsetY(new InlineEditor.CSSLength(newAmount,offsetY.unit||InlineEditor.CSSShadowEditor.defaultUnit));this._yInput.value=this._model.offsetY().asCSSText();this._yInput.classList.remove('invalid');}
this._updateCanvas(true);this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged,this._model);}
_constrainPoint(point,max){if(Math.abs(point.x)<=max&&Math.abs(point.y)<=max)
return new UI.Geometry.Point(point.x,point.y);return point.scale(max/Math.max(Math.abs(point.x),Math.abs(point.y)));}
_snapToClosestDirection(point){let minDistance=Number.MAX_VALUE;let closestPoint=point;const directions=[new UI.Geometry.Point(0,-1),new UI.Geometry.Point(1,-1),new UI.Geometry.Point(1,0),new UI.Geometry.Point(1,1)];for(const direction of directions){const projection=point.projectOn(direction);const distance=point.distanceTo(projection);if(distance<minDistance){minDistance=distance;closestPoint=projection;}}
return closestPoint;}
_sliderThumbPosition(){const x=(this._model.offsetX().amount/InlineEditor.CSSShadowEditor.maxRange)*this._innerCanvasSize;const y=(this._model.offsetY().amount/InlineEditor.CSSShadowEditor.maxRange)*this._innerCanvasSize;return this._constrainPoint(new UI.Geometry.Point(x,y),this._innerCanvasSize);}};InlineEditor.CSSShadowEditor.Events={ShadowChanged:Symbol('ShadowChanged')};InlineEditor.CSSShadowEditor.maxRange=20;InlineEditor.CSSShadowEditor.defaultUnit='px';InlineEditor.CSSShadowEditor.sliderThumbRadius=6;InlineEditor.CSSShadowEditor.canvasSize=88;;InlineEditor.SwatchPopoverHelper=class extends Common.Object{constructor(){super();this._popover=new UI.GlassPane();this._popover.registerRequiredCSS('inline_editor/swatchPopover.css');this._popover.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);this._popover.setMarginBehavior(UI.GlassPane.MarginBehavior.Arrow);this._popover.element.addEventListener('mousedown',e=>e.consume(),false);this._hideProxy=this.hide.bind(this,true);this._boundOnKeyDown=this._onKeyDown.bind(this);this._boundFocusOut=this._onFocusOut.bind(this);this._isHidden=true;}
_onFocusOut(event){if(!event.relatedTarget||event.relatedTarget.isSelfOrDescendant(this._view.contentElement))
return;this._hideProxy();}
isShowing(){return this._popover.isShowing();}
show(view,anchorElement,hiddenCallback){if(this._popover.isShowing()){if(this._anchorElement===anchorElement)
return;this.hide(true);}
delete this._isHidden;this._anchorElement=anchorElement;this._view=view;this._hiddenCallback=hiddenCallback;this.reposition();view.focus();const document=this._popover.element.ownerDocument;document.addEventListener('mousedown',this._hideProxy,false);document.defaultView.addEventListener('resize',this._hideProxy,false);this._view.contentElement.addEventListener('keydown',this._boundOnKeyDown,false);}
reposition(){this._view.contentElement.removeEventListener('focusout',this._boundFocusOut,false);this._view.show(this._popover.contentElement);this._popover.setContentAnchorBox(this._anchorElement.boxInWindow());this._popover.show(this._anchorElement.ownerDocument);this._view.contentElement.addEventListener('focusout',this._boundFocusOut,false);if(!this._focusRestorer)
this._focusRestorer=new UI.WidgetFocusRestorer(this._view);}
hide(commitEdit){if(this._isHidden)
return;const document=this._popover.element.ownerDocument;this._isHidden=true;this._popover.hide();document.removeEventListener('mousedown',this._hideProxy,false);document.defaultView.removeEventListener('resize',this._hideProxy,false);if(this._hiddenCallback)
this._hiddenCallback.call(null,!!commitEdit);this._focusRestorer.restore();delete this._anchorElement;if(this._view){this._view.detach();this._view.contentElement.removeEventListener('keydown',this._boundOnKeyDown,false);this._view.contentElement.removeEventListener('focusout',this._boundFocusOut,false);delete this._view;}}
_onKeyDown(event){if(event.key==='Enter'){this.hide(true);event.consume(true);return;}
if(event.key==='Escape'){this.hide(false);event.consume(true);}}};;InlineEditor.CSSShadowModel=class{constructor(isBoxShadow){this._isBoxShadow=isBoxShadow;this._inset=false;this._offsetX=InlineEditor.CSSLength.zero();this._offsetY=InlineEditor.CSSLength.zero();this._blurRadius=InlineEditor.CSSLength.zero();this._spreadRadius=InlineEditor.CSSLength.zero();this._color=(Common.Color.parse('black'));this._format=[InlineEditor.CSSShadowModel._Part.OffsetX,InlineEditor.CSSShadowModel._Part.OffsetY];}
static parseTextShadow(text){return InlineEditor.CSSShadowModel._parseShadow(text,false);}
static parseBoxShadow(text){return InlineEditor.CSSShadowModel._parseShadow(text,true);}
static _parseShadow(text,isBoxShadow){const shadowTexts=[];const splits=TextUtils.TextUtils.splitStringByRegexes(text,[Common.Color.Regex,/,/g]);let currentIndex=0;for(let i=0;i<splits.length;i++){if(splits[i].regexIndex===1){const comma=splits[i];shadowTexts.push(text.substring(currentIndex,comma.position));currentIndex=comma.position+1;}}
shadowTexts.push(text.substring(currentIndex,text.length));const shadows=[];for(let i=0;i<shadowTexts.length;i++){const shadow=new InlineEditor.CSSShadowModel(isBoxShadow);shadow._format=[];let nextPartAllowed=true;const regexes=[/inset/gi,Common.Color.Regex,InlineEditor.CSSLength.Regex];const results=TextUtils.TextUtils.splitStringByRegexes(shadowTexts[i],regexes);for(let j=0;j<results.length;j++){const result=results[j];if(result.regexIndex===-1){if(/\S/.test(result.value))
return[];nextPartAllowed=true;}else{if(!nextPartAllowed)
return[];nextPartAllowed=false;if(result.regexIndex===0){shadow._inset=true;shadow._format.push(InlineEditor.CSSShadowModel._Part.Inset);}else if(result.regexIndex===1){const color=Common.Color.parse(result.value);if(!color)
return[];shadow._color=color;shadow._format.push(InlineEditor.CSSShadowModel._Part.Color);}else if(result.regexIndex===2){const length=InlineEditor.CSSLength.parse(result.value);if(!length)
return[];const previousPart=shadow._format.length>0?shadow._format[shadow._format.length-1]:'';if(previousPart===InlineEditor.CSSShadowModel._Part.OffsetX){shadow._offsetY=length;shadow._format.push(InlineEditor.CSSShadowModel._Part.OffsetY);}else if(previousPart===InlineEditor.CSSShadowModel._Part.OffsetY){shadow._blurRadius=length;shadow._format.push(InlineEditor.CSSShadowModel._Part.BlurRadius);}else if(previousPart===InlineEditor.CSSShadowModel._Part.BlurRadius){shadow._spreadRadius=length;shadow._format.push(InlineEditor.CSSShadowModel._Part.SpreadRadius);}else{shadow._offsetX=length;shadow._format.push(InlineEditor.CSSShadowModel._Part.OffsetX);}}}}
if(invalidCount(shadow,InlineEditor.CSSShadowModel._Part.OffsetX,1,1)||invalidCount(shadow,InlineEditor.CSSShadowModel._Part.OffsetY,1,1)||invalidCount(shadow,InlineEditor.CSSShadowModel._Part.Color,0,1)||invalidCount(shadow,InlineEditor.CSSShadowModel._Part.BlurRadius,0,1)||invalidCount(shadow,InlineEditor.CSSShadowModel._Part.Inset,0,isBoxShadow?1:0)||invalidCount(shadow,InlineEditor.CSSShadowModel._Part.SpreadRadius,0,isBoxShadow?1:0))
return[];shadows.push(shadow);}
return shadows;function invalidCount(shadow,part,min,max){let count=0;for(let i=0;i<shadow._format.length;i++){if(shadow._format[i]===part)
count++;}
return count<min||count>max;}}
setInset(inset){this._inset=inset;if(this._format.indexOf(InlineEditor.CSSShadowModel._Part.Inset)===-1)
this._format.unshift(InlineEditor.CSSShadowModel._Part.Inset);}
setOffsetX(offsetX){this._offsetX=offsetX;}
setOffsetY(offsetY){this._offsetY=offsetY;}
setBlurRadius(blurRadius){this._blurRadius=blurRadius;if(this._format.indexOf(InlineEditor.CSSShadowModel._Part.BlurRadius)===-1){const yIndex=this._format.indexOf(InlineEditor.CSSShadowModel._Part.OffsetY);this._format.splice(yIndex+1,0,InlineEditor.CSSShadowModel._Part.BlurRadius);}}
setSpreadRadius(spreadRadius){this._spreadRadius=spreadRadius;if(this._format.indexOf(InlineEditor.CSSShadowModel._Part.SpreadRadius)===-1){this.setBlurRadius(this._blurRadius);const blurIndex=this._format.indexOf(InlineEditor.CSSShadowModel._Part.BlurRadius);this._format.splice(blurIndex+1,0,InlineEditor.CSSShadowModel._Part.SpreadRadius);}}
setColor(color){this._color=color;if(this._format.indexOf(InlineEditor.CSSShadowModel._Part.Color)===-1)
this._format.push(InlineEditor.CSSShadowModel._Part.Color);}
isBoxShadow(){return this._isBoxShadow;}
inset(){return this._inset;}
offsetX(){return this._offsetX;}
offsetY(){return this._offsetY;}
blurRadius(){return this._blurRadius;}
spreadRadius(){return this._spreadRadius;}
color(){return this._color;}
asCSSText(){const parts=[];for(let i=0;i<this._format.length;i++){const part=this._format[i];if(part===InlineEditor.CSSShadowModel._Part.Inset&&this._inset)
parts.push('inset');else if(part===InlineEditor.CSSShadowModel._Part.OffsetX)
parts.push(this._offsetX.asCSSText());else if(part===InlineEditor.CSSShadowModel._Part.OffsetY)
parts.push(this._offsetY.asCSSText());else if(part===InlineEditor.CSSShadowModel._Part.BlurRadius)
parts.push(this._blurRadius.asCSSText());else if(part===InlineEditor.CSSShadowModel._Part.SpreadRadius)
parts.push(this._spreadRadius.asCSSText());else if(part===InlineEditor.CSSShadowModel._Part.Color)
parts.push(this._color.asString(this._color.format()));}
return parts.join(' ');}};InlineEditor.CSSShadowModel._Part={Inset:'I',OffsetX:'X',OffsetY:'Y',BlurRadius:'B',SpreadRadius:'S',Color:'C'};InlineEditor.CSSLength=class{constructor(amount,unit){this.amount=amount;this.unit=unit;}
static parse(text){const lengthRegex=new RegExp('^(?:'+InlineEditor.CSSLength.Regex.source+')$','i');const match=text.match(lengthRegex);if(!match)
return null;if(match.length>2&&match[2])
return new InlineEditor.CSSLength(parseFloat(match[1]),match[2]);return InlineEditor.CSSLength.zero();}
static zero(){return new InlineEditor.CSSLength(0,'');}
asCSSText(){return this.amount+this.unit;}};InlineEditor.CSSLength.Regex=(function(){const number='([+-]?(?:[0-9]*[.])?[0-9]+(?:[eE][+-]?[0-9]+)?)';const unit='(ch|cm|em|ex|in|mm|pc|pt|px|rem|vh|vmax|vmin|vw)';const zero='[+-]?(?:0*[.])?0+(?:[eE][+-]?[0-9]+)?';return new RegExp(number+unit+'|'+zero,'gi');})();;Runtime.cachedResources["inline_editor/bezierEditor.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n width: 270px;\n height: 350px;\n -webkit-user-select: none;\n padding: 16px;\n overflow: hidden;\n}\n\n.bezier-preset-selected > svg {\n background-color: var(--selection-bg-color);\n}\n\n.bezier-preset {\n width: 50px;\n height: 50px;\n padding: 5px;\n margin: auto;\n background-color: #f5f5f5;\n border-radius: 3px;\n}\n\n.bezier-preset line.bezier-control-line {\n stroke: #666;\n stroke-width: 1;\n stroke-linecap: round;\n fill: none;\n}\n\n.bezier-preset circle.bezier-control-circle {\n fill: #666;\n}\n\n.bezier-preset path.bezier-path {\n stroke: black;\n stroke-width: 2;\n stroke-linecap: round;\n fill: none;\n}\n\n.bezier-preset-selected path.bezier-path, .bezier-preset-selected line.bezier-control-line {\n stroke: white;\n}\n\n.bezier-preset-selected circle.bezier-control-circle {\n fill: white;\n}\n\n.bezier-curve line.linear-line {\n stroke: rgb(238, 238, 238);\n stroke-width: 2;\n stroke-linecap: round;\n fill: none;\n}\n\n:host-context(.-theme-with-dark-background) .bezier-curve line.linear-line {\n stroke: rgb(138, 138, 138);\n}\n\n.bezier-curve line.bezier-control-line {\n stroke: #9C27B0;\n stroke-width: 2;\n stroke-linecap: round;\n fill: none;\n opacity: 0.6;\n}\n\n.bezier-curve circle.bezier-control-circle {\n fill: #9C27B0;\n cursor: pointer;\n}\n\n.bezier-curve path.bezier-path {\n stroke: black;\n stroke-width: 3;\n stroke-linecap: round;\n fill: none;\n}\n\n.bezier-preview-container {\n position: relative;\n background-color: white;\n overflow: hidden;\n border-radius: 20px;\n width: 200%;\n height: 20px;\n z-index: 2;\n flex-shrink: 0;\n opacity: 0;\n}\n\n.bezier-preview-animation {\n background-color: #9C27B0;\n width: 20px;\n height: 20px;\n border-radius: 20px;\n position: absolute;\n}\n\n.bezier-preview-onion {\n margin-top: -20px;\n position: relative;\n z-index: 1;\n}\n\n.bezier-preview-onion > .bezier-preview-animation {\n opacity: 0.1;\n}\n\nsvg.bezier-preset-modify {\n background-color: #f5f5f5;\n border-radius: 35px;\n display: inline-block;\n visibility: hidden;\n transition: transform 100ms cubic-bezier(0.4, 0, 0.2, 1);\n cursor: pointer;\n position: absolute;\n}\n\nsvg.bezier-preset-modify:hover, .bezier-preset:hover {\n background-color: #999;\n}\n\n.bezier-preset-selected .bezier-preset:hover {\n background-color: var(--selection-bg-color);\n}\n\n.bezier-preset-modify path {\n stroke-width: 2;\n stroke: black;\n fill: none;\n}\n\n.bezier-preset-selected .bezier-preset-modify {\n opacity: 1;\n}\n\n.bezier-preset-category {\n width: 50px;\n margin: 20px 0;\n cursor: pointer;\n transition: transform 100ms cubic-bezier(0.4, 0, 0.2, 1);\n}\n\nspan.bezier-display-value {\n width: 100%;\n -webkit-user-select: text;\n display: block;\n text-align: center;\n line-height: 20px;\n height: 20px;\n cursor: text;\n white-space: nowrap !important;\n}\n\n.bezier-container {\n display: flex;\n margin-top: 38px;\n}\n\nsvg.bezier-curve {\n margin-left: 32px;\n margin-top: -8px;\n}\n\nsvg.bezier-preset-modify.bezier-preset-plus {\n right: 0;\n}\n\n.bezier-header {\n margin-top: 16px;\n}\n\nsvg.bezier-preset-modify:active {\n transform: scale(1.1);\n background-color: var(--selection-bg-color);\n}\n\n.bezier-preset-category:active {\n transform: scale(1.05);\n}\n\n.bezier-header-acti
this._staticMethods.set(nativeFunction.receiver,new Map());this._staticMethods.get(nativeFunction.receiver).set(nativeFunction.name,nativeFunction.signatures);}else{if(!this._instanceMethods.has(nativeFunction.receiver))
this._instanceMethods.set(nativeFunction.receiver,new Map());this._instanceMethods.get(nativeFunction.receiver).set(nativeFunction.name,nativeFunction.signatures);}}}
signaturesForNativeFunction(name){return this._uniqueFunctions.get(name)||null;}
signaturesForInstanceMethod(name,receiverClassName){if(!this._instanceMethods.has(receiverClassName))
return null;return this._instanceMethods.get(receiverClassName).get(name)||null;}
signaturesForStaticMethod(name,receiverConstructorName){if(!this._staticMethods.has(receiverConstructorName))
return null;return this._staticMethods.get(receiverConstructorName).get(name)||null;}};JavaScriptMetadata.NativeFunctions;;LayerViewer.LayerDetailsView=class extends UI.Widget{constructor(layerViewHost){super(true);this.registerRequiredCSS('layer_viewer/layerDetailsView.css');this._layerViewHost=layerViewHost;this._layerViewHost.registerView(this);this._emptyWidget=new UI.EmptyWidget(Common.UIString('Select a layer to see its details'));this._buildContent();}
hoverObject(selection){}
selectObject(selection){this._selection=selection;if(this.isShowing())
this.update();}
setLayerTree(layerTree){}
wasShown(){super.wasShown();this.update();}
_onScrollRectClicked(index,event){if(event.which!==1)
return;this._layerViewHost.selectObject(new LayerViewer.LayerView.ScrollRectSelection(this._selection.layer(),index));}
_onPaintProfilerButtonClicked(){if(this._selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot||this._selection.layer())
this.dispatchEventToListeners(LayerViewer.LayerDetailsView.Events.PaintProfilerRequested,this._selection);}
_createScrollRectElement(scrollRect,index){if(index)
this._scrollRectsCell.createTextChild(', ');const element=this._scrollRectsCell.createChild('span','scroll-rect');if(this._selection.scrollRectIndex===index)
element.classList.add('active');element.textContent=Common.UIString('%s %d × %d (at %d, %d)',LayerViewer.LayerDetailsView._slowScrollRectNames.get(scrollRect.type),scrollRect.rect.x,scrollRect.rect.y,scrollRect.rect.width,scrollRect.rect.height);element.addEventListener('click',this._onScrollRectClicked.bind(this,index),false);}
_formatStickyAncestorLayer(title,layer){if(!layer)
return'';const node=layer.nodeForSelfOrAncestor();const name=node?node.simpleSelector():Common.UIString('<unnamed>');return Common.UIString('%s: %s (%s)',title,name,layer.id());}
_createStickyAncestorChild(title,layer){if(!layer)
return;this._stickyPositionConstraintCell.createTextChild(', ');const child=this._stickyPositionConstraintCell.createChild('span');child.textContent=this._formatStickyAncestorLayer(title,layer);}
_populateStickyPositionConstraintCell(constraint){this._stickyPositionConstraintCell.removeChildren();if(!constraint)
return;const stickyBoxRect=constraint.stickyBoxRect();const stickyBoxRectElement=this._stickyPositionConstraintCell.createChild('span');stickyBoxRectElement.textContent=Common.UIString('Sticky Box %d × %d (at %d, %d)',stickyBoxRect.width,stickyBoxRect.height,stickyBoxRect.x,stickyBoxRect.y);this._stickyPositionConstraintCell.createTextChild(', ');const containingBlockRect=constraint.containingBlockRect();const containingBlockRectElement=this._stickyPositionConstraintCell.createChild('span');containingBlockRectElement.textContent=Common.UIString('Containing Block %d × %d (at %d, %d)',containingBlockRect.width,containingBlockRect.height,containingBlockRect.x,containingBlockRect.y);this._createStickyAncestorChild(Common.UIString('Nearest Layer Shifting Sticky Box'),constraint.nearestLayerShiftingStickyBox());this._createStickyAncestorChild(Common.UIString('Nearest Layer Shifting Containing Block'),constraint.nearestLayerShiftingContainingBlock());}
update(){const layer=this._selection&&this._selection.layer();if(!layer){this._tableElement.remove();this._paintProfilerButton.remove();this._emptyWidget.show(this.contentElement);return;}
this._emptyWidget.detach();this.contentElement.appendChild(this._tableElement);this.contentElement.appendChild(this._paintProfilerButton);this._sizeCell.textContent=Common.UIString('%d × %d (at %d,%d)',layer.width(),layer.height(),layer.offsetX(),layer.offsetY());this._paintCountCell.parentElement.classList.toggle('hidden',!layer.paintCount());this._paintCountCell.textContent=layer.paintCount();this._memoryEstimateCell.textContent=Number.bytesToString(layer.gpuMemoryUsage());layer.requestCompositingReasons().then(this._updateCompositingReasons.bind(this));this._scrollRectsCell.removeChildren();layer.scrollRects().forEach(this._createScrollRectElement.bind(this));this._populateStickyPositionConstraintCell(layer.stickyPositionConstraint());const snapshot=this._selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot?(this._selection).snapshot():null;this._paintProfilerButton.classList.toggle('hidden',!snapshot);}
_buildContent(){this._tableElement=this.contentElement.createChild('table');this._tbodyElement=this._tableElement.createChild('tbody');this._sizeCell=this._createRow(Common.UIString('Size'));this._compositingReasonsCell=this._createRow(Common.UIString('Compositing Reasons'));this._memoryEstimateCell=this._createRow(Common.UIString('Memory estimate'));this._paintCountCell=this._createRow(Common.UIString('Paint count'));this._scrollRectsCell=this._createRow(Common.UIString('Slow scroll regions'));this._stickyPositionConstraintCell=this._createRow(Common.UIString('Sticky position constraint'));this._paintProfilerButton=this.contentElement.createChild('a','hidden link');this._paintProfilerButton.textContent=Common.UIString('Paint Profiler');this._paintProfilerButton.addEventListener('click',this._onPaintProfilerButtonClicked.bind(this));}
_createRow(title){const tr=this._tbodyElement.createChild('tr');const titleCell=tr.createChild('td');titleCell.textContent=title;return tr.createChild('td');}
_updateCompositingReasons(compositingReasons){if(!compositingReasons||!compositingReasons.length){this._compositingReasonsCell.textContent='n/a';return;}
this._compositingReasonsCell.removeChildren();const list=this._compositingReasonsCell.createChild('ul');for(let i=0;i<compositingReasons.length;++i){let text=LayerViewer.LayerDetailsView.CompositingReasonDetail[compositingReasons[i]]||compositingReasons[i];if(/\s.*[^.]$/.test(text))
text+='.';list.createChild('li').textContent=text;}}};LayerViewer.LayerDetailsView.Events={PaintProfilerRequested:Symbol('PaintProfilerRequested')};LayerViewer.LayerDetailsView.CompositingReasonDetail={'transform3D':Common.UIString('Composition due to association with an element with a CSS 3D transform.'),'video':Common.UIString('Composition due to association with a <video> element.'),'canvas':Common.UIString('Composition due to the element being a <canvas> element.'),'plugin':Common.UIString('Composition due to association with a plugin.'),'iFrame':Common.UIString('Composition due to association with an <iframe> element.'),'backfaceVisibilityHidden':Common.UIString('Composition due to association with an element with a "backface-visibility: hidden" style.'),'animation':Common.UIString('Composition due to association with an animated element.'),'filters':Common.UIString('Composition due to association with an element with CSS filters applied.'),'scrollDependentPosition':Common.UIString('Composition due to association with an element with a "position: fixed" or "position: sticky" style.'),'overflowScrollingTouch':Common.UIString('Composition due to association with an element with a "overflow-scrolling: touch" style.'),'blending':Common.UIString('Composition due to association with an element that has blend mode other than "normal".'),'assumedOverlap':Common.UIString('Composition due to association with an element that may overlap other composited elements.'),'overlap':Common.UIString('Composition due to association with an element overlapping other composited elements.'),'negativeZIndexChildren':Common.UIString('Composition due to association with an element with descendants that have a negative z-index.'),'transformWithCompositedDescendants':Common.UIString('Composition due to association with an element with composited descendants.'),'opacityWithCompositedDescendants':Common.UIString('Composition due to association with an element with opacity applied and composited descendants.'),'maskWithCompositedDescendants':Common.UIString('Composition due to association with a masked element and composited descendants.'),'reflectionWithCompositedDescendants':Common.UIString('Composition due to association with an element with a reflection and composited descendants.'),'filterWithCompositedDescendants':Common.UIString('Composition due to association with an element with CSS filters applied and composited descendants.'),'blendingWithCompositedDescendants':Common.UIString('Composition due to association with an element with CSS blending applied and composited descendants.'),'clipsCompositingDescendants':Common.UIString('Composition due to association with an element clipping compositing descendants.'),'perspective':Common.UIString('Composition due to association with an element with perspective applied.'),'preserve3D':Common.UIString('Composition due to association with an element with a "transform-style: preserve-3d" style.'),'root':Common.UIString('Root layer.'),'layerForClip':Common.UIString('Layer for clip.'),'layerForScrollbar':Common.UIString('Layer for scrollbar.'),'layerForScrollingContainer':Common.UIString('Layer for scrolling container.'),'layerForForeground':Common.UIString('Layer for foreground.'),'layerForBackground':Common.UIString('Layer for background.'),'layerForMask':Common.UIString('Layer for mask.'),'layerForVideoOverlay':Common.UIString('Layer for video overlay.'),};LayerViewer.LayerDetailsView._slowScrollRectNames=new Map([[SDK.Layer.ScrollRectType.NonFastScrollable,Common.UIString('Non fast scrollable')],[SDK.Layer.ScrollRectType.TouchEventHandler,Common.UIString('Touch event handler')],[SDK.Layer.ScrollRectType.WheelEventHandler,Common.UIString('Wheel event handler')],[SDK.Layer.ScrollRectType.RepaintsOnScroll,Common.UIString('Repaints on scroll')]]);;LayerViewer.LayerTreeOutline=class extends Common.Object{constructor(layerViewHost){super();this._layerViewHost=layerViewHost;this._layerViewHost.registerView(this);this._treeOutline=new UI.TreeOutlineInShadow();this._treeOutline.element.classList.add('layer-
focus(){this._treeOutline.focus();}
selectObject(selection){this.hoverObject(null);const layer=selection&&selection.layer();const node=layer&&layer[LayerViewer.LayerTreeElement._symbol];if(node)
node.revealAndSelect(true);else if(this._treeOutline.selectedTreeElement)
this._treeOutline.selectedTreeElement.deselect();}
hoverObject(selection){const layer=selection&&selection.layer();const node=layer&&layer[LayerViewer.LayerTreeElement._symbol];if(node===this._lastHoveredNode)
return;if(this._lastHoveredNode)
this._lastHoveredNode.setHovered(false);if(node)
node.setHovered(true);this._lastHoveredNode=node;}
setLayerTree(layerTree){this._layerTree=layerTree;this._update();}
_update(){const showInternalLayers=this._layerViewHost.showInternalLayersSetting().get();const seenLayers=new Map();let root=null;if(this._layerTree){if(!showInternalLayers)
root=this._layerTree.contentRoot();if(!root)
root=this._layerTree.root();}
function updateLayer(layer){if(!layer.drawsContent()&&!showInternalLayers)
return;if(seenLayers.get(layer))
console.assert(false,'Duplicate layer: '+layer.id());seenLayers.set(layer,true);let node=layer[LayerViewer.LayerTreeElement._symbol];let parentLayer=layer.parent();while(parentLayer&&parentLayer!==root&&!parentLayer.drawsContent()&&!showInternalLayers)
parentLayer=parentLayer.parent();const parent=layer===root?this._treeOutline.rootElement():parentLayer[LayerViewer.LayerTreeElement._symbol];if(!parent){console.assert(false,'Parent is not in the tree');return;}
if(!node){node=new LayerViewer.LayerTreeElement(this,layer);parent.appendChild(node);if(!layer.drawsContent())
node.expand();}else{if(node.parent!==parent){const oldSelection=this._treeOutline.selectedTreeElement;if(node.parent)
node.parent.removeChild(node);parent.appendChild(node);if(oldSelection!==this._treeOutline.selectedTreeElement)
oldSelection.select();}
node._update();}}
if(root)
this._layerTree.forEachLayer(updateLayer.bind(this),root);const rootElement=this._treeOutline.rootElement();for(let node=rootElement.firstChild();node&&!node.root;){if(seenLayers.get(node._layer)){node=node.traverseNextTreeElement(false);}else{const nextNode=node.nextSibling||node.parent;node.parent.removeChild(node);if(node===this._lastHoveredNode)
this._lastHoveredNode=null;node=nextNode;}}
if(!this._treeOutline.selectedTreeElement){const elementToSelect=this._layerTree.contentRoot()||this._layerTree.root();if(elementToSelect)
elementToSelect[LayerViewer.LayerTreeElement._symbol].revealAndSelect(true);}}
_onMouseMove(event){const node=this._treeOutline.treeElementFromEvent(event);if(node===this._lastHoveredNode)
return;this._layerViewHost.hoverObject(this._selectionForNode(node));}
_selectedNodeChanged(node){this._layerViewHost.selectObject(this._selectionForNode(node));}
_onContextMenu(event){const selection=this._selectionForNode(this._treeOutline.treeElementFromEvent(event));const contextMenu=new UI.ContextMenu(event);this._layerViewHost.showContextMenu(contextMenu,selection);}
_selectionForNode(node){return node&&node._layer?new LayerViewer.LayerView.LayerSelection(node._layer):null;}};LayerViewer.LayerTreeElement=class extends UI.TreeElement{constructor(tree,layer){super();this._treeOutline=tree;this._layer=layer;this._layer[LayerViewer.LayerTreeElement._symbol]=this;this._update();}
_update(){const node=this._layer.nodeForSelfOrAncestor();const title=createDocumentFragment();title.createTextChild(node?node.simpleSelector():'#'+this._layer.id());const details=title.createChild('span','dimmed');details.textContent=Common.UIString(' (%d × %d)',this._layer.width(),this._layer.height());this.title=title;}
onselect(){this._treeOutline._selectedNodeChanged(this);return false;}
setHovered(hovered){this.listItemElement.classList.toggle('hovered',hovered);}};LayerViewer.LayerTreeElement._symbol=Symbol('layer');;LayerViewer.LayerView=function(){};LayerViewer.LayerView.prototype={hoverObject(selection){},selectObject(selection){},setLayerTree(layerTree){}};LayerViewer.LayerView.Selection=class{constructor(type,layer){this._type=type;this._layer=layer;}
static isEqual(a,b){return a&&b?a._isEqual(b):a===b;}
type(){return this._type;}
layer(){return this._layer;}
_isEqual(other){return false;}};LayerViewer.LayerView.Selection.Type={Layer:Symbol('Layer'),ScrollRect:Symbol('ScrollRect'),Snapshot:Symbol('Snapshot')};LayerViewer.LayerView.LayerSelection=class extends LayerViewer.LayerView.Selection{constructor(layer){console.assert(layer,'LayerSelection with empty layer');super(LayerViewer.LayerView.Selection.Type.Layer,layer);}
_isEqual(other){return other._type===LayerViewer.LayerView.Selection.Type.Layer&&other.layer().id()===this.layer().id();}};LayerViewer.LayerView.ScrollRectSelection=class extends LayerViewer.LayerView.Selection{constructor(layer,scrollRectIndex){super(LayerViewer.LayerView.Selection.Type.ScrollRect,layer);this.scrollRectIndex=scrollRectIndex;}
_isEqual(other){return other._type===LayerViewer.LayerView.Selection.Type.ScrollRect&&this.layer().id()===other.layer().id()&&this.scrollRectIndex===other.scrollRectIndex;}};LayerViewer.LayerView.SnapshotSelection=class extends LayerViewer.LayerView.Selection{constructor(layer,snapshot){super(LayerViewer.LayerView.Selection.Type.Snapshot,layer);this._snapshot=snapshot;}
_isEqual(other){return other._type===LayerViewer.LayerView.Selection.Type.Snapshot&&this.layer().id()===other.layer().id()&&this._snapshot===other._snapshot;}
snapshot(){return this._snapshot;}};LayerViewer.LayerViewHost=class{constructor(){this._views=[];this._selectedObject=null;this._hoveredObject=null;this._showInternalLayersSetting=Common.settings.createSetting('layersShowInternalLayers',false);}
registerView(layerView){this._views.push(layerView);}
setLayerTree(layerTree){this._target=layerTree.target();const selectedLayer=this._selectedObject&&this._selectedObject.layer();if(selectedLayer&&(!layerTree||!layerTree.layerById(selectedLayer.id())))
this.selectObject(null);const hoveredLayer=this._hoveredObject&&this._hoveredObject.layer();if(hoveredLayer&&(!layerTree||!layerTree.layerById(hoveredLayer.id())))
this.hoverObject(null);for(const view of this._views)
view.setLayerTree(layerTree);}
hoverObject(selection){if(LayerViewer.LayerView.Selection.isEqual(this._hoveredObject,selection))
return;this._hoveredObject=selection;const layer=selection&&selection.layer();this._toggleNodeHighlight(layer?layer.nodeForSelfOrAncestor():null);for(const view of this._views)
view.hoverObject(selection);}
selectObject(selection){if(LayerViewer.LayerView.Selection.isEqual(this._selectedObject,selection))
return;this._selectedObject=selection;for(const view of this._views)
view.selectObject(selection);}
selection(){return this._selectedObject;}
showContextMenu(contextMenu,selection){contextMenu.defaultSection().appendCheckboxItem(Common.UIString('Show internal layers'),this._toggleShowInternalLayers.bind(this),this._showInternalLayersSetting.get());const node=selection&&selection.layer()&&selection.layer().nodeForSelfOrAncestor();if(node)
contextMenu.appendApplicableItems(node);contextMenu.show();}
showInternalLayersSetting(){return this._showInternalLayersSetting;}
_toggleShowInternalLayers(){this._showInternalLayersSetting.set(!this._showInternalLayersSetting.get());}
_toggleNodeHighlight(node){if(node){node.highlightForTwoSeconds();return;}
SDK.OverlayModel.hideDOMNodeHighlight();}};;LayerViewer.Layers3DView=class extends UI.VBox{constructor(layerViewHost){super(true);this.registerRequiredCSS('layer_viewer/layers3DView.css');this.contentElement.classList.add('layers-3d-view');this._failBanner=new UI.VBox();this._failBanner.element.classList.add('full-widget-dimmed-banner');this._failBanner.element.createTextChild(Common.UIString('Layer information is not yet available.'));this._layerViewHost=layerViewHost;this._layerViewHost.registerView(this);this._transformController=new LayerViewer.TransformController(this.contentElement);this._transformController.addEventListener(LayerViewer.TransformController.Events.TransformChanged,this._update,this);this._initToolbar();this._canvasElement=this.contentElement.createChild('canvas');this._canvasElement.tabIndex=0;this._canvasElement.addEventListener('dblclick',this._onDoubleClick.bind(this),false);this._canvasElement.addEventListener('mousedown',this._onMouseDown.bind(this),false);this._canvasElement.addEventListener('mouseup',this._onMouseUp.bind(this),false);this._canvasElement.addEventListener('mouseleave',this._onMouseMove.bind(this),false);this._canvasElement.addEventListener('mousemove',this._onMouseMove.bind(this),false);this._canvasElement.addEventListener('contextmenu',this._onContextMenu.bind(this),false);this._lastSelection={};this._layerTree=null;this._textureManager=new LayerViewer.LayerTextureManager(this._update.bind(this));this._chromeTextures=[];this._rects=[];this._layerViewHost.showInternalLayersSetting().addChangeListener(this._update,this);}
setLayerTree(layerTree){this._layerTree=layerTree;this._layerTexture=null;delete this._oldTextureScale;if(this._showPaints())
this._textureManager.setLayerTree(layerTree);this._update();}
showImageForLayer(layer,imageURL){if(!imageURL){this._layerTexture=null;this._update();return;}
UI.loadImage(imageURL).then(image=>{const texture=image&&LayerViewer.LayerTextureManager._createTextureForImage(this._gl,image);this._layerTexture=texture?{layer:layer,texture:texture}:null;this._update();});}
onResize(){this._resizeCanvas();this._update();}
willHide(){this._textureManager.suspend();}
wasShown(){this._textureManager.resume();if(!this._needsUpdate)
return;this._resizeCanvas();this._update();}
updateLayerSnapshot(layer){this._textureManager.layerNeedsUpdate(layer);}
_setOutline(type,selection){this._lastSelection[type]=selection;this._update();}
hoverObject(selection){this._setOutline(LayerViewer.Layers3DView.OutlineType.Hovered,selection);}
selectObject(selection){this._setOutline(LayerViewer.Layers3DView.OutlineType.Hovered,null);this._setOutline(LayerViewer.Layers3DView.OutlineType.Selected,selection);}
snapshotForSelection(selection){if(selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot){const snapshotWithRect=(selection).snapshot();snapshotWithRect.snapshot.addReference();return(Promise.resolve(snapshotWithRect));}
if(selection.layer()){const promise=selection.layer().snapshots()[0];if(promise)
return promise;}
return(Promise.resolve(null));}
_initGL(canvas){const gl=canvas.getContext('webgl');if(!gl)
return null;gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);gl.enable(gl.BLEND);gl.clearColor(0.0,0.0,0.0,0.0);gl.enable(gl.DEPTH_TEST);return gl;}
_createShader(type,script){const shader=this._gl.createShader(type);this._gl.shaderSource(shader,script);this._gl.compileShader(shader);this._gl.attachShader(this._shaderProgram,shader);}
_initShaders(){this._shaderProgram=this._gl.createProgram();this._createShader(this._gl.FRAGMENT_SHADER,LayerViewer.Layers3DView.FragmentShader);this._createShader(this._gl.VERTEX_SHADER,LayerViewer.Layers3DView.VertexShader);this._gl.linkProgram(this._shaderProgram);this._gl.useProgram(this._shaderProgram);this._shaderProgram.vertexPositionAttribute=this._gl.getAttribLocation(this._shaderProgram,'aVertexPosition');this._gl.enableVertexAttribArray(this._shaderProgram.vertexPositionAttribute);this._shaderProgram.vertexColorAttribute=this._gl.getAttribLocation(this._shaderProgram,'aVertexColor');this._gl.enableVertexAttribArray(this._shaderProgram.vertexColorAttribute);this._shaderProgram.textureCoordAttribute=this._gl.getAttribLocation(this._shaderProgram,'aTextureCoord');this._gl.enableVertexAttribArray(this._shaderProgram.textureCoordAttribute);this._shaderProgram.pMatrixUniform=this._gl.getUniformLocation(this._shaderProgram,'uPMatrix');this._shaderProgram.samplerUniform=this._gl.getUniformLocation(this._shaderProgram,'uSampler');}
_resizeCanvas(){this._canvasElement.width=this._canvasElement.offsetWidth*window.devicePixelRatio;this._canvasElement.height=this._canvasElement.offsetHeight*window.devicePixelRatio;}
_updateTransformAndConstraints(){const paddingFraction=0.1;const viewport=this._layerTree.viewportSize();const baseWidth=viewport?viewport.width:this._dimensionsForAutoscale.width;const baseHeight=viewport?viewport.height:this._dimensionsForAutoscale.height;const canvasWidth=this._canvasElement.width;const canvasHeight=this._canvasElement.height;const paddingX=canvasWidth*paddingFraction;const paddingY=canvasHeight*paddingFraction;const scaleX=(canvasWidth-2*paddingX)/baseWidth;const scaleY=(canvasHeight-2*paddingY)/baseHeight;const viewScale=Math.min(scaleX,scaleY);const minScaleConstraint=Math.min(baseWidth/this._dimensionsForAutoscale.width,baseHeight/this._dimensionsForAutoscale.width)/2;this._transformController.setScaleConstraints(minScaleConstraint,10/viewScale);const scale=this._transformController.scale();const rotateX=this._transformController.rotateX();const rotateY=this._transformController.rotateY();this._scale=scale*viewScale;const textureScale=Number.constrain(this._scale,0.1,1);if(textureScale!==this._oldTextureScale){this._oldTextureScale=textureScale;this._textureManager.setScale(textureScale);this.dispatchEventToListeners(LayerViewer.Layers3DView.Events.ScaleChanged,textureScale);}
const scaleAndRotationMatrix=new WebKitCSSMatrix().scale(scale,scale,scale).translate(canvasWidth/2,canvasHeight/2,0).rotate(rotateX,rotateY,0).scale(viewScale,viewScale,viewScale).translate(-baseWidth/2,-baseHeight/2,0);let bounds;for(let i=0;i<this._rects.length;++i)
bounds=UI.Geometry.boundsForTransformedPoints(scaleAndRotationMatrix,this._rects[i].vertices,bounds);this._transformController.clampOffsets((paddingX-bounds.maxX)/window.devicePixelRatio,(canvasWidth-paddingX-bounds.minX)/window.devicePixelRatio,(paddingY-bounds.maxY)/window.devicePixelRatio,(canvasHeight-paddingY-bounds.minY)/window.devicePixelRatio);const offsetX=this._transformController.offsetX()*window.devicePixelRatio;const offsetY=this._transformController.offsetY()*window.devicePixelRatio;this._projectionMatrix=new WebKitCSSMatrix().translate(offsetX,offsetY,0).multiply(scaleAndRotationMatrix);const glProjectionMatrix=new WebKitCSSMatrix().scale(1,-1,-1).translate(-1,-1,0).scale(2/this._canvasElement.width,2/this._canvasElement.height,1/1000000).multiply(this._projectionMatrix);this._gl.uniformMatrix4fv(this._shaderProgram.pMatrixUniform,false,this._arrayFromMatrix(glProjectionMatrix));}
_arrayFromMatrix(m){return new Float32Array([m.m11,m.m12,m.m13,m.m14,m.m21,m.m22,m.m23,m.m24,m.m31,m.m32,m.m33,m.m34,m.m41,m.m42,m.m43,m.m44]);}
_initWhiteTexture(){this._whiteTexture=this._gl.createTexture();this._gl.bindTexture(this._gl.TEXTURE_2D,this._whiteTexture);const whitePixel=new Uint8Array([255,255,255,255]);this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,1,1,0,this._gl.RGBA,this._gl.UNSIGNED_BYTE,whitePixel);}
_initChromeTextures(){function loadChromeTexture(index,url){UI.loadImage(url).then(image=>{this._chromeTextures[index]=image&&LayerViewer.LayerTextureManager._createTextureForImage(this._gl,image)||undefined;});}
loadChromeTexture.call(this,LayerViewer.Layers3DView.ChromeTexture.Left,'Images/chromeLeft.png');loadChromeTexture.call(this,LayerViewer.Layers3DView.ChromeTexture.Middle,'Images/chromeMiddle.png');loadChromeTexture.call(this,LayerViewer.Layers3DView.ChromeTexture.Right,'Images/chromeRight.png');}
_initGLIfNecessary(){if(this._gl)
return this._gl;this._gl=this._initGL(this._canvasElement);if(!this._gl)
return null;this._initShaders();this._initWhiteTexture();this._initChromeTextures();this._textureManager.setContext(this._gl);return this._gl;}
_calculateDepthsAndVisibility(){this._depthByLayerId={};let depth=0;const showInternalLayers=this._layerViewHost.showInternalLayersSetting().get();const root=showInternalLayers?this._layerTree.root():(this._layerTree.contentRoot()||this._layerTree.root());const queue=[root];this._depthByLayerId[root.id()]=0;this._visibleLayers=new Set();while(queue.length>0){const layer=queue.shift();if(showInternalLayers||layer.drawsContent())
this._visibleLayers.add(layer);const children=layer.children();for(let i=0;i<children.length;++i){this._depthByLayerId[children[i].id()]=++depth;queue.push(children[i]);}}
this._maxDepth=depth;}
_depthForLayer(layer){return this._depthByLayerId[layer.id()]*LayerViewer.Layers3DView.LayerSpacing;}
_calculateScrollRectDepth(layer,index){return this._depthForLayer(layer)+index*LayerViewer.Layers3DView.ScrollRectSpacing+1;}
_updateDimensionsForAutoscale(layer){this._dimensionsForAutoscale.width=Math.max(layer.width(),this._dimensionsForAutoscale.width);this._dimensionsForAutoscale.height=Math.max(layer.height(),this._dimensionsForAutoscale.height);}
_calculateLayerRect(layer){if(!this._visibleLayers.has(layer))
return;const selection=new LayerViewer.LayerView.LayerSelection(layer);const rect=new LayerViewer.Layers3DView.Rectangle(selection);rect.setVertices(layer.quad(),this._depthForLayer(layer));this._appendRect(rect);this._updateDimensionsForAutoscale(layer);}
_appendRect(rect){const selection=rect.relatedObject;const isSelected=LayerViewer.LayerView.Selection.isEqual(this._lastSelection[LayerViewer.Layers3DView.OutlineType.Selected],selection);const isHovered=LayerViewer.LayerView.Selection.isEqual(this._lastSelection[LayerViewer.Layers3DView.OutlineType.Hovered],selection);if(isSelected){rect.borderColor=LayerViewer.Layers3DView.SelectedBorderColor;}else if(isHovered){rect.borderColor=LayerViewer.Layers3DView.HoveredBorderColor;const fillColor=rect.fillColor||[255,255,255,1];const maskColor=LayerViewer.Layers3DView.HoveredImageMaskColor;rect.fillColor=[fillColor[0]*maskColor[0]/255,fillColor[1]*maskColor[1]/255,fillColor[2]*maskColor[2]/255,fillColor[3]*maskColor[3]];}else{rect.borderColor=LayerViewer.Layers3DView.BorderColor;}
rect.lineWidth=isSelected?LayerViewer.Layers3DView.SelectedBorderWidth:LayerViewer.Layers3DView.BorderWidth;this._rects.push(rect);}
_calculateLayerScrollRects(layer){const scrollRects=layer.scrollRects();for(let i=0;i<scrollRects.length;++i){const selection=new LayerViewer.LayerView.ScrollRectSelection(layer,i);const rect=new LayerViewer.Layers3DView.Rectangle(selection);rect.calculateVerticesFromRect(layer,scrollRects[i].rect,this._calculateScrollRectDepth(layer,i));rect.fillColor=LayerViewer.Layers3DView.ScrollRectBackgroundColor;this._appendRect(rect);}}
_calculateLayerTileRects(layer){const tiles=this._textureManager.tilesForLayer(layer);for(let i=0;i<tiles.length;++i){const tile=tiles[i];if(!tile.texture)
continue;const selection=new LayerViewer.LayerView.SnapshotSelection(layer,{rect:tile.rect,snapshot:tile.snapshot});const rect=new LayerViewer.Layers3DView.Rectangle(selection);rect.calculateVerticesFromRect(layer,tile.rect,this._depthForLayer(layer)+1);rect.texture=tile.texture;this._appendRect(rect);}}
_calculateRects(){this._rects=[];this._dimensionsForAutoscale={width:0,height:0};this._layerTree.forEachLayer(this._calculateLayerRect.bind(this));if(this._showSlowScrollRectsSetting.get())
this._layerTree.forEachLayer(this._calculateLayerScrollRects.bind(this));if(this._layerTexture&&this._visibleLayers.has(this._layerTexture.layer)){const layer=this._layerTexture.layer;const selection=new LayerViewer.LayerView.LayerSelection(layer);const rect=new LayerViewer.Layers3DView.Rectangle(selection);rect.setVertices(layer.quad(),this._depthForLayer(layer));rect.texture=this._layerTexture.texture;this._appendRect(rect);}else if(this._showPaints()){this._layerTree.forEachLayer(this._calculateLayerTileRects.bind(this));}}
_makeColorsArray(color){let colors=[];const normalizedColor=[color[0]/255,color[1]/255,color[2]/255,color[3]];for(let i=0;i<4;i++)
colors=colors.concat(normalizedColor);return colors;}
_setVertexAttribute(attribute,array,length){const gl=this._gl;const buffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(array),gl.STATIC_DRAW);gl.vertexAttribPointer(attribute,length,gl.FLOAT,false,0,0);}
_drawRectangle(vertices,mode,color,texture){const gl=this._gl;const white=[255,255,255,1];color=color||white;this._setVertexAttribute(this._shaderProgram.vertexPositionAttribute,vertices,3);this._setVertexAttribute(this._shaderProgram.textureCoordAttribute,[0,1,1,1,1,0,0,0],2);this._setVertexAttribute(this._shaderProgram.vertexColorAttribute,this._makeColorsArray(color),color.length);if(texture){gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,texture);gl.uniform1i(this._shaderProgram.samplerUniform,0);}else{gl.bindTexture(gl.TEXTURE_2D,this._whiteTexture);}
const numberOfVertices=vertices.length/3;gl.drawArrays(mode,0,numberOfVertices);}
_drawTexture(vertices,texture,color){this._drawRectangle(vertices,this._gl.TRIANGLE_FAN,color,texture);}
_drawViewportAndChrome(){const viewport=this._layerTree.viewportSize();if(!viewport)
return;const drawChrome=!Common.moduleSetting('frameViewerHideChromeWindow').get()&&this._chromeTextures.length>=3&&this._chromeTextures.indexOf(undefined)<0;const z=(this._maxDepth+1)*LayerViewer.Layers3DView.LayerSpacing;const borderWidth=Math.ceil(LayerViewer.Layers3DView.ViewportBorderWidth*this._scale);let vertices=[viewport.width,0,z,viewport.width,viewport.height,z,0,viewport.height,z,0,0,z];this._gl.lineWidth(borderWidth);this._drawRectangle(vertices,drawChrome?this._gl.LINE_STRIP:this._gl.LINE_LOOP,LayerViewer.Layers3DView.ViewportBorderColor);if(!drawChrome)
return;const borderAdjustment=LayerViewer.Layers3DView.ViewportBorderWidth/2;const viewportWidth=this._layerTree.viewportSize().width+2*borderAdjustment;const chromeHeight=this._chromeTextures[0].image.naturalHeight;const middleFragmentWidth=viewportWidth-this._chromeTextures[0].image.naturalWidth-this._chromeTextures[2].image.naturalWidth;let x=-borderAdjustment;const y=-chromeHeight;for(let i=0;i<this._chromeTextures.length;++i){const width=i===LayerViewer.Layers3DView.ChromeTexture.Middle?middleFragmentWidth:this._chromeTextures[i].image.naturalWidth;if(width<0||x+width>viewportWidth)
break;vertices=[x,y,z,x+width,y,z,x+width,y+chromeHeight,z,x,y+chromeHeight,z];this._drawTexture(vertices,(this._chromeTextures[i]));x+=width;}}
_drawViewRect(rect){const vertices=rect.vertices;if(rect.texture)
this._drawTexture(vertices,rect.texture,rect.fillColor||undefined);else if(rect.fillColor)
this._drawRectangle(vertices,this._gl.TRIANGLE_FAN,rect.fillColor);this._gl.lineWidth(rect.lineWidth);if(rect.borderColor)
this._drawRectangle(vertices,this._gl.LINE_LOOP,rect.borderColor);}
_update(){if(!this.isShowing()){this._needsUpdate=true;return;}
if(!this._layerTree||!this._layerTree.root()){this._failBanner.show(this.contentElement);return;}
const gl=this._initGLIfNecessary();if(!gl){this._failBanner.element.removeChildren();this._failBanner.element.appendChild(this._webglDisabledBanner());this._failBanner.show(this.contentElement);return;}
this._failBanner.detach();this._gl.viewportWidth=this._canvasElement.width;this._gl.viewportHeight=this._canvasElement.height;this._calculateDepthsAndVisibility();this._calculateRects();this._updateTransformAndConstraints();gl.viewport(0,0,gl.viewportWidth,gl.viewportHeight);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this._rects.forEach(this._drawViewRect.bind(this));this._drawViewportAndChrome();}
_webglDisabledBanner(){const fragment=this.contentElement.ownerDocument.createDocumentFragment();fragment.createChild('div').textContent=Common.UIString('Can\'t display layers,');fragment.createChild('div').textContent=Common.UIString('WebGL support is disabled in your browser.');fragment.appendChild(UI.formatLocalized('Check %s for possible reasons.',[UI.XLink.create('about:gpu')]));return fragment;}
_selectionFromEventPoint(event){if(!this._layerTree)
return null;let closestIntersectionPoint=Infinity;let closestObject=null;const projectionMatrix=new WebKitCSSMatrix().scale(1,-1,-1).translate(-1,-1,0).multiply(this._projectionMatrix);const x0=(event.clientX-this._canvasElement.totalOffsetLeft())*window.devicePixelRatio;const y0=-(event.clientY-this._canvasElement.totalOffsetTop())*window.devicePixelRatio;function checkIntersection(rect){if(!rect.relatedObject)
return;const t=rect.intersectWithLine(projectionMatrix,x0,y0);if(t<closestIntersectionPoint){closestIntersectionPoint=t;closestObject=rect.relatedObject;}}
this._rects.forEach(checkIntersection);return closestObject;}
_createVisibilitySetting(caption,name,value,toolbar){const setting=Common.settings.createSetting(name,value);setting.setTitle(Common.UIString(caption));setting.addChangeListener(this._update,this);toolbar.appendToolbarItem(new UI.ToolbarSettingCheckbox(setting));return setting;}
_initToolbar(){this._panelToolbar=this._transformController.toolbar();this.contentElement.appendChild(this._panelToolbar.element);this._showSlowScrollRectsSetting=this._createVisibilitySetting('Slow scroll rects','frameViewerShowSlowScrollRects',true,this._panelToolbar);this._showPaintsSetting=this._createVisibilitySetting('Paints','frameViewerShowPaints',true,this._panelToolbar);this._showPaintsSetting.addChangeListener(this._updatePaints,this);Common.moduleSetting('frameViewerHideChromeWindow').addChangeListener(this._update,this);}
_onContextMenu(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Reset View'),this._transformController.resetAndNotify.bind(this._transformController),false);const selection=this._selectionFromEventPoint(event);if(selection&&selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot){contextMenu.defaultSection().appendItem(Common.UIString('Show Paint Profiler'),this.dispatchEventToListeners.bind(this,LayerViewer.Layers3DView.Events.PaintProfilerRequested,selection),false);}
this._layerViewHost.showContextMenu(contextMenu,selection);}
_onMouseMove(event){if(event.which)
return;this._layerViewHost.hoverObject(this._selectionFromEventPoint(event));}
_onMouseDown(event){this._mouseDownX=event.clientX;this._mouseDownY=event.clientY;}
_onMouseUp(event){const maxDistanceInPixels=6;if(this._mouseDownX&&Math.abs(event.clientX-this._mouseDownX)<maxDistanceInPixels&&Math.abs(event.clientY-this._mouseDownY)<maxDistanceInPixels)
this._layerViewHost.selectObject(this._selectionFromEventPoint(event));delete this._mouseDownX;delete this._mouseDownY;}
_onDoubleClick(event){const selection=this._selectionFromEventPoint(event);if(selection&&(selection.type()===LayerViewer.LayerView.Selection.Type.Snapshot||selection.layer()))
this.dispatchEventToListeners(LayerViewer.Layers3DView.Events.PaintProfilerRequested,selection);event.stopPropagation();}
_updatePaints(){if(this._showPaints()){this._textureManager.setLayerTree(this._layerTree);this._textureManager.forceUpdate();}else{this._textureManager.reset();}
this._update();}
_showPaints(){return this._showPaintsSetting.get();}};LayerViewer.Layers3DView.LayerStyle;LayerViewer.Layers3DView.OutlineType={Hovered:'hovered',Selected:'selected'};LayerViewer.Layers3DView.Events={PaintProfilerRequested:Symbol('PaintProfilerRequested'),ScaleChanged:Symbol('ScaleChanged')};LayerViewer.Layers3DView.ChromeTexture={Left:0,Middle:1,Right:2};LayerViewer.Layers3DView.ScrollRectTitles={RepaintsOnScroll:Common.UIString('repaints on scroll'),TouchEventHandler:Common.UIString('touch event listener'),WheelEventHandler:Common.UIString('mousewheel event listener')};LayerViewer.Layers3DView.FragmentShader=''+'precision mediump float;\n'+'varying vec4 vColor;\n'+'varying vec2 vTextureCoord;\n'+'uniform sampler2D uSampler;\n'+'void main(void)\n'+'{\n'+' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)) * vColor;\n'+'}';LayerViewer.Layers3DView.VertexShader=''+'attribute vec3 aVertexPosition;\n'+'attribute vec2 aTextureCoord;\n'+'attribute vec4 aVertexColor;\n'+'uniform mat4 uPMatrix;\n'+'varying vec2 vTextureCoord;\n'+'varying vec4 vColor;\n'+'void main(void)\n'+'{\n'+'gl_Position = uPMatrix * vec4(aVertexPosition, 1.0);\n'+'vColor = aVertexColor;\n'+'vTextureCoord = aTextureCoord;\n'+'}';LayerViewer.Layers3DView.HoveredBorderColor=[0,0,255,1];LayerViewer.Layers3DView.SelectedBorderColor=[0,255,0,1];LayerViewer.Layers3DView.BorderColor=[0,0,0,1];LayerViewer.Layers3DView.ViewportBorderColor=[160,160,160,1];LayerViewer.Layers3DView.ScrollRectBackgroundColor=[178,100,100,0.6];LayerViewer.Layers3DView.HoveredImageMaskColor=[200,200,255,1];LayerViewer.Layers3DView.BorderWidth=1;LayerViewer.Layers3DView.SelectedBorderWidth=2;LayerViewer.Layers3DView.ViewportBorderWidth=3;LayerViewer.Layers3DView.LayerSpacing=20;LayerViewer.Layers3DView.ScrollRectSpacing=4;LayerViewer.LayerTextureManager=class{constructor(textureUpdatedCallback){this._textureUpdatedCallback=textureUpdatedCallback;this._throttler=new Common.Throttler(0);this._scale=0;this._active=false;this.reset();}
static _createTextureForImage(gl,image){const texture=gl.createTexture();texture.image=image;gl.bindTexture(gl.TEXTURE_2D,texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,1);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,texture.image);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.bindTexture(gl.TEXTURE_2D,null);return texture;}
reset(){if(this._tilesByLayer)
this.setLayerTree(null);this._tilesByLayer=new Map();this._queue=[];}
setContext(glContext){this._gl=glContext;if(this._scale)
this._updateTextures();}
suspend(){this._active=false;}
resume(){this._active=true;if(this._queue.length)
this._update();}
setLayerTree(layerTree){const newLayers=new Set();const oldLayers=Array.from(this._tilesByLayer.keys());if(layerTree){layerTree.forEachLayer(layer=>{if(!layer.drawsContent())
return;newLayers.add(layer);if(!this._tilesByLayer.has(layer)){this._tilesByLayer.set(layer,[]);this.layerNeedsUpdate(layer);}});}
if(!oldLayers.length)
this.forceUpdate();for(const layer of oldLayers){if(newLayers.has(layer))
continue;this._tilesByLayer.get(layer).forEach(tile=>tile.dispose());this._tilesByLayer.delete(layer);}}
_setSnapshotsForLayer(layer,snapshots){const oldSnapshotsToTiles=new Map((this._tilesByLayer.get(layer)||[]).map(tile=>[tile.snapshot,tile]));const newTiles=[];const reusedTiles=[];for(const snapshot of snapshots){const oldTile=oldSnapshotsToTiles.get(snapshot);if(oldTile){reusedTiles.push(oldTile);oldSnapshotsToTiles.delete(oldTile);}else{newTiles.push(new LayerViewer.LayerTextureManager.Tile(snapshot));}}
this._tilesByLayer.set(layer,reusedTiles.concat(newTiles));for(const tile of oldSnapshotsToTiles.values())
tile.dispose();if(!this._gl||!this._scale)
return Promise.resolve();return Promise.all(newTiles.map(tile=>tile.update(this._gl,this._scale))).then(this._textureUpdatedCallback);}
setScale(scale){if(this._scale&&this._scale>=scale)
return;this._scale=scale;this._updateTextures();}
tilesForLayer(layer){return this._tilesByLayer.get(layer)||[];}
layerNeedsUpdate(layer){if(this._queue.indexOf(layer)<0)
this._queue.push(layer);if(this._active)
this._throttler.schedule(this._update.bind(this));}
forceUpdate(){this._queue.forEach(layer=>this._updateLayer(layer));this._queue=[];this._update();}
_update(){const layer=this._queue.shift();if(!layer)
return Promise.resolve();if(this._queue.length)
this._throttler.schedule(this._update.bind(this));return this._updateLayer(layer);}
_updateLayer(layer){return Promise.all(layer.snapshots()).then(snapshots=>this._setSnapshotsForLayer(layer,snapshots.filter(snapshot=>!!snapshot)));}
_updateTextures(){if(!this._gl)
return;if(!this._scale)
return;for(const tiles of this._tilesByLayer.values()){for(const tile of tiles){const promise=tile.updateScale(this._gl,this._scale);if(promise)
promise.then(this._textureUpdatedCallback);}}}};LayerViewer.Layers3DView.Rectangle=class{constructor(relatedObject){this.relatedObject=relatedObject;this.lineWidth=1;this.borderColor=null;this.fillColor=null;this.texture=null;}
setVertices(quad,z){this.vertices=[quad[0],quad[1],z,quad[2],quad[3],z,quad[4],quad[5],z,quad[6],quad[7],z];}
_calculatePointOnQuad(quad,ratioX,ratioY){const x0=quad[0];const y0=quad[1];const x1=quad[2];const y1=quad[3];const x2=quad[4];const y2=quad[5];const x3=quad[6];const y3=quad[7];const firstSidePointX=x0+ratioX*(x1-x0);const firstSidePointY=y0+ratioX*(y1-y0);const thirdSidePointX=x3+ratioX*(x2-x3);const thirdSidePointY=y3+ratioX*(y2-y3);const x=firstSidePointX+ratioY*(thirdSidePointX-firstSidePointX);const y=firstSidePointY+ratioY*(thirdSidePointY-firstSidePointY);return[x,y];}
calculateVerticesFromRect(layer,rect,z){const quad=layer.quad();const rx1=rect.x/layer.width();const rx2=(rect.x+rect.width)/layer.width();const ry1=rect.y/layer.height();const ry2=(rect.y+rect.height)/layer.height();const rectQuad=this._calculatePointOnQuad(quad,rx1,ry1).concat(this._calculatePointOnQuad(quad,rx2,ry1)).concat(this._calculatePointOnQuad(quad,rx2,ry2)).concat(this._calculatePointOnQuad(quad,rx1,ry2));this.setVertices(rectQuad,z);}
intersectWithLine(matrix,x0,y0){let i;const points=[];for(i=0;i<4;++i){points[i]=UI.Geometry.multiplyVectorByMatrixAndNormalize(new UI.Geometry.Vector(this.vertices[i*3],this.vertices[i*3+1],this.vertices[i*3+2]),matrix);}
const normal=UI.Geometry.crossProduct(UI.Geometry.subtract(points[1],points[0]),UI.Geometry.subtract(points[2],points[1]));const A=normal.x;const B=normal.y;const C=normal.z;const D=-(A*points[0].x+B*points[0].y+C*points[0].z);const t=-(D+A*x0+B*y0)/C;const pt=new UI.Geometry.Vector(x0,y0,t);const tVects=points.map(UI.Geometry.subtract.bind(null,pt));for(i=0;i<tVects.length;++i){const product=UI.Geometry.scalarProduct(normal,UI.Geometry.crossProduct(tVects[i],tVects[(i+1)%tVects.length]));if(product<0)
return undefined;}
return t;}};LayerViewer.LayerTextureManager.Tile=class{constructor(snapshotWithRect){this.snapshot=snapshotWithRect.snapshot;this.rect=snapshotWithRect.rect;this.scale=0;this.texture=null;}
dispose(){this.snapshot.release();if(this.texture){this._gl.deleteTexture(this.texture);this.texture=null;}}
updateScale(glContext,scale){if(this.texture&&this.scale>=scale)
return null;return this.update(glContext,scale);}
async update(glContext,scale){this._gl=glContext;this.scale=scale;const imageURL=await this.snapshot.replay(scale);const image=imageURL&&await UI.loadImage(imageURL);this.texture=image&&LayerViewer.LayerTextureManager._createTextureForImage(glContext,image);}};;LayerViewer.PaintProfilerView=class extends UI.HBox{constructor(showImageCallback){super(true);this.registerRequiredCSS('layer_viewer/paintProfiler.css');this.contentElement.classList.add('paint-profiler-overview');this._canvasContainer=this.contentElement.createChild('div','paint-profiler-canvas-container');this._progressBanner=this.contentElement.createChild('div','full-widget-dimmed-banner hidden');this._progressBanner.textContent=Common.UIString('Profiling\u2026');this._pieChart=new PerfUI.PieChart({chartName:ls`Profiling Results`,size:55,formatter:this._formatPieChartTime.bind(this)});this._pieChart.element.classList.add('paint-profiler-pie-chart');this.contentElement.appendChild(this._pieChart.element);this._showImageCallback=showImageCallback;this._canvas=this._canvasContainer.createChild('canvas','fill');this._context=this._canvas.getContext('2d');this._selectionWindow=new PerfUI.OverviewGrid.Window(this._canvasContainer);this._selectionWindow.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);this._innerBarWidth=4*window.devicePixelRatio;this._minBarHeight=window.devicePixelRatio;this._barPaddingWidth=2*window.devicePixelRatio;this._outerBarWidth=this._innerBarWidth+this._barPaddingWidth;this._pendingScale=1;this._scale=this._pendingScale;this._reset();}
static categories(){if(LayerViewer.PaintProfilerView._categories)
return LayerViewer.PaintProfilerView._categories;LayerViewer.PaintProfilerView._categories={shapes:new LayerViewer.PaintProfilerCategory('shapes',Common.UIString('Shapes'),'rgb(255, 161, 129)'),bitmap:new LayerViewer.PaintProfilerCategory('bitmap',Common.UIString('Bitmap'),'rgb(136, 196, 255)'),text:new LayerViewer.PaintProfilerCategory('text',Common.UIString('Text'),'rgb(180, 255, 137)'),misc:new LayerViewer.PaintProfilerCategory('misc',Common.UIString('Misc'),'rgb(206, 160, 255)')};return LayerViewer.PaintProfilerView._categories;}
static _initLogItemCategories(){if(LayerViewer.PaintProfilerView._logItemCategoriesMap)
return LayerViewer.PaintProfilerView._logItemCategoriesMap;const categories=LayerViewer.PaintProfilerView.categories();const logItemCategories={};logItemCategories['Clear']=categories['misc'];logItemCategories['DrawPaint']=categories['misc'];logItemCategories['DrawData']=categories['misc'];logItemCategories['SetMatrix']=categories['misc'];logItemCategories['PushCull']=categories['misc'];logItemCategories['PopCull']=categories['misc'];logItemCategories['Translate']=categories['misc'];logItemCategories['Scale']=categories['misc'];logItemCategories['Concat']=categories['misc'];logItemCategories['Restore']=categories['misc'];logItemCategories['SaveLayer']=categories['misc'];logItemCategories['Save']=categories['misc'];logItemCategories['BeginCommentGroup']=categories['misc'];logItemCategories['AddComment']=categories['misc'];logItemCategories['EndCommentGroup']=categories['misc'];logItemCategories['ClipRect']=categories['misc'];logItemCategories['ClipRRect']=categories['misc'];logItemCategories['ClipPath']=categories['misc'];logItemCategories['ClipRegion']=categories['misc'];logItemCategories['DrawPoints']=categories['shapes'];logItemCategories['DrawRect']=categories['shapes'];logItemCategories['DrawOval']=categories['shapes'];logItemCategories['DrawRRect']=categories['shapes'];logItemCategories['DrawPath']=categories['shapes'];logItemCategories['DrawVertices']=categories['shapes'];logItemCategories['DrawDRRect']=categories['shapes'];logItemCategories['DrawBitmap']=categories['bitmap'];logItemCategories['DrawBitmapRectToRect']=categories['bitmap'];logItemCategories['DrawBitmapMatrix']=categories['bitmap'];logItemCategories['DrawBitmapNine']=categories['bitmap'];logItemCategories['DrawSprite']=categories['bitmap'];logItemCategories['DrawPicture']=categories['bitmap'];logItemCategories['DrawText']=categories['text'];logItemCategories['DrawPosText']=categories['text'];logItemCategories['DrawPosTextH']=categories['text'];logItemCategories['DrawTextOnPath']=categories['text'];LayerViewer.PaintProfilerView._logItemCategoriesMap=logItemCategories;return logItemCategories;}
static _categoryForLogItem(logItem){const method=logItem.method.toTitleCase();const logItemCategories=LayerViewer.PaintProfilerView._initLogItemCategories();let result=logItemCategories[method];if(!result){result=LayerViewer.PaintProfilerView.categories()['misc'];logItemCategories[method]=result;}
return result;}
onResize(){this._update();}
async setSnapshotAndLog(snapshot,log,clipRect){this._reset();this._snapshot=snapshot;if(this._snapshot)
this._snapshot.addReference();this._log=log;this._logCategories=this._log.map(LayerViewer.PaintProfilerView._categoryForLogItem);if(!this._snapshot){this._update();this._pieChart.setTotal(0);this._selectionWindow.setEnabled(false);return;}
this._selectionWindow.setEnabled(true);this._progressBanner.classList.remove('hidden');this._updateImage();const profiles=await snapshot.profile(clipRect);this._progressBanner.classList.add('hidden');this._profiles=profiles;this._update();this._updatePieChart();}
setScale(scale){const needsUpdate=scale>this._scale;const predictiveGrowthFactor=2;this._pendingScale=Math.min(1,scale*predictiveGrowthFactor);if(needsUpdate&&this._snapshot)
this._updateImage();}
_update(){this._canvas.width=this._canvasContainer.clientWidth*window.devicePixelRatio;this._canvas.height=this._canvasContainer.clientHeight*window.devicePixelRatio;this._samplesPerBar=0;if(!this._profiles||!this._profiles.length)
return;const maxBars=Math.floor((this._canvas.width-2*this._barPaddingWidth)/this._outerBarWidth);const sampleCount=this._log.length;this._samplesPerBar=Math.ceil(sampleCount/maxBars);let maxBarTime=0;const barTimes=[];const barHeightByCategory=[];let heightByCategory={};for(let i=0,lastBarIndex=0,lastBarTime=0;i<sampleCount;){let categoryName=(this._logCategories[i]&&this._logCategories[i].name)||'misc';const sampleIndex=this._log[i].commandIndex;for(let row=0;row<this._profiles.length;row++){const sample=this._profiles[row][sampleIndex];lastBarTime+=sample;heightByCategory[categoryName]=(heightByCategory[categoryName]||0)+sample;}
++i;if(i-lastBarIndex===this._samplesPerBar||i===sampleCount){const factor=this._profiles.length*(i-lastBarIndex);lastBarTime/=factor;for(categoryName in heightByCategory)
heightByCategory[categoryName]/=factor;barTimes.push(lastBarTime);barHeightByCategory.push(heightByCategory);if(lastBarTime>maxBarTime)
maxBarTime=lastBarTime;lastBarTime=0;heightByCategory={};lastBarIndex=i;}}
const paddingHeight=4*window.devicePixelRatio;const scale=(this._canvas.height-paddingHeight-this._minBarHeight)/maxBarTime;for(let i=0;i<barTimes.length;++i){for(const categoryName in barHeightByCategory[i])
barHeightByCategory[i][categoryName]*=(barTimes[i]*scale+this._minBarHeight)/barTimes[i];this._renderBar(i,barHeightByCategory[i]);}}
_renderBar(index,heightByCategory){const categories=LayerViewer.PaintProfilerView.categories();let currentHeight=0;const x=this._barPaddingWidth+index*this._outerBarWidth;for(const categoryName in categories){if(!heightByCategory[categoryName])
continue;currentHeight+=heightByCategory[categoryName];const y=this._canvas.height-currentHeight;this._context.fillStyle=categories[categoryName].color;this._context.fillRect(x,y,this._innerBarWidth,heightByCategory[categoryName]);}}
_onWindowChanged(){this.dispatchEventToListeners(LayerViewer.PaintProfilerView.Events.WindowChanged);this._updatePieChart();if(this._updateImageTimer)
return;this._updateImageTimer=setTimeout(this._updateImage.bind(this),100);}
_updatePieChart(){const window=this.selectionWindow();if(!this._profiles||!this._profiles.length||!window)
return;let totalTime=0;const timeByCategory={};for(let i=window.left;i<window.right;++i){const logEntry=this._log[i];const category=LayerViewer.PaintProfilerView._categoryForLogItem(logEntry);timeByCategory[category.color]=timeByCategory[category.color]||0;for(let j=0;j<this._profiles.length;++j){const time=this._profiles[j][logEntry.commandIndex];totalTime+=time;timeByCategory[category.color]+=time;}}
this._pieChart.setTotal(totalTime/this._profiles.length);for(const color in timeByCategory)
this._pieChart.addSlice(timeByCategory[color]/this._profiles.length,color);}
_formatPieChartTime(value){return Number.millisToString(value*1000,true);}
selectionWindow(){if(!this._log)
return null;const screenLeft=this._selectionWindow.windowLeft*this._canvas.width;const screenRight=this._selectionWindow.windowRight*this._canvas.width;const barLeft=Math.floor(screenLeft/this._outerBarWidth);const barRight=Math.floor((screenRight+this._innerBarWidth-this._barPaddingWidth/2)/this._outerBarWidth);const stepLeft=Number.constrain(barLeft*this._samplesPerBar,0,this._log.length-1);const stepRight=Number.constrain(barRight*this._samplesPerBar,0,this._log.length);return{left:stepLeft,right:stepRight};}
_updateImage(){delete this._updateImageTimer;let left;let right;const window=this.selectionWindow();if(this._profiles&&this._profiles.length&&window){left=this._log[window.left].commandIndex;right=this._log[window.right-1].commandIndex;}
const scale=this._pendingScale;this._snapshot.replay(scale,left,right).then(image=>{if(!image)
return;this._scale=scale;this._showImageCallback(image);});}
_reset(){if(this._snapshot)
this._snapshot.release();this._snapshot=null;this._profiles=null;this._selectionWindow.reset();this._selectionWindow.setEnabled(false);}};LayerViewer.PaintProfilerView.Events={WindowChanged:Symbol('WindowChanged')};LayerViewer.PaintProfilerCommandLogView=class extends UI.ThrottledWidget{constructor(){super();this.setMinimumSize(100,25);this.element.classList.add('overflow-auto');this._treeOutline=new UI.TreeOutlineInShadow();this.element.appendChild(this._treeOutline.element);this._log=[];}
setCommandLog(log){this._log=log;this._treeItemCache=new Map();this.updateWindow({left:0,right:this._log.length});}
_appendLogItem(logItem){let treeElement=this._treeItemCache.get(logItem);if(!treeElement){treeElement=new LayerViewer.LogTreeElement(this,logItem);this._treeItemCache.set(logItem,treeElement);}else if(treeElement.parent){return;}
this._treeOutline.appendChild(treeElement);}
updateWindow(selectionWindow){this._selectionWindow=selectionWindow;this.update();}
doUpdate(){if(!this._selectionWindow||!this._log.length){this._treeOutline.removeChildren();return Promise.resolve();}
const root=this._treeOutline.rootElement();for(;;){const child=root.firstChild();if(!child||child._logItem.commandIndex>=this._selectionWindow.left)
break;root.removeChildAtIndex(0);}
for(;;){const child=root.lastChild();if(!child||child._logItem.commandIndex<this._selectionWindow.right)
break;root.removeChildAtIndex(root.children().length-1);}
for(let i=this._selectionWindow.left,right=this._selectionWindow.right;i<right;++i)
this._appendLogItem(this._log[i]);return Promise.resolve();}};LayerViewer.LogTreeElement=class extends UI.TreeElement{constructor(ownerView,logItem){super('',!!logItem.params);this._logItem=logItem;this._ownerView=ownerView;this._filled=false;}
onattach(){this._update();}
onpopulate(){for(const param in this._logItem.params)
LayerViewer.LogPropertyTreeElement._appendLogPropertyItem(this,param,this._logItem.params[param]);}
_paramToString(param,name){if(typeof param!=='object')
return typeof param==='string'&&param.length>100?name:JSON.stringify(param);let str='';let keyCount=0;for(const key in param){if(++keyCount>4||typeof param[key]==='object'||(typeof param[key]==='string'&&param[key].length>100))
return name;if(str)
str+=', ';str+=param[key];}
return str;}
_paramsToString(params){let str='';for(const key in params){if(str)
str+=', ';str+=this._paramToString(params[key],key);}
return str;}
_update(){const title=createDocumentFragment();title.createTextChild(this._logItem.method+'('+this._paramsToString(this._logItem.params)+')');this.title=title;}};LayerViewer.LogPropertyTreeElement=class extends UI.TreeElement{constructor(property){super();this._property=property;}
static _appendLogPropertyItem(element,name,value){const treeElement=new LayerViewer.LogPropertyTreeElement({name:name,value:value});element.appendChild(treeElement);if(value&&typeof value==='object'){for(const property in value)
LayerViewer.LogPropertyTreeElement._appendLogPropertyItem(treeElement,property,value[property]);}}
onattach(){const title=createDocumentFragment();const nameElement=title.createChild('span','name');nameElement.textContent=this._property.name;const separatorElement=title.createChild('span','separator');separatorElement.textContent=': ';if(this._property.value===null||typeof this._property.value!=='object'){const valueElement=title.createChild('span','value');valueElement.textContent=JSON.stringify(this._property.value);valueElement.classList.add('cm-js-'+(this._property.value===null?'null':typeof this._property.value));}
this.title=title;}};LayerViewer.PaintProfilerCategory=class{constructor(name,title,color){this.name=name;this.title=title;this.color=color;}};;LayerViewer.TransformController=class extends Common.Object{constructor(element,disableRotate){super();this._shortcuts={};this.element=element;if(this.element.tabIndex<0)
this.element.tabIndex=0;this._registerShortcuts();UI.installDragHandle(element,this._onDragStart.bind(this),this._onDrag.bind(this),this._onDragEnd.bind(this),'move',null);element.addEventListener('keydown',this._onKeyDown.bind(this),false);element.addEventListener('keyup',this._onKeyUp.bind(this),false);element.addEventListener('mousewheel',this._onMouseWheel.bind(this),false);this._minScale=0;this._maxScale=Infinity;this._controlPanelToolbar=new UI.Toolbar('transform-control-panel');this._modeButtons={};if(!disableRotate){const panModeButton=new UI.ToolbarToggle(Common.UIString('Pan mode (X)'),'largeicon-pan');panModeButton.addEventListener(UI.ToolbarButton.Events.Click,this._setMode.bind(this,LayerViewer.TransformController.Modes.Pan));this._modeButtons[LayerViewer.TransformController.Modes.Pan]=panModeButton;this._controlPanelToolbar.appendToolbarItem(panModeButton);const rotateModeButton=new UI.ToolbarToggle(Common.UIString('Rotate mode (V)'),'largeicon-rotate');rotateModeButton.addEventListener(UI.ToolbarButton.Events.Click,this._setMode.bind(this,LayerViewer.TransformController.Modes.Rotate));this._modeButtons[LayerViewer.TransformController.Modes.Rotate]=rotateModeButton;this._controlPanelToolbar.appendToolbarItem(rotateModeButton);}
this._setMode(LayerViewer.TransformController.Modes.Pan);const resetButton=new UI.ToolbarButton(Common.UIString('Reset transform (0)'),'largeicon-center');resetButton.addEventListener(UI.ToolbarButton.Events.Click,this.resetAndNotify.bind(this,undefined));this._controlPanelToolbar.appendToolbarItem(resetButton);this._reset();}
toolbar(){return this._controlPanelToolbar;}
_onKeyDown(event){if(event.keyCode===UI.KeyboardShortcut.Keys.Shift.code){this._toggleMode();return;}
const shortcutKey=UI.KeyboardShortcut.makeKeyFromEventIgnoringModifiers(event);const handler=this._shortcuts[shortcutKey];if(handler&&handler(event))
event.consume();}
_onKeyUp(event){if(event.keyCode===UI.KeyboardShortcut.Keys.Shift.code)
this._toggleMode();}
_addShortcuts(keys,handler){for(let i=0;i<keys.length;++i)
this._shortcuts[keys[i].key]=handler;}
_registerShortcuts(){this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.ResetView,this.resetAndNotify.bind(this));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.PanMode,this._setMode.bind(this,LayerViewer.TransformController.Modes.Pan));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.RotateMode,this._setMode.bind(this,LayerViewer.TransformController.Modes.Rotate));const zoomFactor=1.1;this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.ZoomIn,this._onKeyboardZoom.bind(this,zoomFactor));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.ZoomOut,this._onKeyboardZoom.bind(this,1/zoomFactor));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.Up,this._onKeyboardPanOrRotate.bind(this,0,-1));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.Down,this._onKeyboardPanOrRotate.bind(this,0,1));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.Left,this._onKeyboardPanOrRotate.bind(this,-1,0));this._addShortcuts(UI.ShortcutsScreen.LayersPanelShortcuts.Right,this._onKeyboardPanOrRotate.bind(this,1,0));}
_postChangeEvent(){this.dispatchEventToListeners(LayerViewer.TransformController.Events.TransformChanged);}
_reset(){this._scale=1;this._offsetX=0;this._offsetY=0;this._rotateX=0;this._rotateY=0;}
_toggleMode(){this._setMode(this._mode===LayerViewer.TransformController.Modes.Pan?LayerViewer.TransformController.Modes.Rotate:LayerViewer.TransformController.Modes.Pan);}
_setMode(mode){if(this._mode===mode)
return;this._mode=mode;this._updateModeButtons();this.element.focus();}
_updateModeButtons(){for(const mode in this._modeButtons)
this._modeButtons[mode].setToggled(mode===this._mode);}
resetAndNotify(event){this._reset();this._postChangeEvent();if(event)
event.preventDefault();this.element.focus();}
setScaleConstraints(minScale,maxScale){this._minScale=minScale;this._maxScale=maxScale;this._scale=Number.constrain(this._scale,minScale,maxScale);}
clampOffsets(minX,maxX,minY,maxY){this._offsetX=Number.constrain(this._offsetX,minX,maxX);this._offsetY=Number.constrain(this._offsetY,minY,maxY);}
scale(){return this._scale;}
offsetX(){return this._offsetX;}
offsetY(){return this._offsetY;}
rotateX(){return this._rotateX;}
rotateY(){return this._rotateY;}
_onScale(scaleFactor,x,y){scaleFactor=Number.constrain(this._scale*scaleFactor,this._minScale,this._maxScale)/this._scale;this._scale*=scaleFactor;this._offsetX-=(x-this._offsetX)*(scaleFactor-1);this._offsetY-=(y-this._offsetY)*(scaleFactor-1);this._postChangeEvent();}
_onPan(offsetX,offsetY){this._offsetX+=offsetX;this._offsetY+=offsetY;this._postChangeEvent();}
_onRotate(rotateX,rotateY){this._rotateX=rotateX;this._rotateY=rotateY;this._postChangeEvent();}
_onKeyboardZoom(zoomFactor){this._onScale(zoomFactor,this.element.clientWidth/2,this.element.clientHeight/2);}
_onKeyboardPanOrRotate(xMultiplier,yMultiplier){const panStepInPixels=6;const rotateStepInDegrees=5;if(this._mode===LayerViewer.TransformController.Modes.Rotate){this._onRotate(this._rotateX+yMultiplier*rotateStepInDegrees,this._rotateY+xMultiplier*rotateStepInDegrees);}else{this._onPan(xMultiplier*panStepInPixels,yMultiplier*panStepInPixels);}}
_onMouseWheel(event){const zoomFactor=1.1;const mouseWheelZoomSpeed=1/120;const scaleFactor=Math.pow(zoomFactor,event.wheelDeltaY*mouseWheelZoomSpeed);this._onScale(scaleFactor,event.clientX-this.element.totalOffsetLeft(),event.clientY-this.element.totalOffsetTop());}
_onDrag(event){if(this._mode===LayerViewer.TransformController.Modes.Rotate){this._onRotate(this._oldRotateX+(this._originY-event.clientY)/this.element.clientHeight*180,this._oldRotateY-(this._originX-event.clientX)/this.element.clientWidth*180);}else{this._onPan(event.clientX-this._originX,event.clientY-this._originY);this._originX=event.clientX;this._originY=event.clientY;}}
_onDragStart(event){this.element.focus();this._originX=event.clientX;this._originY=event.clientY;this._oldRotateX=this._rotateX;this._oldRotateY=this._rotateY;return true;}
_onDragEnd(){delete this._originX;delete this._originY;delete this._oldRotateX;delete this._oldRotateY;}};LayerViewer.TransformController.Events={TransformChanged:Symbol('TransformChanged')};LayerViewer.TransformController.Modes={Pan:'Pan',Rotate:'Rotate',};;Runtime.cachedResources["layer_viewer/layers3DView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.layers-3d-view {\n overflow: hidden;\n -webkit-user-select: none;\n}\n\n.toolbar {\n background-color: var(--toolbar-bg-color);\n border-bottom: var(--divider-border);\n}\n\ncanvas {\n flex: 1 1;\n}\n\n/*# sourceURL=layer_viewer/layers3DView.css */";Runtime.cachedResources["layer_viewer/paintProfiler.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.paint-profiler-overview {\n background-color: #eee;\n}\n\n.paint-profiler-canvas-container {\n flex: auto;\n position: relative;\n}\n\n.paint-profiler-pie-chart {\n width: 60px !important;\n height: 60px !important;\n padding: 2px;\n overflow: hidden;\n font-size: 10px;\n}\n\n.paint-profiler-canvas-container canvas {\n z-index: 200;\n background-color: white;\n opacity: 0.95;\n height: 100%;\n width: 100%;\n}\n\n.paint-profiler-canvas-container .overview-grid-window-resizer {\n z-index: 2000;\n}\n\n/*# sourceURL=layer_viewer/paintProfiler.css */";Runtime.cachedResources["layer_viewer/layerDetailsView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\ntable td {\n padding-left: 8px;\n}\n\ntable td:first-child {\n font-weight: bold;\n}\n\n.scroll-rect.active {\n background-color: rgba(100, 100, 100, 0.2);\n}\n\nul {\n list-style: none;\n padding-inline-start: 0;\n margin-block-start: 0;\n margin-block-end: 0;\n}\n\na {\n padding: 8px;\n display: block;\n}\n\n/*# sourceURL=layer_viewer/layerDetailsView.css */";Layers.LayerPaintProfilerView=class extends UI.SplitWidget{constructor(showImageCallback){super(true,false);this._logTreeView=new LayerViewer.PaintProfilerCommandLogView();this.setSidebarWidget(this._logTreeView);this._paintProfilerView=new LayerViewer.PaintProfilerView(showImageCallback);this.setMainWidget(this._paintProfilerView);this._paintProfilerView.addEventListener(LayerViewer.PaintProfilerView.Events.WindowChanged,this._onWindowChanged,this);}
reset(){this._paintProfilerView.setSnapshotAndLog(null,[],null);}
profile(snapshot){snapshot.commandLog().then(log=>setSnapshotAndLog.call(this,snapshot,log));function setSnapshotAndLog(snapshot,log){this._logTreeView.setCommandLog(log||[]);this._paintProfilerView.setSnapshotAndLog(snapshot,log||[],null);if(snapshot)
snapshot.release();}}
setScale(scale){this._paintProfilerView.setScale(scale);}
_onWindowChanged(){this._logTreeView.updateWindow(this._paintProfilerView.selectionWindow());}};;Layers.LayerTreeModel=class extends SDK.SDKModel{constructor(target){super(target);this._layerTreeAgent=target.layerTreeAgent();target.registerLayerTreeDispatcher(new Layers.LayerTreeDispatcher(this));this._paintProfilerModel=(target.model(SDK.PaintProfilerModel));const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this);}
this._layerTree=null;this._throttler=new Common.Throttler(20);}
disable(){if(!this._enabled)
return;this._enabled=false;this._layerTreeAgent.disable();}
enable(){if(this._enabled)
return;this._enabled=true;this._forceEnable();}
_forceEnable(){this._lastPaintRectByLayerId={};if(!this._layerTree)
this._layerTree=new Layers.AgentLayerTree(this);this._layerTreeAgent.enable();}
layerTree(){return this._layerTree;}
async _layerTreeChanged(layers){if(!this._enabled)
return;this._throttler.schedule(this._innerSetLayers.bind(this,layers));}
async _innerSetLayers(layers){const layerTree=(this._layerTree);await layerTree.setLayers(layers);for(const layerId in this._lastPaintRectByLayerId){const lastPaintRect=this._lastPaintRectByLayerId[layerId];const layer=layerTree.layerById(layerId);if(layer)
layer._lastPaintRect=lastPaintRect;}
this._lastPaintRectByLayerId={};this.dispatchEventToListeners(Layers.LayerTreeModel.Events.LayerTreeChanged);}
_layerPainted(layerId,clipRect){if(!this._enabled)
return;const layerTree=(this._layerTree);const layer=layerTree.layerById(layerId);if(!layer){this._lastPaintRectByLayerId[layerId]=clipRect;return;}
layer._didPaint(clipRect);this.dispatchEventToListeners(Layers.LayerTreeModel.Events.LayerPainted,layer);}
_onMainFrameNavigated(){this._layerTree=null;if(this._enabled)
this._forceEnable();}};SDK.SDKModel.register(Layers.LayerTreeModel,SDK.Target.Capability.DOM,false);Layers.LayerTreeModel.Events={LayerTreeChanged:Symbol('LayerTreeChanged'),LayerPainted:Symbol('LayerPainted'),};Layers.AgentLayerTree=class extends SDK.LayerTreeBase{constructor(layerTreeModel){super(layerTreeModel.target());this._layerTreeModel=layerTreeModel;}
async setLayers(payload){if(!payload){this._innerSetLayers(payload);return;}
const idsToResolve=new Set();for(let i=0;i<payload.length;++i){const backendNodeId=payload[i].backendNodeId;if(!backendNodeId||this.backendNodeIdToNode().has(backendNodeId))
continue;idsToResolve.add(backendNodeId);}
await this.resolveBackendNodeIds(idsToResolve);this._innerSetLayers(payload);}
_innerSetLayers(layers){this.setRoot(null);this.setContentRoot(null);if(!layers)
return;let root;const oldLayersById=this._layersById;this._layersById={};for(let i=0;i<layers.length;++i){const layerId=layers[i].layerId;let layer=oldLayersById[layerId];if(layer)
layer._reset(layers[i]);else
layer=new Layers.AgentLayer(this._layerTreeModel,layers[i]);this._layersById[layerId]=layer;const backendNodeId=layers[i].backendNodeId;if(backendNodeId)
layer._setNode(this.backendNodeIdToNode().get(backendNodeId));if(!this.contentRoot()&&layer.drawsContent())
this.setContentRoot(layer);const parentId=layer.parentId();if(parentId){const parent=this._layersById[parentId];if(!parent)
console.assert(parent,'missing parent '+parentId+' for layer '+layerId);parent.addChild(layer);}else{if(root)
console.assert(false,'Multiple root layers');root=layer;}}
if(root){this.setRoot(root);root._calculateQuad(new WebKitCSSMatrix());}}};Layers.AgentLayer=class{constructor(layerTreeModel,layerPayload){this._layerTreeModel=layerTreeModel;this._reset(layerPayload);}
id(){return this._layerPayload.layerId;}
parentId(){return this._layerPayload.parentLayerId;}
parent(){return this._parent;}
isRoot(){return!this.parentId();}
children(){return this._children;}
addChild(child){if(child._parent)
console.assert(false,'Child already has a parent');this._children.push(child);child._parent=this;}
_setNode(node){this._node=node;}
node(){return this._node;}
nodeForSelfOrAncestor(){for(let layer=this;layer;layer=layer._parent){if(layer._node)
return layer._node;}
return null;}
offsetX(){return this._layerPayload.offsetX;}
offsetY(){return this._layerPayload.offsetY;}
width(){return this._layerPayload.width;}
height(){return this._layerPayload.height;}
transform(){return this._layerPayload.transform;}
quad(){return this._quad;}
anchorPoint(){return[this._layerPayload.anchorX||0,this._layerPayload.anchorY||0,this._layerPayload.anchorZ||0,];}
invisible(){return this._layerPayload.invisible;}
paintCount(){return this._paintCount||this._layerPayload.paintCount;}
lastPaintRect(){return this._lastPaintRect;}
scrollRects(){return this._scrollRects;}
stickyPositionConstraint(){return this._stickyPositionConstraint;}
async requestCompositingReasons(){const reasons=await this._layerTreeModel._layerTreeAgent.compositingReasons(this.id());return reasons||[];}
drawsContent(){return this._layerPayload.drawsContent;}
gpuMemoryUsage(){const bytesPerPixel=4;return this.drawsContent()?this.width()*this.height()*bytesPerPixel:0;}
snapshots(){const promise=this._layerTreeModel._paintProfilerModel.makeSnapshot(this.id()).then(snapshot=>{if(!snapshot)
return null;return{rect:{x:0,y:0,width:this.width(),height:this.height()},snapshot:snapshot};});return[promise];}
_didPaint(rect){this._lastPaintRect=rect;this._paintCount=this.paintCount()+1;this._image=null;}
_reset(layerPayload){this._node=null;this._children=[];this._parent=null;this._paintCount=0;this._layerPayload=layerPayload;this._image=null;this._scrollRects=this._layerPayload.scrollRects||[];this._stickyPositionConstraint=this._layerPayload.stickyPositionConstraint?new SDK.Layer.StickyPositionConstraint(this._layerTreeModel.layerTree(),this._layerPayload.stickyPositionConstraint):null;}
_matrixFromArray(a){function toFixed9(x){return x.toFixed(9);}
return new WebKitCSSMatrix('matrix3d('+a.map(toFixed9).join(',')+')');}
_calculateTransformToViewport(parentTransform){const offsetMatrix=new WebKitCSSMatrix().translate(this._layerPayload.offsetX,this._layerPayload.offsetY);let matrix=offsetMatrix;if(this._layerPayload.transform){const transformMatrix=this._matrixFromArray(this._layerPayload.transform);const anchorVector=new UI.Geometry.Vector(this._layerPayload.width*this.anchorPoint()[0],this._layerPayload.height*this.anchorPoint()[1],this.anchorPoint()[2]);const anchorPoint=UI.Geometry.multiplyVectorByMatrixAndNormalize(anchorVector,matrix);const anchorMatrix=new WebKitCSSMatrix().translate(-anchorPoint.x,-anchorPoint.y,-anchorPoint.z);matrix=anchorMatrix.inverse().multiply(transformMatrix.multiply(anchorMatrix.multiply(matrix)));}
matrix=parentTransform.multiply(matrix);return matrix;}
_createVertexArrayForRect(width,height){return[0,0,0,width,0,0,width,height,0,0,height,0];}
_calculateQuad(parentTransform){const matrix=this._calculateTransformToViewport(parentTransform);this._quad=[];const vertices=this._createVertexArrayForRect(this._layerPayload.width,this._layerPayload.height);for(let i=0;i<4;++i){const point=UI.Geometry.multiplyVectorByMatrixAndNormalize(new UI.Geometry.Vector(vertices[i*3],vertices[i*3+1],vertices[i*3+2]),matrix);this._quad.push(point.x,point.y);}
function calculateQuadForLayer(layer){layer._calculateQuad(matrix);}
this._children.forEach(calculateQuadForLayer);}};Layers.LayerTreeDispatcher=class{constructor(layerTreeModel){this._layerTreeModel=layerTreeModel;}
layerTreeDidChange(layers){this._layerTreeModel._layerTreeChanged(layers||null);}
layerPainted(layerId,clipRect){this._layerTreeModel._layerPainted(layerId,clipRect);}};;Layers.LayersPanel=class extends UI.PanelWithSidebar{constructor(){super('layers',225);this._model=null;SDK.targetManager.observeTargets(this);this._layerViewHost=new LayerViewer.LayerViewHost();this._layerTreeOutline=new LayerViewer.LayerTreeOutline(this._layerViewHost);this.panelSidebarElement().appendChild(this._layerTreeOutline.element);this.setDefaultFocusedElement(this._layerTreeOutline.element);this._rightSplitWidget=new UI.SplitWidget(false,true,'layerDetailsSplitViewState');this.splitWidget().setMainWidget(this._rightSplitWidget);this._layers3DView=new LayerViewer.Layers3DView(this._layerViewHost);this._rightSplitWidget.setMainWidget(this._layers3DView);this._layers3DView.addEventListener(LayerViewer.Layers3DView.Events.PaintProfilerRequested,this._onPaintProfileRequested,this);this._layers3DView.addEventListener(LayerViewer.Layers3DView.Events.ScaleChanged,this._onScaleChanged,this);this._tabbedPane=new UI.TabbedPane();this._rightSplitWidget.setSidebarWidget(this._tabbedPane);this._layerDetailsView=new LayerViewer.LayerDetailsView(this._layerViewHost);this._layerDetailsView.addEventListener(LayerViewer.LayerDetailsView.Events.PaintProfilerRequested,this._onPaintProfileRequested,this);this._tabbedPane.appendTab(Layers.LayersPanel.DetailsViewTabs.Details,Common.UIString('Details'),this._layerDetailsView);this._paintProfilerView=new Layers.LayerPaintProfilerView(this._showImage.bind(this));this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabClosed,this._onTabClosed,this);this._updateThrottler=new Common.Throttler(100);}
focus(){this._layerTreeOutline.focus();}
wasShown(){super.wasShown();if(this._model)
this._model.enable();}
willHide(){if(this._model)
this._model.disable();super.willHide();}
targetAdded(target){if(this._model)
return;this._model=target.model(Layers.LayerTreeModel);if(!this._model)
return;this._model.addEventListener(Layers.LayerTreeModel.Events.LayerTreeChanged,this._onLayerTreeUpdated,this);this._model.addEventListener(Layers.LayerTreeModel.Events.LayerPainted,this._onLayerPainted,this);if(this.isShowing())
this._model.enable();}
targetRemoved(target){if(!this._model||this._model.target()!==target)
return;this._model.removeEventListener(Layers.LayerTreeModel.Events.LayerTreeChanged,this._onLayerTreeUpdated,this);this._model.removeEventListener(Layers.LayerTreeModel.Events.LayerPainted,this._onLayerPainted,this);this._model.disable();this._model=null;}
_onLayerTreeUpdated(){this._updateThrottler.schedule(this._update.bind(this));}
_update(){if(this._model)
this._layerViewHost.setLayerTree(this._model.layerTree());return Promise.resolve();}
_onLayerPainted(event){if(!this._model)
return;const layer=(event.data);if(this._layerViewHost.selection()&&this._layerViewHost.selection().layer()===layer)
this._layerDetailsView.update();this._layers3DView.updateLayerSnapshot(layer);}
_onPaintProfileRequested(event){const selection=(event.data);this._layers3DView.snapshotForSelection(selection).then(snapshotWithRect=>{if(!snapshotWithRect)
return;this._layerBeingProfiled=selection.layer();if(!this._tabbedPane.hasTab(Layers.LayersPanel.DetailsViewTabs.Profiler)){this._tabbedPane.appendTab(Layers.LayersPanel.DetailsViewTabs.Profiler,Common.UIString('Profiler'),this._paintProfilerView,undefined,true,true);}
this._tabbedPane.selectTab(Layers.LayersPanel.DetailsViewTabs.Profiler);this._paintProfilerView.profile(snapshotWithRect.snapshot);});}
_onTabClosed(event){if(event.data.tabId!==Layers.LayersPanel.DetailsViewTabs.Profiler||!this._layerBeingProfiled)
return;this._paintProfilerView.reset();this._layers3DView.showImageForLayer(this._layerBeingProfiled,undefined);this._layerBeingProfiled=null;}
_showImage(imageURL){this._layers3DView.showImageForLayer(this._layerBeingProfiled,imageURL);}
_onScaleChanged(event){this._paintProfilerView.setScale((event.data));}};Layers.LayersPanel.DetailsViewTabs={Details:'details',Profiler:'profiler'};;Network.BinaryResourceView=class extends UI.VBox{constructor(base64content,contentUrl,resourceType){super();this.registerRequiredCSS('network/binaryResourceView.css');this._empty=!base64content.length;if(this._empty){new UI.EmptyWidget('No data present in selected item').show(this.element);return;}
this._binaryResourceViewFactory=new SourceFrame.BinaryResourceViewFactory(base64content,contentUrl,resourceType);this._toolbar=new UI.Toolbar('binary-view-toolbar',this.element);this._binaryViewObjects=[new Network.BinaryResourceView.BinaryViewObject('base64',ls`Base64`,ls`Copied as Base64`,this._binaryResourceViewFactory.createBase64View.bind(this._binaryResourceViewFactory),this._binaryResourceViewFactory.base64.bind(this._binaryResourceViewFactory)),new Network.BinaryResourceView.BinaryViewObject('hex',ls`Hex Viewer`,ls`Copied as Hex`,this._binaryResourceViewFactory.createHexView.bind(this._binaryResourceViewFactory),this._binaryResourceViewFactory.hex.bind(this._binaryResourceViewFactory)),new Network.BinaryResourceView.BinaryViewObject('utf8',ls`UTF-8`,ls`Copied as UTF-8`,this._binaryResourceViewFactory.createUtf8View.bind(this._binaryResourceViewFactory),this._binaryResourceViewFactory.utf8.bind(this._binaryResourceViewFactory)),];this._binaryViewTypeSetting=Common.settings.createSetting('binaryViewType','hex');this._binaryViewTypeCombobox=new UI.ToolbarComboBox(this._binaryViewTypeChanged.bind(this));for(const viewObject of this._binaryViewObjects){this._binaryViewTypeCombobox.addOption(this._binaryViewTypeCombobox.createOption(viewObject.label,viewObject.label,viewObject.type));}
this._toolbar.appendToolbarItem(this._binaryViewTypeCombobox);const copyButton=new UI.ToolbarButton(ls`Copy to clipboard`,'largeicon-copy');copyButton.addEventListener(UI.ToolbarButton.Events.Click,this._copySelectedViewToClipboard.bind(this),this);this._toolbar.appendToolbarItem(copyButton);this._copiedText=new UI.ToolbarText();this._copiedText.element.classList.add('binary-view-copied-text');this._toolbar.element.appendChild(this._copiedText.element);this._addFadeoutSettimeoutId=null;this._lastView=null;this._updateView();}
_getCurrentViewObject(){const filter=obj=>obj.type===this._binaryViewTypeSetting.get();const binaryViewObject=this._binaryViewObjects.find(filter);console.assert(binaryViewObject,`No binary view found for binary view type found in setting 'binaryViewType': ${
this._binaryViewTypeSetting.get()}`);return binaryViewObject||null;}
async _copySelectedViewToClipboard(){const viewObject=this._getCurrentViewObject();InspectorFrontendHost.copyText(await viewObject.content());this._copiedText.setText(viewObject.copiedMessage);this._copiedText.element.classList.remove('fadeout');function addFadeoutClass(){this._copiedText.element.classList.add('fadeout');}
if(this._addFadeoutSettimeoutId){clearTimeout(this._addFadeoutSettimeoutId);this._addFadeoutSettimeoutId=null;}
this._addFadeoutSettimeoutId=setTimeout(addFadeoutClass.bind(this),2000);}
wasShown(){if(!this._empty)
this._updateView();}
_updateView(){const newViewObject=this._getCurrentViewObject();if(!newViewObject)
return;const newView=newViewObject.getView();if(newView===this._lastView)
return;if(this._lastView)
this._lastView.detach();this._lastView=newView;newView.show(this.element,this._toolbar.element);this._binaryViewTypeCombobox.selectElement().value=this._binaryViewTypeSetting.get();}
_binaryViewTypeChanged(){const newViewType=this._binaryViewTypeCombobox.selectedOption().value;if(this._binaryViewTypeSetting.get()===newViewType)
return;this._binaryViewTypeSetting.set(newViewType);this._updateView();}
addCopyToContextMenu(contextMenu,submenuItemText){if(this._empty)
return;const copyMenu=contextMenu.clipboardSection().appendSubMenuItem(submenuItemText);const footerSection=copyMenu.footerSection();footerSection.appendItem(ls`Copy as Base64`,async()=>InspectorFrontendHost.copyText(await this._binaryResourceViewFactory.base64()));footerSection.appendItem(ls`Copy as Hex`,async()=>InspectorFrontendHost.copyText(await this._binaryResourceViewFactory.hex()));footerSection.appendItem(ls`Copy as UTF-8`,async()=>InspectorFrontendHost.copyText(await this._binaryResourceViewFactory.utf8()));}};Network.BinaryResourceView.BinaryViewObject=class{constructor(type,label,copiedMessage,createViewFn,content){this.type=type;this.label=label;this.copiedMessage=copiedMessage;this.content=content;this._createViewFn=createViewFn;this._view=null;}
getView(){if(!this._view)
this._view=this._createViewFn();return this._view;}};;Network.BlockedURLsPane=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('network/blockedURLsPane.css');Network.BlockedURLsPane._instance=this;this._manager=SDK.multitargetNetworkManager;this._manager.addEventListener(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged,this._update,this);this._toolbar=new UI.Toolbar('',this.contentElement);this._enabledCheckbox=new UI.ToolbarCheckbox(Common.UIString('Enable request blocking'),undefined,this._toggleEnabled.bind(this));this._toolbar.appendToolbarItem(this._enabledCheckbox);this._toolbar.appendSeparator();const addButton=new UI.ToolbarButton(Common.UIString('Add pattern'),'largeicon-add');addButton.addEventListener(UI.ToolbarButton.Events.Click,this._addButtonClicked,this);this._toolbar.appendToolbarItem(addButton);const clearButton=new UI.ToolbarButton(Common.UIString('Remove all patterns'),'largeicon-clear');clearButton.addEventListener(UI.ToolbarButton.Events.Click,this._removeAll,this);this._toolbar.appendToolbarItem(clearButton);this._list=new UI.ListWidget(this);this._list.element.classList.add('blocked-urls');this._list.registerRequiredCSS('network/blockedURLsPane.css');this._list.setEmptyPlaceholder(this._createEmptyPlaceholder());this._list.show(this.contentElement);this._editor=null;this._blockedCountForUrl=new Map();SDK.targetManager.addModelListener(SDK.NetworkManager,SDK.NetworkManager.Events.RequestFinished,this._onRequestFinished,this);this._updateThrottler=new Common.Throttler(200);this._update();}
_createEmptyPlaceholder(){const element=this.contentElement.createChild('div','no-blocked-urls');element.createChild('span').textContent=Common.UIString('Requests are not blocked. ');const addLink=element.createChild('span','link');addLink.textContent=Common.UIString('Add pattern.');addLink.href='';addLink.addEventListener('click',this._addButtonClicked.bind(this),false);return element;}
static reset(){if(Network.BlockedURLsPane._instance)
Network.BlockedURLsPane._instance.reset();}
_addButtonClicked(){this._manager.setBlockingEnabled(true);this._list.addNewItem(0,{url:'',enabled:true});}
renderItem(pattern,editable){const count=this._blockedRequestsCount(pattern.url);const element=createElementWithClass('div','blocked-url');const checkbox=element.createChild('input','blocked-url-checkbox');checkbox.type='checkbox';checkbox.checked=pattern.enabled;checkbox.disabled=!this._manager.blockingEnabled();element.createChild('div','blocked-url-label').textContent=pattern.url;element.createChild('div','blocked-url-count').textContent=Common.UIString('%d blocked',count);element.addEventListener('click',event=>this._togglePattern(pattern,event),false);checkbox.addEventListener('click',event=>this._togglePattern(pattern,event),false);return element;}
_togglePattern(pattern,event){event.consume(true);const patterns=this._manager.blockedPatterns();patterns.splice(patterns.indexOf(pattern),1,{enabled:!pattern.enabled,url:pattern.url});this._manager.setBlockedPatterns(patterns);}
_toggleEnabled(){this._manager.setBlockingEnabled(!this._manager.blockingEnabled());this._update();}
removeItemRequested(pattern,index){const patterns=this._manager.blockedPatterns();patterns.splice(index,1);this._manager.setBlockedPatterns(patterns);}
beginEdit(pattern){this._editor=this._createEditor();this._editor.control('url').value=pattern.url;return this._editor;}
commitEdit(item,editor,isNew){const url=editor.control('url').value;const patterns=this._manager.blockedPatterns();if(isNew)
patterns.push({enabled:true,url:url});else
patterns.splice(patterns.indexOf(item),1,{enabled:true,url:url});this._manager.setBlockedPatterns(patterns);}
_createEditor(){if(this._editor)
return this._editor;const editor=new UI.ListWidget.Editor();const content=editor.contentElement();const titles=content.createChild('div','blocked-url-edit-row');titles.createChild('div').textContent=Common.UIString('Text pattern to block matching requests; use * for wildcard');const fields=content.createChild('div','blocked-url-edit-row');const urlInput=editor.createInput('url','text','',(item,index,input)=>!!input.value&&!this._manager.blockedPatterns().find(pattern=>pattern.url===input.value));fields.createChild('div','blocked-url-edit-value').appendChild(urlInput);return editor;}
_removeAll(){this._manager.setBlockedPatterns([]);}
_update(){const enabled=this._manager.blockingEnabled();this._list.element.classList.toggle('blocking-disabled',!enabled&&!!this._manager.blockedPatterns().length);this._enabledCheckbox.setChecked(enabled);this._list.clear();for(const pattern of this._manager.blockedPatterns())
this._list.appendItem(pattern,true);return Promise.resolve();}
_blockedRequestsCount(url){if(!url)
return 0;let result=0;for(const blockedUrl of this._blockedCountForUrl.keys()){if(this._matches(url,blockedUrl))
result+=this._blockedCountForUrl.get(blockedUrl);}
return result;}
_matches(pattern,url){let pos=0;const parts=pattern.split('*');for(let index=0;index<parts.length;index++){const part=parts[index];if(!part.length)
continue;pos=url.indexOf(part,pos);if(pos===-1)
return false;pos+=part.length;}
return true;}
reset(){this._blockedCountForUrl.clear();this._updateThrottler.schedule(this._update.bind(this));}
_onRequestFinished(event){const request=(event.data);if(request.wasBlocked()){const count=this._blockedCountForUrl.get(request.url())||0;this._blockedCountForUrl.set(request.url(),count+1);this._updateThrottler.schedule(this._update.bind(this));}}};Network.BlockedURLsPane._instance=null;;Network.EventSourceMessagesView=class extends UI.VBox{constructor(request){super();this.registerRequiredCSS('network/eventSourceMessagesView.css');this.element.classList.add('event-source-messages-view');this._request=request;const columns=([{id:'id',title:Common.UIString('Id'),sortable:true,weight:8},{id:'type',title:Common.UIString('Type'),sortable:true,weight:8},{id:'data',title:Common.UIString('Data'),sortable:false,weight:88},{id:'time',title:Common.UIString('Time'),sortable:true,weight:8}]);this._dataGrid=new DataGrid.SortableDataGrid(columns);this._dataGrid.setStriped(true);this._dataGrid.setStickToBottom(true);this._dataGrid.markColumnAsSortedBy('time',DataGrid.DataGrid.Order.Ascending);this._sortItems();this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortItems,this);this._dataGrid.setName('EventSourceMessagesView');this._dataGrid.asWidget().show(this.element);}
wasShown(){this._dataGrid.rootNode().removeChildren();const messages=this._request.eventSourceMessages();for(let i=0;i<messages.length;++i)
this._dataGrid.insertChild(new Network.EventSourceMessageNode(messages[i]));this._request.addEventListener(SDK.NetworkRequest.Events.EventSourceMessageAdded,this._messageAdded,this);}
willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.EventSourceMessageAdded,this._messageAdded,this);}
_messageAdded(event){const message=(event.data);this._dataGrid.insertChild(new Network.EventSourceMessageNode(message));}
_sortItems(){const sortColumnId=this._dataGrid.sortColumnId();if(!sortColumnId)
return;const comparator=Network.EventSourceMessageNode.Comparators[sortColumnId];if(!comparator)
return;this._dataGrid.sortNodes(comparator,!this._dataGrid.isSortOrderAscending());}};Network.EventSourceMessageNode=class extends DataGrid.SortableDataGridNode{constructor(message){const time=new Date(message.time*1000);const timeText=('0'+time.getHours()).substr(-2)+':'+('0'+time.getMinutes()).substr(-2)+':'+
('0'+time.getSeconds()).substr(-2)+'.'+('00'+time.getMilliseconds()).substr(-3);const timeNode=createElement('div');timeNode.createTextChild(timeText);timeNode.title=time.toLocaleString();super({id:message.eventId,type:message.eventName,data:message.data,time:timeNode});this._message=message;}};Network.EventSourceMessageNodeComparator=function(field,a,b){const aValue=a._message[field];const bValue=b._message[field];return aValue<bValue?-1:aValue>bValue?1:0;};Network.EventSourceMessageNode.Comparators={'id':Network.EventSourceMessageNodeComparator.bind(null,'eventId'),'type':Network.EventSourceMessageNodeComparator.bind(null,'eventName'),'time':Network.EventSourceMessageNodeComparator.bind(null,'time')};;Network.HARWriter=class{static async write(stream,requests,progress){const compositeProgress=new Common.CompositeProgress(progress);const content=await Network.HARWriter._harStringForRequests(requests,compositeProgress);if(progress.isCanceled())
return Promise.resolve();return Network.HARWriter._writeToStream(stream,compositeProgress,content);}
static async _harStringForRequests(requests,compositeProgress){const progress=compositeProgress.createSubProgress();progress.setTitle(Common.UIString('Collecting content\u2026'));progress.setTotalWork(requests.length);const harLog=await SDK.HARLog.build(requests);const promises=[];for(let i=0;i<requests.length;i++){const promise=requests[i].contentData();promises.push(promise.then(contentLoaded.bind(null,harLog.entries[i])));}
await Promise.all(promises);progress.done();if(progress.isCanceled())
return'';return JSON.stringify({log:harLog},null,Network.HARWriter._jsonIndent);function isValidCharacter(code_point){return code_point<0xD800||(code_point>=0xE000&&code_point<0xFDD0)||(code_point>0xFDEF&&code_point<=0x10FFFF&&(code_point&0xFFFE)!==0xFFFE);}
function needsEncoding(content){for(let i=0;i<content.length;i++){if(!isValidCharacter(content.charCodeAt(i)))
return true;}
return false;}
function contentLoaded(entry,contentData){progress.worked();let encoded=contentData.encoded;if(contentData.content!==null){let content=contentData.content;if(content&&!encoded&&needsEncoding(content)){content=content.toBase64();encoded=true;}
entry.response.content.text=content;}
if(encoded)
entry.response.content.encoding='base64';}}
static async _writeToStream(stream,compositeProgress,fileContent){const progress=compositeProgress.createSubProgress();progress.setTitle(Common.UIString('Writing file\u2026'));progress.setTotalWork(fileContent.length);for(let i=0;i<fileContent.length&&!progress.isCanceled();i+=Network.HARWriter._chunkSize){const chunk=fileContent.substr(i,Network.HARWriter._chunkSize);await stream.write(chunk);progress.worked(chunk.length);}
progress.done();}};Network.HARWriter._jsonIndent=2;Network.HARWriter._chunkSize=100000;;Network.NetworkConfigView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('network/networkConfigView.css');this.contentElement.classList.add('network-config');this._createCacheSection();this.contentElement.createChild('div').classList.add('panel-section-separator');this._createNetworkThrottlingSection();this.contentElement.createChild('div').classList.add('panel-section-separator');this._createUserAgentSection();}
static createUserAgentSelectAndInput(){const userAgentSetting=Common.settings.createSetting('customUserAgent','');const userAgentSelectElement=createElement('select');const customOverride={title:Common.UIString('Custom...'),value:'custom'};userAgentSelectElement.appendChild(new Option(customOverride.title,customOverride.value));const groups=Network.NetworkConfigView._userAgentGroups;for(const userAgentDescriptor of groups){const groupElement=userAgentSelectElement.createChild('optgroup');groupElement.label=userAgentDescriptor.title;for(const userAgentVersion of userAgentDescriptor.values){const userAgentValue=SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(userAgentVersion.value);groupElement.appendChild(new Option(userAgentVersion.title,userAgentValue));}}
userAgentSelectElement.selectedIndex=0;const otherUserAgentElement=UI.createInput('','text');otherUserAgentElement.value=userAgentSetting.get();otherUserAgentElement.title=userAgentSetting.get();otherUserAgentElement.placeholder=Common.UIString('Enter a custom user agent');otherUserAgentElement.required=true;settingChanged();userAgentSelectElement.addEventListener('change',userAgentSelected,false);otherUserAgentElement.addEventListener('input',applyOtherUserAgent,false);function userAgentSelected(){const value=userAgentSelectElement.options[userAgentSelectElement.selectedIndex].value;if(value!==customOverride.value){userAgentSetting.set(value);otherUserAgentElement.value=value;otherUserAgentElement.title=value;}else{otherUserAgentElement.select();}}
function settingChanged(){const value=userAgentSetting.get();const options=userAgentSelectElement.options;let selectionRestored=false;for(let i=0;i<options.length;++i){if(options[i].value===value){userAgentSelectElement.selectedIndex=i;selectionRestored=true;break;}}
if(!selectionRestored)
userAgentSelectElement.selectedIndex=0;}
function applyOtherUserAgent(){if(userAgentSetting.get()!==otherUserAgentElement.value){userAgentSetting.set(otherUserAgentElement.value);otherUserAgentElement.title=otherUserAgentElement.value;settingChanged();}}
return{select:userAgentSelectElement,input:otherUserAgentElement};}
_createSection(title,className){const section=this.contentElement.createChild('section','network-config-group');if(className)
section.classList.add(className);section.createChild('div','network-config-title').textContent=title;return section.createChild('div','network-config-fields');}
_createCacheSection(){const section=this._createSection(Common.UIString('Caching'),'network-config-disable-cache');section.appendChild(UI.SettingsUI.createSettingCheckbox(Common.UIString('Disable cache'),Common.moduleSetting('cacheDisabled'),true));}
_createNetworkThrottlingSection(){const section=this._createSection(Common.UIString('Network throttling'),'network-config-throttling');const networkThrottlingSelect=(section.createChild('select','chrome-select'));MobileThrottling.throttlingManager().decorateSelectWithNetworkThrottling(networkThrottlingSelect);}
_createUserAgentSection(){const section=this._createSection(Common.UIString('User agent'),'network-config-ua');const checkboxLabel=UI.CheckboxLabel.create(Common.UIString('Select automatically'),true);section.appendChild(checkboxLabel);const autoCheckbox=checkboxLabel.checkboxElement;const customUserAgentSetting=Common.settings.createSetting('customUserAgent','');customUserAgentSetting.addChangeListener(()=>{if(autoCheckbox.checked)
return;SDK.multitargetNetworkManager.setCustomUserAgentOverride(customUserAgentSetting.get());});const customUserAgentSelectBox=section.createChild('div','network-config-ua-custom');autoCheckbox.addEventListener('change',userAgentSelectBoxChanged);const customSelectAndInput=Network.NetworkConfigView.createUserAgentSelectAndInput();customSelectAndInput.select.classList.add('chrome-select');customUserAgentSelectBox.appendChild(customSelectAndInput.select);customUserAgentSelectBox.appendChild(customSelectAndInput.input);userAgentSelectBoxChanged();function userAgentSelectBoxChanged(){const useCustomUA=!autoCheckbox.checked;customUserAgentSelectBox.classList.toggle('checked',useCustomUA);customSelectAndInput.select.disabled=!useCustomUA;customSelectAndInput.input.disabled=!useCustomUA;const customUA=useCustomUA?customUserAgentSetting.get():'';SDK.multitargetNetworkManager.setCustomUserAgentOverride(customUA);}}};Network.NetworkConfigView._userAgentGroups=[{title:'Android',values:[{title:'Android (4.0.2) Browser \u2014 Galaxy Nexus',value:'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'},{title:'Android (2.3) Browser \u2014 Nexus S',value:'Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'}]},{title:'BlackBerry',values:[{title:'BlackBerry \u2014 BB10',value:'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.1+ (KHTML, like Gecko) Version/10.0.0.1337 Mobile Safari/537.1+'},{title:'BlackBerry \u2014 PlayBook 2.1',value:'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML, like Gecko) Version/7.2.1.0 Safari/536.2+'},{title:'BlackBerry \u2014 9900',value:'Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en-US) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.0.0.187 Mobile Safari/534.11+'}]},{title:'Chrome',values:[{title:'Chrome \u2014 Android Mobile',value:'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36'},{title:'Chrome \u2014 Android Tablet',value:'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'},{title:'Chrome \u2014 iPhone',value:'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/%s Mobile/13B143 Safari/601.1.46'},{title:'Chrome \u2014 iPad',value:'Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/%s Mobile/13B143 Safari/601.1.46'},{title:'Chrome \u2014 Chrome OS',value:'Mozilla/5.0 (X11; CrOS x86_64 10066.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'},{title:'Chrome \u2014 Mac',value:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'},{title:'Chrome \u2014 Windows',value:'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'}]},{title:'Edge',values:[{title:'Edge \u2014 Windows',value:'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240'},{title:'Edge \u2014 Mobile',value:'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166'},{title:'Edge \u2014 XBox',value:'Mozilla/5.0 (Windows NT 10.0; Win64; x64; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13.10586'}]},{title:'Firefox',values:[{title:'Firefox \u2014 Android Mobile',value:'Mozilla/5.0 (Android 4.4; Mobile; rv:46.0) Gecko/46.0 Firefox/46.0'},{title:'Firefox \u2014 Android Tablet',value:'Mozilla/5.0 (Android 4.4; Tablet; rv:46.0) Gecko/46.0 Firefox/46.0'},{title:'Firefox \u2014 iPhone',value:'Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4'},{title:'Firefox \u2014 iPad',value:'Mozilla/5.0
static _themedBackgroundColors(){if(Network.NetworkNode._themedBackgroundColorsCache)
return Network.NetworkNode._themedBackgroundColorsCache;const themedColors={};for(const name in Network.NetworkNode._backgroundColors){const color=Common.Color.fromRGBA(Network.NetworkNode._backgroundColors[name]);themedColors[name]=UI.themeSupport.patchColor(color,UI.ThemeSupport.ColorUsage.Background);}
Network.NetworkNode._themedBackgroundColorsCache=(themedColors);return Network.NetworkNode._themedBackgroundColorsCache;}
displayName(){return'';}
createCell(columnId){const cell=this.createTD(columnId);this.renderCell(cell,columnId);return cell;}
renderCell(cell,columnId){}
backgroundColor(){const bgColors=Network.NetworkNode._themedBackgroundColors();if(this.selected)
return(bgColors.Selected.asString(Common.Color.Format.HEX));let color=this.isStriped()?bgColors.Stripe:bgColors.Default;if(this.isNavigationRequest())
color=color.blendWith(bgColors.Navigation);if(this.hovered())
color=color.blendWith(bgColors.Hovered);if(this.isOnInitiatorPath())
color=color.blendWith(bgColors.InitiatorPath);if(this.isOnInitiatedPath())
color=color.blendWith(bgColors.InitiatedPath);return(color.asString(Common.Color.Format.HEX));}
_updateBackgroundColor(){const element=this.existingElement();if(!element)
return;element.style.backgroundColor=this.backgroundColor();this._parentView.stylesChanged();}
setStriped(isStriped){super.setStriped(isStriped);this._updateBackgroundColor();}
parentView(){return this._parentView;}
hovered(){return this._isHovered;}
showingInitiatorChain(){return this._showingInitiatorChain;}
nodeSelfHeight(){return this._parentView.rowHeight();}
setHovered(hovered,showInitiatorChain){if(this._isHovered===hovered&&this._showingInitiatorChain===showInitiatorChain)
return;if(this._isHovered!==hovered){this._isHovered=hovered;if(this.attached())
this.element().classList.toggle('hover',hovered);}
if(this._showingInitiatorChain!==showInitiatorChain){this._showingInitiatorChain=showInitiatorChain;this.showingInitiatorChainChanged();}
this._parentView.stylesChanged();this._updateBackgroundColor();}
showingInitiatorChainChanged(){}
isOnInitiatorPath(){return false;}
isOnInitiatedPath(){return false;}
request(){return null;}
isNavigationRequest(){return false;}
clearFlatNodes(){super.clearFlatNodes();this._requestOrFirstKnownChildRequest=null;}
requestOrFirstKnownChildRequest(){if(this._requestOrFirstKnownChildRequest)
return this._requestOrFirstKnownChildRequest;let request=this.request();if(request||!this.hasChildren()){this._requestOrFirstKnownChildRequest=request;return this._requestOrFirstKnownChildRequest;}
let firstChildRequest=null;const flatChildren=this.flatChildren();for(let i=0;i<flatChildren.length;i++){request=flatChildren[i].request();if(!firstChildRequest||(request&&request.issueTime()<firstChildRequest.issueTime()))
firstChildRequest=request;}
this._requestOrFirstKnownChildRequest=firstChildRequest;return this._requestOrFirstKnownChildRequest;}};Network.NetworkNode._backgroundColors={Default:[255,255,255,1.0],Stripe:[245,245,245,1.0],Navigation:[221,238,255,1.0],Hovered:[235,242,252,0.7],InitiatorPath:[58,217,58,0.4],InitiatedPath:[217,58,58,0.4],Selected:[63,81,181,.6],FromFrame:[224,247,250,.4],IsProduct:[255,252,225,.6],};Network.NetworkNode._SupportedBackgroundColors;Network.NetworkNode._themedBackgroundColorsCache;Network.NetworkNode._ProductEntryInfo;Network.NetworkRequestNode=class extends Network.NetworkNode{constructor(parentView,request){super(parentView);this._nameCell=null;this._nameBadgeElement=null;this._initiatorCell=null;this._request=request;this._isNavigationRequest=false;this.selectable=true;this._isOnInitiatorPath=false;this._isOnInitiatedPath=false;}
static NameComparator(a,b){const aName=a.displayName().toLowerCase();const bName=b.displayName().toLowerCase();if(aName===bName){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(aRequest&&bRequest)
return aRequest.indentityCompare(bRequest);return aRequest?-1:1;}
return aName<bName?-1:1;}
static RemoteAddressComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aRemoteAddress=aRequest.remoteAddress();const bRemoteAddress=bRequest.remoteAddress();if(aRemoteAddress>bRemoteAddress)
return 1;if(bRemoteAddress>aRemoteAddress)
return-1;return aRequest.indentityCompare(bRequest);}
static ProductComparator(productRegistry,a,b){const aRequest=a.request();const bRequest=b.request();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aName=productRegistry.nameForUrl(aRequest.parsedURL)||'';const bName=productRegistry.nameForUrl(bRequest.parsedURL)||'';return aName.localeCompare(bName)||aRequest.indentityCompare(bRequest);}
static SizeComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;if(bRequest.cached()&&!aRequest.cached())
return 1;if(aRequest.cached()&&!bRequest.cached())
return-1;return(aRequest.transferSize-bRequest.transferSize)||(aRequest.resourceSize-bRequest.resourceSize)||aRequest.indentityCompare(bRequest);}
static TypeComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aSimpleType=a.displayType();const bSimpleType=b.displayType();if(aSimpleType>bSimpleType)
return 1;if(bSimpleType>aSimpleType)
return-1;return aRequest.indentityCompare(bRequest);}
static InitiatorComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;if(!a._initiatorCell||!b._initiatorCell)
return!a._initiatorCell?-1:1;const aText=a._linkifiedInitiatorAnchor?a._linkifiedInitiatorAnchor.textContent:a._initiatorCell.title;const bText=b._linkifiedInitiatorAnchor?b._linkifiedInitiatorAnchor.textContent:b._initiatorCell.title;return aText.localeCompare(bText);}
static RequestCookiesCountComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aScore=aRequest.requestCookies?aRequest.requestCookies.length:0;const bScore=bRequest.requestCookies?bRequest.requestCookies.length:0;return(aScore-bScore)||aRequest.indentityCompare(bRequest);}
static ResponseCookiesCountComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aScore=aRequest.responseCookies?aRequest.responseCookies.length:0;const bScore=bRequest.responseCookies?bRequest.responseCookies.length:0;return(aScore-bScore)||aRequest.indentityCompare(bRequest);}
static PriorityComparator(a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aPriority=aRequest.priority();let aScore=aPriority?PerfUI.networkPriorityWeight(aPriority):0;aScore=aScore||0;const bPriority=bRequest.priority();let bScore=bPriority?PerfUI.networkPriorityWeight(bPriority):0;bScore=bScore||0;return aScore-bScore||aRequest.indentityCompare(bRequest);}
static RequestPropertyComparator(propertyName,a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aValue=aRequest[propertyName];const bValue=bRequest[propertyName];if(aValue===bValue)
return aRequest.indentityCompare(bRequest);return aValue>bValue?1:-1;}
static ResponseHeaderStringComparator(propertyName,a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aValue=String(aRequest.responseHeaderValue(propertyName)||'');const bValue=String(bRequest.responseHeaderValue(propertyName)||'');return aValue.localeCompare(bValue)||aRequest.indentityCompare(bRequest);}
static ResponseHeaderNumberComparator(propertyName,a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aValue=(aRequest.responseHeaderValue(propertyName)!==undefined)?parseFloat(aRequest.responseHeaderValue(propertyName)):-Infinity;const bValue=(bRequest.responseHeaderValue(propertyName)!==undefined)?parseFloat(bRequest.responseHeaderValue(propertyName)):-Infinity;if(aValue===bValue)
return aRequest.indentityCompare(bRequest);return aValue>bValue?1:-1;}
static ResponseHeaderDateComparator(propertyName,a,b){const aRequest=a.requestOrFirstKnownChildRequest();const bRequest=b.requestOrFirstKnownChildRequest();if(!aRequest||!bRequest)
return!aRequest?-1:1;const aHeader=aRequest.responseHeaderValue(propertyName);const bHeader=bRequest.responseHeaderValue(propertyName);const aValue=aHeader?new Date(aHeader).getTime():-Infinity;const bValue=bHeader?new Date(bHeader).getTime():-Infinity;if(aValue===bValue)
return aRequest.indentityCompare(bRequest);return aValue>bValue?1:-1;}
showingInitiatorChainChanged(){const showInitiatorChain=this.showingInitiatorChain();const initiatorGraph=SDK.networkLog.initiatorGraphForRequest(this._request);for(const request of initiatorGraph.initiators){if(request===this._request)
continue;const node=this.parentView().nodeForRequest(request);if(!node)
continue;node._setIsOnInitiatorPath(showInitiatorChain);}
for(const request of initiatorGraph.initiated){if(request===this._request)
continue;const node=this.parentView().nodeForRequest(request);if(!node)
continue;node._setIsOnInitiatedPath(showInitiatorChain);}}
_setIsOnInitiatorPath(isOnInitiatorPath){if(this._isOnInitiatorPath===isOnInitiatorPath||!this.attached())
return;this._isOnInitiatorPath=isOnInitiatorPath;this._updateBackgroundColor();}
isOnInitiatorPath(){return this._isOnInitiatorPath;}
_setIsOnInitiatedPath(isOnInitiatedPath){if(this._isOnInitiatedPath===isOnInitiatedPath||!this.attached())
return;this._isOnInitiatedPath=isOnInitiatedPath;this._updateBackgroundColor();}
isOnInitiatedPath(){return this._isOnInitiatedPath;}
displayType(){const mimeType=this._request.mimeType||this._request.requestContentType()||'';const resourceType=this._request.resourceType();let simpleType=resourceType.name();if(resourceType===Common.resourceTypes.Other||resourceType===Common.resourceTypes.Image)
simpleType=mimeType.replace(/^(application|image)\//,'');return simpleType;}
displayName(){return this._request.name();}
request(){return this._request;}
isNavigationRequest(){const pageLoad=SDK.NetworkLog.PageLoad.forRequest(this._request);return pageLoad?pageLoad.mainRequest===this._request:false;}
nodeSelfHeight(){return this.parentView().rowHeight();}
createCells(element){this._nameCell=null;this._initiatorCell=null;element.classList.toggle('network-error-row',this._isFailed());element.classList.toggle('network-navigation-row',this._isNavigationRequest);super.createCells(element);this._updateBackgroundColor();ProductRegistry.instance().then(productRegistry=>{if(productRegistry.entryForUrl(this._request.parsedURL)){this._isProduct=true;this._updateBackgroundColor();}});}
_setTextAndTitle(element,text){element.createTextChild(text);element.title=text;}
renderCell(cell,columnId){switch(columnId){case'name':this._renderNameCell(cell);break;case'method':this._setTextAndTitle(cell,this._request.requestMethod);break;case'status':this._renderStatusCell(cell);break;case'protocol':this._setTextAndTitle(cell,this._request.protocol);break;case'scheme':this._setTextAndTitle(cell,this._request.scheme);break;case'domain':this._setTextAndTitle(cell,this._request.domain);break;case'remoteaddress':this._setTextAndTitle(cell,this._request.remoteAddress());break;case'cookies':this._setTextAndTitle(cell,this._arrayLength(this._request.requestCookies));break;case'setcookies':this._setTextAndTitle(cell,this._arrayLength(this._request.responseCookies));break;case'priority':const priority=this._request.priority();this._setTextAndTitle(cell,priority?PerfUI.uiLabelForNetworkPriority(priority):'');break;case'connectionid':this._setTextAndTitle(cell,this._request.connectionId);break;case'type':this._setTextAndTitle(cell,this.displayType());break;case'initiator':this._renderInitiatorCell(cell);break;case'size':this._renderSizeCell(cell);break;case'time':this._renderTimeCell(cell);break;case'timeline':this._setTextAndTitle(cell,'');break;default:this._setTextAndTitle(cell,this._request.responseHeaderValue(columnId)||'');break;}}
_arrayLength(array){return array?''+array.length:'';}
select(supressSelectedEvent){super.select(supressSelectedEvent);this.parentView().dispatchEventToListeners(Network.NetworkLogView.Events.RequestSelected,this._request);}
highlightMatchedSubstring(regexp){if(!regexp)
return[];this.element();const domChanges=[];const matchInfo=this._nameCell.textContent.match(regexp);if(matchInfo)
UI.highlightSearchResult(this._nameCell,matchInfo.index,matchInfo[0].length,domChanges);return domChanges;}
_openInNewTab(){InspectorFrontendHost.openInNewTab(this._request.url());}
_isFailed(){return(this._request.failed&&!this._request.statusCode)||(this._request.statusCode>=400)||(!!this._request.signedExchangeInfo()&&!!this._request.signedExchangeInfo().errors);}
_renderNameCell(cell){const leftPadding=this.leftPadding?this.leftPadding+'px':'';cell.style.setProperty('padding-left',leftPadding);this._nameCell=cell;cell.addEventListener('dblclick',this._openInNewTab.bind(this),false);let iconElement;if(this._request.resourceType()===Common.resourceTypes.Image){const previewImage=createElementWithClass('img','image-network-icon-preview');this._request.populateImageSource(previewImage);iconElement=createElementWithClass('div','icon');iconElement.appendChild(previewImage);}else{iconElement=createElementWithClass('img','icon');}
iconElement.classList.add(this._request.resourceType().name());cell.appendChild(iconElement);if(!this._nameBadgeElement){this._nameBadgeElement=this.parentView().badgePool.badgeForURL(this._request.parsedURL);this._nameBadgeElement.classList.add('network-badge');}
cell.appendChild(this._nameBadgeElement);const name=this._request.name().trimMiddle(100);const networkManager=SDK.NetworkManager.forRequest(this._request);cell.createTextChild(networkManager?networkManager.target().decorateLabel(name):name);this._appendSubtitle(cell,this._request.path());cell.title=this._request.url();}
_renderStatusCell(cell){cell.classList.toggle('network-dim-cell',!this._isFailed()&&(this._request.cached()||!this._request.statusCode));if(this._request.failed&&!this._request.canceled&&!this._request.wasBlocked()){const failText=Common.UIString('(failed)');if(this._request.localizedFailDescription){cell.createTextChild(failText);this._appendSubtitle(cell,this._request.localizedFailDescription);cell.title=failText+' '+this._request.localizedFailDescription;}else{this._setTextAndTitle(cell,failText);}}else if(this._request.statusCode){cell.createTextChild(''+this._request.statusCode);this._appendSubtitle(cell,this._request.statusText);cell.title=this._request.statusCode+' '+this._request.statusText;}else if(this._request.parsedURL.isDataURL()){this._setTextAndTitle(cell,Common.UIString('(data)'));}else if(this._request.canceled){this._setTextAndTitle(cell,Common.UIString('(canceled)'));}else if(this._request.wasBlocked()){let reason=Common.UIString('other');switch(this._request.blockedReason()){case Protocol.Network.BlockedReason.Other:reason=Common.UIString('other');break;case Protocol.Network.BlockedReason.Csp:reason=Common.UIString('csp');break;case Protocol.Network.BlockedReason.MixedContent:reason=Common.UIString('mixed-content');break;case Protocol.Network.BlockedReason.Origin:reason=Common.UIString('origin');break;case Protocol.Network.BlockedReason.Inspector:reason=Common.UIString('devtools');break;case Protocol.Network.BlockedReason.SubresourceFilter:reason=Common.UIString('subresource-filter');break;case Protocol.Network.BlockedReason.ContentType:reason=Common.UIString('content-type');break;case Protocol.Network.BlockedReason.CollapsedByClient:reason=Common.UIString('extension');break;}
this._setTextAndTitle(cell,Common.UIString('(blocked:%s)',reason));}else if(this._request.finished){this._setTextAndTitle(cell,Common.UIString('Finished'));}else{this._setTextAndTitle(cell,Common.UIString('(pending)'));}}
_renderInitiatorCell(cell){this._initiatorCell=cell;const request=this._request;const initiator=SDK.networkLog.initiatorInfoForRequest(request);const timing=request.timing;if(timing&&timing.pushStart)
cell.appendChild(createTextNode(Common.UIString('Push / ')));switch(initiator.type){case SDK.NetworkRequest.InitiatorType.Parser:cell.title=initiator.url+':'+(initiator.lineNumber+1);const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(initiator.url);cell.appendChild(Components.Linkifier.linkifyURL(initiator.url,{text:uiSourceCode?uiSourceCode.displayName():undefined,lineNumber:initiator.lineNumber,columnNumber:initiator.columnNumber}));this._appendSubtitle(cell,Common.UIString('Parser'));break;case SDK.NetworkRequest.InitiatorType.Redirect:cell.title=initiator.url;const redirectSource=(request.redirectSource());console.assert(redirectSource);if(this.parentView().nodeForRequest(redirectSource)){cell.appendChild(Components.Linkifier.linkifyRevealable(redirectSource,Bindings.displayNameForURL(redirectSource.url())));}else{cell.appendChild(Components.Linkifier.linkifyURL(redirectSource.url()));}
this._appendSubtitle(cell,Common.UIString('Redirect'));break;case SDK.NetworkRequest.InitiatorType.Script:const networkManager=SDK.NetworkManager.forRequest(request);if(initiator.stack){this._linkifiedInitiatorAnchor=this.parentView().linkifier.linkifyStackTraceTopFrame(networkManager?networkManager.target():null,initiator.stack);}else{this._linkifiedInitiatorAnchor=this.parentView().linkifier.linkifyScriptLocation(networkManager?networkManager.target():null,initiator.scriptId,initiator.url,initiator.lineNumber,initiator.columnNumber);}
this._linkifiedInitiatorAnchor.title='';cell.appendChild(this._linkifiedInitiatorAnchor);this._appendSubtitle(cell,Common.UIString('Script'));cell.classList.add('network-script-initiated');cell.request=request;break;case SDK.NetworkRequest.InitiatorType.Preload:cell.title=Common.UIString('Preload');cell.classList.add('network-dim-cell');cell.appendChild(createTextNode(Common.UIString('Preload')));break;case SDK.NetworkRequest.InitiatorType.SignedExchange:cell.appendChild(Components.Linkifier.linkifyURL(initiator.url));this._appendSubtitle(cell,Common.UIString('signed-exchange'));break;default:cell.title=Common.UIString('Other');cell.classList.add('network-dim-cell');cell.appendChild(createTextNode(Common.UIString('Other')));}}
_renderSizeCell(cell){const resourceSize=Number.bytesToString(this._request.resourceSize);if(this._request.cachedInMemory()){cell.createTextChild(ls`(memory cache)`);cell.title=ls`Served from memory cache, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else if(this._request.fetchedViaServiceWorker){cell.createTextChild(ls`(ServiceWorker)`);cell.title=ls`Served from ServiceWorker, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else if(this._request.redirectSource()&&this._request.redirectSource().signedExchangeInfo()&&!this._request.redirectSource().signedExchangeInfo().errors){cell.createTextChild(ls`(signed-exchange)`);cell.title=ls`Served from Signed HTTP Exchange, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else if(this._request.fromPrefetchCache()){cell.createTextChild(ls`(prefetch cache)`);cell.title=ls`Served from prefetch cache, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else if(this._request.cached()){cell.createTextChild(ls`(disk cache)`);cell.title=ls`Served from disk cache, resource size: ${resourceSize}`;cell.classList.add('network-dim-cell');}else{const transferSize=Number.bytesToString(this._request.transferSize);cell.createTextChild(transferSize);cell.title=`${transferSize} transferred over network, resource size: ${resourceSize}`;}
this._appendSubtitle(cell,resourceSize);}
_renderTimeCell(cell){if(this._request.duration>0){this._setTextAndTitle(cell,Number.secondsToString(this._request.duration));this._appendSubtitle(cell,Number.secondsToString(this._request.latency));}else{cell.classList.add('network-dim-cell');this._setTextAndTitle(cell,Common.UIString('Pending'));}}
_appendSubtitle(cellElement,subtitleText){const subtitleElement=createElement('div');subtitleElement.className='network-cell-subtitle';subtitleElement.textContent=subtitleText;cellElement.appendChild(subtitleElement);}};Network.NetworkGroupNode=class extends Network.NetworkNode{renderCell(cell,columnId){if(columnId==='name'){const leftPadding=this.leftPadding?this.leftPadding+'px':'';cell.style.setProperty('padding-left',leftPadding);cell.classList.add('disclosure');}}
select(supressSelectedEvent){if(this.expanded){this.collapse();return;}
this.expand();}};;Network.NetworkItemView=class extends UI.TabbedPane{constructor(request,calculator){super();this.element.classList.add('network-item-view');this._resourceViewTabSetting=Common.settings.createSetting('resourceViewTab','preview');this._headersView=new Network.RequestHeadersView(request);this.appendTab(Network.NetworkItemView.Tabs.Headers,Common.UIString('Headers'),this._headersView,Common.UIString('Headers and request body'));this.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);if(request.resourceType()===Common.resourceTypes.WebSocket){const frameView=new Network.ResourceWebSocketFrameView(request);this.appendTab(Network.NetworkItemView.Tabs.WsFrames,Common.UIString('Messages'),frameView,Common.UIString('WebSocket messages'));}else if(request.mimeType==='text/event-stream'){this.appendTab(Network.NetworkItemView.Tabs.EventSource,Common.UIString('EventStream'),new Network.EventSourceMessagesView(request));}else{this._responseView=new Network.RequestResponseView(request);const previewView=new Network.RequestPreviewView(request);this.appendTab(Network.NetworkItemView.Tabs.Preview,Common.UIString('Preview'),previewView,Common.UIString('Response preview'));if(request.signedExchangeInfo()&&request.signedExchangeInfo().errors&&request.signedExchangeInfo().errors.length){const icon=UI.Icon.create('smallicon-error');icon.title=Common.UIString('SignedExchange error');this.setTabIcon(Network.NetworkItemView.Tabs.Preview,icon);}
this.appendTab(Network.NetworkItemView.Tabs.Response,Common.UIString('Response'),this._responseView,Common.UIString('Raw response data'));}
if(request.requestCookies||request.responseCookies){this._cookiesView=new Network.RequestCookiesView(request);this.appendTab(Network.NetworkItemView.Tabs.Cookies,Common.UIString('Cookies'),this._cookiesView,Common.UIString('Request and response cookies'));}
this.appendTab(Network.NetworkItemView.Tabs.Timing,Common.UIString('Timing'),new Network.RequestTimingView(request,calculator),Common.UIString('Request and response timeline'));this._request=request;}
wasShown(){super.wasShown();this._selectTab();}
_selectTab(tabId){if(!tabId)
tabId=this._resourceViewTabSetting.get();if(!this.selectTab(tabId))
this.selectTab('headers');}
_tabSelected(event){if(!event.data.isUserGesture)
return;this._resourceViewTabSetting.set(event.data.tabId);}
request(){return this._request;}
async revealResponseBody(line){this._selectTab(Network.NetworkItemView.Tabs.Response);if(this._responseView&&typeof line==='number')
await this._responseView.revealLine((line));}
revealRequestHeader(header){this._selectTab(Network.NetworkItemView.Tabs.Headers);this._headersView.revealRequestHeader(header);}
revealResponseHeader(header){this._selectTab(Network.NetworkItemView.Tabs.Headers);this._headersView.revealResponseHeader(header);}};Network.NetworkItemView.Tabs={Cookies:'cookies',EventSource:'eventSource',Headers:'headers',Preview:'preview',Response:'response',Timing:'timing',WsFrames:'webSocketFrames'};;Network.NetworkTimeBoundary=class{constructor(minimum,maximum){this.minimum=minimum;this.maximum=maximum;}
equals(other){return(this.minimum===other.minimum)&&(this.maximum===other.maximum);}};Network.NetworkTimeCalculator=class extends Common.Object{constructor(startAtZero){super();this.startAtZero=startAtZero;this._minimumBoundary=-1;this._maximumBoundary=-1;this._boundryChangedEventThrottler=new Common.Throttler(0);this._window=null;}
setWindow(window){this._window=window;this._boundaryChanged();}
setInitialUserFriendlyBoundaries(){this._minimumBoundary=0;this._maximumBoundary=1;}
computePosition(time){return(time-this.minimumBoundary())/this.boundarySpan()*this._workingArea;}
formatValue(value,precision){return Number.secondsToString(value,!!precision);}
minimumBoundary(){return this._window?this._window.minimum:this._minimumBoundary;}
zeroTime(){return this._minimumBoundary;}
maximumBoundary(){return this._window?this._window.maximum:this._maximumBoundary;}
boundary(){return new Network.NetworkTimeBoundary(this.minimumBoundary(),this.maximumBoundary());}
boundarySpan(){return this.maximumBoundary()-this.minimumBoundary();}
reset(){this._minimumBoundary=-1;this._maximumBoundary=-1;this._boundaryChanged();}
_value(item){return 0;}
setDisplayWidth(clientWidth){this._workingArea=clientWidth;}
computeBarGraphPercentages(request){let start;let middle;let end;if(request.startTime!==-1)
start=((request.startTime-this.minimumBoundary())/this.boundarySpan())*100;else
start=0;if(request.responseReceivedTime!==-1)
middle=((request.responseReceivedTime-this.minimumBoundary())/this.boundarySpan())*100;else
middle=(this.startAtZero?start:100);if(request.endTime!==-1)
end=((request.endTime-this.minimumBoundary())/this.boundarySpan())*100;else
end=(this.startAtZero?middle:100);if(this.startAtZero){end-=start;middle-=start;start=0;}
return{start:start,middle:middle,end:end};}
computePercentageFromEventTime(eventTime){if(eventTime!==-1&&!this.startAtZero)
return((eventTime-this.minimumBoundary())/this.boundarySpan())*100;return 0;}
percentageToTime(percentage){return percentage*this.boundarySpan()/100+this.minimumBoundary();}
_boundaryChanged(){this._boundryChangedEventThrottler.schedule(dispatchEvent.bind(this));function dispatchEvent(){this.dispatchEventToListeners(Network.NetworkTimeCalculator.Events.BoundariesChanged);return Promise.resolve();}}
updateBoundariesForEventTime(eventTime){if(eventTime===-1||this.startAtZero)
return;if(this._maximumBoundary===undefined||eventTime>this._maximumBoundary){this._maximumBoundary=eventTime;this._boundaryChanged();}}
computeBarGraphLabels(request){let rightLabel='';if(request.responseReceivedTime!==-1&&request.endTime!==-1)
rightLabel=Number.secondsToString(request.endTime-request.responseReceivedTime);const hasLatency=request.latency>0;const leftLabel=hasLatency?Number.secondsToString(request.latency):rightLabel;if(request.timing)
return{left:leftLabel,right:rightLabel};let tooltip;if(hasLatency&&rightLabel){const total=Number.secondsToString(request.duration);tooltip=Network.NetworkTimeCalculator._latencyDownloadTotalFormat.format(leftLabel,rightLabel,total);}else if(hasLatency){tooltip=Network.NetworkTimeCalculator._latencyFormat.format(leftLabel);}else if(rightLabel){tooltip=Network.NetworkTimeCalculator._downloadFormat.format(rightLabel);}
if(request.fetchedViaServiceWorker)
tooltip=Network.NetworkTimeCalculator._fromServiceWorkerFormat.format(tooltip);else if(request.cached())
tooltip=Network.NetworkTimeCalculator._fromCacheFormat.format(tooltip);return{left:leftLabel,right:rightLabel,tooltip:tooltip};}
updateBoundaries(request){const lowerBound=this._lowerBound(request);const upperBound=this._upperBound(request);let changed=false;if(lowerBound!==-1||this.startAtZero)
changed=this._extendBoundariesToIncludeTimestamp(this.startAtZero?0:lowerBound);if(upperBound!==-1)
changed=this._extendBoundariesToIncludeTimestamp(upperBound)||changed;if(changed)
this._boundaryChanged();}
_extendBoundariesToIncludeTimestamp(timestamp){const previousMinimumBoundary=this._minimumBoundary;const previousMaximumBoundary=this._maximumBoundary;const minOffset=Network.NetworkTimeCalculator._minimumSpread;if(this._minimumBoundary===-1||this._maximumBoundary===-1){this._minimumBoundary=timestamp;this._maximumBoundary=timestamp+minOffset;}else{this._minimumBoundary=Math.min(timestamp,this._minimumBoundary);this._maximumBoundary=Math.max(timestamp,this._minimumBoundary+minOffset,this._maximumBoundary);}
return previousMinimumBoundary!==this._minimumBoundary||previousMaximumBoundary!==this._maximumBoundary;}
_lowerBound(request){return 0;}
_upperBound(request){return 0;}};Network.NetworkTimeCalculator._minimumSpread=0.1;Network.NetworkTimeCalculator.Events={BoundariesChanged:Symbol('BoundariesChanged')};Network.NetworkTimeCalculator._latencyDownloadTotalFormat=new Common.UIStringFormat('%s latency, %s download (%s total)');Network.NetworkTimeCalculator._latencyFormat=new Common.UIStringFormat('%s latency');Network.NetworkTimeCalculator._downloadFormat=new Common.UIStringFormat('%s download');Network.NetworkTimeCalculator._fromServiceWorkerFormat=new Common.UIStringFormat('%s (from ServiceWorker)');Network.NetworkTimeCalculator._fromCacheFormat=new Common.UIStringFormat('%s (from cache)');Network.NetworkTransferTimeCalculator=class extends Network.NetworkTimeCalculator{constructor(){super(false);}
formatValue(value,precision){return Number.secondsToString(value-this.zeroTime(),!!precision);}
_lowerBound(request){return request.issueTime();}
_upperBound(request){return request.endTime;}};Network.NetworkTransferDurationCalculator=class extends Network.NetworkTimeCalculator{constructor(){super(true);}
formatValue(value,precision){return Number.secondsToString(value,!!precision);}
_upperBound(request){return request.duration;}};;Network.NetworkLogView=class extends UI.VBox{constructor(filterBar,progressBarContainer,networkLogLargeRowsSetting){super();this.setMinimumSize(50,64);this.registerRequiredCSS('network/networkLogView.css');this.element.id='network-container';this._networkHideDataURLSetting=Common.settings.createSetting('networkHideDataURL',false);this._networkResourceTypeFiltersSetting=Common.settings.createSetting('networkResourceTypeFilters',{});this._rawRowHeight=0;this._progressBarContainer=progressBarContainer;this._networkLogLargeRowsSetting=networkLogLargeRowsSetting;this._networkLogLargeRowsSetting.addChangeListener(updateRowHeight.bind(this),this);function updateRowHeight(){this._rawRowHeight=!!this._networkLogLargeRowsSetting.get()?41:21;this._rowHeight=this._computeRowHeight();}
this._rawRowHeight=0;this._rowHeight=0;updateRowHeight.call(this);this._timeCalculator=new Network.NetworkTransferTimeCalculator();this._durationCalculator=new Network.NetworkTransferDurationCalculator();this._calculator=this._timeCalculator;this._columns=new Network.NetworkLogViewColumns(this,this._timeCalculator,this._durationCalculator,networkLogLargeRowsSetting);this._columns.show(this.element);this._staleRequests=new Set();this._mainRequestLoadTime=-1;this._mainRequestDOMContentLoadedTime=-1;this._highlightedSubstringChanges=[];this._filters=[];this._timeFilter=null;this._hoveredNode=null;this._recordingHint=null;this._refreshRequestId=null;this._highlightedNode=null;this.linkifier=new Components.Linkifier();this.badgePool=new ProductRegistry.BadgePool();this._recording=false;this._needsRefresh=false;this._headerHeight=0;this._groupLookups=new Map();this._groupLookups.set('Frame',new Network.NetworkFrameGrouper(this));this._activeGroupLookup=null;this._textFilterUI=new UI.TextFilterUI();this._textFilterUI.addEventListener(UI.FilterUI.Events.FilterChanged,this._filterChanged,this);filterBar.addFilter(this._textFilterUI);this._dataURLFilterUI=new UI.CheckboxFilterUI('hide-data-url',Common.UIString('Hide data URLs'),true,this._networkHideDataURLSetting);this._dataURLFilterUI.addEventListener(UI.FilterUI.Events.FilterChanged,this._filterChanged.bind(this),this);this._dataURLFilterUI.element().title=ls`Hides data: and blob: URLs`;filterBar.addFilter(this._dataURLFilterUI);const filterItems=Object.values(Common.resourceCategories).map(category=>({name:category.title,label:category.shortTitle,title:category.title}));this._resourceCategoryFilterUI=new UI.NamedBitSetFilterUI(filterItems,this._networkResourceTypeFiltersSetting);this._resourceCategoryFilterUI.addEventListener(UI.FilterUI.Events.FilterChanged,this._filterChanged.bind(this),this);filterBar.addFilter(this._resourceCategoryFilterUI);this._filterParser=new TextUtils.FilterParser(Network.NetworkLogView._searchKeys);this._suggestionBuilder=new UI.FilterSuggestionBuilder(Network.NetworkLogView._searchKeys,Network.NetworkLogView._sortSearchValues);this._resetSuggestionBuilder();this._dataGrid=this._columns.dataGrid();this._setupDataGrid();this._columns.sortByCurrentColumn();filterBar.filterButton().addEventListener(UI.ToolbarButton.Events.Click,this._dataGrid.scheduleUpdate.bind(this._dataGrid,true));this._summaryToolbar=new UI.Toolbar('network-summary-bar',this.element);new UI.DropTarget(this.element,[UI.DropTarget.Type.File],Common.UIString('Drop HAR files here'),this._handleDrop.bind(this));Common.moduleSetting('networkColorCodeResourceTypes').addChangeListener(this._invalidateAllItems.bind(this,false),this);SDK.targetManager.observeModels(SDK.NetworkManager,this);SDK.networkLog.addEventListener(SDK.NetworkLog.Events.RequestAdded,this._onRequestUpdated,this);SDK.networkLog.addEventListener(SDK.NetworkLog.Events.RequestUpdated,this._onRequestUpdated,this);SDK.networkLog.addEventListener(SDK.NetworkLog.Events.Reset,this._reset,this);this._updateGroupByFrame();Common.moduleSetting('network.group-by-frame').addChangeListener(()=>this._updateGroupByFrame());this._filterBar=filterBar;}
_updateGroupByFrame(){const value=Common.moduleSetting('network.group-by-frame').get();this._setGrouping(value?'Frame':null);}
static _sortSearchValues(key,values){if(key===Network.NetworkLogView.FilterType.Priority){values.sort((a,b)=>{const aPriority=(PerfUI.uiLabelToNetworkPriority(a));const bPriority=(PerfUI.uiLabelToNetworkPriority(b));return PerfUI.networkPriorityWeight(aPriority)-PerfUI.networkPriorityWeight(bPriority);});}else{values.sort();}}
static _negativeFilter(filter,request){return!filter(request);}
static _requestPathFilter(regex,request){if(!regex)
return false;return regex.test(request.path()+'/'+request.name());}
static _subdomains(domain){const result=[domain];let indexOfPeriod=domain.indexOf('.');while(indexOfPeriod!==-1){result.push('*'+domain.substring(indexOfPeriod));indexOfPeriod=domain.indexOf('.',indexOfPeriod+1);}
return result;}
static _createRequestDomainFilter(value){function escapeForRegExp(string){return string.escapeForRegExp();}
const escapedPattern=value.split('*').map(escapeForRegExp).join('.*');return Network.NetworkLogView._requestDomainFilter.bind(null,new RegExp('^'+escapedPattern+'$','i'));}
static _requestDomainFilter(regex,request){return regex.test(request.domain);}
static _runningRequestFilter(request){return!request.finished;}
static _fromCacheRequestFilter(request){return request.cached();}
static _interceptedByServiceWorkerFilter(request){return request.fetchedViaServiceWorker;}
static _initiatedByServiceWorkerFilter(request){return request.initiatedByServiceWorker();}
static _requestResponseHeaderFilter(value,request){return request.responseHeaderValue(value)!==undefined;}
static _requestMethodFilter(value,request){return request.requestMethod===value;}
static _requestPriorityFilter(value,request){return request.priority()===value;}
static _requestMimeTypeFilter(value,request){return request.mimeType===value;}
static _requestMixedContentFilter(value,request){if(value===Network.NetworkLogView.MixedContentFilterValues.Displayed)
return request.mixedContentType===Protocol.Security.MixedContentType.OptionallyBlockable;else if(value===Network.NetworkLogView.MixedContentFilterValues.Blocked)
return request.mixedContentType===Protocol.Security.MixedContentType.Blockable&&request.wasBlocked();else if(value===Network.NetworkLogView.MixedContentFilterValues.BlockOverridden)
return request.mixedContentType===Protocol.Security.MixedContentType.Blockable&&!request.wasBlocked();else if(value===Network.NetworkLogView.MixedContentFilterValues.All)
return request.mixedContentType!==Protocol.Security.MixedContentType.None;return false;}
static _requestSchemeFilter(value,request){return request.scheme===value;}
static _requestSetCookieDomainFilter(value,request){const cookies=request.responseCookies;for(let i=0,l=cookies?cookies.length:0;i<l;++i){if(cookies[i].domain()===value)
return true;}
return false;}
static _requestSetCookieNameFilter(value,request){const cookies=request.responseCookies;for(let i=0,l=cookies?cookies.length:0;i<l;++i){if(cookies[i].name()===value)
return true;}
return false;}
static _requestSetCookieValueFilter(value,request){const cookies=request.responseCookies;for(let i=0,l=cookies?cookies.length:0;i<l;++i){if(cookies[i].value()===value)
return true;}
return false;}
static _requestSizeLargerThanFilter(value,request){return request.transferSize>=value;}
static _statusCodeFilter(value,request){return(''+request.statusCode)===value;}
static HTTPRequestsFilter(request){return request.parsedURL.isValid&&(request.scheme in Network.NetworkLogView.HTTPSchemas);}
static _requestTimeFilter(windowStart,windowEnd,request){if(request.issueTime()>windowEnd)
return false;if(request.endTime!==-1&&request.endTime<windowStart)
return false;return true;}
static _copyRequestHeaders(request){InspectorFrontendHost.copyText(request.requestHeadersText());}
static _copyResponseHeaders(request){InspectorFrontendHost.copyText(request.responseHeadersText);}
static async _copyResponse(request){const contentData=await request.contentData();let content=contentData.content||'';if(!request.contentType().isTextType())
content=Common.ContentProvider.contentAsDataURL(content,request.mimeType,contentData.encoded);else if(contentData.encoded)
content=window.atob(content);InspectorFrontendHost.copyText(content);}
_handleDrop(dataTransfer){const items=dataTransfer.items;if(!items.length)
return;const entry=items[0].webkitGetAsEntry();if(entry.isDirectory)
return;entry.file(this.onLoadFromFile.bind(this));}
async onLoadFromFile(file){const outputStream=new Common.StringOutputStream();const reader=new Bindings.ChunkedFileReader(file,10000000);const success=await reader.read(outputStream);if(!success){this._harLoadFailed(reader.error().message);return;}
let harRoot;try{harRoot=new HARImporter.HARRoot(JSON.parse(outputStream.data()));}catch(e){this._harLoadFailed(e);return;}
SDK.networkLog.importRequests(HARImporter.Importer.requestsFromHARLog(harRoot.log));}
_harLoadFailed(message){Common.console.error('Failed to load HAR file with following error: '+message);}
_setGrouping(groupKey){if(this._activeGroupLookup)
this._activeGroupLookup.reset();const groupLookup=groupKey?this._groupLookups.get(groupKey)||null:null;this._activeGroupLookup=groupLookup;this._invalidateAllItems();}
_computeRowHeight(){return Math.round(this._rawRowHeight*window.devicePixelRatio)/window.devicePixelRatio;}
nodeForRequest(request){return request[Network.NetworkLogView._networkNodeSymbol]||null;}
headerHeight(){return this._headerHeight;}
setRecording(recording){this._recording=recording;this._updateSummaryBar();}
modelAdded(networkManager){if(networkManager.target().parentTarget())
return;const resourceTreeModel=networkManager.target().model(SDK.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,this._domContentLoadedEventFired,this);}}
modelRemoved(networkManager){if(!networkManager.target().parentTarget()){const resourceTreeModel=networkManager.target().model(SDK.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,this._domContentLoadedEventFired,this);}}}
setWindow(start,end){if(!start&&!end){this._timeFilter=null;this._timeCalculator.setWindow(null);}else{this._timeFilter=Network.NetworkLogView._requestTimeFilter.bind(null,start,end);this._timeCalculator.setWindow(new Network.NetworkTimeBoundary(start,end));}
this._filterRequests();}
clearSelection(){if(this._dataGrid.selectedNode)
this._dataGrid.selectedNode.deselect();}
_resetSuggestionBuilder(){this._suggestionBuilder.clear();this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Is,Network.NetworkLogView.IsFilterType.Running);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Is,Network.NetworkLogView.IsFilterType.FromCache);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Is,Network.NetworkLogView.IsFilterType.ServiceWorkerIntercepted);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Is,Network.NetworkLogView.IsFilterType.ServiceWorkerInitiated);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.LargerThan,'100');this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.LargerThan,'10k');this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.LargerThan,'1M');this._textFilterUI.setSuggestionProvider(this._suggestionBuilder.completions.bind(this._suggestionBuilder));}
_filterChanged(event){this.removeAllNodeHighlights();this._parseFilterQuery(this._textFilterUI.value());this._filterRequests();}
_showRecordingHint(){this._hideRecordingHint();this._recordingHint=this.element.createChild('div','network-status-pane fill');const hintText=this._recordingHint.createChild('div','recording-hint');let reloadShortcutNode=null;const reloadShortcutDescriptor=UI.shortcutRegistry.shortcutDescriptorsForAction('inspector_main.reload')[0];if(reloadShortcutDescriptor){reloadShortcutNode=this._recordingHint.createChild('b');reloadShortcutNode.textContent=reloadShortcutDescriptor.name;}
if(this._recording){const recordingText=hintText.createChild('span');recordingText.textContent=Common.UIString('Recording network activity\u2026');if(reloadShortcutNode){hintText.createChild('br');hintText.appendChild(UI.formatLocalized('Perform a request or hit %s to record the reload.',[reloadShortcutNode]));}}else{const recordNode=hintText.createChild('b');recordNode.textContent=UI.shortcutRegistry.shortcutTitleForAction('network.toggle-recording');if(reloadShortcutNode){hintText.appendChild(UI.formatLocalized('Record (%s) or reload (%s) to display network activity.',[recordNode,reloadShortcutNode]));}else{hintText.appendChild(UI.formatLocalized('Record (%s) to display network activity.',[recordNode]));}}
hintText.createChild('br');hintText.appendChild(UI.XLink.create('https://developers.google.com/web/tools/chrome-devtools/network/?utm_source=devtools&utm_campaign=2019Q1','Learn more'));}
_hideRecordingHint(){if(this._recordingHint)
this._recordingHint.remove();this._recordingHint=null;}
elementsToRestoreScrollPositionsFor(){if(!this._dataGrid)
return[];return[this._dataGrid.scrollContainer];}
columnExtensionResolved(){this._invalidateAllItems(true);}
_setupDataGrid(){this._dataGrid.setRowContextMenuCallback((contextMenu,node)=>{const request=node.request();if(request)
this.handleContextMenuForRequest(contextMenu,request);});this._dataGrid.setStickToBottom(true);this._dataGrid.setName('networkLog');this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);this._dataGrid.element.classList.add('network-log-grid');this._dataGrid.element.addEventListener('mousedown',this._dataGridMouseDown.bind(this),true);this._dataGrid.element.addEventListener('mousemove',this._dataGridMouseMove.bind(this),true);this._dataGrid.element.addEventListener('mouseleave',()=>this._setHoveredNode(null),true);return this._dataGrid;}
_dataGridMouseMove(event){const node=(this._dataGrid.dataGridNodeFromNode((event.target)));const highlightInitiatorChain=event.shiftKey;this._setHoveredNode(node,highlightInitiatorChain);}
hoveredNode(){return this._hoveredNode;}
_setHoveredNode(node,highlightInitiatorChain){if(this._hoveredNode)
this._hoveredNode.setHovered(false,false);this._hoveredNode=node;if(this._hoveredNode)
this._hoveredNode.setHovered(true,!!highlightInitiatorChain);}
_dataGridMouseDown(event){if(!this._dataGrid.selectedNode&&event.button)
event.consume();}
_updateSummaryBar(){this._hideRecordingHint();let transferSize=0;let resourceSize=0;let selectedNodeNumber=0;let selectedTransferSize=0;let selectedResourceSize=0;let baseTime=-1;let maxTime=-1;let nodeCount=0;for(const request of SDK.networkLog.requests()){const node=request[Network.NetworkLogView._networkNodeSymbol];if(!node)
continue;nodeCount++;const requestTransferSize=request.transferSize;transferSize+=requestTransferSize;const requestResourceSize=request.resourceSize;resourceSize+=requestResourceSize;if(!node[Network.NetworkLogView._isFilteredOutSymbol]){selectedNodeNumber++;selectedTransferSize+=requestTransferSize;selectedResourceSize+=requestResourceSize;}
const networkManager=SDK.NetworkManager.forRequest(request);if(networkManager&&request.url()===networkManager.target().inspectedURL()&&request.resourceType()===Common.resourceTypes.Document&&!networkManager.target().parentTarget())
baseTime=request.startTime;if(request.endTime>maxTime)
maxTime=request.endTime;}
if(!nodeCount){this._showRecordingHint();return;}
this._summaryToolbar.removeToolbarItems();const appendChunk=(chunk,title)=>{const toolbarText=new UI.ToolbarText(chunk);toolbarText.setTitle(title?title:chunk);this._summaryToolbar.appendToolbarItem(toolbarText);return toolbarText.element;};if(selectedNodeNumber!==nodeCount){appendChunk(ls`${selectedNodeNumber} / ${nodeCount} requests`);this._summaryToolbar.appendSeparator();appendChunk(ls`${Number.bytesToString(selectedTransferSize)} / ${Number.bytesToString(transferSize)} transferred`,ls`${selectedTransferSize} B / ${transferSize} B transferred`);this._summaryToolbar.appendSeparator();appendChunk(ls`${Number.bytesToString(selectedResourceSize)} / ${Number.bytesToString(resourceSize)} resources`,ls`${selectedResourceSize} B / ${resourceSize} B resources`);}else{appendChunk(ls`${nodeCount} requests`);this._summaryToolbar.appendSeparator();appendChunk(ls`${Number.bytesToString(transferSize)} transferred`,ls`${transferSize} B transferred`);this._summaryToolbar.appendSeparator();appendChunk(ls`${Number.bytesToString(resourceSize)} resources`,ls`${resourceSize} B resources`);}
if(baseTime!==-1&&maxTime!==-1){this._summaryToolbar.appendSeparator();appendChunk(ls`Finish: ${Number.secondsToString(maxTime - baseTime)}`);if(this._mainRequestDOMContentLoadedTime!==-1&&this._mainRequestDOMContentLoadedTime>baseTime){this._summaryToolbar.appendSeparator();const domContentLoadedText=ls`DOMContentLoaded: ${Number.secondsToString(this._mainRequestDOMContentLoadedTime - baseTime)}`;appendChunk(domContentLoadedText).style.color=Network.NetworkLogView.getDCLEventColor();}
if(this._mainRequestLoadTime!==-1){this._summaryToolbar.appendSeparator();const loadText=ls`Load: ${Number.secondsToString(this._mainRequestLoadTime - baseTime)}`;appendChunk(loadText).style.color=Network.NetworkLogView.getLoadEventColor();}}}
scheduleRefresh(){if(this._needsRefresh)
return;this._needsRefresh=true;if(this.isShowing()&&!this._refreshRequestId)
this._refreshRequestId=this.element.window().requestAnimationFrame(this._refresh.bind(this));}
addFilmStripFrames(times){this._columns.addEventDividers(times,'network-frame-divider');}
selectFilmStripFrame(time){this._columns.selectFilmStripFrame(time);}
clearFilmStripFrame(){this._columns.clearFilmStripFrame();}
_refreshIfNeeded(){if(this._needsRefresh)
this._refresh();}
_invalidateAllItems(deferUpdate){this._staleRequests=new Set(SDK.networkLog.requests());if(deferUpdate)
this.scheduleRefresh();else
this._refresh();}
timeCalculator(){return this._timeCalculator;}
calculator(){return this._calculator;}
setCalculator(x){if(!x||this._calculator===x)
return;if(this._calculator!==x){this._calculator=x;this._columns.setCalculator(this._calculator);}
this._calculator.reset();if(this._calculator.startAtZero)
this._columns.hideEventDividers();else
this._columns.showEventDividers();this._invalidateAllItems();}
_loadEventFired(event){if(!this._recording)
return;const time=(event.data.loadTime);if(time){this._mainRequestLoadTime=time;this._columns.addEventDividers([time],'network-load-divider');}}
_domContentLoadedEventFired(event){if(!this._recording)
return;const data=(event.data);if(data){this._mainRequestDOMContentLoadedTime=data;this._columns.addEventDividers([data],'network-dcl-divider');}}
wasShown(){this._refreshIfNeeded();this._columns.wasShown();}
willHide(){this._columns.willHide();}
onResize(){this._rowHeight=this._computeRowHeight();}
flatNodesList(){return this._dataGrid.rootNode().flatChildren();}
stylesChanged(){this._columns.scheduleRefresh();}
_refresh(){this._needsRefresh=false;if(this._refreshRequestId){this.element.window().cancelAnimationFrame(this._refreshRequestId);this._refreshRequestId=null;}
this.removeAllNodeHighlights();this._timeCalculator.updateBoundariesForEventTime(this._mainRequestLoadTime);this._durationCalculator.updateBoundariesForEventTime(this._mainRequestLoadTime);this._timeCalculator.updateBoundariesForEventTime(this._mainRequestDOMContentLoadedTime);this._durationCalculator.updateBoundariesForEventTime(this._mainRequestDOMContentLoadedTime);const nodesToInsert=new Map();const nodesToRefresh=[];const staleNodes=new Set();while(this._staleRequests.size){const request=this._staleRequests.firstValue();this._staleRequests.delete(request);let node=request[Network.NetworkLogView._networkNodeSymbol];if(!node)
node=this._createNodeForRequest(request);staleNodes.add(node);}
for(const node of staleNodes){const isFilteredOut=!this._applyFilter(node);if(isFilteredOut&&node===this._hoveredNode)
this._setHoveredNode(null);if(!isFilteredOut)
nodesToRefresh.push(node);const request=node.request();this._timeCalculator.updateBoundaries(request);this._durationCalculator.updateBoundaries(request);const newParent=this._parentNodeForInsert(node);if(node[Network.NetworkLogView._isFilteredOutSymbol]===isFilteredOut&&node.parent===newParent)
continue;node[Network.NetworkLogView._isFilteredOutSymbol]=isFilteredOut;const removeFromParent=node.parent&&(isFilteredOut||node.parent!==newParent);if(removeFromParent){let parent=node.parent;parent.removeChild(node);while(parent&&!parent.hasChildren()&&parent.dataGrid&&parent.dataGrid.rootNode()!==parent){const grandparent=parent.parent;grandparent.removeChild(parent);parent=grandparent;}}
if(!newParent||isFilteredOut)
continue;if(!newParent.dataGrid&&!nodesToInsert.has(newParent)){nodesToInsert.set(newParent,this._dataGrid.rootNode());nodesToRefresh.push(newParent);}
nodesToInsert.set(node,newParent);}
for(const node of nodesToInsert.keys())
nodesToInsert.get(node).appendChild(node);for(const node of nodesToRefresh)
node.refresh();this._updateSummaryBar();if(nodesToInsert.size)
this._columns.sortByCurrentColumn();this._dataGrid.updateInstantly();this._didRefreshForTest();}
_didRefreshForTest(){}
_parentNodeForInsert(node){if(!this._activeGroupLookup)
return this._dataGrid.rootNode();const groupNode=this._activeGroupLookup.groupNodeForRequest(node.request());if(!groupNode)
return this._dataGrid.rootNode();return groupNode;}
_reset(){this.dispatchEventToListeners(Network.NetworkLogView.Events.RequestSelected,null);this._setHoveredNode(null);this._columns.reset();this._timeFilter=null;this._calculator.reset();this._timeCalculator.setWindow(null);this.linkifier.reset();this.badgePool.reset();if(this._activeGroupLookup)
this._activeGroupLookup.reset();this._staleRequests.clear();this._resetSuggestionBuilder();this._mainRequestLoadTime=-1;this._mainRequestDOMContentLoadedTime=-1;this._dataGrid.rootNode().removeChildren();this._updateSummaryBar();this._dataGrid.setStickToBottom(true);this.scheduleRefresh();}
setTextFilterValue(filterString){this._textFilterUI.setValue(filterString);this._dataURLFilterUI.setChecked(false);this._resourceCategoryFilterUI.reset();}
_createNodeForRequest(request){const node=new Network.NetworkRequestNode(this,request);request[Network.NetworkLogView._networkNodeSymbol]=node;node[Network.NetworkLogView._isFilteredOutSymbol]=true;for(let redirect=request.redirectSource();redirect;redirect=redirect.redirectSource())
this._refreshRequest(redirect);return node;}
_onRequestUpdated(event){const request=(event.data);this._refreshRequest(request);}
_refreshRequest(request){Network.NetworkLogView._subdomains(request.domain).forEach(this._suggestionBuilder.addItem.bind(this._suggestionBuilder,Network.NetworkLogView.FilterType.Domain));this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Method,request.requestMethod);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MimeType,request.mimeType);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Scheme,''+request.scheme);this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.StatusCode,''+request.statusCode);const priority=request.priority();if(priority){this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.Priority,PerfUI.uiLabelForNetworkPriority(priority));}
if(request.mixedContentType!==Protocol.Security.MixedContentType.None){this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MixedContent,Network.NetworkLogView.MixedContentFilterValues.All);}
if(request.mixedContentType===Protocol.Security.MixedContentType.OptionallyBlockable){this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MixedContent,Network.NetworkLogView.MixedContentFilterValues.Displayed);}
if(request.mixedContentType===Protocol.Security.MixedContentType.Blockable){const suggestion=request.wasBlocked()?Network.NetworkLogView.MixedContentFilterValues.Blocked:Network.NetworkLogView.MixedContentFilterValues.BlockOverridden;this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MixedContent,suggestion);}
const responseHeaders=request.responseHeaders;for(let i=0,l=responseHeaders.length;i<l;++i)
this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.HasResponseHeader,responseHeaders[i].name);const cookies=request.responseCookies;for(let i=0,l=cookies?cookies.length:0;i<l;++i){const cookie=cookies[i];this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.SetCookieDomain,cookie.domain());this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.SetCookieName,cookie.name());this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.SetCookieValue,cookie.value());}
this._staleRequests.add(request);this.scheduleRefresh();}
rowHeight(){return this._rowHeight;}
switchViewMode(gridMode){this._columns.switchViewMode(gridMode);}
handleContextMenuForRequest(contextMenu,request){contextMenu.appendApplicableItems(request);let copyMenu=contextMenu.clipboardSection().appendSubMenuItem(Common.UIString('Copy'));const footerSection=copyMenu.footerSection();if(request){copyMenu.defaultSection().appendItem(UI.copyLinkAddressLabel(),InspectorFrontendHost.copyText.bind(InspectorFrontendHost,request.contentURL()));if(request.requestHeadersText()){copyMenu.defaultSection().appendItem(Common.UIString('Copy request headers'),Network.NetworkLogView._copyRequestHeaders.bind(null,request));}
if(request.responseHeadersText){copyMenu.defaultSection().appendItem(Common.UIString('Copy response headers'),Network.NetworkLogView._copyResponseHeaders.bind(null,request));}
if(request.finished){copyMenu.defaultSection().appendItem(Common.UIString('Copy response'),Network.NetworkLogView._copyResponse.bind(null,request));}
const disableIfBlob=request.isBlobRequest();if(Host.isWin()){footerSection.appendItem(Common.UIString('Copy as PowerShell'),this._copyPowerShellCommand.bind(this,request),disableIfBlob);footerSection.appendItem(Common.UIString('Copy as fetch'),this._copyFetchCall.bind(this,request),disableIfBlob);footerSection.appendItem(Common.UIString('Copy as cURL (cmd)'),this._copyCurlCommand.bind(this,request,'win'),disableIfBlob);footerSection.appendItem(Common.UIString('Copy as cURL (bash)'),this._copyCurlCommand.bind(this,request,'unix'),disableIfBlob);footerSection.appendItem(Common.UIString('Copy all as PowerShell'),this._copyAllPowerShellCommand.bind(this));footerSection.appendItem(Common.UIString('Copy all as fetch'),this._copyAllFetchCall.bind(this));footerSection.appendItem(Common.UIString('Copy all as cURL (cmd)'),this._copyAllCurlCommand.bind(this,'win'));footerSection.appendItem(Common.UIString('Copy all as cURL (bash)'),this._copyAllCurlCommand.bind(this,'unix'));}else{footerSection.appendItem(Common.UIString('Copy as fetch'),this._copyFetchCall.bind(this,request),disableIfBlob);footerSection.appendItem(Common.UIString('Copy as cURL'),this._copyCurlCommand.bind(this,request,'unix'),disableIfBlob);footerSection.appendItem(Common.UIString('Copy all as fetch'),this._copyAllFetchCall.bind(this));footerSection.appendItem(Common.UIString('Copy all as cURL'),this._copyAllCurlCommand.bind(this,'unix'));}}else{copyMenu=contextMenu.clipboardSection().appendSubMenuItem(Common.UIString('Copy'));}
footerSection.appendItem(Common.UIString('Copy all as HAR'),this._copyAll.bind(this));contextMenu.saveSection().appendItem(ls`Save all as HAR with content`,this.exportAll.bind(this));contextMenu.editSection().appendItem(Common.UIString('Clear browser cache'),this._clearBrowserCache.bind(this));contextMenu.editSection().appendItem(Common.UIString('Clear browser cookies'),this._clearBrowserCookies.bind(this));if(request){const maxBlockedURLLength=20;const manager=SDK.multitargetNetworkManager;let patterns=manager.blockedPatterns();const urlWithoutScheme=request.parsedURL.urlWithoutScheme();if(urlWithoutScheme&&!patterns.find(pattern=>pattern.url===urlWithoutScheme)){contextMenu.debugSection().appendItem(Common.UIString('Block request URL'),addBlockedURL.bind(null,urlWithoutScheme));}else if(urlWithoutScheme){const croppedURL=urlWithoutScheme.trimMiddle(maxBlockedURLLength);contextMenu.debugSection().appendItem(Common.UIString('Unblock %s',croppedURL),removeBlockedURL.bind(null,urlWithoutScheme));}
const domain=request.parsedURL.domain();if(domain&&!patterns.find(pattern=>pattern.url===domain)){contextMenu.debugSection().appendItem(Common.UIString('Block request domain'),addBlockedURL.bind(null,domain));}else if(domain){const croppedDomain=domain.trimMiddle(maxBlockedURLLength);contextMenu.debugSection().appendItem(Common.UIString('Unblock %s',croppedDomain),removeBlockedURL.bind(null,domain));}
if(SDK.NetworkManager.canReplayRequest(request)){contextMenu.debugSection().appendItem(Common.UIString('Replay XHR'),SDK.NetworkManager.replayRequest.bind(null,request));}
function addBlockedURL(url){patterns.push({enabled:true,url:url});manager.setBlockedPatterns(patterns);manager.setBlockingEnabled(true);UI.viewManager.showView('network.blocked-urls');}
function removeBlockedURL(url){patterns=patterns.filter(pattern=>pattern.url!==url);manager.setBlockedPatterns(patterns);UI.viewManager.showView('network.blocked-urls');}}}
_harRequests(){return SDK.networkLog.requests().filter(Network.NetworkLogView.HTTPRequestsFilter).filter(request=>{return request.finished||(request.resourceType()===Common.resourceTypes.WebSocket&&request.responseReceivedTime);});}
async _copyAll(){const harArchive={log:await SDK.HARLog.build(this._harRequests())};InspectorFrontendHost.copyText(JSON.stringify(harArchive,null,2));}
async _copyCurlCommand(request,platform){const command=await this._generateCurlCommand(request,platform);InspectorFrontendHost.copyText(command);}
async _copyAllCurlCommand(platform){const commands=await this._generateAllCurlCommand(SDK.networkLog.requests(),platform);InspectorFrontendHost.copyText(commands);}
async _copyFetchCall(request,platform){const command=await this._generateFetchCall(request);InspectorFrontendHost.copyText(command);}
async _copyAllFetchCall(){const commands=await this._generateAllFetchCall(SDK.networkLog.requests());InspectorFrontendHost.copyText(commands);}
async _copyPowerShellCommand(request){const command=await this._generatePowerShellCommand(request);InspectorFrontendHost.copyText(command);}
async _copyAllPowerShellCommand(){const commands=this._generateAllPowerShellCommand(SDK.networkLog.requests());InspectorFrontendHost.copyText(commands);}
async exportAll(){const url=SDK.targetManager.mainTarget().inspectedURL();const parsedURL=url.asParsedURL();const filename=parsedURL?parsedURL.host:'network-log';const stream=new Bindings.FileOutputStream();if(!await stream.open(filename+'.har'))
return;const progressIndicator=new UI.ProgressIndicator();this._progressBarContainer.appendChild(progressIndicator.element);await Network.HARWriter.write(stream,this._harRequests(),progressIndicator);progressIndicator.done();stream.close();}
_clearBrowserCache(){if(confirm(Common.UIString('Are you sure you want to clear browser cache?')))
SDK.multitargetNetworkManager.clearBrowserCache();}
_clearBrowserCookies(){if(confirm(Common.UIString('Are you sure you want to clear browser cookies?')))
SDK.multitargetNetworkManager.clearBrowserCookies();}
_removeAllHighlights(){this.removeAllNodeHighlights();for(let i=0;i<this._highlightedSubstringChanges.length;++i)
UI.revertDomChanges(this._highlightedSubstringChanges[i]);this._highlightedSubstringChanges=[];}
_applyFilter(node){const request=node.request();if(this._timeFilter&&!this._timeFilter(request))
return false;const categoryName=request.resourceType().category().title;if(!this._resourceCategoryFilterUI.accept(categoryName))
return false;if(this._dataURLFilterUI.checked()&&(request.parsedURL.isDataURL()||request.parsedURL.isBlobURL()))
return false;if(request.statusText==='Service Worker Fallback Required')
return false;for(let i=0;i<this._filters.length;++i){if(!this._filters[i](request))
return false;}
return true;}
_parseFilterQuery(query){const descriptors=this._filterParser.parse(query);this._filters=descriptors.map(descriptor=>{const key=descriptor.key;const text=descriptor.text||'';const regex=descriptor.regex;let filter;if(key){const defaultText=(key+':'+text).escapeForRegExp();filter=this._createSpecialFilter((key),text)||Network.NetworkLogView._requestPathFilter.bind(null,new RegExp(defaultText,'i'));}else if(descriptor.regex){filter=Network.NetworkLogView._requestPathFilter.bind(null,(regex));}else{filter=Network.NetworkLogView._requestPathFilter.bind(null,new RegExp(text.escapeForRegExp(),'i'));}
return descriptor.negative?Network.NetworkLogView._negativeFilter.bind(null,filter):filter;});}
_createSpecialFilter(type,value){switch(type){case Network.NetworkLogView.FilterType.Domain:return Network.NetworkLogView._createRequestDomainFilter(value);case Network.NetworkLogView.FilterType.HasResponseHeader:return Network.NetworkLogView._requestResponseHeaderFilter.bind(null,value);case Network.NetworkLogView.FilterType.Is:if(value.toLowerCase()===Network.NetworkLogView.IsFilterType.Running)
return Network.NetworkLogView._runningRequestFilter;if(value.toLowerCase()===Network.NetworkLogView.IsFilterType.FromCache)
return Network.NetworkLogView._fromCacheRequestFilter;if(value.toLowerCase()===Network.NetworkLogView.IsFilterType.ServiceWorkerIntercepted)
return Network.NetworkLogView._interceptedByServiceWorkerFilter;if(value.toLowerCase()===Network.NetworkLogView.IsFilterType.ServiceWorkerInitiated)
return Network.NetworkLogView._initiatedByServiceWorkerFilter;break;case Network.NetworkLogView.FilterType.LargerThan:return this._createSizeFilter(value.toLowerCase());case Network.NetworkLogView.FilterType.Method:return Network.NetworkLogView._requestMethodFilter.bind(null,value);case Network.NetworkLogView.FilterType.MimeType:return Network.NetworkLogView._requestMimeTypeFilter.bind(null,value);case Network.NetworkLogView.FilterType.MixedContent:return Network.NetworkLogView._requestMixedContentFilter.bind(null,(value));case Network.NetworkLogView.FilterType.Scheme:return Network.NetworkLogView._requestSchemeFilter.bind(null,value);case Network.NetworkLogView.FilterType.SetCookieDomain:return Network.NetworkLogView._requestSetCookieDomainFilter.bind(null,value);case Network.NetworkLogView.FilterType.SetCookieName:return Network.NetworkLogView._requestSetCookieNameFilter.bind(null,value);case Network.NetworkLogView.FilterType.SetCookieValue:return Network.NetworkLogView._requestSetCookieValueFilter.bind(null,value);case Network.NetworkLogView.FilterType.Priority:return Network.NetworkLogView._requestPriorityFilter.bind(null,PerfUI.uiLabelToNetworkPriority(value));case Network.NetworkLogView.FilterType.StatusCode:return Network.NetworkLogView._statusCodeFilter.bind(null,value);}
return null;}
_createSizeFilter(value){let multiplier=1;if(value.endsWith('k')){multiplier=1024;value=value.substring(0,value.length-1);}else if(value.endsWith('m')){multiplier=1024*1024;value=value.substring(0,value.length-1);}
const quantity=Number(value);if(isNaN(quantity))
return null;return Network.NetworkLogView._requestSizeLargerThanFilter.bind(null,quantity*multiplier);}
_filterRequests(){this._removeAllHighlights();this._invalidateAllItems();}
_reveal(request){this.removeAllNodeHighlights();const node=request[Network.NetworkLogView._networkNodeSymbol];if(!node||!node.dataGrid)
return null;node.reveal();return node;}
revealAndHighlightRequest(request){const node=this._reveal(request);if(node)
this._highlightNode(node);}
selectRequest(request){this.setTextFilterValue('');const node=this._reveal(request);if(node)
node.select();}
removeAllNodeHighlights(){if(this._highlightedNode){this._highlightedNode.element().classList.remove('highlighted-row');this._highlightedNode=null;}}
_highlightNode(node){UI.runCSSAnimationOnce(node.element(),'highlighted-row');this._highlightedNode=node;}
_filterOutBlobRequests(requests){return requests.filter(request=>!request.isBlobRequest());}
async _generateFetchCall(request){const ignoredHeaders={'method':1,'path':1,'scheme':1,'version':1,'accept-charset':1,'accept-encoding':1,'access-control-request-headers':1,'access-control-request-method':1,'connection':1,'content-length':1,'cookie':1,'cookie2':1,'date':1,'dnt':1,'expect':1,'host':1,'keep-alive':1,'origin':1,'referer':1,'te':1,'trailer':1,'transfer-encoding':1,'upgrade':1,'via':1,'user-agent':1};const credentialHeaders={'cookie':1,'authorization':1};const url=JSON.stringify(request.url());const requestHeaders=request.requestHeaders();const headerData=requestHeaders.reduce((result,header)=>{const name=header.name;if(!ignoredHeaders[name.toLowerCase()]&&!name.includes(':'))
result.append(name,header.value);return result;},new Headers());const headers={};for(const headerArray of headerData)
headers[headerArray[0]]=headerArray[1];const credentials=request.requestCookies||requestHeaders.some(({name})=>credentialHeaders[name.toLowerCase()])?'include':'omit';const referrerHeader=requestHeaders.find(({name})=>name.toLowerCase()==='referer');const referrer=referrerHeader?referrerHeader.value:void 0;const referrerPolicy=request.referrerPolicy()||void 0;const requestBody=await request.requestFormData();const fetchOptions={credentials,headers:Object.keys(headers).length?headers:void 0,referrer,referrerPolicy,body:requestBody,method:request.requestMethod,mode:'cors'};const options=JSON.stringify(fetchOptions);return`fetch(${url}, ${options});`;}
async _generateAllFetchCall(requests){const nonBlobRequests=this._filterOutBlobRequests(requests);const commands=await Promise.all(nonBlobRequests.map(request=>this._generateFetchCall(request)));return commands.join(' ;\n');}
async _generateCurlCommand(request,platform){let command=['curl'];const ignoredHeaders={'host':1,'method':1,'path':1,'scheme':1,'version':1};function escapeStringWin(str){const encapsChars=/[\r\n]/.test(str)?'^"':'"';return encapsChars+
str.replace(/\\/g,'\\\\').replace(/"/g,'\\"').replace(/[^a-zA-Z0-9\s_\-:=+~'\/.',?;()*`]/g,'^$&').replace(/%(?=[a-zA-Z0-9_])/g,'%^').replace(/\r\n|[\n\r]/g,'^\n\n')+
encapsChars;}
function escapeStringPosix(str){function escapeCharacter(x){const code=x.charCodeAt(0);let hexString=code.toString(16);while(hexString.length<4)
hexString='0'+hexString;return'\\u'+hexString;}
if(/[\u0000-\u001f\u007f-\u009f!]|\'/.test(str)){return'$\''+
str.replace(/\\/g,'\\\\').replace(/\'/g,'\\\'').replace(/\n/g,'\\n').replace(/\r/g,'\\r').replace(/[\u0000-\u001f\u007f-\u009f!]/g,escapeCharacter)+'\'';}else{return'\''+str+'\'';}}
const escapeString=platform==='win'?escapeStringWin:escapeStringPosix;command.push(escapeString(request.url()).replace(/[[{}\]]/g,'\\$&'));let inferredMethod='GET';const data=[];const requestContentType=request.requestContentType();const formData=await request.requestFormData();if(requestContentType&&requestContentType.startsWith('application/x-www-form-urlencoded')&&formData){data.push('--data');data.push(escapeString(formData));ignoredHeaders['content-length']=true;inferredMethod='POST';}else if(formData){data.push('--data-binary');data.push(escapeString(formData));ignoredHeaders['content-length']=true;inferredMethod='POST';}
if(request.requestMethod!==inferredMethod){command.push('-X');command.push(request.requestMethod);}
const requestHeaders=request.requestHeaders();for(let i=0;i<requestHeaders.length;i++){const header=requestHeaders[i];const name=header.name.replace(/^:/,'');if(name.toLowerCase()in ignoredHeaders)
continue;command.push('-H');command.push(escapeString(name+': '+header.value));}
command=command.concat(data);command.push('--compressed');if(request.securityState()===Protocol.Security.SecurityState.Insecure)
command.push('--insecure');return command.join(' ');}
async _generateAllCurlCommand(requests,platform){const nonBlobRequests=this._filterOutBlobRequests(requests);const commands=await Promise.all(nonBlobRequests.map(request=>this._generateCurlCommand(request,platform)));if(platform==='win')
return commands.join(' &\r\n');else
return commands.join(' ;\n');}
async _generatePowerShellCommand(request){const command=['Invoke-WebRequest'];const ignoredHeaders=new Set(['host','connection','proxy-connection','content-length','expect','range','content-type']);function escapeString(str){return'"'+
str.replace(/[`\$"]/g,'`$&').replace(/[^\x20-\x7E]/g,char=>'$([char]'+char.charCodeAt(0)+')')+'"';}
command.push('-Uri');command.push(escapeString(request.url()));if(request.requestMethod!=='GET'){command.push('-Method');command.push(escapeString(request.requestMethod));}
const requestHeaders=request.requestHeaders();const headerNameValuePairs=[];for(const header of requestHeaders){const name=header.name.replace(/^:/,'');if(ignoredHeaders.has(name.toLowerCase()))
continue;headerNameValuePairs.push(escapeString(name)+'='+escapeString(header.value));}
if(headerNameValuePairs.length){command.push('-Headers');command.push('@{'+headerNameValuePairs.join('; ')+'}');}
const contentTypeHeader=requestHeaders.find(({name})=>name.toLowerCase()==='content-type');if(contentTypeHeader){command.push('-ContentType');command.push(escapeString(contentTypeHeader.value));}
const formData=await request.requestFormData();if(formData){command.push('-Body');const body=escapeString(formData);if(/[^\x20-\x7E]/.test(formData))
command.push('([System.Text.Encoding]::UTF8.GetBytes('+body+'))');else
command.push(body);}
return command.join(' ');}
async _generateAllPowerShellCommand(requests){const nonBlobRequests=this._filterOutBlobRequests(requests);const commands=await Promise.all(nonBlobRequests.map(request=>this._generatePowerShellCommand(request)));return commands.join(';\r\n');}
static getDCLEventColor(){if(UI.themeSupport.themeName()==='dark')
return'#03A9F4';return'#0867CB';}
static getLoadEventColor(){return UI.themeSupport.patchColorText('#B31412',UI.ThemeSupport.ColorUsage.Foreground);}};Network.NetworkLogView._isFilteredOutSymbol=Symbol('isFilteredOut');Network.NetworkLogView._networkNodeSymbol=Symbol('NetworkNode');Network.NetworkLogView.HTTPSchemas={'http':true,'https':true,'ws':true,'wss':true};Network.NetworkLogView.Events={RequestSelected:Symbol('RequestSelected')};Network.NetworkLogView.FilterType={Domain:'domain',HasResponseHeader:'has-response-header',Is:'is',LargerThan:'larger-than',Method:'method',MimeType:'mime-type',MixedContent:'mixed-content',Priority:'priority',Scheme:'scheme',SetCookieDomain:'set-cookie-domain',SetCookieName:'set-cookie-name',SetCookieValue:'set-cookie-value',StatusCode:'status-code'};Network.NetworkLogView.MixedContentFilterValues={All:'all',Displayed:'displayed',Blocked:'blocked',BlockOverridden:'block-overridden'};Network.NetworkLogView.IsFilterType={Running:'running',FromCache:'from-cache',ServiceWorkerIntercepted:'service-worker-intercepted',ServiceWorkerInitiated:'service-worker-initiated'};Network.NetworkLogView._searchKeys=Object.keys(Network.NetworkLogView.FilterType).map(key=>Network.NetworkLogView.FilterType[key]);Network.NetworkLogView.Filter;Network.GroupLookupInterface=function(){};Network.GroupLookupInterface.prototype={groupNodeForRequest:function(request){},reset:function(){}};;Network.NetworkLogViewColumns=class{constructor(networkLogView,timeCalculator,durationCalculator,networkLogLargeRowsSetting){this._networkLogView=networkLogView;this._persistantSettings=Common.settings.createSetting('networkLogColumns',{});this._networkLogLargeRowsSetting=networkLogLargeRowsSetting;this._networkLogLargeRowsSetting.addChangeListener(this._updateRowsSize,this);this._eventDividers=new Map();this._eventDividersShown=false;this._gridMode=true;this._columns=[];this._waterfallRequestsAreStale=false;this._waterfallScrollerWidthIsStale=true;this._popupLinkifier=new Components.Linkifier();this._calculatorsMap=new Map();this._calculatorsMap.set(Network.NetworkLogViewColumns._calculatorTypes.Time,timeCalculator);this._calculatorsMap.set(Network.NetworkLogViewColumns._calculatorTypes.Duration,durationCalculator);this._lastWheelTime=0;this._setupDataGrid();this._setupWaterfall();}
static _convertToDataGridDescriptor(columnConfig){return({id:columnConfig.id,title:columnConfig.title,sortable:columnConfig.sortable,align:columnConfig.align,nonSelectable:columnConfig.nonSelectable,weight:columnConfig.weight});}
wasShown(){this._updateRowsSize();}
willHide(){this._popoverHelper.hidePopover();}
reset(){if(this._popoverHelper)
this._popoverHelper.hidePopover();this._eventDividers.clear();}
_setupDataGrid(){const defaultColumns=Network.NetworkLogViewColumns._defaultColumns;const defaultColumnConfig=Network.NetworkLogViewColumns._defaultColumnConfig;this._columns=([]);for(const currentConfigColumn of defaultColumns){const columnConfig=(Object.assign({},defaultColumnConfig,currentConfigColumn));columnConfig.id=columnConfig.id;if(columnConfig.subtitle)
columnConfig.titleDOMFragment=this._makeHeaderFragment(columnConfig.title,columnConfig.subtitle);this._columns.push(columnConfig);}
this._loadCustomColumnsAndSettings();this._popoverHelper=new UI.PopoverHelper(this._networkLogView.element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(300,300);this._dataGrid=new DataGrid.SortableDataGrid(this._columns.map(Network.NetworkLogViewColumns._convertToDataGridDescriptor));this._dataGrid.element.addEventListener('mousedown',event=>{if(!this._dataGrid.selectedNode&&event.button)
event.consume();},true);this._dataGridScroller=this._dataGrid.scrollContainer;this._updateColumns();this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortHandler,this);this._dataGrid.setHeaderContextMenuCallback(this._innerHeaderContextMenu.bind(this));this._activeWaterfallSortId=Network.NetworkLogViewColumns.WaterfallSortIds.StartTime;this._dataGrid.markColumnAsSortedBy(Network.NetworkLogViewColumns._initialSortColumn,DataGrid.DataGrid.Order.Ascending);this._splitWidget=new UI.SplitWidget(true,true,'networkPanelSplitViewWaterfall',200);const widget=this._dataGrid.asWidget();widget.setMinimumSize(150,0);this._splitWidget.setMainWidget(widget);}
_setupWaterfall(){this._waterfallColumn=new Network.NetworkWaterfallColumn(this._networkLogView.calculator());this._waterfallColumn.element.addEventListener('contextmenu',handleContextMenu.bind(this));this._waterfallColumn.element.addEventListener('mousewheel',this._onMouseWheel.bind(this,false),{passive:true});this._dataGridScroller.addEventListener('mousewheel',this._onMouseWheel.bind(this,true),true);this._waterfallScroller=this._waterfallColumn.contentElement.createChild('div','network-waterfall-v-scroll');this._waterfallScrollerContent=this._waterfallScroller.createChild('div','network-waterfall-v-scroll-content');this._dataGrid.addEventListener(DataGrid.DataGrid.Events.PaddingChanged,()=>{this._waterfallScrollerWidthIsStale=true;this._syncScrollers();});this._dataGrid.addEventListener(DataGrid.ViewportDataGrid.Events.ViewportCalculated,this._redrawWaterfallColumn.bind(this));this._createWaterfallHeader();this._waterfallColumn.contentElement.classList.add('network-waterfall-view');this._waterfallColumn.setMinimumSize(100,0);this._splitWidget.setSidebarWidget(this._waterfallColumn);this.switchViewMode(false);function handleContextMenu(event){const node=this._waterfallColumn.getNodeFromPoint(event.offsetX,event.offsetY);if(!node)
return;const request=node.request();if(!request)
return;const contextMenu=new UI.ContextMenu(event);this._networkLogView.handleContextMenuForRequest(contextMenu,request);contextMenu.show();}}
_onMouseWheel(shouldConsume,event){if(shouldConsume)
event.consume(true);const hasRecentWheel=Date.now()-this._lastWheelTime<80;this._activeScroller.scrollBy({top:-event.wheelDeltaY,behavior:hasRecentWheel?'instant':'smooth'});this._syncScrollers();this._lastWheelTime=Date.now();}
_syncScrollers(){if(!this._waterfallColumn.isShowing())
return;this._waterfallScrollerContent.style.height=this._dataGridScroller.scrollHeight+'px';this._updateScrollerWidthIfNeeded();this._dataGridScroller.scrollTop=this._waterfallScroller.scrollTop;}
_updateScrollerWidthIfNeeded(){if(this._waterfallScrollerWidthIsStale){this._waterfallScrollerWidthIsStale=false;this._waterfallColumn.setRightPadding(this._waterfallScroller.offsetWidth-this._waterfallScrollerContent.offsetWidth);}}
_redrawWaterfallColumn(){if(!this._waterfallRequestsAreStale){this._updateScrollerWidthIfNeeded();this._waterfallColumn.update(this._activeScroller.scrollTop,this._eventDividersShown?this._eventDividers:undefined);return;}
this._syncScrollers();const nodes=this._networkLogView.flatNodesList();this._waterfallColumn.update(this._activeScroller.scrollTop,this._eventDividers,nodes);}
_createWaterfallHeader(){this._waterfallHeaderElement=this._waterfallColumn.contentElement.createChild('div','network-waterfall-header');this._waterfallHeaderElement.addEventListener('click',waterfallHeaderClicked.bind(this));this._waterfallHeaderElement.addEventListener('contextmenu',event=>this._innerHeaderContextMenu(new UI.ContextMenu(event)));const innerElement=this._waterfallHeaderElement.createChild('div');innerElement.textContent=Common.UIString('Waterfall');this._waterfallColumnSortIcon=UI.Icon.create('','sort-order-icon');this._waterfallHeaderElement.createChild('div','sort-order-icon-container').appendChild(this._waterfallColumnSortIcon);function waterfallHeaderClicked(){const sortOrders=DataGrid.DataGrid.Order;const sortOrder=this._dataGrid.sortOrder()===sortOrders.Ascending?sortOrders.Descending:sortOrders.Ascending;this._dataGrid.markColumnAsSortedBy('waterfall',sortOrder);this._sortHandler();}}
setCalculator(x){this._waterfallColumn.setCalculator(x);}
scheduleRefresh(){this._waterfallColumn.scheduleDraw();}
_updateRowsSize(){const largeRows=!!this._networkLogLargeRowsSetting.get();this._dataGrid.element.classList.toggle('small',!largeRows);this._dataGrid.scheduleUpdate();this._waterfallScrollerWidthIsStale=true;this._waterfallColumn.setRowHeight(largeRows?41:21);this._waterfallScroller.classList.toggle('small',!largeRows);this._waterfallHeaderElement.classList.toggle('small',!largeRows);this._waterfallColumn.setHeaderHeight(this._waterfallScroller.offsetTop);}
show(element){this._splitWidget.show(element);}
dataGrid(){return this._dataGrid;}
sortByCurrentColumn(){this._sortHandler();}
_sortHandler(){const columnId=this._dataGrid.sortColumnId();this._networkLogView.removeAllNodeHighlights();this._waterfallRequestsAreStale=true;if(columnId==='waterfall'){if(this._dataGrid.sortOrder()===DataGrid.DataGrid.Order.Ascending)
this._waterfallColumnSortIcon.setIconType('smallicon-triangle-up');else
this._waterfallColumnSortIcon.setIconType('smallicon-triangle-down');const sortFunction=Network.NetworkRequestNode.RequestPropertyComparator.bind(null,this._activeWaterfallSortId);this._dataGrid.sortNodes(sortFunction,!this._dataGrid.isSortOrderAscending());this._dataGridSortedForTest();return;}
this._waterfallColumnSortIcon.setIconType('');const columnConfig=this._columns.find(columnConfig=>columnConfig.id===columnId);if(!columnConfig||!columnConfig.sortingFunction)
return;this._dataGrid.sortNodes(columnConfig.sortingFunction,!this._dataGrid.isSortOrderAscending());this._dataGridSortedForTest();}
_dataGridSortedForTest(){}
_updateColumns(){if(!this._dataGrid)
return;const visibleColumns=({});if(this._gridMode){for(const columnConfig of this._columns)
visibleColumns[columnConfig.id]=columnConfig.visible;}else{visibleColumns.name=true;}
this._dataGrid.setColumnsVisiblity(visibleColumns);}
switchViewMode(gridMode){if(this._gridMode===gridMode)
return;this._gridMode=gridMode;if(gridMode){if(this._dataGrid.selectedNode)
this._dataGrid.selectedNode.selected=false;this._splitWidget.showBoth();this._activeScroller=this._waterfallScroller;this._waterfallScroller.scrollTop=this._dataGridScroller.scrollTop;this._dataGrid.setScrollContainer(this._waterfallScroller);}else{this._networkLogView.removeAllNodeHighlights();this._splitWidget.hideSidebar();this._activeScroller=this._dataGridScroller;this._dataGrid.setScrollContainer(this._dataGridScroller);}
this._networkLogView.element.classList.toggle('brief-mode',!gridMode);this._updateColumns();this._updateRowsSize();}
_toggleColumnVisibility(columnConfig){this._loadCustomColumnsAndSettings();columnConfig.visible=!columnConfig.visible;this._saveColumnsSettings();this._updateColumns();}
_saveColumnsSettings(){const saveableSettings={};for(const columnConfig of this._columns)
saveableSettings[columnConfig.id]={visible:columnConfig.visible,title:columnConfig.title};this._persistantSettings.set(saveableSettings);}
_loadCustomColumnsAndSettings(){const savedSettings=this._persistantSettings.get();const columnIds=Object.keys(savedSettings);for(const columnId of columnIds){const setting=savedSettings[columnId];let columnConfig=this._columns.find(columnConfig=>columnConfig.id===columnId);if(!columnConfig)
columnConfig=this._addCustomHeader(setting.title,columnId);if(columnConfig.hideable&&typeof setting.visible==='boolean')
columnConfig.visible=!!setting.visible;if(typeof setting.title==='string')
columnConfig.title=setting.title;}}
_makeHeaderFragment(title,subtitle){const fragment=createDocumentFragment();fragment.createTextChild(title);const subtitleDiv=fragment.createChild('div','network-header-subtitle');subtitleDiv.createTextChild(subtitle);return fragment;}
_innerHeaderContextMenu(contextMenu){const columnConfigs=this._columns.filter(columnConfig=>columnConfig.hideable);const nonResponseHeaders=columnConfigs.filter(columnConfig=>!columnConfig.isResponseHeader);for(const columnConfig of nonResponseHeaders){contextMenu.headerSection().appendCheckboxItem(columnConfig.title,this._toggleColumnVisibility.bind(this,columnConfig),columnConfig.visible);}
const responseSubMenu=contextMenu.footerSection().appendSubMenuItem(Common.UIString('Response Headers'));const responseHeaders=columnConfigs.filter(columnConfig=>columnConfig.isResponseHeader);for(const columnConfig of responseHeaders){responseSubMenu.defaultSection().appendCheckboxItem(columnConfig.title,this._toggleColumnVisibility.bind(this,columnConfig),columnConfig.visible);}
responseSubMenu.footerSection().appendItem(Common.UIString('Manage Header Columns\u2026'),this._manageCustomHeaderDialog.bind(this));const waterfallSortIds=Network.NetworkLogViewColumns.WaterfallSortIds;const waterfallSubMenu=contextMenu.footerSection().appendSubMenuItem(Common.UIString('Waterfall'));waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('Start Time'),setWaterfallMode.bind(this,waterfallSortIds.StartTime),this._activeWaterfallSortId===waterfallSortIds.StartTime);waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('Response Time'),setWaterfallMode.bind(this,waterfallSortIds.ResponseTime),this._activeWaterfallSortId===waterfallSortIds.ResponseTime);waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('End Time'),setWaterfallMode.bind(this,waterfallSortIds.EndTime),this._activeWaterfallSortId===waterfallSortIds.EndTime);waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('Total Duration'),setWaterfallMode.bind(this,waterfallSortIds.Duration),this._activeWaterfallSortId===waterfallSortIds.Duration);waterfallSubMenu.defaultSection().appendCheckboxItem(Common.UIString('Latency'),setWaterfallMode.bind(this,waterfallSortIds.Latency),this._activeWaterfallSortId===waterfallSortIds.Latency);contextMenu.show();function setWaterfallMode(sortId){let calculator=this._calculatorsMap.get(Network.NetworkLogViewColumns._calculatorTypes.Time);const waterfallSortIds=Network.NetworkLogViewColumns.WaterfallSortIds;if(sortId===waterfallSortIds.Duration||sortId===waterfallSortIds.Latency)
calculator=this._calculatorsMap.get(Network.NetworkLogViewColumns._calculatorTypes.Duration);this._networkLogView.setCalculator(calculator);this._activeWaterfallSortId=sortId;this._dataGrid.markColumnAsSortedBy('waterfall',DataGrid.DataGrid.Order.Ascending);this._sortHandler();}}
_manageCustomHeaderDialog(){const customHeaders=[];for(const columnConfig of this._columns){if(columnConfig.isResponseHeader)
customHeaders.push({title:columnConfig.title,editable:columnConfig.isCustomHeader});}
const manageCustomHeaders=new Network.NetworkManageCustomHeadersView(customHeaders,headerTitle=>!!this._addCustomHeader(headerTitle),this._changeCustomHeader.bind(this),this._removeCustomHeader.bind(this));const dialog=new UI.Dialog();manageCustomHeaders.show(dialog.contentElement);dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.show(this._networkLogView.element);}
_removeCustomHeader(headerId){headerId=headerId.toLowerCase();const index=this._columns.findIndex(columnConfig=>columnConfig.id===headerId);if(index===-1)
return false;this._columns.splice(index,1);this._dataGrid.removeColumn(headerId);this._saveColumnsSettings();this._updateColumns();return true;}
_addCustomHeader(headerTitle,headerId,index){if(!headerId)
headerId=headerTitle.toLowerCase();if(index===undefined)
index=this._columns.length-1;const currentColumnConfig=this._columns.find(columnConfig=>columnConfig.id===headerId);if(currentColumnConfig)
return null;const columnConfig=(Object.assign({},Network.NetworkLogViewColumns._defaultColumnConfig,{id:headerId,title:headerTitle,isResponseHeader:true,isCustomHeader:true,visible:true,sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,headerId)}));this._columns.splice(index,0,columnConfig);if(this._dataGrid)
this._dataGrid.addColumn(Network.NetworkLogViewColumns._convertToDataGridDescriptor(columnConfig),index);this._saveColumnsSettings();this._updateColumns();return columnConfig;}
_changeCustomHeader(oldHeaderId,newHeaderTitle,newHeaderId){if(!newHeaderId)
newHeaderId=newHeaderTitle.toLowerCase();oldHeaderId=oldHeaderId.toLowerCase();const oldIndex=this._columns.findIndex(columnConfig=>columnConfig.id===oldHeaderId);const oldColumnConfig=this._columns[oldIndex];const currentColumnConfig=this._columns.find(columnConfig=>columnConfig.id===newHeaderId);if(!oldColumnConfig||(currentColumnConfig&&oldHeaderId!==newHeaderId))
return false;this._removeCustomHeader(oldHeaderId);this._addCustomHeader(newHeaderTitle,newHeaderId,oldIndex);return true;}
_getPopoverRequest(event){if(!this._gridMode)
return null;const hoveredNode=this._networkLogView.hoveredNode();if(!hoveredNode)
return null;const anchor=event.target.enclosingNodeOrSelfWithClass('network-script-initiated');if(!anchor)
return null;const request=hoveredNode.request();const initiator=request?request.initiator():null;if(!initiator||!initiator.stack)
return null;return{box:anchor.boxInWindow(),show:popover=>{const manager=anchor.request?SDK.NetworkManager.forRequest(anchor.request):null;const content=Components.JSPresentationUtils.buildStackTracePreviewContents(manager?manager.target():null,this._popupLinkifier,initiator.stack,()=>popover.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent));popover.contentElement.appendChild(content.element);return Promise.resolve(true);},hide:this._popupLinkifier.reset.bind(this._popupLinkifier)};}
addEventDividers(times,className){let color='transparent';switch(className){case'network-dcl-divider':color='#0867CB';break;case'network-load-divider':color='#B31412';break;default:return;}
const currentTimes=this._eventDividers.get(color)||[];this._eventDividers.set(color,currentTimes.concat(times));this._networkLogView.scheduleRefresh();}
hideEventDividers(){this._eventDividersShown=true;this._redrawWaterfallColumn();}
showEventDividers(){this._eventDividersShown=false;this._redrawWaterfallColumn();}
selectFilmStripFrame(time){this._eventDividers.set(Network.NetworkLogViewColumns._filmStripDividerColor,[time]);this._redrawWaterfallColumn();}
clearFilmStripFrame(){this._eventDividers.delete(Network.NetworkLogViewColumns._filmStripDividerColor);this._redrawWaterfallColumn();}};Network.NetworkLogViewColumns._initialSortColumn='waterfall';Network.NetworkLogViewColumns.Descriptor;Network.NetworkLogViewColumns._calculatorTypes={Duration:'Duration',Time:'Time'};Network.NetworkLogViewColumns._defaultColumnConfig={subtitle:null,visible:false,weight:6,sortable:true,hideable:true,nonSelectable:true,isResponseHeader:false,alwaysVisible:false,isCustomHeader:false};Network.NetworkLogViewColumns._defaultColumns=[{id:'name',title:Common.UIString('Name'),subtitle:Common.UIString('Path'),visible:true,weight:20,hideable:false,nonSelectable:false,alwaysVisible:true,sortingFunction:Network.NetworkRequestNode.NameComparator},{id:'method',title:Common.UIString('Method'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'requestMethod')},{id:'status',title:Common.UIString('Status'),visible:true,subtitle:Common.UIString('Text'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'statusCode')},{id:'protocol',title:Common.UIString('Protocol'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'protocol')},{id:'scheme',title:Common.UIString('Scheme'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'scheme')},{id:'domain',title:Common.UIString('Domain'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'domain')},{id:'remoteaddress',title:Common.UIString('Remote Address'),weight:10,align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.RemoteAddressComparator},{id:'type',title:Common.UIString('Type'),visible:true,sortingFunction:Network.NetworkRequestNode.TypeComparator},{id:'initiator',title:Common.UIString('Initiator'),visible:true,weight:10,sortingFunction:Network.NetworkRequestNode.InitiatorComparator},{id:'cookies',title:Common.UIString('Cookies'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.RequestCookiesCountComparator},{id:'setcookies',title:Common.UIString('Set Cookies'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.ResponseCookiesCountComparator},{id:'size',title:Common.UIString('Size'),visible:true,subtitle:Common.UIString('Content'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.SizeComparator},{id:'time',title:Common.UIString('Time'),visible:true,subtitle:Common.UIString('Latency'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'duration')},{id:'priority',title:Common.UIString('Priority'),sortingFunction:Network.NetworkRequestNode.PriorityComparator},{id:'connectionid',title:Common.UIString('Connection ID'),sortingFunction:Network.NetworkRequestNode.RequestPropertyComparator.bind(null,'connectionId')},{id:'cache-control',isResponseHeader:true,title:Common.UIString('Cache-Control'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'cache-control')},{id:'connection',isResponseHeader:true,title:Common.UIString('Connection'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'connection')},{id:'content-encoding',isResponseHeader:true,title:Common.UIString('Content-Encoding'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'content-encoding')},{id:'content-length',isResponseHeader:true,title:Common.UIString('Content-Length'),align:DataGrid.DataGrid.Align.Right,sortingFunction:Network.NetworkRequestNode.ResponseHeaderNumberComparator.bind(null,'content-length')},{id:'etag',isResponseHeader:true,title:Common.UIString('ETag'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'etag')},{id:'keep-alive',isResponseHeader:true,title:Common.UIString('Keep-Alive'),sortingFunction:Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null,'keep-alive')},{id:'last-modified',isResponseHeader:true,title:Common.UIString
groupNodeForRequest(request){const frame=SDK.ResourceTreeModel.frameForRequest(request);if(!frame||frame.isTopFrame())
return null;let groupNode=this._activeGroups.get(frame);if(groupNode)
return groupNode;groupNode=new Network.FrameGroupNode(this._parentView,frame);this._activeGroups.set(frame,groupNode);return groupNode;}
reset(){this._activeGroups.clear();}};Network.FrameGroupNode=class extends Network.NetworkGroupNode{constructor(parentView,frame){super(parentView);this._frame=frame;this._productBadge=null;}
displayName(){return new Common.ParsedURL(this._frame.url).domain()||this._frame.name||'<iframe>';}
renderCell(cell,columnId){super.renderCell(cell,columnId);if(columnId==='name'){const name=this.displayName();if(!this._productBadge){this._productBadge=this.parentView().badgePool.badgeForFrame(this._frame);this._productBadge.classList.add('network-frame-group-badge');}
cell.appendChild(UI.Icon.create('largeicon-navigator-frame','network-frame-group-icon'));cell.appendChild(this._productBadge);cell.createTextChild(name);cell.title=name;}}};;Network.NetworkManageCustomHeadersView=class extends UI.VBox{constructor(columnData,addHeaderColumnCallback,changeHeaderColumnCallback,removeHeaderColumnCallback){super(true);this.registerRequiredCSS('network/networkManageCustomHeadersView.css');this.contentElement.classList.add('custom-headers-wrapper');this.contentElement.createChild('div','header').textContent=Common.UIString('Manage Header Columns');this._list=new UI.ListWidget(this);this._list.element.classList.add('custom-headers-list');this._list.registerRequiredCSS('network/networkManageCustomHeadersView.css');const placeholder=createElementWithClass('div','custom-headers-list-list-empty');placeholder.textContent=Common.UIString('No custom headers');this._list.setEmptyPlaceholder(placeholder);this._list.show(this.contentElement);this.contentElement.appendChild(UI.createTextButton(Common.UIString('Add custom header\u2026'),this._addButtonClicked.bind(this),'add-button'));this._columnConfigs=new Map();columnData.forEach(columnData=>this._columnConfigs.set(columnData.title.toLowerCase(),columnData));this._addHeaderColumnCallback=addHeaderColumnCallback;this._changeHeaderColumnCallback=changeHeaderColumnCallback;this._removeHeaderColumnCallback=removeHeaderColumnCallback;this.contentElement.tabIndex=0;}
wasShown(){this._headersUpdated();}
_headersUpdated(){this._list.clear();this._columnConfigs.forEach(headerData=>this._list.appendItem({header:headerData.title},headerData.editable));}
_addButtonClicked(){this._list.addNewItem(this._columnConfigs.size,{header:''});}
renderItem(item,editable){const element=createElementWithClass('div','custom-headers-list-item');const header=element.createChild('div','custom-header-name');header.textContent=item.header;header.title=item.header;return element;}
removeItemRequested(item,index){this._removeHeaderColumnCallback(item.header);this._columnConfigs.delete(item.header.toLowerCase());this._headersUpdated();}
commitEdit(item,editor,isNew){const headerId=editor.control('header').value.trim();let success;if(isNew)
success=this._addHeaderColumnCallback(headerId);else
success=this._changeHeaderColumnCallback(item.header,headerId);if(success&&!isNew)
this._columnConfigs.delete(item.header.toLowerCase());if(success)
this._columnConfigs.set(headerId.toLowerCase(),{title:headerId,editable:true});this._headersUpdated();}
beginEdit(item){const editor=this._createEditor();editor.control('header').value=item.header;return editor;}
_createEditor(){if(this._editor)
return this._editor;const editor=new UI.ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const titles=content.createChild('div','custom-headers-edit-row');titles.createChild('div','custom-headers-header').textContent=Common.UIString('Header Name');const fields=content.createChild('div','custom-headers-edit-row');fields.createChild('div','custom-headers-header').appendChild(editor.createInput('header','text','x-custom-header',validateHeader.bind(this)));return editor;function validateHeader(item,index,input){const headerId=editor.control('header').value.trim().toLowerCase();if(this._columnConfigs.has(headerId)&&item.header!==headerId)
return false;return true;}}};;Network.NetworkOverview=class extends PerfUI.TimelineOverviewBase{constructor(){super();this._selectedFilmStripTime=-1;this.element.classList.add('network-overview');this._numBands=1;this._updateScheduled=false;SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.DOMContentLoaded,this._domContentLoadedEventFired,this);this.reset();}
setFilmStripModel(filmStripModel){this._filmStripModel=filmStripModel;this.scheduleUpdate();}
selectFilmStripFrame(time){this._selectedFilmStripTime=time;this.scheduleUpdate();}
clearFilmStripFrame(){this._selectedFilmStripTime=-1;this.scheduleUpdate();}
_loadEventFired(event){const time=(event.data.loadTime);if(time)
this._loadEvents.push(time*1000);this.scheduleUpdate();}
_domContentLoadedEventFired(event){const data=(event.data);if(data)
this._domContentLoadedEvents.push(data*1000);this.scheduleUpdate();}
_bandId(connectionId){if(!connectionId||connectionId==='0')
return-1;if(this._bandMap.has(connectionId))
return(this._bandMap.get(connectionId));const result=this._nextBand++;this._bandMap.set(connectionId,result);return result;}
updateRequest(request){if(!this._requestsSet.has(request)){this._requestsSet.add(request);this._requestsList.push(request);}
this.scheduleUpdate();}
wasShown(){this.onResize();}
onResize(){const width=this.element.offsetWidth;const height=this.element.offsetHeight;this.calculator().setDisplayWidth(width);this.resetCanvas();const numBands=(((height-1)/Network.NetworkOverview._bandHeight)-1)|0;this._numBands=(numBands>0)?numBands:1;this.scheduleUpdate();}
reset(){this._filmStripModel=null;this._span=1;this._lastBoundary=null;this._nextBand=0;this._bandMap=new Map();this._requestsList=[];this._requestsSet=new Set();this._loadEvents=[];this._domContentLoadedEvents=[];this.resetCanvas();}
scheduleUpdate(){if(this._updateScheduled||!this.isShowing())
return;this._updateScheduled=true;this.element.window().requestAnimationFrame(this.update.bind(this));}
update(){this._updateScheduled=false;const calculator=this.calculator();const newBoundary=new Network.NetworkTimeBoundary(calculator.minimumBoundary(),calculator.maximumBoundary());if(!this._lastBoundary||!newBoundary.equals(this._lastBoundary)){const span=calculator.boundarySpan();while(this._span<span)
this._span*=1.25;calculator.setBounds(calculator.minimumBoundary(),calculator.minimumBoundary()+this._span);this._lastBoundary=new Network.NetworkTimeBoundary(calculator.minimumBoundary(),calculator.maximumBoundary());}
const context=this.context();const linesByType={};const paddingTop=2;function drawLines(type,strokeStyle){const lines=linesByType[type];if(!lines)
return;const n=lines.length;context.beginPath();context.strokeStyle=strokeStyle;for(let i=0;i<n;){const y=lines[i++]*Network.NetworkOverview._bandHeight+paddingTop;const startTime=lines[i++];let endTime=lines[i++];if(endTime===Number.MAX_VALUE)
endTime=calculator.maximumBoundary();context.moveTo(calculator.computePosition(startTime),y);context.lineTo(calculator.computePosition(endTime)+1,y);}
context.stroke();}
function addLine(type,y,start,end){let lines=linesByType[type];if(!lines){lines=[];linesByType[type]=lines;}
lines.push(y,start,end);}
const requests=this._requestsList;const n=requests.length;for(let i=0;i<n;++i){const request=requests[i];const band=this._bandId(request.connectionId);const y=(band===-1)?0:(band%this._numBands+1);const timeRanges=Network.RequestTimingView.calculateRequestTimeRanges(request,this.calculator().minimumBoundary());for(let j=0;j<timeRanges.length;++j){const type=timeRanges[j].name;if(band!==-1||type===Network.RequestTimeRangeNames.Total)
addLine(type,y,timeRanges[j].start*1000,timeRanges[j].end*1000);}}
context.clearRect(0,0,this.width(),this.height());context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);context.lineWidth=2;drawLines(Network.RequestTimeRangeNames.Total,'#CCCCCC');drawLines(Network.RequestTimeRangeNames.Blocking,'#AAAAAA');drawLines(Network.RequestTimeRangeNames.Connecting,'#FF9800');drawLines(Network.RequestTimeRangeNames.ServiceWorker,'#FF9800');drawLines(Network.RequestTimeRangeNames.ServiceWorkerPreparation,'#FF9800');drawLines(Network.RequestTimeRangeNames.Push,'#8CDBff');drawLines(Network.RequestTimeRangeNames.Proxy,'#A1887F');drawLines(Network.RequestTimeRangeNames.DNS,'#009688');drawLines(Network.RequestTimeRangeNames.SSL,'#9C27B0');drawLines(Network.RequestTimeRangeNames.Sending,'#B0BEC5');drawLines(Network.RequestTimeRangeNames.Waiting,'#00C853');drawLines(Network.RequestTimeRangeNames.Receiving,'#03A9F4');const height=this.element.offsetHeight;context.lineWidth=1;context.beginPath();context.strokeStyle=Network.NetworkLogView.getDCLEventColor();for(let i=this._domContentLoadedEvents.length-1;i>=0;--i){const x=Math.round(calculator.computePosition(this._domContentLoadedEvents[i]))+0.5;context.moveTo(x,0);context.lineTo(x,height);}
context.stroke();context.beginPath();context.strokeStyle=Network.NetworkLogView.getLoadEventColor();for(let i=this._loadEvents.length-1;i>=0;--i){const x=Math.round(calculator.computePosition(this._loadEvents[i]))+0.5;context.moveTo(x,0);context.lineTo(x,height);}
context.stroke();if(this._selectedFilmStripTime!==-1){context.lineWidth=2;context.beginPath();context.strokeStyle='#FCCC49';const x=Math.round(calculator.computePosition(this._selectedFilmStripTime));context.moveTo(x,0);context.lineTo(x,height);context.stroke();}
context.restore();}};Network.NetworkOverview._bandHeight=3;Network.NetworkOverview.Window;;Network.NetworkSearchScope=class{performIndexing(progress){setImmediate(progress.done.bind(progress));}
async performSearch(searchConfig,progress,searchResultCallback,searchFinishedCallback){const promises=[];const requests=SDK.networkLog.requests().filter(request=>searchConfig.filePathMatchesFileQuery(request.url()));progress.setTotalWork(requests.length);for(const request of requests){const promise=this._searchRequest(searchConfig,request,progress);promises.push(promise);}
const results=await Promise.all(promises);if(progress.isCanceled()){searchFinishedCallback(false);return;}
for(const result of results.sort((r1,r2)=>r1.label().localeCompare(r2.label()))){if(result.matchesCount()>0)
searchResultCallback(result);}
progress.done();searchFinishedCallback(true);}
async _searchRequest(searchConfig,request,progress){let bodyMatches=[];if(request.contentType().isTextType()){bodyMatches=await request.searchInContent(searchConfig.query(),!searchConfig.ignoreCase(),searchConfig.isRegex());}
if(progress.isCanceled())
return null;const locations=[];if(stringMatchesQuery(request.url()))
locations.push(Network.UIRequestLocation.urlMatch(request));for(const header of request.requestHeaders()){if(headerMatchesQuery(header))
locations.push(Network.UIRequestLocation.requestHeaderMatch(request,header));}
for(const header of request.responseHeaders){if(headerMatchesQuery(header))
locations.push(Network.UIRequestLocation.responseHeaderMatch(request,header));}
for(const match of bodyMatches)
locations.push(Network.UIRequestLocation.bodyMatch(request,match));progress.worked();return new Network.NetworkSearchResult(request,locations);function headerMatchesQuery(header){return stringMatchesQuery(`${header.name}: ${header.value}`);}
function stringMatchesQuery(string){const flags=searchConfig.ignoreCase()?'i':'';const regExps=searchConfig.queries().map(query=>new RegExp(query,flags));let pos=0;for(const regExp of regExps){const match=string.substr(pos).match(regExp);if(!match)
return false;pos+=match.index+match[0].length;}
return true;}}
stopSearch(){}};Network.UIRequestLocation=class{constructor(request,requestHeader,responseHeader,searchMatch,urlMatch){this.request=request;this.requestHeader=requestHeader;this.responseHeader=responseHeader;this.searchMatch=searchMatch;this.isUrlMatch=urlMatch;}
static requestHeaderMatch(request,header){return new Network.UIRequestLocation(request,header,null,null,false);}
static responseHeaderMatch(request,header){return new Network.UIRequestLocation(request,null,header,null,false);}
static bodyMatch(request,searchMatch){return new Network.UIRequestLocation(request,null,null,searchMatch,false);}
static urlMatch(request){return new Network.UIRequestLocation(request,null,null,null,true);}};Network.NetworkSearchResult=class{constructor(request,locations){this._request=request;this._locations=locations;}
matchesCount(){return this._locations.length;}
label(){return this._request.displayName;}
description(){const parsedUrl=this._request.parsedURL;if(!parsedUrl)
return this._request.url();return parsedUrl.urlWithoutScheme();}
matchLineContent(index){const location=this._locations[index];if(location.isUrlMatch)
return this._request.url();const header=location.requestHeader||location.responseHeader;if(header)
return header.value;return location.searchMatch.lineContent;}
matchRevealable(index){return this._locations[index];}
matchLabel(index){const location=this._locations[index];if(location.isUrlMatch)
return Common.UIString('URL');const header=location.requestHeader||location.responseHeader;if(header)
return`${header.name}:`;return location.searchMatch.lineNumber+1;}};;Network.NetworkWaterfallColumn=class extends UI.VBox{constructor(calculator){super(false);this.registerRequiredCSS('network/networkWaterfallColumn.css');this._canvas=this.contentElement.createChild('canvas');this._canvas.tabIndex=0;this.setDefaultFocusedElement(this._canvas);this._canvasPosition=this._canvas.getBoundingClientRect();this._leftPadding=5;this._fontSize=10;this._rightPadding=0;this._scrollTop=0;this._headerHeight=0;this._calculator=calculator;this._rawRowHeight=0;this._rowHeight=0;this._offsetWidth=0;this._offsetHeight=0;this._startTime=this._calculator.minimumBoundary();this._endTime=this._calculator.maximumBoundary();this._popoverHelper=new UI.PopoverHelper(this.element,this._getPopoverRequest.bind(this));this._popoverHelper.setHasPadding(true);this._popoverHelper.setTimeout(300,300);this._nodes=[];this._hoveredNode=null;this._eventDividers=new Map();this._updateRequestID;this.element.addEventListener('mousemove',this._onMouseMove.bind(this),true);this.element.addEventListener('mouseleave',event=>this._setHoveredNode(null,false),true);this._styleForTimeRangeName=Network.NetworkWaterfallColumn._buildRequestTimeRangeStyle();const resourceStyleTuple=Network.NetworkWaterfallColumn._buildResourceTypeStyle();this._styleForWaitingResourceType=resourceStyleTuple[0];this._styleForDownloadingResourceType=resourceStyleTuple[1];const baseLineColor=UI.themeSupport.patchColorText('#a5a5a5',UI.ThemeSupport.ColorUsage.Foreground);this._wiskerStyle={borderColor:baseLineColor,lineWidth:1};this._hoverDetailsStyle={fillStyle:baseLineColor,lineWidth:1,borderColor:baseLineColor};this._pathForStyle=new Map();this._textLayers=[];}
static _buildRequestTimeRangeStyle(){const types=Network.RequestTimeRangeNames;const styleMap=new Map();styleMap.set(types.Connecting,{fillStyle:'#FF9800'});styleMap.set(types.SSL,{fillStyle:'#9C27B0'});styleMap.set(types.DNS,{fillStyle:'#009688'});styleMap.set(types.Proxy,{fillStyle:'#A1887F'});styleMap.set(types.Blocking,{fillStyle:'#AAAAAA'});styleMap.set(types.Push,{fillStyle:'#8CDBff'});styleMap.set(types.Queueing,{fillStyle:'white',lineWidth:2,borderColor:'lightgrey'});styleMap.set(types.Receiving,{fillStyle:'#03A9F4',lineWidth:2,borderColor:'#03A9F4'});styleMap.set(types.Waiting,{fillStyle:'#00C853'});styleMap.set(types.ReceivingPush,{fillStyle:'#03A9F4'});styleMap.set(types.ServiceWorker,{fillStyle:'orange'});styleMap.set(types.ServiceWorkerPreparation,{fillStyle:'orange'});return styleMap;}
static _buildResourceTypeStyle(){const baseResourceTypeColors=new Map([['document','hsl(215, 100%, 80%)'],['font','hsl(8, 100%, 80%)'],['media','hsl(90, 50%, 80%)'],['image','hsl(90, 50%, 80%)'],['script','hsl(31, 100%, 80%)'],['stylesheet','hsl(272, 64%, 80%)'],['texttrack','hsl(8, 100%, 80%)'],['websocket','hsl(0, 0%, 95%)'],['xhr','hsl(53, 100%, 80%)'],['fetch','hsl(53, 100%, 80%)'],['other','hsl(0, 0%, 95%)'],]);const waitingStyleMap=new Map();const downloadingStyleMap=new Map();for(const resourceType of Object.values(Common.resourceTypes)){let color=baseResourceTypeColors.get(resourceType.name());if(!color)
color=baseResourceTypeColors.get('other');const borderColor=toBorderColor(color);waitingStyleMap.set(resourceType,{fillStyle:toWaitingColor(color),lineWidth:1,borderColor:borderColor});downloadingStyleMap.set(resourceType,{fillStyle:color,lineWidth:1,borderColor:borderColor});}
return[waitingStyleMap,downloadingStyleMap];function toBorderColor(color){const parsedColor=Common.Color.parse(color);const hsla=parsedColor.hsla();hsla[1]/=2;hsla[2]-=Math.min(hsla[2],0.2);return parsedColor.asString(null);}
function toWaitingColor(color){const parsedColor=Common.Color.parse(color);const hsla=parsedColor.hsla();hsla[2]*=1.1;return parsedColor.asString(null);}}
_resetPaths(){this._pathForStyle.clear();this._pathForStyle.set(this._wiskerStyle,new Path2D());this._styleForTimeRangeName.forEach(style=>this._pathForStyle.set(style,new Path2D()));this._styleForWaitingResourceType.forEach(style=>this._pathForStyle.set(style,new Path2D()));this._styleForDownloadingResourceType.forEach(style=>this._pathForStyle.set(style,new Path2D()));this._pathForStyle.set(this._hoverDetailsStyle,new Path2D());}
willHide(){this._popoverHelper.hidePopover();}
wasShown(){this.update();}
_onMouseMove(event){this._setHoveredNode(this.getNodeFromPoint(event.offsetX,event.offsetY),event.shiftKey);}
_getPopoverRequest(event){if(!this._hoveredNode)
return null;const request=this._hoveredNode.request();if(!request)
return null;const useTimingBars=!Common.moduleSetting('networkColorCodeResourceTypes').get()&&!this._calculator.startAtZero;let range;let start;let end;if(useTimingBars){range=Network.RequestTimingView.calculateRequestTimeRanges(request,0).find(data=>data.name===Network.RequestTimeRangeNames.Total);start=this._timeToPosition(range.start);end=this._timeToPosition(range.end);}else{range=this._getSimplifiedBarRange(request,0);start=range.start;end=range.end;}
if(end-start<50){const halfWidth=(end-start)/2;start=start+halfWidth-25;end=end-halfWidth+25;}
if(event.clientX<this._canvasPosition.left+start||event.clientX>this._canvasPosition.left+end)
return null;const rowIndex=this._nodes.findIndex(node=>node.hovered());const barHeight=this._getBarHeight(range.name);const y=this._headerHeight+(this._rowHeight*rowIndex-this._scrollTop)+((this._rowHeight-barHeight)/2);if(event.clientY<this._canvasPosition.top+y||event.clientY>this._canvasPosition.top+y+barHeight)
return null;const anchorBox=this.element.boxInWindow();anchorBox.x+=start;anchorBox.y+=y;anchorBox.width=end-start;anchorBox.height=barHeight;return{box:anchorBox,show:popover=>{const content=Network.RequestTimingView.createTimingTable((request),this._calculator);popover.contentElement.appendChild(content);return Promise.resolve(true);}};}
_setHoveredNode(node,highlightInitiatorChain){if(this._hoveredNode)
this._hoveredNode.setHovered(false,false);this._hoveredNode=node;if(this._hoveredNode)
this._hoveredNode.setHovered(true,highlightInitiatorChain);}
setRowHeight(height){this._rawRowHeight=height;this._updateRowHeight();}
_updateRowHeight(){this._rowHeight=Math.round(this._rawRowHeight*window.devicePixelRatio)/window.devicePixelRatio;}
setHeaderHeight(height){this._headerHeight=height;}
setRightPadding(padding){this._rightPadding=padding;this._calculateCanvasSize();}
setCalculator(calculator){this._calculator=calculator;}
getNodeFromPoint(x,y){if(y<=this._headerHeight)
return null;return this._nodes[Math.floor((this._scrollTop+y-this._headerHeight)/this._rowHeight)];}
scheduleDraw(){if(this._updateRequestID)
return;this._updateRequestID=this.element.window().requestAnimationFrame(()=>this.update());}
update(scrollTop,eventDividers,nodes){if(scrollTop!==undefined&&this._scrollTop!==scrollTop){this._popoverHelper.hidePopover();this._scrollTop=scrollTop;}
if(nodes){this._nodes=nodes;this._calculateCanvasSize();}
if(eventDividers!==undefined)
this._eventDividers=eventDividers;if(this._updateRequestID){this.element.window().cancelAnimationFrame(this._updateRequestID);delete this._updateRequestID;}
this._startTime=this._calculator.minimumBoundary();this._endTime=this._calculator.maximumBoundary();this._resetCanvas();this._resetPaths();this._textLayers=[];this._draw();}
_resetCanvas(){const ratio=window.devicePixelRatio;this._canvas.width=this._offsetWidth*ratio;this._canvas.height=this._offsetHeight*ratio;this._canvas.style.width=this._offsetWidth+'px';this._canvas.style.height=this._offsetHeight+'px';}
onResize(){super.onResize();this._updateRowHeight();this._calculateCanvasSize();this.scheduleDraw();}
_calculateCanvasSize(){this._offsetWidth=this.contentElement.offsetWidth-this._rightPadding;this._offsetHeight=this.contentElement.offsetHeight;this._calculator.setDisplayWidth(this._offsetWidth);this._canvasPosition=this._canvas.getBoundingClientRect();}
_timeToPosition(time){const availableWidth=this._offsetWidth-this._leftPadding;const timeToPixel=availableWidth/(this._endTime-this._startTime);return Math.floor(this._leftPadding+(time-this._startTime)*timeToPixel);}
_didDrawForTest(){}
_draw(){const useTimingBars=!Common.moduleSetting('networkColorCodeResourceTypes').get()&&!this._calculator.startAtZero;const nodes=this._nodes;const context=this._canvas.getContext('2d');context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);context.translate(0,this._headerHeight);context.rect(0,0,this._offsetWidth,this._offsetHeight);context.clip();const firstRequestIndex=Math.floor(this._scrollTop/this._rowHeight);const lastRequestIndex=Math.min(nodes.length,firstRequestIndex+Math.ceil(this._offsetHeight/this._rowHeight));for(let i=firstRequestIndex;i<lastRequestIndex;i++){const rowOffset=this._rowHeight*i;const node=nodes[i];this._decorateRow(context,node,rowOffset-this._scrollTop);let drawNodes=[];if(node.hasChildren()&&!node.expanded)
drawNodes=(node.flatChildren());drawNodes.push(node);for(const drawNode of drawNodes){if(useTimingBars)
this._buildTimingBarLayers(drawNode,rowOffset-this._scrollTop);else
this._buildSimplifiedBarLayers(context,drawNode,rowOffset-this._scrollTop);}}
this._drawLayers(context);context.save();context.fillStyle=UI.themeSupport.patchColorText('#888',UI.ThemeSupport.ColorUsage.Foreground);for(const textData of this._textLayers)
context.fillText(textData.text,textData.x,textData.y);context.restore();this._drawEventDividers(context);context.restore();const freeZoneAtLeft=75;const freeZoneAtRight=18;const dividersData=PerfUI.TimelineGrid.calculateGridOffsets(this._calculator);PerfUI.TimelineGrid.drawCanvasGrid(context,dividersData);PerfUI.TimelineGrid.drawCanvasHeaders(context,dividersData,time=>this._calculator.formatValue(time,dividersData.precision),this._fontSize,this._headerHeight,freeZoneAtLeft);context.clearRect(this._offsetWidth-freeZoneAtRight,0,freeZoneAtRight,this._headerHeight);this._didDrawForTest();}
_drawLayers(context){for(const entry of this._pathForStyle){const style=(entry[0]);const path=(entry[1]);context.save();context.beginPath();if(style.lineWidth){context.lineWidth=style.lineWidth;context.strokeStyle=style.borderColor;context.stroke(path);}
if(style.fillStyle){context.fillStyle=style.fillStyle;context.fill(path);}
context.restore();}}
_drawEventDividers(context){context.save();context.lineWidth=1;for(const color of this._eventDividers.keys()){context.strokeStyle=color;for(const time of this._eventDividers.get(color)){context.beginPath();const x=this._timeToPosition(time);context.moveTo(x,0);context.lineTo(x,this._offsetHeight);}
context.stroke();}
context.restore();}
_getBarHeight(type){const types=Network.RequestTimeRangeNames;switch(type){case types.Connecting:case types.SSL:case types.DNS:case types.Proxy:case types.Blocking:case types.Push:case types.Queueing:return 7;default:return 13;}}
_getSimplifiedBarRange(request,borderOffset){const drawWidth=this._offsetWidth-this._leftPadding;const percentages=this._calculator.computeBarGraphPercentages(request);return{start:this._leftPadding+Math.floor((percentages.start/100)*drawWidth)+borderOffset,mid:this._leftPadding+Math.floor((percentages.middle/100)*drawWidth)+borderOffset,end:this._leftPadding+Math.floor((percentages.end/100)*drawWidth)+borderOffset};}
_buildSimplifiedBarLayers(context,node,y){const request=node.request();if(!request)
return;const borderWidth=1;const borderOffset=borderWidth%2===0?0:0.5;const ranges=this._getSimplifiedBarRange(request,borderOffset);const height=this._getBarHeight();y+=Math.floor(this._rowHeight/2-height/2+borderWidth)-borderWidth/2;const waitingStyle=this._styleForWaitingResourceType.get(request.resourceType());const waitingPath=this._pathForStyle.get(waitingStyle);waitingPath.rect(ranges.start,y,ranges.mid-ranges.start,height-borderWidth);const barWidth=Math.max(2,ranges.end-ranges.mid);const downloadingStyle=this._styleForDownloadingResourceType.get(request.resourceType());const downloadingPath=this._pathForStyle.get(downloadingStyle);downloadingPath.rect(ranges.mid,y,barWidth,height-borderWidth);let labels=null;if(node.hovered()){labels=this._calculator.computeBarGraphLabels(request);const barDotLineLength=10;const leftLabelWidth=context.measureText(labels.left).width;const rightLabelWidth=context.measureText(labels.right).width;const hoverLinePath=this._pathForStyle.get(this._hoverDetailsStyle);if(leftLabelWidth<ranges.mid-ranges.start){const midBarX=ranges.start+(ranges.mid-ranges.start-leftLabelWidth)/2;this._textLayers.push({text:labels.left,x:midBarX,y:y+this._fontSize});}else if(barDotLineLength+leftLabelWidth+this._leftPadding<ranges.start){this._textLayers.push({text:labels.left,x:ranges.start-leftLabelWidth-barDotLineLength-1,y:y+this._fontSize});hoverLinePath.moveTo(ranges.start-barDotLineLength,y+Math.floor(height/2));hoverLinePath.arc(ranges.start,y+Math.floor(height/2),2,0,2*Math.PI);hoverLinePath.moveTo(ranges.start-barDotLineLength,y+Math.floor(height/2));hoverLinePath.lineTo(ranges.start,y+Math.floor(height/2));}
const endX=ranges.mid+barWidth+borderOffset;if(rightLabelWidth<endX-ranges.mid){const midBarX=ranges.mid+(endX-ranges.mid-rightLabelWidth)/2;this._textLayers.push({text:labels.right,x:midBarX,y:y+this._fontSize});}else if(endX+barDotLineLength+rightLabelWidth<this._offsetWidth-this._leftPadding){this._textLayers.push({text:labels.right,x:endX+barDotLineLength+1,y:y+this._fontSize});hoverLinePath.moveTo(endX,y+Math.floor(height/2));hoverLinePath.arc(endX,y+Math.floor(height/2),2,0,2*Math.PI);hoverLinePath.moveTo(endX,y+Math.floor(height/2));hoverLinePath.lineTo(endX+barDotLineLength,y+Math.floor(height/2));}}
if(!this._calculator.startAtZero){const queueingRange=Network.RequestTimingView.calculateRequestTimeRanges(request,0).find(data=>data.name===Network.RequestTimeRangeNames.Total);const leftLabelWidth=labels?context.measureText(labels.left).width:0;const leftTextPlacedInBar=leftLabelWidth<ranges.mid-ranges.start;const wiskerTextPadding=13;const textOffset=(labels&&!leftTextPlacedInBar)?leftLabelWidth+wiskerTextPadding:0;const queueingStart=this._timeToPosition(queueingRange.start);if(ranges.start-textOffset>queueingStart){const wiskerPath=this._pathForStyle.get(this._wiskerStyle);wiskerPath.moveTo(queueingStart,y+Math.floor(height/2));wiskerPath.lineTo(ranges.start-textOffset,y+Math.floor(height/2));const wiskerHeight=height/2;wiskerPath.moveTo(queueingStart+borderOffset,y+wiskerHeight/2);wiskerPath.lineTo(queueingStart+borderOffset,y+height-wiskerHeight/2-1);}}}
_buildTimingBarLayers(node,y){const request=node.request();if(!request)
return;const ranges=Network.RequestTimingView.calculateRequestTimeRanges(request,0);for(const range of ranges){if(range.name===Network.RequestTimeRangeNames.Total||range.name===Network.RequestTimeRangeNames.Sending||range.end-range.start===0)
continue;const style=this._styleForTimeRangeName.get(range.name);const path=this._pathForStyle.get(style);const lineWidth=style.lineWidth||0;const height=this._getBarHeight(range.name);const middleBarY=y+Math.floor(this._rowHeight/2-height/2)+lineWidth/2;const start=this._timeToPosition(range.start);const end=this._timeToPosition(range.end);path.rect(start,middleBarY,end-start,height-lineWidth);}}
_decorateRow(context,node,y){context.save();context.beginPath();context.fillStyle=node.backgroundColor();context.rect(0,y,this._offsetWidth,this._rowHeight);context.fill();context.restore();}};Network.NetworkWaterfallColumn._LayerStyle;Network.NetworkWaterfallColumn._TextLayer;;Network.RequestCookiesView=class extends UI.VBox{constructor(request){super();this.registerRequiredCSS('network/requestCookiesView.css');this.element.classList.add('request-cookies-view');this._request=request;}
wasShown(){this._request.addEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this._refreshCookies,this);this._request.addEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this._refreshCookies,this);if(!this._gotCookies){if(!this._emptyWidget){this._emptyWidget=new UI.EmptyWidget(Common.UIString('This request has no cookies.'));this._emptyWidget.show(this.element);}
return;}
if(!this._cookiesTable)
this._buildCookiesTable();}
willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this._refreshCookies,this);this._request.removeEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this._refreshCookies,this);}
get _gotCookies(){return(this._request.requestCookies&&this._request.requestCookies.length)||(this._request.responseCookies&&this._request.responseCookies.length);}
_buildCookiesTable(){this.detachChildWidgets();this._cookiesTable=new CookieTable.CookiesTable();this._cookiesTable.setCookieFolders([{folderName:Common.UIString('Request Cookies'),cookies:this._request.requestCookies},{folderName:Common.UIString('Response Cookies'),cookies:this._request.responseCookies}]);this._cookiesTable.show(this.element);}
_refreshCookies(){delete this._cookiesTable;if(!this._gotCookies||!this.isShowing())
return;this._buildCookiesTable();}};;Network.RequestHeadersView=class extends UI.VBox{constructor(request){super();this.registerRequiredCSS('network/requestHeadersView.css');this.element.classList.add('request-headers-view');this._request=request;this._decodeRequestParameters=true;this._showRequestHeadersText=false;this._showResponseHeadersText=false;this._highlightedElement=null;const root=new UI.TreeOutlineInShadow();root.registerRequiredCSS('network/requestHeadersTree.css');root.element.classList.add('request-headers-tree');root.setFocusable(false);root.makeDense();root.expandTreeElementsWhenArrowing=true;this.element.appendChild(root.element);const generalCategory=new Network.RequestHeadersView.Category(root,'general',Common.UIString('General'));generalCategory.hidden=false;this._urlItem=generalCategory.createLeaf();this._requestMethodItem=generalCategory.createLeaf();this._statusCodeItem=generalCategory.createLeaf();this._remoteAddressItem=generalCategory.createLeaf();this._remoteAddressItem.hidden=true;this._referrerPolicyItem=generalCategory.createLeaf();this._referrerPolicyItem.hidden=true;this._responseHeadersCategory=new Network.RequestHeadersView.Category(root,'responseHeaders','');this._requestHeadersCategory=new Network.RequestHeadersView.Category(root,'requestHeaders','');this._queryStringCategory=new Network.RequestHeadersView.Category(root,'queryString','');this._formDataCategory=new Network.RequestHeadersView.Category(root,'formData','');this._requestPayloadCategory=new Network.RequestHeadersView.Category(root,'requestPayload',Common.UIString('Request Payload'));}
wasShown(){this._clearHighlight();this._request.addEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged,this._refreshRemoteAddress,this);this._request.addEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestHeaders,this);this._request.addEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this._refreshResponseHeaders,this);this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._refreshHTTPInformation,this);this._refreshURL();this._refreshQueryString();this._refreshRequestHeaders();this._refreshResponseHeaders();this._refreshHTTPInformation();this._refreshRemoteAddress();this._refreshReferrerPolicy();}
willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged,this._refreshRemoteAddress,this);this._request.removeEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestHeaders,this);this._request.removeEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this._refreshResponseHeaders,this);this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._refreshHTTPInformation,this);}
_formatHeader(name,value){const fragment=createDocumentFragment();fragment.createChild('div','header-name').textContent=name+': ';fragment.createChild('span','header-separator');fragment.createChild('div','header-value source-code').textContent=value;return fragment;}
_formatParameter(value,className,decodeParameters){let errorDecoding=false;if(decodeParameters){value=value.replace(/\+/g,' ');if(value.indexOf('%')>=0){try{value=decodeURIComponent(value);}catch(e){errorDecoding=true;}}}
const div=createElementWithClass('div',className);if(value==='')
div.classList.add('empty-value');if(errorDecoding)
div.createChild('span','header-decode-error').textContent=Common.UIString('(unable to decode value)');else
div.textContent=value;return div;}
_refreshURL(){this._urlItem.title=this._formatHeader(Common.UIString('Request URL'),this._request.url());}
_refreshQueryString(){const queryString=this._request.queryString();const queryParameters=this._request.queryParameters;this._queryStringCategory.hidden=!queryParameters;if(queryParameters){this._refreshParams(Common.UIString('Query String Parameters'),queryParameters,queryString,this._queryStringCategory);}}
async _refreshFormData(){this._formDataCategory.hidden=true;this._requestPayloadCategory.hidden=true;const formData=await this._request.requestFormData();if(!formData)
return;const formParameters=await this._request.formParameters();if(formParameters){this._formDataCategory.hidden=false;this._refreshParams(Common.UIString('Form Data'),formParameters,formData,this._formDataCategory);}else{this._requestPayloadCategory.hidden=false;try{const json=JSON.parse(formData);this._refreshRequestJSONPayload(json,formData);}catch(e){this._populateTreeElementWithSourceText(this._requestPayloadCategory,formData);}}}
_populateTreeElementWithSourceText(treeElement,sourceText){const max_len=3000;const text=(sourceText||'').trim();const trim=text.length>max_len;const sourceTextElement=createElementWithClass('span','header-value source-code');sourceTextElement.textContent=trim?text.substr(0,max_len):text;const sourceTreeElement=new UI.TreeElement(sourceTextElement);sourceTreeElement.selectable=false;treeElement.removeChildren();treeElement.appendChild(sourceTreeElement);if(!trim)
return;const showMoreButton=createElementWithClass('button','request-headers-show-more-button');showMoreButton.textContent=Common.UIString('Show more');showMoreButton.addEventListener('click',()=>{showMoreButton.remove();sourceTextElement.textContent=text;});sourceTextElement.appendChild(showMoreButton);}
_refreshParams(title,params,sourceText,paramsTreeElement){paramsTreeElement.removeChildren();paramsTreeElement.listItemElement.removeChildren();paramsTreeElement.listItemElement.createTextChild(title);const headerCount=createElementWithClass('span','header-count');headerCount.textContent=Common.UIString('\u00A0(%d)',params.length);paramsTreeElement.listItemElement.appendChild(headerCount);function toggleViewSource(event){paramsTreeElement[Network.RequestHeadersView._viewSourceSymbol]=!paramsTreeElement[Network.RequestHeadersView._viewSourceSymbol];this._refreshParams(title,params,sourceText,paramsTreeElement);event.consume();}
paramsTreeElement.listItemElement.appendChild(this._createViewSourceToggle(paramsTreeElement[Network.RequestHeadersView._viewSourceSymbol],toggleViewSource.bind(this)));if(paramsTreeElement[Network.RequestHeadersView._viewSourceSymbol]){this._populateTreeElementWithSourceText(paramsTreeElement,sourceText);return;}
const toggleTitle=this._decodeRequestParameters?Common.UIString('view URL encoded'):Common.UIString('view decoded');const toggleButton=this._createToggleButton(toggleTitle);toggleButton.addEventListener('click',this._toggleURLDecoding.bind(this),false);paramsTreeElement.listItemElement.appendChild(toggleButton);for(let i=0;i<params.length;++i){const paramNameValue=createDocumentFragment();if(params[i].name!==''){const name=this._formatParameter(params[i].name+': ','header-name',this._decodeRequestParameters);const value=this._formatParameter(params[i].value,'header-value source-code',this._decodeRequestParameters);paramNameValue.appendChild(name);paramNameValue.createChild('span','header-separator');paramNameValue.appendChild(value);}else{paramNameValue.appendChild(this._formatParameter(Common.UIString('(empty)'),'empty-request-header',this._decodeRequestParameters));}
const paramTreeElement=new UI.TreeElement(paramNameValue);paramTreeElement.selectable=false;paramsTreeElement.appendChild(paramTreeElement);}}
_refreshRequestJSONPayload(parsedObject,sourceText){const treeElement=this._requestPayloadCategory;treeElement.removeChildren();const listItem=this._requestPayloadCategory.listItemElement;listItem.removeChildren();listItem.createTextChild(this._requestPayloadCategory.title);function toggleViewSource(event){treeElement[Network.RequestHeadersView._viewSourceSymbol]=!treeElement[Network.RequestHeadersView._viewSourceSymbol];this._refreshRequestJSONPayload(parsedObject,sourceText);event.consume();}
listItem.appendChild(this._createViewSourceToggle(treeElement[Network.RequestHeadersView._viewSourceSymbol],toggleViewSource.bind(this)));if(treeElement[Network.RequestHeadersView._viewSourceSymbol]){this._populateTreeElementWithSourceText(this._requestPayloadCategory,sourceText);}else{const object=SDK.RemoteObject.fromLocalObject(parsedObject);const section=new ObjectUI.ObjectPropertiesSection(object,object.description);section.expand();section.editable=false;treeElement.appendChild(new UI.TreeElement(section.element));}}
_createViewSourceToggle(viewSource,handler){const viewSourceToggleTitle=viewSource?Common.UIString('view parsed'):Common.UIString('view source');const viewSourceToggleButton=this._createToggleButton(viewSourceToggleTitle);viewSourceToggleButton.addEventListener('click',handler,false);return viewSourceToggleButton;}
_toggleURLDecoding(event){this._decodeRequestParameters=!this._decodeRequestParameters;this._refreshQueryString();this._refreshFormData();event.consume();}
_refreshRequestHeaders(){const treeElement=this._requestHeadersCategory;const headers=this._request.requestHeaders().slice();headers.sort(function(a,b){return a.name.toLowerCase().compareTo(b.name.toLowerCase());});const headersText=this._request.requestHeadersText();if(this._showRequestHeadersText&&headersText)
this._refreshHeadersText(Common.UIString('Request Headers'),headers.length,headersText,treeElement);else
this._refreshHeaders(Common.UIString('Request Headers'),headers,treeElement,headersText===undefined);if(headersText){const toggleButton=this._createHeadersToggleButton(this._showRequestHeadersText);toggleButton.addEventListener('click',this._toggleRequestHeadersText.bind(this),false);treeElement.listItemElement.appendChild(toggleButton);}
this._refreshFormData();}
_refreshResponseHeaders(){const treeElement=this._responseHeadersCategory;const headers=this._request.sortedResponseHeaders.slice();const headersText=this._request.responseHeadersText;if(this._showResponseHeadersText)
this._refreshHeadersText(Common.UIString('Response Headers'),headers.length,headersText,treeElement);else
this._refreshHeaders(Common.UIString('Response Headers'),headers,treeElement);if(headersText){const toggleButton=this._createHeadersToggleButton(this._showResponseHeadersText);toggleButton.addEventListener('click',this._toggleResponseHeadersText.bind(this),false);treeElement.listItemElement.appendChild(toggleButton);}}
_refreshHTTPInformation(){const requestMethodElement=this._requestMethodItem;requestMethodElement.hidden=!this._request.statusCode;const statusCodeElement=this._statusCodeItem;statusCodeElement.hidden=!this._request.statusCode;if(this._request.statusCode){const statusCodeFragment=createDocumentFragment();statusCodeFragment.createChild('div','header-name').textContent=ls`Status Code`+': ';statusCodeFragment.createChild('span','header-separator');const statusCodeImage=statusCodeFragment.createChild('span','resource-status-image','dt-icon-label');statusCodeImage.title=this._request.statusCode+' '+this._request.statusText;if(this._request.statusCode<300||this._request.statusCode===304)
statusCodeImage.type='smallicon-green-ball';else if(this._request.statusCode<400)
statusCodeImage.type='smallicon-orange-ball';else
statusCodeImage.type='smallicon-red-ball';requestMethodElement.title=this._formatHeader(ls`Request Method`,this._request.requestMethod);const statusTextElement=statusCodeFragment.createChild('div','header-value source-code');let statusText=this._request.statusCode+' '+this._request.statusText;if(this._request.cachedInMemory()){statusText+=' '+ls`(from memory cache)`;statusTextElement.classList.add('status-from-cache');}else if(this._request.fetchedViaServiceWorker){statusText+=' '+ls`(from ServiceWorker)`;statusTextElement.classList.add('status-from-cache');}else if(this._request.redirectSource()&&this._request.redirectSource().signedExchangeInfo()&&!this._request.redirectSource().signedExchangeInfo().errors){statusText+=' '+ls`(from signed-exchange)`;statusTextElement.classList.add('status-from-cache');}else if(this._request.fromPrefetchCache()){statusText+=' '+ls`(from prefetch cache)`;statusTextElement.classList.add('status-from-cache');}else if(this._request.cached()){statusText+=' '+ls`(from disk cache)`;statusTextElement.classList.add('status-from-cache');}
statusTextElement.textContent=statusText;statusCodeElement.title=statusCodeFragment;}}
_refreshHeadersTitle(title,headersTreeElement,headersLength){headersTreeElement.listItemElement.removeChildren();headersTreeElement.listItemElement.createTextChild(title);const headerCount=Common.UIString('\u00A0(%d)',headersLength);headersTreeElement.listItemElement.createChild('span','header-count').textContent=headerCount;}
_refreshHeaders(title,headers,headersTreeElement,provisionalHeaders){headersTreeElement.removeChildren();const length=headers.length;this._refreshHeadersTitle(title,headersTreeElement,length);if(provisionalHeaders){const cautionText=Common.UIString('Provisional headers are shown');const cautionFragment=createDocumentFragment();cautionFragment.createChild('span','','dt-icon-label').type='smallicon-warning';cautionFragment.createChild('div','caution').textContent=cautionText;const cautionTreeElement=new UI.TreeElement(cautionFragment);cautionTreeElement.selectable=false;headersTreeElement.appendChild(cautionTreeElement);}
headersTreeElement.hidden=!length&&!provisionalHeaders;for(let i=0;i<length;++i){const headerTreeElement=new UI.TreeElement(this._formatHeader(headers[i].name,headers[i].value));headerTreeElement.selectable=false;headersTreeElement.appendChild(headerTreeElement);headerTreeElement[Network.RequestHeadersView._headerNameSymbol]=headers[i].name;}}
_refreshHeadersText(title,count,headersText,headersTreeElement){this._populateTreeElementWithSourceText(headersTreeElement,headersText);this._refreshHeadersTitle(title,headersTreeElement,count);}
_refreshRemoteAddress(){const remoteAddress=this._request.remoteAddress();const treeElement=this._remoteAddressItem;treeElement.hidden=!remoteAddress;if(remoteAddress)
treeElement.title=this._formatHeader(Common.UIString('Remote Address'),remoteAddress);}
_refreshReferrerPolicy(){const referrerPolicy=this._request.referrerPolicy();const treeElement=this._referrerPolicyItem;treeElement.hidden=!referrerPolicy;if(referrerPolicy)
treeElement.title=this._formatHeader(Common.UIString('Referrer Policy'),referrerPolicy);}
_toggleRequestHeadersText(event){this._showRequestHeadersText=!this._showRequestHeadersText;this._refreshRequestHeaders();event.consume();}
_toggleResponseHeadersText(event){this._showResponseHeadersText=!this._showResponseHeadersText;this._refreshResponseHeaders();event.consume();}
_createToggleButton(title){const button=createElementWithClass('span','header-toggle');button.textContent=title;return button;}
_createHeadersToggleButton(isHeadersTextShown){const toggleTitle=isHeadersTextShown?Common.UIString('view parsed'):Common.UIString('view source');return this._createToggleButton(toggleTitle);}
_clearHighlight(){if(this._highlightedElement)
this._highlightedElement.listItemElement.classList.remove('header-highlight');this._highlightedElement=null;}
_revealAndHighlight(category,name){this._clearHighlight();for(const element of category.children()){if(element[Network.RequestHeadersView._headerNameSymbol]!==name)
continue;this._highlightedElement=element;element.reveal();element.listItemElement.classList.add('header-highlight');return;}}
revealRequestHeader(header){this._revealAndHighlight(this._requestHeadersCategory,header);}
revealResponseHeader(header){this._revealAndHighlight(this._responseHeadersCategory,header);}};Network.RequestHeadersView._headerNameSymbol=Symbol('HeaderName');Network.RequestHeadersView._viewSourceSymbol=Symbol('ViewSource');Network.RequestHeadersView.Category=class extends UI.TreeElement{constructor(root,name,title){super(title||'',true);this.selectable=false;this.toggleOnClick=true;this.hidden=true;this._expandedSetting=Common.settings.createSetting('request-info-'+name+'-category-expanded',true);this.expanded=this._expandedSetting.get();root.appendChild(this);}
createLeaf(){const leaf=new UI.TreeElement();leaf.selectable=false;this.appendChild(leaf);return leaf;}
onexpand(){this._expandedSetting.set(true);}
oncollapse(){this._expandedSetting.set(false);}};;Network.RequestHTMLView=class extends UI.VBox{constructor(dataURL){super(true);this.registerRequiredCSS('network/requestHTMLView.css');this._dataURL=encodeURI(dataURL).replace(/#/g,'%23');this.contentElement.classList.add('html','request-view');}
wasShown(){this._createIFrame();}
willHide(){this.contentElement.removeChildren();}
_createIFrame(){this.contentElement.removeChildren();const iframe=createElement('iframe');iframe.className='html-preview-frame';iframe.setAttribute('sandbox','');iframe.setAttribute('src',this._dataURL);iframe.setAttribute('tabIndex',-1);this.contentElement.appendChild(iframe);}};;Network.RequestResponseView=class extends UI.VBox{constructor(request){super();this.element.classList.add('request-view');this.request=request;this._contentViewPromise=null;}
static _hasTextContent(request,contentData){const mimeType=request.mimeType||'';let resourceType=Common.ResourceType.fromMimeType(mimeType);if(resourceType===Common.resourceTypes.Other)
resourceType=request.contentType();if(resourceType===Common.resourceTypes.Image)
return mimeType.startsWith('image/svg');if(resourceType.isTextType())
return true;if(contentData.error)
return false;if(resourceType===Common.resourceTypes.Other)
return!!contentData.content&&!contentData.encoded;return false;}
static async sourceViewForRequest(request){let sourceView=request[Network.RequestResponseView._sourceViewSymbol];if(sourceView!==undefined)
return sourceView;const contentData=await request.contentData();if(!Network.RequestResponseView._hasTextContent(request,contentData)){request[Network.RequestResponseView._sourceViewSymbol]=null;return null;}
const highlighterType=request.resourceType().canonicalMimeType()||request.mimeType;sourceView=SourceFrame.ResourceSourceFrame.createSearchableView(request,highlighterType);request[Network.RequestResponseView._sourceViewSymbol]=sourceView;return sourceView;}
wasShown(){this._doShowPreview();}
_doShowPreview(){if(!this._contentViewPromise)
this._contentViewPromise=this.showPreview();return this._contentViewPromise;}
async showPreview(){const responseView=await this.createPreview();responseView.show(this.element);return responseView;}
async createPreview(){const contentData=await this.request.contentData();const sourceView=await Network.RequestResponseView.sourceViewForRequest(this.request);if((!contentData.content||!sourceView)&&!contentData.error)
return new UI.EmptyWidget(Common.UIString('This request has no response data available.'));if(contentData.content&&sourceView)
return sourceView;return new UI.EmptyWidget(Common.UIString('Failed to load response data'));}
async revealLine(line){const view=await this._doShowPreview();if(view instanceof SourceFrame.ResourceSourceFrame.SearchableContainer)
view.revealPosition(line);}};Network.RequestResponseView._sourceViewSymbol=Symbol('RequestResponseSourceView');;Network.RequestPreviewView=class extends Network.RequestResponseView{constructor(request){super(request);}
async showPreview(){const view=await super.showPreview();if(!(view instanceof UI.SimpleView))
return view;const toolbar=new UI.Toolbar('network-item-preview-toolbar',this.element);for(const item of view.syncToolbarItems())
toolbar.appendToolbarItem(item);return view;}
async _htmlPreview(){const contentData=await this.request.contentData();if(contentData.error)
return new UI.EmptyWidget(Common.UIString('Failed to load response data'));const whitelist=new Set(['text/html','text/plain','application/xhtml+xml']);if(!whitelist.has(this.request.mimeType))
return null;const content=contentData.encoded?window.atob(contentData.content):contentData.content;const jsonView=await SourceFrame.JSONView.createView(content);if(jsonView)
return jsonView;const dataURL=Common.ContentProvider.contentAsDataURL(contentData.content,this.request.mimeType,contentData.encoded,this.request.charset());return dataURL?new Network.RequestHTMLView(dataURL):null;}
async createPreview(){if(this.request.signedExchangeInfo())
return new Network.SignedExchangeInfoView(this.request);const htmlErrorPreview=await this._htmlPreview();if(htmlErrorPreview)
return htmlErrorPreview;const provided=await SourceFrame.PreviewFactory.createPreview(this.request,this.request.mimeType);if(provided)
return provided;return new UI.EmptyWidget(Common.UIString('Preview not available'));}};;Network.RequestTimingView=class extends UI.VBox{constructor(request,calculator){super();this.element.classList.add('resource-timing-view');this._request=request;this._calculator=calculator;}
static _timeRangeTitle(name){switch(name){case Network.RequestTimeRangeNames.Push:return Common.UIString('Receiving Push');case Network.RequestTimeRangeNames.Queueing:return Common.UIString('Queueing');case Network.RequestTimeRangeNames.Blocking:return Common.UIString('Stalled');case Network.RequestTimeRangeNames.Connecting:return Common.UIString('Initial connection');case Network.RequestTimeRangeNames.DNS:return Common.UIString('DNS Lookup');case Network.RequestTimeRangeNames.Proxy:return Common.UIString('Proxy negotiation');case Network.RequestTimeRangeNames.ReceivingPush:return Common.UIString('Reading Push');case Network.RequestTimeRangeNames.Receiving:return Common.UIString('Content Download');case Network.RequestTimeRangeNames.Sending:return Common.UIString('Request sent');case Network.RequestTimeRangeNames.ServiceWorker:return Common.UIString('Request to ServiceWorker');case Network.RequestTimeRangeNames.ServiceWorkerPreparation:return Common.UIString('ServiceWorker Preparation');case Network.RequestTimeRangeNames.SSL:return Common.UIString('SSL');case Network.RequestTimeRangeNames.Total:return Common.UIString('Total');case Network.RequestTimeRangeNames.Waiting:return Common.UIString('Waiting (TTFB)');default:return Common.UIString(name);}}
static calculateRequestTimeRanges(request,navigationStart){const result=[];function addRange(name,start,end){if(start<Number.MAX_VALUE&&start<=end)
result.push({name:name,start:start,end:end});}
function firstPositive(numbers){for(let i=0;i<numbers.length;++i){if(numbers[i]>0)
return numbers[i];}
return undefined;}
function addOffsetRange(name,start,end){if(start>=0&&end>=0)
addRange(name,startTime+(start/1000),startTime+(end/1000));}
const timing=request.timing;if(!timing){const start=request.issueTime()!==-1?request.issueTime():request.startTime!==-1?request.startTime:0;const middle=(request.responseReceivedTime===-1)?Number.MAX_VALUE:request.responseReceivedTime;const end=(request.endTime===-1)?Number.MAX_VALUE:request.endTime;addRange(Network.RequestTimeRangeNames.Total,start,end);addRange(Network.RequestTimeRangeNames.Blocking,start,middle);addRange(Network.RequestTimeRangeNames.Receiving,middle,end);return result;}
const issueTime=request.issueTime();const startTime=timing.requestTime;const endTime=firstPositive([request.endTime,request.responseReceivedTime])||startTime;addRange(Network.RequestTimeRangeNames.Total,issueTime<startTime?issueTime:startTime,endTime);if(timing.pushStart){const pushEnd=timing.pushEnd||endTime;if(pushEnd>navigationStart)
addRange(Network.RequestTimeRangeNames.Push,Math.max(timing.pushStart,navigationStart),pushEnd);}
if(issueTime<startTime)
addRange(Network.RequestTimeRangeNames.Queueing,issueTime,startTime);const responseReceived=(request.responseReceivedTime-startTime)*1000;if(request.fetchedViaServiceWorker){addOffsetRange(Network.RequestTimeRangeNames.Blocking,0,timing.workerStart);addOffsetRange(Network.RequestTimeRangeNames.ServiceWorkerPreparation,timing.workerStart,timing.workerReady);addOffsetRange(Network.RequestTimeRangeNames.ServiceWorker,timing.workerReady,timing.sendEnd);addOffsetRange(Network.RequestTimeRangeNames.Waiting,timing.sendEnd,responseReceived);}else if(!timing.pushStart){const blockingEnd=firstPositive([timing.dnsStart,timing.connectStart,timing.sendStart,responseReceived])||0;addOffsetRange(Network.RequestTimeRangeNames.Blocking,0,blockingEnd);addOffsetRange(Network.RequestTimeRangeNames.Proxy,timing.proxyStart,timing.proxyEnd);addOffsetRange(Network.RequestTimeRangeNames.DNS,timing.dnsStart,timing.dnsEnd);addOffsetRange(Network.RequestTimeRangeNames.Connecting,timing.connectStart,timing.connectEnd);addOffsetRange(Network.RequestTimeRangeNames.SSL,timing.sslStart,timing.sslEnd);addOffsetRange(Network.RequestTimeRangeNames.Sending,timing.sendStart,timing.sendEnd);addOffsetRange(Network.RequestTimeRangeNames.Waiting,Math.max(timing.sendEnd,timing.connectEnd,timing.dnsEnd,timing.proxyEnd,blockingEnd),responseReceived);}
if(request.endTime!==-1){addRange(timing.pushStart?Network.RequestTimeRangeNames.ReceivingPush:Network.RequestTimeRangeNames.Receiving,request.responseReceivedTime,endTime);}
return result;}
static createTimingTable(request,calculator){const tableElement=createElementWithClass('table','network-timing-table');UI.appendStyle(tableElement,'network/networkTimingTable.css');const colgroup=tableElement.createChild('colgroup');colgroup.createChild('col','labels');colgroup.createChild('col','bars');colgroup.createChild('col','duration');const timeRanges=Network.RequestTimingView.calculateRequestTimeRanges(request,calculator.minimumBoundary());const startTime=timeRanges.map(r=>r.start).reduce((a,b)=>Math.min(a,b));const endTime=timeRanges.map(r=>r.end).reduce((a,b)=>Math.max(a,b));const scale=100/(endTime-startTime);let connectionHeader;let dataHeader;let queueingHeader;let totalDuration=0;const startTimeHeader=tableElement.createChild('thead','network-timing-start');const queuedCell=startTimeHeader.createChild('tr').createChild('td');const startedCell=startTimeHeader.createChild('tr').createChild('td');queuedCell.colSpan=startedCell.colSpan=2;queuedCell.createTextChild(Common.UIString('Queued at %s',calculator.formatValue(request.issueTime(),2)));startedCell.createTextChild(Common.UIString('Started at %s',calculator.formatValue(request.startTime,2)));let right;for(let i=0;i<timeRanges.length;++i){const range=timeRanges[i];const rangeName=range.name;if(rangeName===Network.RequestTimeRangeNames.Total){totalDuration=range.end-range.start;continue;}
if(rangeName===Network.RequestTimeRangeNames.Push){createHeader(Common.UIString('Server Push'));}else if(rangeName===Network.RequestTimeRangeNames.Queueing){queueingHeader=tableElement.createChild('tr','network-timing-table-header');queueingHeader.createChild('td').createTextChild(Common.UIString('Resource Scheduling'));queueingHeader.createChild('td').createTextChild('');queueingHeader.createChild('td').createTextChild(Common.UIString('TIME'));}else if(Network.RequestTimingView.ConnectionSetupRangeNames.has(rangeName)){if(!connectionHeader)
connectionHeader=createHeader(Common.UIString('Connection Start'));}else{if(!dataHeader)
dataHeader=createHeader(Common.UIString('Request/Response'));}
const left=(scale*(range.start-startTime));right=(scale*(endTime-range.end));const duration=range.end-range.start;const tr=tableElement.createChild('tr');tr.createChild('td').createTextChild(Network.RequestTimingView._timeRangeTitle(rangeName));const row=tr.createChild('td').createChild('div','network-timing-row');const bar=row.createChild('span','network-timing-bar '+rangeName);bar.style.left=left+'%';bar.style.right=right+'%';bar.textContent='\u200B';const label=tr.createChild('td').createChild('div','network-timing-bar-title');label.textContent=Number.secondsToString(duration,true);}
if(!request.finished){const cell=tableElement.createChild('tr').createChild('td','caution');cell.colSpan=3;cell.createTextChild(Common.UIString('CAUTION: request is not finished yet!'));}
const footer=tableElement.createChild('tr','network-timing-footer');const note=footer.createChild('td');note.colSpan=1;note.appendChild(UI.createDocumentationLink('network-performance/reference#timing-explanation',Common.UIString('Explanation')));footer.createChild('td');footer.createChild('td').createTextChild(Number.secondsToString(totalDuration,true));const serverTimings=request.serverTimings;if(!serverTimings)
return tableElement;const lastTimingRightEdge=right===undefined?100:right;const breakElement=tableElement.createChild('tr','network-timing-table-header').createChild('td');breakElement.colSpan=3;breakElement.createChild('hr','break');const serverHeader=tableElement.createChild('tr','network-timing-table-header');serverHeader.createChild('td').createTextChild(Common.UIString('Server Timing'));serverHeader.createChild('td');serverHeader.createChild('td').createTextChild(Common.UIString('TIME'));serverTimings.filter(item=>item.metric.toLowerCase()!=='total').forEach(item=>addTiming(item,lastTimingRightEdge));serverTimings.filter(item=>item.metric.toLowerCase()==='total').forEach(item=>addTiming(item,lastTimingRightEdge));return tableElement;function addTiming(serverTiming,right){const colorGenerator=new Common.Color.Generator({min:0,max:360,count:36},{min:50,max:80},80);const isTotal=serverTiming.metric.toLowerCase()==='total';const tr=tableElement.createChild('tr',isTotal?'network-timing-footer':'');const metric=tr.createChild('td','network-timing-metric');metric.createTextChild(serverTiming.description||serverTiming.metric);const row=tr.createChild('td').createChild('div','network-timing-row');if(serverTiming.value===null)
return;const left=scale*(endTime-startTime-(serverTiming.value/1000));if(left>=0){const bar=row.createChild('span','network-timing-bar server-timing');bar.style.left=left+'%';bar.style.right=right+'%';bar.textContent='\u200B';if(!isTotal)
bar.style.backgroundColor=colorGenerator.colorForID(serverTiming.metric);}
const label=tr.createChild('td').createChild('div','network-timing-bar-title');label.textContent=Number.millisToString(serverTiming.value,true);}
function createHeader(title){const dataHeader=tableElement.createChild('tr','network-timing-table-header');dataHeader.createChild('td').createTextChild(title);dataHeader.createChild('td').createTextChild('');dataHeader.createChild('td').createTextChild(Common.UIString('TIME'));return dataHeader;}}
wasShown(){this._request.addEventListener(SDK.NetworkRequest.Events.TimingChanged,this._refresh,this);this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._refresh,this);this._calculator.addEventListener(Network.NetworkTimeCalculator.Events.BoundariesChanged,this._refresh,this);this._refresh();}
willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.TimingChanged,this._refresh,this);this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._refresh,this);this._calculator.removeEventListener(Network.NetworkTimeCalculator.Events.BoundariesChanged,this._refresh,this);}
_refresh(){if(this._tableElement)
this._tableElement.remove();this._tableElement=Network.RequestTimingView.createTimingTable(this._request,this._calculator);this._tableElement.classList.add('resource-timing-table');this.element.appendChild(this._tableElement);}};Network.RequestTimeRangeNames={Push:'push',Queueing:'queueing',Blocking:'blocking',Connecting:'connecting',DNS:'dns',Proxy:'proxy',Receiving:'receiving',ReceivingPush:'receiving-push',Sending:'sending',ServiceWorker:'serviceworker',ServiceWorkerPreparation:'serviceworker-preparation',SSL:'ssl',Total:'total',Waiting:'waiting'};Network.RequestTimingView.ConnectionSetupRangeNames=new Set([Network.RequestTimeRangeNames.Queueing,Network.RequestTimeRangeNames.Blocking,Network.RequestTimeRangeNames.Connecting,Network.RequestTimeRangeNames.DNS,Network.RequestTimeRangeNames.Proxy,Network.RequestTimeRangeNames.SSL]);Network.RequestTimeRange;;Network.ResourceWebSocketFrameView=class extends UI.VBox{constructor(request){super();this.registerRequiredCSS('network/webSocketFrameView.css');this.element.classList.add('websocket-frame-view');this._request=request;this._splitWidget=new UI.SplitWidget(false,true,'resourceWebSocketFrameSplitViewState');this._splitWidget.show(this.element);const columns=([{id:'data',title:Common.UIString('Data'),sortable:false,weight:88},{id:'length',title:Common.UIString('Length'),sortable:false,align:DataGrid.DataGrid.Align.Right,weight:5},{id:'time',title:Common.UIString('Time'),sortable:true,weight:7}]);this._dataGrid=new DataGrid.SortableDataGrid(columns);this._dataGrid.setRowContextMenuCallback(onRowContextMenu.bind(this));this._dataGrid.setStickToBottom(true);this._dataGrid.setStriped(true);this._timeComparator=(Network.ResourceWebSocketFrameNodeTimeComparator);this._dataGrid.sortNodes(this._timeComparator,false);this._dataGrid.markColumnAsSortedBy('time',DataGrid.DataGrid.Order.Ascending);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortItems,this);this._dataGrid.setName('ResourceWebSocketFrameView');this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._onFrameSelected,this);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.DeselectedNode,this._onFrameDeselected,this);this._mainToolbar=new UI.Toolbar('');this._clearAllButton=new UI.ToolbarButton(Common.UIString('Clear All'),'largeicon-clear');this._clearAllButton.addEventListener(UI.ToolbarButton.Events.Click,this._clearFrames,this);this._mainToolbar.appendToolbarItem(this._clearAllButton);this._filterTypeCombobox=new UI.ToolbarComboBox(this._updateFilterSetting.bind(this));for(const filterItem of Network.ResourceWebSocketFrameView._filterTypes){const option=this._filterTypeCombobox.createOption(filterItem.label,filterItem.label,filterItem.name);this._filterTypeCombobox.addOption(option);}
this._mainToolbar.appendToolbarItem(this._filterTypeCombobox);this._filterType=null;const placeholder='Enter regex, for example: (web)?socket';this._filterTextInput=new UI.ToolbarInput(Common.UIString(placeholder),0.4);this._filterTextInput.addEventListener(UI.ToolbarInput.Event.TextChanged,this._updateFilterSetting,this);this._mainToolbar.appendToolbarItem(this._filterTextInput);this._filterRegex=null;const mainContainer=new UI.VBox();mainContainer.element.appendChild(this._mainToolbar.element);this._dataGrid.asWidget().show(mainContainer.element);mainContainer.setMinimumSize(0,72);this._splitWidget.setMainWidget(mainContainer);this._frameEmptyWidget=new UI.EmptyWidget(Common.UIString('Select message to browse its content.'));this._splitWidget.setSidebarWidget(this._frameEmptyWidget);this._selectedNode=null;function onRowContextMenu(contextMenu,genericNode){const node=(genericNode);const binaryView=node.binaryView();if(binaryView){binaryView.addCopyToContextMenu(contextMenu,ls`Copy message...`);}else{contextMenu.clipboardSection().appendItem(Common.UIString('Copy message'),InspectorFrontendHost.copyText.bind(InspectorFrontendHost,node.data.data));}
contextMenu.footerSection().appendItem(Common.UIString('Clear all'),this._clearFrames.bind(this));}}
static opCodeDescription(opCode,mask){const localizedDescription=Network.ResourceWebSocketFrameView.opCodeDescriptions[opCode]||'';if(mask)
return ls`${localizedDescription} (Opcode ${opCode}, mask)`;return ls`${localizedDescription} (Opcode ${opCode})`;}
wasShown(){this.refresh();this._request.addEventListener(SDK.NetworkRequest.Events.WebsocketFrameAdded,this._frameAdded,this);}
willHide(){this._request.removeEventListener(SDK.NetworkRequest.Events.WebsocketFrameAdded,this._frameAdded,this);}
_frameAdded(event){const frame=(event.data);if(!this._frameFilter(frame))
return;this._dataGrid.insertChild(new Network.ResourceWebSocketFrameNode(this._request.url(),frame));}
_frameFilter(frame){if(this._filterType&&frame.type!==this._filterType)
return false;return!this._filterRegex||this._filterRegex.test(frame.text);}
_clearFrames(){this._request[Network.ResourceWebSocketFrameView._clearFrameOffsetSymbol]=this._request.frames().length;this.refresh();}
_updateFilterSetting(){const text=this._filterTextInput.value();const type=this._filterTypeCombobox.selectedOption().value;this._filterRegex=text?new RegExp(text,'i'):null;this._filterType=type==='all'?null:type;this.refresh();}
async _onFrameSelected(event){this._currentSelectedNode=(event.data);const content=this._currentSelectedNode.dataText();const binaryView=this._currentSelectedNode.binaryView();if(binaryView){this._splitWidget.setSidebarWidget(binaryView);return;}
const jsonView=await SourceFrame.JSONView.createView(content);if(jsonView){this._splitWidget.setSidebarWidget(jsonView);return;}
this._splitWidget.setSidebarWidget(new SourceFrame.ResourceSourceFrame(Common.StaticContentProvider.fromString(this._request.url(),Common.resourceTypes.WebSocket,content)));}
_onFrameDeselected(event){this._currentSelectedNode=null;this._splitWidget.setSidebarWidget(this._frameEmptyWidget);}
refresh(){this._dataGrid.rootNode().removeChildren();const url=this._request.url();let frames=this._request.frames();const offset=this._request[Network.ResourceWebSocketFrameView._clearFrameOffsetSymbol]||0;frames=frames.slice(offset);frames=frames.filter(this._frameFilter.bind(this));frames.forEach(frame=>this._dataGrid.insertChild(new Network.ResourceWebSocketFrameNode(url,frame)));}
_sortItems(){this._dataGrid.sortNodes(this._timeComparator,!this._dataGrid.isSortOrderAscending());}};Network.ResourceWebSocketFrameView.OpCodes={ContinuationFrame:0,TextFrame:1,BinaryFrame:2,ConnectionCloseFrame:8,PingFrame:9,PongFrame:10};Network.ResourceWebSocketFrameView.opCodeDescriptions=(function(){const opCodes=Network.ResourceWebSocketFrameView.OpCodes;const map=[];map[opCodes.ContinuationFrame]=ls`Continuation Frame`;map[opCodes.TextFrame]=ls`Text Message`;map[opCodes.BinaryFrame]=ls`Binary Message`;map[opCodes.ContinuationFrame]=ls`Connection Close Message`;map[opCodes.PingFrame]=ls`Ping Message`;map[opCodes.PongFrame]=ls`Pong Message`;return map;})();Network.ResourceWebSocketFrameView._filterTypes=[{name:'all',label:Common.UIString('All')},{name:'send',label:Common.UIString('Send')},{name:'receive',label:Common.UIString('Receive')},];Network.ResourceWebSocketFrameNode=class extends DataGrid.SortableDataGridNode{constructor(url,frame){let length=frame.text.length;const time=new Date(frame.time*1000);const timeText=('0'+time.getHours()).substr(-2)+':'+('0'+time.getMinutes()).substr(-2)+':'+
('0'+time.getSeconds()).substr(-2)+'.'+('00'+time.getMilliseconds()).substr(-3);const timeNode=createElement('div');timeNode.createTextChild(timeText);timeNode.title=time.toLocaleString();let dataText=frame.text;let description=Network.ResourceWebSocketFrameView.opCodeDescription(frame.opCode,frame.mask);const isTextFrame=frame.opCode===Network.ResourceWebSocketFrameView.OpCodes.TextFrame;if(frame.type===SDK.NetworkRequest.WebSocketFrameType.Error){description=dataText;length=ls`N/A`;}else if(isTextFrame){description=dataText;}else if(frame.opCode===Network.ResourceWebSocketFrameView.OpCodes.BinaryFrame){length=Number.bytesToString(base64ToSize(frame.text));description=Network.ResourceWebSocketFrameView.opCodeDescriptions[frame.opCode];}else{dataText=description;}
super({data:description,length:length,time:timeNode});this._url=url;this._frame=frame;this._isTextFrame=isTextFrame;this._dataText=dataText;}
createCells(element){element.classList.toggle('websocket-frame-view-row-error',this._frame.type===SDK.NetworkRequest.WebSocketFrameType.Error);element.classList.toggle('websocket-frame-view-row-send',this._frame.type===SDK.NetworkRequest.WebSocketFrameType.Send);element.classList.toggle('websocket-frame-view-row-receive',this._frame.type===SDK.NetworkRequest.WebSocketFrameType.Receive);super.createCells(element);}
nodeSelfHeight(){return 21;}
dataText(){return this._dataText;}
opCode(){return(this._frame.opCode);}
binaryView(){if(this._isTextFrame||this._frame.type===SDK.NetworkRequest.WebSocketFrameType.Error)
return null;if(!this._binaryView)
this._binaryView=new Network.BinaryResourceView(this._dataText,'',Common.resourceTypes.WebSocket);return this._binaryView;}};Network.ResourceWebSocketFrameNodeTimeComparator=function(a,b){return a._frame.time-b._frame.time;};Network.ResourceWebSocketFrameView._clearFrameOffsetSymbol=Symbol('ClearFrameOffset');;Network.SignedExchangeInfoView=class extends UI.VBox{constructor(request){super();const signedExchangeInfo=request.signedExchangeInfo();console.assert(signedExchangeInfo);this.registerRequiredCSS('network/signedExchangeInfoView.css');this.element.classList.add('signed-exchange-info-view');const root=new UI.TreeOutlineInShadow();root.registerRequiredCSS('network/signedExchangeInfoTree.css');root.element.classList.add('signed-exchange-info-tree');root.setFocusable(false);root.makeDense();root.expandTreeElementsWhenArrowing=true;this.element.appendChild(root.element);const errorFieldSetMap=new Map();if(signedExchangeInfo.errors&&signedExchangeInfo.errors.length){const errorMessagesCategory=new Network.SignedExchangeInfoView.Category(root,Common.UIString('Errors'));for(const error of signedExchangeInfo.errors){const fragment=createDocumentFragment();fragment.appendChild(UI.Icon.create('smallicon-error','prompt-icon'));fragment.createChild('div','error-log').textContent=error.message;errorMessagesCategory.createLeaf(fragment);if(error.errorField){let errorFieldSet=errorFieldSetMap.get(error.signatureIndex);if(!errorFieldSet){errorFieldSet=new Set();errorFieldSetMap.set(error.signatureIndex,errorFieldSet);}
errorFieldSet.add(error.errorField);}}}
const titleElement=createDocumentFragment();titleElement.createChild('div','header-name').textContent=Common.UIString('Signed HTTP exchange');const learnMoreNode=UI.XLink.create('https://github.com/WICG/webpackage',Common.UIString('Learn\xa0more'),'header-toggle');titleElement.appendChild(learnMoreNode);const headerCategory=new Network.SignedExchangeInfoView.Category(root,titleElement);if(signedExchangeInfo.header){const header=signedExchangeInfo.header;const redirectDestination=request.redirectDestination();const requestURLElement=this._formatHeader(Common.UIString('Request URL'),header.requestUrl);if(redirectDestination){const viewRequestLink=Components.Linkifier.linkifyRevealable(redirectDestination,'View request');viewRequestLink.classList.add('header-toggle');requestURLElement.appendChild(viewRequestLink);}
headerCategory.createLeaf(requestURLElement);headerCategory.createLeaf(this._formatHeader(Common.UIString('Response code'),header.responseCode+''));this._responseHeadersItem=headerCategory.createLeaf(this._formatHeader(Common.UIString('Response headers'),''));const responseHeaders=header.responseHeaders;for(const name in responseHeaders){const headerTreeElement=new UI.TreeElement(this._formatHeader(name,responseHeaders[name]));headerTreeElement.selectable=false;this._responseHeadersItem.appendChild(headerTreeElement);}
this._responseHeadersItem.expand();for(let i=0;i<header.signatures.length;++i){const errorFieldSet=errorFieldSetMap.get(i)||new Set();const signature=header.signatures[i];const signatureCategory=new Network.SignedExchangeInfoView.Category(root,Common.UIString('Signature'));signatureCategory.createLeaf(this._formatHeader(Common.UIString('Label'),signature.label));signatureCategory.createLeaf(this._formatHeaderForHexData(Common.UIString('Signature'),signature.signature,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureSig)));if(signature.certUrl){const certURLElement=this._formatHeader(Common.UIString('Certificate URL'),signature.certUrl,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureCertUrl));if(signature.certificates){const viewCertLink=certURLElement.createChild('span','devtools-link header-toggle');viewCertLink.textContent=Common.UIString('View certificate');viewCertLink.addEventListener('click',InspectorFrontendHost.showCertificateViewer.bind(null,signature.certificates),false);}
signatureCategory.createLeaf(certURLElement);}
signatureCategory.createLeaf(this._formatHeader(Common.UIString('Integrity'),signature.integrity,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureIntegrity)));if(signature.certSha256){signatureCategory.createLeaf(this._formatHeaderForHexData(Common.UIString('Certificate SHA256'),signature.certSha256,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureCertSha256)));}
signatureCategory.createLeaf(this._formatHeader(Common.UIString('Validity URL'),signature.validityUrl,errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureValidityUrl)));signatureCategory.createLeaf().title=this._formatHeader(Common.UIString('Date'),new Date(1000*signature.date).toUTCString(),errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureTimestamps));signatureCategory.createLeaf().title=this._formatHeader(Common.UIString('Expires'),new Date(1000*signature.expires).toUTCString(),errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureTimestamps));}}
if(signedExchangeInfo.securityDetails){const securityDetails=signedExchangeInfo.securityDetails;const securityCategory=new Network.SignedExchangeInfoView.Category(root,Common.UIString('Certificate'));securityCategory.createLeaf(this._formatHeader(Common.UIString('Subject'),securityDetails.subjectName));securityCategory.createLeaf(this._formatHeader(Common.UIString('Valid from'),new Date(1000*securityDetails.validFrom).toUTCString()));securityCategory.createLeaf(this._formatHeader(Common.UIString('Valid until'),new Date(1000*securityDetails.validTo).toUTCString()));securityCategory.createLeaf(this._formatHeader(Common.UIString('Issuer'),securityDetails.issuer));}}
_formatHeader(name,value,highlighted){const fragment=createDocumentFragment();const nameElement=fragment.createChild('div','header-name');nameElement.textContent=name+': ';fragment.createChild('span','header-separator');const valueElement=fragment.createChild('div','header-value source-code');valueElement.textContent=value;if(highlighted){nameElement.classList.add('error-field');valueElement.classList.add('error-field');}
return fragment;}
_formatHeaderForHexData(name,value,highlighted){const fragment=createDocumentFragment();const nameElement=fragment.createChild('div','header-name');nameElement.textContent=name+': ';fragment.createChild('span','header-separator');const valueElement=fragment.createChild('div','header-value source-code hex-data');valueElement.textContent=value.replace(/(.{2})/g,'$1 ');if(highlighted){nameElement.classList.add('error-field');valueElement.classList.add('error-field');}
return fragment;}};Network.SignedExchangeInfoView.Category=class extends UI.TreeElement{constructor(root,title){super(title,true);this.selectable=false;this.toggleOnClick=true;this.expanded=true;root.appendChild(this);}
createLeaf(title){const leaf=new UI.TreeElement(title);leaf.selectable=false;this.appendChild(leaf);return leaf;}};;Network.NetworkPanel=class extends UI.Panel{constructor(){super('network');this.registerRequiredCSS('network/networkPanel.css');this._networkLogShowOverviewSetting=Common.settings.createSetting('networkLogShowOverview',true);this._networkLogLargeRowsSetting=Common.settings.createSetting('networkLogLargeRows',false);this._networkRecordFilmStripSetting=Common.settings.createSetting('networkRecordFilmStripSetting',false);this._toggleRecordAction=(UI.actionRegistry.action('network.toggle-recording'));this._pendingStopTimer;this._networkItemView=null;this._filmStripView=null;this._filmStripRecorder=null;const panel=new UI.VBox();const networkToolbarContainer=panel.contentElement.createChild('div','network-toolbar-container');this._panelToolbar=new UI.Toolbar('',networkToolbarContainer);this._rightToolbar=new UI.Toolbar('',networkToolbarContainer);this._filterBar=new UI.FilterBar('networkPanel',true);this._filterBar.show(panel.contentElement);this._settingsPane=new UI.HBox();this._settingsPane.element.classList.add('network-settings-pane');this._settingsPane.show(panel.contentElement);this._showSettingsPaneSetting=Common.settings.createSetting('networkShowSettingsToolbar',false);this._showSettingsPaneSetting.addChangeListener(this._updateSettingsPaneVisibility.bind(this));this._updateSettingsPaneVisibility();this._filmStripPlaceholderElement=panel.contentElement.createChild('div','network-film-strip-placeholder');this._overviewPane=new PerfUI.TimelineOverviewPane('network');this._overviewPane.addEventListener(PerfUI.TimelineOverviewPane.Events.WindowChanged,this._onWindowChanged.bind(this));this._overviewPane.element.id='network-overview-panel';this._networkOverview=new Network.NetworkOverview();this._overviewPane.setOverviewControls([this._networkOverview]);this._overviewPlaceholderElement=panel.contentElement.createChild('div');this._calculator=new Network.NetworkTransferTimeCalculator();this._splitWidget=new UI.SplitWidget(true,false,'networkPanelSplitViewState');this._splitWidget.hideMain();this._splitWidget.show(panel.contentElement);panel.setDefaultFocusedChild(this._filterBar);const initialSidebarWidth=225;const splitWidget=new UI.SplitWidget(true,false,'networkPanelSidebarState',initialSidebarWidth);splitWidget.hideSidebar();splitWidget.enableShowModeSaving();splitWidget.show(this.element);this._sidebarLocation=UI.viewManager.createTabbedLocation(async()=>{UI.viewManager.showView('network');splitWidget.showBoth();},'network-sidebar',true);const tabbedPane=this._sidebarLocation.tabbedPane();tabbedPane.setMinimumSize(100,25);tabbedPane.element.classList.add('network-tabbed-pane');tabbedPane.element.addEventListener('keydown',event=>{if(event.key!=='Escape')
return;splitWidget.hideSidebar();event.consume();});const closeSidebar=new UI.ToolbarButton(Common.UIString('Close'),'largeicon-delete');closeSidebar.addEventListener(UI.ToolbarButton.Events.Click,()=>splitWidget.hideSidebar());tabbedPane.rightToolbar().appendToolbarItem(closeSidebar);splitWidget.setSidebarWidget(tabbedPane);splitWidget.setMainWidget(panel);splitWidget.setDefaultFocusedChild(panel);this.setDefaultFocusedChild(splitWidget);this._progressBarContainer=createElement('div');this._networkLogView=new Network.NetworkLogView(this._filterBar,this._progressBarContainer,this._networkLogLargeRowsSetting);this._splitWidget.setSidebarWidget(this._networkLogView);this._fileSelectorElement=UI.createFileSelectorElement(this._networkLogView.onLoadFromFile.bind(this._networkLogView));panel.element.appendChild(this._fileSelectorElement);this._detailsWidget=new UI.VBox();this._detailsWidget.element.classList.add('network-details-view');this._splitWidget.setMainWidget(this._detailsWidget);this._closeButtonElement=createElement('div','dt-close-button');this._closeButtonElement.addEventListener('click',this._showRequest.bind(this,null),false);this._closeButtonElement.style.margin='0 5px';this._networkLogShowOverviewSetting.addChangeListener(this._toggleShowOverview,this);this._networkLogLargeRowsSetting.addChangeListener(this._toggleLargerRequests,this);this._networkRecordFilmStripSetting.addChangeListener(this._toggleRecordFilmStrip,this);this._preserveLogSetting=Common.moduleSetting('network_log.preserve-log');this._throttlingSelect=this._createThrottlingConditionsSelect();this._setupToolbarButtons(splitWidget);this._toggleRecord(true);this._toggleShowOverview();this._toggleLargerRequests();this._toggleRecordFilmStrip();this._updateUI();SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.WillReloadPage,this._willReloadPage,this);SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._load,this);this._networkLogView.addEventListener(Network.NetworkLogView.Events.RequestSelected,this._onRequestSelected,this);SDK.networkLog.addEventListener(SDK.NetworkLog.Events.RequestAdded,this._onUpdateRequest,this);SDK.networkLog.addEventListener(SDK.NetworkLog.Events.RequestUpdated,this._onUpdateRequest,this);SDK.networkLog.addEventListener(SDK.NetworkLog.Events.Reset,this._onNetworkLogReset,this);}
static revealAndFilter(filters){const panel=Network.NetworkPanel._instance();let filterString='';for(const filter of filters)
filterString+=`${filter.filterType}:${filter.filterValue} `;panel._networkLogView.setTextFilterValue(filterString);UI.viewManager.showView('network');}
static _instance(){return(self.runtime.sharedInstance(Network.NetworkPanel));}
throttlingSelectForTest(){return this._throttlingSelect;}
_onWindowChanged(event){const startTime=Math.max(this._calculator.minimumBoundary(),event.data.startTime/1000);const endTime=Math.min(this._calculator.maximumBoundary(),event.data.endTime/1000);this._networkLogView.setWindow(startTime,endTime);}
_setupToolbarButtons(splitWidget){const searchToggle=new UI.ToolbarToggle('Search','largeicon-search');function updateSidebarToggle(){searchToggle.setToggled(splitWidget.showMode()!==UI.SplitWidget.ShowMode.OnlyMain);}
this._panelToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._toggleRecordAction));const clearButton=new UI.ToolbarButton(Common.UIString('Clear'),'largeicon-clear');clearButton.addEventListener(UI.ToolbarButton.Events.Click,()=>SDK.networkLog.reset(),this);this._panelToolbar.appendToolbarItem(clearButton);this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._filterBar.filterButton());updateSidebarToggle();splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged,updateSidebarToggle);searchToggle.addEventListener(UI.ToolbarButton.Events.Click,()=>{if(splitWidget.showMode()===UI.SplitWidget.ShowMode.OnlyMain)
splitWidget.showBoth();else
splitWidget.hideSidebar();});this._panelToolbar.appendToolbarItem(searchToggle);this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._preserveLogSetting,Common.UIString('Do not clear log on page reload / navigation'),Common.UIString('Preserve log')));const disableCacheCheckbox=new UI.ToolbarSettingCheckbox(Common.moduleSetting('cacheDisabled'),Common.UIString('Disable cache (while DevTools is open)'),Common.UIString('Disable cache'));this._panelToolbar.appendToolbarItem(disableCacheCheckbox);this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._throttlingSelect);this._rightToolbar.appendToolbarItem(new UI.ToolbarItem(this._progressBarContainer));this._rightToolbar.appendSeparator();this._rightToolbar.appendToolbarItem(new UI.ToolbarSettingToggle(this._showSettingsPaneSetting,'largeicon-settings-gear',ls`Network settings`));const settingsToolbarLeft=new UI.Toolbar('',this._settingsPane.element);settingsToolbarLeft.makeVertical();settingsToolbarLeft.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._networkLogLargeRowsSetting,'',ls`Use large request rows`));settingsToolbarLeft.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._networkLogShowOverviewSetting,'',ls`Show overview`));const settingsToolbarRight=new UI.Toolbar('',this._settingsPane.element);settingsToolbarRight.makeVertical();settingsToolbarRight.appendToolbarItem(new UI.ToolbarSettingCheckbox(Common.moduleSetting('network.group-by-frame'),'',ls`Group by frame`));settingsToolbarRight.appendToolbarItem(new UI.ToolbarSettingCheckbox(this._networkRecordFilmStripSetting,'',ls`Capture screenshots`));this._panelToolbar.appendSeparator();const importHarButton=new UI.ToolbarButton(ls`Import HAR file...`,'largeicon-load');importHarButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._fileSelectorElement.click(),this);this._panelToolbar.appendToolbarItem(importHarButton);const exportHarButton=new UI.ToolbarButton(ls`Export HAR...`,'largeicon-download');exportHarButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._networkLogView.exportAll(),this);this._panelToolbar.appendToolbarItem(exportHarButton);}
_updateSettingsPaneVisibility(){this._settingsPane.element.classList.toggle('hidden',!this._showSettingsPaneSetting.get());}
_createThrottlingConditionsSelect(){const toolbarItem=new UI.ToolbarComboBox(null);toolbarItem.setTitle(ls`Throttling`);toolbarItem.setMaxWidth(160);MobileThrottling.throttlingManager().decorateSelectWithNetworkThrottling(toolbarItem.selectElement());return toolbarItem;}
_toggleRecording(){if(!this._preserveLogSetting.get()&&!this._toggleRecordAction.toggled())
SDK.networkLog.reset();this._toggleRecord(!this._toggleRecordAction.toggled());}
_toggleRecord(toggled){this._toggleRecordAction.setToggled(toggled);this._networkLogView.setRecording(toggled);if(!toggled&&this._filmStripRecorder)
this._filmStripRecorder.stopRecording(this._filmStripAvailable.bind(this));SDK.networkLog.setIsRecording(toggled);}
_filmStripAvailable(filmStripModel){if(!filmStripModel)
return;const calculator=this._networkLogView.timeCalculator();this._filmStripView.setModel(filmStripModel,calculator.minimumBoundary()*1000,calculator.boundarySpan()*1000);this._networkOverview.setFilmStripModel(filmStripModel);const timestamps=filmStripModel.frames().map(mapTimestamp);function mapTimestamp(frame){return frame.timestamp/1000;}
this._networkLogView.addFilmStripFrames(timestamps);}
_onNetworkLogReset(){Network.BlockedURLsPane.reset();if(!this._preserveLogSetting.get()){this._calculator.reset();this._overviewPane.reset();}
if(this._filmStripView)
this._resetFilmStripView();}
_willReloadPage(event){this._toggleRecord(true);if(this._pendingStopTimer){clearTimeout(this._pendingStopTimer);delete this._pendingStopTimer;}
if(this.isShowing()&&this._filmStripRecorder)
this._filmStripRecorder.startRecording();}
_load(event){if(this._filmStripRecorder&&this._filmStripRecorder.isRecording()){this._pendingStopTimer=setTimeout(this._stopFilmStripRecording.bind(this),Network.NetworkPanel.displayScreenshotDelay);}}
_stopFilmStripRecording(){this._filmStripRecorder.stopRecording(this._filmStripAvailable.bind(this));delete this._pendingStopTimer;}
_toggleLargerRequests(){this._updateUI();}
_toggleShowOverview(){const toggled=this._networkLogShowOverviewSetting.get();if(toggled)
this._overviewPane.show(this._overviewPlaceholderElement);else
this._overviewPane.detach();this.doResize();}
_toggleRecordFilmStrip(){const toggled=this._networkRecordFilmStripSetting.get();if(toggled&&!this._filmStripRecorder){this._filmStripView=new PerfUI.FilmStripView();this._filmStripView.setMode(PerfUI.FilmStripView.Modes.FrameBased);this._filmStripView.element.classList.add('network-film-strip');this._filmStripRecorder=new Network.NetworkPanel.FilmStripRecorder(this._networkLogView.timeCalculator(),this._filmStripView);this._filmStripView.show(this._filmStripPlaceholderElement);this._filmStripView.addEventListener(PerfUI.FilmStripView.Events.FrameSelected,this._onFilmFrameSelected,this);this._filmStripView.addEventListener(PerfUI.FilmStripView.Events.FrameEnter,this._onFilmFrameEnter,this);this._filmStripView.addEventListener(PerfUI.FilmStripView.Events.FrameExit,this._onFilmFrameExit,this);this._resetFilmStripView();}
if(!toggled&&this._filmStripRecorder){this._filmStripView.detach();this._filmStripView=null;this._filmStripRecorder=null;}}
_resetFilmStripView(){const reloadShortcutDescriptor=UI.shortcutRegistry.shortcutDescriptorsForAction('inspector_main.reload')[0];this._filmStripView.reset();if(reloadShortcutDescriptor){this._filmStripView.setStatusText(Common.UIString('Hit %s to reload and capture filmstrip.',reloadShortcutDescriptor.name));}}
elementsToRestoreScrollPositionsFor(){return this._networkLogView.elementsToRestoreScrollPositionsFor();}
wasShown(){UI.context.setFlavor(Network.NetworkPanel,this);Host.userMetrics.panelLoaded('network','DevTools.Launch.Network');}
willHide(){UI.context.setFlavor(Network.NetworkPanel,null);}
revealAndHighlightRequest(request){this._showRequest(null);if(request)
this._networkLogView.revealAndHighlightRequest(request);}
async selectRequest(request){await UI.viewManager.showView('network');this._networkLogView.selectRequest(request);return this._networkItemView;}
_onRowSizeChanged(event){this._updateUI();}
_onRequestSelected(event){const request=(event.data);this._showRequest(request);}
_showRequest(request){if(this._networkItemView){this._networkItemView.detach();this._networkItemView=null;}
if(request){this._networkItemView=new Network.NetworkItemView(request,this._networkLogView.timeCalculator());this._networkItemView.leftToolbar().appendToolbarItem(new UI.ToolbarItem(this._closeButtonElement));this._networkItemView.show(this._detailsWidget.element);this._splitWidget.showBoth();}else{this._splitWidget.hideMain();this._networkLogView.clearSelection();}
this._updateUI();}
_updateUI(){this._detailsWidget.element.classList.toggle('network-details-view-tall-header',this._networkLogLargeRowsSetting.get());this._networkLogView.switchViewMode(!this._splitWidget.isResizable());}
appendApplicableItems(event,contextMenu,target){function reveal(request){UI.viewManager.showView('network').then(this.revealAndHighlightRequest.bind(this,request));}
function appendRevealItem(request){contextMenu.revealSection().appendItem(Common.UIString('Reveal in Network panel'),reveal.bind(this,request));}
if(event.target.isSelfOrDescendant(this.element))
return;if(target instanceof SDK.Resource){const resource=(target);if(resource.request)
appendRevealItem.call(this,resource.request);return;}
if(target instanceof Workspace.UISourceCode){const uiSourceCode=(target);const resource=Bindings.resourceForURL(uiSourceCode.url());if(resource&&resource.request)
appendRevealItem.call(this,resource.request);return;}
if(!(target instanceof SDK.NetworkRequest))
return;const request=(target);if(this._networkItemView&&this._networkItemView.isShowing()&&this._networkItemView.request()===request)
return;appendRevealItem.call(this,request);}
_onFilmFrameSelected(event){const timestamp=(event.data);this._overviewPane.setWindowTimes(0,timestamp);}
_onFilmFrameEnter(event){const timestamp=(event.data);this._networkOverview.selectFilmStripFrame(timestamp);this._networkLogView.selectFilmStripFrame(timestamp/1000);}
_onFilmFrameExit(event){this._networkOverview.clearFilmStripFrame();this._networkLogView.clearFilmStripFrame();}
_onUpdateRequest(event){const request=(event.data);this._calculator.updateBoundaries(request);this._overviewPane.setBounds(this._calculator.minimumBoundary()*1000,this._calculator.maximumBoundary()*1000);this._networkOverview.updateRequest(request);this._overviewPane.scheduleUpdate();}
resolveLocation(locationName){if(locationName==='network-sidebar')
return this._sidebarLocation;return null;}};Network.NetworkPanel.displayScreenshotDelay=1000;Network.NetworkPanel.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){Network.NetworkPanel._instance().appendApplicableItems(event,contextMenu,target);}};Network.NetworkPanel.RequestRevealer=class{reveal(request){if(!(request instanceof SDK.NetworkRequest))
return Promise.reject(new Error('Internal error: not a network request'));const panel=Network.NetworkPanel._instance();return UI.viewManager.showView('network').then(panel.revealAndHighlightRequest.bind(panel,request));}};Network.NetworkPanel.FilmStripRecorder=class{constructor(timeCalculator,filmStripView){this._tracingManager=null;this._resourceTreeModel=null;this._timeCalculator=timeCalculator;this._filmStripView=filmStripView;this._tracingModel=null;this._callback=null;}
traceEventsCollected(events){if(this._tracingModel)
this._tracingModel.addEvents(events);}
tracingComplete(){if(!this._tracingModel||!this._tracingManager)
return;this._tracingModel.tracingComplete();this._tracingManager=null;this._callback(new SDK.FilmStripModel(this._tracingModel,this._timeCalculator.minimumBoundary()*1000));this._callback=null;if(this._resourceTreeModel)
this._resourceTreeModel.resumeReload();this._resourceTreeModel=null;}
tracingBufferUsage(){}
eventsRetrievalProgress(progress){}
startRecording(){this._filmStripView.reset();this._filmStripView.setStatusText(Common.UIString('Recording frames...'));const tracingManagers=SDK.targetManager.models(SDK.TracingManager);if(this._tracingManager||!tracingManagers.length)
return;this._tracingManager=tracingManagers[0];this._resourceTreeModel=this._tracingManager.target().model(SDK.ResourceTreeModel);if(this._tracingModel)
this._tracingModel.dispose();this._tracingModel=new SDK.TracingModel(new Bindings.TempFileBackingStorage());this._tracingManager.start(this,'-*,disabled-by-default-devtools.screenshot','');Host.userMetrics.actionTaken(Host.UserMetrics.Action.FilmStripStartedRecording);}
isRecording(){return!!this._tracingManager;}
stopRecording(callback){if(!this._tracingManager)
return;this._tracingManager.stop();if(this._resourceTreeModel)
this._resourceTreeModel.suspendReload();this._callback=callback;this._filmStripView.setStatusText(Common.UIString('Fetching frames...'));}};Network.NetworkPanel.ActionDelegate=class{handleAction(context,actionId){const panel=UI.context.flavor(Network.NetworkPanel);console.assert(panel&&panel instanceof Network.NetworkPanel);switch(actionId){case'network.toggle-recording':panel._toggleRecording();return true;case'network.hide-request-details':if(!panel._networkItemView)
return false;panel._showRequest(null);return true;case'network.search':const selection=UI.inspectorView.element.window().getSelection();let queryCandidate='';if(selection.rangeCount)
queryCandidate=selection.toString().replace(/\r?\n.*/,'');Network.SearchNetworkView.openSearch(queryCandidate);return true;}
return false;}};Network.NetworkPanel.RequestLocationRevealer=class{async reveal(match){const location=(match);const view=await Network.NetworkPanel._instance().selectRequest(location.request);if(!view)
return;if(location.searchMatch)
await view.revealResponseBody(location.searchMatch.lineNumber);if(location.requestHeader)
view.revealRequestHeader(location.requestHeader.name);if(location.responseHeader)
view.revealResponseHeader(location.responseHeader.name);}};Network.SearchNetworkView=class extends Search.SearchView{constructor(){super('network');}
static async openSearch(query,searchImmediately){await UI.viewManager.showView('network.search-network-tab');const searchView=(self.runtime.sharedInstance(Network.SearchNetworkView));searchView.toggle(query,!!searchImmediately);return searchView;}
createScope(){return new Network.NetworkSearchScope();}};;Runtime.cachedResources["network/binaryResourceView.css"]="/*\n * Copyright 2019 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.panel.network .toolbar.binary-view-toolbar {\n border-top: 1px solid #ccc;\n border-bottom: 0px;\n padding-left: 5px;\n}\n\n.binary-view-copied-text {\n opacity: 1;\n}\n\n.binary-view-copied-text.fadeout {\n opacity: 0;\n transition: opacity 1s;\n}\n\n/*# sourceURL=network/binaryResourceView.css */";Runtime.cachedResources["network/blockedURLsPane.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.list {\n border: none !important;\n border-top: var(--divider-border) !important;\n}\n\n.blocking-disabled {\n pointer-events: none;\n opacity: 0.8;\n}\n\n.editor-container {\n padding: 0 4px;\n}\n\n.no-blocked-urls, .blocked-urls {\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n.no-blocked-urls {\n display: flex;\n justify-content: center;\n padding: 10px;\n}\n\n.no-blocked-urls > span {\n white-space: pre;\n}\n\n.blocked-url {\n display: flex;\n flex-direction: row;\n align-items: center;\n flex: auto;\n}\n\n.blocked-url-count {\n flex: none;\n padding-right: 9px;\n}\n\n.blocked-url-checkbox {\n margin-left: 8px;\n flex: none;\n}\n\n.blocked-url-label {\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n flex: auto;\n padding: 0 3px;\n}\n\n.blocked-url-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 7px 5px 0 5px;\n align-items: center;\n}\n\n.blocked-url-edit-value {\n -webkit-user-select: none;\n flex: 1 1 0px;\n}\n\n.blocked-url-edit-row input {\n width: 100%;\n text-align: inherit;\n height: 22px;\n}\n\n/*# sourceURL=network/blockedURLsPane.css */";Runtime.cachedResources["network/eventSourceMessagesView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.event-source-messages-view .data-grid {\n flex: auto;\n border: none;\n}\n\n/*# sourceURL=network/eventSourceMessagesView.css */";Runtime.cachedResources["network/networkConfigView.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.network-config {\n padding: 12px;\n display: block;\n}\n\n.network-config-group {\n display: flex;\n margin-bottom: 10px;\n flex-wrap: wrap;\n flex: 0 0 auto;\n min-height: 30px;\n}\n\n.network-config-title {\n margin-right: 16px;\n width: 130px;\n}\n\n.network-config-fields {\n flex: 2 0 200px;\n}\n\n.panel-section-separator {\n height: 1px;\n margin-bottom: 10px;\n background: #f0f0f0;\n}\n\n/* Disable cache */\n\n.network-config-disable-cache {\n line-height: 28px;\n border-top: none;\n padding-top: 0;\n}\n\n/* Network throttling */\n\n.network-config-throttling .chrome-select {\n width: 100%;\n max-width: 250px;\n}\n\n.network-config-throttling > .network-config-title {\n line-height: 24px;\n}\n\n/* User agent */\n\n.network-config-ua > .network-config-title {\n line-height: 20px;\n}\n\n.network-config-ua span[is=\"dt-radio\"].checked > * {\n display: none\n}\n\n.network-config-ua input {\n display: block;\n width: calc(100% - 20px);\n}\n\n.network-config-ua input[readonly] {\n background-color: rgb(235, 235, 228);\n}\n\n.network-config-ua input[type=text], .network-config-ua .chrome-select {\n margin-top: 8px;\n}\n\n.network-config-ua .chrome-select {\n width: calc(100% - 20px);\n max-width: 250px;\n}\n\n.network-config-ua span[is=\"dt-radio\"] {\n display: block;\n}\n\n.network-config-ua-custo
this._header=this._renderJSONMLTag(headerJSON);if(this._header.nodeType===Node.TEXT_NODE){Common.console.error('Broken formatter: header should be an element node.');return;}
if(customPreview.hasBody||customPreview.bodyGetterId){this._header.classList.add('custom-expandable-section-header');this._header.addEventListener('click',this._onClick.bind(this),false);this._expandIcon=UI.Icon.create('smallicon-triangle-right','custom-expand-icon');this._header.insertBefore(this._expandIcon,this._header.firstChild);}
this._sectionElement.appendChild(this._header);}
element(){return this._sectionElement;}
_renderJSONMLTag(jsonML){if(!Array.isArray(jsonML))
return createTextNode(jsonML+'');const array=(jsonML);return array[0]==='object'?this._layoutObjectTag(array):this._renderElement(array);}
_renderElement(object){const tagName=object.shift();if(!ObjectUI.CustomPreviewSection._tagsWhiteList.has(tagName)){Common.console.error('Broken formatter: element '+tagName+' is not allowed!');return createElement('span');}
const element=createElement((tagName));if((typeof object[0]==='object')&&!Array.isArray(object[0])){const attributes=object.shift();for(const key in attributes){const value=attributes[key];if((key!=='style')||(typeof value!=='string'))
continue;element.setAttribute(key,value);}}
this._appendJsonMLTags(element,object);return element;}
_layoutObjectTag(objectTag){objectTag.shift();const attributes=objectTag.shift();const remoteObject=this._object.runtimeModel().createRemoteObject((attributes));if(remoteObject.customPreview())
return(new ObjectUI.CustomPreviewSection(remoteObject)).element();const sectionElement=ObjectUI.ObjectPropertiesSection.defaultObjectPresentation(remoteObject);sectionElement.classList.toggle('custom-expandable-section-standard-section',remoteObject.hasChildren);return sectionElement;}
_appendJsonMLTags(parentElement,jsonMLTags){for(let i=0;i<jsonMLTags.length;++i)
parentElement.appendChild(this._renderJSONMLTag(jsonMLTags[i]));}
_onClick(event){event.consume(true);if(this._cachedContent)
this._toggleExpand();else
this._loadBody();}
_toggleExpand(){this._expanded=!this._expanded;this._header.classList.toggle('expanded',this._expanded);this._cachedContent.classList.toggle('hidden',!this._expanded);if(this._expanded)
this._expandIcon.setIconType('smallicon-triangle-down');else
this._expandIcon.setIconType('smallicon-triangle-right');}
_loadBody(){function load(bindRemoteObject,formatter,config){function substituteObjectTagsInCustomPreview(jsonMLObject){if(!jsonMLObject||(typeof jsonMLObject!=='object')||(typeof jsonMLObject.splice!=='function'))
return;const obj=jsonMLObject.length;if(!(typeof obj==='number'&&obj>>>0===obj&&(obj>0||1/obj>0)))
return;let startIndex=1;if(jsonMLObject[0]==='object'){const attributes=jsonMLObject[1];const originObject=attributes['object'];const config=attributes['config'];if(typeof originObject==='undefined')
throw'Illegal format: obligatory attribute "object" isn\'t specified';jsonMLObject[1]=bindRemoteObject(originObject,config);startIndex=2;}
for(let i=startIndex;i<jsonMLObject.length;++i)
substituteObjectTagsInCustomPreview(jsonMLObject[i]);}
try{const body=formatter.body(this,config);substituteObjectTagsInCustomPreview(body);return body;}catch(e){console.error('Custom Formatter Failed: '+e);return null;}}
const customPreview=this._object.customPreview();if(customPreview.bindRemoteObjectFunctionId&&customPreview.formatterObjectId){const args=[{objectId:customPreview.bindRemoteObjectFunctionId},{objectId:customPreview.formatterObjectId}];if(customPreview.configObjectId)
args.push({objectId:customPreview.configObjectId});this._object.callFunctionJSON(load,args).then(onBodyLoaded.bind(this));}else if(customPreview.bodyGetterId){this._object.callFunctionJSON(bodyGetter=>bodyGetter(),[{objectId:customPreview.bodyGetterId}]).then(onBodyLoaded.bind(this));}
function onBodyLoaded(bodyJsonML){if(!bodyJsonML)
return;this._cachedContent=this._renderJSONMLTag(bodyJsonML);this._sectionElement.appendChild(this._cachedContent);this._toggleExpand();}}};ObjectUI.CustomPreviewComponent=class{constructor(object){this._object=object;this._customPreviewSection=new ObjectUI.CustomPreviewSection(object);this.element=createElementWithClass('span','source-code');const shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'object_ui/customPreviewComponent.css');this.element.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),false);shadowRoot.appendChild(this._customPreviewSection.element());}
expandIfPossible(){if((this._object.customPreview().hasBody||this._object.customPreview().bodyGetterId)&&this._customPreviewSection)
this._customPreviewSection._loadBody();}
_contextMenuEventFired(event){const contextMenu=new UI.ContextMenu(event);if(this._customPreviewSection){contextMenu.revealSection().appendItem(Common.UIString('Show as JavaScript object'),this._disassemble.bind(this));}
contextMenu.appendApplicableItems(this._object);contextMenu.show();}
_disassemble(){this.element.shadowRoot.textContent='';this._customPreviewSection=null;this.element.shadowRoot.appendChild(ObjectUI.ObjectPropertiesSection.defaultObjectPresentation(this._object));}};ObjectUI.CustomPreviewSection._tagsWhiteList=new Set(['span','div','ol','li','table','tr','td']);;ObjectUI.ObjectPopoverHelper=class{constructor(linkifier,resultHighlightedAsDOM){this._linkifier=linkifier;this._resultHighlightedAsDOM=resultHighlightedAsDOM;}
dispose(){if(this._resultHighlightedAsDOM)
SDK.OverlayModel.hideDOMNodeHighlight();if(this._linkifier)
this._linkifier.dispose();}
static async buildObjectPopover(result,popover){const description=result.description.trimEnd(ObjectUI.ObjectPopoverHelper.MaxPopoverTextLength);let popoverContentElement=null;if(result.type==='object'){let linkifier=null;let resultHighlightedAsDOM=false;if(result.subtype==='node'){SDK.OverlayModel.highlightObjectAsDOMNode(result);resultHighlightedAsDOM=true;}
if(result.customPreview()){const customPreviewComponent=new ObjectUI.CustomPreviewComponent(result);customPreviewComponent.expandIfPossible();popoverContentElement=customPreviewComponent.element;}else{popoverContentElement=createElementWithClass('div','object-popover-content');UI.appendStyle(popoverContentElement,'object_ui/objectPopover.css');const titleElement=popoverContentElement.createChild('div','monospace object-popover-title');titleElement.createChild('span').textContent=description;linkifier=new Components.Linkifier();const section=new ObjectUI.ObjectPropertiesSection(result,'',linkifier,undefined,undefined,undefined,true);section.element.classList.add('object-popover-tree');section.titleLessMode();popoverContentElement.appendChild(section.element);}
popover.setMaxContentSize(new UI.Size(300,250));popover.setSizeBehavior(UI.GlassPane.SizeBehavior.SetExactSize);popover.contentElement.appendChild(popoverContentElement);return new ObjectUI.ObjectPopoverHelper(linkifier,resultHighlightedAsDOM);}
popoverContentElement=createElement('span');UI.appendStyle(popoverContentElement,'object_ui/objectValue.css');UI.appendStyle(popoverContentElement,'object_ui/objectPopover.css');const valueElement=popoverContentElement.createChild('span','monospace object-value-'+result.type);valueElement.style.whiteSpace='pre';if(result.type==='string')
valueElement.createTextChildren(`"${description}"`);else if(result.type!=='function')
valueElement.textContent=description;if(result.type!=='function'){popover.contentElement.appendChild(popoverContentElement);return new ObjectUI.ObjectPopoverHelper(null,false);}
ObjectUI.ObjectPropertiesSection.formatObjectAsFunction(result,valueElement,true);const response=await result.debuggerModel().functionDetailsPromise(result);if(!response)
return null;const container=createElementWithClass('div','object-popover-container');const title=container.createChild('div','function-popover-title source-code');const functionName=title.createChild('span','function-name');functionName.textContent=UI.beautifyFunctionName(response.functionName);const rawLocation=response.location;const linkContainer=title.createChild('div','function-title-link-container');const sourceURL=rawLocation&&rawLocation.script()&&rawLocation.script().sourceURL;let linkifier=null;if(sourceURL){linkifier=new Components.Linkifier();linkContainer.appendChild(linkifier.linkifyRawLocation(rawLocation,sourceURL));}
container.appendChild(popoverContentElement);popover.contentElement.appendChild(container);return new ObjectUI.ObjectPopoverHelper(linkifier,false);}};ObjectUI.ObjectPopoverHelper.MaxPopoverTextLength=10000;;ObjectUI.ObjectPropertiesSection=class extends UI.TreeOutlineInShadow{constructor(object,title,linkifier,emptyPlaceholder,ignoreHasOwnProperty,extraProperties,showOverflow){super();this._object=object;this._editable=true;if(!showOverflow)
this.hideOverflow();this.setFocusable(true);this.setShowSelectionOnKeyboardFocus(true);this._objectTreeElement=new ObjectUI.ObjectPropertiesSection.RootElement(object,linkifier,emptyPlaceholder,ignoreHasOwnProperty,extraProperties);this.appendChild(this._objectTreeElement);if(typeof title==='string'||!title){this.titleElement=this.element.createChild('span');this.titleElement.textContent=title||'';}else{this.titleElement=title;this.element.appendChild(title);}
if(!this.titleElement.hasAttribute('tabIndex'))
this.titleElement.tabIndex=-1;this.element._section=this;this.registerRequiredCSS('object_ui/objectValue.css');this.registerRequiredCSS('object_ui/objectPropertiesSection.css');this.rootElement().childrenListElement.classList.add('source-code','object-properties-section');}
static defaultObjectPresentation(object,linkifier,skipProto,readOnly){const componentRoot=createElementWithClass('span','source-code');const shadowRoot=UI.createShadowRootWithCoreStyles(componentRoot,'object_ui/objectValue.css');shadowRoot.appendChild(ObjectUI.ObjectPropertiesSection.createValueElement(object,false,true));if(!object.hasChildren)
return componentRoot;const objectPropertiesSection=new ObjectUI.ObjectPropertiesSection(object,componentRoot,linkifier);objectPropertiesSection.editable=false;if(skipProto)
objectPropertiesSection.skipProto();if(readOnly)
objectPropertiesSection.setEditable(false);return objectPropertiesSection.element;}
static CompareProperties(propertyA,propertyB){const a=propertyA.name;const b=propertyB.name;if(a==='__proto__')
return 1;if(b==='__proto__')
return-1;if(!propertyA.enumerable&&propertyB.enumerable)
return 1;if(!propertyB.enumerable&&propertyA.enumerable)
return-1;if(a.startsWith('_')&&!b.startsWith('_'))
return 1;if(b.startsWith('_')&&!a.startsWith('_'))
return-1;if(propertyA.symbol&&!propertyB.symbol)
return 1;if(propertyB.symbol&&!propertyA.symbol)
return-1;return String.naturalOrderComparator(a,b);}
static createNameElement(name){const nameElement=createElementWithClass('span','name');if(/^\s|\s$|^$|\n/.test(name))
nameElement.createTextChildren('"',name.replace(/\n/g,'\u21B5'),'"');else
nameElement.textContent=name;return nameElement;}
static valueElementForFunctionDescription(description,includePreview,defaultName){const valueElement=createElementWithClass('span','object-value-function');description=description||'';const text=description.replace(/^function [gs]et /,'function ').replace(/^function [gs]et\(/,'function\(').replace(/^[gs]et /,'');defaultName=defaultName||'';const asyncMatch=text.match(/^(async\s+function)/);const isGenerator=text.startsWith('function*');const isGeneratorShorthand=text.startsWith('*');const isBasic=!isGenerator&&text.startsWith('function');const isClass=text.startsWith('class ')||text.startsWith('class{');const firstArrowIndex=text.indexOf('=>');const isArrow=!asyncMatch&&!isGenerator&&!isBasic&&!isClass&&firstArrowIndex>0;let textAfterPrefix;if(isClass){textAfterPrefix=text.substring('class'.length);const classNameMatch=/^[^{\s]+/.exec(textAfterPrefix.trim());let className=defaultName;if(classNameMatch)
className=classNameMatch[0].trim()||defaultName;addElements('class',textAfterPrefix,className);}else if(asyncMatch){textAfterPrefix=text.substring(asyncMatch[1].length);addElements('async \u0192',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isGenerator){textAfterPrefix=text.substring('function*'.length);addElements('\u0192*',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isGeneratorShorthand){textAfterPrefix=text.substring('*'.length);addElements('\u0192*',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isBasic){textAfterPrefix=text.substring('function'.length);addElements('\u0192',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isArrow){const maxArrowFunctionCharacterLength=60;let abbreviation=text;if(defaultName)
abbreviation=defaultName+'()';else if(text.length>maxArrowFunctionCharacterLength)
abbreviation=text.substring(0,firstArrowIndex+2)+' {\u2026}';addElements('',text,abbreviation);}else{addElements('\u0192',text,nameAndArguments(text));}
valueElement.title=description.trimEnd(500);return valueElement;function nameAndArguments(contents){const startOfArgumentsIndex=contents.indexOf('(');const endOfArgumentsMatch=contents.match(/\)\s*{/);if(startOfArgumentsIndex!==-1&&endOfArgumentsMatch&&endOfArgumentsMatch.index>startOfArgumentsIndex){const name=contents.substring(0,startOfArgumentsIndex).trim()||defaultName;const args=contents.substring(startOfArgumentsIndex,endOfArgumentsMatch.index+1);return name+args;}
return defaultName+'()';}
function addElements(prefix,body,abbreviation){const maxFunctionBodyLength=200;if(prefix.length)
valueElement.createChild('span','object-value-function-prefix').textContent=prefix+' ';if(includePreview)
valueElement.createTextChild(body.trim().trimEnd(maxFunctionBodyLength));else
valueElement.createTextChild(abbreviation.replace(/\n/g,' '));}}
static createValueElementWithCustomSupport(value,wasThrown,showPreview,parentElement,linkifier){if(value.customPreview()){const result=(new ObjectUI.CustomPreviewComponent(value)).element;result.classList.add('object-properties-section-custom-section');return result;}
return ObjectUI.ObjectPropertiesSection.createValueElement(value,wasThrown,showPreview,parentElement,linkifier);}
static createValueElement(value,wasThrown,showPreview,parentElement,linkifier){let valueElement;const type=value.type;const subtype=value.subtype;const description=value.description;if(type==='object'&&subtype==='internal#location'){const rawLocation=value.debuggerModel().createRawLocationByScriptId(value.value.scriptId,value.value.lineNumber,value.value.columnNumber);if(rawLocation&&linkifier)
return linkifier.linkifyRawLocation(rawLocation,'');valueElement=createUnknownInternalLocationElement();}else if(type==='string'&&typeof description==='string'){valueElement=createStringElement();}else if(type==='function'){valueElement=ObjectUI.ObjectPropertiesSection.valueElementForFunctionDescription(description);}else if(type==='object'&&subtype==='node'&&description){valueElement=createNodeElement();}else if(type==='number'&&description&&description.indexOf('e')!==-1){valueElement=createNumberWithExponentElement();if(parentElement)
parentElement.classList.add('hbox');}else{valueElement=createElementWithClass('span','object-value-'+(subtype||type));valueElement.title=description||'';if(value.preview&&showPreview){const previewFormatter=new ObjectUI.RemoteObjectPreviewFormatter();previewFormatter.appendObjectPreview(valueElement,value.preview,false);}else if(description.length>ObjectUI.ObjectPropertiesSection._maxRenderableStringLength){valueElement.appendChild(UI.createExpandableText(description,50));}else{valueElement.textContent=description;}}
if(wasThrown){const wrapperElement=createElementWithClass('span','error value');wrapperElement.createTextChild('['+Common.UIString('Exception')+': ');wrapperElement.appendChild(valueElement);wrapperElement.createTextChild(']');return wrapperElement;}
valueElement.classList.add('value');return valueElement;function createUnknownInternalLocationElement(){const valueElement=createElementWithClass('span');valueElement.textContent='<'+Common.UIString('unknown')+'>';valueElement.title=description||'';return valueElement;}
function createStringElement(){const valueElement=createElementWithClass('span','object-value-string');const text=description.replace(/\n/g,'\u21B5');valueElement.createChild('span','object-value-string-quote').textContent='"';if(description.length>ObjectUI.ObjectPropertiesSection._maxRenderableStringLength)
valueElement.appendChild(UI.createExpandableText(text,50));else
valueElement.createTextChild(text);valueElement.createChild('span','object-value-string-quote').textContent='"';valueElement.title=description||'';return valueElement;}
function createNodeElement(){const valueElement=createElementWithClass('span','object-value-node');ObjectUI.RemoteObjectPreviewFormatter.createSpansForNodeTitle(valueElement,(description));valueElement.addEventListener('click',event=>{Common.Revealer.reveal(value);event.consume(true);},false);valueElement.addEventListener('mousemove',()=>SDK.OverlayModel.highlightObjectAsDOMNode(value),false);valueElement.addEventListener('mouseleave',()=>SDK.OverlayModel.hideDOMNodeHighlight(),false);return valueElement;}
function createNumberWithExponentElement(){const valueElement=createElementWithClass('span','object-value-number');const numberParts=description.split('e');valueElement.createChild('span','object-value-scientific-notation-mantissa').textContent=numberParts[0];valueElement.createChild('span','object-value-scientific-notation-exponent').textContent='e'+numberParts[1];valueElement.classList.add('object-value-scientific-notation-number');valueElement.title=description||'';return valueElement;}}
static formatObjectAsFunction(func,element,linkify,includePreview){return func.debuggerModel().functionDetailsPromise(func).then(didGetDetails);function didGetDetails(response){if(linkify&&response&&response.location){element.classList.add('linkified');element.addEventListener('click',()=>Common.Revealer.reveal(response.location)&&false);}
let defaultName=includePreview?'':'anonymous';if(response&&response.functionName)
defaultName=response.functionName;const valueElement=ObjectUI.ObjectPropertiesSection.valueElementForFunctionDescription(func.description,includePreview,defaultName);element.appendChild(valueElement);}}
skipProto(){this._skipProto=true;}
expand(){this._objectTreeElement.expand();}
setEditable(value){this._editable=value;}
objectTreeElement(){return this._objectTreeElement;}
enableContextMenu(){this.element.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),false);}
_contextMenuEventFired(event){const contextMenu=new UI.ContextMenu(event);contextMenu.appendApplicableItems(this._object);if(this._object instanceof SDK.LocalJSONObject){contextMenu.viewSection().appendItem(ls`Expand recursively`,this._objectTreeElement.expandRecursively.bind(this._objectTreeElement,Number.MAX_VALUE));contextMenu.viewSection().appendItem(ls`Collapse children`,this._objectTreeElement.collapseChildren.bind(this._objectTreeElement));}
contextMenu.show();}
titleLessMode(){this._objectTreeElement.listItemElement.classList.add('hidden');this._objectTreeElement.childrenListElement.classList.add('title-less-mode');this._objectTreeElement.expand();}};ObjectUI.ObjectPropertiesSection._arrayLoadThreshold=100;ObjectUI.ObjectPropertiesSection._maxRenderableStringLength=10000;ObjectUI.ObjectPropertiesSection.RootElement=class extends UI.TreeElement{constructor(object,linkifier,emptyPlaceholder,ignoreHasOwnProperty,extraProperties){const contentElement=createElement('slot');super(contentElement);this._object=object;this._extraProperties=extraProperties||[];this._ignoreHasOwnProperty=!!ignoreHasOwnProperty;this._emptyPlaceholder=emptyPlaceholder;this.setExpandable(true);this.selectable=true;this.toggleOnClick=true;this.listItemElement.classList.add('object-properties-section-root-element');this._linkifier=linkifier;}
onexpand(){if(this.treeOutline)
this.treeOutline.element.classList.add('expanded');}
oncollapse(){if(this.treeOutline)
this.treeOutline.element.classList.remove('expanded');}
ondblclick(e){return true;}
onpopulate(){ObjectUI.ObjectPropertyTreeElement._populate(this,this._object,!!this.treeOutline._skipProto,this._linkifier,this._emptyPlaceholder,this._ignoreHasOwnProperty,this._extraProperties);}};ObjectUI.ObjectPropertyTreeElement=class extends UI.TreeElement{constructor(property,linkifier){super();this.property=property;this.toggleOnClick=true;this._highlightChanges=[];this._linkifier=linkifier;this.listItemElement.addEventListener('contextmenu',this._contextMenuFired.bind(this),false);}
static async _populate(treeElement,value,skipProto,linkifier,emptyPlaceholder,flattenProtoChain,extraProperties,targetValue){if(value.arrayLength()>ObjectUI.ObjectPropertiesSection._arrayLoadThreshold){treeElement.removeChildren();ObjectUI.ArrayGroupingTreeElement._populateArray(treeElement,value,0,value.arrayLength()-1,linkifier);return;}
let allProperties;if(flattenProtoChain)
allProperties=await value.getAllProperties(false,true);else
allProperties=await SDK.RemoteObject.loadFromObjectPerProto(value,true);const properties=allProperties.properties;const internalProperties=allProperties.internalProperties;treeElement.removeChildren();if(!properties)
return;extraProperties=extraProperties||[];for(let i=0;i<extraProperties.length;++i)
properties.push(extraProperties[i]);ObjectUI.ObjectPropertyTreeElement.populateWithProperties(treeElement,properties,internalProperties,skipProto,targetValue||value,linkifier,emptyPlaceholder);}
static populateWithProperties(treeNode,properties,internalProperties,skipProto,value,linkifier,emptyPlaceholder){properties.sort(ObjectUI.ObjectPropertiesSection.CompareProperties);const tailProperties=[];let protoProperty=null;for(let i=0;i<properties.length;++i){const property=properties[i];property.parentObject=value;if(property.name==='__proto__'&&!property.isAccessorProperty()){protoProperty=property;continue;}
if(property.isOwn&&property.getter){const getterProperty=new SDK.RemoteObjectProperty('get '+property.name,property.getter,false);getterProperty.parentObject=value;tailProperties.push(getterProperty);}
if(property.isOwn&&property.setter){const setterProperty=new SDK.RemoteObjectProperty('set '+property.name,property.setter,false);setterProperty.parentObject=value;tailProperties.push(setterProperty);}
const canShowProperty=property.getter||!property.isAccessorProperty();if(canShowProperty&&property.name!=='__proto__')
treeNode.appendChild(new ObjectUI.ObjectPropertyTreeElement(property,linkifier));}
for(let i=0;i<tailProperties.length;++i)
treeNode.appendChild(new ObjectUI.ObjectPropertyTreeElement(tailProperties[i],linkifier));if(!skipProto&&protoProperty)
treeNode.appendChild(new ObjectUI.ObjectPropertyTreeElement(protoProperty,linkifier));if(internalProperties){for(let i=0;i<internalProperties.length;i++){internalProperties[i].parentObject=value;const treeElement=new ObjectUI.ObjectPropertyTreeElement(internalProperties[i],linkifier);if(internalProperties[i].name==='[[Entries]]'){treeElement.setExpandable(true);treeElement.expand();}
treeNode.appendChild(treeElement);}}
ObjectUI.ObjectPropertyTreeElement._appendEmptyPlaceholderIfNeeded(treeNode,emptyPlaceholder);}
static _appendEmptyPlaceholderIfNeeded(treeNode,emptyPlaceholder){if(treeNode.childCount())
return;const title=createElementWithClass('div','gray-info-message');title.textContent=emptyPlaceholder||Common.UIString('No properties');const infoElement=new UI.TreeElement(title);treeNode.appendChild(infoElement);}
static createRemoteObjectAccessorPropertySpan(object,propertyPath,callback){const rootElement=createElement('span');const element=rootElement.createChild('span');element.textContent=Common.UIString('(...)');if(!object)
return rootElement;element.classList.add('object-value-calculate-value-button');element.title=Common.UIString('Invoke property getter');element.addEventListener('click',onInvokeGetterClick,false);function onInvokeGetterClick(event){event.consume();object.callFunction(invokeGetter,[{value:JSON.stringify(propertyPath)}]).then(callback);}
function invokeGetter(arrayStr){let result=this;const properties=JSON.parse(arrayStr);for(let i=0,n=properties.length;i<n;++i)
result=result[properties[i]];return result;}
return rootElement;}
setSearchRegex(regex,additionalCssClassName){let cssClasses=UI.highlightedSearchResultClassName;if(additionalCssClassName)
cssClasses+=' '+additionalCssClassName;this.revertHighlightChanges();this._applySearch(regex,this.nameElement,cssClasses);const valueType=this.property.value.type;if(valueType!=='object')
this._applySearch(regex,this.valueElement,cssClasses);return!!this._highlightChanges.length;}
_applySearch(regex,element,cssClassName){const ranges=[];const content=element.textContent;regex.lastIndex=0;let match=regex.exec(content);while(match){ranges.push(new TextUtils.SourceRange(match.index,match[0].length));match=regex.exec(content);}
if(ranges.length)
UI.highlightRangesWithStyleClass(element,ranges,cssClassName,this._highlightChanges);}
revertHighlightChanges(){UI.revertDomChanges(this._highlightChanges);this._highlightChanges=[];}
onpopulate(){const propertyValue=(this.property.value);console.assert(propertyValue);const skipProto=this.treeOutline?this.treeOutline._skipProto:true;const targetValue=this.property.name!=='__proto__'?propertyValue:this.property.parentObject;ObjectUI.ObjectPropertyTreeElement._populate(this,propertyValue,skipProto,this._linkifier,undefined,undefined,undefined,targetValue);}
ondblclick(event){const inEditableElement=event.target.isSelfOrDescendant(this.valueElement)||(this.expandedValueElement&&event.target.isSelfOrDescendant(this.expandedValueElement));if(!this.property.value.customPreview()&&inEditableElement&&(this.property.writable||this.property.setter))
this._startEditing();return false;}
onattach(){this.update();this._updateExpandable();}
onexpand(){this._showExpandedValueElement(true);}
oncollapse(){this._showExpandedValueElement(false);}
_showExpandedValueElement(value){if(!this.expandedValueElement)
return;if(value)
this._rowContainer.replaceChild(this.expandedValueElement,this.valueElement);else
this._rowContainer.replaceChild(this.valueElement,this.expandedValueElement);}
_createExpandedValueElement(value){const needsAlternateValue=value.hasChildren&&!value.customPreview()&&value.subtype!=='node'&&value.type!=='function'&&(value.type!=='object'||value.preview);if(!needsAlternateValue)
return null;const valueElement=createElementWithClass('span','value');if(value.description==='Object')
valueElement.textContent='';else
valueElement.setTextContentTruncatedIfNeeded(value.description||'');valueElement.classList.add('object-value-'+(value.subtype||value.type));valueElement.title=value.description||'';return valueElement;}
update(){this.nameElement=ObjectUI.ObjectPropertiesSection.createNameElement(this.property.name);if(!this.property.enumerable)
this.nameElement.classList.add('object-properties-section-dimmed');if(this.property.synthetic)
this.nameElement.classList.add('synthetic-property');this._updatePropertyPath();if(this.property.value){const showPreview=this.property.name!=='__proto__';this.valueElement=ObjectUI.ObjectPropertiesSection.createValueElementWithCustomSupport(this.property.value,this.property.wasThrown,showPreview,this.listItemElement,this._linkifier);}else if(this.property.getter){this.valueElement=ObjectUI.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(this.property.parentObject,[this.property.name],this._onInvokeGetterClick.bind(this));}else{this.valueElement=createElementWithClass('span','object-value-undefined');this.valueElement.textContent=Common.UIString('<unreadable>');this.valueElement.title=Common.UIString('No property getter');}
const valueText=this.valueElement.textContent;if(this.property.value&&valueText&&!this.property.wasThrown)
this.expandedValueElement=this._createExpandedValueElement(this.property.value);this.listItemElement.removeChildren();this._rowContainer=UI.html`<span class='name-and-value'>${this.nameElement}: ${this.valueElement}</span>`;this.listItemElement.appendChild(this._rowContainer);}
_updatePropertyPath(){if(this.nameElement.title)
return;const name=this.property.name;if(this.property.synthetic){this.nameElement.title=name;return;}
const useDotNotation=/^(_|\$|[A-Z])(_|\$|[A-Z]|\d)*$/i;const isInteger=/^[1-9]\d*$/;const parentPath=(this.parent.nameElement&&!this.parent.property.synthetic)?this.parent.nameElement.title:'';if(useDotNotation.test(name))
this.nameElement.title=parentPath?`${parentPath}.${name}`:name;else if(isInteger.test(name))
this.nameElement.title=parentPath+'['+name+']';else
this.nameElement.title=parentPath+'["'+JSON.stringify(name)+'"]';}
_contextMenuFired(event){const contextMenu=new UI.ContextMenu(event);contextMenu.appendApplicableItems(this);if(this.property.symbol)
contextMenu.appendApplicableItems(this.property.symbol);if(this.property.value)
contextMenu.appendApplicableItems(this.property.value);if(!this.property.synthetic&&this.nameElement&&this.nameElement.title){const copyPathHandler=InspectorFrontendHost.copyText.bind(InspectorFrontendHost,this.nameElement.title);contextMenu.clipboardSection().appendItem(ls`Copy property path`,copyPathHandler);}
if(this.property.parentObject instanceof SDK.LocalJSONObject){contextMenu.viewSection().appendItem(ls`Expand recursively`,this.expandRecursively.bind(this,Number.MAX_VALUE));contextMenu.viewSection().appendItem(ls`Collapse children`,this.collapseChildren.bind(this));}
contextMenu.show();}
_startEditing(){if(this._prompt||!this.treeOutline._editable||this._readOnly)
return;this._editableDiv=this._rowContainer.createChild('span','editable-div');let text=this.property.value.description;if(this.property.value.type==='string'&&typeof text==='string')
text='"'+text+'"';this._editableDiv.setTextContentTruncatedIfNeeded(text,Common.UIString('<string is too large to edit>'));const originalContent=this._editableDiv.textContent;this.setExpandable(false);this.listItemElement.classList.add('editing-sub-part');this.valueElement.classList.add('hidden');this._prompt=new ObjectUI.ObjectPropertyPrompt();const proxyElement=this._prompt.attachAndStartEditing(this._editableDiv,this._editingCommitted.bind(this,originalContent));proxyElement.classList.add('property-prompt');this.listItemElement.getComponentSelection().selectAllChildren(this._editableDiv);proxyElement.addEventListener('keydown',this._promptKeyDown.bind(this,originalContent),false);}
_editingEnded(){this._prompt.detach();delete this._prompt;this._editableDiv.remove();this._updateExpandable();this.listItemElement.scrollLeft=0;this.listItemElement.classList.remove('editing-sub-part');}
_editingCancelled(){this.valueElement.classList.remove('hidden');this._editingEnded();}
_editingCommitted(originalContent){const userInput=this._prompt.text();if(userInput===originalContent){this._editingCancelled();return;}
this._editingEnded();this._applyExpression(userInput);}
_promptKeyDown(originalContent,event){if(isEnterKey(event)){event.consume();this._editingCommitted(originalContent);return;}
if(event.key==='Escape'){event.consume();this._editingCancelled();return;}}
async _applyExpression(expression){const property=SDK.RemoteObject.toCallArgument(this.property.symbol||this.property.name);expression=ObjectUI.JavaScriptREPL.wrapObjectLiteral(expression.trim());if(this.property.synthetic){let invalidate=false;if(expression)
invalidate=await this.property.setSyntheticValue(expression);if(invalidate){const parent=this.parent;parent.invalidateChildren();parent.onpopulate();}else{this.update();}
return;}
const errorPromise=expression?this.property.parentObject.setPropertyValue(property,expression):this.property.parentObject.deleteProperty(property);const error=await errorPromise;if(error){this.update();return;}
if(!expression){this.parent.removeChild(this);}else{const parent=this.parent;parent.invalidateChildren();parent.onpopulate();}}
_onInvokeGetterClick(result){if(!result.object)
return;this.property.value=result.object;this.property.wasThrown=result.wasThrown;this.update();this.invalidateChildren();this._updateExpandable();}
_updateExpandable(){if(this.property.value){this.setExpandable(!this.property.value.customPreview()&&this.property.value.hasChildren&&!this.property.wasThrown);}else{this.setExpandable(false);}}
path(){return this.nameElement.title;}};ObjectUI.ArrayGroupingTreeElement=class extends UI.TreeElement{constructor(object,fromIndex,toIndex,propertyCount,linkifier){super(String.sprintf('[%d \u2026 %d]',fromIndex,toIndex),true);this.toggleOnClick=true;this._fromIndex=fromIndex;this._toIndex=toIndex;this._object=object;this._readOnly=true;this._propertyCount=propertyCount;this._linkifier=linkifier;}
static _populateArray(treeNode,object,fromIndex,toIndex,linkifier){ObjectUI.ArrayGroupingTreeElement._populateRanges(treeNode,object,fromIndex,toIndex,true,linkifier);}
static _populateRanges(treeNode,object,fromIndex,toIndex,topLevel,linkifier){object.callFunctionJSON(packRanges,[{value:fromIndex},{value:toIndex},{value:ObjectUI.ArrayGroupingTreeElement._bucketThreshold},{value:ObjectUI.ArrayGroupingTreeElement._sparseIterationThreshold},{value:ObjectUI.ArrayGroupingTreeElement._getOwnPropertyNamesThreshold}]).then(callback);function packRanges(fromIndex,toIndex,bucketThreshold,sparseIterationThreshold,getOwnPropertyNamesThreshold){let ownPropertyNames=null;const consecutiveRange=(toIndex-fromIndex>=sparseIterationThreshold)&&ArrayBuffer.isView(this);const skipGetOwnPropertyNames=consecutiveRange&&(toIndex-fromIndex>=getOwnPropertyNamesThreshold);function*arrayIndexes(object){if(toIndex-fromIndex<sparseIterationThreshold){for(let i=fromIndex;i<=toIndex;++i){if(i in object)
yield i;}}else{ownPropertyNames=ownPropertyNames||Object.getOwnPropertyNames(object);for(let i=0;i<ownPropertyNames.length;++i){const name=ownPropertyNames[i];const index=name>>>0;if((''+index)===name&&fromIndex<=index&&index<=toIndex)
yield index;}}}
let count=0;if(consecutiveRange){count=toIndex-fromIndex+1;}else{for(const i of arrayIndexes(this))
++count;}
let bucketSize=count;if(count<=bucketThreshold)
bucketSize=count;else
bucketSize=Math.pow(bucketThreshold,Math.ceil(Math.log(count)/Math.log(bucketThreshold))-1);const ranges=[];if(consecutiveRange){for(let i=fromIndex;i<=toIndex;i+=bucketSize){const groupStart=i;let groupEnd=groupStart+bucketSize-1;if(groupEnd>toIndex)
groupEnd=toIndex;ranges.push([groupStart,groupEnd,groupEnd-groupStart+1]);}}else{count=0;let groupStart=-1;let groupEnd=0;for(const i of arrayIndexes(this)){if(groupStart===-1)
groupStart=i;groupEnd=i;if(++count===bucketSize){ranges.push([groupStart,groupEnd,count]);count=0;groupStart=-1;}}
if(count>0)
ranges.push([groupStart,groupEnd,count]);}
return{ranges:ranges,skipGetOwnPropertyNames:skipGetOwnPropertyNames};}
function callback(result){if(!result)
return;const ranges=(result.ranges);if(ranges.length===1){ObjectUI.ArrayGroupingTreeElement._populateAsFragment(treeNode,object,ranges[0][0],ranges[0][1],linkifier);}else{for(let i=0;i<ranges.length;++i){const fromIndex=ranges[i][0];const toIndex=ranges[i][1];const count=ranges[i][2];if(fromIndex===toIndex)
ObjectUI.ArrayGroupingTreeElement._populateAsFragment(treeNode,object,fromIndex,toIndex,linkifier);else
treeNode.appendChild(new ObjectUI.ArrayGroupingTreeElement(object,fromIndex,toIndex,count,linkifier));}}
if(topLevel){ObjectUI.ArrayGroupingTreeElement._populateNonIndexProperties(treeNode,object,result.skipGetOwnPropertyNames,linkifier);}}}
static async _populateAsFragment(treeNode,object,fromIndex,toIndex,linkifier){const result=await object.callFunction(buildArrayFragment,[{value:fromIndex},{value:toIndex},{value:ObjectUI.ArrayGroupingTreeElement._sparseIterationThreshold}]);if(!result.object||result.wasThrown)
return;const arrayFragment=result.object;const allProperties=await arrayFragment.getAllProperties(false,true);arrayFragment.release();const properties=allProperties.properties;if(!properties)
return;properties.sort(ObjectUI.ObjectPropertiesSection.CompareProperties);for(let i=0;i<properties.length;++i){properties[i].parentObject=this._object;const childTreeElement=new ObjectUI.ObjectPropertyTreeElement(properties[i],linkifier);childTreeElement._readOnly=true;treeNode.appendChild(childTreeElement);}
function buildArrayFragment(fromIndex,toIndex,sparseIterationThreshold){const result=Object.create(null);if(toIndex-fromIndex<sparseIterationThreshold){for(let i=fromIndex;i<=toIndex;++i){if(i in this)
result[i]=this[i];}}else{const ownPropertyNames=Object.getOwnPropertyNames(this);for(let i=0;i<ownPropertyNames.length;++i){const name=ownPropertyNames[i];const index=name>>>0;if(String(index)===name&&fromIndex<=index&&index<=toIndex)
result[index]=this[index];}}
return result;}}
static async _populateNonIndexProperties(treeNode,object,skipGetOwnPropertyNames,linkifier){const result=await object.callFunction(buildObjectFragment,[{value:skipGetOwnPropertyNames}]);if(!result.object||result.wasThrown)
return;const allProperties=await result.object.getOwnProperties(true);result.object.release();if(!allProperties.properties)
return;const properties=allProperties.properties;properties.sort(ObjectUI.ObjectPropertiesSection.CompareProperties);for(let i=0;i<properties.length;++i){properties[i].parentObject=this._object;const childTreeElement=new ObjectUI.ObjectPropertyTreeElement(properties[i],linkifier);childTreeElement._readOnly=true;treeNode.appendChild(childTreeElement);}
function buildObjectFragment(skipGetOwnPropertyNames){const result={__proto__:this.__proto__};if(skipGetOwnPropertyNames)
return result;const names=Object.getOwnPropertyNames(this);for(let i=0;i<names.length;++i){const name=names[i];if(String(name>>>0)===name&&name>>>0!==0xffffffff)
continue;const descriptor=Object.getOwnPropertyDescriptor(this,name);if(descriptor)
Object.defineProperty(result,name,descriptor);}
return result;}}
onpopulate(){if(this._propertyCount>=ObjectUI.ArrayGroupingTreeElement._bucketThreshold){ObjectUI.ArrayGroupingTreeElement._populateRanges(this,this._object,this._fromIndex,this._toIndex,false,this._linkifier);return;}
ObjectUI.ArrayGroupingTreeElement._populateAsFragment(this,this._object,this._fromIndex,this._toIndex,this._linkifier);}
onattach(){this.listItemElement.classList.add('object-properties-section-name');}};ObjectUI.ArrayGroupingTreeElement._bucketThreshold=100;ObjectUI.ArrayGroupingTreeElement._sparseIterationThreshold=250000;ObjectUI.ArrayGroupingTreeElement._getOwnPropertyNamesThreshold=500000;ObjectUI.ObjectPropertyPrompt=class extends UI.TextPrompt{constructor(){super();this.initialize(ObjectUI.javaScriptAutocomplete.completionsForTextInCurrentContext.bind(ObjectUI.javaScriptAutocomplete));}};ObjectUI.ObjectPropertiesSectionExpandController=class{constructor(){this._expandedProperties=new Set();}
watchSection(id,section){section.addEventListener(UI.TreeOutline.Events.ElementAttached,this._elementAttached,this);section.addEventListener(UI.TreeOutline.Events.ElementExpanded,this._elementExpanded,this);section.addEventListener(UI.TreeOutline.Events.ElementCollapsed,this._elementCollapsed,this);section[ObjectUI.ObjectPropertiesSectionExpandController._treeOutlineId]=id;if(this._expandedProperties.has(id))
section.expand();}
stopWatchSectionsWithId(id){for(const property of this._expandedProperties){if(property.startsWith(id+':'))
this._expandedProperties.delete(property);}}
_elementAttached(event){const element=(event.data);if(element.isExpandable()&&this._expandedProperties.has(this._propertyPath(element)))
element.expand();}
_elementExpanded(event){const element=(event.data);this._expandedProperties.add(this._propertyPath(element));}
_elementCollapsed(event){const element=(event.data);this._expandedProperties.delete(this._propertyPath(element));}
_propertyPath(treeElement){const cachedPropertyPath=treeElement[ObjectUI.ObjectPropertiesSectionExpandController._cachedPathSymbol];if(cachedPropertyPath)
return cachedPropertyPath;let current=treeElement;const rootElement=treeElement.treeOutline.objectTreeElement();let result;while(current!==rootElement){let currentName='';if(current.property)
currentName=current.property.name;else
currentName=typeof current.title==='string'?current.title:current.title.textContent;result=currentName+(result?'.'+result:'');current=current.parent;}
const treeOutlineId=treeElement.treeOutline[ObjectUI.ObjectPropertiesSectionExpandController._treeOutlineId];result=treeOutlineId+(result?':'+result:'');treeElement[ObjectUI.ObjectPropertiesSectionExpandController._cachedPathSymbol]=result;return result;}};ObjectUI.ObjectPropertiesSectionExpandController._cachedPathSymbol=Symbol('cachedPath');ObjectUI.ObjectPropertiesSectionExpandController._treeOutlineId=Symbol('treeOutlineId');ObjectUI.ObjectPropertiesSection.Renderer=class{render(object,options){if(!(object instanceof SDK.RemoteObject))
return Promise.reject(new Error('Can\'t render '+object));options=options||{};const title=options.title;const section=new ObjectUI.ObjectPropertiesSection(object,title);if(!title)
section.titleLessMode();section.editable=!!options.editable;return Promise.resolve(({node:section.element,tree:section}));}};;ObjectUI.JavaScriptAutocomplete=class{constructor(){this._expressionCache=new Map();SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.CommandEvaluated,this._clearCache,this);UI.context.addFlavorChangeListener(SDK.ExecutionContext,this._clearCache,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerResumed,this._clearCache,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerPaused,this._clearCache,this);}
_clearCache(){this._expressionCache.clear();}
async completionsForTextInCurrentContext(fullText,query,force){const trimmedText=fullText.trim();const[mapCompletions,expressionCompletions]=await Promise.all([this._mapCompletions(trimmedText,query),this._completionsForExpression(trimmedText,query,force)]);return mapCompletions.concat(expressionCompletions);}
async argumentsHint(fullText){const functionCall=await Formatter.formatterWorkerPool().findLastFunctionCall(fullText);if(!functionCall)
return null;const executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext)
return null;const result=await executionContext.evaluate({expression:functionCall.baseExpression,objectGroup:'argumentsHint',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false,throwOnSideEffect:functionCall.possibleSideEffects,timeout:functionCall.possibleSideEffects?500:undefined},false,false);if(!result||result.exceptionDetails||!result.object||result.object.type!=='function'){executionContext.runtimeModel.releaseObjectGroup('argumentsHint');return null;}
const args=await this._argumentsForFunction(result.object,async()=>{const result=await executionContext.evaluate({expression:functionCall.receiver,objectGroup:'argumentsHint',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false,throwOnSideEffect:functionCall.possibleSideEffects,timeout:functionCall.possibleSideEffects?500:undefined},false,false);return(result&&!result.exceptionDetails)?result.object:null;},functionCall.functionName);executionContext.runtimeModel.releaseObjectGroup('argumentsHint');if(!args.length||(args.length===1&&!args[0].length))
return null;return{args,argumentIndex:functionCall.argumentIndex};}
async _argumentsForFunction(functionObject,receiverObjGetter,parsedFunctionName){const description=functionObject.description;if(!description.endsWith('{ [native code] }'))
return[await Formatter.formatterWorkerPool().argumentsList(description)];if(description==='function () { [native code] }'){const properties=await functionObject.getOwnProperties(false);const internalProperties=properties.internalProperties||[];const targetProperty=internalProperties.find(property=>property.name==='[[TargetFunction]]');const argsProperty=internalProperties.find(property=>property.name==='[[BoundArgs]]');const thisProperty=internalProperties.find(property=>property.name==='[[BoundThis]]');if(thisProperty&&targetProperty&&argsProperty){const originalSignatures=await this._argumentsForFunction(targetProperty.value,()=>Promise.resolve(thisProperty.value));const boundArgsLength=SDK.RemoteObject.arrayLength(argsProperty.value);const clippedArgs=[];for(const signature of originalSignatures){const restIndex=signature.slice(0,boundArgsLength).findIndex(arg=>arg.startsWith('...'));if(restIndex!==-1)
clippedArgs.push(signature.slice(restIndex));else
clippedArgs.push(signature.slice(boundArgsLength));}
return clippedArgs;}}
const javaScriptMetadata=await self.runtime.extension(Common.JavaScriptMetadata).instance();const name=/^function ([^(]*)\(/.exec(description)[1]||parsedFunctionName;if(!name)
return[];const uniqueSignatures=javaScriptMetadata.signaturesForNativeFunction(name);if(uniqueSignatures)
return uniqueSignatures;const receiverObj=await receiverObjGetter();const className=receiverObj.className;if(javaScriptMetadata.signaturesForInstanceMethod(name,className))
return javaScriptMetadata.signaturesForInstanceMethod(name,className);if(receiverObj.type==='function'&&receiverObj.description.endsWith('{ [native code] }')){const receiverName=/^function ([^(]*)\(/.exec(receiverObj.description)[1];const staticSignatures=javaScriptMetadata.signaturesForStaticMethod(name,receiverName);if(staticSignatures)
return staticSignatures;}
let protoNames;if(receiverObj.type==='number'){protoNames=['Number','Object'];}else if(receiverObj.type==='string'){protoNames=['String','Object'];}else if(receiverObj.type==='symbol'){protoNames=['Symbol','Object'];}else if(receiverObj.type==='bigint'){protoNames=['BigInt','Object'];}else if(receiverObj.type==='boolean'){protoNames=['Boolean','Object'];}else if(receiverObj.type==='undefined'||receiverObj.subtype==='null'){protoNames=[];}else{protoNames=await receiverObj.callFunctionJSON(function(){const result=[];for(let object=this;object;object=Object.getPrototypeOf(object)){if(typeof object==='object'&&object.constructor&&object.constructor.name)
result[result.length]=object.constructor.name;}
return result;});}
for(const proto of protoNames){const instanceSignatures=javaScriptMetadata.signaturesForInstanceMethod(name,proto);if(instanceSignatures)
return instanceSignatures;}
return[];}
async _mapCompletions(text,query){const mapMatch=text.match(/\.\s*(get|set|delete)\s*\(\s*$/);const executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext||!mapMatch)
return[];const expression=await Formatter.formatterWorkerPool().findLastExpression(text.substring(0,mapMatch.index));if(!expression)
return[];const result=await executionContext.evaluate({expression:expression.baseExpression,objectGroup:'mapCompletion',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false,throwOnSideEffect:expression.possibleSideEffects,timeout:expression.possibleSideEffects?500:undefined},false,false);if(result.error||!!result.exceptionDetails||result.object.subtype!=='map')
return[];const properties=await result.object.getOwnProperties(false);const internalProperties=properties.internalProperties||[];const entriesProperty=internalProperties.find(property=>property.name==='[[Entries]]');if(!entriesProperty)
return[];const keysObj=await entriesProperty.value.callFunctionJSON(getEntries);executionContext.runtimeModel.releaseObjectGroup('mapCompletion');return gotKeys(Object.keys(keysObj));function getEntries(){const result={__proto__:null};for(let i=0;i<this.length;i++){if(typeof this[i].key==='string')
result[this[i].key]=true;}
return result;}
function gotKeys(rawKeys){const caseSensitivePrefix=[];const caseInsensitivePrefix=[];const caseSensitiveAnywhere=[];const caseInsensitiveAnywhere=[];let quoteChar='"';if(query.startsWith('\''))
quoteChar='\'';let endChar=')';if(mapMatch[0].indexOf('set')!==-1)
endChar=', ';const sorter=rawKeys.length<1000?String.naturalOrderComparator:undefined;const keys=rawKeys.sort(sorter).map(key=>quoteChar+key+quoteChar);for(const key of keys){if(key.length<query.length)
continue;if(query.length&&key.toLowerCase().indexOf(query.toLowerCase())===-1)
continue;const title=key.split('\n').join('\\n');const text=title+endChar;if(key.startsWith(query))
caseSensitivePrefix.push({text:text,title:title,priority:4});else if(key.toLowerCase().startsWith(query.toLowerCase()))
caseInsensitivePrefix.push({text:text,title:title,priority:3});else if(key.indexOf(query)!==-1)
caseSensitiveAnywhere.push({text:text,title:title,priority:2});else
caseInsensitiveAnywhere.push({text:text,title:title,priority:1});}
const suggestions=caseSensitivePrefix.concat(caseInsensitivePrefix,caseSensitiveAnywhere,caseInsensitiveAnywhere);if(suggestions.length)
suggestions[0].subtitle=Common.UIString('Keys');return suggestions;}}
async _completionsForExpression(fullText,query,force){const executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext)
return[];let expression;if(fullText.endsWith('.')||fullText.endsWith('['))
expression=await Formatter.formatterWorkerPool().findLastExpression(fullText.substring(0,fullText.length-1));if(!expression){if(fullText.endsWith('.'))
return[];expression={baseExpression:'',possibleSideEffects:false};}
const needsNoSideEffects=expression.possibleSideEffects;const expressionString=expression.baseExpression;const dotNotation=fullText.endsWith('.');const bracketNotation=!!expressionString&&fullText.endsWith('[');if((expressionString&&!isNaN(expressionString))||(!expressionString&&query&&!isNaN(query)))
return[];if(!query&&!expressionString&&!force)
return[];const selectedFrame=executionContext.debuggerModel.selectedCallFrame();let completionGroups;const TEN_SECONDS=10000;let cache=this._expressionCache.get(expressionString);if(cache&&cache.date+TEN_SECONDS>Date.now()){completionGroups=await cache.value;}else if(!expressionString&&selectedFrame){cache={date:Date.now(),value:completionsOnPause(selectedFrame)};this._expressionCache.set(expressionString,cache);completionGroups=await cache.value;}else{const resultPromise=executionContext.evaluate({expression:expressionString,objectGroup:'completion',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false,throwOnSideEffect:needsNoSideEffects,timeout:needsNoSideEffects?500:undefined},false,false);cache={date:Date.now(),value:resultPromise.then(result=>completionsOnGlobal.call(this,result))};this._expressionCache.set(expressionString,cache);completionGroups=await cache.value;}
return this._receivedPropertyNames(completionGroups.slice(0),dotNotation,bracketNotation,expressionString,query);async function completionsOnGlobal(result){if(result.error||!!result.exceptionDetails||!result.object)
return[];let object=result.object;while(object&&object.type==='object'&&object.subtype==='proxy'){const properties=await object.getOwnProperties(false);const internalProperties=properties.internalProperties||[];const target=internalProperties.find(property=>property.name==='[[Target]]');object=target?target.value:null;}
if(!object)
return[];let completions=[];if(object.type==='object'||object.type==='function'){completions=await object.callFunctionJSON(getCompletions,[SDK.RemoteObject.toCallArgument(object.subtype)])||[];}else if(object.type==='string'||object.type==='number'||object.type==='boolean'||object.type==='bigint'){const evaluateResult=await executionContext.evaluate({expression:'('+getCompletions+')("'+object.type+'")',objectGroup:'completion',includeCommandLineAPI:false,silent:true,returnByValue:true,generatePreview:false},false,false);if(evaluateResult.object&&!evaluateResult.exceptionDetails)
completions=evaluateResult.object.value||[];}
executionContext.runtimeModel.releaseObjectGroup('completion');if(!expressionString){const globalNames=await executionContext.globalLexicalScopeNames();if(completions.length)
completions[0].items=completions[0].items.concat(globalNames);else
completions.push({items:globalNames.sort(),title:Common.UIString('Lexical scope variables')});}
for(const group of completions){for(let i=0;i<group.items.length;i++)
group.items[i]=group.items[i].replace(/\n/g,'\\n');group.items.sort(group.items.length<1000?this._itemComparator:undefined);}
return completions;function getCompletions(type){let object;if(type==='string')
object=new String('');else if(type==='number')
object=new Number(0);else if(type==='bigint')
object=Object(BigInt(0));else if(type==='boolean')
object=new Boolean(false);else
object=this;const result=[];try{for(let o=object;o;o=Object.getPrototypeOf(o)){if((type==='array'||type==='typedarray')&&o===object&&o.length>9999)
continue;const group={items:[],__proto__:null};try{if(typeof o==='object'&&Object.prototype.hasOwnProperty.call(o,'constructor')&&o.constructor&&o.constructor.name)
group.title=o.constructor.name;}catch(ee){}
result[result.length]=group;const names=Object.getOwnPropertyNames(o);const isArray=Array.isArray(o);for(let i=0;i<names.length&&group.items.length<10000;++i){if(isArray&&/^[0-9]/.test(names[i]))
continue;group.items[group.items.length]=names[i];}}}catch(e){}
return result;}}
async function completionsOnPause(callFrame){const result=[{items:['this']}];const scopeChain=callFrame.scopeChain();const groupPromises=[];for(const scope of scopeChain){groupPromises.push(scope.object().getAllProperties(false,false).then(result=>({properties:result.properties,name:scope.name()})));}
const fullScopes=await Promise.all(groupPromises);executionContext.runtimeModel.releaseObjectGroup('completion');for(const scope of fullScopes)
result.push({title:scope.name,items:scope.properties.map(property=>property.name).sort()});return result;}}
_receivedPropertyNames(propertyGroups,dotNotation,bracketNotation,expressionString,query){if(!propertyGroups)
return[];const includeCommandLineAPI=(!dotNotation&&!bracketNotation);if(includeCommandLineAPI){const commandLineAPI=['dir','dirxml','keys','values','profile','profileEnd','monitorEvents','unmonitorEvents','inspect','copy','clear','getEventListeners','debug','undebug','monitor','unmonitor','table','queryObjects','$','$$','$x','$0','$_'];propertyGroups.push({items:commandLineAPI});}
return this._completionsForQuery(dotNotation,bracketNotation,expressionString,query,propertyGroups);}
_completionsForQuery(dotNotation,bracketNotation,expressionString,query,propertyGroups){const quoteUsed=(bracketNotation&&query.startsWith('\''))?'\'':'"';if(!expressionString){const keywords=['await','break','case','catch','class','const','continue','debugger','default','delete','do','else','exports','extends','finally','for','function','if','import','in','instanceof','new','return','super','switch','this','throw','try','typeof','var','void','while','with','yield','let','static','async','of'];propertyGroups.push({title:ls`keywords`,items:keywords.sort()});}
const allProperties=new Set();let result=[];let lastGroupTitle;const regex=/^[a-zA-Z_$\u008F-\uFFFF][a-zA-Z0-9_$\u008F-\uFFFF]*$/;const lowerCaseQuery=query.toLowerCase();for(const group of propertyGroups){const caseSensitivePrefix=[];const caseInsensitivePrefix=[];const caseSensitiveAnywhere=[];const caseInsensitiveAnywhere=[];for(let i=0;i<group.items.length;i++){let property=group.items[i];if(!bracketNotation&&!regex.test(property))
continue;if(bracketNotation){if(!/^[0-9]+$/.test(property))
property=quoteUsed+property.escapeCharacters(quoteUsed+'\\')+quoteUsed;property+=']';}
if(allProperties.has(property))
continue;if(property.length<query.length)
continue;const lowerCaseProperty=property.toLowerCase();if(query.length&&lowerCaseProperty.indexOf(lowerCaseQuery)===-1)
continue;allProperties.add(property);if(property.startsWith(query))
caseSensitivePrefix.push({text:property,priority:property===query?5:4});else if(lowerCaseProperty.startsWith(lowerCaseQuery))
caseInsensitivePrefix.push({text:property,priority:3});else if(property.indexOf(query)!==-1)
caseSensitiveAnywhere.push({text:property,priority:2});else
caseInsensitiveAnywhere.push({text:property,priority:1});}
const structuredGroup=caseSensitivePrefix.concat(caseInsensitivePrefix,caseSensitiveAnywhere,caseInsensitiveAnywhere);if(structuredGroup.length&&group.title!==lastGroupTitle){structuredGroup[0].subtitle=group.title;lastGroupTitle=group.title;}
result=result.concat(structuredGroup);result.forEach(item=>{if(item.text.endsWith(']'))
item.title=item.text.substring(0,item.text.length-1);});}
return result;}
_itemComparator(a,b){const aStartsWithUnderscore=a.startsWith('_');const bStartsWithUnderscore=b.startsWith('_');if(aStartsWithUnderscore&&!bStartsWithUnderscore)
return 1;if(bStartsWithUnderscore&&!aStartsWithUnderscore)
return-1;return String.naturalOrderComparator(a,b);}
static async isExpressionComplete(expression){const currentExecutionContext=UI.context.flavor(SDK.ExecutionContext);if(!currentExecutionContext)
return true;const result=await currentExecutionContext.runtimeModel.compileScript(expression,'',false,currentExecutionContext.id);if(!result.exceptionDetails)
return true;const description=result.exceptionDetails.exception.description;return!description.startsWith('SyntaxError: Unexpected end of input')&&!description.startsWith('SyntaxError: Unterminated template literal');}};ObjectUI.JavaScriptAutocomplete.CompletionGroup;ObjectUI.javaScriptAutocomplete=new ObjectUI.JavaScriptAutocomplete();ObjectUI.JavaScriptAutocompleteConfig=class{constructor(editor){this._editor=editor;}
static createConfigForEditor(editor){const autocomplete=new ObjectUI.JavaScriptAutocompleteConfig(editor);return{substituteRangeCallback:autocomplete._substituteRange.bind(autocomplete),suggestionsCallback:autocomplete._suggestionsCallback.bind(autocomplete),tooltipCallback:autocomplete._tooltipCallback.bind(autocomplete),};}
_substituteRange(lineNumber,columnNumber){const token=this._editor.tokenAtTextPosition(lineNumber,columnNumber);if(token&&token.type==='js-string')
return new TextUtils.TextRange(lineNumber,token.startColumn,lineNumber,columnNumber);const lineText=this._editor.line(lineNumber);let index;for(index=columnNumber-1;index>=0;index--){if(' =:[({;,!+-*/&|^<>.\t\r\n'.indexOf(lineText.charAt(index))!==-1)
break;}
return new TextUtils.TextRange(lineNumber,index+1,lineNumber,columnNumber);}
async _suggestionsCallback(queryRange,substituteRange,force){const query=this._editor.text(queryRange);const before=this._editor.text(new TextUtils.TextRange(0,0,queryRange.startLine,queryRange.startColumn));const token=this._editor.tokenAtTextPosition(substituteRange.startLine,substituteRange.startColumn);if(token){const excludedTokens=new Set(['js-comment','js-string-2','js-def']);const trimmedBefore=before.trim();if(!trimmedBefore.endsWith('[')&&!trimmedBefore.match(/\.\s*(get|set|delete)\s*\(\s*$/))
excludedTokens.add('js-string');if(!trimmedBefore.endsWith('.'))
excludedTokens.add('js-property');if(excludedTokens.has(token.type))
return[];}
const queryAndAfter=this._editor.line(queryRange.startLine).substring(queryRange.startColumn);const words=await ObjectUI.javaScriptAutocomplete.completionsForTextInCurrentContext(before,query,force);if(!force&&queryAndAfter&&queryAndAfter!==query&&words.some(word=>queryAndAfter.startsWith(word.text)&&query.length!==word.text.length))
return[];return words;}
async _tooltipCallback(lineNumber,columnNumber){const before=this._editor.text(new TextUtils.TextRange(0,0,lineNumber,columnNumber));const result=await ObjectUI.javaScriptAutocomplete.argumentsHint(before);if(!result)
return null;const argumentIndex=result.argumentIndex;const tooltip=createElement('div');for(const args of result.args){const argumentsElement=createElement('span');for(let i=0;i<args.length;i++){if(i===argumentIndex||(i<argumentIndex&&args[i].startsWith('...')))
argumentsElement.appendChild(UI.html`<b>${args[i]}</b>`);else
argumentsElement.createTextChild(args[i]);if(i<args.length-1)
argumentsElement.createTextChild(', ');}
tooltip.appendChild(UI.html`<div class='source-code'>\u0192(${argumentsElement})</div>`);}
return tooltip;}};;ObjectUI.JavaScriptREPL=class{static wrapObjectLiteral(code){if(!(/^\s*\{/.test(code)&&/\}\s*$/.test(code)))
return code;const parse=(async()=>0).constructor;try{parse('return '+code+';');const wrappedCode='('+code+')';parse(wrappedCode);return wrappedCode;}catch(e){return code;}}
static async preprocessExpression(text){text=ObjectUI.JavaScriptREPL.wrapObjectLiteral(text);let preprocessed=false;if(text.indexOf('await')!==-1){const preprocessedText=await Formatter.formatterWorkerPool().preprocessTopLevelAwaitExpressions(text);preprocessed=!!preprocessedText;text=preprocessedText||text;}
return{text,preprocessed};}
static async evaluateAndBuildPreview(text,throwOnSideEffect,timeout,allowErrors,objectGroup){const executionContext=UI.context.flavor(SDK.ExecutionContext);const isTextLong=text.length>ObjectUI.JavaScriptREPL._MaxLengthForEvaluation;if(!text||!executionContext||(throwOnSideEffect&&isTextLong))
return{preview:createDocumentFragment(),result:null};const wrappedResult=await ObjectUI.JavaScriptREPL.preprocessExpression(text);const options={expression:wrappedResult.text,generatePreview:true,includeCommandLineAPI:true,throwOnSideEffect:throwOnSideEffect,timeout:timeout,objectGroup:objectGroup};const result=await executionContext.evaluate(options,false,wrappedResult.preprocessed);const preview=ObjectUI.JavaScriptREPL._buildEvaluationPreview(result,allowErrors);return{preview,result};}
static _buildEvaluationPreview(result,allowErrors){const fragment=createDocumentFragment();if(result.error)
return fragment;if(result.exceptionDetails&&result.exceptionDetails.exception&&result.exceptionDetails.exception.description){const exception=result.exceptionDetails.exception.description;if(exception.startsWith('TypeError: ')||allowErrors)
fragment.createChild('span').textContent=result.exceptionDetails.text+' '+exception;return fragment;}
const formatter=new ObjectUI.RemoteObjectPreviewFormatter();const{preview,type,subtype,description}=result.object;if(preview&&type==='object'&&subtype!=='node'){formatter.appendObjectPreview(fragment,preview,false);}else{const nonObjectPreview=formatter.renderPropertyPreview(type,subtype,description.trimEnd(400));fragment.appendChild(nonObjectPreview);}
return fragment;}};ObjectUI.JavaScriptREPL._MaxLengthForEvaluation=2000;;ObjectUI.RemoteObjectPreviewFormatter=class{static _objectPropertyComparator(a,b){return sortValue(a)-sortValue(b);function sortValue(property){const internalName=ObjectUI.RemoteObjectPreviewFormatter._internalName;if(property.name===internalName.PromiseStatus)
return 1;else if(property.name===internalName.PromiseValue)
return 2;else if(property.name===internalName.GeneratorStatus||internalName.PrimitiveValue)
return 3;else if(property.type!=='function')
return 4;return 5;}}
appendObjectPreview(parentElement,preview,isEntry){const description=preview.description;const subTypesWithoutValuePreview=new Set(['null','regexp','error','internal#entry']);if(preview.type!=='object'||subTypesWithoutValuePreview.has(preview.subtype)||isEntry){parentElement.appendChild(this.renderPropertyPreview(preview.type,preview.subtype,description));return;}
const isArrayOrTypedArray=preview.subtype==='array'||preview.subtype==='typedarray';if(description){let text;if(isArrayOrTypedArray){const arrayLength=SDK.RemoteObject.arrayLength(preview);const arrayLengthText=arrayLength>1?('('+arrayLength+')'):'';const arrayName=SDK.RemoteObject.arrayNameFromDescription(description);text=arrayName==='Array'?arrayLengthText:(arrayName+arrayLengthText);}else{const hideDescription=description==='Object';text=hideDescription?'':description;}
if(text.length>0)
parentElement.createChild('span','object-description').textContent=text+'\u00a0';}
const propertiesElement=parentElement.createChild('span','object-properties-preview');propertiesElement.createTextChild(isArrayOrTypedArray?'[':'{');if(preview.entries)
this._appendEntriesPreview(propertiesElement,preview);else if(isArrayOrTypedArray)
this._appendArrayPropertiesPreview(propertiesElement,preview);else
this._appendObjectPropertiesPreview(propertiesElement,preview);if(preview.overflow){const ellipsisText=propertiesElement.textContent.length>1?',\u00a0\u2026':'\u2026';propertiesElement.createChild('span').textContent=ellipsisText;}
propertiesElement.createTextChild(isArrayOrTypedArray?']':'}');}
_abbreviateFullQualifiedClassName(description){const abbreviatedDescription=description.split('.');for(let i=0;i<abbreviatedDescription.length-1;++i)
abbreviatedDescription[i]=abbreviatedDescription[i].trimMiddle(3);return abbreviatedDescription.join('.');}
_appendObjectPropertiesPreview(parentElement,preview){const internalName=ObjectUI.RemoteObjectPreviewFormatter._internalName;const properties=preview.properties.filter(p=>p.type!=='accessor').stableSort(ObjectUI.RemoteObjectPreviewFormatter._objectPropertyComparator);for(let i=0;i<properties.length;++i){if(i>0)
parentElement.createTextChild(', ');const property=properties[i];const name=property.name;if(preview.subtype==='promise'&&name===internalName.PromiseStatus){parentElement.appendChild(this._renderDisplayName('<'+property.value+'>'));const nextProperty=i+1<properties.length?properties[i+1]:null;if(nextProperty&&nextProperty.name===internalName.PromiseValue){if(property.value!=='pending'){parentElement.createTextChild(': ');parentElement.appendChild(this._renderPropertyPreviewOrAccessor([nextProperty]));}
i++;}}else if(preview.subtype==='generator'&&name===internalName.GeneratorStatus){parentElement.appendChild(this._renderDisplayName('<'+property.value+'>'));}else if(name===internalName.PrimitiveValue){parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));}else{parentElement.appendChild(this._renderDisplayName(name));parentElement.createTextChild(': ');parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));}}}
_appendArrayPropertiesPreview(parentElement,preview){const arrayLength=SDK.RemoteObject.arrayLength(preview);const indexProperties=preview.properties.filter(p=>toArrayIndex(p.name)!==-1).stableSort(arrayEntryComparator);const otherProperties=preview.properties.filter(p=>toArrayIndex(p.name)===-1).stableSort(ObjectUI.RemoteObjectPreviewFormatter._objectPropertyComparator);function arrayEntryComparator(a,b){return toArrayIndex(a.name)-toArrayIndex(b.name);}
function toArrayIndex(name){const index=name>>>0;if(String(index)===name&&index<arrayLength)
return index;return-1;}
const canShowGaps=!preview.overflow;let lastNonEmptyArrayIndex=-1;let elementsAdded=false;for(let i=0;i<indexProperties.length;++i){if(elementsAdded)
parentElement.createTextChild(', ');const property=indexProperties[i];const index=toArrayIndex(property.name);if(canShowGaps&&index-lastNonEmptyArrayIndex>1){appendUndefined(index);parentElement.createTextChild(', ');}
if(!canShowGaps&&i!==index){parentElement.appendChild(this._renderDisplayName(property.name));parentElement.createTextChild(': ');}
parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));lastNonEmptyArrayIndex=index;elementsAdded=true;}
if(canShowGaps&&arrayLength-lastNonEmptyArrayIndex>1){if(elementsAdded)
parentElement.createTextChild(', ');appendUndefined(arrayLength);}
for(let i=0;i<otherProperties.length;++i){if(elementsAdded)
parentElement.createTextChild(', ');const property=otherProperties[i];parentElement.appendChild(this._renderDisplayName(property.name));parentElement.createTextChild(': ');parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));elementsAdded=true;}
function appendUndefined(index){const span=parentElement.createChild('span','object-value-undefined');const count=index-lastNonEmptyArrayIndex-1;span.textContent=count!==1?Common.UIString('empty × %d',count):Common.UIString('empty');elementsAdded=true;}}
_appendEntriesPreview(parentElement,preview){for(let i=0;i<preview.entries.length;++i){if(i>0)
parentElement.createTextChild(', ');const entry=preview.entries[i];if(entry.key){this.appendObjectPreview(parentElement,entry.key,true);parentElement.createTextChild(' => ');}
this.appendObjectPreview(parentElement,entry.value,true);}}
_renderDisplayName(name){const result=createElementWithClass('span','name');const needsQuotes=/^\s|\s$|^$|\n/.test(name);result.textContent=needsQuotes?'"'+name.replace(/\n/g,'\u21B5')+'"':name;return result;}
_renderPropertyPreviewOrAccessor(propertyPath){const property=propertyPath.peekLast();return this.renderPropertyPreview(property.type,(property.subtype),property.value);}
renderPropertyPreview(type,subtype,description){const span=createElementWithClass('span','object-value-'+(subtype||type));description=description||'';if(type==='accessor'){span.textContent='(...)';span.title=Common.UIString('The property is computed with a getter');return span;}
if(type==='function'){span.textContent='\u0192';return span;}
if(type==='object'&&subtype==='node'&&description){ObjectUI.RemoteObjectPreviewFormatter.createSpansForNodeTitle(span,description);return span;}
if(type==='string'){span.createTextChildren('"',description.replace(/\n/g,'\u21B5'),'"');return span;}
if(type==='object'&&!subtype){let preview=this._abbreviateFullQualifiedClassName(description);if(preview==='Object')
preview='{\u2026}';span.textContent=preview;span.title=description;return span;}
span.textContent=description;return span;}};ObjectUI.RemoteObjectPreviewFormatter._internalName={GeneratorStatus:'[[GeneratorStatus]]',PrimitiveValue:'[[PrimitiveValue]]',PromiseStatus:'[[PromiseStatus]]',PromiseValue:'[[PromiseValue]]'};ObjectUI.RemoteObjectPreviewFormatter.createSpansForNodeTitle=function(container,nodeTitle){const match=nodeTitle.match(/([^#.]+)(#[^.]+)?(\..*)?/);container.createChild('span','webkit-html-tag-name').textContent=match[1];if(match[2])
container.createChild('span','webkit-html-attribute-value').textContent=match[2];if(match[3])
container.createChild('span','webkit-html-attribute-name').textContent=match[3];};;Runtime.cachedResources["object_ui/customPreviewComponent.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.custom-expandable-section {\n display: inline-flex;\n flex-direction: column;\n}\n\n.custom-expand-icon {\n -webkit-user-select: none;\n opacity: 0.5;\n margin-right: 4px;\n margin-bottom: -2px;\n background: black;\n}\n\n.custom-expandable-section-standard-section {\n display: inline-flex;\n}\n/*# sourceURL=object_ui/customPreviewComponent.css */";Runtime.cachedResources["object_ui/objectPopover.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.object-popover-content {\n display: block;\n position: relative;\n overflow: hidden;\n flex: 1 1 auto;\n}\n\n.object-popover-title {\n text-overflow: ellipsis;\n overflow: hidden;\n white-space: nowrap;\n font-weight: bold;\n padding-left: 18px;\n padding-bottom: 2px;\n}\n\n.object-popover-tree {\n border-top: 1px solid rgb(184, 184, 184);\n overflow: auto;\n width: 100%;\n height: calc(100% - 13px);\n}\n\n.object-popover-container {\n display: inline-block;\n}\n\n.function-popover-title {\n border-bottom: 1px solid #AAA;\n margin-bottom: 3px;\n padding-bottom: 2px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n.function-popover-title .function-name {\n font-weight: bold;\n}\n\n.function-title-link-container {\n display: flex;\n align-items: center;\n position: relative;\n margin-left: 10px;\n}\n\n.function-title-link-container .devtools-link {\n white-space: nowrap;\n overflow: hidden;\n}\n\n/*# sourceURL=object_ui/objectPopover.css */";Runtime.cachedResources["object_ui/objectPropertiesSection.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.object-properties-section-dimmed {\n opacity: 0.6;\n}\n\n.object-properties-section {\n padding: 0 0 0px 0px;\n color: rgb(33,33,33) !important;\n display: flex;\n flex-direction: column;\n}\n\n.object-properties-section li {\n -webkit-user-select: text;\n}\n\n.object-properties-section li::before {\n top: -1px;\n}\n\n.object-properties-section li.editing-sub-part {\n padding: 3px 12px 8px 6px;\n margin: -1px -6px -8px -6px;\n text-overflow: clip;\n}\n\n.object-properties-section li.editing {\n margin-left: 10px;\n text-overflow: clip;\n}\n\n.tree-outline ol.title-less-mode {\n padding-left: 0px;\n}\n\n.object-properties-section .synthetic-property {\n font-style: italic;\n}\n\n.object-properties-section-root-element {\n display: flex;\n flex-direction: row;\n}\n\n.object-properties-section .editable-div {\n overflow: hidden;\n}\n\n.name-and-value {\n overflow: hidden;\n text-overflow: ellipsis;\n line-height: 16px;\n}\n\n.editing-sub-part .name-and-value {\n overflow: visible;\n display: inline-flex;\n}\n\n.property-prompt {\n margin-left: 4px;\n}\n\n.tree-outline.hide-selection-when-blurred .selected:focus[data-keyboard-focus=\"true\"] {\n background: none;\n}\n\n.tree-outline.hide-selection-when-blurred .selected:focus[data-keyboard-focus=\"true\"] ::slotted(*),\n.tree-outline.hide-selection-when-blurred .selected:focus[data-keyboard-focus=\"true\"] .name-and-value {\n background: var(--focus-bg-color);\n border-radius: 2px;\n box-shadow: 0px 0px 0px 2px var(--focus-bg-color);\n}\n\n/*# sourceURL=object_ui/objectPropertiesSection.css */";Runtime.cachedResources["object_ui/objectValue.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that c
alwaysShowVerticalScroll(){this._alwaysShowVerticalScroll=true;this._vScrollElement.classList.add('always-show-scrollbar');}
disableRangeSelection(){this._rangeSelectionEnabled=false;this._rangeSelectionStart=null;this._rangeSelectionEnd=null;this._updateRangeSelectionOverlay();}
isDragging(){return this._isDragging;}
elementsToRestoreScrollPositionsFor(){return[this._vScrollElement];}
_updateScrollBar(){const showScroll=this._alwaysShowVerticalScroll||this._totalHeight>this._offsetHeight;if(this._vScrollElement.classList.contains('hidden')!==showScroll)
return;this._vScrollElement.classList.toggle('hidden',!showScroll);this._updateContentElementSize();}
onResize(){this._updateScrollBar();this._updateContentElementSize();this.scheduleUpdate();}
reset(){this._vScrollElement.scrollTop=0;this._scrollTop=0;this._rangeSelectionStart=null;this._rangeSelectionEnd=null;this._isDragging=false;this._dragStartPointX=0;this._dragStartPointY=0;this._dragStartScrollTop=0;this._visibleLeftTime=0;this._visibleRightTime=0;this._offsetWidth=0;this._offsetHeight=0;this._totalHeight=0;this._targetLeftTime=0;this._targetRightTime=0;this._updateContentElementSize();}
_updateContentElementSize(){let offsetWidth=this._vScrollElement.offsetLeft;if(!offsetWidth)
offsetWidth=this.contentElement.offsetWidth;this._offsetWidth=offsetWidth;this._offsetHeight=this.contentElement.offsetHeight;this._delegate.setSize(this._offsetWidth,this._offsetHeight);}
setContentHeight(totalHeight){this._totalHeight=totalHeight;this._vScrollContent.style.height=totalHeight+'px';this._updateScrollBar();if(this._scrollTop+this._offsetHeight<=totalHeight)
return;this._scrollTop=Math.max(0,totalHeight-this._offsetHeight);this._vScrollElement.scrollTop=this._scrollTop;}
setScrollOffset(offset,height){height=height||0;if(this._vScrollElement.scrollTop>offset)
this._vScrollElement.scrollTop=offset;else if(this._vScrollElement.scrollTop<offset-this._offsetHeight+height)
this._vScrollElement.scrollTop=offset-this._offsetHeight+height;}
scrollOffset(){return this._vScrollElement.scrollTop;}
setBoundaries(zeroTime,totalTime){this._minimumBoundary=zeroTime;this._totalTime=totalTime;}
_onMouseWheel(e){const doZoomInstead=e.shiftKey^(Common.moduleSetting('flamechartMouseWheelAction').get()==='zoom');const panVertically=!doZoomInstead&&(e.wheelDeltaY||Math.abs(e.wheelDeltaX)===120);const panHorizontally=doZoomInstead&&Math.abs(e.wheelDeltaX)>Math.abs(e.wheelDeltaY);if(panVertically){this._vScrollElement.scrollTop-=(e.wheelDeltaY||e.wheelDeltaX)/120*this._offsetHeight/8;}else if(panHorizontally){this._handlePanGesture(-e.wheelDeltaX,true);}else{const mouseWheelZoomSpeed=1/120;this._handleZoomGesture(Math.pow(1.2,-(e.wheelDeltaY||e.wheelDeltaX)*mouseWheelZoomSpeed)-1);}
e.consume(true);}
_startDragging(event){if(event.shiftKey)
return false;this._isDragging=true;this._dragStartPointX=event.pageX;this._dragStartPointY=event.pageY;this._dragStartScrollTop=this._vScrollElement.scrollTop;this.viewportElement.style.cursor='';return true;}
_dragging(event){const pixelShift=this._dragStartPointX-event.pageX;this._dragStartPointX=event.pageX;this._handlePanGesture(pixelShift);const pixelScroll=this._dragStartPointY-event.pageY;this._vScrollElement.scrollTop=this._dragStartScrollTop+pixelScroll;}
_endDragging(){this._isDragging=false;}
_startRangeSelection(event){if(!event.shiftKey||!this._rangeSelectionEnabled)
return false;this._isDragging=true;this._selectionOffsetShiftX=event.offsetX-event.pageX;this._selectionOffsetShiftY=event.offsetY-event.pageY;this._selectionStartX=event.offsetX;const style=this._selectionOverlay.style;style.left=this._selectionStartX+'px';style.width='1px';this._selectedTimeSpanLabel.textContent='';this._selectionOverlay.classList.remove('hidden');return true;}
_endRangeSelection(){this._isDragging=false;this._selectionStartX=null;}
hideRangeSelection(){this._selectionOverlay.classList.add('hidden');this._rangeSelectionStart=null;this._rangeSelectionEnd=null;}
setRangeSelection(startTime,endTime){if(!this._rangeSelectionEnabled)
return;this._rangeSelectionStart=Math.min(startTime,endTime);this._rangeSelectionEnd=Math.max(startTime,endTime);this._updateRangeSelectionOverlay();this._delegate.updateRangeSelection(this._rangeSelectionStart,this._rangeSelectionEnd);}
onClick(event){const time=this.pixelToTime(event.offsetX);if(this._rangeSelectionStart!==null&&time>=this._rangeSelectionStart&&time<=this._rangeSelectionEnd)
return;this.hideRangeSelection();}
_rangeSelectionDragging(event){const x=Number.constrain(event.pageX+this._selectionOffsetShiftX,0,this._offsetWidth);const start=this.pixelToTime(this._selectionStartX);const end=this.pixelToTime(x);this.setRangeSelection(start,end);}
_updateRangeSelectionOverlay(){const margin=100;const left=Number.constrain(this.timeToPosition(this._rangeSelectionStart),-margin,this._offsetWidth+margin);const right=Number.constrain(this.timeToPosition(this._rangeSelectionEnd),-margin,this._offsetWidth+margin);const style=this._selectionOverlay.style;style.left=left+'px';style.width=(right-left)+'px';const timeSpan=this._rangeSelectionEnd-this._rangeSelectionStart;this._selectedTimeSpanLabel.textContent=Number.preciseMillisToString(timeSpan,2);}
_onScroll(){this._scrollTop=this._vScrollElement.scrollTop;this.scheduleUpdate();}
_onMouseOut(){this._lastMouseOffsetX=-1;this._showCursor(false);}
_updateCursorPosition(e){this._showCursor(e.shiftKey);this._cursorElement.style.left=e.offsetX+'px';this._lastMouseOffsetX=e.offsetX;}
pixelToTime(x){return this.pixelToTimeOffset(x)+this._visibleLeftTime;}
pixelToTimeOffset(x){return x*(this._visibleRightTime-this._visibleLeftTime)/this._offsetWidth;}
timeToPosition(time){return Math.floor((time-this._visibleLeftTime)/(this._visibleRightTime-this._visibleLeftTime)*this._offsetWidth);}
timeToPixel(){return this._offsetWidth/(this._visibleRightTime-this._visibleLeftTime);}
_showCursor(visible){this._cursorElement.classList.toggle('hidden',!visible||this._isDragging);}
_onChartKeyDown(e){this._showCursor(e.shiftKey);this._handleZoomPanKeys(e);}
_onChartKeyUp(e){this._showCursor(e.shiftKey);}
_handleZoomPanKeys(e){if(!UI.KeyboardShortcut.hasNoModifiers(e))
return;const zoomFactor=e.shiftKey?0.8:0.3;const panOffset=e.shiftKey?320:160;switch(e.code){case'KeyA':this._handlePanGesture(-panOffset,true);break;case'KeyD':this._handlePanGesture(panOffset,true);break;case'KeyW':this._handleZoomGesture(-zoomFactor);break;case'KeyS':this._handleZoomGesture(zoomFactor);break;default:return;}
e.consume(true);}
_handleZoomGesture(zoom){const bounds={left:this._targetLeftTime,right:this._targetRightTime};const cursorTime=this.pixelToTime(this._lastMouseOffsetX);bounds.left+=(bounds.left-cursorTime)*zoom;bounds.right+=(bounds.right-cursorTime)*zoom;this._requestWindowTimes(bounds,true);}
_handlePanGesture(offset,animate){const bounds={left:this._targetLeftTime,right:this._targetRightTime};const timeOffset=Number.constrain(this.pixelToTimeOffset(offset),this._minimumBoundary-bounds.left,this._totalTime+this._minimumBoundary-bounds.right);bounds.left+=timeOffset;bounds.right+=timeOffset;this._requestWindowTimes(bounds,!!animate);}
_requestWindowTimes(bounds,animate){const maxBound=this._minimumBoundary+this._totalTime;if(bounds.left<this._minimumBoundary){bounds.right=Math.min(bounds.right+this._minimumBoundary-bounds.left,maxBound);bounds.left=this._minimumBoundary;}else if(bounds.right>maxBound){bounds.left=Math.max(bounds.left-bounds.right+maxBound,this._minimumBoundary);bounds.right=maxBound;}
if(bounds.right-bounds.left<PerfUI.FlameChart.MinimalTimeWindowMs)
return;this._delegate.windowChanged(bounds.left,bounds.right,animate);}
scheduleUpdate(){if(this._updateTimerId||this._cancelWindowTimesAnimation)
return;this._updateTimerId=this.element.window().requestAnimationFrame(()=>{this._updateTimerId=0;this._update();});}
_update(){this._updateRangeSelectionOverlay();this._delegate.update();}
setWindowTimes(startTime,endTime,animate){if(startTime===this._targetLeftTime&&endTime===this._targetRightTime)
return;if(!animate||this._visibleLeftTime===0||this._visibleRightTime===Infinity||(startTime===0&&endTime===Infinity)||(startTime===Infinity&&endTime===Infinity)){this._targetLeftTime=startTime;this._targetRightTime=endTime;this._visibleLeftTime=startTime;this._visibleRightTime=endTime;this.scheduleUpdate();return;}
if(this._cancelWindowTimesAnimation){this._cancelWindowTimesAnimation();this._visibleLeftTime=this._targetLeftTime;this._visibleRightTime=this._targetRightTime;}
this._targetLeftTime=startTime;this._targetRightTime=endTime;this._cancelWindowTimesAnimation=UI.animateFunction(this.element.window(),animateWindowTimes.bind(this),[{from:this._visibleLeftTime,to:startTime},{from:this._visibleRightTime,to:endTime}],100,()=>this._cancelWindowTimesAnimation=null);function animateWindowTimes(startTime,endTime){this._visibleLeftTime=startTime;this._visibleRightTime=endTime;this._update();}}
windowLeftTime(){return this._visibleLeftTime;}
windowRightTime(){return this._visibleRightTime;}};;PerfUI.FilmStripView=class extends UI.HBox{constructor(){super(true);this.registerRequiredCSS('perf_ui/filmStripView.css');this.contentElement.classList.add('film-strip-view');this._statusLabel=this.contentElement.createChild('div','label');this.reset();this.setMode(PerfUI.FilmStripView.Modes.TimeBased);}
static _setImageData(imageElement,data){if(data)
imageElement.src='data:image/jpg;base64,'+data;}
setMode(mode){this._mode=mode;this.contentElement.classList.toggle('time-based',mode===PerfUI.FilmStripView.Modes.TimeBased);this.update();}
setModel(filmStripModel,zeroTime,spanTime){this._model=filmStripModel;this._zeroTime=zeroTime;this._spanTime=spanTime;const frames=filmStripModel.frames();if(!frames.length){this.reset();return;}
this.update();}
createFrameElement(frame){const time=frame.timestamp;const element=createElementWithClass('div','frame');element.title=Common.UIString('Doubleclick to zoom image. Click to view preceding requests.');element.createChild('div','time').textContent=Number.millisToString(time-this._zeroTime);const imageElement=element.createChild('div','thumbnail').createChild('img');element.addEventListener('mousedown',this._onMouseEvent.bind(this,PerfUI.FilmStripView.Events.FrameSelected,time),false);element.addEventListener('mouseenter',this._onMouseEvent.bind(this,PerfUI.FilmStripView.Events.FrameEnter,time),false);element.addEventListener('mouseout',this._onMouseEvent.bind(this,PerfUI.FilmStripView.Events.FrameExit,time),false);element.addEventListener('dblclick',this._onDoubleClick.bind(this,frame),false);return frame.imageDataPromise().then(PerfUI.FilmStripView._setImageData.bind(null,imageElement)).then(returnElement);function returnElement(){return element;}}
frameByTime(time){function comparator(time,frame){return time-frame.timestamp;}
const frames=this._model.frames();const index=Math.max(frames.upperBound(time,comparator)-1,0);return frames[index];}
update(){if(!this._model)
return;const frames=this._model.frames();if(!frames.length)
return;if(this._mode===PerfUI.FilmStripView.Modes.FrameBased){Promise.all(frames.map(this.createFrameElement.bind(this))).then(appendElements.bind(this));return;}
const width=this.contentElement.clientWidth;const scale=this._spanTime/width;this.createFrameElement(frames[0]).then(continueWhenFrameImageLoaded.bind(this));function continueWhenFrameImageLoaded(element0){const frameWidth=Math.ceil(UI.measurePreferredSize(element0,this.contentElement).width);if(!frameWidth)
return;const promises=[];for(let pos=frameWidth;pos<width;pos+=frameWidth){const time=pos*scale+this._zeroTime;promises.push(this.createFrameElement(this.frameByTime(time)).then(fixWidth));}
Promise.all(promises).then(appendElements.bind(this));function fixWidth(element){element.style.width=frameWidth+'px';return element;}}
function appendElements(elements){this.contentElement.removeChildren();for(let i=0;i<elements.length;++i)
this.contentElement.appendChild(elements[i]);}}
onResize(){if(this._mode===PerfUI.FilmStripView.Modes.FrameBased)
return;this.update();}
_onMouseEvent(eventName,timestamp){this.dispatchEventToListeners(eventName,timestamp);}
_onDoubleClick(filmStripFrame){new PerfUI.FilmStripView.Dialog(filmStripFrame,this._zeroTime);}
reset(){this._zeroTime=0;this.contentElement.removeChildren();this.contentElement.appendChild(this._statusLabel);}
setStatusText(text){this._statusLabel.textContent=text;}};PerfUI.FilmStripView.Events={FrameSelected:Symbol('FrameSelected'),FrameEnter:Symbol('FrameEnter'),FrameExit:Symbol('FrameExit'),};PerfUI.FilmStripView.Modes={TimeBased:'TimeBased',FrameBased:'FrameBased'};PerfUI.FilmStripView.Dialog=class{constructor(filmStripFrame,zeroTime){const prevButton=UI.createTextButton('\u25C0',this._onPrevFrame.bind(this));prevButton.title=Common.UIString('Previous frame');const nextButton=UI.createTextButton('\u25B6',this._onNextFrame.bind(this));nextButton.title=Common.UIString('Next frame');this._fragment=UI.Fragment.build`
<x-widget flex=none margin=12px>
<x-hbox overflow=auto border='1px solid #ddd' max-height=80vh max-width=80vw>
<img $=image></img>
</x-hbox>
<x-hbox x-center justify-content=center margin-top=10px>
${prevButton}
<x-hbox $=time margin=8px></x-hbox>
${nextButton}
</x-hbox>
</x-widget>
`;this._widget=(this._fragment.element());this._widget.tabIndex=0;this._widget.addEventListener('keydown',this._keyDown.bind(this),false);this._frames=filmStripFrame.model().frames();this._index=filmStripFrame.index;this._zeroTime=zeroTime||filmStripFrame.model().zeroTime();this._dialog=null;this._render();}
_resize(){if(!this._dialog){this._dialog=new UI.Dialog();this._dialog.contentElement.appendChild(this._widget);this._dialog.setDefaultFocusedElement(this._widget);this._dialog.show();}
this._dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);}
_keyDown(event){switch(event.key){case'ArrowLeft':if(Host.isMac()&&event.metaKey)
this._onFirstFrame();else
this._onPrevFrame();break;case'ArrowRight':if(Host.isMac()&&event.metaKey)
this._onLastFrame();else
this._onNextFrame();break;case'Home':this._onFirstFrame();break;case'End':this._onLastFrame();break;}}
_onPrevFrame(){if(this._index>0)
--this._index;this._render();}
_onNextFrame(){if(this._index<this._frames.length-1)
++this._index;this._render();}
_onFirstFrame(){this._index=0;this._render();}
_onLastFrame(){this._index=this._frames.length-1;this._render();}
_render(){const frame=this._frames[this._index];this._fragment.$('time').textContent=Number.millisToString(frame.timestamp-this._zeroTime);return frame.imageDataPromise().then(PerfUI.FilmStripView._setImageData.bind(null,this._fragment.$('image'))).then(this._resize.bind(this));}};;PerfUI.FlameChartDelegate=function(){};PerfUI.FlameChartDelegate.prototype={windowChanged(startTime,endTime,animate){},updateRangeSelection(startTime,endTime){},updateSelectedGroup(flameChart,group){},};PerfUI.FlameChart=class extends UI.VBox{constructor(dataProvider,flameChartDelegate,groupExpansionSetting){super(true);this.registerRequiredCSS('perf_ui/flameChart.css');this.contentElement.classList.add('flame-chart-main-pane');this._groupExpansionSetting=groupExpansionSetting;this._groupExpansionState=groupExpansionSetting&&groupExpansionSetting.get()||{};this._flameChartDelegate=flameChartDelegate;this._useWebGL=Runtime.experiments.isEnabled('timelineWebGL');this._chartViewport=new PerfUI.ChartViewport(this);this._chartViewport.show(this.contentElement);this._dataProvider=dataProvider;this._viewportElement=this._chartViewport.viewportElement;if(this._useWebGL){this._canvasGL=(this._viewportElement.createChild('canvas','fill'));this._initWebGL();}
this._canvas=(this._viewportElement.createChild('canvas','fill'));this._canvas.tabIndex=0;this.setDefaultFocusedElement(this._canvas);this._canvas.addEventListener('mousemove',this._onMouseMove.bind(this),false);this._canvas.addEventListener('mouseout',this._onMouseOut.bind(this),false);this._canvas.addEventListener('click',this._onClick.bind(this),false);this._canvas.addEventListener('keydown',this._onKeyDown.bind(this),false);this._entryInfo=this._viewportElement.createChild('div','flame-chart-entry-info');this._markerHighlighElement=this._viewportElement.createChild('div','flame-chart-marker-highlight-element');this._highlightElement=this._viewportElement.createChild('div','flame-chart-highlight-element');this._selectedElement=this._viewportElement.createChild('div','flame-chart-selected-element');UI.installDragHandle(this._viewportElement,this._startDragging.bind(this),this._dragging.bind(this),this._endDragging.bind(this),null);this._rulerEnabled=true;this._rangeSelectionStart=0;this._rangeSelectionEnd=0;this._barHeight=17;this._textBaseline=5;this._textPadding=5;this._markerRadius=6;this._chartViewport.setWindowTimes(dataProvider.minimumBoundary(),dataProvider.minimumBoundary()+dataProvider.totalTime());this._headerLeftPadding=6;this._arrowSide=8;this._expansionArrowIndent=this._headerLeftPadding+this._arrowSide/2;this._headerLabelXPadding=3;this._headerLabelYPadding=2;this._highlightedMarkerIndex=-1;this._highlightedEntryIndex=-1;this._selectedEntryIndex=-1;this._rawTimelineDataLength=0;this._textWidth=new Map();this._markerPositions=new Map();this._lastMouseOffsetX=0;this._selectedGroup=-1;this._selectedGroupBackroundColor=UI.themeSupport.patchColorText(PerfUI.FlameChart.Colors.SelectedGroupBackground,UI.ThemeSupport.ColorUsage.Background);this._selectedGroupBorderColor=UI.themeSupport.patchColorText(PerfUI.FlameChart.Colors.SelectedGroupBorder,UI.ThemeSupport.ColorUsage.Background);}
willHide(){this.hideHighlight();}
setBarHeight(value){this._barHeight=value;}
setTextBaseline(value){this._textBaseline=value;}
setTextPadding(value){this._textPadding=value;}
enableRuler(enable){this._rulerEnabled=enable;}
alwaysShowVerticalScroll(){this._chartViewport.alwaysShowVerticalScroll();}
disableRangeSelection(){this._chartViewport.disableRangeSelection();}
highlightEntry(entryIndex){if(this._highlightedEntryIndex===entryIndex)
return;if(!this._dataProvider.entryColor(entryIndex))
return;this._highlightedEntryIndex=entryIndex;this._updateElementPosition(this._highlightElement,this._highlightedEntryIndex);this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntryHighlighted,entryIndex);}
hideHighlight(){this._entryInfo.removeChildren();this._highlightedEntryIndex=-1;this._updateElementPosition(this._highlightElement,this._highlightedEntryIndex);this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntryHighlighted,-1);}
_resetCanvas(){const ratio=window.devicePixelRatio;const width=Math.round(this._offsetWidth*ratio);const height=Math.round(this._offsetHeight*ratio);this._canvas.width=width;this._canvas.height=height;this._canvas.style.width=`${width / ratio}px`;this._canvas.style.height=`${height / ratio}px`;if(this._useWebGL){this._canvasGL.width=width;this._canvasGL.height=height;this._canvasGL.style.width=`${width / ratio}px`;this._canvasGL.style.height=`${height / ratio}px`;}}
windowChanged(startTime,endTime,animate){this._flameChartDelegate.windowChanged(startTime,endTime,animate);}
updateRangeSelection(startTime,endTime){this._flameChartDelegate.updateRangeSelection(startTime,endTime);}
setSize(width,height){this._offsetWidth=width;this._offsetHeight=height;}
_startDragging(event){this.hideHighlight();this._maxDragOffset=0;this._dragStartX=event.pageX;this._dragStartY=event.pageY;return true;}
_dragging(event){const dx=event.pageX-this._dragStartX;const dy=event.pageY-this._dragStartY;this._maxDragOffset=Math.max(this._maxDragOffset,Math.sqrt(dx*dx+dy*dy));}
_endDragging(event){this._updateHighlight();}
_timelineData(){if(!this._dataProvider)
return null;const timelineData=this._dataProvider.timelineData();if(timelineData!==this._rawTimelineData||timelineData.entryStartTimes.length!==this._rawTimelineDataLength)
this._processTimelineData(timelineData);return this._rawTimelineData;}
_revealEntry(entryIndex){const timelineData=this._timelineData();if(!timelineData)
return;const timeLeft=this._chartViewport.windowLeftTime();const timeRight=this._chartViewport.windowRightTime();const entryStartTime=timelineData.entryStartTimes[entryIndex];const entryTotalTime=timelineData.entryTotalTimes[entryIndex];const entryEndTime=entryStartTime+entryTotalTime;let minEntryTimeWindow=Math.min(entryTotalTime,timeRight-timeLeft);const level=timelineData.entryLevels[entryIndex];this._chartViewport.setScrollOffset(this._levelToOffset(level),this._levelHeight(level));const minVisibleWidthPx=30;const futurePixelToTime=(timeRight-timeLeft)/this._offsetWidth;minEntryTimeWindow=Math.max(minEntryTimeWindow,futurePixelToTime*minVisibleWidthPx);if(timeLeft>entryEndTime){const delta=timeLeft-entryEndTime+minEntryTimeWindow;this.windowChanged(timeLeft-delta,timeRight-delta,true);}else if(timeRight<entryStartTime){const delta=entryStartTime-timeRight+minEntryTimeWindow;this.windowChanged(timeLeft+delta,timeRight+delta,true);}}
setWindowTimes(startTime,endTime,animate){this._chartViewport.setWindowTimes(startTime,endTime,animate);this._updateHighlight();}
_onMouseMove(event){this._lastMouseOffsetX=event.offsetX;this._lastMouseOffsetY=event.offsetY;if(!this._enabled())
return;if(this._chartViewport.isDragging())
return;if(this._coordinatesToGroupIndex(event.offsetX,event.offsetY,true)>=0){this.hideHighlight();this._viewportElement.style.cursor='pointer';return;}
this._updateHighlight();}
_updateHighlight(){const entryIndex=this._coordinatesToEntryIndex(this._lastMouseOffsetX,this._lastMouseOffsetY);if(entryIndex===-1){this.hideHighlight();const group=this._coordinatesToGroupIndex(this._lastMouseOffsetX,this._lastMouseOffsetY,false);if(group>=0&&this._rawTimelineData.groups[group].selectable)
this._viewportElement.style.cursor='pointer';else
this._viewportElement.style.cursor='default';return;}
if(this._chartViewport.isDragging())
return;this._updatePopover(entryIndex);this._viewportElement.style.cursor=this._dataProvider.canJumpToEntry(entryIndex)?'pointer':'default';this.highlightEntry(entryIndex);}
_onMouseOut(){this._lastMouseOffsetX=-1;this._lastMouseOffsetY=-1;this.hideHighlight();}
_updatePopover(entryIndex){if(entryIndex===this._highlightedEntryIndex){this._updatePopoverOffset();return;}
this._entryInfo.removeChildren();const popoverElement=this._dataProvider.prepareHighlightedEntryInfo(entryIndex);if(popoverElement){this._entryInfo.appendChild(popoverElement);this._updatePopoverOffset();}}
_updatePopoverOffset(){const mouseX=this._lastMouseOffsetX;const mouseY=this._lastMouseOffsetY;const parentWidth=this._entryInfo.parentElement.clientWidth;const parentHeight=this._entryInfo.parentElement.clientHeight;const infoWidth=this._entryInfo.clientWidth;const infoHeight=this._entryInfo.clientHeight;const offsetX=10;const offsetY=6;let x;let y;for(let quadrant=0;quadrant<4;++quadrant){const dx=quadrant&2?-offsetX-infoWidth:offsetX;const dy=quadrant&1?-offsetY-infoHeight:offsetY;x=Number.constrain(mouseX+dx,0,parentWidth-infoWidth);y=Number.constrain(mouseY+dy,0,parentHeight-infoHeight);if(x>=mouseX||mouseX>=x+infoWidth||y>=mouseY||mouseY>=y+infoHeight)
break;}
this._entryInfo.style.left=x+'px';this._entryInfo.style.top=y+'px';}
_onClick(event){this.focus();const clickThreshold=5;if(this._maxDragOffset>clickThreshold)
return;this._selectGroup(this._coordinatesToGroupIndex(event.offsetX,event.offsetY,false));this._toggleGroupVisibility(this._coordinatesToGroupIndex(event.offsetX,event.offsetY,true));const timelineData=this._timelineData();if(event.shiftKey&&this._highlightedEntryIndex!==-1&&timelineData){const start=timelineData.entryStartTimes[this._highlightedEntryIndex];const end=start+timelineData.entryTotalTimes[this._highlightedEntryIndex];this._chartViewport.setRangeSelection(start,end);}else{this._chartViewport.onClick(event);this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected,this._highlightedEntryIndex);}}
_selectGroup(groupIndex){const groups=this._rawTimelineData.groups;if(groupIndex<0||!groups[groupIndex].selectable||this._selectedGroup===groupIndex)
return;this._selectedGroup=groupIndex;this._flameChartDelegate.updateSelectedGroup(this,groups[groupIndex]);this._resetCanvas();this._draw();}
_toggleGroupVisibility(groupIndex){if(groupIndex<0||!this._isGroupCollapsible(groupIndex))
return;const groups=this._rawTimelineData.groups;const group=groups[groupIndex];group.expanded=!group.expanded;this._groupExpansionState[group.name]=group.expanded;if(this._groupExpansionSetting)
this._groupExpansionSetting.set(this._groupExpansionState);this._updateLevelPositions();this._updateHighlight();if(!group.expanded){const timelineData=this._timelineData();const level=timelineData.entryLevels[this._selectedEntryIndex];if(this._selectedEntryIndex>=0&&level>=group.startLevel&&(groupIndex>=groups.length-1||groups[groupIndex+1].startLevel>level))
this._selectedEntryIndex=-1;}
this._updateHeight();this._resetCanvas();this._draw();}
_onKeyDown(e){this._handleSelectionNavigation(e);}
_handleSelectionNavigation(e){if(!UI.KeyboardShortcut.hasNoModifiers(e))
return;if(this._selectedEntryIndex===-1)
return;const timelineData=this._timelineData();if(!timelineData)
return;function timeComparator(time,entryIndex){return time-timelineData.entryStartTimes[entryIndex];}
function entriesIntersect(entry1,entry2){const start1=timelineData.entryStartTimes[entry1];const start2=timelineData.entryStartTimes[entry2];const end1=start1+timelineData.entryTotalTimes[entry1];const end2=start2+timelineData.entryTotalTimes[entry2];return start1<end2&&start2<end1;}
const keys=UI.KeyboardShortcut.Keys;if(e.keyCode===keys.Left.code||e.keyCode===keys.Right.code){const level=timelineData.entryLevels[this._selectedEntryIndex];const levelIndexes=this._timelineLevels[level];let indexOnLevel=levelIndexes.lowerBound(this._selectedEntryIndex);indexOnLevel+=e.keyCode===keys.Left.code?-1:1;e.consume(true);if(indexOnLevel>=0&&indexOnLevel<levelIndexes.length)
this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected,levelIndexes[indexOnLevel]);return;}
if(e.keyCode===keys.Up.code||e.keyCode===keys.Down.code){e.consume(true);let level=timelineData.entryLevels[this._selectedEntryIndex];level+=e.keyCode===keys.Up.code?-1:1;if(level<0||level>=this._timelineLevels.length)
return;const entryTime=timelineData.entryStartTimes[this._selectedEntryIndex]+
timelineData.entryTotalTimes[this._selectedEntryIndex]/2;const levelIndexes=this._timelineLevels[level];let indexOnLevel=levelIndexes.upperBound(entryTime,timeComparator)-1;if(!entriesIntersect(this._selectedEntryIndex,levelIndexes[indexOnLevel])){++indexOnLevel;if(indexOnLevel>=levelIndexes.length||!entriesIntersect(this._selectedEntryIndex,levelIndexes[indexOnLevel]))
return;}
this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected,levelIndexes[indexOnLevel]);}}
_coordinatesToEntryIndex(x,y){if(x<0||y<0)
return-1;const timelineData=this._timelineData();if(!timelineData)
return-1;y+=this._chartViewport.scrollOffset();const cursorLevel=this._visibleLevelOffsets.upperBound(y)-1;if(cursorLevel<0||!this._visibleLevels[cursorLevel])
return-1;const offsetFromLevel=y-this._visibleLevelOffsets[cursorLevel];if(offsetFromLevel>this._levelHeight(cursorLevel))
return-1;for(const[index,pos]of this._markerPositions){if(timelineData.entryLevels[index]!==cursorLevel)
continue;if(pos.x<=x&&x<pos.x+pos.width)
return(index);}
const entryStartTimes=timelineData.entryStartTimes;const entriesOnLevel=this._timelineLevels[cursorLevel];if(!entriesOnLevel||!entriesOnLevel.length)
return-1;const cursorTime=this._chartViewport.pixelToTime(x);const indexOnLevel=Math.max(entriesOnLevel.upperBound(cursorTime,(time,entryIndex)=>time-entryStartTimes[entryIndex])-1,0);function checkEntryHit(entryIndex){if(entryIndex===undefined)
return false;const startTime=entryStartTimes[entryIndex];const duration=timelineData.entryTotalTimes[entryIndex];const startX=this._chartViewport.timeToPosition(startTime);const endX=this._chartViewport.timeToPosition(startTime+duration);const barThresholdPx=3;return startX-barThresholdPx<x&&x<endX+barThresholdPx;}
let entryIndex=entriesOnLevel[indexOnLevel];if(checkEntryHit.call(this,entryIndex))
return entryIndex;entryIndex=entriesOnLevel[indexOnLevel+1];if(checkEntryHit.call(this,entryIndex))
return entryIndex;return-1;}
_coordinatesToGroupIndex(x,y,headerOnly){if(x<0||y<0)
return-1;y+=this._chartViewport.scrollOffset();const groups=this._rawTimelineData.groups||[];const group=this._groupOffsets.upperBound(y)-1;if(group<0||group>=groups.length)
return-1;const height=headerOnly?groups[group].style.height:this._groupOffsets[group+1]-this._groupOffsets[group];if(y-this._groupOffsets[group]>=height)
return-1;if(!headerOnly)
return group;const context=(this._canvas.getContext('2d'));context.save();context.font=groups[group].style.font;const right=this._headerLeftPadding+this._labelWidthForGroup(context,groups[group]);context.restore();if(x>right)
return-1;return group;}
_markerIndexAtPosition(x){const markers=this._timelineData().markers;if(!markers)
return-1;const accurracyOffsetPx=4;const time=this._chartViewport.pixelToTime(x);const leftTime=this._chartViewport.pixelToTime(x-accurracyOffsetPx);const rightTime=this._chartViewport.pixelToTime(x+accurracyOffsetPx);const left=this._markerIndexBeforeTime(leftTime);let markerIndex=-1;let distance=Infinity;for(let i=left;i<markers.length&&markers[i].startTime()<rightTime;i++){const nextDistance=Math.abs(markers[i].startTime()-time);if(nextDistance<distance){markerIndex=i;distance=nextDistance;}}
return markerIndex;}
_markerIndexBeforeTime(time){return this._timelineData().markers.lowerBound(time,(markerTimestamp,marker)=>markerTimestamp-marker.startTime());}
_draw(){const timelineData=this._timelineData();if(!timelineData)
return;const width=this._offsetWidth;const height=this._offsetHeight;const context=(this._canvas.getContext('2d'));context.save();const ratio=window.devicePixelRatio;const top=this._chartViewport.scrollOffset();context.scale(ratio,ratio);context.fillStyle='rgba(0, 0, 0, 0)';context.fillRect(0,0,width,height);context.translate(0,-top);const defaultFont='11px '+Host.fontFamily();context.font=defaultFont;const entryTotalTimes=timelineData.entryTotalTimes;const entryStartTimes=timelineData.entryStartTimes;const entryLevels=timelineData.entryLevels;const timeToPixel=this._chartViewport.timeToPixel();const titleIndices=[];const markerIndices=[];const textPadding=this._textPadding;const minTextWidth=2*textPadding+UI.measureTextWidth(context,'\u2026');const minTextWidthDuration=this._chartViewport.pixelToTimeOffset(minTextWidth);const minVisibleBarLevel=Math.max(this._visibleLevelOffsets.upperBound(top)-1,0);this._markerPositions.clear();const colorBuckets=new Map();for(let level=minVisibleBarLevel;level<this._dataProvider.maxStackDepth();++level){if(this._levelToOffset(level)>top+height)
break;if(!this._visibleLevels[level])
continue;const levelIndexes=this._timelineLevels[level];const rightIndexOnLevel=levelIndexes.lowerBound(this._chartViewport.windowRightTime(),(time,entryIndex)=>time-entryStartTimes[entryIndex])-
1;let lastDrawOffset=Infinity;for(let entryIndexOnLevel=rightIndexOnLevel;entryIndexOnLevel>=0;--entryIndexOnLevel){const entryIndex=levelIndexes[entryIndexOnLevel];const duration=entryTotalTimes[entryIndex];if(isNaN(duration)){markerIndices.push(entryIndex);continue;}
if(duration>=minTextWidthDuration||this._forceDecorationCache[entryIndex])
titleIndices.push(entryIndex);const entryStartTime=entryStartTimes[entryIndex];const entryOffsetRight=entryStartTime+duration;if(entryOffsetRight<=this._chartViewport.windowLeftTime())
break;if(this._useWebGL)
continue;const barX=this._timeToPositionClipped(entryStartTime);if(barX>=lastDrawOffset)
continue;lastDrawOffset=barX;const color=this._entryColorsCache[entryIndex];let bucket=colorBuckets.get(color);if(!bucket){bucket=[];colorBuckets.set(color,bucket);}
bucket.push(entryIndex);}}
if(this._useWebGL){this._drawGL();}else{context.save();this._forEachGroupInViewport((offset,index,group,isFirst,groupHeight)=>{if(index===this._selectedGroup){context.fillStyle=this._selectedGroupBackroundColor;context.fillRect(0,offset,width,groupHeight-group.style.padding);}});context.restore();for(const[color,indexes]of colorBuckets){context.beginPath();for(let i=0;i<indexes.length;++i){const entryIndex=indexes[i];const duration=entryTotalTimes[entryIndex];if(isNaN(duration))
continue;const entryStartTime=entryStartTimes[entryIndex];const barX=this._timeToPositionClipped(entryStartTime);const barLevel=entryLevels[entryIndex];const barHeight=this._levelHeight(barLevel);const barY=this._levelToOffset(barLevel);const barRight=this._timeToPositionClipped(entryStartTime+duration);const barWidth=Math.max(barRight-barX,1);context.rect(barX,barY,barWidth-0.4,barHeight-1);}
context.fillStyle=color;context.fill();}}
context.textBaseline='alphabetic';context.beginPath();let lastMarkerLevel=-1;let lastMarkerX=-Infinity;for(let m=markerIndices.length-1;m>=0;--m){const entryIndex=markerIndices[m];const title=this._dataProvider.entryTitle(entryIndex);if(!title)
continue;const entryStartTime=entryStartTimes[entryIndex];const level=entryLevels[entryIndex];if(lastMarkerLevel!==level)
lastMarkerX=-Infinity;const x=Math.max(this._chartViewport.timeToPosition(entryStartTime),lastMarkerX);const y=this._levelToOffset(level);const h=this._levelHeight(level);const padding=4;const width=Math.ceil(UI.measureTextWidth(context,title))+2*padding;lastMarkerX=x+width+1;lastMarkerLevel=level;this._markerPositions.set(entryIndex,{x,width});context.fillStyle=this._dataProvider.entryColor(entryIndex);context.fillRect(x,y,width,h-1);context.fillStyle='white';context.fillText(title,x+padding,y+h-this._textBaseline);}
context.strokeStyle='rgba(0, 0, 0, 0.2)';context.stroke();for(let i=0;i<titleIndices.length;++i){const entryIndex=titleIndices[i];const entryStartTime=entryStartTimes[entryIndex];const barX=this._timeToPositionClipped(entryStartTime);const barRight=Math.min(this._timeToPositionClipped(entryStartTime+entryTotalTimes[entryIndex]),width)+1;const barWidth=barRight-barX;const barLevel=entryLevels[entryIndex];const barY=this._levelToOffset(barLevel);let text=this._dataProvider.entryTitle(entryIndex);if(text&&text.length){context.font=this._dataProvider.entryFont(entryIndex)||defaultFont;text=UI.trimTextMiddle(context,text,barWidth-2*textPadding);}
const unclippedBarX=this._chartViewport.timeToPosition(entryStartTime);const barHeight=this._levelHeight(barLevel);if(this._dataProvider.decorateEntry(entryIndex,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixel))
continue;if(!text||!text.length)
continue;context.fillStyle=this._dataProvider.textColor(entryIndex);context.fillText(text,barX+textPadding,barY+barHeight-this._textBaseline);}
context.restore();this._drawGroupHeaders(width,height);this._drawFlowEvents(context,width,height);this._drawMarkers();const dividersData=PerfUI.TimelineGrid.calculateGridOffsets(this);PerfUI.TimelineGrid.drawCanvasGrid(context,dividersData);if(this._rulerEnabled){PerfUI.TimelineGrid.drawCanvasHeaders(context,dividersData,time=>this.formatValue(time,dividersData.precision),3,PerfUI.FlameChart.HeaderHeight);}
this._updateElementPosition(this._highlightElement,this._highlightedEntryIndex);this._updateElementPosition(this._selectedElement,this._selectedEntryIndex);this._updateMarkerHighlight();}
_initWebGL(){const gl=(this._canvasGL.getContext('webgl'));if(!gl){console.error('Failed to obtain WebGL context.');this._useWebGL=false;return;}
const vertexShaderSource=`
attribute vec2 aVertexPosition;
attribute float aVertexColor;
uniform vec2 uScalingFactor;
uniform vec2 uShiftVector;
varying mediump vec2 vPalettePosition;
void main() {
vec2 shiftedPosition = aVertexPosition - uShiftVector;
gl_Position = vec4(shiftedPosition * uScalingFactor + vec2(-1.0, 1.0), 0.0, 1.0);
vPalettePosition = vec2(aVertexColor, 0.5);
}`;const fragmentShaderSource=`
varying mediump vec2 vPalettePosition;
uniform sampler2D uSampler;
void main() {
gl_FragColor = texture2D(uSampler, vPalettePosition);
}`;function loadShader(gl,type,source){const shader=gl.createShader(type);gl.shaderSource(shader,source);gl.compileShader(shader);if(gl.getShaderParameter(shader,gl.COMPILE_STATUS))
return shader;console.error('Shader compile error: '+gl.getShaderInfoLog(shader));gl.deleteShader(shader);return null;}
const vertexShader=loadShader(gl,gl.VERTEX_SHADER,vertexShaderSource);const fragmentShader=loadShader(gl,gl.FRAGMENT_SHADER,fragmentShaderSource);const shaderProgram=gl.createProgram();gl.attachShader(shaderProgram,vertexShader);gl.attachShader(shaderProgram,fragmentShader);gl.linkProgram(shaderProgram);if(gl.getProgramParameter(shaderProgram,gl.LINK_STATUS)){this._shaderProgram=shaderProgram;gl.useProgram(shaderProgram);}else{console.error('Unable to initialize the shader program: '+gl.getProgramInfoLog(shaderProgram));this._shaderProgram=null;}
this._vertexBuffer=gl.createBuffer();this._colorBuffer=gl.createBuffer();this._uScalingFactor=gl.getUniformLocation(shaderProgram,'uScalingFactor');this._uShiftVector=gl.getUniformLocation(shaderProgram,'uShiftVector');const uSampler=gl.getUniformLocation(shaderProgram,'uSampler');gl.uniform1i(uSampler,0);this._aVertexPosition=gl.getAttribLocation(this._shaderProgram,'aVertexPosition');this._aVertexColor=gl.getAttribLocation(this._shaderProgram,'aVertexColor');gl.enableVertexAttribArray(this._aVertexPosition);gl.enableVertexAttribArray(this._aVertexColor);}
_setupGLGeometry(){const gl=(this._canvasGL.getContext('webgl'));if(!gl)
return;const timelineData=this._timelineData();if(!timelineData)
return;const entryTotalTimes=timelineData.entryTotalTimes;const entryStartTimes=timelineData.entryStartTimes;const entryLevels=timelineData.entryLevels;const verticesPerBar=6;const vertexArray=new Float32Array(entryTotalTimes.length*verticesPerBar*2);let colorArray=new Uint8Array(entryTotalTimes.length*verticesPerBar);let vertex=0;const parsedColorCache=new Map();const colors=[];const collapsedOverviewLevels=new Array(this._visibleLevels.length);const groups=this._rawTimelineData.groups||[];this._forEachGroup((offset,index,group)=>{if(group.style.useFirstLineForOverview||!this._isGroupCollapsible(index)||group.expanded)
return;let nextGroup=index+1;while(nextGroup<groups.length&&groups[nextGroup].style.nestingLevel>group.style.nestingLevel)
++nextGroup;const endLevel=nextGroup<groups.length?groups[nextGroup].startLevel:this._dataProvider.maxStackDepth();for(let i=group.startLevel;i<endLevel;++i)
collapsedOverviewLevels[i]=offset;});for(let i=0;i<entryTotalTimes.length;++i){const level=entryLevels[i];const collapsedGroupOffset=collapsedOverviewLevels[level];if(!this._visibleLevels[level]&&!collapsedGroupOffset)
continue;const color=this._entryColorsCache[i];if(!color)
continue;let colorIndex=parsedColorCache.get(color);if(colorIndex===undefined){const rgba=Common.Color.parse(color).canonicalRGBA();rgba[3]=Math.round(rgba[3]*255);colorIndex=colors.length/4;colors.push(...rgba);if(colorIndex===256)
colorArray=new Uint16Array(colorArray);parsedColorCache.set(color,colorIndex);}
for(let j=0;j<verticesPerBar;++j)
colorArray[vertex+j]=colorIndex;const vpos=vertex*2;const x0=entryStartTimes[i]-this._minimumBoundary;const x1=x0+entryTotalTimes[i];const y0=collapsedGroupOffset||this._levelToOffset(level);const y1=y0+this._levelHeight(level)-1;vertexArray[vpos+0]=x0;vertexArray[vpos+1]=y0;vertexArray[vpos+2]=x1;vertexArray[vpos+3]=y0;vertexArray[vpos+4]=x0;vertexArray[vpos+5]=y1;vertexArray[vpos+6]=x0;vertexArray[vpos+7]=y1;vertexArray[vpos+8]=x1;vertexArray[vpos+9]=y0;vertexArray[vpos+10]=x1;vertexArray[vpos+11]=y1;vertex+=verticesPerBar;}
this._vertexCount=vertex;const paletteTexture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,paletteTexture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.activeTexture(gl.TEXTURE0);const numColors=colors.length/4;const useShortForColors=numColors>=256;const width=!useShortForColors?256:Math.min(1<<16,gl.getParameter(gl.MAX_TEXTURE_SIZE));console.assert(numColors<=width,'Too many colors');const height=1;const colorIndexType=useShortForColors?gl.UNSIGNED_SHORT:gl.UNSIGNED_BYTE;if(useShortForColors){const factor=(1<<16)/width;for(let i=0;i<vertex;++i)
colorArray[i]*=factor;}
const pixels=new Uint8Array(width*4);pixels.set(colors);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,width,height,0,gl.RGBA,gl.UNSIGNED_BYTE,pixels);gl.bindBuffer(gl.ARRAY_BUFFER,this._vertexBuffer);gl.bufferData(gl.ARRAY_BUFFER,vertexArray,gl.STATIC_DRAW);gl.vertexAttribPointer(this._aVertexPosition,2,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,this._colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,colorArray,gl.STATIC_DRAW);gl.vertexAttribPointer(this._aVertexColor,1,colorIndexType,true,0,0);}
_drawGL(){const gl=(this._canvasGL.getContext('webgl'));if(!gl)
return;const timelineData=this._timelineData();if(!timelineData)
return;if(!this._prevTimelineData||timelineData.entryTotalTimes!==this._prevTimelineData.entryTotalTimes){this._prevTimelineData=timelineData;this._setupGLGeometry();}
gl.viewport(0,0,this._canvasGL.width,this._canvasGL.height);if(!this._vertexCount)
return;const viewportScale=[2.0/this.boundarySpan(),-2.0*window.devicePixelRatio/this._canvasGL.height];const viewportShift=[this.minimumBoundary()-this.zeroTime(),this._chartViewport.scrollOffset()];gl.uniform2fv(this._uScalingFactor,viewportScale);gl.uniform2fv(this._uShiftVector,viewportShift);gl.drawArrays(gl.TRIANGLES,0,this._vertexCount);}
_drawGroupHeaders(width,height){const context=(this._canvas.getContext('2d'));const top=this._chartViewport.scrollOffset();const ratio=window.devicePixelRatio;const groups=this._rawTimelineData.groups||[];if(!groups.length)
return;const groupOffsets=this._groupOffsets;const lastGroupOffset=Array.prototype.peekLast.call(groupOffsets);const colorUsage=UI.ThemeSupport.ColorUsage;context.save();context.scale(ratio,ratio);context.translate(0,-top);const defaultFont='11px '+Host.fontFamily();context.font=defaultFont;context.fillStyle=UI.themeSupport.patchColorText('#fff',colorUsage.Background);this._forEachGroupInViewport((offset,index,group)=>{const paddingHeight=group.style.padding;if(paddingHeight<5)
return;context.fillRect(0,offset-paddingHeight+2,width,paddingHeight-4);});if(groups.length&&lastGroupOffset<top+height)
context.fillRect(0,lastGroupOffset+2,width,top+height-lastGroupOffset);context.strokeStyle=UI.themeSupport.patchColorText('#eee',colorUsage.Background);context.beginPath();this._forEachGroupInViewport((offset,index,group,isFirst)=>{if(isFirst||group.style.padding<4)
return;hLine(offset-2.5);});hLine(lastGroupOffset+1.5);context.stroke();this._forEachGroupInViewport((offset,index,group)=>{if(group.style.useFirstLineForOverview)
return;if(!this._isGroupCollapsible(index)||group.expanded){if(!group.style.shareHeaderLine&&index!==this._selectedGroup){context.fillStyle=group.style.backgroundColor;context.fillRect(0,offset,width,group.style.height);}
return;}
if(this._useWebGL)
return;let nextGroup=index+1;while(nextGroup<groups.length&&groups[nextGroup].style.nestingLevel>group.style.nestingLevel)
nextGroup++;const endLevel=nextGroup<groups.length?groups[nextGroup].startLevel:this._dataProvider.maxStackDepth();this._drawCollapsedOverviewForGroup(group,offset,endLevel);});context.save();this._forEachGroupInViewport((offset,index,group)=>{context.font=group.style.font;if(this._isGroupCollapsible(index)&&!group.expanded||group.style.shareHeaderLine){const width=this._labelWidthForGroup(context,group)+2;if(index===this._selectedGroup)
context.fillStyle=this._selectedGroupBackroundColor;else
context.fillStyle=Common.Color.parse(group.style.backgroundColor).setAlpha(0.8).asString(null);context.fillRect(this._headerLeftPadding-this._headerLabelXPadding,offset+this._headerLabelYPadding,width,group.style.height-2*this._headerLabelYPadding);}
context.fillStyle=group.style.color;context.fillText(group.name,Math.floor(this._expansionArrowIndent*(group.style.nestingLevel+1)+this._arrowSide),offset+group.style.height-this._textBaseline);});context.restore();context.fillStyle=UI.themeSupport.patchColorText('#6e6e6e',colorUsage.Foreground);context.beginPath();this._forEachGroupInViewport((offset,index,group)=>{if(this._isGroupCollapsible(index)){drawExpansionArrow.call(this,this._expansionArrowIndent*(group.style.nestingLevel+1),offset+group.style.height-this._textBaseline-this._arrowSide/2,!!group.expanded);}});context.fill();context.strokeStyle=UI.themeSupport.patchColorText('#ddd',colorUsage.Background);context.beginPath();context.stroke();this._forEachGroupInViewport((offset,index,group,isFirst,groupHeight)=>{if(index===this._selectedGroup){const lineWidth=2;const bracketLength=10;context.fillStyle=this._selectedGroupBorderColor;context.fillRect(0,offset-lineWidth,lineWidth,groupHeight-group.style.padding+2*lineWidth);context.fillRect(0,offset-lineWidth,bracketLength,lineWidth);context.fillRect(0,offset+groupHeight-group.style.padding,bracketLength,lineWidth);}});context.restore();function hLine(y){context.moveTo(0,y);context.lineTo(width,y);}
function drawExpansionArrow(x,y,expanded){const arrowHeight=this._arrowSide*Math.sqrt(3)/2;const arrowCenterOffset=Math.round(arrowHeight/2);context.save();context.translate(x,y);context.rotate(expanded?Math.PI/2:0);context.moveTo(-arrowCenterOffset,-this._arrowSide/2);context.lineTo(-arrowCenterOffset,this._arrowSide/2);context.lineTo(arrowHeight-arrowCenterOffset,0);context.restore();}}
_forEachGroup(callback){const groups=this._rawTimelineData.groups||[];if(!groups.length)
return;const groupOffsets=this._groupOffsets;const groupStack=[{nestingLevel:-1,visible:true}];for(let i=0;i<groups.length;++i){const groupTop=groupOffsets[i];const group=groups[i];let firstGroup=true;while(groupStack.peekLast().nestingLevel>=group.style.nestingLevel){groupStack.pop();firstGroup=false;}
const parentGroupVisible=groupStack.peekLast().visible;const thisGroupVisible=parentGroupVisible&&(!this._isGroupCollapsible(i)||group.expanded);groupStack.push({nestingLevel:group.style.nestingLevel,visible:thisGroupVisible});const nextOffset=i===groups.length-1?groupOffsets[i+1]+group.style.padding:groupOffsets[i+1];if(!parentGroupVisible)
continue;callback(groupTop,i,group,firstGroup,nextOffset-groupTop);}}
_forEachGroupInViewport(callback){const top=this._chartViewport.scrollOffset();this._forEachGroup((groupTop,index,group,firstGroup,height)=>{if(groupTop-group.style.padding>top+this._offsetHeight)
return;if(groupTop+height<top)
return;callback(groupTop,index,group,firstGroup,height);});}
_labelWidthForGroup(context,group){return UI.measureTextWidth(context,group.name)+this._expansionArrowIndent*(group.style.nestingLevel+1)+
2*this._headerLabelXPadding;}
_drawCollapsedOverviewForGroup(group,y,endLevel){const range=new Common.SegmentedRange(mergeCallback);const timeWindowLeft=this._chartViewport.windowLeftTime();const timeWindowRight=this._chartViewport.windowRightTime();const context=(this._canvas.getContext('2d'));const barHeight=group.style.height;const entryStartTimes=this._rawTimelineData.entryStartTimes;const entryTotalTimes=this._rawTimelineData.entryTotalTimes;const timeToPixel=this._chartViewport.timeToPixel();for(let level=group.startLevel;level<endLevel;++level){const levelIndexes=this._timelineLevels[level];const rightIndexOnLevel=levelIndexes.lowerBound(timeWindowRight,(time,entryIndex)=>time-entryStartTimes[entryIndex])-1;let lastDrawOffset=Infinity;for(let entryIndexOnLevel=rightIndexOnLevel;entryIndexOnLevel>=0;--entryIndexOnLevel){const entryIndex=levelIndexes[entryIndexOnLevel];const entryStartTime=entryStartTimes[entryIndex];const barX=this._timeToPositionClipped(entryStartTime);const entryEndTime=entryStartTime+entryTotalTimes[entryIndex];if(isNaN(entryEndTime)||barX>=lastDrawOffset)
continue;if(entryEndTime<=timeWindowLeft)
break;lastDrawOffset=barX;const color=this._entryColorsCache[entryIndex];const endBarX=this._timeToPositionClipped(entryEndTime);if(group.style.useDecoratorsForOverview&&this._dataProvider.forceDecoration(entryIndex)){const unclippedBarX=this._chartViewport.timeToPosition(entryStartTime);const barWidth=endBarX-barX;context.beginPath();context.fillStyle=color;context.fillRect(barX,y,barWidth,barHeight-1);this._dataProvider.decorateEntry(entryIndex,context,'',barX,y,barWidth,barHeight,unclippedBarX,timeToPixel);continue;}
range.append(new Common.Segment(barX,endBarX,color));}}
const segments=range.segments().slice().sort((a,b)=>a.data.localeCompare(b.data));let lastColor;context.beginPath();for(let i=0;i<segments.length;++i){const segment=segments[i];if(lastColor!==segments[i].data){context.fill();context.beginPath();lastColor=segments[i].data;context.fillStyle=lastColor;}
context.rect(segment.begin,y,segment.end-segment.begin,barHeight);}
context.fill();function mergeCallback(a,b){return a.data===b.data&&a.end+0.4>b.end?a:null;}}
_drawFlowEvents(context,width,height){context.save();const ratio=window.devicePixelRatio;const top=this._chartViewport.scrollOffset();const arrowWidth=6;context.scale(ratio,ratio);context.translate(0,-top);context.fillStyle='#7f5050';context.strokeStyle='#7f5050';const td=this._timelineData();const endIndex=td.flowStartTimes.lowerBound(this._chartViewport.windowRightTime());context.lineWidth=0.5;for(let i=0;i<endIndex;++i){if(!td.flowEndTimes[i]||td.flowEndTimes[i]<this._chartViewport.windowLeftTime())
continue;const startX=this._chartViewport.timeToPosition(td.flowStartTimes[i]);const endX=this._chartViewport.timeToPosition(td.flowEndTimes[i]);const startLevel=td.flowStartLevels[i];const endLevel=td.flowEndLevels[i];const startY=this._levelToOffset(startLevel)+this._levelHeight(startLevel)/2;const endY=this._levelToOffset(endLevel)+this._levelHeight(endLevel)/2;const segment=Math.min((endX-startX)/4,40);const distanceTime=td.flowEndTimes[i]-td.flowStartTimes[i];const distanceY=(endY-startY)/10;const spread=30;const lineY=distanceTime<1?startY:spread+Math.max(0,startY+distanceY*(i%spread));const p=[];p.push({x:startX,y:startY});p.push({x:startX+arrowWidth,y:startY});p.push({x:startX+segment+2*arrowWidth,y:startY});p.push({x:startX+segment,y:lineY});p.push({x:startX+segment*2,y:lineY});p.push({x:endX-segment*2,y:lineY});p.push({x:endX-segment,y:lineY});p.push({x:endX-segment-2*arrowWidth,y:endY});p.push({x:endX-arrowWidth,y:endY});context.beginPath();context.moveTo(p[0].x,p[0].y);context.lineTo(p[1].x,p[1].y);context.bezierCurveTo(p[2].x,p[2].y,p[3].x,p[3].y,p[4].x,p[4].y);context.lineTo(p[5].x,p[5].y);context.bezierCurveTo(p[6].x,p[6].y,p[7].x,p[7].y,p[8].x,p[8].y);context.stroke();context.beginPath();context.arc(startX,startY,2,-Math.PI/2,Math.PI/2,false);context.fill();context.beginPath();context.moveTo(endX,endY);context.lineTo(endX-arrowWidth,endY-3);context.lineTo(endX-arrowWidth,endY+3);context.fill();}
context.restore();}
_drawMarkers(){const markers=this._timelineData().markers;const left=this._markerIndexBeforeTime(this.minimumBoundary());const rightBoundary=this.maximumBoundary();const timeToPixel=this._chartViewport.timeToPixel();const context=(this._canvas.getContext('2d'));context.save();const ratio=window.devicePixelRatio;context.scale(ratio,ratio);context.translate(0,3);const height=PerfUI.FlameChart.HeaderHeight-1;for(let i=left;i<markers.length;i++){const timestamp=markers[i].startTime();if(timestamp>rightBoundary)
break;markers[i].draw(context,this._chartViewport.timeToPosition(timestamp),height,timeToPixel);}
context.restore();}
_updateMarkerHighlight(){const element=this._markerHighlighElement;if(element.parentElement)
element.remove();const markerIndex=this._highlightedMarkerIndex;if(markerIndex===-1)
return;const marker=this._timelineData().markers[markerIndex];const barX=this._timeToPositionClipped(marker.startTime());element.title=marker.title();const style=element.style;style.left=barX+'px';style.backgroundColor=marker.color();this._viewportElement.appendChild(element);}
_processTimelineData(timelineData){if(!timelineData){this._timelineLevels=null;this._visibleLevelOffsets=null;this._visibleLevels=null;this._groupOffsets=null;this._rawTimelineData=null;this._forceDecorationCache=null;this._entryColorsCache=null;this._rawTimelineDataLength=0;this._selectedGroup=-1;this._flameChartDelegate.updateSelectedGroup(this,null);return;}
this._rawTimelineData=timelineData;this._rawTimelineDataLength=timelineData.entryStartTimes.length;this._forceDecorationCache=new Int8Array(this._rawTimelineDataLength);this._entryColorsCache=new Array(this._rawTimelineDataLength);for(let i=0;i<this._rawTimelineDataLength;++i){this._forceDecorationCache[i]=this._dataProvider.forceDecoration(i)?1:0;this._entryColorsCache[i]=this._dataProvider.entryColor(i);}
const entryCounters=new Uint32Array(this._dataProvider.maxStackDepth()+1);for(let i=0;i<timelineData.entryLevels.length;++i)
++entryCounters[timelineData.entryLevels[i]];const levelIndexes=new Array(entryCounters.length);for(let i=0;i<levelIndexes.length;++i){levelIndexes[i]=new Uint32Array(entryCounters[i]);entryCounters[i]=0;}
for(let i=0;i<timelineData.entryLevels.length;++i){const level=timelineData.entryLevels[i];levelIndexes[level][entryCounters[level]++]=i;}
this._timelineLevels=levelIndexes;const groups=this._rawTimelineData.groups||[];for(let i=0;i<groups.length;++i){const expanded=this._groupExpansionState[groups[i].name];if(expanded!==undefined)
groups[i].expanded=expanded;}
this._updateLevelPositions();this._updateHeight();this._selectedGroup=timelineData.selectedGroup?groups.indexOf(timelineData.selectedGroup):-1;this._flameChartDelegate.updateSelectedGroup(this,timelineData.selectedGroup);}
_updateLevelPositions(){const levelCount=this._dataProvider.maxStackDepth();const groups=this._rawTimelineData.groups||[];this._visibleLevelOffsets=new Uint32Array(levelCount+1);this._visibleLevelHeights=new Uint32Array(levelCount);this._visibleLevels=new Uint16Array(levelCount);this._groupOffsets=new Uint32Array(groups.length+1);let groupIndex=-1;let currentOffset=this._rulerEnabled?PerfUI.FlameChart.HeaderHeight+2:2;let visible=true;const groupStack=[{nestingLevel:-1,visible:true}];const lastGroupLevel=Math.max(levelCount,groups.length?groups.peekLast().startLevel+1:0);let level;for(level=0;level<lastGroupLevel;++level){let parentGroupIsVisible=true;let style;while(groupIndex<groups.length-1&&level===groups[groupIndex+1].startLevel){++groupIndex;style=groups[groupIndex].style;let nextLevel=true;while(groupStack.peekLast().nestingLevel>=style.nestingLevel){groupStack.pop();nextLevel=false;}
const thisGroupIsVisible=groupIndex>=0&&this._isGroupCollapsible(groupIndex)?groups[groupIndex].expanded:true;parentGroupIsVisible=groupStack.peekLast().visible;visible=thisGroupIsVisible&&parentGroupIsVisible;groupStack.push({nestingLevel:style.nestingLevel,visible:visible});if(parentGroupIsVisible)
currentOffset+=nextLevel?0:style.padding;this._groupOffsets[groupIndex]=currentOffset;if(parentGroupIsVisible&&!style.shareHeaderLine)
currentOffset+=style.height;}
const isFirstOnLevel=groupIndex>=0&&level===groups[groupIndex].startLevel;const thisLevelIsVisible=parentGroupIsVisible&&(visible||isFirstOnLevel&&groups[groupIndex].style.useFirstLineForOverview);if(level<levelCount){let height;if(groupIndex>=0){const group=groups[groupIndex];const styleB=group.style;height=isFirstOnLevel&&!styleB.shareHeaderLine||(styleB.collapsible&&!group.expanded)?styleB.height:(styleB.itemsHeight||this._barHeight);}else{height=this._barHeight;}
this._visibleLevels[level]=thisLevelIsVisible;this._visibleLevelOffsets[level]=currentOffset;this._visibleLevelHeights[level]=height;}
if(thisLevelIsVisible||(parentGroupIsVisible&&style&&style.shareHeaderLine&&isFirstOnLevel))
currentOffset+=this._visibleLevelHeights[level];}
if(groupIndex>=0)
this._groupOffsets[groupIndex+1]=currentOffset;this._visibleLevelOffsets[level]=currentOffset;if(this._useWebGL)
this._setupGLGeometry();}
_isGroupCollapsible(index){const groups=this._rawTimelineData.groups||[];const style=groups[index].style;if(!style.shareHeaderLine||!style.collapsible)
return!!style.collapsible;const isLastGroup=index+1>=groups.length;if(!isLastGroup&&groups[index+1].style.nestingLevel>style.nestingLevel)
return true;const nextGroupLevel=isLastGroup?this._dataProvider.maxStackDepth():groups[index+1].startLevel;if(nextGroupLevel!==groups[index].startLevel+1)
return true;return style.height!==style.itemsHeight;}
setSelectedEntry(entryIndex){if(this._selectedEntryIndex===entryIndex)
return;if(entryIndex!==-1)
this._chartViewport.hideRangeSelection();this._selectedEntryIndex=entryIndex;this._revealEntry(entryIndex);this._updateElementPosition(this._selectedElement,this._selectedEntryIndex);}
_updateElementPosition(element,entryIndex){const elementMinWidthPx=2;element.classList.add('hidden');if(entryIndex===-1)
return;const timelineData=this._timelineData();const startTime=timelineData.entryStartTimes[entryIndex];const duration=timelineData.entryTotalTimes[entryIndex];let barX=0;let barWidth=0;let visible=true;if(Number.isNaN(duration)){const position=this._markerPositions.get(entryIndex);if(position){barX=position.x;barWidth=position.width;}else{visible=false;}}else{barX=this._chartViewport.timeToPosition(startTime);barWidth=duration*this._chartViewport.timeToPixel();}
if(barX+barWidth<=0||barX>=this._offsetWidth)
return;const barCenter=barX+barWidth/2;barWidth=Math.max(barWidth,elementMinWidthPx);barX=barCenter-barWidth/2;const entryLevel=timelineData.entryLevels[entryIndex];const barY=this._levelToOffset(entryLevel)-this._chartViewport.scrollOffset();const barHeight=this._levelHeight(entryLevel);const style=element.style;style.left=barX+'px';style.top=barY+'px';style.width=barWidth+'px';style.height=barHeight-1+'px';element.classList.toggle('hidden',!visible);this._viewportElement.appendChild(element);}
_timeToPositionClipped(time){return Number.constrain(this._chartViewport.timeToPosition(time),0,this._offsetWidth);}
_levelToOffset(level){return this._visibleLevelOffsets[level];}
_levelHeight(level){return this._visibleLevelHeights[level];}
_updateBoundaries(){this._totalTime=this._dataProvider.totalTime();this._minimumBoundary=this._dataProvider.minimumBoundary();this._chartViewport.setBoundaries(this._minimumBoundary,this._totalTime);}
_updateHeight(){const height=this._levelToOffset(this._dataProvider.maxStackDepth())+2;this._chartViewport.setContentHeight(height);}
onResize(){this.scheduleUpdate();}
update(){if(!this._timelineData())
return;this._resetCanvas();this._updateHeight();this._updateBoundaries();this._draw();if(!this._chartViewport.isDragging())
this._updateHighlight();}
reset(){this._chartViewport.reset();this._rawTimelineData=null;this._rawTimelineDataLength=0;this._highlightedMarkerIndex=-1;this._highlightedEntryIndex=-1;this._selectedEntryIndex=-1;this._textWidth=new Map();this._chartViewport.scheduleUpdate();}
scheduleUpdate(){this._chartViewport.scheduleUpdate();}
_enabled(){return this._rawTimelineDataLength!==0;}
computePosition(time){return this._chartViewport.timeToPosition(time);}
formatValue(value,precision){return this._dataProvider.formatValue(value-this.zeroTime(),precision);}
maximumBoundary(){return this._chartViewport.windowRightTime();}
minimumBoundary(){return this._chartViewport.windowLeftTime();}
zeroTime(){return this._dataProvider.minimumBoundary();}
boundarySpan(){return this.maximumBoundary()-this.minimumBoundary();}};PerfUI.FlameChart.HeaderHeight=15;PerfUI.FlameChart.MinimalTimeWindowMs=0.5;PerfUI.FlameChartDataProvider=function(){};PerfUI.FlameChart.Group;PerfUI.FlameChart.GroupStyle;PerfUI.FlameChart.TimelineData=class{constructor(entryLevels,entryTotalTimes,entryStartTimes,groups){this.entryLevels=entryLevels;this.entryTotalTimes=entryTotalTimes;this.entryStartTimes=entryStartTimes;this.groups=groups;this.markers=[];this.flowStartTimes=[];this.flowStartLevels=[];this.flowEndTimes=[];this.flowEndLevels=[];this.selectedGroup=null;}};PerfUI.FlameChartDataProvider.prototype={minimumBoundary(){},totalTime(){},formatValue(value,precision){},maxStackDepth(){},timelineData(){},prepareHighlightedEntryInfo(entryIndex){},canJumpToEntry(entryIndex){},entryTitle(entryIndex){},entryFont(entryIndex){},entryColor(entryIndex){},decorateEntry(entryIndex,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixelRatio){},forceDecoration(entryIndex){},textColor(entryIndex){},};PerfUI.FlameChartMarker=function(){};PerfUI.FlameChartMarker.prototype={startTime(){},color(){},title(){},draw(context,x,height,pixelsPerMillisecond){},};PerfUI.FlameChart.Events={EntrySelected:Symbol('EntrySelected'),EntryHighlighted:Symbol('EntryHighlighted')};PerfUI.FlameChart.Colors={SelectedGroupBackground:'hsl(215, 85%, 98%)',SelectedGroupBorder:'hsl(216, 68%, 54%)',};;PerfUI.GCActionDelegate=class{handleAction(context,actionId){for(const heapProfilerModel of SDK.targetManager.models(SDK.HeapProfilerModel))
heapProfilerModel.collectGarbage();return true;}};;PerfUI.LineLevelProfile={};PerfUI.LineLevelProfile.Performance=class{constructor(){this._helper=new PerfUI.LineLevelProfile._Helper('performance');}
reset(){this._helper.reset();}
_appendLegacyCPUProfile(profile){const target=profile.target();const nodesToGo=[profile.profileHead];const sampleDuration=(profile.profileEndTime-profile.profileStartTime)/profile.totalHitCount;while(nodesToGo.length){const nodes=nodesToGo.pop().children;for(let i=0;i<nodes.length;++i){const node=nodes[i];nodesToGo.push(node);if(!node.url||!node.positionTicks)
continue;for(let j=0;j<node.positionTicks.length;++j){const lineInfo=node.positionTicks[j];const line=lineInfo.line;const time=lineInfo.ticks*sampleDuration;this._helper.addLineData(target,node.url,line,time);}}}}
appendCPUProfile(profile){if(!profile.lines){this._appendLegacyCPUProfile(profile);this._helper.scheduleUpdate();return;}
const target=profile.target();for(let i=1;i<profile.samples.length;++i){const line=profile.lines[i];if(!line)
continue;const node=profile.nodeByIndex(i);const scriptIdOrUrl=node.scriptId||node.url;if(!scriptIdOrUrl)
continue;const time=profile.timestamps[i]-profile.timestamps[i-1];this._helper.addLineData(target,scriptIdOrUrl,line,time);}
this._helper.scheduleUpdate();}};PerfUI.LineLevelProfile.Memory=class{constructor(){this._helper=new PerfUI.LineLevelProfile._Helper('memory');}
reset(){this._helper.reset();}
appendHeapProfile(profile,target){const helper=this._helper;processNode(profile.head);helper.scheduleUpdate();function processNode(node){node.children.forEach(processNode);if(!node.selfSize)
return;const script=Number(node.callFrame.scriptId)||node.callFrame.url;if(!script)
return;const line=node.callFrame.lineNumber+1;helper.addLineData(target,script,line,node.selfSize);}}};PerfUI.LineLevelProfile._Helper=class{constructor(type){this._type=type;this._locationPool=new Bindings.LiveLocationPool();this._updateTimer=null;this.reset();}
reset(){this._lineData=new Map();this.scheduleUpdate();}
addLineData(target,scriptIdOrUrl,line,data){let targetData=this._lineData.get(target);if(!targetData){targetData=new Map();this._lineData.set(target,targetData);}
let scriptData=targetData.get(scriptIdOrUrl);if(!scriptData){scriptData=new Map();targetData.set(scriptIdOrUrl,scriptData);}
scriptData.set(line,(scriptData.get(line)||0)+data);}
scheduleUpdate(){if(this._updateTimer)
return;this._updateTimer=setTimeout(()=>{this._updateTimer=null;this._doUpdate();},0);}
_doUpdate(){this._locationPool.disposeAll();Workspace.workspace.uiSourceCodes().forEach(uiSourceCode=>uiSourceCode.removeDecorationsForType(this._type));for(const targetToScript of this._lineData){const target=(targetToScript[0]);const debuggerModel=target?target.model(SDK.DebuggerModel):null;const scriptToLineMap=(targetToScript[1]);for(const scriptToLine of scriptToLineMap){const scriptIdOrUrl=(scriptToLine[0]);const lineToDataMap=(scriptToLine[1]);const uiSourceCode=!debuggerModel&&typeof scriptIdOrUrl==='string'?Workspace.workspace.uiSourceCodeForURL(scriptIdOrUrl):null;if(!debuggerModel&&!uiSourceCode)
continue;for(const lineToData of lineToDataMap){const line=(lineToData[0])-1;const data=(lineToData[1]);if(uiSourceCode){uiSourceCode.addLineDecoration(line,this._type,data);continue;}
const rawLocation=typeof scriptIdOrUrl==='string'?debuggerModel.createRawLocationByURL(scriptIdOrUrl,line,0):debuggerModel.createRawLocationByScriptId(String(scriptIdOrUrl),line,0);if(rawLocation)
new PerfUI.LineLevelProfile.Presentation(rawLocation,this._type,data,this._locationPool);}}}}};PerfUI.LineLevelProfile.Presentation=class{constructor(rawLocation,type,time,locationPool){this._type=type;this._time=time;this._uiLocation=null;Bindings.debuggerWorkspaceBinding.createLiveLocation(rawLocation,this.updateLocation.bind(this),locationPool);}
updateLocation(liveLocation){if(this._uiLocation)
this._uiLocation.uiSourceCode.removeDecorationsForType(this._type);this._uiLocation=liveLocation.uiLocation();if(this._uiLocation)
this._uiLocation.uiSourceCode.addLineDecoration(this._uiLocation.lineNumber,this._type,this._time);}};PerfUI.LineLevelProfile.LineDecorator=class{decorate(uiSourceCode,textEditor,type){const gutterType=`CodeMirror-gutter-${type}`;const decorations=uiSourceCode.decorationsForType(type);textEditor.uninstallGutter(gutterType);if(!decorations||!decorations.size)
return;textEditor.installGutter(gutterType,false);for(const decoration of decorations){const value=(decoration.data());const element=this._createElement(type,value);textEditor.setGutterDecoration(decoration.range().startLine,gutterType,element);}}
_createElement(type,value){const element=createElementWithClass('div','text-editor-line-marker-text');if(type==='performance'){const intensity=Number.constrain(Math.log10(1+10*value)/5,0.02,1);element.textContent=Common.UIString('%.1f',value);element.style.backgroundColor=`hsla(44, 100%, 50%, ${intensity.toFixed(3)})`;element.createChild('span','line-marker-units').textContent=ls`ms`;}else{const intensity=Number.constrain(Math.log10(1+2e-3*value)/5,0.02,1);element.style.backgroundColor=`hsla(217, 100%, 70%, ${intensity.toFixed(3)})`;value/=1e3;let units;let fractionDigits;if(value>=1e3){units=ls`MB`;value/=1e3;fractionDigits=value>=20?0:1;}else{units=ls`KB`;fractionDigits=0;}
element.textContent=Common.UIString(`%.${fractionDigits}f`,value);element.createChild('span','line-marker-units').textContent=units;}
return element;}};;PerfUI.LiveHeapProfile=class{constructor(){this._running=false;this._sessionId=0;this._loadEventCallback=()=>{};this._setting=Common.settings.moduleSetting('memoryLiveHeapProfile');this._setting.addChangeListener(event=>event.data?this._startProfiling():this._stopProfiling());if(this._setting.get())
this._startProfiling();}
run(){}
modelAdded(model){model.startSampling(1e4);}
modelRemoved(model){}
async _startProfiling(){if(this._running)
return;this._running=true;const sessionId=this._sessionId;SDK.targetManager.observeModels(SDK.HeapProfilerModel,this);SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);do{const models=SDK.targetManager.models(SDK.HeapProfilerModel);const profiles=await Promise.all(models.map(model=>model.getSamplingProfile()));if(sessionId!==this._sessionId)
break;const lineLevelProfile=self.runtime.sharedInstance(PerfUI.LineLevelProfile.Memory);lineLevelProfile.reset();for(let i=0;i<profiles.length;++i){if(profiles[i])
lineLevelProfile.appendHeapProfile(profiles[i],models[i].target());}
await Promise.race([new Promise(r=>setTimeout(r,Host.isUnderTest()?10:5000)),new Promise(r=>this._loadEventCallback=r)]);}while(sessionId===this._sessionId);SDK.targetManager.unobserveModels(SDK.HeapProfilerModel,this);SDK.targetManager.removeModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);for(const model of SDK.targetManager.models(SDK.HeapProfilerModel))
model.stopSampling();self.runtime.sharedInstance(PerfUI.LineLevelProfile.Memory).reset();}
_stopProfiling(){if(!this._running)
return;this._running=0;this._sessionId++;}
_loadEventFired(){this._loadEventCallback();}};;PerfUI.uiLabelForNetworkPriority=function(priority){return PerfUI._priorityUILabelMap().get(priority)||'';};PerfUI.uiLabelToNetworkPriority=function(priorityLabel){if(!PerfUI._uiLabelToPriorityMapInstance){PerfUI._uiLabelToPriorityMapInstance=new Map();PerfUI._priorityUILabelMap().forEach((value,key)=>PerfUI._uiLabelToPriorityMapInstance.set(value,key));}
return PerfUI._uiLabelToPriorityMapInstance.get(priorityLabel)||'';};PerfUI._priorityUILabelMap=function(){if(PerfUI._priorityUILabelMapInstance)
return PerfUI._priorityUILabelMapInstance;const map=new Map();map.set(Protocol.Network.ResourcePriority.VeryLow,Common.UIString('Lowest'));map.set(Protocol.Network.ResourcePriority.Low,Common.UIString('Low'));map.set(Protocol.Network.ResourcePriority.Medium,Common.UIString('Medium'));map.set(Protocol.Network.ResourcePriority.High,Common.UIString('High'));map.set(Protocol.Network.ResourcePriority.VeryHigh,Common.UIString('Highest'));PerfUI._priorityUILabelMapInstance=map;return map;};PerfUI.networkPriorityWeight=function(priority){if(!PerfUI._networkPriorityWeights){const priorityMap=new Map();priorityMap.set(Protocol.Network.ResourcePriority.VeryLow,1);priorityMap.set(Protocol.Network.ResourcePriority.Low,2);priorityMap.set(Protocol.Network.ResourcePriority.Medium,3);priorityMap.set(Protocol.Network.ResourcePriority.High,4);priorityMap.set(Protocol.Network.ResourcePriority.VeryHigh,5);PerfUI._networkPriorityWeights=priorityMap;}
return PerfUI._networkPriorityWeights.get(priority)||0;};;PerfUI.OverviewGrid=class{constructor(prefix){this.element=createElement('div');this.element.id=prefix+'-overview-container';this._grid=new PerfUI.TimelineGrid();this._grid.element.id=prefix+'-overview-grid';this._grid.setScrollTop(0);this.element.appendChild(this._grid.element);this._window=new PerfUI.OverviewGrid.Window(this.element,this._grid.dividersLabelBarElement);}
clientWidth(){return this.element.clientWidth;}
updateDividers(calculator){this._grid.updateDividers(calculator);}
addEventDividers(dividers){this._grid.addEventDividers(dividers);}
removeEventDividers(){this._grid.removeEventDividers();}
reset(){this._window.reset();}
windowLeft(){return this._window.windowLeft;}
windowRight(){return this._window.windowRight;}
setWindow(left,right){this._window._setWindow(left,right);}
addEventListener(eventType,listener,thisObject){return this._window.addEventListener(eventType,listener,thisObject);}
setClickHandler(clickHandler){this._window.setClickHandler(clickHandler);}
zoom(zoomFactor,referencePoint){this._window._zoom(zoomFactor,referencePoint);}
setResizeEnabled(enabled){this._window.setEnabled(enabled);}};PerfUI.OverviewGrid.MinSelectableSize=14;PerfUI.OverviewGrid.WindowScrollSpeedFactor=.3;PerfUI.OverviewGrid.ResizerOffset=3.5;PerfUI.OverviewGrid.Window=class extends Common.Object{constructor(parentElement,dividersLabelBarElement){super();this._parentElement=parentElement;UI.installDragHandle(this._parentElement,this._startWindowSelectorDragging.bind(this),this._windowSelectorDragging.bind(this),this._endWindowSelectorDragging.bind(this),'text',null);if(dividersLabelBarElement){UI.installDragHandle(dividersLabelBarElement,this._startWindowDragging.bind(this),this._windowDragging.bind(this),null,'-webkit-grabbing','-webkit-grab');}
this._parentElement.addEventListener('mousewheel',this._onMouseWheel.bind(this),true);this._parentElement.addEventListener('dblclick',this._resizeWindowMaximum.bind(this),true);UI.appendStyle(this._parentElement,'perf_ui/overviewGrid.css');this._leftResizeElement=parentElement.createChild('div','overview-grid-window-resizer');UI.installDragHandle(this._leftResizeElement,this._resizerElementStartDragging.bind(this),this._leftResizeElementDragging.bind(this),null,'ew-resize');this._rightResizeElement=parentElement.createChild('div','overview-grid-window-resizer');UI.installDragHandle(this._rightResizeElement,this._resizerElementStartDragging.bind(this),this._rightResizeElementDragging.bind(this),null,'ew-resize');this._leftCurtainElement=parentElement.createChild('div','window-curtain-left');this._rightCurtainElement=parentElement.createChild('div','window-curtain-right');this.reset();}
reset(){this.windowLeft=0.0;this.windowRight=1.0;this.setEnabled(true);this._updateCurtains();}
setEnabled(enabled){this._enabled=enabled;}
setClickHandler(clickHandler){this._clickHandler=clickHandler;}
_resizerElementStartDragging(event){if(!this._enabled)
return false;this._resizerParentOffsetLeft=event.pageX-event.offsetX-event.target.offsetLeft;event.stopPropagation();return true;}
_leftResizeElementDragging(event){this._resizeWindowLeft(event.pageX-this._resizerParentOffsetLeft);event.preventDefault();}
_rightResizeElementDragging(event){this._resizeWindowRight(event.pageX-this._resizerParentOffsetLeft);event.preventDefault();}
_startWindowSelectorDragging(event){if(!this._enabled)
return false;this._offsetLeft=this._parentElement.totalOffsetLeft();const position=event.x-this._offsetLeft;this._overviewWindowSelector=new PerfUI.OverviewGrid.WindowSelector(this._parentElement,position);return true;}
_windowSelectorDragging(event){this._overviewWindowSelector._updatePosition(event.x-this._offsetLeft);event.preventDefault();}
_endWindowSelectorDragging(event){const window=this._overviewWindowSelector._close(event.x-this._offsetLeft);delete this._overviewWindowSelector;const clickThreshold=3;if(window.end-window.start<clickThreshold){if(this._clickHandler&&this._clickHandler.call(null,event))
return;const middle=window.end;window.start=Math.max(0,middle-PerfUI.OverviewGrid.MinSelectableSize/2);window.end=Math.min(this._parentElement.clientWidth,middle+PerfUI.OverviewGrid.MinSelectableSize/2);}else if(window.end-window.start<PerfUI.OverviewGrid.MinSelectableSize){if(this._parentElement.clientWidth-window.end>PerfUI.OverviewGrid.MinSelectableSize)
window.end=window.start+PerfUI.OverviewGrid.MinSelectableSize;else
window.start=window.end-PerfUI.OverviewGrid.MinSelectableSize;}
this._setWindowPosition(window.start,window.end);}
_startWindowDragging(event){this._dragStartPoint=event.pageX;this._dragStartLeft=this.windowLeft;this._dragStartRight=this.windowRight;event.stopPropagation();return true;}
_windowDragging(event){event.preventDefault();let delta=(event.pageX-this._dragStartPoint)/this._parentElement.clientWidth;if(this._dragStartLeft+delta<0)
delta=-this._dragStartLeft;if(this._dragStartRight+delta>1)
delta=1-this._dragStartRight;this._setWindow(this._dragStartLeft+delta,this._dragStartRight+delta);}
_resizeWindowLeft(start){if(start<10)
start=0;else if(start>this._rightResizeElement.offsetLeft-4)
start=this._rightResizeElement.offsetLeft-4;this._setWindowPosition(start,null);}
_resizeWindowRight(end){if(end>this._parentElement.clientWidth-10)
end=this._parentElement.clientWidth;else if(end<this._leftResizeElement.offsetLeft+PerfUI.OverviewGrid.MinSelectableSize)
end=this._leftResizeElement.offsetLeft+PerfUI.OverviewGrid.MinSelectableSize;this._setWindowPosition(null,end);}
_resizeWindowMaximum(){this._setWindowPosition(0,this._parentElement.clientWidth);}
_setWindow(windowLeft,windowRight){this.windowLeft=windowLeft;this.windowRight=windowRight;this._updateCurtains();this.dispatchEventToListeners(PerfUI.OverviewGrid.Events.WindowChanged);}
_updateCurtains(){let left=this.windowLeft;let right=this.windowRight;const width=right-left;const widthInPixels=width*this._parentElement.clientWidth;const minWidthInPixels=PerfUI.OverviewGrid.MinSelectableSize/2;if(widthInPixels<minWidthInPixels){const factor=minWidthInPixels/widthInPixels;left=((this.windowRight+this.windowLeft)-width*factor)/2;right=((this.windowRight+this.windowLeft)+width*factor)/2;}
this._leftResizeElement.style.left=(100*left).toFixed(2)+'%';this._rightResizeElement.style.left=(100*right).toFixed(2)+'%';this._leftCurtainElement.style.width=(100*left).toFixed(2)+'%';this._rightCurtainElement.style.width=(100*(1-right)).toFixed(2)+'%';}
_setWindowPosition(start,end){const clientWidth=this._parentElement.clientWidth;const windowLeft=typeof start==='number'?start/clientWidth:this.windowLeft;const windowRight=typeof end==='number'?end/clientWidth:this.windowRight;this._setWindow(windowLeft,windowRight);}
_onMouseWheel(event){if(!this._enabled)
return;if(typeof event.wheelDeltaY==='number'&&event.wheelDeltaY){const zoomFactor=1.1;const mouseWheelZoomSpeed=1/120;const reference=event.offsetX/event.target.clientWidth;this._zoom(Math.pow(zoomFactor,-event.wheelDeltaY*mouseWheelZoomSpeed),reference);}
if(typeof event.wheelDeltaX==='number'&&event.wheelDeltaX){let offset=Math.round(event.wheelDeltaX*PerfUI.OverviewGrid.WindowScrollSpeedFactor);const windowLeft=this._leftResizeElement.offsetLeft+PerfUI.OverviewGrid.ResizerOffset;const windowRight=this._rightResizeElement.offsetLeft+PerfUI.OverviewGrid.ResizerOffset;if(windowLeft-offset<0)
offset=windowLeft;if(windowRight-offset>this._parentElement.clientWidth)
offset=windowRight-this._parentElement.clientWidth;this._setWindowPosition(windowLeft-offset,windowRight-offset);event.preventDefault();}}
_zoom(factor,reference){let left=this.windowLeft;let right=this.windowRight;const windowSize=right-left;let newWindowSize=factor*windowSize;if(newWindowSize>1){newWindowSize=1;factor=newWindowSize/windowSize;}
left=reference+(left-reference)*factor;left=Number.constrain(left,0,1-newWindowSize);right=reference+(right-reference)*factor;right=Number.constrain(right,newWindowSize,1);this._setWindow(left,right);}};PerfUI.OverviewGrid.Events={WindowChanged:Symbol('WindowChanged')};PerfUI.OverviewGrid.WindowSelector=class{constructor(parent,position){this._startPosition=position;this._width=parent.offsetWidth;this._windowSelector=createElement('div');this._windowSelector.className='overview-grid-window-selector';this._windowSelector.style.left=this._startPosition+'px';this._windowSelector.style.right=this._width-this._startPosition+'px';parent.appendChild(this._windowSelector);}
_close(position){position=Math.max(0,Math.min(position,this._width));this._windowSelector.remove();return this._startPosition<position?{start:this._startPosition,end:position}:{start:position,end:this._startPosition};}
_updatePosition(position){position=Math.max(0,Math.min(position,this._width));if(position<this._startPosition){this._windowSelector.style.left=position+'px';this._windowSelector.style.right=this._width-this._startPosition+'px';}else{this._windowSelector.style.left=this._startPosition+'px';this._windowSelector.style.right=this._width-position+'px';}}};;PerfUI.PieChartOptions;PerfUI.PieChart=class{constructor(options){const{size,formatter,showLegend,chartName}=options;this.element=createElement('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'perf_ui/pieChart.css');const root=this._shadowRoot.createChild('div','root');UI.ARIAUtils.markAsGroup(root);UI.ARIAUtils.setAccessibleName(root,chartName);this._chartRoot=root.createChild('div','chart-root');const svg=this._createSVGChild(this._chartRoot,'svg');this._group=this._createSVGChild(svg,'g');this._innerR=0.618;const strokeWidth=1/size;let circle=this._createSVGChild(this._group,'circle');circle.setAttribute('r',1);circle.setAttribute('stroke','hsl(0, 0%, 80%)');circle.setAttribute('fill','transparent');circle.setAttribute('stroke-width',strokeWidth);circle=this._createSVGChild(this._group,'circle');circle.setAttribute('r',this._innerR);circle.setAttribute('stroke','hsl(0, 0%, 80%)');circle.setAttribute('fill','transparent');circle.setAttribute('stroke-width',strokeWidth);this._foregroundElement=this._chartRoot.createChild('div','pie-chart-foreground');this._totalElement=this._foregroundElement.createChild('div','pie-chart-total');this._formatter=formatter;this._slices=[];this._lastAngle=-Math.PI/2;if(showLegend)
this._legend=root.createChild('div','pie-chart-legend');this._setSize(size);}
setTotal(totalValue){for(let i=0;i<this._slices.length;++i)
this._slices[i].remove();this._slices=[];this._totalValue=totalValue;this._lastAngle=-Math.PI/2;let totalString;if(totalValue)
totalString=this._formatter?this._formatter(totalValue):totalValue;else
totalString='';this._totalElement.textContent=totalString;if(this._legend){this._legend.removeChildren();const legendItem=this._addLegendItem(totalValue,ls`Total`);UI.ARIAUtils.setLabelledBy(this._totalElement,legendItem);}}
_setSize(value){this._group.setAttribute('transform','scale('+(value/2)+') translate(1, 1) scale(0.99, 0.99)');const size=value+'px';this._chartRoot.style.width=size;this._chartRoot.style.height=size;}
addSlice(value,color,name){let sliceAngle=value/this._totalValue*2*Math.PI;if(!isFinite(sliceAngle))
return;sliceAngle=Math.min(sliceAngle,2*Math.PI*0.9999);const path=this._createSVGChild(this._group,'path');const x1=Math.cos(this._lastAngle);const y1=Math.sin(this._lastAngle);this._lastAngle+=sliceAngle;const x2=Math.cos(this._lastAngle);const y2=Math.sin(this._lastAngle);const r2=this._innerR;const x3=x2*r2;const y3=y2*r2;const x4=x1*r2;const y4=y1*r2;const largeArc=sliceAngle>Math.PI?1:0;path.setAttribute('d',`M${x1},${y1} A1,1,0,${largeArc},1,${x2},${y2} L${x3},${y3} A${r2},${r2},0,${largeArc},0,${x4},${y4} Z`);path.setAttribute('fill',color);this._slices.push(path);if(this._legend){const legendItem=this._addLegendItem(value,name,color);UI.ARIAUtils.setLabelledBy(path,legendItem);}}
_createSVGChild(parent,childType){const child=parent.ownerDocument.createElementNS('http://www.w3.org/2000/svg',childType);parent.appendChild(child);return child;}
_addLegendItem(value,name,color){const node=this._legend.ownerDocument.createElement('div');node.className='pie-chart-legend-row';if(this._legend.childElementCount)
this._legend.insertBefore(node,this._legend.lastElementChild);else
this._legend.appendChild(node);const sizeDiv=node.createChild('div','pie-chart-size');const swatchDiv=node.createChild('div','pie-chart-swatch');const nameDiv=node.createChild('div','pie-chart-name');if(color)
swatchDiv.style.backgroundColor=color;else
swatchDiv.classList.add('pie-chart-empty-swatch');nameDiv.textContent=name;sizeDiv.textContent=this._formatter?this._formatter(value):value;return node;}};;PerfUI.TimelineGrid=class{constructor(){this.element=createElement('div');UI.appendStyle(this.element,'perf_ui/timelineGrid.css');this._dividersElement=this.element.createChild('div','resources-dividers');this._gridHeaderElement=createElement('div');this._gridHeaderElement.classList.add('timeline-grid-header');this._eventDividersElement=this._gridHeaderElement.createChild('div','resources-event-dividers');this._dividersLabelBarElement=this._gridHeaderElement.createChild('div','resources-dividers-label-bar');this.element.appendChild(this._gridHeaderElement);}
static calculateGridOffsets(calculator,freeZoneAtLeft){const minGridSlicePx=64;const clientWidth=calculator.computePosition(calculator.maximumBoundary());let dividersCount=clientWidth/minGridSlicePx;let gridSliceTime=calculator.boundarySpan()/dividersCount;const pixelsPerTime=clientWidth/calculator.boundarySpan();const logGridSliceTime=Math.ceil(Math.log(gridSliceTime)/Math.LN10);gridSliceTime=Math.pow(10,logGridSliceTime);if(gridSliceTime*pixelsPerTime>=5*minGridSlicePx)
gridSliceTime=gridSliceTime/5;if(gridSliceTime*pixelsPerTime>=2*minGridSlicePx)
gridSliceTime=gridSliceTime/2;const firstDividerTime=Math.ceil((calculator.minimumBoundary()-calculator.zeroTime())/gridSliceTime)*gridSliceTime+
calculator.zeroTime();let lastDividerTime=calculator.maximumBoundary();lastDividerTime+=minGridSlicePx/pixelsPerTime;dividersCount=Math.ceil((lastDividerTime-firstDividerTime)/gridSliceTime);if(!gridSliceTime)
dividersCount=0;const offsets=[];for(let i=0;i<dividersCount;++i){const time=firstDividerTime+gridSliceTime*i;if(calculator.computePosition(time)<freeZoneAtLeft)
continue;offsets.push({position:Math.floor(calculator.computePosition(time)),time:time});}
return{offsets:offsets,precision:Math.max(0,-Math.floor(Math.log(gridSliceTime*1.01)/Math.LN10))};}
static drawCanvasGrid(context,dividersData){context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);const height=Math.floor(context.canvas.height/window.devicePixelRatio);context.strokeStyle=UI.themeSupport.patchColorText('rgba(0, 0, 0, 0.1)',UI.ThemeSupport.ColorUsage.Foreground);context.lineWidth=1;context.translate(0.5,0.5);context.beginPath();for(const offsetInfo of dividersData.offsets){context.moveTo(offsetInfo.position,0);context.lineTo(offsetInfo.position,height);}
context.stroke();context.restore();}
static drawCanvasHeaders(context,dividersData,formatTimeFunction,paddingTop,headerHeight,freeZoneAtLeft){context.save();context.scale(window.devicePixelRatio,window.devicePixelRatio);const width=Math.ceil(context.canvas.width/window.devicePixelRatio);context.beginPath();context.fillStyle=UI.themeSupport.patchColorText('rgba(255, 255, 255, 0.5)',UI.ThemeSupport.ColorUsage.Background);context.fillRect(0,0,width,headerHeight);context.fillStyle=UI.themeSupport.patchColorText('#333',UI.ThemeSupport.ColorUsage.Foreground);context.textBaseline='hanging';context.font='11px '+Host.fontFamily();const paddingRight=4;for(const offsetInfo of dividersData.offsets){const text=formatTimeFunction(offsetInfo.time);const textWidth=context.measureText(text).width;const textPosition=offsetInfo.position-textWidth-paddingRight;if(!freeZoneAtLeft||freeZoneAtLeft<textPosition)
context.fillText(text,textPosition,paddingTop);}
context.restore();}
get dividersElement(){return this._dividersElement;}
get dividersLabelBarElement(){return this._dividersLabelBarElement;}
removeDividers(){this._dividersElement.removeChildren();this._dividersLabelBarElement.removeChildren();}
updateDividers(calculator,freeZoneAtLeft){const dividersData=PerfUI.TimelineGrid.calculateGridOffsets(calculator,freeZoneAtLeft);const dividerOffsets=dividersData.offsets;const precision=dividersData.precision;const dividersElementClientWidth=this._dividersElement.clientWidth;let divider=(this._dividersElement.firstChild);let dividerLabelBar=(this._dividersLabelBarElement.firstChild);for(let i=0;i<dividerOffsets.length;++i){if(!divider){divider=createElement('div');divider.className='resources-divider';this._dividersElement.appendChild(divider);dividerLabelBar=createElement('div');dividerLabelBar.className='resources-divider';const label=createElement('div');label.className='resources-divider-label';dividerLabelBar._labelElement=label;dividerLabelBar.appendChild(label);this._dividersLabelBarElement.appendChild(dividerLabelBar);}
const time=dividerOffsets[i].time;const position=dividerOffsets[i].position;dividerLabelBar._labelElement.textContent=calculator.formatValue(time,precision);const percentLeft=100*position/dividersElementClientWidth;divider.style.left=percentLeft+'%';dividerLabelBar.style.left=percentLeft+'%';divider=(divider.nextSibling);dividerLabelBar=(dividerLabelBar.nextSibling);}
while(divider){const nextDivider=divider.nextSibling;this._dividersElement.removeChild(divider);divider=nextDivider;}
while(dividerLabelBar){const nextDivider=dividerLabelBar.nextSibling;this._dividersLabelBarElement.removeChild(dividerLabelBar);dividerLabelBar=nextDivider;}
return true;}
addEventDivider(divider){this._eventDividersElement.appendChild(divider);}
addEventDividers(dividers){this._gridHeaderElement.removeChild(this._eventDividersElement);for(const divider of dividers)
this._eventDividersElement.appendChild(divider);this._gridHeaderElement.appendChild(this._eventDividersElement);}
removeEventDividers(){this._eventDividersElement.removeChildren();}
hideEventDividers(){this._eventDividersElement.classList.add('hidden');}
showEventDividers(){this._eventDividersElement.classList.remove('hidden');}
hideDividers(){this._dividersElement.classList.add('hidden');}
showDividers(){this._dividersElement.classList.remove('hidden');}
setScrollTop(scrollTop){this._dividersLabelBarElement.style.top=scrollTop+'px';this._eventDividersElement.style.top=scrollTop+'px';}};PerfUI.TimelineGrid.DividersData;PerfUI.TimelineGrid.Calculator=function(){};PerfUI.TimelineGrid.Calculator.prototype={computePosition(time){},formatValue(time,precision){},minimumBoundary(){},zeroTime(){},maximumBoundary(){},boundarySpan(){}};;PerfUI.TimelineOverviewPane=class extends UI.VBox{constructor(prefix){super();this.element.id=prefix+'-overview-pane';this._overviewCalculator=new PerfUI.TimelineOverviewCalculator();this._overviewGrid=new PerfUI.OverviewGrid(prefix);this.element.appendChild(this._overviewGrid.element);this._cursorArea=this._overviewGrid.element.createChild('div','overview-grid-cursor-area');this._cursorElement=this._overviewGrid.element.createChild('div','overview-grid-cursor-position');this._cursorArea.addEventListener('mousemove',this._onMouseMove.bind(this),true);this._cursorArea.addEventListener('mouseleave',this._hideCursor.bind(this),true);this._overviewGrid.setResizeEnabled(false);this._overviewGrid.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);this._overviewGrid.setClickHandler(this._onClick.bind(this));this._overviewControls=[];this._markers=new Map();this._overviewInfo=new PerfUI.TimelineOverviewPane.OverviewInfo(this._cursorElement);this._updateThrottler=new Common.Throttler(100);this._cursorEnabled=false;this._cursorPosition=0;this._lastWidth=0;}
_onMouseMove(event){if(!this._cursorEnabled)
return;this._cursorPosition=event.offsetX+event.target.offsetLeft;this._cursorElement.style.left=this._cursorPosition+'px';this._cursorElement.style.visibility='visible';this._overviewInfo.setContent(this._buildOverviewInfo());}
async _buildOverviewInfo(){const document=this.element.ownerDocument;const x=this._cursorPosition;const elements=await Promise.all(this._overviewControls.map(control=>control.overviewInfoPromise(x)));const fragment=document.createDocumentFragment();elements.remove(null);fragment.appendChildren.apply(fragment,elements);return fragment;}
_hideCursor(){this._cursorElement.style.visibility='hidden';this._overviewInfo.hide();}
wasShown(){this._update();}
willHide(){this._overviewInfo.hide();}
onResize(){const width=this.element.offsetWidth;if(width===this._lastWidth)
return;this._lastWidth=width;this.scheduleUpdate();}
setOverviewControls(overviewControls){for(let i=0;i<this._overviewControls.length;++i)
this._overviewControls[i].dispose();for(let i=0;i<overviewControls.length;++i){overviewControls[i].setCalculator(this._overviewCalculator);overviewControls[i].show(this._overviewGrid.element);}
this._overviewControls=overviewControls;this._update();}
setBounds(minimumBoundary,maximumBoundary){this._overviewCalculator.setBounds(minimumBoundary,maximumBoundary);this._overviewGrid.setResizeEnabled(true);this._cursorEnabled=true;}
scheduleUpdate(){this._updateThrottler.schedule(process.bind(this));function process(){this._update();return Promise.resolve();}}
_update(){if(!this.isShowing())
return;this._overviewCalculator.setDisplayWidth(this._overviewGrid.clientWidth());for(let i=0;i<this._overviewControls.length;++i)
this._overviewControls[i].update();this._overviewGrid.updateDividers(this._overviewCalculator);this._updateMarkers();this._updateWindow();}
setMarkers(markers){this._markers=markers;}
_updateMarkers(){const filteredMarkers=new Map();for(const time of this._markers.keys()){const marker=this._markers.get(time);const position=Math.round(this._overviewCalculator.computePosition(time));if(filteredMarkers.has(position))
continue;filteredMarkers.set(position,marker);marker.style.left=position+'px';}
this._overviewGrid.removeEventDividers();this._overviewGrid.addEventDividers(filteredMarkers.valuesArray());}
reset(){this._windowStartTime=0;this._windowEndTime=Infinity;this._overviewCalculator.reset();this._overviewGrid.reset();this._overviewGrid.setResizeEnabled(false);this._cursorEnabled=false;this._hideCursor();this._markers=new Map();for(const control of this._overviewControls)
control.reset();this._overviewInfo.hide();this.scheduleUpdate();}
_onClick(event){return this._overviewControls.some(control=>control.onClick(event));}
_onWindowChanged(event){if(this._muteOnWindowChanged)
return;if(!this._overviewControls.length)
return;const absoluteMin=this._overviewCalculator.minimumBoundary();const timeSpan=this._overviewCalculator.maximumBoundary()-absoluteMin;const windowTimes={startTime:absoluteMin+timeSpan*this._overviewGrid.windowLeft(),endTime:absoluteMin+timeSpan*this._overviewGrid.windowRight()};this._windowStartTime=windowTimes.startTime;this._windowEndTime=windowTimes.endTime;this.dispatchEventToListeners(PerfUI.TimelineOverviewPane.Events.WindowChanged,windowTimes);}
setWindowTimes(startTime,endTime){if(startTime===this._windowStartTime&&endTime===this._windowEndTime)
return;this._windowStartTime=startTime;this._windowEndTime=endTime;this._updateWindow();this.dispatchEventToListeners(PerfUI.TimelineOverviewPane.Events.WindowChanged,{startTime:startTime,endTime:endTime});}
_updateWindow(){if(!this._overviewControls.length)
return;const absoluteMin=this._overviewCalculator.minimumBoundary();const timeSpan=this._overviewCalculator.maximumBoundary()-absoluteMin;const haveRecords=absoluteMin>0;const left=haveRecords&&this._windowStartTime?Math.min((this._windowStartTime-absoluteMin)/timeSpan,1):0;const right=haveRecords&&this._windowEndTime<Infinity?(this._windowEndTime-absoluteMin)/timeSpan:1;this._muteOnWindowChanged=true;this._overviewGrid.setWindow(left,right);this._muteOnWindowChanged=false;}};PerfUI.TimelineOverviewPane.Events={WindowChanged:Symbol('WindowChanged')};PerfUI.TimelineOverviewCalculator=class{constructor(){this.reset();}
computePosition(time){return(time-this._minimumBoundary)/this.boundarySpan()*this._workingArea;}
positionToTime(position){return position/this._workingArea*this.boundarySpan()+this._minimumBoundary;}
setBounds(minimumBoundary,maximumBoundary){this._minimumBoundary=minimumBoundary;this._maximumBoundary=maximumBoundary;}
setDisplayWidth(clientWidth){this._workingArea=clientWidth;}
reset(){this.setBounds(0,100);}
formatValue(value,precision){return Number.preciseMillisToString(value-this.zeroTime(),precision);}
maximumBoundary(){return this._maximumBoundary;}
minimumBoundary(){return this._minimumBoundary;}
zeroTime(){return this._minimumBoundary;}
boundarySpan(){return this._maximumBoundary-this._minimumBoundary;}};PerfUI.TimelineOverview=function(){};PerfUI.TimelineOverview.prototype={show(parentElement,insertBefore){},update(){},dispose(){},reset(){},overviewInfoPromise(x){},onClick(event){},};PerfUI.TimelineOverviewBase=class extends UI.VBox{constructor(){super();this._calculator=null;this._canvas=this.element.createChild('canvas','fill');this._context=this._canvas.getContext('2d');}
width(){return this._canvas.width;}
height(){return this._canvas.height;}
context(){return this._context;}
calculator(){return this._calculator;}
update(){this.resetCanvas();}
dispose(){this.detach();}
reset(){}
overviewInfoPromise(x){return Promise.resolve((null));}
setCalculator(calculator){this._calculator=calculator;}
onClick(event){return false;}
resetCanvas(){if(this.element.clientWidth)
this.setCanvasSize(this.element.clientWidth,this.element.clientHeight);}
setCanvasSize(width,height){this._canvas.width=width*window.devicePixelRatio;this._canvas.height=height*window.devicePixelRatio;}};PerfUI.TimelineOverviewPane.OverviewInfo=class{constructor(anchor){this._anchorElement=anchor;this._glassPane=new UI.GlassPane();this._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.PierceContents);this._glassPane.setMarginBehavior(UI.GlassPane.MarginBehavior.Arrow);this._glassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);this._visible=false;this._element=UI.createShadowRootWithCoreStyles(this._glassPane.contentElement,'perf_ui/timelineOverviewInfo.css').createChild('div','overview-info');}
async setContent(contentPromise){this._visible=true;const content=await contentPromise;if(!this._visible)
return;this._element.removeChildren();this._element.appendChild(content);this._glassPane.setContentAnchorBox(this._anchorElement.boxInWindow());if(!this._glassPane.isShowing())
this._glassPane.show((this._anchorElement.ownerDocument));}
hide(){this._visible=false;this._glassPane.hide();}};;Runtime.cachedResources["perf_ui/chartViewport.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.chart-viewport-v-scroll {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n overflow-x: hidden;\n z-index: 200;\n padding-left: 1px;\n}\n\n.chart-viewport-v-scroll.always-show-scrollbar {\n overflow-y: scroll;\n}\n\n/* force non overlay scrollbars for Mac */\n:host-context(.platform-mac) .chart-viewport-v-scroll {\n right: 2px;\n top: 3px;\n bottom: 3px;\n}\n\n:host-context(.platform-mac) ::-webkit-scrollbar {\n width: 8px;\n}\n\n:host-context(.platform-mac) ::-webkit-scrollbar-thumb {\n background-color: hsla(0, 0%, 56%, 0.6);\n border-radius: 50px;\n}\n\n:host-context(.platform-mac) .chart-viewport-v-scroll:hover::-webkit-scrollbar-thumb {\n background-color: hsla(0, 0%, 25%, 0.6);\n}\n\n/* force non overlay scrollbars for Aura Overlay Scrollbar enabled */\n:host-context(.overlay-scrollbar-enabled) ::-webkit-scrollbar {\n width: 10px;\n}\n\n:host-context(.overlay-scrollbar-enabled) ::-webkit-scrollbar-thumb {\n background-color: hsla(0, 0%, 0%, 0.5);\n}\n\n:host-context(.overlay-scrollbar-enabled) .chart-viewport-v-scroll:hover::-webkit-scrollbar-thumb {\n background-color: hsla(0, 0%, 0%, 0.7);\n}\n\n.chart-viewport-selection-overlay {\n position: absolute;\n z-index: 100;\n background-color: rgba(56, 121, 217, 0.3);\n border-color: rgb(16, 81, 177);\n border-width: 0 1px;\n border-style: solid;\n pointer-events: none;\n top: 0;\n bottom: 0;\n text-align: center;\n}\n\n.chart-viewport-selection-overlay .time-span {\n white-space: nowrap;\n position: absolute;\n left: 0;\n right: 0;\n bottom: 0;\n}\n\n/*# sourceURL=perf_ui/chartViewport.css */";Runtime.cachedResources["perf_ui/filmStripView.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.film-strip-view {\n overflow-x: auto;\n overflow-y: hidden;\n align-content: flex-start;\n min-height: 81px;\n}\n\n.film-strip-view.time-based .frame .time {\n display: none;\n}\n\n.film-strip-view .label {\n margin: auto;\n font-size: 18px;\n color: #999;\n}\n\n.film-strip-view .frame {\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: 4px;\n flex: none;\n cursor: pointer;\n}\n\n.film-strip-view .frame .thumbnail {\n min-width: 24px;\n display: flex;\n flex-direction: row;\n align-items: center;\n pointer-events: none;\n margin: 4px 0 2px;\n border: 2px solid transparent;\n}\n\n.film-strip-view .frame:hover .thumbnail {\n border-color: #FBCA46;\n}\n\n.film-strip-view .frame .thumbnail img {\n height: auto;\n width: auto;\n max-width: 80px;\n max-height: 50px;\n pointer-events: none;\n box-shadow: 0 0 3px #bbb;\n flex: 0 0 auto;\n}\n\n.film-strip-view .frame:hover .thumbnail img {\n box-shadow: none;\n}\n\n.film-strip-view .frame .time {\n font-size: 10px;\n margin-top: 2px;\n}\n\n/*# sourceURL=perf_ui/filmStripView.css */";Runtime.cachedResources["perf_ui/flameChart.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.flame-chart-main-pane {\n overflow: hidden;\n}\n\n.flame-chart-marker-highlight-element {\n position: absolute;\n top: 1px;\n height: 18px;\n width: 6px;\n margin: 0 -3px;\n content: \"\";\n display: block;\n}\n\n.flame-chart-highlight-element {\n position: absolute;\n pointer-events: none;\n background-color: rgba(56, 121, 217, 0.1);\n}\n\n.flame-chart-selected-element {\n position: absolute;\n pointer-events: none;\n outline: 2px solid var(--sele
wasShown(){if(!this._model)
return;SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._suspendStateChanged,this);this._model.enable();this._suspendStateChanged();}
willHide(){if(!this._model)
return;SDK.targetManager.removeEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._suspendStateChanged,this);this._stopPolling();this._model.disable();}
modelAdded(model){if(this._model)
return;this._model=model;if(this.isShowing())
this.wasShown();}
modelRemoved(model){if(this._model!==model)
return;if(this.isShowing())
this.willHide();this._model=null;}
_suspendStateChanged(){const suspended=SDK.targetManager.allTargetsSuspended();if(suspended)
this._stopPolling();else
this._startPolling();this.contentElement.classList.toggle('suspended',suspended);}
_startPolling(){this._startTimestamp=0;this._pollTimer=setInterval(()=>this._poll(),this._pollIntervalMs);this.onResize();animate.call(this);function animate(){this._draw();this._animationId=this.contentElement.window().requestAnimationFrame(animate.bind(this));}}
_stopPolling(){clearInterval(this._pollTimer);this.contentElement.window().cancelAnimationFrame(this._animationId);this._metricsBuffer=[];}
async _poll(){const data=await this._model.requestMetrics();const timestamp=data.timestamp;const metrics=data.metrics;this._metricsBuffer.push({timestamp,metrics:metrics});const millisPerWidth=this._width/this._pixelsPerMs;const maxCount=Math.ceil(millisPerWidth/this._pollIntervalMs*2);if(this._metricsBuffer.length>maxCount*2)
this._metricsBuffer.splice(0,this._metricsBuffer.length-maxCount);this._controlPane.updateMetrics(metrics);}
_draw(){const ctx=(this._canvas.getContext('2d'));ctx.save();ctx.scale(window.devicePixelRatio,window.devicePixelRatio);ctx.clearRect(0,0,this._width,this._height);ctx.save();ctx.translate(0,this._scaleHeight);for(const chartInfo of this._controlPane.charts()){if(!this._controlPane.isActive(chartInfo.metrics[0].name))
continue;this._drawChart(ctx,chartInfo,this._graphHeight);ctx.translate(0,this._graphHeight);}
ctx.restore();this._drawHorizontalGrid(ctx);ctx.restore();}
_drawHorizontalGrid(ctx){const labelDistanceSeconds=10;const lightGray=UI.themeSupport.patchColorText('rgba(0, 0, 0, 0.02)',UI.ThemeSupport.ColorUsage.Foreground);ctx.font='10px '+Host.fontFamily();ctx.fillStyle=UI.themeSupport.patchColorText('rgba(0, 0, 0, 0.55)',UI.ThemeSupport.ColorUsage.Foreground);const currentTime=Date.now()/1000;for(let sec=Math.ceil(currentTime);;--sec){const x=this._width-((currentTime-sec)*1000-this._pollIntervalMs)*this._pixelsPerMs;if(x<-50)
break;ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,this._height);if(sec>=0&&sec%labelDistanceSeconds===0)
ctx.fillText(new Date(sec*1000).toLocaleTimeString(),x+4,12);ctx.strokeStyle=sec%labelDistanceSeconds?lightGray:this._gridColor;ctx.stroke();}}
_drawChart(ctx,chartInfo,height){ctx.save();ctx.rect(0,0,this._width,height);ctx.clip();const bottomPadding=8;const extraSpace=1.05;const max=this._calcMax(chartInfo)*extraSpace;const stackedChartBaseLandscape=chartInfo.stacked?new Map():null;const paths=[];for(let i=chartInfo.metrics.length-1;i>=0;--i){const metricInfo=chartInfo.metrics[i];paths.push({path:this._buildMetricPath(chartInfo,metricInfo,height-bottomPadding,max,i?stackedChartBaseLandscape:null),color:metricInfo.color});}
const backgroundColor=Common.Color.parse(UI.themeSupport.patchColorText('white',UI.ThemeSupport.ColorUsage.Background));for(const path of paths.reverse()){const color=path.color;ctx.save();ctx.fillStyle=backgroundColor.blendWith(Common.Color.parse(color).setAlpha(0.2)).asString(null);ctx.fill(path.path);ctx.strokeStyle=color;ctx.lineWidth=0.5;ctx.stroke(path.path);ctx.restore();}
ctx.fillStyle=UI.themeSupport.patchColorText('rgba(0, 0, 0, 0.55)',UI.ThemeSupport.ColorUsage.Foreground);ctx.font=`10px ${Host.fontFamily()}`;ctx.fillText(chartInfo.title,8,10);this._drawVerticalGrid(ctx,height-bottomPadding,max,chartInfo);ctx.restore();}
_calcMax(chartInfo){if(chartInfo.max)
return chartInfo.max;const width=this._width;const startTime=performance.now()-this._pollIntervalMs-width/this._pixelsPerMs;let max=-Infinity;for(const metricInfo of chartInfo.metrics){for(let i=this._metricsBuffer.length-1;i>=0;--i){const metrics=this._metricsBuffer[i];const value=metrics.metrics.get(metricInfo.name);max=Math.max(max,value);if(metrics.timestamp<startTime)
break;}}
if(!this._metricsBuffer.length)
return 10;const base10=Math.pow(10,Math.floor(Math.log10(max)));max=Math.ceil(max/base10/2)*base10*2;const alpha=0.2;chartInfo.currentMax=max*alpha+(chartInfo.currentMax||max)*(1-alpha);return chartInfo.currentMax;}
_drawVerticalGrid(ctx,height,max,info){let base=Math.pow(10,Math.floor(Math.log10(max)));const firstDigit=Math.floor(max/base);if(firstDigit!==1&&firstDigit%2===1)
base*=2;let scaleValue=Math.floor(max/base)*base;const span=max;const topPadding=18;const visibleHeight=height-topPadding;ctx.fillStyle=UI.themeSupport.patchColorText('rgba(0, 0, 0, 0.55)',UI.ThemeSupport.ColorUsage.Foreground);ctx.strokeStyle=this._gridColor;ctx.beginPath();for(let i=0;i<2;++i){const y=calcY(scaleValue);const labelText=PerformanceMonitor.PerformanceMonitor.MetricIndicator._formatNumber(scaleValue,info);ctx.moveTo(0,y);ctx.lineTo(4,y);ctx.moveTo(ctx.measureText(labelText).width+12,y);ctx.lineTo(this._width,y);ctx.fillText(labelText,8,calcY(scaleValue)+3);scaleValue/=2;}
ctx.stroke();ctx.beginPath();ctx.moveTo(0,height+0.5);ctx.lineTo(this._width,height+0.5);ctx.strokeStyle=UI.themeSupport.patchColorText('rgba(0, 0, 0, 0.2)',UI.ThemeSupport.ColorUsage.Foreground);ctx.stroke();function calcY(value){return Math.round(height-visibleHeight*value/span)+0.5;}}
_buildMetricPath(chartInfo,metricInfo,height,scaleMax,stackedChartBaseLandscape){const path=new Path2D();const topPadding=18;const visibleHeight=height-topPadding;if(visibleHeight<1)
return path;const span=scaleMax;const metricName=metricInfo.name;const pixelsPerMs=this._pixelsPerMs;const startTime=performance.now()-this._pollIntervalMs-this._width/pixelsPerMs;const smooth=chartInfo.smooth;let x=0;let lastY=0;let lastX=0;if(this._metricsBuffer.length){x=(this._metricsBuffer[0].timestamp-startTime)*pixelsPerMs;path.moveTo(x,calcY(0));path.lineTo(this._width+5,calcY(0));lastY=calcY(this._metricsBuffer.peekLast().metrics.get(metricName));lastX=this._width+5;path.lineTo(lastX,lastY);}
for(let i=this._metricsBuffer.length-1;i>=0;--i){const metrics=this._metricsBuffer[i];const timestamp=metrics.timestamp;let value=metrics.metrics.get(metricName);if(stackedChartBaseLandscape){value+=stackedChartBaseLandscape.get(timestamp)||0;value=Number.constrain(value,0,1);stackedChartBaseLandscape.set(timestamp,value);}
const y=calcY(value);x=(timestamp-startTime)*pixelsPerMs;if(smooth){const midX=(lastX+x)/2;path.bezierCurveTo(midX,lastY,midX,y,x,y);}else{path.lineTo(x,lastY);path.lineTo(x,y);}
lastX=x;lastY=y;if(timestamp<startTime)
break;}
return path;function calcY(value){return Math.round(height-visibleHeight*value/span)+0.5;}}
onResize(){super.onResize();this._width=this._canvas.offsetWidth;this._canvas.width=Math.round(this._width*window.devicePixelRatio);this._recalcChartHeight();}
_recalcChartHeight(){let height=this._scaleHeight;for(const chartInfo of this._controlPane.charts()){if(this._controlPane.isActive(chartInfo.metrics[0].name))
height+=this._graphHeight;}
this._height=Math.ceil(height*window.devicePixelRatio);this._canvas.height=this._height;this._canvas.style.height=`${this._height / window.devicePixelRatio}px`;}};PerformanceMonitor.PerformanceMonitor.Format={Percent:Symbol('Percent'),Bytes:Symbol('Bytes'),};PerformanceMonitor.PerformanceMonitor.ChartInfo;PerformanceMonitor.PerformanceMonitor.MetricInfo;PerformanceMonitor.PerformanceMonitor.ControlPane=class extends Common.Object{constructor(parent){super();this.element=parent.createChild('div','perfmon-control-pane');this._enabledChartsSetting=Common.settings.createSetting('perfmonActiveIndicators2',['TaskDuration','JSHeapTotalSize','Nodes']);this._enabledCharts=new Set(this._enabledChartsSetting.get());const format=PerformanceMonitor.PerformanceMonitor.Format;this._chartsInfo=[{title:Common.UIString('CPU usage'),metrics:[{name:'TaskDuration',color:'#999'},{name:'ScriptDuration',color:'orange'},{name:'LayoutDuration',color:'blueviolet'},{name:'RecalcStyleDuration',color:'violet'}],format:format.Percent,smooth:true,stacked:true,color:'red',max:1},{title:Common.UIString('JS heap size'),metrics:[{name:'JSHeapTotalSize',color:'#99f'},{name:'JSHeapUsedSize',color:'blue'}],format:format.Bytes,color:'blue'},{title:Common.UIString('DOM Nodes'),metrics:[{name:'Nodes',color:'green'}]},{title:Common.UIString('JS event listeners'),metrics:[{name:'JSEventListeners',color:'yellowgreen'}]},{title:Common.UIString('Documents'),metrics:[{name:'Documents',color:'darkblue'}]},{title:Common.UIString('Document Frames'),metrics:[{name:'Frames',color:'darkcyan'}]},{title:Common.UIString('Layouts / sec'),metrics:[{name:'LayoutCount',color:'hotpink'}]},{title:Common.UIString('Style recalcs / sec'),metrics:[{name:'RecalcStyleCount',color:'deeppink'}]}];for(const info of this._chartsInfo){for(const metric of info.metrics)
metric.color=UI.themeSupport.patchColorText(metric.color,UI.ThemeSupport.ColorUsage.Foreground);}
this._indicators=new Map();for(const chartInfo of this._chartsInfo){const chartName=chartInfo.metrics[0].name;const active=this._enabledCharts.has(chartName);const indicator=new PerformanceMonitor.PerformanceMonitor.MetricIndicator(this.element,chartInfo,active,this._onToggle.bind(this,chartName));this._indicators.set(chartName,indicator);}}
_onToggle(chartName,active){if(active)
this._enabledCharts.add(chartName);else
this._enabledCharts.delete(chartName);this._enabledChartsSetting.set(Array.from(this._enabledCharts));this.dispatchEventToListeners(PerformanceMonitor.PerformanceMonitor.ControlPane.Events.MetricChanged);}
charts(){return this._chartsInfo;}
isActive(metricName){return this._enabledCharts.has(metricName);}
updateMetrics(metrics){for(const name of this._indicators.keys()){if(metrics.has(name))
this._indicators.get(name).setValue(metrics.get(name));}}};PerformanceMonitor.PerformanceMonitor.ControlPane.Events={MetricChanged:Symbol('MetricChanged')};PerformanceMonitor.PerformanceMonitor.MetricIndicator=class{constructor(parent,info,active,onToggle){const color=info.color||info.metrics[0].color;this._info=info;this._active=active;this._onToggle=onToggle;this.element=parent.createChild('div','perfmon-indicator');this._swatchElement=UI.Icon.create('smallicon-checkmark-square','perfmon-indicator-swatch');this._swatchElement.style.backgroundColor=color;this.element.appendChild(this._swatchElement);this.element.createChild('div','perfmon-indicator-title').textContent=info.title;this._valueElement=this.element.createChild('div','perfmon-indicator-value');this._valueElement.style.color=color;this.element.addEventListener('click',()=>this._toggleIndicator());this.element.addEventListener('keypress',event=>this._handleKeypress(event));this.element.classList.toggle('active',active);UI.ARIAUtils.markAsCheckbox(this.element);UI.ARIAUtils.setChecked(this.element,this._active);this.element.tabIndex=0;}
static _formatNumber(value,info){if(!PerformanceMonitor.PerformanceMonitor.MetricIndicator._numberFormatter){PerformanceMonitor.PerformanceMonitor.MetricIndicator._numberFormatter=new Intl.NumberFormat('en-US',{maximumFractionDigits:1});PerformanceMonitor.PerformanceMonitor.MetricIndicator._percentFormatter=new Intl.NumberFormat('en-US',{maximumFractionDigits:1,style:'percent'});}
switch(info.format){case PerformanceMonitor.PerformanceMonitor.Format.Percent:return PerformanceMonitor.PerformanceMonitor.MetricIndicator._percentFormatter.format(value);case PerformanceMonitor.PerformanceMonitor.Format.Bytes:return Number.bytesToString(value);default:return PerformanceMonitor.PerformanceMonitor.MetricIndicator._numberFormatter.format(value);}}
setValue(value){this._valueElement.textContent=PerformanceMonitor.PerformanceMonitor.MetricIndicator._formatNumber(value,this._info);}
_toggleIndicator(){this._active=!this._active;this.element.classList.toggle('active',this._active);UI.ARIAUtils.setChecked(this.element,this._active);this._onToggle(this._active);}
_handleKeypress(event){const keyboardEvent=(event);if(keyboardEvent.key===' '||keyboardEvent.key==='Enter')
this._toggleIndicator();}};PerformanceMonitor.PerformanceMonitor.MetricIndicator._format=new Intl.NumberFormat('en-US',{maximumFractionDigits:1});;Runtime.cachedResources["performance_monitor/performanceMonitor.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.perfmon-pane {\n overflow: hidden;\n}\n\n.perfmon-pane.suspended {\n opacity: 0.4;\n pointer-events: none;\n}\n\n.perfmon-pane .perfmon-chart-suspend-overlay {\n display: none;\n font-size: 26px;\n align-items: center;\n justify-content: center;\n}\n\n.perfmon-pane.suspended .perfmon-chart-suspend-overlay {\n display: flex;\n}\n\n.perfmon-control-pane {\n display: flex;\n flex-direction: column;\n padding: 6px 0;\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n.perfmon-chart-container {\n display: flex;\n flex: 1 1;\n border-left: 1px solid #ccc;\n overflow-y: auto;\n}\n\n.perfmon-chart-container canvas {\n width: 100%;\n}\n\n.perfmon-indicator {\n padding: 6px 12px;\n margin: -1px 0;\n display: flex;\n flex-shrink: 0;\n width: 210px;\n}\n\n.perfmon-indicator:hover {\n background-color: #f8f8f8;\n}\n\n.perfmon-indicator[data-keyboard-focus=\"true\"]:focus {\n background-color: #f8f8f8;\n}\n\n.perfmon-indicator-swatch {\n margin-right: 6px;\n}\n\n.perfmon-indicator:not(.active) .perfmon-indicator-swatch {\n background-color: #eee !important;\n}\n\n.perfmon-indicator-title {\n flex: 0 0 115px;\n}\n\n.perfmon-indicator:not(.active) .perfmon-indicator-title {\n color: #aaa;\n}\n\n.perfmon-indicator-value {\n flex: 0 0 55px;\n text-align: right;\n overflow: visible;\n}\n\n.perfmon-indicator:not(.active) .perfmon-indicator-value {\n opacity: 0;\n}\n\n/*# sourceURL=performance_monitor/performanceMonitor.css */";Profiler.ProfileType=class extends Common.Object{constructor(id,name){super();this._id=id;this._name=name;this._profiles=[];this._profileBeingRecorded=null;this._nextProfileUid=1;if(!window.opener)
window.addEventListener('unload',this._clearTempStorage.bind(this),false);}
typeName(){return'';}
nextProfileUid(){return this._nextProfileUid;}
incrementProfileUid(){return this._nextProfileUid++;}
hasTemporaryView(){return false;}
fileExtension(){return null;}
get buttonTooltip(){return'';}
get id(){return this._id;}
get treeItemTitle(){return this._name;}
get name(){return this._name;}
buttonClicked(){return false;}
get description(){return'';}
isInstantProfile(){return false;}
isEnabled(){return true;}
getProfiles(){function isFinished(profile){return this._profileBeingRecorded!==profile;}
return this._profiles.filter(isFinished.bind(this));}
customContent(){return null;}
getProfile(uid){for(let i=0;i<this._profiles.length;++i){if(this._profiles[i].uid===uid)
return this._profiles[i];}
return null;}
loadFromFile(file){let name=file.name;const fileExtension=this.fileExtension();if(fileExtension&&name.endsWith(fileExtension))
name=name.substr(0,name.length-fileExtension.length);const profile=this.createProfileLoadedFromFile(name);profile.setFromFile();this.setProfileBeingRecorded(profile);this.addProfile(profile);return profile.loadFromFile(file);}
createProfileLoadedFromFile(title){throw new Error('Needs implemented.');}
addProfile(profile){this._profiles.push(profile);this.dispatchEventToListeners(Profiler.ProfileType.Events.AddProfileHeader,profile);}
removeProfile(profile){const index=this._profiles.indexOf(profile);if(index===-1)
return;this._profiles.splice(index,1);this._disposeProfile(profile);}
_clearTempStorage(){for(let i=0;i<this._profiles.length;++i)
this._profiles[i].removeTempFile();}
profileBeingRecorded(){return this._profileBeingRecorded;}
setProfileBeingRecorded(profile){this._profileBeingRecorded=profile;}
profileBeingRecordedRemoved(){}
reset(){for(const profile of this._profiles.slice())
this._disposeProfile(profile);this._profiles=[];this._nextProfileUid=1;}
_disposeProfile(profile){this.dispatchEventToListeners(Profiler.ProfileType.Events.RemoveProfileHeader,profile);profile.dispose();if(this._profileBeingRecorded===profile){this.profileBeingRecordedRemoved();this.setProfileBeingRecorded(null);}}};Profiler.ProfileType.Events={AddProfileHeader:Symbol('add-profile-header'),ProfileComplete:Symbol('profile-complete'),RemoveProfileHeader:Symbol('remove-profile-header'),ViewUpdated:Symbol('view-updated')};Profiler.ProfileType.DataDisplayDelegate=function(){};Profiler.ProfileType.DataDisplayDelegate.prototype={showProfile(profile){},showObject(snapshotObjectId,perspectiveName){},async linkifyObject(nodeIndex){}};;Profiler.ProfileHeader=class extends Common.Object{constructor(profileType,title){super();this._profileType=profileType;this.title=title;this.uid=profileType.incrementProfileUid();this._fromFile=false;}
setTitle(title){this.title=title;this.dispatchEventToListeners(Profiler.ProfileHeader.Events.ProfileTitleChanged,this);}
profileType(){return this._profileType;}
updateStatus(subtitle,wait){this.dispatchEventToListeners(Profiler.ProfileHeader.Events.UpdateStatus,new Profiler.ProfileHeader.StatusUpdate(subtitle,wait));}
createSidebarTreeElement(dataDisplayDelegate){throw new Error('Not implemented.');}
createView(dataDisplayDelegate){throw new Error('Not implemented.');}
removeTempFile(){if(this._tempFile)
this._tempFile.remove();}
dispose(){}
canSaveToFile(){return false;}
saveToFile(){throw new Error('Not implemented');}
loadFromFile(file){throw new Error('Not implemented');}
fromFile(){return this._fromFile;}
setFromFile(){this._fromFile=true;}
setProfile(profile){}};Profiler.ProfileHeader.StatusUpdate=class{constructor(subtitle,wait){this.subtitle=subtitle;this.wait=wait;}};Profiler.ProfileHeader.Events={UpdateStatus:Symbol('UpdateStatus'),ProfileReceived:Symbol('ProfileReceived'),ProfileTitleChanged:Symbol('ProfileTitleChanged')};;Profiler.ProfilesPanel=class extends UI.PanelWithSidebar{constructor(name,profileTypes,recordingActionId){super(name);this._profileTypes=profileTypes;this.registerRequiredCSS('profiler/heapProfiler.css');this.registerRequiredCSS('profiler/profilesPanel.css');this.registerRequiredCSS('object_ui/objectValue.css');const mainContainer=new UI.VBox();this.splitWidget().setMainWidget(mainContainer);this.profilesItemTreeElement=new Profiler.ProfilesSidebarTreeElement(this);this._sidebarTree=new UI.TreeOutlineInShadow();this._sidebarTree.registerRequiredCSS('profiler/profilesSidebarTree.css');this._sidebarTree.element.classList.add('profiles-sidebar-tree-box');this.panelSidebarElement().appendChild(this._sidebarTree.element);this._sidebarTree.appendChild(this.profilesItemTreeElement);this.profileViews=createElement('div');this.profileViews.id='profile-views';this.profileViews.classList.add('vbox');mainContainer.element.appendChild(this.profileViews);this._toolbarElement=createElementWithClass('div','profiles-toolbar');mainContainer.element.insertBefore(this._toolbarElement,mainContainer.element.firstChild);this.panelSidebarElement().classList.add('profiles-tree-sidebar');const toolbarContainerLeft=createElementWithClass('div','profiles-toolbar');this.panelSidebarElement().insertBefore(toolbarContainerLeft,this.panelSidebarElement().firstChild);const toolbar=new UI.Toolbar('',toolbarContainerLeft);this._toggleRecordAction=(UI.actionRegistry.action(recordingActionId));this._toggleRecordButton=UI.Toolbar.createActionButton(this._toggleRecordAction);toolbar.appendToolbarItem(this._toggleRecordButton);this.clearResultsButton=new UI.ToolbarButton(Common.UIString('Clear all profiles'),'largeicon-clear');this.clearResultsButton.addEventListener(UI.ToolbarButton.Events.Click,this._reset,this);toolbar.appendToolbarItem(this.clearResultsButton);toolbar.appendSeparator();toolbar.appendToolbarItem(UI.Toolbar.createActionButtonForId('components.collect-garbage'));this._profileViewToolbar=new UI.Toolbar('',this._toolbarElement);this._profileGroups={};this._launcherView=new Profiler.ProfileLauncherView(this);this._launcherView.addEventListener(Profiler.ProfileLauncherView.Events.ProfileTypeSelected,this._onProfileTypeSelected,this);this._profileToView=[];this._typeIdToSidebarSection={};const types=this._profileTypes;for(let i=0;i<types.length;i++)
this._registerProfileType(types[i]);this._launcherView.restoreSelectedProfileType();this.profilesItemTreeElement.select();this._showLauncherView();this._createFileSelectorElement();this.element.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),false);this.contentElement.addEventListener('keydown',this._onKeyDown.bind(this),false);SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._onSuspendStateChanged,this);UI.context.addFlavorChangeListener(SDK.CPUProfilerModel,this._updateProfileTypeSpecificUI,this);UI.context.addFlavorChangeListener(SDK.HeapProfilerModel,this._updateProfileTypeSpecificUI,this);}
_onKeyDown(event){let handled=false;if(event.key==='ArrowDown'&&!event.altKey)
handled=this._sidebarTree.selectNext();else if(event.key==='ArrowUp'&&!event.altKey)
handled=this._sidebarTree.selectPrevious();if(handled)
event.consume(true);}
searchableView(){return this.visibleView&&this.visibleView.searchableView?this.visibleView.searchableView():null;}
_createFileSelectorElement(){if(this._fileSelectorElement)
this.element.removeChild(this._fileSelectorElement);this._fileSelectorElement=UI.createFileSelectorElement(this._loadFromFile.bind(this));Profiler.ProfilesPanel._fileSelectorElement=this._fileSelectorElement;this.element.appendChild(this._fileSelectorElement);}
_findProfileTypeByExtension(fileName){return this._profileTypes.find(type=>!!type.fileExtension()&&fileName.endsWith(type.fileExtension()||''))||null;}
async _loadFromFile(file){this._createFileSelectorElement();const profileType=this._findProfileTypeByExtension(file.name);if(!profileType){const extensions=new Set(this._profileTypes.map(type=>type.fileExtension()).filter(ext=>ext));Common.console.error(Common.UIString(`Can't load file. Supported file extensions: '%s'.`,Array.from(extensions).join(`', '`)));return;}
if(!!profileType.profileBeingRecorded()){Common.console.error(Common.UIString(`Can't load profile while another profile is being recorded.`));return;}
const error=await profileType.loadFromFile(file);if(error)
UI.MessageDialog.show(Common.UIString('Profile loading failed: %s.',error.message));}
toggleRecord(){if(!this._toggleRecordAction.enabled())
return true;const type=this._selectedProfileType;const isProfiling=type.buttonClicked();this._updateToggleRecordAction(isProfiling);if(isProfiling){this._launcherView.profileStarted();if(type.hasTemporaryView())
this.showProfile(type.profileBeingRecorded());}else{this._launcherView.profileFinished();}
return true;}
_onSuspendStateChanged(){this._updateToggleRecordAction(this._toggleRecordAction.toggled());}
_updateToggleRecordAction(toggled){const hasSelectedTarget=!!(UI.context.flavor(SDK.CPUProfilerModel)||UI.context.flavor(SDK.HeapProfilerModel));const enable=toggled||(!SDK.targetManager.allTargetsSuspended()&&hasSelectedTarget);this._toggleRecordAction.setEnabled(enable);this._toggleRecordAction.setToggled(toggled);if(enable)
this._toggleRecordButton.setTitle(this._selectedProfileType?this._selectedProfileType.buttonTooltip:'');else
this._toggleRecordButton.setTitle(UI.anotherProfilerActiveLabel());if(this._selectedProfileType)
this._launcherView.updateProfileType(this._selectedProfileType,enable);}
_profileBeingRecordedRemoved(){this._updateToggleRecordAction(false);this._launcherView.profileFinished();}
_onProfileTypeSelected(event){this._selectedProfileType=(event.data);this._updateProfileTypeSpecificUI();}
_updateProfileTypeSpecificUI(){this._updateToggleRecordAction(this._toggleRecordAction.toggled());}
_reset(){this._profileTypes.forEach(type=>type.reset());delete this.visibleView;this._profileGroups={};this._updateToggleRecordAction(false);this._launcherView.profileFinished();this._sidebarTree.element.classList.remove('some-expandable');this._launcherView.detach();this.profileViews.removeChildren();this._profileViewToolbar.removeToolbarItems();this.clearResultsButton.element.classList.remove('hidden');this.profilesItemTreeElement.select();this._showLauncherView();}
_showLauncherView(){this.closeVisibleView();this._profileViewToolbar.removeToolbarItems();this._launcherView.show(this.profileViews);this.visibleView=this._launcherView;this._toolbarElement.classList.add('hidden');}
_registerProfileType(profileType){this._launcherView.addProfileType(profileType);const profileTypeSection=new Profiler.ProfileTypeSidebarSection(this,profileType);this._typeIdToSidebarSection[profileType.id]=profileTypeSection;this._sidebarTree.appendChild(profileTypeSection);profileTypeSection.childrenListElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),false);function onAddProfileHeader(event){this._addProfileHeader((event.data));}
function onRemoveProfileHeader(event){this._removeProfileHeader((event.data));}
function profileComplete(event){this.showProfile((event.data));}
profileType.addEventListener(Profiler.ProfileType.Events.ViewUpdated,this._updateProfileTypeSpecificUI,this);profileType.addEventListener(Profiler.ProfileType.Events.AddProfileHeader,onAddProfileHeader,this);profileType.addEventListener(Profiler.ProfileType.Events.RemoveProfileHeader,onRemoveProfileHeader,this);profileType.addEventListener(Profiler.ProfileType.Events.ProfileComplete,profileComplete,this);const profiles=profileType.getProfiles();for(let i=0;i<profiles.length;i++)
this._addProfileHeader(profiles[i]);}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);if(this.panelSidebarElement().isSelfOrAncestor(event.srcElement)){contextMenu.defaultSection().appendItem(Common.UIString('Load\u2026'),this._fileSelectorElement.click.bind(this._fileSelectorElement));}
contextMenu.show();}
showLoadFromFileDialog(){this._fileSelectorElement.click();}
_addProfileHeader(profile){const profileType=profile.profileType();const typeId=profileType.id;this._typeIdToSidebarSection[typeId].addProfileHeader(profile);if(!this.visibleView||this.visibleView===this._launcherView)
this.showProfile(profile);}
_removeProfileHeader(profile){if(profile.profileType().profileBeingRecorded()===profile)
this._profileBeingRecordedRemoved();const i=this._indexOfViewForProfile(profile);if(i!==-1)
this._profileToView.splice(i,1);const typeId=profile.profileType().id;const sectionIsEmpty=this._typeIdToSidebarSection[typeId].removeProfileHeader(profile);if(sectionIsEmpty){this.profilesItemTreeElement.select();this._showLauncherView();}}
showProfile(profile){if(!profile||(profile.profileType().profileBeingRecorded()===profile)&&!profile.profileType().hasTemporaryView())
return null;const view=this.viewForProfile(profile);if(view===this.visibleView)
return view;this.closeVisibleView();view.show(this.profileViews);view.focus();this._toolbarElement.classList.remove('hidden');this.visibleView=view;const profileTypeSection=this._typeIdToSidebarSection[profile.profileType().id];const sidebarElement=profileTypeSection.sidebarElementForProfile(profile);sidebarElement.revealAndSelect();this._profileViewToolbar.removeToolbarItems();const toolbarItems=view.syncToolbarItems();for(let i=0;i<toolbarItems.length;++i)
this._profileViewToolbar.appendToolbarItem(toolbarItems[i]);return view;}
showObject(snapshotObjectId,perspectiveName){}
async linkifyObject(nodeIndex){return null;}
viewForProfile(profile){const index=this._indexOfViewForProfile(profile);if(index!==-1)
return this._profileToView[index].view;const view=profile.createView(this);view.element.classList.add('profile-view');this._profileToView.push({profile:profile,view:view});return view;}
_indexOfViewForProfile(profile){return this._profileToView.findIndex(item=>item.profile===profile);}
closeVisibleView(){if(this.visibleView)
this.visibleView.detach();delete this.visibleView;}
focus(){this._sidebarTree.focus();}};Profiler.ProfileTypeSidebarSection=class extends UI.TreeElement{constructor(dataDisplayDelegate,profileType){super(profileType.treeItemTitle.escapeHTML(),true);this.selectable=false;this._dataDisplayDelegate=dataDisplayDelegate;this._profileTreeElements=[];this._profileGroups={};this.expand();this.hidden=true;this.setCollapsible(false);}
addProfileHeader(profile){this.hidden=false;const profileType=profile.profileType();let sidebarParent=this;const profileTreeElement=profile.createSidebarTreeElement(this._dataDisplayDelegate);this._profileTreeElements.push(profileTreeElement);if(!profile.fromFile()&&profileType.profileBeingRecorded()!==profile){const profileTitle=profile.title;let group=this._profileGroups[profileTitle];if(!group){group=new Profiler.ProfileTypeSidebarSection.ProfileGroup();this._profileGroups[profileTitle]=group;}
group.profileSidebarTreeElements.push(profileTreeElement);const groupSize=group.profileSidebarTreeElements.length;if(groupSize===2){group.sidebarTreeElement=new Profiler.ProfileGroupSidebarTreeElement(this._dataDisplayDelegate,profile.title);const firstProfileTreeElement=group.profileSidebarTreeElements[0];const index=this.children().indexOf(firstProfileTreeElement);this.insertChild(group.sidebarTreeElement,index);const selected=firstProfileTreeElement.selected;this.removeChild(firstProfileTreeElement);group.sidebarTreeElement.appendChild(firstProfileTreeElement);if(selected)
firstProfileTreeElement.revealAndSelect();firstProfileTreeElement.setSmall(true);firstProfileTreeElement.setMainTitle(Common.UIString('Run %d',1));this.treeOutline.element.classList.add('some-expandable');}
if(groupSize>=2){sidebarParent=group.sidebarTreeElement;profileTreeElement.setSmall(true);profileTreeElement.setMainTitle(Common.UIString('Run %d',groupSize));}}
sidebarParent.appendChild(profileTreeElement);}
removeProfileHeader(profile){const index=this._sidebarElementIndex(profile);if(index===-1)
return false;const profileTreeElement=this._profileTreeElements[index];this._profileTreeElements.splice(index,1);let sidebarParent=this;const group=this._profileGroups[profile.title];if(group){const groupElements=group.profileSidebarTreeElements;groupElements.splice(groupElements.indexOf(profileTreeElement),1);if(groupElements.length===1){const pos=sidebarParent.children().indexOf((group.sidebarTreeElement));group.sidebarTreeElement.removeChild(groupElements[0]);this.insertChild(groupElements[0],pos);groupElements[0].setSmall(false);groupElements[0].setMainTitle(profile.title);this.removeChild(group.sidebarTreeElement);}
if(groupElements.length!==0)
sidebarParent=group.sidebarTreeElement;}
sidebarParent.removeChild(profileTreeElement);profileTreeElement.dispose();if(this.childCount())
return false;this.hidden=true;return true;}
sidebarElementForProfile(profile){const index=this._sidebarElementIndex(profile);return index===-1?null:this._profileTreeElements[index];}
_sidebarElementIndex(profile){const elements=this._profileTreeElements;for(let i=0;i<elements.length;i++){if(elements[i].profile===profile)
return i;}
return-1;}
onattach(){this.listItemElement.classList.add('profiles-tree-section');}};Profiler.ProfileTypeSidebarSection.ProfileGroup=class{constructor(){this.profileSidebarTreeElements=[];this.sidebarTreeElement=null;}};Profiler.ProfileSidebarTreeElement=class extends UI.TreeElement{constructor(dataDisplayDelegate,profile,className){super('',false);this._iconElement=createElementWithClass('div','icon');this._titlesElement=createElementWithClass('div','titles no-subtitle');this._titleContainer=this._titlesElement.createChild('span','title-container');this._titleElement=this._titleContainer.createChild('span','title');this._subtitleElement=this._titlesElement.createChild('span','subtitle');this._titleElement.textContent=profile.title;this._className=className;this._small=false;this._dataDisplayDelegate=dataDisplayDelegate;this.profile=profile;profile.addEventListener(Profiler.ProfileHeader.Events.UpdateStatus,this._updateStatus,this);if(profile.canSaveToFile())
this._createSaveLink();else
profile.addEventListener(Profiler.ProfileHeader.Events.ProfileReceived,this._onProfileReceived,this);}
_createSaveLink(){this._saveLinkElement=this._titleContainer.createChild('span','save-link');this._saveLinkElement.textContent=Common.UIString('Save');this._saveLinkElement.addEventListener('click',this._saveProfile.bind(this),false);}
_onProfileReceived(event){this._createSaveLink();}
_updateStatus(event){const statusUpdate=event.data;if(statusUpdate.subtitle!==null){this._subtitleElement.textContent=statusUpdate.subtitle||'';this._titlesElement.classList.toggle('no-subtitle',!statusUpdate.subtitle);}
if(typeof statusUpdate.wait==='boolean'&&this.listItemElement)
this.listItemElement.classList.toggle('wait',statusUpdate.wait);}
ondblclick(event){if(!this._editing)
this._startEditing((event.target));return false;}
_startEditing(eventTarget){const container=eventTarget.enclosingNodeOrSelfWithClass('title');if(!container)
return;const config=new UI.InplaceEditor.Config(this._editingCommitted.bind(this),this._editingCancelled.bind(this));this._editing=UI.InplaceEditor.startEditing(container,config);}
_editingCommitted(container,newTitle){delete this._editing;this.profile.setTitle(newTitle);}
_editingCancelled(){delete this._editing;}
dispose(){this.profile.removeEventListener(Profiler.ProfileHeader.Events.UpdateStatus,this._updateStatus,this);this.profile.removeEventListener(Profiler.ProfileHeader.Events.ProfileReceived,this._onProfileReceived,this);}
onselect(){this._dataDisplayDelegate.showProfile(this.profile);return true;}
ondelete(){this.profile.profileType().removeProfile(this.profile);return true;}
onattach(){if(this._className)
this.listItemElement.classList.add(this._className);if(this._small)
this.listItemElement.classList.add('small');this.listItemElement.appendChildren(this._iconElement,this._titlesElement);this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const profile=this.profile;const contextMenu=new UI.ContextMenu(event);contextMenu.headerSection().appendItem(Common.UIString('Load\u2026'),Profiler.ProfilesPanel._fileSelectorElement.click.bind(Profiler.ProfilesPanel._fileSelectorElement));if(profile.canSaveToFile())
contextMenu.saveSection().appendItem(Common.UIString('Save\u2026'),profile.saveToFile.bind(profile));contextMenu.footerSection().appendItem(Common.UIString('Delete'),this.ondelete.bind(this));contextMenu.show();}
_saveProfile(event){this.profile.saveToFile();}
setSmall(small){this._small=small;if(this.listItemElement)
this.listItemElement.classList.toggle('small',this._small);}
setMainTitle(title){this._titleElement.textContent=title;}};Profiler.ProfileGroupSidebarTreeElement=class extends UI.TreeElement{constructor(dataDisplayDelegate,title){super('',true);this.selectable=false;this._dataDisplayDelegate=dataDisplayDelegate;this._title=title;this.expand();this.toggleOnClick=true;}
onselect(){const hasChildren=this.childCount()>0;if(hasChildren)
this._dataDisplayDelegate.showProfile(this.lastChild().profile);return hasChildren;}
onattach(){this.listItemElement.classList.add('profile-group-sidebar-tree-item');this.listItemElement.createChild('div','icon');this.listItemElement.createChild('div','titles no-subtitle').createChild('span','title-container').createChild('span','title').textContent=this._title;}};Profiler.ProfilesSidebarTreeElement=class extends UI.TreeElement{constructor(panel){super('',false);this.selectable=true;this._panel=panel;}
onselect(){this._panel._showLauncherView();return true;}
onattach(){this.listItemElement.classList.add('profile-launcher-view-tree-item');this.listItemElement.createChild('div','icon');this.listItemElement.createChild('div','titles no-subtitle').createChild('span','title-container').createChild('span','title').textContent=Common.UIString('Profiles');}};Profiler.JSProfilerPanel=class extends Profiler.ProfilesPanel{constructor(){const registry=Profiler.ProfileTypeRegistry.instance;super('js_profiler',[registry.cpuProfileType],'profiler.js-toggle-recording');}
wasShown(){UI.context.setFlavor(Profiler.JSProfilerPanel,this);}
willHide(){UI.context.setFlavor(Profiler.JSProfilerPanel,null);}
handleAction(context,actionId){const panel=UI.context.flavor(Profiler.JSProfilerPanel);console.assert(panel&&panel instanceof Profiler.JSProfilerPanel);panel.toggleRecord();return true;}};;Profiler.ProfileView=class extends UI.SimpleView{constructor(){super(Common.UIString('Profile'));this._profile=null;this._searchableView=new UI.SearchableView(this);this._searchableView.setPlaceholder(Common.UIString('Find by cost (>50ms), name or file'));this._searchableView.show(this.element);const columns=([]);columns.push({id:'self',title:this.columnHeader('self'),width:'120px',fixedWidth:true,sortable:true,sort:DataGrid.DataGrid.Order.Descending});columns.push({id:'total',title:this.columnHeader('total'),width:'120px',fixedWidth:true,sortable:true});columns.push({id:'function',title:Common.UIString('Function'),disclosure:true,sortable:true});this.dataGrid=new DataGrid.DataGrid(columns);this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortProfile,this);this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._nodeSelected.bind(this,true));this.dataGrid.addEventListener(DataGrid.DataGrid.Events.DeselectedNode,this._nodeSelected.bind(this,false));this.viewSelectComboBox=new UI.ToolbarComboBox(this._changeView.bind(this));this.focusButton=new UI.ToolbarButton(Common.UIString('Focus selected function'),'largeicon-visibility');this.focusButton.setEnabled(false);this.focusButton.addEventListener(UI.ToolbarButton.Events.Click,this._focusClicked,this);this.excludeButton=new UI.ToolbarButton(Common.UIString('Exclude selected function'),'largeicon-delete');this.excludeButton.setEnabled(false);this.excludeButton.addEventListener(UI.ToolbarButton.Events.Click,this._excludeClicked,this);this.resetButton=new UI.ToolbarButton(Common.UIString('Restore all functions'),'largeicon-refresh');this.resetButton.setEnabled(false);this.resetButton.addEventListener(UI.ToolbarButton.Events.Click,this._resetClicked,this);this._linkifier=new Components.Linkifier(Profiler.ProfileView._maxLinkLength);}
static buildPopoverTable(entryInfo){const table=createElement('table');for(const entry of entryInfo){const row=table.createChild('tr');row.createChild('td').textContent=entry.title;row.createChild('td').textContent=entry.value;}
return table;}
setProfile(profile){this._profile=profile;this._bottomUpProfileDataGridTree=null;this._topDownProfileDataGridTree=null;this._changeView();this.refresh();}
profile(){return this._profile;}
initialize(nodeFormatter,viewTypes){this._nodeFormatter=nodeFormatter;this._viewType=Common.settings.createSetting('profileView',Profiler.ProfileView.ViewTypes.Heavy);viewTypes=viewTypes||[Profiler.ProfileView.ViewTypes.Flame,Profiler.ProfileView.ViewTypes.Heavy,Profiler.ProfileView.ViewTypes.Tree];const optionNames=new Map([[Profiler.ProfileView.ViewTypes.Flame,ls`Chart`],[Profiler.ProfileView.ViewTypes.Heavy,ls`Heavy (Bottom Up)`],[Profiler.ProfileView.ViewTypes.Tree,ls`Tree (Top Down)`],[Profiler.ProfileView.ViewTypes.Text,ls`Text (Top Down)`],]);const options=new Map(viewTypes.map(type=>[type,this.viewSelectComboBox.createOption(optionNames.get(type),'',type)]));const optionName=this._viewType.get()||viewTypes[0];const option=options.get(optionName)||options.get(viewTypes[0]);this.viewSelectComboBox.select(option);this._changeView();if(this._flameChart)
this._flameChart.update();}
focus(){if(this._flameChart)
this._flameChart.focus();else
super.focus();}
columnHeader(columnId){throw'Not implemented';}
selectRange(timeLeft,timeRight){if(!this._flameChart)
return;this._flameChart.selectRange(timeLeft,timeRight);}
syncToolbarItems(){return[this.viewSelectComboBox,this.focusButton,this.excludeButton,this.resetButton];}
_getBottomUpProfileDataGridTree(){if(!this._bottomUpProfileDataGridTree){this._bottomUpProfileDataGridTree=new Profiler.BottomUpProfileDataGridTree(this._nodeFormatter,this._searchableView,this._profile.root,this.adjustedTotal);}
return this._bottomUpProfileDataGridTree;}
_getTopDownProfileDataGridTree(){if(!this._topDownProfileDataGridTree){this._topDownProfileDataGridTree=new Profiler.TopDownProfileDataGridTree(this._nodeFormatter,this._searchableView,this._profile.root,this.adjustedTotal);}
return this._topDownProfileDataGridTree;}
willHide(){this._currentSearchResultIndex=-1;}
refresh(){if(!this.profileDataGridTree)
return;const selectedProfileNode=this.dataGrid.selectedNode?this.dataGrid.selectedNode.profileNode:null;this.dataGrid.rootNode().removeChildren();const children=this.profileDataGridTree.children;const count=children.length;for(let index=0;index<count;++index)
this.dataGrid.rootNode().appendChild(children[index]);if(selectedProfileNode)
selectedProfileNode.selected=true;}
refreshVisibleData(){let child=this.dataGrid.rootNode().children[0];while(child){child.refresh();child=child.traverseNextNode(false,null,true);}}
searchableView(){return this._searchableView;}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return false;}
searchCanceled(){this._searchableElement.searchCanceled();}
performSearch(searchConfig,shouldJump,jumpBackwards){this._searchableElement.performSearch(searchConfig,shouldJump,jumpBackwards);}
jumpToNextSearchResult(){this._searchableElement.jumpToNextSearchResult();}
jumpToPreviousSearchResult(){this._searchableElement.jumpToPreviousSearchResult();}
linkifier(){return this._linkifier;}
_ensureTextViewCreated(){if(this._textView)
return;this._textView=new UI.SimpleView(ls`Call tree`);this._textView.registerRequiredCSS('profiler/profilesPanel.css');this.populateTextView(this._textView);}
populateTextView(view){}
createFlameChartDataProvider(){throw'Not implemented';}
_ensureFlameChartCreated(){if(this._flameChart)
return;this._dataProvider=this.createFlameChartDataProvider();this._flameChart=new Profiler.CPUProfileFlameChart(this._searchableView,this._dataProvider);this._flameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected,this._onEntrySelected.bind(this));}
_onEntrySelected(event){const entryIndex=event.data;const node=this._dataProvider._entryNodes[entryIndex];const debuggerModel=this._profileHeader._debuggerModel;if(!node||!node.scriptId||!debuggerModel)
return;const script=debuggerModel.scriptForId(node.scriptId);if(!script)
return;const location=(debuggerModel.createRawLocation(script,node.lineNumber,node.columnNumber));Common.Revealer.reveal(Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(location));}
_changeView(){if(!this._profile)
return;this._searchableView.closeSearch();if(this._visibleView)
this._visibleView.detach();this._viewType.set(this.viewSelectComboBox.selectedOption().value);switch(this._viewType.get()){case Profiler.ProfileView.ViewTypes.Flame:this._ensureFlameChartCreated();this._visibleView=this._flameChart;this._searchableElement=this._flameChart;break;case Profiler.ProfileView.ViewTypes.Tree:this.profileDataGridTree=this._getTopDownProfileDataGridTree();this._sortProfile();this._visibleView=this.dataGrid.asWidget();this._searchableElement=this.profileDataGridTree;break;case Profiler.ProfileView.ViewTypes.Heavy:this.profileDataGridTree=this._getBottomUpProfileDataGridTree();this._sortProfile();this._visibleView=this.dataGrid.asWidget();this._searchableElement=this.profileDataGridTree;break;case Profiler.ProfileView.ViewTypes.Text:this._ensureTextViewCreated();this._visibleView=this._textView;this._searchableElement=this._textView;break;}
const isFlame=this._viewType.get()===Profiler.ProfileView.ViewTypes.Flame;this.focusButton.setVisible(!isFlame);this.excludeButton.setVisible(!isFlame);this.resetButton.setVisible(!isFlame);this._visibleView.show(this._searchableView.element);}
_nodeSelected(selected){this.focusButton.setEnabled(selected);this.excludeButton.setEnabled(selected);}
_focusClicked(event){if(!this.dataGrid.selectedNode)
return;this.resetButton.setEnabled(true);this.profileDataGridTree.focus(this.dataGrid.selectedNode);this.refresh();this.refreshVisibleData();Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuProfileNodeFocused);}
_excludeClicked(event){const selectedNode=this.dataGrid.selectedNode;if(!selectedNode)
return;selectedNode.deselect();this.resetButton.setEnabled(true);this.profileDataGridTree.exclude(selectedNode);this.refresh();this.refreshVisibleData();Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuProfileNodeExcluded);}
_resetClicked(event){this.resetButton.setEnabled(false);this.profileDataGridTree.restore();this._linkifier.reset();this.refresh();this.refreshVisibleData();}
_sortProfile(){const sortAscending=this.dataGrid.isSortOrderAscending();const sortColumnId=this.dataGrid.sortColumnId();const sortProperty=sortColumnId==='function'?'functionName':sortColumnId||'';this.profileDataGridTree.sort(Profiler.ProfileDataGridTree.propertyComparator(sortProperty,sortAscending));this.refresh();}};Profiler.ProfileView._maxLinkLength=30;Profiler.ProfileView.ViewTypes={Flame:'Flame',Tree:'Tree',Heavy:'Heavy',Text:'Text'};Profiler.WritableProfileHeader=class extends Profiler.ProfileHeader{constructor(debuggerModel,type,title){super(type,title||Common.UIString('Profile %d',type.nextProfileUid()));this._debuggerModel=debuggerModel;this._tempFile=null;}
_onChunkTransferred(reader){this.updateStatus(Common.UIString('Loading\u2026 %d%%',Number.bytesToString(this._jsonifiedProfile.length)));}
_onError(reader){this.updateStatus(Common.UIString(`File '%s' read error: %s`,reader.fileName(),reader.error().message));}
async write(text){this._jsonifiedProfile+=text;}
close(){}
dispose(){this.removeTempFile();}
createSidebarTreeElement(panel){return new Profiler.ProfileSidebarTreeElement(panel,this,'profile-sidebar-tree-item');}
canSaveToFile(){return!this.fromFile()&&this._protocolProfile;}
async saveToFile(){const fileOutputStream=new Bindings.FileOutputStream();this._fileName=this._fileName||`${this.profileType().typeName()}-${new Date().toISO8601Compact()}${this.profileType().fileExtension()}`;const accepted=await fileOutputStream.open(this._fileName);if(!accepted||!this._tempFile)
return;const data=await this._tempFile.read();if(data)
await fileOutputStream.write(data);fileOutputStream.close();}
async loadFromFile(file){this.updateStatus(Common.UIString('Loading\u2026'),true);const fileReader=new Bindings.ChunkedFileReader(file,10000000,this._onChunkTransferred.bind(this));this._jsonifiedProfile='';const success=await fileReader.read(this);if(!success){this._onError(fileReader);return new Error(Common.UIString('Failed to read file'));}
this.updateStatus(Common.UIString('Parsing\u2026'),true);let error=null;try{this._profile=(JSON.parse(this._jsonifiedProfile));this.setProfile(this._profile);this.updateStatus(Common.UIString('Loaded'),false);}catch(e){error=e;this.profileType().removeProfile(this);}
this._jsonifiedProfile=null;if(this.profileType().profileBeingRecorded()===this)
this.profileType().setProfileBeingRecorded(null);return error;}
setProtocolProfile(profile){this.setProfile(profile);this._protocolProfile=profile;this._tempFile=new Bindings.TempFile();this._tempFile.write([JSON.stringify(profile)]);if(this.canSaveToFile())
this.dispatchEventToListeners(Profiler.ProfileHeader.Events.ProfileReceived);}};;Profiler.ProfileDataGridNode=class extends DataGrid.DataGridNode{constructor(profileNode,owningTree,hasChildren){super(null,hasChildren);this._searchMatchedSelfColumn=false;this._searchMatchedTotalColumn=false;this._searchMatchedFunctionColumn=false;this.profileNode=profileNode;this.tree=owningTree;this.childrenByCallUID=new Map();this.lastComparator=null;this.callUID=profileNode.callUID;this.self=profileNode.self;this.total=profileNode.total;this.functionName=UI.beautifyFunctionName(profileNode.functionName);this._deoptReason=profileNode.deoptReason||'';this.url=profileNode.url;}
static sort(gridNodeGroups,comparator,force){for(let gridNodeGroupIndex=0;gridNodeGroupIndex<gridNodeGroups.length;++gridNodeGroupIndex){const gridNodes=gridNodeGroups[gridNodeGroupIndex];const count=gridNodes.length;for(let index=0;index<count;++index){const gridNode=gridNodes[index];if(!force&&(!gridNode.expanded||gridNode.lastComparator===comparator)){if(gridNode.children.length)
gridNode.shouldRefreshChildren=true;continue;}
gridNode.lastComparator=comparator;const children=gridNode.children;const childCount=children.length;if(childCount){children.sort(comparator);for(let childIndex=0;childIndex<childCount;++childIndex)
children[childIndex].recalculateSiblings(childIndex);gridNodeGroups.push(children);}}}}
static merge(container,child,shouldAbsorb){container.self+=child.self;if(!shouldAbsorb)
container.total+=child.total;let children=container.children.slice();container.removeChildren();let count=children.length;for(let index=0;index<count;++index){if(!shouldAbsorb||children[index]!==child)
container.appendChild(children[index]);}
children=child.children.slice();count=children.length;for(let index=0;index<count;++index){const orphanedChild=children[index];const existingChild=container.childrenByCallUID.get(orphanedChild.callUID);if(existingChild)
existingChild.merge((orphanedChild),false);else
container.appendChild(orphanedChild);}}
static populate(container){if(container._populated)
return;container._populated=true;container.populateChildren();const currentComparator=container.tree.lastComparator;if(currentComparator)
container.sort(currentComparator,true);}
createCell(columnId){let cell;switch(columnId){case'self':cell=this._createValueCell(this.self,this.selfPercent);cell.classList.toggle('highlight',this._searchMatchedSelfColumn);break;case'total':cell=this._createValueCell(this.total,this.totalPercent);cell.classList.toggle('highlight',this._searchMatchedTotalColumn);break;case'function':cell=this.createTD(columnId);cell.classList.toggle('highlight',this._searchMatchedFunctionColumn);if(this._deoptReason){cell.classList.add('not-optimized');const warningIcon=UI.Icon.create('smallicon-warning','profile-warn-marker');warningIcon.title=Common.UIString('Not optimized: %s',this._deoptReason);cell.appendChild(warningIcon);}
cell.createTextChild(this.functionName);if(this.profileNode.scriptId==='0')
break;const urlElement=this.tree._formatter.linkifyNode(this);if(!urlElement)
break;urlElement.style.maxWidth='75%';cell.appendChild(urlElement);break;default:cell=super.createCell(columnId);break;}
return cell;}
_createValueCell(value,percent){const cell=createElementWithClass('td','numeric-column');const div=cell.createChild('div','profile-multiple-values');div.createChild('span').textContent=this.tree._formatter.formatValue(value,this);div.createChild('span','percent-column').textContent=this.tree._formatter.formatPercent(percent,this);return cell;}
sort(comparator,force){return Profiler.ProfileDataGridNode.sort([[this]],comparator,force);}
insertChild(profileDataGridNode,index){super.insertChild(profileDataGridNode,index);this.childrenByCallUID.set(profileDataGridNode.callUID,(profileDataGridNode));}
removeChild(profileDataGridNode){super.removeChild(profileDataGridNode);this.childrenByCallUID.delete(((profileDataGridNode)).callUID);}
removeChildren(){super.removeChildren();this.childrenByCallUID.clear();}
findChild(node){if(!node)
return null;return this.childrenByCallUID.get(node.callUID);}
get selfPercent(){return this.self/this.tree.total*100.0;}
get totalPercent(){return this.total/this.tree.total*100.0;}
populate(){Profiler.ProfileDataGridNode.populate(this);}
populateChildren(){}
save(){if(this._savedChildren)
return;this._savedSelf=this.self;this._savedTotal=this.total;this._savedChildren=this.children.slice();}
restore(){if(!this._savedChildren)
return;this.self=this._savedSelf;this.total=this._savedTotal;this.removeChildren();const children=this._savedChildren;const count=children.length;for(let index=0;index<count;++index){children[index].restore();this.appendChild(children[index]);}}
merge(child,shouldAbsorb){Profiler.ProfileDataGridNode.merge(this,child,shouldAbsorb);}};Profiler.ProfileDataGridTree=class{constructor(formatter,searchableView,total){this.tree=this;this.children=[];this._formatter=formatter;this._searchableView=searchableView;this.total=total;this.lastComparator=null;this.childrenByCallUID=new Map();this.deepSearch=true;}
static propertyComparator(property,isAscending){let comparator=Profiler.ProfileDataGridTree.propertyComparators[(isAscending?1:0)][property];if(!comparator){if(isAscending){comparator=function(lhs,rhs){if(lhs[property]<rhs[property])
return-1;if(lhs[property]>rhs[property])
return 1;return 0;};}else{comparator=function(lhs,rhs){if(lhs[property]>rhs[property])
return-1;if(lhs[property]<rhs[property])
return 1;return 0;};}
Profiler.ProfileDataGridTree.propertyComparators[(isAscending?1:0)][property]=comparator;}
return comparator;}
get expanded(){return true;}
appendChild(child){this.insertChild(child,this.children.length);}
insertChild(child,index){this.children.splice(index,0,child);this.childrenByCallUID.set(child.callUID,child);}
removeChildren(){this.children=[];this.childrenByCallUID.clear();}
populateChildren(){}
findChild(node){if(!node)
return null;return this.childrenByCallUID.get(node.callUID);}
sort(comparator,force){return Profiler.ProfileDataGridNode.sort([[this]],comparator,force);}
save(){if(this._savedChildren)
return;this._savedTotal=this.total;this._savedChildren=this.children.slice();}
restore(){if(!this._savedChildren)
return;this.children=this._savedChildren;this.total=this._savedTotal;const children=this.children;const count=children.length;for(let index=0;index<count;++index)
children[index].restore();this._savedChildren=null;}
_matchFunction(searchConfig){const query=searchConfig.query.trim();if(!query.length)
return null;const greaterThan=(query.startsWith('>'));const lessThan=(query.startsWith('<'));let equalTo=(query.startsWith('=')||((greaterThan||lessThan)&&query.indexOf('=')===1));const percentUnits=(query.endsWith('%'));const millisecondsUnits=(query.length>2&&query.endsWith('ms'));const secondsUnits=(!millisecondsUnits&&query.endsWith('s'));let queryNumber=parseFloat(query);if(greaterThan||lessThan||equalTo){if(equalTo&&(greaterThan||lessThan))
queryNumber=parseFloat(query.substring(2));else
queryNumber=parseFloat(query.substring(1));}
const queryNumberMilliseconds=(secondsUnits?(queryNumber*1000):queryNumber);if(!isNaN(queryNumber)&&!(greaterThan||lessThan))
equalTo=true;const matcher=createPlainTextSearchRegex(query,'i');function matchesQuery(profileDataGridNode){profileDataGridNode._searchMatchedSelfColumn=false;profileDataGridNode._searchMatchedTotalColumn=false;profileDataGridNode._searchMatchedFunctionColumn=false;if(percentUnits){if(lessThan){if(profileDataGridNode.selfPercent<queryNumber)
profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalPercent<queryNumber)
profileDataGridNode._searchMatchedTotalColumn=true;}else if(greaterThan){if(profileDataGridNode.selfPercent>queryNumber)
profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalPercent>queryNumber)
profileDataGridNode._searchMatchedTotalColumn=true;}
if(equalTo){if(profileDataGridNode.selfPercent===queryNumber)
profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalPercent===queryNumber)
profileDataGridNode._searchMatchedTotalColumn=true;}}else if(millisecondsUnits||secondsUnits){if(lessThan){if(profileDataGridNode.self<queryNumberMilliseconds)
profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.total<queryNumberMilliseconds)
profileDataGridNode._searchMatchedTotalColumn=true;}else if(greaterThan){if(profileDataGridNode.self>queryNumberMilliseconds)
profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.total>queryNumberMilliseconds)
profileDataGridNode._searchMatchedTotalColumn=true;}
if(equalTo){if(profileDataGridNode.self===queryNumberMilliseconds)
profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.total===queryNumberMilliseconds)
profileDataGridNode._searchMatchedTotalColumn=true;}}
if(profileDataGridNode.functionName.match(matcher)||(profileDataGridNode.url&&profileDataGridNode.url.match(matcher)))
profileDataGridNode._searchMatchedFunctionColumn=true;if(profileDataGridNode._searchMatchedSelfColumn||profileDataGridNode._searchMatchedTotalColumn||profileDataGridNode._searchMatchedFunctionColumn){profileDataGridNode.refresh();return true;}
return false;}
return matchesQuery;}
performSearch(searchConfig,shouldJump,jumpBackwards){this.searchCanceled();const matchesQuery=this._matchFunction(searchConfig);if(!matchesQuery)
return;this._searchResults=[];const deepSearch=this.deepSearch;for(let current=this.children[0];current;current=current.traverseNextNode(!deepSearch,null,!deepSearch)){if(matchesQuery(current))
this._searchResults.push({profileNode:current});}
this._searchResultIndex=jumpBackwards?0:this._searchResults.length-1;this._searchableView.updateSearchMatchesCount(this._searchResults.length);this._searchableView.updateCurrentMatchIndex(this._searchResultIndex);}
searchCanceled(){if(this._searchResults){for(let i=0;i<this._searchResults.length;++i){const profileNode=this._searchResults[i].profileNode;profileNode._searchMatchedSelfColumn=false;profileNode._searchMatchedTotalColumn=false;profileNode._searchMatchedFunctionColumn=false;profileNode.refresh();}}
this._searchResults=[];this._searchResultIndex=-1;}
jumpToNextSearchResult(){if(!this._searchResults||!this._searchResults.length)
return;this._searchResultIndex=(this._searchResultIndex+1)%this._searchResults.length;this._jumpToSearchResult(this._searchResultIndex);}
jumpToPreviousSearchResult(){if(!this._searchResults||!this._searchResults.length)
return;this._searchResultIndex=(this._searchResultIndex-1+this._searchResults.length)%this._searchResults.length;this._jumpToSearchResult(this._searchResultIndex);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return false;}
_jumpToSearchResult(index){const searchResult=this._searchResults[index];if(!searchResult)
return;const profileNode=searchResult.profileNode;profileNode.revealAndSelect();this._searchableView.updateCurrentMatchIndex(index);}};Profiler.ProfileDataGridTree.propertyComparators=[{},{}];Profiler.ProfileDataGridNode.Formatter=function(){};Profiler.ProfileDataGridNode.Formatter.prototype={formatValue(value,node){},formatPercent(value,node){},linkifyNode(node){}};;Profiler.BottomUpProfileDataGridNode=class extends Profiler.ProfileDataGridNode{constructor(profileNode,owningTree){super(profileNode,owningTree,!!profileNode.parent&&!!profileNode.parent.parent);this._remainingNodeInfos=[];}
static _sharedPopulate(container){const remainingNodeInfos=container._remainingNodeInfos;const count=remainingNodeInfos.length;for(let index=0;index<count;++index){const nodeInfo=remainingNodeInfos[index];const ancestor=nodeInfo.ancestor;const focusNode=nodeInfo.focusNode;let child=container.findChild(ancestor);if(child){const totalAccountedFor=nodeInfo.totalAccountedFor;child.self+=focusNode.self;if(!totalAccountedFor)
child.total+=focusNode.total;}else{child=new Profiler.BottomUpProfileDataGridNode(ancestor,(container.tree));if(ancestor!==focusNode){child.self=focusNode.self;child.total=focusNode.total;}
container.appendChild(child);}
const parent=ancestor.parent;if(parent&&parent.parent){nodeInfo.ancestor=parent;child._remainingNodeInfos.push(nodeInfo);}}
delete container._remainingNodeInfos;}
_takePropertiesFromProfileDataGridNode(profileDataGridNode){this.save();this.self=profileDataGridNode.self;this.total=profileDataGridNode.total;}
_keepOnlyChild(child){this.save();this.removeChildren();this.appendChild(child);}
_exclude(aCallUID){if(this._remainingNodeInfos)
this.populate();this.save();const children=this.children;let index=this.children.length;while(index--)
children[index]._exclude(aCallUID);const child=this.childrenByCallUID.get(aCallUID);if(child)
this.merge(child,true);}
restore(){super.restore();if(!this.children.length)
this.setHasChildren(this._willHaveChildren(this.profileNode));}
merge(child,shouldAbsorb){this.self-=child.self;super.merge(child,shouldAbsorb);}
populateChildren(){Profiler.BottomUpProfileDataGridNode._sharedPopulate(this);}
_willHaveChildren(profileNode){return!!(profileNode.parent&&profileNode.parent.parent);}};Profiler.BottomUpProfileDataGridTree=class extends Profiler.ProfileDataGridTree{constructor(formatter,searchableView,rootProfileNode,total){super(formatter,searchableView,total);this.deepSearch=false;let profileNodeUIDs=0;const profileNodeGroups=[[],[rootProfileNode]];const visitedProfileNodesForCallUID=new Map();this._remainingNodeInfos=[];for(let profileNodeGroupIndex=0;profileNodeGroupIndex<profileNodeGroups.length;++profileNodeGroupIndex){const parentProfileNodes=profileNodeGroups[profileNodeGroupIndex];const profileNodes=profileNodeGroups[++profileNodeGroupIndex];const count=profileNodes.length;for(let index=0;index<count;++index){const profileNode=profileNodes[index];if(!profileNode.UID)
profileNode.UID=++profileNodeUIDs;if(profileNode.parent){let visitedNodes=visitedProfileNodesForCallUID.get(profileNode.callUID);let totalAccountedFor=false;if(!visitedNodes){visitedNodes=new Set();visitedProfileNodesForCallUID.set(profileNode.callUID,visitedNodes);}else{const parentCount=parentProfileNodes.length;for(let parentIndex=0;parentIndex<parentCount;++parentIndex){if(visitedNodes.has(parentProfileNodes[parentIndex].UID)){totalAccountedFor=true;break;}}}
visitedNodes.add(profileNode.UID);this._remainingNodeInfos.push({ancestor:profileNode,focusNode:profileNode,totalAccountedFor:totalAccountedFor});}
const children=profileNode.children;if(children.length){profileNodeGroups.push(parentProfileNodes.concat([profileNode]));profileNodeGroups.push(children);}}}
Profiler.ProfileDataGridNode.populate(this);return this;}
focus(profileDataGridNode){if(!profileDataGridNode)
return;this.save();let currentNode=profileDataGridNode;let focusNode=profileDataGridNode;while(currentNode.parent&&(currentNode instanceof Profiler.ProfileDataGridNode)){currentNode._takePropertiesFromProfileDataGridNode(profileDataGridNode);focusNode=currentNode;currentNode=currentNode.parent;if(currentNode instanceof Profiler.ProfileDataGridNode)
currentNode._keepOnlyChild(focusNode);}
this.children=[focusNode];this.total=profileDataGridNode.total;}
exclude(profileDataGridNode){if(!profileDataGridNode)
return;this.save();const excludedCallUID=profileDataGridNode.callUID;const excludedTopLevelChild=this.childrenByCallUID.get(excludedCallUID);if(excludedTopLevelChild)
this.children.remove(excludedTopLevelChild);const children=this.children;const count=children.length;for(let index=0;index<count;++index)
children[index]._exclude(excludedCallUID);if(this.lastComparator)
this.sort(this.lastComparator,true);}
populateChildren(){Profiler.BottomUpProfileDataGridNode._sharedPopulate(this);}};;Profiler.TopDownProfileDataGridNode=class extends Profiler.ProfileDataGridNode{constructor(profileNode,owningTree){const hasChildren=!!(profileNode.children&&profileNode.children.length);super(profileNode,owningTree,hasChildren);this._remainingChildren=profileNode.children;}
static _sharedPopulate(container){const children=container._remainingChildren;const childrenLength=children.length;for(let i=0;i<childrenLength;++i){container.appendChild(new Profiler.TopDownProfileDataGridNode(children[i],(container.tree)));}
container._remainingChildren=null;}
static _excludeRecursively(container,aCallUID){if(container._remainingChildren)
container.populate();container.save();const children=container.children;let index=container.children.length;while(index--)
Profiler.TopDownProfileDataGridNode._excludeRecursively(children[index],aCallUID);const child=container.childrenByCallUID.get(aCallUID);if(child)
Profiler.ProfileDataGridNode.merge(container,child,true);}
populateChildren(){Profiler.TopDownProfileDataGridNode._sharedPopulate(this);}};Profiler.TopDownProfileDataGridTree=class extends Profiler.ProfileDataGridTree{constructor(formatter,searchableView,rootProfileNode,total){super(formatter,searchableView,total);this._remainingChildren=rootProfileNode.children;Profiler.ProfileDataGridNode.populate(this);}
focus(profileDataGridNode){if(!profileDataGridNode)
return;this.save();profileDataGridNode.savePosition();this.children=[profileDataGridNode];this.total=profileDataGridNode.total;}
exclude(profileDataGridNode){if(!profileDataGridNode)
return;this.save();Profiler.TopDownProfileDataGridNode._excludeRecursively(this,profileDataGridNode.callUID);if(this.lastComparator)
this.sort(this.lastComparator,true);}
restore(){if(!this._savedChildren)
return;this.children[0].restorePosition();super.restore();}
populateChildren(){Profiler.TopDownProfileDataGridNode._sharedPopulate(this);}};;Profiler.ProfileFlameChartDataProvider=class{constructor(){PerfUI.FlameChartDataProvider.call(this);this._colorGenerator=Profiler.ProfileFlameChartDataProvider.colorGenerator();}
static colorGenerator(){if(!Profiler.ProfileFlameChartDataProvider._colorGenerator){const colorGenerator=new Common.Color.Generator({min:30,max:330},{min:50,max:80,count:5},{min:80,max:90,count:3});colorGenerator.setColorForID('(idle)','hsl(0, 0%, 94%)');colorGenerator.setColorForID('(program)','hsl(0, 0%, 80%)');colorGenerator.setColorForID('(garbage collector)','hsl(0, 0%, 80%)');Profiler.ProfileFlameChartDataProvider._colorGenerator=colorGenerator;}
return Profiler.ProfileFlameChartDataProvider._colorGenerator;}
minimumBoundary(){return this._cpuProfile.profileStartTime;}
totalTime(){return this._cpuProfile.profileHead.total;}
formatValue(value,precision){return Number.preciseMillisToString(value,precision);}
maxStackDepth(){return this._maxStackDepth;}
timelineData(){return this._timelineData||this._calculateTimelineData();}
_calculateTimelineData(){throw'Not implemented.';}
prepareHighlightedEntryInfo(entryIndex){throw'Not implemented.';}
canJumpToEntry(entryIndex){return this._entryNodes[entryIndex].scriptId!=='0';}
entryTitle(entryIndex){const node=this._entryNodes[entryIndex];return UI.beautifyFunctionName(node.functionName);}
entryFont(entryIndex){if(!this._font){this._font='11px '+Host.fontFamily();this._boldFont='bold '+this._font;}
const node=this._entryNodes[entryIndex];return node.deoptReason?this._boldFont:this._font;}
entryColor(entryIndex){const node=this._entryNodes[entryIndex];return this._colorGenerator.colorForID(node.url||(node.scriptId!=='0'?node.scriptId:node.functionName));}
decorateEntry(entryIndex,context,text,barX,barY,barWidth,barHeight){return false;}
forceDecoration(entryIndex){return false;}
textColor(entryIndex){return'#333';}};Profiler.CPUProfileFlameChart=class extends UI.VBox{constructor(searchableView,dataProvider){super();this.element.id='cpu-flame-chart';this._searchableView=searchableView;this._overviewPane=new Profiler.CPUProfileFlameChart.OverviewPane(dataProvider);this._overviewPane.show(this.element);this._mainPane=new PerfUI.FlameChart(dataProvider,this._overviewPane);this._mainPane.setBarHeight(15);this._mainPane.setTextBaseline(4);this._mainPane.setTextPadding(2);this._mainPane.show(this.element);this._mainPane.addEventListener(PerfUI.FlameChart.Events.EntrySelected,this._onEntrySelected,this);this._overviewPane.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);this._dataProvider=dataProvider;this._searchResults=[];}
focus(){this._mainPane.focus();}
_onWindowChanged(event){const windowLeft=event.data.windowTimeLeft;const windowRight=event.data.windowTimeRight;this._mainPane.setWindowTimes(windowLeft,windowRight,true);}
selectRange(timeLeft,timeRight){this._overviewPane._selectRange(timeLeft,timeRight);}
_onEntrySelected(event){this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected,event.data);}
update(){this._overviewPane.update();this._mainPane.update();}
performSearch(searchConfig,shouldJump,jumpBackwards){const matcher=createPlainTextSearchRegex(searchConfig.query,searchConfig.caseSensitive?'':'i');const selectedEntryIndex=this._searchResultIndex!==-1?this._searchResults[this._searchResultIndex]:-1;this._searchResults=[];const entriesCount=this._dataProvider._entryNodes.length;for(let index=0;index<entriesCount;++index){if(this._dataProvider.entryTitle(index).match(matcher))
this._searchResults.push(index);}
if(this._searchResults.length){this._searchResultIndex=this._searchResults.indexOf(selectedEntryIndex);if(this._searchResultIndex===-1)
this._searchResultIndex=jumpBackwards?this._searchResults.length-1:0;this._mainPane.setSelectedEntry(this._searchResults[this._searchResultIndex]);}else{this.searchCanceled();}
this._searchableView.updateSearchMatchesCount(this._searchResults.length);this._searchableView.updateCurrentMatchIndex(this._searchResultIndex);}
searchCanceled(){this._mainPane.setSelectedEntry(-1);this._searchResults=[];this._searchResultIndex=-1;}
jumpToNextSearchResult(){this._searchResultIndex=(this._searchResultIndex+1)%this._searchResults.length;this._mainPane.setSelectedEntry(this._searchResults[this._searchResultIndex]);this._searchableView.updateCurrentMatchIndex(this._searchResultIndex);}
jumpToPreviousSearchResult(){this._searchResultIndex=(this._searchResultIndex-1+this._searchResults.length)%this._searchResults.length;this._mainPane.setSelectedEntry(this._searchResults[this._searchResultIndex]);this._searchableView.updateCurrentMatchIndex(this._searchResultIndex);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return false;}};Profiler.CPUProfileFlameChart.OverviewCalculator=class{constructor(dataProvider){this._dataProvider=dataProvider;}
_updateBoundaries(overviewPane){this._minimumBoundaries=overviewPane._dataProvider.minimumBoundary();const totalTime=overviewPane._dataProvider.totalTime();this._maximumBoundaries=this._minimumBoundaries+totalTime;this._xScaleFactor=overviewPane._overviewContainer.clientWidth/totalTime;}
computePosition(time){return(time-this._minimumBoundaries)*this._xScaleFactor;}
formatValue(value,precision){return this._dataProvider.formatValue(value-this._minimumBoundaries,precision);}
maximumBoundary(){return this._maximumBoundaries;}
minimumBoundary(){return this._minimumBoundaries;}
zeroTime(){return this._minimumBoundaries;}
boundarySpan(){return this._maximumBoundaries-this._minimumBoundaries;}};Profiler.CPUProfileFlameChart.OverviewPane=class extends UI.VBox{constructor(dataProvider){super();this.element.classList.add('cpu-profile-flame-chart-overview-pane');this._overviewContainer=this.element.createChild('div','cpu-profile-flame-chart-overview-container');this._overviewGrid=new PerfUI.OverviewGrid('cpu-profile-flame-chart');this._overviewGrid.element.classList.add('fill');this._overviewCanvas=this._overviewContainer.createChild('canvas','cpu-profile-flame-chart-overview-canvas');this._overviewContainer.appendChild(this._overviewGrid.element);this._overviewCalculator=new Profiler.CPUProfileFlameChart.OverviewCalculator(dataProvider);this._dataProvider=dataProvider;this._overviewGrid.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);}
windowChanged(windowStartTime,windowEndTime){this._selectRange(windowStartTime,windowEndTime);}
updateRangeSelection(startTime,endTime){}
updateSelectedGroup(flameChart,group){}
_selectRange(timeLeft,timeRight){const startTime=this._dataProvider.minimumBoundary();const totalTime=this._dataProvider.totalTime();this._overviewGrid.setWindow((timeLeft-startTime)/totalTime,(timeRight-startTime)/totalTime);}
_onWindowChanged(event){const startTime=this._dataProvider.minimumBoundary();const totalTime=this._dataProvider.totalTime();const data={windowTimeLeft:startTime+this._overviewGrid.windowLeft()*totalTime,windowTimeRight:startTime+this._overviewGrid.windowRight()*totalTime};this.dispatchEventToListeners(PerfUI.OverviewGrid.Events.WindowChanged,data);}
_timelineData(){return this._dataProvider.timelineData();}
onResize(){this._scheduleUpdate();}
_scheduleUpdate(){if(this._updateTimerId)
return;this._updateTimerId=this.element.window().requestAnimationFrame(this.update.bind(this));}
update(){this._updateTimerId=0;const timelineData=this._timelineData();if(!timelineData)
return;this._resetCanvas(this._overviewContainer.clientWidth,this._overviewContainer.clientHeight-PerfUI.FlameChart.HeaderHeight);this._overviewCalculator._updateBoundaries(this);this._overviewGrid.updateDividers(this._overviewCalculator);this._drawOverviewCanvas();}
_drawOverviewCanvas(){const canvasWidth=this._overviewCanvas.width;const canvasHeight=this._overviewCanvas.height;const drawData=this._calculateDrawData(canvasWidth);const context=this._overviewCanvas.getContext('2d');const ratio=window.devicePixelRatio;const offsetFromBottom=ratio;const lineWidth=1;const yScaleFactor=canvasHeight/(this._dataProvider.maxStackDepth()*1.1);context.lineWidth=lineWidth;context.translate(0.5,0.5);context.strokeStyle='rgba(20,0,0,0.4)';context.fillStyle='rgba(214,225,254,0.8)';context.moveTo(-lineWidth,canvasHeight+lineWidth);context.lineTo(-lineWidth,Math.round(canvasHeight-drawData[0]*yScaleFactor-offsetFromBottom));let value;for(let x=0;x<canvasWidth;++x){value=Math.round(canvasHeight-drawData[x]*yScaleFactor-offsetFromBottom);context.lineTo(x,value);}
context.lineTo(canvasWidth+lineWidth,value);context.lineTo(canvasWidth+lineWidth,canvasHeight+lineWidth);context.fill();context.stroke();context.closePath();}
_calculateDrawData(width){const dataProvider=this._dataProvider;const timelineData=this._timelineData();const entryStartTimes=timelineData.entryStartTimes;const entryTotalTimes=timelineData.entryTotalTimes;const entryLevels=timelineData.entryLevels;const length=entryStartTimes.length;const minimumBoundary=this._dataProvider.minimumBoundary();const drawData=new Uint8Array(width);const scaleFactor=width/dataProvider.totalTime();for(let entryIndex=0;entryIndex<length;++entryIndex){const start=Math.floor((entryStartTimes[entryIndex]-minimumBoundary)*scaleFactor);const finish=Math.floor((entryStartTimes[entryIndex]-minimumBoundary+entryTotalTimes[entryIndex])*scaleFactor);for(let x=start;x<=finish;++x)
drawData[x]=Math.max(drawData[x],entryLevels[entryIndex]+1);}
return drawData;}
_resetCanvas(width,height){const ratio=window.devicePixelRatio;this._overviewCanvas.width=width*ratio;this._overviewCanvas.height=height*ratio;this._overviewCanvas.style.width=width+'px';this._overviewCanvas.style.height=height+'px';}};;Profiler.CPUProfileView=class extends Profiler.ProfileView{constructor(profileHeader){super();this._profileHeader=profileHeader;this.initialize(new Profiler.CPUProfileView.NodeFormatter(this));const profile=profileHeader.profileModel();this.adjustedTotal=profile.profileHead.total;this.adjustedTotal-=profile.idleNode?profile.idleNode.total:0;this.setProfile(profile);}
wasShown(){super.wasShown();const lineLevelProfile=self.runtime.sharedInstance(PerfUI.LineLevelProfile.Performance);lineLevelProfile.reset();lineLevelProfile.appendCPUProfile(this._profileHeader.profileModel());}
columnHeader(columnId){switch(columnId){case'self':return Common.UIString('Self Time');case'total':return Common.UIString('Total Time');}
return'';}
createFlameChartDataProvider(){return new Profiler.CPUFlameChartDataProvider(this._profileHeader.profileModel(),this._profileHeader._cpuProfilerModel);}};Profiler.CPUProfileType=class extends Profiler.ProfileType{constructor(){super(Profiler.CPUProfileType.TypeId,Common.UIString('Record JavaScript CPU Profile'));this._recording=false;Profiler.CPUProfileType.instance=this;SDK.targetManager.addModelListener(SDK.CPUProfilerModel,SDK.CPUProfilerModel.Events.ConsoleProfileFinished,this._consoleProfileFinished,this);}
profileBeingRecorded(){return(super.profileBeingRecorded());}
typeName(){return'CPU';}
fileExtension(){return'.cpuprofile';}
get buttonTooltip(){return this._recording?Common.UIString('Stop CPU profiling'):Common.UIString('Start CPU profiling');}
buttonClicked(){if(this._recording){this._stopRecordingProfile();return false;}else{this._startRecordingProfile();return true;}}
get treeItemTitle(){return Common.UIString('CPU PROFILES');}
get description(){return Common.UIString('CPU profiles show where the execution time is spent in your page\'s JavaScript functions.');}
_consoleProfileFinished(event){const data=(event.data);const cpuProfile=(data.cpuProfile);const profile=new Profiler.CPUProfileHeader(data.cpuProfilerModel,this,data.title);profile.setProtocolProfile(cpuProfile);this.addProfile(profile);}
_startRecordingProfile(){const cpuProfilerModel=UI.context.flavor(SDK.CPUProfilerModel);if(this.profileBeingRecorded()||!cpuProfilerModel)
return;const profile=new Profiler.CPUProfileHeader(cpuProfilerModel,this);this.setProfileBeingRecorded(profile);SDK.targetManager.suspendAllTargets();this.addProfile(profile);profile.updateStatus(Common.UIString('Recording\u2026'));this._recording=true;cpuProfilerModel.startRecording();Host.userMetrics.actionTaken(Host.UserMetrics.Action.ProfilesCPUProfileTaken);}
async _stopRecordingProfile(){this._recording=false;if(!this.profileBeingRecorded()||!this.profileBeingRecorded()._cpuProfilerModel)
return;const profile=await this.profileBeingRecorded()._cpuProfilerModel.stopRecording();const recordedProfile=this.profileBeingRecorded();if(recordedProfile){console.assert(profile);recordedProfile.setProtocolProfile(profile);recordedProfile.updateStatus('');this.setProfileBeingRecorded(null);}
await SDK.targetManager.resumeAllTargets();this.dispatchEventToListeners(Profiler.ProfileType.Events.ProfileComplete,recordedProfile);}
createProfileLoadedFromFile(title){return new Profiler.CPUProfileHeader(null,this,title);}
profileBeingRecordedRemoved(){this._stopRecordingProfile();}};Profiler.CPUProfileType.TypeId='CPU';Profiler.CPUProfileHeader=class extends Profiler.WritableProfileHeader{constructor(cpuProfilerModel,type,title){super(cpuProfilerModel&&cpuProfilerModel.debuggerModel(),type,title);this._cpuProfilerModel=cpuProfilerModel;}
createView(){return new Profiler.CPUProfileView(this);}
protocolProfile(){return this._protocolProfile;}
profileModel(){return this._profileModel;}
setProfile(profile){const target=this._cpuProfilerModel&&this._cpuProfilerModel.target()||null;this._profileModel=new SDK.CPUProfileDataModel(profile,target);}};Profiler.CPUProfileView.NodeFormatter=class{constructor(profileView){this._profileView=profileView;}
formatValue(value){return Common.UIString('%.1f\xa0ms',value);}
formatPercent(value,node){return node.profileNode===this._profileView.profile().idleNode?'':Common.UIString('%.2f\xa0%%',value);}
linkifyNode(node){const cpuProfilerModel=this._profileView._profileHeader._cpuProfilerModel;return this._profileView.linkifier().maybeLinkifyConsoleCallFrame(cpuProfilerModel?cpuProfilerModel.target():null,node.profileNode.callFrame,'profile-node-file');}};Profiler.CPUFlameChartDataProvider=class extends Profiler.ProfileFlameChartDataProvider{constructor(cpuProfile,cpuProfilerModel){super();this._cpuProfile=cpuProfile;this._cpuProfilerModel=cpuProfilerModel;}
_calculateTimelineData(){const entries=[];const stack=[];let maxDepth=5;function onOpenFrame(){stack.push(entries.length);entries.push(null);}
function onCloseFrame(depth,node,startTime,totalTime,selfTime){const index=stack.pop();entries[index]=new Profiler.CPUFlameChartDataProvider.ChartEntry(depth,totalTime,startTime,selfTime,node);maxDepth=Math.max(maxDepth,depth);}
this._cpuProfile.forEachFrame(onOpenFrame,onCloseFrame);const entryNodes=new Array(entries.length);const entryLevels=new Uint16Array(entries.length);const entryTotalTimes=new Float32Array(entries.length);const entrySelfTimes=new Float32Array(entries.length);const entryStartTimes=new Float64Array(entries.length);for(let i=0;i<entries.length;++i){const entry=entries[i];entryNodes[i]=entry.node;entryLevels[i]=entry.depth;entryTotalTimes[i]=entry.duration;entryStartTimes[i]=entry.startTime;entrySelfTimes[i]=entry.selfTime;}
this._maxStackDepth=maxDepth+1;this._timelineData=new PerfUI.FlameChart.TimelineData(entryLevels,entryTotalTimes,entryStartTimes,null);this._entryNodes=entryNodes;this._entrySelfTimes=entrySelfTimes;return this._timelineData;}
prepareHighlightedEntryInfo(entryIndex){const timelineData=this._timelineData;const node=this._entryNodes[entryIndex];if(!node)
return null;const entryInfo=[];function pushEntryInfoRow(title,value){entryInfo.push({title:title,value:value});}
function millisecondsToString(ms){if(ms===0)
return'0';if(ms<1000)
return Common.UIString('%.1f\xa0ms',ms);return Number.secondsToString(ms/1000,true);}
const name=UI.beautifyFunctionName(node.functionName);pushEntryInfoRow(Common.UIString('Name'),name);const selfTime=millisecondsToString(this._entrySelfTimes[entryIndex]);const totalTime=millisecondsToString(timelineData.entryTotalTimes[entryIndex]);pushEntryInfoRow(Common.UIString('Self time'),selfTime);pushEntryInfoRow(Common.UIString('Total time'),totalTime);const linkifier=new Components.Linkifier();const link=linkifier.maybeLinkifyConsoleCallFrame(this._cpuProfilerModel&&this._cpuProfilerModel.target(),node.callFrame);if(link)
pushEntryInfoRow(Common.UIString('URL'),link.textContent);linkifier.dispose();pushEntryInfoRow(Common.UIString('Aggregated self time'),Number.secondsToString(node.self/1000,true));pushEntryInfoRow(Common.UIString('Aggregated total time'),Number.secondsToString(node.total/1000,true));if(node.deoptReason)
pushEntryInfoRow(Common.UIString('Not optimized'),node.deoptReason);return Profiler.ProfileView.buildPopoverTable(entryInfo);}};Profiler.CPUFlameChartDataProvider.ChartEntry=class{constructor(depth,duration,startTime,selfTime,node){this.depth=depth;this.duration=duration;this.startTime=startTime;this.selfTime=selfTime;this.node=node;}};;Profiler.HeapProfileView=class extends Profiler.ProfileView{constructor(profileHeader){super();this._profileHeader=profileHeader;this._profileType=profileHeader.profileType();const views=[Profiler.ProfileView.ViewTypes.Flame,Profiler.ProfileView.ViewTypes.Heavy,Profiler.ProfileView.ViewTypes.Tree];const isNativeProfile=this._profileType.id===Profiler.SamplingNativeHeapProfileType.TypeId||this._profileType.id===Profiler.SamplingNativeHeapSnapshotType.TypeId;if(isNativeProfile)
views.push(Profiler.ProfileView.ViewTypes.Text);this.initialize(new Profiler.HeapProfileView.NodeFormatter(this),views);const profile=new Profiler.SamplingHeapProfileModel(profileHeader._profile||profileHeader.protocolProfile());this.adjustedTotal=profile.total;this.setProfile(profile);this._selectedSizeText=new UI.ToolbarText();if(Runtime.experiments.isEnabled('samplingHeapProfilerTimeline')){this._timelineOverview=new Profiler.HeapTimelineOverview();this._timelineOverview.addEventListener(Profiler.HeapTimelineOverview.IdsRangeChanged,this._onIdsRangeChanged.bind(this));this._timelineOverview.show(this.element,this.element.firstChild);this._timelineOverview.start();this._profileType.addEventListener(Profiler.SamplingHeapProfileType.Events.StatsUpdate,this._onStatsUpdate,this);this._profileType.once(Profiler.ProfileType.Events.ProfileComplete).then(()=>{this._profileType.removeEventListener(Profiler.SamplingHeapProfileType.Events.StatsUpdate,this._onStatsUpdate,this);this._timelineOverview.stop();this._timelineOverview.updateGrid();});}}
syncToolbarItems(){return[...super.syncToolbarItems(),this._selectedSizeText];}
_onIdsRangeChanged(event){const minId=(event.data.minId);const maxId=(event.data.maxId);this._selectedSizeText.setText(ls`Selected size: ${Number.bytesToString(event.data.size)}`);this._setSelectionRange(minId,maxId);}
_setSelectionRange(minId,maxId){const profile=new Profiler.SamplingHeapProfileModel(this._profileHeader._profile||this._profileHeader.protocolProfile(),minId,maxId);this.adjustedTotal=profile.total;this.setProfile(profile);}
_onStatsUpdate(event){const profile=event.data;if(!this._totalTime){this._timestamps=[];this._sizes=[];this._max=[];this._ordinals=[];this._totalTime=30000;this._lastOrdinal=0;}
this._sizes.fill(0);this._sizes.push(0);this._timestamps.push(Date.now());this._ordinals.push(this._lastOrdinal+1);this._lastOrdinal=profile.samples.reduce((res,sample)=>Math.max(res,sample.ordinal),this._lastOrdinal);for(const sample of profile.samples){const bucket=this._ordinals.upperBound(sample.ordinal)-1;this._sizes[bucket]+=sample.size;}
this._max.push(this._sizes.peekLast());if(this._timestamps.peekLast()-this._timestamps[0]>this._totalTime)
this._totalTime*=2;const samples=({sizes:this._sizes,max:this._max,ids:this._ordinals,timestamps:this._timestamps,totalTime:this._totalTime});this._timelineOverview.setSamples(samples);}
columnHeader(columnId){switch(columnId){case'self':return Common.UIString('Self Size (bytes)');case'total':return Common.UIString('Total Size (bytes)');}
return'';}
createFlameChartDataProvider(){return new Profiler.HeapFlameChartDataProvider((this.profile()),this._profileHeader.heapProfilerModel());}
populateTextView(view){const guides='+!:|';let text=`Sampling memory profile.\n\nDate/Time: ${new Date()}\n`+`Report Version: 7\n`+`App Version: ${/Chrom\S*/.exec(navigator.appVersion)[0] || 'Unknown'}\n`+`Node Weight: 1 KiB\n`+`Total Size: ${Math.round(this.profile().root.total / 1024)} KiB\n`+`----\n\nCall graph:\n`;const sortedChildren=this.profile().root.children.sort((a,b)=>b.total-a.total);const modules=this.profile().modules.map(m=>Object.assign({address:BigInt(m.baseAddress),endAddress:BigInt(m.baseAddress)+BigInt(m.size)},m));modules.sort((m1,m2)=>m1.address>m2.address?1:m1.address<m2.address?-1:0);for(const child of sortedChildren)
printTree(' ',child!==sortedChildren.peekLast(),child);text+='\nBinary Images:\n';for(const module of modules){const fileName=/[^/\\]*$/.exec(module.name)[0];const version='1.0';const formattedUuid=module.uuid.includes('-')?module.uuid:module.uuid.replace(/(.{8})(.{4})(.{4})(.{4})(.{12}).*/,'$1-$2-$3-$4-$5');text+=`${('0x' + module.address.toString(16)).padStart(18)} - `;text+=`${('0x' + (module.endAddress - BigInt(1)).toString(16)).padStart(18)}`;text+=` ${fileName} (${version}) <${formattedUuid}> ${module.name}\n`;}
view.contentElement.createChild('pre','profile-text-view monospace').textContent=text;function printTree(padding,drawGuide,node){const addressText=/0x[0-9a-f]*|[0-9]*/.exec(node.functionName)[0]||'';let module;if(addressText){const address=BigInt(addressText);const pos=modules.upperBound(address,(address,module)=>address-module.address);if(pos>0&&address<modules[pos-1].endAddress)
module=modules[pos-1];}
const functionName=(addressText?node.functionName.substr(addressText.length+1):node.functionName)||'???';text+=`${padding}${Math.round(node.total / 1024)} ${functionName} `;if(module){const fileName=/[^/\\]*$/.exec(module.name);if(fileName)
text+=`(in ${fileName}) `;const offset=BigInt(addressText)-module.address;text+=`load address ${module.baseAddress} + 0x${offset.toString(16)} `;}
if(addressText)
text+=`[${addressText}]`;text+='\n';const guideChar=drawGuide?guides[padding.length/2%guides.length]:' ';const nextPadding=padding+guideChar+' ';const sortedChildren=node.children.sort((a,b)=>b.total-a.total);for(const child of sortedChildren)
printTree(nextPadding,child!==sortedChildren.peekLast(),child);}}};Profiler.SamplingHeapProfileTypeBase=class extends Profiler.ProfileType{constructor(typeId,description){super(typeId,description);this._recording=false;}
profileBeingRecorded(){return(super.profileBeingRecorded());}
typeName(){return'Heap';}
fileExtension(){return'.heapprofile';}
get buttonTooltip(){return this._recording?ls`Stop heap profiling`:ls`Start heap profiling`;}
buttonClicked(){if(this._recording)
this._stopRecordingProfile();else
this._startRecordingProfile();return this._recording;}
_startRecordingProfile(){const heapProfilerModel=UI.context.flavor(SDK.HeapProfilerModel);if(this.profileBeingRecorded()||!heapProfilerModel)
return;const profileHeader=new Profiler.SamplingHeapProfileHeader(heapProfilerModel,this);this.setProfileBeingRecorded(profileHeader);this.addProfile(profileHeader);profileHeader.updateStatus(ls`Recording\u2026`);const icon=UI.Icon.create('smallicon-warning');icon.title=ls`Heap profiler is recording`;UI.inspectorView.setPanelIcon('heap_profiler',icon);this._recording=true;this._startSampling();}
async _stopRecordingProfile(){this._recording=false;if(!this.profileBeingRecorded()||!this.profileBeingRecorded().heapProfilerModel())
return;this.profileBeingRecorded().updateStatus(ls`Stopping\u2026`);const profile=await this._stopSampling();const recordedProfile=this.profileBeingRecorded();if(recordedProfile){console.assert(profile);recordedProfile.setProtocolProfile(profile);recordedProfile.updateStatus('');this.setProfileBeingRecorded(null);}
UI.inspectorView.setPanelIcon('heap_profiler',null);this.dispatchEventToListeners(Profiler.ProfileType.Events.ProfileComplete,recordedProfile);}
createProfileLoadedFromFile(title){return new Profiler.SamplingHeapProfileHeader(null,this,title);}
profileBeingRecordedRemoved(){this._stopRecordingProfile();}
_startSampling(){throw'Not implemented';}
_stopSampling(){throw'Not implemented';}};Profiler.SamplingHeapProfileType=class extends Profiler.SamplingHeapProfileTypeBase{constructor(){super(Profiler.SamplingHeapProfileType.TypeId,ls`Allocation sampling`);Profiler.SamplingHeapProfileType.instance=this;this._updateTimer=null;this._updateIntervalMs=200;}
get treeItemTitle(){return ls`SAMPLING PROFILES`;}
get description(){return ls`Record memory allocations using sampling method.
This profile type has minimal performance overhead and can be used for long running operations.
It provides good approximation of allocations broken down by JavaScript execution stack.`;}
hasTemporaryView(){return Runtime.experiments.isEnabled('samplingHeapProfilerTimeline');}
_startSampling(){this.profileBeingRecorded().heapProfilerModel().startSampling();if(Runtime.experiments.isEnabled('samplingHeapProfilerTimeline'))
this._updateTimer=setTimeout(this._updateStats.bind(this),this._updateIntervalMs);}
_stopSampling(){clearTimeout(this._updateTimer);this._updateTimer=null;this.dispatchEventToListeners(Profiler.SamplingHeapProfileType.Events.RecordingStopped);return this.profileBeingRecorded().heapProfilerModel().stopSampling();}
async _updateStats(){const profile=await this.profileBeingRecorded().heapProfilerModel().getSamplingProfile();if(!this._updateTimer)
return;this.dispatchEventToListeners(Profiler.SamplingHeapProfileType.Events.StatsUpdate,profile);this._updateTimer=setTimeout(this._updateStats.bind(this),this._updateIntervalMs);}};Profiler.SamplingHeapProfileType.TypeId='SamplingHeap';Profiler.SamplingHeapProfileType.Events={RecordingStopped:Symbol('RecordingStopped'),StatsUpdate:Symbol('StatsUpdate')};Profiler.SamplingNativeHeapProfileType=class extends Profiler.SamplingHeapProfileTypeBase{constructor(){super(Profiler.SamplingNativeHeapProfileType.TypeId,ls`Native memory allocation sampling`);Profiler.SamplingNativeHeapProfileType.instance=this;}
get treeItemTitle(){return ls`NATIVE SAMPLING PROFILES`;}
get description(){return ls`Allocation profiles show sampled native memory allocations from the renderer process.`;}
_startSampling(){this.profileBeingRecorded().heapProfilerModel().startNativeSampling();}
_stopSampling(){return this.profileBeingRecorded().heapProfilerModel().stopNativeSampling();}};Profiler.SamplingNativeHeapProfileType.TypeId='SamplingNativeHeapRecording';Profiler.SamplingNativeHeapSnapshotType=class extends Profiler.SamplingHeapProfileTypeBase{constructor(processType){super(Profiler.SamplingNativeHeapSnapshotType.TypeId,ls`Native memory allocation snapshot (${processType})`);}
isInstantProfile(){return true;}
get treeItemTitle(){return ls`NATIVE SNAPSHOTS`;}
get description(){return ls`Native memory snapshots show sampled native allocations in the renderer process since start up.
Chrome has to be started with --memlog=all flag. Check flags at chrome://flags`;}
buttonClicked(){this._takeSnapshot();return false;}
async _takeSnapshot(){if(this.profileBeingRecorded())
return;const heapProfilerModel=UI.context.flavor(SDK.HeapProfilerModel);if(!heapProfilerModel)
return;const profile=new Profiler.SamplingHeapProfileHeader(heapProfilerModel,this,ls`Snapshot ${this.nextProfileUid()}`);this.setProfileBeingRecorded(profile);this.addProfile(profile);profile.updateStatus(ls`Snapshotting\u2026`);const protocolProfile=await this._takeNativeSnapshot((heapProfilerModel));const recordedProfile=this.profileBeingRecorded();if(recordedProfile){console.assert(protocolProfile);recordedProfile.setProtocolProfile(protocolProfile);recordedProfile.updateStatus('');this.setProfileBeingRecorded(null);}
this.dispatchEventToListeners(Profiler.ProfileType.Events.ProfileComplete,recordedProfile);}
_takeNativeSnapshot(heapProfilerModel){throw'Not implemented';}};Profiler.SamplingNativeHeapSnapshotType.TypeId='SamplingNativeHeapSnapshot';Profiler.SamplingNativeHeapSnapshotBrowserType=class extends Profiler.SamplingNativeHeapSnapshotType{constructor(){super(ls`Browser`);Profiler.SamplingNativeHeapSnapshotBrowserType.instance=this;}
async _takeNativeSnapshot(heapProfilerModel){return await heapProfilerModel.takeNativeBrowserSnapshot();}};Profiler.SamplingNativeHeapSnapshotRendererType=class extends Profiler.SamplingNativeHeapSnapshotType{constructor(){super(ls`Renderer`);Profiler.SamplingNativeHeapSnapshotRendererType.instance=this;}
async _takeNativeSnapshot(heapProfilerModel){return await heapProfilerModel.takeNativeSnapshot();}};Profiler.SamplingHeapProfileHeader=class extends Profiler.WritableProfileHeader{constructor(heapProfilerModel,type,title){super(heapProfilerModel&&heapProfilerModel.debuggerModel(),type,title||Common.UIString('Profile %d',type.nextProfileUid()));this._heapProfilerModel=heapProfilerModel;this._protocolProfile=({head:{callFrame:{},children:[]}});}
createView(){return new Profiler.HeapProfileView(this);}
protocolProfile(){return this._protocolProfile;}
heapProfilerModel(){return this._heapProfilerModel;}};Profiler.SamplingHeapProfileNode=class extends SDK.ProfileNode{constructor(node){const callFrame=node.callFrame||({functionName:node['functionName'],scriptId:node['scriptId'],url:node['url'],lineNumber:node['lineNumber']-1,columnNumber:node['columnNumber']-1});super(callFrame);this.self=node.selfSize;}};Profiler.SamplingHeapProfileModel=class extends SDK.ProfileTreeModel{constructor(profile,minOrdinal,maxOrdinal){super();this.modules=profile.modules||[];let nodeIdToSizeMap=null;if(minOrdinal||maxOrdinal){nodeIdToSizeMap=new Map();minOrdinal=minOrdinal||0;maxOrdinal=maxOrdinal||Infinity;for(const sample of profile.samples){if(sample.ordinal<minOrdinal||sample.ordinal>maxOrdinal)
continue;const size=nodeIdToSizeMap.get(sample.nodeId)||0;nodeIdToSizeMap.set(sample.nodeId,size+sample.size);}}
this.initialize(translateProfileTree(profile.head));function translateProfileTree(root){const resultRoot=new Profiler.SamplingHeapProfileNode(root);const sourceNodeStack=[root];const targetNodeStack=[resultRoot];while(sourceNodeStack.length){const sourceNode=sourceNodeStack.pop();const targetNode=targetNodeStack.pop();targetNode.children=sourceNode.children.map(child=>{const targetChild=new Profiler.SamplingHeapProfileNode(child);if(nodeIdToSizeMap)
targetChild.self=nodeIdToSizeMap.get(child.id)||0;return targetChild;});sourceNodeStack.pushAll(sourceNode.children);targetNodeStack.pushAll(targetNode.children);}
pruneEmptyBranches(resultRoot);return resultRoot;}
function pruneEmptyBranches(node){node.children=node.children.filter(pruneEmptyBranches);return!!(node.children.length||node.self);}}};Profiler.HeapProfileView.NodeFormatter=class{constructor(profileView){this._profileView=profileView;}
formatValue(value){return Number.withThousandsSeparator(value);}
formatPercent(value,node){return Common.UIString('%.2f\xa0%%',value);}
linkifyNode(node){const heapProfilerModel=this._profileView._profileHeader.heapProfilerModel();return this._profileView.linkifier().maybeLinkifyConsoleCallFrame(heapProfilerModel?heapProfilerModel.target():null,node.profileNode.callFrame,'profile-node-file');}};Profiler.HeapFlameChartDataProvider=class extends Profiler.ProfileFlameChartDataProvider{constructor(profile,heapProfilerModel){super();this._profile=profile;this._heapProfilerModel=heapProfilerModel;}
minimumBoundary(){return 0;}
totalTime(){return this._profile.root.total;}
formatValue(value,precision){return Common.UIString('%s\xa0KB',Number.withThousandsSeparator(value/1e3));}
_calculateTimelineData(){function nodesCount(node){return node.children.reduce((count,node)=>count+nodesCount(node),1);}
const count=nodesCount(this._profile.root);const entryNodes=new Array(count);const entryLevels=new Uint16Array(count);const entryTotalTimes=new Float32Array(count);const entryStartTimes=new Float64Array(count);let depth=0;let maxDepth=0;let position=0;let index=0;function addNode(node){const start=position;entryNodes[index]=node;entryLevels[index]=depth;entryTotalTimes[index]=node.total;entryStartTimes[index]=position;++index;++depth;node.children.forEach(addNode);--depth;maxDepth=Math.max(maxDepth,depth);position=start+node.total;}
addNode(this._profile.root);this._maxStackDepth=maxDepth+1;this._entryNodes=entryNodes;this._timelineData=new PerfUI.FlameChart.TimelineData(entryLevels,entryTotalTimes,entryStartTimes,null);return this._timelineData;}
prepareHighlightedEntryInfo(entryIndex){const node=this._entryNodes[entryIndex];if(!node)
return null;const entryInfo=[];function pushEntryInfoRow(title,value){entryInfo.push({title:title,value:value});}
pushEntryInfoRow(Common.UIString('Name'),UI.beautifyFunctionName(node.functionName));pushEntryInfoRow(Common.UIString('Self size'),Number.bytesToString(node.self));pushEntryInfoRow(Common.UIString('Total size'),Number.bytesToString(node.total));const linkifier=new Components.Linkifier();const link=linkifier.maybeLinkifyConsoleCallFrame(this._heapProfilerModel?this._heapProfilerModel.target():null,node.callFrame);if(link)
pushEntryInfoRow(Common.UIString('URL'),link.textContent);linkifier.dispose();return Profiler.ProfileView.buildPopoverTable(entryInfo);}};;Profiler.HeapProfilerPanel=class extends Profiler.ProfilesPanel{constructor(){const registry=Profiler.ProfileTypeRegistry.instance;const profileTypes=[registry.heapSnapshotProfileType,registry.trackingHeapSnapshotProfileType,registry.samplingHeapProfileType];if(Runtime.experiments.isEnabled('nativeHeapProfiler')){profileTypes.push(registry.samplingNativeHeapProfileType);profileTypes.push(registry.samplingNativeHeapSnapshotRendererType);profileTypes.push(registry.samplingNativeHeapSnapshotBrowserType);}
super('heap_profiler',profileTypes,'profiler.heap-toggle-recording');}
appendApplicableItems(event,contextMenu,target){if(!(target instanceof SDK.RemoteObject))
return;if(!this.isShowing())
return;const object=(target);if(!object.objectId)
return;const objectId=(object.objectId);const heapProfiles=Profiler.ProfileTypeRegistry.instance.heapSnapshotProfileType.getProfiles();if(!heapProfiles.length)
return;const heapProfilerModel=object.runtimeModel().heapProfilerModel();if(!heapProfilerModel)
return;function revealInView(viewName){heapProfilerModel.snapshotObjectIdForObjectId(objectId).then(result=>{if(this.isShowing()&&result)
this.showObject(result,viewName);});}
contextMenu.revealSection().appendItem(Common.UIString('Reveal in Summary view'),revealInView.bind(this,'Summary'));}
handleAction(context,actionId){const panel=UI.context.flavor(Profiler.HeapProfilerPanel);console.assert(panel&&panel instanceof Profiler.HeapProfilerPanel);panel.toggleRecord();return true;}
wasShown(){UI.context.setFlavor(Profiler.HeapProfilerPanel,this);}
willHide(){UI.context.setFlavor(Profiler.HeapProfilerPanel,null);}
showObject(snapshotObjectId,perspectiveName){const registry=Profiler.ProfileTypeRegistry.instance;const heapProfiles=registry.heapSnapshotProfileType.getProfiles();for(let i=0;i<heapProfiles.length;i++){const profile=heapProfiles[i];if(profile.maxJSObjectId>=snapshotObjectId){this.showProfile(profile);const view=this.viewForProfile(profile);view.selectLiveObject(perspectiveName,snapshotObjectId);break;}}}};;Profiler.HeapSnapshotWorkerProxy=class extends Common.Object{constructor(eventHandler){super();this._eventHandler=eventHandler;this._nextObjectId=1;this._nextCallId=1;this._callbacks=new Map();this._previousCallbacks=new Set();this._worker=new Common.Worker('heap_snapshot_worker');this._worker.onmessage=this._messageReceived.bind(this);}
createLoader(profileUid,snapshotReceivedCallback){const objectId=this._nextObjectId++;const proxy=new Profiler.HeapSnapshotLoaderProxy(this,objectId,profileUid,snapshotReceivedCallback);this._postMessage({callId:this._nextCallId++,disposition:'create',objectId:objectId,methodName:'HeapSnapshotWorker.HeapSnapshotLoader'});return proxy;}
dispose(){this._worker.terminate();if(this._interval)
clearInterval(this._interval);}
disposeObject(objectId){this._postMessage({callId:this._nextCallId++,disposition:'dispose',objectId:objectId});}
evaluateForTest(script,callback){const callId=this._nextCallId++;this._callbacks.set(callId,callback);this._postMessage({callId:callId,disposition:'evaluateForTest',source:script});}
callFactoryMethod(callback,objectId,methodName,proxyConstructor){const callId=this._nextCallId++;const methodArguments=Array.prototype.slice.call(arguments,4);const newObjectId=this._nextObjectId++;function wrapCallback(remoteResult){callback(remoteResult?new proxyConstructor(this,newObjectId):null);}
if(callback){this._callbacks.set(callId,wrapCallback.bind(this));this._postMessage({callId:callId,disposition:'factory',objectId:objectId,methodName:methodName,methodArguments:methodArguments,newObjectId:newObjectId});return null;}else{this._postMessage({callId:callId,disposition:'factory',objectId:objectId,methodName:methodName,methodArguments:methodArguments,newObjectId:newObjectId});return new proxyConstructor(this,newObjectId);}}
callMethod(callback,objectId,methodName){const callId=this._nextCallId++;const methodArguments=Array.prototype.slice.call(arguments,3);if(callback)
this._callbacks.set(callId,callback);this._postMessage({callId:callId,disposition:'method',objectId:objectId,methodName:methodName,methodArguments:methodArguments});}
startCheckingForLongRunningCalls(){if(this._interval)
return;this._checkLongRunningCalls();this._interval=setInterval(this._checkLongRunningCalls.bind(this),300);}
_checkLongRunningCalls(){for(const callId of this._previousCallbacks){if(!this._callbacks.has(callId))
this._previousCallbacks.delete(callId);}
const hasLongRunningCalls=!!this._previousCallbacks.size;this.dispatchEventToListeners(Profiler.HeapSnapshotWorkerProxy.Events.Wait,hasLongRunningCalls);for(const callId of this._callbacks.keysArray())
this._previousCallbacks.add(callId);}
_messageReceived(event){const data=event.data;if(data.eventName){if(this._eventHandler)
this._eventHandler(data.eventName,data.data);return;}
if(data.error){if(data.errorMethodName){Common.console.error(Common.UIString('An error occurred when a call to method \'%s\' was requested',data.errorMethodName));}
Common.console.error(data['errorCallStack']);this._callbacks.delete(data.callId);return;}
if(!this._callbacks.has(data.callId))
return;const callback=this._callbacks.get(data.callId);this._callbacks.delete(data.callId);callback(data.result);}
_postMessage(message){this._worker.postMessage(message);}};Profiler.HeapSnapshotWorkerProxy.Events={Wait:Symbol('Wait')};Profiler.HeapSnapshotProxyObject=class{constructor(worker,objectId){this._worker=worker;this._objectId=objectId;}
_callWorker(workerMethodName,args){args.splice(1,0,this._objectId);return this._worker[workerMethodName].apply(this._worker,args);}
dispose(){this._worker.disposeObject(this._objectId);}
disposeWorker(){this._worker.dispose();}
callFactoryMethod(callback,methodName,proxyConstructor,var_args){return this._callWorker('callFactoryMethod',Array.prototype.slice.call(arguments,0));}
_callMethodPromise(methodName,var_args){const args=Array.prototype.slice.call(arguments);return new Promise(resolve=>this._callWorker('callMethod',[resolve,...args]));}};Profiler.HeapSnapshotLoaderProxy=class extends Profiler.HeapSnapshotProxyObject{constructor(worker,objectId,profileUid,snapshotReceivedCallback){super(worker,objectId);this._profileUid=profileUid;this._snapshotReceivedCallback=snapshotReceivedCallback;}
write(chunk){return this._callMethodPromise('write',chunk);}
async close(){await this._callMethodPromise('close');const snapshotProxy=await new Promise(resolve=>this.callFactoryMethod(resolve,'buildSnapshot',Profiler.HeapSnapshotProxy));this.dispose();snapshotProxy.setProfileUid(this._profileUid);await snapshotProxy.updateStaticData();this._snapshotReceivedCallback(snapshotProxy);}};Profiler.HeapSnapshotProxy=class extends Profiler.HeapSnapshotProxyObject{constructor(worker,objectId){super(worker,objectId);this._staticData=null;}
search(searchConfig,filter){return this._callMethodPromise('search',searchConfig,filter);}
aggregatesWithFilter(filter){return this._callMethodPromise('aggregatesWithFilter',filter);}
aggregatesForDiff(){return this._callMethodPromise('aggregatesForDiff');}
calculateSnapshotDiff(baseSnapshotId,baseSnapshotAggregates){return this._callMethodPromise('calculateSnapshotDiff',baseSnapshotId,baseSnapshotAggregates);}
nodeClassName(snapshotObjectId){return this._callMethodPromise('nodeClassName',snapshotObjectId);}
createEdgesProvider(nodeIndex){return this.callFactoryMethod(null,'createEdgesProvider',Profiler.HeapSnapshotProviderProxy,nodeIndex);}
createRetainingEdgesProvider(nodeIndex){return this.callFactoryMethod(null,'createRetainingEdgesProvider',Profiler.HeapSnapshotProviderProxy,nodeIndex);}
createAddedNodesProvider(baseSnapshotId,className){return this.callFactoryMethod(null,'createAddedNodesProvider',Profiler.HeapSnapshotProviderProxy,baseSnapshotId,className);}
createDeletedNodesProvider(nodeIndexes){return this.callFactoryMethod(null,'createDeletedNodesProvider',Profiler.HeapSnapshotProviderProxy,nodeIndexes);}
createNodesProvider(filter){return this.callFactoryMethod(null,'createNodesProvider',Profiler.HeapSnapshotProviderProxy,filter);}
createNodesProviderForClass(className,nodeFilter){return this.callFactoryMethod(null,'createNodesProviderForClass',Profiler.HeapSnapshotProviderProxy,className,nodeFilter);}
allocationTracesTops(){return this._callMethodPromise('allocationTracesTops');}
allocationNodeCallers(nodeId){return this._callMethodPromise('allocationNodeCallers',nodeId);}
allocationStack(nodeIndex){return this._callMethodPromise('allocationStack',nodeIndex);}
dispose(){throw new Error('Should never be called');}
get nodeCount(){return this._staticData.nodeCount;}
get rootNodeIndex(){return this._staticData.rootNodeIndex;}
async updateStaticData(){this._staticData=await this._callMethodPromise('updateStaticData');}
getStatistics(){return this._callMethodPromise('getStatistics');}
getLocation(nodeIndex){return this._callMethodPromise('getLocation',nodeIndex);}
getSamples(){return this._callMethodPromise('getSamples');}
get totalSize(){return this._staticData.totalSize;}
get uid(){return this._profileUid;}
setProfileUid(profileUid){this._profileUid=profileUid;}
maxJSObjectId(){return this._staticData.maxJSObjectId;}};Profiler.HeapSnapshotProviderProxy=class extends Profiler.HeapSnapshotProxyObject{constructor(worker,objectId){super(worker,objectId);}
nodePosition(snapshotObjectId){return this._callMethodPromise('nodePosition',snapshotObjectId);}
isEmpty(){return this._callMethodPromise('isEmpty');}
serializeItemsRange(startPosition,endPosition){return this._callMethodPromise('serializeItemsRange',startPosition,endPosition);}
sortAndRewind(comparator){return this._callMethodPromise('sortAndRewind',comparator);}};;Profiler.HeapSnapshotSortableDataGrid=class extends DataGrid.DataGrid{constructor(dataDisplayDelegate,columns){super(columns);this._dataDisplayDelegate=dataDisplayDelegate;const tooltips=[['distance',ls`Distance from window object`],['shallowSize',ls`Size of the object itself in bytes`],['retainedSize',ls`Size of the object plus the graph it retains in bytes`]];for(const info of tooltips){const headerCell=this.headerTableHeader(info[0]);if(headerCell)
headerCell.setAttribute('title',info[1]);}
this._recursiveSortingDepth=0;this._highlightedNode=null;this._populatedAndSorted=false;this._nameFilter=null;this._nodeFilter=new HeapSnapshotModel.NodeFilter();this.addEventListener(Profiler.HeapSnapshotSortableDataGrid.Events.SortingComplete,this._sortingComplete,this);this.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this.sortingChanged,this);}
dataDisplayDelegate(){return this._dataDisplayDelegate;}
nodeFilter(){return this._nodeFilter;}
setNameFilter(nameFilter){this._nameFilter=nameFilter;}
defaultPopulateCount(){return 100;}
_disposeAllNodes(){const children=this.topLevelNodes();for(let i=0,l=children.length;i<l;++i)
children[i].dispose();}
wasShown(){if(this._nameFilter){this._nameFilter.addEventListener(UI.ToolbarInput.Event.TextChanged,this._onNameFilterChanged,this);this.updateVisibleNodes(true);}
if(this._populatedAndSorted)
this.dispatchEventToListeners(Profiler.HeapSnapshotSortableDataGrid.Events.ContentShown,this);}
_sortingComplete(){this.removeEventListener(Profiler.HeapSnapshotSortableDataGrid.Events.SortingComplete,this._sortingComplete,this);this._populatedAndSorted=true;this.dispatchEventToListeners(Profiler.HeapSnapshotSortableDataGrid.Events.ContentShown,this);}
willHide(){if(this._nameFilter)
this._nameFilter.removeEventListener(UI.ToolbarInput.Event.TextChanged,this._onNameFilterChanged,this);this._clearCurrentHighlight();}
populateContextMenu(contextMenu,event){const td=event.target.enclosingNodeOrSelfWithNodeName('td');if(!td)
return;const node=td.heapSnapshotNode;contextMenu.revealSection().appendItem(ls`Reveal in Summary view`,()=>{this._dataDisplayDelegate.showObject(node.snapshotNodeId,ls`Summary`);});}
resetSortingCache(){delete this._lastSortColumnId;delete this._lastSortAscending;}
topLevelNodes(){return this.rootNode().children;}
revealObjectByHeapSnapshotId(heapSnapshotObjectId){return Promise.resolve((null));}
highlightNode(node){this._clearCurrentHighlight();this._highlightedNode=node;UI.runCSSAnimationOnce(this._highlightedNode.element(),'highlighted-row');}
_clearCurrentHighlight(){if(!this._highlightedNode)
return;this._highlightedNode.element().classList.remove('highlighted-row');this._highlightedNode=null;}
resetNameFilter(){this._nameFilter.setValue('');}
_onNameFilterChanged(){this.updateVisibleNodes(true);}
sortingChanged(){const sortAscending=this.isSortOrderAscending();const sortColumnId=this.sortColumnId();if(this._lastSortColumnId===sortColumnId&&this._lastSortAscending===sortAscending)
return;this._lastSortColumnId=sortColumnId;this._lastSortAscending=sortAscending;const sortFields=this._sortFields(sortColumnId,sortAscending);function SortByTwoFields(nodeA,nodeB){let field1=nodeA[sortFields[0]];let field2=nodeB[sortFields[0]];let result=field1<field2?-1:(field1>field2?1:0);if(!sortFields[1])
result=-result;if(result!==0)
return result;field1=nodeA[sortFields[2]];field2=nodeB[sortFields[2]];result=field1<field2?-1:(field1>field2?1:0);if(!sortFields[3])
result=-result;return result;}
this._performSorting(SortByTwoFields);}
_performSorting(sortFunction){this.recursiveSortingEnter();const children=this.allChildren(this.rootNode());this.rootNode().removeChildren();children.sort(sortFunction);for(let i=0,l=children.length;i<l;++i){const child=children[i];this.appendChildAfterSorting(child);if(child.expanded)
child.sort();}
this.recursiveSortingLeave();}
appendChildAfterSorting(child){const revealed=child.revealed;this.rootNode().appendChild(child);child.revealed=revealed;}
recursiveSortingEnter(){++this._recursiveSortingDepth;}
recursiveSortingLeave(){if(!this._recursiveSortingDepth)
return;if(--this._recursiveSortingDepth)
return;this.updateVisibleNodes(true);this.dispatchEventToListeners(Profiler.HeapSnapshotSortableDataGrid.Events.SortingComplete);}
updateVisibleNodes(force){}
allChildren(parent){return parent.children;}
insertChild(parent,node,index){parent.insertChild(node,index);}
removeChildByIndex(parent,index){parent.removeChild(parent.children[index]);}
removeAllChildren(parent){parent.removeChildren();}};Profiler.HeapSnapshotSortableDataGrid.Events={ContentShown:Symbol('ContentShown'),SortingComplete:Symbol('SortingComplete')};Profiler.HeapSnapshotViewportDataGrid=class extends Profiler.HeapSnapshotSortableDataGrid{constructor(dataDisplayDelegate,columns){super(dataDisplayDelegate,columns);this.scrollContainer.addEventListener('scroll',this._onScroll.bind(this),true);this._topPaddingHeight=0;this._bottomPaddingHeight=0;}
topLevelNodes(){return this.allChildren(this.rootNode());}
appendChildAfterSorting(child){}
updateVisibleNodes(force){const guardZoneHeight=40;const scrollHeight=this.scrollContainer.scrollHeight;let scrollTop=this.scrollContainer.scrollTop;let scrollBottom=scrollHeight-scrollTop-this.scrollContainer.offsetHeight;scrollTop=Math.max(0,scrollTop-guardZoneHeight);scrollBottom=Math.max(0,scrollBottom-guardZoneHeight);let viewPortHeight=scrollHeight-scrollTop-scrollBottom;if(!force&&scrollTop>=this._topPaddingHeight&&scrollBottom>=this._bottomPaddingHeight)
return;const hysteresisHeight=500;scrollTop-=hysteresisHeight;viewPortHeight+=2*hysteresisHeight;const selectedNode=this.selectedNode;this.rootNode().removeChildren();this._topPaddingHeight=0;this._bottomPaddingHeight=0;this._addVisibleNodes(this.rootNode(),scrollTop,scrollTop+viewPortHeight);this.setVerticalPadding(this._topPaddingHeight,this._bottomPaddingHeight);if(selectedNode){if(selectedNode.parent)
selectedNode.select(true);else
this.selectedNode=selectedNode;}}
_addVisibleNodes(parentNode,topBound,bottomBound){if(!parentNode.expanded)
return 0;const children=this.allChildren(parentNode);let topPadding=0;const nameFilterValue=this._nameFilter?this._nameFilter.value().toLowerCase():'';let i=0;for(;i<children.length;++i){const child=children[i];if(nameFilterValue&&child.filteredOut&&child.filteredOut(nameFilterValue))
continue;const newTop=topPadding+this._nodeHeight(child);if(newTop>topBound)
break;topPadding=newTop;}
let position=topPadding;for(;i<children.length&&position<bottomBound;++i){const child=children[i];if(nameFilterValue&&child.filteredOut&&child.filteredOut(nameFilterValue))
continue;const hasChildren=child.hasChildren();child.removeChildren();child.setHasChildren(hasChildren);parentNode.appendChild(child);position+=child.nodeSelfHeight();position+=this._addVisibleNodes(child,topBound-position,bottomBound-position);}
let bottomPadding=0;for(;i<children.length;++i){const child=children[i];if(nameFilterValue&&child.filteredOut&&child.filteredOut(nameFilterValue))
continue;bottomPadding+=this._nodeHeight(child);}
this._topPaddingHeight+=topPadding;this._bottomPaddingHeight+=bottomPadding;return position+bottomPadding;}
_nodeHeight(node){let result=node.nodeSelfHeight();if(!node.expanded)
return result;const children=this.allChildren(node);for(let i=0;i<children.length;i++)
result+=this._nodeHeight(children[i]);return result;}
revealTreeNode(pathToReveal){const height=this._calculateOffset(pathToReveal);const node=(pathToReveal.peekLast());const scrollTop=this.scrollContainer.scrollTop;const scrollBottom=scrollTop+this.scrollContainer.offsetHeight;if(height>=scrollTop&&height<scrollBottom)
return Promise.resolve(node);const scrollGap=40;this.scrollContainer.scrollTop=Math.max(0,height-scrollGap);return new Promise(resolve=>{console.assert(!this._scrollToResolveCallback);this._scrollToResolveCallback=resolve.bind(null,node);this.scrollContainer.window().requestAnimationFrame(()=>{if(!this._scrollToResolveCallback)
return;this._scrollToResolveCallback();this._scrollToResolveCallback=null;});});}
_calculateOffset(pathToReveal){let parentNode=this.rootNode();let height=0;for(let i=0;i<pathToReveal.length;++i){const node=pathToReveal[i];const children=this.allChildren(parentNode);for(let j=0;j<children.length;++j){const child=children[j];if(node===child){height+=node.nodeSelfHeight();break;}
height+=this._nodeHeight(child);}
parentNode=node;}
return height-pathToReveal.peekLast().nodeSelfHeight();}
allChildren(parent){return parent._allChildren||(parent._allChildren=[]);}
appendNode(parent,node){this.allChildren(parent).push(node);}
insertChild(parent,node,index){this.allChildren(parent).splice(index,0,(node));}
removeChildByIndex(parent,index){this.allChildren(parent).splice(index,1);}
removeAllChildren(parent){parent._allChildren=[];}
removeTopLevelNodes(){this._disposeAllNodes();this.rootNode().removeChildren();this.rootNode()._allChildren=[];}
_isScrolledIntoView(element){const viewportTop=this.scrollContainer.scrollTop;const viewportBottom=viewportTop+this.scrollContainer.clientHeight;const elemTop=element.offsetTop;const elemBottom=elemTop+element.offsetHeight;return elemBottom<=viewportBottom&&elemTop>=viewportTop;}
onResize(){super.onResize();this.updateVisibleNodes(false);}
_onScroll(event){this.updateVisibleNodes(false);if(this._scrollToResolveCallback){this._scrollToResolveCallback();this._scrollToResolveCallback=null;}}};Profiler.HeapSnapshotContainmentDataGrid=class extends Profiler.HeapSnapshotSortableDataGrid{constructor(dataDisplayDelegate,columns){columns=columns||(([{id:'object',title:ls`Object`,disclosure:true,sortable:true},{id:'distance',title:ls`Distance`,width:'70px',sortable:true,fixedWidth:true},{id:'shallowSize',title:ls`Shallow Size`,width:'110px',sortable:true,fixedWidth:true},{id:'retainedSize',title:ls`Retained Size`,width:'110px',sortable:true,fixedWidth:true,sort:DataGrid.DataGrid.Order.Descending}]));super(dataDisplayDelegate,columns);}
setDataSource(snapshot,nodeIndex){this.snapshot=snapshot;const node={nodeIndex:nodeIndex||snapshot.rootNodeIndex};const fakeEdge={node:node};this.setRootNode(this._createRootNode(snapshot,fakeEdge));this.rootNode().sort();}
_createRootNode(snapshot,fakeEdge){return new Profiler.HeapSnapshotObjectNode(this,snapshot,fakeEdge,null);}
sortingChanged(){const rootNode=this.rootNode();if(rootNode.hasChildren())
rootNode.sort();}};Profiler.HeapSnapshotRetainmentDataGrid=class extends Profiler.HeapSnapshotContainmentDataGrid{constructor(dataDisplayDelegate){const columns=([{id:'object',title:ls`Object`,disclosure:true,sortable:true},{id:'distance',title:ls`Distance`,width:'70px',sortable:true,fixedWidth:true,sort:DataGrid.DataGrid.Order.Ascending},{id:'shallowSize',title:ls`Shallow Size`,width:'110px',sortable:true,fixedWidth:true},{id:'retainedSize',title:ls`Retained Size`,width:'110px',sortable:true,fixedWidth:true}]);super(dataDisplayDelegate,columns);}
_createRootNode(snapshot,fakeEdge){return new Profiler.HeapSnapshotRetainingObjectNode(this,snapshot,fakeEdge,null);}
_sortFields(sortColumn,sortAscending){return{object:['_name',sortAscending,'_count',false],count:['_count',sortAscending,'_name',true],shallowSize:['_shallowSize',sortAscending,'_name',true],retainedSize:['_retainedSize',sortAscending,'_name',true],distance:['_distance',sortAscending,'_name',true]}[sortColumn];}
reset(){this.rootNode().removeChildren();this.resetSortingCache();}
setDataSource(snapshot,nodeIndex){super.setDataSource(snapshot,nodeIndex);this.rootNode().expand();}};Profiler.HeapSnapshotRetainmentDataGrid.Events={ExpandRetainersComplete:Symbol('ExpandRetainersComplete')};Profiler.HeapSnapshotConstructorsDataGrid=class extends Profiler.HeapSnapshotViewportDataGrid{constructor(dataDisplayDelegate){const columns=([{id:'object',title:ls`Constructor`,disclosure:true,sortable:true},{id:'distance',title:ls`Distance`,width:'70px',sortable:true,fixedWidth:true},{id:'shallowSize',title:ls`Shallow Size`,width:'110px',sortable:true,fixedWidth:true},{id:'retainedSize',title:ls`Retained Size`,width:'110px',sort:DataGrid.DataGrid.Order.Descending,sortable:true,fixedWidth:true}]);super(dataDisplayDelegate,columns);this._profileIndex=-1;this._objectIdToSelect=null;}
_sortFields(sortColumn,sortAscending){return{object:['_name',sortAscending,'_retainedSize',false],distance:['_distance',sortAscending,'_retainedSize',false],shallowSize:['_shallowSize',sortAscending,'_name',true],retainedSize:['_retainedSize',sortAscending,'_name',true]}[sortColumn];}
async revealObjectByHeapSnapshotId(id){if(!this.snapshot){this._objectIdToSelect=id;return null;}
const className=await this.snapshot.nodeClassName(parseInt(id,10));if(!className)
return null;const parent=this.topLevelNodes().find(classNode=>classNode._name===className);if(!parent)
return null;const nodes=await parent.populateNodeBySnapshotObjectId(parseInt(id,10));return nodes.length?this.revealTreeNode(nodes):null;}
clear(){this._nextRequestedFilter=null;this._lastFilter=null;this.removeTopLevelNodes();}
setDataSource(snapshot){this.snapshot=snapshot;if(this._profileIndex===-1)
this._populateChildren();if(this._objectIdToSelect){this.revealObjectByHeapSnapshotId(this._objectIdToSelect);this._objectIdToSelect=null;}}
setSelectionRange(minNodeId,maxNodeId){this._nodeFilter=new HeapSnapshotModel.NodeFilter(minNodeId,maxNodeId);this._populateChildren(this._nodeFilter);}
setAllocationNodeId(allocationNodeId){this._nodeFilter=new HeapSnapshotModel.NodeFilter();this._nodeFilter.allocationNodeId=allocationNodeId;this._populateChildren(this._nodeFilter);}
_aggregatesReceived(nodeFilter,aggregates){this._filterInProgress=null;if(this._nextRequestedFilter){this.snapshot.aggregatesWithFilter(this._nextRequestedFilter).then(this._aggregatesReceived.bind(this,this._nextRequestedFilter));this._filterInProgress=this._nextRequestedFilter;this._nextRequestedFilter=null;}
this.removeTopLevelNodes();this.resetSortingCache();for(const constructor in aggregates){this.appendNode(this.rootNode(),new Profiler.HeapSnapshotConstructorNode(this,constructor,aggregates[constructor],nodeFilter));}
this.sortingChanged();this._lastFilter=nodeFilter;}
async _populateChildren(maybeNodeFilter){const nodeFilter=maybeNodeFilter||new HeapSnapshotModel.NodeFilter();if(this._filterInProgress){this._nextRequestedFilter=this._filterInProgress.equals(nodeFilter)?null:nodeFilter;return;}
if(this._lastFilter&&this._lastFilter.equals(nodeFilter))
return;this._filterInProgress=nodeFilter;const aggregates=await this.snapshot.aggregatesWithFilter(nodeFilter);this._aggregatesReceived(nodeFilter,aggregates);}
filterSelectIndexChanged(profiles,profileIndex){this._profileIndex=profileIndex;this._nodeFilter=undefined;if(profileIndex!==-1){const minNodeId=profileIndex>0?profiles[profileIndex-1].maxJSObjectId:0;const maxNodeId=profiles[profileIndex].maxJSObjectId;this._nodeFilter=new HeapSnapshotModel.NodeFilter(minNodeId,maxNodeId);}
this._populateChildren(this._nodeFilter);}};Profiler.HeapSnapshotDiffDataGrid=class extends Profiler.HeapSnapshotViewportDataGrid{constructor(dataDisplayDelegate){const columns=([{id:'object',title:ls`Constructor`,disclosure:true,sortable:true},{id:'addedCount',title:ls`# New`,width:'75px',sortable:true,fixedWidth:true},{id:'removedCount',title:ls`# Deleted`,width:'75px',sortable:true,fixedWidth:true},{id:'countDelta',title:ls`# Delta`,width:'65px',sortable:true,fixedWidth:true},{id:'addedSize',title:ls`Alloc. Size`,width:'75px',sortable:true,fixedWidth:true,sort:DataGrid.DataGrid.Order.Descending},{id:'removedSize',title:ls`Freed Size`,width:'75px',sortable:true,fixedWidth:true},{id:'sizeDelta',title:ls`Size Delta`,width:'75px',sortable:true,fixedWidth:true}]);super(dataDisplayDelegate,columns);}
defaultPopulateCount(){return 50;}
_sortFields(sortColumn,sortAscending){return{object:['_name',sortAscending,'_count',false],addedCount:['_addedCount',sortAscending,'_name',true],removedCount:['_removedCount',sortAscending,'_name',true],countDelta:['_countDelta',sortAscending,'_name',true],addedSize:['_addedSize',sortAscending,'_name',true],removedSize:['_removedSize',sortAscending,'_name',true],sizeDelta:['_sizeDelta',sortAscending,'_name',true]}[sortColumn];}
setDataSource(snapshot){this.snapshot=snapshot;}
setBaseDataSource(baseSnapshot){this.baseSnapshot=baseSnapshot;this.removeTopLevelNodes();this.resetSortingCache();if(this.baseSnapshot===this.snapshot){this.dispatchEventToListeners(Profiler.HeapSnapshotSortableDataGrid.Events.SortingComplete);return;}
this._populateChildren();}
async _populateChildren(){const aggregatesForDiff=await this.baseSnapshot.aggregatesForDiff();const diffByClassName=await this.snapshot.calculateSnapshotDiff(this.baseSnapshot.uid,aggregatesForDiff);for(const className in diffByClassName){const diff=diffByClassName[className];this.appendNode(this.rootNode(),new Profiler.HeapSnapshotDiffNode(this,className,diff));}
this.sortingChanged();}};Profiler.AllocationDataGrid=class extends Profiler.HeapSnapshotViewportDataGrid{constructor(heapProfilerModel,dataDisplayDelegate){const columns=([{id:'liveCount',title:ls`Live Count`,width:'75px',sortable:true,fixedWidth:true},{id:'count',title:ls`Count`,width:'65px',sortable:true,fixedWidth:true},{id:'liveSize',title:ls`Live Size`,width:'75px',sortable:true,fixedWidth:true},{id:'size',title:ls`Size`,width:'75px',sortable:true,fixedWidth:true,sort:DataGrid.DataGrid.Order.Descending},{id:'name',title:ls`Function`,disclosure:true,sortable:true},]);super(dataDisplayDelegate,columns);this._heapProfilerModel=heapProfilerModel;this._linkifier=new Components.Linkifier();}
heapProfilerModel(){return this._heapProfilerModel;}
dispose(){this._linkifier.reset();}
async setDataSource(snapshot){this.snapshot=snapshot;this._topNodes=await this.snapshot.allocationTracesTops();this._populateChildren();}
_populateChildren(){this.removeTopLevelNodes();const root=this.rootNode();const tops=this._topNodes;for(const top of tops)
this.appendNode(root,new Profiler.AllocationGridNode(this,top));this.updateVisibleNodes(true);}
sortingChanged(){this._topNodes.sort(this._createComparator());this.rootNode().removeChildren();this._populateChildren();}
_createComparator(){const fieldName=this.sortColumnId();const compareResult=(this.sortOrder()===DataGrid.DataGrid.Order.Ascending)?+1:-1;function compare(a,b){if(a[fieldName]>b[fieldName])
return compareResult;if(a[fieldName]<b[fieldName])
return-compareResult;return 0;}
return compare;}};;Profiler.HeapSnapshotGridNode=class extends DataGrid.DataGridNode{constructor(tree,hasChildren){super(null,hasChildren);this._dataGrid=tree;this._instanceCount=0;this._savedChildren=null;this._retrievedChildrenRanges=[];this._providerObject=null;this._reachableFromWindow=false;}
static createComparator(fieldNames){return({fieldName1:fieldNames[0],ascending1:fieldNames[1],fieldName2:fieldNames[2],ascending2:fieldNames[3]});}
heapSnapshotDataGrid(){return this._dataGrid;}
createProvider(){throw new Error('Not implemented.');}
retainersDataSource(){return null;}
_provider(){if(!this._providerObject)
this._providerObject=this.createProvider();return this._providerObject;}
createCell(columnId){const cell=super.createCell(columnId);if(this._searchMatched)
cell.classList.add('highlight');return cell;}
collapse(){super.collapse();this._dataGrid.updateVisibleNodes(true);}
expand(){super.expand();this._dataGrid.updateVisibleNodes(true);}
dispose(){if(this._providerObject)
this._providerObject.dispose();for(let node=this.children[0];node;node=node.traverseNextNode(true,this,true)){if(node.dispose)
node.dispose();}}
queryObjectContent(heapProfilerModel,objectGroupName){}
_toPercentString(num){return num.toFixed(0)+'\xa0%';}
_toUIDistance(distance){const baseSystemDistance=HeapSnapshotModel.baseSystemDistance;return distance>=0&&distance<baseSystemDistance?Common.UIString('%d',distance):Common.UIString('\u2212');}
allChildren(){return this._dataGrid.allChildren(this);}
removeChildByIndex(index){this._dataGrid.removeChildByIndex(this,index);}
childForPosition(nodePosition){let indexOfFirstChildInRange=0;for(let i=0;i<this._retrievedChildrenRanges.length;i++){const range=this._retrievedChildrenRanges[i];if(range.from<=nodePosition&&nodePosition<range.to){const childIndex=indexOfFirstChildInRange+nodePosition-range.from;return this.allChildren()[childIndex];}
indexOfFirstChildInRange+=range.to-range.from+1;}
return null;}
_createValueCell(columnId){const cell=UI.html`<td class="numeric-column" />`;if(this.dataGrid.snapshot.totalSize!==0){const div=UI.html`<div><span>${this.data[columnId]}</span></div>`;const percentColumn=columnId+'-percent';if(percentColumn in this.data){div.appendChild(UI.html`<span class="percent-column">${this.data[percentColumn]}</span>`);div.classList.add('profile-multiple-values');}
cell.appendChild(div);}
return cell;}
populate(){if(this._populated)
return;this._populated=true;this._provider().sortAndRewind(this.comparator()).then(()=>this._populateChildren());}
expandWithoutPopulate(){this._populated=true;this.expand();return this._provider().sortAndRewind(this.comparator());}
_populateChildren(fromPosition,toPosition){let afterPopulate;const promise=new Promise(resolve=>afterPopulate=resolve);fromPosition=fromPosition||0;toPosition=toPosition||fromPosition+this._dataGrid.defaultPopulateCount();let firstNotSerializedPosition=fromPosition;serializeNextChunk.call(this);return promise;function serializeNextChunk(){if(firstNotSerializedPosition>=toPosition)
return;const end=Math.min(firstNotSerializedPosition+this._dataGrid.defaultPopulateCount(),toPosition);this._provider().serializeItemsRange(firstNotSerializedPosition,end).then(childrenRetrieved.bind(this));firstNotSerializedPosition=end;}
function insertRetrievedChild(item,insertionIndex){if(this._savedChildren){const hash=this._childHashForEntity(item);if(hash in this._savedChildren){this._dataGrid.insertChild(this,this._savedChildren[hash],insertionIndex);return;}}
this._dataGrid.insertChild(this,this._createChildNode(item),insertionIndex);}
function insertShowMoreButton(from,to,insertionIndex){const button=new DataGrid.ShowMoreDataGridNode(this._populateChildren.bind(this),from,to,this._dataGrid.defaultPopulateCount());this._dataGrid.insertChild(this,button,insertionIndex);}
function childrenRetrieved(itemsRange){let itemIndex=0;let itemPosition=itemsRange.startPosition;const items=itemsRange.items;let insertionIndex=0;if(!this._retrievedChildrenRanges.length){if(itemsRange.startPosition>0){this._retrievedChildrenRanges.push({from:0,to:0});insertShowMoreButton.call(this,0,itemsRange.startPosition,insertionIndex++);}
this._retrievedChildrenRanges.push({from:itemsRange.startPosition,to:itemsRange.endPosition});for(let i=0,l=items.length;i<l;++i)
insertRetrievedChild.call(this,items[i],insertionIndex++);if(itemsRange.endPosition<itemsRange.totalLength)
insertShowMoreButton.call(this,itemsRange.endPosition,itemsRange.totalLength,insertionIndex++);}else{let rangeIndex=0;let found=false;let range;while(rangeIndex<this._retrievedChildrenRanges.length){range=this._retrievedChildrenRanges[rangeIndex];if(range.to>=itemPosition){found=true;break;}
insertionIndex+=range.to-range.from;if(range.to<itemsRange.totalLength)
insertionIndex+=1;++rangeIndex;}
if(!found||itemsRange.startPosition<range.from){this.allChildren()[insertionIndex-1].setEndPosition(itemsRange.startPosition);insertShowMoreButton.call(this,itemsRange.startPosition,found?range.from:itemsRange.totalLength,insertionIndex);range={from:itemsRange.startPosition,to:itemsRange.startPosition};if(!found)
rangeIndex=this._retrievedChildrenRanges.length;this._retrievedChildrenRanges.splice(rangeIndex,0,range);}else{insertionIndex+=itemPosition-range.from;}
while(range.to<itemsRange.endPosition){const skipCount=range.to-itemPosition;insertionIndex+=skipCount;itemIndex+=skipCount;itemPosition=range.to;const nextRange=this._retrievedChildrenRanges[rangeIndex+1];let newEndOfRange=nextRange?nextRange.from:itemsRange.totalLength;if(newEndOfRange>itemsRange.endPosition)
newEndOfRange=itemsRange.endPosition;while(itemPosition<newEndOfRange){insertRetrievedChild.call(this,items[itemIndex++],insertionIndex++);++itemPosition;}
if(nextRange&&newEndOfRange===nextRange.from){range.to=nextRange.to;this.removeChildByIndex(insertionIndex);this._retrievedChildrenRanges.splice(rangeIndex+1,1);}else{range.to=newEndOfRange;if(newEndOfRange===itemsRange.totalLength)
this.removeChildByIndex(insertionIndex);else
this.allChildren()[insertionIndex].setStartPosition(itemsRange.endPosition);}}}
this._instanceCount+=items.length;if(firstNotSerializedPosition<toPosition){serializeNextChunk.call(this);return;}
if(this.expanded)
this._dataGrid.updateVisibleNodes(true);afterPopulate();this.dispatchEventToListeners(Profiler.HeapSnapshotGridNode.Events.PopulateComplete);}}
_saveChildren(){this._savedChildren=null;const children=this.allChildren();for(let i=0,l=children.length;i<l;++i){const child=children[i];if(!child.expanded)
continue;if(!this._savedChildren)
this._savedChildren={};this._savedChildren[this._childHashForNode(child)]=child;}}
async sort(){this._dataGrid.recursiveSortingEnter();await this._provider().sortAndRewind(this.comparator());this._saveChildren();this._dataGrid.removeAllChildren(this);this._retrievedChildrenRanges=[];const instanceCount=this._instanceCount;this._instanceCount=0;await this._populateChildren(0,instanceCount);for(const child of this.allChildren()){if(child.expanded)
child.sort();}
this._dataGrid.recursiveSortingLeave();}};Profiler.HeapSnapshotGridNode.Events={PopulateComplete:Symbol('PopulateComplete')};Profiler.HeapSnapshotGridNode.ChildrenProvider=function(){};Profiler.HeapSnapshotGridNode.ChildrenProvider.prototype={dispose(){},nodePosition(snapshotObjectId){},isEmpty(){},serializeItemsRange(startPosition,endPosition){},sortAndRewind(comparator){}};Profiler.HeapSnapshotGenericObjectNode=class extends Profiler.HeapSnapshotGridNode{constructor(dataGrid,node){super(dataGrid,false);if(!node)
return;this._name=node.name;this._type=node.type;this._distance=node.distance;this._shallowSize=node.selfSize;this._retainedSize=node.retainedSize;this.snapshotNodeId=node.id;this.snapshotNodeIndex=node.nodeIndex;if(this._type==='string'){this._reachableFromWindow=true;}else if(this._type==='object'&&this._name.startsWith('Window')){this._name=this.shortenWindowURL(this._name,false);this._reachableFromWindow=true;}else if(node.canBeQueried){this._reachableFromWindow=true;}
if(node.detachedDOMTreeNode)
this.detachedDOMTreeNode=true;const snapshot=dataGrid.snapshot;const shallowSizePercent=this._shallowSize/snapshot.totalSize*100.0;const retainedSizePercent=this._retainedSize/snapshot.totalSize*100.0;this.data={'distance':this._toUIDistance(this._distance),'shallowSize':Number.withThousandsSeparator(this._shallowSize),'retainedSize':Number.withThousandsSeparator(this._retainedSize),'shallowSize-percent':this._toPercentString(shallowSizePercent),'retainedSize-percent':this._toPercentString(retainedSizePercent)};}
retainersDataSource(){return{snapshot:this._dataGrid.snapshot,snapshotNodeIndex:this.snapshotNodeIndex};}
createCell(columnId){const cell=columnId!=='object'?this._createValueCell(columnId):this._createObjectCell();if(this._searchMatched)
cell.classList.add('highlight');return cell;}
_createObjectCell(){let value=this._name;let valueStyle='object';switch(this._type){case'concatenated string':case'string':value=`"${value}"`;valueStyle='string';break;case'regexp':value=`/${value}/`;valueStyle='string';break;case'closure':value=`${value}()`;valueStyle='function';break;case'bigint':valueStyle='bigint';break;case'number':valueStyle='number';break;case'hidden':valueStyle='null';break;case'array':value=(value||ls`(internal array)`)+'[]';break;}
return this._createObjectCellWithValue(valueStyle,value);}
_createObjectCellWithValue(valueStyle,value){const fragment=UI.Fragment.build`
<td class="object-column disclosure">
<div class="source-code event-properties" style="overflow: visible" $="container">
<span class="value object-value-${valueStyle}">${value}</span>
<span class="object-value-id">@${this.snapshotNodeId}</span>
</div>
</td>`;const div=fragment.$('container');this._prefixObjectCell(div);if(this._reachableFromWindow){div.appendChild(UI.html`<span class="heap-object-tag" title="${ls`User object reachable from window`}">🗖</span>`);}
if(this.detachedDOMTreeNode)
div.appendChild(UI.html`<span class="heap-object-tag" title="${ls`Detached from DOM tree`}">✀</span>`);this._appendSourceLocation(div);const cell=fragment.element();if(this.depth)
cell.style.setProperty('padding-left',(this.depth*this.dataGrid.indentWidth)+'px');cell.heapSnapshotNode=this;return cell;}
_prefixObjectCell(div){}
async _appendSourceLocation(div){const linkContainer=UI.html`<span class="heap-object-source-link" />`;div.appendChild(linkContainer);const link=await this._dataGrid.dataDisplayDelegate().linkifyObject(this.snapshotNodeIndex);if(link)
linkContainer.appendChild(link);else
linkContainer.remove();}
async queryObjectContent(heapProfilerModel,objectGroupName){const runtimeModel=heapProfilerModel.runtimeModel();let result;if(this._type==='string')
result=runtimeModel.createRemoteObjectFromPrimitiveValue(this._name);else
result=await heapProfilerModel.objectForSnapshotObjectId(String(this.snapshotNodeId),objectGroupName);return result||runtimeModel.createRemoteObjectFromPrimitiveValue(ls`Preview is not available`);}
async updateHasChildren(){const isEmpty=await this._provider().isEmpty();this.setHasChildren(!isEmpty);}
shortenWindowURL(fullName,hasObjectId){const startPos=fullName.indexOf('/');const endPos=hasObjectId?fullName.indexOf('@'):fullName.length;if(startPos===-1||endPos===-1)
return fullName;const fullURL=fullName.substring(startPos+1,endPos).trimLeft();let url=fullURL.trimURL();if(url.length>40)
url=url.trimMiddle(40);return fullName.substr(0,startPos+2)+url+fullName.substr(endPos);}};Profiler.HeapSnapshotObjectNode=class extends Profiler.HeapSnapshotGenericObjectNode{constructor(dataGrid,snapshot,edge,parentObjectNode){super(dataGrid,edge.node);this._referenceName=edge.name;this._referenceType=edge.type;this._edgeIndex=edge.edgeIndex;this._snapshot=snapshot;this._parentObjectNode=parentObjectNode;this._cycledWithAncestorGridNode=this._findAncestorWithSameSnapshotNodeId();if(!this._cycledWithAncestorGridNode)
this.updateHasChildren();const data=this.data;data['count']='';data['addedCount']='';data['removedCount']='';data['countDelta']='';data['addedSize']='';data['removedSize']='';data['sizeDelta']='';}
retainersDataSource(){return{snapshot:this._snapshot,snapshotNodeIndex:this.snapshotNodeIndex};}
createProvider(){return this._snapshot.createEdgesProvider(this.snapshotNodeIndex);}
_findAncestorWithSameSnapshotNodeId(){let ancestor=this._parentObjectNode;while(ancestor){if(ancestor.snapshotNodeId===this.snapshotNodeId)
return ancestor;ancestor=ancestor._parentObjectNode;}
return null;}
_createChildNode(item){return new Profiler.HeapSnapshotObjectNode(this._dataGrid,this._snapshot,item,this);}
_childHashForEntity(edge){return edge.edgeIndex;}
_childHashForNode(childNode){return childNode._edgeIndex;}
comparator(){const sortAscending=this._dataGrid.isSortOrderAscending();const sortColumnId=this._dataGrid.sortColumnId();const sortFields={object:['!edgeName',sortAscending,'retainedSize',false],count:['!edgeName',true,'retainedSize',false],shallowSize:['selfSize',sortAscending,'!edgeName',true],retainedSize:['retainedSize',sortAscending,'!edgeName',true],distance:['distance',sortAscending,'_name',true]}[sortColumnId]||['!edgeName',true,'retainedSize',false];return Profiler.HeapSnapshotGridNode.createComparator(sortFields);}
_prefixObjectCell(div){let name=this._referenceName||'(empty)';let nameClass='name';switch(this._referenceType){case'context':nameClass='object-value-number';break;case'internal':case'hidden':case'weak':nameClass='object-value-null';break;case'element':name=`[${name}]`;break;}
if(this._cycledWithAncestorGridNode)
div.classList.add('cycled-ancessor-node');div.prepend(UI.html`<span class="${nameClass}">${name}</span>
<span class="grayed">${this._edgeNodeSeparator()}</span>`);}
_edgeNodeSeparator(){return'::';}};Profiler.HeapSnapshotRetainingObjectNode=class extends Profiler.HeapSnapshotObjectNode{constructor(dataGrid,snapshot,edge,parentRetainingObjectNode){super(dataGrid,snapshot,edge,parentRetainingObjectNode);}
createProvider(){return this._snapshot.createRetainingEdgesProvider(this.snapshotNodeIndex);}
_createChildNode(item){return new Profiler.HeapSnapshotRetainingObjectNode(this._dataGrid,this._snapshot,item,this);}
_edgeNodeSeparator(){return ls`in`;}
expand(){this._expandRetainersChain(20);}
_expandRetainersChain(maxExpandLevels){if(!this._populated){this.once(Profiler.HeapSnapshotGridNode.Events.PopulateComplete).then(()=>this._expandRetainersChain(maxExpandLevels));this.populate();return;}
super.expand();if(--maxExpandLevels>0&&this.children.length>0){const retainer=this.children[0];if(retainer._distance>1){retainer._expandRetainersChain(maxExpandLevels);return;}}
this._dataGrid.dispatchEventToListeners(Profiler.HeapSnapshotRetainmentDataGrid.Events.ExpandRetainersComplete);}};Profiler.HeapSnapshotInstanceNode=class extends Profiler.HeapSnapshotGenericObjectNode{constructor(dataGrid,snapshot,node,isDeletedNode){super(dataGrid,node);this._baseSnapshotOrSnapshot=snapshot;this._isDeletedNode=isDeletedNode;this.updateHasChildren();const data=this.data;data['count']='';data['countDelta']='';data['sizeDelta']='';if(this._isDeletedNode){data['addedCount']='';data['addedSize']='';data['removedCount']='\u2022';data['removedSize']=Number.withThousandsSeparator(this._shallowSize);}else{data['addedCount']='\u2022';data['addedSize']=Number.withThousandsSeparator(this._shallowSize);data['removedCount']='';data['removedSize']='';}}
retainersDataSource(){return{snapshot:this._baseSnapshotOrSnapshot,snapshotNodeIndex:this.snapshotNodeIndex};}
createProvider(){return this._baseSnapshotOrSnapshot.createEdgesProvider(this.snapshotNodeIndex);}
_createChildNode(item){return new Profiler.HeapSnapshotObjectNode(this._dataGrid,this._baseSnapshotOrSnapshot,item,null);}
_childHashForEntity(edge){return edge.edgeIndex;}
_childHashForNode(childNode){return childNode._edgeIndex;}
comparator(){const sortAscending=this._dataGrid.isSortOrderAscending();const sortColumnId=this._dataGrid.sortColumnId();const sortFields={object:['!edgeName',sortAscending,'retainedSize',false],distance:['distance',sortAscending,'retainedSize',false],count:['!edgeName',true,'retainedSize',false],addedSize:['selfSize',sortAscending,'!edgeName',true],removedSize:['selfSize',sortAscending,'!edgeName',true],shallowSize:['selfSize',sortAscending,'!edgeName',true],retainedSize:['retainedSize',sortAscending,'!edgeName',true]}[sortColumnId]||['!edgeName',true,'retainedSize',false];return Profiler.HeapSnapshotGridNode.createComparator(sortFields);}};Profiler.HeapSnapshotConstructorNode=class extends Profiler.HeapSnapshotGridNode{constructor(dataGrid,className,aggregate,nodeFilter){super(dataGrid,aggregate.count>0);this._name=className;this._nodeFilter=nodeFilter;this._distance=aggregate.distance;this._count=aggregate.count;this._shallowSize=aggregate.self;this._retainedSize=aggregate.maxRet;const snapshot=dataGrid.snapshot;const retainedSizePercent=this._retainedSize/snapshot.totalSize*100.0;const shallowSizePercent=this._shallowSize/snapshot.totalSize*100.0;this.data={'object':className,'count':Number.withThousandsSeparator(this._count),'distance':this._toUIDistance(this._distance),'shallowSize':Number.withThousandsSeparator(this._shallowSize),'retainedSize':Number.withThousandsSeparator(this._retainedSize),'shallowSize-percent':this._toPercentString(shallowSizePercent),'retainedSize-percent':this._toPercentString(retainedSizePercent)};}
createProvider(){return this._dataGrid.snapshot.createNodesProviderForClass(this._name,this._nodeFilter);}
async populateNodeBySnapshotObjectId(snapshotObjectId){this._dataGrid.resetNameFilter();await this.expandWithoutPopulate();const nodePosition=await this._provider().nodePosition(snapshotObjectId);if(nodePosition===-1){this.collapse();return[];}
await this._populateChildren(nodePosition,null);const node=(this.childForPosition(nodePosition));return node?[this,node]:[];}
filteredOut(filterValue){return this._name.toLowerCase().indexOf(filterValue)===-1;}
createCell(columnId){const cell=columnId==='object'?super.createCell(columnId):this._createValueCell(columnId);if(columnId==='object'&&this._count>1)
cell.appendChild(UI.html`<span class="objects-count">×${this._count}</span>`);if(this._searchMatched)
cell.classList.add('highlight');return cell;}
_createChildNode(item){return new Profiler.HeapSnapshotInstanceNode(this._dataGrid,this._dataGrid.snapshot,item,false);}
comparator(){const sortAscending=this._dataGrid.isSortOrderAscending();const sortColumnId=this._dataGrid.sortColumnId();const sortFields={object:['name',sortAscending,'id',true],distance:['distance',sortAscending,'retainedSize',false],shallowSize:['selfSize',sortAscending,'id',true],retainedSize:['retainedSize',sortAscending,'id',true]}[sortColumnId];return Profiler.HeapSnapshotGridNode.createComparator(sortFields);}
_childHashForEntity(node){return node.id;}
_childHashForNode(childNode){return childNode.snapshotNodeId;}};Profiler.HeapSnapshotDiffNodesProvider=class{constructor(addedNodesProvider,deletedNodesProvider,addedCount,removedCount){this._addedNodesProvider=addedNodesProvider;this._deletedNodesProvider=deletedNodesProvider;this._addedCount=addedCount;this._removedCount=removedCount;}
dispose(){this._addedNodesProvider.dispose();this._deletedNodesProvider.dispose();}
nodePosition(snapshotObjectId){throw new Error('Unreachable');}
isEmpty(){return Promise.resolve(false);}
async serializeItemsRange(beginPosition,endPosition){let itemsRange;let addedItems;if(beginPosition<this._addedCount){itemsRange=await this._addedNodesProvider.serializeItemsRange(beginPosition,endPosition);for(const item of itemsRange.items)
item.isAddedNotRemoved=true;if(itemsRange.endPosition>=endPosition){itemsRange.totalLength=this._addedCount+this._removedCount;return itemsRange;}
addedItems=itemsRange;itemsRange=await this._deletedNodesProvider.serializeItemsRange(0,endPosition-itemsRange.endPosition);}else{addedItems=new HeapSnapshotModel.ItemsRange(0,0,0,[]);itemsRange=await this._deletedNodesProvider.serializeItemsRange(beginPosition-this._addedCount,endPosition-this._addedCount);}
if(!addedItems.items.length)
addedItems.startPosition=this._addedCount+itemsRange.startPosition;for(const item of itemsRange.items)
item.isAddedNotRemoved=false;addedItems.items.pushAll(itemsRange.items);addedItems.endPosition=this._addedCount+itemsRange.endPosition;addedItems.totalLength=this._addedCount+this._removedCount;return addedItems;}
async sortAndRewind(comparator){await this._addedNodesProvider.sortAndRewind(comparator);await this._deletedNodesProvider.sortAndRewind(comparator);}};Profiler.HeapSnapshotDiffNode=class extends Profiler.HeapSnapshotGridNode{constructor(dataGrid,className,diffForClass){super(dataGrid,true);this._name=className;this._addedCount=diffForClass.addedCount;this._removedCount=diffForClass.removedCount;this._countDelta=diffForClass.countDelta;this._addedSize=diffForClass.addedSize;this._removedSize=diffForClass.removedSize;this._sizeDelta=diffForClass.sizeDelta;this._deletedIndexes=diffForClass.deletedIndexes;this.data={'object':className,'addedCount':Number.withThousandsSeparator(this._addedCount),'removedCount':Number.withThousandsSeparator(this._removedCount),'countDelta':this._signForDelta(this._countDelta)+Number.withThousandsSeparator(Math.abs(this._countDelta)),'addedSize':Number.withThousandsSeparator(this._addedSize),'removedSize':Number.withThousandsSeparator(this._removedSize),'sizeDelta':this._signForDelta(this._sizeDelta)+Number.withThousandsSeparator(Math.abs(this._sizeDelta))};}
createProvider(){const tree=this._dataGrid;return new Profiler.HeapSnapshotDiffNodesProvider(tree.snapshot.createAddedNodesProvider(tree.baseSnapshot.uid,this._name),tree.baseSnapshot.createDeletedNodesProvider(this._deletedIndexes),this._addedCount,this._removedCount);}
createCell(columnId){const cell=super.createCell(columnId);if(columnId!=='object')
cell.classList.add('numeric-column');return cell;}
_createChildNode(item){if(item.isAddedNotRemoved)
return new Profiler.HeapSnapshotInstanceNode(this._dataGrid,this._dataGrid.snapshot,item,false);else
return new Profiler.HeapSnapshotInstanceNode(this._dataGrid,this._dataGrid.baseSnapshot,item,true);}
_childHashForEntity(node){return node.id;}
_childHashForNode(childNode){return childNode.snapshotNodeId;}
comparator(){const sortAscending=this._dataGrid.isSortOrderAscending();const sortColumnId=this._dataGrid.sortColumnId();const sortFields={object:['name',sortAscending,'id',true],addedCount:['name',true,'id',true],removedCount:['name',true,'id',true],countDelta:['name',true,'id',true],addedSize:['selfSize',sortAscending,'id',true],removedSize:['selfSize',sortAscending,'id',true],sizeDelta:['selfSize',sortAscending,'id',true]}[sortColumnId];return Profiler.HeapSnapshotGridNode.createComparator(sortFields);}
filteredOut(filterValue){return this._name.toLowerCase().indexOf(filterValue)===-1;}
_signForDelta(delta){if(delta===0)
return'';if(delta>0)
return'+';else
return'\u2212';}};Profiler.AllocationGridNode=class extends Profiler.HeapSnapshotGridNode{constructor(dataGrid,data){super(dataGrid,data.hasChildren);this._populated=false;this._allocationNode=data;this.data={'liveCount':Number.withThousandsSeparator(data.liveCount),'count':Number.withThousandsSeparator(data.count),'liveSize':Number.withThousandsSeparator(data.liveSize),'size':Number.withThousandsSeparator(data.size),'name':data.name};}
populate(){if(this._populated)
return;this._doPopulate();}
async _doPopulate(){this._populated=true;const callers=await this._dataGrid.snapshot.allocationNodeCallers(this._allocationNode.id);const callersChain=callers.nodesWithSingleCaller;let parentNode=this;const dataGrid=(this._dataGrid);for(const caller of callersChain){const child=new Profiler.AllocationGridNode(dataGrid,caller);dataGrid.appendNode(parentNode,child);parentNode=child;parentNode._populated=true;if(this.expanded)
parentNode.expand();}
const callersBranch=callers.branchingCallers;callersBranch.sort(this._dataGrid._createComparator());for(const caller of callersBranch)
dataGrid.appendNode(parentNode,new Profiler.AllocationGridNode(dataGrid,caller));dataGrid.updateVisibleNodes(true);}
expand(){super.expand();if(this.children.length===1)
this.children[0].expand();}
createCell(columnId){if(columnId!=='name')
return this._createValueCell(columnId);const cell=super.createCell(columnId);const allocationNode=this._allocationNode;const heapProfilerModel=this._dataGrid.heapProfilerModel();if(allocationNode.scriptId){const linkifier=this._dataGrid._linkifier;const urlElement=linkifier.linkifyScriptLocation(heapProfilerModel?heapProfilerModel.target():null,String(allocationNode.scriptId),allocationNode.scriptName,allocationNode.line-1,allocationNode.column-1,'profile-node-file');urlElement.style.maxWidth='75%';cell.insertBefore(urlElement,cell.firstChild);}
return cell;}
allocationNodeId(){return this._allocationNode.id;}};;Profiler.HeapSnapshotView=class extends UI.SimpleView{constructor(dataDisplayDelegate,profile){super(Common.UIString('Heap Snapshot'));this.element.classList.add('heap-snapshot-view');this._profile=profile;this._linkifier=new Components.Linkifier();const profileType=profile.profileType();profileType.addEventListener(Profiler.HeapSnapshotProfileType.SnapshotReceived,this._onReceiveSnapshot,this);profileType.addEventListener(Profiler.ProfileType.Events.RemoveProfileHeader,this._onProfileHeaderRemoved,this);const isHeapTimeline=profileType.id===Profiler.TrackingHeapSnapshotProfileType.TypeId;if(isHeapTimeline)
this._createOverview();this._parentDataDisplayDelegate=dataDisplayDelegate;this._searchableView=new UI.SearchableView(this);this._searchableView.show(this.element);this._splitWidget=new UI.SplitWidget(false,true,'heapSnapshotSplitViewState',200,200);this._splitWidget.show(this._searchableView.element);this._containmentDataGrid=new Profiler.HeapSnapshotContainmentDataGrid(this);this._containmentDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._selectionChanged,this);this._containmentWidget=this._containmentDataGrid.asWidget();this._containmentWidget.setMinimumSize(50,25);this._statisticsView=new Profiler.HeapSnapshotStatisticsView();this._constructorsDataGrid=new Profiler.HeapSnapshotConstructorsDataGrid(this);this._constructorsDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._selectionChanged,this);this._constructorsWidget=this._constructorsDataGrid.asWidget();this._constructorsWidget.setMinimumSize(50,25);this._diffDataGrid=new Profiler.HeapSnapshotDiffDataGrid(this);this._diffDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._selectionChanged,this);this._diffWidget=this._diffDataGrid.asWidget();this._diffWidget.setMinimumSize(50,25);if(isHeapTimeline){this._allocationDataGrid=new Profiler.AllocationDataGrid(profile.heapProfilerModel(),this);this._allocationDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._onSelectAllocationNode,this);this._allocationWidget=this._allocationDataGrid.asWidget();this._allocationWidget.setMinimumSize(50,25);this._allocationStackView=new Profiler.HeapAllocationStackView(profile.heapProfilerModel());this._allocationStackView.setMinimumSize(50,25);this._tabbedPane=new UI.TabbedPane();}
this._retainmentDataGrid=new Profiler.HeapSnapshotRetainmentDataGrid(this);this._retainmentWidget=this._retainmentDataGrid.asWidget();this._retainmentWidget.setMinimumSize(50,21);this._retainmentWidget.element.classList.add('retaining-paths-view');let splitWidgetResizer;if(this._allocationStackView){this._tabbedPane=new UI.TabbedPane();this._tabbedPane.appendTab('retainers',Common.UIString('Retainers'),this._retainmentWidget);this._tabbedPane.appendTab('allocation-stack',Common.UIString('Allocation stack'),this._allocationStackView);splitWidgetResizer=this._tabbedPane.headerElement();this._objectDetailsView=this._tabbedPane;}else{const retainmentViewHeader=createElementWithClass('div','heap-snapshot-view-resizer');const retainingPathsTitleDiv=retainmentViewHeader.createChild('div','title');const retainingPathsTitle=retainingPathsTitleDiv.createChild('span');retainingPathsTitle.textContent=Common.UIString('Retainers');splitWidgetResizer=retainmentViewHeader;this._objectDetailsView=new UI.VBox();this._objectDetailsView.element.appendChild(retainmentViewHeader);this._retainmentWidget.show(this._objectDetailsView.element);}
this._splitWidget.hideDefaultResizer();this._splitWidget.installResizer(splitWidgetResizer);this._retainmentDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._inspectedObjectChanged,this);this._retainmentDataGrid.reset();this._perspectives=[];this._comparisonPerspective=new Profiler.HeapSnapshotView.ComparisonPerspective();this._perspectives.push(new Profiler.HeapSnapshotView.SummaryPerspective());if(profile.profileType()!==Profiler.ProfileTypeRegistry.instance.trackingHeapSnapshotProfileType)
this._perspectives.push(this._comparisonPerspective);this._perspectives.push(new Profiler.HeapSnapshotView.ContainmentPerspective());if(this._allocationWidget)
this._perspectives.push(new Profiler.HeapSnapshotView.AllocationPerspective());this._perspectives.push(new Profiler.HeapSnapshotView.StatisticsPerspective());this._perspectiveSelect=new UI.ToolbarComboBox(this._onSelectedPerspectiveChanged.bind(this));this._updatePerspectiveOptions();this._baseSelect=new UI.ToolbarComboBox(this._changeBase.bind(this));this._baseSelect.setVisible(false);this._updateBaseOptions();this._filterSelect=new UI.ToolbarComboBox(this._changeFilter.bind(this));this._filterSelect.setVisible(false);this._updateFilterOptions();this._classNameFilter=new UI.ToolbarInput('Class filter');this._classNameFilter.setVisible(false);this._constructorsDataGrid.setNameFilter(this._classNameFilter);this._diffDataGrid.setNameFilter(this._classNameFilter);this._selectedSizeText=new UI.ToolbarText();this._popoverHelper=new UI.PopoverHelper(this.element,this._getPopoverRequest.bind(this));this._popoverHelper.setDisableOnClick(true);this._popoverHelper.setHasPadding(true);this.element.addEventListener('scroll',this._popoverHelper.hidePopover.bind(this._popoverHelper),true);this._currentPerspectiveIndex=0;this._currentPerspective=this._perspectives[0];this._currentPerspective.activate(this);this._dataGrid=this._currentPerspective.masterGrid(this);this._populate();this._searchThrottler=new Common.Throttler(0);this.element.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);for(const existingProfile of this._profiles())
existingProfile.addEventListener(Profiler.ProfileHeader.Events.ProfileTitleChanged,this._updateControls,this);}
_createOverview(){const profileType=this._profile.profileType();this._trackingOverviewGrid=new Profiler.HeapTimelineOverview();this._trackingOverviewGrid.addEventListener(Profiler.HeapTimelineOverview.IdsRangeChanged,this._onIdsRangeChanged.bind(this));if(!this._profile.fromFile()&&profileType.profileBeingRecorded()===this._profile){profileType.addEventListener(Profiler.TrackingHeapSnapshotProfileType.HeapStatsUpdate,this._onHeapStatsUpdate,this);profileType.addEventListener(Profiler.TrackingHeapSnapshotProfileType.TrackingStopped,this._onStopTracking,this);this._trackingOverviewGrid.start();}}
_onStopTracking(){this._profile.profileType().removeEventListener(Profiler.TrackingHeapSnapshotProfileType.HeapStatsUpdate,this._onHeapStatsUpdate,this);this._profile.profileType().removeEventListener(Profiler.TrackingHeapSnapshotProfileType.TrackingStopped,this._onStopTracking,this);if(this._trackingOverviewGrid)
this._trackingOverviewGrid.stop();}
_onHeapStatsUpdate(event){const samples=event.data;if(samples)
this._trackingOverviewGrid.setSamples(event.data);}
searchableView(){return this._searchableView;}
showProfile(profile){return this._parentDataDisplayDelegate.showProfile(profile);}
showObject(snapshotObjectId,perspectiveName){if(snapshotObjectId<=this._profile.maxJSObjectId)
this.selectLiveObject(perspectiveName,snapshotObjectId);else
this._parentDataDisplayDelegate.showObject(snapshotObjectId,perspectiveName);}
async linkifyObject(nodeIndex){const heapProfilerModel=this._profile.heapProfilerModel();if(!heapProfilerModel)
return null;const location=await this._profile.getLocation(nodeIndex);if(!location)
return null;const debuggerModel=heapProfilerModel.runtimeModel().debuggerModel();const rawLocation=debuggerModel.createRawLocationByScriptId(String(location.scriptId),location.lineNumber,location.columnNumber);if(!rawLocation)
return null;const sourceURL=rawLocation.script()&&rawLocation.script().sourceURL;return sourceURL&&this._linkifier?this._linkifier.linkifyRawLocation(rawLocation,sourceURL):null;}
async _populate(){const heapSnapshotProxy=await this._profile._loadPromise;this._retrieveStatistics(heapSnapshotProxy);this._dataGrid.setDataSource(heapSnapshotProxy);if(this._profile.profileType().id===Profiler.TrackingHeapSnapshotProfileType.TypeId&&this._profile.fromFile()){const samples=await heapSnapshotProxy.getSamples();if(samples){console.assert(samples.timestamps.length);const profileSamples=new Profiler.HeapTimelineOverview.Samples();profileSamples.sizes=samples.sizes;profileSamples.ids=samples.lastAssignedIds;profileSamples.timestamps=samples.timestamps;profileSamples.max=samples.sizes;profileSamples.totalTime=Math.max(samples.timestamps.peekLast(),10000);this._trackingOverviewGrid.setSamples(profileSamples);}}
const list=this._profiles();const profileIndex=list.indexOf(this._profile);this._baseSelect.setSelectedIndex(Math.max(0,profileIndex-1));if(this._trackingOverviewGrid)
this._trackingOverviewGrid.updateGrid();}
async _retrieveStatistics(heapSnapshotProxy){const statistics=await heapSnapshotProxy.getStatistics();this._statisticsView.setTotal(statistics.total);this._statisticsView.addRecord(statistics.code,Common.UIString('Code'),'#f77');this._statisticsView.addRecord(statistics.strings,Common.UIString('Strings'),'#5e5');this._statisticsView.addRecord(statistics.jsArrays,Common.UIString('JS Arrays'),'#7af');this._statisticsView.addRecord(statistics.native,Common.UIString('Typed Arrays'),'#fc5');this._statisticsView.addRecord(statistics.system,Common.UIString('System Objects'),'#98f');return statistics;}
_onIdsRangeChanged(event){const minId=event.data.minId;const maxId=event.data.maxId;this._selectedSizeText.setText(Common.UIString('Selected size: %s',Number.bytesToString(event.data.size)));if(this._constructorsDataGrid.snapshot)
this._constructorsDataGrid.setSelectionRange(minId,maxId);}
syncToolbarItems(){const result=[this._perspectiveSelect,this._classNameFilter];if(this._profile.profileType()!==Profiler.ProfileTypeRegistry.instance.trackingHeapSnapshotProfileType)
result.push(this._baseSelect,this._filterSelect);result.push(this._selectedSizeText);return result;}
willHide(){this._currentSearchResultIndex=-1;this._popoverHelper.hidePopover();}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return false;}
searchCanceled(){this._currentSearchResultIndex=-1;this._searchResults=[];}
_selectRevealedNode(node){if(node)
node.select();}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);if(this._dataGrid)
this._dataGrid.populateContextMenu(contextMenu,event);contextMenu.show();}
performSearch(searchConfig,shouldJump,jumpBackwards){const nextQuery=new HeapSnapshotModel.SearchConfig(searchConfig.query.trim(),searchConfig.caseSensitive,searchConfig.isRegex,shouldJump,jumpBackwards||false);this._searchThrottler.schedule(this._performSearch.bind(this,nextQuery));}
async _performSearch(nextQuery){this.searchCanceled();if(!this._currentPerspective.supportsSearch())
return;this.currentQuery=nextQuery;const query=nextQuery.query.trim();if(!query)
return;if(query.charAt(0)==='@'){const snapshotNodeId=parseInt(query.substring(1),10);if(isNaN(snapshotNodeId))
return;const node=await this._dataGrid.revealObjectByHeapSnapshotId(String(snapshotNodeId));this._selectRevealedNode(node);return;}
this._searchResults=await this._profile._snapshotProxy.search(this.currentQuery,this._dataGrid.nodeFilter());this._searchableView.updateSearchMatchesCount(this._searchResults.length);if(this._searchResults.length)
this._currentSearchResultIndex=nextQuery.jumpBackwards?this._searchResults.length-1:0;await this._jumpToSearchResult(this._currentSearchResultIndex);}
jumpToNextSearchResult(){if(!this._searchResults.length)
return;this._currentSearchResultIndex=(this._currentSearchResultIndex+1)%this._searchResults.length;this._searchThrottler.schedule(this._jumpToSearchResult.bind(this,this._currentSearchResultIndex));}
jumpToPreviousSearchResult(){if(!this._searchResults.length)
return;this._currentSearchResultIndex=(this._currentSearchResultIndex+this._searchResults.length-1)%this._searchResults.length;this._searchThrottler.schedule(this._jumpToSearchResult.bind(this,this._currentSearchResultIndex));}
async _jumpToSearchResult(searchResultIndex){this._searchableView.updateCurrentMatchIndex(searchResultIndex);if(searchResultIndex===-1)
return;const node=await this._dataGrid.revealObjectByHeapSnapshotId(String(this._searchResults[searchResultIndex]));this._selectRevealedNode(node);}
refreshVisibleData(){if(!this._dataGrid)
return;let child=this._dataGrid.rootNode().children[0];while(child){child.refresh();child=child.traverseNextNode(false,null,true);}}
_changeBase(){if(this._baseProfile===this._profiles()[this._baseSelect.selectedIndex()])
return;this._baseProfile=this._profiles()[this._baseSelect.selectedIndex()];const dataGrid=(this._dataGrid);if(dataGrid.snapshot)
this._baseProfile._loadPromise.then(dataGrid.setBaseDataSource.bind(dataGrid));if(!this.currentQuery||!this._searchResults)
return;this.performSearch(this.currentQuery,false);}
_changeFilter(){const profileIndex=this._filterSelect.selectedIndex()-1;this._dataGrid.filterSelectIndexChanged(this._profiles(),profileIndex);if(!this.currentQuery||!this._searchResults)
return;this.performSearch(this.currentQuery,false);}
_profiles(){return this._profile.profileType().getProfiles();}
_selectionChanged(event){const selectedNode=(event.data);this._setSelectedNodeForDetailsView(selectedNode);this._inspectedObjectChanged(event);}
_onSelectAllocationNode(event){const selectedNode=(event.data);this._constructorsDataGrid.setAllocationNodeId(selectedNode.allocationNodeId());this._setSelectedNodeForDetailsView(null);}
_inspectedObjectChanged(event){const selectedNode=(event.data);const heapProfilerModel=this._profile.heapProfilerModel();if(heapProfilerModel&&selectedNode instanceof Profiler.HeapSnapshotGenericObjectNode)
heapProfilerModel.addInspectedHeapObject(String(selectedNode.snapshotNodeId));}
_setSelectedNodeForDetailsView(nodeItem){const dataSource=nodeItem&&nodeItem.retainersDataSource();if(dataSource){this._retainmentDataGrid.setDataSource(dataSource.snapshot,dataSource.snapshotNodeIndex);if(this._allocationStackView)
this._allocationStackView.setAllocatedObject(dataSource.snapshot,dataSource.snapshotNodeIndex);}else{if(this._allocationStackView)
this._allocationStackView.clear();this._retainmentDataGrid.reset();}}
_changePerspectiveAndWait(perspectiveTitle){const perspectiveIndex=this._perspectives.findIndex(perspective=>perspective.title()===perspectiveTitle);if(perspectiveIndex===-1||this._currentPerspectiveIndex===perspectiveIndex)
return Promise.resolve();const promise=this._perspectives[perspectiveIndex].masterGrid(this).once(Profiler.HeapSnapshotSortableDataGrid.Events.ContentShown);const option=this._perspectiveSelect.options().find(option=>option.value===perspectiveIndex);this._perspectiveSelect.select((option));this._changePerspective(perspectiveIndex);return promise;}
async _updateDataSourceAndView(){const dataGrid=this._dataGrid;if(!dataGrid||dataGrid.snapshot)
return;const snapshotProxy=await this._profile._loadPromise;if(this._dataGrid!==dataGrid)
return;if(dataGrid.snapshot!==snapshotProxy)
dataGrid.setDataSource(snapshotProxy);if(dataGrid!==this._diffDataGrid)
return;if(!this._baseProfile)
this._baseProfile=this._profiles()[this._baseSelect.selectedIndex()];const baseSnapshotProxy=await this._baseProfile._loadPromise;if(this._diffDataGrid.baseSnapshot!==baseSnapshotProxy)
this._diffDataGrid.setBaseDataSource(baseSnapshotProxy);}
_onSelectedPerspectiveChanged(event){this._changePerspective(event.target.selectedOptions[0].value);}
_changePerspective(selectedIndex){if(selectedIndex===this._currentPerspectiveIndex)
return;this._currentPerspectiveIndex=selectedIndex;this._currentPerspective.deactivate(this);const perspective=this._perspectives[selectedIndex];this._currentPerspective=perspective;this._dataGrid=perspective.masterGrid(this);perspective.activate(this);this.refreshVisibleData();if(this._dataGrid)
this._dataGrid.updateWidths();this._updateDataSourceAndView();if(!this.currentQuery||!this._searchResults)
return;this.performSearch(this.currentQuery,false);}
async selectLiveObject(perspectiveName,snapshotObjectId){await this._changePerspectiveAndWait(perspectiveName);const node=await this._dataGrid.revealObjectByHeapSnapshotId(snapshotObjectId);if(node)
node.select();else
Common.console.error('Cannot find corresponding heap snapshot node');}
_getPopoverRequest(event){const span=event.target.enclosingNodeOrSelfWithNodeName('span');const row=event.target.enclosingNodeOrSelfWithNodeName('tr');const heapProfilerModel=this._profile.heapProfilerModel();if(!row||!span||!heapProfilerModel)
return null;const node=row._dataGridNode;let objectPopoverHelper;return{box:span.boxInWindow(),show:async popover=>{const remoteObject=await node.queryObjectContent(heapProfilerModel,'popover');if(!remoteObject)
return false;objectPopoverHelper=await ObjectUI.ObjectPopoverHelper.buildObjectPopover(remoteObject,popover);if(!objectPopoverHelper){heapProfilerModel.runtimeModel().releaseObjectGroup('popover');return false;}
return true;},hide:()=>{heapProfilerModel.runtimeModel().releaseObjectGroup('popover');objectPopoverHelper.dispose();}};}
_updatePerspectiveOptions(){const multipleSnapshots=this._profiles().length>1;this._perspectiveSelect.removeOptions();this._perspectives.forEach((perspective,index)=>{if(multipleSnapshots||perspective!==this._comparisonPerspective)
this._perspectiveSelect.createOption(perspective.title(),'',String(index));});}
_updateBaseOptions(){const list=this._profiles();const selectedIndex=this._baseSelect.selectedIndex();this._baseSelect.removeOptions();for(const item of list)
this._baseSelect.createOption(item.title);if(selectedIndex>-1)
this._baseSelect.setSelectedIndex(selectedIndex);}
_updateFilterOptions(){const list=this._profiles();const selectedIndex=this._filterSelect.selectedIndex();this._filterSelect.removeOptions();this._filterSelect.createOption(Common.UIString('All objects'));for(let i=0;i<list.length;++i){let title;if(!i)
title=Common.UIString('Objects allocated before %s',list[i].title);else
title=Common.UIString('Objects allocated between %s and %s',list[i-1].title,list[i].title);this._filterSelect.createOption(title);}
if(selectedIndex>-1)
this._filterSelect.setSelectedIndex(selectedIndex);}
_updateControls(){this._updatePerspectiveOptions();this._updateBaseOptions();this._updateFilterOptions();}
_onReceiveSnapshot(event){this._updateControls();const profile=event.data;profile.addEventListener(Profiler.ProfileHeader.Events.ProfileTitleChanged,this._updateControls,this);}
_onProfileHeaderRemoved(event){const profile=event.data;profile.removeEventListener(Profiler.ProfileHeader.Events.ProfileTitleChanged,this._updateControls,this);if(this._profile===profile){this.detach();this._profile.profileType().removeEventListener(Profiler.HeapSnapshotProfileType.SnapshotReceived,this._onReceiveSnapshot,this);this._profile.profileType().removeEventListener(Profiler.ProfileType.Events.RemoveProfileHeader,this._onProfileHeaderRemoved,this);this.dispose();}else{this._updateControls();}}
dispose(){this._linkifier.dispose();this._popoverHelper.dispose();if(this._allocationStackView){this._allocationStackView.clear();this._allocationDataGrid.dispose();}
this._onStopTracking();if(this._trackingOverviewGrid){this._trackingOverviewGrid.removeEventListener(Profiler.HeapTimelineOverview.IdsRangeChanged,this._onIdsRangeChanged.bind(this));}}};Profiler.HeapSnapshotView.Perspective=class{constructor(title){this._title=title;}
activate(heapSnapshotView){}
deactivate(heapSnapshotView){heapSnapshotView._baseSelect.setVisible(false);heapSnapshotView._filterSelect.setVisible(false);heapSnapshotView._classNameFilter.setVisible(false);if(heapSnapshotView._trackingOverviewGrid)
heapSnapshotView._trackingOverviewGrid.detach();if(heapSnapshotView._allocationWidget)
heapSnapshotView._allocationWidget.detach();if(heapSnapshotView._statisticsView)
heapSnapshotView._statisticsView.detach();heapSnapshotView._splitWidget.detach();heapSnapshotView._splitWidget.detachChildWidgets();}
masterGrid(heapSnapshotView){return null;}
title(){return this._title;}
supportsSearch(){return false;}};Profiler.HeapSnapshotView.SummaryPerspective=class extends Profiler.HeapSnapshotView.Perspective{constructor(){super(Common.UIString('Summary'));}
activate(heapSnapshotView){heapSnapshotView._splitWidget.setMainWidget(heapSnapshotView._constructorsWidget);heapSnapshotView._splitWidget.setSidebarWidget(heapSnapshotView._objectDetailsView);heapSnapshotView._splitWidget.show(heapSnapshotView._searchableView.element);heapSnapshotView._filterSelect.setVisible(true);heapSnapshotView._classNameFilter.setVisible(true);if(!heapSnapshotView._trackingOverviewGrid)
return;heapSnapshotView._trackingOverviewGrid.show(heapSnapshotView._searchableView.element,heapSnapshotView._splitWidget.element);heapSnapshotView._trackingOverviewGrid.update();heapSnapshotView._trackingOverviewGrid.updateGrid();}
masterGrid(heapSnapshotView){return heapSnapshotView._constructorsDataGrid;}
supportsSearch(){return true;}};Profiler.HeapSnapshotView.ComparisonPerspective=class extends Profiler.HeapSnapshotView.Perspective{constructor(){super(Common.UIString('Comparison'));}
activate(heapSnapshotView){heapSnapshotView._splitWidget.setMainWidget(heapSnapshotView._diffWidget);heapSnapshotView._splitWidget.setSidebarWidget(heapSnapshotView._objectDetailsView);heapSnapshotView._splitWidget.show(heapSnapshotView._searchableView.element);heapSnapshotView._baseSelect.setVisible(true);heapSnapshotView._classNameFilter.setVisible(true);}
masterGrid(heapSnapshotView){return heapSnapshotView._diffDataGrid;}
supportsSearch(){return true;}};Profiler.HeapSnapshotView.ContainmentPerspective=class extends Profiler.HeapSnapshotView.Perspective{constructor(){super(Common.UIString('Containment'));}
activate(heapSnapshotView){heapSnapshotView._splitWidget.setMainWidget(heapSnapshotView._containmentWidget);heapSnapshotView._splitWidget.setSidebarWidget(heapSnapshotView._objectDetailsView);heapSnapshotView._splitWidget.show(heapSnapshotView._searchableView.element);}
masterGrid(heapSnapshotView){return heapSnapshotView._containmentDataGrid;}};Profiler.HeapSnapshotView.AllocationPerspective=class extends Profiler.HeapSnapshotView.Perspective{constructor(){super(Common.UIString('Allocation'));this._allocationSplitWidget=new UI.SplitWidget(false,true,'heapSnapshotAllocationSplitViewState',200,200);this._allocationSplitWidget.setSidebarWidget(new UI.VBox());}
activate(heapSnapshotView){this._allocationSplitWidget.setMainWidget(heapSnapshotView._allocationWidget);heapSnapshotView._splitWidget.setMainWidget(heapSnapshotView._constructorsWidget);heapSnapshotView._splitWidget.setSidebarWidget(heapSnapshotView._objectDetailsView);const allocatedObjectsView=new UI.VBox();const resizer=createElementWithClass('div','heap-snapshot-view-resizer');const title=resizer.createChild('div','title').createChild('span');title.textContent=Common.UIString('Live objects');this._allocationSplitWidget.hideDefaultResizer();this._allocationSplitWidget.installResizer(resizer);allocatedObjectsView.element.appendChild(resizer);heapSnapshotView._splitWidget.show(allocatedObjectsView.element);this._allocationSplitWidget.setSidebarWidget(allocatedObjectsView);this._allocationSplitWidget.show(heapSnapshotView._searchableView.element);heapSnapshotView._constructorsDataGrid.clear();const selectedNode=heapSnapshotView._allocationDataGrid.selectedNode;if(selectedNode)
heapSnapshotView._constructorsDataGrid.setAllocationNodeId(selectedNode.allocationNodeId());}
deactivate(heapSnapshotView){this._allocationSplitWidget.detach();super.deactivate(heapSnapshotView);}
masterGrid(heapSnapshotView){return heapSnapshotView._allocationDataGrid;}};Profiler.HeapSnapshotView.StatisticsPerspective=class extends Profiler.HeapSnapshotView.Perspective{constructor(){super(Common.UIString('Statistics'));}
activate(heapSnapshotView){heapSnapshotView._statisticsView.show(heapSnapshotView._searchableView.element);}
masterGrid(heapSnapshotView){return null;}};Profiler.HeapSnapshotProfileType=class extends Profiler.ProfileType{constructor(id,title){super(id||Profiler.HeapSnapshotProfileType.TypeId,title||ls`Heap snapshot`);SDK.targetManager.observeModels(SDK.HeapProfilerModel,this);SDK.targetManager.addModelListener(SDK.HeapProfilerModel,SDK.HeapProfilerModel.Events.ResetProfiles,this._resetProfiles,this);SDK.targetManager.addModelListener(SDK.HeapProfilerModel,SDK.HeapProfilerModel.Events.AddHeapSnapshotChunk,this._addHeapSnapshotChunk,this);SDK.targetManager.addModelListener(SDK.HeapProfilerModel,SDK.HeapProfilerModel.Events.ReportHeapSnapshotProgress,this._reportHeapSnapshotProgress,this);}
modelAdded(heapProfilerModel){heapProfilerModel.enable();}
modelRemoved(heapProfilerModel){}
getProfiles(){return(super.getProfiles());}
fileExtension(){return'.heapsnapshot';}
get buttonTooltip(){return Common.UIString('Take heap snapshot');}
isInstantProfile(){return true;}
buttonClicked(){this._takeHeapSnapshot();Host.userMetrics.actionTaken(Host.UserMetrics.Action.ProfilesHeapProfileTaken);return false;}
get treeItemTitle(){return Common.UIString('HEAP SNAPSHOTS');}
get description(){return Common.UIString('Heap snapshot profiles show memory distribution among your page\'s JavaScript objects and related DOM nodes.');}
createProfileLoadedFromFile(title){return new Profiler.HeapProfileHeader(null,this,title);}
async _takeHeapSnapshot(){if(this.profileBeingRecorded())
return;const heapProfilerModel=UI.context.flavor(SDK.HeapProfilerModel);if(!heapProfilerModel)
return;let profile=new Profiler.HeapProfileHeader(heapProfilerModel,this);this.setProfileBeingRecorded(profile);this.addProfile(profile);profile.updateStatus(Common.UIString('Snapshotting\u2026'));await heapProfilerModel.takeHeapSnapshot(true);profile=this.profileBeingRecorded();profile.title=Common.UIString('Snapshot %d',profile.uid);profile._finishLoad();this.setProfileBeingRecorded(null);this.dispatchEventToListeners(Profiler.ProfileType.Events.ProfileComplete,profile);}
_addHeapSnapshotChunk(event){if(!this.profileBeingRecorded())
return;const chunk=(event.data);this.profileBeingRecorded().transferChunk(chunk);}
_reportHeapSnapshotProgress(event){const profile=this.profileBeingRecorded();if(!profile)
return;const data=(event.data);profile.updateStatus(Common.UIString('%.0f%%',(data.done/data.total)*100),true);if(data.finished)
profile._prepareToLoad();}
_resetProfiles(event){const heapProfilerModel=(event.data);for(const profile of this.getProfiles()){if(profile.heapProfilerModel()===heapProfilerModel)
this.removeProfile(profile);}}
_snapshotReceived(profile){if(this.profileBeingRecorded()===profile)
this.setProfileBeingRecorded(null);this.dispatchEventToListeners(Profiler.HeapSnapshotProfileType.SnapshotReceived,profile);}};Profiler.HeapSnapshotProfileType.TypeId='HEAP';Profiler.HeapSnapshotProfileType.SnapshotReceived='SnapshotReceived';Profiler.TrackingHeapSnapshotProfileType=class extends Profiler.HeapSnapshotProfileType{constructor(){super(Profiler.TrackingHeapSnapshotProfileType.TypeId,ls`Allocation instrumentation on timeline`);this._recordAllocationStacksSetting=Common.settings.createSetting('recordAllocationStacks',false);}
modelAdded(heapProfilerModel){super.modelAdded(heapProfilerModel);heapProfilerModel.addEventListener(SDK.HeapProfilerModel.Events.HeapStatsUpdate,this._heapStatsUpdate,this);heapProfilerModel.addEventListener(SDK.HeapProfilerModel.Events.LastSeenObjectId,this._lastSeenObjectId,this);}
modelRemoved(heapProfilerModel){super.modelRemoved(heapProfilerModel);heapProfilerModel.removeEventListener(SDK.HeapProfilerModel.Events.HeapStatsUpdate,this._heapStatsUpdate,this);heapProfilerModel.removeEventListener(SDK.HeapProfilerModel.Events.LastSeenObjectId,this._lastSeenObjectId,this);}
_heapStatsUpdate(event){if(!this._profileSamples)
return;const samples=(event.data);let index;for(let i=0;i<samples.length;i+=3){index=samples[i];const size=samples[i+2];this._profileSamples.sizes[index]=size;if(!this._profileSamples.max[index])
this._profileSamples.max[index]=size;}}
_lastSeenObjectId(event){const profileSamples=this._profileSamples;if(!profileSamples)
return;const data=(event.data);const currentIndex=Math.max(profileSamples.ids.length,profileSamples.max.length-1);profileSamples.ids[currentIndex]=data.lastSeenObjectId;if(!profileSamples.max[currentIndex]){profileSamples.max[currentIndex]=0;profileSamples.sizes[currentIndex]=0;}
profileSamples.timestamps[currentIndex]=data.timestamp;if(profileSamples.totalTime<data.timestamp-profileSamples.timestamps[0])
profileSamples.totalTime*=2;this.dispatchEventToListeners(Profiler.TrackingHeapSnapshotProfileType.HeapStatsUpdate,this._profileSamples);this.profileBeingRecorded().updateStatus(null,true);}
hasTemporaryView(){return true;}
get buttonTooltip(){return this._recording?ls`Stop recording heap profile`:ls`Start recording heap profile`;}
isInstantProfile(){return false;}
buttonClicked(){return this._toggleRecording();}
_startRecordingProfile(){if(this.profileBeingRecorded())
return;const heapProfilerModel=this._addNewProfile();if(!heapProfilerModel)
return;heapProfilerModel.startTrackingHeapObjects(this._recordAllocationStacksSetting.get());}
customContent(){return UI.SettingsUI.createSettingCheckbox(ls`Record allocation stacks (extra performance overhead)`,this._recordAllocationStacksSetting,true);}
_addNewProfile(){const heapProfilerModel=UI.context.flavor(SDK.HeapProfilerModel);if(!heapProfilerModel)
return null;this.setProfileBeingRecorded(new Profiler.HeapProfileHeader(heapProfilerModel,this,undefined));this._profileSamples=new Profiler.HeapTimelineOverview.Samples();this.profileBeingRecorded()._profileSamples=this._profileSamples;this._recording=true;this.addProfile((this.profileBeingRecorded()));this.profileBeingRecorded().updateStatus(Common.UIString('Recording\u2026'));this.dispatchEventToListeners(Profiler.TrackingHeapSnapshotProfileType.TrackingStarted);return heapProfilerModel;}
async _stopRecordingProfile(){this.profileBeingRecorded().updateStatus(Common.UIString('Snapshotting\u2026'));const stopPromise=this.profileBeingRecorded().heapProfilerModel().stopTrackingHeapObjects(true);this._recording=false;this.dispatchEventToListeners(Profiler.TrackingHeapSnapshotProfileType.TrackingStopped);await stopPromise;const profile=this.profileBeingRecorded();if(!profile)
return;profile._finishLoad();this._profileSamples=null;this.setProfileBeingRecorded(null);this.dispatchEventToListeners(Profiler.ProfileType.Events.ProfileComplete,profile);}
_toggleRecording(){if(this._recording)
this._stopRecordingProfile();else
this._startRecordingProfile();return this._recording;}
fileExtension(){return'.heaptimeline';}
get treeItemTitle(){return ls`ALLOCATION TIMELINES`;}
get description(){return ls`
Allocation timelines show instrumented JavaScript memory allocations over time.
Once profile is recorded you can select a time interval to see objects that
were allocated within it and still alive by the end of recording.
Use this profile type to isolate memory leaks.`;}
_resetProfiles(event){const wasRecording=this._recording;this.setProfileBeingRecorded(null);super._resetProfiles(event);this._profileSamples=null;if(wasRecording)
this._addNewProfile();}
profileBeingRecordedRemoved(){this._stopRecordingProfile();this._profileSamples=null;}};Profiler.TrackingHeapSnapshotProfileType.TypeId='HEAP-RECORD';Profiler.TrackingHeapSnapshotProfileType.HeapStatsUpdate='HeapStatsUpdate';Profiler.TrackingHeapSnapshotProfileType.TrackingStarted='TrackingStarted';Profiler.TrackingHeapSnapshotProfileType.TrackingStopped='TrackingStopped';Profiler.HeapProfileHeader=class extends Profiler.ProfileHeader{constructor(heapProfilerModel,type,title){super(type,title||Common.UIString('Snapshot %d',type.nextProfileUid()));this._heapProfilerModel=heapProfilerModel;this.maxJSObjectId=-1;this._workerProxy=null;this._receiver=null;this._snapshotProxy=null;this._loadPromise=new Promise(resolve=>this._fulfillLoad=resolve);this._totalNumberOfChunks=0;this._bufferedWriter=null;this._tempFile=null;}
heapProfilerModel(){return this._heapProfilerModel;}
getLocation(nodeIndex){return this._snapshotProxy.getLocation(nodeIndex);}
createSidebarTreeElement(dataDisplayDelegate){return new Profiler.ProfileSidebarTreeElement(dataDisplayDelegate,this,'heap-snapshot-sidebar-tree-item');}
createView(dataDisplayDelegate){return new Profiler.HeapSnapshotView(dataDisplayDelegate,this);}
_prepareToLoad(){console.assert(!this._receiver,'Already loading');this._setupWorker();this.updateStatus(Common.UIString('Loading\u2026'),true);}
_finishLoad(){if(!this._wasDisposed)
this._receiver.close();if(!this._bufferedWriter)
return;this._didWriteToTempFile(this._bufferedWriter);}
_didWriteToTempFile(tempFile){if(this._wasDisposed){if(tempFile)
tempFile.remove();return;}
this._tempFile=tempFile;if(!tempFile)
this._failedToCreateTempFile=true;if(this._onTempFileReady){this._onTempFileReady();this._onTempFileReady=null;}}
_setupWorker(){function setProfileWait(event){this.updateStatus(null,event.data);}
console.assert(!this._workerProxy,'HeapSnapshotWorkerProxy already exists');this._workerProxy=new Profiler.HeapSnapshotWorkerProxy(this._handleWorkerEvent.bind(this));this._workerProxy.addEventListener(Profiler.HeapSnapshotWorkerProxy.Events.Wait,setProfileWait,this);this._receiver=this._workerProxy.createLoader(this.uid,this._snapshotReceived.bind(this));}
_handleWorkerEvent(eventName,data){if(HeapSnapshotModel.HeapSnapshotProgressEvent.BrokenSnapshot===eventName){const error=(data);Common.console.error(error);return;}
if(HeapSnapshotModel.HeapSnapshotProgressEvent.Update!==eventName)
return;const subtitle=(data);this.updateStatus(subtitle);}
dispose(){if(this._workerProxy)
this._workerProxy.dispose();this.removeTempFile();this._wasDisposed=true;}
_didCompleteSnapshotTransfer(){if(!this._snapshotProxy)
return;this.updateStatus(Number.bytesToString(this._snapshotProxy.totalSize),false);}
transferChunk(chunk){if(!this._bufferedWriter)
this._bufferedWriter=new Bindings.TempFile();this._bufferedWriter.write([chunk]);++this._totalNumberOfChunks;this._receiver.write(chunk);}
_snapshotReceived(snapshotProxy){if(this._wasDisposed)
return;this._receiver=null;this._snapshotProxy=snapshotProxy;this.maxJSObjectId=snapshotProxy.maxJSObjectId();this._didCompleteSnapshotTransfer();this._workerProxy.startCheckingForLongRunningCalls();this.notifySnapshotReceived();}
notifySnapshotReceived(){this._fulfillLoad(this._snapshotProxy);this.profileType()._snapshotReceived(this);if(this.canSaveToFile())
this.dispatchEventToListeners(Profiler.ProfileHeader.Events.ProfileReceived);}
canSaveToFile(){return!this.fromFile()&&!!this._snapshotProxy;}
saveToFile(){const fileOutputStream=new Bindings.FileOutputStream();this._fileName=this._fileName||'Heap-'+new Date().toISO8601Compact()+this.profileType().fileExtension();fileOutputStream.open(this._fileName).then(onOpen.bind(this));async function onOpen(accepted){if(!accepted)
return;if(this._failedToCreateTempFile){Common.console.error('Failed to open temp file with heap snapshot');fileOutputStream.close();return;}
if(this._tempFile){const error=await this._tempFile.copyToOutputStream(fileOutputStream,this._onChunkTransferred.bind(this));if(error)
Common.console.error('Failed to read heap snapshot from temp file: '+error.message);this._didCompleteSnapshotTransfer();return;}
this._onTempFileReady=onOpen.bind(this,accepted);this._updateSaveProgress(0,1);}}
_onChunkTransferred(reader){this._updateSaveProgress(reader.loadedSize(),reader.fileSize());}
_updateSaveProgress(value,total){const percentValue=((total&&value/total)*100).toFixed(0);this.updateStatus(Common.UIString('Saving\u2026 %d%%',percentValue));}
async loadFromFile(file){this.updateStatus(Common.UIString('Loading\u2026'),true);this._setupWorker();const reader=new Bindings.ChunkedFileReader(file,10000000);const success=await reader.read((this._receiver));if(!success)
this.updateStatus(reader.error().message);return success?null:reader.error();}};Profiler.HeapSnapshotStatisticsView=class extends UI.VBox{constructor(){super();this.element.classList.add('heap-snapshot-statistics-view');this._pieChart=new PerfUI.PieChart({chartName:ls`Heap memory usage`,size:150,formatter:Profiler.HeapSnapshotStatisticsView._valueFormatter,showLegend:true});this._pieChart.element.classList.add('heap-snapshot-stats-pie-chart');this.element.appendChild(this._pieChart.element);}
static _valueFormatter(value){return Common.UIString('%s KB',Number.withThousandsSeparator(Math.round(value/1024)));}
setTotal(value){this._pieChart.setTotal(value);}
addRecord(value,name,color){this._pieChart.addSlice(value,color,name);}};Profiler.HeapAllocationStackView=class extends UI.Widget{constructor(heapProfilerModel){super();this._heapProfilerModel=heapProfilerModel;this._linkifier=new Components.Linkifier();}
async setAllocatedObject(snapshot,snapshotNodeIndex){this.clear();const frames=await snapshot.allocationStack(snapshotNodeIndex);if(!frames){const stackDiv=this.element.createChild('div','no-heap-allocation-stack');stackDiv.createTextChild(Common.UIString('Stack was not recorded for this object because it had been allocated before this profile recording started.'));return;}
const stackDiv=this.element.createChild('div','heap-allocation-stack');for(const frame of frames){const frameDiv=stackDiv.createChild('div','stack-frame');const name=frameDiv.createChild('div');name.textContent=UI.beautifyFunctionName(frame.functionName);if(!frame.scriptId)
continue;const urlElement=this._linkifier.linkifyScriptLocation(this._heapProfilerModel?this._heapProfilerModel.target():null,String(frame.scriptId),frame.scriptName,frame.line-1,frame.column-1);frameDiv.appendChild(urlElement);}}
clear(){this.element.removeChildren();this._linkifier.reset();}};;Profiler.HeapTimelineOverview=class extends UI.VBox{constructor(){super();this.element.id='heap-recording-view';this.element.classList.add('heap-tracking-overview');this._overviewContainer=this.element.createChild('div','heap-overview-container');this._overviewGrid=new PerfUI.OverviewGrid('heap-recording');this._overviewGrid.element.classList.add('fill');this._overviewCanvas=this._overviewContainer.createChild('canvas','heap-recording-overview-canvas');this._overviewContainer.appendChild(this._overviewGrid.element);this._overviewCalculator=new Profiler.HeapTimelineOverview.OverviewCalculator();this._overviewGrid.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);this._windowLeft=0.0;this._windowRight=1.0;this._overviewGrid.setWindow(this._windowLeft,this._windowRight);this._yScale=new Profiler.HeapTimelineOverview.SmoothScale();this._xScale=new Profiler.HeapTimelineOverview.SmoothScale();this._profileSamples=new Profiler.HeapTimelineOverview.Samples();}
start(){this._running=true;const drawFrame=()=>{this.update();if(this._running)
this.element.window().requestAnimationFrame(drawFrame);};drawFrame();}
stop(){this._running=false;}
setSamples(samples){this._profileSamples=samples;if(!this._running)
this.update();}
_drawOverviewCanvas(width,height){if(!this._profileSamples)
return;const profileSamples=this._profileSamples;const sizes=profileSamples.sizes;const topSizes=profileSamples.max;const timestamps=profileSamples.timestamps;const startTime=timestamps[0];const scaleFactor=this._xScale.nextScale(width/profileSamples.totalTime);let maxSize=0;function aggregateAndCall(sizes,callback){let size=0;let currentX=0;for(let i=1;i<timestamps.length;++i){const x=Math.floor((timestamps[i]-startTime)*scaleFactor);if(x!==currentX){if(size)
callback(currentX,size);size=0;currentX=x;}
size+=sizes[i];}
callback(currentX,size);}
function maxSizeCallback(x,size){maxSize=Math.max(maxSize,size);}
aggregateAndCall(sizes,maxSizeCallback);const yScaleFactor=this._yScale.nextScale(maxSize?height/(maxSize*1.1):0.0);this._overviewCanvas.width=width*window.devicePixelRatio;this._overviewCanvas.height=height*window.devicePixelRatio;this._overviewCanvas.style.width=width+'px';this._overviewCanvas.style.height=height+'px';const context=this._overviewCanvas.getContext('2d');context.scale(window.devicePixelRatio,window.devicePixelRatio);if(this._running){context.beginPath();context.lineWidth=2;context.strokeStyle='rgba(192, 192, 192, 0.6)';const currentX=(Date.now()-startTime)*scaleFactor;context.moveTo(currentX,height-1);context.lineTo(currentX,0);context.stroke();context.closePath();}
let gridY;let gridValue;const gridLabelHeight=14;if(yScaleFactor){const maxGridValue=(height-gridLabelHeight)/yScaleFactor;gridValue=Math.pow(1024,Math.floor(Math.log(maxGridValue)/Math.log(1024)));gridValue*=Math.pow(10,Math.floor(Math.log(maxGridValue/gridValue)/Math.LN10));if(gridValue*5<=maxGridValue)
gridValue*=5;gridY=Math.round(height-gridValue*yScaleFactor-0.5)+0.5;context.beginPath();context.lineWidth=1;context.strokeStyle='rgba(0, 0, 0, 0.2)';context.moveTo(0,gridY);context.lineTo(width,gridY);context.stroke();context.closePath();}
function drawBarCallback(x,size){context.moveTo(x,height-1);context.lineTo(x,Math.round(height-size*yScaleFactor-1));}
context.beginPath();context.lineWidth=2;context.strokeStyle='rgba(192, 192, 192, 0.6)';aggregateAndCall(topSizes,drawBarCallback);context.stroke();context.closePath();context.beginPath();context.lineWidth=2;context.strokeStyle='rgba(0, 0, 192, 0.8)';aggregateAndCall(sizes,drawBarCallback);context.stroke();context.closePath();if(gridValue){const label=Number.bytesToString(gridValue);const labelPadding=4;const labelX=0;const labelY=gridY-0.5;const labelWidth=2*labelPadding+context.measureText(label).width;context.beginPath();context.textBaseline='bottom';context.font='10px '+window.getComputedStyle(this.element,null).getPropertyValue('font-family');context.fillStyle='rgba(255, 255, 255, 0.75)';context.fillRect(labelX,labelY-gridLabelHeight,labelWidth,gridLabelHeight);context.fillStyle='rgb(64, 64, 64)';context.fillText(label,labelX+labelPadding,labelY);context.fill();context.closePath();}}
onResize(){this._updateOverviewCanvas=true;this._scheduleUpdate();}
_onWindowChanged(){if(!this._updateGridTimerId)
this._updateGridTimerId=setTimeout(this.updateGrid.bind(this),10);}
_scheduleUpdate(){if(this._updateTimerId)
return;this._updateTimerId=setTimeout(this.update.bind(this),10);}
_updateBoundaries(){this._windowLeft=this._overviewGrid.windowLeft();this._windowRight=this._overviewGrid.windowRight();this._windowWidth=this._windowRight-this._windowLeft;}
update(){this._updateTimerId=null;if(!this.isShowing())
return;this._updateBoundaries();this._overviewCalculator._updateBoundaries(this);this._overviewGrid.updateDividers(this._overviewCalculator);this._drawOverviewCanvas(this._overviewContainer.clientWidth,this._overviewContainer.clientHeight-20);}
updateGrid(){this._updateGridTimerId=0;this._updateBoundaries();const ids=this._profileSamples.ids;if(!ids.length)
return;const timestamps=this._profileSamples.timestamps;const sizes=this._profileSamples.sizes;const startTime=timestamps[0];const totalTime=this._profileSamples.totalTime;const timeLeft=startTime+totalTime*this._windowLeft;const timeRight=startTime+totalTime*this._windowRight;const minIndex=timestamps.lowerBound(timeLeft);const maxIndex=timestamps.upperBound(timeRight);let size=0;for(let i=minIndex;i<=maxIndex;++i)
size+=sizes[i];const minId=minIndex>0?ids[minIndex-1]:0;const maxId=maxIndex<ids.length?ids[maxIndex]:Infinity;this.dispatchEventToListeners(Profiler.HeapTimelineOverview.IdsRangeChanged,{minId,maxId,size});}};Profiler.HeapTimelineOverview.IdsRangeChanged=Symbol('IdsRangeChanged');Profiler.HeapTimelineOverview.SmoothScale=class{constructor(){this._lastUpdate=0;this._currentScale=0.0;}
nextScale(target){target=target||this._currentScale;if(this._currentScale){const now=Date.now();const timeDeltaMs=now-this._lastUpdate;this._lastUpdate=now;const maxChangePerSec=20;const maxChangePerDelta=Math.pow(maxChangePerSec,timeDeltaMs/1000);const scaleChange=target/this._currentScale;this._currentScale*=Number.constrain(scaleChange,1/maxChangePerDelta,maxChangePerDelta);}else{this._currentScale=target;}
return this._currentScale;}};Profiler.HeapTimelineOverview.Samples=class{constructor(){this.sizes=[];this.ids=[];this.timestamps=[];this.max=[];this.totalTime=30000;}};Profiler.HeapTimelineOverview.OverviewCalculator=class{_updateBoundaries(chart){this._minimumBoundaries=0;this._maximumBoundaries=chart._profileSamples.totalTime;this._xScaleFactor=chart._overviewContainer.clientWidth/this._maximumBoundaries;}
computePosition(time){return(time-this._minimumBoundaries)*this._xScaleFactor;}
formatValue(value,precision){return Number.secondsToString(value/1000,!!precision);}
maximumBoundary(){return this._maximumBoundaries;}
minimumBoundary(){return this._minimumBoundaries;}
zeroTime(){return this._minimumBoundaries;}
boundarySpan(){return this._maximumBoundaries-this._minimumBoundaries;}};;Profiler.IsolateSelector=class extends UI.VBox{constructor(){super(false);this._items=new UI.ListModel();this._list=new UI.ListControl(this._items,this,UI.ListMode.NonViewport);this.contentElement.appendChild(this._list.element);this._itemByIsolate=new Map();this._totalElement=createElementWithClass('div','profile-memory-usage-item hbox');this._totalValueDiv=this._totalElement.createChild('div','profile-memory-usage-item-size');this._totalTrendDiv=this._totalElement.createChild('div','profile-memory-usage-item-trend');this._totalElement.createChild('div').textContent=ls`Total JS heap size`;const trendIntervalMinutes=Math.round(SDK.IsolateManager.MemoryTrendWindowMs/60e3);this._totalTrendDiv.title=ls`Total page JS heap size change trend over the last ${trendIntervalMinutes} minutes.`;this._totalValueDiv.title=ls`Total page JS heap size across all VM instances.`;SDK.isolateManager.observeIsolates(this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.NameChanged,this._targetChanged,this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._targetChanged,this);}
wasShown(){SDK.isolateManager.addEventListener(SDK.IsolateManager.Events.MemoryChanged,this._heapStatsChanged,this);}
willHide(){SDK.isolateManager.removeEventListener(SDK.IsolateManager.Events.MemoryChanged,this._heapStatsChanged,this);}
isolateAdded(isolate){const item=new Profiler.IsolateSelector.ListItem(isolate);const index=item.model().target()===SDK.targetManager.mainTarget()?0:this._items.length;this._items.insert(index,item);this._itemByIsolate.set(isolate,item);if(this._items.length===1)
this._list.selectItem(item);this._update();}
isolateChanged(isolate){const item=this._itemByIsolate.get(isolate);item.updateTitle();this._update();}
isolateRemoved(isolate){const item=this._itemByIsolate.get(isolate);this._items.remove(this._items.indexOf(item));this._itemByIsolate.delete(isolate);this._update();}
_targetChanged(event){const target=(event.data);const model=target.model(SDK.RuntimeModel);if(!model)
return;const isolate=SDK.isolateManager.isolateByModel(model);const item=isolate&&this._itemByIsolate.get(isolate);if(item)
item.updateTitle();}
_heapStatsChanged(event){const isolate=(event.data);const listItem=this._itemByIsolate.get(isolate);if(listItem)
listItem.updateStats();this._updateTotal();}
_updateTotal(){let total=0;let trend=0;for(const isolate of SDK.isolateManager.isolates()){total+=isolate.usedHeapSize();trend+=isolate.usedHeapSizeGrowRate();}
this._totalValueDiv.textContent=Number.bytesToString(total);Profiler.IsolateSelector._formatTrendElement(trend,this._totalTrendDiv);}
static _formatTrendElement(trendValueMs,element){const changeRateBytesPerSecond=trendValueMs*1e3;const changeRateThresholdBytesPerSecond=1024;if(Math.abs(changeRateBytesPerSecond)<changeRateThresholdBytesPerSecond)
return;const changeRateText=Number.bytesToString(Math.abs(changeRateBytesPerSecond));const changeText=changeRateBytesPerSecond>0?ls`\u2B06${changeRateText}/s`:ls`\u2B07${changeRateText}/s`;element.classList.toggle('increasing',changeRateBytesPerSecond>0);element.textContent=changeText;}
totalMemoryElement(){return this._totalElement;}
createElementForItem(item){return item.element;}
heightForItem(item){}
isItemSelectable(item){return true;}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('selected');if(toElement)
toElement.classList.add('selected');const model=to&&to.model();UI.context.setFlavor(SDK.HeapProfilerModel,model&&model.heapProfilerModel());UI.context.setFlavor(SDK.CPUProfilerModel,model&&model.target().model(SDK.CPUProfilerModel));}
_update(){this._updateTotal();this._list.invalidateRange(0,this._items.length);}};Profiler.IsolateSelector.ListItem=class{constructor(isolate){this._isolate=isolate;const trendIntervalMinutes=Math.round(SDK.IsolateManager.MemoryTrendWindowMs/60e3);this.element=createElementWithClass('div','profile-memory-usage-item hbox');this._heapDiv=this.element.createChild('div','profile-memory-usage-item-size');this._trendDiv=this.element.createChild('div','profile-memory-usage-item-trend');this._nameDiv=this.element.createChild('div','profile-memory-usage-item-name');this._heapDiv.title=ls`Heap size in use by live JS objects.`;this._trendDiv.title=ls`Heap size change trend over the last ${trendIntervalMinutes} minutes.`;this.updateTitle();}
model(){return this._isolate.runtimeModel();}
updateStats(){this._heapDiv.textContent=Number.bytesToString(this._isolate.usedHeapSize());Profiler.IsolateSelector._formatTrendElement(this._isolate.usedHeapSizeGrowRate(),this._trendDiv);}
updateTitle(){const modelCountByName=new Map();for(const model of this._isolate.models()){const target=model.target();const name=SDK.targetManager.mainTarget()!==target?target.name():'';const parsedURL=new Common.ParsedURL(target.inspectedURL());const domain=parsedURL.isValid?parsedURL.domain():'';const title=target.decorateLabel(domain&&name?`${domain}: ${name}`:name||domain||ls`(empty)`);modelCountByName.set(title,(modelCountByName.get(title)||0)+1);}
this._nameDiv.removeChildren();for(const[name,count]of modelCountByName){const title=count>1?`${name} (${count})`:name;this._nameDiv.appendChild(UI.html`<div title="${title}">${title}</div>`);}}};;Profiler.LiveHeapProfileView=class extends UI.VBox{constructor(){super(true);this._gridNodeByUrl=new Map();this.registerRequiredCSS('profiler/liveHeapProfile.css');const columns=[{id:'size',title:ls`JS Heap`,width:'72px',fixedWidth:true,sortable:true,align:DataGrid.DataGrid.Align.Right,sort:DataGrid.DataGrid.Order.Descending},{id:'isolates',title:ls`VMs`,width:'40px',fixedWidth:true,align:DataGrid.DataGrid.Align.Right},{id:'url',title:ls`Script URL`,fixedWidth:false,sortable:true}];this._dataGrid=new DataGrid.SortableDataGrid(columns);this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);this._dataGrid.element.classList.add('flex-auto');this._dataGrid.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.OpenedNode,this._revealSourceForSelectedNode,this);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortingChanged,this);this._dataGrid.asWidget().show(this.contentElement);this._currentPollId=0;}
wasShown(){this._poll();}
willHide(){++this._currentPollId;}
async _poll(){const pollId=this._currentPollId;do{const isolates=Array.from(SDK.isolateManager.isolates());const profiles=await Promise.all(isolates.map(isolate=>isolate.heapProfilerModel()&&isolate.heapProfilerModel().getSamplingProfile()));if(this._currentPollId!==pollId)
return;this._update(isolates,profiles);await new Promise(r=>setTimeout(r,3000));}while(this._currentPollId===pollId);}
_update(isolates,profiles){const dataByUrl=new Map();profiles.forEach((profile,index)=>{if(profile)
processNodeTree(isolates[index],'',profile.head);});const rootNode=this._dataGrid.rootNode();const exisitingNodes=new Set();for(const pair of dataByUrl){const url=(pair[0]);const size=(pair[1].size);const isolateCount=(pair[1].isolates.size);if(!url){console.info(`Node with empty URL: ${size} bytes`);continue;}
let node=this._gridNodeByUrl.get(url);if(node){node.updateNode(size,isolateCount);}else{node=new Profiler.LiveHeapProfileView.GridNode(url,size,isolateCount);this._gridNodeByUrl.set(url,node);rootNode.appendChild(node);}
exisitingNodes.add(node);}
for(const node of rootNode.children.slice()){if(!exisitingNodes.has(node))
node.remove();this._gridNodeByUrl.delete(node);}
this._sortingChanged();function processNodeTree(isolate,parentUrl,node){const url=node.callFrame.url||parentUrl||systemNodeName(node)||anonymousScriptName(node);node.children.forEach(processNodeTree.bind(null,isolate,url));if(!node.selfSize)
return;let data=dataByUrl.get(url);if(!data){data={size:0,isolates:new Set()};dataByUrl.set(url,data);}
data.size+=node.selfSize;data.isolates.add(isolate);}
function systemNodeName(node){const name=node.callFrame.functionName;return name.startsWith('(')&&name!=='(root)'?name:'';}
function anonymousScriptName(node){return Number(node.callFrame.scriptId)?Common.UIString('(Anonymous Script %s)',node.callFrame.scriptId):'';}}
_onKeyDown(event){if(!isEnterKey(event))
return;event.consume(true);this._revealSourceForSelectedNode();}
_revealSourceForSelectedNode(){const node=this._dataGrid.selectedNode;if(!node||!node._url)
return;const sourceCode=Workspace.workspace.uiSourceCodeForURL(node._url);if(sourceCode)
Common.Revealer.reveal(sourceCode);}
_sortingChanged(){const columnId=this._dataGrid.sortColumnId();if(!columnId)
return;const sortByUrl=(a,b)=>b._url.localeCompare(a._url);const sortBySize=(a,b)=>b._size-a._size;const sortFunction=columnId==='url'?sortByUrl:sortBySize;this._dataGrid.sortNodes(sortFunction,this._dataGrid.isSortOrderAscending());}};Profiler.LiveHeapProfileView.GridNode=class extends DataGrid.SortableDataGridNode{constructor(url,size,isolateCount){super();this._url=url;this._size=size;this._isolateCount=isolateCount;}
updateNode(size,isolateCount){if(this._size===size&&this._isolateCount===isolateCount)
return;this._size=size;this._isolateCount=isolateCount;this.refresh();}
createCell(columnId){const cell=this.createTD(columnId);switch(columnId){case'url':cell.textContent=this._url;break;case'size':cell.textContent=Number.withThousandsSeparator(Math.round(this._size/1e3));cell.createChild('span','size-units').textContent=ls`KB`;break;case'isolates':cell.textContent=this._isolateCount;break;}
return cell;}};;Profiler.ProfileLauncherView=class extends UI.VBox{constructor(profilesPanel){super();this.registerRequiredCSS('profiler/profileLauncherView.css');this._panel=profilesPanel;this.element.classList.add('profile-launcher-view');this._contentElement=this.element.createChild('div','profile-launcher-view-content vbox');const profileTypeSelectorElement=this._contentElement.createChild('div','vbox');this._selectedProfileTypeSetting=Common.settings.createSetting('selectedProfileType','CPU');this._profileTypeHeaderElement=profileTypeSelectorElement.createChild('h1');this._profileTypeSelectorForm=profileTypeSelectorElement.createChild('form');const isolateSelectorElement=this._contentElement.createChild('div','vbox profile-isolate-selector-block');isolateSelectorElement.createChild('h1').textContent=ls`Select JavaScript VM instance`;const isolateSelector=new Profiler.IsolateSelector();isolateSelector.show(isolateSelectorElement.createChild('div','vbox profile-launcher-target-list'));isolateSelectorElement.appendChild(isolateSelector.totalMemoryElement());const buttonsDiv=this._contentElement.createChild('div','hbox profile-launcher-buttons');this._controlButton=UI.createTextButton('',this._controlButtonClicked.bind(this),'',true);this._loadButton=UI.createTextButton(ls`Load`,this._loadButtonClicked.bind(this),'');buttonsDiv.appendChild(this._controlButton);buttonsDiv.appendChild(this._loadButton);this._recordButtonEnabled=true;this._typeIdToOptionElement=new Map();}
_loadButtonClicked(){this._panel.showLoadFromFileDialog();}
_updateControls(){if(this._isEnabled&&this._recordButtonEnabled)
this._controlButton.removeAttribute('disabled');else
this._controlButton.setAttribute('disabled','');this._controlButton.title=this._recordButtonEnabled?'':UI.anotherProfilerActiveLabel();if(this._isInstantProfile){this._controlButton.classList.remove('running');this._controlButton.classList.add('primary-button');this._controlButton.textContent=Common.UIString('Take snapshot');}else if(this._isProfiling){this._controlButton.classList.add('running');this._controlButton.classList.remove('primary-button');this._controlButton.textContent=Common.UIString('Stop');}else{this._controlButton.classList.remove('running');this._controlButton.classList.add('primary-button');this._controlButton.textContent=Common.UIString('Start');}
for(const item of this._typeIdToOptionElement.values())
item.disabled=!!this._isProfiling;}
profileStarted(){this._isProfiling=true;this._updateControls();}
profileFinished(){this._isProfiling=false;this._updateControls();}
updateProfileType(profileType,recordButtonEnabled){this._isInstantProfile=profileType.isInstantProfile();this._recordButtonEnabled=recordButtonEnabled;this._isEnabled=profileType.isEnabled();this._updateControls();}
addProfileType(profileType){const labelElement=UI.createRadioLabel('profile-type',profileType.name);this._profileTypeSelectorForm.appendChild(labelElement);const optionElement=labelElement.radioElement;this._typeIdToOptionElement.set(profileType.id,optionElement);optionElement._profileType=profileType;optionElement.style.hidden=true;optionElement.addEventListener('change',this._profileTypeChanged.bind(this,profileType),false);const descriptionElement=this._profileTypeSelectorForm.createChild('p');descriptionElement.textContent=profileType.description;const customContent=profileType.customContent();if(customContent)
this._profileTypeSelectorForm.createChild('p').appendChild(customContent);if(this._typeIdToOptionElement.size>1)
this._profileTypeHeaderElement.textContent=ls`Select profiling type`;else
this._profileTypeHeaderElement.textContent=profileType.name;}
restoreSelectedProfileType(){let typeId=this._selectedProfileTypeSetting.get();if(!this._typeIdToOptionElement.has(typeId))
typeId=this._typeIdToOptionElement.keys().next().value;this._typeIdToOptionElement.get(typeId).checked=true;const type=this._typeIdToOptionElement.get(typeId)._profileType;this.dispatchEventToListeners(Profiler.ProfileLauncherView.Events.ProfileTypeSelected,type);}
_controlButtonClicked(){this._panel.toggleRecord();}
_profileTypeChanged(profileType){this.dispatchEventToListeners(Profiler.ProfileLauncherView.Events.ProfileTypeSelected,profileType);this._isInstantProfile=profileType.isInstantProfile();this._isEnabled=profileType.isEnabled();this._updateControls();this._selectedProfileTypeSetting.set(profileType.id);}};Profiler.ProfileLauncherView.Events={ProfileTypeSelected:Symbol('ProfileTypeSelected')};;Profiler.ProfileTypeRegistry=class{constructor(){this.cpuProfileType=new Profiler.CPUProfileType();this.heapSnapshotProfileType=new Profiler.HeapSnapshotProfileType();this.samplingHeapProfileType=new Profiler.SamplingHeapProfileType();this.samplingNativeHeapProfileType=new Profiler.SamplingNativeHeapProfileType();this.samplingNativeHeapSnapshotBrowserType=new Profiler.SamplingNativeHeapSnapshotBrowserType();this.samplingNativeHeapSnapshotRendererType=new Profiler.SamplingNativeHeapSnapshotRendererType();this.trackingHeapSnapshotProfileType=new Profiler.TrackingHeapSnapshotProfileType();}};Profiler.ProfileTypeRegistry.instance=new Profiler.ProfileTypeRegistry();;Runtime.cachedResources["profiler/heapProfiler.css"]="/*\n * Copyright (C) 2009 Google Inc. All rights reserved.\n * Copyright (C) 2010 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.heap-snapshot-view {\n overflow: hidden;\n}\n\n.heap-snapshot-view .data-grid {\n border: none;\n}\n\n.heap-snapshot-view .data-grid tr:empty {\n height: 16px;\n visibility: hidden;\n}\n\n.heap-snapshot-view .data-grid span.percent-column {\n width: 35px !important;\n}\n\n.heap-snapshot-view .object-value-object,\n.object-value-node {\n display: inline;\n position: static;\n}\n\n.heap-snapshot-view .object-value-string {\n white-space: nowrap;\n}\n\n.heap-snapshot-view td.object-column .objects-count {\n margin-left: 10px;\n font-size: 11px;\n color: grey;\n}\n\n.heap-snapshot-view tr:not(.selected) .object-value-id {\n color: grey;\n}\n\n.heap-snapshot-view .data-grid {\n flex: auto;\n}\n\n.profile-view .heap-tracking-overview {\n flex: 0 0 80px;\n height: 80px;\n}\n\n.heap-snapshot-view .retaining-paths-view {\n overflow: hidden;\n}\n\n.heap-snapshot-view .heap-snapshot-view-resizer {\n background-image: url(Images/toolbarResizerVertical.png);\n background-color: #eee;\n border-bottom: 1px solid rgb(179, 179, 179);\n background-repeat: no-repeat;\n background-position: right center, center;\n flex: 0 0 21px;\n}\n\n.heap-snapshot-view .heap-snapshot-view-resizer .title > span {\n display: inline-block;\n padding-top: 3px;\n verti
static highlightRanges(element,query,caseInsensitive){if(!query)
return false;function rangesForMatch(text,query){const opcodes=Diff.Diff.charDiff(query,text);let offset=0;const ranges=[];for(let i=0;i<opcodes.length;++i){const opcode=opcodes[i];if(opcode[0]===Diff.Diff.Operation.Equal)
ranges.push(new TextUtils.SourceRange(offset,opcode[1].length));else if(opcode[0]!==Diff.Diff.Operation.Insert)
return null;offset+=opcode[1].length;}
return ranges;}
const text=element.textContent;let ranges=rangesForMatch(text,query);if(!ranges||caseInsensitive)
ranges=rangesForMatch(text.toUpperCase(),query.toUpperCase());if(ranges){UI.highlightRangesWithStyleClass(element,ranges,'highlight');return true;}
return false;}
setPlaceholder(placeholder){this._prompt.setPlaceholder(placeholder);}
showAsDialog(){this._dialog=new UI.Dialog();this._dialog.setMaxContentSize(new UI.Size(504,340));this._dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.SetExactWidthMaxHeight);this._dialog.setContentPosition(null,22);this.show(this._dialog.contentElement);this._dialog.show();}
setPrefix(prefix){this._prefix=prefix;}
setProvider(provider){if(provider===this._provider)
return;if(this._provider)
this._provider.detach();this._clearTimers();this._provider=provider;if(this.isShowing())
this._attachProvider();}
_attachProvider(){this._items.replaceAll([]);this._list.invalidateItemHeight();if(this._provider){this._provider.setRefreshCallback(this._itemsLoaded.bind(this,this._provider));this._provider.attach();}
this._itemsLoaded(this._provider);}
_value(){return this._prompt.text().trim();}
_cleanValue(){return this._value().substring(this._prefix.length);}
wasShown(){this._attachProvider();}
willHide(){if(this._provider)
this._provider.detach();this._clearTimers();}
_clearTimers(){clearTimeout(this._filterTimer);clearTimeout(this._scoringTimer);clearTimeout(this._loadTimeout);delete this._filterTimer;delete this._scoringTimer;delete this._loadTimeout;delete this._refreshListWithCurrentResult;}
_onEnter(event){if(!this._provider)
return;const selectedIndexInProvider=this._provider.itemCount()?this._list.selectedItem():null;this._selectItem(selectedIndexInProvider);if(this._dialog)
this._dialog.hide();}
_itemsLoaded(provider){if(this._loadTimeout||provider!==this._provider)
return;this._loadTimeout=setTimeout(this._updateAfterItemsLoaded.bind(this),0);}
_updateAfterItemsLoaded(){delete this._loadTimeout;this._filterItems();}
createElementForItem(item){const itemElement=createElement('div');itemElement.className='filtered-list-widget-item '+(this._provider.renderAsTwoRows()?'two-rows':'one-row');const titleElement=itemElement.createChild('div','filtered-list-widget-title');const subtitleElement=itemElement.createChild('div','filtered-list-widget-subtitle');subtitleElement.textContent='\u200B';this._provider.renderItem(item,this._cleanValue(),titleElement,subtitleElement);return itemElement;}
heightForItem(item){return 0;}
isItemSelectable(item){return true;}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('selected');if(toElement){toElement.classList.add('selected');UI.ARIAUtils.alert(toElement.textContent,toElement);}}
_onClick(event){const item=this._list.itemForNode((event.target));if(item===null)
return;event.consume(true);this._selectItem(item);if(this._dialog)
this._dialog.hide();}
setQuery(query){this._prompt.focus();this._prompt.setText(query);this._queryChanged();this._prompt.autoCompleteSoon(true);this._scheduleFilter();}
_tabKeyPressed(){const userEnteredText=this._prompt.text();let completion;for(let i=this._promptHistory.length-1;i>=0;i--){if(this._promptHistory[i]!==userEnteredText&&this._promptHistory[i].startsWith(userEnteredText)){completion=this._promptHistory[i];break;}}
if(!completion)
return false;this._prompt.focus();this._prompt.setText(completion);this._prompt.setDOMSelection(userEnteredText.length,completion.length);this._scheduleFilter();return true;}
_itemsFilteredForTest(){}
_filterItems(){delete this._filterTimer;if(this._scoringTimer){clearTimeout(this._scoringTimer);delete this._scoringTimer;if(this._refreshListWithCurrentResult)
this._refreshListWithCurrentResult();}
if(!this._provider){this._bottomElementsContainer.classList.toggle('hidden',true);this._itemsFilteredForTest();return;}
this._bottomElementsContainer.classList.toggle('hidden',false);this._progressBarElement.style.transform='scaleX(0)';this._progressBarElement.classList.remove('filtered-widget-progress-fade');this._progressBarElement.classList.remove('hidden');const query=this._provider.rewriteQuery(this._cleanValue());this._query=query;const filterRegex=query?String.filterRegex(query):null;const filteredItems=[];const bestScores=[];const bestItems=[];const bestItemsToCollect=100;let minBestScore=0;const overflowItems=[];const scoreStartTime=window.performance.now();const maxWorkItems=Number.constrain(10,500,(this._provider.itemCount()/10)|0);scoreItems.call(this,0);function compareIntegers(a,b){return b-a;}
function scoreItems(fromIndex){delete this._scoringTimer;let workDone=0;let i;for(i=fromIndex;i<this._provider.itemCount()&&workDone<maxWorkItems;++i){if(filterRegex&&!filterRegex.test(this._provider.itemKeyAt(i)))
continue;const score=this._provider.itemScoreAt(i,query);if(query)
workDone++;if(score>minBestScore||bestScores.length<bestItemsToCollect){const index=bestScores.upperBound(score,compareIntegers);bestScores.splice(index,0,score);bestItems.splice(index,0,i);if(bestScores.length>bestItemsToCollect){overflowItems.push(bestItems.peekLast());bestScores.length=bestItemsToCollect;bestItems.length=bestItemsToCollect;}
minBestScore=bestScores.peekLast();}else{filteredItems.push(i);}}
this._refreshListWithCurrentResult=this._refreshList.bind(this,bestItems,overflowItems,filteredItems);if(i<this._provider.itemCount()){this._scoringTimer=setTimeout(scoreItems.bind(this,i),0);if(window.performance.now()-scoreStartTime>50)
this._progressBarElement.style.transform='scaleX('+i/this._provider.itemCount()+')';return;}
if(window.performance.now()-scoreStartTime>100){this._progressBarElement.style.transform='scaleX(1)';this._progressBarElement.classList.add('filtered-widget-progress-fade');}else{this._progressBarElement.classList.add('hidden');}
this._refreshListWithCurrentResult();}}
_refreshList(bestItems,overflowItems,filteredItems){delete this._refreshListWithCurrentResult;filteredItems=[].concat(bestItems,overflowItems,filteredItems);this._updateNotFoundMessage(!!filteredItems.length);const oldHeight=this._list.element.offsetHeight;this._items.replaceAll(filteredItems);if(filteredItems.length)
this._list.selectItem(filteredItems[0]);if(this._list.element.offsetHeight!==oldHeight)
this._list.viewportResized();this._itemsFilteredForTest();}
_updateNotFoundMessage(hasItems){this._list.element.classList.toggle('hidden',!hasItems);this._notFoundElement.classList.toggle('hidden',hasItems);if(!hasItems)
this._notFoundElement.textContent=this._provider.notFoundText(this._cleanValue());}
_onInput(){this._queryChanged();this._scheduleFilter();}
_queryChanged(){if(this._queryChangedCallback)
this._queryChangedCallback(this._value());if(this._provider)
this._provider.queryChanged(this._cleanValue());}
_onKeyDown(event){let handled=false;switch(event.key){case'Enter':this._onEnter(event);return;case'Tab':handled=this._tabKeyPressed();break;case'ArrowUp':handled=this._list.selectPreviousItem(true,false);break;case'ArrowDown':handled=this._list.selectNextItem(true,false);break;case'PageUp':handled=this._list.selectItemPreviousPage(false);break;case'PageDown':handled=this._list.selectItemNextPage(false);break;}
if(handled)
event.consume(true);}
_scheduleFilter(){if(this._filterTimer)
return;this._filterTimer=setTimeout(this._filterItems.bind(this),0);}
_selectItem(itemIndex){this._promptHistory.push(this._value());if(this._promptHistory.length>100)
this._promptHistory.shift();this._provider.selectItem(itemIndex,this._cleanValue());}};QuickOpen.FilteredListWidget.Provider=class{setRefreshCallback(refreshCallback){this._refreshCallback=refreshCallback;}
attach(){}
itemCount(){return 0;}
itemKeyAt(itemIndex){return'';}
itemScoreAt(itemIndex,query){return 1;}
renderItem(itemIndex,query,titleElement,subtitleElement){}
renderAsTwoRows(){return false;}
selectItem(itemIndex,promptValue){}
refresh(){this._refreshCallback();}
rewriteQuery(query){return query;}
queryChanged(query){}
notFoundText(query){return Common.UIString('No results found');}
detach(){}};;QuickOpen.QuickOpen=class{constructor(){this._prefix=null;this._query='';this._providers=new Map();this._prefixes=[];this._filteredListWidget=null;self.runtime.extensions(QuickOpen.FilteredListWidget.Provider).forEach(this._addProvider.bind(this));this._prefixes.sort((a,b)=>b.length-a.length);}
static show(query){const quickOpen=new this();const filteredListWidget=new QuickOpen.FilteredListWidget(null,this._history,quickOpen._queryChanged.bind(quickOpen));quickOpen._filteredListWidget=filteredListWidget;filteredListWidget.setPlaceholder(Common.UIString('Type \'?\' to see available commands'));filteredListWidget.showAsDialog();filteredListWidget.setQuery(query);}
_addProvider(extension){const prefix=extension.descriptor()['prefix'];this._prefixes.push(prefix);this._providers.set(prefix,(extension.instance.bind(extension)));}
_queryChanged(query){const prefix=this._prefixes.find(prefix=>query.startsWith(prefix));if(typeof prefix!=='string'||this._prefix===prefix)
return;this._prefix=prefix;this._filteredListWidget.setPrefix(prefix);this._filteredListWidget.setProvider(null);this._providers.get(prefix)().then(provider=>{if(this._prefix!==prefix)
return;this._filteredListWidget.setProvider(provider);this._providerLoadedForTest(provider);});}
_providerLoadedForTest(provider){}};QuickOpen.QuickOpen._history=[];QuickOpen.QuickOpen.ShowActionDelegate=class{handleAction(context,actionId){switch(actionId){case'quickOpen.show':QuickOpen.QuickOpen.show('');return true;}
return false;}};;QuickOpen.CommandMenu=class{constructor(){this._commands=[];this._loadCommands();}
static createCommand(category,keys,title,shortcut,executeHandler,availableHandler){const key=keys.replace(/,/g,'\0');return new QuickOpen.CommandMenu.Command(category,title,key,shortcut,executeHandler,availableHandler);}
static createSettingCommand(extension,title,value){const category=extension.descriptor()['category']||'';const tags=extension.descriptor()['tags']||'';const setting=Common.settings.moduleSetting(extension.descriptor()['settingName']);return QuickOpen.CommandMenu.createCommand(category,tags,title,'',setting.set.bind(setting,value),availableHandler);function availableHandler(){return setting.get()!==value;}}
static createActionCommand(action){const shortcut=UI.shortcutRegistry.shortcutTitleForAction(action.id())||'';return QuickOpen.CommandMenu.createCommand(action.category(),action.tags(),action.title(),shortcut,action.execute.bind(action));}
static createRevealViewCommand(extension,category){const viewId=extension.descriptor()['id'];const executeHandler=UI.viewManager.showView.bind(UI.viewManager,viewId);const tags=extension.descriptor()['tags']||'';return QuickOpen.CommandMenu.createCommand(category,tags,Common.UIString('Show %s',extension.title()),'',executeHandler);}
_loadCommands(){const locations=new Map();self.runtime.extensions(UI.ViewLocationResolver).forEach(extension=>{const category=extension.descriptor()['category'];const name=extension.descriptor()['name'];if(category&&name)
locations.set(name,category);});const viewExtensions=self.runtime.extensions('view');for(const extension of viewExtensions){const category=locations.get(extension.descriptor()['location']);if(category)
this._commands.push(QuickOpen.CommandMenu.createRevealViewCommand(extension,category));}
const settingExtensions=self.runtime.extensions('setting');for(const extension of settingExtensions){const options=extension.descriptor()['options'];if(!options||!extension.descriptor()['category'])
continue;for(const pair of options)
this._commands.push(QuickOpen.CommandMenu.createSettingCommand(extension,pair['title'],pair['value']));}}
commands(){return this._commands;}};QuickOpen.CommandMenuProvider=class extends QuickOpen.FilteredListWidget.Provider{constructor(){super();this._commands=[];}
attach(){const allCommands=QuickOpen.commandMenu.commands();const actions=UI.actionRegistry.availableActions();for(const action of actions){if(action.category())
this._commands.push(QuickOpen.CommandMenu.createActionCommand(action));}
for(const command of allCommands){if(command.available())
this._commands.push(command);}
this._commands=this._commands.sort(commandComparator);function commandComparator(left,right){const cats=left.category().compareTo(right.category());return cats?cats:left.title().compareTo(right.title());}}
detach(){this._commands=[];}
itemCount(){return this._commands.length;}
itemKeyAt(itemIndex){return this._commands[itemIndex].key();}
itemScoreAt(itemIndex,query){const command=this._commands[itemIndex];const opcodes=Diff.Diff.charDiff(query.toLowerCase(),command.title().toLowerCase());let score=0;for(let i=0;i<opcodes.length;++i){if(opcodes[i][0]===Diff.Diff.Operation.Equal)
score+=opcodes[i][1].length*opcodes[i][1].length;}
if(command.category().startsWith('Panel'))
score+=2;else if(command.category().startsWith('Drawer'))
score+=1;return score;}
renderItem(itemIndex,query,titleElement,subtitleElement){const command=this._commands[itemIndex];titleElement.removeChildren();const tagElement=titleElement.createChild('span','tag');const index=String.hashCode(command.category())%QuickOpen.CommandMenuProvider.MaterialPaletteColors.length;tagElement.style.backgroundColor=QuickOpen.CommandMenuProvider.MaterialPaletteColors[index];tagElement.textContent=command.category();titleElement.createTextChild(command.title());QuickOpen.FilteredListWidget.highlightRanges(titleElement,query,true);subtitleElement.textContent=command.shortcut();}
selectItem(itemIndex,promptValue){if(itemIndex===null)
return;this._commands[itemIndex].execute();Host.userMetrics.actionTaken(Host.UserMetrics.Action.SelectCommandFromCommandMenu);}
notFoundText(){return Common.UIString('No commands found');}};QuickOpen.CommandMenuProvider.MaterialPaletteColors=['#F44336','#E91E63','#9C27B0','#673AB7','#3F51B5','#03A9F4','#00BCD4','#009688','#4CAF50','#8BC34A','#CDDC39','#FFC107','#FF9800','#FF5722','#795548','#9E9E9E','#607D8B'];QuickOpen.CommandMenu.Command=class{constructor(category,title,key,shortcut,executeHandler,availableHandler){this._category=category;this._title=title;this._key=category+'\0'+title+'\0'+key;this._shortcut=shortcut;this._executeHandler=executeHandler;this._availableHandler=availableHandler;}
category(){return this._category;}
title(){return this._title;}
key(){return this._key;}
shortcut(){return this._shortcut;}
available(){return this._availableHandler?this._availableHandler():true;}
execute(){this._executeHandler();}};QuickOpen.commandMenu=new QuickOpen.CommandMenu();QuickOpen.CommandMenu.ShowActionDelegate=class{handleAction(context,actionId){InspectorFrontendHost.bringToFront();QuickOpen.QuickOpen.show('>');return true;}};;QuickOpen.HelpQuickOpen=class extends QuickOpen.FilteredListWidget.Provider{constructor(){super();this._providers=[];self.runtime.extensions(QuickOpen.FilteredListWidget.Provider).forEach(this._addProvider.bind(this));}
_addProvider(extension){if(extension.descriptor()['title'])
this._providers.push({prefix:extension.descriptor()['prefix'],title:extension.descriptor()['title']});}
itemCount(){return this._providers.length;}
itemKeyAt(itemIndex){return this._providers[itemIndex].prefix;}
itemScoreAt(itemIndex,query){return-this._providers[itemIndex].prefix.length;}
renderItem(itemIndex,query,titleElement,subtitleElement){const provider=this._providers[itemIndex];const prefixElement=titleElement.createChild('span','monospace');prefixElement.textContent=(provider.prefix||'\u2026')+' ';titleElement.createTextChild(provider.title);}
selectItem(itemIndex,promptValue){if(itemIndex!==null)
QuickOpen.QuickOpen.show(this._providers[itemIndex].prefix);}
renderAsTwoRows(){return false;}};;Runtime.cachedResources["quick_open/filteredListWidget.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.filtered-list-widget {\n display: flex;\n flex-direction: column;\n flex: auto;\n}\n\n.filtered-list-widget-prompt-element {\n flex: 0 0 34px;\n border: 0;\n margin: 0;\n padding: 0 6px;\n z-index: 1;\n font-size: inherit;\n}\n\n.filtered-list-widget-input {\n white-space: pre;\n height: 18px;\n margin-top: 12px;\n overflow: hidden;\n flex: auto;\n}\n\n.filtered-list-widget-progress {\n flex: none;\n background: rgba(0, 0, 0, 0.2);\n height: 2px;\n}\n\n.filtered-list-widget-progress-bar {\n background-color: #2196F3;\n height: 2px;\n width: 100%;\n transform: scaleX(0);\n transform-origin: top left;\n opacity: 1;\n transition: none;\n}\n\n.filtered-widget-progress-fade {\n opacity: 0;\n transition: opacity 500ms;\n}\n\n.filtered-list-widget > div.container {\n flex: auto;\n overflow-y: auto;\n background: #fbfbfb;\n}\n\n.filtered-list-widget-item {\n padding: 4px 6px;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n color: rgb(95, 95, 95);\n}\n\n.filtered-list-widget-item.selected {\n background-color: #f0f0f0;\n}\n\n:host-context(.-theme-with-dark-background) .filtered-list-widget-item.selected {\n background-color: #333333;\n}\n\n.filtered-list-widget-item span.highlight {\n color: #222;\n font-weight: bold;\n}\n\n.filtered-list-widget-item .filtered-list-widget-title {\n flex: auto;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.filtered-list-widget-item .filtered-list-widget-subtitle {\n flex: none;\n overflow: hidden;\n text-overflow: ellipsis;\n color: rgb(155, 155, 155);\n display: flex;\n}\n\n.filtered-list-widget-item .filtered-list-widget-subtitle .first-part {\n flex-shrink: 1000;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.filtered-list-widget-item.one-row {\n display: flex;\n}\n\n.filtered-list-widget-item.two-rows {\n border-bottom: 1px solid rgb(235, 235, 235);\n}\n\n.tag {\n color: white;\n padding: 1px 3px;\n margin-right: 5px;\n border-radius: 2px;\n line-height: 18px;\n}\n\n.filtered-list-widget-item .tag .highlight {\n color: white;\n}\n\n.not-found-text {\n height: 34px;\n line-height: 34px;\n padding-left: 4px;\n font-style: italic;\n color: #888;\n background: #fbfbfb;\n}\n\n/*# sourceURL=quick_open/filteredListWidget.css */";Resources.ApplicationCacheModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerApplicationCacheDispatcher(new Resources.ApplicationCacheDispatcher(this));this._agent=target.applicationCacheAgent();this._agent.enable();const resourceTreeModel=target.model(SDK.ResourceTreeModel);resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameNavigated,this._frameNavigated,this);resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameDetached,this._frameDetached,this);this._statuses={};this._manifestURLsByFrame={};this._mainFrameNavigated();this._onLine=true;}
async _frameNavigated(event){const frame=(event.data);if(frame.isMainFrame()){this._mainFrameNavigated();return;}
const frameId=frame.id;const manifestURL=await this._agent.getManifestForFrame(frameId);if(manifestURL!==null&&!manifestURL)
this._frameManifestRemoved(frameId);}
_frameDetached(event){const frame=(event.data);this._frameManifestRemoved(frame.id);}
reset(){this._statuses={};this._manifestURLsByFrame={};this.dispatchEventToListeners(Resources.ApplicationCacheModel.Events.FrameManifestsReset);}
async _mainFrameNavigated(){const framesWithManifests=await this._agent.getFramesWithManifests();for(const frame of framesWithManifests||[])
this._frameManifestUpdated(frame.frameId,frame.manifestURL,frame.status);}
_frameManifestUpdated(frameId,manifestURL,status){if(status===Resources.ApplicationCacheModel.UNCACHED){this._frameManifestRemoved(frameId);return;}
if(!manifestURL)
return;if(this._manifestURLsByFrame[frameId]&&manifestURL!==this._manifestURLsByFrame[frameId])
this._frameManifestRemoved(frameId);const statusChanged=this._statuses[frameId]!==status;this._statuses[frameId]=status;if(!this._manifestURLsByFrame[frameId]){this._manifestURLsByFrame[frameId]=manifestURL;this.dispatchEventToListeners(Resources.ApplicationCacheModel.Events.FrameManifestAdded,frameId);}
if(statusChanged)
this.dispatchEventToListeners(Resources.ApplicationCacheModel.Events.FrameManifestStatusUpdated,frameId);}
_frameManifestRemoved(frameId){if(!this._manifestURLsByFrame[frameId])
return;delete this._manifestURLsByFrame[frameId];delete this._statuses[frameId];this.dispatchEventToListeners(Resources.ApplicationCacheModel.Events.FrameManifestRemoved,frameId);}
frameManifestURL(frameId){return this._manifestURLsByFrame[frameId]||'';}
frameManifestStatus(frameId){return this._statuses[frameId]||Resources.ApplicationCacheModel.UNCACHED;}
get onLine(){return this._onLine;}
_statusUpdated(frameId,manifestURL,status){this._frameManifestUpdated(frameId,manifestURL,status);}
requestApplicationCache(frameId){return this._agent.getApplicationCacheForFrame(frameId);}
_networkStateUpdated(isNowOnline){this._onLine=isNowOnline;this.dispatchEventToListeners(Resources.ApplicationCacheModel.Events.NetworkStateChanged,isNowOnline);}};SDK.SDKModel.register(Resources.ApplicationCacheModel,SDK.Target.Capability.DOM,false);Resources.ApplicationCacheModel.Events={FrameManifestStatusUpdated:Symbol('FrameManifestStatusUpdated'),FrameManifestAdded:Symbol('FrameManifestAdded'),FrameManifestRemoved:Symbol('FrameManifestRemoved'),FrameManifestsReset:Symbol('FrameManifestsReset'),NetworkStateChanged:Symbol('NetworkStateChanged')};Resources.ApplicationCacheDispatcher=class{constructor(applicationCacheModel){this._applicationCacheModel=applicationCacheModel;}
applicationCacheStatusUpdated(frameId,manifestURL,status){this._applicationCacheModel._statusUpdated(frameId,manifestURL,status);}
networkStateUpdated(isNowOnline){this._applicationCacheModel._networkStateUpdated(isNowOnline);}};Resources.ApplicationCacheModel.UNCACHED=0;Resources.ApplicationCacheModel.IDLE=1;Resources.ApplicationCacheModel.CHECKING=2;Resources.ApplicationCacheModel.DOWNLOADING=3;Resources.ApplicationCacheModel.UPDATEREADY=4;Resources.ApplicationCacheModel.OBSOLETE=5;;Resources.AppManifestView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('resources/appManifestView.css');this._emptyView=new UI.EmptyWidget(Common.UIString('No manifest detected'));this._emptyView.appendLink('https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/?utm_source=devtools');this._emptyView.show(this.contentElement);this._emptyView.hideWidget();this._reportView=new UI.ReportView(Common.UIString('App Manifest'));this._reportView.show(this.contentElement);this._reportView.hideWidget();this._errorsSection=this._reportView.appendSection(Common.UIString('Errors and warnings'));this._installabilitySection=this._reportView.appendSection(Common.UIString('Installability'));this._identitySection=this._reportView.appendSection(Common.UIString('Identity'));this._presentationSection=this._reportView.appendSection(Common.UIString('Presentation'));this._iconsSection=this._reportView.appendSection(Common.UIString('Icons'));this._nameField=this._identitySection.appendField(Common.UIString('Name'));this._shortNameField=this._identitySection.appendField(Common.UIString('Short name'));this._startURLField=this._presentationSection.appendField(Common.UIString('Start URL'));const themeColorField=this._presentationSection.appendField(Common.UIString('Theme color'));this._themeColorSwatch=InlineEditor.ColorSwatch.create();themeColorField.appendChild(this._themeColorSwatch);const backgroundColorField=this._presentationSection.appendField(Common.UIString('Background color'));this._backgroundColorSwatch=InlineEditor.ColorSwatch.create();backgroundColorField.appendChild(this._backgroundColorSwatch);this._orientationField=this._presentationSection.appendField(Common.UIString('Orientation'));this._displayField=this._presentationSection.appendField(Common.UIString('Display'));this._throttler=new Common.Throttler(1000);SDK.targetManager.observeTargets(this);}
targetAdded(target){if(this._target)
return;this._target=target;this._resourceTreeModel=target.model(SDK.ResourceTreeModel);this._serviceWorkerManager=target.model(SDK.ServiceWorkerManager);if(!this._resourceTreeModel||!this._serviceWorkerManager)
return;this._updateManifest(true);this._registeredListeners=[this._resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,this._updateManifest.bind(this,true)),this._serviceWorkerManager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationUpdated,this._updateManifest.bind(this,false))];}
targetRemoved(target){if(this._target!==target)
return;if(!this._resourceTreeModel||!this._serviceWorkerManager)
return;delete this._resourceTreeModel;delete this._serviceWorkerManager;Common.EventTarget.removeEventListeners(this._registeredListeners);}
async _updateManifest(immediately){const{url,data,errors}=await this._resourceTreeModel.fetchAppManifest();const installabilityErrors=await this._resourceTreeModel.getInstallabilityErrors();this._throttler.schedule(()=>this._renderManifest(url,data,errors,installabilityErrors),immediately);}
async _renderManifest(url,data,errors,installabilityErrors){if(!data&&!errors.length){this._emptyView.showWidget();this._reportView.hideWidget();return;}
this._emptyView.hideWidget();this._reportView.showWidget();this._reportView.setURL(Components.Linkifier.linkifyURL(url));this._errorsSection.clearContent();this._errorsSection.element.classList.toggle('hidden',!errors.length);for(const error of errors){this._errorsSection.appendRow().appendChild(UI.createIconLabel(error.message,error.critical?'smallicon-error':'smallicon-warning'));}
if(!data)
return;if(data.charCodeAt(0)===0xFEFF)
data=data.slice(1);const parsedManifest=JSON.parse(data);this._nameField.textContent=stringProperty('name');this._shortNameField.textContent=stringProperty('short_name');this._startURLField.removeChildren();const startURL=stringProperty('start_url');if(startURL){const completeURL=(Common.ParsedURL.completeURL(url,startURL));this._startURLField.appendChild(Components.Linkifier.linkifyURL(completeURL,{text:startURL}));}
this._themeColorSwatch.classList.toggle('hidden',!stringProperty('theme_color'));const themeColor=Common.Color.parse(stringProperty('theme_color')||'white')||Common.Color.parse('white');this._themeColorSwatch.setColor((themeColor));this._backgroundColorSwatch.classList.toggle('hidden',!stringProperty('background_color'));const backgroundColor=Common.Color.parse(stringProperty('background_color')||'white')||Common.Color.parse('white');this._backgroundColorSwatch.setColor((backgroundColor));this._orientationField.textContent=stringProperty('orientation');const displayType=stringProperty('display');this._displayField.textContent=displayType;const icons=parsedManifest['icons']||[];this._iconsSection.clearContent();for(const icon of icons){const title=(icon['sizes']||'')+'\n'+(icon['type']||'');const field=this._iconsSection.appendField(title);const image=await this._loadImage(Common.ParsedURL.completeURL(url,icon['src']));if(image)
field.appendChild(image);}
this._installabilitySection.clearContent();this._installabilitySection.element.classList.toggle('hidden',!installabilityErrors.length);for(const error of installabilityErrors)
this._installabilitySection.appendRow().appendChild(UI.createIconLabel(error,'smallicon-warning'));function stringProperty(name){const value=parsedManifest[name];if(typeof value!=='string')
return'';return value;}}
async _loadImage(url){const image=createElement('img');image.style.maxWidth='200px';image.style.maxHeight='200px';const result=new Promise((f,r)=>{image.onload=f;image.onerror=r;});image.src=url;try{await result;return image;}catch(e){}
return null;}};;Resources.ApplicationCacheItemsView=class extends UI.SimpleView{constructor(model,frameId){super(Common.UIString('AppCache'));this._model=model;this.element.classList.add('storage-view','table');this._deleteButton=new UI.ToolbarButton(Common.UIString('Delete'),'largeicon-delete');this._deleteButton.setVisible(false);this._deleteButton.addEventListener(UI.ToolbarButton.Events.Click,this._deleteButtonClicked,this);this._connectivityIcon=createElement('span','dt-icon-label');this._connectivityIcon.style.margin='0 2px 0 5px';this._statusIcon=createElement('span','dt-icon-label');this._statusIcon.style.margin='0 2px 0 5px';this._frameId=frameId;this._emptyWidget=new UI.EmptyWidget(Common.UIString('No Application Cache information available.'));this._emptyWidget.show(this.element);this._markDirty();const status=this._model.frameManifestStatus(frameId);this.updateStatus(status);this.updateNetworkState(this._model.onLine);this._deleteButton.element.style.display='none';}
syncToolbarItems(){return[this._deleteButton,new UI.ToolbarItem(this._connectivityIcon),new UI.ToolbarSeparator(),new UI.ToolbarItem(this._statusIcon)];}
wasShown(){this._maybeUpdate();}
willHide(){this._deleteButton.setVisible(false);}
_maybeUpdate(){if(!this.isShowing()||!this._viewDirty)
return;this._update();this._viewDirty=false;}
_markDirty(){this._viewDirty=true;}
updateStatus(status){const oldStatus=this._status;this._status=status;const statusInformation={};statusInformation[Resources.ApplicationCacheModel.UNCACHED]={type:'smallicon-red-ball',text:'UNCACHED'};statusInformation[Resources.ApplicationCacheModel.IDLE]={type:'smallicon-green-ball',text:'IDLE'};statusInformation[Resources.ApplicationCacheModel.CHECKING]={type:'smallicon-orange-ball',text:'CHECKING'};statusInformation[Resources.ApplicationCacheModel.DOWNLOADING]={type:'smallicon-orange-ball',text:'DOWNLOADING'};statusInformation[Resources.ApplicationCacheModel.UPDATEREADY]={type:'smallicon-green-ball',text:'UPDATEREADY'};statusInformation[Resources.ApplicationCacheModel.OBSOLETE]={type:'smallicon-red-ball',text:'OBSOLETE'};const info=statusInformation[status]||statusInformation[Resources.ApplicationCacheModel.UNCACHED];this._statusIcon.type=info.type;this._statusIcon.textContent=info.text;if(this.isShowing()&&this._status===Resources.ApplicationCacheModel.IDLE&&(oldStatus===Resources.ApplicationCacheModel.UPDATEREADY||!this._resources))
this._markDirty();this._maybeUpdate();}
updateNetworkState(isNowOnline){if(isNowOnline){this._connectivityIcon.type='smallicon-green-ball';this._connectivityIcon.textContent=Common.UIString('Online');}else{this._connectivityIcon.type='smallicon-red-ball';this._connectivityIcon.textContent=Common.UIString('Offline');}}
async _update(){const applicationCache=await this._model.requestApplicationCache(this._frameId);if(!applicationCache||!applicationCache.manifestURL){delete this._manifest;delete this._creationTime;delete this._updateTime;delete this._size;delete this._resources;this._emptyWidget.show(this.element);this._deleteButton.setVisible(false);if(this._dataGrid)
this._dataGrid.element.classList.add('hidden');return;}
this._manifest=applicationCache.manifestURL;this._creationTime=applicationCache.creationTime;this._updateTime=applicationCache.updateTime;this._size=applicationCache.size;this._resources=applicationCache.resources;if(!this._dataGrid)
this._createDataGrid();this._populateDataGrid();this._dataGrid.autoSizeColumns(20,80);this._dataGrid.element.classList.remove('hidden');this._emptyWidget.detach();this._deleteButton.setVisible(true);}
_createDataGrid(){const columns=([{id:'resource',title:Common.UIString('Resource'),sort:DataGrid.DataGrid.Order.Ascending,sortable:true},{id:'type',title:Common.UIString('Type'),sortable:true},{id:'size',title:Common.UIString('Size'),align:DataGrid.DataGrid.Align.Right,sortable:true}]);this._dataGrid=new DataGrid.DataGrid(columns);this._dataGrid.setStriped(true);this._dataGrid.asWidget().show(this.element);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._populateDataGrid,this);}
_populateDataGrid(){const selectedResource=this._dataGrid.selectedNode?this._dataGrid.selectedNode.resource:null;const sortDirection=this._dataGrid.isSortOrderAscending()?1:-1;function numberCompare(field,resource1,resource2){return sortDirection*(resource1[field]-resource2[field]);}
function localeCompare(field,resource1,resource2){return sortDirection*(resource1[field]+'').localeCompare(resource2[field]+'');}
let comparator;switch(this._dataGrid.sortColumnId()){case'resource':comparator=localeCompare.bind(null,'url');break;case'type':comparator=localeCompare.bind(null,'type');break;case'size':comparator=numberCompare.bind(null,'size');break;default:localeCompare.bind(null,'resource');}
this._resources.sort(comparator);this._dataGrid.rootNode().removeChildren();let nodeToSelect;for(let i=0;i<this._resources.length;++i){const data={};const resource=this._resources[i];data.resource=resource.url;data.type=resource.type;data.size=Number.bytesToString(resource.size);const node=new DataGrid.DataGridNode(data);node.resource=resource;node.selectable=true;this._dataGrid.rootNode().appendChild(node);if(resource===selectedResource){nodeToSelect=node;nodeToSelect.selected=true;}}
if(!nodeToSelect&&this._dataGrid.rootNode().children.length)
this._dataGrid.rootNode().children[0].selected=true;}
_deleteButtonClicked(event){if(!this._dataGrid||!this._dataGrid.selectedNode)
return;this._deleteCallback(this._dataGrid.selectedNode);}
_deleteCallback(node){}};;Resources.BackgroundServiceModel=class extends SDK.SDKModel{constructor(target){super(target);this._backgroundServiceAgent=target.backgroundServiceAgent();target.registerBackgroundServiceDispatcher(this);this._events=new Map();}
enable(serviceName){this._events.set(serviceName,[]);this._backgroundServiceAgent.startObserving(serviceName);}
setRecording(shouldRecord,serviceName){this._backgroundServiceAgent.setRecording(shouldRecord,serviceName);}
clearEvents(serviceName){this._events.set(serviceName,[]);this._backgroundServiceAgent.clearEvents(serviceName);}
getEvents(serviceName){return this._events.get(serviceName)||[];}
recordingStateChanged(isRecording,serviceName){this.dispatchEventToListeners(Resources.BackgroundServiceModel.Events.RecordingStateChanged,{isRecording,serviceName});}
backgroundServiceEventReceived(backgroundServiceEvent){this._events.get(backgroundServiceEvent.service).push(backgroundServiceEvent);this.dispatchEventToListeners(Resources.BackgroundServiceModel.Events.BackgroundServiceEventReceived,backgroundServiceEvent);}};SDK.SDKModel.register(Resources.BackgroundServiceModel,SDK.Target.Capability.Browser,false);Resources.BackgroundServiceModel.Events={RecordingStateChanged:Symbol('RecordingStateChanged'),BackgroundServiceEventReceived:Symbol('BackgroundServiceEventReceived'),};Resources.BackgroundServiceModel.RecordingState;;Resources.BackgroundServiceView=class extends UI.VBox{static getUIString(serviceName){switch(serviceName){case Protocol.BackgroundService.ServiceName.BackgroundFetch:return ls`Background Fetch`;case Protocol.BackgroundService.ServiceName.BackgroundSync:return ls`Background Sync`;case Protocol.BackgroundService.ServiceName.PushMessaging:return ls`Push Messaging`;case Protocol.BackgroundService.ServiceName.Notifications:return ls`Notifications`;default:return'';}}
constructor(serviceName,model){super(true);this.registerRequiredCSS('resources/backgroundServiceView.css');this.registerRequiredCSS('ui/emptyWidget.css');this._serviceName=serviceName;this._model=model;this._model.addEventListener(Resources.BackgroundServiceModel.Events.RecordingStateChanged,this._onRecordingStateChanged,this);this._model.addEventListener(Resources.BackgroundServiceModel.Events.BackgroundServiceEventReceived,this._onEventReceived,this);this._model.enable(this._serviceName);this._serviceWorkerManager=this._model.target().model(SDK.ServiceWorkerManager);this._securityOriginManager=this._model.target().model(SDK.SecurityOriginManager);this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.MainSecurityOriginChanged,()=>this._onOriginChanged());this._recordAction=(UI.actionRegistry.action('background-service.toggle-recording'));this._recordButton=null;this._originCheckbox=null;this._saveButton=null;this._toolbar=new UI.Toolbar('background-service-toolbar',this.contentElement);this._setupToolbar();this._splitWidget=new UI.SplitWidget(false,true);this._splitWidget.show(this.contentElement);this._dataGrid=this._createDataGrid();this._previewPanel=new UI.VBox();this._selectedEventNode=null;this._preview=null;this._splitWidget.setMainWidget(this._dataGrid.asWidget());this._splitWidget.setSidebarWidget(this._previewPanel);this._showPreview(null);}
async _setupToolbar(){this._recordButton=UI.Toolbar.createActionButton(this._recordAction);this._toolbar.appendToolbarItem(this._recordButton);const clearButton=new UI.ToolbarButton(ls`Clear`,'largeicon-clear');clearButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._clearEvents());this._toolbar.appendToolbarItem(clearButton);this._toolbar.appendSeparator();this._saveButton=new UI.ToolbarButton(ls`Save events`,'largeicon-download');this._saveButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._saveToFile());this._saveButton.setEnabled(false);this._toolbar.appendToolbarItem(this._saveButton);this._toolbar.appendSeparator();this._originCheckbox=new UI.ToolbarCheckbox(ls`Show events from other domains`,undefined,()=>this._refreshView());this._toolbar.appendToolbarItem(this._originCheckbox);}
_refreshView(){this._clearView();const events=this._model.getEvents(this._serviceName).filter(event=>this._acceptEvent(event));for(const event of events)
this._addEvent(event);}
_clearView(){this._selectedEventNode=null;this._dataGrid.rootNode().removeChildren();this._saveButton.setEnabled(false);this._showPreview(null);}
_toggleRecording(){this._model.setRecording(!this._recordButton.toggled(),this._serviceName);}
_clearEvents(){this._model.clearEvents(this._serviceName);this._clearView();}
_onRecordingStateChanged(event){const state=(event.data);if(state.serviceName!==this._serviceName)
return;if(state.isRecording===this._recordButton.toggled())
return;this._recordButton.setToggled(state.isRecording);this._showPreview(this._selectedEventNode);}
_onEventReceived(event){const serviceEvent=(event.data);if(!this._acceptEvent(serviceEvent))
return;this._addEvent(serviceEvent);}
_onOriginChanged(){if(this._originCheckbox.checked())
return;this._refreshView();}
_addEvent(serviceEvent){const data=this._createEventData(serviceEvent);const dataNode=new Resources.BackgroundServiceView.EventDataNode(data,serviceEvent.eventMetadata);this._dataGrid.rootNode().appendChild(dataNode);if(this._dataGrid.rootNode().children.length===1){this._saveButton.setEnabled(true);this._showPreview(this._selectedEventNode);}}
_createDataGrid(){const columns=([{id:'id',title:ls`#`,weight:1},{id:'timestamp',title:ls`Timestamp`,weight:8},{id:'eventName',title:ls`Event`,weight:10},{id:'origin',title:ls`Origin`,weight:10},{id:'swScope',title:ls`SW Scope`,weight:2},{id:'instanceId',title:ls`Instance ID`,weight:10},]);const dataGrid=new DataGrid.DataGrid(columns);dataGrid.setStriped(true);dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,event=>this._showPreview((event.data)));return dataGrid;}
_createEventData(serviceEvent){let swScope='';const registration=this._serviceWorkerManager.registrations().get(serviceEvent.serviceWorkerRegistrationId);if(registration)
swScope=registration.scopeURL.substr(registration.securityOrigin.length);return{id:this._dataGrid.rootNode().children.length+1,timestamp:UI.formatTimestamp(serviceEvent.timestamp*1000,true),origin:serviceEvent.origin,swScope,eventName:serviceEvent.eventName,instanceId:serviceEvent.instanceId,};}
_acceptEvent(event){if(event.service!==this._serviceName)
return false;if(this._originCheckbox.checked())
return true;const origin=event.origin.substr(0,event.origin.length-1);return this._securityOriginManager.securityOrigins().includes(origin);}
_showPreview(dataNode){if(this._selectedEventNode&&this._selectedEventNode===dataNode)
return;this._selectedEventNode=dataNode;if(this._preview)
this._preview.detach();if(this._selectedEventNode){this._preview=this._selectedEventNode.createPreview();}else if(this._dataGrid.rootNode().children.length){this._preview=new UI.EmptyWidget(ls`Select an entry to view metadata`);}else if(this._recordButton.toggled()){this._preview=new UI.EmptyWidget(ls`Recording ${Resources.BackgroundServiceView.getUIString(this._serviceName)} activity...`);}else{this._preview=new UI.VBox();this._preview.contentElement.classList.add('empty-view-scroller');const centered=this._preview.contentElement.createChild('div','empty-view');const landingRecordButton=UI.Toolbar.createActionButton(this._recordAction);const recordKey=createElementWithClass('b','background-service-shortcut');recordKey.textContent=UI.shortcutRegistry.shortcutDescriptorsForAction('background-service.toggle-recording')[0].name;centered.createChild('h2').appendChild(UI.formatLocalized('Click the record button %s or hit %s to start recording.',[UI.createInlineButton(landingRecordButton),recordKey]));}
this._preview.show(this._previewPanel.contentElement);}
async _saveToFile(){const fileName=`${this._serviceName}-${new Date().toISO8601Compact()}.json`;const stream=new Bindings.FileOutputStream();const accepted=await stream.open(fileName);if(!accepted)
return;const events=this._model.getEvents(this._serviceName).filter(event=>this._acceptEvent(event));await stream.write(JSON.stringify(events,undefined,2));stream.close();}};Resources.BackgroundServiceView.EventData;Resources.BackgroundServiceView.EventDataNode=class extends DataGrid.DataGridNode{constructor(data,eventMetadata){super(data);this._eventMetadata=eventMetadata.sort((m1,m2)=>m1.key.compareTo(m2.key));}
createPreview(){const preview=new UI.VBox();preview.element.classList.add('background-service-metadata');for(const entry of this._eventMetadata){const div=createElementWithClass('div','background-service-metadata-entry');div.createChild('div','background-service-metadata-name').textContent=entry.key+': ';div.createChild('div','background-service-metadata-value source-code').textContent=entry.value;preview.element.appendChild(div);}
if(!preview.element.children.length){const div=createElementWithClass('div','background-service-metadata-entry');div.createChild('div','background-service-metadata-name').textContent=ls`No metadata for this event`;preview.element.appendChild(div);}
return preview;}};Resources.BackgroundServiceView.ActionDelegate=class{handleAction(context,actionId){const view=context.flavor(Resources.BackgroundServiceView);switch(actionId){case'background-service.toggle-recording':view._toggleRecording();return true;}
return false;}};;Resources.ClearStorageView=class extends UI.ThrottledWidget{constructor(){super(true,1000);const types=Protocol.Storage.StorageType;this._pieColors=new Map([[types.Appcache,'rgb(110, 161, 226)'],[types.Cache_storage,'rgb(229, 113, 113)'],[types.Cookies,'rgb(239, 196, 87)'],[types.Indexeddb,'rgb(155, 127, 230)'],[types.Local_storage,'rgb(116, 178, 102)'],[types.Service_workers,'rgb(255, 167, 36)'],[types.Websql,'rgb(203, 220, 56)'],]);this._reportView=new UI.ReportView(Common.UIString('Clear storage'));this._reportView.registerRequiredCSS('resources/clearStorageView.css');this._reportView.element.classList.add('clear-storage-header');this._reportView.show(this.contentElement);this._target=null;this._securityOrigin=null;this._settings=new Map();for(const type of Resources.ClearStorageView.AllStorageTypes)
this._settings.set(type,Common.settings.createSetting('clear-storage-'+type,true));const quota=this._reportView.appendSection(Common.UIString('Usage'));this._quotaRow=quota.appendSelectableRow();const learnMoreRow=quota.appendRow();const learnMore=UI.XLink.create('https://developers.google.com/web/tools/chrome-devtools/progressive-web-apps#opaque-responses',ls`Learn more`);learnMoreRow.appendChild(learnMore);this._quotaUsage=null;this._pieChart=new PerfUI.PieChart({chartName:ls`Storage Usage`,size:110,formatter:Number.bytesToString,showLegend:true});const usageBreakdownRow=quota.appendRow();usageBreakdownRow.classList.add('usage-breakdown-row');usageBreakdownRow.appendChild(this._pieChart.element);const clearButtonSection=this._reportView.appendSection('','clear-storage-button').appendRow();this._clearButton=UI.createTextButton(ls`Clear site data`,this._clear.bind(this));clearButtonSection.appendChild(this._clearButton);const application=this._reportView.appendSection(Common.UIString('Application'));this._appendItem(application,Common.UIString('Unregister service workers'),'service_workers');application.markFieldListAsGroup();const storage=this._reportView.appendSection(Common.UIString('Storage'));this._appendItem(storage,Common.UIString('Local and session storage'),'local_storage');this._appendItem(storage,Common.UIString('IndexedDB'),'indexeddb');this._appendItem(storage,Common.UIString('Web SQL'),'websql');this._appendItem(storage,Common.UIString('Cookies'),'cookies');storage.markFieldListAsGroup();const caches=this._reportView.appendSection(Common.UIString('Cache'));this._appendItem(caches,Common.UIString('Cache storage'),'cache_storage');this._appendItem(caches,Common.UIString('Application cache'),'appcache');caches.markFieldListAsGroup();SDK.targetManager.observeTargets(this);}
_appendItem(section,title,settingName){const row=section.appendRow();row.appendChild(UI.SettingsUI.createSettingCheckbox(title,this._settings.get(settingName),true));}
targetAdded(target){if(this._target)
return;this._target=target;const securityOriginManager=target.model(SDK.SecurityOriginManager);this._updateOrigin(securityOriginManager.mainSecurityOrigin(),securityOriginManager.unreachableMainSecurityOrigin());securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.MainSecurityOriginChanged,this._originChanged,this);}
targetRemoved(target){if(this._target!==target)
return;const securityOriginManager=target.model(SDK.SecurityOriginManager);securityOriginManager.removeEventListener(SDK.SecurityOriginManager.Events.MainSecurityOriginChanged,this._originChanged,this);}
_originChanged(event){const mainOrigin=(event.data.mainSecurityOrigin);const unreachableMainOrigin=(event.data.unreachableMainSecurityOrigin);this._updateOrigin(mainOrigin,unreachableMainOrigin);}
_updateOrigin(mainOrigin,unreachableMainOrigin){if(unreachableMainOrigin){this._securityOrigin=unreachableMainOrigin;this._reportView.setSubtitle(ls`${unreachableMainOrigin} (failed to load)`);}else{this._securityOrigin=mainOrigin;this._reportView.setSubtitle(mainOrigin);}
this.doUpdate();}
_clear(){if(!this._securityOrigin)
return;const selectedStorageTypes=[];for(const type of this._settings.keys()){if(this._settings.get(type).get())
selectedStorageTypes.push(type);}
if(this._target)
Resources.ClearStorageView.clear(this._target,this._securityOrigin,selectedStorageTypes);this._clearButton.disabled=true;const label=this._clearButton.textContent;this._clearButton.textContent=Common.UIString('Clearing...');setTimeout(()=>{this._clearButton.disabled=false;this._clearButton.textContent=label;},500);}
static clear(target,securityOrigin,selectedStorageTypes){target.storageAgent().clearDataForOrigin(securityOrigin,selectedStorageTypes.join(','));const set=new Set(selectedStorageTypes);const hasAll=set.has(Protocol.Storage.StorageType.All);if(set.has(Protocol.Storage.StorageType.Cookies)||hasAll){const cookieModel=target.model(SDK.CookieModel);if(cookieModel)
cookieModel.clear();}
if(set.has(Protocol.Storage.StorageType.Indexeddb)||hasAll){for(const target of SDK.targetManager.targets()){const indexedDBModel=target.model(Resources.IndexedDBModel);if(indexedDBModel)
indexedDBModel.clearForOrigin(securityOrigin);}}
if(set.has(Protocol.Storage.StorageType.Local_storage)||hasAll){const storageModel=target.model(Resources.DOMStorageModel);if(storageModel)
storageModel.clearForOrigin(securityOrigin);}
if(set.has(Protocol.Storage.StorageType.Websql)||hasAll){const databaseModel=target.model(Resources.DatabaseModel);if(databaseModel){databaseModel.disable();databaseModel.enable();}}
if(set.has(Protocol.Storage.StorageType.Cache_storage)||hasAll){const target=SDK.targetManager.mainTarget();const model=target&&target.model(SDK.ServiceWorkerCacheModel);if(model)
model.clearForOrigin(securityOrigin);}
if(set.has(Protocol.Storage.StorageType.Appcache)||hasAll){const appcacheModel=target.model(Resources.ApplicationCacheModel);if(appcacheModel)
appcacheModel.reset();}}
async doUpdate(){if(!this._securityOrigin)
return;const securityOrigin=(this._securityOrigin);const response=await this._target.storageAgent().invoke_getUsageAndQuota({origin:securityOrigin});if(response[Protocol.Error]){this._quotaRow.textContent='';this._resetPieChart(0);return;}
this._quotaRow.textContent=Common.UIString('%s used out of %s storage quota.\u00a0',Number.bytesToString(response.usage),Number.bytesToString(response.quota));if(response.quota<125829120){this._quotaRow.title=ls`Storage quota is limited in Incognito mode`;this._quotaRow.appendChild(UI.Icon.create('smallicon-info'));}
if(!this._quotaUsage||this._quotaUsage!==response.usage){this._quotaUsage=response.usage;this._resetPieChart(response.usage);for(const usageForType of response.usageBreakdown.sort((a,b)=>b.usage-a.usage)){const value=usageForType.usage;if(!value)
continue;const title=this._getStorageTypeName(usageForType.storageType);const color=this._pieColors.get(usageForType.storageType)||'#ccc';this._pieChart.addSlice(value,color,title);}}
this._usageUpdatedForTest(response.usage,response.quota,response.usageBreakdown);this.update();}
_resetPieChart(total){this._pieChart.setTotal(total);}
_getStorageTypeName(type){switch(type){case Protocol.Storage.StorageType.File_systems:return Common.UIString('File System');case Protocol.Storage.StorageType.Websql:return Common.UIString('Web SQL');case Protocol.Storage.StorageType.Appcache:return Common.UIString('Application Cache');case Protocol.Storage.StorageType.Indexeddb:return Common.UIString('IndexedDB');case Protocol.Storage.StorageType.Cache_storage:return Common.UIString('Cache Storage');case Protocol.Storage.StorageType.Service_workers:return Common.UIString('Service Workers');default:return Common.UIString('Other');}}
_usageUpdatedForTest(usage,quota,usageBreakdown){}};Resources.ClearStorageView.AllStorageTypes=[Protocol.Storage.StorageType.Appcache,Protocol.Storage.StorageType.Cache_storage,Protocol.Storage.StorageType.Cookies,Protocol.Storage.StorageType.Indexeddb,Protocol.Storage.StorageType.Local_storage,Protocol.Storage.StorageType.Service_workers,Protocol.Storage.StorageType.Websql];Resources.ClearStorageView.ActionDelegate=class{handleAction(context,actionId){switch(actionId){case'resources.clear':return this._handleClear();}
return false;}
_handleClear(){const target=SDK.targetManager.mainTarget();if(!target)
return false;const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel)
return false;const securityOrigin=resourceTreeModel.getMainSecurityOrigin();if(!securityOrigin)
return false;Resources.ClearStorageView.clear(target,securityOrigin,Resources.ClearStorageView.AllStorageTypes);return true;}};;Resources.StorageItemsView=class extends UI.VBox{constructor(title,filterName){super(false);this._filterRegex=null;this._refreshButton=this._addButton(Common.UIString('Refresh'),'largeicon-refresh',this.refreshItems);this._mainToolbar=new UI.Toolbar('top-resources-toolbar',this.element);this._filterItem=new UI.ToolbarInput(Common.UIString('Filter'),0.4);this._filterItem.addEventListener(UI.ToolbarInput.Event.TextChanged,this._filterChanged,this);const toolbarSeparator=new UI.ToolbarSeparator();this._deleteAllButton=this._addButton(Common.UIString('Clear All'),'largeicon-clear',this.deleteAllItems);this._deleteSelectedButton=this._addButton(Common.UIString('Delete Selected'),'largeicon-delete',this.deleteSelectedItem);const toolbarItems=[this._refreshButton,this._filterItem,toolbarSeparator,this._deleteAllButton,this._deleteSelectedButton];for(const item of toolbarItems)
this._mainToolbar.appendToolbarItem(item);this.element.addEventListener('contextmenu',this._showContextMenu.bind(this),true);}
_addButton(label,glyph,callback){const button=new UI.ToolbarButton(label,glyph);button.addEventListener(UI.ToolbarButton.Events.Click,callback,this);return button;}
_showContextMenu(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Refresh'),this.refreshItems.bind(this));contextMenu.show();}
_filterChanged(event){const text=(event.data);this._filterRegex=text?new RegExp(text.escapeForRegExp(),'i'):null;this.refreshItems();}
filter(items,keyFunction){if(!this._filterRegex)
return items;return items.filter(item=>this._filterRegex.test(keyFunction(item)));}
wasShown(){this.refreshItems();}
setCanDeleteAll(enabled){this._deleteAllButton.setEnabled(enabled);}
setCanDeleteSelected(enabled){this._deleteSelectedButton.setEnabled(enabled);}
setCanRefresh(enabled){this._refreshButton.setEnabled(enabled);}
setCanFilter(enabled){this._filterItem.setEnabled(enabled);}
deleteAllItems(){}
deleteSelectedItem(){}
refreshItems(){}};;Resources.CookieItemsView=class extends Resources.StorageItemsView{constructor(model,cookieDomain){super(Common.UIString('Cookies'),'cookiesPanel');this.element.classList.add('storage-view');this._model=model;this._cookieDomain=cookieDomain;this._totalSize=0;this._cookiesTable=null;this._refreshThrottler=new Common.Throttler(300);this._eventDescriptors=[];this.setCookiesDomain(model,cookieDomain);}
setCookiesDomain(model,domain){this._model=model;this._cookieDomain=domain;this.refreshItems();Common.EventTarget.removeEventListeners(this._eventDescriptors);const networkManager=model.target().model(SDK.NetworkManager);this._eventDescriptors=[networkManager.addEventListener(SDK.NetworkManager.Events.ResponseReceived,this._onResponseReceived,this)];}
_saveCookie(newCookie,oldCookie){if(!this._model)
return Promise.resolve(false);if(oldCookie&&(newCookie.name()!==oldCookie.name()||newCookie.url()!==oldCookie.url()))
this._model.deleteCookie(oldCookie);return this._model.saveCookie(newCookie);}
_deleteCookie(cookie,callback){this._model.deleteCookie(cookie,callback);}
_updateWithCookies(allCookies){this._totalSize=allCookies.reduce((size,cookie)=>size+cookie.size(),0);if(!this._cookiesTable){this._cookiesTable=new CookieTable.CookiesTable(this._saveCookie.bind(this),this.refreshItems.bind(this),()=>this.setCanDeleteSelected(!!this._cookiesTable.selectedCookie()),this._deleteCookie.bind(this));}
const parsedURL=this._cookieDomain.asParsedURL();const host=parsedURL?parsedURL.host:'';this._cookiesTable.setCookieDomain(host);const shownCookies=this.filter(allCookies,cookie=>`${cookie.name()} ${cookie.value()} ${cookie.domain()}`);this._cookiesTable.setCookies(shownCookies);this._cookiesTable.show(this.element);this.setCanFilter(true);this.setCanDeleteAll(true);this.setCanDeleteSelected(!!this._cookiesTable.selectedCookie());}
deleteAllItems(){this._model.clear(this._cookieDomain,()=>this.refreshItems());}
deleteSelectedItem(){const selectedCookie=this._cookiesTable.selectedCookie();if(selectedCookie)
this._model.deleteCookie(selectedCookie,()=>this.refreshItems());}
refreshItems(){this._model.getCookiesForDomain(this._cookieDomain).then(this._updateWithCookies.bind(this));}
_onResponseReceived(){this._refreshThrottler.schedule(()=>Promise.resolve(this.refreshItems()));}};;Resources.Database=class{constructor(model,id,domain,name,version){this._model=model;this._id=id;this._domain=domain;this._name=name;this._version=version;}
get id(){return this._id;}
get name(){return this._name;}
set name(x){this._name=x;}
get version(){return this._version;}
set version(x){this._version=x;}
get domain(){return this._domain;}
set domain(x){this._domain=x;}
async tableNames(){const names=await this._model._agent.getDatabaseTableNames(this._id)||[];return names.sort();}
async executeSql(query,onSuccess,onError){const response=await this._model._agent.invoke_executeSQL({'databaseId':this._id,'query':query});const error=response[Protocol.Error];if(error){onError(error);return;}
const sqlError=response.sqlError;if(!sqlError){onSuccess(response.columnNames,response.values);return;}
let message;if(sqlError.message)
message=sqlError.message;else if(sqlError.code===2)
message=Common.UIString('Database no longer has expected version.');else
message=Common.UIString('An unexpected error %s occurred.',sqlError.code);onError(message);}};Resources.DatabaseModel=class extends SDK.SDKModel{constructor(target){super(target);this._databases=[];this._agent=target.databaseAgent();this.target().registerDatabaseDispatcher(new Resources.DatabaseDispatcher(this));}
enable(){if(this._enabled)
return;this._agent.enable();this._enabled=true;}
disable(){if(!this._enabled)
return;this._enabled=false;this._databases=[];this._agent.disable();this.dispatchEventToListeners(Resources.DatabaseModel.Events.DatabasesRemoved);}
databases(){const result=[];for(const database of this._databases)
result.push(database);return result;}
_addDatabase(database){this._databases.push(database);this.dispatchEventToListeners(Resources.DatabaseModel.Events.DatabaseAdded,database);}};SDK.SDKModel.register(Resources.DatabaseModel,SDK.Target.Capability.None,false);Resources.DatabaseModel.Events={DatabaseAdded:Symbol('DatabaseAdded'),DatabasesRemoved:Symbol('DatabasesRemoved'),};Resources.DatabaseDispatcher=class{constructor(model){this._model=model;}
addDatabase(payload){this._model._addDatabase(new Resources.Database(this._model,payload.id,payload.domain,payload.name,payload.version));}};Resources.DatabaseModel._symbol=Symbol('DatabaseModel');;Resources.DOMStorage=class extends Common.Object{constructor(model,securityOrigin,isLocalStorage){super();this._model=model;this._securityOrigin=securityOrigin;this._isLocalStorage=isLocalStorage;}
static storageId(securityOrigin,isLocalStorage){return{securityOrigin:securityOrigin,isLocalStorage:isLocalStorage};}
get id(){return Resources.DOMStorage.storageId(this._securityOrigin,this._isLocalStorage);}
get securityOrigin(){return this._securityOrigin;}
get isLocalStorage(){return this._isLocalStorage;}
getItems(){return this._model._agent.getDOMStorageItems(this.id);}
setItem(key,value){this._model._agent.setDOMStorageItem(this.id,key,value);}
removeItem(key){this._model._agent.removeDOMStorageItem(this.id,key);}
clear(){this._model._agent.clear(this.id);}};Resources.DOMStorage.Events={DOMStorageItemsCleared:Symbol('DOMStorageItemsCleared'),DOMStorageItemRemoved:Symbol('DOMStorageItemRemoved'),DOMStorageItemAdded:Symbol('DOMStorageItemAdded'),DOMStorageItemUpdated:Symbol('DOMStorageItemUpdated')};Resources.DOMStorageModel=class extends SDK.SDKModel{constructor(target){super(target);this._securityOriginManager=target.model(SDK.SecurityOriginManager);this._storages={};this._agent=target.domstorageAgent();}
enable(){if(this._enabled)
return;this.target().registerDOMStorageDispatcher(new Resources.DOMStorageDispatcher(this));this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);for(const securityOrigin of this._securityOriginManager.securityOrigins())
this._addOrigin(securityOrigin);this._agent.enable();this._enabled=true;}
clearForOrigin(origin){if(!this._enabled)
return;for(const isLocal of[true,false]){const key=this._storageKey(origin,isLocal);const storage=this._storages[key];storage.clear();}
this._removeOrigin(origin);this._addOrigin(origin);}
_securityOriginAdded(event){this._addOrigin((event.data));}
_addOrigin(securityOrigin){const parsed=new Common.ParsedURL(securityOrigin);if(!parsed.isValid||parsed.scheme==='data'||parsed.scheme==='about'||parsed.scheme==='javascript')
return;for(const isLocal of[true,false]){const key=this._storageKey(securityOrigin,isLocal);console.assert(!this._storages[key]);const storage=new Resources.DOMStorage(this,securityOrigin,isLocal);this._storages[key]=storage;this.dispatchEventToListeners(Resources.DOMStorageModel.Events.DOMStorageAdded,storage);}}
_securityOriginRemoved(event){this._removeOrigin((event.data));}
_removeOrigin(securityOrigin){for(const isLocal of[true,false]){const key=this._storageKey(securityOrigin,isLocal);const storage=this._storages[key];if(!storage)
continue;delete this._storages[key];this.dispatchEventToListeners(Resources.DOMStorageModel.Events.DOMStorageRemoved,storage);}}
_storageKey(securityOrigin,isLocalStorage){return JSON.stringify(Resources.DOMStorage.storageId(securityOrigin,isLocalStorage));}
_domStorageItemsCleared(storageId){const domStorage=this.storageForId(storageId);if(!domStorage)
return;const eventData={};domStorage.dispatchEventToListeners(Resources.DOMStorage.Events.DOMStorageItemsCleared,eventData);}
_domStorageItemRemoved(storageId,key){const domStorage=this.storageForId(storageId);if(!domStorage)
return;const eventData={key:key};domStorage.dispatchEventToListeners(Resources.DOMStorage.Events.DOMStorageItemRemoved,eventData);}
_domStorageItemAdded(storageId,key,value){const domStorage=this.storageForId(storageId);if(!domStorage)
return;const eventData={key:key,value:value};domStorage.dispatchEventToListeners(Resources.DOMStorage.Events.DOMStorageItemAdded,eventData);}
_domStorageItemUpdated(storageId,key,oldValue,value){const domStorage=this.storageForId(storageId);if(!domStorage)
return;const eventData={key:key,oldValue:oldValue,value:value};domStorage.dispatchEventToListeners(Resources.DOMStorage.Events.DOMStorageItemUpdated,eventData);}
storageForId(storageId){return this._storages[JSON.stringify(storageId)];}
storages(){const result=[];for(const id in this._storages)
result.push(this._storages[id]);return result;}};SDK.SDKModel.register(Resources.DOMStorageModel,SDK.Target.Capability.DOM,false);Resources.DOMStorageModel.Events={DOMStorageAdded:Symbol('DOMStorageAdded'),DOMStorageRemoved:Symbol('DOMStorageRemoved')};Resources.DOMStorageDispatcher=class{constructor(model){this._model=model;}
domStorageItemsCleared(storageId){this._model._domStorageItemsCleared(storageId);}
domStorageItemRemoved(storageId,key){this._model._domStorageItemRemoved(storageId,key);}
domStorageItemAdded(storageId,key,value){this._model._domStorageItemAdded(storageId,key,value);}
domStorageItemUpdated(storageId,key,oldValue,value){this._model._domStorageItemUpdated(storageId,key,oldValue,value);}};Resources.DOMStorageModel._symbol=Symbol('DomStorage');;Resources.DOMStorageItemsView=class extends Resources.StorageItemsView{constructor(domStorage){super(Common.UIString('DOM Storage'),'domStoragePanel');this._domStorage=domStorage;this.element.classList.add('storage-view','table');const columns=([{id:'key',title:Common.UIString('Key'),sortable:false,editable:true,longText:true,weight:50},{id:'value',title:Common.UIString('Value'),sortable:false,editable:true,longText:true,weight:50}]);this._dataGrid=new DataGrid.DataGrid(columns,this._editingCallback.bind(this),this._deleteCallback.bind(this));this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,event=>this._previewEntry((event.data)));this._dataGrid.addEventListener(DataGrid.DataGrid.Events.DeselectedNode,event=>this._previewEntry(null));this._dataGrid.setStriped(true);this._dataGrid.setName('DOMStorageItemsView');this._splitWidget=new UI.SplitWidget(false,false);this._splitWidget.show(this.element);this._splitWidget.setSecondIsSidebar(true);this._previewPanel=new UI.VBox();const resizer=this._previewPanel.element.createChild('div','preview-panel-resizer');const dataGridWidget=this._dataGrid.asWidget();dataGridWidget.setMinimumSize(0,50);this._splitWidget.setMainWidget(dataGridWidget);this._splitWidget.setSidebarWidget(this._previewPanel);this._splitWidget.installResizer(resizer);this._preview=null;this._previewValue=null;this._showPreview(null,null);this._eventListeners=[];this.setStorage(domStorage);}
setStorage(domStorage){Common.EventTarget.removeEventListeners(this._eventListeners);this._domStorage=domStorage;this._eventListeners=[this._domStorage.addEventListener(Resources.DOMStorage.Events.DOMStorageItemsCleared,this._domStorageItemsCleared,this),this._domStorage.addEventListener(Resources.DOMStorage.Events.DOMStorageItemRemoved,this._domStorageItemRemoved,this),this._domStorage.addEventListener(Resources.DOMStorage.Events.DOMStorageItemAdded,this._domStorageItemAdded,this),this._domStorage.addEventListener(Resources.DOMStorage.Events.DOMStorageItemUpdated,this._domStorageItemUpdated,this),];this.refreshItems();}
_domStorageItemsCleared(){if(!this.isShowing()||!this._dataGrid)
return;this._dataGrid.rootNode().removeChildren();this._dataGrid.addCreationNode(false);this.setCanDeleteSelected(false);}
_domStorageItemRemoved(event){if(!this.isShowing()||!this._dataGrid)
return;const storageData=event.data;const rootNode=this._dataGrid.rootNode();const children=rootNode.children;for(let i=0;i<children.length;++i){const childNode=children[i];if(childNode.data.key===storageData.key){rootNode.removeChild(childNode);this.setCanDeleteSelected(children.length>1);return;}}}
_domStorageItemAdded(event){if(!this.isShowing()||!this._dataGrid)
return;const storageData=event.data;const rootNode=this._dataGrid.rootNode();const children=rootNode.children;for(let i=0;i<children.length;++i){if(children[i].data.key===storageData.key)
return;}
const childNode=new DataGrid.DataGridNode({key:storageData.key,value:storageData.value},false);rootNode.insertChild(childNode,children.length-1);}
_domStorageItemUpdated(event){if(!this.isShowing()||!this._dataGrid)
return;const storageData=event.data;const childNode=this._dataGrid.rootNode().children.find(child=>child.data.key===storageData.key);if(!childNode||childNode.data.value===storageData.value)
return;childNode.data.value=storageData.value;childNode.refresh();if(!childNode.selected)
return;this._previewEntry(childNode);this.setCanDeleteSelected(true);}
_showDOMStorageItems(items){const rootNode=this._dataGrid.rootNode();let selectedKey=null;for(const node of rootNode.children){if(!node.selected)
continue;selectedKey=node.data.key;break;}
rootNode.removeChildren();let selectedNode=null;const filteredItems=item=>`${item[0]} ${item[1]}`;for(const item of this.filter(items,filteredItems)){const key=item[0];const value=item[1];const node=new DataGrid.DataGridNode({key:key,value:value},false);node.selectable=true;rootNode.appendChild(node);if(!selectedNode||key===selectedKey)
selectedNode=node;}
if(selectedNode)
selectedNode.selected=true;this._dataGrid.addCreationNode(false);this.setCanDeleteSelected(!!selectedNode);}
deleteSelectedItem(){if(!this._dataGrid||!this._dataGrid.selectedNode)
return;this._deleteCallback(this._dataGrid.selectedNode);}
refreshItems(){this._domStorage.getItems().then(items=>items&&this._showDOMStorageItems(items));}
deleteAllItems(){this._domStorage.clear();this._domStorageItemsCleared();}
_editingCallback(editingNode,columnIdentifier,oldText,newText){const domStorage=this._domStorage;if(columnIdentifier==='key'){if(typeof oldText==='string')
domStorage.removeItem(oldText);domStorage.setItem(newText,editingNode.data.value||'');this._removeDupes(editingNode);}else{domStorage.setItem(editingNode.data.key||'',newText);}}
_removeDupes(masterNode){const rootNode=this._dataGrid.rootNode();const children=rootNode.children;for(let i=children.length-1;i>=0;--i){const childNode=children[i];if((childNode.data.key===masterNode.data.key)&&(masterNode!==childNode))
rootNode.removeChild(childNode);}}
_deleteCallback(node){if(!node||node.isCreationNode)
return;if(this._domStorage)
this._domStorage.removeItem(node.data.key);}
_showPreview(preview,value){if(this._preview&&this._previewValue===value)
return;if(this._preview)
this._preview.detach();if(!preview)
preview=new UI.EmptyWidget(Common.UIString('Select a value to preview'));this._previewValue=value;this._preview=preview;preview.show(this._previewPanel.contentElement);}
async _previewEntry(entry){const value=entry&&entry.data&&entry.data.value;if(!value){this._showPreview(null,value);return;}
const protocol=this._domStorage.isLocalStorage?'localstorage':'sessionstorage';const url=`${protocol}://${entry.key}`;const provider=Common.StaticContentProvider.fromString(url,Common.resourceTypes.XHR,(value));const preview=await SourceFrame.PreviewFactory.createPreview(provider,'text/plain');if(!entry.selected)
return;this._showPreview(preview,value);}};;Resources.DatabaseQueryView=class extends UI.VBox{constructor(database){super();this.database=database;this.element.classList.add('storage-view','query','monospace');this.element.addEventListener('selectstart',this._selectStart.bind(this),false);this._promptContainer=this.element.createChild('div','database-query-prompt-container');this._promptContainer.appendChild(UI.Icon.create('smallicon-text-prompt','prompt-icon'));this._promptElement=this._promptContainer.createChild('div');this._promptElement.className='database-query-prompt';this._promptElement.addEventListener('keydown',this._promptKeyDown.bind(this));this._prompt=new UI.TextPrompt();this._prompt.initialize(this.completions.bind(this),' ');this._proxyElement=this._prompt.attach(this._promptElement);this.element.addEventListener('click',this._messagesClicked.bind(this),true);this.element.tabIndex=0;this.element.addEventListener('focus',this._prompt.focus.bind(this._prompt));}
_messagesClicked(){if(!this._prompt.isCaretInsidePrompt()&&!this.element.hasSelection())
this._prompt.moveCaretToEndOfPrompt();}
async completions(expression,prefix,force){if(!prefix)
return[];prefix=prefix.toLowerCase();const tableNames=await this.database.tableNames();return tableNames.map(name=>name+' ').concat(Resources.DatabaseQueryView._SQL_BUILT_INS).filter(proposal=>proposal.toLowerCase().startsWith(prefix)).map(completion=>({text:completion}));}
_selectStart(event){if(this._selectionTimeout)
clearTimeout(this._selectionTimeout);this._prompt.clearAutocomplete();function moveBackIfOutside(){delete this._selectionTimeout;if(!this._prompt.isCaretInsidePrompt()&&!this.element.hasSelection())
this._prompt.moveCaretToEndOfPrompt();this._prompt.autoCompleteSoon();}
this._selectionTimeout=setTimeout(moveBackIfOutside.bind(this),100);}
_promptKeyDown(event){if(isEnterKey(event)){this._enterKeyPressed(event);return;}}
async _enterKeyPressed(event){event.consume(true);const query=this._prompt.textWithCurrentSuggestion();this._prompt.clearAutocomplete();if(!query.length)
return;this._prompt.setEnabled(false);try{const result=await new Promise((resolve,reject)=>{this.database.executeSql(query,(columnNames,values)=>resolve({columnNames,values}),errorText=>reject(errorText));});this._queryFinished(query,result.columnNames,result.values);}catch(e){this._appendErrorQueryResult(query,e);}
this._prompt.setEnabled(true);this._prompt.setText('');this._prompt.focus();}
_queryFinished(query,columnNames,values){const dataGrid=DataGrid.SortableDataGrid.create(columnNames,values);const trimmedQuery=query.trim();let view=null;if(dataGrid){dataGrid.setStriped(true);dataGrid.renderInline();dataGrid.autoSizeColumns(5);view=dataGrid.asWidget();}
this._appendViewQueryResult(trimmedQuery,view);if(trimmedQuery.match(/^create /i)||trimmedQuery.match(/^drop table /i))
this.dispatchEventToListeners(Resources.DatabaseQueryView.Events.SchemaUpdated,this.database);}
_appendViewQueryResult(query,view){const resultElement=this._appendQueryResult(query);if(view)
view.show(resultElement);else
resultElement.remove();this._promptElement.scrollIntoView(false);}
_appendErrorQueryResult(query,errorText){const resultElement=this._appendQueryResult(query);resultElement.classList.add('error');resultElement.appendChild(UI.Icon.create('smallicon-error','prompt-icon'));resultElement.createTextChild(errorText);this._promptElement.scrollIntoView(false);}
_appendQueryResult(query){const element=createElement('div');element.className='database-user-query';element.appendChild(UI.Icon.create('smallicon-user-command','prompt-icon'));this.element.insertBefore(element,this._promptContainer);const commandTextElement=createElement('span');commandTextElement.className='database-query-text';commandTextElement.textContent=query;element.appendChild(commandTextElement);const resultElement=createElement('div');resultElement.className='database-query-result';element.appendChild(resultElement);return resultElement;}};Resources.DatabaseQueryView.Events={SchemaUpdated:Symbol('SchemaUpdated')};Resources.DatabaseQueryView._SQL_BUILT_INS=['SELECT ','FROM ','WHERE ','LIMIT ','DELETE FROM ','CREATE ','DROP ','TABLE ','INDEX ','UPDATE ','INSERT INTO ','VALUES ('];;Resources.DatabaseTableView=class extends UI.SimpleView{constructor(database,tableName){super(Common.UIString('Database'));this.database=database;this.tableName=tableName;this.element.classList.add('storage-view','table');this._visibleColumnsSetting=Common.settings.createSetting('databaseTableViewVisibleColumns',{});this.refreshButton=new UI.ToolbarButton(Common.UIString('Refresh'),'largeicon-refresh');this.refreshButton.addEventListener(UI.ToolbarButton.Events.Click,this._refreshButtonClicked,this);this._visibleColumnsInput=new UI.ToolbarInput(Common.UIString('Visible columns'),1);this._visibleColumnsInput.addEventListener(UI.ToolbarInput.Event.TextChanged,this._onVisibleColumnsChanged,this);}
wasShown(){this.update();}
syncToolbarItems(){return[this.refreshButton,this._visibleColumnsInput];}
_escapeTableName(tableName){return tableName.replace(/\"/g,'""');}
update(){this.database.executeSql('SELECT rowid, * FROM "'+this._escapeTableName(this.tableName)+'"',this._queryFinished.bind(this),this._queryError.bind(this));}
_queryFinished(columnNames,values){this.detachChildWidgets();this.element.removeChildren();this._dataGrid=DataGrid.SortableDataGrid.create(columnNames,values);this._visibleColumnsInput.setVisible(!!this._dataGrid);if(!this._dataGrid){this._emptyWidget=new UI.EmptyWidget(ls`The "${this.tableName}"\ntable is empty.`);this._emptyWidget.show(this.element);return;}
this._dataGrid.setStriped(true);this._dataGrid.asWidget().show(this.element);this._dataGrid.autoSizeColumns(5);this._columnsMap=new Map();for(let i=1;i<columnNames.length;++i)
this._columnsMap.set(columnNames[i],String(i));this._lastVisibleColumns='';const visibleColumnsText=this._visibleColumnsSetting.get()[this.tableName]||'';this._visibleColumnsInput.setValue(visibleColumnsText);this._onVisibleColumnsChanged();}
_onVisibleColumnsChanged(){if(!this._dataGrid)
return;const text=this._visibleColumnsInput.value();const parts=text.split(/[\s,]+/);const matches=new Set();const columnsVisibility={};columnsVisibility['0']=true;for(let i=0;i<parts.length;++i){const part=parts[i];if(this._columnsMap.has(part)){matches.add(part);columnsVisibility[this._columnsMap.get(part)]=true;}}
const newVisibleColumns=matches.valuesArray().sort().join(', ');if(newVisibleColumns.length===0){for(const v of this._columnsMap.values())
columnsVisibility[v]=true;}
if(newVisibleColumns===this._lastVisibleColumns)
return;const visibleColumnsRegistry=this._visibleColumnsSetting.get();visibleColumnsRegistry[this.tableName]=text;this._visibleColumnsSetting.set(visibleColumnsRegistry);this._dataGrid.setColumnsVisiblity(columnsVisibility);this._lastVisibleColumns=newVisibleColumns;}
_queryError(error){this.detachChildWidgets();this.element.removeChildren();const errorMsgElement=createElement('div');errorMsgElement.className='storage-table-error';errorMsgElement.textContent=ls`An error occurred trying to\nread the "${this.tableName}" table.`;this.element.appendChild(errorMsgElement);}
_refreshButtonClicked(event){this.update();}};;Resources.IndexedDBModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerStorageDispatcher(this);this._securityOriginManager=target.model(SDK.SecurityOriginManager);this._indexedDBAgent=target.indexedDBAgent();this._storageAgent=target.storageAgent();this._databases=new Map();this._databaseNamesBySecurityOrigin={};this._originsUpdated=new Set();this._throttler=new Common.Throttler(1000);}
static keyFromIDBKey(idbKey){if(typeof(idbKey)==='undefined'||idbKey===null)
return undefined;let type;const key={};switch(typeof(idbKey)){case'number':key.number=idbKey;type=Resources.IndexedDBModel.KeyTypes.NumberType;break;case'string':key.string=idbKey;type=Resources.IndexedDBModel.KeyTypes.StringType;break;case'object':if(idbKey instanceof Date){key.date=idbKey.getTime();type=Resources.IndexedDBModel.KeyTypes.DateType;}else if(Array.isArray(idbKey)){key.array=[];for(let i=0;i<idbKey.length;++i)
key.array.push(Resources.IndexedDBModel.keyFromIDBKey(idbKey[i]));type=Resources.IndexedDBModel.KeyTypes.ArrayType;}
break;default:return undefined;}
key.type=(type);return key;}
static _keyRangeFromIDBKeyRange(idbKeyRange){const keyRange={};keyRange.lower=Resources.IndexedDBModel.keyFromIDBKey(idbKeyRange.lower);keyRange.upper=Resources.IndexedDBModel.keyFromIDBKey(idbKeyRange.upper);keyRange.lowerOpen=!!idbKeyRange.lowerOpen;keyRange.upperOpen=!!idbKeyRange.upperOpen;return keyRange;}
static idbKeyPathFromKeyPath(keyPath){let idbKeyPath;switch(keyPath.type){case Resources.IndexedDBModel.KeyPathTypes.NullType:idbKeyPath=null;break;case Resources.IndexedDBModel.KeyPathTypes.StringType:idbKeyPath=keyPath.string;break;case Resources.IndexedDBModel.KeyPathTypes.ArrayType:idbKeyPath=keyPath.array;break;}
return idbKeyPath;}
static keyPathStringFromIDBKeyPath(idbKeyPath){if(typeof idbKeyPath==='string')
return'"'+idbKeyPath+'"';if(idbKeyPath instanceof Array)
return'["'+idbKeyPath.join('", "')+'"]';return null;}
enable(){if(this._enabled)
return;this._indexedDBAgent.enable();this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);for(const securityOrigin of this._securityOriginManager.securityOrigins())
this._addOrigin(securityOrigin);this._enabled=true;}
clearForOrigin(origin){if(!this._enabled)
return;this._removeOrigin(origin);this._addOrigin(origin);}
async deleteDatabase(databaseId){if(!this._enabled)
return;await this._indexedDBAgent.deleteDatabase(databaseId.securityOrigin,databaseId.name);this._loadDatabaseNames(databaseId.securityOrigin);}
async refreshDatabaseNames(){for(const securityOrigin in this._databaseNamesBySecurityOrigin)
await this._loadDatabaseNames(securityOrigin);this.dispatchEventToListeners(Resources.IndexedDBModel.Events.DatabaseNamesRefreshed);}
refreshDatabase(databaseId){this._loadDatabase(databaseId,true);}
clearObjectStore(databaseId,objectStoreName){return this._indexedDBAgent.clearObjectStore(databaseId.securityOrigin,databaseId.name,objectStoreName);}
deleteEntries(databaseId,objectStoreName,idbKeyRange){const keyRange=Resources.IndexedDBModel._keyRangeFromIDBKeyRange(idbKeyRange);return this._indexedDBAgent.deleteObjectStoreEntries(databaseId.securityOrigin,databaseId.name,objectStoreName,keyRange);}
_securityOriginAdded(event){const securityOrigin=(event.data);this._addOrigin(securityOrigin);}
_securityOriginRemoved(event){const securityOrigin=(event.data);this._removeOrigin(securityOrigin);}
_addOrigin(securityOrigin){console.assert(!this._databaseNamesBySecurityOrigin[securityOrigin]);this._databaseNamesBySecurityOrigin[securityOrigin]=[];this._loadDatabaseNames(securityOrigin);if(this._isValidSecurityOrigin(securityOrigin))
this._storageAgent.trackIndexedDBForOrigin(securityOrigin);}
_removeOrigin(securityOrigin){console.assert(this._databaseNamesBySecurityOrigin[securityOrigin]);for(let i=0;i<this._databaseNamesBySecurityOrigin[securityOrigin].length;++i)
this._databaseRemoved(securityOrigin,this._databaseNamesBySecurityOrigin[securityOrigin][i]);delete this._databaseNamesBySecurityOrigin[securityOrigin];if(this._isValidSecurityOrigin(securityOrigin))
this._storageAgent.untrackIndexedDBForOrigin(securityOrigin);}
_isValidSecurityOrigin(securityOrigin){const parsedURL=securityOrigin.asParsedURL();return!!parsedURL&&parsedURL.scheme.startsWith('http');}
_updateOriginDatabaseNames(securityOrigin,databaseNames){const newDatabaseNames=new Set(databaseNames);const oldDatabaseNames=new Set(this._databaseNamesBySecurityOrigin[securityOrigin]);this._databaseNamesBySecurityOrigin[securityOrigin]=databaseNames;for(const databaseName of oldDatabaseNames){if(!newDatabaseNames.has(databaseName))
this._databaseRemoved(securityOrigin,databaseName);}
for(const databaseName of newDatabaseNames){if(!oldDatabaseNames.has(databaseName))
this._databaseAdded(securityOrigin,databaseName);}}
databases(){const result=[];for(const securityOrigin in this._databaseNamesBySecurityOrigin){const databaseNames=this._databaseNamesBySecurityOrigin[securityOrigin];for(let i=0;i<databaseNames.length;++i)
result.push(new Resources.IndexedDBModel.DatabaseId(securityOrigin,databaseNames[i]));}
return result;}
_databaseAdded(securityOrigin,databaseName){const databaseId=new Resources.IndexedDBModel.DatabaseId(securityOrigin,databaseName);this.dispatchEventToListeners(Resources.IndexedDBModel.Events.DatabaseAdded,{model:this,databaseId:databaseId});}
_databaseRemoved(securityOrigin,databaseName){const databaseId=new Resources.IndexedDBModel.DatabaseId(securityOrigin,databaseName);this.dispatchEventToListeners(Resources.IndexedDBModel.Events.DatabaseRemoved,{model:this,databaseId:databaseId});}
async _loadDatabaseNames(securityOrigin){const databaseNames=await this._indexedDBAgent.requestDatabaseNames(securityOrigin);if(!databaseNames)
return[];if(!this._databaseNamesBySecurityOrigin[securityOrigin])
return[];this._updateOriginDatabaseNames(securityOrigin,databaseNames);return databaseNames;}
async _loadDatabase(databaseId,entriesUpdated){const databaseWithObjectStores=await this._indexedDBAgent.requestDatabase(databaseId.securityOrigin,databaseId.name);if(!databaseWithObjectStores)
return;if(!this._databaseNamesBySecurityOrigin[databaseId.securityOrigin])
return;const databaseModel=new Resources.IndexedDBModel.Database(databaseId,databaseWithObjectStores.version);this._databases.set(databaseId,databaseModel);for(const objectStore of databaseWithObjectStores.objectStores){const objectStoreIDBKeyPath=Resources.IndexedDBModel.idbKeyPathFromKeyPath(objectStore.keyPath);const objectStoreModel=new Resources.IndexedDBModel.ObjectStore(objectStore.name,objectStoreIDBKeyPath,objectStore.autoIncrement);for(let j=0;j<objectStore.indexes.length;++j){const index=objectStore.indexes[j];const indexIDBKeyPath=Resources.IndexedDBModel.idbKeyPathFromKeyPath(index.keyPath);const indexModel=new Resources.IndexedDBModel.Index(index.name,indexIDBKeyPath,index.unique,index.multiEntry);objectStoreModel.indexes[indexModel.name]=indexModel;}
databaseModel.objectStores[objectStoreModel.name]=objectStoreModel;}
this.dispatchEventToListeners(Resources.IndexedDBModel.Events.DatabaseLoaded,{model:this,database:databaseModel,entriesUpdated:entriesUpdated});}
loadObjectStoreData(databaseId,objectStoreName,idbKeyRange,skipCount,pageSize,callback){this._requestData(databaseId,databaseId.name,objectStoreName,'',idbKeyRange,skipCount,pageSize,callback);}
loadIndexData(databaseId,objectStoreName,indexName,idbKeyRange,skipCount,pageSize,callback){this._requestData(databaseId,databaseId.name,objectStoreName,indexName,idbKeyRange,skipCount,pageSize,callback);}
async _requestData(databaseId,databaseName,objectStoreName,indexName,idbKeyRange,skipCount,pageSize,callback){const keyRange=idbKeyRange?Resources.IndexedDBModel._keyRangeFromIDBKeyRange(idbKeyRange):undefined;const response=await this._indexedDBAgent.invoke_requestData({securityOrigin:databaseId.securityOrigin,databaseName,objectStoreName,indexName,skipCount,pageSize,keyRange});if(response[Protocol.Error]){console.error('IndexedDBAgent error: '+response[Protocol.Error]);return;}
const runtimeModel=this.target().model(SDK.RuntimeModel);if(!runtimeModel||!this._databaseNamesBySecurityOrigin[databaseId.securityOrigin])
return;const dataEntries=response.objectStoreDataEntries;const entries=[];for(const dataEntry of dataEntries){const key=runtimeModel.createRemoteObject(dataEntry.key);const primaryKey=runtimeModel.createRemoteObject(dataEntry.primaryKey);const value=runtimeModel.createRemoteObject(dataEntry.value);entries.push(new Resources.IndexedDBModel.Entry(key,primaryKey,value));}
callback(entries,response.hasMore);}
async getMetadata(databaseId,objectStore){const databaseOrigin=databaseId.securityOrigin;const databaseName=databaseId.name;const objectStoreName=objectStore.name;const response=await this._indexedDBAgent.invoke_getMetadata({securityOrigin:databaseOrigin,databaseName,objectStoreName});if(response[Protocol.Error]){console.error('IndexedDBAgent error: '+response[Protocol.Error]);return null;}
return{entriesCount:response.entriesCount,keyGeneratorValue:response.keyGeneratorValue};}
async _refreshDatabaseList(securityOrigin){const databaseNames=await this._loadDatabaseNames(securityOrigin);for(const databaseName of databaseNames)
this._loadDatabase(new Resources.IndexedDBModel.DatabaseId(securityOrigin,databaseName),false);}
indexedDBListUpdated(securityOrigin){this._originsUpdated.add(securityOrigin);this._throttler.schedule(()=>{const promises=Array.from(this._originsUpdated,securityOrigin=>{this._refreshDatabaseList(securityOrigin);});this._originsUpdated.clear();return Promise.all(promises);});}
indexedDBContentUpdated(securityOrigin,databaseName,objectStoreName){const databaseId=new Resources.IndexedDBModel.DatabaseId(securityOrigin,databaseName);this.dispatchEventToListeners(Resources.IndexedDBModel.Events.IndexedDBContentUpdated,{databaseId:databaseId,objectStoreName:objectStoreName,model:this});}
cacheStorageListUpdated(securityOrigin){}
cacheStorageContentUpdated(securityOrigin){}};SDK.SDKModel.register(Resources.IndexedDBModel,SDK.Target.Capability.DOM,false);Resources.IndexedDBModel.KeyTypes={NumberType:'number',StringType:'string',DateType:'date',ArrayType:'array'};Resources.IndexedDBModel.KeyPathTypes={NullType:'null',StringType:'string',ArrayType:'array'};Resources.IndexedDBModel.Events={DatabaseAdded:Symbol('DatabaseAdded'),DatabaseRemoved:Symbol('DatabaseRemoved'),DatabaseLoaded:Symbol('DatabaseLoaded'),DatabaseNamesRefreshed:Symbol('DatabaseNamesRefreshed'),IndexedDBContentUpdated:Symbol('IndexedDBContentUpdated')};Resources.IndexedDBModel.Entry=class{constructor(key,primaryKey,value){this.key=key;this.primaryKey=primaryKey;this.value=value;}};Resources.IndexedDBModel.DatabaseId=class{constructor(securityOrigin,name){this.securityOrigin=securityOrigin;this.name=name;}
equals(databaseId){return this.name===databaseId.name&&this.securityOrigin===databaseId.securityOrigin;}};Resources.IndexedDBModel.Database=class{constructor(databaseId,version){this.databaseId=databaseId;this.version=version;this.objectStores={};}};Resources.IndexedDBModel.ObjectStore=class{constructor(name,keyPath,autoIncrement){this.name=name;this.keyPath=keyPath;this.autoIncrement=autoIncrement;this.indexes={};}
get keyPathString(){return(Resources.IndexedDBModel.keyPathStringFromIDBKeyPath((this.keyPath)));}};Resources.IndexedDBModel.ObjectStoreMetadata;Resources.IndexedDBModel.Index=class{constructor(name,keyPath,unique,multiEntry){this.name=name;this.keyPath=keyPath;this.unique=unique;this.multiEntry=multiEntry;}
get keyPathString(){return(Resources.IndexedDBModel.keyPathStringFromIDBKeyPath((this.keyPath)));}};;Resources.IDBDatabaseView=class extends UI.VBox{constructor(model,database){super();this._model=model;const databaseName=database?database.databaseId.name:ls`Loading\u2026`;this._reportView=new UI.ReportView(databaseName);this._reportView.show(this.contentElement);const bodySection=this._reportView.appendSection('');this._securityOriginElement=bodySection.appendField(ls`Security origin`);this._versionElement=bodySection.appendField(ls`Version`);this._objectStoreCountElement=bodySection.appendField(ls`Object stores`);const footer=this._reportView.appendSection('').appendRow();this._clearButton=UI.createTextButton(ls`Delete database`,()=>this._deleteDatabase(),ls`Delete database`);footer.appendChild(this._clearButton);this._refreshButton=UI.createTextButton(ls`Refresh database`,()=>this._refreshDatabaseButtonClicked(),ls`Refresh database`);footer.appendChild(this._refreshButton);if(database)
this.update(database);}
_refreshDatabase(){this._securityOriginElement.textContent=this._database.databaseId.securityOrigin;this._versionElement.textContent=this._database.version;this._objectStoreCountElement.textContent=Object.keys(this._database.objectStores).length;}
_refreshDatabaseButtonClicked(){this._model.refreshDatabase(this._database.databaseId);}
update(database){this._database=database;this._reportView.setTitle(this._database.databaseId.name);this._refreshDatabase();this._updatedForTests();}
_updatedForTests(){}
async _deleteDatabase(){const ok=await UI.ConfirmDialog.show(Common.UIString('Please confirm delete of "%s" database.',this._database.databaseId.name),this.element);if(ok)
this._model.deleteDatabase(this._database.databaseId);}};Resources.IDBDataView=class extends UI.SimpleView{constructor(model,databaseId,objectStore,index,refreshObjectStoreCallback){super(Common.UIString('IDB'));this.registerRequiredCSS('resources/indexedDBViews.css');this._model=model;this._databaseId=databaseId;this._isIndex=!!index;this._refreshObjectStoreCallback=refreshObjectStoreCallback;this.element.classList.add('indexed-db-data-view','storage-view');this._refreshButton=new UI.ToolbarButton(Common.UIString('Refresh'),'largeicon-refresh');this._refreshButton.addEventListener(UI.ToolbarButton.Events.Click,this._refreshButtonClicked,this);this._deleteSelectedButton=new UI.ToolbarButton(Common.UIString('Delete selected'),'largeicon-delete');this._deleteSelectedButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._deleteButtonClicked(null));this._clearButton=new UI.ToolbarButton(Common.UIString('Clear object store'),'largeicon-clear');this._clearButton.addEventListener(UI.ToolbarButton.Events.Click,this._clearButtonClicked,this);this._needsRefresh=new UI.ToolbarItem(UI.createIconLabel(Common.UIString('Data may be stale'),'smallicon-warning'));this._needsRefresh.setVisible(false);this._needsRefresh.setTitle(Common.UIString('Some entries may have been modified'));this._createEditorToolbar();this._pageSize=50;this._skipCount=0;this.update(objectStore,index);this._entries=[];}
_createDataGrid(){const keyPath=this._isIndex?this._index.keyPath:this._objectStore.keyPath;const columns=([]);columns.push({id:'number',title:Common.UIString('#'),sortable:false,width:'50px'});columns.push({id:'key',titleDOMFragment:this._keyColumnHeaderFragment(Common.UIString('Key'),keyPath),sortable:false});if(this._isIndex){columns.push({id:'primaryKey',titleDOMFragment:this._keyColumnHeaderFragment(Common.UIString('Primary key'),this._objectStore.keyPath),sortable:false});}
columns.push({id:'value',title:Common.UIString('Value'),sortable:false});const dataGrid=new DataGrid.DataGrid(columns,undefined,this._deleteButtonClicked.bind(this),this._updateData.bind(this,true));dataGrid.setStriped(true);dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,event=>this._updateToolbarEnablement(),this);return dataGrid;}
_keyColumnHeaderFragment(prefix,keyPath){const keyColumnHeaderFragment=createDocumentFragment();keyColumnHeaderFragment.createTextChild(prefix);if(keyPath===null)
return keyColumnHeaderFragment;keyColumnHeaderFragment.createTextChild(' ('+Common.UIString('Key path: '));if(Array.isArray(keyPath)){keyColumnHeaderFragment.createTextChild('[');for(let i=0;i<keyPath.length;++i){if(i!==0)
keyColumnHeaderFragment.createTextChild(', ');keyColumnHeaderFragment.appendChild(this._keyPathStringFragment(keyPath[i]));}
keyColumnHeaderFragment.createTextChild(']');}else{const keyPathString=(keyPath);keyColumnHeaderFragment.appendChild(this._keyPathStringFragment(keyPathString));}
keyColumnHeaderFragment.createTextChild(')');return keyColumnHeaderFragment;}
_keyPathStringFragment(keyPathString){const keyPathStringFragment=createDocumentFragment();keyPathStringFragment.createTextChild('"');const keyPathSpan=keyPathStringFragment.createChild('span','source-code indexed-db-key-path');keyPathSpan.textContent=keyPathString;keyPathStringFragment.createTextChild('"');return keyPathStringFragment;}
_createEditorToolbar(){const editorToolbar=new UI.Toolbar('data-view-toolbar',this.element);editorToolbar.appendToolbarItem(this._refreshButton);editorToolbar.appendToolbarItem(new UI.ToolbarSeparator());this._pageBackButton=new UI.ToolbarButton(Common.UIString('Show previous page'),'largeicon-play-back');this._pageBackButton.addEventListener(UI.ToolbarButton.Events.Click,this._pageBackButtonClicked,this);editorToolbar.appendToolbarItem(this._pageBackButton);this._pageForwardButton=new UI.ToolbarButton(Common.UIString('Show next page'),'largeicon-play');this._pageForwardButton.setEnabled(false);this._pageForwardButton.addEventListener(UI.ToolbarButton.Events.Click,this._pageForwardButtonClicked,this);editorToolbar.appendToolbarItem(this._pageForwardButton);this._keyInput=new UI.ToolbarInput(ls`Start from key`,0.5);this._keyInput.addEventListener(UI.ToolbarInput.Event.TextChanged,this._updateData.bind(this,false));editorToolbar.appendToolbarItem(this._keyInput);editorToolbar.appendToolbarItem(new UI.ToolbarSeparator());editorToolbar.appendToolbarItem(this._clearButton);editorToolbar.appendToolbarItem(this._deleteSelectedButton);editorToolbar.appendToolbarItem(this._needsRefresh);}
_pageBackButtonClicked(event){this._skipCount=Math.max(0,this._skipCount-this._pageSize);this._updateData(false);}
_pageForwardButtonClicked(event){this._skipCount=this._skipCount+this._pageSize;this._updateData(false);}
refreshData(){this._updateData(true);}
update(objectStore,index){this._objectStore=objectStore;this._index=index;if(this._dataGrid)
this._dataGrid.asWidget().detach();this._dataGrid=this._createDataGrid();this._dataGrid.asWidget().show(this.element);this._skipCount=0;this._updateData(true);}
_parseKey(keyString){let result;try{result=JSON.parse(keyString);}catch(e){result=keyString;}
return result;}
_updateData(force){const key=this._parseKey(this._keyInput.value());const pageSize=this._pageSize;let skipCount=this._skipCount;let selected=this._dataGrid.selectedNode?this._dataGrid.selectedNode.data['number']:0;selected=Math.max(selected,this._skipCount);this._refreshButton.setEnabled(false);this._clearButton.setEnabled(!this._isIndex);if(!force&&this._lastKey===key&&this._lastPageSize===pageSize&&this._lastSkipCount===skipCount)
return;if(this._lastKey!==key||this._lastPageSize!==pageSize){skipCount=0;this._skipCount=0;}
this._lastKey=key;this._lastPageSize=pageSize;this._lastSkipCount=skipCount;function callback(entries,hasMore){this._refreshButton.setEnabled(true);this.clear();this._entries=entries;let selectedNode=null;for(let i=0;i<entries.length;++i){const data={};data['number']=i+skipCount;data['key']=entries[i].key;data['primaryKey']=entries[i].primaryKey;data['value']=entries[i].value;const node=new Resources.IDBDataGridNode(data);this._dataGrid.rootNode().appendChild(node);if(data['number']<=selected)
selectedNode=node;}
if(selectedNode)
selectedNode.select();this._pageBackButton.setEnabled(!!skipCount);this._pageForwardButton.setEnabled(hasMore);this._needsRefresh.setVisible(false);this._updateToolbarEnablement();this._updatedDataForTests();}
const idbKeyRange=key?window.IDBKeyRange.lowerBound(key):null;if(this._isIndex){this._model.loadIndexData(this._databaseId,this._objectStore.name,this._index.name,idbKeyRange,skipCount,pageSize,callback.bind(this));}else{this._model.loadObjectStoreData(this._databaseId,this._objectStore.name,idbKeyRange,skipCount,pageSize,callback.bind(this));}
this._model.getMetadata(this._databaseId,this._objectStore).then(this._updateSummaryBar.bind(this));}
_updateSummaryBar(metadata){if(!this._summaryBarElement)
this._summaryBarElement=this.element.createChild('div','object-store-summary-bar');this._summaryBarElement.removeChildren();if(!metadata)
return;const separator='\u2002\u2758\u2002';const span=this._summaryBarElement.createChild('span');span.textContent=ls`Total entries: ${String(metadata.entriesCount)}`;if(this._objectStore.autoIncrement){span.textContent+=separator;span.textContent+=ls`Key generator value: ${String(metadata.keyGeneratorValue)}`;}}
_updatedDataForTests(){}
_refreshButtonClicked(event){this._updateData(true);}
async _clearButtonClicked(event){this._clearButton.setEnabled(false);await this._model.clearObjectStore(this._databaseId,this._objectStore.name);this._clearButton.setEnabled(true);this._updateData(true);}
markNeedsRefresh(){this._needsRefresh.setVisible(true);}
async _deleteButtonClicked(node){if(!node){node=this._dataGrid.selectedNode;if(!node)
return;}
const key=(this._isIndex?node.data.primaryKey:node.data.key);const keyValue=(key.value);await this._model.deleteEntries(this._databaseId,this._objectStore.name,window.IDBKeyRange.only(keyValue));this._refreshObjectStoreCallback();}
clear(){this._dataGrid.rootNode().removeChildren();this._entries=[];}
_updateToolbarEnablement(){const empty=!this._dataGrid||this._dataGrid.rootNode().children.length===0;this._clearButton.setEnabled(!empty);this._deleteSelectedButton.setEnabled(!empty&&this._dataGrid.selectedNode!==null);}};Resources.IDBDataGridNode=class extends DataGrid.DataGridNode{constructor(data){super(data,false);this.selectable=true;}
createCell(columnIdentifier){const cell=super.createCell(columnIdentifier);const value=(this.data[columnIdentifier]);switch(columnIdentifier){case'value':case'key':case'primaryKey':cell.removeChildren();const objectElement=ObjectUI.ObjectPropertiesSection.defaultObjectPresentation(value,undefined,true,true);cell.appendChild(objectElement);break;default:}
return cell;}};;Resources.ResourcesPanel=class extends UI.PanelWithSidebar{constructor(){super('resources');this.registerRequiredCSS('resources/resourcesPanel.css');this._resourcesLastSelectedItemSetting=Common.settings.createSetting('resourcesLastSelectedElementPath',[]);this.visibleView=null;this._pendingViewPromise=null;this._categoryView=null;const mainContainer=new UI.VBox();this.storageViews=mainContainer.element.createChild('div','vbox flex-auto');this._storageViewToolbar=new UI.Toolbar('resources-toolbar',mainContainer.element);this.splitWidget().setMainWidget(mainContainer);this._domStorageView=null;this._cookieView=null;this._emptyWidget=null;this._sidebar=new Resources.ApplicationPanelSidebar(this);this._sidebar.show(this.panelSidebarElement());}
static _instance(){return(self.runtime.sharedInstance(Resources.ResourcesPanel));}
static _shouldCloseOnReset(view){const viewClassesToClose=[SourceFrame.ResourceSourceFrame,SourceFrame.ImageView,SourceFrame.FontView,Resources.StorageItemsView,Resources.DatabaseQueryView,Resources.DatabaseTableView];return viewClassesToClose.some(type=>view instanceof type);}
focus(){this._sidebar.focus();}
lastSelectedItemPath(){return this._resourcesLastSelectedItemSetting.get();}
setLastSelectedItemPath(path){this._resourcesLastSelectedItemSetting.set(path);}
resetView(){if(this.visibleView&&Resources.ResourcesPanel._shouldCloseOnReset(this.visibleView))
this.showView(null);}
showView(view){this._pendingViewPromise=null;if(this.visibleView===view)
return;if(this.visibleView)
this.visibleView.detach();if(view)
view.show(this.storageViews);this.visibleView=view;this._storageViewToolbar.removeToolbarItems();const toolbarItems=(view instanceof UI.SimpleView&&view.syncToolbarItems())||[];for(let i=0;i<toolbarItems.length;++i)
this._storageViewToolbar.appendToolbarItem(toolbarItems[i]);this._storageViewToolbar.element.classList.toggle('hidden',!toolbarItems.length);}
async scheduleShowView(viewPromise){this._pendingViewPromise=viewPromise;const view=await viewPromise;if(this._pendingViewPromise!==viewPromise)
return null;this.showView(view);return view;}
showCategoryView(categoryName,categoryLink){if(!this._categoryView)
this._categoryView=new Resources.StorageCategoryView();this._categoryView.setText(categoryName);this._categoryView.setLink(categoryLink);this.showView(this._categoryView);}
showDOMStorage(domStorage){if(!domStorage)
return;if(!this._domStorageView)
this._domStorageView=new Resources.DOMStorageItemsView(domStorage);else
this._domStorageView.setStorage(domStorage);this.showView(this._domStorageView);}
showCookies(cookieFrameTarget,cookieDomain){const model=cookieFrameTarget.model(SDK.CookieModel);if(!model)
return;if(!this._cookieView)
this._cookieView=new Resources.CookieItemsView(model,cookieDomain);else
this._cookieView.setCookiesDomain(model,cookieDomain);this.showView(this._cookieView);}
clearCookies(target,cookieDomain){const model=target.model(SDK.CookieModel);if(!model)
return;model.clear(cookieDomain,()=>{if(this._cookieView)
this._cookieView.refreshItems();});}};Resources.ResourcesPanel.ResourceRevealer=class{async reveal(resource){if(!(resource instanceof SDK.Resource))
return Promise.reject(new Error('Internal error: not a resource'));const sidebar=Resources.ResourcesPanel._instance()._sidebar;await UI.viewManager.showView('resources');await sidebar.showResource(resource);}};;Resources.ApplicationPanelSidebar=class extends UI.VBox{constructor(panel){super();this._panel=panel;this._sidebarTree=new UI.TreeOutlineInShadow();this._sidebarTree.element.classList.add('resources-sidebar');this._sidebarTree.registerRequiredCSS('resources/resourcesSidebar.css');this._sidebarTree.element.classList.add('filter-all');this._sidebarTree.addEventListener(UI.TreeOutline.Events.ElementAttached,this._treeElementAdded,this);this.contentElement.appendChild(this._sidebarTree.element);this._applicationTreeElement=this._addSidebarSection(Common.UIString('Application'));const manifestTreeElement=new Resources.AppManifestTreeElement(panel);this._applicationTreeElement.appendChild(manifestTreeElement);this.serviceWorkersTreeElement=new Resources.ServiceWorkersTreeElement(panel);this._applicationTreeElement.appendChild(this.serviceWorkersTreeElement);const clearStorageTreeElement=new Resources.ClearStorageTreeElement(panel);this._applicationTreeElement.appendChild(clearStorageTreeElement);const storageTreeElement=this._addSidebarSection(Common.UIString('Storage'));this.localStorageListTreeElement=new Resources.StorageCategoryTreeElement(panel,Common.UIString('Local Storage'),'LocalStorage');this.localStorageListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/localstorage?utm_source=devtools');const localStorageIcon=UI.Icon.create('mediumicon-table','resource-tree-item');this.localStorageListTreeElement.setLeadingIcons([localStorageIcon]);storageTreeElement.appendChild(this.localStorageListTreeElement);this.sessionStorageListTreeElement=new Resources.StorageCategoryTreeElement(panel,Common.UIString('Session Storage'),'SessionStorage');this.sessionStorageListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/sessionstorage?utm_source=devtools');const sessionStorageIcon=UI.Icon.create('mediumicon-table','resource-tree-item');this.sessionStorageListTreeElement.setLeadingIcons([sessionStorageIcon]);storageTreeElement.appendChild(this.sessionStorageListTreeElement);this.indexedDBListTreeElement=new Resources.IndexedDBTreeElement(panel);this.indexedDBListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/indexeddb?utm_source=devtools');storageTreeElement.appendChild(this.indexedDBListTreeElement);this.databasesListTreeElement=new Resources.StorageCategoryTreeElement(panel,Common.UIString('Web SQL'),'Databases');this.databasesListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/websql?utm_source=devtools');const databaseIcon=UI.Icon.create('mediumicon-database','resource-tree-item');this.databasesListTreeElement.setLeadingIcons([databaseIcon]);storageTreeElement.appendChild(this.databasesListTreeElement);this.cookieListTreeElement=new Resources.StorageCategoryTreeElement(panel,Common.UIString('Cookies'),'Cookies');this.cookieListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/cookies?utm_source=devtools');const cookieIcon=UI.Icon.create('mediumicon-cookie','resource-tree-item');this.cookieListTreeElement.setLeadingIcons([cookieIcon]);storageTreeElement.appendChild(this.cookieListTreeElement);const cacheTreeElement=this._addSidebarSection(Common.UIString('Cache'));this.cacheStorageListTreeElement=new Resources.ServiceWorkerCacheTreeElement(panel);cacheTreeElement.appendChild(this.cacheStorageListTreeElement);this.applicationCacheListTreeElement=new Resources.StorageCategoryTreeElement(panel,Common.UIString('Application Cache'),'ApplicationCache');this.applicationCacheListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/applicationcache?utm_source=devtools');const applicationCacheIcon=UI.Icon.create('mediumicon-table','resource-tree-item');this.applicationCacheListTreeElement.setLeadingIcons([applicationCacheIco
if(Runtime.experiments.isEnabled('backgroundServicesPushMessaging')){this.pushMessagingTreeElement=new Resources.BackgroundServiceTreeElement(panel,Protocol.BackgroundService.ServiceName.PushMessaging);backgroundServiceTreeElement.appendChild(this.pushMessagingTreeElement);}}
this._resourcesSection=new Resources.ResourcesSection(panel,this._addSidebarSection(Common.UIString('Frames')));this._databaseTableViews=new Map();this._databaseQueryViews=new Map();this._databaseTreeElements=new Map();this._domStorageTreeElements=new Map();this._domains={};this._sidebarTree.contentElement.addEventListener('mousemove',this._onmousemove.bind(this),false);this._sidebarTree.contentElement.addEventListener('mouseleave',this._onmouseleave.bind(this),false);SDK.targetManager.observeTargets(this);SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.FrameNavigated,this._frameNavigated,this);const selection=this._panel.lastSelectedItemPath();if(!selection.length)
manifestTreeElement.select();}
_addSidebarSection(title){const treeElement=new UI.TreeElement(title,true);treeElement.listItemElement.classList.add('storage-group-list-item');treeElement.setCollapsible(false);treeElement.selectable=false;this._sidebarTree.appendChild(treeElement);return treeElement;}
targetAdded(target){if(this._target)
return;this._target=target;this._databaseModel=target.model(Resources.DatabaseModel);this._databaseModel.addEventListener(Resources.DatabaseModel.Events.DatabaseAdded,this._databaseAdded,this);this._databaseModel.addEventListener(Resources.DatabaseModel.Events.DatabasesRemoved,this._resetWebSQL,this);const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel)
return;if(resourceTreeModel.cachedResourcesLoaded())
this._initialize();resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded,this._initialize,this);resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.WillLoadCachedResources,this._resetWithFrames,this);}
targetRemoved(target){if(target!==this._target)
return;delete this._target;const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded,this._initialize,this);resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.WillLoadCachedResources,this._resetWithFrames,this);}
this._databaseModel.removeEventListener(Resources.DatabaseModel.Events.DatabaseAdded,this._databaseAdded,this);this._databaseModel.removeEventListener(Resources.DatabaseModel.Events.DatabasesRemoved,this._resetWebSQL,this);this._resetWithFrames();}
focus(){this._sidebarTree.focus();}
_initialize(){for(const frame of SDK.ResourceTreeModel.frames())
this._addCookieDocument(frame);this._databaseModel.enable();const cacheStorageModel=this._target.model(SDK.ServiceWorkerCacheModel);if(cacheStorageModel)
cacheStorageModel.enable();const resourceTreeModel=this._target.model(SDK.ResourceTreeModel);if(resourceTreeModel)
this._populateApplicationCacheTree(resourceTreeModel);SDK.targetManager.observeModels(Resources.DOMStorageModel,({modelAdded:model=>this._domStorageModelAdded(model),modelRemoved:model=>this._domStorageModelRemoved(model)}));this.indexedDBListTreeElement._initialize();SDK.targetManager.observeModels(Resources.IndexedDBModel,({modelAdded:model=>model.enable(),modelRemoved:model=>this.indexedDBListTreeElement.removeIndexedDBForModel(model)}));const serviceWorkerCacheModel=this._target.model(SDK.ServiceWorkerCacheModel);this.cacheStorageListTreeElement._initialize(serviceWorkerCacheModel);const backgroundServiceModel=this._target.model(Resources.BackgroundServiceModel);if(Runtime.experiments.isEnabled('backgroundServices')){this.backgroundFetchTreeElement._initialize(backgroundServiceModel);this.backgroundSyncTreeElement._initialize(backgroundServiceModel);if(Runtime.experiments.isEnabled('backgroundServicesNotifications'))
this.notificationsTreeElement._initialize(backgroundServiceModel);if(Runtime.experiments.isEnabled('backgroundServicesPushMessaging'))
this.pushMessagingTreeElement._initialize(backgroundServiceModel);}}
_domStorageModelAdded(model){model.enable();model.storages().forEach(this._addDOMStorage.bind(this));model.addEventListener(Resources.DOMStorageModel.Events.DOMStorageAdded,this._domStorageAdded,this);model.addEventListener(Resources.DOMStorageModel.Events.DOMStorageRemoved,this._domStorageRemoved,this);}
_domStorageModelRemoved(model){model.storages().forEach(this._removeDOMStorage.bind(this));model.removeEventListener(Resources.DOMStorageModel.Events.DOMStorageAdded,this._domStorageAdded,this);model.removeEventListener(Resources.DOMStorageModel.Events.DOMStorageRemoved,this._domStorageRemoved,this);}
_resetWithFrames(){this._resourcesSection.reset();this._reset();}
_resetWebSQL(){const queryViews=this._databaseQueryViews.valuesArray();for(let i=0;i<queryViews.length;++i){queryViews[i].removeEventListener(Resources.DatabaseQueryView.Events.SchemaUpdated,this._updateDatabaseTables,this);}
this._databaseTableViews.clear();this._databaseQueryViews.clear();this._databaseTreeElements.clear();this.databasesListTreeElement.removeChildren();this.databasesListTreeElement.setExpandable(false);}
_resetAppCache(){for(const frameId of Object.keys(this._applicationCacheFrameElements))
this._applicationCacheFrameManifestRemoved({data:frameId});this.applicationCacheListTreeElement.setExpandable(false);}
_treeElementAdded(event){const selection=this._panel.lastSelectedItemPath();if(!selection.length)
return;const element=event.data;const index=selection.indexOf(element.itemURL);if(index<0)
return;for(let parent=element.parent;parent;parent=parent.parent)
parent.expand();if(index>0)
element.expand();element.select();}
_reset(){this._domains={};this._resetWebSQL();this.cookieListTreeElement.removeChildren();}
_frameNavigated(event){const frame=(event.data);if(frame.isTopFrame())
this._reset();const applicationCacheFrameTreeElement=this._applicationCacheFrameElements[frame.id];if(applicationCacheFrameTreeElement)
applicationCacheFrameTreeElement.frameNavigated(frame);this._addCookieDocument(frame);}
_databaseAdded(event){const database=(event.data);const databaseTreeElement=new Resources.DatabaseTreeElement(this,database);this._databaseTreeElements.set(database,databaseTreeElement);this.databasesListTreeElement.appendChild(databaseTreeElement);}
_addCookieDocument(frame){const parsedURL=frame.url.asParsedURL();if(!parsedURL||(parsedURL.scheme!=='http'&&parsedURL.scheme!=='https'&&parsedURL.scheme!=='file'))
return;const domain=parsedURL.securityOrigin();if(!this._domains[domain]){this._domains[domain]=true;const cookieDomainTreeElement=new Resources.CookieTreeElement(this._panel,frame,domain);this.cookieListTreeElement.appendChild(cookieDomainTreeElement);}}
_domStorageAdded(event){const domStorage=(event.data);this._addDOMStorage(domStorage);}
_addDOMStorage(domStorage){console.assert(!this._domStorageTreeElements.get(domStorage));const domStorageTreeElement=new Resources.DOMStorageTreeElement(this._panel,domStorage);this._domStorageTreeElements.set(domStorage,domStorageTreeElement);if(domStorage.isLocalStorage)
this.localStorageListTreeElement.appendChild(domStorageTreeElement);else
this.sessionStorageListTreeElement.appendChild(domStorageTreeElement);}
_domStorageRemoved(event){const domStorage=(event.data);this._removeDOMStorage(domStorage);}
_removeDOMStorage(domStorage){const treeElement=this._domStorageTreeElements.get(domStorage);if(!treeElement)
return;const wasSelected=treeElement.selected;const parentListTreeElement=treeElement.parent;parentListTreeElement.removeChild(treeElement);if(wasSelected)
parentListTreeElement.select();this._domStorageTreeElements.remove(domStorage);}
selectDatabase(database){if(database){this._showDatabase(database);this._databaseTreeElements.get(database).select();}}
async showResource(resource,line,column){await this._resourcesSection.revealResource(resource,line,column);}
_showDatabase(database,tableName){if(!database)
return;let view;if(tableName){let tableViews=this._databaseTableViews.get(database);if(!tableViews){tableViews=({});this._databaseTableViews.set(database,tableViews);}
view=tableViews[tableName];if(!view){view=new Resources.DatabaseTableView(database,tableName);tableViews[tableName]=view;}}else{view=this._databaseQueryViews.get(database);if(!view){view=new Resources.DatabaseQueryView(database);this._databaseQueryViews.set(database,view);view.addEventListener(Resources.DatabaseQueryView.Events.SchemaUpdated,this._updateDatabaseTables,this);}}
this._innerShowView(view);}
_showApplicationCache(frameId){if(!this._applicationCacheViews[frameId]){this._applicationCacheViews[frameId]=new Resources.ApplicationCacheItemsView(this._applicationCacheModel,frameId);}
this._innerShowView(this._applicationCacheViews[frameId]);}
showFileSystem(view){this._innerShowView(view);}
_innerShowView(view){this._panel.showView(view);}
_updateDatabaseTables(event){const database=event.data;if(!database)
return;const databasesTreeElement=this._databaseTreeElements.get(database);if(!databasesTreeElement)
return;databasesTreeElement.invalidateChildren();const tableViews=this._databaseTableViews.get(database);if(!tableViews)
return;const tableNamesHash={};const panel=this._panel;function tableNamesCallback(tableNames){const tableNamesLength=tableNames.length;for(let i=0;i<tableNamesLength;++i)
tableNamesHash[tableNames[i]]=true;for(const tableName in tableViews){if(!(tableName in tableNamesHash)){if(panel.visibleView===tableViews[tableName])
panel.showView(null);delete tableViews[tableName];}}}
database.getTableNames(tableNamesCallback);}
_populateApplicationCacheTree(resourceTreeModel){this._applicationCacheModel=this._target.model(Resources.ApplicationCacheModel);this._applicationCacheViews={};this._applicationCacheFrameElements={};this._applicationCacheManifestElements={};this._applicationCacheModel.addEventListener(Resources.ApplicationCacheModel.Events.FrameManifestAdded,this._applicationCacheFrameManifestAdded,this);this._applicationCacheModel.addEventListener(Resources.ApplicationCacheModel.Events.FrameManifestRemoved,this._applicationCacheFrameManifestRemoved,this);this._applicationCacheModel.addEventListener(Resources.ApplicationCacheModel.Events.FrameManifestsReset,this._resetAppCache,this);this._applicationCacheModel.addEventListener(Resources.ApplicationCacheModel.Events.FrameManifestStatusUpdated,this._applicationCacheFrameManifestStatusChanged,this);this._applicationCacheModel.addEventListener(Resources.ApplicationCacheModel.Events.NetworkStateChanged,this._applicationCacheNetworkStateChanged,this);}
_applicationCacheFrameManifestAdded(event){const frameId=event.data;const manifestURL=this._applicationCacheModel.frameManifestURL(frameId);let manifestTreeElement=this._applicationCacheManifestElements[manifestURL];if(!manifestTreeElement){manifestTreeElement=new Resources.ApplicationCacheManifestTreeElement(this._panel,manifestURL);this.applicationCacheListTreeElement.appendChild(manifestTreeElement);this._applicationCacheManifestElements[manifestURL]=manifestTreeElement;}
const model=this._target.model(SDK.ResourceTreeModel);const frameTreeElement=new Resources.ApplicationCacheFrameTreeElement(this,model.frameForId(frameId),manifestURL);manifestTreeElement.appendChild(frameTreeElement);manifestTreeElement.expand();this._applicationCacheFrameElements[frameId]=frameTreeElement;}
_applicationCacheFrameManifestRemoved(event){const frameId=event.data;const frameTreeElement=this._applicationCacheFrameElements[frameId];if(!frameTreeElement)
return;const manifestURL=frameTreeElement.manifestURL;delete this._applicationCacheFrameElements[frameId];delete this._applicationCacheViews[frameId];frameTreeElement.parent.removeChild(frameTreeElement);const manifestTreeElement=this._applicationCacheManifestElements[manifestURL];if(manifestTreeElement.childCount())
return;delete this._applicationCacheManifestElements[manifestURL];manifestTreeElement.parent.removeChild(manifestTreeElement);}
_applicationCacheFrameManifestStatusChanged(event){const frameId=event.data;const status=this._applicationCacheModel.frameManifestStatus(frameId);if(this._applicationCacheViews[frameId])
this._applicationCacheViews[frameId].updateStatus(status);}
_applicationCacheNetworkStateChanged(event){const isNowOnline=event.data;for(const manifestURL in this._applicationCacheViews)
this._applicationCacheViews[manifestURL].updateNetworkState(isNowOnline);}
showView(view){if(view)
this.showResource(view.resource);}
_onmousemove(event){const nodeUnderMouse=event.target;if(!nodeUnderMouse)
return;const listNode=nodeUnderMouse.enclosingNodeOrSelfWithNodeName('li');if(!listNode)
return;const element=listNode.treeElement;if(this._previousHoveredElement===element)
return;if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;delete this._previousHoveredElement;}
if(element instanceof Resources.FrameTreeElement){this._previousHoveredElement=element;element.hovered=true;}}
_onmouseleave(event){if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;delete this._previousHoveredElement;}}};Resources.BaseStorageTreeElement=class extends UI.TreeElement{constructor(storagePanel,title,expandable){super(title,expandable);this._storagePanel=storagePanel;}
onselect(selectedByUser){if(!selectedByUser)
return false;const path=[];for(let el=this;el;el=el.parent){const url=el.itemURL;if(!url)
break;path.push(url);}
this._storagePanel.setLastSelectedItemPath(path);return false;}
showView(view){this._storagePanel.showView(view);}};Resources.StorageCategoryTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,categoryName,settingsKey){super(storagePanel,categoryName,false);this._expandedSetting=Common.settings.createSetting('resources'+settingsKey+'Expanded',settingsKey==='Frames');this._categoryName=categoryName;this._categoryLink=null;}
get itemURL(){return'category://'+this._categoryName;}
setLink(link){this._categoryLink=link;}
onselect(selectedByUser){super.onselect(selectedByUser);this._storagePanel.showCategoryView(this._categoryName,this._categoryLink);return false;}
onattach(){super.onattach();if(this._expandedSetting.get())
this.expand();}
onexpand(){this._expandedSetting.set(true);}
oncollapse(){this._expandedSetting.set(false);}};Resources.BackgroundServiceTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,serviceName){super(storagePanel,Resources.BackgroundServiceView.getUIString(serviceName),false);this._serviceName=serviceName;this._selected=false;this._view=null;this._model=null;const backgroundServiceIcon=UI.Icon.create(this._getIconType(),'resource-tree-item');this.setLeadingIcons([backgroundServiceIcon]);}
_getIconType(){switch(this._serviceName){case Protocol.BackgroundService.ServiceName.BackgroundFetch:return'mediumicon-fetch';case Protocol.BackgroundService.ServiceName.BackgroundSync:return'mediumicon-sync';case Protocol.BackgroundService.ServiceName.PushMessaging:return'mediumicon-cloud';case Protocol.BackgroundService.ServiceName.Notifications:return'mediumicon-bell';default:console.error(`Service ${this._serviceName} does not have a dedicated icon`);return'mediumicon-table';}}
_initialize(model){this._model=model;if(this._selected&&!this._view)
this.onselect(false);}
get itemURL(){return`background-service://${this._serviceName}`;}
onselect(selectedByUser){super.onselect(selectedByUser);this._selected=true;if(!this._model)
return false;if(!this._view)
this._view=new Resources.BackgroundServiceView(this._serviceName,this._model);this.showView(this._view);UI.context.setFlavor(Resources.BackgroundServiceView,this._view);return false;}};Resources.DatabaseTreeElement=class extends Resources.BaseStorageTreeElement{constructor(sidebar,database){super(sidebar._panel,database.name,true);this._sidebar=sidebar;this._database=database;const icon=UI.Icon.create('mediumicon-database','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'database://'+encodeURI(this._database.name);}
onselect(selectedByUser){super.onselect(selectedByUser);this._sidebar._showDatabase(this._database);return false;}
onexpand(){this._updateChildren();}
async _updateChildren(){const tableNames=await this._database.tableNames();for(const tableName of tableNames)
this.appendChild(new Resources.DatabaseTableTreeElement(this._sidebar,this._database,tableName));}};Resources.DatabaseTableTreeElement=class extends Resources.BaseStorageTreeElement{constructor(sidebar,database,tableName){super(sidebar._panel,tableName,false);this._sidebar=sidebar;this._database=database;this._tableName=tableName;const icon=UI.Icon.create('mediumicon-table','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'database://'+encodeURI(this._database.name)+'/'+encodeURI(this._tableName);}
onselect(selectedByUser){super.onselect(selectedByUser);this._sidebar._showDatabase(this._database,this._tableName);return false;}};Resources.ServiceWorkerCacheTreeElement=class extends Resources.StorageCategoryTreeElement{constructor(storagePanel){super(storagePanel,Common.UIString('Cache Storage'),'CacheStorage');const icon=UI.Icon.create('mediumicon-database','resource-tree-item');this.setLeadingIcons([icon]);this._swCacheModel=null;}
_initialize(model){this._swCacheTreeElements=[];this._swCacheModel=model;if(model){for(const cache of model.caches())
this._addCache(model,cache);}
SDK.targetManager.addModelListener(SDK.ServiceWorkerCacheModel,SDK.ServiceWorkerCacheModel.Events.CacheAdded,this._cacheAdded,this);SDK.targetManager.addModelListener(SDK.ServiceWorkerCacheModel,SDK.ServiceWorkerCacheModel.Events.CacheRemoved,this._cacheRemoved,this);}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Refresh Caches'),this._refreshCaches.bind(this));contextMenu.show();}
_refreshCaches(){if(this._swCacheModel)
this._swCacheModel.refreshCacheNames();}
_cacheAdded(event){const cache=(event.data.cache);const model=(event.data.model);this._addCache(model,cache);}
_addCache(model,cache){const swCacheTreeElement=new Resources.SWCacheTreeElement(this._storagePanel,model,cache);this._swCacheTreeElements.push(swCacheTreeElement);this.appendChild(swCacheTreeElement);}
_cacheRemoved(event){const cache=(event.data.cache);const model=(event.data.model);const swCacheTreeElement=this._cacheTreeElement(model,cache);if(!swCacheTreeElement)
return;this.removeChild(swCacheTreeElement);this._swCacheTreeElements.remove(swCacheTreeElement);this.setExpandable(this.childCount()>0);}
_cacheTreeElement(model,cache){let index=-1;let i;for(i=0;i<this._swCacheTreeElements.length;++i){if(this._swCacheTreeElements[i]._cache.equals(cache)&&this._swCacheTreeElements[i]._model===model){index=i;break;}}
if(index!==-1)
return this._swCacheTreeElements[i];return null;}};Resources.SWCacheTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,model,cache){super(storagePanel,cache.cacheName+' - '+cache.securityOrigin,false);this._model=model;this._cache=cache;this._view=null;const icon=UI.Icon.create('mediumicon-table','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'cache://'+this._cache.cacheId;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Delete'),this._clearCache.bind(this));contextMenu.show();}
_clearCache(){this._model.deleteCache(this._cache);}
update(cache){this._cache=cache;if(this._view)
this._view.update(cache);}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view)
this._view=new Resources.ServiceWorkerCacheView(this._model,this._cache);this.showView(this._view);return false;}};Resources.ServiceWorkersTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel){super(storagePanel,Common.UIString('Service Workers'),false);const icon=UI.Icon.create('mediumicon-service-worker','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'service-workers://';}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view)
this._view=new Resources.ServiceWorkersView();this.showView(this._view);return false;}};Resources.AppManifestTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel){super(storagePanel,Common.UIString('Manifest'),false);const icon=UI.Icon.create('mediumicon-manifest','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'manifest://';}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view)
this._view=new Resources.AppManifestView();this.showView(this._view);return false;}};Resources.ClearStorageTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel){super(storagePanel,Common.UIString('Clear storage'),false);const icon=UI.Icon.create('mediumicon-clear-storage','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'clear-storage://';}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view)
this._view=new Resources.ClearStorageView();this.showView(this._view);return false;}};Resources.IndexedDBTreeElement=class extends Resources.StorageCategoryTreeElement{constructor(storagePanel){super(storagePanel,Common.UIString('IndexedDB'),'IndexedDB');const icon=UI.Icon.create('mediumicon-database','resource-tree-item');this.setLeadingIcons([icon]);}
_initialize(){SDK.targetManager.addModelListener(Resources.IndexedDBModel,Resources.IndexedDBModel.Events.DatabaseAdded,this._indexedDBAdded,this);SDK.targetManager.addModelListener(Resources.IndexedDBModel,Resources.IndexedDBModel.Events.DatabaseRemoved,this._indexedDBRemoved,this);SDK.targetManager.addModelListener(Resources.IndexedDBModel,Resources.IndexedDBModel.Events.DatabaseLoaded,this._indexedDBLoaded,this);SDK.targetManager.addModelListener(Resources.IndexedDBModel,Resources.IndexedDBModel.Events.IndexedDBContentUpdated,this._indexedDBContentUpdated,this);this._idbDatabaseTreeElements=[];for(const indexedDBModel of SDK.targetManager.models(Resources.IndexedDBModel)){const databases=indexedDBModel.databases();for(let j=0;j<databases.length;++j)
this._addIndexedDB(indexedDBModel,databases[j]);}}
removeIndexedDBForModel(model){const idbDatabaseTreeElements=this._idbDatabaseTreeElements.filter(element=>element._model===model);for(const idbDatabaseTreeElement of idbDatabaseTreeElements)
this._removeIDBDatabaseTreeElement(idbDatabaseTreeElement);}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Refresh IndexedDB'),this.refreshIndexedDB.bind(this));contextMenu.show();}
refreshIndexedDB(){for(const indexedDBModel of SDK.targetManager.models(Resources.IndexedDBModel))
indexedDBModel.refreshDatabaseNames();}
_indexedDBAdded(event){const databaseId=(event.data.databaseId);const model=(event.data.model);this._addIndexedDB(model,databaseId);}
_addIndexedDB(model,databaseId){const idbDatabaseTreeElement=new Resources.IDBDatabaseTreeElement(this._storagePanel,model,databaseId);this._idbDatabaseTreeElements.push(idbDatabaseTreeElement);this.appendChild(idbDatabaseTreeElement);model.refreshDatabase(databaseId);}
_indexedDBRemoved(event){const databaseId=(event.data.databaseId);const model=(event.data.model);const idbDatabaseTreeElement=this._idbDatabaseTreeElement(model,databaseId);if(!idbDatabaseTreeElement)
return;this._removeIDBDatabaseTreeElement(idbDatabaseTreeElement);}
_removeIDBDatabaseTreeElement(idbDatabaseTreeElement){idbDatabaseTreeElement.clear();this.removeChild(idbDatabaseTreeElement);this._idbDatabaseTreeElements.remove(idbDatabaseTreeElement);this.setExpandable(this.childCount()>0);}
_indexedDBLoaded(event){const database=(event.data.database);const model=(event.data.model);const entriesUpdated=(event.data.entriesUpdated);const idbDatabaseTreeElement=this._idbDatabaseTreeElement(model,database.databaseId);if(!idbDatabaseTreeElement)
return;idbDatabaseTreeElement.update(database,entriesUpdated);this._indexedDBLoadedForTest();}
_indexedDBLoadedForTest(){}
_indexedDBContentUpdated(event){const databaseId=(event.data.databaseId);const objectStoreName=(event.data.objectStoreName);const model=(event.data.model);const idbDatabaseTreeElement=this._idbDatabaseTreeElement(model,databaseId);if(!idbDatabaseTreeElement)
return;idbDatabaseTreeElement.indexedDBContentUpdated(objectStoreName);}
_idbDatabaseTreeElement(model,databaseId){return this._idbDatabaseTreeElements.find(x=>x._databaseId.equals(databaseId)&&x._model===model)||null;}};Resources.IDBDatabaseTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,model,databaseId){super(storagePanel,databaseId.name+' - '+databaseId.securityOrigin,false);this._model=model;this._databaseId=databaseId;this._idbObjectStoreTreeElements={};const icon=UI.Icon.create('mediumicon-database','resource-tree-item');this.setLeadingIcons([icon]);this._model.addEventListener(Resources.IndexedDBModel.Events.DatabaseNamesRefreshed,this._refreshIndexedDB,this);}
get itemURL(){return'indexedDB://'+this._databaseId.securityOrigin+'/'+this._databaseId.name;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Refresh IndexedDB'),this._refreshIndexedDB.bind(this));contextMenu.show();}
_refreshIndexedDB(){this._model.refreshDatabase(this._databaseId);}
indexedDBContentUpdated(objectStoreName){if(this._idbObjectStoreTreeElements[objectStoreName])
this._idbObjectStoreTreeElements[objectStoreName].markNeedsRefresh();}
update(database,entriesUpdated){this._database=database;const objectStoreNames={};const objectStoreNamesSorted=Object.keys(this._database.objectStores).sort();for(const objectStoreName of objectStoreNamesSorted){const objectStore=this._database.objectStores[objectStoreName];objectStoreNames[objectStore.name]=true;if(!this._idbObjectStoreTreeElements[objectStore.name]){const idbObjectStoreTreeElement=new Resources.IDBObjectStoreTreeElement(this._storagePanel,this._model,this._databaseId,objectStore);this._idbObjectStoreTreeElements[objectStore.name]=idbObjectStoreTreeElement;this.appendChild(idbObjectStoreTreeElement);}
this._idbObjectStoreTreeElements[objectStore.name].update(objectStore,entriesUpdated);}
for(const objectStoreName in this._idbObjectStoreTreeElements){if(!objectStoreNames[objectStoreName])
this._objectStoreRemoved(objectStoreName);}
if(this._view)
this._view.update(database);this._updateTooltip();}
_updateTooltip(){this.tooltip=Common.UIString('Version')+': '+this._database.version;if(Object.keys(this._idbObjectStoreTreeElements).length===0)
this.tooltip+=ls` (empty)`;}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view)
this._view=new Resources.IDBDatabaseView(this._model,this._database);this.showView(this._view);return false;}
_objectStoreRemoved(objectStoreName){const objectStoreTreeElement=this._idbObjectStoreTreeElements[objectStoreName];objectStoreTreeElement.clear();this.removeChild(objectStoreTreeElement);delete this._idbObjectStoreTreeElements[objectStoreName];this._updateTooltip();}
clear(){for(const objectStoreName in this._idbObjectStoreTreeElements)
this._objectStoreRemoved(objectStoreName);}};Resources.IDBObjectStoreTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,model,databaseId,objectStore){super(storagePanel,objectStore.name,false);this._model=model;this._databaseId=databaseId;this._idbIndexTreeElements={};this._objectStore=objectStore;this._view=null;const icon=UI.Icon.create('mediumicon-table','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'indexedDB://'+this._databaseId.securityOrigin+'/'+this._databaseId.name+'/'+
this._objectStore.name;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
markNeedsRefresh(){if(this._view)
this._view.markNeedsRefresh();for(const indexName in this._idbIndexTreeElements)
this._idbIndexTreeElements[indexName].markNeedsRefresh();}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Clear'),this._clearObjectStore.bind(this));contextMenu.show();}
_refreshObjectStore(){if(this._view)
this._view.refreshData();for(const indexName in this._idbIndexTreeElements)
this._idbIndexTreeElements[indexName].refreshIndex();}
async _clearObjectStore(){await this._model.clearObjectStore(this._databaseId,this._objectStore.name);this.update(this._objectStore,true);}
update(objectStore,entriesUpdated){this._objectStore=objectStore;const indexNames={};for(const indexName in this._objectStore.indexes){const index=this._objectStore.indexes[indexName];indexNames[index.name]=true;if(!this._idbIndexTreeElements[index.name]){const idbIndexTreeElement=new Resources.IDBIndexTreeElement(this._storagePanel,this._model,this._databaseId,this._objectStore,index,this._refreshObjectStore.bind(this));this._idbIndexTreeElements[index.name]=idbIndexTreeElement;this.appendChild(idbIndexTreeElement);}
this._idbIndexTreeElements[index.name].update(this._objectStore,index,entriesUpdated);}
for(const indexName in this._idbIndexTreeElements){if(!indexNames[indexName])
this._indexRemoved(indexName);}
for(const indexName in this._idbIndexTreeElements){if(!indexNames[indexName]){this.removeChild(this._idbIndexTreeElements[indexName]);delete this._idbIndexTreeElements[indexName];}}
if(this.childCount())
this.expand();if(this._view&&entriesUpdated)
this._view.update(this._objectStore,null);this._updateTooltip();}
_updateTooltip(){const keyPathString=this._objectStore.keyPathString;let tooltipString=keyPathString!==null?(Common.UIString('Key path: ')+keyPathString):'';if(this._objectStore.autoIncrement)
tooltipString+='\n'+Common.UIString('autoIncrement');this.tooltip=tooltipString;}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view){this._view=new Resources.IDBDataView(this._model,this._databaseId,this._objectStore,null,this._refreshObjectStore.bind(this));}
this.showView(this._view);return false;}
_indexRemoved(indexName){const indexTreeElement=this._idbIndexTreeElements[indexName];indexTreeElement.clear();this.removeChild(indexTreeElement);delete this._idbIndexTreeElements[indexName];}
clear(){for(const indexName in this._idbIndexTreeElements)
this._indexRemoved(indexName);if(this._view)
this._view.clear();}};Resources.IDBIndexTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,model,databaseId,objectStore,index,refreshObjectStore){super(storagePanel,index.name,false);this._model=model;this._databaseId=databaseId;this._objectStore=objectStore;this._index=index;this._refreshObjectStore=refreshObjectStore;}
get itemURL(){return'indexedDB://'+this._databaseId.securityOrigin+'/'+this._databaseId.name+'/'+
this._objectStore.name+'/'+this._index.name;}
markNeedsRefresh(){if(this._view)
this._view.markNeedsRefresh();}
refreshIndex(){if(this._view)
this._view.refreshData();}
update(objectStore,index,entriesUpdated){this._objectStore=objectStore;this._index=index;if(this._view&&entriesUpdated)
this._view.update(this._objectStore,this._index);this._updateTooltip();}
_updateTooltip(){const tooltipLines=[];const keyPathString=this._index.keyPathString;tooltipLines.push(Common.UIString('Key path: ')+keyPathString);if(this._index.unique)
tooltipLines.push(Common.UIString('unique'));if(this._index.multiEntry)
tooltipLines.push(Common.UIString('multiEntry'));this.tooltip=tooltipLines.join('\n');}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view){this._view=new Resources.IDBDataView(this._model,this._databaseId,this._objectStore,this._index,this._refreshObjectStore);}
this.showView(this._view);return false;}
clear(){if(this._view)
this._view.clear();}};Resources.DOMStorageTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,domStorage){super(storagePanel,domStorage.securityOrigin?domStorage.securityOrigin:Common.UIString('Local Files'),false);this._domStorage=domStorage;const icon=UI.Icon.create('mediumicon-table','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'storage://'+this._domStorage.securityOrigin+'/'+
(this._domStorage.isLocalStorage?'local':'session');}
onselect(selectedByUser){super.onselect(selectedByUser);this._storagePanel.showDOMStorage(this._domStorage);return false;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Clear'),()=>this._domStorage.clear());contextMenu.show();}};Resources.CookieTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,frame,cookieDomain){super(storagePanel,cookieDomain?cookieDomain:Common.UIString('Local Files'),false);this._target=frame.resourceTreeModel().target();this._cookieDomain=cookieDomain;this.tooltip=ls`cookies used by frames from `+cookieDomain;const icon=UI.Icon.create('mediumicon-cookie','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'cookies://'+this._cookieDomain;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendItem(Common.UIString('Clear'),()=>this._storagePanel.clearCookies(this._target,this._cookieDomain));contextMenu.show();}
onselect(selectedByUser){super.onselect(selectedByUser);this._storagePanel.showCookies(this._target,this._cookieDomain);return false;}};Resources.ApplicationCacheManifestTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,manifestURL){const title=new Common.ParsedURL(manifestURL).displayName;super(storagePanel,title,false);this.tooltip=manifestURL;this._manifestURL=manifestURL;}
get itemURL(){return'appcache://'+this._manifestURL;}
get manifestURL(){return this._manifestURL;}
onselect(selectedByUser){super.onselect(selectedByUser);this._storagePanel.showCategoryView(this._manifestURL,null);return false;}};Resources.ApplicationCacheFrameTreeElement=class extends Resources.BaseStorageTreeElement{constructor(sidebar,frame,manifestURL){super(sidebar._panel,'',false);this._sidebar=sidebar;this._frameId=frame.id;this._manifestURL=manifestURL;this._refreshTitles(frame);const icon=UI.Icon.create('largeicon-navigator-folder','navigator-tree-item');icon.classList.add('navigator-folder-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'appcache://'+this._manifestURL+'/'+encodeURI(this.titleAsText());}
get frameId(){return this._frameId;}
get manifestURL(){return this._manifestURL;}
_refreshTitles(frame){this.title=frame.displayName();}
frameNavigated(frame){this._refreshTitles(frame);}
onselect(selectedByUser){super.onselect(selectedByUser);this._sidebar._showApplicationCache(this._frameId);return false;}};Resources.StorageCategoryView=class extends UI.VBox{constructor(){super();this.element.classList.add('storage-view');this._emptyWidget=new UI.EmptyWidget('');this._linkElement=null;this._emptyWidget.show(this.element);}
setText(text){this._emptyWidget.text=text;}
setLink(link){if(link&&!this._linkElement)
this._linkElement=this._emptyWidget.appendLink(link);if(!link&&this._linkElement)
this._linkElement.classList.add('hidden');if(link&&this._linkElement){this._linkElement.setAttribute('href',link);this._linkElement.classList.remove('hidden');}}};;Resources.ResourcesSection=class{constructor(storagePanel,treeElement){this._panel=storagePanel;this._treeElement=treeElement;this._treeElementForFrameId=new Map();function addListener(eventType,handler,target){SDK.targetManager.addModelListener(SDK.ResourceTreeModel,eventType,event=>handler.call(target,event.data));}
addListener(SDK.ResourceTreeModel.Events.FrameAdded,this._frameAdded,this);addListener(SDK.ResourceTreeModel.Events.FrameNavigated,this._frameNavigated,this);addListener(SDK.ResourceTreeModel.Events.FrameDetached,this._frameDetached,this);addListener(SDK.ResourceTreeModel.Events.ResourceAdded,this._resourceAdded,this);const mainTarget=SDK.targetManager.mainTarget();const resourceTreeModel=mainTarget&&mainTarget.model(SDK.ResourceTreeModel);const mainFrame=resourceTreeModel&&resourceTreeModel.mainFrame;if(mainFrame)
this._frameAdded(mainFrame);}
static _getParentFrame(frame){const parentFrame=frame.parentFrame;if(parentFrame)
return parentFrame;const parentTarget=frame.resourceTreeModel().target().parentTarget();if(!parentTarget)
return null;return parentTarget.model(SDK.ResourceTreeModel).mainFrame;}
_expandFrame(frame){if(!frame)
return false;let treeElement=this._treeElementForFrameId.get(frame.id);if(!treeElement&&!this._expandFrame(Resources.ResourcesSection._getParentFrame(frame)))
return false;treeElement=this._treeElementForFrameId.get(frame.id);if(!treeElement)
return false;treeElement.expand();return true;}
async revealResource(resource,line,column){if(!this._expandFrame(resource.frame()))
return;const resourceTreeElement=Resources.FrameResourceTreeElement.forResource(resource);if(resourceTreeElement)
await resourceTreeElement.revealResource(line,column);}
_frameAdded(frame){const parentFrame=Resources.ResourcesSection._getParentFrame(frame);const parentTreeElement=parentFrame?this._treeElementForFrameId.get(parentFrame.id):this._treeElement;if(!parentTreeElement)
return;const frameTreeElement=new Resources.FrameTreeElement(this,frame);this._treeElementForFrameId.set(frame.id,frameTreeElement);parentTreeElement.appendChild(frameTreeElement);}
_frameDetached(frame){const frameTreeElement=this._treeElementForFrameId.get(frame.id);if(!frameTreeElement)
return;this._treeElementForFrameId.remove(frame.id);if(frameTreeElement.parent)
frameTreeElement.parent.removeChild(frameTreeElement);}
_frameNavigated(frame){const frameTreeElement=this._treeElementForFrameId.get(frame.id);if(frameTreeElement)
frameTreeElement.frameNavigated(frame);}
_resourceAdded(resource){const frameTreeElement=this._treeElementForFrameId.get(resource.frameId);if(!frameTreeElement){return;}
frameTreeElement.appendResource(resource);}
reset(){this._treeElement.removeChildren();this._treeElementForFrameId.clear();}};Resources.FrameTreeElement=class extends Resources.BaseStorageTreeElement{constructor(section,frame){super(section._panel,'',false);this._populated=false;this._section=section;this._frame=frame;this._frameId=frame.id;this._categoryElements={};this._treeElementForResource={};this.setExpandable(true);this.frameNavigated(frame);const icon=UI.Icon.create('largeicon-navigator-frame','navigator-tree-item');icon.classList.add('navigator-frame-tree-item');this.setLeadingIcons([icon]);}
frameNavigated(frame){this.invalidateChildren();this._frameId=frame.id;this.title=frame.displayName();this._categoryElements={};this._treeElementForResource={};}
get itemURL(){return'frame://'+encodeURI(this.titleAsText());}
onselect(selectedByUser){super.onselect(selectedByUser);this._section._panel.showCategoryView(this.titleAsText(),null);this.listItemElement.classList.remove('hovered');SDK.OverlayModel.hideDOMNodeHighlight();return false;}
set hovered(hovered){if(hovered){this.listItemElement.classList.add('hovered');this._frame.resourceTreeModel().domModel().overlayModel().highlightFrame(this._frameId);}else{this.listItemElement.classList.remove('hovered');SDK.OverlayModel.hideDOMNodeHighlight();}}
appendResource(resource){if(!this._populated)
return;const statusCode=resource['statusCode'];if(statusCode>=301&&statusCode<=303)
return;const resourceType=resource.resourceType();const categoryName=resourceType.name();let categoryElement=resourceType===Common.resourceTypes.Document?this:this._categoryElements[categoryName];if(!categoryElement){categoryElement=new Resources.StorageCategoryTreeElement(this._section._panel,resource.resourceType().category().title,categoryName);this._categoryElements[resourceType.name()]=categoryElement;this._insertInPresentationOrder(this,categoryElement);}
const resourceTreeElement=new Resources.FrameResourceTreeElement(this._section._panel,resource);this._insertInPresentationOrder(categoryElement,resourceTreeElement);this._treeElementForResource[resource.url]=resourceTreeElement;}
resourceByURL(url){const treeElement=this._treeElementForResource[url];return treeElement?treeElement._resource:null;}
appendChild(treeElement){if(!this._populated)
return;this._insertInPresentationOrder(this,treeElement);}
_insertInPresentationOrder(parentTreeElement,childTreeElement){function typeWeight(treeElement){if(treeElement instanceof Resources.StorageCategoryTreeElement)
return 2;if(treeElement instanceof Resources.FrameTreeElement)
return 1;return 3;}
function compare(treeElement1,treeElement2){const typeWeight1=typeWeight(treeElement1);const typeWeight2=typeWeight(treeElement2);let result;if(typeWeight1>typeWeight2)
result=1;else if(typeWeight1<typeWeight2)
result=-1;else
result=treeElement1.titleAsText().localeCompare(treeElement2.titleAsText());return result;}
const childCount=parentTreeElement.childCount();let i;for(i=0;i<childCount;++i){if(compare(childTreeElement,parentTreeElement.childAt(i))<0)
break;}
parentTreeElement.insertChild(childTreeElement,i);}
onpopulate(){this._populated=true;for(const child of this._frame.childFrames)
this._section._frameAdded(child);for(const resource of this._frame.resources())
this.appendResource(resource);}};Resources.FrameResourceTreeElement=class extends Resources.BaseStorageTreeElement{constructor(storagePanel,resource){super(storagePanel,resource.displayName,false);this._panel=storagePanel;this._resource=resource;this._previewPromise=null;this.tooltip=resource.url;this._resource[Resources.FrameResourceTreeElement._symbol]=this;const icon=UI.Icon.create('largeicon-navigator-file','navigator-tree-item');icon.classList.add('navigator-file-tree-item');icon.classList.add('navigator-'+resource.resourceType().name()+'-tree-item');this.setLeadingIcons([icon]);}
static forResource(resource){return resource[Resources.FrameResourceTreeElement._symbol];}
get itemURL(){return this._resource.url;}
_preparePreview(){if(this._previewPromise)
return this._previewPromise;const viewPromise=SourceFrame.PreviewFactory.createPreview(this._resource,this._resource.mimeType);this._previewPromise=viewPromise.then(view=>{if(view)
return view;return new UI.EmptyWidget(this._resource.url);});return this._previewPromise;}
onselect(selectedByUser){super.onselect(selectedByUser);this._panel.scheduleShowView(this._preparePreview());return false;}
ondblclick(event){InspectorFrontendHost.openInNewTab(this._resource.url);return false;}
onattach(){super.onattach();this.listItemElement.draggable=true;this.listItemElement.addEventListener('dragstart',this._ondragstart.bind(this),false);this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_ondragstart(event){event.dataTransfer.setData('text/plain',this._resource.content||'');event.dataTransfer.effectAllowed='copy';return true;}
_handleContextMenuEvent(event){const contextMenu=new UI.ContextMenu(event);contextMenu.appendApplicableItems(this._resource);contextMenu.show();}
async revealResource(line,column){this.revealAndSelect(true);const view=await this._panel.scheduleShowView(this._preparePreview());if(!(view instanceof SourceFrame.ResourceSourceFrame)||typeof line!=='number')
return;view.revealPosition(line,column,true);}};Resources.FrameResourceTreeElement._symbol=Symbol('treeElement');;Resources.ServiceWorkerCacheView=class extends UI.SimpleView{constructor(model,cache){super(Common.UIString('Cache'));this.registerRequiredCSS('resources/serviceWorkerCacheViews.css');this._model=model;this._entriesForTest=null;this.element.classList.add('service-worker-cache-data-view');this.element.classList.add('storage-view');const editorToolbar=new UI.Toolbar('data-view-toolbar',this.element);this._splitWidget=new UI.SplitWidget(false,false);this._splitWidget.show(this.element);this._previewPanel=new UI.VBox();const resizer=this._previewPanel.element.createChild('div','cache-preview-panel-resizer');this._splitWidget.setMainWidget(this._previewPanel);this._splitWidget.installResizer(resizer);this._preview=null;this._cache=cache;this._dataGrid=null;this._lastPageSize=null;this._lastSkipCount=null;this._refreshThrottler=new Common.Throttler(300);this._pageBackButton=new UI.ToolbarButton(Common.UIString('Show previous page'),'largeicon-play-back');this._pageBackButton.addEventListener(UI.ToolbarButton.Events.Click,this._pageBackButtonClicked,this);editorToolbar.appendToolbarItem(this._pageBackButton);this._pageForwardButton=new UI.ToolbarButton(Common.UIString('Show next page'),'largeicon-play');this._pageForwardButton.setEnabled(false);this._pageForwardButton.addEventListener(UI.ToolbarButton.Events.Click,this._pageForwardButtonClicked,this);editorToolbar.appendToolbarItem(this._pageForwardButton);this._refreshButton=new UI.ToolbarButton(Common.UIString('Refresh'),'largeicon-refresh');this._refreshButton.addEventListener(UI.ToolbarButton.Events.Click,this._refreshButtonClicked,this);editorToolbar.appendToolbarItem(this._refreshButton);this._deleteSelectedButton=new UI.ToolbarButton(Common.UIString('Delete Selected'),'largeicon-delete');this._deleteSelectedButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._deleteButtonClicked(null));editorToolbar.appendToolbarItem(this._deleteSelectedButton);const entryPathFilterBox=new UI.ToolbarInput(ls`Filter by Path`,1);editorToolbar.appendToolbarItem(entryPathFilterBox);const entryPathFilterThrottler=new Common.Throttler(300);this._entryPathFilter='';entryPathFilterBox.addEventListener(UI.ToolbarInput.Event.TextChanged,()=>{entryPathFilterThrottler.schedule(()=>{this._entryPathFilter=entryPathFilterBox.value();this._skipCount=0;return this._updateData(true);});});this._pageSize=50;this._skipCount=0;this._returnCount=(null);this._summaryBarElement=(null);this.update(cache);}
_resetDataGrid(){if(this._dataGrid)
this._dataGrid.asWidget().detach();this._dataGrid=this._createDataGrid();const dataGridWidget=this._dataGrid.asWidget();this._splitWidget.setSidebarWidget(dataGridWidget);dataGridWidget.setMinimumSize(0,250);this._skipCount=0;}
wasShown(){this._model.addEventListener(SDK.ServiceWorkerCacheModel.Events.CacheStorageContentUpdated,this._cacheContentUpdated,this);this._updateData(true);}
willHide(){this._model.removeEventListener(SDK.ServiceWorkerCacheModel.Events.CacheStorageContentUpdated,this._cacheContentUpdated,this);}
_showPreview(preview){if(preview&&this._preview===preview)
return;if(this._preview)
this._preview.detach();if(!preview)
preview=new UI.EmptyWidget(Common.UIString('Select a cache entry above to preview'));this._preview=preview;this._preview.show(this._previewPanel.element);}
_createDataGrid(){const columns=([{id:'number',title:'#',sortable:false,width:'3px'},{id:'name',title:Common.UIString('Name'),weight:4,sortable:true},{id:'responseType',title:ls`Response-Type`,weight:1,align:DataGrid.DataGrid.Align.Right,sortable:true},{id:'contentType',title:Common.UIString('Content-Type'),weight:1,sortable:true},{id:'contentLength',title:Common.UIString('Content-Length'),weight:1,align:DataGrid.DataGrid.Align.Right,sortable:true},{id:'responseTime',title:Common.UIString('Time Cached'),width:'12em',weight:1,align:DataGrid.DataGrid.Align.Right,sortable:true}]);const dataGrid=new DataGrid.DataGrid(columns,undefined,this._deleteButtonClicked.bind(this),this._updateData.bind(this,true));dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortingChanged,this);dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,event=>this._previewCachedResponse(event.data.data),this);dataGrid.setStriped(true);return dataGrid;}
_sortingChanged(){if(!this._dataGrid)
return;const accending=this._dataGrid.isSortOrderAscending();const columnId=this._dataGrid.sortColumnId();let comparator;if(columnId==='name')
comparator=(a,b)=>a._path.localeCompare(b._path);else if(columnId==='contentType')
comparator=(a,b)=>a.data.mimeType.localeCompare(b.data.mimeType);else if(columnId==='contentLength')
comparator=(a,b)=>a.data.resourceSize-b.data.resourceSize;else if(columnId==='responseTime')
comparator=(a,b)=>a.data.endTime-b.data.endTime;const children=this._dataGrid.rootNode().children.slice();this._dataGrid.rootNode().removeChildren();children.sort((a,b)=>{const result=comparator(a,b);return accending?result:-result;});children.forEach(child=>this._dataGrid.rootNode().appendChild(child));}
_pageBackButtonClicked(event){this._skipCount=Math.max(0,this._skipCount-this._pageSize);this._updateData(false);}
_pageForwardButtonClicked(event){this._skipCount=this._skipCount+this._pageSize;this._updateData(false);}
async _deleteButtonClicked(node){if(!node){node=this._dataGrid&&this._dataGrid.selectedNode;if(!node)
return;}
await this._model.deleteCacheEntry(this._cache,(node.data.url()));node.remove();}
update(cache){this._cache=cache;this._resetDataGrid();this._updateData(true);}
_updateSummaryBar(){if(!this._summaryBarElement)
this._summaryBarElement=this.element.createChild('div','cache-storage-summary-bar');this._summaryBarElement.removeChildren();const span=this._summaryBarElement.createChild('span');if(this._entryPathFilter)
span.textContent=ls`Matching entries: ${this._returnCount}`;else
span.textContent=ls`Total entries: ${this._returnCount}`;}
_updateDataCallback(skipCount,entries,returnCount){const selected=this._dataGrid.selectedNode&&this._dataGrid.selectedNode.data.url();this._refreshButton.setEnabled(true);this._entriesForTest=entries;this._returnCount=returnCount;this._updateSummaryBar();const hasMore=(this._skipCount+this._pageSize)<returnCount;const oldEntries=new Map();const rootNode=this._dataGrid.rootNode();for(const node of rootNode.children)
oldEntries.set(node.data.url,node);rootNode.removeChildren();let selectedNode=null;for(let i=0;i<entries.length;++i){const entry=entries[i];let node=oldEntries.get(entry.requestURL);if(!node||node.data.responseTime!==entry.responseTime){node=new Resources.ServiceWorkerCacheView.DataGridNode(i+this._skipCount,this._createRequest(entry),entry.responseType);node.selectable=true;}else{node.data.number=i+this._skipCount;}
rootNode.appendChild(node);if(entry.requestURL===selected)
selectedNode=node;}
this._pageBackButton.setEnabled(!!skipCount);this._pageForwardButton.setEnabled(hasMore);if(!selectedNode)
this._showPreview(null);else
selectedNode.revealAndSelect();this._updatedForTest();}
_updateData(force){const pageSize=this._pageSize;let skipCount=this._skipCount;if(!force&&this._lastPageSize===pageSize&&this._lastSkipCount===skipCount)
return;this._refreshButton.setEnabled(false);if(this._lastPageSize!==pageSize){skipCount=0;this._skipCount=0;}
this._lastPageSize=pageSize;this._lastSkipCount=skipCount;return new Promise(resolve=>{this._model.loadCacheData(this._cache,skipCount,pageSize,this._entryPathFilter,(entries,returnCount)=>{this._updateDataCallback(skipCount,entries,returnCount);resolve();});});}
_refreshButtonClicked(event){this._updateData(true);}
_cacheContentUpdated(event){const nameAndOrigin=event.data;if(this._cache.securityOrigin!==nameAndOrigin.origin||this._cache.cacheName!==nameAndOrigin.cacheName)
return;this._refreshThrottler.schedule(()=>Promise.resolve(this._updateData(true)),true);}
async _previewCachedResponse(request){let preview=request[Resources.ServiceWorkerCacheView._previewSymbol];if(!preview){preview=new Resources.ServiceWorkerCacheView.RequestView(request);request[Resources.ServiceWorkerCacheView._previewSymbol]=preview;}
if(request===this._dataGrid.selectedNode.data)
this._showPreview(preview);}
_createRequest(entry){const request=new SDK.NetworkRequest('cache-storage-'+entry.requestURL,entry.requestURL,'','','',null);request.requestMethod=entry.requestMethod;request.setRequestHeaders(entry.requestHeaders);request.statusCode=entry.responseStatus;request.statusText=entry.responseStatusText;request.protocol=new Common.ParsedURL(entry.requestURL).scheme;request.responseHeaders=entry.responseHeaders;request.setRequestHeadersText('');request.endTime=entry.responseTime;let header=entry.responseHeaders.find(header=>header.name.toLowerCase()==='content-type');const contentType=header?header.value:'text/plain';request.mimeType=contentType;header=entry.responseHeaders.find(header=>header.name.toLowerCase()==='content-length');request.resourceSize=(header&&header.value)|0;let resourceType=Common.ResourceType.fromMimeType(contentType);if(!resourceType)
resourceType=Common.ResourceType.fromURL(entry.requestURL)||Common.resourceTypes.Other;request.setResourceType(resourceType);request.setContentDataProvider(this._requestContent.bind(this,request));return request;}
async _requestContent(request){const isText=request.resourceType().isTextType();const contentData={error:null,content:null,encoded:!isText};const response=await this._cache.requestCachedResponse(request.url(),request.requestHeaders());if(response)
contentData.content=isText?window.atob(response.body):response.body;return contentData;}
_updatedForTest(){}};Resources.ServiceWorkerCacheView._previewSymbol=Symbol('preview');Resources.ServiceWorkerCacheView._RESPONSE_CACHE_SIZE=10;Resources.ServiceWorkerCacheView.DataGridNode=class extends DataGrid.DataGridNode{constructor(number,request,responseType){super(request);this._number=number;const parsed=new Common.ParsedURL(request.url());if(parsed.isValid)
this._name=request.url().trimURL(parsed.domain());else
this._name=request.url();this._request=request;this._responseType=responseType;}
createCell(columnId){const cell=this.createTD(columnId);let value;if(columnId==='number'){value=String(this._number);}else if(columnId==='name'){value=this._name;}else if(columnId==='responseType'){if(this._responseType==='opaqueResponse')
value='opaque';else if(this._responseType==='opaqueRedirect')
value='opaqueredirect';else
value=this._responseType;}else if(columnId==='contentType'){value=this._request.mimeType;}else if(columnId==='contentLength'){value=(this._request.resourceSize|0).toLocaleString('en-US');}else if(columnId==='responseTime'){value=new Date(this._request.endTime*1000).toLocaleString();}
DataGrid.DataGrid.setElementText(cell,value||'',true);cell.title=this._request.url();return cell;}};Resources.ServiceWorkerCacheView.RequestView=class extends UI.VBox{constructor(request){super();this._tabbedPane=new UI.TabbedPane();this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);this._resourceViewTabSetting=Common.settings.createSetting('cacheStorageViewTab','preview');this._tabbedPane.appendTab('headers',Common.UIString('Headers'),new Network.RequestHeadersView(request));this._tabbedPane.appendTab('preview',Common.UIString('Preview'),new Network.RequestPreviewView(request));this._tabbedPane.show(this.element);}
wasShown(){super.wasShown();this._selectTab();}
_selectTab(tabId){if(!tabId)
tabId=this._resourceViewTabSetting.get();if(!this._tabbedPane.selectTab(tabId))
this._tabbedPane.selectTab('headers');}
_tabSelected(event){if(!event.data.isUserGesture)
return;this._resourceViewTabSetting.set(event.data.tabId);}};;Resources.ServiceWorkersView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('resources/serviceWorkersView.css');this._currentWorkersView=new UI.ReportView(Common.UIString('Service Workers'));this._currentWorkersView.setBodyScrollable(false);this.contentElement.classList.add('service-worker-list');this._currentWorkersView.show(this.contentElement);this._currentWorkersView.element.classList.add('service-workers-this-origin');this._toolbar=this._currentWorkersView.createToolbar();this._toolbar.makeWrappable(true);this._sections=new Map();this._registrationSymbol=Symbol('Resources.ServiceWorkersView');this._manager=null;this._securityOriginManager=null;this._filterThrottler=new Common.Throttler(300);this._otherWorkers=this.contentElement.createChild('div','service-workers-other-origin');this._otherSWFilter=this._otherWorkers.createChild('div','service-worker-filter');this._otherSWFilter.setAttribute('tabindex',0);this._otherSWFilter.setAttribute('role','switch');this._otherSWFilter.setAttribute('aria-checked',false);this._otherSWFilter.addEventListener('keydown',event=>{if(event.target!==this._otherSWFilter)
return;if(isEnterKey(event)||event.key===' ')
this._toggleFilter();});const filterLabel=this._otherSWFilter.createChild('label','service-worker-filter-label');filterLabel.textContent=Common.UIString('Service workers from other origins');filterLabel.addEventListener('click',()=>this._toggleFilter());const toolbar=new UI.Toolbar('service-worker-filter-toolbar',this._otherSWFilter);this._filter=new UI.ToolbarInput(ls`Filter service worker`,1);this._filter.addEventListener(UI.ToolbarInput.Event.TextChanged,()=>this._filterChanged());toolbar.appendToolbarItem(this._filter);this._otherWorkersView=new UI.ReportView();this._otherWorkersView.setBodyScrollable(false);this._otherWorkersView.show(this._otherWorkers);this._otherWorkersView.element.classList.add('service-workers-for-other-origins');this._updateCollapsedStyle();this._toolbar.appendToolbarItem(MobileThrottling.throttlingManager().createOfflineToolbarCheckbox());const updateOnReloadSetting=Common.settings.createSetting('serviceWorkerUpdateOnReload',false);updateOnReloadSetting.setTitle(Common.UIString('Update on reload'));const forceUpdate=new UI.ToolbarSettingCheckbox(updateOnReloadSetting,ls`On page reload, force the service worker to update, and activate it`);this._toolbar.appendToolbarItem(forceUpdate);const bypassServiceWorkerSetting=Common.settings.createSetting('bypassServiceWorker',false);bypassServiceWorkerSetting.setTitle(Common.UIString('Bypass for network'));const fallbackToNetwork=new UI.ToolbarSettingCheckbox(bypassServiceWorkerSetting,ls`Bypass the service worker and load resources from the network`);this._toolbar.appendToolbarItem(fallbackToNetwork);this._eventListeners=new Map();SDK.targetManager.observeModels(SDK.ServiceWorkerManager,this);this._updateListVisibility();}
modelAdded(serviceWorkerManager){if(this._manager)
return;this._manager=serviceWorkerManager;this._securityOriginManager=serviceWorkerManager.target().model(SDK.SecurityOriginManager);for(const registration of this._manager.registrations().values())
this._updateRegistration(registration);this._eventListeners.set(serviceWorkerManager,[this._manager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationUpdated,this._registrationUpdated,this),this._manager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationDeleted,this._registrationDeleted,this),this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginAdded,this._updateSectionVisibility,this),this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,this._updateSectionVisibility,this),]);}
modelRemoved(serviceWorkerManager){if(!this._manager||this._manager!==serviceWorkerManager)
return;Common.EventTarget.removeEventListeners(this._eventListeners.get(serviceWorkerManager));this._eventListeners.delete(serviceWorkerManager);this._manager=null;this._securityOriginManager=null;}
_getTimeStamp(registration){const versions=registration.versionsByMode();let timestamp=0;const active=versions.get(SDK.ServiceWorkerVersion.Modes.Active);const installing=versions.get(SDK.ServiceWorkerVersion.Modes.Installing);const waiting=versions.get(SDK.ServiceWorkerVersion.Modes.Waiting);const redundant=versions.get(SDK.ServiceWorkerVersion.Modes.Redundant);if(active)
timestamp=active.scriptResponseTime;else if(waiting)
timestamp=waiting.scriptResponseTime;else if(installing)
timestamp=installing.scriptResponseTime;else if(redundant)
timestamp=redundant.scriptResponseTime;return timestamp;}
_updateSectionVisibility(){let hasOthers=false;let hasThis=false;const movedSections=[];for(const section of this._sections.values()){const expectedView=this._getReportViewForOrigin(section._registration.securityOrigin);hasOthers|=expectedView===this._otherWorkersView;hasThis|=expectedView===this._currentWorkersView;if(section._section.parentWidget()!==expectedView)
movedSections.push(section);}
for(const section of movedSections){const registration=section._registration;this._removeRegistrationFromList(registration);this._updateRegistration(registration,true);}
this._currentWorkersView.sortSections((a,b)=>{const aTimestamp=this._getTimeStamp(a[this._registrationSymbol]);const bTimestamp=this._getTimeStamp(b[this._registrationSymbol]);return bTimestamp-aTimestamp;});const scorer=new Sources.FilePathScoreFunction(this._filter.value());this._otherWorkersView.sortSections((a,b)=>{const cmp=scorer.score(b.title(),null)-scorer.score(a.title(),null);return cmp===0?a.title().localeCompare(b.title()):cmp;});for(const section of this._sections.values()){if(section._section.parentWidget()===this._currentWorkersView||this._isRegistrationVisible(section._registration))
section._section.showWidget();else
section._section.hideWidget();}
this.contentElement.classList.toggle('service-worker-has-current',hasThis);this._otherWorkers.classList.toggle('hidden',!hasOthers);this._updateListVisibility();}
_registrationUpdated(event){const registration=(event.data);this._updateRegistration(registration);this._gcRegistrations();}
_gcRegistrations(){let hasNonDeletedRegistrations=false;const securityOrigins=new Set(this._securityOriginManager.securityOrigins());for(const registration of this._manager.registrations().values()){if(!securityOrigins.has(registration.securityOrigin)&&!this._isRegistrationVisible(registration))
continue;if(!registration.canBeRemoved()){hasNonDeletedRegistrations=true;break;}}
if(!hasNonDeletedRegistrations)
return;for(const registration of this._manager.registrations().values()){const visible=securityOrigins.has(registration.securityOrigin)||this._isRegistrationVisible(registration);if(!visible&&registration.canBeRemoved())
this._removeRegistrationFromList(registration);}}
_getReportViewForOrigin(origin){if(this._securityOriginManager.securityOrigins().includes(origin)||this._securityOriginManager.unreachableMainSecurityOrigin()===origin)
return this._currentWorkersView;else
return this._otherWorkersView;}
_updateRegistration(registration,skipUpdate){let section=this._sections.get(registration);if(!section){const title=Resources.ServiceWorkersView._displayScopeURL(registration.scopeURL);const uiSection=this._getReportViewForOrigin(registration.securityOrigin).appendSection(title);uiSection[this._registrationSymbol]=registration;section=new Resources.ServiceWorkersView.Section((this._manager),uiSection,registration);this._sections.set(registration,section);}
if(skipUpdate)
return;this._updateSectionVisibility();section._scheduleUpdate();}
_registrationDeleted(event){const registration=(event.data);this._removeRegistrationFromList(registration);}
_removeRegistrationFromList(registration){const section=this._sections.get(registration);if(section)
section._section.detach();this._sections.delete(registration);this._updateSectionVisibility();}
_isRegistrationVisible(registration){const filterString=this._filter.value();if(!filterString||!registration.scopeURL)
return true;const regex=String.filterRegex(filterString);return registration.scopeURL.match(regex);}
_filterChanged(){this._updateCollapsedStyle();this._filterThrottler.schedule(()=>Promise.resolve(this._updateSectionVisibility()));}
_updateCollapsedStyle(){const expanded=this._otherSWFilter.getAttribute('aria-checked')==='true';this._otherWorkers.classList.toggle('service-worker-filter-collapsed',!expanded);if(expanded)
this._otherWorkersView.showWidget();else
this._otherWorkersView.hideWidget();this._otherWorkersView.setHeaderVisible(false);}
static _displayScopeURL(scopeURL){const parsedURL=scopeURL.asParsedURL();let path=parsedURL.path;if(path.endsWith('/'))
path=path.substring(0,path.length-1);return parsedURL.domain()+path;}
_updateListVisibility(){this.contentElement.classList.toggle('service-worker-list-empty',this._sections.size===0);}
_toggleFilter(){const expanded=this._otherSWFilter.getAttribute('aria-checked')==='true';this._otherSWFilter.setAttribute('aria-checked',!expanded);this._filterChanged();}};Resources.ServiceWorkersView.Section=class{constructor(manager,section,registration){this._manager=manager;this._section=section;this._registration=registration;this._fingerprint=null;this._pushNotificationDataSetting=Common.settings.createLocalSetting('pushData',Common.UIString('Test push message from DevTools.'));this._syncTagNameSetting=Common.settings.createLocalSetting('syncTagName','test-tag-from-devtools');this._toolbar=section.createToolbar();this._toolbar.renderAsLinks();this._updateButton=new UI.ToolbarButton(Common.UIString('Update'),undefined,Common.UIString('Update'));this._updateButton.addEventListener(UI.ToolbarButton.Events.Click,this._updateButtonClicked,this);this._toolbar.appendToolbarItem(this._updateButton);this._deleteButton=new UI.ToolbarButton(Common.UIString('Unregister service worker'),undefined,Common.UIString('Unregister'));this._deleteButton.addEventListener(UI.ToolbarButton.Events.Click,this._unregisterButtonClicked,this);this._toolbar.appendToolbarItem(this._deleteButton);this._sourceField=this._wrapWidget(this._section.appendField(Common.UIString('Source')));this._statusField=this._wrapWidget(this._section.appendField(Common.UIString('Status')));this._clientsField=this._wrapWidget(this._section.appendField(Common.UIString('Clients')));this._createSyncNotificationField(Common.UIString('Push'),this._pushNotificationDataSetting.get(),Common.UIString('Push data'),this._push.bind(this));this._createSyncNotificationField(Common.UIString('Sync'),this._syncTagNameSetting.get(),Common.UIString('Sync tag'),this._sync.bind(this));this._linkifier=new Components.Linkifier();this._clientInfoCache=new Map();this._throttler=new Common.Throttler(500);}
_createSyncNotificationField(label,initialValue,placeholder,callback){const form=this._wrapWidget(this._section.appendField(label)).createChild('form','service-worker-editor-with-button');const editor=form.createChild('input','source-code service-worker-notification-editor');const button=UI.createTextButton(label);button.type='submit';form.appendChild(button);editor.value=initialValue;editor.placeholder=placeholder;UI.ARIAUtils.setAccessibleName(editor,label);form.addEventListener('submit',e=>{callback(editor.value||'');e.consume(true);});}
_scheduleUpdate(){if(Resources.ServiceWorkersView._noThrottle){this._update();return;}
this._throttler.schedule(this._update.bind(this));}
_targetForVersionId(versionId){const version=this._manager.findVersion(versionId);if(!version||!version.targetId)
return null;return SDK.targetManager.targetById(version.targetId);}
_addVersion(versionsStack,icon,label){const installingEntry=versionsStack.createChild('div','service-worker-version');installingEntry.createChild('div',icon);installingEntry.createChild('span').textContent=label;return installingEntry;}
_updateClientsField(version){this._clientsField.removeChildren();this._section.setFieldVisible(Common.UIString('Clients'),version.controlledClients.length);for(const client of version.controlledClients){const clientLabelText=this._clientsField.createChild('div','service-worker-client');if(this._clientInfoCache.has(client)){this._updateClientInfo(clientLabelText,(this._clientInfoCache.get(client)));}
this._manager.target().targetAgent().getTargetInfo(client).then(this._onClientInfo.bind(this,clientLabelText));}}
_updateSourceField(version){this._sourceField.removeChildren();const fileName=Common.ParsedURL.extractName(version.scriptURL);const name=this._sourceField.createChild('div','report-field-value-filename');const link=Components.Linkifier.linkifyURL(version.scriptURL,{text:fileName});link.tabIndex=0;name.appendChild(link);if(this._registration.errors.length){const errorsLabel=UI.createIconLabel(String(this._registration.errors.length),'smallicon-error');errorsLabel.classList.add('link');errorsLabel.tabIndex=0;UI.ARIAUtils.setAccessibleName(errorsLabel,ls`${this._registration.errors.length} registration errors`);errorsLabel.addEventListener('click',()=>Common.console.show());errorsLabel.addEventListener('keydown',event=>{if(isEnterKey(event)||event.key===' ')
Common.console.show();});name.appendChild(errorsLabel);}
this._sourceField.createChild('div','report-field-value-subtitle').textContent=Common.UIString('Received %s',new Date(version.scriptResponseTime*1000).toLocaleString());}
_update(){const fingerprint=this._registration.fingerprint();if(fingerprint===this._fingerprint)
return Promise.resolve();this._fingerprint=fingerprint;this._toolbar.setEnabled(!this._registration.isDeleted);const versions=this._registration.versionsByMode();const scopeURL=Resources.ServiceWorkersView._displayScopeURL(this._registration.scopeURL);const title=this._registration.isDeleted?Common.UIString('%s - deleted',scopeURL):scopeURL;this._section.setTitle(title);const active=versions.get(SDK.ServiceWorkerVersion.Modes.Active);const waiting=versions.get(SDK.ServiceWorkerVersion.Modes.Waiting);const installing=versions.get(SDK.ServiceWorkerVersion.Modes.Installing);const redundant=versions.get(SDK.ServiceWorkerVersion.Modes.Redundant);this._statusField.removeChildren();const versionsStack=this._statusField.createChild('div','service-worker-version-stack');versionsStack.createChild('div','service-worker-version-stack-bar');if(active){this._updateSourceField(active);const activeEntry=this._addVersion(versionsStack,'service-worker-active-circle',Common.UIString('#%s activated and is %s',active.id,active.runningStatus));if(active.isRunning()||active.isStarting()){this._createLink(activeEntry,Common.UIString('stop'),this._stopButtonClicked.bind(this,active.id));if(!this._targetForVersionId(active.id))
this._createLink(activeEntry,Common.UIString('inspect'),this._inspectButtonClicked.bind(this,active.id));}else if(active.isStartable()){this._createLink(activeEntry,Common.UIString('start'),this._startButtonClicked.bind(this));}
this._updateClientsField(active);}else if(redundant){this._updateSourceField(redundant);this._addVersion(versionsStack,'service-worker-redundant-circle',Common.UIString('#%s is redundant',redundant.id));this._updateClientsField(redundant);}
if(waiting){const waitingEntry=this._addVersion(versionsStack,'service-worker-waiting-circle',Common.UIString('#%s waiting to activate',waiting.id));this._createLink(waitingEntry,Common.UIString('skipWaiting'),this._skipButtonClicked.bind(this));waitingEntry.createChild('div','service-worker-subtitle').textContent=Common.UIString('Received %s',new Date(waiting.scriptResponseTime*1000).toLocaleString());if(!this._targetForVersionId(waiting.id)&&(waiting.isRunning()||waiting.isStarting()))
this._createLink(waitingEntry,Common.UIString('inspect'),this._inspectButtonClicked.bind(this,waiting.id));}
if(installing){const installingEntry=this._addVersion(versionsStack,'service-worker-installing-circle',Common.UIString('#%s trying to install',installing.id));installingEntry.createChild('div','service-worker-subtitle').textContent=Common.UIString('Received %s',new Date(installing.scriptResponseTime*1000).toLocaleString());if(!this._targetForVersionId(installing.id)&&(installing.isRunning()||installing.isStarting())){this._createLink(installingEntry,Common.UIString('inspect'),this._inspectButtonClicked.bind(this,installing.id));}}
return Promise.resolve();}
_createLink(parent,title,listener,className,useCapture){const button=parent.createChild('button',className);button.classList.add('link');button.textContent=title;button.tabIndex=0;button.addEventListener('click',listener,useCapture);return button;}
_unregisterButtonClicked(event){this._manager.deleteRegistration(this._registration.id);}
_updateButtonClicked(event){this._manager.updateRegistration(this._registration.id);}
_push(data){this._pushNotificationDataSetting.set(data);this._manager.deliverPushMessage(this._registration.id,data);}
_sync(tag){this._syncTagNameSetting.set(tag);this._manager.dispatchSyncEvent(this._registration.id,tag,true);}
_onClientInfo(element,targetInfo){if(!targetInfo)
return;this._clientInfoCache.set(targetInfo.targetId,targetInfo);this._updateClientInfo(element,targetInfo);}
_updateClientInfo(element,targetInfo){if(targetInfo.type!=='page'&&targetInfo.type==='iframe'){const clientString=element.createChild('span','service-worker-client-string');clientString.createTextChild(ls`Worker: ${targetInfo.url}`);return;}
element.removeChildren();const clientString=element.createChild('span','service-worker-client-string');clientString.createTextChild(targetInfo.url);this._createLink(element,ls`focus`,this._activateTarget.bind(this,targetInfo.targetId),'service-worker-client-focus-link');}
_activateTarget(targetId){this._manager.target().targetAgent().activateTarget(targetId);}
_startButtonClicked(){this._manager.startWorker(this._registration.scopeURL);}
_skipButtonClicked(){this._manager.skipWaiting(this._registration.scopeURL);}
_stopButtonClicked(versionId){this._manager.stopWorker(versionId);}
_inspectButtonClicked(versionId){this._manager.inspectWorker(versionId);}
_wrapWidget(container){const shadowRoot=UI.createShadowRootWithCoreStyles(container);UI.appendStyle(shadowRoot,'resources/serviceWorkersView.css');const contentElement=createElement('div');shadowRoot.appendChild(contentElement);return contentElement;}};;Runtime.cachedResources["resources/appManifestView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n/*# sourceURL=resources/appManifestView.css */";Runtime.cachedResources["resources/backgroundServiceView.css"]=".background-service-toolbar {\n background-color: var(--toolbar-bg-color);\n border-bottom: var(--divider-border);\n}\n\n.data-grid {\n flex: auto;\n border: none;\n}\n\n.background-service-shortcut {\n color: hsla(0, 0%, 50%, 1);\n}\n\n.background-service-metadata {\n padding-left: 5px;\n padding-top: 10px;\n}\n\n.background-service-metadata-entry {\n padding-left: 10px;\n padding-bottom: 5px;\n}\n\n.background-service-metadata-name {\n color: rgb(33%, 33%, 33%);\n display: inline-block;\n margin-right: 0.25em;\n font-weight: bold;\n}\n\n.background-service-metadata-value {\n display: inline;\n margin-right: 1em;\n white-space: pre-wrap;\n word-break: break-all;\n}\n/*# sourceURL=resources/backgroundServiceView.css */";Runtime.cachedResources["resources/clearStorageView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.report-row {\n display: flex;\n align-items: center;\n}\n\n.clear-storage-button .report-row {\n margin: 0 0 0 17px;\n display: flex;\n}\n\n.link {\n margin-left: 10px;\n display: none;\n}\n\n.report-row:hover .link {\n display: inline;\n}\n\n.usage-breakdown-row {\n min-width: fit-content;\n}\n\n/*# sourceURL=resources/clearStorageView.css */";Runtime.cachedResources["resources/indexedDBViews.css"]="/*\n * Copyright (C) 2012 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.indexed-db-data-view .data-view-toolbar {\n position: relative;\n background-color: #eee;\n border-bottom: 1px solid #ccc;\n}\n\n.indexed-db-data-view .data-grid {\n flex: auto;\n}\n\n.indexed-db-data-view .data-grid .data-container tr:nth-last-child(1) {\n background-color: white;\n}\n\n.indexed-db-data-view .data-grid .data-container tr:nth-last-child(1) td {\n border: 0;\n}\n\n.indexed-db-data-view .data-grid .data-contain
static _appendToolbarToggle(toolbar,text,tooltip){const toggle=new UI.ToolbarToggle(tooltip);toggle.setText(text);toggle.addEventListener(UI.ToolbarButton.Events.Click,()=>toggle.setToggled(!toggle.toggled()));toolbar.appendToolbarItem(toggle);return toggle;}
_buildSearchConfig(){return new Search.SearchConfig(this._search.value,!this._matchCaseButton.toggled(),this._regexButton.toggled());}
async toggle(queryCandidate,searchImmediately){if(queryCandidate)
this._search.value=queryCandidate;if(this.isShowing())
this.focus();else
this._focusOnShow=true;this._initScope();if(searchImmediately)
this._onAction();else
this._startIndexing();}
createScope(){throw new Error('Not implemented');}
_initScope(){this._searchScope=this.createScope();}
wasShown(){if(this._focusOnShow){this.focus();this._focusOnShow=false;}}
_onIndexingFinished(){const finished=!this._progressIndicator.isCanceled();this._progressIndicator.done();this._progressIndicator=null;this._isIndexing=false;this._indexingFinished(finished);if(!finished)
this._pendingSearchConfig=null;if(!this._pendingSearchConfig)
return;const searchConfig=this._pendingSearchConfig;this._pendingSearchConfig=null;this._innerStartSearch(searchConfig);}
_startIndexing(){this._isIndexing=true;if(this._progressIndicator)
this._progressIndicator.done();this._progressIndicator=new UI.ProgressIndicator();this._searchMessageElement.textContent=Common.UIString('Indexing\u2026');this._progressIndicator.show(this._searchProgressPlaceholderElement);this._searchScope.performIndexing(new Common.ProgressProxy(this._progressIndicator,this._onIndexingFinished.bind(this)));}
_onSearchInputClear(){this._search.value='';this.focus();}
_onSearchResult(searchId,searchResult){if(searchId!==this._searchId||!this._progressIndicator)
return;if(this._progressIndicator&&this._progressIndicator.isCanceled()){this._onIndexingFinished();return;}
this._addSearchResult(searchResult);if(!searchResult.matchesCount())
return;if(!this._searchResultsPane){this._searchResultsPane=new Search.SearchResultsPane((this._searchConfig));this._showPane(this._searchResultsPane);}
this._searchResultsPane.addSearchResult(searchResult);}
_onSearchFinished(searchId,finished){if(searchId!==this._searchId||!this._progressIndicator)
return;if(!this._searchResultsPane)
this._nothingFound();this._searchFinished(finished);this._searchConfig=null;}
async _startSearch(searchConfig){this._resetSearch();++this._searchId;this._initScope();if(!this._isIndexing)
this._startIndexing();this._pendingSearchConfig=searchConfig;}
_innerStartSearch(searchConfig){this._searchConfig=searchConfig;if(this._progressIndicator)
this._progressIndicator.done();this._progressIndicator=new UI.ProgressIndicator();this._searchStarted(this._progressIndicator);this._searchScope.performSearch(searchConfig,this._progressIndicator,this._onSearchResult.bind(this,this._searchId),this._onSearchFinished.bind(this,this._searchId));}
_resetSearch(){this._stopSearch();this._showPane(null);this._searchResultsPane=null;}
_stopSearch(){if(this._progressIndicator&&!this._isIndexing)
this._progressIndicator.cancel();if(this._searchScope)
this._searchScope.stopSearch();this._searchConfig=null;}
_searchStarted(progressIndicator){this._resetCounters();if(!this._searchingView)
this._searchingView=new UI.EmptyWidget(Common.UIString('Searching\u2026'));this._showPane(this._searchingView);this._searchMessageElement.textContent=Common.UIString('Searching\u2026');progressIndicator.show(this._searchProgressPlaceholderElement);this._updateSearchResultsMessage();}
_indexingFinished(finished){this._searchMessageElement.textContent=finished?'':Common.UIString('Indexing interrupted.');}
_updateSearchResultsMessage(){if(this._searchMatchesCount&&this._searchResultsCount){if(this._searchMatchesCount===1&&this._nonEmptySearchResultsCount===1){this._searchResultsMessageElement.textContent=Common.UIString('Found 1 matching line in 1 file.');}else if(this._searchMatchesCount>1&&this._nonEmptySearchResultsCount===1){this._searchResultsMessageElement.textContent=Common.UIString('Found %d matching lines in 1 file.',this._searchMatchesCount);}else{this._searchResultsMessageElement.textContent=Common.UIString('Found %d matching lines in %d files.',this._searchMatchesCount,this._nonEmptySearchResultsCount);}}else{this._searchResultsMessageElement.textContent='';}}
_showPane(panel){if(this._visiblePane)
this._visiblePane.detach();if(panel)
panel.show(this._searchResultsElement);this._visiblePane=panel;}
_resetCounters(){this._searchMatchesCount=0;this._searchResultsCount=0;this._nonEmptySearchResultsCount=0;}
_nothingFound(){if(!this._notFoundView)
this._notFoundView=new UI.EmptyWidget(Common.UIString('No matches found.'));this._showPane(this._notFoundView);this._searchResultsMessageElement.textContent=Common.UIString('No matches found.');}
_addSearchResult(searchResult){const matchesCount=searchResult.matchesCount();this._searchMatchesCount+=matchesCount;this._searchResultsCount++;if(matchesCount)
this._nonEmptySearchResultsCount++;this._updateSearchResultsMessage();}
_searchFinished(finished){this._searchMessageElement.textContent=finished?Common.UIString('Search finished.'):Common.UIString('Search interrupted.');}
focus(){this._search.focus();this._search.select();}
willHide(){this._stopSearch();}
_onKeyDown(event){switch(event.keyCode){case UI.KeyboardShortcut.Keys.Enter.code:this._onAction();break;}}
_save(){this._advancedSearchConfig.set(this._buildSearchConfig().toPlainObject());}
_load(){const searchConfig=Search.SearchConfig.fromPlainObject(this._advancedSearchConfig.get());this._search.value=searchConfig.query();this._matchCaseButton.setToggled(!searchConfig.ignoreCase());this._regexButton.setToggled(searchConfig.isRegex());}
_onAction(){const searchConfig=this._buildSearchConfig();if(!searchConfig.query()||!searchConfig.query().length)
return;this._save();this._startSearch(searchConfig);}};;Search.SearchConfig=class{constructor(query,ignoreCase,isRegex){this._query=query;this._ignoreCase=ignoreCase;this._isRegex=isRegex;this._parse();}
static fromPlainObject(object){return new Search.SearchConfig(object.query,object.ignoreCase,object.isRegex);}
query(){return this._query;}
ignoreCase(){return this._ignoreCase;}
isRegex(){return this._isRegex;}
toPlainObject(){return{query:this.query(),ignoreCase:this.ignoreCase(),isRegex:this.isRegex()};}
_parse(){const quotedPattern=/"([^\\"]|\\.)+"/;const unquotedWordPattern=/(\s*(?!-?f(ile)?:)[^\\ ]|\\.)+/;const unquotedPattern=unquotedWordPattern.source+'(\\s+'+unquotedWordPattern.source+')*';const pattern=['(\\s*'+Search.SearchConfig.FilePatternRegex.source+'\\s*)','('+quotedPattern.source+')','('+unquotedPattern+')',].join('|');const regexp=new RegExp(pattern,'g');const queryParts=this._query.match(regexp)||[];this._fileQueries=[];this._queries=[];for(let i=0;i<queryParts.length;++i){const queryPart=queryParts[i];if(!queryPart)
continue;const fileQuery=this._parseFileQuery(queryPart);if(fileQuery){this._fileQueries.push(fileQuery);this._fileRegexQueries=this._fileRegexQueries||[];this._fileRegexQueries.push({regex:new RegExp(fileQuery.text,this.ignoreCase?'i':''),isNegative:fileQuery.isNegative});continue;}
if(this._isRegex){this._queries.push(queryPart);continue;}
if(queryPart.startsWith('"')){if(!queryPart.endsWith('"'))
continue;this._queries.push(this._parseQuotedQuery(queryPart));continue;}
this._queries.push(this._parseUnquotedQuery(queryPart));}}
filePathMatchesFileQuery(filePath){if(!this._fileRegexQueries)
return true;for(let i=0;i<this._fileRegexQueries.length;++i){if(!!filePath.match(this._fileRegexQueries[i].regex)===this._fileRegexQueries[i].isNegative)
return false;}
return true;}
queries(){return this._queries;}
_parseUnquotedQuery(query){return query.replace(/\\(.)/g,'$1');}
_parseQuotedQuery(query){return query.substring(1,query.length-1).replace(/\\(.)/g,'$1');}
_parseFileQuery(query){const match=query.match(Search.SearchConfig.FilePatternRegex);if(!match)
return null;const isNegative=!!match[1];query=match[3];let result='';for(let i=0;i<query.length;++i){const char=query[i];if(char==='*'){result+='.*';}else if(char==='\\'){++i;const nextChar=query[i];if(nextChar===' ')
result+=' ';}else{if(String.regexSpecialCharacters().indexOf(query.charAt(i))!==-1)
result+='\\';result+=query.charAt(i);}}
return new Search.SearchConfig.QueryTerm(result,isNegative);}};Search.SearchConfig.FilePatternRegex=/(-)?f(ile)?:((?:[^\\ ]|\\.)+)/;Search.SearchConfig.RegexQuery;Search.SearchConfig.QueryTerm=class{constructor(text,isNegative){this.text=text;this.isNegative=isNegative;}};Search.SearchResult=function(){};Search.SearchResult.prototype={label(){},description(){},matchesCount(){},matchLabel(index){},matchLineContent(index){},matchRevealable(index){}};Search.SearchScope=function(){};Search.SearchScope.prototype={performSearch(searchConfig,progress,searchResultCallback,searchFinishedCallback){},performIndexing(progress){},stopSearch(){}};;Search.SearchResultsPane=class extends UI.VBox{constructor(searchConfig){super(true);this._searchConfig=searchConfig;this._searchResults=[];this._treeOutline=new UI.TreeOutlineInShadow();this._treeOutline.hideOverflow();this._treeOutline.registerRequiredCSS('search/searchResultsPane.css');this.contentElement.appendChild(this._treeOutline.element);this._matchesExpandedCount=0;}
addSearchResult(searchResult){this._searchResults.push(searchResult);this._addTreeElement(searchResult);}
_addTreeElement(searchResult){const treeElement=new Search.SearchResultsPane.SearchResultsTreeElement(this._searchConfig,searchResult);this._treeOutline.appendChild(treeElement);if(this._matchesExpandedCount<Search.SearchResultsPane._matchesExpandedByDefault)
treeElement.expand();this._matchesExpandedCount+=searchResult.matchesCount();}};Search.SearchResultsPane._matchesExpandedByDefault=20;Search.SearchResultsPane._matchesShownAtOnce=20;Search.SearchResultsPane.SearchResultsTreeElement=class extends UI.TreeElement{constructor(searchConfig,searchResult){super('',true);this._searchConfig=searchConfig;this._searchResult=searchResult;this._initialized=false;this.toggleOnClick=true;this.selectable=false;}
onexpand(){if(this._initialized)
return;this._updateMatchesUI();this._initialized=true;}
_updateMatchesUI(){this.removeChildren();const toIndex=Math.min(this._searchResult.matchesCount(),Search.SearchResultsPane._matchesShownAtOnce);if(toIndex<this._searchResult.matchesCount()){this._appendSearchMatches(0,toIndex-1);this._appendShowMoreMatchesElement(toIndex-1);}else{this._appendSearchMatches(0,toIndex);}}
onattach(){this._updateSearchMatches();}
_updateSearchMatches(){this.listItemElement.classList.add('search-result');const fileNameSpan=span(this._searchResult.label(),'search-result-file-name');fileNameSpan.appendChild(span('\u2014','search-result-dash'));fileNameSpan.appendChild(span(this._searchResult.description(),'search-result-qualifier'));this.tooltip=this._searchResult.description();this.listItemElement.appendChild(fileNameSpan);const matchesCountSpan=createElement('span');matchesCountSpan.className='search-result-matches-count';matchesCountSpan.textContent=`${this._searchResult.matchesCount()}`;this.listItemElement.appendChild(matchesCountSpan);if(this.expanded)
this._updateMatchesUI();function span(text,className){const span=createElement('span');span.className=className;span.textContent=text;return span;}}
_appendSearchMatches(fromIndex,toIndex){const searchResult=this._searchResult;const queries=this._searchConfig.queries();const regexes=[];for(let i=0;i<queries.length;++i)
regexes.push(createSearchRegex(queries[i],!this._searchConfig.ignoreCase(),this._searchConfig.isRegex()));for(let i=fromIndex;i<toIndex;++i){const lineContent=searchResult.matchLineContent(i).trim();let matchRanges=[];for(let j=0;j<regexes.length;++j)
matchRanges=matchRanges.concat(this._regexMatchRanges(lineContent,regexes[j]));const anchor=Components.Linkifier.linkifyRevealable(searchResult.matchRevealable(i),'');anchor.classList.add('search-match-link');const lineNumberSpan=createElement('span');lineNumberSpan.classList.add('search-match-line-number');lineNumberSpan.textContent=searchResult.matchLabel(i);anchor.appendChild(lineNumberSpan);const contentSpan=this._createContentSpan(lineContent,matchRanges);anchor.appendChild(contentSpan);const searchMatchElement=new UI.TreeElement();searchMatchElement.selectable=false;this.appendChild(searchMatchElement);searchMatchElement.listItemElement.className='search-match';searchMatchElement.listItemElement.appendChild(anchor);searchMatchElement.tooltip=lineContent;}}
_appendShowMoreMatchesElement(startMatchIndex){const matchesLeftCount=this._searchResult.matchesCount()-startMatchIndex;const showMoreMatchesText=Common.UIString('Show %d more',matchesLeftCount);const showMoreMatchesTreeElement=new UI.TreeElement(showMoreMatchesText);this.appendChild(showMoreMatchesTreeElement);showMoreMatchesTreeElement.listItemElement.classList.add('show-more-matches');showMoreMatchesTreeElement.onselect=this._showMoreMatchesElementSelected.bind(this,showMoreMatchesTreeElement,startMatchIndex);}
_createContentSpan(lineContent,matchRanges){let trimBy=0;if(matchRanges.length>0&&matchRanges[0].offset>20)
trimBy=15;lineContent=lineContent.substring(trimBy,1000+trimBy);if(trimBy){matchRanges=matchRanges.map(range=>new TextUtils.SourceRange(range.offset-trimBy+1,range.length));lineContent='\u2026'+lineContent;}
const contentSpan=createElement('span');contentSpan.className='search-match-content';contentSpan.textContent=lineContent;UI.highlightRangesWithStyleClass(contentSpan,matchRanges,'highlighted-match');return contentSpan;}
_regexMatchRanges(lineContent,regex){regex.lastIndex=0;let match;const matchRanges=[];while((regex.lastIndex<lineContent.length)&&(match=regex.exec(lineContent)))
matchRanges.push(new TextUtils.SourceRange(match.index,match[0].length));return matchRanges;}
_showMoreMatchesElementSelected(showMoreMatchesTreeElement,startMatchIndex){this.removeChild(showMoreMatchesTreeElement);this._appendSearchMatches(startMatchIndex,this._searchResult.matchesCount());return false;}};;Runtime.cachedResources["search/searchResultsPane.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n padding: 0;\n margin: 0;\n overflow-y: auto;\n}\n\n.tree-outline {\n padding: 0;\n}\n\n.tree-outline ol {\n padding: 0;\n}\n\n.tree-outline li {\n height: 16px;\n}\n\nli.search-result {\n cursor: pointer;\n font-size: 12px;\n margin-top: 8px;\n padding: 2px 0 2px 4px;\n word-wrap: normal;\n white-space: pre;\n}\n\nli.search-result:hover {\n background-color: rgba(121, 121, 121, 0.1);\n}\n\nli.search-result .search-result-file-name {\n color: #222;\n flex: 1 1;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\nli.search-result .search-result-matches-count {\n color: #888;\n margin: 0 8px;\n}\n\nli.search-result.expanded .search-result-matches-count {\n display: none;\n}\n\nli.show-more-matches {\n color: #222;\n cursor: pointer;\n margin: 8px 0 0 -4px;\n}\n\nli.show-more-matches:hover {\n text-decoration: underline;\n}\n\nli.search-match {\n margin: 2px 0;\n word-wrap: normal;\n white-space: pre;\n}\n\nli.search-match::before {\n display: none;\n}\n\nli.search-match .search-match-line-number {\n color: rgb(128, 128, 128);\n text-align: right;\n vertical-align: top;\n word-break: normal;\n padding: 2px 4px 2px 6px;\n margin-right: 5px;\n}\n\nli.search-match:hover {\n background-color: rgba(56, 121, 217, 0.1);\n}\n\nli.search-match .highlighted-match {\n background-color: #F1EA00;\n}\n\n:host-context(.-theme-with-dark-background) li.search-match .highlighted-match {\n background-color: hsl(133, 100%, 30%) !important;\n}\n\n.tree-outline .devtools-link {\n text-decoration: none;\n display: block;\n flex: auto;\n}\n\nli.search-match .search-match-content {\n color: #000;\n}\n\nol.children.expanded {\n padding-bottom: 4px;\n}\n\n.search-match-link {\n overflow: hidden;\n text-overflow: ellipsis;\n margin-left: 9px;\n}\n\n.search-result-qualifier {\n color: #AAA;\n}\n\n.search-result-dash {\n color: #AAA;\n margin: 0 4px;\n}\n\n/*# sourceURL=search/searchResultsPane.css */";Runtime.cachedResources["search/searchView.css"]="/*\n * Copyright 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.search-drawer-header {\n align-items: center;\n flex-shrink: 0;\n overflow: hidden;\n}\n\n.search-toolbar {\n background-color: var(--toolbar-bg-color);\n border-bottom: var(--divider-border);\n}\n\n.search-toolbar-summary {\n background-color: #eee;\n border-top: 1px solid #ccc;\n padding-left: 5px;\n flex: 0 0 19px;\n display: flex;\n padding-right: 5px;\n}\n\n.search-toolbar-summary .search-message {\n padding-top: 2px;\n padding-left: 1ex;\n text-overflow: ellipsis;\n white-space: nowrap;\n overflow: hidden;\n}\n\n.search-view .search-results {\n overflow-y: auto;\n display: flex;\n flex: auto;\n}\n\n.search-view .search-results > div {\n flex: auto;\n}\n\n/*# sourceURL=search/searchView.css */";Security.SecurityModel=class extends SDK.SDKModel{constructor(target){super(target);this._dispatcher=new Security.SecurityDispatcher(this);this._securityAgent=target.securityAgent();target.registerSecurityDispatcher(this._dispatcher);this._securityAgent.enable();}
resourceTreeModel(){return(this.target().model(SDK.ResourceTreeModel));}
networkManager(){return(this.target().model(SDK.NetworkManager));}
static SecurityStateComparator(a,b){let securityStateMap;if(Security.SecurityModel._symbolicToNumericSecurityState){securityStateMap=Security.SecurityModel._symbolicToNumericSecurityState;}else{securityStateMap=new Map();const ordering=[Protocol.Security.SecurityState.Info,Protocol.Security.SecurityState.Insecure,Protocol.Security.SecurityState.Neutral,Protocol.Security.SecurityState.Secure,Protocol.Security.SecurityState.Unknown];for(let i=0;i<ordering.length;i++)
securityStateMap.set(ordering[i],i+1);Security.SecurityModel._symbolicToNumericSecurityState=securityStateMap;}
const aScore=securityStateMap.get(a)||0;const bScore=securityStateMap.get(b)||0;return aScore-bScore;}};SDK.SDKModel.register(Security.SecurityModel,SDK.Target.Capability.Security,false);Security.SecurityModel.Events={SecurityStateChanged:Symbol('SecurityStateChanged')};Security.PageSecurityState=class{constructor(securityState,explanations,summary){this.securityState=securityState;this.explanations=explanations;this.summary=summary;}};Security.SecurityDispatcher=class{constructor(model){this._model=model;}
securityStateChanged(securityState,schemeIsCryptographic,explanations,insecureContentStatus,summary){const pageSecurityState=new Security.PageSecurityState(securityState,explanations,summary||null);this._model.dispatchEventToListeners(Security.SecurityModel.Events.SecurityStateChanged,pageSecurityState);}
certificateError(eventId,errorType,requestURL){}};;Security.SecurityPanel=class extends UI.PanelWithSidebar{constructor(){super('security');this._mainView=new Security.SecurityMainView(this);const title=createElementWithClass('span','title');title.textContent=Common.UIString('Overview');this._sidebarMainViewElement=new Security.SecurityPanelSidebarTreeElement(title,this._setVisibleView.bind(this,this._mainView),'security-main-view-sidebar-tree-item','lock-icon');this._sidebarMainViewElement.tooltip=title.textContent;this._sidebarTree=new Security.SecurityPanelSidebarTree(this._sidebarMainViewElement,this.showOrigin.bind(this));this.panelSidebarElement().appendChild(this._sidebarTree.element);this._lastResponseReceivedForLoaderId=new Map();this._origins=new Map();this._filterRequestCounts=new Map();SDK.targetManager.observeModels(Security.SecurityModel,this);}
static _instance(){return(self.runtime.sharedInstance(Security.SecurityPanel));}
static createCertificateViewerButtonForOrigin(text,origin){return UI.createTextButton(text,async e=>{e.consume();const names=await SDK.multitargetNetworkManager.getCertificate(origin);InspectorFrontendHost.showCertificateViewer(names);},'origin-button');}
static createCertificateViewerButtonForCert(text,names){return UI.createTextButton(text,e=>{e.consume();InspectorFrontendHost.showCertificateViewer(names);},'security-certificate-button');}
static createHighlightedUrl(url,securityState){const schemeSeparator='://';const index=url.indexOf(schemeSeparator);if(index===-1){const text=createElement('span','');text.textContent=url;return text;}
const highlightedUrl=createElement('span');const scheme=url.substr(0,index);const content=url.substr(index+schemeSeparator.length);highlightedUrl.createChild('span','url-scheme-'+securityState).textContent=scheme;highlightedUrl.createChild('span','url-scheme-separator').textContent=schemeSeparator;highlightedUrl.createChild('span').textContent=content;return highlightedUrl;}
_updateSecurityState(newSecurityState,explanations,summary){this._sidebarMainViewElement.setSecurityState(newSecurityState);this._mainView.updateSecurityState(newSecurityState,explanations,summary);}
_onSecurityStateChanged(event){const data=(event.data);const securityState=(data.securityState);const explanations=(data.explanations);const summary=(data.summary);this._updateSecurityState(securityState,explanations,summary);}
selectAndSwitchToMainView(){this._sidebarMainViewElement.select(true);}
showOrigin(origin){const originState=this._origins.get(origin);if(!originState.originView)
originState.originView=new Security.SecurityOriginView(this,origin,originState);this._setVisibleView(originState.originView);}
wasShown(){super.wasShown();if(!this._visibleView)
this.selectAndSwitchToMainView();}
focus(){this._sidebarTree.focus();}
_setVisibleView(view){if(this._visibleView===view)
return;if(this._visibleView)
this._visibleView.detach();this._visibleView=view;if(view)
this.splitWidget().setMainWidget(view);}
_onResponseReceived(event){const request=(event.data);if(request.resourceType()===Common.resourceTypes.Document)
this._lastResponseReceivedForLoaderId.set(request.loaderId,request);}
_processRequest(request){const origin=Common.ParsedURL.extractOrigin(request.url());if(!origin){return;}
let securityState=(request.securityState());if(request.mixedContentType===Protocol.Security.MixedContentType.Blockable||request.mixedContentType===Protocol.Security.MixedContentType.OptionallyBlockable)
securityState=Protocol.Security.SecurityState.Insecure;if(this._origins.has(origin)){const originState=this._origins.get(origin);const oldSecurityState=originState.securityState;originState.securityState=this._securityStateMin(oldSecurityState,securityState);if(oldSecurityState!==originState.securityState){const securityDetails=(request.securityDetails());if(securityDetails)
originState.securityDetails=securityDetails;this._sidebarTree.updateOrigin(origin,securityState);if(originState.originView)
originState.originView.setSecurityState(securityState);}}else{const originState={};originState.securityState=securityState;const securityDetails=request.securityDetails();if(securityDetails)
originState.securityDetails=securityDetails;originState.loadedFromCache=request.cached();this._origins.set(origin,originState);this._sidebarTree.addOrigin(origin,securityState);}}
_onRequestFinished(event){const request=(event.data);this._updateFilterRequestCounts(request);this._processRequest(request);}
_updateFilterRequestCounts(request){if(request.mixedContentType===Protocol.Security.MixedContentType.None)
return;let filterKey=Network.NetworkLogView.MixedContentFilterValues.All;if(request.wasBlocked())
filterKey=Network.NetworkLogView.MixedContentFilterValues.Blocked;else if(request.mixedContentType===Protocol.Security.MixedContentType.Blockable)
filterKey=Network.NetworkLogView.MixedContentFilterValues.BlockOverridden;else if(request.mixedContentType===Protocol.Security.MixedContentType.OptionallyBlockable)
filterKey=Network.NetworkLogView.MixedContentFilterValues.Displayed;if(!this._filterRequestCounts.has(filterKey))
this._filterRequestCounts.set(filterKey,1);else
this._filterRequestCounts.set(filterKey,this._filterRequestCounts.get(filterKey)+1);this._mainView.refreshExplanations();}
filterRequestCount(filterKey){return this._filterRequestCounts.get(filterKey)||0;}
_securityStateMin(stateA,stateB){return Security.SecurityModel.SecurityStateComparator(stateA,stateB)<0?stateA:stateB;}
modelAdded(securityModel){if(this._securityModel)
return;this._securityModel=securityModel;const resourceTreeModel=securityModel.resourceTreeModel();const networkManager=securityModel.networkManager();this._eventListeners=[securityModel.addEventListener(Security.SecurityModel.Events.SecurityStateChanged,this._onSecurityStateChanged,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.InterstitialShown,this._onInterstitialShown,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.InterstitialHidden,this._onInterstitialHidden,this),networkManager.addEventListener(SDK.NetworkManager.Events.ResponseReceived,this._onResponseReceived,this),networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished,this._onRequestFinished,this),];if(resourceTreeModel.isInterstitialShowing())
this._onInterstitialShown();}
modelRemoved(securityModel){if(this._securityModel!==securityModel)
return;delete this._securityModel;Common.EventTarget.removeEventListeners(this._eventListeners);}
_onMainFrameNavigated(event){const frame=(event.data);const request=this._lastResponseReceivedForLoaderId.get(frame.loaderId);this.selectAndSwitchToMainView();this._sidebarTree.clearOrigins();this._origins.clear();this._lastResponseReceivedForLoaderId.clear();this._filterRequestCounts.clear();this._mainView.refreshExplanations();const origin=Common.ParsedURL.extractOrigin(request?request.url():frame.url);this._sidebarTree.setMainOrigin(origin);if(request)
this._processRequest(request);}
_onInterstitialShown(){this.selectAndSwitchToMainView();this._sidebarTree.toggleOriginsList(true);}
_onInterstitialHidden(){this._sidebarTree.toggleOriginsList(false);}};Security.SecurityPanel.Origin;Security.SecurityPanel.OriginState;Security.SecurityPanelSidebarTree=class extends UI.TreeOutlineInShadow{constructor(mainViewElement,showOriginInPanel){super();this.registerRequiredCSS('security/sidebar.css');this.registerRequiredCSS('security/lockIcon.css');this.appendChild(mainViewElement);this._showOriginInPanel=showOriginInPanel;this._mainOrigin=null;this._originGroups=new Map();this._originGroupTitles=new Map([[Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin,ls`Main origin`],[Security.SecurityPanelSidebarTree.OriginGroup.NonSecure,ls`Non-secure origins`],[Security.SecurityPanelSidebarTree.OriginGroup.Secure,ls`Secure origins`],[Security.SecurityPanelSidebarTree.OriginGroup.Unknown,ls`Unknown / canceled`],]);for(const key in Security.SecurityPanelSidebarTree.OriginGroup){const group=Security.SecurityPanelSidebarTree.OriginGroup[key];const element=this._createOriginGroupElement(this._originGroupTitles.get(group));this._originGroups.set(group,element);this.appendChild(element);}
this._clearOriginGroups();const mainViewReloadMessage=new UI.TreeElement(Common.UIString('Reload to view details'));mainViewReloadMessage.selectable=false;mainViewReloadMessage.listItemElement.classList.add('security-main-view-reload-message');this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin).appendChild(mainViewReloadMessage);this._elementsByOrigin=new Map();}
_createOriginGroupElement(originGroupTitle){const originGroup=new UI.TreeElement(originGroupTitle,true);originGroup.selectable=false;originGroup.setCollapsible(false);originGroup.expand();originGroup.listItemElement.classList.add('security-sidebar-origins');return originGroup;}
toggleOriginsList(hidden){for(const element of this._originGroups.values())
element.hidden=hidden;}
addOrigin(origin,securityState){const originElement=new Security.SecurityPanelSidebarTreeElement(Security.SecurityPanel.createHighlightedUrl(origin,securityState),this._showOriginInPanel.bind(this,origin),'security-sidebar-tree-item','security-property');originElement.tooltip=origin;this._elementsByOrigin.set(origin,originElement);this.updateOrigin(origin,securityState);}
setMainOrigin(origin){this._mainOrigin=origin;}
updateOrigin(origin,securityState){const originElement=(this._elementsByOrigin.get(origin));originElement.setSecurityState(securityState);let newParent;if(origin===this._mainOrigin){newParent=this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin);if(securityState===Protocol.Security.SecurityState.Secure)
newParent.title=ls`Main origin (secure)`;else
newParent.title=ls`Main origin (non-secure)`;}else{switch(securityState){case Protocol.Security.SecurityState.Secure:newParent=this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.Secure);break;case Protocol.Security.SecurityState.Unknown:newParent=this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.Unknown);break;default:newParent=this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.NonSecure);break;}}
const oldParent=originElement.parent;if(oldParent!==newParent){if(oldParent){oldParent.removeChild(originElement);if(oldParent.childCount()===0)
oldParent.hidden=true;}
newParent.appendChild(originElement);newParent.hidden=false;}}
_clearOriginGroups(){for(const originGroup of this._originGroups.values()){originGroup.removeChildren();originGroup.hidden=true;}
const mainOrigin=this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin);mainOrigin.title=this._originGroupTitles.get(Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin);mainOrigin.hidden=false;}
clearOrigins(){this._clearOriginGroups();this._elementsByOrigin.clear();}};Security.SecurityPanelSidebarTree.OriginGroup={MainOrigin:Symbol('MainOrigin'),NonSecure:Symbol('NonSecure'),Secure:Symbol('Secure'),Unknown:Symbol('Unknown')};Security.SecurityPanelSidebarTreeElement=class extends UI.TreeElement{constructor(textElement,selectCallback,className,cssPrefix){super('',false);this._selectCallback=selectCallback;this._cssPrefix=cssPrefix;this.listItemElement.classList.add(className);this._iconElement=this.listItemElement.createChild('div','icon');this._iconElement.classList.add(this._cssPrefix);this.listItemElement.appendChild(textElement);this.setSecurityState(Protocol.Security.SecurityState.Unknown);}
static SecurityStateComparator(a,b){return Security.SecurityModel.SecurityStateComparator(a.securityState(),b.securityState());}
setSecurityState(newSecurityState){if(this._securityState)
this._iconElement.classList.remove(this._cssPrefix+'-'+this._securityState);this._securityState=newSecurityState;this._iconElement.classList.add(this._cssPrefix+'-'+newSecurityState);}
securityState(){return this._securityState;}
onselect(){this._selectCallback();return true;}};Security.SecurityMainView=class extends UI.VBox{constructor(panel){super(true);this.registerRequiredCSS('security/mainView.css');this.registerRequiredCSS('security/lockIcon.css');this.setMinimumSize(200,100);this.contentElement.classList.add('security-main-view');this._panel=panel;this._summarySection=this.contentElement.createChild('div','security-summary');this._securityExplanationsMain=this.contentElement.createChild('div','security-explanation-list security-explanations-main');this._securityExplanationsExtra=this.contentElement.createChild('div','security-explanation-list security-explanations-extra');this._summarySection.createChild('div','security-summary-section-title').textContent=Common.UIString('Security overview');const lockSpectrum=this._summarySection.createChild('div','lock-spectrum');lockSpectrum.createChild('div','lock-icon lock-icon-secure').title=Common.UIString('Secure');lockSpectrum.createChild('div','lock-icon lock-icon-neutral').title=Common.UIString('Not secure');lockSpectrum.createChild('div','lock-icon lock-icon-insecure').title=Common.UIString('Not secure (broken)');this._summarySection.createChild('div','triangle-pointer-container').createChild('div','triangle-pointer-wrapper').createChild('div','triangle-pointer');this._summaryText=this._summarySection.createChild('div','security-summary-text');}
_addExplanation(parent,explanation){const explanationSection=parent.createChild('div','security-explanation');explanationSection.classList.add('security-explanation-'+explanation.securityState);explanationSection.createChild('div','security-property').classList.add('security-property-'+explanation.securityState);const text=explanationSection.createChild('div','security-explanation-text');const explanationHeader=text.createChild('div','security-explanation-title');if(explanation.title){explanationHeader.createChild('span').textContent=explanation.title+' - ';explanationHeader.createChild('span','security-explanation-title-'+explanation.securityState).textContent=explanation.summary;}else{explanationHeader.textContent=explanation.summary;}
text.createChild('div').textContent=explanation.description;if(explanation.certificate.length){text.appendChild(Security.SecurityPanel.createCertificateViewerButtonForCert(Common.UIString('View certificate'),explanation.certificate));}
if(explanation.recommendations&&explanation.recommendations.length){const recommendationList=text.createChild('ul','security-explanation-recommendations');for(const recommendation of explanation.recommendations)
recommendationList.createChild('li').textContent=recommendation;}
return text;}
updateSecurityState(newSecurityState,explanations,summary){this._summarySection.classList.remove('security-summary-'+this._securityState);this._securityState=newSecurityState;this._summarySection.classList.add('security-summary-'+this._securityState);const summaryExplanationStrings={'unknown':Common.UIString('The security of this page is unknown.'),'insecure':Common.UIString('This page is not secure (broken HTTPS).'),'neutral':Common.UIString('This page is not secure.'),'secure':Common.UIString('This page is secure (valid HTTPS).')};this._summaryText.textContent=summary||summaryExplanationStrings[this._securityState];this._explanations=explanations;this.refreshExplanations();}
refreshExplanations(){this._securityExplanationsMain.removeChildren();this._securityExplanationsExtra.removeChildren();for(const explanation of this._explanations){if(explanation.securityState===Protocol.Security.SecurityState.Info){this._addExplanation(this._securityExplanationsExtra,explanation);}else{switch(explanation.mixedContentType){case Protocol.Security.MixedContentType.Blockable:this._addMixedContentExplanation(this._securityExplanationsMain,explanation,Network.NetworkLogView.MixedContentFilterValues.BlockOverridden);break;case Protocol.Security.MixedContentType.OptionallyBlockable:this._addMixedContentExplanation(this._securityExplanationsMain,explanation,Network.NetworkLogView.MixedContentFilterValues.Displayed);break;default:this._addExplanation(this._securityExplanationsMain,explanation);break;}}}
if(this._panel.filterRequestCount(Network.NetworkLogView.MixedContentFilterValues.Blocked)>0){const explanation=({securityState:Protocol.Security.SecurityState.Info,summary:Common.UIString('Blocked mixed content'),description:Common.UIString('Your page requested non-secure resources that were blocked.'),mixedContentType:Protocol.Security.MixedContentType.Blockable,certificate:[]});this._addMixedContentExplanation(this._securityExplanationsMain,explanation,Network.NetworkLogView.MixedContentFilterValues.Blocked);}}
_addMixedContentExplanation(parent,explanation,filterKey){const element=this._addExplanation(parent,explanation);const filterRequestCount=this._panel.filterRequestCount(filterKey);if(!filterRequestCount){const refreshPrompt=element.createChild('div','security-mixed-content');refreshPrompt.textContent=Common.UIString('Reload the page to record requests for HTTP resources.');return;}
const requestsAnchor=element.createChild('div','security-mixed-content link');if(filterRequestCount===1)
requestsAnchor.textContent=Common.UIString('View %d request in Network Panel',filterRequestCount);else
requestsAnchor.textContent=Common.UIString('View %d requests in Network Panel',filterRequestCount);requestsAnchor.href='';requestsAnchor.addEventListener('click',this.showNetworkFilter.bind(this,filterKey));}
showNetworkFilter(filterKey,e){e.consume();Network.NetworkPanel.revealAndFilter([{filterType:Network.NetworkLogView.FilterType.MixedContent,filterValue:filterKey}]);}};Security.SecurityOriginView=class extends UI.VBox{constructor(panel,origin,originState){super();this._panel=panel;this.setMinimumSize(200,100);this.element.classList.add('security-origin-view');this.registerRequiredCSS('security/originView.css');this.registerRequiredCSS('security/lockIcon.css');const titleSection=this.element.createChild('div','title-section');titleSection.createChild('div','title-section-header').textContent=ls`Origin`;const originDisplay=titleSection.createChild('div','origin-display');this._originLockIcon=originDisplay.createChild('span','security-property');this._originLockIcon.classList.add('security-property-'+originState.securityState);originDisplay.appendChild(Security.SecurityPanel.createHighlightedUrl(origin,originState.securityState));const originNetworkButton=titleSection.createChild('div','view-network-button');originNetworkButton.appendChild(UI.createTextButton('View requests in Network Panel',e=>{e.consume();const parsedURL=new Common.ParsedURL(origin);Network.NetworkPanel.revealAndFilter([{filterType:Network.NetworkLogView.FilterType.Domain,filterValue:parsedURL.host},{filterType:Network.NetworkLogView.FilterType.Scheme,filterValue:parsedURL.scheme}]);},'origin-button'));if(originState.securityDetails){const connectionSection=this.element.createChild('div','origin-view-section');connectionSection.createChild('div','origin-view-section-title').textContent=Common.UIString('Connection');let table=new Security.SecurityDetailsTable();connectionSection.appendChild(table.element());table.addRow(Common.UIString('Protocol'),originState.securityDetails.protocol);if(originState.securityDetails.keyExchange)
table.addRow(Common.UIString('Key exchange'),originState.securityDetails.keyExchange);if(originState.securityDetails.keyExchangeGroup)
table.addRow(Common.UIString('Key exchange group'),originState.securityDetails.keyExchangeGroup);table.addRow(Common.UIString('Cipher'),originState.securityDetails.cipher+
(originState.securityDetails.mac?' with '+originState.securityDetails.mac:''));const certificateSection=this.element.createChild('div','origin-view-section');certificateSection.createChild('div','origin-view-section-title').textContent=Common.UIString('Certificate');const sctListLength=originState.securityDetails.signedCertificateTimestampList.length;const ctCompliance=originState.securityDetails.certificateTransparencyCompliance;let sctSection;if(sctListLength||ctCompliance!==Protocol.Network.CertificateTransparencyCompliance.Unknown){sctSection=this.element.createChild('div','origin-view-section');sctSection.createChild('div','origin-view-section-title').textContent=Common.UIString('Certificate Transparency');}
const sanDiv=this._createSanDiv(originState.securityDetails.sanList);const validFromString=new Date(1000*originState.securityDetails.validFrom).toUTCString();const validUntilString=new Date(1000*originState.securityDetails.validTo).toUTCString();table=new Security.SecurityDetailsTable();certificateSection.appendChild(table.element());table.addRow(Common.UIString('Subject'),originState.securityDetails.subjectName);table.addRow(Common.UIString('SAN'),sanDiv);table.addRow(Common.UIString('Valid from'),validFromString);table.addRow(Common.UIString('Valid until'),validUntilString);table.addRow(Common.UIString('Issuer'),originState.securityDetails.issuer);table.addRow('',Security.SecurityPanel.createCertificateViewerButtonForOrigin(Common.UIString('Open full certificate details'),origin));if(!sctSection)
return;const sctSummaryTable=new Security.SecurityDetailsTable();sctSummaryTable.element().classList.add('sct-summary');sctSection.appendChild(sctSummaryTable.element());for(let i=0;i<sctListLength;i++){const sct=originState.securityDetails.signedCertificateTimestampList[i];sctSummaryTable.addRow(Common.UIString('SCT'),sct.logDescription+' ('+sct.origin+', '+sct.status+')');}
const sctTableWrapper=sctSection.createChild('div','sct-details');sctTableWrapper.classList.add('hidden');for(let i=0;i<sctListLength;i++){const sctTable=new Security.SecurityDetailsTable();sctTableWrapper.appendChild(sctTable.element());const sct=originState.securityDetails.signedCertificateTimestampList[i];sctTable.addRow(Common.UIString('Log name'),sct.logDescription);sctTable.addRow(Common.UIString('Log ID'),sct.logId.replace(/(.{2})/g,'$1 '));sctTable.addRow(Common.UIString('Validation status'),sct.status);sctTable.addRow(Common.UIString('Source'),sct.origin);sctTable.addRow(Common.UIString('Issued at'),new Date(sct.timestamp).toUTCString());sctTable.addRow(Common.UIString('Hash algorithm'),sct.hashAlgorithm);sctTable.addRow(Common.UIString('Signature algorithm'),sct.signatureAlgorithm);sctTable.addRow(Common.UIString('Signature data'),sct.signatureData.replace(/(.{2})/g,'$1 '));}
if(sctListLength){const toggleSctsDetailsLink=sctSection.createChild('div','link');toggleSctsDetailsLink.classList.add('sct-toggle');toggleSctsDetailsLink.textContent=Common.UIString('Show full details');function toggleSctDetailsDisplay(){const isDetailsShown=!sctTableWrapper.classList.contains('hidden');if(isDetailsShown)
toggleSctsDetailsLink.textContent=Common.UIString('Show full details');else
toggleSctsDetailsLink.textContent=Common.UIString('Hide full details');sctSummaryTable.element().classList.toggle('hidden');sctTableWrapper.classList.toggle('hidden');}
toggleSctsDetailsLink.addEventListener('click',toggleSctDetailsDisplay,false);}
switch(ctCompliance){case Protocol.Network.CertificateTransparencyCompliance.Compliant:sctSection.createChild('div','origin-view-section-notes').textContent=Common.UIString('This request complies with Chrome\'s Certificate Transparency policy.');break;case Protocol.Network.CertificateTransparencyCompliance.NotCompliant:sctSection.createChild('div','origin-view-section-notes').textContent=Common.UIString('This request does not comply with Chrome\'s Certificate Transparency policy.');break;case Protocol.Network.CertificateTransparencyCompliance.Unknown:break;}
const noteSection=this.element.createChild('div','origin-view-section origin-view-notes');if(originState.loadedFromCache){noteSection.createChild('div').textContent=Common.UIString('This response was loaded from cache. Some security details might be missing.');}
noteSection.createChild('div').textContent=Common.UIString('The security details above are from the first inspected response.');}else if(originState.securityState===Protocol.Security.SecurityState.Secure){const secureSection=this.element.createChild('div','origin-view-section');secureSection.createChild('div','origin-view-section-title').textContent=Common.UIString('Secure');secureSection.createChild('div').textContent=Common.UIString('This origin is a non-HTTPS secure origin.');}else if(originState.securityState!==Protocol.Security.SecurityState.Unknown){const notSecureSection=this.element.createChild('div','origin-view-section');notSecureSection.createChild('div','origin-view-section-title').textContent=Common.UIString('Not secure');notSecureSection.createChild('div').textContent=Common.UIString('Your connection to this origin is not secure.');}else{const noInfoSection=this.element.createChild('div','origin-view-section');noInfoSection.createChild('div','origin-view-section-title').textContent=Common.UIString('No security information');noInfoSection.createChild('div').textContent=Common.UIString('No security details are available for this origin.');}}
_createSanDiv(sanList){const sanDiv=createElement('div');if(sanList.length===0){sanDiv.textContent=Common.UIString('(n/a)');sanDiv.classList.add('empty-san');}else{const truncatedNumToShow=2;const listIsTruncated=sanList.length>truncatedNumToShow+1;for(let i=0;i<sanList.length;i++){const span=sanDiv.createChild('span','san-entry');span.textContent=sanList[i];if(listIsTruncated&&i>=truncatedNumToShow)
span.classList.add('truncated-entry');}
if(listIsTruncated){const truncatedSANToggle=sanDiv.createChild('div','link');truncatedSANToggle.href='';function toggleSANTruncation(){if(sanDiv.classList.contains('truncated-san')){sanDiv.classList.remove('truncated-san');truncatedSANToggle.textContent=Common.UIString('Show less');}else{sanDiv.classList.add('truncated-san');truncatedSANToggle.textContent=Common.UIString('Show more (%d total)',sanList.length);}}
truncatedSANToggle.addEventListener('click',toggleSANTruncation,false);toggleSANTruncation();}}
return sanDiv;}
setSecurityState(newSecurityState){for(const className of Array.prototype.slice.call(this._originLockIcon.classList)){if(className.startsWith('security-property-'))
this._originLockIcon.classList.remove(className);}
this._originLockIcon.classList.add('security-property-'+newSecurityState);}};Security.SecurityDetailsTable=class{constructor(){this._element=createElement('table');this._element.classList.add('details-table');}
element(){return this._element;}
addRow(key,value){const row=this._element.createChild('div','details-table-row');row.createChild('div').textContent=key;const valueDiv=row.createChild('div');if(typeof value==='string')
valueDiv.textContent=value;else
valueDiv.appendChild(value);}};;Runtime.cachedResources["security/lockIcon.css"]="/* Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.lock-icon,\n.security-property {\n height: 16px;\n width: 16px;\n\n -webkit-mask-image: url(Images/securityIcons.png);\n -webkit-mask-size: 80px 32px;\n\n background-color: #888;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n .lock-icon,\n .security-property {\n -webkit-mask-image: url(Images/securityIcons_2x.png);\n }\n}\n\n.lock-icon-secure {\n -webkit-mask-position: 0px 0px;\n background-color: #0B8043;\n}\n\n.lock-icon-unknown,\n.lock-icon-neutral {\n -webkit-mask-position: -16px 0px;\n background-color: #000000; /* Black for clarity on lower DPI screens */\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n .lock-icon-unknown,\n .lock-icon-neutral {\n background-color: #5A5A5A; /* Gray for hiDPI screens */\n }\n}\n\n.lock-icon-insecure {\n -webkit-mask-position: -32px 0px;\n background-color: #C63626;\n}\n\n.security-property-secure {\n -webkit-mask-position: 0px -16px;\n background-color: #0B8043;\n}\n\n.security-property-neutral {\n -webkit-mask-position: -16px -16px;\n background-color: #C63626;\n}\n\n.security-property-insecure {\n -webkit-mask-position: -32px -16px;\n background-color: #C63626;\n}\n\n.security-property-info {\n -webkit-mask-position: -48px -16px;\n background-color: rgba(0, 0, 0, 0.5);\n}\n\n.security-property-unknown {\n -webkit-mask-position: -64px -16px;\n background-color: rgba(0, 0, 0, 0.5);\n}\n\n.url-scheme-secure {\n color: #0b8043;\n}\n\n.url-scheme-neutral,\n.url-scheme-insecure {\n color: #cb3626;\n}\n\n.url-scheme-separator {\n color: #8a8a8a;\n}\n\n/*# sourceURL=security/lockIcon.css */";Runtime.cachedResources["security/mainView.css"]="/* Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.security-main-view {\n -webkit-user-select: text;\n overflow-x: hidden;\n overflow-y: auto;\n background-color: var(--toolbar-bg-color);\n}\n\n.security-main-view > div {\n flex-shrink: 0;\n}\n\n.security-summary-section-title {\n font-size: 15px;\n margin: 12px 16px;\n}\n\n.lock-spectrum {\n margin: 8px 16px;\n display: flex;\n align-items: flex-start;\n}\n\n.security-summary .lock-icon {\n flex: none;\n width: 16px;\n height: 16px;\n margin: 0 0;\n}\n\n/* Separate the middle icon from the other two. */\n.security-summary .lock-icon-neutral {\n margin: 0 16px;\n}\n\n.security-summary:not(.security-summary-secure) .lock-icon-secure,\n.security-summary:not(.security-summary-neutral) .lock-icon-neutral,\n.security-summary:not(.security-summary-insecure) .lock-icon-insecure {\n background-color: rgba(90, 90, 90, 0.25);\n}\n\n.triangle-pointer-container {\n margin: 8px 24px 0;\n padding: 0 0;\n}\n\n.triangle-pointer-wrapper {\n /* Defaults for dynamic properties. */\n transform: translateX(0);\n transition: transform 0.3s;\n}\n\n.triangle-pointer {\n width: 12px;\n height: 12px;\n margin-bottom: -6px;\n margin-left: -6px;\n transform: rotate(-45deg);\n border-style: solid;\n border-width: 1px 1px 0 0;\n\n background: #fff;\n border-color: rgb(217, 217, 217);\n}\n\n.security-summary-secure .triangle-pointer-wrapper {\n transform: translateX(0px);\n}\n\n.security-summary-neutral .triangle-pointer-wrapper {\n transform: translateX(32px);\n}\n\n.security-summary-insecure .triangle-pointer-wrapper {\n transform: translateX(64px);\n}\n\n.security-summary-text {\n padding: 16px 24px;\n border-style: solid;\n border-width: 1px 0;\n font-size: 15px;\n\n background: #fff;\n border-color: rgb(217, 217, 217);\n}\n\n.security-summary-secure .triangle-pointer,\n.security-summary-secure .security-summary-t
static _showSettingsScreen(name){const settingsScreen=(self.runtime.sharedInstance(Settings.SettingsScreen));if(settingsScreen.isShowing())
return;const dialog=new UI.Dialog();dialog.addCloseButton();settingsScreen.show(dialog.contentElement);dialog.show();settingsScreen._selectTab(name||'preferences');}
resolveLocation(locationName){return this._tabbedLocation;}
_selectTab(name){UI.viewManager.showView(name);}
_keyDown(event){const shiftKeyCode=16;if(event.keyCode===shiftKeyCode&&++this._developerModeCounter>5)
this.contentElement.classList.add('settings-developer-mode');}};Settings.SettingsTab=class extends UI.VBox{constructor(name,id){super();this.element.classList.add('settings-tab-container');if(id)
this.element.id=id;const header=this.element.createChild('header');header.createChild('h3').createTextChild(name);this.containerElement=this.element.createChild('div','settings-container-wrapper').createChild('div','settings-tab settings-content settings-container');}
_appendSection(name){const block=this.containerElement.createChild('div','settings-block');if(name)
block.createChild('div','settings-section-title').textContent=name;return block;}};Settings.GenericSettingsTab=class extends Settings.SettingsTab{constructor(){super(Common.UIString('Preferences'),'preferences-tab-content');const explicitSectionOrder=['','Appearance','Sources','Elements','Network','Performance','Console','Extensions'];this._nameToSection=new Map();for(const sectionName of explicitSectionOrder)
this._sectionElement(sectionName);self.runtime.extensions('setting').forEach(this._addSetting.bind(this));self.runtime.extensions(UI.SettingUI).forEach(this._addSettingUI.bind(this));this._appendSection().appendChild(UI.createTextButton(Common.UIString('Restore defaults and reload'),restoreAndReload));function restoreAndReload(){Common.settings.clearAll();Components.reload();}}
static isSettingVisible(extension){const descriptor=extension.descriptor();if(!('title'in descriptor))
return false;if(!('category'in descriptor))
return false;return true;}
_addSetting(extension){if(!Settings.GenericSettingsTab.isSettingVisible(extension))
return;const sectionElement=this._sectionElement(extension.descriptor()['category']);const setting=Common.moduleSetting(extension.descriptor()['settingName']);const settingControl=UI.SettingsUI.createControlForSetting(setting);if(settingControl)
sectionElement.appendChild(settingControl);}
_addSettingUI(extension){const descriptor=extension.descriptor();const sectionName=descriptor['category']||'';extension.instance().then(appendCustomSetting.bind(this));function appendCustomSetting(object){const settingUI=(object);const element=settingUI.settingElement();if(element)
this._sectionElement(sectionName).appendChild(element);}}
_sectionElement(sectionName){let sectionElement=this._nameToSection.get(sectionName);if(!sectionElement){const uiSectionName=sectionName&&Common.UIString(sectionName);sectionElement=this._appendSection(uiSectionName);this._nameToSection.set(sectionName,sectionElement);}
return sectionElement;}};Settings.ExperimentsSettingsTab=class extends Settings.SettingsTab{constructor(){super(Common.UIString('Experiments'),'experiments-tab-content');const experiments=Runtime.experiments.allConfigurableExperiments();if(experiments.length){const experimentsSection=this._appendSection();experimentsSection.appendChild(this._createExperimentsWarningSubsection());for(let i=0;i<experiments.length;++i)
experimentsSection.appendChild(this._createExperimentCheckbox(experiments[i]));}}
_createExperimentsWarningSubsection(){const subsection=createElement('div');const warning=subsection.createChild('span','settings-experiments-warning-subsection-warning');warning.textContent=Common.UIString('WARNING:');subsection.createTextChild(' ');const message=subsection.createChild('span','settings-experiments-warning-subsection-message');message.textContent=Common.UIString('These experiments could be dangerous and may require restart.');return subsection;}
_createExperimentCheckbox(experiment){const label=UI.CheckboxLabel.create(Common.UIString(experiment.title),experiment.isEnabled());const input=label.checkboxElement;input.name=experiment.name;function listener(){experiment.setEnabled(input.checked);}
input.addEventListener('click',listener,false);const p=createElement('p');p.className=experiment.hidden&&!experiment.isEnabled()?'settings-experiment-hidden':'';p.appendChild(label);return p;}};Settings.SettingsScreen.ActionDelegate=class{handleAction(context,actionId){switch(actionId){case'settings.show':Settings.SettingsScreen._showSettingsScreen();return true;case'settings.documentation':InspectorFrontendHost.openInNewTab('https://developers.google.com/web/tools/chrome-devtools/');return true;case'settings.shortcuts':Settings.SettingsScreen._showSettingsScreen(Common.UIString('Shortcuts'));return true;}
return false;}};Settings.SettingsScreen.Revealer=class{reveal(object){console.assert(object instanceof Common.Setting);const setting=(object);let success=false;self.runtime.extensions('setting').forEach(revealModuleSetting);self.runtime.extensions(UI.SettingUI).forEach(revealSettingUI);self.runtime.extensions('view').forEach(revealSettingsView);return success?Promise.resolve():Promise.reject();function revealModuleSetting(extension){if(!Settings.GenericSettingsTab.isSettingVisible(extension))
return;if(extension.descriptor()['settingName']===setting.name){InspectorFrontendHost.bringToFront();Settings.SettingsScreen._showSettingsScreen();success=true;}}
function revealSettingUI(extension){const settings=extension.descriptor()['settings'];if(settings&&settings.indexOf(setting.name)!==-1){InspectorFrontendHost.bringToFront();Settings.SettingsScreen._showSettingsScreen();success=true;}}
function revealSettingsView(extension){const location=extension.descriptor()['location'];if(location!=='settings-view')
return;const settings=extension.descriptor()['settings'];if(settings&&settings.indexOf(setting.name)!==-1){InspectorFrontendHost.bringToFront();Settings.SettingsScreen._showSettingsScreen(extension.descriptor()['id']);success=true;}}}};;Settings.FrameworkBlackboxSettingsTab=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('settings/frameworkBlackboxSettingsTab.css');this.contentElement.createChild('div','header').textContent=Common.UIString('Framework Blackboxing');this.contentElement.createChild('div','intro').textContent=ls`Debugger will skip through the scripts and will not stop on exceptions thrown by them.`;const blackboxContentScripts=this.contentElement.createChild('div','blackbox-content-scripts');blackboxContentScripts.appendChild(UI.SettingsUI.createSettingCheckbox(ls`Blackbox content scripts`,Common.moduleSetting('skipContentScripts'),true));blackboxContentScripts.title=ls`Blackbox content scripts (extension scripts in the page)`;this._blackboxLabel=Common.UIString('Blackbox');this._disabledLabel=Common.UIString('Disabled');this._list=new UI.ListWidget(this);this._list.element.classList.add('blackbox-list');this._list.registerRequiredCSS('settings/frameworkBlackboxSettingsTab.css');const placeholder=createElementWithClass('div','blackbox-list-empty');placeholder.textContent=Common.UIString('No blackboxed patterns');this._list.setEmptyPlaceholder(placeholder);this._list.show(this.contentElement);const addPatternButton=UI.createTextButton(Common.UIString('Add pattern...'),this._addButtonClicked.bind(this),'add-button');this.contentElement.appendChild(addPatternButton);this._setting=Common.moduleSetting('skipStackFramesPattern');this._setting.addChangeListener(this._settingUpdated,this);this.setDefaultFocusedElement(addPatternButton);this.contentElement.tabIndex=0;}
wasShown(){super.wasShown();this._settingUpdated();}
_settingUpdated(){this._list.clear();const patterns=this._setting.getAsArray();for(let i=0;i<patterns.length;++i)
this._list.appendItem(patterns[i],true);}
_addButtonClicked(){this._list.addNewItem(this._setting.getAsArray().length,{pattern:'',disabled:false});}
renderItem(item,editable){const element=createElementWithClass('div','blackbox-list-item');const pattern=element.createChild('div','blackbox-pattern');pattern.textContent=item.pattern;pattern.title=ls`Blackbox scripts whose names match`+' \''+item.pattern+'\'';element.createChild('div','blackbox-separator');element.createChild('div','blackbox-behavior').textContent=item.disabled?this._disabledLabel:this._blackboxLabel;if(item.disabled)
element.classList.add('blackbox-disabled');return element;}
removeItemRequested(item,index){const patterns=this._setting.getAsArray();patterns.splice(index,1);this._setting.setAsArray(patterns);}
commitEdit(item,editor,isNew){item.pattern=editor.control('pattern').value.trim();item.disabled=editor.control('behavior').value===this._disabledLabel;const list=this._setting.getAsArray();if(isNew)
list.push(item);this._setting.setAsArray(list);}
beginEdit(item){const editor=this._createEditor();editor.control('pattern').value=item.pattern;editor.control('behavior').value=item.disabled?this._disabledLabel:this._blackboxLabel;return editor;}
_createEditor(){if(this._editor)
return this._editor;const editor=new UI.ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const titles=content.createChild('div','blackbox-edit-row');titles.createChild('div','blackbox-pattern').textContent=Common.UIString('Pattern');titles.createChild('div','blackbox-separator blackbox-separator-invisible');titles.createChild('div','blackbox-behavior').textContent=Common.UIString('Behavior');const fields=content.createChild('div','blackbox-edit-row');fields.createChild('div','blackbox-pattern').appendChild(editor.createInput('pattern','text','/framework\\.js$',patternValidator.bind(this)));fields.createChild('div','blackbox-separator blackbox-separator-invisible');fields.createChild('div','blackbox-behavior').appendChild(editor.createSelect('behavior',[this._blackboxLabel,this._disabledLabel],behaviorValidator));return editor;function patternValidator(item,index,input){const pattern=input.value.trim();const patterns=this._setting.getAsArray();for(let i=0;i<patterns.length;++i){if(i!==index&&patterns[i].pattern===pattern)
return false;}
let regex;try{regex=new RegExp(pattern);}catch(e){}
return!!(pattern&&regex);}
function behaviorValidator(item,index,input){return true;}}};;Runtime.cachedResources["settings/frameworkBlackboxSettingsTab.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow:hidden;\n}\n\n.header {\n padding: 0 0 6px;\n border-bottom: 1px solid #EEEEEE;\n font-size: 18px;\n font-weight: normal;\n flex: none;\n}\n\n.intro {\n margin-top: 10px;\n}\n\n.blackbox-content-scripts {\n margin-top: 10px;\n flex: none;\n}\n\n.add-button {\n margin: 10px 2px;\n align-self: flex-start;\n flex: none;\n}\n\n.blackbox-list {\n margin-top: 10px;\n max-width: 500px;\n flex: 0 1 auto;\n min-height: 30px;\n}\n\n.blackbox-list-empty {\n flex: auto;\n height: 30px;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.blackbox-list-item {\n padding: 3px 5px 3px 5px;\n height: 30px;\n display: flex;\n align-items: center;\n position: relative;\n flex: auto 1 1;\n}\n\n .blackbox-list-item .blackbox-pattern {\n white-space: nowrap;\n text-overflow: ellipsis;\n -webkit-user-select: none;\n color: #222;\n overflow: hidden;\n}\n\n.blackbox-pattern {\n flex: auto;\n min-width: 100px;\n}\n\n.blackbox-list-item.blackbox-disabled .blackbox-pattern {\n text-decoration: line-through;\n}\n\n.blackbox-behavior {\n flex: 0 0 100px;\n padding-left: 10px;\n}\n\n.blackbox-behavior > select {\n margin-left: -10px;\n}\n\n.blackbox-separator {\n flex: 0 0 1px;\n background-color: rgb(231, 231, 231);\n height: 30px;\n margin: 0 4px;\n}\n\n.blackbox-separator-invisible {\n visibility: hidden;\n height: 100% !important;\n}\n\n.blackbox-edit-row {\n flex: none;\n display: flex;\n flex-direction: row;\n margin: 6px 5px;\n align-items: center;\n}\n\n.blackbox-edit-row input,\n.blackbox-edit-row select {\n width: 100%;\n text-align: inherit;\n}\n\n/*# sourceURL=settings/frameworkBlackboxSettingsTab.css */";Runtime.cachedResources["settings/settingsScreen.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.settings-window-main {\n color: rgb(48, 57, 66);\n background-color: white;\n padding: 11px 0 0 0;\n}\n\n.settings-content {\n overflow-y: auto;\n overflow-x: hidden;\n margin: 8px 8px 8px 0;\n padding: 0 4px;\n flex: auto;\n}\n\n.settings-footnote {\n border-top: 1px solid #EEEEEE;\n margin: 0;\n padding: 12px;\n}\n\n.settings-container {\n width: 100%;\n -webkit-column-width: 288px;\n}\n\n.settings-block {\n display: block;\n padding-bottom: 9px;\n width: 288px;\n -webkit-column-break-inside: avoid;\n}\n\n.settings-tab.settings-container {\n -webkit-column-width: 308px;\n}\n\n.settings-tab .settings-block {\n margin-left: 20px;\n}\n\n.settings-line {\n padding-bottom: 5px;\n margin-bottom: 5px;\n}\n\n.settings-key-cell {\n display: inline-block;\n width: 153px;\n white-space: nowrap;\n text-align: right;\n vertical-align: middle;\n padding-right: 6px;\n}\n\n.settings-cell {\n display: inline-block;\n width: 135px;\n vertical-align: middle;\n}\n\n.settings-section-title {\n font-size: 120%;\n text-align: left;\n}\n\n.settings-key {\n padding: 0.1em 0.6em;\n border: 1px solid #ccc;\n font-size: 11px;\n background-color: #f7f7f7;\n color: #333;\n box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), 0 0 0 2px #ffffff inset;\n border-radius: 3px;\n display: inline-block;\n margin: 0 0.1em;\n text-shadow: 0 1px 0 #fff;\n line-height: 1.5;\n white-space: nowrap;\n}\n\n.settings-combine-keys,\n.settings-key-delimiter {\n font-size: 9px;\n}\n\n.settings-combine-keys {\n margin: 0 0.3em;\n}\n\n.settings-key-delimiter {\n margin: 0 0.5em;\n display: none;\n}\n\nfieldset {\n margin: 0;\
initialFilePaths(){const savedSnippets=this._snippetsSetting.get();return savedSnippets.map(snippet=>escape(snippet.name));}
async createFile(path,name){const nextId=this._lastSnippetIdentifierSetting.get()+1;this._lastSnippetIdentifierSetting.set(nextId);const snippetName=`Script snippet #${nextId}`;const snippets=this._snippetsSetting.get();snippets.push({name:snippetName,content:''});this._snippetsSetting.set(snippets);return escape(snippetName);}
async deleteFile(path){const name=unescape(path.substring(1));const allSnippets=this._snippetsSetting.get();const snippets=allSnippets.filter(snippet=>snippet.name!==name);if(allSnippets.length!==snippets.length){this._snippetsSetting.set(snippets);return true;}
return false;}
requestFileContent(path,callback){const name=unescape(path.substring(1));const snippet=this._snippetsSetting.get().find(snippet=>snippet.name===name);callback(snippet?snippet.content:null,false);}
async setFileContent(path,content,isBase64){const name=unescape(path.substring(1));const snippets=this._snippetsSetting.get();const snippet=snippets.find(snippet=>snippet.name===name);if(snippet){snippet.content=content;this._snippetsSetting.set(snippets);return true;}
return false;}
renameFile(path,newName,callback){const name=unescape(path.substring(1));const snippets=this._snippetsSetting.get();const snippet=snippets.find(snippet=>snippet.name===name);newName=newName.trim();if(!snippet||newName.length===0||snippets.find(snippet=>snippet.name===newName)){callback(false);return;}
snippet.name=newName;this._snippetsSetting.set(snippets);callback(true,newName);}
async searchInPath(query,progress){const re=new RegExp(query.escapeForRegExp(),'i');const snippets=this._snippetsSetting.get().filter(snippet=>snippet.content.match(re));return snippets.map(snippet=>escape(snippet.name));}
mimeFromPath(path){return'text/javascript';}
contentType(path){return Common.resourceTypes.Script;}
tooltipForURL(url){return ls`Linked to ${unescape(url.substring(this.path().length))}`;}
supportsAutomapping(){return true;}};Snippets.evaluateScriptSnippet=async function(uiSourceCode){if(!uiSourceCode.url().startsWith('snippet://'))
return;const executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext)
return;const runtimeModel=executionContext.runtimeModel;await uiSourceCode.requestContent();uiSourceCode.commitWorkingCopy();const expression=uiSourceCode.workingCopy();Common.console.show();const url=uiSourceCode.url();const result=await executionContext.evaluate({expression:`${expression}\n//# sourceURL=${url}`,objectGroup:'console',silent:false,includeCommandLineAPI:true,returnByValue:false,generatePreview:true,},false,true);if(result.exceptionDetails){SDK.consoleModel.addMessage(SDK.ConsoleMessage.fromException(runtimeModel,result.exceptionDetails,undefined,undefined,url));return;}
if(!result.object)
return;const scripts=executionContext.debuggerModel.scriptsForSourceURL(url);const scriptId=scripts[scripts.length-1].scriptId;SDK.consoleModel.addMessage(new SDK.ConsoleMessage(runtimeModel,SDK.ConsoleMessage.MessageSource.JS,SDK.ConsoleMessage.MessageLevel.Info,'',SDK.ConsoleMessage.MessageType.Result,url,undefined,undefined,[result.object],undefined,undefined,executionContext.id,scriptId));};Snippets.isSnippetsUISourceCode=function(uiSourceCode){return uiSourceCode.url().startsWith('snippet://');};Snippets.isSnippetsProject=function(project){return project.type()===Workspace.projectTypes.FileSystem&&Persistence.FileSystemWorkspaceBinding.fileSystemType(project)==='snippets';};Persistence.isolatedFileSystemManager.addPlatformFileSystem('snippet://',new Snippets.SnippetFileSystem());Snippets.project=(Workspace.workspace.projectsForType(Workspace.projectTypes.FileSystem).find(project=>Persistence.FileSystemWorkspaceBinding.fileSystemType(project)==='snippets'));;Snippets.SnippetsQuickOpen=class extends QuickOpen.FilteredListWidget.Provider{constructor(){super();this._snippets=[];}
selectItem(itemIndex,promptValue){if(itemIndex===null)
return;Snippets.evaluateScriptSnippet(this._snippets[itemIndex]);}
notFoundText(query){return Common.UIString('No snippets found.');}
attach(){this._snippets=Snippets.project.uiSourceCodes();}
detach(){this._snippets=[];}
itemCount(){return this._snippets.length;}
itemKeyAt(itemIndex){return this._snippets[itemIndex].name();}
renderItem(itemIndex,query,titleElement,subtitleElement){titleElement.textContent=unescape(this._snippets[itemIndex].name());titleElement.classList.add('monospace');QuickOpen.FilteredListWidget.highlightRanges(titleElement,query,true);}};;SourceFrame.BinaryResourceViewFactory=class{constructor(base64content,contentUrl,resourceType){this._base64content=base64content;this._contentUrl=contentUrl;this._resourceType=resourceType;this._arrayPromise=null;this._hexPromise=null;this._utf8Promise=null;}
async _fetchContentAsArray(){if(!this._arrayPromise){this._arrayPromise=new Promise(async resolve=>{const fetchResponse=await fetch('data:;base64,'+this._base64content);resolve(new Uint8Array(await fetchResponse.arrayBuffer()));});}
return await this._arrayPromise;}
async hex(){if(!this._hexPromise){this._hexPromise=new Promise(async resolve=>{const content=await this._fetchContentAsArray();const hexString=SourceFrame.BinaryResourceViewFactory.uint8ArrayToHexString(content);resolve(hexString);});}
return this._hexPromise;}
async base64(){return this._base64content;}
async utf8(){if(!this._utf8Promise){this._utf8Promise=new Promise(async resolve=>{const content=await this._fetchContentAsArray();const utf8String=new TextDecoder('utf8').decode(content);resolve(utf8String);});}
return this._utf8Promise;}
createBase64View(){return new SourceFrame.ResourceSourceFrame(Common.StaticContentProvider.fromString(this._contentUrl,this._resourceType,this._base64content),false,{lineNumbers:false,lineWrapping:true});}
createHexView(){const hexViewerContentProvider=new Common.StaticContentProvider(this._contentUrl,this._resourceType,async()=>SourceFrame.BinaryResourceViewFactory.uint8ArrayToHexViewer(await this._fetchContentAsArray()));return new SourceFrame.ResourceSourceFrame(hexViewerContentProvider,false,{lineNumbers:false,lineWrapping:false});}
createUtf8View(){const utf8fn=(this.utf8.bind(this));const utf8ContentProvider=new Common.StaticContentProvider(this._contentUrl,this._resourceType,utf8fn);return new SourceFrame.ResourceSourceFrame(utf8ContentProvider,false,{lineNumbers:true,lineWrapping:true});}
static uint8ArrayToHexString(uint8Array){let output='';for(let i=0;i<uint8Array.length;i++)
output+=SourceFrame.BinaryResourceViewFactory.numberToHex(uint8Array[i],2);return output;}
static numberToHex(number,padding){let hex=number.toString(16);while(hex.length<padding)
hex='0'+hex;return hex;}
static uint8ArrayToHexViewer(array){let output='';let line=0;while((line*16)<array.length){const lineArray=array.slice(line*16,(line+1)*16);output+=SourceFrame.BinaryResourceViewFactory.numberToHex(line,8)+':';let hexColsPrinted=0;for(let i=0;i<lineArray.length;i++){if(i%2===0){output+=' ';hexColsPrinted++;}
output+=SourceFrame.BinaryResourceViewFactory.numberToHex(lineArray[i],2);hexColsPrinted+=2;}
while(hexColsPrinted<42){output+=' ';hexColsPrinted++;}
for(let i=0;i<lineArray.length;i++){const code=lineArray[i];if(code>=32&&code<=126){output+=String.fromCharCode(code);}else{output+='.';}}
output+='\n';line++;}
return output;}};;SourceFrame.SourcesTextEditor=class extends TextEditor.CodeMirrorTextEditor{constructor(delegate,codeMirrorOptions){const defaultCodeMirrorOptions={lineNumbers:true,lineWrapping:false,bracketMatchingSetting:Common.moduleSetting('textEditorBracketMatching'),padBottom:true};if(codeMirrorOptions)
Object.assign(defaultCodeMirrorOptions,codeMirrorOptions);super(defaultCodeMirrorOptions);this.codeMirror().addKeyMap({'Enter':'smartNewlineAndIndent','Esc':'sourcesDismiss'});this._delegate=delegate;this.codeMirror().on('cursorActivity',this._cursorActivity.bind(this));this.codeMirror().on('gutterClick',this._gutterClick.bind(this));this.codeMirror().on('scroll',this._scroll.bind(this));this.codeMirror().on('focus',this._focus.bind(this));this.codeMirror().on('blur',this._blur.bind(this));this.codeMirror().on('beforeSelectionChange',this._fireBeforeSelectionChanged.bind(this));this.element.addEventListener('contextmenu',this._contextMenu.bind(this),false);this._gutterMouseMove=event=>{this.element.classList.toggle('CodeMirror-gutter-hovered',event.clientX<this.codeMirror().getGutterElement().getBoundingClientRect().right);};this._gutterMouseOut=event=>{this.element.classList.toggle('CodeMirror-gutter-hovered',false);};this.codeMirror().addKeyMap(SourceFrame.SourcesTextEditor._BlockIndentController);this._tokenHighlighter=new SourceFrame.SourcesTextEditor.TokenHighlighter(this,this.codeMirror());this._gutters=['CodeMirror-linenumbers'];this.codeMirror().setOption('gutters',this._gutters.slice());this.codeMirror().setOption('electricChars',false);this.codeMirror().setOption('smartIndent',false);function updateAnticipateJumpFlag(value){this._isHandlingMouseDownEvent=value;}
this.element.addEventListener('mousedown',updateAnticipateJumpFlag.bind(this,true),true);this.element.addEventListener('mousedown',updateAnticipateJumpFlag.bind(this,false),false);Common.moduleSetting('textEditorIndent').addChangeListener(this._onUpdateEditorIndentation,this);Common.moduleSetting('textEditorAutoDetectIndent').addChangeListener(this._onUpdateEditorIndentation,this);Common.moduleSetting('showWhitespacesInEditor').addChangeListener(this._updateWhitespace,this);Common.moduleSetting('textEditorCodeFolding').addChangeListener(this._updateCodeFolding,this);this._updateCodeFolding();this._autocompleteConfig={isWordChar:TextUtils.TextUtils.isWordChar};Common.moduleSetting('textEditorAutocompletion').addChangeListener(this._updateAutocomplete,this);this._updateAutocomplete();this._onUpdateEditorIndentation();this._setupWhitespaceHighlight();}
attachInfobar(infobar){this.element.insertBefore(infobar.element,this.element.firstChild);infobar.setParentView(this);this.doResize();}
static _guessIndentationLevel(lines){const tabRegex=/^\t+/;let tabLines=0;const indents={};for(let lineNumber=0;lineNumber<lines.length;++lineNumber){const text=lines[lineNumber];if(text.length===0||!TextUtils.TextUtils.isSpaceChar(text[0]))
continue;if(tabRegex.test(text)){++tabLines;continue;}
let i=0;while(i<text.length&&TextUtils.TextUtils.isSpaceChar(text[i]))
++i;if(i%2!==0)
continue;indents[i]=1+(indents[i]||0);}
const linesCountPerIndentThreshold=3*lines.length/100;if(tabLines&&tabLines>linesCountPerIndentThreshold)
return'\t';let minimumIndent=Infinity;for(const i in indents){if(indents[i]<linesCountPerIndentThreshold)
continue;const indent=parseInt(i,10);if(minimumIndent>indent)
minimumIndent=indent;}
if(minimumIndent===Infinity)
return Common.moduleSetting('textEditorIndent').get();return' '.repeat(minimumIndent);}
_isSearchActive(){return!!this._tokenHighlighter.highlightedRegex();}
scrollToLine(lineNumber){super.scrollToLine(lineNumber);this._scroll();}
highlightSearchResults(regex,range){function innerHighlightRegex(){if(range){this.scrollLineIntoView(range.startLine);if(range.endColumn>TextEditor.CodeMirrorTextEditor.maxHighlightLength)
this.setSelection(range);else
this.setSelection(TextUtils.TextRange.createFromLocation(range.startLine,range.startColumn));}
this._tokenHighlighter.highlightSearchResults(regex,range);}
if(!this._selectionBeforeSearch)
this._selectionBeforeSearch=this.selection();this.codeMirror().operation(innerHighlightRegex.bind(this));}
cancelSearchResultsHighlight(){this.codeMirror().operation(this._tokenHighlighter.highlightSelectedTokens.bind(this._tokenHighlighter));if(this._selectionBeforeSearch){this._reportJump(this._selectionBeforeSearch,this.selection());delete this._selectionBeforeSearch;}}
removeHighlight(highlightDescriptor){highlightDescriptor.clear();}
highlightRange(range,cssClass){cssClass='CodeMirror-persist-highlight '+cssClass;const pos=TextEditor.CodeMirrorUtils.toPos(range);++pos.end.ch;return this.codeMirror().markText(pos.start,pos.end,{className:cssClass,startStyle:cssClass+'-start',endStyle:cssClass+'-end'});}
installGutter(type,leftToNumbers){if(this._gutters.indexOf(type)!==-1)
return;if(leftToNumbers)
this._gutters.unshift(type);else
this._gutters.push(type);this.codeMirror().setOption('gutters',this._gutters.slice());this.refresh();}
uninstallGutter(type){const index=this._gutters.indexOf(type);if(index===-1)
return;this.codeMirror().clearGutter(type);this._gutters.splice(index,1);this.codeMirror().setOption('gutters',this._gutters.slice());this.refresh();}
setGutterDecoration(lineNumber,type,element){console.assert(this._gutters.indexOf(type)!==-1,'Cannot decorate unexisting gutter.');this.codeMirror().setGutterMarker(lineNumber,type,element);}
setExecutionLocation(lineNumber,columnNumber){this.clearPositionHighlight();this._executionLine=this.codeMirror().getLineHandle(lineNumber);if(!this._executionLine)
return;this.showExecutionLineBackground();this.codeMirror().addLineClass(this._executionLine,'wrap','cm-execution-line-outline');let token=this.tokenAtTextPosition(lineNumber,columnNumber);if(token&&!token.type&&token.startColumn+1===token.endColumn){const tokenContent=this.codeMirror().getLine(lineNumber)[token.startColumn];if(tokenContent==='.'||tokenContent==='(')
token=this.tokenAtTextPosition(lineNumber,token.endColumn+1);}
let endColumn;if(token&&token.type)
endColumn=token.endColumn;else
endColumn=this.codeMirror().getLine(lineNumber).length;this._executionLineTailMarker=this.codeMirror().markText({line:lineNumber,ch:columnNumber},{line:lineNumber,ch:endColumn},{className:'cm-execution-line-tail'});}
showExecutionLineBackground(){if(this._executionLine)
this.codeMirror().addLineClass(this._executionLine,'wrap','cm-execution-line');}
hideExecutionLineBackground(){if(this._executionLine)
this.codeMirror().removeLineClass(this._executionLine,'wrap','cm-execution-line');}
clearExecutionLine(){this.clearPositionHighlight();if(this._executionLine){this.hideExecutionLineBackground();this.codeMirror().removeLineClass(this._executionLine,'wrap','cm-execution-line-outline');}
delete this._executionLine;if(this._executionLineTailMarker)
this._executionLineTailMarker.clear();delete this._executionLineTailMarker;}
toggleLineClass(lineNumber,className,toggled){if(this.hasLineClass(lineNumber,className)===toggled)
return;const lineHandle=this.codeMirror().getLineHandle(lineNumber);if(!lineHandle)
return;if(toggled){this.codeMirror().addLineClass(lineHandle,'gutter',className);this.codeMirror().addLineClass(lineHandle,'wrap',className);}else{this.codeMirror().removeLineClass(lineHandle,'gutter',className);this.codeMirror().removeLineClass(lineHandle,'wrap',className);}}
hasLineClass(lineNumber,className){const lineInfo=this.codeMirror().lineInfo(lineNumber);const wrapClass=lineInfo.wrapClass||'';const classNames=wrapClass.split(' ');return classNames.indexOf(className)!==-1;}
_gutterClick(instance,lineNumber,gutter,event){if(gutter!=='CodeMirror-linenumbers')
return;this.dispatchEventToListeners(SourceFrame.SourcesTextEditor.Events.GutterClick,{lineNumber:lineNumber,event:event});}
_contextMenu(event){const contextMenu=new UI.ContextMenu(event);event.consume(true);const wrapper=event.target.enclosingNodeOrSelfWithClass('CodeMirror-gutter-wrapper');const target=wrapper?wrapper.querySelector('.CodeMirror-linenumber'):null;let promise;if(target){promise=this._delegate.populateLineGutterContextMenu(contextMenu,parseInt(target.textContent,10)-1);}else{const textSelection=this.selection();promise=this._delegate.populateTextAreaContextMenu(contextMenu,textSelection.startLine,textSelection.startColumn);}
promise.then(showAsync.bind(this));function showAsync(){contextMenu.appendApplicableItems(this);contextMenu.show();}}
editRange(range,text,origin){const newRange=super.editRange(range,text,origin);if(Common.moduleSetting('textEditorAutoDetectIndent').get())
this._onUpdateEditorIndentation();return newRange;}
_onUpdateEditorIndentation(){this._setEditorIndentation(TextEditor.CodeMirrorUtils.pullLines(this.codeMirror(),SourceFrame.SourcesTextEditor.LinesToScanForIndentationGuessing));}
_setEditorIndentation(lines){const extraKeys={};let indent=Common.moduleSetting('textEditorIndent').get();if(Common.moduleSetting('textEditorAutoDetectIndent').get())
indent=SourceFrame.SourcesTextEditor._guessIndentationLevel(lines);if(indent===TextUtils.TextUtils.Indent.TabCharacter){this.codeMirror().setOption('indentWithTabs',true);this.codeMirror().setOption('indentUnit',4);}else{this.codeMirror().setOption('indentWithTabs',false);this.codeMirror().setOption('indentUnit',indent.length);extraKeys.Tab=function(codeMirror){if(codeMirror.somethingSelected())
return CodeMirror.Pass;const pos=codeMirror.getCursor('head');codeMirror.replaceRange(indent.substring(pos.ch%indent.length),codeMirror.getCursor());};}
this.codeMirror().setOption('extraKeys',extraKeys);this._indentationLevel=indent;}
indent(){return this._indentationLevel;}
_onAutoAppendedSpaces(){this._autoAppendedSpaces=this._autoAppendedSpaces||[];for(let i=0;i<this._autoAppendedSpaces.length;++i){const position=this._autoAppendedSpaces[i].resolve();if(!position)
continue;const line=this.line(position.lineNumber);if(line.length===position.columnNumber&&TextUtils.TextUtils.lineIndent(line).length===line.length){this.codeMirror().replaceRange('',new CodeMirror.Pos(position.lineNumber,0),new CodeMirror.Pos(position.lineNumber,position.columnNumber));}}
this._autoAppendedSpaces=[];const selections=this.selections();for(let i=0;i<selections.length;++i){const selection=selections[i];this._autoAppendedSpaces.push(this.textEditorPositionHandle(selection.startLine,selection.startColumn));}}
_cursorActivity(){if(!this._isSearchActive())
this.codeMirror().operation(this._tokenHighlighter.highlightSelectedTokens.bind(this._tokenHighlighter));const start=this.codeMirror().getCursor('anchor');const end=this.codeMirror().getCursor('head');this.dispatchEventToListeners(SourceFrame.SourcesTextEditor.Events.SelectionChanged,TextEditor.CodeMirrorUtils.toRange(start,end));}
_reportJump(from,to){if(from&&to&&from.equal(to))
return;this.dispatchEventToListeners(SourceFrame.SourcesTextEditor.Events.JumpHappened,{from:from,to:to});}
_scroll(){const topmostLineNumber=this.codeMirror().lineAtHeight(this.codeMirror().getScrollInfo().top,'local');this.dispatchEventToListeners(SourceFrame.SourcesTextEditor.Events.ScrollChanged,topmostLineNumber);}
_focus(){this.dispatchEventToListeners(SourceFrame.SourcesTextEditor.Events.EditorFocused);}
_blur(){this.dispatchEventToListeners(SourceFrame.SourcesTextEditor.Events.EditorBlurred);}
_fireBeforeSelectionChanged(codeMirror,selection){if(!this._isHandlingMouseDownEvent)
return;if(!selection.ranges.length)
return;const primarySelection=selection.ranges[0];this._reportJump(this.selection(),TextEditor.CodeMirrorUtils.toRange(primarySelection.anchor,primarySelection.head));}
dispose(){super.dispose();Common.moduleSetting('textEditorIndent').removeChangeListener(this._onUpdateEditorIndentation,this);Common.moduleSetting('textEditorAutoDetectIndent').removeChangeListener(this._onUpdateEditorIndentation,this);Common.moduleSetting('showWhitespacesInEditor').removeChangeListener(this._updateWhitespace,this);Common.moduleSetting('textEditorCodeFolding').removeChangeListener(this._updateCodeFolding,this);}
setText(text){this._setEditorIndentation(text.split('\n').slice(0,SourceFrame.SourcesTextEditor.LinesToScanForIndentationGuessing));super.setText(text);}
_updateWhitespace(){this.setMimeType(this.mimeType());}
_updateCodeFolding(){if(Common.moduleSetting('textEditorCodeFolding').get()){this.installGutter('CodeMirror-foldgutter',false);this.element.addEventListener('mousemove',this._gutterMouseMove);this.element.addEventListener('mouseout',this._gutterMouseOut);this.codeMirror().setOption('foldGutter',true);this.codeMirror().setOption('foldOptions',{minFoldSize:1});}else{this.codeMirror().execCommand('unfoldAll');this.element.removeEventListener('mousemove',this._gutterMouseMove);this.element.removeEventListener('mouseout',this._gutterMouseOut);this.uninstallGutter('CodeMirror-foldgutter');this.codeMirror().setOption('foldGutter',false);}}
rewriteMimeType(mimeType){this._setupWhitespaceHighlight();const whitespaceMode=Common.moduleSetting('showWhitespacesInEditor').get();this.element.classList.toggle('show-whitespaces',whitespaceMode==='all');if(whitespaceMode==='all')
return this._allWhitespaceOverlayMode(mimeType);else if(whitespaceMode==='trailing')
return this._trailingWhitespaceOverlayMode(mimeType);return mimeType;}
_allWhitespaceOverlayMode(mimeType){let modeName=CodeMirror.mimeModes[mimeType]?(CodeMirror.mimeModes[mimeType].name||CodeMirror.mimeModes[mimeType]):CodeMirror.mimeModes['text/plain'];modeName+='+all-whitespaces';if(CodeMirror.modes[modeName])
return modeName;function modeConstructor(config,parserConfig){function nextToken(stream){if(stream.peek()===' '){let spaces=0;while(spaces<SourceFrame.SourcesTextEditor.MaximumNumberOfWhitespacesPerSingleSpan&&stream.peek()===' '){++spaces;stream.next();}
return'whitespace whitespace-'+spaces;}
while(!stream.eol()&&stream.peek()!==' ')
stream.next();return null;}
const whitespaceMode={token:nextToken};return CodeMirror.overlayMode(CodeMirror.getMode(config,mimeType),whitespaceMode,false);}
CodeMirror.defineMode(modeName,modeConstructor);return modeName;}
_trailingWhitespaceOverlayMode(mimeType){let modeName=CodeMirror.mimeModes[mimeType]?(CodeMirror.mimeModes[mimeType].name||CodeMirror.mimeModes[mimeType]):CodeMirror.mimeModes['text/plain'];modeName+='+trailing-whitespaces';if(CodeMirror.modes[modeName])
return modeName;function modeConstructor(config,parserConfig){function nextToken(stream){if(stream.match(/^\s+$/,true))
return true?'trailing-whitespace':null;do
stream.next();while(!stream.eol()&&stream.peek()!==' ');return null;}
const whitespaceMode={token:nextToken};return CodeMirror.overlayMode(CodeMirror.getMode(config,mimeType),whitespaceMode,false);}
CodeMirror.defineMode(modeName,modeConstructor);return modeName;}
_setupWhitespaceHighlight(){const doc=this.element.ownerDocument;if(doc._codeMirrorWhitespaceStyleInjected||!Common.moduleSetting('showWhitespacesInEditor').get())
return;doc._codeMirrorWhitespaceStyleInjected=true;const classBase='.show-whitespaces .CodeMirror .cm-whitespace-';const spaceChar='·';let spaceChars='';let rules='';for(let i=1;i<=SourceFrame.SourcesTextEditor.MaximumNumberOfWhitespacesPerSingleSpan;++i){spaceChars+=spaceChar;const rule=classBase+i+'::before { content: \''+spaceChars+'\';}\n';rules+=rule;}
const style=doc.createElement('style');style.textContent=rules;doc.head.appendChild(style);}
configureAutocomplete(config){this._autocompleteConfig=config;this._updateAutocomplete();}
_updateAutocomplete(){super.configureAutocomplete(Common.moduleSetting('textEditorAutocompletion').get()?this._autocompleteConfig:null);}};SourceFrame.SourcesTextEditor.GutterClickEventData;SourceFrame.SourcesTextEditor.Events={GutterClick:Symbol('GutterClick'),SelectionChanged:Symbol('SelectionChanged'),ScrollChanged:Symbol('ScrollChanged'),EditorFocused:Symbol('EditorFocused'),EditorBlurred:Symbol('EditorBlurred'),JumpHappened:Symbol('JumpHappened')};SourceFrame.SourcesTextEditorDelegate=function(){};SourceFrame.SourcesTextEditorDelegate.prototype={populateLineGutterContextMenu(contextMenu,lineNumber){},populateTextAreaContextMenu(contextMenu,lineNumber,columnNumber){},};CodeMirror.commands.smartNewlineAndIndent=function(codeMirror){codeMirror.operation(innerSmartNewlineAndIndent.bind(null,codeMirror));function innerSmartNewlineAndIndent(codeMirror){const selections=codeMirror.listSelections();const replacements=[];for(let i=0;i<selections.length;++i){const selection=selections[i];const cur=CodeMirror.cmpPos(selection.head,selection.anchor)<0?selection.head:selection.anchor;const line=codeMirror.getLine(cur.line);const indent=TextUtils.TextUtils.lineIndent(line);replacements.push('\n'+indent.substring(0,Math.min(cur.ch,indent.length)));}
codeMirror.replaceSelections(replacements);codeMirror._codeMirrorTextEditor._onAutoAppendedSpaces();}};CodeMirror.commands.sourcesDismiss=function(codemirror){if(codemirror.listSelections().length===1&&codemirror._codeMirrorTextEditor._isSearchActive())
return CodeMirror.Pass;return CodeMirror.commands.dismiss(codemirror);};SourceFrame.SourcesTextEditor._BlockIndentController={name:'blockIndentKeymap',Enter:function(codeMirror){let selections=codeMirror.listSelections();const replacements=[];let allSelectionsAreCollapsedBlocks=false;for(let i=0;i<selections.length;++i){const selection=selections[i];const start=CodeMirror.cmpPos(selection.head,selection.anchor)<0?selection.head:selection.anchor;const line=codeMirror.getLine(start.line);const indent=TextUtils.TextUtils.lineIndent(line);let indentToInsert='\n'+indent+codeMirror._codeMirrorTextEditor.indent();let isCollapsedBlock=false;if(selection.head.ch===0)
return CodeMirror.Pass;if(line.substr(selection.head.ch-1,2)==='{}'){indentToInsert+='\n'+indent;isCollapsedBlock=true;}else if(line.substr(selection.head.ch-1,1)!=='{'){return CodeMirror.Pass;}
if(i>0&&allSelectionsAreCollapsedBlocks!==isCollapsedBlock)
return CodeMirror.Pass;replacements.push(indentToInsert);allSelectionsAreCollapsedBlocks=isCollapsedBlock;}
codeMirror.replaceSelections(replacements);if(!allSelectionsAreCollapsedBlocks){codeMirror._codeMirrorTextEditor._onAutoAppendedSpaces();return;}
selections=codeMirror.listSelections();const updatedSelections=[];for(let i=0;i<selections.length;++i){const selection=selections[i];const line=codeMirror.getLine(selection.head.line-1);const position=new CodeMirror.Pos(selection.head.line-1,line.length);updatedSelections.push({head:position,anchor:position});}
codeMirror.setSelections(updatedSelections);codeMirror._codeMirrorTextEditor._onAutoAppendedSpaces();},'\'}\'':function(codeMirror){if(codeMirror.somethingSelected())
return CodeMirror.Pass;let selections=codeMirror.listSelections();let replacements=[];for(let i=0;i<selections.length;++i){const selection=selections[i];const line=codeMirror.getLine(selection.head.line);if(line!==TextUtils.TextUtils.lineIndent(line))
return CodeMirror.Pass;replacements.push('}');}
codeMirror.replaceSelections(replacements);selections=codeMirror.listSelections();replacements=[];const updatedSelections=[];for(let i=0;i<selections.length;++i){const selection=selections[i];const matchingBracket=codeMirror.findMatchingBracket(selection.head);if(!matchingBracket||!matchingBracket.match)
return;updatedSelections.push({head:selection.head,anchor:new CodeMirror.Pos(selection.head.line,0)});const line=codeMirror.getLine(matchingBracket.to.line);const indent=TextUtils.TextUtils.lineIndent(line);replacements.push(indent+'}');}
codeMirror.setSelections(updatedSelections);codeMirror.replaceSelections(replacements);}};SourceFrame.SourcesTextEditor.TokenHighlighter=class{constructor(textEditor,codeMirror){this._textEditor=textEditor;this._codeMirror=codeMirror;}
highlightSearchResults(regex,range){const oldRegex=this._highlightRegex;this._highlightRegex=regex;this._highlightRange=range;if(this._searchResultMarker){this._searchResultMarker.clear();delete this._searchResultMarker;}
if(this._highlightDescriptor&&this._highlightDescriptor.selectionStart)
this._codeMirror.removeLineClass(this._highlightDescriptor.selectionStart.line,'wrap','cm-line-with-selection');const selectionStart=this._highlightRange?new CodeMirror.Pos(this._highlightRange.startLine,this._highlightRange.startColumn):null;if(selectionStart)
this._codeMirror.addLineClass(selectionStart.line,'wrap','cm-line-with-selection');if(oldRegex&&this._highlightRegex.toString()===oldRegex.toString()){if(this._highlightDescriptor)
this._highlightDescriptor.selectionStart=selectionStart;}else{this._removeHighlight();this._setHighlighter(this._searchHighlighter.bind(this,this._highlightRegex),selectionStart);}
if(this._highlightRange){const pos=TextEditor.CodeMirrorUtils.toPos(this._highlightRange);this._searchResultMarker=this._codeMirror.markText(pos.start,pos.end,{className:'cm-column-with-selection'});}}
highlightedRegex(){return this._highlightRegex;}
highlightSelectedTokens(){delete this._highlightRegex;delete this._highlightRange;if(this._highlightDescriptor&&this._highlightDescriptor.selectionStart)
this._codeMirror.removeLineClass(this._highlightDescriptor.selectionStart.line,'wrap','cm-line-with-selection');this._removeHighlight();const selectionStart=this._codeMirror.getCursor('start');const selectionEnd=this._codeMirror.getCursor('end');if(selectionStart.line!==selectionEnd.line)
return;if(selectionStart.ch===selectionEnd.ch)
return;const selections=this._codeMirror.getSelections();if(selections.length>1)
return;const selectedText=selections[0];if(this._isWord(selectedText,selectionStart.line,selectionStart.ch,selectionEnd.ch)){if(selectionStart)
this._codeMirror.addLineClass(selectionStart.line,'wrap','cm-line-with-selection');this._setHighlighter(this._tokenHighlighter.bind(this,selectedText,selectionStart),selectionStart);}}
_isWord(selectedText,lineNumber,startColumn,endColumn){const line=this._codeMirror.getLine(lineNumber);const leftBound=startColumn===0||!TextUtils.TextUtils.isWordChar(line.charAt(startColumn-1));const rightBound=endColumn===line.length||!TextUtils.TextUtils.isWordChar(line.charAt(endColumn));return leftBound&&rightBound&&TextUtils.TextUtils.isWord(selectedText);}
_removeHighlight(){if(this._highlightDescriptor){this._codeMirror.removeOverlay(this._highlightDescriptor.overlay);delete this._highlightDescriptor;}}
_searchHighlighter(regex,stream){if(stream.column()===0)
delete this._searchMatchLength;if(this._searchMatchLength){if(this._searchMatchLength>2){for(let i=0;i<this._searchMatchLength-2;++i)
stream.next();this._searchMatchLength=1;return'search-highlight';}else{stream.next();delete this._searchMatchLength;return'search-highlight search-highlight-end';}}
const match=stream.match(regex,false);if(match){stream.next();const matchLength=match[0].length;if(matchLength===1)
return'search-highlight search-highlight-full';this._searchMatchLength=matchLength;return'search-highlight search-highlight-start';}
while(!stream.match(regex,false)&&stream.next()){}}
_tokenHighlighter(token,selectionStart,stream){const tokenFirstChar=token.charAt(0);if(stream.match(token)&&(stream.eol()||!TextUtils.TextUtils.isWordChar(stream.peek())))
return stream.column()===selectionStart.ch?'token-highlight column-with-selection':'token-highlight';let eatenChar;do
eatenChar=stream.next();while(eatenChar&&(TextUtils.TextUtils.isWordChar(eatenChar)||stream.peek()!==tokenFirstChar));}
_setHighlighter(highlighter,selectionStart){const overlayMode={token:highlighter};this._codeMirror.addOverlay(overlayMode);this._highlightDescriptor={overlay:overlayMode,selectionStart:selectionStart};}};SourceFrame.SourcesTextEditor.LinesToScanForIndentationGuessing=1000;SourceFrame.SourcesTextEditor.MaximumNumberOfWhitespacesPerSingleSpan=16;;SourceFrame.FontView=class extends UI.SimpleView{constructor(mimeType,contentProvider){super(Common.UIString('Font'));this.registerRequiredCSS('source_frame/fontView.css');this.element.classList.add('font-view');this._url=contentProvider.contentURL();this._mimeType=mimeType;this._contentProvider=contentProvider;this._mimeTypeLabel=new UI.ToolbarText(mimeType);}
syncToolbarItems(){return[this._mimeTypeLabel];}
_onFontContentLoaded(uniqueFontName,content){const url=content?Common.ContentProvider.contentAsDataURL(content,this._mimeType,true):this._url;this.fontStyleElement.textContent=String.sprintf('@font-face { font-family: "%s"; src: url(%s); }',uniqueFontName,url);}
_createContentIfNeeded(){if(this.fontPreviewElement)
return;const uniqueFontName='WebInspectorFontPreview'+(++SourceFrame.FontView._fontId);this.fontStyleElement=createElement('style');this._contentProvider.requestContent().then(this._onFontContentLoaded.bind(this,uniqueFontName));this.element.appendChild(this.fontStyleElement);const fontPreview=createElement('div');for(let i=0;i<SourceFrame.FontView._fontPreviewLines.length;++i){if(i>0)
fontPreview.createChild('br');fontPreview.createTextChild(SourceFrame.FontView._fontPreviewLines[i]);}
this.fontPreviewElement=fontPreview.cloneNode(true);this.fontPreviewElement.style.overflow='hidden';this.fontPreviewElement.style.setProperty('font-family',uniqueFontName);this.fontPreviewElement.style.setProperty('visibility','hidden');this._dummyElement=fontPreview;this._dummyElement.style.visibility='hidden';this._dummyElement.style.zIndex='-1';this._dummyElement.style.display='inline';this._dummyElement.style.position='absolute';this._dummyElement.style.setProperty('font-family',uniqueFontName);this._dummyElement.style.setProperty('font-size',SourceFrame.FontView._measureFontSize+'px');this.element.appendChild(this.fontPreviewElement);}
wasShown(){this._createContentIfNeeded();this.updateFontPreviewSize();}
onResize(){if(this._inResize)
return;this._inResize=true;try{this.updateFontPreviewSize();}finally{delete this._inResize;}}
_measureElement(){this.element.appendChild(this._dummyElement);const result={width:this._dummyElement.offsetWidth,height:this._dummyElement.offsetHeight};this.element.removeChild(this._dummyElement);return result;}
updateFontPreviewSize(){if(!this.fontPreviewElement||!this.isShowing())
return;this.fontPreviewElement.style.removeProperty('visibility');const dimension=this._measureElement();const height=dimension.height;const width=dimension.width;const containerWidth=this.element.offsetWidth-50;const containerHeight=this.element.offsetHeight-30;if(!height||!width||!containerWidth||!containerHeight){this.fontPreviewElement.style.removeProperty('font-size');return;}
const widthRatio=containerWidth/width;const heightRatio=containerHeight/height;const finalFontSize=Math.floor(SourceFrame.FontView._measureFontSize*Math.min(widthRatio,heightRatio))-2;this.fontPreviewElement.style.setProperty('font-size',finalFontSize+'px',null);}};SourceFrame.FontView._fontPreviewLines=['ABCDEFGHIJKLM','NOPQRSTUVWXYZ','abcdefghijklm','nopqrstuvwxyz','1234567890'];SourceFrame.FontView._fontId=0;SourceFrame.FontView._measureFontSize=50;;SourceFrame.ImageView=class extends UI.SimpleView{constructor(mimeType,contentProvider){super(Common.UIString('Image'));this.registerRequiredCSS('source_frame/imageView.css');this.element.classList.add('image-view');this._url=contentProvider.contentURL();this._parsedURL=new Common.ParsedURL(this._url);this._mimeType=mimeType;this._contentProvider=contentProvider;this._uiSourceCode=contentProvider instanceof Workspace.UISourceCode?(contentProvider):null;if(this._uiSourceCode){this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);new UI.DropTarget(this.element,[UI.DropTarget.Type.ImageFile,UI.DropTarget.Type.URI],Common.UIString('Drop image file here'),this._handleDrop.bind(this));}
this._sizeLabel=new UI.ToolbarText();this._dimensionsLabel=new UI.ToolbarText();this._mimeTypeLabel=new UI.ToolbarText(mimeType);this._container=this.element.createChild('div','image');this._imagePreviewElement=this._container.createChild('img','resource-image-view');this._imagePreviewElement.addEventListener('contextmenu',this._contextMenu.bind(this),true);}
syncToolbarItems(){return[this._sizeLabel,new UI.ToolbarSeparator(),this._dimensionsLabel,new UI.ToolbarSeparator(),this._mimeTypeLabel];}
wasShown(){this._updateContentIfNeeded();}
disposeView(){if(this._uiSourceCode){this._uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);}}
_workingCopyCommitted(){this._updateContentIfNeeded();}
async _updateContentIfNeeded(){const content=await this._contentProvider.requestContent();if(this._cachedContent===content)
return;const contentEncoded=await this._contentProvider.contentEncoded();this._cachedContent=content;let imageSrc=Common.ContentProvider.contentAsDataURL(content,this._mimeType,contentEncoded);if(content===null)
imageSrc=this._url;const loadPromise=new Promise(x=>this._imagePreviewElement.onload=x);this._imagePreviewElement.src=imageSrc;const size=content&&!contentEncoded?content.length:base64ToSize(content);this._sizeLabel.setText(Number.bytesToString(size));await loadPromise;this._dimensionsLabel.setText(Common.UIString('%d × %d',this._imagePreviewElement.naturalWidth,this._imagePreviewElement.naturalHeight));}
_contextMenu(event){const contextMenu=new UI.ContextMenu(event);if(!this._parsedURL.isDataURL())
contextMenu.clipboardSection().appendItem(Common.UIString('Copy image URL'),this._copyImageURL.bind(this));if(this._imagePreviewElement.src){contextMenu.clipboardSection().appendItem(Common.UIString('Copy image as data URI'),this._copyImageAsDataURL.bind(this));}
contextMenu.clipboardSection().appendItem(Common.UIString('Open image in new tab'),this._openInNewTab.bind(this));contextMenu.clipboardSection().appendItem(Common.UIString('Save\u2026'),this._saveImage.bind(this));contextMenu.show();}
_copyImageAsDataURL(){InspectorFrontendHost.copyText(this._imagePreviewElement.src);}
_copyImageURL(){InspectorFrontendHost.copyText(this._url);}
_saveImage(){const link=createElement('a');link.download=this._parsedURL.displayName;link.href=this._url;link.click();}
_openInNewTab(){InspectorFrontendHost.openInNewTab(this._url);}
async _handleDrop(dataTransfer){const items=dataTransfer.items;if(!items.length||items[0].kind!=='file')
return;const entry=items[0].webkitGetAsEntry();const encoded=!entry.name.endsWith('.svg');entry.file(file=>{const reader=new FileReader();reader.onloadend=()=>{let result;try{result=(reader.result);}catch(e){result=null;console.error('Can\'t read file: '+e);}
if(typeof result!=='string')
return;this._uiSourceCode.setContent(encoded?btoa(result):result,encoded);};if(encoded)
reader.readAsBinaryString(file);else
reader.readAsText(file);});}};;SourceFrame.SourceFrame=class extends UI.SimpleView{constructor(lazyContent,codeMirrorOptions){super(Common.UIString('Source'));this._lazyContent=lazyContent;this._pretty=false;this._rawContent=null;this._formattedContentPromise=null;this._formattedMap=null;this._prettyToggle=new UI.ToolbarToggle(ls`Pretty print`,'largeicon-pretty-print');this._prettyToggle.addEventListener(UI.ToolbarButton.Events.Click,()=>{this._setPretty(!this._prettyToggle.toggled());});this._shouldAutoPrettyPrint=false;this._prettyToggle.setVisible(false);this._textEditor=new SourceFrame.SourcesTextEditor(this,codeMirrorOptions);this._textEditor.show(this.element);this._prettyCleanGeneration=null;this._cleanGeneration=0;this._searchConfig=null;this._delayedFindSearchMatches=null;this._currentSearchResultIndex=-1;this._searchResults=[];this._searchRegex=null;this._textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.EditorFocused,this._resetCurrentSearchResultIndex,this);this._textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.SelectionChanged,this._updateSourcePosition,this);this._textEditor.addEventListener(UI.TextEditor.Events.TextChanged,event=>{if(!this._muteChangeEventsForSetContent)
this.onTextChanged(event.data.oldRange,event.data.newRange);});this._muteChangeEventsForSetContent=false;this._sourcePosition=new UI.ToolbarText();this._searchableView=null;this._editable=false;this._textEditor.setReadOnly(true);this._positionToReveal=null;this._lineToScrollTo=null;this._selectionToSet=null;this._loaded=false;this._contentRequested=false;this._highlighterType='';this._transformer={editorToRawLocation:(editorLineNumber,editorColumnNumber=0)=>{if(!this._pretty)
return[editorLineNumber,editorColumnNumber];return this._prettyToRawLocation(editorLineNumber,editorColumnNumber);},rawToEditorLocation:(lineNumber,columnNumber=0)=>{if(!this._pretty)
return[lineNumber,columnNumber];return this._rawToPrettyLocation(lineNumber,columnNumber);}};}
setCanPrettyPrint(canPrettyPrint,autoPrettyPrint){this._shouldAutoPrettyPrint=canPrettyPrint&&!!autoPrettyPrint;this._prettyToggle.setVisible(canPrettyPrint);}
async _setPretty(value){this._pretty=value;this._prettyToggle.setEnabled(false);const wasLoaded=this.loaded;const selection=this.selection();let newSelection;if(this._pretty){const formatInfo=await this._requestFormattedContent();this._formattedMap=formatInfo.map;this.setContent(formatInfo.content);this._prettyCleanGeneration=this._textEditor.markClean();const start=this._rawToPrettyLocation(selection.startLine,selection.startColumn);const end=this._rawToPrettyLocation(selection.endLine,selection.endColumn);newSelection=new TextUtils.TextRange(start[0],start[1],end[0],end[1]);}else{this.setContent(this._rawContent);this._cleanGeneration=this._textEditor.markClean();const start=this._prettyToRawLocation(selection.startLine,selection.startColumn);const end=this._prettyToRawLocation(selection.endLine,selection.endColumn);newSelection=new TextUtils.TextRange(start[0],start[1],end[0],end[1]);}
if(wasLoaded){this.textEditor.revealPosition(newSelection.endLine,newSelection.endColumn,this._editable);this.textEditor.setSelection(newSelection);}
this._prettyToggle.setEnabled(true);this._updatePrettyPrintState();}
_updatePrettyPrintState(){this._prettyToggle.setToggled(this._pretty);this._textEditor.element.classList.toggle('pretty-printed',this._pretty);if(this._pretty){this._textEditor.setLineNumberFormatter(lineNumber=>{const line=this._prettyToRawLocation(lineNumber-1,0)[0]+1;if(lineNumber===1)
return String(line);if(line!==this._prettyToRawLocation(lineNumber-2,0)[0]+1)
return String(line);return'-';});}else{this._textEditor.setLineNumberFormatter(lineNumber=>{return String(lineNumber);});}}
transformer(){return this._transformer;}
_prettyToRawLocation(line,column){if(!this._formattedMap)
return[line,column];return this._formattedMap.formattedToOriginal(line,column);}
_rawToPrettyLocation(line,column){if(!this._formattedMap)
return[line,column];return this._formattedMap.originalToFormatted(line,column);}
setEditable(editable){this._editable=editable;if(this._loaded)
this._textEditor.setReadOnly(!editable);}
wasShown(){this._ensureContentLoaded();this._wasShownOrLoaded();}
willHide(){super.willHide();this._clearPositionToReveal();}
syncToolbarItems(){return[this._prettyToggle,this._sourcePosition];}
get loaded(){return this._loaded;}
get textEditor(){return this._textEditor;}
get pretty(){return this._pretty;}
async _ensureContentLoaded(){if(!this._contentRequested){this._contentRequested=true;const content=await this._lazyContent();this._rawContent=content||'';this._formattedContentPromise=null;this._formattedMap=null;this._prettyToggle.setEnabled(true);if(this._shouldAutoPrettyPrint&&TextUtils.isMinified(content))
await this._setPretty(true);else
this.setContent(this._rawContent);}}
_requestFormattedContent(){if(this._formattedContentPromise)
return this._formattedContentPromise;let fulfill;this._formattedContentPromise=new Promise(x=>fulfill=x);new Formatter.ScriptFormatter(this._highlighterType,this._rawContent||'',(content,map)=>{fulfill({content,map});});return this._formattedContentPromise;}
revealPosition(line,column,shouldHighlight){this._lineToScrollTo=null;this._selectionToSet=null;this._positionToReveal={line:line,column:column,shouldHighlight:shouldHighlight};this._innerRevealPositionIfNeeded();}
_innerRevealPositionIfNeeded(){if(!this._positionToReveal)
return;if(!this.loaded||!this.isShowing())
return;const[line,column]=this._transformer.rawToEditorLocation(this._positionToReveal.line,this._positionToReveal.column);this._textEditor.revealPosition(line,column,this._positionToReveal.shouldHighlight);this._positionToReveal=null;}
_clearPositionToReveal(){this._textEditor.clearPositionHighlight();this._positionToReveal=null;}
scrollToLine(line){this._clearPositionToReveal();this._lineToScrollTo=line;this._innerScrollToLineIfNeeded();}
_innerScrollToLineIfNeeded(){if(this._lineToScrollTo!==null){if(this.loaded&&this.isShowing()){this._textEditor.scrollToLine(this._lineToScrollTo);this._lineToScrollTo=null;}}}
selection(){return this.textEditor.selection();}
setSelection(textRange){this._selectionToSet=textRange;this._innerSetSelectionIfNeeded();}
_innerSetSelectionIfNeeded(){if(this._selectionToSet&&this.loaded&&this.isShowing()){this._textEditor.setSelection(this._selectionToSet,true);this._selectionToSet=null;}}
_wasShownOrLoaded(){this._innerRevealPositionIfNeeded();this._innerSetSelectionIfNeeded();this._innerScrollToLineIfNeeded();}
onTextChanged(oldRange,newRange){const wasPretty=this.pretty;this._pretty=this._prettyCleanGeneration!==null&&this.textEditor.isClean(this._prettyCleanGeneration);if(this._pretty!==wasPretty)
this._updatePrettyPrintState();this._prettyToggle.setEnabled(this.isClean());if(this._searchConfig&&this._searchableView)
this.performSearch(this._searchConfig,false,false);}
isClean(){return this.textEditor.isClean(this._cleanGeneration)||(this._prettyCleanGeneration!==null&&this.textEditor.isClean(this._prettyCleanGeneration));}
contentCommitted(){this._cleanGeneration=this._textEditor.markClean();this._prettyCleanGeneration=null;this._rawContent=this.textEditor.text();this._formattedMap=null;this._formattedContentPromise=null;if(this._pretty){this._pretty=false;this._updatePrettyPrintState();}
this._prettyToggle.setEnabled(true);}
_simplifyMimeType(content,mimeType){if(!mimeType)
return'';if(mimeType.indexOf('javascript')>=0||mimeType.indexOf('jscript')>=0||mimeType.indexOf('ecmascript')>=0)
return'text/javascript';if(mimeType==='text/x-php'&&content.match(/\<\?.*\?\>/g))
return'application/x-httpd-php';return mimeType;}
setHighlighterType(highlighterType){this._highlighterType=highlighterType;this._updateHighlighterType('');}
highlighterType(){return this._highlighterType;}
_updateHighlighterType(content){this._textEditor.setMimeType(this._simplifyMimeType(content,this._highlighterType));}
setContent(content){this._muteChangeEventsForSetContent=true;if(!this._loaded){this._loaded=true;this._textEditor.setText(content||'');this._cleanGeneration=this._textEditor.markClean();this._textEditor.setReadOnly(!this._editable);}else{const scrollTop=this._textEditor.scrollTop();const selection=this._textEditor.selection();this._textEditor.setText(content||'');this._textEditor.setScrollTop(scrollTop);this._textEditor.setSelection(selection);}
this._updateHighlighterType(content||'');this._wasShownOrLoaded();if(this._delayedFindSearchMatches){this._delayedFindSearchMatches();this._delayedFindSearchMatches=null;}
this._muteChangeEventsForSetContent=false;}
setSearchableView(view){this._searchableView=view;}
_doFindSearchMatches(searchConfig,shouldJump,jumpBackwards){this._currentSearchResultIndex=-1;this._searchResults=[];const regex=searchConfig.toSearchRegex();this._searchRegex=regex;this._searchResults=this._collectRegexMatches(regex);if(this._searchableView)
this._searchableView.updateSearchMatchesCount(this._searchResults.length);if(!this._searchResults.length)
this._textEditor.cancelSearchResultsHighlight();else if(shouldJump&&jumpBackwards)
this.jumpToPreviousSearchResult();else if(shouldJump)
this.jumpToNextSearchResult();else
this._textEditor.highlightSearchResults(regex,null);}
performSearch(searchConfig,shouldJump,jumpBackwards){if(this._searchableView)
this._searchableView.updateSearchMatchesCount(0);this._resetSearch();this._searchConfig=searchConfig;if(this.loaded)
this._doFindSearchMatches(searchConfig,shouldJump,!!jumpBackwards);else
this._delayedFindSearchMatches=this._doFindSearchMatches.bind(this,searchConfig,shouldJump,!!jumpBackwards);this._ensureContentLoaded();}
_resetCurrentSearchResultIndex(){if(!this._searchResults.length)
return;this._currentSearchResultIndex=-1;if(this._searchableView)
this._searchableView.updateCurrentMatchIndex(this._currentSearchResultIndex);this._textEditor.highlightSearchResults((this._searchRegex),null);}
_resetSearch(){this._searchConfig=null;this._delayedFindSearchMatches=null;this._currentSearchResultIndex=-1;this._searchResults=[];this._searchRegex=null;}
searchCanceled(){const range=this._currentSearchResultIndex!==-1?this._searchResults[this._currentSearchResultIndex]:null;this._resetSearch();if(!this.loaded)
return;this._textEditor.cancelSearchResultsHighlight();if(range)
this.setSelection(range);}
jumpToLastSearchResult(){this.jumpToSearchResult(this._searchResults.length-1);}
_searchResultIndexForCurrentSelection(){return this._searchResults.lowerBound(this._textEditor.selection().collapseToEnd(),TextUtils.TextRange.comparator);}
jumpToNextSearchResult(){const currentIndex=this._searchResultIndexForCurrentSelection();const nextIndex=this._currentSearchResultIndex===-1?currentIndex:currentIndex+1;this.jumpToSearchResult(nextIndex);}
jumpToPreviousSearchResult(){const currentIndex=this._searchResultIndexForCurrentSelection();this.jumpToSearchResult(currentIndex-1);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}
jumpToSearchResult(index){if(!this.loaded||!this._searchResults.length)
return;this._currentSearchResultIndex=(index+this._searchResults.length)%this._searchResults.length;if(this._searchableView)
this._searchableView.updateCurrentMatchIndex(this._currentSearchResultIndex);this._textEditor.highlightSearchResults((this._searchRegex),this._searchResults[this._currentSearchResultIndex]);}
replaceSelectionWith(searchConfig,replacement){const range=this._searchResults[this._currentSearchResultIndex];if(!range)
return;this._textEditor.highlightSearchResults((this._searchRegex),null);const oldText=this._textEditor.text(range);const regex=searchConfig.toSearchRegex();let text;if(regex.__fromRegExpQuery){text=oldText.replace(regex,replacement);}else{text=oldText.replace(regex,function(){return replacement;});}
const newRange=this._textEditor.editRange(range,text);this._textEditor.setSelection(newRange.collapseToEnd());}
replaceAllWith(searchConfig,replacement){this._resetCurrentSearchResultIndex();let text=this._textEditor.text();const range=this._textEditor.fullRange();const regex=searchConfig.toSearchRegex(true);if(regex.__fromRegExpQuery){text=text.replace(regex,replacement);}else{text=text.replace(regex,function(){return replacement;});}
const ranges=this._collectRegexMatches(regex);if(!ranges.length)
return;const currentRangeIndex=ranges.lowerBound(this._textEditor.selection(),TextUtils.TextRange.comparator);const lastRangeIndex=mod(currentRangeIndex-1,ranges.length);const lastRange=ranges[lastRangeIndex];const replacementLineEndings=replacement.computeLineEndings();const replacementLineCount=replacementLineEndings.length;const lastLineNumber=lastRange.startLine+replacementLineEndings.length-1;let lastColumnNumber=lastRange.startColumn;if(replacementLineEndings.length>1){lastColumnNumber=replacementLineEndings[replacementLineCount-1]-replacementLineEndings[replacementLineCount-2]-1;}
this._textEditor.editRange(range,text);this._textEditor.revealPosition(lastLineNumber,lastColumnNumber);this._textEditor.setSelection(TextUtils.TextRange.createFromLocation(lastLineNumber,lastColumnNumber));}
_collectRegexMatches(regexObject){const ranges=[];for(let i=0;i<this._textEditor.linesCount;++i){let line=this._textEditor.line(i);let offset=0;let match;do{match=regexObject.exec(line);if(match){const matchEndIndex=match.index+Math.max(match[0].length,1);if(match[0].length)
ranges.push(new TextUtils.TextRange(i,offset+match.index,i,offset+matchEndIndex));offset+=matchEndIndex;line=line.substring(matchEndIndex);}}while(match&&line);}
return ranges;}
populateLineGutterContextMenu(contextMenu,editorLineNumber){return Promise.resolve();}
populateTextAreaContextMenu(contextMenu,editorLineNumber,editorColumnNumber){return Promise.resolve();}
canEditSource(){return this._editable;}
_updateSourcePosition(){const selections=this._textEditor.selections();if(!selections.length)
return;if(selections.length>1){this._sourcePosition.setText(Common.UIString('%d selection regions',selections.length));return;}
let textRange=selections[0];if(textRange.isEmpty()){const location=this._prettyToRawLocation(textRange.endLine,textRange.endColumn);this._sourcePosition.setText(ls`Line ${location[0] + 1}, Column ${location[1] + 1}`);return;}
textRange=textRange.normalize();const selectedText=this._textEditor.text(textRange);if(textRange.startLine===textRange.endLine){this._sourcePosition.setText(Common.UIString('%d characters selected',selectedText.length));}else{this._sourcePosition.setText(Common.UIString('%d lines, %d characters selected',textRange.endLine-textRange.startLine+1,selectedText.length));}}};SourceFrame.LineDecorator=function(){};SourceFrame.LineDecorator.prototype={decorate(uiSourceCode,textEditor,type){}};SourceFrame.Transformer;;SourceFrame.ResourceSourceFrame=class extends SourceFrame.SourceFrame{constructor(resource,autoPrettyPrint,codeMirrorOptions){super(async()=>{let content=await resource.requestContent();if(await resource.contentEncoded())
content=window.atob(content);return content;},codeMirrorOptions);this._resource=resource;this.setCanPrettyPrint(this._resource.contentType().isDocumentOrScriptOrStyleSheet(),autoPrettyPrint);}
static createSearchableView(resource,highlighterType,autoPrettyPrint){return new SourceFrame.ResourceSourceFrame.SearchableContainer(resource,highlighterType,autoPrettyPrint);}
get resource(){return this._resource;}
populateTextAreaContextMenu(contextMenu,lineNumber,columnNumber){contextMenu.appendApplicableItems(this._resource);return Promise.resolve();}};SourceFrame.ResourceSourceFrame.SearchableContainer=class extends UI.VBox{constructor(resource,highlighterType,autoPrettyPrint){super(true);this.registerRequiredCSS('source_frame/resourceSourceFrame.css');const sourceFrame=new SourceFrame.ResourceSourceFrame(resource,autoPrettyPrint);this._sourceFrame=sourceFrame;sourceFrame.setHighlighterType(highlighterType);const searchableView=new UI.SearchableView(sourceFrame);searchableView.element.classList.add('searchable-view');searchableView.setPlaceholder(ls`Find`);sourceFrame.show(searchableView.element);sourceFrame.setSearchableView(searchableView);searchableView.show(this.contentElement);const toolbar=new UI.Toolbar('toolbar',this.contentElement);for(const item of sourceFrame.syncToolbarItems())
toolbar.appendToolbarItem(item);}
async revealPosition(lineNumber,columnNumber){this._sourceFrame.revealPosition(lineNumber,columnNumber,true);}};;SourceFrame.JSONView=class extends UI.VBox{constructor(parsedJSON){super();this._initialized=false;this.registerRequiredCSS('source_frame/jsonView.css');this._parsedJSON=parsedJSON;this.element.classList.add('json-view');this._searchableView;this._treeOutline;this._currentSearchFocusIndex=0;this._currentSearchTreeElements=[];this._searchRegex=null;}
static async createView(content){const parsedJSON=await SourceFrame.JSONView._parseJSON(content);if(!parsedJSON||typeof parsedJSON.data!=='object')
return null;const jsonView=new SourceFrame.JSONView(parsedJSON);const searchableView=new UI.SearchableView(jsonView);searchableView.setPlaceholder(Common.UIString('Find'));jsonView._searchableView=searchableView;jsonView.show(searchableView.element);jsonView.element.setAttribute('tabIndex',0);return searchableView;}
static createViewSync(obj){const jsonView=new SourceFrame.JSONView(new SourceFrame.ParsedJSON(obj,'',''));const searchableView=new UI.SearchableView(jsonView);searchableView.setPlaceholder(Common.UIString('Find'));jsonView._searchableView=searchableView;jsonView.show(searchableView.element);jsonView.element.setAttribute('tabIndex',0);return searchableView;}
static _parseJSON(text){let returnObj=null;if(text)
returnObj=SourceFrame.JSONView._extractJSON((text));if(!returnObj)
return Promise.resolve((null));return Formatter.formatterWorkerPool().parseJSONRelaxed(returnObj.data).then(handleReturnedJSON);function handleReturnedJSON(data){if(!data)
return null;returnObj.data=data;return returnObj;}}
static _extractJSON(text){if(text.startsWith('<'))
return null;let inner=SourceFrame.JSONView._findBrackets(text,'{','}');const inner2=SourceFrame.JSONView._findBrackets(text,'[',']');inner=inner2.length>inner.length?inner2:inner;if(inner.length===-1||text.length-inner.length>80)
return null;const prefix=text.substring(0,inner.start);const suffix=text.substring(inner.end+1);text=text.substring(inner.start,inner.end+1);if(suffix.trim().length&&!(suffix.trim().startsWith(')')&&prefix.trim().endsWith('(')))
return null;return new SourceFrame.ParsedJSON(text,prefix,suffix);}
static _findBrackets(text,open,close){const start=text.indexOf(open);const end=text.lastIndexOf(close);let length=end-start-1;if(start===-1||end===-1||end<start)
length=-1;return{start:start,end:end,length:length};}
wasShown(){this._initialize();}
_initialize(){if(this._initialized)
return;this._initialized=true;const obj=SDK.RemoteObject.fromLocalObject(this._parsedJSON.data);const title=this._parsedJSON.prefix+obj.description+this._parsedJSON.suffix;this._treeOutline=new ObjectUI.ObjectPropertiesSection(obj,title,undefined,undefined,undefined,undefined,true);this._treeOutline.enableContextMenu();this._treeOutline.setEditable(false);this._treeOutline.expand();this.element.appendChild(this._treeOutline.element);}
_jumpToMatch(index){if(!this._searchRegex)
return;const previousFocusElement=this._currentSearchTreeElements[this._currentSearchFocusIndex];if(previousFocusElement)
previousFocusElement.setSearchRegex(this._searchRegex);const newFocusElement=this._currentSearchTreeElements[index];if(newFocusElement){this._updateSearchIndex(index);newFocusElement.setSearchRegex(this._searchRegex,UI.highlightedCurrentSearchResultClassName);newFocusElement.reveal();}else{this._updateSearchIndex(0);}}
_updateSearchCount(count){if(!this._searchableView)
return;this._searchableView.updateSearchMatchesCount(count);}
_updateSearchIndex(index){this._currentSearchFocusIndex=index;if(!this._searchableView)
return;this._searchableView.updateCurrentMatchIndex(index);}
searchCanceled(){this._searchRegex=null;this._currentSearchTreeElements=[];for(let element=this._treeOutline.rootElement();element;element=element.traverseNextTreeElement(false)){if(!(element instanceof ObjectUI.ObjectPropertyTreeElement))
continue;element.revertHighlightChanges();}
this._updateSearchCount(0);this._updateSearchIndex(0);}
performSearch(searchConfig,shouldJump,jumpBackwards){let newIndex=this._currentSearchFocusIndex;const previousSearchFocusElement=this._currentSearchTreeElements[newIndex];this.searchCanceled();this._searchRegex=searchConfig.toSearchRegex(true);for(let element=this._treeOutline.rootElement();element;element=element.traverseNextTreeElement(false)){if(!(element instanceof ObjectUI.ObjectPropertyTreeElement))
continue;const hasMatch=element.setSearchRegex(this._searchRegex);if(hasMatch)
this._currentSearchTreeElements.push(element);if(previousSearchFocusElement===element){const currentIndex=this._currentSearchTreeElements.length-1;if(hasMatch||jumpBackwards)
newIndex=currentIndex;else
newIndex=currentIndex+1;}}
this._updateSearchCount(this._currentSearchTreeElements.length);if(!this._currentSearchTreeElements.length){this._updateSearchIndex(0);return;}
newIndex=mod(newIndex,this._currentSearchTreeElements.length);this._jumpToMatch(newIndex);}
jumpToNextSearchResult(){if(!this._currentSearchTreeElements.length)
return;const newIndex=mod(this._currentSearchFocusIndex+1,this._currentSearchTreeElements.length);this._jumpToMatch(newIndex);}
jumpToPreviousSearchResult(){if(!this._currentSearchTreeElements.length)
return;const newIndex=mod(this._currentSearchFocusIndex-1,this._currentSearchTreeElements.length);this._jumpToMatch(newIndex);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}};SourceFrame.ParsedJSON=class{constructor(data,prefix,suffix){this.data=data;this.prefix=prefix;this.suffix=suffix;}};;SourceFrame.XMLView=class extends UI.Widget{constructor(parsedXML){super(true);this.registerRequiredCSS('source_frame/xmlView.css');this.contentElement.classList.add('shadow-xml-view','source-code');this._treeOutline=new UI.TreeOutlineInShadow();this._treeOutline.registerRequiredCSS('source_frame/xmlTree.css');this.contentElement.appendChild(this._treeOutline.element);this._searchableView;this._currentSearchFocusIndex=0;this._currentSearchTreeElements=[];this._searchConfig;SourceFrame.XMLView.Node.populate(this._treeOutline,parsedXML,this);}
static createSearchableView(parsedXML){const xmlView=new SourceFrame.XMLView(parsedXML);const searchableView=new UI.SearchableView(xmlView);searchableView.setPlaceholder(Common.UIString('Find'));xmlView._searchableView=searchableView;xmlView.show(searchableView.element);xmlView.contentElement.setAttribute('tabIndex',0);return searchableView;}
static parseXML(text,mimeType){let parsedXML;try{parsedXML=(new DOMParser()).parseFromString(text,mimeType);}catch(e){return null;}
if(parsedXML.body)
return null;return parsedXML;}
_jumpToMatch(index,shouldJump){if(!this._searchConfig)
return;const regex=this._searchConfig.toSearchRegex(true);const previousFocusElement=this._currentSearchTreeElements[this._currentSearchFocusIndex];if(previousFocusElement)
previousFocusElement.setSearchRegex(regex);const newFocusElement=this._currentSearchTreeElements[index];if(newFocusElement){this._updateSearchIndex(index);if(shouldJump)
newFocusElement.reveal(true);newFocusElement.setSearchRegex(regex,UI.highlightedCurrentSearchResultClassName);}else{this._updateSearchIndex(0);}}
_updateSearchCount(count){if(!this._searchableView)
return;this._searchableView.updateSearchMatchesCount(count);}
_updateSearchIndex(index){this._currentSearchFocusIndex=index;if(!this._searchableView)
return;this._searchableView.updateCurrentMatchIndex(index);}
_innerPerformSearch(shouldJump,jumpBackwards){if(!this._searchConfig)
return;let newIndex=this._currentSearchFocusIndex;const previousSearchFocusElement=this._currentSearchTreeElements[newIndex];this._innerSearchCanceled();this._currentSearchTreeElements=[];const regex=this._searchConfig.toSearchRegex(true);for(let element=this._treeOutline.rootElement();element;element=element.traverseNextTreeElement(false)){if(!(element instanceof SourceFrame.XMLView.Node))
continue;const hasMatch=element.setSearchRegex(regex);if(hasMatch)
this._currentSearchTreeElements.push(element);if(previousSearchFocusElement===element){const currentIndex=this._currentSearchTreeElements.length-1;if(hasMatch||jumpBackwards)
newIndex=currentIndex;else
newIndex=currentIndex+1;}}
this._updateSearchCount(this._currentSearchTreeElements.length);if(!this._currentSearchTreeElements.length){this._updateSearchIndex(0);return;}
newIndex=mod(newIndex,this._currentSearchTreeElements.length);this._jumpToMatch(newIndex,shouldJump);}
_innerSearchCanceled(){for(let element=this._treeOutline.rootElement();element;element=element.traverseNextTreeElement(false)){if(!(element instanceof SourceFrame.XMLView.Node))
continue;element.revertHighlightChanges();}
this._updateSearchCount(0);this._updateSearchIndex(0);}
searchCanceled(){this._searchConfig=null;this._currentSearchTreeElements=[];this._innerSearchCanceled();}
performSearch(searchConfig,shouldJump,jumpBackwards){this._searchConfig=searchConfig;this._innerPerformSearch(shouldJump,jumpBackwards);}
jumpToNextSearchResult(){if(!this._currentSearchTreeElements.length)
return;const newIndex=mod(this._currentSearchFocusIndex+1,this._currentSearchTreeElements.length);this._jumpToMatch(newIndex,true);}
jumpToPreviousSearchResult(){if(!this._currentSearchTreeElements.length)
return;const newIndex=mod(this._currentSearchFocusIndex-1,this._currentSearchTreeElements.length);this._jumpToMatch(newIndex,true);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}};SourceFrame.XMLView.Node=class extends UI.TreeElement{constructor(node,closeTag,xmlView){super('',!closeTag&&!!node.childElementCount);this._node=node;this._closeTag=closeTag;this.selectable=false;this._highlightChanges=[];this._xmlView=xmlView;this._updateTitle();}
static populate(root,xmlNode,xmlView){let node=xmlNode.firstChild;while(node){const currentNode=node;node=node.nextSibling;const nodeType=currentNode.nodeType;if(nodeType===3&&currentNode.nodeValue.match(/\s+/))
continue;if((nodeType!==1)&&(nodeType!==3)&&(nodeType!==4)&&(nodeType!==7)&&(nodeType!==8))
continue;root.appendChild(new SourceFrame.XMLView.Node(currentNode,false,xmlView));}}
setSearchRegex(regex,additionalCssClassName){this.revertHighlightChanges();if(!regex)
return false;if(this._closeTag&&this.parent&&!this.parent.expanded)
return false;regex.lastIndex=0;let cssClasses=UI.highlightedSearchResultClassName;if(additionalCssClassName)
cssClasses+=' '+additionalCssClassName;const content=this.listItemElement.textContent.replace(/\xA0/g,' ');let match=regex.exec(content);const ranges=[];while(match){ranges.push(new TextUtils.SourceRange(match.index,match[0].length));match=regex.exec(content);}
if(ranges.length)
UI.highlightRangesWithStyleClass(this.listItemElement,ranges,cssClasses,this._highlightChanges);return!!this._highlightChanges.length;}
revertHighlightChanges(){UI.revertDomChanges(this._highlightChanges);this._highlightChanges=[];}
_updateTitle(){const node=this._node;switch(node.nodeType){case 1:const tag=node.tagName;if(this._closeTag){this._setTitle(['</'+tag+'>','shadow-xml-view-tag']);return;}
const titleItems=['<'+tag,'shadow-xml-view-tag'];const attributes=node.attributes;for(let i=0;i<attributes.length;++i){const attributeNode=attributes.item(i);titleItems.push('\u00a0','shadow-xml-view-tag',attributeNode.name,'shadow-xml-view-attribute-name','="','shadow-xml-view-tag',attributeNode.value,'shadow-xml-view-attribute-value','"','shadow-xml-view-tag');}
if(!this.expanded){if(node.childElementCount){titleItems.push('>','shadow-xml-view-tag','\u2026','shadow-xml-view-comment','</'+tag,'shadow-xml-view-tag');}else if(this._node.textContent){titleItems.push('>','shadow-xml-view-tag',node.textContent,'shadow-xml-view-text','</'+tag,'shadow-xml-view-tag');}else{titleItems.push(' /','shadow-xml-view-tag');}}
titleItems.push('>','shadow-xml-view-tag');this._setTitle(titleItems);return;case 3:this._setTitle([node.nodeValue,'shadow-xml-view-text']);return;case 4:this._setTitle(['<![CDATA[','shadow-xml-view-cdata',node.nodeValue,'shadow-xml-view-text',']]>','shadow-xml-view-cdata']);return;case 7:this._setTitle(['<?'+node.nodeName+' '+node.nodeValue+'?>','shadow-xml-view-processing-instruction']);return;case 8:this._setTitle(['<!--'+node.nodeValue+'-->','shadow-xml-view-comment']);return;}}
_setTitle(items){const titleFragment=createDocumentFragment();for(let i=0;i<items.length;i+=2)
titleFragment.createChild('span',items[i+1]).textContent=items[i];this.title=titleFragment;this._xmlView._innerPerformSearch(false,false);}
onattach(){this.listItemElement.classList.toggle('shadow-xml-view-close-tag',this._closeTag);}
onexpand(){this._updateTitle();}
oncollapse(){this._updateTitle();}
onpopulate(){SourceFrame.XMLView.Node.populate(this,this._node,this._xmlView);this.appendChild(new SourceFrame.XMLView.Node(this._node,true,this._xmlView));}};;SourceFrame.PreviewFactory=class{static async createPreview(provider,mimeType){let resourceType=Common.ResourceType.fromMimeType(mimeType);if(resourceType===Common.resourceTypes.Other)
resourceType=provider.contentType();switch(resourceType){case Common.resourceTypes.Image:return new SourceFrame.ImageView(mimeType,provider);case Common.resourceTypes.Font:return new SourceFrame.FontView(mimeType,provider);}
let content=await provider.requestContent();if(!content)
return new UI.EmptyWidget(Common.UIString('Nothing to preview'));if(await provider.contentEncoded())
content=window.atob(content);const parsedXML=SourceFrame.XMLView.parseXML(content,mimeType);if(parsedXML)
return SourceFrame.XMLView.createSearchableView(parsedXML);const jsonView=await SourceFrame.JSONView.createView(content);if(jsonView)
return jsonView;if(resourceType.isTextType()){const highlighterType=provider.contentType().canonicalMimeType()||mimeType.replace(/;.*/,'');return SourceFrame.ResourceSourceFrame.createSearchableView(provider,highlighterType,true);}
return null;}};;SourceFrame.SourceCodeDiff=class{constructor(textEditor){this._textEditor=textEditor;this._animatedLines=[];this._animationTimeout=null;}
highlightModifiedLines(oldContent,newContent){if(typeof oldContent!=='string'||typeof newContent!=='string')
return;const diff=SourceFrame.SourceCodeDiff.computeDiff(Diff.Diff.lineDiff(oldContent.split('\n'),newContent.split('\n')));const changedLines=[];for(let i=0;i<diff.length;++i){const diffEntry=diff[i];if(diffEntry.type===SourceFrame.SourceCodeDiff.EditType.Delete)
continue;for(let lineNumber=diffEntry.from;lineNumber<diffEntry.to;++lineNumber){const position=this._textEditor.textEditorPositionHandle(lineNumber,0);if(position)
changedLines.push(position);}}
this._updateHighlightedLines(changedLines);this._animationTimeout=setTimeout(this._updateHighlightedLines.bind(this,[]),400);}
_updateHighlightedLines(newLines){if(this._animationTimeout)
clearTimeout(this._animationTimeout);this._animationTimeout=null;this._textEditor.operation(operation.bind(this));function operation(){toggleLines.call(this,false);this._animatedLines=newLines;toggleLines.call(this,true);}
function toggleLines(value){for(let i=0;i<this._animatedLines.length;++i){const location=this._animatedLines[i].resolve();if(location)
this._textEditor.toggleLineClass(location.lineNumber,'highlight-line-modification',value);}}}
static computeDiff(diff){const result=[];let hasAdded=false;let hasRemoved=false;let blockStartLineNumber=0;let currentLineNumber=0;let isInsideBlock=false;for(let i=0;i<diff.length;++i){const token=diff[i];if(token[0]===Diff.Diff.Operation.Equal){if(isInsideBlock)
flush();currentLineNumber+=token[1].length;continue;}
if(!isInsideBlock){isInsideBlock=true;blockStartLineNumber=currentLineNumber;}
if(token[0]===Diff.Diff.Operation.Delete){hasRemoved=true;}else{currentLineNumber+=token[1].length;hasAdded=true;}}
if(isInsideBlock)
flush();if(result.length>1&&result[0].from===0&&result[1].from===0){const merged={type:SourceFrame.SourceCodeDiff.EditType.Modify,from:0,to:result[1].to};result.splice(0,2,merged);}
return result;function flush(){let type=SourceFrame.SourceCodeDiff.EditType.Insert;let from=blockStartLineNumber;let to=currentLineNumber;if(hasAdded&&hasRemoved){type=SourceFrame.SourceCodeDiff.EditType.Modify;}else if(!hasAdded&&hasRemoved&&from===0&&to===0){type=SourceFrame.SourceCodeDiff.EditType.Modify;to=1;}else if(!hasAdded&&hasRemoved){type=SourceFrame.SourceCodeDiff.EditType.Delete;from-=1;}
result.push({type:type,from:from,to:to});isInsideBlock=false;hasAdded=false;hasRemoved=false;}}};SourceFrame.SourceCodeDiff.EditType={Insert:Symbol('Insert'),Delete:Symbol('Delete'),Modify:Symbol('Modify'),};;Runtime.cachedResources["source_frame/fontView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.font-view {\n font-size: 60px;\n white-space: pre-wrap;\n word-wrap: break-word;\n text-align: center;\n padding: 15px;\n}\n\n/*# sourceURL=source_frame/fontView.css */";Runtime.cachedResources["source_frame/imageView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.image-view {\n overflow: auto;\n}\n\n.image-view > .image {\n padding: 20px 20px 10px 20px;\n text-align: center;\n}\n\n.image-view img.resource-image-view {\n max-width: 100%;\n max-height: 1000px;\n background-image: url(Images/checker.png);\n box-shadow: 0 5px 10px rgba(0, 0, 0, 0.5);\n -webkit-user-select: text;\n -webkit-user-drag: auto;\n}\n\n/*# sourceURL=source_frame/imageView.css */";Runtime.cachedResources["source_frame/jsonView.css"]=".json-view {\n padding: 2px 6px;\n overflow: auto;\n}\n\n/*# sourceURL=source_frame/jsonView.css */";Runtime.cachedResources["source_frame/messagesPopover.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.text-editor-messages-description-container {\n display: inline-block;\n}\n\n.text-editor-row-message:first-child {\n border-top-width: 0;\n}\n\n.text-editor-row-message {\n line-height: 1.2;\n white-space: nowrap;\n display: flex;\n align-items: center;\n justify-content: flex-start;\n margin-top: 2px;\n}\n\n.text-editor-row-message-repeat-count {\n margin-right: 0.5em;\n}\n\n/*# sourceURL=source_frame/messagesPopover.css */";Runtime.cachedResources["source_frame/xmlTree.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tree-outline ol {\n list-style: none;\n padding: 0;\n margin: 0;\n padding-inline-start: 16px;\n}\n\nol.tree-outline {\n padding-inline-start: 0;\n}\n\n.tree-outline li {\n min-height: 12px;\n}\n\n.tree-outline li.shadow-xml-view-close-tag {\n margin-left: -16px;\n}\n\n.shadow-xml-view-tag {\n color: rgb(136, 18, 128);\n}\n\n.shadow-xml-view-comment {\n color: rgb(35, 110, 37);\n}\n\n.shadow-xml-view-processing-instruction {\n color: rgb(35, 110, 37);\n}\n\n.shadow-xml-view-attribute-name {\n color: rgb(153, 69, 0);\n}\n\n.shadow-xml-view-attribute-value {\n color: rgb(26, 26, 166);\n}\n\n.shadow-xml-view-text {\n color: rgb(0, 0, 0);\n white-space: pre;\n}\n\n.shadow-xml-view-cdata {\n color: rgb(0, 0, 0);\n}\n\n/*# sourceURL=source_frame/xmlTree.css */";Runtime.cachedResources["source_frame/xmlView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.shadow-xml-view {\n -webkit-user-select: text;\n overflow: auto;\n padding: 2px 4px;\n}\n\n/*# sourceURL=source_frame/xmlView.css */";Runtime.cachedResources["source_frame/resourceSourceFrame.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n.searchable-view {\n flex: 1;\n}\n\n.toolbar {\n background-color: #eee;\n border-top: 1px solid #ccc;\n}\n\n/*# sourceURL=source_frame/resourceSourceFrame.css */";Sources.AddSourceMapURLDialog=class extends UI.HBox{constructor(callback){super(true);this.registerRequiredCS
static show(callback){const dialog=new UI.Dialog();const addSourceMapURLDialog=new Sources.AddSourceMapURLDialog(done);addSourceMapURLDialog.show(dialog.contentElement);dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.show();function done(value){dialog.hide();callback(value);}}
_apply(){this._callback(this._input.value);}
_onKeyDown(event){if(event.keyCode===UI.KeyboardShortcut.Keys.Enter.code){event.preventDefault();this._apply();}}};;Sources.BreakpointEditDialog=class extends UI.Widget{constructor(editorLineNumber,oldCondition,preferLogpoint,onFinish){super(true);this.registerRequiredCSS('sources/breakpointEditDialog.css');this._onFinish=onFinish;this._finished=false;this._editor=null;this.element.tabIndex=-1;const logpointPrefix=Sources.BreakpointEditDialog._LogpointPrefix;const logpointSuffix=Sources.BreakpointEditDialog._LogpointSuffix;this._isLogpoint=oldCondition.startsWith(logpointPrefix)&&oldCondition.endsWith(logpointSuffix);if(this._isLogpoint)
oldCondition=oldCondition.substring(logpointPrefix.length,oldCondition.length-logpointSuffix.length);this._isLogpoint=this._isLogpoint||preferLogpoint;this.element.classList.add('sources-edit-breakpoint-dialog');const toolbar=new UI.Toolbar('source-frame-breakpoint-toolbar',this.contentElement);toolbar.appendText(`Line ${editorLineNumber + 1}:`);this._typeSelector=new UI.ToolbarComboBox(this._onTypeChanged.bind(this));this._typeSelector.createOption(ls`Breakpoint`,'',Sources.BreakpointEditDialog.BreakpointType.Breakpoint);const conditionalOption=this._typeSelector.createOption(ls`Conditional breakpoint`,'',Sources.BreakpointEditDialog.BreakpointType.Conditional);const logpointOption=this._typeSelector.createOption(ls`Logpoint`,'',Sources.BreakpointEditDialog.BreakpointType.Logpoint);this._typeSelector.select(this._isLogpoint?logpointOption:conditionalOption);toolbar.appendToolbarItem(this._typeSelector);self.runtime.extension(UI.TextEditorFactory).instance().then(factory=>{const editorOptions={lineNumbers:false,lineWrapping:true,mimeType:'javascript',autoHeight:true};this._editor=factory.createEditor(editorOptions);this._updatePlaceholder();this._editor.widget().element.classList.add('condition-editor');this._editor.configureAutocomplete(ObjectUI.JavaScriptAutocompleteConfig.createConfigForEditor(this._editor));if(oldCondition)
this._editor.setText(oldCondition);this._editor.widget().show(this.contentElement);this._editor.setSelection(this._editor.fullRange());this._editor.widget().focus();this._editor.widget().element.addEventListener('keydown',this._onKeyDown.bind(this),true);this.contentElement.addEventListener('blur',event=>{if(event.relatedTarget&&!event.relatedTarget.isSelfOrDescendant(this.element))
this._finishEditing(true);},true);});}
static _conditionForLogpoint(condition){return`${Sources.BreakpointEditDialog._LogpointPrefix}${condition}${Sources.BreakpointEditDialog._LogpointSuffix}`;}
_onTypeChanged(){const value=this._typeSelector.selectedOption().value;this._isLogpoint=value===Sources.BreakpointEditDialog.BreakpointType.Logpoint;this._updatePlaceholder();if(value===Sources.BreakpointEditDialog.BreakpointType.Breakpoint){this._editor.setText('');this._finishEditing(true);}}
_updatePlaceholder(){const selectedValue=this._typeSelector.selectedOption().value;if(selectedValue===Sources.BreakpointEditDialog.BreakpointType.Conditional){this._editor.setPlaceholder(ls`Expression to check before pausing, e.g. x > 5`);this._typeSelector.element.title=ls`Pause only when the condition is true`;}else if(selectedValue===Sources.BreakpointEditDialog.BreakpointType.Logpoint){this._editor.setPlaceholder(ls`Log message, e.g. 'x is', x`);this._typeSelector.element.title=ls`Log a message to Console, do not break`;}}
_finishEditing(committed){if(this._finished)
return;this._finished=true;this._editor.widget().detach();let condition=this._editor.text();if(this._isLogpoint)
condition=Sources.BreakpointEditDialog._conditionForLogpoint(condition);this._onFinish({committed,condition});}
async _onKeyDown(event){if(isEnterKey(event)&&!event.shiftKey){event.consume(true);const expression=this._editor.text();if(event.ctrlKey||await ObjectUI.JavaScriptAutocomplete.isExpressionComplete(expression))
this._finishEditing(true);else
this._editor.newlineAndIndent();}
if(isEscKey(event))
this._finishEditing(false);}};Sources.BreakpointEditDialog._LogpointPrefix='/** DEVTOOLS_LOGPOINT */ console.log(';Sources.BreakpointEditDialog._LogpointSuffix=')';Sources.BreakpointEditDialog.BreakpointType={Breakpoint:'Breakpoint',Conditional:'Conditional',Logpoint:'Logpoint',};;Sources.CallStackSidebarPane=class extends UI.SimpleView{constructor(){super(Common.UIString('Call Stack'),true);this.registerRequiredCSS('sources/callStackSidebarPane.css');this._blackboxedMessageElement=this._createBlackboxedMessageElement();this.contentElement.appendChild(this._blackboxedMessageElement);this._notPausedMessageElement=this.contentElement.createChild('div','gray-info-message');this._notPausedMessageElement.textContent=Common.UIString('Not paused');this._items=new UI.ListModel();this._list=new UI.ListControl(this._items,this,UI.ListMode.NonViewport);this.contentElement.appendChild(this._list.element);this._list.element.addEventListener('contextmenu',this._onContextMenu.bind(this),false);this._list.element.addEventListener('click',this._onClick.bind(this),false);this._showMoreMessageElement=this._createShowMoreMessageElement();this._showMoreMessageElement.classList.add('hidden');this.contentElement.appendChild(this._showMoreMessageElement);this._showBlackboxed=false;this._locationPool=new Bindings.LiveLocationPool();this._updateThrottler=new Common.Throttler(100);this._maxAsyncStackChainDepth=Sources.CallStackSidebarPane._defaultMaxAsyncStackChainDepth;this._update();this._updateItemThrottler=new Common.Throttler(100);this._scheduledForUpdateItems=new Set();}
flavorChanged(object){this._showBlackboxed=false;this._maxAsyncStackChainDepth=Sources.CallStackSidebarPane._defaultMaxAsyncStackChainDepth;this._update();}
_update(){this._updateThrottler.schedule(()=>this._doUpdate());}
async _doUpdate(){this._locationPool.disposeAll();const details=UI.context.flavor(SDK.DebuggerPausedDetails);if(!details){this._notPausedMessageElement.classList.remove('hidden');this._blackboxedMessageElement.classList.add('hidden');this._showMoreMessageElement.classList.add('hidden');this._items.replaceAll([]);UI.context.setFlavor(SDK.DebuggerModel.CallFrame,null);return;}
let debuggerModel=details.debuggerModel;this._notPausedMessageElement.classList.add('hidden');const items=details.callFrames.map(frame=>{const item=Sources.CallStackSidebarPane.Item.createForDebuggerCallFrame(frame,this._locationPool,this._refreshItem.bind(this));item[Sources.CallStackSidebarPane._debuggerCallFrameSymbol]=frame;return item;});let asyncStackTrace=details.asyncStackTrace;if(!asyncStackTrace&&details.asyncStackTraceId){if(details.asyncStackTraceId.debuggerId)
debuggerModel=SDK.DebuggerModel.modelForDebuggerId(details.asyncStackTraceId.debuggerId);asyncStackTrace=debuggerModel?await debuggerModel.fetchAsyncStackTrace(details.asyncStackTraceId):null;}
let peviousStackTrace=details.callFrames;let maxAsyncStackChainDepth=this._maxAsyncStackChainDepth;while(asyncStackTrace&&maxAsyncStackChainDepth>0){let title='';const isAwait=asyncStackTrace.description==='async function';if(isAwait&&peviousStackTrace.length&&asyncStackTrace.callFrames.length){const lastPreviousFrame=peviousStackTrace[peviousStackTrace.length-1];const lastPreviousFrameName=UI.beautifyFunctionName(lastPreviousFrame.functionName);title=UI.asyncStackTraceLabel('await in '+lastPreviousFrameName);}else{title=UI.asyncStackTraceLabel(asyncStackTrace.description);}
items.push(...Sources.CallStackSidebarPane.Item.createItemsForAsyncStack(title,debuggerModel,asyncStackTrace.callFrames,this._locationPool,this._refreshItem.bind(this)));--maxAsyncStackChainDepth;peviousStackTrace=asyncStackTrace.callFrames;if(asyncStackTrace.parent){asyncStackTrace=asyncStackTrace.parent;}else if(asyncStackTrace.parentId){if(asyncStackTrace.parentId.debuggerId)
debuggerModel=SDK.DebuggerModel.modelForDebuggerId(asyncStackTrace.parentId.debuggerId);asyncStackTrace=debuggerModel?await debuggerModel.fetchAsyncStackTrace(asyncStackTrace.parentId):null;}else{asyncStackTrace=null;}}
this._showMoreMessageElement.classList.toggle('hidden',!asyncStackTrace);this._items.replaceAll(items);if(this._maxAsyncStackChainDepth===Sources.CallStackSidebarPane._defaultMaxAsyncStackChainDepth)
this._list.selectNextItem(true,false);this._updatedForTest();}
_updatedForTest(){}
_refreshItem(item){this._scheduledForUpdateItems.add(item);this._updateItemThrottler.schedule(innerUpdate.bind(this));function innerUpdate(){const items=Array.from(this._scheduledForUpdateItems);this._scheduledForUpdateItems.clear();this._muteActivateItem=true;if(!this._showBlackboxed&&this._items.every(item=>item.isBlackboxed)){this._showBlackboxed=true;for(let i=0;i<this._items.length;++i)
this._list.refreshItemByIndex(i);this._blackboxedMessageElement.classList.toggle('hidden',true);}else{const itemsSet=new Set(items);let hasBlackboxed=false;for(let i=0;i<this._items.length;++i){const item=this._items.at(i);if(itemsSet.has(item))
this._list.refreshItemByIndex(i);hasBlackboxed=hasBlackboxed||item.isBlackboxed;}
this._blackboxedMessageElement.classList.toggle('hidden',this._showBlackboxed||!hasBlackboxed);}
delete this._muteActivateItem;return Promise.resolve();}}
createElementForItem(item){const element=createElementWithClass('div','call-frame-item');const title=element.createChild('div','call-frame-item-title');title.createChild('div','call-frame-title-text').textContent=item.title;if(item.isAsyncHeader){element.classList.add('async-header');}else{const linkElement=element.createChild('div','call-frame-location');linkElement.textContent=item.linkText.trimMiddle(30);linkElement.title=item.linkText;element.classList.toggle('blackboxed-call-frame',item.isBlackboxed);}
element.classList.toggle('hidden',!this._showBlackboxed&&item.isBlackboxed);element.appendChild(UI.Icon.create('smallicon-thick-right-arrow','selected-call-frame-icon'));return element;}
heightForItem(item){console.assert(false);return 0;}
isItemSelectable(item){return!!item[Sources.CallStackSidebarPane._debuggerCallFrameSymbol];}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('selected');if(toElement)
toElement.classList.add('selected');if(to)
this._activateItem(to);}
_createBlackboxedMessageElement(){const element=createElementWithClass('div','blackboxed-message');element.createChild('span');const showAllLink=element.createChild('span','link');showAllLink.textContent=Common.UIString('Show blackboxed frames');showAllLink.addEventListener('click',()=>{this._showBlackboxed=true;for(const item of this._items)
this._refreshItem(item);this._blackboxedMessageElement.classList.toggle('hidden',true);});return element;}
_createShowMoreMessageElement(){const element=createElementWithClass('div','show-more-message');element.createChild('span');const showAllLink=element.createChild('span','link');showAllLink.textContent=Common.UIString('Show more');showAllLink.addEventListener('click',()=>{this._maxAsyncStackChainDepth+=Sources.CallStackSidebarPane._defaultMaxAsyncStackChainDepth;this._update();},false);return element;}
_onContextMenu(event){const item=this._list.itemForNode((event.target));if(!item)
return;const contextMenu=new UI.ContextMenu(event);const debuggerCallFrame=item[Sources.CallStackSidebarPane._debuggerCallFrameSymbol];if(debuggerCallFrame)
contextMenu.defaultSection().appendItem(Common.UIString('Restart frame'),()=>debuggerCallFrame.restart());contextMenu.defaultSection().appendItem(Common.UIString('Copy stack trace'),this._copyStackTrace.bind(this));if(item.uiLocation)
this.appendBlackboxURLContextMenuItems(contextMenu,item.uiLocation.uiSourceCode);contextMenu.show();}
_onClick(event){const item=this._list.itemForNode((event.target));if(item)
this._activateItem(item);}
_activateItem(item){const uiLocation=item.uiLocation;if(this._muteActivateItem||!uiLocation)
return;const debuggerCallFrame=item[Sources.CallStackSidebarPane._debuggerCallFrameSymbol];if(debuggerCallFrame&&UI.context.flavor(SDK.DebuggerModel.CallFrame)!==debuggerCallFrame){debuggerCallFrame.debuggerModel.setSelectedCallFrame(debuggerCallFrame);UI.context.setFlavor(SDK.DebuggerModel.CallFrame,debuggerCallFrame);}else{Common.Revealer.reveal(uiLocation);}}
appendBlackboxURLContextMenuItems(contextMenu,uiSourceCode){const binding=Persistence.persistence.binding(uiSourceCode);if(binding)
uiSourceCode=binding.network;if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem)
return;const canBlackbox=Bindings.blackboxManager.canBlackboxUISourceCode(uiSourceCode);const isBlackboxed=Bindings.blackboxManager.isBlackboxedUISourceCode(uiSourceCode);const isContentScript=uiSourceCode.project().type()===Workspace.projectTypes.ContentScripts;const manager=Bindings.blackboxManager;if(canBlackbox){if(isBlackboxed){contextMenu.defaultSection().appendItem(Common.UIString('Stop blackboxing'),manager.unblackboxUISourceCode.bind(manager,uiSourceCode));}else{contextMenu.defaultSection().appendItem(Common.UIString('Blackbox script'),manager.blackboxUISourceCode.bind(manager,uiSourceCode));}}
if(isContentScript){if(isBlackboxed){contextMenu.defaultSection().appendItem(Common.UIString('Stop blackboxing all content scripts'),manager.blackboxContentScripts.bind(manager));}else{contextMenu.defaultSection().appendItem(Common.UIString('Blackbox all content scripts'),manager.unblackboxContentScripts.bind(manager));}}}
_selectNextCallFrameOnStack(){return this._list.selectNextItem(false,false);}
_selectPreviousCallFrameOnStack(){return this._list.selectPreviousItem(false,false);}
_copyStackTrace(){const text=[];for(const item of this._items){let itemText=item.title;if(item.uiLocation)
itemText+=' ('+item.uiLocation.linkText(true)+')';text.push(itemText);}
InspectorFrontendHost.copyText(text.join('\n'));}};Sources.CallStackSidebarPane._debuggerCallFrameSymbol=Symbol('debuggerCallFrame');Sources.CallStackSidebarPane._elementSymbol=Symbol('element');Sources.CallStackSidebarPane._defaultMaxAsyncStackChainDepth=32;Sources.CallStackSidebarPane.ActionDelegate=class{handleAction(context,actionId){const callStackSidebarPane=self.runtime.sharedInstance(Sources.CallStackSidebarPane);switch(actionId){case'debugger.next-call-frame':callStackSidebarPane._selectNextCallFrameOnStack();return true;case'debugger.previous-call-frame':callStackSidebarPane._selectPreviousCallFrameOnStack();return true;}
return false;}};Sources.CallStackSidebarPane.Item=class{static createForDebuggerCallFrame(frame,locationPool,updateDelegate){const item=new Sources.CallStackSidebarPane.Item(UI.beautifyFunctionName(frame.functionName),updateDelegate);Bindings.debuggerWorkspaceBinding.createCallFrameLiveLocation(frame.location(),item._update.bind(item),locationPool);return item;}
static createItemsForAsyncStack(title,debuggerModel,frames,locationPool,updateDelegate){const whiteboxedItemsSymbol=Symbol('whiteboxedItems');const asyncHeaderItem=new Sources.CallStackSidebarPane.Item(title,updateDelegate);asyncHeaderItem[whiteboxedItemsSymbol]=new Set();asyncHeaderItem.isAsyncHeader=true;const asyncFrameItems=frames.map(frame=>{const item=new Sources.CallStackSidebarPane.Item(UI.beautifyFunctionName(frame.functionName),update);const rawLocation=debuggerModel?debuggerModel.createRawLocationByScriptId(frame.scriptId,frame.lineNumber,frame.columnNumber):null;if(!rawLocation){item.linkText=(frame.url||'<unknown>')+':'+(frame.lineNumber+1);item.updateDelegate(item);}else{Bindings.debuggerWorkspaceBinding.createCallFrameLiveLocation(rawLocation,item._update.bind(item),locationPool);}
return item;});updateDelegate(asyncHeaderItem);return[asyncHeaderItem,...asyncFrameItems];function update(item){updateDelegate(item);let shouldUpdate=false;const items=asyncHeaderItem[whiteboxedItemsSymbol];if(item.isBlackboxed){items.delete(item);shouldUpdate=items.size===0;}else{shouldUpdate=items.size===0;items.add(item);}
asyncHeaderItem.isBlackboxed=asyncHeaderItem[whiteboxedItemsSymbol].size===0;if(shouldUpdate)
updateDelegate(asyncHeaderItem);}}
constructor(title,updateDelegate){this.isBlackboxed=false;this.title=title;this.linkText='';this.uiLocation=null;this.isAsyncHeader=false;this.updateDelegate=updateDelegate;}
_update(liveLocation){const uiLocation=liveLocation.uiLocation();this.isBlackboxed=uiLocation?Bindings.blackboxManager.isBlackboxedUISourceCode(uiLocation.uiSourceCode):false;this.linkText=uiLocation?uiLocation.linkText():'';this.uiLocation=uiLocation;this.updateDelegate(this);}};;Sources.DebuggerPausedMessage=class{constructor(){this._element=createElementWithClass('div','paused-message flex-none');const root=UI.createShadowRootWithCoreStyles(this._element,'sources/debuggerPausedMessage.css');this._contentElement=root.createChild('div');}
element(){return this._element;}
static _descriptionWithoutStack(description){const firstCallFrame=/^\s+at\s/m.exec(description);return firstCallFrame?description.substring(0,firstCallFrame.index-1):description.substring(0,description.lastIndexOf('\n'));}
static async _createDOMBreakpointHitMessage(details){const messageWrapper=createElement('span');const domDebuggerModel=details.debuggerModel.target().model(SDK.DOMDebuggerModel);if(!details.auxData||!domDebuggerModel)
return messageWrapper;const data=domDebuggerModel.resolveDOMBreakpointData((details.auxData));if(!data)
return messageWrapper;const mainElement=messageWrapper.createChild('div','status-main');mainElement.appendChild(UI.Icon.create('smallicon-info','status-icon'));mainElement.appendChild(createTextNode(String.sprintf('Paused on %s',Sources.DebuggerPausedMessage.BreakpointTypeNouns.get(data.type))));const subElement=messageWrapper.createChild('div','status-sub monospace');const linkifiedNode=await Common.Linkifier.linkify(data.node);subElement.appendChild(linkifiedNode);if(data.targetNode){const targetNodeLink=await Common.Linkifier.linkify(data.targetNode);let message;if(data.insertion)
message=data.targetNode===data.node?'Child %s added':'Descendant %s added';else
message='Descendant %s removed';subElement.appendChild(createElement('br'));subElement.appendChild(UI.formatLocalized(message,[targetNodeLink]));}
return messageWrapper;}
async render(details,debuggerWorkspaceBinding,breakpointManager){this._contentElement.removeChildren();this._contentElement.hidden=!details;if(!details)
return;const status=this._contentElement.createChild('div','paused-status');const errorLike=details.reason===SDK.DebuggerModel.BreakReason.Exception||details.reason===SDK.DebuggerModel.BreakReason.PromiseRejection||details.reason===SDK.DebuggerModel.BreakReason.Assert||details.reason===SDK.DebuggerModel.BreakReason.OOM;let messageWrapper;if(details.reason===SDK.DebuggerModel.BreakReason.DOM){messageWrapper=await Sources.DebuggerPausedMessage._createDOMBreakpointHitMessage(details);}else if(details.reason===SDK.DebuggerModel.BreakReason.EventListener){let eventNameForUI='';if(details.auxData){eventNameForUI=SDK.domDebuggerManager.resolveEventListenerBreakpointTitle((details.auxData));}
messageWrapper=buildWrapper(Common.UIString('Paused on event listener'),eventNameForUI);}else if(details.reason===SDK.DebuggerModel.BreakReason.XHR){messageWrapper=buildWrapper(Common.UIString('Paused on XHR or fetch'),details.auxData['url']||'');}else if(details.reason===SDK.DebuggerModel.BreakReason.Exception){const description=details.auxData['description']||details.auxData['value']||'';const descriptionWithoutStack=Sources.DebuggerPausedMessage._descriptionWithoutStack(description);messageWrapper=buildWrapper(Common.UIString('Paused on exception'),descriptionWithoutStack,description);}else if(details.reason===SDK.DebuggerModel.BreakReason.PromiseRejection){const description=details.auxData['description']||details.auxData['value']||'';const descriptionWithoutStack=Sources.DebuggerPausedMessage._descriptionWithoutStack(description);messageWrapper=buildWrapper(Common.UIString('Paused on promise rejection'),descriptionWithoutStack,description);}else if(details.reason===SDK.DebuggerModel.BreakReason.Assert){messageWrapper=buildWrapper(Common.UIString('Paused on assertion'));}else if(details.reason===SDK.DebuggerModel.BreakReason.DebugCommand){messageWrapper=buildWrapper(Common.UIString('Paused on debugged function'));}else if(details.reason===SDK.DebuggerModel.BreakReason.OOM){messageWrapper=buildWrapper(Common.UIString('Paused before potential out-of-memory crash'));}else if(details.callFrames.length){const uiLocation=debuggerWorkspaceBinding.rawLocationToUILocation(details.callFrames[0].location());const breakpoint=uiLocation?breakpointManager.findBreakpoint(uiLocation):null;const defaultText=breakpoint?Common.UIString('Paused on breakpoint'):Common.UIString('Debugger paused');messageWrapper=buildWrapper(defaultText);}else{console.warn('ScriptsPanel paused, but callFrames.length is zero.');}
status.classList.toggle('error-reason',errorLike);if(messageWrapper)
status.appendChild(messageWrapper);function buildWrapper(mainText,subText,title){const messageWrapper=createElement('span');const mainElement=messageWrapper.createChild('div','status-main');const icon=UI.Icon.create(errorLike?'smallicon-error':'smallicon-info','status-icon');mainElement.appendChild(icon);mainElement.appendChild(createTextNode(mainText));if(subText){const subElement=messageWrapper.createChild('div','status-sub monospace');subElement.textContent=subText;subElement.title=title||subText;}
return messageWrapper;}}};Sources.DebuggerPausedMessage.BreakpointTypeNouns=new Map([[SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified,Common.UIString('subtree modifications')],[SDK.DOMDebuggerModel.DOMBreakpoint.Type.AttributeModified,Common.UIString('attribute modifications')],[SDK.DOMDebuggerModel.DOMBreakpoint.Type.NodeRemoved,Common.UIString('node removal')],]);;Sources.HistoryEntry=function(){};Sources.HistoryEntry.prototype={valid(){},reveal(){}};Sources.SimpleHistoryManager=class{constructor(historyDepth){this._entries=[];this._activeEntryIndex=-1;this._coalescingReadonly=0;this._historyDepth=historyDepth;}
readOnlyLock(){++this._coalescingReadonly;}
releaseReadOnlyLock(){--this._coalescingReadonly;}
readOnly(){return!!this._coalescingReadonly;}
filterOut(filterOutCallback){if(this.readOnly())
return;const filteredEntries=[];let removedBeforeActiveEntry=0;for(let i=0;i<this._entries.length;++i){if(!filterOutCallback(this._entries[i]))
filteredEntries.push(this._entries[i]);else if(i<=this._activeEntryIndex)
++removedBeforeActiveEntry;}
this._entries=filteredEntries;this._activeEntryIndex=Math.max(0,this._activeEntryIndex-removedBeforeActiveEntry);}
empty(){return!this._entries.length;}
active(){return this.empty()?null:this._entries[this._activeEntryIndex];}
push(entry){if(this.readOnly())
return;if(!this.empty())
this._entries.splice(this._activeEntryIndex+1);this._entries.push(entry);if(this._entries.length>this._historyDepth)
this._entries.shift();this._activeEntryIndex=this._entries.length-1;}
rollback(){if(this.empty())
return false;let revealIndex=this._activeEntryIndex-1;while(revealIndex>=0&&!this._entries[revealIndex].valid())
--revealIndex;if(revealIndex<0)
return false;this.readOnlyLock();this._entries[revealIndex].reveal();this.releaseReadOnlyLock();this._activeEntryIndex=revealIndex;return true;}
rollover(){let revealIndex=this._activeEntryIndex+1;while(revealIndex<this._entries.length&&!this._entries[revealIndex].valid())
++revealIndex;if(revealIndex>=this._entries.length)
return false;this.readOnlyLock();this._entries[revealIndex].reveal();this.releaseReadOnlyLock();this._activeEntryIndex=revealIndex;return true;}};;Sources.EditingLocationHistoryManager=class{constructor(sourcesView,currentSourceFrameCallback){this._sourcesView=sourcesView;this._historyManager=new Sources.SimpleHistoryManager(Sources.EditingLocationHistoryManager.HistoryDepth);this._currentSourceFrameCallback=currentSourceFrameCallback;}
trackSourceFrameCursorJumps(sourceFrame){sourceFrame.textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.JumpHappened,this._onJumpHappened.bind(this));}
_onJumpHappened(event){if(event.data.from)
this._updateActiveState(event.data.from);if(event.data.to)
this._pushActiveState(event.data.to);}
rollback(){this._historyManager.rollback();}
rollover(){this._historyManager.rollover();}
updateCurrentState(){const sourceFrame=this._currentSourceFrameCallback();if(!sourceFrame)
return;this._updateActiveState(sourceFrame.textEditor.selection());}
pushNewState(){const sourceFrame=this._currentSourceFrameCallback();if(!sourceFrame)
return;this._pushActiveState(sourceFrame.textEditor.selection());}
_updateActiveState(selection){const active=this._historyManager.active();if(!active)
return;const sourceFrame=this._currentSourceFrameCallback();if(!sourceFrame)
return;const entry=new Sources.EditingLocationHistoryEntry(this._sourcesView,this,sourceFrame,selection);active.merge(entry);}
_pushActiveState(selection){const sourceFrame=this._currentSourceFrameCallback();if(!sourceFrame)
return;const entry=new Sources.EditingLocationHistoryEntry(this._sourcesView,this,sourceFrame,selection);this._historyManager.push(entry);}
removeHistoryForSourceCode(uiSourceCode){function filterOut(entry){return entry._projectId===uiSourceCode.project().id()&&entry._url===uiSourceCode.url();}
this._historyManager.filterOut(filterOut);}};Sources.EditingLocationHistoryManager.HistoryDepth=20;Sources.EditingLocationHistoryEntry=class{constructor(sourcesView,editingLocationManager,sourceFrame,selection){this._sourcesView=sourcesView;this._editingLocationManager=editingLocationManager;const uiSourceCode=sourceFrame.uiSourceCode();this._projectId=uiSourceCode.project().id();this._url=uiSourceCode.url();const position=this._positionFromSelection(selection);this._positionHandle=sourceFrame.textEditor.textEditorPositionHandle(position.lineNumber,position.columnNumber);}
merge(entry){if(this._projectId!==entry._projectId||this._url!==entry._url)
return;this._positionHandle=entry._positionHandle;}
_positionFromSelection(selection){return{lineNumber:selection.endLine,columnNumber:selection.endColumn};}
valid(){const position=this._positionHandle.resolve();const uiSourceCode=Workspace.workspace.uiSourceCode(this._projectId,this._url);return!!(position&&uiSourceCode);}
reveal(){const position=this._positionHandle.resolve();const uiSourceCode=Workspace.workspace.uiSourceCode(this._projectId,this._url);if(!position||!uiSourceCode)
return;this._editingLocationManager.updateCurrentState();this._sourcesView.showSourceLocation(uiSourceCode,position.lineNumber,position.columnNumber);}};;Sources.FilePathScoreFunction=class{constructor(query){this._query=query;this._queryUpperCase=query.toUpperCase();this._score=new Int32Array(20*100);this._sequence=new Int32Array(20*100);this._dataUpperCase='';this._fileNameIndex=0;}
score(data,matchIndexes){if(!data||!this._query)
return 0;const n=this._query.length;const m=data.length;if(!this._score||this._score.length<n*m){this._score=new Int32Array(n*m*2);this._sequence=new Int32Array(n*m*2);}
const score=this._score;const sequence=(this._sequence);this._dataUpperCase=data.toUpperCase();this._fileNameIndex=data.lastIndexOf('/');for(let i=0;i<n;++i){for(let j=0;j<m;++j){const skipCharScore=j===0?0:score[i*m+j-1];const prevCharScore=i===0||j===0?0:score[(i-1)*m+j-1];const consecutiveMatch=i===0||j===0?0:sequence[(i-1)*m+j-1];const pickCharScore=this._match(this._query,data,i,j,consecutiveMatch);if(pickCharScore&&prevCharScore+pickCharScore>=skipCharScore){sequence[i*m+j]=consecutiveMatch+1;score[i*m+j]=(prevCharScore+pickCharScore);}else{sequence[i*m+j]=0;score[i*m+j]=skipCharScore;}}}
if(matchIndexes)
this._restoreMatchIndexes(sequence,n,m,matchIndexes);const maxDataLength=256;return score[n*m-1]*maxDataLength+(maxDataLength-data.length);}
_testWordStart(data,j){if(j===0)
return true;const prevChar=data.charAt(j-1);return prevChar==='_'||prevChar==='-'||prevChar==='/'||(data[j-1]!==this._dataUpperCase[j-1]&&data[j]===this._dataUpperCase[j]);}
_restoreMatchIndexes(sequence,n,m,out){let i=n-1,j=m-1;while(i>=0&&j>=0){switch(sequence[i*m+j]){case 0:--j;break;default:out.push(j);--i;--j;break;}}
out.reverse();}
_singleCharScore(query,data,i,j){const isWordStart=this._testWordStart(data,j);const isFileName=j>this._fileNameIndex;const isPathTokenStart=j===0||data[j-1]==='/';const isCapsMatch=query[i]===data[j]&&query[i]===this._queryUpperCase[i];let score=10;if(isPathTokenStart)
score+=4;if(isWordStart)
score+=2;if(isCapsMatch)
score+=6;if(isFileName)
score+=4;if(j===this._fileNameIndex+1&&i===0)
score+=5;if(isFileName&&isWordStart)
score+=3;return score;}
_sequenceCharScore(query,data,i,j,sequenceLength){const isFileName=j>this._fileNameIndex;const isPathTokenStart=j===0||data[j-1]==='/';let score=10;if(isFileName)
score+=4;if(isPathTokenStart)
score+=5;score+=sequenceLength*4;return score;}
_match(query,data,i,j,consecutiveMatch){if(this._queryUpperCase[i]!==this._dataUpperCase[j])
return 0;if(!consecutiveMatch)
return this._singleCharScore(query,data,i,j);else
return this._sequenceCharScore(query,data,i,j-consecutiveMatch,consecutiveMatch);}};;Sources.FilteredUISourceCodeListProvider=class extends QuickOpen.FilteredListWidget.Provider{constructor(){super();this._queryLineNumberAndColumnNumber='';this._defaultScores=null;this._scorer=new Sources.FilePathScoreFunction('');}
_projectRemoved(event){const project=(event.data);this._populate(project);this.refresh();}
_populate(skipProject){this._uiSourceCodes=[];const projects=Workspace.workspace.projects().filter(this.filterProject.bind(this));for(let i=0;i<projects.length;++i){if(skipProject&&projects[i]===skipProject)
continue;const uiSourceCodes=projects[i].uiSourceCodes().filter(this._filterUISourceCode.bind(this));this._uiSourceCodes=this._uiSourceCodes.concat(uiSourceCodes);}}
_filterUISourceCode(uiSourceCode){const binding=Persistence.persistence.binding(uiSourceCode);return!binding||binding.fileSystem===uiSourceCode;}
uiSourceCodeSelected(uiSourceCode,lineNumber,columnNumber){}
filterProject(project){return true;}
itemCount(){return this._uiSourceCodes.length;}
itemKeyAt(itemIndex){return this._uiSourceCodes[itemIndex].url();}
setDefaultScores(defaultScores){this._defaultScores=defaultScores;}
itemScoreAt(itemIndex,query){const uiSourceCode=this._uiSourceCodes[itemIndex];const score=this._defaultScores?(this._defaultScores.get(uiSourceCode)||0):0;if(!query||query.length<2)
return score;if(this._query!==query){this._query=query;this._scorer=new Sources.FilePathScoreFunction(query);}
let multiplier=10;if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem&&!Persistence.persistence.binding(uiSourceCode))
multiplier=5;const fullDisplayName=uiSourceCode.fullDisplayName();return score+multiplier*this._scorer.score(fullDisplayName,null);}
renderItem(itemIndex,query,titleElement,subtitleElement){query=this.rewriteQuery(query);const uiSourceCode=this._uiSourceCodes[itemIndex];const fullDisplayName=uiSourceCode.fullDisplayName();const indexes=[];new Sources.FilePathScoreFunction(query).score(fullDisplayName,indexes);const fileNameIndex=fullDisplayName.lastIndexOf('/');titleElement.classList.add('monospace');subtitleElement.classList.add('monospace');titleElement.textContent=uiSourceCode.displayName()+(this._queryLineNumberAndColumnNumber||'');this._renderSubtitleElement(subtitleElement,fullDisplayName);subtitleElement.title=fullDisplayName;const ranges=[];for(let i=0;i<indexes.length;++i)
ranges.push({offset:indexes[i],length:1});if(indexes[0]>fileNameIndex){for(let i=0;i<ranges.length;++i)
ranges[i].offset-=fileNameIndex+1;UI.highlightRangesWithStyleClass(titleElement,ranges,'highlight');}else{UI.highlightRangesWithStyleClass(subtitleElement,ranges,'highlight');}}
_renderSubtitleElement(element,text){element.removeChildren();let splitPosition=text.lastIndexOf('/');if(text.length>55)
splitPosition=text.length-55;const first=element.createChild('div','first-part');first.textContent=text.substring(0,splitPosition);const second=element.createChild('div','second-part');second.textContent=text.substring(splitPosition);element.title=text;}
selectItem(itemIndex,promptValue){const parsedExpression=promptValue.trim().match(/^([^:]*)(:\d+)?(:\d+)?$/);if(!parsedExpression)
return;let lineNumber;let columnNumber;if(parsedExpression[2])
lineNumber=parseInt(parsedExpression[2].substr(1),10)-1;if(parsedExpression[3])
columnNumber=parseInt(parsedExpression[3].substr(1),10)-1;const uiSourceCode=itemIndex!==null?this._uiSourceCodes[itemIndex]:null;this.uiSourceCodeSelected(uiSourceCode,lineNumber,columnNumber);}
rewriteQuery(query){query=query?query.trim():'';if(!query||query===':')
return'';const lineNumberMatch=query.match(/^([^:]+)((?::[^:]*){0,2})$/);this._queryLineNumberAndColumnNumber=lineNumberMatch?lineNumberMatch[2]:'';return lineNumberMatch?lineNumberMatch[1]:query;}
_uiSourceCodeAdded(event){const uiSourceCode=(event.data);if(!this._filterUISourceCode(uiSourceCode)||!this.filterProject(uiSourceCode.project()))
return;this._uiSourceCodes.push(uiSourceCode);this.refresh();}
notFoundText(){return Common.UIString('No files found');}
attach(){Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._uiSourceCodeAdded,this);Workspace.workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,this._projectRemoved,this);this._populate();}
detach(){Workspace.workspace.removeEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._uiSourceCodeAdded,this);Workspace.workspace.removeEventListener(Workspace.Workspace.Events.ProjectRemoved,this._projectRemoved,this);this._queryLineNumberAndColumnNumber='';this._defaultScores=null;}};;Sources.GoToLineQuickOpen=class extends QuickOpen.FilteredListWidget.Provider{selectItem(itemIndex,promptValue){const uiSourceCode=this._currentUISourceCode();if(!uiSourceCode)
return;const position=this._parsePosition(promptValue);if(!position)
return;Common.Revealer.reveal(uiSourceCode.uiLocation(position.line-1,position.column-1));}
notFoundText(query){if(!this._currentUISourceCode())
return Common.UIString('No file selected.');const position=this._parsePosition(query);if(!position)
return Common.UIString('Type a number to go to that line.');if(position.column&&position.column>1)
return ls`Go to line ${position.line} and column ${position.column}.`;return ls`Go to line ${position.line}.`;}
_parsePosition(query){const parts=query.match(/([0-9]+)(\:[0-9]*)?/);if(!parts||!parts[0]||parts[0].length!==query.length)
return null;const line=parseInt(parts[1],10);let column;if(parts[2])
column=parseInt(parts[2].substring(1),10);return{line:Math.max(line|0,1),column:Math.max(column|0,1)};}
_currentUISourceCode(){const sourcesView=UI.context.flavor(Sources.SourcesView);if(!sourcesView)
return null;return sourcesView.currentUISourceCode();}};;Sources.SourceMapNamesResolver={};Sources.SourceMapNamesResolver._cachedMapSymbol=Symbol('cache');Sources.SourceMapNamesResolver._cachedIdentifiersSymbol=Symbol('cachedIdentifiers');Sources.SourceMapNamesResolver.Identifier=class{constructor(name,lineNumber,columnNumber){this.name=name;this.lineNumber=lineNumber;this.columnNumber=columnNumber;}};Sources.SourceMapNamesResolver._scopeIdentifiers=function(scope){const startLocation=scope.startLocation();const endLocation=scope.endLocation();if(scope.type()===Protocol.Debugger.ScopeType.Global||!startLocation||!endLocation||!startLocation.script()||!startLocation.script().sourceMapURL||(startLocation.script()!==endLocation.script()))
return Promise.resolve(([]));const script=startLocation.script();return script.requestContent().then(onContent);function onContent(content){if(!content)
return Promise.resolve(([]));const text=new TextUtils.Text(content);const scopeRange=new TextUtils.TextRange(startLocation.lineNumber,startLocation.columnNumber,endLocation.lineNumber,endLocation.columnNumber);const scopeText=text.extract(scopeRange);const scopeStart=text.toSourceRange(scopeRange).offset;const prefix='function fui';return Formatter.formatterWorkerPool().javaScriptIdentifiers(prefix+scopeText).then(onIdentifiers.bind(null,text,scopeStart,prefix));}
function onIdentifiers(text,scopeStart,prefix,identifiers){const result=[];const cursor=new TextUtils.TextCursor(text.lineEndings());for(let i=0;i<identifiers.length;++i){const id=identifiers[i];if(id.offset<prefix.length)
continue;const start=scopeStart+id.offset-prefix.length;cursor.resetTo(start);result.push(new Sources.SourceMapNamesResolver.Identifier(id.name,cursor.lineNumber(),cursor.columnNumber()));}
return result;}};Sources.SourceMapNamesResolver._resolveScope=function(scope){let identifiersPromise=scope[Sources.SourceMapNamesResolver._cachedIdentifiersSymbol];if(identifiersPromise)
return identifiersPromise;const script=scope.callFrame().script;const sourceMap=Bindings.debuggerWorkspaceBinding.sourceMapForScript(script);if(!sourceMap)
return Promise.resolve(new Map());const textCache=new Map();identifiersPromise=Sources.SourceMapNamesResolver._scopeIdentifiers(scope).then(onIdentifiers);scope[Sources.SourceMapNamesResolver._cachedIdentifiersSymbol]=identifiersPromise;return identifiersPromise;function onIdentifiers(identifiers){const namesMapping=new Map();for(let i=0;i<identifiers.length;++i){const id=identifiers[i];const entry=sourceMap.findEntry(id.lineNumber,id.columnNumber);if(entry&&entry.name)
namesMapping.set(id.name,entry.name);}
const promises=[];for(let i=0;i<identifiers.length;++i){const id=identifiers[i];if(namesMapping.has(id.name))
continue;const promise=resolveSourceName(id).then(onSourceNameResolved.bind(null,namesMapping,id));promises.push(promise);}
return Promise.all(promises).then(()=>Sources.SourceMapNamesResolver._scopeResolvedForTest()).then(()=>namesMapping);}
function onSourceNameResolved(namesMapping,id,sourceName){if(!sourceName)
return;namesMapping.set(id.name,sourceName);}
function resolveSourceName(id){const startEntry=sourceMap.findEntry(id.lineNumber,id.columnNumber);const endEntry=sourceMap.findEntry(id.lineNumber,id.columnNumber+id.name.length);if(!startEntry||!endEntry||!startEntry.sourceURL||startEntry.sourceURL!==endEntry.sourceURL||!startEntry.sourceLineNumber||!startEntry.sourceColumnNumber||!endEntry.sourceLineNumber||!endEntry.sourceColumnNumber)
return Promise.resolve((null));const sourceTextRange=new TextUtils.TextRange(startEntry.sourceLineNumber,startEntry.sourceColumnNumber,endEntry.sourceLineNumber,endEntry.sourceColumnNumber);const uiSourceCode=Bindings.debuggerWorkspaceBinding.uiSourceCodeForSourceMapSourceURL(script.debuggerModel,startEntry.sourceURL,script.isContentScript());if(!uiSourceCode)
return Promise.resolve((null));return uiSourceCode.requestContent().then(onSourceContent.bind(null,sourceTextRange));}
function onSourceContent(sourceTextRange,content){if(!content)
return null;let text=textCache.get(content);if(!text){text=new TextUtils.Text(content);textCache.set(content,text);}
const originalIdentifier=text.extract(sourceTextRange).trim();return/[a-zA-Z0-9_$]+/.test(originalIdentifier)?originalIdentifier:null;}};Sources.SourceMapNamesResolver._scopeResolvedForTest=function(){};Sources.SourceMapNamesResolver._allVariablesInCallFrame=function(callFrame){const cached=callFrame[Sources.SourceMapNamesResolver._cachedMapSymbol];if(cached)
return Promise.resolve(cached);const promises=[];const scopeChain=callFrame.scopeChain();for(let i=0;i<scopeChain.length;++i)
promises.push(Sources.SourceMapNamesResolver._resolveScope(scopeChain[i]));return Promise.all(promises).then(mergeVariables);function mergeVariables(nameMappings){const reverseMapping=new Map();for(const map of nameMappings){for(const compiledName of map.keys()){const originalName=map.get(compiledName);if(!reverseMapping.has(originalName))
reverseMapping.set(originalName,compiledName);}}
callFrame[Sources.SourceMapNamesResolver._cachedMapSymbol]=reverseMapping;return reverseMapping;}};Sources.SourceMapNamesResolver.resolveExpression=function(callFrame,originalText,uiSourceCode,lineNumber,startColumnNumber,endColumnNumber){if(!uiSourceCode.contentType().isFromSourceMap())
return Promise.resolve('');return Sources.SourceMapNamesResolver._allVariablesInCallFrame(callFrame).then(reverseMapping=>findCompiledName(callFrame.debuggerModel,reverseMapping));function findCompiledName(debuggerModel,reverseMapping){if(reverseMapping.has(originalText))
return Promise.resolve(reverseMapping.get(originalText)||'');return Sources.SourceMapNamesResolver._resolveExpression(debuggerModel,uiSourceCode,lineNumber,startColumnNumber,endColumnNumber);}};Sources.SourceMapNamesResolver._resolveExpression=function(debuggerModel,uiSourceCode,lineNumber,startColumnNumber,endColumnNumber){const rawLocations=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode,lineNumber,startColumnNumber);const rawLocation=rawLocations.find(location=>location.debuggerModel===debuggerModel);if(!rawLocation)
return Promise.resolve('');const script=rawLocation.script();if(!script)
return Promise.resolve('');const sourceMap=Bindings.debuggerWorkspaceBinding.sourceMapForScript(script);if(!sourceMap)
return Promise.resolve('');return script.requestContent().then(onContent);function onContent(content){if(!content)
return Promise.resolve('');const text=new TextUtils.Text(content);const textRange=sourceMap.reverseMapTextRange(uiSourceCode.url(),new TextUtils.TextRange(lineNumber,startColumnNumber,lineNumber,endColumnNumber));const originalText=text.extract(textRange);if(!originalText)
return Promise.resolve('');return Formatter.formatterWorkerPool().evaluatableJavaScriptSubstring(originalText);}};Sources.SourceMapNamesResolver.resolveThisObject=function(callFrame){if(!callFrame)
return Promise.resolve((null));if(!callFrame.scopeChain().length)
return Promise.resolve(callFrame.thisObject());return Sources.SourceMapNamesResolver._resolveScope(callFrame.scopeChain()[0]).then(onScopeResolved);function onScopeResolved(namesMapping){const thisMappings=namesMapping.inverse().get('this');if(!thisMappings||thisMappings.size!==1)
return Promise.resolve(callFrame.thisObject());const thisMapping=thisMappings.valuesArray()[0];return callFrame.evaluate({expression:thisMapping,objectGroup:'backtrace',includeCommandLineAPI:false,silent:true,returnByValue:false,generatePreview:true}).then(onEvaluated);}
function onEvaluated(result){return!result.exceptionDetails&&result.object?result.object:callFrame.thisObject();}};Sources.SourceMapNamesResolver.resolveScopeInObject=function(scope){const startLocation=scope.startLocation();const endLocation=scope.endLocation();if(scope.type()===Protocol.Debugger.ScopeType.Global||!startLocation||!endLocation||!startLocation.script()||!startLocation.script().sourceMapURL||startLocation.script()!==endLocation.script())
return scope.object();return new Sources.SourceMapNamesResolver.RemoteObject(scope);};Sources.SourceMapNamesResolver.RemoteObject=class extends SDK.RemoteObject{constructor(scope){super();this._scope=scope;this._object=scope.object();}
customPreview(){return this._object.customPreview();}
get objectId(){return this._object.objectId;}
get type(){return this._object.type;}
get subtype(){return this._object.subtype;}
get value(){return this._object.value;}
get description(){return this._object.description;}
get hasChildren(){return this._object.hasChildren;}
get preview(){return this._object.preview;}
arrayLength(){return this._object.arrayLength();}
getOwnProperties(generatePreview){return this._object.getOwnProperties(generatePreview);}
async getAllProperties(accessorPropertiesOnly,generatePreview){const allProperties=await this._object.getAllProperties(accessorPropertiesOnly,generatePreview);const namesMapping=await Sources.SourceMapNamesResolver._resolveScope(this._scope);const properties=allProperties.properties;const internalProperties=allProperties.internalProperties;const newProperties=[];if(properties){for(let i=0;i<properties.length;++i){const property=properties[i];const name=namesMapping.get(property.name)||properties[i].name;newProperties.push(new SDK.RemoteObjectProperty(name,property.value,property.enumerable,property.writable,property.isOwn,property.wasThrown,property.symbol,property.synthetic));}}
return{properties:newProperties,internalProperties:internalProperties};}
async setPropertyValue(argumentName,value){const namesMapping=await Sources.SourceMapNamesResolver._resolveScope(this._scope);let name;if(typeof argumentName==='string')
name=argumentName;else
name=(argumentName.value);let actualName=name;for(const compiledName of namesMapping.keys()){if(namesMapping.get(compiledName)===name){actualName=compiledName;break;}}
return this._object.setPropertyValue(actualName,value);}
async deleteProperty(name){return this._object.deleteProperty(name);}
callFunction(functionDeclaration,args){return this._object.callFunction(functionDeclaration,args);}
callFunctionJSON(functionDeclaration,args){return this._object.callFunctionJSON(functionDeclaration,args);}
release(){this._object.release();}
debuggerModel(){return this._object.debuggerModel();}
runtimeModel(){return this._object.runtimeModel();}
isNode(){return this._object.isNode();}};;Sources.JavaScriptBreakpointsSidebarPane=class extends UI.ThrottledWidget{constructor(){super(true);this.registerRequiredCSS('sources/javaScriptBreakpointsSidebarPane.css');this._breakpointManager=Bindings.breakpointManager;this._breakpointManager.addEventListener(Bindings.BreakpointManager.Events.BreakpointAdded,this.update,this);this._breakpointManager.addEventListener(Bindings.BreakpointManager.Events.BreakpointRemoved,this.update,this);Common.moduleSetting('breakpointsActive').addChangeListener(this.update,this);this._listElement=null;this.update();}
doUpdate(){const breakpointLocations=this._breakpointManager.allBreakpointLocations().filter(breakpointLocation=>breakpointLocation.uiLocation.uiSourceCode.project().type()!==Workspace.projectTypes.Debugger);if(!breakpointLocations.length){this._listElement=null;this.contentElement.removeChildren();const emptyElement=this.contentElement.createChild('div','gray-info-message');emptyElement.textContent=Common.UIString('No breakpoints');this.contentElement.appendChild(emptyElement);this._didUpdateForTest();return Promise.resolve();}
if(!this._listElement){this.contentElement.removeChildren();this._listElement=this.contentElement.createChild('div');this.contentElement.appendChild(this._listElement);}
breakpointLocations.sort((item1,item2)=>item1.uiLocation.compareTo(item2.uiLocation));const breakpointEntriesForLine=new Multimap();const locationForEntry=new Multimap();for(const breakpointLocation of breakpointLocations){const uiLocation=breakpointLocation.uiLocation;const entryDescriptor=`${uiLocation.uiSourceCode.url()}:${uiLocation.lineNumber}:${uiLocation.columnNumber}`;locationForEntry.set(entryDescriptor,breakpointLocation);const lineDescriptor=`${uiLocation.uiSourceCode.url()}:${uiLocation.lineNumber}`;breakpointEntriesForLine.set(lineDescriptor,entryDescriptor);}
const details=UI.context.flavor(SDK.DebuggerPausedDetails);const selectedUILocation=details&&details.callFrames.length?Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(details.callFrames[0].location()):null;let shouldShowView=false;let entry=this._listElement.firstChild;const promises=[];for(const descriptor of locationForEntry.keysArray()){if(!entry){entry=this._listElement.createChild('div','breakpoint-entry');entry.addEventListener('contextmenu',this._breakpointContextMenu.bind(this),true);entry.addEventListener('click',this._revealLocation.bind(this),false);const checkboxLabel=UI.CheckboxLabel.create('');checkboxLabel.addEventListener('click',this._breakpointCheckboxClicked.bind(this),false);entry.appendChild(checkboxLabel);entry[Sources.JavaScriptBreakpointsSidebarPane._checkboxLabelSymbol]=checkboxLabel;const snippetElement=entry.createChild('div','source-text monospace');entry[Sources.JavaScriptBreakpointsSidebarPane._snippetElementSymbol]=snippetElement;}
const locations=Array.from(locationForEntry.get(descriptor));const uiLocation=locations[0].uiLocation;const isSelected=!!selectedUILocation&&locations.some(location=>location.uiLocation.id()===selectedUILocation.id());const hasEnabled=locations.some(location=>location.breakpoint.enabled());const hasDisabled=locations.some(location=>!location.breakpoint.enabled());const showCoumn=breakpointEntriesForLine.get(`${uiLocation.uiSourceCode.url()}:${uiLocation.lineNumber}`).size>1;promises.push(this._resetEntry((entry),uiLocation,isSelected,hasEnabled,hasDisabled,showCoumn));entry[Sources.JavaScriptBreakpointsSidebarPane._breakpointLocationsSymbol]=locations;if(isSelected)
shouldShowView=true;entry=entry.nextSibling;}
while(entry){const next=entry.nextSibling;entry.remove();entry=next;}
if(shouldShowView)
UI.viewManager.showView('sources.jsBreakpoints');this._listElement.classList.toggle('breakpoints-list-deactivated',!Common.moduleSetting('breakpointsActive').get());return Promise.all(promises).then(()=>this._didUpdateForTest());}
async _resetEntry(element,uiLocation,isSelected,hasEnabled,hasDisabled,showColumn){element[Sources.JavaScriptBreakpointsSidebarPane._locationSymbol]=uiLocation;element.classList.toggle('breakpoint-hit',isSelected);const checkboxLabel=element[Sources.JavaScriptBreakpointsSidebarPane._checkboxLabelSymbol];checkboxLabel.textElement.textContent=uiLocation.linkText()+(showColumn?':'+(uiLocation.columnNumber+1):'');checkboxLabel.checkboxElement.checked=hasEnabled;checkboxLabel.checkboxElement.indeterminate=hasEnabled&&hasDisabled;const snippetElement=element[Sources.JavaScriptBreakpointsSidebarPane._snippetElementSymbol];const content=await uiLocation.uiSourceCode.requestContent();const lineNumber=uiLocation.lineNumber;const text=new TextUtils.Text(content||'');if(lineNumber<text.lineCount()){const lineText=text.lineAt(lineNumber);const maxSnippetLength=200;snippetElement.textContent=lineText.substring(showColumn?uiLocation.columnNumber:0).trimEnd(maxSnippetLength);}}
_breakpointLocations(event){const node=event.target.enclosingNodeOrSelfWithClass('breakpoint-entry');if(!node)
return[];return node[Sources.JavaScriptBreakpointsSidebarPane._breakpointLocationsSymbol]||[];}
_breakpointCheckboxClicked(event){const breakpoints=this._breakpointLocations(event).map(breakpointLocation=>breakpointLocation.breakpoint);const newState=event.target.checkboxElement.checked;for(const breakpoint of breakpoints)
breakpoint.setEnabled(newState);event.consume();}
_revealLocation(event){const uiLocations=this._breakpointLocations(event).map(breakpointLocation=>breakpointLocation.uiLocation);let uiLocation=null;for(const uiLocationCandidate of uiLocations){if(!uiLocation||uiLocationCandidate.columnNumber<uiLocation.columnNumber)
uiLocation=uiLocationCandidate;}
if(uiLocation)
Common.Revealer.reveal(uiLocation);}
_breakpointContextMenu(event){const breakpoints=this._breakpointLocations(event).map(breakpointLocation=>breakpointLocation.breakpoint);const contextMenu=new UI.ContextMenu(event);const removeEntryTitle=breakpoints.length>1?Common.UIString('Remove all breakpoints in line'):Common.UIString('Remove breakpoint');contextMenu.defaultSection().appendItem(removeEntryTitle,()=>breakpoints.map(breakpoint=>breakpoint.remove(false)));const breakpointActive=Common.moduleSetting('breakpointsActive').get();const breakpointActiveTitle=breakpointActive?Common.UIString('Deactivate breakpoints'):Common.UIString('Activate breakpoints');contextMenu.defaultSection().appendItem(breakpointActiveTitle,()=>Common.moduleSetting('breakpointsActive').set(!breakpointActive));if(breakpoints.some(breakpoint=>!breakpoint.enabled())){const enableTitle=Common.UIString('Enable all breakpoints');contextMenu.defaultSection().appendItem(enableTitle,this._toggleAllBreakpoints.bind(this,true));}
if(breakpoints.some(breakpoint=>breakpoint.enabled())){const disableTitle=Common.UIString('Disable all breakpoints');contextMenu.defaultSection().appendItem(disableTitle,this._toggleAllBreakpoints.bind(this,false));}
const removeAllTitle=Common.UIString('Remove all breakpoints');contextMenu.defaultSection().appendItem(removeAllTitle,this._removeAllBreakpoints.bind(this));const removeOtherTitle=Common.UIString('Remove other breakpoints');contextMenu.defaultSection().appendItem(removeOtherTitle,this._removeOtherBreakpoints.bind(this,new Set(breakpoints)));contextMenu.show();}
_toggleAllBreakpoints(toggleState){for(const breakpointLocation of this._breakpointManager.allBreakpointLocations())
breakpointLocation.breakpoint.setEnabled(toggleState);}
_removeAllBreakpoints(){for(const breakpointLocation of this._breakpointManager.allBreakpointLocations())
breakpointLocation.breakpoint.remove(false);}
_removeOtherBreakpoints(selectedBreakpoints){for(const breakpointLocation of this._breakpointManager.allBreakpointLocations()){if(!selectedBreakpoints.has(breakpointLocation.breakpoint))
breakpointLocation.breakpoint.remove(false);}}
flavorChanged(object){this.update();}
_didUpdateForTest(){}};Sources.JavaScriptBreakpointsSidebarPane._locationSymbol=Symbol('location');Sources.JavaScriptBreakpointsSidebarPane._checkboxLabelSymbol=Symbol('checkbox-label');Sources.JavaScriptBreakpointsSidebarPane._snippetElementSymbol=Symbol('snippet-element');Sources.JavaScriptBreakpointsSidebarPane._breakpointLocationsSymbol=Symbol('locations');;Sources.UISourceCodeFrame=class extends SourceFrame.SourceFrame{constructor(uiSourceCode){super(workingCopy);this._uiSourceCode=uiSourceCode;if(Runtime.experiments.isEnabled('sourceDiff'))
this._diff=new SourceFrame.SourceCodeDiff(this.textEditor);this._muteSourceCodeEvents=false;this._isSettingContent=false;this._persistenceBinding=Persistence.persistence.binding(uiSourceCode);this._rowMessageBuckets=new Map();this._typeDecorationsPending=new Set();this._uiSourceCodeEventListeners=[];this._messageAndDecorationListeners=[];this._boundOnBindingChanged=this._onBindingChanged.bind(this);this.textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.EditorBlurred,()=>UI.context.setFlavor(Sources.UISourceCodeFrame,null));this.textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.EditorFocused,()=>UI.context.setFlavor(Sources.UISourceCodeFrame,this));Common.settings.moduleSetting('persistenceNetworkOverridesEnabled').addChangeListener(this._onNetworkPersistenceChanged,this);this._errorPopoverHelper=new UI.PopoverHelper(this.element,this._getErrorPopoverContent.bind(this));this._errorPopoverHelper.setHasPadding(true);this._errorPopoverHelper.setTimeout(100,100);this._plugins=[];this._initializeUISourceCode();function workingCopy(){if(uiSourceCode.isDirty())
return(Promise.resolve(uiSourceCode.workingCopy()));return uiSourceCode.requestContent();}}
_installMessageAndDecorationListeners(){if(this._persistenceBinding){const networkSourceCode=this._persistenceBinding.network;const fileSystemSourceCode=this._persistenceBinding.fileSystem;this._messageAndDecorationListeners=[networkSourceCode.addEventListener(Workspace.UISourceCode.Events.MessageAdded,this._onMessageAdded,this),networkSourceCode.addEventListener(Workspace.UISourceCode.Events.MessageRemoved,this._onMessageRemoved,this),networkSourceCode.addEventListener(Workspace.UISourceCode.Events.LineDecorationAdded,this._onLineDecorationAdded,this),networkSourceCode.addEventListener(Workspace.UISourceCode.Events.LineDecorationRemoved,this._onLineDecorationRemoved,this),fileSystemSourceCode.addEventListener(Workspace.UISourceCode.Events.MessageAdded,this._onMessageAdded,this),fileSystemSourceCode.addEventListener(Workspace.UISourceCode.Events.MessageRemoved,this._onMessageRemoved,this),];}else{this._messageAndDecorationListeners=[this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.MessageAdded,this._onMessageAdded,this),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.MessageRemoved,this._onMessageRemoved,this),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.LineDecorationAdded,this._onLineDecorationAdded,this),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.LineDecorationRemoved,this._onLineDecorationRemoved,this)];}}
uiSourceCode(){return this._uiSourceCode;}
setUISourceCode(uiSourceCode){this._unloadUISourceCode();this._uiSourceCode=uiSourceCode;if(uiSourceCode.contentLoaded()){if(uiSourceCode.workingCopy()!==this.textEditor.text())
this._innerSetContent(uiSourceCode.workingCopy());}else{uiSourceCode.requestContent().then(()=>{if(this._uiSourceCode!==uiSourceCode)
return;if(uiSourceCode.workingCopy()!==this.textEditor.text())
this._innerSetContent(uiSourceCode.workingCopy());});}
this._initializeUISourceCode();}
_unloadUISourceCode(){this._disposePlugins();for(const message of this._allMessages())
this._removeMessageFromSource(message);Common.EventTarget.removeEventListeners(this._messageAndDecorationListeners);Common.EventTarget.removeEventListeners(this._uiSourceCodeEventListeners);this._uiSourceCode.removeWorkingCopyGetter();Persistence.persistence.unsubscribeFromBindingEvent(this._uiSourceCode,this._boundOnBindingChanged);}
_initializeUISourceCode(){this._uiSourceCodeEventListeners=[this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.TitleChanged,this._refreshHighlighterType,this)];Persistence.persistence.subscribeForBindingEvent(this._uiSourceCode,this._boundOnBindingChanged);for(const message of this._allMessages())
this._addMessageToSource(message);this._installMessageAndDecorationListeners();this._updateStyle();this._decorateAllTypes();this._refreshHighlighterType();if(Runtime.experiments.isEnabled('sourcesPrettyPrint')){const supportedPrettyTypes=new Set(['text/html','text/css','text/javascript']);this.setCanPrettyPrint(supportedPrettyTypes.has(this.highlighterType()),true);}
this._ensurePluginsLoaded();}
wasShown(){super.wasShown();setImmediate(this._updateBucketDecorations.bind(this));this.setEditable(this._canEditSource());for(const plugin of this._plugins)
plugin.wasShown();}
willHide(){for(const plugin of this._plugins)
plugin.willHide();super.willHide();UI.context.setFlavor(Sources.UISourceCodeFrame,null);this._uiSourceCode.removeWorkingCopyGetter();}
_refreshHighlighterType(){const binding=Persistence.persistence.binding(this._uiSourceCode);const highlighterType=binding?binding.network.mimeType():this._uiSourceCode.mimeType();if(this.highlighterType()===highlighterType)
return;this._disposePlugins();this.setHighlighterType(highlighterType);this._ensurePluginsLoaded();}
_canEditSource(){if(Persistence.persistence.binding(this._uiSourceCode))
return true;if(this._uiSourceCode.project().canSetFileContent())
return true;if(this._uiSourceCode.project().isServiceProject())
return false;if(this._uiSourceCode.project().type()===Workspace.projectTypes.Network&&Persistence.networkPersistenceManager.active())
return true;if(this.pretty&&this._uiSourceCode.contentType().hasScripts())
return false;return this._uiSourceCode.contentType()!==Common.resourceTypes.Document;}
_onNetworkPersistenceChanged(){this.setEditable(this._canEditSource());}
commitEditing(){if(!this._uiSourceCode.isDirty())
return;this._muteSourceCodeEvents=true;this._uiSourceCode.commitWorkingCopy();this._muteSourceCodeEvents=false;}
setContent(content){this._disposePlugins();this._rowMessageBuckets.clear();super.setContent(content);for(const message of this._allMessages())
this._addMessageToSource(message);this._decorateAllTypes();this._ensurePluginsLoaded();}
_allMessages(){if(this._persistenceBinding){const combinedSet=this._persistenceBinding.network.messages();combinedSet.addAll(this._persistenceBinding.fileSystem.messages());return combinedSet;}
return this._uiSourceCode.messages();}
onTextChanged(oldRange,newRange){const wasPretty=this.pretty;super.onTextChanged(oldRange,newRange);this._errorPopoverHelper.hidePopover();if(this._isSettingContent)
return;Sources.SourcesPanel.instance().updateLastModificationTime();this._muteSourceCodeEvents=true;if(this.isClean())
this._uiSourceCode.resetWorkingCopy();else
this._uiSourceCode.setWorkingCopyGetter(this.textEditor.text.bind(this.textEditor));this._muteSourceCodeEvents=false;if(wasPretty!==this.pretty){this._updateStyle();this._disposePlugins();this._ensurePluginsLoaded();}}
_onWorkingCopyChanged(event){if(this._muteSourceCodeEvents)
return;this._innerSetContent(this._uiSourceCode.workingCopy());}
_onWorkingCopyCommitted(event){if(!this._muteSourceCodeEvents)
this._innerSetContent(this._uiSourceCode.workingCopy());this.contentCommitted();this._updateStyle();}
_ensurePluginsLoaded(){if(!this.loaded||this._plugins.length)
return;const binding=Persistence.persistence.binding(this._uiSourceCode);const pluginUISourceCode=binding?binding.network:this._uiSourceCode;if(Sources.DebuggerPlugin.accepts(pluginUISourceCode))
this._plugins.push(new Sources.DebuggerPlugin(this.textEditor,pluginUISourceCode,this.transformer()));if(Sources.CSSPlugin.accepts(pluginUISourceCode))
this._plugins.push(new Sources.CSSPlugin(this.textEditor));if(!this.pretty&&Sources.JavaScriptCompilerPlugin.accepts(pluginUISourceCode))
this._plugins.push(new Sources.JavaScriptCompilerPlugin(this.textEditor,pluginUISourceCode));if(Sources.SnippetsPlugin.accepts(pluginUISourceCode))
this._plugins.push(new Sources.SnippetsPlugin(this.textEditor,pluginUISourceCode));if(Sources.ScriptOriginPlugin.accepts(pluginUISourceCode))
this._plugins.push(new Sources.ScriptOriginPlugin(this.textEditor,pluginUISourceCode));if(!this.pretty&&Runtime.experiments.isEnabled('sourceDiff')&&Sources.GutterDiffPlugin.accepts(pluginUISourceCode))
this._plugins.push(new Sources.GutterDiffPlugin(this.textEditor,pluginUISourceCode));this.dispatchEventToListeners(Sources.UISourceCodeFrame.Events.ToolbarItemsChanged);for(const plugin of this._plugins)
plugin.wasShown();}
_disposePlugins(){this.textEditor.operation(()=>{for(const plugin of this._plugins)
plugin.dispose();});this._plugins=[];}
_onBindingChanged(){const binding=Persistence.persistence.binding(this._uiSourceCode);if(binding===this._persistenceBinding)
return;this._unloadUISourceCode();this._persistenceBinding=binding;this._initializeUISourceCode();}
_updateStyle(){this.setEditable(this._canEditSource());}
_innerSetContent(content){this._isSettingContent=true;const oldContent=this.textEditor.text();if(this._diff)
this._diff.highlightModifiedLines(oldContent,content);if(oldContent!==content)
this.setContent(content);this._isSettingContent=false;}
async populateTextAreaContextMenu(contextMenu,editorLineNumber,editorColumnNumber){await super.populateTextAreaContextMenu(contextMenu,editorLineNumber,editorColumnNumber);contextMenu.appendApplicableItems(this._uiSourceCode);const location=this.transformer().editorToRawLocation(editorLineNumber,editorColumnNumber);contextMenu.appendApplicableItems(new Workspace.UILocation(this._uiSourceCode,location[0],location[1]));contextMenu.appendApplicableItems(this);for(const plugin of this._plugins)
await plugin.populateTextAreaContextMenu(contextMenu,editorLineNumber,editorColumnNumber);}
dispose(){this._errorPopoverHelper.dispose();this._unloadUISourceCode();this.textEditor.dispose();this.detach();Common.settings.moduleSetting('persistenceNetworkOverridesEnabled').removeChangeListener(this._onNetworkPersistenceChanged,this);}
_onMessageAdded(event){const message=(event.data);this._addMessageToSource(message);}
_addMessageToSource(message){if(!this.loaded)
return;const editorLocation=this.transformer().rawToEditorLocation(message.lineNumber(),message.columnNumber());let editorLineNumber=editorLocation[0];if(editorLineNumber>=this.textEditor.linesCount)
editorLineNumber=this.textEditor.linesCount-1;if(editorLineNumber<0)
editorLineNumber=0;let messageBucket=this._rowMessageBuckets.get(editorLineNumber);if(!messageBucket){messageBucket=new Sources.UISourceCodeFrame.RowMessageBucket(this,this.textEditor,editorLineNumber);this._rowMessageBuckets.set(editorLineNumber,messageBucket);}
messageBucket.addMessage(message);}
_onMessageRemoved(event){const message=(event.data);this._removeMessageFromSource(message);}
_removeMessageFromSource(message){if(!this.loaded)
return;const editorLocation=this.transformer().rawToEditorLocation(message.lineNumber(),message.columnNumber());let editorLineNumber=editorLocation[0];if(editorLineNumber>=this.textEditor.linesCount)
editorLineNumber=this.textEditor.linesCount-1;if(editorLineNumber<0)
editorLineNumber=0;const messageBucket=this._rowMessageBuckets.get(editorLineNumber);if(!messageBucket)
return;messageBucket.removeMessage(message);if(!messageBucket.uniqueMessagesCount()){messageBucket.detachFromEditor();this._rowMessageBuckets.delete(editorLineNumber);}}
_getErrorPopoverContent(event){const element=event.target.enclosingNodeOrSelfWithClass('text-editor-line-decoration-icon')||event.target.enclosingNodeOrSelfWithClass('text-editor-line-decoration-wave');if(!element)
return null;const anchor=element.enclosingNodeOrSelfWithClass('text-editor-line-decoration-icon')?element.boxInWindow():new AnchorBox(event.clientX,event.clientY,1,1);return{box:anchor,show:popover=>{const messageBucket=element.enclosingNodeOrSelfWithClass('text-editor-line-decoration')._messageBucket;const messagesOutline=messageBucket.messagesDescription();popover.contentElement.appendChild(messagesOutline);return Promise.resolve(true);}};}
_updateBucketDecorations(){for(const bucket of this._rowMessageBuckets.values())
bucket._updateDecoration();}
_onLineDecorationAdded(event){const marker=(event.data);this._decorateTypeThrottled(marker.type());}
_onLineDecorationRemoved(event){const marker=(event.data);this._decorateTypeThrottled(marker.type());}
async _decorateTypeThrottled(type){if(this._typeDecorationsPending.has(type))
return;this._typeDecorationsPending.add(type);const decorator=await self.runtime.extensions(SourceFrame.LineDecorator).find(extension=>extension.descriptor()['decoratorType']===type).instance();this._typeDecorationsPending.delete(type);this.textEditor.codeMirror().operation(()=>{decorator.decorate(this._persistenceBinding?this._persistenceBinding.network:this.uiSourceCode(),this.textEditor,type);});}
_decorateAllTypes(){if(!this.loaded)
return;for(const extension of self.runtime.extensions(SourceFrame.LineDecorator)){const type=extension.descriptor()['decoratorType'];if(this._uiSourceCode.decorationsForType(type))
this._decorateTypeThrottled(type);}}
syncToolbarItems(){const leftToolbarItems=super.syncToolbarItems();const rightToolbarItems=[];for(const plugin of this._plugins){leftToolbarItems.pushAll(plugin.leftToolbarItems());rightToolbarItems.pushAll(plugin.rightToolbarItems());}
if(!rightToolbarItems.length)
return leftToolbarItems;return[...leftToolbarItems,new UI.ToolbarSeparator(true),...rightToolbarItems];}
async populateLineGutterContextMenu(contextMenu,lineNumber){await super.populateLineGutterContextMenu(contextMenu,lineNumber);for(const plugin of this._plugins)
await plugin.populateLineGutterContextMenu(contextMenu,lineNumber);}};Sources.UISourceCodeFrame._iconClassPerLevel={};Sources.UISourceCodeFrame._iconClassPerLevel[Workspace.UISourceCode.Message.Level.Error]='smallicon-error';Sources.UISourceCodeFrame._iconClassPerLevel[Workspace.UISourceCode.Message.Level.Warning]='smallicon-warning';Sources.UISourceCodeFrame._bubbleTypePerLevel={};Sources.UISourceCodeFrame._bubbleTypePerLevel[Workspace.UISourceCode.Message.Level.Error]='error';Sources.UISourceCodeFrame._bubbleTypePerLevel[Workspace.UISourceCode.Message.Level.Warning]='warning';Sources.UISourceCodeFrame._lineClassPerLevel={};Sources.UISourceCodeFrame._lineClassPerLevel[Workspace.UISourceCode.Message.Level.Error]='text-editor-line-with-error';Sources.UISourceCodeFrame._lineClassPerLevel[Workspace.UISourceCode.Message.Level.Warning]='text-editor-line-with-warning';Sources.UISourceCodeFrame.RowMessage=class{constructor(message){this._message=message;this._repeatCount=1;this.element=createElementWithClass('div','text-editor-row-message');this._icon=this.element.createChild('label','','dt-icon-label');this._icon.type=Sources.UISourceCodeFrame._iconClassPerLevel[message.level()];this._repeatCountElement=this.element.createChild('span','text-editor-row-message-repeat-count hidden','dt-small-bubble');this._repeatCountElement.type=Sources.UISourceCodeFrame._bubbleTypePerLevel[message.level()];const linesContainer=this.element.createChild('div');const lines=this._message.text().split('\n');for(let i=0;i<lines.length;++i){const messageLine=linesContainer.createChild('div');messageLine.textContent=lines[i];}}
message(){return this._message;}
repeatCount(){return this._repeatCount;}
setRepeatCount(repeatCount){if(this._repeatCount===repeatCount)
return;this._repeatCount=repeatCount;this._updateMessageRepeatCount();}
_updateMessageRepeatCount(){this._repeatCountElement.textContent=this._repeatCount;const showRepeatCount=this._repeatCount>1;this._repeatCountElement.classList.toggle('hidden',!showRepeatCount);this._icon.classList.toggle('hidden',showRepeatCount);}};Sources.UISourceCodeFrame.RowMessageBucket=class{constructor(sourceFrame,textEditor,editorLineNumber){this._sourceFrame=sourceFrame;this.textEditor=textEditor;this._lineHandle=textEditor.textEditorPositionHandle(editorLineNumber,0);this._decoration=createElementWithClass('div','text-editor-line-decoration');this._decoration._messageBucket=this;this._wave=this._decoration.createChild('div','text-editor-line-decoration-wave');this._icon=this._wave.createChild('span','text-editor-line-decoration-icon','dt-icon-label');this._decorationStartColumn=null;this._messagesDescriptionElement=createElementWithClass('div','text-editor-messages-description-container');this._messages=[];this._level=null;}
_updateWavePosition(editorLineNumber,columnNumber){editorLineNumber=Math.min(editorLineNumber,this.textEditor.linesCount-1);const lineText=this.textEditor.line(editorLineNumber);columnNumber=Math.min(columnNumber,lineText.length);const lineIndent=TextUtils.TextUtils.lineIndent(lineText).length;const startColumn=Math.max(columnNumber-1,lineIndent);if(this._decorationStartColumn===startColumn)
return;if(this._decorationStartColumn!==null)
this.textEditor.removeDecoration(this._decoration,editorLineNumber);this.textEditor.addDecoration(this._decoration,editorLineNumber,startColumn);this._decorationStartColumn=startColumn;}
messagesDescription(){this._messagesDescriptionElement.removeChildren();UI.appendStyle(this._messagesDescriptionElement,'source_frame/messagesPopover.css');for(let i=0;i<this._messages.length;++i)
this._messagesDescriptionElement.appendChild(this._messages[i].element);return this._messagesDescriptionElement;}
detachFromEditor(){const position=this._lineHandle.resolve();if(!position)
return;const editorLineNumber=position.lineNumber;if(this._level){this.textEditor.toggleLineClass(editorLineNumber,Sources.UISourceCodeFrame._lineClassPerLevel[this._level],false);}
if(this._decorationStartColumn!==null){this.textEditor.removeDecoration(this._decoration,editorLineNumber);this._decorationStartColumn=null;}}
uniqueMessagesCount(){return this._messages.length;}
addMessage(message){for(let i=0;i<this._messages.length;++i){const rowMessage=this._messages[i];if(rowMessage.message().isEqual(message)){rowMessage.setRepeatCount(rowMessage.repeatCount()+1);return;}}
const rowMessage=new Sources.UISourceCodeFrame.RowMessage(message);this._messages.push(rowMessage);this._updateDecoration();}
removeMessage(message){for(let i=0;i<this._messages.length;++i){const rowMessage=this._messages[i];if(!rowMessage.message().isEqual(message))
continue;rowMessage.setRepeatCount(rowMessage.repeatCount()-1);if(!rowMessage.repeatCount())
this._messages.splice(i,1);this._updateDecoration();return;}}
_updateDecoration(){if(!this._sourceFrame.isShowing())
return;if(!this._messages.length)
return;const position=this._lineHandle.resolve();if(!position)
return;const editorLineNumber=position.lineNumber;let columnNumber=Number.MAX_VALUE;let maxMessage=null;for(let i=0;i<this._messages.length;++i){const message=this._messages[i].message();const editorLocation=this._sourceFrame.transformer().rawToEditorLocation(editorLineNumber,message.columnNumber());columnNumber=Math.min(columnNumber,editorLocation[1]);if(!maxMessage||Workspace.UISourceCode.Message.messageLevelComparator(maxMessage,message)<0)
maxMessage=message;}
this._updateWavePosition(editorLineNumber,columnNumber);if(this._level===maxMessage.level())
return;if(this._level){this.textEditor.toggleLineClass(editorLineNumber,Sources.UISourceCodeFrame._lineClassPerLevel[this._level],false);this._icon.type='';}
this._level=maxMessage.level();if(!this._level)
return;this.textEditor.toggleLineClass(editorLineNumber,Sources.UISourceCodeFrame._lineClassPerLevel[this._level],true);this._icon.type=Sources.UISourceCodeFrame._iconClassPerLevel[this._level];}};Workspace.UISourceCode.Message._messageLevelPriority={'Warning':3,'Error':4};Workspace.UISourceCode.Message.messageLevelComparator=function(a,b){return Workspace.UISourceCode.Message._messageLevelPriority[a.level()]-
Workspace.UISourceCode.Message._messageLevelPriority[b.level()];};Sources.UISourceCodeFrame.Plugin=class{static accepts(uiSourceCode){return false;}
wasShown(){}
willHide(){}
rightToolbarItems(){return[];}
leftToolbarItems(){return[];}
populateLineGutterContextMenu(contextMenu,lineNumber){return Promise.resolve();}
populateTextAreaContextMenu(contextMenu,lineNumber,columnNumber){return Promise.resolve();}
dispose(){}};Sources.UISourceCodeFrame.Events={ToolbarItemsChanged:Symbol('ToolbarItemsChanged')};;Sources.DebuggerPlugin=class extends Sources.UISourceCodeFrame.Plugin{constructor(textEditor,uiSourceCode,transformer){super();this._textEditor=textEditor;this._uiSourceCode=uiSourceCode;this._transformer=transformer;this._executionLocation=null;this._controlDown=false;this._asyncStepInHoveredLine=0;this._asyncStepInHovered=false;this._clearValueWidgetsTimer=null;this._sourceMapInfobar=null;this._controlTimeout=null;this._scriptsPanel=Sources.SourcesPanel.instance();this._breakpointManager=Bindings.breakpointManager;if(uiSourceCode.project().type()===Workspace.projectTypes.Debugger)
this._textEditor.element.classList.add('source-frame-debugger-script');this._popoverHelper=new UI.PopoverHelper(this._scriptsPanel.element,this._getPopoverRequest.bind(this));this._popoverHelper.setDisableOnClick(true);this._popoverHelper.setTimeout(250,250);this._popoverHelper.setHasPadding(true);this._boundPopoverHelperHide=this._popoverHelper.hidePopover.bind(this._popoverHelper);this._scriptsPanel.element.addEventListener('scroll',this._boundPopoverHelperHide,true);this._boundKeyDown=(this._onKeyDown.bind(this));this._textEditor.element.addEventListener('keydown',this._boundKeyDown,true);this._boundKeyUp=(this._onKeyUp.bind(this));this._textEditor.element.addEventListener('keyup',this._boundKeyUp,true);this._boundMouseMove=(this._onMouseMove.bind(this));this._textEditor.element.addEventListener('mousemove',this._boundMouseMove,false);this._boundMouseDown=(this._onMouseDown.bind(this));this._textEditor.element.addEventListener('mousedown',this._boundMouseDown,true);this._boundBlur=this._onBlur.bind(this);this._textEditor.element.addEventListener('focusout',this._boundBlur,false);this._boundWheel=event=>{if(this._executionLocation&&UI.KeyboardShortcut.eventHasCtrlOrMeta(event))
event.preventDefault();};this._textEditor.element.addEventListener('wheel',this._boundWheel,true);this._textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.GutterClick,this._handleGutterClick,this);this._breakpointManager.addEventListener(Bindings.BreakpointManager.Events.BreakpointAdded,this._breakpointAdded,this);this._breakpointManager.addEventListener(Bindings.BreakpointManager.Events.BreakpointRemoved,this._breakpointRemoved,this);this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this);this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);this._breakpointDecorations=new Set();this._decorationByBreakpoint=new Map();this._possibleBreakpointsRequested=new Set();this._scriptFileForDebuggerModel=new Map();Common.moduleSetting('skipStackFramesPattern').addChangeListener(this._showBlackboxInfobarIfNeeded,this);Common.moduleSetting('skipContentScripts').addChangeListener(this._showBlackboxInfobarIfNeeded,this);this._valueWidgets=new Map();this._continueToLocationDecorations=null;UI.context.addFlavorChangeListener(SDK.DebuggerModel.CallFrame,this._callFrameChanged,this);this._liveLocationPool=new Bindings.LiveLocationPool();this._callFrameChanged();this._updateScriptFiles();if(this._uiSourceCode.isDirty()){this._muted=true;this._mutedFromStart=true;}else{this._muted=false;this._mutedFromStart=false;this._initializeBreakpoints();}
this._blackboxInfobar=null;this._showBlackboxInfobarIfNeeded();const scriptFiles=this._scriptFileForDebuggerModel.valuesArray();for(let i=0;i<scriptFiles.length;++i)
scriptFiles[i].checkMapping();this._hasLineWithoutMapping=false;this._updateLinesWithoutMappingHighlight();if(!Runtime.experiments.isEnabled('sourcesPrettyPrint')){this._prettyPrintInfobar=null;this._detectMinified();}}
static accepts(uiSourceCode){return uiSourceCode.contentType().hasScripts();}
_showBlackboxInfobarIfNeeded(){const uiSourceCode=this._uiSourceCode;if(!uiSourceCode.contentType().hasScripts())
return;const projectType=uiSourceCode.project().type();if(!Bindings.blackboxManager.isBlackboxedUISourceCode(uiSourceCode)){this._hideBlackboxInfobar();return;}
if(this._blackboxInfobar)
this._blackboxInfobar.dispose();const infobar=new UI.Infobar(UI.Infobar.Type.Warning,Common.UIString('This script is blackboxed in debugger'));this._blackboxInfobar=infobar;infobar.createDetailsRowMessage(Common.UIString('Debugger will skip stepping through this script, and will not stop on exceptions'));const scriptFile=this._scriptFileForDebuggerModel.size?this._scriptFileForDebuggerModel.valuesArray()[0]:null;if(scriptFile&&scriptFile.hasSourceMapURL())
infobar.createDetailsRowMessage(Common.UIString('Source map found, but ignored for blackboxed file.'));infobar.createDetailsRowMessage();infobar.createDetailsRowMessage(Common.UIString('Possible ways to cancel this behavior are:'));infobar.createDetailsRowMessage(' - ').createTextChild(Common.UIString('Go to "%s" tab in settings',Common.UIString('Blackboxing')));const unblackboxLink=infobar.createDetailsRowMessage(' - ').createChild('span','link');unblackboxLink.textContent=Common.UIString('Unblackbox this script');unblackboxLink.addEventListener('click',unblackbox,false);function unblackbox(){Bindings.blackboxManager.unblackboxUISourceCode(uiSourceCode);if(projectType===Workspace.projectTypes.ContentScripts)
Bindings.blackboxManager.unblackboxContentScripts();}
this._textEditor.attachInfobar(this._blackboxInfobar);}
_hideBlackboxInfobar(){if(!this._blackboxInfobar)
return;this._blackboxInfobar.dispose();this._blackboxInfobar=null;}
wasShown(){if(this._executionLocation){setImmediate(()=>{this._generateValuesInSource();});}}
willHide(){this._popoverHelper.hidePopover();}
populateLineGutterContextMenu(contextMenu,editorLineNumber){function populate(resolve,reject){const uiLocation=new Workspace.UILocation(this._uiSourceCode,editorLineNumber,0);this._scriptsPanel.appendUILocationItems(contextMenu,uiLocation);const breakpoints=this._lineBreakpointDecorations(editorLineNumber).map(decoration=>decoration.breakpoint).filter(breakpoint=>!!breakpoint);if(!breakpoints.length){contextMenu.debugSection().appendItem(Common.UIString('Add breakpoint'),this._createNewBreakpoint.bind(this,editorLineNumber,'',true));contextMenu.debugSection().appendItem(Common.UIString('Add conditional breakpoint\u2026'),this._editBreakpointCondition.bind(this,editorLineNumber,null,null));contextMenu.debugSection().appendItem(ls`Add logpoint\u2026`,this._editBreakpointCondition.bind(this,editorLineNumber,null,null,true));contextMenu.debugSection().appendItem(Common.UIString('Never pause here'),this._createNewBreakpoint.bind(this,editorLineNumber,'false',true));}else{const hasOneBreakpoint=breakpoints.length===1;const removeTitle=hasOneBreakpoint?Common.UIString('Remove breakpoint'):Common.UIString('Remove all breakpoints in line');contextMenu.debugSection().appendItem(removeTitle,()=>breakpoints.map(breakpoint=>breakpoint.remove()));if(hasOneBreakpoint){contextMenu.debugSection().appendItem(Common.UIString('Edit breakpoint\u2026'),this._editBreakpointCondition.bind(this,editorLineNumber,breakpoints[0],null));}
const hasEnabled=breakpoints.some(breakpoint=>breakpoint.enabled());if(hasEnabled){const title=hasOneBreakpoint?Common.UIString('Disable breakpoint'):Common.UIString('Disable all breakpoints in line');contextMenu.debugSection().appendItem(title,()=>breakpoints.map(breakpoint=>breakpoint.setEnabled(false)));}
const hasDisabled=breakpoints.some(breakpoint=>!breakpoint.enabled());if(hasDisabled){const title=hasOneBreakpoint?Common.UIString('Enable breakpoint'):Common.UIString('Enabled all breakpoints in line');contextMenu.debugSection().appendItem(title,()=>breakpoints.map(breakpoint=>breakpoint.setEnabled(true)));}}
resolve();}
return new Promise(populate.bind(this));}
populateTextAreaContextMenu(contextMenu,editorLineNumber,editorColumnNumber){function addSourceMapURL(scriptFile){Sources.AddSourceMapURLDialog.show(addSourceMapURLDialogCallback.bind(null,scriptFile));}
function addSourceMapURLDialogCallback(scriptFile,url){if(!url)
return;scriptFile.addSourceMapURL(url);}
function populateSourceMapMembers(){if(this._uiSourceCode.project().type()===Workspace.projectTypes.Network&&Common.moduleSetting('jsSourceMapsEnabled').get()&&!Bindings.blackboxManager.isBlackboxedUISourceCode(this._uiSourceCode)){if(this._scriptFileForDebuggerModel.size){const scriptFile=this._scriptFileForDebuggerModel.valuesArray()[0];const addSourceMapURLLabel=Common.UIString('Add source map\u2026');contextMenu.debugSection().appendItem(addSourceMapURLLabel,addSourceMapURL.bind(null,scriptFile));}}}
return super.populateTextAreaContextMenu(contextMenu,editorLineNumber,editorColumnNumber).then(populateSourceMapMembers.bind(this));}
_workingCopyChanged(){if(this._scriptFileForDebuggerModel.size)
return;if(this._uiSourceCode.isDirty())
this._muteBreakpointsWhileEditing();else
this._restoreBreakpointsAfterEditing();}
_workingCopyCommitted(event){this._scriptsPanel.updateLastModificationTime();if(!this._scriptFileForDebuggerModel.size)
this._restoreBreakpointsAfterEditing();}
_didMergeToVM(){this._restoreBreakpointsIfConsistentScripts();}
_didDivergeFromVM(){this._muteBreakpointsWhileEditing();}
_muteBreakpointsWhileEditing(){if(this._muted)
return;for(const decoration of this._breakpointDecorations)
this._updateBreakpointDecoration(decoration);this._muted=true;}
_restoreBreakpointsIfConsistentScripts(){const scriptFiles=this._scriptFileForDebuggerModel.valuesArray();for(let i=0;i<scriptFiles.length;++i){if(scriptFiles[i].hasDivergedFromVM()||scriptFiles[i].isMergingToVM())
return;}
this._restoreBreakpointsAfterEditing();}
_restoreBreakpointsAfterEditing(){this._muted=false;if(this._mutedFromStart){this._mutedFromStart=false;this._initializeBreakpoints();return;}
const decorations=Array.from(this._breakpointDecorations);this._breakpointDecorations.clear();this._textEditor.operation(()=>decorations.map(decoration=>decoration.hide()));for(const decoration of decorations){if(!decoration.breakpoint)
continue;const enabled=decoration.enabled;decoration.breakpoint.remove();const location=decoration.handle.resolve();if(location)
this._setBreakpoint(location.lineNumber,location.columnNumber,decoration.condition,enabled);}}
_isIdentifier(tokenType){return tokenType.startsWith('js-variable')||tokenType.startsWith('js-property')||tokenType==='js-def';}
_getPopoverRequest(event){if(UI.KeyboardShortcut.eventHasCtrlOrMeta(event))
return null;const target=UI.context.flavor(SDK.Target);const debuggerModel=target?target.model(SDK.DebuggerModel):null;if(!debuggerModel||!debuggerModel.isPaused())
return null;const textPosition=this._textEditor.coordinatesToCursorPosition(event.x,event.y);if(!textPosition)
return null;const mouseLine=textPosition.startLine;const mouseColumn=textPosition.startColumn;const textSelection=this._textEditor.selection().normalize();let anchorBox;let editorLineNumber;let startHighlight;let endHighlight;if(textSelection&&!textSelection.isEmpty()){if(textSelection.startLine!==textSelection.endLine||textSelection.startLine!==mouseLine||mouseColumn<textSelection.startColumn||mouseColumn>textSelection.endColumn)
return null;const leftCorner=this._textEditor.cursorPositionToCoordinates(textSelection.startLine,textSelection.startColumn);const rightCorner=this._textEditor.cursorPositionToCoordinates(textSelection.endLine,textSelection.endColumn);anchorBox=new AnchorBox(leftCorner.x,leftCorner.y,rightCorner.x-leftCorner.x,leftCorner.height);editorLineNumber=textSelection.startLine;startHighlight=textSelection.startColumn;endHighlight=textSelection.endColumn-1;}else{const token=this._textEditor.tokenAtTextPosition(textPosition.startLine,textPosition.startColumn);if(!token||!token.type)
return null;editorLineNumber=textPosition.startLine;const line=this._textEditor.line(editorLineNumber);const tokenContent=line.substring(token.startColumn,token.endColumn);const isIdentifier=this._isIdentifier(token.type);if(!isIdentifier&&(token.type!=='js-keyword'||tokenContent!=='this'))
return null;const leftCorner=this._textEditor.cursorPositionToCoordinates(editorLineNumber,token.startColumn);const rightCorner=this._textEditor.cursorPositionToCoordinates(editorLineNumber,token.endColumn-1);anchorBox=new AnchorBox(leftCorner.x,leftCorner.y,rightCorner.x-leftCorner.x,leftCorner.height);startHighlight=token.startColumn;endHighlight=token.endColumn-1;while(startHighlight>1&&line.charAt(startHighlight-1)==='.'){const tokenBefore=this._textEditor.tokenAtTextPosition(editorLineNumber,startHighlight-2);if(!tokenBefore||!tokenBefore.type)
return null;if(tokenBefore.type==='js-meta')
break;startHighlight=tokenBefore.startColumn;}}
let objectPopoverHelper;let highlightDescriptor;return{box:anchorBox,show:async popover=>{const selectedCallFrame=UI.context.flavor(SDK.DebuggerModel.CallFrame);if(!selectedCallFrame)
return false;const evaluationText=this._textEditor.line(editorLineNumber).substring(startHighlight,endHighlight+1);const resolvedText=await Sources.SourceMapNamesResolver.resolveExpression((selectedCallFrame),evaluationText,this._uiSourceCode,editorLineNumber,startHighlight,endHighlight);const result=await selectedCallFrame.evaluate({expression:resolvedText||evaluationText,objectGroup:'popover',includeCommandLineAPI:false,silent:true,returnByValue:false,generatePreview:false});if(!result.object)
return false;objectPopoverHelper=await ObjectUI.ObjectPopoverHelper.buildObjectPopover(result.object,popover);const potentiallyUpdatedCallFrame=UI.context.flavor(SDK.DebuggerModel.CallFrame);if(!objectPopoverHelper||selectedCallFrame!==potentiallyUpdatedCallFrame){debuggerModel.runtimeModel().releaseObjectGroup('popover');if(objectPopoverHelper)
objectPopoverHelper.dispose();return false;}
const highlightRange=new TextUtils.TextRange(editorLineNumber,startHighlight,editorLineNumber,endHighlight);highlightDescriptor=this._textEditor.highlightRange(highlightRange,'source-frame-eval-expression');return true;},hide:()=>{objectPopoverHelper.dispose();debuggerModel.runtimeModel().releaseObjectGroup('popover');this._textEditor.removeHighlight(highlightDescriptor);}};}
_onKeyDown(event){this._clearControlDown();if(event.key==='Escape'){if(this._popoverHelper.isPopoverVisible()){this._popoverHelper.hidePopover();event.consume();}
return;}
if(UI.shortcutRegistry.eventMatchesAction(event,'debugger.toggle-breakpoint')){const selection=this._textEditor.selection();if(!selection)
return;this._toggleBreakpoint(selection.startLine,false);event.consume(true);return;}
if(UI.shortcutRegistry.eventMatchesAction(event,'debugger.toggle-breakpoint-enabled')){const selection=this._textEditor.selection();if(!selection)
return;this._toggleBreakpoint(selection.startLine,true);event.consume(true);return;}
if(UI.KeyboardShortcut.eventHasCtrlOrMeta(event)&&this._executionLocation){this._controlDown=true;if(event.key===(Host.isMac()?'Meta':'Control')){this._controlTimeout=setTimeout(()=>{if(this._executionLocation&&this._controlDown)
this._showContinueToLocations();},150);}}}
_onMouseMove(event){if(this._executionLocation&&this._controlDown&&UI.KeyboardShortcut.eventHasCtrlOrMeta(event)){if(!this._continueToLocationDecorations)
this._showContinueToLocations();}
if(this._continueToLocationDecorations){const textPosition=this._textEditor.coordinatesToCursorPosition(event.x,event.y);const hovering=!!event.target.enclosingNodeOrSelfWithClass('source-frame-async-step-in');this._setAsyncStepInHoveredLine(textPosition?textPosition.startLine:null,hovering);}}
_setAsyncStepInHoveredLine(editorLineNumber,hovered){if(this._asyncStepInHoveredLine===editorLineNumber&&this._asyncStepInHovered===hovered)
return;if(this._asyncStepInHovered&&this._asyncStepInHoveredLine)
this._textEditor.toggleLineClass(this._asyncStepInHoveredLine,'source-frame-async-step-in-hovered',false);this._asyncStepInHoveredLine=editorLineNumber;this._asyncStepInHovered=hovered;if(this._asyncStepInHovered&&this._asyncStepInHoveredLine)
this._textEditor.toggleLineClass(this._asyncStepInHoveredLine,'source-frame-async-step-in-hovered',true);}
_onMouseDown(event){if(!this._executionLocation||!UI.KeyboardShortcut.eventHasCtrlOrMeta(event))
return;if(!this._continueToLocationDecorations)
return;event.consume();const textPosition=this._textEditor.coordinatesToCursorPosition(event.x,event.y);if(!textPosition)
return;for(const decoration of this._continueToLocationDecorations.keys()){const range=decoration.find();if(range.from.line!==textPosition.startLine||range.to.line!==textPosition.startLine)
continue;if(range.from.ch<=textPosition.startColumn&&textPosition.startColumn<=range.to.ch){this._continueToLocationDecorations.get(decoration)();break;}}}
_onBlur(event){if(this._textEditor.element.isAncestor((event.target)))
return;this._clearControlDown();}
_onKeyUp(event){this._clearControlDown();}
_clearControlDown(){this._controlDown=false;this._clearContinueToLocations();clearTimeout(this._controlTimeout);}
async _editBreakpointCondition(editorLineNumber,breakpoint,location,preferLogpoint){const oldCondition=breakpoint?breakpoint.condition():'';const decorationElement=createElement('div');const dialog=new Sources.BreakpointEditDialog(editorLineNumber,oldCondition,!!preferLogpoint,result=>{dialog.detach();this._textEditor.removeDecoration(decorationElement,editorLineNumber);if(!result.committed)
return;if(breakpoint)
breakpoint.setCondition(result.condition);else if(location)
this._setBreakpoint(location.lineNumber,location.columnNumber,result.condition,true);else
this._createNewBreakpoint(editorLineNumber,result.condition,true);});this._textEditor.addDecoration(decorationElement,editorLineNumber);dialog.show(decorationElement);}
_executionLineChanged(liveLocation){this._clearExecutionLine();const uiLocation=liveLocation.uiLocation();if(!uiLocation||uiLocation.uiSourceCode!==this._uiSourceCode){this._executionLocation=null;return;}
this._executionLocation=uiLocation;const editorLocation=this._transformer.rawToEditorLocation(uiLocation.lineNumber,uiLocation.columnNumber);this._textEditor.setExecutionLocation(editorLocation[0],editorLocation[1]);if(this._textEditor.isShowing()){setImmediate(()=>{if(this._controlDown)
this._showContinueToLocations();else
this._generateValuesInSource();});}}
_generateValuesInSource(){if(!Common.moduleSetting('inlineVariableValues').get())
return;const executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext)
return;const callFrame=UI.context.flavor(SDK.DebuggerModel.CallFrame);if(!callFrame)
return;const localScope=callFrame.localScope();const functionLocation=callFrame.functionLocation();if(localScope&&functionLocation){Sources.SourceMapNamesResolver.resolveScopeInObject(localScope).getAllProperties(false,false).then(this._prepareScopeVariables.bind(this,callFrame));}}
_showContinueToLocations(){this._popoverHelper.hidePopover();const executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext)
return;const callFrame=UI.context.flavor(SDK.DebuggerModel.CallFrame);if(!callFrame)
return;const start=callFrame.functionLocation()||callFrame.location();const debuggerModel=callFrame.debuggerModel;debuggerModel.getPossibleBreakpoints(start,null,true).then(locations=>this._textEditor.operation(renderLocations.bind(this,locations)));function renderLocations(locations){this._clearContinueToLocationsNoRestore();this._textEditor.hideExecutionLineBackground();this._clearValueWidgets();this._continueToLocationDecorations=new Map();locations=locations.reverse();let previousCallLine=-1;for(const location of locations){const editorLocation=this._transformer.rawToEditorLocation(location.lineNumber,location.columnNumber);let token=this._textEditor.tokenAtTextPosition(editorLocation[0],editorLocation[1]);if(!token)
continue;const line=this._textEditor.line(editorLocation[0]);let tokenContent=line.substring(token.startColumn,token.endColumn);if(!token.type&&tokenContent==='.'){token=this._textEditor.tokenAtTextPosition(editorLocation[0],token.endColumn+1);tokenContent=line.substring(token.startColumn,token.endColumn);}
if(!token.type)
continue;const validKeyword=token.type==='js-keyword'&&(tokenContent==='this'||tokenContent==='return'||tokenContent==='new'||tokenContent==='continue'||tokenContent==='break');if(!validKeyword&&!this._isIdentifier(token.type))
continue;if(previousCallLine===editorLocation[0]&&location.type!==Protocol.Debugger.BreakLocationType.Call)
continue;let highlightRange=new TextUtils.TextRange(editorLocation[0],token.startColumn,editorLocation[0],token.endColumn-1);let decoration=this._textEditor.highlightRange(highlightRange,'source-frame-continue-to-location');this._continueToLocationDecorations.set(decoration,location.continueToLocation.bind(location));if(location.type===Protocol.Debugger.BreakLocationType.Call)
previousCallLine=editorLocation[0];let isAsyncCall=(line[token.startColumn-1]==='.'&&tokenContent==='then')||tokenContent==='setTimeout'||tokenContent==='setInterval'||tokenContent==='postMessage';if(tokenContent==='new'){token=this._textEditor.tokenAtTextPosition(editorLocation[0],token.endColumn+1);tokenContent=line.substring(token.startColumn,token.endColumn);isAsyncCall=tokenContent==='Worker';}
const isCurrentPosition=this._executionLocation&&location.lineNumber===this._executionLocation.lineNumber&&location.columnNumber===this._executionLocation.columnNumber;if(location.type===Protocol.Debugger.BreakLocationType.Call&&isAsyncCall){const asyncStepInRange=this._findAsyncStepInRange(this._textEditor,editorLocation[0],line,token.endColumn);if(asyncStepInRange){highlightRange=new TextUtils.TextRange(editorLocation[0],asyncStepInRange.from,editorLocation[0],asyncStepInRange.to-1);decoration=this._textEditor.highlightRange(highlightRange,'source-frame-async-step-in');this._continueToLocationDecorations.set(decoration,this._asyncStepIn.bind(this,location,!!isCurrentPosition));}}}
this._continueToLocationRenderedForTest();}}
_continueToLocationRenderedForTest(){}
_findAsyncStepInRange(textEditor,editorLineNumber,line,column){let token;let tokenText;let from=column;let to=line.length;let position=line.indexOf('(',column);const argumentsStart=position;if(position===-1)
return null;position++;skipWhitespace();if(position>=line.length)
return null;nextToken();if(!token)
return null;from=token.startColumn;if(token.type==='js-keyword'&&tokenText==='async'){skipWhitespace();if(position>=line.length)
return{from:from,to:to};nextToken();if(!token)
return{from:from,to:to};}
if(token.type==='js-keyword'&&tokenText==='function')
return{from:from,to:to};if(token.type==='js-string')
return{from:argumentsStart,to:to};if(token.type&&this._isIdentifier(token.type))
return{from:from,to:to};if(tokenText!=='(')
return null;const closeParen=line.indexOf(')',position);if(closeParen===-1||line.substring(position,closeParen).indexOf('(')!==-1)
return{from:from,to:to};return{from:from,to:closeParen+1};function nextToken(){token=textEditor.tokenAtTextPosition(editorLineNumber,position);if(token){position=token.endColumn;to=token.endColumn;tokenText=line.substring(token.startColumn,token.endColumn);}}
function skipWhitespace(){while(position<line.length){if(line[position]===' '){position++;continue;}
const token=textEditor.tokenAtTextPosition(editorLineNumber,position);if(token.type==='js-comment'){position=token.endColumn;continue;}
break;}}}
_asyncStepIn(location,isCurrentPosition){if(!isCurrentPosition)
location.continueToLocation(asyncStepIn);else
asyncStepIn();function asyncStepIn(){location.debuggerModel.scheduleStepIntoAsync();}}
_prepareScopeVariables(callFrame,allProperties){const properties=allProperties.properties;this._clearValueWidgets();if(!properties||!properties.length||properties.length>500||!this._textEditor.isShowing())
return;const functionUILocation=Bindings.debuggerWorkspaceBinding.rawLocationToUILocation((callFrame.functionLocation()));const executionUILocation=Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(callFrame.location());if(!functionUILocation||!executionUILocation||functionUILocation.uiSourceCode!==this._uiSourceCode||executionUILocation.uiSourceCode!==this._uiSourceCode)
return;const functionEditorLocation=this._transformer.rawToEditorLocation(functionUILocation.lineNumber,functionUILocation.columnNumber);const executionEditorLocation=this._transformer.rawToEditorLocation(executionUILocation.lineNumber,executionUILocation.columnNumber);const fromLine=functionEditorLocation[0];const fromColumn=functionEditorLocation[1];const toLine=executionEditorLocation[0];if(fromLine>=toLine||toLine-fromLine>500||fromLine<0||toLine>=this._textEditor.linesCount)
return;const valuesMap=new Map();for(const property of properties)
valuesMap.set(property.name,property.value);const namesPerLine=new Map();let skipObjectProperty=false;const tokenizer=new TextEditor.CodeMirrorUtils.TokenizerFactory().createTokenizer('text/javascript');tokenizer(this._textEditor.line(fromLine).substring(fromColumn),processToken.bind(this,fromLine));for(let i=fromLine+1;i<toLine;++i)
tokenizer(this._textEditor.line(i),processToken.bind(this,i));function processToken(editorLineNumber,tokenValue,tokenType,column,newColumn){if(!skipObjectProperty&&tokenType&&this._isIdentifier(tokenType)&&valuesMap.get(tokenValue)){let names=namesPerLine.get(editorLineNumber);if(!names){names=new Set();namesPerLine.set(editorLineNumber,names);}
names.add(tokenValue);}
skipObjectProperty=tokenValue==='.';}
this._textEditor.operation(this._renderDecorations.bind(this,valuesMap,namesPerLine,fromLine,toLine));}
_renderDecorations(valuesMap,namesPerLine,fromLine,toLine){const formatter=new ObjectUI.RemoteObjectPreviewFormatter();for(let i=fromLine;i<toLine;++i){const names=namesPerLine.get(i);const oldWidget=this._valueWidgets.get(i);if(!names){if(oldWidget){this._valueWidgets.delete(i);this._textEditor.removeDecoration(oldWidget,i);}
continue;}
const widget=createElementWithClass('div','text-editor-value-decoration');const base=this._textEditor.cursorPositionToCoordinates(i,0);const offset=this._textEditor.cursorPositionToCoordinates(i,this._textEditor.line(i).length);const codeMirrorLinesLeftPadding=4;const left=offset.x-base.x+codeMirrorLinesLeftPadding;widget.style.left=left+'px';widget.__nameToToken=new Map();let renderedNameCount=0;for(const name of names){if(renderedNameCount>10)
break;if(namesPerLine.get(i-1)&&namesPerLine.get(i-1).has(name))
continue;if(renderedNameCount)
widget.createTextChild(', ');const nameValuePair=widget.createChild('span');widget.__nameToToken.set(name,nameValuePair);nameValuePair.createTextChild(name+' = ');const value=valuesMap.get(name);const propertyCount=value.preview?value.preview.properties.length:0;const entryCount=value.preview&&value.preview.entries?value.preview.entries.length:0;if(value.preview&&propertyCount+entryCount<10){formatter.appendObjectPreview(nameValuePair,value.preview,false);}else{nameValuePair.appendChild(ObjectUI.ObjectPropertiesSection.createValueElement(value,false,false));}
++renderedNameCount;}
let widgetChanged=true;if(oldWidget){widgetChanged=false;for(const name of widget.__nameToToken.keys()){const oldText=oldWidget.__nameToToken.get(name)?oldWidget.__nameToToken.get(name).textContent:'';const newText=widget.__nameToToken.get(name)?widget.__nameToToken.get(name).textContent:'';if(newText!==oldText){widgetChanged=true;UI.runCSSAnimationOnce((widget.__nameToToken.get(name)),'source-frame-value-update-highlight');}}
if(widgetChanged){this._valueWidgets.delete(i);this._textEditor.removeDecoration(oldWidget,i);}}
if(widgetChanged){this._valueWidgets.set(i,widget);this._textEditor.addDecoration(widget,i);}}}
_clearExecutionLine(){this._textEditor.operation(()=>{if(this._executionLocation)
this._textEditor.clearExecutionLine();this._executionLocation=null;if(this._clearValueWidgetsTimer){clearTimeout(this._clearValueWidgetsTimer);this._clearValueWidgetsTimer=null;}
this._clearValueWidgetsTimer=setTimeout(this._clearValueWidgets.bind(this),1000);this._clearContinueToLocationsNoRestore();});}
_clearValueWidgets(){clearTimeout(this._clearValueWidgetsTimer);this._clearValueWidgetsTimer=null;this._textEditor.operation(()=>{for(const line of this._valueWidgets.keys())
this._textEditor.removeDecoration(this._valueWidgets.get(line),line);this._valueWidgets.clear();});}
_clearContinueToLocationsNoRestore(){if(!this._continueToLocationDecorations)
return;this._textEditor.operation(()=>{for(const decoration of this._continueToLocationDecorations.keys())
this._textEditor.removeHighlight(decoration);this._continueToLocationDecorations=null;this._setAsyncStepInHoveredLine(null,false);});}
_clearContinueToLocations(){if(!this._continueToLocationDecorations)
return;this._textEditor.operation(()=>{this._textEditor.showExecutionLineBackground();this._generateValuesInSource();this._clearContinueToLocationsNoRestore();});}
_lineBreakpointDecorations(lineNumber){return Array.from(this._breakpointDecorations).filter(decoration=>(decoration.handle.resolve()||{}).lineNumber===lineNumber);}
_breakpointDecoration(editorLineNumber,editorColumnNumber){for(const decoration of this._breakpointDecorations){const location=decoration.handle.resolve();if(!location)
continue;if(location.lineNumber===editorLineNumber&&location.columnNumber===editorColumnNumber)
return decoration;}
return null;}
_updateBreakpointDecoration(decoration){if(!this._scheduledBreakpointDecorationUpdates){this._scheduledBreakpointDecorationUpdates=new Set();setImmediate(()=>this._textEditor.operation(update.bind(this)));}
this._scheduledBreakpointDecorationUpdates.add(decoration);function update(){if(!this._scheduledBreakpointDecorationUpdates)
return;const editorLineNumbers=new Set();for(const decoration of this._scheduledBreakpointDecorationUpdates){const location=decoration.handle.resolve();if(!location)
continue;editorLineNumbers.add(location.lineNumber);}
this._scheduledBreakpointDecorationUpdates=null;let waitingForInlineDecorations=false;for(const lineNumber of editorLineNumbers){const decorations=this._lineBreakpointDecorations(lineNumber);updateGutter.call(this,lineNumber,decorations);if(this._possibleBreakpointsRequested.has(lineNumber)){waitingForInlineDecorations=true;continue;}
updateInlineDecorations.call(this,lineNumber,decorations);}
if(!waitingForInlineDecorations)
this._breakpointDecorationsUpdatedForTest();}
function updateGutter(editorLineNumber,decorations){this._textEditor.toggleLineClass(editorLineNumber,'cm-breakpoint',false);this._textEditor.toggleLineClass(editorLineNumber,'cm-breakpoint-disabled',false);this._textEditor.toggleLineClass(editorLineNumber,'cm-breakpoint-conditional',false);if(decorations.length){decorations.sort(Sources.DebuggerPlugin.BreakpointDecoration.mostSpecificFirst);this._textEditor.toggleLineClass(editorLineNumber,'cm-breakpoint',true);this._textEditor.toggleLineClass(editorLineNumber,'cm-breakpoint-disabled',!decorations[0].enabled||this._muted);this._textEditor.toggleLineClass(editorLineNumber,'cm-breakpoint-conditional',!!decorations[0].condition);}}
function updateInlineDecorations(editorLineNumber,decorations){const actualBookmarks=new Set(decorations.map(decoration=>decoration.bookmark).filter(bookmark=>!!bookmark));const lineEnd=this._textEditor.line(editorLineNumber).length;const bookmarks=this._textEditor.bookmarks(new TextUtils.TextRange(editorLineNumber,0,editorLineNumber,lineEnd),Sources.DebuggerPlugin.BreakpointDecoration.bookmarkSymbol);for(const bookmark of bookmarks){if(!actualBookmarks.has(bookmark))
bookmark.clear();}
if(!decorations.length)
return;if(decorations.length>1){for(const decoration of decorations){decoration.update();if(!this._muted)
decoration.show();else
decoration.hide();}}else{decorations[0].update();decorations[0].hide();}}}
_breakpointDecorationsUpdatedForTest(){}
_inlineBreakpointClick(decoration,event){event.consume(true);if(decoration.breakpoint){if(event.shiftKey)
decoration.breakpoint.setEnabled(!decoration.breakpoint.enabled());else
decoration.breakpoint.remove();}else{const editorLocation=decoration.handle.resolve();if(!editorLocation)
return;const location=this._transformer.editorToRawLocation(editorLocation.lineNumber,editorLocation.columnNumber);this._setBreakpoint(location[0],location[1],decoration.condition,true);}}
_inlineBreakpointContextMenu(decoration,event){event.consume(true);const editorLocation=decoration.handle.resolve();if(!editorLocation)
return;const location=this._transformer.editorToRawLocation(editorLocation[0],editorLocation[1]);const contextMenu=new UI.ContextMenu(event);if(decoration.breakpoint){contextMenu.debugSection().appendItem(Common.UIString('Edit breakpoint\u2026'),this._editBreakpointCondition.bind(this,editorLocation.lineNumber,decoration.breakpoint,null));}else{contextMenu.debugSection().appendItem(Common.UIString('Add conditional breakpoint\u2026'),this._editBreakpointCondition.bind(this,editorLocation.lineNumber,null,editorLocation));contextMenu.debugSection().appendItem(ls`Add logpoint\u2026`,this._editBreakpointCondition.bind(this,editorLocation.lineNumber,null,editorLocation,true));contextMenu.debugSection().appendItem(Common.UIString('Never pause here'),this._setBreakpoint.bind(this,location[0],location[1],'false',true));}
contextMenu.show();}
_shouldIgnoreExternalBreakpointEvents(event){const uiLocation=(event.data.uiLocation);if(uiLocation.uiSourceCode!==this._uiSourceCode)
return true;if(this._muted)
return true;const scriptFiles=this._scriptFileForDebuggerModel.valuesArray();for(let i=0;i<scriptFiles.length;++i){if(scriptFiles[i].isDivergingFromVM()||scriptFiles[i].isMergingToVM())
return true;}
return false;}
_breakpointAdded(event){if(this._shouldIgnoreExternalBreakpointEvents(event))
return;const uiLocation=(event.data.uiLocation);const breakpoint=(event.data.breakpoint);this._addBreakpoint(uiLocation,breakpoint);}
_addBreakpoint(uiLocation,breakpoint){const editorLocation=this._transformer.rawToEditorLocation(uiLocation.lineNumber,uiLocation.columnNumber);const lineDecorations=this._lineBreakpointDecorations(uiLocation.lineNumber);let decoration=this._breakpointDecoration(editorLocation[0],editorLocation[1]);if(decoration){decoration.breakpoint=breakpoint;decoration.condition=breakpoint.condition();decoration.enabled=breakpoint.enabled();}else{const handle=this._textEditor.textEditorPositionHandle(editorLocation[0],editorLocation[1]);decoration=new Sources.DebuggerPlugin.BreakpointDecoration(this._textEditor,handle,breakpoint.condition(),breakpoint.enabled(),breakpoint);decoration.element.addEventListener('click',this._inlineBreakpointClick.bind(this,decoration),true);decoration.element.addEventListener('contextmenu',this._inlineBreakpointContextMenu.bind(this,decoration),true);this._breakpointDecorations.add(decoration);}
this._decorationByBreakpoint.set(breakpoint,decoration);this._updateBreakpointDecoration(decoration);if(breakpoint.enabled()&&!lineDecorations.length){this._possibleBreakpointsRequested.add(editorLocation[0]);const start=this._transformer.editorToRawLocation(editorLocation[0],0);const end=this._transformer.editorToRawLocation(editorLocation[0]+1,0);this._breakpointManager.possibleBreakpoints(this._uiSourceCode,new TextUtils.TextRange(start[0],start[1],end[0],end[1])).then(addInlineDecorations.bind(this,editorLocation[0]));}
function addInlineDecorations(editorLineNumber,possibleLocations){this._possibleBreakpointsRequested.delete(editorLineNumber);const decorations=this._lineBreakpointDecorations(editorLineNumber);for(const decoration of decorations)
this._updateBreakpointDecoration(decoration);if(!decorations.some(decoration=>!!decoration.breakpoint))
return;const columns=new Set();for(const decoration of decorations){const editorLocation=decoration.handle.resolve();if(!editorLocation)
continue;columns.add(editorLocation.columnNumber);}
for(const location of possibleLocations){const editorLocation=this._transformer.rawToEditorLocation(location.lineNumber,location.columnNumber);if(columns.has(editorLocation[1]))
continue;const handle=this._textEditor.textEditorPositionHandle(editorLocation[0],editorLocation[1]);const decoration=new Sources.DebuggerPlugin.BreakpointDecoration(this._textEditor,handle,'',false,null);decoration.element.addEventListener('click',this._inlineBreakpointClick.bind(this,decoration),true);decoration.element.addEventListener('contextmenu',this._inlineBreakpointContextMenu.bind(this,decoration),true);this._breakpointDecorations.add(decoration);this._updateBreakpointDecoration(decoration);}}}
_breakpointRemoved(event){if(this._shouldIgnoreExternalBreakpointEvents(event))
return;const uiLocation=(event.data.uiLocation);const breakpoint=(event.data.breakpoint);const decoration=this._decorationByBreakpoint.get(breakpoint);if(!decoration)
return;this._decorationByBreakpoint.delete(breakpoint);const editorLocation=this._transformer.rawToEditorLocation(uiLocation.lineNumber,uiLocation.columnNumber);decoration.breakpoint=null;decoration.enabled=false;const lineDecorations=this._lineBreakpointDecorations(editorLocation[0]);if(!lineDecorations.some(decoration=>!!decoration.breakpoint)){for(const lineDecoration of lineDecorations){this._breakpointDecorations.delete(lineDecoration);this._updateBreakpointDecoration(lineDecoration);}}else{this._updateBreakpointDecoration(decoration);}}
_initializeBreakpoints(){const breakpointLocations=this._breakpointManager.breakpointLocationsForUISourceCode(this._uiSourceCode);for(const breakpointLocation of breakpointLocations)
this._addBreakpoint(breakpointLocation.uiLocation,breakpointLocation.breakpoint);}
_updateLinesWithoutMappingHighlight(){const isSourceMapSource=!!Bindings.CompilerScriptMapping.uiSourceCodeOrigin(this._uiSourceCode);if(!isSourceMapSource)
return;const linesCount=this._textEditor.linesCount;for(let i=0;i<linesCount;++i){const lineHasMapping=Bindings.CompilerScriptMapping.uiLineHasMapping(this._uiSourceCode,i);if(!lineHasMapping)
this._hasLineWithoutMapping=true;if(this._hasLineWithoutMapping)
this._textEditor.toggleLineClass(i,'cm-line-without-source-mapping',!lineHasMapping);}}
_updateScriptFiles(){for(const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)){const scriptFile=Bindings.debuggerWorkspaceBinding.scriptFile(this._uiSourceCode,debuggerModel);if(scriptFile)
this._updateScriptFile(debuggerModel);}}
_updateScriptFile(debuggerModel){const oldScriptFile=this._scriptFileForDebuggerModel.get(debuggerModel);const newScriptFile=Bindings.debuggerWorkspaceBinding.scriptFile(this._uiSourceCode,debuggerModel);this._scriptFileForDebuggerModel.delete(debuggerModel);if(oldScriptFile){oldScriptFile.removeEventListener(Bindings.ResourceScriptFile.Events.DidMergeToVM,this._didMergeToVM,this);oldScriptFile.removeEventListener(Bindings.ResourceScriptFile.Events.DidDivergeFromVM,this._didDivergeFromVM,this);if(this._muted&&!this._uiSourceCode.isDirty())
this._restoreBreakpointsIfConsistentScripts();}
if(!newScriptFile)
return;this._scriptFileForDebuggerModel.set(debuggerModel,newScriptFile);newScriptFile.addEventListener(Bindings.ResourceScriptFile.Events.DidMergeToVM,this._didMergeToVM,this);newScriptFile.addEventListener(Bindings.ResourceScriptFile.Events.DidDivergeFromVM,this._didDivergeFromVM,this);newScriptFile.checkMapping();if(newScriptFile.hasSourceMapURL())
this._showSourceMapInfobar();}
_showSourceMapInfobar(){if(this._sourceMapInfobar)
return;this._sourceMapInfobar=UI.Infobar.create(UI.Infobar.Type.Info,Common.UIString('Source Map detected.'),Common.settings.createSetting('sourceMapInfobarDisabled',false));if(!this._sourceMapInfobar)
return;this._sourceMapInfobar.createDetailsRowMessage(Common.UIString('Associated files should be added to the file tree. You can debug these resolved source files as regular JavaScript files.'));this._sourceMapInfobar.createDetailsRowMessage(Common.UIString('Associated files are available via file tree or %s.',UI.shortcutRegistry.shortcutTitleForAction('quickOpen.show')));this._sourceMapInfobar.setCloseCallback(()=>this._sourceMapInfobar=null);this._textEditor.attachInfobar(this._sourceMapInfobar);}
_detectMinified(){const content=this._uiSourceCode.content();if(!content||!TextUtils.isMinified(content))
return;this._prettyPrintInfobar=UI.Infobar.create(UI.Infobar.Type.Info,Common.UIString('Pretty-print this minified file?'),Common.settings.createSetting('prettyPrintInfobarDisabled',false));if(!this._prettyPrintInfobar)
return;this._prettyPrintInfobar.setCloseCallback(()=>this._prettyPrintInfobar=null);const toolbar=new UI.Toolbar('');const button=new UI.ToolbarButton('','largeicon-pretty-print');toolbar.appendToolbarItem(button);toolbar.element.style.display='inline-block';toolbar.element.style.verticalAlign='middle';toolbar.element.style.marginBottom='3px';toolbar.element.style.pointerEvents='none';const element=this._prettyPrintInfobar.createDetailsRowMessage();element.appendChild(UI.formatLocalized('You can click the %s button on the bottom status bar, and continue debugging with the new formatted source.',[toolbar.element]));this._textEditor.attachInfobar(this._prettyPrintInfobar);}
_handleGutterClick(event){if(this._muted)
return;const eventData=(event.data);const editorLineNumber=eventData.lineNumber;const eventObject=eventData.event;if(eventObject.button!==0||eventObject.altKey||eventObject.ctrlKey||eventObject.metaKey)
return;this._toggleBreakpoint(editorLineNumber,eventObject.shiftKey);eventObject.consume(true);}
_toggleBreakpoint(editorLineNumber,onlyDisable){const decorations=this._lineBreakpointDecorations(editorLineNumber);if(!decorations.length){this._createNewBreakpoint(editorLineNumber,'',true);return;}
const hasDisabled=this._textEditor.hasLineClass(editorLineNumber,'cm-breakpoint-disabled');const breakpoints=decorations.map(decoration=>decoration.breakpoint).filter(breakpoint=>!!breakpoint);for(const breakpoint of breakpoints){if(onlyDisable)
breakpoint.setEnabled(hasDisabled);else
breakpoint.remove();}}
async _createNewBreakpoint(editorLineNumber,condition,enabled){Host.userMetrics.actionTaken(Host.UserMetrics.Action.ScriptsBreakpointSet);if(editorLineNumber<this._textEditor.linesCount){const lineLength=Math.min(this._textEditor.line(editorLineNumber).length,1024);const start=this._transformer.editorToRawLocation(editorLineNumber,0);const end=this._transformer.editorToRawLocation(editorLineNumber,lineLength);const locations=await this._breakpointManager.possibleBreakpoints(this._uiSourceCode,new TextUtils.TextRange(start[0],start[1],end[0],end[1]));if(locations&&locations.length){this._setBreakpoint(locations[0].lineNumber,locations[0].columnNumber,condition,enabled);return;}}
const origin=this._transformer.editorToRawLocation(editorLineNumber,0);await this._setBreakpoint(origin[0],origin[1],condition,enabled);}
toggleBreakpointOnCurrentLine(onlyDisable){if(this._muted)
return;const selection=this._textEditor.selection();if(!selection)
return;this._toggleBreakpoint(selection.startLine,onlyDisable);}
_setBreakpoint(lineNumber,columnNumber,condition,enabled){if(!Bindings.CompilerScriptMapping.uiLineHasMapping(this._uiSourceCode,lineNumber))
return;Common.moduleSetting('breakpointsActive').set(true);this._breakpointManager.setBreakpoint(this._uiSourceCode,lineNumber,columnNumber,condition,enabled);this._breakpointWasSetForTest(lineNumber,columnNumber,condition,enabled);}
_breakpointWasSetForTest(lineNumber,columnNumber,condition,enabled){}
_callFrameChanged(){this._liveLocationPool.disposeAll();const callFrame=UI.context.flavor(SDK.DebuggerModel.CallFrame);if(!callFrame){this._clearExecutionLine();return;}
Bindings.debuggerWorkspaceBinding.createCallFrameLiveLocation(callFrame.location(),this._executionLineChanged.bind(this),this._liveLocationPool);}
dispose(){for(const decoration of this._breakpointDecorations)
decoration.dispose();this._breakpointDecorations.clear();if(this._scheduledBreakpointDecorationUpdates){for(const decoration of this._scheduledBreakpointDecorationUpdates)
decoration.dispose();this._scheduledBreakpointDecorationUpdates.clear();}
this._hideBlackboxInfobar();if(this._sourceMapInfobar)
this._sourceMapInfobar.dispose();if(this._prettyPrintInfobar)
this._prettyPrintInfobar.dispose();this._scriptsPanel.element.removeEventListener('scroll',this._boundPopoverHelperHide,true);for(const script of this._scriptFileForDebuggerModel.values()){script.removeEventListener(Bindings.ResourceScriptFile.Events.DidMergeToVM,this._didMergeToVM,this);script.removeEventListener(Bindings.ResourceScriptFile.Events.DidDivergeFromVM,this._didDivergeFromVM,this);}
this._scriptFileForDebuggerModel.clear();this._textEditor.element.removeEventListener('keydown',this._boundKeyDown,true);this._textEditor.element.removeEventListener('keyup',this._boundKeyUp,true);this._textEditor.element.removeEventListener('mousemove',this._boundMouseMove,false);this._textEditor.element.removeEventListener('mousedown',this._boundMouseDown,true);this._textEditor.element.removeEventListener('focusout',this._boundBlur,false);this._textEditor.element.removeEventListener('wheel',this._boundWheel,true);this._textEditor.removeEventListener(SourceFrame.SourcesTextEditor.Events.GutterClick,this._handleGutterClick,this);this._popoverHelper.hidePopover();this._popoverHelper.dispose();this._breakpointManager.removeEventListener(Bindings.BreakpointManager.Events.BreakpointAdded,this._breakpointAdded,this);this._breakpointManager.removeEventListener(Bindings.BreakpointManager.Events.BreakpointRemoved,this._breakpointRemoved,this);this._uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this);this._uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);Common.moduleSetting('skipStackFramesPattern').removeChangeListener(this._showBlackboxInfobarIfNeeded,this);Common.moduleSetting('skipContentScripts').removeChangeListener(this._showBlackboxInfobarIfNeeded,this);super.dispose();this._clearExecutionLine();UI.context.removeFlavorChangeListener(SDK.DebuggerModel.CallFrame,this._callFrameChanged,this);this._liveLocationPool.disposeAll();}};Sources.DebuggerPlugin.BreakpointDecoration=class{constructor(textEditor,handle,condition,enabled,breakpoint){this._textEditor=textEditor;this.handle=handle;this.condition=condition;this.enabled=enabled;this.breakpoint=breakpoint;this.element=UI.Icon.create('smallicon-inline-breakpoint');this.element.classList.toggle('cm-inline-breakpoint',true);this.bookmark=null;}
static mostSpecificFirst(decoration1,decoration2){if(decoration1.enabled!==decoration2.enabled)
return decoration1.enabled?-1:1;if(!!decoration1.condition!==!!decoration2.condition)
return!!decoration1.condition?-1:1;return 0;}
update(){if(!this.condition)
this.element.setIconType('smallicon-inline-breakpoint');else
this.element.setIconType('smallicon-inline-breakpoint-conditional');this.element.classList.toggle('cm-inline-disabled',!this.enabled);}
show(){if(this.bookmark)
return;const editorLocation=this.handle.resolve();if(!editorLocation)
return;this.bookmark=this._textEditor.addBookmark(editorLocation.lineNumber,editorLocation.columnNumber,this.element,Sources.DebuggerPlugin.BreakpointDecoration.bookmarkSymbol);this.bookmark[Sources.DebuggerPlugin.BreakpointDecoration._elementSymbolForTest]=this.element;}
hide(){if(!this.bookmark)
return;this.bookmark.clear();this.bookmark=null;}
dispose(){const location=this.handle.resolve();if(location){this._textEditor.toggleLineClass(location.lineNumber,'cm-breakpoint',false);this._textEditor.toggleLineClass(location.lineNumber,'cm-breakpoint-disabled',false);this._textEditor.toggleLineClass(location.lineNumber,'cm-breakpoint-conditional',false);}
this.hide();}};Sources.DebuggerPlugin.BreakpointDecoration.bookmarkSymbol=Symbol('bookmark');Sources.DebuggerPlugin.BreakpointDecoration._elementSymbolForTest=Symbol('element');Sources.DebuggerPlugin.continueToLocationDecorationSymbol=Symbol('bookmark');;Sources.CSSPlugin=class extends Sources.UISourceCodeFrame.Plugin{constructor(textEditor){super();this._textEditor=textEditor;this._swatchPopoverHelper=new InlineEditor.SwatchPopoverHelper();this._muteSwatchProcessing=false;this._hadSwatchChange=false;this._bezierEditor=null;this._editedSwatchTextRange=null;this._spectrum=null;this._currentSwatch=null;this._textEditor.configureAutocomplete({suggestionsCallback:this._cssSuggestions.bind(this),isWordChar:this._isWordChar.bind(this)});this._textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.ScrollChanged,this._textEditorScrolled,this);this._textEditor.addEventListener(UI.TextEditor.Events.TextChanged,this._onTextChanged,this);this._updateSwatches(0,this._textEditor.linesCount-1);this._shortcuts={};this._registerShortcuts();this._boundHandleKeyDown=this._handleKeyDown.bind(this);this._textEditor.element.addEventListener('keydown',this._boundHandleKeyDown,false);}
static accepts(uiSourceCode){return uiSourceCode.contentType().isStyleSheet();}
_registerShortcuts(){const shortcutKeys=UI.ShortcutsScreen.SourcesPanelShortcuts;for(const descriptor of shortcutKeys.IncreaseCSSUnitByOne)
this._shortcuts[descriptor.key]=this._handleUnitModification.bind(this,1);for(const descriptor of shortcutKeys.DecreaseCSSUnitByOne)
this._shortcuts[descriptor.key]=this._handleUnitModification.bind(this,-1);for(const descriptor of shortcutKeys.IncreaseCSSUnitByTen)
this._shortcuts[descriptor.key]=this._handleUnitModification.bind(this,10);for(const descriptor of shortcutKeys.DecreaseCSSUnitByTen)
this._shortcuts[descriptor.key]=this._handleUnitModification.bind(this,-10);}
_handleKeyDown(event){const shortcutKey=UI.KeyboardShortcut.makeKeyFromEvent((event));const handler=this._shortcuts[shortcutKey];if(handler&&handler())
event.consume(true);}
_textEditorScrolled(){if(this._swatchPopoverHelper.isShowing())
this._swatchPopoverHelper.hide(true);}
_modifyUnit(unit,change){const unitValue=parseInt(unit,10);if(isNaN(unitValue))
return null;const tail=unit.substring((unitValue).toString().length);return String.sprintf('%d%s',unitValue+change,tail);}
_handleUnitModification(change){const selection=this._textEditor.selection().normalize();let token=this._textEditor.tokenAtTextPosition(selection.startLine,selection.startColumn);if(!token){if(selection.startColumn>0)
token=this._textEditor.tokenAtTextPosition(selection.startLine,selection.startColumn-1);if(!token)
return false;}
if(token.type!=='css-number')
return false;const cssUnitRange=new TextUtils.TextRange(selection.startLine,token.startColumn,selection.startLine,token.endColumn);const cssUnitText=this._textEditor.text(cssUnitRange);const newUnitText=this._modifyUnit(cssUnitText,change);if(!newUnitText)
return false;this._textEditor.editRange(cssUnitRange,newUnitText);selection.startColumn=token.startColumn;selection.endColumn=selection.startColumn+newUnitText.length;this._textEditor.setSelection(selection);return true;}
_updateSwatches(startLine,endLine){const swatches=[];const swatchPositions=[];const regexes=[SDK.CSSMetadata.VariableRegex,SDK.CSSMetadata.URLRegex,UI.Geometry.CubicBezier.Regex,Common.Color.Regex];const handlers=new Map();handlers.set(Common.Color.Regex,this._createColorSwatch.bind(this));handlers.set(UI.Geometry.CubicBezier.Regex,this._createBezierSwatch.bind(this));for(let lineNumber=startLine;lineNumber<=endLine;lineNumber++){const line=this._textEditor.line(lineNumber).substring(0,Sources.CSSPlugin.maxSwatchProcessingLength);const results=TextUtils.TextUtils.splitStringByRegexes(line,regexes);for(let i=0;i<results.length;i++){const result=results[i];if(result.regexIndex===-1||!handlers.has(regexes[result.regexIndex]))
continue;const delimiters=/[\s:;,(){}]/;const positionBefore=result.position-1;const positionAfter=result.position+result.value.length;if(positionBefore>=0&&!delimiters.test(line.charAt(positionBefore))||positionAfter<line.length&&!delimiters.test(line.charAt(positionAfter)))
continue;const swatch=handlers.get(regexes[result.regexIndex])(result.value);if(!swatch)
continue;swatches.push(swatch);swatchPositions.push(TextUtils.TextRange.createFromLocation(lineNumber,result.position));}}
this._textEditor.operation(putSwatchesInline.bind(this));function putSwatchesInline(){const clearRange=new TextUtils.TextRange(startLine,0,endLine,this._textEditor.line(endLine).length);this._textEditor.bookmarks(clearRange,Sources.CSSPlugin.SwatchBookmark).forEach(marker=>marker.clear());for(let i=0;i<swatches.length;i++){const swatch=swatches[i];const swatchPosition=swatchPositions[i];const bookmark=this._textEditor.addBookmark(swatchPosition.startLine,swatchPosition.startColumn,swatch,Sources.CSSPlugin.SwatchBookmark);swatch[Sources.CSSPlugin.SwatchBookmark]=bookmark;}}}
_createColorSwatch(text){const color=Common.Color.parse(text);if(!color)
return null;const swatch=InlineEditor.ColorSwatch.create();swatch.setColor(color);swatch.iconElement().title=Common.UIString('Open color picker.');swatch.iconElement().addEventListener('click',this._swatchIconClicked.bind(this,swatch),false);swatch.hideText(true);return swatch;}
_createBezierSwatch(text){if(!UI.Geometry.CubicBezier.parse(text))
return null;const swatch=InlineEditor.BezierSwatch.create();swatch.setBezierText(text);swatch.iconElement().title=Common.UIString('Open cubic bezier editor.');swatch.iconElement().addEventListener('click',this._swatchIconClicked.bind(this,swatch),false);swatch.hideText(true);return swatch;}
_swatchIconClicked(swatch,event){event.consume(true);this._hadSwatchChange=false;this._muteSwatchProcessing=true;const swatchPosition=swatch[Sources.CSSPlugin.SwatchBookmark].position();this._textEditor.setSelection(swatchPosition);this._editedSwatchTextRange=swatchPosition.clone();this._editedSwatchTextRange.endColumn+=swatch.textContent.length;this._currentSwatch=swatch;if(swatch instanceof InlineEditor.ColorSwatch)
this._showSpectrum(swatch);else if(swatch instanceof InlineEditor.BezierSwatch)
this._showBezierEditor(swatch);}
_showSpectrum(swatch){if(!this._spectrum){this._spectrum=new ColorPicker.Spectrum();this._spectrum.addEventListener(ColorPicker.Spectrum.Events.SizeChanged,this._spectrumResized,this);this._spectrum.addEventListener(ColorPicker.Spectrum.Events.ColorChanged,this._spectrumChanged,this);}
this._spectrum.setColor(swatch.color(),swatch.format());this._swatchPopoverHelper.show(this._spectrum,swatch.iconElement(),this._swatchPopoverHidden.bind(this));}
_spectrumResized(event){this._swatchPopoverHelper.reposition();}
_spectrumChanged(event){const colorString=(event.data);const color=Common.Color.parse(colorString);if(!color)
return;this._currentSwatch.setColor(color);this._changeSwatchText(colorString);}
_showBezierEditor(swatch){if(!this._bezierEditor){this._bezierEditor=new InlineEditor.BezierEditor();this._bezierEditor.addEventListener(InlineEditor.BezierEditor.Events.BezierChanged,this._bezierChanged,this);}
let cubicBezier=UI.Geometry.CubicBezier.parse(swatch.bezierText());if(!cubicBezier){cubicBezier=(UI.Geometry.CubicBezier.parse('linear'));}
this._bezierEditor.setBezier(cubicBezier);this._swatchPopoverHelper.show(this._bezierEditor,swatch.iconElement(),this._swatchPopoverHidden.bind(this));}
_bezierChanged(event){const bezierString=(event.data);this._currentSwatch.setBezierText(bezierString);this._changeSwatchText(bezierString);}
_changeSwatchText(text){this._hadSwatchChange=true;this._textEditor.editRange((this._editedSwatchTextRange),text,'*swatch-text-changed');this._editedSwatchTextRange.endColumn=this._editedSwatchTextRange.startColumn+text.length;}
_swatchPopoverHidden(commitEdit){this._muteSwatchProcessing=false;if(!commitEdit&&this._hadSwatchChange)
this._textEditor.undo();}
_onTextChanged(event){if(!this._muteSwatchProcessing)
this._updateSwatches(event.data.newRange.startLine,event.data.newRange.endLine);}
_isWordChar(char){return TextUtils.TextUtils.isWordChar(char)||char==='.'||char==='-'||char==='$';}
_cssSuggestions(prefixRange,substituteRange){const prefix=this._textEditor.text(prefixRange);if(prefix.startsWith('$'))
return null;const propertyToken=this._backtrackPropertyToken(prefixRange.startLine,prefixRange.startColumn-1);if(!propertyToken)
return null;const line=this._textEditor.line(prefixRange.startLine);const tokenContent=line.substring(propertyToken.startColumn,propertyToken.endColumn);const propertyValues=SDK.cssMetadata().propertyValues(tokenContent);return Promise.resolve(propertyValues.filter(value=>value.startsWith(prefix)).map(value=>({text:value})));}
_backtrackPropertyToken(lineNumber,columnNumber){const backtrackDepth=10;let tokenPosition=columnNumber;const line=this._textEditor.line(lineNumber);let seenColon=false;for(let i=0;i<backtrackDepth&&tokenPosition>=0;++i){const token=this._textEditor.tokenAtTextPosition(lineNumber,tokenPosition);if(!token)
return null;if(token.type==='css-property')
return seenColon?token:null;if(token.type&&!(token.type.indexOf('whitespace')!==-1||token.type.startsWith('css-comment')))
return null;if(!token.type&&line.substring(token.startColumn,token.endColumn)===':'){if(!seenColon)
seenColon=true;else
return null;}
tokenPosition=token.startColumn-1;}
return null;}
dispose(){if(this._swatchPopoverHelper.isShowing())
this._swatchPopoverHelper.hide(true);this._textEditor.removeEventListener(SourceFrame.SourcesTextEditor.Events.ScrollChanged,this._textEditorScrolled,this);this._textEditor.removeEventListener(UI.TextEditor.Events.TextChanged,this._onTextChanged,this);this._textEditor.bookmarks(this._textEditor.fullRange(),Sources.CSSPlugin.SwatchBookmark).forEach(marker=>marker.clear());this._textEditor.element.removeEventListener('keydown',this._boundHandleKeyDown,false);}};Sources.CSSPlugin.maxSwatchProcessingLength=300;Sources.CSSPlugin.SwatchBookmark=Symbol('swatch');;Sources.GutterDiffPlugin=class extends Sources.UISourceCodeFrame.Plugin{constructor(textEditor,uiSourceCode){super();this._textEditor=textEditor;this._uiSourceCode=uiSourceCode;this._decorations=[];this._textEditor.installGutter(Sources.GutterDiffPlugin.DiffGutterType,true);this._workspaceDiff=WorkspaceDiff.workspaceDiff();this._workspaceDiff.subscribeToDiffChange(this._uiSourceCode,this._update,this);this._update();}
static accepts(uiSourceCode){return uiSourceCode.project().type()===Workspace.projectTypes.Network;}
_updateDecorations(removed,added){this._textEditor.operation(operation);function operation(){for(const decoration of removed)
decoration.remove();for(const decoration of added)
decoration.install();}}
_update(){if(this._uiSourceCode)
this._workspaceDiff.requestDiff(this._uiSourceCode).then(this._innerUpdate.bind(this));else
this._innerUpdate(null);}
_innerUpdate(lineDiff){if(!lineDiff){this._updateDecorations(this._decorations,[]);this._decorations=[];return;}
const oldDecorations=new Map();for(let i=0;i<this._decorations.length;++i){const decoration=this._decorations[i];const lineNumber=decoration.lineNumber();if(lineNumber===-1)
continue;oldDecorations.set(lineNumber,decoration);}
const diff=SourceFrame.SourceCodeDiff.computeDiff(lineDiff);const newDecorations=new Map();for(let i=0;i<diff.length;++i){const diffEntry=diff[i];for(let lineNumber=diffEntry.from;lineNumber<diffEntry.to;++lineNumber)
newDecorations.set(lineNumber,{lineNumber:lineNumber,type:diffEntry.type});}
const decorationDiff=oldDecorations.diff(newDecorations,(e1,e2)=>e1.type===e2.type);const addedDecorations=decorationDiff.added.map(entry=>new Sources.GutterDiffPlugin.GutterDecoration(this._textEditor,entry.lineNumber,entry.type));this._decorations=decorationDiff.equal.concat(addedDecorations);this._updateDecorations(decorationDiff.removed,addedDecorations);this._decorationsSetForTest(newDecorations);}
_decorationsSetForTest(decorations){}
async populateLineGutterContextMenu(contextMenu,lineNumber){Sources.GutterDiffPlugin._appendRevealDiffContextMenu(contextMenu,this._uiSourceCode);}
async populateTextAreaContextMenu(contextMenu,lineNumber,columnNumber){Sources.GutterDiffPlugin._appendRevealDiffContextMenu(contextMenu,this._uiSourceCode);}
static _appendRevealDiffContextMenu(contextMenu,uiSourceCode){if(!WorkspaceDiff.workspaceDiff().isUISourceCodeModified(uiSourceCode))
return;contextMenu.revealSection().appendItem(ls`Local Modifications...`,()=>{Common.Revealer.reveal(new WorkspaceDiff.DiffUILocation(uiSourceCode));});}
dispose(){for(const decoration of this._decorations)
decoration.remove();WorkspaceDiff.workspaceDiff().unsubscribeFromDiffChange(this._uiSourceCode,this._update,this);}};Sources.GutterDiffPlugin.GutterDecoration=class{constructor(textEditor,lineNumber,type){this._textEditor=textEditor;this._position=this._textEditor.textEditorPositionHandle(lineNumber,0);this._className='';if(type===SourceFrame.SourceCodeDiff.EditType.Insert)
this._className='diff-entry-insert';else if(type===SourceFrame.SourceCodeDiff.EditType.Delete)
this._className='diff-entry-delete';else if(type===SourceFrame.SourceCodeDiff.EditType.Modify)
this._className='diff-entry-modify';this.type=type;}
lineNumber(){const location=this._position.resolve();if(!location)
return-1;return location.lineNumber;}
install(){const location=this._position.resolve();if(!location)
return;const element=createElementWithClass('div','diff-marker');element.textContent='\u00A0';this._textEditor.setGutterDecoration(location.lineNumber,Sources.GutterDiffPlugin.DiffGutterType,element);this._textEditor.toggleLineClass(location.lineNumber,this._className,true);}
remove(){const location=this._position.resolve();if(!location)
return;this._textEditor.setGutterDecoration(location.lineNumber,Sources.GutterDiffPlugin.DiffGutterType,null);this._textEditor.toggleLineClass(location.lineNumber,this._className,false);}};Sources.GutterDiffPlugin.DiffGutterType='CodeMirror-gutter-diff';Sources.GutterDiffPlugin.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){let uiSourceCode=(target);const binding=Persistence.persistence.binding(uiSourceCode);if(binding)
uiSourceCode=binding.network;Sources.GutterDiffPlugin._appendRevealDiffContextMenu(contextMenu,uiSourceCode);}};;Sources.SearchSourcesView=class extends Search.SearchView{constructor(){super('sources');}
static async openSearch(query,searchImmediately){const view=UI.viewManager.view('sources.search-sources-tab');const location=await UI.viewManager.resolveLocation('drawer-view');location.appendView(view);await UI.viewManager.revealView((view));const widget=(await view.widget());widget.toggle(query,!!searchImmediately);return widget;}
createScope(){return new Sources.SourcesSearchScope();}};Sources.SearchSourcesView.ActionDelegate=class{handleAction(context,actionId){this._showSearch();return true;}
_showSearch(){const selection=UI.inspectorView.element.window().getSelection();let queryCandidate='';if(selection.rangeCount)
queryCandidate=selection.toString().replace(/\r?\n.*/,'');return Sources.SearchSourcesView.openSearch(queryCandidate);}};;Sources.NavigatorView=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('sources/navigatorView.css');this._scriptsTree=new UI.TreeOutlineInShadow();this._scriptsTree.registerRequiredCSS('sources/navigatorTree.css');this._scriptsTree.setComparator(Sources.NavigatorView._treeElementsCompare);this.contentElement.appendChild(this._scriptsTree.element);this.setDefaultFocusedElement(this._scriptsTree.element);this._uiSourceCodeNodes=new Multimap();this._subfolderNodes=new Map();this._rootNode=new Sources.NavigatorRootTreeNode(this);this._rootNode.populate();this._frameNodes=new Map();this.contentElement.addEventListener('contextmenu',this.handleContextMenu.bind(this),false);UI.shortcutRegistry.addShortcutListener(this.contentElement,'sources.rename',this._renameShortcut.bind(this),true);this._navigatorGroupByFolderSetting=Common.moduleSetting('navigatorGroupByFolder');this._navigatorGroupByFolderSetting.addChangeListener(this._groupingChanged.bind(this));this._initGrouping();Persistence.persistence.addEventListener(Persistence.Persistence.Events.BindingCreated,this._onBindingChanged,this);Persistence.persistence.addEventListener(Persistence.Persistence.Events.BindingRemoved,this._onBindingChanged,this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.NameChanged,this._targetNameChanged,this);SDK.targetManager.observeTargets(this);this._resetWorkspace(Workspace.workspace);this._workspace.uiSourceCodes().forEach(this._addUISourceCode.bind(this));Bindings.networkProjectManager.addEventListener(Bindings.NetworkProjectManager.Events.FrameAttributionAdded,this._frameAttributionAdded,this);Bindings.networkProjectManager.addEventListener(Bindings.NetworkProjectManager.Events.FrameAttributionRemoved,this._frameAttributionRemoved,this);}
static _treeElementOrder(treeElement){if(treeElement._boostOrder)
return 0;if(!Sources.NavigatorView._typeOrders){const weights={};const types=Sources.NavigatorView.Types;weights[types.Root]=1;weights[types.Domain]=10;weights[types.FileSystemFolder]=1;weights[types.NetworkFolder]=1;weights[types.SourceMapFolder]=2;weights[types.File]=10;weights[types.Frame]=70;weights[types.Worker]=90;weights[types.FileSystem]=100;Sources.NavigatorView._typeOrders=weights;}
let order=Sources.NavigatorView._typeOrders[treeElement._nodeType];if(treeElement._uiSourceCode){const contentType=treeElement._uiSourceCode.contentType();if(contentType.isDocument())
order+=3;else if(contentType.isScript())
order+=5;else if(contentType.isStyleSheet())
order+=10;else
order+=15;}
return order;}
static appendSearchItem(contextMenu,path){function searchPath(){Sources.SearchSourcesView.openSearch(`file:${path.trim()}`);}
let searchLabel=Common.UIString('Search in folder');if(!path||!path.trim()){path='*';searchLabel=Common.UIString('Search in all files');}
contextMenu.viewSection().appendItem(searchLabel,searchPath);}
static _treeElementsCompare(treeElement1,treeElement2){const typeWeight1=Sources.NavigatorView._treeElementOrder(treeElement1);const typeWeight2=Sources.NavigatorView._treeElementOrder(treeElement2);if(typeWeight1>typeWeight2)
return 1;if(typeWeight1<typeWeight2)
return-1;return treeElement1.titleAsText().compareTo(treeElement2.titleAsText());}
_onBindingChanged(event){const binding=(event.data);const networkNodes=this._uiSourceCodeNodes.get(binding.network);for(const networkNode of networkNodes)
networkNode.updateTitle();const fileSystemNodes=this._uiSourceCodeNodes.get(binding.fileSystem);for(const fileSystemNode of fileSystemNodes)
fileSystemNode.updateTitle();const pathTokens=Persistence.FileSystemWorkspaceBinding.relativePath(binding.fileSystem);let folderPath='';for(let i=0;i<pathTokens.length-1;++i){folderPath+=pathTokens[i];const folderId=this._folderNodeId(binding.fileSystem.project(),null,null,binding.fileSystem.origin(),folderPath);const folderNode=this._subfolderNodes.get(folderId);if(folderNode)
folderNode.updateTitle();folderPath+='/';}
const fileSystemRoot=this._rootNode.child(binding.fileSystem.project().id());if(fileSystemRoot)
fileSystemRoot.updateTitle();}
focus(){this._scriptsTree.focus();}
_resetWorkspace(workspace){this._workspace=workspace;this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._uiSourceCodeAdded,this);this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this._uiSourceCodeRemoved,this);this._workspace.addEventListener(Workspace.Workspace.Events.ProjectAdded,event=>{const project=(event.data);this._projectAdded(project);if(project.type()===Workspace.projectTypes.FileSystem)
this._computeUniqueFileSystemProjectNames();});this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,event=>{const project=(event.data);this._removeProject(project);if(project.type()===Workspace.projectTypes.FileSystem)
this._computeUniqueFileSystemProjectNames();});this._workspace.projects().forEach(this._projectAdded.bind(this));this._computeUniqueFileSystemProjectNames();}
workspace(){return this._workspace;}
acceptProject(project){return!project.isServiceProject();}
_frameAttributionAdded(event){const uiSourceCode=(event.data.uiSourceCode);if(!this._acceptsUISourceCode(uiSourceCode))
return;const addedFrame=(event.data.frame);this._addUISourceCodeNode(uiSourceCode,addedFrame);}
_frameAttributionRemoved(event){const uiSourceCode=(event.data.uiSourceCode);if(!this._acceptsUISourceCode(uiSourceCode))
return;const removedFrame=(event.data.frame);const node=Array.from(this._uiSourceCodeNodes.get(uiSourceCode)).find(node=>node.frame()===removedFrame);this._removeUISourceCodeNode(node);}
_acceptsUISourceCode(uiSourceCode){return this.acceptProject(uiSourceCode.project());}
_addUISourceCode(uiSourceCode){if(!this._acceptsUISourceCode(uiSourceCode))
return;const frames=Bindings.NetworkProject.framesForUISourceCode(uiSourceCode);if(frames.length){for(const frame of frames)
this._addUISourceCodeNode(uiSourceCode,frame);}else{this._addUISourceCodeNode(uiSourceCode,null);}
this.uiSourceCodeAdded(uiSourceCode);}
_addUISourceCodeNode(uiSourceCode,frame){const isFromSourceMap=uiSourceCode.contentType().isFromSourceMap();let path;if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem)
path=Persistence.FileSystemWorkspaceBinding.relativePath(uiSourceCode).slice(0,-1);else
path=Common.ParsedURL.extractPath(uiSourceCode.url()).split('/').slice(1,-1);const project=uiSourceCode.project();const target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);const folderNode=this._folderNode(uiSourceCode,project,target,frame,uiSourceCode.origin(),path,isFromSourceMap);const uiSourceCodeNode=new Sources.NavigatorUISourceCodeTreeNode(this,uiSourceCode,frame);folderNode.appendChild(uiSourceCodeNode);this._uiSourceCodeNodes.set(uiSourceCode,uiSourceCodeNode);}
uiSourceCodeAdded(uiSourceCode){}
_uiSourceCodeAdded(event){const uiSourceCode=(event.data);this._addUISourceCode(uiSourceCode);}
_uiSourceCodeRemoved(event){const uiSourceCode=(event.data);this._removeUISourceCode(uiSourceCode);}
tryAddProject(project){this._projectAdded(project);project.uiSourceCodes().forEach(this._addUISourceCode.bind(this));}
_projectAdded(project){if(!this.acceptProject(project)||project.type()!==Workspace.projectTypes.FileSystem||Snippets.isSnippetsProject(project)||this._rootNode.child(project.id()))
return;this._rootNode.appendChild(new Sources.NavigatorGroupTreeNode(this,project,project.id(),Sources.NavigatorView.Types.FileSystem,project.displayName()));}
_computeUniqueFileSystemProjectNames(){const fileSystemProjects=this._workspace.projectsForType(Workspace.projectTypes.FileSystem);if(!fileSystemProjects.length)
return;const encoder=new Persistence.PathEncoder();const reversedPaths=fileSystemProjects.map(project=>{const fileSystem=(project);return encoder.encode(fileSystem.fileSystemPath()).reverse();});const reversedIndex=new Common.Trie();for(const reversedPath of reversedPaths)
reversedIndex.add(reversedPath);for(let i=0;i<fileSystemProjects.length;++i){const reversedPath=reversedPaths[i];const project=fileSystemProjects[i];reversedIndex.remove(reversedPath);const commonPrefix=reversedIndex.longestPrefix(reversedPath,false);reversedIndex.add(reversedPath);const path=encoder.decode(reversedPath.substring(0,commonPrefix.length+1).reverse());const fileSystemNode=this._rootNode.child(project.id());if(fileSystemNode)
fileSystemNode.setTitle(path);}}
_removeProject(project){const uiSourceCodes=project.uiSourceCodes();for(let i=0;i<uiSourceCodes.length;++i)
this._removeUISourceCode(uiSourceCodes[i]);if(project.type()!==Workspace.projectTypes.FileSystem)
return;const fileSystemNode=this._rootNode.child(project.id());if(!fileSystemNode)
return;this._rootNode.removeChild(fileSystemNode);}
_folderNodeId(project,target,frame,projectOrigin,path){const targetId=target?target.id():'';const projectId=project.type()===Workspace.projectTypes.FileSystem?project.id():'';const frameId=this._groupByFrame&&frame?frame.id:'';return targetId+':'+projectId+':'+frameId+':'+projectOrigin+':'+path;}
_folderNode(uiSourceCode,project,target,frame,projectOrigin,path,fromSourceMap){if(Snippets.isSnippetsUISourceCode(uiSourceCode))
return this._rootNode;if(target&&!this._groupByFolder&&!fromSourceMap)
return this._domainNode(uiSourceCode,project,target,frame,projectOrigin);const folderPath=path.join('/');const folderId=this._folderNodeId(project,target,frame,projectOrigin,folderPath);let folderNode=this._subfolderNodes.get(folderId);if(folderNode)
return folderNode;if(!path.length){if(target)
return this._domainNode(uiSourceCode,project,target,frame,projectOrigin);return(this._rootNode.child(project.id()));}
const parentNode=this._folderNode(uiSourceCode,project,target,frame,projectOrigin,path.slice(0,-1),fromSourceMap);let type=fromSourceMap?Sources.NavigatorView.Types.SourceMapFolder:Sources.NavigatorView.Types.NetworkFolder;if(project.type()===Workspace.projectTypes.FileSystem)
type=Sources.NavigatorView.Types.FileSystemFolder;const name=path[path.length-1];folderNode=new Sources.NavigatorFolderTreeNode(this,project,folderId,type,folderPath,name);this._subfolderNodes.set(folderId,folderNode);parentNode.appendChild(folderNode);return folderNode;}
_domainNode(uiSourceCode,project,target,frame,projectOrigin){const frameNode=this._frameNode(project,target,frame);if(!this._groupByDomain)
return frameNode;let domainNode=frameNode.child(projectOrigin);if(domainNode)
return domainNode;domainNode=new Sources.NavigatorGroupTreeNode(this,project,projectOrigin,Sources.NavigatorView.Types.Domain,this._computeProjectDisplayName(target,projectOrigin));if(frame&&projectOrigin===Common.ParsedURL.extractOrigin(frame.url))
domainNode.treeNode()._boostOrder=true;frameNode.appendChild(domainNode);return domainNode;}
_frameNode(project,target,frame){if(!this._groupByFrame||!frame)
return this._targetNode(project,target);let frameNode=this._frameNodes.get(frame);if(frameNode)
return frameNode;frameNode=new Sources.NavigatorGroupTreeNode(this,project,target.id()+':'+frame.id,Sources.NavigatorView.Types.Frame,frame.displayName());frameNode.setHoverCallback(hoverCallback);this._frameNodes.set(frame,frameNode);const parentFrame=frame.parentFrame||frame.crossTargetParentFrame();this._frameNode(project,parentFrame?parentFrame.resourceTreeModel().target():target,parentFrame).appendChild(frameNode);if(!parentFrame)
frameNode.treeNode()._boostOrder=true;function hoverCallback(hovered){if(hovered){const overlayModel=target.model(SDK.OverlayModel);if(overlayModel)
overlayModel.highlightFrame(frame.id);}else{SDK.OverlayModel.hideDOMNodeHighlight();}}
return frameNode;}
_targetNode(project,target){if(target===SDK.targetManager.mainTarget())
return this._rootNode;let targetNode=this._rootNode.child('target:'+target.id());if(!targetNode){targetNode=new Sources.NavigatorGroupTreeNode(this,project,'target:'+target.id(),target.type()===SDK.Target.Type.Frame?Sources.NavigatorView.Types.Frame:Sources.NavigatorView.Types.Worker,target.name());this._rootNode.appendChild(targetNode);}
return targetNode;}
_computeProjectDisplayName(target,projectOrigin){const runtimeModel=target.model(SDK.RuntimeModel);const executionContexts=runtimeModel?runtimeModel.executionContexts():[];for(const context of executionContexts){if(context.name&&context.origin&&projectOrigin.startsWith(context.origin))
return context.name;}
if(!projectOrigin)
return Common.UIString('(no domain)');const parsedURL=new Common.ParsedURL(projectOrigin);const prettyURL=parsedURL.isValid?parsedURL.host+(parsedURL.port?(':'+parsedURL.port):''):'';return(prettyURL||projectOrigin);}
revealUISourceCode(uiSourceCode,select){const nodes=this._uiSourceCodeNodes.get(uiSourceCode);const node=nodes.firstValue();if(!node)
return null;if(this._scriptsTree.selectedTreeElement)
this._scriptsTree.selectedTreeElement.deselect();this._lastSelectedUISourceCode=uiSourceCode;node.reveal(select);return node;}
_sourceSelected(uiSourceCode,focusSource){this._lastSelectedUISourceCode=uiSourceCode;Common.Revealer.reveal(uiSourceCode,!focusSource);}
_removeUISourceCode(uiSourceCode){const nodes=this._uiSourceCodeNodes.get(uiSourceCode);for(const node of nodes)
this._removeUISourceCodeNode(node);}
_removeUISourceCodeNode(node){const uiSourceCode=node.uiSourceCode();this._uiSourceCodeNodes.delete(uiSourceCode,node);const project=uiSourceCode.project();const target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);const frame=node.frame();let parentNode=node.parent;parentNode.removeChild(node);node=parentNode;while(node){parentNode=node.parent;if(!parentNode||!node.isEmpty())
break;if(parentNode===this._rootNode&&project.type()===Workspace.projectTypes.FileSystem)
break;if(!(node instanceof Sources.NavigatorGroupTreeNode||node instanceof Sources.NavigatorFolderTreeNode))
break;if(node._type===Sources.NavigatorView.Types.Frame){this._discardFrame((frame));break;}
const folderId=this._folderNodeId(project,target,frame,uiSourceCode.origin(),node._folderPath);this._subfolderNodes.delete(folderId);parentNode.removeChild(node);node=parentNode;}}
reset(){for(const node of this._uiSourceCodeNodes.valuesArray())
node.dispose();this._scriptsTree.removeChildren();this._uiSourceCodeNodes.clear();this._subfolderNodes.clear();this._frameNodes.clear();this._rootNode.reset();}
handleContextMenu(event){}
_renameShortcut(){const node=this._scriptsTree.selectedTreeElement&&this._scriptsTree.selectedTreeElement._node;if(!node||!node._uiSourceCode||!node._uiSourceCode.canRename())
return false;this.rename(node,false);return true;}
_handleContextMenuCreate(project,path,uiSourceCode){if(uiSourceCode){const relativePath=Persistence.FileSystemWorkspaceBinding.relativePath(uiSourceCode);relativePath.pop();path=relativePath.join('/');}
this.create(project,path,uiSourceCode);}
_handleContextMenuRename(node){this.rename(node,false);}
_handleContextMenuExclude(project,path){const shouldExclude=window.confirm(Common.UIString('Are you sure you want to exclude this folder?'));if(shouldExclude){UI.startBatchUpdate();project.excludeFolder(Persistence.FileSystemWorkspaceBinding.completeURL(project,path));UI.endBatchUpdate();}}
_handleContextMenuDelete(uiSourceCode){const shouldDelete=window.confirm(Common.UIString('Are you sure you want to delete this file?'));if(shouldDelete)
uiSourceCode.project().deleteFile(uiSourceCode);}
handleFileContextMenu(event,node){const uiSourceCode=node.uiSourceCode();const contextMenu=new UI.ContextMenu(event);contextMenu.appendApplicableItems(uiSourceCode);const project=uiSourceCode.project();if(project.type()===Workspace.projectTypes.FileSystem){contextMenu.editSection().appendItem(Common.UIString('Rename\u2026'),this._handleContextMenuRename.bind(this,node));contextMenu.editSection().appendItem(Common.UIString('Make a copy\u2026'),this._handleContextMenuCreate.bind(this,project,'',uiSourceCode));contextMenu.editSection().appendItem(Common.UIString('Delete'),this._handleContextMenuDelete.bind(this,uiSourceCode));}
contextMenu.show();}
handleFolderContextMenu(event,node){const path=node._folderPath||'';const project=node._project;const contextMenu=new UI.ContextMenu(event);Sources.NavigatorView.appendSearchItem(contextMenu,path);const folderPath=Common.ParsedURL.urlToPlatformPath(Persistence.FileSystemWorkspaceBinding.completeURL(project,path),Host.isWin());contextMenu.revealSection().appendItem(Common.UIString('Open folder'),()=>InspectorFrontendHost.showItemInFolder(folderPath));if(project.canCreateFile()){contextMenu.defaultSection().appendItem(Common.UIString('New file'),this._handleContextMenuCreate.bind(this,project,path));}
if(project.canExcludeFolder(path)){contextMenu.defaultSection().appendItem(Common.UIString('Exclude folder'),this._handleContextMenuExclude.bind(this,project,path));}
function removeFolder(){const shouldRemove=window.confirm(Common.UIString('Are you sure you want to remove this folder?'));if(shouldRemove)
project.remove();}
if(project.type()===Workspace.projectTypes.FileSystem){contextMenu.defaultSection().appendAction('sources.add-folder-to-workspace',undefined,true);if(node instanceof Sources.NavigatorGroupTreeNode)
contextMenu.defaultSection().appendItem(Common.UIString('Remove folder from workspace'),removeFolder);}
contextMenu.show();}
rename(node,creatingNewUISourceCode){const uiSourceCode=node.uiSourceCode();node.rename(callback.bind(this));function callback(committed){if(!creatingNewUISourceCode)
return;if(!committed)
uiSourceCode.remove();else if(node._treeElement.listItemElement.hasFocus())
this._sourceSelected(uiSourceCode,true);}}
async create(project,path,uiSourceCodeToCopy){let content='';if(uiSourceCodeToCopy)
content=(await uiSourceCodeToCopy.requestContent())||'';const uiSourceCode=await project.createFile(path,null,content);if(!uiSourceCode)
return;this._sourceSelected(uiSourceCode,false);const node=this.revealUISourceCode(uiSourceCode,true);if(node)
this.rename(node,true);}
_groupingChanged(){this.reset();this._initGrouping();this._workspace.uiSourceCodes().forEach(this._addUISourceCode.bind(this));}
_initGrouping(){this._groupByFrame=true;this._groupByDomain=this._navigatorGroupByFolderSetting.get();this._groupByFolder=this._groupByDomain;}
_resetForTest(){this.reset();this._workspace.uiSourceCodes().forEach(this._addUISourceCode.bind(this));}
_discardFrame(frame){const node=this._frameNodes.get(frame);if(!node)
return;if(node.parent)
node.parent.removeChild(node);this._frameNodes.delete(frame);for(const child of frame.childFrames)
this._discardFrame(child);}
targetAdded(target){}
targetRemoved(target){const targetNode=this._rootNode.child('target:'+target.id());if(targetNode)
this._rootNode.removeChild(targetNode);}
_targetNameChanged(event){const target=(event.data);const targetNode=this._rootNode.child('target:'+target.id());if(targetNode)
targetNode.setTitle(target.name());}};Sources.NavigatorView.Types={Domain:'domain',File:'file',FileSystem:'fs',FileSystemFolder:'fs-folder',Frame:'frame',NetworkFolder:'nw-folder',Root:'root',SourceMapFolder:'sm-folder',Worker:'worker'};Sources.NavigatorFolderTreeElement=class extends UI.TreeElement{constructor(navigatorView,type,title,hoverCallback){super('',true);this.listItemElement.classList.add('navigator-'+type+'-tree-item','navigator-folder-tree-item');this._nodeType=type;this.title=title;this.tooltip=title;this._navigatorView=navigatorView;this._hoverCallback=hoverCallback;let iconType='largeicon-navigator-folder';if(type===Sources.NavigatorView.Types.Domain)
iconType='largeicon-navigator-domain';else if(type===Sources.NavigatorView.Types.Frame)
iconType='largeicon-navigator-frame';else if(type===Sources.NavigatorView.Types.Worker)
iconType='largeicon-navigator-worker';this.setLeadingIcons([UI.Icon.create(iconType,'icon')]);}
onpopulate(){this._node.populate();}
onattach(){this.collapse();this._node.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),false);this.listItemElement.addEventListener('mousemove',this._mouseMove.bind(this),false);this.listItemElement.addEventListener('mouseleave',this._mouseLeave.bind(this),false);}
setNode(node){this._node=node;const paths=[];while(node&&!node.isRoot()){paths.push(node._title);node=node.parent;}
paths.reverse();this.tooltip=paths.join('/');}
_handleContextMenuEvent(event){if(!this._node)
return;this.select();this._navigatorView.handleFolderContextMenu(event,this._node);}
_mouseMove(event){if(this._hovered||!this._hoverCallback)
return;this._hovered=true;this._hoverCallback(true);}
_mouseLeave(event){if(!this._hoverCallback)
return;this._hovered=false;this._hoverCallback(false);}};Sources.NavigatorSourceTreeElement=class extends UI.TreeElement{constructor(navigatorView,uiSourceCode,title,node){super('',false);this._nodeType=Sources.NavigatorView.Types.File;this._node=node;this.title=title;this.listItemElement.classList.add('navigator-'+uiSourceCode.contentType().name()+'-tree-item','navigator-file-tree-item');this.tooltip=uiSourceCode.url();this._navigatorView=navigatorView;this._uiSourceCode=uiSourceCode;this.updateIcon();}
updateIcon(){const binding=Persistence.persistence.binding(this._uiSourceCode);if(binding){const container=createElementWithClass('span','icon-stack');let iconType='largeicon-navigator-file-sync';if(Snippets.isSnippetsUISourceCode(binding.fileSystem))
iconType='largeicon-navigator-snippet';const icon=UI.Icon.create(iconType,'icon');const badge=UI.Icon.create('badge-navigator-file-sync','icon-badge');if(Persistence.networkPersistenceManager.project()===binding.fileSystem.project())
badge.style.filter='hue-rotate(160deg)';container.appendChild(icon);container.appendChild(badge);container.title=Persistence.PersistenceUtils.tooltipForUISourceCode(this._uiSourceCode);this.setLeadingIcons([container]);}else{let iconType='largeicon-navigator-file';if(Snippets.isSnippetsUISourceCode(this._uiSourceCode))
iconType='largeicon-navigator-snippet';const defaultIcon=UI.Icon.create(iconType,'icon');this.setLeadingIcons([defaultIcon]);}}
get uiSourceCode(){return this._uiSourceCode;}
onattach(){this.listItemElement.draggable=true;this.listItemElement.addEventListener('click',this._onclick.bind(this),false);this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),false);this.listItemElement.addEventListener('dragstart',this._ondragstart.bind(this),false);}
_shouldRenameOnMouseDown(){if(!this._uiSourceCode.canRename())
return false;const isSelected=this===this.treeOutline.selectedTreeElement;return isSelected&&this.treeOutline.element.hasFocus()&&!UI.isBeingEdited(this.treeOutline.element);}
selectOnMouseDown(event){if(event.which!==1||!this._shouldRenameOnMouseDown()){super.selectOnMouseDown(event);return;}
setTimeout(rename.bind(this),300);function rename(){if(this._shouldRenameOnMouseDown())
this._navigatorView.rename(this._node,false);}}
_ondragstart(event){event.dataTransfer.setData('text/plain',this._uiSourceCode.url());event.dataTransfer.effectAllowed='copy';}
onspace(){this._navigatorView._sourceSelected(this.uiSourceCode,true);return true;}
_onclick(event){this._navigatorView._sourceSelected(this.uiSourceCode,false);}
ondblclick(event){const middleClick=event.button===1;this._navigatorView._sourceSelected(this.uiSourceCode,!middleClick);return false;}
onenter(){this._navigatorView._sourceSelected(this.uiSourceCode,true);return true;}
ondelete(){return true;}
_handleContextMenuEvent(event){this.select();this._navigatorView.handleFileContextMenu(event,this._node);}};Sources.NavigatorTreeNode=class{constructor(id,type){this.id=id;this._type=type;this._children=new Map();}
treeNode(){throw'Not implemented';}
dispose(){}
isRoot(){return false;}
hasChildren(){return true;}
onattach(){}
setTitle(title){throw'Not implemented';}
populate(){if(this.isPopulated())
return;if(this.parent)
this.parent.populate();this._populated=true;this.wasPopulated();}
wasPopulated(){const children=this.children();for(let i=0;i<children.length;++i)
this.treeNode().appendChild((children[i].treeNode()));}
didAddChild(node){if(this.isPopulated())
this.treeNode().appendChild((node.treeNode()));}
willRemoveChild(node){if(this.isPopulated())
this.treeNode().removeChild((node.treeNode()));}
isPopulated(){return this._populated;}
isEmpty(){return!this._children.size;}
children(){return this._children.valuesArray();}
child(id){return this._children.get(id)||null;}
appendChild(node){this._children.set(node.id,node);node.parent=this;this.didAddChild(node);}
removeChild(node){this.willRemoveChild(node);this._children.remove(node.id);delete node.parent;node.dispose();}
reset(){this._children.clear();}};Sources.NavigatorRootTreeNode=class extends Sources.NavigatorTreeNode{constructor(navigatorView){super('',Sources.NavigatorView.Types.Root);this._navigatorView=navigatorView;}
isRoot(){return true;}
treeNode(){return this._navigatorView._scriptsTree.rootElement();}};Sources.NavigatorUISourceCodeTreeNode=class extends Sources.NavigatorTreeNode{constructor(navigatorView,uiSourceCode,frame){super(uiSourceCode.project().id()+':'+uiSourceCode.url(),Sources.NavigatorView.Types.File);this._navigatorView=navigatorView;this._uiSourceCode=uiSourceCode;this._treeElement=null;this._eventListeners=[];this._frame=frame;}
frame(){return this._frame;}
uiSourceCode(){return this._uiSourceCode;}
treeNode(){if(this._treeElement)
return this._treeElement;this._treeElement=new Sources.NavigatorSourceTreeElement(this._navigatorView,this._uiSourceCode,'',this);this.updateTitle();const updateTitleBound=this.updateTitle.bind(this,undefined);this._eventListeners=[this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.TitleChanged,updateTitleBound),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,updateTitleBound),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,updateTitleBound)];return this._treeElement;}
updateTitle(ignoreIsDirty){if(!this._treeElement)
return;let titleText=this._uiSourceCode.displayName();if(!ignoreIsDirty&&this._uiSourceCode.isDirty())
titleText='*'+titleText;this._treeElement.title=titleText;this._treeElement.updateIcon();let tooltip=this._uiSourceCode.url();if(this._uiSourceCode.contentType().isFromSourceMap())
tooltip=Common.UIString('%s (from source map)',this._uiSourceCode.displayName());this._treeElement.tooltip=tooltip;}
hasChildren(){return false;}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);}
reveal(select){this.parent.populate();this.parent.treeNode().expand();this._treeElement.reveal(true);if(select)
this._treeElement.select(true);}
rename(callback){if(!this._treeElement)
return;this._treeElement.listItemElement.focus();const treeOutlineElement=this._treeElement.treeOutline.element;UI.markBeingEdited(treeOutlineElement,true);function commitHandler(element,newTitle,oldTitle){if(newTitle!==oldTitle){this._treeElement.title=newTitle;this._uiSourceCode.rename(newTitle).then(renameCallback.bind(this));return;}
afterEditing.call(this,true);}
function renameCallback(success){if(!success){UI.markBeingEdited(treeOutlineElement,false);this.updateTitle();this.rename(callback);return;}
afterEditing.call(this,true);}
function afterEditing(committed){UI.markBeingEdited(treeOutlineElement,false);this.updateTitle();if(callback)
callback(committed);}
this.updateTitle(true);this._treeElement.startEditingTitle(new UI.InplaceEditor.Config(commitHandler.bind(this),afterEditing.bind(this,false)));}};Sources.NavigatorFolderTreeNode=class extends Sources.NavigatorTreeNode{constructor(navigatorView,project,id,type,folderPath,title){super(id,type);this._navigatorView=navigatorView;this._project=project;this._folderPath=folderPath;this._title=title;}
treeNode(){if(this._treeElement)
return this._treeElement;this._treeElement=this._createTreeElement(this._title,this);this.updateTitle();return this._treeElement;}
updateTitle(){if(!this._treeElement||this._project.type()!==Workspace.projectTypes.FileSystem)
return;const absoluteFileSystemPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(this._project.id())+'/'+this._folderPath;const hasMappedFiles=Persistence.persistence.filePathHasBindings(absoluteFileSystemPath);this._treeElement.listItemElement.classList.toggle('has-mapped-files',hasMappedFiles);}
_createTreeElement(title,node){if(this._project.type()!==Workspace.projectTypes.FileSystem){try{title=decodeURI(title);}catch(e){}}
const treeElement=new Sources.NavigatorFolderTreeElement(this._navigatorView,this._type,title);treeElement.setNode(node);return treeElement;}
wasPopulated(){if(!this._treeElement||this._treeElement._node!==this)
return;this._addChildrenRecursive();}
_addChildrenRecursive(){const children=this.children();for(let i=0;i<children.length;++i){const child=children[i];this.didAddChild(child);if(child instanceof Sources.NavigatorFolderTreeNode)
child._addChildrenRecursive();}}
_shouldMerge(node){return this._type!==Sources.NavigatorView.Types.Domain&&node instanceof Sources.NavigatorFolderTreeNode;}
didAddChild(node){function titleForNode(node){return node._title;}
if(!this._treeElement)
return;let children=this.children();if(children.length===1&&this._shouldMerge(node)){node._isMerged=true;this._treeElement.title=this._treeElement.title+'/'+node._title;node._treeElement=this._treeElement;this._treeElement.setNode(node);return;}
let oldNode;if(children.length===2)
oldNode=children[0]!==node?children[0]:children[1];if(oldNode&&oldNode._isMerged){delete oldNode._isMerged;const mergedToNodes=[];mergedToNodes.push(this);let treeNode=this;while(treeNode._isMerged){treeNode=treeNode.parent;mergedToNodes.push(treeNode);}
mergedToNodes.reverse();const titleText=mergedToNodes.map(titleForNode).join('/');const nodes=[];treeNode=oldNode;do{nodes.push(treeNode);children=treeNode.children();treeNode=children.length===1?children[0]:null;}while(treeNode&&treeNode._isMerged);if(!this.isPopulated()){this._treeElement.title=titleText;this._treeElement.setNode(this);for(let i=0;i<nodes.length;++i){delete nodes[i]._treeElement;delete nodes[i]._isMerged;}
return;}
const oldTreeElement=this._treeElement;const treeElement=this._createTreeElement(titleText,this);for(let i=0;i<mergedToNodes.length;++i)
mergedToNodes[i]._treeElement=treeElement;oldTreeElement.parent.appendChild(treeElement);oldTreeElement.setNode(nodes[nodes.length-1]);oldTreeElement.title=nodes.map(titleForNode).join('/');oldTreeElement.parent.removeChild(oldTreeElement);this._treeElement.appendChild(oldTreeElement);if(oldTreeElement.expanded)
treeElement.expand();}
if(this.isPopulated())
this._treeElement.appendChild(node.treeNode());}
willRemoveChild(node){if(node._isMerged||!this.isPopulated())
return;this._treeElement.removeChild(node._treeElement);}};Sources.NavigatorGroupTreeNode=class extends Sources.NavigatorTreeNode{constructor(navigatorView,project,id,type,title){super(id,type);this._project=project;this._navigatorView=navigatorView;this._title=title;this.populate();}
setHoverCallback(hoverCallback){this._hoverCallback=hoverCallback;}
treeNode(){if(this._treeElement)
return this._treeElement;this._treeElement=new Sources.NavigatorFolderTreeElement(this._navigatorView,this._type,this._title,this._hoverCallback);this._treeElement.setNode(this);return this._treeElement;}
onattach(){this.updateTitle();}
updateTitle(){if(!this._treeElement||this._project.type()!==Workspace.projectTypes.FileSystem)
return;const fileSystemPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(this._project.id());const wasActive=this._treeElement.listItemElement.classList.contains('has-mapped-files');const isActive=Persistence.persistence.filePathHasBindings(fileSystemPath);if(wasActive===isActive)
return;this._treeElement.listItemElement.classList.toggle('has-mapped-files',isActive);if(this._treeElement.childrenListElement.hasFocus())
return;if(isActive)
this._treeElement.expand();else
this._treeElement.collapse();}
setTitle(title){this._title=title;if(this._treeElement)
this._treeElement.title=this._title;}};;Sources.ScopeChainSidebarPane=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('sources/scopeChainSidebarPane.css');this._expandController=new ObjectUI.ObjectPropertiesSectionExpandController();this._linkifier=new Components.Linkifier();this._update();}
flavorChanged(object){this._update();}
_update(){const callFrame=UI.context.flavor(SDK.DebuggerModel.CallFrame);const details=UI.context.flavor(SDK.DebuggerPausedDetails);this._linkifier.reset();Sources.SourceMapNamesResolver.resolveThisObject(callFrame).then(this._innerUpdate.bind(this,details,callFrame));}
_innerUpdate(details,callFrame,thisObject){this.contentElement.removeChildren();if(!details||!callFrame){const infoElement=createElement('div');infoElement.className='gray-info-message';infoElement.textContent=Common.UIString('Not paused');this.contentElement.appendChild(infoElement);return;}
let foundLocalScope=false;const scopeChain=callFrame.scopeChain();for(let i=0;i<scopeChain.length;++i){const scope=scopeChain[i];let title=scope.typeName();let emptyPlaceholder=null;const extraProperties=[];switch(scope.type()){case Protocol.Debugger.ScopeType.Local:foundLocalScope=true;emptyPlaceholder=Common.UIString('No variables');if(thisObject)
extraProperties.push(new SDK.RemoteObjectProperty('this',thisObject));if(i===0){const exception=details.exception();if(exception){extraProperties.push(new SDK.RemoteObjectProperty(Common.UIString('Exception'),exception,undefined,undefined,undefined,undefined,undefined,true));}
const returnValue=callFrame.returnValue();if(returnValue){extraProperties.push(new SDK.RemoteObjectProperty(Common.UIString('Return value'),returnValue,undefined,undefined,undefined,undefined,undefined,true,callFrame.setReturnValue.bind(callFrame)));}}
break;case Protocol.Debugger.ScopeType.Closure:const scopeName=scope.name();if(scopeName)
title=Common.UIString('Closure (%s)',UI.beautifyFunctionName(scopeName));else
title=Common.UIString('Closure');emptyPlaceholder=Common.UIString('No variables');break;}
let subtitle=scope.description();if(!title||title===subtitle)
subtitle=undefined;const titleElement=createElementWithClass('div','scope-chain-sidebar-pane-section-header');titleElement.createChild('div','scope-chain-sidebar-pane-section-subtitle').textContent=subtitle;titleElement.createChild('div','scope-chain-sidebar-pane-section-title').textContent=title;const section=new ObjectUI.ObjectPropertiesSection(Sources.SourceMapNamesResolver.resolveScopeInObject(scope),titleElement,this._linkifier,emptyPlaceholder,true,extraProperties);this._expandController.watchSection(title+(subtitle?':'+subtitle:''),section);if(scope.type()===Protocol.Debugger.ScopeType.Global)
section.objectTreeElement().collapse();else if(!foundLocalScope||scope.type()===Protocol.Debugger.ScopeType.Local)
section.objectTreeElement().expand();section.element.classList.add('scope-chain-sidebar-pane-section');this.contentElement.appendChild(section.element);}
this._sidebarPaneUpdatedForTest();}
_sidebarPaneUpdatedForTest(){}};Sources.ScopeChainSidebarPane._pathSymbol=Symbol('path');;Sources.NetworkNavigatorView=class extends Sources.NavigatorView{constructor(){super();SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);Host.userMetrics.panelLoaded('sources','DevTools.Launch.Sources');}
acceptProject(project){return project.type()===Workspace.projectTypes.Network;}
_inspectedURLChanged(event){const mainTarget=SDK.targetManager.mainTarget();if(event.data!==mainTarget)
return;const inspectedURL=mainTarget&&mainTarget.inspectedURL();if(!inspectedURL)
return;for(const uiSourceCode of this.workspace().uiSourceCodes()){if(this.acceptProject(uiSourceCode.project())&&uiSourceCode.url()===inspectedURL)
this.revealUISourceCode(uiSourceCode,true);}}
uiSourceCodeAdded(uiSourceCode){const mainTarget=SDK.targetManager.mainTarget();const inspectedURL=mainTarget&&mainTarget.inspectedURL();if(!inspectedURL)
return;if(uiSourceCode.url()===inspectedURL)
this.revealUISourceCode(uiSourceCode,true);}};Sources.FilesNavigatorView=class extends Sources.NavigatorView{constructor(){super();const toolbar=new UI.Toolbar('navigator-toolbar');toolbar.appendItemsAtLocation('files-navigator-toolbar').then(()=>{if(!toolbar.empty())
this.contentElement.insertBefore(toolbar.element,this.contentElement.firstChild);});}
acceptProject(project){return project.type()===Workspace.projectTypes.FileSystem&&Persistence.FileSystemWorkspaceBinding.fileSystemType(project)!=='overrides'&&!Snippets.isSnippetsProject(project);}
handleContextMenu(event){const contextMenu=new UI.ContextMenu(event);contextMenu.defaultSection().appendAction('sources.add-folder-to-workspace',undefined,true);contextMenu.show();}};Sources.OverridesNavigatorView=class extends Sources.NavigatorView{constructor(){super();this._toolbar=new UI.Toolbar('navigator-toolbar');this.contentElement.insertBefore(this._toolbar.element,this.contentElement.lastChild);Persistence.networkPersistenceManager.addEventListener(Persistence.NetworkPersistenceManager.Events.ProjectChanged,this._updateProjectAndUI,this);this.workspace().addEventListener(Workspace.Workspace.Events.ProjectAdded,this._onProjectAddOrRemoved,this);this.workspace().addEventListener(Workspace.Workspace.Events.ProjectRemoved,this._onProjectAddOrRemoved,this);this._updateProjectAndUI();}
_onProjectAddOrRemoved(event){const project=(event.data);if(project&&project.type()===Workspace.projectTypes.FileSystem&&Persistence.FileSystemWorkspaceBinding.fileSystemType(project)!=='overrides')
return;this._updateUI();}
_updateProjectAndUI(){this.reset();const project=Persistence.networkPersistenceManager.project();if(project)
this.tryAddProject(project);this._updateUI();}
_updateUI(){this._toolbar.removeToolbarItems();const project=Persistence.networkPersistenceManager.project();if(project){const enableCheckbox=new UI.ToolbarSettingCheckbox(Common.settings.moduleSetting('persistenceNetworkOverridesEnabled'));this._toolbar.appendToolbarItem(enableCheckbox);this._toolbar.appendToolbarItem(new UI.ToolbarSeparator(true));const clearButton=new UI.ToolbarButton(Common.UIString('Clear configuration'),'largeicon-clear');clearButton.addEventListener(UI.ToolbarButton.Events.Click,()=>{project.remove();});this._toolbar.appendToolbarItem(clearButton);return;}
const title=Common.UIString('Select folder for overrides');const setupButton=new UI.ToolbarButton(title,'largeicon-add',title);setupButton.addEventListener(UI.ToolbarButton.Events.Click,this._setupNewWorkspace,this);this._toolbar.appendToolbarItem(setupButton);}
async _setupNewWorkspace(){const fileSystem=await Persistence.isolatedFileSystemManager.addFileSystem('overrides');if(!fileSystem)
return;Common.settings.moduleSetting('persistenceNetworkOverridesEnabled').set(true);}
acceptProject(project){return project===Persistence.networkPersistenceManager.project();}};Sources.ContentScriptsNavigatorView=class extends Sources.NavigatorView{constructor(){super();}
acceptProject(project){return project.type()===Workspace.projectTypes.ContentScripts;}};Sources.SnippetsNavigatorView=class extends Sources.NavigatorView{constructor(){super();const toolbar=new UI.Toolbar('navigator-toolbar');const newButton=new UI.ToolbarButton('','largeicon-add',Common.UIString('New snippet'));newButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this.create(Snippets.project,''));toolbar.appendToolbarItem(newButton);this.contentElement.insertBefore(toolbar.element,this.contentElement.firstChild);}
acceptProject(project){return Snippets.isSnippetsProject(project);}
handleContextMenu(event){const contextMenu=new UI.ContextMenu(event);contextMenu.headerSection().appendItem(Common.UIString('New'),()=>this.create(Snippets.project,''));contextMenu.show();}
handleFileContextMenu(event,node){const uiSourceCode=node.uiSourceCode();const contextMenu=new UI.ContextMenu(event);contextMenu.headerSection().appendItem(Common.UIString('Run'),()=>Snippets.evaluateScriptSnippet(uiSourceCode));contextMenu.editSection().appendItem(Common.UIString('Rename\u2026'),()=>this.rename(node,false));contextMenu.editSection().appendItem(Common.UIString('Remove'),()=>uiSourceCode.project().deleteFile(uiSourceCode));contextMenu.saveSection().appendItem(Common.UIString('Save as...'),this._handleSaveAs.bind(this,uiSourceCode));contextMenu.show();}
async _handleSaveAs(uiSourceCode){uiSourceCode.commitWorkingCopy();const content=await uiSourceCode.requestContent();Workspace.fileManager.save(uiSourceCode.url(),content,true);Workspace.fileManager.close(uiSourceCode.url());}};Sources.ActionDelegate=class{handleAction(context,actionId){switch(actionId){case'sources.create-snippet':Snippets.project.createFile('',null,'').then(uiSourceCode=>Common.Revealer.reveal(uiSourceCode));return true;case'sources.add-folder-to-workspace':Persistence.isolatedFileSystemManager.addFileSystem();return true;}
return false;}};;Sources.OutlineQuickOpen=class extends QuickOpen.FilteredListWidget.Provider{constructor(){super();this._items=[];this._active=false;}
attach(){this._items=[];this._active=false;const uiSourceCode=this._currentUISourceCode();if(uiSourceCode){this._active=Formatter.formatterWorkerPool().outlineForMimetype(uiSourceCode.workingCopy(),uiSourceCode.contentType().canonicalMimeType(),this._didBuildOutlineChunk.bind(this));}}
_didBuildOutlineChunk(isLastChunk,items){this._items.push(...items);this.refresh();}
itemCount(){return this._items.length;}
itemKeyAt(itemIndex){const item=this._items[itemIndex];return item.title+(item.subtitle?item.subtitle:'');}
itemScoreAt(itemIndex,query){const item=this._items[itemIndex];const methodName=query.split('(')[0];if(methodName.toLowerCase()===item.title.toLowerCase())
return 1/(1+item.line);return-item.line-1;}
renderItem(itemIndex,query,titleElement,subtitleElement){const item=this._items[itemIndex];titleElement.textContent=item.title+(item.subtitle?item.subtitle:'');QuickOpen.FilteredListWidget.highlightRanges(titleElement,query);subtitleElement.textContent=':'+(item.line+1);}
selectItem(itemIndex,promptValue){if(itemIndex===null)
return;const uiSourceCode=this._currentUISourceCode();if(!uiSourceCode)
return;const lineNumber=this._items[itemIndex].line;if(!isNaN(lineNumber)&&lineNumber>=0)
Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber,this._items[itemIndex].column));}
_currentUISourceCode(){const sourcesView=UI.context.flavor(Sources.SourcesView);if(!sourcesView)
return null;return sourcesView.currentUISourceCode();}
notFoundText(){if(!this._currentUISourceCode())
return Common.UIString('No file selected.');if(!this._active)
return Common.UIString('Open a JavaScript or CSS file to see symbols');return Common.UIString('No results found');}};;Sources.TabbedEditorContainerDelegate=function(){};Sources.TabbedEditorContainerDelegate.prototype={viewForFile(uiSourceCode){},recycleUISourceCodeFrame(sourceFrame,uiSourceCode){},};Sources.TabbedEditorContainer=class extends Common.Object{constructor(delegate,setting,placeholderElement){super();this._delegate=delegate;this._tabbedPane=new UI.TabbedPane();this._tabbedPane.setPlaceholderElement(placeholderElement);this._tabbedPane.setTabDelegate(new Sources.EditorContainerTabDelegate(this));this._tabbedPane.setCloseableTabs(true);this._tabbedPane.setAllowTabReorder(true,true);this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabClosed,this._tabClosed,this);this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);Persistence.persistence.addEventListener(Persistence.Persistence.Events.BindingCreated,this._onBindingCreated,this);Persistence.persistence.addEventListener(Persistence.Persistence.Events.BindingRemoved,this._onBindingRemoved,this);this._tabIds=new Map();this._files={};this._previouslyViewedFilesSetting=setting;this._history=Sources.TabbedEditorContainer.History.fromObject(this._previouslyViewedFilesSetting.get());}
_onBindingCreated(event){const binding=(event.data);this._updateFileTitle(binding.fileSystem);const networkTabId=this._tabIds.get(binding.network);let fileSystemTabId=this._tabIds.get(binding.fileSystem);const wasSelectedInNetwork=this._currentFile===binding.network;const currentSelectionRange=this._history.selectionRange(binding.network.url());const currentScrollLineNumber=this._history.scrollLineNumber(binding.network.url());this._history.remove(binding.network.url());if(!networkTabId)
return;if(!fileSystemTabId){const networkView=this._tabbedPane.tabView(networkTabId);const tabIndex=this._tabbedPane.tabIndex(networkTabId);if(networkView instanceof Sources.UISourceCodeFrame){this._delegate.recycleUISourceCodeFrame(networkView,binding.fileSystem);fileSystemTabId=this._appendFileTab(binding.fileSystem,false,tabIndex,networkView);}else{fileSystemTabId=this._appendFileTab(binding.fileSystem,false,tabIndex);const fileSystemTabView=(this._tabbedPane.tabView(fileSystemTabId));this._restoreEditorProperties(fileSystemTabView,currentSelectionRange,currentScrollLineNumber);}}
this._closeTabs([networkTabId],true);if(wasSelectedInNetwork)
this._tabbedPane.selectTab(fileSystemTabId,false);this._updateHistory();}
_onBindingRemoved(event){const binding=(event.data);this._updateFileTitle(binding.fileSystem);}
get view(){return this._tabbedPane;}
get visibleView(){return this._tabbedPane.visibleView;}
fileViews(){return(this._tabbedPane.tabViews());}
leftToolbar(){return this._tabbedPane.leftToolbar();}
rightToolbar(){return this._tabbedPane.rightToolbar();}
show(parentElement){this._tabbedPane.show(parentElement);}
showFile(uiSourceCode){this._innerShowFile(uiSourceCode,true);}
closeFile(uiSourceCode){const tabId=this._tabIds.get(uiSourceCode);if(!tabId)
return;this._closeTabs([tabId]);}
closeAllFiles(){this._closeTabs(this._tabbedPane.tabIds());}
historyUISourceCodes(){const uriToUISourceCode={};for(const id in this._files){const uiSourceCode=this._files[id];uriToUISourceCode[uiSourceCode.url()]=uiSourceCode;}
const result=[];const uris=this._history._urls();for(let i=0;i<uris.length;++i){const uiSourceCode=uriToUISourceCode[uris[i]];if(uiSourceCode)
result.push(uiSourceCode);}
return result;}
_addViewListeners(){if(!this._currentView||!this._currentView.textEditor)
return;this._currentView.textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.ScrollChanged,this._scrollChanged,this);this._currentView.textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.SelectionChanged,this._selectionChanged,this);}
_removeViewListeners(){if(!this._currentView||!this._currentView.textEditor)
return;this._currentView.textEditor.removeEventListener(SourceFrame.SourcesTextEditor.Events.ScrollChanged,this._scrollChanged,this);this._currentView.textEditor.removeEventListener(SourceFrame.SourcesTextEditor.Events.SelectionChanged,this._selectionChanged,this);}
_scrollChanged(event){if(this._scrollTimer)
clearTimeout(this._scrollTimer);const lineNumber=(event.data);this._scrollTimer=setTimeout(saveHistory.bind(this),100);this._history.updateScrollLineNumber(this._currentFile.url(),lineNumber);function saveHistory(){this._history.save(this._previouslyViewedFilesSetting);}}
_selectionChanged(event){const range=(event.data);this._history.updateSelectionRange(this._currentFile.url(),range);this._history.save(this._previouslyViewedFilesSetting);Extensions.extensionServer.sourceSelectionChanged(this._currentFile.url(),range);}
_innerShowFile(uiSourceCode,userGesture){const binding=Persistence.persistence.binding(uiSourceCode);uiSourceCode=binding?binding.fileSystem:uiSourceCode;if(this._currentFile===uiSourceCode)
return;this._removeViewListeners();this._currentFile=uiSourceCode;const tabId=this._tabIds.get(uiSourceCode)||this._appendFileTab(uiSourceCode,userGesture);this._tabbedPane.selectTab(tabId,userGesture);if(userGesture)
this._editorSelectedByUserAction();const previousView=this._currentView;this._currentView=this.visibleView;this._addViewListeners();const eventData={currentFile:this._currentFile,currentView:this._currentView,previousView:previousView,userGesture:userGesture};this.dispatchEventToListeners(Sources.TabbedEditorContainer.Events.EditorSelected,eventData);}
_titleForFile(uiSourceCode){const maxDisplayNameLength=30;let title=uiSourceCode.displayName(true).trimMiddle(maxDisplayNameLength);if(uiSourceCode.isDirty())
title+='*';return title;}
_maybeCloseTab(id,nextTabId){const uiSourceCode=this._files[id];const shouldPrompt=uiSourceCode.isDirty()&&uiSourceCode.project().canSetFileContent();if(!shouldPrompt||confirm(Common.UIString('Are you sure you want to close unsaved file: %s?',uiSourceCode.name()))){uiSourceCode.resetWorkingCopy();if(nextTabId)
this._tabbedPane.selectTab(nextTabId,true);this._tabbedPane.closeTab(id,true);return true;}
return false;}
_closeTabs(ids,forceCloseDirtyTabs){const dirtyTabs=[];const cleanTabs=[];for(let i=0;i<ids.length;++i){const id=ids[i];const uiSourceCode=this._files[id];if(!forceCloseDirtyTabs&&uiSourceCode.isDirty())
dirtyTabs.push(id);else
cleanTabs.push(id);}
if(dirtyTabs.length)
this._tabbedPane.selectTab(dirtyTabs[0],true);this._tabbedPane.closeTabs(cleanTabs,true);for(let i=0;i<dirtyTabs.length;++i){const nextTabId=i+1<dirtyTabs.length?dirtyTabs[i+1]:null;if(!this._maybeCloseTab(dirtyTabs[i],nextTabId))
break;}}
_onContextMenu(tabId,contextMenu){const uiSourceCode=this._files[tabId];if(uiSourceCode)
contextMenu.appendApplicableItems(uiSourceCode);}
addUISourceCode(uiSourceCode){const binding=Persistence.persistence.binding(uiSourceCode);uiSourceCode=binding?binding.fileSystem:uiSourceCode;if(this._currentFile===uiSourceCode)
return;const uri=uiSourceCode.url();const index=this._history.index(uri);if(index===-1)
return;if(!this._tabIds.has(uiSourceCode))
this._appendFileTab(uiSourceCode,false);if(!index){this._innerShowFile(uiSourceCode,false);return;}
if(!this._currentFile)
return;const currentProjectIsSnippets=Snippets.isSnippetsUISourceCode(this._currentFile);const addedProjectIsSnippets=Snippets.isSnippetsUISourceCode(uiSourceCode);if(this._history.index(this._currentFile.url())&&currentProjectIsSnippets&&!addedProjectIsSnippets)
this._innerShowFile(uiSourceCode,false);}
removeUISourceCode(uiSourceCode){this.removeUISourceCodes([uiSourceCode]);}
removeUISourceCodes(uiSourceCodes){const tabIds=[];for(let i=0;i<uiSourceCodes.length;++i){const uiSourceCode=uiSourceCodes[i];const tabId=this._tabIds.get(uiSourceCode);if(tabId)
tabIds.push(tabId);}
this._tabbedPane.closeTabs(tabIds);}
_editorClosedByUserAction(uiSourceCode){this._history.remove(uiSourceCode.url());this._updateHistory();}
_editorSelectedByUserAction(){this._updateHistory();}
_updateHistory(){const tabIds=this._tabbedPane.lastOpenedTabIds(Sources.TabbedEditorContainer.maximalPreviouslyViewedFilesCount);function tabIdToURI(tabId){return this._files[tabId].url();}
this._history.update(tabIds.map(tabIdToURI.bind(this)));this._history.save(this._previouslyViewedFilesSetting);}
_tooltipForFile(uiSourceCode){uiSourceCode=Persistence.persistence.network(uiSourceCode)||uiSourceCode;return uiSourceCode.url();}
_appendFileTab(uiSourceCode,userGesture,index,replaceView){const view=replaceView||this._delegate.viewForFile(uiSourceCode);const title=this._titleForFile(uiSourceCode);const tooltip=this._tooltipForFile(uiSourceCode);const tabId=this._generateTabId();this._tabIds.set(uiSourceCode,tabId);this._files[tabId]=uiSourceCode;if(!replaceView){const savedSelectionRange=this._history.selectionRange(uiSourceCode.url());const savedScrollLineNumber=this._history.scrollLineNumber(uiSourceCode.url());this._restoreEditorProperties(view,savedSelectionRange,savedScrollLineNumber);}
this._tabbedPane.appendTab(tabId,title,view,tooltip,userGesture,undefined,index);this._updateFileTitle(uiSourceCode);this._addUISourceCodeListeners(uiSourceCode);return tabId;}
_restoreEditorProperties(editorView,selection,firstLineNumber){const sourceFrame=editorView instanceof SourceFrame.SourceFrame?(editorView):null;if(!sourceFrame)
return;if(selection)
sourceFrame.setSelection(selection);if(typeof firstLineNumber==='number')
sourceFrame.scrollToLine(firstLineNumber);}
_tabClosed(event){const tabId=(event.data.tabId);const userGesture=(event.data.isUserGesture);const uiSourceCode=this._files[tabId];if(this._currentFile===uiSourceCode){this._removeViewListeners();delete this._currentView;delete this._currentFile;}
this._tabIds.remove(uiSourceCode);delete this._files[tabId];this._removeUISourceCodeListeners(uiSourceCode);this.dispatchEventToListeners(Sources.TabbedEditorContainer.Events.EditorClosed,uiSourceCode);if(userGesture)
this._editorClosedByUserAction(uiSourceCode);}
_tabSelected(event){const tabId=(event.data.tabId);const userGesture=(event.data.isUserGesture);const uiSourceCode=this._files[tabId];this._innerShowFile(uiSourceCode,userGesture);}
_addUISourceCodeListeners(uiSourceCode){uiSourceCode.addEventListener(Workspace.UISourceCode.Events.TitleChanged,this._uiSourceCodeTitleChanged,this);uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._uiSourceCodeWorkingCopyChanged,this);uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._uiSourceCodeWorkingCopyCommitted,this);}
_removeUISourceCodeListeners(uiSourceCode){uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.TitleChanged,this._uiSourceCodeTitleChanged,this);uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._uiSourceCodeWorkingCopyChanged,this);uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._uiSourceCodeWorkingCopyCommitted,this);}
_updateFileTitle(uiSourceCode){const tabId=this._tabIds.get(uiSourceCode);if(tabId){const title=this._titleForFile(uiSourceCode);this._tabbedPane.changeTabTitle(tabId,title);let icon=null;if(Persistence.persistence.hasUnsavedCommittedChanges(uiSourceCode)){icon=UI.Icon.create('smallicon-warning');icon.title=Common.UIString('Changes to this file were not saved to file system.');}else{icon=Persistence.PersistenceUtils.iconForUISourceCode(uiSourceCode);}
this._tabbedPane.setTabIcon(tabId,icon);}}
_uiSourceCodeTitleChanged(event){const uiSourceCode=(event.data);this._updateFileTitle(uiSourceCode);this._updateHistory();}
_uiSourceCodeWorkingCopyChanged(event){const uiSourceCode=(event.data);this._updateFileTitle(uiSourceCode);}
_uiSourceCodeWorkingCopyCommitted(event){const uiSourceCode=(event.data.uiSourceCode);this._updateFileTitle(uiSourceCode);}
_generateTabId(){return'tab_'+(Sources.TabbedEditorContainer._tabId++);}
currentFile(){return this._currentFile||null;}};Sources.TabbedEditorContainer.Events={EditorSelected:Symbol('EditorSelected'),EditorClosed:Symbol('EditorClosed')};Sources.TabbedEditorContainer._tabId=0;Sources.TabbedEditorContainer.maximalPreviouslyViewedFilesCount=30;Sources.TabbedEditorContainer.HistoryItem=class{constructor(url,selectionRange,scrollLineNumber){this.url=url;this._isSerializable=url.length<Sources.TabbedEditorContainer.HistoryItem.serializableUrlLengthLimit;this.selectionRange=selectionRange;this.scrollLineNumber=scrollLineNumber;}
static fromObject(serializedHistoryItem){const selectionRange=serializedHistoryItem.selectionRange?TextUtils.TextRange.fromObject(serializedHistoryItem.selectionRange):undefined;return new Sources.TabbedEditorContainer.HistoryItem(serializedHistoryItem.url,selectionRange,serializedHistoryItem.scrollLineNumber);}
serializeToObject(){if(!this._isSerializable)
return null;const serializedHistoryItem={};serializedHistoryItem.url=this.url;serializedHistoryItem.selectionRange=this.selectionRange;serializedHistoryItem.scrollLineNumber=this.scrollLineNumber;return serializedHistoryItem;}};Sources.TabbedEditorContainer.HistoryItem.serializableUrlLengthLimit=4096;Sources.TabbedEditorContainer.History=class{constructor(items){this._items=items;this._rebuildItemIndex();}
static fromObject(serializedHistory){const items=[];for(let i=0;i<serializedHistory.length;++i)
items.push(Sources.TabbedEditorContainer.HistoryItem.fromObject(serializedHistory[i]));return new Sources.TabbedEditorContainer.History(items);}
index(url){return this._itemsIndex.has(url)?(this._itemsIndex.get(url)):-1;}
_rebuildItemIndex(){this._itemsIndex=new Map();for(let i=0;i<this._items.length;++i){console.assert(!this._itemsIndex.has(this._items[i].url));this._itemsIndex.set(this._items[i].url,i);}}
selectionRange(url){const index=this.index(url);return index!==-1?this._items[index].selectionRange:undefined;}
updateSelectionRange(url,selectionRange){if(!selectionRange)
return;const index=this.index(url);if(index===-1)
return;this._items[index].selectionRange=selectionRange;}
scrollLineNumber(url){const index=this.index(url);return index!==-1?this._items[index].scrollLineNumber:undefined;}
updateScrollLineNumber(url,scrollLineNumber){const index=this.index(url);if(index===-1)
return;this._items[index].scrollLineNumber=scrollLineNumber;}
update(urls){for(let i=urls.length-1;i>=0;--i){const index=this.index(urls[i]);let item;if(index!==-1){item=this._items[index];this._items.splice(index,1);}else{item=new Sources.TabbedEditorContainer.HistoryItem(urls[i]);}
this._items.unshift(item);this._rebuildItemIndex();}}
remove(url){const index=this.index(url);if(index!==-1){this._items.splice(index,1);this._rebuildItemIndex();}}
save(setting){setting.set(this._serializeToObject());}
_serializeToObject(){const serializedHistory=[];for(let i=0;i<this._items.length;++i){const serializedItem=this._items[i].serializeToObject();if(serializedItem)
serializedHistory.push(serializedItem);if(serializedHistory.length===Sources.TabbedEditorContainer.maximalPreviouslyViewedFilesCount)
break;}
return serializedHistory;}
_urls(){const result=[];for(let i=0;i<this._items.length;++i)
result.push(this._items[i].url);return result;}};Sources.EditorContainerTabDelegate=class{constructor(editorContainer){this._editorContainer=editorContainer;}
closeTabs(tabbedPane,ids){this._editorContainer._closeTabs(ids);}
onContextMenu(tabId,contextMenu){this._editorContainer._onContextMenu(tabId,contextMenu);}};;Sources.WatchExpressionsSidebarPane=class extends UI.ThrottledWidget{constructor(){super(true);this.registerRequiredCSS('object_ui/objectValue.css');this.registerRequiredCSS('sources/watchExpressionsSidebarPane.css');this._watchExpressions=[];this._watchExpressionsSetting=Common.settings.createLocalSetting('watchExpressions',[]);this._addButton=new UI.ToolbarButton(Common.UIString('Add expression'),'largeicon-add');this._addButton.addEventListener(UI.ToolbarButton.Events.Click,this._addButtonClicked.bind(this));this._refreshButton=new UI.ToolbarButton(Common.UIString('Refresh'),'largeicon-refresh');this._refreshButton.addEventListener(UI.ToolbarButton.Events.Click,this.update,this);this.contentElement.classList.add('watch-expressions');this.contentElement.addEventListener('contextmenu',this._contextMenu.bind(this),false);this._expandController=new ObjectUI.ObjectPropertiesSectionExpandController();UI.context.addFlavorChangeListener(SDK.ExecutionContext,this.update,this);UI.context.addFlavorChangeListener(SDK.DebuggerModel.CallFrame,this.update,this);this._linkifier=new Components.Linkifier();this.update();}
toolbarItems(){return[this._addButton,this._refreshButton];}
hasExpressions(){return!!this._watchExpressionsSetting.get().length;}
_saveExpressions(){const toSave=[];for(let i=0;i<this._watchExpressions.length;i++){if(this._watchExpressions[i].expression())
toSave.push(this._watchExpressions[i].expression());}
this._watchExpressionsSetting.set(toSave);}
async _addButtonClicked(){await UI.viewManager.showView('sources.watch');this._createWatchExpression(null).startEditing();}
doUpdate(){this._linkifier.reset();this.contentElement.removeChildren();this._watchExpressions=[];this._emptyElement=this.contentElement.createChild('div','gray-info-message');this._emptyElement.textContent=Common.UIString('No watch expressions');const watchExpressionStrings=this._watchExpressionsSetting.get();for(let i=0;i<watchExpressionStrings.length;++i){const expression=watchExpressionStrings[i];if(!expression)
continue;this._createWatchExpression(expression);}
return Promise.resolve();}
_createWatchExpression(expression){this._emptyElement.classList.add('hidden');const watchExpression=new Sources.WatchExpression(expression,this._expandController,this._linkifier);watchExpression.addEventListener(Sources.WatchExpression.Events.ExpressionUpdated,this._watchExpressionUpdated,this);this.contentElement.appendChild(watchExpression.element());this._watchExpressions.push(watchExpression);return watchExpression;}
_watchExpressionUpdated(event){const watchExpression=(event.data);if(!watchExpression.expression()){this._watchExpressions.remove(watchExpression);this.contentElement.removeChild(watchExpression.element());this._emptyElement.classList.toggle('hidden',!!this._watchExpressions.length);}
this._saveExpressions();}
_contextMenu(event){const contextMenu=new UI.ContextMenu(event);this._populateContextMenu(contextMenu,event);contextMenu.show();}
_populateContextMenu(contextMenu,event){let isEditing=false;for(const watchExpression of this._watchExpressions)
isEditing|=watchExpression.isEditing();if(!isEditing)
contextMenu.debugSection().appendItem(Common.UIString('Add watch expression'),this._addButtonClicked.bind(this));if(this._watchExpressions.length>1){contextMenu.debugSection().appendItem(Common.UIString('Delete all watch expressions'),this._deleteAllButtonClicked.bind(this));}
const target=event.deepElementFromPoint();if(!target)
return;for(const watchExpression of this._watchExpressions){if(watchExpression.element().isSelfOrAncestor(target))
watchExpression._populateContextMenu(contextMenu,event);}}
_deleteAllButtonClicked(){this._watchExpressions=[];this._saveExpressions();this.update();}
_focusAndAddExpressionToWatch(expression){UI.viewManager.showView('sources.watch');this.doUpdate();this._addExpressionToWatch(expression);}
_addExpressionToWatch(expression){this._createWatchExpression(expression);this._saveExpressions();}
handleAction(context,actionId){const frame=UI.context.flavor(Sources.UISourceCodeFrame);if(!frame)
return false;const text=frame.textEditor.text(frame.textEditor.selection());this._focusAndAddExpressionToWatch(text);return true;}
_addPropertyPathToWatch(target){this._addExpressionToWatch(target.path());}
appendApplicableItems(event,contextMenu,target){if(target instanceof ObjectUI.ObjectPropertyTreeElement&&!target.property.synthetic){contextMenu.debugSection().appendItem(ls`Add property path to watch`,this._addPropertyPathToWatch.bind(this,target));}
const frame=UI.context.flavor(Sources.UISourceCodeFrame);if(!frame||frame.textEditor.selection().isEmpty())
return;contextMenu.debugSection().appendAction('sources.add-to-watch');}};Sources.WatchExpression=class extends Common.Object{constructor(expression,expandController,linkifier){super();this._expression=expression;this._expandController=expandController;this._element=createElementWithClass('div','watch-expression monospace');this._editing=false;this._linkifier=linkifier;this._createWatchExpression();this.update();}
element(){return this._element;}
expression(){return this._expression;}
update(){const currentExecutionContext=UI.context.flavor(SDK.ExecutionContext);if(currentExecutionContext&&this._expression){currentExecutionContext.evaluate({expression:this._expression,objectGroup:Sources.WatchExpression._watchObjectGroupId,includeCommandLineAPI:false,silent:true,returnByValue:false,generatePreview:false},false,false).then(result=>this._createWatchExpression(result.object,result.exceptionDetails));}}
startEditing(){this._editing=true;this._element.removeChild(this._objectPresentationElement);const newDiv=this._element.createChild('div');newDiv.textContent=this._nameElement.textContent;this._textPrompt=new ObjectUI.ObjectPropertyPrompt();this._textPrompt.renderAsBlock();const proxyElement=this._textPrompt.attachAndStartEditing(newDiv,this._finishEditing.bind(this));proxyElement.classList.add('watch-expression-text-prompt-proxy');proxyElement.addEventListener('keydown',this._promptKeyDown.bind(this),false);this._element.getComponentSelection().selectAllChildren(newDiv);}
isEditing(){return!!this._editing;}
_finishEditing(event,canceled){if(event)
event.consume(canceled);this._editing=false;this._textPrompt.detach();const newExpression=canceled?this._expression:this._textPrompt.text();delete this._textPrompt;this._element.removeChildren();this._element.appendChild(this._objectPresentationElement);this._updateExpression(newExpression);}
_dblClickOnWatchExpression(event){event.consume();if(!this.isEditing())
this.startEditing();}
_updateExpression(newExpression){if(this._expression)
this._expandController.stopWatchSectionsWithId(this._expression);this._expression=newExpression;this.update();this.dispatchEventToListeners(Sources.WatchExpression.Events.ExpressionUpdated,this);}
_deleteWatchExpression(event){event.consume(true);this._updateExpression(null);}
_createWatchExpression(result,exceptionDetails){this._result=result||null;const headerElement=createElementWithClass('div','watch-expression-header');const deleteButton=UI.Icon.create('smallicon-cross','watch-expression-delete-button');deleteButton.title=ls`Delete watch expression`;deleteButton.addEventListener('click',this._deleteWatchExpression.bind(this),false);headerElement.appendChild(deleteButton);const titleElement=headerElement.createChild('div','watch-expression-title');this._nameElement=ObjectUI.ObjectPropertiesSection.createNameElement(this._expression);if(!!exceptionDetails||!result){this._valueElement=createElementWithClass('span','watch-expression-error value');titleElement.classList.add('dimmed');this._valueElement.textContent=Common.UIString('<not available>');}else{this._valueElement=ObjectUI.ObjectPropertiesSection.createValueElementWithCustomSupport(result,!!exceptionDetails,false,titleElement,this._linkifier);}
const separatorElement=createElementWithClass('span','watch-expressions-separator');separatorElement.textContent=': ';titleElement.appendChildren(this._nameElement,separatorElement,this._valueElement);this._element.removeChildren();this._objectPropertiesSection=null;if(!exceptionDetails&&result&&result.hasChildren&&!result.customPreview()){headerElement.classList.add('watch-expression-object-header');this._objectPropertiesSection=new ObjectUI.ObjectPropertiesSection(result,headerElement,this._linkifier);this._objectPresentationElement=this._objectPropertiesSection.element;this._objectPresentationElement.classList.add('watch-expression-object');this._expandController.watchSection((this._expression),this._objectPropertiesSection);const objectTreeElement=this._objectPropertiesSection.objectTreeElement();objectTreeElement.toggleOnClick=false;objectTreeElement.listItemElement.addEventListener('click',this._onSectionClick.bind(this),false);objectTreeElement.listItemElement.addEventListener('dblclick',this._dblClickOnWatchExpression.bind(this));}else{this._objectPresentationElement=headerElement;this._objectPresentationElement.addEventListener('dblclick',this._dblClickOnWatchExpression.bind(this));}
this._element.appendChild(this._objectPresentationElement);}
_onSectionClick(event){event.consume(true);if(event.detail===1){this._preventClickTimeout=setTimeout(handleClick.bind(this),333);}else{clearTimeout(this._preventClickTimeout);delete this._preventClickTimeout;}
function handleClick(){if(!this._objectPropertiesSection)
return;const objectTreeElement=this._objectPropertiesSection.objectTreeElement();if(objectTreeElement.expanded)
objectTreeElement.collapse();else
objectTreeElement.expand();}}
_promptKeyDown(event){if(isEnterKey(event)||isEscKey(event))
this._finishEditing(event,isEscKey(event));}
_populateContextMenu(contextMenu,event){if(!this.isEditing()){contextMenu.editSection().appendItem(Common.UIString('Delete watch expression'),this._updateExpression.bind(this,null));}
if(!this.isEditing()&&this._result&&(this._result.type==='number'||this._result.type==='string'))
contextMenu.clipboardSection().appendItem(Common.UIString('Copy value'),this._copyValueButtonClicked.bind(this));const target=event.deepElementFromPoint();if(target&&this._valueElement.isSelfOrAncestor(target))
contextMenu.appendApplicableItems(this._result);}
_copyValueButtonClicked(){InspectorFrontendHost.copyText(this._valueElement.textContent);}};Sources.WatchExpression._watchObjectGroupId='watch-group';Sources.WatchExpression.Events={ExpressionUpdated:Symbol('ExpressionUpdated')};;Sources.ThreadsSidebarPane=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('sources/threadsSidebarPane.css');this._items=new UI.ListModel();this._list=new UI.ListControl(this._items,this,UI.ListMode.NonViewport);this.contentElement.appendChild(this._list.element);UI.context.addFlavorChangeListener(SDK.Target,this._targetFlavorChanged,this);SDK.targetManager.observeModels(SDK.DebuggerModel,this);}
static shouldBeShown(){return SDK.targetManager.models(SDK.DebuggerModel).length>=2;}
createElementForItem(debuggerModel){const element=createElementWithClass('div','thread-item');const title=element.createChild('div','thread-item-title');const pausedState=element.createChild('div','thread-item-paused-state');element.appendChild(UI.Icon.create('smallicon-thick-right-arrow','selected-thread-icon'));function updateTitle(){const executionContext=debuggerModel.runtimeModel().defaultExecutionContext();title.textContent=executionContext&&executionContext.label()?executionContext.label():debuggerModel.target().name();}
function updatePausedState(){pausedState.textContent=debuggerModel.isPaused()?ls`paused`:'';}
function targetNameChanged(event){const target=(event.data);if(target===debuggerModel.target())
updateTitle();}
debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerPaused,updatePausedState);debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerResumed,updatePausedState);debuggerModel.runtimeModel().addEventListener(SDK.RuntimeModel.Events.ExecutionContextChanged,updateTitle);SDK.targetManager.addEventListener(SDK.TargetManager.Events.NameChanged,targetNameChanged);updatePausedState();updateTitle();return element;}
heightForItem(debuggerModel){console.assert(false);return 0;}
isItemSelectable(debuggerModel){return true;}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('selected');if(toElement)
toElement.classList.add('selected');if(to)
UI.context.setFlavor(SDK.Target,to.target());}
modelAdded(debuggerModel){this._items.insert(this._items.length,debuggerModel);const currentTarget=UI.context.flavor(SDK.Target);if(currentTarget===debuggerModel.target())
this._list.selectItem(debuggerModel);}
modelRemoved(debuggerModel){this._items.remove(this._items.indexOf(debuggerModel));}
_targetFlavorChanged(event){const target=(event.data);const debuggerModel=target.model(SDK.DebuggerModel);if(debuggerModel)
this._list.selectItem(debuggerModel);}};;Sources.ScriptFormatterEditorAction=class{constructor(){this._pathsToFormatOnLoad=new Set();}
_editorSelected(event){const uiSourceCode=(event.data);this._updateButton(uiSourceCode);if(this._isFormatableScript(uiSourceCode)&&this._pathsToFormatOnLoad.has(uiSourceCode.url())&&!Sources.sourceFormatter.hasFormatted(uiSourceCode))
this._showFormatted(uiSourceCode);}
_editorClosed(event){const uiSourceCode=(event.data.uiSourceCode);const wasSelected=(event.data.wasSelected);if(wasSelected)
this._updateButton(null);const original=Sources.sourceFormatter.discardFormattedUISourceCode(uiSourceCode);if(original)
this._pathsToFormatOnLoad.delete(original.url());}
_updateButton(uiSourceCode){this._button.element.classList.toggle('hidden',!this._isFormatableScript(uiSourceCode));}
button(sourcesView){if(this._button)
return this._button;this._sourcesView=sourcesView;this._sourcesView.addEventListener(Sources.SourcesView.Events.EditorSelected,this._editorSelected.bind(this));this._sourcesView.addEventListener(Sources.SourcesView.Events.EditorClosed,this._editorClosed.bind(this));this._button=new UI.ToolbarButton(Common.UIString('Pretty print'),'largeicon-pretty-print');this._button.addEventListener(UI.ToolbarButton.Events.Click,this._toggleFormatScriptSource,this);this._updateButton(sourcesView.currentUISourceCode());return this._button;}
_isFormatableScript(uiSourceCode){if(!uiSourceCode)
return false;if(uiSourceCode.project().canSetFileContent())
return false;if(uiSourceCode.project().type()===Workspace.projectTypes.Formatter)
return false;if(Persistence.persistence.binding(uiSourceCode))
return false;return uiSourceCode.contentType().hasScripts();}
_toggleFormatScriptSource(event){const uiSourceCode=this._sourcesView.currentUISourceCode();if(!this._isFormatableScript(uiSourceCode))
return;this._pathsToFormatOnLoad.add(uiSourceCode.url());this._showFormatted(uiSourceCode);}
async _showFormatted(uiSourceCode){const formatData=await Sources.sourceFormatter.format(uiSourceCode);if(uiSourceCode!==this._sourcesView.currentUISourceCode())
return;const sourceFrame=this._sourcesView.viewForFile(uiSourceCode);let start=[0,0];if(sourceFrame){const selection=sourceFrame.selection();start=formatData.mapping.originalToFormatted(selection.startLine,selection.startColumn);}
this._sourcesView.showSourceLocation(formatData.formattedSourceCode,start[0],start[1]);}};;Sources.InplaceFormatterEditorAction=class{_editorSelected(event){const uiSourceCode=(event.data);this._updateButton(uiSourceCode);}
_editorClosed(event){const wasSelected=(event.data.wasSelected);if(wasSelected)
this._updateButton(null);}
_updateButton(uiSourceCode){this._button.element.classList.toggle('hidden',!this._isFormattable(uiSourceCode));}
button(sourcesView){if(this._button)
return this._button;this._sourcesView=sourcesView;this._sourcesView.addEventListener(Sources.SourcesView.Events.EditorSelected,this._editorSelected.bind(this));this._sourcesView.addEventListener(Sources.SourcesView.Events.EditorClosed,this._editorClosed.bind(this));this._button=new UI.ToolbarButton(Common.UIString('Format'),'largeicon-pretty-print');this._button.addEventListener(UI.ToolbarButton.Events.Click,this._formatSourceInPlace,this);this._updateButton(sourcesView.currentUISourceCode());return this._button;}
_isFormattable(uiSourceCode){if(!uiSourceCode)
return false;if(uiSourceCode.project().canSetFileContent())
return true;if(Persistence.persistence.binding(uiSourceCode))
return true;return uiSourceCode.contentType().isStyleSheet();}
_formatSourceInPlace(event){const uiSourceCode=this._sourcesView.currentUISourceCode();if(!this._isFormattable(uiSourceCode))
return;if(uiSourceCode.isDirty())
contentLoaded.call(this,uiSourceCode.workingCopy());else
uiSourceCode.requestContent().then(contentLoaded.bind(this));function contentLoaded(content){const highlighterType=uiSourceCode.mimeType();Formatter.Formatter.format(uiSourceCode.contentType(),highlighterType,content||'',innerCallback.bind(this));}
function innerCallback(formattedContent,formatterMapping){if(uiSourceCode.workingCopy()===formattedContent)
return;const sourceFrame=this._sourcesView.viewForFile(uiSourceCode);let start=[0,0];if(sourceFrame){const selection=sourceFrame.selection();start=formatterMapping.originalToFormatted(selection.startLine,selection.startColumn);}
uiSourceCode.setWorkingCopy(formattedContent);this._sourcesView.showSourceLocation(uiSourceCode,start[0],start[1]);}}};;Sources.SourceFormatData=class{constructor(originalSourceCode,formattedSourceCode,mapping){this.originalSourceCode=originalSourceCode;this.formattedSourceCode=formattedSourceCode;this.mapping=mapping;}
originalPath(){return this.originalSourceCode.project().id()+':'+this.originalSourceCode.url();}
static _for(object){return object[Sources.SourceFormatData._formatDataSymbol];}};Sources.SourceFormatData._formatDataSymbol=Symbol('formatData');Sources.SourceFormatter=class{constructor(){this._projectId='formatter:';this._project=new Bindings.ContentProviderBasedProject(Workspace.workspace,this._projectId,Workspace.projectTypes.Formatter,'formatter',true);this._formattedSourceCodes=new Map();this._scriptMapping=new Sources.SourceFormatter.ScriptMapping();this._styleMapping=new Sources.SourceFormatter.StyleMapping();Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this._onUISourceCodeRemoved,this);}
_onUISourceCodeRemoved(event){const uiSourceCode=(event.data);const cacheEntry=this._formattedSourceCodes.get(uiSourceCode);if(cacheEntry&&cacheEntry.formatData)
this._discardFormatData(cacheEntry.formatData);this._formattedSourceCodes.remove(uiSourceCode);}
discardFormattedUISourceCode(formattedUISourceCode){const formatData=Sources.SourceFormatData._for(formattedUISourceCode);if(!formatData)
return null;this._discardFormatData(formatData);this._formattedSourceCodes.remove(formatData.originalSourceCode);return formatData.originalSourceCode;}
_discardFormatData(formatData){delete formatData.formattedSourceCode[Sources.SourceFormatData._formatDataSymbol];this._scriptMapping._setSourceMappingEnabled(formatData,false);this._styleMapping._setSourceMappingEnabled(formatData,false);this._project.removeFile(formatData.formattedSourceCode.url());}
hasFormatted(uiSourceCode){return this._formattedSourceCodes.has(uiSourceCode);}
async format(uiSourceCode){const cacheEntry=this._formattedSourceCodes.get(uiSourceCode);if(cacheEntry)
return cacheEntry.promise;let fulfillFormatPromise;const resultPromise=new Promise(fulfill=>{fulfillFormatPromise=fulfill;});this._formattedSourceCodes.set(uiSourceCode,{promise:resultPromise,formatData:null});const content=await uiSourceCode.requestContent();Formatter.Formatter.format(uiSourceCode.contentType(),uiSourceCode.mimeType(),content||'',formatDone.bind(this));return resultPromise;function formatDone(formattedContent,formatterMapping){const cacheEntry=this._formattedSourceCodes.get(uiSourceCode);if(!cacheEntry||cacheEntry.promise!==resultPromise)
return;let formattedURL;let count=0;let suffix='';do{formattedURL=`${uiSourceCode.url()}:formatted${suffix}`;suffix=`:${count++}`;}while(this._project.uiSourceCodeForURL(formattedURL));const contentProvider=Common.StaticContentProvider.fromString(formattedURL,uiSourceCode.contentType(),formattedContent);const formattedUISourceCode=this._project.addContentProvider(formattedURL,contentProvider,uiSourceCode.mimeType());const formatData=new Sources.SourceFormatData(uiSourceCode,formattedUISourceCode,formatterMapping);formattedUISourceCode[Sources.SourceFormatData._formatDataSymbol]=formatData;this._scriptMapping._setSourceMappingEnabled(formatData,true);this._styleMapping._setSourceMappingEnabled(formatData,true);cacheEntry.formatData=formatData;for(const decoration of uiSourceCode.allDecorations()){const range=decoration.range();const startLocation=formatterMapping.originalToFormatted(range.startLine,range.startColumn);const endLocation=formatterMapping.originalToFormatted(range.endLine,range.endColumn);formattedUISourceCode.addDecoration(new TextUtils.TextRange(startLocation[0],startLocation[1],endLocation[0],endLocation[1]),(decoration.type()),decoration.data());}
fulfillFormatPromise(formatData);}}};Sources.SourceFormatter.ScriptMapping=class{constructor(){Bindings.debuggerWorkspaceBinding.addSourceMapping(this);}
rawLocationToUILocation(rawLocation){const script=rawLocation.script();const formatData=script&&Sources.SourceFormatData._for(script);if(!formatData)
return null;const lineNumber=rawLocation.lineNumber;const columnNumber=rawLocation.columnNumber||0;const formattedLocation=formatData.mapping.originalToFormatted(lineNumber,columnNumber);return formatData.formattedSourceCode.uiLocation(formattedLocation[0],formattedLocation[1]);}
uiLocationToRawLocations(uiSourceCode,lineNumber,columnNumber){const formatData=Sources.SourceFormatData._for(uiSourceCode);if(!formatData)
return[];const originalLocation=formatData.mapping.formattedToOriginal(lineNumber,columnNumber);const scripts=this._scriptsForUISourceCode(formatData.originalSourceCode);if(!scripts.length)
return[];return scripts.map(script=>script.debuggerModel.createRawLocation(script,originalLocation[0],originalLocation[1]));}
_setSourceMappingEnabled(formatData,enabled){const scripts=this._scriptsForUISourceCode(formatData.originalSourceCode);if(!scripts.length)
return;if(enabled){for(const script of scripts)
script[Sources.SourceFormatData._formatDataSymbol]=formatData;}else{for(const script of scripts)
delete script[Sources.SourceFormatData._formatDataSymbol];}
for(const script of scripts)
Bindings.debuggerWorkspaceBinding.updateLocations(script);}
_scriptsForUISourceCode(uiSourceCode){if(uiSourceCode.contentType()===Common.resourceTypes.Document){const target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);const debuggerModel=target&&target.model(SDK.DebuggerModel);if(debuggerModel){const scripts=debuggerModel.scriptsForSourceURL(uiSourceCode.url()).filter(script=>script.isInlineScript()&&!script.hasSourceURL);return scripts;}}
if(uiSourceCode.contentType().isScript()){const rawLocations=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode,0,0);return rawLocations.map(location=>location.script());}
return[];}};Sources.SourceFormatter.StyleMapping=class{constructor(){Bindings.cssWorkspaceBinding.addSourceMapping(this);this._headersSymbol=Symbol('Sources.SourceFormatter.StyleMapping._headersSymbol');}
rawLocationToUILocation(rawLocation){const styleHeader=rawLocation.header();const formatData=styleHeader&&Sources.SourceFormatData._for(styleHeader);if(!formatData)
return null;const formattedLocation=formatData.mapping.originalToFormatted(rawLocation.lineNumber,rawLocation.columnNumber||0);return formatData.formattedSourceCode.uiLocation(formattedLocation[0],formattedLocation[1]);}
uiLocationToRawLocations(uiLocation){const formatData=Sources.SourceFormatData._for(uiLocation.uiSourceCode);if(!formatData)
return[];const originalLocation=formatData.mapping.formattedToOriginal(uiLocation.lineNumber,uiLocation.columnNumber);const headers=formatData.originalSourceCode[this._headersSymbol];return headers.map(header=>new SDK.CSSLocation(header,originalLocation[0],originalLocation[1]));}
_setSourceMappingEnabled(formatData,enable){const original=formatData.originalSourceCode;const rawLocations=Bindings.cssWorkspaceBinding.uiLocationToRawLocations(original.uiLocation(0,0));const headers=rawLocations.map(rawLocation=>rawLocation.header()).filter(header=>!!header);if(!headers.length)
return;if(enable){original[this._headersSymbol]=headers;headers.forEach(header=>header[Sources.SourceFormatData._formatDataSymbol]=formatData);}else{original[this._headersSymbol]=null;headers.forEach(header=>delete header[Sources.SourceFormatData._formatDataSymbol]);}
headers.forEach(header=>Bindings.cssWorkspaceBinding.updateLocations(header));}};Sources.sourceFormatter=new Sources.SourceFormatter();;Sources.OpenFileQuickOpen=class extends Sources.FilteredUISourceCodeListProvider{attach(){this.setDefaultScores(Sources.SourcesView.defaultUISourceCodeScores());super.attach();}
uiSourceCodeSelected(uiSourceCode,lineNumber,columnNumber){Host.userMetrics.actionTaken(Host.UserMetrics.Action.SelectFileFromFilePicker);if(!uiSourceCode)
return;if(typeof lineNumber==='number')
Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber,columnNumber));else
Common.Revealer.reveal(uiSourceCode);}
filterProject(project){return!project.isServiceProject();}
renderAsTwoRows(){return true;}};;Sources.SourcesView=class extends UI.VBox{constructor(){super();this.registerRequiredCSS('sources/sourcesView.css');this.element.id='sources-panel-sources-view';this.setMinimumAndPreferredSizes(88,52,150,100);const workspace=Workspace.workspace;this._searchableView=new UI.SearchableView(this,'sourcesViewSearchConfig');this._searchableView.setMinimalSearchQuerySize(0);this._searchableView.show(this.element);this._sourceViewByUISourceCode=new Map();this._editorContainer=new Sources.TabbedEditorContainer(this,Common.settings.createLocalSetting('previouslyViewedFiles',[]),this._placeholderElement());this._editorContainer.show(this._searchableView.element);this._editorContainer.addEventListener(Sources.TabbedEditorContainer.Events.EditorSelected,this._editorSelected,this);this._editorContainer.addEventListener(Sources.TabbedEditorContainer.Events.EditorClosed,this._editorClosed,this);this._historyManager=new Sources.EditingLocationHistoryManager(this,this.currentSourceFrame.bind(this));this._toolbarContainerElement=this.element.createChild('div','sources-toolbar');if(!Runtime.experiments.isEnabled('sourcesPrettyPrint')){this._toolbarEditorActions=new UI.Toolbar('',this._toolbarContainerElement);self.runtime.allInstances(Sources.SourcesView.EditorAction).then(appendButtonsForExtensions.bind(this));}
function appendButtonsForExtensions(actions){for(let i=0;i<actions.length;++i)
this._toolbarEditorActions.appendToolbarItem(actions[i].button(this));}
this._scriptViewToolbar=new UI.Toolbar('',this._toolbarContainerElement);this._scriptViewToolbar.element.style.flex='auto';this._bottomToolbar=new UI.Toolbar('',this._toolbarContainerElement);this._toolbarChangedListener=null;UI.startBatchUpdate();workspace.uiSourceCodes().forEach(this._addUISourceCode.bind(this));UI.endBatchUpdate();workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._uiSourceCodeAdded,this);workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this._uiSourceCodeRemoved,this);workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,this._projectRemoved.bind(this),this);function handleBeforeUnload(event){if(event.returnValue)
return;let unsavedSourceCodes=[];const projects=Workspace.workspace.projectsForType(Workspace.projectTypes.FileSystem);for(let i=0;i<projects.length;++i){unsavedSourceCodes=unsavedSourceCodes.concat(projects[i].uiSourceCodes().filter(sourceCode=>sourceCode.isDirty()));}
if(!unsavedSourceCodes.length)
return;event.returnValue=Common.UIString('DevTools have unsaved changes that will be permanently lost.');UI.viewManager.showView('sources');for(let i=0;i<unsavedSourceCodes.length;++i)
Common.Revealer.reveal(unsavedSourceCodes[i]);}
if(!window.opener)
window.addEventListener('beforeunload',handleBeforeUnload,true);this._shortcuts={};this.element.addEventListener('keydown',this._handleKeyDown.bind(this),false);}
_placeholderElement(){const shortcuts=[{actionId:'quickOpen.show',description:Common.UIString('Open file')},{actionId:'commandMenu.show',description:Common.UIString('Run command')}];const element=createElementWithClass('span','tabbed-pane-placeholder');for(const shortcut of shortcuts){const shortcutKeyText=UI.shortcutRegistry.shortcutTitleForAction(shortcut.actionId);const row=element.createChild('div','tabbed-pane-placeholder-row');row.createChild('div','tabbed-pane-placeholder-key').textContent=shortcutKeyText;row.createChild('div','tabbed-pane-placeholder-value').textContent=shortcut.description;}
element.createChild('div').textContent=Common.UIString('Drop in a folder to add to workspace');element.appendChild(UI.XLink.create('https://developers.google.com/web/tools/chrome-devtools/sources?utm_source=devtools&utm_campaign=2018Q1','Learn more'));return element;}
static defaultUISourceCodeScores(){const defaultScores=new Map();const sourcesView=UI.context.flavor(Sources.SourcesView);if(sourcesView){const uiSourceCodes=sourcesView._editorContainer.historyUISourceCodes();for(let i=1;i<uiSourceCodes.length;++i)
defaultScores.set(uiSourceCodes[i],uiSourceCodes.length-i);}
return defaultScores;}
leftToolbar(){return this._editorContainer.leftToolbar();}
rightToolbar(){return this._editorContainer.rightToolbar();}
bottomToolbar(){return this._bottomToolbar;}
_registerShortcuts(keys,handler){for(let i=0;i<keys.length;++i)
this._shortcuts[keys[i].key]=handler;}
_handleKeyDown(event){const shortcutKey=UI.KeyboardShortcut.makeKeyFromEvent(event);const handler=this._shortcuts[shortcutKey];if(handler&&handler())
event.consume(true);}
wasShown(){super.wasShown();UI.context.setFlavor(Sources.SourcesView,this);}
willHide(){UI.context.setFlavor(Sources.SourcesView,null);super.willHide();}
toolbarContainerElement(){return this._toolbarContainerElement;}
searchableView(){return this._searchableView;}
visibleView(){return this._editorContainer.visibleView;}
currentSourceFrame(){const view=this.visibleView();if(!(view instanceof Sources.UISourceCodeFrame))
return null;return(view);}
currentUISourceCode(){return this._editorContainer.currentFile();}
_onCloseEditorTab(){const uiSourceCode=this._editorContainer.currentFile();if(!uiSourceCode)
return false;this._editorContainer.closeFile(uiSourceCode);return true;}
_onJumpToPreviousLocation(){this._historyManager.rollback();}
_onJumpToNextLocation(){this._historyManager.rollover();}
_uiSourceCodeAdded(event){const uiSourceCode=(event.data);this._addUISourceCode(uiSourceCode);}
_addUISourceCode(uiSourceCode){if(uiSourceCode.project().isServiceProject())
return;if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem&&Persistence.FileSystemWorkspaceBinding.fileSystemType(uiSourceCode.project())==='overrides')
return;this._editorContainer.addUISourceCode(uiSourceCode);}
_uiSourceCodeRemoved(event){const uiSourceCode=(event.data);this._removeUISourceCodes([uiSourceCode]);}
_removeUISourceCodes(uiSourceCodes){this._editorContainer.removeUISourceCodes(uiSourceCodes);for(let i=0;i<uiSourceCodes.length;++i){this._removeSourceFrame(uiSourceCodes[i]);this._historyManager.removeHistoryForSourceCode(uiSourceCodes[i]);}}
_projectRemoved(event){const project=event.data;const uiSourceCodes=project.uiSourceCodes();this._removeUISourceCodes(uiSourceCodes);}
_updateScriptViewToolbarItems(){this._scriptViewToolbar.removeToolbarItems();const view=this.visibleView();if(view instanceof UI.SimpleView){for(const item of((view)).syncToolbarItems())
this._scriptViewToolbar.appendToolbarItem(item);}}
showSourceLocation(uiSourceCode,lineNumber,columnNumber,omitFocus,omitHighlight){this._historyManager.updateCurrentState();this._editorContainer.showFile(uiSourceCode);const currentSourceFrame=this.currentSourceFrame();if(currentSourceFrame&&typeof lineNumber==='number')
currentSourceFrame.revealPosition(lineNumber,columnNumber,!omitHighlight);this._historyManager.pushNewState();if(!omitFocus)
this.visibleView().focus();}
_createSourceView(uiSourceCode){let sourceFrame;let sourceView;const contentType=uiSourceCode.contentType();if(contentType===Common.resourceTypes.Image)
sourceView=new SourceFrame.ImageView(uiSourceCode.mimeType(),uiSourceCode);else if(contentType===Common.resourceTypes.Font)
sourceView=new SourceFrame.FontView(uiSourceCode.mimeType(),uiSourceCode);else
sourceFrame=new Sources.UISourceCodeFrame(uiSourceCode);if(sourceFrame)
this._historyManager.trackSourceFrameCursorJumps(sourceFrame);const widget=(sourceFrame||sourceView);this._sourceViewByUISourceCode.set(uiSourceCode,widget);return widget;}
_getOrCreateSourceView(uiSourceCode){return this._sourceViewByUISourceCode.get(uiSourceCode)||this._createSourceView(uiSourceCode);}
recycleUISourceCodeFrame(sourceFrame,uiSourceCode){this._sourceViewByUISourceCode.delete(sourceFrame.uiSourceCode());sourceFrame.setUISourceCode(uiSourceCode);this._sourceViewByUISourceCode.set(uiSourceCode,sourceFrame);}
viewForFile(uiSourceCode){return this._getOrCreateSourceView(uiSourceCode);}
_removeSourceFrame(uiSourceCode){const sourceView=this._sourceViewByUISourceCode.get(uiSourceCode);this._sourceViewByUISourceCode.remove(uiSourceCode);if(sourceView&&sourceView instanceof Sources.UISourceCodeFrame)
(sourceView).dispose();}
_editorClosed(event){const uiSourceCode=(event.data);this._historyManager.removeHistoryForSourceCode(uiSourceCode);let wasSelected=false;if(!this._editorContainer.currentFile())
wasSelected=true;this._removeToolbarChangedListener();this._updateScriptViewToolbarItems();this._searchableView.resetSearch();const data={};data.uiSourceCode=uiSourceCode;data.wasSelected=wasSelected;this.dispatchEventToListeners(Sources.SourcesView.Events.EditorClosed,data);}
_editorSelected(event){const previousSourceFrame=event.data.previousView instanceof Sources.UISourceCodeFrame?event.data.previousView:null;if(previousSourceFrame)
previousSourceFrame.setSearchableView(null);const currentSourceFrame=event.data.currentView instanceof Sources.UISourceCodeFrame?event.data.currentView:null;if(currentSourceFrame)
currentSourceFrame.setSearchableView(this._searchableView);this._searchableView.setReplaceable(!!currentSourceFrame&&currentSourceFrame.canEditSource());this._searchableView.refreshSearch();this._updateToolbarChangedListener();this._updateScriptViewToolbarItems();this.dispatchEventToListeners(Sources.SourcesView.Events.EditorSelected,this._editorContainer.currentFile());}
_removeToolbarChangedListener(){if(this._toolbarChangedListener)
Common.EventTarget.removeEventListeners([this._toolbarChangedListener]);this._toolbarChangedListener=null;}
_updateToolbarChangedListener(){this._removeToolbarChangedListener();const sourceFrame=this.currentSourceFrame();if(!sourceFrame)
return;this._toolbarChangedListener=sourceFrame.addEventListener(Sources.UISourceCodeFrame.Events.ToolbarItemsChanged,this._updateScriptViewToolbarItems,this);}
searchCanceled(){if(this._searchView)
this._searchView.searchCanceled();delete this._searchView;delete this._searchConfig;}
performSearch(searchConfig,shouldJump,jumpBackwards){const sourceFrame=this.currentSourceFrame();if(!sourceFrame)
return;this._searchView=sourceFrame;this._searchConfig=searchConfig;this._searchView.performSearch(this._searchConfig,shouldJump,jumpBackwards);}
jumpToNextSearchResult(){if(!this._searchView)
return;if(this._searchView!==this.currentSourceFrame()){this.performSearch(this._searchConfig,true);return;}
this._searchView.jumpToNextSearchResult();}
jumpToPreviousSearchResult(){if(!this._searchView)
return;if(this._searchView!==this.currentSourceFrame()){this.performSearch(this._searchConfig,true);if(this._searchView)
this._searchView.jumpToLastSearchResult();return;}
this._searchView.jumpToPreviousSearchResult();}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}
replaceSelectionWith(searchConfig,replacement){const sourceFrame=this.currentSourceFrame();if(!sourceFrame){console.assert(sourceFrame);return;}
sourceFrame.replaceSelectionWith(searchConfig,replacement);}
replaceAllWith(searchConfig,replacement){const sourceFrame=this.currentSourceFrame();if(!sourceFrame){console.assert(sourceFrame);return;}
sourceFrame.replaceAllWith(searchConfig,replacement);}
_showOutlineQuickOpen(){QuickOpen.QuickOpen.show('@');}
_showGoToLineQuickOpen(){if(this._editorContainer.currentFile())
QuickOpen.QuickOpen.show(':');}
_save(){this._saveSourceFrame(this.currentSourceFrame());}
_saveAll(){const sourceFrames=this._editorContainer.fileViews();sourceFrames.forEach(this._saveSourceFrame.bind(this));}
_saveSourceFrame(sourceFrame){if(!(sourceFrame instanceof Sources.UISourceCodeFrame))
return;const uiSourceCodeFrame=(sourceFrame);uiSourceCodeFrame.commitEditing();}
toggleBreakpointsActiveState(active){this._editorContainer.view.element.classList.toggle('breakpoints-deactivated',!active);}};Sources.SourcesView.Events={EditorClosed:Symbol('EditorClosed'),EditorSelected:Symbol('EditorSelected'),};Sources.SourcesView.EditorAction=function(){};Sources.SourcesView.EditorAction.prototype={button(sourcesView){}};Sources.SourcesView.SwitchFileActionDelegate=class{static _nextFile(currentUISourceCode){function fileNamePrefix(name){const lastDotIndex=name.lastIndexOf('.');const namePrefix=name.substr(0,lastDotIndex!==-1?lastDotIndex:name.length);return namePrefix.toLowerCase();}
const uiSourceCodes=currentUISourceCode.project().uiSourceCodes();const candidates=[];const url=currentUISourceCode.parentURL();const name=currentUISourceCode.name();const namePrefix=fileNamePrefix(name);for(let i=0;i<uiSourceCodes.length;++i){const uiSourceCode=uiSourceCodes[i];if(url!==uiSourceCode.parentURL())
continue;if(fileNamePrefix(uiSourceCode.name())===namePrefix)
candidates.push(uiSourceCode.name());}
candidates.sort(String.naturalOrderComparator);const index=mod(candidates.indexOf(name)+1,candidates.length);const fullURL=(url?url+'/':'')+candidates[index];const nextUISourceCode=currentUISourceCode.project().uiSourceCodeForURL(fullURL);return nextUISourceCode!==currentUISourceCode?nextUISourceCode:null;}
handleAction(context,actionId){const sourcesView=UI.context.flavor(Sources.SourcesView);const currentUISourceCode=sourcesView.currentUISourceCode();if(!currentUISourceCode)
return false;const nextUISourceCode=Sources.SourcesView.SwitchFileActionDelegate._nextFile(currentUISourceCode);if(!nextUISourceCode)
return false;sourcesView.showSourceLocation(nextUISourceCode);return true;}};Sources.SourcesView.ActionDelegate=class{handleAction(context,actionId){const sourcesView=UI.context.flavor(Sources.SourcesView);if(!sourcesView)
return false;switch(actionId){case'sources.close-all':sourcesView._editorContainer.closeAllFiles();return true;case'sources.jump-to-previous-location':sourcesView._onJumpToPreviousLocation();return true;case'sources.jump-to-next-location':sourcesView._onJumpToNextLocation();return true;case'sources.close-editor-tab':return sourcesView._onCloseEditorTab();case'sources.go-to-line':sourcesView._showGoToLineQuickOpen();return true;case'sources.go-to-member':sourcesView._showOutlineQuickOpen();return true;case'sources.save':sourcesView._save();return true;case'sources.save-all':sourcesView._saveAll();return true;}
return false;}};;Sources.SourcesSearchScope=class{constructor(){this._searchId=0;this._searchResultCandidates=[];this._searchResultCallback=null;this._searchFinishedCallback=null;this._searchConfig=null;}
static _filesComparator(uiSourceCode1,uiSourceCode2){if(uiSourceCode1.isDirty()&&!uiSourceCode2.isDirty())
return-1;if(!uiSourceCode1.isDirty()&&uiSourceCode2.isDirty())
return 1;const isFileSystem1=uiSourceCode1.project().type()===Workspace.projectTypes.FileSystem&&!Persistence.persistence.binding(uiSourceCode1);const isFileSystem2=uiSourceCode2.project().type()===Workspace.projectTypes.FileSystem&&!Persistence.persistence.binding(uiSourceCode2);if(isFileSystem1!==isFileSystem2)
return isFileSystem1?1:-1;const url1=uiSourceCode1.url();const url2=uiSourceCode2.url();if(url1&&!url2)
return-1;if(!url1&&url2)
return 1;return String.naturalOrderComparator(uiSourceCode1.fullDisplayName(),uiSourceCode2.fullDisplayName());}
performIndexing(progress){this.stopSearch();const projects=this._projects();const compositeProgress=new Common.CompositeProgress(progress);for(let i=0;i<projects.length;++i){const project=projects[i];const projectProgress=compositeProgress.createSubProgress(project.uiSourceCodes().length);project.indexContent(projectProgress);}}
_projects(){const searchInAnonymousAndContentScripts=Common.moduleSetting('searchInAnonymousAndContentScripts').get();return Workspace.workspace.projects().filter(project=>{if(project.type()===Workspace.projectTypes.Service)
return false;if(!searchInAnonymousAndContentScripts&&project.isServiceProject())
return false;if(!searchInAnonymousAndContentScripts&&project.type()===Workspace.projectTypes.ContentScripts)
return false;return true;});}
performSearch(searchConfig,progress,searchResultCallback,searchFinishedCallback){this.stopSearch();this._searchResultCandidates=[];this._searchResultCallback=searchResultCallback;this._searchFinishedCallback=searchFinishedCallback;this._searchConfig=searchConfig;const promises=[];const compositeProgress=new Common.CompositeProgress(progress);const searchContentProgress=compositeProgress.createSubProgress();const findMatchingFilesProgress=new Common.CompositeProgress(compositeProgress.createSubProgress());for(const project of this._projects()){const weight=project.uiSourceCodes().length;const findMatchingFilesInProjectProgress=findMatchingFilesProgress.createSubProgress(weight);const filesMathingFileQuery=this._projectFilesMatchingFileQuery(project,searchConfig);const promise=project.findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,findMatchingFilesInProjectProgress).then(this._processMatchingFilesForProject.bind(this,this._searchId,project,searchConfig,filesMathingFileQuery));promises.push(promise);}
Promise.all(promises).then(this._processMatchingFiles.bind(this,this._searchId,searchContentProgress,this._searchFinishedCallback.bind(this,true)));}
_projectFilesMatchingFileQuery(project,searchConfig,dirtyOnly){const result=[];const uiSourceCodes=project.uiSourceCodes();for(let i=0;i<uiSourceCodes.length;++i){const uiSourceCode=uiSourceCodes[i];if(!uiSourceCode.contentType().isTextType())
continue;const binding=Persistence.persistence.binding(uiSourceCode);if(binding&&binding.network===uiSourceCode)
continue;if(dirtyOnly&&!uiSourceCode.isDirty())
continue;if(searchConfig.filePathMatchesFileQuery(uiSourceCode.fullDisplayName()))
result.push(uiSourceCode.url());}
result.sort(String.naturalOrderComparator);return result;}
_processMatchingFilesForProject(searchId,project,searchConfig,filesMathingFileQuery,files){if(searchId!==this._searchId){this._searchFinishedCallback(false);return;}
files.sort(String.naturalOrderComparator);files=files.intersectOrdered(filesMathingFileQuery,String.naturalOrderComparator);const dirtyFiles=this._projectFilesMatchingFileQuery(project,searchConfig,true);files=files.mergeOrdered(dirtyFiles,String.naturalOrderComparator);const uiSourceCodes=[];for(const file of files){const uiSourceCode=project.uiSourceCodeForURL(file);if(!uiSourceCode)
continue;const script=Bindings.DefaultScriptMapping.scriptForUISourceCode(uiSourceCode);if(script&&!script.isAnonymousScript())
continue;uiSourceCodes.push(uiSourceCode);}
uiSourceCodes.sort(Sources.SourcesSearchScope._filesComparator);this._searchResultCandidates=this._searchResultCandidates.mergeOrdered(uiSourceCodes,Sources.SourcesSearchScope._filesComparator);}
_processMatchingFiles(searchId,progress,callback){if(searchId!==this._searchId){this._searchFinishedCallback(false);return;}
const files=this._searchResultCandidates;if(!files.length){progress.done();callback();return;}
progress.setTotalWork(files.length);let fileIndex=0;const maxFileContentRequests=20;let callbacksLeft=0;for(let i=0;i<maxFileContentRequests&&i<files.length;++i)
scheduleSearchInNextFileOrFinish.call(this);function searchInNextFile(uiSourceCode){if(uiSourceCode.isDirty())
contentLoaded.call(this,uiSourceCode,uiSourceCode.workingCopy());else
uiSourceCode.requestContent().then(contentLoaded.bind(this,uiSourceCode));}
function scheduleSearchInNextFileOrFinish(){if(fileIndex>=files.length){if(!callbacksLeft){progress.done();callback();return;}
return;}
++callbacksLeft;const uiSourceCode=files[fileIndex++];setTimeout(searchInNextFile.bind(this,uiSourceCode),0);}
function contentLoaded(uiSourceCode,content){function matchesComparator(a,b){return a.lineNumber-b.lineNumber;}
progress.worked(1);let matches=[];const queries=this._searchConfig.queries();if(content!==null){for(let i=0;i<queries.length;++i){const nextMatches=Common.ContentProvider.performSearchInContent(content,queries[i],!this._searchConfig.ignoreCase(),this._searchConfig.isRegex());matches=matches.mergeOrdered(nextMatches,matchesComparator);}}
if(matches){const searchResult=new Sources.FileBasedSearchResult(uiSourceCode,matches);this._searchResultCallback(searchResult);}
--callbacksLeft;scheduleSearchInNextFileOrFinish.call(this);}}
stopSearch(){++this._searchId;}};Sources.FileBasedSearchResult=class{constructor(uiSourceCode,searchMatches){this._uiSourceCode=uiSourceCode;this._searchMatches=searchMatches;}
label(){return this._uiSourceCode.displayName();}
description(){return this._uiSourceCode.fullDisplayName();}
matchesCount(){return this._searchMatches.length;}
matchLineContent(index){return this._searchMatches[index].lineContent;}
matchRevealable(index){const match=this._searchMatches[index];return this._uiSourceCode.uiLocation(match.lineNumber,match.columnNumber);}
matchLabel(index){return this._searchMatches[index].lineNumber+1;}};;Sources.SourcesPanel=class extends UI.Panel{constructor(){super('sources');Sources.SourcesPanel._instance=this;this.registerRequiredCSS('sources/sourcesPanel.css');new UI.DropTarget(this.element,[UI.DropTarget.Type.Folder],Common.UIString('Drop workspace folder here'),this._handleDrop.bind(this));this._workspace=Workspace.workspace;this._togglePauseAction=(UI.actionRegistry.action('debugger.toggle-pause'));this._stepOverAction=(UI.actionRegistry.action('debugger.step-over'));this._stepIntoAction=(UI.actionRegistry.action('debugger.step-into'));this._stepOutAction=(UI.actionRegistry.action('debugger.step-out'));this._stepAction=(UI.actionRegistry.action('debugger.step'));this._toggleBreakpointsActiveAction=(UI.actionRegistry.action('debugger.toggle-breakpoints-active'));this._debugToolbar=this._createDebugToolbar();this._debugToolbarDrawer=this._createDebugToolbarDrawer();this._debuggerPausedMessage=new Sources.DebuggerPausedMessage();const initialDebugSidebarWidth=225;this._splitWidget=new UI.SplitWidget(true,true,'sourcesPanelSplitViewState',initialDebugSidebarWidth);this._splitWidget.enableShowModeSaving();this._splitWidget.show(this.element);const initialNavigatorWidth=225;this.editorView=new UI.SplitWidget(true,false,'sourcesPanelNavigatorSplitViewState',initialNavigatorWidth);this.editorView.enableShowModeSaving();this.editorView.element.tabIndex=0;this._splitWidget.setMainWidget(this.editorView);this._navigatorTabbedLocation=UI.viewManager.createTabbedLocation(this._revealNavigatorSidebar.bind(this),'navigator-view',true);const tabbedPane=this._navigatorTabbedLocation.tabbedPane();tabbedPane.setMinimumSize(100,25);tabbedPane.element.classList.add('navigator-tabbed-pane');const navigatorMenuButton=new UI.ToolbarMenuButton(this._populateNavigatorMenu.bind(this),true);navigatorMenuButton.setTitle(Common.UIString('More options'));tabbedPane.rightToolbar().appendToolbarItem(navigatorMenuButton);if(UI.viewManager.hasViewsForLocation('run-view-sidebar')){const navigatorSplitWidget=new UI.SplitWidget(false,true,'sourcePanelNavigatorSidebarSplitViewState');navigatorSplitWidget.setMainWidget(tabbedPane);const runViewTabbedPane=UI.viewManager.createTabbedLocation(this._revealNavigatorSidebar.bind(this),'run-view-sidebar').tabbedPane();navigatorSplitWidget.setSidebarWidget(runViewTabbedPane);navigatorSplitWidget.installResizer(runViewTabbedPane.headerElement());this.editorView.setSidebarWidget(navigatorSplitWidget);}else{this.editorView.setSidebarWidget(tabbedPane);}
this._sourcesView=new Sources.SourcesView();this._sourcesView.addEventListener(Sources.SourcesView.Events.EditorSelected,this._editorSelected.bind(this));this._toggleNavigatorSidebarButton=this.editorView.createShowHideSidebarButton('navigator');this._toggleDebuggerSidebarButton=this._splitWidget.createShowHideSidebarButton('debugger');this.editorView.setMainWidget(this._sourcesView);this._threadsSidebarPane=null;this._watchSidebarPane=(UI.viewManager.view('sources.watch'));this._callstackPane=self.runtime.sharedInstance(Sources.CallStackSidebarPane);Common.moduleSetting('sidebarPosition').addChangeListener(this._updateSidebarPosition.bind(this));this._updateSidebarPosition();this._updateDebuggerButtonsAndStatus();this._pauseOnExceptionEnabledChanged();Common.moduleSetting('pauseOnExceptionEnabled').addChangeListener(this._pauseOnExceptionEnabledChanged,this);this._liveLocationPool=new Bindings.LiveLocationPool();this._setTarget(UI.context.flavor(SDK.Target));Common.moduleSetting('breakpointsActive').addChangeListener(this._breakpointsActiveStateChanged,this);UI.context.addFlavorChangeListener(SDK.Target,this._onCurrentTargetChanged,this);UI.context.addFlavorChangeListener(SDK.DebuggerModel.CallFrame,this._callFrameChanged,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerWasEnabled,this._debuggerWasEnabled,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerPaused,this._debuggerPaused,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerResumed,event=>this._debuggerResumed((event.data)));SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.GlobalObjectCleared,event=>this._debuggerResumed((event.data)));Extensions.extensionServer.addEventListener(Extensions.ExtensionServer.Events.SidebarPaneAdded,this._extensionSidebarPaneAdded,this);SDK.targetManager.observeTargets(this);}
static instance(){if(Sources.SourcesPanel._instance)
return Sources.SourcesPanel._instance;return(self.runtime.sharedInstance(Sources.SourcesPanel));}
static updateResizerAndSidebarButtons(panel){panel._sourcesView.leftToolbar().removeToolbarItems();panel._sourcesView.rightToolbar().removeToolbarItems();panel._sourcesView.bottomToolbar().removeToolbarItems();const isInWrapper=Sources.SourcesPanel.WrapperView.isShowing()&&!UI.inspectorView.isDrawerMinimized();if(panel._splitWidget.isVertical()||isInWrapper)
panel._splitWidget.uninstallResizer(panel._sourcesView.toolbarContainerElement());else
panel._splitWidget.installResizer(panel._sourcesView.toolbarContainerElement());if(!isInWrapper){panel._sourcesView.leftToolbar().appendToolbarItem(panel._toggleNavigatorSidebarButton);if(panel._splitWidget.isVertical())
panel._sourcesView.rightToolbar().appendToolbarItem(panel._toggleDebuggerSidebarButton);else
panel._sourcesView.bottomToolbar().appendToolbarItem(panel._toggleDebuggerSidebarButton);}}
targetAdded(target){this._showThreadsIfNeeded();}
targetRemoved(target){}
_showThreadsIfNeeded(){if(Sources.ThreadsSidebarPane.shouldBeShown()&&!this._threadsSidebarPane){this._threadsSidebarPane=(UI.viewManager.view('sources.threads'));if(this._sidebarPaneStack&&this._threadsSidebarPane){this._sidebarPaneStack.showView(this._threadsSidebarPane,this._splitWidget.isVertical()?this._watchSidebarPane:this._callstackPane);}}}
_setTarget(target){if(!target)
return;const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel)
return;if(debuggerModel.isPaused()){this._showDebuggerPausedDetails((debuggerModel.debuggerPausedDetails()));}else{this._paused=false;this._clearInterface();this._toggleDebuggerSidebarButton.setEnabled(true);}}
_onCurrentTargetChanged(event){const target=(event.data);this._setTarget(target);}
paused(){return this._paused;}
wasShown(){UI.context.setFlavor(Sources.SourcesPanel,this);super.wasShown();const wrapper=Sources.SourcesPanel.WrapperView._instance;if(wrapper&&wrapper.isShowing()){UI.inspectorView.setDrawerMinimized(true);Sources.SourcesPanel.updateResizerAndSidebarButtons(this);}
this.editorView.setMainWidget(this._sourcesView);}
willHide(){super.willHide();UI.context.setFlavor(Sources.SourcesPanel,null);if(Sources.SourcesPanel.WrapperView.isShowing()){Sources.SourcesPanel.WrapperView._instance._showViewInWrapper();UI.inspectorView.setDrawerMinimized(false);Sources.SourcesPanel.updateResizerAndSidebarButtons(this);}}
resolveLocation(locationName){if(locationName==='sources.sidebar-top'||locationName==='sources.sidebar-bottom'||locationName==='sources.sidebar-tabs')
return this._sidebarPaneStack;else
return this._navigatorTabbedLocation;}
_ensureSourcesViewVisible(){if(Sources.SourcesPanel.WrapperView.isShowing())
return true;if(!UI.inspectorView.canSelectPanel('sources'))
return false;UI.viewManager.showView('sources');return true;}
onResize(){if(Common.moduleSetting('sidebarPosition').get()==='auto')
this.element.window().requestAnimationFrame(this._updateSidebarPosition.bind(this));}
searchableView(){return this._sourcesView.searchableView();}
_debuggerPaused(event){const debuggerModel=(event.data);const details=debuggerModel.debuggerPausedDetails();if(!this._paused)
this._setAsCurrentPanel();if(UI.context.flavor(SDK.Target)===debuggerModel.target())
this._showDebuggerPausedDetails((details));else if(!this._paused)
UI.context.setFlavor(SDK.Target,debuggerModel.target());}
_showDebuggerPausedDetails(details){this._paused=true;this._updateDebuggerButtonsAndStatus();UI.context.setFlavor(SDK.DebuggerPausedDetails,details);this._toggleDebuggerSidebarButton.setEnabled(false);this._revealDebuggerSidebar();window.focus();InspectorFrontendHost.bringToFront();}
_debuggerResumed(debuggerModel){const target=debuggerModel.target();if(UI.context.flavor(SDK.Target)!==target)
return;this._paused=false;this._clearInterface();this._toggleDebuggerSidebarButton.setEnabled(true);this._switchToPausedTargetTimeout=setTimeout(this._switchToPausedTarget.bind(this,debuggerModel),500);}
_debuggerWasEnabled(event){const debuggerModel=(event.data);if(UI.context.flavor(SDK.Target)!==debuggerModel.target())
return;this._updateDebuggerButtonsAndStatus();}
get visibleView(){return this._sourcesView.visibleView();}
showUISourceCode(uiSourceCode,lineNumber,columnNumber,omitFocus){if(omitFocus){const wrapperShowing=Sources.SourcesPanel.WrapperView._instance&&Sources.SourcesPanel.WrapperView._instance.isShowing();if(!this.isShowing()&&!wrapperShowing)
return;}else{this._showEditor();}
this._sourcesView.showSourceLocation(uiSourceCode,lineNumber,columnNumber,omitFocus);}
_showEditor(){if(Sources.SourcesPanel.WrapperView._instance&&Sources.SourcesPanel.WrapperView._instance.isShowing())
return;this._setAsCurrentPanel();}
showUILocation(uiLocation,omitFocus){this.showUISourceCode(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber,omitFocus);}
_revealInNavigator(uiSourceCode,skipReveal){const extensions=self.runtime.extensions(Sources.NavigatorView);Promise.all(extensions.map(extension=>extension.instance())).then(filterNavigators.bind(this));function filterNavigators(objects){for(let i=0;i<objects.length;++i){const navigatorView=(objects[i]);const viewId=extensions[i].descriptor()['viewId'];if(navigatorView.acceptProject(uiSourceCode.project())){navigatorView.revealUISourceCode(uiSourceCode,true);if(skipReveal)
this._navigatorTabbedLocation.tabbedPane().selectTab(viewId);else
UI.viewManager.showView(viewId);}}}}
_populateNavigatorMenu(contextMenu){const groupByFolderSetting=Common.moduleSetting('navigatorGroupByFolder');contextMenu.appendItemsAtLocation('navigatorMenu');contextMenu.viewSection().appendCheckboxItem(Common.UIString('Group by folder'),()=>groupByFolderSetting.set(!groupByFolderSetting.get()),groupByFolderSetting.get());}
setIgnoreExecutionLineEvents(ignoreExecutionLineEvents){this._ignoreExecutionLineEvents=ignoreExecutionLineEvents;}
updateLastModificationTime(){this._lastModificationTime=window.performance.now();}
_executionLineChanged(liveLocation){const uiLocation=liveLocation.uiLocation();if(!uiLocation)
return;if(window.performance.now()-this._lastModificationTime<Sources.SourcesPanel._lastModificationTimeout)
return;this._sourcesView.showSourceLocation(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber,undefined,true);}
_lastModificationTimeoutPassedForTest(){Sources.SourcesPanel._lastModificationTimeout=Number.MIN_VALUE;}
_updateLastModificationTimeForTest(){Sources.SourcesPanel._lastModificationTimeout=Number.MAX_VALUE;}
_callFrameChanged(){const callFrame=UI.context.flavor(SDK.DebuggerModel.CallFrame);if(!callFrame)
return;if(this._executionLineLocation)
this._executionLineLocation.dispose();this._executionLineLocation=Bindings.debuggerWorkspaceBinding.createCallFrameLiveLocation(callFrame.location(),this._executionLineChanged.bind(this),this._liveLocationPool);}
_pauseOnExceptionEnabledChanged(){const enabled=Common.moduleSetting('pauseOnExceptionEnabled').get();this._pauseOnExceptionButton.setToggled(enabled);this._pauseOnExceptionButton.setTitle(enabled?ls`Don't pause on exceptions`:ls`Pause on exceptions`);this._debugToolbarDrawer.classList.toggle('expanded',enabled);}
async _updateDebuggerButtonsAndStatus(){const currentTarget=UI.context.flavor(SDK.Target);const currentDebuggerModel=currentTarget?currentTarget.model(SDK.DebuggerModel):null;if(!currentDebuggerModel){this._togglePauseAction.setEnabled(false);this._stepOverAction.setEnabled(false);this._stepIntoAction.setEnabled(false);this._stepOutAction.setEnabled(false);this._stepAction.setEnabled(false);}else if(this._paused){this._togglePauseAction.setToggled(true);this._togglePauseAction.setEnabled(true);this._stepOverAction.setEnabled(true);this._stepIntoAction.setEnabled(true);this._stepOutAction.setEnabled(true);this._stepAction.setEnabled(true);}else{this._togglePauseAction.setToggled(false);this._togglePauseAction.setEnabled(!currentDebuggerModel.isPausing());this._stepOverAction.setEnabled(false);this._stepIntoAction.setEnabled(false);this._stepOutAction.setEnabled(false);this._stepAction.setEnabled(false);}
const details=currentDebuggerModel?currentDebuggerModel.debuggerPausedDetails():null;await this._debuggerPausedMessage.render(details,Bindings.debuggerWorkspaceBinding,Bindings.breakpointManager);if(details)
this._updateDebuggerButtonsAndStatusForTest();}
_updateDebuggerButtonsAndStatusForTest(){}
_clearInterface(){this._updateDebuggerButtonsAndStatus();UI.context.setFlavor(SDK.DebuggerPausedDetails,null);if(this._switchToPausedTargetTimeout)
clearTimeout(this._switchToPausedTargetTimeout);this._liveLocationPool.disposeAll();}
_switchToPausedTarget(debuggerModel){delete this._switchToPausedTargetTimeout;if(this._paused)
return;if(debuggerModel.isPaused())
return;const debuggerModels=SDK.targetManager.models(SDK.DebuggerModel);for(let i=0;i<debuggerModels.length;++i){if(debuggerModels[i].isPaused()){UI.context.setFlavor(SDK.Target,debuggerModels[i].target());break;}}}
_togglePauseOnExceptions(){Common.moduleSetting('pauseOnExceptionEnabled').set(!this._pauseOnExceptionButton.toggled());}
_runSnippet(){const uiSourceCode=this._sourcesView.currentUISourceCode();if(!uiSourceCode)
return;Snippets.evaluateScriptSnippet(uiSourceCode);}
_editorSelected(event){const uiSourceCode=(event.data);if(this.editorView.mainWidget()&&Common.moduleSetting('autoRevealInNavigator').get())
this._revealInNavigator(uiSourceCode,true);}
_togglePause(){const target=UI.context.flavor(SDK.Target);if(!target)
return true;const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel)
return true;if(this._paused){this._paused=false;debuggerModel.resume();}else{debuggerModel.pause();}
this._clearInterface();return true;}
_prepareToResume(){if(!this._paused)
return null;this._paused=false;this._clearInterface();const target=UI.context.flavor(SDK.Target);return target?target.model(SDK.DebuggerModel):null;}
_longResume(event){const debuggerModel=this._prepareToResume();if(!debuggerModel)
return;debuggerModel.skipAllPausesUntilReloadOrTimeout(500);debuggerModel.resume();}
_terminateExecution(event){const debuggerModel=this._prepareToResume();if(!debuggerModel)
return;debuggerModel.runtimeModel().terminateExecution();debuggerModel.resume();}
_stepOver(){const debuggerModel=this._prepareToResume();if(!debuggerModel)
return true;debuggerModel.stepOver();return true;}
_stepInto(){const debuggerModel=this._prepareToResume();if(!debuggerModel)
return true;debuggerModel.stepInto();return true;}
_stepIntoAsync(){const debuggerModel=this._prepareToResume();if(!debuggerModel)
return true;debuggerModel.scheduleStepIntoAsync();return true;}
_stepOut(){const debuggerModel=this._prepareToResume();if(!debuggerModel)
return true;debuggerModel.stepOut();return true;}
_continueToLocation(uiLocation){const executionContext=UI.context.flavor(SDK.ExecutionContext);if(!executionContext)
return;const rawLocations=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiLocation.uiSourceCode,uiLocation.lineNumber,0);const rawLocation=rawLocations.find(location=>location.debuggerModel===executionContext.debuggerModel);if(!rawLocation)
return;if(!this._prepareToResume())
return;rawLocation.continueToLocation();}
_toggleBreakpointsActive(){Common.moduleSetting('breakpointsActive').set(!Common.moduleSetting('breakpointsActive').get());}
_breakpointsActiveStateChanged(){const active=Common.moduleSetting('breakpointsActive').get();this._toggleBreakpointsActiveAction.setToggled(!active);this._sourcesView.toggleBreakpointsActiveState(active);}
_createDebugToolbar(){const debugToolbar=new UI.Toolbar('scripts-debug-toolbar');const longResumeButton=new UI.ToolbarButton(Common.UIString('Resume with all pauses blocked for 500 ms'),'largeicon-play');longResumeButton.addEventListener(UI.ToolbarButton.Events.Click,this._longResume,this);const terminateExecutionButton=new UI.ToolbarButton(ls`Terminate current JavaScript call`,'largeicon-terminate-execution');terminateExecutionButton.addEventListener(UI.ToolbarButton.Events.Click,this._terminateExecution,this);debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._togglePauseAction,[terminateExecutionButton,longResumeButton],[]));debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._stepOverAction));debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._stepIntoAction));debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._stepOutAction));debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._stepAction));debugToolbar.appendSeparator();debugToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._toggleBreakpointsActiveAction));this._pauseOnExceptionButton=new UI.ToolbarToggle('','largeicon-pause-on-exceptions');this._pauseOnExceptionButton.addEventListener(UI.ToolbarButton.Events.Click,this._togglePauseOnExceptions,this);debugToolbar.appendToolbarItem(this._pauseOnExceptionButton);return debugToolbar;}
_createDebugToolbarDrawer(){const debugToolbarDrawer=createElementWithClass('div','scripts-debug-toolbar-drawer');const label=Common.UIString('Pause on caught exceptions');const setting=Common.moduleSetting('pauseOnCaughtException');debugToolbarDrawer.appendChild(UI.SettingsUI.createSettingCheckbox(label,setting,true));return debugToolbarDrawer;}
appendApplicableItems(event,contextMenu,target){this._appendUISourceCodeItems(event,contextMenu,target);this._appendUISourceCodeFrameItems(event,contextMenu,target);this.appendUILocationItems(contextMenu,target);this._appendRemoteObjectItems(contextMenu,target);this._appendNetworkRequestItems(contextMenu,target);}
_appendUISourceCodeItems(event,contextMenu,target){if(!(target instanceof Workspace.UISourceCode))
return;const uiSourceCode=(target);if(!uiSourceCode.project().isServiceProject()&&!event.target.isSelfOrDescendant(this._navigatorTabbedLocation.widget().element)){contextMenu.revealSection().appendItem(Common.UIString('Reveal in sidebar'),this._handleContextMenuReveal.bind(this,uiSourceCode));}}
_appendUISourceCodeFrameItems(event,contextMenu,target){if(!(target instanceof Sources.UISourceCodeFrame))
return;if(target.uiSourceCode().contentType().isFromSourceMap()||target.textEditor.selection().isEmpty())
return;contextMenu.debugSection().appendAction('debugger.evaluate-selection');}
appendUILocationItems(contextMenu,object){if(!(object instanceof Workspace.UILocation))
return;const uiLocation=(object);const uiSourceCode=uiLocation.uiSourceCode;const contentType=uiSourceCode.contentType();if(contentType.hasScripts()){const target=UI.context.flavor(SDK.Target);const debuggerModel=target?target.model(SDK.DebuggerModel):null;if(debuggerModel&&debuggerModel.isPaused()){contextMenu.debugSection().appendItem(Common.UIString('Continue to here'),this._continueToLocation.bind(this,uiLocation));}
this._callstackPane.appendBlackboxURLContextMenuItems(contextMenu,uiSourceCode);}}
_handleContextMenuReveal(uiSourceCode){this.editorView.showBoth();this._revealInNavigator(uiSourceCode);}
_appendRemoteObjectItems(contextMenu,target){if(!(target instanceof SDK.RemoteObject))
return;const remoteObject=(target);const executionContext=UI.context.flavor(SDK.ExecutionContext);contextMenu.debugSection().appendItem(ls`Store as global variable`,()=>SDK.consoleModel.saveToTempVariable(executionContext,remoteObject));if(remoteObject.type==='function'){contextMenu.debugSection().appendItem(ls`Show function definition`,this._showFunctionDefinition.bind(this,remoteObject));}}
_appendNetworkRequestItems(contextMenu,target){if(!(target instanceof SDK.NetworkRequest))
return;const request=(target);const uiSourceCode=this._workspace.uiSourceCodeForURL(request.url());if(!uiSourceCode)
return;const openText=Common.UIString('Open in Sources panel');contextMenu.revealSection().appendItem(openText,this.showUILocation.bind(this,uiSourceCode.uiLocation(0,0)));}
_showFunctionDefinition(remoteObject){remoteObject.debuggerModel().functionDetailsPromise(remoteObject).then(this._didGetFunctionDetails.bind(this));}
_didGetFunctionDetails(response){if(!response||!response.location)
return;const location=response.location;if(!location)
return;const uiLocation=Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(location);if(uiLocation)
this.showUILocation(uiLocation);}
_revealNavigatorSidebar(){this._setAsCurrentPanel();this.editorView.showBoth(true);}
_revealDebuggerSidebar(){this._setAsCurrentPanel();this._splitWidget.showBoth(true);}
_updateSidebarPosition(){let vertically;const position=Common.moduleSetting('sidebarPosition').get();if(position==='right')
vertically=false;else if(position==='bottom')
vertically=true;else
vertically=UI.inspectorView.element.offsetWidth<680;if(this.sidebarPaneView&&vertically===!this._splitWidget.isVertical())
return;if(this.sidebarPaneView&&this.sidebarPaneView.shouldHideOnDetach())
return;if(this.sidebarPaneView)
this.sidebarPaneView.detach();this._splitWidget.setVertical(!vertically);this._splitWidget.element.classList.toggle('sources-split-view-vertical',vertically);Sources.SourcesPanel.updateResizerAndSidebarButtons(this);const vbox=new UI.VBox();vbox.element.appendChild(this._debugToolbarDrawer);vbox.setMinimumAndPreferredSizes(25,25,Sources.SourcesPanel.minToolbarWidth,100);this._sidebarPaneStack=UI.viewManager.createStackLocation(this._revealDebuggerSidebar.bind(this));this._sidebarPaneStack.widget().element.classList.add('overflow-auto');this._sidebarPaneStack.widget().show(vbox.element);this._sidebarPaneStack.widget().element.appendChild(this._debuggerPausedMessage.element());this._sidebarPaneStack.appendApplicableItems('sources.sidebar-top');vbox.element.appendChild(this._debugToolbar.element);if(this._threadsSidebarPane)
this._sidebarPaneStack.showView(this._threadsSidebarPane);if(!vertically)
this._sidebarPaneStack.appendView(this._watchSidebarPane);this._sidebarPaneStack.showView(this._callstackPane);const jsBreakpoints=(UI.viewManager.view('sources.jsBreakpoints'));const scopeChainView=(UI.viewManager.view('sources.scopeChain'));if(this._tabbedLocationHeader){this._splitWidget.uninstallResizer(this._tabbedLocationHeader);this._tabbedLocationHeader=null;}
if(!vertically){this._sidebarPaneStack.showView(scopeChainView);this._sidebarPaneStack.showView(jsBreakpoints);this._extensionSidebarPanesContainer=this._sidebarPaneStack;this.sidebarPaneView=vbox;this._splitWidget.uninstallResizer(this._debugToolbar.gripElementForResize());}else{const splitWidget=new UI.SplitWidget(true,true,'sourcesPanelDebuggerSidebarSplitViewState',0.5);splitWidget.setMainWidget(vbox);this._sidebarPaneStack.showView(jsBreakpoints);const tabbedLocation=UI.viewManager.createTabbedLocation(this._revealDebuggerSidebar.bind(this));splitWidget.setSidebarWidget(tabbedLocation.tabbedPane());this._tabbedLocationHeader=tabbedLocation.tabbedPane().headerElement();this._splitWidget.installResizer(this._tabbedLocationHeader);this._splitWidget.installResizer(this._debugToolbar.gripElementForResize());tabbedLocation.appendView(scopeChainView);tabbedLocation.appendView(this._watchSidebarPane);tabbedLocation.appendApplicableItems('sources.sidebar-tabs');this._extensionSidebarPanesContainer=tabbedLocation;this.sidebarPaneView=splitWidget;}
this._sidebarPaneStack.appendApplicableItems('sources.sidebar-bottom');const extensionSidebarPanes=Extensions.extensionServer.sidebarPanes();for(let i=0;i<extensionSidebarPanes.length;++i)
this._addExtensionSidebarPane(extensionSidebarPanes[i]);this._splitWidget.setSidebarWidget(this.sidebarPaneView);}
_setAsCurrentPanel(){return UI.viewManager.showView('sources');}
_extensionSidebarPaneAdded(event){const pane=(event.data);this._addExtensionSidebarPane(pane);}
_addExtensionSidebarPane(pane){if(pane.panelName()===this.name)
this._extensionSidebarPanesContainer.appendView(pane);}
sourcesView(){return this._sourcesView;}
_handleDrop(dataTransfer){const items=dataTransfer.items;if(!items.length)
return;const entry=items[0].webkitGetAsEntry();if(!entry.isDirectory)
return;InspectorFrontendHost.upgradeDraggedFileSystemPermissions(entry.filesystem);}};Sources.SourcesPanel._lastModificationTimeout=200;Sources.SourcesPanel.minToolbarWidth=215;Sources.SourcesPanel.UILocationRevealer=class{reveal(uiLocation,omitFocus){if(!(uiLocation instanceof Workspace.UILocation))
return Promise.reject(new Error('Internal error: not a ui location'));Sources.SourcesPanel.instance().showUILocation(uiLocation,omitFocus);return Promise.resolve();}};Sources.SourcesPanel.DebuggerLocationRevealer=class{reveal(rawLocation,omitFocus){if(!(rawLocation instanceof SDK.DebuggerModel.Location))
return Promise.reject(new Error('Internal error: not a debugger location'));const uiLocation=Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(rawLocation);if(!uiLocation)
return Promise.resolve();Sources.SourcesPanel.instance().showUILocation(uiLocation,omitFocus);return Promise.resolve();}};Sources.SourcesPanel.UISourceCodeRevealer=class{reveal(uiSourceCode,omitFocus){if(!(uiSourceCode instanceof Workspace.UISourceCode))
return Promise.reject(new Error('Internal error: not a ui source code'));Sources.SourcesPanel.instance().showUISourceCode(uiSourceCode,undefined,undefined,omitFocus);return Promise.resolve();}};Sources.SourcesPanel.DebuggerPausedDetailsRevealer=class{reveal(object){return Sources.SourcesPanel.instance()._setAsCurrentPanel();}};Sources.SourcesPanel.RevealingActionDelegate=class{handleAction(context,actionId){const panel=Sources.SourcesPanel.instance();if(!panel._ensureSourcesViewVisible())
return false;switch(actionId){case'debugger.toggle-pause':panel._togglePause();return true;}
return false;}};Sources.SourcesPanel.DebuggingActionDelegate=class{handleAction(context,actionId){const panel=Sources.SourcesPanel.instance();switch(actionId){case'debugger.step-over':panel._stepOver();return true;case'debugger.step-into':panel._stepIntoAsync();return true;case'debugger.step':panel._stepInto();return true;case'debugger.step-out':panel._stepOut();return true;case'debugger.run-snippet':panel._runSnippet();return true;case'debugger.toggle-breakpoints-active':panel._toggleBreakpointsActive();return true;case'debugger.evaluate-selection':const frame=UI.context.flavor(Sources.UISourceCodeFrame);if(frame){let text=frame.textEditor.text(frame.textEditor.selection());const executionContext=UI.context.flavor(SDK.ExecutionContext);if(executionContext){const message=SDK.consoleModel.addCommandMessage(executionContext,text);text=ObjectUI.JavaScriptREPL.wrapObjectLiteral(text);SDK.consoleModel.evaluateCommandInConsole(executionContext,message,text,true,false);}}
return true;}
return false;}};Sources.SourcesPanel.WrapperView=class extends UI.VBox{constructor(){super();this.element.classList.add('sources-view-wrapper');Sources.SourcesPanel.WrapperView._instance=this;this._view=Sources.SourcesPanel.instance()._sourcesView;}
static isShowing(){return!!Sources.SourcesPanel.WrapperView._instance&&Sources.SourcesPanel.WrapperView._instance.isShowing();}
wasShown(){if(!Sources.SourcesPanel.instance().isShowing())
this._showViewInWrapper();else
UI.inspectorView.setDrawerMinimized(true);Sources.SourcesPanel.updateResizerAndSidebarButtons(Sources.SourcesPanel.instance());}
willHide(){UI.inspectorView.setDrawerMinimized(false);setImmediate(()=>Sources.SourcesPanel.updateResizerAndSidebarButtons(Sources.SourcesPanel.instance()));}
_showViewInWrapper(){this._view.show(this.element);}};;Sources.JavaScriptCompilerPlugin=class extends Sources.UISourceCodeFrame.Plugin{constructor(textEditor,uiSourceCode){super();this._textEditor=textEditor;this._uiSourceCode=uiSourceCode;this._compiling=false;this._recompileScheduled=false;this._timeout=null;this._message=null;this._disposed=false;this._textEditor.addEventListener(UI.TextEditor.Events.TextChanged,this._scheduleCompile,this);if(this._uiSourceCode.hasCommits()||this._uiSourceCode.isDirty())
this._scheduleCompile();}
static accepts(uiSourceCode){if(uiSourceCode.extension()==='js')
return true;if(Snippets.isSnippetsUISourceCode(uiSourceCode))
return true;for(const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)){if(Bindings.debuggerWorkspaceBinding.scriptFile(uiSourceCode,debuggerModel))
return true;}
return false;}
_scheduleCompile(){if(this._compiling){this._recompileScheduled=true;return;}
if(this._timeout)
clearTimeout(this._timeout);this._timeout=setTimeout(this._compile.bind(this),Sources.JavaScriptCompilerPlugin.CompileDelay);}
_findRuntimeModel(){const debuggerModels=SDK.targetManager.models(SDK.DebuggerModel);for(let i=0;i<debuggerModels.length;++i){const scriptFile=Bindings.debuggerWorkspaceBinding.scriptFile(this._uiSourceCode,debuggerModels[i]);if(scriptFile)
return debuggerModels[i].runtimeModel();}
return SDK.targetManager.mainTarget()?SDK.targetManager.mainTarget().model(SDK.RuntimeModel):null;}
async _compile(){const runtimeModel=this._findRuntimeModel();if(!runtimeModel)
return;const currentExecutionContext=UI.context.flavor(SDK.ExecutionContext);if(!currentExecutionContext)
return;const code=this._textEditor.text();if(code.length>1024*100)
return;this._compiling=true;const result=await runtimeModel.compileScript(code,'',false,currentExecutionContext.id);this._compiling=false;if(this._recompileScheduled){this._recompileScheduled=false;this._scheduleCompile();return;}
if(this._message)
this._uiSourceCode.removeMessage(this._message);if(this._disposed||!result||!result.exceptionDetails)
return;const exceptionDetails=result.exceptionDetails;const text=SDK.RuntimeModel.simpleTextFromException(exceptionDetails);this._message=this._uiSourceCode.addLineMessage(Workspace.UISourceCode.Message.Level.Error,text,exceptionDetails.lineNumber,exceptionDetails.columnNumber);this._compilationFinishedForTest();}
_compilationFinishedForTest(){}
dispose(){this._textEditor.removeEventListener(UI.TextEditor.Events.TextChanged,this._scheduleCompile,this);if(this._message)
this._uiSourceCode.removeMessage(this._message);this._disposed=true;if(this._timeout)
clearTimeout(this._timeout);}};Sources.JavaScriptCompilerPlugin.CompileDelay=1000;;Sources.SnippetsPlugin=class extends Sources.UISourceCodeFrame.Plugin{constructor(textEditor,uiSourceCode){super();this._textEditor=textEditor;this._uiSourceCode=uiSourceCode;}
static accepts(uiSourceCode){return Snippets.isSnippetsUISourceCode(uiSourceCode);}
rightToolbarItems(){const runSnippet=UI.Toolbar.createActionButtonForId('debugger.run-snippet');runSnippet.setText(Host.isMac()?Common.UIString('\u2318+Enter'):Common.UIString('Ctrl+Enter'));return[runSnippet];}};;Sources.ScriptOriginPlugin=class extends Sources.UISourceCodeFrame.Plugin{constructor(textEditor,uiSourceCode){super();this._textEditor=textEditor;this._uiSourceCode=uiSourceCode;}
static accepts(uiSourceCode){return uiSourceCode.contentType().hasScripts()||!!Sources.ScriptOriginPlugin._script(uiSourceCode);}
rightToolbarItems(){const originURL=Bindings.CompilerScriptMapping.uiSourceCodeOrigin(this._uiSourceCode);if(originURL){const item=UI.formatLocalized('(source mapped from %s)',[Components.Linkifier.linkifyURL(originURL)]);return[new UI.ToolbarItem(item)];}
const script=Sources.ScriptOriginPlugin._script(this._uiSourceCode);if(!script||!script.originStackTrace)
return[];const link=Sources.ScriptOriginPlugin._linkifier.linkifyStackTraceTopFrame(script.debuggerModel.target(),script.originStackTrace);return[new UI.ToolbarItem(link)];}
static _script(uiSourceCode){const locations=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode,0,0);for(const location of locations){const script=location.script();if(script.originStackTrace)
return script;}
return null;}};Sources.ScriptOriginPlugin._linkifier=new Components.Linkifier();;Runtime.cachedResources["sources/breakpointEditDialog.css"]="/*\n * Copyright 2018 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n z-index: 30;\n padding: 4px;\n background-color: #e6e6e6;\n border-radius: 7px;\n border: 2px solid #bababa;\n width: 90%;\n pointer-events: auto;\n}\n\n:host(.sources-edit-breakpoint-dialog) {\n border: none;\n border-radius: 0;\n z-index: 30;\n background-color: var(--toolbar-bg-color);\n width: 555px;\n pointer-events: auto;\n margin: 2px 0 2px -1px;\n padding: 0 10px 10px 5px;\n border: 1px solid var(--divider-color);\n}\n\n:host-context(.sources-edit-breakpoint-dialog) .condition-editor {\n background-color: #fff;\n margin-left: 3px;\n}\n\n:host-context(.sources-edit-breakpoint-dialog) .source-frame-breakpoint-toolbar {\n font-family: sans-serif;\n font-size: 12px;\n}\n\n/*# sourceURL=sources/breakpointEditDialog.css */";Runtime.cachedResources["sources/callStackSidebarPane.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.blackboxed-message {\n text-align: center;\n font-style: italic;\n padding: 4px;\n color: #888;\n background-color: #FFFFC2;\n}\n\n.blackboxed-message > .link {\n margin-left: 5px;\n}\n\n.show-more-message {\n text-align: center;\n font-style: italic;\n padding: 4px;\n border-top: 1px solid #d8d8d8;\n}\n\n.show-more-message > .link {\n margin-left: 5px;\n}\n\n.call-frame-item {\n padding: 3px 8px 3px 20px;\n position: relative;\n min-height: 18px;\n line-height: 15px;\n display: flex;\n flex-wrap: wrap;\n}\n\n.call-frame-title-text {\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.call-frame-item:not(.async-header) {\n border-top: 1px solid #efefef;\n}\n\n.call-frame-item:not(.async-header):hover {\n background-color: #eee;\n}\n\n.async-header + .call-frame-item {\n border-top: 0;\n}\n\n.call-frame-item-title,\n.call-frame-location {\n display: flex;\n white-space: nowrap;\n}\n\n.call-frame-location {\n color: #888;\n margin-left: auto;\n padding: 0 10px 0 10px;\n}\n\n.async-header::before {\n content: \" \";\n width: 100%;\n border-top: 1px solid #d8d8d8;\n margin-top: 8px;\n position: absolute;\n z-index: -1;\n left: 0;\n}\n\n.async-header .call-frame-item-title {\n font-weight: bold;\n color: #999;\n background-color: white;\n margin-left: -5px;\n padding: 0 5px;\n}\n\n.blackboxed-call-frame {\n opacity: 0.6;\n font-style: italic;\n}\n\n.selected-call-frame-icon {\n display: none;\n position: absolute;\n top: 5px;\n left: 4px;\n}\n\n.call-frame-item.selected .selected-call-frame-icon {\n display: block;\n}\n\n:host-context(.-theme-with-dark-background) .blackboxed-message {\n background-color: hsl(46, 98%, 22%);\n color: #aaa;\n}\n\n:host-context(.-theme-with-dark-background) .blackboxed-message > .link {\n color: hsl(0, 0%, 67%);\n}\n\n/*# sourceURL=sources/callStackSidebarPane.css */";Runtime.cachedResources["sources/debuggerPausedMessage.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.paused-status {\n padding: 6px;\n border-bottom: 1px solid transparent;\n border-top: 1px solid rgb(189, 189, 189);\n background-color: hsl(50, 100%, 95%);\n color: rgb(107, 97, 48);\n}\n\n.-theme-with-dark-background .paused-status {\n background-color: hsl(46, 98%, 22%);\n color: #ccc;\n}\n\n.paused-status.error-reason {\n background-color: hsl(0, 100%, 97%);\n color: #6b3b3b;\n}\n\n.status-main {\n font-weight: bold;\n padding-left: 15px;\n position: relative;\n}\n\n.status-sub:not(:empty) {\n padding-le
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.defineMode("css",function(config,parserConfig){var inline=parserConfig.inline
if(!parserConfig.propertyKeywords)parserConfig=CodeMirror.resolveMode("text/css");var indentUnit=config.indentUnit,tokenHooks=parserConfig.tokenHooks,documentTypes=parserConfig.documentTypes||{},mediaTypes=parserConfig.mediaTypes||{},mediaFeatures=parserConfig.mediaFeatures||{},mediaValueKeywords=parserConfig.mediaValueKeywords||{},propertyKeywords=parserConfig.propertyKeywords||{},nonStandardPropertyKeywords=parserConfig.nonStandardPropertyKeywords||{},fontProperties=parserConfig.fontProperties||{},counterDescriptors=parserConfig.counterDescriptors||{},colorKeywords=parserConfig.colorKeywords||{},valueKeywords=parserConfig.valueKeywords||{},allowNested=parserConfig.allowNested,lineComment=parserConfig.lineComment,supportsAtComponent=parserConfig.supportsAtComponent===true;var type,override;function ret(style,tp){type=tp;return style;}
function tokenBase(stream,state){var ch=stream.next();if(tokenHooks[ch]){var result=tokenHooks[ch](stream,state);if(result!==false)return result;}
if(ch=="@"){stream.eatWhile(/[\w\\\-]/);return ret("def",stream.current());}else if(ch=="="||(ch=="~"||ch=="|")&&stream.eat("=")){return ret(null,"compare");}else if(ch=="\""||ch=="'"){state.tokenize=tokenString(ch);return state.tokenize(stream,state);}else if(ch=="#"){stream.eatWhile(/[\w\\\-]/);return ret("atom","hash");}else if(ch=="!"){stream.match(/^\s*\w*/);return ret("keyword","important");}else if(/\d/.test(ch)||ch=="."&&stream.eat(/\d/)){stream.eatWhile(/[\w.%]/);return ret("number","unit");}else if(ch==="-"){if(/[\d.]/.test(stream.peek())){stream.eatWhile(/[\w.%]/);return ret("number","unit");}else if(stream.match(/^-[\w\\\-]*/)){stream.eatWhile(/[\w\\\-]/);if(stream.match(/^\s*:/,false))
return ret("variable-2","variable-definition");return ret("variable-2","variable");}else if(stream.match(/^\w+-/)){return ret("meta","meta");}}else if(/[,+>*\/]/.test(ch)){return ret(null,"select-op");}else if(ch=="."&&stream.match(/^-?[_a-z][_a-z0-9-]*/i)){return ret("qualifier","qualifier");}else if(/[:;{}\[\]\(\)]/.test(ch)){return ret(null,ch);}else if(((ch=="u"||ch=="U")&&stream.match(/rl(-prefix)?\(/i))||((ch=="d"||ch=="D")&&stream.match("omain(",true,true))||((ch=="r"||ch=="R")&&stream.match("egexp(",true,true))){stream.backUp(1);state.tokenize=tokenParenthesized;return ret("property","word");}else if(/[\w\\\-]/.test(ch)){stream.eatWhile(/[\w\\\-]/);return ret("property","word");}else{return ret(null,null);}}
function tokenString(quote){return function(stream,state){var escaped=false,ch;while((ch=stream.next())!=null){if(ch==quote&&!escaped){if(quote==")")stream.backUp(1);break;}
escaped=!escaped&&ch=="\\";}
if(ch==quote||!escaped&&quote!=")")state.tokenize=null;return ret("string","string");};}
function tokenParenthesized(stream,state){stream.next();if(!stream.match(/\s*[\"\')]/,false))
state.tokenize=tokenString(")");else
state.tokenize=null;return ret(null,"(");}
function Context(type,indent,prev){this.type=type;this.indent=indent;this.prev=prev;}
function pushContext(state,stream,type,indent){state.context=new Context(type,stream.indentation()+(indent===false?0:indentUnit),state.context);return type;}
function popContext(state){if(state.context.prev)
state.context=state.context.prev;return state.context.type;}
function pass(type,stream,state){return states[state.context.type](type,stream,state);}
function popAndPass(type,stream,state,n){for(var i=n||1;i>0;i--)
state.context=state.context.prev;return pass(type,stream,state);}
function wordAsValue(stream){var word=stream.current().toLowerCase();if(valueKeywords.hasOwnProperty(word))
override="atom";else if(colorKeywords.hasOwnProperty(word))
override="keyword";else
override="variable";}
var states={};states.top=function(type,stream,state){if(type=="{"){return pushContext(state,stream,"block");}else if(type=="}"&&state.context.prev){return popContext(state);}else if(supportsAtComponent&&/@component/i.test(type)){return pushContext(state,stream,"atComponentBlock");}else if(/^@(-moz-)?document$/i.test(type)){return pushContext(state,stream,"documentTypes");}else if(/^@(media|supports|(-moz-)?document|import)$/i.test(type)){return pushContext(state,stream,"atBlock");}else if(/^@(font-face|counter-style)/i.test(type)){state.stateArg=type;return"restricted_atBlock_before";}else if(/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)){return"keyframes";}else if(type&&type.charAt(0)=="@"){return pushContext(state,stream,"at");}else if(type=="hash"){override="builtin";}else if(type=="word"){override="tag";}else if(type=="variable-definition"){return"maybeprop";}else if(type=="interpolation"){return pushContext(state,stream,"interpolation");}else if(type==":"){return"pseudo";}else if(allowNested&&type=="("){return pushContext(state,stream,"parens");}
return state.context.type;};states.block=function(type,stream,state){if(type=="word"){var word=stream.current().toLowerCase();if(propertyKeywords.hasOwnProperty(word)){override="property";return"maybeprop";}else if(nonStandardPropertyKeywords.hasOwnProperty(word)){override="string-2";return"maybeprop";}else if(allowNested){override=stream.match(/^\s*:(?:\s|$)/,false)?"property":"tag";return"block";}else{override+=" error";return"maybeprop";}}else if(type=="meta"){return"block";}else if(!allowNested&&(type=="hash"||type=="qualifier")){override="error";return"block";}else{return states.top(type,stream,state);}};states.maybeprop=function(type,stream,state){if(type==":")return pushContext(state,stream,"prop");return pass(type,stream,state);};states.prop=function(type,stream,state){if(type==";")return popContext(state);if(type=="{"&&allowNested)return pushContext(state,stream,"propBlock");if(type=="}"||type=="{")return popAndPass(type,stream,state);if(type=="(")return pushContext(state,stream,"parens");if(type=="hash"&&!/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())){override+=" error";}else if(type=="word"){wordAsValue(stream);}else if(type=="interpolation"){return pushContext(state,stream,"interpolation");}
return"prop";};states.propBlock=function(type,_stream,state){if(type=="}")return popContext(state);if(type=="word"){override="property";return"maybeprop";}
return state.context.type;};states.parens=function(type,stream,state){if(type=="{"||type=="}")return popAndPass(type,stream,state);if(type==")")return popContext(state);if(type=="(")return pushContext(state,stream,"parens");if(type=="interpolation")return pushContext(state,stream,"interpolation");if(type=="word")wordAsValue(stream);return"parens";};states.pseudo=function(type,stream,state){if(type=="meta")return"pseudo";if(type=="word"){override="variable-3";return state.context.type;}
return pass(type,stream,state);};states.documentTypes=function(type,stream,state){if(type=="word"&&documentTypes.hasOwnProperty(stream.current())){override="tag";return state.context.type;}else{return states.atBlock(type,stream,state);}};states.atBlock=function(type,stream,state){if(type=="(")return pushContext(state,stream,"atBlock_parens");if(type=="}"||type==";")return popAndPass(type,stream,state);if(type=="{")return popContext(state)&&pushContext(state,stream,allowNested?"block":"top");if(type=="interpolation")return pushContext(state,stream,"interpolation");if(type=="word"){var word=stream.current().toLowerCase();if(word=="only"||word=="not"||word=="and"||word=="or")
override="keyword";else if(mediaTypes.hasOwnProperty(word))
override="attribute";else if(mediaFeatures.hasOwnProperty(word))
override="property";else if(mediaValueKeywords.hasOwnProperty(word))
override="keyword";else if(propertyKeywords.hasOwnProperty(word))
override="property";else if(nonStandardPropertyKeywords.hasOwnProperty(word))
override="string-2";else if(valueKeywords.hasOwnProperty(word))
override="atom";else if(colorKeywords.hasOwnProperty(word))
override="keyword";else
override="error";}
return state.context.type;};states.atComponentBlock=function(type,stream,state){if(type=="}")
return popAndPass(type,stream,state);if(type=="{")
return popContext(state)&&pushContext(state,stream,allowNested?"block":"top",false);if(type=="word")
override="error";return state.context.type;};states.atBlock_parens=function(type,stream,state){if(type==")")return popContext(state);if(type=="{"||type=="}")return popAndPass(type,stream,state,2);return states.atBlock(type,stream,state);};states.restricted_atBlock_before=function(type,stream,state){if(type=="{")
return pushContext(state,stream,"restricted_atBlock");if(type=="word"&&state.stateArg=="@counter-style"){override="variable";return"restricted_atBlock_before";}
return pass(type,stream,state);};states.restricted_atBlock=function(type,stream,state){if(type=="}"){state.stateArg=null;return popContext(state);}
if(type=="word"){if((state.stateArg=="@font-face"&&!fontProperties.hasOwnProperty(stream.current().toLowerCase()))||(state.stateArg=="@counter-style"&&!counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
override="error";else
override="property";return"maybeprop";}
return"restricted_atBlock";};states.keyframes=function(type,stream,state){if(type=="word"){override="variable";return"keyframes";}
if(type=="{")return pushContext(state,stream,"top");return pass(type,stream,state);};states.at=function(type,stream,state){if(type==";")return popContext(state);if(type=="{"||type=="}")return popAndPass(type,stream,state);if(type=="word")override="tag";else if(type=="hash")override="builtin";return"at";};states.interpolation=function(type,stream,state){if(type=="}")return popContext(state);if(type=="{"||type==";")return popAndPass(type,stream,state);if(type=="word")override="variable";else if(type!="variable"&&type!="("&&type!=")")override="error";return"interpolation";};return{startState:function(base){return{tokenize:null,state:inline?"block":"top",stateArg:null,context:new Context(inline?"block":"top",base||0,null)};},token:function(stream,state){if(!state.tokenize&&stream.eatSpace())return null;var style=(state.tokenize||tokenBase)(stream,state);if(style&&typeof style=="object"){type=style[1];style=style[0];}
override=style;if(type!="comment")
state.state=states[state.state](type,stream,state);return override;},indent:function(state,textAfter){var cx=state.context,ch=textAfter&&textAfter.charAt(0);var indent=cx.indent;if(cx.type=="prop"&&(ch=="}"||ch==")"))cx=cx.prev;if(cx.prev){if(ch=="}"&&(cx.type=="block"||cx.type=="top"||cx.type=="interpolation"||cx.type=="restricted_atBlock")){cx=cx.prev;indent=cx.indent;}else if(ch==")"&&(cx.type=="parens"||cx.type=="atBlock_parens")||ch=="{"&&(cx.type=="at"||cx.type=="atBlock")){indent=Math.max(0,cx.indent-indentUnit);}}
return indent;},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:lineComment,fold:"brace"};});function keySet(array){var keys={};for(var i=0;i<array.length;++i){keys[array[i].toLowerCase()]=true;}
return keys;}
var documentTypes_=["domain","regexp","url","url-prefix"],documentTypes=keySet(documentTypes_);var mediaTypes_=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],mediaTypes=keySet(mediaTypes_);var mediaFeatures_=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover"],mediaFeatures=keySet(mediaFeatures_);var mediaValueKeywords_=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],mediaValueKeywords=keySet(mediaValueKeywords_);var propertyKeywords_=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","justify-items","justify-self","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-
maybeEnd=(ch=="*");}
return["comment","comment"];}
CodeMirror.defineMIME("text/css",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return false;state.tokenize=tokenCComment;return tokenCComment(stream,state);}},name:"css"});CodeMirror.defineMIME("text/x-scss",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:true,lineComment:"//",tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"];}else if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state);}else{return["operator","operator"];}},":":function(stream){if(stream.match(/\s*\{/,false))
return[null,null]
return false;},"$":function(stream){stream.match(/^[\w-]+/);if(stream.match(/^\s*:/,false))
return["variable-2","variable-definition"];return["variable-2","variable"];},"#":function(stream){if(!stream.eat("{"))return false;return[null,"interpolation"];}},name:"css",helperType:"scss"});CodeMirror.defineMIME("text/x-less",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:true,lineComment:"//",tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"];}else if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state);}else{return["operator","operator"];}},"@":function(stream){if(stream.eat("{"))return[null,"interpolation"];if(stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i,false))return false;stream.eatWhile(/[\w\\\-]/);if(stream.match(/^\s*:/,false))
return["variable-2","variable-definition"];return["variable-2","variable"];},"&":function(){return["atom","atom"];}},name:"css",helperType:"less"});CodeMirror.defineMIME("text/x-gss",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,supportsAtComponent:true,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return false;state.tokenize=tokenCComment;return tokenCComment(stream,state);}},name:"css",helperType:"gss"});});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.defineMode("javascript",function(config,parserConfig){var indentUnit=config.indentUnit;var statementIndent=parserConfig.statementIndent;var jsonldMode=parserConfig.jsonld;var jsonMode=parserConfig.json||jsonldMode;var isTS=parserConfig.typescript;var wordRE=parserConfig.wordCharacters||/[\w$\xa1-\uffff]/;var keywords=function(){function kw(type){return{type:type,style:"keyword"};}
var A=kw("keyword a"),B=kw("keyword b"),C=kw("keyword c"),D=kw("keyword d");var operator=kw("operator"),atom={type:"atom",style:"atom"};return{"if":kw("if"),"while":A,"with":A,"else":B,"do":B,"try":B,"finally":B,"return":D,"break":D,"continue":D,"new":kw("new"),"delete":C,"void":C,"throw":C,"debugger":kw("debugger"),"var":kw("var"),"const":kw("var"),"let":kw("var"),"function":kw("function"),"catch":kw("catch"),"for":kw("for"),"switch":kw("switch"),"case":kw("case"),"default":kw("default"),"in":operator,"typeof":operator,"instanceof":operator,"true":atom,"false":atom,"null":atom,"undefined":atom,"NaN":atom,"Infinity":atom,"this":kw("this"),"class":kw("class"),"super":kw("atom"),"yield":C,"export":kw("export"),"import":kw("import"),"extends":C,"await":C};}();var isOperatorChar=/[+\-*&%=<>!?|~^@]/;var isJsonldKeyword=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;function readRegexp(stream){var escaped=false,next,inSet=false;while((next=stream.next())!=null){if(!escaped){if(next=="/"&&!inSet)return;if(next=="[")inSet=true;else if(inSet&&next=="]")inSet=false;}
escaped=!escaped&&next=="\\";}}
var type,content;function ret(tp,style,cont){type=tp;content=cont;return style;}
function tokenBase(stream,state){var ch=stream.next();if(ch=='"'||ch=="'"){state.tokenize=tokenString(ch);return state.tokenize(stream,state);}else if(ch=="."&&stream.match(/^\d+(?:[eE][+\-]?\d+)?/)){return ret("number","number");}else if(ch=="."&&stream.match("..")){return ret("spread","meta");}else if(/[\[\]{}\(\),;\:\.]/.test(ch)){return ret(ch);}else if(ch=="="&&stream.eat(">")){return ret("=>","operator");}else if(ch=="0"&&stream.match(/^(?:x[\da-f]+|o[0-7]+|b[01]+)n?/i)){return ret("number","number");}else if(/\d/.test(ch)){stream.match(/^\d*(?:n|(?:\.\d*)?(?:[eE][+\-]?\d+)?)?/);return ret("number","number");}else if(ch=="/"){if(stream.eat("*")){state.tokenize=tokenComment;return tokenComment(stream,state);}else if(stream.eat("/")){stream.skipToEnd();return ret("comment","comment");}else if(expressionAllowed(stream,state,1)){readRegexp(stream);stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);return ret("regexp","string-2");}else{stream.eat("=");return ret("operator","operator",stream.current());}}else if(ch=="`"){state.tokenize=tokenQuasi;return tokenQuasi(stream,state);}else if(ch=="#"){stream.skipToEnd();return ret("error","error");}else if(isOperatorChar.test(ch)){if(ch!=">"||!state.lexical||state.lexical.type!=">"){if(stream.eat("=")){if(ch=="!"||ch=="=")stream.eat("=")}else if(/[<>*+\-]/.test(ch)){stream.eat(ch)
if(ch==">")stream.eat(ch)}}
return ret("operator","operator",stream.current());}else if(wordRE.test(ch)){stream.eatWhile(wordRE);var word=stream.current()
if(state.lastType!="."){if(keywords.propertyIsEnumerable(word)){var kw=keywords[word]
return ret(kw.type,kw.style,word)}
if(word=="async"&&stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/,false))
return ret("async","keyword",word)}
return ret("variable","variable",word)}}
function tokenString(quote){return function(stream,state){var escaped=false,next;if(jsonldMode&&stream.peek()=="@"&&stream.match(isJsonldKeyword)){state.tokenize=tokenBase;return ret("jsonld-keyword","meta");}
while((next=stream.next())!=null){if(next==quote&&!escaped)break;escaped=!escaped&&next=="\\";}
if(!escaped)state.tokenize=tokenBase;return ret("string","string");};}
function tokenComment(stream,state){var maybeEnd=false,ch;while(ch=stream.next()){if(ch=="/"&&maybeEnd){state.tokenize=tokenBase;break;}
maybeEnd=(ch=="*");}
return ret("comment","comment");}
function tokenQuasi(stream,state){var escaped=false,next;while((next=stream.next())!=null){if(!escaped&&(next=="`"||next=="$"&&stream.eat("{"))){state.tokenize=tokenBase;break;}
escaped=!escaped&&next=="\\";}
return ret("quasi","string-2",stream.current());}
var brackets="([{}])";function findFatArrow(stream,state){if(state.fatArrowAt)state.fatArrowAt=null;var arrow=stream.string.indexOf("=>",stream.start);if(arrow<0)return;if(isTS){var m=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start,arrow))
if(m)arrow=m.index}
var depth=0,sawSomething=false;for(var pos=arrow-1;pos>=0;--pos){var ch=stream.string.charAt(pos);var bracket=brackets.indexOf(ch);if(bracket>=0&&bracket<3){if(!depth){++pos;break;}
if(--depth==0){if(ch=="(")sawSomething=true;break;}}else if(bracket>=3&&bracket<6){++depth;}else if(wordRE.test(ch)){sawSomething=true;}else if(/["'\/]/.test(ch)){return;}else if(sawSomething&&!depth){++pos;break;}}
if(sawSomething&&!depth)state.fatArrowAt=pos;}
var atomicTypes={"atom":true,"number":true,"variable":true,"string":true,"regexp":true,"this":true,"jsonld-keyword":true};function JSLexical(indented,column,type,align,prev,info){this.indented=indented;this.column=column;this.type=type;this.prev=prev;this.info=info;if(align!=null)this.align=align;}
function inScope(state,varname){for(var v=state.localVars;v;v=v.next)
if(v.name==varname)return true;for(var cx=state.context;cx;cx=cx.prev){for(var v=cx.vars;v;v=v.next)
if(v.name==varname)return true;}}
function parseJS(state,style,type,content,stream){var cc=state.cc;cx.state=state;cx.stream=stream;cx.marked=null,cx.cc=cc;cx.style=style;if(!state.lexical.hasOwnProperty("align"))
state.lexical.align=true;while(true){var combinator=cc.length?cc.pop():jsonMode?expression:statement;if(combinator(type,content)){while(cc.length&&cc[cc.length-1].lex)
cc.pop()();if(cx.marked)return cx.marked;if(type=="variable"&&inScope(state,content))return"variable-2";return style;}}}
var cx={state:null,column:null,marked:null,cc:null};function pass(){for(var i=arguments.length-1;i>=0;i--)cx.cc.push(arguments[i]);}
function cont(){pass.apply(null,arguments);return true;}
function inList(name,list){for(var v=list;v;v=v.next)if(v.name==name)return true
return false;}
function register(varname){var state=cx.state;cx.marked="def";if(state.context){if(state.lexical.info=="var"&&state.context&&state.context.block){var newContext=registerVarScoped(varname,state.context)
if(newContext!=null){state.context=newContext
return}}else if(!inList(varname,state.localVars)){state.localVars=new Var(varname,state.localVars)
return}}
if(parserConfig.globalVars&&!inList(varname,state.globalVars))
state.globalVars=new Var(varname,state.globalVars)}
function registerVarScoped(varname,context){if(!context){return null}else if(context.block){var inner=registerVarScoped(varname,context.prev)
if(!inner)return null
if(inner==context.prev)return context
return new Context(inner,context.vars,true)}else if(inList(varname,context.vars)){return context}else{return new Context(context.prev,new Var(varname,context.vars),false)}}
function isModifier(name){return name=="public"||name=="private"||name=="protected"||name=="abstract"||name=="readonly"}
function Context(prev,vars,block){this.prev=prev;this.vars=vars;this.block=block}
function Var(name,next){this.name=name;this.next=next}
var defaultVars=new Var("this",new Var("arguments",null))
function pushcontext(){cx.state.context=new Context(cx.state.context,cx.state.localVars,false)
cx.state.localVars=defaultVars}
function pushblockcontext(){cx.state.context=new Context(cx.state.context,cx.state.localVars,true)
cx.state.localVars=null}
function popcontext(){cx.state.localVars=cx.state.context.vars
cx.state.context=cx.state.context.prev}
popcontext.lex=true
function pushlex(type,info){var result=function(){var state=cx.state,indent=state.indented;if(state.lexical.type=="stat")indent=state.lexical.indented;else for(var outer=state.lexical;outer&&outer.type==")"&&outer.align;outer=outer.prev)
indent=outer.indented;state.lexical=new JSLexical(indent,cx.stream.column(),type,null,state.lexical,info);};result.lex=true;return result;}
function poplex(){var state=cx.state;if(state.lexical.prev){if(state.lexical.type==")")
state.indented=state.lexical.indented;state.lexical=state.lexical.prev;}}
poplex.lex=true;function expect(wanted){function exp(type){if(type==wanted)return cont();else if(wanted==";"||type=="}"||type==")"||type=="]")return pass();else return cont(exp);};return exp;}
function statement(type,value){if(type=="var")return cont(pushlex("vardef",value),vardef,expect(";"),poplex);if(type=="keyword a")return cont(pushlex("form"),parenExpr,statement,poplex);if(type=="keyword b")return cont(pushlex("form"),statement,poplex);if(type=="keyword d")return cx.stream.match(/^\s*$/,false)?cont():cont(pushlex("stat"),maybeexpression,expect(";"),poplex);if(type=="debugger")return cont(expect(";"));if(type=="{")return cont(pushlex("}"),pushblockcontext,block,poplex,popcontext);if(type==";")return cont();if(type=="if"){if(cx.state.lexical.info=="else"&&cx.state.cc[cx.state.cc.length-1]==poplex)
cx.state.cc.pop()();return cont(pushlex("form"),parenExpr,statement,poplex,maybeelse);}
if(type=="function")return cont(functiondef);if(type=="for")return cont(pushlex("form"),forspec,statement,poplex);if(type=="class"||(isTS&&value=="interface")){cx.marked="keyword";return cont(pushlex("form"),className,poplex);}
if(type=="variable"){if(isTS&&value=="declare"){cx.marked="keyword"
return cont(statement)}else if(isTS&&(value=="module"||value=="enum"||value=="type")&&cx.stream.match(/^\s*\w/,false)){cx.marked="keyword"
if(value=="enum")return cont(enumdef);else if(value=="type")return cont(typeexpr,expect("operator"),typeexpr,expect(";"));else return cont(pushlex("form"),pattern,expect("{"),pushlex("}"),block,poplex,poplex)}else if(isTS&&value=="namespace"){cx.marked="keyword"
return cont(pushlex("form"),expression,block,poplex)}else if(isTS&&value=="abstract"){cx.marked="keyword"
return cont(statement)}else{return cont(pushlex("stat"),maybelabel);}}
if(type=="switch")return cont(pushlex("form"),parenExpr,expect("{"),pushlex("}","switch"),pushblockcontext,block,poplex,poplex,popcontext);if(type=="case")return cont(expression,expect(":"));if(type=="default")return cont(expect(":"));if(type=="catch")return cont(pushlex("form"),pushcontext,maybeCatchBinding,statement,poplex,popcontext);if(type=="export")return cont(pushlex("stat"),afterExport,poplex);if(type=="import")return cont(pushlex("stat"),afterImport,poplex);if(type=="async")return cont(statement)
if(value=="@")return cont(expression,statement)
return pass(pushlex("stat"),expression,expect(";"),poplex);}
function maybeCatchBinding(type){if(type=="(")return cont(funarg,expect(")"))}
function expression(type,value){return expressionInner(type,value,false);}
function expressionNoComma(type,value){return expressionInner(type,value,true);}
function parenExpr(type){if(type!="(")return pass()
return cont(pushlex(")"),expression,expect(")"),poplex)}
function expressionInner(type,value,noComma){if(cx.state.fatArrowAt==cx.stream.start){var body=noComma?arrowBodyNoComma:arrowBody;if(type=="(")return cont(pushcontext,pushlex(")"),commasep(funarg,")"),poplex,expect("=>"),body,popcontext);else if(type=="variable")return pass(pushcontext,pattern,expect("=>"),body,popcontext);}
var maybeop=noComma?maybeoperatorNoComma:maybeoperatorComma;if(atomicTypes.hasOwnProperty(type))return cont(maybeop);if(type=="function")return cont(functiondef,maybeop);if(type=="class"||(isTS&&value=="interface")){cx.marked="keyword";return cont(pushlex("form"),classExpression,poplex);}
if(type=="keyword c"||type=="async")return cont(noComma?expressionNoComma:expression);if(type=="(")return cont(pushlex(")"),maybeexpression,expect(")"),poplex,maybeop);if(type=="operator"||type=="spread")return cont(noComma?expressionNoComma:expression);if(type=="[")return cont(pushlex("]"),arrayLiteral,poplex,maybeop);if(type=="{")return contCommasep(objprop,"}",null,maybeop);if(type=="quasi")return pass(quasi,maybeop);if(type=="new")return cont(maybeTarget(noComma));if(type=="import")return cont(expression);return cont();}
function maybeexpression(type){if(type.match(/[;\}\)\],]/))return pass();return pass(expression);}
function maybeoperatorComma(type,value){if(type==",")return cont(expression);return maybeoperatorNoComma(type,value,false);}
function maybeoperatorNoComma(type,value,noComma){var me=noComma==false?maybeoperatorComma:maybeoperatorNoComma;var expr=noComma==false?expression:expressionNoComma;if(type=="=>")return cont(pushcontext,noComma?arrowBodyNoComma:arrowBody,popcontext);if(type=="operator"){if(/\+\+|--/.test(value)||isTS&&value=="!")return cont(me);if(isTS&&value=="<"&&cx.stream.match(/^([^>]|<.*?>)*>\s*\(/,false))
return cont(pushlex(">"),commasep(typeexpr,">"),poplex,me);if(value=="?")return cont(expression,expect(":"),expr);return cont(expr);}
if(type=="quasi"){return pass(quasi,me);}
if(type==";")return;if(type=="(")return contCommasep(expressionNoComma,")","call",me);if(type==".")return cont(property,me);if(type=="[")return cont(pushlex("]"),maybeexpression,expect("]"),poplex,me);if(isTS&&value=="as"){cx.marked="keyword";return cont(typeexpr,me)}
if(type=="regexp"){cx.state.lastType=cx.marked="operator"
cx.stream.backUp(cx.stream.pos-cx.stream.start-1)
return cont(expr)}}
function quasi(type,value){if(type!="quasi")return pass();if(value.slice(value.length-2)!="${")return cont(quasi);return cont(expression,continueQuasi);}
function continueQuasi(type){if(type=="}"){cx.marked="string-2";cx.state.tokenize=tokenQuasi;return cont(quasi);}}
function arrowBody(type){findFatArrow(cx.stream,cx.state);return pass(type=="{"?statement:expression);}
function arrowBodyNoComma(type){findFatArrow(cx.stream,cx.state);return pass(type=="{"?statement:expressionNoComma);}
function maybeTarget(noComma){return function(type){if(type==".")return cont(noComma?targetNoComma:target);else if(type=="variable"&&isTS)return cont(maybeTypeArgs,noComma?maybeoperatorNoComma:maybeoperatorComma)
else return pass(noComma?expressionNoComma:expression);};}
function target(_,value){if(value=="target"){cx.marked="keyword";return cont(maybeoperatorComma);}}
function targetNoComma(_,value){if(value=="target"){cx.marked="keyword";return cont(maybeoperatorNoComma);}}
function maybelabel(type){if(type==":")return cont(poplex,statement);return pass(maybeoperatorComma,expect(";"),poplex);}
function property(type){if(type=="variable"){cx.marked="property";return cont();}}
function objprop(type,value){if(type=="async"){cx.marked="property";return cont(objprop);}else if(type=="variable"||cx.style=="keyword"){cx.marked="property";if(value=="get"||value=="set")return cont(getterSetter);var m
if(isTS&&cx.state.fatArrowAt==cx.stream.start&&(m=cx.stream.match(/^\s*:\s*/,false)))
cx.state.fatArrowAt=cx.stream.pos+m[0].length
return cont(afterprop);}else if(type=="number"||type=="string"){cx.marked=jsonldMode?"property":(cx.style+" property");return cont(afterprop);}else if(type=="jsonld-keyword"){return cont(afterprop);}else if(isTS&&isModifier(value)){cx.marked="keyword"
return cont(objprop)}else if(type=="["){return cont(expression,maybetype,expect("]"),afterprop);}else if(type=="spread"){return cont(expressionNoComma,afterprop);}else if(value=="*"){cx.marked="keyword";return cont(objprop);}else if(type==":"){return pass(afterprop)}}
function getterSetter(type){if(type!="variable")return pass(afterprop);cx.marked="property";return cont(functiondef);}
function afterprop(type){if(type==":")return cont(expressionNoComma);if(type=="(")return pass(functiondef);}
function commasep(what,end,sep){function proceed(type,value){if(sep?sep.indexOf(type)>-1:type==","){var lex=cx.state.lexical;if(lex.info=="call")lex.pos=(lex.pos||0)+1;return cont(function(type,value){if(type==end||value==end)return pass()
return pass(what)},proceed);}
if(type==end||value==end)return cont();return cont(expect(end));}
return function(type,value){if(type==end||value==end)return cont();return pass(what,proceed);};}
function contCommasep(what,end,info){for(var i=3;i<arguments.length;i++)
cx.cc.push(arguments[i]);return cont(pushlex(end,info),commasep(what,end),poplex);}
function block(type){if(type=="}")return cont();return pass(statement,block);}
function maybetype(type,value){if(isTS){if(type==":")return cont(typeexpr);if(value=="?")return cont(maybetype);}}
function mayberettype(type){if(isTS&&type==":"){if(cx.stream.match(/^\s*\w+\s+is\b/,false))return cont(expression,isKW,typeexpr)
else return cont(typeexpr)}}
function isKW(_,value){if(value=="is"){cx.marked="keyword"
return cont()}}
function typeexpr(type,value){if(value=="keyof"||value=="typeof"){cx.marked="keyword"
return cont(value=="keyof"?typeexpr:expressionNoComma)}
if(type=="variable"||value=="void"){cx.marked="type"
return cont(afterType)}
if(type=="string"||type=="number"||type=="atom")return cont(afterType);if(type=="[")return cont(pushlex("]"),commasep(typeexpr,"]",","),poplex,afterType)
if(type=="{")return cont(pushlex("}"),commasep(typeprop,"}",",;"),poplex,afterType)
if(type=="(")return cont(commasep(typearg,")"),maybeReturnType)
if(type=="<")return cont(commasep(typeexpr,">"),typeexpr)}
function maybeReturnType(type){if(type=="=>")return cont(typeexpr)}
function typeprop(type,value){if(type=="variable"||cx.style=="keyword"){cx.marked="property"
return cont(typeprop)}else if(value=="?"){return cont(typeprop)}else if(type==":"){return cont(typeexpr)}else if(type=="["){return cont(expression,maybetype,expect("]"),typeprop)}}
function typearg(type,value){if(type=="variable"&&cx.stream.match(/^\s*[?:]/,false)||value=="?")return cont(typearg)
if(type==":")return cont(typeexpr)
return pass(typeexpr)}
function afterType(type,value){if(value=="<")return cont(pushlex(">"),commasep(typeexpr,">"),poplex,afterType)
if(value=="|"||type=="."||value=="&")return cont(typeexpr)
if(type=="[")return cont(expect("]"),afterType)
if(value=="extends"||value=="implements"){cx.marked="keyword";return cont(typeexpr)}}
function maybeTypeArgs(_,value){if(value=="<")return cont(pushlex(">"),commasep(typeexpr,">"),poplex,afterType)}
function typeparam(){return pass(typeexpr,maybeTypeDefault)}
function maybeTypeDefault(_,value){if(value=="=")return cont(typeexpr)}
function vardef(_,value){if(value=="enum"){cx.marked="keyword";return cont(enumdef)}
return pass(pattern,maybetype,maybeAssign,vardefCont);}
function pattern(type,value){if(isTS&&isModifier(value)){cx.marked="keyword";return cont(pattern)}
if(type=="variable"){register(value);return cont();}
if(type=="spread")return cont(pattern);if(type=="[")return contCommasep(eltpattern,"]");if(type=="{")return contCommasep(proppattern,"}");}
function proppattern(type,value){if(type=="variable"&&!cx.stream.match(/^\s*:/,false)){register(value);return cont(maybeAssign);}
if(type=="variable")cx.marked="property";if(type=="spread")return cont(pattern);if(type=="}")return pass();if(type=="[")return cont(expression,expect(']'),expect(':'),proppattern);return cont(expect(":"),pattern,maybeAssign);}
function eltpattern(){return pass(pattern,maybeAssign)}
function maybeAssign(_type,value){if(value=="=")return cont(expressionNoComma);}
function vardefCont(type){if(type==",")return cont(vardef);}
function maybeelse(type,value){if(type=="keyword b"&&value=="else")return cont(pushlex("form","else"),statement,poplex);}
function forspec(type,value){if(value=="await")return cont(forspec);if(type=="(")return cont(pushlex(")"),forspec1,expect(")"),poplex);}
function forspec1(type){if(type=="var")return cont(vardef,expect(";"),forspec2);if(type==";")return cont(forspec2);if(type=="variable")return cont(formaybeinof);return pass(expression,expect(";"),forspec2);}
function formaybeinof(_type,value){if(value=="in"||value=="of"){cx.marked="keyword";return cont(expression);}
return cont(maybeoperatorComma,forspec2);}
function forspec2(type,value){if(type==";")return cont(forspec3);if(value=="in"||value=="of"){cx.marked="keyword";return cont(expression);}
return pass(expression,expect(";"),forspec3);}
function forspec3(type){if(type!=")")cont(expression);}
function functiondef(type,value){if(value=="*"){cx.marked="keyword";return cont(functiondef);}
if(type=="variable"){register(value);return cont(functiondef);}
if(type=="(")return cont(pushcontext,pushlex(")"),commasep(funarg,")"),poplex,mayberettype,statement,popcontext);if(isTS&&value=="<")return cont(pushlex(">"),commasep(typeparam,">"),poplex,functiondef)}
function funarg(type,value){if(value=="@")cont(expression,funarg)
if(type=="spread")return cont(funarg);if(isTS&&isModifier(value)){cx.marked="keyword";return cont(funarg);}
return pass(pattern,maybetype,maybeAssign);}
function classExpression(type,value){if(type=="variable")return className(type,value);return classNameAfter(type,value);}
function className(type,value){if(type=="variable"){register(value);return cont(classNameAfter);}}
function classNameAfter(type,value){if(value=="<")return cont(pushlex(">"),commasep(typeparam,">"),poplex,classNameAfter)
if(value=="extends"||value=="implements"||(isTS&&type==",")){if(value=="implements")cx.marked="keyword";return cont(isTS?typeexpr:expression,classNameAfter);}
if(type=="{")return cont(pushlex("}"),classBody,poplex);}
function classBody(type,value){if(type=="async"||(type=="variable"&&(value=="static"||value=="get"||value=="set"||(isTS&&isModifier(value)))&&cx.stream.match(/^\s+[\w$\xa1-\uffff]/,false))){cx.marked="keyword";return cont(classBody);}
if(type=="variable"||cx.style=="keyword"){cx.marked="property";return cont(isTS?classfield:functiondef,classBody);}
if(type=="[")
return cont(expression,maybetype,expect("]"),isTS?classfield:functiondef,classBody)
if(value=="*"){cx.marked="keyword";return cont(classBody);}
if(type==";")return cont(classBody);if(type=="}")return cont();if(value=="@")return cont(expression,classBody)}
function classfield(type,value){if(value=="?")return cont(classfield)
if(type==":")return cont(typeexpr,maybeAssign)
if(value=="=")return cont(expressionNoComma)
return pass(functiondef)}
function afterExport(type,value){if(value=="*"){cx.marked="keyword";return cont(maybeFrom,expect(";"));}
if(value=="default"){cx.marked="keyword";return cont(expression,expect(";"));}
if(type=="{")return cont(commasep(exportField,"}"),maybeFrom,expect(";"));return pass(statement);}
function exportField(type,value){if(value=="as"){cx.marked="keyword";return cont(expect("variable"));}
if(type=="variable")return pass(expressionNoComma,exportField);}
function afterImport(type){if(type=="string")return cont();if(type=="(")return pass(expression);return pass(importSpec,maybeMoreImports,maybeFrom);}
function importSpec(type,value){if(type=="{")return contCommasep(importSpec,"}");if(type=="variable")register(value);if(value=="*")cx.marked="keyword";return cont(maybeAs);}
function maybeMoreImports(type){if(type==",")return cont(importSpec,maybeMoreImports)}
function maybeAs(_type,value){if(value=="as"){cx.marked="keyword";return cont(importSpec);}}
function maybeFrom(_type,value){if(value=="from"){cx.marked="keyword";return cont(expression);}}
function arrayLiteral(type){if(type=="]")return cont();return pass(commasep(expressionNoComma,"]"));}
function enumdef(){return pass(pushlex("form"),pattern,expect("{"),pushlex("}"),commasep(enummember,"}"),poplex,poplex)}
function enummember(){return pass(pattern,maybeAssign);}
function isContinuedStatement(state,textAfter){return state.lastType=="operator"||state.lastType==","||isOperatorChar.test(textAfter.charAt(0))||/[,.]/.test(textAfter.charAt(0));}
function expressionAllowed(stream,state,backUp){return state.tokenize==tokenBase&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType)||(state.lastType=="quasi"&&/\{\s*$/.test(stream.string.slice(0,stream.pos-(backUp||0))))}
return{startState:function(basecolumn){var state={tokenize:tokenBase,lastType:"sof",cc:[],lexical:new JSLexical((basecolumn||0)-indentUnit,0,"block",false),localVars:parserConfig.localVars,context:parserConfig.localVars&&new Context(null,null,false),indented:basecolumn||0};if(parserConfig.globalVars&&typeof parserConfig.globalVars=="object")
state.globalVars=parserConfig.globalVars;return state;},token:function(stream,state){if(stream.sol()){if(!state.lexical.hasOwnProperty("align"))
state.lexical.align=false;state.indented=stream.indentation();findFatArrow(stream,state);}
if(state.tokenize!=tokenComment&&stream.eatSpace())return null;var style=state.tokenize(stream,state);if(type=="comment")return style;state.lastType=type=="operator"&&(content=="++"||content=="--")?"incdec":type;return parseJS(state,style,type,content,stream);},indent:function(state,textAfter){if(state.tokenize==tokenComment)return CodeMirror.Pass;if(state.tokenize!=tokenBase)return 0;var firstChar=textAfter&&textAfter.charAt(0),lexical=state.lexical,top
if(!/^\s*else\b/.test(textAfter))for(var i=state.cc.length-1;i>=0;--i){var c=state.cc[i];if(c==poplex)lexical=lexical.prev;else if(c!=maybeelse)break;}
while((lexical.type=="stat"||lexical.type=="form")&&(firstChar=="}"||((top=state.cc[state.cc.length-1])&&(top==maybeoperatorComma||top==maybeoperatorNoComma)&&!/^[,\.=+\-*:?[\(]/.test(textAfter))))
lexical=lexical.prev;if(statementIndent&&lexical.type==")"&&lexical.prev.type=="stat")
lexical=lexical.prev;var type=lexical.type,closing=firstChar==type;if(type=="vardef")return lexical.indented+(state.lastType=="operator"||state.lastType==","?lexical.info.length+1:0);else if(type=="form"&&firstChar=="{")return lexical.indented;else if(type=="form")return lexical.indented+indentUnit;else if(type=="stat")
return lexical.indented+(isContinuedStatement(state,textAfter)?statementIndent||indentUnit:0);else if(lexical.info=="switch"&&!closing&&parserConfig.doubleIndentSwitch!=false)
return lexical.indented+(/^(?:case|default)\b/.test(textAfter)?indentUnit:2*indentUnit);else if(lexical.align)return lexical.column+(closing?0:1);else return lexical.indented+(closing?0:indentUnit);},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:jsonMode?null:"/*",blockCommentEnd:jsonMode?null:"*/",blockCommentContinue:jsonMode?null:" * ",lineComment:jsonMode?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:jsonMode?"json":"javascript",jsonldMode:jsonldMode,jsonMode:jsonMode,expressionAllowed:expressionAllowed,skipExpression:function(state){var top=state.cc[state.cc.length-1]
if(top==expression||top==expressionNoComma)state.cc.pop()}};});CodeMirror.registerHelper("wordChars","javascript",/[\w$]/);CodeMirror.defineMIME("text/javascript","javascript");CodeMirror.defineMIME("text/ecmascript","javascript");CodeMirror.defineMIME("application/javascript","javascript");CodeMirror.defineMIME("application/x-javascript","javascript");CodeMirror.defineMIME("application/ecmascript","javascript");CodeMirror.defineMIME("application/json",{name:"javascript",json:true});CodeMirror.defineMIME("application/x-json",{name:"javascript",json:true});CodeMirror.defineMIME("application/ld+json",{name:"javascript",jsonld:true});CodeMirror.defineMIME("text/typescript",{name:"javascript",typescript:true});CodeMirror.defineMIME("application/typescript",{name:"javascript",typescript:true});});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";var htmlConfig={autoSelfClosers:{'area':true,'base':true,'br':true,'col':true,'command':true,'embed':true,'frame':true,'hr':true,'img':true,'input':true,'keygen':true,'link':true,'meta':true,'param':true,'source':true,'track':true,'wbr':true,'menuitem':true},implicitlyClosed:{'dd':true,'li':true,'optgroup':true,'option':true,'p':true,'rp':true,'rt':true,'tbody':true,'td':true,'tfoot':true,'th':true,'tr':true},contextGrabbers:{'dd':{'dd':true,'dt':true},'dt':{'dd':true,'dt':true},'li':{'li':true},'option':{'option':true,'optgroup':true},'optgroup':{'optgroup':true},'p':{'address':true,'article':true,'aside':true,'blockquote':true,'dir':true,'div':true,'dl':true,'fieldset':true,'footer':true,'form':true,'h1':true,'h2':true,'h3':true,'h4':true,'h5':true,'h6':true,'header':true,'hgroup':true,'hr':true,'menu':true,'nav':true,'ol':true,'p':true,'pre':true,'section':true,'table':true,'ul':true},'rp':{'rp':true,'rt':true},'rt':{'rp':true,'rt':true},'tbody':{'tbody':true,'tfoot':true},'td':{'td':true,'th':true},'tfoot':{'tbody':true},'th':{'td':true,'th':true},'thead':{'tbody':true,'tfoot':true},'tr':{'tr':true}},doNotIndent:{"pre":true},allowUnquoted:true,allowMissing:true,caseFold:true}
var xmlConfig={autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:false,allowMissing:false,allowMissingTagName:false,caseFold:false}
CodeMirror.defineMode("xml",function(editorConf,config_){var indentUnit=editorConf.indentUnit
var config={}
var defaults=config_.htmlMode?htmlConfig:xmlConfig
for(var prop in defaults)config[prop]=defaults[prop]
for(var prop in config_)config[prop]=config_[prop]
var type,setStyle;function inText(stream,state){function chain(parser){state.tokenize=parser;return parser(stream,state);}
var ch=stream.next();if(ch=="<"){if(stream.eat("!")){if(stream.eat("[")){if(stream.match("CDATA["))return chain(inBlock("atom","]]>"));else return null;}else if(stream.match("--")){return chain(inBlock("comment","-->"));}else if(stream.match("DOCTYPE",true,true)){stream.eatWhile(/[\w\._\-]/);return chain(doctype(1));}else{return null;}}else if(stream.eat("?")){stream.eatWhile(/[\w\._\-]/);state.tokenize=inBlock("meta","?>");return"meta";}else{type=stream.eat("/")?"closeTag":"openTag";state.tokenize=inTag;return"tag bracket";}}else if(ch=="&"){var ok;if(stream.eat("#")){if(stream.eat("x")){ok=stream.eatWhile(/[a-fA-F\d]/)&&stream.eat(";");}else{ok=stream.eatWhile(/[\d]/)&&stream.eat(";");}}else{ok=stream.eatWhile(/[\w\.\-:]/)&&stream.eat(";");}
return ok?"atom":"error";}else{stream.eatWhile(/[^&<]/);return null;}}
inText.isInText=true;function inTag(stream,state){var ch=stream.next();if(ch==">"||(ch=="/"&&stream.eat(">"))){state.tokenize=inText;type=ch==">"?"endTag":"selfcloseTag";return"tag bracket";}else if(ch=="="){type="equals";return null;}else if(ch=="<"){state.tokenize=inText;state.state=baseState;state.tagName=state.tagStart=null;var next=state.tokenize(stream,state);return next?next+" tag error":"tag error";}else if(/[\'\"]/.test(ch)){state.tokenize=inAttribute(ch);state.stringStartCol=stream.column();return state.tokenize(stream,state);}else{stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);return"word";}}
function inAttribute(quote){var closure=function(stream,state){while(!stream.eol()){if(stream.next()==quote){state.tokenize=inTag;break;}}
return"string";};closure.isInAttribute=true;return closure;}
function inBlock(style,terminator){return function(stream,state){while(!stream.eol()){if(stream.match(terminator)){state.tokenize=inText;break;}
stream.next();}
return style;}}
function doctype(depth){return function(stream,state){var ch;while((ch=stream.next())!=null){if(ch=="<"){state.tokenize=doctype(depth+1);return state.tokenize(stream,state);}else if(ch==">"){if(depth==1){state.tokenize=inText;break;}else{state.tokenize=doctype(depth-1);return state.tokenize(stream,state);}}}
return"meta";};}
function Context(state,tagName,startOfLine){this.prev=state.context;this.tagName=tagName;this.indent=state.indented;this.startOfLine=startOfLine;if(config.doNotIndent.hasOwnProperty(tagName)||(state.context&&state.context.noIndent))
this.noIndent=true;}
function popContext(state){if(state.context)state.context=state.context.prev;}
function maybePopContext(state,nextTagName){var parentTagName;while(true){if(!state.context){return;}
parentTagName=state.context.tagName;if(!config.contextGrabbers.hasOwnProperty(parentTagName)||!config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)){return;}
popContext(state);}}
function baseState(type,stream,state){if(type=="openTag"){state.tagStart=stream.column();return tagNameState;}else if(type=="closeTag"){return closeTagNameState;}else{return baseState;}}
function tagNameState(type,stream,state){if(type=="word"){state.tagName=stream.current();setStyle="tag";return attrState;}else if(config.allowMissingTagName&&type=="endTag"){setStyle="tag bracket";return attrState(type,stream,state);}else{setStyle="error";return tagNameState;}}
function closeTagNameState(type,stream,state){if(type=="word"){var tagName=stream.current();if(state.context&&state.context.tagName!=tagName&&config.implicitlyClosed.hasOwnProperty(state.context.tagName))
popContext(state);if((state.context&&state.context.tagName==tagName)||config.matchClosing===false){setStyle="tag";return closeState;}else{setStyle="tag error";return closeStateErr;}}else if(config.allowMissingTagName&&type=="endTag"){setStyle="tag bracket";return closeState(type,stream,state);}else{setStyle="error";return closeStateErr;}}
function closeState(type,_stream,state){if(type!="endTag"){setStyle="error";return closeState;}
popContext(state);return baseState;}
function closeStateErr(type,stream,state){setStyle="error";return closeState(type,stream,state);}
function attrState(type,_stream,state){if(type=="word"){setStyle="attribute";return attrEqState;}else if(type=="endTag"||type=="selfcloseTag"){var tagName=state.tagName,tagStart=state.tagStart;state.tagName=state.tagStart=null;if(type=="selfcloseTag"||config.autoSelfClosers.hasOwnProperty(tagName)){maybePopContext(state,tagName);}else{maybePopContext(state,tagName);state.context=new Context(state,tagName,tagStart==state.indented);}
return baseState;}
setStyle="error";return attrState;}
function attrEqState(type,stream,state){if(type=="equals")return attrValueState;if(!config.allowMissing)setStyle="error";return attrState(type,stream,state);}
function attrValueState(type,stream,state){if(type=="string")return attrContinuedState;if(type=="word"&&config.allowUnquoted){setStyle="string";return attrState;}
setStyle="error";return attrState(type,stream,state);}
function attrContinuedState(type,stream,state){if(type=="string")return attrContinuedState;return attrState(type,stream,state);}
return{startState:function(baseIndent){var state={tokenize:inText,state:baseState,indented:baseIndent||0,tagName:null,tagStart:null,context:null}
if(baseIndent!=null)state.baseIndent=baseIndent
return state},token:function(stream,state){if(!state.tagName&&stream.sol())
state.indented=stream.indentation();if(stream.eatSpace())return null;type=null;var style=state.tokenize(stream,state);if((style||type)&&style!="comment"){setStyle=null;state.state=state.state(type||style,stream,state);if(setStyle)
style=setStyle=="error"?style+" error":setStyle;}
return style;},indent:function(state,textAfter,fullLine){var context=state.context;if(state.tokenize.isInAttribute){if(state.tagStart==state.indented)
return state.stringStartCol+1;else
return state.indented+indentUnit;}
if(context&&context.noIndent)return CodeMirror.Pass;if(state.tokenize!=inTag&&state.tokenize!=inText)
return fullLine?fullLine.match(/^(\s*)/)[0].length:0;if(state.tagName){if(config.multilineTagIndentPastTag!==false)
return state.tagStart+state.tagName.length+2;else
return state.tagStart+indentUnit*(config.multilineTagIndentFactor||1);}
if(config.alignCDATA&&/<!\[CDATA\[/.test(textAfter))return 0;var tagAfter=textAfter&&/^<(\/)?([\w_:\.-]*)/.exec(textAfter);if(tagAfter&&tagAfter[1]){while(context){if(context.tagName==tagAfter[2]){context=context.prev;break;}else if(config.implicitlyClosed.hasOwnProperty(context.tagName)){context=context.prev;}else{break;}}}else if(tagAfter){while(context){var grabbers=config.contextGrabbers[context.tagName];if(grabbers&&grabbers.hasOwnProperty(tagAfter[2]))
context=context.prev;else
break;}}
while(context&&context.prev&&!context.startOfLine)
context=context.prev;if(context)return context.indent+indentUnit;else return state.baseIndent||0;},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:config.htmlMode?"html":"xml",helperType:config.htmlMode?"html":"xml",skipAttribute:function(state){if(state.state==attrValueState)
state.state=attrState}};});CodeMirror.defineMIME("text/xml","xml");CodeMirror.defineMIME("application/xml","xml");if(!CodeMirror.mimeModes.hasOwnProperty("text/html"))
CodeMirror.defineMIME("text/html",{name:"xml",htmlMode:true});});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"),require("../xml/xml"),require("../javascript/javascript"),require("../css/css"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror","../xml/xml","../javascript/javascript","../css/css"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";var defaultTags={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]};function maybeBackup(stream,pat,style){var cur=stream.current(),close=cur.search(pat);if(close>-1){stream.backUp(cur.length-close);}else if(cur.match(/<\/?$/)){stream.backUp(cur.length);if(!stream.match(pat,false))stream.match(cur);}
return style;}
var attrRegexpCache={};function getAttrRegexp(attr){var regexp=attrRegexpCache[attr];if(regexp)return regexp;return attrRegexpCache[attr]=new RegExp("\\s+"+attr+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*");}
function getAttrValue(text,attr){var match=text.match(getAttrRegexp(attr))
return match?/^\s*(.*?)\s*$/.exec(match[2])[1]:""}
function getTagRegexp(tagName,anchored){return new RegExp((anchored?"^":"")+"<\/\s*"+tagName+"\s*>","i");}
function addTags(from,to){for(var tag in from){var dest=to[tag]||(to[tag]=[]);var source=from[tag];for(var i=source.length-1;i>=0;i--)
dest.unshift(source[i])}}
function findMatchingMode(tagInfo,tagText){for(var i=0;i<tagInfo.length;i++){var spec=tagInfo[i];if(!spec[0]||spec[1].test(getAttrValue(tagText,spec[0])))return spec[2];}}
CodeMirror.defineMode("htmlmixed",function(config,parserConfig){var htmlMode=CodeMirror.getMode(config,{name:"xml",htmlMode:true,multilineTagIndentFactor:parserConfig.multilineTagIndentFactor,multilineTagIndentPastTag:parserConfig.multilineTagIndentPastTag});var tags={};var configTags=parserConfig&&parserConfig.tags,configScript=parserConfig&&parserConfig.scriptTypes;addTags(defaultTags,tags);if(configTags)addTags(configTags,tags);if(configScript)for(var i=configScript.length-1;i>=0;i--)
tags.script.unshift(["type",configScript[i].matches,configScript[i].mode])
function html(stream,state){var style=htmlMode.token(stream,state.htmlState),tag=/\btag\b/.test(style),tagName
if(tag&&!/[<>\s\/]/.test(stream.current())&&(tagName=state.htmlState.tagName&&state.htmlState.tagName.toLowerCase())&&tags.hasOwnProperty(tagName)){state.inTag=tagName+" "}else if(state.inTag&&tag&&/>$/.test(stream.current())){var inTag=/^([\S]+) (.*)/.exec(state.inTag)
state.inTag=null
var modeSpec=stream.current()==">"&&findMatchingMode(tags[inTag[1]],inTag[2])
var mode=CodeMirror.getMode(config,modeSpec)
var endTagA=getTagRegexp(inTag[1],true),endTag=getTagRegexp(inTag[1],false);state.token=function(stream,state){if(stream.match(endTagA,false)){state.token=html;state.localState=state.localMode=null;return null;}
return maybeBackup(stream,endTag,state.localMode.token(stream,state.localState));};state.localMode=mode;state.localState=CodeMirror.startState(mode,htmlMode.indent(state.htmlState,""));}else if(state.inTag){state.inTag+=stream.current()
if(stream.eol())state.inTag+=" "}
return style;};return{startState:function(){var state=CodeMirror.startState(htmlMode);return{token:html,inTag:null,localMode:null,localState:null,htmlState:state};},copyState:function(state){var local;if(state.localState){local=CodeMirror.copyState(state.localMode,state.localState);}
return{token:state.token,inTag:state.inTag,localMode:state.localMode,localState:local,htmlState:CodeMirror.copyState(htmlMode,state.htmlState)};},token:function(stream,state){return state.token(stream,state);},indent:function(state,textAfter,line){if(!state.localMode||/^\s*<\//.test(textAfter))
return htmlMode.indent(state.htmlState,textAfter);else if(state.localMode.indent)
return state.localMode.indent(state.localState,textAfter,line);else
return CodeMirror.Pass;},innerMode:function(state){return{state:state.localState||state.htmlState,mode:state.localMode||htmlMode};}};},"xml","javascript","css");CodeMirror.defineMIME("text/html","htmlmixed");});;(function(mod){if(typeof exports=="object"&&typeof module=="object")
mod(require("../../lib/codemirror"),require("../htmlmixed/htmlmixed"),require("../../addon/mode/multiplex"));else if(typeof define=="function"&&define.amd)
define(["../../lib/codemirror","../htmlmixed/htmlmixed","../../addon/mode/multiplex"],mod);else
mod(CodeMirror);})(function(CodeMirror){"use strict";CodeMirror.defineMode("htmlembedded",function(config,parserConfig){var closeComment=parserConfig.closeComment||"--%>"
return CodeMirror.multiplexingMode(CodeMirror.getMode(config,"htmlmixed"),{open:parserConfig.openComment||"<%--",close:closeComment,delimStyle:"comment",mode:{token:function(stream){stream.skipTo(closeComment)||stream.skipToEnd()
return"comment"}}},{open:parserConfig.open||parserConfig.scriptStartRegex||"<%",close:parserConfig.close||parserConfig.scriptEndRegex||"%>",mode:CodeMirror.getMode(config,parserConfig.scriptingModeSpec)});},"htmlmixed");CodeMirror.defineMIME("application/x-ejs",{name:"htmlembedded",scriptingModeSpec:"javascript"});CodeMirror.defineMIME("application/x-aspx",{name:"htmlembedded",scriptingModeSpec:"text/x-csharp"});CodeMirror.defineMIME("application/x-jsp",{name:"htmlembedded",scriptingModeSpec:"text/x-java"});CodeMirror.defineMIME("application/x-erb",{name:"htmlembedded",scriptingModeSpec:"ruby"});});;TextEditor.CodeMirrorUtils={};TextEditor.CodeMirrorUtils.toPos=function(range){return{start:new CodeMirror.Pos(range.startLine,range.startColumn),end:new CodeMirror.Pos(range.endLine,range.endColumn)};};TextEditor.CodeMirrorUtils.toRange=function(start,end){return new TextUtils.TextRange(start.line,start.ch,end.line,end.ch);};TextEditor.CodeMirrorUtils.changeObjectToEditOperation=function(changeObject){const oldRange=TextEditor.CodeMirrorUtils.toRange(changeObject.from,changeObject.to);const newRange=oldRange.clone();const linesAdded=changeObject.text.length;if(linesAdded===0){newRange.endLine=newRange.startLine;newRange.endColumn=newRange.startColumn;}else if(linesAdded===1){newRange.endLine=newRange.startLine;newRange.endColumn=newRange.startColumn+changeObject.text[0].length;}else{newRange.endLine=newRange.startLine+linesAdded-1;newRange.endColumn=changeObject.text[linesAdded-1].length;}
return{oldRange:oldRange,newRange:newRange};};TextEditor.CodeMirrorUtils.pullLines=function(codeMirror,linesCount){const lines=[];codeMirror.eachLine(0,linesCount,onLineHandle);return lines;function onLineHandle(lineHandle){lines.push(lineHandle.text);}};TextEditor.CodeMirrorUtils.TokenizerFactory=class{createTokenizer(mimeType){const mode=CodeMirror.getMode({indentUnit:2},mimeType);const state=CodeMirror.startState(mode);function tokenize(line,callback){const stream=new CodeMirror.StringStream(line);while(!stream.eol()){const style=mode.token(stream,state);const value=stream.current();callback(value,style,stream.start,stream.start+value.length);stream.start=stream.pos;}}
return tokenize;}};;TextEditor.TextEditorAutocompleteController=class{constructor(textEditor,codeMirror,config){this._textEditor=textEditor;this._codeMirror=codeMirror;this._config=config;this._initialized=false;this._onScroll=this._onScroll.bind(this);this._onCursorActivity=this._onCursorActivity.bind(this);this._changes=this._changes.bind(this);this._blur=this._blur.bind(this);this._beforeChange=this._beforeChange.bind(this);this._mouseDown=()=>{this.clearAutocomplete();this._tooltipGlassPane.hide();};this._codeMirror.on('changes',this._changes);this._lastHintText='';this._suggestBox=null;this._currentSuggestion=null;this._hintElement=createElementWithClass('span','auto-complete-text');this._tooltipGlassPane=new UI.GlassPane();this._tooltipGlassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);this._tooltipGlassPane.setOutsideClickCallback(this._tooltipGlassPane.hide.bind(this._tooltipGlassPane));this._tooltipElement=createElementWithClass('div','autocomplete-tooltip');const shadowRoot=UI.createShadowRootWithCoreStyles(this._tooltipGlassPane.contentElement,'text_editor/autocompleteTooltip.css');shadowRoot.appendChild(this._tooltipElement);}
_initializeIfNeeded(){if(this._initialized)
return;this._initialized=true;this._codeMirror.on('scroll',this._onScroll);this._codeMirror.on('cursorActivity',this._onCursorActivity);this._codeMirror.on('mousedown',this._mouseDown);this._codeMirror.on('blur',this._blur);if(this._config.isWordChar){this._codeMirror.on('beforeChange',this._beforeChange);this._dictionary=new Common.TextDictionary();this._addWordsFromText(this._codeMirror.getValue());}}
dispose(){this._codeMirror.off('changes',this._changes);if(this._initialized){this._codeMirror.off('scroll',this._onScroll);this._codeMirror.off('cursorActivity',this._onCursorActivity);this._codeMirror.off('mousedown',this._mouseDown);this._codeMirror.off('blur',this._blur);}
if(this._dictionary){this._codeMirror.off('beforeChange',this._beforeChange);this._dictionary.reset();}}
_beforeChange(codeMirror,changeObject){this._updatedLines=this._updatedLines||{};for(let i=changeObject.from.line;i<=changeObject.to.line;++i){if(this._updatedLines[i]===undefined)
this._updatedLines[i]=this._codeMirror.getLine(i);}}
_addWordsFromText(text){TextUtils.TextUtils.textToWords(text,(this._config.isWordChar),addWord.bind(this));function addWord(word){if(word.length&&(word[0]<'0'||word[0]>'9'))
this._dictionary.addWord(word);}}
_removeWordsFromText(text){TextUtils.TextUtils.textToWords(text,(this._config.isWordChar),word=>this._dictionary.removeWord(word));}
_substituteRange(lineNumber,columnNumber){let range=this._config.substituteRangeCallback?this._config.substituteRangeCallback(lineNumber,columnNumber):null;if(!range&&this._config.isWordChar)
range=this._textEditor.wordRangeForCursorPosition(lineNumber,columnNumber,this._config.isWordChar);return range;}
_wordsWithQuery(queryRange,substituteRange,force){const external=this._config.suggestionsCallback?this._config.suggestionsCallback(queryRange,substituteRange,force):null;if(external)
return external;if(!this._dictionary||(!force&&queryRange.isEmpty()))
return Promise.resolve([]);let completions=this._dictionary.wordsWithPrefix(this._textEditor.text(queryRange));const substituteWord=this._textEditor.text(substituteRange);if(this._dictionary.wordCount(substituteWord)===1)
completions=completions.filter(word=>word!==substituteWord);completions.sort((a,b)=>this._dictionary.wordCount(b)-this._dictionary.wordCount(a)||a.length-b.length);return Promise.resolve(completions.map(item=>({text:item})));}
_changes(codeMirror,changes){if(!changes.length)
return;if(this._dictionary&&this._updatedLines){for(const lineNumber in this._updatedLines)
this._removeWordsFromText(this._updatedLines[lineNumber]);delete this._updatedLines;const linesToUpdate={};for(let changeIndex=0;changeIndex<changes.length;++changeIndex){const changeObject=changes[changeIndex];const editInfo=TextEditor.CodeMirrorUtils.changeObjectToEditOperation(changeObject);for(let i=editInfo.newRange.startLine;i<=editInfo.newRange.endLine;++i)
linesToUpdate[i]=this._codeMirror.getLine(i);}
for(const lineNumber in linesToUpdate)
this._addWordsFromText(linesToUpdate[lineNumber]);}
let singleCharInput=false;let singleCharDelete=false;const cursor=this._codeMirror.getCursor('head');for(let changeIndex=0;changeIndex<changes.length;++changeIndex){const changeObject=changes[changeIndex];if(changeObject.origin==='+input'&&changeObject.text.length===1&&changeObject.text[0].length===1&&changeObject.to.line===cursor.line&&changeObject.to.ch+1===cursor.ch){singleCharInput=true;break;}
if(changeObject.origin==='+delete'&&changeObject.removed.length===1&&changeObject.removed[0].length===1&&changeObject.to.line===cursor.line&&changeObject.to.ch-1===cursor.ch){singleCharDelete=true;break;}}
if(this._queryRange){if(singleCharInput)
this._queryRange.endColumn++;else if(singleCharDelete)
this._queryRange.endColumn--;if(singleCharDelete||singleCharInput)
this._setHint(this._lastHintText);}
if(singleCharInput||singleCharDelete)
setImmediate(this.autocomplete.bind(this));else
this.clearAutocomplete();}
_blur(){this.clearAutocomplete();}
_validateSelectionsContexts(mainSelection){const selections=this._codeMirror.listSelections();if(selections.length<=1)
return true;const mainSelectionContext=this._textEditor.text(mainSelection);for(let i=0;i<selections.length;++i){const wordRange=this._substituteRange(selections[i].head.line,selections[i].head.ch);if(!wordRange)
return false;const context=this._textEditor.text(wordRange);if(context!==mainSelectionContext)
return false;}
return true;}
autocomplete(force){this._initializeIfNeeded();if(this._codeMirror.somethingSelected()){this._hideSuggestBox();return;}
const cursor=this._codeMirror.getCursor('head');const substituteRange=this._substituteRange(cursor.line,cursor.ch);if(!substituteRange||!this._validateSelectionsContexts(substituteRange)){this._hideSuggestBox();return;}
const queryRange=substituteRange.clone();queryRange.endColumn=cursor.ch;const query=this._textEditor.text(queryRange);let hadSuggestBox=false;if(this._suggestBox)
hadSuggestBox=true;this._wordsWithQuery(queryRange,substituteRange,force).then(wordsAcquired.bind(this));function wordsAcquired(wordsWithQuery){if(!wordsWithQuery.length||(wordsWithQuery.length===1&&query===wordsWithQuery[0].text)||(!this._suggestBox&&hadSuggestBox)){this._hideSuggestBox();this._onSuggestionsShownForTest([]);return;}
if(!this._suggestBox){this._suggestBox=new UI.SuggestBox(this,20);if(this._config.anchorBehavior)
this._suggestBox.setAnchorBehavior(this._config.anchorBehavior);}
const oldQueryRange=this._queryRange;this._queryRange=queryRange;if(!oldQueryRange||queryRange.startLine!==oldQueryRange.startLine||queryRange.startColumn!==oldQueryRange.startColumn)
this._updateAnchorBox();this._suggestBox.updateSuggestions(this._anchorBox,wordsWithQuery,true,!this._isCursorAtEndOfLine(),query);if(this._suggestBox.visible)
this._tooltipGlassPane.hide();this._onSuggestionsShownForTest(wordsWithQuery);}}
_setHint(hint){const query=this._textEditor.text(this._queryRange);if(!hint||!this._isCursorAtEndOfLine()||!hint.startsWith(query)){this._clearHint();return;}
const suffix=hint.substring(query.length).split('\n')[0];this._hintElement.textContent=suffix.trimEnd(10000);const cursor=this._codeMirror.getCursor('to');if(this._hintMarker){const position=this._hintMarker.position();if(!position||!position.equal(TextUtils.TextRange.createFromLocation(cursor.line,cursor.ch))){this._hintMarker.clear();this._hintMarker=null;}}
if(!this._hintMarker){this._hintMarker=this._textEditor.addBookmark(cursor.line,cursor.ch,this._hintElement,TextEditor.TextEditorAutocompleteController.HintBookmark,true);}else if(this._lastHintText!==hint){this._hintMarker.refresh();}
this._lastHintText=hint;}
_clearHint(){if(!this._hintElement.textContent)
return;this._lastHintText='';this._hintElement.textContent='';if(this._hintMarker)
this._hintMarker.refresh();}
_onSuggestionsShownForTest(suggestions){}
_onSuggestionsHiddenForTest(){}
clearAutocomplete(){this._tooltipGlassPane.hide();this._hideSuggestBox();}
_hideSuggestBox(){if(!this._suggestBox)
return;this._suggestBox.hide();this._suggestBox=null;this._queryRange=null;this._anchorBox=null;this._currentSuggestion=null;this._textEditor.dispatchEventToListeners(UI.TextEditor.Events.SuggestionChanged);this._clearHint();this._onSuggestionsHiddenForTest();}
keyDown(event){if(this._tooltipGlassPane.isShowing()&&event.keyCode===UI.KeyboardShortcut.Keys.Esc.code){this._tooltipGlassPane.hide();return true;}
if(!this._suggestBox)
return false;switch(event.keyCode){case UI.KeyboardShortcut.Keys.Tab.code:this._suggestBox.acceptSuggestion();this.clearAutocomplete();return true;case UI.KeyboardShortcut.Keys.End.code:case UI.KeyboardShortcut.Keys.Right.code:if(this._isCursorAtEndOfLine()){this._suggestBox.acceptSuggestion();this.clearAutocomplete();return true;}else{this.clearAutocomplete();return false;}
case UI.KeyboardShortcut.Keys.Left.code:case UI.KeyboardShortcut.Keys.Home.code:this.clearAutocomplete();return false;case UI.KeyboardShortcut.Keys.Esc.code:this.clearAutocomplete();return true;}
return this._suggestBox.keyPressed(event);}
_isCursorAtEndOfLine(){const cursor=this._codeMirror.getCursor('to');return cursor.ch===this._codeMirror.getLine(cursor.line).length;}
applySuggestion(suggestion,isIntermediateSuggestion){const oldSuggestion=this._currentSuggestion;this._currentSuggestion=suggestion;this._setHint(suggestion?suggestion.text:'');if((oldSuggestion?oldSuggestion.text:'')!==(suggestion?suggestion.text:''))
this._textEditor.dispatchEventToListeners(UI.TextEditor.Events.SuggestionChanged);}
acceptSuggestion(){const selections=this._codeMirror.listSelections().slice();const queryLength=this._queryRange.endColumn-this._queryRange.startColumn;const suggestion=this._currentSuggestion.text;this._codeMirror.operation(()=>{for(let i=selections.length-1;i>=0;--i){const start=selections[i].head;const end=new CodeMirror.Pos(start.line,start.ch-queryLength);this._codeMirror.replaceRange(suggestion,start,end,'+autocomplete');}});}
textWithCurrentSuggestion(){if(!this._queryRange||this._currentSuggestion===null)
return this._codeMirror.getValue();const selections=this._codeMirror.listSelections().slice();let last={line:0,column:0};let text='';const queryLength=this._queryRange.endColumn-this._queryRange.startColumn;for(const selection of selections){const range=new TextUtils.TextRange(last.line,last.column,selection.head.line,selection.head.ch-queryLength);text+=this._textEditor.text(range);text+=this._currentSuggestion.text;last={line:selection.head.line,column:selection.head.ch};}
const range=new TextUtils.TextRange(last.line,last.column,Infinity,Infinity);text+=this._textEditor.text(range);return text;}
_onScroll(){this._tooltipGlassPane.hide();if(!this._suggestBox)
return;const cursor=this._codeMirror.getCursor();const scrollInfo=this._codeMirror.getScrollInfo();const topmostLineNumber=this._codeMirror.lineAtHeight(scrollInfo.top,'local');const bottomLine=this._codeMirror.lineAtHeight(scrollInfo.top+scrollInfo.clientHeight,'local');if(cursor.line<topmostLineNumber||cursor.line>bottomLine){this.clearAutocomplete();}else{this._updateAnchorBox();this._suggestBox.setPosition(this._anchorBox);}}
async _updateTooltip(){const cursor=this._codeMirror.getCursor();const tooltip=this._config.tooltipCallback?await this._config.tooltipCallback(cursor.line,cursor.ch):null;const newCursor=this._codeMirror.getCursor();if(newCursor.line!==cursor.line&&newCursor.ch!==cursor.ch)
return;if(this._suggestBox&&this._suggestBox.visible)
return;if(!tooltip){this._tooltipGlassPane.hide();return;}
const metrics=this._textEditor.cursorPositionToCoordinates(cursor.line,cursor.ch);if(!metrics){this._tooltipGlassPane.hide();return;}
this._tooltipGlassPane.setContentAnchorBox(new AnchorBox(metrics.x,metrics.y,0,metrics.height));this._tooltipElement.removeChildren();this._tooltipElement.appendChild(tooltip);this._tooltipGlassPane.show((this._textEditor.element.ownerDocument));}
_onCursorActivity(){this._updateTooltip();if(!this._suggestBox)
return;const cursor=this._codeMirror.getCursor();let shouldCloseAutocomplete=!(cursor.line===this._queryRange.startLine&&this._queryRange.startColumn<=cursor.ch&&cursor.ch<=this._queryRange.endColumn);if(cursor.line===this._queryRange.startLine&&cursor.ch===this._queryRange.endColumn+1){const line=this._codeMirror.getLine(cursor.line);shouldCloseAutocomplete=this._config.isWordChar?!this._config.isWordChar(line.charAt(cursor.ch-1)):false;}
if(shouldCloseAutocomplete)
this.clearAutocomplete();this._onCursorActivityHandledForTest();}
_onCursorActivityHandledForTest(){}
_updateAnchorBox(){const line=this._queryRange.startLine;const column=this._queryRange.startColumn;const metrics=this._textEditor.cursorPositionToCoordinates(line,column);this._anchorBox=metrics?new AnchorBox(metrics.x,metrics.y,0,metrics.height):null;}};TextEditor.TextEditorAutocompleteController.HintBookmark=Symbol('hint');;TextEditor.CodeMirrorTextEditor=class extends UI.VBox{constructor(options){super();this._options=options;this.registerRequiredCSS('cm/codemirror.css');this.registerRequiredCSS('text_editor/cmdevtools.css');this._codeMirror=new CodeMirror(this.element,{lineNumbers:options.lineNumbers,matchBrackets:true,smartIndent:true,styleSelectedText:true,electricChars:true,styleActiveLine:true,indentUnit:4,lineWrapping:options.lineWrapping,lineWiseCopyCut:false,tabIndex:0,pollInterval:Math.pow(2,31)-1,inputStyle:'devToolsAccessibleTextArea'});this._codeMirrorElement=this.element.lastElementChild;this._codeMirror._codeMirrorTextEditor=this;CodeMirror.keyMap['devtools-common']={'Left':'goCharLeft','Right':'goCharRight','Up':'goLineUp','Down':'goLineDown','End':'goLineEnd','Home':'goLineStartSmart','PageUp':'goSmartPageUp','PageDown':'goSmartPageDown','Delete':'delCharAfter','Backspace':'delCharBefore','Tab':'defaultTab','Shift-Tab':'indentLessOrPass','Enter':'newlineAndIndent','Ctrl-Space':'autocomplete','Esc':'dismiss','Ctrl-M':'gotoMatchingBracket'};CodeMirror.keyMap['devtools-pc']={'Ctrl-A':'selectAll','Ctrl-Z':'undoAndReveal','Shift-Ctrl-Z':'redoAndReveal','Ctrl-Y':'redo','Ctrl-Home':'goDocStart','Ctrl-Up':'goDocStart','Ctrl-End':'goDocEnd','Ctrl-Down':'goDocEnd','Ctrl-Left':'goGroupLeft','Ctrl-Right':'goGroupRight','Alt-Left':'moveCamelLeft','Alt-Right':'moveCamelRight','Shift-Alt-Left':'selectCamelLeft','Shift-Alt-Right':'selectCamelRight','Ctrl-Backspace':'delGroupBefore','Ctrl-Delete':'delGroupAfter','Ctrl-/':'toggleComment','Ctrl-D':'selectNextOccurrence','Ctrl-U':'undoLastSelection',fallthrough:'devtools-common'};CodeMirror.keyMap['devtools-mac']={'Cmd-A':'selectAll','Cmd-Z':'undoAndReveal','Shift-Cmd-Z':'redoAndReveal','Cmd-Up':'goDocStart','Cmd-Down':'goDocEnd','Alt-Left':'goGroupLeft','Alt-Right':'goGroupRight','Ctrl-Left':'moveCamelLeft','Ctrl-Right':'moveCamelRight','Ctrl-A':'goLineLeft','Ctrl-E':'goLineRight','Ctrl-B':'goCharLeft','Ctrl-F':'goCharRight','Ctrl-Alt-B':'goGroupLeft','Ctrl-Alt-F':'goGroupRight','Ctrl-H':'delCharBefore','Ctrl-D':'delCharAfter','Ctrl-K':'killLine','Ctrl-T':'transposeChars','Shift-Ctrl-Left':'selectCamelLeft','Shift-Ctrl-Right':'selectCamelRight','Cmd-Left':'goLineStartSmart','Cmd-Right':'goLineEnd','Cmd-Backspace':'delLineLeft','Alt-Backspace':'delGroupBefore','Alt-Delete':'delGroupAfter','Cmd-/':'toggleComment','Cmd-D':'selectNextOccurrence','Cmd-U':'undoLastSelection',fallthrough:'devtools-common'};if(options.bracketMatchingSetting)
options.bracketMatchingSetting.addChangeListener(this._enableBracketMatchingIfNeeded,this);this._enableBracketMatchingIfNeeded();this._codeMirror.setOption('keyMap',Host.isMac()?'devtools-mac':'devtools-pc');this._codeMirror.setOption('flattenSpans',false);let maxHighlightLength=options.maxHighlightLength;if(typeof maxHighlightLength!=='number')
maxHighlightLength=TextEditor.CodeMirrorTextEditor.maxHighlightLength;this._codeMirror.setOption('maxHighlightLength',maxHighlightLength);this._codeMirror.setOption('mode',null);this._codeMirror.setOption('crudeMeasuringFrom',1000);this._shouldClearHistory=true;this._lineSeparator='\n';TextEditor.CodeMirrorTextEditor._fixWordMovement(this._codeMirror);this._selectNextOccurrenceController=new TextEditor.CodeMirrorTextEditor.SelectNextOccurrenceController(this,this._codeMirror);this._codeMirror.on('changes',this._changes.bind(this));this._codeMirror.on('beforeSelectionChange',this._beforeSelectionChange.bind(this));this._codeMirror.on('cursorActivity',()=>{this.dispatchEventToListeners(UI.TextEditor.Events.CursorChanged);});this.element.style.overflow='hidden';this._codeMirrorElement.classList.add('source-code');this._codeMirrorElement.classList.add('fill');this._decorations=new Multimap();this.element.addEventListener('keydown',this._handleKeyDown.bind(this),true);this.element.addEventListener('keydown',this._handlePostKeyDown.bind(this),false);this._needsRefresh=true;this._readOnly=false;this._mimeType='';if(options.mimeType)
this.setMimeType(options.mimeType);if(options.autoHeight)
this._codeMirror.setSize(null,'auto');this._placeholderElement=null;if(options.placeholder){this._placeholderElement=createElement('pre');this._placeholderElement.classList.add('placeholder-text');this._placeholderElement.textContent=options.placeholder;this._updatePlaceholder();}}
static autocompleteCommand(codeMirror){const autocompleteController=codeMirror._codeMirrorTextEditor._autocompleteController;if(autocompleteController)
autocompleteController.autocomplete(true);}
static undoLastSelectionCommand(codeMirror){codeMirror._codeMirrorTextEditor._selectNextOccurrenceController.undoLastSelection();}
static selectNextOccurrenceCommand(codeMirror){codeMirror._codeMirrorTextEditor._selectNextOccurrenceController.selectNextOccurrence();}
static moveCamelLeftCommand(shift,codeMirror){codeMirror._codeMirrorTextEditor._doCamelCaseMovement(-1,shift);}
static moveCamelRightCommand(shift,codeMirror){codeMirror._codeMirrorTextEditor._doCamelCaseMovement(1,shift);}
static _overrideModeWithPrefixedTokens(modeName,tokenPrefix){const oldModeName=modeName+'-old';if(CodeMirror.modes[oldModeName])
return;CodeMirror.defineMode(oldModeName,CodeMirror.modes[modeName]);CodeMirror.defineMode(modeName,modeConstructor);function modeConstructor(config,parserConfig){const innerConfig={};for(const i in parserConfig)
innerConfig[i]=parserConfig[i];innerConfig.name=oldModeName;const codeMirrorMode=CodeMirror.getMode(config,innerConfig);codeMirrorMode.name=modeName;codeMirrorMode.token=tokenOverride.bind(null,codeMirrorMode.token);return codeMirrorMode;}
function tokenOverride(superToken,stream,state){const token=superToken(stream,state);return token?tokenPrefix+token.split(/ +/).join(' '+tokenPrefix):token;}}
static _collectUninstalledModes(mimeType){const installed=TextEditor.CodeMirrorTextEditor._loadedMimeModeExtensions;const nameToExtension=new Map();const extensions=self.runtime.extensions(TextEditor.CodeMirrorMimeMode);for(const extension of extensions)
nameToExtension.set(extension.descriptor()['fileName'],extension);const modesToLoad=new Set();for(const extension of extensions){const descriptor=extension.descriptor();if(installed.has(extension)||descriptor['mimeTypes'].indexOf(mimeType)===-1)
continue;modesToLoad.add(extension);const deps=descriptor['dependencies']||[];for(let i=0;i<deps.length;++i){const extension=nameToExtension.get(deps[i]);if(extension&&!installed.has(extension))
modesToLoad.add(extension);}}
return Array.from(modesToLoad);}
static _installMimeTypeModes(extensions){const promises=extensions.map(extension=>extension.instance().then(installMode.bind(null,extension)));return Promise.all(promises);function installMode(extension,instance){if(TextEditor.CodeMirrorTextEditor._loadedMimeModeExtensions.has(extension))
return;const mode=(instance);mode.install(extension);TextEditor.CodeMirrorTextEditor._loadedMimeModeExtensions.add(extension);}}
static _fixWordMovement(codeMirror){function moveLeft(shift,codeMirror){codeMirror.setExtending(shift);const cursor=codeMirror.getCursor('head');codeMirror.execCommand('goGroupLeft');const newCursor=codeMirror.getCursor('head');if(newCursor.ch===0&&newCursor.line!==0){codeMirror.setExtending(false);return;}
const skippedText=codeMirror.getRange(newCursor,cursor,'#');if(/^\s+$/.test(skippedText))
codeMirror.execCommand('goGroupLeft');codeMirror.setExtending(false);}
function moveRight(shift,codeMirror){codeMirror.setExtending(shift);const cursor=codeMirror.getCursor('head');codeMirror.execCommand('goGroupRight');const newCursor=codeMirror.getCursor('head');if(newCursor.ch===0&&newCursor.line!==0){codeMirror.setExtending(false);return;}
const skippedText=codeMirror.getRange(cursor,newCursor,'#');if(/^\s+$/.test(skippedText))
codeMirror.execCommand('goGroupRight');codeMirror.setExtending(false);}
const modifierKey=Host.isMac()?'Alt':'Ctrl';const leftKey=modifierKey+'-Left';const rightKey=modifierKey+'-Right';const keyMap={};keyMap[leftKey]=moveLeft.bind(null,false);keyMap[rightKey]=moveRight.bind(null,false);keyMap['Shift-'+leftKey]=moveLeft.bind(null,true);keyMap['Shift-'+rightKey]=moveRight.bind(null,true);codeMirror.addKeyMap(keyMap);}
codeMirror(){return this._codeMirror;}
widget(){return this;}
setPlaceholder(placeholder){if(!this._placeholderElement){this._placeholderElement=createElement('pre');this._placeholderElement.classList.add('placeholder-text');}
this._placeholderElement.textContent=placeholder||'';this._updatePlaceholder();}
_normalizePositionForOverlappingColumn(lineNumber,lineLength,charNumber){const linesCount=this._codeMirror.lineCount();let columnNumber=charNumber;if(charNumber<0&&lineNumber>0){--lineNumber;columnNumber=this.line(lineNumber).length;}else if(charNumber>=lineLength&&lineNumber<linesCount-1){++lineNumber;columnNumber=0;}else{columnNumber=Number.constrain(charNumber,0,lineLength);}
return{lineNumber:lineNumber,columnNumber:columnNumber};}
_camelCaseMoveFromPosition(lineNumber,columnNumber,direction){function valid(charNumber,length){return charNumber>=0&&charNumber<length;}
function isWordStart(text,charNumber){const position=charNumber;const nextPosition=charNumber+1;return valid(position,text.length)&&valid(nextPosition,text.length)&&TextUtils.TextUtils.isWordChar(text[position])&&TextUtils.TextUtils.isWordChar(text[nextPosition])&&TextUtils.TextUtils.isUpperCase(text[position])&&TextUtils.TextUtils.isLowerCase(text[nextPosition]);}
function isWordEnd(text,charNumber){const position=charNumber;const prevPosition=charNumber-1;return valid(position,text.length)&&valid(prevPosition,text.length)&&TextUtils.TextUtils.isWordChar(text[position])&&TextUtils.TextUtils.isWordChar(text[prevPosition])&&TextUtils.TextUtils.isUpperCase(text[position])&&TextUtils.TextUtils.isLowerCase(text[prevPosition]);}
function constrainPosition(lineNumber,lineLength,columnNumber){return{lineNumber:lineNumber,columnNumber:Number.constrain(columnNumber,0,lineLength)};}
const text=this.line(lineNumber);const length=text.length;if((columnNumber===length&&direction===1)||(columnNumber===0&&direction===-1))
return this._normalizePositionForOverlappingColumn(lineNumber,length,columnNumber+direction);let charNumber=direction===1?columnNumber:columnNumber-1;while(valid(charNumber,length)&&TextUtils.TextUtils.isSpaceChar(text[charNumber]))
charNumber+=direction;if(!valid(charNumber,length))
return constrainPosition(lineNumber,length,charNumber);if(TextUtils.TextUtils.isStopChar(text[charNumber])){while(valid(charNumber,length)&&TextUtils.TextUtils.isStopChar(text[charNumber]))
charNumber+=direction;if(!valid(charNumber,length))
return constrainPosition(lineNumber,length,charNumber);return{lineNumber:lineNumber,columnNumber:direction===-1?charNumber+1:charNumber};}
charNumber+=direction;while(valid(charNumber,length)&&!isWordStart(text,charNumber)&&!isWordEnd(text,charNumber)&&TextUtils.TextUtils.isWordChar(text[charNumber]))
charNumber+=direction;if(!valid(charNumber,length))
return constrainPosition(lineNumber,length,charNumber);if(isWordStart(text,charNumber)||isWordEnd(text,charNumber))
return{lineNumber:lineNumber,columnNumber:charNumber};return{lineNumber:lineNumber,columnNumber:direction===-1?charNumber+1:charNumber};}
_doCamelCaseMovement(direction,shift){const selections=this.selections();for(let i=0;i<selections.length;++i){const selection=selections[i];const move=this._camelCaseMoveFromPosition(selection.endLine,selection.endColumn,direction);selection.endLine=move.lineNumber;selection.endColumn=move.columnNumber;if(!shift)
selections[i]=selection.collapseToEnd();}
this.setSelections(selections);}
dispose(){if(this._options.bracketMatchingSetting)
this._options.bracketMatchingSetting.removeChangeListener(this._enableBracketMatchingIfNeeded,this);}
_enableBracketMatchingIfNeeded(){this._codeMirror.setOption('autoCloseBrackets',(this._options.bracketMatchingSetting&&this._options.bracketMatchingSetting.get())?{explode:false}:false);}
wasShown(){if(this._needsRefresh)
this.refresh();}
refresh(){if(this.isShowing()){this._codeMirror.refresh();this._needsRefresh=false;return;}
this._needsRefresh=true;}
willHide(){delete this._editorSizeInSync;}
undo(){this._codeMirror.undo();}
redo(){this._codeMirror.redo();}
_handleKeyDown(e){if(e.key==='Tab'&&Common.moduleSetting('textEditorTabMovesFocus').get()){e.consume(false);return;}
if(this._autocompleteController&&this._autocompleteController.keyDown(e))
e.consume(true);}
_handlePostKeyDown(e){if(e.defaultPrevented)
e.consume(true);}
configureAutocomplete(config){if(this._autocompleteController){this._autocompleteController.dispose();delete this._autocompleteController;}
if(config)
this._autocompleteController=new TextEditor.TextEditorAutocompleteController(this,this._codeMirror,config);}
cursorPositionToCoordinates(lineNumber,column){if(lineNumber>=this._codeMirror.lineCount()||lineNumber<0||column<0||column>this._codeMirror.getLine(lineNumber).length)
return null;const metrics=this._codeMirror.cursorCoords(new CodeMirror.Pos(lineNumber,column));return{x:metrics.left,y:metrics.top,height:metrics.bottom-metrics.top};}
coordinatesToCursorPosition(x,y){const element=this.element.ownerDocument.elementFromPoint(x,y);if(!element||!element.isSelfOrDescendant(this._codeMirror.getWrapperElement()))
return null;const gutterBox=this._codeMirror.getGutterElement().boxInWindow();if(x>=gutterBox.x&&x<=gutterBox.x+gutterBox.width&&y>=gutterBox.y&&y<=gutterBox.y+gutterBox.height)
return null;const coords=this._codeMirror.coordsChar({left:x,top:y});return TextEditor.CodeMirrorUtils.toRange(coords,coords);}
visualCoordinates(lineNumber,columnNumber){const metrics=this._codeMirror.cursorCoords(new CodeMirror.Pos(lineNumber,columnNumber));return{x:metrics.left,y:metrics.top};}
tokenAtTextPosition(lineNumber,columnNumber){if(lineNumber<0||lineNumber>=this._codeMirror.lineCount())
return null;const token=this._codeMirror.getTokenAt(new CodeMirror.Pos(lineNumber,(columnNumber||0)+1));if(!token)
return null;return{startColumn:token.start,endColumn:token.end,type:token.type};}
isClean(generation){return this._codeMirror.isClean(generation);}
markClean(){return this._codeMirror.changeGeneration(true);}
_hasLongLines(){function lineIterator(lineHandle){if(lineHandle.text.length>TextEditor.CodeMirrorTextEditor.LongLineModeLineLengthThreshold)
hasLongLines=true;return hasLongLines;}
let hasLongLines=false;this._codeMirror.eachLine(lineIterator);return hasLongLines;}
_enableLongLinesMode(){this._codeMirror.setOption('styleSelectedText',false);}
_disableLongLinesMode(){this._codeMirror.setOption('styleSelectedText',true);}
setMimeType(mimeType){this._mimeType=mimeType;const modesToLoad=TextEditor.CodeMirrorTextEditor._collectUninstalledModes(mimeType);if(!modesToLoad.length)
setMode.call(this);else
TextEditor.CodeMirrorTextEditor._installMimeTypeModes(modesToLoad).then(setMode.bind(this));function setMode(){const rewrittenMimeType=this.rewriteMimeType(mimeType);if(this._codeMirror.options.mode!==rewrittenMimeType)
this._codeMirror.setOption('mode',rewrittenMimeType);}}
setHighlightMode(mode){this._mimeType='';this._codeMirror.setOption('mode',mode);}
rewriteMimeType(mimeType){return mimeType;}
mimeType(){return this._mimeType;}
setReadOnly(readOnly){if(this._readOnly===readOnly)
return;this.clearPositionHighlight();this._readOnly=readOnly;this.element.classList.toggle('CodeMirror-readonly',readOnly);this._codeMirror.setOption('readOnly',readOnly);}
readOnly(){return!!this._codeMirror.getOption('readOnly');}
setLineNumberFormatter(formatter){this._codeMirror.setOption('lineNumberFormatter',formatter);}
addKeyDownHandler(handler){this._codeMirror.on('keydown',(CodeMirror,event)=>handler(event));}
addBookmark(lineNumber,columnNumber,element,type,insertBefore){const bookmark=new TextEditor.TextEditorBookMark(this._codeMirror.setBookmark(new CodeMirror.Pos(lineNumber,columnNumber),{widget:element,insertLeft:insertBefore}),type,this);this._updateDecorations(lineNumber);return bookmark;}
bookmarks(range,type){const pos=TextEditor.CodeMirrorUtils.toPos(range);let markers=this._codeMirror.findMarksAt(pos.start);if(!range.isEmpty()){const middleMarkers=this._codeMirror.findMarks(pos.start,pos.end);const endMarkers=this._codeMirror.findMarksAt(pos.end);markers=markers.concat(middleMarkers,endMarkers);}
const bookmarks=[];for(let i=0;i<markers.length;i++){const bookmark=markers[i][TextEditor.TextEditorBookMark._symbol];if(bookmark&&(!type||bookmark.type()===type))
bookmarks.push(bookmark);}
return bookmarks;}
focus(){this._codeMirror.focus();}
hasFocus(){return this._codeMirror.hasFocus();}
operation(operation){this._codeMirror.operation(operation);}
scrollLineIntoView(lineNumber){this._innerRevealLine(lineNumber,this._codeMirror.getScrollInfo());}
_innerRevealLine(lineNumber,scrollInfo){const topLine=this._codeMirror.lineAtHeight(scrollInfo.top,'local');const bottomLine=this._codeMirror.lineAtHeight(scrollInfo.top+scrollInfo.clientHeight,'local');const linesPerScreen=bottomLine-topLine+1;if(lineNumber<topLine){const topLineToReveal=Math.max(lineNumber-(linesPerScreen/2)+1,0)|0;this._codeMirror.scrollIntoView(new CodeMirror.Pos(topLineToReveal,0));}else if(lineNumber>bottomLine){const bottomLineToReveal=Math.min(lineNumber+(linesPerScreen/2)-1,this.linesCount-1)|0;this._codeMirror.scrollIntoView(new CodeMirror.Pos(bottomLineToReveal,0));}}
addDecoration(element,lineNumber,startColumn,endColumn){const widget=this._codeMirror.addLineWidget(lineNumber,element);let update=null;if(typeof startColumn!=='undefined'){if(typeof endColumn==='undefined')
endColumn=Infinity;update=this._updateFloatingDecoration.bind(this,element,lineNumber,startColumn,endColumn);update();}
this._decorations.set(lineNumber,{element:element,update:update,widget:widget});}
_updateFloatingDecoration(element,lineNumber,startColumn,endColumn){const base=this._codeMirror.cursorCoords(new CodeMirror.Pos(lineNumber,0),'page');const start=this._codeMirror.cursorCoords(new CodeMirror.Pos(lineNumber,startColumn),'page');const end=this._codeMirror.charCoords(new CodeMirror.Pos(lineNumber,endColumn),'page');element.style.width=(end.right-start.left)+'px';element.style.left=(start.left-base.left)+'px';}
_updateDecorations(lineNumber){this._decorations.get(lineNumber).forEach(innerUpdateDecorations);function innerUpdateDecorations(decoration){if(decoration.update)
decoration.update();}}
removeDecoration(element,lineNumber){this._decorations.get(lineNumber).forEach(innerRemoveDecoration.bind(this));function innerRemoveDecoration(decoration){if(decoration.element!==element)
return;this._codeMirror.removeLineWidget(decoration.widget);this._decorations.delete(lineNumber,decoration);}}
revealPosition(lineNumber,columnNumber,shouldHighlight){lineNumber=Number.constrain(lineNumber,0,this._codeMirror.lineCount()-1);if(typeof columnNumber!=='number')
columnNumber=0;columnNumber=Number.constrain(columnNumber,0,this._codeMirror.getLine(lineNumber).length);this.clearPositionHighlight();this._highlightedLine=this._codeMirror.getLineHandle(lineNumber);if(!this._highlightedLine)
return;this.scrollLineIntoView(lineNumber);if(shouldHighlight){this._codeMirror.addLineClass(this._highlightedLine,null,this._readOnly?'cm-readonly-highlight':'cm-highlight');if(!this._readOnly)
this._clearHighlightTimeout=setTimeout(this.clearPositionHighlight.bind(this),2000);}
this.setSelection(TextUtils.TextRange.createFromLocation(lineNumber,columnNumber));}
clearPositionHighlight(){if(this._clearHighlightTimeout)
clearTimeout(this._clearHighlightTimeout);delete this._clearHighlightTimeout;if(this._highlightedLine){this._codeMirror.removeLineClass(this._highlightedLine,null,this._readOnly?'cm-readonly-highlight':'cm-highlight');}
delete this._highlightedLine;}
elementsToRestoreScrollPositionsFor(){return[];}
_updatePaddingBottom(width,height){if(!this._options.padBottom)
return;const scrollInfo=this._codeMirror.getScrollInfo();let newPaddingBottom;const linesElement=this._codeMirrorElement.querySelector('.CodeMirror-lines');const lineCount=this._codeMirror.lineCount();if(lineCount<=1){newPaddingBottom=0;}else{newPaddingBottom=Math.max(scrollInfo.clientHeight-this._codeMirror.getLineHandle(this._codeMirror.lastLine()).height,0);}
newPaddingBottom+='px';linesElement.style.paddingBottom=newPaddingBottom;this._codeMirror.setSize(width,height);}
_resizeEditor(){const parentElement=this.element.parentElement;if(!parentElement||!this.isShowing())
return;this._codeMirror.operation(()=>{const scrollLeft=this._codeMirror.doc.scrollLeft;const scrollTop=this._codeMirror.doc.scrollTop;const width=parentElement.offsetWidth;const height=parentElement.offsetHeight-this.element.offsetTop;if(this._options.autoHeight){this._codeMirror.setSize(width,'auto');}else{this._codeMirror.setSize(width,height);this._updatePaddingBottom(width,height);}
this._codeMirror.scrollTo(scrollLeft,scrollTop);});}
onResize(){if(this._autocompleteController)
this._autocompleteController.clearAutocomplete();this._resizeEditor();this._editorSizeInSync=true;if(this._selectionSetScheduled){delete this._selectionSetScheduled;this.setSelection(this._lastSelection);}}
editRange(range,text,origin){const pos=TextEditor.CodeMirrorUtils.toPos(range);this._codeMirror.replaceRange(text,pos.start,pos.end,origin);const newRange=TextEditor.CodeMirrorUtils.toRange(pos.start,this._codeMirror.posFromIndex(this._codeMirror.indexFromPos(pos.start)+text.length));this.dispatchEventToListeners(UI.TextEditor.Events.TextChanged,{oldRange:range,newRange:newRange});return newRange;}
clearAutocomplete(){if(this._autocompleteController)
this._autocompleteController.clearAutocomplete();}
wordRangeForCursorPosition(lineNumber,column,isWordChar){const line=this.line(lineNumber);let wordStart=column;if(column!==0&&isWordChar(line.charAt(column-1))){wordStart=column-1;while(wordStart>0&&isWordChar(line.charAt(wordStart-1)))
--wordStart;}
let wordEnd=column;while(wordEnd<line.length&&isWordChar(line.charAt(wordEnd)))
++wordEnd;return new TextUtils.TextRange(lineNumber,wordStart,lineNumber,wordEnd);}
_changes(codeMirror,changes){if(!changes.length)
return;this._updatePlaceholder();const hasOneLine=this._codeMirror.lineCount()===1;if(hasOneLine!==this._hasOneLine)
this._resizeEditor();this._hasOneLine=hasOneLine;this._decorations.valuesArray().forEach(decoration=>this._codeMirror.removeLineWidget(decoration.widget));this._decorations.clear();const edits=[];let currentEdit;for(let changeIndex=0;changeIndex<changes.length;++changeIndex){const changeObject=changes[changeIndex];const edit=TextEditor.CodeMirrorUtils.changeObjectToEditOperation(changeObject);if(currentEdit&&edit.oldRange.equal(currentEdit.newRange)){currentEdit.newRange=edit.newRange;}else{currentEdit=edit;edits.push(currentEdit);}}
for(let i=0;i<edits.length;i++){this.dispatchEventToListeners(UI.TextEditor.Events.TextChanged,{oldRange:edits[i].oldRange,newRange:edits[i].newRange});}}
_beforeSelectionChange(codeMirror,selection){this._selectNextOccurrenceController.selectionWillChange();}
scrollToLine(lineNumber){const pos=new CodeMirror.Pos(lineNumber,0);const coords=this._codeMirror.charCoords(pos,'local');this._codeMirror.scrollTo(0,coords.top);}
firstVisibleLine(){return this._codeMirror.lineAtHeight(this._codeMirror.getScrollInfo().top,'local');}
scrollTop(){return this._codeMirror.getScrollInfo().top;}
setScrollTop(scrollTop){this._codeMirror.scrollTo(0,scrollTop);}
lastVisibleLine(){const scrollInfo=this._codeMirror.getScrollInfo();return this._codeMirror.lineAtHeight(scrollInfo.top+scrollInfo.clientHeight,'local');}
selection(){const start=this._codeMirror.getCursor('anchor');const end=this._codeMirror.getCursor('head');return TextEditor.CodeMirrorUtils.toRange(start,end);}
selections(){const selectionList=this._codeMirror.listSelections();const result=[];for(let i=0;i<selectionList.length;++i){const selection=selectionList[i];result.push(TextEditor.CodeMirrorUtils.toRange(selection.anchor,selection.head));}
return result;}
lastSelection(){return this._lastSelection;}
setSelection(textRange,dontScroll){this._lastSelection=textRange;if(!this._editorSizeInSync){this._selectionSetScheduled=true;return;}
const pos=TextEditor.CodeMirrorUtils.toPos(textRange);this._codeMirror.setSelection(pos.start,pos.end,{scroll:!dontScroll});}
setSelections(ranges,primarySelectionIndex){const selections=[];for(let i=0;i<ranges.length;++i){const selection=TextEditor.CodeMirrorUtils.toPos(ranges[i]);selections.push({anchor:selection.start,head:selection.end});}
primarySelectionIndex=primarySelectionIndex||0;this._codeMirror.setSelections(selections,primarySelectionIndex,{scroll:false});}
_detectLineSeparator(text){this._lineSeparator=text.indexOf('\r\n')>=0?'\r\n':'\n';}
setText(text){if(text.length>TextEditor.CodeMirrorTextEditor.MaxEditableTextSize){this.configureAutocomplete(null);this.setReadOnly(true);}
this._codeMirror.setValue(text);if(this._shouldClearHistory){this._codeMirror.clearHistory();this._shouldClearHistory=false;}
this._detectLineSeparator(text);if(this._hasLongLines())
this._enableLongLinesMode();else
this._disableLongLinesMode();if(!this.isShowing())
this.refresh();}
text(textRange){if(!textRange)
return this._codeMirror.getValue(this._lineSeparator);const pos=TextEditor.CodeMirrorUtils.toPos(textRange.normalize());return this._codeMirror.getRange(pos.start,pos.end,this._lineSeparator);}
textWithCurrentSuggestion(){if(!this._autocompleteController)
return this.text();return this._autocompleteController.textWithCurrentSuggestion();}
fullRange(){const lineCount=this.linesCount;const lastLine=this._codeMirror.getLine(lineCount-1);return TextEditor.CodeMirrorUtils.toRange(new CodeMirror.Pos(0,0),new CodeMirror.Pos(lineCount-1,lastLine.length));}
line(lineNumber){return this._codeMirror.getLine(lineNumber);}
get linesCount(){return this._codeMirror.lineCount();}
newlineAndIndent(){this._codeMirror.execCommand('newlineAndIndent');}
textEditorPositionHandle(lineNumber,columnNumber){return new TextEditor.CodeMirrorPositionHandle(this._codeMirror,new CodeMirror.Pos(lineNumber,columnNumber));}
_updatePlaceholder(){if(!this._placeholderElement)
return;this._placeholderElement.remove();if(this.linesCount===1&&!this.line(0)){this._codeMirror.display.lineSpace.insertBefore(this._placeholderElement,this._codeMirror.display.lineSpace.firstChild);}}};TextEditor.CodeMirrorTextEditor.maxHighlightLength=1000;CodeMirror.commands.autocomplete=TextEditor.CodeMirrorTextEditor.autocompleteCommand;CodeMirror.commands.undoLastSelection=TextEditor.CodeMirrorTextEditor.undoLastSelectionCommand;CodeMirror.commands.selectNextOccurrence=TextEditor.CodeMirrorTextEditor.selectNextOccurrenceCommand;CodeMirror.commands.moveCamelLeft=TextEditor.CodeMirrorTextEditor.moveCamelLeftCommand.bind(null,false);CodeMirror.commands.selectCamelLeft=TextEditor.CodeMirrorTextEditor.moveCamelLeftCommand.bind(null,true);CodeMirror.commands.moveCamelRight=TextEditor.CodeMirrorTextEditor.moveCamelRightCommand.bind(null,false);CodeMirror.commands.selectCamelRight=TextEditor.CodeMirrorTextEditor.moveCamelRightCommand.bind(null,true);CodeMirror.commands.indentLessOrPass=function(codeMirror){const selections=codeMirror.listSelections();if(selections.length===1){const range=TextEditor.CodeMirrorUtils.toRange(selections[0].anchor,selections[0].head);if(range.isEmpty()&&!/^\s/.test(codeMirror.getLine(range.startLine)))
return CodeMirror.Pass;}
codeMirror.execCommand('indentLess');};CodeMirror.commands.gotoMatchingBracket=function(codeMirror){const updatedSelections=[];const selections=codeMirror.listSelections();for(let i=0;i<selections.length;++i){const selection=selections[i];const cursor=selection.head;const matchingBracket=codeMirror.findMatchingBracket(cursor,false,{maxScanLines:10000});let updatedHead=cursor;if(matchingBracket&&matchingBracket.match){const columnCorrection=CodeMirror.cmpPos(matchingBracket.from,cursor)===0?1:0;updatedHead=new CodeMirror.Pos(matchingBracket.to.line,matchingBracket.to.ch+columnCorrection);}
updatedSelections.push({anchor:updatedHead,head:updatedHead});}
codeMirror.setSelections(updatedSelections);};CodeMirror.commands.undoAndReveal=function(codemirror){const scrollInfo=codemirror.getScrollInfo();codemirror.execCommand('undo');const cursor=codemirror.getCursor('start');codemirror._codeMirrorTextEditor._innerRevealLine(cursor.line,scrollInfo);const autocompleteController=codemirror._codeMirrorTextEditor._autocompleteController;if(autocompleteController)
autocompleteController.clearAutocomplete();};CodeMirror.commands.redoAndReveal=function(codemirror){const scrollInfo=codemirror.getScrollInfo();codemirror.execCommand('redo');const cursor=codemirror.getCursor('start');codemirror._codeMirrorTextEditor._innerRevealLine(cursor.line,scrollInfo);const autocompleteController=codemirror._codeMirrorTextEditor._autocompleteController;if(autocompleteController)
autocompleteController.clearAutocomplete();};CodeMirror.commands.dismiss=function(codemirror){const selections=codemirror.listSelections();const selection=selections[0];if(selections.length===1){if(TextEditor.CodeMirrorUtils.toRange(selection.anchor,selection.head).isEmpty())
return CodeMirror.Pass;codemirror.setSelection(selection.anchor,selection.anchor,{scroll:false});codemirror._codeMirrorTextEditor.scrollLineIntoView(selection.anchor.line);return;}
codemirror.setSelection(selection.anchor,selection.head,{scroll:false});codemirror._codeMirrorTextEditor.scrollLineIntoView(selection.anchor.line);};CodeMirror.commands.goSmartPageUp=function(codemirror){if(codemirror._codeMirrorTextEditor.selection().equal(TextUtils.TextRange.createFromLocation(0,0)))
return CodeMirror.Pass;codemirror.execCommand('goPageUp');};CodeMirror.commands.goSmartPageDown=function(codemirror){if(codemirror._codeMirrorTextEditor.selection().equal(codemirror._codeMirrorTextEditor.fullRange().collapseToEnd()))
return CodeMirror.Pass;codemirror.execCommand('goPageDown');};TextEditor.CodeMirrorTextEditor.LongLineModeLineLengthThreshold=2000;TextEditor.CodeMirrorTextEditor.MaxEditableTextSize=1024*1024*10;TextEditor.CodeMirrorPositionHandle=class{constructor(codeMirror,pos){this._codeMirror=codeMirror;this._lineHandle=codeMirror.getLineHandle(pos.line);this._columnNumber=pos.ch;}
resolve(){const lineNumber=this._lineHandle?this._codeMirror.getLineNumber(this._lineHandle):null;if(typeof lineNumber!=='number')
return null;return{lineNumber:lineNumber,columnNumber:this._columnNumber};}
equal(positionHandle){return positionHandle._lineHandle===this._lineHandle&&positionHandle._columnNumber===this._columnNumber&&positionHandle._codeMirror===this._codeMirror;}};TextEditor.CodeMirrorTextEditor.SelectNextOccurrenceController=class{constructor(textEditor,codeMirror){this._textEditor=textEditor;this._codeMirror=codeMirror;}
selectionWillChange(){if(!this._muteSelectionListener)
delete this._fullWordSelection;}
_findRange(selections,range){for(let i=0;i<selections.length;++i){if(range.equal(selections[i]))
return true;}
return false;}
undoLastSelection(){this._muteSelectionListener=true;this._codeMirror.execCommand('undoSelection');this._muteSelectionListener=false;}
selectNextOccurrence(){const selections=this._textEditor.selections();let anyEmptySelection=false;for(let i=0;i<selections.length;++i){const selection=selections[i];anyEmptySelection=anyEmptySelection||selection.isEmpty();if(selection.startLine!==selection.endLine)
return;}
if(anyEmptySelection){this._expandSelectionsToWords(selections);return;}
const last=selections[selections.length-1];let next=last;do
next=this._findNextOccurrence(next,!!this._fullWordSelection);while(next&&this._findRange(selections,next)&&!next.equal(last));if(!next)
return;selections.push(next);this._muteSelectionListener=true;this._textEditor.setSelections(selections,selections.length-1);delete this._muteSelectionListener;this._textEditor.scrollLineIntoView(next.startLine);}
_expandSelectionsToWords(selections){const newSelections=[];for(let i=0;i<selections.length;++i){const selection=selections[i];const startRangeWord=this._textEditor.wordRangeForCursorPosition(selection.startLine,selection.startColumn,TextUtils.TextUtils.isWordChar)||TextUtils.TextRange.createFromLocation(selection.startLine,selection.startColumn);const endRangeWord=this._textEditor.wordRangeForCursorPosition(selection.endLine,selection.endColumn,TextUtils.TextUtils.isWordChar)||TextUtils.TextRange.createFromLocation(selection.endLine,selection.endColumn);const newSelection=new TextUtils.TextRange(startRangeWord.startLine,startRangeWord.startColumn,endRangeWord.endLine,endRangeWord.endColumn);newSelections.push(newSelection);}
this._textEditor.setSelections(newSelections,newSelections.length-1);this._fullWordSelection=true;}
_findNextOccurrence(range,fullWord){range=range.normalize();let matchedLineNumber;let matchedColumnNumber;const textToFind=this._textEditor.text(range);function findWordInLine(wordRegex,lineNumber,lineText,from,to){if(typeof matchedLineNumber==='number')
return true;wordRegex.lastIndex=from;const result=wordRegex.exec(lineText);if(!result||result.index+textToFind.length>to)
return false;matchedLineNumber=lineNumber;matchedColumnNumber=result.index;return true;}
let iteratedLineNumber;function lineIterator(regex,lineHandle){if(findWordInLine(regex,iteratedLineNumber++,lineHandle.text,0,lineHandle.text.length))
return true;}
let regexSource=textToFind.escapeForRegExp();if(fullWord)
regexSource='\\b'+regexSource+'\\b';const wordRegex=new RegExp(regexSource,'g');const currentLineText=this._codeMirror.getLine(range.startLine);findWordInLine(wordRegex,range.startLine,currentLineText,range.endColumn,currentLineText.length);iteratedLineNumber=range.startLine+1;this._codeMirror.eachLine(range.startLine+1,this._codeMirror.lineCount(),lineIterator.bind(null,wordRegex));iteratedLineNumber=0;this._codeMirror.eachLine(0,range.startLine,lineIterator.bind(null,wordRegex));findWordInLine(wordRegex,range.startLine,currentLineText,0,range.startColumn);if(typeof matchedLineNumber!=='number')
return null;return new TextUtils.TextRange(matchedLineNumber,matchedColumnNumber,matchedLineNumber,matchedColumnNumber+textToFind.length);}};TextEditor.TextEditorPositionHandle=function(){};TextEditor.TextEditorPositionHandle.prototype={resolve(){},equal(positionHandle){}};TextEditor.CodeMirrorTextEditor._overrideModeWithPrefixedTokens('css','css-');TextEditor.CodeMirrorTextEditor._overrideModeWithPrefixedTokens('javascript','js-');TextEditor.CodeMirrorTextEditor._overrideModeWithPrefixedTokens('xml','xml-');TextEditor.CodeMirrorTextEditor._loadedMimeModeExtensions=new Set();TextEditor.CodeMirrorMimeMode=function(){};TextEditor.CodeMirrorMimeMode.prototype={install(extension){}};TextEditor.TextEditorBookMark=class{constructor(marker,type,editor){marker[TextEditor.TextEditorBookMark._symbol]=this;this._marker=marker;this._type=type;this._editor=editor;}
clear(){const position=this._marker.find();this._marker.clear();if(position)
this._editor._updateDecorations(position.line);}
refresh(){this._marker.changed();const position=this._marker.find();if(position)
this._editor._updateDecorations(position.line);}
type(){return this._type;}
position(){const pos=this._marker.find();return pos?TextUtils.TextRange.createFromLocation(pos.line,pos.ch):null;}};TextEditor.TextEditorBookMark._symbol=Symbol('TextEditor.TextEditorBookMark');TextEditor.CodeMirrorTextEditor.Decoration;TextEditor.CodeMirrorTextEditorFactory=class{createEditor(options){return new TextEditor.CodeMirrorTextEditor(options);}};CodeMirror.inputStyles.devToolsAccessibleTextArea=class extends CodeMirror.inputStyles.textarea{init(display){super.init(display);UI.ARIAUtils.setAccessibleName(this.textarea,ls`Code editor`);this.textarea.addEventListener('compositionstart',this._onCompositionStart.bind(this));}
_onCompositionStart(){if(this.textarea.selectionEnd===this.textarea.value.length)
return;this.textarea.value=this.textarea.value.substring(0,this.textarea.selectionEnd);this.textarea.setSelectionRange(this.textarea.value.length,this.textarea.value.length);this.prevInput=this.textarea.value;}
reset(typing){if(typing||this.contextMenuPending||this.composing||this.cm.somethingSelected()){super.reset(typing);return;}
const cursor=this.cm.getCursor();let start,end;if(this.cm.options.lineWrapping){const top=this.cm.charCoords(cursor,'page').top;start=this.cm.coordsChar({left:-Infinity,top});end=this.cm.coordsChar({left:Infinity,top});}else{const offset=Math.floor(cursor.ch/1000)*1000;start={ch:offset,line:cursor.line};end={ch:offset+1000,line:cursor.line};}
this.textarea.value=this.cm.getRange(start,end);const caretPosition=cursor.ch-start.ch;this.textarea.setSelectionRange(caretPosition,caretPosition);this.prevInput=this.textarea.value;}
poll(){if(this.contextMenuPending||this.composing)
return super.poll();const text=this.textarea.value;let start=0;const length=Math.min(this.prevInput.length,text.length);while(start<length&&this.prevInput[start]===text[start])
++start;let end=0;while(end<length-start&&this.prevInput[this.prevInput.length-end-1]===text[text.length-end-1])
++end;const placeholder=this.textarea;this.textarea=(createElement('textarea'));this.textarea.value=text.substring(start,text.length-end);this.textarea.setSelectionRange(placeholder.selectionStart-start,placeholder.selectionEnd-start);this.prevInput='';const result=super.poll();this.prevInput=text;this.textarea=placeholder;return result;}};;Runtime.cachedResources["text_editor/autocompleteTooltip.css"]="/*\n * Copyright (c) 2018 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n.autocomplete-tooltip {\n pointer-events: none;\n margin-left: -3px;\n}\n\n.autocomplete-tooltip > div > * {\n padding: 0px 4px;\n white-space: nowrap;\n vertical-align: middle;\n line-height: 20px;\n box-shadow: var(--drop-shadow);\n background-color: #FFFFFF;\n width: fit-content;\n}\n/*# sourceURL=text_editor/autocompleteTooltip.css */";Runtime.cachedResources["text_editor/cmdevtools.css"]=".CodeMirror {\n line-height: 1.2em !important;\n background-color: transparent !important;\n color: #222;\n height: 300px;\n}\n\n.CodeMirror-linewidget {\n overflow: visible !important;\n}\n\n.CodeMirror-gutter-performance {\n width: 60px;\n background-color: white;\n margin-left: 3px;\n}\n\n.CodeMirror-gutter-memory {\n width: 48px;\n background-color: white;\n margin-left: 3px;\n}\n\n.CodeMirror-gutter-coverage {\n width: 5px;\n background-color: white;\n margin-left: 3px;\n}\n\n.CodeMirror .source-frame-eval-expression {\n outline: 0;\n border: 1px solid rgb(163, 41, 34);\n border-left-width: 0;\n border-right-width: 0;\n background-color: rgb(255, 255, 194);\n}\n\n.CodeMirror .source-frame-eval-expression-start {\n border-left-width: 1px;\n margin-left: -1px;\n}\n\n.CodeMirror .source-frame-eval-expression-end {\n border-right-width: 1px;\n margin-right: -1px;\n}\n\n.CodeMirror .source-frame-continue-to-location {\n outline: 0;\n border: 1px solid transparent;\n border-left-width: 0;\n border-right-width: 0;\n background-color: rgb(230, 236, 255);\n cursor: pointer;\n}\n\n.CodeMirror .source-frame-continue-to-location:hover {\n border: 1px solid rgb(121, 141, 254);\n background-color: rgb(171, 191, 254);\n}\n\n:host-context(.-theme-with-dark-background) .CodeMirror .source-frame-continue-to-location,\n.-theme-with-dark-background .CodeMirror .source-frame-continue-to-location {\n background-color: #14522b;\n}\n\n:host-context(.-theme-with-dark-background) .CodeMirror .source-frame-continue-to-location:hover,\n.-theme-with-dark-background .CodeMirror .source-frame-continue-to-location:hover {\n border: 1px solid #33cc6b;\n background-color: #14522b;\n}\n\n.CodeMirror .source-frame-continue-to-location-start {\n border-left-width: 1px;\n margin-left: -1px;\n}\n\n.CodeMirror .source-frame-continue-to-location-end {\n border-right-width: 1px;\n margin-right: -1px;\n}\n\n.CodeMirror .source-frame-async-step-in {\n outline: 0;\n background-color: hsla(100, 46%, 80%, 1);\n cursor: pointer;\n border: 1px solid transparent;\n border-left-width: 0;\n border-right-width: 0;\n}\n\n.source-frame-async-step-in-hovered .source-frame-async-step-in {\n background-color: hsl(96, 53%, 65%);\n border-color: rgb(100, 154, 100);\n}\n\n.source-frame-async-step-in-hovered .source-frame-async-step-in-start {\n border-left-width: 1px;\n margin-left: -1px;\n}\n\n.source-frame-async-step-in-hovered .source-frame-async-step-in-end {\n border-right-width: 1px;\n margin-right: -1px;\n}\n\n.CodeMirror-readonly .CodeMirror-cursor {\n display: none;\n}\n\n.CodeMirror-gutters {\n border-right: 1px solid var(--divider-color);\n white-space: nowrap;\n background-color: white;\n}\n\n.CodeMirror-linenumber {\n color: rgb(128, 128, 128);\n padding: 0 3px 0 5px;\n min-width: 22px;\n text-align: right;\n white-space: nowrap;\n}\n\n.pretty-printed .CodeMirror-linenumber {\n color: var(--accent-color);\n}\n\
accept(event){return this._visibleTypes.has(TimelineModel.TimelineVisibleEventsFilter._eventType(event));}
static _eventType(event){if(event.hasCategory(TimelineModel.TimelineModel.Category.Console))
return TimelineModel.TimelineModel.RecordType.ConsoleTime;if(event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming))
return TimelineModel.TimelineModel.RecordType.UserTiming;if(event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo))
return TimelineModel.TimelineModel.RecordType.LatencyInfo;return(event.name);}};TimelineModel.TimelineInvisibleEventsFilter=class extends TimelineModel.TimelineModelFilter{constructor(invisibleTypes){super();this._invisibleTypes=new Set(invisibleTypes);}
accept(event){return!this._invisibleTypes.has(TimelineModel.TimelineVisibleEventsFilter._eventType(event));}};TimelineModel.ExclusiveNameFilter=class extends TimelineModel.TimelineModelFilter{constructor(excludeNames){super();this._excludeNames=new Set(excludeNames);}
accept(event){return!this._excludeNames.has(event.name);}};;TimelineModel.TracingLayerPayload;TimelineModel.TracingLayerTile;TimelineModel.TracingLayerTree=class extends SDK.LayerTreeBase{constructor(target){super(target);this._tileById=new Map();this._paintProfilerModel=target&&target.model(SDK.PaintProfilerModel);}
async setLayers(root,layers,paints){const idsToResolve=new Set();if(root){this._extractNodeIdsToResolve(idsToResolve,{},root);}else{for(let i=0;i<layers.length;++i)
this._extractNodeIdsToResolve(idsToResolve,{},layers[i]);}
await this.resolveBackendNodeIds(idsToResolve);const oldLayersById=this._layersById;this._layersById={};this.setContentRoot(null);if(root){const convertedLayers=this._innerSetLayers(oldLayersById,root);this.setRoot(convertedLayers);}else{const processedLayers=layers.map(this._innerSetLayers.bind(this,oldLayersById));const contentRoot=this.contentRoot();this.setRoot(contentRoot);for(let i=0;i<processedLayers.length;++i){if(processedLayers[i].id()!==contentRoot.id())
contentRoot.addChild(processedLayers[i]);}}
this._setPaints(paints);}
setTiles(tiles){this._tileById=new Map();for(const tile of tiles)
this._tileById.set(tile.id,tile);}
pictureForRasterTile(tileId){const tile=this._tileById.get('cc::Tile/'+tileId);if(!tile){Common.console.error(`Tile ${tileId} is missing`);return(Promise.resolve(null));}
const layer=this.layerById(tile.layer_id);if(!layer){Common.console.error(`Layer ${tile.layer_id} for tile ${tileId} is not found`);return(Promise.resolve(null));}
return layer._pictureForRect(tile.content_rect);}
_setPaints(paints){for(let i=0;i<paints.length;++i){const layer=this._layersById[paints[i].layerId()];if(layer)
layer._addPaintEvent(paints[i]);}}
_innerSetLayers(oldLayersById,payload){let layer=(oldLayersById[payload.layer_id]);if(layer)
layer._reset(payload);else
layer=new TimelineModel.TracingLayer(this._paintProfilerModel,payload);this._layersById[payload.layer_id]=layer;if(payload.owner_node)
layer._setNode(this.backendNodeIdToNode().get(payload.owner_node)||null);if(!this.contentRoot()&&layer.drawsContent())
this.setContentRoot(layer);for(let i=0;payload.children&&i<payload.children.length;++i)
layer.addChild(this._innerSetLayers(oldLayersById,payload.children[i]));return layer;}
_extractNodeIdsToResolve(nodeIdsToResolve,seenNodeIds,payload){const backendNodeId=payload.owner_node;if(backendNodeId&&!this.backendNodeIdToNode().has(backendNodeId))
nodeIdsToResolve.add(backendNodeId);for(let i=0;payload.children&&i<payload.children.length;++i)
this._extractNodeIdsToResolve(nodeIdsToResolve,seenNodeIds,payload.children[i]);}};TimelineModel.TracingLayer=class{constructor(paintProfilerModel,payload){this._paintProfilerModel=paintProfilerModel;this._reset(payload);}
_reset(payload){this._node=null;this._layerId=String(payload.layer_id);this._offsetX=payload.position[0];this._offsetY=payload.position[1];this._width=payload.bounds.width;this._height=payload.bounds.height;this._children=[];this._parentLayerId=null;this._parent=null;this._quad=payload.layer_quad||[];this._createScrollRects(payload);this._compositingReasons=payload.compositing_reasons||[];this._drawsContent=!!payload.draws_content;this._gpuMemoryUsage=payload.gpu_memory_usage;this._paints=[];}
id(){return this._layerId;}
parentId(){return this._parentLayerId;}
parent(){return this._parent;}
isRoot(){return!this.parentId();}
children(){return this._children;}
addChild(child){if(child._parent)
console.assert(false,'Child already has a parent');this._children.push(child);child._parent=this;child._parentLayerId=this._layerId;}
_setNode(node){this._node=node;}
node(){return this._node;}
nodeForSelfOrAncestor(){for(let layer=this;layer;layer=layer._parent){if(layer._node)
return layer._node;}
return null;}
offsetX(){return this._offsetX;}
offsetY(){return this._offsetY;}
width(){return this._width;}
height(){return this._height;}
transform(){return null;}
quad(){return this._quad;}
anchorPoint(){return[0.5,0.5,0];}
invisible(){return false;}
paintCount(){return 0;}
lastPaintRect(){return null;}
scrollRects(){return this._scrollRects;}
stickyPositionConstraint(){return null;}
gpuMemoryUsage(){return this._gpuMemoryUsage;}
snapshots(){return this._paints.map(paint=>paint.snapshotPromise().then(snapshot=>{if(!snapshot)
return null;const rect={x:snapshot.rect[0],y:snapshot.rect[1],width:snapshot.rect[2],height:snapshot.rect[3]};return{rect:rect,snapshot:snapshot.snapshot};}));}
_pictureForRect(targetRect){return Promise.all(this._paints.map(paint=>paint.picturePromise())).then(pictures=>{const fragments=pictures.filter(picture=>picture&&rectsOverlap(picture.rect,targetRect)).map(picture=>({x:picture.rect[0],y:picture.rect[1],picture:picture.serializedPicture}));if(!fragments.length||!this._paintProfilerModel)
return null;const x0=fragments.reduce((min,item)=>Math.min(min,item.x),Infinity);const y0=fragments.reduce((min,item)=>Math.min(min,item.y),Infinity);const rect={x:targetRect[0]-x0,y:targetRect[1]-y0,width:targetRect[2],height:targetRect[3]};return this._paintProfilerModel.loadSnapshotFromFragments(fragments).then(snapshot=>snapshot?{rect:rect,snapshot:snapshot}:null);});function segmentsOverlap(a1,a2,b1,b2){console.assert(a1<=a2&&b1<=b2,'segments should be specified as ordered pairs');return a2>b1&&a1<b2;}
function rectsOverlap(a,b){return segmentsOverlap(a[0],a[0]+a[2],b[0],b[0]+b[2])&&segmentsOverlap(a[1],a[1]+a[3],b[1],b[1]+b[3]);}}
_scrollRectsFromParams(params,type){return{rect:{x:params[0],y:params[1],width:params[2],height:params[3]},type:type};}
_createScrollRects(payload){this._scrollRects=[];if(payload.non_fast_scrollable_region){this._scrollRects.push(this._scrollRectsFromParams(payload.non_fast_scrollable_region,SDK.Layer.ScrollRectType.NonFastScrollable.name));}
if(payload.touch_event_handler_region){this._scrollRects.push(this._scrollRectsFromParams(payload.touch_event_handler_region,SDK.Layer.ScrollRectType.TouchEventHandler.name));}
if(payload.wheel_event_handler_region){this._scrollRects.push(this._scrollRectsFromParams(payload.wheel_event_handler_region,SDK.Layer.ScrollRectType.WheelEventHandler.name));}
if(payload.scroll_event_handler_region){this._scrollRects.push(this._scrollRectsFromParams(payload.scroll_event_handler_region,SDK.Layer.ScrollRectType.RepaintsOnScroll.name));}}
_addPaintEvent(paint){this._paints.push(paint);}
requestCompositingReasons(){return Promise.resolve(this._compositingReasons);}
drawsContent(){return this._drawsContent;}};;TimelineModel.TimelineModel=class{constructor(){this._reset();}
static forEachEvent(events,onStartEvent,onEndEvent,onInstantEvent,startTime,endTime,filter){startTime=startTime||0;endTime=endTime||Infinity;const stack=[];const startEvent=TimelineModel.TimelineModel._topLevelEventEndingAfter(events,startTime);for(let i=startEvent;i<events.length;++i){const e=events[i];if((e.endTime||e.startTime)<startTime)
continue;if(e.startTime>=endTime)
break;if(SDK.TracingModel.isAsyncPhase(e.phase)||SDK.TracingModel.isFlowPhase(e.phase))
continue;while(stack.length&&stack.peekLast().endTime<=e.startTime)
onEndEvent(stack.pop());if(filter&&!filter(e))
continue;if(e.duration){onStartEvent(e);stack.push(e);}else{onInstantEvent&&onInstantEvent(e,stack.peekLast()||null);}}
while(stack.length)
onEndEvent(stack.pop());}
static _topLevelEventEndingAfter(events,time){let index=events.upperBound(time,(time,event)=>time-event.startTime)-1;while(index>0&&!SDK.TracingModel.isTopLevelEvent(events[index]))
index--;return Math.max(index,0);}
isMarkerEvent(event){const recordTypes=TimelineModel.TimelineModel.RecordType;switch(event.name){case recordTypes.TimeStamp:return true;case recordTypes.MarkFirstPaint:case recordTypes.MarkFCP:case recordTypes.MarkFMP:return this._mainFrame&&event.args.frame===this._mainFrame.frameId&&!!event.args.data;case recordTypes.MarkDOMContent:case recordTypes.MarkLoad:return!!event.args['data']['isMainFrame'];default:return false;}}
static globalEventId(event,field){const data=event.args['data']||event.args['beginData'];const id=data&&data[field];if(!id)
return'';return`${event.thread.process().id()}.${id}`;}
static eventFrameId(event){const data=event.args['data']||event.args['beginData'];return data&&data['frame']||'';}
cpuProfiles(){return this._cpuProfiles;}
targetByEvent(event){const workerId=this._workerIdByThread.get(event.thread);const mainTarget=SDK.targetManager.mainTarget();return workerId?SDK.targetManager.targetById(workerId):mainTarget;}
setEvents(tracingModel){this._reset();this._resetProcessingState();this._tracingModel=tracingModel;this._minimumRecordTime=tracingModel.minimumRecordTime();this._maximumRecordTime=tracingModel.maximumRecordTime();this._processSyncBrowserEvents(tracingModel);if(this._browserFrameTracking){this._processThreadsForBrowserFrames(tracingModel);}else{const metadataEvents=this._processMetadataEvents(tracingModel);this._isGenericTrace=!metadataEvents;if(metadataEvents)
this._processMetadataAndThreads(tracingModel,metadataEvents);else
this._processGenericTrace(tracingModel);}
this._inspectedTargetEvents.stableSort(SDK.TracingModel.Event.compareStartTime);this._processAsyncBrowserEvents(tracingModel);this._buildGPUEvents(tracingModel);this._resetProcessingState();}
_processGenericTrace(tracingModel){let browserMainThread=SDK.TracingModel.browserMainThread(tracingModel);if(!browserMainThread&&tracingModel.sortedProcesses().length)
browserMainThread=tracingModel.sortedProcesses()[0].sortedThreads()[0];for(const process of tracingModel.sortedProcesses()){for(const thread of process.sortedThreads()){this._processThreadEvents(tracingModel,[{from:0,to:Infinity}],thread,thread===browserMainThread,false,true,null);}}}
_processMetadataAndThreads(tracingModel,metadataEvents){let startTime=0;for(let i=0,length=metadataEvents.page.length;i<length;i++){const metaEvent=metadataEvents.page[i];const process=metaEvent.thread.process();const endTime=i+1<length?metadataEvents.page[i+1].startTime:Infinity;if(startTime===endTime)
continue;this._legacyCurrentPage=metaEvent.args['data']&&metaEvent.args['data']['page'];for(const thread of process.sortedThreads()){let workerUrl=null;if(thread.name()===TimelineModel.TimelineModel.WorkerThreadName||thread.name()===TimelineModel.TimelineModel.WorkerThreadNameLegacy){const workerMetaEvent=metadataEvents.workers.find(e=>{if(e.args['data']['workerThreadId']!==thread.id())
return false;if(e.args['data']['sessionId']===this._sessionId)
return true;return!!this._pageFrames.get(TimelineModel.TimelineModel.eventFrameId(e));});if(!workerMetaEvent)
continue;const workerId=workerMetaEvent.args['data']['workerId'];if(workerId)
this._workerIdByThread.set(thread,workerId);workerUrl=workerMetaEvent.args['data']['url']||'';}
this._processThreadEvents(tracingModel,[{from:startTime,to:endTime}],thread,thread===metaEvent.thread,!!workerUrl,true,workerUrl);}
startTime=endTime;}}
_processThreadsForBrowserFrames(tracingModel){const processData=new Map();for(const frame of this._pageFrames.values()){for(let i=0;i<frame.processes.length;i++){const pid=frame.processes[i].processId;let data=processData.get(pid);if(!data){data=[];processData.set(pid,data);}
const to=i===frame.processes.length-1?(frame.deletedTime||this._maximumRecordTime):frame.processes[i+1].time;data.push({from:frame.processes[i].time,to:to,main:!frame.parent,url:frame.processes[i].url});}}
const allMetadataEvents=tracingModel.devToolsMetadataEvents();for(const process of tracingModel.sortedProcesses()){const data=processData.get(process.id());if(!data)
continue;data.sort((a,b)=>a.from-b.from||a.to-b.to);const ranges=[];let lastUrl=null;let lastMainUrl=null;let hasMain=false;for(const item of data){if(!ranges.length||item.from>ranges.peekLast().to)
ranges.push({from:item.from,to:item.to});else
ranges.peekLast().to=item.to;if(item.main)
hasMain=true;if(item.url){if(item.main)
lastMainUrl=item.url;lastUrl=item.url;}}
for(const thread of process.sortedThreads()){if(thread.name()===TimelineModel.TimelineModel.RendererMainThreadName){this._processThreadEvents(tracingModel,ranges,thread,true,false,hasMain,hasMain?lastMainUrl:lastUrl);}else if(thread.name()===TimelineModel.TimelineModel.WorkerThreadName||thread.name()===TimelineModel.TimelineModel.WorkerThreadNameLegacy){const workerMetaEvent=allMetadataEvents.find(e=>{if(e.name!==TimelineModel.TimelineModel.DevToolsMetadataEvent.TracingSessionIdForWorker)
return false;if(e.thread.process()!==process)
return false;if(e.args['data']['workerThreadId']!==thread.id())
return false;return!!this._pageFrames.get(TimelineModel.TimelineModel.eventFrameId(e));});if(!workerMetaEvent)
continue;this._workerIdByThread.set(thread,workerMetaEvent.args['data']['workerId']||'');this._processThreadEvents(tracingModel,ranges,thread,false,true,false,workerMetaEvent.args['data']['url']||'');}else{this._processThreadEvents(tracingModel,ranges,thread,false,false,false,null);}}}}
_processMetadataEvents(tracingModel){const metadataEvents=tracingModel.devToolsMetadataEvents();const pageDevToolsMetadataEvents=[];const workersDevToolsMetadataEvents=[];for(const event of metadataEvents){if(event.name===TimelineModel.TimelineModel.DevToolsMetadataEvent.TracingStartedInPage){pageDevToolsMetadataEvents.push(event);if(event.args['data']&&event.args['data']['persistentIds'])
this._persistentIds=true;const frames=((event.args['data']&&event.args['data']['frames'])||[]);frames.forEach(payload=>this._addPageFrame(event,payload));this._mainFrame=this.rootFrames()[0];}else if(event.name===TimelineModel.TimelineModel.DevToolsMetadataEvent.TracingSessionIdForWorker){workersDevToolsMetadataEvents.push(event);}else if(event.name===TimelineModel.TimelineModel.DevToolsMetadataEvent.TracingStartedInBrowser){console.assert(!this._mainFrameNodeId,'Multiple sessions in trace');this._mainFrameNodeId=event.args['frameTreeNodeId'];}}
if(!pageDevToolsMetadataEvents.length)
return null;const sessionId=pageDevToolsMetadataEvents[0].args['sessionId']||pageDevToolsMetadataEvents[0].args['data']['sessionId'];this._sessionId=sessionId;const mismatchingIds=new Set();function checkSessionId(event){let args=event.args;if(args['data'])
args=args['data'];const id=args['sessionId'];if(id===sessionId)
return true;mismatchingIds.add(id);return false;}
const result={page:pageDevToolsMetadataEvents.filter(checkSessionId).sort(SDK.TracingModel.Event.compareStartTime),workers:workersDevToolsMetadataEvents.sort(SDK.TracingModel.Event.compareStartTime)};if(mismatchingIds.size){Common.console.error('Timeline recording was started in more than one page simultaneously. Session id mismatch: '+
this._sessionId+' and '+mismatchingIds.valuesArray()+'.');}
return result;}
_processSyncBrowserEvents(tracingModel){const browserMain=SDK.TracingModel.browserMainThread(tracingModel);if(browserMain)
browserMain.events().forEach(this._processBrowserEvent,this);}
_processAsyncBrowserEvents(tracingModel){const browserMain=SDK.TracingModel.browserMainThread(tracingModel);if(browserMain)
this._processAsyncEvents(browserMain,[{from:0,to:Infinity}]);}
_buildGPUEvents(tracingModel){const thread=tracingModel.threadByName('GPU Process','CrGpuMain');if(!thread)
return;const gpuEventName=TimelineModel.TimelineModel.RecordType.GPUTask;const track=this._ensureNamedTrack(TimelineModel.TimelineModel.TrackType.GPU);track.thread=thread;track.events=thread.events().filter(event=>event.name===gpuEventName);}
_resetProcessingState(){this._asyncEventTracker=new TimelineModel.TimelineAsyncEventTracker();this._invalidationTracker=new TimelineModel.InvalidationTracker();this._layoutInvalidate={};this._lastScheduleStyleRecalculation={};this._paintImageEventByPixelRefId={};this._lastPaintForLayer={};this._lastRecalculateStylesEvent=null;this._currentScriptEvent=null;this._eventStack=[];this._knownInputEvents=new Set();this._browserFrameTracking=false;this._persistentIds=false;this._legacyCurrentPage=null;}
_extractCpuProfile(tracingModel,thread){const events=thread.events();let cpuProfile;let target=null;let cpuProfileEvent=events.peekLast();if(cpuProfileEvent&&cpuProfileEvent.name===TimelineModel.TimelineModel.RecordType.CpuProfile){const eventData=cpuProfileEvent.args['data'];cpuProfile=(eventData&&eventData['cpuProfile']);target=this.targetByEvent(cpuProfileEvent);}
if(!cpuProfile){cpuProfileEvent=events.find(e=>e.name===TimelineModel.TimelineModel.RecordType.Profile);if(!cpuProfileEvent)
return null;target=this.targetByEvent(cpuProfileEvent);const profileGroup=tracingModel.profileGroup(cpuProfileEvent);if(!profileGroup){Common.console.error('Invalid CPU profile format.');return null;}
cpuProfile=({startTime:cpuProfileEvent.args['data']['startTime'],endTime:0,nodes:[],samples:[],timeDeltas:[],lines:[]});for(const profileEvent of profileGroup.children){const eventData=profileEvent.args['data'];if('startTime'in eventData)
cpuProfile.startTime=eventData['startTime'];if('endTime'in eventData)
cpuProfile.endTime=eventData['endTime'];const nodesAndSamples=eventData['cpuProfile']||{};const samples=nodesAndSamples['samples']||[];const lines=eventData['lines']||Array(samples.length).fill(0);cpuProfile.nodes.pushAll(nodesAndSamples['nodes']||[]);cpuProfile.lines.pushAll(lines);cpuProfile.samples.pushAll(samples);cpuProfile.timeDeltas.pushAll(eventData['timeDeltas']||[]);if(cpuProfile.samples.length!==cpuProfile.timeDeltas.length){Common.console.error('Failed to parse CPU profile.');return null;}}
if(!cpuProfile.endTime)
cpuProfile.endTime=cpuProfile.timeDeltas.reduce((x,y)=>x+y,cpuProfile.startTime);}
try{const jsProfileModel=new SDK.CPUProfileDataModel(cpuProfile,target);this._cpuProfiles.push(jsProfileModel);return jsProfileModel;}catch(e){Common.console.error('Failed to parse CPU profile.');}
return null;}
_injectJSFrameEvents(tracingModel,thread){const jsProfileModel=this._extractCpuProfile(tracingModel,thread);let events=thread.events();const jsSamples=jsProfileModel?TimelineModel.TimelineJSProfileProcessor.generateTracingEventsFromCpuProfile(jsProfileModel,thread):null;if(jsSamples&&jsSamples.length)
events=events.mergeOrdered(jsSamples,SDK.TracingModel.Event.orderedCompareStartTime);if(jsSamples||events.some(e=>e.name===TimelineModel.TimelineModel.RecordType.JSSample)){const jsFrameEvents=TimelineModel.TimelineJSProfileProcessor.generateJSFrameEvents(events);if(jsFrameEvents&&jsFrameEvents.length)
events=jsFrameEvents.mergeOrdered(events,SDK.TracingModel.Event.orderedCompareStartTime);}
return events;}
_processThreadEvents(tracingModel,ranges,thread,isMainThread,isWorker,forMainFrame,url){const track=new TimelineModel.TimelineModel.Track();track.name=thread.name()||ls`Thread ${thread.id()}`;track.type=TimelineModel.TimelineModel.TrackType.Other;track.thread=thread;if(isMainThread){track.type=TimelineModel.TimelineModel.TrackType.MainThread;track.url=url||null;track.forMainFrame=forMainFrame;}else if(isWorker){track.type=TimelineModel.TimelineModel.TrackType.Worker;track.url=url;}else if(thread.name().startsWith('CompositorTileWorker')){track.type=TimelineModel.TimelineModel.TrackType.Raster;}
this._tracks.push(track);const events=this._injectJSFrameEvents(tracingModel,thread);this._eventStack=[];const eventStack=this._eventStack;for(const range of ranges){let i=events.lowerBound(range.from,(time,event)=>time-event.startTime);for(;i<events.length;i++){const event=events[i];if(event.startTime>=range.to)
break;while(eventStack.length&&eventStack.peekLast().endTime<=event.startTime)
eventStack.pop();if(!this._processEvent(event))
continue;if(!SDK.TracingModel.isAsyncPhase(event.phase)&&event.duration){if(eventStack.length){const parent=eventStack.peekLast();parent.selfTime-=event.duration;if(parent.selfTime<0)
this._fixNegativeDuration(parent,event);}
event.selfTime=event.duration;if(!eventStack.length)
track.tasks.push(event);eventStack.push(event);}
if(this.isMarkerEvent(event))
this._timeMarkerEvents.push(event);track.events.push(event);this._inspectedTargetEvents.push(event);}}
this._processAsyncEvents(thread,ranges);}
_fixNegativeDuration(event,child){const epsilon=1e-3;if(event.selfTime<-epsilon){console.error(`Children are longer than parent at ${event.startTime} `+`(${(child.startTime - this.minimumRecordTime()).toFixed(3)} by ${(-event.selfTime).toFixed(3)}`);}
event.selfTime=0;}
_processAsyncEvents(thread,ranges){const asyncEvents=thread.asyncEvents();const groups=new Map();function group(type){if(!groups.has(type))
groups.set(type,[]);return groups.get(type);}
for(const range of ranges){let i=asyncEvents.lowerBound(range.from,function(time,asyncEvent){return time-asyncEvent.startTime;});for(;i<asyncEvents.length;++i){const asyncEvent=asyncEvents[i];if(asyncEvent.startTime>=range.to)
break;if(asyncEvent.hasCategory(TimelineModel.TimelineModel.Category.Console)){group(TimelineModel.TimelineModel.TrackType.Console).push(asyncEvent);continue;}
if(asyncEvent.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)){group(TimelineModel.TimelineModel.TrackType.Timings).push(asyncEvent);continue;}
if(asyncEvent.name===TimelineModel.TimelineModel.RecordType.Animation){group(TimelineModel.TimelineModel.TrackType.Animation).push(asyncEvent);continue;}
if(asyncEvent.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)||asyncEvent.name===TimelineModel.TimelineModel.RecordType.ImplSideFling){const lastStep=asyncEvent.steps.peekLast();if(lastStep.phase!==SDK.TracingModel.Phase.AsyncEnd)
continue;const data=lastStep.args['data'];asyncEvent.causedFrame=!!(data&&data['INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT']);if(asyncEvent.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)){if(!this._knownInputEvents.has(lastStep.id))
continue;if(asyncEvent.name===TimelineModel.TimelineModel.RecordType.InputLatencyMouseMove&&!asyncEvent.causedFrame)
continue;const rendererMain=data['INPUT_EVENT_LATENCY_RENDERER_MAIN_COMPONENT'];if(rendererMain){const time=rendererMain['time']/1000;TimelineModel.TimelineData.forEvent(asyncEvent.steps[0]).timeWaitingForMainThread=time-asyncEvent.steps[0].startTime;}}
group(TimelineModel.TimelineModel.TrackType.Input).push(asyncEvent);continue;}}}
for(const[type,events]of groups){const track=this._ensureNamedTrack(type);track.thread=thread;track.asyncEvents=track.asyncEvents.mergeOrdered(events,SDK.TracingModel.Event.compareStartTime);}}
_processEvent(event){const recordTypes=TimelineModel.TimelineModel.RecordType;const eventStack=this._eventStack;if(!eventStack.length){if(this._currentTaskLayoutAndRecalcEvents&&this._currentTaskLayoutAndRecalcEvents.length){const totalTime=this._currentTaskLayoutAndRecalcEvents.reduce((time,event)=>time+event.duration,0);if(totalTime>TimelineModel.TimelineModel.Thresholds.ForcedLayout){for(const e of this._currentTaskLayoutAndRecalcEvents){const timelineData=TimelineModel.TimelineData.forEvent(e);timelineData.warning=e.name===recordTypes.Layout?TimelineModel.TimelineModel.WarningType.ForcedLayout:TimelineModel.TimelineModel.WarningType.ForcedStyle;}}}
this._currentTaskLayoutAndRecalcEvents=[];}
if(this._currentScriptEvent&&event.startTime>this._currentScriptEvent.endTime)
this._currentScriptEvent=null;const eventData=event.args['data']||event.args['beginData']||{};const timelineData=TimelineModel.TimelineData.forEvent(event);if(eventData['stackTrace'])
timelineData.stackTrace=eventData['stackTrace'];if(timelineData.stackTrace&&event.name!==recordTypes.JSSample){for(let i=0;i<timelineData.stackTrace.length;++i){--timelineData.stackTrace[i].lineNumber;--timelineData.stackTrace[i].columnNumber;}}
let pageFrameId=TimelineModel.TimelineModel.eventFrameId(event);if(!pageFrameId&&eventStack.length)
pageFrameId=TimelineModel.TimelineData.forEvent(eventStack.peekLast()).frameId;timelineData.frameId=pageFrameId||(this._mainFrame&&this._mainFrame.frameId)||'';this._asyncEventTracker.processEvent(event);if(this.isMarkerEvent(event))
this._ensureNamedTrack(TimelineModel.TimelineModel.TrackType.Timings);switch(event.name){case recordTypes.ResourceSendRequest:case recordTypes.WebSocketCreate:timelineData.setInitiator(eventStack.peekLast()||null);timelineData.url=eventData['url'];break;case recordTypes.ScheduleStyleRecalculation:this._lastScheduleStyleRecalculation[eventData['frame']]=event;break;case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:this._invalidationTracker.didRecalcStyle(event);if(event.args['beginData'])
timelineData.setInitiator(this._lastScheduleStyleRecalculation[event.args['beginData']['frame']]);this._lastRecalculateStylesEvent=event;if(this._currentScriptEvent)
this._currentTaskLayoutAndRecalcEvents.push(event);break;case recordTypes.ScheduleStyleInvalidationTracking:case recordTypes.StyleRecalcInvalidationTracking:case recordTypes.StyleInvalidatorInvalidationTracking:case recordTypes.LayoutInvalidationTracking:case recordTypes.LayerInvalidationTracking:case recordTypes.PaintInvalidationTracking:this._invalidationTracker.addInvalidation(new TimelineModel.InvalidationTrackingEvent(event));break;case recordTypes.InvalidateLayout:{let layoutInitator=event;const frameId=eventData['frame'];if(!this._layoutInvalidate[frameId]&&this._lastRecalculateStylesEvent&&this._lastRecalculateStylesEvent.endTime>event.startTime)
layoutInitator=TimelineModel.TimelineData.forEvent(this._lastRecalculateStylesEvent).initiator();this._layoutInvalidate[frameId]=layoutInitator;break;}
case recordTypes.Layout:{this._invalidationTracker.didLayout(event);const frameId=event.args['beginData']['frame'];timelineData.setInitiator(this._layoutInvalidate[frameId]);if(event.args['endData'])
timelineData.backendNodeId=event.args['endData']['rootNode'];this._layoutInvalidate[frameId]=null;if(this._currentScriptEvent)
this._currentTaskLayoutAndRecalcEvents.push(event);break;}
case recordTypes.Task:if(event.duration>TimelineModel.TimelineModel.Thresholds.LongTask)
timelineData.warning=TimelineModel.TimelineModel.WarningType.LongTask;break;case recordTypes.EventDispatch:if(event.duration>TimelineModel.TimelineModel.Thresholds.RecurringHandler)
timelineData.warning=TimelineModel.TimelineModel.WarningType.LongHandler;break;case recordTypes.TimerFire:case recordTypes.FireAnimationFrame:if(event.duration>TimelineModel.TimelineModel.Thresholds.RecurringHandler)
timelineData.warning=TimelineModel.TimelineModel.WarningType.LongRecurringHandler;break;case recordTypes.FunctionCall:if(typeof eventData['scriptName']==='string')
eventData['url']=eventData['scriptName'];if(typeof eventData['scriptLine']==='number')
eventData['lineNumber']=eventData['scriptLine'];case recordTypes.EvaluateScript:case recordTypes.CompileScript:if(typeof eventData['lineNumber']==='number')
--eventData['lineNumber'];if(typeof eventData['columnNumber']==='number')
--eventData['columnNumber'];case recordTypes.RunMicrotasks:if(!this._currentScriptEvent)
this._currentScriptEvent=event;break;case recordTypes.SetLayerTreeId:if(this._sessionId&&eventData['sessionId']&&this._sessionId===eventData['sessionId']){this._mainFrameLayerTreeId=eventData['layerTreeId'];break;}
const frameId=TimelineModel.TimelineModel.eventFrameId(event);const pageFrame=this._pageFrames.get(frameId);if(!pageFrame||pageFrame.parent)
return false;this._mainFrameLayerTreeId=eventData['layerTreeId'];break;case recordTypes.Paint:{this._invalidationTracker.didPaint(event);timelineData.backendNodeId=eventData['nodeId'];if(!eventData['layerId'])
break;const layerId=eventData['layerId'];this._lastPaintForLayer[layerId]=event;break;}
case recordTypes.DisplayItemListSnapshot:case recordTypes.PictureSnapshot:{const layerUpdateEvent=this._findAncestorEvent(recordTypes.UpdateLayer);if(!layerUpdateEvent||layerUpdateEvent.args['layerTreeId']!==this._mainFrameLayerTreeId)
break;const paintEvent=this._lastPaintForLayer[layerUpdateEvent.args['layerId']];if(paintEvent){TimelineModel.TimelineData.forEvent(paintEvent).picture=(event);}
break;}
case recordTypes.ScrollLayer:timelineData.backendNodeId=eventData['nodeId'];break;case recordTypes.PaintImage:timelineData.backendNodeId=eventData['nodeId'];timelineData.url=eventData['url'];break;case recordTypes.DecodeImage:case recordTypes.ResizeImage:{let paintImageEvent=this._findAncestorEvent(recordTypes.PaintImage);if(!paintImageEvent){const decodeLazyPixelRefEvent=this._findAncestorEvent(recordTypes.DecodeLazyPixelRef);paintImageEvent=decodeLazyPixelRefEvent&&this._paintImageEventByPixelRefId[decodeLazyPixelRefEvent.args['LazyPixelRef']];}
if(!paintImageEvent)
break;const paintImageData=TimelineModel.TimelineData.forEvent(paintImageEvent);timelineData.backendNodeId=paintImageData.backendNodeId;timelineData.url=paintImageData.url;break;}
case recordTypes.DrawLazyPixelRef:{const paintImageEvent=this._findAncestorEvent(recordTypes.PaintImage);if(!paintImageEvent)
break;this._paintImageEventByPixelRefId[event.args['LazyPixelRef']]=paintImageEvent;const paintImageData=TimelineModel.TimelineData.forEvent(paintImageEvent);timelineData.backendNodeId=paintImageData.backendNodeId;timelineData.url=paintImageData.url;break;}
case recordTypes.FrameStartedLoading:if(timelineData.frameId!==event.args['frame'])
return false;break;case recordTypes.MarkDOMContent:case recordTypes.MarkLoad:{const frameId=TimelineModel.TimelineModel.eventFrameId(event);if(!this._pageFrames.has(frameId))
return false;break;}
case recordTypes.CommitLoad:{if(this._browserFrameTracking)
break;const frameId=TimelineModel.TimelineModel.eventFrameId(event);const isMainFrame=!!eventData['isMainFrame'];const pageFrame=this._pageFrames.get(frameId);if(pageFrame){pageFrame.update(event.startTime,eventData);}else{if(!this._persistentIds){if(eventData['page']&&eventData['page']!==this._legacyCurrentPage)
return false;}else if(isMainFrame){return false;}else if(!this._addPageFrame(event,eventData)){return false;}}
if(isMainFrame)
this._mainFrame=this._pageFrames.get(frameId);break;}
case recordTypes.FireIdleCallback:if(event.duration>eventData['allottedMilliseconds']+TimelineModel.TimelineModel.Thresholds.IdleCallbackAddon)
timelineData.warning=TimelineModel.TimelineModel.WarningType.IdleDeadlineExceeded;break;}
return true;}
_processBrowserEvent(event){if(event.name===TimelineModel.TimelineModel.RecordType.LatencyInfoFlow){const frameId=event.args['frameTreeNodeId'];if(typeof frameId==='number'&&frameId===this._mainFrameNodeId)
this._knownInputEvents.add(event.bind_id);return;}
if(event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory)&&event.args['data']){const data=event.args['data'];if(event.name===TimelineModel.TimelineModel.DevToolsMetadataEvent.TracingStartedInBrowser){if(!data['persistentIds'])
return;this._browserFrameTracking=true;this._mainFrameNodeId=data['frameTreeNodeId'];const frames=data['frames']||[];frames.forEach(payload=>{const parent=payload['parent']&&this._pageFrames.get(payload['parent']);if(payload['parent']&&!parent)
return;let frame=this._pageFrames.get(payload['frame']);if(!frame){frame=new TimelineModel.TimelineModel.PageFrame(payload);this._pageFrames.set(frame.frameId,frame);if(parent)
parent.addChild(frame);else
this._mainFrame=frame;}
frame.update(this._minimumRecordTime,payload);});return;}
if(event.name===TimelineModel.TimelineModel.DevToolsMetadataEvent.FrameCommittedInBrowser&&this._browserFrameTracking){let frame=this._pageFrames.get(data['frame']);if(!frame){const parent=data['parent']&&this._pageFrames.get(data['parent']);if(!parent)
return;frame=new TimelineModel.TimelineModel.PageFrame(data);this._pageFrames.set(frame.frameId,frame);parent.addChild(frame);}
frame.update(event.startTime,data);return;}
if(event.name===TimelineModel.TimelineModel.DevToolsMetadataEvent.ProcessReadyInBrowser&&this._browserFrameTracking){const frame=this._pageFrames.get(data['frame']);if(frame)
frame.processReady(data['processPseudoId'],data['processId']);return;}
if(event.name===TimelineModel.TimelineModel.DevToolsMetadataEvent.FrameDeletedInBrowser&&this._browserFrameTracking){const frame=this._pageFrames.get(data['frame']);if(frame)
frame.deletedTime=event.startTime;return;}}}
_ensureNamedTrack(type){if(!this._namedTracks.has(type)){const track=new TimelineModel.TimelineModel.Track();track.type=type;this._tracks.push(track);this._namedTracks.set(type,track);}
return this._namedTracks.get(type);}
_findAncestorEvent(name){for(let i=this._eventStack.length-1;i>=0;--i){const event=this._eventStack[i];if(event.name===name)
return event;}
return null;}
_addPageFrame(event,payload){const parent=payload['parent']&&this._pageFrames.get(payload['parent']);if(payload['parent']&&!parent)
return false;const pageFrame=new TimelineModel.TimelineModel.PageFrame(payload);this._pageFrames.set(pageFrame.frameId,pageFrame);pageFrame.update(event.startTime,payload);if(parent)
parent.addChild(pageFrame);return true;}
_reset(){this._isGenericTrace=false;this._tracks=[];this._namedTracks=new Map();this._inspectedTargetEvents=[];this._timeMarkerEvents=[];this._sessionId=null;this._mainFrameNodeId=null;this._cpuProfiles=[];this._workerIdByThread=new WeakMap();this._pageFrames=new Map();this._mainFrame=null;this._minimumRecordTime=0;this._maximumRecordTime=0;}
isGenericTrace(){return this._isGenericTrace;}
tracingModel(){return this._tracingModel;}
minimumRecordTime(){return this._minimumRecordTime;}
maximumRecordTime(){return this._maximumRecordTime;}
inspectedTargetEvents(){return this._inspectedTargetEvents;}
tracks(){return this._tracks;}
isEmpty(){return this.minimumRecordTime()===0&&this.maximumRecordTime()===0;}
timeMarkerEvents(){return this._timeMarkerEvents;}
rootFrames(){return Array.from(this._pageFrames.values()).filter(frame=>!frame.parent);}
pageURL(){return this._mainFrame&&this._mainFrame.url||'';}
pageFrameById(frameId){return frameId?this._pageFrames.get(frameId)||null:null;}
networkRequests(){if(this.isGenericTrace())
return[];const requests=new Map();const requestsList=[];const zeroStartRequestsList=[];const types=TimelineModel.TimelineModel.RecordType;const resourceTypes=new Set([types.ResourceSendRequest,types.ResourceReceiveResponse,types.ResourceReceivedData,types.ResourceFinish]);const events=this.inspectedTargetEvents();for(let i=0;i<events.length;++i){const e=events[i];if(!resourceTypes.has(e.name))
continue;const id=TimelineModel.TimelineModel.globalEventId(e,'requestId');let request=requests.get(id);if(request){request.addEvent(e);}else{request=new TimelineModel.TimelineModel.NetworkRequest(e);requests.set(id,request);if(request.startTime)
requestsList.push(request);else
zeroStartRequestsList.push(request);}}
return zeroStartRequestsList.concat(requestsList);}};TimelineModel.TimelineModel.RecordType={Task:'RunTask',Program:'Program',EventDispatch:'EventDispatch',GPUTask:'GPUTask',Animation:'Animation',RequestMainThreadFrame:'RequestMainThreadFrame',BeginFrame:'BeginFrame',NeedsBeginFrameChanged:'NeedsBeginFrameChanged',BeginMainThreadFrame:'BeginMainThreadFrame',ActivateLayerTree:'ActivateLayerTree',DrawFrame:'DrawFrame',HitTest:'HitTest',ScheduleStyleRecalculation:'ScheduleStyleRecalculation',RecalculateStyles:'RecalculateStyles',UpdateLayoutTree:'UpdateLayoutTree',InvalidateLayout:'InvalidateLayout',Layout:'Layout',UpdateLayer:'UpdateLayer',UpdateLayerTree:'UpdateLayerTree',PaintSetup:'PaintSetup',Paint:'Paint',PaintImage:'PaintImage',Rasterize:'Rasterize',RasterTask:'RasterTask',ScrollLayer:'ScrollLayer',CompositeLayers:'CompositeLayers',ScheduleStyleInvalidationTracking:'ScheduleStyleInvalidationTracking',StyleRecalcInvalidationTracking:'StyleRecalcInvalidationTracking',StyleInvalidatorInvalidationTracking:'StyleInvalidatorInvalidationTracking',LayoutInvalidationTracking:'LayoutInvalidationTracking',LayerInvalidationTracking:'LayerInvalidationTracking',PaintInvalidationTracking:'PaintInvalidationTracking',ParseHTML:'ParseHTML',ParseAuthorStyleSheet:'ParseAuthorStyleSheet',TimerInstall:'TimerInstall',TimerRemove:'TimerRemove',TimerFire:'TimerFire',XHRReadyStateChange:'XHRReadyStateChange',XHRLoad:'XHRLoad',CompileScript:'v8.compile',EvaluateScript:'EvaluateScript',CompileModule:'v8.compileModule',EvaluateModule:'v8.evaluateModule',WasmStreamFromResponseCallback:'v8.wasm.streamFromResponseCallback',WasmCompiledModule:'v8.wasm.compiledModule',WasmCachedModule:'v8.wasm.cachedModule',WasmModuleCacheHit:'v8.wasm.moduleCacheHit',WasmModuleCacheInvalid:'v8.wasm.moduleCacheInvalid',FrameStartedLoading:'FrameStartedLoading',CommitLoad:'CommitLoad',MarkLoad:'MarkLoad',MarkDOMContent:'MarkDOMContent',MarkFirstPaint:'firstPaint',MarkFCP:'firstContentfulPaint',MarkFMP:'firstMeaningfulPaint',TimeStamp:'TimeStamp',ConsoleTime:'ConsoleTime',UserTiming:'UserTiming',ResourceSendRequest:'ResourceSendRequest',ResourceReceiveResponse:'ResourceReceiveResponse',ResourceReceivedData:'ResourceReceivedData',ResourceFinish:'ResourceFinish',RunMicrotasks:'RunMicrotasks',FunctionCall:'FunctionCall',GCEvent:'GCEvent',MajorGC:'MajorGC',MinorGC:'MinorGC',JSFrame:'JSFrame',JSSample:'JSSample',V8Sample:'V8Sample',JitCodeAdded:'JitCodeAdded',JitCodeMoved:'JitCodeMoved',ParseScriptOnBackground:'v8.parseOnBackground',V8Execute:'V8.Execute',UpdateCounters:'UpdateCounters',RequestAnimationFrame:'RequestAnimationFrame',CancelAnimationFrame:'CancelAnimationFrame',FireAnimationFrame:'FireAnimationFrame',RequestIdleCallback:'RequestIdleCallback',CancelIdleCallback:'CancelIdleCallback',FireIdleCallback:'FireIdleCallback',WebSocketCreate:'WebSocketCreate',WebSocketSendHandshakeRequest:'WebSocketSendHandshakeRequest',WebSocketReceiveHandshakeResponse:'WebSocketReceiveHandshakeResponse',WebSocketDestroy:'WebSocketDestroy',EmbedderCallback:'EmbedderCallback',SetLayerTreeId:'SetLayerTreeId',TracingStartedInPage:'TracingStartedInPage',TracingSessionIdForWorker:'TracingSessionIdForWorker',DecodeImage:'Decode Image',ResizeImage:'Resize Image',DrawLazyPixelRef:'Draw LazyPixelRef',DecodeLazyPixelRef:'Decode LazyPixelRef',LazyPixelRef:'LazyPixelRef',LayerTreeHostImplSnapshot:'cc::LayerTreeHostImpl',PictureSnapshot:'cc::Picture',DisplayItemListSnapshot:'cc::DisplayItemList',LatencyInfo:'LatencyInfo',LatencyInfoFlow:'LatencyInfo.Flow',InputLatencyMouseMove:'InputLatency::MouseMove',InputLatencyMouseWheel:'InputLatency::MouseWheel',ImplSideFling:'InputHandlerProxy::HandleGestureFling::started',GCCollectGarbage:'BlinkGC.AtomicPhase',CryptoDoEncrypt:'DoEncrypt',CryptoDoEncryptReply:'DoEncryptReply',CryptoDoDecrypt:'DoDecrypt',CryptoDoDecryptReply:'DoDecryptReply',CryptoDoDigest:'DoDigest',CryptoDoDigestReply:'DoDigestReply',CryptoDoSign:'DoSign',CryptoDoSignReply:'DoSignReply',CryptoDoVerify:'DoVerify',CryptoDoVerifyReply:'DoVerifyReply',CpuProfile:'CpuProfile',Profile:'Profile',A
syncEvents(){if(this.events.length)
return this.events;if(this._syncEvents)
return this._syncEvents;const stack=[];this._syncEvents=[];for(const event of this.asyncEvents){const startTime=event.startTime;const endTime=event.endTime;while(stack.length&&startTime>=stack.peekLast().endTime)
stack.pop();if(stack.length&&endTime>stack.peekLast().endTime){this._syncEvents=[];break;}
const syncEvent=new SDK.TracingModel.Event(event.categoriesString,event.name,SDK.TracingModel.Phase.Complete,startTime,event.thread);syncEvent.setEndTime(endTime);syncEvent.addArgs(event.args);this._syncEvents.push(syncEvent);stack.push(syncEvent);}
return this._syncEvents;}};TimelineModel.TimelineModel.TrackType={MainThread:Symbol('MainThread'),Worker:Symbol('Worker'),Input:Symbol('Input'),Animation:Symbol('Animation'),Timings:Symbol('Timings'),Console:Symbol('Console'),Raster:Symbol('Raster'),GPU:Symbol('GPU'),Other:Symbol('Other'),};TimelineModel.TimelineModel.PageFrame=class{constructor(payload){this.frameId=payload['frame'];this.url=payload['url']||'';this.name=payload['name'];this.children=[];this.parent=null;this.processes=[];this.deletedTime=null;this.ownerNode=null;}
update(time,payload){this.url=payload['url']||'';this.name=payload['name'];if(payload['processId']){this.processes.push({time:time,processId:payload['processId'],processPseudoId:'',url:payload['url']||''});}else{this.processes.push({time:time,processId:-1,processPseudoId:payload['processPseudoId'],url:payload['url']||''});}}
processReady(processPseudoId,processId){for(const process of this.processes){if(process.processPseudoId===processPseudoId){process.processPseudoId='';process.processId=processId;}}}
addChild(child){this.children.push(child);child.parent=this;}};TimelineModel.TimelineModel.MetadataEvents;TimelineModel.TimelineModel.NetworkRequest=class{constructor(event){this.startTime=event.name===TimelineModel.TimelineModel.RecordType.ResourceSendRequest?event.startTime:0;this.endTime=Infinity;this.encodedDataLength=0;this.decodedBodyLength=0;this.children=[];this.timing;this.mimeType;this.url;this.requestMethod;this.addEvent(event);}
addEvent(event){this.children.push(event);const recordType=TimelineModel.TimelineModel.RecordType;this.startTime=Math.min(this.startTime,event.startTime);const eventData=event.args['data'];if(eventData['mimeType'])
this.mimeType=eventData['mimeType'];if('priority'in eventData)
this.priority=eventData['priority'];if(event.name===recordType.ResourceFinish)
this.endTime=event.startTime;if(eventData['finishTime'])
this.finishTime=eventData['finishTime']*1000;if(!this.responseTime&&(event.name===recordType.ResourceReceiveResponse||event.name===recordType.ResourceReceivedData))
this.responseTime=event.startTime;const encodedDataLength=eventData['encodedDataLength']||0;if(event.name===recordType.ResourceReceiveResponse){if(eventData['fromCache'])
this.fromCache=true;if(eventData['fromServiceWorker'])
this.fromServiceWorker=true;this.encodedDataLength=encodedDataLength;}
if(event.name===recordType.ResourceReceivedData)
this.encodedDataLength+=encodedDataLength;if(event.name===recordType.ResourceFinish&&encodedDataLength)
this.encodedDataLength=encodedDataLength;const decodedBodyLength=eventData['decodedBodyLength'];if(event.name===recordType.ResourceFinish&&decodedBodyLength)
this.decodedBodyLength=decodedBodyLength;if(!this.url)
this.url=eventData['url'];if(!this.requestMethod)
this.requestMethod=eventData['requestMethod'];if(!this.timing)
this.timing=eventData['timing'];if(eventData['fromServiceWorker'])
this.fromServiceWorker=true;}
beginTime(){return Math.min(this.startTime,this.timing&&this.timing.requestTime*1000||Infinity,this.timing&&this.timing.pushStart*1000||Infinity);}};TimelineModel.InvalidationTrackingEvent=class{constructor(event){this.type=event.name;this.startTime=event.startTime;this._tracingEvent=event;const eventData=event.args['data'];this.frame=eventData['frame'];this.nodeId=eventData['nodeId'];this.nodeName=eventData['nodeName'];this.paintId=eventData['paintId'];this.invalidationSet=eventData['invalidationSet'];this.invalidatedSelectorId=eventData['invalidatedSelectorId'];this.changedId=eventData['changedId'];this.changedClass=eventData['changedClass'];this.changedAttribute=eventData['changedAttribute'];this.changedPseudo=eventData['changedPseudo'];this.selectorPart=eventData['selectorPart'];this.extraData=eventData['extraData'];this.invalidationList=eventData['invalidationList'];this.cause={reason:eventData['reason'],stackTrace:eventData['stackTrace']};if(!this.cause.reason&&this.cause.stackTrace&&this.type===TimelineModel.TimelineModel.RecordType.LayoutInvalidationTracking)
this.cause.reason='Layout forced';}};TimelineModel.InvalidationCause;TimelineModel.InvalidationTracker=class{constructor(){this._lastRecalcStyle=null;this._lastPaintWithLayer=null;this._didPaint=false;this._initializePerFrameState();}
static invalidationEventsFor(event){return event[TimelineModel.InvalidationTracker._invalidationTrackingEventsSymbol]||null;}
addInvalidation(invalidation){this._startNewFrameIfNeeded();if(!invalidation.nodeId&&!invalidation.paintId){console.error('Invalidation lacks node information.');console.error(invalidation);return;}
const recordTypes=TimelineModel.TimelineModel.RecordType;if(invalidation.type===recordTypes.PaintInvalidationTracking&&invalidation.nodeId){const invalidations=this._invalidationsByNodeId[invalidation.nodeId]||[];for(let i=0;i<invalidations.length;++i)
invalidations[i].paintId=invalidation.paintId;return;}
if(invalidation.type===recordTypes.StyleRecalcInvalidationTracking&&invalidation.cause.reason==='StyleInvalidator')
return;const styleRecalcInvalidation=(invalidation.type===recordTypes.ScheduleStyleInvalidationTracking||invalidation.type===recordTypes.StyleInvalidatorInvalidationTracking||invalidation.type===recordTypes.StyleRecalcInvalidationTracking);if(styleRecalcInvalidation){const duringRecalcStyle=invalidation.startTime&&this._lastRecalcStyle&&invalidation.startTime>=this._lastRecalcStyle.startTime&&invalidation.startTime<=this._lastRecalcStyle.endTime;if(duringRecalcStyle)
this._associateWithLastRecalcStyleEvent(invalidation);}
if(this._invalidations[invalidation.type])
this._invalidations[invalidation.type].push(invalidation);else
this._invalidations[invalidation.type]=[invalidation];if(invalidation.nodeId){if(this._invalidationsByNodeId[invalidation.nodeId])
this._invalidationsByNodeId[invalidation.nodeId].push(invalidation);else
this._invalidationsByNodeId[invalidation.nodeId]=[invalidation];}}
didRecalcStyle(recalcStyleEvent){this._lastRecalcStyle=recalcStyleEvent;const types=[TimelineModel.TimelineModel.RecordType.ScheduleStyleInvalidationTracking,TimelineModel.TimelineModel.RecordType.StyleInvalidatorInvalidationTracking,TimelineModel.TimelineModel.RecordType.StyleRecalcInvalidationTracking];for(const invalidation of this._invalidationsOfTypes(types))
this._associateWithLastRecalcStyleEvent(invalidation);}
_associateWithLastRecalcStyleEvent(invalidation){if(invalidation.linkedRecalcStyleEvent)
return;const recordTypes=TimelineModel.TimelineModel.RecordType;const recalcStyleFrameId=this._lastRecalcStyle.args['beginData']['frame'];if(invalidation.type===recordTypes.StyleInvalidatorInvalidationTracking){this._addSyntheticStyleRecalcInvalidations(this._lastRecalcStyle,recalcStyleFrameId,invalidation);}else if(invalidation.type===recordTypes.ScheduleStyleInvalidationTracking){}else{this._addInvalidationToEvent(this._lastRecalcStyle,recalcStyleFrameId,invalidation);}
invalidation.linkedRecalcStyleEvent=true;}
_addSyntheticStyleRecalcInvalidations(event,frameId,styleInvalidatorInvalidation){if(!styleInvalidatorInvalidation.invalidationList){this._addSyntheticStyleRecalcInvalidation(styleInvalidatorInvalidation._tracingEvent,styleInvalidatorInvalidation);return;}
if(!styleInvalidatorInvalidation.nodeId){console.error('Invalidation lacks node information.');console.error(styleInvalidatorInvalidation);return;}
for(let i=0;i<styleInvalidatorInvalidation.invalidationList.length;i++){const setId=styleInvalidatorInvalidation.invalidationList[i]['id'];let lastScheduleStyleRecalculation;const nodeInvalidations=this._invalidationsByNodeId[styleInvalidatorInvalidation.nodeId]||[];for(let j=0;j<nodeInvalidations.length;j++){const invalidation=nodeInvalidations[j];if(invalidation.frame!==frameId||invalidation.invalidationSet!==setId||invalidation.type!==TimelineModel.TimelineModel.RecordType.ScheduleStyleInvalidationTracking)
continue;lastScheduleStyleRecalculation=invalidation;}
if(!lastScheduleStyleRecalculation){console.error('Failed to lookup the event that scheduled a style invalidator invalidation.');continue;}
this._addSyntheticStyleRecalcInvalidation(lastScheduleStyleRecalculation._tracingEvent,styleInvalidatorInvalidation);}}
_addSyntheticStyleRecalcInvalidation(baseEvent,styleInvalidatorInvalidation){const invalidation=new TimelineModel.InvalidationTrackingEvent(baseEvent);invalidation.type=TimelineModel.TimelineModel.RecordType.StyleRecalcInvalidationTracking;if(styleInvalidatorInvalidation.cause.reason)
invalidation.cause.reason=styleInvalidatorInvalidation.cause.reason;if(styleInvalidatorInvalidation.selectorPart)
invalidation.selectorPart=styleInvalidatorInvalidation.selectorPart;this.addInvalidation(invalidation);if(!invalidation.linkedRecalcStyleEvent)
this._associateWithLastRecalcStyleEvent(invalidation);}
didLayout(layoutEvent){const layoutFrameId=layoutEvent.args['beginData']['frame'];for(const invalidation of this._invalidationsOfTypes([TimelineModel.TimelineModel.RecordType.LayoutInvalidationTracking])){if(invalidation.linkedLayoutEvent)
continue;this._addInvalidationToEvent(layoutEvent,layoutFrameId,invalidation);invalidation.linkedLayoutEvent=true;}}
didPaint(paintEvent){this._didPaint=true;const layerId=paintEvent.args['data']['layerId'];if(layerId)
this._lastPaintWithLayer=paintEvent;if(!this._lastPaintWithLayer)
return;const effectivePaintId=this._lastPaintWithLayer.args['data']['nodeId'];const paintFrameId=paintEvent.args['data']['frame'];const types=[TimelineModel.TimelineModel.RecordType.StyleRecalcInvalidationTracking,TimelineModel.TimelineModel.RecordType.LayoutInvalidationTracking,TimelineModel.TimelineModel.RecordType.PaintInvalidationTracking];for(const invalidation of this._invalidationsOfTypes(types)){if(invalidation.paintId===effectivePaintId)
this._addInvalidationToEvent(paintEvent,paintFrameId,invalidation);}}
_addInvalidationToEvent(event,eventFrameId,invalidation){if(eventFrameId!==invalidation.frame)
return;if(!event[TimelineModel.InvalidationTracker._invalidationTrackingEventsSymbol])
event[TimelineModel.InvalidationTracker._invalidationTrackingEventsSymbol]=[invalidation];else
event[TimelineModel.InvalidationTracker._invalidationTrackingEventsSymbol].push(invalidation);}
_invalidationsOfTypes(types){const invalidations=this._invalidations;if(!types)
types=Object.keys(invalidations);function*generator(){for(let i=0;i<types.length;++i){const invalidationList=invalidations[types[i]]||[];for(let j=0;j<invalidationList.length;++j)
yield invalidationList[j];}}
return generator();}
_startNewFrameIfNeeded(){if(!this._didPaint)
return;this._initializePerFrameState();}
_initializePerFrameState(){this._invalidations={};this._invalidationsByNodeId={};this._lastRecalcStyle=null;this._lastPaintWithLayer=null;this._didPaint=false;}};TimelineModel.InvalidationTracker._invalidationTrackingEventsSymbol=Symbol('invalidationTrackingEvents');TimelineModel.TimelineAsyncEventTracker=class{constructor(){TimelineModel.TimelineAsyncEventTracker._initialize();this._initiatorByType=new Map();for(const initiator of TimelineModel.TimelineAsyncEventTracker._asyncEvents.keys())
this._initiatorByType.set(initiator,new Map());}
static _initialize(){if(TimelineModel.TimelineAsyncEventTracker._asyncEvents)
return;const events=new Map();let type=TimelineModel.TimelineModel.RecordType;events.set(type.TimerInstall,{causes:[type.TimerFire],joinBy:'timerId'});events.set(type.ResourceSendRequest,{causes:[type.ResourceReceiveResponse,type.ResourceReceivedData,type.ResourceFinish],joinBy:'requestId'});events.set(type.RequestAnimationFrame,{causes:[type.FireAnimationFrame],joinBy:'id'});events.set(type.RequestIdleCallback,{causes:[type.FireIdleCallback],joinBy:'id'});events.set(type.WebSocketCreate,{causes:[type.WebSocketSendHandshakeRequest,type.WebSocketReceiveHandshakeResponse,type.WebSocketDestroy],joinBy:'identifier'});TimelineModel.TimelineAsyncEventTracker._asyncEvents=events;TimelineModel.TimelineAsyncEventTracker._typeToInitiator=new Map();for(const entry of events){const types=entry[1].causes;for(type of types)
TimelineModel.TimelineAsyncEventTracker._typeToInitiator.set(type,entry[0]);}}
processEvent(event){let initiatorType=TimelineModel.TimelineAsyncEventTracker._typeToInitiator.get((event.name));const isInitiator=!initiatorType;if(!initiatorType)
initiatorType=(event.name);const initiatorInfo=TimelineModel.TimelineAsyncEventTracker._asyncEvents.get(initiatorType);if(!initiatorInfo)
return;const id=TimelineModel.TimelineModel.globalEventId(event,initiatorInfo.joinBy);if(!id)
return;const initiatorMap=this._initiatorByType.get(initiatorType);if(isInitiator){initiatorMap.set(id,event);return;}
const initiator=initiatorMap.get(id)||null;const timelineData=TimelineModel.TimelineData.forEvent(event);timelineData.setInitiator(initiator);if(!timelineData.frameId&&initiator)
timelineData.frameId=TimelineModel.TimelineModel.eventFrameId(initiator);}};TimelineModel.TimelineData=class{constructor(){this.warning=null;this.previewElement=null;this.url=null;this.backendNodeId=0;this.stackTrace=null;this.picture=null;this._initiator=null;this.frameId='';this.timeWaitingForMainThread;}
setInitiator(initiator){this._initiator=initiator;if(!initiator||this.url)
return;const initiatorURL=TimelineModel.TimelineData.forEvent(initiator).url;if(initiatorURL)
this.url=initiatorURL;}
initiator(){return this._initiator;}
topFrame(){const stackTrace=this.stackTraceForSelfOrInitiator();return stackTrace&&stackTrace[0]||null;}
stackTraceForSelfOrInitiator(){return this.stackTrace||(this._initiator&&TimelineModel.TimelineData.forEvent(this._initiator).stackTrace);}
static forEvent(event){let data=event[TimelineModel.TimelineData._symbol];if(!data){data=new TimelineModel.TimelineData();event[TimelineModel.TimelineData._symbol]=data;}
return data;}};TimelineModel.TimelineData._symbol=Symbol('timelineData');;TimelineModel.TimelineIRModel=class{constructor(){this.reset();}
static phaseForEvent(event){return event[TimelineModel.TimelineIRModel._eventIRPhase];}
populate(inputLatencies,animations){this.reset();if(!inputLatencies)
return;this._processInputLatencies(inputLatencies);if(animations)
this._processAnimations(animations);const range=new Common.SegmentedRange();range.appendRange(this._drags);range.appendRange(this._cssAnimations);range.appendRange(this._scrolls);range.appendRange(this._responses);this._segments=range.segments();}
_processInputLatencies(events){const eventTypes=TimelineModel.TimelineIRModel.InputEvents;const phases=TimelineModel.TimelineIRModel.Phases;const thresholdsMs=TimelineModel.TimelineIRModel._mergeThresholdsMs;let scrollStart;let flingStart;let touchStart;let firstTouchMove;let mouseWheel;let mouseDown;let mouseMove;for(let i=0;i<events.length;++i){const event=events[i];if(i>0&&events[i].startTime<events[i-1].startTime)
console.assert(false,'Unordered input events');const type=this._inputEventType(event.name);switch(type){case eventTypes.ScrollBegin:this._scrolls.append(this._segmentForEvent(event,phases.Scroll));scrollStart=event;break;case eventTypes.ScrollEnd:if(scrollStart)
this._scrolls.append(this._segmentForEventRange(scrollStart,event,phases.Scroll));else
this._scrolls.append(this._segmentForEvent(event,phases.Scroll));scrollStart=null;break;case eventTypes.ScrollUpdate:touchStart=null;this._scrolls.append(this._segmentForEvent(event,phases.Scroll));break;case eventTypes.FlingStart:if(flingStart){Common.console.error(Common.UIString('Two flings at the same time? %s vs %s',flingStart.startTime,event.startTime));break;}
flingStart=event;break;case eventTypes.FlingCancel:if(!flingStart)
break;this._scrolls.append(this._segmentForEventRange(flingStart,event,phases.Fling));flingStart=null;break;case eventTypes.ImplSideFling:this._scrolls.append(this._segmentForEvent(event,phases.Fling));break;case eventTypes.ShowPress:case eventTypes.Tap:case eventTypes.KeyDown:case eventTypes.KeyDownRaw:case eventTypes.KeyUp:case eventTypes.Char:case eventTypes.Click:case eventTypes.ContextMenu:this._responses.append(this._segmentForEvent(event,phases.Response));break;case eventTypes.TouchStart:if(touchStart){Common.console.error(Common.UIString('Two touches at the same time? %s vs %s',touchStart.startTime,event.startTime));break;}
touchStart=event;event.steps[0][TimelineModel.TimelineIRModel._eventIRPhase]=phases.Response;firstTouchMove=null;break;case eventTypes.TouchCancel:touchStart=null;break;case eventTypes.TouchMove:if(firstTouchMove){this._drags.append(this._segmentForEvent(event,phases.Drag));}else if(touchStart){firstTouchMove=event;this._responses.append(this._segmentForEventRange(touchStart,event,phases.Response));}
break;case eventTypes.TouchEnd:touchStart=null;break;case eventTypes.MouseDown:mouseDown=event;mouseMove=null;break;case eventTypes.MouseMove:if(mouseDown&&!mouseMove&&mouseDown.startTime+thresholdsMs.mouse>event.startTime){this._responses.append(this._segmentForEvent(mouseDown,phases.Response));this._responses.append(this._segmentForEvent(event,phases.Response));}else if(mouseDown){this._drags.append(this._segmentForEvent(event,phases.Drag));}
mouseMove=event;break;case eventTypes.MouseUp:this._responses.append(this._segmentForEvent(event,phases.Response));mouseDown=null;break;case eventTypes.MouseWheel:if(mouseWheel&&canMerge(thresholdsMs.mouse,mouseWheel,event))
this._scrolls.append(this._segmentForEventRange(mouseWheel,event,phases.Scroll));else
this._scrolls.append(this._segmentForEvent(event,phases.Scroll));mouseWheel=event;break;}}
function canMerge(threshold,first,second){return first.endTime<second.startTime&&second.startTime<first.endTime+threshold;}}
_processAnimations(events){for(let i=0;i<events.length;++i)
this._cssAnimations.append(this._segmentForEvent(events[i],TimelineModel.TimelineIRModel.Phases.Animation));}
_segmentForEvent(event,phase){this._setPhaseForEvent(event,phase);return new Common.Segment(event.startTime,event.endTime,phase);}
_segmentForEventRange(startEvent,endEvent,phase){this._setPhaseForEvent(startEvent,phase);this._setPhaseForEvent(endEvent,phase);return new Common.Segment(startEvent.startTime,endEvent.endTime,phase);}
_setPhaseForEvent(asyncEvent,phase){asyncEvent.steps[0][TimelineModel.TimelineIRModel._eventIRPhase]=phase;}
interactionRecords(){return this._segments;}
reset(){const thresholdsMs=TimelineModel.TimelineIRModel._mergeThresholdsMs;this._segments=[];this._drags=new Common.SegmentedRange(merge.bind(null,thresholdsMs.mouse));this._cssAnimations=new Common.SegmentedRange(merge.bind(null,thresholdsMs.animation));this._responses=new Common.SegmentedRange(merge.bind(null,0));this._scrolls=new Common.SegmentedRange(merge.bind(null,thresholdsMs.animation));function merge(threshold,first,second){return first.end+threshold>=second.begin&&first.data===second.data?first:null;}}
_inputEventType(eventName){const prefix='InputLatency::';if(!eventName.startsWith(prefix)){if(eventName===TimelineModel.TimelineIRModel.InputEvents.ImplSideFling)
return(eventName);console.error('Unrecognized input latency event: '+eventName);return null;}
return(eventName.substr(prefix.length));}};TimelineModel.TimelineIRModel.Phases={Idle:'Idle',Response:'Response',Scroll:'Scroll',Fling:'Fling',Drag:'Drag',Animation:'Animation',Uncategorized:'Uncategorized'};TimelineModel.TimelineIRModel.InputEvents={Char:'Char',Click:'GestureClick',ContextMenu:'ContextMenu',FlingCancel:'GestureFlingCancel',FlingStart:'GestureFlingStart',ImplSideFling:TimelineModel.TimelineModel.RecordType.ImplSideFling,KeyDown:'KeyDown',KeyDownRaw:'RawKeyDown',KeyUp:'KeyUp',LatencyScrollUpdate:'ScrollUpdate',MouseDown:'MouseDown',MouseMove:'MouseMove',MouseUp:'MouseUp',MouseWheel:'MouseWheel',PinchBegin:'GesturePinchBegin',PinchEnd:'GesturePinchEnd',PinchUpdate:'GesturePinchUpdate',ScrollBegin:'GestureScrollBegin',ScrollEnd:'GestureScrollEnd',ScrollUpdate:'GestureScrollUpdate',ScrollUpdateRenderer:'ScrollUpdate',ShowPress:'GestureShowPress',Tap:'GestureTap',TapCancel:'GestureTapCancel',TapDown:'GestureTapDown',TouchCancel:'TouchCancel',TouchEnd:'TouchEnd',TouchMove:'TouchMove',TouchStart:'TouchStart'};TimelineModel.TimelineIRModel._mergeThresholdsMs={animation:1,mouse:40,};TimelineModel.TimelineIRModel._eventIRPhase=Symbol('eventIRPhase');;TimelineModel.TimelineJSProfileProcessor=class{static generateTracingEventsFromCpuProfile(jsProfileModel,thread){const idleNode=jsProfileModel.idleNode;const programNode=jsProfileModel.programNode;const gcNode=jsProfileModel.gcNode;const samples=jsProfileModel.samples;const timestamps=jsProfileModel.timestamps;const jsEvents=[];const nodeToStackMap=new Map();nodeToStackMap.set(programNode,[]);for(let i=0;i<samples.length;++i){let node=jsProfileModel.nodeByIndex(i);if(!node){console.error(`Node with unknown id ${samples[i]} at index ${i}`);continue;}
if(node===gcNode||node===idleNode)
continue;let callFrames=nodeToStackMap.get(node);if(!callFrames){callFrames=(new Array(node.depth+1));nodeToStackMap.set(node,callFrames);for(let j=0;node.parent;node=node.parent)
callFrames[j++]=(node);}
const jsSampleEvent=new SDK.TracingModel.Event(SDK.TracingModel.DevToolsTimelineEventCategory,TimelineModel.TimelineModel.RecordType.JSSample,SDK.TracingModel.Phase.Instant,timestamps[i],thread);jsSampleEvent.args['data']={stackTrace:callFrames};jsEvents.push(jsSampleEvent);}
return jsEvents;}
static generateJSFrameEvents(events){function equalFrames(frame1,frame2){return frame1.scriptId===frame2.scriptId&&frame1.functionName===frame2.functionName&&frame1.lineNumber===frame2.lineNumber;}
function isJSInvocationEvent(e){switch(e.name){case TimelineModel.TimelineModel.RecordType.RunMicrotasks:case TimelineModel.TimelineModel.RecordType.FunctionCall:case TimelineModel.TimelineModel.RecordType.EvaluateScript:case TimelineModel.TimelineModel.RecordType.EvaluateModule:case TimelineModel.TimelineModel.RecordType.EventDispatch:case TimelineModel.TimelineModel.RecordType.V8Execute:return true;}
return false;}
const jsFrameEvents=[];const jsFramesStack=[];const lockedJsStackDepth=[];let ordinal=0;const showAllEvents=Runtime.experiments.isEnabled('timelineShowAllEvents');const showRuntimeCallStats=Runtime.experiments.isEnabled('timelineV8RuntimeCallStats');const showNativeFunctions=Common.moduleSetting('showNativeFunctionsInJSProfile').get();function onStartEvent(e){e.ordinal=++ordinal;extractStackTrace(e);lockedJsStackDepth.push(jsFramesStack.length);}
function onInstantEvent(e,parent){e.ordinal=++ordinal;if(parent&&isJSInvocationEvent(parent))
extractStackTrace(e);}
function onEndEvent(e){truncateJSStack(lockedJsStackDepth.pop(),e.endTime);}
function truncateJSStack(depth,time){if(lockedJsStackDepth.length){const lockedDepth=lockedJsStackDepth.peekLast();if(depth<lockedDepth){console.error(`Child stack is shallower (${depth}) than the parent stack (${lockedDepth}) at ${time}`);depth=lockedDepth;}}
if(jsFramesStack.length<depth){console.error(`Trying to truncate higher than the current stack size at ${time}`);depth=jsFramesStack.length;}
for(let k=0;k<jsFramesStack.length;++k)
jsFramesStack[k].setEndTime(time);jsFramesStack.length=depth;}
function showNativeName(name){return showRuntimeCallStats&&!!TimelineModel.TimelineJSProfileProcessor.nativeGroup(name);}
function filterStackFrames(stack){if(showAllEvents)
return;let previousNativeFrameName=null;let j=0;for(let i=0;i<stack.length;++i){const frame=stack[i];const url=frame.url;const isNativeFrame=url&&url.startsWith('native ');if(!showNativeFunctions&&isNativeFrame)
continue;const isNativeRuntimeFrame=TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame);if(isNativeRuntimeFrame&&!showNativeName(frame.functionName))
continue;const nativeFrameName=isNativeRuntimeFrame?TimelineModel.TimelineJSProfileProcessor.nativeGroup(frame.functionName):null;if(previousNativeFrameName&&previousNativeFrameName===nativeFrameName)
continue;previousNativeFrameName=nativeFrameName;stack[j++]=frame;}
stack.length=j;}
function extractStackTrace(e){const recordTypes=TimelineModel.TimelineModel.RecordType;const callFrames=e.name===recordTypes.JSSample?e.args['data']['stackTrace'].slice().reverse():jsFramesStack.map(frameEvent=>frameEvent.args['data']);filterStackFrames(callFrames);const endTime=e.endTime||e.startTime;const minFrames=Math.min(callFrames.length,jsFramesStack.length);let i;for(i=lockedJsStackDepth.peekLast()||0;i<minFrames;++i){const newFrame=callFrames[i];const oldFrame=jsFramesStack[i].args['data'];if(!equalFrames(newFrame,oldFrame))
break;jsFramesStack[i].setEndTime(Math.max(jsFramesStack[i].endTime,endTime));}
truncateJSStack(i,e.startTime);for(;i<callFrames.length;++i){const frame=callFrames[i];const jsFrameEvent=new SDK.TracingModel.Event(SDK.TracingModel.DevToolsTimelineEventCategory,recordTypes.JSFrame,SDK.TracingModel.Phase.Complete,e.startTime,e.thread);jsFrameEvent.ordinal=e.ordinal;jsFrameEvent.addArgs({data:frame});jsFrameEvent.setEndTime(endTime);jsFramesStack.push(jsFrameEvent);jsFrameEvents.push(jsFrameEvent);}}
const firstTopLevelEvent=events.find(SDK.TracingModel.isTopLevelEvent);const startTime=firstTopLevelEvent?firstTopLevelEvent.startTime:0;TimelineModel.TimelineModel.forEachEvent(events,onStartEvent,onEndEvent,onInstantEvent,startTime);return jsFrameEvents;}
static isNativeRuntimeFrame(frame){return frame.url==='native V8Runtime';}
static nativeGroup(nativeName){if(nativeName.startsWith('Parse'))
return TimelineModel.TimelineJSProfileProcessor.NativeGroups.Parse;if(nativeName.startsWith('Compile')||nativeName.startsWith('Recompile'))
return TimelineModel.TimelineJSProfileProcessor.NativeGroups.Compile;return null;}
static buildTraceProfileFromCpuProfile(profile,tid,injectPageEvent,name){const events=[];if(injectPageEvent)
appendEvent('TracingStartedInPage',{data:{'sessionId':'1'}},0,0,'M');if(!name)
name=ls`Thread ${tid}`;appendEvent(SDK.TracingModel.MetadataEvent.ThreadName,{name},0,0,'M','__metadata');if(!profile)
return events;const idToNode=new Map();const nodes=profile['nodes'];for(let i=0;i<nodes.length;++i)
idToNode.set(nodes[i].id,nodes[i]);let programEvent=null;let functionEvent=null;let nextTime=profile.startTime;let currentTime;const samples=profile['samples'];const timeDeltas=profile['timeDeltas'];for(let i=0;i<samples.length;++i){currentTime=nextTime;nextTime+=timeDeltas[i];const node=idToNode.get(samples[i]);const name=node.callFrame.functionName;if(name==='(idle)'){closeEvents();continue;}
if(!programEvent)
programEvent=appendEvent('MessageLoop::RunTask',{},currentTime,0,'X','toplevel');if(name==='(program)'){if(functionEvent){functionEvent.dur=currentTime-functionEvent.ts;functionEvent=null;}}else{if(!functionEvent)
functionEvent=appendEvent('FunctionCall',{data:{'sessionId':'1'}},currentTime);}}
closeEvents();appendEvent('CpuProfile',{data:{'cpuProfile':profile}},profile.endTime,0,'I');return events;function closeEvents(){if(programEvent)
programEvent.dur=currentTime-programEvent.ts;if(functionEvent)
functionEvent.dur=currentTime-functionEvent.ts;programEvent=null;functionEvent=null;}
function appendEvent(name,args,ts,dur,ph,cat){const event=({cat:cat||'disabled-by-default-devtools.timeline',name,ph:ph||'X',pid:1,tid,ts,args});if(dur)
event.dur=dur;events.push(event);return event;}}};TimelineModel.TimelineJSProfileProcessor.NativeGroups={'Compile':'Compile','Parse':'Parse'};;TimelineModel.TimelineFrameModel=class{constructor(categoryMapper){this._categoryMapper=categoryMapper;this.reset();}
frames(startTime,endTime){if(!startTime&&!endTime)
return this._frames;const firstFrame=this._frames.lowerBound(startTime||0,(time,frame)=>time-frame.endTime);const lastFrame=this._frames.lowerBound(endTime||Infinity,(time,frame)=>time-frame.startTime);return this._frames.slice(firstFrame,lastFrame);}
hasRasterTile(rasterTask){const data=rasterTask.args['tileData'];if(!data)
return false;const frameId=data['sourceFrameNumber'];const frame=frameId&&this._frameById[frameId];if(!frame||!frame.layerTree)
return false;return true;}
rasterTilePromise(rasterTask){if(!this._target)
return Promise.resolve(null);const data=rasterTask.args['tileData'];const frameId=data['sourceFrameNumber'];const tileId=data['tileId']&&data['tileId']['id_ref'];const frame=frameId&&this._frameById[frameId];if(!frame||!frame.layerTree||!tileId)
return Promise.resolve(null);return frame.layerTree.layerTreePromise().then(layerTree=>layerTree&&layerTree.pictureForRasterTile(tileId));}
reset(){this._minimumRecordTime=Infinity;this._frames=[];this._frameById={};this._lastFrame=null;this._lastLayerTree=null;this._mainFrameCommitted=false;this._mainFrameRequested=false;this._framePendingCommit=null;this._lastBeginFrame=null;this._lastNeedsBeginFrame=null;this._framePendingActivation=null;this._lastTaskBeginTime=null;this._target=null;this._layerTreeId=null;this._currentTaskTimeByCategory={};}
handleBeginFrame(startTime){if(!this._lastFrame)
this._startFrame(startTime);this._lastBeginFrame=startTime;}
handleDrawFrame(startTime){if(!this._lastFrame){this._startFrame(startTime);return;}
if(this._mainFrameCommitted||!this._mainFrameRequested){if(this._lastNeedsBeginFrame){const idleTimeEnd=this._framePendingActivation?this._framePendingActivation.triggerTime:(this._lastBeginFrame||this._lastNeedsBeginFrame);if(idleTimeEnd>this._lastFrame.startTime){this._lastFrame.idle=true;this._startFrame(idleTimeEnd);if(this._framePendingActivation)
this._commitPendingFrame();this._lastBeginFrame=null;}
this._lastNeedsBeginFrame=null;}
this._startFrame(startTime);}
this._mainFrameCommitted=false;}
handleActivateLayerTree(){if(!this._lastFrame)
return;if(this._framePendingActivation&&!this._lastNeedsBeginFrame)
this._commitPendingFrame();}
handleRequestMainThreadFrame(){if(!this._lastFrame)
return;this._mainFrameRequested=true;}
handleCompositeLayers(){if(!this._framePendingCommit)
return;this._framePendingActivation=this._framePendingCommit;this._framePendingCommit=null;this._mainFrameRequested=false;this._mainFrameCommitted=true;}
handleLayerTreeSnapshot(layerTree){this._lastLayerTree=layerTree;}
handleNeedFrameChanged(startTime,needsBeginFrame){if(needsBeginFrame)
this._lastNeedsBeginFrame=startTime;}
_startFrame(startTime){if(this._lastFrame)
this._flushFrame(this._lastFrame,startTime);this._lastFrame=new TimelineModel.TimelineFrame(startTime,startTime-this._minimumRecordTime);}
_flushFrame(frame,endTime){frame._setLayerTree(this._lastLayerTree);frame._setEndTime(endTime);if(this._lastLayerTree)
this._lastLayerTree._setPaints(frame._paints);if(this._frames.length&&(frame.startTime!==this._frames.peekLast().endTime||frame.startTime>frame.endTime)){console.assert(false,`Inconsistent frame time for frame ${this._frames.length} (${frame.startTime} - ${frame.endTime})`);}
this._frames.push(frame);if(typeof frame._mainFrameId==='number')
this._frameById[frame._mainFrameId]=frame;}
_commitPendingFrame(){this._lastFrame._addTimeForCategories(this._framePendingActivation.timeByCategory);this._lastFrame._paints=this._framePendingActivation.paints;this._lastFrame._mainFrameId=this._framePendingActivation.mainFrameId;this._framePendingActivation=null;}
addTraceEvents(target,events,threadData){this._target=target;let j=0;this._currentProcessMainThread=threadData.length&&threadData[0].thread||null;for(let i=0;i<events.length;++i){while(j+1<threadData.length&&threadData[j+1].time<=events[i].startTime)
this._currentProcessMainThread=threadData[++j].thread;this._addTraceEvent(events[i]);}
this._currentProcessMainThread=null;}
_addTraceEvent(event){const eventNames=TimelineModel.TimelineModel.RecordType;if(event.startTime&&event.startTime<this._minimumRecordTime)
this._minimumRecordTime=event.startTime;if(event.name===eventNames.SetLayerTreeId){this._layerTreeId=event.args['layerTreeId']||event.args['data']['layerTreeId'];}else if(event.phase===SDK.TracingModel.Phase.SnapshotObject&&event.name===eventNames.LayerTreeHostImplSnapshot&&parseInt(event.id,0)===this._layerTreeId){const snapshot=(event);this.handleLayerTreeSnapshot(new TimelineModel.TracingFrameLayerTree(this._target,snapshot));}else{this._processCompositorEvents(event);if(event.thread===this._currentProcessMainThread)
this._addMainThreadTraceEvent(event);else if(this._lastFrame&&event.selfTime&&!SDK.TracingModel.isTopLevelEvent(event))
this._lastFrame._addTimeForCategory(this._categoryMapper(event),event.selfTime);}}
_processCompositorEvents(event){const eventNames=TimelineModel.TimelineModel.RecordType;if(event.args['layerTreeId']!==this._layerTreeId)
return;const timestamp=event.startTime;if(event.name===eventNames.BeginFrame)
this.handleBeginFrame(timestamp);else if(event.name===eventNames.DrawFrame)
this.handleDrawFrame(timestamp);else if(event.name===eventNames.ActivateLayerTree)
this.handleActivateLayerTree();else if(event.name===eventNames.RequestMainThreadFrame)
this.handleRequestMainThreadFrame();else if(event.name===eventNames.NeedsBeginFrameChanged)
this.handleNeedFrameChanged(timestamp,event.args['data']&&event.args['data']['needsBeginFrame']);}
_addMainThreadTraceEvent(event){const eventNames=TimelineModel.TimelineModel.RecordType;if(SDK.TracingModel.isTopLevelEvent(event)){this._currentTaskTimeByCategory={};this._lastTaskBeginTime=event.startTime;}
if(!this._framePendingCommit&&TimelineModel.TimelineFrameModel._mainFrameMarkers.indexOf(event.name)>=0){this._framePendingCommit=new TimelineModel.PendingFrame(this._lastTaskBeginTime||event.startTime,this._currentTaskTimeByCategory);}
if(!this._framePendingCommit){this._addTimeForCategory(this._currentTaskTimeByCategory,event);return;}
this._addTimeForCategory(this._framePendingCommit.timeByCategory,event);if(event.name===eventNames.BeginMainThreadFrame&&event.args['data']&&event.args['data']['frameId'])
this._framePendingCommit.mainFrameId=event.args['data']['frameId'];if(event.name===eventNames.Paint&&event.args['data']['layerId']&&TimelineModel.TimelineData.forEvent(event).picture&&this._target)
this._framePendingCommit.paints.push(new TimelineModel.LayerPaintEvent(event,this._target));if(event.name===eventNames.CompositeLayers&&event.args['layerTreeId']===this._layerTreeId)
this.handleCompositeLayers();}
_addTimeForCategory(timeByCategory,event){if(!event.selfTime)
return;const categoryName=this._categoryMapper(event);timeByCategory[categoryName]=(timeByCategory[categoryName]||0)+event.selfTime;}};TimelineModel.TimelineFrameModel._mainFrameMarkers=[TimelineModel.TimelineModel.RecordType.ScheduleStyleRecalculation,TimelineModel.TimelineModel.RecordType.InvalidateLayout,TimelineModel.TimelineModel.RecordType.BeginMainThreadFrame,TimelineModel.TimelineModel.RecordType.ScrollLayer];TimelineModel.TracingFrameLayerTree=class{constructor(target,snapshot){this._target=target;this._snapshot=snapshot;this._paints;}
async layerTreePromise(){const result=await this._snapshot.objectPromise();if(!result)
return null;const viewport=result['device_viewport_size'];const tiles=result['active_tiles'];const rootLayer=result['active_tree']['root_layer'];const layers=result['active_tree']['layers'];const layerTree=new TimelineModel.TracingLayerTree(this._target);layerTree.setViewportSize(viewport);layerTree.setTiles(tiles);await layerTree.setLayers(rootLayer,layers,this._paints||[]);return layerTree;}
paints(){return this._paints||[];}
_setPaints(paints){this._paints=paints;}};TimelineModel.TimelineFrame=class{constructor(startTime,startTimeOffset){this.startTime=startTime;this.startTimeOffset=startTimeOffset;this.endTime=this.startTime;this.duration=0;this.timeByCategory={};this.cpuTime=0;this.idle=false;this.layerTree=null;this._paints=[];this._mainFrameId=undefined;}
hasWarnings(){return false;}
_setEndTime(endTime){this.endTime=endTime;this.duration=this.endTime-this.startTime;}
_setLayerTree(layerTree){this.layerTree=layerTree;}
_addTimeForCategories(timeByCategory){for(const category in timeByCategory)
this._addTimeForCategory(category,timeByCategory[category]);}
_addTimeForCategory(category,time){this.timeByCategory[category]=(this.timeByCategory[category]||0)+time;this.cpuTime+=time;}};TimelineModel.LayerPaintEvent=class{constructor(event,target){this._event=event;this._target=target;}
layerId(){return this._event.args['data']['layerId'];}
event(){return this._event;}
picturePromise(){const picture=TimelineModel.TimelineData.forEvent(this._event).picture;return picture.objectPromise().then(result=>{if(!result)
return null;const rect=result['params']&&result['params']['layer_rect'];const picture=result['skp64'];return rect&&picture?{rect:rect,serializedPicture:picture}:null;});}
snapshotPromise(){const paintProfilerModel=this._target&&this._target.model(SDK.PaintProfilerModel);return this.picturePromise().then(picture=>{if(!picture||!paintProfilerModel)
return null;return paintProfilerModel.loadSnapshot(picture.serializedPicture).then(snapshot=>snapshot?{rect:picture.rect,snapshot:snapshot}:null);});}};TimelineModel.PendingFrame=class{constructor(triggerTime,timeByCategory){this.timeByCategory=timeByCategory;this.paints=[];this.mainFrameId=undefined;this.triggerTime=triggerTime;}};;TimelineModel.TimelineProfileTree={};TimelineModel.TimelineProfileTree.Node=class{constructor(id,event){this.totalTime=0;this.selfTime=0;this.id=id;this.event=event;this.parent;this._groupId='';this._isGroupNode=false;}
isGroupNode(){return this._isGroupNode;}
hasChildren(){throw'Not implemented';}
children(){throw'Not implemented';}
searchTree(matchFunction,results){results=results||[];if(this.event&&matchFunction(this.event))
results.push(this);for(const child of this.children().values())
child.searchTree(matchFunction,results);return results;}};TimelineModel.TimelineProfileTree.TopDownNode=class extends TimelineModel.TimelineProfileTree.Node{constructor(id,event,parent){super(id,event);this._root=parent&&parent._root;this._hasChildren=false;this._children=null;this.parent=parent;}
hasChildren(){return this._hasChildren;}
children(){return this._children||this._buildChildren();}
_buildChildren(){const path=[];for(let node=this;node.parent&&!node._isGroupNode;node=node.parent)
path.push((node));path.reverse();const children=new Map();const self=this;const root=this._root;const startTime=root._startTime;const endTime=root._endTime;const instantEventCallback=root._doNotAggregate?onInstantEvent:undefined;const eventIdCallback=root._doNotAggregate?undefined:TimelineModel.TimelineProfileTree._eventId;const eventGroupIdCallback=root._eventGroupIdCallback;let depth=0;let matchedDepth=0;let currentDirectChild=null;TimelineModel.TimelineModel.forEachEvent(root._events,onStartEvent,onEndEvent,instantEventCallback,startTime,endTime,root._filter);function onStartEvent(e){++depth;if(depth>path.length+2)
return;if(!matchPath(e))
return;const duration=Math.min(endTime,e.endTime)-Math.max(startTime,e.startTime);if(duration<0)
console.error('Negative event duration');processEvent(e,duration);}
function onInstantEvent(e){++depth;if(matchedDepth===path.length&&depth<=path.length+2)
processEvent(e,0);--depth;}
function processEvent(e,duration){if(depth===path.length+2){currentDirectChild._hasChildren=true;currentDirectChild.selfTime-=duration;return;}
let id;let groupId='';if(!eventIdCallback){id=Symbol('uniqueId');}else{id=eventIdCallback(e);groupId=eventGroupIdCallback?eventGroupIdCallback(e):'';if(groupId)
id+='/'+groupId;}
let node=children.get(id);if(!node){node=new TimelineModel.TimelineProfileTree.TopDownNode(id,e,self);node._groupId=groupId;children.set(id,node);}
node.selfTime+=duration;node.totalTime+=duration;currentDirectChild=node;}
function matchPath(e){if(matchedDepth===path.length)
return true;if(matchedDepth!==depth-1)
return false;if(!e.endTime)
return false;if(!eventIdCallback){if(e===path[matchedDepth].event)
++matchedDepth;return false;}
let id=eventIdCallback(e);const groupId=eventGroupIdCallback?eventGroupIdCallback(e):'';if(groupId)
id+='/'+groupId;if(id===path[matchedDepth].id)
++matchedDepth;return false;}
function onEndEvent(e){--depth;if(matchedDepth>depth)
matchedDepth=depth;}
this._children=children;return children;}};TimelineModel.TimelineProfileTree.TopDownRootNode=class extends TimelineModel.TimelineProfileTree.TopDownNode{constructor(events,filters,startTime,endTime,doNotAggregate,eventGroupIdCallback){super('',null,null);this._root=this;this._events=events;this._filter=e=>filters.every(f=>f.accept(e));this._startTime=startTime;this._endTime=endTime;this._eventGroupIdCallback=eventGroupIdCallback;this._doNotAggregate=doNotAggregate;this.totalTime=endTime-startTime;this.selfTime=this.totalTime;}
children(){return this._children||this._grouppedTopNodes();}
_grouppedTopNodes(){const flatNodes=super.children();for(const node of flatNodes.values())
this.selfTime-=node.totalTime;if(!this._eventGroupIdCallback)
return flatNodes;const groupNodes=new Map();for(const node of flatNodes.values()){const groupId=this._eventGroupIdCallback((node.event));let groupNode=groupNodes.get(groupId);if(!groupNode){groupNode=new TimelineModel.TimelineProfileTree.GroupNode(groupId,this,(node.event));groupNodes.set(groupId,groupNode);}
groupNode.addChild(node,node.selfTime,node.totalTime);}
this._children=groupNodes;return groupNodes;}};TimelineModel.TimelineProfileTree.BottomUpRootNode=class extends TimelineModel.TimelineProfileTree.Node{constructor(events,filters,startTime,endTime,eventGroupIdCallback){super('',null);this._children=null;this._events=events;this._filter=e=>filters.every(f=>f.accept(e));this._startTime=startTime;this._endTime=endTime;this._eventGroupIdCallback=eventGroupIdCallback;this.totalTime=endTime-startTime;}
hasChildren(){return true;}
children(){return this._children||this._grouppedTopNodes();}
_ungrouppedTopNodes(){const root=this;const startTime=this._startTime;const endTime=this._endTime;const nodeById=new Map();const selfTimeStack=[endTime-startTime];const firstNodeStack=[];const totalTimeById=new Map();TimelineModel.TimelineModel.forEachEvent(this._events,onStartEvent,onEndEvent,undefined,startTime,endTime,this._filter);function onStartEvent(e){const duration=Math.min(e.endTime,endTime)-Math.max(e.startTime,startTime);selfTimeStack[selfTimeStack.length-1]-=duration;selfTimeStack.push(duration);const id=TimelineModel.TimelineProfileTree._eventId(e);const noNodeOnStack=!totalTimeById.has(id);if(noNodeOnStack)
totalTimeById.set(id,duration);firstNodeStack.push(noNodeOnStack);}
function onEndEvent(e){const id=TimelineModel.TimelineProfileTree._eventId(e);let node=nodeById.get(id);if(!node){node=new TimelineModel.TimelineProfileTree.BottomUpNode(root,id,e,false,root);nodeById.set(id,node);}
node.selfTime+=selfTimeStack.pop();if(firstNodeStack.pop()){node.totalTime+=totalTimeById.get(id);totalTimeById.delete(id);}
if(firstNodeStack.length)
node.setHasChildren();}
this.selfTime=selfTimeStack.pop();for(const pair of nodeById){if(pair[1].selfTime<=0)
nodeById.delete((pair[0]));}
return nodeById;}
_grouppedTopNodes(){const flatNodes=this._ungrouppedTopNodes();if(!this._eventGroupIdCallback){this._children=flatNodes;return flatNodes;}
const groupNodes=new Map();for(const node of flatNodes.values()){const groupId=this._eventGroupIdCallback((node.event));let groupNode=groupNodes.get(groupId);if(!groupNode){groupNode=new TimelineModel.TimelineProfileTree.GroupNode(groupId,this,(node.event));groupNodes.set(groupId,groupNode);}
groupNode.addChild(node,node.selfTime,node.selfTime);}
this._children=groupNodes;return groupNodes;}};TimelineModel.TimelineProfileTree.GroupNode=class extends TimelineModel.TimelineProfileTree.Node{constructor(id,parent,event){super(id,event);this._children=new Map();this.parent=parent;this._isGroupNode=true;}
addChild(child,selfTime,totalTime){this._children.set(child.id,child);this.selfTime+=selfTime;this.totalTime+=totalTime;child.parent=this;}
hasChildren(){return true;}
children(){return this._children;}};TimelineModel.TimelineProfileTree.BottomUpNode=class extends TimelineModel.TimelineProfileTree.Node{constructor(root,id,event,hasChildren,parent){super(id,event);this.parent=parent;this._root=root;this._depth=(parent._depth||0)+1;this._cachedChildren=null;this._hasChildren=hasChildren;}
setHasChildren(){this._hasChildren=true;}
hasChildren(){return this._hasChildren;}
children(){if(this._cachedChildren)
return this._cachedChildren;const selfTimeStack=[0];const eventIdStack=[];const eventStack=[];const nodeById=new Map();const startTime=this._root._startTime;const endTime=this._root._endTime;let lastTimeMarker=startTime;const self=this;TimelineModel.TimelineModel.forEachEvent(this._root._events,onStartEvent,onEndEvent,undefined,startTime,endTime,this._root._filter);function onStartEvent(e){const duration=Math.min(e.endTime,endTime)-Math.max(e.startTime,startTime);if(duration<0)
console.assert(false,'Negative duration of an event');selfTimeStack[selfTimeStack.length-1]-=duration;selfTimeStack.push(duration);const id=TimelineModel.TimelineProfileTree._eventId(e);eventIdStack.push(id);eventStack.push(e);}
function onEndEvent(e){const selfTime=selfTimeStack.pop();const id=eventIdStack.pop();eventStack.pop();let node;for(node=self;node._depth>1;node=node.parent){if(node.id!==eventIdStack[eventIdStack.length+1-node._depth])
return;}
if(node.id!==id||eventIdStack.length<self._depth)
return;const childId=eventIdStack[eventIdStack.length-self._depth];node=nodeById.get(childId);if(!node){const event=eventStack[eventStack.length-self._depth];const hasChildren=eventStack.length>self._depth;node=new TimelineModel.TimelineProfileTree.BottomUpNode(self._root,childId,event,hasChildren,self);nodeById.set(childId,node);}
const totalTime=Math.min(e.endTime,endTime)-Math.max(e.startTime,lastTimeMarker);node.selfTime+=selfTime;node.totalTime+=totalTime;lastTimeMarker=Math.min(e.endTime,endTime);}
this._cachedChildren=nodeById;return nodeById;}
searchTree(matchFunction,results){results=results||[];if(this.event&&matchFunction(this.event))
results.push(this);return results;}};TimelineModel.TimelineProfileTree.eventURL=function(event){const data=event.args['data']||event.args['beginData'];if(data&&data['url'])
return data['url'];let frame=TimelineModel.TimelineProfileTree.eventStackFrame(event);while(frame){const url=frame['url'];if(url)
return url;frame=frame.parent;}
return null;};TimelineModel.TimelineProfileTree.eventStackFrame=function(event){if(event.name===TimelineModel.TimelineModel.RecordType.JSFrame)
return(event.args['data']||null);return TimelineModel.TimelineData.forEvent(event).topFrame();};TimelineModel.TimelineProfileTree._eventId=function(event){if(event.name===TimelineModel.TimelineModel.RecordType.TimeStamp)
return`${event.name}:${event.args.data.message}`;if(event.name!==TimelineModel.TimelineModel.RecordType.JSFrame)
return event.name;const frame=event.args['data'];const location=frame['scriptId']||frame['url']||'';const functionName=frame['functionName'];const name=TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame)?TimelineModel.TimelineJSProfileProcessor.nativeGroup(functionName)||functionName:`${functionName}:${frame['lineNumber']}:${frame['columnNumber']}`;return`f:${name}@${location}`;};;Timeline.CountersGraph=class extends UI.VBox{constructor(delegate){super();this.element.id='memory-graphs-container';this._delegate=delegate;this._calculator=new Timeline.CountersGraph.Calculator();this._header=new UI.HBox();this._header.element.classList.add('timeline-memory-header');this._header.show(this.element);this._toolbar=new UI.Toolbar('timeline-memory-toolbar');this._header.element.appendChild(this._toolbar.element);this._graphsContainer=new UI.VBox();this._graphsContainer.show(this.element);const canvasWidget=new UI.VBoxWithResizeCallback(this._resize.bind(this));canvasWidget.show(this._graphsContainer.element);this._createCurrentValuesBar();this._canvasContainer=canvasWidget.element;this._canvasContainer.id='memory-graphs-canvas-container';this._canvas=this._canvasContainer.createChild('canvas');this._canvas.id='memory-counters-graph';this._canvasContainer.addEventListener('mouseover',this._onMouseMove.bind(this),true);this._canvasContainer.addEventListener('mousemove',this._onMouseMove.bind(this),true);this._canvasContainer.addEventListener('mouseleave',this._onMouseLeave.bind(this),true);this._canvasContainer.addEventListener('click',this._onClick.bind(this),true);this._timelineGrid=new PerfUI.TimelineGrid();this._canvasContainer.appendChild(this._timelineGrid.dividersElement);this._counters=[];this._counterUI=[];this._countersByName={};this._countersByName['jsHeapSizeUsed']=this._createCounter(Common.UIString('JS Heap'),Common.UIString('JS Heap: %s'),'hsl(220, 90%, 43%)',Number.bytesToString);this._countersByName['documents']=this._createCounter(Common.UIString('Documents'),Common.UIString('Documents: %s'),'hsl(0, 90%, 43%)');this._countersByName['nodes']=this._createCounter(Common.UIString('Nodes'),Common.UIString('Nodes: %s'),'hsl(120, 90%, 43%)');this._countersByName['jsEventListeners']=this._createCounter(Common.UIString('Listeners'),Common.UIString('Listeners: %s'),'hsl(38, 90%, 43%)');this._gpuMemoryCounter=this._createCounter(Common.UIString('GPU Memory'),Common.UIString('GPU Memory [KB]: %s'),'hsl(300, 90%, 43%)',Number.bytesToString);this._countersByName['gpuMemoryUsedKB']=this._gpuMemoryCounter;}
setModel(model,track){if(this._model!==model){if(this._model)
this._model.removeEventListener(Timeline.PerformanceModel.Events.WindowChanged,this._onWindowChanged,this);this._model=model;if(this._model)
this._model.addEventListener(Timeline.PerformanceModel.Events.WindowChanged,this._onWindowChanged,this);}
this._calculator.setZeroTime(model?model.timelineModel().minimumRecordTime():0);for(let i=0;i<this._counters.length;++i){this._counters[i].reset();this._counterUI[i].reset();}
this.scheduleRefresh();this._track=track;if(!track)
return;const events=track.syncEvents();for(let i=0;i<events.length;++i){const event=events[i];if(event.name!==TimelineModel.TimelineModel.RecordType.UpdateCounters)
continue;const counters=event.args.data;if(!counters)
return;for(const name in counters){const counter=this._countersByName[name];if(counter)
counter.appendSample(event.startTime,counters[name]);}
const gpuMemoryLimitCounterName='gpuMemoryLimitKB';if(gpuMemoryLimitCounterName in counters)
this._gpuMemoryCounter.setLimit(counters[gpuMemoryLimitCounterName]);}}
_createCurrentValuesBar(){this._currentValuesBar=this._graphsContainer.element.createChild('div');this._currentValuesBar.id='counter-values-bar';}
_createCounter(uiName,uiValueTemplate,color,formatter){const counter=new Timeline.CountersGraph.Counter();this._counters.push(counter);this._counterUI.push(new Timeline.CountersGraph.CounterUI(this,uiName,uiValueTemplate,color,counter,formatter));return counter;}
resizerElement(){return this._header.element;}
_resize(){const parentElement=this._canvas.parentElement;this._canvas.width=parentElement.clientWidth*window.devicePixelRatio;this._canvas.height=parentElement.clientHeight*window.devicePixelRatio;this._calculator.setDisplayWidth(this._canvas.width);this.refresh();}
_onWindowChanged(event){const window=(event.data.window);this._calculator.setWindow(window.left,window.right);this.scheduleRefresh();}
scheduleRefresh(){UI.invokeOnceAfterBatchUpdate(this,this.refresh);}
draw(){this._clear();for(const counter of this._counters){counter._calculateVisibleIndexes(this._calculator);counter._calculateXValues(this._canvas.width);}
for(const counterUI of this._counterUI)
counterUI._drawGraph(this._canvas);}
_onClick(event){const x=event.x-this._canvasContainer.totalOffsetLeft();let minDistance=Infinity;let bestTime;for(const counterUI of this._counterUI){if(!counterUI.counter.times.length)
continue;const index=counterUI._recordIndexAt(x);const distance=Math.abs(x*window.devicePixelRatio-counterUI.counter.x[index]);if(distance<minDistance){minDistance=distance;bestTime=counterUI.counter.times[index];}}
if(bestTime!==undefined){this._delegate.selectEntryAtTime(this._track.events.length?this._track.events:this._track.asyncEvents,bestTime);}}
_onMouseLeave(event){delete this._markerXPosition;this._clearCurrentValueAndMarker();}
_clearCurrentValueAndMarker(){for(let i=0;i<this._counterUI.length;i++)
this._counterUI[i]._clearCurrentValueAndMarker();}
_onMouseMove(event){const x=event.x-this._canvasContainer.totalOffsetLeft();this._markerXPosition=x;this._refreshCurrentValues();}
_refreshCurrentValues(){if(this._markerXPosition===undefined)
return;for(let i=0;i<this._counterUI.length;++i)
this._counterUI[i].updateCurrentValue(this._markerXPosition);}
refresh(){this._timelineGrid.updateDividers(this._calculator);this.draw();this._refreshCurrentValues();}
_clear(){const ctx=this._canvas.getContext('2d');ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);}};Timeline.CountersGraph.Counter=class{constructor(){this.times=[];this.values=[];}
appendSample(time,value){if(this.values.length&&this.values.peekLast()===value)
return;this.times.push(time);this.values.push(value);}
reset(){this.times=[];this.values=[];}
setLimit(value){this._limitValue=value;}
_calculateBounds(){let maxValue;let minValue;for(let i=this._minimumIndex;i<=this._maximumIndex;i++){const value=this.values[i];if(minValue===undefined||value<minValue)
minValue=value;if(maxValue===undefined||value>maxValue)
maxValue=value;}
minValue=minValue||0;maxValue=maxValue||1;if(this._limitValue){if(maxValue>this._limitValue*0.5)
maxValue=Math.max(maxValue,this._limitValue);minValue=Math.min(minValue,this._limitValue);}
return{min:minValue,max:maxValue};}
_calculateVisibleIndexes(calculator){const start=calculator.minimumBoundary();const end=calculator.maximumBoundary();this._minimumIndex=Number.constrain(this.times.upperBound(start)-1,0,this.times.length-1);this._maximumIndex=Number.constrain(this.times.lowerBound(end),0,this.times.length-1);this._minTime=start;this._maxTime=end;}
_calculateXValues(width){if(!this.values.length)
return;const xFactor=width/(this._maxTime-this._minTime);this.x=new Array(this.values.length);for(let i=this._minimumIndex+1;i<=this._maximumIndex;i++)
this.x[i]=xFactor*(this.times[i]-this._minTime);}};Timeline.CountersGraph.CounterUI=class{constructor(countersPane,title,currentValueLabel,graphColor,counter,formatter){this._countersPane=countersPane;this.counter=counter;this._formatter=formatter||Number.withThousandsSeparator;this._setting=Common.settings.createSetting('timelineCountersGraph-'+title,true);this._setting.setTitle(title);this._filter=new UI.ToolbarSettingCheckbox(this._setting,title);this._filter.inputElement.classList.add('-theme-preserve');const color=Common.Color.parse(graphColor).setAlpha(0.5).asString(Common.Color.Format.RGBA);if(color){this._filter.element.backgroundColor=color;this._filter.element.borderColor='transparent';}
this._filter.inputElement.addEventListener('click',this._toggleCounterGraph.bind(this));countersPane._toolbar.appendToolbarItem(this._filter);this._range=this._filter.element.createChild('span','range');this._value=countersPane._currentValuesBar.createChild('span','memory-counter-value');this._value.style.color=graphColor;this.graphColor=graphColor;this.limitColor=Common.Color.parse(graphColor).setAlpha(0.3).asString(Common.Color.Format.RGBA);this.graphYValues=[];this._verticalPadding=10;this._currentValueLabel=currentValueLabel;this._marker=countersPane._canvasContainer.createChild('div','memory-counter-marker');this._marker.style.backgroundColor=graphColor;this._clearCurrentValueAndMarker();}
reset(){this._range.textContent='';}
setRange(minValue,maxValue){const min=this._formatter(minValue);const max=this._formatter(maxValue);this._range.textContent=Common.UIString('[%s\xa0\u2013\xa0%s]',min,max);}
_toggleCounterGraph(event){this._value.classList.toggle('hidden',!this._filter.checked());this._countersPane.refresh();}
_recordIndexAt(x){return this.counter.x.upperBound(x*window.devicePixelRatio,null,this.counter._minimumIndex+1,this.counter._maximumIndex+1)-
1;}
updateCurrentValue(x){if(!this.visible()||!this.counter.values.length||!this.counter.x)
return;const index=this._recordIndexAt(x);const value=Number.withThousandsSeparator(this.counter.values[index]);this._value.textContent=Common.UIString(this._currentValueLabel,value);const y=this.graphYValues[index]/window.devicePixelRatio;this._marker.style.left=x+'px';this._marker.style.top=y+'px';this._marker.classList.remove('hidden');}
_clearCurrentValueAndMarker(){this._value.textContent='';this._marker.classList.add('hidden');}
_drawGraph(canvas){const ctx=canvas.getContext('2d');const width=canvas.width;const height=canvas.height-2*this._verticalPadding;if(height<=0){this.graphYValues=[];return;}
const originY=this._verticalPadding;const counter=this.counter;const values=counter.values;if(!values.length)
return;const bounds=counter._calculateBounds();const minValue=bounds.min;const maxValue=bounds.max;this.setRange(minValue,maxValue);if(!this.visible())
return;const yValues=this.graphYValues;const maxYRange=maxValue-minValue;const yFactor=maxYRange?height/(maxYRange):1;ctx.save();ctx.lineWidth=window.devicePixelRatio;if(ctx.lineWidth%2)
ctx.translate(0.5,0.5);ctx.beginPath();let value=values[counter._minimumIndex];let currentY=Math.round(originY+height-(value-minValue)*yFactor);ctx.moveTo(0,currentY);let i=counter._minimumIndex;for(;i<=counter._maximumIndex;i++){const x=Math.round(counter.x[i]);ctx.lineTo(x,currentY);const currentValue=values[i];if(typeof currentValue!=='undefined')
value=currentValue;currentY=Math.round(originY+height-(value-minValue)*yFactor);ctx.lineTo(x,currentY);yValues[i]=currentY;}
yValues.length=i;ctx.lineTo(width,currentY);ctx.strokeStyle=this.graphColor;ctx.stroke();if(counter._limitValue){const limitLineY=Math.round(originY+height-(counter._limitValue-minValue)*yFactor);ctx.moveTo(0,limitLineY);ctx.lineTo(width,limitLineY);ctx.strokeStyle=this.limitColor;ctx.stroke();}
ctx.closePath();ctx.restore();}
visible(){return this._filter.checked();}};Timeline.CountersGraph.Calculator=class{setZeroTime(time){this._zeroTime=time;}
computePosition(time){return(time-this._minimumBoundary)/this.boundarySpan()*this._workingArea;}
setWindow(minimumBoundary,maximumBoundary){this._minimumBoundary=minimumBoundary;this._maximumBoundary=maximumBoundary;}
setDisplayWidth(clientWidth){this._workingArea=clientWidth;}
formatValue(value,precision){return Number.preciseMillisToString(value-this.zeroTime(),precision);}
maximumBoundary(){return this._maximumBoundary;}
minimumBoundary(){return this._minimumBoundary;}
zeroTime(){return this._zeroTime;}
boundarySpan(){return this._maximumBoundary-this._minimumBoundary;}};;Timeline.ExtensionTracingSession=class{constructor(provider,performanceModel){this._provider=provider;this._performanceModel=performanceModel;this._completionCallback;this._completionPromise=new Promise(fulfill=>{this._completionCallback=fulfill;});this._timeOffset=0;}
loadingStarted(){}
processingStarted(){}
loadingProgress(progress){}
loadingComplete(tracingModel){if(!tracingModel)
return;this._performanceModel.addExtensionEvents(this._provider.longDisplayName(),tracingModel,this._timeOffset);this._completionCallback();}
complete(url,timeOffsetMicroseconds){if(!url){this._completionCallback();return;}
this._timeOffset=timeOffsetMicroseconds;Timeline.TimelineLoader.loadFromURL(url,this);}
start(){this._provider.start(this);}
stop(){this._provider.stop();return this._completionPromise;}};;Timeline.PerformanceModel=class extends Common.Object{constructor(){super();this._mainTarget=null;this._tracingModel=null;this._filters=[];this._timelineModel=new TimelineModel.TimelineModel();this._frameModel=new TimelineModel.TimelineFrameModel(event=>Timeline.TimelineUIUtils.eventStyle(event).category.name);this._filmStripModel=null;this._irModel=new TimelineModel.TimelineIRModel();this._window={left:0,right:Infinity};this._extensionTracingModels=[];this._recordStartTime=undefined;}
setMainTarget(target){this._mainTarget=target;}
setRecordStartTime(time){this._recordStartTime=time;}
recordStartTime(){return this._recordStartTime;}
setFilters(filters){this._filters=filters;}
filters(){return this._filters;}
isVisible(event){return this._filters.every(f=>f.accept(event));}
setTracingModel(model){this._tracingModel=model;this._timelineModel.setEvents(model);let inputEvents=null;let animationEvents=null;for(const track of this._timelineModel.tracks()){if(track.type===TimelineModel.TimelineModel.TrackType.Input)
inputEvents=track.asyncEvents;if(track.type===TimelineModel.TimelineModel.TrackType.Animation)
animationEvents=track.asyncEvents;}
if(inputEvents||animationEvents)
this._irModel.populate(inputEvents||[],animationEvents||[]);const mainTracks=this._timelineModel.tracks().filter(track=>track.type===TimelineModel.TimelineModel.TrackType.MainThread&&track.forMainFrame&&track.events.length);const threadData=mainTracks.map(track=>{const event=track.events[0];return{thread:event.thread,time:event.startTime};});this._frameModel.addTraceEvents(this._mainTarget,this._timelineModel.inspectedTargetEvents(),threadData);for(const entry of this._extensionTracingModels){entry.model.adjustTime(this._tracingModel.minimumRecordTime()+(entry.timeOffset/1000)-this._recordStartTime);}
this._autoWindowTimes();}
addExtensionEvents(title,model,timeOffset){this._extensionTracingModels.push({model:model,title:title,timeOffset:timeOffset});if(!this._tracingModel)
return;model.adjustTime(this._tracingModel.minimumRecordTime()+(timeOffset/1000)-this._recordStartTime);this.dispatchEventToListeners(Timeline.PerformanceModel.Events.ExtensionDataAdded);}
tracingModel(){if(!this._tracingModel)
throw'call setTracingModel before accessing PerformanceModel';return this._tracingModel;}
timelineModel(){return this._timelineModel;}
filmStripModel(){if(this._filmStripModel)
return this._filmStripModel;if(!this._tracingModel)
throw'call setTracingModel before accessing PerformanceModel';this._filmStripModel=new SDK.FilmStripModel(this._tracingModel);return this._filmStripModel;}
frames(){return this._frameModel.frames();}
frameModel(){return this._frameModel;}
interactionRecords(){return this._irModel.interactionRecords();}
extensionInfo(){return this._extensionTracingModels;}
dispose(){if(this._tracingModel)
this._tracingModel.dispose();for(const extensionEntry of this._extensionTracingModels)
extensionEntry.model.dispose();}
filmStripModelFrame(frame){const screenshotTime=frame.idle?frame.startTime:frame.endTime;const filmStripFrame=this._filmStripModel.frameByTimestamp(screenshotTime);return filmStripFrame&&filmStripFrame.timestamp-frame.endTime<10?filmStripFrame:null;}
save(stream){const backingStorage=(this._tracingModel.backingStorage());return backingStorage.writeToStream(stream);}
setWindow(window,animate){this._window=window;this.dispatchEventToListeners(Timeline.PerformanceModel.Events.WindowChanged,{window,animate});}
window(){return this._window;}
_autoWindowTimes(){const timelineModel=this._timelineModel;let tasks=[];for(const track of timelineModel.tracks()){if(track.type===TimelineModel.TimelineModel.TrackType.MainThread&&track.forMainFrame)
tasks=track.tasks;}
if(!tasks.length){this.setWindow({left:timelineModel.minimumRecordTime(),right:timelineModel.maximumRecordTime()});return;}
function findLowUtilizationRegion(startIndex,stopIndex){const threshold=0.1;let cutIndex=startIndex;let cutTime=(tasks[cutIndex].startTime+tasks[cutIndex].endTime)/2;let usedTime=0;const step=Math.sign(stopIndex-startIndex);for(let i=startIndex;i!==stopIndex;i+=step){const task=tasks[i];const taskTime=(task.startTime+task.endTime)/2;const interval=Math.abs(cutTime-taskTime);if(usedTime<threshold*interval){cutIndex=i;cutTime=taskTime;usedTime=0;}
usedTime+=task.duration;}
return cutIndex;}
const rightIndex=findLowUtilizationRegion(tasks.length-1,0);const leftIndex=findLowUtilizationRegion(0,rightIndex);let leftTime=tasks[leftIndex].startTime;let rightTime=tasks[rightIndex].endTime;const span=rightTime-leftTime;const totalSpan=timelineModel.maximumRecordTime()-timelineModel.minimumRecordTime();if(span<totalSpan*0.1){leftTime=timelineModel.minimumRecordTime();rightTime=timelineModel.maximumRecordTime();}else{leftTime=Math.max(leftTime-0.05*span,timelineModel.minimumRecordTime());rightTime=Math.min(rightTime+0.05*span,timelineModel.maximumRecordTime());}
this.setWindow({left:leftTime,right:rightTime});}};Timeline.PerformanceModel.Events={ExtensionDataAdded:Symbol('ExtensionDataAdded'),WindowChanged:Symbol('WindowChanged')};Timeline.PerformanceModel.Window;;Timeline.TimelineController=class{constructor(target,client){this._target=target;this._tracingManager=target.model(SDK.TracingManager);this._performanceModel=new Timeline.PerformanceModel();this._performanceModel.setMainTarget(target);this._client=client;const backingStorage=new Bindings.TempFileBackingStorage();this._tracingModel=new SDK.TracingModel(backingStorage);this._extensionSessions=[];SDK.targetManager.observeModels(SDK.CPUProfilerModel,this);}
dispose(){SDK.targetManager.unobserveModels(SDK.CPUProfilerModel,this);}
mainTarget(){return this._target;}
startRecording(options,providers){this._extensionTraceProviders=Extensions.extensionServer.traceProviders().slice();function disabledByDefault(category){return'disabled-by-default-'+category;}
const categoriesArray=['-*','devtools.timeline',disabledByDefault('devtools.timeline'),disabledByDefault('devtools.timeline.frame'),'v8.execute',TimelineModel.TimelineModel.Category.Console,TimelineModel.TimelineModel.Category.UserTiming];categoriesArray.push(TimelineModel.TimelineModel.Category.LatencyInfo);if(Runtime.experiments.isEnabled('timelineFlowEvents'))
categoriesArray.push('devtools.timeline.async');if(Runtime.experiments.isEnabled('timelineV8RuntimeCallStats')&&options.enableJSSampling)
categoriesArray.push(disabledByDefault('v8.runtime_stats_sampling'));if(!Runtime.queryParam('timelineTracingJSProfileDisabled')&&options.enableJSSampling){categoriesArray.push(disabledByDefault('v8.cpu_profiler'));if(Common.moduleSetting('highResolutionCpuProfiling').get())
categoriesArray.push(disabledByDefault('v8.cpu_profiler.hires'));}
categoriesArray.push(disabledByDefault('devtools.timeline.stack'));if(Runtime.experiments.isEnabled('timelineInvalidationTracking'))
categoriesArray.push(disabledByDefault('devtools.timeline.invalidationTracking'));if(options.capturePictures){categoriesArray.push(disabledByDefault('devtools.timeline.layers'),disabledByDefault('devtools.timeline.picture'),disabledByDefault('blink.graphics_context_annotations'));}
if(options.captureFilmStrip)
categoriesArray.push(disabledByDefault('devtools.screenshot'));this._extensionSessions=providers.map(provider=>new Timeline.ExtensionTracingSession(provider,this._performanceModel));this._extensionSessions.forEach(session=>session.start());const startPromise=this._startRecordingWithCategories(categoriesArray.join(','),options.enableJSSampling);this._performanceModel.setRecordStartTime(Date.now());return startPromise;}
async stopRecording(){const tracingStoppedPromises=[];if(this._tracingManager)
tracingStoppedPromises.push(new Promise(resolve=>this._tracingCompleteCallback=resolve));tracingStoppedPromises.push(this._stopProfilingOnAllModels());if(this._tracingManager)
this._tracingManager.stop();this._client.loadingStarted();const extensionCompletionPromises=this._extensionSessions.map(session=>session.stop());if(extensionCompletionPromises.length){tracingStoppedPromises.push(Promise.race([Promise.all(extensionCompletionPromises),new Promise(r=>setTimeout(r,5000))]));}
await Promise.all(tracingStoppedPromises);this._allSourcesFinished();return this._performanceModel;}
modelAdded(cpuProfilerModel){if(this._profiling)
cpuProfilerModel.startRecording();}
modelRemoved(cpuProfilerModel){}
_startProfilingOnAllModels(){this._profiling=true;const models=SDK.targetManager.models(SDK.CPUProfilerModel);return Promise.all(models.map(model=>model.startRecording()));}
_addCpuProfile(targetId,cpuProfile){if(!cpuProfile){Common.console.warn(Common.UIString('CPU profile for a target is not available.'));return;}
if(!this._cpuProfiles)
this._cpuProfiles=new Map();this._cpuProfiles.set(targetId,cpuProfile);}
_stopProfilingOnAllModels(){const models=this._profiling?SDK.targetManager.models(SDK.CPUProfilerModel):[];this._profiling=false;const promises=[];for(const model of models){const targetId=model.target().id();const modelPromise=model.stopRecording().then(this._addCpuProfile.bind(this,targetId));promises.push(modelPromise);}
return Promise.all(promises);}
async _startRecordingWithCategories(categories,enableJSSampling){SDK.targetManager.suspendAllTargets();if(enableJSSampling&&Runtime.queryParam('timelineTracingJSProfileDisabled'))
await this._startProfilingOnAllModels();if(!this._tracingManager)
return;const samplingFrequencyHz=Common.moduleSetting('highResolutionCpuProfiling').get()?10000:1000;const options='sampling-frequency='+samplingFrequencyHz;return this._tracingManager.start(this,categories,options);}
traceEventsCollected(events){this._tracingModel.addEvents(events);}
tracingComplete(){this._tracingCompleteCallback();this._tracingCompleteCallback=null;}
_allSourcesFinished(){this._client.processingStarted();setTimeout(()=>this._finalizeTrace(),0);}
async _finalizeTrace(){this._injectCpuProfileEvents();await SDK.targetManager.resumeAllTargets();this._tracingModel.tracingComplete();this._client.loadingComplete(this._tracingModel);}
_injectCpuProfileEvent(pid,tid,cpuProfile){if(!cpuProfile)
return;const cpuProfileEvent=({cat:SDK.TracingModel.DevToolsMetadataEventCategory,ph:SDK.TracingModel.Phase.Instant,ts:this._tracingModel.maximumRecordTime()*1000,pid:pid,tid:tid,name:TimelineModel.TimelineModel.RecordType.CpuProfile,args:{data:{cpuProfile:cpuProfile}}});this._tracingModel.addEvents([cpuProfileEvent]);}
_buildTargetToProcessIdMap(){const metadataEventTypes=TimelineModel.TimelineModel.DevToolsMetadataEvent;const metadataEvents=this._tracingModel.devToolsMetadataEvents();const browserMetaEvent=metadataEvents.find(e=>e.name===metadataEventTypes.TracingStartedInBrowser);if(!browserMetaEvent)
return null;const pseudoPidToFrames=new Multimap();const targetIdToPid=new Map();const frames=browserMetaEvent.args.data['frames'];for(const frameInfo of frames)
targetIdToPid.set(frameInfo.frame,frameInfo.processId);for(const event of metadataEvents){const data=event.args.data;switch(event.name){case metadataEventTypes.FrameCommittedInBrowser:if(data.processId)
targetIdToPid.set(data.frame,data.processId);else
pseudoPidToFrames.set(data.processPseudoId,data.frame);break;case metadataEventTypes.ProcessReadyInBrowser:for(const frame of pseudoPidToFrames.get(data.processPseudoId)||[])
targetIdToPid.set(frame,data.processId);break;}}
const mainFrame=frames.find(frame=>!frame.parent);const mainRendererProcessId=mainFrame.processId;const mainProcess=this._tracingModel.processById(mainRendererProcessId);if(mainProcess)
targetIdToPid.set(SDK.targetManager.mainTarget().id(),mainProcess.id());return targetIdToPid;}
_injectCpuProfileEvents(){if(!this._cpuProfiles)
return;const metadataEventTypes=TimelineModel.TimelineModel.DevToolsMetadataEvent;const metadataEvents=this._tracingModel.devToolsMetadataEvents();const targetIdToPid=this._buildTargetToProcessIdMap();if(targetIdToPid){for(const[id,profile]of this._cpuProfiles){const pid=targetIdToPid.get(id);if(!pid)
continue;const process=this._tracingModel.processById(pid);const thread=process&&process.threadByName(TimelineModel.TimelineModel.RendererMainThreadName);if(thread)
this._injectCpuProfileEvent(pid,thread.id(),profile);}}else{const mainMetaEvent=metadataEvents.filter(event=>event.name===metadataEventTypes.TracingStartedInPage).peekLast();if(mainMetaEvent){const pid=mainMetaEvent.thread.process().id();const mainCpuProfile=this._cpuProfiles.get(this._tracingManager.target().id());this._injectCpuProfileEvent(pid,mainMetaEvent.thread.id(),mainCpuProfile);}else{let tid=0;for(const pair of this._cpuProfiles){const target=SDK.targetManager.targetById(pair[0]);const name=target&&target.name();this._tracingModel.addEvents(TimelineModel.TimelineJSProfileProcessor.buildTraceProfileFromCpuProfile(pair[1],++tid,tid===1,name));}}}
const workerMetaEvents=metadataEvents.filter(event=>event.name===metadataEventTypes.TracingSessionIdForWorker);for(const metaEvent of workerMetaEvents){const workerId=metaEvent.args['data']['workerId'];const cpuProfile=this._cpuProfiles.get(workerId);this._injectCpuProfileEvent(metaEvent.thread.process().id(),metaEvent.args['data']['workerThreadId'],cpuProfile);}
this._cpuProfiles=null;}
tracingBufferUsage(usage){this._client.recordingProgress(usage);}
eventsRetrievalProgress(progress){this._client.loadingProgress(progress);}};Timeline.TimelineController.Client=function(){};Timeline.TimelineController.Client.prototype={recordingProgress(usage){},};Timeline.TimelineController.RecordingOptions;;Timeline.TimelineDetailsView=class extends UI.VBox{constructor(delegate){super();this.element.classList.add('timeline-details');this._detailsLinkifier=new Components.Linkifier();this._badgePool=new ProductRegistry.BadgePool();this._badgePool.setShowTitles(true);this._tabbedPane=new UI.TabbedPane();this._tabbedPane.show(this.element);const tabIds=Timeline.TimelineDetailsView.Tab;this._defaultDetailsWidget=new UI.VBox();this._defaultDetailsWidget.element.classList.add('timeline-details-view');this._defaultDetailsContentElement=this._defaultDetailsWidget.element.createChild('div','timeline-details-view-body vbox');this._defaultDetailsContentElement.tabIndex=0;this._appendTab(tabIds.Details,Common.UIString('Summary'),this._defaultDetailsWidget);this.setPreferredTab(tabIds.Details);this._rangeDetailViews=new Map();const bottomUpView=new Timeline.BottomUpTimelineTreeView();this._appendTab(tabIds.BottomUp,Common.UIString('Bottom-Up'),bottomUpView);this._rangeDetailViews.set(tabIds.BottomUp,bottomUpView);const callTreeView=new Timeline.CallTreeTimelineTreeView();this._appendTab(tabIds.CallTree,Common.UIString('Call Tree'),callTreeView);this._rangeDetailViews.set(tabIds.CallTree,callTreeView);const eventsView=new Timeline.EventsTimelineTreeView(delegate);this._appendTab(tabIds.EventLog,Common.UIString('Event Log'),eventsView);this._rangeDetailViews.set(tabIds.EventLog,eventsView);this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);}
setModel(model,track){if(this._model!==model){if(this._model)
this._model.removeEventListener(Timeline.PerformanceModel.Events.WindowChanged,this._onWindowChanged,this);this._model=model;if(this._model)
this._model.addEventListener(Timeline.PerformanceModel.Events.WindowChanged,this._onWindowChanged,this);}
this._track=track;this._tabbedPane.closeTabs([Timeline.TimelineDetailsView.Tab.PaintProfiler,Timeline.TimelineDetailsView.Tab.LayerViewer],false);for(const view of this._rangeDetailViews.values())
view.setModel(model,track);this._lazyPaintProfilerView=null;this._lazyLayersView=null;this.setSelection(null);}
_setContent(node){const allTabs=this._tabbedPane.otherTabs(Timeline.TimelineDetailsView.Tab.Details);for(let i=0;i<allTabs.length;++i){if(!this._rangeDetailViews.has(allTabs[i]))
this._tabbedPane.closeTab(allTabs[i]);}
this._defaultDetailsContentElement.removeChildren();this._defaultDetailsContentElement.appendChild(node);}
_updateContents(){const view=this._rangeDetailViews.get(this._tabbedPane.selectedTabId||'');if(view){const window=this._model.window();view.updateContents(this._selection||Timeline.TimelineSelection.fromRange(window.left,window.right));}}
_appendTab(id,tabTitle,view,isCloseable){this._tabbedPane.appendTab(id,tabTitle,view,undefined,undefined,isCloseable);if(this._preferredTabId!==this._tabbedPane.selectedTabId)
this._tabbedPane.selectTab(id);}
headerElement(){return this._tabbedPane.headerElement();}
setPreferredTab(tabId){this._preferredTabId=tabId;}
_onWindowChanged(event){if(!this._selection)
this._updateContentsFromWindow();}
_updateContentsFromWindow(){if(!this._model){this._setContent(UI.html`<div/>`);return;}
const window=this._model.window();this._updateSelectedRangeStats(window.left,window.right);this._updateContents();}
setSelection(selection){this._detailsLinkifier.reset();this._badgePool.reset();this._selection=selection;if(!this._selection){this._updateContentsFromWindow();return;}
switch(this._selection.type()){case Timeline.TimelineSelection.Type.TraceEvent:const event=(this._selection.object());Timeline.TimelineUIUtils.buildTraceEventDetails(event,this._model.timelineModel(),this._detailsLinkifier,this._badgePool,true).then(fragment=>this._appendDetailsTabsForTraceEventAndShowDetails(event,fragment));break;case Timeline.TimelineSelection.Type.Frame:const frame=(this._selection.object());const filmStripFrame=this._model.filmStripModelFrame(frame);this._setContent(Timeline.TimelineUIUtils.generateDetailsContentForFrame(frame,filmStripFrame));if(frame.layerTree){const layersView=this._layersView();layersView.showLayerTree(frame.layerTree);if(!this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.LayerViewer))
this._appendTab(Timeline.TimelineDetailsView.Tab.LayerViewer,Common.UIString('Layers'),layersView);}
break;case Timeline.TimelineSelection.Type.NetworkRequest:const request=(this._selection.object());Timeline.TimelineUIUtils.buildNetworkRequestDetails(request,this._model.timelineModel(),this._detailsLinkifier,this._badgePool).then(this._setContent.bind(this));break;case Timeline.TimelineSelection.Type.Range:this._updateSelectedRangeStats(this._selection.startTime(),this._selection.endTime());break;}
this._updateContents();}
_tabSelected(event){if(!event.data.isUserGesture)
return;this.setPreferredTab(event.data.tabId);this._updateContents();}
_layersView(){if(this._lazyLayersView)
return this._lazyLayersView;this._lazyLayersView=new Timeline.TimelineLayersView(this._model.timelineModel(),this._showSnapshotInPaintProfiler.bind(this));return this._lazyLayersView;}
_paintProfilerView(){if(this._lazyPaintProfilerView)
return this._lazyPaintProfilerView;this._lazyPaintProfilerView=new Timeline.TimelinePaintProfilerView(this._model.frameModel());return this._lazyPaintProfilerView;}
_showSnapshotInPaintProfiler(snapshot){const paintProfilerView=this._paintProfilerView();paintProfilerView.setSnapshot(snapshot);if(!this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.PaintProfiler)){this._appendTab(Timeline.TimelineDetailsView.Tab.PaintProfiler,Common.UIString('Paint Profiler'),paintProfilerView,true);}
this._tabbedPane.selectTab(Timeline.TimelineDetailsView.Tab.PaintProfiler,true);}
_appendDetailsTabsForTraceEventAndShowDetails(event,content){this._setContent(content);if(event.name===TimelineModel.TimelineModel.RecordType.Paint||event.name===TimelineModel.TimelineModel.RecordType.RasterTask)
this._showEventInPaintProfiler(event);}
_showEventInPaintProfiler(event){const paintProfilerModel=SDK.targetManager.models(SDK.PaintProfilerModel)[0];if(!paintProfilerModel)
return;const paintProfilerView=this._paintProfilerView();const hasProfileData=paintProfilerView.setEvent(paintProfilerModel,event);if(!hasProfileData)
return;if(this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.PaintProfiler))
return;this._appendTab(Timeline.TimelineDetailsView.Tab.PaintProfiler,Common.UIString('Paint Profiler'),paintProfilerView);}
_updateSelectedRangeStats(startTime,endTime){if(!this._model||!this._track)
return;const aggregatedStats=Timeline.TimelineUIUtils.statsForTimeRange(this._track.syncEvents(),startTime,endTime);const startOffset=startTime-this._model.timelineModel().minimumRecordTime();const endOffset=endTime-this._model.timelineModel().minimumRecordTime();const contentHelper=new Timeline.TimelineDetailsContentHelper(null,null);contentHelper.addSection(ls`Range: ${Number.millisToString(startOffset)} \u2013 ${Number.millisToString(endOffset)}`);const pieChart=Timeline.TimelineUIUtils.generatePieChart(aggregatedStats);contentHelper.appendElementRow('',pieChart);this._setContent(contentHelper.fragment);}};Timeline.TimelineDetailsView.Tab={Details:'Details',EventLog:'EventLog',CallTree:'CallTree',BottomUp:'BottomUp',PaintProfiler:'PaintProfiler',LayerViewer:'LayerViewer'};;Timeline.TimelineLoader=class{constructor(client){this._client=client;this._backingStorage=new Bindings.TempFileBackingStorage();this._tracingModel=new SDK.TracingModel(this._backingStorage);this._canceledCallback=null;this._state=Timeline.TimelineLoader.State.Initial;this._buffer='';this._firstRawChunk=true;this._firstChunk=true;this._loadedBytes=0;this._totalSize;this._jsonTokenizer=new TextUtils.TextUtils.BalancedJSONTokenizer(this._writeBalancedJSON.bind(this),true);}
static loadFromFile(file,client){const loader=new Timeline.TimelineLoader(client);const fileReader=new Bindings.ChunkedFileReader(file,Timeline.TimelineLoader.TransferChunkLengthBytes);loader._canceledCallback=fileReader.cancel.bind(fileReader);loader._totalSize=file.size;fileReader.read(loader).then(success=>{if(!success)
this._reportErrorAndCancelLoading(fileReader.error().message);});return loader;}
static loadFromEvents(events,client){const loader=new Timeline.TimelineLoader(client);setTimeout(async()=>{const eventsPerChunk=5000;client.loadingStarted();for(let i=0;i<events.length;i+=eventsPerChunk){const chunk=events.slice(i,i+eventsPerChunk);loader._tracingModel.addEvents(chunk);client.loadingProgress((i+chunk.length)/events.length);await new Promise(r=>setTimeout(r));}
loader.close();});return loader;}
static loadFromURL(url,client){const loader=new Timeline.TimelineLoader(client);Host.ResourceLoader.loadAsStream(url,null,loader);return loader;}
cancel(){this._tracingModel=null;this._backingStorage.reset();this._client.loadingComplete(null);this._client=null;if(this._canceledCallback)
this._canceledCallback();}
write(chunk){if(!this._client)
return Promise.resolve();this._loadedBytes+=chunk.length;if(this._firstRawChunk)
this._client.loadingStarted();else
this._client.loadingProgress(this._totalSize?this._loadedBytes/this._totalSize:undefined);this._firstRawChunk=false;if(this._state===Timeline.TimelineLoader.State.Initial){if(chunk.startsWith('{"nodes":[')){this._state=Timeline.TimelineLoader.State.LoadingCPUProfileFormat;}else if(chunk[0]==='{'){this._state=Timeline.TimelineLoader.State.LookingForEvents;}else if(chunk[0]==='['){this._state=Timeline.TimelineLoader.State.ReadingEvents;}else{this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline data: Unknown JSON format'));return Promise.resolve();}}
if(this._state===Timeline.TimelineLoader.State.LoadingCPUProfileFormat){this._buffer+=chunk;return Promise.resolve();}
if(this._state===Timeline.TimelineLoader.State.LookingForEvents){const objectName='"traceEvents":';const startPos=this._buffer.length-objectName.length;this._buffer+=chunk;const pos=this._buffer.indexOf(objectName,startPos);if(pos===-1)
return Promise.resolve();chunk=this._buffer.slice(pos+objectName.length);this._state=Timeline.TimelineLoader.State.ReadingEvents;}
if(this._state!==Timeline.TimelineLoader.State.ReadingEvents)
return Promise.resolve();if(this._jsonTokenizer.write(chunk))
return Promise.resolve();this._state=Timeline.TimelineLoader.State.SkippingTail;if(this._firstChunk)
this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline input, wrong JSON brackets balance'));return Promise.resolve();}
_writeBalancedJSON(data){let json=data+']';if(!this._firstChunk){const commaIndex=json.indexOf(',');if(commaIndex!==-1)
json=json.slice(commaIndex+1);json='['+json;}
let items;try{items=(JSON.parse(json));}catch(e){this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline data: %s',e.toString()));return;}
if(this._firstChunk){this._firstChunk=false;if(this._looksLikeAppVersion(items[0])){this._reportErrorAndCancelLoading(Common.UIString('Legacy Timeline format is not supported.'));return;}}
try{this._tracingModel.addEvents(items);}catch(e){this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline data: %s',e.toString()));}}
_reportErrorAndCancelLoading(message){if(message)
Common.console.error(message);this.cancel();}
_looksLikeAppVersion(item){return typeof item==='string'&&item.indexOf('Chrome')!==-1;}
close(){if(!this._client)
return;this._client.processingStarted();setTimeout(()=>this._finalizeTrace(),0);}
_finalizeTrace(){if(this._state===Timeline.TimelineLoader.State.LoadingCPUProfileFormat){this._parseCPUProfileFormat(this._buffer);this._buffer='';}
this._tracingModel.tracingComplete();this._client.loadingComplete(this._tracingModel);}
_parseCPUProfileFormat(text){let traceEvents;try{const profile=JSON.parse(text);traceEvents=TimelineModel.TimelineJSProfileProcessor.buildTraceProfileFromCpuProfile(profile,1,true);}catch(e){this._reportErrorAndCancelLoading(Common.UIString('Malformed CPU profile format'));return;}
this._tracingModel.addEvents(traceEvents);}};Timeline.TimelineLoader.TransferChunkLengthBytes=5000000;Timeline.TimelineLoader.Client=function(){};Timeline.TimelineLoader.Client.prototype={loadingStarted(){},loadingProgress(progress){},processingStarted(){},loadingComplete(tracingModel){},};Timeline.TimelineLoader.State={Initial:Symbol('Initial'),LookingForEvents:Symbol('LookingForEvents'),ReadingEvents:Symbol('ReadingEvents'),SkippingTail:Symbol('SkippingTail'),LoadingCPUProfileFormat:Symbol('LoadingCPUProfileFormat')};;Timeline.TimelineEventOverview=class extends PerfUI.TimelineOverviewBase{constructor(id,title){super();this.element.id='timeline-overview-'+id;this.element.classList.add('overview-strip');this._model=null;if(title)
this.element.createChild('div','timeline-overview-strip-title').textContent=title;}
setModel(model){this._model=model;}
_renderBar(begin,end,position,height,color){const x=begin;const width=end-begin;const ctx=this.context();ctx.fillStyle=color;ctx.fillRect(x,position,width,height);}};Timeline.TimelineEventOverviewInput=class extends Timeline.TimelineEventOverview{constructor(){super('input',null);}
update(){super.update();if(!this._model)
return;const height=this.height();const descriptors=Timeline.TimelineUIUtils.eventDispatchDesciptors();const descriptorsByType=new Map();let maxPriority=-1;for(const descriptor of descriptors){for(const type of descriptor.eventTypes)
descriptorsByType.set(type,descriptor);maxPriority=Math.max(maxPriority,descriptor.priority);}
const minWidth=2*window.devicePixelRatio;const timeOffset=this._model.timelineModel().minimumRecordTime();const timeSpan=this._model.timelineModel().maximumRecordTime()-timeOffset;const canvasWidth=this.width();const scale=canvasWidth/timeSpan;for(let priority=0;priority<=maxPriority;++priority){for(const track of this._model.timelineModel().tracks()){for(let i=0;i<track.events.length;++i){const event=track.events[i];if(event.name!==TimelineModel.TimelineModel.RecordType.EventDispatch)
continue;const descriptor=descriptorsByType.get(event.args['data']['type']);if(!descriptor||descriptor.priority!==priority)
continue;const start=Number.constrain(Math.floor((event.startTime-timeOffset)*scale),0,canvasWidth);const end=Number.constrain(Math.ceil((event.endTime-timeOffset)*scale),0,canvasWidth);const width=Math.max(end-start,minWidth);this._renderBar(start,start+width,0,height,descriptor.color);}}}}};Timeline.TimelineEventOverviewNetwork=class extends Timeline.TimelineEventOverview{constructor(){super('network',Common.UIString('NET'));}
update(){super.update();if(!this._model)
return;const timelineModel=this._model.timelineModel();const bandHeight=this.height()/2;const timeOffset=timelineModel.minimumRecordTime();const timeSpan=timelineModel.maximumRecordTime()-timeOffset;const canvasWidth=this.width();const scale=canvasWidth/timeSpan;const highPath=new Path2D();const lowPath=new Path2D();const priorities=Protocol.Network.ResourcePriority;const highPrioritySet=new Set([priorities.VeryHigh,priorities.High,priorities.Medium]);for(const request of timelineModel.networkRequests()){const path=highPrioritySet.has(request.priority)?highPath:lowPath;const s=Math.max(Math.floor((request.startTime-timeOffset)*scale),0);const e=Math.min(Math.ceil((request.endTime-timeOffset)*scale+1),canvasWidth);path.rect(s,0,e-s,bandHeight-1);}
const ctx=this.context();ctx.save();ctx.fillStyle='hsl(214, 60%, 60%)';ctx.fill((highPath));ctx.translate(0,bandHeight);ctx.fillStyle='hsl(214, 80%, 80%)';ctx.fill((lowPath));ctx.restore();}};Timeline.TimelineEventOverviewCPUActivity=class extends Timeline.TimelineEventOverview{constructor(){super('cpu-activity',Common.UIString('CPU'));this._backgroundCanvas=this.element.createChild('canvas','fill background');}
resetCanvas(){super.resetCanvas();this._backgroundCanvas.width=this.element.clientWidth*window.devicePixelRatio;this._backgroundCanvas.height=this.element.clientHeight*window.devicePixelRatio;}
update(){super.update();if(!this._model)
return;const timelineModel=this._model.timelineModel();const quantSizePx=4*window.devicePixelRatio;const width=this.width();const height=this.height();const baseLine=height;const timeOffset=timelineModel.minimumRecordTime();const timeSpan=timelineModel.maximumRecordTime()-timeOffset;const scale=width/timeSpan;const quantTime=quantSizePx/scale;const categories=Timeline.TimelineUIUtils.categories();const categoryOrder=['idle','loading','painting','rendering','scripting','other'];const otherIndex=categoryOrder.indexOf('other');const idleIndex=0;console.assert(idleIndex===categoryOrder.indexOf('idle'));for(let i=idleIndex+1;i<categoryOrder.length;++i)
categories[categoryOrder[i]]._overviewIndex=i;const backgroundContext=this._backgroundCanvas.getContext('2d');for(const track of timelineModel.tracks()){if(track.type===TimelineModel.TimelineModel.TrackType.MainThread&&track.forMainFrame)
drawThreadEvents(this.context(),track.events);else
drawThreadEvents(backgroundContext,track.events);}
applyPattern(backgroundContext);function drawThreadEvents(ctx,events){const quantizer=new Timeline.Quantizer(timeOffset,quantTime,drawSample);let x=0;const categoryIndexStack=[];const paths=[];const lastY=[];for(let i=0;i<categoryOrder.length;++i){paths[i]=new Path2D();paths[i].moveTo(0,height);lastY[i]=height;}
function drawSample(counters){let y=baseLine;for(let i=idleIndex+1;i<categoryOrder.length;++i){const h=(counters[i]||0)/quantTime*height;y-=h;paths[i].bezierCurveTo(x,lastY[i],x,y,x+quantSizePx/2,y);lastY[i]=y;}
x+=quantSizePx;}
function onEventStart(e){const index=categoryIndexStack.length?categoryIndexStack.peekLast():idleIndex;quantizer.appendInterval(e.startTime,index);categoryIndexStack.push(Timeline.TimelineUIUtils.eventStyle(e).category._overviewIndex||otherIndex);}
function onEventEnd(e){quantizer.appendInterval(e.endTime,categoryIndexStack.pop());}
TimelineModel.TimelineModel.forEachEvent(events,onEventStart,onEventEnd);quantizer.appendInterval(timeOffset+timeSpan+quantTime,idleIndex);for(let i=categoryOrder.length-1;i>0;--i){paths[i].lineTo(width,height);ctx.fillStyle=categories[categoryOrder[i]].color;ctx.fill(paths[i]);}}
function applyPattern(ctx){const step=4*window.devicePixelRatio;ctx.save();ctx.lineWidth=step/Math.sqrt(8);for(let x=0.5;x<width+height;x+=step){ctx.moveTo(x,0);ctx.lineTo(x-height,height);}
ctx.globalCompositeOperation='destination-out';ctx.stroke();ctx.restore();}}};Timeline.TimelineEventOverviewResponsiveness=class extends Timeline.TimelineEventOverview{constructor(){super('responsiveness',null);}
update(){super.update();if(!this._model)
return;const height=this.height();const timeOffset=this._model.timelineModel().minimumRecordTime();const timeSpan=this._model.timelineModel().maximumRecordTime()-timeOffset;const scale=this.width()/timeSpan;const frames=this._model.frames();const ctx=(this.context());const fillPath=new Path2D();const markersPath=new Path2D();for(let i=0;i<frames.length;++i){const frame=frames[i];if(!frame.hasWarnings())
continue;paintWarningDecoration(frame.startTime,frame.duration);}
for(const track of this._model.timelineModel().tracks()){const events=track.events;for(let i=0;i<events.length;++i){if(!TimelineModel.TimelineData.forEvent(events[i]).warning)
continue;paintWarningDecoration(events[i].startTime,events[i].duration);}}
ctx.fillStyle='hsl(0, 80%, 90%)';ctx.strokeStyle='red';ctx.lineWidth=2*window.devicePixelRatio;ctx.fill(fillPath);ctx.stroke(markersPath);function paintWarningDecoration(time,duration){const x=Math.round(scale*(time-timeOffset));const w=Math.round(scale*duration);fillPath.rect(x,0,w,height);markersPath.moveTo(x+w,0);markersPath.lineTo(x+w,height);}}};Timeline.TimelineFilmStripOverview=class extends Timeline.TimelineEventOverview{constructor(){super('filmstrip',null);this.reset();}
update(){super.update();const frames=this._model?this._model.filmStripModel().frames():[];if(!frames.length)
return;const drawGeneration=Symbol('drawGeneration');this._drawGeneration=drawGeneration;this._imageByFrame(frames[0]).then(image=>{if(this._drawGeneration!==drawGeneration)
return;if(!image||!image.naturalWidth||!image.naturalHeight)
return;const imageHeight=this.height()-2*Timeline.TimelineFilmStripOverview.Padding;const imageWidth=Math.ceil(imageHeight*image.naturalWidth/image.naturalHeight);const popoverScale=Math.min(200/image.naturalWidth,1);this._emptyImage=new Image(image.naturalWidth*popoverScale,image.naturalHeight*popoverScale);this._drawFrames(imageWidth,imageHeight);});}
_imageByFrame(frame){let imagePromise=this._frameToImagePromise.get(frame);if(!imagePromise){imagePromise=frame.imageDataPromise().then(data=>UI.loadImageFromData(data));this._frameToImagePromise.set(frame,imagePromise);}
return imagePromise;}
_drawFrames(imageWidth,imageHeight){if(!imageWidth||!this._model)
return;const filmStripModel=this._model.filmStripModel();if(!filmStripModel.frames().length)
return;const padding=Timeline.TimelineFilmStripOverview.Padding;const width=this.width();const zeroTime=filmStripModel.zeroTime();const spanTime=filmStripModel.spanTime();const scale=spanTime/width;const context=this.context();const drawGeneration=this._drawGeneration;context.beginPath();for(let x=padding;x<width;x+=imageWidth+2*padding){const time=zeroTime+(x+imageWidth/2)*scale;const frame=filmStripModel.frameByTimestamp(time);if(!frame)
continue;context.rect(x-0.5,0.5,imageWidth+1,imageHeight+1);this._imageByFrame(frame).then(drawFrameImage.bind(this,x));}
context.strokeStyle='#ddd';context.stroke();function drawFrameImage(x,image){if(this._drawGeneration!==drawGeneration||!image)
return;context.drawImage(image,x,1,imageWidth,imageHeight);}}
overviewInfoPromise(x){if(!this._model||!this._model.filmStripModel().frames().length)
return Promise.resolve((null));const time=this.calculator().positionToTime(x);const frame=this._model.filmStripModel().frameByTimestamp(time);if(frame===this._lastFrame)
return Promise.resolve(this._lastElement);const imagePromise=frame?this._imageByFrame(frame):Promise.resolve(this._emptyImage);return imagePromise.then(createFrameElement.bind(this));function createFrameElement(image){const element=createElementWithClass('div','frame');if(image)
element.createChild('div','thumbnail').appendChild(image);this._lastFrame=frame;this._lastElement=element;return element;}}
reset(){this._lastFrame=undefined;this._lastElement=null;this._frameToImagePromise=new Map();this._imageWidth=0;}};Timeline.TimelineFilmStripOverview.Padding=2;Timeline.TimelineEventOverviewFrames=class extends Timeline.TimelineEventOverview{constructor(){super('framerate',Common.UIString('FPS'));}
update(){super.update();if(!this._model)
return;const frames=this._model.frames();if(!frames.length)
return;const height=this.height();const padding=1*window.devicePixelRatio;const baseFrameDurationMs=1e3/60;const visualHeight=height-2*padding;const timeOffset=this._model.timelineModel().minimumRecordTime();const timeSpan=this._model.timelineModel().maximumRecordTime()-timeOffset;const scale=this.width()/timeSpan;const baseY=height-padding;const ctx=this.context();const bottomY=baseY+10*window.devicePixelRatio;let x=0;let y=bottomY;const lineWidth=window.devicePixelRatio;const offset=lineWidth&1?0.5:0;const tickDepth=1.5*window.devicePixelRatio;ctx.beginPath();ctx.moveTo(0,y);for(let i=0;i<frames.length;++i){const frame=frames[i];x=Math.round((frame.startTime-timeOffset)*scale)+offset;ctx.lineTo(x,y);ctx.lineTo(x,y+tickDepth);y=frame.idle?bottomY:Math.round(baseY-visualHeight*Math.min(baseFrameDurationMs/frame.duration,1))-offset;ctx.lineTo(x,y+tickDepth);ctx.lineTo(x,y);}
const lastFrame=frames.peekLast();x=Math.round((lastFrame.startTime+lastFrame.duration-timeOffset)*scale)+offset;ctx.lineTo(x,y);ctx.lineTo(x,bottomY);ctx.fillStyle='hsl(110, 50%, 88%)';ctx.strokeStyle='hsl(110, 50%, 60%)';ctx.lineWidth=lineWidth;ctx.fill();ctx.stroke();}};Timeline.TimelineEventOverviewMemory=class extends Timeline.TimelineEventOverview{constructor(){super('memory',Common.UIString('HEAP'));this._heapSizeLabel=this.element.createChild('div','memory-graph-label');}
resetHeapSizeLabels(){this._heapSizeLabel.textContent='';}
update(){super.update();const ratio=window.devicePixelRatio;if(!this._model){this.resetHeapSizeLabels();return;}
const tracks=this._model.timelineModel().tracks().filter(track=>track.type===TimelineModel.TimelineModel.TrackType.MainThread&&track.forMainFrame);const trackEvents=tracks.map(track=>track.events);const lowerOffset=3*ratio;let maxUsedHeapSize=0;let minUsedHeapSize=100000000000;const minTime=this._model.timelineModel().minimumRecordTime();const maxTime=this._model.timelineModel().maximumRecordTime();function isUpdateCountersEvent(event){return event.name===TimelineModel.TimelineModel.RecordType.UpdateCounters;}
for(let i=0;i<trackEvents.length;i++)
trackEvents[i]=trackEvents[i].filter(isUpdateCountersEvent);function calculateMinMaxSizes(event){const counters=event.args.data;if(!counters||!counters.jsHeapSizeUsed)
return;maxUsedHeapSize=Math.max(maxUsedHeapSize,counters.jsHeapSizeUsed);minUsedHeapSize=Math.min(minUsedHeapSize,counters.jsHeapSizeUsed);}
for(let i=0;i<trackEvents.length;i++)
trackEvents[i].forEach(calculateMinMaxSizes);minUsedHeapSize=Math.min(minUsedHeapSize,maxUsedHeapSize);const lineWidth=1;const width=this.width();const height=this.height()-lowerOffset;const xFactor=width/(maxTime-minTime);const yFactor=(height-lineWidth)/Math.max(maxUsedHeapSize-minUsedHeapSize,1);const histogram=new Array(width);function buildHistogram(event){const counters=event.args.data;if(!counters||!counters.jsHeapSizeUsed)
return;const x=Math.round((event.startTime-minTime)*xFactor);const y=Math.round((counters.jsHeapSizeUsed-minUsedHeapSize)*yFactor);histogram[x]=Math.max(histogram[x]||0,y);}
for(let i=0;i<trackEvents.length;i++)
trackEvents[i].forEach(buildHistogram);const ctx=this.context();const heightBeyondView=height+lowerOffset+lineWidth;ctx.translate(0.5,0.5);ctx.beginPath();ctx.moveTo(-lineWidth,heightBeyondView);let y=0;let isFirstPoint=true;let lastX=0;for(let x=0;x<histogram.length;x++){if(typeof histogram[x]==='undefined')
continue;if(isFirstPoint){isFirstPoint=false;y=histogram[x];ctx.lineTo(-lineWidth,height-y);}
const nextY=histogram[x];if(Math.abs(nextY-y)>2&&Math.abs(x-lastX)>1)
ctx.lineTo(x,height-y);y=nextY;ctx.lineTo(x,height-y);lastX=x;}
ctx.lineTo(width+lineWidth,height-y);ctx.lineTo(width+lineWidth,heightBeyondView);ctx.closePath();ctx.fillStyle='hsla(220, 90%, 70%, 0.2)';ctx.fill();ctx.lineWidth=lineWidth;ctx.strokeStyle='hsl(220, 90%, 70%)';ctx.stroke();this._heapSizeLabel.textContent=Common.UIString('%s \u2013 %s',Number.bytesToString(minUsedHeapSize),Number.bytesToString(maxUsedHeapSize));}};Timeline.Quantizer=class{constructor(startTime,quantDuration,callback){this._lastTime=startTime;this._quantDuration=quantDuration;this._callback=callback;this._counters=[];this._remainder=quantDuration;}
appendInterval(time,group){let interval=time-this._lastTime;if(interval<=this._remainder){this._counters[group]=(this._counters[group]||0)+interval;this._remainder-=interval;this._lastTime=time;return;}
this._counters[group]=(this._counters[group]||0)+this._remainder;this._callback(this._counters);interval-=this._remainder;while(interval>=this._quantDuration){const counters=[];counters[group]=this._quantDuration;this._callback(counters);interval-=this._quantDuration;}
this._counters=[];this._counters[group]=interval;this._lastTime=time;this._remainder=this._quantDuration-interval;}};;Timeline.TimelineFilters={};Timeline.TimelineFilters.IsLong=class extends TimelineModel.TimelineModelFilter{constructor(){super();this._minimumRecordDuration=0;}
setMinimumRecordDuration(value){this._minimumRecordDuration=value;}
accept(event){const duration=event.endTime?event.endTime-event.startTime:0;return duration>=this._minimumRecordDuration;}};Timeline.TimelineFilters.Category=class extends TimelineModel.TimelineModelFilter{constructor(){super();}
accept(event){return!Timeline.TimelineUIUtils.eventStyle(event).category.hidden;}};Timeline.TimelineFilters.RegExp=class extends TimelineModel.TimelineModelFilter{constructor(regExp){super();this._regExp;this.setRegExp(regExp||null);}
setRegExp(regExp){this._regExp=regExp;}
regExp(){return this._regExp;}
accept(event){return!this._regExp||Timeline.TimelineUIUtils.testContentMatching(event,this._regExp);}};;Timeline.TimelineFlameChartDataProvider=class extends Common.Object{constructor(){super();this.reset();this._font='11px '+Host.fontFamily();this._timelineData=null;this._currentLevel=0;this._performanceModel=null;this._model=null;this._minimumBoundary=0;this._maximumBoundary=0;this._timeSpan=0;this._consoleColorGenerator=new Common.Color.Generator({min:30,max:55},{min:70,max:100,count:6},50,0.7);this._extensionColorGenerator=new Common.Color.Generator({min:210,max:300},{min:70,max:100,count:6},70,0.7);this._headerLevel1=this._buildGroupStyle({shareHeaderLine:false});this._headerLevel2=this._buildGroupStyle({padding:2,nestingLevel:1,collapsible:false});this._staticHeader=this._buildGroupStyle({collapsible:false});this._framesHeader=this._buildGroupStyle({useFirstLineForOverview:true});this._timingsHeader=this._buildGroupStyle({shareHeaderLine:true,useFirstLineForOverview:true});this._screenshotsHeader=this._buildGroupStyle({useFirstLineForOverview:true,nestingLevel:1,collapsible:false,itemsHeight:150});this._interactionsHeaderLevel1=this._buildGroupStyle({useFirstLineForOverview:true});this._interactionsHeaderLevel2=this._buildGroupStyle({padding:2,nestingLevel:1});this._flowEventIndexById=new Map();}
_buildGroupStyle(extra){const defaultGroupStyle={padding:4,height:17,collapsible:true,color:UI.themeSupport.patchColorText('#222',UI.ThemeSupport.ColorUsage.Foreground),backgroundColor:UI.themeSupport.patchColorText('white',UI.ThemeSupport.ColorUsage.Background),font:this._font,nestingLevel:0,shareHeaderLine:true};return(Object.assign(defaultGroupStyle,extra));}
setModel(performanceModel){this.reset();this._performanceModel=performanceModel;this._model=performanceModel&&performanceModel.timelineModel();}
groupTrack(group){return group._track||null;}
entryTitle(entryIndex){const entryTypes=Timeline.TimelineFlameChartDataProvider.EntryType;const entryType=this._entryType(entryIndex);if(entryType===entryTypes.Event){const event=(this._entryData[entryIndex]);if(event.phase===SDK.TracingModel.Phase.AsyncStepInto||event.phase===SDK.TracingModel.Phase.AsyncStepPast)
return event.name+':'+event.args['step'];if(event._blackboxRoot)
return Common.UIString('Blackboxed');if(this._performanceModel.timelineModel().isMarkerEvent(event))
return Timeline.TimelineUIUtils.markerShortTitle(event);return Timeline.TimelineUIUtils.eventTitle(event);}
if(entryType===entryTypes.ExtensionEvent){const event=(this._entryData[entryIndex]);return event.name;}
if(entryType===entryTypes.Screenshot)
return'';let title=this._entryIndexToTitle[entryIndex];if(!title){title=Common.UIString('Unexpected entryIndex %d',entryIndex);console.error(title);}
return title;}
textColor(index){const event=this._entryData[index];return event&&event._blackboxRoot?'#888':Timeline.FlameChartStyle.textColor;}
entryFont(index){return this._font;}
reset(){this._currentLevel=0;this._timelineData=null;this._entryData=[];this._entryParent=[];this._entryTypeByLevel=[];this._entryIndexToTitle=[];this._markers=[];this._asyncColorByCategory=new Map();this._asyncColorByInteractionPhase=new Map();this._extensionInfo=[];this._screenshotImageCache=new Map();}
maxStackDepth(){return this._currentLevel;}
timelineData(){if(this._timelineData)
return this._timelineData;this._timelineData=new PerfUI.FlameChart.TimelineData([],[],[],[]);if(!this._model)
return this._timelineData;this._flowEventIndexById.clear();this._minimumBoundary=this._model.minimumRecordTime();this._timeSpan=this._model.isEmpty()?1000:this._model.maximumRecordTime()-this._minimumBoundary;this._currentLevel=0;if(this._model.isGenericTrace())
this._processGenericTrace();else
this._processInspectorTrace();return this._timelineData;}
_processGenericTrace(){const processGroupStyle=this._buildGroupStyle({shareHeaderLine:false});const threadGroupStyle=this._buildGroupStyle({padding:2,nestingLevel:1,shareHeaderLine:false});const eventEntryType=Timeline.TimelineFlameChartDataProvider.EntryType.Event;const tracksByProcess=new Multimap();for(const track of this._model.tracks()){if(track.thread!==null){tracksByProcess.set(track.thread.process(),track);}else{console.error('Failed to process track');}}
for(const process of tracksByProcess.keysArray()){if(tracksByProcess.size>1){const name=`${process.name()} ${process.id()}`;this._appendHeader(name,processGroupStyle,false);}
for(const track of tracksByProcess.get(process)){const group=this._appendSyncEvents(track,track.events,track.name,threadGroupStyle,eventEntryType,true);if(!this._timelineData.selectedGroup||track.name===TimelineModel.TimelineModel.BrowserMainThreadName)
this._timelineData.selectedGroup=group;}}}
_processInspectorTrace(){this._appendFrames();this._appendInteractionRecords();const eventEntryType=Timeline.TimelineFlameChartDataProvider.EntryType.Event;const weight=track=>{switch(track.type){case TimelineModel.TimelineModel.TrackType.Input:return 0;case TimelineModel.TimelineModel.TrackType.Animation:return 1;case TimelineModel.TimelineModel.TrackType.Timings:return 2;case TimelineModel.TimelineModel.TrackType.Console:return 3;case TimelineModel.TimelineModel.TrackType.MainThread:return track.forMainFrame?4:5;case TimelineModel.TimelineModel.TrackType.Worker:return 6;case TimelineModel.TimelineModel.TrackType.Raster:return 7;case TimelineModel.TimelineModel.TrackType.GPU:return 8;case TimelineModel.TimelineModel.TrackType.Other:return 9;}};const tracks=this._model.tracks().slice();tracks.stableSort((a,b)=>weight(a)-weight(b));let rasterCount=0;for(const track of tracks){switch(track.type){case TimelineModel.TimelineModel.TrackType.Input:this._appendAsyncEventsGroup(track,ls`Input`,track.asyncEvents,this._interactionsHeaderLevel2,eventEntryType,false);break;case TimelineModel.TimelineModel.TrackType.Animation:this._appendAsyncEventsGroup(track,ls`Animation`,track.asyncEvents,this._interactionsHeaderLevel2,eventEntryType,false);break;case TimelineModel.TimelineModel.TrackType.Timings:const group=this._appendHeader(ls`Timings`,this._timingsHeader,true);group._track=track;this._appendPageMetrics();this._appendAsyncEventsGroup(track,null,track.asyncEvents,this._timingsHeader,eventEntryType,true);break;case TimelineModel.TimelineModel.TrackType.Console:this._appendAsyncEventsGroup(track,ls`Console`,track.asyncEvents,this._headerLevel1,eventEntryType,true);break;case TimelineModel.TimelineModel.TrackType.MainThread:if(track.forMainFrame){const group=this._appendSyncEvents(track,track.events,track.url?ls`Main \u2014 ${track.url}`:ls`Main`,this._headerLevel1,eventEntryType,true);if(group)
this._timelineData.selectedGroup=group;}else{this._appendSyncEvents(track,track.events,track.url?ls`Frame \u2014 ${track.url}`:ls`Subframe`,this._headerLevel1,eventEntryType,true);}
break;case TimelineModel.TimelineModel.TrackType.Worker:this._appendSyncEvents(track,track.events,track.url?ls`Worker \u2014 ${track.url}`:ls`Dedicated Worker`,this._headerLevel1,eventEntryType,true);break;case TimelineModel.TimelineModel.TrackType.Raster:if(!rasterCount)
this._appendHeader(ls`Raster`,this._headerLevel1,false);++rasterCount;this._appendSyncEvents(track,track.events,ls`Rasterizer Thread ${rasterCount}`,this._headerLevel2,eventEntryType,true);break;case TimelineModel.TimelineModel.TrackType.GPU:this._appendSyncEvents(track,track.events,ls`GPU`,this._headerLevel1,eventEntryType,true);break;case TimelineModel.TimelineModel.TrackType.Other:this._appendSyncEvents(track,track.events,track.name||ls`Thread`,this._headerLevel1,eventEntryType,true);this._appendAsyncEventsGroup(track,track.name,track.asyncEvents,this._headerLevel1,eventEntryType,true);break;}}
if(this._timelineData.selectedGroup)
this._timelineData.selectedGroup.expanded=true;for(let extensionIndex=0;extensionIndex<this._extensionInfo.length;extensionIndex++)
this._innerAppendExtensionEvents(extensionIndex);this._markers.sort((a,b)=>a.startTime()-b.startTime());this._timelineData.markers=this._markers;this._flowEventIndexById.clear();}
minimumBoundary(){return this._minimumBoundary;}
totalTime(){return this._timeSpan;}
search(startTime,endTime,filter){const result=[];const entryTypes=Timeline.TimelineFlameChartDataProvider.EntryType;this.timelineData();for(let i=0;i<this._entryData.length;++i){if(this._entryType(i)!==entryTypes.Event)
continue;const event=(this._entryData[i]);if(event.startTime>endTime)
continue;if((event.endTime||event.startTime)<startTime)
continue;if(filter.accept(event))
result.push(i);}
result.sort((a,b)=>SDK.TracingModel.Event.compareStartTime((this._entryData[a]),(this._entryData[b])));return result;}
_appendSyncEvents(track,events,title,style,entryType,selectable){if(!events.length)
return null;const isExtension=entryType===Timeline.TimelineFlameChartDataProvider.EntryType.ExtensionEvent;const openEvents=[];const flowEventsEnabled=Runtime.experiments.isEnabled('timelineFlowEvents');const blackboxingEnabled=!isExtension&&Runtime.experiments.isEnabled('blackboxJSFramesOnTimeline');let maxStackDepth=0;let group=null;if(track&&track.type===TimelineModel.TimelineModel.TrackType.MainThread){group=this._appendHeader(title,style,selectable);group._track=track;}
for(let i=0;i<events.length;++i){const e=events[i];if(!isExtension&&this._performanceModel.timelineModel().isMarkerEvent(e)){this._markers.push(new Timeline.TimelineFlameChartMarker(e.startTime,e.startTime-this._model.minimumRecordTime(),Timeline.TimelineUIUtils.markerStyleForEvent(e)));}
if(!SDK.TracingModel.isFlowPhase(e.phase)){if(!e.endTime&&e.phase!==SDK.TracingModel.Phase.Instant)
continue;if(SDK.TracingModel.isAsyncPhase(e.phase))
continue;if(!isExtension&&!this._performanceModel.isVisible(e))
continue;}
while(openEvents.length&&openEvents.peekLast().endTime<=e.startTime)
openEvents.pop();e._blackboxRoot=false;if(blackboxingEnabled&&this._isBlackboxedEvent(e)){const parent=openEvents.peekLast();if(parent&&parent._blackboxRoot)
continue;e._blackboxRoot=true;}
if(!group){group=this._appendHeader(title,style,selectable);if(selectable)
group._track=track;}
const level=this._currentLevel+openEvents.length;if(flowEventsEnabled)
this._appendFlowEvent(e,level);const index=this._appendEvent(e,level);if(openEvents.length)
this._entryParent[index]=openEvents.peekLast();if(!isExtension&&this._performanceModel.timelineModel().isMarkerEvent(e))
this._timelineData.entryTotalTimes[this._entryData.length]=undefined;maxStackDepth=Math.max(maxStackDepth,openEvents.length+1);if(e.endTime)
openEvents.push(e);}
this._entryTypeByLevel.length=this._currentLevel+maxStackDepth;this._entryTypeByLevel.fill(entryType,this._currentLevel);this._currentLevel+=maxStackDepth;return group;}
_isBlackboxedEvent(event){if(event.name!==TimelineModel.TimelineModel.RecordType.JSFrame)
return false;const url=event.args['data']['url'];return url&&this._isBlackboxedURL(url);}
_isBlackboxedURL(url){return Bindings.blackboxManager.isBlackboxedURL(url);}
_appendAsyncEventsGroup(track,header,events,style,entryType,selectable){if(!events.length)
return null;const lastUsedTimeByLevel=[];let group=null;for(let i=0;i<events.length;++i){const asyncEvent=events[i];if(!this._performanceModel.isVisible(asyncEvent))
continue;if(!group&&header){group=this._appendHeader(header,style,selectable);if(selectable)
group._track=track;}
const startTime=asyncEvent.startTime;let level;for(level=0;level<lastUsedTimeByLevel.length&&lastUsedTimeByLevel[level]>startTime;++level){}
this._appendAsyncEvent(asyncEvent,this._currentLevel+level);lastUsedTimeByLevel[level]=asyncEvent.endTime;}
this._entryTypeByLevel.length=this._currentLevel+lastUsedTimeByLevel.length;this._entryTypeByLevel.fill(entryType,this._currentLevel);this._currentLevel+=lastUsedTimeByLevel.length;return group;}
_appendInteractionRecords(){const interactionRecords=this._performanceModel.interactionRecords();if(!interactionRecords.length)
return;this._appendHeader(ls`Interactions`,this._interactionsHeaderLevel1,false);for(const segment of interactionRecords){const index=this._entryData.length;this._entryData.push((segment.data));this._entryIndexToTitle[index]=(segment.data);this._timelineData.entryLevels[index]=this._currentLevel;this._timelineData.entryTotalTimes[index]=segment.end-segment.begin;this._timelineData.entryStartTimes[index]=segment.begin;}
this._entryTypeByLevel[this._currentLevel++]=Timeline.TimelineFlameChartDataProvider.EntryType.InteractionRecord;}
_appendPageMetrics(){this._entryTypeByLevel[this._currentLevel]=Timeline.TimelineFlameChartDataProvider.EntryType.Event;const metricEvents=[];for(const track of this._model.tracks()){for(const event of track.events){if(!this._performanceModel.timelineModel().isMarkerEvent(event))
continue;metricEvents.push(event);}}
metricEvents.stableSort(SDK.TracingModel.Event.compareStartTime);const totalTimes=this._timelineData.entryTotalTimes;for(const event of metricEvents){this._appendEvent(event,this._currentLevel);totalTimes[totalTimes.length-1]=Number.NaN;}
++this._currentLevel;}
_appendFrames(){const screenshots=this._performanceModel.filmStripModel().frames();const hasFilmStrip=!!screenshots.length;this._framesHeader.collapsible=hasFilmStrip;this._appendHeader(Common.UIString('Frames'),this._framesHeader,false);this._frameGroup=this._timelineData.groups.peekLast();const style=Timeline.TimelineUIUtils.markerStyleForFrame();this._entryTypeByLevel[this._currentLevel]=Timeline.TimelineFlameChartDataProvider.EntryType.Frame;for(const frame of this._performanceModel.frames()){this._markers.push(new Timeline.TimelineFlameChartMarker(frame.startTime,frame.startTime-this._model.minimumRecordTime(),style));this._appendFrame(frame);}
++this._currentLevel;if(!hasFilmStrip)
return;this._appendHeader('',this._screenshotsHeader,false);this._entryTypeByLevel[this._currentLevel]=Timeline.TimelineFlameChartDataProvider.EntryType.Screenshot;let prevTimestamp;for(const screenshot of screenshots){this._entryData.push(screenshot);this._timelineData.entryLevels.push(this._currentLevel);this._timelineData.entryStartTimes.push(screenshot.timestamp);if(prevTimestamp)
this._timelineData.entryTotalTimes.push(screenshot.timestamp-prevTimestamp);prevTimestamp=screenshot.timestamp;}
if(screenshots.length)
this._timelineData.entryTotalTimes.push(this._model.maximumRecordTime()-prevTimestamp);++this._currentLevel;}
_entryType(entryIndex){return this._entryTypeByLevel[this._timelineData.entryLevels[entryIndex]];}
prepareHighlightedEntryInfo(entryIndex){let time='';let title;let warning;const type=this._entryType(entryIndex);if(type===Timeline.TimelineFlameChartDataProvider.EntryType.Event){const event=(this._entryData[entryIndex]);const totalTime=event.duration;const selfTime=event.selfTime;const eps=1e-6;if(typeof totalTime==='number'){time=Math.abs(totalTime-selfTime)>eps&&selfTime>eps?Common.UIString('%s (self %s)',Number.millisToString(totalTime,true),Number.millisToString(selfTime,true)):Number.millisToString(totalTime,true);}
if(this._performanceModel.timelineModel().isMarkerEvent(event))
title=Timeline.TimelineUIUtils.eventTitle(event);else
title=this.entryTitle(entryIndex);warning=Timeline.TimelineUIUtils.eventWarning(event);}else if(type===Timeline.TimelineFlameChartDataProvider.EntryType.Frame){const frame=(this._entryData[entryIndex]);time=Common.UIString('%s ~ %.0f\xa0fps',Number.preciseMillisToString(frame.duration,1),(1000/frame.duration));title=frame.idle?Common.UIString('Idle Frame'):Common.UIString('Frame');if(frame.hasWarnings()){warning=createElement('span');warning.textContent=Common.UIString('Long frame');}}else{return null;}
const element=createElement('div');const root=UI.createShadowRootWithCoreStyles(element,'timeline/timelineFlamechartPopover.css');const contents=root.createChild('div','timeline-flamechart-popover');contents.createChild('span','timeline-info-time').textContent=time;contents.createChild('span','timeline-info-title').textContent=title;if(warning){warning.classList.add('timeline-info-warning');contents.appendChild(warning);}
return element;}
entryColor(entryIndex){function patchColorAndCache(cache,key,lookupColor){let color=cache.get(key);if(color)
return color;const parsedColor=Common.Color.parse(lookupColor(key));color=parsedColor.setAlpha(0.7).asString(Common.Color.Format.RGBA)||'';cache.set(key,color);return color;}
const entryTypes=Timeline.TimelineFlameChartDataProvider.EntryType;const type=this._entryType(entryIndex);if(type===entryTypes.Event){const event=(this._entryData[entryIndex]);if(this._model.isGenericTrace())
return this._genericTraceEventColor(event);if(this._performanceModel.timelineModel().isMarkerEvent(event))
return Timeline.TimelineUIUtils.markerStyleForEvent(event).color;if(!SDK.TracingModel.isAsyncPhase(event.phase))
return this._colorForEvent(event);if(event.hasCategory(TimelineModel.TimelineModel.Category.Console)||event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming))
return this._consoleColorGenerator.colorForID(event.name);if(event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)){const phase=TimelineModel.TimelineIRModel.phaseForEvent(event)||TimelineModel.TimelineIRModel.Phases.Uncategorized;return patchColorAndCache(this._asyncColorByInteractionPhase,phase,Timeline.TimelineUIUtils.interactionPhaseColor);}
const category=Timeline.TimelineUIUtils.eventStyle(event).category;return patchColorAndCache(this._asyncColorByCategory,category,()=>category.color);}
if(type===entryTypes.Frame)
return'white';if(type===entryTypes.InteractionRecord)
return'transparent';if(type===entryTypes.ExtensionEvent){const event=(this._entryData[entryIndex]);return this._extensionColorGenerator.colorForID(event.name);}
return'';}
_genericTraceEventColor(event){const key=event.categoriesString||event.name;return key?`hsl(${String.hashCode(key) % 300 + 30}, 40%, 70%)`:'#ccc';}
_drawFrame(entryIndex,context,text,barX,barY,barWidth,barHeight){const hPadding=1;const frame=(this._entryData[entryIndex]);barX+=hPadding;barWidth-=2*hPadding;context.fillStyle=frame.idle?'white':(frame.hasWarnings()?'#fad1d1':'#d7f0d1');context.fillRect(barX,barY,barWidth,barHeight);const frameDurationText=Number.preciseMillisToString(frame.duration,1);const textWidth=context.measureText(frameDurationText).width;if(textWidth<=barWidth){context.fillStyle=this.textColor(entryIndex);context.fillText(frameDurationText,barX+(barWidth-textWidth)/2,barY+barHeight-4);}}
async _drawScreenshot(entryIndex,context,barX,barY,barWidth,barHeight){const screenshot=(this._entryData[entryIndex]);if(!this._screenshotImageCache.has(screenshot)){this._screenshotImageCache.set(screenshot,null);const data=await screenshot.imageDataPromise();const image=await UI.loadImageFromData(data);this._screenshotImageCache.set(screenshot,image);this.dispatchEventToListeners(Timeline.TimelineFlameChartDataProvider.Events.DataChanged);return;}
const image=this._screenshotImageCache.get(screenshot);if(!image)
return;const imageX=barX+1;const imageY=barY+1;const imageHeight=barHeight-2;const scale=imageHeight/image.naturalHeight;const imageWidth=Math.floor(image.naturalWidth*scale);context.save();context.beginPath();context.rect(barX,barY,barWidth,barHeight);context.clip();context.drawImage(image,imageX,imageY,imageWidth,imageHeight);context.strokeStyle='#ccc';context.strokeRect(imageX-0.5,imageY-0.5,Math.min(barWidth-1,imageWidth+1),imageHeight);context.restore();}
decorateEntry(entryIndex,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixels){const data=this._entryData[entryIndex];const type=this._entryType(entryIndex);const entryTypes=Timeline.TimelineFlameChartDataProvider.EntryType;if(type===entryTypes.Frame){this._drawFrame(entryIndex,context,text,barX,barY,barWidth,barHeight);return true;}
if(type===entryTypes.Screenshot){this._drawScreenshot(entryIndex,context,barX,barY,barWidth,barHeight);return true;}
if(type===entryTypes.InteractionRecord){const color=Timeline.TimelineUIUtils.interactionPhaseColor((data));context.fillStyle=color;context.fillRect(barX,barY,barWidth-1,2);context.fillRect(barX,barY-3,2,3);context.fillRect(barX+barWidth-3,barY-3,2,3);return false;}
if(type===entryTypes.Event){const event=(data);if(event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)){const timeWaitingForMainThread=TimelineModel.TimelineData.forEvent(event).timeWaitingForMainThread;if(timeWaitingForMainThread){context.fillStyle='hsla(0, 70%, 60%, 1)';const width=Math.floor(unclippedBarX-barX+timeWaitingForMainThread*timeToPixels);context.fillRect(barX,barY+barHeight-3,width,2);}}
if(TimelineModel.TimelineData.forEvent(event).warning)
paintWarningDecoration(barX,barWidth-1.5);}
function paintWarningDecoration(x,width){const triangleSize=8;context.save();context.beginPath();context.rect(x,barY,width,barHeight);context.clip();context.beginPath();context.fillStyle='red';context.moveTo(x+width-triangleSize,barY);context.lineTo(x+width,barY);context.lineTo(x+width,barY+triangleSize);context.fill();context.restore();}
return false;}
forceDecoration(entryIndex){const entryTypes=Timeline.TimelineFlameChartDataProvider.EntryType;const type=this._entryType(entryIndex);if(type===entryTypes.Frame)
return true;if(type===entryTypes.Screenshot)
return true;if(type===entryTypes.Event){const event=(this._entryData[entryIndex]);return!!TimelineModel.TimelineData.forEvent(event).warning;}
return false;}
appendExtensionEvents(entry){this._extensionInfo.push(entry);if(this._timelineData)
this._innerAppendExtensionEvents(this._extensionInfo.length-1);}
_innerAppendExtensionEvents(index){const entry=this._extensionInfo[index];const entryType=Timeline.TimelineFlameChartDataProvider.EntryType.ExtensionEvent;const allThreads=[].concat(...entry.model.sortedProcesses().map(process=>process.sortedThreads()));if(!allThreads.length)
return;const singleTrack=allThreads.length===1&&(!allThreads[0].events().length||!allThreads[0].asyncEvents().length);if(!singleTrack)
this._appendHeader(entry.title,this._headerLevel1,false);const style=singleTrack?this._headerLevel2:this._headerLevel1;let threadIndex=0;for(const thread of allThreads){const title=singleTrack?entry.title:thread.name()||ls`Thread ${++threadIndex}`;this._appendAsyncEventsGroup(null,title,thread.asyncEvents(),style,entryType,false);this._appendSyncEvents(null,thread.events(),title,style,entryType,false);}}
_appendHeader(title,style,selectable){const group={startLevel:this._currentLevel,name:title,style:style,selectable:selectable};this._timelineData.groups.push(group);return group;}
_appendEvent(event,level){const index=this._entryData.length;this._entryData.push(event);this._timelineData.entryLevels[index]=level;this._timelineData.entryTotalTimes[index]=event.duration||Timeline.TimelineFlameChartDataProvider.InstantEventVisibleDurationMs;this._timelineData.entryStartTimes[index]=event.startTime;event[Timeline.TimelineFlameChartDataProvider._indexSymbol]=index;return index;}
_appendAsyncEvent(asyncEvent,level){if(SDK.TracingModel.isNestableAsyncPhase(asyncEvent.phase)){this._appendEvent(asyncEvent,level);return;}
const steps=asyncEvent.steps;const eventOffset=steps.length>1&&steps[1].phase===SDK.TracingModel.Phase.AsyncStepPast?1:0;for(let i=0;i<steps.length-1;++i){const index=this._entryData.length;this._entryData.push(steps[i+eventOffset]);const startTime=steps[i].startTime;this._timelineData.entryLevels[index]=level;this._timelineData.entryTotalTimes[index]=steps[i+1].startTime-startTime;this._timelineData.entryStartTimes[index]=startTime;}}
_appendFlowEvent(event,level){const timelineData=this._timelineData;function pushStartFlow(event){const flowIndex=timelineData.flowStartTimes.length;timelineData.flowStartTimes.push(event.startTime);timelineData.flowStartLevels.push(level);return flowIndex;}
function pushEndFlow(event,flowIndex){timelineData.flowEndTimes[flowIndex]=event.startTime;timelineData.flowEndLevels[flowIndex]=level;}
switch(event.phase){case SDK.TracingModel.Phase.FlowBegin:this._flowEventIndexById.set(event.id,pushStartFlow(event));break;case SDK.TracingModel.Phase.FlowStep:pushEndFlow(event,this._flowEventIndexById.get(event.id));this._flowEventIndexById.set(event.id,pushStartFlow(event));break;case SDK.TracingModel.Phase.FlowEnd:pushEndFlow(event,this._flowEventIndexById.get(event.id));this._flowEventIndexById.delete(event.id);break;}}
_appendFrame(frame){const index=this._entryData.length;this._entryData.push(frame);this._entryIndexToTitle[index]=Number.millisToString(frame.duration,true);this._timelineData.entryLevels[index]=this._currentLevel;this._timelineData.entryTotalTimes[index]=frame.duration;this._timelineData.entryStartTimes[index]=frame.startTime;}
createSelection(entryIndex){const type=this._entryType(entryIndex);let timelineSelection=null;if(type===Timeline.TimelineFlameChartDataProvider.EntryType.Event){timelineSelection=Timeline.TimelineSelection.fromTraceEvent((this._entryData[entryIndex]));}else if(type===Timeline.TimelineFlameChartDataProvider.EntryType.Frame){timelineSelection=Timeline.TimelineSelection.fromFrame((this._entryData[entryIndex]));}
if(timelineSelection)
this._lastSelection=new Timeline.TimelineFlameChartView.Selection(timelineSelection,entryIndex);return timelineSelection;}
formatValue(value,precision){return Number.preciseMillisToString(value,precision);}
canJumpToEntry(entryIndex){return false;}
entryIndexForSelection(selection){if(!selection||selection.type()===Timeline.TimelineSelection.Type.Range)
return-1;if(this._lastSelection&&this._lastSelection.timelineSelection.object()===selection.object())
return this._lastSelection.entryIndex;const index=this._entryData.indexOf((selection.object()));if(index!==-1)
this._lastSelection=new Timeline.TimelineFlameChartView.Selection(selection,index);return index;}
buildFlowForInitiator(entryIndex){if(this._lastInitiatorEntry===entryIndex)
return false;this._lastInitiatorEntry=entryIndex;let event=this.eventByIndex(entryIndex);const td=this._timelineData;td.flowStartTimes=[];td.flowStartLevels=[];td.flowEndTimes=[];td.flowEndLevels=[];while(event){let initiator;for(;event;event=this._eventParent(event)){initiator=TimelineModel.TimelineData.forEvent(event).initiator();if(initiator)
break;}
if(!initiator)
break;const eventIndex=event[Timeline.TimelineFlameChartDataProvider._indexSymbol];const initiatorIndex=initiator[Timeline.TimelineFlameChartDataProvider._indexSymbol];td.flowStartTimes.push(initiator.endTime||initiator.startTime);td.flowStartLevels.push(td.entryLevels[initiatorIndex]);td.flowEndTimes.push(event.startTime);td.flowEndLevels.push(td.entryLevels[eventIndex]);event=initiator;}
return true;}
_eventParent(event){return this._entryParent[event[Timeline.TimelineFlameChartDataProvider._indexSymbol]]||null;}
eventByIndex(entryIndex){return entryIndex>=0&&this._entryType(entryIndex)===Timeline.TimelineFlameChartDataProvider.EntryType.Event?(this._entryData[entryIndex]):null;}
setEventColorMapping(colorForEvent){this._colorForEvent=colorForEvent;}};Timeline.TimelineFlameChartDataProvider.InstantEventVisibleDurationMs=0.001;Timeline.TimelineFlameChartDataProvider._indexSymbol=Symbol('index');Timeline.TimelineFlameChartDataProvider.Events={DataChanged:Symbol('DataChanged')};Timeline.TimelineFlameChartDataProvider.EntryType={Frame:Symbol('Frame'),Event:Symbol('Event'),InteractionRecord:Symbol('InteractionRecord'),ExtensionEvent:Symbol('ExtensionEvent'),Screenshot:Symbol('Screenshot'),};;Timeline.TimelineFlameChartNetworkDataProvider=class{constructor(){this._font='11px '+Host.fontFamily();this.setModel(null);this._style={padding:4,height:17,collapsible:true,color:UI.themeSupport.patchColorText('#222',UI.ThemeSupport.ColorUsage.Foreground),font:this._font,backgroundColor:UI.themeSupport.patchColorText('white',UI.ThemeSupport.ColorUsage.Background),nestingLevel:0,useFirstLineForOverview:false,useDecoratorsForOverview:true,shareHeaderLine:false};this._group={startLevel:0,name:Common.UIString('Network'),expanded:false,style:this._style};this._minimumBoundary=0;this._maximumBoundary=0;this._timeSpan=0;}
setModel(performanceModel){this._model=performanceModel&&performanceModel.timelineModel();this._maxLevel=0;this._timelineData=null;this._requests=[];}
isEmpty(){this.timelineData();return!this._requests.length;}
maxStackDepth(){return this._maxLevel;}
timelineData(){if(this._timelineData)
return this._timelineData;this._requests=[];this._timelineData=new PerfUI.FlameChart.TimelineData([],[],[],[]);if(this._model)
this._appendTimelineData();return this._timelineData;}
minimumBoundary(){return this._minimumBoundary;}
totalTime(){return this._timeSpan;}
setWindowTimes(startTime,endTime){this._startTime=startTime;this._endTime=endTime;this._updateTimelineData();}
createSelection(index){if(index===-1)
return null;const request=this._requests[index];this._lastSelection=new Timeline.TimelineFlameChartView.Selection(Timeline.TimelineSelection.fromNetworkRequest(request),index);return this._lastSelection.timelineSelection;}
entryIndexForSelection(selection){if(!selection)
return-1;if(this._lastSelection&&this._lastSelection.timelineSelection.object()===selection.object())
return this._lastSelection.entryIndex;if(selection.type()!==Timeline.TimelineSelection.Type.NetworkRequest)
return-1;const request=(selection.object());const index=this._requests.indexOf(request);if(index!==-1){this._lastSelection=new Timeline.TimelineFlameChartView.Selection(Timeline.TimelineSelection.fromNetworkRequest(request),index);}
return index;}
entryColor(index){const request=(this._requests[index]);const category=Timeline.TimelineUIUtils.networkRequestCategory(request);return Timeline.TimelineUIUtils.networkCategoryColor(category);}
textColor(index){return Timeline.FlameChartStyle.textColor;}
entryTitle(index){const request=(this._requests[index]);const parsedURL=new Common.ParsedURL(request.url||'');return parsedURL.isValid?`${parsedURL.displayName} (${parsedURL.host})`:request.url||null;}
entryFont(index){return this._font;}
decorateEntry(index,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixelRatio){const request=(this._requests[index]);if(!request.timing)
return false;function timeToPixel(time){return Math.floor(unclippedBarX+(time-beginTime)*timeToPixelRatio);}
const minBarWidthPx=2;const beginTime=request.beginTime();const startTime=Math.min(request.startTime,request.timing&&request.timing.requestTime*1000||Infinity);const endTime=request.endTime;const requestTime=request.timing.requestTime*1000;const sendStart=Math.max(timeToPixel(requestTime+request.timing.sendStart),unclippedBarX);const headersEnd=Math.max(timeToPixel(requestTime+request.timing.receiveHeadersEnd),sendStart);const finish=Math.max(timeToPixel(request.finishTime||endTime),headersEnd+minBarWidthPx);const start=timeToPixel(startTime);const end=Math.max(timeToPixel(endTime),finish);context.fillStyle='hsla(0, 100%, 100%, 0.8)';context.fillRect(sendStart+0.5,barY+0.5,headersEnd-sendStart-0.5,barHeight-2);context.fillStyle=UI.themeSupport.patchColorText('white',UI.ThemeSupport.ColorUsage.Background);context.fillRect(barX,barY-0.5,sendStart-barX,barHeight);context.fillRect(finish,barY-0.5,barX+barWidth-finish,barHeight);if(request.timing.pushStart){const pushStart=timeToPixel(request.timing.pushStart*1000);const pushEnd=timeToPixel(request.timing.pushEnd*1000);const dentSize=Number.constrain(pushEnd-pushStart-2,0,4);const padding=1;context.save();context.beginPath();context.moveTo(pushStart+dentSize,barY+barHeight/2);context.lineTo(pushStart,barY+padding);context.lineTo(pushEnd-dentSize,barY+padding);context.lineTo(pushEnd,barY+barHeight/2);context.lineTo(pushEnd-dentSize,barY+barHeight-padding);context.lineTo(pushStart,barY+barHeight-padding);context.closePath();context.fillStyle=this.entryColor(index);context.globalAlpha=0.3;context.fill();context.restore();}
function drawTick(begin,end,y){const tickHeightPx=6;context.moveTo(begin,y-tickHeightPx/2);context.lineTo(begin,y+tickHeightPx/2);context.moveTo(begin,y);context.lineTo(end,y);}
context.beginPath();context.lineWidth=1;context.strokeStyle='#ccc';const lineY=Math.floor(barY+barHeight/2)+0.5;const leftTick=start+0.5;const rightTick=end-0.5;drawTick(leftTick,sendStart,lineY);drawTick(rightTick,finish,lineY);context.stroke();if(typeof request.priority==='string'){const color=this._colorForPriority(request.priority);if(color){context.fillStyle=color;context.fillRect(sendStart+0.5,barY+0.5,3.5,3.5);}}
const textStart=Math.max(sendStart,0);const textWidth=finish-textStart;const minTextWidthPx=20;if(textWidth>=minTextWidthPx){text=this.entryTitle(index)||'';if(request.fromServiceWorker)
text='⚙ '+text;if(text){const textPadding=4;const textBaseline=5;const textBaseHeight=barHeight-textBaseline;const trimmedText=UI.trimTextEnd(context,text,textWidth-2*textPadding);context.fillStyle='#333';context.fillText(trimmedText,textStart+textPadding,barY+textBaseHeight);}}
return true;}
forceDecoration(index){return true;}
prepareHighlightedEntryInfo(index){const maxURLChars=80;const request=(this._requests[index]);if(!request.url)
return null;const element=createElement('div');const root=UI.createShadowRootWithCoreStyles(element,'timeline/timelineFlamechartPopover.css');const contents=root.createChild('div','timeline-flamechart-popover');const duration=request.endTime-request.startTime;if(request.startTime&&isFinite(duration))
contents.createChild('span','timeline-info-network-time').textContent=Number.millisToString(duration);if(typeof request.priority==='string'){const div=contents.createChild('span');div.textContent=PerfUI.uiLabelForNetworkPriority((request.priority));div.style.color=this._colorForPriority(request.priority)||'black';}
contents.createChild('span').textContent=request.url.trimMiddle(maxURLChars);return element;}
_colorForPriority(priority){if(!this._priorityToValue){const priorities=Protocol.Network.ResourcePriority;this._priorityToValue=new Map([[priorities.VeryLow,1],[priorities.Low,2],[priorities.Medium,3],[priorities.High,4],[priorities.VeryHigh,5]]);}
const value=this._priorityToValue.get(priority);return value?`hsla(214, 80%, 50%, ${value / 5})`:null;}
_appendTimelineData(){this._minimumBoundary=this._model.minimumRecordTime();this._maximumBoundary=this._model.maximumRecordTime();this._timeSpan=this._model.isEmpty()?1000:this._maximumBoundary-this._minimumBoundary;this._model.networkRequests().forEach(this._appendEntry.bind(this));this._updateTimelineData();}
_updateTimelineData(){if(!this._timelineData)
return;const lastTimeByLevel=[];let maxLevel=0;for(let i=0;i<this._requests.length;++i){const r=this._requests[i];const beginTime=r.beginTime();const visible=beginTime<this._endTime&&r.endTime>this._startTime;if(!visible){this._timelineData.entryLevels[i]=-1;continue;}
while(lastTimeByLevel.length&&lastTimeByLevel.peekLast()<=beginTime)
lastTimeByLevel.pop();this._timelineData.entryLevels[i]=lastTimeByLevel.length;lastTimeByLevel.push(r.endTime);maxLevel=Math.max(maxLevel,lastTimeByLevel.length);}
for(let i=0;i<this._requests.length;++i){if(this._timelineData.entryLevels[i]===-1)
this._timelineData.entryLevels[i]=maxLevel;}
this._timelineData=new PerfUI.FlameChart.TimelineData(this._timelineData.entryLevels,this._timelineData.entryTotalTimes,this._timelineData.entryStartTimes,[this._group]);this._maxLevel=maxLevel;}
_appendEntry(request){this._requests.push(request);this._timelineData.entryStartTimes.push(request.beginTime());this._timelineData.entryTotalTimes.push(request.endTime-request.beginTime());this._timelineData.entryLevels.push(this._requests.length-1);}
preferredHeight(){return this._style.height*(this._group.expanded?Number.constrain(this._maxLevel+1,4,8.5):1);}
isExpanded(){return this._group.expanded;}
formatValue(value,precision){return Number.preciseMillisToString(value,precision);}
canJumpToEntry(entryIndex){return false;}};;Timeline.TimelineFlameChartView=class extends UI.VBox{constructor(delegate){super();this.element.classList.add('timeline-flamechart');this._delegate=delegate;this._model=null;this._searchResults;this._eventListeners=[];this._showMemoryGraphSetting=Common.settings.createSetting('timelineShowMemory',false);this._networkSplitWidget=new UI.SplitWidget(false,false,'timelineFlamechartMainView',150);const mainViewGroupExpansionSetting=Common.settings.createSetting('timelineFlamechartMainViewGroupExpansion',{});this._mainDataProvider=new Timeline.TimelineFlameChartDataProvider();this._mainDataProvider.addEventListener(Timeline.TimelineFlameChartDataProvider.Events.DataChanged,()=>this._mainFlameChart.scheduleUpdate());this._mainFlameChart=new PerfUI.FlameChart(this._mainDataProvider,this,mainViewGroupExpansionSetting);this._mainFlameChart.alwaysShowVerticalScroll();this._mainFlameChart.enableRuler(false);this._networkFlameChartGroupExpansionSetting=Common.settings.createSetting('timelineFlamechartNetworkViewGroupExpansion',{});this._networkDataProvider=new Timeline.TimelineFlameChartNetworkDataProvider();this._networkFlameChart=new PerfUI.FlameChart(this._networkDataProvider,this,this._networkFlameChartGroupExpansionSetting);this._networkFlameChart.alwaysShowVerticalScroll();this._networkFlameChart.disableRangeSelection();this._networkPane=new UI.VBox();this._networkPane.setMinimumSize(23,23);this._networkFlameChart.show(this._networkPane.element);this._splitResizer=this._networkPane.element.createChild('div','timeline-flamechart-resizer');this._networkSplitWidget.hideDefaultResizer(true);this._networkSplitWidget.installResizer(this._splitResizer);this._networkSplitWidget.setMainWidget(this._mainFlameChart);this._networkSplitWidget.setSidebarWidget(this._networkPane);this._chartSplitWidget=new UI.SplitWidget(false,true,'timelineCountersSplitViewState');this._countersView=new Timeline.CountersGraph(this._delegate);this._chartSplitWidget.setMainWidget(this._networkSplitWidget);this._chartSplitWidget.setSidebarWidget(this._countersView);this._chartSplitWidget.hideDefaultResizer();this._chartSplitWidget.installResizer((this._countersView.resizerElement()));this._updateCountersGraphToggle();this._detailsSplitWidget=new UI.SplitWidget(false,true,'timelinePanelDetailsSplitViewState');this._detailsSplitWidget.element.classList.add('timeline-details-split');this._detailsView=new Timeline.TimelineDetailsView(delegate);this._detailsSplitWidget.installResizer(this._detailsView.headerElement());this._detailsSplitWidget.setMainWidget(this._chartSplitWidget);this._detailsSplitWidget.setSidebarWidget(this._detailsView);this._detailsSplitWidget.show(this.element);this._onMainEntrySelected=this._onEntrySelected.bind(this,this._mainDataProvider);this._onNetworkEntrySelected=this._onEntrySelected.bind(this,this._networkDataProvider);this._mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected,this._onMainEntrySelected,this);this._networkFlameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected,this._onNetworkEntrySelected,this);this._mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryHighlighted,this._onEntryHighlighted,this);this._nextExtensionIndex=0;this._boundRefresh=this._refresh.bind(this);this._selectedTrack=null;this._mainDataProvider.setEventColorMapping(Timeline.TimelineUIUtils.eventColor);this._groupBySetting=Common.settings.createSetting('timelineTreeGroupBy',Timeline.AggregatedTimelineTreeView.GroupBy.None);this._groupBySetting.addChangeListener(this._updateColorMapper,this);this._updateColorMapper();ProductRegistry.instance().then(registry=>this._productRegistry=registry);}
_updateColorMapper(){this._urlToColorCache=new Map();if(!this._model)
return;const colorByProduct=this._groupBySetting.get()===Timeline.AggregatedTimelineTreeView.GroupBy.Product;this._mainDataProvider.setEventColorMapping(colorByProduct?this._colorByProductForEvent.bind(this):Timeline.TimelineUIUtils.eventColor);this._mainFlameChart.update();}
_colorByProductForEvent(event){return Timeline.TimelineUIUtils.eventColorByProduct(this._productRegistry,this._model.timelineModel(),this._urlToColorCache,event);}
_onWindowChanged(event){const window=(event.data.window);const animate=!!event.data.animate;this._mainFlameChart.setWindowTimes(window.left,window.right,animate);this._networkFlameChart.setWindowTimes(window.left,window.right,animate);this._networkDataProvider.setWindowTimes(window.left,window.right);this._updateSearchResults(false,false);}
windowChanged(windowStartTime,windowEndTime,animate){this._model.setWindow({left:windowStartTime,right:windowEndTime},animate);}
updateRangeSelection(startTime,endTime){this._delegate.select(Timeline.TimelineSelection.fromRange(startTime,endTime));}
updateSelectedGroup(flameChart,group){if(flameChart!==this._mainFlameChart)
return;const track=group?this._mainDataProvider.groupTrack(group):null;this._selectedTrack=track;this._updateTrack();}
setModel(model){if(model===this._model)
return;Common.EventTarget.removeEventListeners(this._eventListeners);this._model=model;this._selectedTrack=null;this._mainDataProvider.setModel(this._model);this._networkDataProvider.setModel(this._model);if(this._model){this._eventListeners=[this._model.addEventListener(Timeline.PerformanceModel.Events.WindowChanged,this._onWindowChanged,this),this._model.addEventListener(Timeline.PerformanceModel.Events.ExtensionDataAdded,this._appendExtensionData,this)];const window=model.window();this._mainFlameChart.setWindowTimes(window.left,window.right);this._networkFlameChart.setWindowTimes(window.left,window.right);this._networkDataProvider.setWindowTimes(window.left,window.right);this._updateSearchResults(false,false);}
this._updateColorMapper();this._updateTrack();this._nextExtensionIndex=0;this._appendExtensionData();this._refresh();}
_updateTrack(){this._countersView.setModel(this._model,this._selectedTrack);this._detailsView.setModel(this._model,this._selectedTrack);}
_refresh(){if(this._networkDataProvider.isEmpty()){this._mainFlameChart.enableRuler(true);this._networkSplitWidget.hideSidebar();}else{this._mainFlameChart.enableRuler(false);this._networkSplitWidget.showBoth();this.resizeToPreferredHeights();}
this._mainFlameChart.reset();this._networkFlameChart.reset();this._updateSearchResults(false,false);}
_appendExtensionData(){if(!this._model)
return;const extensions=this._model.extensionInfo();while(this._nextExtensionIndex<extensions.length)
this._mainDataProvider.appendExtensionEvents(extensions[this._nextExtensionIndex++]);this._mainFlameChart.scheduleUpdate();}
_onEntryHighlighted(commonEvent){SDK.OverlayModel.hideDOMNodeHighlight();const entryIndex=(commonEvent.data);const event=this._mainDataProvider.eventByIndex(entryIndex);if(!event)
return;const target=this._model&&this._model.timelineModel().targetByEvent(event);if(!target)
return;const timelineData=TimelineModel.TimelineData.forEvent(event);const backendNodeId=timelineData.backendNodeId;if(!backendNodeId)
return;new SDK.DeferredDOMNode(target,backendNodeId).highlight();}
highlightEvent(event){const entryIndex=event?this._mainDataProvider.entryIndexForSelection(Timeline.TimelineSelection.fromTraceEvent(event)):-1;if(entryIndex>=0)
this._mainFlameChart.highlightEntry(entryIndex);else
this._mainFlameChart.hideHighlight();}
willHide(){this._networkFlameChartGroupExpansionSetting.removeChangeListener(this.resizeToPreferredHeights,this);this._showMemoryGraphSetting.removeChangeListener(this._updateCountersGraphToggle,this);Bindings.blackboxManager.removeChangeListener(this._boundRefresh);}
wasShown(){this._networkFlameChartGroupExpansionSetting.addChangeListener(this.resizeToPreferredHeights,this);this._showMemoryGraphSetting.addChangeListener(this._updateCountersGraphToggle,this);Bindings.blackboxManager.addChangeListener(this._boundRefresh);if(this._needsResizeToPreferredHeights)
this.resizeToPreferredHeights();this._mainFlameChart.scheduleUpdate();this._networkFlameChart.scheduleUpdate();}
_updateCountersGraphToggle(){if(this._showMemoryGraphSetting.get())
this._chartSplitWidget.showBoth();else
this._chartSplitWidget.hideSidebar();}
setSelection(selection){let index=this._mainDataProvider.entryIndexForSelection(selection);this._mainFlameChart.setSelectedEntry(index);index=this._networkDataProvider.entryIndexForSelection(selection);this._networkFlameChart.setSelectedEntry(index);if(this._detailsView)
this._detailsView.setSelection(selection);}
_onEntrySelected(dataProvider,event){const entryIndex=(event.data);if(Runtime.experiments.isEnabled('timelineEventInitiators')&&dataProvider===this._mainDataProvider){if(this._mainDataProvider.buildFlowForInitiator(entryIndex))
this._mainFlameChart.scheduleUpdate();}
this._delegate.select(dataProvider.createSelection(entryIndex));}
resizeToPreferredHeights(){if(!this.isShowing()){this._needsResizeToPreferredHeights=true;return;}
this._needsResizeToPreferredHeights=false;this._networkPane.element.classList.toggle('timeline-network-resizer-disabled',!this._networkDataProvider.isExpanded());this._networkSplitWidget.setSidebarSize(this._networkDataProvider.preferredHeight()+this._splitResizer.clientHeight+PerfUI.FlameChart.HeaderHeight+
2);}
setSearchableView(searchableView){this._searchableView=searchableView;}
jumpToNextSearchResult(){if(!this._searchResults||!this._searchResults.length)
return;const index=typeof this._selectedSearchResult!=='undefined'?this._searchResults.indexOf(this._selectedSearchResult):-1;this._selectSearchResult(mod(index+1,this._searchResults.length));}
jumpToPreviousSearchResult(){if(!this._searchResults||!this._searchResults.length)
return;const index=typeof this._selectedSearchResult!=='undefined'?this._searchResults.indexOf(this._selectedSearchResult):0;this._selectSearchResult(mod(index-1,this._searchResults.length));}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}
_selectSearchResult(index){this._searchableView.updateCurrentMatchIndex(index);this._selectedSearchResult=this._searchResults[index];this._delegate.select(this._mainDataProvider.createSelection(this._selectedSearchResult));}
_updateSearchResults(shouldJump,jumpBackwards){const oldSelectedSearchResult=this._selectedSearchResult;delete this._selectedSearchResult;this._searchResults=[];if(!this._searchRegex||!this._model)
return;const regExpFilter=new Timeline.TimelineFilters.RegExp(this._searchRegex);const window=this._model.window();this._searchResults=this._mainDataProvider.search(window.left,window.right,regExpFilter);this._searchableView.updateSearchMatchesCount(this._searchResults.length);if(!shouldJump||!this._searchResults.length)
return;let selectedIndex=this._searchResults.indexOf(oldSelectedSearchResult);if(selectedIndex===-1)
selectedIndex=jumpBackwards?this._searchResults.length-1:0;this._selectSearchResult(selectedIndex);}
searchCanceled(){if(typeof this._selectedSearchResult!=='undefined')
this._delegate.select(null);delete this._searchResults;delete this._selectedSearchResult;delete this._searchRegex;}
performSearch(searchConfig,shouldJump,jumpBackwards){this._searchRegex=searchConfig.toSearchRegex();this._updateSearchResults(shouldJump,jumpBackwards);}};Timeline.TimelineFlameChartView.Selection=class{constructor(selection,entryIndex){this.timelineSelection=selection;this.entryIndex=entryIndex;}};Timeline.FlameChartStyle={textColor:'#333'};Timeline.TimelineFlameChartMarker=class{constructor(startTime,startOffset,style){this._startTime=startTime;this._startOffset=startOffset;this._style=style;}
startTime(){return this._startTime;}
color(){return this._style.color;}
title(){if(this._style.lowPriority)
return null;const startTime=Number.millisToString(this._startOffset);return ls`${this._style.title} at ${startTime}`;}
draw(context,x,height,pixelsPerMillisecond){const lowPriorityVisibilityThresholdInPixelsPerMs=4;if(this._style.lowPriority&&pixelsPerMillisecond<lowPriorityVisibilityThresholdInPixelsPerMs)
return;context.save();if(this._style.tall){context.strokeStyle=this._style.color;context.lineWidth=this._style.lineWidth;context.translate(this._style.lineWidth<1||(this._style.lineWidth&1)?0.5:0,0.5);context.beginPath();context.moveTo(x,0);context.setLineDash(this._style.dashStyle);context.lineTo(x,context.canvas.height);context.stroke();}
context.restore();}};Timeline.TimelineFlameChartView._ColorBy={URL:'URL',Product:'Product'};;Timeline.TimelineHistoryManager=class{constructor(){this._recordings=[];this._action=(UI.actionRegistry.action('timeline.show-history'));this._nextNumberByDomain=new Map();this._button=new Timeline.TimelineHistoryManager.ToolbarButton(this._action);this.clear();this._allOverviews=[{constructor:Timeline.TimelineEventOverviewResponsiveness,height:3},{constructor:Timeline.TimelineEventOverviewFrames,height:16},{constructor:Timeline.TimelineEventOverviewCPUActivity,height:20},{constructor:Timeline.TimelineEventOverviewNetwork,height:8}];this._totalHeight=this._allOverviews.reduce((acc,entry)=>acc+entry.height,0);this._enabled=true;this._lastActiveModel=null;}
addRecording(performanceModel){this._lastActiveModel=performanceModel;this._recordings.unshift(performanceModel);this._buildPreview(performanceModel);this._button.setText(this._title(performanceModel));this._updateState();if(this._recordings.length<=Timeline.TimelineHistoryManager._maxRecordings)
return;const lruModel=this._recordings.reduce((a,b)=>lastUsedTime(a)<lastUsedTime(b)?a:b);this._recordings.splice(this._recordings.indexOf(lruModel),1);lruModel.dispose();function lastUsedTime(model){return Timeline.TimelineHistoryManager._dataForModel(model).lastUsed;}}
setEnabled(enabled){this._enabled=enabled;this._updateState();}
button(){return this._button;}
clear(){this._recordings.forEach(model=>model.dispose());this._recordings=[];this._lastActiveModel=null;this._updateState();this._button.setText(Common.UIString('(no recordings)'));this._nextNumberByDomain.clear();}
async showHistoryDropDown(){if(this._recordings.length<2||!this._enabled)
return null;const model=await Timeline.TimelineHistoryManager.DropDown.show(this._recordings,(this._lastActiveModel),this._button.element);if(!model)
return null;const index=this._recordings.indexOf(model);if(index<0){console.assert(false,`selected recording not found`);return null;}
this._setCurrentModel(model);return model;}
cancelIfShowing(){Timeline.TimelineHistoryManager.DropDown.cancelIfShowing();}
navigate(direction){if(!this._enabled||!this._lastActiveModel)
return null;const index=this._recordings.indexOf(this._lastActiveModel);if(index<0)
return null;const newIndex=Number.constrain(index+direction,0,this._recordings.length-1);const model=this._recordings[newIndex];this._setCurrentModel(model);return model;}
_setCurrentModel(model){Timeline.TimelineHistoryManager._dataForModel(model).lastUsed=Date.now();this._lastActiveModel=model;this._button.setText(this._title(model));}
_updateState(){this._action.setEnabled(this._recordings.length>1&&this._enabled);}
static _previewElement(performanceModel){const data=Timeline.TimelineHistoryManager._dataForModel(performanceModel);const startedAt=performanceModel.recordStartTime();data.time.textContent=startedAt?Common.UIString('(%s ago)',Timeline.TimelineHistoryManager._coarseAge(startedAt)):'';return data.preview;}
static _coarseAge(time){const seconds=Math.round((Date.now()-time)/1000);if(seconds<50)
return Common.UIString('moments');const minutes=Math.round(seconds/60);if(minutes<50)
return Common.UIString('%s m',minutes);const hours=Math.round(minutes/60);return Common.UIString('%s h',hours);}
_title(performanceModel){return Timeline.TimelineHistoryManager._dataForModel(performanceModel).title;}
_buildPreview(performanceModel){const parsedURL=performanceModel.timelineModel().pageURL().asParsedURL();const domain=parsedURL?parsedURL.host:'';const sequenceNumber=this._nextNumberByDomain.get(domain)||1;const title=Common.UIString('%s #%d',domain,sequenceNumber);this._nextNumberByDomain.set(domain,sequenceNumber+1);const timeElement=createElement('span');const preview=createElementWithClass('div','preview-item vbox');const data={preview:preview,title:title,time:timeElement,lastUsed:Date.now()};performanceModel[Timeline.TimelineHistoryManager._previewDataSymbol]=data;preview.appendChild(this._buildTextDetails(performanceModel,title,timeElement));const screenshotAndOverview=preview.createChild('div','hbox');screenshotAndOverview.appendChild(this._buildScreenshotThumbnail(performanceModel));screenshotAndOverview.appendChild(this._buildOverview(performanceModel));return data.preview;}
_buildTextDetails(performanceModel,title,timeElement){const container=createElementWithClass('div','text-details hbox');container.createChild('span','name').textContent=title;const tracingModel=performanceModel.tracingModel();const duration=Number.millisToString(tracingModel.maximumRecordTime()-tracingModel.minimumRecordTime(),false);const timeContainer=container.createChild('span','time');timeContainer.appendChild(createTextNode(duration));timeContainer.appendChild(timeElement);return container;}
_buildScreenshotThumbnail(performanceModel){const container=createElementWithClass('div','screenshot-thumb');const thumbnailAspectRatio=3/2;container.style.width=this._totalHeight*thumbnailAspectRatio+'px';container.style.height=this._totalHeight+'px';const filmStripModel=performanceModel.filmStripModel();const lastFrame=filmStripModel.frames().peekLast();if(!lastFrame)
return container;lastFrame.imageDataPromise().then(data=>UI.loadImageFromData(data)).then(image=>image&&container.appendChild(image));return container;}
_buildOverview(performanceModel){const container=createElement('div');container.style.width=Timeline.TimelineHistoryManager._previewWidth+'px';container.style.height=this._totalHeight+'px';const canvas=container.createChild('canvas');canvas.width=window.devicePixelRatio*Timeline.TimelineHistoryManager._previewWidth;canvas.height=window.devicePixelRatio*this._totalHeight;const ctx=canvas.getContext('2d');let yOffset=0;for(const overview of this._allOverviews){const timelineOverview=new overview.constructor();timelineOverview.setCanvasSize(Timeline.TimelineHistoryManager._previewWidth,overview.height);timelineOverview.setModel(performanceModel);timelineOverview.update();const sourceContext=timelineOverview.context();const imageData=sourceContext.getImageData(0,0,sourceContext.canvas.width,sourceContext.canvas.height);ctx.putImageData(imageData,0,yOffset);yOffset+=overview.height*window.devicePixelRatio;}
return container;}
static _dataForModel(model){return model[Timeline.TimelineHistoryManager._previewDataSymbol]||null;}};Timeline.TimelineHistoryManager.PreviewData;Timeline.TimelineHistoryManager._maxRecordings=5;Timeline.TimelineHistoryManager._previewWidth=450;Timeline.TimelineHistoryManager._previewDataSymbol=Symbol('previewData');Timeline.TimelineHistoryManager.DropDown=class{constructor(models){this._glassPane=new UI.GlassPane();this._glassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);this._glassPane.setOutsideClickCallback(()=>this._close(null));this._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this._glassPane.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferBottom);const shadowRoot=UI.createShadowRootWithCoreStyles(this._glassPane.contentElement,'timeline/timelineHistoryManager.css');const contentElement=shadowRoot.createChild('div','drop-down');const listModel=new UI.ListModel();this._listControl=new UI.ListControl(listModel,this,UI.ListMode.NonViewport);this._listControl.element.addEventListener('mousemove',this._onMouseMove.bind(this),false);listModel.replaceAll(models);contentElement.appendChild(this._listControl.element);contentElement.addEventListener('keydown',this._onKeyDown.bind(this),false);contentElement.addEventListener('click',this._onClick.bind(this),false);this._selectionDone=null;}
static show(models,currentModel,anchor){if(Timeline.TimelineHistoryManager.DropDown._instance)
return Promise.resolve((null));const instance=new Timeline.TimelineHistoryManager.DropDown(models);return instance._show(anchor,currentModel);}
static cancelIfShowing(){if(!Timeline.TimelineHistoryManager.DropDown._instance)
return;Timeline.TimelineHistoryManager.DropDown._instance._close(null);}
_show(anchor,currentModel){Timeline.TimelineHistoryManager.DropDown._instance=this;this._glassPane.setContentAnchorBox(anchor.boxInWindow());this._glassPane.show((this._glassPane.contentElement.ownerDocument));this._listControl.element.focus();this._listControl.selectItem(currentModel);return new Promise(fulfill=>this._selectionDone=fulfill);}
_onMouseMove(event){const node=event.target.enclosingNodeOrSelfWithClass('preview-item');const listItem=node&&this._listControl.itemForNode(node);if(!listItem)
return;this._listControl.selectItem(listItem);}
_onClick(event){if(!event.target.enclosingNodeOrSelfWithClass('preview-item'))
return;this._close(this._listControl.selectedItem());}
_onKeyDown(event){switch(event.key){case'Escape':this._close(null);break;case'Enter':this._close(this._listControl.selectedItem());break;default:return;}
event.consume(true);}
_close(model){this._selectionDone(model);this._glassPane.hide();Timeline.TimelineHistoryManager.DropDown._instance=null;}
createElementForItem(item){const element=Timeline.TimelineHistoryManager._previewElement(item);element.classList.remove('selected');return element;}
heightForItem(item){console.assert(false,'Should not be called');return 0;}
isItemSelectable(item){return true;}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('selected');if(toElement)
toElement.classList.add('selected');}};Timeline.TimelineHistoryManager.DropDown._instance=null;Timeline.TimelineHistoryManager.ToolbarButton=class extends UI.ToolbarItem{constructor(action){super(createElementWithClass('button','history-dropdown-button'));UI.appendStyle(this.element,'timeline/historyToolbarButton.css');this._contentElement=this.element.createChild('span','content');const dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down');this.element.appendChild(dropdownArrowIcon);this.element.addEventListener('click',()=>void action.execute(),false);this.setEnabled(action.enabled());action.addEventListener(UI.Action.Events.Enabled,event=>this.setEnabled((event.data)));this.setTitle(action.title());}
setText(text){this._contentElement.textContent=text;}};;Timeline.TimelineTreeView=class extends UI.VBox{constructor(){super();this._model=null;this._track=null;this._tree=null;this.element.classList.add('timeline-tree-view');}
static eventNameForSorting(event){if(event.name===TimelineModel.TimelineModel.RecordType.JSFrame){const data=event.args['data'];return data['functionName']+'@'+(data['scriptId']||data['url']||'');}
return event.name+':@'+TimelineModel.TimelineProfileTree.eventURL(event);}
setSearchableView(searchableView){this._searchableView=searchableView;}
setModel(model,track){this._model=model;this._track=track;this.refreshTree();}
model(){return this._model;}
init(){this._linkifier=new Components.Linkifier();this._taskFilter=new TimelineModel.ExclusiveNameFilter([TimelineModel.TimelineModel.RecordType.Task]);this._textFilter=new Timeline.TimelineFilters.RegExp();this._currentThreadSetting=Common.settings.createSetting('timelineTreeCurrentThread',0);this._currentThreadSetting.addChangeListener(this.refreshTree,this);const columns=([]);this.populateColumns(columns);this._splitWidget=new UI.SplitWidget(true,true,'timelineTreeViewDetailsSplitWidget');const mainView=new UI.VBox();const toolbar=new UI.Toolbar('',mainView.element);this.populateToolbar(toolbar);this._dataGrid=new DataGrid.SortableDataGrid(columns);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortingChanged,this);this._dataGrid.element.addEventListener('mousemove',this._onMouseMove.bind(this),true);this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);this._dataGrid.setRowContextMenuCallback(this._onContextMenu.bind(this));this._dataGrid.asWidget().show(mainView.element);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._updateDetailsForSelection,this);this._detailsView=new UI.VBox();this._detailsView.element.classList.add('timeline-details-view','timeline-details-view-body');this._splitWidget.setMainWidget(mainView);this._splitWidget.setSidebarWidget(this._detailsView);this._splitWidget.hideSidebar();this._splitWidget.show(this.element);this._splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged,this._onShowModeChanged,this);this._lastSelectedNode;}
lastSelectedNode(){return this._lastSelectedNode;}
updateContents(selection){this.setRange(selection.startTime(),selection.endTime());}
setRange(startTime,endTime){this._startTime=startTime;this._endTime=endTime;this.refreshTree();}
filters(){return[this._taskFilter,this._textFilter,...this._model.filters()];}
_exposePercentages(){return false;}
populateToolbar(toolbar){this._textFilterUI=new UI.ToolbarInput(Common.UIString('Filter'));this._textFilterUI.addEventListener(UI.ToolbarInput.Event.TextChanged,textFilterChanged,this);toolbar.appendToolbarItem(this._textFilterUI);function textFilterChanged(){const searchQuery=this._textFilterUI.value();this._textFilter.setRegExp(searchQuery?createPlainTextSearchRegex(searchQuery,'i'):null);this.refreshTree();}}
_modelEvents(){return this._track?this._track.syncEvents():[];}
_onHover(node){}
_appendContextMenuItems(contextMenu,node){}
_linkifyLocation(event){const target=this._model.timelineModel().targetByEvent(event);if(!target)
return null;const frame=TimelineModel.TimelineProfileTree.eventStackFrame(event);if(!frame)
return null;return this._linkifier.maybeLinkifyConsoleCallFrame(target,frame);}
selectProfileNode(treeNode,suppressSelectedEvent){const pathToRoot=[];for(let node=treeNode;node;node=node.parent)
pathToRoot.push(node);for(let i=pathToRoot.length-1;i>0;--i){const gridNode=this.dataGridNodeForTreeNode(pathToRoot[i]);if(gridNode&&gridNode.dataGrid)
gridNode.expand();}
const gridNode=this.dataGridNodeForTreeNode(treeNode);if(gridNode.dataGrid){gridNode.reveal();gridNode.select(suppressSelectedEvent);}}
refreshTree(){this._linkifier.reset();this._dataGrid.rootNode().removeChildren();if(!this._model){this._updateDetailsForSelection();return;}
this._root=this._buildTree();const children=this._root.children();let maxSelfTime=0;let maxTotalTime=0;const totalUsedTime=this._root.totalTime-this._root.selfTime;for(const child of children.values()){maxSelfTime=Math.max(maxSelfTime,child.selfTime);maxTotalTime=Math.max(maxTotalTime,child.totalTime);}
for(const child of children.values()){const gridNode=new Timeline.TimelineTreeView.TreeGridNode(child,totalUsedTime,maxSelfTime,maxTotalTime,this);this._dataGrid.insertChild(gridNode);}
this._sortingChanged();this._updateDetailsForSelection();if(this._searchableView)
this._searchableView.refreshSearch();}
_buildTree(){throw new Error('Not Implemented');}
buildTopDownTree(doNotAggregate,groupIdCallback){return new TimelineModel.TimelineProfileTree.TopDownRootNode(this._modelEvents(),this.filters(),this._startTime,this._endTime,doNotAggregate,groupIdCallback);}
populateColumns(columns){columns.push({id:'self',title:Common.UIString('Self Time'),width:'120px',fixedWidth:true,sortable:true});columns.push({id:'total',title:Common.UIString('Total Time'),width:'120px',fixedWidth:true,sortable:true});columns.push({id:'activity',title:Common.UIString('Activity'),disclosure:true,sortable:true});}
_sortingChanged(){const columnId=this._dataGrid.sortColumnId();if(!columnId)
return;let sortFunction;switch(columnId){case'startTime':sortFunction=compareStartTime;break;case'self':sortFunction=compareNumericField.bind(null,'selfTime');break;case'total':sortFunction=compareNumericField.bind(null,'totalTime');break;case'activity':sortFunction=compareName;break;default:console.assert(false,'Unknown sort field: '+columnId);return;}
this._dataGrid.sortNodes(sortFunction,!this._dataGrid.isSortOrderAscending());function compareNumericField(field,a,b){const nodeA=(a);const nodeB=(b);return nodeA._profileNode[field]-nodeB._profileNode[field];}
function compareStartTime(a,b){const nodeA=(a);const nodeB=(b);return nodeA._profileNode.event.startTime-nodeB._profileNode.event.startTime;}
function compareName(a,b){const nodeA=(a);const nodeB=(b);const nameA=Timeline.TimelineTreeView.eventNameForSorting(nodeA._profileNode.event);const nameB=Timeline.TimelineTreeView.eventNameForSorting(nodeB._profileNode.event);return nameA.localeCompare(nameB);}}
_onShowModeChanged(){if(this._splitWidget.showMode()===UI.SplitWidget.ShowMode.OnlyMain)
return;this._lastSelectedNode=undefined;this._updateDetailsForSelection();}
_updateDetailsForSelection(){const selectedNode=this._dataGrid.selectedNode?(this._dataGrid.selectedNode)._profileNode:null;if(selectedNode===this._lastSelectedNode)
return;this._lastSelectedNode=selectedNode;if(this._splitWidget.showMode()===UI.SplitWidget.ShowMode.OnlyMain)
return;this._detailsView.detachChildWidgets();this._detailsView.element.removeChildren();if(selectedNode&&this._showDetailsForNode(selectedNode))
return;const banner=this._detailsView.element.createChild('div','full-widget-dimmed-banner');banner.createTextChild(Common.UIString('Select item for details.'));}
_showDetailsForNode(node){return false;}
_onMouseMove(event){const gridNode=event.target&&(event.target instanceof Node)?(this._dataGrid.dataGridNodeFromNode((event.target))):null;const profileNode=gridNode&&gridNode._profileNode;if(profileNode===this._lastHoveredProfileNode)
return;this._lastHoveredProfileNode=profileNode;this._onHover(profileNode);}
_onContextMenu(contextMenu,gridNode){const profileNode=gridNode._profileNode;if(!profileNode)
return;this._appendContextMenuItems(contextMenu,profileNode);}
dataGridNodeForTreeNode(treeNode){return treeNode[Timeline.TimelineTreeView.TreeGridNode._gridNodeSymbol]||null;}
searchCanceled(){this._searchResults=[];this._currentResult=0;}
performSearch(searchConfig,shouldJump,jumpBackwards){this._searchResults=[];this._currentResult=0;if(!this._root)
return;const searchRegex=searchConfig.toSearchRegex();this._searchResults=this._root.searchTree(event=>Timeline.TimelineUIUtils.testContentMatching(event,searchRegex));this._searchableView.updateSearchMatchesCount(this._searchResults.length);}
jumpToNextSearchResult(){if(!this._searchResults.length)
return;this.selectProfileNode(this._searchResults[this._currentResult],false);this._currentResult=mod(this._currentResult+1,this._searchResults.length);}
jumpToPreviousSearchResult(){if(!this._searchResults.length)
return;this.selectProfileNode(this._searchResults[this._currentResult],false);this._currentResult=mod(this._currentResult-1,this._searchResults.length);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}};Timeline.TimelineTreeView.GridNode=class extends DataGrid.SortableDataGridNode{constructor(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView){super(null,false);this._populated=false;this._profileNode=profileNode;this._treeView=treeView;this._grandTotalTime=grandTotalTime;this._maxSelfTime=maxSelfTime;this._maxTotalTime=maxTotalTime;}
createCell(columnId){if(columnId==='activity')
return this._createNameCell(columnId);return this._createValueCell(columnId)||super.createCell(columnId);}
_createNameCell(columnId){const cell=this.createTD(columnId);const container=cell.createChild('div','name-container');const iconContainer=container.createChild('div','activity-icon-container');const icon=iconContainer.createChild('div','activity-icon');const name=container.createChild('div','activity-name');const event=this._profileNode.event;if(this._profileNode.isGroupNode()){const treeView=(this._treeView);const info=treeView._displayInfoForGroupNode(this._profileNode);name.textContent=info.name;icon.style.backgroundColor=info.color;if(info.icon)
iconContainer.insertBefore(info.icon,icon);}else if(event){const data=event.args['data'];const deoptReason=data&&data['deoptReason'];if(deoptReason)
container.createChild('div','activity-warning').title=Common.UIString('Not optimized: %s',deoptReason);name.textContent=Timeline.TimelineUIUtils.eventTitle(event);const link=this._treeView._linkifyLocation(event);if(link)
container.createChild('div','activity-link').appendChild(link);icon.style.backgroundColor=Timeline.TimelineUIUtils.eventColor(event);}
return cell;}
_createValueCell(columnId){if(columnId!=='self'&&columnId!=='total'&&columnId!=='startTime')
return null;let showPercents=false;let value;let maxTime;switch(columnId){case'startTime':value=this._profileNode.event.startTime-this._treeView._model.timelineModel().minimumRecordTime();break;case'self':value=this._profileNode.selfTime;maxTime=this._maxSelfTime;showPercents=true;break;case'total':value=this._profileNode.totalTime;maxTime=this._maxTotalTime;showPercents=true;break;default:return null;}
const cell=this.createTD(columnId);cell.className='numeric-column';const textDiv=cell.createChild('div');textDiv.createChild('span').textContent=Common.UIString('%.1f\xa0ms',value);if(showPercents&&this._treeView._exposePercentages()){textDiv.createChild('span','percent-column').textContent=Common.UIString('%.1f\xa0%%',value/this._grandTotalTime*100);}
if(maxTime){textDiv.classList.add('background-percent-bar');cell.createChild('div','background-bar-container').createChild('div','background-bar').style.width=(value*100/maxTime).toFixed(1)+'%';}
return cell;}};Timeline.TimelineTreeView.TreeGridNode=class extends Timeline.TimelineTreeView.GridNode{constructor(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView){super(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView);this.setHasChildren(this._profileNode.hasChildren());profileNode[Timeline.TimelineTreeView.TreeGridNode._gridNodeSymbol]=this;}
populate(){if(this._populated)
return;this._populated=true;if(!this._profileNode.children)
return;for(const node of this._profileNode.children().values()){const gridNode=new Timeline.TimelineTreeView.TreeGridNode(node,this._grandTotalTime,this._maxSelfTime,this._maxTotalTime,this._treeView);this.insertChildOrdered(gridNode);}}};Timeline.TimelineTreeView.TreeGridNode._gridNodeSymbol=Symbol('treeGridNode');Timeline.AggregatedTimelineTreeView=class extends Timeline.TimelineTreeView{constructor(){super();this._groupBySetting=Common.settings.createSetting('timelineTreeGroupBy',Timeline.AggregatedTimelineTreeView.GroupBy.None);this._groupBySetting.addChangeListener(this.refreshTree.bind(this));this.init();this._stackView=new Timeline.TimelineStackView(this);this._stackView.addEventListener(Timeline.TimelineStackView.Events.SelectionChanged,this._onStackViewSelectionChanged,this);this._badgePool=new ProductRegistry.BadgePool(true);this._productByURLCache=new Map();this._colorByURLCache=new Map();ProductRegistry.instance().then(registry=>{this._productRegistry=registry;this.refreshTree();});}
setModel(model,track){this._badgePool.reset();super.setModel(model,track);}
updateContents(selection){this._updateExtensionResolver();super.updateContents(selection);const rootNode=this._dataGrid.rootNode();if(rootNode.children.length)
rootNode.children[0].revealAndSelect();}
_updateExtensionResolver(){this._executionContextNamesByOrigin=new Map();for(const runtimeModel of SDK.targetManager.models(SDK.RuntimeModel)){for(const context of runtimeModel.executionContexts())
this._executionContextNamesByOrigin.set(context.origin,context.name);}}
_beautifyDomainName(name){if(Timeline.AggregatedTimelineTreeView._isExtensionInternalURL(name))
name=Common.UIString('[Chrome extensions overhead]');else if(Timeline.AggregatedTimelineTreeView._isV8NativeURL(name))
name=Common.UIString('[V8 Runtime]');else if(name.startsWith('chrome-extension'))
name=this._executionContextNamesByOrigin.get(name)||name;return name;}
_displayInfoForGroupNode(node){const categories=Timeline.TimelineUIUtils.categories();let color=node.id?Timeline.TimelineUIUtils.eventColor((node.event)):categories['other'].color;const unattributed=Common.UIString('[unattributed]');switch(this._groupBySetting.get()){case Timeline.AggregatedTimelineTreeView.GroupBy.Category:{const category=categories[node.id]||categories['other'];return{name:category.title,color:category.color};}
case Timeline.AggregatedTimelineTreeView.GroupBy.Domain:case Timeline.AggregatedTimelineTreeView.GroupBy.Subdomain:{let domainName=this._beautifyDomainName(node.id);if(domainName){const productName=this._productByEvent((node.event));if(productName)
domainName+=' \u2014 '+productName;}
return{name:domainName||unattributed,color:color};}
case Timeline.AggregatedTimelineTreeView.GroupBy.EventName:{const name=node.event.name===TimelineModel.TimelineModel.RecordType.JSFrame?Common.UIString('JavaScript'):Timeline.TimelineUIUtils.eventTitle(node.event);return{name:name,color:node.event.name===TimelineModel.TimelineModel.RecordType.JSFrame?Timeline.TimelineUIUtils.eventStyle(node.event).category.color:color};}
case Timeline.AggregatedTimelineTreeView.GroupBy.Product:{const event=(node.event);const info=this._productAndBadgeByEvent(event);const name=info&&info.name||unattributed;color=Timeline.TimelineUIUtils.eventColorByProduct(this._productRegistry,this._model.timelineModel(),this._colorByURLCache,event);return{name:name,color:color,icon:info&&info.badge||undefined};}
case Timeline.AggregatedTimelineTreeView.GroupBy.URL:break;case Timeline.AggregatedTimelineTreeView.GroupBy.Frame:{const frame=this._model.timelineModel().pageFrameById(node.id);const frameName=frame?Timeline.TimelineUIUtils.displayNameForFrame(frame,80):Common.UIString('Page');return{name:frameName,color:color};}
default:console.assert(false,'Unexpected grouping type');}
return{name:node.id||unattributed,color:color};}
populateToolbar(toolbar){super.populateToolbar(toolbar);const groupBy=Timeline.AggregatedTimelineTreeView.GroupBy;const options=[{label:Common.UIString('No Grouping'),value:groupBy.None},{label:Common.UIString('Group by Activity'),value:groupBy.EventName},{label:Common.UIString('Group by Category'),value:groupBy.Category},{label:Common.UIString('Group by Domain'),value:groupBy.Domain},{label:Common.UIString('Group by Frame'),value:groupBy.Frame},{label:Common.UIString('Group by Product'),value:groupBy.Product},{label:Common.UIString('Group by Subdomain'),value:groupBy.Subdomain},{label:Common.UIString('Group by URL'),value:groupBy.URL},];toolbar.appendToolbarItem(new UI.ToolbarSettingComboBox(options,this._groupBySetting));toolbar.appendSpacer();toolbar.appendToolbarItem(this._splitWidget.createShowHideSidebarButton(Common.UIString('heaviest stack')));}
_buildHeaviestStack(treeNode){console.assert(!!treeNode.parent,'Attempt to build stack for tree root');let result=[];for(let node=treeNode;node&&node.parent;node=node.parent)
result.push(node);result=result.reverse();for(let node=treeNode;node&&node.children()&&node.children().size;){const children=Array.from(node.children().values());node=children.reduce((a,b)=>a.totalTime>b.totalTime?a:b);result.push(node);}
return result;}
_exposePercentages(){return true;}
_onStackViewSelectionChanged(){const treeNode=this._stackView.selectedTreeNode();if(treeNode)
this.selectProfileNode(treeNode,true);}
_showDetailsForNode(node){const stack=this._buildHeaviestStack(node);this._stackView.setStack(stack,node);this._stackView.show(this._detailsView.element);return true;}
_groupingFunction(groupBy){const GroupBy=Timeline.AggregatedTimelineTreeView.GroupBy;switch(groupBy){case GroupBy.None:return null;case GroupBy.EventName:return event=>Timeline.TimelineUIUtils.eventStyle(event).title;case GroupBy.Category:return event=>Timeline.TimelineUIUtils.eventStyle(event).category.name;case GroupBy.Subdomain:return this._domainByEvent.bind(this,false);case GroupBy.Domain:return this._domainByEvent.bind(this,true);case GroupBy.Product:return event=>this._productByEvent(event)||this._domainByEvent(true,event)||'';case GroupBy.URL:return event=>TimelineModel.TimelineProfileTree.eventURL(event)||'';case GroupBy.Frame:return event=>TimelineModel.TimelineData.forEvent(event).frameId;default:console.assert(false,`Unexpected aggregation setting: ${groupBy}`);return null;}}
_domainByEvent(groupSubdomains,event){const url=TimelineModel.TimelineProfileTree.eventURL(event);if(!url)
return'';if(Timeline.AggregatedTimelineTreeView._isExtensionInternalURL(url))
return Timeline.AggregatedTimelineTreeView._extensionInternalPrefix;if(Timeline.AggregatedTimelineTreeView._isV8NativeURL(url))
return Timeline.AggregatedTimelineTreeView._v8NativePrefix;const parsedURL=url.asParsedURL();if(!parsedURL)
return'';if(parsedURL.scheme==='chrome-extension')
return parsedURL.scheme+'://'+parsedURL.host;if(!groupSubdomains)
return parsedURL.host;if(/^[.0-9]+$/.test(parsedURL.host))
return parsedURL.host;const domainMatch=/([^.]*\.)?[^.]*$/.exec(parsedURL.host);return domainMatch&&domainMatch[0]||'';}
_productByEvent(event){const url=TimelineModel.TimelineProfileTree.eventURL(event);if(!url)
return'';if(this._productByURLCache.has(url))
return this._productByURLCache.get(url);if(!this._productRegistry)
return'';const parsedURL=url.asParsedURL();const name=parsedURL&&this._productRegistry.nameForUrl(parsedURL)||'';this._productByURLCache.set(url,name);return name;}
_productAndBadgeByEvent(event){const url=TimelineModel.TimelineProfileTree.eventURL(event);if(!url||!this._productRegistry)
return null;const parsedURL=url.asParsedURL();const name=parsedURL&&this._productRegistry.nameForUrl(parsedURL)||this._domainByEvent(true,event);if(!name)
return null;const icon=parsedURL&&this._badgePool.badgeForURL(parsedURL);return{name:this._beautifyDomainName(name),badge:icon};}
_appendContextMenuItems(contextMenu,node){if(this._groupBySetting.get()!==Timeline.AggregatedTimelineTreeView.GroupBy.Frame)
return;if(!node.isGroupNode())
return;const frame=this._model.timelineModel().pageFrameById(node.id);if(!frame||!frame.ownerNode)
return;contextMenu.appendApplicableItems(frame.ownerNode);}
static _isExtensionInternalURL(url){return url.startsWith(Timeline.AggregatedTimelineTreeView._extensionInternalPrefix);}
static _isV8NativeURL(url){return url.startsWith(Timeline.AggregatedTimelineTreeView._v8NativePrefix);}};Timeline.AggregatedTimelineTreeView._extensionInternalPrefix='extensions::';Timeline.AggregatedTimelineTreeView._v8NativePrefix='native ';Timeline.AggregatedTimelineTreeView.GroupBy={None:'None',EventName:'EventName',Category:'Category',Domain:'Domain',Subdomain:'Subdomain',Product:'Product',URL:'URL',Frame:'Frame'};Timeline.CallTreeTimelineTreeView=class extends Timeline.AggregatedTimelineTreeView{constructor(){super();this._dataGrid.markColumnAsSortedBy('total',DataGrid.DataGrid.Order.Descending);}
_buildTree(){const grouping=this._groupBySetting.get();return this.buildTopDownTree(false,this._groupingFunction(grouping));}};Timeline.BottomUpTimelineTreeView=class extends Timeline.AggregatedTimelineTreeView{constructor(){super();this._dataGrid.markColumnAsSortedBy('self',DataGrid.DataGrid.Order.Descending);}
_buildTree(){return new TimelineModel.TimelineProfileTree.BottomUpRootNode(this._modelEvents(),this.filters(),this._startTime,this._endTime,this._groupingFunction(this._groupBySetting.get()));}};Timeline.TimelineStackView=class extends UI.VBox{constructor(treeView){super();const header=this.element.createChild('div','timeline-stack-view-header');header.textContent=Common.UIString('Heaviest stack');this._treeView=treeView;const columns=([{id:'total',title:Common.UIString('Total Time'),fixedWidth:true,width:'110px'},{id:'activity',title:Common.UIString('Activity')}]);this._dataGrid=new DataGrid.ViewportDataGrid(columns);this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._onSelectionChanged,this);this._dataGrid.asWidget().show(this.element);}
setStack(stack,selectedNode){const rootNode=this._dataGrid.rootNode();rootNode.removeChildren();let nodeToReveal=null;const totalTime=Math.max.apply(Math,stack.map(node=>node.totalTime));for(const node of stack){const gridNode=new Timeline.TimelineTreeView.GridNode(node,totalTime,totalTime,totalTime,this._treeView);rootNode.appendChild(gridNode);if(node===selectedNode)
nodeToReveal=gridNode;}
nodeToReveal.revealAndSelect();}
selectedTreeNode(){const selectedNode=this._dataGrid.selectedNode;return selectedNode&&(selectedNode)._profileNode;}
_onSelectionChanged(){this.dispatchEventToListeners(Timeline.TimelineStackView.Events.SelectionChanged);}};Timeline.TimelineStackView.Events={SelectionChanged:Symbol('SelectionChanged')};;Timeline.EventsTimelineTreeView=class extends Timeline.TimelineTreeView{constructor(delegate){super();this._filtersControl=new Timeline.EventsTimelineTreeView.Filters();this._filtersControl.addEventListener(Timeline.EventsTimelineTreeView.Filters.Events.FilterChanged,this._onFilterChanged,this);this.init();this._delegate=delegate;this._badgePool=new ProductRegistry.BadgePool(true);this._dataGrid.markColumnAsSortedBy('startTime',DataGrid.DataGrid.Order.Ascending);this._splitWidget.showBoth();}
filters(){return[...super.filters(),...this._filtersControl.filters()];}
updateContents(selection){this._badgePool.reset();super.updateContents(selection);if(selection.type()===Timeline.TimelineSelection.Type.TraceEvent){const event=(selection.object());this._selectEvent(event,true);}}
_buildTree(){this._currentTree=this.buildTopDownTree(true,null);return this._currentTree;}
_onFilterChanged(){const selectedEvent=this.lastSelectedNode()&&this.lastSelectedNode().event;this.refreshTree();if(selectedEvent)
this._selectEvent(selectedEvent,false);}
_findNodeWithEvent(event){const iterators=[this._currentTree.children().values()];while(iterators.length){const iterator=iterators.peekLast().next();if(iterator.done){iterators.pop();continue;}
const child=(iterator.value);if(child.event===event)
return child;iterators.push(child.children().values());}
return null;}
_selectEvent(event,expand){const node=this._findNodeWithEvent(event);if(!node)
return;this.selectProfileNode(node,false);if(expand)
this.dataGridNodeForTreeNode(node).expand();}
populateColumns(columns){columns.push({id:'startTime',title:Common.UIString('Start Time'),width:'80px',fixedWidth:true,sortable:true});super.populateColumns(columns);columns.filter(c=>c.fixedWidth).forEach(c=>c.width='80px');}
populateToolbar(toolbar){super.populateToolbar(toolbar);this._filtersControl.populateToolbar(toolbar);}
_showDetailsForNode(node){const traceEvent=node.event;if(!traceEvent)
return false;Timeline.TimelineUIUtils.buildTraceEventDetails(traceEvent,this.model().timelineModel(),this._linkifier,this._badgePool,false).then(fragment=>this._detailsView.element.appendChild(fragment));return true;}
_onHover(node){this._delegate.highlightEvent(node&&node.event);}};Timeline.EventsTimelineTreeView.Filters=class extends Common.Object{constructor(){super();this._categoryFilter=new Timeline.TimelineFilters.Category();this._durationFilter=new Timeline.TimelineFilters.IsLong();this._filters=[this._categoryFilter,this._durationFilter];}
filters(){return this._filters;}
populateToolbar(toolbar){const durationFilterUI=new UI.ToolbarComboBox(durationFilterChanged.bind(this));for(const durationMs of Timeline.EventsTimelineTreeView.Filters._durationFilterPresetsMs){durationFilterUI.addOption(durationFilterUI.createOption(durationMs?Common.UIString('\u2265 %d\xa0ms',durationMs):Common.UIString('All'),durationMs?Common.UIString('Hide records shorter than %d\xa0ms',durationMs):Common.UIString('Show all records'),String(durationMs)));}
toolbar.appendToolbarItem(durationFilterUI);const categoryFiltersUI={};const categories=Timeline.TimelineUIUtils.categories();for(const categoryName in categories){const category=categories[categoryName];if(!category.visible)
continue;const checkbox=new UI.ToolbarCheckbox(category.title,undefined,categoriesFilterChanged.bind(this,categoryName));checkbox.setChecked(true);checkbox.inputElement.style.backgroundColor=category.color;categoryFiltersUI[category.name]=checkbox;toolbar.appendToolbarItem(checkbox);}
function durationFilterChanged(){const duration=durationFilterUI.selectedOption().value;const minimumRecordDuration=parseInt(duration,10);this._durationFilter.setMinimumRecordDuration(minimumRecordDuration);this._notifyFiltersChanged();}
function categoriesFilterChanged(name){const categories=Timeline.TimelineUIUtils.categories();categories[name].hidden=!categoryFiltersUI[name].checked();this._notifyFiltersChanged();}}
_notifyFiltersChanged(){this.dispatchEventToListeners(Timeline.EventsTimelineTreeView.Filters.Events.FilterChanged);}};Timeline.EventsTimelineTreeView.Filters._durationFilterPresetsMs=[0,1,15];Timeline.EventsTimelineTreeView.Filters.Events={FilterChanged:Symbol('FilterChanged')};;Timeline.TimelineUIUtils=class{static _initEventStyles(){if(Timeline.TimelineUIUtils._eventStylesMap)
return Timeline.TimelineUIUtils._eventStylesMap;const type=TimelineModel.TimelineModel.RecordType;const categories=Timeline.TimelineUIUtils.categories();const rendering=categories['rendering'];const scripting=categories['scripting'];const loading=categories['loading'];const painting=categories['painting'];const other=categories['other'];const eventStyles={};eventStyles[type.Task]=new Timeline.TimelineRecordStyle(ls`Task`,other);eventStyles[type.Program]=new Timeline.TimelineRecordStyle(ls`Other`,other);eventStyles[type.Animation]=new Timeline.TimelineRecordStyle(ls`Animation`,rendering);eventStyles[type.EventDispatch]=new Timeline.TimelineRecordStyle(ls`Event`,scripting);eventStyles[type.RequestMainThreadFrame]=new Timeline.TimelineRecordStyle(ls`Request Main Thread Frame`,rendering,true);eventStyles[type.BeginFrame]=new Timeline.TimelineRecordStyle(ls`Frame Start`,rendering,true);eventStyles[type.BeginMainThreadFrame]=new Timeline.TimelineRecordStyle(ls`Frame Start (main thread)`,rendering,true);eventStyles[type.DrawFrame]=new Timeline.TimelineRecordStyle(ls`Draw Frame`,rendering,true);eventStyles[type.HitTest]=new Timeline.TimelineRecordStyle(ls`Hit Test`,rendering);eventStyles[type.ScheduleStyleRecalculation]=new Timeline.TimelineRecordStyle(ls`Schedule Style Recalculation`,rendering);eventStyles[type.RecalculateStyles]=new Timeline.TimelineRecordStyle(ls`Recalculate Style`,rendering);eventStyles[type.UpdateLayoutTree]=new Timeline.TimelineRecordStyle(ls`Recalculate Style`,rendering);eventStyles[type.InvalidateLayout]=new Timeline.TimelineRecordStyle(ls`Invalidate Layout`,rendering,true);eventStyles[type.Layout]=new Timeline.TimelineRecordStyle(ls`Layout`,rendering);eventStyles[type.PaintSetup]=new Timeline.TimelineRecordStyle(ls`Paint Setup`,painting);eventStyles[type.PaintImage]=new Timeline.TimelineRecordStyle(ls`Paint Image`,painting,true);eventStyles[type.UpdateLayer]=new Timeline.TimelineRecordStyle(ls`Update Layer`,painting,true);eventStyles[type.UpdateLayerTree]=new Timeline.TimelineRecordStyle(ls`Update Layer Tree`,rendering);eventStyles[type.Paint]=new Timeline.TimelineRecordStyle(ls`Paint`,painting);eventStyles[type.RasterTask]=new Timeline.TimelineRecordStyle(ls`Rasterize Paint`,painting);eventStyles[type.ScrollLayer]=new Timeline.TimelineRecordStyle(ls`Scroll`,rendering);eventStyles[type.CompositeLayers]=new Timeline.TimelineRecordStyle(ls`Composite Layers`,painting);eventStyles[type.ParseHTML]=new Timeline.TimelineRecordStyle(ls`Parse HTML`,loading);eventStyles[type.ParseAuthorStyleSheet]=new Timeline.TimelineRecordStyle(ls`Parse Stylesheet`,loading);eventStyles[type.TimerInstall]=new Timeline.TimelineRecordStyle(ls`Install Timer`,scripting);eventStyles[type.TimerRemove]=new Timeline.TimelineRecordStyle(ls`Remove Timer`,scripting);eventStyles[type.TimerFire]=new Timeline.TimelineRecordStyle(ls`Timer Fired`,scripting);eventStyles[type.XHRReadyStateChange]=new Timeline.TimelineRecordStyle(ls`XHR Ready State Change`,scripting);eventStyles[type.XHRLoad]=new Timeline.TimelineRecordStyle(ls`XHR Load`,scripting);eventStyles[type.CompileScript]=new Timeline.TimelineRecordStyle(ls`Compile Script`,scripting);eventStyles[type.EvaluateScript]=new Timeline.TimelineRecordStyle(ls`Evaluate Script`,scripting);eventStyles[type.CompileModule]=new Timeline.TimelineRecordStyle(ls`Compile Module`,scripting);eventStyles[type.EvaluateModule]=new Timeline.TimelineRecordStyle(ls`Evaluate Module`,scripting);eventStyles[type.ParseScriptOnBackground]=new Timeline.TimelineRecordStyle(ls`Parse Script`,scripting);eventStyles[type.WasmStreamFromResponseCallback]=new Timeline.TimelineRecordStyle(ls`Streaming Wasm Response`,scripting);eventStyles[type.WasmCompiledModule]=new Timeline.TimelineRecordStyle(ls`Compiled Wasm Module`,scripting);eventStyles[type.WasmCachedModule]=new Timeline.TimelineRecordStyle(ls`Cached Wasm Module`,scripting);eventStyles[type.WasmModuleCacheHit]=new Timeline.TimelineRecordStyle(ls`Wasm Module Cache Hit`,scripting);eventStyles[type.WasmModuleCacheInvalid]=new Timeline.TimelineRecordStyle(ls`Wasm Module Cache
static inputEventDisplayName(inputEventType){if(!Timeline.TimelineUIUtils._inputEventToDisplayName){const inputEvent=TimelineModel.TimelineIRModel.InputEvents;Timeline.TimelineUIUtils._inputEventToDisplayName=new Map([[inputEvent.Char,ls`Key Character`],[inputEvent.KeyDown,ls`Key Down`],[inputEvent.KeyDownRaw,ls`Key Down`],[inputEvent.KeyUp,ls`Key Up`],[inputEvent.Click,ls`Click`],[inputEvent.ContextMenu,ls`Context Menu`],[inputEvent.MouseDown,ls`Mouse Down`],[inputEvent.MouseMove,ls`Mouse Move`],[inputEvent.MouseUp,ls`Mouse Up`],[inputEvent.MouseWheel,ls`Mouse Wheel`],[inputEvent.ScrollBegin,ls`Scroll Begin`],[inputEvent.ScrollEnd,ls`Scroll End`],[inputEvent.ScrollUpdate,ls`Scroll Update`],[inputEvent.FlingStart,ls`Fling Start`],[inputEvent.FlingCancel,ls`Fling Halt`],[inputEvent.Tap,ls`Tap`],[inputEvent.TapCancel,ls`Tap Halt`],[inputEvent.ShowPress,ls`Tap Begin`],[inputEvent.TapDown,ls`Tap Down`],[inputEvent.TouchCancel,ls`Touch Cancel`],[inputEvent.TouchEnd,ls`Touch End`],[inputEvent.TouchMove,ls`Touch Move`],[inputEvent.TouchStart,ls`Touch Start`],[inputEvent.PinchBegin,ls`Pinch Begin`],[inputEvent.PinchEnd,ls`Pinch End`],[inputEvent.PinchUpdate,ls`Pinch Update`]]);}
return Timeline.TimelineUIUtils._inputEventToDisplayName.get(inputEventType)||null;}
static frameDisplayName(frame){if(!TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame))
return UI.beautifyFunctionName(frame.functionName);const nativeGroup=TimelineModel.TimelineJSProfileProcessor.nativeGroup(frame.functionName);const groups=TimelineModel.TimelineJSProfileProcessor.NativeGroups;switch(nativeGroup){case groups.Compile:return ls`Compile`;case groups.Parse:return ls`Parse`;}
return frame.functionName;}
static testContentMatching(traceEvent,regExp){const title=Timeline.TimelineUIUtils.eventStyle(traceEvent).title;const tokens=[title];const url=TimelineModel.TimelineData.forEvent(traceEvent).url;if(url)
tokens.push(url);appendObjectProperties(traceEvent.args,2);return regExp.test(tokens.join('|'));function appendObjectProperties(object,depth){if(!depth)
return;for(const key in object){const value=object[key];const type=typeof value;if(type==='string')
tokens.push(value);else if(type==='number')
tokens.push(String(value));else if(type==='object')
appendObjectProperties(value,depth-1);}}}
static eventURL(event){const data=event.args['data']||event.args['beginData'];const url=data&&data.url;if(url)
return url;const stackTrace=data&&data['stackTrace'];const frame=stackTrace&&stackTrace.length&&stackTrace[0]||TimelineModel.TimelineData.forEvent(event).topFrame();return frame&&frame.url||null;}
static eventStyle(event){const eventStyles=Timeline.TimelineUIUtils._initEventStyles();if(event.hasCategory(TimelineModel.TimelineModel.Category.Console)||event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming))
return{title:event.name,category:Timeline.TimelineUIUtils.categories()['scripting']};if(event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)){const prefix='InputLatency::';const inputEventType=event.name.startsWith(prefix)?event.name.substr(prefix.length):event.name;const displayName=Timeline.TimelineUIUtils.inputEventDisplayName((inputEventType));return{title:displayName||inputEventType,category:Timeline.TimelineUIUtils.categories()['scripting']};}
let result=eventStyles[event.name];if(!result){result=new Timeline.TimelineRecordStyle(event.name,Timeline.TimelineUIUtils.categories()['other'],true);eventStyles[event.name]=result;}
return result;}
static eventColor(event){if(event.name===TimelineModel.TimelineModel.RecordType.JSFrame){const frame=event.args['data'];if(Timeline.TimelineUIUtils.isUserFrame(frame))
return Timeline.TimelineUIUtils.colorForId(frame.url);}
return Timeline.TimelineUIUtils.eventStyle(event).category.color;}
static eventColorByProduct(productRegistry,model,urlToColorCache,event){const url=Timeline.TimelineUIUtils.eventURL(event)||'';let color=urlToColorCache.get(url);if(color)
return color;const defaultColor='#f2ecdc';const parsedURL=url.asParsedURL();if(!parsedURL)
return defaultColor;let name=productRegistry&&productRegistry.nameForUrl(parsedURL);if(!name){name=parsedURL.host;const rootFrames=model.rootFrames();if(rootFrames.some(pageFrame=>new Common.ParsedURL(pageFrame.url).host===name))
color=defaultColor;}
if(!color)
color=name?ProductRegistry.BadgePool.colorForEntryName(name):defaultColor;urlToColorCache.set(url,color);return color;}
static eventTitle(event){const recordType=TimelineModel.TimelineModel.RecordType;const eventData=event.args['data'];if(event.name===recordType.JSFrame)
return Timeline.TimelineUIUtils.frameDisplayName(eventData);const title=Timeline.TimelineUIUtils.eventStyle(event).title;if(event.hasCategory(TimelineModel.TimelineModel.Category.Console))
return title;if(event.name===recordType.TimeStamp)
return ls`${title}: ${eventData['message']}`;if(event.name===recordType.Animation&&eventData&&eventData['name'])
return ls`${title}: ${eventData['name']}`;if(event.name===recordType.EventDispatch&&eventData&&eventData['type'])
return ls`${title}: ${eventData['type']}`;return title;}
static _interactionPhaseStyles(){let map=Timeline.TimelineUIUtils._interactionPhaseStylesMap;if(!map){map=new Map([[TimelineModel.TimelineIRModel.Phases.Idle,{color:'white',label:'Idle'}],[TimelineModel.TimelineIRModel.Phases.Response,{color:'hsl(43, 83%, 64%)',label:ls`Response`}],[TimelineModel.TimelineIRModel.Phases.Scroll,{color:'hsl(256, 67%, 70%)',label:ls`Scroll`}],[TimelineModel.TimelineIRModel.Phases.Fling,{color:'hsl(256, 67%, 70%)',label:ls`Fling`}],[TimelineModel.TimelineIRModel.Phases.Drag,{color:'hsl(256, 67%, 70%)',label:ls`Drag`}],[TimelineModel.TimelineIRModel.Phases.Animation,{color:'hsl(256, 67%, 70%)',label:ls`Animation`}],[TimelineModel.TimelineIRModel.Phases.Uncategorized,{color:'hsl(0, 0%, 87%)',label:ls`Uncategorized`}]]);Timeline.TimelineUIUtils._interactionPhaseStylesMap=map;}
return map;}
static interactionPhaseColor(phase){return Timeline.TimelineUIUtils._interactionPhaseStyles().get(phase).color;}
static interactionPhaseLabel(phase){return Timeline.TimelineUIUtils._interactionPhaseStyles().get(phase).label;}
static isUserFrame(frame){return frame.scriptId!=='0'&&!(frame.url&&frame.url.startsWith('native '));}
static networkRequestCategory(request){const categories=Timeline.TimelineUIUtils.NetworkCategory;switch(request.mimeType){case'text/html':return categories.HTML;case'application/javascript':case'application/x-javascript':case'text/javascript':return categories.Script;case'text/css':return categories.Style;case'audio/ogg':case'image/gif':case'image/jpeg':case'image/png':case'image/svg+xml':case'image/webp':case'image/x-icon':case'font/opentype':case'font/woff2':case'application/font-woff':return categories.Media;default:return categories.Other;}}
static networkCategoryColor(category){const categories=Timeline.TimelineUIUtils.NetworkCategory;switch(category){case categories.HTML:return'hsl(214, 67%, 66%)';case categories.Script:return'hsl(43, 83%, 64%)';case categories.Style:return'hsl(256, 67%, 70%)';case categories.Media:return'hsl(109, 33%, 55%)';default:return'hsl(0, 0%, 70%)';}}
static buildDetailsTextForTraceEvent(event,target){const recordType=TimelineModel.TimelineModel.RecordType;let detailsText;const eventData=event.args['data'];switch(event.name){case recordType.GCEvent:case recordType.MajorGC:case recordType.MinorGC:{const delta=event.args['usedHeapSizeBefore']-event.args['usedHeapSizeAfter'];detailsText=Common.UIString('%s collected',Number.bytesToString(delta));break;}
case recordType.FunctionCall:if(eventData){detailsText=linkifyLocationAsText(eventData['scriptId'],eventData['lineNumber'],eventData['columnNumber']);}
break;case recordType.JSFrame:detailsText=Timeline.TimelineUIUtils.frameDisplayName(eventData);break;case recordType.EventDispatch:detailsText=eventData?eventData['type']:null;break;case recordType.Paint:{const width=Timeline.TimelineUIUtils.quadWidth(eventData.clip);const height=Timeline.TimelineUIUtils.quadHeight(eventData.clip);if(width&&height)
detailsText=Common.UIString('%d\xa0\u00d7\xa0%d',width,height);break;}
case recordType.ParseHTML:{const startLine=event.args['beginData']['startLine'];const endLine=event.args['endData']&&event.args['endData']['endLine'];const url=Bindings.displayNameForURL(event.args['beginData']['url']);if(endLine>=0)
detailsText=Common.UIString('%s [%s\u2026%s]',url,startLine+1,endLine+1);else
detailsText=Common.UIString('%s [%s\u2026]',url,startLine+1);break;}
case recordType.CompileModule:detailsText=Bindings.displayNameForURL(event.args['fileName']);break;case recordType.CompileScript:case recordType.EvaluateScript:{const url=eventData&&eventData['url'];if(url)
detailsText=Bindings.displayNameForURL(url)+':'+(eventData['lineNumber']+1);break;}
case recordType.WasmCompiledModule:case recordType.WasmModuleCacheHit:{const url=event.args['url'];if(url)
detailsText=Bindings.displayNameForURL(url);break;}
case recordType.ParseScriptOnBackground:case recordType.XHRReadyStateChange:case recordType.XHRLoad:{const url=eventData['url'];if(url)
detailsText=Bindings.displayNameForURL(url);break;}
case recordType.TimeStamp:detailsText=eventData['message'];break;case recordType.WebSocketCreate:case recordType.WebSocketSendHandshakeRequest:case recordType.WebSocketReceiveHandshakeResponse:case recordType.WebSocketDestroy:case recordType.ResourceSendRequest:case recordType.ResourceReceivedData:case recordType.ResourceReceiveResponse:case recordType.ResourceFinish:case recordType.PaintImage:case recordType.DecodeImage:case recordType.ResizeImage:case recordType.DecodeLazyPixelRef:{const url=TimelineModel.TimelineData.forEvent(event).url;if(url)
detailsText=Bindings.displayNameForURL(url);break;}
case recordType.EmbedderCallback:detailsText=eventData['callbackName'];break;case recordType.Animation:detailsText=eventData&&eventData['name'];break;case recordType.AsyncTask:detailsText=eventData?eventData['name']:null;break;default:if(event.hasCategory(TimelineModel.TimelineModel.Category.Console))
detailsText=null;else
detailsText=linkifyTopCallFrameAsText();break;}
return detailsText;function linkifyLocationAsText(scriptId,lineNumber,columnNumber){const debuggerModel=target?target.model(SDK.DebuggerModel):null;if(!target||target.isDisposed()||!scriptId||!debuggerModel)
return null;const rawLocation=debuggerModel.createRawLocationByScriptId(scriptId,lineNumber,columnNumber);if(!rawLocation)
return null;const uiLocation=Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(rawLocation);return uiLocation?uiLocation.linkText():null;}
function linkifyTopCallFrameAsText(){const frame=TimelineModel.TimelineData.forEvent(event).topFrame();if(!frame)
return null;let text=linkifyLocationAsText(frame.scriptId,frame.lineNumber,frame.columnNumber);if(!text){text=frame.url;if(typeof frame.lineNumber==='number')
text+=':'+(frame.lineNumber+1);}
return text;}}
static buildDetailsNodeForTraceEvent(event,target,linkifier){const recordType=TimelineModel.TimelineModel.RecordType;let details=null;let detailsText;const eventData=event.args['data'];switch(event.name){case recordType.GCEvent:case recordType.MajorGC:case recordType.MinorGC:case recordType.EventDispatch:case recordType.Paint:case recordType.Animation:case recordType.EmbedderCallback:case recordType.ParseHTML:case recordType.WasmStreamFromResponseCallback:case recordType.WasmCompiledModule:case recordType.WasmModuleCacheHit:case recordType.WasmCachedModule:case recordType.WasmModuleCacheInvalid:case recordType.WebSocketCreate:case recordType.WebSocketSendHandshakeRequest:case recordType.WebSocketReceiveHandshakeResponse:case recordType.WebSocketDestroy:detailsText=Timeline.TimelineUIUtils.buildDetailsTextForTraceEvent(event,target);break;case recordType.PaintImage:case recordType.DecodeImage:case recordType.ResizeImage:case recordType.DecodeLazyPixelRef:case recordType.XHRReadyStateChange:case recordType.XHRLoad:case recordType.ResourceSendRequest:case recordType.ResourceReceivedData:case recordType.ResourceReceiveResponse:case recordType.ResourceFinish:{const url=TimelineModel.TimelineData.forEvent(event).url;if(url)
details=Components.Linkifier.linkifyURL(url);break;}
case recordType.FunctionCall:case recordType.JSFrame:details=createElement('span');details.createTextChild(Timeline.TimelineUIUtils.frameDisplayName(eventData));const location=linkifyLocation(eventData['scriptId'],eventData['url'],eventData['lineNumber'],eventData['columnNumber']);if(location){details.createTextChild(' @ ');details.appendChild(location);}
break;case recordType.CompileModule:details=linkifyLocation('',event.args['fileName'],0,0);break;case recordType.CompileScript:case recordType.EvaluateScript:{const url=eventData['url'];if(url)
details=linkifyLocation('',url,eventData['lineNumber'],0);break;}
case recordType.ParseScriptOnBackground:{const url=eventData['url'];if(url)
details=linkifyLocation('',url,0,0);break;}
default:if(event.hasCategory(TimelineModel.TimelineModel.Category.Console))
detailsText=null;else
details=linkifyTopCallFrame();break;}
if(!details&&detailsText)
details=createTextNode(detailsText);return details;function linkifyLocation(scriptId,url,lineNumber,columnNumber){return linkifier.linkifyScriptLocation(target,scriptId,url,lineNumber,columnNumber,'timeline-details');}
function linkifyTopCallFrame(){const frame=TimelineModel.TimelineData.forEvent(event).topFrame();return frame?linkifier.maybeLinkifyConsoleCallFrame(target,frame,'timeline-details'):null;}}
static async buildTraceEventDetails(event,model,linkifier,badgePool,detailed){const maybeTarget=model.targetByEvent(event);let relatedNodesMap=null;if(maybeTarget){const target=(maybeTarget);if(typeof event[Timeline.TimelineUIUtils._previewElementSymbol]==='undefined'){let previewElement=null;const url=TimelineModel.TimelineData.forEvent(event).url;if(url)
previewElement=await Components.ImagePreview.build(target,url,false);else if(TimelineModel.TimelineData.forEvent(event).picture)
previewElement=await Timeline.TimelineUIUtils.buildPicturePreviewContent(event,target);event[Timeline.TimelineUIUtils._previewElementSymbol]=previewElement;}
const nodeIdsToResolve=new Set();const timelineData=TimelineModel.TimelineData.forEvent(event);if(timelineData.backendNodeId)
nodeIdsToResolve.add(timelineData.backendNodeId);const invalidationTrackingEvents=TimelineModel.InvalidationTracker.invalidationEventsFor(event);if(invalidationTrackingEvents)
Timeline.TimelineUIUtils._collectInvalidationNodeIds(nodeIdsToResolve,invalidationTrackingEvents);if(nodeIdsToResolve.size){const domModel=target.model(SDK.DOMModel);if(domModel)
relatedNodesMap=await domModel.pushNodesByBackendIdsToFrontend(nodeIdsToResolve);}}
const recordTypes=TimelineModel.TimelineModel.RecordType;let relatedNodeLabel;const contentHelper=new Timeline.TimelineDetailsContentHelper(model.targetByEvent(event),linkifier);const color=model.isMarkerEvent(event)?Timeline.TimelineUIUtils.markerStyleForEvent(event).color:Timeline.TimelineUIUtils.eventStyle(event).category.color;contentHelper.addSection(Timeline.TimelineUIUtils.eventTitle(event),color);const eventData=event.args['data'];const timelineData=TimelineModel.TimelineData.forEvent(event);const initiator=timelineData.initiator();let url=null;if(timelineData.warning)
contentHelper.appendWarningRow(event);if(event.name===recordTypes.JSFrame&&eventData['deoptReason'])
contentHelper.appendWarningRow(event,TimelineModel.TimelineModel.WarningType.V8Deopt);if(detailed&&!Number.isNaN(event.duration+0)){contentHelper.appendTextRow(ls`Total Time`,Number.millisToString(event.duration,true));contentHelper.appendTextRow(ls`Self Time`,Number.millisToString(event.selfTime,true));}
if(model.isGenericTrace()){for(const key in event.args){try{contentHelper.appendTextRow(key,JSON.stringify(event.args[key]));}catch(e){contentHelper.appendTextRow(key,`<${typeof event.args[key]}>`);}}
return contentHelper.fragment;}
switch(event.name){case recordTypes.GCEvent:case recordTypes.MajorGC:case recordTypes.MinorGC:const delta=event.args['usedHeapSizeBefore']-event.args['usedHeapSizeAfter'];contentHelper.appendTextRow(ls`Collected`,Number.bytesToString(delta));break;case recordTypes.JSFrame:case recordTypes.FunctionCall:const detailsNode=Timeline.TimelineUIUtils.buildDetailsNodeForTraceEvent(event,model.targetByEvent(event),linkifier);if(detailsNode)
contentHelper.appendElementRow(ls`Function`,detailsNode);break;case recordTypes.TimerFire:case recordTypes.TimerInstall:case recordTypes.TimerRemove:contentHelper.appendTextRow(ls`Timer ID`,eventData['timerId']);if(event.name===recordTypes.TimerInstall){contentHelper.appendTextRow(ls`Timeout`,Number.millisToString(eventData['timeout']));contentHelper.appendTextRow(ls`Repeats`,!eventData['singleShot']);}
break;case recordTypes.FireAnimationFrame:contentHelper.appendTextRow(ls`Callback ID`,eventData['id']);break;case recordTypes.ResourceSendRequest:case recordTypes.ResourceReceiveResponse:case recordTypes.ResourceReceivedData:case recordTypes.ResourceFinish:url=timelineData.url;if(url)
contentHelper.appendElementRow(ls`Resource`,Components.Linkifier.linkifyURL(url));if(eventData['requestMethod'])
contentHelper.appendTextRow(ls`Request Method`,eventData['requestMethod']);if(typeof eventData['statusCode']==='number')
contentHelper.appendTextRow(ls`Status Code`,eventData['statusCode']);if(eventData['mimeType'])
contentHelper.appendTextRow(ls`MIME Type`,eventData['mimeType']);if('priority'in eventData){const priority=PerfUI.uiLabelForNetworkPriority(eventData['priority']);contentHelper.appendTextRow(ls`Priority`,priority);}
if(eventData['encodedDataLength'])
contentHelper.appendTextRow(ls`Encoded Data`,ls`${eventData['encodedDataLength']} Bytes`);if(eventData['decodedBodyLength'])
contentHelper.appendTextRow(ls`Decoded Body`,ls`${eventData['decodedBodyLength']} Bytes`);break;case recordTypes.CompileModule:contentHelper.appendLocationRow(ls`Module`,event.args['fileName'],0);break;case recordTypes.CompileScript:url=eventData&&eventData['url'];if(url)
contentHelper.appendLocationRow(ls`Script`,url,eventData['lineNumber'],eventData['columnNumber']);contentHelper.appendTextRow(ls`Streamed`,eventData['streamed']);const producedCacheSize=eventData&&eventData['producedCacheSize'];if(producedCacheSize)
contentHelper.appendTextRow(ls`Produced Cache Size`,producedCacheSize);const cacheConsumeOptions=eventData&&eventData['cacheConsumeOptions'];if(cacheConsumeOptions){contentHelper.appendTextRow(ls`Cache Consume Options`,cacheConsumeOptions);contentHelper.appendTextRow(ls`Consumed Cache Size`,eventData['consumedCacheSize']);contentHelper.appendTextRow(ls`Cache Rejected`,eventData['cacheRejected']);}
break;case recordTypes.EvaluateScript:url=eventData&&eventData['url'];if(url)
contentHelper.appendLocationRow(ls`Script`,url,eventData['lineNumber'],eventData['columnNumber']);break;case recordTypes.WasmStreamFromResponseCallback:case recordTypes.WasmCompiledModule:case recordTypes.WasmCachedModule:case recordTypes.WasmModuleCacheHit:case recordTypes.WasmModuleCacheInvalid:if(eventData){url=event.args['url'];if(url)
contentHelper.appendTextRow(ls`Url`,url);const producedCachedSize=event.args['producedCachedSize'];if(producedCachedSize)
contentHelper.appendTextRow(ls`Produced Cache Size`,producedCachedSize);const consumedCachedSize=event.args['consumedCachedSize'];if(consumedCachedSize)
contentHelper.appendTextRow(ls`Consumed Cache Size`,consumedCachedSize);}
break;case recordTypes.Paint:const clip=eventData['clip'];contentHelper.appendTextRow(ls`Location`,ls`(${clip[0]}, ${clip[1]})`);const clipWidth=Timeline.TimelineUIUtils.quadWidth(clip);const clipHeight=Timeline.TimelineUIUtils.quadHeight(clip);contentHelper.appendTextRow(ls`Dimensions`,ls`${clipWidth} × ${clipHeight}`);case recordTypes.PaintSetup:case recordTypes.Rasterize:case recordTypes.ScrollLayer:relatedNodeLabel=ls`Layer Root`;break;case recordTypes.PaintImage:case recordTypes.DecodeLazyPixelRef:case recordTypes.DecodeImage:case recordTypes.ResizeImage:case recordTypes.DrawLazyPixelRef:relatedNodeLabel=ls`Owner Element`;url=timelineData.url;if(url)
contentHelper.appendElementRow(ls`Image URL`,Components.Linkifier.linkifyURL(url));break;case recordTypes.ParseAuthorStyleSheet:url=eventData['styleSheetUrl'];if(url)
contentHelper.appendElementRow(ls`Stylesheet URL`,Components.Linkifier.linkifyURL(url));break;case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:contentHelper.appendTextRow(ls`Elements Affected`,event.args['elementCount']);break;case recordTypes.Layout:const beginData=event.args['beginData'];contentHelper.appendTextRow(ls`Nodes That Need Layout`,ls`${beginData['dirtyObjects']} of ${beginData['totalObjects']}`);relatedNodeLabel=ls`Layout root`;break;case recordTypes.ConsoleTime:contentHelper.appendTextRow(ls`Message`,event.name);break;case recordTypes.WebSocketCreate:case recordTypes.WebSocketSendHandshakeRequest:case recordTypes.WebSocketReceiveHandshakeResponse:case recordTypes.WebSocketDestroy:const initiatorData=initiator?initiator.args['data']:eventData;if(typeof initiatorData['webSocketURL']!=='undefined')
contentHelper.appendTextRow(ls`URL`,initiatorData['webSocketURL']);if(typeof initiatorData['webSocketProtocol']!=='undefined')
contentHelper.appendTextRow(ls`WebSocket Protocol`,initiatorData['webSocketProtocol']);if(typeof eventData['message']!=='undefined')
contentHelper.appendTextRow(ls`Message`,eventData['message']);break;case recordTypes.EmbedderCallback:contentHelper.appendTextRow(ls`Callback Function`,eventData['callbackName']);break;case recordTypes.Animation:if(event.phase===SDK.TracingModel.Phase.NestableAsyncInstant)
contentHelper.appendTextRow(ls`State`,eventData['state']);break;case recordTypes.ParseHTML:{const beginData=event.args['beginData'];const startLine=beginData['startLine']-1;const endLine=event.args['endData']?event.args['endData']['endLine']-1:undefined;url=beginData['url'];if(url)
contentHelper.appendLocationRange(ls`Range`,url,startLine,endLine);break;}
case recordTypes.FireIdleCallback:contentHelper.appendTextRow(ls`Allotted Time`,Number.millisToString(eventData['allottedMilliseconds']));contentHelper.appendTextRow(ls`Invoked by Timeout`,eventData['timedOut']);case recordTypes.RequestIdleCallback:case recordTypes.CancelIdleCallback:contentHelper.appendTextRow(ls`Callback ID`,eventData['id']);break;case recordTypes.EventDispatch:contentHelper.appendTextRow(ls`Type`,eventData['type']);break;case recordTypes.MarkFirstPaint:case recordTypes.MarkFCP:case recordTypes.MarkFMP:case recordTypes.MarkLoad:case recordTypes.MarkDOMContent:contentHelper.appendTextRow(ls`Timestamp`,Number.preciseMillisToString(event.startTime-model.minimumRecordTime(),1));const learnMoreLink=UI.XLink.create('https://developers.google.com/web/fundamentals/performance/user-centric-performance-metrics#user-centric_performance_metrics',ls`Learn more`);const linkDiv=UI.html`<div>${learnMoreLink} about page performance metrics.</div>`;contentHelper.appendElementRow(ls`Details`,linkDiv);break;default:{const detailsNode=Timeline.TimelineUIUtils.buildDetailsNodeForTraceEvent(event,model.targetByEvent(event),linkifier);if(detailsNode)
contentHelper.appendElementRow(ls`Details`,detailsNode);break;}}
Timeline.TimelineUIUtils._maybeAppendProductToDetails(contentHelper,badgePool,url||eventData&&eventData['url']);if(timelineData.timeWaitingForMainThread){contentHelper.appendTextRow(ls`Time Waiting for Main Thread`,Number.millisToString(timelineData.timeWaitingForMainThread,true));}
const relatedNode=relatedNodesMap&&relatedNodesMap.get(timelineData.backendNodeId);if(relatedNode){const nodeSpan=await Common.Linkifier.linkify(relatedNode);contentHelper.appendElementRow(relatedNodeLabel||ls`Related Node`,nodeSpan);}
if(event[Timeline.TimelineUIUtils._previewElementSymbol]){contentHelper.addSection(ls`Preview`);contentHelper.appendElementRow('',event[Timeline.TimelineUIUtils._previewElementSymbol]);}
if(initiator||timelineData.stackTraceForSelfOrInitiator()||TimelineModel.InvalidationTracker.invalidationEventsFor(event))
Timeline.TimelineUIUtils._generateCauses(event,model.targetByEvent(event),relatedNodesMap,contentHelper);const stats={};const showPieChart=detailed&&Timeline.TimelineUIUtils._aggregatedStatsForTraceEvent(stats,model,event);if(showPieChart){contentHelper.addSection(ls`Aggregated Time`);const pieChart=Timeline.TimelineUIUtils.generatePieChart(stats,Timeline.TimelineUIUtils.eventStyle(event).category,event.selfTime);contentHelper.appendElementRow('',pieChart);}
return contentHelper.fragment;}
static _maybeAppendProductToDetails(contentHelper,badgePool,url){const parsedURL=url?url.asParsedURL():null;if(parsedURL)
contentHelper.appendElementRow('',badgePool.badgeForURL(parsedURL));}
static statsForTimeRange(events,startTime,endTime){if(!events.length)
return{'idle':endTime-startTime};buildRangeStatsCacheIfNeeded(events);const aggregatedStats=subtractStats(aggregatedStatsAtTime(endTime),aggregatedStatsAtTime(startTime));const aggregatedTotal=Object.values(aggregatedStats).reduce((a,b)=>a+b,0);aggregatedStats['idle']=Math.max(0,endTime-startTime-aggregatedTotal);return aggregatedStats;function aggregatedStatsAtTime(time){const stats={};const cache=events[Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol];for(const category in cache){const categoryCache=cache[category];const index=categoryCache.time.upperBound(time);let value;if(index===0){value=0;}else if(index===categoryCache.time.length){value=categoryCache.value.peekLast();}else{const t0=categoryCache.time[index-1];const t1=categoryCache.time[index];const v0=categoryCache.value[index-1];const v1=categoryCache.value[index];value=v0+(v1-v0)*(time-t0)/(t1-t0);}
stats[category]=value;}
return stats;}
function subtractStats(a,b){const result=Object.assign({},a);for(const key in b)
result[key]-=b[key];return result;}
function buildRangeStatsCacheIfNeeded(events){if(events[Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol])
return;const aggregatedStats={};const categoryStack=[];let lastTime=0;TimelineModel.TimelineModel.forEachEvent(events,onStartEvent,onEndEvent,undefined,undefined,undefined,filterForStats());function filterForStats(){const visibleEventsFilter=Timeline.TimelineUIUtils.visibleEventsFilter();return event=>visibleEventsFilter.accept(event)||SDK.TracingModel.isTopLevelEvent(event);}
function updateCategory(category,time){let statsArrays=aggregatedStats[category];if(!statsArrays){statsArrays={time:[],value:[]};aggregatedStats[category]=statsArrays;}
if(statsArrays.time.length&&statsArrays.time.peekLast()===time)
return;const lastValue=statsArrays.value.length?statsArrays.value.peekLast():0;statsArrays.value.push(lastValue+time-lastTime);statsArrays.time.push(time);}
function categoryChange(from,to,time){if(from)
updateCategory(from,time);lastTime=time;if(to)
updateCategory(to,time);}
function onStartEvent(e){const category=Timeline.TimelineUIUtils.eventStyle(e).category.name;const parentCategory=categoryStack.length?categoryStack.peekLast():null;if(category!==parentCategory)
categoryChange(parentCategory,category,e.startTime);categoryStack.push(category);}
function onEndEvent(e){const category=categoryStack.pop();const parentCategory=categoryStack.length?categoryStack.peekLast():null;if(category!==parentCategory)
categoryChange(category,parentCategory,e.endTime);}
const obj=(events);obj[Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol]=aggregatedStats;}}
static async buildNetworkRequestDetails(request,model,linkifier,badgePool){const target=model.targetByEvent(request.children[0]);const contentHelper=new Timeline.TimelineDetailsContentHelper(target,linkifier);const category=Timeline.TimelineUIUtils.networkRequestCategory(request);const color=Timeline.TimelineUIUtils.networkCategoryColor(category);contentHelper.addSection(ls`Network request`,color);const duration=request.endTime-(request.startTime||-Infinity);if(request.url)
contentHelper.appendElementRow(ls`URL`,Components.Linkifier.linkifyURL(request.url));Timeline.TimelineUIUtils._maybeAppendProductToDetails(contentHelper,badgePool,request.url);if(isFinite(duration))
contentHelper.appendTextRow(ls`Duration`,Number.millisToString(duration,true));if(request.requestMethod)
contentHelper.appendTextRow(ls`Request Method`,request.requestMethod);if(typeof request.priority==='string'){const priority=PerfUI.uiLabelForNetworkPriority((request.priority));contentHelper.appendTextRow(ls`Priority`,priority);}
if(request.mimeType)
contentHelper.appendTextRow(ls`Mime Type`,request.mimeType);let lengthText='';if(request.fromCache)
lengthText+=ls` (from cache)`;if(request.fromServiceWorker)
lengthText+=ls` (from service worker)`;if(request.encodedDataLength||!lengthText)
lengthText=`${Number.bytesToString(request.encodedDataLength)}${lengthText}`;contentHelper.appendTextRow(ls`Encoded Data`,lengthText);if(request.decodedBodyLength)
contentHelper.appendTextRow(ls`Decoded Body`,Number.bytesToString(request.decodedBodyLength));const title=ls`Initiator`;const sendRequest=request.children[0];const topFrame=TimelineModel.TimelineData.forEvent(sendRequest).topFrame();if(topFrame){const link=linkifier.maybeLinkifyConsoleCallFrame(target,topFrame);if(link)
contentHelper.appendElementRow(title,link);}else{const initiator=TimelineModel.TimelineData.forEvent(sendRequest).initiator();if(initiator){const initiatorURL=TimelineModel.TimelineData.forEvent(initiator).url;if(initiatorURL){const link=linkifier.maybeLinkifyScriptLocation(target,null,initiatorURL,0);if(link)
contentHelper.appendElementRow(title,link);}}}
if(!request.previewElement&&request.url&&target)
request.previewElement=await Components.ImagePreview.build(target,request.url,false);if(request.previewElement)
contentHelper.appendElementRow(ls`Preview`,request.previewElement);return contentHelper.fragment;}
static _stackTraceFromCallFrames(callFrames){return({callFrames:callFrames});}
static _generateCauses(event,target,relatedNodesMap,contentHelper){const recordTypes=TimelineModel.TimelineModel.RecordType;let callSiteStackLabel;let stackLabel;switch(event.name){case recordTypes.TimerFire:callSiteStackLabel=ls`Timer Installed`;break;case recordTypes.FireAnimationFrame:callSiteStackLabel=ls`Animation Frame Requested`;break;case recordTypes.FireIdleCallback:callSiteStackLabel=ls`Idle Callback Requested`;break;case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:stackLabel=ls`Recalculation Forced`;break;case recordTypes.Layout:callSiteStackLabel=ls`First Layout Invalidation`;stackLabel=ls`Layout Forced`;break;}
const timelineData=TimelineModel.TimelineData.forEvent(event);if(timelineData.stackTrace&&timelineData.stackTrace.length){contentHelper.addSection(ls`Call Stacks`);contentHelper.appendStackTrace(stackLabel||ls`Stack Trace`,Timeline.TimelineUIUtils._stackTraceFromCallFrames(timelineData.stackTrace));}
const initiator=TimelineModel.TimelineData.forEvent(event).initiator();if(TimelineModel.InvalidationTracker.invalidationEventsFor(event)&&target){contentHelper.addSection(ls`Invalidations`);Timeline.TimelineUIUtils._generateInvalidations(event,target,relatedNodesMap,contentHelper);}else if(initiator){const delay=event.startTime-initiator.startTime;contentHelper.appendTextRow(ls`Pending for`,Number.preciseMillisToString(delay,1));const link=createElementWithClass('span','devtools-link');link.textContent=ls`Reveal`;link.addEventListener('click',()=>{Timeline.TimelinePanel.instance().select(Timeline.TimelineSelection.fromTraceEvent((initiator)));});contentHelper.appendElementRow(ls`Initiator`,link);const initiatorStackTrace=TimelineModel.TimelineData.forEvent(initiator).stackTrace;if(initiatorStackTrace){contentHelper.appendStackTrace(callSiteStackLabel||ls`First Invalidated`,Timeline.TimelineUIUtils._stackTraceFromCallFrames(initiatorStackTrace));}}}
static _generateInvalidations(event,target,relatedNodesMap,contentHelper){const invalidationTrackingEvents=TimelineModel.InvalidationTracker.invalidationEventsFor(event);const invalidations={};invalidationTrackingEvents.forEach(function(invalidation){if(!invalidations[invalidation.type])
invalidations[invalidation.type]=[invalidation];else
invalidations[invalidation.type].push(invalidation);});Object.keys(invalidations).forEach(function(type){Timeline.TimelineUIUtils._generateInvalidationsForType(type,target,invalidations[type],relatedNodesMap,contentHelper);});}
static _generateInvalidationsForType(type,target,invalidations,relatedNodesMap,contentHelper){let title;switch(type){case TimelineModel.TimelineModel.RecordType.StyleRecalcInvalidationTracking:title=ls`Style Invalidations`;break;case TimelineModel.TimelineModel.RecordType.LayoutInvalidationTracking:title=ls`Layout Invalidations`;break;default:title=ls`Other Invalidations`;break;}
const invalidationsTreeOutline=new UI.TreeOutlineInShadow();invalidationsTreeOutline.registerRequiredCSS('timeline/invalidationsTree.css');invalidationsTreeOutline.element.classList.add('invalidations-tree');const invalidationGroups=groupInvalidationsByCause(invalidations);invalidationGroups.forEach(function(group){const groupElement=new Timeline.TimelineUIUtils.InvalidationsGroupElement(target,relatedNodesMap,contentHelper,group);invalidationsTreeOutline.appendChild(groupElement);});contentHelper.appendElementRow(title,invalidationsTreeOutline.element,false,true);function groupInvalidationsByCause(invalidations){const causeToInvalidationMap=new Map();for(let index=0;index<invalidations.length;index++){const invalidation=invalidations[index];let causeKey='';if(invalidation.cause.reason)
causeKey+=invalidation.cause.reason+'.';if(invalidation.cause.stackTrace){invalidation.cause.stackTrace.forEach(function(stackFrame){causeKey+=stackFrame['functionName']+'.';causeKey+=stackFrame['scriptId']+'.';causeKey+=stackFrame['url']+'.';causeKey+=stackFrame['lineNumber']+'.';causeKey+=stackFrame['columnNumber']+'.';});}
if(causeToInvalidationMap.has(causeKey))
causeToInvalidationMap.get(causeKey).push(invalidation);else
causeToInvalidationMap.set(causeKey,[invalidation]);}
return causeToInvalidationMap.valuesArray();}}
static _collectInvalidationNodeIds(nodeIds,invalidations){nodeIds.addAll(invalidations.map(invalidation=>invalidation.nodeId).filter(id=>id));}
static _aggregatedStatsForTraceEvent(total,model,event){const events=model.inspectedTargetEvents();function eventComparator(startTime,e){return startTime-e.startTime;}
const index=events.binaryIndexOf(event.startTime,eventComparator);if(index<0)
return false;let hasChildren=false;const endTime=event.endTime;if(endTime){for(let i=index;i<events.length;i++){const nextEvent=events[i];if(nextEvent.startTime>=endTime)
break;if(!nextEvent.selfTime)
continue;if(nextEvent.thread!==event.thread)
continue;if(i>index)
hasChildren=true;const categoryName=Timeline.TimelineUIUtils.eventStyle(nextEvent).category.name;total[categoryName]=(total[categoryName]||0)+nextEvent.selfTime;}}
if(SDK.TracingModel.isAsyncPhase(event.phase)){if(event.endTime){let aggregatedTotal=0;for(const categoryName in total)
aggregatedTotal+=total[categoryName];total['idle']=Math.max(0,event.endTime-event.startTime-aggregatedTotal);}
return false;}
return hasChildren;}
static async buildPicturePreviewContent(event,target){const snapshotWithRect=await new TimelineModel.LayerPaintEvent(event,target).snapshotPromise();if(!snapshotWithRect)
return null;const imageURLPromise=snapshotWithRect.snapshot.replay();snapshotWithRect.snapshot.release();const imageURL=await imageURLPromise;if(!imageURL)
return null;const container=createElement('div');UI.appendStyle(container,'components/imagePreview.css');container.classList.add('image-preview-container','vbox','link');const img=container.createChild('img');img.src=imageURL;const paintProfilerButton=container.createChild('a');paintProfilerButton.textContent=ls`Paint Profiler`;container.addEventListener('click',()=>Timeline.TimelinePanel.instance().select(Timeline.TimelineSelection.fromTraceEvent(event)),false);return container;}
static createEventDivider(event,zeroTime){const eventDivider=createElementWithClass('div','resources-event-divider');const startTime=Number.millisToString(event.startTime-zeroTime);eventDivider.title=Common.UIString('%s at %s',Timeline.TimelineUIUtils.eventTitle(event),startTime);const style=Timeline.TimelineUIUtils.markerStyleForEvent(event);if(style.tall)
eventDivider.style.backgroundColor=style.color;return eventDivider;}
static _visibleTypes(){const eventStyles=Timeline.TimelineUIUtils._initEventStyles();const result=[];for(const name in eventStyles){if(!eventStyles[name].hidden)
result.push(name);}
return result;}
static visibleEventsFilter(){return new TimelineModel.TimelineVisibleEventsFilter(Timeline.TimelineUIUtils._visibleTypes());}
static categories(){if(Timeline.TimelineUIUtils._categories)
return Timeline.TimelineUIUtils._categories;Timeline.TimelineUIUtils._categories={loading:new Timeline.TimelineCategory('loading',ls`Loading`,true,'hsl(214, 67%, 74%)','hsl(214, 67%, 66%)'),scripting:new Timeline.TimelineCategory('scripting',ls`Scripting`,true,'hsl(43, 83%, 72%)','hsl(43, 83%, 64%) '),rendering:new Timeline.TimelineCategory('rendering',ls`Rendering`,true,'hsl(256, 67%, 76%)','hsl(256, 67%, 70%)'),painting:new Timeline.TimelineCategory('painting',ls`Painting`,true,'hsl(109, 33%, 64%)','hsl(109, 33%, 55%)'),gpu:new Timeline.TimelineCategory('gpu',ls`GPU`,false,'hsl(109, 33%, 64%)','hsl(109, 33%, 55%)'),async:new Timeline.TimelineCategory('async',ls`Async`,false,'hsl(0, 100%, 50%)','hsl(0, 100%, 40%)'),other:new Timeline.TimelineCategory('other',ls`System`,false,'hsl(0, 0%, 87%)','hsl(0, 0%, 79%)'),idle:new Timeline.TimelineCategory('idle',ls`Idle`,false,'hsl(0, 0%, 98%)','hsl(0, 0%, 98%)')};return Timeline.TimelineUIUtils._categories;}
static generatePieChart(aggregatedStats,selfCategory,selfTime){let total=0;for(const categoryName in aggregatedStats)
total+=aggregatedStats[categoryName];const element=createElementWithClass('div','timeline-details-view-pie-chart-wrapper hbox');const pieChart=new PerfUI.PieChart({chartName:ls`Time spent in rendering`,size:110,formatter:value=>Number.preciseMillisToString(value),showLegend:true,});pieChart.element.classList.add('timeline-details-view-pie-chart');pieChart.setTotal(total);const pieChartContainer=element.createChild('div','vbox');pieChartContainer.appendChild(pieChart.element);function appendLegendRow(name,title,value,color){if(!value)
return;pieChart.addSlice(value,color,title);}
if(selfCategory){if(selfTime){appendLegendRow(selfCategory.name,Common.UIString('%s (self)',selfCategory.title),selfTime,selfCategory.color);}
const categoryTime=aggregatedStats[selfCategory.name];const value=categoryTime-selfTime;if(value>0){appendLegendRow(selfCategory.name,Common.UIString('%s (children)',selfCategory.title),value,selfCategory.childColor);}}
for(const categoryName in Timeline.TimelineUIUtils.categories()){const category=Timeline.TimelineUIUtils.categories()[categoryName];if(category===selfCategory)
continue;appendLegendRow(category.name,category.title,aggregatedStats[category.name],category.childColor);}
return element;}
static generateDetailsContentForFrame(frame,filmStripFrame){const contentHelper=new Timeline.TimelineDetailsContentHelper(null,null);contentHelper.addSection(ls`Frame`);const duration=Timeline.TimelineUIUtils.frameDuration(frame);contentHelper.appendElementRow(ls`Duration`,duration,frame.hasWarnings());const durationInMillis=frame.endTime-frame.startTime;contentHelper.appendTextRow(ls`FPS`,Math.floor(1000/durationInMillis));contentHelper.appendTextRow(ls`CPU time`,Number.millisToString(frame.cpuTime,true));if(filmStripFrame){const filmStripPreview=createElementWithClass('div','timeline-filmstrip-preview');filmStripFrame.imageDataPromise().then(data=>UI.loadImageFromData(data)).then(image=>image&&filmStripPreview.appendChild(image));contentHelper.appendElementRow('',filmStripPreview);filmStripPreview.addEventListener('click',frameClicked.bind(null,filmStripFrame),false);}
if(frame.layerTree)
contentHelper.appendElementRow(ls`Layer tree`,Components.Linkifier.linkifyRevealable(frame.layerTree,ls`Show`));function frameClicked(filmStripFrame){new PerfUI.FilmStripView.Dialog(filmStripFrame,0);}
return contentHelper.fragment;}
static frameDuration(frame){const durationText=Common.UIString('%s (at %s)',Number.millisToString(frame.endTime-frame.startTime,true),Number.millisToString(frame.startTimeOffset,true));const element=createElement('span');element.createTextChild(durationText);if(!frame.hasWarnings())
return element;element.createTextChild(Common.UIString('. Long frame times are an indication of '));element.appendChild(UI.XLink.create('https://developers.google.com/web/fundamentals/performance/rendering/',Common.UIString('jank')));element.createTextChild('.');return element;}
static createFillStyle(context,width,height,color0,color1,color2){const gradient=context.createLinearGradient(0,0,width,height);gradient.addColorStop(0,color0);gradient.addColorStop(0.25,color1);gradient.addColorStop(0.75,color1);gradient.addColorStop(1,color2);return gradient;}
static quadWidth(quad){return Math.round(Math.sqrt(Math.pow(quad[0]-quad[2],2)+Math.pow(quad[1]-quad[3],2)));}
static quadHeight(quad){return Math.round(Math.sqrt(Math.pow(quad[0]-quad[6],2)+Math.pow(quad[1]-quad[7],2)));}
static eventDispatchDesciptors(){if(Timeline.TimelineUIUtils._eventDispatchDesciptors)
return Timeline.TimelineUIUtils._eventDispatchDesciptors;const lightOrange='hsl(40,100%,80%)';const orange='hsl(40,100%,50%)';const green='hsl(90,100%,40%)';const purple='hsl(256,100%,75%)';Timeline.TimelineUIUtils._eventDispatchDesciptors=[new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(1,lightOrange,['mousemove','mouseenter','mouseleave','mouseout','mouseover']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(1,lightOrange,['pointerover','pointerout','pointerenter','pointerleave','pointermove']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(2,green,['wheel']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(3,orange,['click','mousedown','mouseup']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(3,orange,['touchstart','touchend','touchmove','touchcancel']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(3,orange,['pointerdown','pointerup','pointercancel','gotpointercapture','lostpointercapture']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(3,purple,['keydown','keyup','keypress'])];return Timeline.TimelineUIUtils._eventDispatchDesciptors;}
static markerShortTitle(event){const recordTypes=TimelineModel.TimelineModel.RecordType;switch(event.name){case recordTypes.MarkDOMContent:return ls`DCL`;case recordTypes.MarkLoad:return ls`L`;case recordTypes.MarkFirstPaint:return ls`FP`;case recordTypes.MarkFCP:return ls`FCP`;case recordTypes.MarkFMP:return ls`FMP`;}
return null;}
static markerStyleForEvent(event){const tallMarkerDashStyle=[6,4];const title=Timeline.TimelineUIUtils.eventTitle(event);if(event.hasCategory(TimelineModel.TimelineModel.Category.Console)||event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)){return{title:title,dashStyle:tallMarkerDashStyle,lineWidth:0.5,color:event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)?'purple':'orange',tall:false,lowPriority:false,};}
const recordTypes=TimelineModel.TimelineModel.RecordType;let tall=false;let color='grey';switch(event.name){case recordTypes.FrameStartedLoading:color='green';tall=true;break;case recordTypes.MarkDOMContent:color='#0867CB';tall=true;break;case recordTypes.MarkLoad:color='#B31412';tall=true;break;case recordTypes.MarkFirstPaint:color='#228847';tall=true;break;case recordTypes.MarkFCP:color='#1A6937';tall=true;break;case recordTypes.MarkFMP:color='#134A26';tall=true;break;case recordTypes.TimeStamp:color='orange';break;}
return{title:title,dashStyle:tallMarkerDashStyle,lineWidth:0.5,color:color,tall:tall,lowPriority:false,};}
static markerStyleForFrame(){return{title:ls`Frame`,color:'rgba(100, 100, 100, 0.4)',lineWidth:3,dashStyle:[3],tall:true,lowPriority:true};}
static colorForId(id){if(!Timeline.TimelineUIUtils.colorForId._colorGenerator){Timeline.TimelineUIUtils.colorForId._colorGenerator=new Common.Color.Generator({min:30,max:330},{min:50,max:80,count:3},85);Timeline.TimelineUIUtils.colorForId._colorGenerator.setColorForID('','#f2ecdc');}
return Timeline.TimelineUIUtils.colorForId._colorGenerator.colorForID(id);}
static eventWarning(event,warningType){const timelineData=TimelineModel.TimelineData.forEvent(event);const warning=warningType||timelineData.warning;if(!warning)
return null;const warnings=TimelineModel.TimelineModel.WarningType;const span=createElement('span');const eventData=event.args['data'];switch(warning){case warnings.ForcedStyle:case warnings.ForcedLayout:span.appendChild(UI.createDocumentationLink('../../fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts',Common.UIString('Forced reflow')));span.createTextChild(Common.UIString(' is a likely performance bottleneck.'));break;case warnings.IdleDeadlineExceeded:const exceededMs=Number.millisToString(event.duration-eventData['allottedMilliseconds'],true);span.textContent=ls`Idle callback execution extended beyond deadline by ${exceededMs}`;break;case warnings.LongHandler:span.textContent=Common.UIString('Handler took %s',Number.millisToString(event.duration,true));break;case warnings.LongRecurringHandler:span.textContent=Common.UIString('Recurring handler took %s',Number.millisToString(event.duration,true));break;case warnings.LongTask:span.appendChild(UI.createDocumentationLink('../../fundamentals/performance/rail#goals-and-guidelines',ls`Long task`));span.createTextChild(ls` took ${Number.millisToString(event.duration, true)}.`);break;case warnings.V8Deopt:span.appendChild(UI.XLink.create('https://github.com/GoogleChrome/devtools-docs/issues/53',Common.UIString('Not optimized')));span.createTextChild(Common.UIString(': %s',eventData['deoptReason']));break;default:console.assert(false,'Unhandled TimelineModel.WarningType');}
return span;}
static displayNameForFrame(frame,trimAt){const url=frame.url;if(!trimAt)
trimAt=30;return url.startsWith('about:')?`"${frame.name.trimMiddle(trimAt)}"`:frame.url.trimEnd(trimAt);}};Timeline.TimelineRecordStyle=class{constructor(title,category,hidden){this.title=title;this.category=category;this.hidden=!!hidden;}};Timeline.TimelineUIUtils.NetworkCategory={HTML:Symbol('HTML'),Script:Symbol('Script'),Style:Symbol('Style'),Media:Symbol('Media'),Other:Symbol('Other')};Timeline.TimelineUIUtils._aggregatedStatsKey=Symbol('aggregatedStats');Timeline.TimelineUIUtils.InvalidationsGroupElement=class extends UI.TreeElement{constructor(target,relatedNodesMap,contentHelper,invalidations){super('',true);this.listItemElement.classList.add('header');this.selectable=false;this.toggleOnClick=true;this._relatedNodesMap=relatedNodesMap;this._contentHelper=contentHelper;this._invalidations=invalidations;this.title=this._createTitle(target);}
_createTitle(target){const first=this._invalidations[0];const reason=first.cause.reason;const topFrame=first.cause.stackTrace&&first.cause.stackTrace[0];const title=createElement('span');if(reason)
title.createTextChild(Common.UIString('%s for ',reason));else
title.createTextChild(Common.UIString('Unknown cause for '));this._appendTruncatedNodeList(title,this._invalidations);if(topFrame&&this._contentHelper.linkifier()){title.createTextChild(Common.UIString('. '));const stack=title.createChild('span','monospace');stack.createChild('span').textContent=Timeline.TimelineUIUtils.frameDisplayName(topFrame);const link=this._contentHelper.linkifier().maybeLinkifyConsoleCallFrame(target,topFrame);if(link){stack.createChild('span').textContent=' @ ';stack.createChild('span').appendChild(link);}}
return title;}
onpopulate(){const content=createElementWithClass('div','content');const first=this._invalidations[0];if(first.cause.stackTrace){const stack=content.createChild('div');stack.createTextChild(ls`Stack trace:`);this._contentHelper.createChildStackTraceElement(stack,Timeline.TimelineUIUtils._stackTraceFromCallFrames(first.cause.stackTrace));}
content.createTextChild(this._invalidations.length!==1?ls`Nodes:`:ls`Node:`);const nodeList=content.createChild('div','node-list');let firstNode=true;for(let i=0;i<this._invalidations.length;i++){const invalidation=this._invalidations[i];const invalidationNode=this._createInvalidationNode(invalidation,true);if(invalidationNode){if(!firstNode)
nodeList.createTextChild(ls`, `);firstNode=false;nodeList.appendChild(invalidationNode);const extraData=invalidation.extraData?', '+invalidation.extraData:'';if(invalidation.changedId){nodeList.createTextChild(Common.UIString('(changed id to "%s"%s)',invalidation.changedId,extraData));}else if(invalidation.changedClass){nodeList.createTextChild(Common.UIString('(changed class to "%s"%s)',invalidation.changedClass,extraData));}else if(invalidation.changedAttribute){nodeList.createTextChild(Common.UIString('(changed attribute to "%s"%s)',invalidation.changedAttribute,extraData));}else if(invalidation.changedPseudo){nodeList.createTextChild(Common.UIString('(changed pesudo to "%s"%s)',invalidation.changedPseudo,extraData));}else if(invalidation.selectorPart){nodeList.createTextChild(Common.UIString('(changed "%s"%s)',invalidation.selectorPart,extraData));}}}
const contentTreeElement=new UI.TreeElement(content,false);contentTreeElement.selectable=false;this.appendChild(contentTreeElement);}
_appendTruncatedNodeList(parentElement,invalidations){const invalidationNodes=[];const invalidationNodeIdMap={};for(let i=0;i<invalidations.length;i++){const invalidation=invalidations[i];const invalidationNode=this._createInvalidationNode(invalidation,false);invalidationNode.addEventListener('click',e=>e.consume(),false);if(invalidationNode&&!invalidationNodeIdMap[invalidation.nodeId]){invalidationNodes.push(invalidationNode);invalidationNodeIdMap[invalidation.nodeId]=true;}}
if(invalidationNodes.length===1){parentElement.appendChild(invalidationNodes[0]);}else if(invalidationNodes.length===2){parentElement.appendChild(invalidationNodes[0]);parentElement.createTextChild(Common.UIString(' and '));parentElement.appendChild(invalidationNodes[1]);}else if(invalidationNodes.length>=3){parentElement.appendChild(invalidationNodes[0]);parentElement.createTextChild(Common.UIString(', '));parentElement.appendChild(invalidationNodes[1]);parentElement.createTextChild(Common.UIString(', and %s others',invalidationNodes.length-2));}}
_createInvalidationNode(invalidation,showUnknownNodes){const node=(invalidation.nodeId&&this._relatedNodesMap)?this._relatedNodesMap.get(invalidation.nodeId):null;if(node){const nodeSpan=createElement('span');Common.Linkifier.linkify(node).then(link=>nodeSpan.appendChild(link));return nodeSpan;}
if(invalidation.nodeName){const nodeSpan=createElement('span');nodeSpan.textContent=Common.UIString('[ %s ]',invalidation.nodeName);return nodeSpan;}
if(showUnknownNodes){const nodeSpan=createElement('span');return nodeSpan.createTextChild(Common.UIString('[ unknown node ]'));}}};Timeline.TimelineUIUtils._previewElementSymbol=Symbol('previewElement');Timeline.TimelineUIUtils.EventDispatchTypeDescriptor=class{constructor(priority,color,eventTypes){this.priority=priority;this.color=color;this.eventTypes=eventTypes;}};Timeline.TimelineCategory=class extends Common.Object{constructor(name,title,visible,childColor,color){super();this.name=name;this.title=title;this.visible=visible;this.childColor=childColor;this.color=color;this.hidden=false;}
get hidden(){return this._hidden;}
set hidden(hidden){this._hidden=hidden;this.dispatchEventToListeners(Timeline.TimelineCategory.Events.VisibilityChanged,this);}};Timeline.TimelineCategory.Events={VisibilityChanged:Symbol('VisibilityChanged')};Timeline.TimelineMarkerStyle;Timeline.TimelinePopupContentHelper=class{constructor(title){this._contentTable=createElement('table');const titleCell=this._createCell(Common.UIString('%s - Details',title),'timeline-details-title');titleCell.colSpan=2;const titleRow=createElement('tr');titleRow.appendChild(titleCell);this._contentTable.appendChild(titleRow);}
contentTable(){return this._contentTable;}
_createCell(content,styleName){const text=createElement('label');text.createTextChild(String(content));const cell=createElement('td');cell.className='timeline-details';if(styleName)
cell.className+=' '+styleName;cell.textContent=content;return cell;}
appendTextRow(title,content){const row=createElement('tr');row.appendChild(this._createCell(title,'timeline-details-row-title'));row.appendChild(this._createCell(content,'timeline-details-row-data'));this._contentTable.appendChild(row);}
appendElementRow(title,content){const row=createElement('tr');const titleCell=this._createCell(title,'timeline-details-row-title');row.appendChild(titleCell);const cell=createElement('td');cell.className='details';if(content instanceof Node)
cell.appendChild(content);else
cell.createTextChild(content||'');row.appendChild(cell);this._contentTable.appendChild(row);}};Timeline.TimelineDetailsContentHelper=class{constructor(target,linkifier){this.fragment=createDocumentFragment();this._linkifier=linkifier;this._target=target;this.element=createElementWithClass('div','timeline-details-view-block');this._tableElement=this.element.createChild('div','vbox timeline-details-chip-body');this.fragment.appendChild(this.element);}
addSection(title,swatchColor){if(!this._tableElement.hasChildNodes()){this.element.removeChildren();}else{this.element=createElementWithClass('div','timeline-details-view-block');this.fragment.appendChild(this.element);}
if(title){const titleElement=this.element.createChild('div','timeline-details-chip-title');if(swatchColor)
titleElement.createChild('div').style.backgroundColor=swatchColor;titleElement.createTextChild(title);}
this._tableElement=this.element.createChild('div','vbox timeline-details-chip-body');this.fragment.appendChild(this.element);}
linkifier(){return this._linkifier;}
appendTextRow(title,value){const rowElement=this._tableElement.createChild('div','timeline-details-view-row');rowElement.createChild('div','timeline-details-view-row-title').textContent=title;rowElement.createChild('div','timeline-details-view-row-value').textContent=value;}
appendElementRow(title,content,isWarning,isStacked){const rowElement=this._tableElement.createChild('div','timeline-details-view-row');if(isWarning)
rowElement.classList.add('timeline-details-warning');if(isStacked)
rowElement.classList.add('timeline-details-stack-values');const titleElement=rowElement.createChild('div','timeline-details-view-row-title');titleElement.textContent=title;const valueElement=rowElement.createChild('div','timeline-details-view-row-value');if(content instanceof Node)
valueElement.appendChild(content);else
valueElement.createTextChild(content||'');}
appendLocationRow(title,url,startLine,startColumn){if(!this._linkifier||!this._target)
return;const link=this._linkifier.maybeLinkifyScriptLocation(this._target,null,url,startLine,startColumn);if(!link)
return;this.appendElementRow(title,link);}
appendLocationRange(title,url,startLine,endLine){if(!this._linkifier||!this._target)
return;const locationContent=createElement('span');const link=this._linkifier.maybeLinkifyScriptLocation(this._target,null,url,startLine);if(!link)
return;locationContent.appendChild(link);locationContent.createTextChild(String.sprintf(' [%s\u2026%s]',startLine+1,endLine+1||''));this.appendElementRow(title,locationContent);}
appendStackTrace(title,stackTrace){if(!this._linkifier||!this._target)
return;const rowElement=this._tableElement.createChild('div','timeline-details-view-row');rowElement.createChild('div','timeline-details-view-row-title').textContent=title;this.createChildStackTraceElement(rowElement,stackTrace);}
createChildStackTraceElement(parentElement,stackTrace){if(!this._linkifier||!this._target)
return;parentElement.classList.add('timeline-details-stack-values');const stackTraceElement=parentElement.createChild('div','timeline-details-view-row-value timeline-details-view-row-stack-trace');const callFrameContents=Components.JSPresentationUtils.buildStackTracePreviewContents(this._target,this._linkifier,stackTrace);stackTraceElement.appendChild(callFrameContents.element);}
appendWarningRow(event,warningType){const warning=Timeline.TimelineUIUtils.eventWarning(event,warningType);if(warning)
this.appendElementRow(ls`Warning`,warning,true);}};Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol=Symbol('categoryBreakdownCache');;Timeline.TimelineLayersView=class extends UI.SplitWidget{constructor(model,showPaintProfilerCallback){super(true,false,'timelineLayersView');this._model=model;this._showPaintProfilerCallback=showPaintProfilerCallback;this.element.classList.add('timeline-layers-view');this._rightSplitWidget=new UI.SplitWidget(true,true,'timelineLayersViewDetails');this._rightSplitWidget.element.classList.add('timeline-layers-view-properties');this.setMainWidget(this._rightSplitWidget);const vbox=new UI.VBox();this.setSidebarWidget(vbox);this._layerViewHost=new LayerViewer.LayerViewHost();const layerTreeOutline=new LayerViewer.LayerTreeOutline(this._layerViewHost);vbox.element.appendChild(layerTreeOutline.element);this._layers3DView=new LayerViewer.Layers3DView(this._layerViewHost);this._layers3DView.addEventListener(LayerViewer.Layers3DView.Events.PaintProfilerRequested,this._onPaintProfilerRequested,this);this._rightSplitWidget.setMainWidget(this._layers3DView);const layerDetailsView=new LayerViewer.LayerDetailsView(this._layerViewHost);this._rightSplitWidget.setSidebarWidget(layerDetailsView);layerDetailsView.addEventListener(LayerViewer.LayerDetailsView.Events.PaintProfilerRequested,this._onPaintProfilerRequested,this);}
showLayerTree(frameLayerTree){this._frameLayerTree=frameLayerTree;if(this.isShowing())
this._update();else
this._updateWhenVisible=true;}
wasShown(){if(this._updateWhenVisible){this._updateWhenVisible=false;this._update();}}
_onPaintProfilerRequested(event){const selection=(event.data);this._layers3DView.snapshotForSelection(selection).then(snapshotWithRect=>{if(snapshotWithRect)
this._showPaintProfilerCallback(snapshotWithRect.snapshot);});}
_update(){this._frameLayerTree.layerTreePromise().then(layerTree=>this._layerViewHost.setLayerTree(layerTree));}};;Timeline.TimelinePaintProfilerView=class extends UI.SplitWidget{constructor(frameModel){super(false,false);this.element.classList.add('timeline-paint-profiler-view');this.setSidebarSize(60);this.setResizable(false);this._frameModel=frameModel;this._logAndImageSplitWidget=new UI.SplitWidget(true,false);this._logAndImageSplitWidget.element.classList.add('timeline-paint-profiler-log-split');this.setMainWidget(this._logAndImageSplitWidget);this._imageView=new Timeline.TimelinePaintImageView();this._logAndImageSplitWidget.setMainWidget(this._imageView);this._paintProfilerView=new LayerViewer.PaintProfilerView(this._imageView.showImage.bind(this._imageView));this._paintProfilerView.addEventListener(LayerViewer.PaintProfilerView.Events.WindowChanged,this._onWindowChanged,this);this.setSidebarWidget(this._paintProfilerView);this._logTreeView=new LayerViewer.PaintProfilerCommandLogView();this._logAndImageSplitWidget.setSidebarWidget(this._logTreeView);this._needsUpdateWhenVisible=false;this._pendingSnapshot=null;this._event=null;this._paintProfilerModel=null;this._lastLoadedSnapshot=null;}
wasShown(){if(this._needsUpdateWhenVisible){this._needsUpdateWhenVisible=false;this._update();}}
setSnapshot(snapshot){this._releaseSnapshot();this._pendingSnapshot=snapshot;this._event=null;this._updateWhenVisible();}
setEvent(paintProfilerModel,event){this._releaseSnapshot();this._paintProfilerModel=paintProfilerModel;this._pendingSnapshot=null;this._event=event;this._updateWhenVisible();if(this._event.name===TimelineModel.TimelineModel.RecordType.Paint)
return!!TimelineModel.TimelineData.forEvent(event).picture;if(this._event.name===TimelineModel.TimelineModel.RecordType.RasterTask)
return this._frameModel.hasRasterTile(this._event);return false;}
_updateWhenVisible(){if(this.isShowing())
this._update();else
this._needsUpdateWhenVisible=true;}
_update(){this._logTreeView.setCommandLog([]);this._paintProfilerView.setSnapshotAndLog(null,[],null);let snapshotPromise;if(this._pendingSnapshot){snapshotPromise=Promise.resolve({rect:null,snapshot:this._pendingSnapshot});}else if(this._event.name===TimelineModel.TimelineModel.RecordType.Paint){const picture=TimelineModel.TimelineData.forEvent(this._event).picture;snapshotPromise=picture.objectPromise().then(data=>this._paintProfilerModel.loadSnapshot(data['skp64'])).then(snapshot=>snapshot&&{rect:null,snapshot:snapshot});}else if(this._event.name===TimelineModel.TimelineModel.RecordType.RasterTask){snapshotPromise=this._frameModel.rasterTilePromise(this._event);}else{console.assert(false,'Unexpected event type or no snapshot');return;}
snapshotPromise.then(snapshotWithRect=>{this._releaseSnapshot();if(!snapshotWithRect){this._imageView.showImage();return;}
const snapshot=snapshotWithRect.snapshot;this._lastLoadedSnapshot=snapshot;this._imageView.setMask(snapshotWithRect.rect);snapshot.commandLog().then(log=>onCommandLogDone.call(this,snapshot,snapshotWithRect.rect,log));});function onCommandLogDone(snapshot,clipRect,log){this._logTreeView.setCommandLog(log||[]);this._paintProfilerView.setSnapshotAndLog(snapshot,log||[],clipRect);}}
_releaseSnapshot(){if(!this._lastLoadedSnapshot)
return;this._lastLoadedSnapshot.release();this._lastLoadedSnapshot=null;}
_onWindowChanged(){this._logTreeView.updateWindow(this._paintProfilerView.selectionWindow());}};Timeline.TimelinePaintImageView=class extends UI.Widget{constructor(){super(true);this.registerRequiredCSS('timeline/timelinePaintProfiler.css');this.contentElement.classList.add('fill','paint-profiler-image-view');this._imageContainer=this.contentElement.createChild('div','paint-profiler-image-container');this._imageElement=this._imageContainer.createChild('img');this._maskElement=this._imageContainer.createChild('div');this._imageElement.addEventListener('load',this._updateImagePosition.bind(this),false);this._transformController=new LayerViewer.TransformController(this.contentElement,true);this._transformController.addEventListener(LayerViewer.TransformController.Events.TransformChanged,this._updateImagePosition,this);}
onResize(){if(this._imageElement.src)
this._updateImagePosition();}
_updateImagePosition(){const width=this._imageElement.naturalWidth;const height=this._imageElement.naturalHeight;const clientWidth=this.contentElement.clientWidth;const clientHeight=this.contentElement.clientHeight;const paddingFraction=0.1;const paddingX=clientWidth*paddingFraction;const paddingY=clientHeight*paddingFraction;const scaleX=(clientWidth-paddingX)/width;const scaleY=(clientHeight-paddingY)/height;const scale=Math.min(scaleX,scaleY);if(this._maskRectangle){const style=this._maskElement.style;style.width=width+'px';style.height=height+'px';style.borderLeftWidth=this._maskRectangle.x+'px';style.borderTopWidth=this._maskRectangle.y+'px';style.borderRightWidth=(width-this._maskRectangle.x-this._maskRectangle.width)+'px';style.borderBottomWidth=(height-this._maskRectangle.y-this._maskRectangle.height)+'px';}
this._transformController.setScaleConstraints(0.5,10/scale);let matrix=new WebKitCSSMatrix().scale(this._transformController.scale(),this._transformController.scale()).translate(clientWidth/2,clientHeight/2).scale(scale,scale).translate(-width/2,-height/2);const bounds=UI.Geometry.boundsForTransformedPoints(matrix,[0,0,0,width,height,0]);this._transformController.clampOffsets(paddingX-bounds.maxX,clientWidth-paddingX-bounds.minX,paddingY-bounds.maxY,clientHeight-paddingY-bounds.minY);matrix=new WebKitCSSMatrix().translate(this._transformController.offsetX(),this._transformController.offsetY()).multiply(matrix);this._imageContainer.style.webkitTransform=matrix.toString();}
showImage(imageURL){this._imageContainer.classList.toggle('hidden',!imageURL);if(imageURL)
this._imageElement.src=imageURL;}
setMask(maskRectangle){this._maskRectangle=maskRectangle;this._maskElement.classList.toggle('hidden',!maskRectangle);}};;Timeline.TimelinePanel=class extends UI.Panel{constructor(){super('timeline');this.registerRequiredCSS('timeline/timelinePanel.css');this.element.addEventListener('contextmenu',this._contextMenu.bind(this),false);this._dropTarget=new UI.DropTarget(this.element,[UI.DropTarget.Type.File,UI.DropTarget.Type.URI],Common.UIString('Drop timeline file or URL here'),this._handleDrop.bind(this));this._recordingOptionUIControls=[];this._state=Timeline.TimelinePanel.State.Idle;this._recordingPageReload=false;this._millisecondsToRecordAfterLoadEvent=3000;this._toggleRecordAction=(UI.actionRegistry.action('timeline.toggle-recording'));this._recordReloadAction=(UI.actionRegistry.action('timeline.record-reload'));this._historyManager=new Timeline.TimelineHistoryManager();this._performanceModel=null;this._viewModeSetting=Common.settings.createSetting('timelineViewMode',Timeline.TimelinePanel.ViewMode.FlameChart);this._disableCaptureJSProfileSetting=Common.settings.createSetting('timelineDisableJSSampling',false);this._disableCaptureJSProfileSetting.setTitle(Common.UIString('Disable JavaScript samples'));this._captureLayersAndPicturesSetting=Common.settings.createSetting('timelineCaptureLayersAndPictures',false);this._captureLayersAndPicturesSetting.setTitle(Common.UIString('Enable advanced paint instrumentation (slow)'));this._showScreenshotsSetting=Common.settings.createSetting('timelineShowScreenshots',true);this._showScreenshotsSetting.setTitle(Common.UIString('Screenshots'));this._showScreenshotsSetting.addChangeListener(this._updateOverviewControls,this);this._showMemorySetting=Common.settings.createSetting('timelineShowMemory',false);this._showMemorySetting.setTitle(Common.UIString('Memory'));this._showMemorySetting.addChangeListener(this._onModeChanged,this);const timelineToolbarContainer=this.element.createChild('div','timeline-toolbar-container');this._panelToolbar=new UI.Toolbar('timeline-main-toolbar',timelineToolbarContainer);this._panelRightToolbar=new UI.Toolbar('',timelineToolbarContainer);this._createSettingsPane();this._updateShowSettingsToolbarButton();this._timelinePane=new UI.VBox();this._timelinePane.show(this.element);const topPaneElement=this._timelinePane.element.createChild('div','hbox');topPaneElement.id='timeline-overview-panel';this._overviewPane=new PerfUI.TimelineOverviewPane('timeline');this._overviewPane.addEventListener(PerfUI.TimelineOverviewPane.Events.WindowChanged,this._onOverviewWindowChanged.bind(this));this._overviewPane.show(topPaneElement);this._overviewControls=[];this._statusPaneContainer=this._timelinePane.element.createChild('div','status-pane-container fill');this._createFileSelector();SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);this._flameChart=new Timeline.TimelineFlameChartView(this);this._searchableView=new UI.SearchableView(this._flameChart);this._searchableView.setMinimumSize(0,100);this._searchableView.element.classList.add('searchable-view');this._searchableView.show(this._timelinePane.element);this._flameChart.show(this._searchableView.element);this._flameChart.setSearchableView(this._searchableView);this._onModeChanged();this._populateToolbar();this._showLandingPage();this._updateTimelineControls();Extensions.extensionServer.addEventListener(Extensions.ExtensionServer.Events.TraceProviderAdded,this._appendExtensionsToToolbar,this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._onSuspendStateChanged,this);}
static instance(){return(self.runtime.sharedInstance(Timeline.TimelinePanel));}
searchableView(){return this._searchableView;}
wasShown(){UI.context.setFlavor(Timeline.TimelinePanel,this);}
willHide(){UI.context.setFlavor(Timeline.TimelinePanel,null);this._historyManager.cancelIfShowing();}
loadFromEvents(events){if(this._state!==Timeline.TimelinePanel.State.Idle)
return;this._prepareToLoadTimeline();this._loader=Timeline.TimelineLoader.loadFromEvents(events,this);}
_onOverviewWindowChanged(event){const left=event.data.startTime;const right=event.data.endTime;this._performanceModel.setWindow({left,right},true);}
_onModelWindowChanged(event){const window=(event.data.window);this._overviewPane.setWindowTimes(window.left,window.right);}
_setState(state){this._state=state;this._updateTimelineControls();}
_createSettingCheckbox(setting,tooltip){const checkboxItem=new UI.ToolbarSettingCheckbox(setting,tooltip);this._recordingOptionUIControls.push(checkboxItem);return checkboxItem;}
_populateToolbar(){this._panelToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._toggleRecordAction));this._panelToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._recordReloadAction));this._clearButton=new UI.ToolbarButton(Common.UIString('Clear'),'largeicon-clear');this._clearButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._onClearButton());this._panelToolbar.appendToolbarItem(this._clearButton);this._loadButton=new UI.ToolbarButton(Common.UIString('Load profile...'),'largeicon-load');this._loadButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._selectFileToLoad());this._saveButton=new UI.ToolbarButton(Common.UIString('Save profile...'),'largeicon-download');this._saveButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._saveToFile());this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._loadButton);this._panelToolbar.appendToolbarItem(this._saveButton);this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._historyManager.button());this._panelToolbar.appendSeparator();this._panelToolbar.appendSeparator();this._showScreenshotsToolbarCheckbox=this._createSettingCheckbox(this._showScreenshotsSetting,Common.UIString('Capture screenshots'));this._panelToolbar.appendToolbarItem(this._showScreenshotsToolbarCheckbox);this._showMemoryToolbarCheckbox=this._createSettingCheckbox(this._showMemorySetting,Common.UIString('Show memory timeline'));this._panelToolbar.appendToolbarItem(this._showMemoryToolbarCheckbox);this._panelToolbar.appendToolbarItem(UI.Toolbar.createActionButtonForId('components.collect-garbage'));this._panelRightToolbar.appendSeparator();this._panelRightToolbar.appendToolbarItem(this._showSettingsPaneButton);}
_createSettingsPane(){this._showSettingsPaneSetting=Common.settings.createSetting('timelineShowSettingsToolbar',false);this._showSettingsPaneButton=new UI.ToolbarSettingToggle(this._showSettingsPaneSetting,'largeicon-settings-gear',Common.UIString('Capture settings'));SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,this._updateShowSettingsToolbarButton,this);MobileThrottling.throttlingManager().addEventListener(MobileThrottling.ThrottlingManager.Events.RateChanged,this._updateShowSettingsToolbarButton,this);this._disableCaptureJSProfileSetting.addChangeListener(this._updateShowSettingsToolbarButton,this);this._captureLayersAndPicturesSetting.addChangeListener(this._updateShowSettingsToolbarButton,this);this._settingsPane=new UI.HBox();this._settingsPane.element.classList.add('timeline-settings-pane');this._settingsPane.show(this.element);const captureToolbar=new UI.Toolbar('',this._settingsPane.element);captureToolbar.element.classList.add('flex-auto');captureToolbar.makeVertical();captureToolbar.appendToolbarItem(this._createSettingCheckbox(this._disableCaptureJSProfileSetting,Common.UIString('Disables JavaScript sampling, reduces overhead when running against mobile devices')));captureToolbar.appendToolbarItem(this._createSettingCheckbox(this._captureLayersAndPicturesSetting,Common.UIString('Captures advanced paint instrumentation, introduces significant performance overhead')));const throttlingPane=new UI.VBox();throttlingPane.element.classList.add('flex-auto');throttlingPane.show(this._settingsPane.element);const networkThrottlingToolbar=new UI.Toolbar('',throttlingPane.element);networkThrottlingToolbar.appendText(Common.UIString('Network:'));this._networkThrottlingSelect=this._createNetworkConditionsSelect();networkThrottlingToolbar.appendToolbarItem(this._networkThrottlingSelect);const cpuThrottlingToolbar=new UI.Toolbar('',throttlingPane.element);cpuThrottlingToolbar.appendText(Common.UIString('CPU:'));this._cpuThrottlingSelect=MobileThrottling.throttlingManager().createCPUThrottlingSelector();cpuThrottlingToolbar.appendToolbarItem(this._cpuThrottlingSelect);this._showSettingsPaneSetting.addChangeListener(this._updateSettingsPaneVisibility.bind(this));this._updateSettingsPaneVisibility();}
_appendExtensionsToToolbar(event){const provider=(event.data);const setting=Timeline.TimelinePanel._settingForTraceProvider(provider);const checkbox=this._createSettingCheckbox(setting,provider.longDisplayName());this._panelToolbar.appendToolbarItem(checkbox);}
static _settingForTraceProvider(traceProvider){let setting=traceProvider[Timeline.TimelinePanel._traceProviderSettingSymbol];if(!setting){const providerId=traceProvider.persistentIdentifier();setting=Common.settings.createSetting(providerId,false);setting.setTitle(traceProvider.shortDisplayName());traceProvider[Timeline.TimelinePanel._traceProviderSettingSymbol]=setting;}
return setting;}
_createNetworkConditionsSelect(){const toolbarItem=new UI.ToolbarComboBox(null);toolbarItem.setMaxWidth(140);MobileThrottling.throttlingManager().decorateSelectWithNetworkThrottling(toolbarItem.selectElement());return toolbarItem;}
_prepareToLoadTimeline(){console.assert(this._state===Timeline.TimelinePanel.State.Idle);this._setState(Timeline.TimelinePanel.State.Loading);if(this._performanceModel){this._performanceModel.dispose();this._performanceModel=null;}}
_createFileSelector(){if(this._fileSelectorElement)
this._fileSelectorElement.remove();this._fileSelectorElement=UI.createFileSelectorElement(this._loadFromFile.bind(this));this._timelinePane.element.appendChild(this._fileSelectorElement);}
_contextMenu(event){const contextMenu=new UI.ContextMenu(event);contextMenu.appendItemsAtLocation('timelineMenu');contextMenu.show();}
async _saveToFile(){if(this._state!==Timeline.TimelinePanel.State.Idle)
return;const performanceModel=this._performanceModel;if(!performanceModel)
return;const now=new Date();const fileName='Profile-'+now.toISO8601Compact()+'.json';const stream=new Bindings.FileOutputStream();const accepted=await stream.open(fileName);if(!accepted)
return;const error=await performanceModel.save(stream);if(!error)
return;Common.console.error(Common.UIString('Failed to save timeline: %s (%s, %s)',error.message,error.name,error.code));}
async _showHistory(){const model=await this._historyManager.showHistoryDropDown();if(model&&model!==this._performanceModel)
this._setModel(model);}
_navigateHistory(direction){const model=this._historyManager.navigate(direction);if(model&&model!==this._performanceModel)
this._setModel(model);return true;}
_selectFileToLoad(){this._fileSelectorElement.click();}
_loadFromFile(file){if(this._state!==Timeline.TimelinePanel.State.Idle)
return;this._prepareToLoadTimeline();this._loader=Timeline.TimelineLoader.loadFromFile(file,this);this._createFileSelector();}
_loadFromURL(url){if(this._state!==Timeline.TimelinePanel.State.Idle)
return;this._prepareToLoadTimeline();this._loader=Timeline.TimelineLoader.loadFromURL(url,this);}
_updateOverviewControls(){this._overviewControls=[];this._overviewControls.push(new Timeline.TimelineEventOverviewResponsiveness());if(Runtime.experiments.isEnabled('inputEventsOnTimelineOverview'))
this._overviewControls.push(new Timeline.TimelineEventOverviewInput());this._overviewControls.push(new Timeline.TimelineEventOverviewFrames());this._overviewControls.push(new Timeline.TimelineEventOverviewCPUActivity());this._overviewControls.push(new Timeline.TimelineEventOverviewNetwork());if(this._showScreenshotsSetting.get()&&this._performanceModel&&this._performanceModel.filmStripModel().frames().length)
this._overviewControls.push(new Timeline.TimelineFilmStripOverview());if(this._showMemorySetting.get())
this._overviewControls.push(new Timeline.TimelineEventOverviewMemory());for(const control of this._overviewControls)
control.setModel(this._performanceModel);this._overviewPane.setOverviewControls(this._overviewControls);}
_onModeChanged(){this._updateOverviewControls();this.doResize();this.select(null);}
_updateSettingsPaneVisibility(){if(this._showSettingsPaneSetting.get())
this._settingsPane.showWidget();else
this._settingsPane.hideWidget();}
_updateShowSettingsToolbarButton(){const messages=[];if(MobileThrottling.throttlingManager().cpuThrottlingRate()!==1)
messages.push(Common.UIString('- CPU throttling is enabled'));if(SDK.multitargetNetworkManager.isThrottling())
messages.push(Common.UIString('- Network throttling is enabled'));if(this._captureLayersAndPicturesSetting.get())
messages.push(Common.UIString('- Significant overhead due to paint instrumentation'));if(this._disableCaptureJSProfileSetting.get())
messages.push(Common.UIString('- JavaScript sampling is disabled'));this._showSettingsPaneButton.setDefaultWithRedColor(messages.length);this._showSettingsPaneButton.setToggleWithRedColor(messages.length);if(messages.length){const tooltipElement=createElement('div');messages.forEach(message=>{tooltipElement.createChild('div').textContent=message;});this._showSettingsPaneButton.setTitle(tooltipElement);}else{this._showSettingsPaneButton.setTitle(Common.UIString('Capture settings'));}}
_setUIControlsEnabled(enabled){this._recordingOptionUIControls.forEach(control=>control.setEnabled(enabled));}
async _startRecording(){console.assert(!this._statusPane,'Status pane is already opened.');this._setState(Timeline.TimelinePanel.State.StartPending);this._showRecordingStarted();const enabledTraceProviders=Extensions.extensionServer.traceProviders().filter(provider=>Timeline.TimelinePanel._settingForTraceProvider(provider).get());const recordingOptions={enableJSSampling:!this._disableCaptureJSProfileSetting.get(),capturePictures:this._captureLayersAndPicturesSetting.get(),captureFilmStrip:this._showScreenshotsSetting.get()};const mainTarget=(SDK.targetManager.mainTarget());this._controller=new Timeline.TimelineController(mainTarget,this);this._setUIControlsEnabled(false);this._hideLandingPage();await this._controller.startRecording(recordingOptions,enabledTraceProviders);this._recordingStarted();}
async _stopRecording(){if(this._statusPane){this._statusPane.finish();this._statusPane.updateStatus(Common.UIString('Stopping timeline\u2026'));this._statusPane.updateProgressBar(Common.UIString('Received'),0);}
this._setState(Timeline.TimelinePanel.State.StopPending);this._performanceModel=await this._controller.stopRecording();this._setUIControlsEnabled(true);this._controller.dispose();this._controller=null;}
_onSuspendStateChanged(){this._updateTimelineControls();}
_updateTimelineControls(){const state=Timeline.TimelinePanel.State;this._toggleRecordAction.setToggled(this._state===state.Recording);this._toggleRecordAction.setEnabled(this._state===state.Recording||this._state===state.Idle);this._recordReloadAction.setEnabled(this._state===state.Idle);this._historyManager.setEnabled(this._state===state.Idle);this._clearButton.setEnabled(this._state===state.Idle);this._panelToolbar.setEnabled(this._state!==state.Loading);this._panelRightToolbar.setEnabled(this._state!==state.Loading);this._dropTarget.setEnabled(this._state===state.Idle);this._loadButton.setEnabled(this._state===state.Idle);this._saveButton.setEnabled(this._state===state.Idle&&!!this._performanceModel);}
_toggleRecording(){if(this._state===Timeline.TimelinePanel.State.Idle){this._recordingPageReload=false;this._startRecording();Host.userMetrics.actionTaken(Host.UserMetrics.Action.TimelineStarted);}else if(this._state===Timeline.TimelinePanel.State.Recording){this._stopRecording();}}
_recordReload(){if(this._state!==Timeline.TimelinePanel.State.Idle)
return;this._recordingPageReload=true;this._startRecording();Host.userMetrics.actionTaken(Host.UserMetrics.Action.TimelinePageReloadStarted);}
_onClearButton(){this._historyManager.clear();this._clear();}
_clear(){this._showLandingPage();this._reset();}
_reset(){self.runtime.sharedInstance(PerfUI.LineLevelProfile.Performance).reset();this._setModel(null);}
_applyFilters(model){if(model.timelineModel().isGenericTrace()||Runtime.experiments.isEnabled('timelineShowAllEvents'))
return;model.setFilters([Timeline.TimelineUIUtils.visibleEventsFilter()]);}
_setModel(model){if(this._performanceModel){this._performanceModel.removeEventListener(Timeline.PerformanceModel.Events.WindowChanged,this._onModelWindowChanged,this);}
this._performanceModel=model;if(model)
this._applyFilters(model);this._flameChart.setModel(model);this._updateOverviewControls();this._overviewPane.reset();if(model){this._performanceModel.addEventListener(Timeline.PerformanceModel.Events.WindowChanged,this._onModelWindowChanged,this);this._overviewPane.setBounds(model.timelineModel().minimumRecordTime(),model.timelineModel().maximumRecordTime());const lineLevelProfile=self.runtime.sharedInstance(PerfUI.LineLevelProfile.Performance);lineLevelProfile.reset();for(const profile of model.timelineModel().cpuProfiles())
lineLevelProfile.appendCPUProfile(profile);this._setMarkers(model.timelineModel());this._flameChart.setSelection(null);this._overviewPane.setWindowTimes(model.window().left,model.window().right);}
for(const control of this._overviewControls)
control.setModel(model);if(this._flameChart)
this._flameChart.resizeToPreferredHeights();this._updateTimelineControls();}
_recordingStarted(){if(this._recordingPageReload){const target=this._controller.mainTarget();const resourceModel=target.model(SDK.ResourceTreeModel);if(resourceModel)
resourceModel.reloadPage();}
this._reset();this._setState(Timeline.TimelinePanel.State.Recording);this._showRecordingStarted();this._statusPane.updateStatus(Common.UIString('Profiling\u2026'));this._statusPane.updateProgressBar(Common.UIString('Buffer usage'),0);this._statusPane.startTimer();this._hideLandingPage();}
recordingProgress(usage){this._statusPane.updateProgressBar(Common.UIString('Buffer usage'),usage*100);}
_showLandingPage(){if(this._landingPage){this._landingPage.show(this._statusPaneContainer);return;}
function encloseWithTag(tagName,contents){const e=createElement(tagName);e.textContent=contents;return e;}
const learnMoreNode=UI.XLink.create('https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/',Common.UIString('Learn\xa0more'));const recordKey=encloseWithTag('b',UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.toggle-recording')[0].name);const reloadKey=encloseWithTag('b',UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.record-reload')[0].name);const navigateNode=encloseWithTag('b',Common.UIString('WASD'));this._landingPage=new UI.VBox();this._landingPage.contentElement.classList.add('timeline-landing-page','fill');const centered=this._landingPage.contentElement.createChild('div');const recordButton=UI.createInlineButton(UI.Toolbar.createActionButton(this._toggleRecordAction));const reloadButton=UI.createInlineButton(UI.Toolbar.createActionButtonForId('timeline.record-reload'));centered.createChild('p').appendChild(UI.formatLocalized('Click the record button %s or hit %s to start a new recording.\nClick the reload button %s or hit %s to record the page load.',[recordButton,recordKey,reloadButton,reloadKey]));centered.createChild('p').appendChild(UI.formatLocalized('After recording, select an area of interest in the overview by dragging.\nThen, zoom and pan the timeline with the mousewheel or %s keys.\n%s',[navigateNode,learnMoreNode]));this._landingPage.show(this._statusPaneContainer);}
_hideLandingPage(){this._landingPage.detach();}
loadingStarted(){this._hideLandingPage();if(this._statusPane)
this._statusPane.hide();this._statusPane=new Timeline.TimelinePanel.StatusPane(false,this._cancelLoading.bind(this));this._statusPane.showPane(this._statusPaneContainer);this._statusPane.updateStatus(Common.UIString('Loading profile\u2026'));if(!this._loader)
this._statusPane.finish();this.loadingProgress(0);}
loadingProgress(progress){if(typeof progress==='number')
this._statusPane.updateProgressBar(Common.UIString('Received'),progress*100);}
processingStarted(){this._statusPane.updateStatus(Common.UIString('Processing profile\u2026'));}
loadingComplete(tracingModel){delete this._loader;this._setState(Timeline.TimelinePanel.State.Idle);if(this._statusPane)
this._statusPane.hide();delete this._statusPane;if(!tracingModel){this._clear();return;}
if(!this._performanceModel)
this._performanceModel=new Timeline.PerformanceModel();this._performanceModel.setTracingModel(tracingModel);this._setModel(this._performanceModel);this._historyManager.addRecording(this._performanceModel);}
_showRecordingStarted(){if(this._statusPane)
return;this._statusPane=new Timeline.TimelinePanel.StatusPane(true,this._stopRecording.bind(this));this._statusPane.showPane(this._statusPaneContainer);this._statusPane.updateStatus(Common.UIString('Initializing profiler\u2026'));}
_cancelLoading(){if(this._loader)
this._loader.cancel();}
_setMarkers(timelineModel){const markers=new Map();const recordTypes=TimelineModel.TimelineModel.RecordType;const zeroTime=timelineModel.minimumRecordTime();for(const event of timelineModel.timeMarkerEvents()){if(event.name===recordTypes.TimeStamp||event.name===recordTypes.ConsoleTime)
continue;markers.set(event.startTime,Timeline.TimelineUIUtils.createEventDivider(event,zeroTime));}
this._overviewPane.setMarkers(markers);}
async _loadEventFired(event){if(this._state!==Timeline.TimelinePanel.State.Recording||!this._recordingPageReload||this._controller.mainTarget()!==event.data.resourceTreeModel.target())
return;const controller=this._controller;await new Promise(r=>setTimeout(r,this._millisecondsToRecordAfterLoadEvent));if(controller!==this._controller||this._state!==Timeline.TimelinePanel.State.Recording)
return;this._stopRecording();}
_frameForSelection(selection){switch(selection.type()){case Timeline.TimelineSelection.Type.Frame:return(selection.object());case Timeline.TimelineSelection.Type.Range:return null;case Timeline.TimelineSelection.Type.TraceEvent:return this._performanceModel.frameModel().frames(selection._endTime,selection._endTime)[0];default:console.assert(false,'Should never be reached');return null;}}
_jumpToFrame(offset){const currentFrame=this._selection&&this._frameForSelection(this._selection);if(!currentFrame)
return;const frames=this._performanceModel.frames();let index=frames.indexOf(currentFrame);console.assert(index>=0,'Can\'t find current frame in the frame list');index=Number.constrain(index+offset,0,frames.length-1);const frame=frames[index];this._revealTimeRange(frame.startTime,frame.endTime);this.select(Timeline.TimelineSelection.fromFrame(frame));return true;}
select(selection){this._selection=selection;this._flameChart.setSelection(selection);}
selectEntryAtTime(events,time){if(!events)
return;for(let index=events.upperBound(time,(time,event)=>time-event.startTime)-1;index>=0;--index){const event=events[index];const endTime=event.endTime||event.startTime;if(SDK.TracingModel.isTopLevelEvent(event)&&endTime<time)
break;if(this._performanceModel.isVisible(event)&&endTime>=time){this.select(Timeline.TimelineSelection.fromTraceEvent(event));return;}}
this.select(null);}
highlightEvent(event){this._flameChart.highlightEvent(event);}
_revealTimeRange(startTime,endTime){const window=this._performanceModel.window();let offset=0;if(window.right<endTime)
offset=endTime-window.right;else if(window.left>startTime)
offset=startTime-window.left;this._performanceModel.setWindow({left:window.left+offset,right:window.right+offset},true);}
_handleDrop(dataTransfer){const items=dataTransfer.items;if(!items.length)
return;const item=items[0];if(item.kind==='string'){const url=dataTransfer.getData('text/uri-list');if(new Common.ParsedURL(url).isValid)
this._loadFromURL(url);}else if(item.kind==='file'){const entry=items[0].webkitGetAsEntry();if(!entry.isFile)
return;entry.file(this._loadFromFile.bind(this));}}};Timeline.TimelinePanel.State={Idle:Symbol('Idle'),StartPending:Symbol('StartPending'),Recording:Symbol('Recording'),StopPending:Symbol('StopPending'),Loading:Symbol('Loading')};Timeline.TimelinePanel.ViewMode={FlameChart:'FlameChart',BottomUp:'BottomUp',CallTree:'CallTree',EventLog:'EventLog'};Timeline.TimelinePanel.rowHeight=18;Timeline.TimelinePanel.headerHeight=20;Timeline.TimelinePanel.ModelSelectionData;Timeline.TimelineSelection=class{constructor(type,startTime,endTime,object){this._type=type;this._startTime=startTime;this._endTime=endTime;this._object=object||null;}
static fromFrame(frame){return new Timeline.TimelineSelection(Timeline.TimelineSelection.Type.Frame,frame.startTime,frame.endTime,frame);}
static fromNetworkRequest(request){return new Timeline.TimelineSelection(Timeline.TimelineSelection.Type.NetworkRequest,request.startTime,request.endTime||request.startTime,request);}
static fromTraceEvent(event){return new Timeline.TimelineSelection(Timeline.TimelineSelection.Type.TraceEvent,event.startTime,event.endTime||(event.startTime+1),event);}
static fromRange(startTime,endTime){return new Timeline.TimelineSelection(Timeline.TimelineSelection.Type.Range,startTime,endTime);}
type(){return this._type;}
object(){return this._object;}
startTime(){return this._startTime;}
endTime(){return this._endTime;}};Timeline.TimelineSelection.Type={Frame:'Frame',NetworkRequest:'NetworkRequest',TraceEvent:'TraceEvent',Range:'Range'};Timeline.TimelineModeViewDelegate=function(){};Timeline.TimelineModeViewDelegate.prototype={select(selection){},selectEntryAtTime(events,time){},highlightEvent(event){},};Timeline.TimelinePanel.StatusPane=class extends UI.VBox{constructor(showTimer,stopCallback){super(true);this.registerRequiredCSS('timeline/timelineStatusDialog.css');this.contentElement.classList.add('timeline-status-dialog');const statusLine=this.contentElement.createChild('div','status-dialog-line status');statusLine.createChild('div','label').textContent=Common.UIString('Status');this._status=statusLine.createChild('div','content');if(showTimer){const timeLine=this.contentElement.createChild('div','status-dialog-line time');timeLine.createChild('div','label').textContent=Common.UIString('Time');this._time=timeLine.createChild('div','content');}
const progressLine=this.contentElement.createChild('div','status-dialog-line progress');this._progressLabel=progressLine.createChild('div','label');this._progressBar=progressLine.createChild('div','indicator-container').createChild('div','indicator');this._stopButton=UI.createTextButton(Common.UIString('Stop'),stopCallback,'',true);this.contentElement.createChild('div','stop-button').appendChild(this._stopButton);}
finish(){this._stopTimer();this._stopButton.disabled=true;}
hide(){this.element.parentNode.classList.remove('tinted');this.element.remove();}
showPane(parent){this.show(parent);parent.classList.add('tinted');this._stopButton.focus();}
updateStatus(text){this._status.textContent=text;}
updateProgressBar(activity,percent){this._progressLabel.textContent=activity;this._progressBar.style.width=percent.toFixed(1)+'%';this._updateTimer();}
startTimer(){this._startTime=Date.now();this._timeUpdateTimer=setInterval(this._updateTimer.bind(this,false),1000);this._updateTimer();}
_stopTimer(){if(!this._timeUpdateTimer)
return;clearInterval(this._timeUpdateTimer);this._updateTimer(true);delete this._timeUpdateTimer;}
_updateTimer(precise){if(!this._timeUpdateTimer)
return;const elapsed=(Date.now()-this._startTime)/1000;this._time.textContent=Common.UIString('%s\xa0sec',elapsed.toFixed(precise?1:0));}};Timeline.LoadTimelineHandler=class{handleQueryParam(value){UI.viewManager.showView('timeline').then(()=>{Timeline.TimelinePanel.instance()._loadFromURL(window.decodeURIComponent(value));});}};Timeline.TimelinePanel.ActionDelegate=class{handleAction(context,actionId){const panel=UI.context.flavor(Timeline.TimelinePanel);console.assert(panel&&panel instanceof Timeline.TimelinePanel);switch(actionId){case'timeline.toggle-recording':panel._toggleRecording();return true;case'timeline.record-reload':panel._recordReload();return true;case'timeline.save-to-file':panel._saveToFile();return true;case'timeline.load-from-file':panel._selectFileToLoad();return true;case'timeline.jump-to-previous-frame':panel._jumpToFrame(-1);return true;case'timeline.jump-to-next-frame':panel._jumpToFrame(1);return true;case'timeline.show-history':panel._showHistory();return true;case'timeline.previous-recording':panel._navigateHistory(1);return true;case'timeline.next-recording':panel._navigateHistory(-1);return true;}
return false;}};Timeline.TimelinePanel._traceProviderSettingSymbol=Symbol('traceProviderSetting');;Runtime.cachedResources["timeline/historyToolbarButton.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.history-dropdown-button {\n width: 160px;\n height: 26px;\n text-align: left;\n display: flex;\n}\n\n.history-dropdown-button[disabled] {\n opacity: .5;\n}\n\n.history-dropdown-button > .content {\n padding-right: 5px;\n overflow: hidden;\n text-overflow: ellipsis;\n flex: 1 1;\n min-width: 35px;\n}\n\n/*# sourceURL=timeline/historyToolbarButton.css */";Runtime.cachedResources["timeline/invalidationsTree.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.header, .children, .content {\n min-height: initial;\n line-height: initial;\n}\n\n/* This TreeElement is always expanded and has no arrow. */\n/* FIXME(crbug.com/475618): Implement this in TreeElement. */\n.children li::before {\n display: none;\n}\n\n.content {\n margin-bottom: 4px;\n}\n\n.content .stack-preview-container {\n margin-left: 8px;\n}\n\n.content .node-list {\n margin-left: 10px;\n}\n\n/*# sourceURL=timeline/invalidationsTree.css */";Runtime.cachedResources["timeline/timelineFlamechartPopover.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.timeline-flamechart-popover {\n overflow: hidden;\n}\n\n.timeline-flamechart-popover span {\n margin-right: 5px;\n}\n\n.timeline-flamechart-popover span.timeline-info-network-time {\n color: #009;\n}\n\n.timeline-flamechart-popover span.timeline-info-time {\n color: #282;\n}\n\n.timeline-flamechart-popover span.timeline-info-warning {\n color: #e44;\n}\n\n.timeline-flamechart-popover span.timeline-info-warning * {\n color: inherit;\n}\n\n/*# sourceURL=timeline/timelineFlamechartPopover.css */";Runtime.cachedResources["timeline/timelineHistoryManager.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.drop-down {\n padding: 1px;\n box-shadow: var(--drop-shadow);\n background: white;\n}\n\n.preview-item {\n border-color: transparent;\n border-style: solid;\n border-width: 1px 5px;\n padding: 2px 0px;\n margin: 2px 1px;\n}\n\n.preview-item.selected {\n border-color: var(--selection-bg-color);\n}\n\n.preview-item canvas {\n width: 100%;\n height: 100%;\n}\n\n.text-details {\n font-size: 11px;\n padding: 3px;\n}\n\n.text-details span {\n flex: 1 0;\n padding-left: 8px;\n padding-right: 8px;\n}\n\n.text-details .name {\n font-weight: bold;\n}\n\n.text-details span.time {\n color: #555;\n text-align: right;\n}\n\n.screenshot-thumb {\n display: flex;\n border: 1px solid #ccc;\n margin: 2px 4px;\n}\n\n.screenshot-thumb img {\n margin: auto;\n max-width: 100%;\n max-height: 100%;\n}\n\n/*# sourceURL=timeline/timelineHistoryManager.css */";Runtime.cachedResources["timeline/timelinePanel.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *
_flushContexts(){this._contextMapById.clear();this.dispatchEventToListeners(WebAudio.WebAudioModel.Events.ModelReset);}
suspendModel(){this._contextMapById.clear();return this._agent.disable();}
resumeModel(){if(!this._enabled)
return Promise.resolve();return this._agent.enable();}
ensureEnabled(){if(this._enabled)
return;this._agent.enable();this._enabled=true;}
contextCreated(context){this._contextMapById.set(context.contextId,context);this.dispatchEventToListeners(WebAudio.WebAudioModel.Events.ContextCreated,context);}
contextDestroyed(contextId){this._contextMapById.delete(contextId);this.dispatchEventToListeners(WebAudio.WebAudioModel.Events.ContextDestroyed,contextId);}
contextChanged(context){if(!this._contextMapById.has(context.contextId))
return;this._contextMapById.set(context.contextId,context);this.dispatchEventToListeners(WebAudio.WebAudioModel.Events.ContextChanged,context);}
async requestRealtimeData(contextId){if(!this._contextMapById.has(contextId))
return Promise.resolve();return await this._agent.getRealtimeData(contextId);}};SDK.SDKModel.register(WebAudio.WebAudioModel,SDK.Target.Capability.DOM,false);WebAudio.WebAudioModel.Events={ContextCreated:Symbol('ContextCreated'),ContextDestroyed:Symbol('ContextDestroyed'),ContextChanged:Symbol('ContextChanged'),ModelReset:Symbol('ModelReset'),};;WebAudio.AudioContextSelector=class extends Common.Object{constructor(title){super();this._items=new UI.ListModel();this._dropDown=new UI.SoftDropDown(this._items,this);this._dropDown.setPlaceholderText(ls`(no recordings)`);this._toolbarItem=new UI.ToolbarItem(this._dropDown.element);this._toolbarItem.setEnabled(false);this._toolbarItem.setTitle(title);this._items.addEventListener(UI.ListModel.Events.ItemsReplaced,this._onListItemReplaced,this);this._toolbarItem.element.classList.add('toolbar-has-dropdown');this._selectedContext=null;}
_onListItemReplaced(){this._toolbarItem.setEnabled(!!this._items.length);}
contextCreated(event){const context=(event.data);this._items.insert(this._items.length,context);if(this._items.length===1)
this._dropDown.selectItem(context);}
contextDestroyed(event){const contextId=(event.data);const contextIndex=this._items.findIndex(context=>context.contextId===contextId);if(contextIndex>-1)
this._items.remove(contextIndex);}
contextChanged(event){const changedContext=(event.data);const contextIndex=this._items.findIndex(context=>context.contextId===changedContext.contextId);if(contextIndex>-1){this._items.remove(contextIndex);this._items.insert(contextIndex,changedContext);if(this._selectedContext&&this._selectedContext.contextId===changedContext.contextId)
this._dropDown.selectItem(changedContext);}}
createElementForItem(item){const element=createElementWithClass('div');const shadowRoot=UI.createShadowRootWithCoreStyles(element,'web_audio/audioContextSelector.css');const title=shadowRoot.createChild('div','title');title.createTextChild(this.titleFor(item).trimEnd(100));return element;}
selectedContext(){if(!this._selectedContext)
return null;return this._selectedContext;}
highlightedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('highlighted');if(toElement)
toElement.classList.add('highlighted');}
isItemSelectable(item){return true;}
itemSelected(item){if(!item)
return;if(!this._selectedContext||this._selectedContext.contextId!==item.contextId)
this._selectedContext=item;this.dispatchEventToListeners(WebAudio.AudioContextSelector.Events.ContextSelected,item);}
reset(){this._items.replaceAll([]);}
titleFor(context){return`${context.contextType} (${context.contextId.substr(-6)})`;}
toolbarItem(){return this._toolbarItem;}};WebAudio.AudioContextSelector.Events={ContextSelected:Symbol('ContextSelected')};;WebAudio.ContextDetailBuilder=class{constructor(context){this._fragment=createDocumentFragment();this._container=createElementWithClass('div','context-detail-container');this._fragment.appendChild(this._container);this._build(context);}
_build(context){const title=context.contextType==='realtime'?ls`AudioContext`:ls`OfflineAudioContext`;this._addTitle(title,context.contextId);this._addEntry(ls`State`,context.contextState);this._addEntry(ls`Sample Rate`,context.sampleRate,'Hz');if(context.contextType==='realtime')
this._addEntry(ls`Callback Buffer Size`,context.callbackBufferSize,'frames');this._addEntry(ls`Max Output Channels`,context.maxOutputChannelCount,'ch');}
_addTitle(title,subtitle){this._container.appendChild(UI.html`
<div class="context-detail-header">
<div class="context-detail-title">${title}</div>
<div class="context-detail-subtitle">${subtitle}</div>
</div>
`);}
_addEntry(entry,value,unit){const valueWithUnit=value+(unit?` ${unit}`:'');this._container.appendChild(UI.html`
<div class="context-detail-row">
<div class="context-detail-row-entry">${entry}</div>
<div class="context-detail-row-value">${valueWithUnit}</div>
</div>
`);}
getFragment(){return this._fragment;}};WebAudio.AudioContextSummaryBuilder=class{constructor(contextId,contextRealtimeData){const time=contextRealtimeData.currentTime.toFixed(3);const capacity=(contextRealtimeData.renderCapacity*100).toFixed(3);this._fragment=createDocumentFragment();this._fragment.appendChild(UI.html`
<div class="context-summary-container">
<span>${ls`Current Time`}: ${time} s</span>
<span>\u2758</span>
<span>${ls`Render Capacity`}: ${capacity} %</span>
</div>
`);}
getFragment(){return this._fragment;}};;WebAudio.WebAudioView=class extends UI.ThrottledWidget{constructor(){super(true,1000);this.element.classList.add('web-audio-drawer');this.registerRequiredCSS('web_audio/webAudio.css');const toolbarContainer=this.contentElement.createChild('div','web-audio-toolbar-container vbox');this._contextSelector=new WebAudio.AudioContextSelector(ls`BaseAudioContexts`);const toolbar=new UI.Toolbar('web-audio-toolbar',toolbarContainer);toolbar.appendToolbarItem(UI.Toolbar.createActionButtonForId('components.collect-garbage'));toolbar.appendSeparator();toolbar.appendToolbarItem(this._contextSelector.toolbarItem());this._detailViewContainer=this.contentElement.createChild('div','vbox flex-auto');this._landingPage=new UI.VBox();this._landingPage.contentElement.classList.add('web-audio-landing-page','fill');this._landingPage.contentElement.appendChild(UI.html`
<div>
<p>${ls`Open a page that uses Web Audio API to start monitoring.`}</p>
</div>
`);this._landingPage.show(this._detailViewContainer);this._summaryBarContainer=this.contentElement.createChild('div','web-audio-summary-container');this._contextSelector.addEventListener(WebAudio.AudioContextSelector.Events.ContextSelected,event=>{const context=(event.data);this._updateDetailView(context);this.doUpdate();});SDK.targetManager.observeModels(WebAudio.WebAudioModel,this);}
wasShown(){for(const model of SDK.targetManager.models(WebAudio.WebAudioModel))
this._addEventListeners(model);}
willHide(){for(const model of SDK.targetManager.models(WebAudio.WebAudioModel))
this._removeEventListeners(model);}
modelAdded(webAudioModel){if(this.isShowing())
this._addEventListeners(webAudioModel);}
modelRemoved(webAudioModel){this._removeEventListeners(webAudioModel);}
async doUpdate(){await this._pollRealtimeData();this.update();}
_addEventListeners(webAudioModel){webAudioModel.ensureEnabled();webAudioModel.addEventListener(WebAudio.WebAudioModel.Events.ContextCreated,this._contextCreated,this);webAudioModel.addEventListener(WebAudio.WebAudioModel.Events.ContextDestroyed,this._contextDestroyed,this);webAudioModel.addEventListener(WebAudio.WebAudioModel.Events.ContextChanged,this._contextChanged,this);webAudioModel.addEventListener(WebAudio.WebAudioModel.Events.ModelReset,this._reset,this);}
_removeEventListeners(webAudioModel){webAudioModel.removeEventListener(WebAudio.WebAudioModel.Events.ContextCreated,this._contextCreated,this);webAudioModel.removeEventListener(WebAudio.WebAudioModel.Events.ContextDestroyed,this._contextDestroyed,this);webAudioModel.removeEventListener(WebAudio.WebAudioModel.Events.ContextChanged,this._contextChanged,this);webAudioModel.removeEventListener(WebAudio.WebAudioModel.Events.ModelReset,this._reset,this);}
_contextCreated(event){this._contextSelector.contextCreated(event);}
_contextDestroyed(event){this._contextSelector.contextDestroyed(event);}
_contextChanged(event){this._contextSelector.contextChanged(event);}
_reset(){if(this._landingPage.isShowing())
this._landingPage.detach();this._contextSelector.reset();this._detailViewContainer.removeChildren();this._landingPage.show(this._detailViewContainer);}
_updateDetailView(context){if(this._landingPage.isShowing())
this._landingPage.detach();const detailBuilder=new WebAudio.ContextDetailBuilder(context);this._detailViewContainer.removeChildren();this._detailViewContainer.appendChild(detailBuilder.getFragment());}
_updateSummaryBar(contextId,contextRealtimeData){const summaryBuilder=new WebAudio.AudioContextSummaryBuilder(contextId,contextRealtimeData);this._summaryBarContainer.removeChildren();this._summaryBarContainer.appendChild(summaryBuilder.getFragment());}
_clearSummaryBar(){this._summaryBarContainer.removeChildren();}
async _pollRealtimeData(){const context=this._contextSelector.selectedContext();if(!context){this._clearSummaryBar();return;}
for(const model of SDK.targetManager.models(WebAudio.WebAudioModel)){if(context.contextType==='realtime'){const realtimeData=await model.requestRealtimeData(context.contextId);if(realtimeData&&realtimeData.currentTime&&realtimeData.renderCapacity)
this._updateSummaryBar(context.contextId,realtimeData);}else{this._clearSummaryBar();}}}};;Runtime.cachedResources["web_audio/webAudio.css"]="/*\n * Copyright 2019 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n overflow: hidden;\n}\n\n.web-audio-toolbar-container {\n background-color: var(--toolbar-bg-color);\n border-bottom: var(--divider-border);\n}\n\n.web-audio-toolbar {\n display: inline-block;\n}\n\n.web-audio-landing-page {\n position: absolute;\n background-color: white;\n justify-content: center;\n align-items: center;\n overflow: auto;\n font-size: 13px;\n color: #777;\n}\n\n.web-audio-landing-page > div {\n max-width: 500px;\n margin: 10px;\n}\n\n.web-audio-landing-page > div > p {\n flex: none;\n white-space: pre-line;\n}\n\n.context-detail-container {\n flex: none;\n display: flex;\n background-color: white;\n flex-direction: column;\n}\n\n.context-detail-header {\n border-bottom: 1px solid rgb(230, 230, 230);\n padding: 12px 24px;\n margin-bottom: 10px;\n}\n\n.context-detail-title {\n font-size: 15px;\n font-weight: 400;\n}\n\n.context-detail-subtitle {\n font-size: 12px;\n margin-top: 10px;\n user-select: text;\n}\n\n.context-detail-row {\n flex-direction: row;\n display: flex;\n line-height: 18px;\n padding-left: 24px;\n}\n\n.context-detail-row-entry:not(:empty) {\n color: hsla(0, 0%, 46%, 1);\n overflow: hidden;\n width: 130px;\n}\n\n.context-detail-row-value {\n user-select: text;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.context-summary-container {\n flex: 0 0 27px;\n line-height: 27px;\n padding-left: 5px;\n background-color: #eee;\n border-top: 1px solid #ccc;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.context-summary-container span {\n margin-right: 6px;\n}\n\n/*# sourceURL=web_audio/webAudio.css */";Runtime.cachedResources["web_audio/audioContextSelector.css"]="/*\n * Copyright 2019 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n padding: 2px 1px 2px 2px;\n white-space: nowrap;\n display: flex;\n flex-direction: column;\n height: 36px;\n justify-content: center;\n}\n\n.title {\n overflow: hidden;\n text-overflow: ellipsis;\n flex-grow: 0;\n}\n/*# sourceURL=web_audio/audioContextSelector.css */";WorkspaceDiff.WorkspaceDiff=class extends Common.Object{constructor(workspace){super();this._uiSourceCodeDiffs=new WeakMap();this._loadingUISourceCodes=new Map();this._modifiedUISourceCodes=new Set();workspace.addEventListener(Workspace.Workspace.Events.WorkingCopyChanged,this._uiSourceCodeChanged,this);workspace.addEventListener(Workspace.Workspace.Events.WorkingCopyCommitted,this._uiSourceCodeChanged,this);workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._uiSourceCodeAdded,this);workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this._uiSourceCodeRemoved,this);workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,this._projectRemoved,this);workspace.uiSourceCodes().forEach(this._updateModifiedState.bind(this));}
requestDiff(uiSourceCode){return this._uiSourceCodeDiff(uiSourceCode).requestDiff();}
subscribeToDiffChange(uiSourceCode,callback,thisObj){this._uiSourceCodeDiff(uiSourceCode).addEventListener(WorkspaceDiff.Events.DiffChanged,callback,thisObj);}
unsubscribeFromDiffChange(uiSourceCode,callback,thisObj){this._uiSourceCodeDiff(uiSourceCode).removeEventListener(WorkspaceDiff.Events.DiffChanged,callback,thisObj);}
modifiedUISourceCodes(){return Array.from(this._modifiedUISourceCodes);}
isUISourceCodeModified(uiSourceCode){return this._modifiedUISourceCodes.has(uiSourceCode)||this._loadingUISourceCodes.has(uiSourceCode);}
_uiSourceCodeDiff(uiSourceCode){if(!this._uiSourceCodeDiffs.has(uiSourceCode))
this._uiSourceCodeDiffs.set(uiSourceCode,new WorkspaceDiff.WorkspaceDiff.UISourceCodeDiff(uiSourceCode));return this._uiSourceCodeDiffs.get(uiSourceCode);}
_uiSourceCodeChanged(event){const uiSourceCode=(event.data.uiSourceCode);this._updateModifiedState(uiSourceCode);}
_uiSourceCodeAdded(event){const uiSourceCode=(event.data);this._updateModifiedState(uiSourceCode);}
_uiSourceCodeRemoved(event){const uiSourceCode=(event.data);this._removeUISourceCode(uiSourceCode);}
_projectRemoved(event){const project=(event.data);for(const uiSourceCode of project.uiSourceCodes())
this._removeUISourceCode(uiSourceCode);}
_removeUISourceCode(uiSourceCode){this._loadingUISourceCodes.delete(uiSourceCode);const uiSourceCodeDiff=this._uiSourceCodeDiffs.get(uiSourceCode);if(uiSourceCodeDiff)
uiSourceCodeDiff._dispose=true;this._markAsUnmodified(uiSourceCode);}
_markAsUnmodified(uiSourceCode){this._uiSourceCodeProcessedForTest();if(this._modifiedUISourceCodes.delete(uiSourceCode))
this.dispatchEventToListeners(WorkspaceDiff.Events.ModifiedStatusChanged,{uiSourceCode,isModified:false});}
_markAsModified(uiSourceCode){this._uiSourceCodeProcessedForTest();if(this._modifiedUISourceCodes.has(uiSourceCode))
return;this._modifiedUISourceCodes.add(uiSourceCode);this.dispatchEventToListeners(WorkspaceDiff.Events.ModifiedStatusChanged,{uiSourceCode,isModified:true});}
_uiSourceCodeProcessedForTest(){}
async _updateModifiedState(uiSourceCode){this._loadingUISourceCodes.delete(uiSourceCode);if(uiSourceCode.project().type()!==Workspace.projectTypes.Network){this._markAsUnmodified(uiSourceCode);return;}
if(uiSourceCode.isDirty()){this._markAsModified(uiSourceCode);return;}
if(!uiSourceCode.hasCommits()){this._markAsUnmodified(uiSourceCode);return;}
const contentsPromise=Promise.all([this.requestOriginalContentForUISourceCode(uiSourceCode),uiSourceCode.requestContent()]);this._loadingUISourceCodes.set(uiSourceCode,contentsPromise);const contents=await contentsPromise;if(this._loadingUISourceCodes.get(uiSourceCode)!==contentsPromise)
return;this._loadingUISourceCodes.delete(uiSourceCode);if(contents[0]!==null&&contents[1]!==null&&contents[0]!==contents[1])
this._markAsModified(uiSourceCode);else
this._markAsUnmodified(uiSourceCode);}
requestOriginalContentForUISourceCode(uiSourceCode){return this._uiSourceCodeDiff(uiSourceCode)._originalContent();}
revertToOriginal(uiSourceCode){function callback(content){if(typeof content!=='string')
return;uiSourceCode.addRevision(content);}
Host.userMetrics.actionTaken(Host.UserMetrics.Action.RevisionApplied);return this.requestOriginalContentForUISourceCode(uiSourceCode).then(callback);}};WorkspaceDiff.WorkspaceDiff.UISourceCodeDiff=class extends Common.Object{constructor(uiSourceCode){super();this._uiSourceCode=uiSourceCode;uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._uiSourceCodeChanged,this);uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._uiSourceCodeChanged,this);this._requestDiffPromise=null;this._pendingChanges=null;this._dispose=false;}
_uiSourceCodeChanged(){if(this._pendingChanges){clearTimeout(this._pendingChanges);this._pendingChanges=null;}
this._requestDiffPromise=null;const content=this._uiSourceCode.content();const delay=(!content||content.length<65536)?0:WorkspaceDiff.WorkspaceDiff.UpdateTimeout;this._pendingChanges=setTimeout(emitDiffChanged.bind(this),delay);function emitDiffChanged(){if(this._dispose)
return;this.dispatchEventToListeners(WorkspaceDiff.Events.DiffChanged);this._pendingChanges=null;}}
requestDiff(){if(!this._requestDiffPromise)
this._requestDiffPromise=this._innerRequestDiff();return this._requestDiffPromise;}
_originalContent(){const originalNetworkContent=Persistence.networkPersistenceManager.originalContentForUISourceCode(this._uiSourceCode);if(originalNetworkContent)
return originalNetworkContent;let callback;const promise=new Promise(fulfill=>callback=fulfill);this._uiSourceCode.project().requestFileContent(this._uiSourceCode,callback);return promise;}
async _innerRequestDiff(){if(this._dispose)
return null;const baseline=await this._originalContent();if(baseline.length>1024*1024)
return null;if(this._dispose)
return null;let current=this._uiSourceCode.workingCopy();if(!current&&!this._uiSourceCode.contentLoaded())
current=await this._uiSourceCode.requestContent();if(current.length>1024*1024)
return null;if(this._dispose)
return null;if(current===null||baseline===null)
return null;return Diff.Diff.lineDiff(baseline.split(/\r\n|\n|\r/),current.split(/\r\n|\n|\r/));}};WorkspaceDiff.Events={DiffChanged:Symbol('DiffChanged'),ModifiedStatusChanged:Symbol('ModifiedStatusChanged')};WorkspaceDiff.workspaceDiff=function(){if(!WorkspaceDiff.WorkspaceDiff._instance)
WorkspaceDiff.WorkspaceDiff._instance=new WorkspaceDiff.WorkspaceDiff(Workspace.workspace);return WorkspaceDiff.WorkspaceDiff._instance;};WorkspaceDiff.DiffUILocation=class{constructor(uiSourceCode){this.uiSourceCode=uiSourceCode;}};WorkspaceDiff.WorkspaceDiff.UpdateTimeout=200;;// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* eslint-disable indent */
(function(window) {
// DevToolsAPI ----------------------------------------------------------------
/**
* @unrestricted
*/
const DevToolsAPIImpl = class {
constructor() {
/**
* @type {number}
*/
this._lastCallId = 0;
/**
* @type {!Object.<number, function(?Object)>}
*/
this._callbacks = {};
}
/**
* @param {number} id
* @param {?Object} arg
*/
embedderMessageAck(id, arg) {
const callback = this._callbacks[id];
delete this._callbacks[id];
if (callback)
callback(arg);
}
/**
* @param {string} method
* @param {!Array.<*>} args
* @param {?function(?Object)} callback
*/
sendMessageToEmbedder(method, args, callback) {
const callId = ++this._lastCallId;
if (callback)
this._callbacks[callId] = callback;
const message = {'id': callId, 'method': method};
if (args.length)
message.params = args;
DevToolsHost.sendMessageToEmbedder(JSON.stringify(message));
}
/**
* @param {string} method
* @param {!Array<*>} args
*/
_dispatchOnInspectorFrontendAPI(method, args) {
const inspectorFrontendAPI = /** @type {!Object<string, function()>} */ (window['InspectorFrontendAPI']);
inspectorFrontendAPI[method].apply(inspectorFrontendAPI, args);
}
// API methods below this line --------------------------------------------
/**
* @param {!Array.<!ExtensionDescriptor>} extensions
*/
addExtensions(extensions) {
// Support for legacy front-ends (<M41).
if (window['WebInspector'] && window['WebInspector']['addExtensions']) {
window['WebInspector']['addExtensions'](extensions);
} else if (window['InspectorFrontendAPI']) {
// The addExtensions command is sent as the onload event happens for
// DevTools front-end. In case of hosted mode, this
// happens before the InspectorFrontendAPI is initialized.
this._dispatchOnInspectorFrontendAPI('addExtensions', [extensions]);
}
}
/**
* @param {string} url
*/
appendedToURL(url) {
this._dispatchOnInspectorFrontendAPI('appendedToURL', [url]);
}
/**
* @param {string} url
*/
canceledSaveURL(url) {
this._dispatchOnInspectorFrontendAPI('canceledSaveURL', [url]);
}
contextMenuCleared() {
this._dispatchOnInspectorFrontendAPI('contextMenuCleared', []);
}
/**
* @param {string} id
*/
contextMenuItemSelected(id) {
this._dispatchOnInspectorFrontendAPI('contextMenuItemSelected', [id]);
}
/**
* @param {number} count
*/
deviceCountUpdated(count) {
this._dispatchOnInspectorFrontendAPI('deviceCountUpdated', [count]);
}
/**
* @param {!Adb.Config} config
*/
devicesDiscoveryConfigChanged(config) {
this._dispatchOnInspectorFrontendAPI('devicesDiscoveryConfigChanged', [config]);
}
/**
* @param {!Adb.PortForwardingStatus} status
*/
devicesPortForwardingStatusChanged(status) {
this._dispatchOnInspectorFrontendAPI('devicesPortForwardingStatusChanged', [status]);
}
/**
* @param {!Array.<!Adb.Device>} devices
*/
devicesUpdated(devices) {
this._dispatchOnInspectorFrontendAPI('devicesUpdated', [devices]);
}
/**
* @param {string} message
*/
dispatchMessage(message) {
this._dispatchOnInspectorFrontendAPI('dispatchMessage', [message]);
}
/**
* @param {string} messageChunk
* @param {number} messageSize
*/
dispatchMessageChunk(messageChunk, messageSize) {
this._dispatchOnInspectorFrontendAPI('dispatchMessageChunk', [messageChunk, messageSize]);
}
enterInspectElementMode() {
this._dispatchOnInspectorFrontendAPI('enterInspectElementMode', []);
}
/**
* @param {!{r: number, g: number, b: number, a: number}} color
*/
eyeDropperPickedColor(color) {
this._dispatchOnInspectorFrontendAPI('eyeDropperPickedColor', [color]);
}
/**
* @param {!Array.<!{fileSystemName: string, rootURL: string, fileSystemPath: string}>} fileSystems
*/
fileSystemsLoaded(fileSystems) {
this._dispatchOnInspectorFrontendAPI('fileSystemsLoaded', [fileSystems]);
}
/**
* @param {string} fileSystemPath
*/
fileSystemRemoved(fileSystemPath) {
this._dispatchOnInspectorFrontendAPI('fileSystemRemoved', [fileSystemPath]);
}
/**
* @param {?string} error
* @param {?{type: string, fileSystemName: string, rootURL: string, fileSystemPath: string}} fileSystem
*/
fileSystemAdded(error, fileSystem) {
this._dispatchOnInspectorFrontendAPI('fileSystemAdded', [error, fileSystem]);
}
/**
* @param {!Array<string>} changedPaths
* @param {!Array<string>} addedPaths
* @param {!Array<string>} removedPaths
*/
fileSystemFilesChangedAddedRemoved(changedPaths, addedPaths, removedPaths) {
// Support for legacy front-ends (<M58)
if (window['InspectorFrontendAPI'] && window['InspectorFrontendAPI']['fileSystemFilesChanged']) {
this._dispatchOnInspectorFrontendAPI(
'fileSystemFilesChanged', [changedPaths.concat(addedPaths).concat(removedPaths)]);
} else {
this._dispatchOnInspectorFrontendAPI(
'fileSystemFilesChangedAddedRemoved', [changedPaths, addedPaths, removedPaths]);
}
}
/**
* @param {number} requestId
* @param {string} fileSystemPath
* @param {number} totalWork
*/
indexingTotalWorkCalculated(requestId, fileSystemPath, totalWork) {
this._dispatchOnInspectorFrontendAPI('indexingTotalWorkCalculated', [requestId, fileSystemPath, totalWork]);
}
/**
* @param {number} requestId
* @param {string} fileSystemPath
* @param {number} worked
*/
indexingWorked(requestId, fileSystemPath, worked) {
this._dispatchOnInspectorFrontendAPI('indexingWorked', [requestId, fileSystemPath, worked]);
}
/**
* @param {number} requestId
* @param {string} fileSystemPath
*/
indexingDone(requestId, fileSystemPath) {
this._dispatchOnInspectorFrontendAPI('indexingDone', [requestId, fileSystemPath]);
}
/**
* @param {{type: string, key: string, code: string, keyCode: number, modifiers: number}} event
*/
keyEventUnhandled(event) {
event.keyIdentifier = keyCodeToKeyIdentifier(event.keyCode);
this._dispatchOnInspectorFrontendAPI('keyEventUnhandled', [event]);
}
/**
* @param {boolean} hard
*/
reloadInspectedPage(hard) {
this._dispatchOnInspectorFrontendAPI('reloadInspectedPage', [hard]);
}
/**
* @param {string} url
* @param {number} lineNumber
* @param {number} columnNumber
*/
revealSourceLine(url, lineNumber, columnNumber) {
this._dispatchOnInspectorFrontendAPI('revealSourceLine', [url, lineNumber, columnNumber]);
}
/**
* @param {string} url
* @param {string=} fileSystemPath
*/
savedURL(url, fileSystemPath) {
this._dispatchOnInspectorFrontendAPI('savedURL', [url, fileSystemPath]);
}
/**
* @param {number} requestId
* @param {string} fileSystemPath
* @param {!Array.<string>} files
*/
searchCompleted(requestId, fileSystemPath, files) {
this._dispatchOnInspectorFrontendAPI('searchCompleted', [requestId, fileSystemPath, files]);
}
/**
* @param {string} tabId
*/
setInspectedTabId(tabId) {
// Support for legacy front-ends (<M41).
if (window['WebInspector'] && window['WebInspector']['setInspectedTabId'])
window['WebInspector']['setInspectedTabId'](tabId);
else
this._dispatchOnInspectorFrontendAPI('setInspectedTabId', [tabId]);
}
/**
* @param {boolean} useSoftMenu
*/
setUseSoftMenu(useSoftMenu) {
this._dispatchOnInspectorFrontendAPI('setUseSoftMenu', [useSoftMenu]);
}
/**
* @param {string} panelName
*/
showPanel(panelName) {
this._dispatchOnInspectorFrontendAPI('showPanel', [panelName]);
}
/**
* @param {number} id
* @param {string} chunk
* @param {boolean} encoded
*/
streamWrite(id, chunk, encoded) {
this._dispatchOnInspectorFrontendAPI('streamWrite', [id, encoded ? this._decodeBase64(chunk) : chunk]);
}
/**
* @param {string} chunk
* @return {string}
*/
_decodeBase64(chunk) {
const request = new XMLHttpRequest();
request.open('GET', 'data:text/plain;base64,' + chunk, false);
request.send(null);
if (request.status === 200) {
return request.responseText;
} else {
console.error('Error while decoding chunk in streamWrite');
return '';
}
}
};
const DevToolsAPI = new DevToolsAPIImpl();
window.DevToolsAPI = DevToolsAPI;
// InspectorFrontendHostImpl --------------------------------------------------
/**
* @implements {InspectorFrontendHostAPI}
* @unrestricted
*/
const InspectorFrontendHostImpl = class {
/**
* @return {string}
*/
getSelectionBackgroundColor() {
return '#6e86ff';
}
/**
* @return {string}
*/
getSelectionForegroundColor() {
return '#ffffff';
}
/**
* @return {string}
*/
getInactiveSelectionBackgroundColor() {
return '#c9c8c8';
}
/**
* @return {string}
*/
getInactiveSelectionForegroundColor() {
return '#323232';
}
/**
* @override
* @return {string}
*/
platform() {
return DevToolsHost.platform();
}
/**
* @override
*/
loadCompleted() {
DevToolsAPI.sendMessageToEmbedder('loadCompleted', [], null);
// Support for legacy (<57) frontends.
if (window.Runtime && window.Runtime.queryParam) {
const panelToOpen = window.Runtime.queryParam('panel');
if (panelToOpen)
window.DevToolsAPI.showPanel(panelToOpen);
}
}
/**
* @override
*/
bringToFront() {
DevToolsAPI.sendMessageToEmbedder('bringToFront', [], null);
}
/**
* @override
*/
closeWindow() {
DevToolsAPI.sendMessageToEmbedder('closeWindow', [], null);
}
/**
* @override
* @param {boolean} isDocked
* @param {function()} callback
*/
setIsDocked(isDocked, callback) {
DevToolsAPI.sendMessageToEmbedder('setIsDocked', [isDocked], callback);
}
/**
* Requests inspected page to be placed atop of the inspector frontend with specified bounds.
* @override
* @param {{x: number, y: number, width: number, height: number}} bounds
*/
setInspectedPageBounds(bounds) {
DevToolsAPI.sendMessageToEmbedder('setInspectedPageBounds', [bounds], null);
}
/**
* @override
*/
inspectElementCompleted() {
DevToolsAPI.sendMessageToEmbedder('inspectElementCompleted', [], null);
}
/**
* @override
* @param {string} url
* @param {string} headers
* @param {number} streamId
* @param {function(!InspectorFrontendHostAPI.LoadNetworkResourceResult)} callback
*/
loadNetworkResource(url, headers, streamId, callback) {
DevToolsAPI.sendMessageToEmbedder(
'loadNetworkResource', [url, headers, streamId], /** @type {function(?Object)} */ (callback));
}
/**
* @override
* @param {function(!Object<string, string>)} callback
*/
getPreferences(callback) {
DevToolsAPI.sendMessageToEmbedder('getPreferences', [], /** @type {function(?Object)} */ (callback));
}
/**
* @override
* @param {string} name
* @param {string} value
*/
setPreference(name, value) {
DevToolsAPI.sendMessageToEmbedder('setPreference', [name, value], null);
}
/**
* @override
* @param {string} name
*/
removePreference(name) {
DevToolsAPI.sendMessageToEmbedder('removePreference', [name], null);
}
/**
* @override
*/
clearPreferences() {
DevToolsAPI.sendMessageToEmbedder('clearPreferences', [], null);
}
/**
* @override
* @param {string} origin
* @param {string} script
*/
setInjectedScriptForOrigin(origin, script) {
DevToolsAPI.sendMessageToEmbedder('registerExtensionsAPI', [origin, script], null);
}
/**
* @override
* @param {string} url
*/
inspectedURLChanged(url) {
DevToolsAPI.sendMessageToEmbedder('inspectedURLChanged', [url], null);
}
/**
* @override
* @param {string} text
*/
copyText(text) {
DevToolsHost.copyText(text);
}
/**
* @override
* @param {string} url
*/
openInNewTab(url) {
DevToolsAPI.sendMessageToEmbedder('openInNewTab', [url], null);
}
/**
* @override
* @param {string} fileSystemPath
*/
showItemInFolder(fileSystemPath) {
DevToolsAPI.sendMessageToEmbedder('showItemInFolder', [fileSystemPath], null);
}
/**
* @override
* @param {string} url
* @param {string} content
* @param {boolean} forceSaveAs
*/
save(url, content, forceSaveAs) {
DevToolsAPI.sendMessageToEmbedder('save', [url, content, forceSaveAs], null);
}
/**
* @override
* @param {string} url
* @param {string} content
*/
append(url, content) {
DevToolsAPI.sendMessageToEmbedder('append', [url, content], null);
}
/**
* @override
* @param {string} url
*/
close(url) {
}
/**
* @override
* @param {string} message
*/
sendMessageToBackend(message) {
DevToolsAPI.sendMessageToEmbedder('dispatchProtocolMessage', [message], null);
}
/**
* @override
* @param {string} actionName
* @param {number} actionCode
* @param {number} bucketSize
*/
recordEnumeratedHistogram(actionName, actionCode, bucketSize) {
// Support for M49 frontend.
if (actionName === 'DevTools.DrawerShown')
return;
DevToolsAPI.sendMessageToEmbedder('recordEnumeratedHistogram', [actionName, actionCode, bucketSize], null);
}
/**
* @override
* @param {string} histogramName
* @param {number} duration
*/
recordPerformanceHistogram(histogramName, duration) {
DevToolsAPI.sendMessageToEmbedder('recordPerformanceHistogram', [histogramName, duration], null);
}
/**
* @override
* @param {string} umaName
*/
recordUserMetricsAction(umaName) {
DevToolsAPI.sendMessageToEmbedder('recordUserMetricsAction', [umaName], null);
}
/**
* @override
*/
requestFileSystems() {
DevToolsAPI.sendMessageToEmbedder('requestFileSystems', [], null);
}
/**
* @override
* @param {string=} type
*/
addFileSystem(type) {
DevToolsAPI.sendMessageToEmbedder('addFileSystem', [type || ''], null);
}
/**
* @override
* @param {string} fileSystemPath
*/
removeFileSystem(fileSystemPath) {
DevToolsAPI.sendMessageToEmbedder('removeFileSystem', [fileSystemPath], null);
}
/**
* @override
* @param {string} fileSystemId
* @param {string} registeredName
* @return {?DOMFileSystem}
*/
isolatedFileSystem(fileSystemId, registeredName) {
return DevToolsHost.isolatedFileSystem(fileSystemId, registeredName);
}
/**
* @override
* @param {!FileSystem} fileSystem
*/
upgradeDraggedFileSystemPermissions(fileSystem) {
DevToolsHost.upgradeDraggedFileSystemPermissions(fileSystem);
}
/**
* @override
* @param {number} requestId
* @param {string} fileSystemPath
* @param {string} excludedFolders
*/
indexPath(requestId, fileSystemPath, excludedFolders) {
// |excludedFolders| added in M67. For backward compatibility,
// pass empty array.
excludedFolders = excludedFolders || '[]';
DevToolsAPI.sendMessageToEmbedder('indexPath', [requestId, fileSystemPath, excludedFolders], null);
}
/**
* @override
* @param {number} requestId
*/
stopIndexing(requestId) {
DevToolsAPI.sendMessageToEmbedder('stopIndexing', [requestId], null);
}
/**
* @override
* @param {number} requestId
* @param {string} fileSystemPath
* @param {string} query
*/
searchInPath(requestId, fileSystemPath, query) {
DevToolsAPI.sendMessageToEmbedder('searchInPath', [requestId, fileSystemPath, query], null);
}
/**
* @override
* @return {number}
*/
zoomFactor() {
return DevToolsHost.zoomFactor();
}
/**
* @override
*/
zoomIn() {
DevToolsAPI.sendMessageToEmbedder('zoomIn', [], null);
}
/**
* @override
*/
zoomOut() {
DevToolsAPI.sendMessageToEmbedder('zoomOut', [], null);
}
/**
* @override
*/
resetZoom() {
DevToolsAPI.sendMessageToEmbedder('resetZoom', [], null);
}
/**
* @override
* @param {string} shortcuts
*/
setWhitelistedShortcuts(shortcuts) {
DevToolsAPI.sendMessageToEmbedder('setWhitelistedShortcuts', [shortcuts], null);
}
/**
* @override
* @param {boolean} active
*/
setEyeDropperActive(active) {
DevToolsAPI.sendMessageToEmbedder('setEyeDropperActive', [active], null);
}
/**
* @override
* @param {!Array<string>} certChain
*/
showCertificateViewer(certChain) {
DevToolsAPI.sendMessageToEmbedder('showCertificateViewer', [JSON.stringify(certChain)], null);
}
/**
* @override
* @param {function()} callback
*/
reattach(callback) {
DevToolsAPI.sendMessageToEmbedder('reattach', [], callback);
}
/**
* @override
*/
readyForTest() {
DevToolsAPI.sendMessageToEmbedder('readyForTest', [], null);
}
/**
* @override
*/
connectionReady() {
DevToolsAPI.sendMessageToEmbedder('connectionReady', [], null);
}
/**
* @override
* @param {boolean} value
*/
setOpenNewWindowForPopups(value) {
DevToolsAPI.sendMessageToEmbedder('setOpenNewWindowForPopups', [value], null);
}
/**
* @override
* @param {!Adb.Config} config
*/
setDevicesDiscoveryConfig(config) {
DevToolsAPI.sendMessageToEmbedder(
'setDevicesDiscoveryConfig',
[
config.discoverUsbDevices, config.portForwardingEnabled, JSON.stringify(config.portForwardingConfig),
config.networkDiscoveryEnabled, JSON.stringify(config.networkDiscoveryConfig)
],
null);
}
/**
* @override
* @param {boolean} enabled
*/
setDevicesUpdatesEnabled(enabled) {
DevToolsAPI.sendMessageToEmbedder('setDevicesUpdatesEnabled', [enabled], null);
}
/**
* @override
* @param {string} pageId
* @param {string} action
*/
performActionOnRemotePage(pageId, action) {
DevToolsAPI.sendMessageToEmbedder('performActionOnRemotePage', [pageId, action], null);
}
/**
* @override
* @param {string} browserId
* @param {string} url
*/
openRemotePage(browserId, url) {
DevToolsAPI.sendMessageToEmbedder('openRemotePage', [browserId, url], null);
}
/**
* @override
*/
openNodeFrontend() {
DevToolsAPI.sendMessageToEmbedder('openNodeFrontend', [], null);
}
/**
* @override
* @param {number} x
* @param {number} y
* @param {!Array.<!InspectorFrontendHostAPI.ContextMenuDescriptor>} items
* @param {!Document} document
*/
showContextMenuAtPoint(x, y, items, document) {
DevToolsHost.showContextMenuAtPoint(x, y, items, document);
}
/**
* @override
* @return {boolean}
*/
isHostedMode() {
return DevToolsHost.isHostedMode();
}
// Backward-compatible methods below this line --------------------------------------------
/**
* Support for legacy front-ends (<M65).
* @return {boolean}
*/
isUnderTest() {
return false;
}
/**
* Support for legacy front-ends (<M50).
* @param {string} message
*/
sendFrontendAPINotification(message) {
}
/**
* Support for legacy front-ends (<M41).
* @return {string}
*/
port() {
return 'unknown';
}
/**
* Support for legacy front-ends (<M38).
* @param {number} zoomFactor
*/
setZoomFactor(zoomFactor) {
}
/**
* Support for legacy front-ends (<M34).
*/
sendMessageToEmbedder() {
}
/**
* Support for legacy front-ends (<M34).
* @param {string} dockSide
*/
requestSetDockSide(dockSide) {
DevToolsAPI.sendMessageToEmbedder('setIsDocked', [dockSide !== 'undocked'], null);
}
/**
* Support for legacy front-ends (<M34).
* @return {boolean}
*/
supportsFileSystems() {
return true;
}
/**
* Support for legacy front-ends (<M44).
* @param {number} actionCode
*/
recordActionTaken(actionCode) {
this.recordEnumeratedHistogram('DevTools.ActionTaken', actionCode, 100);
}
/**
* Support for legacy front-ends (<M44).
* @param {number} panelCode
*/
recordPanelShown(panelCode) {
this.recordEnumeratedHistogram('DevTools.PanelShown', panelCode, 20);
}
};
window.InspectorFrontendHost = new InspectorFrontendHostImpl();
// DevToolsApp ---------------------------------------------------------------
function installObjectObserve() {
/** @type {!Array<string>} */
const properties = [
'advancedSearchConfig',
'auditsPanelSplitViewState',
'auditsSidebarWidth',
'blockedURLs',
'breakpoints',
'cacheDisabled',
'colorFormat',
'consoleHistory',
'consoleTimestampsEnabled',
'cpuProfilerView',
'cssSourceMapsEnabled',
'currentDockState',
'customColorPalette',
'customDevicePresets',
'customEmulatedDeviceList',
'customFormatters',
'customUserAgent',
'databaseTableViewVisibleColumns',
'dataGrid-cookiesTable',
'dataGrid-DOMStorageItemsView',
'debuggerSidebarHidden',
'disableDataSaverInfobar',
'disablePausedStateOverlay',
'domBreakpoints',
'domWordWrap',
'elementsPanelSplitViewState',
'elementsSidebarWidth',
'emulation.deviceHeight',
'emulation.deviceModeValue',
'emulation.deviceOrientationOverride',
'emulation.deviceScale',
'emulation.deviceScaleFactor',
'emulation.deviceUA',
'emulation.deviceWidth',
'emulation.geolocationOverride',
'emulation.showDeviceMode',
'emulation.showRulers',
'enableAsyncStackTraces',
'eventListenerBreakpoints',
'fileMappingEntries',
'fileSystemMapping',
'FileSystemViewSidebarWidth',
'fileSystemViewSplitViewState',
'filterBar-consoleView',
'filterBar-networkPanel',
'filterBar-promisePane',
'filterBar-timelinePanel',
'frameViewerHideChromeWindow',
'heapSnapshotRetainersViewSize',
'heapSnapshotSplitViewState',
'hideCollectedPromises',
'hideNetworkMessages',
'highlightNodeOnHoverInOverlay',
'highResolutionCpuProfiling',
'inlineVariableValues',
'Inspector.drawerSplitView',
'Inspector.drawerSplitViewState',
'InspectorView.panelOrder',
'InspectorView.screencastSplitView',
'InspectorView.screencastSplitViewState',
'InspectorView.splitView',
'InspectorView.splitViewState',
'javaScriptDisabled',
'jsSourceMapsEnabled',
'lastActivePanel',
'lastDockState',
'lastSelectedSourcesSidebarPaneTab',
'lastSnippetEvaluationIndex',
'layerDetailsSplitView',
'layerDetailsSplitViewState',
'layersPanelSplitViewState',
'layersShowInternalLayers',
'layersSidebarWidth',
'messageLevelFilters',
'messageURLFilters',
'monitoringXHREnabled',
'navigatorGroupByFolder',
'navigatorHidden',
'networkColorCodeResourceTypes',
'networkConditions',
'networkConditionsCustomProfiles',
'networkHideDataURL',
'networkLogColumnsVisibility',
'networkLogLargeRows',
'networkLogShowOverview',
'networkPanelSplitViewState',
'networkRecordFilmStripSetting',
'networkResourceTypeFilters',
'networkShowPrimaryLoadWaterfall',
'networkSidebarWidth',
'openLinkHandler',
'pauseOnCaughtException',
'pauseOnExceptionEnabled',
'preserveConsoleLog',
'prettyPrintInfobarDisabled',
'previouslyViewedFiles',
'profilesPanelSplitViewState',
'profilesSidebarWidth',
'promiseStatusFilters',
'recordAllocationStacks',
'requestHeaderFilterSetting',
'request-info-formData-category-expanded',
'request-info-general-category-expanded',
'request-info-queryString-category-expanded',
'request-info-requestHeaders-category-expanded',
'request-info-requestPayload-category-expanded',
'request-info-responseHeaders-category-expanded',
'resources',
'resourcesLastSelectedItem',
'resourcesPanelSplitViewState',
'resourcesSidebarWidth',
'resourceViewTab',
'savedURLs',
'screencastEnabled',
'scriptsPanelNavigatorSidebarWidth',
'searchInContentScripts',
'selectedAuditCategories',
'selectedColorPalette',
'selectedProfileType',
'shortcutPanelSwitch',
'showAdvancedHeapSnapshotProperties',
'showEventListenersForAncestors',
'showFrameowkrListeners',
'showHeaSnapshotObjectsHiddenProperties',
'showInheritedComputedStyleProperties',
'showMediaQueryInspector',
'showNativeFunctionsInJSProfile',
'showUAShadowDOM',
'showWhitespacesInEditor',
'sidebarPosition',
'skipContentScripts',
'skipStackFramesPattern',
'sourceMapInfobarDisabled',
'sourcesPanelDebuggerSidebarSplitViewState',
'sourcesPanelNavigatorSplitViewState',
'sourcesPanelSplitSidebarRatio',
'sourcesPanelSplitViewState',
'sourcesSidebarWidth',
'standardEmulatedDeviceList',
'StylesPaneSplitRatio',
'stylesPaneSplitViewState',
'textEditorAutocompletion',
'textEditorAutoDetectIndent',
'textEditorBracketMatching',
'textEditorIndent',
'textEditorTabMovesFocus',
'timelineCaptureFilmStrip',
'timelineCaptureLayersAndPictures',
'timelineCaptureMemory',
'timelineCaptureNetwork',
'timeline-details',
'timelineEnableJSSampling',
'timelineOverviewMode',
'timelinePanelDetailsSplitViewState',
'timelinePanelRecorsSplitViewState',
'timelinePanelTimelineStackSplitViewState',
'timelinePerspective',
'timeline-split',
'timelineTreeGroupBy',
'timeline-view',
'timelineViewMode',
'uiTheme',
'watchExpressions',
'WebInspector.Drawer.lastSelectedView',
'WebInspector.Drawer.showOnLoad',
'workspaceExcludedFolders',
'workspaceFolderExcludePattern',
'workspaceInfobarDisabled',
'workspaceMappingInfobarDisabled',
'xhrBreakpoints'
];
/**
* @this {!{_storage: Object, _name: string}}
*/
function settingRemove() {
this._storage[this._name] = undefined;
}
/**
* @param {!Object} object
* @param {function(!Array<!{name: string}>)} observer
*/
function objectObserve(object, observer) {
if (window['WebInspector']) {
const settingPrototype = /** @type {!Object} */ (window['WebInspector']['Setting']['prototype']);
if (typeof settingPrototype['remove'] === 'function')
settingPrototype['remove'] = settingRemove;
}
/** @type {!Set<string>} */
const changedProperties = new Set();
let scheduled = false;
function scheduleObserver() {
if (scheduled)
return;
scheduled = true;
setImmediate(callObserver);
}
function callObserver() {
scheduled = false;
const changes = /** @type {!Array<!{name: string}>} */ ([]);
changedProperties.forEach(function(name) {
changes.push({name: name});
});
changedProperties.clear();
observer.call(null, changes);
}
/** @type {!Map<string, *>} */
const storage = new Map();
/**
* @param {string} property
*/
function defineProperty(property) {
if (property in object) {
storage.set(property, object[property]);
delete object[property];
}
Object.defineProperty(object, property, {
/**
* @return {*}
*/
get: function() {
return storage.get(property);
},
/**
* @param {*} value
*/
set: function(value) {
storage.set(property, value);
changedProperties.add(property);
scheduleObserver();
}
});
}
for (let i = 0; i < properties.length; ++i)
defineProperty(properties[i]);
}
window.Object.observe = objectObserve;
}
/** @type {!Map<number, string>} */
const staticKeyIdentifiers = new Map([
[0x12, 'Alt'],
[0x11, 'Control'],
[0x10, 'Shift'],
[0x14, 'CapsLock'],
[0x5b, 'Win'],
[0x5c, 'Win'],
[0x0c, 'Clear'],
[0x28, 'Down'],
[0x23, 'End'],
[0x0a, 'Enter'],
[0x0d, 'Enter'],
[0x2b, 'Execute'],
[0x70, 'F1'],
[0x71, 'F2'],
[0x72, 'F3'],
[0x73, 'F4'],
[0x74, 'F5'],
[0x75, 'F6'],
[0x76, 'F7'],
[0x77, 'F8'],
[0x78, 'F9'],
[0x79, 'F10'],
[0x7a, 'F11'],
[0x7b, 'F12'],
[0x7c, 'F13'],
[0x7d, 'F14'],
[0x7e, 'F15'],
[0x7f, 'F16'],
[0x80, 'F17'],
[0x81, 'F18'],
[0x82, 'F19'],
[0x83, 'F20'],
[0x84, 'F21'],
[0x85, 'F22'],
[0x86, 'F23'],
[0x87, 'F24'],
[0x2f, 'Help'],
[0x24, 'Home'],
[0x2d, 'Insert'],
[0x25, 'Left'],
[0x22, 'PageDown'],
[0x21, 'PageUp'],
[0x13, 'Pause'],
[0x2c, 'PrintScreen'],
[0x27, 'Right'],
[0x91, 'Scroll'],
[0x29, 'Select'],
[0x26, 'Up'],
[0x2e, 'U+007F'], // Standard says that DEL becomes U+007F.
[0xb0, 'MediaNextTrack'],
[0xb1, 'MediaPreviousTrack'],
[0xb2, 'MediaStop'],
[0xb3, 'MediaPlayPause'],
[0xad, 'VolumeMute'],
[0xae, 'VolumeDown'],
[0xaf, 'VolumeUp'],
]);
/**
* @param {number} keyCode
* @return {string}
*/
function keyCodeToKeyIdentifier(keyCode) {
let result = staticKeyIdentifiers.get(keyCode);
if (result !== undefined)
return result;
result = 'U+';
const hexString = keyCode.toString(16).toUpperCase();
for (let i = hexString.length; i < 4; ++i)
result += '0';
result += hexString;
return result;
}
function installBackwardsCompatibility() {
const majorVersion = getRemoteMajorVersion();
if (!majorVersion)
return;
/** @type {!Array<string>} */
const styleRules = [];
// Shadow DOM V0 polyfill
if (majorVersion <= 73 && !Element.prototype.createShadowRoot) {
Element.prototype.createShadowRoot = function() {
try {
return this.attachShadow({mode: 'open'});
} catch (e) {
// some elements we use to add shadow roots can no
// longer have shadow roots.
const fakeShadowHost = document.createElement('span');
this.appendChild(fakeShadowHost);
fakeShadowHost.className = 'fake-shadow-host';
return fakeShadowHost.createShadowRoot();
}
};
const origAdd = DOMTokenList.prototype.add;
DOMTokenList.prototype.add = function(...tokens) {
if (tokens[0].startsWith('insertion-point') || tokens[0].startsWith('tabbed-pane-header'))
this._myElement.slot = '.' + tokens[0];
return origAdd.apply(this, tokens);
};
const origCreateElement = Document.prototype.createElement;
Document.prototype.createElement = function(tagName, ...rest) {
if (tagName === 'content')
tagName = 'slot';
const element = origCreateElement.call(this, tagName, ...rest);
element.classList._myElement = element;
return element;
};
Object.defineProperty(HTMLSlotElement.prototype, 'select', {
async set(selector) {
this.name = selector;
}
});
// Document.prototype.createElementWithClass is a DevTools method, so we
// need to wait for DOMContentLoaded in order to override it.
if (window.document.head &&
(window.document.readyState === 'complete' || window.document.readyState === 'interactive'))
overrideCreateElementWithClass();
else
window.addEventListener('DOMContentLoaded', overrideCreateElementWithClass);
function overrideCreateElementWithClass() {
window.removeEventListener('DOMContentLoaded', overrideCreateElementWithClass);
const origCreateElementWithClass = Document.prototype.createElementWithClass;
Document.prototype.createElementWithClass = function(tagName, className, ...rest) {
if (tagName !== 'button' || (className !== 'soft-dropdown' && className !== 'dropdown-button'))
return origCreateElementWithClass.call(this, tagName, className, ...rest);
const element = origCreateElementWithClass.call(this, 'div', className, ...rest);
element.tabIndex = 0;
element.role = 'button';
return element;
};
}
}
// Custom Elements V0 polyfill
if (majorVersion <= 73 && !Document.prototype.registerElement) {
const fakeRegistry = new Map();
Document.prototype.registerElement = function(typeExtension, options) {
const {prototype, extends: localName} = options;
const document = this;
const callback = function() {
const element = document.createElement(localName || typeExtension);
const skip = new Set(['constructor', '__proto__']);
for (const key of Object.keys(Object.getOwnPropertyDescriptors(prototype.__proto__ || {}))) {
if (skip.has(key))
continue;
element[key] = prototype[key];
}
element.setAttribute('is', typeExtension);
if (element['createdCallback'])
element['createdCallback']();
return element;
};
fakeRegistry.set(typeExtension, callback);
return callback;
};
const origCreateElement = Document.prototype.createElement;
Document.prototype.createElement = function(tagName, fakeCustomElementType) {
const fakeConstructor = fakeRegistry.get(fakeCustomElementType);
if (fakeConstructor)
return fakeConstructor();
return origCreateElement.call(this, tagName, fakeCustomElementType);
};
// DevTools front-ends mistakenly assume that
// classList.toggle('a', undefined) works as
// classList.toggle('a', false) rather than as
// classList.toggle('a');
const originalDOMTokenListToggle = DOMTokenList.prototype.toggle;
DOMTokenList.prototype.toggle = function(token, force) {
if (arguments.length === 1)
force = !this.contains(token);
return originalDOMTokenListToggle.call(this, token, !!force);
};
}
if (majorVersion <= 66) {
/** @type {(!function(number, number):Element|undefined)} */
ShadowRoot.prototype.__originalShadowRootElementFromPoint;
if (!ShadowRoot.prototype.__originalShadowRootElementFromPoint) {
ShadowRoot.prototype.__originalShadowRootElementFromPoint = ShadowRoot.prototype.elementFromPoint;
/**
* @param {number} x
* @param {number} y
* @return {Element}
*/
ShadowRoot.prototype.elementFromPoint = function(x, y) {
const originalResult = ShadowRoot.prototype.__originalShadowRootElementFromPoint.apply(this, arguments);
if (this.host && originalResult === this.host)
return null;
return originalResult;
};
}
}
if (majorVersion <= 53) {
Object.defineProperty(window.KeyboardEvent.prototype, 'keyIdentifier', {
/**
* @return {string}
* @this {KeyboardEvent}
*/
get: function() {
return keyCodeToKeyIdentifier(this.keyCode);
}
});
}
if (majorVersion <= 50)
installObjectObserve();
if (majorVersion <= 45) {
/**
* @param {string} property
* @return {!CSSValue|null}
* @this {CSSStyleDeclaration}
*/
function getValue(property) {
// Note that |property| comes from another context, so we can't use === here.
// eslint-disable-next-line eqeqeq
if (property == 'padding-left') {
return /** @type {!CSSValue} */ ({
/**
* @return {number}
* @this {!{__paddingLeft: number}}
*/
getFloatValue: function() {
return this.__paddingLeft;
},
__paddingLeft: parseFloat(this.paddingLeft)
});
}
throw new Error('getPropertyCSSValue is undefined');
}
window.CSSStyleDeclaration.prototype.getPropertyCSSValue = getValue;
function CSSPrimitiveValue() {
}
CSSPrimitiveValue.CSS_PX = 5;
window.CSSPrimitiveValue = CSSPrimitiveValue;
}
if (majorVersion <= 45)
styleRules.push('* { min-width: 0; min-height: 0; }');
if (majorVersion <= 51) {
// Support for quirky border-image behavior (<M51), see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=559258
styleRules.push('.cm-breakpoint .CodeMirror-linenumber { border-style: solid !important; }');
styleRules.push(
'.cm-breakpoint.cm-breakpoint-conditional .CodeMirror-linenumber { border-style: solid !important; }');
}
if (majorVersion <= 71) {
styleRules.push(
'.coverage-toolbar-container, .animation-timeline-toolbar-container, .computed-properties { flex-basis: auto; }');
}
if (majorVersion <= 50)
Event.prototype.deepPath = undefined;
if (majorVersion <= 54) {
window.FileError = /** @type {!function (new: FileError) : ?} */ ({
NOT_FOUND_ERR: DOMException.NOT_FOUND_ERR,
ABORT_ERR: DOMException.ABORT_ERR,
INVALID_MODIFICATION_ERR: DOMException.INVALID_MODIFICATION_ERR,
NOT_READABLE_ERR: 0 // No matching DOMException, so code will be 0.
});
}
installExtraStyleRules(styleRules);
}
/**
* @return {?number}
*/
function getRemoteMajorVersion() {
try {
const remoteVersion = new URLSearchParams(window.location.search).get('remoteVersion');
if (!remoteVersion)
return null;
const majorVersion = parseInt(remoteVersion.split('.')[0], 10);
return majorVersion;
} catch (e) {
return null;
}
}
/**
* @param {!Array<string>} styleRules
*/
function installExtraStyleRules(styleRules) {
if (!styleRules.length)
return;
const styleText = styleRules.join('\n');
document.head.appendChild(createStyleElement(styleText));
const origCreateShadowRoot = HTMLElement.prototype.createShadowRoot;
HTMLElement.prototype.createShadowRoot = function(...args) {
const shadowRoot = origCreateShadowRoot.call(this, ...args);
shadowRoot.appendChild(createStyleElement(styleText));
return shadowRoot;
};
}
/**
* @param {string} styleText
* @return {!Element}
*/
function createStyleElement(styleText) {
const style = document.createElement('style');
style.type = 'text/css';
style.textContent = styleText;
return style;
}
installBackwardsCompatibility();
})(window);
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* eslint-disable indent */
/**
* @fileoverview This file contains small testing framework along with the
* test suite for the frontend. These tests are a part of the continues build
* and are executed by the devtools_sanity_unittest.cc as a part of the
* Interactive UI Test suite.
* FIXME: change field naming style to use trailing underscore.
*/
(function createTestSuite(window) {
/**
* @unrestricted
*/
const TestSuite = class {
/**
* Test suite for interactive UI tests.
* @param {Object} domAutomationController DomAutomationController instance.
*/
constructor(domAutomationController) {
this.domAutomationController_ = domAutomationController;
this.controlTaken_ = false;
this.timerId_ = -1;
this._asyncInvocationId = 0;
}
/**
* Key event with given key identifier.
*/
static createKeyEvent(key) {
return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: key});
}
};
/**
* Reports test failure.
* @param {string} message Failure description.
*/
TestSuite.prototype.fail = function(message) {
if (this.controlTaken_)
this.reportFailure_(message);
else
throw message;
};
/**
* Equals assertion tests that expected === actual.
* @param {!Object|boolean} expected Expected object.
* @param {!Object|boolean} actual Actual object.
* @param {string} opt_message User message to print if the test fails.
*/
TestSuite.prototype.assertEquals = function(expected, actual, opt_message) {
if (expected !== actual) {
let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\'';
if (opt_message)
message = opt_message + '(' + message + ')';
this.fail(message);
}
};
/**
* True assertion tests that value == true.
* @param {!Object} value Actual object.
* @param {string} opt_message User message to print if the test fails.
*/
TestSuite.prototype.assertTrue = function(value, opt_message) {
this.assertEquals(true, !!value, opt_message);
};
/**
* Takes control over execution.
*/
TestSuite.prototype.takeControl = function() {
this.controlTaken_ = true;
// Set up guard timer.
const self = this;
this.timerId_ = setTimeout(function() {
self.reportFailure_('Timeout exceeded: 20 sec');
}, 20000);
};
/**
* Releases control over execution.
*/
TestSuite.prototype.releaseControl = function() {
if (this.timerId_ !== -1) {
clearTimeout(this.timerId_);
this.timerId_ = -1;
}
this.controlTaken_ = false;
this.reportOk_();
};
/**
* Async tests use this one to report that they are completed.
*/
TestSuite.prototype.reportOk_ = function() {
this.domAutomationController_.send('[OK]');
};
/**
* Async tests use this one to report failures.
*/
TestSuite.prototype.reportFailure_ = function(error) {
if (this.timerId_ !== -1) {
clearTimeout(this.timerId_);
this.timerId_ = -1;
}
this.domAutomationController_.send('[FAILED] ' + error);
};
/**
* Run specified test on a fresh instance of the test suite.
* @param {Array<string>} args method name followed by its parameters.
*/
TestSuite.prototype.dispatchOnTestSuite = function(args) {
const methodName = args.shift();
try {
this[methodName].apply(this, args);
if (!this.controlTaken_)
this.reportOk_();
} catch (e) {
this.reportFailure_(e);
}
};
/**
* Wrap an async method with TestSuite.{takeControl(), releaseControl()}
* and invoke TestSuite.reportOk_ upon completion.
* @param {Array<string>} args method name followed by its parameters.
*/
TestSuite.prototype.waitForAsync = function(var_args) {
const args = Array.prototype.slice.call(arguments);
this.takeControl();
args.push(this.releaseControl.bind(this));
this.dispatchOnTestSuite(args);
};
/**
* Overrides the method with specified name until it's called first time.
* @param {!Object} receiver An object whose method to override.
* @param {string} methodName Name of the method to override.
* @param {!Function} override A function that should be called right after the
* overridden method returns.
* @param {?boolean} opt_sticky Whether restore original method after first run
* or not.
*/
TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) {
const orig = receiver[methodName];
if (typeof orig !== 'function')
this.fail('Cannot find method to override: ' + methodName);
const test = this;
receiver[methodName] = function(var_args) {
let result;
try {
result = orig.apply(this, arguments);
} finally {
if (!opt_sticky)
receiver[methodName] = orig;
}
// In case of exception the override won't be called.
try {
override.apply(this, arguments);
} catch (e) {
test.fail('Exception in overriden method \'' + methodName + '\': ' + e);
}
return result;
};
};
/**
* Waits for current throttler invocations, if any.
* @param {!Common.Throttler} throttler
* @param {function()} callback
*/
TestSuite.prototype.waitForThrottler = function(throttler, callback) {
const test = this;
let scheduleShouldFail = true;
test.addSniffer(throttler, 'schedule', onSchedule);
function hasSomethingScheduled() {
return throttler._isRunningProcess || throttler._process;
}
function checkState() {
if (!hasSomethingScheduled()) {
scheduleShouldFail = false;
callback();
return;
}
test.addSniffer(throttler, '_processCompletedForTests', checkState);
}
function onSchedule() {
if (scheduleShouldFail)
test.fail('Unexpected Throttler.schedule');
}
checkState();
};
/**
* @param {string} panelName Name of the panel to show.
*/
TestSuite.prototype.showPanel = function(panelName) {
return UI.inspectorView.showPanel(panelName);
};
// UI Tests
/**
* Tests that scripts tab can be open and populated with inspected scripts.
*/
TestSuite.prototype.testShowScriptsTab = function() {
const test = this;
this.showPanel('sources').then(function() {
// There should be at least main page script.
this._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
test.releaseControl();
});
}.bind(this));
// Wait until all scripts are added to the debugger.
this.takeControl();
};
/**
* Tests that scripts tab is populated with inspected scripts even if it
* hadn't been shown by the moment inspected paged refreshed.
* @see http://crbug.com/26312
*/
TestSuite.prototype.testScriptsTabIsPopulatedOnInspectedPageRefresh = function() {
const test = this;
const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
this.showPanel('elements').then(function() {
// Reload inspected page. It will reset the debugger agent.
test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
});
function waitUntilScriptIsParsed() {
debuggerModel.removeEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
test.showPanel('sources').then(function() {
test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
test.releaseControl();
});
});
}
// Wait until all scripts are added to the debugger.
this.takeControl();
};
/**
* Tests that scripts list contains content scripts.
*/
TestSuite.prototype.testContentScriptIsPresent = function() {
const test = this;
this.showPanel('sources').then(function() {
test._waitUntilScriptsAreParsed(['page_with_content_script.html', 'simple_content_script.js'], function() {
test.releaseControl();
});
});
// Wait until all scripts are added to the debugger.
this.takeControl();
};
/**
* Tests that scripts are not duplicaed on Scripts tab switch.
*/
TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() {
const test = this;
function switchToElementsTab() {
test.showPanel('elements').then(function() {
setTimeout(switchToScriptsTab, 0);
});
}
function switchToScriptsTab() {
test.showPanel('sources').then(function() {
setTimeout(checkScriptsPanel, 0);
});
}
function checkScriptsPanel() {
test.assertTrue(test._scriptsAreParsed(['debugger_test_page.html']), 'Some scripts are missing.');
checkNoDuplicates();
test.releaseControl();
}
function checkNoDuplicates() {
const uiSourceCodes = test.nonAnonymousUISourceCodes_();
for (let i = 0; i < uiSourceCodes.length; i++) {
for (let j = i + 1; j < uiSourceCodes.length; j++) {
test.assertTrue(
uiSourceCodes[i].url() !== uiSourceCodes[j].url(),
'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes));
}
}
}
this.showPanel('sources').then(function() {
test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
checkNoDuplicates();
setTimeout(switchToElementsTab, 0);
});
});
// Wait until all scripts are added to the debugger.
this.takeControl();
};
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
TestSuite.prototype.testPauseWhenLoadingDevTools = function() {
const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
if (debuggerModel.debuggerPausedDetails)
return;
this.showPanel('sources').then(function() {
// Script execution can already be paused.
this._waitForScriptPause(this.releaseControl.bind(this));
}.bind(this));
this.takeControl();
};
// Tests that pressing "Pause" will pause script execution if the script
// is already running.
TestSuite.prototype.testPauseWhenScriptIsRunning = function() {
this.showPanel('sources').then(function() {
this.evaluateInConsole_('setTimeout("handleClick()", 0)', didEvaluateInConsole.bind(this));
}.bind(this));
function didEvaluateInConsole(resultText) {
this.assertTrue(!isNaN(resultText), 'Failed to get timer id: ' + resultText);
// Wait for some time to make sure that inspected page is running the
// infinite loop.
setTimeout(testScriptPause.bind(this), 300);
}
function testScriptPause() {
// The script should be in infinite loop. Click "Pause" button to
// pause it and wait for the result.
UI.panels.sources._togglePause();
this._waitForScriptPause(this.releaseControl.bind(this));
}
this.takeControl();
};
/**
* Tests network size.
*/
TestSuite.prototype.testNetworkSize = function() {
const test = this;
function finishRequest(request, finishTime) {
test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
// Reload inspected page to sniff network events
test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
this.takeControl();
};
/**
* Tests network sync size.
*/
TestSuite.prototype.testNetworkSyncSize = function() {
const test = this;
function finishRequest(request, finishTime) {
test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
// Send synchronous XHR to sniff network events
test.evaluateInConsole_(
'let xhr = new XMLHttpRequest(); xhr.open("GET", "chunked", false); xhr.send(null);', function() {});
this.takeControl();
};
/**
* Tests network raw headers text.
*/
TestSuite.prototype.testNetworkRawHeadersText = function() {
const test = this;
function finishRequest(request, finishTime) {
if (!request.responseHeadersText)
test.fail('Failure: resource does not have response headers text');
const index = request.responseHeadersText.indexOf('Date:');
test.assertEquals(
112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
// Reload inspected page to sniff network events
test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
this.takeControl();
};
/**
* Tests network timing.
*/
TestSuite.prototype.testNetworkTiming = function() {
const test = this;
function finishRequest(request, finishTime) {
// Setting relaxed expectations to reduce flakiness.
// Server sends headers after 100ms, then sends data during another 100ms.
// We expect these times to be measured at least as 70ms.
test.assertTrue(
request.timing.receiveHeadersEnd - request.timing.connectStart >= 70,
'Time between receiveHeadersEnd and connectStart should be >=70ms, but was ' +
'receiveHeadersEnd=' + request.timing.receiveHeadersEnd + ', connectStart=' +
request.timing.connectStart + '.');
test.assertTrue(
request.responseReceivedTime - request.startTime >= 0.07,
'Time between responseReceivedTime and startTime should be >=0.07s, but was ' +
'responseReceivedTime=' + request.responseReceivedTime + ', startTime=' + request.startTime + '.');
test.assertTrue(
request.endTime - request.startTime >= 0.14,
'Time between endTime and startTime should be >=0.14s, but was ' +
'endtime=' + request.endTime + ', startTime=' + request.startTime + '.');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
// Reload inspected page to sniff network events
test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
this.takeControl();
};
TestSuite.prototype.testPushTimes = function(url) {
const test = this;
let pendingRequestCount = 2;
function finishRequest(request, finishTime) {
test.assertTrue(
typeof request.timing.pushStart === 'number' && request.timing.pushStart > 0,
`pushStart is invalid: ${request.timing.pushStart}`);
test.assertTrue(typeof request.timing.pushEnd === 'number', `pushEnd is invalid: ${request.timing.pushEnd}`);
test.assertTrue(request.timing.pushStart < request.startTime, 'pushStart should be before startTime');
if (request.url().endsWith('?pushUseNullEndTime')) {
test.assertTrue(request.timing.pushEnd === 0, `pushEnd should be 0 but is ${request.timing.pushEnd}`);
} else {
test.assertTrue(
request.timing.pushStart < request.timing.pushEnd,
`pushStart should be before pushEnd (${request.timing.pushStart} >= ${request.timing.pushEnd})`);
// The below assertion is just due to the way we generate times in the moch URLRequestJob and is not generally an invariant.
test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime');
test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime');
}
if (!--pendingRequestCount)
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest, true);
test.evaluateInConsole_('addImage(\'' + url + '\')', function(resultText) {});
test.evaluateInConsole_('addImage(\'' + url + '?pushUseNullEndTime\')', function(resultText) {});
this.takeControl();
};
TestSuite.prototype.testConsoleOnNavigateBack = function() {
function filteredMessages() {
return SDK.consoleModel.messages().filter(a => a.source !== SDK.ConsoleMessage.MessageSource.Violation);
}
if (filteredMessages().length === 1)
firstConsoleMessageReceived.call(this, null);
else
SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
function firstConsoleMessageReceived(event) {
if (event && event.data.source === SDK.ConsoleMessage.MessageSource.Violation)
return;
SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
this.evaluateInConsole_('clickLink();', didClickLink.bind(this));
}
function didClickLink() {
// Check that there are no new messages(command is not a message).
this.assertEquals(3, filteredMessages().length);
this.evaluateInConsole_('history.back();', didNavigateBack.bind(this));
}
function didNavigateBack() {
// Make sure navigation completed and possible console messages were pushed.
this.evaluateInConsole_('void 0;', didCompleteNavigation.bind(this));
}
function didCompleteNavigation() {
this.assertEquals(7, filteredMessages().length);
this.releaseControl();
}
this.takeControl();
};
TestSuite.prototype.testSharedWorker = function() {
function didEvaluateInConsole(resultText) {
this.assertEquals('2011', resultText);
this.releaseControl();
}
this.evaluateInConsole_('globalVar', didEvaluateInConsole.bind(this));
this.takeControl();
};
TestSuite.prototype.testPauseInSharedWorkerInitialization1 = function() {
// Make sure the worker is loaded.
this.takeControl();
this._waitForTargets(2, callback.bind(this));
function callback() {
Protocol.test.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this));
}
};
TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() {
this.takeControl();
this._waitForTargets(2, callback.bind(this));
function callback() {
const debuggerModel = SDK.targetManager.models(SDK.DebuggerModel)[0];
if (debuggerModel.isPaused()) {
SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
debuggerModel.resume();
return;
}
this._waitForScriptPause(callback.bind(this));
}
function onConsoleMessage(event) {
const message = event.data.messageText;
if (message !== 'connected')
this.fail('Unexpected message: ' + message);
this.releaseControl();
}
};
TestSuite.prototype.testSharedWorkerNetworkPanel = function() {
this.takeControl();
this.showPanel('network').then(() => {
if (!document.querySelector('#network-container'))
this.fail('unable to find #network-container');
this.releaseControl();
});
};
TestSuite.prototype.enableTouchEmulation = function() {
const deviceModeModel = new Emulation.DeviceModeModel(function() {});
deviceModeModel._target = SDK.targetManager.mainTarget();
deviceModeModel._applyTouch(true, true);
};
TestSuite.prototype.waitForDebuggerPaused = function() {
const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
if (debuggerModel.debuggerPausedDetails)
return;
this.takeControl();
this._waitForScriptPause(this.releaseControl.bind(this));
};
TestSuite.prototype.switchToPanel = function(panelName) {
this.showPanel(panelName).then(this.releaseControl.bind(this));
this.takeControl();
};
// Regression test for crbug.com/370035.
TestSuite.prototype.testDeviceMetricsOverrides = function() {
function dumpPageMetrics() {
return JSON.stringify(
{width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio});
}
const test = this;
async function testOverrides(params, metrics, callback) {
await SDK.targetManager.mainTarget().emulationAgent().invoke_setDeviceMetricsOverride(params);
test.evaluateInConsole_('(' + dumpPageMetrics.toString() + ')()', checkMetrics);
function checkMetrics(consoleResult) {
test.assertEquals(
'"' + JSON.stringify(metrics) + '"', consoleResult, 'Wrong metrics for params: ' + JSON.stringify(params));
callback();
}
}
function step1() {
testOverrides(
{width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true},
{width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
}
function step2() {
testOverrides(
{width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false},
{width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
}
function step3() {
testOverrides(
{width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true},
{width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
}
function step4() {
testOverrides(
{width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false},
{width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
}
function finish() {
test.releaseControl();
}
test.takeControl();
step1();
};
TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() {
const test = this;
let receivedReady = false;
function signalToShowAutofill() {
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
}
function selectTopAutoFill() {
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
}
function onResultOfInput(value) {
// Console adds "" around the response.
test.assertEquals('"Abbf"', value);
test.releaseControl();
}
function onConsoleMessage(event) {
const message = event.data.messageText;
if (message === 'ready' && !receivedReady) {
receivedReady = true;
signalToShowAutofill();
}
// This log comes from the browser unittest code.
if (message === 'didShowSuggestions')
selectTopAutoFill();
}
this.takeControl();
// It is possible for the ready console messagage to be already received but not handled
// or received later. This ensures we can catch both cases.
SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
const messages = SDK.consoleModel.messages();
if (messages.length) {
const text = messages[0].messageText;
this.assertEquals('ready', text);
signalToShowAutofill();
}
};
TestSuite.prototype.testKeyEventUnhandled = function() {
function onKeyEventUnhandledKeyDown(event) {
this.assertEquals('keydown', event.data.type);
this.assertEquals('F8', event.data.key);
this.assertEquals(119, event.data.keyCode);
this.assertEquals(0, event.data.modifiers);
this.assertEquals('', event.data.code);
InspectorFrontendHost.events.removeEventListener(
InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
InspectorFrontendHost.events.addEventListener(
InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
}
function onKeyEventUnhandledKeyUp(event) {
this.assertEquals('keyup', event.data.type);
this.assertEquals('F8', event.data.key);
this.assertEquals(119, event.data.keyCode);
this.assertEquals(0, event.data.modifiers);
this.assertEquals('F8', event.data.code);
this.releaseControl();
}
this.takeControl();
InspectorFrontendHost.events.addEventListener(
InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
};
TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
};
// Check that showing the certificate viewer does not crash, crbug.com/954874
TestSuite.prototype.testShowCertificate = function() {
InspectorFrontendHost.showCertificateViewer([
'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
'X7qUz7Hvr3oeG+Ma9OUMmIebl//zHtC82mE0mCRBQAW0MWEgT5nOWey74tJR' +
'GRqUEI8ftV9grAshD5gY8kxxUoMfqrreaXVqcRF58ZPiwUJ0+SbtC5q9cJ+K' +
'MuYM4TCetEuk/WQsa+1EnSa40dhGRtZjxbwEwQAJ1vLOcIA7AVR/Ck22Uj8X' +
'UOECercjUrKdDyaAPcLp2TThAgMBAAGjggHZMIIB1TATBgNVHSUEDDAKBggr' +
'BgEFBQcDATCBrwYDVR0RBIGnMIGkgg0qLmFwcHNwb3QuY29tggsqLmEucnVu' +
'LmFwcIIVKi50aGlua3dpdGhnb29nbGUuY29tghAqLndpdGhnb29nbGUuY29t' +
'ghEqLndpdGh5b3V0dWJlLmNvbYILYXBwc3BvdC5jb22CB3J1bi5hcHCCE3Ro' +
'aW5rd2l0aGdvb2dsZS5jb22CDndpdGhnb29nbGUuY29tgg93aXRoeW91dHVi' +
'ZS5jb20waAYIKwYBBQUHAQEEXDBaMC0GCCsGAQUFBzAChiFodHRwOi8vcGtp' +
'Lmdvb2cvZ3NyMi9HVFNHSUFHMy5jcnQwKQYIKwYBBQUHMAGGHWh0dHA6Ly9v' +
'Y3NwLnBraS5nb29nL0dUU0dJQUczMB0GA1UdDgQWBBTGkpE5o0H9+Wjc05rF' +
'hNQiYDjBFjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFHfCuFCaZ3Z2sS3C' +
'htCDoH6mfrpLMCEGA1UdIAQaMBgwDAYKKwYBBAHWeQIFAzAIBgZngQwBAgIw' +
'MQYDVR0fBCowKDAmoCSgIoYgaHR0cDovL2NybC5wa2kuZ29vZy9HVFNHSUFH' +
'My5jcmwwDQYJKoZIhvcNAQELBQADggEBALqoYGqWtJW/6obEzY+ehsgfyXb+' +
'qNIuV09wt95cRF93HlLbBlSZ/Iz8HXX44ZT1/tGAkwKnW0gDKSSab3I8U+e9' +
'LHbC9VXrgAFENzu89MNKNmK5prwv+MPA2HUQPu4Pad3qXmd4+nKc/EUjtg1d' +
'/xKGK1Vn6JX3i5ly/rduowez3LxpSAJuIwseum331aQaKC2z2ri++96B8MPU' +
'KFXzvV2gVGOe3ZYqmwPaG8y38Tba+OzEh59ygl8ydJJhoI6+R3itPSy0aXUU' +
'lMvvAbfCobXD5kBRQ28ysgbDSDOPs3fraXpAKL92QUjsABs58XBz5vka4swu' +
'gg/u+ZxaKOqfIm8=',
'MIIEXDCCA0SgAwIBAgINAeOpMBz8cgY4P5pTHTANBgkqhkiG9w0BAQsFADBM' +
'MSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMK' +
'R2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xNzA2MTUwMDAw' +
'NDJaFw0yMTEyMTUwMDAwNDJaMFQxCzAJBgNVBAYTAlVTMR4wHAYDVQQKExVH' +
'b29nbGUgVHJ1c3QgU2VydmljZXMxJTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5l' +
'dCBBdXRob3JpdHkgRzMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB' +
'AQDKUkvqHv/OJGuo2nIYaNVWXQ5IWi01CXZaz6TIHLGp/lOJ+600/4hbn7vn' +
'6AAB3DVzdQOts7G5pH0rJnnOFUAK71G4nzKMfHCGUksW/mona+Y2emJQ2N+a' +
'icwJKetPKRSIgAuPOB6Aahh8Hb2XO3h9RUk2T0HNouB2VzxoMXlkyW7XUR5m' +
'w6JkLHnA52XDVoRTWkNty5oCINLvGmnRsJ1zouAqYGVQMc/7sy+/EYhALrVJ' +
'EA8KbtyX+r8snwU5C1hUrwaW6MWOARa8qBpNQcWTkaIeoYvy/sGIJEmjR0vF' +
'EwHdp1cSaWIr6/4g72n7OqXwfinu7ZYW97EfoOSQJeAzAgMBAAGjggEzMIIB' +
'LzAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUF' +
'BwMCMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFHfCuFCaZ3Z2sS3C' +
'htCDoH6mfrpLMB8GA1UdIwQYMBaAFJviB1dnHB7AagbeWbSaLd/cGYYuMDUG' +
'CCsGAQUFBwEBBCkwJzAlBggrBgEFBQcwAYYZaHR0cDovL29jc3AucGtpLmdv' +
'b2cvZ3NyMjAyBgNVHR8EKzApMCegJaAjhiFodHRwOi8vY3JsLnBraS5nb29n' +
'L2dzcjIvZ3NyMi5jcmwwPwYDVR0gBDgwNjA0BgZngQwBAgIwKjAoBggrBgEF' +
'BQcCARYcaHR0cHM6Ly9wa2kuZ29vZy9yZXBvc2l0b3J5LzANBgkqhkiG9w0B' +
'AQsFAAOCAQEAHLeJluRT7bvs26gyAZ8so81trUISd7O45skDUmAge1cnxhG1' +
'P2cNmSxbWsoiCt2eux9LSD+PAj2LIYRFHW31/6xoic1k4tbWXkDCjir37xTT' +
'NqRAMPUyFRWSdvt+nlPqwnb8Oa2I/maSJukcxDjNSfpDh/Bd1lZNgdd/8cLd' +
'sE3+wypufJ9uXO1iQpnh9zbuFIwsIONGl1p3A8CgxkqI/UAih3JaGOqcpcda' +
'CIzkBaR9uYQ1X4k2Vg5APRLouzVy7a8IVk6wuy6pm+T7HT4LY8ibS5FEZlfA' +
'FLSW8NwsVz9SBK2Vqn1N0PIMn5xA6NZVc7o835DLAFshEWfC7TIe3g==',
'MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEg' +
'MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkds' +
'b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAw' +
'WhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3Qg' +
'Q0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs' +
'U2lnbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8o' +
'mUVCxKs+IVSbC9N/hHD6ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe' +
'+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1' +
'AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5' +
'TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo' +
'4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99y' +
'qWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8E' +
'BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5Z' +
'tJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz' +
'aWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0' +
'mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs' +
'J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4' +
'h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRD' +
'LenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7' +
'9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmg' +
'QWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq' +
'/H5COEBkEveegeGTLg=='
]);
};
// Simple sanity check to make sure network throttling is wired up
// See crbug.com/747724
TestSuite.prototype.testOfflineNetworkConditions = async function() {
const test = this;
SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
function finishRequest(request) {
test.assertEquals(
'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
test.takeControl();
test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
};
TestSuite.prototype.testEmulateNetworkConditions = function() {
const test = this;
function testPreset(preset, messages, next) {
function onConsoleMessage(event) {
const index = messages.indexOf(event.data.messageText);
if (index === -1) {
test.fail('Unexpected message: ' + event.data.messageText);
return;
}
messages.splice(index, 1);
if (!messages.length) {
SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
next();
}
}
SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
SDK.multitargetNetworkManager.setNetworkConditions(preset);
}
test.takeControl();
step1();
function step1() {
testPreset(
MobileThrottling.networkPresets[2],
[
'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
],
step2);
}
function step2() {
testPreset(
MobileThrottling.networkPresets[1],
[
'online event: online = true',
'connection change event: type = cellular; downlinkMax = 0.390625; effectiveType = 2g'
],
step3);
}
function step3() {
testPreset(
MobileThrottling.networkPresets[0],
['connection change event: type = cellular; downlinkMax = 1.4400000000000002; effectiveType = 3g'],
test.releaseControl.bind(test));
}
};
TestSuite.prototype.testScreenshotRecording = function() {
const test = this;
function performActionsInPage(callback) {
let count = 0;
const div = document.createElement('div');
div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
document.body.appendChild(div);
requestAnimationFrame(frame);
function frame() {
const color = [0, 0, 0];
color[count % 3] = 255;
div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
if (++count > 10)
requestAnimationFrame(callback);
else
requestAnimationFrame(frame);
}
}
const captureFilmStripSetting = Common.settings.createSetting('timelineCaptureFilmStrip', false);
captureFilmStripSetting.set(true);
test.evaluateInConsole_(performActionsInPage.toString(), function() {});
test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
function onTimelineDone() {
captureFilmStripSetting.set(false);
const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel();
const frames = filmStripModel.frames();
test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
loadFrameImages(frames);
}
function loadFrameImages(frames) {
const readyImages = [];
for (const frame of frames)
frame.imageDataPromise().then(onGotImageData);
function onGotImageData(data) {
const image = new Image();
test.assertTrue(!!data, 'No image data for frame');
image.addEventListener('load', onLoad);
image.src = 'data:image/jpg;base64,' + data;
}
function onLoad(event) {
readyImages.push(event.target);
if (readyImages.length === frames.length)
validateImagesAndCompleteTest(readyImages);
}
}
function validateImagesAndCompleteTest(images) {
let redCount = 0;
let greenCount = 0;
let blueCount = 0;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
for (const image of images) {
test.assertTrue(image.naturalWidth > 10);
test.assertTrue(image.naturalHeight > 10);
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
ctx.drawImage(image, 0, 0);
const data = ctx.getImageData(0, 0, 1, 1);
const color = Array.prototype.join.call(data.data, ',');
if (data.data[0] > 200)
redCount++;
else if (data.data[1] > 200)
greenCount++;
else if (data.data[2] > 200)
blueCount++;
else
test.fail('Unexpected color: ' + color);
}
test.assertTrue(redCount && greenCount && blueCount, 'Color sanity check failed');
test.releaseControl();
}
test.takeControl();
};
TestSuite.prototype.testSettings = function() {
const test = this;
createSettings();
test.takeControl();
setTimeout(reset, 0);
function createSettings() {
const localSetting = Common.settings.createLocalSetting('local', undefined);
localSetting.set({s: 'local', n: 1});
const globalSetting = Common.settings.createSetting('global', undefined);
globalSetting.set({s: 'global', n: 2});
}
function reset() {
Runtime.experiments.clearForTest();
InspectorFrontendHost.getPreferences(gotPreferences);
}
function gotPreferences(prefs) {
Main.Main._instanceForTest._createSettings(prefs);
const localSetting = Common.settings.createLocalSetting('local', undefined);
test.assertEquals('object', typeof localSetting.get());
test.assertEquals('local', localSetting.get().s);
test.assertEquals(1, localSetting.get().n);
const globalSetting = Common.settings.createSetting('global', undefined);
test.assertEquals('object', typeof globalSetting.get());
test.assertEquals('global', globalSetting.get().s);
test.assertEquals(2, globalSetting.get().n);
test.releaseControl();
}
};
TestSuite.prototype.testWindowInitializedOnNavigateBack = function() {
const test = this;
test.takeControl();
const messages = SDK.consoleModel.messages();
if (messages.length === 1)
checkMessages();
else
SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this);
function checkMessages() {
const messages = SDK.consoleModel.messages();
test.assertEquals(1, messages.length);
test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1);
test.releaseControl();
}
};
TestSuite.prototype.testConsoleContextNames = function() {
const test = this;
test.takeControl();
this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this)));
function onExecutionContexts() {
const consoleView = Console.ConsoleView.instance();
const selector = consoleView._consoleContextSelector;
const values = [];
for (const item of selector._items)
values.push(selector.titleFor(item));
test.assertEquals('top', values[0]);
test.assertEquals('Simple content script', values[1]);
test.releaseControl();
}
};
TestSuite.prototype.testRawHeadersWithHSTS = function(url) {
const test = this;
test.takeControl();
SDK.targetManager.addModelListener(
SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived);
this.evaluateInConsole_(`
let img = document.createElement('img');
img.src = "${url}";
document.body.appendChild(img);
`, () => {});
let count = 0;
function onResponseReceived(event) {
const networkRequest = event.data;
if (!networkRequest.url().startsWith('http'))
return;
switch (++count) {
case 1: // Original redirect
test.assertEquals(301, networkRequest.statusCode);
test.assertEquals('Moved Permanently', networkRequest.statusText);
test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location')));
break;
case 2: // HSTS internal redirect
test.assertTrue(networkRequest.url().startsWith('http://'));
test.assertEquals(undefined, networkRequest.requestHeadersText());
test.assertEquals(307, networkRequest.statusCode);
test.assertEquals('Internal Redirect', networkRequest.statusText);
test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason'));
test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://'));
break;
case 3: // Final response
test.assertTrue(networkRequest.url().startsWith('https://'));
test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1'));
test.assertEquals(200, networkRequest.statusCode);
test.assertEquals('OK', networkRequest.statusText);
test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length'));
test.releaseControl();
}
}
};
TestSuite.prototype.testDOMWarnings = function() {
const messages = SDK.consoleModel.messages();
this.assertEquals(1, messages.length);
const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:';
this.assertTrue(messages[0].messageText.startsWith(expectedPrefix));
};
TestSuite.prototype.waitForTestResultsInConsole = function() {
const messages = SDK.consoleModel.messages();
for (let i = 0; i < messages.length; ++i) {
const text = messages[i].messageText;
if (text === 'PASS')
return;
else if (/^FAIL/.test(text))
this.fail(text); // This will throw.
}
// Neither PASS nor FAIL, so wait for more messages.
function onConsoleMessage(event) {
const text = event.data.messageText;
if (text === 'PASS')
this.releaseControl();
else if (/^FAIL/.test(text))
this.fail(text);
}
SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
this.takeControl();
};
TestSuite.prototype._overrideMethod = function(receiver, methodName, override) {
const original = receiver[methodName];
if (typeof original !== 'function') {
this.fail(`TestSuite._overrideMethod: $[methodName] is not a function`);
return;
}
receiver[methodName] = function() {
let value;
try {
value = original.apply(receiver, arguments);
} finally {
receiver[methodName] = original;
}
override.apply(original, arguments);
return value;
};
};
TestSuite.prototype.startTimeline = function(callback) {
const test = this;
this.showPanel('timeline').then(function() {
const timeline = UI.panels.timeline;
test._overrideMethod(timeline, '_recordingStarted', callback);
timeline._toggleRecording();
});
};
TestSuite.prototype.stopTimeline = function(callback) {
const timeline = UI.panels.timeline;
this._overrideMethod(timeline, 'loadingComplete', callback);
timeline._toggleRecording();
};
TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) {
const callback = arguments[arguments.length - 1];
const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`;
const argsString = arguments.length < 3 ?
'' :
Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ',';
this.evaluateInConsole_(
`${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {});
SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
function onConsoleMessage(event) {
const text = event.data.messageText;
if (text === doneMessage) {
SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
callback();
}
}
};
TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) {
const test = this;
this.startTimeline(onRecordingStarted);
function onRecordingStarted() {
test.invokePageFunctionAsync(functionName, pageActionsDone);
}
function pageActionsDone() {
test.stopTimeline(callback);
}
};
TestSuite.prototype.enableExperiment = function(name) {
Runtime.experiments.enableForTest(name);
};
TestSuite.prototype.checkInputEventsPresent = function() {
const expectedEvents = new Set(arguments);
const model = UI.panels.timeline._performanceModel.timelineModel();
const asyncEvents = model.virtualThreads().find(thread => thread.isMainFrame).asyncEventsByGroup;
const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || [];
const prefix = 'InputLatency::';
for (const e of input) {
if (!e.name.startsWith(prefix))
continue;
if (e.steps.length < 2)
continue;
if (e.name.startsWith(prefix + 'Mouse') &&
typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number')
throw `Missing timeWaitingForMainThread on ${e.name}`;
expectedEvents.delete(e.name.substr(prefix.length));
}
if (expectedEvents.size)
throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(',');
};
TestSuite.prototype.testInspectedElementIs = async function(nodeName) {
this.takeControl();
await self.runtime.loadModulePromise('elements');
if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest)
await new Promise(f => this.addSniffer(Elements.ElementsPanel, '_firstInspectElementCompletedForTest', f));
this.assertEquals(nodeName, Elements.ElementsPanel._firstInspectElementNodeNameForTest);
this.releaseControl();
};
TestSuite.prototype.testDisposeEmptyBrowserContext = async function(url) {
this.takeControl();
const targetAgent = SDK.targetManager.mainTarget().targetAgent();
const {browserContextId} = await targetAgent.invoke_createBrowserContext();
const response1 = await targetAgent.invoke_getBrowserContexts();
this.assertEquals(response1.browserContextIds.length, 1);
await targetAgent.invoke_disposeBrowserContext({browserContextId});
const response2 = await targetAgent.invoke_getBrowserContexts();
this.assertEquals(response2.browserContextIds.length, 0);
this.releaseControl();
};
TestSuite.prototype.testCreateBrowserContext = async function(url) {
this.takeControl();
const browserContextIds = [];
const targetAgent = SDK.targetManager.mainTarget().targetAgent();
const target1 = await createIsolatedTarget(url);
const target2 = await createIsolatedTarget(url);
const response = await targetAgent.invoke_getBrowserContexts();
this.assertEquals(response.browserContextIds.length, 2);
this.assertTrue(response.browserContextIds.includes(browserContextIds[0]));
this.assertTrue(response.browserContextIds.includes(browserContextIds[1]));
await evalCode(target1, 'localStorage.setItem("page1", "page1")');
await evalCode(target2, 'localStorage.setItem("page2", "page2")');
this.assertEquals(await evalCode(target1, 'localStorage.getItem("page1")'), 'page1');
this.assertEquals(await evalCode(target1, 'localStorage.getItem("page2")'), null);
this.assertEquals(await evalCode(target2, 'localStorage.getItem("page1")'), null);
this.assertEquals(await evalCode(target2, 'localStorage.getItem("page2")'), 'page2');
const removedTargets = [];
SDK.targetManager.observeTargets({targetAdded: () => {}, targetRemoved: target => removedTargets.push(target)});
await Promise.all([disposeBrowserContext(browserContextIds[0]), disposeBrowserContext(browserContextIds[1])]);
this.assertEquals(removedTargets.length, 2);
this.assertEquals(removedTargets.indexOf(target1) !== -1, true);
this.assertEquals(removedTargets.indexOf(target2) !== -1, true);
this.releaseControl();
/**
* @param {string} url
* @return {!Promise<!SDK.Target>}
*/
async function createIsolatedTarget(url) {
const {browserContextId} = await targetAgent.invoke_createBrowserContext();
browserContextIds.push(browserContextId);
const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
await targetAgent.invoke_attachToTarget({targetId, flatten: true});
const target = SDK.targetManager.targets().find(target => target.id() === targetId);
const pageAgent = target.pageAgent();
await pageAgent.invoke_enable();
await pageAgent.invoke_navigate({url});
return target;
}
async function disposeBrowserContext(browserContextId) {
const targetAgent = SDK.targetManager.mainTarget().targetAgent();
await targetAgent.invoke_disposeBrowserContext({browserContextId});
}
async function evalCode(target, code) {
return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
}
};
TestSuite.prototype.testInputDispatchEventsToOOPIF = async function() {
this.takeControl();
await new Promise(callback => this._waitForTargets(2, callback));
async function takeLogs(target) {
const code = `
(function() {
var result = window.logs.join(' ');
window.logs = [];
return result;
})()
`;
return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
}
let parentFrameOutput;
let childFrameOutput;
const inputAgent = SDK.targetManager.mainTarget().inputAgent();
const runtimeAgent = SDK.targetManager.mainTarget().runtimeAgent();
await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10});
await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20});
await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20});
await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140});
await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150});
await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150});
parentFrameOutput = 'Event type: mousedown button: 0 x: 10 y: 10 Event type: mouseup button: 0 x: 10 y: 20';
this.assertEquals(parentFrameOutput, await takeLogs(SDK.targetManager.targets()[0]));
childFrameOutput = 'Event type: mousedown button: 0 x: 30 y: 40 Event type: mouseup button: 0 x: 30 y: 50';
this.assertEquals(childFrameOutput, await takeLogs(SDK.targetManager.targets()[1]));
await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
await runtimeAgent.invoke_evaluate({expression: `document.querySelector('iframe').focus()`});
await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
parentFrameOutput = 'Event type: keydown';
this.assertEquals(parentFrameOutput, await takeLogs(SDK.targetManager.targets()[0]));
childFrameOutput = 'Event type: keydown';
this.assertEquals(childFrameOutput, await takeLogs(SDK.targetManager.targets()[1]));
await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 10, y: 10}]});
await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 230, y: 140}]});
await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
parentFrameOutput = 'Event type: touchstart touch x: 10 touch y: 10';
this.assertEquals(parentFrameOutput, await takeLogs(SDK.targetManager.targets()[0]));
childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40';
this.assertEquals(childFrameOutput, await takeLogs(SDK.targetManager.targets()[1]));
this.releaseControl();
};
TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL, fileURL) {
const test = this;
const loggedHeaders = new Set(['cache-control', 'pragma']);
function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) {
return new Promise(fulfill => {
Host.ResourceLoader.load(url, headers, callback);
function callback(statusCode, headers, content) {
test.assertEquals(expectedStatus, statusCode);
const headersArray = [];
for (const name in headers) {
const nameLower = name.toLowerCase();
if (loggedHeaders.has(nameLower))
headersArray.push(nameLower);
}
headersArray.sort();
test.assertEquals(expectedHeaders.join(', '), headersArray.join(', '));
test.assertEquals(expectedContent, content);
fulfill();
}
});
}
this.takeControl();
await testCase(baseURL + 'non-existent.html', undefined, 404, [], '');
await testCase(baseURL + 'hello.html', undefined, 200, [], '<!doctype html>\n<p>hello</p>\n');
await testCase(baseURL + 'echoheader?x-devtools-test', {'x-devtools-test': 'Foo'}, 200, ['cache-control'], 'Foo');
await testCase(baseURL + 'set-header?pragma:%20no-cache', undefined, 200, ['pragma'], 'pragma: no-cache');
await SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
expression: `fetch("/set-cookie?devtools-test-cookie=Bar",
{credentials: 'include'})`,
awaitPromise: true
});
await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar');
await SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
expression: `fetch("/set-cookie?devtools-test-cookie=same-site-cookie;SameSite=Lax",
{credentials: 'include'})`,
awaitPromise: true
});
await testCase(
baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie');
await testCase('data:text/html,<body>hello</body>', undefined, 200, [], '<body>hello</body>');
await testCase(fileURL, undefined, 200, [], '<html>\n<body>\nDummy page.\n</body>\n</html>\n');
this.releaseControl();
};
TestSuite.prototype.testExtensionWebSocketUserAgentOverride = async function(websocketPort) {
this.takeControl();
const testUserAgent = 'test user agent';
SDK.multitargetNetworkManager.setUserAgentOverride(testUserAgent);
function onRequestUpdated(event) {
const request = event.data;
if (request.resourceType() !== Common.resourceTypes.WebSocket)
return;
if (!request.requestHeadersText())
return;
let actualUserAgent = 'no user-agent header';
for (const {name, value} of request.requestHeaders()) {
if (name.toLowerCase() === 'user-agent')
actualUserAgent = value;
}
this.assertEquals(testUserAgent, actualUserAgent);
this.releaseControl();
}
SDK.targetManager.addModelListener(
SDK.NetworkManager, SDK.NetworkManager.Events.RequestUpdated, onRequestUpdated.bind(this));
this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}')`, () => {});
};
/**
* Serializes array of uiSourceCodes to string.
* @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes
* @return {string}
*/
TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) {
const names = [];
for (let i = 0; i < uiSourceCodes.length; i++)
names.push('"' + uiSourceCodes[i].url() + '"');
return names.join(',');
};
/**
* Returns all loaded non anonymous uiSourceCodes.
* @return {!Array.<!Workspace.UISourceCode>}
*/
TestSuite.prototype.nonAnonymousUISourceCodes_ = function() {
/**
* @param {!Workspace.UISourceCode} uiSourceCode
*/
function filterOutService(uiSourceCode) {
return !uiSourceCode.project().isServiceProject();
}
const uiSourceCodes = Workspace.workspace.uiSourceCodes();
return uiSourceCodes.filter(filterOutService);
};
/*
* Evaluates the code in the console as if user typed it manually and invokes
* the callback when the result message is received and added to the console.
* @param {string} code
* @param {function(string)} callback
*/
TestSuite.prototype.evaluateInConsole_ = function(code, callback) {
function innerEvaluate() {
UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
const consoleView = Console.ConsoleView.instance();
consoleView._prompt._appendCommand(code);
this.addSniffer(Console.ConsoleView.prototype, '_consoleMessageAddedForTest', function(viewMessage) {
callback(viewMessage.toMessageElement().deepTextContent());
}.bind(this));
}
function showConsoleAndEvaluate() {
Common.console.showPromise().then(innerEvaluate.bind(this));
}
if (!UI.context.flavor(SDK.ExecutionContext)) {
UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
return;
}
showConsoleAndEvaluate.call(this);
};
/**
* Checks that all expected scripts are present in the scripts list
* in the Scripts panel.
* @param {!Array.<string>} expected Regular expressions describing
* expected script names.
* @return {boolean} Whether all the scripts are in "scripts-files" select
* box
*/
TestSuite.prototype._scriptsAreParsed = function(expected) {
const uiSourceCodes = this.nonAnonymousUISourceCodes_();
// Check that at least all the expected scripts are present.
const missing = expected.slice(0);
for (let i = 0; i < uiSourceCodes.length; ++i) {
for (let j = 0; j < missing.length; ++j) {
if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
missing.splice(j, 1);
break;
}
}
}
return missing.length === 0;
};
/**
* Waits for script pause, checks expectations, and invokes the callback.
* @param {function():void} callback
*/
TestSuite.prototype._waitForScriptPause = function(callback) {
this.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', callback);
};
/**
* Waits until all the scripts are parsed and invokes the callback.
*/
TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) {
const test = this;
function waitForAllScripts() {
if (test._scriptsAreParsed(expectedScripts))
callback();
else
test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts);
}
waitForAllScripts();
};
TestSuite.prototype._waitForTargets = function(n, callback) {
checkTargets.call(this);
function checkTargets() {
if (SDK.targetManager.targets().length >= n)
callback.call(null);
else
this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this));
}
};
TestSuite.prototype._waitForExecutionContexts = function(n, callback) {
const runtimeModel = SDK.targetManager.mainTarget().model(SDK.RuntimeModel);
checkForExecutionContexts.call(this);
function checkForExecutionContexts() {
if (runtimeModel.executionContexts().length >= n)
callback.call(null);
else
this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this));
}
};
window.uiTests = new TestSuite(window.domAutomationController);
})(window);
(function() {
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* eslint-disable indent */
function defineCommonExtensionSymbols(apiPrivate) {
if (!apiPrivate.panels)
apiPrivate.panels = {};
apiPrivate.panels.SearchAction = {
CancelSearch: 'cancelSearch',
PerformSearch: 'performSearch',
NextSearchResult: 'nextSearchResult',
PreviousSearchResult: 'previousSearchResult'
};
/** @enum {string} */
apiPrivate.Events = {
ButtonClicked: 'button-clicked-',
PanelObjectSelected: 'panel-objectSelected-',
NetworkRequestFinished: 'network-request-finished',
OpenResource: 'open-resource',
PanelSearch: 'panel-search-',
RecordingStarted: 'trace-recording-started-',
RecordingStopped: 'trace-recording-stopped-',
ResourceAdded: 'resource-added',
ResourceContentCommitted: 'resource-content-committed',
ViewShown: 'view-shown-',
ViewHidden: 'view-hidden-'
};
/** @enum {string} */
apiPrivate.Commands = {
AddRequestHeaders: 'addRequestHeaders',
AddTraceProvider: 'addTraceProvider',
ApplyStyleSheet: 'applyStyleSheet',
CompleteTraceSession: 'completeTraceSession',
CreatePanel: 'createPanel',
CreateSidebarPane: 'createSidebarPane',
CreateToolbarButton: 'createToolbarButton',
EvaluateOnInspectedPage: 'evaluateOnInspectedPage',
ForwardKeyboardEvent: '_forwardKeyboardEvent',
GetHAR: 'getHAR',
GetPageResources: 'getPageResources',
GetRequestContent: 'getRequestContent',
GetResourceContent: 'getResourceContent',
InspectedURLChanged: 'inspectedURLChanged',
OpenResource: 'openResource',
Reload: 'Reload',
Subscribe: 'subscribe',
SetOpenResourceHandler: 'setOpenResourceHandler',
SetResourceContent: 'setResourceContent',
SetSidebarContent: 'setSidebarContent',
SetSidebarHeight: 'setSidebarHeight',
SetSidebarPage: 'setSidebarPage',
ShowPanel: 'showPanel',
Unsubscribe: 'unsubscribe',
UpdateButton: 'updateButton'
};
}
/**
* @param {!ExtensionDescriptor} extensionInfo
* @param {string} inspectedTabId
* @param {string} themeName
* @param {!Array<number>} keysToForward
* @param {number} injectedScriptId
* @param {function(!Object, !Object)} testHook
* @suppressGlobalPropertiesCheck
*/
function injectedExtensionAPI(extensionInfo, inspectedTabId, themeName, keysToForward, testHook, injectedScriptId) {
const keysToForwardSet = new Set(keysToForward);
const chrome = window.chrome || {};
const devtools_descriptor = Object.getOwnPropertyDescriptor(chrome, 'devtools');
if (devtools_descriptor)
return;
const apiPrivate = {};
defineCommonExtensionSymbols(apiPrivate);
const commands = apiPrivate.Commands;
const events = apiPrivate.Events;
let userAction = false;
// Here and below, all constructors are private to API implementation.
// For a public type Foo, if internal fields are present, these are on
// a private FooImpl type, an instance of FooImpl is used in a closure
// by Foo consutrctor to re-bind publicly exported members to an instance
// of Foo.
/**
* @constructor
*/
function EventSinkImpl(type, customDispatch) {
this._type = type;
this._listeners = [];
this._customDispatch = customDispatch;
}
EventSinkImpl.prototype = {
addListener: function(callback) {
if (typeof callback !== 'function')
throw 'addListener: callback is not a function';
if (this._listeners.length === 0)
extensionServer.sendRequest({command: commands.Subscribe, type: this._type});
this._listeners.push(callback);
extensionServer.registerHandler('notify-' + this._type, this._dispatch.bind(this));
},
removeListener: function(callback) {
const listeners = this._listeners;
for (let i = 0; i < listeners.length; ++i) {
if (listeners[i] === callback) {
listeners.splice(i, 1);
break;
}
}
if (this._listeners.length === 0)
extensionServer.sendRequest({command: commands.Unsubscribe, type: this._type});
},
/**
* @param {...} vararg
*/
_fire: function(vararg) {
const listeners = this._listeners.slice();
for (let i = 0; i < listeners.length; ++i)
listeners[i].apply(null, arguments);
},
_dispatch: function(request) {
if (this._customDispatch)
this._customDispatch.call(this, request);
else
this._fire.apply(this, request.arguments);
}
};
/**
* @constructor
*/
function InspectorExtensionAPI() {
this.inspectedWindow = new InspectedWindow();
this.panels = new Panels();
this.network = new Network();
this.timeline = new Timeline();
defineDeprecatedProperty(this, 'webInspector', 'resources', 'network');
}
/**
* @constructor
*/
function Network() {
/**
* @this {EventSinkImpl}
*/
function dispatchRequestEvent(message) {
const request = message.arguments[1];
request.__proto__ = new Request(message.arguments[0]);
this._fire(request);
}
this.onRequestFinished = new EventSink(events.NetworkRequestFinished, dispatchRequestEvent);
defineDeprecatedProperty(this, 'network', 'onFinished', 'onRequestFinished');
this.onNavigated = new EventSink(events.InspectedURLChanged);
}
Network.prototype = {
getHAR: function(callback) {
function callbackWrapper(result) {
const entries = (result && result.entries) || [];
for (let i = 0; i < entries.length; ++i) {
entries[i].__proto__ = new Request(entries[i]._requestId);
delete entries[i]._requestId;
}
callback(result);
}
extensionServer.sendRequest({command: commands.GetHAR}, callback && callbackWrapper);
},
addRequestHeaders: function(headers) {
extensionServer.sendRequest(
{command: commands.AddRequestHeaders, headers: headers, extensionId: window.location.hostname});
}
};
/**
* @constructor
*/
function RequestImpl(id) {
this._id = id;
}
RequestImpl.prototype = {
getContent: function(callback) {
function callbackWrapper(response) {
callback(response.content, response.encoding);
}
extensionServer.sendRequest({command: commands.GetRequestContent, id: this._id}, callback && callbackWrapper);
}
};
/**
* @constructor
*/
function Panels() {
const panels = {
elements: new ElementsPanel(),
sources: new SourcesPanel(),
};
function panelGetter(name) {
return panels[name];
}
for (const panel in panels)
this.__defineGetter__(panel, panelGetter.bind(null, panel));
this.applyStyleSheet = function(styleSheet) {
extensionServer.sendRequest({command: commands.ApplyStyleSheet, styleSheet: styleSheet});
};
}
Panels.prototype = {
create: function(title, icon, page, callback) {
const id = 'extension-panel-' + extensionServer.nextObjectId();
const request = {command: commands.CreatePanel, id: id, title: title, icon: icon, page: page};
extensionServer.sendRequest(request, callback && callback.bind(this, new ExtensionPanel(id)));
},
setOpenResourceHandler: function(callback) {
const hadHandler = extensionServer.hasHandler(events.OpenResource);
function callbackWrapper(message) {
// Allow the panel to show itself when handling the event.
userAction = true;
try {
callback.call(null, new Resource(message.resource), message.lineNumber);
} finally {
userAction = false;
}
}
if (!callback)
extensionServer.unregisterHandler(events.OpenResource);
else
extensionServer.registerHandler(events.OpenResource, callbackWrapper);
// Only send command if we either removed an existing handler or added handler and had none before.
if (hadHandler === !callback)
extensionServer.sendRequest({command: commands.SetOpenResourceHandler, 'handlerPresent': !!callback});
},
openResource: function(url, lineNumber, callback) {
extensionServer.sendRequest({command: commands.OpenResource, 'url': url, 'lineNumber': lineNumber}, callback);
},
get SearchAction() {
return apiPrivate.panels.SearchAction;
}
};
/**
* @constructor
*/
function ExtensionViewImpl(id) {
this._id = id;
/**
* @this {EventSinkImpl}
*/
function dispatchShowEvent(message) {
const frameIndex = message.arguments[0];
if (typeof frameIndex === 'number')
this._fire(window.parent.frames[frameIndex]);
else
this._fire();
}
if (id) {
this.onShown = new EventSink(events.ViewShown + id, dispatchShowEvent);
this.onHidden = new EventSink(events.ViewHidden + id);
}
}
/**
* @constructor
* @extends {ExtensionViewImpl}
* @param {string} hostPanelName
*/
function PanelWithSidebarImpl(hostPanelName) {
ExtensionViewImpl.call(this, null);
this._hostPanelName = hostPanelName;
this.onSelectionChanged = new EventSink(events.PanelObjectSelected + hostPanelName);
}
PanelWithSidebarImpl.prototype = {
createSidebarPane: function(title, callback) {
const id = 'extension-sidebar-' + extensionServer.nextObjectId();
const request = {command: commands.CreateSidebarPane, panel: this._hostPanelName, id: id, title: title};
function callbackWrapper() {
callback(new ExtensionSidebarPane(id));
}
extensionServer.sendRequest(request, callback && callbackWrapper);
},
__proto__: ExtensionViewImpl.prototype
};
function declareInterfaceClass(implConstructor) {
return function() {
const impl = {__proto__: implConstructor.prototype};
implConstructor.apply(impl, arguments);
populateInterfaceClass(this, impl);
};
}
function defineDeprecatedProperty(object, className, oldName, newName) {
let warningGiven = false;
function getter() {
if (!warningGiven) {
console.warn(className + '.' + oldName + ' is deprecated. Use ' + className + '.' + newName + ' instead');
warningGiven = true;
}
return object[newName];
}
object.__defineGetter__(oldName, getter);
}
function extractCallbackArgument(args) {
const lastArgument = args[args.length - 1];
return typeof lastArgument === 'function' ? lastArgument : undefined;
}
const Button = declareInterfaceClass(ButtonImpl);
const EventSink = declareInterfaceClass(EventSinkImpl);
const ExtensionPanel = declareInterfaceClass(ExtensionPanelImpl);
const ExtensionSidebarPane = declareInterfaceClass(ExtensionSidebarPaneImpl);
const PanelWithSidebar = declareInterfaceClass(PanelWithSidebarImpl);
const Request = declareInterfaceClass(RequestImpl);
const Resource = declareInterfaceClass(ResourceImpl);
const TraceSession = declareInterfaceClass(TraceSessionImpl);
/**
* @constructor
* @extends {PanelWithSidebar}
*/
function ElementsPanel() {
PanelWithSidebar.call(this, 'elements');
}
ElementsPanel.prototype = {__proto__: PanelWithSidebar.prototype};
/**
* @constructor
* @extends {PanelWithSidebar}
*/
function SourcesPanel() {
PanelWithSidebar.call(this, 'sources');
}
SourcesPanel.prototype = {__proto__: PanelWithSidebar.prototype};
/**
* @constructor
* @extends {ExtensionViewImpl}
*/
function ExtensionPanelImpl(id) {
ExtensionViewImpl.call(this, id);
this.onSearch = new EventSink(events.PanelSearch + id);
}
ExtensionPanelImpl.prototype = {
/**
* @return {!Object}
*/
createStatusBarButton: function(iconPath, tooltipText, disabled) {
const id = 'button-' + extensionServer.nextObjectId();
const request = {
command: commands.CreateToolbarButton,
panel: this._id,
id: id,
icon: iconPath,
tooltip: tooltipText,
disabled: !!disabled
};
extensionServer.sendRequest(request);
return new Button(id);
},
show: function() {
if (!userAction)
return;
const request = {command: commands.ShowPanel, id: this._id};
extensionServer.sendRequest(request);
},
__proto__: ExtensionViewImpl.prototype
};
/**
* @constructor
* @extends {ExtensionViewImpl}
*/
function ExtensionSidebarPaneImpl(id) {
ExtensionViewImpl.call(this, id);
}
ExtensionSidebarPaneImpl.prototype = {
setHeight: function(height) {
extensionServer.sendRequest({command: commands.SetSidebarHeight, id: this._id, height: height});
},
setExpression: function(expression, rootTitle, evaluateOptions) {
const request = {
command: commands.SetSidebarContent,
id: this._id,
expression: expression,
rootTitle: rootTitle,
evaluateOnPage: true,
};
if (typeof evaluateOptions === 'object')
request.evaluateOptions = evaluateOptions;
extensionServer.sendRequest(request, extractCallbackArgument(arguments));
},
setObject: function(jsonObject, rootTitle, callback) {
extensionServer.sendRequest(
{command: commands.SetSidebarContent, id: this._id, expression: jsonObject, rootTitle: rootTitle}, callback);
},
setPage: function(page) {
extensionServer.sendRequest({command: commands.SetSidebarPage, id: this._id, page: page});
},
__proto__: ExtensionViewImpl.prototype
};
/**
* @constructor
*/
function ButtonImpl(id) {
this._id = id;
this.onClicked = new EventSink(events.ButtonClicked + id);
}
ButtonImpl.prototype = {
update: function(iconPath, tooltipText, disabled) {
const request =
{command: commands.UpdateButton, id: this._id, icon: iconPath, tooltip: tooltipText, disabled: !!disabled};
extensionServer.sendRequest(request);
}
};
/**
* @constructor
*/
function Timeline() {
}
Timeline.prototype = {
/**
* @param {string} categoryName
* @param {string} categoryTooltip
* @return {!TraceProvider}
*/
addTraceProvider: function(categoryName, categoryTooltip) {
const id = 'extension-trace-provider-' + extensionServer.nextObjectId();
extensionServer.sendRequest(
{command: commands.AddTraceProvider, id: id, categoryName: categoryName, categoryTooltip: categoryTooltip});
return new TraceProvider(id);
}
};
/**
* @constructor
* @param {string} id
*/
function TraceSessionImpl(id) {
this._id = id;
}
TraceSessionImpl.prototype = {
/**
* @param {string=} url
* @param {number=} timeOffset
*/
complete: function(url, timeOffset) {
const request =
{command: commands.CompleteTraceSession, id: this._id, url: url || '', timeOffset: timeOffset || 0};
extensionServer.sendRequest(request);
}
};
/**
* @constructor
* @param {string} id
*/
function TraceProvider(id) {
/**
* @this {EventSinkImpl}
*/
function dispatchRecordingStarted(message) {
const sessionId = message.arguments[0];
this._fire(new TraceSession(sessionId));
}
this.onRecordingStarted = new EventSink(events.RecordingStarted + id, dispatchRecordingStarted);
this.onRecordingStopped = new EventSink(events.RecordingStopped + id);
}
/**
* @constructor
*/
function InspectedWindow() {
/**
* @this {EventSinkImpl}
*/
function dispatchResourceEvent(message) {
this._fire(new Resource(message.arguments[0]));
}
/**
* @this {EventSinkImpl}
*/
function dispatchResourceContentEvent(message) {
this._fire(new Resource(message.arguments[0]), message.arguments[1]);
}
this.onResourceAdded = new EventSink(events.ResourceAdded, dispatchResourceEvent);
this.onResourceContentCommitted = new EventSink(events.ResourceContentCommitted, dispatchResourceContentEvent);
}
InspectedWindow.prototype = {
reload: function(optionsOrUserAgent) {
let options = null;
if (typeof optionsOrUserAgent === 'object') {
options = optionsOrUserAgent;
} else if (typeof optionsOrUserAgent === 'string') {
options = {userAgent: optionsOrUserAgent};
console.warn(
'Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. ' +
'Use inspectedWindow.reload({ userAgent: value}) instead.');
}
extensionServer.sendRequest({command: commands.Reload, options: options});
},
/**
* @return {?Object}
*/
eval: function(expression, evaluateOptions) {
const callback = extractCallbackArgument(arguments);
function callbackWrapper(result) {
if (result.isError || result.isException)
callback(undefined, result);
else
callback(result.value);
}
const request = {command: commands.EvaluateOnInspectedPage, expression: expression};
if (typeof evaluateOptions === 'object')
request.evaluateOptions = evaluateOptions;
extensionServer.sendRequest(request, callback && callbackWrapper);
return null;
},
getResources: function(callback) {
function wrapResource(resourceData) {
return new Resource(resourceData);
}
function callbackWrapper(resources) {
callback(resources.map(wrapResource));
}
extensionServer.sendRequest({command: commands.GetPageResources}, callback && callbackWrapper);
}
};
/**
* @constructor
*/
function ResourceImpl(resourceData) {
this._url = resourceData.url;
this._type = resourceData.type;
}
ResourceImpl.prototype = {
get url() {
return this._url;
},
get type() {
return this._type;
},
getContent: function(callback) {
function callbackWrapper(response) {
callback(response.content, response.encoding);
}
extensionServer.sendRequest({command: commands.GetResourceContent, url: this._url}, callback && callbackWrapper);
},
setContent: function(content, commit, callback) {
extensionServer.sendRequest(
{command: commands.SetResourceContent, url: this._url, content: content, commit: commit}, callback);
}
};
function getTabId() {
return inspectedTabId;
}
let keyboardEventRequestQueue = [];
let forwardTimer = null;
function forwardKeyboardEvent(event) {
let modifiers = 0;
if (event.shiftKey)
modifiers |= 1;
if (event.ctrlKey)
modifiers |= 2;
if (event.altKey)
modifiers |= 4;
if (event.metaKey)
modifiers |= 8;
const num = (event.keyCode & 255) | (modifiers << 8);
// We only care about global hotkeys, not about random text
if (!keysToForwardSet.has(num))
return;
event.preventDefault();
const requestPayload = {
eventType: event.type,
ctrlKey: event.ctrlKey,
altKey: event.altKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
keyIdentifier: event.keyIdentifier,
key: event.key,
code: event.code,
location: event.location,
keyCode: event.keyCode
};
keyboardEventRequestQueue.push(requestPayload);
if (!forwardTimer)
forwardTimer = setTimeout(forwardEventQueue, 0);
}
function forwardEventQueue() {
forwardTimer = null;
const request = {command: commands.ForwardKeyboardEvent, entries: keyboardEventRequestQueue};
extensionServer.sendRequest(request);
keyboardEventRequestQueue = [];
}
document.addEventListener('keydown', forwardKeyboardEvent, false);
/**
* @constructor
*/
function ExtensionServerClient() {
this._callbacks = {};
this._handlers = {};
this._lastRequestId = 0;
this._lastObjectId = 0;
this.registerHandler('callback', this._onCallback.bind(this));
const channel = new MessageChannel();
this._port = channel.port1;
this._port.addEventListener('message', this._onMessage.bind(this), false);
this._port.start();
window.parent.postMessage('registerExtension', '*', [channel.port2]);
}
ExtensionServerClient.prototype = {
/**
* @param {!Object} message
* @param {function()=} callback
*/
sendRequest: function(message, callback) {
if (typeof callback === 'function')
message.requestId = this._registerCallback(callback);
this._port.postMessage(message);
},
/**
* @return {boolean}
*/
hasHandler: function(command) {
return !!this._handlers[command];
},
registerHandler: function(command, handler) {
this._handlers[command] = handler;
},
unregisterHandler: function(command) {
delete this._handlers[command];
},
/**
* @return {string}
*/
nextObjectId: function() {
return injectedScriptId.toString() + '_' + ++this._lastObjectId;
},
_registerCallback: function(callback) {
const id = ++this._lastRequestId;
this._callbacks[id] = callback;
return id;
},
_onCallback: function(request) {
if (request.requestId in this._callbacks) {
const callback = this._callbacks[request.requestId];
delete this._callbacks[request.requestId];
callback(request.result);
}
},
_onMessage: function(event) {
const request = event.data;
const handler = this._handlers[request.command];
if (handler)
handler.call(this, request);
}
};
function populateInterfaceClass(interfaze, implementation) {
for (const member in implementation) {
if (member.charAt(0) === '_')
continue;
let descriptor = null;
// Traverse prototype chain until we find the owner.
for (let owner = implementation; owner && !descriptor; owner = owner.__proto__)
descriptor = Object.getOwnPropertyDescriptor(owner, member);
if (!descriptor)
continue;
if (typeof descriptor.value === 'function')
interfaze[member] = descriptor.value.bind(implementation);
else if (typeof descriptor.get === 'function')
interfaze.__defineGetter__(member, descriptor.get.bind(implementation));
else
Object.defineProperty(interfaze, member, descriptor);
}
}
const extensionServer = new ExtensionServerClient();
const coreAPI = new InspectorExtensionAPI();
Object.defineProperty(chrome, 'devtools', {value: {}, enumerable: true});
// Only expose tabId on chrome.devtools.inspectedWindow, not webInspector.inspectedWindow.
chrome.devtools.inspectedWindow = {};
chrome.devtools.inspectedWindow.__defineGetter__('tabId', getTabId);
chrome.devtools.inspectedWindow.__proto__ = coreAPI.inspectedWindow;
chrome.devtools.network = coreAPI.network;
chrome.devtools.panels = coreAPI.panels;
chrome.devtools.panels.themeName = themeName;
// default to expose experimental APIs for now.
if (extensionInfo.exposeExperimentalAPIs !== false) {
chrome.experimental = chrome.experimental || {};
chrome.experimental.devtools = chrome.experimental.devtools || {};
const properties = Object.getOwnPropertyNames(coreAPI);
for (let i = 0; i < properties.length; ++i) {
const descriptor = Object.getOwnPropertyDescriptor(coreAPI, properties[i]);
if (descriptor)
Object.defineProperty(chrome.experimental.devtools, properties[i], descriptor);
}
chrome.experimental.devtools.inspectedWindow = chrome.devtools.inspectedWindow;
}
if (extensionInfo.exposeWebInspectorNamespace)
window.webInspector = coreAPI;
testHook(extensionServer, coreAPI);
}
/**
* @param {!ExtensionDescriptor} extensionInfo
* @param {string} inspectedTabId
* @param {string} themeName
* @param {!Array<number>} keysToForward
* @param {function(!Object, !Object)|undefined} testHook
* @return {string}
*/
function buildExtensionAPIInjectedScript(extensionInfo, inspectedTabId, themeName, keysToForward, testHook) {
const argumentsJSON = [extensionInfo, inspectedTabId || null, themeName, keysToForward].map(_ => JSON.stringify(_)).join(',');
if (!testHook)
testHook = () => {};
return '(function(injectedScriptId){ ' + defineCommonExtensionSymbols.toString() + ';' +
'(' + injectedExtensionAPI.toString() + ')(' + argumentsJSON + ',' + testHook + ', injectedScriptId);' +
'})';
}
var tabId;
var extensionInfo = {};
var extensionServer;
platformExtensionAPI(injectedExtensionAPI("remote-" + window.parent.frames.length));
})();<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 770.00001 1580"
version="1.1"
width="770"
height="1580"
id="svg11071">
<defs
id="defs3775" />
<metadata
id="metadata11076">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
transform="matrix(-1,0,0,1,770.5,0)"
id="layer3">
<path
style="fill:none;stroke:#ff8800;stroke-width:9"
d="M 766,366 V 466"
id="path11635" />
<path
style="fill:none;stroke:#888888;stroke-width:9"
d="M 766,768 V 568"
id="path11637" />
<g
style="fill-rule:evenodd"
id="g3764">
<rect
style="fill:#222222"
x="0"
y="0"
width="767"
height="1580"
ry="80"
rx="80"
id="rect11633" />
</g>
<g
style="fill:#ffffff;fill-rule:evenodd"
id="g3769">
<rect
style="fill-opacity:0.13332998"
x="273.5"
y="1526"
width="220"
height="15"
ry="5"
rx="5"
id="rect11707" />
<path
style="fill-opacity:0.86667002"
d="M 70.36319,6.9493575 C 28.332124,5.755102 4.8083241,47.982906 4.8378685,83.222978 L 6.032124,1507.7128 c 0.025949,30.952 32.037776,68.2787 64.633409,68.2161 l 622.086167,-1.1942 c 30.87325,-0.059 68.21618,-37.2632 68.21618,-64.6334 V 76.057445 c 0,-31.282766 -24.68851,-66.7195765 -63.13681,-70.302343 C 456.89848,4.61017 269.72229,6.9493575 70.36319,6.9493575 Z"
id="path11722" />
</g>
</g>
</svg>
<EFBFBD>PNG

IHDR<00><00><>H<EFBFBD>!PLTE<54><45><EFBFBD>!!!444ddd<64><64><EFBFBD><EFBFBD><EFBFBD><EFBFBD>eee333...///<2F><>Xe\IDATx^<5E>ԡ <0A>0<14><><1A>]<5D>A<EFBFBD>@<40><>jqhl7<6C>]<5D>9k<39><6B><EFBFBD>=G<>?<3F><><EFBFBD>9<EFBFBD><39><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1A><-<2D>$.<2E><>$<24><><EFBFBD>I<EFBFBD><49><EFBFBD>zb<7A> $q<><71>Ib<49>_a=<3D>˾5<><35>3!<21><>܄IEND<4E>B`<60><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg id="svg11071" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="1580" width="770" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" viewBox="0 0 770.00001 1580">
<metadata id="metadata11076">
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
<dc:title/>
</cc:Work>
</rdf:RDF>
</metadata>
<g id="layer3">
<path id="path11635" d="m766 366v100" stroke="#f80" stroke-width="9" fill="none"/>
<path id="path11637" d="m766 768v-200" stroke="#888" stroke-width="9" fill="none"/>
<g fill-rule="evenodd">
<rect id="rect11633" rx="80" ry="80" height="1580" width="767" y="0" x="0" fill="#222"/>
<rect id="rect11061" fill-opacity=".13333" rx="5" ry="5" height="18" width="80" y="80" x="343.5" fill="#fff"/>
<circle id="path11063" cx="459" fill-opacity=".26667" cy="76.25" r="15" fill="#00f"/>
<circle id="path11069" cx="297.25" fill-opacity=".26667" cy="74" r="17.5" fill="#00f"/>
</g>
<g fill-rule="evenodd" fill="#fff">
<rect id="rect11705" fill-opacity=".13333" rx="10" ry="10" height="25" width="50" y="34" x="358.5"/>
<rect id="rect11707" fill-opacity=".13333" rx="5" ry="5" height="15" width="220" y="1526" x="273.5"/>
<path id="path11722" d="m83.5 38c-27.7 0-50 22.3-50 50v1360c0 16.62 13.38 30 30 30h640c16.62 0 30-13.38 30-30v-1360c0-27.7-22.3-50-50-50h-90-50c-19.39 0-35 15.61-35 35v4c0 24.93-20.07 45-45 45h-160c-24.93 0-45-20.07-45-45v-4c0-19.39-15.61-35-35-35h-70z" fill-opacity=".86667"/>
</g>
</g>
</svg>
<EFBFBD>PNG

IHDR<00><00>?tBPLTE<54><45><EFBFBD>d<EFBFBD>V-IDATx^<5E><>1<00>@ؿ<><11><>1<%$ DT<44> C<>j-IEND<4E>B`<60><>PNG

IHDR<00>s<><73>2PLTE<54><45><EFBFBD><E0BDBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>آ<EFBFBD><D8A2><EFBFBD><EFBFBD>٥<EFBFBD><D9A5>7d/<2F>eIDATx^<5E>ԡ <0A>@ <0C><>3<04>~<7E><>tn<01>m@<40>(`r <0C><>\<02><>W<EFBFBD>ɶy/<2F><><09><><EFBFBD>
,<2C><01><>}<00>
B<1C><><EFBFBD>́<><CC81><EFBFBD>,<2C>+?<3F>#<23><11>?<3F><>
<EFBFBD><EFBFBD>rw<EFBFBD> <09> <1C><>v27<32><37>IEND<4E>B`<60><>PNG

IHDR<00>.<2E><>PLTE<54><45><EFBFBD>d<EFBFBD>V-"IDATx^<5E>С <0C><><EFBFBD>?-P<>@pH^F<>(kZ<6B><1F><0F>1<><31><EFBFBD>IEND<4E>B`<60><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
id="Layer_1"
data-name="Layer 1"
viewBox="0 0 750 750"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="PWA_Illustration_Lighthouse_05_Lighthouse.svg"
inkscape:export-filename="/Users/ericbidelman/Desktop/lh_logo_icon.png"
inkscape:export-xdpi="180"
inkscape:export-ydpi="180"
width="750"
height="750">
<metadata
id="metadata85">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title>PWA_Illustration_Lighthouse</dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1143"
inkscape:window-height="714"
id="namedview83"
showgrid="false"
borderlayer="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="50"
fit-margin-bottom="0"
inkscape:zoom="0.49370068"
inkscape:cx="330.80744"
inkscape:cy="423.36785"
inkscape:window-x="44"
inkscape:window-y="42"
inkscape:window-maximized="0"
inkscape:current-layer="layer6" />
<defs
id="defs3">
<style
id="style5">.cls-1,.cls-10{fill:#304ffe;}.cls-2{fill:#ffe082;}.cls-10,.cls-2{opacity:0.5;}.cls-3{fill:#2979ff;}.cls-4{fill:#ffd54f;}.cls-5{fill:#fff176;}.cls-6{fill:#f4511e;}.cls-7{fill:#e64a19;}.cls-8{fill:#c5cae9;}.cls-9{fill:#ff7043;}.cls-11{fill:#fdd835;}.cls-12{fill:#fff9c4;}.cls-13{fill:#448aff;}.cls-14{fill:#00c853;}.cls-15{fill:#64dd17;}</style>
</defs>
<title
id="title7">PWA_Illustration_Lighthouse</title>
<path
class="cls-1"
d="m 92.427653,571.02434 c 52.319997,0 52.319997,-33.94 104.639997,-33.94 52.32,0 52.31,33.94 104.63,33.94 52.32,0 52.32,-33.94 104.63,-33.94 52.31,0 52.32,33.94 104.64,33.94 52.32,0 52.32,-33.94 104.64,-33.94 49.48,0 52.17,30.34 96.56,33.64 a 326.73,326.73 0 0 0 8.09,-72.39 c 0,-179.87 -145.82,-325.69 -325.69,-325.69 -179.87,0 -325.699998,145.82 -325.699998,325.69 a 326.75,326.75 0 0 0 7.9,71.51 98.88,98.88 0 0 0 15.660001,1.18 z"
id="path9"
inkscape:connector-curvature="0"
style="fill:#304ffe" />
<path
class="cls-3"
d="M 345.99765,377.16434"
id="path13"
inkscape:connector-curvature="0"
style="fill:#2979ff" />
<rect
class="cls-4"
x="362.97766"
y="213.56435"
width="84.839996"
height="78.489998"
id="rect15"
style="fill:#ffd54f" />
<rect
class="cls-5"
x="362.97766"
y="213.56435"
width="29.950001"
height="78.489998"
id="rect17"
style="fill:#fff176" />
<ellipse
class="cls-5"
cx="392.29767"
cy="233.21434"
rx="19.84"
ry="24.889999"
id="ellipse19"
style="fill:#fff176" />
<path
class="cls-6"
d="m 360.89765,204.70434 a 43.835,43.835 0 1 1 87.67,0"
id="path21"
inkscape:connector-curvature="0"
style="fill:#f4511e" />
<path
class="cls-7"
d="m 405.10765,160.87434 a 43.51,43.51 0 0 1 43.46,43.83 l -43.46,0 0,-43.83 z"
id="path23"
inkscape:connector-curvature="0"
style="fill:#e64a19" />
<rect
class="cls-6"
x="352.41766"
y="203.29433"
width="104.64"
height="11.31"
rx="5.6599998"
ry="5.6599998"
id="rect25"
style="fill:#f4511e" />
<polygon
class="cls-8"
points="393,416 405.23,173.5 490.07,173.5 501,404 501,404 "
id="polygon27"
style="fill:#c5cae9"
transform="translate(-42.202351,118.02434)" />
<line
class="cls-9"
x1="449.03766"
y1="310.25433"
x2="452.29767"
y2="374.42432"
id="line29"
style="fill:#ff7043" />
<polygon
class="cls-9"
points="402.05,233.8 398.63,301.09 494.5,256.4 491.24,192.23 491.24,192.23 "
id="polygon31"
style="fill:#ff7043"
transform="translate(-42.202351,118.02434)" />
<line
class="cls-9"
x1="455.51767"
y1="437.66437"
x2="458.78766"
y2="501.8443"
id="line33"
style="fill:#ff7043" />
<polygon
class="cls-9"
points="395.25,367.4 391.83,434.7 500.99,383.82 497.72,319.64 497.72,319.64 "
id="polygon35"
style="fill:#ff7043"
transform="translate(-42.202351,118.02434)" />
<rect
class="cls-7"
x="349.98767"
y="255.90434"
width="109.49"
height="35.82"
id="rect39"
style="fill:#e64a19" />
<rect
class="cls-6"
x="349.98767"
y="255.90434"
width="71.779999"
height="35.82"
id="rect41"
style="fill:#f4511e" />
<path
class="cls-2"
d="m 403.97765,255.90434 c 0,13 -12.1,23.5 -27,23.5 -14.9,0 -27,-10.52 -27,-23.5"
id="path43"
inkscape:connector-curvature="0"
style="opacity:0.5;fill:#ffe082" />
<g
inkscape:groupmode="layer"
id="layer1"
inkscape:label="clouds"
style="display:inline"
transform="translate(-111.06999,296.26999)">
<path
style="fill:#2979ff"
class="cls-3"
d="m 653.72764,-50.455653 a 19.59,19.59 0 0 1 8.32,1.84 34.49,34.49 0 0 1 66.7,-9 l 0.12,0 a 23.25,23.25 0 0 1 0,46.5 l -75.14,0 a 19.67,19.67 0 1 1 0,-39.34 z"
id="path71"
inkscape:connector-curvature="0" />
<path
style="fill:#448aff"
class="cls-13"
d="m 430.72764,137.02435 a 16.6,16.6 0 0 1 7,1.56 29.23,29.23 0 0 1 56.53,-7.63 l 0.1,0 a 19.71,19.71 0 1 1 0,39.41 l -63.63,0 a 16.67,16.67 0 1 1 0,-33.34 z"
id="path77"
inkscape:connector-curvature="0" />
</g>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="stars"
style="display:inline"
transform="translate(-111.06999,296.26999)">
<circle
style="fill:#fdd835"
class="cls-11"
cx="593.86761"
cy="-88.77565"
r="3.53"
id="circle45" />
<circle
style="fill:#fff9c4"
class="cls-12"
cx="624.86761"
cy="109.62434"
r="6.1300001"
id="circle47" />
<circle
style="fill:#fff9c4"
class="cls-12"
cx="253.46765"
cy="53.594345"
r="6.1300001"
id="circle49" />
<circle
style="fill:#fff9c4"
class="cls-12"
cx="353.41763"
cy="160.21434"
r="6.1300001"
id="circle51" />
<circle
style="fill:#fff9c4"
class="cls-12"
cx="598.4776"
cy="11.644347"
r="6.1300001"
id="circle53" />
<circle
style="fill:#fff9c4"
class="cls-12"
cx="727.62762"
cy="169.54436"
r="6.1300001"
id="circle55" />
<circle
style="fill:#fdd835"
class="cls-11"
cx="240.26764"
cy="192.40434"
r="3.53"
id="circle57" />
<circle
style="fill:#fdd835"
class="cls-11"
cx="272.82764"
cy="121.09435"
r="3.53"
id="circle59" />
<circle
style="fill:#fdd835"
class="cls-11"
cx="294.73764"
cy="102.71434"
r="3.53"
id="circle61" />
<circle
style="fill:#fdd835"
class="cls-11"
cx="387.34766"
cy="20.004347"
r="3.53"
id="circle63" />
<circle
style="fill:#fdd835"
class="cls-11"
cx="679.86761"
cy="30.224348"
r="3.53"
id="circle65" />
<circle
style="fill:#fdd835"
class="cls-11"
cx="818.5976"
cy="177.65434"
r="3.53"
id="circle67" />
<circle
style="fill:#fdd835"
class="cls-11"
cx="328.67764"
cy="9.3943472"
r="3.53"
id="circle69" />
<circle
style="fill:#fdd835"
class="cls-11"
cx="640.89764"
cy="179.20436"
r="3.53"
id="circle73" />
<circle
style="fill:#fdd835"
class="cls-11"
cx="747.86761"
cy="90.754349"
r="3.53"
id="circle75" />
</g>
<g
inkscape:groupmode="layer"
id="layer3"
inkscape:label="light"
style="display:inline"
transform="translate(-111.06999,296.26999)">
<path
style="opacity:0.5;fill:#ffe082"
class="cls-2"
d="m 475.48764,-83.895653 -334.62,-47.789997 a 3.65,3.65 0 0 0 -1,-0.14 c -8.67,0 -16,31.889997 -16,71.149997 0,39.26 7.33,71.07 16,71.07 a 3.66,3.66 0 0 0 0.93,-0.13 l 334.64,-47.88 0,-46.28 z"
id="path11"
inkscape:connector-curvature="0" />
</g>
<g
inkscape:groupmode="layer"
id="layer6"
inkscape:label="shade"
style="display:inline">
<polygon
class="cls-10"
points="493.27,173.5 450.37,173.5 450.37,393 502,416 493.27,173.5 "
id="polygon37"
style="opacity:0.5;fill:#304ffe"
transform="translate(-42.202351,118.02434)" />
</g>
<g
inkscape:groupmode="layer"
id="layer5"
inkscape:label="GRASS"
transform="translate(-111.06999,296.26999)"
style="display:inline">
<path
style="fill:#00c853"
class="cls-14"
d="m 413.76764,275.48435 c 52.32,0 52.32,-33.94 104.63,-33.94 52.31,0 52.32,33.94 104.63,33.94 44.42,0 51.13,-24.46 84.16,-31.84 -45.13,-24.66 -112.53,-40.33 -187.84,-40.33 -75.63,0 -143.28,15.79 -188.41,40.64 31.93,7.73 39.02,31.53 82.83,31.53 z"
id="path79"
inkscape:connector-curvature="0" />
<path
style="fill:#64dd17"
class="cls-15"
d="m 413.86764,275.01435 c 52.32,0 52.32,-33.94 104.63,-33.94 l 1.1,0 -0.58,-37.32 c -74.89,0 -142,15.49 -187.08,39.91 31.16,7.98 38.55,31.35 81.93,31.35 z"
id="path81"
inkscape:connector-curvature="0" />
</g>
</svg>
<EFBFBD>PNG

IHDR a<><61><EFBFBD>~IDAT8<54>cp(<28><><EFBFBD>f<EFBFBD><66>K <0C>2{<7B>Q'<27><><EFBFBD><EFBFBD>T<EFBFBD><54><EFBFBD>e<EFBFBD>N<7F>Z<04><>U߾:<3A>~)<29><>Eɝ@_<>|<7C><>^<5E>Q<EFBFBD><51><16><><EFBFBD><7F><EFBFBD>N<EFBFBD>_<EFBFBD>hnQb۟<62><DB9F><EFBFBD>_?<3F><>"?<3F><><EFBFBD><EFBFBD><EFBFBD> <0C>8<02><><EFBFBD>/<2F><><EFBFBD>G<EFBFBD><47>)<29><><EFBFBD>3<EFBFBD>?;<3B>"z<> <00>(ާ/$IEND<4E>B`<60><>PNG

IHDR a<><61><EFBFBD>~IDAT8<54>cX<63><58><EFBFBD><EFBFBD>Vxi.C <0C><04><><EFBFBD><EFBFBD>:<3A>7<EFBFBD><37><EFBFBD><EFBFBD><Ʒ<>
8ijo<>b<EFBFBD><62>,<2C><><EFBFBD><EFBFBD>=<3D><><EFBFBD>Y.<2E>g<EFBFBD><67><EFBFBD>hj<08><>c<EFBFBD><63>4<EFBFBD><34><EFBFBD><EFBFBD>ݟ<>L<14><><EFBFBD><EFBFBD><EFBFBD><15>L=<3D>#<23><><EFBFBD>.<2E><><EFBFBD><EFBFBD><EFBFBD>7<><37>_M<5F>e`<60>[D<><44><00>Ƣ<EFBFBD><C6A2><EFBFBD><EFBFBD>
IEND<4E>B`<60><>PNG

IHDR4<00><1C><><00>IDATx<54>cX<63><58><EFBFBD>(<28>%9  <0C>Hr<48><72><EFBFBD><EFBFBD>
<19>pz<70><7A>\<5C>!<21>wT<77><54>ݼ(<28><>gXx<58><78><14><>K <20><><EFBFBD>4<EFBFBD>Ai{<08><>ղA<D5B2>ӂaᡧӹ<E1A1A7>/<2F><05><><EFBFBD><EFBFBD>,<06>!<21>!><3E><>+ <20> <0F><><EFBFBD><EFBFBD>y><13><><EFBFBD>ap<1A>B<>Sm<53>P1<><31><EFBFBD><EFBFBD><EFBFBD>8<EFBFBD>=<3D>v6<76><36>Յ<EFBFBD>XZ<58><5A>2<>=<3D><>:9`y<>~3<><33><EFBFBD><EFBFBD>&<26><><18><>~<7E><>:<
D<><44><07><><EFBFBD>y <0C>àb<C3A0><62><EFBFBD><EFBFBD>Ѧ<EFBFBD>`<60>{<7B><><EFBFBD>%<25>L<EFBFBD><4C>S<EFBFBD><53><EFBFBD><EFBFBD>|<06><><EFBFBD><EFBFBD>b<><62><EFBFBD><EFBFBD><1F>8<EFBFBD><38><EFBFBD> {ox1tIEND<4E>B`<60><>PNG

IHDR4<00><1C><><00>IDATx<54>cp(<28><><EFBFBD><7F>
,`({<7B><>{<7B>G!<21><1E><><EFBFBD>7d<37>w<EFBFBD>w<EFBFBD><77>z<EFBFBD><7A><EFBFBD><EFBFBD>:<3A><><EFBFBD>l_<6C><5F><EFBFBD>K<EFBFBD><0F>!<21>!<04><><EFBFBD><01><><05><>C)<>;<3B><>c<EFBFBD><63>C<EFBFBD><17>!<21>!<0E><> <09><>-<2D><>Ci]<>;<3B>|<05>Hv<1A>B<>І<EFBFBD><D086><02>$<03><EFBFBD>!<21><><EFBFBD><EFBFBD><EFBFBD>]K<>B<EFBFBD><42><EFBFBD><EFBFBD>!<21>!<04>h<EFBFBD><05><><EFBFBD><EFBFBD><1A>IΥ <0C><><1C>><0F>B<EFBFBD>~x
<EFBFBD>bZ <20>}v<1C><>v`-<2D>b<EFBFBD><<3C><><1A>8<EFBFBD>?<3F><><0F>`<60><><EFBFBD>R<EFBFBD>]n<>w<EFBFBD><77><EFBFBD><1D><>/<2F>#<23> >$qɗr,M<>:<3A><><EFBFBD>f<EFBFBD>IEND<4E>B`<60><>PNG

IHDR <03><><EFBFBD>`IDAT<08>c` t0`
&1<>g8<67>.h<><68><EFBFBD><EFBFBD>9<EFBFBD>,<2C><>"<22>+<2B><> 0<>>C2<43>d<><64><EFBFBD><EFBFBD>! <0C><>P<>!<21>n<EFBFBD><6E><75><18>0|
.c`D5<44> (x<><78> <0B>, <0C>ĉ<><06>V|h|IEND<4E>B`<60><>PNG

IHDRn<><6E><EFBFBD><00>IDAT(<28>c`8<><38>0<EFBFBD><30><EFBFBD>X<EFBFBD> <0C><19>3<EFBFBD><11>4<EFBFBD><34>P<><EFBFBD>#<23><><EFBFBD>0|+<2B><><EFBFBD>OH<4F>4<EFBFBD><13><><EFBFBD> ń<><C584>0\<5C>*<2A>OH)<13>F<EFBFBD><46>C <0C><><14>A<EFBFBD><41>cŔdcF<><46>B<EFBFBD><42>cPǦt<03><>P<><1D>O<EFBFBD><4F><EFBFBD> .<2E>,] <0B>|<7C> d<>1<EFBFBD><31><EFBFBD><EFBFBD><EFBFBD>݅uP<75><50> B 7<><37> <09><><EFBFBD><EFBFBD>p<14><><0E><><14> >B<><42><EFBFBD>5<EFBFBD><35><EFBFBD><EFBFBD>x<EFBFBD><78>7 *<2A>S<EFBFBD>r<EFBFBD>ҟ <0C>Ĥ0<01><>@űĦ]'<27><><EFBFBD><EFBFBD>aR<>UO<55><4F><EFBFBD><EFBFBD>IEND<4E>B`<60><>PNG

IHDR <00>˰IDATWc8<63><01>c<00>!<21>SSېU<00>̓X<CD83>{<7B><>IEND<4E>B`<60><>PNG

IHDR
 ~&<26>rIDAT(<28>c`<60>p0<70><30><EFBFBD>y<03>J<EFBFBD><4A>3b<33><62>1|gX<67><58>JP<4A>L<EFBFBD>.8;<3B><> B<><1A>ړ<18>2<EFBFBD><32>Y<EFBFBD> <0C><19>00<30>$<~1<>Bs.<2E>hZJ<18>3T<13><>T<EFBFBD>@8 <0B>b<>B<EFBFBD><42>D<EFBFBD>ZL<5A>V <0C><>PN<50>V<00><><1B><><EFBFBD><EFBFBD>0IEND<4E>B`<60><>PNG

IHDR<{
<EFBFBD><EFBFBD><00>IDATH<54><48>ұ<0E>P<18><><07><><30><D8AC> <16><>Gib<69>:<3A><>n&<26><06>t%<25>-ep{<7B><><EFBFBD>w<EFBFBD><77><EFBFBD><EFBFBD><EFBFBD>?Ӣ<><D3A2>ݳ<EFBFBD>i^#<23><>`<60>^<5E>K<EFBFBD><4B><EFBFBD><EFBFBD><EFBFBD>> fo逄~<7E>N <0C>1BL_<4C>)"<22>S=<3D><>P<EFBFBD>u<EFBFBD>!Vԋ3O<33>tX<74>VK<56><1C>Y<EFBFBD><59><EFBFBD>_<EFBFBD><5F><EFBFBD>~<7E><><EFBFBD>X<EFBFBD> D<><44>Ⱥ<EFBFBD><C8BA><11><>K|;<3B>sk<73>m<EFBFBD><6D>u<EFBFBD>v<EFBFBD><76>ӑ<EFBFBD><D391>؏<19>a!rÂG䂽F<>o<EFBFBD><6F><EFBFBD><EFBFBD>,IEND<4E>B`<60><>PNG

IHDR<00>H JIDAT<18>c<EFBFBD><63>@ DfF1<46><31><EFBFBD>(<28><><1B>#<23><>D<EFBFBD><44><EFBFBD>+,X<>P<EFBFBD>`<60><05><>"))b<><62>6<EFBFBD>B<EFBFBD>"<<3C>@
<EFBFBD>6A<14>Ua<><61><EFBFBD><1A><><EFBFBD><EFBFBD>=<3D>IEND<4E>B`<60><>PNG

IHDR&<00>ŕDIDATx^<5E>̱ <04><>~<7E><><EFBFBD>J<EFBFBD> :<3A><><EFBFBD><17>π<EFBFBD><CF80><<3C>uP癝5<><35>d<EFBFBD>dv<64>
3;<3B>0<EFBFBD><30>J3a<33>g<EFBFBD>j<EFBFBD>e~<7E>[x<>^<19>J DIEND<4E>B`<60><>PNG

IHDR<I/<2F> <0A>sRGB<00><><1C> pHYs  <00><>tIME<07>
%6j<36><6A><EFBFBD> IDATx<54><78><EFBFBD>i<EFBFBD><69><EFBFBD>U<1E><{<7B><><EFBFBD>CUݚK<DD9A>Ri<52>,K<>l<><6C>&<06><><EFBFBD>`<60> XBw<1A>t<EFBFBD><74>^<5E>4<EFBFBD>V:<3A>IH<>L: Ħ<><C4A6>!<21><>`+@<40><><EFBFBD><10>A<EFBFBD>5<EFBFBD>R<EFBFBD>4T<34>T*<2A>t<EFBFBD><><DFBB><><DEAB>sK <20><><EFBFBD>-<2D>ֹ<EFBFBD><>i<EFBFBD>g/<2F><><EFBFBD>3<EFBFBD><33><EFBFBD>?q<>D<EFBFBD>u<EFBFBD>P<EFBFBD> <14><04>H!)%" <20>$<24>H<EFBFBD><48>H$`<06>
$dP#<15><><04>!3͈d<CD88><64><00> "$3e <20>K$<24>܏<EFBFBD><DC8F>yl[<5B><7F><EEA3AC>><3E><>c<EFBFBD>k<EFBFBD>{<7B><>޾m<DEBE><6D><EFBFBD><EFBFBD>$<24>Ó<EFBFBD>7<EFBFBD><37>_<EFBFBD>o&<26>m'<27><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>%<25><>W]<5D><><EFBFBD>U<55>&.<2E><>2sB<02><><EFBFBD>̆z<><7A><EFBFBD><EFBFBD> l<16><><EFBFBD><EFBFBD>[<5B>ߒ?<3F><><EFBFBD><EFBFBD><0F><><EFBFBD>E<1F><><EFBFBD><EFBFBD><EFBFBD>s<EFBFBD>ε[<5B>{<7B><><05><>kf<6B>l(<28><><EFBFBD><EFBFBD>D0<04><><1D><>f<EFBFBD><66><EFBFBD><EFBFBD><EFBFBD>'<27><><EFBFBD><EFBFBD>g5oۿ<6F><DBBF><EFBFBD><EFBFBD><EFBFBD>{<02>ğfր<66>gf<67><66><EFBFBD><EFBFBD><EFBFBD><EFBFBD>L<EFBFBD><4C><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/gΜ޽g<DEBD><67><EFBFBD>lD<6C> %<25>Z<1B><>#<23>R<EFBFBD><52><EFBFBD><EFBFBD><EFBFBD>zH<7A><48><EFBFBD>7O/<2F><>-<1B><>a<EFBFBD>,8|<7C><>z<EFBFBD>s{PD<50>Y<EFBFBD><59><EFBFBD><EFBFBD><EFBFBD><1D>R<EFBFBD>\<5C><><EFBFBD><EFBFBD> /(<28><>d&x(<28>~<05>B<03>~<7E><><EFBFBD>P,<2C><>ߒ<EFBFBD><DF92><EFBFBD>_Y<5F>e<EFBFBD><65><EFBFBD>K<EFBFBD>1<l<><6C>g<EFBFBD><54><C3B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>87<38>V<EFBFBD><56><EFBFBD><11>ϡ<08><><EFBFBD>a><3E>ݹ<EFBFBD>7<EFBFBD><37><EFBFBD>o8<6F><38>?h(<28><>h<EFBFBD>θ<13><>~v<><76><EFBFBD><EFBFBD><>5<EFBFBD>N<EFBFBD><4E><EFBFBD><EFBFBD><EFBFBD><1E>%<25>-<2D>)<29>/<2F><><EFBFBD><EFBFBD>~h<17>g<EFBFBD>Z<EFBFBD> pA<70>m<>ީ<EFBFBD><DEA9><EFBFBD><EFBFBD><EFBFBD>Ą1<C484>M4g<34><67><EFBFBD><EFBFBD>n7ާo<DEA7><6F>3_<33>u<EFBFBD><75><EFBFBD>\<5C><>v<EFBFBD><76><EFBFBD><EFBFBD>؋<EFBFBD><D88B>}<7D><><EFBFBD>[q<>u'g<><67>s<EFBFBD>KnV<6E><56><EFBFBD><EFBFBD>%<25>/]<5D>%2<>ev<65>A<<3C><><EFBFBD>]^<5E>?<3F>h<EFBFBD><68><EFBFBD><EFBFBD>D.hX_p~<7E><><EFBFBD><EFBFBD> <09>o<EFBFBD><6F><EFBFBD>ڐ<EFBFBD><DA90><EFBFBD>jDC<44><43><EFBFBD>p<EFBFBD><70> -<2D><> }?<3F><><EFBFBD>P<EFBFBD>ʪ?yx<79><78>CM<43><><D892><EFBFBD><EFBFBD>D<EFBFBD><44> *<2A>C;{<7B>h<>73
<EFBFBD>ʟ<EFBFBD>?<3F><>m<EFBFBD><12> <09> <09>~8<>^<5E><><EFBFBD>;<3B><05><>~<7E><><00><EFBFBD>'<27>p<EFBFBD><70><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӑ<EFBFBD>v<> <09>'<27><>U<EFBFBD>B<1E>C<>rK<72>[<5B><><12>_jv<6A><76>SEO*L<>
Cx<EFBFBD><EFBFBD>r<EFBFBD>S?U<>o<EFBFBD><1F>/lx<6C><78>=<3D>><3E>S<EFBFBD><53>!<21><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><66><D3A5>g{<16><>|<7C>P<EFBFBD>p&x¡<78><C2A1><EFBFBD>qAm<41><6D>r<EFBFBD><72>M<EFBFBD>x{<7B>n<EFBFBD>K<7F>_<EFBFBD><5F>K$<24><1F><><7F><EFBFBD>U<EFBFBD><55>wH3<48>S<EFBFBD><04><>#y<><79><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>QJiO<69>O<1B>m<EFBFBD><6D><18>U<EFBFBD><55>طq<D8B7>E<>$}<0F>ډ9~8<>o8<mh<6D> -<2D> <09>ɖ<EFBFBD><C996><EFBFBD><EFBFBD><EFBFBD>$<24><>Cm<43><EFBFBD><7F>݇V~<7E>Ӑ<EFBFBD>j>C<>Y<><59><EFBFBD><EFBFBD><EFBFBD><EFBFBD>6<EFBFBD>0t<03>STk<54><6B><EFBFBD><EFBFBD>4<EFBFBD>}<7D>^o<>49N0<13><><EFBFBD>?<3F>'<18><><EFBFBD><EFBFBD><EFBFBD> <17>D<EFBFBD><44>ټ<EFBFBD><05><EFBFBD><7F><EFBFBD>}<7D><19><><EFBFBD><EFBFBD><EFBFBD>ٻ<EFBFBD>%<25>-<2D><><EFBFBD><EFBFBD>K<EFBFBD>:t<1C>o0᡾ ׿k<D7BF>{<7B>'|_<>g<EFBFBD> sb<73><62><EFBFBD>W<EFBFBD><57> <0C><><EFBFBD><EFBFBD>4<EFBFBD>)<29><>{<7B>=<3D>6<EFBFBD>5'n<>K<EFBFBD><4B><EFBFBD><1E>fAO<41>a<EFBFBD>; }!C<><EFBFBD>\<5C>}<7D><07>%<25>-<2D>)<29>/<2F>? هzO^<0F><><EFBFBD>e?<3F><><EFBFBD>i]׵'m<><6D>z5<7A>D<><44><EFBFBD><EFBFBD>Mן<4D><04>7$<24><>\6<1B>C<EFBFBD>i<EFBFBD><*'<>'O><3E><><EFBFBD><EFBFBD>Νk.<2E><><EFBFBD><EFBFBD>/%<25>nsЄ<02><>$<24><>Q4<51><34>Nȉ_'<14><><00>͎<EFBFBD><CD8E>_<EFBFBD>i¡?D<>r<EFBFBD><72><05>a<EFBFBD>w<EFBFBD>r1<72><17>~<7E><0E>`|<7C>k.<2E>R<EFBFBD><52><EFBFBD>Ҟ={v<><76>5<EFBFBD><35>}<7D><> Eo<45><6F>m<><6D><EFBFBD>[ k<><6B>h7jZАo<>Ѱa&"`<60>L<EFBFBD><4C><EFBFBD><EFBFBD>ϣ<EFBFBD><CFA3>{AL<41>QS<>0`<60><><EFBFBD>~<7E>!a<><61>C<0F><><EFBFBD><EFBFBD>t<EFBFBD><74> n<>4<02>$E<1A>d <04><>&@P<14><> <09><>;<10>1<EFBFBD><04><><01>H<>^Q<>A  <20>?<3F><><EFBFBD>t30<33><06><><EFBFBD>@)I@%<25>4@fTK<54><4B>K<EFBFBD>_J<5F>H<EFBFBD>M<EFBFBD>Q[<5B><>x<EFBFBD>"p<><70><EFBFBD>{<7B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>+<2B><>xm<78>Ɉ <06><>õg<C3B5>$<24>}<7D><><EFBFBD>o<EFBFBD><6F><EFBFBD>;?<><7F>G<05>=|<7C><>n<><6E><EFBFBD><EFBFBD>-<2D><>=<3D><16><03>_<EFBFBD>_|<7C><><07><><EFBFBD>ɇ?<><7F>Cv<1E><><EFBFBD><EFBFBD>7^<5E><><EFBFBD><17><>j<><13>K<EFBFBD>u$O<<>3w<33><77><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Oqh<71><68>W_r<5F>W<EFBFBD><57><EFBFBD><1D>V<EFBFBD><56>&<08><>R<EFBFBD><52>7<EFBFBD>
<EFBFBD><1C><><33>Xy<58>޸<><DEB8><EFBFBD><EFBFBD><EFBFBD>b <20>*<2A><><18>)<29><>j<EFBFBD>4
nD<EFBFBD><EFBFBD>! <0A><>p<EFBFBD>5INDP<44>'T@Y<04>ҀNi<><69><EFBFBD>4"p<><70>:H<><48><EFBFBD><EFBFBD><EFBFBD>,EO%ӈtτ!)4XM<58><4D><EFBFBD><10>H<EFBFBD>%,<2C><05>Omzv<7A>Ͻ<EFBFBD>Mw|<7C> O=<3D>ԁ<07><><EFBFBD>u<EFBFBD>f?<3F><><EFBFBD><18>1<EFBFBD>̇<EFBFBD><CC87><EFBFBD><EFBFBD><EFBFBD>!<21><0E><><EFBFBD><EFBFBD><EFBFBD>}<7D><><EFBFBD> <>P}<7D>Չ<EFBFBD><D589><EFBFBD>sۿ<73><DBBF>{o<><6F><1D><><EFBFBD><EFBFBD><EFBFBD>;<3B><>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>=w<><77><EFBFBD><EFBFBD>]K<>wO<77>=<0F><>'<1F><><EFBFBD>~⧞<><E2A79E><EFBFBD><EFBFBD>)g<>x<EFBFBD><78>Kwͭ{<7B><><EFBFBD><EFBFBD>v<EFBFBD><76>g<EFBFBD><67>vm۹w<DBB9><77><EFBFBD>7<EFBFBD>|<7C><>_<EFBFBD><5F>~<7E>S_<53>5n<35><6E>\<5C><77>gO<1F><><><7F>g<EFBFBD><67>X\ٹc<D9B9>fchDm<44><6D><EFBFBD><0F><><EFBFBD>{즛ߚ<19>*-<11> <0A>)<29>G<EFBFBD>2<EFBFBD><12><06>DzZ*<2A>3<><33><EFBFBD>H<>A0 DC<18>< <0C>N2c<32>4X2<58><32>1<EFBFBD>J<><4A>HedՖ<>4<00> <09><>PD9,!<21>$c<><1C><><1B><12>BY<12>&W&<26><><EFBFBD>[<5B><><EFBFBD><EFBFBD>U<><55><EFBFBD><EFBFBD><EFBFBD><71>v<EFBFBD><1A>FMX<4D>/<2F><>'b<>7۷<37><DBB7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>%2z<32><7A><EFBFBD><EFBFBD><EFBFBD>e<EFBFBD>@<40>x<EFBFBD><78>g~<7E><>_<EFBFBD><5F><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD><6F><>Soy3<79><33><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>,<2C><><EFBFBD>ҏ<EFBFBD> <09><><EFBFBD> <0B><><EFBFBD><EFBFBD>G<EFBFBD><47>m<EFBFBD><6D><EFBFBD>w<><77><EFBFBD><EFBFBD><EFBFBD><EFBFBD>`w<><77><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><7F>~<7E> <0B><><EFBFBD><EFBFBD><EFBFBD>W<EFBFBD><57><EFBFBD>,C<><43><EFBFBD>N|<7C><><EFBFBD><7F><EFBFBD><EFBFBD><EFBFBD>ο<EFBFBD>W<EFBFBD>y<EFBFBD><5F><00><>~<7E>W<EFBFBD><57>Ŀ<EFBFBD><C4BF><EFBFBD>u{n߶s׎<73>á8<C3A1>+<2B><19><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>{<7B><>k<EFBFBD>1<EFBFBD>z<EFBFBD><7A><03><>
+ <12><><EFBFBD><00><>,<2C><>!!<21>P<EFBFBD><50><EFBFBD><EFBFBD><19><>bK7o<19>d<EFBFBD><64><EFBFBD><EFBFBD><00>BϨ<><20><>`<60>D<EFBFBD>2ݬ&<26><><EFBFBD>5<EFBFBD>2f<32>V<><56>#"<22><>j@h<>4U<34>,^<5E>ɵ<05>?<07><><EFBFBD>FW_}<7D><>'<27><><EFBFBD><EFBFBD><EFBFBD>1<EFBFBD>p<EFBFBD>}N<17><>=w0tb<74>R&b<>.<2E><>{<7B><><0F><1E>"<22>{<7B><>'{<1E><><EFBFBD>?<3F><><EFBFBD>^wվC<07><><EFBFBD><EFBFBD>><04><><EFBFBD>_r<5F><72>W_<57>o><3E><>G~<7E>wn|<7C>{zC<><43>ѻ~'<1F><>_<EFBFBD><5F>kW<6B><57><06><>^?<3F>a,<2C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/<2F><><EFBFBD><1E><> <0A><><EFBFBD><EFBFBD>G<EFBFBD>Q{<7B>>t<><74>>w<><77>><3E>ܝ7<37><1B>:t<><74>O<`<60>L<EFBFBD><4C><EFBFBD>k<EFBFBD><6B>MO<4D><4F><EFBFBD>;?<><7F><EFBFBD><EFBFBD>-<2D>|Aj<41><6A>L<><4C><EFBFBD><EFBFBD>g<EFBFBD>}<7D><>n<>1<EFBFBD>0<EFBFBD>c<16>: <20><><EFBFBD><EFBFBD>s<><73><EFBFBD>1<><31>ez
%<25><><EFBFBD><EFBFBD>bL )<29><><EFBFBD><12><><EFBFBD>z
I:<3A><><EFBFBD>!<21>QRZB0<11>3"<22> <20>])<29><10><>"aT<61>&tQ<74>S*<2A><> <0B>"<22>0&<26><>,R<> HK<48> Ӊ<>Q.<00>4̡p<1A><><EFBFBD>0PBa.nA<6E> <20>.<2E><><EFBFBD><EFBFBD><<3C><><EFBFBD><EFBFBD>J)<29>w<1D><><EFBFBD><EFBFBD><y<><79><EFBFBD>~<7E><><EFBFBD><EFBFBD>=<1B><1B>m<EFBFBD>M<EFBFBD><06><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/,, <0C><>0躟Jd<4A><64><EFBFBD>pJ<70><4A>}<7D><>;<3B><><EFBFBD><EFBFBD>]<5D><>d3<64>rm<72><6D>><3E>'<27><><EFBFBD>f<EFBFBD><66><EFBFBD><0E><>=<3D>Z=<3D>l:y<><79><EFBFBD>.<2E>_<EFBFBD><5F><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <0B>65 <20><>8<EFBFBD><38><EFBFBD><EFBFBD><EFBFBD>u<17>?<3F><><17><>3<1E>{<03><><EFBFBD><EFBFBD><EFBFBD>?}<7D><>+w<>/<2F><><7F><ECBE85><EFBFBD><EFBFBD><08><>[?<3F>zfnin<69>U;~<7E>ޯ织<DEAF>%<13><><EFBFBD>d<EFBFBD>~b:<><7F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>z<EFBFBD>F<EFBFBD>@V< <20><>,(<28><>?0<>ԭ<EFBFBD>wyvʌ<76><CA8C><EFBFBD>7L<37><4C><1B><><EFBFBD>Z<EFBFBD><5A> <>`4<>4"<04><><EFBFBD><01><12>( <20>Jz<08><><EFBFBD><EFBFBD>Z}<7D><><EFBFBD><EFBFBD> <16>qV@֦<>
<EFBFBD>j<EFBFBD><EFBFBD><EFBFBD>̒E<65>F7
<EFBFBD> z<><01> aU<>sT<73> <09>ׂ<EFBFBD><D782><EFBFBD>[<5B>*<2A>Вl<D092>IW6s<36>)<29><>+%+<2B>p<EFBFBD>u<EFBFBD>#E)<29>ɔ<EFBFBD>Ă<EFBFBD>VG<56>b<03>`0<>$fg<1C><><EFBFBD>N<EFBFBD>!<21> @<40><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\[c2<63><32><EFBFBD><EFBFBD>/:4=7<><37><EFBFBD>d8<64><38>ђ`<60>,B)<02>*C&h<><68>0x<30>z<EFBFBD><7A><EFBFBD> '<27>;s<>̞={<7B><>?<3F><><EFBFBD>yIe<49>F4<46>><03><>O^17<31><37>z~<7E><>s<EFBFBD><73><EFBFBD><EFBFBD>X_+<2B><>km<6B><6D><EFBFBD>ѱ<EFBFBD>O<0E><><EFBFBD>D@r|<7C><><EFBFBD>o<><6F>a<EFBFBD>9 Z<><5A><EFBFBD>*uvz<76><7A>/<2F><><EFBFBD>3OL<04><>v<EFBFBD><76><EFBFBD>c<EFBFBD><63><EFBFBD><EFBFBD>Y<EFBFBD><59>v><3E>u#]tc<74><63>L<EFBFBD>;<3B><><EFBFBD>g<EFBFBD><06> I<><49><EFBFBD>;<3B><>>v<><76> 7<>PQ<50><51>`<55><D99A><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1F><>ggmjJ<6A><4A><EFBFBD>j<EFBFBD><6A><EFBFBD><EFBFBD>}<7D>gf<67><66>7<EFBFBD><37><EFBFBD>{<7B><>_<>:#<23>[K <20>V7<56>F<17>W <09><>B<EFBFBD>&<26><>JZ<08> ep<65>
#gfps<70><73><EFBFBD>t <09>d&<26>}鄐2<E98490><32><EFBFBD>92JR<4A><52>2G'<4B>N <20>)3<32><CF90>g<EFBFBD>h%<25><>M5<4D><35><EFBFBD><EFBFBD>;<3B><><EFBFBD><EFBFBD><EFBFBD>.<2E><<3C><>8{<><EEBC89>a<><61><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>$BQ<42><51>,<2C>ժ<EFBFBD><01>ld<6C>0;=5<35><7F><EFBFBD>G<EFBFBD><y<><79><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>6<11>Q<EFBFBD><51><04>ڻqG<71>QSVG<56><47>̔/M<><4D>.,<2C><>9<EFBFBD><39>az$<24><><EFBFBD>,<2C> ά<><CEAC> <0A>¯<EFBFBD><03><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>mi<6D><69>hӳ,3T<><54>L<EFBFBD><4C><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>g䆁i<E48681>>5<><35> <0B>s 3<>3>=<3D>Ӓ<EFBFBD>9<EFBFBD><39><EFBFBD><EFBFBD><EFBFBD>8~qvu<76><75><1B><> <0C><><><D59E>'O<>ܹse<<3C>f<14><><EFBFBD> ,g~<7E>xji<6A><69><EFBFBD>0^<5E><>
9<EFBFBD><EFBFBD><EFBFBD><EFBFBD>k<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>v|<7C><EFBFBD><7F>C<EFBFBD><43>9haP<61><50><EFBFBD>C2<43>jAY<41><59><EFBFBD>d<EFBFBD><64><EFBFBD><06><10><4B>A<15><><EFBFBD>D<EFBFBD>, <20><><EFBFBD>3<EFBFBD>$<14>LB K<16><><EFBFBD>$<18><><EFBFBD>afa<66>̔<EFBFBD><CC94><EFBFBD>t<11><>0<EFBFBD>Jz<4A>d&<26><#U`Ja٦=<3D>Q<EFBFBD>^Sh<53><68><EFBFBD>ܱ<EFBFBD>r<EFBFBD><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD>QJrvv<76><76><EFBFBD><17>R᲌<52>إ
<12>{e<><65><EFBFBD>S*<2A><>A<06>*<2A>T <54>D <20><><EFBFBD>qݷo<DDB7><6F><EFBFBD>ݻ<EFBFBD><DDBB><EFBFBD>3MCEzá#l04<30><34>i}<7D>w<1C><><19><>^vzj<0E>۸k/:<3A><>.<2E>e<EFBFBD><65><EFBFBD><EFBFBD>ܹ<07><>N<EFBFBD><4E>/\zi<7A><69><EFBFBD><1E>^A]<5D>y<EFBFBD>Ŝ<EFBFBD><C59C>E<EFBFBD>[<5B><>\<5C>å=<3D><><EFBFBD>m~<7E>4fV.i<><69> b-3w<33>8<EFBFBD>g9<67>ӋS<D38B>;f<><66><EFBFBD>ٽ{vώ<76><CF8E> S<>3><3E><><EFBFBD>g<EFBFBD><67><EFBFBD><EFBFBD>ڏ<EFBFBD>m<><6D><EFBFBD><EFBFBD>6<><36>ĉ׽<>uD<>"jJ!<21>BIݝ<49><DD9D>̝?6z<36><7A>a<EFBFBD>ȑ<EFBFBD><C891>'g<><67><EFBFBD>m<EFBFBD><6D><EFBFBD><EFBFBD>k<EFBFBD>An<41>u<EFBFBD><75><EFBFBD><EFBFBD>~<><7F>ݲ<EFBFBD><DDB2>^͊^<5E>HR<48>QȂ<15><>j<>*jg<6A><02>-<14><>a<>]03Ra!<21><>!D<>L"3᪪)""<22><16><12>Y3/U)e$ъv<>*Y&<26>$<24><>c<0F><>pKx0<78>MM*iIE2<45>{M<><4D>z<EFBFBD><7A><EFBFBD>/:Ԡ%<25><>㏥x!hx<>5<EFBFBD>><3E><><EFBFBD><EFBFBD><EFBFBD>877w<37><77><EFBFBD>0<EFBFBD>)P<13>%<13><><EFBFBD>TV<54><56>u[<5B>!2*ީSuR<11><><EFBFBD>uՌ\^Zz<5A><7A><17><><EFBFBD><0F>a<EFBFBD>_Q<5F>x<n<><6E>D<EFBFBD>B<EFBFBD>l<EFBFBD><6C><EFBFBD>u<EFBFBD>?<3F>;<3B>]<5D><><EFBFBD>l<EFBFBD><6C>}<7D><><EFBFBD>4<B><3E>Z<EFBFBD><5A>=u~<7E><><EFBFBD>0$cy<63><79>'N<><4E>z<EFBFBD><7A><EFBFBD><EFBFBD><EFBFBD>%Mo@<17><>^<5E><>j]<5D>{}[f<>a<EFBFBD><61>nf<6E>V<EFBFBD>|<7C><EFBFBD><E4A7A7>q~y<><7<><06>t^<5E>x5ί=<3D>~<7E><>{=3<><33>1 <0A><>4<EFBFBD>9"<22>?<3F>7<>
9hd- <0C><><EFBFBD><EFBFBD>?<>w<EFBFBD><77><EFBFBD>?<>3Or<4F><72>;<3B><><EFBFBD>ܷ|<7C> <0B>Zz<5A><7A>}_<>85<38><35><EFBFBD>N<><4E>>
<EFBFBD><EFBFBD>Z<EFBFBD>/ %k<><6B><08>ݬR<DDAC><52><EFBFBD>;;<3B><>"<22><14>6C#3aP<61>M0O<30><4F>b <0A><><EFBFBD>V<EFBFBD><56>m<EFBFBD><6D><EFBFBD>"LNV<4E>Q<EFBFBD>HC<48> +,# 7<><37> <20>1=<12>e<><65><EFBFBD>!L%=<3D><><EFBFBD>h<EFBFBD><68><EFBFBD><EFBFBD>Q<05> O<><05><>Z`<60><>#~<7E><13><><EFBFBD><EFBFBD> _s<5F>[-<2D><><EFBFBD>><3E><><7F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><th34+:|<7C><>}<7D>޷<EFBFBD><DEB7>Җ<EFBFBD><D296><EFBFBD>iI<69><49>֦eQP<><50>d<EFBFBD>yf*<2A>"<22>CU<43><55><EFBFBD><EFBFBD>Œ<EFBFBD>Q뙖<51>G<EFBFBD><5<><35><EFBFBD><EFBFBD><1D>?<3F><><EFBFBD><6D>۽<EFBFBD><DBBD><EFBFBD><EFBFBD>ο<EFBFBD><CEBF><EFBFBD>_vY<76><59>'<27><><EFBFBD><EFBFBD>xn<78><6E>sǞ=<3D>><3E>q<EFBFBD><52><DBB9>˚<EFBFBD><CB9A><EFBFBD><EFBFBD><EFBFBD>;<3B>~<7E><><EFBFBD><07><><EFBFBD>(eH<>[<5B>3<EFBFBD>۟?<3F><><EFBFBD><EFBFBD>gw<67><77>aS<61><53>iA<69><41><EFBFBD>_;<3B><><EFBFBD><EFBFBD><EFBFBD>:x<><78>|4;<3B><00>/<2F><><EFBFBD><EFBFBD><EFBFBD>O;s慽<73><76><CE8F>}<7D>`<60><>s<EFBFBD><73>>xד<78><D793><EFBFBD>_y<5F>ۦ<EFBFBD><DBA6>0<EFBFBD>|<7C>V<EFBFBD><56>|<7C>12smmm<_}<7D><>9<EFBFBD>XD­d<C2AD>H<EFBFBD>\<5C><>d<7F>Gǫ_{<7B>3{~<7E>?<3F><>3W<33><57><1D>}<7D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD>ƅ<EFBFBD>O<EFBFBD><4F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>b<EFBFBD><62><12>J<19><><1A>JhT<68>37(+<2B><>&<26>[<5B><>"<22> <09><><19><>g<EFBFBD><67>A2<41><32>%<25><><EFBFBD>)<29> <0A>%RanH<6E><48><EFBFBD><EFBFBD>4<EFBFBD>%6<>m<EFBFBD>H<11>$<24>N<EFBFBD>y<01>D1됥*<2A>f<EFBFBD>9Y!<21>L<EFBFBD><03>0Q<30>,H<0F>k-w<><77>=5<><35><EFBFBD>g><1B><><EFBFBD>#O|<7C><>;<3B><><EFBFBD><EFBFBD>]w͵<77><CDB5> -ds<64>SG<53><1D>F<EFBFBD><46><EFBFBD>;<><7F><EFBFBD><EFBFBD>2<>2*%(<30>d<06>3-K<>H<13>(<28><00><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ǧ<EFBFBD><C7A7>F<EFBFBD><51><DF81>Œ<EFBFBD><C28C><EFBFBD>{祇s ے5<DB92>95=<3D>0<EFBFBD><30><EFBFBD><EFBFBD>'<27>:q|mz&<26><><EFBFBD>t<EFBFBD>'<27>=v<>C<0F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>_7<5F>{O<>5-<2D><1F>ӳ <0B> <0B><>;v<><76>g]<5D>k<EFBFBD>z<EFBFBD>ܩ#O>q<>}Gά<1F><EFBFBD>7<EFBFBD>-m8<6D>6'1<>N<EFBFBD><4E>X<EFBFBD>u<EFBFBD><75><EFBFBD><EFBFBD><EFBFBD><1E>uf<75>̙<EFBFBD>G?z<><7A>Oו<4F><D795><EFBFBD>+K{z<><72>a<EFBFBD><61>X<EFBFBD>v=z<><7A><EFBFBD>_?;<3B>Ѕ<<3C>4+<2B>2<EFBFBD><15>\<5C><><EFBFBD><EFBFBD><EFBFBD>r<EFBFBD><72><EFBFBD><EFBFBD>g.y<><79><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD><6F>']p<>8><3E><><EFBFBD><17><><EFBFBD><EFBFBD><EFBFBD><1E><>;V<><56>v<EFBFBD>Mͽ<><CDBD><EFBFBD><15>
<EFBFBD>%`<60><><EFBFBD>KU<>nd"a!n<><16><>fV6֐<>@Ҫ<><D2AA><EFBFBD>I<EFBFBD><49>r<EFBFBD><72><1A>C1<43>p<EFBFBD><70><12>F4<1E><>uiI<>h<EFBFBD>0<EFBFBD><30>465Fҙ <09>N&<26><>H<EFBFBD><><C39C>4K<34><4B><EFBFBD>As<41><73><1D>;v<><76>Moy<6F>W}<7D>W<EFBFBD>G}9h<39>-.,<<3C><>cKKKmtLMM=ztǮ=<3D><>bV<14>Y
HJÒ=Ou<05><>j<EFBFBD>B4e<><14>(+F<><46><EFBFBD><EFBFBD>/<2F><><EFBFBD><EFBFBD>83 <0B><><EFBFBD>n[<5B><><EFBFBD>>(*"<22>2<EFBFBD>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD>'<27><><EFBFBD><EFBFBD>Ï<EFBFBD>{<7B>v<><76>y<EFBFBD><79>ۯ~<7E>fgWWW<57>l<EFBFBD>6C<36><43><EFBFBD>c<EFBFBD>w^<5E><><EFBFBD>/<<3C><>ǟ<EFBFBD><C79F>޻<EFBFBD>`~<7E>ж<EFBFBD><D0B6>p<EFBFBD><70><EFBFBD>d<EFBFBD><1F>ǽ<EFBFBD>><3E>hoJ<6F><4A><EFBFBD><><1B><>ѧ<EFBFBD>z<EFBFBD>ه<EFBFBD><D987><EFBFBD><>\<5C><>͇<EFBFBD>_7<5F>s]<5D>M<EFBFBD>55}<7D>Y<EFBFBD><59><EFBFBD>P<EFBFBD>N<EFBFBD>ڳoO<6F><4F>LJ<4C><4A>NTAWQ<57>*F<>ӿ<EFBFBD><D3BF>]7<>uO<75>xn<78><6E><EFBFBD><EFBFBD>S<EFBFBD>ƵG<>L<EFBFBD>5<><35>U;*<2A>EM<45>U<EFBFBD>@M<>Ɏa<C98E>9-<17> <0B>@G#<23><01>L8Y=<3D><><EFBFBD>y<EFBFBD>i <19>f<EFBFBD><66>'<27><>4<EFBFBD>hdPB8dfe&<26>]<5D><>f<EFBFBD>4<16>+*<2A><>;<3B><><EFBFBD>HS<>*<2A>@<1A><1C><>F^%^Ch]B<>s󂺬<19>f|9hQs<51><73><EFBFBD>'?ur߾}<7D><>enn<6E><6E>S'<17>Eɑ<45>H<EFBFBD>)<29><>sc<73><63>(T5<54>qT'TE<54><45>BEj<45>VKZ<4B>xyy<79><79><EFBFBD>]YY<59>H<EFBFBD>؈<EFBFBD>ʗ<EFBFBD><1E><>SSS} e<1B>C^{}}}4=<3D><>-o=<3D><>w6<77><36>ֺ<EFBFBD><D6BA>~<7E><>ٵ<EFBFBD>g<EFBFBD><1E>H<1E><>Z]]-e<><65><EFBFBD>_<5F><7F><EFBFBD>8<1A><>j<EFBFBD>u]<5D><><EFBFBD><EFBFBD><EFBFBD>-<2D>#<23>QS<51><53><EFBFBD><EFBFBD><EFBFBD>7^<5E><>?7<><37><EFBFBD><EFBFBD><6E><D7BE><EFBFBD><EFBFBD><EFBFBD><EFBFBD><57>'<27>'|\<5C><><EFBFBD><EFBFBD><EFBFBD>_s<5F><73><10><>3 f<><66><EFBFBD>fP<66>Ls<4C>t.N<><4E><EFBFBD>=<3D>w}<7D>N<><4E>3˿z<CBBF><7A>f<EFBFBD><66>ګ<EFBFBD><DAAB><EFBFBD>'<27>c(#d<>F<><46>P<1D>*Zvc<76>L<02>fu<66>,E5<45>L<EFBFBD> <0C><>/-<2D>LF<4C><46>Q <0A><>tX*<2A><74><CBA8>
;<3B>"Q>V<><56>Պgi<01><><EFBFBD>D2R<32><52>j <0A>["<22>k<><6B>#A<>)X0I<30>H<02>@& <20>RDe<10>ZA <1F><><EFBFBD><EFBFBD>}<7D><>/<2F>|<7C>M <09><>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD>[<5B>|<7C>8<EFBFBD><38><EFBFBD>` L_u<5F>U'O<>\YYi<59>k۶m<DBB6>><3E>̎<EFBFBD>׭<EFBFBD>?g(25<13>h<EFBFBD>Pk<50>d<EFBFBD><P!<21>,<2C><><EFBFBD>0<>Z `<60><><EFBFBD>.<2E>#<23><>m<EFBFBD>Μ9<CE9C>}<7D><>a<EFBFBD><61>Fa<46> <0C><>Ir}}<7D><>i<EFBFBD><03>N?<1E><><EFBFBD>k#<23>7<1D>sh<73>H6<48>{"i<<1E>>}<7D><><EFBFBD><EFBFBD><02><> Me<><1E><>Z<EFBFBD><5A><0E><><EFBFBD><EFBFBD>^<5E><1F><><16>V<>lԍ7<D48D>8VUN<55><4E> Ly*=<3D>rN]<5D>r<EFBFBD><72><EFBFBD>dfn<11><><EFBFBD><7F>?<3F><><EFBFBD>C_<5F><7F>4<EFBFBD><34><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>i<EFBFBD><06>#<23>ߕ6oMC|Ն,D 5*RE$<24>#̘mo<6D>{hTg<54><67>d]<06>ai<61>0K<30>+MnDb<><62>5<02>5<EFBFBD><11><><EFBFBD><EFBFBD><EFBFBD><14>UųY<C5B3>5<EFBFBD><35><EFBFBD>%-̀P@<40> ѣz<D1A3><7A>l&<26>*X<>4<EFBFBD><34><EFBFBD>41<04>iG<69> 4<16><><EFBFBD>w<EFBFBD><77><EFBFBD>Ͽ<EFBFBD><CFBF>7<EFBFBD><37> o<>ed<65><64>m<EFBFBD><6D>Y<EFBFBD>s<EFBFBD><73><EFBFBD>F<EFBFBD><05>u<EFBFBD><75>]v<><76><EFBFBD>~<7E>-<2D><><EFBFBD><EFBFBD><EFBFBD>܋<EFBFBD>Y<EFBFBD><59>N(<47><D089>D<EFBFBD><18>;&3<> <20><>$<24><>7'<27>R<EFBFBD>t<EFBFBD>[<5B><><EFBFBD><EFBFBD><EFBFBD>ȣ<EFBFBD>/,, <0C><>l<EFBFBD>B<EFBFBD><42><EFBFBD>w\q<><15>W}<7D><>DA<44><41>؈<EFBFBD>6z<36><7A>6<EFBFBD><36>1 t<1E>5M5"<22>:<3A>d<><64><EFBFBD>'7L$<24><>t<>se6g?<0F><%<25><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>]<><7F><EFBFBD><EFBFBD>J<17>fL<03>(<1E>[ v<><76><EFBFBD><EFBFBD>_<EFBFBD><5F>2g<32>3<EFBFBD>ϟ<CF9F><7F><EFBFBD>~<7E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>#<23>{<7B>v<EFBFBD>P<EFBFBD><50><EFBFBD>S<EFBFBD><53><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><16><><EFBFBD>i<EFBFBD><0E>҈4<D288><34>:<3A>M!eJ<65><02><>9<EFBFBD>q2^7<> <20> <20><>*<2A>YZ]6<><36><EFBFBD>ja<>(<28><>2<EFBFBD><32>Jzf-,(<16>nZ<><5A><EFBFBD>A:<3A> {69<<3C>d<11><><><D594>0<EFBFBD>k<03>v<>ZYٱ<59><D9B1><EFBFBD>_<1F><0E><><EFBFBD><EFBFBD><EFBFBD>۷<EFBFBD><DBB7>Ç\<5C>rвjai<61><69><EFBFBD><1F><><EFBFBD>.$gΞYZZ3<>wDZۛ*<2A><08>@<40><>T<>9R<01><>#<23>Kinv<6E><76>ѧ<17>gZ/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.94A5<><35><0F><1C><>R<><52>BU<42><55><EFBFBD>v<EFBFBD><76>x<EFBFBD>{<7B><>)<29>/0Q<30>g<02>{z<>0<EFBFBD>fo<0F>'z<>i<EFBFBD>p<Q«<51><C2AB><1F><>SO<53><4F><EFBFBD><EFBFBD><EFBFBD><17>2<EFBFBD>M<EFBFBD>n<EFBFBD><12>(*i<>f<EFBFBD>i<EFBFBD><69>
<EFBFBD>><3E><>oҹ0<D2B9><30><EFBFBD><0F>:<3A><>w<EFBFBD><77><EFBFBD>Ϗ <0C><>`<60><05><><EFBFBD>_f<5F>~KXz <0B>y<EFBFBD><79>c<EFBFBD><63>Ts<54>)Y<><59>(f<12><><EFBFBD>AC<41>(f<><66><EFBFBD>)<29>LO<4C>Y<EFBFBD><59>lc<6C><63>d<16><><EFBFBD><EFBFBD><EFBFBD> <0C>`<60><>4<EFBFBD>.&7<><37><EFBFBD>E <15>H"<22>F<EFBFBD>D<EFBFBD><08><><EFBFBD><08>bJ<62><4A>"J&E1$q<>d<EFBFBD>V<EFBFBD>F<EFBFBD>={vv<76>-#<23><>ئ<EFBFBD>W<EFBFBD>Fqa~<7E><><EFBFBD>YZZj<5A>wzz<7A>ȑ#{<7B><>E<EFBFBD>Bi<> <0C><><EFBFBD>'<1B>&Y<>
<EFBFBD> <0C><><EFBFBD> <20><>PaL<61>!p<><70>S<EFBFBD><53><EFBFBD><13><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>>|I?l&<26>u <0A>8<EFBFBD><38>f>5<>Ծ<>=<3D><15><>19<31><39>4o<>H<EFBFBD><48><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Oi߷Ыa<D0AB><61>a,T<>]?<3F><><EFBFBD>_<EFBFBD>57E<37><45>P2)O6Ύpdn<><6E><EFBFBD>{o<>3s<33><73><EFBFBD><EFBFBD>+:
<EFBFBD>X<EFBFBD><EFBFBD><EFBFBD>N<><4E>g<EFBFBD><67><EFBFBD><EFBFBD><EFBFBD><EFBFBD>+<2B><><EFBFBD>
<EFBFBD>xWZ<57>)A<>*x@<40>`@<40><>'<27>
<EFBFBD>d <0B>PP<50>6<EFBFBD> !)<29><><EFBFBD>0#,-<2D><>è*<2A>d<EFBFBD><64>ZӁ4<D381>T<EFBFBD>jʕc<CA95><63>
@1%$<19><>d<EFBFBD><64>a<EFBFBD> f1<66>m<>Fz<46>5<EFBFBD>&q-<2D><>#<23>e<EFBFBD><65><EFBFBD><EFBFBD>O<4F><7F><EFBFBD>d<EFBFBD><64>y<>ԩ<EFBFBD>+<2B>HQ<48>V<<3C>.<2E>Q0ܲ<30>M<<3C><1B>.<2E>J:-<2D><><EFBFBD>W<><57>\X^z<><7A>Gv<47><76>=<3D><><EFBFBD><EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD>/.<2E>U &<26><03>О"<22> X?NZ<4E>n<6E>v<EFBFBD><76><07><>l&<26><> <0C>'<27><>a\<5C>p<EFBFBD><70><EFBFBD>/<2F><<3C><>-'<27>Y<EFBFBD><59>?<3F><><EFBFBD>^t <20><>Ғ 3<>4Y<34><59><EFBFBD><EFBFBD><EFBFBD>. uo<75><6F>Ư<EFBFBD><C6AF><EFBFBD><EFBFBD><EFBFBD>?<3F><> W<>}<7D><1B>S<EFBFBD>=<3D><><EFBFBD>e<EFBFBD><65><0F><1D>Wm<57>*<2A>j<EFBFBD>i3T,e<><65>q<EFBFBD><14><02><><EFBFBD>W<EFBFBD>fb<66>R<06>%<25><><EFBFBD>[D<><44>I<15><08>4%<25>ͱ<><CDB1>V<EFBFBD>)<29><><EFBFBD>L<1D><><EFBFBD>` <09><><EFBFBD>dh<64>՜<12><><EFBFBD>H<EFBFBD><48><EFBFBD> Q<><51><EFBFBD>Q*ӕ<>16<31><36>3M<><4D>25<32><35>'O<><4F><EFBFBD><EFBFBD>k{aa<61><61><EFBFBD><EFBFBD>?v<><76><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;h<><68><EFBFBD><EFBFBD><EFBFBD>p<EFBFBD>$<03>fjAZ<10><1C><>)w<><77><EFBFBD>[?~<7E>؞={&<26>Q<7F><51>mT<6D>z<EFBFBD>DhѰ<68>MO<4D> 7><3E><><EFBFBD><EFBFBD><EFBFBD>ͅ<EFBFBD><CD85>R<EFBFBD>}u<>f<EFBFBD><0E>}_<>i<EFBFBD><69>VOG <0A>4^<5E>OqVy<56>i<EFBFBD>f <0C>e<EFBFBD><65><EFBFBD><EFBFBD>{<7B>W}<7D><>v<01>g<EFBFBD>#)<29>OQ ¬<><C2AC><EFBFBD><1B>\u<><75><EFBFBD><1D><>T._<1E>IDAT<41><54><EFBFBD><EFBFBD>tV'b45=<1E><>SA<53><41>Z<EFBFBD><EFBFBD>$<24>A<EFBFBD>[<5B>O+<2B><>/ZDKx<00>tp#<23>γ<EFBFBD>$ <0C><>4<EFBFBD><34>23<32><18>β<11>/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><06>V-<k<>V1Z<><17>LK<4C>`j]<5D><><EFBFBD>i<EFBFBD>#<23> <><7F>E<EFBFBD>_qŕ<1F><><EFBFBD><6C>u<EFBFBD><75><EFBFBD><EFBFBD>K.<2E><>ĉ=t<>ٳg<D9B3>Y<EFBFBD><59> <0B><>a<17>|<7C><>fff.<2E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <0C>y<EFBFBD><79><EFBFBD><EFBFBD><1D><><EFBFBD>R6<52>Um`<60>A2<41>*<2A>i<EFBFBD><69><EFBFBD><EFBFBD>c<EFBFBD>{=|<18><>E<>Ѩ<EFBFBD><D1A8>-<2D><>׮7<D7AE><37><EFBFBD><EFBFBD><16><>Ys<59><73><EFBFBD><EFBFBD>J<EFBFBD><4A>3gJ-<2D>,<2C><>['<27>@<40><11>4E-<2D><><EFBFBD>(KRU<52>p:<3A>ɻ<EFBFBD>ũ<EFBFBD><C5A9>l<EFBFBD>(<28>ar <0B><><EFBFBD>a,<2C><>z#WE<57>( <09><>TšC<C29A>K<EFBFBD><4B>y<>6<EFBFBD><08> <69>-<2D>p<EFBFBD>Hb<48><+PL5Z<35>Օ2<02>FP(<05>FwKcq<63>P˧c<CBA7>j<EFBFBD>o!<21>"ӡ4!<21>g<0E><58>c45<>K<EFBFBD><4B>WVV<56><56><EFBFBD><EFBFBD><1E>a<EFBFBD><61><EFBFBD><EFBFBD><EFBFBD>G<><47><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>_<EFBFBD><5F>8L)<29>Cl<43>K<EFBFBD>7<EFBFBD>9<EFBFBD><17>*<2A>-<15><><EFBFBD>^/<2F>W<EFBFBD><><DAA1><EFBFBD><EFBFBD><EFBFBD><13><><EFBFBD><EFBFBD>n F=<3D><><EFBFBD><1E><><EFBFBD><EFBFBD> -<2D><>B<12>G<EFBFBD>y<>[<5B><1A>]<5D><>
lI<6E><12><>&<26>X)$`)<29>*c<>B<EFBFBD><42><EFBFBD><EFBFBD><17>N$<24>x\
C0: B.+@<40>e<EFBFBD>H<EFBFBD>3-rs(<28><>VU!<21>%$<24>a<EFBFBD><61>iR<02><1C><><EFBFBD><EFBFBD><EFBFBD>º<>zq<7A><71><EFBFBD>@ʹ<><CDB4>-7<><37><EFBFBD>TE <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"b$v<>n<>f<EFBFBD><66>R&D"F*<2A>&<26>J<EFBFBD>{t2&<26><>B<1B><>ozӛn<D39B><6E><EFBFBD>k<EFBFBD><6B><EFBFBD>_BZ<42>T<EFBFBD><54>'<27> ټQذ<51><D8B0><EFBFBD><EFBFBD>lf<6C><66>:<3A><><EFBFBD>P<EFBFBD>oKW<4B><57><EFBFBD><EFBFBD><EFBFBD>~<11><><EFBFBD>>Np<18><><D48D>ҟ<EFBFBD>S<EFBFBD><13><>޲mW k<>6ORs<52><73><EFBFBD>V<13><><EFBFBD><EFBFBD><EFBFBD>{<7B><><EFBFBD> <0B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>q{<7B><>s<EFBFBD>x<><78><03>>|h=:of<6F><66>@<40>V<EFBFBD><̈́0s<30><16>ޕDq<14>j<EFBFBD><6A><EFBFBD>_<EFBFBD>!w<><77>5<EFBFBD>2<EFBFBD><32>Z8Ҳ4<D2B2>-@<40> y4W~V[<5B>w<00>Ê<>NL4x<34>2<EFBFBD>0<EFBFBD>$<24><>LW<4C><57>3<>)"<22><><EFBFBD>TK*u<><75><EFBFBD>-h<>><3E><><EFBFBD>%<25>_|<7C><>x<><78><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>K(<28><><EFBFBD>^<5E>z<>ܵ<EFBFBD><DCB5><EFBFBD>o:t<>%<25><><EFBFBD>
#U<><55>E<EFBFBD><45><EFBFBD>Ay<41>R<EFBFBD><52>v_EB<45> Q<>"<22>0<03>I<10>o<><6F><EFBFBD><EFBFBD>lg`d2<>E<EFBFBD>9ڄp:<3A><>r<EFBFBD><72>Ɋp<C98A><70>"<22>F<EFBFBD>"<22><><10>r<EFBFBD>֑I<D691>HX<48>,2+<2B>"B<>4<EFBFBD><34>H<13><>R<11><><16><>Zc<><63><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>G<1E><><EFBFBD><07>9<>j<EFBFBD>BP<42>;<3B><>;<3B>D<EFBFBD><44>ǍġV<C4A1>Vj<56><6A>`K<> (<28><02>h<EFBFBD>u<EFBFBD>XwI/͂Z<CD82><13>@#<23>JXn<58><6E><15>
<EFBFBD>4<EFBFBD>O<EFBFBD><EFBFBD>~<7E>h<><68><EFBFBD><EFBFBD>_*g<>R<EFBFBD><52>V<EFBFBD><05><>i<EFBFBD>y<02><><EFBFBD>ZJ<5A><4A><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD><63><EFBFBD><EFBFBD>Υ<EFBFBD>4H8Ti<54> <0C><>+<2B>Ų3<C5B2><33>%#<23>P"<22><><EFBFBD><EFBFBD><EFBFBD>d<EFBFBD><64>V<EFBFBD><56><EFBFBD>`<60>LcƆӒ<C686><D392><EFBFBD><EFBFBD>K<EFBFBD><6B>O<EFBFBD><4F><EFBFBD>(<28>QC )C&EI<12>A <0C> <0C>\<5C><>s<11><>j(<28>t<EFBFBD><74><EFBFBD>b<EFBFBD>p<EFBFBD><16><>
Z(+<2B><>%<25>_~Y<>i^<5E>C<1A>'k<><6B><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>B¬%7<>Rԁ#e<><65>
<EFBFBD>RAc<EFBFBD>`<60><>Q:<K $<24><><EFBFBD><EFBFBD>H<>i<EFBFBD> d<><64><02>aa<61><61>L<EFBFBD>ƿC$"27<32>T<><17>*`HA<48>+<00>E&<26>V<EFBFBD><56>i<EFBFBD>pY<70> <20><>ZYPkyM<><4D>T<EFBFBD>bL<62>B,#<23><>3B<33><42><EFBFBD>(FȘU0cIU<49><55>t5h<35>V<EFBFBD>/G(\2<> BG:<3A>n.<11><1B>
<EFBFBD>ʌHs<EFBFBD><EFBFBD>I^<5E>A<EFBFBD>4&<26>/3 <09>V_<56>%<25> T<><54><EFBFBD><EFBFBD>Hr <20><>-lA{͡<05><><<3C><><EFBFBD><0E>'k<><6B>7<37>W<EFBFBD>|3C
X!&<26>t /%#<06>B8GnL2<>D6<44><36>HXi9<69><39>D<EFBFBD><44>e2<65>U<EFBFBD><0F><>'j<>(<28>o<EFBFBD>@ <0C>nD"<-<2D>L<EFBFBD>"<22><19><19><>Ey!<21>OH%6<>1<><31>2P<32><50>"V<><16>-h<><68>A+<2B><<15>F˚pcʼ<63><CABC><EFBFBD><0E><><EFBFBD><EFBFBD>;G <09>{IT<49><54>![] <0A> bT<10> <20><19><><EFBFBD>uJc<4A><63>%<25>BT<42><54>Z]<5D>*U<><55><EFBFBD>%F<> X<>dm{C<><04><>, <0C>B<EFBFBD>ܕD<DC95>V<EFBFBD>Tu<54><75><02><><1E>2<1C><><EFBFBD><EFBFBD>6<EFBFBD>)<29>B<EFBFBD>1R <09>
a4y:
<EFBFBD>*#%<25>d<EFBFBD>e<EFBFBD>LKK<4B>,@0F<30>s<1A><>H<EFBFBD><79><D28A><EFBFBD><EFBFBD>6<05>+M<><4D>dN<64> <09><><11><><02>%<25><11>^,œ`A<>=F<> yqWU<16>"s$ӌ#]%<25>f#@<40>k*`<60><05>OZ<>$<24>J<EFBFBD>G<EFBFBD>!<02>!B*<2A>p<12><><EFBFBD><EFBFBD><EFBFBD>(`<60>0<EFBFBD>B<EFBFBD><42><EFBFBD>z<>("!<21><11><> 7<>ʼn<EFBFBD><C589>v<EFBFBD>N<EFBFBD><4E>ޱ<EFBFBD><DEB1>+<2B><>`9<><39>R<EFBFBD>b<>(fA<66>:<08>\<5C>B<EFBFBD>5<EFBFBD><35>L9L
X<EFBFBD>H<EFBFBD>WJ!:<3A>;j<>;<3B><>l<EFBFBD><6C>|9@<40>B<EFBFBD><42><EFBFBD><EFBFBD><EFBFBD><EFBFBD><<3C>u<>B<EFBFBD><42>2<EFBFBD>N<> <0C>D!&a<> <09><>D<>!<19><0E><><EFBFBD>@+<2B><><EFBFBD> <0C>hEU<45>N5A]<01>l:_ Dɠ[<5B><>2<03>[<5B>e<EFBFBD><08>M<EFBFBD>!<21>B
J<0F><><EFBFBD>2S<06><1B>JH<4A>˂d<><64><EFBFBD>)B+=<3D>]<5D>ZxuYJ<59>pB`<60>\<5C>X<01>he<68>k
*<2A><><C79E>j3<6A>CRҌ<52>i<EFBFBD><69><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>n<EFBFBD><6E>l;<3B><>m<EFBFBD>"PMӠ%<25><>aUja<6A>U<EFBFBD><55><EFBFBD>'pS<70><53>L3Tz<54>X9<58><08> <0C><05><>h*TF <0B><><EFBFBD><EFBFBD>VX<1E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>|<7C>W~<7E><>ₙa<E28299><61>:<3A>x<EFBFBD>q<EFBFBD>(<28><08>Sa4<61>R <0C>J<EFBFBD>rD1<44><31>~<7E><>1<EFBFBD><P<>@P<06>s<11>#X<1D>(<28><><EFBFBD><EFBFBD>04n<34>-<11>p<EFBFBD><70><EFBFBD>R&G<>X<EFBFBD><58><EFBFBD>H)ELO<4C>XҜ%/!"3i<33> /`lĻU<C4BB><55> -<0E><> <09>A<EFBFBD>Ϝ<EFBFBD><CF9C><EFBFBD>k^|Q <1D>:<3A><>?n!<21> i<><69><EFBFBD><EFBFBD>
2<EFBFBD>ު`z<><7A><14>R<EFBFBD>jNXN<58>DCʑ <0C><>@<40><>"<22><19><>B<EFBFBD><42>Y<EFBFBD>* Q<><51><EFBFBD><05>A<EFBFBD>- <09>S锦<53><E994A6>LJHR*<2A><>#h<>,A<><41>XM<58>D<14><1A><1C><>F`<60> 6<><36><EFBFBD><EFBFBD><EFBFBD>ZJV|yiqk<71>n<>A<EFBFBD><41><EFBFBD><02>l<EFBFBD>%<25>2"<22><71><DEA2>%<03>a<EFBFBD><61>#JZ<4A>R
1<02>2+"<22>DQ<>TVFD<46>j<>I<EFBFBD>*uJ<75><4A>h<11>IB<49>j<EFBFBD><6A><EFBFBD>. lś:<3A>5,<2C>l<EFBFBD>li<6C> TkM(<28>J<EFBFBD>I<EFBFBD>@<40>HU<48>Q<EFBFBD>:<3A>eM<06><>ԭc<D4AD><63><EFBFBD><0F>Q)<29><><EFBFBD><EFBFBD>Ηr9G<39> sȑ]{E<>P& Y<>)<29>Hf2<66> atdz"]<5D>!0" eҼ<65><D2BC><EFBFBD><EFBFBD>VP<56>`W<><57><EFBFBD>i <09>ɼK<C9BC><08>D#<23>5"]n<>Ȱ<EFBFBD><C8B0><EFBFBD>e:<3A>E<EFBFBD>R&"%<13><08><>B)j<><6A>5<EFBFBD><02>F0<46><30>N<EFBFBD><4E>w<><77> -<2D> <0A>(<28>e<EFBFBD>,<2C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֱu<D6B1><75>mZ<6D><5A>r<EFBFBD>0a̮m?Fw%8B<38><42>cc<63><63><EFBFBD>#D<><44><EFBFBD><EFBFBD>P3A<33>g<EFBFBD>LQ DQ<44>!<21>-<2D>[" p<11><>T<><54><EFBFBD>r<EFBFBD>X <0C>2Y<32>e0 3I<33>RT<52><54><EFBFBD>Nk<><6B>Z<EFBFBD>
<EFBFBD>t<EFBFBD><EFBFBD><EFBFBD>=<3D><>#<23><><1B><><EFBFBD><EFBFBD><0F>9{fqq񪫮~<7E>;<3B><>eW\<5C><>L<EFBFBD><4C>O<EFBFBD>?<3F><><EFBFBD><EFBFBD><EFBFBD>EBK<42><4B> "<22><><EFBFBD><EFBFBD>f<EFBFBD>/<2F>{<7B> o<><01>A<EFBFBD><41><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1F>g<EFBFBD>L/MFNRnPyc<79><63><EFBFBD>s?<3F>s<EFBFBD><1B><><EFBFBD>~<7E><><EFBFBD><EFBFBD>V<07>:.<h<>.<05><>U#2<>e<EFBFBD><15><>J<EFBFBD><02><>d<EFBFBD><64><EFBFBD><EFBFBD><1F><>o~<7E>}<7D><><EFBFBD>[nyVK<56>L<EFBFBD>X<18><13>DX$P<>[a&<26><44>F<1A><><EFBFBD><EFBFBD><EFBFBD>p<EFBFBD><70><17>x׳Ǟ9<C79E><39><EFBFBD>k_w<5F>B<EFBFBD><42><EFBFBD>Jj*ʘ<><CA98><EFBFBD><EFBFBD><08>U<EFBFBD>+[^U&<26>p/x<>̹<CCB9><7F>|<7C>ӟ^XX<58><58><EFBFBD>u<EFBFBD>ӧO<4F>S<EFBFBD><53><EFBFBD><EFBFBD><EFBFBD>mo<6D><6F><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/<2F><><EFBFBD><EFBFBD><EFBFBD>@K<><4B><EFBFBD> <0B>0<EFBFBD>mr<6D><19><>?<3F>K<1F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><7F><EFBFBD><EFBFBD>[<5B><>W39;77=3<><16><>2<EFBFBD>lT<6C><54><EFBFBD>/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>[ny<79><7F><EFBFBD><EFBFBD><EFBFBD><EFBFBD>><3E><>_<EFBFBD><5F><EFBFBD><7F><EFBFBD><EFBFBD>ָ<EFBFBD>:.HDb…$Y<12><><EFBFBD><EFBFBD>
HaY<EFBFBD>.!<21><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>}<7D>3<EFBFBD>ۿ<DBBF>'<><7F>r<EFBFBD><72>2g<32><67>Ja<><61>!UR<55>2@<40>X=)G<>p$<24> <0C>G<>6<EFBFBD><36>QO<51>xvO<EF818B>>}<7D><><EFBFBD>`<60>l<EFBFBD><6C>q<EFBFBD>(<28><J<>*<2A>R *O<>e<EFBFBD>,HW<48>;<3B><><03><><EFBFBD><EFBFBD><EFBFBD>w<EFBFBD><77>Ç<EFBFBD><C387>۷w<DBB7><77>K.<2E>d<EFBFBD>޽<EFBFBD><DEBD><1F><><EFBFBD>K<EFBFBD><4B><EFBFBD>ο<EFBFBD><CEBF><EFBFBD><EFBFBD><13><>uϞ=ChI<68><49>)%k<><04><>fhp<68><0F><><EFBFBD><1F>ȿ>|<7C><>/<2F><>G?<3F><>[I<>x<EFBFBD><1B><><EFBFBD>d<EFBFBD>͔<>z<><56><DA96>u<EFBFBD><75><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˭~<7E>ֱuL<75><4C>IEv<45><76>VX"k<><6B>;<3B><><EFBFBD>H]<5D><><EFBFBD>G<EFBFBD><47><EFBFBD><EFBFBD>K.9Tk<EFBFBD>馷@
T3<EFBFBD>z<EFBFBD><EFBFBD># ]<5D>#E&S<>e<EFBFBD>l<15>$<24>
U<EFBFBD>y<EFBFBD>ɴTE<EFBFBD><EFBFBD>w<EFBFBD>%<17>9wv߾]<5D><u<><75>{<7B><><EFBFBD><EFBFBD><EFBFBD>M<EFBFBD><4D>^<5E><>(<1C>pE<70>V<<1E><>T<EFBFBD>bE4<1B><><EFBFBD><EFBFBD>?{<7B>쾽{w<><77><EFBFBD><EFBFBD>o~<7E><1B>x<EFBFBD><78><EFBFBD>s<<3C><EFBFBD><EC9D9F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><71>YPC<50>t<19>i<EFBFBD><69>r!<21><><EFBFBD><EFBFBD><EFBFBD>O<EFBFBD><4F>S?<3F><>]t<><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD>܇?<3F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>7<1F>y%<25><><EFBFBD><EFBFBD>m#6<><36><EFBFBD> ,<2C>/U<><55>,z<><1D>qˇ><3E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>l<EFBFBD><6C>[<5B><EFBFBD>JY: <0C>Z4ru(<28>tYV<59><1F><><1F>瞻/<2F><>boy<6F>[<5B>근w}|<7C>Q"<22>ԑ<><D491>Ci<32>20U<30><55><EFBFBD>a<EFBFBD>V<13> +J<>^t<>⧞~<7E><><EFBFBD><17><><EFBFBD>u<EFBFBD><75>s<0F><EFBFBD>5W_]<5D><>U`<1D><><05>N<1D>m7<6D>H<EFBFBD>n=<3D>Н_<D09D><5F><EFBFBD><EFBFBD><03>KK<4B>o<EFBFBD><6F><EFBFBD><16>jh<6A>4 7<><37><EFBFBD><EFBFBD>}<7D>ӟ<EFBFBD><D39F><EFBFBD><EFBFBD><EFBFBD>3<EFBFBD>v<EFBFBD> <19> 0<><30>Q<EFBFBD><51>Q<EFBFBD><0E><11>1<EFBFBD><31>9<EFBFBD><39>w~<7E><><1F><>޽<EFBFBD><DEBD>o<EFBFBD><6F><EFBFBD>l߾=3<33><7F>\X\~߷<>o<EFBFBD><1B><><EFBFBD>ɪ”<C9AA><C294><07>K <09><EFBFBD><7F>x<<3C><>><3E>><>c<EFBFBD>x<EFBFBD>-<2D><><EFBFBD>xl[G<01><>0e<30>%<25><><EFBFBD>n<10><>?<3F><>w<EFBFBD>}<7D><>_<><5F>_<EFBFBD>_<>-<2D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>}
. <20><><EFBFBD><EFBFBD><EFBFBD>D<EFBFBD>']"<22>L<EFBFBD>kr<6B><13>eY<>>r<>fVBeґq<D291><71>G"<22><>Ww<57><77>u<EFBFBD><75><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ꫮP8,+5<>D<13>ɝ\<1E>&7<><37><EFBFBD>o<EFBFBD>ֶm<D6B6>|<7C>7~<7E><><EFBFBD><EFBFBD><EFBFBD>xL<78>B<EFBFBD><42><EFBFBD><><7F><EFBFBD>nۿo<04>m<EFBFBD>#@<40><>`<60><>b<EFBFBD><11>2<EFBFBD><04><>hdy<64><79><0F>؏<EFBFBD><D88F><EFBFBD>;w<><77><EFBFBD>0sA液cEҏ<45><D28F><0F><><1F>;<3B><><EFBFBD><EFBFBD>ځ<EFBFBD><19>T<EFBFBD>L^<5E>H9<48><39>o<03>2<EFBFBD>V<EFBFBD>E<EFBFBD><01><><EFBFBD>}뷾<><EBB7BE><EFBFBD><EFBFBD>[omeٷ:<3A><><EFBFBD><07>6<EFBFBD><36>T"<22><><EFBFBD>kQ<6B><51>R<EFBFBD>F<EFBFBD><46><EFBFBD>}<7D><>ع<EFBFBD><D8B9>~<7E><><EFBFBD>#<1F>ș<EFBFBD>g<EFBFBD>N<EFBFBD>Ҿ<><D2BE><EFBFBD><EFBFBD>[n<><6E>ڙ%R<>$( <0A>*<2A>.<2E>Q<EFBFBD>`<60>C=<3D><><EFBFBD><EFBFBD><03><03>V<EFBFBD><56>gf<67><66><EFBFBD><16><>Z<EFBFBD><5A>]<5D>v<EFBFBD>8~⡇<><E2A187>ˮ<EFBFBD>.陁@<40>@<40><>H<><48><EFBFBD><02>ѧ<EFBFBD>ZXXȈ<58>^<5E><><EFBFBD><EFBFBD>V<EFBFBD><56>d<EFBFBD><64> <1F><>'?<3F>{<7B>n/<2F>F<EFBFBD><46><EFBFBD>L<EFBFBD><4C><EFBFBD>L<EFBFBD><4C>$<24><16>D<EFBFBD><44><EFBFBD>`<60> E=<3D><>?<3F><>?<3F><6D>;w<>9<01><>ܭmv<6D><0F><>?<3F><><EFBFBD><7F><EFBFBD><EFBFBD><EFBFBD>C<1D><>b<EFBFBD>(<28>*`T<>\E<><45>J<EFBFBD>j <09>?gggfgg^<5E><<3C>o<1D>ul<1B>V<EFBFBD><56> ҋX^<11>J!<21><><EFBFBD><EFBFBD>q<EFBFBD>E]4;;Ks*v<><76>1???QJ<51>m<EFBFBD><6D>[<5B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><10> <0C>L<><4C>Z<EFBFBD>X-D<><44><EFBFBD><EFBFBD>><3E>{<7B>^3Z<33>n<02>
<EFBFBD><EFBFBD>S# #<23>LM<4C>\Yy<59><79><EFBFBD>˯Ȯ<CBAF><C8AE>e%"<22><>i<>[*<12><><EFBFBD>(^P<>h<EFBFBD><68>NsW<73><57><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1D> <20><>)<13><><EFBFBD>j]ˎRaf֢<66>!c5s*<2A>:<3A><><0F><><EFBFBD>???<3F>s<EFBFBD>N/<2F><><EFBFBD><EFBFBD><00><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>s<EFBFBD><73>Z<EFBFBD><0F><>?<3F><><EFBFBD>׿<EFBFBD><EFBFBD>]E<><12><>;+<2B><>U<EFBFBD><55><EFBFBD>l<>L<EFBFBD><4C>:<3A>ul<><7F>B<EFBFBD>3<EFBFBD>B<EFBFBD><42>yD<79><44><14><>]<5D>z<EFBFBD><7A>w<EFBFBD>mf<6D><66>azjjc<6A>xI㓴<49><E393B4>x<EFBFBD><78>7$<24>ԈQ<D488><51><EFBFBD><EFBFBD>Y<><59> <07><>e<EFBFBD>/{<7B><> <0B><>K[<5B>iD֨<44><D6A8><EFBFBD>m<EFBFBD>8*i]<5D><><17>m<EFBFBD>`@ <0A>C<12> Y<><59>ŔUsss<73>Ξ{<7B><> <0B>ϯ<EFBFBD>hAJ<>j<17><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><01>2M<02><><EFBFBD>1<EFBFBD>ѢS<D1A2>2I<32><0E><18>΋<1D><><EFBFBD><7F><EFBFBD><EFBFBD>}<7D>;*#<00>kk<6B><6B><EFBFBD>w<EFBFBD><77>_<><5F>O<EFBFBD>v<EFBFBD><76><1F><><EFBFBD>/<2F><><EFBFBD><EFBFBD>><3E><><0F><>_<EFBFBD>5j<35>"<22><><EFBFBD>8-Gf<47>W<1C><>5h<35><68>/<2F><><EFBFBD><EFBFBD><EFBFBD>b4<62><34>eѢw<D1A2><77>ny<6E><79><EFBFBD>#<1F><><EFBFBD><EFBFBD>ggf<67><66>־<EFBFBD>M_<4D>m<EFBFBD>}/h-}_e2Q<32><51><EFBFBD>ٵ<EFBFBD>/<2F><14>݋<10><>2<EFBFBD>*<2A><><EFBFBD><EFBFBD>K<1C><>

3<EFBFBD>"<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>*<2A>ϳ<EFBFBD><CFB3><EFBFBD>[<5B><><EFBFBD>\z<><7A><EFBFBD>ؚ<EFBFBD>U<12> j<>$H<>-:rX <20><><0F><><EFBFBD>P<EFBFBD><50><EFBFBD>02<30><01><>:<3A>RDB5<11>mm{<7B>}<7D><><EFBFBD>g<EFBFBD><67><<0E>)<29><>T1<><31><EFBFBD>3:'or<6F><72>|w<><77>k<EFBFBD><6B>|<1C><><EFBFBD><EFBFBD>N.m<><6D><EFBFBD><EFBFBD><EFBFBD>7<EFBFBD>u<EFBFBD>}<7D><><EFBFBD><EFBFBD> l<> tEd <0C><10><>ef<65><66><EFBFBD>?<3F><>/?e<><65><EFBFBD><EFBFBD>o~<7E><>G=<3D>1B<31><42><EFBFBD><1C> <0B>L <08>H<EFBFBD>#<23>nA' <20><19>%<25><>|<7C>u<EFBFBD>V<18><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>w<EFBFBD>v<EFBFBD><76><EFBFBD><EFBFBD>#<23><>̧/]<5D> <0C><>ONNW!mH<6D> <0B>f<EFBFBD>6<<3C>v^<5E><><EFBFBD>L{<7B><>03<><01><15>C<EFBFBD><43><1E> V<><56>|<7C><><EFBFBD><EFBFBD><EFBFBD>_x<5F>lw<6C>m<EFBFBD>g?<3F>ُ}<7D><>oݼq<DDBC><71><EFBFBD>n<>z<EFBFBD><7A><EFBFBD>s<EFBFBD>7n޸<6E><DEB8><EFBFBD>[<5B><><EFBFBD>C<EFBFBD><43>2<EFBFBD>,<1B>)<29><><EFBFBD>PR<50><52><EFBFBD><EFBFBD><EFBFBD><EFBFBD>twvzzvvzk<7A><6B><EFBFBD><EFBFBD>wg<77><67><EFBFBD><EFBFBD><EFBFBD>ן}<7D>۷mNN<4E><4E><EFBFBD><EFBFBD><EFBFBD><>j1'<10>6<> <09><>0<EFBFBD><05><><EFBFBD>x䑪<78>|<7C><><EFBFBD><EFBFBD>٧<EFBFBD><D9A7><EFBFBD><EFBFBD><EFBFBD> <0A>%-<13><><EFBFBD><EFBFBD>y<EFBFBD><79><EFBFBD><EFBFBD><EFBFBD><EFBFBD>}<7D><><EFBFBD>tI<74>q<18>[<5B><> <0A> <09>HE:Fo&0<>K{~~^<5E>0:??_Is<49><73>=i#l<><6C><EFBFBD>2<EFBFBD>]<5D><>)pP<70>Y=<3D>+_x <1B><18><><EFBFBD><EFBFBD><EFBFBD><1A>(6 P<><50>)<29>E<EFBFBD><45><EFBFBD><<><7F><EFBFBD>=<3D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;<3B><><EFBFBD>_}<7D>O<<3C><><EFBFBD>0<EFBFBD><30>[O1C<31><43><EFBFBD><EFBFBD>e7<65>dڅb
L<EFBFBD><EFBFBD><EFBFBD>h<EFBFBD>=$ľk<00><><EFBFBD>|<7C><>g<EFBFBD><67>y<EFBFBD><79><EFBFBD><EFBFBD>˷_~<7E><><EFBFBD><EFBFBD>5<EFBFBD><35><EFBFBD><EFBFBD>IT<49><>`O<>!K"<22><>x<><78><EFBFBD>Fć?<3F><><EFBFBD><EFBFBD>s<EFBFBD><73>1k<31><6B><EFBFBD><EFBFBD>܇><3E><>[7o><3E><><EFBFBD>O}<7D><> .ita[mӐ܀<D390>_*m<><6D><EFBFBD><EFBFBD>yQ<79>^<5E>_[ZHH3V<33><56>km<6B>_<19>L{<7B>W<EFBFBD>[<5B><><EFBFBD><EFBFBD>* <0C>݈0<DD88><30> <0C>w<EFBFBD><EFBFBD><7F><EFBFBD><EFBFBD><EFBFBD><EFBFBD>W<EFBFBD><57><EFBFBD><EFBFBD><EFBFBD><EFBFBD><7F>'<27><>ʤ<EFBFBD>'<27>S<EFBFBD>H<EFBFBD><48><18><>C<><43><EFBFBD>#64"jU}d9<16>D<<3C><><EFBFBD><7F>MW<4D><57>yו7<D795><37><EFBFBD>}<7D><><EFBFBD><EFBFBD>@<40>iD<69><19><><EFBFBD><EFBFBD><EFBFBD><04>h<14><>ׯ<D7AF><7F><EFBFBD><EFBFBD>4<EFBFBD><34>O|<7C><><1F><>K<EFBFBD>.<2E><><EFBFBD>^<5E>x<EFBFBD><78>w<EFBFBD><77><EFBFBD>ŋ<EFBFBD><C58B><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>J<EFBFBD><0E>"<22>@t<>b<13><><EFBFBD>*3<>'<27>ee^<5E>96<39>|<7C>]#x<>ä<EFBFBD><C3A4><EFBFBD><<02>#<23>Ӿ<EFBFBD><D3BE>c<1C><EFBFBD><E585A8>N<EFBFBD><4E><EFBFBD>J
<EFBFBD><05>s$<24><><EFBFBD>><3E><>Ǯ?v<><76>۾<EFBFBD><DBBE>/<2F><>]<5D><><01>Lf6ڪ6<03>sa<73>"<<3C><><EFBFBD>"y(<28>N<EFBFBD>S<EFBFBD>pg<70>L+<2B><><>_<EFBFBD><5F><EFBFBD>w<EFBFBD><EFBFBD><7F>Y<EFBFBD><59><EFBFBD>V<EFBFBD><56><07>8`G <09><><EFBFBD>,<2C>)<29><>@<40>6<EFBFBD>}<7D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>S_~<7E><> ۅ<>G<><47><17><><EFBFBD>~<7E>=<3D>~<7E><>}<7D><><EFBFBD><EFBFBD><EFBFBD>,f<><66>X<EFBFBD><58><EFBFBD>i^~Ԕ[<1D>|雝<><E99B9D>C<EFBFBD>q1<71><31><EFBFBD>k<EFBFBD>Z<EFBFBD><5A><EFBFBD>7ϴ<><CFB4><EFBFBD>3m<33>F<EFBFBD>A <0C><43>Є#<23><><EFBFBD><EFBFBD>=<3D><><EFBFBD>߹~}<7D>???=SF<53>lfnQ<6E>(uE<75><15><>2<06><>(#\<1B>e<EFBFBD><65> Ys<><73><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>[<5B><><EFBFBD>|<1F><>pq<70>Dw2p-<2D>'v<1B><><EFBFBD>'<10><>H<<3C><><EFBFBD>{<7B>7<1E>җ<EFBFBD><D297><EFBFBD>7<EFBFBD>yzvv<76><76>+><3E><>ÿ<EFBFBD><C3BF><EFBFBD>ko><3E><>n<0F><07> <0A>@<40><74>9H<39><01>vgk<67>EE<45><45><01><><EFBFBD><EFBFBD><EFBFBD>dد!<21><><EFBFBD>d¯~O{vv<76>я<EFBFBD><D18F><0F><><EFBFBD>m<15>xy<78><79><1F><><EFBFBD><EFBFBD><EFBFBD>Q<>04<30><34><EFBFBD><EFBFBD>z<EFBFBD><39>@VxcN<1F><>4<04>ư<14><><EFBFBD>Zk<5A><6B><EFBFBD><EFBFBD>
m<EFBFBD>h722 <18>FN<02><>7r&B <0C> D(@<40>;2W7S<37><53>m,G<><47><EFBFBD><EFBFBD><EFBFBD>d<EFBFBD><64><EFBFBD><11><>]<5D>1<EFBFBD><31>[<5B><><EFBFBD><EFBFBD><EFBFBD><43>t<EFBFBD><74>5<EFBFBD>ǭ[7<>blWn<57>B<EFBFBD>a<EFBFBD>7<EFBFBD>n<EFBFBD><6E>kK<6B><4B><EFBFBD>.<>_<5F>W<EFBFBD><57><03>'''<27><<3C>̂<18><><EFBFBD>Y<EFBFBD>_<EFBFBD>z<EFBFBD><7A><EFBFBD><EFBFBD>LJ<EFBFBD><18>ϴTa<54><61><1C>U<EFBFBD><1A><><01><><10>t<>kuL<75> Q<><51>m<EFBFBD>1܅<><DC85>8܅HȘ<>X]<5D><>E$<24><>#m<><6D>#<23><1A>6<EFBFBD> 9<>,<2C><><EFBFBD>Pp;<3B>H<EFBFBD><48>\D<><44>TƲI72<05>p6OE<4F>ƀ+r<><72><43><1B>[+0<><30>A<EFBFBD>n><3E>\!26<>;i<>L<EFBFBD>Jμx<CEBC><78>իW_<57><5F>i<EFBFBD>q<EFBFBD><71><EFBFBD><EFBFBD><EFBFBD>z<EFBFBD><7A><EFBFBD>iͰd<CDB0><64><EFBFBD> <20><><EFBFBD><EFBFBD>R<EFBFBD><52><14>ee <20>d<>A<>rG&Z<><5A><EFBFBD><EFBFBD><EFBFBD><EFBFBD> J<>j<EFBFBD> <0C><>=<3D>%F<><46>"\<5C>\7"v<> <09>{b1<62><31><1A>څ<EFBFBD><03>1l'<27>FJ<46><4A>f0'@L#<03><1B>i <20>W9<57><39>1<EFBFBD><1B>c<EFBFBD><63><EFBFBD>|H% <20>f<04><16>=h<13>B@$A <06> <20>K<><4B><EFBFBD>$<24>kD<0F>`
`z!<21> <0B><><EFBFBD>#<23>X<EFBFBD>WVn^<5E>-<11>R<>"~<7E><><EFBFBD><EFBFBD>A<EFBFBD>u(<28>4^<5E>l7<6C>#ѣ<>i#Y<12>|<7C>Hcwf<77>x<EFBFBD><78><EFBFBD>|<7C><><EFBFBD>L<EFBFBD>l&<26>D<EFBFBD><44><EFBFBD> <0B><># <1B><>Ջ<EFBFBD> <09>NmAA<41>GF<47><@g<><67> <0A><><EFBFBD>!<21>"<22><><1A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>5=<3D><>̲F<CCB2><46>謩mtwb<77> <0C><15><><05>-0<>a<EFBFBD>k>h<><18>0<EFBFBD>[<5B>^<5E><><EFBFBD>G<EFBFBD>
<EFBFBD>N<EFBFBD><EFBFBD>|<7C>ҕo}<7D>_@<40>y<EFBFBD>G<><47>c<EFBFBD><63>gZR<5A><52>L<EFBFBD><4C> <0A><>Rw <20>6<EFBFBD><36>
S<10><><1C><1A><><EFBFBD>-){<7B>gh<>*<2A>Ȥ<EFBFBD><C8A4><EFBFBD><EFBFBD><EFBFBD>jF${U<><55>aJ<61>(q<>Z<EFBFBD>K <09>+<00><04>Q=Gr<47><72>8e
<EFBFBD><EFBFBD><EFBFBD>f!,;P<>@L2<4C><32><EFBFBD><EFBFBD>i<><69><EFBFBD><EFBFBD>{<7B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD>C<EFBFBD>K<1A><><EFBFBD>d8eA<65><08><0F>BX <0A>(q<><71>9<EFBFBD>9<EFBFBD><39>s<EFBFBD>Cnn<6E>SN 
v<EFBFBD>D<EFBFBD>{<7B>(<28><><1C>ta$-%<25><><EFBFBD>XdHY#<23>;<3B>6TWDFS<46>- R<>unMeb<65><62>0Tf<1C><><EFBFBD><EFBFBD><EFBFBD>uens<1B>tDVE<56><45>=b<>j( ǂ<><C782>hpӢbd8rk7;<3B>v<15><19>.<2E><>t<EFBFBD><74><EFBFBD>tE$& <0A>Q<EFBFBD>@<13>DĀ:VqH<71>S<>]<5D>`<60>3<EFBFBD><33>5<EFBFBD> <09>j xr<78><72>{ȈZ<C888><5A>׍4<D78D><34><EFBFBD><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD><6F>޻<EFBFBD><DEBB>‹<08>^<5E><>X<>5<EFBFBD>a;j<><6A>5<1F> <20>Ȱ<EFBFBD><C8B0><EFBFBD><EFBFBD><EFBFBD>(CV<43><56><EFBFBD> b!<03>IB4 <0C><>ȅk6<6B><36><0E>'<17>t<EFBFBD>0+ L<><4C><EFBFBD>Wg<0F><><03><>(<28><>)mh75<>ـ+1<><31><EFBFBD><EFBFBD>(*F<>%<25><>s<EFBFBD>5#<23><> O<>"Y<>n<>jw1 %<10>j<EFBFBD>*
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>I<1B><>n`C9h'z<><7A>M<01>TXM<07><>@ɚ<01><>`@<40><><EFBFBD><EFBFBD><EFBFBD>G<EFBFBD>&o괁 ^hsb6G6 <0B><><EFBFBD>m <0A><02><>h<>D3F<33><46><EFBFBD><EFBFBD> 8<<3C>f<EFBFBD>31
4<><34><EFBFBD><EFBFBD>f<03><>r<EFBFBD><01><14><>h:`@=<3D><>S0<53><30><02><><EFBFBD><EFBFBD><>#<23><><EFBFBD>͊<><CD8A>Y6<1E><><EFBFBD><EFBFBD>:J<><4A><EFBFBD>6<EFBFBD><36><EFBFBD><EFBFBD><EFBFBD>fVD#<23>а6<><11>ك<18>n<11>)Ttv<74>H<EFBFBD><0E><>B<EFBFBD>Z<EFBFBD><18>ɱ<0F>8`$<24>-<2D>&<26> <09><> <20>-A6<41> ;<06><><EFBFBD><7F># <0A>+<2B><>l<>m<EFBFBD>@A<>A<EFBFBD>W<EFBFBD><57><EFBFBD><EFBFBD>`XGiGi?c<>@;<3B><><K*<2A><08>ȶ+<2B><><0E><>\<5C>?bC<62>:K<>VS<56>i<>\<5C>m |<7C><><1A><>
<EFBFBD><EFBFBD>N<EFBFBD><EFBFBD><01><>0<14><><EFBFBD>\px<70>vf<76>Qd<51><14>`<60><><EFBFBD>),8<><02>KPL0<07><> *<2A>閏Ҏ<E9968F>~<06><01><><EFBFBD>~<7E>X<EFBFBD>;<3B>1<EFBFBD><31><EFBFBD><01><18><18><><EFBFBD>'IEND<4E>B`<60><>PNG

IHDRIz<>{<7B>sRGB<00><><1C> pHYs  <00><>tIME<07>
 -#x+tHIDAT8<54><38>S1N<31>@ {<7B><><EFBFBD><1E><02>\Gq<1F>'\E<>H<EFBFBD><48><14>C<EFBFBD><43>&<26><>d<EFBFBD>hmώǓ]9<><39><EFBFBD>-<2D><><EFBFBD><EFBFBD>DHڲ,<2C>H<EFBFBD>2s<32><18>Bf<42><66><18><>xU<78>"<00>t<EFBFBD>?(H*<2A><>Y-<2D><><EFBFBD><EFBFBD><EFBFBD>n<EFBFBD>Ԣ<1D>M_<<3C>[k<><6B><EFBFBD><14><><EFBFBD>{<7B>:<3A>$<24>TQUw<55>|<7C><1E><>duJK<4A>P<EFBFBD>5<35><7F>̾#<23><1B>t<EFBFBD><74><EFBFBD><EFBFBD><EFBFBD><Q<>{<7B><>t<EFBFBD><74><EFBFBD>b<EFBFBD><62><EFBFBD>w<EFBFBD><77><EFBFBD><EFBFBD>؊<EFBFBD>X;Dl<44><6C>l <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>w<EFBFBD>!"6<>EDkͮ<6B><CDAE><EFBFBD><EFBFBD><EFBFBD><EFBFBD>w@@<40><><EFBFBD>}/_<>f<EFBFBD><15><>ԕ5jXf0<66>d<EFBFBD>F<EFBFBD>c<EFBFBD>7=<3D><><EFBFBD>;@3<14><>n<EFBFBD><03><>~P<1C><EFBFBD><7F>q[|<7C>|<7C><>#<23><>4M$T<>"<22>i<EFBFBD><69>dQTTL .<2E>Z<EFBFBD> <09>4IMOi<4F>d<EFBFBD><64><EFBFBD><EFBFBD>=<3D>'1p"-`8IEND<4E>B`<60><>PNG

IHDR@I<04>AsRGB<00><><1C> pHYs  <00><>tIME<07>
%;Q<>Z<12>IDATh<54><68>Z[<5B>gUy<55><79><EFBFBD>o<EFBFBD>90<39><30><EFBFBD><EFBFBD>Mf<4D><66>b.^b
b<EFBFBD><EFBFBD>̋<EFBFBD><EFBFBD><EFBFBD><14><EFBFBD>݇jb_<62>s56<35>"<22><><EFBFBD><EFBFBD><08>BjG.<1A><>ń $<24>Ј
&`<60>9<EFBFBD><39><EFBFBD><EFBFBD><EFBFBD><EFBFBD>}<7D>><3E><>b<EFBFBD>?gf<0E>><3E><><EFBFBD>?kk<7F><6B><EFBFBD>w<EFBFBD>}ko~<7E>{<7B><><EFBFBD><EFBFBD>E<EFBFBD>4<EFBFBD><34>4z<34>doXXXؼy<D8BC>[<5B><><EFBFBD>Z+<2B><><EFBFBD><EFBFBD>C%<25><>ԉ<EFBFBD>}<7D><><EFBFBD> h<><68><EFBFBD>6<EFBFBD>F&<26>{X<>v<EFBFBD><76><EFBFBD><EFBFBD>=z<><7A>ѣ\p<><70>'2<><32><EFBFBD><1A>yI<79>v<EFBFBD>r<EFBFBD>̜۶<1A><><EFBFBD><EFBFBD>i<EFBFBD><69><EFBFBD>kN<6B><4E>2<EFBFBD>~<7E><><EFBFBD><EFBFBD><EFBFBD> /<2F><><EFBFBD><EFBFBD><EFBFBD>Nj$3<>Ի<EFBFBD>zm}[<5B><>Z<EFBFBD><5A>e<EFBFBD>t<EFBFBD><74><EFBFBD><EFBFBD>›<EFBFBD>s:<3A><><EFBFBD><><D4B9><EFBFBD> <0B>5=33<33><33>r<EFBFBD><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD>+e<><65>T}<7D>Ӈ<EFBFBD> ;o<><6F><EFBFBD><EFBFBD><EFBFBD>#v<>ED翏_;<3B><><EFBFBD><EFBFBD><01><>v<EFBFBD>{<7B>:<3A><><EFBFBD>lV<6C>}D<><44><EFBFBD><EFBFBD>R{<7B> <0B><>:5<>u<EFBFBD><1D><>u<EFBFBD>u<EFBFBD><75><EFBFBD><EFBFBD>T<1B><>:$<24>lm<6C>6Ui<55>u1L<31><4C>5<EFBFBD><35>s.8<EFBFBD><EFBFBD>t<EFBFBD><EFBFBD>0<EFBFBD><1D>Kj<4B><6A>&<26>u<EFBFBD>C3<>hWoDdf<64><1A>\h<>=I[<5B><11><>89<15><>I<EFBFBD> <20>Lv<13><><EFBFBD>Ks<4B> s<>`Us<>o3v<07><>o<EFBFBD>8<EFBFBD>㹮.¾<>~<7E><05><>~݆IvZ<><5A>n<EFBFBD>S<EFBFBD>ef{f<><66><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>i<EFBFBD>m<EFBFBD><6D><EFBFBD>n<EFBFBD><6E><EFBFBD>8<EFBFBD>gfs<66><73>p4g<34>S3<53><33>N<EFBFBD><4E><06>=b<><62><EFBFBD><D1BD>C<EFBFBD><43>N=g<>h:<3A>Ѭt3<74>ziO<69>As<41>7Bl<42>^w<><><7F>)3_}<7D>կ<D5AF><7F>G<EFBFBD><1D><>K<EFBFBD><4B>ɓ<EFBFBD><C993><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>|<7C><>纨֊<E7BAA8>;<3B>Z<EFBFBD><5A><EFBFBD>8'ڵ]Ә<>X"<22><><EFBFBD><0F><><EFBFBD><EFBFBD>B<EFBFBD><42><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)<i<>4<EFBFBD>D<EFBFBD><44>O?m]<5D><>¦iu<69><75>qb<71><62><EFBFBD>]<5D><>f<EFBFBD>]'Qk<51><6B>k<EFBFBD><6B><EFBFBD> [<5B><><EFBFBD> <0C>s<EFBFBD>mY<6D><1E><><16><><EFBFBD><EFBFBD>N<EFBFBD><4E><EFBFBD>\<5C>|饗<><E9A597><EFBFBD><EFBFBD>K/<2F>t<EFBFBD><74><EFBFBD>fZ<66>m&<26>`<60>8<EFBFBD><38><EFBFBD>L<EFBFBD><4C>\<14><0E><><11>v27<32>TE<54><45><EFBFBD><EFBFBD><EFBFBD>ޝ;w<><77>8<EFBFBD>S[o^<5E>3O<33>^#<23>v4^<5E><><EFBFBD><EFBFBD>z(<28><><EFBFBD>K\<5C>k(<28><><EFBFBD><EFBFBD>><3E><>2<EFBFBD><32>l6{<7B><><EFBFBD>]k<><6B>f<EFBFBD><66>f`s9<73><39>Qk<51>t<08>5<EFBFBD><35><EFBFBD><EFBFBD>'N<><4E>ڮV<DAAE>4l<34>L<><4C>k<EFBFBD>=v<>XD<58>ٳg<18>={<7B><>{<7B>OJu<4A>?<3F><>'<27>|<12><>7<EFBFBD><37> <0B><>><3E>w<EFBFBD>=#<23><07><>]f<><66><EFBFBD>|<7C><>[nY\\\ZZ<5A><5A><EFBFBD><EFBFBD>><3E>{<7B><>ݻwo޼<6F><DEBC><EFBFBD>q<1C>}<18>fN}<7D><>(<28>t@u<><75>A눪S;<3B><>;<3B>o<EFBFBD><6F>E<EFBFBD><45><EFBFBD><6D>u<EFBFBD>]/<2F><>w޹}<7D><>w<EFBFBD><77><EFBFBD>O<<3C><><EFBFBD><EFBFBD><EFBFBD>K/<2F>t<EFBFBD><74><EFBFBD><EFBFBD>v<EFBFBD><76>t<07><><EFBFBD><EFBFBD><EFBFBD>:OM<4F><4D>v"<22><>);=<3D>5<15>骵n޼y<DEBC>֭<1C><><EFBFBD>K6o<36><<3C><>.<2E><><EFBFBD>)<29><><EFBFBD><EFBFBD>Yδ&<26><>z<15><>y<EFBFBD><02>wC<><43>n<EFBFBD>g$N<><4E>\W<><57>s<EFBFBD>9g׮]<5D><>q<EFBFBD><71><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȴ<EFBFBD><C8B4><35><DCBD>iqӡ{<7B>1W<31>L<EFBFBD>㔾A<E394BE><1C><>vM<76>1<EFBFBD>q<1C><><EFBFBD><EFBFBD>֘<EFBFBD><D698><EFBFBD>)Lr<4C>F_ <0A><>L[@<40><><EFBFBD>Z<EFBFBD><5A>"<22>j<EFBFBD><6A><EFBFBD>;<3B><><EFBFBD><EFBFBD>;^}<7D>Վ<EFBFBD><D58E><1B>ZNO<4E><1D>f<EFBFBD><66>f<EFBFBD><66><EFBFBD><EFBFBD>P<EFBFBD><50>#<23><>7Hl <0C><><EFBFBD>رc<D8B1>^ZZ:r<><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>7<EFBFBD><37><EFBFBD><63><C78E><30>86~Z<><5A><EFBFBD>&3y<33><79><EFBFBD>n<EFBFBD><1D>N<EFBFBD><4E><EFBFBD>7N<37>֜s]ozӛ<7A>u<EFBFBD><75><EFBFBD><EFBFBD><EFBFBD>,--<2D><>؁S<D881><53>F8<46><38>6<EFBFBD>c<EFBFBD>=Vf<56>Y ;M<><4D><EFBFBD><EFBFBD>q-}<1C> {~]w<>_<EFBFBD><5F><EFBFBD>sвW<0E><>i<EFBFBD>m<EFBFBD>]<5D><><EFBFBD>Ki!<21><><EFBFBD>vkfMZ<4D><15><>d<EFBFBD>0 $NE<4E><45><EFBFBD><07><>P<>dz<64><7A><1E><><EFBFBD><EFBFBD><EFBFBD><><DFA6><EFBFBD>k<02>=5<>;<3B>:#<23>4<EFBFBD>t<EFBFBD>v<EFBFBD><76><EFBFBD><EFBFBD>c<EFBFBD><63>L<EFBFBD><4C>ӳ<EFBFBD>.<2E><>n<EFBFBD>q<EFBFBD>>3<><33>4<EFBFBD>M<EFBFBD>'v^۵<><DBB5><EFBFBD><00>t<EFBFBD><74><EFBFBD><0E><>d<EFBFBD><64><EFBFBD><EFBFBD>d!~DŽ<00>$:<3A>;<3B><> ȍ{=9<><39><EFBFBD>a<EFBFBD>!r<>1ԴZ<D4B4><5A><EFBFBD>ˀ<EFBFBD><CB80>e6<65><36><EFBFBD><EFBFBD>d<EFBFBD>m#<23>#v<><14><><EFBFBD><EFBFBD><13><><EFBFBD>{<7B><>b@G
<EFBFBD><EFBFBD><EFBFBD>E<EFBFBD>\iѵ<69><D1B5><EFBFBD>=<3D><><EFBFBD>VS<56><1C><><12><EFBFBD><ED9AA6>Y[<5B>i<EFBFBD>_YYi<59><69><EFBFBD><EFBFBD>Z<1B><><EFBFBD>;<3B><>)FmD<>F<EFBFBD>¦<EFBFBD><C2A6><13>H{<7B><><EFBFBD><EFBFBD>ڶZ<DAB6> n<><6E><EFBFBD><EFBFBD><14>4;lU<6C><55><EFBFBD><EFBFBD>u_)<29>t<EFBFBD>1<EFBFBD>nKf<4B><66>j<07><><03><>R{<7B>[ <0B> <0A>t<EFBFBD><74>qQ<71><51><14>t+<2B>&<26><>K<EFBFBD><4B>v<EFBFBD><76>Q<EFBFBD><51>җ<EFBFBD><D297>t<EFBFBD><74><0F>zY<7A><59><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̜<1E><>g<EFBFBD><EFBFBD><E0BBB0><EFBFBD><EFBFBD><EFBFBD>n<EFBFBD>K<>ҢX<0F><><EFBFBD><<3C><>S<EFBFBD><53><EFBFBD>$<24><><EFBFBD><EFBFBD>HA@h<>/{<7B>o<EFBFBD><08>-<0E><>4Y2)<29><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>PJ <20><><EFBFBD>:@"AD@<40>T<EFBFBD>.<08>Nζ|k b[*A
4j;<17>ſ<EFBFBD>b9<62>|<<01> S0<> <20><15><>"<22><>h<EFBFBD><68>F <0B>U
B)<29><><05><><EFBFBD><EFBFBD><EFBFBD><08>
<09><>2<EFBFBD><32><EFBFBD><1C>r3(K<05><19>Z2N<>óBB<01><<3C>$<24>`A8<41>J9$<24>$<04><>*j<><6A><EFBFBD>(C<>j<EFBFBD>Ȁ<EFBFBD>H<EFBFBD>[<04>,!"M<><4D><EFBFBD><06><19>U<EFBFBD><55><EFBFBD><EFBFBD>j$@<40>,3k<16>@XZ(Y I<>I!RNB<>#)<29><10>C<><43><EFBFBD>4(Ӕ<>*5搞<35><E6909E>ʰ<EFBFBD> נ<12>94<14>h<EFBFBD>t*U%<25>d<EFBFBD><64><EFBFBD><EFBFBD>AKK<4B>,@0lJ<6C><4A><1A>5<EFBFBD>Ɣy<05><><11><><EFBFBD><EFBFBD>GG <09>{IT<49><54>!AK&C<>1D%:<3A><>(D<06>C<EFBFBD>Qi,<15>d+'<27><>w<EFBFBD><77>,<00><>dIQ<49>p2e0)a.&a<> <09><>D<><>r<EFBFBD><72> /<2F>|<7C>[<5B>p<0F>RQ<52><51><EFBFBD><EFBFBD>UV/E3<>)2'<27><><EFBFBD>DQDBt#d<>n<12>͒GU<47>WK%<25><><EFBFBD><7F><EFBFBD><EFBFBD>h<EFBFBD><68>G<EFBFBD>}<7D>g<EFBFBD><67><EFBFBD>s?<><7F><EFBFBD>X&dRuYJ<59>pB`<60>\<5C>X<01>@:=k
*<2A>*g<><67> <0C><05><><EFBFBD>4cf<63><66>ҥj2<6A>q<00>7<EFBFBD><37><EFBFBD><EFBFBD><7F>6<EFBFBD><36>P<EFBFBD>g<EFBFBD>y<EFBFBD><79>ͳ<EFBFBD>F<EFBFBD><46> <20><>Pj<50>#<23>Y4<><02><>Q<EFBFBD>@<40>AH<13>E<EFBFBD>*<2A>:<3A><>@<40><>I<18>̀["T<><54>d<64><7F>< <0C><><EFBFBD>b6QT0XA<58><41>eR<65>3e<33> <20>
Vs<EFBFBD>r<EFBFBD>I4<04>d<>4<07>Fy<>R
Ɋg<01><>XD<58><44><EFBFBD><EFBFBD>C<EFBFBD><03>wl<><6C><EFBFBD><EFBFBD><EFBFBD> <20><19><><EFBFBD>$<03>a<EFBFBD>u$JZ<4A>R
13+"<22><>Q<>TVF<56><46>j<>I<EFBFBD>*<2A>J<EFBFBD>$<24><>d<EFBFBD><64><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;w<><77><EFBFBD>ֿ*<2A>t<EFBFBD>P<EFBFBD>`T<>s<00><><EFBFBD>+<2B>c <09>%HS& Q5<51><35> f<03><08><><D393><19>e<EFBFBD> 2+U2<55><32>VC0K<30><05><>5<EFBFBD><35><EFBFBD><EFBFBD>?<3F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>'<27>;<3B><><EFBFBD>O<EFBFBD><4F><EFBFBD>#<23><><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD><63>A7<41>1<EFBFBD><04>(c!|<7C><02>.+$<24>X)<29><><EFBFBD><EFBFBD>iS<69>&BDq ,&H<>d<EFBFBD>H<08>2<EFBFBD><32><EFBFBD>;<3B>u<EFBFBD>С<EFBFBD>.<2E><> ox<6F><78><EFBFBD>_<EFBFBD><5F>S?<3F>ꪫN<EAAAAB>/<2F><><EFBFBD><EFBFBD><19>2d%<25><>.<2E><><1F>v<EFBFBD><76><EFBFBD>9p@)a<>OoJ)<1F><><EFBFBD>}<7D>PQ<50><51>&<26><00><><EFBFBD>g<EFBFBD>=t<><74>W<00><><EFBFBD>+z<><7A>Z멬<5A>$H<>%t<>U<EFBFBD><11><><EFBFBD><08><>Ly<4C>}<7D><>s<EFBFBD>9o<><1B><>{<7B><><EFBFBD><EFBFBD><EFBFBD>`<60><>c<EFBFBD>y<EFBFBD><79>p<EFBFBD>2 G2<47><32><EFBFBD><EFBFBD>#G^|<7C><><>F۷<><DBB7><EFBFBD>͛<EFBFBD>}<7D><>]<5D>v<EFBFBD><76>o<02><0E><><06>LJdA <0A>pÍ7><3E><>#<23><><EFBFBD><EFBFBD><EFBFBD>޽<EFBFBD>G<EFBFBD>Ĕd<C494>5<EFBFBD>X
I<><49>q<EFBFBD><07><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>p<>e<EFBFBD><65>m<EFBFBD><6D><EFBFBD><EFBFBD>y<EFBFBD><79>{<7B><><EFBFBD>?<3F><><EFBFBD>MH<11>s<EFBFBD>Ώ}<7D><><EFBFBD>ޢ& Z<> <0A><>e<><65> 0<><30><1F><>G><3E><><EFBFBD>)*M<><05><>P<EFBFBD><50><04><>ʸ<EFBFBD>3<>G!S5(<18>n<EFBFBD><1A><>o<EFBFBD><6F><EFBFBD><EFBFBD><1F><>g<EFBFBD>f<EFBFBD><66>yz]}<7D><>W_}<7D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>?<>%<25><>6<EFBFBD><36>̄JR43<34>(<28>"-0<>e<EFBFBD>GO<47>KwJ<>XL5<4C>Nd=D<><44><EFBFBD><EFBFBD><EFBFBD>ja<>2<EFBFBD><32>kp7@O><3E><>;<3B><><EFBFBD><EFBFBD><04><><EFBFBD><EFBFBD>gѹ%<25><00>Y<11>{-*<2A>c<EFBFBD>Г<EFBFBD>4<EFBFBD>4H<34><48><EFBFBD>/<2F>}<7D><><EFBFBD>w0sN|<7C>M7<37><7F><EFBFBD>j;Ӏ<><10><><1C>5 <0C><>g<EFBFBD><67><EFBFBD>Ͽ<EFBFBD><CFBF>[<5B><><EFBFBD><EFBFBD>g<EFBFBD>y<EFBFBD><79><EFBFBD><EFBFBD><EFBFBD>}<7D>٧?><3E>݇<1E><>u<EFBFBD>]<5D>cǎI<C78E>gt<67>^<11>J!a<><61>&2<><32><0F>f'~<7E><><07><>о<EFBFBD>p2PK0Y"k1c<31><10>pص벝;<3B><><EFBFBD>{<7B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>o<><6F><EFBFBD><EFBFBD><EFBFBD>ξ<EFBFBD><CEBE><EFBFBD><EFBFBD>o<EFBFBD>q<EFBFBD><71><EFBFBD><EFBFBD>><3E><><EFBFBD>۷<EFBFBD>Np(<28><08>ZFUX
b
^f<>F<EFBFBD><46><EFBFBD><1B><><EFBFBD>G;U b<><62><EFBFBD>z<EFBFBD><7A><EFBFBD>j<EFBFBD>fY<><59> <07><>N<><11><><EFBFBD>?~<7E><><EFBFBD><EFBFBD>|<7C>3k<33><6B><EFBFBD>/}颋.ڻw<77>8q<38><71>?~<7E>ʫ޺<CAAB><DEBA><EFBFBD>)<29>,<04>`Y<><59><EFBFBD><EFBFBD>A𬅳<41>M$<24>F<EFBFBD><46>d2<64> 0<>g<><67><EFBFBD><EFBFBD><EFBFBD>a<EFBFBD>V<EFBFBD><56>ir<69>L<EFBFBD>_<><5F>?<3F>2<EFBFBD><32>رcn<ǎߵk<DFB5>ZG'i,<2C><><EFBFBD><EFBFBD><EFBFBD>4<EFBFBD><34>D;iS8<>Ɠ<EFBFBD>R<EFBFBD>A<><41>V<EFBFBD>z*an<61><6E><EFBFBD><EFBFBD> <0C><><EFBFBD><01>d6$<24>d&<26>Y<EFBFBD><59><EFBFBD><1E><>ʫ<EFBFBD>>h'%W_<57><5F>?<3F><>×^z麉<7A><02>f4<66>V<EFBFBD>#<23><><EFBFBD> e<>H|<7C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;J<><17>t<EFBFBD>M<EFBFBD><4D><EFBFBD><EFBFBD>Q[,27OUTB<><42>4<EFBFBD> e<>O<<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1F><>_<><5F><EFBFBD><EFBFBD>߿<EFBFBD><DFBF><EFBFBD><EFBFBD>-<2D><><EFBFBD>Ͽ<><CFBF><EFBFBD><EFBFBD>`<60><><EFBFBD>9<EFBFBD>h<EFBFBD>3<>a+G<><47>K<4B><7F><EFBFBD><EFBFBD>=<3D>ܭ<EFBFBD>ڲ<EFBFBD><DAB2><EFBFBD>:<3A><>:<3A><><EFBFBD>~<7E><>2<EFBFBD>ːn!
<09> <0A>b<EFBFBD>i
<EFBFBD><EFBFBD> :thaa<61><61> /<q<><71><EFBFBD><EFBFBD><EFBFBD><EFBFBD><7F><EFBFBD><7A><D7BB><EFBFBD>+<2B><><EFBFBD><EFBFBD><EFBFBD><7F><EFBFBD>}<7D>y<EFBFBD><79><EFBFBD><EFBFBD>o{<7B><>G<EFBFBD>>%Ii<49>T<EFBFBD>#d(h<15><> T<><54>n<><6E><EFBFBD>?ٲe˖<65><CB96>ŭ[<5B>,nٲ<6E>uq˖Fٲ<46><D9B2><EFBFBD>m<EFBFBD><6D><EFBFBD><EFBFBD>>32<33>k;>˪<18>#<23>=pJ<13>կ^عs<D8B9><73>/<2F><><EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD>o<EFBFBD><6F><EFBFBD>?}<7D><>[w<><77><EFBFBD>x<><78><EFBFBD>nۻw<DBBB><77><EFBFBD><EFBFBD>g<EFBFBD><67><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> Ґ@<40>XR鄒<14><>bʛn<CA9B><6E><EFBFBD>[o]=HԲ<><12> <20>O<EFBFBD>X^)<29><>ˆe<02><>VSN<>o{<7B>[<5B><><EFBFBD><EFBFBD><7F>s<EFBFBD>^<5E><>ݻw7W޴i<DEB4>><3E><><EFBFBD>.<2E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>={<7B><><EFBFBD><EFBFBD>a< <0B>I<06>U,<2C><>L<1A>+<2B><><07><>(<28><>h<04>@Q<>!<21>J<>J<13>@V<>fa<66><61><EFBFBD>NF<46><7F><EFBFBD><EFBFBD>?<3F><>-W,<2C><<01>2K<02> <20><><EFBFBD><1D><>DX<44>da<><61>'
<0A>J
<EFBFBD>LVC<EFBFBD><EFBFBD>*`ZQT<51><1B><><EFBFBD><EFBFBD>y<EFBFBD>y<EFBFBD>W<EFBFBD><57><EFBFBD>,)3<><33>@<40>Q<EFBFBD>8c<38><63><EFBFBD>8<EFBFBD>!E<06>*e%<25>9 ILe <18>9<EFBFBD>ZQME!QE֠%<25><>j<15>5SU<53><55><EFBFBD>?g=<3D><>j<EFBFBD>&<26>/sT<05> k0<6B>U<EFBFBD><55><04>*Ѐ4<1A><><EFBFBD><EFBFBD>A<EFBFBD><41><EFBFBD>*b<>1<EFBFBD>D<EFBFBD>`n<><6E> <20>7<EFBFBD>)<29><>t<EFBFBD>u]<11><>ѥ<EFBFBD><D1A5><EFBFBD><EFBFBD><EFBFBD>n9/<14>(<28><>}<7D><>ՂPL<50><4C><EFBFBD>e<05>㘃1<E39883><31><EFBFBD>[m#<23>$0Z<30>$DgIE<49><11><>iAG<><01><>yYEk<45><14><>u<>s$<24><>Ɣ<EFBFBD><C694>I5<49>\<5C>Ȥ<06><><EFBFBD><<3C><10>[<5B><6C><DBB6><EFBFBD><EFBFBD>ѡȡ($gɌ082D<32><44><EFBFBD><EFBFBD>nH:)C<><43>cE<63><45>L<EFBFBD>!5F<35><46>J0ksg
<EFBFBD> !LYGk<47>,W^~<7E>ڡ<EFBFBD><DAA1>D;<3B>f<EFBFBD>ܐ`l(rռW<D5BC>$"<22>-<2D><>$H <20>zb<7A>bT
<EFBFBD> <09><><EFBFBD>j^b<>b<EFBFBD>f-鄬B[ p<>vh赂ŇP0<50><30>$<24>1Eè
<EFBFBD><EFBFBD><EFBFBD>|U<01><>G<EFBFBD>0@"%'<27>`<60>`E<>LJY<4A>i0V<30><03> <20><>h<EFBFBD>2<EFBFBD>S<08><><EFBFBD>c<00><>"((<28><>2 HB0<42><30><EFBFBD><EFBFBD>ckd4<64>)<29><>!A&i<><69><EFBFBD>c E<> <09>- f<> +<2B>5(<28><>D<><44>\<10>!1<>bh<62><68>T<08>)S<><53><EFBFBD><68><1C>Z <09>*<2A>=<3D>`Bf%<18>(<28><>$<24>=Q-<L<><4C>f@<40>PQ{<7B><><EFBFBD>hu<06>ef<65><66><02><>:<3A><>e<EFBFBD><65>&1<><12>U<EFBFBD><><D394>𨉴<11><>"<22>HCV<43><56>H<EFBFBD>ܢ<EFBFBD>ƚ<06><>̲&R5<52><35>2& <0A> <0C><00> <0C><19> &FWz<57>Z<EFBFBD>2A<32>,<04>`<60>4<EFBFBD><16>շ(<28><><EFBFBD><EFBFBD><EFBFBD><78><DF91>_<EFBFBD>j}<7D><><EFBFBD><EFBFBD>IEND<4E>B`<60><>PNG

IHDR<00>H RIDAT<18>c<EFBFBD><63>@ DfF1<46><31><EFBFBD>(<28><><13><>!<21><><EFBFBD><13>*<2A><><EFBFBD>`!<21>O<08><><EFBFBD><15>[
W<51>mP<6D>|_ <20><>()|<7C>Q<>WP<>΂Cj<><6A><EFBFBD>
<EFBFBD>8VIEND<4E>B`<60><>PNG

IHDR'<>AIDATx^<5E>̱ <09>00<>~<7E>'<27><> ><3E><04>zy<7A><79>d'<27>!<21><>. <0C><>: E<>C<><43>0<EFBFBD><30> C<><43>0<EFBFBD><30><EFBFBD>Pw<50><77><EFBFBD><EFBFBD>C-<2D>|<7C><><EFBFBD>IEND<4E>B`<60><>PNG

IHDR<00>NC/IDAT<08>c<EFBFBD><63><EFBFBD><EFBFBD>΀<06>b<EFBFBD> b<10># &<03>,<18> <0C><><EFBFBD><EFBFBD> <0A><>ѵq<04>^<5E>%<25><>W<EFBFBD>IEND<4E>B`<60><>PNG

IHDR <00><><1E>uIDATx<54>c<EFBFBD><63><EFBFBD> <20>@<00>w<>X<EFBFBD><08>J@|<1D><><0F><><EFBFBD><EFBFBD><11>b+ ~<05><>@6 ^Ŀ<>8<03><> <20><06>k<EFBFBD><6B>Y"<1F><><02>D f<>.<2E>iZ$<07>@<<0F>q!<21>Y<03>k ~<0F><><EFBFBD><06>2kb<6B> b<q
<EFBFBD><EFBFBD>IEND<4E>B`<60><svg xmlns="http://www.w3.org/2000/svg" width="18px" height="18px" viewBox="0 0 48 48" fill="#000000">
<path d="M0 0h48v48H0z" fill="none"/>
<path d="M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm2 30h-4V22h4v12zm0-16h-4v-4h4v4z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="18px" height="18px" viewBox="0 0 18 18" fill="#000000">
<path d="M0 0h18v18H0z" fill="none"/>
<path d="M.5 16h17L9 1 .5 16zm9.5-2H8v-2h2v2zm0-3H8V7h2v4z"/>
</svg>
<EFBFBD>PNG

IHDR<00><00><00><04>!sIDATx<54><78><EFBFBD>pG<><47>[<5B><>L1[<5B><>1r^X<> <0B>q<EFBFBD><71>CS<43><53><EFBFBD>C<EFBFBD><1C><>pq81<38>sd<0E><>AC<41>̖dI<64><49>~_^}<7D><><EFBFBD>Z<EFBFBD>G<EFBFBD>ݓ<EFBFBD><DD93><EFBFBD>W<EFBFBD><57><EFBFBD><EFBFBD><EFBFBD><EFBFBD>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD><EFBFBD>i<EFBFBD><69><08> <08> <08> <08> <20>u V)<29><><EFBFBD><EFBFBD>P<EFBFBD><50>AM<41>U:<3A>1t<31><74>JX<4A><58>r|<10><06><>%<25><1B>,lNa<00><>6<EFBFBD><36>A<0F><><EFBFBD><EFBFBD>|<7C><04><>8 ^<0F>9<EFBFBD><39><EFBFBD><0F><><EFBFBD>Y&<26><>m<EFBFBD><6D>F<EFBFBD><46><EFBFBD>tX<74><58>r<10><0F><04>t<EFBFBD><74><EFBFBD><EFBFBD><EFBFBD>4<EFBFBD><34>B<EFBFBD><42>w<1B>u)<29>ׄ<><D784><1E><><EFBFBD><EFBFBD> <0C>
<EFBFBD><EFBFBD>ڔe7<EFBFBD><1E><>&<26><>pK<70><1F><>XG<><1A>a+8kng<03>O<EFBFBD>W!<21><>2<EFBFBD>mlp0<70><30>J8<4A>6Bx2<78>p%<25>Pv <0A>
<EFBFBD>Ŗ<EFBFBD>QX<EFBFBD><EFBFBD><EFBFBD><EFBFBD>7.<2E>p<EFBFBD><70>.<2E><><EFBFBD><EFBFBD>F<EFBFBD>
xR<EFBFBD>H<>d<EFBFBD><11><> Q<><51><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>=:<3A><>fY<><59>Y<EFBFBD> <20><19><><D486><EFBFBD>UÍ<><C38D><EFBFBD>%<25>5 <0C> <0C> <09><><16><15><>]<5D>{`i`h8<68>t#<23>U<EFBFBD>H<><48><EFBFBD>y<EFBFBD><79>Nh<4E><11><><EFBFBD><EFBFBD>lb<6C>v<EFBFBD>Rk<52> T9<54>gy<03>*x̆<><CC86><EFBFBD><EFBFBD>n<EFBFBD><6E><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>p<EFBFBD><70><EFBFBD><15>|<7C><>:M<><4D><EFBFBD><EFBFBD> <20>=<3D>}<7D><>3X><3E>ݔg<DD94>by<62><79><EFBFBD><EFBFBD><EFBFBD><EFBFBD>n<EFBFBD><6E>uˇB<CB87>i<00><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/V9`H֨<48><D6A8> Ԇ<D486>]`<60>Q<EFBFBD>;<3B><><03>><3E>ZFHW<48><57><EFBFBD>5;<3B>\; <0C> ?@<00><>~><3E><1A>Z<EFBFBD>%<1A><><01><>}<7D>"<><7F><EFBFBD>fK<66>Z<EFBFBD>Bmx)<29><1E><><EFBFBD><EFBFBD><EFBFBD><05><>H4z 8<>-<2D>S!-<2D><>]<5D> <07><>~D·<><C2B7><EFBFBD><EFBFBD><EFBFBD>0<EFBFBD><30><EFBFBD><EFBFBD><1D>1|<7C><><EFBFBD>e<0F>lR`<60>e&|<7C>w@<40>-\<03>p<>50<35><30>> <0F>h\~u<04><>#<23><>T<<3C>
\<5C><>s<EFBFBD><73>R<><52>Kmx<6D><78><EFBFBD>gJ<67><4A><<03><>cp4<><34><10><><12>E<>c<><63><EFBFBD><EFBFBD><11><EFBFBD><7F>y<EFBFBD><09><><EFBFBD><EFBFBD><04>#<23><><EFBFBD>8d<38>*U<>27<32><37><EFBFBD><>x<><78><EFBFBD>2<32><7F><EFBFBD>bVh<56><68>-<2D><><EFBFBD><EFBFBD>.<2E><13><><EFBFBD><EFBFBD><EEA094>O+7<00><18>f<EFBFBD> <0C>7m<><6D>ti<74>)pA<70>{<7B><><EFBFBD>9@<0E><>Պx<14><>P<EFBFBD>p<EFBFBD><70><EFBFBD>ɥh<C9A5>+<2B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;<3B><>t<EFBFBD>ɕ)<29><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>r<EFBFBD>%Z><3E>~<7E><>E<1B>C<02><>J<EFBFBD>]9<><39>^<5E>v;u<><75>7<EFBFBD><00><>/@<00><>><3E>o<EFBFBD>wA<11><1B>kA<> B<><42>F<1C>AAAAA<10><><EFBFBD><EFBFBD>QJ<10><><EFBFBD><0E><>:x<>!qz<71><7A>ZBA(<28><>`|Ά<><CE86><EFBFBD>T<EFBFBD><11>d<EFBFBD><64>RBǤ<>G}<7D><1D>/\/<2F>=<3D>\<1E>|
OW)<29>e<EFBFBD><65><EFBFBD>` |<17><>r<Z<>
`<60>r<18><><EFBFBD><EFBFBD>U<EFBFBD><55>7<19> v<>3<EFBFBD><15>,<2C>[<5B>5<<3C>A<EFBFBD><41>U_h<>ok<6F><6B><EFBFBD><EFBFBD>!<<3C><> `T| <0C><0E><>Q<EFBFBD><51><EFBFBD><EFBFBD>a<08><>+<15>wi<11>V<02>2<EFBFBD><32><EFBFBD>9<EFBFBD><39>3)cy<1D>K*|<7C>p-<2D><><EFBFBD>f<>`<60> <0C>%<15>,<2C>7i<><10><>Qv)&]Жy6<><36>au<0E><><EFBFBD>g<EFBFBD>{N<> <0C>OR<4F><02><><EFBFBD><03><>'<27><>r<EFBFBD>!lr:k<1A><><EFBFBD>
<EFBFBD>wu(<28><p<>kh<6B><oe <0B>C<EFBFBD><43>v@<40><>T<EFBFBD>R<18>,<2C>4&<26><>.<2E>d(<28>
ۇ<EFBFBD>p<EFBFBD>1<1F><><12>p<EFBFBD> a<1D>u \
;<3B><>\ <0C>k<EFBFBD><6B><EFBFBD>O<>*<2A><01>j<>e<00>0UF <0C>P<05>B#| ] ˯<>cj<63>O<EFBFBD>i<EFBFBD>\<5C><><EFBFBD><EFBFBD>SZ<53><5A><EFBFBD>@<40><10>cw<63><<3C>n<08>><3E>;<3B>t<EFBFBD><74>O_<4F>)<29>pB0|@9<06><>C<14><><EFBFBD><EFBFBD>B8N<>Y `t<0E>O<EFBFBD>C`<60><><18><>*?z<>+<2B><>c><3E><03><>((<28><>vpQ<70>J<EFBFBD>+<19><0E>w<EFBFBD><77>k']<5D><02>!<21><> <0C><><EFBFBD><EFBFBD><EFBFBD>=<3D> g<>+Z;<3B>$<24> <0C><>Opr<70><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD><12>ƿ<00>3x<<3C><1C> {<7B><><EFBFBD><12><>M<EFBFBD>Ox<><1D><02><16><><18>zQ<7A>ϖ<EFBFBD>:<3A><><EFBFBD><EFBFBD>2<EFBFBD> <16>B@(<08>PAAAAAAA<10><><EFBFBD>Sݻw<DDBB>F<EFBFBD>Cl<43>ի<EFBFBD>0<EFBFBD><30>"oAM߆<4D><DF86><EFBFBD><EFBFBD><EFBFBD>][<5B><><EFBFBD><EFBFBD>Am<41>ȼ<EFBFBD><C8BC>L憢<4C><E686A2>F<EFBFBD>#<23>H)<29>O١(p#<23>:<3A>IC5BV<42><56>V<EFBFBD>
<EFBFBD>iUhH<00><>5B<><42>Gy<47>^\<><13>h<EFBFBD><03>O<><4F><EFBFBD>{7<><00>ς{9<><39>+<13><>
/ .'<14>0| <0C>n<EFBFBD>y<EFBFBD>al<>:<3A><><EFBFBD><EFBFBD><EFBFBD><07><><EFBFBD>@<00><><_.<2E> .<2E>(<28><>a<EFBFBD>}(G<><07>u<><1A>8<EFBFBD> <09><>k<EFBFBD>PMv<4D>w<EFBFBD><05><>]<5D><><EFBFBD>=p<> t@<40><>*<2A>!<21>><3E><1A>wNQ<07>F<EFBFBD><46>j<EFBFBD><6A>"|<7C>j<>Q10<31>s<EFBFBD><73><EFBFBD>6A<36>K<EFBFBD>ۤ9<DBA4><39><EFBFBD>}<08> <20>7<EFBFBD>H^<07> <0C><>WM<>X<EFBFBD><58>%|l` x<00><00><>}<7D><>p<03><>ѺJ/ <05><>~ `<60><>[<03>T-<2D>\n<><6E>R<19>J<EFBFBD><4A>z<EFBFBD><02><><EFBFBD><EFBFBD>W<EFBFBD><57>mvAM<41> <09>F<EFBFBD>w<>qp
N<EFBFBD>W<EFBFBD><EFBFBD>w<EFBFBD>aC<EFBFBD><04>Ra6<61>c<EFBFBD>w<EFBFBD>X <0B><>Z<EFBFBD><5A>0:FG<>O<EFBFBD>/a|<10>aQ<61><51><EFBFBD>~<7E><><EFBFBD>a9<61>rBFA<46>4<EFBFBD><34><EFBFBD><EFBFBD>9?<3F><><EFBFBD>M<EFBFBD>Љ<EFBFBD><13><13><>sV<73>𝩄<EFBFBD>*<2A><><14><>V^ <0A><>R<EFBFBD><52>\<5C><16><>6B<><42>S ^<06><>ʛ<EFBFBD>}1<> <08> <08> <08> <08> <08> <08> <08><><07>N <09><>8<EFBFBD><38>{<7B> <0B><><EFBFBD><EFBFBD>P
<EFBFBD><EFBFBD><EFBFBD>FFn<>.<2E><>6<EFBFBD><36><EFBFBD><EFBFBD><EFBFBD>=<3D>s8<73>Au <0C><>P8<50>-B#<23><1C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>j8!<21><><EFBFBD>e*Y<0E>M<EFBFBD><4D>>^<5E>Mt<4D><74><EFBFBD><EFBFBD>ϋY<CF8B>e<><65><EFBFBD>3I*<2A>Y<EFBFBD>ziÆ<69><C386><EFBFBD><EFBFBD>..<2E><>f8*<2A>\<5C><1D>"<22><><1D>@/<2F>@3|<7C><>,<2C>V<>:#<23>q<EFBFBD>[<1B><>î9,r<>y<><79><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <0C>L.<2E><><EFBFBD><EFBFBD>hF<>؇<>G: `>K<><10>à6\<08><>&<15><><EFBFBD><0F><10>߆<EFBFBD><DF86><<1B>8<EFBFBD><38><EFBFBD><EFBFBD>^FK<46><00><14><>yX<79>Sc<>TK<54>$<24>F<EFBFBD>]<5D><><00><>^ <17><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>X<08>3<EFBFBD>_<EFBFBD><5F><EFBFBD>s}|A<><41>]<5D>g\<5C><0E>mN<6D>c<EFBFBD>X<EFBFBD>.<2E><><EFBFBD>M <07><><EFBFBD>4<>]<5D><><16>=<3D>_@<40>n<EFBFBD>V!!܋<><DC8B>[<08><><EFBFBD>م<><D985><EFBFBD>r<00><>U<1B><>9<EFBFBD>#<23>u ޭ<> <01><>c<EFBFBD><63> 0_<><5F><EFBFBD>5Xl<58><6C>e<EFBFBD><14>[p
<EFBFBD><EFBFBD>B#lP$$<24>[<5B><><EFBFBD><EFBFBD>6<>
<EFBFBD>_<EFBFBD><EFBFBD><EFBFBD><01><><> <0A><>c$mH<6D> : <0B>.<1D><> <0B>~<00><>Xl<01><>D+<2B><><EFBFBD>g <09><>7<EFBFBD>q<EFBFBD>Qa<51>m<EFBFBD> Z<>m<00>#iC<69> <07>4<EFBFBD>}<14><1C><><EFBFBD><EFBFBD>d<EFBFBD>U<EFBFBD>N<><4E><EFBFBD>U<N<><02>5<35><7F>0<EFBFBD>+<2B><>'!<21>{f<>u<75><12> <<15> uZH<><48>(<28><><EFBFBD>c<><63><EFBFBD><EFBFBD><10>fn<13>Npr<70><^h<><68><EFBFBD><EFBFBD>N._<><5F>4DR<44>H<EFBFBD><48>,3x<33>)<29>fuƽƴ<C6BD><C6B4>p/<2F><> 8180a<01>4<><34><EFBFBD>B <0C>eZB<0F><>t<EFBFBD><74><EFBFBD><EFBFBD>ɓ<EFBFBD>0<EFBFBD>z7<7A><37><EFBFBD><EFBFBD>p|;<3B><02>v<>4<EFBFBD><34><EFBFBD><7F>Ӓ<EFBFBD>?R<><52> H<><48>E<EFBFBD>`8<>-<2D>||V(<28><><EFBFBD>@Au<41>a<16>ك<EFBFBD><D983><EFBFBD><00><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>M8VZ<56>͛[<5B> <0B><>E<EFBFBD><16><><EFBFBD> '@AAAAAAA!><3E><>3<EFBFBD><33>"<22><><12>0~<0E>T<EFBFBD>0~<01>V<EFBFBD>S<04>Q<O5o<35>e<EFBFBD><1A><>I*o<>s<EFBFBD><73>W<EFBFBD><1C><>w<EFBFBD>d>l<>o<EFBFBD><6F>! Lzu<7A>J/<2F><><EFBFBD><EFBFBD>j<EFBFBD>\<5C>ְ$<05><><EFBFBD>@6B<36><42>n<1D><><EFBFBD>3e<33>6p!l<><6C><EFBFBD><EFBFBD>Y<EFBFBD>_AT<41>#<23>s<EFBFBD><73><EFBFBD><19><>~<>\ k<>[<5B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>?\<5C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ep#<23><><EFBFBD><0F>><3E><>:<3A><>l<1D><><EFBFBD>-<2D><><EFBFBD>;<3B>+<2B>3{ 7<>﯃]S<18><>|/×<>p)<29>_<EFBFBD>*<2A><>OI><3E>%Zl<5A><6C>G]<5D><1A><>9<EFBFBD><39><EFBFBD><EFBFBD><EFBFBD> k<>~j<>T0 s<>=A wb<77>5<EFBFBD><01><02>,<2C><><EFBFBD><1A> <0A>é<EFBFBD>~ <1B><>P9<08><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>N<EFBFBD>><3E>E<EFBFBD><45><EFBFBD><EFBFBD>-<2D><><EFBFBD><EFBFBD>FG<><47>)<29><1F>+<2B>O<EFBFBD>L<1F> <0A><>?6<><36>_U<5F><55>FsS<73>.<2E><71><DE85><EFBFBD><EFBFBD>7@O<><4F><18>?;
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><15>yZB<5A><42><04><><EFBFBD>A<EFBFBD><41>@oV<6F><56> <0A>$<24>'<27><><15><><EFBFBD>_p<>7y<><79>U<EFBFBD>7bݗ<62>qwOe<4F><65><EFBFBD>6<EFBFBD><36>|<7C><>><3E>O<EFBFBD><4F>%<25><02>0nx<6E>g<EFBFBD> <0A><><01>*W<01><><EFBFBD>
<EFBFBD>z11<EFBFBD><07><><EFBFBD> <0B>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD>m۶K;<3B><><EFBFBD><EFBFBD><0F>w<EFBFBD>Q<EFBFBD>1<EFBFBD><31>8F<38>eTH<54> W~<7E>~
<EFBFBD>`=[<5B><>p<01><><EFBFBD><EFBFBD>8*<2A>4<>?<3F><><EFBFBD><EFBFBD><17><>Y~(<28>J<EFBFBD>]΀z<CE80>m<EFBFBD><6D><EFBFBD>}<00><><EFBFBD> u<><75>K<07> o<><6F><EFBFBD>o<EFBFBD><6F><EFBFBD>Ʒ.hx.<2E>a<EFBFBD><61>@<40><><EFBFBD>Fx<46><31>-`<60>z<10>C<EFBFBD>Z<EFBFBD>t}X<>#vkj9z<39>]VV6<56><36>~<7E><>чz<11><>8<18>D<EFBFBD><44><EFBFBD><EFBFBD><00><><EFBFBD>l<EFBFBD>6<EFBFBD>ˠ<EFBFBD><CBA0><EFBFBD><EFBFBD>*<0F>cЃ<><D083>Z<EFBFBD>qx˗<78><00><00><>uIJg<C4B2>0<EFBFBD>FA<46><41><EFBFBD><EFBFBD><EFBFBD>lਧ<6C>1l<01><><EFBFBD><EFBFBD>n<EFBFBD><6E>QP<51><03>;|<03>#<23>s)<29><><EFBFBD>|<7C>0<1C>GA<47>W<>o<EFBFBD><13><><EFBFBD>bv <09>Ͱx}"<22>)I<>|&<26>.<2E><>-_R蒒<52><E89292>ݺu{<7B>K<EFBFBD>.<2E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>&0h<30><68>*Z<><5A>7+`-CY/<2F><<3C>:<3A><08>/<2F><><EFBFBD><EFBFBD>K<EFBFBD>_<EFBFBD><5F>Ʊ<EFBFBD>T<EFBFBD><54><EFBFBD>9<EFBFBD><39><EFBFBD><EFBFBD><EFBFBD> p
l<EFBFBD>K<19>O<EFBFBD><1C><>h?2-<2D> 4<><34><EFBFBD>oWv?<3F><><EFBFBD> `w<>?|އ
<EFBFBD> <08> <08> <08> <08> <08> <08>`<60><><EFBFBD>n<EFBFBD>*%4<><34><EFBFBD><EFBFBD><EFBFBD>B<7F><17>5B<35><42><12>JX<4A><58><EFBFBD>eq0p<11>X<><58> <0A><><1B>;2<><1C>"\k<>+<2B>b<EFBFBD>s@<40> <20><><EFBFBD><EFBFBD>Po<50>zx<7A><78>ׂ<EFBFBD><D782>wu<77><75> p<16>=,V<><15>A W)7t<37><74>q<1F><>p<EFBFBD>~<7E>1<EFBFBD><31> <05>j<19><>ԫ<EFBFBD>h<EFBFBD>wM<77>p9l<39>+<2B>S<EFBFBD><11>j<>i<EFBFBD><69><1B><16><>z<EFBFBD><7A><EFBFBD> <0C>`4<>n<><6E>'@<40>!<21>q<EFBFBD><71> <20><>0|3<>VFy<46><79><EFBFBD><EFBFBD><EFBFBD>(<28>h<EFBFBD><68><EFBFBD>B<16><><EFBFBD><EFBFBD> <0B>߸͞n<><0E><>f<>`G|<7C><><EFBFBD>m`<60>"<22>\ K%<25><>E <09>at/o<>=T<>te+8 <09><><EFBFBD><00><>O_8jG<01><12>W<EFBFBD>̥Pý<50>PP<50>0<30><1A><><EFBFBD><EFBFBD><19>tl<>q_<><13>oa<01><>J֙v<18>e<EFBFBD>i$8<><38><EFBFBD>J(<28>A<EFBFBD>El<45>ZKgxC<>w<EFBFBD><03> Ԇ_Z<08><0E><>j<EFBFBD>2<EFBFBD><32><EFBFBD>7!SFN<46><4E><EFBFBD><06>bTR<54><52>2<08>oU<6F>y~<7E>q/`y<>o<EFBFBD><6F><1E><><EFBFBD>B<EFBFBD><1F>hr׍<>JXX|'<27><>ܞǐ<DC9E>.<2E><00><>:<3A>X<><58>1<EFBFBD><31><EFBFBD>΅U<CE85>
<EFBFBD>SJ<EFBFBD>*X<>8<EFBFBD>B<EFBFBD><42><EFBFBD>4<;f7<66>c<EFBFBD><63><EFBFBD>$K<>6<EFBFBD><36>ʧQPRĿ<52><0E><1A>K%<25><>3<08><0E>
5GѮ<EFBFBD><EFBFBD><11><><EFBFBD>k<EFBFBD>{<7B><10><><13>-_<15>Wyx"<22> bo<62> l<>~<7E><>|<7C>F9Gc_<63>&W<>0<EFBFBD>Up<11>1 l<>>/<18><14><<0E><><EFBFBD>v!<21>2<EFBFBD>a<EFBFBD><1C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <09>S<EFBFBD><53>cW<63><1F><><1A>*<2A><>+ǀK<4D>fK8Lm><3E>W5<04>)<29><17>`3<><33><EFBFBD><EFBFBD>f>*B<><EFBFBD><>CAAAAA<10><><EFBFBD><EFBFBD>ܳ;<3B>.<2E><>t<01><03><06>#<23>uDgJ<67>6G<36>U|tA86<>f<EFBFBD>|<7C><>bY<13><17><><EFBFBD><EFBFBD>I<EFBFBD><49> <09><><EFBFBD>Y<EFBFBD><59>z<1D>:<3A><>h;<3B>m<EFBFBD><6D><EFBFBD>&¾0H?<3F><04><>KS<16>@<08><0F>g<EFBFBD><67>cl<63>m<EFBFBD><6D>Am<41><6D>rG@ <0A>֊/<2F>=i <0B>a<EFBFBD>gtX<12><>M<0E><><EFBFBD><EFBFBD>˩H<0F>lO<6C>a<EFBFBD>9U<39>F<EFBFBD><46>ͮLHyr<79><72><1E><>i֟I<D69F><49>ܧ<EFBFBD><DCA7>? `<60><>k<EFBFBD>@ -<2D> <0C><>m<EFBFBD>-<2D><><0F>,SdG<64><47>6O<18><>J<EFBFBD>x<EFBFBD>s<>E۪?<3F>7<06><>"<22><>O<EFBFBD><01><>$d<03>|4Ȼ;<3B><10> U<><00>Yp<59>0@<40>/<2F><>X<58>$<24>Kr<4B>q<EFBFBD><71><EFBFBD>0t<30>%<25><1B>e 35<33><35><03><> <12>ܸ
<20>/w<00>X <09><><EFBFBD>O<02>\u W<><57>q*pL<70><00><>k$<24><11>11<02><><EFBFBD><12><>\:(]- <20><>.<2E><><EFBFBD><08><><02><>JY1<7F><31><EFBFBD>-vA39<33>}_e9<65>c<EFBFBD>M<1D><>kE<00>7<EFBFBD>A<EFBFBD>&Oh<>_<EFBFBD> <20><><EFBFBD><EFBFBD>9<EFBFBD>f<EFBFBD>1<EFBFBD><31>.2
<1A><><EFBFBD>F<EFBFBD>D<EFBFBD><44>E<>i<EFBFBD>NCTB<54>
<EFBFBD><EFBFBD>< <09>Y<59><7F>!,ן<>A<EFBFBD>b<EFBFBD>P9<0F>:<3A>m<EFBFBD>Tu<54><70>'<27><08><>P%@<40><>O<EFBFBD> Yx?<1F>J<EFBFBD>VP
<EFBFBD>A<EFBFBD>nˎ-t[<5B><>6S<36><1A><><10><>۳<00><>?<3F><12>a<EFBFBD><61><EFBFBD><EFBFBD>F<EFBFBD><46><EFBFBD><EFBFBD><1E><><EFBFBD><EFBFBD>l<EFBFBD>8<03>@<40>uwq[<5B><><10>Exr<1E>y<EFBFBD>I<00><> a<>+<0F><><EFBFBD>:<3A>eX<17><><EFBFBD><EFBFBD>c8ͳ<38><CDB3>1<EFBFBD><31>AAAAAAA<04><>S<10>fK<66>gus@<40>
<EFBFBD><EFBFBD>k<EFBFBD>h<>.<2E><>`7<>s<EFBFBD><0E><><EFBFBD>5Z_<>3?<3F><><EFBFBD><<3C>1?O<><4F><EFBFBD><EFBFBD><EFBFBD>R<EFBFBD>!p<><70><EFBFBD><EFBFBD><EFBFBD>h<EFBFBD> Í/<2F><><EFBFBD><EFBFBD>4<EFBFBD><34><EFBFBD>;<3B><1D>3.L<><4C><EFBFBD>p#C<><43><EFBFBD><EFBFBD><EFBFBD><12><1C><>Bp<42>y<EFBFBD><79>6<EFBFBD><0E><><EFBFBD><EFBFBD>4<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>rS5<>˗<36>S<EFBFBD>K<EFBFBD>v<><76>/<2F><><EFBFBD><EFBFBD><EFBFBD>n<EFBFBD>N(<28><><EFBFBD><EFBFBD>XY<58><59><Ýe<C39D>%<25><>&<WtD<><44><EFBFBD>[妧<>oȗ!F<><46>]ڟ2<00> <0C><><EFBFBD>t<EFBFBD><1C><><EFBFBD><EFBFBD><1E><#9<><39><06><>><3E><><EFBFBD><EFBFBD>~<05>Bfs<66>׳u<D7B3><75><EFBFBD><EFBFBD> <0A><>ڙt<DA99><74><EFBFBD>j<EFBFBD>S<EFBFBD><53>n<EFBFBD>ΐ<00>&8<><38><EFBFBD><EFBFBD><EFBFBD>yF<79>5<EFBFBD> ^<5E><01>ć<><C487><EFBFBD><EFBFBD>>ws<77><73><EFBFBD><15><1A>c٧y:Ch<><<3C><><EFBFBD><EFBFBD><11><>VG<><11>&<26><><EFBFBD>} G9`g<><67> _;<3B><><<3C><>xj<78>\Sx<01>.hg<68>5l<35><6C>B<EFBFBD><42><4D><DC8E><EFBFBD>u<EFBFBD><75><EFBFBD>T˜f<CB9C>i<EFBFBD><<3C><>3n<17>F/<2F><>g$_-<2D><00> +1d<31>zk<7A>E<7F>'8{<7B><><EFBFBD>+ <0C>~<7E>m<06><><EFBFBD>g<>Na<>yFr@aPNC<4E><43><EFBFBD><EFBFBD>I<EFBFBD><49>G\?<3F>Ұ<EFBFBD>lc$<24><54>f<EFBFBD><66>X<><58>i<EFBFBD><69> <0C><02>p<EFBFBD><18>tzp<1A><>g<EFBFBD><67><EFBFBD><EFBFBD>4D<34><44><EFBFBD>Le<4C><65><EFBFBD><EFBFBD>I0j8<01>MN<4D><4E>p<EFBFBD>h<EFBFBD>'<27>go<67>˲<EFBFBD><CBB2>yV<79><56><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>I x
<EFBFBD><EFBFBD>B<EFBFBD><EFBFBD><EFBFBD>t<EFBFBD>P<1F><>8<EFBFBD>m2<17>c<08><><<3C><> <20>*<2A><><EFBFBD><EFBFBD><EFBFBD>Tjq3<><33><EFBFBD><EFBFBD><EFBFBD>g<EFBFBD><67><EFBFBD>)<08><><EFBFBD><EFBFBD>@MoP<6F><50><<3C><> <20><>Ӎ.<2E><><EFBFBD><EFBFBD><<3C><>AAAAAA<10> l ;Ҷ,s<> %<25><07> <09><>.<2E><>e=<3D><> <08><>Ȑ<EFBFBD>+<2B><><EFBFBD>Xz$<24><><EFBFBD>6<13><>c<EFBFBD>Q5<>s<EFBFBD><06>0 v<><76>ýR<10><><EFBFBD><1F>$Nm<4E>6<>Ep4<<3C><><EFBFBD><EFBFBD>3<EFBFBD>΀<>t <0C>|<7C><>3<1D><>Q|?:<3A>\w<><77><EFBFBD><EFBFBD><EFBFBD><04><><EFBFBD>'<27>1Eñ<45>'<27><>-<2D>> <0C><><EFBFBD><EFBFBD><EFBFBD>ngO<06><<3C> Թ<><D4B9><EFBFBD><EFBFBD>m<EFBFBD><<3C><>Ka6<61>Yj>*<2A><>;i<>­JA/O{<01><>6l<36>g:<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ߳pobv-O
e(N<>k<EFBFBD>T<EFBFBD><54><03><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>+<2B><><EFBFBD>&<16><>ܴ<06><12>u<0E>-<2D><>v<EFBFBD>oBm<42>.<2E><EFBFBD><EB8DB2><EFBFBD>y<EFBFBD>v<EFBFBD><76><15>vꈎ<76>|m<>B<00><><1A><02><><EFBFBD><EFBFBD><EFBFBD><18>%1M<31> ۡK<<3C>l36<33>d<EFBFBD><64>%<19>J__<><5F><EFBFBD>6><3E><><EFBFBD>2XkL&t<>j=ma9<<3C><><EFBFBD><11><><EFBFBD>)<29><>ȇ<EFBFBD><C887><>9|T<><08>\<5C><>q<11>۱0l<30><6C>=<3D>c<EFBFBD><63>(<1F>h<EFBFBD><68><EFBFBD>^ 5} fUn<55><6E><EFBFBD><EFBFBD>i <09><>|م_<D985><5F>V<04><><EFBFBD>م#_<><0F>5zExo=<3D>@<40><8P6A9<41> <20><>;X<0F><>˻-\5| <0B>ǃ<17>6<EFBFBD><36><02><1E>_<EFBFBD>8<EFBFBD><38>< `<06>o<EFBFBD>}eR<65><02><><19><>Ӕ#vc<76>w<EFBFBD><77><EFBFBD><EFBFBD>:<3A><>AF<41>$<24>|b<>T<EFBFBD>R<EFBFBD> <0F><>]<5D>|<17><> <0B>Gg$<24>C<EFBFBD><43><<3C>0\<5C>ǀ]<5D><><EFBFBD><EFBFBD>B<11><><EFBFBD>𕐙<EFBFBD>ײ<EFBFBD>t<EFBFBD><74>Ώ9s?<3F><11><><EFBFBD> 5<><35>}<00>C<EFBFBD><43>I) `3?<3F>Di<44><0F><>-D<1B><><EFBFBD>}<7D>V|b }<7D>m<EFBFBD><6D>P<EFBFBD><50><1C><>Xj<58>4<EFBFBD>CP<1B>w@<40>=<3D><>;
`<60>\<13><>P^<5E><><EFBFBD><EFBFBD><EFBFBD>>.l!<21><><EFBFBD>i0<69><30>D<<3C>wn<77>D<EFBFBD>e\<5C><><17><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\ D<><44>Kťh'<27><><<3C>k<EFBFBD><1F><><EFBFBD>]<5D><16>^<5E>><3E><>"$I<00>ӆݴ8<>ˉ<EFBFBD>O.ƶ<12>s <0C>l<EFBFBD><6C>!A<>:A<>ۑ!!<21><>\AAA<10><>><3E><04>h<16>IEND<4E>B`<60><>PNG

IHDR<01><01>><07><>:IDATx<54><78><EFBFBD><07>T<EFBFBD><54><EFBFBD>q<EFBFBD><71>ٕE@<40>Y<>*<2A>C(<28>1<>ylHzb<7A><62>`I̚<49><CC9A>Xb<58><62><EFBFBD><EFBFBD>f@<40><>5<EFBFBD><35>O<EFBFBD><4F><EFBFBD><EFBFBD>Yvw<76><77><EFBFBD>y<EFBFBD><6F>;3;<3B><><EFBFBD><EFBFBD>~<7E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><<3C><><EFBFBD>s<><73>;ۨ<RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ<52><4A>2X<32><58>PI}<11><> )<29><><EFBFBD>Ư<EFBFBD><C6AF><EFBFBD>`|<14>*<2A><>`)<29>A<EFBFBD><41>E!<21>_<EFBFBD>\<18>W<EFBFBD>c<EFBFBD>><3E>P<>h<EFBFBD><68><06>05<30><35><<03>|<17><><1C>}1%H)<29>Uv Tl0f#<23>+<2B><>f<EFBFBD><66>6<>2<EFBFBD><18><> P<05>T<EFBFBD>u<EFBFBD><75>j5<><35><EFBFBD><EFBFBD><EFBFBD><EFBFBD>7<EFBFBD>y<17>=<03><><EFBFBD><EFBFBD><01>#<23><>`NE<13>u<EFBFBD>ܟ<EFBFBD><DC9F>.P*<2A>N<EFBFBD>X<><58><EFBFBD>(<28>޶x<10>#<23><><EFBFBD><EFBFBD>h<EFBFBD><68>jC<1C><><EFBFBD>5<EFBFBD>I5<49><17>
<EFBFBD>f <20>j<EFBFBD><05>alğq(j<>J<EFBFBD><4A> <0B>²<EFBFBD><06><>d<EFBFBD><64><EFBFBD>am<61>#<23>7<EFBFBD><37><EFBFBD>4<>?<3F><1A><>G<EFBFBD><07><03>0<EFBFBD><30>x
<EFBFBD>$`9j<39>4<EFBFBD>Бx<07><><EFBFBD><EFBFBD>E<EFBFBD> eepB<><1E>e<EFBFBD>W<EFBFBD>Az<10><>S<EFBFBD>G<EFBFBD>ƻ<EFBFBD>kI<1E><>9<EE89AD><39>ܻ<EFBFBD>0<><11>!,<2C>5<EFBFBD><01> <0A>zj<>;`*N<>Mx#<23><><08><>\m<>`E<><45><EFBFBD><EFBFBD>*<2A>؆Y\h<><68>Z<EFBFBD><14>4<EFBFBD>{_<><5F> <0C>3<EFBFBD><33>gq<67><71> <09><>?<3F>)<29><><EFBFBD>3<EFBFBD>y<EFBFBD>,<2C><>Ҟ<<3C><0F><><<3C><19>E<EFBFBD><45><EFBFBD><EFBFBD>e;<3B><1C>K<>t<EFBFBD><74>}3\˹
<EFBFBD><EFBFBD>^<5E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>}XK<>7T\<07>ٌP<><50>b<14>u4<75>{<7B><><<18><1A>O@<40><1E><><EFBFBD>/<2F>@uë<75> ^G<>`<60><><EFBFBD><EFBFBD>0|<7C><>!<21>?<3F><16>4<1E><>%<25>Qw@<40><><EFBFBD>nC/<2F><>7<37><EE80A5>x<EFBFBD>Gee<65>F<><16><1E><1A>W<EFBFBD><3<><33><EFBFBD> <03>v<04><1F>j<6A>f8
1<11><01><>*<2A><><12>B<EFBFBD> @u<><75>9<EFBFBD>@3 _@-<2D>j<EFBFBD><6A><18>b<EFBFBD><62>9~<7E>d8<64>;<1A><><EFBFBD><EFBFBD><EFBFBD>ƀ2~<7E> Q<>tգG<D5A3><07>B<EFBFBD>C<EFBFBD><1C><><EFBFBD>/<2F><><EFBFBD>&<26>/" `DME<><45><EFBFBD>t|<17><><11><>XK<>9<EFBFBD><39>΃<EFBFBD> <12><>މ;<3B>x<01><>k<EFBFBD>U@<16><67>_<EFBFBD>EH<45>v^H<>.,I<><49>:<3A><>S'<27><>21<1E>^x<1B>yu<1A>H{<11>ȧ<EFBFBD>Q<EFBFBD>|<1A><>EW<45>:p8<70>;m0O<30>wi<77><11>\U@<16><><EFBFBD><EFBFBD>L_gf"<22><><EFBFBD>8<EFBFBD>y ;"<22><>h<EFBFBD><68><17>g<EFBFBD><67>?<3F><><EFBFBD>LqB<71><42> `<60><><EFBFBD>#<23>C<EFBFBD><1D>Ӑk<D390><6B>6<>ԍ<EFBFBD>p<EFBFBD>}<1D>%=S<><10><><EFBFBD><EFBFBD>gvݰ<1E>F+<2B>C<EFBFBD><43><05><>2~<7E><>I1O<31><<3C><>8<EFBFBD><38>2<EFBFBD><32>G0<47><30><EFBFBD><EFBFBD><7F>
ni#n ocz<03>)<29><><0E><><EFBFBD>I#Q<>n<EFBFBD>u<EFBFBD><75>ޡO<DEA1>`<1A>{ցې{J<03>yuh@<02>I<EFBFBD><0F><>ߵ
<1C><>8<><38>b9V<39><56>ѷ6<D1B7>?&<26>]<5D>@<40><EFBFBD><05><EFBFBD>l<EFBFBD><6C>&Kݛ<4B><0E><1D><05><>(<28><>wXބ<>!Т `<60>
@<><7F><1F><>j<><6A><EFBFBD><0E>f<EFBFBD><1D><><EFBFBD><EFBFBD>J=<3D><19>ۼ<EFBFBD><DBBC><EFBFBD><EFBFBD><EFBFBD>Q<EFBFBD>N<EFBFBD>x<EFBFBD>(r<><72>e<EFBFBD>[<0E>z2<7A>N<EFBFBD>)<29><>\<5C>ah<61>q<EFBFBD><71>Q<EFBFBD>7<1F>9<EFBFBD>: &C<1A><>{<12><>O<EFBFBD><4F><EFBFBD>-.<2E><><EFBFBD><1B>5<EFBFBD><35><EFBFBD>+<2B><><EFBFBD><EFBFBD>W<EFBFBD><57>c),<2C><>w<0E>ð4<1E>NJ<><4A>xݠtDQO<51><4F><11>y<EFBFBD><17><>`2\<5C><><EFBFBD>:A <0A>0<>.<2E><15>;<3B><>aoB}><3E>X]<5D><><06><><EFBFBD><EFBFBD>9<EFBFBD><39><EFBFBD>~<7E>aT<61>C<EFBFBD><43>.<2E>Or!<21><> H<>Ea^<0E><><EFBFBD><EFBFBD>j3k<33><6B>qF<><46>3Q׈Ͱ"<22>=<3D><01><><EFBFBD><EFBFBD>6ûnjD{]07;<3B>{<7B>q<EFBFBD><71> <19>eU<65>ZI/<2F><>s<EFBFBD>|!|<7C><><EFBFBD><EFBFBD>j3[<5B>F<EFBFBD><46>%<25>":2<><01>/<2F>U<><55>K<EFBFBD><4B>wA<77>v<EFBFBD>p<EFBFBD><70>?<3F>J7<4A>.٭І<D9AD>e<EFBFBD><65>Q1<51>Z<><5A><EFBFBD><EFBFBD>Z<04>8<EFBFBD><38>8!V<>?<3F><><EFBFBD>C<EFBFBD><43>`?<3F>x(<28>u~_E <0A>j<EFBFBD><6A> <0C> ޏ<>Pz;<3B><><EFBFBD>Oz<4F><7A><EFBFBD>O<EFBFBD>ј /落h<EFA498><68>!<21>4<EFBFBD><34>"<22><><EFBFBD>J<EFBFBD><4A>
tK<07>?<3F><>(W<>Y<EFBFBD>f<15><><EFBFBD><EFBFBD>X<>ŝ_jP!]<5D><7U<37><55>͍5Oosc<73>lp<6C><70><EFBFBD><EFBFBD><EFBFBD>c*<2A><>C<EFBFBD><43>Eh<45><68><EFBFBD>C<EFBFBD><43>SI<53>W<EFBFBD>o<EFBFBD><6F>C<EFBFBD> <10><><EFBFBD><1F><02><>[<5B><>f<00>Ď<08><><EFBFBD>6<EFBFBD>@o<> <0B><>n<EFBFBD>f<07><>X<1A><><EFBFBD>߉*<2A><><7F><EFBFBD><EFBFBD>m<11><>Ń<18>\<1B><07><>z5<7A><35>f E<><45> <0C><>B<EFBFBD>ob<!<21><11>q2<71>R<>q.<2E><>s<EFBFBD><73>A7P%=<3D>s<EFBFBD><73><EFBFBD><EFBFBD>z&X<><58><EFBFBD><EFBFBD>,<1B><><EFBFBD>Q<EFBFBD>4<EFBFBD><34><EFBFBD>#<23> <0A>Wp5<70><35>;X<07><>B<><07>*<2A>?<3F><><19>g<EFBFBD>ߙ<EFBFBD>jT`<1C><><~<7E> էm<D5A7>J<EFBFBD><4A>z_<7A>><3E>LD<4C><44><00><>E<EFBFBD>v<EFBFBD>wӌ.<2E><><EFBFBD><EFBFBD><1F><><EFBFBD><EFBFBD>F'<27>ƚg<C69A>@<40><<3C>M<EFBFBD>)KM<05><06>7<EFBFBD> <0C>F<EFBFBD><46><EFBFBD>{ <0C>zXv<58><76>J<03>4<EFBFBD><34><EFBFBD><EFBFBD>x:a<1A><><EFBFBD>t<EFBFBD>4<EFBFBD>J<EFBFBD>A,<2C>@<<3C>*(U<1A>
O83<38><1C>J<EFBFBD>@ <0C><><EFBFBD><EFBFBD><EFBFBD>O'<27>t<EFBFBD><74>RJ<52><4A> <20><><EFBFBD>2<EFBFBD><32>x<EFBFBD>G<EFBFBD><47>R<EFBFBD><52>.<2E>^<17>w<EFBFBD><77>RJ<52><4A><EFBFBD><EFBFBD>q<>:<3A>;15Onß陟RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ<52><4A>'0<18>&<26><>R<1A><>0,<2C>v<><76>RJ<1D>f<EFBFBD><66><08><><EFBFBD>RJU|3<><05>g<EFBFBD>J)<29>J<EFBFBD>FP)<29><><EFBFBD>'xO<><07>Ո4<D588><34> +<2B><>P<EFBFBD><50><EFBFBD><EFBFBD>Ӱ<EFBFBD>7<EFBFBD>[aI^<5E>qBU<><55><15><13>3Ae<11>:+M<>XC<1B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>`<02><>`(J<>R<03><08>lu<6C><75>LPi5<>j(<28><>pV<> <0A>B{G<>w<>w<><77> E`<60><><EFBFBD><EFBFBD><EFBFBD>T<EFBFBD>3<EFBFBD>V<1C><1D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><00><><EFBFBD><EFBFBD>2'<27>fb,KM4~<7E><>?<1B><0F><> ho<j<>ޱ؈fL<66><4C><EFBFBD>n<EFBFBD><12>F2~.<2E>`I<>j<00><><EFBFBD><EFBFBD><1C><><EFBFBD>~<1B><>#x"<22>5 <1B>c4<63><1A>b<EFBFBD>߫i<DFAB>O#8<> <09>JM<><4D><EFBFBD><EFBFBD><53><C393>\<5C>j4<6A><34>bg!<21><>Q<EFBFBD><01><00>n<EFBFBD>4<EFBFBD>#<23><02>c7 `di+g<04>c9 砣vK<1A><><EFBFBD><EFBFBD><EFBFBD>a8Q<03>,<2C><>i<04><><EFBFBD>7<><1A><>0"<22>p<08>nD<6E><44><EFBFBD> W<>#<23><1B>&<26><>SJ<03> <0B>yg{ W<>#<23>zU<7A><55>i<00>?<3F><>ф<EFBFBD><D184>6<EFBFBD><36>RD<52>`<60>@g!<21>Fa8<15><><1E><><EFBFBD>)<29><)<29><><EFBFBD>><3E>'h<>@ <0A><01>?<3F>:<3A>"<22>·a\E<1D><>0\Ó<>4<EFBFBD>e<EFBFBD>DX<44>}K<><17>j{b>Za<1A>H;<08><>^<5E>;<3B>$p:<3A><><EFBFBD>f<EFBFBD>]<18><>e<EFBFBD>4<EFBFBD>y:<3A><>/{=<3D><12>H^BO<42>_@<03><<18><> `<60><><EFBFBD><04>c<04>id#<23><<3C><01><>j <0A>+<2B><02><>h<><1A><>Z<EFBFBD><5A>,<2C><00><>MH<4D>|<1A><>; <09>|O<><4F>4 <09><19>}<7D><00>S<EFBFBD><53><EFBFBD> f<>I<EFBFBD>a<><01><>!<21><>ÿ0-<2D>
<EFBFBD>@<40>i<1D>ð<1C><>0<>N,t<04><><>!<21>2><13><><EFBFBD><EFBFBD>&"CQ<><0E>f<18><><EFBFBD><EFBFBD><EFBFBD>P<03>|@r<>#<23><>Y<>g<EFBFBD>gA<67>$<24><>F0<46><30><EFBFBD><EFBFBD>EX<45>Q<>(<28> [`I~<1A>3?<3F><><EFBFBD>!P}<1F><>M<EFBFBD><4D>`w-<2D>3<EFBFBD><33>*<2A>H<EFBFBD>0<><11><><EFBFBD><EFBFBD><10><><EFBFBD>y<EFBFBD>̓y<CD83><79><EFBFBD><EFBFBD>oF<>4<EFBFBD>: F<><46><02><0E>I<EFBFBD>;<15>|o<><6F>{<7B>P<18><08><><EFBFBD><EFBFBD>m<EFBFBD><6D><EFBFBD>93<><33>?<3F><><EFBFBD>e<10>>N<><4E>:PqF<71>;<3B>tk5<>Q<EFBFBD><51>?~~<7E>a)<1C>ru̳<><CCB3><EFBFBD>=<3D><>S<17><><EFBFBD>X<EFBFBD><58><EFBFBD><01><><EFBFBD><EFBFBD><EFBFBD>81<38>l<EFBFBD>YE<59>i<00>8<EFBFBD>/y<><79> @<40>~Krʛ<>L0<4C>g~<7E>ũ[<5B><><EFBFBD>x2 <0C><>
<1E>s<EFBFBD> <0B><><06><><EFBFBD><EFBFBD>ם9<1E>8SJ<>"?<3F><><EFBFBD>Ͱ<EFBFBD>}<7D><>3H<33><48>,/<2F><18>T<EFBFBD> <0B>2<EFBFBD><32>P<>׼H<D7BC>O<EFBFBD>8<EFBFBD>vH<76>><3E><>uX<75><58>e1<65>`L<>s <0B>a<18>L<EFBFBD>D5<44>j<EFBFBD>7~@ <0A><06><>MG36<33><18>W<EFBFBD><57>h<EFBFBD><68>#x K1<05>TjH<03><01><46><04><>Ќ#<23>޷Іո<D086>? <0A>RJ<03><01>W9<1B><><EFBFBD><EFBFBD><EFBFBD>9[<5B>E<EFBFBD><45>M<EFBFBD><4D><EFBFBD><04>(( <0A><><13><>Rx'<27><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>T<><54><EFBFBD><08><>{<7B><><EFBFBD>S<EFBFBD><15><>*<2A><K#<1A><08>j<EFBFBD><6A>K<EFBFBD>8<16>7<>Ji<00>RJ) <0A>RJ)<29>TJ)<29>4<EFBFBD>a<EFBFBD><61>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><><0A>6dȐ˰V<><56><EFBFBD><EFBFBD><EFBFBD>?=zt<7A>m:oJ)5 X
 <20><>?+&Fp<46>6<EFBFBD>7<EFBFBD><37><EFBFBD><0F><>$ <0A>*X<><58><EFBFBD>F<EFBFBD><46><EFBFBD><EFBFBD>E<EFBFBD><45>I<EFBFBD>u<EFBFBD><75><EFBFBD><EFBFBD>IUU<55>JX <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!<21>,<2C>wB*y<>"<22>\Ji<00>in<69><6E><EFBFBD><EFBFBD><EFBFBD> <09>hSW<53><57><EFBFBD>hCwt<77>4<EFBFBD>Ji<00><>|<7C>DZ <09><><EFBFBD><EFBFBD>u<EFBFBD><75><16>B F{<7B>p9,<2C>+<2B><1F> <0A>X<>( `LS@ <0A>Ee<45><65>t5<74>i<EFBFBD>_0ò<><06><><EFBFBD><EFBFBD>3<EFBFBD><33><10>4<EFBFBD>s<EFBFBD><73><EFBFBD>8T<38><54>i<><69>P<EFBFBD><50>p=N<><4E><EFBFBD><EFBFBD><EFBFBD>`<60>4<EFBFBD><1A>B<1B><><EFBFBD>i<>X<EFBFBD>= <0A>gl ` <0C><><18><><EFBFBD><EFBFBD><1F>j5<><05>8<EFBFBD><38><EFBFBD><EFBFBD>*TP<1A>#+d<00><><EFBFBD><EFBFBD>} m0$prƏ<72><C68F>p\<5C>`<60>><>f<EFBFBD>"2QՄl<D584><6C>q<EFBFBD><05>b5<62>b#<23><>i\<5C>#Q<><01><>z<00><>C}<7D><1F><>- ` <0B><>{<7B><03>|7<>gq<67>b<EFBFBD>s<EFBFBD><73>3<EFBFBD><33>D<>e<18>A<EFBFBD>aYZ<59><5A>0LX<03><><1F><>FPh<>[<5B><1A>j<00><>VX?F<15><><EFBFBD>#Xm8QeiF<69>~<7E> <0A><m<>%<25><><01><><00><><EFBFBD>/<2F><><06>I<EFBFBD>&<26>!S<1A><>;<10><><EFBFBD><EFBFBD> 2<>gX`:<3A><>R<EFBFBD><52>0<EFBFBD>+<2B><17><13>H<18><><EFBFBD><11>z<><7A><EFBFBD><EFBFBD>( `y<1A>Ű><3E>LK<>M<EFBFBD><10><><EFBFBD>F|Ka)<29><> <0C><>^艝0?<3F>rX
+<2B><>P<03><11><><00>s<17>!U<1A><><EFBFBD>w<EFBFBD>'<27><><EFBFBD>T<EFBFBD>4<EFBFBD>R<EFBFBD><19><>n9<6E><39>d<>ǧ•<>IX<>4<EFBFBD><34><EFBFBD>' `j<>P<03>D<EFBFBD><01><>LuE<1B><><EFBFBD>@wFr<>w<></<2F><>P<03><><EFBFBD>j+<2B><10>Dd<44><64>!<02><<3C>j<EFBFBD>[~<06>\<5C><01><>΍<>I0'e<>x<EFBFBD><78><00><10>N<EFBFBD><4E>2<><32>`O<>I<EFBFBD> <09>T<EFBFBD>ߧ8;t<>0H)GP<47><50><01>I0<49> <0C>wi<07>A<EFBFBD> <0B>2<EFBFBD><32><EFBFBD><E6A390> <0C><>Z `|0<>j<>4<EFBFBD><34><EFBFBD>2 <0A>;<3B>,=<3D><><EFBFBD><EFBFBD>9O{!<"x&8<07>d-z<>sWŠlE<6C><0E>7<EFBFBD><37>? <0A>.<2E><><00>Vh<16>v<>R|<7C><>0]P<>R<7F><01>q<EFBFBD>o<><6F>t<><74>Ͱ5<CDB0>1<EFBFBD><15>P7<50><0A><>Fp<05>@+w<>i<EFBFBD><69>jjj<6A><1C><00>퐪q <0B><><EFBFBD><EFBFBD>5<EFBFBD><35><19>Po<50><6F><EFBFBD>攈RzC<7A><43><EFBFBD><00><> q?<3F>\<5C>!<21><06><>R@ <0A>JX<04>oS<6F><53>`.<2E>`<60><><1F><>2<EFBFBD>»<EFBFBD>e.<2E>B4@iU<1C>j<00><><EFBFBD><EFBFBD>G1<47><31><EFBFBD><EFBFBD><EFBFBD>&<26><><EFBFBD>%<25>%ݡnV <09><>HTxJ<03><01><><EFBFBD>ӥ<EFBFBD>ԊR=<3D>s<EFBFBD><73>!<21>,<2C>w<EFBFBD>o\<5C>P/<2F>*ee<65><65><EFBFBD>>X@^5<>aV<61><56><EFBFBD><EFBFBD>E5*=<3D>4<EFBFBD>j.<12>.<2E>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>R<EFBFBD><52><1A>*<2A><>R<EFBFBD>
<EFBFBD>\t<><74>RJ<52>S`<60>M肊N)<29><><1A> <0A>$<24>B<EFBFBD>R4{g<> <0B>R<EFBFBD>$U<><55><EFBFBD>$-]<16>rw<16>`YZX<5A><11><>O)<29><1D><>GP<47>Z<><5A><EFBFBD>r<EFBFBD>5<EFBFBD><11><>O<EFBFBD><4F>\<<3C>E<EFBFBD><45>,r6#Z<>0'd<>x<EFBFBD><78><EFBFBD><EFBFBD>(l<>%y]J<16>reN<65><4E>?<3F><><EFBFBD><EFBFBD>؂<EFBFBD><D882><1B>O߿<4F>U<EFBFBD>p<EFBFBD><70>GaY<61>7><3E><10>Nj<EFBFBD>m<><6D><EFBFBD><EFBFBD><EFBFBD>ų<EFBFBD>$<24><><03><><01>R<>#<23><><EFBFBD><06> <0B>G<02><><04> <0B><><EFBFBD><EFBFBD><EFBFBD><-G%w <09>s<01>J<03><01>z<04><><EFBFBD><00><><EFBFBD><19>!<21><>ZXC<03><>0<>bzjP<6A><EFBFBD>$O<><4F><EFBFBD>j5<>Q<EFBFBD><51><EFBFBD><1A>.i<>o=<3D><>~<7E>3<EFBFBD>:<1C><><EFBFBD>H3<48>]P<>~CK'?Y<>O<EFBFBD>k<EFBFBD>/{߈<11><><13><>}<7D><>}<7D><><15><01><00><18><0F><>b<EFBFBD>0<><30><EFBFBD><EFBFBD>p&2<>7<16><<3C>8<>]ј<>]P<1B><01><><EFBFBD><EFBFBD>s<05>s<EFBFBD><73>X/,<2C>y><3E>(D<>P<03>w
?<3F>aaL<07><0F>c<15>j<00>i<EFBFBD>^<5E>k<EFBFBD><6B>,<2C><><EFBFBD>L<EFBFBD><4C><EFBFBD><EFBFBD> <0A><><EFBFBD> <0C><><EFBFBD>8:<3A><>@<40>E{<7B>E<EFBFBD><45><EFBFBD>GQ<47>>~s<><73>D?<3F><01>i<EFBFBD>!}<7D>1<1D>_<EFBFBD><5F>;4<><34><EFBFBD><18>)d<04><>]X<><58><19><><EFBFBD><06><>F<EFBFBD><46><EFBFBD>/<2F><><EFBFBD>%<25><>ݛ<EFBFBD><DD9B><EFBFBD>&<26>ڌ,Nxz}5<><1A><><EFBFBD>NK<4E>8<EFBFBD><38>,<><7F>x<EFBFBD><78>L<EFBFBD><4C>9<EFBFBD><39><03><>`<00>
s<EFBFBD><EFBFBD><EFBFBD>,<2C> s<><73><EFBFBD>H@{7<><_O<5F><07>*X<16>A/ `<60><><10><06>ކy<DE86><79>.&߿<>Ê<EFBFBD>:<04>\X<>+A<>]<5D>#<23>,<2C>y <0C> 0g|/X<>33&<26>@nD{!<21>}<7D><>h<1C> ]4<>EL<03><> ൰4<E0B5B0><34><EFBFBD><EFBFBD><EFBFBD><0F>
<EFBFBD>0jL<><4C><EFBFBD>q(p/<2F>%y<08>O<03>~<7E><>'<27>bi<62><69>Z<06><><03><>;Q<>,R<1A>~<7E><><EFBFBD>:<3A>Ж<><D096><EFBFBD><EFBFBD>br<08><01>ayZ<79><06><><EFBFBD>mEPA#8 <0A><>u<EFBFBD>> <0A><1C>w'<27>s<EFBFBD><73><EFBFBD><10><><EFBFBD><EFBFBD>Z `<60><><00><>!<21><><01><>W<EFBFBD><1C><><EFBFBD><0F>k<04><>r<EFBFBD>#\<5C>`<60>*<2A>
<1A>Q<EFBFBD>$<24>P<EFBFBD>4<EFBFBD>O<EFBFBD><4F><EFBFBD><EFBFBD>a<61>>V<><56><EFBFBD><15>2 <0A><>#+<2B><00><18><>॰,͋<>I0<49><30><02>R <0B><><EFBFBD><1E>O<EFBFBD><4F><EFBFBD>ђb<04><04>1)<29>:,]<1A>f<EFBFBD><66><EFBFBD>^<><7F>}|%<25>s<1F>V<>;Q<><01>ud%<19>C<18><01>[s<1C><>ct詰,<2C><>`<60><><EFBFBD>ց
z&xh<78><68>@5<>MhoA<6F>;<3B><13>C3,OC<7F>N<EFBFBD><4E>ud<75>@<40><>q̣[<5B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>t<><74>=<3D>*h<>}<7D>A<EFBFBD>& <0A><>I<EFBFBD>|<05><>%<25><><EFBFBD><EFBFBD>`yzZ<7A>A<EFBFBD>:<3A><><07>N<>
`<60>?3<>a<EFBFBD><61><EFBFBD><EFBFBD>Q<EFBFBD><02>=<3D>]<5D><><EFBFBD>طQ<D8B7>4<EFBFBD><34><EFBFBD><EFBFBD>wH<77><48><EFBFBD><EFBFBD><EFBFBD>w<1F>,]<08><>Ȃ<18><><EFBFBD><EFBFBD>h?3ԝ<33>~#s<>}Y<>\<08> G<>]<5D>I<06>7<EFBFBD>cU<63>?<3F><><EFBFBD>S<EFBFBD>gyX<79><58>QH@]Gf<47><66><|<7C>0<>3C<33><19><><EFBFBD><EFBFBD><7F>E<EFBFBD><45><EFBFBD><08>F<><46><EFBFBD><EFBFBD>
<1F><><18>>v
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>'<27><>2<EFBFBD>ͰuY<><03><><EFBFBD>9~<7E><>] g<><67><EFBFBD>w<EFBFBD><77>'<27>3<EFBFBD><EFBFBD>_<EFBFBD><>P<EFBFBD>><3E><>+xON<4F><4E>o}<7D><><EFBFBD>z<EFBFBD><7A><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><00><00>:<3A><> <0A>9x<1F><>0<>Nqb<71>u0ϻY<CFBB><14> 2<1C> <09><>`<60><><EFBFBD><EFBFBD><14>S<EFBFBD>GH<47> quY<><59>/U]<5D>,<2C><>p<11>av<>!<21>Ka)<<3C>.<1A><>N`r~<7E><1C><00>:2 <0A>P5<50>#<23><>Gр<47><D180>̹7e<37>!<21>3!5*<2A>{<1B><><EFBFBD>? <0A>n<EFBFBD><6E><01><>/<2F><><EFBFBD><EFBFBD><<3C>l<>5<EFBFBD>Eh <0A><>N<06>G(<28><><EFBFBD>w<><77>!<21><01>/<2F><04>H@ `<60><1B><><EFBFBD><EFBFBD>6{!<21><><EFBFBD><EFBFBD>9><3E>^<5E>$<24><>%0<>P<><50>_<EFBFBD>/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1A><><EFBFBD>a<><61>tM{<7B>xm<78>)<29>@<40><>~<7E><>Ÿ<EFBFBD><C29F>݃<><DD83><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!<21><>
#<23><>O<EFBFBD><4F>+<2B><>R<EFBFBD>j0<1F><><15>,<15><>J<7F>o<EFBFBD>T<>S<EFBFBD><53>RJU#eJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ<52>.<04>><3E>ȔRJ<52><4A>x<17>`<12><>26<32>w<EFBFBD><0F><><EFBFBD>h<EFBFBD><68><EFBFBD>1<10>ֱ<EFBFBD><04>b<07>p<EFBFBD><70><EFBFBD><EFBFBD> <0C>xwZІ<16><>I<EFBFBD>$<24><>RAtZ`<60>b F<>t<EFBFBD><74><EFBFBD><EFBFBD><EFBFBD> <0C>j<EFBFBD>s<><73>*<2A><>/<2F>`h<>/<2F>2,I<03>*{<7B><><EFBFBD>C\G<><08><><EFBFBD><EFBFBD>h<EFBFBD>9<1A><>:<04><><15>`<05><>x<EFBFBD>m<EFBFBD><6D>(GV&q<>T<EFBFBD><54>N<EFBFBD><4E>h<EFBFBD><68><EFBFBD><08>z<><7A><15>c7ﰮ?<3F><1A><>Z<08>,<2C><>_=p<1C><><EFBFBD>0<<3C><>8<17><><EFBFBD> <0C>g4<>A4-<2D>tt<74><74><EFBFBD>6X<1A>B<EFBFBD><42><EFBFBD>-0g9<67>w<EFBFBD><77><EFBFBD><EFBFBD>"N@<40><><EFBFBD>
<EFBFBD><EFBFBD>},<2C>,W<>z<06>9l@[<5B><>t%z<><7A><EFBFBD><EFBFBD>9 <09><>w<EFBFBD><EFBFBD>r<EFBFBD>x<EFBFBD><78>r#<23><06><>q<56>aW#<23><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>l<EFBFBD><6C><EFBFBD>@X<><58>œ;<3B> <0B>s<EFBFBD>ЉGG<47><Ar<41>`<60> <1A><>Հ<EFBFBD>i^<5E>j@E<></<2F>lu?<0E><01>Q <0B><>,KUx<03>L<EFBFBD><14>AX<41>D<<1A>ǐ<EFBFBD>9c[<5B><>xsڐ<73>C<1A><>T<EFBFBD><54>ai<<3C><>J?<3F><>B$w,Z<><5A>o<0E>P<03><03>A+<2B> <0B><17><>h(<28><>B<EFBFBD><05><>ݻ<EFBFBD>rނ9<DE82>4<EFBFBD><34>W<EFBFBD>8<00>ð<18><><EFBFBD><EFBFBD><EFBFBD>b<EFBFBD><62>[<5B><05>,C?<3F>ep]g8<67><38><EFBFBD>#<23><05>k<EFBFBD>J<EFBFBD>Z<EFBFBD><5A>
<EFBFBD><EFBFBD>X<EFBFBD><EFBFBD>Fd#B<>N<EFBFBD><4E>}<7D><>s~<15><01><><EFBFBD><EFBFBD>pT#<23><>0<16><>>؊6<D88A>?<3F><>k<EFBFBD>b1<62><31>*lO<>e<EFBFBD>ļ<>gC<67><43>CwB<1C><>`I<><49><EFBFBD> <0C>=<3D>B9<42><39><EFBFBD>}<7D><04><><EFBFBD>z<EFBFBD><7A><EFBFBD>a<EFBFBD>/"<22><>`# 4<><34>]<5D><06>&4h<00><><0A>[<5B>!<21><><49>q><3E><>Њ<EFBFBD><D08A><1C>l<EFBFBD><6C><00>`><3E>W<EFBFBD>NGK<47>/M<><4D>g~<7E><> <09><><EFBFBD><EFBFBD>|<7C><><EFBFBD>b]<5D>g~<7E>B<><42><EFBFBD>K~<7E>*<2A>[u<>K
Έ<EFBFBD><EFBFBD><EFBFBD>q<EFBFBD>s<EFBFBD><0E>ӅHxߛ<78>x<1F>0lh<C29D>V<EFBFBD>B<03><>g<EFBFBD><67><EFBFBD>h<00>y S<>8<EFBFBD><38><19>9Z<39><11><><EFBFBD><EFBFBD>_<EFBFBD><5F>1~<7E>w <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><18>Pj<50>%<25>!<21><>jX<6A><58><>9_<39><5F>W`΋<1A>`<60>^<5E><00><>|<1E><>{<7B>9<EFBFBD>û<EFBFBD><C3BB>;h<><68><EFBFBD>+n<03>$p<13>b5<62><35><19><>[<5B><>J{<7B><>=3<><33><EFBFBD>y<EFBFBD><12>Y<11>V<>vX<76>v<><76><EFBFBD><<3C>)<17> z<><7A><1A>B5Bl<<3C>Y<EFBFBD><59><EFBFBD><EFBFBD><EFBFBD>=<3D><>*<2A>.<2E>b<EFBFBD>Ǯ8 <20><>#C-<2D><><EFBFBD>b<EFBFBD>wG<77>z<EFBFBD><7A>5<EFBFBD><35><EFBFBD>pp<70><03><><EFBFBD>Y<EFBFBD><59>Q<EFBFBD><51> <0B><><EFBFBD><EFBFBD>a<><61>;ƄQ$X<>СC<43><7F><EFBFBD> 2<>.<2E><><EFBFBD>3<EFBFBD><33>P<EFBFBD><05>܆t<DC86>sn<73><6E><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>pEҟ<45><D29F>_<EFBFBD><19>V<EFBFBD>1T<31><15><01>܅~<7E><0F><>aErBN<42><4E><EFBFBD><EFBFBD>)<1E><><EFBFBD><15>f<1C>P<EFBFBD>K>,X]]ݼ<><DDBC><EFBFBD>ߘi<DF98>F<EFBFBD>}KUU<55>V<EFBFBD>5<EFBFBD><35><08><>Xˑ{<7B><>"<22>0o<30>Z<EFBFBD><5A><EFBFBD>,<2C>w<EFBFBD><77><EFBFBD>?<3F>/<2F>T<EFBFBD>:<3A><><EFBFBD>̟O'sE?~z<><7A><<3C>KzW<7A>M8<02>5K`<60><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>U<EFBFBD><55>oܸqW<71>w6$}<7D>b8B<38>[<5B><} *<2A>nHss<73>U8;c;|L<7F>;f=vi5<>Q<EFBFBD><51><EFBFBD><EFBFBD><EFBFBD>Er; <20>vǧ0X<30>n<EFBFBD>V<EFBFBD><1B>.]<5D><><EFBFBD>N+<2B><0F><> ,O<><4F>I0<49><30>?@<02><16><> <0B>|<7C>?<3F>:<04><01>~<7E><><EFBFBD>/NM<4E><4D>K7<4B><37><EFBFBD><EFBFBD>?<08><>a<EFBFBD><61><1A>N<1B><01><>=pΆ%<19><><EFBFBD>'Z<><5A>p&<26>A/<2F><>$ <0A><>O<EFBFBD><4F><EFBFBD><EFBFBD>ơk`Σȶ<C8B6><7F>+5<>%<25>^Oq<4F><71><EFBFBD>Md꫰6<><1B><>e@<40><>Ư<EFBFBD><07>;><3E><><EFBFBD>˶o<CBB6><6F><EFBFBD><EFBFBD>MX<><58>`)$p2<><32><0E><> ?]<08><01><>y<EFBFBD><79><EFBFBD>k~ϡ/<2F>J8<07>l<EFBFBD><6C><EFBFBD><EFBFBD>zl<7A>9<EFBFBD><39>GI<47><49><EFBFBD>ѹ<15><><EFBFBD><EFBFBD>35<33>;[<5B><15>Ǻ<15>P<><50>6K<36><4B>؏<EFBFBD>p6<70>;_C<5F>}<03> `m<><6D><EFBFBD>,<2C><06>3<EFBFBD><33>ߠ<05>xw<>瘄j<14>n<EFBFBD><6E><EFBFBD><EFBFBD>oovt<76><00><>[Y{j<00>n<EFBFBD>6m0<6D><30>A<EFBFBD>f<EFBFBD>}P<><50>vH<76><12><>yY<79><11>t<EFBFBD>4<EFBFBD>Jx<><11><>Ơ<><C6A0>8 <0B><>u<EFBFBD> <09><>^@U<>*v<>\<5C>Ÿ1?<3F>a<EFBFBD><61>*<2A><><EFBFBD><EFBFBD><EFBFBD>;<3B><><EFBFBD><EFBFBD><EFBFBD>8~<7E><><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD>+<2B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <0A>*q<>a Ic<49><63> <0A>
,<2C><16><><EFBFBD>#x<><06><>YQP<><50><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>g~<7E>~ <20>:<3A>{<7B>/<2F>g<EFBFBD><67><EFBFBD><EFBFBD>)<29><>N<EFBFBD>y]4<><34>N<18><><EFBFBD><EFBFBD><~<7E><><EFBFBD>,<2C><0F>M<EFBFBD><4D>9<EFBFBD>Q<EFBFBD>W<EFBFBD><57><EFBFBD><EFBFBD>S8C<>K<> 7` <20><><1A>`?<3F><><EFBFBD><EFBFBD>*r<><~<7E>9<EFBFBD>ϫ'<27><>_<EFBFBD><15><><06><>;q,<2C><>TiU<06><><EFBFBD><EFBFBD>C<EFBFBD><43><EFBFBD>bX<62> h<><06>@@<40>T|<7C><00><><EFBFBD><03>k7<><37>RJ) <0A><> s<>H<EFBFBD><48><EFBFBD>)0g-**<2A><><EFBFBD><00>.87bw$7<0F>a(<28>T<EFBFBD>i<00>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29>h<06><>r<EFBFBD><04><>R*<2A><>s4<73>JEX=n<><1A><><><D78F><EFBFBD><EFBFBD>G<EFBFBD><47>R-<2D><̅a><3E><>#<23><><EFBFBD><EFBFBD>W<><57>k<04><><EFBFBD><00>FP<46>|<7C><16><00><>,U<>z<EFBFBD>:|<7C><>p9<70>!<21>m<EFBFBD>S<EFBFBD>'<27><> X<>7q7NBC<42>`LFp0<16>cX<63>|<7C>_<EFBFBD>QgeBU87<>5<EFBFBD>CV<>8;!<16><>p<00>@<40><><EFBFBD>`<60>y<EFBFBD>c<EFBFBD>p)6<>2X<32><58><EFBFBD>Q<EFBFBD><18>.<2E><>ȍ<1A><><EFBFBD>O<>2؂+<2B><1B><><EFBFBD><EFBFBD>0<EFBFBD>{<7B>[<5B><>:,G<>0<EFBFBD>B0<><11>V<>!<21><>\<18><> a<00><>fX^<5E>."<22>><3E>y<EFBFBD>E<EFBFBD><45><1F><><EFBFBD>'c7<63>F=F<> <K<>{ <20>Z <1F><>GМx|^? <0A>Wa<57>{<7B><15><>LF<13>’<EFBFBD><C292>~({J]<03><>q<>?<3F>x<EFBFBD>6<EFBFBD><36><EFBFBD><EFBFBD>—<EFBFBD><01>,AC<41> ` FP<03><1C>-0g&!]=<3D>SX<53><58>Q<EFBFBD><51><EFBFBD><EFBFBD>k<EFBFBD>1V<31>2tE\<5C><><EFBFBD><EFBFBD><EFBFBD>^9><3E>?<3F>9<EFBFBD><39><EFBFBD>,<2C>j5<><35><EFBFBD><EFBFBD>U<EFBFBD> <0C><><X<><58>\<5C> <09><>+U<>)<29><1D>"sE<>̈́9m<39>-<2D><03><>r<EFBFBD><01><17><01><17><>`<60><><EFBFBD><1A><>Sj<04>K<><1E>۟`<60>u<EFBFBD>" <0A><06>;<3B><><1C><01>1<EFBFBD><31>rm/<2F><1F><>5<EFBFBD><35>S<EFBFBD><53><EFBFBD><EFBFBD>J<EFBFBD>4<EFBFBD>۔N<00><00>;s<><73><00>s<>2<EFBFBD>O<EFBFBD><4F><EFBFBD><EFBFBD>O<EFBFBD>œY@<40>:n<>7~͸P<>B<EFBFBD><42>Z<EFBFBD><5A>6<EFBFBD><36>#P<><01><><01><><EFBFBD>h<EFBFBD><68>p߄93<39>O<EFBFBD>œ3<C29C><33><EFBFBD><04>A<EFBFBD><41><EFBFBD>8<1B>b<EFBFBD>",<2C>'<27>D<><06><>$<24><> h<><68><1E><>`Np)̙Z<CC99><5A> ̅R<CC85>L<><0E><>&1<16><>1X+<2B><>xW<03><><EFBFBD><EFBFBD>^<5E><><18><><EC839B><EFBFBD>|<00><>9_*<2A><><EFBFBD>*<2A>ҝ`<60>t3̹<16><><16><>}l<><11><01>p<EFBFBD>u<EFBFBD><75>h<EFBFBD><68>aXs<><<3C><>eG<65>B<EFBFBD><42><EFBFBD><0E><> <0A>t'<27>4-<2D>9<EFBFBD>#<23><0E>F<EFBFBD>XD<58>е <0B>W<EFBFBD>A<EFBFBD>΂9<CE82><39>#r<><12><>><3E>T<><54><12><04>t'<27><>0<EFBFBD>Q<>}<7D><>DUB<03><>5<EFBFBD><35><EFBFBD>8J<38>@<40>^<0F><>9<EFBFBD><39><06>4λQ<CEBB><51> <0A>ҝ`B<1D><><EFBFBD>]/"J<03><><0E><><EFBFBD><EFBFBD>_'<27><><EFBFBD>o’܉<C292>Y\@<40><>{<7B><>G<03><16>!P<>.0g+"H<03><><EFBFBD>0<EFBFBD><30><EFBFBD>2W<16>xW<78>c<EFBFBD><13>5<EFBFBD>
l<EFBFBD><EFBFBD>v<EFBFBD>& <0A>R7<52><37>ku<>zX<>ܥ<><DCA5><EFBFBD>t!<21>_<EFBFBD>4gNo<4E><6F><EFBFBD>W<EFBFBD>C<EFBFBD> ^Ÿ18<31><58><DA94>]<06>'<27><>b<EFBFBD><62>WD<57>0<><30><01><>K<EFBFBD>B+q]pUw-Z<>)<29><>@c<>P<><50>n<EFBFBD><6E>,<2C><11><><EFBFBD>:Q<><01><>u@u3<75>h<EFBFBD> <0A><><EFBFBD>V<EFBFBD><56>pV<70><56>џ<EFBFBD><D19F>A <0A>ҝ`F`<60><>L<EFBFBD>j<EFBFBD>GO<14>j <0C><><EFBFBD><EFBFBD>=<3D>jD<6A>i3<><0E><07>-<2D><08><1D><><EFBFBD>`?<1C><>b&><03><>x<00><>u <0C>*<2A> &u<><75><11><>j E<><45>~ <03><>:<3A><>J1<4A><1A><>’<EB8ABF><C292>B:<3A><3<>?<3F>Jw<4A>ɶ<EFBFBD>x<16><>J2~<1A><><EFBFBD><EFBFBD>2<EFBFBD>x<14>k<EFBFBD>%i<><00>b<04><><EFBFBD>`<60><> .<2E>po<>ҝ`rm:n<><6E><EFBFBD>+<2B>6<EFBFBD><36>_1<1B>(~<1A><>X<EFBFBD><58>a<EFBFBD> <0C><03>W<><11><00>?<3F>!<21>&8E0<45><30>Q<EFBFBD><51>\<5C><><04><><19><><EFBFBD><EFBFBD>w<EFBFBD><77><EFBFBD>?<1C>}D<><44>EI<45><08><>?`m p x<><78><EFBFBD><EFBFBD><EFBFBD>N0J<03>u<EFBFBD><75>(d<><64>! `L<><4C><EFBFBD>`<60>Z<EFBFBD>U<><55><07>R<EFBFBD> V"KZJuş<75><16>CU<43><55>A<EFBFBD><41><EFBFBD>IJ<12><> <0C><>Rݰ;T<><54><1F>RJ<52><4A>1~@<40><>R?(<28><>R<EFBFBD>o<EFBFBD><6F><EFBFBD>RJU<4A><55>i<00>RJi<4A><1C><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><><EFBFBD>z<EFBFBD><7A>-x<16><><EFBFBD>Y<EFBFBD><59><EFBFBD>f<1C>:<3A>2<EFBFBD>><3E>%<25>"{<07><><EFBFBD>Ta p<><70>H܆M<DC86>,mĭ<18><12><><1B><>xG<78>?<3F><><EFBFBD>?^<5E>" B<1C><><EFBFBD><EFBFBD><02><>V\<5C><><>7!gNL><3E>.<2E>D<EFBFBD>R<03>2<EFBFBD>y9<79><39><04><>e<EFBFBD><65><05><>;<3B><>I<EFBFBD>l<EFBFBD>ţi<1E>OaT<00><17>j<00><><EFBFBD>j<><6A>8<EFBFBD><38><EFBFBD><1A>d-<2D><><EFBFBD><EFBFBD>T_|<0F>`I<>a<0F>P<EFBFBD>/<2F><11><00><>gN\?<3F><>p<EFBFBD><70>R<EFBFBD><52><EFBFBD><EFBFBD><EFBFBD>)|w<>rm<16>B=<13>~<7E><>A <0A>@<40>_<EFBFBD>F<EFBFBD><46><EFBFBD><EFBFBD>5<EFBFBD><35>Q<EFBFBD>|<7C>B<12><><EFBFBD><EFBFBD>P<EFBFBD><50>_<EFBFBD>#<23><01><>O<03>ÞNl<0E>^Krq !_<15><>E9<45>@=<3D>4<EFBFBD><34>5<EFBFBD><35><EFBFBD>a7-<2D>a<EFBFBD>*<14>*<2A>p<EFBFBD> <0C>E<EFBFBD><45><EFBFBD>~P<><17>j<00><><EFBFBD><00><>0O3B<33>6<EFBFBD><05><>HՑ8<D591><19><>F%<25><><EFBFBD>H<EFBFBD><00><><EFBFBD><EFBFBD>5<EFBFBD><35>?<3F>| `<60><>?<3F> Q<><51><EFBFBD><EFBFBD><EFBFBD><EFBFBD>T<03><><EFBFBD>0<EFBFBD><30><EFBFBD>?Wd<57>c#̹<08><><0F>9<01><>s<>;i<><69><EFBFBD>Wh<57><06>hY^9<39><17>_<><5F><EFBFBD><EFBFBD>9!=<3D><>Z<EFBFBD>X<EFBFBD><58> "x<><78>2<08><EFBFBD>0<EFBFBD>F<EFBFBD>,<2C><>g{<7B>j<EFBFBD><6A>p<00><><0E><1C>̐pI<70>wr1'<27>ǟ<EFBFBD>2<EFBFBD>JL<4A>W<EFBFBD>@<40><EFBFBD>0<EFBFBD>:<3A>,<2C><>Co<43>9<EFBFBD><39>J3<4A><33><EFBFBD>a<EFBFBD>M<1A> i-<1F>`<04>?o<00>V|<0F>p<EFBFBD><70><EFBFBD><EFBFBD>C<EFBFBD>:<3A>3]ka<6B><61>HYg<>> s<><13><00>s<><73>j<00><1F>@<>z<1E><><EFBFBD><EFBFBD>@]<5D>Њ5I0O<30><4F>;m]"<22>!<21>96<39><01> s><3E>f<>0<><30><1F><><><00>VbjT<6A>? <0A>Ư`<01>`3̙<14>N<>9[4<><1A><>=<3D><><EFBFBD>/<2F>t<>05<>><3E>4<EFBFBD><1A>`F<>N<>`<00>j5<>)<29>N<>`<00>:<3A>{b+,K-<2D>[<03>,<2C>!<21><>t<08><>j<00>{<7B>U<EFBFBD>!<21>y<EFBFBD>,<2C><><18>?<3F>C<EFBFBD><43><EFBFBD><EFBFBD><EFBFBD> <0C>0<>) <0A><06>3<0F><><EFBFBD><EFBFBD><EFBFBD>$<18><><17><76> ^Gw `8#<23>I'<27>|<12><><EFBFBD>n<EFBFBD>9<EFBFBD>E0<45>O<EFBFBD><4F>5<><1A>N><3E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>~<7E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>8<EFBFBD>;<3B>X<EFBFBD>?<3F><> <20><><EFBFBD>B<EFBFBD>~<7E><0F>Q@ `'<1F>c#<23>><3E>ǟ9u ,<2C><>+<2B>$]?<10><>76<37><36><EFBFBD><EFBFBD>p<00><>[1<><31><00>r<00>h<00><EFBFBD><7F>~+<2B>̏<EFBFBD>@<07><17>Ns<4E><73>: `#<23><>M<EFBFBD><4D>
͍_y<EFBFBD><EFBFBD><1B>%<25><19><><EFBFBD>?nF<6E><46>΅E`+<0E>F<><46><EFBFBD><EFBFBD>f<EFBFBD>A><3E><><EFBFBD>ԁ)^N:X<>A<EFBFBD>fإh<D8A5>w
<EFBFBD><EFBFBD><12><1D>=0<><19><1A>؍`+<2B>i<00><>+<2B><EFBFBD>w<EFBFBD><77><EFBFBD>u<1D><><0E><>]K҄b<D284>X<>K<EFBFBD><4B>5<EFBFBD><35>8<1E><01><>/<2F><>~<7E><>r<EFBFBD>B_ <0A><><10><>u<EFBFBD><53>M<EFBFBD>B<EFBFBD>U<EFBFBD>ޡ<><EFBFBD>T|F0<46>o<EFBFBD>4<EFBFBD>z<EFBFBD>E<EFBFBD><45><EFBFBD><EFBFBD><04><>S<03>
,K<>`Bl<10><><EFBFBD>,<2C><00><><EFBFBD><EFBFBD><07>d)B<>g8<19><00><><EFBFBD>[<5B><><EFBFBD>Д<EFBFBD><D094>=
<EFBFBD>=R<<08><>bl<62>L<EFBFBD><4C><EFBFBD><EFBFBD>>Ńow<6F>x<EFBFBD>ෑ9 <0A>@<40>`L<><4C>o<10><>yZ<79><18><><EFBFBD><EFBFBD><EFBFBD><1C> <0B>x<EFBFBD>C<EFBFBD>O<EFBFBD><4F>_,G<>|<14><>I<>? <0A><0E><>Þ<EFBFBD><C39E>;.<2E>X<><58>1ݠ<>5<EFBFBD><35>E!i<00><><EFBFBD>j<04><>ŷ<EFBFBD><C5B7>><3E><07>܄F(UH<55>a[<5B><><5F><C9B2><0E><>ÞQo<1C><1B>4>@<40><><EFBFBD><EFBFBD><EFBFBD>p4z<34>)uV<>"<22><1C><><EFBFBD><EFBFBD>T<>5<EFBFBD> 1<><31>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>1<1B><>Y<EFBFBD><59>Vg<56><67><EFBFBD><EFBFBD>q,<2C><10><>RJ<52><4A><EFBFBD> <0A>`Yڈ[1<1C>J)<29><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><02><>V\<5C><>PJ)<29>R<EFBFBD>+<2B> <20><><EFBFBD>e<EFBFBD><65><05><>;<3B><>I<EFBFBD>l<EFBFBD>ţi<06>) <0C>RJu<4A><75><EFBFBD><EFBFBD>XC+<2B>A<EFBFBD>~<7E><>ь<EFBFBD>p#F#<0E><><EFBFBD>p?a6a<19><03>Fb<05><>܍<EFBFBD>jX<6A><58><EFBFBD>.<2E>"S}<7D>=<3D><>%Y<>=<3D><02><>t<16>><3E><>Q<><51>RǧyF<79><0E>Z<EFBFBD><5A>P<EFBFBD>l<EFBFBD><6C><0E><05><> Z<>k<EFBFBD><6B><EFBFBD><EFBFBD>o,<2C><1C>b<EFBFBD><62>B?<3F><>,H1<48><31><EFBFBD><EFBFBD>mܔ<><DC94><EFBFBD><36>@UP<13>0B<30>_<EFBFBD><5F>J<EFBFBD>O<EFBFBD>'<27><><EFBFBD>p <0C>u V<><<3C><><0F>u8<75><38>r<EFBFBD>g<><67>_<03><>;<3B><><EFBFBD>ŨB<C5A8>U<EFBFBD> <09>phw<68>+K<><4B><EFBFBD><11>@<40>?<3F><>pT<> <0C>9<EFBFBD>eN<65> <0A>,X<>ߠg<DFA0><67> <20><>%<25><><EFBFBD>:m<>B0<><30>Ò\<5C>b<EFBFBD>KrI аsQ<73><51><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <0A>A<EFBFBD><EFBFBD><7F><1F>J³aI<61>C<EFBFBD>Kr2B<32><42>4<EFBFBD>\^™<18>^<5E><16><><EFBFBD>x-<2D><1C><16><>g<15>U<EFBFBD>w8t<06>><3E>I<EFBFBD><49>~<7E>S<EFBFBD><53>V<>6<1C>P<EFBFBD>U<><55><EFBFBD>l+e/<2F>%9<08><>yX<79>sB;<3B>8<EFBFBD><38><EFBFBD> t5<74>U<EFBFBD>ˑlo<><0E><>GG]<5D>j<EFBFBD><6A><><EFBFB3>2<EFBFBD>NnB=B<><42><EFBFBD>,<2C>Z <0C><00>{<7B><>6<EFBFBD>q<1F><>a'<27><>|!tk<74><6B><EFBFBD><EFBFBD><EFBFBD><EFBFBD>'<27><>3<EFBFBD><33><EFBFBD>s.B<>Z<EFBFBD>X<1E>/<2F><><05><>`}+<2B>e<EFBFBD>ܭ<EFBFBD>"<22>I<18><><EFBFBD><EFBFBD><00>u<08>K2<1D><>?,<2C>9<><39>?<3F>tR<74><52><17><00><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>V<><56><EFBFBD><EFBFBD><76>cb8<62>Nx'<27><>?<3F>4<><34><1D><><>װ${#<23><><EFBFBD>%<25><15><>i)^<5E><><EFBFBD>}<7D><><19>[`Σ<><CEA3><06>i<EFBFBD><69>P<EFBFBD>lz<6C>V<11> <0C>$<24><>a%r<>0<><30><EFBFBD><EFBFBD><00>'<27>ٻ<EFBFBD><D9BB><0E>V<EFBFBD>}<7D>M<01><>p<>s<EFBFBD>œ<EFBFBD><C29C>2<EFBFBD><32><EFBFBD><EFBFBD>=2u><3E>y:<3A><18>I2<49><32>J<EFBFBD>o<1A>P<EFBFBD>O<18><10><>+<2B>L<EFBFBD><4C>#o+<2B>3<14><0F><>2<1D>Z K<><1B>܇0<DC87><30>|<07>Y<EFBFBD><59>9r<> <20><18>I2o<32>J<EFBFBD>u `hç e߅<><DF85>=<3D>o=<3D><00>«<EFBFBD>:<3A>N5<4E><11><>aΤB<06>i<EFBFBD>|<7C> US`Ζ<>`p'ɬ<><C9AC><EFBFBD>z <0A>P<03><>`)܇z<DC87>[o<> K<>5D<35>zy<1D><><EFBFBD><>8!<21><01><> <06>(<28><>u<EFBFBD>Y<><01>!PM<>@|w<><77><EFBFBD><EFBFBD><EFBFBD><EFBFBD>o7<6F>8z/.€<>K<><4B>̇@<40>P<EFBFBD><00>(<28>P<EFBFBD><16>J<EFBFBD>5 `<60>t<12>N<EFBFBD><4E><EFBFBD>=<3D>h<EFBFBD><68>Y`Wl<57><6C>1L<31><4C><EFBFBD>`<60><0E>$<24>g`<60>y<11>s<01>yJ'<27><>$ `<60><>2<EFBFBD><32><EFBFBD>=,<2C>h<EFBFBD><68><EFBFBD><14>LP<4C>N<EFBFBD>%y<1A><1A><><EFBFBD>n<EFBFBD>9<EFBFBD>Ep<19>0<>F]Q<><51><EFBFBD>9IF<>><3E>.<2E>%<25> <0B><>;,<2C>OQ<4F>vLq<4C><71>T<EFBFBD><54><19>\h|<7C>7f<37>Jx!|?o<<3C><><EFBFBD><EFBFBD><EFBFBD>;<3B>+ȟO]<08>[<5B><>Vh<11>CX<43> ȵ<>`I.C<08><>K6c<1A>m:<3A><><EFBFBD><EFBFBD><6C>w+<2B> <0B><1C><>1<EFBFBD><31><EFBFBD>m@<40><><EFBFBD>
<EFBFBD>(<28><>Ͱ"<22><01><><01>Ͱ<EFBFBD><CDB0>X<><58>E<18> <20>c]<5D>< 5HW <0A>H1~<7E>b` <20><>\<5C><1D>W<EFBFBD><57>n<><6E><EFBFBD>w<EFBFBD><77><EFBFBD>1<EFBFBD>v<02><><EFBFBD><EFBFBD>]?<3F>@<40>R<>;<1F><>0<EFBFBD><30><01>$sJ<><4A> <0A>ygc z;cp^M<><4D><EFBFBD>P<EFBFBD><50><EFBFBD><EFBFBD>(/@r<>p7z!<21><>p<EFBFBD><70><EFBFBD><EFBFBD>F<EFBFBD>RI<52>QķC<C4B7>J<03>7<EFBFBD> <0A>c<EFBFBD>7<EFBFBD><37><EFBFBD><EFBFBD>W<1F><12><><EFBFBD><08>ӊ<EFBFBD><D38A><EFBFBD><EFBFBD>"<22>~Kri<72>kJ<6B><4A>
<18><1F><>[o<><6F><EFBFBD>Om<><6D>B<> LF<4C><46><0F>R<EFBFBD><52><EFBFBD>_A<5F>N<EFBFBD>)<1E>́<EFBFBD>t<EFBFBD><05><><EFBFBD><EFBFBD>ҡ<08>x <09><>:<3A>(<28><>7Un<55>0<><30><EFBFBD><16><01>;!<21><><EFBFBD><EFBFBD><EFBFBD>:<06>S_0<5F><30>i<>@;=<3D><><EFBFBD><>Zp!<21><>b5,<2C><>_<><5F><07>d)Bu<42><75>O<EFBFBD><4F>\<5C>g<EFBFBD><11><>H׹X<D7B9>-x<07>`Oġp2<70><32>kX<58><EFBC86><EFBFBD><EFBFBD>[`)<29>#S<><53>}<7D>O1~<7E>C<EFBFBD><43>3<EFBFBD><33>R<EFBFBD>;~ Kc[<5B>M<EFBFBD><4D><EFBFBD><00><><15>y2<79>g~J)<29><>@< <0A>@<1F>Y<07>1<0F>dJ)<29><>h<EFBFBD><68><EFBFBD><EFBFBD>4<EFBFBD><34>< Y<0E>܄F<DC84>*<2A><>R<EFBFBD><1A>0 M<><1B><>k<EFBFBD>x7<>h<EFBFBD><68>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><><EFBFBD>
<EFBFBD><EFBFBD><EFBFBD>nNWԢ
J)<29>T<EFBFBD>T<EFBFBD><1E>Cl<>~<7E><><EFBFBD>s<73>u<><75><1A>2<EFBFBD><32>R<EFBFBD><16>Ѐ<18><>1<04><18>4b<34><62><EFBFBD>` @z<><16>H)<29><><EFBFBD>B4` v<>P<EFBFBD><50>1<EFBFBD>c1<63><19><>l<EFBFBD><6C>;C<>3<06>=P<>`SJ)<29>jP<6A><50><EFBFBD> <09>0c<>/&`"&c<>3<EFBFBD><33><EFBFBD><04>w<EFBFBD>b4<62><34><EFBFBD><EFBFBD>u<>A<EFBFBD><41><EFBFBD><EFBFBD>g<EFBFBD><67>RJu<4A>jQ<6A><51><18>Q<18><><EFBFBD><EFBFBD>i83qw<0E>L<EFBFBD><4C>i<EFBFBD><69><EFBFBD><18>Q<18><><EFBFBD><07>@ <0A>R<EFBFBD>!<21><>|\<5C>j<EFBFBD>/U<>z B#<23>`L<>t<EFBFBD><74>7q^<5E>
lqV<EFBFBD>y܊o`&<26>c<EFBFBD><63>cЈA<D088>G<EFBFBD>0<>><3E><><EFBFBD><-<2D>A(r<><72>* `W<><16>,D<0F><><EFBFBD>B<06><11>c?L<> 7j<37><6A><15>AO<>[<5B><>)<29>s<EFBFBD><73>F D<1D>e<><<3C><03>~M0<4D> ~]q<00><><EFBFBD><EFBFBD>э_A<5F><41>7<><01><>'`<60>'<27><1D>^-v<><1C>0]b=<3D>C0<06>a*fb>6<>r<EFBFBD><19>1S<><53><1C>!<21><><1E>2<EFBFBD>J4<4A>/<2F><00>5`%<25>S<EFBFBD>Bi<00>A<05><1C><>ai<61><69><EFBFBD><11><><EFBFBD>h<EFBFBD><1F>RX<52>?<3F>[<5B><11>X7`'<27><>><3E><><EFBFBD><EFBFBD> X<><12> 31<33>}<7D>Q<EFBFBD> <0A>ETn6<><36><EFBFBD>4<EFBFBD><1A>K<>K<1A>x7K`<19><>|o<>r<EFBFBD>
<EFBFBD><EFBFBD><1B>Y/ <0C>0<EFBFBD><30>D<EFBFBD><44><EFBFBD><EFBFBD>+P<02>11<16>0<10>P<EFBFBD><50>$<24><1B>܍9<DC8D>Sg<>H?O<19>1]Ϧ<>X<><58><EFBFBD><EFBFBD><08><1D>X^<5E><>2<EFBFBD>wv<>h<EFBFBD><68>t|<03>aE<61> _<>t<EFBFBD><74>h<EFBFBD><68><06>h3<>4<EFBFBD><34>Z<EFBFBD><5A><01>WG<57><47> <0B><19><>CXl<><11><><18><><18>I<EFBFBD><49><EFBFBD>`E<>fb<12>b(<06><><06>d}+<2B>G<EFBFBD>]<5D>@gE/<13>D#<23>j<00>ۙJK<4A> !5 <0A>`<1D><14><>><3E> d1<64>_@<40><>a0vž<76><C5BE>o<EFBFBD> Vd<56><64><06>a_<61><5F><EFBFBD><EFBFBD> d<0F>ei^<03>s<>=<3D>W<EFBFBD><57>8$<24>|V<>#<23>4<EFBFBD>Ϋh<CEAB>_/\<5C>f6<><36><EFBFBD>Z<EFBFBD>1WY<><59><EFBFBD><0E><>T<EFBFBD>"<22>*<2A><>;<3B><15><>LFU<>v<>L<><4C><EFBFBD>V"<22><>`L<><18><>><3E>*<2A><00>BW4<57>8<EFBFBD>~]1+<2B><01><05>@wh#<23><><EFBFBD>wtGr<47><72>R<EFBFBD>^<5E>5<><35><EFBFBD><1D>wp<77><70>Ȧ1x<15><><EFBFBD><EFBFBD>.<05><>v<18>=13<><<3C>D<EFBFBD><44>LLĞ<18><>P[<5B>*l]<5D><1A> a<05><00><><01><>!<21>&"<22>ex<65>4<06>6!<21>c<EFBFBD><63>`2<>Kx,<2C><EFBFBD>/r<>'<1E><><EFBFBD><10><>+<2B><>c1<19>a<15>DV<44>0L<30>X4<58>_ <20>gr<1F><><EFBFBD>+<2B>,<04>0<><30><EFBFBD><EFBFBD>1ց*<2A>2<EFBFBD><18><><EFBFBD>K<>i<EFBFBD>#<23>z<EFBFBD><7A>0_<04>vC <0C>8L<38><4C><EFBFBD> +<2B><>8S0C<><1F>4<EFBFBD>%iwX<77><58>h<00><1F><><EFBFBD><EFBFBD><EFBFBD>.<2E><03>+<2B>B<EFBFBD>W"<22>P\X<>E0χ<18>B<1A><><EFBFBD>.<2E>J<EFBFBD><4A><EFBFBD>̈<>n<>FZ<46><02>/hCw `l<0E><><EFBFBD>,<2C><><18>XT<58><54><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>h<EFBFBD>~<13><>aHՎ<48>#<23>9 1<<3C>CU<43><55><EFBFBD>hF v<><76>!<21>:y<><79><EFBFBD><EFBFBD>.<2E>I<03>{ݐ<><DD90>)F<> _<><5F><EFBFBD>EwG<77>i_<>y<EFBFBD><79>`<60>><3E>y><3E>H׿a<1D><>N<EFBFBD><4E><00>у<EFBFBD><=<10>,<2C>p2<70>+h@<40>½x <0B>9IJj\<5C>T#<23>4<EFBFBD><34><EFBFBD>< <09><>T<EFBFBD>1<EFBFBD><31>
<EFBFBD><EFBFBD>h<EFBFBD><EFBFBD>_<EFBFBD><EFBFBD>Gtĭ<><12>9<EFBFBD><39> <20><><EFBFBD><EFBFBD>y2<><32><EFBFBD><EFBFBD>t K<03><>Q<EFBFBD> <0C><><EFBFBD>0<EFBFBD>CH׺ Ƿ<>9,<2C>e<EFBFBD><65>/<2F><>Z;Ʌ<>~<0F><><EFBFBD>
<18><>ay:<3A>s<0F>n<EFBFBD><6E><EFBFBD> <09><>7
_B<EFBFBD><EFBFBD>f3<EFBFBD><EFBFBD>}<7D>,,<2C><>#<23><15>#<23>"{(<28>[<5B><><0F>_x0,O<><4F><00>f<EFBFBD>ї<EFBFBD>D
}}<7D><>s<><1B>B<EFBFBD><16><><EFBFBD>#<23>jqfù ]"<22><19>׋|6<>F|5Лa<1F><>2 <0C>I1<1E>]`y<>L<EFBFBD><06><>K`*<2A><>'R<><52><EFBFBD><EFBFBD><11>(<28><>6 <0C><1A>_<EFBFBD>8<EFBFBD><38><EFBFBD>2<EFBFBD>ҏ<><D28F>vH<76><06>vHM<48> n<><6E>Vcs<63><73><EFBFBD>Tk<00><>lTr9<72>Hz<><7A>v<EFBFBD><1F><><EFBFBD>#<23>!<21>&<26>U6<>o<19><10><>"<22>!<21><><19>7<>b{<08><>2,G/<2F><>oUt<55>p"E<>}<7D>+.<2E>e<EFBFBD><65><1E><>!<18><>03q)6<>y<EFBFBD>sfb<66><62><EFBFBD>c0<04><>qi,<2C>8c<11><16>r<EFBFBD>@X<><58><EFBFBD>B_<42><5F>B<06><11>c?L<> |<19>gyvh+<1E><>0S<><53><EFBFBD><1D><18>:T!.M<>g<1A><><X<>~<7E>Tї߉<14><>T<EFBFBD>ՠ<1E>Ј1<D088>13<> ܂<><DC82><02><>x<>}<7D><1B><><EFBFBD><EFBFBD><EFBFBD>><3E>4b<10>Q<EFBFBD><51>4s<C<10><>
<EFBFBD><EFBFBD>W4<EFBFBD>*n'R<><52>S<EFBFBD>T<EFBFBD>z <0C><10><>X<EFBFBD><58>$L<><4C><EFBFBD><EFBFBD><EFBFBD>p<EFBFBD>sf<><66>M<EFBFBD>$<24><>X<EFBFBD><58> D=j<11>{<7B><>|<7C>0q<>X<>&@<40>X<EFBFBD>H<EFBFBD><48>O<EFBFBD>[ <0A><>;aFc,<2C><>L<>dLq&<26>?<3F><><EFBFBD><EFBFBD>X<EFBFBD><58>0<EFBFBD>9<EFBFBD><39>5<>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD> 1<><31>r<EFBFBD><1D>R<EFBFBD><52>U<EFBFBD>h<>@쌡<>c<>'<27>b<EFBFBD>3<EFBFBD><33><EFBFBD><18>w<EFBFBD>bg Dz<>
<EFBFBD>H)<29><><EFBFBD>E/4`cg A#<23>:<3A><18>>6Ѐ^<5E>E,SJ)<29>j<EFBFBD>u<><75><EFBFBD><EFBFBD><0F><>~<7E><><EFBFBD><EFBFBD>=P<03><>R<EFBFBD>b<EFBFBD>B-<2D><><EFBFBD><EFBFBD><15><>B0)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><>RJ)<29><><EFBFBD><EFBFBD><EFBFBD>^81<38><31><EFBFBD>5IEND<4E>B`<60><>PNG

IHDR``<00><>w8<12>IDATx<54><78><EFBFBD>lY<1A><>ISf<53>0\7<>N<><4E><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>S<><53><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>*3<><33><EFBFBD><EFBFBD>ҳd=<3D>d<^;7<><37>_<EFBFBD>%<25><><16><><EFBFBD>lOU<4F><55><EFBFBD><EFBFBD><1C>FC<46>q^} <20>ՈC<D588>y5<79>-x<1E><> <0A>G85—<10> <0C><>M^]<5D><1C>Y<EFBFBD>v<EFBFBD><76>o o<><6F><EFBFBD><EFBFBD>0b<>[<5B>V3<56><33>X8<58>.<2E><>j<EFBFBD><6A> 6<><36>V]<01>1Z^<5E><><EFBFBD>ɏ<EFBFBD><C98F><08>7@<40>kġ<><C4A1>7<00><10>Eo^CZ<0F><>Al<41>-<2D>TTA<54><41>õ<08><12>@lA <09><>Z<EFBFBD>)<29><>j<>o<EFBFBD><6F>^9<><39><EFBFBD>#<23>8<EFBFBD><<3C><14><><EFBFBD>댵؊Lxy]x<><78><EFBFBD>Zu-<2D>A.<2E><>`%<25><><10>a<1A>I<EFBFBD>8<0F>BD<42><44>v<><76><EFBFBD><EFBFBD><EFBFBD>`$<24><>j<>><3E>(<28>!<1E>6
<EFBFBD>ud<><64><EFBFBD><1B> qA<71><1B>لRX<52>w<EFBFBD><77><1C><>{1<10>?<3F><><EFBFBD>DyT]<5D><13><><EFBFBD>5'Q<08><><EFBFBD>@<11><03>c<EFBFBD><63>B<EFBFBD>o<EFBFBD>C5<43><10>H<EFBFBD><48><43>ΰ<EFBFBD>oJ<6F><4A><19>x\ *F<>F<EFBFBD><10><1E>`<05>`<60><00><>/;<3B><04>!<18>Hz<48><7A>lt<6C>
q#<10>>B<>A<><41><01><><EFBFBD><07><17>+oA<6F>&<26>v9<76>CL<>C>\<5C>< <0A>FBpW0<07>{<04><>JT<4A>)<29>4<1D>@<40><>8<EFBFBD><38>wC0V=<03><><EFBFBD><18>V4<>Y<59>de"<22><>b9<00>Wn@<04>@<40><><EFBFBD><EFBFBD>p<16>1<18>(̀Y<CC80>B<EFBFBD>"^<5E>`5Bk<42><6B>h
<EFBFBD><15><<3C>`_<> <09><><EFBFBD>y<EFBFBD>x+m<06><><EFBFBD>8<EFBFBD>
<EFBFBD>6b{<00><><EFBFBD>)<29>'!<21>
<EFBFBD>CP<EFBFBD><04><17><><EFBFBD><EFBFBD>q<12><>=Lpg!<21><0F>p<><70>N <20>uP<>`#DS<03>"<22><><EFBFBD> <09><>{t<>~t<><06>nG<05><><02> q<> <0A><><18><> ؏<>I<><49>>D<><14>0<EFBFBD>/<16><04><>}A<0F><>p}<7D><><04><>/<2F>5<EFBFBD>]M<><4D>|t<19><,<2C><1F>h<EFBFBD>]<5D><><EFBFBD><EFBFBD><EFBFBD>w<EFBFBD>O<EFBFBD>op7<70>!yy<79><79><EFBFBD><EFBFBD><EFBFBD>0<EFBFBD>{Yjj<6A><6A><EFBFBD>ށ<13>Y<EFBFBD><59>AL< '<27>`$^UF"<22><><EFBFBD><EFBFBD><0E><11><EFBFBD><C28F><12>#<23><><EFBFBD><EFBFBD>X<EFBFBD><1A>Rj<52>T<02><>B<0F><>]<5D><><0E>o<>o<EFBFBD><6F>[Ϛ1a<10><><EFBFBD><><7F><EFBFBD><EFBFBD>}<7D>B<EFBFBD><42><EFBFBD><EFBFBD><01><>Za<5A><61><EFBFBD><EFBFBD>1<<3C>]eĕ<10><>?999<39><39>ϫ<05>jPfffn<66>sv<73><76><EFBFBD><0F>X<EFBFBD>a<EFBFBD>א0}<7D>|<00>Cx<43><78><EFBFBD> <09>S<EFBFBD><0E><><01><><EFBFBD>!<21>}x<01>!<21><> <0C><>c<EFBFBD>0 <0C>?<3F><04>8<EFBFBD>Tc<54>:6<08>m`G/<2F>d<EFBFBD>i<EFBFBD><69><1D>v<EFBFBD><76><EFBFBD>p<>V<EFBFBD><56>O0b<>aM<61><4D><EFBFBD> <0C><><EFBFBD><EFBFBD>M<EFBFBD>C<EFBFBD>GW4Q<34><51>@<1D><08><>FA4<41><10>sn<1A>i<16>O<EFBFBD>l<EFBFBD>]mE<6D><16><>7@t<19><>p <0B><><EFBFBD>11_/<2F>ip<><70><EFBFBD><1B>+<2B>s(<28><>gB<67><01><>(<28><>f 2<1F><1A><><EFBFBD>q<EFBFBD>̶<>cX<63><58><EFBFBD>*<2A>rss<1B>7<EFBFBD><37>]<5D>vm<76><6D>-h&r<><72><EFBFBD><EFBFBD>n݂<DD82> <0C><><EFBFBD><EFBFBD><10><> <20><>Sy<> mA<6D><41>Cl<43>{%C<>s՛p~~~<03>_ Q*<02><>T2y<32>q<06>#7}
R<EFBFBD><05>D<EFBFBD><44>^+L<><4C>u<EFBFBD>| U<><55><EFBFBD>ɱJ<0E><06><>B<0F>?<3F>2<EFBFBD><32>*<2A>lA<6C><41>X A%F<><46>2
<EFBFBD><10>@ D<><44>ڨ0,JII<49><49><EFBFBD><EFBFBD><EFBFBD><EFBFBD>h<16><>P<EFBFBD>i ҆<><06><10><0F><>l<EFBFBD><6C><0E>BE<42>1<EFBFBD>M<EFBFBD> I<<3C><><EFBFBD>%΂<>yΕF<18><><05>\<5C><>1ve<76>Y<EFBFBD><59><<3C>,<2C>M^^^lB.L0.<2E><><EFBFBD><EFBFBD>8<EFBFBD><38>.<2E>o<EFBFBD><6F><EFBFBD>v<EFBFBD><76><EFBFBD><EFBFBD><EFBFBD>&vjzǗ]f],H<><48><EFBFBD><EFBFBD>Y<EFBFBD><59>i<11><><EFBFBD><04>՗][<5B><><EFBFBD><EFBFBD>y<EFBFBD><79><EFBFBD>/<2F>=%<25>e_i_<69><5F>)<29>-<2D><><EFBFBD>Rf<52>wY<77>e<EFBFBD>6<EFBFBD>F,<2C> <0A>><16>j<EFBFBD><6A>#<23><>&8<><38>߁<EFBFBD><DF81>'<27>_k<><6B><EFBFBD>VY<><59>G`<60><><06><18><>Q Bm<42><6D><EFBFBD>g<EFBFBD>'<27>ڔ<EFBFBD><DA94><EFBFBD>egԨ<67>7<EFBFBD> <20>Ȓ<EFBFBD>K<><7F>1Èf<C388><66><EFBFBD> ,<2C>q<EFBFBD><71><EFBFBD>3<EFBFBD><33><EFBFBD><EFBFBD>s<EFBFBD><73>as,<2C>4<EFBFBD>ş<EFBFBD><C59F><EFBFBD>R<0E><><EFBFBD>0/7k<37>ޒ><3E><><EFBFBD>A4><3E>^<5E><> /{<7B><07><1F><><EFBFBD><EFBFBD>& t<08>+<2B><><EFBFBD><EFBFBD><EFBFBD>Dy<00>[l<1F><>!<21><><EFBFBD>4<>M<EFBFBD><4D>[<5B><><EFBFBD><EFBFBD><EFBFBD>B<EFBFBD><42><17><>!`<60><>~<7E><><EFBFBD><EFBFBD>U<EFBFBD>}RQ<52>S<EFBFBD>_<EFBFBD><5F><EFBFBD>hn?<3F><><16><04><><EFBFBD><EFBFBD><16>/^<5E>!C8x,Zѭ<12><><EFBFBD>%<1F>6<EFBFBD><36><EFBFBD>J"96<39><36>`<60><>R<EFBFBD><52>Ã<>x<EFBFBD><78>s<49>K-<2D>w{虱<><E899B1><EFBFBD><EFBFBD>X|>j<><6A><56><EFBFBD><E0A8A1>p<06>|<7C><><EFBFBD>u:<3A><01> <09>-/<2F><><EFBFBD>ɖ3V<18>\}u<g<><1D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>X <0C>ϛ{<11><>1@E<>g<EFBFBD><0E><03>iu<69><75><EFBFBD><EFBFBD><03>_<EFBFBD><5F><EFBFBD><7F>T<1C><><EFBFBD><1F><>nPw<50>6<EFBFBD><36><EFBFBD><EFBFBD>ս@<40>,qw"<22><>Op<4F><14><><EFBFBD><04><>(<28><>u<EFBFBD><75>~<7E>Ng<4E><67><EFBFBD><EFBFBD>f<EFBFBD><66>ͩ<EFBFBD>=<3D>s<EFBFBD><73><EFBFBD><EFBFBD>T<EFBFBD><54><EFBFBD>}o&B%r{<1C><>s<EFBFBD><06>xq<78>A6-AXv<58>q<EFBFBD><71>&]<5D><><EFBFBD><1E><>*<12>$<24>~% <09><>!<21><><EFBFBD><EFBFBD><E1BA82><EFBFBD>2ru<72><75>p<><70>=̀~> B
<EFBFBD><EFBFBD>8l<EFBFBD>M<1E>Hm<48>68<36>_<EFBFBD><5F>)<29><1A><>5`<60>*<2A><><1C>ǻ <0A><><09><><19><16> <09><>݈10baM<61><01>A)<29><><EFBFBD><EFBFBD>>C<><43>qn<71><6E>m<EFBFBD>P<EFBFBD>0<EFBFBD> <09><>%<25><>-<2D><>>\<5C>"Ԛ<$P<>KF<4B><46><EFBFBD><EFBFBD><EFBFBD>z.<2E><<3C><>v<EFBFBD>H<EFBFBD>e<EFBFBD><65>Y<EFBFBD><59><EFBFBD>El<45><6C>XNAl<41><6C>E<EFBFBD><06>^<07><><EFBFBD><EFBFBD><06><><EFBFBD>]<5D>V<EFBFBD>-;T<><54>&<26><><EFBFBD>G<EFBFBD>u#] <0A>`s<>.<2E>M<EFBFBD>9<EFBFBD><39><EFBFBD><EFBFBD>S<04><>Zi@<16><>DK<10><><EFBFBD><EFBFBD><EFBFBD>*<2A><>V<EFBFBD><56><1F>$<24>u}<7D>Q<EFBFBD>ӤK<D3A4><4B><EFBFBD><EFBFBD><EFBFBD><EFBFBD>1<EFBFBD>ᆋ&<26><> ܄E<04><><EFBFBD><EFBFBD><EFBFBD>~<7E>U?ޣw<DEA3><77>ѻN<D1BB><4E><EFBFBD>>>X<<3C>j<7F>W<EFBFBD>&-jQ<6A><51><EFBFBD>
<0A> <0B><01>@p<01>ݵkWb<><62><EFBFBD><EFBFBD><EFBFBD>fff<66><01>@p!###V<>PXt<58><74><EFBFBD>sL|<7C>ɕ<EFBFBD>{w<> <0C>נگ<>D<EFBFBD>N:<3A><><EFBFBD>1b<31>:<3A>R<EFBFBD><52><EFBFBD><EFBFBD><EFBFBD>{<7B>G<1E><>aP^<5E><><73>3<33>ܿ<EFBFBD>=].<2E><><07><>P3l<33>yDD<44><44><EFBFBD><EFBFBD><EFBFBD><EFBFBD>pj<70><6A>8<EFBFBD>H(<28><>g<EFBFBD>
G5\<5C><>G<EFBFBD>/Xdƴ#<23><18>^{<7B>U<EFBFBD><55><EFBFBD><EFBFBD><0F><><EFBFBD><EFBFBD><EFBFBD><E1AABA>YI[<5B>T <0C>&<26><><EFBFBD><0E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!m<14><>fP<66>O&ߜ DD<44><44>/@<40><><EFBFBD>w^v<>{<7B>`<60>͢<EFBFBD><CDA2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ąr<>}<7D><><EFBFBD>J<EFBFBD><4A>E<EFBFBD>&^}<7D><><EFBFBD>ҵ<EFBFBD>L<EFBFBD><4C>O#<23><><EFBFBD>n<EFBFBD><6E><EFBFBD>?HֆX<>==,,<2C><1F>`<60>VK<56><4B><EFBFBD><EFBFBD> <09>>ƍ}<7D>ߛ<EFBFBD>%<25><1F>`<60>^OKKK<4B> <09>><3E><>1<EFBFBD><31>Sڿ<53>X4~<7E><>Ir<49>"zkW<6B> <20>l ư]4~̝D<CC9D><44><EFBFBD>v<EFBFBD>Y<EFBFBD><59>CWL4<4C><34>* <09>mǟx<C79F><78>!<21><><EFBFBD><EFBFBD><EFBFBD><0E>y<EFBFBD><79>><3E>ڽ{w<<3C><>~<7E><>666M<><4D><EFBFBD>f<EFBFBD><66><EFBFBD><EFBFBD><EFBFBD>Cx<43><78><EFBFBD>s<EFBFBD>MII<49><49>F<13><><EFBFBD><EFBFBD>><3E> |L<><><DAA5>+~ <0B><>^ <0C>I<EFBFBD>z<>P<EFBFBD>1<EFBFBD><31><EFBFBD><18>a<EFBFBD><61><EFBFBD>|<7C>ӹ<EFBFBD>2<EFBFBD><32>g<EFBFBD>ֱ<EFBFBD><D6B1><EFBFBD>7^<5E><><EFBFBD>[;<3B>v<EFBFBD><76><EFBFBD><EFBFBD><EFBFBD>8}{x><3E><><EFBFBD>C<EFBFBD>ml<6D><6C>c<EFBFBD><63>K<EFBFBD><4B><EFBFBD><10>w<EFBFBD>^&i:<3A><><EFBFBD><EFBFBD>ٳ<EFBFBD><07>8<EFBFBD><05><01>\r<><72><EFBFBD>P555<14><><EFBFBD><EFBFBD>$<24>&<26><17><1B><><EFBFBD><EFBFBD><EFBFBD>U<><55>E9<13>d<><64><EFBFBD>pZ<70>Ϙ<EFBFBD>P8nl<6E>р<EFBFBD>K<EFBFBD>۱<EFBFBD><DBB1><EFBFBD>F+gu<67>v<EFBFBD><76>o<EFBFBD><6F><15><><EFBFBD><EFBFBD><EFBFBD>?H<0E>;<19>P<> XrPx<50>><3E>y4<00>o>(<28>b<1F><L<>/<2F><>a<EFBFBD><0F>Hx<04>z<04>L<EFBFBD>?<3F><><EFBFBD><EFBFBD>@X<><58><EFBFBD><EFBFBD>Ir1<72><31><EFBFBD><EFBFBD>>*f<><66>]<5D>O<EFBFBD>-<2D><00><>3<EFBFBD>N<EFBFBD><4E><EFBFBD>#~ :/<2F> \򋊊8<13><06><>_<EFBFBD>3<EFBFBD><33><00>ʁCF<03>-<1C><><EFBFBD>z<EFBFBD><7A>r<EFBFBD>]h<>]2
<EFBFBD>N<06>&5<1F>Ζ-[hBB<02><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>%؄c1<63><31><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>411<31><EFBFBD><E99794> 0<><30><EFBFBD>k<EFBFBD><6B><EFBFBD>\^ى0-G<>9%<25><><EFBFBD>%<25><><EFBFBD><EFBFBD>Ymdj<64> x<>}j<><6A>ɀ@#@<40><><EFBFBD>0<EFBFBD>\<5C><>+<2B>1.u
<EFBFBD>#hHj#@<40>J%&<1F><><11>q<EFBFBD>S<EFBFBD><53><EFBFBD>c<EFBFBD>չ <0B>X<EFBFBD>;vSʫ<53>Xz4aL9bƘ9<C698> <0B><><EFBFBD>c)a5㋲<35><E38BB2><4<1B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ll<4C>l<EFBFBD>J<EFBFBD>u<EFBFBD><75><EFBFBD><EFBFBD>ݶm<DDB6><6D><EFBFBD>c<1F>\<5C>7<11><><1E><>jR<6A><52><EFBFBD>ql<71>YM<59><4D>:<3A>8<EFBFBD>g}<7D><><EFBFBD>j_8<5F>,YnR<6E><52><EFBFBD>1þ~<7E><EFBFBD><E7B795><EFBFBD><EFBFBD>֖ݘ<D696>EEm<45>L<EFBFBD>/x<>ǑwFV><08>G<><06><><EFBFBD><EFBFBD> <0A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>I<EFBFBD><49>˙ &<26>ܛ0g<30><14>|@<40><>B<EFBFBD><42>\k<><6B><EFBFBD><04><><1A>h=<3D>Ȉ@<40><17>3`<60><>&kB<10><><EFBFBD>Y<15>%<25><>!y<>?<3F>N<EFBFBD>p<EFBFBD>w<15> 8<><38>#<23> <0A>
<EFBFBD><EFBFBD><05><><02><00><><06> <0A><>]<5D>/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>w<EFBFBD>Γ7I<37><49>y<EFBFBD><79><EFBFBD>g~<7E><>&-#r<>q<EFBFBD><71>@<0F><><EFBFBD>"5߂<><DF82><EFBFBD>s홶<73>È<EFBFBD>ZT9<54>ߡ|<7C><>eg><3E>_u<5F><75><04><><EFBFBD><EFBFBD>--<2D><><EFBFBD>s<EFBFBD>.0@q<>`W<>K<EFBFBD> ʄcO<63>ێ:V<><56><EFBFBD><EFBFBD><EFBFBD>7z*f?<3F>><3E>QbK<62><4B>E-<2D>urr̞<72><CC9E>R<EFBFBD><52>l<EFBFBD><6C><EFBFBD><EFBFBD><1B>_ޠ<7F>d<EFBFBD>.<2E><>m<05><11><>Xh<><68>,j`1<>`<60><>=<3D>^$<24>1<1C>HY<48><59>CY<1C>U&<26><><EFBFBD><EFBFBD><EFBFBD>-r/<2F><><EFBFBD><EFBFBD>V<EFBFBD>͗<EFBFBD><CD97><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ML<><4C>Ʋ<><C6B2>]<5D><05>8q<38>>>><3E>&M<>dͧ[W<>:<3A>+<2B>
<EFBFBD>eIec<EFBFBD>1/_<><02><>,<2C>x<EFBFBD><78>-<2D>&<26><><EFBFBD><EFBFBD> 9E<14>O<EFBFBD>dO<64>r<EFBFBD>|Z<>y<EFBFBD>YpN<70>/I<>8<EFBFBD><38><EFBFBD><EFBFBD>w^<5E>40<34>= <0B><>dc,<07><><EFBFBD>;@ P'p̢<70>L^<5E>p<EFBFBD><70><EFBFBD>Pw<50>М-<2D><><EFBFBD><EFBFBD>$<24><><EFBFBD><03><><EFBFBD>{<7B><>$<24><>X<EFBFBD><58>7w<37><77><EFBFBD>:4ɠ<34><EFBFBD>2`<60><>i<EFBFBD>gcxyy<79>B<EFBFBD><16>y<EFBFBD><4C>&<26>A3<33>.<2E><>
<EFBFBD><EFBFBD>P<EFBFBD><EFBFBD>T<><54><16><>0u9<75>П<13><>R<<05><>(<28><><EFBFBD>gM_ya<79>ZZ<5A>JMT8<54><38>~)3 <0A><08>1<EFBFBD>cL<63><4C><EFBFBD>54o<34><6F>e"eg <09><>X""<22>ˁ3I<33>Ud<55>S<16><>g<EFBFBD>
<EFBFBD>Z<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>O~<7E><>n<EFBFBD><6E>o9錤o<E98CA4><6F><EFBFBD><EFBFBD><EFBFBD>@<40><><EFBFBD>%<25>P<EFBFBD><50>7<EFBFBD>ZH,rf<72>Jz<12><>hBF<1A><><EFBFBD>´<EFBFBD>A[<5B><><EFBFBD><EFBFBD>)7<><37><EFBFBD><EFBFBD>*
!<21>}<7D><><==<3D><><EFBFBD><EFBFBD><EFBFBD>&l/2\<5C><>yK<79><0E><05><15><><EFBFBD>><3E><>!9<><39><EFBFBD><EFBFBD><EFBFBD>J<05><1F>N<EFBFBD>v<EFBFBD>.<2E><><EFBFBD>~5Ɗ<35>ɏ<EFBFBD>* <0A>k<EFBFBD>ݺ<EFBFBD>r<EFBFBD>Y<EFBFBD>n<><6E><EFBFBD>m<EFBFBD><6D><EFBFBD><EFBFBD><04>D <0C><><EFBFBD><EFBFBD><EFBFBD>6<EFBFBD>E<EFBFBD><45><EFBFBD>A)2<><32>I<EFBFBD><1B>*+<2B><><EFBFBD>5l<35>j<><6A>o&<26><><EFBFBD> ͮ~<7E><><06>S<EFBFBD><53><EFBFBD><EFBFBD>o~<03><>L @<40>S<13>`[8^*<2A><EFBFBD> <09>܉<><<<:<3A>AD\<5C><>5V<18><16><><EFBFBD>%HN<><4E><EFBFBD>7<37>]"Wl<57><6C><EFBFBD>ŋbHin<05><>j<EFBFBD>m<EFBFBD><1C>Ғ<EFBFBD>e<EFBFBD><65><EFBFBD><EFBFBD>L<EFBFBD><4C>"<22><><EFBFBD>-<2D>+A.x<><78>2e<32>S<EFBFBD><53><EFBFBD>ď<>A<EFBFBD>K<EFBFBD>{@<40><06>*<2A><12>#,A<>q<EFBFBD><71><13><>'7C<37><43>!<1C>c<EFBFBD><19><><EFBFBD>O<EFBFBD><0E>9<EFBFBD><39><EFBFBD>vE͖u<CD96>[<5B><10>+;<3B><><EFBFBD>u+<2B>*x+<13>K<EFBFBD>b<EFBFBD><62>l^GU<47><55>,<2C>8<EFBFBD><38><01><01><>~<01><1D><16><>MX<08>oA <09>]<5D>a$<13><19><><EFBFBD><EFBFBD> df<64>F2<1E><><EFBFBD>HQ<14>،<EFBFBD>~<7E><>c<EFBFBD><63>@C<><43> <0A>jE <20>q<EFBFBD>$~<05>><3E>m<EFBFBD><6D><18>a<EFBFBD>m<EFBFBD>7<EFBFBD><1F>Єa@ <0C><0F><><EFBFBD>w<EFBFBD>#hwh<77>C{<7B><>-lIɱ<49>zx<><78>J<EFBFBD>b+y<><79><EFBFBD><EFBFBD>a<EFBFBD><61>#6x
4<01>\<5C><><EFBFBD>1<EFBFBD><31>ЭYN<59><01>d<EFBFBD>/<08><> L<><4C><EFBFBD><EFBFBD><EFBFBD>D<EFBFBD>e@#<23><><EFBFBD>E<EFBFBD><45>g<EFBFBD>~&<26><><EFBFBD>`<60>0<EFBFBD><30>
<EFBFBD><<3C>4<EFBFBD>$ <13><02><>v<EFBFBD>)Ig$?<3F>><3E>oRE<>HsK<18>Z<EFBFBD>j<EFBFBD><6A><EFBFBD>m<EFBFBD>h}<7D>>Pz<50><7A><EFBFBD><EFBFBD><EFBFBD>n<EFBFBD><03>N<EFBFBD>`?p03,c<><63>_<EFBFBD>:<3A><>%<25><>]<05><>y<EFBFBD>Ί$<24><><EFBFBD>_9sz<0F><><1B><><EFBFBD><EFBFBD>\I|<7C><><EFBFBD><EFBFBD>~<14><>ߏ<EFBFBD><DF8F>R/<2F>w<EFBFBD>.\V<>jiU<69><55><EFBFBD><04><>%<25><>J<EFBFBD><4A>9b{9<>{<7B><>=<3D>^gہ<67>sV<73>t<EFBFBD><74>,߰1Q<15><>Eg<45><67><EFBFBD><EFBFBD><EFBFBD><EFBFBD>K<EFBFBD>p<16>F<EFBFBD><08><>W<EFBFBD><57><07><><EFBFBD><EFBFBD><EFBFBD>=<3D>IEND<4E>B`<60><>PNG

IHDR<00><00>R<>l)<29>IDATx<54><78><EFBFBD><03>k<><6B><EFBFBD><EFBFBD>ll,<2C><><EFBFBD>m<EFBFBD>S<EFBFBD>Gpm<70>6+<2B><><6D>k#<23><>؞<EFBFBD>=S<>U<EFBFBD><55>V<EFBFBD><56>'3<><33>T<EFBFBD><54><EFBFBD> <09><>N<EFBFBD>;<3B>=)M<>4M+<2B><><EFBFBD>?ф#<23><><EFBFBD><EFBFBD>4<EFBFBD><34>XV<58>/ZD<5A><44>b<><05><>N<EFBFBD><07>-<2D>a<NFGhZ<68><1B><18><><EFBFBD>EH<45> <0A>-<2D><><14><><EFBFBD>Ӵ
܂y<10>܈
<EFBFBD>ݦ<EFBFBD><0F>i%"<22>4<EFBFBD> ,<2C>xX<78>}W<1D>;$<24><05><><EFBFBD>E<EFBFBD>xd >ep4<70><34>|HH"R<><52>#VCZ<><5A><10>V<EFBFBD> iJ8M<38><14><>WHH<48> J[B"<22><1F>Ӵr<D3B4><08>ɶ<08><EFBFBD><E19088><EFBFBD>4<EFBFBD>S 1<><13>9<EFBFBD><39>7=M<><4D> &B<12>e<EFBFBD><65><EFBFBD>+!<11>M<><4D>H<>V<EFBFBD>-{<13>˱<><0E><><6F><CD86><EFBFBD>:Z<><5A><1C>#<23>u<00>|<7C>OH<4F>д{<7B><19>%<25>m<EFBFBD>L<14>%HD?<3F> <Ӵ[r<><72><EFBFBD><EFBFBD><EFBFBD>s<EFBFBD><73><EFBFBD><EFBFBD><EFBFBD>c<02>Om<4F><1C>c<EFBFBD><63><02>v4-<2D><><EFBFBD>$F<13><07>:<00><>1<EFBFBD>4<EFBFBD>ա?FD0<18><><EFBFBD>?<3F>DBE!<21>i<EFBFBD><69>݁<EFBFBD> <0A><>E<EFBFBD>iC <0C><>"Ҵ4N<34>$<24><>k<EFBFBD>ɦi<C9A6><69>i<EFBFBD><69>iZ<7F><E4A2AD>v-<2D><><EFBFBD>]S<>f<EFBFBD>/V"<22><>1<13><>>rQ7,<2C>C>5<03><><EFBFBD><EFBFBD><EFBFBD><06>$<24>g\<5C>0<05>H<EFBFBD><48>!>@<40><>?<3F>W<EFBFBD>E<EFBFBD><45>΂ؤ<CE82>D<EFBFBD>1b<><1E><>d<EFBFBD>@,<2C>!<21> j<><0F>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ӊ\NQ^<5E><>xG<>Q눏 .>Gg$Q2<10>I<EFBFBD><49><EFBFBD>EXە`<60>q#<23><>H0<48><30>we><17>#<<3C><><02><>&<26>!<21>.7<EFBFBD>-<2D>OC,"<22><><EFBFBD><EFBFBD><10>mH0<48>RH<00><><EFBFBD><EFBFBD><EFBFBD>x-<2D>#h<><68>J<EFBFBD><0F><>yd<1B>GoǴVC k<>L;<19><><EFBFBD>|m<><6D><EFBFBD><E5B780><EFBFBD>@<02>q<>'<27>f<1F>.<2E>"<22><>.<2E><>ޅ<EFBFBD><DE85><30><C2B3><EFBFBD>ز<EFBFBD><D8B2><EFBFBD>1<EFBFBD><05> ̄DT<44>[<5B>
b<EFBFBD>6<EFBFBD>|.=<3D>p <20><0E>!r<>1<EFBFBD><12>8<EFBFBD>ac7<63>#r<><08><><EFBFBD><08><><10><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>b<EFBFBD>}i<>U<EFBFBD>_ 0<>BlE<>ĐT<C490><54><EFBFBD><EFBFBD><EFBFBD>1<EFBFBD><31>U<EFBFBD>;<EFBFBD>e<EFBFBD>}޺f2:<3A>D<>-<2D>C <0A>*<2A>885<38><35>%<25><><EFBFBD>y>AxJ<>N<EFBFBD><4E><EFBFBD>.P<><50>B0 <0A><><EFBFBD><EFBFBD>p<EFBFBD>Q<EFBFBD>Ϳ<EFBFBD><1F>H<03>6$<24>5(G.<2E>g<;<3B>ǿ{ *2<>f<EFBFBD>ez<><Gl<47><6C><EFBFBD><01><>cu<63>ց<EFBFBD>trу<10><><> <20><><EFBFBD>F<EFBFBD><46>h<EFBFBD>X<EFBFBD><58><EFBFBD>8b<>O8<4F>
S<EFBFBD>W<EFBFBD><EFBFBD>n{dB @;<3B>.P<>~<7E>X>Cؾ<43>X<EFBFBD><58><EFBFBD>x_Y<5F>C<EFBFBD>ǰ|eS<65><53>J<EFBFBD>3H<33><00>B+=<08><><EFBFBD><EFBFBD>1 <0A><>y0I<>3F9<46><18>aX<61>c<EFBFBD>!<21>8@ xo&<26> <0B>A @K{<7B><>d<EFBFBD><64> @<07>˲<EFBFBD>b<18>誻@<40><>b<>5<EFBFBD>Vl<56>\<5C>T@<03><06>s" @<40>;<3B>]<01><><EFBFBD><EFBFBD><02>/<2F>ͣ!<21>B<EFBFBD><42>,<17><00><>`t<><01>d<7F><64>Xe<58>P<EFBFBD>\5X<16> <0A><><EFBFBD><EFBFBD><EFBFBD>-&O<>C<EFBFBD>Է<EFBFBD> <0B><><EFBFBD>'h<><68><EFBFBD>fBpG<70><01>2<EFBFBD><32>:<17><>ă<>xxRw<52><77><EFBFBD>k<EFBFBD>B<EFBFBD><42><EFBFBD><EFBFBD>4<><34>"P<> <0C>_<EFBFBD>Fq63<36><33><EFBFBD> <0A><><EFBFBD><EFBFBD>><00><><EFBFBD> <20>Ex<45><78><EFBFBD><EFBFBD><E6B7A2>?<3F> <09><>|ɟ<<3C>L<><4C><1C><><EFBFBD>Ӑ1<D390><31>6<EFBFBD>SE<53><45><EFBFBD>|<7C><>:<00><><EFBFBD>_!<0E><><EFBFBD><0E><1C>"W]<5D><><EFBFBD><EFBFBD>w@<40><12><1C><EFBFBD><1C> <20>Vt<56><74>9<><00><>]<5D><>C<EFBFBD>^<5E><>:<3A>qo<17><><EFBFBD><EFBFBD>o)<29><>%y <0C><>x<02>:\M<><4D><EFBFBD><EFBFBD>wG$as<61>Z<><5A><EFBFBD><6C><CC87>-rU<1B><1C>%<25><><EFBFBD>+\<5C><06><><EFBFBD>$<0E><>z<EFBFBD><7A><EFBFBD><EFBFBD><1C>Z<>z<EFBFBD>H<EFBFBD><48>)X 1<<3C><><EFBFBD>e<1D>a<EFBFBD><17>o`<60><EFBFBD><7F>f<EFBFBD><66><18>] 6<>+e+!9<>
!bZb3
i<EFBFBD><EFBFBD><EFBFBD><EFBFBD>@~<17>)<29>3<EFBFBD><33>X1<><31>0<EFBFBD>pZ3<07><>@r<> Đ&<26><>t<EFBFBD><74><EFBFBD>&x#<23><><EFBFBD>[F<1D>#q<00><03> FY<46>r<EFBFBD>Tt<0F>i<>p<08>W(<28>R<EFBFBD>~*ă<><C483><06><>w3<77>0<07>c?<3F><>:<3A><><EFBFBD>CE<>4M<34>4<EFBFBD>𪩩<EFBFBD> b?<3F><><EFBFBD>/<2F>q<0F><><EFBFBD>}<7D><><EFBFBD><EFBFBD><><CCA9><EFBFBD><EFBFBD>Z7<1B><>yz~M16<31>@ <0C>~<7E> q<>P^^ޏ<><DE8F>s5<73><35>@<40><>Z7<5A> <09><><EFBFBD><EFBFBD><EFBFBD><0E>x<EFBFBD><78>7<17><><EFBFBD>l<EFBFBD>I<1B>1|<7C>H3<48><33><EFBFBD>=y<><79><18><><EFBFBD><EFBFBD><EFBFBD>yƭcfb"^<5E><18><>~<08>T<>o1
qV<EFBFBD><EFBFBD><02>R<EFBFBD>7<>!<21>(<28>co<63>9<1F><>8 M<>q<EFBFBD><71><EFBFBD>PC<>f@B<><42>]<5D><05><><EFBFBD>Æ<EFBFBD> <0A>B<EFBFBD><42><EFBFBD><EFBFBD><10>_<EFBFBD><5F><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD><63><EFBFBD><EFBFBD>1<EFBFBD>ۏ<EFBFBD><01><><EFBFBD><EFBFBD>4<EFBFBD><01>sFb9<62><39><<3C><><EFBFBD>0<0F>b<19>C<EFBFBD><1B><><1B>'[m<>U<EFBFBD>Q<><51>?q0&<15> <09>!<21><01>ev<><76><EFBFBD><EFBFBD>G'<10>c<EFBFBD><63>1ۣpZ<1B>>uuu<75>|<7C>B<EFBFBD><42><04><><EFBFBD>o<EFBFBD><03>g<EFBFBD>|<00>O~"A)fB\<<06><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>b<1D><><EFBFBD><EFBFBD><EFBFBD>!<0E>w<04>ij<EFBFBD>w8<77>r&6OoS<6F><06><>o<EFBFBD>8<EFBFBD><01><7A<37><41><05><>
Ҍ<EFBFBD>u<00>w}<7D><>q<EFBFBD>!<0E><><EFBFBD>{<7B><><EFBFBD>z]<5D><><EFBFBD>0<13><><^?h<17>:<3A>8<16>!<11><>1h<31> <0A>7<EFBFBD><37><EFBFBD><EFBFBD>|<7C><><EFBFBD><EFBFBD>[<5B>!<21>X<EFBFBD>Z<00><03>}<7D>Xuʾ<75><CABE>
<EFBFBD><EFBFBD><EFBFBD>:v<1F><>Qx<01>0s<><73><EFBFBD><EFBFBD>t<EFBFBD><74>>f<14>Fc<><63>6<EFBFBD><07><12><>r<EFBFBD>U <09>p<1C>g<EFBFBD><67>m<1F><><EFBFBD>x<EFBFBD><78>oB$<24>+l<>E<07>8S<>7c DmK܂e<DC82><<1F><>gE|#<23><>pH<70><01><><EFBFBD><EFBFBD><0F><>=<3D><><07><>Cnx<6E><78><08><>l<>>聴<><07>`K <0C>Yx<14>!<21>|<1D>b<EFBFBD>K<><07><06>|<7C>,<2C><>:F|<7C>tVYK<59><4B><EFBFBD>{bYȀ<59><C880>F<6D>y ?<3F><03><>Ͻ<EFBFBD><CFBD>W<EFBFBD>"<22>j3<6A>O<EFBFBD><4F><0E>< `S<18><00><>X<EFBFBD>Rd[<5B><>hۀ/4<>9N <0A>w<EFBFBD><77><EFBFBD>W<EFBFBD>"<22>j$G<><47>1}>dC_<43>_<EFBFBD>~<7E><><EFBFBD>X<EFBFBD>+<2B><><EFBFBD><EFBFBD> <0A>p<><70>9<><1F>#<23><>cz <0C><>M<EFBFBD>V<><56><EFBFBD> <10><1B><>N<EFBFBD>.<2E><><0E><00>t(<28>.<2E>8\<5C><03>;<3B><>~|<05><>.P<>g<EFBFBD><67>Ȏ<><C88E> <0B> b<>sv(<28>W<EFBFBD><57>@,RYY<59><59><EFBFBD>9<> <0B>b.E<05><><EFBFBD><EFBFBD>X<1C> X<>A<EFBFBD><41>a<EFBFBD><61><EFBFBD><19><0F>l<EFBFBD>O<EFBFBD><4F>HW<48>\<5C><>r<EFBFBD>R<EFBFBD><52>5<EFBFBD>w<EFBFBD>g<10>t<17><><EFBFBD>JpK<><4B><EFBFBD><EFBFBD>0bsu<73>tȵ<>!<21>]<11><>!<21> u܇<>Z<1F>5 7<>)d <20><>|<7C><><EFBFBD>ڥZ<05>,c<><63>x
<EFBFBD>U <20>:<3A>;<3B>m<EFBFBD><6D>m<EFBFBD>p*D<>@<40><><EFBFBD>.<2E><>hB<68>m<EFBFBD><6D><EFBFBD><><7F><EFBFBD>\ _<><5F>5<EFBFBD>@%<25><>S<>`<60><>B\<h<>@<40><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>tz.<2E><>J<1C><02> ;<3B>o;<3B>/<2F><>4<EFBFBD><34><01><><EFBFBD><EFBFBD>#<0E>7<EFBFBD><37><EFBFBD>A<<3C>eR^<5E>*<2A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>עn5<6E>:<3A>v<EFBFBD> f[<5B> <20>E<7F><45><03>+<2B>,e<><65>Ǜz<C79B>v<EFBFBD><76>Oe<4F><EFBFBD><7F><EFBFBD><EFBFBD><02>i<EFBFBD>9<04> ><3E>(<28>h<19><0F><><18>a
+<2B>ʬ<EFBFBD><16><>;<1C>Ő><3E><><EFBFBD><EFBFBD><EFBFBD>2<EFBFBD>U<EFBFBD> m<>ɐ<EFBFBD><C990>c;P<> <0A><><EFBFBD>8<EFBFBD>U<EFBFBD><55><54><C8AA><EFBFBD><EFBFBD>wbć߳<C487>)<29><EFBFBD>]<05><><18>cħ<15><16>P<EFBFBD>e<EFBFBD> ٘fC"<22>ǮHc*b<><62><EFBFBD><EFBFBD><<3C>!<21><><EFBFBD>7h<37>r<EFBFBD><72><EFBFBD>0<EFBFBD><30><EFBFBD><EFBFBD>q<EFBFBD>y9<79>U<EFBFBD>H7Ɗ<37>/D<>y<><79><EFBFBD>Å<EFBFBD>A<EFBFBD>Dzd9<1B>!<21><>_<EFBFBD><5F><EFBFBD>om<6F><6D>\<5C>U<EFBFBD>p <0A>HD<48>8<><38>'6<> ?<3F><>4M<34>4M<34>4M<34><5A>S-"<22><><EFBFBD>T<EFBFBD><54>KR<4B><52>-MսX<D5BD>j<EFBFBD><6A>}<7D><><EFBFBD><EFBFBD>.,=<3D>h<>d/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>6׼X<D7BC><58><EFBFBD>7ʻ<37><07>%<25>Y}<7D>|VW.V<><56><EFBFBD><15><EFBFBD>M<EFBFBD><4D>=/<2F><><EFBFBD><EFBFBD><0E><>WO<1C><><EFBFBD>[~³8=`<60><>2<EFBFBD><32>H,6<>ڗ<EFBFBD>vz䭊<1E>o6Z_<5A>l<EFBFBD><6C><EFBFBD><EFBFBD>a<47>Y<EFBFBD><59>x#y<><79><EFBFBD>s<EFBFBD><EFBFBD>_<EFBFBD><5F>u
<EFBFBD>8 <1E><>\t@Ԧ<><D4A6><EFBFBD>Gz<47><7A><EFBFBD><EFBFBD>תz,<2C>v<EFBFBD> <0A>i<EFBFBD>ݬ <0A>[<5B><0E><>O<EFBFBD>m&oUg^<5E><>~q<><71><1A>1<1F><><EFBFBD><EFBFBD><EFBFBD>IjÚ9<C39A>l<EFBFBD><6C>[<5B>f+<2B><>>/<2F><19><>AO<41> p<><70>T
<EFBFBD><EFBFBD><EFBFBD>_@<02><>JDI<00><>? <0B>Q<EFBFBD><51>Wk<57><6B>x<EFBFBD><78>Of<4F><66><EFBFBD>[vp3<70><33>U>j<><6A>W<EFBFBD><57>|<7C><><EFBFBD>PN<50><4E><EFBFBD><EFBFBD>X<EFBFBD>YwhK[<1B>P<EFBFBD> <09><><07><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>>$<24><>)<29><><EFBFBD>?<3F><01>LIyW<79><57><EFBFBD><EFBFBD><EFBFBD><EFBFBD>_<EFBFBD>@q<0F><1B><>G<EFBFBD><47>X<EFBFBD><58><EFBFBD>ݮ<EFBFBD><DDAE>^<5E><><EFBFBD><EFBFBD>'<1B><><EFBFBD>u<EFBFBD>Ǧ
<EFBFBD>"<22><<1B><><1C>#<03>)<29><><EFBFBD>9<EFBFBD><39><1B>"<22>i<EFBFBD> <09><>_<07><>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD>D<EFBFBD><44> <20>!x<><78>j<EFBFBD><6A><EFBFBD>w`Qk{,<2C><><EFBFBD><EFBFBD>h<EFBFBD><68>džhPQ<50>n JY<4A><08><><EFBFBD><04><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˵<EFBFBD><CBB5><EFBFBD><1D><>Y`<60> <0B> <0A>t<1B>y<EFBFBD><79><EFBFBD><EFBFBD>{<7B><><EFBFBD><EFBFBD><EFBFBD>=<3D>lIv<49><76>}<7D><>a=3s<33>/<2F>;<3B><>73'<27><><EFBFBD>~<7E><><1D>6 k!|JF<13><><EFBFBD>c<EFBFBD><63><EFBFBD>< 5'<27>?edX#p<><06><EFBFBD><E4A9B3>0<> bzwI.<2E><19>K̿<4B>~<7E><>S9t<04><>ӵ.o<>Y"<22>K& @jf6<66><17>,<2C><00>
\<5C>R<EFBFBD>q<EFBFBD>|<7C><><EFBFBD>3<EFBFBD>0E#<23>oO<6F><4F>}q<11>%<25><>{<7B>@<40>w<EFBFBD><77><EFBFBD>T<EFBFBD>h<EFBFBD><68>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><w<> <20><><EFBFBD>c<EFBFBD><63><EFBFBD><EFBFBD><EFBFBD><EFBFBD>D<08><07><>G<EFBFBD><47><EFBFBD>K<EFBFBD>!<21><>~<7E>M<EFBFBD><17>-<2D><33><C59F><EFBFBD> <02><><03><>:o;<3B>Kܗo<DC97>Mx<4D>(|<7C><><EFBFBD><EFBFBD><EFBFBD>[<5B>:<3A>Wl<1C>'<00><><EFBFBD><1E><1D>Y<EFBFBD><1A><14>G<EFBFBD><1C><>["P<> <20><<3C><>-<2D><><EFBFBD>w<15><><EFBFBD><EFBFBD>b<><62><EFBFBD><EFBFBD>,<2C><><EFBFBD> <0C>g<EFBFBD><67><EFBFBD>3<EFBFBD><33><EFBFBD><EFBFBD>;t~8<>f<EFBFBD><66>uܣ?<3F><>}a@e<>v<EFBFBD><76><EFBFBD>o8<6F><38>?<3F>iؘq<D898><71>W<EFBFBD><57><EFBFBD>Lm^<><7F><17><>:<3A><00> `<11>u7L<>#vNC<4E><43><EFBFBD>|3A<33><41><1B><>v`ΰa,<2C>r<EFBFBD><72>q<EFBFBD>}&<18><> <09>F<EFBFBD><46><EFBFBD><7F>x]<5D>G<16>1<EFBFBD>&b <0A><><EFBFBD>b<EFBFBD><62><EFBFBD><7F>+<2B><>\<5C>%!lX<6C>"<22>Y<EFBFBD>xM<78>l<EFBFBD>H<><48>Sd7R@Z<>q<EFBFBD>;<3B><><EFBFBD>wpx<70>0<EFBFBD><30>s<EFBFBD><73>O<EFBFBD><4F>
;{<7B>d7,<2C>*/<2F>3<EFBFBD>cz<63><7A><EFBFBD><EFBFBD><10><><EFBFBD>!<03><>
<EFBFBD>0^<5E><><11>e<EFBFBD>G <09><><EFBFBD>&<1A><><EFBFBD>D(<28><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>4e<34><65>}<7D>`<60><1B><00>Q><3E>!<21><>Vd<56>2<EFBFBD><06>?Rm<52>Hup<75><7Bhn<68>)<29><><EFBFBD><EFBFBD><11><><EFBFBD>m <:"<22>m<EFBFBD>pG<70>:<3A>񈵆@Bv<42><76><<04><> <0C><>o-<2D>ic<69>LTۏb<>&#tpM١<0F><>_<1C>DS<44><53>m<EFBFBD><6D>E<EFBFBD>O|<7C>l<>R!<21><19><><EFBFBD>7<EFBFBD>v<><76><EFBFBD><EFBFBD><EFBFBD> Ɂv<19>@<40>[H<><48><EFBFBD>{e<Ȝ<38>a<EFBFBD>~<7E>wT<77><54>_<EFBFBD><5F><EFBFBD>$\h<><68><03>k<EFBFBD>Q<EFBFBD>h<EFBFBD><68>7ì6
\<5C>G<EFBFBD><11>Ӡ<16>a׀O<D780><4F><00><>+ t<15><>`޽:z<>?<3F><><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD><15><><EFBFBD>#<23>! <0C>G8N<38><4E><EFBFBD>3<EFBFBD><33>셱><14><>L<EFBFBD><4C>;<3B><><EFBFBD><EFBFBD><EFBFBD>h<EFBFBD><68><EFBFBD><EFBFBD>Ʉ=<3D><>o<EFBFBD>Y,V 2<00>ȏ\f<><66><10><><EFBFBD>?<0F><>f<EFBFBD><66><37>G<EFBFBD><47>a<EEA5A6><61>$ <1A><1C><><EFBFBD>?X<><58>&<18>pVk<56> <0C><EFBFBD>d<EFBFBD><64><EFBFBD><EFBFBD><EFBFBD>=&<1D><>l< <0C>6<EFBFBD>a<EFBFBD>L<EFBFBD><1D>ca
\<10><><EFBFBD>O<EFBFBD>@9<>#<23>t<EFBFBD>3[<5B>Zo|<7C><>~<7E><><EFBFBD>9mќؼ<>4<EFBFBD>B<1F>[<5B><>w<EFBFBD>_pn<><6E><EFBFBD>@<40><><EFBFBD>W<19>A*<2A><>&<15>e8<65>X<07>e
5<00>
uz"<22>ŷ<EFBFBD><C5B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>N<><4E><EFBFBD>y<EFBFBD> _p<5F>0<>;Q<><51>םl<17>~<7E>ǡA<C7A1><07><>84<38>BL<42><01><>5<EFBFBD><35><EFBFBD> <09>J~<03>mn<00>˃Y<><59>bg/,
<EFBFBD>d,<2C><>Nse<01><><EFBFBD>B z
<EFBFBD><EFBFBD><><DEB8>c`<60>C+.<2E><>11<31>C@<40>C<EFBFBD>n<08><>ڨ<<3C><>(<28><>a2<61>_7<><37><EFBFBD>fg<>,x<>5\<5C>t<EFBFBD>޸<>_<EFBFBD><5F>:<03><>80<>j`3<><33><EFBFBD>pO<><4F><<02>"<22>/<2F><>|<7C><>ʊ)<29><><EFBFBD>H<EFBFBD>_<EFBFBD><5F>J <0B>Ck<43><C;<13><><EFBFBD>/<2F><>uſ<75><00><><EFBFBD><00><><EFBFBD><17><>(<28><>}<7D><><EFBFBD>w<EFBFBD><77>A<EFBFBD><41>~<7E><><EFBFBD><EFBFBD>#<23><><EFBFBD>S})<29>#?<3F>o~<02> `<01><><EFBFBD>U<10>M$<24>v4OP<1A>+<2B> *<2A><>- [Y쿴<59><ECBFB4><EFBFBD><0F>9N<39><4E><EFBFBD><EFBFBD>˓<EFBFBD><CB93><12>E<EFBFBD>. ;<3B><> H0$0ay<61>7„<37><70><D6AA>g<EFBFBD><67>]2k<32><6B>r<EFBFBD>y<EFBFBD><79>[<5B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʘ<EFBFBD><CA98><15><>h<15>9<EFBFBD>.Ux<55>В<EFBFBD><D092><EFBFBD><15>^<5E>U<EFBFBD><55>e<EFBFBD><65>_<06>`t<><07>|fa l<><6C>ϰ<EFBFBD>$]|<7C>U<EFBFBD><55>P<EFBFBD>Pu<50><75><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>JC"<0E>C"6<><36>F,)<0E>pJ<70>-y<> $H<> A<> $H<>p<EFBFBD>ȑ<EFBFBD>ǎ[<0E><05><><EFBFBD><18><>1<13><><EFBFBD>z<EFBFBD><7A><EFBFBD>/<2F><><EFBFBD>@5<>C5>c<><63><EFBFBD>?<3F><><><01><>ۯ<>~<7E>}<<3C>x<><78><1A><>}T<><54> &Z<><5A><EFBFBD><EFBFBD><EFBFBD>@*<2A><>|<7C><>b"<22><><EFBFBD><EFBFBD><EFBFBD>@*<2A><><EFBFBD><11>~<7E>?<1F>8<EFBFBD><38>G<EFBFBD><14>:<3A><> N<><4E><EFBFBD> Z<>`<11><>2<EFBFBD><1E>7><3E>2<EFBFBD><32>u<EFBFBD><75><EFBFBD><EFBFBD><EFBFBD><EFBFBD>_e<1E><><EFBFBD><EFBFBD><EFBFBD>5{<7B><>s<EFBFBD><73>aof<16>LLo0.<2E><>םR.<2E><1E><><EFBFBD>cD<63>{<7B>F$8<12><><EFBFBD><EFBFBD>`2<><32><EFBFBD><EFBFBD><EFBFBD><EFBFBD>|<00><><04><02>"<22>m<EFBFBD><6D>;<3B><>P*<2A><0F><><EFBFBD>[<5B>T$<24><>|1<02>;<<3C><>D<EFBFBD>'<27><07>F+gͤ7׬ğCBh<42>M/
m3<EFBFBD><EFBFBD><EFBFBD>TW<EFBFBD><EFBFBD><EFBFBD><EFBFBD>;d<><64>ܘQ<DC98>9<EFBFBD><39>5<EFBFBD><35>wQ<77>~<7E>J<EFBFBD><4A>5<EFBFBD><35>q¿<><4C>&e<>i'۸<>Wl<14><><06><><EFBFBD>X<><58><EFBFBD>><3E>,8H<><48>ѣG<D1A3>><3E><><EFBFBD>gD <0B><><EFBFBD>gA<67><41>@j a<><61>KNN~<7E> <20>w|<7C><>L<EFBFBD><17><><<3C>@<40>Q(l<><6C><EFBFBD>e<EFBFBD>]<5D><><EFBFBD><EFBFBD>7<EFBFBD><37><EFBFBD><EFBFBD>1<1F><><EFBFBD>::<3A>K<EFBFBD>b <0B><><EFBFBD>b<17>^<5E>ٴ<EFBFBD><D9B4>$<24><><EFBFBD><EFBFBD><EFBFBD><17><>H,V<>}z<1C>Q<EFBFBD>(`1 6p3<><33>p<EFBFBD> <0B><><04><>G<EFBFBD><47><EFBFBD><EFBFBD>Sl<53>WoW<6F><57><EFBFBD><EFBFBD><EFBFBD>bUp<08><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/;<11><><EFBFBD>^<5E>6<EFBFBD>0k<30>W<1E><>{<7B><>d<EFBFBD>uW<75><57><EFBFBD><EFBFBD><EFBFBD><01><><EFBFBD>e<EFBFBD><65>3<> b~y<><79>)<19>
X<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>D <20><><EFBFBD><EFBFBD><EFBFBD>`<02><><EFBFBD><EFBFBD><EFBFBD>R<EFBFBD><52><EFBFBD>:6T<05><><EFBFBD>MŸC<C29F>И<1D>Nw<4E>Н<08>ςsO<73><16><>Rq<52><71><EFBFBD>9<EFBFBD><39><EFBFBD><EFBFBD>v<EFBFBD>A_<41><5F><EFBFBD><EFBFBD>f<EFBFBD>oe<6F><65><07><><EFBFBD>D<EFBFBD><44>S[<5B>Lb<10>-<2D>EC<45><43><EFBFBD><EFBFBD><EFBFBD>B(<28>+<2B><><EFBFBD>z<><7A>y<EFBFBD><79><EFBFBD>j<> <09>=6<><07><><EFBFBD><EFBFBD><EFBFBD>1?<3F><>^<5E>r<EFBFBD><72><EFBFBD><EFBFBD><EFBFBD>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>b<1B>5<EFBFBD><35><EFBFBD>oL<6F><4C>Y缽P<E7BCBD>&<26>9/OӫS:<3A><><EFBFBD>A<1E>~<7E><EFBFBD>}<7D>u<EFBFBD>8}]<5D>ބ<EFBFBD>~.9<EFBFBD><EFBFBD><EFBFBD>D=<3D>d<EFBFBD>'<27><><EFBFBD><EFBFBD>X<EFBFBD>S<EFBFBD>[<5B><01>6W<><57><EFBFBD>G<EFBFBD><47><EFBFBD>Ф<EFBFBD>$<24><><EFBFBD>2<EFBFBD><03>6\<5C>@ <0C>W<><57><EFBFBD>g<EFBFBD><67>k,c<><63>6\ux<75><78><EFBFBD><EFBFBD><EFBFBD>3}<7D>0<EFBFBD><30>?r=<3D><><EFBFBD>G<47><7F>G^<5E><><EFBFBD>շ<EFBFBD>v~<01><>v<EFBFBD>֚ m<>P۷<>;<3B><03><><EFBFBD><EFBFBD><EFBFBD>
<EFBFBD><EFBFBD><EFBFBD>P<EFBFBD>\q<><01>s<EFBFBD><73><EFBFBD> :<3A>M<EFBFBD><4D>v?<3F>K<EFBFBD><4B>m<EFBFBD>1Eᣏ><3E><>%<25>/<2F><><EFBFBD>޽{<7B>O<11>L<EFBFBD>9<EFBFBD>cٟu<D99F><75><EFBFBD>N<><4E><EFBFBD>'HLL<4C><4C>%lXc<>zM<7A>#?<3F><><EFBFBD><EFBFBD>]F<><46>o<EFBFBD>W<EFBFBD><57>Y<EFBFBD><59><EFBFBD>yZ<79>F<EFBFBD>3/<13><>S<EFBFBD>X<EFBFBD>u<00>F{=<00><10><><EFBFBD>5 <0B><>?<3F><19><>4=<3D>o<EFBFBD><6F> aP`<><7F>}<7D>s'<27><>+<2B><><EFBFBD><EFBFBD><0E><>v=<3D>-<19>;<3B>Y<EFBFBD>%<25><>۷<EFBFBD>C<EFBFBD>q<><71>[<5B><>l۶m<DBB6>f<EFBFBD>p<EFBFBD>
<EFBFBD>b<05>h?<3F><>3<EFBFBD><33><EFBFBD><EFBFBD>s<EFBFBD><73>[<5B>_<5F>5<EFBFBD><35><EFBFBD>Ot@g<><67><EFBFBD><EFBFBD> I<><1F>)<29><><03><>w<EFBFBD><77>a<EFBFBD><61>GΑ<47><CE91><EFBFBD>?c<><EFBFBD>J<EFBFBD><4A><EFBFBD><EFBFBD><03> "<1C><>_<EFBFBD>`B@!<21><>,<2C>
<EFBFBD><EFBFBD><07>/<2F>~<03><><1D><>KE<4B>@<40><><EFBFBD>g<EFBFBD>,~c<>T<EFBFBD> Ċ<1F>:<3A>O<EFBFBD><1D><><EFBFBD>c:<3A>h<EFBFBD>,<2C>q<EFBFBD><71><EFBFBD>an<>'<27><>C <0B>/<2F>|<7C>Z6<5A><36>('<1C><>_<EFBFBD>0<EFBFBD>+O<><4F><EFBFBD>sk{<7B><><EFBFBD><EFBFBD>d_<64>\w<>&x<><78>iJ<69>q<EFBFBD>тd<D182>r <20>gX#<23><05><><EFBFBD>e|<7C>G<EFBFBD><47><EFBFBD><01>Q<EFBFBD><51>L<00>L<EFBFBD><4C>C<EFBFBD>^<5E>3<EFBFBD><33><EFBFBD>0<EFBFBD><30><EFBFBD><EFBFBD> Q<>bL J<><4A><EFBFBD><EFBFBD> h<>0[<05><><EFBFBD><05><1E><>SvG<47><7F>S<EFBFBD><53>])<29>%˵#,<2C>w<EFBFBD>Q<7F>^<4F><DBBD><EFBFBD>d<00><>g3<67>xQ<78><51><EFBFBD>@<40><><EFBFBD><10><>34<><34>Ξ <09><><EFBFBD>l<EFBFBD><6C>?<3F>ή<EFBFBD><CEAE><EFBFBD><EFBFBD>(R<>&Hع<48>1<00><>Lezŏ<7A>><3E>/-#<23><><EFBFBD><EFBFBD><EFBFBD>\"H<>`<60><> 5@<07>ھ<><DABE>D <0B> pH<><1D>%<25><>'Ob<4F><10><>c<EFBFBD><63>@<40><><EFBFBD><EFBFBD>T<EFBFBD><54><EFBFBD><EFBFBD>ҰLu<><75>bo<62>|}<7D>Z<EFBFBD>,<08>=<13><><EFBFBD><EFBFBD><EFBFBD>><3E>/<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Sf<16><><00>ǥ<EFBFBD><C7A5><EFBFBD><EFBFBD><EFBFBD><EFBFBD>hA2@<19><>!թ3aR<61>|T<>1@<19><>!<21><><EFBFBD>?<3F>0<EFBFBD><30>Z<EFBFBD><5A><EFBFBD><EFBFBD>n^_)lw<6C><77>ǴEÄU<>e<EFBFBD> <0C>:<3A>Iˈ<49><CB88><EFBFBD>=&<15><>]'<27><>v<1D><>-H!P<>><3E>r-xug<75>t<EFBFBD><74><03><>/ׂWwvH'u<><75>:fBYc<59>J<EFBFBD>XyS<79><53> yS<79>l6@iN㵌8<><38><EFBFBD>[<5B><>u<1A><>!<21>;D <0B> <0C>\<5C><>!<21><>I<EFBFBD>r<1E> ӳ <09>\<5C><>!<21><>M<EFBFBD>j<16>:<3A><>?9<>ʢ<EFBFBD><CAA2><EFBFBD><EFBFBD>k<EFBFBD><6B>;;<3B>͚<EFBFBD>K)<29><><EFBFBD><EFBFBD><01>s V<><56><00><>N<EFBFBD>(zтd<D182><64>Ĉ<EFBFBD>)e8"<22>C<EFBFBD>F<EFBFBD>kb<6B>ϔ<EFBFBD>2<1C><><EFBFBD>֤<7F>Q<15>!<21><>1?o<>T<EFBFBD><15><>4c<34><63>H<EFBFBD>#<10>sKy<7F>x<>FA<46>u<EFBFBD><75>&<19>\_
5S<35><53><><02><>Bp]|<7C><>E<EFBFBD><45>N<EFBFBD>iEE<45><45><EFBFBD>ʷ\<07>ܼE<DCBC><45>)e<02><><37>2<EFBFBD>p<EFBFBD>w^<5E><77><C3BD>f<EFBFBD><66><EFBFBD>G^;y<><79><12><1C><>d<EFBFBD><64><EFBFBD><EFBFBD>l<EFBFBD>FDD`<60><>7<EFBFBD>eX<07>b<1B><0E>A4<10>z<EFBFBD>-<2D>={<7B>P8"͛<><CD9B>2<EFBFBD><32>u<EFBFBD><75><EFBFBD><EFBFBD>px<A<><41>UZ<55>D;z-=S3<53>ɛ"<22>
m<EFBFBD>Ÿ<><CBA8>S<EFBFBD>B<EFBFBD>wn<77>ה<EFBFBD>"<22><19><><EFBFBD>T<EFBFBD>@<40>h<05><18>m|<03>7<EFBFBD>4<EFBFBD>v<EFBFBD>z<EFBFBD>jAy~<7E><>u<EFBFBD><75>f<EFBFBD>.ǡ<>h<EFBFBD><68>t<EFBFBD><74>݂<EFBFBD><DD82>P<07>b<1B>2A<32>+]<5D>dE><3E>7<EFBFBD>A<><41>,6<>7ϏeX<07>b<1B><>pE><3E>h<EFBFBD><68><EFBFBD> <0B><01><><EFBFBD><EFBFBD>
U<0E>T<EFBFBD><54><00>]s<>S}<7D><><EFBFBD>]<5D>G+<2B>$`<60><><EFBFBD><EFBFBD> <0C><><EFBFBD> 1
<EFBFBD>bpȓdT.<2E>1|<03>8[P<><1F>`]l<>~^5<>m<EFBFBD>>*<2A>qh<68><EF9092><41>;<3B><>a78<37><38>K<EFBFBD>8<EFBFBD>BY<>#<23><1C><05><>s n<>=<3D><>ķ<EFBFBD><12><1A><>n<EFBFBD>) <0C><12><>Mt+L!<21>J$~F<<3C>3<EFBFBD><33>.l<><6C><EFBFBD>ԇ<><D487>^<5E><><EFBFBD><1E>݈x<>.<2E>1<EFBFBD>?<3F><>վS<>K<EFBFBD>c<EFBFBD><63><EFBFBD>ݔs<DD94><73><EFBFBD>mB:}<7D>ש<EFBFBD><D7A9>w;<3B>"<22> <20>R<EFBFBD>n/<2F><><05><><EFBFBD><EFBFBD><14>7<EFBFBD> <0C><17> <0B>Կ<>{<7B>c<EFBFBD>߼<EFBFBD>uaF<><46>.|5-<2D><><EFBFBD>G<EFBFBD>ל<EFBFBD>D 0r *:<3A><><EFBFBD>&`<60>B<12><>l<EFBFBD><6C>7<1F>}<7D><1F>`<60><05>~`<60>h<11>c`<60>l<>Ϣ<EFBFBD><CFA2><EFBFBD>>Z<><5A>c<EFBFBD><63><EFBFBD><EFBFBD><EFBFBD><EFBFBD><17>,<2C>_\W<>x<EFBFBD>a<EFBFBD><61><EFBFBD>ՋW<D58B><57> <1B><><EFBFBD>ND$<24>p<EFBFBD><70><EFBFBD><EFBFBD><EFBFBD><EFBFBD>|T<><54><EFBFBD>&pU<70>.<2E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>T<#<23><>x0<78><04><><EFBFBD>@5lC<6C><43>Kp<4B><70>){<7B><> <09>>A8if><3E>Ռ<04><><EFBFBD>/<2F>abB-<2D>Z<18>4<EFBFBD>,8 F<>5<EFBFBD>C<EFBFBD>ekhYH8-
\<5C><><18>)~<7E><> ^<5E>&;Y<0E>'H<>p<12><>w<1C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/<2F><>{<7B>Y"A<>1<1F>*<2A><><EFBFBD>XZ<16><>V.<2E><> <0A><>Ҧ<EFBFBD>Q<EFBFBD>F<EFBFBD>:$<24><><EFBFBD><EFBFBD>#<23><>a<EFBFBD><61>Y<EFBFBD>j<EFBFBD>><3E><><EFBFBD>><3E>5- <20><>q<EFBFBD>s79<37><39><EFBFBD><EFBFBD><EFBFBD><EFBFBD>>x<><78><00><03><><EFBFBD>M<EFBFBD>8g<38>><3E>3iOHsv<1D>x<EFBFBD><78>и<EFBFBD><07>!$<24>šk<06>7<EFBFBD><37><EFBFBD><EFBFBD>Պ<EFBFBD><D58A><EFBFBD><EFBFBD><EA9290>H<EFBFBD><48><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><16>^5<><35> r9m;<3B>%w<>S2C<32><43><EFBFBD>e3)}<7D><>q<EFBFBD>G_wL<77><4C>stRx<52><78><EFBFBD>{<7B>Hy<48>H<EFBFBD> <20>5@<40> $H<> A<>F<EFBFBD>ɦ<EFBFBD>$<24>O[<5B> <20>,<05><><0F><><EFBFBD><19><>J<EFBFBD>pLZ/<03><01><>j<EFBFBD>-<2D>j<EFBFBD>YS<>lK<6C>і<EFBFBD>kV$<24>#<23><><EFBFBD><10><><18><>t<EFBFBD>l*<2A><><<3C>j<EFBFBD><6A><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Z<EFBFBD><16>C <0B>.<2E><15><><EFBFBD><EFBFBD><EFBFBD>M<EFBFBD>j<EFBFBD>{<7B><><EFBFBD><EFBFBD><19>a<1D><><EFBFBD><EFBFBD><EFBFBD>|<7C><><EFBFBD><EFBFBD>(<03><01>@<40>ݙ<><DD99>@<10>.<2E><08> <09><>}<7D><16>\b&$<24>'.<2E>_<10><><EFBFBD>?<3F><><EFBFBD><EFBFBD>Ľd3im<69><6D>ɺ'z<>eeΚqO<71>ջv<08><><EFBFBD><EFBFBD>hfp <20><><19><>n]<5D><><EFBFBD>0H d:<3A><> F<><46><EFBFBD>w<EFBFBD>2>;Īw<C4AA>3<>W_<57>v<EFBFBD><76>HEs,c<00><><1F>?Rv<52><EFBFBD>ւ_w<5F>d<EFBFBD><64><EFBFBD><EFBFBD><EFBFBD>+@<40><><EFBFBD><EFBFBD><EFBFBD>;<3B>ڔ@<40>$<24><>M<EFBFBD>^2'b"<22>d<EFBFBD>v<EFBFBD><76><EFBFBD><EFBFBD><EFBFBD><EFBFBD>>>><3E>^^^#<23><><EFBFBD>̑{v6j<08>*<2A>(p*<2A>'<27>1$<24>{SvU<76>Mp41(<28><><1A><><10>\<5C>d~ըsۚa<DB9A><61><EFBFBD><EFBFBD>-K<> <0C>v<>րD?/'en<65>H~<05>l <0C>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD>d_Ob^<06><>6)<29><><EFBFBD>޿<EFBFBD><DEBF>h??<3F>a&<14>,1<>
<EFBFBD>|<7C><><EFBFBD>i<EFBFBD>f<EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD>QF<51>a<EFBFBD><61><EFBFBD><<3C>,a<><61>?<3F>9<><1C><12><>,<2C><>O^<5E>r<EFBFBD><72>uI<75><49>n8<6E><38><11> xa<78>z
<EFBFBD>lJ<EFBFBD><EFBFBD><EFBFBD>N \of<6F><66>f<><66><EFBFBD><EFBFBD><EFBFBD><EFBFBD>t<EFBFBD><1D>y <0B><><EFBFBD><EFBFBD><EFBFBD>О<18><><EFBFBD>z<EFBFBD><7A><EFBFBD><EFBFBD><EFBFBD>D</<2F><><EFBFBD>ȄT<C884><54>p<><03>o<03><08><EFBFBD>;7`H<>Ov[<5B><>7e<37>OV<4F><56>U(\<5C><12> <09>N<EFBFBD>>D<>?<18><><08>;<18><> <0A><><EFBFBD>?<07><>A<EFBFBD><41>L<EFBFBD>1T2p<32><70><EFBFBD>GA<07><06><>f<EFBFBD>I3pa<70>9<EFBFBD><39><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>9g<39><67><EFBFBD><EFBFBD>Hb<>H <0A><>̞<02>}<7D><><D9B3>ܻ<EFBFBD><DCBB>RRL<52>Şa<C59E><61><EFBFBD><EFBFBD>3'<27><>ejze߮<65><DFAE><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>@w"߃<>o[`<60>_Dx<00>l<EFBFBD>^=c<> D<da<><10>_<EFBFBD>֍<EFBFBD><1A><><11>y@j <20><>l<EFBFBD><6C>Gf`<60><>t<EFBFBD><74><EFBFBD><EFBFBD>d<><01><>*G<>ԙ<EFBFBD>e<EFBFBD>7<EFBFBD><37>5<><35><EFBFBD><EFBFBD><EFBFBD>6p-F<> <09> <0C> <20><>f<EFBFBD>xwj<77><6A>Z<EFBFBD>,<2C>D<>d<EFBFBD>,8<><06>gB<67>?`V<>*r<>/e<>gAo<00>V=5<>{<7B>L<EFBFBD>F<EFBFBD> <0C><>c -<2D><><EFBFBD>o7<6F><37><EFBFBD><EFBFBD>f<12><>w<EFBFBD>HX<48><58>6<EFBFBD>f<01>G<EFBFBD>ߊ=<3D><13>&<26> ɚ<1F>)켽<>؟<EFBFBD><D89F><EFBFBD><EFBFBD>s<EFBFBD><73><EFBFBD><EFBFBD><1D>7<EFBFBD><37>><3E>we<77>,<2C>6<EFBFBD><EFBFBD><7F><EFBFBD>Ǒ%,<2C>&"m<>0m<30><17><><EFBFBD><EFBFBD><EFBFBD><eB<<3C><>hMH<>K.}<7D>!c<>M<EFBFBD>Y<EFBFBD>$<24><><EFBFBD><00>)<29><>>bMH<4D><1D><>8b<05>h<EFBFBD><68><16>8<EFBFBD>jnp<>?2?<3F>o/<2F>|W<><57><EFBFBD>458H.<2E>; e<><65>P<EFBFBD><50>"<1C>4<EFBFBD>(<28><>1<EFBFBD><31><EFBFBD><EFBFBD>b<1C>3<0F><><EFBFBD><14> <0A><>,<10><>t<EFBFBD><03>Ί<EFBFBD><CE8A>e<03><01>r<EFBFBD><72><04><>\<5C><><02><>z<0F><>:K!`<14>aD<<3C><><07>O<EFBFBD>ipp<70><70>D<18>Y"<22>FLW<><57>D<18>D<EFBFBD><44>r<EFBFBD>֨<EFBFBD>? <09><>y<79>h8ie<69>@<40><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>m<EFBFBD>5{w<><77>r<EFBFBD>b<10><1C><><EFBFBD>}zxe ~<7E><><EFBFBD>|o+͘\*<2A>* <20><>~18<><03><1F>u<EFBFBD>0<EFBFBD><30>D<EFBFBD><EFBFBD>Q<EFBFBD><51><EFBFBD>S㨄<10>1<EFBFBD><01><03><H<1E><><EFBFBD><EFBFBD>[
<EFBFBD>`f<>;V3 d<> i<><69><EFBFBD><1E>T/<2F><>Q{&`<60><>P<EFBFBD><50><1E><><EFBFBD>8<><38><EFBFBD>e<><01>)<29>C<EFBFBD><43>Imf<6D><66>q3<18>qV<71>f" <0C><06>F<EFBFBD><46>g2<67><32>A<06><>@<40>~r<>: <0C>`<60>M!@^<5E><>C<14>}<06><><EFBFBD>'X&<26><00><> ><3E>`  <0F>nL<6E><4C>$"<22>~<7E><>x<>U<EFBFBD><55><EFBFBD><EFBFBD>p<><70><EFBFBD><18><>e_
W<><57>o<EFBFBD><6F>YG<59>p<EFBFBD> <0B>I<EFBFBD>M<EFBFBD>KG<4B><47>yeU;<3B><>
<18>~v؃d<D883> x<>W<EFBFBD><57><EFBFBD>f,<2C><><16>Μ<EFBFBD> [<5B><>Y<EFBFBD><59>d <0C><0E>i<EFBFBD>f0@/v*<2A><> <0A>ǝ/3<>6뎃6<><36>F4<46><34>f"+<2B><>PM<50>4<EFBFBD>$<14>H<EFBFBD><48>|,<2C>w<><77>ʹf<CDB4><0E><>vV{<7B><><EFBFBD>\+<2B><>}<7D><>w6<77><36><EFBFBD><EFBFBD>y<17><>xW3&<26>!<21><0E><1B><><EFBFBD><EFBFBD>G<><47>E0eӄ<65>`jN
<1E><0F>JM1<4D>bx<62><78>6<EFBFBD>Z<06><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>@<40>l<05>@<40>ۋ<EFBFBD>J<EFBFBD>G<EFBFBD>Z)<17>s<EFBFBD>?;l!<21>Y<EFBFBD><59><1D>&<26><><EFBFBD><EFBFBD>u<EFBFBD>4kɂH<C982>bR<>-<2D><1B><18>C=%c<><63><EFBFBD>8D<38>Dr<44> <06><>U7Ғ<37> {<7B>lf<6C><66>4<00>:<3A>n<EFBFBD><6E>F<17><>M<EFBFBD><4D>6<EFBFBD>L9<4C><39><EFBFBD><05><><43> _<X<>2\<5C><><EFBFBD>rQ&P<> <0C><>K<EFBFBD><10><><>7<"PG<50><47>P<EFBFBD><1C>"<22> û<11><><EFBFBD><37>7<EFBFBD>,5 <0B>7<EFBFBD>#<23>H.<2E>C<08>o7<6F><37><EFBFBD><1F><>p<EFBFBD><02><>HW<48>>
<EFBFBD><1D>v<EFBFBD><76>w<EFBFBD>j<EFBFBD><6A>1;<3B><><EFBFBD>d<EFBFBD><64>e<EFBFBD><65>S<EFBFBD> YZu.<2E><><EFBFBD>f<EFBFBD>/U<11><><EFBFBD>x“%<25>+<2B><03><>)<29><><EFBFBD><V<>o<EFBFBD><6F>*\ qb<> <0A><>U<EFBFBD><55>G<> P#2<><1F>o<EFBFBD>G^<5E>!4<>Xe<>1<EFBFBD><1C>s<EFBFBD><73><EFBFBD>u<EFBFBD><75><1B><><EFBFBD><EFBFBD><EFBFBD><02>-{X.+X<><58><EFBFBD><EFBFBD><EFBFBD>qO<><4F><EFBFBD><EFBFBD>'~<7E>O<EFBFBD>?|><3E>$<24>a<1D><>m<EFBFBD>/<2F><><13>9+<2B>\ <=D]<00>:<3A>fXńA<C584><06><><EFBFBD>%<25>߀<EFBFBD>f8 <0C>j<EFBFBD>g<EFBFBD><67>ѿ<EFBFBD>V,<2C><><EFBFBD>S<EFBFBD><05>0 (W<>g<EFBFBD>߾<EFBFBD>><3E>րxO<78>{<7B>?<3F>X۰<>Wlۀ<6C>O5<4F><35>0n<30><01>2G%<25><03><><1C><>B<EFBFBD><42><EFBFBD><EFBFBD><EFBFBD>&hL7<4C>q<EFBFBD><14><>R qzh%<25><><EFBFBD>K<EFBFBD>Y<EFBFBD><08>d<EFBFBD><64>X<EFBFBD>97bE<62><45><1D>P<EFBFBD>&a%<25>+7by<62>2"<22>1?<3F>Y<EFBFBD><59>?M<00><>n<EFBFBD><6E><EFBFBD>+<2B>(.<16><>/<2F>X<EFBFBD><01>J<EFBFBD>@<40>aR<61>7<EFBFBD>cx<63>|<7C><><EFBFBD><EFBFBD><EFBFBD>D<EFBFBD>f<EFBFBD>~2[<5B><><EFBFBD>Y@q<>t<EFBFBD><74>P(r<>c^<5E><>ۗwo4<12><><EFBFBD><EFBFBD>5+G<><47><18><><EFBFBD>Ѓ<08>h<EFBFBD><1A><><16><><02>Dn<05><>q%Ҟ<18>#<23>><3E><04><><EFBFBD>U~<7E>}<7D>E<EFBFBD>N<EFBFBD>n<EFBFBD>}<02>8F,J<><4A><EFBFBD>yk#<23><><EFBFBD><EFBFBD>@<1D>3u f<>Ķ <20><>y<><13><><EFBFBD>&<26><10><><EFBFBD>14h<08><1A><03> <0B><><EFBFBD>8<EFBFBD><38><EFBFBD>”]<5D>hS<68>'~<7E>)T<><54><EFBFBD><EFBFBD><00><>=}+<2B><>@<40>>$<24><><EFBFBD><EFBFBD>9ryW<79><2<>p<EFBFBD><70>V<EFBFBD>lPw`<60>B<><42><EFBFBD><16>y<EFBFBD><79><EFBFBD><<3C><>3<EFBFBD>^t<01>1<02>M<><4D>;<3B>F`<60><>~<7E><45><DD8B>'E<>x/|Ch<43><68>65<36><35><1A>T<EFBFBD><11><>g<EFBFBD>Ǥ<EFBFBD>R 7{<7B>#W.wϋ<77>,-<2D>E<><45>Nn<4E><6E><EFBFBD><EFBFBD><EFBFBD>=<3D>B<EFBFBD><42><EFBFBD>=V<>}<7D><><EFBFBD><EFBFBD> 먢"<22>*<2A>ܕ<EFBFBD>V<EFBFBD>a,7<>Z<EFBFBD><5A>K<EFBFBD><4B><EFBFBD><EFBFBD>L<><4C>oSG4<12><><EFBFBD><EFBFBD><EFBFBD>7<EFBFBD><37>/<2F> lj5B<35><6E><DDA0>r<EFBFBD>j<EFBFBD>\<5C>Z'W<><57>f$<24>[<5B><>>jm<6A>F<EFBFBD>@<40>z1(*C43T3<54><33><12><>3<EFBFBD> <0B> <0E><>gFtm<74><6D><EFBFBD>%<25><06>V#<15>`<60>QR<00><>{'w<>'<27><>
$H<> <20><><19><>;<EFBFBD>yIEND<4E>B`<60><>PNG

IHDR6<00>q<EFBFBD>v<02>IDATx^<5E><><EFBFBD>K<EFBFBD>`<18><>#6<>Rӊ#%<25><><EFBFBD>`<60><>2<EFBFBD><32>ZRI<52>5 <0B>;<3B> <16>C=xY <07>q<EFBFBD><71><EFBFBD>DAţ2vЊ؁<D08A>X<EFBFBD>-|<7C><>wO4MC<4D><43><><CA97><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><o<><6F>-ꆶ<><EA86B6>s<EFBFBD><73><EFBFBD>e<EFBFBD><65>~D<><02><>)+iq|<7C>F<1C><>RV\<5C>g^Ln<4C>G<06><><02><1B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><10>_B<0E><>V<EFBFBD>`<60><>8<EFBFBD><38><EFBFBD><EFBFBD><13><>Ӑ0<D390>f!ӧ6FQ<46>M<EFBFBD> j<><6A>*4<>iF<69><46><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1C><>K<EFBFBD>CP<>zvx<76><78><1E><>)(^<5E><>Bi0<69><30>=<16><>H<EFBFBD>d<EFBFBD>p<EFBFBD><70><EFBFBD>Ǎ<<3C><><EFBFBD>Ūl<C5AA><6C>hU<68><55> С<>E<17><10><>eT.Qµ <20><>
<EFBFBD><EFBFBD><EFBFBD>b7<62><37>%<25><><EFBFBD><EFBFBD>;<11>><3E>,<2C>܅<EFBFBD><DC85>L;O<><4F>P !<21>{<7B><06><>8<EFBFBD><38><EFBFBD>)kЏ<6B>UQȽ<51><2<><32><EFBFBD>3<EFBFBD><ŷ?w<><77><EFBFBD>v<EFBFBD><76>~g<><67>M<EFBFBD><4D>Ӄ<EFBFBD>k9<6B><1B>
J(<28><>!a<><61>:<3A>j<12>@<40>DN׿<4E><1C><EFBFBD><E4B894><EFBFBD><EFBFBD><EFBFBD><EFBFBD>o-<2D>5_<35>=XcYs潇<73>*Cs<1A>G9<47><39>^n<>w<EFBFBD><77><EFBFBD>a3XR<58><52>ګ<EFBFBD>{<7B><>c5ٯ<35>v<EFBFBD>
l'<18><><EFBFBD>C<EFBFBD><18><><EFBFBD>,c<16>_C<5F>k&h<>|I<><PQ<50><51><EFBFBD>v<EFBFBD><12>J<EFBFBD>m<><6D>*6<0F>(R<><52>]<5D>8=<3D><><EFBFBD><EFBFBD><EFBFBD>Y-#<15>[*ʘtK<74>G<EFBFBD><47>|<7C>=IN<15>-V <0C><>7w<37>F1P<31><50>tee<07>#<17><>X<EFBFBD>`a\<0E><>$<24><> <0B>B<12>Zs(@BiZ
<EFBFBD><EFBFBD>V<EFBFBD> >,<2C>3<EFBFBD><33><EFBFBD>A <0C>G<EFBFBD>U<m<><6D>B<EFBFBD>Z
L<EFBFBD><EFBFBD><EFBFBD>q^<5E><><1D>57<35><37><EFBFBD><EFBFBD><EFBFBD><EFBFBD>i<EFBFBD><69><EFBFBD>=<3D><>g<EFBFBD><67>٧<EFBFBD>n<>/<2F>^<5E>){I+j<><6A><EFBFBD>_m<5F><6D>{a<><61>IEND<4E>B`<60><>PNG

IHDRl$<00>dG<05>IDATx^<5E><>OoG<18><><05><>zcBl<42>q<EFBFBD>PH@<40>
<09> 5$<24>1<EFBFBD><31><EFBFBD>lR"UJ<55>T<EFBFBD>!<21>j<EFBFBD><6A><EFBFBD>jUT<55>Ym8<6D>ҤPN<50>9pSE\<5C><><EFBFBD>JI#Q+<0E>ՄZϡ<5A>Z<EFBFBD>/<2F>}45Y<35>kgY<67>B<>e4;<3B><><EFBFBD><EFBFBD><EFBFBD>y=<3D>~M{I<>
<EFBFBD>Ő<EFBFBD>x<01><>N).%<25>4<EFBFBD>`<60><><EFBFBD>©:<3A><>`<60>_JJ9iI<69><49>*N<><1C><1C><><EFBFBD>+%<25>9<17><><EFBFBD>딇%<17>9z<>V<EFBFBD>Z<EFBFBD><5A>q<EFBFBD><71><14>騝w<E9A89D>o<>FV<46>`<60>j=]<1A>F<EFBFBD><46><EFBFBD>2<EFBFBD>3^<5E>s<EFBFBD><11><08><10>R<EFBFBD>Xje <0A>r<EFBFBD><72><EFBFBD>1<؍s)ml{0b<30><62><EFBFBD>Ўnta?:<3A><><01><><EFBFBD>ӥ<EFBFBD>nM<6E><4D>gMr<4D>i7v<37><76>q<EFBFBD>A<14>T<EFBFBD><54>0k<30><6B><EFBFBD> 9<>V<EFBFBD><56>s<EFBFBD>d<EFBFBD>f<>jA'<27>`1<><31><EFBFBD><EFBFBD>i<EFBFBD><69><07>7s<37>.Ct<43>D<EFBFBD> Zy>@<40>(P<>4<EFBFBD><34><10><><EFBFBD>c<EFBFBD>K<EFBFBD><4B><EFBFBD><EFBFBD><EFBFBD>f<><>8K<38><4B><EFBFBD><EFBFBD>m<><6D><EFBFBD><0E>OC<4F><43>0<1D>Z@s<><73>q<EFBFBD><71><EFBFBD><04><><EFBFBD>͇+<2B>O<y<><79>|<7C><><EFBFBD>&<26><10><><0E>%^˧J<CBA7>̰<EFBFBD>۫ڂ<DBAB><DA82><EFBFBD><EFBFBD>x<EFBFBD><07>2<EFBFBD>+<2B>̶1 B<>h!<21>J<>Y-(<18><><EFBFBD><EFBFBD>R `&XwhIu<49>ʋ]wV<77><56><EFBFBD>_<><08><05><><1B>?<3F><18><>!-<2D><>P<01><><EFBFBD><EFBFBD><EFBFBD>F<EFBFBD>aj<61>"<22>9w<>ME<4D><45><EFBFBD><EFBFBD><01><><08>V<><18> N$<24> ̕<><CC95>e<1B>{<7B>z<EFBFBD><7A>\7}#<23>j-<2D>-<<3C><1F>P<EFBFBD><05>6لN<D984>ċ5<C48B><35><EFBFBD>6<EFBFBD>b<1C> <09>*h<>m<11><><EFBFBD>M<EFBFBD><4D> X<><58><EFBFBD>A<EFBFBD><41><EFBFBD>*T<15>X>F?<3F>E<EFBFBD>E '<27><>2<>j<EFBFBD>I<EFBFBD>pRAe<41><65><EFBFBD><EFBFBD><1C><><EFBFBD>@<40><>h><3E>&+<2B>5<EFBFBD>E.ķY1<59><06><>n<EFBFBD>Xm‡C<C287>B<EFBFBD>z<EFBFBD>g<10>>4<><34><EFBFBD>|<7C><><EFBFBD>U<EFBFBD><55><EFBFBD>W<EFBFBD>}3݂8<DD82><38><EFBFBD>"<22><11><>0<EFBFBD><30><EFBFBD><EFBFBD>@<40>s,-ks<6B><73><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E39FA4>^/<2F>L<EFBFBD><4C><EFBFBD><01>!<21>c <09><1F>><3E><>*<2A><>h3<>>Ϭ U<>QL<51>#eho<68>n۟<> 1<>Nj"T<>"<22>B%<19><02>0<EFBFBD>H,<2C>]<5D>D<><44><07><>g<EFBFBD><15><><EFBFBD>}<7D><>M<EFBFBD><4D>ݞ<EFBFBD>
<EFBFBD>^l,j<>
X5<04><>@X0<11><>Z2<5A>b<EFBFBD>}<7D><><EFBFBD><EFBFBD>Y<EFBFBD><59><EFBFBD>S<EFBFBD>b<EFBFBD><62><EFBFBD>e<EFBFBD><03><><EFBFBD><EFBFBD><EFBFBD>'<27>ӲVg<56><67><EFBFBD>կ<EFBFBD><D5AF>f<EFBFBD>E]^<5E><>A <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>hjуF<><46><EFBFBD>`<60><><EFBFBD><EFBFBD><EFBFBD>I<EFBFBD><49><EFBFBD><EFBFBD>Pw<50><77>M5Ub8<62>}<7D><>"ݗbQƥ<51><16><>!<21>"<22><><EFBFBD>e~<1D><0E>a 4 <17>}<04>VM<56>jJ<6A><4A>vh<76>V#<23>t?<3F>c<EFBFBD><63>1<EFBFBD>t<EFBFBD>`<60><>SW<53><57>r<EFBFBD>]؉:<3A>3<EFBFBD><33><EFBFBD>?<13>MO<4D><4F>Ӧ<>U<EFBFBD>&7<><37>+cQ<63>_<14><18><><EFBFBD><EFBFBD>V<EFBFBD>S<EFBFBD><53>s<EFBFBD><73><EFBFBD>^4`;0<><30>-<2D>!<21>@<40>@<40>F<EFBFBD>R{0<><30><EFBFBD><EFBFBD>:t<><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD>G뢳"<22><>[?<3F><0F><11>o<EFBFBD>Pz<50><7A><EFBFBD>H<EFBFBD><48><EFBFBD><02>=<3D>Y}!<1B><> Dc<44><63><EFBFBD><r<>,u<07>V7[<5B><>"<22><13><11>-l +l<1D><><EFBFBD><EFBFBD>[cA<><41>!/I<>L<0E>S<1A><><EFBFBD><EFBFBD><>g<EFBFBD><67><EFBFBD>J034qb<71><62>m<07>3<EFBFBD>s<EFBFBD>U,
1
<EFBFBD>><3E>w<EFBFBD>G<EFBFBD><47>6%S.<2E><1A>gm <0C><>n+3ASi<1B>{y;Ͷt<CDB6>.<2E>5,<2C><>S<EFBFBD><53><EFBFBD>%<25><><EFBFBD>pm<>E<EFBFBD><45>t<EFBFBD>51<35>x>/<1C> <0A><><04><>bn<62>Χ<EFBFBD><CEA7><EFBFBD>(<14>X<14><>^ˊO<02><><EFBFBD>S[<5B> <0C>qo<71><6F>&`:ڕ<><DA95><EFBFBD><EFBFBD><EFBFBD>l<EFBFBD>0#<16>ͽ<EFBFBD><CDBD><EFBFBD>•u X:<3A>4Sk<53>C<EFBFBD><08><5A><C3A2>6:<3A>Η<EFBFBD>h<EFBFBD><68><EFBFBD><EFBFBD><EFBFBD><05>E<EFBFBD>11,<2C>,_Ϧ<5F>.<2E>/<2F>Sk׳+<2B>E<EFBFBD>L<EFBFBD>ӿ<EFBFBD>|M<><4D><EFBFBD><EFBFBD>lOct<63><74>'<15><>㱋peʰ<65><CAB0>e<EFBFBD><65>%<25><>e<><65>d)<29><><EFBFBD><EFBFBD>@<40><><EFBFBD>FpI<70>z<EFBFBD><7A>XIEND<4E>B`<60><>PNG

IHDR"":G <0B>bKGD<00><00><00><><EFBFBD><EFBFBD><EFBFBD> pHYs  <01><>~<7E>tIME<07>
x{=IDATXõ<58>k<EFBFBD>UW<15>k<7F>s<EFBFBD>f<><66>08ֶ &<26>|<7C><><EFBFBD>CA +
<16><><EFBFBD><EFBFBD>ZT 6Ŗ<36><C596><EFBFBD>a<EFBFBD>V)<29><><EFBFBD>J<EFBFBD><4A><EFBFBD>h<EFBFBD>1<EFBFBD><31>XR<>cIkSӤ<53><D3A4>(3<14>qߏs<DF8F><73><EFBFBD>w<><77>pf\<5C>;9ɽg<C9BD><67><EFBFBD><EFBFBD><EFBFBD>Y<EFBFBD>
<13>]<5D><>X<EFBFBD>h <0B>z<EFBFBD><7A>r<EFBFBD><72>*Q<><51>I<EFBFBD>y<EFBFBD>k<><6B>5<EFBFBD><35><EFBFBD>ί<16><><EFBFBD>f6.<2E><!<21><>e<EFBFBD><65>#<1B><0F><><1F>ֿ<EFBFBD>&୧P<E0ADA7>P <0A>:k<><6B> <0A>V<ph<70>>'<04><><EFBFBD><EFBFBD>kJ<6B><4A><EFBFBD>ը<EFBFBD><D5A8>;<3B>8<EFBFBD>Y<07>jB<6A><12><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><74><D397><EFBFBD><EFBFBD><EFBFBD>K<EFBFBD><4B><17><><EFBFBD><EFBFBD>7<02><><EFBFBD>Ǜ<EFBFBD>{f͞<66>r<EFBFBD>˕<EFBFBD><CB95><>o<EFBFBD>0<EFBFBD><18>YG<59><47>[9<>?<3F>ʝO<CA9D><4F><EFBFBD><EFBFBD>מ<EFBFBD><06><><EFBFBD><EFBFBD>'<06><>/<2F>|<7C><>w0<18>0<EFBFBD>x<EFBFBD>++z<><7A>Tm<54>sλ+<2B><><EFBFBD>=<3D>T<EFBFBD><54><EFBFBD><EFBFBD>#v<><76>U<><55><EFBFBD><EFBFBD><13><1F><><EFBFBD><EFBFBD><01><><EFBFBD><EFBFBD>x<EFBFBD><78>_]zh<7A><68><EFBFBD><EFBFBD><EFBFBD>B<EFBFBD><42><EFBFBD>Zw<5A>:Eŀ3<18><><13>g=<3D>A<EFBFBD><12><>E<EFBFBD>`DP5A<><41><EFBFBD>ͳ<EFBFBD><CDB3><D6BD><1C><><EFBFBD>o<EFBFBD><6F><EFBFBD>w<EFBFBD><77><EFBFBD>=<3D><><EFBFBD>g<EFBFBD><67><EFBFBD><EFBFBD><EFBFBD>R\X*<04> <08>"<12>Ӌ<EFBFBD>Xk)<29>"<22><11> 5<><35>R<1B><>6<EFBFBD><36>><3E><>ko<6B>/<2F><><EFBFBD><1F><><EFBFBD> <0B>nQd!8<>H<EFBFBD><48> <07>b<1F><>><3E><>7<EFBFBD><06>4E<34>uDQBl-<2D><08><><EFBFBD>Q! S<>0vnYqo<71><6F><EFBFBD><EFBFBD><EFBFBD><06><><10>k<EFBFBD>sf><3E><> UE<><45>^j ^j<>^E<>vy<76><79><EFBFBD>y<EFBFBD> "P<> <02><><EFBFBD>K[<5B>,~<7E><>o<16><><EFBFBD><EFBFBD>=<3D><>5<EFBFBD><35><05><>Q&m<15>wx<77><78><EFBFBD>Y<EFBFBD><59><EFBFBD><EFBFBD><1C>K%2<><32><>T8<54>$<10>t<EFBFBD><14><13><><EFBFBD>-<2D>;<3B><>8<ށ<><0E>srhpT<70><54> T0<54>P<EFBFBD>k<EFBFBD><6B>)j<>"57<><10><>"<22><>B-lcAT<41><54><EFBFBD><EFBFBD>e<03>ʜ<EFBFBD>X7<58><37>s<EFBFBD><73><EFBFBD><EFBFBD><EFBFBD>B1<04><1A>1<EFBFBD><31><EFBFBD><EFBFBD>TRS<07><1D>Ֆ<EFBFBD><D596>L<EFBFBD><4C><EFBFBD>'<27><><EFBFBD><14>U<><55><EFBFBD><EFBFBD>"SSI<53><49><EFBFBD><EFBFBD><EFBFBD>|<16><><EFBFBD>rNe<4E>
<EFBFBD><EFBFBD>`T<>@<40><>!.<2E>)R<>SMb<06>y<EFBFBD><79>o<EFBFBD>,<2C>|QЀZ<D080><11><>P<EFBFBD><50>eW<65>X+E<15><>2<EFBFBD>!F Jm<4A>: <20>"<22>2<EFBFBD><11>&<26><>eN-cT<63><54>R*(<28>jP?4<>ǛZ VU2<55><<3C>j<EFBFBD><EFBFBD>-<2D><>0i<0F>OOh<4F>PS?G"b<>ПBU(c<06>*S<>n=T<>#`<14><>q<>A"<22><>3C<33>9
<EFBFBD><EFBFBD><EFBFBD>k^<5E><>ab<61><62>#<23><>:}Ċū'r1<72>bi<62><69><EFBFBD>l<EFBFBD>l.<2E><>r<EFBFBD>V<EFBFBD> 0j<30><6A>$XM8vj?<3F><>F<EFBFBD><46><EFBFBD>z<06><><EFBFBD>r<EFBFBD><72>a<EFBFBD>Q<EFBFBD>+<2B>ak,H<><03><<3C>jR<6A><52><EFBFBD>:<3A><><EFBFBD><EFBFBD>ˑs<CB91><73>T<EFBFBD>z}<7D>`<60>d<EFBFBD>+<17><><EFBFBD>@<1E><><EFBFBD><15>=<3D><1C>r<EFBFBD>Ȑ><3E>/<2F>I5J<35>O<EFBFBD><4F>H9ON<11>b<EFBFBD>?<3F>yێ6:o^<5E><>xEW:L<><4C>8<EFBFBD><38>"<1C><1F>T<EFBFBD>.?U<<3C><>T<EFBFBD><54><EFBFBD><EFBFBD><EFBFBD><EFBFBD>U]<5D><>tȇ<>|<7C>u<EFBFBD><75>Tr<54>G6l<36><6C><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>{DžQ<C785>_'/<1B><>y<EFBFBD><79>;<3B>w\<5C><><EFBFBD><EFBFBD>lY0<59><30>d<EFBFBD><64><17>v>۳z鉁<13>U<EFBFBD>h<EFBFBD>S-"‚<>shJ<68>q<EFBFBD><71><EFBFBD>s<EFBFBD>8g<>G<><47>T<EFBFBD>A<><41><EFBFBD>ܾy<DCBE><79>=<3D>/<2F><05><>/<2F>n<>GW<47><57><EFBFBD><EFBFBD>Ҷx<D2B6><78><EFBFBD>KSA<53>0v<30>y<EFBFBD><79>)<29><><EFBFBD><EFBFBD><1B>TWwN<77>ֺd<D6BA><64>=<3D>o<EFBFBD><6F><EFBFBD>#<23><><EFBFBD><EFBFBD> 7_w <0B><>]<5D>6<EFBFBD><36><EFBFBD><EFBFBD><~<7E><>O<EFBFBD>=<3D><><EFBFBD><EFBFBD>{<7B> r<><72>G<EFBFBD><47><12><06>u<EFBFBD><75>FM<46>!<21><><EFBFBD>=+7<>i<EFBFBD><69>w<1D><><EFBFBD><EFBFBD><1C><><EFBFBD>|q<>m<EFBFBD>Do}<7D><>+s<><73>Ã<EFBFBD><C383><EFBFBD><00><>4<EFBFBD>x<EFBFBD><1C>בQ<10><><EFBFBD>Æ'Sa<53><61>[Vm;<3B><EFBFBD>[b<>c<EFBFBD><63>w<EFBFBD><77><EFBFBD><EFBFBD><EFBFBD>$~<7E><><EFBFBD><EFBFBD>L{s ΁x}<7D><>i<EFBFBD><1B>m=2Q<32>~<7E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>[{]<><7F>oh<6F>޶<EFBFBD>o(<28><06><><EFBFBD><EFBFBD><EFBFBD><0F>똿p㲭Gv<1C>:<3A><><EFBFBD>ђ<01><>UnIEND<4E>B`<60><>PNG

IHDRL<00>V|<7C>TPLTE<00><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>і<EFBFBD><D196><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Н<EFBFBD><D09D><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ė<EFBFBD><C496><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>itRNS+T
^c<>Wa<57>Q)\<5C>OB0}<01><00>IDATx^<5E><>I<0E>0<05>o<08><>8<EFBFBD><38><EFBFBD>gD<67>V H<><48><EFBFBD>{S<><53>9<EFBFBD><39>64<36><34>|<7C><>!G4<47>bL}0<>2<EFBFBD>A<EFBFBD>f<EFBFBD>@<08>d<04> <0B><><EFBFBD><EFBFBD>;<15><>
BN<EFBFBD><EFBFBD>5<00>0<EFBFBD>>a<>F<EFBFBD><46><EFBFBD><EFBFBD><EFBFBD><EFBFBD><14><><EFBFBD><EFBFBD>k<EFBFBD><6B><EFBFBD>@q<>0<08>&<26><>F<18><><EFBFBD>ȄI<C884>]<5D><>-<08><08>)^F@T<> <0B>ە<EFBFBD><DB95><EFBFBD><EFBFBD> <0A>E11<03><>][<5B><1D>7Vh# <0C> <12>n<EFBFBD>0<13>¾<><C2BE><1F><><EFBFBD><EFBFBD> IEND<4E>B`<60><>PNG

IHDR szz<7A> IDATx^<5E>W<EFBFBD>k\E<14>ݛd<DD9B><64><EFBFBD><EFBFBD><EFBFBD>6F<>4<EFBFBD>d7<64><37>m<EFBFBD>Ə
<EFBFBD>(<28>>X}<7D>O-<2D><1F><>@<40>OR<4F>[UP(<28>X<EFBFBD><58> V-<15><>"<22><>f<EFBFBD><66><EFBFBD>n<EFBFBD>ۢɦjR<6A>К4<D09A>3<EFBFBD>9́{a<>] <0C>Y&3s<33><73><EFBFBD>~<7E>sΜ<73>q<EFBFBD>ָ<EFBFBD><D6B8>Q&<26>r<EFBFBD><72><EFBFBD><EFBFBD>v5<76><35><EFBFBD><<3C><><EFBFBD><EFBFBD><0E>FC<46><43><EFBFBD><EFBFBD>)<29><>:N<>R<EFBFBD><00>F<1A>ǡ<11><>'s3<73><33>=giii<69><69>O<EFBFBD><4F>><02><>5\<5C><>ַ><3E><><EFBFBD> ӕ<>vn<76>"<22><>ݳ<><DDB3><0E><><EFBFBD><EFBFBD><EFBFBD><6ҵ<36><D2B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD>PJq<4A>L<EFBFBD>4<EFBFBD><34>y<EFBFBD>ZF<5A><46><EFBFBD><1E><><EFBFBD><EFBFBD>[<5B>G<EFBFBD> <0C>rW ޵<1A><>"Q<>Α#'<27><0F><>}~<7E>Gh4<68><34>\l<>A)<29><><1D><02><>͵<EFBFBD>dc̊ؠj w<><77><EFBFBD><EFBFBD><EFBFBD>֙<EFBFBD><D699><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD><63>6W<36><57><EFBFBD><EFBFBD>=<3D>uo<75><6F>y<>)<16><><EFBFBD><EFBFBD>l <0C>e<EFBFBD><65>x<EFBFBD>%<25><>u8<>ڐ<07><>ĒX<C492><58><EFBFBD>\im<69>B<EFBFBD><42><EFBFBD>a<EFBFBD><61><03>R<EFBFBD><52><EFBFBD>b`<60>q]<5D>JW|<16><>^\c8<63>g<EFBFBD>+!<21>_<EFBFBD><5F><EFBFBD><EFBFBD>!m||<1D>Ԡ$<24>Y<EFBFBD><59>LFٞ<><D99E>@"<22>gO<><4F>|PP<50><50><EFBFBD><00><><EFBFBD><EFBFBD>x;<3B>Cl<43><6C><EFBFBD><EFBFBD>g<EFBFBD>6<><36><EFBFBD>9[h<><68>HD <0C>)<29>c<EFBFBD><63> <0A>Iy<49>V<EFBFBD>@*<13><1A> <1E>&C<>,<2C>/<2F><>f<EFBFBD>"<22><1A>L&<1B>E <09>`i><3E>np<>4033k<33>kԧs <0C><>4 <0B>y<EFBFBD>p<EFBFBD>A&3<>6<EFBFBD><36><1A>zb<7A>"<03><>a@<40>U<>C <20><>IR)<29><<3C>j<EFBFBD><19>2'<27><>A~&<1D><>G<EFBFBD><47><EFBFBD>?<3F><04>y<EFBFBD>
]<5D>'<27><><EFBFBD><EFBFBD>,%<1A><><EFBFBD>H<><48>o<EFBFBD><6F><EFBFBD><07><>B<EFBFBD><08>n<EFBFBD>1<EFBFBD>J<EFBFBD>@th@<40><1B><>H<01>ZT3<54>(<28><1A>&<26>[<5B>액(<28><><EFBFBD>`U<>Y<EFBFBD>2<EFBFBD><32><EFBFBD>C@<40>k<EFBFBD>@<13>99<00><><EFBFBD>nkk<6B><6B>0oRS/<2F>~`&<26><>y?+絧k<13>{<7B>M<1F>s,,<2C>m<EFBFBD>=<3D><>˅j<CB85>B-<2D><>v<EFBFBD><76>W<EFBFBD>ϮM@<40>^<5E><>E> C<>:3I#<23><>/<2F> "9 <20><>Ÿ<EFBFBD><C29F><EFBFBD>m {<7B><><EFBFBD>
<EFBFBD><EFBFBD><EFBFBD>z<><1E>^<0F><>= <20><><EFBFBD>2<11>`<12><><EFBFBD><EFBFBD><EFBFBD><0F><EFBFBD><E2BE96><EFBFBD><EFBFBD>Ϗ<><CF8F>w<EFBFBD><77><EFBFBD><EFBFBD>Cav<61><76> <09>Lm<02>%e<><65>$1<><31><EFBFBD>yt<79><74><EFBFBD><EFBFBD><00><><12><>k<EFBFBD><6B><EFBFBD>E~<7E><>g<EFBFBD><67><EFBFBD><EFBFBD><EFBFBD>h,iԯ<69><D4AF><EFBFBD><EFBFBD>W<EFBFBD><57>s<12>q<EFBFBD>"<22><>t<EFBFBD>T1RJvRM
8d<>/<>ނ<EFBFBD><DE82><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>'<27>Fy<46>l<>w<EFBFBD><77><>J<EFBFBD><4A>Y<>N2{<7B>3R<>y^<5E>-!<1C><>%<25>zm<7A>><3E>~òQ><3E>F<EFBFBD><<3C>՛kx}<7D>˒<EFBFBD>PuTBQ<42><51><EFBFBD>D<EFBFBD>Kv+{%E<><45><EFBFBD><EFBFBD><EFBFBD>x<EFBFBD><78><11><><EFBFBD>1<1C><>*><3E><>$J<><4A>ض<EFBFBD>3<EFBFBD><33>j<EFBFBD> <09><>E9@<40> <09>(<28>L<EFBFBD><4C>8<EFBFBD><38>H<1E><><EFBFBD>9_|lf
<1D>m<EFBFBD>gS v'<27>q<EFBFBD><71><EFBFBD><EFBFBD>N<EFBFBD><4E>\p<><70>څHi_ <09>wG<77><<><EEA7BD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>߽<EFBFBD><DFBD>y"<22><><EFBFBD><EFBFBD><14>Ki<4B><69><EFBFBD><15><>J5<02><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ҏN<D28F><4E>k;<>8}<7D><>ɓ_<C993><5F><EFBFBD><EFBFBD><EFBFBD>RUR<><52><EFBFBD>r<EFBFBD><72>O<><4F>g0<><><7F>9t<06><>j}]<5D><>H<EFBFBD>q<EFBFBD><71><EFBFBD>|<7C><10><>_<EFBFBD>mp\w<>):<3A><>'g<>U+D*
<EFBFBD>8` c<><00>Yy<59>v<EFBFBD><76>=<3D>(/ U@<40>:IEND<4E>B`<60><>PNG

IHDR szz<7A><04>IDATx^<5E>W<EFBFBD>k\U<14><>7I <0C><><EFBFBD><EFBFBD>6F<>4<EFBFBD><34>Lf&<26>1<EFBFBD>¢VD <09><><EFBFBD><EFBFBD><EFBFBD>v<EFBFBD>…<EFBFBD>u%u[<14>+<2B>n<15>"<22>|5_<35>d<EFBFBD>E'Iմ<18><><EFBFBD><EFBFBD>s<EFBFBD><73>p<0F>Q<EFBFBD>oJ<6F><1B>0y<30><79>w<EFBFBD><77><EFBFBD><EFBFBD>9<EFBFBD>{<7B>$<24><><EFBFBD>V<EFBFBD><10>xtl7<6C><37>z q[w<><77><EFBFBD><EFBFBD>P,:<3A><>|_<><5F>(A'<27>MHx<78><7F>_<><5F><EFBFBD><EFBFBD><EFBFBD>}<7D>> <20>g<EFBFBD><67><EFBFBD><EFBFBD>|<7C>թ<12>!<19><><EFBFBD>ɓ<1F>&<06><>Z<EFBFBD>82<38>/<2F><>,<2C><><EFBFBD>9v}vh<05>|<7C>C<EFBFBD>l<><13>fMD<4D>G<><47><EFBFBD>l<EFBFBD><6C>w3<77>б<EFBFBD>8<EFBFBD><38><03>{d<>^<5E><>z"<22><> <0F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>?<3F>)$<01>;R<01><06><><EFBFBD><EFBFBD>'2'<27>e<EFBFBD>$ <0C>ČO@<40><><EFBFBD>j<EFBFBD>E<EFBFBD>a<>f<EFBFBD>
++<17>#
n159<EFBFBD>0$<00>E<EFBFBD><45>sI蘝<49>B<EFBFBD><42>T<EFBFBD>9<EFBFBD><39>|>\<5C><>&s<>^<5E>Z<15><>
0HĞ<EFBFBD><EFBFBD><EFBFBD>`~B<> u/:x<>---<2D><18>I<EFBFBD>&'ӎ<><r<>$<24><>µE<C2B5>P<EFBFBD>jIxفgAd]<5D> <0F>M<EFBFBD><4D>s`i/8+d<><64>q<EFBFBD><71><EFBFBD>6<01>T<04><>뮼.<2E>bU<00>~<7E><><EFBFBD>a<EFBFBD>9<1A><><1C>$s<><73><EFBFBD><EFBFBD><EFBFBD>s<02>ͥ!<05>% <20>|Z<><5A>dG۲&C<><43><EFBFBD>3<EFBFBD>%eM&<26><><EFBFBD><EFBFBD>y<EFBFBD><79>_4!ac<10>S<EFBFBD>+Pa<50>I֋K5<4B>X<EFBFBD><58><EFBFBD>[<02><><18>Vk<56><6B>5)<12><><EFBFBD><04><> <0A><>Uz<55>Y <0B>fl-ؖ<><D896>T<EFBFBD>$U<><55>H<EFBFBD>A>k<>C<>0.<01>۪<EFBFBD><DBAA><EFBFBD><EFBFBD><EFBFBD>Ċ<><C48A>n<EFBFBD><6E><EFBFBD><EFBFBD><EFBFBD><1F><>I<EFBFBD>j<EFBFBD>F<EFBFBD>yy<79><79><EFBFBD>l<EFBFBD>׀<EFBFBD>cQ4<34><7F>ٔ<EFBFBD><1B><><EFBFBD>} <20><><EFBFBD><EFBFBD>2Al<>l|<02><>*<16>I<EFBFBD><49>S<EFBFBD>e<EFBFBD>4'WXrh<>&9<><39><EFBFBD>ʯ?c<>w<EFBFBD>T<EFBFBD><54><EFBFBD>.<2E><>F<06><>*<2A>_͘Hz(D <20><>+~\H<>yu<13><>{
w<EFBFBD><EFBFBD><06><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>oQ<6F>/<32>*<2A>"<22><>s $$j<>癉$ʕy<00><>&<26>ȶÏ<17><04><>Ǟ<EFBFBD>k<EFBFBD><6B><EFBFBD><43>~<03><><EFBFBD>ێ<EFBFBD><DB8E><04><><EFBFBD><EFBFBD>z<EFBFBD>!e8k <09><><EFBFBD>H<EFBFBD>?<3F><>K~g<><67> <0C>><3E>8V/<2F><>}w<><77>:j<>ƈhPq<10><><EFBFBD>\*<2A>{u<03>z<13><><18>rZ<72>|<7C><><EFBFBD>+?<3F><><EFBFBD><EFBFBD>l<EFBFBD><6C><EFBFBD>j <0B>]<5D>+G^<5E>x<08>X<07>f<1D><>L<EFBFBD>3Vu<56>ߒ<EFBFBD>K<EFBFBD><EFBFBD><1E><><EFBFBD><EFBFBD>Ɖc/<2F><>O?Bs<42><73><EFBFBD><EFBFBD>$t<><74>冤ܬ<01>Z<EFBFBD>k<EFBFBD><6B><EFBFBD><EFBFBD>e<EFBFBD>]<5D><02><><EFBFBD><EFBFBD>E<EFBFBD>g<16><><EFBFBD>Ӌ;v<><76><EFBFBD><EFBFBD>N<><4E>6<EFBFBD><05>,<2C>s<12>p<EFBFBD>e<>H<EFBFBD><48>n<EFBFBD>J<EFBFBD><4A><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>blh<6C><68>yd<79><64><EFBFBD>s<05><>G{<7B>w<EFBFBD>?&6Z<36><5A>t<7F> <09>G<EFBFBD> <1C><><EFBFBD><EFBFBD>ߌG@<40><>(<28><13><><EFBFBD><EFBFBD>k<14><>[/ <0C><>%<12><><EFBFBD><EFBFBD>/<2F>i<EFBFBD><03><><03>a" W<>0X<30><58>
PWWW<1D><00><><EFBFBD>bG<62><47><05>lmٯ<1D><><EFBFBD><EFBFBD><EFBFBD><01>H:$yW)qIEND<4E>B`<60><>PNG

IHDR<1F><>a<01>IDATxڍQ<DA8D>/A<14>f<EFBFBD>mV<6D><56>
<1A><><EFBFBD>D<EFBFBD>\<5C>.<0E><>܃D<DC83><44><EFBFBD><EFBFBD>]<5D>D$W!<21>ġ'$~<7E>B+ďD#-[<5B><> 3]<5D><><EFBFBD><EFBFBD><EFBFBD>̼<EFBFBD>6<EFBFBD>}<7D>{o c <0C>3 ~<7E><><EFBFBD>@<40> co<63>]<5D>^[O<><4F>Z<EFBFBD>W<EFBFBD>J<EFBFBD>WWW<57><57> ʘLN/X<><58>&h<>
<EFBFBD><EFBFBD>E7YJ<>Ș<07><13><>z<EFBFBD>T<EFBFBD><54><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!NO<4E><4F><EFBFBD><EFBFBD>C<<3C><>*D<><44><EFBFBD>о<><D0BE>#-<18><><EFBFBD> ^K%<25><>%<25>65s)"F<>Dm<>^J6<4A><36>R莙<52>}0<>@<40>P<EFBFBD>dyT<79><54>%M<0E><><EFBFBD><EFBFBD>-<2D><>rWx<57><78><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>[@v<>.I<><49>\}<7D><><EFBFBD>lCè7 .<2E>)<29>.I<>n!hBd3<64> <06><>p<18>z<EFBFBD><7A><EFBFBD>@<40>݌vȼ7n<37><6E>3<EFBFBD>˿v@<40><>d%<11> "U<><55><15>^bWW<57><57><EFBFBD><EFBFBD>(<28><><EFBFBD>B<EFBFBD><42><EFBFBD>q<EFBFBD>ډ$<24>NJ<EFBFBD><C78A><EFBFBD><01>ho<68><03>T]ܹ\4!<21><>!<21><><EFBFBD>ӹ<EFBFBD><D3B9>%Z<>Qx<><78>i<EFBFBD><69>0Y<>wuF`<60>R<02>O<><0F><>u]/<2F><>'<27><><<3C><>ƒ<EFBFBD>IEND<4E>B`<60><>PNG

IHDR J<>ΛfIDAT<18>c<EFBFBD><63><EFBFBD><EFBFBD>AYS<59>By<42>r<EFBFBD><72>)<29>D<>q<EFBFBD><71><EFBFBD><EFBFBD>@a!PHWO<57>
tc0<EFBFBD>59<EFBFBD><02><18>'Y<>A<EFBFBD>+<18>+<2B>Ϡ<EFBFBD>>/=<3D>3(<28>hc@d<><64><EFBFBD>3P<33>v<><EFBFBD>͐<><CD90>Y!!F <00><>Il<49>˰<EFBFBD>IEND<4E>B`<60><>PNG

IHDR r<><72>|gAMA<00><> <0B>a<00>IDAT(<15><>A
<EFBFBD>0E<>ĝ<14><>7p<37><70><EFBFBD><EFBFBD>d<EFBFBD>K<EFBFBD>w+.q#<23><1F>ԉ<19>$<24><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ďh<C48E>.<2E>F<><46><EFBFBD><EFBFBD>]<5D><>K<>FfVn<56><6E>e<13>S <1E><02>~]<5D><06>|Y<><07><1F><1E>˓j<CB93>@<40>G<0F>2<EFBFBD><1F>v<EFBFBD>{<11>F<EFBFBD><02>{:<3A><>l<EFBFBD><6C><EFBFBD>wr<77>N<4E><1D><>p<EFBFBD><18><>]QD<51>3<EFBFBD><33>}<7D>W<EFBFBD> <0A>1,<2C><><EFBFBD>~<7E>IEND<4E>B`<60><>PNG

IHDR<00>JL<4A>gAMA<00><> <0B>a2IDATH ͖<>j<EFBFBD>@F<>?m<><6D>K<EFBFBD><4B> <0A>-<2D>o<EFBFBD>F<EFBFBD>;_@<08>εؖ<CEB5><D896>YFƠc<C6A0>:/<2F>L&<26><><13><>dZY<5A>Q<>^a {<7B>Z:$<24>jI<6A>O0<4F>%dM<12>$<1F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ew<45>Ҟ<EFBFBD>Z<>b)D<>$S$'j<>c<1B><>~<7E>[D<>%ZEQ<12>(Zb<11>$<24>"<22>D<EFBFBD><44><EFBFBD>;Vң<56>V<EFBFBD>cT <0C><12><>C<1B>0<EFBFBD><30><EFBFBD><EFBFBD>"<22>2$<24>b <0C>: <09>:<3A>į<EFBFBD><C4AF>c<12><><08><>[<5B>s<EFBFBD>Q*<2A>ֺ\EYT<59><54>,<2C>M<EFBFBD><4D>j<EFBFBD>H<EFBFBD><11>o|<7C><>Xp<58><70><1D>w<11>P<EFBFBD><50>$zH<7F>$]r5<19><><EFBFBD><EFBFBD><1F><><EFBFBD>uhC<12>=<3D><><EFBFBD><EFBFBD>_<EFBFBD>W<EFBFBD>!<21> ҖH<D296><48><EFBFBD><EFBFBD>Vp)<29>uB4g<>Cm<43><07><>y<79>Ic<><63>; ;IEND<4E>B`<60><>PNG

IHDR<00><>-<2D>gAMA<00><> <0B>a7IDAT(cd``<60><07><>@|<08>A<00>g2<><32>\<01>3!<21><><EFBFBD>Q <09><><00>F<EFBFBD>#H@<40><>)<29>(<28><00>lt<>,<2C>}IEND<4E>B`<60><>PNG

IHDR 4<00>\<5C>'gAMA<00><> <0B>a<00>IDATH <0A><>1
<EFBFBD>0D<><><7F>E<EFBFBD><45><EFBFBD><EFBFBD><06><>^<5E><><EFBFBD>Y!<21>S,h<>,<2C><><EFBFBD>1<EFBFBD>#E<><45>Rz`5<><35><EFBFBD><EFBFBD><EFBFBD><EFBFBD><12>Ԡ <0A><>/<2F>H<7F><48>\<5C>ܸ/<2F>v<EFBFBD>U<EFBFBD><55>]<5D>$K<>]<5D>@ <0C>e<EFBFBD>tY
<EFBFBD><EFBFBD>X<EFBFBD>HG<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <09>]<5D>[<5B><>E<EFBFBD><45><1C><>p+<2B>E<EFBFBD> <09><><0F><>ӊ<EFBFBD>IEND<4E>B`<60><>PNG

IHDR<00>^<5E>.gAMA<00><> <0B>a#IDAT(cd``<60>bi <20>%x<>4<><34><EFBFBD>6 _<>A<EFBFBD>6<EFBFBD><36>c<02><><17>VIEND<4E>B`<60><>PNG

IHDR4 -Q<>+gAMA<00><> <0B>a^IDATH cd``<60>bS <20><06><> <0C><>H<>1<>P<EFBFBD> <09>ۿ1!q<><03>?3<><17><>X <0C>Y<EFBFBD><59><EFBFBD><EFBFBD><02>z<7F><7A>a<EFBFBD><61><EFBFBD>!0<>!*<2A>G<EFBFBD><47><01><06><18><>p<EFBFBD><70><EFBFBD>ˀ<EFBFBD>!m.w<><77><EFBFBD><EFBFBD>IEND<4E>B`<60><>PNG

IHDR szz<7A><03>IDATx<54><78><EFBFBD>iHTQ<14><><EFBFBD>(6<><36><EFBFBD>:j<>d<EFBFBD>2<EFBFBD>N<EFBFBD> <09>Mc<14>6<EFBFBD><36><EFBFBD><12>/E<> a<11>T<14><>Z)<29><><EFBFBD>ʡ<EFBFBD><CAA1>C<>(<28>p<EFBFBD>R<EFBFBD>%<25><><0F>+T<>L<EFBFBD>^z<>ɩW<C9A9>1QЁ˽<D081><CBBD><EFBFBD><EFBFBD><EFBFBD>9<EFBFBD><39>7<EFBFBD>v<EFBFBD><76><EFBFBD><EFBFBD><EFBFBD>&<26><>P(*<2A>V<EFBFBD>%''GQ<47>gq<67>\*<2A>R<EFBFBD>Gk:<>|<7C><>Fj<46><14><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>p8΋E@IR<49><52><EFBFBD><EFBFBD><EFBFBD><EFBFBD> !sX<04>5<1A><>?<3F>~Q"<01><06><>D <0C><><EFBFBD>$<00><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>AVs<1C><><EFBFBD><0E><><05><><EFBFBD>'<06>R, ##<23>K<1D><>|ONN<4E><4E><EFBFBD> !<12>iii|D<>M<<3C>F<EFBFBD><46><EFBFBD><14><><EFBFBD>D$EB<45>P<EFBFBD><50><EFBFBD>,<02>Z<EFBFBD>z<EFBFBD><10><><EFBFBD><EFBFBD>hhh<68><68>tQ<01>
y?`2<>D$<11>D<00><><EFBFBD>!<21>><3E><>} <00><><EFBFBD><EFBFBD><EFBFBD>$} <0B>I<EFBFBD>Zo<5A>E<EFBFBD><13><16><> K<><4B><EFBFBD>5<EFBFBD>x<>x
j<EFBFBD>tf,<2C><><EFBFBD><EFBFBD><EFBFBD><77><DE87><EFBFBD>Ǣ<>,,<2C>]<5D> <09><><10><><EFBFBD><EFBFBD>,M<><4D><EFBFBD>+<2B><>讼.<2E>6<EFBFBD>N<EFBFBD><4E>3(J=BIQf?!<21><>6<EFBFBD>C<EFBFBD><43><EFBFBD><EFBFBD>t<EFBFBD><74>)bv!]<5D>JH<4A>$<24>gmw<6D>1<EFBFBD>L1f!<21><>_<EFBFBD><5F><EFBFBD>2
<EFBFBD>04<EFBFBD> $F<>>-<01> <20>y 4~! <20>m<1A><><EFBFBD>0<EFBFBD><30><EFBFBD><EFBFBD><EFBFBD><01><>{0C#<23>9B<>D<EFBFBD>@<40><>{8<>b<17>0I"G_cd&<26><>+q<>a/<2F><>'<10>Y1<>?R8<03><02>C0<43>yD<79><44><EFBFBD><EFBFBD>6_6s-NfU<66>s<EFBFBD>M<03><><EFBFBD><EBB1A0>:v,<<3C><>%<25><>mAː <0A>އx<DE87>y EIG%<01>!c<><EFBFBD><7F>*"88?<3F><><EFBFBD><EFBFBD>8r<38><72><EFBFBD>qk<19>Ԃ<EFBFBD><D482>א={3:G<>ٜ<EFBFBD><D99C><1B>:<1E><><EFBFBD><EFBFBD><EFBFBD>q<05>& <20><><EFBFBD><EFBFBD><08>'<27><41><C5BB><EFBFBD>h<05><><EFBFBD>ي<EFBFBD>qk<71>$<24><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>l<EFBFBD>f<EFBFBD>.H,f<>p<><70><EFBFBD>n<15>ϛnD~<7E>><3E>u0
<1C>C<>ww;@<15>MIQ<>P<EFBFBD>u<EFBFBD>7<EFBFBD>ۏ<EFBFBD>s<EFBFBD>y<EFBFBD>2<01><1A>vy<00><><EFBFBD><EFBFBD>=44<34><34>)))hll<6C>n<EFBFBD><6E><EFBFBD>P <0F>><3E>-<2D><><EFBFBD><EFBFBD>A<>{<7B>8<EFBFBD><38><EFBFBD><EFBFBD>l6K}r<>1<EFBFBD>X<><58>l<EFBFBD><6C>Q<EFBFBD>z~A<>c<EFBFBD><63><EFBFBD><EFBFBD>aaal <11>K<><4B>K)<29>%d%55U<35><55><EFBFBD><EFBFBD>L<11><><14><><EFBFBD>y<EFBFBD><EFBFBD><E59384>7Sd<53>Wn"N<><4E>p@ |#JRzI<7A><49>+<00>Z<EFBFBD>n<EFBFBD><6E><EFBFBD>('<27><>Y<>|#
<EFBFBD><18><><EFBFBD>d<10><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>W<EFBFBD><57><EFBFBD>`7%<25>TIEND<4E>B`<60><>PNG

IHDR szz<7A>~IDATx<54><78>VKHQ<18><>̽7<>KY֦P<D6A6>{<7B>.<2E>E<>B<EFBFBD><12>1<10><16><>E<EFBFBD>t<13><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>&<26>\A=<3D>V*d<12><>P<EFBFBD>H<EFBFBD>Z<EFBFBD><5A><EFBFBD>3s<33>st<73>;3<><33><18><>><3E><><EFBFBD><EFBFBD>3<EFBFBD><33><EFBFBD><EFBFBD><7F><EFBFBD><19><> 0B<30><42><EFBFBD>񗕕<EFBFBD>p<><70><EFBFBD>(<28> N<> !<21>Z?<3F>Z;|L<><4C><EFBFBD>O{<04><07>(<28>9<EFBFBD><39><EFBFBD>ݰunDSIp<49><70><EFBFBD><EFBFBD> $<07>#<1B>NBE
Lp
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>c||\k[<5B><><EFBFBD><><DAB8>>//<2F>{΄TUU<55><55><EFBFBD><EFBFBD><EFBFBD><EFBFBD>r<EFBFBD><72><EFBFBD>n<EFBFBD><02><>}t<> VTT<54>G<EFBFBD><47>0<EFBFBD><30>z<EFBFBD>
<08>U<EFBFBD>"}aaa<61>h#<19>fK<66><4B><EFBFBD>b B<03><><EFBFBD><EFBFBD><EFBFBD>N<EFBFBD>A-_<04>AM<01>.**J<> <0A>h<EFBFBD><68>뙏^z<>=@씡<><EC94A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> K<>`vX<16>>#<23><><EFBFBD>9\<5C>?<3F>?"<22>
<EFBFBD>w<EFBFBD>p<EFBFBD><EFBFBD>2<EFBFBD>B&"&c<>79<>'%<25><> aa<61><61><EFBFBD><EFBFBD><EFBFBD><EFBFBD>K<EFBFBD><0F>(.uI؛ <0B>9d<>XS<58><53><EFBFBD>C<EFBFBD>0<EFBFBD><30> m<>`<60><>QϿ<7F>`p<><70>alhyx<><78><EFBFBD>*<2A><>T<EFBFBD><1E><><EFBFBD>Ⲃs<E2B282><73>`<60><>#x<><08><1D><>t%<25>t<EFBFBD><74>g<EFBFBD><67>!<21><><EFBFBD><EFBFBD>c)N<01>ǖ<EFBFBD><14><>+<2B><>Ek<45><6B>6<EFBFBD><36><EFBFBD> <09><08><15><><EFBFBD><EFBFBD>2<EFBFBD><32>\A8B+B<7F><42>7<>4<EFBFBD>b<EFBFBD><62>co<>(l<>E<EFBFBD><45>'<27><02>t<1B><><EFBFBD>T<EFBFBD><54><EFBFBD><EFBFBD>&<26>l]"<22>O<15>z&<26>)G<>kE5<45><35>Gqh<71>j
:<3A>
x<EFBFBD><EFBFBD>Ka<4B><61><EFBFBD><EFBFBD>Edl<64>J2~ u<>#<23><>f<EFBFBD><66><EFBFBD>'R]<5D><><EFBFBD>#{<7B><>a<EFBFBD><61><EFBFBD><EFBFBD>2Z<32>p<><70><<3C><>d[e<18><14>Ϡj~)~<7E>R<EFBFBD><52><12>(<28>2<EFBFBD>#ۗ/<2F>ԁ%<25>8,s5<73><01><><EFBFBD>-<2D>e<EFBFBD><65>X<EFBFBD>S<EFBFBD>V<EFBFBD><00>h<EFBFBD>Y<EFBFBD>d[b<>pX<><58>̔<EFBFBD>z/<2F>;<3B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>}<7D><><EFBFBD>2<><32>YYYl<59>?<3F><><EFBFBD>bddD<64><44><EFBFBD><EFBFBD>dU5<55><35><EFBFBD>O<EFBFBD><00><><EFBFBD>DR[[5<><35><EFBFBD><EFBFBD>h
<EFBFBD>D<08>;_W<5F><57><EFBFBD><18>xxx L<><4C><EFBFBD>m<><6D>=<1E><><EFBFBD><EFBFBD><14><>ʘw}MMM<4D>q<EFBFBD><71><EFBFBD>P<b<>Z%4n<34><6E>X<04><>yu<79><75><01>ab 9cP<0E>gI<67><49>!<21><g<>a<>x<><78>0<EFBFBD>/<2F><>QiW]IEND<4E>B`<60><>PNG

IHDR<00><>7<EFBFBD>TIDAT(<28>c` <06>8bB! G<><02><><EFBFBD>X<EFBFBD>P"BA(!@<13>!<21><>e<>) <20>dS<64>3<EFBFBD>:n<><6E>C<EFBFBD> <09><><18><02>&<26>D<10>B<EFBFBD>@<40>S<EFBFBD><01><><EFBFBD>+!
`4<15>{<7B>yIEND<4E>B`<60><>PNG

IHDR szz<7A><02>IDATx^<5E>WMhQ<10><><EFBFBD>m<><6D>n/&<26>"<22>"6.I<>${(*=
E<EFBFBD>^ī=<3D>w<15><><1E>Ѓ<15>$E<>BZH<5A><48><EFBFBD>!UH<55>ؤ<EFBFBD>Қ<EFBFBD>f<EFBFBD>}<7D>>H<><48>&<26>Tz<54><7A>afvvw<76><77><EFBFBD>n<EFBFBD>qα<71>0<EFBFBD>ǰ<EFBFBD>Ƙi۶<69>8<EFBFBD><11><17><>L<EFBFBD>0B<><42><EFBFBD><EFBFBD>K<EFBFBD><4B><EFBFBD>ئ6<D8A6><36><EFBFBD><EFBFBD>B!_*<2A>$ ι<><CEB9>d^@<1F><>o+<2B>$<24><06><><EFBFBD><EFBFBD>DR <00><>#<23> <0C>UJ
<EFBFBD><EFBFBD><16><><EFBFBD>)<29><><EFBFBD><EFBFBD>Ԯ<EFBFBD><D4AE>X,*<2A>G`dddG -<02>t<1A><08><><EFBFBD><EFBFBD>k<EFBFBD><1A> }t'T<>T*<2A>:<3A><>4ēɤЂ<C9A4><D082>y$<01>N<EFBFBD><4E><EFBFBD>H<EFBFBD><48>cL<1D><>Q}?<3F><><EFBFBD><EFBFBD> n<><6E>ض<><D8B6><EFBFBD><EFBFBD><00> <09><><EFBFBD>/<19><><EFBFBD>ߒ<EFBFBD><DF92> <0B><>vE<76>]P_<50>?q)<03>񉴱<EFBFBD><05>ۛ<EFBFBD>&.<2E>|7<06>4G<04><>!вR<D0B2>=6<>R<EFBFBD><52><EFBFBD>%<25><16><>nH<6E><48><EFBFBD>(um<75>#h<>n5WH<57>-<><7F>} <0C><>QT<51>[<5B><><EFBFBD><11><> I( H<1B><><EFBFBD><11><>E<EFBFBD>U]<5D>+`<60>Y<EFBFBD>Zt`~<12><>Sq<53><71><0E><><EFBFBD><EFBFBD>勳X=<3D><10><>1t<31><74><0F>2<EFBFBD><32>n<>xX<78><58><EFBFBD><EFBFBD>@<40>|<7C>x<><78><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>U<18>Z<EFBFBD><02><>G<EFBFBD>h<16><><EFBFBD>[<5B>'<27><>}{<7B><>xT<78>\T,<2C><><EFBFBD>;<3B>j)<<10><><EFBFBD><18>CăH<C483>@# <09><56>4<><34>y<EFBFBD>
<EFBFBD>kL<EFBFBD>/<2F><><1D><>R'<27>߁l6+<2B>J<EFBFBD>"<22>x<<3C>\.<2E>PQ(<14><><EFBFBD><EFBFBD><EFBFBD><1D>Aoo/<2F><> <00>"ຮ<><E0BAAE><EFBFBD><EFBFBD><EFBFBD>T%<25>Rk<13>233#<23><EFBFBD><E882BA>U<EFBFBD><55>|^<5E>===<3D><01><><EFBFBD><EFBFBD>I۶mE<6D>iH$;V;44D<34>;%<15>B<EFBFBD>-<02>I<EFBFBD>x~<7E>"<22>7<EFBFBD><12><><03><02>v<EFBFBD>p<1E>B+<02>eY<65>766<36>1<EFBFBD>ș<><0E>( <0C>$<24><><EFBFBD><EFBFBD><EFBFBD>Te<54><65><19><0F>IEND<4E>B`<60><>PNG

IHDR <00>s<EFBFBD><00>IDATx^<5E><>?
<EFBFBD>0<05><>?ѭ<><D1AD><15><>y(<28><><EFBFBD>G<EFBFBD>#<23><><EFBFBD>N]
<0E>}*
! <09>QT<51>J<EFBFBD>oȯ/4<>LJ<EFBFBD>5<EFBFBD><35><EFBFBD><EFBFBD><14>u<EFBFBD><75><EFBFBD>8<EFBFBD><38><EFBFBD><EFBFBD><EFBFBD><EFBFBD>W2<57><32>˝<EFBFBD><CB9D>:<06><><EFBFBD><1D><><EFBFBD><EFBFBD>@1^ ڂ@<02> <20><>T)<29><>ǀ<EFBFBD>^|(`<60><>Q<EFBFBD><51><EFBFBD>A<EFBFBD>$<24>0e ]g<02><>!<21><><EFBFBD><EFBFBD><EFBFBD><08><><EFBFBD>͉<EFBFBD><16><0F><01><18><1C><>yN<>-p<><03> '<27>$N<10><11>$r<>6<EFBFBD><1F><>R!<21><><EFBFBD><02><>|<7C>|,t) <20>|<7C><>8d@ע<>˿<EFBFBD><1D><06><08>%<25><>IEND<4E>B`<60><>PNG

IHDR<00><>7<EFBFBD>9IDAT(<28>c` <06>8bB! G<><02><><EFBFBD>X<EFBFBD>P"BA(!<05><>
<EFBFBD><EFBFBD>@$<24><> B"<22>(<28>%\ Qsp<19>56<35>%IEND<4E>B`<60><>PNG

IHDR szz<7A>BIDATx^<5E><>{K#gƳ_<C6B3>O<EFBFBD><1F><><EFBFBD>'PP<50>h<7F><68>J<EFBFBD>ƈ<EFBFBD><C688>u<EFBFBD>4&n<>T3<54>4<>"<22><>Z/t<> <0B>1<EFBFBD>F<EFBFBD><05><>V\<04> <09><><EFBFBD>S<EFBFBD><53>8&<26><>S聗y<E88197>9<EFBFBD><39>9yg<79><67><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><03>+<2B>˕<EFBFBD>t<EFBFBD><74>]<5D><>]S4<53><34>G<EFBFBD><47><EFBFBD><EFBFBD>s8<73>_5okk/p8\<5C><><EFBFBD>H$Vp||<7C><><EFBFBD>K<EFBFBD><4B><EFBFBD><EFBFBD><EFBFBD>9ߓg<DF93>ù<EFBFBD><C3B9><EFBFBD><EFBFBD>v<EFBFBD>+ϡ:<3A><0F>hf{{<1B><><EFBFBD>8<<<3C><><EFBFBD>:<3A><><EFBFBD>0;;Kc<4B><63>|<7C><>I<0E><>FU
<EFBFBD>H<EFBFBD> ͝<>U<EFBFBD>g<EFBFBD><67><EFBFBD>NOO<4F><4F><EFBFBD><EFBFBD><EFBFBD><EFBFBD>i<EFBFBD>|><3E><><EFBFBD><EFBFBD>l6<6C><36><EFBFBD><EFBFBD><07><>?<3F><1C><15><15><>m~f=<3D>ܞg<DC9E><67><EFBFBD><EFBFBD><EFBFBD>E<02><><EFBFBD><EFBFBD>Ux<55>^4[<5B><>hfff<66><66><EFBFBD><EFBFBD><EFBFBD><EFBFBD>k<<3C>{<7B>ǃ<EFBFBD>f+<2B><>F<EFBFBD><46><EFBFBD>i<11>bf<62>(J<><4A>q<EFBFBD>#NN~<7E>ev<65>w<EFBFBD><77><EFBFBD>F<<1E><>19<19><>Up<55>侧AZa<5A><10><>9<EFBFBD><39>lJA <10><08>M ZZ<5A><5A>(<28> <20><><EFBFBD>a<EFBFBD>0<EFBFBD><30>Lfgm5k<35>-<2D>X^<5E><><EFBFBD><1A><><EFBFBD><EFBFBD><EFBFBD>.<2E>'<27>52<35> <0C><12>t<EFBFBD>V'<27><><EFBFBD><1A> X<><58><EFBFBD><EFBFBD>-<2D><>ؘ<EFBFBD><D898><EFBFBD><EFBFBD><EFBFBD><EFBFBD>}<7D>OL<4F><4C>$|<7C><><EFBFBD><EFBFBD> w<><77><EFBFBD>B<EFBFBD><42>b<EFBFBD><62><EFBFBD><04><><EFBFBD>l<EFBFBD>0,<2C><><EFBFBD><EFBFBD><99<39>d<EFBFBD><64>|H}}}<7D>6<EFBFBD><36><EFBFBD><EFBFBD><EFBFBD><EFBFBD>&<26><><19><><EFBFBD>L<EFBFBD><4C><EFBFBD>aX<61><58>b<EFBFBD>pO<70><4F><EFBFBD><EFBFBD><EFBFBD>t<EFBFBD><74><EFBFBD><EFBFBD>><3E><><EFBFBD><EFBFBD>b.! <0C><>)Wf[,u<11>޾5<DEBE>xC<78><43>bhii<69><69><EFBFBD><11><16><><EFBFBD>Ygg'<27><>S<EFBFBD>G<>Gx<47><78>N<EFBFBD><4E><EFBFBD><EFBFBD>< <0B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><1A><>pss<73><73><EFBFBD>~{{<7B>P($E <f<><66>F<13><><EFBFBD><EFBFBD><1F>ð<EFBFBD><C3B0><EFBFBD><EFBFBD>+<2B>b<EFBFBD><62>(l6<19><><14><> <0B><>"<22>J<19>(<28>1K<31><4B><EFBFBD><EFBFBD>< <0B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>‚T<C282>p8<70><38> <0A><><EFBFBD><EFBFBD>N<EFBFBD>IPੴf <09><>UUUƯ<55><C6AF>7o"<22><><EFBFBD>all ]]]X<>/<1B>ceH<><48>%<25>g<>0GGG<47><1E>TTT<54><35>X<EFBFBD>[G<><47><EFBFBD><EFBFBD><12>Vlj
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҹ <0A><><EFBFBD><EFBFBD><1A>_<EFBFBD><5F> z~<7E><><EFBFBD><EFBFBD><EFBFBD>K<EFBFBD>E<EFBFBD><45>Ӄ`0<>1<><31><1E>'<27>U<EFBFBD>7e<01>ׇ<EFBFBD>0W<30>chhggg<67><67><EFBFBD>9<EFBFBD><39><11><><EFBFBD>J<EFBFBD><4A>eee<01>0=<15><><EFBFBD><05><><EFBFBD><EFBFBD>p8<70>p8<04>G<EFBFBD><47>t_<>1<>~}!s<><73>I<EFBFBD>A8Ĝ0<C49C><30>lS.Q\\<5C><>F<14>D<EFBFBD><44><EFBFBD><EFBFBD>i<1A><>0<EFBFBD><30>v<EFBFBD><02>h<EFBFBD><1E><>Fg<46>0<EFBFBD><30>LS<4C>QRR<52>WTT<54>W<EFBFBD><16><>!<02><><EFBFBD>(G<>_gER<45>l<EFBFBD><6C>i<<><7F>)<29> <0B><>E<7F>h<EFBFBD><68>,f<><66>$z]XX误<58><E8AFAF><EFBFBD><EFBFBD>'  ǫ<>k<EFBFBD>4<<3C><><EFBFBD><EFBFBD>4<EFBFBD><34>=<14><><EFBFBD><EFBFBD><EFBFBD>?;+<2B><><EFBFBD><EFBFBD>0<EFBFBD><30>C<15>
<EFBFBD>"q)<29><><EFBFBD><19> <0B>b<EFBFBD>$<24> $&<26><><EFBFBD>E<EFBFBD><45>]s<><73><08><><EFBFBD><EFBFBD>,<<3C>x<EFBFBD><1E>3<EFBFBD>f|#!+<2B>|<7C>#×<><C397><EFBFBD>!C<>$y<05>F<EFBFBD>b<EFBFBD><62><EFBFBD><EFBFBD>q<EFBFBD>0<EFBFBD><30>_<EFBFBD>Ž*<2A>RUU<55><55>z"}<7D>4z<34>|<7C><>O<><4F>R>z<>w<EFBFBD>,<13><>L<EFBFBD>!<21>6<EFBFBD><36>]<5D>&<08>7\!<21><>3<EFBFBD><33><EFBFBD>ZE<><45>bU<62>e<EFBFBD>T<EFBFBD>,SZ<13><><EFBFBD>m<EFBFBD>)<29><07><><1C>r<EFBFBD>.Z<><18>Cpb݋S<DD8B>o]<5D>}B<><42>(<28><><EFBFBD><EFBFBD><EFBFBD>@<40><><EFBFBD>׎<EFBFBD><D78E>p<EFBFBD><02><>G<EFBFBD>!<21><>V'@;&<26> L<>e<EFBFBD>)<29>'<27><1B>>*F<>> <0C><18>]
<EFBFBD>k`QD<7F><01><><EFBFBD>7Т:d<><64>0<> b<><62>z M<>|췝<10>C<EFBFBD><43>W<EFBFBD><57>IEND<4E>B`<60><>PNG

IHDR =Z<0E>'IDAT<18>cx͠<78>_<EFBFBD><5F>k<04><>D<10>b@0aRH`j<19>M<EFBFBD><4D><00><>-<2D>2^˓IEND<4E>B`<60><>PNG

IHDR =Z<0E>"IDAT<18>cx<63><00>J<EFBFBD><4A><EFBFBD>CXH0A<01> \!<21>b
<EFBFBD> k<>-<2D><>jP<6A>IEND<4E>B`<60><>PNG

IHDRP /:7<><02>IDATX<54><58><EFBFBD><EFBFBD>kA<18><1F><><EFBFBD>^<5E><><EFBFBD><EFBFBD>R<EFBFBD>I/<1E><><EFBFBD><00><><EFBFBD>"<22>EA/<2F><>!<21><><EFBFBD>4=+֋<>z<EFBFBD><7A>j<12><><EFBFBD><EFBFBD>VA<>A <1E>d6<64><03><>x<EFBFBD>f3<66>;<3B><>m6<6D><36>7<EFBFBD><37><EFBFBD>͐g<CD90><67><EFBFBD>}<03><>1<>
*,3E<33>gW?}<07>*&I$Hb"<22>iv<69><76><03><>
<0F>6
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD>{<7B>R<EFBFBD> <20>E"<22><16>y><3E>M7<4D><37>s]<5D>A<EFBFBD>.$<12>.r<08>EG("<22><0E>8<> 3<>;<3B>Oc<4F>ѫB<14> Ǿ<>Hk<
o<>)<29>#E<>^<5E>yKR{"Ͳ<>/<2F>r<EFBFBD><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>H~*N<><4E><EFBFBD><EFBFBD>A<><41>Pv<50><76>=<3D>$öVJ<>h<EFBFBD>`V <0B>@(i$<1D><><EFBFBD><EFBFBD><01>(W<>:i<><69>l7<6C><<3C>?<3F><>]<5D><><EFBFBD>I<12><><EFBFBD><1D><><EFBFBD>{<7B><02> <20>j<EFBFBD>L<EFBFBD><4C><1C><><05><><EFBFBD><EFBFBD>$ Ĩ<>#j<><6A><EFBFBD><EFBFBD>r<EFBFBD>Z=<3D><>\}<k%`<0F><><EFBFBD>rcL<><4C>1G<1A><12><>s<EFBFBD><73>/`<60>U<EFBFBD>CU<43>I<EFBFBD><49>1<EFBFBD>3a]nG<1D>+<1A>Ф<EFBFBD><D0A4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>G<EFBFBD><47><05>S<EFBFBD><53><EFBFBD><EFBFBD>n<EFBFBD>z_<7A><5F><EFBFBD>VV<56>3'X<><58>`Q<><51>Nm<4E><1D>ٱap<><70>F<EFBFBD><46><EFBFBD>^<5E><><EFBFBD><EFBFBD>G<EFBFBD><47><EFBFBD>W<EFBFBD><57><EFBFBD><0F>u$<24>kMi<02><><04><>\r<>/4x<34>( <20>|e<65><08><>KJo<4A><04><><EFBFBD>zT<7A>m70<><30>g<07>n<1D><><EFBFBD><EFBFBD>P<EFBFBD><50> x<>/z<><7A><1D><><EFBFBD><EFBFBD><7F><EFBFBD><03>RlU<><55><EFBFBD>+Bp<42>5<EFBFBD><35>*<2A><02>G<EFBFBD>u<19>7<16>%<02><>^y^<5E>u<EFBFBD>$i<16><><EFBFBD>W<EFBFBD>K<EFBFBD>)<29>ajX<6A>(<28>a<EFBFBD>7}Z<>H<EFBFBD>_<EFBFBD><5F><EFBFBD><1B>3<EFBFBD><33><EFBFBD><EFBFBD><EFBFBD><EFBFBD>IEND<4E>B`<60><>PNG

IHDR<00>@7<><37>$,IDATx<54><78><EFBFBD>OlU<1C>?<3F>*FZ<46>&& bڠ<62><DAA0><EFBFBD><14>pPЃB<D083><42><EFBFBD>&<1E><><EFBFBD>^5A]<5D>8HQ<02> <09><>G=1i<31>D<1C>B<EFBFBD>e<EFBFBD> [<5B><06><><EFBFBD>B<EFBFBD><42><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>웷o<EC9BB7>t<EFBFBD>L<EFBFBD><4C>N<EFBFBD><4E><><DF9B><EFBFBD>y<EFBFBD><79><EFBFBD>Y<EFBFBD><59>ˋ<EFBFBD><CB8B><1E><><EFBFBD>%D<><44><6C><C8A8><EFBFBD>.4tE<EFBFBD><EFBFBD>;<3B>(<28>4S䪯<18>O\H<>VqN /V<>Rᢷ<11><0E><><EFBFBD>a<EFBFBD><61>I'uT<75><54><EFBFBD>TRO'7<><37><EFBFBD>l1<6C><31>1F<10>[,+L;<3B>&J<> ; <0C>M wheiJk<19>C&<26>l<EFBFBD><6C>7<EFBFBD><10><>&M<><4D>i<EFBFBD>/<2F><1A>0<EFBFBD> <0B>Ǭ<EFBFBD>2<EFBFBD>p<EFBFBD>Ui<55>{<7B><><EFBFBD><EFBFBD><EFBFBD><Wh<57><68><10><><EFBFBD>r<EFBFBD><72><08><>Y:<3A>Y<EFBFBD>V&<26><><00>j%<25>™<><C299>I0<49><07><><EFBFBD><EFBFBD><EFBFBD>s<EFBFBD>B<EFBFBD><15><>1B<31><42><EFBFBD>k<>><3E>T<EFBFBD>
6Z<13>ɠ<EFBFBD><C9A0><EFBFBD>\X#H­{¨<><C2A8>DZm<5A>*<2A><>Ai<>{<7B><>R<00>y<EFBFBD><79>ڿv*<2A><><EFBFBD>yf<79>]j<04><>Z<EFBFBD><5A>;<3B><><EFBFBD>2<04>Ļ<00> ƽ<C6BD> ZW<10><><EFBFBD><EFBFBD>t<EFBFBD>' ]-W<1C><>0<EFBFBD>in<69><6E><EFBFBD>c4"]<0E>ߧ\<5C><><EFBFBD><EFBFBD><02><>e<EFBFBD><65><04>i<EFBFBD>u<EFBFBD><75>v+<2B><><EFBFBD>J<EFBFBD><4A><EFBFBD><08>./<16><><EFBFBD><15>%G(1X<> D4<44><34><1A><><EFBFBD>}^8<><12>k<><6B><EFBFBD>w<EFBFBD>c%ֽ<>E<EFBFBD><33><D997><00><02>+<2B><><01><>%<25><03><><EFBFBD><EFBFBD>8y<38><16><>iG<17>/<2F>p7<70><37>i <0C><04>𙭶<EFBFBD>ڣ<EFBFBD>+<2B><<3C>5<EFBFBD><35>@<40><>0<EFBFBD>Q<06>?:<3A>e<EFBFBD><65><EFBFBD>kc[<5B>}F <08>l<EFBFBD><6C>h<EFBFBD>Jmy<6D>[<00>A<18><><EFBFBD>tɄƤ<C984>b.<2E><02><><EFBFBD><EFBFBD>X<>YW<59><57>Ӷ<EFBFBD><D3B6><EFBFBD>ڱTm<54>y <0B>lB<6C>*<1D><>vH<76><48>Y^7<>_<1E>O<EFBFBD>C<EFBFBD><43>k<>[<5B><><EFBFBD><18>S<EFBFBD>(<28><00>VJ<56>%[[<5B>k|<7C>p0?<01><10><>ۦ<EFBFBD>n<EFBFBD><6E>u<EFBFBD><08>i<EFBFBD><69>J<><4A><EFBFBD><EFBFBD><EFBFBD><EFBFBD>+\K<>W<EFBFBD>dF<00><><<3C>
<EFBFBD>h<EFBFBD><EFBFBD>i<EFBFBD>S<?e<>O~<7E><>*<2A><><EFBFBD><EFBFBD><EFBFBD>^<5E><><EFBFBD><EFBFBD>4<EFBFBD>&@!"D<08><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/_<>|<7C><><EFBFBD><EFBFBD><EFBFBD>W#<23><>{<7B>I<EFBFBD>1i <0B><><EFBFBD>x<>k<EFBFBD><6B>p<EFBFBD><70>I~ۦ޵<DBA6> nc<6E><EFBFBD><01>&<26>ϻ<EFBFBD><CFBB><EFBFBD>?<3F>b~c<>0u:<3A><1A>D<EFBFBD><44>}BcR}"<22>5<EFBFBD>& <0C>xg~_1@<40>(<28>bmF<00>Ev<1D>I2"<22>?L<13><>Ro=<3D>0ʍf<CA8D><0F><>"ڙN<DA99>Ms<4D>E.<2E><>pA<><41>Ҝ '<27>lQ&<26>2:|<7C><>ΠK<CEA0><4B><EFBFBD>30<07><>ڜ<EFBFBD>M@-C Q<><51><EFBFBD><EFBFBD>y<03><><EFBFBD>=<3D><02><>D<EFBFBD><44>;<<3C><03><><EFBFBD><EFBFBD>&<26>:J<00><>M<EFBFBD><4D>2<EFBFBD>c<>I<>c9<63><07><>0<EFBFBD>"[<00>ֺی<D6BA><DB8C>)<29>=<3D>:g<00>y<EFBFBD>؟~<7E>p@<40><>7x2<78>ٕ<EFBFBD>)+;<3B>M<EFBFBD><4D><16><><EFBFBD>=j><3E><>[s<02>P<1E>V<><01>2 <0C>U^}H=_<00><><EFBFBD>ݰ<EFBFBD><DDB0>)|<7C>8|v<>L<EFBFBD>X <09>@Һ<>4<0E>UER<><52>=<3D>%<25><>\<5C> c<>?
hGx u<>v><3E><>sH=_M<><4D>t+T:<3A> <0A>{ޑv<DE91>c<EFBFBD><0E><>$<13><><02>)<>갶:<3A>;Wk5<08><>o<><6F><EFBFBD>F?"\<5C><><EFBFBD>k@'<27>N<EFBFBD>+<2B><16><>&<26>Z<EFBFBD>r<EFBFBD><72><EFBFBD><EFBFBD>~J~*5<><35><EFBFBD>R3S<><53>ǚ=<3D>)k<><19>{<7B><><EFBFBD>ޗ/_<><16><><07><>~z<>y<EFBFBD>4IEND<4E>B`<60><>PNG

IHDRnn<00>[&<26>]IDATx<54><78><EFBFBD>T\<5C><><EFBFBD>7.1$L<>^[<5B>#.<2E><><EFBFBD><06><07><14>m\*1H<>w<><77><EFBFBD><1A><>8)$|y <09><><EFBFBD>b<>pd<64>Nk]`<60>r%<0F><><EFBFBD><EFBFBD><EFBFBD>[s<> rr<72><72><EFBFBD>{n<>^ <10>G<EFBFBD><41><C690>/<2F>/<2F><1D><><EFBFBD>d)Sh<53><68><EFBFBD>8<EFBFBD><38><EFBFBD>I[Q_;r5<72><35>YG"<22>Kn#?$/<2F><><EFBFBD><EFBFBD>?<3F><1F><>G<EFBFBD>14g<34><67>g<EFBFBD> r<>ę<EFBFBD><C499>wI#щ<><D189>D<EFBFBD><44>7<EFBFBD> <09>Id~<7E><0E>k<>'J -'<27>ʹ<EFBFBD><06><>H<16>q<EFBFBD><0E><>z2
<EFBFBD><EFBFBD>9 <0B>3<EFBFBD>}vO(%Q<>n<03><>ʙ<>BK&;J<1C>V<EFBFBD><56><0E> KT_
i <0B>X<EFBFBD><><7F>ϻ<EFBFBD><CFBB><EFBFBD>=<3D>?<3F><><EFBFBD>P$<24><><11>&c|<><EF8380><EFBFBD><EFBFBD><EFBFBD><EFBFBD>M~x<>C<EFBFBD><43><14>?`<60><;<3B>7h9<68><39>e<EFBFBD>Iah<61><68><EFBFBD>'<27> <0A><>y<><79>S?4Yh<59>:&<26><>-<2D>$<24><><EFBFBD><EFBFBD>S<EFBFBD><53><EFBFBD>"<22>YxZ<78><5A><EFBFBD>7'ߓD<>}D"s
HǍ|<7C><><EFBFBD><08> <09>A<EFBFBD><41><EFBFBD><EFBFBD><EFBFBD>.<2E><><02> 'o<>(
M kI$<24><><EFBFBD><EFBFBD>w<EFBFBD>-<05><16>EE<>ݷ<EFBFBD>4<EFBFBD><34><EFBFBD><EFBFBD>y&<26>g^$ M |<7C><>ʘJo<4A>G<EFBFBD>Q2Bk<42>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p<0E><>&A볇<41>'<27>Y<EFBFBD><59>$<24>FcB<63><EFBFBD>W<EFBFBD><57>XZ<58><5A>\V<02><19>U<>o<EFBFBD><07><><1B><><1A>whyً<79><D98B>Q<EFBFBD><51>Mu8.<2E><><EFBFBD>ki<6B>c<EFBFBD><00>7J<37>F<EFBFBD>~kP[n(<19>bp3<15>`4ܧ08<30><38><EFBFBD><EFBFBD><EFBFBD>Zv<5A>kIE<0F><>(m<><6D><EFBFBD><EFBFBD><EFBFBD><17>[.o<><6F><EFBFBD>zt<17>\ iJ<69><4A>Rp<52>dy<><79>զ<EFBFBD>c><3E>ZW<5A>Z<><15>Es<45><73>p<EFBFBD><70><EFBFBD>\Y><3E><><EFBFBD>I<EFBFBD><49><EFBFBD><EFBFBD>q2<71><32><EFBFBD>Sp<15><07><>doR<6F><01>@<40><><EFBFBD><EFBFBD><EFBFBD>d%<25> m.8f<EFBFBD>[<5B><><EFBFBD><EFBFBD><EFBFBD>?<03><>iK5\Y<><59>K<> y<>Im<49><13><>Evp<05><><EFBFBD>>&+e^<5E><06><><EFBFBD>l<EFBFBD><v=z<><7A><EFBFBD>\U9ͺ/[98cr/<2F>L<EFBFBD><4C>H<EFBFBD><48><55><DB99><EFBFBD>a<EFBFBD><19><><EFBFBD><EFBFBD>( }([r<><72> @[<0E><><EFBFBD>5<EFBFBD>R<EFBFBD>=iZ<><5A>R<EFBFBD>.YK<59><01><>k<EFBFBD>gz<67>u<EFBFBD>PqW<71><57>~I<05><>7<EFBFBD>Q[<6E>7'a=<3D><><EFBFBD>d%9<07><><EFBFBD>V<EFBFBD><56>ہ<EFBFBD>$<24><>HkP<6B><50><1E>=<3D>}֮S<D6AE>v<EFBFBD>sI<73><49><EFBFBD><EFBFBD>v <20><05>%<25>tL<74>=dP<><50>Yx<59> <0B><>wj݀<6A><0E><><EFBFBD>p8<0E><><EFBFBD>p8<1C><EFBFBD><7F>{<7B>Ju엛=<3D>Y'<27>B<EFBFBD>?z<> <20><>W/<1B><EFBFBD>ШR<D0A8>W<EFBFBD><18><>Y<00>A%Ư+֪<>u <09><><EFBFBD><EFBFBD>\A<><41>{<7B>ܹs<1F>3gN<67><4E>ٳ<EFBFBD>Ch }<7D>g <20>Î<EFBFBD><C38E><EFBFBD>wu<77><75><EFBFBD><<1B><><EFBFBD><E28687>DH <09>ۅ<EFBFBD>e<EFBFBD>?<3F><>b ?h<>{<>2<<3C>Fh<46><68>#(cy<>D<EFBFBD><1C><><EFBFBD><EFBFBD>d"66vPttt<18><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>3g<33><67><EFBFBD>N<EFBFBD>k<EFBFBD><6B><EFBFBD><EFBFBD>k(<28><>Y<EFBFBD>f]<5D><><EFBFBD>t<02><>z0<7A>`<60>h}P<><02>ֿ<EFBFBD><D6BF><EFBFBD><EFBFBD><EFBFBD>1<EFBFBD>ߎ<EFBFBD><DF8E><EFBFBD>c^o<><6F>.6<EFBFBD><EFBFBD><EFBFBD>|<7C><>4<EFBFBD><34>ʘi <0A><><EFBFBD><16><1F><>"<22><><EFBFBD><EFBFBD><EFBFBD>(7
<EFBFBD>y122<32>d2lذA<14>y
<EFBFBD>:t<>`<60>A<EFBFBD><08>܆<EFBFBD><DC86>n<EFBFBD>Ƣ<EFBFBD><C6A2><EFBFBD><15> <0A>e<EFBFBD><65><EFBFBD>Q3s<33>e<EFBFBD>w<EFBFBD><77><EFBFBD><EFBFBD>h<EFBFBD>\yh<79><68>[B"3VԿQ<D4BF><51><EFBFBD>84<38><34><EFBFBD><EFBFBD>
<EFBFBD>L\\<5C><03><> &<26><>7o^<5E><><EFBFBD><06><><1A><>k<EFBFBD>eE<65>b]I)֓E<D693><45>`C<>I7w<37><77><EFBFBD><EFBFBD><EFBFBD>Z<EFBFBD><5A><EFBFBD><><4<><34><EFBFBD>kR;<3B><>U<0F><><EFBFBD><EFBFBD>6<EFBFBD><36>$VM<56>Q[<5B><>|<7C>}1<>9$<24><>il<69>
m<EFBFBD>dp<64><70>K<1C>V<EFBFBD>,<2C><><EFBFBD><EFBFBD><EFBFBD>j<06>g<EFBFBD><67><17>N<EFBFBD>uE<75>U <0C>'Q@<40>X<01>.<2E><><EFBFBD>?<3F><><EFBFBD> <09> <09><><EFBFBD>A<02>k<EFBFBD><6B><EFBFBD>ː<EFBFBD>Ç_<>@"y^S<>q<EFBFBD><1vr<76><1A>eo<65>/<2F><>;<17><><EFBFBD>J<EFBFBD><4A>4V<34>pV<70>Ƥ<EFBFBD>@<40><>Ϫ/<2F><><EFBFBD><EFBFBD>.ӦMK<5F><D384>'|I x&<26><><EFBFBD><EFBFBD>;nN.<2E><><EFBFBD>l<EFBFBD><17>Tٜ,2<><>H<>'[?%MI1!l<><6C>V}s<><73>d<EFBFBD>O&y<>3"<22><6<><36><EFBFBD><EFBFBD><EFBFBD><EFBFBD>&bN<62><4E>p5n<07>,1.<2E>b<01><01><><EFBFBD>@l<><6C><EFBFBD>f<EFBFBD>k<EFBFBD><6B>,<2C>7d<37><0E>'<27>/<2F>?8#<23>¤'u<><75><02>e<EFBFBD>za<7A><61>z7<7A>ơm<C6A1><06>?<3F>=<3D># <0B><><EFBFBD> <0A><>p8<0E><><EFBFBD>p8<0E><><EFBFBD><EFBFBD><EFBFBD>LP<4C>/M<><4D>N<18>;-uF<75>̴Y5<1E>^y<><79><EFBFBD>/<2F>d<EFBFBD>SiA.<2E><><EFBFBD><0E>O<EFBFBD><4F><EFBFBD>=<3D>{h\rnO<6E><4F>@<40>ɥ<EFBFBD><C9A5><EFBFBD>8<EFBFBD>Ѽ<EFBFBD><D1BC>j*<2A>Ϩ)N<>Ȼ<EFBFBD> <0A><>B<EFBFBD>m(Y<>:56!Po<50><6F><EFBFBD>UP<55><50><01><> g6`<60><>h<EFBFBD><68><11>7<EFBFBD>f,<03><><EFBFBD>3$2<><32><EFBFBD><EFBFBD><07>b<62><7F><EFBFBD>
q<EFBFBD><EFBFBD>S<EFBFBD><EFBFBD>x*><3E>{ 5<><35>"@"<22>?چמ<DA86>"hd홵x<ED99B5>'<27>pP<70><50><1F>2“YcCa<43>ؠf<D8A0><66><EFBFBD><EFBFBD>U <0B><>5$<24><>d<EFBFBD><64>#<23><><EFBFBD>s<EFBFBD>q<EFBFBD><71> z7<7A>߈<EFBFBD><DF88>o<EFBFBD>;!e"<22>^h!<21><><EFBFBD><EFBFBD><EFBFBD><<3C><>j <20><>ί<EFBFBD><CEAF><EFBFBD><EFBFBD><EFBFBD><EFBFBD> :<3A>Ek<45>()3M<33>< <0C>t<EFBFBD>Au4<75><34><EFBFBD><EFBFBD>GjXb<58><62>'<27><><EFBFBD>1<EFBFBD><31><1C><>ۢ-<2D>-5<><35>_<EFBFBD><1B><><EFBFBD>s췩_<ECB7A9><5F>r<EFBFBD><72><EFBFBD><EFBFBD>A
?<19>9$9`pz0><3E><><EFBFBD><EFBFBD>'3<><33><EFBFBD>T<EFBFBD>S<EFBFBD>/<2F><1F><>&<26>Z|Pfd<66>6<EFBFBD><36>`<60><19><18><><EFBFBD><EFBFBD>}<7D>#r<><72><EFBFBD><EFBFBD>i<>h<EFBFBD>x<EFBFBD>۰I<1A><>R<>'/<VcÂ<63><C382><EFBFBD><EFBFBD>@<40>A<><41><EFBFBD>c56Z<36>4YfR#&<26><>_<><5F>v<EFBFBD>2<EFBFBD>W<EFBFBD>)O<>#<23><> <1E><><EFBFBD>5vO<76><4F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ;<1E><><EFBFBD>g<EFBFBD>}M q.]'<0E><><EFBFBD>L<7F><4C>(<28>^c<>t<EFBFBD>BJ~<7E>*<2A><03>K
<EFBFBD>3<EFBFBD><EFBFBD>o<13><>`<60><>g<EFBFBD>?B<><42><EFBFBD>d<EFBFBD>'<27><>!<21><<3C><>F<EFBFBD><46><EFBFBD><EFBFBD><EFBFBD>aC<61><43><1A><>,<2C>v<EFBFBD><76><EFBFBD><>6<EFBFBD>wW<77>LT<0E>P<EFBFBD><50><EFBFBD><1A><15><><EFBFBD>?A<>Z<EFBFBD><5A>gsrjlH<6C>D<03><><1A><>`C<><43><>X<EFBFBD>}8 <09>F Fht<68>^<5E><>Xpd<70><64><EFBFBD><16>Ҧg<D2A6><67>Sp<1A><>lh!<21> <0C>6 <0A>ix<69><78>S#<23> <09><><36><C8AA><EFBFBD>R<EFBFBD>jl^{<7B>)QgsK
<EFBFBD><EFBFBD><EFBFBD>N<EFBFBD><EFBFBD><EFBFBD> <0A><j<>=<3D><>ˑqB<71>&<26><><EFBFBD><04><> <1A><><EFBFBD><EFBFBD><EFBFBD>7N`EU?Q<>c<EFBFBD>g<EFBFBD><67>}is<69><14>-D<><44>W<EFBFBD>X<><58>%<25>%Z5<5A><35>O >+<2B><16><><04><>f<EFBFBD><66><EFBFBD><EFBFBD><EFBFBD>D\c<><63><EFBFBD>$<24>mqI<71><49>Ϟ<1E>Ϝ<1E>O<EFBFBD><1A>O<EFBFBD><1A>.<>A8h<38>$2iZf<5A><66><EFBFBD>4|tz:<3A>)K<><4B>g<EFBFBD><67><EFBFBD>ԣ<EFBFBD><12><><07>T<EFBFBD><54><1E>r{7<><37><EFBFBD>^<5E>6<>lX<6C><1B><><EFBFBD> <0C>56j݀'<27><><EFBFBD><49><D1A4>p<EFBFBD>yd:<3A>J<><4A><0E>h<EFBFBD><68>d<EFBFBD><64><19><><EFBFBD><EFBFBD>9<EFBFBD><39><EFBFBD><EFBFBD><EFBFBD>O9<4F>s<1C><><EFBFBD>kD<6B><1F>D<EFBFBD><44>ߌ<EFBFBD><DF8C>]<5D><><EFBFBD>)N<><4E>܌n<DC8C><6E>f<EFBFBD><66>z<EFBFBD>խVc<56>><0E><><EFBFBD>p8<0E><><EFBFBD>p8Z<38><5A><EFBFBD><EFBFBD><EFBFBD><01>?<3F>h^<5E> /<2F><>̘Q<CC98><51><EFBFBD><EFBFBD><EFBFBD><05><><EFBFBD>9D r <09><07><>a<EFBFBD>Y<EFBFBD>Yy<59><79>8j(<28><><16>-N<>"<22><02><><EFBFBD><1A>_lm<6C> <0B>Z<EFBFBD>8p<38><70><EFBFBD>k<EFBFBD><6B>o<0E>k0<6B><30><EFBFBD>E<EFBFBD>p<>yۦTx<54>$<24><><EFBFBD><EFBFBD>!<1D><>Afaf<61><66><EFBFBD><EFBFBD>Z<EFBFBD><5A><EFBFBD>OG?+ '<27>6<EFBFBD>z<>Q<EFBFBD><1C><><EFBFBD>9(<28><>f56{<01>N<1B><>CC z<><7A>G<EFBFBD><47><EFBFBD>G<EFBFBD><47><0E>
0<04><><EFBFBD>Y<EFBFBD>ixn<78>3cf<63><66>Ge! <0C><>4<EFBFBD><34>^<5E><>豮G٧W?<3F><><EFBFBD>Y1<59>j)<29><><EFBFBD><EFBFBD><06><>F<EFBFBD><05><><1B><>p<7F>3ImkVc<03>v<EFBFBD><76> <0B><> zA<7A><41>X<EFBFBD><14><>;Dn'QƁ<51><C681><EFBFBD><EFBFBD>k<EFBFBD><6B><EFBFBD>}<7D><03>"}<05><><EFBFBD>RX%^ό)<29>H첪K<ECB2AA><4B><13>@<40><> <20>ɪ&<26>U<EFBFBD>N<EFBFBD><4E>ScC<63><43>?(m9<6D><>&<19><> <00><><EFBFBD><EFBFBD><EFBFBD>Ν<EFBFBD>R׮z <0B>}<7D><>
<EFBFBD><EFBFBD><0E>ר ̓Ds<>׭<EFBFBD>oʞ)<29><>No<13><>rX^ <20>E<EFBFBD>d<EFBFBD><64>+<07>p<EFBFBD><70><EFBFBD>$<24> Ff<46>F<EFBFBD><46>d<EFBFBD><64><EFBFBD><EFBFBD>LkVc<56><16>سM<D8B3><01>l<EFBFBD><6C><18><>-<1D>󴙨6 5 %PpM<70><4D><EFBFBD>5<EFBFBD>]<5D>O<07>2<EFBFBD><32>U<EFBFBD><55><EFBFBD><EFBFBD><EFBFBD>jl<6A><52>5b<35><62><EFBFBD><EFBFBD>9&18<31>*<0E>0]f<><66>v<EFBFBD><76>
]A ^<5E><>Z/P<><50>$<24><>@&<26><><EFBFBD>.<2E><><1A>8<00>,̷<><CCB7><EFBFBD>Ѻ<EFBFBD><D1BA><EFBFBD>V<EFBFBD> <09><> <20>ɰ8(vM9[IpV˭69ns<6E><0F>1<18><><EFBFBD>KA)t-<2D><><EFBFBD><EFBFBD><01>\<5C><><EFBFBD><EFBFBD><00><18>;٫,<2C>56΁<36>I<EFBFBD><49>Oo<4F>pp<70>(z<7A>Y<EFBFBD><59>a<EFBFBD>-<2D><>5xm<78><03><7<>+<02>5<18><>Q<EFBFBD><51><EFBFBD><EFBFBD>v<EFBFBD><76><EFBFBD><EFBFBD>K<EFBFBD><4B><EFBFBD><EFBFBD>BAS-<2D>3P@<40><>:<3A>-=<12><>J<1B><><EFBFBD>F`56Bp<42>)<29>3<EFBFBD>r<EFBFBD>56I>=h<>ubt<1F> <09><><EFBFBD> '<27><>d<13><01>h<EFBFBD><68><EFBFBD><EFBFBD><EFBFBD>!<21><><EFBFBD>Wv<57>ѽW<D1BD><57>
<EFBFBD>DPJ(<D<><05>wҌ[<5B><>Z<1F>56m<1F>]<5D>p<00><><EFBFBD>`<19>8<EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>L&'Ae<>09<30><07>
<EFBFBD><EFBFBD>u|{H;PS2<53><32>%͠ r<>SX\ ((<28><><EFBFBD><EFBFBD>!y<><79>uXD"s!<21><><EFBFBD>]<5D><>"""<06>u6<75><36> E~<14>vq<76>L<><4C><EFBFBD>1>d֓;H <0B><>-y<>D<EFBFBD>-<2D><14>u<EFBFBD>V;
<EFBFBD>"ykǎnj<6E><6A><17><>4 <20><><EFBFBD>B@>0<>7<16><><EFBFBD>w<EFBFBD><77>p0W:>`<60>m|<7C>į@>; <0A><><1D>
<EFBFBD>wxxx<1E>WNNRr6_8<00><>Gm<47>+<2B>;<3B>(<28>w<EFBFBD><77>T<EFBFBD><54>,<2C>B<EFBFBD><42><EFBFBD>h|<7C>0<>ugܿI<DCBF><49><EFBFBD>j<EFBFBD><01><>ݻwk(<28>4<EFBFBD><34>|Rɵ<52>ꯀU兂<55>6<EFBFBD>ɟu<C99F><75><EFBFBD><EFBFBD>&v<><76>JǷg-8<1E><>׸?H<><48>1j'<27>l.<2E>,#/<2F>|%(<28>I<05><><EFBFBD><EFBFBD>f<EFBFBD>-|3]<5D><>~<7E> <0C>
<EFBFBD>m|ߐ6ІQ<D086>T<EFBFBD>vjq<06>?<3F><>/<2F><><EFBFBD>׶QsBg<42>M<EFBFBD>l_<><5F>vC<76><43>5<EFBFBD>6'BP<42><50>N<EFBFBD><4E>6'J<> E<>SN<53><4E><0E><>g<><67>(X@#<23>[<5B><>vC<76><43>5<EFBFBD>*<2A><><EFBFBD><EFBFBD><01><><EFBFBD>Ǣ<EFBFBD>Z<EFBFBD>IEND<4E>B`<60><>PNG

IHDR<00><00>Zρ%IDATx<54><78><EFBFBD>p<><70>ڇqŮ7efff<66>:3<1A><>23%vа<76><D0B0><EFBFBD>܆<EFBFBD><DC86><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E0A5AC>ϸG3<47><33>uT<75><54><EFBFBD><EFBFBD>w<EFBFBD>g<EFBFBD>7T<37><54>)G<><47>G1<47>b<11>@<40>x<03>P<EFBFBD><18><>U`<1A><>5<EFBFBD><1A>a><3E><><02><><10><><EFBFBD>тF<D182><46> xS<>$<24> <09>&<26>D<EFBFBD><44>q2Oa<18>j\ <0B>I(s<>2<EFBFBD> <09><>Ҽ~<7E>;<3B> C<<3C><>8<><38><EFBFBD>c<EFBFBD>s<>V<>j<EFBFBD><0F>"<01>8%<25>6b܂<62>pB<70>N0 <09>V<EFBFBD>Ց<EFBFBD>&C|<7C>b<05>j<1z0<01>6 <0C>b<00>bx<17>qs<71>C<EFBFBD>k<EFBFBD>6b<36><62><EFBFBD>h<EFBFBD>3X+O$oCr<43>z9<7A>[<11>A<EFBFBD>w-<2D>~SЁG<D081><1A><>V <0B><><EFBFBD><10><03><>Tæƣb܁<62><DC81>b|<7C><> K<>3<EFBFBD><33><EFBFBD>1<>Y:61nG>k<><EFBFBD>6<EFBFBD><36>Z <0C><>m!/<2F><> <0B>lb$p <06><>c.*pm<70><6D>] 1<>Ö<EFBFBD><C396><EFBFBD>_<1A><>Wq<08>1A<>B<16><>Q4<51> Y<><59>Q<EFBFBD><51>N<EFBFBD>%66<36><36><EFBFBD>jt<6A><10><>R<1C>i<16>?<3F><><EFBFBD>-(<28><><EFBFBD><00>"ht H<><48><EFBFBD><EFBFBD><EFBFBD>oUP<55><50><EFBFBD>1<><31>~<7E><>E8<45><38><1F>) xzوD<D988><44><EFBFBD><EFBFBD>V<EFBFBD><56>r,
8H16<>-<2D><>E0<45><30>)<29><>G <0C><>0<EFBFBD><30>D<07>4<EFBFBD><34>8 I<><49>_<><5F><EFBFBD>/<2F>N<EFBFBD>K)G!<1B><>F7<11><>~l<>E<EFBFBD>n<>`<60>{<1F>1<EFBFBD><31><EFBFBD><EFBFBD> <20>eQ<65><51><02><>Q<EFBFBD>P<EFBFBD><50>b,б<>Q<>vC<76>8<EFBFBD><38>HH<48>W<06><>x<EFBFBD>}'<27><>B<EFBFBD>Eug 8<><38><1E><><18>}<10>j<14><>֍<EFBFBD>w<EFBFBD><77>iAQ<17>;<3B><>n<EFBFBD>`<60><><1C>F<06><><EFBFBD>8<EFBFBD><38><EFBFBD><EFBFBD>"<22><><EFBFBD><EFBFBD><EFBFBD>ĸ<17><10>s<EFBFBD><73>
<EFBFBD><EFBFBD>}\<5C><0E>M<EFBFBD>
?6<><36>AX<41><58>b&<26>T<EFBFBD><54><EFBFBD>ɝ-<2D><>8<EFBFBD>al<61><6C><EFBFBD>=<00><><EFBFBD>B<EFBFBD><06><><EFBFBD><EFBFBD>Z>6<><36><EFBFBD>?<3F>I<EFBFBD><49>
<EFBFBD><EFBFBD>q<qE|g<>w
ģ <0A>a<1A><><11> <0A><><EFBFBD><EFBFBD><EFBFBD>B<EFBFBD>
<1E>>Fje8<12> (E1<45><31><EFBFBD>f*wG<17><>(/<2F><><EFBFBD>_<EFBFBD>V<EFBFBD>?@<40><><EFBFBD>12<31>љ<EFBFBD><D199><EFBFBD><03><01><>:3:<3A>ƦU<C6A6> <0B>:R<><52>X<EFBFBD>i<EFBFBD>@T<><54>;pl,<2C>Z,<2C>[X<> <0C><>b<EFBFBD>"<22><>Z<15><>Pq<><71>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD><69>i<EFBFBD>|駏1<E9A78F>ѶÃ<D1B6><C383><EFBFBD><EFBFBD>b;䯸<>U<EFBFBD>HK-<2D>}  <39><1F><>B nH}Z<><5A><EFBFBD><04><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>2==<3D><><EFBFBD><EFBFBD> (<28><1A><>q
Q;A <09> 1<>Q<EFBFBD><51>ɟN<C99F> <09><>c;ݻ<>w<EFBFBD><77>g<EFBFBD>r"D]u<><75>;E<>.<0E><>ؼP<D8BC>3<EFBFBD><33><17><><EFBFBD><EFBFBD>x<EFBFBD><78>x<EFBFBD><78>A<EFBFBD><41><EFBFBD><EFBFBD><EFBFBD>ڿ1<11><>ߔ<EFBFBD><DF94>2.+<2B><><EFBFBD>0n<>[:<3A>:<3A>@<40>GtpN<><4E><EFBFBD><EFBFBD>m<EFBFBD><6D>(:#}<7D>A<>5<EFBFBD>cl<63>:<3A>1qwe<77><65>UK}pup;<3B><><EFBFBD><EFBFBD><EFBFBD> <0C><><EFBFBD>D\<5C>?<3F><>-#<23>kz<6B>t<EFBFBD>3p
<EFBFBD> ڿ<><DABF><04><><EFBFBD><EFBFBD>><3E><EFBFBD><E4BA8E><EFBFBD><EFBFBD><EFBFBD><EFBFBD>2<EFBFBD>n<>X6<58>Mr<4D><72>΀I<17>7'tqؒ<71><D892><EFBFBD><EFBFBD><4<><34><EFBFBD><EFBFBD>Y <0C>b<>v@<40><>M<1D><1A>Ntaj><06>*<2A><>m}<7D>Y4<59>U<EFBFBD><02><>2<EFBFBD>.<2E><><1E><>!
>>3<>q$<24><><EFBFBD><EFBFBD>C<><43><EFBFBD><EFBFBD><EFBFBD>x<EFBFBD>G<EFBFBD><47>;:<3A><><14><><EFBFBD><EFBFBD>\<0F> <0C>?<3F><><EFBFBD>3-:4)Í<10><>0:<3A><>0<EFBFBD><30><EFBFBD><EFBFBD><EFBFBD><EFBFBD><19>G<EFBFBD><47>s"h<>y<EFBFBD><79><EFBFBD><EFBFBD>b|~<7E><><EFBFBD>vw<76>m|<07>I`ϰ<>{ӰJ<D3B0>q<EFBFBD>,<2C>O<EFBFBD><4F>
<EFBFBD>x<0F>!L:8<>!<21>عY<D8B9><10><>M<>5&F1<46> <0C><><6E>!N4m<34><6D>-<2D>݆<18>`<60><><EFBFBD><EFBFBD>30}<7D><1A><>T<04>b<><62>\<5C><0E><>v@<><7F><EFBFBD>ɚ<EFBFBD>\<5C><><EFBFBD>^<13>V1<56>$<24><><EFBFBD><EFBFBD>y<EFBFBD><79><EFBFBD>r<1D>1^ĚX <0A>@<40><><EFBFBD>~<7E><>N<EFBFBD><4E>m<EFBFBD><13><><EFBFBD><EFBFBD><16>{<7B>n@7*<2A><>p<EFBFBD>C<EFBFBD>N C?<3F><>Mkv<6B>˥<1E>GJg%<25><01>;<3B>n<><6E> <0A><>d<EFBFBD><64>D1<44>Xn#<23><>E/<2F><><EFBFBD>`M<><4D>=<3D><>x<EFBFBD><11>MM<><4D>4w<34><77><EFBFBD>U<EFBFBD>Z<EFBFBD>I<EFBFBD><1F><><EFBFBD>z<EFBFBD><7A><15><><EFBFBD><EFBFBD><EFBFBD>+<2B><><EFBFBD><EFBFBD><EFBFBD>͐<EFBFBD><CD90>K<EFBFBD>f<EFBFBD><66><EFBFBD>X;<3B>/
<EFBFBD><EFBFBD><EFBFBD><EFBFBD>k<EFBFBD>ʼ<16><><EFBFBD>:\_ 8<>@<40><04>F_<46><5F>ĸ<><C4B8>$ƹp<C6B9> ?<3F><10>w <1E><><1C>I_|<7C><>y<EFBFBD>]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>m<04><18><>*<2A><06><18>­<EFBFBD><C2AD>o)<29>B<02><>kX<13>L?<3F><>`><3E>:bzz<7A>~<7E><>_<EFBFBD><5F>Z<EFBFBD><5A>jqz<71><EFBFBD><7F> <0B><>7<EFBFBD>6$>ݸ<12><> 1<><31>x<EFBFBD><78><EFBFBD>{<7B><><EFBFBD><EFBFBD>㲲~<7E><>?-@<40>b<EFBFBD>ю#`K<><10>+<2B>v%İ<><C4B0>s<EFBFBD>! <09><>jh<6A>F<G<00>mM|<08><>`S@<<3C><><EFBFBD>|<7C><><05>T<><54><EFBFBD>,H﷓<48>ٺ+<2B><><1E>hyk4><1A><><EFBFBD>B<EFBFBD><42><EFBFBD>Q<EFBFBD><51>mq?<3F>!<21><>|<7C>#e<1E><><EFBFBD>\(<28>3<EFBFBD>t<12>a
<00> <20>y]B<08><>'<27><13>6<EFBFBD>0{<7B>n<19>><3E><>;<3B><><EFBFBD>m<EFBFBD>7 <09><>*8<><38><EFBFBD><EFBFBD><1D>W<07><><EFBFBD>_\<5C><10>}]H['8<>n:<05><><EFBFBD>LKm<4B>p!<15>!<21>B <0A><10><1B><>u<EFBFBD><75><EFBFBD><EFBFBD>p<EFBFBD>KB’<><C7AF><EFBFBD>~<7E><><EFBFBD>yΕ?<3F><>9}<7D>I"<22>N<EFBFBD>a<EFBFBD>N<EFBFBD><4E><EFBFBD><06>=f<>~<7E>,<2C>ac<61><63><05>$b<> 6<><36><15>DʴM<CAB4>A .ڑ3<DA91>e<EFBFBD><08><><EFBFBD><EFBFBD>k<1B><><EFBFBD>ʎ<19><><EFBFBD>L<EFBFBD><4C><EFBFBD><EFBFBD><EFBFBD>ɶU <0C><>^<5E>K<4B>j<EFBFBD>i<EFBFBD><69><EFBFBD>W<EFBFBD><57><EFBFBD><EFBFBD><EFBFBD><06>Z<EFBFBD><5A><EFBFBD>n<EFBFBD> 0U<30><55>M <0B>D<07><><EFBFBD><EFBFBD>m<12>x<EFBFBD>|<7C><><EFBFBD><EFBFBD>HPP<50>d<EFBFBD><64><EFBFBD>_<EFBFBD><5F><EFBFBD>-<2D><06><><EFBFBD><EFBFBD>Gc#i<>-X<>X<00><><EFBFBD><EFBFBD>²<0F><><EFBFBD><EFBFBD>Y\<5C>Ic&<26>!E<45>ջ}h<10>Ĝ<EFBFBD><C49C><EFBFBD><EFBFBD>/<2F><>m<EFBFBD><1E><>#<23><><EFBFBD>DG<44>>b<>M<04>ْ<EFBFBD><D992><1B>Q<EFBFBD><h<><68>H$<24><> <0B><19>@<18>lX<>ݏu S<><18>bj<62>y4<79>憈!8<><38>wZ<77><5A><EFBFBD><EFBFBD><63><D782>bcZ9<5A>F<><46>D~L<>Afy<>"9<02>Bll<6C>4..nX OOϵtt<74><74><EFBFBD><EFBFBD><1D>L<1C>j<EFBFBD>М<EFBFBD>`!<21><07><>:<| <0B>Yf<1B>q<EFBFBD>{zX?8<><38>m1<6D>e<EFBFBD>6<EFBFBD>ȕ<EFBFBD>p<EFBFBD><70>V<EFBFBD>`~XTh`9<><39><EFBFBD>7<EFBFBD><37>12<31><32><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>{<7B><><EFBFBD>%<25><> <02><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>uS<75><19><><EFBFBD><EFBFBD><EFBFBD><b<><12><y<><79><EFBFBD><EFBFBD>q<EFBFBD><71>"<22>z<EFBFBD><03>8óN\<5C><>=<3D><><EFBFBD>b<EFBFBD>dL<1E><>ۗՃ#<23><><EFBFBD> n['<27>-<2D><>[=6<>7<><37>i<EFBFBD><69>P<EFBFBD>N&<26>~ <0A><><EFBFBD>Ԇ"<22>g<EFBFBD><67>LHH<48>_1Eg<45><67>I<><07><16>v2<76><32>Cd<43>U<17>E<EFBFBD><1E>m <1A>7<EFBFBD>`<60><13>1X)<29><><EFBFBD><EFBFBD>>{cVI4<49>+l<><6C>?OX56<35><07><>D#> u<>!<21><><EFBFBD><EFBFBD>C<EFBFBD>Sl߾<6C>=v<><76>Z~<7E><>6`=:SPo<50><6F>t<EFBFBD>1<EFBFBD>#y<><79><EFBFBD>3G<><47>n<EFBFBD>x<EFBFBD>H]]i^<5E><>md<6D><64><EFBFBD><1C><>}#GD<47>%8f<38>f;<3B><><EFBFBD><EFBFBD>\<5C>
<EFBFBD>f<EFBFBD>ج\<5C>zV#<23><><EFBFBD><EFBFBD><>MٺБ-<2D> <20>`<07>t<EFBFBD> <0B><1D> bs <0B>>nl<6E><10><><EFBFBD>N<EFBFBD>Ļ%e&cә<63><D399><EFBFBD>Sp<53><70>7<EFBFBD>E<EFBFBD>l<0E><06><><EFBFBD><EFBFBD>Y<<3C><19>t<>\B<><42>O<EFBFBD><4F><19> <0C><><EFBFBD>P\<5C><>B<EFBFBD>G.<11><>SO<53><4F><EFBFBD>j7<37><7F><EFBFBD>`M<>x<EFBFBD><78>b2<62><32>R$<24><>N<EFBFBD><4E><EFBFBD><EFBFBD><EFBFBD>%<25><>.<2E><>^<5E><>F<17>R<EFBFBD><52><EFBFBD>c<EFBFBD>xp<78>Hl<48><6C>dy<><79>q<EFBFBD>P<1B><><EFBFBD>a<14><>Z<EFBFBD>ݢ<EFBFBD>}<7D><00>><3E><><C9A4>,|<7C>`<60><>SJ<53><4A>Ńsv<73>7<EFBFBD><37>u<EFBFBD><75>6<EFBFBD>Z<EFBFBD><<3C><>肣U<E882A3><55>/֬Z~
fb<EFBFBD><EFBFBD>+E<1A>*[ȣ<>#<23>@^<5E>۟<14>+A<> O<>0<><1A>N/<2F><>^Z<>̩<EFBFBD><CCA9> <0A>R<EFBFBD>8<EFBFBD>;ұSJ<53><4A>e<EFBFBD><65><16><><EFBFBD><EFBFBD><EFBFBD><56><D5B1>I՝R<D59D>1:0>&<26>)%<25>']<5D>d7r,<2C><>L4<4C>R:v<><76>=<3D><><EFBFBD>P;8v<38>Kp<4B>W#M_2<5F>n<>Qg'Lm`<60><>K<EFBFBD><4B>dtg'<27>`<60><>{<7B>M<><4D><EFBFBD><EFBFBD><EFBFBD>;<08>1:0<1F> <0C><>K<EFBFBD>&m<>~'<27><19><>ܬSJ" <0B>Ɏ<EFBFBD>V<EFBFBD>M<EFBFBD>z<EFBFBD><1D><><EFBFBD>S<e<>}_P<><50>a<EFBFBD>,<2C><>X<EFBFBD>;<3B>9]X]}Y <20>p<01>F<07>D?<3F><><EFBFBD><EFBFBD> 3<08><><EFBFBD>X4Y<34>xq<78><71><EFBFBD>L^2<>91`<01><><EFBFBD>dG<64><47><EFBFBD>T<EFBFBD>wi<77><69>o<EFBFBD><6F>3۷L<DBB7>T<EFBFBD><54><EFBFBD><EFBFBD><EFBFBD>Z<17>#V<>
st`^<5E><>M2<4D>
<1A><>Z<EFBFBD><5A>H<EFBFBD>Ⲁ\.H+<2B>;<1A><><EFBFBD><EFBFBD>ư<EFBFBD>lX<>#<23>Ş<EFBFBD>n<EFBFBD><6E>c3,r<><72>d+<17>˭]{_<> <09>$<24> <20><><EFBFBD><EFBFBD><EFBFBD>ȣ<EFBFBD><C8A3><EFBFBD><EFBFBD><6C>n׺|0 <09><07><>w<EFBFBD>F^gs<14>Z<EFBFBD><5A><EFBFBD><EFBFBD>CK<43>{69<36><39>i<EFBFBD><69>;<3B><EFBFBD>Xn^<5E><>ݼ<EFBFBD><DDBC>&<26>+?h <0A><><EFBFBD><03>я<EFBFBD>X+<2B><><EFBFBD><1A><> L7r'<27><><EFBFBD>-xk<07><>$<24>Ϯ
)<29><>4VLpi(43<15>s<EFBFBD><73><EFBFBD>.X<1D><><EFBFBD>!<21><>[<5B>И<EFBFBD><D098>] <09><><EFBFBD><EFBFBD><EFBFBD><03>2<EFBFBD>,3<><33><16>]#<17>7<EFBFBD>@<40>o^<5E><><EFBFBD>8<><38><EFBFBD>$<24>#<23><><EFBFBD>%e3}<7D><><EFBFBD><EFBFBD>:<3A><>m<EFBFBD><6D><EFBFBD>gW<15><16>s<EFBFBD><73>PWI<57><49><EFBFBD><EFBFBD> <0A><><EFBFBD><EE9DA4>"<22>W[t`}:<3A>_<EFBFBD>wH<77><48>,<2C><>H<EFBFBD>}<<3C><>RT~/+<2B><><EFBFBD>Y<>0<EFBFBD><30><EFBFBD><EFBFBD>י<><16>-<2D><>{)B<><42>Eo6F<36>_<EFBFBD><10>^<5E>_<EFBFBD><5F>(z<><7A><EFBFBD>md&<26>"ㅥg<7F><06><0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD><04><1B> <20>p<EFBFBD><<08>E<EFBFBD>w<EFBFBD><77><><DCB6><EFBFBD>̃<EFBFBD>d<EFBFBD><64><EFBFBD><EFBFBD>[;<3B>J(<28>*<2A>d<EFBFBD><1E><>cfe<66><1F><>vcش<63>
<EFBFBD><EFBFBD><EFBFBD>~<7E>S<EFBFBD><53><EFBFBD>M<EFBFBD>Q(b<><62><EFBFBD>T<EFBFBD> ?<03><><EFBFBD>!<21>, <20> <09><>ѧ<EFBFBD><D1A7><EFBFBD><EFBFBD><11>d<EFBFBD><64>`<19>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>w<EFBFBD><EFBFBD>,:<3A><><EFBFBD>:<3A>W<EFBFBD>L<><4C>m<EFBFBD><6D><EFBFBD>܇<EFBFBD>inp7!<10>A,DJ<44><4A>Q<EFBFBD><51><EFBFBD><EFBFBD><EFBFBD>a<EFBFBD>z33*30<33>2<13><>H<EFBFBD><48><EFBFBD>q<>|(<28><><EFBFBD><EFBFBD>z<EFBFBD><7A><EFBFBD><EFBFBD>L<EFBFBD><4C>T<EFBFBD><54><EFBFBD>Qއp<DE87><70>!l<>G&<26><><EFBFBD><EFBFBD>=<3D><>J<1D><><EFBFBD><EFBFBD><EFBFBD>; ^<5E><>H<EFBFBD>+S<><53>uj<>oG<6F>L#3Psa7<61>)<29><00><><EFBFBD><EFBFBD><EFBFBD>X;<3B><><18>OL<4F><4C><EFBFBD><EFBFBD><EFBFBD>+<2B>g<EFBFBD><67><EFBFBD>C<06><>1<13>| "<22>vT1<18>{<7B>/<2F><><EFBFBD><EFBFBD>gs<67>C<EFBFBD><0E><>E`M<>@Ѷa<D1B6><61>F<EFBFBD><46>g<EFBFBD><67><EFBFBD>˩<EFBFBD>z<EFBFBD>ڴ+iz<69>_I<5F>_<EFBFBD><EFBFBD>'<12><><EFBFBD><E684B0>?<3F><><EFBFBD>c<EFBFBD>aO<61>;<3B><>Z<EFBFBD>=<3D>8_<><5F><14>=T/<2F>As<41><73><EFBFBD><EFBFBD>d절 2<><32><EFBFBD>X<EFBFBD>Rla<17>x<>Է<EFBFBD><17>֫<EFBFBD><D6AB><16><>0<16><><17>A <20>fpb<70>.@<40><>w<EFBFBD><77><EFBFBD><EFBFBD><03>|<7C>dW}ҘIxH<78>w<>n ijpL E<08><>{<7B><>%(pK<70><16><><EFBFBD>'=<3D>Ul<55><6C><EFBFBD>n+߆<>ɓbl<62>3<><33>T6~<7E>a<EFBFBD><61><EFBFBD><EFBFBD>d<EFBFBD><64><EFBFBD>[ȸRu<07>.8R<EFBFBD><EFBFBD><EFBFBD>7<EFBFBD><EFBFBD><EFBFBD>0`g<08>ە<><DB95>O<> <0B><>7<EFBFBD><37><EFBFBD><EFBFBD>X<EFBFBD>8<EFBFBD>Eb<><62><EFBFBD><1D><>Ǻ<EFBFBD><C7BA>F g15<31><<3C>CsC<73><43>u<EFBFBD>DS<44><04><><1E>k<EFBFBD>/<2F><>A:<17>Jq<4A><71><EFBFBD><EFBFBD>ى<EFBFBD>j<EFBFBD><6A><EFBFBD><EFBFBD>z~q<> =<3D><<3C>%n.ی<>m<><C49A>r<EFBFBD><EFBFBD>הgr<67><72><EFBFBD><02>h<EFBFBD><68><EFBFBD><EFBFBD>yu<79>0<EFBFBD><30>ۇ<EFBFBD><1F><>a<EFBFBD><61><EFBFBD><EFBFBD>X@M<><4D><EFBFBD>%o5IM<49>,<2C><>"<22><><EFBFBD>Raj<><6A><EFBFBD><07><>:<| <0B>Yf<1B>q<EFBFBD>{z蟮QL<51><4C><EFBFBD><EFBFBD><1A><><EFBFBD>V<EFBFBD><08><>[K-<2D>Pp<50><70><EFBFBD>_,z_)zE<7A>W<EFBFBD>^<5E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>|]<5D><><EFBFBD>.<2E><>"<22><><EFBFBD> )<29> <20><>k<EFBFBD><6B>T<EFBFBD><54><EFBFBD><EFBFBD><EFBFBD>Q<><51>t<EFBFBD>-<2D><>U<EFBFBD><55><EFBFBD> <0C><>B<EFBFBD>A<EFBFBD>O-<2D><>c<EFBFBD><63>b)<29><>K<EFBFBD>X<EFBFBD><58>,o'<27>#-<2D><14>}Y>8<>F<17><50> ,-7I?<3F><>S><3E>ˍV.<<3C>:+<2B>M<EFBFBD><4D>!<21>O<EFBFBD>}邓<><E98293>l<EFBFBD><6C><EFBFBD><EFBFBD>W4<7F>K<EFBFBD>^<5E>V[<5B>"<22>F<EFBFBD>s<><73>T <09>R艀ss<73><73>b<EFBFBD><62><1A><><EFBFBD>ԸT<D4B8>T<EFBFBD>e<EFBFBD>eZ<65><5A>-E<><45><EFBFBD>P<EFBFBD><50><EFBFBD>Rha<16>8<EFBFBD><38>l<EFBFBD><6C>6T<36>͎pz<70>)&{Ψ=<3D>SP<53>k<EFBFBD>Z<18>ya+ <20>%OC<4F>uo<75><6F>h<EFBFBD><14>>NE<4E><45><EFBFBD><EFBFBD>Y7<59><37><EFBFBD><EFBFBD>| F;<3B>^@c<>|ĥ<><C4A5><EFBFBD>DWζ<01><>ԞS0<53> <09><><18>-~КE<D09A>b<EFBFBD><62><EFBFBD>58?۾Ҷ:<3A><><EFBFBD>6@[0'?<3F>b N<> <0A>1<EFBFBD>]<5D>]<5D>t<EFBFBD>v<EFBFBD>qF<71><46>gf<67><66>:$m<>v.<2E><> l<>E@ <0B><70><C5B1>ʺ!y<04><>!<21><><EFBFBD><EFBFBD> n<><6E><EFBFBD>(<28><>=<3D>Ń<EFBFBD><C583><EFBFBD>?<3F> <0B>%;"f<>m<EFBFBD><6D>{h<><68>}о"-<1F>u<EFBFBD>K5<<3C><><EFBFBD>э<EFBFBD>87<38>y(<17>MH<48>1<EFBFBD><31>l<EFBFBD>9l<1F>F<EFBFBD><46>-+<2B><>d<><64><1D><>A?,<2C>ۿ<>^w<>;<08><> <09><>/<2F><05>`<60><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>v<EFBFBD>HU<48><55>ԡ8,uX<75><58>S<EFBFBD><53><EFBFBD><EFBFBD><EFBFBD>:"m<04>L<EFBFBD><4C>6<EFBFBD><36>\<5C><07><><18>0><3E><>%<25>"b<><62><EFBFBD>٨<EFBFBD><D9A8>v<EFBFBD>w<EFBFBD><77><10><>;q,8<>}<0E><>}<7D>G6<>C<EFBFBD><<3C>v<><76><EFBFBD><EFBFBD>Y7<59><37>qcK<63>hLFW<46><57><EFBFBD><EFBFBD><EFBFBD>X<EFBFBD>A<EFBFBD><62><D399><EFBFBD>-<2D><><EFBFBD>,<2C>6/<2F>aA5<41><35>J?C<>7u<><75><1B><1B><><EFBFBD>l<EFBFBD><6C>`j+I<><49>]<5D>:$9`<60><>;bǤj;%u<><0E>w<EFBFBD>6<EFBFBD>m<EFBFBD>6і<36><D196><EFBFBD>W<EFBFBD>Jha<68><>R<EFBFBD><52>w<> <0C>UiX4<58><34> &=<3D><>{
<EFBFBD><EFBFBD><EFBFBD>6<EFBFBD><EFBFBD><EFBFBD>K<EFBFBD><EFBFBD><EFBFBD>a<EFBFBD>`<60><>|p֍<70>Є<EFBFBD><D084><EFBFBD>Y<10>ЅƠ<D085>W<EFBFBD>k*6&ۗ<>י<>c<EFBFBD><63><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!<21><><EFBFBD>,<2C><06>ۈ<EFBFBD><DB88>˪Z<8<><38> <0B>^<5E><><EFBFBD>e<EFBFBD>3"<1B>h<EFBFBD>y!<21>J1gΟ<67>:<3A><><EFBFBD><EFBFBD><EFBFBD>Θ\<5C>t<EFBFBD>z <0A><><EFBFBD><EFBFBD>,<2C><><EFBFBD><EFBFBD><17>)<29>N<EFBFBD>q<EFBFBD><71><EFBFBD><EFBFBD><EFBFBD>}о<><D0BE><EFBFBD><EFBFBD>y.<2E><>O)<29><><10>1<EFBFBD><31><EFBFBD><EFBFBD>N)<29><><16><><EFBFBD>+!`F2<46><32>7<><37><EFBFBD>TtY.<2E>E<EFBFBD>kp=I<><49>F'<27>-<2D><><EFBFBD>EB<45><42><05><> <20>W˯R<44><D1A2>',<2C><>o<><6F><EFBFBD> JX4<58>/<2F>m׮R<D7AE><52><EFBFBD>cl<63> 7<><37><EFBFBD><13>6<EFBFBD>hrV<72><56>Ttg'<27>`<60><>{8hY}X@t<>(<28><>qr_<72><5F><EFBFBD>;5<>l<EE93A0>eɂ)<29><1E>RR<52><52>T<7F>}<7D><><EFBFBD><EFBFBD><EFBFBD>,|<7C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><0E><>s2J{<7B><> - <0C><11>沀N:<3A>k<EFBFBD>%<25>M<EFBFBD><4D>1zs<7A><73>b<>[4<><34>\  pp<70><70>O<EFBFBD><4F><19>}Y@<40><EFBFBD><E28699>ޠe=<3D><13><><EFBFBD>,<2C>A<EFBFBD><41><10><>Ƈ<EFBFBD><C687>Ž<EFBFBD>c<>4Az<41>!<21>u<EFBFBD><75><EFBFBD><EFBFBD><EFBFBD>==<3D>K<EFBFBD> <09><><EFBFBD>Y<>9.|<7C><>e<EFBFBD><65>.<2E>+Qx7;8<><38>w\<5C>9.|g}2<>Wxs<78><73><EFBFBD>b<EFBFBD>R<EFBFBD><52>(o<>l,<2C>s<EFBFBD><73>R<EFBFBD>j<EFBFBD>\<5C>f<EFBFBD>Y<EFBFBD><EFBFBD><E7A38F>+<2B><18><><EFBFBD> <0B>47g<37>o<EFBFBD>J<EFBFBD><4A><03><1A>B<12><>]<5D>tdVf?<3F><>w<>ALz<4C>x<><78><EFBFBD><EFBFBD><03><1D><><EFBFBD><EFBFBD>,<04>fb<66><EFBFBD><7F>˳<EFBFBD><17><>Vţ<>?<3F><>m <0A>(9}?<3F>>]<5D>֮<EFBFBD><D6AE>4<EFBFBD><34>n7<6E><37>cw<63><77>x/<1E><><01>ƻ<EFBFBD><C6BB>v<0E><>P<EFBFBD>s,|kWy<><79><02><>w<EFBFBD><77>Q.<2E>,t<>b<EFBFBD>4<EFBFBD>"7/M<>r<EFBFBD><72><07><><EFBFBD><EFBFBD>塐d<E5A190>#<23><>D<EFBFBD><44>A<EFBFBD><41>/H<><48><EFBFBD>3<07><><Az<41>d<EFBFBD><00>X6<58><36>}̌<>RUh훗G=}<18><>q<EFBFBD><71><EFBFBD>V<EFBFBD> n^><3E>m<07><>f<><66><EFBFBD>~+<2B><><EFBFBD>x<>H<EFBFBD>Fy<46>`{<<3C> <20><>$<24><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ș<EFBFBD><<3C>t<EFBFBD>g<EFBFBD>c+<2B><EFBFBD><E689B9>7=x<1F>A<EFBFBD><41>>yp<79><70><EFBFBD>pV<70>\]6 הM<D794><4D><EFBFBD>\<5C><>W
z<EFBFBD><0F><><EFBFBD>[k Y<1E><>kf<6B><66>P<EFBFBD><50>(7d<37><64>#<23><>sꗝF<EA979D>vN<76>tT<74> <09><><EFBFBD>s<EFBFBD>@<40><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><16><>z<EFBFBD><7A><EFBFBD>~<7E><><EFBFBD>ݱ<>');<3B><05><><EFBFBD>9<14><15><> I<><49>U!Es<45>Ɗ . <0A>Fc<46><63><EFBFBD><EFBFBD>iM<69><4D><EFBFBD><EFBFBD>l<EFBFBD><03>T
<EFBFBD><03>e<EFBFBD><65><EFBFBD>pV<70><10>+|_*{_$_(<28>H<EFBFBD> <0A>Rd<52>i<EFBFBD>;X<><58><EFBFBD><EFBFBD>z<EFBFBD><7A>.<2E><>j<><6A><EFBFBD><EFBFBD>P{9%?2"<22><>
@<40><><EFBFBD>
/Ƶƪ?z<><7A>,<2C>3<EFBFBD><33><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/V<><76><C78B><EFBFBD>ݡB+<2B><>`e<>W#+7<>H<EFBFBD>[<12><><EFBFBD><EFBFBD><EFBFBD><EA92B2>x<EFBFBD>yz<79><7A><EFBFBD>6<EFBFBD>\<5C><><EFBFBD><EFBFBD>U<EFBFBD>ֹ<EFBFBD><D6B9><EFBFBD><EFBFBD><15><><EFBFBD><EFBFBD> <0B>ˢ<EFBFBD><CBA2>,Re<52><65>߫d<0E>r<EFBFBD>v<EFBFBD><76>J<EFBFBD><4A><EFBFBD><17>,<2C>D<EFBFBD><44><EFBFBD>ѳ=>3<><33><EFBFBD>i<EFBFBD><69>O9P<39>BrD<1F>$<24><>#<23><><EFBFBD><EFBFBD><EFBFBD>B
<EFBFBD><11><>I<><49>U<EFBFBD>y<EFBFBD>8<12>V#<23><01><>M!E<><45><EFBFBD>2<32><7F><EFBFBD> <03>
<EFBFBD>^q<>yl<79><6C><EFBFBD><<3C><>"T<>_<EFBFBD>fc<66><63> <0C><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E><><EFBFBD>p8<0E>þ}<7D>:pb<01><><01><><EFBFBD><EFBFBD><05>5<EFBFBD><02>-<02><><EFBFBD>ˀ<><CB80>Z<EFBFBD>u<><75><EFBFBD><EFBFBD><EFBFBD><08> <00><1A><>l<1C>R%<25><><<3C>;<3B>#3z̬ <0C><>3<EFBFBD>n <0C><>zC<7A><43>_<EFBFBD>o|Jt<4A><74><EFBFBD>><3E><>~<7E>6<EFBFBD><36>%<25><16>O<EFBFBD><4F><EFBFBD>CB<43>j<EFBFBD>v<EFBFBD><76><EFBFBD><EFBFBD>722<32>j<EFBFBD>n<<3C><><07><><EFBFBD><EFBFBD>1vv<76>HO<1E><11><>ll<><6C><EFBFBD>O<04><>Q<EFBFBD>5<EFBFBD>%<25><01>pf<<3C><>5<EFBFBD>7<EFBFBD>L<EFBFBD>5<EFBFBD>ƾs<C6BE>#S<>5<EFBFBD>=<3D><>J<1D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>&<26>KR(<28><><EFBFBD>o<EFBFBD><6F>޽<EFBFBD>Z<EFBFBD>e &<26><1D>4'4@b<><62><1A>H<EFBFBD><1B><>P<EFBFBD><50><EFBFBD><EFBFBD><><D28F>!8<1B>-<2D><>I<><04><>g<EFBFBD>.<2E>{<7B>20<32><1F>P<EFBFBD><50>菰'<27>6<><36><EFBFBD>r<EFBFBD>Wֿ<57>_u<5F><75><06><><EFBFBD>ޓ<EFBFBD><DE93><EFBFBD>".<2E><><17>n<EFBFBD>ؒ<EFBFBD><D892>ë<EFBFBD><C3AB>^<5E><><EFBFBD>FY<46><59>ט>j<14><><10>n<>W<EFBFBD><57><EFBFBD>
<EFBFBD>Z;8X <1F><>`<60><>ק<>׾<EFBFBD><05><17>~CB<03>4<EFBFBD><06><>RU<52><55>U<EFBFBD><55><EFBFBD>3@<40><><08>2<EFBFBD><03>}<7D>4<EFBFBD>*<2A><><EFBFBD>0`<60>~<1F>x<><02><17>+<2B>z<EFBFBD>I^ܰ<>J<EFBFBD><4A><EFBFBD><EFBFBD><EFBFBD>Nx<03>lDp<44><70><>J<>B<00>G<1B>z[<5B>xp<78><70>k<EFBFBD><6B><EFBFBD>Ǣӽ<C7A2><D3BD><EFBFBD>r<EFBFBD> <20><>n 0<>?<3F>k<EFBFBD>39<33><39>1/<01>  <0C><>:ld v<1B>[?<3F>ӣf<D3A3>d+@Q<>D<EFBFBD><44><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>(f<>Ypu5A <20><00>mfpo[0<><30>H<EFBFBD>o<EFBFBD><6F>kG^3<><33>V<EFBFBD>_<EFBFBD>N3u<33>-,C_<43>fb<>E3<> <52><C9BD>J<EFBFBD><4A><19><><EFBFBD>ٽ<EEA0B9>4<EFBFBD><05>[c<><63><EFBFBD>v<EFBFBD><00><><EFBFBD>#<23>o<<00><>
Z(<28><><EFBFBD><EFBFBD>4g<34>B<EFBFBD>T<EFBFBD>{<00>'<00>_58!:9@<02>=6<><36><EFBFBD>*<2A>3<EFBFBD><33><EFBFBD><EFBFBD><EFBFBD><17><><EFBFBD><EFBFBD><EFBFBD> e<><65><EFBFBD>^<5E><>f<EFBFBD><07>SK<53>F"<22> <09><><EFBFBD>X<><EFBFBD><E298AF><EFBFBD>v<><1D> <0C>c<EFBFBD>7SP<53>k<EFBFBD>~<06><><14>+st<73><74><EFBFBD>c<EFBFBD><63><EFBFBD>=<3D>s<0F><><EFBFBD>H<EFBFBD>7Y<37><59>N37<33><03><>T|<7C><>-<2D><><EFBFBD>=<3D>-v{<7B><><EFBFBD>B<EFBFBD><42><EFBFBD><EFBFBD><04><><EFBFBD>:<3A> <0A><>,][<5B>L#b;G:<3A>X<><58>X<EFBFBD><58><EFBFBD><EFBFBD><1E>u( <0C><> <09><><EFBFBD><EFBFBD><EFBFBD>H<EFBFBD><05>x<EFBFBD><1C><><EFBFBD><01><><EFBFBD><EFBFBD>g}<7D>^ϐ':t<><74><EFBFBD>
<EFBFBD><EFBFBD><EFBFBD>1<EFBFBD>Bw<08>$N<>zn<>ܪ}#<23>\<5C><> н<>sY<73>|Q<>oDp <0B>B<EFBFBD><42><EFBFBD><E79798><EFBFBD>P<1E>ۘ<EFBFBD><DB98>v<EFBFBD>w<EFBFBD><77>7<EFBFBD><37>B!<1A><> <09>=<3D><10>l<EFBFBD>O<><4F><EFBFBD>y<EFBFBD><79><EFBFBD><EFBFBD><EFBFBD>JhL<68>9<EFBFBD>$<24>N` <0C><00>L<EFBFBD><4C>Vw<56><77><EFBFBD>8<>_cu<63>'a<03>c<><63>l<EFBFBD><6C>zb<7A>"%`!<21><>R<EFBFBD><52>w<1D>S$E, <0B><1B><><EFBFBD><50>E < p<><70>~<7E><><EFBFBD><EFBFBD>la <0C><><EFBFBD><17>G<EFBFBD><47><EFBFBD>Ħ!<21><><EFBFBD><EFBFBD><EFBFBD>k<EFBFBD><6B><EFBFBD>{<7B><>N<EFBFBD>c<EFBFBD>,<2C><>4<EFBFBD>:<3A>|\<5C><><EFBFBD>e׵H$o<><6F>O<00><>k<EFBFBD>o<EFBFBD><04>5X<18><><EFBFBD><EFBFBD>[<5B><><EFBFBD>vDe<44>@p<>$<24>+<2B>g<>x<><78><EFBFBD><EFBFBD>Ul<12><>WH<14>Jv <0B>`EA-<2D><>op¢Ɏp<C98E><70><EFBFBD><EFBFBD><1B>F<EFBFBD><00>Jl<4A>TjBz<42><7A><EFBFBD><EFBFBD>I!<21><00>Ev/<2F><><EFBFBD><EFBFBD><EFBFBD>5<EFBFBD>2]H<>L<EFBFBD>ݣ<DDA3><7F><EFBFBD>ς<EFBFBD>X#`-xB<00>q<><71>D<EFBFBD>u`<16>P<EFBFBD><50><EFBFBD>L<EFBFBD>}<07><>9<19><>~<7E><>,EW<45><12>)<29>I<EFBFBD>T[y<>,k%<25><>9J&<00> .|<7C><><02>vY<>A<EFBFBD>=<3D>{<7B>t<EFBFBD><14>߰<0E><><18><><EFBFBD>66; <0C>x<EFBFBD>J{_<1C><><02><>lV<><56>/K6wY^<5E>»<EFBFBD><C2BB> <17><><EFBFBD>@<40> <09><><00>)<29><>Ǚnm<6E>LO<4C><4F><EFBFBD><EFBFBD>A;<3B><>j<01><><EFBFBD><EFBFBD>ʄV^<5E>|<7C><>̚v<CC9A><76><EFBFBD><EFBFBD><7F>7n<37><6E><13>ی<> 2<><32>U !<21><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>K0<4B><30><EFBFBD>8w<38><77>.<2E><>@<<3C><10><1A><><EFBFBD><]<5D><>s<EFBFBD><73><EFBFBD>@塑}<7D>
[<5B><>@<40>#<23><><EFBFBD><EFBFBD><EFBFBD>un<75><1A><4F>v<EFBFBD>>~M<07><>;<3B><>1<EFBFBD><1B><>a<EFBFBD>`<00><03><04><><EFBFBD>a<>d<EFBFBD><04><><EFBFBD><EFBFBD>b<EFBFBD>q<EFBFBD><>U\ <1D><><EFBFBD><11>t<EFBFBD><74><13>^_<><5F><EFBFBD><EFBFBD>S<EFBFBD>=<3D><07>k<EFBFBD>*<2A><><EFBFBD><EFBFBD>*2ވy<DE88>7/<1F><>w<><77>$<24>!v2<9<>Q<EFBFBD>P*<2A><><EFBFBD>k_<h<>JC<4A><05><>`?<3F>9<EFBFBD><39>#{c앭<63>7są(txՁ<1D><><EFBFBD><EFBFBD><EFBFBD>M<EFBFBD>^ZR'<27>P<1E>1<EFBFBD><31>P<EFBFBD><50>(7d<37><64>#<23><1F>AS<41><53><EFBFBD><EFBFBD>S4{<7B>i<EFBFBD>LA<4C>y$<24>@aN<61>vX2<58>?<3F>^8ϭ<1C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><0F><><19>9};<3B><01><>q<1A><0E><>J <0A>4<12>n<EFBFBD><6E>s<EFBFBD><73><EFBFBD><EFBFBD><EFBFBD>v<EFBFBD>><3E>·b:<3A>\<14>X{J<><4A><EFBFBD>g<03>\<5C><>~&<26><><EFBFBD><EFBFBD>pI<70>P<><50><EFBFBD><EFBFBD>><3E><><EFBFBD>)<29><><EFBFBD><11><><EFBFBD><EFBFBD>-<2D><>(D<><44>d<EFBFBD>`Az<41>1P?<8:m<><6D>Y;<3B>d
w<EFBFBD>oc<EFBFBD>O<EFBFBD><EFBFBD><EFBFBD><EFBFBD>E&<26><><08><><EFBFBD><EFBFBD>I<EFBFBD>HZHq<48><71>RNtϊ=<3D>`<60><><0F><>z}<7D><><03><>'$G<>qJ<71>92<39>j}pؽ<70><D8BD><EFBFBD> +<2B>3<EFBFBD><33>u0<75><30>س<10>a<EFBFBD><61>/<08><><EFBFBD><EFBFBD>T,[<5B>Gw7<00>k<EFBFBD>;K<>( <0C>϶m;γ<>^<5E><><EFBFBD><EFBFBD>ؙ ׶w/׶m۶m<DBB6>{<7B><><6C>rkz<6B>u<EFBFBD><75>?<3F><><EFBFBD><EFBFBD>=<3D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>^e<><65>,<2C>]<5D>'i<>"/<2F><><EFBFBD><EFBFBD>:f#sJ-<2D>EI<<3C>i Ν<><12>-}<7D>U޿!̓ЯB<D0AF>
Pjy<EFBFBD><EFBFBD><EFBFBD>''<27>r7<72><37><EFBFBD><0F><><EFBFBD>G<EFBFBD><1E><07><>̱P<CCB1>N0O<30>T<EFBFBD><54><EFBFBD><EFBFBD>A8/7J<37>̓paf{<<3C>x<EFBFBD><78>3<EFBFBD><33>d<EFBFBD><64><0F><>d<EFBFBD> eJ<65><4A><EFBFBD>2<>.(ԼNhxrȼaNM-<2D><><EFBFBD><15>d<7F><64><EFBFBD>z<>s<>!<21><><EFBFBD><EFBFBD>P<EFBFBD>T*Հ<>d29<32><67>k<1C><><EFBFBD><06><>W<14><><EFBFBD>\<5C><>Q.1ՙ;<3B>^<19>0
<EFBFBD>!<21>Y<EFBFBD>bj&<26>yJ4<4A>#<1A>輺7Ȕ<37>)<29><><EFBFBD><EFBFBD>3<EFBFBD><33><EFBFBD><EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD><12><>}<7D>ܫ<>?*<2A>T әW<1C>(<28>?<3F>XDt<07><><EFBFBD><11><><EFBFBD>;w~Z<><5A><EFBFBD>8{<7B><><EFBFBD><EFBFBD>+P<><50>%L]C<><43><EFBFBD>Ү<><D2AE>^|u=<3D><>4<EFBFBD>Ce<43><65>"8<>TqX<06>Ԕ <09><>tuڍP<DA8D>6<EFBFBD><36><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>=pNg<4E><67>$l<>?EB<45>y-ݽ<><DDBD><EFBFBD>!<21><EFBFBD>g/DS<44><53><EFBFBD><EFBFBD>*<07>*C<>3<EFBFBD>H<EFBFBD><48>xt<78><08><>YN<59><4E>2<EFBFBD><32>!3<><33><EFBFBD>_[ӵ0<14><><EFBFBD>%<25>Y<06><><EFBFBD>L<EFBFBD>A<EFBFBD><41><EFBFBD><EFBFBD>P<EFBFBD><50>l6<6C><36><EFBFBD><EFBFBD>5<EFBFBD><35>_<EFBFBD>z<EFBFBD>I[<5B>ܞX<DC9E><58><EFBFBD><EFBFBD><EFBFBD>2<EFBFBD><32><14><><EFBFBD><37>oH;<<3C>@<40>.<2E>M<>Q!<21>^&<26>C<EFBFBD><43>9h<39>C<EFBFBD>;<3B>|<7C><>n$'j<><6A>O<EFBFBD><4F>m<>@<40>G;<3B><>}<7D><>Nk<4E>L><3E>l<EFBFBD>k<EFBFBD>F4<46><34>4<>)<29><><EFBFBD><EFBFBD><EFBFBD>,]0<>^&<26>1<EFBFBD>N<EFBFBD> <05>$<24><>k<EFBFBD>u<EFBFBD><75>̺i<CCBA><69><EFBFBD><EFBFBD>i<05><><EFBFBD>.<2E><>g%<0F>\<5C>ؿ<EFBFBD>-<2D>L ИVw&<26><><EFBFBD>_<EFBFBD><5F><EFBFBD>P<19><EFBFBD>G<EFBFBD>s+<06>K9<4B><18>N<EFBFBD>o<19><>-)_{s<>k<EFBFBD>t<>c q{k<>1<<3C><>P<EFBFBD><50><EFBFBD>>:<3A><><EFBFBD><EFBFBD>,'u69<36><39><4iu<69><75><EFBFBD>q;<3B>7<EFBFBD>y^1<><1C><>v\<5C>r<EFBFBD>A<EFBFBD><41><EFBFBD>M<EFBFBD><4D>M^{<7B><>u<00><><EFBFBD><EFBFBD><EFBFBD>/|/<2F>£<EFBFBD><C2A3><7<><37>,<10><><EFBFBD>; ^<5E><>N<EFBFBD><4E><EFBFBD><EFBFBD>)<29><><EFBFBD><EFBFBD><EFBFBD> ^<5E><> 9<>Ͻ<EFBFBD><CFBD>]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>mt.?<3F><><10><><EFBFBD>:<3A><><EFBFBD><EFBFBD>4R<34>v<EFBFBD><76><EFBFBD>W<EFBFBD>0<7F><30>?<3F><>/<2F>;<3B>m7<6D><37><EFBFBD><EFBFBD>=<3D>#}<7D><>0'<27>N<EFBFBD>?<3F><><6F> <09><>z<>PPy<50><79>!_ <0B><>߿<EFBFBD>X<EFBFBD><58>O;<3B>+IEND<4E>B`<60><>PNG

IHDR<1F><>atEXtSoftwareAdobe ImageReadyq<79>e<-IDATxڄS<DA84><11>@<14>dR@:@t@<05><00><><15><0E><>_<EFBFBD><5F><EFBFBD> Q<1D><1D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>of<6F>./<2F><><EFBFBD><EFBFBD>%1<>E<><45><EFBFBD>˪<><CBAA><EFBFBD><03>'<27>-<2D>
<11><><04><><00> <0A><>éG&q\l<>`<60>P <06><1D><01><>H<12><><EFBFBD><EFBFBD>!<21><11><>w]V<01><><1F><>V<><02>Q<EFBFBD>65<36><35>w
<I#<23>o6#<23>V[W<>5<EFBFBD>g'&<26>"<22>)PG=<3D><>8<EFBFBD><38>:<3A>y=<3D><><EFBFBD> <09><>i|<7C>HA<00><>v<><76>~<7E><><EFBFBD><EFBFBD>'<27>z;<3B>$<24>ס <0A><>s<EFBFBD>`Ti<54><69>\.NOA<4F>$<24>Gf<47>Zc,<15>Kv<08><>^<01><>j0<>%<25>/l"۹<>x<EFBFBD><78>4<EFBFBD>l"3<>l]!!<21><>L\";<3B>̎MB<4D>5<EFBFBD><35>Q<03><>-<2D><00><><EFBFBD>C<EFBFBD>n<EFBFBD><6E>IEND<4E>B`<60><>PNG

IHDR_<><5F>#IDAT(<28>c`<60>LLL" aR<><52><EFBFBD><EFBFBD><EFBFBD> a<>AF<>?<3F><><00>dy0<79><30>KwIEND<4E>B`<60><>PNG

IHDRJ#+<00>IDATx^<5E><>1<EFBFBD><31>0Ec<45><63><EFBFBD>{<7B><><EFBFBD>v*a<>A&^<06><>we1k<31>p <09><><EFBFBD>C<EFBFBD><43><EFBFBD><EFBFBD>iO<69><4F><EFBFBD><EFBFBD>8r*:z&< =Un<55>
fJ<><01>Na_ǭ<5F>㶯G8<47><38> <0C><>B<>W<1B>ON?/<2F>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD>|'<27><><EFBFBD><EFBFBD>b<><62><<3C><><EFBFBD><00><>$<24>bN1J)'Eb<45>rt<72>T<EFBFBD><54><EFBFBD>6<EFBFBD>Bt<42><1D>
<EFBFBD><EFBFBD><EFBFBD><13><>{}_<11>cA<63>v<EFBFBD><76>bqxT<78>{<7B><>o<>ݘ<EFBFBD>8<19>܍<EFBFBD>jꌩ<6A><EA8CA9><EFBFBD>۷ɾ<DBB7>Ɵ<EFBFBD>ף<>+9<><39>IEND<4E>B`<60><>PNG

IHDR..<00><><EFBFBD><EFBFBD><01>IDATx^<5E><>O<EFBFBD><4F>0<14><><EFBFBD>t)<05>v<EFBFBD>M=A<>e<EFBFBD>ҝ(<28>B[-<2D><>hT<><08>U<EFBFBD><55><EFBFBD><11>|3Ц<33><D0A6>k<EFBFBD>L<1F>&<26><>%|yyyO<06>z<18>G<>%<25>-<11><><EFBFBD>=<3D>ܦ/<2F>p<EFBFBD>#<23>E18\<5C><><EFBFBD> x<08><><EFBFBD><1E>6psd-4<><34>7<EFBFBD><37><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>%<25>2<EFBFBD><19><><EFBFBD>}<1E><>&<26>.<2E>s<EFBFBD>e<EFBFBD>)L<1D><>LMx<4D><78>d<EFBFBD>3<05>A<EFBFBD><41><EFBFBD><EFBFBD><EFBFBD>U_b<06> ><3E>B<EFBFBD><42><EFBFBD>8&<26><><1C>I <0A><><EFBFBD>7<EFBFBD><37>Џ<EFBFBD><D08F><EFBFBD><00><><EFBFBD>cU<63>[?<3F>Me<4D>=<1E>P<EFBFBD><50><EFBFBD><1E><>1<EFBFBD><31><EFBFBD>1<EFBFBD><31><EFBFBD><13><>v<EFBFBD>)<29><>+<2B>Q<EFBFBD><51><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>:<3A><>\z<>`<60>֜<EFBFBD><D69C>9 <05>䚚c<E49A9A><1E><><EFBFBD><EFBFBD><EFBFBD>>B|L<>OU`<60><>pW^}\<5C>㾺Vn<01><><EFBFBD><a<><61><EFBFBD><EFBFBD><EFBFBD>9CO&<26>ɮ <0B>dW%<25><1E>H<EFBFBD>'St7E<37><45>F ~1<><31>Lt<4C>KZ<4B><5A><EFBFBD><EFBFBD>(<28>
e<>u<EFBFBD><75><18>MWp<57>)<29>ò<18><>]<5D><><EFBFBD><12>d(<1D><>]<5D><>s OIᤶ<49>(i(<28>^"<22><>O<EFBFBD><4F>S.<2E>cA<63><41><>aQDXΑ<16><>%4a<34>OضP6\<5C><>"}<7D><4B><DF9E><EFBFBD><EFBFBD>b<><62><EFBFBD>J<EFBFBD><4A>gIEND<4E>B`<60><>PNG

IHDR 1Z7<5A>gIDAT8<54>c` <20><><EFBFBD>2<03>3<EFBFBD>b<EFBFBD><62>̀<EFBFBD> Ұ<>q3<71><02>C<EFBFBD>=^\<06><>V),<2C>V <><7F><19>p<EFBFBD>b<>$V<>n<EFBFBD>|9^v<>K@<15>8<>DC<44><43> <0C><>E<EFBFBD>6<EFBFBD>(<05>`P<00>i)C<>Mi<4D>IEND<4E>B`<60><>PNG

IHDR@0 B<><42><00>IDATX<54><58><EFBFBD><EFBFBD>
Q<14><>!<21> EY<45><59><EFBFBD>:<3A><><EFBFBD><EFBFBD>؊'<27>46XXQx<14>& <09><>3<>Ps<73>﬿;3<7F><33> <0B><><EFBFBD>i;<3B><>19<31><14>u<>WdlP(<28>T<EFBFBD><54>א<1D>[<5B>n<EFBFBD><6E>#]<1C><08><><01>&o<><6F>9<EFBFBD><39>n<EFBFBD><6E><EFBFBD><EFBFBD>Pxt<13>N1<4E>A<><41><EFBFBD>ߏ<EFBFBD>=<3D><12>3<EFBFBD><33><0E><><EFBFBD><EFBFBD>jQ<6A><12><><EFBFBD>B'<27><><EFBFBD>t^g<>M<EFBFBD><4D>%<25>"<22><>PLM<17>6<EFBFBD>*γ<>@<40><>e<EFBFBD><65><EFBFBD><EFBFBD>u,<08> <08> <08> <20>+<06><><EFBFBD>S<EFBFBD> mIEND<4E>B`<60><>PNG

IHDR<00><00>ᢜ`PLTE(y<><79><EFBFBD><EFBFBD>.}<7D><>+{<7B>0~<7E>:<3A><>5<EFBFBD><35>)z<>7<EFBFBD><37>3<EFBFBD><33>2<32><<3C><>$w<>?<3F><>D<EFBFBD><44>N<EFBFBD><4E>A<EFBFBD><41>!u<>I<EFBFBD><49>0|<7C>0y<30>F<EFBFBD><46>4z<34>5|<7C>V<EFBFBD><56>2x<32>K<EFBFBD><4B>1{<7B>2~<7E>/z<>Q<EFBFBD><51>k<>S<EFBFBD><53> f<>2w<32>,u<>5y<35>8<38>X<EFBFBD><58>)y<>s<>5~<7E><><1A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>7<EFBFBD><37>2u<32>i<>1z<31>y<EFBFBD><79>4<34>+v<>(x<>q<>*u<>!c<>A<EFBFBD><41><EFBFBD><EFBFBD><EFBFBD>*w<>o<>Z<EFBFBD><5A>d<>e<EFBFBD><65>b<>X<EFBFBD><58><EFBFBD><EFBFBD><EFBFBD>.|<7C>#i<>0}<7D>m<>'w<>4|<7C>'u<>3w<33>9<EFBFBD><39>,z<><7A><EFBFBD><EFBFBD>-x<>1~<7E>+y<>/w<>8<EFBFBD><38>N<EFBFBD><4E>%h<>%f<>`<60><>$n<><6E><EFBFBD><EFBFBD>D<EFBFBD><44>0u<30>#k<>!e<><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>%q<>(p<><70><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>}<7D><>b<EFBFBD><62><EFBFBD><EFBFBD><EFBFBD>8|<7C>!f<>V<EFBFBD><56>G<EFBFBD><47>
^<5E>]<5D><>H<EFBFBD><48>&r<>a<EFBFBD><61>;<>G<EFBFBD><47><EFBFBD><EFBFBD><EFBFBD>_<><5F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>u<EFBFBD><75>'t<><74><EFBFBD><EFBFBD>h<EFBFBD><68>K<EFBFBD><4B>'m<>6y<36>)s<>#s<><73><EFBFBD><EFBFBD>g<EFBFBD><67>]<5D> b<>_<>j<EFBFBD><6A><EFBFBD><EFBFBD><EFBFBD>^<5E><>e<>?<3F><>e<><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><<3C><>e<EFBFBD><65>(t<><74><EFBFBD><EFBFBD>Y<><59><EFBFBD><EFBFBD> k<>3t<33><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>j<>;}<7D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>V<EFBFBD><56>&r<>~<7E><> n<>$m<><6D><EFBFBD><EFBFBD>d<>]<5D><>'k<><6B><EFBFBD><EFBFBD>o<>s<EFBFBD><73><EFBFBD><EFBFBD><EFBFBD>B<EFBFBD><42><EFBFBD><EFBFBD>ҟ<EFBFBD><D29F>j<><6A><EFBFBD><EFBFBD>W<EFBFBD><57><EFBFBD><EFBFBD><EFBFBD>0t<30><74><EFBFBD><EFBFBD><50><D693>]<5D>Y<><59><EFBFBD><EFBFBD>=xڏ<78><DA8F><EFBFBD><EFBFBD>٫<EFBFBD><D9AB>9r<39>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD>_<><5F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>2o<32>Z<><5A><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>,q<>g<EFBFBD><67>5y<35>@<>H{<7B><><1A><><EFBFBD>Z<><5A><17><><EFBFBD>v<EFBFBD><76><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>9x<39>b<62>e<><65>oo<6F>(<28><><EFBFBD>M<EFBFBD><EFBFBD><E1A6B9><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>YD<59><44><EFBFBD><EFBFBD><EFBFBD>55D<><44><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>FS<46>v?}<7D>GG<47>%@<40><><EFBFBD><EFBFBD><EFBFBD>댤ܼ<EB8CA4><DCBC>u<EFBFBD><75>e<EFBFBD><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD>6m{<7B><>h<EFBFBD><68>}<7D><>Z<EFBFBD><5A>6`ç&GVM<56><4D>-U<>+OJ<02>,!IDATxڼ<78><DABC>Og<07><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>rkK<6B>mזҎ%S<>XI6
<EFBFBD><EFBFBD>[K”<4B>-*ib <0B><><EFBFBD>BԒAef<65> !Z2ё<><D191>#N%a&<26>H<EFBFBD>L`?<3F><>a<7F><61>><3E>s-<2D>b<EFBFBD><62><EFBFBD><EFBFBD><EFBFBD>@<40>|}<7D><><EFBFBD><<3C><>1<1D><><EFBFBD><EFBFBD>f/c<>HZ/<2F><><EFBFBD>:<1E>jVl&<26><><EFBFBD><EFBFBD><EFBFBD><16>Mq<4D>U<EFBFBD><55>1<EFBFBD><18>Y<1C><15><><EFBFBD>H<EFBFBD>,<2C><08>i<EFBFBD><69><EFBFBD><EFBFBD>@7G<37><47><EFBFBD><EFBFBD><EFBFBD>`<60><><1A><><08><10>,K:<3A>1*<2A>A˛TG<54><47>*k@<40>J<EFBFBD>"x<10><>mf@<40>d<EFBFBD>`J<><4A>E<EFBFBD> ^<5E><><EFBFBD>c'@|<7C>LWG<57><1C><06><0E>Pa<50>eMj <20>Q$Vdy<06><>Y<EFBFBD><00><>ZX<5A>&<26><><EFBFBD><EFBFBD>Q]IB<49>+<2B>颗B^s='A|<7C>L]<5D>2<EFBFBD>q<EFBFBD><71>f<04>yL<<3C><16>:<3A>hFhQ6;<&<26><12><12>ּø<D6BC>I,n<>:b<><62><EFBFBD>'XWWRC<01>X<>4<15>84<38>B<EFBFBD><42>X<EFBFBD><58><EFBFBD>5/<2F>y b<><62>e<EFBFBD>`<60><><EFBFBD><EFBFBD><EFBFBD> <09>ĕ<EFBFBD><C495> y<><13>2S<1D><>q<04><>2<EFBFBD>J<><4A><EFBFBD><EFBFBD><EFBFBD>nQ,xMP<4D><07><1A>z<EFBFBD>eOQ,<2C><>YM:d<>םU+̖<><CC96>"j@<40><><EFBFBD>
<17><14>s!4޸<34><DEB8>Pu<05>5<EFBFBD><35>r<EFBFBD>M,<02><><1F><>X'3<><33>B<EFBFBD>%cI<63><49>H<EFBFBD><48>i<EFBFBD><69><1A><>.<2E><>`\cV*<03>rh<72>\<5C><><0E>(<28><>ERr@<15>20<32><30><EFBFBD><0E>el<65>g0,y[<5B><><EFBFBD>%$fvZZfX׀<58>`9S <0A><>Va<01>"]! G<>`<60>+<2B><>!BW<00>&<26>~`]\<00>,JZ<04><><EFBFBD><EFBFBD><EFBFBD>--<2D><>Pa%k`m<><6D>^LR=w <0A> <09>K<EFBFBD><13><><01><><EFBFBD><EFBFBD>i<EFBFBD><69><EFBFBD><EFBFBD><02><62><D8B0><EFBFBD>i`Z<><5A>ӝ<><15><><EFBFBD>c}+<2B><>Yf]Ê<>H\<5C><><EFBFBD><EFBFBD>
<EFBFBD>"[B<16>&]<16><><EFBFBD><EFBFBD>zĞnh<6E><68>1<EFBFBD>~`<60>jb<6A><68>JRU0<55><30>a <0A><><EFBFBD><EFBFBD>Bpf<70>8|<7C><>¡<><C2A1><EFBFBD>;<3B><>,<2C><>%<25><>jS<6A>H
<07><>X<1C><><EFBFBD>:<3A>D)<29><>E<EFBFBD><45><EFBFBD><EFBFBD>&&<26><>g<EFBFBD><67>PZ<50>V<EFBFBD><56><EFBFBD>p<EFBFBD> Up<>FV<><01>e"<22>ϻ<>J<14><>`8<><38>I<EFBFBD>Z:<3A>Z:<3A><13> <0C>[<1A>ZZ[Y<> <0C>Z<EFBFBD>᰻bZQ<1E><><EFBFBD><EFBFBD><EFBFBD>m<EFBFBD><1C>-><3E><><EFBFBD>@YݗOv<4F>=-<2D>!G1<1C>Ga<47><18>}<7D><><EFBFBD><07>~[<5B>z<EFBFBD><7A><EFBFBD>j<EFBFBD><1F>
<02>~<7E>5w _<><5F><EFBFBD><EFBFBD>q2<71><32>*<2A><>A<EFBFBD>-2Ó<32><1B><><EFBFBD>&_><3E><>m<EFBFBD><6D><EFBFBD><EFBFBD>V<EFBFBD>H<EFBFBD><48>t<EFBFBD><74><EFBFBD>;<3B><1A><1D><><EFBFBD><18> <09><1B>&<26><> <0A><><EFBFBD><17><EFBFBD>f#<<3C>"<22><><EFBFBD> <0B>V<EFBFBD><56>WW <0C><>w<EFBFBD>+Fx<46>--<2D><>u8l<38><6C><1B><>a<>MK<4D>;;+q<><71><EFBFBD><EFBFBD><EFBFBD><EFBFBD>z.<2E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>m<><6D><EFBFBD>+&<26>+<y<>t<EFBFBD> |<7C><><EFBFBD><5F>L<1F><>@<40><><EFBFBD>K<EFBFBD>W<07>9𖀃<><F0968083>%Mux3<78><33><EFBFBD>u&<26>N<4E>G<1A><>rq%<25><>]<5D>+k<6B><7F><EFBFBD>Id8S<><53><EFBFBD><EFBFBD>ل5<D984><35><EFBFBD><EFBFBD>tA<74>;<3B><>^_>C<>,<2C>ʰ$<24>=<<3C>9<EFBFBD>@Y<04>D<EFBFBD><44><EFBFBD>io<><65><D299><EFBFBD>}{<7B><>ߟ\ۻ<><DBBB><EFBFBD><EFBFBD><EFBFBD>O<EFBFBD>m?<3F><><EFBFBD><EFBFBD><EFBFBD>&!<21><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>X<EFBFBD><58>72;j<><6A><EFBFBD>m<EFBFBD><6D><EFBFBD><EFBFBD>#R<0F>s<EFBFBD>`j <09> ,<2C><><EFBFBD><EFBFBD><EFBFBD>]<1E><>X<EFBFBD><58>4<<3C><>s<>IS"s<>or<6F>E<03>2<><32><4C>9g@y<>0?؇<>E<EFBFBD><45>cd<63><64><EFBFBD><EFBFBD><7F><1D><>w<EFBFBD><77><EFBFBD><04><01><>1<EFBFBD>^`<60>O<EFBFBD><05>w9<00>j <0C><18>e<EFBFBD>uLb<4C>y<EFBFBD><79><19>E<EFBFBD>^-k<08>0<EFBFBD>^Y<59>2<EFBFBD><32>`<60>^C<>h<EFBFBD>Ȭ<EFBFBD><C8AC>{<7B><>w<EFBFBD>~<7E><><EFBFBD><EFBFBD>
<EFBFBD><EFBFBD><EFBFBD>GpQ<EFBFBD> u˂'$<24>2F`,<00>A<EFBFBD>5<EFBFBD><35>~,<2C>wƛq&upY<70><59><EFBFBD><EFBFBD><EFBFBD>q<EFBFBD>3<EFBFBD>>Ta<54>~ި*l<><6C><EFBFBD><EFBFBD><EFBFBD>ZA X<>VH<56><48><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><02>Y<EFBFBD>)<29>A<EFBFBD>v;<04>Er[<5B>@p <20><>7<EFBFBD><37> 5<04><>m<EFBFBD>gr<67><72><EFBFBD><EFBFBD><03><>
<EFBFBD>jਵ}<7D><><EFBFBD>[<5B><>8d<38>x<EFBFBD><78><EFBFBD>=Vc<56>\h<>Ȁ<02>bK3X<33>H<EFBFBD><01>膹T—<54>C4o_s0<><17>߇<><DF87><EFBFBD><EFBFBD>/v /p8<05><><EFBFBD><EFBFBD>dE<><<00>"<15><>O@@<40>x<EFBFBD>“7b<37>N<EFBFBD>O <1B>,<2C>:<1A>[ <0B>L<EFBFBD><4C><EFBFBD>t<1A><><EFBFBD><EFBFBD>t<EFBFBD><74><01><><EFBFBD><0F>7<EFBFBD><37>~<7E><>g<EFBFBD>(<28><>Y!<21>z!<21>XG*<2A><><EFBFBD>_xq<78>d<EFBFBD>X$<1B>CDRC<52><43>Ţ<EFBFBD><1E>v<EFBFBD><76><EFBFBD>Φ<EFBFBD>,B&<01>7><3E>gn<67><6E>z<EFBFBD>ϕ<EFBFBD><CF95>Lz<4C>oR<6F><52><EFBFBD><EFBFBD>;H<><1E>h<EFBFBD>Ko<><6F>U<><55>C<EFBFBD>H<EFBFBD><11>]<11><>^<5E><>Ka<4B><61><1D>!_U<5F><55><EFBFBD>S<EFBFBD>jV<6A><14> Q<>݊Y<DD8A>ˈ<EFBFBD><CB88>?\<1E><1F>I|<7C>il<69><6C><EFBFBD>C1<07><><EFBFBD>V<EFBFBD>&<26><><EFBFBD>f<EFBFBD><66><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>GmK<>c1<63>H<EFBFBD><01>T<EFBFBD><54><EFBFBD>p!<21>:<3A><>v<EFBFBD>1<EFBFBD><18><15><><EFBFBD>'/H<><48><EFBFBD>|;<3B><><EFBFBD>fp$<24>4<EFBFBD>6Τ<><E38D8D><EFBFBD><1E>/'<27><><EFBFBD> /f<><66><EFBFBD><EFBFBD> ,<2C>A-M<><4D>H<EFBFBD>a<17><73>Z<EFBFBD><5A>0MV Etނ<74><DE82>1<EFBFBD><31>- <0A><18>t x<><78>`<60>SE3<45><33>h#h<> <0A><><EFBFBD><EFBFBD>Ӊb]<5D>677o.k=<3D>tM<>B|<7C>+W<><57>,<2C><>(<28>`aQ <09><><EFBFBD>"{<7B><><EFBFBD>vk <0C>7M<><4D> ,<19>}p<><70>m<EFBFBD><6D>o<EFBFBD><6F><EFBFBD>=1<>Q<EFBFBD><51><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Bfk1[<5B><><EFBFBD><EFBFBD><EFBFBD>v <0A><> <02>h;1<0E><><EFBFBD>1<EFBFBD><31>`J<><4A>j^<5E>[<5B>o$<24>k<EFBFBD>K<EFBFBD><04><><EFBFBD>Q^*Kt<4B>o<EFBFBD>)g<><67>c<EFBFBD>V<EFBFBD><56>F<17> ׾<><D7BE><EFBFBD>@a, n<><6E>tf|<><7F>.2<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>c<EFBFBD>?<3F>Z9<5A>LX<4C><00>*6<61><C59C>jN<>w<EFBFBD>~sL <0B><> <0A>e<EFBFBD><65><EFBFBD><EFBFBD><EFBFBD>X<EFBFBD><58>f#ӹ{<7B><><EFBFBD>A|<7C>lB<6C>><3E><><EFBFBD><EFBFBD><EFBFBD>{<7B><>+<2B>iF<69>_S*<2A><>3<>k<17><>T<EFBFBD><54><EFBFBD><EFBFBD>t<EFBFBD> Z<7F><5A>e<EFBFBD>G<EFBFBD>S<EFBFBD><53>k<V<><56><EFBFBD><EFBFBD><07>i~<7E><>G<EFBFBD>o<EFBFBD><6F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>YN<59><6A> <09><><00><><EFBFBD><EFBFBD>º<01><><EFBFBD><EFBFBD> <20><><EFBFBD>M<><12><12>ܬH<DCAC><48>i<EFBFBD><69>zYO{<7B><>J<EFBFBD>!x3<33><EF9CBD><EFBFBD>
bVA`<60><01><><EFBFBD>TlV<13><>fQ<66><51>Ja<4A><61>0<><30><EFBFBD><19>Xs<58><05><16>;<3B>M<>f<EFBFBD><66><EFBFBD><EFBFBD>Z&iU<69><55><EFBFBD><EFBFBD><EFBFBD>at<61><74>!<21>0<EFBFBD><30><EFBFBD><EFB7A6><14>1X<31><58>t/<2F>S<17><07><17>&{Q<><51>@գ<1D>&<26>N<>FS<46><53><EFBFBD> <0A>7#/<2F><>4
<EFBFBD><EFBFBD><19><><EFBFBD>k=<04><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>F<EFBFBD><02>&x(<28><><19>NeS<65><53>ᓇߤ<E19387><DFA4><EFBFBD><EFBFBD>i^<5E>G<EFBFBD>v<EFBFBD><><DF8C>(j<>s<EFBFBD><73>L1<4C><31><15><><EFBFBD>t<EFBFBD><74><EFBFBD>`C<>^<5E>= #Xr<58><72><EFBFBD><14><>i<EFBFBD><69><EFBFBD>!<21><>Ƒw<C691><77>D<EFBFBD>r<EFBFBD><72><EFBFBD>9<EFBFBD>Ri9k<39>`g<><0E><>;<3B>P<EFBFBD><50>$gf<67><66><EFBFBD><EFBFBD><10><><EFBFBD>RC0 <0C>)Q<7F><51>0<EFBFBD>@E<><45><EFBFBD>i<15>?s?<3F><><EFBFBD><EFBFBD><EFBFBD>`<60><>n<EFBFBD>`<60>J3:F?Nt8l<><6C><EFBFBD><05>B6<42>`<14>M!<21><><EFBFBD>"<22>p<EFBFBD><70>v`hލ<19><><18><>H<1A>⋘V<E28B98><56><EFBFBD><EFBFBD>{<16><><EFBFBD>e<EFBFBD>& v<><76>(̣Q\<5C>' ;[<5B>G<EFBFBD><47><EFBFBD><EFBFBD><EFBFBD><EFBFBD>`<60><>T<EFBFBD>i
LjN<EFBFBD><EFBFBD><EFBFBD>j><02>`d(1<><31>.<2E>"<22><>Ù ˞B5;<3B>M<><4D><EFBFBD>
<EFBFBD>hnr<EFBFBD> <20>3<EFBFBD><01>7:<3A>؄ϟ<D884><CF9F>1<EFBFBD><31>W<EFBFBD><EFBFBD>`<60>k2s<32>%b/ܮ}<7D>S;0@ϲ<>b.<2E>5<EFBFBD><35>><0F><19>|<12><>׳<EFBFBD>Ѐ<EFBFBD><D080>76<37>ոى<D5B8>Nx(<28>}<1D><><EFBFBD>=<3D><>z(<28>0$<24><08>"<22><>f<00>bB1U<><55>.<2E><>k^c<><63>a<EFBFBD><19><>\(<28><>8<EFBFBD><38>a<EFBFBD><61><EFBFBD>%<25>'<27><><EFBFBD> <0B><19>(<28><>o<>؉<EFBFBD><D889><EFBFBD><EFBFBD>(<28><>{<02>)/&<00>r<EFBFBD>8<EFBFBD><38><EFBFBD><15>h<EFBFBD><68>"<22>z)t<><74>z<EFBFBD><7A>f`<60><>
%<25><> <20><>{<7B>8z<38><7A><EFBFBD><EFBFBD>n<EFBFBD>p<EFBFBD><70><EFBFBD><EFBFBD>:<3A><>3<EFBFBD><02> n+<2B>8<><38> 񡦞<><F1A1A69E>1<EFBFBD>m<EFBFBD>[hR<>)<29>-<2D>4k<34><6B><EFBFBD><EFBFBD><EFBFBD><01>a<EFBFBD><61>f`c2<63>={<7B><><EFBFBD>|%<25><><EFBFBD>k{<7B> 0.<2E><>,.py<70>q<EFBFBD>˼<EFBFBD>><3E>̏<EFBFBD>gZQz<51><7A>L<EFBFBD>Mh<15>ѹx<D1B9>*<2A><>ڇN<DA87>5<03><^<5E><>n#.<2E><><EFBFBD>w<><EFBFBD><7F><06><><EFBFBD><EFBFBD><EFBFBD><01>.no<6E>+\<5C><><EFBFBD><EFBFBD>|<7C>j[<5B><><04>||<7C><><EFBFBD>t<EFBFBD>٧p<D9A7>!<21>20<32><30>D5/e ®<><C2AE><EFBFBD> <0C><><1B>sHD<04>T<>N<EFBFBD><4E><EFBFBD>SS*<14>T<EFBFBD>_.<2E><><EFBFBD><EFBFBD>^dt<64><74><EFBFBD><EFBFBD><EFBFBD>Z<><5A><17>ad<61>ҽ<36> t<><<3C>S3<53><33>ƻϣ<C6BB><CFA3>/<10><><EFBFBD><EFBFBD>ͼ<><CDBC><EFBFBD><7F>_<EFBFBD>~<7E><><EFBFBD><15>V[K<>V<EFBFBD><56><EFBFBD>Vmൾy<E0B5BE><79><EFBFBD>ab<61>+s<><73>Us]wa.<2E><0E><>Y!<08><><EFBFBD>7<EFBFBD>v<EFBFBD><76>D<18>|f<><19><>m<EFBFBD>7t<37><74>ЪP<18><><EFBFBD><EFBFBD>d<EFBFBD>P\+X<>P<EFBFBD><50>E6<45>T<EFBFBD>Y<><59><EFBFBD><EFBFBD>X<EFBFBD><58>:E<>,H<>P<EFBFBD><50>Q<><51><EFBFBD><EFBFBD><EFBFBD>g<EFBFBD>fv<66>S<EFBFBD>7<EFBFBD>%<25><><EFBFBD>{<7B><> <0C><><EFBFBD>6[`<60>^<17><><EFBFBD><EFBFBD>=N<>~&<26><><EFBFBD>q<EFBFBD><71>6 f<><66><EFBFBD><EFBFBD>:<۟,=}<7D>!<21><08><><EFBFBD><EFBFBD>a>9|<0F><><EFBFBD>w`<60><>/<2F><><EFBFBD>~~<7E><>٤<EFBFBD><D9A4><EFBFBD>d<EFBFBD><64><EFBFBD>t<74>ˑ<EFBFBD>ݏg<DD8F>m<EFBFBD>8<>c<EFBFBD>3O/<2F>Q<EFBFBD><51><EFBFBD>I
<EFBFBD><EFBFBD>6<EFBFBD>ո<EFBFBD>Xc-tv<74><76>Y<EFBFBD><59><EFBFBD><1E><><EFBFBD><EFBFBD><EFBFBD>ю<15>GQ/<2F>mp<6D>&<26>a"<22>C<EFBFBD><43><1B><00>ܶcہ<63>#\Fq<46><71><10><><EFBFBD>[I<1B>r<EFBFBD><72>ɼS<C9BC><53>%y<><79><EFBFBD>4NK<4B>=<05>c4<63>Eha<04>X<EFBFBD><58>?<3F>qMr<>w<><77>'0<>v<EFBFBD><76>-<19>=<3D><><EFBFBD><EFBFBD><EFBFBD><06>&h<>:#h<>:<3A>zKv<4B>t<EFBFBD>aZy<5A>-<2D><<1B>
<EFBFBD>y<EFBFBD><EFBFBD>ӡ<EFBFBD>_<1E>1o<31>x<EFBFBD>E<EFBFBD><45><EFBFBD>T<EFBFBD>/L<><4C><EFBFBD><EFBFBD>ٱ<EFBFBD><D9B1>r<EFBFBD>9<EFBFBD><39><EFBFBD>:L<`Tb<54><02>:;<3B><>_<EFBFBD>t
<EFBFBD>C<EFBFBD><EFBFBD>g`<60><><EFBFBD><EFBFBD>=-<2D>(Z
/<2F>1<EFBFBD><31>~T<>-<2D>*Ъ{<7B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ui\J$<1E>c<EFBFBD>]<><E6B687>\<02><01><G<00><>]f<><66><EFBFBD><EFBFBD>
z<EFBFBD>$(n<>h<EFBFBD><68>1a7<19>ޫmk<6D><6B>v3~Z<>g.5ț<1A><>f<EFBFBD><1B>Qn<51>><3E>ގc<13>3<EFBFBD>.<2E>><3E><><EFBFBD><EFBFBD>(<28>W<EFBFBD><57><EFBFBD>dQ<64>,+68<36><38><1B><>t<EFBFBD><74><EFBFBD>{<7B><>W]g/J<><1C>>Nz<4E><7A>'ǥR<C7A5><52><0F><00><>][<5B>P0<50>m<EFBFBD>|o<><6F>1GT<47><54>5<EFBFBD><35><EFBFBD>+<2B><><EFBFBD><><7F><EFBFBD>5<EFBFBD><1A><>p\G<>G<EFBFBD><47><EFBFBD>.<2E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>K<EFBFBD>S<EFBFBD>?<3F><>{<7B><>|u<>w~<7E>c<EFBFBD><63>O<02>*<2A>g<EFBFBD>k<EFBFBD><6B><EFBFBD><EFBFBD>QGB!<21><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>a><3E>H<ξ<>!<21><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><15>e<EFBFBD>3<EFBFBD>ފ<EFBFBD><10>qa<71><61><EFBFBD><12><EFBFBD>w<EFBFBD>H<EFBFBD>R<EFBFBD>T7<54>թ׿F<D7BF><46><EFBFBD><EFBFBD>]<5D><>]<1B><><EFBFBD>_ /<2F>r$<24><><EFBFBD>r<EFBFBD>^p&|<11><>pʑJ%<25><><EFBFBD>L= <0A><>3ԇYZZp/撟Qa^T<10>`MZ<4D>
<EFBFBD><EFBFBD>#Mܐd<DC90>:Z<>^*%<13>2<EFBFBD><32>U<EFBFBD><55>xf<18><>/<2F>]<5D>4ު#<23><>i<1C><><EFBFBD><EFBFBD>$<24>N<EFBFBD><4E><<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>J <0A><><01><>34h-d <0B><>̼kk<6B><6B>ħ<EFBFBD><C4A7>'4hu<68>Iwh<77><68><EFBFBD><EFBFBD><00><><EFBFBD>{В<>^]=<3D><>[<5B><><02> <11><><10>P<EFBFBD><50> <0B>8(.<2E>(<28>F<EFBFBD>^<5E><>_<1B><><EFBFBD><EFBFBD>`{Zj$<24><>aдt:\t<>1-<2D><>"OK)Q<>Ɵ^<5E>+<05>|<7C><><EFBFBD><EFBFBD><EFBFBD> <>2S<32><53>M<13>I<EFBFBD>KvG<76>n<EFBFBD>_<EFBFBD>%$vc <0A>n<EFBFBD><6E><<3C><> <0A>X<EFBFBD><58>G<EFBFBD>ݮ<EFBFBD><DDAE> <0B><>p<EFBFBD>[<5B><><EFBFBD>M<EFBFBD><4D><EFBFBD><EFBFBD>V <20>EEX<>?b#<23>.L1<>l<EFBFBD> <09>M<00>H`>v<><76><EFBFBD>
_<EFBFBD>o0om<6F><6D><EFBFBD>]<5D>\`Y<>s<EFBFBD><73><EFBFBD><EFBFBD>4<>b<EFBFBD>3<EFBFBD>4<03><>t9<74><39><EFBFBD>_<EFBFBD>X<EFBFBD> <0B><><EFBFBD>Va<12> <0C>m<EFBFBD>`<60><>j<<3C>uw|M<>qk<71><6B><17><>c<EFBFBD>{!<21>K<EFBFBD>V-<2D>m~<7E><><EFBFBD><<3C><><EFBFBD>[<5B><><>b<EFBFBD>S<EFBFBD><53><EFBFBD>b<01><>y<EFBFBD><79>ilM<12><><EFBFBD>2<EFBFBD>a[<5B><1A>K`4<><34>E<EFBFBD><16>=<3D><>ō<EFBFBD><C58D>y<EFBFBD>= <05>Y4<59><0E>gU<67> /P<><50><EFBFBD><EFBFBD>S<EFBFBD><53>&/<2F> <13>Ae<41>ؤ<EFBFBD>|<7C>֮YV<59><56>)<29>t<EFBFBD><74>,K<> 8<><38><1F><> V<><56><EFBFBD><EFBFBD>k~,q <0C><>?`ד<><02>Y<EFBFBD><59><EFBFBD><EFBFBD>#<23><><EFBFBD><0F><>`ep<65><70>O<><4F><EFBFBD>5k[<5B><>y,<2C>8<17> <0B>[<5B>Y<EFBFBD><59><07>ۻ#<23><>.B*<2A><17><><EFBFBD>w$^.<2E><><EFBFBD>"^<5E><>Ҍl<D28C><6C>(<28><><14>$1<>Ә:<3A>݅<EFBFBD> <0B>/c%<13>\`-ֶ<><D6B6><EFBFBD><10><>w`=2<05><><EFBFBD>+<04><>WX<><58><EFBFBD>1/<2F>XUў3T_xx`z<><7A>+<03><><EFBFBD><EFBFBD><EFBFBD>ա<EFBFBD><D5A1><EFBFBD><EFBFBD>r<18><>'.$o<><6F><EFBFBD><EFBFBD><EFBFBD>E<EFBFBD>2F<32>e<EFBFBD><65>i<EFBFBD>)<15>Y<EFBFBD><59><1F><>"<07>0l<05><>$<16><><16>3<EFBFBD>i<EFBFBD>җѪM;<3B> <20><>գĭqY<06>P<EFBFBD>Ikv2<76><32> =<3D><>b<EFBFBD><62>qD<71>{V<16>X<>+<2B>%<25><>"<03>e<EFBFBD> J<><4A><EFBFBD>%Q<><51>ڶ<EFBFBD>%sI5U<35><55>^)X<>45}9n<39>Qӫt<D3AB>p)dY<<3C><>^<5E><><EFBFBD><EFBFBD><Ȥm<C8A4><6D>9<EFBFBD><39><EFBFBD><EFBFBD> <04><07><> <0B>=<03><><EFBFBD><EFBFBD>ݣ<EFBFBD>)<29>0<EFBFBD>B%<25><><EFBFBD>
y<EFBFBD>#<23>5<EFBFBD><35>g/-Y<> <20>j<EFBFBD><12><> 8̎@C<oA<6F><41>ѣs7<73><37><EFBFBD><>X<EFBFBD>7<EFBFBD><37>1B<31>o/<2F><><EFBFBD>
;<3B><>C1<14><0E>1<EFBFBD>$<14>ҿ<EFBFBD>I<EFBFBD>ˋ<01><>Tn<54>YKTc<12><><EFBFBD><03><>
׬q<EFBFBD>أ<EFBFBD><EFBFBD><EFBFBD>\<5C>}<7D><>/<2F>K<EFBFBD><4B><EFBFBD><EFBFBD>GJ,<2C><>D>j<><6A>zW<7A>hJt<4A><74><EFBFBD>r<EFBFBD><72>1Dq<1C>g<EFBFBD>Lgg<67><67>.KIw<49><04>ud<75><64><EFBFBD>KU<>΢θ<CEA2><CEB8><EFBFBD><EFBFBD>ZD<5A>΢h<CEA2>M<11><>U<EFBFBD><55>u<1F>#<23>#n<><6E><EFBFBD><EFBFBD><EFBFBD><EFBFBD>=<3D>:<3A>~<7E>&<26><><EFBFBD>4<EFBFBD><34><EFBFBD><EFBFBD>ޛ=ƪ<><C6AA>7<EFBFBD>"oi+
<EFBFBD>
0ڣq<12>t:ˉ<>p_`<<3C>\-<2D><>&4]Q<>Sf<53><66><EFBFBD><EFBFBD><17>7<EFBFBD>1<><31>?<3F>G<1C> 0KǏ<1F><06>H<EFBFBD><48><EFBFBD><EFBFBD><EFBFBD><EFBFBD>W*)<05><><06>f<)^<5E>l <ōS<C58D><53>4m<34>݋U<DD8B><55><03>]<5D><>f<EFBFBD>B<EFBFBD>P<EFBFBD>:<3A>5<EFBFBD>DEM<45><4D>"5uݐ<75><DD90><EFBFBD>{O<><4F>w<EFBFBD><77>S~HVV<56>ҥ<EFBFBD>Ƨ<EFBFBD><C6A7><EFBFBD>_<EFBFBD>F0<46>X-LX<>FC<46>)<01>T<EFBFBD>͸<EFBFBD><CDB8><EFBFBD><EFBFBD><EFBFBD>G"<22>"<22><><EFBFBD><1C>r<EFBFBD><72>1<EFBFBD><31><EFBFBD> <20>R<EFBFBD>;Ķ5FE<46>=t9##<23><><EFBFBD><EFBFBD><EFBFBD>3<EFBFBD>}|<7C>/,đ?dԻw!<21>h<EFBFBD><68><EFBFBD>#<23>p<EFBFBD>M<EFBFBD>`0#<23><><EFBFBD><EFBFBD>rv<72>TXpH<70>p<EFBFBD>;9ޯ<39><DEAF><<3C><><EFBFBD><16><><EFBFBD><EFBFBD><EFBFBD>)<29><1B>iIT<49>UK<55><><CDBC>'<27><>Z<EFBFBD>I<EFBFBD><49>(\<0E><>dgg<67><67>Ar<41><72>=<3D><><EFBFBD>0|`P|<7C><>"~3&<26>a<EFBFBD>F8er+F<>j<03><>N<EFBFBD>oh<6F>H<EFBFBD>nJ>"<22><><EFBFBD>1e<31><65>m<EFBFBD><>̼IE<49>Z<EFBFBD>/o<><6F>{Z,<2C>o<EFBFBD>#<23><>O<EFBFBD><1E><><EFBFBD><EFBFBD><EFBFBD>|h<><68>=+<2B>`<60>5<EFBFBD>Y<01><>Í<EFBFBD><C38D>f!`^<5E>i2ɣ<32><C9A3>`Ith ɶ<>)u<><75><EFBFBD><EFBFBD>2<EFBFBD>򐑙<EFBFBD><F2909199><EFBFBD><EFBFBD>۶%<25><>J<EFBFBD><4A>=I<><49>0<0E><00><> r$ٓ6<D993>Z8<5A>\<5C>
<EFBFBD><1F>3.<2E><>w""D<08><>Rf<52><66>JJ3<4A>?<3F><><EFBFBD><EFBFBD>i8<69><38><EFBFBD>a<><61>A<EFBFBD><1A><><D9BC>yw<79>'u<>K8z*!Η<>q8<71>'!<01><>$9;~^֝<><D69D>fJ<18><><EFBFBD>F2| X<14><>4<EFBFBD><34><08><0E>#N3<4E>@M<>Ma<4D><61><EFBFBD><EFBFBD>h<EFBFBD>l<EFBFBD><6C>?<3F>/h<><68>jUv<55><76><EFBFBD>[<5B>y<05><><EFBFBD><EFBFBD>=<3D>Y<EFBFBD>w<EFBFBD><77><EFBFBD><EFBFBD><EFBFBD><EFBFBD>$<10>o<EFBFBD>H<EFBFBD><48>jG<6A>ja<05><><EFBFBD>U<18><><EFBFBD>F<EFBFBD>
<zN<><4E><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;4;'<06><>ˮ9f/<2F>!}<7D>U<EFBFBD><55>=W<><57>W<><57>
<EFBFBD><EFBFBD>ާ5J<EFBFBD>Yj<Eq<45><71><EFBFBD>Gf<47>
'<18>J1<4A>`<60>i <0B>I<EFBFBD>"U<>x<EFBFBD><78><EFBFBD>
<EFBFBD><10>(Q<>)<0E><>3 +;<14><>H<EFBFBD>c<EFBFBD>i<EFBFBD><w <0C>ئ㼑<D8A6>-8<><38>ğ<EFBFBD>]B<><42><EFBFBD>G<EFBFBD><19><0F><><0F>0<EFBFBD>YS<59>`0)s-XaXu<58><75>ߐxV<78>z<EFBFBD>ĵ2<C4B5>*<2A>[<5B>TI<54><49><EFBFBD>.VJ[9<><39><EFBFBD>g5Vo<><6F><EFBFBD>s:9<><07>7<EFBFBD>J<EFBFBD>M<EFBFBD>%\X<><58>yu<79><75>6<EFBFBD><36> &%<25><03>(<28><>S<EFBFBD>Z<EFBFBD><5A>L<>#>Z3<5A><33><EFBFBD><EFBFBD><EFBFBD><EFBFBD>k<EFBFBD><6B><EFBFBD><EFBFBD><EFBFBD><EFBFBD><><D08F>עE<17><>e<EFBFBD><65><EFBFBD>X<EFBFBD><12><><EFBFBD>_<EFBFBD>+<2B>ņ<EFBFBD>y<>w<EFBFBD>m
;<3B>5U`+<2B><><EFBFBD>D<EFBFBD>B<EFBFBD>*<2A>#J-<2D><>]<5D><><EFBFBD>3<EFBFBD>]J<>qh!<21>1<EFBFBD>g<67>
<EFBFBD>Wyz<EFBFBD>v^<5E><><EFBFBD><EFBFBD><00>F0<46>+<2B><><1F>"<22>(^ON<4F><4E><EFBFBD><EFBFBD>E<1E>kC<6B>l<> <0A>&<26>5<07><><18><><EFBFBD><EFBFBD> :օ/ <09>r<EFBFBD><72> <20>pVV<07><><EFBFBD>̔<>*q<>`<60>\q?<3F><>N\<5C>|f<>M<EFBFBD>*<2A>,t<><74><EFBFBD>ǝ<EFBFBD>R<EFBFBD><52><EFBFBD>E}<7D>|<7C> <0B><><EFBFBD>{<7B><>ϸ
>{<7B><>_<EFBFBD>o<EFBFBD>)(x<>}f<><66>*<2A><>F<EFBFBD>#<23>LB<4C>
<EFBFBD>1<06><><EFBFBD> <0A><><EFBFBD>D<EFBFBD><44><EFBFBD>t<EFBFBD><74><EFBFBD>Ҡ<EFBFBD>J<EFBFBD>ad<61>MU<4D>i)<29><>(<28>+<2B><><EFBFBD>I<EFBFBD><49>NǸ};.<2E><>_<EFBFBD>/<2F><>)<29>Xtfr<66><72><EFBFBD>k<EFBFBD>1<1A><><EFBFBD><EFBFBD>`N<>Z<EFBFBD><5A><EFBFBD>h<EFBFBD>`($><3E><13><>qL<71>X<EFBFBD>N<0E><>*<2A>2?^=I<><49><EFBFBD>Oz<08> <20><><EFBFBD>b<EFBFBD><62>~<7E><16><><EFBFBD>l+<2B><>=<1E>VX<56>4H<34>UN<><10>*r<>/#<23><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>NQl<51><6C>s1>p<><70>cT%<25>_7O2¹<1F>G<EFBFBD>~<7E><>q.t<>sr^y{<7B><>aiZ<69> <16><>>0<03>e<EFBFBD>Hd<>f<1A><><EFBFBD><EFBFBD>ćq<C487><71>`<60><>i<EFBFBD><00>ϕ+<19>w<EFBFBD>%<25>W<>4<>8$<24>\N<>Y7<18>0p<30>><11><>%<25>73 <09><>؅ݐ<D885>֤<EFBFBD>T<EFBFBD>
<EFBFBD><EFBFBD><EFBFBD>%<25><>L<<3C><><EFBFBD><EFBFBD><EFBFBD>P<EFBFBD>%<25>a<EFBFBD>`$<24>߾p=<3D>`<60>Vh³ <0C><03>"Ĝl><3E><>-<2D>ڵ<EFBFBD>0 <0B><>DKٜ<4B><D99C><EFBFBD><EFBFBD><EFBFBD><EFBFBD>䇗R3- EF<45>[o<><6F><EFBFBD>F<EFBFBD>(<><7F><EFBFBD><EFBFBD>x;<3B>0<>6E<36>F2eHYDcz<63><7A><EFBFBD><15>!<21>><3E><><EFBFBD>V<EFBFBD>VwO<1A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>i<16><><06><<3C>Q <0C><><EFBFBD> łO<C582>(<28><> <0B><>k|<7C>zk`<60><>x<1A>q <0A><>,vQ|p<>߃%<25>b<05>h6<68><36><EFBFBD><EFBFBD><EFBFBD>e<EFBFBD>R"<22><><6<><36>:l
Y<EFBFBD>T<15><>e<EFBFBD>X<EFBFBD>"<22>|<7C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>+<2B><>CW84<38><34>o<>b<EFBFBD>.zP<7A>Zk/v<>.#<23><>5`<60><><EFBFBD>4<EFBFBD>6<EFBFBD>Q$<24><>i <09><><1F>9<EFBFBD>j<EFBFBD><6A><EFBFBD><EFBFBD><EFBFBD>2c<32>Ɲ<EFBFBD><C69D>}'<27>y<EFBFBD>;m\<5C>”qi<71><69><EFBFBD><EFBFBD><EFBFBD>z<EFBFBD>]ڹ)=<3D>{<7B>AO<41><4F><03>~ <0B>$<24><>w!)<04><><EFBFBD>Ћ<>
<EFBFBD>P<><08><38><D29D>Zk<5A><6B>N<EFBFBD><4E>a±T<C2B1>&U<>S,G<>&><3E>><3E><><EFBFBD>.<2E><00>b3fúa[<5B><><EFBFBD><EFBFBD>CVòt9<74><0F>~ ><3E><><EFBFBD>e<EFBFBD> g<><08>:U 7<EFA29B>P<><50>dݘ<><DD98><EFBFBD><EFBFBD><08><><EFBFBD>^S<>1<EFBFBD> E<><45><EFBFBD><EFBFBD>
<EFBFBD><EFBFBD>f<EFBFBD>8<0E>O/w<><77>r<EFBFBD><72>hP)u@ck<63>B<EFBFBD>j<>Zc<5A><63><03>諯(<0E><> u<>5<EFBFBD>{<7B><><EFBFBD>~}<7D>(<28>8y<38>}5n<35><6E>[c4qE<71>t<EFBFBD><74><EFBFBD><EFBFBD>y<EFBFBD><1B>1 <20>(e<><65><EFBFBD><EFBFBD><EFBFBD>uw<75><77><EFBFBD><E58EBE>%<25><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> S<>`{<7B>Ň<EFBFBD><C587><EFBFBD><EFBFBD>Woy<6F><79>{<7B>nIo<49>;<3B>ك<EFBFBD><D983>i<EFBFBD><69><EFBFBD>?<3F>y<EFBFBD><79><EFBFBD><18><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;<3B><07>{<7B><><EFBFBD><EFBFBD><EFBFBD>x<EFBFBD><78><EFBFBD><EFBFBD><E194B8>QY>oKR<4B><52> wV<77>eEgv<j<>cC<63><07>x+<2B>^=<3D><><EFBFBD>?<3F>i<EFBFBD><69>I<EFBFBD><49><EFBFBD><EFBFBD><EFBFBD>Y=<8qú<71><C3BA>n_w<5F><77><EFBFBD><EFBFBD><EFBFBD><EFBFBD>N<d`<60>N<>\<5C><1A><>W <0C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><<3C>9<0F>q<11><>s33<1F><><EFBFBD>'<1E> <09>JC<4A><43>_<04><><EFBFBD>!<18><>~<7E>8K<>6n<1B>k<><6B><12>p<EFBFBD><70>b<EFBFBD> <09>x<EFBFBD><78><EFBFBD><EFBFBD><EFBFBD><EFBFBD>;7'tyA<79>H$"@ۨ<>w<EFBFBD><77><EFBFBD><EFBFBD><EFBFBD><EFBFBD>V[<5B>(f<>=<3D><><EFBFBD>^=<3D><>3W<19>a<EFBFBD>j<EFBFBD>w:<3A><>><3E><5A>)VI<56><49><17>`o<1D>:<3A><><08>6 l<03><><F/<2F><>S<EFBFBD>!<21><>,<2C>R<EFBFBD> <0C><><EFBFBD><EFBFBD><EFBFBD>z<EFBFBD>gH<><48>[Q1<51>w<EFBFBD><77><EFBFBD>a<EFBFBD><61><EFBFBD><EFBFBD><1D><><EFBFBD>w.ؔ 8<>}:<3A><>M<EFBFBD>D<EFBFBD><44>&<26>a\o<><6F>DX<44><58><1C><>`<07><11>B<<3C>.<06>7c.<18><><EFBFBD><EFBFBD><EFBFBD>{<1B><>[<1D>d/<2F><13><>)(n<><6E><EFBFBD>Dߌے<DF8C>`J<>5F/<2F> <12>؋<EFBFBD><D88B><11>c<><63>? k<><6B><EFBFBD><EFBFBD><EFBFBD><EFBFBD>܅<><DC85><EFBFBD>&<1B>Q,<2C>so><3E><>6s<><73>a}u,Ǒڎ Ϻ4<CFBA><34>\<5C><><EFBFBD>E<EFBFBD><45>ǟO<C79F><4F>73C<>]8X=͖`>ΧDz <09><>e<><65>^<5E>vWC<57><43><EFBFBD><EFBFBD>̬<EFBFBD><00>.<2E><>ܢ<07><>Ҝ<EFBFBD>K<02>h<EFBFBD>ߍ<><DF8D><EFBFBD>`<60><>=U Vb<56><03><><EFBFBD><EFBFBD><EFBFBD>C0|<7C><><EFBFBD>FO<46>K<EFBFBD>U<EFBFBD><55>E<EFBFBD>P<EFBFBD><50><EFBFBD>υ7<>w<EFBFBD><77>Ǿ<EFBFBD><C7BE><EFBFBD>S<f<><66>8a<>KK0[<5B>HO<48>H<EFBFBD><48>J/<2F><03><>#<23><><EFBFBD><1A><>X<EFBFBD><58><EFBFBD>[<5B>K<EFBFBD><4B><EFBFBD><14>9<EFBFBD><39>D<EFBFBD><44>33ov<6F>i<11><><08><>*<2A><>˽W<1A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>IJ}<7D><><EFBFBD><0A>bX~ӎ<00>dj<><6A> <0B>@h<><68><EFBFBD><78>ή-N]<5D><><EFBFBD>ϯ;l<>?,<2C><><06><><12><18><><EFBFBD><EFBFBD><EFBFBD>
є '1[T<>ζ<EFBFBD>1<18><<3C>J<1E>Rj<1D><> #0<><30>.<00><12>s<EFBFBD>QtsL˭#-<0F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><16>c֕{<7B><>j<08>w<EFBFBD><77>%+N<><15>:#<06><> <0C>{<7B><><EFBFBD><EFBFBD>8<05><00><>V<EFBFBD>mY<6D>
<EFBFBD>lC<><43><0E><><EFBFBD><EFBFBD>V}x<><01><>?X<02> u<><01><>xTb<54><62><EFBFBD><EFBFBD><1A>/<2F> xy<78>j<EFBFBD><6A>K<>u<EFBFBD>u5<au<61><75><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ޗ"!<21><><EFBFBD><EFBFBD><EFBFBD><07>|<7C><><EFBFBD>A<EFBFBD><41><EFBFBD><1B><17>R '<27><>8<EFBFBD>`hͬ<68>
z<EFBFBD>;A<>
<EFBFBD>ق]x<><78>$<24>. <0C>ļ<EFBFBD>]G<>l<EFBFBD><6C><EFBFBD><EFBFBD>)<29>{<7B>~<7E><>0<EFBFBD><30><EFBFBD><EFBFBD>[<5B>ΏP_<50>E/&<18> <0C>3 <05>##<23><>o<><6F><EFBFBD><00>U<EFBFBD><55>r,va<76><61><02>L<EFBFBD><11>:<3A>Zv<<3C><>U<EFBFBD><55><17>{<7B>Ex<45><78>ܛϽ(<><7F>o><08><><EFBFBD>}<7D>*n%<25>&X<>J0<4A>*N<00><>s<07><>з4r<08> <0C>۔<EFBFBD>Yvρ=GFZ<46><0E><><EFBFBD>9 #<23><>:;<3B><>Z<EFBFBD><5A>i<EFBFBD><69>(<28><> F<><46>}<13><><<3C>"rE<72>\<5C>E<03><><EFBFBD><EFBFBD> <0C><> !<02><><><E0AEBD>]<5D><>;<3B> ,-<2D>;lr<6C>I<EFBFBD>|<7C><><17>(<28>&x'0<><30><EFBFBD><EFBFBD><EFBFBD>Uw<55><77><EFBFBD>n<07>
>lV^1<t?<3F>2x}<7D><1D><>A<EFBFBD><41> <0B><>`<60>+<2B><><01>ưPZ<50>S<EFBFBD> <02>>a<>7Pw܉|<7C><>7ns
}=J<>-<12>k<EFBFBD><6B><EFBFBD><EFBFBD><EFBFBD>C)w<><77><EFBFBD>X<><58>{<7B>O<1C><>3<EFBFBD><<0F>9<EFBFBD><39>"{<7B><><EFBFBD><02><><03><><EFBFBD><EFBFBD><EFBFBD>ny<6E><79>Z<EFBFBD>E<EFBFBD><45><EFBFBD>;<3B><11>J<EFBFBD>mN<6D><11>"<22><><EFBFBD><EFBFBD>>٭"<22>}><3E><><13>}<7D><>SO<53><<3C>۵D.z<><7A><EFBFBD> f%<25>V<EFBFBD>}<00> <09><> Ї<><1D><1B>M<EFBFBD><4D><EFBFBD>3<EFBFBD><33><EFBFBD><EFBFBD>]<5D><02>#Vx7<78>?<3F><><EFBFBD>9<EFBFBD><39><EFBFBD>C?<3F><><EFBFBD><EFBFBD><1F><EFBFBD>|<7C><>g<EFBFBD><67><EFBFBD><EFBFBD> /<2F><>JT<4A><54><EFBFBD>h<EFBFBD><68>*%<1E><>`mKU<4B><55><EFBFBD><EFBFBD><EFBFBD>Q<EFBFBD><13><><EFBFBD>=r<>:<3A><>x6x<36><78><EFBFBD>@|<7C><>G<EFBFBD><47><EFBFBD><EFBFBD><0F><13><>Ϸ<EFBFBD>z<EFBFBD>w<EFBFBD><77><EFBFBD>><3E><><EFBFBD>K/=<3D><>k<EFBFBD><6B>>37d<37><64>"S<>1ع00-<2D>4}<7D><>`<60>ag<05>]p<03><>W<EFBFBD><57><EFBFBD>k8<><38>ʜy<CA9C><79>?<3F>|<7C><><EFBFBD>}v<><76>K!<21><05>e<EFBFBD>h<EFBFBD>1;<02>ji<6A><69><EFBFBD><11><>1Ud+<2B>]MS<4D>@<40><13>B<EFBFBD>}<7D><><EFBFBD><EFBFBD>BN<1D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>/<2F>w<EFBFBD><77><EFBFBD><EFBFBD>-<06>Ry<52><79>G<EFBFBD>6<EFBFBD><36>
g8n`h<><68><17><>~3<>`{mS<13>!#o3<6F><33><EFBFBD>Lo<4C> <0A>ni9<69><39>s<EFBFBD>`uu<75><75><EFBFBD><><CFAD>R<EFBFBD>1C<31>)uE<75><45>/<2F> <09><>mC<6D><43>/Vxy<78>0MW+<2B><>9x<39>x<><78>62}<1A>=?<3F><>.Wܯ$<24><17><>Q<EFBFBD><51>1<EFBFBD>:<1E>'I<><49>mce<63><65>vVC<><43>s<EFBFBD>Q<EFBFBD><51><EFBFBD>A<>"0<><30>Mb<4D><62>턦V)<29><> k<0E><><EFBFBD> 4<>=<3D>V%MMD#I<>hS<68>yY<79>'<27>Bw<42><67><04>m1}n<19><>xY<07>!<21><5B<35><42>]<5D><>O<EFBFBD> <1D>m"<22><>`<04>4D/Q<1B><>h<EFBFBD><68><EFBFBD><EFBFBD><EFBFBD>$1z<><7A>K<EFBFBD><4B><EFBFBD><EFBFBD><0F><>k<EFBFBD><6B>I<EFBFBD>R<EFBFBD>SR+,G<><47>%<25><03><>_L<5F><4C><EFBFBD>F<EFBFBD>e<EFBFBD><13><>1<11>Q<EFBFBD>1J<31>ל<EFBFBD>b<EFBFBD><62> <0B><><EFBFBD><EFBFBD><EFBFBD>럾2qY<04><>Mw<4D><02><>:<3A>0S<30>U<EFBFBD>E<1B>ໞ^G<16>,xQ<78>QE<<3C><03>A{<7B><15><><EFBFBD>CG<43> <20>39<33>%0 <0B>]<5D>n<><6E>:<3A>EF<45>W<05>{<7B>򣷹x<F2A3B7B9> rxs<78>!{ <0C>8<08>E4<45>Bo<42>D,<2C> <09>q<EFBFBD><71>KB<4B>7 f<><66>%<25><><EFBFBD><EFBFBD>y<EFBFBD>v<EFBFBD><76><EFBFBD>:f<><66>nt+<2B>X<EFBFBD><58><EFBFBD>b<>__<5F>׷qG<71><47>`3<><33>^<5E><>39<33><18><><EFBFBD><EFBFBD>>/50Z<15><00><0F>-<2D>E<EFBFBD>\6<><36>^<5E>b,<2C><><06><><EFBFBD>,x<><78>'<27>vl<76>G<EFBFBD><47><EFBFBD><1B>Y<EFBFBD><59><0E> mg<6D>@/5DTZ
<EFBFBD><EFBFBD><EFBFBD>K<EFBFBD>P<EFBFBD><EFBFBD>r6<>\<5C>~ʬ8<CAAC><38>ԡN<>WJd>aC<61>K<EFBFBD>LJ<EFBFBD>3<EFBFBD><33>`V<>T<EFBFBD>iz<69>qcF.<2E>m<><6D><EFBFBD>,n<>?h<>Ԝ<EFBFBD><18><><EFBFBD><EFBFBD><EFBFBD>@<40><><EFBFBD><EFBFBD>rd~b<62><7F><EFBFBD>u<EFBFBD>7<EFBFBD>i<EFBFBD><69>ת<EFBFBD><D7AA><EFBFBD>w<1B><><EFBFBD>2X<32><58>b<13><><EFBFBD><EFBFBD><EFBFBD>p<EFBFBD> e<01><><EFBFBD>u<EFBFBD><75><EFBFBD>Jj<4A><6A><EFBFBD><EFBFBD><EFBFBD>Rx6\<5C>g<>u<EFBFBD>rn<0E><> <0C><><EFBFBD>*(<28><><EFBFBD><11>*<2A><><EFBFBD><EFBFBD>7x<37><78><jM<6A><19><><EFBFBD>}<7D><><03><><05><>y<EFBFBD>E&l4<6C>΢Dv<03><>M<EFBFBD>.1X<EFBFBD><EFBFBD><EFBFBD><EFBFBD> <0A><>eנxOD<04>kE<6B><45>XjpJk<4A>e<EFBFBD>'&q<>Ք<EFBFBD>b<><62>v<EFBFBD><76><EFBFBD><13><><EFBFBD>&<12><01>'<27><><EFBFBD>!<1B><><1E><><1A>q<EFBFBD>R<EFBFBD><<3C>D .-<2D><><18>d2g]<5D><>A_:-0><3E>~<7E><><EFBFBD>.<2E><>k<EFBFBD> <0C> <0B>#<23><><EFBFBD>Q<<3C><>=:<3A>Ƶ<EFBFBD><C6B5>W <20>Ue\<&> <0E><><EFBFBD><EFBFBD>X܇uCO;=nd<6E>"<22>饆fA<66>Kxx<78><78>r<EFBFBD><72><EFBFBD>[s<>(Vu<56><A<>ƐU <20>B<04>=<3D><>B<EFBFBD><42>Yʴ<><CAB4>f&s4<73>3<>hsI<73>9Q+=u<><75><EFBFBD>B<><42><EFBFBD>5<EFBFBD>`<60>#<23>F<EFBFBD>5<EFBFBD>\9<><39>"<1B><>!{8<>4<><34>h<06><>V<EFBFBD><56>bھz<DABE> 3<>3T:+<2B><><EFBFBD><15>R<EFBFBD>,A<><41>#F<>`<60><><EFBFBD>Í<13>H<EFBFBD><48> <0A><>3<EFBFBD><33>4C<34>N<>B<EFBFBD>KhOs<><73><>цp1[<16>qi<71>Nɥǔ<C9A5>})<29><18><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>oN9<>as<>p<EFBFBD>=<3D>I<EFBFBD>"/{C.x><3E>2<EFBFBD><32>DH4g29<32> ÷<>?<3F><>)<29><05><04><15>줬*<2A>Z<EFBFBD>Y<EFBFBD><59><EFBFBD>QjU<6A><55><EFBFBD>Lh/,<2C>z<EFBFBD>z<EFBFBD>Ͳ<EFBFBD>S<EFBFBD>M:΄<>vC<76> <14><><EFBFBD>#<23><><EFBFBD>H"לΤsl<73><6C><EFBFBD>&<26>a@z<><7A><EFBFBD><EFBFBD><01><04>(V<>Zkva<76>><3E>J<EFBFBD>d<1D><><EFBFBD>p<EFBFBD>l<03>K<EFBFBD><4B><EFBFBD>^|ɦn<C9A6>߾<EFBFBD> n<>Τ<><CEA4>`k<>ƭ<EFBFBD><C6AD><EFBFBD><EFBFBD><EFBFBD>9\/<2F><>~<7E><>`<60><>~y<>U<EFBFBD> <0B><><EFBFBD><10>i%j,<2C><><EFBFBD><EFBFBD><EFBFBD>9<EFBFBD><39><EFBFBD>ڔ<1C><><EFBFBD><EFBFBD><EFBFBD>^<5E>?<3F><><EFBFBD><EFBFBD>C<EFBFBD><43><EFBFBD>p<EFBFBD>e<EFBFBD><65>'W/<2F><18> <15>,<2C><1D><>1<EFBFBD><31><EFBFBD><EFBFBD>W<EFBFBD>Z`<1C><><EFBFBD>[<5B><>h}<7D>|<7C> !8<>F<EFBFBD>C<EFBFBD>x<1F>q<EFBFBD><71>
F<EFBFBD><EFBFBD><10><>i<15><04>b<EFBFBD><62>
Xu%{<7B>Ql<51><15><>o<EFBFBD>`L<>G<><47><EFBFBD><EFBFBD><EFBFBD><EFBFBD>{O<><4F><0F>{<7B><>ӗx<D397>\&<26>!<21><05>q<EFBFBD><15><>&{w<>Ok<4F><1A><><<3C> 0<><30><0E>p<EFBFBD><70>t<>5t<35><74><EFBFBD>Ãp<C383><70><EFBFBD><EFBFBD>W <0A><>p<>Ca<43><61><EFBFBD><EFBFBD>.<14><><EFBFBD><EFBFBD><18><<3C>`<60><1A>9<EFBFBD><39><EFBFBD>ɔ(.,<18><18><><EFBFBD> <0C><>p<EFBFBD>#$ <0A>VBFlM<!/:05<30>`<14><><EFBFBD><EFBFBD>S<EFBFBD><53>X.<2E>l<EFBFBD><6C><EFBFBD><04><>+F[<5B><><04><>Qyq<79>^V<>Q<EFBFBD><51>g8a<16>?&<26><>rc<><63><EFBFBD>9<EFBFBD><15><>%<25><>3<EFBFBD><33>2<02>$<24><>p<><70>ՙ<EFBFBD>2<02><>J<EFBFBD><4A>u<EFBFBD><75>MvL\<5C>-p<><70>bQ<62><07>V<EFBFBD>F<> '<27><>|<7C><><03><>j<17><><EFBFBD> X<>OǦ><3E>`<11><e<><1C><><EFBFBD>p<EFBFBD><70>X+<2B><>2'+V<><56><EFBFBD>K<EFBFBD><0E>/<06>װ8<D7B0>h<EFBFBD><18>q<EFBFBD><71><EFBFBD>%<25><>,l<>[p<>r <0C><>{Y `<60>Y0\ <0C><><EFBFBD>t,&x/<2F>`<60>i<EFBFBD><69>.XYU⌢/<2F><>7<EFBFBD><37><EFBFBD>m<1A>3 j<><6A><EFBFBD>q<EFBFBD><71>F<EFBFBD><46><07>I<EFBFBD>`g<>`L<><1A><><04>9<EFBFBD><39><EFBFBD>zE<><45><EFBFBD>Wڒf<DA92><66><EFBFBD>,<2C>w<EFBFBD><13>5<EFBFBD>U<EFBFBD><55><EFBFBD>8U<38>RZ<52><5A><EFBFBD>DX<44><58><13><><05><><EFBFBD>UeV<65>wys'.é<><C3A9><EFBFBD>ϛ<06>*`<60>QV<51><56><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>,<2C><>+<2B>3W=1)O-}<7D><><EFBFBD><EFBFBD>c<><63><EFBFBD><EFBFBD><EFBFBD>pi郣<69><E983A3>+<2B>bU9<55><17><><EFBFBD><0F>c<><63><EFBFBD>(2 <09>K,<2C>* <0A>5f<35><66><EFBFBD><EFBFBD><EFBFBD><7F>祱Մ8k<38>K <0B><><EFBFBD>%6sP<73>b<EFBFBD>D^I<49>x<EFBFBD><78><07>T<EFBFBD><05>~<<3C>'N<><1E><<3C>d<EFBFBD>T#tm<>/<2F><>=O<>><3E>`rU<72><55>q<EFBFBD>ƌW<C68C>ݨ<EFBFBD><DDA8>X<EFBFBD><58><07>s<EFBFBD>iq<69>ڐ<<3C>T.<2E><>-}<7D><><EFBFBD><EFBFBD>_c<>V-%[<5B><>!["K<1F><>Y<EFBFBD>KP<4B>+3<><33><EFBFBD>d<19><><16>e]]J<><4A><EFBFBD>!<21>,<2C>*-<2D>I<EFBFBD>/6<><36><EFBFBD>Q~y<><79>Œ9:<3A><>CKw<1E>_<EFBFBD>(V<> <0C><><EFBFBD><05><><EFBFBD><05><><EFBFBD><05>G+ L<>+ L<>+ L<>+ L<>+ L<><4C><EFBFBD><05><><EFBFBD><05><><EFBFBD><05>"<22>e6=<3D>YIEND<4E>B`<60>