@tinycloud/web-sdk 3.16.0 → 3.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/modals.cjs +1 -2
- package/dist/modals.mjs +1 -2
- package/dist/modules/tcw.d.ts +25 -0
- package/dist/notifications/permissionExpansion.d.ts +6 -0
- package/dist/notifications/permissionExpansionBridge.d.ts +2 -0
- package/package.json +3 -3
- package/dist/modals.cjs.LICENSE.txt +0 -23
- package/dist/modals.mjs.LICENSE.txt +0 -23
package/dist/modals.cjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
/*! For license information please see modals.cjs.LICENSE.txt */
|
|
2
|
-
(()=>{var e,t,r={3725(e){"use strict";!function(){function t(e){return parseInt(e)===e}function r(e){if(!t(e.length))return!1;for(var r=0;r<e.length;r++)if(!t(e[r])||e[r]<0||e[r]>255)return!1;return!0}function n(e,n){if(e.buffer&&ArrayBuffer.isView(e)&&"Uint8Array"===e.name)return n&&(e=e.slice?e.slice():Array.prototype.slice.call(e)),e;if(Array.isArray(e)){if(!r(e))throw new Error("Array contains invalid value: "+e);return new Uint8Array(e)}if(t(e.length)&&r(e))return new Uint8Array(e);throw new Error("unsupported array-like object")}function i(e){return new Uint8Array(e)}function s(e,t,r,n,i){null==n&&null==i||(e=e.slice?e.slice(n,i):Array.prototype.slice.call(e,n,i)),t.set(e,r)}var o,a={toBytes:function(e){var t=[],r=0;for(e=encodeURI(e);r<e.length;){var i=e.charCodeAt(r++);37===i?(t.push(parseInt(e.substr(r,2),16)),r+=2):t.push(i)}return n(t)},fromBytes:function(e){for(var t=[],r=0;r<e.length;){var n=e[r];n<128?(t.push(String.fromCharCode(n)),r++):n>191&&n<224?(t.push(String.fromCharCode((31&n)<<6|63&e[r+1])),r+=2):(t.push(String.fromCharCode((15&n)<<12|(63&e[r+1])<<6|63&e[r+2])),r+=3)}return t.join("")}},c=(o="0123456789abcdef",{toBytes:function(e){for(var t=[],r=0;r<e.length;r+=2)t.push(parseInt(e.substr(r,2),16));return t},fromBytes:function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r];t.push(o[(240&n)>>4]+o[15&n])}return t.join("")}}),u={16:10,24:12,32:14},l=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],h=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],d=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],f=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],p=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],m=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],g=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],y=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],v=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],b=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],w=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],E=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],A=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],k=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],x=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function _(e){for(var t=[],r=0;r<e.length;r+=4)t.push(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]);return t}var T=function(e){if(!(this instanceof T))throw Error("AES must be instanitated with `new`");Object.defineProperty(this,"key",{value:n(e,!0)}),this._prepare()};T.prototype._prepare=function(){var e=u[this.key.length];if(null==e)throw new Error("invalid key size (must be 16, 24 or 32 bytes)");this._Ke=[],this._Kd=[];for(var t=0;t<=e;t++)this._Ke.push([0,0,0,0]),this._Kd.push([0,0,0,0]);var r,n=4*(e+1),i=this.key.length/4,s=_(this.key);for(t=0;t<i;t++)r=t>>2,this._Ke[r][t%4]=s[t],this._Kd[e-r][t%4]=s[t];for(var o,a=0,c=i;c<n;){if(o=s[i-1],s[0]^=h[o>>16&255]<<24^h[o>>8&255]<<16^h[255&o]<<8^h[o>>24&255]^l[a]<<24,a+=1,8!=i)for(t=1;t<i;t++)s[t]^=s[t-1];else{for(t=1;t<i/2;t++)s[t]^=s[t-1];for(o=s[i/2-1],s[i/2]^=h[255&o]^h[o>>8&255]<<8^h[o>>16&255]<<16^h[o>>24&255]<<24,t=i/2+1;t<i;t++)s[t]^=s[t-1]}for(t=0;t<i&&c<n;)d=c>>2,f=c%4,this._Ke[d][f]=s[t],this._Kd[e-d][f]=s[t++],c++}for(var d=1;d<e;d++)for(var f=0;f<4;f++)o=this._Kd[d][f],this._Kd[d][f]=E[o>>24&255]^A[o>>16&255]^k[o>>8&255]^x[255&o]},T.prototype.encrypt=function(e){if(16!=e.length)throw new Error("invalid plaintext size (must be 16 bytes)");for(var t=this._Ke.length-1,r=[0,0,0,0],n=_(e),s=0;s<4;s++)n[s]^=this._Ke[0][s];for(var o=1;o<t;o++){for(s=0;s<4;s++)r[s]=f[n[s]>>24&255]^p[n[(s+1)%4]>>16&255]^m[n[(s+2)%4]>>8&255]^g[255&n[(s+3)%4]]^this._Ke[o][s];n=r.slice()}var a,c=i(16);for(s=0;s<4;s++)a=this._Ke[t][s],c[4*s]=255&(h[n[s]>>24&255]^a>>24),c[4*s+1]=255&(h[n[(s+1)%4]>>16&255]^a>>16),c[4*s+2]=255&(h[n[(s+2)%4]>>8&255]^a>>8),c[4*s+3]=255&(h[255&n[(s+3)%4]]^a);return c},T.prototype.decrypt=function(e){if(16!=e.length)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var t=this._Kd.length-1,r=[0,0,0,0],n=_(e),s=0;s<4;s++)n[s]^=this._Kd[0][s];for(var o=1;o<t;o++){for(s=0;s<4;s++)r[s]=y[n[s]>>24&255]^v[n[(s+3)%4]>>16&255]^b[n[(s+2)%4]>>8&255]^w[255&n[(s+1)%4]]^this._Kd[o][s];n=r.slice()}var a,c=i(16);for(s=0;s<4;s++)a=this._Kd[t][s],c[4*s]=255&(d[n[s]>>24&255]^a>>24),c[4*s+1]=255&(d[n[(s+3)%4]>>16&255]^a>>16),c[4*s+2]=255&(d[n[(s+2)%4]>>8&255]^a>>8),c[4*s+3]=255&(d[255&n[(s+1)%4]]^a);return c};var S=function(e){if(!(this instanceof S))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new T(e)};S.prototype.encrypt=function(e){if((e=n(e)).length%16!=0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var t=i(e.length),r=i(16),o=0;o<e.length;o+=16)s(e,r,0,o,o+16),s(r=this._aes.encrypt(r),t,o);return t},S.prototype.decrypt=function(e){if((e=n(e)).length%16!=0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var t=i(e.length),r=i(16),o=0;o<e.length;o+=16)s(e,r,0,o,o+16),s(r=this._aes.decrypt(r),t,o);return t};var I=function(e,t){if(!(this instanceof I))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Block Chaining",this.name="cbc",t){if(16!=t.length)throw new Error("invalid initialation vector size (must be 16 bytes)")}else t=i(16);this._lastCipherblock=n(t,!0),this._aes=new T(e)};I.prototype.encrypt=function(e){if((e=n(e)).length%16!=0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var t=i(e.length),r=i(16),o=0;o<e.length;o+=16){s(e,r,0,o,o+16);for(var a=0;a<16;a++)r[a]^=this._lastCipherblock[a];this._lastCipherblock=this._aes.encrypt(r),s(this._lastCipherblock,t,o)}return t},I.prototype.decrypt=function(e){if((e=n(e)).length%16!=0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var t=i(e.length),r=i(16),o=0;o<e.length;o+=16){s(e,r,0,o,o+16),r=this._aes.decrypt(r);for(var a=0;a<16;a++)t[o+a]=r[a]^this._lastCipherblock[a];s(e,this._lastCipherblock,0,o,o+16)}return t};var N=function(e,t,r){if(!(this instanceof N))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Feedback",this.name="cfb",t){if(16!=t.length)throw new Error("invalid initialation vector size (must be 16 size)")}else t=i(16);r||(r=1),this.segmentSize=r,this._shiftRegister=n(t,!0),this._aes=new T(e)};N.prototype.encrypt=function(e){if(e.length%this.segmentSize!=0)throw new Error("invalid plaintext size (must be segmentSize bytes)");for(var t,r=n(e,!0),i=0;i<r.length;i+=this.segmentSize){t=this._aes.encrypt(this._shiftRegister);for(var o=0;o<this.segmentSize;o++)r[i+o]^=t[o];s(this._shiftRegister,this._shiftRegister,0,this.segmentSize),s(r,this._shiftRegister,16-this.segmentSize,i,i+this.segmentSize)}return r},N.prototype.decrypt=function(e){if(e.length%this.segmentSize!=0)throw new Error("invalid ciphertext size (must be segmentSize bytes)");for(var t,r=n(e,!0),i=0;i<r.length;i+=this.segmentSize){t=this._aes.encrypt(this._shiftRegister);for(var o=0;o<this.segmentSize;o++)r[i+o]^=t[o];s(this._shiftRegister,this._shiftRegister,0,this.segmentSize),s(e,this._shiftRegister,16-this.segmentSize,i,i+this.segmentSize)}return r};var R=function(e,t){if(!(this instanceof R))throw Error("AES must be instanitated with `new`");if(this.description="Output Feedback",this.name="ofb",t){if(16!=t.length)throw new Error("invalid initialation vector size (must be 16 bytes)")}else t=i(16);this._lastPrecipher=n(t,!0),this._lastPrecipherIndex=16,this._aes=new T(e)};R.prototype.encrypt=function(e){for(var t=n(e,!0),r=0;r<t.length;r++)16===this._lastPrecipherIndex&&(this._lastPrecipher=this._aes.encrypt(this._lastPrecipher),this._lastPrecipherIndex=0),t[r]^=this._lastPrecipher[this._lastPrecipherIndex++];return t},R.prototype.decrypt=R.prototype.encrypt;var O=function(e){if(!(this instanceof O))throw Error("Counter must be instanitated with `new`");0===e||e||(e=1),"number"==typeof e?(this._counter=i(16),this.setValue(e)):this.setBytes(e)};O.prototype.setValue=function(e){if("number"!=typeof e||parseInt(e)!=e)throw new Error("invalid counter value (must be an integer)");for(var t=15;t>=0;--t)this._counter[t]=e%256,e>>=8},O.prototype.setBytes=function(e){if(16!=(e=n(e,!0)).length)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=e},O.prototype.increment=function(){for(var e=15;e>=0;e--){if(255!==this._counter[e]){this._counter[e]++;break}this._counter[e]=0}};var C=function(e,t){if(!(this instanceof C))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",t instanceof O||(t=new O(t)),this._counter=t,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new T(e)};C.prototype.encrypt=function(e){for(var t=n(e,!0),r=0;r<t.length;r++)16===this._remainingCounterIndex&&(this._remainingCounter=this._aes.encrypt(this._counter._counter),this._remainingCounterIndex=0,this._counter.increment()),t[r]^=this._remainingCounter[this._remainingCounterIndex++];return t},C.prototype.decrypt=C.prototype.encrypt;var P={AES:T,Counter:O,ModeOfOperation:{ecb:S,cbc:I,cfb:N,ofb:R,ctr:C},utils:{hex:c,utf8:a},padding:{pkcs7:{pad:function(e){var t=16-(e=n(e,!0)).length%16,r=i(e.length+t);s(e,r);for(var o=e.length;o<r.length;o++)r[o]=t;return r},strip:function(e){if((e=n(e,!0)).length<16)throw new Error("PKCS#7 invalid length");var t=e[e.length-1];if(t>16)throw new Error("PKCS#7 padding byte out of range");for(var r=e.length-t,o=0;o<t;o++)if(e[r+o]!==t)throw new Error("PKCS#7 invalid padding byte");var a=i(r);return s(e,a,0,0,r),a}}},_arrayTest:{coerceArray:n,createArray:i,copyArray:s}};e.exports=P}()},8748(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isUri=t.ParsedMessage=void 0;const i=r(9851),s=r(8651),o=n(r(4202)),a=new i.grammar;t.ParsedMessage=class{constructor(e){const t=new o.default.parser;t.callbacks["sign-in-with-ethereum"]=s.cb.signInWithEtherium,t.callbacks.oscheme=s.cb.oscheme,t.callbacks.domain=s.cb.domain,t.callbacks.LF=s.cb.lineno,t.callbacks["ex-title"]=s.cb.exTitle,t.callbacks["nb-title"]=s.cb.nbTitle,t.callbacks["ri-title"]=s.cb.riTitle,t.callbacks["re-title"]=s.cb.reTitle,t.callbacks.address=s.cb.address,t.callbacks.statement=s.cb.statement,t.callbacks["empty-statement"]=s.cb.emptyStatement,t.callbacks.version=s.cb.version,t.callbacks["chain-id"]=s.cb.chainId,t.callbacks.nonce=s.cb.nonce,t.callbacks["issued-at"]=s.cb.issuedAt,t.callbacks["expiration-time"]=s.cb.expirationTime,t.callbacks["not-before"]=s.cb.notBefore,t.callbacks["request-id"]=s.cb.requestId,t.callbacks.uri=s.cb.uri,t.callbacks["uri-r"]=s.cb.uriR,t.callbacks.resource=s.cb.resource,t.callbacks.scheme=s.cb.scheme,t.callbacks["userinfo-at"]=s.cb.userinfo,t.callbacks.host=s.cb.host,t.callbacks["IP-literal"]=s.cb.ipLiteral,t.callbacks.port=s.cb.port,t.callbacks["path-abempty"]=s.cb.pathAbempty,t.callbacks["path-absolute"]=s.cb.pathAbsolute,t.callbacks["path-rootless"]=s.cb.pathRootless,t.callbacks["path-empty"]=s.cb.pathEmpty,t.callbacks.query=s.cb.query,t.callbacks.fragment=s.cb.fragment,t.callbacks.IPv4address=s.cb.ipv4,t.callbacks.nodcolon=s.cb.nodcolon,t.callbacks.dcolon=s.cb.dcolon,t.callbacks.h16=s.cb.h16,t.callbacks.h16c=s.cb.h16,t.callbacks.h16n=s.cb.h16,t.callbacks.h16cn=s.cb.h16,t.callbacks["dec-octet"]=s.cb.decOctet,t.callbacks["dec-digit"]=s.cb.decDigit;const r={errors:[],lineno:1,scheme:void 0,domain:void 0,address:void 0,statement:void 0,uri:void 0,version:void 0,chainId:void 0,nonce:void 0,issuedAt:void 0,expirationTime:void 0,notBefore:void 0,requestId:void 0,resources:void 0,uriElements:{scheme:void 0,userinfo:void 0,host:void 0,port:void 0,path:void 0,query:void 0,fragment:void 0}},n=t.parse(a,0,e,r);let i="";for(let e=0;e<r.errors.length;e+=1)i+=r.errors[e]+"\n";if(n.success||(i+=`Invalid message: ${JSON.stringify(n)}`),""!==i)throw new Error(i);this.scheme=r.scheme,this.domain=r.domain,this.address=r.address,this.statement=r.statement,this.uri=r.uri,this.version=r.version,this.chainId=r.chainId,this.nonce=r.nonce,this.issuedAt=r.issuedAt,this.expirationTime=r.expirationTime,this.notBefore=r.notBefore,this.requestId=r.requestId,this.resources=r.resources,this.uriElements=r.uriElements}},t.isUri=e=>{const t=new o.default.parser;return t.callbacks["IP-literal"]=s.cb.ipLiteral,t.callbacks.IPv4address=s.cb.ipv4,t.callbacks.nodcolon=s.cb.nodcolon,t.callbacks.dcolon=s.cb.dcolon,t.callbacks.h16=s.cb.h16,t.callbacks.h16c=s.cb.h16,t.callbacks.h16n=s.cb.h16,t.callbacks.h16cn=s.cb.h16,t.callbacks["dec-octet"]=s.cb.decOctet,t.callbacks["dec-digit"]=s.cb.decDigit,t.parse(a,"uri-r",e,{errors:[]}).success}},8651(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cb=void 0;const i=n(r(4202)),s=i.default.utils,o=i.default.ids,a=r(2626),c=/^(?<date>[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(.[0-9]+)?(([Zz])|([+|-]([01][0-9]|2[0-3]):[0-5][0-9]))$/,u=e=>{const t=c.exec(e);if(!t)return!1;const r=new Date(t.groups.date).toISOString(),n=c.exec(r);return t.groups.date===n.groups.date};t.cb={signInWithEtherium:function(e,t,r,n){switch(e.state){case o.ACTIVE:if("object"!=typeof n||null===n)throw new Error("data must be an object");break;case o.NOMATCH:n.errors.push(`invalid message: max line number was ${n.lineno}`)}},lineno:function(e,t,r,n){e.state===o.MATCH&&(n.lineno+=1)},exTitle:function(e,t,r,n){e.state===o.NOMATCH&&(n.lineno-=1)},nbTitle:function(e,t,r,n){e.state===o.NOMATCH&&(n.lineno-=1)},riTitle:function(e,t,r,n){e.state===o.NOMATCH&&(n.lineno-=1)},reTitle:function(e,t,r,n){e.state===o.MATCH?n.resources=[]:e.state===o.NOMATCH&&(n.lineno-=1)},oscheme:function(e,t,r,n){e.state===o.MATCH&&(n.scheme=s.charsToString(t,r,e.phraseLength-3))},domain:function(e,t,r,n){switch(e.state){case o.MATCH:n.domain=s.charsToString(t,r,e.phraseLength);break;case o.EMPTY:n.errors.push(`line ${n.lineno}: domain cannot be empty`);break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid domain`)}},address:function(e,t,r,n){switch(e.state){case o.MATCH:n.address=s.charsToString(t,r,e.phraseLength),(0,a.isEIP55Address)(n.address)||n.errors.push(`line ${n.lineno}: invalid EIP-55 address - ${n.address}`);break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid address`)}},statement:function(e,t,r,n){e.state===o.MATCH&&(n.statement=s.charsToString(t,r,e.phraseLength))},emptyStatement:function(e,t,r,n){e.state===o.MATCH&&(n.statement="")},version:function(e,t,r,n){switch(e.state){case o.MATCH:n.version=s.charsToString(t,r,e.phraseLength);break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid version`)}},nonce:function(e,t,r,n){switch(e.state){case o.MATCH:n.nonce=s.charsToString(t,r,e.phraseLength);break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid nonce`)}},issuedAt:function(e,t,r,n){switch(e.state){case o.MATCH:n.issuedAt=s.charsToString(t,r,e.phraseLength),u(n.issuedAt)||n.errors.push(`line ${n.lineno}: invalid issued-at date time semantics`);break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid issued-at date time syntax`)}},expirationTime:function(e,t,r,n){switch(e.state){case o.MATCH:n.expirationTime=s.charsToString(t,r,e.phraseLength),u(n.expirationTime)||n.errors.push(`line ${n.lineno}: invalid expiration-time date time semantics`);break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid expiration-time date time syntax`)}},notBefore:function(e,t,r,n){switch(e.state){case o.MATCH:n.notBefore=s.charsToString(t,r,e.phraseLength),u(n.notBefore)||n.errors.push(`line ${n.lineno}: invalid not-before date time semantics`);break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid not-before date time syntax`)}},requestId:function(e,t,r,n){switch(e.state){case o.MATCH:n.requestId=s.charsToString(t,r,e.phraseLength);break;case o.EMPTY:n.requestId="";break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid requestID`)}},chainId:function(e,t,r,n){switch(e.state){case o.MATCH:n.chainId=(0,a.parseIntegerNumber)(s.charsToString(t,r,e.phraseLength));break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid chain-id`)}},uriR:function(e,t,r,n){switch(e.state){case o.MATCH:n.uriR=s.charsToString(t,r,e.phraseLength);break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid resource URI`)}},resource:function(e,t,r,n){switch(e.state){case o.MATCH:n.resources.push(n.uriR),delete n.uriR;break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid resource`)}},scheme:function(e,t,r,n){switch(e.state){case o.MATCH:n.uriElements.scheme=s.charsToString(t,r,e.phraseLength);break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid URI scheme`)}},userinfo:function(e,t,r,n){e.state===o.MATCH&&(n.uriElements.userinfo=s.charsToString(t,r,e.phraseLength-1))},host:function(e,t,r,n){switch(e.state){case o.ACTIVE:n.iplit=!1;break;case o.MATCH:n.iplit?n.uriElements.host=s.charsToString(t,r+1,e.phraseLength-2):n.uriElements.host=s.charsToString(t,r,e.phraseLength);break;case o.EMPTY:n.uriElements.host="";break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid URI host`)}},ipLiteral:function(e,t,r,n){e.state===o.MATCH&&(n.iplit=!0)},port:function(e,t,r,n){switch(e.state){case o.MATCH:n.uriElements.port=(0,a.parseIntegerNumber)(s.charsToString(t,r,e.phraseLength));break;case o.EMPTY:n.uriElements.port="";break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid URI port`)}},pathAbempty:function(e,t,r,n){switch(e.state){case o.MATCH:n.uriElements.path=s.charsToString(t,r,e.phraseLength);break;case o.EMPTY:n.uriElements.path="";break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid URI path-abempty`)}},pathAbsolute:function(e,t,r,n){e.state===o.MATCH&&(n.uriElements.path=s.charsToString(t,r,e.phraseLength))},pathRootless:function(e,t,r,n){e.state===o.MATCH&&(n.uriElements.path=s.charsToString(t,r,e.phraseLength))},pathEmpty:function(e,t,r,n){switch(e.state){case o.MATCH:case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid URI - path-empty must be empty`);break;case o.EMPTY:n.uriElements.path=""}},query:function(e,t,r,n){switch(e.state){case o.MATCH:n.uriElements.query=s.charsToString(t,r,e.phraseLength);break;case o.EMPTY:n.uriElements.query="";break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid URI query`)}},fragment:function(e,t,r,n){switch(e.state){case o.MATCH:n.uriElements.fragment=s.charsToString(t,r,e.phraseLength);break;case o.EMPTY:n.uriElements.fragment="";break;case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid URI fragment`)}},uri:function(e,t,r,n){switch(e.state){case o.MATCH:n.uri=s.charsToString(t,r,e.phraseLength);break;case o.EMPTY:case o.NOMATCH:n.errors.push(`line ${n.lineno}: invalid URI`)}},ipv4:function(e,t,r,n){e.state===o.MATCH&&(n.ipv4=!0)},h16:function(e,t,r,n){e.state===o.MATCH&&(n.h16count+=1)},nodcolon:function(e,t,r,n){switch(e.state){case o.ACTIVE:n.h16count=0,n.ipv4=!1;break;case o.MATCH:n.ipv4?6===n.h16count?e.state=o.MATCH:(e.state=o.NOMATCH,e.phraseLength=0):8===n.h16count?e.state=o.MATCH:(e.state=o.NOMATCH,e.phraseLength=0)}},dcolon:function(e,t,r,n){switch(e.state){case o.ACTIVE:n.h16count=0,n.ipv4=!1;break;case o.MATCH:n.ipv4?n.h16count<6?e.state=o.MATCH:(e.state=o.NOMATCH,e.phraseLength=0):n.h16count<8?e.state=o.MATCH:(e.state=o.NOMATCH,e.phraseLength=0)}},decOctet:function(e,t,r,n){switch(e.state){case o.ACTIVE:n.octet=0;break;case o.MATCH:n.octet>255?(e.state=o.NOMATCH,e.phraseLength=0):e.state=o.MATCH}},decDigit:function(e,t,r,n){e.state===o.MATCH&&(n.octet=10*n.octet+t[r]-48)}}},2311(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.isUri=t.ParsedMessage=void 0;const s=r(8748);Object.defineProperty(t,"ParsedMessage",{enumerable:!0,get:function(){return s.ParsedMessage}});const o=r(8748);Object.defineProperty(t,"isUri",{enumerable:!0,get:function(){return o.isUri}}),i(r(2626),t)},9851(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.grammar=void 0,t.grammar=function(){this.grammarObject="grammarObject",this.rules=[],this.rules[0]={name:"sign-in-with-ethereum",lower:"sign-in-with-ethereum",index:0,isBkr:!1},this.rules[1]={name:"ex-title",lower:"ex-title",index:1,isBkr:!1},this.rules[2]={name:"nb-title",lower:"nb-title",index:2,isBkr:!1},this.rules[3]={name:"ri-title",lower:"ri-title",index:3,isBkr:!1},this.rules[4]={name:"re-title",lower:"re-title",index:4,isBkr:!1},this.rules[5]={name:"oscheme",lower:"oscheme",index:5,isBkr:!1},this.rules[6]={name:"domain",lower:"domain",index:6,isBkr:!1},this.rules[7]={name:"address",lower:"address",index:7,isBkr:!1},this.rules[8]={name:"statement",lower:"statement",index:8,isBkr:!1},this.rules[9]={name:"empty-statement",lower:"empty-statement",index:9,isBkr:!1},this.rules[10]={name:"version",lower:"version",index:10,isBkr:!1},this.rules[11]={name:"nonce",lower:"nonce",index:11,isBkr:!1},this.rules[12]={name:"issued-at",lower:"issued-at",index:12,isBkr:!1},this.rules[13]={name:"expiration-time",lower:"expiration-time",index:13,isBkr:!1},this.rules[14]={name:"not-before",lower:"not-before",index:14,isBkr:!1},this.rules[15]={name:"request-id",lower:"request-id",index:15,isBkr:!1},this.rules[16]={name:"chain-id",lower:"chain-id",index:16,isBkr:!1},this.rules[17]={name:"resources",lower:"resources",index:17,isBkr:!1},this.rules[18]={name:"resource",lower:"resource",index:18,isBkr:!1},this.rules[19]={name:"URI",lower:"uri",index:19,isBkr:!1},this.rules[20]={name:"hier-part",lower:"hier-part",index:20,isBkr:!1},this.rules[21]={name:"scheme",lower:"scheme",index:21,isBkr:!1},this.rules[22]={name:"authority",lower:"authority",index:22,isBkr:!1},this.rules[23]={name:"path-abempty",lower:"path-abempty",index:23,isBkr:!1},this.rules[24]={name:"path-absolute",lower:"path-absolute",index:24,isBkr:!1},this.rules[25]={name:"path-rootless",lower:"path-rootless",index:25,isBkr:!1},this.rules[26]={name:"path-empty",lower:"path-empty",index:26,isBkr:!1},this.rules[27]={name:"userinfo-at",lower:"userinfo-at",index:27,isBkr:!1},this.rules[28]={name:"userinfo",lower:"userinfo",index:28,isBkr:!1},this.rules[29]={name:"host",lower:"host",index:29,isBkr:!1},this.rules[30]={name:"IP-literal",lower:"ip-literal",index:30,isBkr:!1},this.rules[31]={name:"IPvFuture",lower:"ipvfuture",index:31,isBkr:!1},this.rules[32]={name:"IPv6address",lower:"ipv6address",index:32,isBkr:!1},this.rules[33]={name:"nodcolon",lower:"nodcolon",index:33,isBkr:!1},this.rules[34]={name:"dcolon",lower:"dcolon",index:34,isBkr:!1},this.rules[35]={name:"h16",lower:"h16",index:35,isBkr:!1},this.rules[36]={name:"h16c",lower:"h16c",index:36,isBkr:!1},this.rules[37]={name:"h16n",lower:"h16n",index:37,isBkr:!1},this.rules[38]={name:"h16cn",lower:"h16cn",index:38,isBkr:!1},this.rules[39]={name:"IPv4address",lower:"ipv4address",index:39,isBkr:!1},this.rules[40]={name:"dec-octet",lower:"dec-octet",index:40,isBkr:!1},this.rules[41]={name:"dec-digit",lower:"dec-digit",index:41,isBkr:!1},this.rules[42]={name:"reg-name",lower:"reg-name",index:42,isBkr:!1},this.rules[43]={name:"reg-name-char",lower:"reg-name-char",index:43,isBkr:!1},this.rules[44]={name:"port",lower:"port",index:44,isBkr:!1},this.rules[45]={name:"query",lower:"query",index:45,isBkr:!1},this.rules[46]={name:"fragment",lower:"fragment",index:46,isBkr:!1},this.rules[47]={name:"URI-r",lower:"uri-r",index:47,isBkr:!1},this.rules[48]={name:"hier-part-r",lower:"hier-part-r",index:48,isBkr:!1},this.rules[49]={name:"scheme-r",lower:"scheme-r",index:49,isBkr:!1},this.rules[50]={name:"query-r",lower:"query-r",index:50,isBkr:!1},this.rules[51]={name:"fragment-r",lower:"fragment-r",index:51,isBkr:!1},this.rules[52]={name:"authority-d",lower:"authority-d",index:52,isBkr:!1},this.rules[53]={name:"userinfo-d",lower:"userinfo-d",index:53,isBkr:!1},this.rules[54]={name:"host-d",lower:"host-d",index:54,isBkr:!1},this.rules[55]={name:"port-d",lower:"port-d",index:55,isBkr:!1},this.rules[56]={name:"path-abempty-r",lower:"path-abempty-r",index:56,isBkr:!1},this.rules[57]={name:"path-absolute-r",lower:"path-absolute-r",index:57,isBkr:!1},this.rules[58]={name:"path-rootless-r",lower:"path-rootless-r",index:58,isBkr:!1},this.rules[59]={name:"path-empty-r",lower:"path-empty-r",index:59,isBkr:!1},this.rules[60]={name:"segment",lower:"segment",index:60,isBkr:!1},this.rules[61]={name:"segment-nz",lower:"segment-nz",index:61,isBkr:!1},this.rules[62]={name:"pchar",lower:"pchar",index:62,isBkr:!1},this.rules[63]={name:"pct-encoded",lower:"pct-encoded",index:63,isBkr:!1},this.rules[64]={name:"date-fullyear",lower:"date-fullyear",index:64,isBkr:!1},this.rules[65]={name:"date-month",lower:"date-month",index:65,isBkr:!1},this.rules[66]={name:"date-mday",lower:"date-mday",index:66,isBkr:!1},this.rules[67]={name:"time-hour",lower:"time-hour",index:67,isBkr:!1},this.rules[68]={name:"time-minute",lower:"time-minute",index:68,isBkr:!1},this.rules[69]={name:"time-second",lower:"time-second",index:69,isBkr:!1},this.rules[70]={name:"time-secfrac",lower:"time-secfrac",index:70,isBkr:!1},this.rules[71]={name:"time-numoffset",lower:"time-numoffset",index:71,isBkr:!1},this.rules[72]={name:"time-offset",lower:"time-offset",index:72,isBkr:!1},this.rules[73]={name:"partial-time",lower:"partial-time",index:73,isBkr:!1},this.rules[74]={name:"full-date",lower:"full-date",index:74,isBkr:!1},this.rules[75]={name:"full-time",lower:"full-time",index:75,isBkr:!1},this.rules[76]={name:"date-time",lower:"date-time",index:76,isBkr:!1},this.rules[77]={name:"ALPHA",lower:"alpha",index:77,isBkr:!1},this.rules[78]={name:"LF",lower:"lf",index:78,isBkr:!1},this.rules[79]={name:"DIGIT",lower:"digit",index:79,isBkr:!1},this.rules[80]={name:"HEXDIG",lower:"hexdig",index:80,isBkr:!1},this.udts=[],this.rules[0].opcodes=[],this.rules[0].opcodes[0]={type:2,children:[1,2,3,4,5,6,7,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,36,41,46]},this.rules[0].opcodes[1]={type:4,index:5},this.rules[0].opcodes[2]={type:4,index:6},this.rules[0].opcodes[3]={type:6,string:[32,119,97,110,116,115,32,121,111,117,32,116,111,32,115,105,103,110,32,105,110,32,119,105,116,104,32,121,111,117,114,32,69,116,104,101,114,101,117,109,32,97,99,99,111,117,110,116,58]},this.rules[0].opcodes[4]={type:4,index:78},this.rules[0].opcodes[5]={type:4,index:7},this.rules[0].opcodes[6]={type:4,index:78},this.rules[0].opcodes[7]={type:1,children:[8,13,14]},this.rules[0].opcodes[8]={type:2,children:[9,10,11,12]},this.rules[0].opcodes[9]={type:4,index:78},this.rules[0].opcodes[10]={type:4,index:8},this.rules[0].opcodes[11]={type:4,index:78},this.rules[0].opcodes[12]={type:4,index:78},this.rules[0].opcodes[13]={type:4,index:9},this.rules[0].opcodes[14]={type:2,children:[15,16]},this.rules[0].opcodes[15]={type:4,index:78},this.rules[0].opcodes[16]={type:4,index:78},this.rules[0].opcodes[17]={type:6,string:[85,82,73,58,32]},this.rules[0].opcodes[18]={type:4,index:19},this.rules[0].opcodes[19]={type:4,index:78},this.rules[0].opcodes[20]={type:6,string:[86,101,114,115,105,111,110,58,32]},this.rules[0].opcodes[21]={type:4,index:10},this.rules[0].opcodes[22]={type:4,index:78},this.rules[0].opcodes[23]={type:6,string:[67,104,97,105,110,32,73,68,58,32]},this.rules[0].opcodes[24]={type:4,index:16},this.rules[0].opcodes[25]={type:4,index:78},this.rules[0].opcodes[26]={type:6,string:[78,111,110,99,101,58,32]},this.rules[0].opcodes[27]={type:4,index:11},this.rules[0].opcodes[28]={type:4,index:78},this.rules[0].opcodes[29]={type:6,string:[73,115,115,117,101,100,32,65,116,58,32]},this.rules[0].opcodes[30]={type:4,index:12},this.rules[0].opcodes[31]={type:3,min:0,max:1},this.rules[0].opcodes[32]={type:2,children:[33,34,35]},this.rules[0].opcodes[33]={type:4,index:78},this.rules[0].opcodes[34]={type:4,index:1},this.rules[0].opcodes[35]={type:4,index:13},this.rules[0].opcodes[36]={type:3,min:0,max:1},this.rules[0].opcodes[37]={type:2,children:[38,39,40]},this.rules[0].opcodes[38]={type:4,index:78},this.rules[0].opcodes[39]={type:4,index:2},this.rules[0].opcodes[40]={type:4,index:14},this.rules[0].opcodes[41]={type:3,min:0,max:1},this.rules[0].opcodes[42]={type:2,children:[43,44,45]},this.rules[0].opcodes[43]={type:4,index:78},this.rules[0].opcodes[44]={type:4,index:3},this.rules[0].opcodes[45]={type:4,index:15},this.rules[0].opcodes[46]={type:3,min:0,max:1},this.rules[0].opcodes[47]={type:2,children:[48,49,50]},this.rules[0].opcodes[48]={type:4,index:78},this.rules[0].opcodes[49]={type:4,index:4},this.rules[0].opcodes[50]={type:4,index:17},this.rules[1].opcodes=[],this.rules[1].opcodes[0]={type:6,string:[69,120,112,105,114,97,116,105,111,110,32,84,105,109,101,58,32]},this.rules[2].opcodes=[],this.rules[2].opcodes[0]={type:6,string:[78,111,116,32,66,101,102,111,114,101,58,32]},this.rules[3].opcodes=[],this.rules[3].opcodes[0]={type:6,string:[82,101,113,117,101,115,116,32,73,68,58,32]},this.rules[4].opcodes=[],this.rules[4].opcodes[0]={type:6,string:[82,101,115,111,117,114,99,101,115,58]},this.rules[5].opcodes=[],this.rules[5].opcodes[0]={type:3,min:0,max:1},this.rules[5].opcodes[1]={type:2,children:[2,3,9]},this.rules[5].opcodes[2]={type:4,index:77},this.rules[5].opcodes[3]={type:3,min:0,max:1/0},this.rules[5].opcodes[4]={type:1,children:[5,6,7,8]},this.rules[5].opcodes[5]={type:4,index:77},this.rules[5].opcodes[6]={type:4,index:79},this.rules[5].opcodes[7]={type:6,string:[43]},this.rules[5].opcodes[8]={type:5,min:45,max:46},this.rules[5].opcodes[9]={type:7,string:[58,47,47]},this.rules[6].opcodes=[],this.rules[6].opcodes[0]={type:4,index:52},this.rules[7].opcodes=[],this.rules[7].opcodes[0]={type:2,children:[1,2]},this.rules[7].opcodes[1]={type:7,string:[48,120]},this.rules[7].opcodes[2]={type:3,min:40,max:40},this.rules[7].opcodes[3]={type:4,index:80},this.rules[8].opcodes=[],this.rules[8].opcodes[0]={type:3,min:1,max:1/0},this.rules[8].opcodes[1]={type:1,children:[2,3,4,5,6,7,8,9,10,11,12,13]},this.rules[8].opcodes[2]={type:5,min:97,max:122},this.rules[8].opcodes[3]={type:5,min:65,max:90},this.rules[8].opcodes[4]={type:5,min:48,max:57},this.rules[8].opcodes[5]={type:5,min:32,max:33},this.rules[8].opcodes[6]={type:5,min:35,max:36},this.rules[8].opcodes[7]={type:5,min:38,max:59},this.rules[8].opcodes[8]={type:6,string:[61]},this.rules[8].opcodes[9]={type:5,min:63,max:64},this.rules[8].opcodes[10]={type:6,string:[91]},this.rules[8].opcodes[11]={type:6,string:[93]},this.rules[8].opcodes[12]={type:6,string:[95]},this.rules[8].opcodes[13]={type:6,string:[126]},this.rules[9].opcodes=[],this.rules[9].opcodes[0]={type:2,children:[1,2,3]},this.rules[9].opcodes[1]={type:4,index:78},this.rules[9].opcodes[2]={type:4,index:78},this.rules[9].opcodes[3]={type:4,index:78},this.rules[10].opcodes=[],this.rules[10].opcodes[0]={type:7,string:[49]},this.rules[11].opcodes=[],this.rules[11].opcodes[0]={type:3,min:8,max:1/0},this.rules[11].opcodes[1]={type:1,children:[2,3]},this.rules[11].opcodes[2]={type:4,index:77},this.rules[11].opcodes[3]={type:4,index:79},this.rules[12].opcodes=[],this.rules[12].opcodes[0]={type:4,index:76},this.rules[13].opcodes=[],this.rules[13].opcodes[0]={type:4,index:76},this.rules[14].opcodes=[],this.rules[14].opcodes[0]={type:4,index:76},this.rules[15].opcodes=[],this.rules[15].opcodes[0]={type:3,min:0,max:1/0},this.rules[15].opcodes[1]={type:4,index:62},this.rules[16].opcodes=[],this.rules[16].opcodes[0]={type:3,min:1,max:1/0},this.rules[16].opcodes[1]={type:4,index:79},this.rules[17].opcodes=[],this.rules[17].opcodes[0]={type:3,min:0,max:1/0},this.rules[17].opcodes[1]={type:2,children:[2,3]},this.rules[17].opcodes[2]={type:4,index:78},this.rules[17].opcodes[3]={type:4,index:18},this.rules[18].opcodes=[],this.rules[18].opcodes[0]={type:2,children:[1,2]},this.rules[18].opcodes[1]={type:7,string:[45,32]},this.rules[18].opcodes[2]={type:4,index:47},this.rules[19].opcodes=[],this.rules[19].opcodes[0]={type:2,children:[1,2,3,4,8]},this.rules[19].opcodes[1]={type:4,index:21},this.rules[19].opcodes[2]={type:7,string:[58]},this.rules[19].opcodes[3]={type:4,index:20},this.rules[19].opcodes[4]={type:3,min:0,max:1},this.rules[19].opcodes[5]={type:2,children:[6,7]},this.rules[19].opcodes[6]={type:7,string:[63]},this.rules[19].opcodes[7]={type:4,index:45},this.rules[19].opcodes[8]={type:3,min:0,max:1},this.rules[19].opcodes[9]={type:2,children:[10,11]},this.rules[19].opcodes[10]={type:7,string:[35]},this.rules[19].opcodes[11]={type:4,index:46},this.rules[20].opcodes=[],this.rules[20].opcodes[0]={type:1,children:[1,5,6,7]},this.rules[20].opcodes[1]={type:2,children:[2,3,4]},this.rules[20].opcodes[2]={type:7,string:[47,47]},this.rules[20].opcodes[3]={type:4,index:22},this.rules[20].opcodes[4]={type:4,index:23},this.rules[20].opcodes[5]={type:4,index:24},this.rules[20].opcodes[6]={type:4,index:25},this.rules[20].opcodes[7]={type:4,index:26},this.rules[21].opcodes=[],this.rules[21].opcodes[0]={type:2,children:[1,2]},this.rules[21].opcodes[1]={type:4,index:77},this.rules[21].opcodes[2]={type:3,min:0,max:1/0},this.rules[21].opcodes[3]={type:1,children:[4,5,6,7]},this.rules[21].opcodes[4]={type:4,index:77},this.rules[21].opcodes[5]={type:4,index:79},this.rules[21].opcodes[6]={type:6,string:[43]},this.rules[21].opcodes[7]={type:5,min:45,max:46},this.rules[22].opcodes=[],this.rules[22].opcodes[0]={type:2,children:[1,3,4]},this.rules[22].opcodes[1]={type:3,min:0,max:1},this.rules[22].opcodes[2]={type:4,index:27},this.rules[22].opcodes[3]={type:4,index:29},this.rules[22].opcodes[4]={type:3,min:0,max:1},this.rules[22].opcodes[5]={type:2,children:[6,7]},this.rules[22].opcodes[6]={type:7,string:[58]},this.rules[22].opcodes[7]={type:4,index:44},this.rules[23].opcodes=[],this.rules[23].opcodes[0]={type:3,min:0,max:1/0},this.rules[23].opcodes[1]={type:2,children:[2,3]},this.rules[23].opcodes[2]={type:7,string:[47]},this.rules[23].opcodes[3]={type:4,index:60},this.rules[24].opcodes=[],this.rules[24].opcodes[0]={type:2,children:[1,2]},this.rules[24].opcodes[1]={type:7,string:[47]},this.rules[24].opcodes[2]={type:3,min:0,max:1},this.rules[24].opcodes[3]={type:2,children:[4,5]},this.rules[24].opcodes[4]={type:4,index:61},this.rules[24].opcodes[5]={type:3,min:0,max:1/0},this.rules[24].opcodes[6]={type:2,children:[7,8]},this.rules[24].opcodes[7]={type:7,string:[47]},this.rules[24].opcodes[8]={type:4,index:60},this.rules[25].opcodes=[],this.rules[25].opcodes[0]={type:2,children:[1,2]},this.rules[25].opcodes[1]={type:4,index:61},this.rules[25].opcodes[2]={type:3,min:0,max:1/0},this.rules[25].opcodes[3]={type:2,children:[4,5]},this.rules[25].opcodes[4]={type:7,string:[47]},this.rules[25].opcodes[5]={type:4,index:60},this.rules[26].opcodes=[],this.rules[26].opcodes[0]={type:7,string:[]},this.rules[27].opcodes=[],this.rules[27].opcodes[0]={type:2,children:[1,2]},this.rules[27].opcodes[1]={type:4,index:28},this.rules[27].opcodes[2]={type:6,string:[64]},this.rules[28].opcodes=[],this.rules[28].opcodes[0]={type:3,min:0,max:1/0},this.rules[28].opcodes[1]={type:1,children:[2,3,4,5,6,7,8,9,10,11,12]},this.rules[28].opcodes[2]={type:5,min:97,max:122},this.rules[28].opcodes[3]={type:5,min:65,max:90},this.rules[28].opcodes[4]={type:5,min:48,max:57},this.rules[28].opcodes[5]={type:4,index:63},this.rules[28].opcodes[6]={type:6,string:[33]},this.rules[28].opcodes[7]={type:6,string:[36]},this.rules[28].opcodes[8]={type:5,min:38,max:46},this.rules[28].opcodes[9]={type:5,min:58,max:59},this.rules[28].opcodes[10]={type:6,string:[61]},this.rules[28].opcodes[11]={type:6,string:[95]},this.rules[28].opcodes[12]={type:6,string:[126]},this.rules[29].opcodes=[],this.rules[29].opcodes[0]={type:1,children:[1,2,6]},this.rules[29].opcodes[1]={type:4,index:30},this.rules[29].opcodes[2]={type:2,children:[3,4]},this.rules[29].opcodes[3]={type:4,index:39},this.rules[29].opcodes[4]={type:13},this.rules[29].opcodes[5]={type:4,index:43},this.rules[29].opcodes[6]={type:4,index:42},this.rules[30].opcodes=[],this.rules[30].opcodes[0]={type:2,children:[1,2,5]},this.rules[30].opcodes[1]={type:7,string:[91]},this.rules[30].opcodes[2]={type:1,children:[3,4]},this.rules[30].opcodes[3]={type:4,index:32},this.rules[30].opcodes[4]={type:4,index:31},this.rules[30].opcodes[5]={type:7,string:[93]},this.rules[31].opcodes=[],this.rules[31].opcodes[0]={type:2,children:[1,2,4,5]},this.rules[31].opcodes[1]={type:7,string:[118]},this.rules[31].opcodes[2]={type:3,min:1,max:1/0},this.rules[31].opcodes[3]={type:4,index:80},this.rules[31].opcodes[4]={type:7,string:[46]},this.rules[31].opcodes[5]={type:3,min:1,max:1/0},this.rules[31].opcodes[6]={type:1,children:[7,8,9,10,11,12,13,14,15,16]},this.rules[31].opcodes[7]={type:5,min:97,max:122},this.rules[31].opcodes[8]={type:5,min:65,max:90},this.rules[31].opcodes[9]={type:5,min:48,max:57},this.rules[31].opcodes[10]={type:6,string:[33]},this.rules[31].opcodes[11]={type:6,string:[36]},this.rules[31].opcodes[12]={type:5,min:38,max:46},this.rules[31].opcodes[13]={type:5,min:58,max:59},this.rules[31].opcodes[14]={type:6,string:[61]},this.rules[31].opcodes[15]={type:6,string:[95]},this.rules[31].opcodes[16]={type:6,string:[126]},this.rules[32].opcodes=[],this.rules[32].opcodes[0]={type:1,children:[1,2]},this.rules[32].opcodes[1]={type:4,index:33},this.rules[32].opcodes[2]={type:4,index:34},this.rules[33].opcodes=[],this.rules[33].opcodes[0]={type:2,children:[1,5]},this.rules[33].opcodes[1]={type:2,children:[2,3]},this.rules[33].opcodes[2]={type:4,index:37},this.rules[33].opcodes[3]={type:3,min:0,max:1/0},this.rules[33].opcodes[4]={type:4,index:38},this.rules[33].opcodes[5]={type:3,min:0,max:1},this.rules[33].opcodes[6]={type:2,children:[7,8]},this.rules[33].opcodes[7]={type:6,string:[58]},this.rules[33].opcodes[8]={type:4,index:39},this.rules[34].opcodes=[],this.rules[34].opcodes[0]={type:2,children:[1,6,7]},this.rules[34].opcodes[1]={type:3,min:0,max:1},this.rules[34].opcodes[2]={type:2,children:[3,4]},this.rules[34].opcodes[3]={type:4,index:35},this.rules[34].opcodes[4]={type:3,min:0,max:1/0},this.rules[34].opcodes[5]={type:4,index:36},this.rules[34].opcodes[6]={type:6,string:[58,58]},this.rules[34].opcodes[7]={type:1,children:[8,17]},this.rules[34].opcodes[8]={type:2,children:[9,13]},this.rules[34].opcodes[9]={type:2,children:[10,11]},this.rules[34].opcodes[10]={type:4,index:37},this.rules[34].opcodes[11]={type:3,min:0,max:1/0},this.rules[34].opcodes[12]={type:4,index:38},this.rules[34].opcodes[13]={type:3,min:0,max:1},this.rules[34].opcodes[14]={type:2,children:[15,16]},this.rules[34].opcodes[15]={type:6,string:[58]},this.rules[34].opcodes[16]={type:4,index:39},this.rules[34].opcodes[17]={type:3,min:0,max:1},this.rules[34].opcodes[18]={type:4,index:39},this.rules[35].opcodes=[],this.rules[35].opcodes[0]={type:3,min:1,max:4},this.rules[35].opcodes[1]={type:4,index:80},this.rules[36].opcodes=[],this.rules[36].opcodes[0]={type:2,children:[1,2]},this.rules[36].opcodes[1]={type:6,string:[58]},this.rules[36].opcodes[2]={type:3,min:1,max:4},this.rules[36].opcodes[3]={type:4,index:80},this.rules[37].opcodes=[],this.rules[37].opcodes[0]={type:2,children:[1,3]},this.rules[37].opcodes[1]={type:3,min:1,max:4},this.rules[37].opcodes[2]={type:4,index:80},this.rules[37].opcodes[3]={type:13},this.rules[37].opcodes[4]={type:6,string:[46]},this.rules[38].opcodes=[],this.rules[38].opcodes[0]={type:2,children:[1,2,4]},this.rules[38].opcodes[1]={type:6,string:[58]},this.rules[38].opcodes[2]={type:3,min:1,max:4},this.rules[38].opcodes[3]={type:4,index:80},this.rules[38].opcodes[4]={type:13},this.rules[38].opcodes[5]={type:6,string:[46]},this.rules[39].opcodes=[],this.rules[39].opcodes[0]={type:2,children:[1,2,3,4,5,6,7]},this.rules[39].opcodes[1]={type:4,index:40},this.rules[39].opcodes[2]={type:7,string:[46]},this.rules[39].opcodes[3]={type:4,index:40},this.rules[39].opcodes[4]={type:7,string:[46]},this.rules[39].opcodes[5]={type:4,index:40},this.rules[39].opcodes[6]={type:7,string:[46]},this.rules[39].opcodes[7]={type:4,index:40},this.rules[40].opcodes=[],this.rules[40].opcodes[0]={type:3,min:0,max:3},this.rules[40].opcodes[1]={type:4,index:41},this.rules[41].opcodes=[],this.rules[41].opcodes[0]={type:5,min:48,max:57},this.rules[42].opcodes=[],this.rules[42].opcodes[0]={type:3,min:0,max:1/0},this.rules[42].opcodes[1]={type:4,index:43},this.rules[43].opcodes=[],this.rules[43].opcodes[0]={type:1,children:[1,2,3,4,5,6,7,8,9,10,11]},this.rules[43].opcodes[1]={type:5,min:97,max:122},this.rules[43].opcodes[2]={type:5,min:65,max:90},this.rules[43].opcodes[3]={type:5,min:48,max:57},this.rules[43].opcodes[4]={type:4,index:63},this.rules[43].opcodes[5]={type:6,string:[33]},this.rules[43].opcodes[6]={type:6,string:[36]},this.rules[43].opcodes[7]={type:5,min:38,max:46},this.rules[43].opcodes[8]={type:6,string:[59]},this.rules[43].opcodes[9]={type:6,string:[61]},this.rules[43].opcodes[10]={type:6,string:[95]},this.rules[43].opcodes[11]={type:6,string:[126]},this.rules[44].opcodes=[],this.rules[44].opcodes[0]={type:3,min:0,max:1/0},this.rules[44].opcodes[1]={type:4,index:79},this.rules[45].opcodes=[],this.rules[45].opcodes[0]={type:3,min:0,max:1/0},this.rules[45].opcodes[1]={type:1,children:[2,3,4]},this.rules[45].opcodes[2]={type:4,index:62},this.rules[45].opcodes[3]={type:6,string:[47]},this.rules[45].opcodes[4]={type:6,string:[63]},this.rules[46].opcodes=[],this.rules[46].opcodes[0]={type:3,min:0,max:1/0},this.rules[46].opcodes[1]={type:1,children:[2,3,4]},this.rules[46].opcodes[2]={type:4,index:62},this.rules[46].opcodes[3]={type:6,string:[47]},this.rules[46].opcodes[4]={type:6,string:[63]},this.rules[47].opcodes=[],this.rules[47].opcodes[0]={type:2,children:[1,2,3,4,8]},this.rules[47].opcodes[1]={type:4,index:49},this.rules[47].opcodes[2]={type:7,string:[58]},this.rules[47].opcodes[3]={type:4,index:48},this.rules[47].opcodes[4]={type:3,min:0,max:1},this.rules[47].opcodes[5]={type:2,children:[6,7]},this.rules[47].opcodes[6]={type:7,string:[63]},this.rules[47].opcodes[7]={type:4,index:50},this.rules[47].opcodes[8]={type:3,min:0,max:1},this.rules[47].opcodes[9]={type:2,children:[10,11]},this.rules[47].opcodes[10]={type:7,string:[35]},this.rules[47].opcodes[11]={type:4,index:51},this.rules[48].opcodes=[],this.rules[48].opcodes[0]={type:1,children:[1,5,6,7]},this.rules[48].opcodes[1]={type:2,children:[2,3,4]},this.rules[48].opcodes[2]={type:7,string:[47,47]},this.rules[48].opcodes[3]={type:4,index:52},this.rules[48].opcodes[4]={type:4,index:56},this.rules[48].opcodes[5]={type:4,index:57},this.rules[48].opcodes[6]={type:4,index:58},this.rules[48].opcodes[7]={type:4,index:59},this.rules[49].opcodes=[],this.rules[49].opcodes[0]={type:2,children:[1,2]},this.rules[49].opcodes[1]={type:4,index:77},this.rules[49].opcodes[2]={type:3,min:0,max:1/0},this.rules[49].opcodes[3]={type:1,children:[4,5,6,7]},this.rules[49].opcodes[4]={type:4,index:77},this.rules[49].opcodes[5]={type:4,index:79},this.rules[49].opcodes[6]={type:6,string:[43]},this.rules[49].opcodes[7]={type:5,min:45,max:46},this.rules[50].opcodes=[],this.rules[50].opcodes[0]={type:3,min:0,max:1/0},this.rules[50].opcodes[1]={type:1,children:[2,3,4]},this.rules[50].opcodes[2]={type:4,index:62},this.rules[50].opcodes[3]={type:6,string:[47]},this.rules[50].opcodes[4]={type:6,string:[63]},this.rules[51].opcodes=[],this.rules[51].opcodes[0]={type:3,min:0,max:1/0},this.rules[51].opcodes[1]={type:1,children:[2,3,4]},this.rules[51].opcodes[2]={type:4,index:62},this.rules[51].opcodes[3]={type:6,string:[47]},this.rules[51].opcodes[4]={type:6,string:[63]},this.rules[52].opcodes=[],this.rules[52].opcodes[0]={type:2,children:[1,5,6]},this.rules[52].opcodes[1]={type:3,min:0,max:1},this.rules[52].opcodes[2]={type:2,children:[3,4]},this.rules[52].opcodes[3]={type:4,index:53},this.rules[52].opcodes[4]={type:6,string:[64]},this.rules[52].opcodes[5]={type:4,index:54},this.rules[52].opcodes[6]={type:3,min:0,max:1},this.rules[52].opcodes[7]={type:2,children:[8,9]},this.rules[52].opcodes[8]={type:7,string:[58]},this.rules[52].opcodes[9]={type:4,index:55},this.rules[53].opcodes=[],this.rules[53].opcodes[0]={type:3,min:0,max:1/0},this.rules[53].opcodes[1]={type:1,children:[2,3,4,5,6,7,8,9,10,11,12]},this.rules[53].opcodes[2]={type:5,min:97,max:122},this.rules[53].opcodes[3]={type:5,min:65,max:90},this.rules[53].opcodes[4]={type:5,min:48,max:57},this.rules[53].opcodes[5]={type:4,index:63},this.rules[53].opcodes[6]={type:6,string:[33]},this.rules[53].opcodes[7]={type:6,string:[36]},this.rules[53].opcodes[8]={type:5,min:38,max:46},this.rules[53].opcodes[9]={type:5,min:58,max:59},this.rules[53].opcodes[10]={type:6,string:[61]},this.rules[53].opcodes[11]={type:6,string:[95]},this.rules[53].opcodes[12]={type:6,string:[126]},this.rules[54].opcodes=[],this.rules[54].opcodes[0]={type:1,children:[1,2,6]},this.rules[54].opcodes[1]={type:4,index:30},this.rules[54].opcodes[2]={type:2,children:[3,4]},this.rules[54].opcodes[3]={type:4,index:39},this.rules[54].opcodes[4]={type:13},this.rules[54].opcodes[5]={type:4,index:43},this.rules[54].opcodes[6]={type:4,index:42},this.rules[55].opcodes=[],this.rules[55].opcodes[0]={type:3,min:0,max:1/0},this.rules[55].opcodes[1]={type:4,index:79},this.rules[56].opcodes=[],this.rules[56].opcodes[0]={type:3,min:0,max:1/0},this.rules[56].opcodes[1]={type:2,children:[2,3]},this.rules[56].opcodes[2]={type:7,string:[47]},this.rules[56].opcodes[3]={type:4,index:60},this.rules[57].opcodes=[],this.rules[57].opcodes[0]={type:2,children:[1,2]},this.rules[57].opcodes[1]={type:7,string:[47]},this.rules[57].opcodes[2]={type:3,min:0,max:1},this.rules[57].opcodes[3]={type:2,children:[4,5]},this.rules[57].opcodes[4]={type:4,index:61},this.rules[57].opcodes[5]={type:3,min:0,max:1/0},this.rules[57].opcodes[6]={type:2,children:[7,8]},this.rules[57].opcodes[7]={type:7,string:[47]},this.rules[57].opcodes[8]={type:4,index:60},this.rules[58].opcodes=[],this.rules[58].opcodes[0]={type:2,children:[1,2]},this.rules[58].opcodes[1]={type:4,index:61},this.rules[58].opcodes[2]={type:3,min:0,max:1/0},this.rules[58].opcodes[3]={type:2,children:[4,5]},this.rules[58].opcodes[4]={type:7,string:[47]},this.rules[58].opcodes[5]={type:4,index:60},this.rules[59].opcodes=[],this.rules[59].opcodes[0]={type:7,string:[]},this.rules[60].opcodes=[],this.rules[60].opcodes[0]={type:3,min:0,max:1/0},this.rules[60].opcodes[1]={type:4,index:62},this.rules[61].opcodes=[],this.rules[61].opcodes[0]={type:3,min:1,max:1/0},this.rules[61].opcodes[1]={type:4,index:62},this.rules[62].opcodes=[],this.rules[62].opcodes[0]={type:1,children:[1,2,3,4,5,6,7,8,9,10,11,12]},this.rules[62].opcodes[1]={type:5,min:97,max:122},this.rules[62].opcodes[2]={type:5,min:65,max:90},this.rules[62].opcodes[3]={type:5,min:48,max:57},this.rules[62].opcodes[4]={type:4,index:63},this.rules[62].opcodes[5]={type:6,string:[33]},this.rules[62].opcodes[6]={type:6,string:[36]},this.rules[62].opcodes[7]={type:5,min:38,max:46},this.rules[62].opcodes[8]={type:5,min:58,max:59},this.rules[62].opcodes[9]={type:6,string:[61]},this.rules[62].opcodes[10]={type:6,string:[64]},this.rules[62].opcodes[11]={type:6,string:[95]},this.rules[62].opcodes[12]={type:6,string:[126]},this.rules[63].opcodes=[],this.rules[63].opcodes[0]={type:2,children:[1,2,3]},this.rules[63].opcodes[1]={type:6,string:[37]},this.rules[63].opcodes[2]={type:4,index:80},this.rules[63].opcodes[3]={type:4,index:80},this.rules[64].opcodes=[],this.rules[64].opcodes[0]={type:3,min:4,max:4},this.rules[64].opcodes[1]={type:4,index:79},this.rules[65].opcodes=[],this.rules[65].opcodes[0]={type:3,min:2,max:2},this.rules[65].opcodes[1]={type:4,index:79},this.rules[66].opcodes=[],this.rules[66].opcodes[0]={type:3,min:2,max:2},this.rules[66].opcodes[1]={type:4,index:79},this.rules[67].opcodes=[],this.rules[67].opcodes[0]={type:3,min:2,max:2},this.rules[67].opcodes[1]={type:4,index:79},this.rules[68].opcodes=[],this.rules[68].opcodes[0]={type:3,min:2,max:2},this.rules[68].opcodes[1]={type:4,index:79},this.rules[69].opcodes=[],this.rules[69].opcodes[0]={type:3,min:2,max:2},this.rules[69].opcodes[1]={type:4,index:79},this.rules[70].opcodes=[],this.rules[70].opcodes[0]={type:2,children:[1,2]},this.rules[70].opcodes[1]={type:7,string:[46]},this.rules[70].opcodes[2]={type:3,min:1,max:1/0},this.rules[70].opcodes[3]={type:4,index:79},this.rules[71].opcodes=[],this.rules[71].opcodes[0]={type:2,children:[1,4,5,6]},this.rules[71].opcodes[1]={type:1,children:[2,3]},this.rules[71].opcodes[2]={type:7,string:[43]},this.rules[71].opcodes[3]={type:7,string:[45]},this.rules[71].opcodes[4]={type:4,index:67},this.rules[71].opcodes[5]={type:7,string:[58]},this.rules[71].opcodes[6]={type:4,index:68},this.rules[72].opcodes=[],this.rules[72].opcodes[0]={type:1,children:[1,2]},this.rules[72].opcodes[1]={type:7,string:[122]},this.rules[72].opcodes[2]={type:4,index:71},this.rules[73].opcodes=[],this.rules[73].opcodes[0]={type:2,children:[1,2,3,4,5,6]},this.rules[73].opcodes[1]={type:4,index:67},this.rules[73].opcodes[2]={type:7,string:[58]},this.rules[73].opcodes[3]={type:4,index:68},this.rules[73].opcodes[4]={type:7,string:[58]},this.rules[73].opcodes[5]={type:4,index:69},this.rules[73].opcodes[6]={type:3,min:0,max:1},this.rules[73].opcodes[7]={type:4,index:70},this.rules[74].opcodes=[],this.rules[74].opcodes[0]={type:2,children:[1,2,3,4,5]},this.rules[74].opcodes[1]={type:4,index:64},this.rules[74].opcodes[2]={type:7,string:[45]},this.rules[74].opcodes[3]={type:4,index:65},this.rules[74].opcodes[4]={type:7,string:[45]},this.rules[74].opcodes[5]={type:4,index:66},this.rules[75].opcodes=[],this.rules[75].opcodes[0]={type:2,children:[1,2]},this.rules[75].opcodes[1]={type:4,index:73},this.rules[75].opcodes[2]={type:4,index:72},this.rules[76].opcodes=[],this.rules[76].opcodes[0]={type:2,children:[1,2,3]},this.rules[76].opcodes[1]={type:4,index:74},this.rules[76].opcodes[2]={type:7,string:[116]},this.rules[76].opcodes[3]={type:4,index:75},this.rules[77].opcodes=[],this.rules[77].opcodes[0]={type:1,children:[1,2]},this.rules[77].opcodes[1]={type:5,min:65,max:90},this.rules[77].opcodes[2]={type:5,min:97,max:122},this.rules[78].opcodes=[],this.rules[78].opcodes[0]={type:6,string:[10]},this.rules[79].opcodes=[],this.rules[79].opcodes[0]={type:5,min:48,max:57},this.rules[80].opcodes=[],this.rules[80].opcodes[0]={type:1,children:[1,2,3]},this.rules[80].opcodes[1]={type:5,min:48,max:57},this.rules[80].opcodes[2]={type:5,min:65,max:70},this.rules[80].opcodes[3]={type:5,min:97,max:102},this.toString=function(){let e="";return e+="; LDT 05/06/2024 \n",e+="; modified in several significant ways\n",e+="; 1) Literal strings are replaced with numbers and ranges (%d32 & %d32-126, etc.) when possible.\n",e+="; TRB and especially TRG operators are much more efficient than TLS operators.\n",e+="; 2) Two rules, authority and URI, are used multiple times in different contexts. These rules will be reproduced and renamed\n",e+="; in order to a) recognize the context and b) remove unneccary callback functions for certain contexts.\n",e+="; This will simiplify recognizing contexts AND remove unneccesary callbacks\n",e+="; 2.a) domain is defined as authority-d which is identical to authority except that there will be no\n",e+="; callback functions defined on authority-d or any of its *-d components.\n",e+="; 2.b) The resource URI is defined as URI-r and its components defined as *-r.\n",e+="; In this way, callback functions can be defined on URI and is components while\n",e+="; leaving URI-r to be parsed identically with no unnecessary callback functions to slow it down.\n",e+='; 3) IPv6address does not work because of APG\'s "first-success disambiguation" and "greedy" repetitions.\n',e+="; IPv6address redefined and validations moved to callback functions (semantic vs syntactic validation)\n",e+="; Redefinition requires negative look-ahead operators, https://en.wikipedia.org/wiki/Syntactic_predicate\n",e+="; That is SABNF instead of simple ABNF.\n",e+='; 4) IPv4address fails because of "first-success disambiguation".\n',e+="; This could be fixed with rearrangement of the alternative terms. However, it would still not\n",e+="; accept zero-padded (leading zeros) decimal octets.\n",e+="; Therefore, IPv4address is also done with callback functions and semantic validation.\n",e+="; 5) The negative look-ahead operator is also needed in the definition of host to\n",e+="; prevent failure with a reg-name that begins with an IPv4 address.\n",e+="; 6) NOTE: host = 1.1.1.256 is a valid host name even though it is an invalid IPv4address.\n",e+="; The IPv4address alternative fails but the reg-name alternative succeeds.\n",e+="; 7) The Ethereum spec (https://eips.ethereum.org/EIPS/eip-4361) message format ABNF\n",e+='; allows for empty statements. Because of the "first success disambiguation" of APG\n',e+='; the an explicit "empty-statement" rule is required to match the spec\'s intent.\n',e+="\n",e+="\n",e+="sign-in-with-ethereum =\n",e+=' oscheme domain %s" wants you to sign in with your Ethereum account:" LF\n',e+=" address LF\n",e+=" ((LF statement LF LF) / empty-statement / (LF LF))\n",e+=' %s"URI: " URI LF\n',e+=' %s"Version: " version LF\n',e+=' %s"Chain ID: " chain-id LF\n',e+=' %s"Nonce: " nonce LF\n',e+=' %s"Issued At: " issued-at\n',e+=" [ LF ex-title expiration-time ]\n",e+=" [ LF nb-title not-before ]\n",e+=" [ LF ri-title request-id ]\n",e+=" [ LF re-title resources ]\n",e+='ex-title = %s"Expiration Time: "\n',e+='nb-title = %s"Not Before: "\n',e+='ri-title = %s"Request ID: "\n',e+='re-title = %s"Resources:"\n',e+='oscheme = [ ALPHA *( ALPHA / DIGIT / %d43 / %d45-46 ) "://" ]\n',e+="domain = authority-d\n",e+='address = "0x" 40*40HEXDIG\n',e+=" ; Must also conform to captilization\n",e+=" ; checksum encoding specified in EIP-55\n",e+=" ; where applicable (EOAs).\n",e+="\n",e+="statement = 1*( %d97-122 / %d65-90 / %d48-57 / %d32-33 / %d35-36 / %d38-59 / %d61 / %d63-64 / %d91 / %d93 / %d95 / %d126)\n",e+=" ; The purpose is to exclude LF (line breaks).\n",e+=" ; LDT 10/04/2023: Do you mean %d32-126? All printing characters\n",e+="empty-statement = LF LF LF\n",e+='version = "1"\n',e+="nonce = 8*( ALPHA / DIGIT )\n",e+="issued-at = date-time\n",e+="expiration-time = date-time\n",e+="not-before = date-time\n",e+="request-id = *pchar\n",e+="chain-id = 1*DIGIT\n",e+=" ; See EIP-155 for valid CHAIN_IDs.\n",e+="resources = *( LF resource )\n",e+='resource = "- " URI-r\n',e+="\n",e+="; ------------------------------------------------------------------------------\n",e+="; RFC 3986\n",e+="\n",e+='URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]\n',e+='hier-part = "//" authority path-abempty\n',e+=" / path-absolute\n",e+=" / path-rootless\n",e+=" / path-empty\n",e+="scheme = ALPHA *( ALPHA / DIGIT / %d43 / %d45-46 )\n",e+='authority = [ userinfo-at ] host [ ":" port ]\n',e+='path-abempty = *( "/" segment )\n',e+='path-absolute = "/" [ segment-nz *( "/" segment ) ]\n',e+='path-rootless = segment-nz *( "/" segment )\n',e+='path-empty = ""\n',e+="userinfo-at = userinfo %d64\n",e+=' ; userinfo redefined to include the "@" so that it will fail without it\n',e+=" ; otherwise userinfo can match host and then the parser will backtrack\n",e+=" ; incorrectly keeping the captured userinfo phrase\n",e+="userinfo = *(%d97-122 / %d65-90 / %d48-57 / pct-encoded / %d33 / %d36 / %d38-46 / %d58-59 / %d61 / %d95 / %d126)\n",e+="host = IP-literal / (IPv4address !reg-name-char) / reg-name\n",e+=" ; negative look-ahead required to prevent IPv4address from being recognized as first part of reg-name\n",e+=" ; same fix as https://github.com/garycourt/uri-js/issues/4\n",e+='IP-literal = "[" ( IPv6address / IPvFuture ) "]"\n',e+='IPvFuture = "v" 1*HEXDIG "." 1*( %d97-122 / %d65-90 / %d48-57 / %d33 / %d36 /%d38-46 / %d58-59 /%d61 /%d95 / %d126 )\n',e+="IPv6address = nodcolon / dcolon\n",e+="nodcolon = (h16n *h16cn) [%d58 IPv4address]\n",e+="dcolon = [h16 *h16c] %d58.58 (((h16n *h16cn) [%d58 IPv4address]) / [IPv4address])\n",e+="h16 = 1*4HEXDIG\n",e+="h16c = %d58 1*4HEXDIG\n",e+="h16n = 1*4HEXDIG !%d46\n",e+="h16cn = %d58 1*4HEXDIG !%d46\n",e+='IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet\n',e+="; Here we will will use callback functions to evaluate and validate the (possibly zero-padded) dec-octet.\n",e+="dec-octet = *3dec-digit\n",e+="dec-digit = %d48-57\n",e+="reg-name = *reg-name-char\n",e+="reg-name-char = %d97-122 / %d65-90 / %d48-57 / pct-encoded / %d33 / %d36 / %d38-46 / %d59 / %d61 /%d95 / %d126\n",e+="port = *DIGIT\n",e+="query = *(pchar / %d47 / %d63)\n",e+="fragment = *(pchar / %d47 / %d63)\n",e+="\n",e+="; URI-r is a redefiniton of URI but without the callback functions attached to it\n",e+="; it reuses athority-d from domain \n",e+='URI-r = scheme-r ":" hier-part-r [ "?" query-r ] [ "#" fragment-r ]\n',e+='hier-part-r = "//" authority-d path-abempty-r\n',e+=" / path-absolute-r\n",e+=" / path-rootless-r\n",e+=" / path-empty-r\n",e+="scheme-r = ALPHA *( ALPHA / DIGIT / %d43 / %d45-46 )\n",e+="query-r = *(pchar / %d47 / %d63)\n",e+="fragment-r = *(pchar / %d47 / %d63)\n",e+="\n",e+="; authority-d is a redefinition of authority for capturing the domian phrase\n",e+="; but without callback functions \n",e+="; it is reused for URI- for the same reason \n",e+='authority-d = [ userinfo-d %d64 ] host-d [ ":" port-d ]\n',e+="userinfo-d = *(%d97-122 / %d65-90 / %d48-57 / pct-encoded / %d33 / %d36 / %d38-46 / %d58-59 / %d61 / %d95 / %d126)\n",e+="host-d = IP-literal / (IPv4address !reg-name-char) / reg-name\n",e+="port-d = *DIGIT\n",e+="\n",e+="; for use with URI-r\n",e+='path-abempty-r = *( "/" segment )\n',e+='path-absolute-r = "/" [ segment-nz *( "/" segment ) ]\n',e+='path-rootless-r = segment-nz *( "/" segment )\n',e+='path-empty-r = ""\n',e+="segment = *pchar\n",e+="segment-nz = 1*pchar\n",e+="pchar = (%d97-122 / %d65-90 / %d48-57 / pct-encoded / %d33 / %d36 / %d38-46 /%d58-59 / %d61 / %d64 / %d95 / %d126)\n",e+="pct-encoded = %d37 HEXDIG HEXDIG\n",e+="\n",e+="; no longer needed - expanded for all usage for fewer branches in the parse there\n",e+="; and more efficient use of the TBS & TRG operators in place of TLS and rule names\n",e+='; does not work with APG probably because of "first-success disambiguation" and greedy repetitions.\n',e+="; will replace with semantic checking of valid number of h16s\n",e+=';IPv6address = 6( h16 ":" ) ls32\n',e+='; / "::" 5( h16 ":" ) ls32\n',e+='; / [ h16 ] "::" 4( h16 ":" ) ls32\n',e+='; / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32\n',e+='; / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32\n',e+='; / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32\n',e+='; / [ *4( h16 ":" ) h16 ] "::" ls32\n',e+='; / [ *5( h16 ":" ) h16 ] "::" h16\n',e+='; / [ *6( h16 ":" ) h16 ] "::"\n',e+=';ls32 = ( h16 ":" h16 ) / IPv4address\n',e+='; dec-octet does not work because of "first-success disambiguation".\n',e+="; Must have the longest (3-digit) numbers first.\n",e+="; Even so, this form does not accept leading zeros.\n",e+="; There does not seem to be a clear standard for this (https://en.wikipedia.org/wiki/Dot-decimal_notation)\n",e+="; however and early RFC 790 did show leading-zero padding of the three digits.\n",e+=";dec-octet = DIGIT ; 0-9\n",e+="; / %x31-39 DIGIT ; 10-99\n",e+='; / "1" 2DIGIT ; 100-199\n',e+='; / "2" %x30-34 DIGIT ; 200-249\n',e+='; / "25" %x30-35 ; 250-255\n',e+=';statement = 1*( reserved / unreserved / " " )\n',e+=';scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )\n',e+=';authority = [ userinfo "@" ] host [ ":" port ]\n',e+=';userinfo = *( unreserved / pct-encoded / sub-delims / ":" )\n',e+=';query = *( pchar / "/" / "?" )\n',e+=';fragment = *( pchar / "/" / "?" )\n',e+=';IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )\n',e+=";reg-name = *( unreserved / pct-encoded / sub-delims )\n",e+=';pct-encoded = "%" HEXDIG HEXDIG\n',e+=';pchar = unreserved / pct-encoded / sub-delims / ":" / "@"\n',e+=';path-empty = 0pchar; deprecated - empty literal string, "", is more efficient \n',e+=';unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"\n',e+=";reserved = gen-delims / sub-delims\n",e+=';gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"\n',e+=';sub-delims = "!" / "$" / "&" / "\'" / "(" / ")"\n',e+='; / "*" / "+" / "," / ";" / "="\n',e+=';HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"\n',e+="\n",e+="; ------------------------------------------------------------------------------\n",e+="; RFC 3339\n",e+="\n",e+="date-fullyear = 4DIGIT\n",e+="date-month = 2DIGIT ; 01-12\n",e+="date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on\n",e+=" ; month/year\n",e+="time-hour = 2DIGIT ; 00-23\n",e+="time-minute = 2DIGIT ; 00-59\n",e+="time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second\n",e+=" ; rules\n",e+='time-secfrac = "." 1*DIGIT\n',e+='time-numoffset = ("+" / "-") time-hour ":" time-minute\n',e+='time-offset = "Z" / time-numoffset\n',e+="\n",e+='partial-time = time-hour ":" time-minute ":" time-second\n',e+=" [time-secfrac]\n",e+='full-date = date-fullyear "-" date-month "-" date-mday\n',e+="full-time = partial-time time-offset\n",e+="\n",e+='date-time = full-date "T" full-time\n',e+="\n",e+="; ------------------------------------------------------------------------------\n",e+="; RFC 5234\n",e+="\n",e+="ALPHA = %x41-5A / %x61-7A ; A-Z / a-z\n",e+="LF = %x0A\n",e+=" ; linefeed\n",e+="DIGIT = %x30-39\n",e+=" ; 0-9\n",e+="HEXDIG = %d48-57 / %d65-70 / %d97-102\n",e+="\n",'; LDT 05/06/2024 \n; modified in several significant ways\n; 1) Literal strings are replaced with numbers and ranges (%d32 & %d32-126, etc.) when possible.\n; TRB and especially TRG operators are much more efficient than TLS operators.\n; 2) Two rules, authority and URI, are used multiple times in different contexts. These rules will be reproduced and renamed\n; in order to a) recognize the context and b) remove unneccary callback functions for certain contexts.\n; This will simiplify recognizing contexts AND remove unneccesary callbacks\n; 2.a) domain is defined as authority-d which is identical to authority except that there will be no\n; callback functions defined on authority-d or any of its *-d components.\n; 2.b) The resource URI is defined as URI-r and its components defined as *-r.\n; In this way, callback functions can be defined on URI and is components while\n; leaving URI-r to be parsed identically with no unnecessary callback functions to slow it down.\n; 3) IPv6address does not work because of APG\'s "first-success disambiguation" and "greedy" repetitions.\n; IPv6address redefined and validations moved to callback functions (semantic vs syntactic validation)\n; Redefinition requires negative look-ahead operators, https://en.wikipedia.org/wiki/Syntactic_predicate\n; That is SABNF instead of simple ABNF.\n; 4) IPv4address fails because of "first-success disambiguation".\n; This could be fixed with rearrangement of the alternative terms. However, it would still not\n; accept zero-padded (leading zeros) decimal octets.\n; Therefore, IPv4address is also done with callback functions and semantic validation.\n; 5) The negative look-ahead operator is also needed in the definition of host to\n; prevent failure with a reg-name that begins with an IPv4 address.\n; 6) NOTE: host = 1.1.1.256 is a valid host name even though it is an invalid IPv4address.\n; The IPv4address alternative fails but the reg-name alternative succeeds.\n; 7) The Ethereum spec (https://eips.ethereum.org/EIPS/eip-4361) message format ABNF\n; allows for empty statements. Because of the "first success disambiguation" of APG\n; the an explicit "empty-statement" rule is required to match the spec\'s intent.\n\n\nsign-in-with-ethereum =\n oscheme domain %s" wants you to sign in with your Ethereum account:" LF\n address LF\n ((LF statement LF LF) / empty-statement / (LF LF))\n %s"URI: " URI LF\n %s"Version: " version LF\n %s"Chain ID: " chain-id LF\n %s"Nonce: " nonce LF\n %s"Issued At: " issued-at\n [ LF ex-title expiration-time ]\n [ LF nb-title not-before ]\n [ LF ri-title request-id ]\n [ LF re-title resources ]\nex-title = %s"Expiration Time: "\nnb-title = %s"Not Before: "\nri-title = %s"Request ID: "\nre-title = %s"Resources:"\noscheme = [ ALPHA *( ALPHA / DIGIT / %d43 / %d45-46 ) "://" ]\ndomain = authority-d\naddress = "0x" 40*40HEXDIG\n ; Must also conform to captilization\n ; checksum encoding specified in EIP-55\n ; where applicable (EOAs).\n\nstatement = 1*( %d97-122 / %d65-90 / %d48-57 / %d32-33 / %d35-36 / %d38-59 / %d61 / %d63-64 / %d91 / %d93 / %d95 / %d126)\n ; The purpose is to exclude LF (line breaks).\n ; LDT 10/04/2023: Do you mean %d32-126? All printing characters\nempty-statement = LF LF LF\nversion = "1"\nnonce = 8*( ALPHA / DIGIT )\nissued-at = date-time\nexpiration-time = date-time\nnot-before = date-time\nrequest-id = *pchar\nchain-id = 1*DIGIT\n ; See EIP-155 for valid CHAIN_IDs.\nresources = *( LF resource )\nresource = "- " URI-r\n\n; ------------------------------------------------------------------------------\n; RFC 3986\n\nURI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]\nhier-part = "//" authority path-abempty\n / path-absolute\n / path-rootless\n / path-empty\nscheme = ALPHA *( ALPHA / DIGIT / %d43 / %d45-46 )\nauthority = [ userinfo-at ] host [ ":" port ]\npath-abempty = *( "/" segment )\npath-absolute = "/" [ segment-nz *( "/" segment ) ]\npath-rootless = segment-nz *( "/" segment )\npath-empty = ""\nuserinfo-at = userinfo %d64\n ; userinfo redefined to include the "@" so that it will fail without it\n ; otherwise userinfo can match host and then the parser will backtrack\n ; incorrectly keeping the captured userinfo phrase\nuserinfo = *(%d97-122 / %d65-90 / %d48-57 / pct-encoded / %d33 / %d36 / %d38-46 / %d58-59 / %d61 / %d95 / %d126)\nhost = IP-literal / (IPv4address !reg-name-char) / reg-name\n ; negative look-ahead required to prevent IPv4address from being recognized as first part of reg-name\n ; same fix as https://github.com/garycourt/uri-js/issues/4\nIP-literal = "[" ( IPv6address / IPvFuture ) "]"\nIPvFuture = "v" 1*HEXDIG "." 1*( %d97-122 / %d65-90 / %d48-57 / %d33 / %d36 /%d38-46 / %d58-59 /%d61 /%d95 / %d126 )\nIPv6address = nodcolon / dcolon\nnodcolon = (h16n *h16cn) [%d58 IPv4address]\ndcolon = [h16 *h16c] %d58.58 (((h16n *h16cn) [%d58 IPv4address]) / [IPv4address])\nh16 = 1*4HEXDIG\nh16c = %d58 1*4HEXDIG\nh16n = 1*4HEXDIG !%d46\nh16cn = %d58 1*4HEXDIG !%d46\nIPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet\n; Here we will will use callback functions to evaluate and validate the (possibly zero-padded) dec-octet.\ndec-octet = *3dec-digit\ndec-digit = %d48-57\nreg-name = *reg-name-char\nreg-name-char = %d97-122 / %d65-90 / %d48-57 / pct-encoded / %d33 / %d36 / %d38-46 / %d59 / %d61 /%d95 / %d126\nport = *DIGIT\nquery = *(pchar / %d47 / %d63)\nfragment = *(pchar / %d47 / %d63)\n\n; URI-r is a redefiniton of URI but without the callback functions attached to it\n; it reuses athority-d from domain \nURI-r = scheme-r ":" hier-part-r [ "?" query-r ] [ "#" fragment-r ]\nhier-part-r = "//" authority-d path-abempty-r\n / path-absolute-r\n / path-rootless-r\n / path-empty-r\nscheme-r = ALPHA *( ALPHA / DIGIT / %d43 / %d45-46 )\nquery-r = *(pchar / %d47 / %d63)\nfragment-r = *(pchar / %d47 / %d63)\n\n; authority-d is a redefinition of authority for capturing the domian phrase\n; but without callback functions \n; it is reused for URI- for the same reason \nauthority-d = [ userinfo-d %d64 ] host-d [ ":" port-d ]\nuserinfo-d = *(%d97-122 / %d65-90 / %d48-57 / pct-encoded / %d33 / %d36 / %d38-46 / %d58-59 / %d61 / %d95 / %d126)\nhost-d = IP-literal / (IPv4address !reg-name-char) / reg-name\nport-d = *DIGIT\n\n; for use with URI-r\npath-abempty-r = *( "/" segment )\npath-absolute-r = "/" [ segment-nz *( "/" segment ) ]\npath-rootless-r = segment-nz *( "/" segment )\npath-empty-r = ""\nsegment = *pchar\nsegment-nz = 1*pchar\npchar = (%d97-122 / %d65-90 / %d48-57 / pct-encoded / %d33 / %d36 / %d38-46 /%d58-59 / %d61 / %d64 / %d95 / %d126)\npct-encoded = %d37 HEXDIG HEXDIG\n\n; no longer needed - expanded for all usage for fewer branches in the parse there\n; and more efficient use of the TBS & TRG operators in place of TLS and rule names\n; does not work with APG probably because of "first-success disambiguation" and greedy repetitions.\n; will replace with semantic checking of valid number of h16s\n;IPv6address = 6( h16 ":" ) ls32\n; / "::" 5( h16 ":" ) ls32\n; / [ h16 ] "::" 4( h16 ":" ) ls32\n; / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32\n; / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32\n; / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32\n; / [ *4( h16 ":" ) h16 ] "::" ls32\n; / [ *5( h16 ":" ) h16 ] "::" h16\n; / [ *6( h16 ":" ) h16 ] "::"\n;ls32 = ( h16 ":" h16 ) / IPv4address\n; dec-octet does not work because of "first-success disambiguation".\n; Must have the longest (3-digit) numbers first.\n; Even so, this form does not accept leading zeros.\n; There does not seem to be a clear standard for this (https://en.wikipedia.org/wiki/Dot-decimal_notation)\n; however and early RFC 790 did show leading-zero padding of the three digits.\n;dec-octet = DIGIT ; 0-9\n; / %x31-39 DIGIT ; 10-99\n; / "1" 2DIGIT ; 100-199\n; / "2" %x30-34 DIGIT ; 200-249\n; / "25" %x30-35 ; 250-255\n;statement = 1*( reserved / unreserved / " " )\n;scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )\n;authority = [ userinfo "@" ] host [ ":" port ]\n;userinfo = *( unreserved / pct-encoded / sub-delims / ":" )\n;query = *( pchar / "/" / "?" )\n;fragment = *( pchar / "/" / "?" )\n;IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )\n;reg-name = *( unreserved / pct-encoded / sub-delims )\n;pct-encoded = "%" HEXDIG HEXDIG\n;pchar = unreserved / pct-encoded / sub-delims / ":" / "@"\n;path-empty = 0pchar; deprecated - empty literal string, "", is more efficient \n;unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"\n;reserved = gen-delims / sub-delims\n;gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"\n;sub-delims = "!" / "$" / "&" / "\'" / "(" / ")"\n; / "*" / "+" / "," / ";" / "="\n;HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"\n\n; ------------------------------------------------------------------------------\n; RFC 3339\n\ndate-fullyear = 4DIGIT\ndate-month = 2DIGIT ; 01-12\ndate-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on\n ; month/year\ntime-hour = 2DIGIT ; 00-23\ntime-minute = 2DIGIT ; 00-59\ntime-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second\n ; rules\ntime-secfrac = "." 1*DIGIT\ntime-numoffset = ("+" / "-") time-hour ":" time-minute\ntime-offset = "Z" / time-numoffset\n\npartial-time = time-hour ":" time-minute ":" time-second\n [time-secfrac]\nfull-date = date-fullyear "-" date-month "-" date-mday\nfull-time = partial-time time-offset\n\ndate-time = full-date "T" full-time\n\n; ------------------------------------------------------------------------------\n; RFC 5234\n\nALPHA = %x41-5A / %x61-7A ; A-Z / a-z\nLF = %x0A\n ; linefeed\nDIGIT = %x30-39\n ; 0-9\nHEXDIG = %d48-57 / %d65-70 / %d97-102\n\n'}}},2626(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseIntegerNumber=t.isEIP55Address=void 0;const n=r(113),i=r(7997);t.isEIP55Address=e=>{if(42!=e.length)return!1;const t=`${e}`.toLowerCase().replace("0x",""),r=(0,i.bytesToHex)((0,n.keccak_256)(t));let s="0x";for(let e=0;e<t.length;e++)parseInt(r[e],16)>=8?s+=t[e].toUpperCase():s+=t[e];return e===s},t.parseIntegerNumber=e=>{const t=parseInt(e);if(isNaN(t))throw new Error("Invalid number.");if(t===1/0)throw new Error("Invalid number.");return t}},3447(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(6411);function i(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>8,t[r+1]=e>>>0,t}function s(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t}function o(e,t){return void 0===t&&(t=0),e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function a(e,t){return void 0===t&&(t=0),(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function c(e,t){return void 0===t&&(t=0),e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}function u(e,t){return void 0===t&&(t=0),(e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t])>>>0}function l(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>24,t[r+1]=e>>>16,t[r+2]=e>>>8,t[r+3]=e>>>0,t}function h(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24,t}function d(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),l(e/4294967296>>>0,t,r),l(e>>>0,t,r+4),t}function f(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),h(e>>>0,t,r),h(e/4294967296>>>0,t,r+4),t}t.readInt16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])<<16>>16},t.readUint16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])>>>0},t.readInt16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])<<16>>16},t.readUint16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])>>>0},t.writeUint16BE=i,t.writeInt16BE=i,t.writeUint16LE=s,t.writeInt16LE=s,t.readInt32BE=o,t.readUint32BE=a,t.readInt32LE=c,t.readUint32LE=u,t.writeUint32BE=l,t.writeInt32BE=l,t.writeUint32LE=h,t.writeInt32LE=h,t.readInt64BE=function(e,t){void 0===t&&(t=0);var r=o(e,t),n=o(e,t+4);return 4294967296*r+n-4294967296*(n>>31)},t.readUint64BE=function(e,t){return void 0===t&&(t=0),4294967296*a(e,t)+a(e,t+4)},t.readInt64LE=function(e,t){void 0===t&&(t=0);var r=c(e,t);return 4294967296*c(e,t+4)+r-4294967296*(r>>31)},t.readUint64LE=function(e,t){void 0===t&&(t=0);var r=u(e,t);return 4294967296*u(e,t+4)+r},t.writeUint64BE=d,t.writeInt64BE=d,t.writeUint64LE=f,t.writeInt64LE=f,t.readUintBE=function(e,t,r){if(void 0===r&&(r=0),e%8!=0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=e/8+r-1;s>=r;s--)n+=t[s]*i,i*=256;return n},t.readUintLE=function(e,t,r){if(void 0===r&&(r=0),e%8!=0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s<r+e/8;s++)n+=t[s]*i,i*=256;return n},t.writeUintBE=function(e,t,r,i){if(void 0===r&&(r=new Uint8Array(e/8)),void 0===i&&(i=0),e%8!=0)throw new Error("writeUintBE supports only bitLengths divisible by 8");if(!n.isSafeInteger(t))throw new Error("writeUintBE value must be an integer");for(var s=1,o=e/8+i-1;o>=i;o--)r[o]=t/s&255,s*=256;return r},t.writeUintLE=function(e,t,r,i){if(void 0===r&&(r=new Uint8Array(e/8)),void 0===i&&(i=0),e%8!=0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!n.isSafeInteger(t))throw new Error("writeUintLE value must be an integer");for(var s=1,o=i;o<i+e/8;o++)r[o]=t/s&255,s*=256;return r},t.readFloat32BE=function(e,t){return void 0===t&&(t=0),new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat32(t)},t.readFloat32LE=function(e,t){return void 0===t&&(t=0),new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat32(t,!0)},t.readFloat64BE=function(e,t){return void 0===t&&(t=0),new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat64(t)},t.readFloat64LE=function(e,t){return void 0===t&&(t=0),new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat64(t,!0)},t.writeFloat32BE=function(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),new DataView(t.buffer,t.byteOffset,t.byteLength).setFloat32(r,e),t},t.writeFloat32LE=function(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),new DataView(t.buffer,t.byteOffset,t.byteLength).setFloat32(r,e,!0),t},t.writeFloat64BE=function(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),new DataView(t.buffer,t.byteOffset,t.byteLength).setFloat64(r,e),t},t.writeFloat64LE=function(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),new DataView(t.buffer,t.byteOffset,t.byteLength).setFloat64(r,e,!0),t}},6411(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mul=Math.imul||function(e,t){var r=65535&e,n=65535&t;return r*n+((e>>>16&65535)*n+r*(t>>>16&65535)<<16>>>0)|0},t.add=function(e,t){return e+t|0},t.sub=function(e,t){return e-t|0},t.rotl=function(e,t){return e<<t|e>>>32-t},t.rotr=function(e,t){return e<<32-t|e>>>t},t.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.MAX_SAFE_INTEGER=9007199254740991,t.isSafeInteger=function(e){return t.isInteger(e)&&e>=-t.MAX_SAFE_INTEGER&&e<=t.MAX_SAFE_INTEGER}},7687(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.randomStringForEntropy=t.randomString=t.randomUint32=t.randomBytes=t.defaultRandomSource=void 0;const n=r(7841),i=r(3447),s=r(8767);function o(e,r=t.defaultRandomSource){return r.randomBytes(e)}t.defaultRandomSource=new n.SystemRandomSource,t.randomBytes=o,t.randomUint32=function(e=t.defaultRandomSource){const r=o(4,e),n=(0,i.readUint32LE)(r);return(0,s.wipe)(r),n};const a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function c(e,r=a,n=t.defaultRandomSource){if(r.length<2)throw new Error("randomString charset is too short");if(r.length>256)throw new Error("randomString charset is too long");let i="";const c=r.length,u=256-256%c;for(;e>0;){const t=o(Math.ceil(256*e/u),n);for(let n=0;n<t.length&&e>0;n++){const s=t[n];s<u&&(i+=r.charAt(s%c),e--)}(0,s.wipe)(t)}return i}t.randomString=c,t.randomStringForEntropy=function(e,r=a,n=t.defaultRandomSource){return c(Math.ceil(e/(Math.log(r.length)/Math.LN2)),r,n)}},4262(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserRandomSource=void 0,t.BrowserRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;const e="undefined"!=typeof self?self.crypto||self.msCrypto:null;e&&void 0!==e.getRandomValues&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");const t=new Uint8Array(e);for(let e=0;e<t.length;e+=65536)this._crypto.getRandomValues(t.subarray(e,e+Math.min(t.length-e,65536)));return t}}},1052(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NodeRandomSource=void 0;const n=r(8767);t.NodeRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;{const e=r(5423);e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let t=this._crypto.randomBytes(e);if(t.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");const r=new Uint8Array(e);for(let e=0;e<r.length;e++)r[e]=t[e];return(0,n.wipe)(t),r}}},7841(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemRandomSource=void 0;const n=r(4262),i=r(1052);t.SystemRandomSource=class{constructor(){return this.isAvailable=!1,this.name="",this._source=new n.BrowserRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Browser")):(this._source=new i.NodeRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Node")):void 0)}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}}},8767(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wipe=function(e){for(var t=0;t<e.length;t++)e[t]=0;return e}},240(e,t,r){const{Buffer:n}=r(1048),i=r(5950),s="UTF8",o="UTF16",a="UTF16BE",c="UTF16LE",u="UTF32",l="UTF32BE",h="UTF32LE",d="UINT7",f="ASCII",p="BINARY",m="UINT8",g="UINT16",y="UINT16LE",v="UINT16BE",b="UINT32",w="UINT32LE",E="UINT32BE",A="ESCAPED",k="STRING",x=function(e,t){switch(e){case s:return i.utf8.encode(t);case a:return i.utf16be.encode(t);case c:return i.utf16le.encode(t);case l:return i.utf32be.encode(t);case h:return i.utf32le.encode(t);case d:return i.uint7.encode(t);case m:return i.uint8.encode(t);case v:return i.uint16be.encode(t);case y:return i.uint16le.encode(t);case E:return i.uint32be.encode(t);case w:return i.uint32le.encode(t);case k:return i.string.encode(t);case A:return i.escaped.encode(t);default:throw new TypeError(`encode type "${e}" not recognized`)}};t.decode=function(e,t){return function(e){switch(e.type){case s:return i.utf8.decode(e.data,e.bom);case c:return i.utf16le.decode(e.data,e.bom);case a:return i.utf16be.decode(e.data,e.bom);case l:return i.utf32be.decode(e.data,e.bom);case h:return i.utf32le.decode(e.data,e.bom);case d:return i.uint7.decode(e.data);case m:return i.uint8.decode(e.data);case v:return i.uint16be.decode(e.data);case y:return i.uint16le.decode(e.data);case E:return i.uint32be.decode(e.data);case w:return i.uint32le.decode(e.data);case k:return i.string.decode(e.data);case A:return i.escaped.decode(e.data);default:throw new TypeError(`decode type "${e.type}" not recognized`)}}(function(e,t){const r=function(e){const t={type:"",base64:!1},r=/^(base64:)?([a-zA-Z0-9]+)$/i.exec(e);return r&&(r[2]&&(t.type=r[2].toUpperCase()),r[1]&&(t.base64=!0)),t}(e.toUpperCase());if(r.base64){if(r.type===k)throw new TypeError(`type: "${e} "BASE64:" prefix not allowed with type ${k}`);if(n.isBuffer(t))r.data=i.base64.decode(t);else{if("string"!=typeof t)throw new TypeError(`type: "${e} unrecognized data type: typeof(data): ${typeof t}`);{const e=n.from(t,"ascii");r.data=i.base64.decode(e)}}}else r.data=t;switch(r.type){case s:!function(e){e.type=s;const t=e.data;e.bom=0,t.length>=3&&239===t[0]&&187===t[1]&&191===t[2]&&(e.bom=3)}(r);break;case o:case a:case c:!function(e){const t=e.data;switch(e.bom=0,e.type){case o:e.type=a,t.length>=2&&(254===t[0]&&255===t[1]?e.bom=2:255===t[0]&&254===t[1]&&(e.type=c,e.bom=2));break;case a:if(e.type=a,t.length>=2)if(254===t[0]&&255===t[1])e.bom=2;else if(255===t[0]&&254===t[1])throw new TypeError(`src type: "${a}" specified but BOM is for "${c}"`);break;case c:if(e.type=c,t.length>=0){if(254===t[0]&&255===t[1])throw new TypeError(`src type: "${c}" specified but BOM is for "${a}"`);255===t[0]&&254===t[1]&&(e.bom=2)}break;default:throw new TypeError(`UTF16 BOM: src type "${e.type}" unrecognized`)}}(r);break;case u:case l:case h:!function(e){const t=e.data;switch(e.bom=0,e.type){case u:e.type=l,t.length>=4&&(0===t[0]&&0===t[1]&&254===t[2]&&255===t[3]&&(e.bom=4),255===t[0]&&254===t[1]&&0===t[2]&&0===t[3]&&(e.type=h,e.bom=4));break;case l:if(e.type=l,t.length>=4&&(0===t[0]&&0===t[1]&&254===t[2]&&255===t[3]&&(e.bom=4),255===t[0]&&254===t[1]&&0===t[2]&&0===t[3]))throw new TypeError(`src type: ${l} specified but BOM is for ${h}"`);break;case h:if(e.type=h,t.length>=4){if(0===t[0]&&0===t[1]&&254===t[2]&&255===t[3])throw new TypeError(`src type: "${h}" specified but BOM is for "${l}"`);255===t[0]&&254===t[1]&&0===t[2]&&0===t[3]&&(e.bom=4)}break;default:throw new TypeError(`UTF32 BOM: src type "${e.type}" unrecognized`)}}(r);break;case g:r.type=v;break;case b:r.type=E;break;case f:r.type=d;break;case p:r.type=m;break;case d:case m:case y:case v:case w:case E:case k:case A:break;default:throw new TypeError(`type: "${e}" not recognized`)}if(r.type===k){if("string"!=typeof r.data)throw new TypeError(`type: "${e}" but data is not a string`)}else if(!n.isBuffer(r.data))throw new TypeError(`type: "${e}" but data is not a Buffer`);return r}(e,t))},t.encode=function(e,t){let r,n;const _=function(e,t){if(!Array.isArray(t))throw new TypeError('dst chars: not array: "'+typeof t);if("string"!=typeof e)throw new TypeError('dst type: not string: "'+typeof e);const r=function(e){let t,r;const n={crlf:!1,lf:!1,base64:!1,type:""};for(;;){if(r=e,t=e.slice(0,5),"CRLF:"===t){n.crlf=!0,r=e.slice(5);break}if(t=e.slice(0,3),"LF:"===t){n.lf=!0,r=e.slice(3);break}break}return t=r.split(":"),1===t.length?n.type=t[0]:2===t.length&&"BASE64"===t[1]&&(n.base64=!0,n.type=t[0]),n}(e.toUpperCase());switch(r.type){case s:case a:case c:case l:case h:case d:case m:case y:case v:case w:case E:case A:break;case k:if(r.base64)throw new TypeError(`":BASE64" suffix not allowed with type ${k}`);break;case f:r.type=d;break;case p:r.type=m;break;case o:r.type=a;break;case u:r.type=l;break;case g:r.type=v;break;case b:r.type=E;break;default:throw new TypeError(`dst type unrecognized: "${e}" : must have form [crlf:|lf:]type[:base64]`)}return r}(e,t);return _.crlf?(r=i.lineEnds.crlf(t),n=x(_.type,r)):_.lf?(r=i.lineEnds.lf(t),n=x(_.type,r)):n=x(_.type,t),_.base64&&(n=i.base64.encode(n)),n},t.convert=function(e,r,n){return t.encode(n,t.decode(e,r))}},5950(e,t,r){const{Buffer:n}=r(1048),i=4294967292,s=4294967293,o=4294967294,a=4294967295,c=[0,1,3,7,15,31,63,127,255,511,1023],u=["00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F","10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F","20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F","30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F","40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F","50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F","60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F","70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F","80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F","90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F","A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF","B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF","C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF","D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF","E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF","F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF"],l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split(""),h=[];l.forEach(e=>{h.push(e.charCodeAt(0))}),t.utf8={encode(e){const t=[];return e.forEach(e=>{if(e>=0&&e<=127)t.push(e);else if(e<=2047)t.push(192+(e>>6&c[5])),t.push(128+(e&c[6]));else if(e<55296||e>57343&&e<=65535)t.push(224+(e>>12&c[4])),t.push(128+(e>>6&c[6])),t.push(128+(e&c[6]));else{if(!(e>=65536&&e<=1114111))throw new RangeError(`utf8.encode: character out of range: char: ${e}`);{const r=e>>16&c[5];t.push(240+(r>>2)),t.push(128+((r&c[2])<<4)+(e>>12&c[4])),t.push(128+(e>>6&c[6])),t.push(128+(e&c[6]))}}}),n.from(t)},decode(e,t){function r(e,t){if(128!=(192&t))return s;const r=((e&c[5])<<6)+(t&c[6]);return r<128?i:r}function n(e,t,r){if(128!=(192&r)||128!=(192&t))return s;const n=((e&c[4])<<12)+((t&c[6])<<6)+(r&c[6]);return n<2048?i:n>=55296&&n<=57343?o:n}function u(e,t,r,n){if(128!=(192&n)||128!=(192&r)||128!=(192&t))return s;const a=(((e&c[3])<<2)+(t>>4&c[2])<<16)+((t&c[4])<<12)+((r&c[6])<<6)+(n&c[6]);return a<65536?i:a>1114111?o:a}let l,h,d,f,p,m;const g=e.length;let y=t?3:0;const v=[];for(;y<g;){h=e[y],l=a;const t=!0;for(;t;){if(h>=0&&h<=127){l=h,m=1;break}if(d=y+1,d<g&&h>=194&&h<=223){l=r(h,e[d]),m=2;break}if(f=y+2,f<g&&h>=224&&h<=239){l=n(h,e[d],e[f]),m=3;break}if(p=y+3,p<g&&h>=240&&h<=244){l=u(h,e[d],e[f],e[p]),m=4;break}break}if(l>1114111){const e=`byte[${y}]`;if(l===a)throw new RangeError(`utf8.decode: ill-formed UTF8 byte sequence found at: ${e}`);if(l===s)throw new RangeError(`utf8.decode: illegal trailing byte found at: ${e}`);if(l===o)throw new RangeError(`utf8.decode: code point out of range found at: ${e}`);if(l===i)throw new RangeError(`utf8.decode: non-shortest form found at: ${e}`);throw new RangeError(`utf8.decode: unrecognized error found at: ${e}`)}v.push(l),y+=m}return v}},t.utf16be={encode(e){const t=[];let r,i,s;for(let n=0;n<e.length;n+=1)if(r=e[n],r>=0&&r<=55295||r>=57344&&r<=65535)t.push(r>>8&c[8]),t.push(r&c[8]);else{if(!(r>=65536&&r<=1114111))throw new RangeError(`utf16be.encode: UTF16BE value out of range: char[${n}]: ${r}`);s=r-65536,i=55296+(s>>10),s=56320+(s&c[10]),t.push(i>>8&c[8]),t.push(i&c[8]),t.push(s>>8&c[8]),t.push(s&c[8])}return n.from(t)},decode(e,t){if(e.length%2>0)throw new RangeError(`utf16be.decode: data length must be even multiple of 2: length: ${e.length}`);const r=[],n=e.length;let i,s,o,a,c,u,l=t?2:0,h=0;for(;l<n;){const t=!0;for(;t;){if(o=l+1,o<n){if(c=(e[l]<<8)+e[o],c<55296||c>57343){i=c,s=2;break}if(a=l+3,a<n&&(u=(e[l+2]<<8)+e[a],c<=56319&&u>=56320&&u<=57343)){i=65536+(c-55296<<10)+(u-56320),s=4;break}}throw new RangeError(`utf16be.decode: ill-formed UTF16BE byte sequence found: byte[${l}]`)}r[h++]=i,l+=s}return r}},t.utf16le={encode(e){const t=[];let r,i,s;for(let n=0;n<e.length;n+=1)if(r=e[n],r>=0&&r<=55295||r>=57344&&r<=65535)t.push(r&c[8]),t.push(r>>8&c[8]);else{if(!(r>=65536&&r<=1114111))throw new RangeError(`utf16le.encode: UTF16LE value out of range: char[${n}]: ${r}`);s=r-65536,i=55296+(s>>10),s=56320+(s&c[10]),t.push(i&c[8]),t.push(i>>8&c[8]),t.push(s&c[8]),t.push(s>>8&c[8])}return n.from(t)},decode(e,t){if(e.length%2>0)throw new RangeError(`utf16le.decode: data length must be even multiple of 2: length: ${e.length}`);const r=[],n=e.length;let i,s,o,a,c,u,l=t?2:0,h=0;for(;l<n;){const t=!0;for(;t;){if(o=l+1,o<n){if(c=(e[o]<<8)+e[l],c<55296||c>57343){i=c,s=2;break}if(a=l+3,a<n&&(u=(e[a]<<8)+e[l+2],c<=56319&&u>=56320&&u<=57343)){i=65536+(c-55296<<10)+(u-56320),s=4;break}}throw new RangeError(`utf16le.decode: ill-formed UTF16LE byte sequence found: byte[${l}]`)}r[h++]=i,l+=s}return r}},t.utf32be={encode(e){const t=n.alloc(4*e.length);let r=0;return e.forEach(e=>{if(e>=55296&&e<=57343||e>1114111)throw new RangeError(`utf32be.encode: UTF32BE character code out of range: char[${r/4}]: ${e}`);t[r++]=e>>24&c[8],t[r++]=e>>16&c[8],t[r++]=e>>8&c[8],t[r++]=e&c[8]}),t},decode(e,t){if(e.length%4>0)throw new RangeError(`utf32be.decode: UTF32BE byte length must be even multiple of 4: length: ${e.length}`);const r=[];let n=t?4:0;for(;n<e.length;n+=4){const t=(e[n]<<24)+(e[n+1]<<16)+(e[n+2]<<8)+e[n+3];if(t>=55296&&t<=57343||t>1114111)throw new RangeError(`utf32be.decode: UTF32BE character code out of range: char[${n/4}]: ${t}`);r.push(t)}return r}},t.utf32le={encode(e){const t=n.alloc(4*e.length);let r=0;return e.forEach(e=>{if(e>=55296&&e<=57343||e>1114111)throw new RangeError(`utf32le.encode: UTF32LE character code out of range: char[${r/4}]: ${e}`);t[r++]=e&c[8],t[r++]=e>>8&c[8],t[r++]=e>>16&c[8],t[r++]=e>>24&c[8]}),t},decode(e,t){if(e.length%4>0)throw new RangeError(`utf32be.decode: UTF32LE byte length must be even multiple of 4: length: ${e.length}`);const r=[];let n=t?4:0;for(;n<e.length;n+=4){const t=(e[n+3]<<24)+(e[n+2]<<16)+(e[n+1]<<8)+e[n];if(t>=55296&&t<=57343||t>1114111)throw new RangeError(`utf32le.encode: UTF32LE character code out of range: char[${n/4}]: ${t}`);r.push(t)}return r}},t.uint7={encode(e){const t=n.alloc(e.length);for(let r=0;r<e.length;r+=1){if(e[r]>127)throw new RangeError(`uint7.encode: UINT7 character code out of range: char[${r}]: ${e[r]}`);t[r]=e[r]}return t},decode(e){const t=[];for(let r=0;r<e.length;r+=1){if(e[r]>127)throw new RangeError(`uint7.decode: UINT7 character code out of range: byte[${r}]: ${e[r]}`);t[r]=e[r]}return t}},t.uint8={encode(e){const t=n.alloc(e.length);for(let r=0;r<e.length;r+=1){if(e[r]>255)throw new RangeError(`uint8.encode: UINT8 character code out of range: char[${r}]: ${e[r]}`);t[r]=e[r]}return t},decode(e){const t=[];for(let r=0;r<e.length;r+=1)t[r]=e[r];return t}},t.uint16be={encode(e){const t=n.alloc(2*e.length);let r=0;return e.forEach(e=>{if(e>65535)throw new RangeError(`uint16be.encode: UINT16BE character code out of range: char[${r/2}]: ${e}`);t[r++]=e>>8&c[8],t[r++]=e&c[8]}),t},decode(e){if(e.length%2>0)throw new RangeError(`uint16be.decode: UINT16BE byte length must be even multiple of 2: length: ${e.length}`);const t=[];for(let r=0;r<e.length;r+=2)t.push((e[r]<<8)+e[r+1]);return t}},t.uint16le={encode(e){const t=n.alloc(2*e.length);let r=0;return e.forEach(e=>{if(e>65535)throw new RangeError(`uint16le.encode: UINT16LE character code out of range: char[${r/2}]: ${e}`);t[r++]=e&c[8],t[r++]=e>>8&c[8]}),t},decode(e){if(e.length%2>0)throw new RangeError(`uint16le.decode: UINT16LE byte length must be even multiple of 2: length: ${e.length}`);const t=[];for(let r=0;r<e.length;r+=2)t.push((e[r+1]<<8)+e[r]);return t}},t.uint32be={encode(e){const t=n.alloc(4*e.length);let r=0;return e.forEach(e=>{t[r++]=e>>24&c[8],t[r++]=e>>16&c[8],t[r++]=e>>8&c[8],t[r++]=e&c[8]}),t},decode(e){if(e.length%4>0)throw new RangeError(`uint32be.decode: UINT32BE byte length must be even multiple of 4: length: ${e.length}`);const t=[];for(let r=0;r<e.length;r+=4)t.push((e[r]<<24)+(e[r+1]<<16)+(e[r+2]<<8)+e[r+3]);return t}},t.uint32le={encode(e){const t=n.alloc(4*e.length);let r=0;return e.forEach(e=>{t[r++]=e&c[8],t[r++]=e>>8&c[8],t[r++]=e>>16&c[8],t[r++]=e>>24&c[8]}),t},decode(e){if(e.length%4>0)throw new RangeError(`uint32le.decode: UINT32LE byte length must be even multiple of 4: length: ${e.length}`);const t=[];for(let r=0;r<e.length;r+=4)t.push((e[r+3]<<24)+(e[r+2]<<16)+(e[r+1]<<8)+e[r]);return t}},t.string={encode:e=>t.utf16le.encode(e).toString("utf16le"),decode:e=>t.utf16le.decode(n.from(e,"utf16le"),0)},t.escaped={encode(e){const t=[];for(let r=0;r<e.length;r+=1){const i=e[r];if(96===i)t.push(i),t.push(i);else if(10===i)t.push(i);else if(i>=32&&i<=126)t.push(i);else{let e="";if(i>=0&&i<=31)e+=`\`x${u[i]}`;else if(i>=127&&i<=255)e+=`\`x${u[i]}`;else if(i>=256&&i<=65535)e+=`\`u${u[i>>8&c[8]]}${u[i&c[8]]}`;else{if(!(i>=65536&&i<=4294967295))throw new Error("escape.encode(char): char > 0xffffffff not allowed");{e+="`u{";const t=i>>24&c[8];t>0&&(e+=u[t]),e+=`${u[i>>16&c[8]]+u[i>>8&c[8]]+u[i&c[8]]}}`}}n.from(e).forEach(e=>{t.push(e)})}}return n.from(t)},decode(e){function t(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function r(e,r,n){const i={char:null,nexti:e+2,error:!0};if(e+1<r&&t(n[e])&&t(n[e+1])){const t=String.fromCodePoint(n[e],n[e+1]);i.char=parseInt(t,16),Number.isNaN(i.char)||(i.error=!1)}return i}function n(e,r,n){const i={char:null,nexti:e+4,error:!0};if(e+3<r&&t(n[e])&&t(n[e+1])&&t(n[e+2])&&t(n[e+3])){const t=String.fromCodePoint(n[e],n[e+1],n[e+2],n[e+3]);i.char=parseInt(t,16),Number.isNaN(i.char)||(i.error=!1)}return i}function i(e,r,n){const i={char:null,nexti:e+4,error:!0};let s="";for(;e<r&&t(n[e]);)s+=String.fromCodePoint(n[e]),e+=1;return i.char=parseInt(s,16),125!==n[e]||Number.isNaN(i.char)||(i.error=!1),i.nexti=e+1,i}const s=[],o=e.length;let a,c,u,l=0;for(;l<o;){const t=!0;for(;t;){if(u=!0,96!==e[l]){s.push(e[l]),l+=1,u=!1;break}if(a=l+1,a>=o)break;if(96===e[a]){s.push(96),l+=2,u=!1;break}if(120===e[a]){if(c=r(a+1,o,e),c.error)break;s.push(c.char),l=c.nexti,u=!1;break}if(117===e[a]){if(123===e[a+1]){if(c=i(a+2,o,e),c.error)break;s.push(c.char),l=c.nexti,u=!1;break}if(c=n(a+1,o,e),c.error)break;s.push(c.char),l=c.nexti,u=!1;break}break}if(u)throw new Error(`escaped.decode: ill-formed escape sequence at buf[${l}]`)}return s}};const d=10;t.lineEnds={crlf(e){const t=[];let r=0;for(;r<e.length;)switch(e[r]){case 13:r+1<e.length&&e[r+1]===d?r+=2:r+=1,t.push(13),t.push(d);break;case d:t.push(13),t.push(d),r+=1;break;default:t.push(e[r]),r+=1}return t.length>0&&t[t.length-1]!==d&&(t.push(13),t.push(d)),t},lf(e){const t=[];let r=0;for(;r<e.length;)switch(e[r]){case 13:r+1<e.length&&e[r+1]===d?r+=2:r+=1,t.push(d);break;case d:t.push(d),r+=1;break;default:t.push(e[r]),r+=1}return t.length>0&&t[t.length-1]!==d&&t.push(d),t}},t.base64={encode(e){if(0===e.length)return n.alloc(0);let t,r,i,s=e.length%3;s=s>0?3-s:0;let o=(e.length+s)/3;const a=n.alloc(4*o);s>0&&(o-=1),t=0,r=0;for(let n=0;n<o;n+=1)i=e[t++]<<16,i+=e[t++]<<8,i+=e[t++],a[r++]=h[i>>18&c[6]],a[r++]=h[i>>12&c[6]],a[r++]=h[i>>6&c[6]],a[r++]=h[i&c[6]];return 0===s?a:1===s?(i=e[t++]<<16,i+=e[t]<<8,a[r++]=h[i>>18&c[6]],a[r++]=h[i>>12&c[6]],a[r++]=h[i>>6&c[6]],a[r]=h[64],a):2===s?(i=e[t]<<16,a[r++]=h[i>>18&c[6]],a[r++]=h[i>>12&c[6]],a[r++]=h[64],a[r]=h[64],a):void 0},decode(e){if(0===e.length)return n.alloc(0);const t=function(e){const t=[];let r=0;for(let n=0;n<e.length;n+=1){const i=e[n],s=!0;for(;s&&32!==i&&9!==i&&10!==i&&13!==i;){if(i>=65&&i<=90){t.push(i-65);break}if(i>=97&&i<=122){t.push(i-71);break}if(i>=48&&i<=57){t.push(i+4);break}if(43===i){t.push(62);break}if(47===i){t.push(63);break}if(61===i){t.push(64),r+=1;break}throw new RangeError(`base64.decode: invalid character buf[${n}]: ${i}`)}}if(t.length%4>0)throw new RangeError(`base64.decode: string length not integral multiple of 4: ${t.length}`);switch(r){case 0:break;case 1:if(64!==t[t.length-1])throw new RangeError("base64.decode: one tail character found: not last character");break;case 2:if(64!==t[t.length-1]||64!==t[t.length-2])throw new RangeError("base64.decode: two tail characters found: not last characters");break;default:throw new RangeError(`base64.decode: more than two tail characters found: ${r}`)}return{tail:r,buf:n.from(t)}}(e),{tail:r}=t,i=t.buf;let s,o,a,u=i.length/4;const l=n.alloc(3*u-r);r>0&&(u-=1),o=0,s=0;for(let e=0;e<u;e+=1)a=i[s++]<<18,a+=i[s++]<<12,a+=i[s++]<<6,a+=i[s++],l[o++]=a>>16&c[8],l[o++]=a>>8&c[8],l[o++]=a&c[8];return 1===r&&(a=i[s++]<<18,a+=i[s++]<<12,a+=i[s]<<6,l[o++]=a>>16&c[8],l[o]=a>>8&c[8]),2===r&&(a=i[s++]<<18,a+=i[s++]<<12,l[o]=a>>16&c[8]),l},toString(e){if(e.length%4>0)throw new RangeError(`base64.toString: input buffer length not multiple of 4: ${e.length}`);let t="",r=0;function n(e,n,i,s){switch(r){case 76:t+=`\r\n${e}${n}${i}${s}`,r=4;break;case 75:t+=`${e}\r\n${n}${i}${s}`,r=3;break;case 74:t+=`${e+n}\r\n${i}${s}`,r=2;break;case 73:t+=`${e+n+i}\r\n${s}`,r=1;break;default:t+=e+n+i+s,r+=4}}function i(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||43===e||47===e||61===e}for(let t=0;t<e.length;t+=4){for(let r=t;r<t+4;r+=1)if(!i(e[r]))throw new RangeError(`base64.toString: buf[${r}]: ${e[r]} : not valid base64 character code`);n(String.fromCharCode(e[t]),String.fromCharCode(e[t+1]),String.fromCharCode(e[t+2]),String.fromCharCode(e[t+3]))}return t}}},7770(e,t,r){e.exports=function(){const e=r(5298),t=r(1174),n=this;let i=null,s=null,o=null,a=0;const c=[],u=[],l=[],h=[];function d(e){let t="";for(let r=0;r<e;r+=1)t+=" ";return t}this.callbacks=[],this.astObject="astObject",this.init=function(e,t,r){let d;l.length=0,h.length=0,c.length=0,a=0,i=e,s=t,o=r;const f=[];for(d=0;d<i.length;d+=1)f.push(i[d].lower);for(d=0;d<s.length;d+=1)f.push(s[d].lower);for(a=i.length+s.length,d=0;d<a;d+=1)c[d]=!1,u[d]=null;for(const e in n.callbacks){const t=e.toLowerCase();if(d=f.indexOf(t),d<0)throw new Error(`ast.js: init: node '${e}' not a rule or udt name`);"function"==typeof n.callbacks[e]&&(c[d]=!0,u[d]=n.callbacks[e]),!0===n.callbacks[e]&&(c[d]=!0)}},this.ruleDefined=function(e){return!1!==c[e]},this.udtDefined=function(e){return!1!==c[i.length+e]},this.down=function(t,r){const n=h.length;return l.push(n),h.push({name:r,thisIndex:n,thatIndex:null,state:e.SEM_PRE,callbackIndex:t,phraseIndex:null,phraseLength:null,stack:l.length}),n},this.up=function(t,r,n,i){const s=h.length,o=l.pop();return h.push({name:r,thisIndex:s,thatIndex:o,state:e.SEM_POST,callbackIndex:t,phraseIndex:n,phraseLength:i,stack:l.length}),h[o].thatIndex=s,h[o].phraseIndex=n,h[o].phraseLength=i,s},this.translate=function(t){let r,n,i;for(let s=0;s<h.length;s+=1)i=h[s],n=u[i.callbackIndex],i.state===e.SEM_PRE?null!==n&&(r=n(e.SEM_PRE,o,i.phraseIndex,i.phraseLength,t),r===e.SEM_SKIP&&(s=i.thatIndex)):null!==n&&n(e.SEM_POST,o,i.phraseIndex,i.phraseLength,t)},this.setLength=function(e){h.length=e,l.length=e>0?h[e-1].stack:0},this.getLength=function(){return h.length},this.toXml=function(r){let n=t.charsToDec,i="decimal integer character codes";if("string"==typeof r&&r.length>=3){const e=r.slice(0,3).toLowerCase();"asc"===e?(n=t.charsToAscii,i="ASCII for printing characters, hex for non-printing"):"hex"===e?(n=t.charsToHex,i="hexadecimal integer character codes"):"uni"===e&&(n=t.charsToUnicode,i="Unicode UTF-32 integer character codes")}let s="",a=0;return s+='<?xml version="1.0" encoding="utf-8"?>\n',s+=`<root nodes="${h.length/2}" characters="${o.length}">\n`,s+=`\x3c!-- input string, ${i} --\x3e\n`,s+=d(a+2),s+=n(o),s+="\n",h.forEach(t=>{t.state===e.SEM_PRE?(a+=1,s+=d(a),s+=`<node name="${t.name}" index="${t.phraseIndex}" length="${t.phraseLength}">\n`,s+=d(a+2),s+=n(o,t.phraseIndex,t.phraseLength),s+="\n"):(s+=d(a),s+=`</node>\x3c!-- name="${t.name}" --\x3e\n`,a-=1)}),s+="</root>\n",s},this.phrases=function(){const t={};let r,n;for(r=0;r<h.length;r+=1)n=h[r],n.state===e.SEM_PRE&&(Array.isArray(t[n.name])||(t[n.name]=[]),t[n.name].push({index:n.phraseIndex,length:n.phraseLength}));return t}}},6660(e){e.exports=function(){let e=-1,t=0;this.init=function(r){if("number"!=typeof r||r<=0)throw new Error("circular-buffer.js: init: circular buffer size must an integer > 0");t=Math.ceil(r),e=-1},this.increment=function(){return e+=1,(e+t)%t},this.maxSize=function(){return t},this.items=function(){return e+1},this.getListIndex=function(r){return-1===e||r<0||r>e||e-r>=t?-1:(r+t)%t},this.forEach=function(r){if(-1!==e)if(e<t)for(let t=0;t<=e;t+=1)r(t,t);else for(let n=e-t+1;n<=e;n+=1)r((n+t)%t,n)}}},9724(e){e.exports=function(){return"/* This file automatically generated by jsonToless() and LESS. */\n.apg-mono {\n font-family: monospace;\n}\n.apg-active {\n font-weight: bold;\n color: #000000;\n}\n.apg-match {\n font-weight: bold;\n color: #264BFF;\n}\n.apg-empty {\n font-weight: bold;\n color: #0fbd0f;\n}\n.apg-nomatch {\n font-weight: bold;\n color: #FF4000;\n}\n.apg-lh-match {\n font-weight: bold;\n color: #1A97BA;\n}\n.apg-lb-match {\n font-weight: bold;\n color: #5F1687;\n}\n.apg-remainder {\n font-weight: bold;\n color: #999999;\n}\n.apg-ctrl-char {\n font-weight: bolder;\n font-style: italic;\n font-size: 0.6em;\n}\n.apg-line-end {\n font-weight: bold;\n color: #000000;\n}\n.apg-error {\n font-weight: bold;\n color: #FF4000;\n}\n.apg-phrase {\n color: #000000;\n background-color: #8caae6;\n}\n.apg-empty-phrase {\n color: #0fbd0f;\n}\ntable.apg-state {\n font-family: monospace;\n margin-top: 5px;\n font-size: 11px;\n line-height: 130%;\n text-align: left;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-state th,\ntable.apg-state td {\n text-align: left;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-state th:nth-last-child(2),\ntable.apg-state td:nth-last-child(2) {\n text-align: right;\n}\ntable.apg-state caption {\n font-size: 125%;\n line-height: 130%;\n font-weight: bold;\n text-align: left;\n}\ntable.apg-stats {\n font-family: monospace;\n margin-top: 5px;\n font-size: 11px;\n line-height: 130%;\n text-align: right;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-stats th,\ntable.apg-stats td {\n text-align: right;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-stats caption {\n font-size: 125%;\n line-height: 130%;\n font-weight: bold;\n text-align: left;\n}\ntable.apg-trace {\n font-family: monospace;\n margin-top: 5px;\n font-size: 11px;\n line-height: 130%;\n text-align: right;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-trace caption {\n font-size: 125%;\n line-height: 130%;\n font-weight: bold;\n text-align: left;\n}\ntable.apg-trace th,\ntable.apg-trace td {\n text-align: right;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-trace th:last-child,\ntable.apg-trace th:nth-last-child(2),\ntable.apg-trace td:last-child,\ntable.apg-trace td:nth-last-child(2) {\n text-align: left;\n}\ntable.apg-grammar {\n font-family: monospace;\n margin-top: 5px;\n font-size: 11px;\n line-height: 130%;\n text-align: right;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-grammar caption {\n font-size: 125%;\n line-height: 130%;\n font-weight: bold;\n text-align: left;\n}\ntable.apg-grammar th,\ntable.apg-grammar td {\n text-align: right;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-grammar th:last-child,\ntable.apg-grammar td:last-child {\n text-align: left;\n}\ntable.apg-rules {\n font-family: monospace;\n margin-top: 5px;\n font-size: 11px;\n line-height: 130%;\n text-align: right;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-rules caption {\n font-size: 125%;\n line-height: 130%;\n font-weight: bold;\n text-align: left;\n}\ntable.apg-rules th,\ntable.apg-rules td {\n text-align: right;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-rules a {\n color: #003399 !important;\n}\ntable.apg-rules a:hover {\n color: #8caae6 !important;\n}\ntable.apg-attrs {\n font-family: monospace;\n margin-top: 5px;\n font-size: 11px;\n line-height: 130%;\n text-align: center;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-attrs caption {\n font-size: 125%;\n line-height: 130%;\n font-weight: bold;\n text-align: left;\n}\ntable.apg-attrs th,\ntable.apg-attrs td {\n text-align: center;\n border: 1px solid black;\n border-collapse: collapse;\n}\ntable.apg-attrs th:nth-child(1),\ntable.apg-attrs th:nth-child(2),\ntable.apg-attrs th:nth-child(3) {\n text-align: right;\n}\ntable.apg-attrs td:nth-child(1),\ntable.apg-attrs td:nth-child(2),\ntable.apg-attrs td:nth-child(3) {\n text-align: right;\n}\ntable.apg-attrs a {\n color: #003399 !important;\n}\ntable.apg-attrs a:hover {\n color: #8caae6 !important;\n}\n"}},5298(e){e.exports={ALT:1,CAT:2,REP:3,RNM:4,TRG:5,TBS:6,TLS:7,UDT:11,AND:12,NOT:13,BKR:14,BKA:15,BKN:16,ABG:17,AEN:18,ACTIVE:100,MATCH:101,EMPTY:102,NOMATCH:103,SEM_PRE:200,SEM_POST:201,SEM_OK:300,SEM_SKIP:301,ATTR_N:400,ATTR_R:401,ATTR_MR:402,LOOKAROUND_NONE:500,LOOKAROUND_AHEAD:501,LOOKAROUND_BEHIND:502,BKR_MODE_UM:601,BKR_MODE_PM:602,BKR_MODE_CS:603,BKR_MODE_CI:604}},4202(e,t,r){e.exports={ast:r(7770),circular:r(6660),ids:r(5298),parser:r(1355),stats:r(7857),trace:r(8127),utils:r(1174),emitcss:r(9724),style:r(2475)}},1355(e,t,r){e.exports=function(){const e=r(5298),t=r(1174),n="parser.js: ",i=this;let s;this.ast=null,this.stats=null,this.trace=null,this.callbacks=[];let o,a,c,u,l=null,h=null,d=0,f=0,p=0,m=null,g=null,y=null,v=null,b=null,w=0,E=1/0,A=1/0;const k=function(t,r,i){const o=`${n}evaluateRule(): `;if(t>=y.length)throw new Error(`${o}rule index: ${t} out of range`);if(r>=c)throw new Error(`${o}phrase index: ${r} out of range`);const{length:a}=l;l.push({type:e.RNM,index:t}),s(a,r,i),l.pop()},x=function(t,r,i){const o=`${n}evaluateUdt(): `;if(t>=v.length)throw new Error(`${o}udt index: ${t} out of range`);if(r>=c)throw new Error(`${o}phrase index: ${r} out of range`);const{length:a}=l;l.push({type:e.UDT,empty:v[t].empty,index:t}),s(a,r,i),l.pop()},_=function(){d=0,f=0,p=0,w=0,u=[{lookAround:e.LOOKAROUND_NONE,anchor:0,charsEnd:0,charsLength:0}],y=null,v=null,h=null,o=0,a=0,c=0,m=null,g=null,b=null,l=null},T=function(){const e=[];this.push=function(){e.push(function(){const t=e[e.length-1],r={};for(const e in t)r[e]=t[e];return r}())},this.pop=function(t){let r=t;if(r||(r=e.length-1),r<1||r>e.length)throw new Error(`${n}backRef.pop(): bad length: ${r}`);return e.length=r,e[e.length-1]},this.length=function(){return e.length},this.savePhrase=function(t,r,n){e[e.length-1][t]={phraseIndex:r,phraseLength:n}},this.getPhrase=function(t){return e[e.length-1][t]},function(){const t={};y.forEach(e=>{e.isBkr&&(t[e.lower]=null)}),v.length>0&&v.forEach(e=>{e.isBkr&&(t[e.lower]=null)}),e.push(t)}()},S=function(){const t=this;this.state=e.ACTIVE,this.phraseLength=0,this.ruleIndex=0,this.udtIndex=0,this.lookAround=u[u.length-1],this.uFrame=new T,this.pFrame=new T,this.evaluateRule=k,this.evaluateUdt=x,this.refresh=function(){t.state=e.ACTIVE,t.phraseLength=0,t.lookAround=u[u.length-1]}},I=function(){return u[u.length-1]},N=function(){return u.length>1},R=function(e,r,i){const s=`${n}initializeInputChars(): `;let u=e,l=r,d=i;if(void 0===u)throw new Error(`${s}input string is undefined`);if(null===u)throw new Error(`${s}input string is null`);if("string"==typeof u)u=t.stringToChars(u);else if(!Array.isArray(u))throw new Error(`${s}input string is not a string or array`);if(u.length>0&&"number"!=typeof u[0])throw new Error(`${s}input string not an array of integers`);if("number"!=typeof l)l=0;else if(l=Math.floor(l),l<0||l>u.length)throw new Error(`${s}input beginning index out of range: ${l}`);if("number"!=typeof d)d=u.length-l;else if(d=Math.floor(d),d<0||d>u.length-l)throw new Error(`${s}input length out of range: ${d}`);h=u,o=l,a=d,c=o+a};this.setMaxTreeDepth=function(e){if("number"!=typeof e)throw new Error(`parser: max tree depth must be integer > 0: ${e}`);if(E=Math.floor(e),E<=0)throw new Error(`parser: max tree depth must be integer > 0: ${e}`)},this.setMaxNodeHits=function(e){if("number"!=typeof e)throw new Error(`parser: max node hits must be integer > 0: ${e}`);if(A=Math.floor(e),A<=0)throw new Error(`parser: max node hits must be integer > 0: ${e}`)};const O=function(t,r,u){let d;const E=`${n}parse(): `;!function(e){const t=`${n}initializeGrammar(): `;if(!e)throw new Error(`${t}grammar object undefined`);if("grammarObject"!==e.grammarObject)throw new Error(`${t}bad grammar object`);y=e.rules,v=e.udts}(t);const A=function(e){const t=`${n}initializeStartRule(): `;let r=null;if("number"==typeof e){if(e>=y.length)throw new Error(`${t}start rule index too large: max: ${y.length}: index: ${e}`);r=e}else{if("string"!=typeof e)throw new Error(`${t}type of start rule '${typeof e}' not recognized`);{const n=e.toLowerCase();for(let e=0;e<y.length;e+=1)if(n===y[e].lower){r=y[e].index;break}if(null===r)throw new Error(`${t}start rule name '${e}' not recognized`)}}return r}(r);!function(){const e=`${n}initializeCallbacks(): `;let t,r;for(m=[],g=[],t=0;t<y.length;t+=1)m[t]=null;for(t=0;t<v.length;t+=1)g[t]=null;const s=[];for(t=0;t<y.length;t+=1)s.push(y[t].lower);for(t=0;t<v.length;t+=1)s.push(v[t].lower);for(const n in i.callbacks){if(t=s.indexOf(n.toLowerCase()),t<0)throw new Error(`${e}syntax callback '${n}' not a rule or udt name`);if(r=i.callbacks[n],r||(r=null),"function"!=typeof r&&null!==r)throw new Error(`${e}syntax callback[${n}] must be function reference or 'false' (false/null/undefined/etc.)`);t<y.length?m[t]=r:g[t-y.length]=r}for(t=0;t<v.length;t+=1)if(null===g[t])throw new Error(`${e}all UDT callbacks must be defined. UDT callback[${v[t].lower}] not a function reference`)}(),function(){const e=`${n}initializeTrace(): `;for(;;){if(void 0===i.trace){i.trace=null;break}if(null===i.trace)break;if("traceObject"!==i.trace.traceObject)throw new Error(`${e}trace object not recognized`);break}null!==i.trace&&i.trace.init(y,v,h)}(),function(){const e=`${n}initializeStats(): `;for(;;){if(void 0===i.stats){i.stats=null;break}if(null===i.stats)break;if("statsObject"!==i.stats.statsObject)throw new Error(`${e}stats object not recognized`);break}null!==i.stats&&i.stats.init(y,v)}(),function(){const e=`${n}initializeAst(): `;for(;;){if(void 0===i.ast){i.ast=null;break}if(null===i.ast)break;if("astObject"!==i.ast.astObject)throw new Error(`${e}ast object not recognized`);break}null!==i.ast&&i.ast.init(y,v,h)}();const k=new S;switch(null!=u&&(b=u),l=[{type:e.RNM,index:A}],s(0,o,k),l=null,k.state){case e.ACTIVE:throw new Error(`${E}final state should never be 'ACTIVE'`);case e.NOMATCH:d=!1;break;case e.EMPTY:case e.MATCH:d=k.phraseLength===a;break;default:throw new Error("unrecognized state")}return{success:d,state:k.state,length:a,matched:k.phraseLength,maxMatched:w,maxTreeDepth:f,nodeHits:p,inputLength:h.length,subBegin:o,subEnd:c,subLength:a}};this.parseSubstring=function(e,t,r,n,i,s){return _(),R(r,n,i),O(e,t,s)},this.parse=function(e,t,r,n){return _(),R(r,0,r.length),O(e,t,n)};const C=function(t,r,n){const i=l[t];for(let t=0;t<i.children.length&&(s(i.children[t],r,n),n.state===e.NOMATCH);t+=1);},P=function(t,r,i,s){if(r.phraseLength>i){let e=`${n}opRNM(${t.name}): callback function error: `;throw e+=`sysData.phraseLength: ${r.phraseLength}`,e+=` must be <= remaining chars: ${i}`,new Error(e)}switch(r.state){case e.ACTIVE:if(!0!==s)throw new Error(`${n}opRNM(${t.name}): callback function return error. ACTIVE state not allowed.`);break;case e.EMPTY:r.phraseLength=0;break;case e.MATCH:0===r.phraseLength&&(r.state=e.EMPTY);break;case e.NOMATCH:r.phraseLength=0;break;default:throw new Error(`${n}opRNM(${t.name}): callback function return error. Unrecognized return state: ${r.state}`)}},M=function(t,r,n){let o,a,u,d,f,p;const g=l[t],v=y[g.index],w=m[v.index],E=!N();if(E&&(a=i.ast&&i.ast.ruleDefined(g.index),a&&(o=i.ast.getLength(),i.ast.down(g.index,y[g.index].name)),d=n.uFrame.length(),f=n.pFrame.length(),n.uFrame.push(),n.pFrame.push(),p=n.pFrame,n.pFrame=new T),null===w)u=l,l=v.opcodes,s(0,r,n),l=u;else{const t=c-r;n.ruleIndex=v.index,w(n,h,r,b),P(v,n,t,!0),n.state===e.ACTIVE&&(u=l,l=v.opcodes,s(0,r,n),l=u,n.ruleIndex=v.index,w(n,h,r,b),P(v,n,t,!1))}E&&(a&&(n.state===e.NOMATCH?i.ast.setLength(o):i.ast.up(g.index,v.name,r,n.phraseLength)),n.pFrame=p,n.state===e.NOMATCH?(n.uFrame.pop(d),n.pFrame.pop(f)):v.isBkr&&(n.pFrame.savePhrase(v.lower,r,n.phraseLength),n.uFrame.savePhrase(v.lower,r,n.phraseLength)))},D=function(t,r,s){let o,a,u,d,f,p;const m=l[t],w=v[m.index];s.UdtIndex=w.index;const E=!N();E&&(u=i.ast&&i.ast.udtDefined(m.index),u&&(a=y.length+m.index,o=i.ast.getLength(),i.ast.down(a,w.name)),d=s.uFrame.length(),f=s.pFrame.length(),s.uFrame.push(),s.pFrame.push(),p=s.pFrame,s.pFrame=new T);const A=c-r;g[m.index](s,h,r,b),function(t,r,i){if(r.phraseLength>i){let e=`${n}opUDT(${t.name}): callback function error: `;throw e+=`sysData.phraseLength: ${r.phraseLength}`,e+=` must be <= remaining chars: ${i}`,new Error(e)}switch(r.state){case e.ACTIVE:throw new Error(`${n}opUDT(${t.name}): callback function return error. ACTIVE state not allowed.`);case e.EMPTY:if(!1===t.empty)throw new Error(`${n}opUDT(${t.name}): callback function return error. May not return EMPTY.`);r.phraseLength=0;break;case e.MATCH:if(0===r.phraseLength){if(!1===t.empty)throw new Error(`${n}opUDT(${t.name}): callback function return error. May not return EMPTY.`);r.state=e.EMPTY}break;case e.NOMATCH:r.phraseLength=0;break;default:throw new Error(`${n}opUDT(${t.name}): callback function return error. Unrecognized return state: ${r.state}`)}}(w,s,A),E&&(u&&(s.state===e.NOMATCH?i.ast.setLength(o):i.ast.up(a,w.name,r,s.phraseLength)),s.pFrame=p,s.state===e.NOMATCH?(s.uFrame.pop(d),s.pFrame.pop(f)):w.isBkr&&(s.pFrame.savePhrase(w.lower,r,s.phraseLength),s.uFrame.savePhrase(w.lower,r,s.phraseLength)))},B=function(t,r,n){u.push({lookAround:e.LOOKAROUND_AHEAD,anchor:r,charsEnd:c,charsLength:a}),c=h.length,a=h.length-o,s(t+1,r,n);const i=u.pop();switch(c=i.charsEnd,a=i.charsLength,n.phraseLength=0,n.state){case e.EMPTY:case e.MATCH:n.state=e.EMPTY;break;case e.NOMATCH:n.state=e.NOMATCH;break;default:throw new Error(`opAND: invalid state ${n.state}`)}},L=function(t,r,n){u.push({lookAround:e.LOOKAROUND_AHEAD,anchor:r,charsEnd:c,charsLength:a}),c=h.length,a=h.length-o,s(t+1,r,n);const i=u.pop();switch(c=i.charsEnd,a=i.charsLength,n.phraseLength=0,n.state){case e.EMPTY:case e.MATCH:n.state=e.NOMATCH;break;case e.NOMATCH:n.state=e.EMPTY;break;default:throw new Error(`opNOT: invalid state ${n.state}`)}},U=function(t,r,n){n.state=e.NOMATCH,n.phraseLength=0,n.state=0===r?e.EMPTY:e.NOMATCH},F=function(t,r,n){n.state=e.NOMATCH,n.phraseLength=0,n.state=r===h.length?e.EMPTY:e.NOMATCH},$=function(t,r,n){switch(u.push({lookAround:e.LOOKAROUND_BEHIND,anchor:r}),s(t+1,r,n),u.pop(),n.phraseLength=0,n.state){case e.EMPTY:case e.MATCH:n.state=e.EMPTY;break;case e.NOMATCH:n.state=e.NOMATCH;break;default:throw new Error(`opBKA: invalid state ${n.state}`)}},H=function(t,r,n){switch(u.push({lookAround:e.LOOKAROUND_BEHIND,anchor:r}),s(t+1,r,n),u.pop(),n.phraseLength=0,n.state){case e.EMPTY:case e.MATCH:n.state=e.NOMATCH;break;case e.NOMATCH:n.state=e.EMPTY;break;default:throw new Error(`opBKN: invalid state ${n.state}`)}};s=function(t,r,n){let o=!0;const a=l[t];if(p+=1,p>A)throw new Error(`parser: maximum number of node hits exceeded: ${A}`);if(d+=1,d>f&&(f=d,f>E))throw new Error(`parser: maximum parse tree depth exceeded: ${E}`);if(n.refresh(),null!==i.trace){const e=I();i.trace.down(a,n.state,r,n.phraseLength,e.anchor,e.lookAround)}if(u[u.length-1].lookAround===e.LOOKAROUND_BEHIND)switch(a.type){case e.ALT:C(t,r,n);break;case e.CAT:!function(t,r,n){let o,a,c,u;const h=l[t],d=n.uFrame.length(),f=n.pFrame.length();i.ast&&(a=i.ast.getLength()),o=!0,c=r,u=0;for(let t=h.children.length-1;t>=0;t-=1)if(s(h.children[t],c,n),c-=n.phraseLength,u+=n.phraseLength,n.state===e.NOMATCH){o=!1;break}o?(n.state=0===u?e.EMPTY:e.MATCH,n.phraseLength=u):(n.state=e.NOMATCH,n.phraseLength=0,n.uFrame.pop(d),n.pFrame.pop(f),i.ast&&i.ast.setLength(a))}(t,r,n);break;case e.REP:!function(t,r,n){let o,a,c,u;const h=l[t];a=r,c=0,u=0;const d=n.uFrame.length(),f=n.pFrame.length();for(i.ast&&(o=i.ast.getLength());!(a<=0)&&(s(t+1,a,n),n.state!==e.NOMATCH)&&n.state!==e.EMPTY&&(u+=1,c+=n.phraseLength,a-=n.phraseLength,u!==h.max););n.state===e.EMPTY||u>=h.min?(n.state=0===c?e.EMPTY:e.MATCH,n.phraseLength=c):(n.state=e.NOMATCH,n.phraseLength=0,n.uFrame.pop(d),n.pFrame.pop(f),i.ast&&i.ast.setLength(o))}(t,r,n);break;case e.RNM:M(t,r,n);break;case e.UDT:D(t,r,n);break;case e.AND:B(t,r,n);break;case e.NOT:L(t,r,n);break;case e.TRG:!function(t,r,n){const i=l[t];if(n.state=e.NOMATCH,n.phraseLength=0,r>0){const t=h[r-1];i.min<=t&&t<=i.max&&(n.state=e.MATCH,n.phraseLength=1)}}(t,r,n);break;case e.TBS:!function(t,r,n){let i;const s=l[t];n.state=e.NOMATCH;const o=s.string.length,a=r-o;if(a>=0){for(i=0;i<o;i+=1)if(h[a+i]!==s.string[i])return;n.state=e.MATCH,n.phraseLength=o}}(t,r,n);break;case e.TLS:!function(t,r,n){let i;const s=l[t];n.state=e.NOMATCH;const o=s.string.length;if(0===o)return void(n.state=e.EMPTY);const a=r-o;if(a>=0){for(let e=0;e<o;e+=1)if(i=h[a+e],i>=65&&i<=90&&(i+=32),i!==s.string[e])return;n.state=e.MATCH,n.phraseLength=o}}(t,r,n);break;case e.BKR:!function(t,r,n){let i,s,o,a;const c=l[t];n.state=e.NOMATCH,n.phraseLength=0,a=c.index<y.length?y[c.index].lower:v[c.index-y.length].lower;const u=c.bkrMode===e.BKR_MODE_PM?n.pFrame.getPhrase(a):n.uFrame.getPhrase(a),d=c.bkrCase===e.BKR_MODE_CI;if(null===u)return;const f=u.phraseIndex,p=u.phraseLength;if(0===p)return n.state=e.EMPTY,void(n.phraseLength=0);const m=r-p;if(m>=0){if(d){for(i=0;i<p;i+=1)if(s=h[m+i],o=h[f+i],s>=65&&s<=90&&(s+=32),o>=65&&o<=90&&(o+=32),s!==o)return;n.state=e.MATCH,n.phraseLength=p}else for(i=0;i<p;i+=1)if(s=h[m+i],o=h[f+i],s!==o)return;n.state=e.MATCH,n.phraseLength=p}}(t,r,n);break;case e.BKA:$(t,r,n);break;case e.BKN:H(t,r,n);break;case e.ABG:U(0,r,n);break;case e.AEN:F(0,r,n);break;default:o=!1}else switch(a.type){case e.ALT:C(t,r,n);break;case e.CAT:!function(t,r,n){let o,a,c,u;const h=l[t],d=n.uFrame.length(),f=n.pFrame.length();i.ast&&(a=i.ast.getLength()),o=!0,c=r,u=0;for(let t=0;t<h.children.length;t+=1){if(s(h.children[t],c,n),n.state===e.NOMATCH){o=!1;break}c+=n.phraseLength,u+=n.phraseLength}o?(n.state=0===u?e.EMPTY:e.MATCH,n.phraseLength=u):(n.state=e.NOMATCH,n.phraseLength=0,n.uFrame.pop(d),n.pFrame.pop(f),i.ast&&i.ast.setLength(a))}(t,r,n);break;case e.REP:!function(t,r,n){let o,a,u,h;const d=l[t];if(0===d.max)return n.state=e.EMPTY,void(n.phraseLength=0);a=r,u=0,h=0;const f=n.uFrame.length(),p=n.pFrame.length();for(i.ast&&(o=i.ast.getLength());!(a>=c)&&(s(t+1,a,n),n.state!==e.NOMATCH)&&n.state!==e.EMPTY&&(h+=1,u+=n.phraseLength,a+=n.phraseLength,h!==d.max););n.state===e.EMPTY||h>=d.min?(n.state=0===u?e.EMPTY:e.MATCH,n.phraseLength=u):(n.state=e.NOMATCH,n.phraseLength=0,n.uFrame.pop(f),n.pFrame.pop(p),i.ast&&i.ast.setLength(o))}(t,r,n);break;case e.RNM:M(t,r,n);break;case e.UDT:D(t,r,n);break;case e.AND:B(t,r,n);break;case e.NOT:L(t,r,n);break;case e.TRG:!function(t,r,n){const i=l[t];n.state=e.NOMATCH,r<c&&i.min<=h[r]&&h[r]<=i.max&&(n.state=e.MATCH,n.phraseLength=1)}(t,r,n);break;case e.TBS:!function(t,r,n){let i;const s=l[t],o=s.string.length;if(n.state=e.NOMATCH,r+o<=c){for(i=0;i<o;i+=1)if(h[r+i]!==s.string[i])return;n.state=e.MATCH,n.phraseLength=o}}(t,r,n);break;case e.TLS:!function(t,r,n){let i,s;const o=l[t];n.state=e.NOMATCH;const a=o.string.length;if(0!==a){if(r+a<=c){for(i=0;i<a;i+=1)if(s=h[r+i],s>=65&&s<=90&&(s+=32),s!==o.string[i])return;n.state=e.MATCH,n.phraseLength=a}}else n.state=e.EMPTY}(t,r,n);break;case e.BKR:!function(t,r,n){let i,s,o,a;const u=l[t];n.state=e.NOMATCH,a=u.index<y.length?y[u.index].lower:v[u.index-y.length].lower;const d=u.bkrMode===e.BKR_MODE_PM?n.pFrame.getPhrase(a):n.uFrame.getPhrase(a),f=u.bkrCase===e.BKR_MODE_CI;if(null===d)return;const p=d.phraseIndex,m=d.phraseLength;if(0!==m){if(r+m<=c){if(f){for(i=0;i<m;i+=1)if(s=h[r+i],o=h[p+i],s>=65&&s<=90&&(s+=32),o>=65&&o<=90&&(o+=32),s!==o)return;n.state=e.MATCH,n.phraseLength=m}else for(i=0;i<m;i+=1)if(s=h[r+i],o=h[p+i],s!==o)return;n.state=e.MATCH,n.phraseLength=m}}else n.state=e.EMPTY}(t,r,n);break;case e.BKA:$(t,r,n);break;case e.BKN:H(t,r,n);break;case e.ABG:U(0,r,n);break;case e.AEN:F(0,r,n);break;default:o=!1}if(!N()&&r+n.phraseLength>w&&(w=r+n.phraseLength),null!==i.stats&&i.stats.collect(a,n),null!==i.trace){const e=I();i.trace.up(a,n.state,r,n.phraseLength,e.anchor,e.lookAround)}return d-=1,o}}},7857(e,t,r){e.exports=function(){const e=r(5298),t=r(1174),n=r(2475);let i=[],s=[];const o=[];let a;const c=[],u=[];this.statsObject="statsObject";const l=function(e,t){return e.lower<t.lower?-1:e.lower>t.lower?1:0},h=function(e,t){return e.total<t.total?1:e.total>t.total?-1:l(e,t)},d=function(e,t){return e.index<t.index?-1:e.index>t.index?1:0},f=function(){this.empty=0,this.match=0,this.nomatch=0,this.total=0},p=function(t,r){switch(t.total+=1,r){case e.EMPTY:t.empty+=1;break;case e.MATCH:t.match+=1;break;case e.NOMATCH:t.nomatch+=1;break;default:throw new Error(`stats.js: collect(): incStat(): unrecognized state: ${r}`)}},m=function(e,t){let r="";return r+="<tr>",r+=`<td class="${n.CLASS_ACTIVE}">${e}</td>`,r+=`<td class="${n.CLASS_EMPTY}">${t.empty}</td>`,r+=`<td class="${n.CLASS_MATCH}">${t.match}</td>`,r+=`<td class="${n.CLASS_NOMATCH}">${t.nomatch}</td>`,r+=`<td class="${n.CLASS_ACTIVE}">${t.total}</td>`,r+="</tr>\n",r},g=function(){let t="";return t+=m("ALT",o[e.ALT]),t+=m("CAT",o[e.CAT]),t+=m("REP",o[e.REP]),t+=m("RNM",o[e.RNM]),t+=m("TRG",o[e.TRG]),t+=m("TBS",o[e.TBS]),t+=m("TLS",o[e.TLS]),t+=m("UDT",o[e.UDT]),t+=m("AND",o[e.AND]),t+=m("NOT",o[e.NOT]),t+=m("BKR",o[e.BKR]),t+=m("BKA",o[e.BKA]),t+=m("BKN",o[e.BKN]),t+=m("ABG",o[e.ABG]),t+=m("AEN",o[e.AEN]),t+=m("totals",a),t},y=function(){let e="";e+="<tr><th></th><th></th><th></th><th></th><th></th></tr>\n",e+="<tr><th>rules</th><th></th><th></th><th></th><th></th></tr>\n";for(let t=0;t<i.length;t+=1)c[t].total>0&&(e+="<tr>",e+=`<td class="${n.CLASS_ACTIVE}">${c[t].name}</td>`,e+=`<td class="${n.CLASS_EMPTY}">${c[t].empty}</td>`,e+=`<td class="${n.CLASS_MATCH}">${c[t].match}</td>`,e+=`<td class="${n.CLASS_NOMATCH}">${c[t].nomatch}</td>`,e+=`<td class="${n.CLASS_ACTIVE}">${c[t].total}</td>`,e+="</tr>\n");if(s.length>0){e+="<tr><th></th><th></th><th></th><th></th><th></th></tr>\n",e+="<tr><th>udts</th><th></th><th></th><th></th><th></th></tr>\n";for(let t=0;t<s.length;t+=1)u[t].total>0&&(e+="<tr>",e+=`<td class="${n.CLASS_ACTIVE}">${u[t].name}</td>`,e+=`<td class="${n.CLASS_EMPTY}">${u[t].empty}</td>`,e+=`<td class="${n.CLASS_MATCH}">${u[t].match}</td>`,e+=`<td class="${n.CLASS_NOMATCH}">${u[t].nomatch}</td>`,e+=`<td class="${n.CLASS_ACTIVE}">${u[t].total}</td>`,e+="</tr>\n")}return e};this.validate=function(e){let t=!1;return"string"==typeof e&&"stats"===e&&(t=!0),t},this.init=function(t,r){i=t,s=r,function(){o.length=0,a=new f,o[e.ALT]=new f,o[e.CAT]=new f,o[e.REP]=new f,o[e.RNM]=new f,o[e.TRG]=new f,o[e.TBS]=new f,o[e.TLS]=new f,o[e.UDT]=new f,o[e.AND]=new f,o[e.NOT]=new f,o[e.BKR]=new f,o[e.BKA]=new f,o[e.BKN]=new f,o[e.ABG]=new f,o[e.AEN]=new f,c.length=0;for(let e=0;e<i.length;e+=1)c.push({empty:0,match:0,nomatch:0,total:0,name:i[e].name,lower:i[e].lower,index:i[e].index});if(s.length>0){u.length=0;for(let e=0;e<s.length;e+=1)u.push({empty:0,match:0,nomatch:0,total:0,name:s[e].name,lower:s[e].lower,index:s[e].index})}}()},this.collect=function(t,r){p(a,r.state,r.phraseLength),p(o[t.type],r.state,r.phraseLength),t.type===e.RNM&&p(c[t.index],r.state,r.phraseLength),t.type===e.UDT&&p(u[t.index],r.state,r.phraseLength)},this.toHtml=function(e,t){let r="";for(r+=`<table class="${n.CLASS_STATS}">\n`,"string"==typeof t&&(r+=`<caption>${t}</caption>\n`),r+=`<tr><th class="${n.CLASS_ACTIVE}">ops</th>\n`,r+=`<th class="${n.CLASS_EMPTY}">EMPTY</th>\n`,r+=`<th class="${n.CLASS_MATCH}">MATCH</th>\n`,r+=`<th class="${n.CLASS_NOMATCH}">NOMATCH</th>\n`,r+=`<th class="${n.CLASS_ACTIVE}">totals</th></tr>\n`;;){if(void 0===e){r+=g();break}if(null===e){r+=g();break}if("ops"===e){r+=g();break}if("index"===e){c.sort(d),u.length>0&&u.sort(d),r+=g(),r+=y();break}if("hits"===e){c.sort(h),u.length>0&&u.sort(d),r+=g(),r+=y();break}if("alpha"===e){c.sort(l),u.length>0&&u.sort(l),r+=g(),r+=y();break}break}return r+="</table>\n",r},this.toHtmlPage=function(e,r,n){return t.htmlToPage(this.toHtml(e,r),n)}}},2475(e){e.exports={CLASS_MONOSPACE:"apg-mono",CLASS_ACTIVE:"apg-active",CLASS_EMPTY:"apg-empty",CLASS_MATCH:"apg-match",CLASS_NOMATCH:"apg-nomatch",CLASS_LOOKAHEAD:"apg-lh-match",CLASS_LOOKBEHIND:"apg-lb-match",CLASS_REMAINDER:"apg-remainder",CLASS_CTRLCHAR:"apg-ctrl-char",CLASS_LINEEND:"apg-line-end",CLASS_ERROR:"apg-error",CLASS_PHRASE:"apg-phrase",CLASS_EMPTYPHRASE:"apg-empty-phrase",CLASS_STATE:"apg-state",CLASS_STATS:"apg-stats",CLASS_TRACE:"apg-trace",CLASS_GRAMMAR:"apg-grammar",CLASS_RULES:"apg-rules",CLASS_RULESLINK:"apg-rules-link",CLASS_ATTRIBUTES:"apg-attrs"}},8127(e,t,r){e.exports=function(){const e=r(1174),t=r(2475),n=new(r(6660)),i=r(5298),s="trace.js: ",o=this,a=16,c=80,u=[];let l=5e3,h=-1,d=0,f=0;const p=[];let m=null,g=null,y=null;const v=[],b=[],w=`<span class="${t.CLASS_LINEEND}">•</span>`,E=`<span class="${t.CLASS_LINEEND}">…</span>`,A=`<span class="${t.CLASS_EMPTY}">𝜺</span>`;this.traceObject="traceObject",this.filter={operators:[],rules:[]},this.setMaxRecords=function(e,t){h=-1,"number"==typeof e&&e>0?(l=Math.ceil(e),"number"==typeof t&&(h=Math.floor(t),h<0&&(h=-1))):l=0},this.getMaxRecords=function(){return l},this.getLastRecord=function(){return h},this.init=function(e,t,r){u.length=0,p.length=0,d=0,f=0,m=r,g=e,y=t,function(){const e=function(e){v[i.ALT]=e,v[i.CAT]=e,v[i.REP]=e,v[i.TLS]=e,v[i.TBS]=e,v[i.TRG]=e,v[i.AND]=e,v[i.NOT]=e,v[i.BKR]=e,v[i.BKA]=e,v[i.BKN]=e,v[i.ABG]=e,v[i.AEN]=e};let t=0;for(const e in o.filter.operators)t+=1;if(0!==t){for(const t in o.filter.operators){const r=t.toUpperCase();if("<ALL>"===r)return void e(!0);if("<NONE>"===r)return void e(!1)}e(!1);for(const e in o.filter.operators){const t=e.toUpperCase();if("ALT"===t)v[i.ALT]=!0===o.filter.operators[e];else if("CAT"===t)v[i.CAT]=!0===o.filter.operators[e];else if("REP"===t)v[i.REP]=!0===o.filter.operators[e];else if("AND"===t)v[i.AND]=!0===o.filter.operators[e];else if("NOT"===t)v[i.NOT]=!0===o.filter.operators[e];else if("TLS"===t)v[i.TLS]=!0===o.filter.operators[e];else if("TBS"===t)v[i.TBS]=!0===o.filter.operators[e];else if("TRG"===t)v[i.TRG]=!0===o.filter.operators[e];else if("BKR"===t)v[i.BKR]=!0===o.filter.operators[e];else if("BKA"===t)v[i.BKA]=!0===o.filter.operators[e];else if("BKN"===t)v[i.BKN]=!0===o.filter.operators[e];else if("ABG"===t)v[i.ABG]=!0===o.filter.operators[e];else{if("AEN"!==t)throw new Error(`${s}initOpratorFilter: '${e}' not a valid operator name. Must be <all>, <none>, alt, cat, rep, tls, tbs, trg, and, not, bkr, bka or bkn`);v[i.AEN]=!0===o.filter.operators[e]}}}else e(!1)}(),function(){const e=function(e){v[i.RNM]=e,v[i.UDT]=e;const t=g.length+y.length;b.length=0;for(let r=0;r<t;r+=1)b.push(e)};let t,r;const n=[];for(r=0;r<g.length;r+=1)n.push(g[r].lower);for(r=0;r<y.length;r+=1)n.push(y[r].lower);b.length=0,t=0;for(const e in o.filter.rules)t+=1;if(0!==t){for(const t in o.filter.rules){const r=t.toLowerCase();if("<all>"===r)return void e(!0);if("<none>"===r)return void e(!1)}e(!1),v[i.RNM]=!0,v[i.UDT]=!0;for(const e in o.filter.rules){const t=e.toLowerCase();if(r=n.indexOf(t),r<0)throw new Error(`${s}initRuleFilter: '${e}' not a valid rule or udt name`);b[r]=!0===o.filter.rules[e]}}else e(!0)}(),n.init(l)};const k=function(e){let t=!1;return t=e.type===i.RNM?!(!v[e.type]||!b[e.index]):e.type===i.UDT?!(!v[e.type]||!b[g.length+e.index]):v[e.type],t},x=function(e){return-1===h||e<=h};this.down=function(e,t,r,i,s,o){x(d)&&k(e)&&(p.push(d),u[n.increment()]={dirUp:!1,depth:f,thisLine:d,thatLine:void 0,opcode:e,state:t,phraseIndex:r,phraseLength:i,lookAnchor:s,lookAround:o},d+=1,f+=1)},this.up=function(e,t,r,i,s,o){if(x(d)&&k(e)){const a=d,c=p.pop(),l=n.getListIndex(c);-1!==l&&(u[l].thatLine=a),f-=1,u[n.increment()]={dirUp:!0,depth:f,thisLine:a,thatLine:c,opcode:e,state:t,phraseIndex:r,phraseLength:i,lookAnchor:s,lookAround:o},d+=1}},this.toTree=function(t){const r=function(){function t(t,r){let n,s,o;if(r)switch(t.op={id:r.type,name:e.opcodeToString(r.type)},t.opData=void 0,r.type){case i.RNM:t.opData=g[r.index].name;break;case i.UDT:t.opData=y[r.index].name;break;case i.BKR:n=r.index<g.length?g[r.index].name:y[r.index-g.length].name,s=r.bkrCase===i.BKR_MODE_CI?"%i":"%s",o=r.bkrMode===i.BKR_MODE_UM?"%u":"%p",t.opData=`\\\\${s}${o}${n}`;break;case i.TLS:t.opData=[];for(let e=0;e<r.string.length;e+=1)t.opData.push(r.string[e]);break;case i.TBS:t.opData=[];for(let e=0;e<r.string.length;e+=1)t.opData.push(r.string[e]);break;case i.TRG:case i.REP:t.opData=[r.min,r.max];break;default:throw new Error("unrecognized opcode")}else t.op={id:void 0,name:void 0},t.opData=void 0}function r(e,t,r){return e===i.MATCH?{index:t,length:r}:e===i.NOMATCH||e===i.EMPTY?{index:t,length:0}:null}let s=-1;function o(n,i,o){const a={id:s++,branch:-1,parent:n,up:!1,down:!1,depth:o,children:[]};return i?(a.down=!0,a.state={id:i.state,name:e.stateToString(i.state)},a.phrase=null,t(a,i.opcode)):(a.state={id:void 0,name:void 0},a.phrase=r(),t(a,void 0)),a}function a(n,i){i&&(n.up=!0,n.state={id:i.state,name:e.stateToString(i.state)},n.phrase=r(i.state,i.phraseIndex,i.phraseLength),n.down||t(n,i.opcode))}let c=0,l=-1,h=1;const d=[];let p,v,b,w,E=!0;const A=o(null,null,-1);for(d.push(A),v=A,n.forEach(e=>{if(w=u[e],E&&(E=!1,w.depth>0)){const e=w.dirUp?w.depth+1:w.depth;for(let t=0;t<e;t+=1)b=v,v=o(v,null,t),d.push(v),b.children.push(v)}w.dirUp?(v=d.pop(),a(v,w),v=d[d.length-1]):(b=v,v=o(v,w,w.depth),d.push(v),b.children.push(v))});d.length>1;)v=d.pop(),a(v,null);if(0===A.children.length)throw new Error("trace.toTree(): parse tree has no nodes");if(0===d.length)throw new Error("trace.toTree(): integrity check: dummy root node disappeared?");p=A.children[0];let k=p;for(;p&&!p.down&&!p.up;)k=p,p=p.children[0];p=k,p.leftMost=!0,p.rightMost=!0,function e(t){if(l+=1,t.branch=h,l>f&&(f=l),0===t.children.length)c+=1;else for(let r=0;r<t.children.length;r+=1)r>0&&(h+=1),t.children[r].leftMost=!1,t.children[r].rightMost=!1,t.leftMost&&(t.children[r].leftMost=0===r),t.rightMost&&(t.children[r].rightMost=r===t.children.length-1),e(t.children[r]);l-=1}(p),p.branch=0;const x={string:[]};for(let e=0;e<m.length;e+=1)x.string[e]=m[e];x.rules=[];for(let e=0;e<g.length;e+=1)x.rules[e]=g[e].name;x.udts=[];for(let e=0;e<y.length;e+=1)x.udts[e]=y[e].name;let _;return x.id={},x.id.ALT={id:i.ALT,name:"ALT"},x.id.CAT={id:i.CAT,name:"CAT"},x.id.REP={id:i.REP,name:"REP"},x.id.RNM={id:i.RNM,name:"RNM"},x.id.TLS={id:i.TLS,name:"TLS"},x.id.TBS={id:i.TBS,name:"TBS"},x.id.TRG={id:i.TRG,name:"TRG"},x.id.UDT={id:i.UDT,name:"UDT"},x.id.AND={id:i.AND,name:"AND"},x.id.NOT={id:i.NOT,name:"NOT"},x.id.BKR={id:i.BKR,name:"BKR"},x.id.BKA={id:i.BKA,name:"BKA"},x.id.BKN={id:i.BKN,name:"BKN"},x.id.ABG={id:i.ABG,name:"ABG"},x.id.AEN={id:i.AEN,name:"AEN"},x.id.ACTIVE={id:i.ACTIVE,name:"ACTIVE"},x.id.MATCH={id:i.MATCH,name:"MATCH"},x.id.EMPTY={id:i.EMPTY,name:"EMPTY"},x.id.NOMATCH={id:i.NOMATCH,name:"NOMATCH"},x.treeDepth=f,x.leafNodes=c,_=p.down?p.up?"none":"right":p.up?"left":"both",x.branchesIncomplete=_,x.tree=function e(t,r){let n;const i={};if(i.id=t.id,i.branch=t.branch,i.leftMost=t.leftMost,i.rightMost=t.rightMost,n=t.state.name?t.state.name:"ACTIVE",i.state={id:t.state.id,name:n},n=t.op.name?t.op.name:"?",i.op={id:t.op.id,name:n},"string"==typeof t.opData)i.opData=t.opData;else if(Array.isArray(t.opData)){i.opData=[];for(let e=0;e<t.opData.length;e+=1)i.opData[e]=t.opData[e]}else i.opData=void 0;t.phrase?i.phrase={index:t.phrase.index,length:t.phrase.length}:i.phrase=null,i.depth=t.depth,i.children=[];for(let n=0;n<t.children.length;n+=1)t.children.length,i.children[n]=e(t.children[n],r);return i}(p,p.depth),x}();return t?JSON.stringify(r):r},this.toHtmlPage=function(t,r,n){return e.htmlToPage(this.toHtml(t,r),n)},this.indent=function(e){let t="";for(let r=0;r<e;r+=1)t+=".";return t};const _=function(t,r,n,i,s){if(0===i)return"";let o="";const c=s?",":"";switch(t){case a:o=c+e.charsToHex(r,n,i);break;case 10:if(s)return`,${e.charsToDec(r,n,i)}`;o=c+e.charsToDec(r,n,i);break;case 32:o=e.charsToUnicode(r,n,i);break;default:o=e.charsToAsciiHtml(r,n,i)}return o},T=function(e,r,n,s,o,a){let u,l,h,d,f="",p=w;const m=`<span class="${t.CLASS_REMAINDER}">`,g="</span>";let y=!1;switch(n){case i.EMPTY:f+=A;case i.NOMATCH:case i.ACTIVE:u=s,l=0,h=s,d=r.length-h;break;case i.MATCH:u=s,l=o,h=s+l,d=r.length-h;break;default:throw new Error("unrecognized state")}return p=w,l>c?(l=c,p=E,d=0):l+d>c&&(p=E,d=c-l),l>0&&(f+=a,f+=_(e,r,u,l,y),f+=g,y=!0),d>0&&(f+=m,f+=_(e,r,h,d,y),f+=g),f+p};this.toHtml=function(r,l){let h=8;if("string"==typeof r&&r.length>=3){const e=r.toLowerCase().slice(0,3);"hex"===e?h=a:"dec"===e?h=10:"uni"===e&&(h=32)}let d="";return d+=function(e,r){let n;switch(e){case a:n="hexadecimal";break;case 10:n="decimal";break;case 8:n="ASCII";break;case 32:n="UNICODE";break;default:throw new Error(`${s}htmlHeader: unrecognized mode: ${e}`)}let i="";return i+=`<p>display mode: ${n}</p>\n`,i+=`<table class="${t.CLASS_TRACE}">\n`,"string"==typeof r&&(i+=`<caption>${r}</caption>`),i}(h,l),d+=function(r){if(null===g)return"";let s,l,h,d,f,p,v="";return v+="<tr><th>(a)</th><th>(b)</th><th>(c)</th><th>(d)</th><th>(e)</th><th>(f)</th>",v+="<th>operator</th><th>phrase</th></tr>\n",n.forEach(n=>{const b=u[n];switch(s=b.thisLine,l=void 0!==b.thatLine?b.thatLine:"--",h=!1,d=!1,f=!1,b.lookAround===i.LOOKAROUND_AHEAD&&(h=!0,f=!0,p=b.lookAnchor),b.opcode.type!==i.AND&&b.opcode.type!==i.NOT||(h=!0,f=!0,p=b.phraseIndex),b.lookAround===i.LOOKAROUND_BEHIND&&(d=!0,f=!0,p=b.lookAnchor),b.opcode.type!==i.BKA&&b.opcode.type!==i.BKN||(d=!0,f=!0,p=b.phraseIndex),v+="<tr>",v+=`<td>${s}</td><td>${l}</td>`,v+=`<td>${b.phraseIndex}</td>`,v+=`<td>${b.phraseLength}</td>`,v+=`<td>${b.depth}</td>`,v+="<td>",b.state){case i.ACTIVE:v+=`<span class="${t.CLASS_ACTIVE}">↓ </span>`;break;case i.MATCH:v+=`<span class="${t.CLASS_MATCH}">↑M</span>`;break;case i.NOMATCH:v+=`<span class="${t.CLASS_NOMATCH}">↑N</span>`;break;case i.EMPTY:v+=`<span class="${t.CLASS_EMPTY}">↑E</span>`;break;default:v+=`<span class="${t.CLASS_ACTIVE}">--</span>`}if(v+="</td>",v+="<td>",v+=o.indent(b.depth),h?v+=`<span class="${t.CLASS_LOOKAHEAD}">`:d&&(v+=`<span class="${t.CLASS_LOOKBEHIND}">`),v+=e.opcodeToString(b.opcode.type),b.opcode.type===i.RNM&&(v+=`(${g[b.opcode.index].name}) `),b.opcode.type===i.BKR){const e=b.opcode.bkrCase===i.BKR_MODE_CI?"%i":"%s",t=b.opcode.bkrMode===i.BKR_MODE_UM?"%u":"%p";v+=`(\\${e}${t}${g[b.opcode.index].name}) `}b.opcode.type===i.UDT&&(v+=`(${y[b.opcode.index].name}) `),b.opcode.type===i.TRG&&(v+=`(${function(e,t){let r="";if(t.type===i.TRG)if(e===a||32===e){let n=t.min.toString(16).toUpperCase();n.length%2!=0&&(n=`0${n}`),r+=e===a?"%x":"U+",r+=n,n=t.max.toString(16).toUpperCase(),n.length%2!=0&&(n=`0${n}`),r+=`–${n}`}else r=`%d${t.min.toString(10)}–${t.max.toString(10)}`;return r}(r,b.opcode)}) `),b.opcode.type===i.TBS&&(v+=`(${function(e,t){let r="";if(t.type===i.TBS){const n=Math.min(t.string.length,10);if(e===a||32===e){r+=e===a?"%x":"U+";for(let e=0;e<n;e+=1){let n;e>0&&(r+="."),n=t.string[e].toString(16).toUpperCase(),n.length%2!=0&&(n=`0${n}`),r+=n}}else{r="%d";for(let e=0;e<n;e+=1)e>0&&(r+="."),r+=t.string[e].toString(10)}n<t.string.length&&(r+=E)}return r}(r,b.opcode)}) `),b.opcode.type===i.TLS&&(v+=`(${function(t,r){let n="";if(r.type===i.TLS){const i=Math.min(r.string.length,5);if(t===a||10===t){let e,s,o;t===a?(n="%x",o=16):(n="%d",o=10);for(let t=0;t<i;t+=1)t>0&&(n+="."),s=r.string[t],s>=97&&s<=122?(e=s-32,n+=`${e.toString(o)}/${s.toString(o)}`.toUpperCase()):s>=65&&s<=90?(e=s,s+=32,n+=`${e.toString(o)}/${s.toString(o)}`.toUpperCase()):n+=s.toString(o).toUpperCase();i<r.string.length&&(n+=E)}else{n='"';for(let t=0;t<i;t+=1)n+=e.asciiChars[r.string[t]];i<r.string.length&&(n+=E),n+='"'}}return n}(r,b.opcode)}) `),b.opcode.type===i.REP&&(v+=`(${function(e,t){let r="";if(t.type===i.REP)if(e===a){let e=t.min.toString(16).toUpperCase();e.length%2!=0&&(e=`0${e}`),r=`x${e}`,t.max<1/0?(e=t.max.toString(16).toUpperCase(),e.length%2!=0&&(e=`0${e}`)):e="inf",r+=`–${e}`}else r=t.max<1/0?`${t.min.toString(10)}–${t.max.toString(10)}`:`${t.min.toString(10)}–inf`;return r}(r,b.opcode)}) `),f&&(v+="</span>"),v+="</td>",v+="<td>",v+=d?function(e,r,n,s,o,a){let u,l,h,d,f="",p=w;const m=`<span class="${t.CLASS_LOOKBEHIND}">`,g=`<span class="${t.CLASS_REMAINDER}">`,y="</span>";let v=!1;switch(n){case i.EMPTY:f+=A;case i.NOMATCH:case i.MATCH:case i.ACTIVE:u=s-o,l=a-u,h=a,d=r.length-h;break;default:throw new Error("unrecognized state")}return p=w,l>c?(l=c,p=E,d=0):l+d>c&&(p=E,d=c-l),l>0&&(f+=m,f+=_(e,r,u,l,v),f+=y,v=!0),d>0&&(f+=g,f+=_(e,r,h,d,v),f+=y),f+p}(r,m,b.state,b.phraseIndex,b.phraseLength,p):h?function(e,r,n,i,s){const o=`<span class="${t.CLASS_LOOKAHEAD}">`;return T(e,r,n,i,s,o)}(r,m,b.state,b.phraseIndex,b.phraseLength):function(e,r,n,i,s){const o=`<span class="${t.CLASS_MATCH}">`;return T(e,r,n,i,s,o)}(r,m,b.state,b.phraseIndex,b.phraseLength),v+="</td></tr>\n"}),v+="<tr><th>(a)</th><th>(b)</th><th>(c)</th><th>(d)</th><th>(e)</th><th>(f)</th>",v+="<th>operator</th><th>phrase</th></tr>\n",v+="</table>\n",v}(h),d+=function(){let e="";return e+="</table>\n",e+=`<p class="${t.CLASS_MONOSPACE}">legend:<br>\n`,e+="(a) - line number<br>\n",e+="(b) - matching line number<br>\n",e+="(c) - phrase offset<br>\n",e+="(d) - phrase length<br>\n",e+="(e) - tree depth<br>\n",e+="(f) - operator state<br>\n",e+=` - <span class="${t.CLASS_ACTIVE}">↓</span> phrase opened<br>\n`,e+=` - <span class="${t.CLASS_MATCH}">↑M</span> phrase matched<br>\n`,e+=` - <span class="${t.CLASS_EMPTY}">↑E</span> empty phrase matched<br>\n`,e+=` - <span class="${t.CLASS_NOMATCH}">↑N</span> phrase not matched<br>\n`,e+="operator - ALT, CAT, REP, RNM, TRG, TLS, TBS<sup>†</sup>, UDT, AND, NOT, BKA, BKN, BKR, ABG, AEN<sup>‡</sup><br>\n",e+="phrase - up to 80 characters of the phrase being matched<br>\n",e+=` - <span class="${t.CLASS_MATCH}">matched characters</span><br>\n`,e+=` - <span class="${t.CLASS_LOOKAHEAD}">matched characters in look ahead mode</span><br>\n`,e+=` - <span class="${t.CLASS_LOOKBEHIND}">matched characters in look behind mode</span><br>\n`,e+=` - <span class="${t.CLASS_REMAINDER}">remainder characters(not yet examined by parser)</span><br>\n`,e+=` - <span class="${t.CLASS_CTRLCHAR}">control characters, TAB, LF, CR, etc. (ASCII mode only)</span><br>\n`,e+=` - ${A} empty string<br>\n`,e+=` - ${w} end of input string<br>\n`,e+=` - ${E} input string display truncated<br>\n`,e+="</p>\n",e+=`<p class="${t.CLASS_MONOSPACE}">\n`,e+="<sup>†</sup>original ABNF operators:<br>\n",e+="ALT - alternation<br>\n",e+="CAT - concatenation<br>\n",e+="REP - repetition<br>\n",e+="RNM - rule name<br>\n",e+="TRG - terminal range<br>\n",e+="TLS - terminal literal string (case insensitive)<br>\n",e+="TBS - terminal binary string (case sensitive)<br>\n",e+="<br>\n",e+="<sup>‡</sup>super set SABNF operators:<br>\n",e+="UDT - user-defined terminal<br>\n",e+="AND - positive look ahead<br>\n",e+="NOT - negative look ahead<br>\n",e+="BKA - positive look behind<br>\n",e+="BKN - negative look behind<br>\n",e+="BKR - back reference<br>\n",e+="ABG - anchor - begin of input string<br>\n",e+="AEN - anchor - end of input string<br>\n",e+="</p>\n",e}(),d}}},1174(e,t,r){const n=r(2475),i=r(240),s=r(9724),o=r(5298),a="utilities.js: ",c=function(e,t,r){let n,i=t;for(;;){if(e<=0){i=0,n=0;break}if("number"!=typeof i){i=0,n=e;break}if(i>=e){i=e,n=e;break}if("number"!=typeof r){n=e;break}if(n=i+r,n>e){n=e;break}break}return{beg:i,end:n}};function u(e){return!(e>=55296&&e<=57343||e>1114111)}t.htmlToPage=function(e,t){let r;if("string"!=typeof e)throw new Error(`${a}htmlToPage: input HTML is not a string`);r="string"!=typeof t?"htmlToPage":t;let n="";return n+="<!DOCTYPE html>\n",n+='<html lang="en">\n',n+="<head>\n",n+='<meta charset="utf-8">\n',n+=`<title>${r}</title>\n`,n+="<style>\n",n+=s(),n+="</style>\n",n+="</head>\n<body>\n",n+=`<p>${new Date}</p>\n`,n+=e,n+="</body>\n</html>\n",n},t.parserResultToHtml=function(e,t){let r,i,s=null;"string"==typeof t&&""!==t&&(s=t),r=!0===e.success?`<span class="${n.CLASS_MATCH}">true</span>`:`<span class="${n.CLASS_NOMATCH}">false</span>`,i=e.state===o.EMPTY?`<span class="${n.CLASS_EMPTY}">EMPTY</span>`:e.state===o.MATCH?`<span class="${n.CLASS_MATCH}">MATCH</span>`:e.state===o.NOMATCH?`<span class="${n.CLASS_NOMATCH}">NOMATCH</span>`:`<span class="${n.CLASS_NOMATCH}">unrecognized</span>`;let a="";return a+=`<table class="${n.CLASS_STATE}">\n`,s&&(a+=`<caption>${s}</caption>\n`),a+="<tr><th>state item</th><th>value</th><th>description</th></tr>\n",a+=`<tr><td>parser success</td><td>${r}</td>\n`,a+=`<td><span class="${n.CLASS_MATCH}">true</span> if the parse succeeded,\n`,a+=` <span class="${n.CLASS_NOMATCH}">false</span> otherwise`,a+="<br><i>NOTE: for success, entire string must be matched</i></td></tr>\n",a+=`<tr><td>parser state</td><td>${i}</td>\n`,a+=`<td><span class="${n.CLASS_EMPTY}">EMPTY</span>, `,a+=`<span class="${n.CLASS_MATCH}">MATCH</span> or \n`,a+=`<span class="${n.CLASS_NOMATCH}">NOMATCH</span></td></tr>\n`,a+=`<tr><td>string length</td><td>${e.length}</td><td>length of the input (sub)string</td></tr>\n`,a+=`<tr><td>matched length</td><td>${e.matched}</td><td>number of input string characters matched</td></tr>\n`,a+=`<tr><td>max matched</td><td>${e.maxMatched}</td><td>maximum number of input string characters matched</td></tr>\n`,a+=`<tr><td>max tree depth</td><td>${e.maxTreeDepth}</td><td>maximum depth of the parse tree reached</td></tr>\n`,a+=`<tr><td>node hits</td><td>${e.nodeHits}</td><td>number of parse tree node hits (opcode function calls)</td></tr>\n`,a+=`<tr><td>input length</td><td>${e.inputLength}</td><td>length of full input string</td></tr>\n`,a+=`<tr><td>sub-string begin</td><td>${e.subBegin}</td><td>sub-string first character index</td></tr>\n`,a+=`<tr><td>sub-string end</td><td>${e.subEnd}</td><td>sub-string end-of-string index</td></tr>\n`,a+=`<tr><td>sub-string length</td><td>${e.subLength}</td><td>sub-string length</td></tr>\n`,a+="</table>\n",a},t.charsToString=function(e,t,r){let n,s;if("number"==typeof t){if(t>=e.length)return"";n=t<0?0:t}else n=0;if("number"==typeof r){if(r<=0)return"";s=r>e.length-n?e.length:n+r}else s=e.length;return n<s?i.encode("UTF16LE",e.slice(n,s)).toString("utf16le"):""},t.stringToChars=function(e){return i.decode("STRING",e)},t.opcodeToString=function(e){let t="unknown";switch(e){case o.ALT:t="ALT";break;case o.CAT:t="CAT";break;case o.RNM:t="RNM";break;case o.UDT:t="UDT";break;case o.AND:t="AND";break;case o.NOT:t="NOT";break;case o.REP:t="REP";break;case o.TRG:t="TRG";break;case o.TBS:t="TBS";break;case o.TLS:t="TLS";break;case o.BKR:t="BKR";break;case o.BKA:t="BKA";break;case o.BKN:t="BKN";break;case o.ABG:t="ABG";break;case o.AEN:t="AEN";break;default:throw new Error("unrecognized opcode")}return t},t.stateToString=function(e){let t="unknown";switch(e){case o.ACTIVE:t="ACTIVE";break;case o.MATCH:t="MATCH";break;case o.EMPTY:t="EMPTY";break;case o.NOMATCH:t="NOMATCH";break;default:throw new Error("unrecognized state")}return t},t.asciiChars=["NUL","SOH","STX","ETX","EOT","ENQ","ACK","BEL","BS","TAB","LF","VT","FF","CR","SO","SI","DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB","CAN","EM","SUB","ESC","FS","GS","RS","US"," ","!",""","#","$","%","&","'","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","[","\","]","^","_","`","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","{","|","}","~","DEL"],t.charToHex=function(e){let t=e.toString(16).toUpperCase();switch(t.length){case 1:case 3:case 7:t=`0${t}`;break;case 2:case 6:t=`00${t}`;break;case 4:break;case 5:t=`000${t}`;break;default:throw new Error("unrecognized option")}return t},t.charsToDec=function(e,t,r){let n="";if(!Array.isArray(e))throw new Error(`${a}charsToDec: input must be an array of integers`);const i=c(e.length,t,r);if(i.end>i.beg){n+=e[i.beg];for(let t=i.beg+1;t<i.end;t+=1)n+=`,${e[t]}`}return n},t.charsToHex=function(e,r,n){let i="";if(!Array.isArray(e))throw new Error(`${a}charsToHex: input must be an array of integers`);const s=c(e.length,r,n);if(s.end>s.beg){i+=`\\x${t.charToHex(e[s.beg])}`;for(let r=s.beg+1;r<s.end;r+=1)i+=`,\\x${t.charToHex(e[r])}`}return i},t.charsToHtmlEntities=function(e,t,r){let n="";if(!Array.isArray(e))throw new Error(`${a}charsToHex: input must be an array of integers`);const i=c(e.length,t,r);if(i.end>i.beg)for(let t=i.beg;t<i.end;t+=1)n+=`&#x${e[t].toString(16)};`;return n},t.charsToUnicode=function(e,r,n){let i="";if(!Array.isArray(e))throw new Error(`${a}charsToUnicode: input must be an array of integers`);const s=c(e.length,r,n);if(s.end>s.beg)for(let r=s.beg;r<s.end;r+=1)u(e[r])?i+=`&#${e[r]};`:i+=` U+${t.charToHex(e[r])}`;return i},t.charsToJsUnicode=function(e,r,n){let i="";if(!Array.isArray(e))throw new Error(`${a}charsToJsUnicode: input must be an array of integers`);const s=c(e.length,r,n);if(s.end>s.beg){i+=`\\u${t.charToHex(e[s.beg])}`;for(let r=s.beg+1;r<s.end;r+=1)i+=`,\\u${t.charToHex(e[r])}`}return i},t.charsToAscii=function(e,r,n){let i="";if(!Array.isArray(e))throw new Error(`${a}charsToAscii: input must be an array of integers`);const s=c(e.length,r,n);for(let r=s.beg;r<s.end;r+=1){const n=e[r];i+=n>=32&&n<=126?String.fromCharCode(n):`\\x${t.charToHex(n)}`}return i},t.charsToAsciiHtml=function(e,r,i){if(!Array.isArray(e))throw new Error(`${a}charsToAsciiHtml: input must be an array of integers`);let s,o="";const u=c(e.length,r,i);for(let r=u.beg;r<u.end;r+=1)s=e[r],o+=s<32||127===s?`<span class="${n.CLASS_CTRLCHAR}">${t.asciiChars[s]}</span>`:s>127?`<span class="${n.CLASS_CTRLCHAR}">U+${t.charToHex(s)}</span>`:t.asciiChars[s];return o},t.stringToAsciiHtml=function(e){const t=i.decode("STRING",e);return this.charsToAsciiHtml(t)}},7991(e,t){"use strict";t.byteLength=function(e){var t=a(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,s=a(e),o=s[0],c=s[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,o,c)),l=0,h=c>0?o-4:o;for(r=0;r<h;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,u[l++]=255&t),1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,s=[],o=16383,a=0,c=n-i;a<c;a+=o)s.push(u(e,a,a+o>c?c:a+o));return 1===i?(t=e[n-1],s.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],s.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),s.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)r[o]=s[o],n[s.charCodeAt(o)]=o;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function c(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function u(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(c(n));return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},8993(e){"use strict";for(var t="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r={},n=0;n<32;n++){var i=t.charAt(n);if(void 0!==r[i])throw new TypeError(i+" is ambiguous");r[i]=n}function s(e){var t=e>>25;return(33554431&e)<<5^996825010&-(1&t)^642813549&-(t>>1&1)^513874426&-(t>>2&1)^1027748829&-(t>>3&1)^705979059&-(t>>4&1)}function o(e){for(var t=1,r=0;r<e.length;++r){var n=e.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+e+")";t=s(t)^n>>5}for(t=s(t),r=0;r<e.length;++r){var i=e.charCodeAt(r);t=s(t)^31&i}return t}function a(e,t){if(t=t||90,e.length<8)return e+" too short";if(e.length>t)return"Exceeds length limit";var n=e.toLowerCase(),i=e.toUpperCase();if(e!==n&&e!==i)return"Mixed-case string "+e;var a=(e=n).lastIndexOf("1");if(-1===a)return"No separator character for "+e;if(0===a)return"Missing prefix for "+e;var c=e.slice(0,a),u=e.slice(a+1);if(u.length<6)return"Data too short";var l=o(c);if("string"==typeof l)return l;for(var h=[],d=0;d<u.length;++d){var f=u.charAt(d),p=r[f];if(void 0===p)return"Unknown character "+f;l=s(l)^p,d+6>=u.length||h.push(p)}return 1!==l?"Invalid checksum for "+e:{prefix:c,words:h}}function c(e,t,r,n){for(var i=0,s=0,o=(1<<r)-1,a=[],c=0;c<e.length;++c)for(i=i<<t|e[c],s+=t;s>=r;)s-=r,a.push(i>>s&o);if(n)s>0&&a.push(i<<r-s&o);else{if(s>=t)return"Excess padding";if(i<<r-s&o)return"Non-zero padding"}return a}e.exports={decodeUnsafe:function(){var e=a.apply(null,arguments);if("object"==typeof e)return e},decode:function(e){var t=a.apply(null,arguments);if("object"==typeof t)return t;throw new Error(t)},encode:function(e,r,n){if(n=n||90,e.length+7+r.length>n)throw new TypeError("Exceeds length limit");var i=o(e=e.toLowerCase());if("string"==typeof i)throw new Error(i);for(var a=e+"1",c=0;c<r.length;++c){var u=r[c];if(u>>5)throw new Error("Non 5-bit word");i=s(i)^u,a+=t.charAt(u)}for(c=0;c<6;++c)i=s(i);for(i^=1,c=0;c<6;++c)a+=t.charAt(i>>5*(5-c)&31);return a},toWordsUnsafe:function(e){var t=c(e,8,5,!0);if(Array.isArray(t))return t},toWords:function(e){var t=c(e,8,5,!0);if(Array.isArray(t))return t;throw new Error(t)},fromWordsUnsafe:function(e){var t=c(e,5,8,!1);if(Array.isArray(t))return t},fromWords:function(e){var t=c(e,5,8,!1);if(Array.isArray(t))return t;throw new Error(t)}}},2823(e,t,r){!function(e,t){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function s(e,t,r){if(s.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var o;"object"==typeof e?e.exports=s:t.BN=s,s.BN=s,s.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:r(8379).Buffer}catch(e){}function a(e,t){var r=e.charCodeAt(t);return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+e)}function c(e,t,r){var n=a(e,r);return r-1>=t&&(n|=a(e,r-1)<<4),n}function u(e,t,r,i){for(var s=0,o=0,a=Math.min(e.length,r),c=t;c<a;c++){var u=e.charCodeAt(c)-48;s*=i,o=u>=49?u-49+10:u>=17?u-17+10:u,n(u>=0&&o<i,"Invalid character"),s+=o}return s}function l(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(s.isBN=function(e){return e instanceof s||null!==e&&"object"==typeof e&&e.constructor.wordSize===s.wordSize&&Array.isArray(e.words)},s.max=function(e,t){return e.cmp(t)>0?e:t},s.min=function(e,t){return e.cmp(t)<0?e:t},s.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i<e.length&&(16===t?this._parseHex(e,i,r):(this._parseBase(e,t,i),"le"===r&&this._initArray(this.toArray(),t,r)))},s.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},s.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var s,o,a=0;if("be"===r)for(i=e.length-1,s=0;i>=0;i-=3)o=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[s]|=o<<a&67108863,this.words[s+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);else if("le"===r)for(i=0,s=0;i<e.length;i+=3)o=e[i]|e[i+1]<<8|e[i+2]<<16,this.words[s]|=o<<a&67108863,this.words[s+1]=o>>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);return this._strip()},s.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n<this.length;n++)this.words[n]=0;var i,s=0,o=0;if("be"===r)for(n=e.length-1;n>=t;n-=2)i=c(e,t,n)<<s,this.words[o]|=67108863&i,s>=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;else for(n=(e.length-t)%2==0?t+1:t;n<e.length;n+=2)i=c(e,t,n)<<s,this.words[o]|=67108863&i,s>=18?(s-=18,o+=1,this.words[o]|=i>>>26):s+=8;this._strip()},s.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var s=e.length-r,o=s%n,a=Math.min(s,s-o)+r,c=0,l=r;l<a;l+=n)c=u(e,l,l+n,t),this.imuln(i),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==o){var h=1;for(c=u(e,l,e.length,t),l=0;l<o;l++)h*=t;this.imuln(h),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}this._strip()},s.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},s.prototype._move=function(e){l(e,this)},s.prototype.clone=function(){var e=new s(null);return this.copy(e),e},s.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},s.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=h}catch(e){s.prototype.inspect=h}else s.prototype.inspect=h;function h(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function m(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],s=0|t.words[0],o=i*s,a=67108863&o,c=o/67108864|0;r.words[0]=a;for(var u=1;u<n;u++){for(var l=c>>>26,h=67108863&c,d=Math.min(u,t.length-1),f=Math.max(0,u-e.length+1);f<=d;f++){var p=u-f|0;l+=(o=(i=0|e.words[p])*(s=0|t.words[f])+h)/67108864|0,h=67108863&o}r.words[u]=0|h,c=0|l}return 0!==c?r.words[u]=0|c:r.length--,r._strip()}s.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,s=0,o=0;o<this.length;o++){var a=this.words[o],c=(16777215&(a<<i|s)).toString(16);s=a>>>24-i&16777215,(i+=2)>=26&&(i-=26,o--),r=0!==s||o!==this.length-1?d[6-c.length]+c+r:c+r}for(0!==s&&(r=s.toString(16)+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var u=f[e],l=p[e];r="";var h=this.clone();for(h.negative=0;!h.isZero();){var m=h.modrn(l).toString(e);r=(h=h.idivn(l)).isZero()?m+r:d[u-m.length]+m+r}for(this.isZero()&&(r="0"+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(e,t){return this.toArrayLike(o,e,t)}),s.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},s.prototype.toArrayLike=function(e,t,r){this._strip();var i=this.byteLength(),s=r||Math.max(1,i);n(i<=s,"byte array longer than desired length"),n(s>0,"Requested array length <= 0");var o=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,s);return this["_toArrayLike"+("le"===t?"LE":"BE")](o,i),o},s.prototype._toArrayLikeLE=function(e,t){for(var r=0,n=0,i=0,s=0;i<this.length;i++){var o=this.words[i]<<s|n;e[r++]=255&o,r<e.length&&(e[r++]=o>>8&255),r<e.length&&(e[r++]=o>>16&255),6===s?(r<e.length&&(e[r++]=o>>24&255),n=0,s=0):(n=o>>>24,s+=2)}if(r<e.length)for(e[r++]=n;r<e.length;)e[r++]=0},s.prototype._toArrayLikeBE=function(e,t){for(var r=e.length-1,n=0,i=0,s=0;i<this.length;i++){var o=this.words[i]<<s|n;e[r--]=255&o,r>=0&&(e[r--]=o>>8&255),r>=0&&(e[r--]=o>>16&255),6===s?(r>=0&&(e[r--]=o>>24&255),n=0,s=0):(n=o>>>24,s+=2)}if(r>=0)for(e[r--]=n;r>=0;)e[r--]=0},Math.clz32?s.prototype._countBits=function(e){return 32-Math.clz32(e)}:s.prototype._countBits=function(e){var t=e,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},s.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 8191&t||(r+=13,t>>>=13),127&t||(r+=7,t>>>=7),15&t||(r+=4,t>>>=4),3&t||(r+=2,t>>>=2),1&t||r++,r},s.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var r=this._zeroBits(this.words[t]);if(e+=r,26!==r)break}return e},s.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},s.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},s.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},s.prototype.isNeg=function(){return 0!==this.negative},s.prototype.neg=function(){return this.clone().ineg()},s.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},s.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this._strip()},s.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},s.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},s.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},s.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;r<t.length;r++)this.words[r]=this.words[r]&e.words[r];return this.length=t.length,this._strip()},s.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},s.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},s.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},s.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;n<r.length;n++)this.words[n]=t.words[n]^r.words[n];if(this!==t)for(;n<t.length;n++)this.words[n]=t.words[n];return this.length=t.length,this._strip()},s.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},s.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},s.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},s.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i<t;i++)this.words[i]=67108863&~this.words[i];return r>0&&(this.words[i]=~this.words[i]&67108863>>26-r),this._strip()},s.prototype.notn=function(e){return this.clone().inotn(e)},s.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<<i:this.words[r]&~(1<<i),this._strip()},s.prototype.iadd=function(e){var t,r,n;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(r=this,n=e):(r=e,n=this);for(var i=0,s=0;s<n.length;s++)t=(0|r.words[s])+(0|n.words[s])+i,this.words[s]=67108863&t,i=t>>>26;for(;0!==i&&s<r.length;s++)t=(0|r.words[s])+i,this.words[s]=67108863&t,i=t>>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;s<r.length;s++)this.words[s]=r.words[s];return this},s.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},s.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var s=0,o=0;o<n.length;o++)s=(t=(0|r.words[o])-(0|n.words[o])+s)>>26,this.words[o]=67108863&t;for(;0!==s&&o<r.length;o++)s=(t=(0|r.words[o])+s)>>26,this.words[o]=67108863&t;if(0===s&&o<r.length&&r!==this)for(;o<r.length;o++)this.words[o]=r.words[o];return this.length=Math.max(this.length,o),r!==this&&(this.negative=1),this._strip()},s.prototype.sub=function(e){return this.clone().isub(e)};var g=function(e,t,r){var n,i,s,o=e.words,a=t.words,c=r.words,u=0,l=0|o[0],h=8191&l,d=l>>>13,f=0|o[1],p=8191&f,m=f>>>13,g=0|o[2],y=8191&g,v=g>>>13,b=0|o[3],w=8191&b,E=b>>>13,A=0|o[4],k=8191&A,x=A>>>13,_=0|o[5],T=8191&_,S=_>>>13,I=0|o[6],N=8191&I,R=I>>>13,O=0|o[7],C=8191&O,P=O>>>13,M=0|o[8],D=8191&M,B=M>>>13,L=0|o[9],U=8191&L,F=L>>>13,$=0|a[0],H=8191&$,K=$>>>13,q=0|a[1],j=8191&q,z=q>>>13,V=0|a[2],G=8191&V,W=V>>>13,J=0|a[3],Z=8191&J,Y=J>>>13,Q=0|a[4],X=8191&Q,ee=Q>>>13,te=0|a[5],re=8191&te,ne=te>>>13,ie=0|a[6],se=8191&ie,oe=ie>>>13,ae=0|a[7],ce=8191&ae,ue=ae>>>13,le=0|a[8],he=8191&le,de=le>>>13,fe=0|a[9],pe=8191&fe,me=fe>>>13;r.negative=e.negative^t.negative,r.length=19;var ge=(u+(n=Math.imul(h,H))|0)+((8191&(i=(i=Math.imul(h,K))+Math.imul(d,H)|0))<<13)|0;u=((s=Math.imul(d,K))+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(p,H),i=(i=Math.imul(p,K))+Math.imul(m,H)|0,s=Math.imul(m,K);var ye=(u+(n=n+Math.imul(h,j)|0)|0)+((8191&(i=(i=i+Math.imul(h,z)|0)+Math.imul(d,j)|0))<<13)|0;u=((s=s+Math.imul(d,z)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(y,H),i=(i=Math.imul(y,K))+Math.imul(v,H)|0,s=Math.imul(v,K),n=n+Math.imul(p,j)|0,i=(i=i+Math.imul(p,z)|0)+Math.imul(m,j)|0,s=s+Math.imul(m,z)|0;var ve=(u+(n=n+Math.imul(h,G)|0)|0)+((8191&(i=(i=i+Math.imul(h,W)|0)+Math.imul(d,G)|0))<<13)|0;u=((s=s+Math.imul(d,W)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,H),i=(i=Math.imul(w,K))+Math.imul(E,H)|0,s=Math.imul(E,K),n=n+Math.imul(y,j)|0,i=(i=i+Math.imul(y,z)|0)+Math.imul(v,j)|0,s=s+Math.imul(v,z)|0,n=n+Math.imul(p,G)|0,i=(i=i+Math.imul(p,W)|0)+Math.imul(m,G)|0,s=s+Math.imul(m,W)|0;var be=(u+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(d,Z)|0))<<13)|0;u=((s=s+Math.imul(d,Y)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(k,H),i=(i=Math.imul(k,K))+Math.imul(x,H)|0,s=Math.imul(x,K),n=n+Math.imul(w,j)|0,i=(i=i+Math.imul(w,z)|0)+Math.imul(E,j)|0,s=s+Math.imul(E,z)|0,n=n+Math.imul(y,G)|0,i=(i=i+Math.imul(y,W)|0)+Math.imul(v,G)|0,s=s+Math.imul(v,W)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(m,Z)|0,s=s+Math.imul(m,Y)|0;var we=(u+(n=n+Math.imul(h,X)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(d,X)|0))<<13)|0;u=((s=s+Math.imul(d,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(T,H),i=(i=Math.imul(T,K))+Math.imul(S,H)|0,s=Math.imul(S,K),n=n+Math.imul(k,j)|0,i=(i=i+Math.imul(k,z)|0)+Math.imul(x,j)|0,s=s+Math.imul(x,z)|0,n=n+Math.imul(w,G)|0,i=(i=i+Math.imul(w,W)|0)+Math.imul(E,G)|0,s=s+Math.imul(E,W)|0,n=n+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,Y)|0)+Math.imul(v,Z)|0,s=s+Math.imul(v,Y)|0,n=n+Math.imul(p,X)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(m,X)|0,s=s+Math.imul(m,ee)|0;var Ee=(u+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(d,re)|0))<<13)|0;u=((s=s+Math.imul(d,ne)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,H),i=(i=Math.imul(N,K))+Math.imul(R,H)|0,s=Math.imul(R,K),n=n+Math.imul(T,j)|0,i=(i=i+Math.imul(T,z)|0)+Math.imul(S,j)|0,s=s+Math.imul(S,z)|0,n=n+Math.imul(k,G)|0,i=(i=i+Math.imul(k,W)|0)+Math.imul(x,G)|0,s=s+Math.imul(x,W)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(E,Z)|0,s=s+Math.imul(E,Y)|0,n=n+Math.imul(y,X)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(v,X)|0,s=s+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(m,re)|0,s=s+Math.imul(m,ne)|0;var Ae=(u+(n=n+Math.imul(h,se)|0)|0)+((8191&(i=(i=i+Math.imul(h,oe)|0)+Math.imul(d,se)|0))<<13)|0;u=((s=s+Math.imul(d,oe)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(C,H),i=(i=Math.imul(C,K))+Math.imul(P,H)|0,s=Math.imul(P,K),n=n+Math.imul(N,j)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(R,j)|0,s=s+Math.imul(R,z)|0,n=n+Math.imul(T,G)|0,i=(i=i+Math.imul(T,W)|0)+Math.imul(S,G)|0,s=s+Math.imul(S,W)|0,n=n+Math.imul(k,Z)|0,i=(i=i+Math.imul(k,Y)|0)+Math.imul(x,Z)|0,s=s+Math.imul(x,Y)|0,n=n+Math.imul(w,X)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(E,X)|0,s=s+Math.imul(E,ee)|0,n=n+Math.imul(y,re)|0,i=(i=i+Math.imul(y,ne)|0)+Math.imul(v,re)|0,s=s+Math.imul(v,ne)|0,n=n+Math.imul(p,se)|0,i=(i=i+Math.imul(p,oe)|0)+Math.imul(m,se)|0,s=s+Math.imul(m,oe)|0;var ke=(u+(n=n+Math.imul(h,ce)|0)|0)+((8191&(i=(i=i+Math.imul(h,ue)|0)+Math.imul(d,ce)|0))<<13)|0;u=((s=s+Math.imul(d,ue)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(D,H),i=(i=Math.imul(D,K))+Math.imul(B,H)|0,s=Math.imul(B,K),n=n+Math.imul(C,j)|0,i=(i=i+Math.imul(C,z)|0)+Math.imul(P,j)|0,s=s+Math.imul(P,z)|0,n=n+Math.imul(N,G)|0,i=(i=i+Math.imul(N,W)|0)+Math.imul(R,G)|0,s=s+Math.imul(R,W)|0,n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(S,Z)|0,s=s+Math.imul(S,Y)|0,n=n+Math.imul(k,X)|0,i=(i=i+Math.imul(k,ee)|0)+Math.imul(x,X)|0,s=s+Math.imul(x,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(E,re)|0,s=s+Math.imul(E,ne)|0,n=n+Math.imul(y,se)|0,i=(i=i+Math.imul(y,oe)|0)+Math.imul(v,se)|0,s=s+Math.imul(v,oe)|0,n=n+Math.imul(p,ce)|0,i=(i=i+Math.imul(p,ue)|0)+Math.imul(m,ce)|0,s=s+Math.imul(m,ue)|0;var xe=(u+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,de)|0)+Math.imul(d,he)|0))<<13)|0;u=((s=s+Math.imul(d,de)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(U,H),i=(i=Math.imul(U,K))+Math.imul(F,H)|0,s=Math.imul(F,K),n=n+Math.imul(D,j)|0,i=(i=i+Math.imul(D,z)|0)+Math.imul(B,j)|0,s=s+Math.imul(B,z)|0,n=n+Math.imul(C,G)|0,i=(i=i+Math.imul(C,W)|0)+Math.imul(P,G)|0,s=s+Math.imul(P,W)|0,n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(R,Z)|0,s=s+Math.imul(R,Y)|0,n=n+Math.imul(T,X)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(S,X)|0,s=s+Math.imul(S,ee)|0,n=n+Math.imul(k,re)|0,i=(i=i+Math.imul(k,ne)|0)+Math.imul(x,re)|0,s=s+Math.imul(x,ne)|0,n=n+Math.imul(w,se)|0,i=(i=i+Math.imul(w,oe)|0)+Math.imul(E,se)|0,s=s+Math.imul(E,oe)|0,n=n+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,ue)|0)+Math.imul(v,ce)|0,s=s+Math.imul(v,ue)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,de)|0)+Math.imul(m,he)|0,s=s+Math.imul(m,de)|0;var _e=(u+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,me)|0)+Math.imul(d,pe)|0))<<13)|0;u=((s=s+Math.imul(d,me)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(U,j),i=(i=Math.imul(U,z))+Math.imul(F,j)|0,s=Math.imul(F,z),n=n+Math.imul(D,G)|0,i=(i=i+Math.imul(D,W)|0)+Math.imul(B,G)|0,s=s+Math.imul(B,W)|0,n=n+Math.imul(C,Z)|0,i=(i=i+Math.imul(C,Y)|0)+Math.imul(P,Z)|0,s=s+Math.imul(P,Y)|0,n=n+Math.imul(N,X)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(R,X)|0,s=s+Math.imul(R,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(S,re)|0,s=s+Math.imul(S,ne)|0,n=n+Math.imul(k,se)|0,i=(i=i+Math.imul(k,oe)|0)+Math.imul(x,se)|0,s=s+Math.imul(x,oe)|0,n=n+Math.imul(w,ce)|0,i=(i=i+Math.imul(w,ue)|0)+Math.imul(E,ce)|0,s=s+Math.imul(E,ue)|0,n=n+Math.imul(y,he)|0,i=(i=i+Math.imul(y,de)|0)+Math.imul(v,he)|0,s=s+Math.imul(v,de)|0;var Te=(u+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,me)|0)+Math.imul(m,pe)|0))<<13)|0;u=((s=s+Math.imul(m,me)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(U,G),i=(i=Math.imul(U,W))+Math.imul(F,G)|0,s=Math.imul(F,W),n=n+Math.imul(D,Z)|0,i=(i=i+Math.imul(D,Y)|0)+Math.imul(B,Z)|0,s=s+Math.imul(B,Y)|0,n=n+Math.imul(C,X)|0,i=(i=i+Math.imul(C,ee)|0)+Math.imul(P,X)|0,s=s+Math.imul(P,ee)|0,n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(R,re)|0,s=s+Math.imul(R,ne)|0,n=n+Math.imul(T,se)|0,i=(i=i+Math.imul(T,oe)|0)+Math.imul(S,se)|0,s=s+Math.imul(S,oe)|0,n=n+Math.imul(k,ce)|0,i=(i=i+Math.imul(k,ue)|0)+Math.imul(x,ce)|0,s=s+Math.imul(x,ue)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,de)|0)+Math.imul(E,he)|0,s=s+Math.imul(E,de)|0;var Se=(u+(n=n+Math.imul(y,pe)|0)|0)+((8191&(i=(i=i+Math.imul(y,me)|0)+Math.imul(v,pe)|0))<<13)|0;u=((s=s+Math.imul(v,me)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(U,Z),i=(i=Math.imul(U,Y))+Math.imul(F,Z)|0,s=Math.imul(F,Y),n=n+Math.imul(D,X)|0,i=(i=i+Math.imul(D,ee)|0)+Math.imul(B,X)|0,s=s+Math.imul(B,ee)|0,n=n+Math.imul(C,re)|0,i=(i=i+Math.imul(C,ne)|0)+Math.imul(P,re)|0,s=s+Math.imul(P,ne)|0,n=n+Math.imul(N,se)|0,i=(i=i+Math.imul(N,oe)|0)+Math.imul(R,se)|0,s=s+Math.imul(R,oe)|0,n=n+Math.imul(T,ce)|0,i=(i=i+Math.imul(T,ue)|0)+Math.imul(S,ce)|0,s=s+Math.imul(S,ue)|0,n=n+Math.imul(k,he)|0,i=(i=i+Math.imul(k,de)|0)+Math.imul(x,he)|0,s=s+Math.imul(x,de)|0;var Ie=(u+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,me)|0)+Math.imul(E,pe)|0))<<13)|0;u=((s=s+Math.imul(E,me)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(U,X),i=(i=Math.imul(U,ee))+Math.imul(F,X)|0,s=Math.imul(F,ee),n=n+Math.imul(D,re)|0,i=(i=i+Math.imul(D,ne)|0)+Math.imul(B,re)|0,s=s+Math.imul(B,ne)|0,n=n+Math.imul(C,se)|0,i=(i=i+Math.imul(C,oe)|0)+Math.imul(P,se)|0,s=s+Math.imul(P,oe)|0,n=n+Math.imul(N,ce)|0,i=(i=i+Math.imul(N,ue)|0)+Math.imul(R,ce)|0,s=s+Math.imul(R,ue)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,de)|0)+Math.imul(S,he)|0,s=s+Math.imul(S,de)|0;var Ne=(u+(n=n+Math.imul(k,pe)|0)|0)+((8191&(i=(i=i+Math.imul(k,me)|0)+Math.imul(x,pe)|0))<<13)|0;u=((s=s+Math.imul(x,me)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,n=Math.imul(U,re),i=(i=Math.imul(U,ne))+Math.imul(F,re)|0,s=Math.imul(F,ne),n=n+Math.imul(D,se)|0,i=(i=i+Math.imul(D,oe)|0)+Math.imul(B,se)|0,s=s+Math.imul(B,oe)|0,n=n+Math.imul(C,ce)|0,i=(i=i+Math.imul(C,ue)|0)+Math.imul(P,ce)|0,s=s+Math.imul(P,ue)|0,n=n+Math.imul(N,he)|0,i=(i=i+Math.imul(N,de)|0)+Math.imul(R,he)|0,s=s+Math.imul(R,de)|0;var Re=(u+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,me)|0)+Math.imul(S,pe)|0))<<13)|0;u=((s=s+Math.imul(S,me)|0)+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(U,se),i=(i=Math.imul(U,oe))+Math.imul(F,se)|0,s=Math.imul(F,oe),n=n+Math.imul(D,ce)|0,i=(i=i+Math.imul(D,ue)|0)+Math.imul(B,ce)|0,s=s+Math.imul(B,ue)|0,n=n+Math.imul(C,he)|0,i=(i=i+Math.imul(C,de)|0)+Math.imul(P,he)|0,s=s+Math.imul(P,de)|0;var Oe=(u+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,me)|0)+Math.imul(R,pe)|0))<<13)|0;u=((s=s+Math.imul(R,me)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(U,ce),i=(i=Math.imul(U,ue))+Math.imul(F,ce)|0,s=Math.imul(F,ue),n=n+Math.imul(D,he)|0,i=(i=i+Math.imul(D,de)|0)+Math.imul(B,he)|0,s=s+Math.imul(B,de)|0;var Ce=(u+(n=n+Math.imul(C,pe)|0)|0)+((8191&(i=(i=i+Math.imul(C,me)|0)+Math.imul(P,pe)|0))<<13)|0;u=((s=s+Math.imul(P,me)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(U,he),i=(i=Math.imul(U,de))+Math.imul(F,he)|0,s=Math.imul(F,de);var Pe=(u+(n=n+Math.imul(D,pe)|0)|0)+((8191&(i=(i=i+Math.imul(D,me)|0)+Math.imul(B,pe)|0))<<13)|0;u=((s=s+Math.imul(B,me)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var Me=(u+(n=Math.imul(U,pe))|0)+((8191&(i=(i=Math.imul(U,me))+Math.imul(F,pe)|0))<<13)|0;return u=((s=Math.imul(F,me))+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,c[0]=ge,c[1]=ye,c[2]=ve,c[3]=be,c[4]=we,c[5]=Ee,c[6]=Ae,c[7]=ke,c[8]=xe,c[9]=_e,c[10]=Te,c[11]=Se,c[12]=Ie,c[13]=Ne,c[14]=Re,c[15]=Oe,c[16]=Ce,c[17]=Pe,c[18]=Me,0!==u&&(c[19]=u,r.length++),r};function y(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,s=0;s<r.length-1;s++){var o=i;i=0;for(var a=67108863&n,c=Math.min(s,t.length-1),u=Math.max(0,s-e.length+1);u<=c;u++){var l=s-u,h=(0|e.words[l])*(0|t.words[u]),d=67108863&h;a=67108863&(d=d+a|0),i+=(o=(o=o+(h/67108864|0)|0)+(d>>>26)|0)>>>26,o&=67108863}r.words[s]=a,n=o,o=i}return 0!==n?r.words[s]=n:r.length--,r._strip()}function v(e,t,r){return y(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(g=m),s.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?g(this,e,t):r<63?m(this,e,t):r<1024?y(this,e,t):v(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=s.prototype._countBits(e)-1,n=0;n<e;n++)t[n]=this.revBin(n,r,e);return t},b.prototype.revBin=function(e,t,r){if(0===e||e===r-1)return e;for(var n=0,i=0;i<t;i++)n|=(1&e)<<t-i-1,e>>=1;return n},b.prototype.permute=function(e,t,r,n,i,s){for(var o=0;o<s;o++)n[o]=t[e[o]],i[o]=r[e[o]]},b.prototype.transform=function(e,t,r,n,i,s){this.permute(s,e,t,r,n,i);for(var o=1;o<i;o<<=1)for(var a=o<<1,c=Math.cos(2*Math.PI/a),u=Math.sin(2*Math.PI/a),l=0;l<i;l+=a)for(var h=c,d=u,f=0;f<o;f++){var p=r[l+f],m=n[l+f],g=r[l+f+o],y=n[l+f+o],v=h*g-d*y;y=h*y+d*g,g=v,r[l+f]=p+g,n[l+f]=m+y,r[l+f+o]=p-g,n[l+f+o]=m-y,f!==a&&(v=c*h-u*d,d=c*d+u*h,h=v)}},b.prototype.guessLen13b=function(e,t){var r=1|Math.max(t,e),n=1&r,i=0;for(r=r/2|0;r;r>>>=1)i++;return 1<<i+1+n},b.prototype.conjugate=function(e,t,r){if(!(r<=1))for(var n=0;n<r/2;n++){var i=e[n];e[n]=e[r-n-1],e[r-n-1]=i,i=t[n],t[n]=-t[r-n-1],t[r-n-1]=-i}},b.prototype.normalize13b=function(e,t){for(var r=0,n=0;n<t/2;n++){var i=8192*Math.round(e[2*n+1]/t)+Math.round(e[2*n]/t)+r;e[n]=67108863&i,r=i<67108864?0:i/67108864|0}return e},b.prototype.convert13b=function(e,t,r,i){for(var s=0,o=0;o<t;o++)s+=0|e[o],r[2*o]=8191&s,s>>>=13,r[2*o+1]=8191&s,s>>>=13;for(o=2*t;o<i;++o)r[o]=0;n(0===s),n(!(-8192&s))},b.prototype.stub=function(e){for(var t=new Array(e),r=0;r<e;r++)t[r]=0;return t},b.prototype.mulp=function(e,t,r){var n=2*this.guessLen13b(e.length,t.length),i=this.makeRBT(n),s=this.stub(n),o=new Array(n),a=new Array(n),c=new Array(n),u=new Array(n),l=new Array(n),h=new Array(n),d=r.words;d.length=n,this.convert13b(e.words,e.length,o,n),this.convert13b(t.words,t.length,u,n),this.transform(o,s,a,c,n,i),this.transform(u,s,l,h,n,i);for(var f=0;f<n;f++){var p=a[f]*l[f]-c[f]*h[f];c[f]=a[f]*h[f]+c[f]*l[f],a[f]=p}return this.conjugate(a,c,n),this.transform(a,c,d,s,n,i),this.conjugate(d,s,n),this.normalize13b(d,n),r.negative=e.negative^t.negative,r.length=e.length+t.length,r._strip()},s.prototype.mul=function(e){var t=new s(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},s.prototype.mulf=function(e){var t=new s(null);return t.words=new Array(this.length+e.length),v(this,e,t)},s.prototype.imul=function(e){return this.clone().mulTo(e,this)},s.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var r=0,i=0;i<this.length;i++){var s=(0|this.words[i])*e,o=(67108863&s)+(67108863&r);r>>=26,r+=s/67108864|0,r+=o>>>26,this.words[i]=67108863&o}return 0!==r&&(this.words[i]=r,this.length++),this.length=0===e?1:this.length,t?this.ineg():this},s.prototype.muln=function(e){return this.clone().imuln(e)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r<t.length;r++){var n=r/26|0,i=r%26;t[r]=e.words[n]>>>i&1}return t}(e);if(0===t.length)return new s(1);for(var r=this,n=0;n<t.length&&0===t[n];n++,r=r.sqr());if(++n<t.length)for(var i=r.sqr();n<t.length;n++,i=i.sqr())0!==t[n]&&(r=r.mul(i));return r},s.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,i=(e-r)/26,s=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(t=0;t<this.length;t++){var a=this.words[t]&s,c=(0|this.words[t])-a<<r;this.words[t]=c|o,o=a>>>26-r}o&&(this.words[t]=o,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t<i;t++)this.words[t]=0;this.length+=i}return this._strip()},s.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},s.prototype.iushrn=function(e,t,r){var i;n("number"==typeof e&&e>=0),i=t?(t-t%26)/26:0;var s=e%26,o=Math.min((e-s)/26,this.length),a=67108863^67108863>>>s<<s,c=r;if(i-=o,i=Math.max(0,i),c){for(var u=0;u<o;u++)c.words[u]=this.words[u];c.length=o}if(0===o);else if(this.length>o)for(this.length-=o,u=0;u<this.length;u++)this.words[u]=this.words[u+o];else this.words[0]=0,this.length=1;var l=0;for(u=this.length-1;u>=0&&(0!==l||u>=i);u--){var h=0|this.words[u];this.words[u]=l<<26-s|h>>>s,l=h&a}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},s.prototype.shln=function(e){return this.clone().ishln(e)},s.prototype.ushln=function(e){return this.clone().iushln(e)},s.prototype.shrn=function(e){return this.clone().ishrn(e)},s.prototype.ushrn=function(e){return this.clone().iushrn(e)},s.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<<t;return!(this.length<=r||!(this.words[r]&i))},s.prototype.imaskn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<<t;this.words[this.length-1]&=i}return this._strip()},s.prototype.maskn=function(e){return this.clone().imaskn(e)},s.prototype.iaddn=function(e){return n("number"==typeof e),n(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<=e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},s.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},s.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this._strip()},s.prototype.addn=function(e){return this.clone().iaddn(e)},s.prototype.subn=function(e){return this.clone().isubn(e)},s.prototype.iabs=function(){return this.negative=0,this},s.prototype.abs=function(){return this.clone().iabs()},s.prototype._ishlnsubmul=function(e,t,r){var i,s,o=e.length+r;this._expand(o);var a=0;for(i=0;i<e.length;i++){s=(0|this.words[i+r])+a;var c=(0|e.words[i])*t;a=((s-=67108863&c)>>26)-(c/67108864|0),this.words[i+r]=67108863&s}for(;i<this.length-r;i++)a=(s=(0|this.words[i+r])+a)>>26,this.words[i+r]=67108863&s;if(0===a)return this._strip();for(n(-1===a),a=0,i=0;i<this.length;i++)a=(s=-(0|this.words[i])+a)>>26,this.words[i]=67108863&s;return this.negative=1,this._strip()},s.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,o=0|i.words[i.length-1];0!=(r=26-this._countBits(o))&&(i=i.ushln(r),n.iushln(r),o=0|i.words[i.length-1]);var a,c=n.length-i.length;if("mod"!==t){(a=new s(null)).length=c+1,a.words=new Array(a.length);for(var u=0;u<a.length;u++)a.words[u]=0}var l=n.clone()._ishlnsubmul(i,1,c);0===l.negative&&(n=l,a&&(a.words[c]=1));for(var h=c-1;h>=0;h--){var d=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(d=Math.min(d/o|0,67108863),n._ishlnsubmul(i,d,h);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);a&&(a.words[h]=d)}return a&&a._strip(),n._strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:a||null,mod:n}},s.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(i=a.div.neg()),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.iadd(e)),{div:i,mod:o}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(i=a.div.neg()),{div:i,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.isub(e)),{div:a.div,mod:o}):e.length>this.length||this.cmp(e)<0?{div:new s(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new s(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new s(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,o,a},s.prototype.div=function(e){return this.divmod(e,"div",!1).div},s.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},s.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},s.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),s=r.cmp(n);return s<0||1===i&&0===s?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},s.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,i=0,s=this.length-1;s>=0;s--)i=(r*i+(0|this.words[s]))%e;return t?-i:i},s.prototype.modn=function(e){return this.modrn(e)},s.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,i=this.length-1;i>=0;i--){var s=(0|this.words[i])+67108864*r;this.words[i]=s/e|0,r=s%e}return this._strip(),t?this.ineg():this},s.prototype.divn=function(e){return this.clone().idivn(e)},s.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new s(1),o=new s(0),a=new s(0),c=new s(1),u=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++u;for(var l=r.clone(),h=t.clone();!t.isZero();){for(var d=0,f=1;0===(t.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(l),o.isub(h)),i.iushrn(1),o.iushrn(1);for(var p=0,m=1;0===(r.words[0]&m)&&p<26;++p,m<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(h)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(a),o.isub(c)):(r.isub(t),a.isub(i),c.isub(o))}return{a,b:c,gcd:r.iushln(u)}},s.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,o=new s(1),a=new s(0),c=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var u=0,l=1;0===(t.words[0]&l)&&u<26;++u,l<<=1);if(u>0)for(t.iushrn(u);u-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);for(var h=0,d=1;0===(r.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(r.iushrn(h);h-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),o.isub(a)):(r.isub(t),a.isub(o))}return(i=0===t.cmpn(1)?o:a).cmpn(0)<0&&i.iadd(e),i},s.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var s=t;t=r,r=s}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},s.prototype.invm=function(e){return this.egcd(e).a.umod(e)},s.prototype.isEven=function(){return!(1&this.words[0])},s.prototype.isOdd=function(){return!(1&~this.words[0])},s.prototype.andln=function(e){return this.words[0]&e},s.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=i,this;for(var s=i,o=r;0!==s&&o<this.length;o++){var a=0|this.words[o];s=(a+=s)>>>26,a&=67108863,this.words[o]=a}return 0!==s&&(this.words[o]=s,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:i<e?-1:1}return 0!==this.negative?0|-t:t},s.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},s.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,r=this.length-1;r>=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){n<i?t=-1:n>i&&(t=1);break}}return t},s.prototype.gtn=function(e){return 1===this.cmpn(e)},s.prototype.gt=function(e){return 1===this.cmp(e)},s.prototype.gten=function(e){return this.cmpn(e)>=0},s.prototype.gte=function(e){return this.cmp(e)>=0},s.prototype.ltn=function(e){return-1===this.cmpn(e)},s.prototype.lt=function(e){return-1===this.cmp(e)},s.prototype.lten=function(e){return this.cmpn(e)<=0},s.prototype.lte=function(e){return this.cmp(e)<=0},s.prototype.eqn=function(e){return 0===this.cmpn(e)},s.prototype.eq=function(e){return 0===this.cmp(e)},s.red=function(e){return new T(e)},s.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(e){return this.red=e,this},s.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},s.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},s.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},s.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},s.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},s.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},s.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},s.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var w={k256:null,p224:null,p192:null,p25519:null};function E(e,t){this.name=e,this.p=new s(t,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function A(){E.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function k(){E.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function x(){E.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){E.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function T(e){if("string"==typeof e){var t=s._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function S(e){T.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}E.prototype._tmp=function(){var e=new s(null);return e.words=new Array(Math.ceil(this.n/13)),e},E.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t<this.n?-1:r.ucmp(this.p);return 0===n?(r.words[0]=0,r.length=1):n>0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},E.prototype.split=function(e,t){e.iushrn(this.n,0,t)},E.prototype.imulK=function(e){return e.imul(this.k)},i(A,E),A.prototype.split=function(e,t){for(var r=4194303,n=Math.min(e.length,9),i=0;i<n;i++)t.words[i]=e.words[i];if(t.length=n,e.length<=9)return e.words[0]=0,void(e.length=1);var s=e.words[9];for(t.words[t.length++]=s&r,i=10;i<e.length;i++){var o=0|e.words[i];e.words[i-10]=(o&r)<<4|s>>>22,s=o}s>>>=22,e.words[i-10]=s,0===s&&e.length>10?e.length-=10:e.length-=9},A.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r<e.length;r++){var n=0|e.words[r];t+=977*n,e.words[r]=67108863&t,t=64*n+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},i(k,E),i(x,E),i(_,E),_.prototype.imulK=function(e){for(var t=0,r=0;r<e.length;r++){var n=19*(0|e.words[r])+t,i=67108863&n;n>>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},s._prime=function(e){if(w[e])return w[e];var t;if("k256"===e)t=new A;else if("p224"===e)t=new k;else if("p192"===e)t=new x;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return w[e]=t,t},T.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},T.prototype._verify2=function(e,t){n(0===(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},T.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},T.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},T.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},T.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},T.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},T.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},T.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},T.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},T.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},T.prototype.isqr=function(e){return this.imul(e,e.clone())},T.prototype.sqr=function(e){return this.mul(e,e)},T.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new s(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);n(!i.isZero());var a=new s(1).toRed(this),c=a.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new s(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var h=this.pow(l,i),d=this.pow(e,i.addn(1).iushrn(1)),f=this.pow(e,i),p=o;0!==f.cmp(a);){for(var m=f,g=0;0!==m.cmp(a);g++)m=m.redSqr();n(g<p);var y=this.pow(h,new s(1).iushln(p-g-1));d=d.redMul(y),h=y.redSqr(),f=f.redMul(h),p=g}return d},T.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},T.prototype.pow=function(e,t){if(t.isZero())return new s(1).toRed(this);if(0===t.cmpn(1))return e.clone();var r=new Array(16);r[0]=new s(1).toRed(this),r[1]=e;for(var n=2;n<r.length;n++)r[n]=this.mul(r[n-1],e);var i=r[0],o=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),n=t.length-1;n>=0;n--){for(var u=t.words[n],l=c-1;l>=0;l--){var h=u>>l&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==o?(o<<=1,o|=h,(4===++a||0===n&&0===l)&&(i=this.mul(i,r[o]),a=0,o=0)):a=0}c=26}return i},T.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},T.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},s.mont=function(e){return new S(e)},i(S,T),S.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},S.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},S.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},S.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new s(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e=r.nmd(e),this)},1048(e,t,r){"use strict";const n=r(7991),i=r(9318),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=c,t.SlowBuffer=function(e){return+e!=e&&(e=0),c.alloc(+e)},t.INSPECT_MAX_BYTES=50;const o=2147483647;function a(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return h(e)}return u(e,t,r)}function u(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=a(r);const i=n.write(e,t);return i!==r&&(n=n.slice(0,i)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(J(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return d(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(J(e,ArrayBuffer)||e&&J(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(J(e,SharedArrayBuffer)||e&&J(e.buffer,SharedArrayBuffer)))return f(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return c.from(n,t,r);const i=function(e){if(c.isBuffer(e)){const t=0|p(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Z(e.length)?a(0):d(e):"Buffer"===e.type&&Array.isArray(e.data)?d(e.data):void 0}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function h(e){return l(e),a(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),r=a(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function f(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(n,c.prototype),n}function p(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function m(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||J(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(i)return n?-1:V(e).length;t=(""+t).toLowerCase(),i=!0}}function g(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,r);case"utf8":case"utf-8":return T(this,t,r);case"ascii":return I(this,t,r);case"latin1":case"binary":return N(this,t,r);case"base64":return _(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function v(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Z(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){let s,o=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;o=2,a/=2,c/=2,r/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){let n=-1;for(s=r;s<a;s++)if(u(e,s)===u(t,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===c)return n*o}else-1!==n&&(s-=s-n),n=-1}else for(r+c>a&&(r=a-c),s=r;s>=0;s--){let r=!0;for(let n=0;n<c;n++)if(u(e,s+n)!==u(t,n)){r=!1;break}if(r)return s}return-1}function w(e,t,r,n){r=Number(r)||0;const i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;const s=t.length;let o;for(n>s/2&&(n=s/2),o=0;o<n;++o){const n=parseInt(t.substr(2*o,2),16);if(Z(n))return o;e[r+o]=n}return o}function E(e,t,r,n){return W(V(t,e.length-r),e,r,n)}function A(e,t,r,n){return W(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function k(e,t,r,n){return W(G(t),e,r,n)}function x(e,t,r,n){return W(function(e,t){let r,n,i;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)r=e.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}(t,e.length-r),e,r,n)}function _(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function T(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i<r;){const t=e[i];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=r){let r,n,a,c;switch(o){case 1:t<128&&(s=t);break;case 2:r=e[i+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(s=c));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(c=(15&t)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:r=e[i+1],n=e[i+2],a=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&a,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(e){const t=e.length;if(t<=S)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=S));return r}(n)}t.kMaxLength=o,c.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),c.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(c.prototype,"parent",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.buffer}}),Object.defineProperty(c.prototype,"offset",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.byteOffset}}),c.poolSize=8192,c.from=function(e,t,r){return u(e,t,r)},Object.setPrototypeOf(c.prototype,Uint8Array.prototype),Object.setPrototypeOf(c,Uint8Array),c.alloc=function(e,t,r){return function(e,t,r){return l(e),e<=0?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)}(e,t,r)},c.allocUnsafe=function(e){return h(e)},c.allocUnsafeSlow=function(e){return h(e)},c.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==c.prototype},c.compare=function(e,t){if(J(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),J(t,Uint8Array)&&(t=c.from(t,t.offset,t.byteLength)),!c.isBuffer(e)||!c.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,s=Math.min(r,n);i<s;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},c.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},c.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return c.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=c.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(J(t,Uint8Array))i+t.length>n.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},c.byteLength=m,c.prototype._isBuffer=!0,c.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)y(this,t,t+1);return this},c.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},c.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},c.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},c.prototype.toLocaleString=c.prototype.toString,c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},s&&(c.prototype[s]=c.prototype.inspect),c.prototype.compare=function(e,t,r,n,i){if(J(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(t>>>=0);const a=Math.min(s,o),u=this.slice(n,i),l=e.slice(t,r);for(let e=0;e<a;++e)if(u[e]!==l[e]){s=u[e],o=l[e];break}return s<o?-1:o<s?1:0},c.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},c.prototype.indexOf=function(e,t,r){return v(this,e,t,r,!0)},c.prototype.lastIndexOf=function(e,t,r){return v(this,e,t,r,!1)},c.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":case"latin1":case"binary":return A(this,e,t,r);case"base64":return k(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const S=4096;function I(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function N(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function R(e,t,r){const n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=t;n<r;++n)i+=Y[e[n]];return i}function O(e,t,r){const n=e.slice(t,r);let i="";for(let e=0;e<n.length-1;e+=2)i+=String.fromCharCode(n[e]+256*n[e+1]);return i}function C(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,r,n,i,s){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function M(e,t,r,n,i){K(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,r}function D(e,t,r,n,i){K(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r+7]=s,s>>=8,e[r+6]=s,s>>=8,e[r+5]=s,s>>=8,e[r+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=o,o>>=8,e[r+2]=o,o>>=8,e[r+1]=o,o>>=8,e[r]=o,r+8}function B(e,t,r,n,i,s){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,n,s){return t=+t,r>>>=0,s||B(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function U(e,t,r,n,s){return t=+t,r>>>=0,s||B(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,c.prototype),n},c.prototype.readUintLE=c.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return n},c.prototype.readUintBE=c.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),c.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),c.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,i=1,s=this[e+--n];for(;n>0&&(i*=256);)s+=this[e+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},c.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),c.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)}),c.prototype.readFloatLE=function(e,t){return e>>>=0,t||C(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||P(this,e,t,r,Math.pow(2,8*r)-1,0);let i=1,s=0;for(this[t]=255&e;++s<r&&(i*=256);)this[t+s]=e/i&255;return t+r},c.prototype.writeUintBE=c.prototype.writeUIntBE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||P(this,e,t,r,Math.pow(2,8*r)-1,0);let i=r-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+r},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigUInt64LE=Q(function(e,t=0){return M(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeBigUInt64BE=Q(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let i=0,s=1,o=0;for(this[t]=255&e;++i<r&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s|0)-o&255;return t+r},c.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s|0)-o&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigInt64LE=Q(function(e,t=0){return M(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeBigInt64BE=Q(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return U(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return U(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);const i=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i},c.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!c.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{const s=c.isBuffer(e)?e:c.from(e,n),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=s[i%o]}return this};const F={};function $(e,t,r){F[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function H(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function K(e,t,r,n,i,s){if(e>r||e<t){const n="bigint"==typeof t?"n":"";let i;throw i=s>3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new F.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||j(t,e.length-(r+1))}(n,i,s)}function q(e,t){if("number"!=typeof e)throw new F.ERR_INVALID_ARG_TYPE(t,"number",e)}function j(e,t,r){if(Math.floor(e)!==e)throw q(e,r),new F.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new F.ERR_BUFFER_OUT_OF_BOUNDS;throw new F.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}$("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),$("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),$("ERR_OUT_OF_RANGE",function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n},RangeError);const z=/[^+/0-9A-Za-z-_]/g;function V(e,t){let r;t=t||1/0;const n=e.length;let i=null;const s=[];for(let o=0;o<n;++o){if(r=e.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function W(e,t,r,n){let i;for(i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function J(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Z(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function Q(e){return"undefined"==typeof BigInt?X:e}function X(){throw new Error("BigInt not supported")}},8367(e,t,r){"use strict";r.r(t),r.d(t,{BaseContract:()=>Cn,BigNumber:()=>W,Contract:()=>Pn,ContractFactory:()=>Mn,FixedNumber:()=>zn,Signer:()=>cr,VoidSigner:()=>ur,Wallet:()=>bs,Wordlist:()=>Ei,constants:()=>i,errors:()=>g,ethers:()=>c,getDefaultProvider:()=>lc,logger:()=>$c,providers:()=>s,utils:()=>a,version:()=>Fc,wordlists:()=>_i});var n={};r.r(n),r.d(n,{decode:()=>Te,encode:()=>ke});var i={};r.r(i),r.d(i,{AddressZero:()=>As,EtherSymbol:()=>xs,HashZero:()=>ks,MaxInt256:()=>mt,MaxUint256:()=>ft,MinInt256:()=>pt,NegativeOne:()=>ct,One:()=>lt,Two:()=>ht,WeiPerEther:()=>dt,Zero:()=>ut});var s={};r.r(s),r.d(s,{AlchemyProvider:()=>ga,AlchemyWebSocketProvider:()=>ma,AnkrProvider:()=>wa,BaseProvider:()=>zo,CloudflareProvider:()=>Aa,EtherscanProvider:()=>Ra,FallbackProvider:()=>za,Formatter:()=>yo,InfuraProvider:()=>Za,InfuraWebSocketProvider:()=>Ja,IpcProvider:()=>Va,JsonRpcBatchProvider:()=>Ya,JsonRpcProvider:()=>ia,JsonRpcSigner:()=>ta,NodesmithProvider:()=>Xa,PocketProvider:()=>rc,Provider:()=>nr,QuickNodeProvider:()=>ic,Resolver:()=>Ko,StaticJsonRpcProvider:()=>ha,UrlJsonRpcProvider:()=>da,Web3Provider:()=>cc,WebSocketProvider:()=>ua,getDefaultProvider:()=>lc,getNetwork:()=>Cs,isCommunityResourcable:()=>vo,isCommunityResource:()=>bo,showThrottleMessage:()=>Eo});var o={};r.r(o),r.d(o,{decode:()=>Ps,encode:()=>Ms});var a={};r.r(a),r.d(a,{AbiCoder:()=>zt,ConstructorFragment:()=>Mt,ErrorFragment:()=>Lt,EventFragment:()=>Rt,FormatTypes:()=>_t,Fragment:()=>Nt,FunctionFragment:()=>Dt,HDNode:()=>Li,Indexed:()=>Yt,Interface:()=>er,LogDescription:()=>Wt,Logger:()=>v,ParamType:()=>St,RLP:()=>n,SigningKey:()=>Yr,SupportedAlgorithm:()=>fi,TransactionDescription:()=>Jt,TransactionTypes:()=>tn,UnicodeNormalizationForm:()=>Fe,Utf8ErrorFuncs:()=>Ke,Utf8ErrorReason:()=>$e,_TypedDataEncoder:()=>li,_fetchData:()=>uo,_toEscapedUtf8String:()=>Ve,accessListify:()=>hn,arrayify:()=>_,base58:()=>di,base64:()=>o,checkProperties:()=>ne,checkResultErrors:()=>de,commify:()=>Mc,computeAddress:()=>an,computeHmac:()=>vi,computePublicKey:()=>Xr,concat:()=>T,deepCopy:()=>ce,defaultAbiCoder:()=>Vt,defaultPath:()=>Bi,defineReadOnly:()=>ee,dnsEncode:()=>io,entropyToMnemonic:()=>$i,fetchJson:()=>lo,formatBytes32String:()=>Rc,formatEther:()=>Lc,formatUnits:()=>Dc,getAccountPath:()=>Ki,getAddress:()=>Pe,getContractAddress:()=>Be,getCreate2Address:()=>Le,getIcapAddress:()=>De,getJsonWalletAddress:()=>ms,getStatic:()=>te,hashMessage:()=>Wn,hexConcat:()=>M,hexDataLength:()=>C,hexDataSlice:()=>P,hexStripZeros:()=>B,hexValue:()=>D,hexZeroPad:()=>L,hexlify:()=>O,id:()=>Ze,isAddress:()=>Me,isBytes:()=>x,isBytesLike:()=>A,isHexString:()=>N,isValidMnemonic:()=>Hi,isValidName:()=>ro,joinSignature:()=>F,keccak256:()=>ve,mnemonicToEntropy:()=>Fi,mnemonicToSeed:()=>Ui,namehash:()=>no,nameprep:()=>Nc,parseBytes32String:()=>Oc,parseEther:()=>Uc,parseTransaction:()=>yn,parseUnits:()=>Bc,poll:()=>ho,randomBytes:()=>Vi,recoverAddress:()=>cn,recoverPublicKey:()=>Qr,resolveProperties:()=>re,ripemd160:()=>mi,serializeTransaction:()=>mn,sha256:()=>gi,sha512:()=>yi,shallowCopy:()=>ie,shuffled:()=>Oa,solidityKeccak256:()=>yc,solidityPack:()=>gc,soliditySha256:()=>vc,splitSignature:()=>U,stripZeros:()=>S,toUtf8Bytes:()=>je,toUtf8CodePoints:()=>Je,toUtf8String:()=>We,verifyMessage:()=>ws,verifyTypedData:()=>Es,zeroPad:()=>I});var c={};r.r(c),r.d(c,{BaseContract:()=>Cn,BigNumber:()=>W,Contract:()=>Pn,ContractFactory:()=>Mn,FixedNumber:()=>zn,Signer:()=>cr,VoidSigner:()=>ur,Wallet:()=>bs,Wordlist:()=>Ei,constants:()=>i,errors:()=>g,getDefaultProvider:()=>lc,logger:()=>$c,providers:()=>s,utils:()=>a,version:()=>Fc,wordlists:()=>_i});let u=!1,l=!1;const h={debug:1,default:2,info:2,warning:3,error:4,off:5};let d=h.default,f=null;const p=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach(t=>{try{if("test"!=="test".normalize(t))throw new Error("bad normalize")}catch(r){e.push(t)}}),e.length)throw new Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(e){return e.message}return null}();var m,g;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(m||(m={})),function(e){e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"}(g||(g={}));const y="0123456789abcdef";class v{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==h[r]&&this.throwArgumentError("invalid log level name","logLevel",e),d>h[r]||console.log.apply(console,t)}debug(...e){this._log(v.levels.DEBUG,e)}info(...e){this._log(v.levels.INFO,e)}warn(...e){this._log(v.levels.WARNING,e)}makeError(e,t,r){if(l)return this.makeError("censored error",t,{});t||(t=v.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach(e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=y[t[e]>>4],r+=y[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}}),n.push(`code=${t}`),n.push(`version=${this.version}`);const i=e;let s="";switch(t){case g.NUMERIC_FAULT:{s="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":s+="-"+t;break;case"negative-power":case"negative-width":s+="-unsupported";break;case"unbound-bitwise-result":s+="-unbound-result"}break}case g.CALL_EXCEPTION:case g.INSUFFICIENT_FUNDS:case g.MISSING_NEW:case g.NONCE_EXPIRED:case g.REPLACEMENT_UNDERPRICED:case g.TRANSACTION_REPLACED:case g.UNPREDICTABLE_GAS_LIMIT:s=t}s&&(e+=" [ See: https://links.ethers.org/v5-errors-"+s+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=new Error(e);return o.reason=i,o.code=t,Object.keys(r).forEach(function(e){o[e]=r[e]}),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,v.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){null==e&&(e="platform missing String.prototype.normalize"),p&&this.throwError("platform missing String.prototype.normalize",v.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:p})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,v.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,v.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,v.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,v.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",v.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",v.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",v.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return f||(f=new v("logger/5.8.0")),f}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",v.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),u){if(!e)return;this.globalLogger().throwError("error censorship permanent",v.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}l=!!e,u=!!t}static setLogLevel(e){const t=h[e.toLowerCase()];null!=t?d=t:v.globalLogger().warn("invalid log level - "+e)}static from(e){return new v(e)}}v.errors=g,v.levels=m;const b=new v("bytes/5.8.0");function w(e){return!!e.toHexString}function E(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return E(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function A(e){return N(e)&&!(e.length%2)||x(e)}function k(e){return"number"==typeof e&&e==e&&e%1==0}function x(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!k(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!k(r)||r<0||r>=256)return!1}return!0}function _(e,t){if(t||(t={}),"number"==typeof e){b.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),E(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),w(e)&&(e=e.toHexString()),N(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":b.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return E(new Uint8Array(n))}return x(e)?E(new Uint8Array(e)):b.throwArgumentError("invalid arrayify value","value",e)}function T(e){const t=e.map(e=>_(e)),r=t.reduce((e,t)=>e+t.length,0),n=new Uint8Array(r);return t.reduce((e,t)=>(n.set(t,e),e+t.length),0),E(n)}function S(e){let t=_(e);if(0===t.length)return t;let r=0;for(;r<t.length&&0===t[r];)r++;return r&&(t=t.slice(r)),t}function I(e,t){(e=_(e)).length>t&&b.throwArgumentError("value out of range","value",arguments[0]);const r=new Uint8Array(t);return r.set(e,t-e.length),E(r)}function N(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/)||t&&e.length!==2+2*t)}const R="0123456789abcdef";function O(e,t){if(t||(t={}),"number"==typeof e){b.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=R[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),w(e))return e.toHexString();if(N(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":b.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(x(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=R[(240&n)>>4]+R[15&n]}return t}return b.throwArgumentError("invalid hexlify value","value",e)}function C(e){if("string"!=typeof e)e=O(e);else if(!N(e)||e.length%2)return null;return(e.length-2)/2}function P(e,t,r){return"string"!=typeof e?e=O(e):(!N(e)||e.length%2)&&b.throwArgumentError("invalid hexData","value",e),t=2+2*t,null!=r?"0x"+e.substring(t,2+2*r):"0x"+e.substring(t)}function M(e){let t="0x";return e.forEach(e=>{t+=O(e).substring(2)}),t}function D(e){const t=B(O(e,{hexPad:"left"}));return"0x"===t?"0x0":t}function B(e){"string"!=typeof e&&(e=O(e)),N(e)||b.throwArgumentError("invalid hex string","value",e),e=e.substring(2);let t=0;for(;t<e.length&&"0"===e[t];)t++;return"0x"+e.substring(t)}function L(e,t){for("string"!=typeof e?e=O(e):N(e)||b.throwArgumentError("invalid hex string","value",e),e.length>2*t+2&&b.throwArgumentError("value out of range","value",arguments[1]);e.length<2*t+2;)e="0x0"+e.substring(2);return e}function U(e){const t={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(A(e)){let r=_(e);64===r.length?(t.v=27+(r[32]>>7),r[32]&=127,t.r=O(r.slice(0,32)),t.s=O(r.slice(32,64))):65===r.length?(t.r=O(r.slice(0,32)),t.s=O(r.slice(32,64)),t.v=r[64]):b.throwArgumentError("invalid signature string","signature",e),t.v<27&&(0===t.v||1===t.v?t.v+=27:b.throwArgumentError("signature invalid v byte","signature",e)),t.recoveryParam=1-t.v%2,t.recoveryParam&&(r[32]|=128),t._vs=O(r.slice(32,64))}else{if(t.r=e.r,t.s=e.s,t.v=e.v,t.recoveryParam=e.recoveryParam,t._vs=e._vs,null!=t._vs){const r=I(_(t._vs),32);t._vs=O(r);const n=r[0]>=128?1:0;null==t.recoveryParam?t.recoveryParam=n:t.recoveryParam!==n&&b.throwArgumentError("signature recoveryParam mismatch _vs","signature",e),r[0]&=127;const i=O(r);null==t.s?t.s=i:t.s!==i&&b.throwArgumentError("signature v mismatch _vs","signature",e)}if(null==t.recoveryParam)null==t.v?b.throwArgumentError("signature missing v and recoveryParam","signature",e):0===t.v||1===t.v?t.recoveryParam=t.v:t.recoveryParam=1-t.v%2;else if(null==t.v)t.v=27+t.recoveryParam;else{const r=0===t.v||1===t.v?t.v:1-t.v%2;t.recoveryParam!==r&&b.throwArgumentError("signature recoveryParam mismatch v","signature",e)}null!=t.r&&N(t.r)?t.r=L(t.r,32):b.throwArgumentError("signature missing or invalid r","signature",e),null!=t.s&&N(t.s)?t.s=L(t.s,32):b.throwArgumentError("signature missing or invalid s","signature",e);const r=_(t.s);r[0]>=128&&b.throwArgumentError("signature s out of range","signature",e),t.recoveryParam&&(r[0]|=128);const n=O(r);t._vs&&(N(t._vs)||b.throwArgumentError("signature invalid _vs","signature",e),t._vs=L(t._vs,32)),null==t._vs?t._vs=n:t._vs!==n&&b.throwArgumentError("signature _vs mismatch v and s","signature",e)}return t.yParityAndS=t._vs,t.compact=t.r+t.yParityAndS.substring(2),t}function F(e){return O(T([(e=U(e)).r,e.s,e.recoveryParam?"0x1c":"0x1b"]))}var $=r(2823),H=r.n($);const K="bignumber/5.8.0";var q=H().BN;const j=new v(K),z={},V=9007199254740991;let G=!1;class W{constructor(e,t){e!==z&&j.throwError("cannot call constructor directly; use BigNumber.from",v.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=t,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return Z(Y(this).fromTwos(e))}toTwos(e){return Z(Y(this).toTwos(e))}abs(){return"-"===this._hex[0]?W.from(this._hex.substring(1)):this}add(e){return Z(Y(this).add(Y(e)))}sub(e){return Z(Y(this).sub(Y(e)))}div(e){return W.from(e).isZero()&&Q("division-by-zero","div"),Z(Y(this).div(Y(e)))}mul(e){return Z(Y(this).mul(Y(e)))}mod(e){const t=Y(e);return t.isNeg()&&Q("division-by-zero","mod"),Z(Y(this).umod(t))}pow(e){const t=Y(e);return t.isNeg()&&Q("negative-power","pow"),Z(Y(this).pow(t))}and(e){const t=Y(e);return(this.isNegative()||t.isNeg())&&Q("unbound-bitwise-result","and"),Z(Y(this).and(t))}or(e){const t=Y(e);return(this.isNegative()||t.isNeg())&&Q("unbound-bitwise-result","or"),Z(Y(this).or(t))}xor(e){const t=Y(e);return(this.isNegative()||t.isNeg())&&Q("unbound-bitwise-result","xor"),Z(Y(this).xor(t))}mask(e){return(this.isNegative()||e<0)&&Q("negative-width","mask"),Z(Y(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Q("negative-width","shl"),Z(Y(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Q("negative-width","shr"),Z(Y(this).shrn(e))}eq(e){return Y(this).eq(Y(e))}lt(e){return Y(this).lt(Y(e))}lte(e){return Y(this).lte(Y(e))}gt(e){return Y(this).gt(Y(e))}gte(e){return Y(this).gte(Y(e))}isNegative(){return"-"===this._hex[0]}isZero(){return Y(this).isZero()}toNumber(){try{return Y(this).toNumber()}catch(e){Q("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch(e){}return j.throwError("this platform does not support BigInt",v.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(10===arguments[0]?G||(G=!0,j.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):16===arguments[0]?j.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",v.errors.UNEXPECTED_ARGUMENT,{}):j.throwError("BigNumber.toString does not accept parameters",v.errors.UNEXPECTED_ARGUMENT,{})),Y(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof W)return e;if("string"==typeof e)return e.match(/^-?0x[0-9a-f]+$/i)?new W(z,J(e)):e.match(/^-?[0-9]+$/)?new W(z,J(new q(e))):j.throwArgumentError("invalid BigNumber string","value",e);if("number"==typeof e)return e%1&&Q("underflow","BigNumber.from",e),(e>=V||e<=-V)&&Q("overflow","BigNumber.from",e),W.from(String(e));const t=e;if("bigint"==typeof t)return W.from(t.toString());if(x(t))return W.from(O(t));if(t)if(t.toHexString){const e=t.toHexString();if("string"==typeof e)return W.from(e)}else{let e=t._hex;if(null==e&&"BigNumber"===t.type&&(e=t.hex),"string"==typeof e&&(N(e)||"-"===e[0]&&N(e.substring(1))))return W.from(e)}return j.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!(!e||!e._isBigNumber)}}function J(e){if("string"!=typeof e)return J(e.toString(16));if("-"===e[0])return"-"===(e=e.substring(1))[0]&&j.throwArgumentError("invalid hex","value",e),"0x00"===(e=J(e))?e:"-"+e;if("0x"!==e.substring(0,2)&&(e="0x"+e),"0x"===e)return"0x00";for(e.length%2&&(e="0x0"+e.substring(2));e.length>4&&"0x00"===e.substring(0,4);)e="0x"+e.substring(4);return e}function Z(e){return W.from(J(e))}function Y(e){const t=W.from(e).toHexString();return"-"===t[0]?new q("-"+t.substring(3),16):new q(t.substring(2),16)}function Q(e,t,r){const n={fault:e,operation:t};return null!=r&&(n.value=r),j.throwError(e,v.errors.NUMERIC_FAULT,n)}const X=new v("properties/5.8.0");function ee(e,t,r){Object.defineProperty(e,t,{enumerable:!0,value:r,writable:!1})}function te(e,t){for(let r=0;r<32;r++){if(e[t])return e[t];if(!e.prototype||"object"!=typeof e.prototype)break;e=Object.getPrototypeOf(e.prototype).constructor}return null}function re(e){return t=this,r=void 0,i=function*(){const t=Object.keys(e).map(t=>{const r=e[t];return Promise.resolve(r).then(e=>({key:t,value:e}))});return(yield Promise.all(t)).reduce((e,t)=>(e[t.key]=t.value,e),{})},new((n=void 0)||(n=Promise))(function(e,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(e){e(r)})).then(o,a)}c((i=i.apply(t,r||[])).next())});var t,r,n,i}function ne(e,t){e&&"object"==typeof e||X.throwArgumentError("invalid object","object",e),Object.keys(e).forEach(r=>{t[r]||X.throwArgumentError("invalid object key - "+r,"transaction:"+r,e)})}function ie(e){const t={};for(const r in e)t[r]=e[r];return t}const se={bigint:!0,boolean:!0,function:!0,number:!0,string:!0};function oe(e){if(null==e||se[typeof e])return!0;if(Array.isArray(e)||"object"==typeof e){if(!Object.isFrozen(e))return!1;const t=Object.keys(e);for(let r=0;r<t.length;r++){let n=null;try{n=e[t[r]]}catch(e){continue}if(!oe(n))return!1}return!0}return X.throwArgumentError("Cannot deepCopy "+typeof e,"object",e)}function ae(e){if(oe(e))return e;if(Array.isArray(e))return Object.freeze(e.map(e=>ce(e)));if("object"==typeof e){const t={};for(const r in e){const n=e[r];void 0!==n&&ee(t,r,ce(n))}return t}return X.throwArgumentError("Cannot deepCopy "+typeof e,"object",e)}function ce(e){return ae(e)}class ue{constructor(e){for(const t in e)this[t]=ce(e[t])}}const le="abi/5.8.0",he=new v(le);function de(e){const t=[],r=function(e,n){if(Array.isArray(n))for(let i in n){const s=e.slice();s.push(i);try{r(s,n[i])}catch(e){t.push({path:s,error:e})}}};return r([],e),t}class fe{constructor(e,t,r,n){this.name=e,this.type=t,this.localName=r,this.dynamic=n}_throwError(e,t){he.throwArgumentError(e,this.localName,t)}}class pe{constructor(e){ee(this,"wordSize",e||32),this._data=[],this._dataLength=0,this._padding=new Uint8Array(e)}get data(){return M(this._data)}get length(){return this._dataLength}_writeData(e){return this._data.push(e),this._dataLength+=e.length,e.length}appendWriter(e){return this._writeData(T(e._data))}writeBytes(e){let t=_(e);const r=t.length%this.wordSize;return r&&(t=T([t,this._padding.slice(r)])),this._writeData(t)}_getValue(e){let t=_(W.from(e));return t.length>this.wordSize&&he.throwError("value out-of-bounds",v.errors.BUFFER_OVERRUN,{length:this.wordSize,offset:t.length}),t.length%this.wordSize&&(t=T([this._padding.slice(t.length%this.wordSize),t])),t}writeValue(e){return this._writeData(this._getValue(e))}writeUpdatableValue(){const e=this._data.length;return this._data.push(this._padding),this._dataLength+=this.wordSize,t=>{this._data[e]=this._getValue(t)}}}class me{constructor(e,t,r,n){ee(this,"_data",_(e)),ee(this,"wordSize",t||32),ee(this,"_coerceFunc",r),ee(this,"allowLoose",n),this._offset=0}get data(){return O(this._data)}get consumed(){return this._offset}static coerce(e,t){let r=e.match("^u?int([0-9]+)$");return r&&parseInt(r[1])<=48&&(t=t.toNumber()),t}coerce(e,t){return this._coerceFunc?this._coerceFunc(e,t):me.coerce(e,t)}_peekBytes(e,t,r){let n=Math.ceil(t/this.wordSize)*this.wordSize;return this._offset+n>this._data.length&&(this.allowLoose&&r&&this._offset+t<=this._data.length?n=t:he.throwError("data out-of-bounds",v.errors.BUFFER_OVERRUN,{length:this._data.length,offset:this._offset+n})),this._data.slice(this._offset,this._offset+n)}subReader(e){return new me(this._data.slice(this._offset+e),this.wordSize,this._coerceFunc,this.allowLoose)}readBytes(e,t){let r=this._peekBytes(0,e,!!t);return this._offset+=r.length,r.slice(0,e)}readValue(){return W.from(this.readBytes(this.wordSize))}}var ge=r(671),ye=r.n(ge);function ve(e){return"0x"+ye().keccak_256(_(e))}const be=new v("rlp/5.8.0");function we(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function Ee(e,t,r){let n=0;for(let i=0;i<r;i++)n=256*n+e[t+i];return n}function Ae(e){if(Array.isArray(e)){let t=[];if(e.forEach(function(e){t=t.concat(Ae(e))}),t.length<=55)return t.unshift(192+t.length),t;const r=we(t.length);return r.unshift(247+r.length),r.concat(t)}A(e)||be.throwArgumentError("RLP object must be BytesLike","object",e);const t=Array.prototype.slice.call(_(e));if(1===t.length&&t[0]<=127)return t;if(t.length<=55)return t.unshift(128+t.length),t;const r=we(t.length);return r.unshift(183+r.length),r.concat(t)}function ke(e){return O(Ae(e))}function xe(e,t,r,n){const i=[];for(;r<t+1+n;){const s=_e(e,r);i.push(s.result),(r+=s.consumed)>t+1+n&&be.throwError("child data too short",v.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:i}}function _e(e,t){if(0===e.length&&be.throwError("data too short",v.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&be.throwError("data short segment too short",v.errors.BUFFER_OVERRUN,{});const n=Ee(e,t+1,r);return t+1+r+n>e.length&&be.throwError("data long segment too short",v.errors.BUFFER_OVERRUN,{}),xe(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&be.throwError("data array too short",v.errors.BUFFER_OVERRUN,{}),xe(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&be.throwError("data array too short",v.errors.BUFFER_OVERRUN,{});const n=Ee(e,t+1,r);return t+1+r+n>e.length&&be.throwError("data array too short",v.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:O(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&be.throwError("data too short",v.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:O(e.slice(t+1,t+1+r))}}return{consumed:1,result:O(e[t])}}function Te(e){const t=_(e),r=_e(t,0);return r.consumed!==t.length&&be.throwArgumentError("invalid rlp data","data",e),r.result}const Se=new v("address/5.8.0");function Ie(e){N(e,20)||Se.throwArgumentError("invalid address","address",e);const t=(e=e.toLowerCase()).substring(2).split(""),r=new Uint8Array(40);for(let e=0;e<40;e++)r[e]=t[e].charCodeAt(0);const n=_(ve(r));for(let e=0;e<40;e+=2)n[e>>1]>>4>=8&&(t[e]=t[e].toUpperCase()),(15&n[e>>1])>=8&&(t[e+1]=t[e+1].toUpperCase());return"0x"+t.join("")}const Ne={};for(let e=0;e<10;e++)Ne[String(e)]=String(e);for(let e=0;e<26;e++)Ne[String.fromCharCode(65+e)]=String(10+e);const Re=Math.floor((Oe=9007199254740991,Math.log10?Math.log10(Oe):Math.log(Oe)/Math.LN10));var Oe;function Ce(e){let t=(e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00").split("").map(e=>Ne[e]).join("");for(;t.length>=Re;){let e=t.substring(0,Re);t=parseInt(e,10)%97+t.substring(e.length)}let r=String(98-parseInt(t,10)%97);for(;r.length<2;)r="0"+r;return r}function Pe(e){let t=null;if("string"!=typeof e&&Se.throwArgumentError("invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/))"0x"!==e.substring(0,2)&&(e="0x"+e),t=Ie(e),e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&t!==e&&Se.throwArgumentError("bad address checksum","address",e);else if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(e.substring(2,4)!==Ce(e)&&Se.throwArgumentError("bad icap checksum","address",e),r=e.substring(4),t=new q(r,36).toString(16);t.length<40;)t="0"+t;t=Ie("0x"+t)}else Se.throwArgumentError("invalid address","address",e);var r;return t}function Me(e){try{return Pe(e),!0}catch(e){}return!1}function De(e){let t=(r=Pe(e).substring(2),new q(r,16).toString(36)).toUpperCase();for(var r;t.length<30;)t="0"+t;return"XE"+Ce("XE00"+t)+t}function Be(e){let t=null;try{t=Pe(e.from)}catch(t){Se.throwArgumentError("missing from address","transaction",e)}return Pe(P(ve(ke([t,S(_(W.from(e.nonce).toHexString()))])),12))}function Le(e,t,r){return 32!==C(t)&&Se.throwArgumentError("salt must be 32 bytes","salt",t),32!==C(r)&&Se.throwArgumentError("initCodeHash must be 32 bytes","initCodeHash",r),Pe(P(ve(T(["0xff",Pe(e),t,r])),12))}const Ue=new v("strings/5.8.0");var Fe,$e;function He(e,t,r,n,i){if(e===$e.BAD_PREFIX||e===$e.UNEXPECTED_CONTINUE){let e=0;for(let n=t+1;n<r.length&&r[n]>>6==2;n++)e++;return e}return e===$e.OVERRUN?r.length-t-1:0}!function(e){e.current="",e.NFC="NFC",e.NFD="NFD",e.NFKC="NFKC",e.NFKD="NFKD"}(Fe||(Fe={})),function(e){e.UNEXPECTED_CONTINUE="unexpected continuation byte",e.BAD_PREFIX="bad codepoint prefix",e.OVERRUN="string overrun",e.MISSING_CONTINUE="missing continuation byte",e.OUT_OF_RANGE="out of UTF-8 range",e.UTF16_SURROGATE="UTF-16 surrogate",e.OVERLONG="overlong representation"}($e||($e={}));const Ke=Object.freeze({error:function(e,t,r,n,i){return Ue.throwArgumentError(`invalid codepoint at offset ${t}; ${e}`,"bytes",r)},ignore:He,replace:function(e,t,r,n,i){return e===$e.OVERLONG?(n.push(i),0):(n.push(65533),He(e,t,r))}});function qe(e,t){null==t&&(t=Ke.error),e=_(e);const r=[];let n=0;for(;n<e.length;){const i=e[n++];if(!(i>>7)){r.push(i);continue}let s=null,o=null;if(192==(224&i))s=1,o=127;else if(224==(240&i))s=2,o=2047;else{if(240!=(248&i)){n+=t(128==(192&i)?$e.UNEXPECTED_CONTINUE:$e.BAD_PREFIX,n-1,e,r);continue}s=3,o=65535}if(n-1+s>=e.length){n+=t($e.OVERRUN,n-1,e,r);continue}let a=i&(1<<8-s-1)-1;for(let i=0;i<s;i++){let i=e[n];if(128!=(192&i)){n+=t($e.MISSING_CONTINUE,n,e,r),a=null;break}a=a<<6|63&i,n++}null!==a&&(a>1114111?n+=t($e.OUT_OF_RANGE,n-1-s,e,r,a):a>=55296&&a<=57343?n+=t($e.UTF16_SURROGATE,n-1-s,e,r,a):a<=o?n+=t($e.OVERLONG,n-1-s,e,r,a):r.push(a))}return r}function je(e,t=Fe.current){t!=Fe.current&&(Ue.checkNormalize(),e=e.normalize(t));let r=[];for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n<128)r.push(n);else if(n<2048)r.push(n>>6|192),r.push(63&n|128);else if(55296==(64512&n)){t++;const i=e.charCodeAt(t);if(t>=e.length||56320!=(64512&i))throw new Error("invalid utf-8 string");const s=65536+((1023&n)<<10)+(1023&i);r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(63&s|128)}else r.push(n>>12|224),r.push(n>>6&63|128),r.push(63&n|128)}return _(r)}function ze(e){const t="0000"+e.toString(16);return"\\u"+t.substring(t.length-4)}function Ve(e,t){return'"'+qe(e,t).map(e=>{if(e<256){switch(e){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 13:return"\\r";case 34:return'\\"';case 92:return"\\\\"}if(e>=32&&e<127)return String.fromCharCode(e)}return e<=65535?ze(e):ze(55296+((e-=65536)>>10&1023))+ze(56320+(1023&e))}).join("")+'"'}function Ge(e){return e.map(e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10&1023),56320+(1023&e)))).join("")}function We(e,t){return Ge(qe(e,t))}function Je(e,t=Fe.current){return qe(je(e,t))}function Ze(e){return ve(je(e))}class Ye extends fe{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){try{t=Pe(t)}catch(e){this._throwError(e.message,t)}return e.writeValue(t)}decode(e){return Pe(L(e.readValue().toHexString(),20))}}class Qe extends fe{constructor(e){super(e.name,e.type,void 0,e.dynamic),this.coder=e}defaultValue(){return this.coder.defaultValue()}encode(e,t){return this.coder.encode(e,t)}decode(e){return this.coder.decode(e)}}const Xe=new v(le);function et(e,t,r){let n=null;if(Array.isArray(r))n=r;else if(r&&"object"==typeof r){let e={};n=t.map(t=>{const n=t.localName;return n||Xe.throwError("cannot encode object for signature with missing names",v.errors.INVALID_ARGUMENT,{argument:"values",coder:t,value:r}),e[n]&&Xe.throwError("cannot encode object for signature with duplicate names",v.errors.INVALID_ARGUMENT,{argument:"values",coder:t,value:r}),e[n]=!0,r[n]})}else Xe.throwArgumentError("invalid tuple value","tuple",r);t.length!==n.length&&Xe.throwArgumentError("types/value length mismatch","tuple",r);let i=new pe(e.wordSize),s=new pe(e.wordSize),o=[];t.forEach((e,t)=>{let r=n[t];if(e.dynamic){let t=s.length;e.encode(s,r);let n=i.writeUpdatableValue();o.push(e=>{n(e+t)})}else e.encode(i,r)}),o.forEach(e=>{e(i.length)});let a=e.appendWriter(i);return a+=e.appendWriter(s),a}function tt(e,t){let r=[],n=e.subReader(0);t.forEach(t=>{let i=null;if(t.dynamic){let r=e.readValue(),s=n.subReader(r.toNumber());try{i=t.decode(s)}catch(e){if(e.code===v.errors.BUFFER_OVERRUN)throw e;i=e,i.baseType=t.name,i.name=t.localName,i.type=t.type}}else try{i=t.decode(e)}catch(e){if(e.code===v.errors.BUFFER_OVERRUN)throw e;i=e,i.baseType=t.name,i.name=t.localName,i.type=t.type}null!=i&&r.push(i)});const i=t.reduce((e,t)=>{const r=t.localName;return r&&(e[r]||(e[r]=0),e[r]++),e},{});t.forEach((e,t)=>{let n=e.localName;if(!n||1!==i[n])return;if("length"===n&&(n="_length"),null!=r[n])return;const s=r[t];s instanceof Error?Object.defineProperty(r,n,{enumerable:!0,get:()=>{throw s}}):r[n]=s});for(let e=0;e<r.length;e++){const t=r[e];t instanceof Error&&Object.defineProperty(r,e,{enumerable:!0,get:()=>{throw t}})}return Object.freeze(r)}class rt extends fe{constructor(e,t,r){super("array",e.type+"["+(t>=0?t:"")+"]",r,-1===t||e.dynamic),this.coder=e,this.length=t}defaultValue(){const e=this.coder.defaultValue(),t=[];for(let r=0;r<this.length;r++)t.push(e);return t}encode(e,t){Array.isArray(t)||this._throwError("expected array value",t);let r=this.length;-1===r&&(r=t.length,e.writeValue(t.length)),Xe.checkArgumentCount(t.length,r,"coder array"+(this.localName?" "+this.localName:""));let n=[];for(let e=0;e<t.length;e++)n.push(this.coder);return et(e,n,t)}decode(e){let t=this.length;-1===t&&(t=e.readValue().toNumber(),32*t>e._data.length&&Xe.throwError("insufficient data length",v.errors.BUFFER_OVERRUN,{length:e._data.length,count:t}));let r=[];for(let e=0;e<t;e++)r.push(new Qe(this.coder));return e.coerce(this.name,tt(e,r))}}class nt extends fe{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){return e.writeValue(t?1:0)}decode(e){return e.coerce(this.type,!e.readValue().isZero())}}class it extends fe{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=_(t);let r=e.writeValue(t.length);return r+=e.writeBytes(t),r}decode(e){return e.readBytes(e.readValue().toNumber(),!0)}}class st extends it{constructor(e){super("bytes",e)}decode(e){return e.coerce(this.name,O(super.decode(e)))}}class ot extends fe{constructor(e,t){let r="bytes"+String(e);super(r,r,t,!1),this.size=e}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(e,t){let r=_(t);return r.length!==this.size&&this._throwError("incorrect data length",t),e.writeBytes(r)}decode(e){return e.coerce(this.name,O(e.readBytes(this.size)))}}class at extends fe{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return null!=t&&this._throwError("not null",t),e.writeBytes([])}decode(e){return e.readBytes(0),e.coerce(this.name,null)}}const ct=W.from(-1),ut=W.from(0),lt=W.from(1),ht=W.from(2),dt=W.from("1000000000000000000"),ft=W.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),pt=W.from("-0x8000000000000000000000000000000000000000000000000000000000000000"),mt=W.from("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class gt extends fe{constructor(e,t,r){const n=(t?"int":"uint")+8*e;super(n,n,r,!1),this.size=e,this.signed=t}defaultValue(){return 0}encode(e,t){let r=W.from(t),n=ft.mask(8*e.wordSize);if(this.signed){let e=n.mask(8*this.size-1);(r.gt(e)||r.lt(e.add(lt).mul(ct)))&&this._throwError("value out-of-bounds",t)}else(r.lt(ut)||r.gt(n.mask(8*this.size)))&&this._throwError("value out-of-bounds",t);return r=r.toTwos(8*this.size).mask(8*this.size),this.signed&&(r=r.fromTwos(8*this.size).toTwos(8*e.wordSize)),e.writeValue(r)}decode(e){let t=e.readValue().mask(8*this.size);return this.signed&&(t=t.fromTwos(8*this.size)),e.coerce(this.name,t)}}class yt extends it{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,je(t))}decode(e){return We(super.decode(e))}}class vt extends fe{constructor(e,t){let r=!1;const n=[];e.forEach(e=>{e.dynamic&&(r=!0),n.push(e.type)}),super("tuple","tuple("+n.join(",")+")",t,r),this.coders=e}defaultValue(){const e=[];this.coders.forEach(t=>{e.push(t.defaultValue())});const t=this.coders.reduce((e,t)=>{const r=t.localName;return r&&(e[r]||(e[r]=0),e[r]++),e},{});return this.coders.forEach((r,n)=>{let i=r.localName;i&&1===t[i]&&("length"===i&&(i="_length"),null==e[i]&&(e[i]=e[n]))}),Object.freeze(e)}encode(e,t){return et(e,this.coders,t)}decode(e){return e.coerce(this.name,tt(e,this.coders))}}const bt=new v(le),wt={};let Et={calldata:!0,memory:!0,storage:!0},At={calldata:!0,memory:!0};function kt(e,t){if("bytes"===e||"string"===e){if(Et[t])return!0}else if("address"===e){if("payable"===t)return!0}else if((e.indexOf("[")>=0||"tuple"===e)&&At[t])return!0;return(Et[t]||"payable"===t)&&bt.throwArgumentError("invalid modifier","name",t),!1}function xt(e,t){for(let r in t)ee(e,r,t[r])}const _t=Object.freeze({sighash:"sighash",minimal:"minimal",full:"full",json:"json"}),Tt=new RegExp(/^(.*)\[([0-9]*)\]$/);class St{constructor(e,t){e!==wt&&bt.throwError("use fromString",v.errors.UNSUPPORTED_OPERATION,{operation:"new ParamType()"}),xt(this,t);let r=this.type.match(Tt);xt(this,r?{arrayLength:parseInt(r[2]||"-1"),arrayChildren:St.fromObject({type:r[1],components:this.components}),baseType:"array"}:{arrayLength:null,arrayChildren:null,baseType:null!=this.components?"tuple":this.type}),this._isParamType=!0,Object.freeze(this)}format(e){if(e||(e=_t.sighash),_t[e]||bt.throwArgumentError("invalid format type","format",e),e===_t.json){let t={type:"tuple"===this.baseType?"tuple":this.type,name:this.name||void 0};return"boolean"==typeof this.indexed&&(t.indexed=this.indexed),this.components&&(t.components=this.components.map(t=>JSON.parse(t.format(e)))),JSON.stringify(t)}let t="";return"array"===this.baseType?(t+=this.arrayChildren.format(e),t+="["+(this.arrayLength<0?"":String(this.arrayLength))+"]"):"tuple"===this.baseType?(e!==_t.sighash&&(t+=this.type),t+="("+this.components.map(t=>t.format(e)).join(e===_t.full?", ":",")+")"):t+=this.type,e!==_t.sighash&&(!0===this.indexed&&(t+=" indexed"),e===_t.full&&this.name&&(t+=" "+this.name)),t}static from(e,t){return"string"==typeof e?St.fromString(e,t):St.fromObject(e)}static fromObject(e){return St.isParamType(e)?e:new St(wt,{name:e.name||null,type:Ut(e.type),indexed:null==e.indexed?null:!!e.indexed,components:e.components?e.components.map(St.fromObject):null})}static fromString(e,t){return r=function(e,t){let r=e;function n(t){bt.throwArgumentError(`unexpected character at position ${t}`,"param",e)}function i(e){let r={type:"",name:"",parent:e,state:{allowType:!0}};return t&&(r.indexed=!1),r}e=e.replace(/\s/g," ");let s={type:"",name:"",state:{allowType:!0}},o=s;for(let r=0;r<e.length;r++){let s=e[r];switch(s){case"(":o.state.allowType&&""===o.type?o.type="tuple":o.state.allowParams||n(r),o.state.allowType=!1,o.type=Ut(o.type),o.components=[i(o)],o=o.components[0];break;case")":delete o.state,"indexed"===o.name&&(t||n(r),o.indexed=!0,o.name=""),kt(o.type,o.name)&&(o.name=""),o.type=Ut(o.type);let e=o;o=o.parent,o||n(r),delete e.parent,o.state.allowParams=!1,o.state.allowName=!0,o.state.allowArray=!0;break;case",":delete o.state,"indexed"===o.name&&(t||n(r),o.indexed=!0,o.name=""),kt(o.type,o.name)&&(o.name=""),o.type=Ut(o.type);let a=i(o.parent);o.parent.components.push(a),delete o.parent,o=a;break;case" ":o.state.allowType&&""!==o.type&&(o.type=Ut(o.type),delete o.state.allowType,o.state.allowName=!0,o.state.allowParams=!0),o.state.allowName&&""!==o.name&&("indexed"===o.name?(t||n(r),o.indexed&&n(r),o.indexed=!0,o.name=""):kt(o.type,o.name)?o.name="":o.state.allowName=!1);break;case"[":o.state.allowArray||n(r),o.type+=s,o.state.allowArray=!1,o.state.allowName=!1,o.state.readArray=!0;break;case"]":o.state.readArray||n(r),o.type+=s,o.state.readArray=!1,o.state.allowArray=!0,o.state.allowName=!0;break;default:o.state.allowType?(o.type+=s,o.state.allowParams=!0,o.state.allowArray=!0):o.state.allowName?(o.name+=s,delete o.state.allowArray):o.state.readArray?o.type+=s:n(r)}}return o.parent&&bt.throwArgumentError("unexpected eof","param",e),delete s.state,"indexed"===o.name?(t||n(r.length-7),o.indexed&&n(r.length-7),o.indexed=!0,o.name=""):kt(o.type,o.name)&&(o.name=""),s.type=Ut(s.type),s}(e,!!t),St.fromObject({name:r.name,type:r.type,indexed:r.indexed,components:r.components});var r}static isParamType(e){return!(null==e||!e._isParamType)}}function It(e,t){return function(e){e=e.trim();let t=[],r="",n=0;for(let i=0;i<e.length;i++){let s=e[i];","===s&&0===n?(t.push(r),r=""):(r+=s,"("===s?n++:")"===s&&(n--,-1===n&&bt.throwArgumentError("unbalanced parenthesis","value",e)))}return r&&t.push(r),t}(e).map(e=>St.fromString(e,t))}class Nt{constructor(e,t){e!==wt&&bt.throwError("use a static from method",v.errors.UNSUPPORTED_OPERATION,{operation:"new Fragment()"}),xt(this,t),this._isFragment=!0,Object.freeze(this)}static from(e){return Nt.isFragment(e)?e:"string"==typeof e?Nt.fromString(e):Nt.fromObject(e)}static fromObject(e){if(Nt.isFragment(e))return e;switch(e.type){case"function":return Dt.fromObject(e);case"event":return Rt.fromObject(e);case"constructor":return Mt.fromObject(e);case"error":return Lt.fromObject(e);case"fallback":case"receive":return null}return bt.throwArgumentError("invalid fragment object","value",e)}static fromString(e){return"event"===(e=(e=(e=e.replace(/\s/g," ")).replace(/\(/g," (").replace(/\)/g,") ").replace(/\s+/g," ")).trim()).split(" ")[0]?Rt.fromString(e.substring(5).trim()):"function"===e.split(" ")[0]?Dt.fromString(e.substring(8).trim()):"constructor"===e.split("(")[0].trim()?Mt.fromString(e.trim()):"error"===e.split(" ")[0]?Lt.fromString(e.substring(5).trim()):bt.throwArgumentError("unsupported fragment","value",e)}static isFragment(e){return!(!e||!e._isFragment)}}class Rt extends Nt{format(e){if(e||(e=_t.sighash),_t[e]||bt.throwArgumentError("invalid format type","format",e),e===_t.json)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});let t="";return e!==_t.sighash&&(t+="event "),t+=this.name+"("+this.inputs.map(t=>t.format(e)).join(e===_t.full?", ":",")+") ",e!==_t.sighash&&this.anonymous&&(t+="anonymous "),t.trim()}static from(e){return"string"==typeof e?Rt.fromString(e):Rt.fromObject(e)}static fromObject(e){if(Rt.isEventFragment(e))return e;"event"!==e.type&&bt.throwArgumentError("invalid event object","value",e);const t={name:$t(e.name),anonymous:e.anonymous,inputs:e.inputs?e.inputs.map(St.fromObject):[],type:"event"};return new Rt(wt,t)}static fromString(e){let t=e.match(Ht);t||bt.throwArgumentError("invalid event string","value",e);let r=!1;return t[3].split(" ").forEach(e=>{switch(e.trim()){case"anonymous":r=!0;break;case"":break;default:bt.warn("unknown modifier: "+e)}}),Rt.fromObject({name:t[1].trim(),anonymous:r,inputs:It(t[2],!0),type:"event"})}static isEventFragment(e){return e&&e._isFragment&&"event"===e.type}}function Ot(e,t){t.gas=null;let r=e.split("@");return 1!==r.length?(r.length>2&&bt.throwArgumentError("invalid human-readable ABI signature","value",e),r[1].match(/^[0-9]+$/)||bt.throwArgumentError("invalid human-readable ABI signature gas","value",e),t.gas=W.from(r[1]),r[0]):e}function Ct(e,t){t.constant=!1,t.payable=!1,t.stateMutability="nonpayable",e.split(" ").forEach(e=>{switch(e.trim()){case"constant":t.constant=!0;break;case"payable":t.payable=!0,t.stateMutability="payable";break;case"nonpayable":t.payable=!1,t.stateMutability="nonpayable";break;case"pure":t.constant=!0,t.stateMutability="pure";break;case"view":t.constant=!0,t.stateMutability="view";break;case"external":case"public":case"":break;default:console.log("unknown modifier: "+e)}})}function Pt(e){let t={constant:!1,payable:!0,stateMutability:"payable"};return null!=e.stateMutability?(t.stateMutability=e.stateMutability,t.constant="view"===t.stateMutability||"pure"===t.stateMutability,null!=e.constant&&!!e.constant!==t.constant&&bt.throwArgumentError("cannot have constant function with mutability "+t.stateMutability,"value",e),t.payable="payable"===t.stateMutability,null!=e.payable&&!!e.payable!==t.payable&&bt.throwArgumentError("cannot have payable function with mutability "+t.stateMutability,"value",e)):null!=e.payable?(t.payable=!!e.payable,null!=e.constant||t.payable||"constructor"===e.type||bt.throwArgumentError("unable to determine stateMutability","value",e),t.constant=!!e.constant,t.constant?t.stateMutability="view":t.stateMutability=t.payable?"payable":"nonpayable",t.payable&&t.constant&&bt.throwArgumentError("cannot have constant payable function","value",e)):null!=e.constant?(t.constant=!!e.constant,t.payable=!t.constant,t.stateMutability=t.constant?"view":"payable"):"constructor"!==e.type&&bt.throwArgumentError("unable to determine stateMutability","value",e),t}class Mt extends Nt{format(e){if(e||(e=_t.sighash),_t[e]||bt.throwArgumentError("invalid format type","format",e),e===_t.json)return JSON.stringify({type:"constructor",stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:this.gas?this.gas.toNumber():void 0,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});e===_t.sighash&&bt.throwError("cannot format a constructor for sighash",v.errors.UNSUPPORTED_OPERATION,{operation:"format(sighash)"});let t="constructor("+this.inputs.map(t=>t.format(e)).join(e===_t.full?", ":",")+") ";return this.stateMutability&&"nonpayable"!==this.stateMutability&&(t+=this.stateMutability+" "),t.trim()}static from(e){return"string"==typeof e?Mt.fromString(e):Mt.fromObject(e)}static fromObject(e){if(Mt.isConstructorFragment(e))return e;"constructor"!==e.type&&bt.throwArgumentError("invalid constructor object","value",e);let t=Pt(e);t.constant&&bt.throwArgumentError("constructor cannot be constant","value",e);const r={name:null,type:e.type,inputs:e.inputs?e.inputs.map(St.fromObject):[],payable:t.payable,stateMutability:t.stateMutability,gas:e.gas?W.from(e.gas):null};return new Mt(wt,r)}static fromString(e){let t={type:"constructor"},r=(e=Ot(e,t)).match(Ht);return r&&"constructor"===r[1].trim()||bt.throwArgumentError("invalid constructor string","value",e),t.inputs=It(r[2].trim(),!1),Ct(r[3].trim(),t),Mt.fromObject(t)}static isConstructorFragment(e){return e&&e._isFragment&&"constructor"===e.type}}class Dt extends Mt{format(e){if(e||(e=_t.sighash),_t[e]||bt.throwArgumentError("invalid format type","format",e),e===_t.json)return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:this.gas?this.gas.toNumber():void 0,inputs:this.inputs.map(t=>JSON.parse(t.format(e))),outputs:this.outputs.map(t=>JSON.parse(t.format(e)))});let t="";return e!==_t.sighash&&(t+="function "),t+=this.name+"("+this.inputs.map(t=>t.format(e)).join(e===_t.full?", ":",")+") ",e!==_t.sighash&&(this.stateMutability?"nonpayable"!==this.stateMutability&&(t+=this.stateMutability+" "):this.constant&&(t+="view "),this.outputs&&this.outputs.length&&(t+="returns ("+this.outputs.map(t=>t.format(e)).join(", ")+") "),null!=this.gas&&(t+="@"+this.gas.toString()+" ")),t.trim()}static from(e){return"string"==typeof e?Dt.fromString(e):Dt.fromObject(e)}static fromObject(e){if(Dt.isFunctionFragment(e))return e;"function"!==e.type&&bt.throwArgumentError("invalid function object","value",e);let t=Pt(e);const r={type:e.type,name:$t(e.name),constant:t.constant,inputs:e.inputs?e.inputs.map(St.fromObject):[],outputs:e.outputs?e.outputs.map(St.fromObject):[],payable:t.payable,stateMutability:t.stateMutability,gas:e.gas?W.from(e.gas):null};return new Dt(wt,r)}static fromString(e){let t={type:"function"},r=(e=Ot(e,t)).split(" returns ");r.length>2&&bt.throwArgumentError("invalid function string","value",e);let n=r[0].match(Ht);if(n||bt.throwArgumentError("invalid function signature","value",e),t.name=n[1].trim(),t.name&&$t(t.name),t.inputs=It(n[2],!1),Ct(n[3].trim(),t),r.length>1){let n=r[1].match(Ht);""==n[1].trim()&&""==n[3].trim()||bt.throwArgumentError("unexpected tokens","value",e),t.outputs=It(n[2],!1)}else t.outputs=[];return Dt.fromObject(t)}static isFunctionFragment(e){return e&&e._isFragment&&"function"===e.type}}function Bt(e){const t=e.format();return"Error(string)"!==t&&"Panic(uint256)"!==t||bt.throwArgumentError(`cannot specify user defined ${t} error`,"fragment",e),e}class Lt extends Nt{format(e){if(e||(e=_t.sighash),_t[e]||bt.throwArgumentError("invalid format type","format",e),e===_t.json)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});let t="";return e!==_t.sighash&&(t+="error "),t+=this.name+"("+this.inputs.map(t=>t.format(e)).join(e===_t.full?", ":",")+") ",t.trim()}static from(e){return"string"==typeof e?Lt.fromString(e):Lt.fromObject(e)}static fromObject(e){if(Lt.isErrorFragment(e))return e;"error"!==e.type&&bt.throwArgumentError("invalid error object","value",e);const t={type:e.type,name:$t(e.name),inputs:e.inputs?e.inputs.map(St.fromObject):[]};return Bt(new Lt(wt,t))}static fromString(e){let t={type:"error"},r=e.match(Ht);return r||bt.throwArgumentError("invalid error signature","value",e),t.name=r[1].trim(),t.name&&$t(t.name),t.inputs=It(r[2],!1),Bt(Lt.fromObject(t))}static isErrorFragment(e){return e&&e._isFragment&&"error"===e.type}}function Ut(e){return e.match(/^uint($|[^1-9])/)?e="uint256"+e.substring(4):e.match(/^int($|[^1-9])/)&&(e="int256"+e.substring(3)),e}const Ft=new RegExp("^[a-zA-Z$_][a-zA-Z0-9$_]*$");function $t(e){return e&&e.match(Ft)||bt.throwArgumentError(`invalid identifier "${e}"`,"value",e),e}const Ht=new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"),Kt=new v(le),qt=new RegExp(/^bytes([0-9]*)$/),jt=new RegExp(/^(u?int)([0-9]*)$/);class zt{constructor(e){ee(this,"coerceFunc",e||null)}_getCoder(e){switch(e.baseType){case"address":return new Ye(e.name);case"bool":return new nt(e.name);case"string":return new yt(e.name);case"bytes":return new st(e.name);case"array":return new rt(this._getCoder(e.arrayChildren),e.arrayLength,e.name);case"tuple":return new vt((e.components||[]).map(e=>this._getCoder(e)),e.name);case"":return new at(e.name)}let t=e.type.match(jt);if(t){let r=parseInt(t[2]||"256");return(0===r||r>256||r%8!=0)&&Kt.throwArgumentError("invalid "+t[1]+" bit length","param",e),new gt(r/8,"int"===t[1],e.name)}if(t=e.type.match(qt),t){let r=parseInt(t[1]);return(0===r||r>32)&&Kt.throwArgumentError("invalid bytes length","param",e),new ot(r,e.name)}return Kt.throwArgumentError("invalid type","type",e.type)}_getWordSize(){return 32}_getReader(e,t){return new me(e,this._getWordSize(),this.coerceFunc,t)}_getWriter(){return new pe(this._getWordSize())}getDefaultValue(e){const t=e.map(e=>this._getCoder(St.from(e)));return new vt(t,"_").defaultValue()}encode(e,t){e.length!==t.length&&Kt.throwError("types/values length mismatch",v.errors.INVALID_ARGUMENT,{count:{types:e.length,values:t.length},value:{types:e,values:t}});const r=e.map(e=>this._getCoder(St.from(e))),n=new vt(r,"_"),i=this._getWriter();return n.encode(i,t),i.data}decode(e,t,r){const n=e.map(e=>this._getCoder(St.from(e)));return new vt(n,"_").decode(this._getReader(_(t),r))}}const Vt=new zt,Gt=new v(le);class Wt extends ue{}class Jt extends ue{}class Zt extends ue{}class Yt extends ue{static isIndexed(e){return!(!e||!e._isIndexed)}}const Qt={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:!0},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"]}};function Xt(e,t){const r=new Error(`deferred error during ABI decoding triggered accessing ${e}`);return r.error=t,r}class er{constructor(e){let t=[];t="string"==typeof e?JSON.parse(e):e,ee(this,"fragments",t.map(e=>Nt.from(e)).filter(e=>null!=e)),ee(this,"_abiCoder",te(new.target,"getAbiCoder")()),ee(this,"functions",{}),ee(this,"errors",{}),ee(this,"events",{}),ee(this,"structs",{}),this.fragments.forEach(e=>{let t=null;switch(e.type){case"constructor":return this.deploy?void Gt.warn("duplicate definition - constructor"):void ee(this,"deploy",e);case"function":t=this.functions;break;case"event":t=this.events;break;case"error":t=this.errors;break;default:return}let r=e.format();t[r]?Gt.warn("duplicate definition - "+r):t[r]=e}),this.deploy||ee(this,"deploy",Mt.from({payable:!1,type:"constructor"})),ee(this,"_isInterface",!0)}format(e){e||(e=_t.full),e===_t.sighash&&Gt.throwArgumentError("interface does not support formatting sighash","format",e);const t=this.fragments.map(t=>t.format(e));return e===_t.json?JSON.stringify(t.map(e=>JSON.parse(e))):t}static getAbiCoder(){return Vt}static getAddress(e){return Pe(e)}static getSighash(e){return P(Ze(e.format()),0,4)}static getEventTopic(e){return Ze(e.format())}getFunction(e){if(N(e)){for(const t in this.functions)if(e===this.getSighash(t))return this.functions[t];Gt.throwArgumentError("no matching function","sighash",e)}if(-1===e.indexOf("(")){const t=e.trim(),r=Object.keys(this.functions).filter(e=>e.split("(")[0]===t);return 0===r.length?Gt.throwArgumentError("no matching function","name",t):r.length>1&&Gt.throwArgumentError("multiple matching functions","name",t),this.functions[r[0]]}const t=this.functions[Dt.fromString(e).format()];return t||Gt.throwArgumentError("no matching function","signature",e),t}getEvent(e){if(N(e)){const t=e.toLowerCase();for(const e in this.events)if(t===this.getEventTopic(e))return this.events[e];Gt.throwArgumentError("no matching event","topichash",t)}if(-1===e.indexOf("(")){const t=e.trim(),r=Object.keys(this.events).filter(e=>e.split("(")[0]===t);return 0===r.length?Gt.throwArgumentError("no matching event","name",t):r.length>1&&Gt.throwArgumentError("multiple matching events","name",t),this.events[r[0]]}const t=this.events[Rt.fromString(e).format()];return t||Gt.throwArgumentError("no matching event","signature",e),t}getError(e){if(N(e)){const t=te(this.constructor,"getSighash");for(const r in this.errors)if(e===t(this.errors[r]))return this.errors[r];Gt.throwArgumentError("no matching error","sighash",e)}if(-1===e.indexOf("(")){const t=e.trim(),r=Object.keys(this.errors).filter(e=>e.split("(")[0]===t);return 0===r.length?Gt.throwArgumentError("no matching error","name",t):r.length>1&&Gt.throwArgumentError("multiple matching errors","name",t),this.errors[r[0]]}const t=this.errors[Dt.fromString(e).format()];return t||Gt.throwArgumentError("no matching error","signature",e),t}getSighash(e){if("string"==typeof e)try{e=this.getFunction(e)}catch(t){try{e=this.getError(e)}catch(e){throw t}}return te(this.constructor,"getSighash")(e)}getEventTopic(e){return"string"==typeof e&&(e=this.getEvent(e)),te(this.constructor,"getEventTopic")(e)}_decodeParams(e,t){return this._abiCoder.decode(e,t)}_encodeParams(e,t){return this._abiCoder.encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){"string"==typeof e&&(e=this.getError(e));const r=_(t);return O(r.slice(0,4))!==this.getSighash(e)&&Gt.throwArgumentError(`data signature does not match error ${e.name}.`,"data",O(r)),this._decodeParams(e.inputs,r.slice(4))}encodeErrorResult(e,t){return"string"==typeof e&&(e=this.getError(e)),O(T([this.getSighash(e),this._encodeParams(e.inputs,t||[])]))}decodeFunctionData(e,t){"string"==typeof e&&(e=this.getFunction(e));const r=_(t);return O(r.slice(0,4))!==this.getSighash(e)&&Gt.throwArgumentError(`data signature does not match function ${e.name}.`,"data",O(r)),this._decodeParams(e.inputs,r.slice(4))}encodeFunctionData(e,t){return"string"==typeof e&&(e=this.getFunction(e)),O(T([this.getSighash(e),this._encodeParams(e.inputs,t||[])]))}decodeFunctionResult(e,t){"string"==typeof e&&(e=this.getFunction(e));let r=_(t),n=null,i="",s=null,o=null,a=null;switch(r.length%this._abiCoder._getWordSize()){case 0:try{return this._abiCoder.decode(e.outputs,r)}catch(e){}break;case 4:{const e=O(r.slice(0,4)),t=Qt[e];if(t)s=this._abiCoder.decode(t.inputs,r.slice(4)),o=t.name,a=t.signature,t.reason&&(n=s[0]),"Error"===o?i=`; VM Exception while processing transaction: reverted with reason string ${JSON.stringify(s[0])}`:"Panic"===o&&(i=`; VM Exception while processing transaction: reverted with panic code ${s[0]}`);else try{const t=this.getError(e);s=this._abiCoder.decode(t.inputs,r.slice(4)),o=t.name,a=t.format()}catch(e){}break}}return Gt.throwError("call revert exception"+i,v.errors.CALL_EXCEPTION,{method:e.format(),data:O(t),errorArgs:s,errorName:o,errorSignature:a,reason:n})}encodeFunctionResult(e,t){return"string"==typeof e&&(e=this.getFunction(e)),O(this._abiCoder.encode(e.outputs,t||[]))}encodeFilterTopics(e,t){"string"==typeof e&&(e=this.getEvent(e)),t.length>e.inputs.length&&Gt.throwError("too many arguments for "+e.format(),v.errors.UNEXPECTED_ARGUMENT,{argument:"values",value:t});let r=[];e.anonymous||r.push(this.getEventTopic(e));const n=(e,t)=>"string"===e.type?Ze(t):"bytes"===e.type?ve(O(t)):("bool"===e.type&&"boolean"==typeof t&&(t=t?"0x01":"0x00"),e.type.match(/^u?int/)&&(t=W.from(t).toHexString()),"address"===e.type&&this._abiCoder.encode(["address"],[t]),L(O(t),32));for(t.forEach((t,i)=>{let s=e.inputs[i];s.indexed?null==t?r.push(null):"array"===s.baseType||"tuple"===s.baseType?Gt.throwArgumentError("filtering with tuples or arrays not supported","contract."+s.name,t):Array.isArray(t)?r.push(t.map(e=>n(s,e))):r.push(n(s,t)):null!=t&&Gt.throwArgumentError("cannot filter non-indexed parameters; must be null","contract."+s.name,t)});r.length&&null===r[r.length-1];)r.pop();return r}encodeEventLog(e,t){"string"==typeof e&&(e=this.getEvent(e));const r=[],n=[],i=[];return e.anonymous||r.push(this.getEventTopic(e)),t.length!==e.inputs.length&&Gt.throwArgumentError("event arguments/values mismatch","values",t),e.inputs.forEach((e,s)=>{const o=t[s];if(e.indexed)if("string"===e.type)r.push(Ze(o));else if("bytes"===e.type)r.push(ve(o));else{if("tuple"===e.baseType||"array"===e.baseType)throw new Error("not implemented");r.push(this._abiCoder.encode([e.type],[o]))}else n.push(e),i.push(o)}),{data:this._abiCoder.encode(n,i),topics:r}}decodeEventLog(e,t,r){if("string"==typeof e&&(e=this.getEvent(e)),null!=r&&!e.anonymous){let t=this.getEventTopic(e);N(r[0],32)&&r[0].toLowerCase()===t||Gt.throwError("fragment/topic mismatch",v.errors.INVALID_ARGUMENT,{argument:"topics[0]",expected:t,value:r[0]}),r=r.slice(1)}let n=[],i=[],s=[];e.inputs.forEach((e,t)=>{e.indexed?"string"===e.type||"bytes"===e.type||"tuple"===e.baseType||"array"===e.baseType?(n.push(St.fromObject({type:"bytes32",name:e.name})),s.push(!0)):(n.push(e),s.push(!1)):(i.push(e),s.push(!1))});let o=null!=r?this._abiCoder.decode(n,T(r)):null,a=this._abiCoder.decode(i,t,!0),c=[],u=0,l=0;e.inputs.forEach((e,t)=>{if(e.indexed)if(null==o)c[t]=new Yt({_isIndexed:!0,hash:null});else if(s[t])c[t]=new Yt({_isIndexed:!0,hash:o[l++]});else try{c[t]=o[l++]}catch(e){c[t]=e}else try{c[t]=a[u++]}catch(e){c[t]=e}if(e.name&&null==c[e.name]){const r=c[t];r instanceof Error?Object.defineProperty(c,e.name,{enumerable:!0,get:()=>{throw Xt(`property ${JSON.stringify(e.name)}`,r)}}):c[e.name]=r}});for(let e=0;e<c.length;e++){const t=c[e];t instanceof Error&&Object.defineProperty(c,e,{enumerable:!0,get:()=>{throw Xt(`index ${e}`,t)}})}return Object.freeze(c)}parseTransaction(e){let t=this.getFunction(e.data.substring(0,10).toLowerCase());return t?new Jt({args:this._abiCoder.decode(t.inputs,"0x"+e.data.substring(10)),functionFragment:t,name:t.name,signature:t.format(),sighash:this.getSighash(t),value:W.from(e.value||"0")}):null}parseLog(e){let t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new Wt({eventFragment:t,name:t.name,signature:t.format(),topic:this.getEventTopic(t),args:this.decodeEventLog(t,e.data,e.topics)})}parseError(e){const t=O(e);let r=this.getError(t.substring(0,10).toLowerCase());return r?new Zt({args:this._abiCoder.decode(r.inputs,"0x"+t.substring(10)),errorFragment:r,name:r.name,signature:r.format(),sighash:this.getSighash(r)}):null}static isInterface(e){return!(!e||!e._isInterface)}}const tr=new v("abstract-provider/5.8.0");class rr extends ue{static isForkEvent(e){return!(!e||!e._isForkEvent)}}class nr{constructor(){tr.checkAbstract(new.target,nr),ee(this,"_isProvider",!0)}getFeeData(){return e=this,t=void 0,n=function*(){const{block:e,gasPrice:t}=yield re({block:this.getBlock("latest"),gasPrice:this.getGasPrice().catch(e=>null)});let r=null,n=null,i=null;return e&&e.baseFeePerGas&&(r=e.baseFeePerGas,i=W.from("1500000000"),n=e.baseFeePerGas.mul(2).add(i)),{lastBaseFeePerGas:r,maxFeePerGas:n,maxPriorityFeePerGas:i,gasPrice:t}},new((r=void 0)||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())});var e,t,r,n}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}static isProvider(e){return!(!e||!e._isProvider)}}var ir=function(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};const sr=new v("abstract-signer/5.8.0"),or=["accessList","ccipReadEnabled","chainId","customData","data","from","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","nonce","to","type","value"],ar=[v.errors.INSUFFICIENT_FUNDS,v.errors.NONCE_EXPIRED,v.errors.REPLACEMENT_UNDERPRICED];class cr{constructor(){sr.checkAbstract(new.target,cr),ee(this,"_isSigner",!0)}getBalance(e){return ir(this,void 0,void 0,function*(){return this._checkProvider("getBalance"),yield this.provider.getBalance(this.getAddress(),e)})}getTransactionCount(e){return ir(this,void 0,void 0,function*(){return this._checkProvider("getTransactionCount"),yield this.provider.getTransactionCount(this.getAddress(),e)})}estimateGas(e){return ir(this,void 0,void 0,function*(){this._checkProvider("estimateGas");const t=yield re(this.checkTransaction(e));return yield this.provider.estimateGas(t)})}call(e,t){return ir(this,void 0,void 0,function*(){this._checkProvider("call");const r=yield re(this.checkTransaction(e));return yield this.provider.call(r,t)})}sendTransaction(e){return ir(this,void 0,void 0,function*(){this._checkProvider("sendTransaction");const t=yield this.populateTransaction(e),r=yield this.signTransaction(t);return yield this.provider.sendTransaction(r)})}getChainId(){return ir(this,void 0,void 0,function*(){return this._checkProvider("getChainId"),(yield this.provider.getNetwork()).chainId})}getGasPrice(){return ir(this,void 0,void 0,function*(){return this._checkProvider("getGasPrice"),yield this.provider.getGasPrice()})}getFeeData(){return ir(this,void 0,void 0,function*(){return this._checkProvider("getFeeData"),yield this.provider.getFeeData()})}resolveName(e){return ir(this,void 0,void 0,function*(){return this._checkProvider("resolveName"),yield this.provider.resolveName(e)})}checkTransaction(e){for(const t in e)-1===or.indexOf(t)&&sr.throwArgumentError("invalid transaction key: "+t,"transaction",e);const t=ie(e);return null==t.from?t.from=this.getAddress():t.from=Promise.all([Promise.resolve(t.from),this.getAddress()]).then(t=>(t[0].toLowerCase()!==t[1].toLowerCase()&&sr.throwArgumentError("from address mismatch","transaction",e),t[0])),t}populateTransaction(e){return ir(this,void 0,void 0,function*(){const t=yield re(this.checkTransaction(e));null!=t.to&&(t.to=Promise.resolve(t.to).then(e=>ir(this,void 0,void 0,function*(){if(null==e)return null;const t=yield this.resolveName(e);return null==t&&sr.throwArgumentError("provided ENS name resolves to null","tx.to",e),t})),t.to.catch(e=>{}));const r=null!=t.maxFeePerGas||null!=t.maxPriorityFeePerGas;if(null==t.gasPrice||2!==t.type&&!r?0!==t.type&&1!==t.type||!r||sr.throwArgumentError("pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","transaction",e):sr.throwArgumentError("eip-1559 transaction do not support gasPrice","transaction",e),2!==t.type&&null!=t.type||null==t.maxFeePerGas||null==t.maxPriorityFeePerGas)if(0===t.type||1===t.type)null==t.gasPrice&&(t.gasPrice=this.getGasPrice());else{const e=yield this.getFeeData();if(null==t.type)if(null!=e.maxFeePerGas&&null!=e.maxPriorityFeePerGas)if(t.type=2,null!=t.gasPrice){const e=t.gasPrice;delete t.gasPrice,t.maxFeePerGas=e,t.maxPriorityFeePerGas=e}else null==t.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),null==t.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas);else null!=e.gasPrice?(r&&sr.throwError("network does not support EIP-1559",v.errors.UNSUPPORTED_OPERATION,{operation:"populateTransaction"}),null==t.gasPrice&&(t.gasPrice=e.gasPrice),t.type=0):sr.throwError("failed to get consistent fee data",v.errors.UNSUPPORTED_OPERATION,{operation:"signer.getFeeData"});else 2===t.type&&(null==t.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),null==t.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas))}else t.type=2;return null==t.nonce&&(t.nonce=this.getTransactionCount("pending")),null==t.gasLimit&&(t.gasLimit=this.estimateGas(t).catch(e=>{if(ar.indexOf(e.code)>=0)throw e;return sr.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",v.errors.UNPREDICTABLE_GAS_LIMIT,{error:e,tx:t})})),null==t.chainId?t.chainId=this.getChainId():t.chainId=Promise.all([Promise.resolve(t.chainId),this.getChainId()]).then(t=>(0!==t[1]&&t[0]!==t[1]&&sr.throwArgumentError("chainId address mismatch","transaction",e),t[0])),yield re(t)})}_checkProvider(e){this.provider||sr.throwError("missing provider",v.errors.UNSUPPORTED_OPERATION,{operation:e||"_checkProvider"})}static isSigner(e){return!(!e||!e._isSigner)}}class ur extends cr{constructor(e,t){super(),ee(this,"address",e),ee(this,"provider",t||null)}getAddress(){return Promise.resolve(this.address)}_fail(e,t){return Promise.resolve().then(()=>{sr.throwError(e,v.errors.UNSUPPORTED_OPERATION,{operation:t})})}signMessage(e){return this._fail("VoidSigner cannot sign messages","signMessage")}signTransaction(e){return this._fail("VoidSigner cannot sign transactions","signTransaction")}_signTypedData(e,t,r){return this._fail("VoidSigner cannot sign typed data","signTypedData")}connect(e){return new ur(this.address,e)}}var lr=r(9499),hr=r.n(lr);function dr(e,t,r){return r={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&r.path)}},e(r,r.exports),r.exports}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self;var fr=pr;function pr(e,t){if(!e)throw new Error(t||"Assertion failed")}pr.equal=function(e,t,r){if(e!=t)throw new Error(r||"Assertion failed: "+e+" != "+t)};var mr=dr(function(e,t){var r=t;function n(e){return 1===e.length?"0"+e:e}function i(e){for(var t="",r=0;r<e.length;r++)t+=n(e[r].toString(16));return t}r.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"!=typeof e){for(var n=0;n<e.length;n++)r[n]=0|e[n];return r}if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),n=0;n<e.length;n+=2)r.push(parseInt(e[n]+e[n+1],16));else for(n=0;n<e.length;n++){var i=e.charCodeAt(n),s=i>>8,o=255&i;s?r.push(s,o):r.push(o)}return r},r.zero2=n,r.toHex=i,r.encode=function(e,t){return"hex"===t?i(e):e}}),gr=dr(function(e,t){var r=t;r.assert=fr,r.toArray=mr.toArray,r.zero2=mr.zero2,r.toHex=mr.toHex,r.encode=mr.encode,r.getNAF=function(e,t,r){var n,i=new Array(Math.max(e.bitLength(),r)+1);for(n=0;n<i.length;n+=1)i[n]=0;var s=1<<t+1,o=e.clone();for(n=0;n<i.length;n++){var a,c=o.andln(s-1);o.isOdd()?(a=c>(s>>1)-1?(s>>1)-c:c,o.isubn(a)):a=0,i[n]=a,o.iushrn(1)}return i},r.getJSF=function(e,t){var r=[[],[]];e=e.clone(),t=t.clone();for(var n,i=0,s=0;e.cmpn(-i)>0||t.cmpn(-s)>0;){var o,a,c=e.andln(3)+i&3,u=t.andln(3)+s&3;3===c&&(c=-1),3===u&&(u=-1),o=1&c?3!=(n=e.andln(7)+i&7)&&5!==n||2!==u?c:-c:0,r[0].push(o),a=1&u?3!=(n=t.andln(7)+s&7)&&5!==n||2!==c?u:-u:0,r[1].push(a),2*i===o+1&&(i=1-i),2*s===a+1&&(s=1-s),e.iushrn(1),t.iushrn(1)}return r},r.cachedProperty=function(e,t,r){var n="_"+t;e.prototype[t]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},r.parseBytes=function(e){return"string"==typeof e?r.toArray(e,"hex"):e},r.intFromLE=function(e){return new(H())(e,"hex","le")}}),yr=gr.getNAF,vr=gr.getJSF,br=gr.assert;function wr(e,t){this.type=e,this.p=new(H())(t.p,16),this.red=t.prime?H().red(t.prime):H().mont(this.p),this.zero=new(H())(0).toRed(this.red),this.one=new(H())(1).toRed(this.red),this.two=new(H())(2).toRed(this.red),this.n=t.n&&new(H())(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Er=wr;function Ar(e,t){this.curve=e,this.type=t,this.precomputed=null}wr.prototype.point=function(){throw new Error("Not implemented")},wr.prototype.validate=function(){throw new Error("Not implemented")},wr.prototype._fixedNafMul=function(e,t){br(e.precomputed);var r=e._getDoubles(),n=yr(t,1,this._bitLength),i=(1<<r.step+1)-(r.step%2==0?2:1);i/=3;var s,o,a=[];for(s=0;s<n.length;s+=r.step){o=0;for(var c=s+r.step-1;c>=s;c--)o=(o<<1)+n[c];a.push(o)}for(var u=this.jpoint(null,null,null),l=this.jpoint(null,null,null),h=i;h>0;h--){for(s=0;s<a.length;s++)(o=a[s])===h?l=l.mixedAdd(r.points[s]):o===-h&&(l=l.mixedAdd(r.points[s].neg()));u=u.add(l)}return u.toP()},wr.prototype._wnafMul=function(e,t){var r=4,n=e._getNAFPoints(r);r=n.wnd;for(var i=n.points,s=yr(t,r,this._bitLength),o=this.jpoint(null,null,null),a=s.length-1;a>=0;a--){for(var c=0;a>=0&&0===s[a];a--)c++;if(a>=0&&c++,o=o.dblp(c),a<0)break;var u=s[a];br(0!==u),o="affine"===e.type?u>0?o.mixedAdd(i[u-1>>1]):o.mixedAdd(i[-u-1>>1].neg()):u>0?o.add(i[u-1>>1]):o.add(i[-u-1>>1].neg())}return"affine"===e.type?o.toP():o},wr.prototype._wnafMulAdd=function(e,t,r,n,i){var s,o,a,c=this._wnafT1,u=this._wnafT2,l=this._wnafT3,h=0;for(s=0;s<n;s++){var d=(a=t[s])._getNAFPoints(e);c[s]=d.wnd,u[s]=d.points}for(s=n-1;s>=1;s-=2){var f=s-1,p=s;if(1===c[f]&&1===c[p]){var m=[t[f],null,null,t[p]];0===t[f].y.cmp(t[p].y)?(m[1]=t[f].add(t[p]),m[2]=t[f].toJ().mixedAdd(t[p].neg())):0===t[f].y.cmp(t[p].y.redNeg())?(m[1]=t[f].toJ().mixedAdd(t[p]),m[2]=t[f].add(t[p].neg())):(m[1]=t[f].toJ().mixedAdd(t[p]),m[2]=t[f].toJ().mixedAdd(t[p].neg()));var g=[-3,-1,-5,-7,0,7,5,1,3],y=vr(r[f],r[p]);for(h=Math.max(y[0].length,h),l[f]=new Array(h),l[p]=new Array(h),o=0;o<h;o++){var v=0|y[0][o],b=0|y[1][o];l[f][o]=g[3*(v+1)+(b+1)],l[p][o]=0,u[f]=m}}else l[f]=yr(r[f],c[f],this._bitLength),l[p]=yr(r[p],c[p],this._bitLength),h=Math.max(l[f].length,h),h=Math.max(l[p].length,h)}var w=this.jpoint(null,null,null),E=this._wnafT4;for(s=h;s>=0;s--){for(var A=0;s>=0;){var k=!0;for(o=0;o<n;o++)E[o]=0|l[o][s],0!==E[o]&&(k=!1);if(!k)break;A++,s--}if(s>=0&&A++,w=w.dblp(A),s<0)break;for(o=0;o<n;o++){var x=E[o];0!==x&&(x>0?a=u[o][x-1>>1]:x<0&&(a=u[o][-x-1>>1].neg()),w="affine"===a.type?w.mixedAdd(a):w.add(a))}}for(s=0;s<n;s++)u[s]=null;return i?w:w.toP()},wr.BasePoint=Ar,Ar.prototype.eq=function(){throw new Error("Not implemented")},Ar.prototype.validate=function(){return this.curve.validate(this)},wr.prototype.decodePoint=function(e,t){e=gr.toArray(e,t);var r=this.p.byteLength();if((4===e[0]||6===e[0]||7===e[0])&&e.length-1==2*r)return 6===e[0]?br(e[e.length-1]%2==0):7===e[0]&&br(e[e.length-1]%2==1),this.point(e.slice(1,1+r),e.slice(1+r,1+2*r));if((2===e[0]||3===e[0])&&e.length-1===r)return this.pointFromX(e.slice(1,1+r),3===e[0]);throw new Error("Unknown point format")},Ar.prototype.encodeCompressed=function(e){return this.encode(e,!0)},Ar.prototype._encode=function(e){var t=this.curve.p.byteLength(),r=this.getX().toArray("be",t);return e?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",t))},Ar.prototype.encode=function(e,t){return gr.encode(this._encode(t),e)},Ar.prototype.precompute=function(e){if(this.precomputed)return this;var t={doubles:null,naf:null,beta:null};return t.naf=this._getNAFPoints(8),t.doubles=this._getDoubles(4,e),t.beta=this._getBeta(),this.precomputed=t,this},Ar.prototype._hasDoubles=function(e){if(!this.precomputed)return!1;var t=this.precomputed.doubles;return!!t&&t.points.length>=Math.ceil((e.bitLength()+1)/t.step)},Ar.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i<t;i+=e){for(var s=0;s<e;s++)n=n.dbl();r.push(n)}return{step:e,points:r}},Ar.prototype._getNAFPoints=function(e){if(this.precomputed&&this.precomputed.naf)return this.precomputed.naf;for(var t=[this],r=(1<<e)-1,n=1===r?null:this.dbl(),i=1;i<r;i++)t[i]=t[i-1].add(n);return{wnd:e,points:t}},Ar.prototype._getBeta=function(){return null},Ar.prototype.dblp=function(e){for(var t=this,r=0;r<e;r++)t=t.dbl();return t};var kr=dr(function(e){"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}}),xr=gr.assert;function _r(e){Er.call(this,"short",e),this.a=new(H())(e.a,16).toRed(this.red),this.b=new(H())(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}kr(_r,Er);var Tr=_r;function Sr(e,t,r,n){Er.BasePoint.call(this,e,"affine"),null===t&&null===r?(this.x=null,this.y=null,this.inf=!0):(this.x=new(H())(t,16),this.y=new(H())(r,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function Ir(e,t,r,n){Er.BasePoint.call(this,e,"jacobian"),null===t&&null===r&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new(H())(0)):(this.x=new(H())(t,16),this.y=new(H())(r,16),this.z=new(H())(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}_r.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,r;if(e.beta)t=new(H())(e.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);t=(t=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(e.lambda)r=new(H())(e.lambda,16);else{var i=this._getEndoRoots(this.n);0===this.g.mul(i[0]).x.cmp(this.g.x.redMul(t))?r=i[0]:(r=i[1],xr(0===this.g.mul(r).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:r,basis:e.basis?e.basis.map(function(e){return{a:new(H())(e.a,16),b:new(H())(e.b,16)}}):this._getEndoBasis(r)}}},_r.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:H().mont(e),r=new(H())(2).toRed(t).redInvm(),n=r.redNeg(),i=new(H())(3).toRed(t).redNeg().redSqrt().redMul(r);return[n.redAdd(i).fromRed(),n.redSub(i).fromRed()]},_r.prototype._getEndoBasis=function(e){for(var t,r,n,i,s,o,a,c,u,l=this.n.ushrn(Math.floor(this.n.bitLength()/2)),h=e,d=this.n.clone(),f=new(H())(1),p=new(H())(0),m=new(H())(0),g=new(H())(1),y=0;0!==h.cmpn(0);){var v=d.div(h);c=d.sub(v.mul(h)),u=m.sub(v.mul(f));var b=g.sub(v.mul(p));if(!n&&c.cmp(l)<0)t=a.neg(),r=f,n=c.neg(),i=u;else if(n&&2===++y)break;a=c,d=h,h=c,m=f,f=u,g=p,p=b}s=c.neg(),o=u;var w=n.sqr().add(i.sqr());return s.sqr().add(o.sqr()).cmp(w)>=0&&(s=t,o=r),n.negative&&(n=n.neg(),i=i.neg()),s.negative&&(s=s.neg(),o=o.neg()),[{a:n,b:i},{a:s,b:o}]},_r.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],n=t[1],i=n.b.mul(e).divRound(this.n),s=r.b.neg().mul(e).divRound(this.n),o=i.mul(r.a),a=s.mul(n.a),c=i.mul(r.b),u=s.mul(n.b);return{k1:e.sub(o).sub(a),k2:c.add(u).neg()}},_r.prototype.pointFromX=function(e,t){(e=new(H())(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(t&&!i||!t&&i)&&(n=n.redNeg()),this.point(e,n)},_r.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,n=this.a.redMul(t),i=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},_r.prototype._endoWnafMulAdd=function(e,t,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,s=0;s<e.length;s++){var o=this._endoSplit(t[s]),a=e[s],c=a._getBeta();o.k1.negative&&(o.k1.ineg(),a=a.neg(!0)),o.k2.negative&&(o.k2.ineg(),c=c.neg(!0)),n[2*s]=a,n[2*s+1]=c,i[2*s]=o.k1,i[2*s+1]=o.k2}for(var u=this._wnafMulAdd(1,n,i,2*s,r),l=0;l<2*s;l++)n[l]=null,i[l]=null;return u},kr(Sr,Er.BasePoint),_r.prototype.point=function(e,t,r){return new Sr(this,e,t,r)},_r.prototype.pointFromJSON=function(e,t){return Sr.fromJSON(this,e,t)},Sr.prototype._getBeta=function(){if(this.curve.endo){var e=this.precomputed;if(e&&e.beta)return e.beta;var t=this.curve.point(this.x.redMul(this.curve.endo.beta),this.y);if(e){var r=this.curve,n=function(e){return r.point(e.x.redMul(r.endo.beta),e.y)};e.beta=t,t.precomputed={beta:null,naf:e.naf&&{wnd:e.naf.wnd,points:e.naf.points.map(n)},doubles:e.doubles&&{step:e.doubles.step,points:e.doubles.points.map(n)}}}return t}},Sr.prototype.toJSON=function(){return this.precomputed?[this.x,this.y,this.precomputed&&{doubles:this.precomputed.doubles&&{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf&&{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}]:[this.x,this.y]},Sr.fromJSON=function(e,t,r){"string"==typeof t&&(t=JSON.parse(t));var n=e.point(t[0],t[1],r);if(!t[2])return n;function i(t){return e.point(t[0],t[1],r)}var s=t[2];return n.precomputed={beta:null,doubles:s.doubles&&{step:s.doubles.step,points:[n].concat(s.doubles.points.map(i))},naf:s.naf&&{wnd:s.naf.wnd,points:[n].concat(s.naf.points.map(i))}},n},Sr.prototype.inspect=function(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+">"},Sr.prototype.isInfinity=function(){return this.inf},Sr.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},Sr.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),n=e.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(n),s=i.redSqr().redISub(this.x.redAdd(this.x)),o=i.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},Sr.prototype.getX=function(){return this.x.fromRed()},Sr.prototype.getY=function(){return this.y.fromRed()},Sr.prototype.mul=function(e){return e=new(H())(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},Sr.prototype.mulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},Sr.prototype.jmulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},Sr.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},Sr.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,n=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return t},Sr.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},kr(Ir,Er.BasePoint),_r.prototype.jpoint=function(e,t,r){return new Ir(this,e,t,r)},Ir.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(r,n)},Ir.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Ir.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(t),i=e.x.redMul(r),s=this.y.redMul(t.redMul(e.z)),o=e.y.redMul(r.redMul(this.z)),a=n.redSub(i),c=s.redSub(o);if(0===a.cmpn(0))return 0!==c.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=a.redSqr(),l=u.redMul(a),h=n.redMul(u),d=c.redSqr().redIAdd(l).redISub(h).redISub(h),f=c.redMul(h.redISub(d)).redISub(s.redMul(l)),p=this.z.redMul(e.z).redMul(a);return this.curve.jpoint(d,f,p)},Ir.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,n=e.x.redMul(t),i=this.y,s=e.y.redMul(t).redMul(this.z),o=r.redSub(n),a=i.redSub(s);if(0===o.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=o.redSqr(),u=c.redMul(o),l=r.redMul(c),h=a.redSqr().redIAdd(u).redISub(l).redISub(l),d=a.redMul(l.redISub(h)).redISub(i.redMul(u)),f=this.z.redMul(o);return this.curve.jpoint(h,d,f)},Ir.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var r=this;for(t=0;t<e;t++)r=r.dbl();return r}var n=this.curve.a,i=this.curve.tinv,s=this.x,o=this.y,a=this.z,c=a.redSqr().redSqr(),u=o.redAdd(o);for(t=0;t<e;t++){var l=s.redSqr(),h=u.redSqr(),d=h.redSqr(),f=l.redAdd(l).redIAdd(l).redIAdd(n.redMul(c)),p=s.redMul(h),m=f.redSqr().redISub(p.redAdd(p)),g=p.redISub(m),y=f.redMul(g);y=y.redIAdd(y).redISub(d);var v=u.redMul(a);t+1<e&&(c=c.redMul(d)),s=m,a=v,u=y}return this.curve.jpoint(s,u.redMul(i),a)},Ir.prototype.dbl=function(){return this.isInfinity()?this:this.curve.zeroA?this._zeroDbl():this.curve.threeA?this._threeDbl():this._dbl()},Ir.prototype._zeroDbl=function(){var e,t,r;if(this.zOne){var n=this.x.redSqr(),i=this.y.redSqr(),s=i.redSqr(),o=this.x.redAdd(i).redSqr().redISub(n).redISub(s);o=o.redIAdd(o);var a=n.redAdd(n).redIAdd(n),c=a.redSqr().redISub(o).redISub(o),u=s.redIAdd(s);u=(u=u.redIAdd(u)).redIAdd(u),e=c,t=a.redMul(o.redISub(c)).redISub(u),r=this.y.redAdd(this.y)}else{var l=this.x.redSqr(),h=this.y.redSqr(),d=h.redSqr(),f=this.x.redAdd(h).redSqr().redISub(l).redISub(d);f=f.redIAdd(f);var p=l.redAdd(l).redIAdd(l),m=p.redSqr(),g=d.redIAdd(d);g=(g=g.redIAdd(g)).redIAdd(g),e=m.redISub(f).redISub(f),t=p.redMul(f.redISub(e)).redISub(g),r=(r=this.y.redMul(this.z)).redIAdd(r)}return this.curve.jpoint(e,t,r)},Ir.prototype._threeDbl=function(){var e,t,r;if(this.zOne){var n=this.x.redSqr(),i=this.y.redSqr(),s=i.redSqr(),o=this.x.redAdd(i).redSqr().redISub(n).redISub(s);o=o.redIAdd(o);var a=n.redAdd(n).redIAdd(n).redIAdd(this.curve.a),c=a.redSqr().redISub(o).redISub(o);e=c;var u=s.redIAdd(s);u=(u=u.redIAdd(u)).redIAdd(u),t=a.redMul(o.redISub(c)).redISub(u),r=this.y.redAdd(this.y)}else{var l=this.z.redSqr(),h=this.y.redSqr(),d=this.x.redMul(h),f=this.x.redSub(l).redMul(this.x.redAdd(l));f=f.redAdd(f).redIAdd(f);var p=d.redIAdd(d),m=(p=p.redIAdd(p)).redAdd(p);e=f.redSqr().redISub(m),r=this.y.redAdd(this.z).redSqr().redISub(h).redISub(l);var g=h.redSqr();g=(g=(g=g.redIAdd(g)).redIAdd(g)).redIAdd(g),t=f.redMul(p.redISub(e)).redISub(g)}return this.curve.jpoint(e,t,r)},Ir.prototype._dbl=function(){var e=this.curve.a,t=this.x,r=this.y,n=this.z,i=n.redSqr().redSqr(),s=t.redSqr(),o=r.redSqr(),a=s.redAdd(s).redIAdd(s).redIAdd(e.redMul(i)),c=t.redAdd(t),u=(c=c.redIAdd(c)).redMul(o),l=a.redSqr().redISub(u.redAdd(u)),h=u.redISub(l),d=o.redSqr();d=(d=(d=d.redIAdd(d)).redIAdd(d)).redIAdd(d);var f=a.redMul(h).redISub(d),p=r.redAdd(r).redMul(n);return this.curve.jpoint(l,f,p)},Ir.prototype.trpl=function(){if(!this.curve.zeroA)return this.dbl().add(this);var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr(),n=t.redSqr(),i=e.redAdd(e).redIAdd(e),s=i.redSqr(),o=this.x.redAdd(t).redSqr().redISub(e).redISub(n),a=(o=(o=(o=o.redIAdd(o)).redAdd(o).redIAdd(o)).redISub(s)).redSqr(),c=n.redIAdd(n);c=(c=(c=c.redIAdd(c)).redIAdd(c)).redIAdd(c);var u=i.redIAdd(o).redSqr().redISub(s).redISub(a).redISub(c),l=t.redMul(u);l=(l=l.redIAdd(l)).redIAdd(l);var h=this.x.redMul(a).redISub(l);h=(h=h.redIAdd(h)).redIAdd(h);var d=this.y.redMul(u.redMul(c.redISub(u)).redISub(o.redMul(a)));d=(d=(d=d.redIAdd(d)).redIAdd(d)).redIAdd(d);var f=this.z.redAdd(o).redSqr().redISub(r).redISub(a);return this.curve.jpoint(h,d,f)},Ir.prototype.mul=function(e,t){return e=new(H())(e,t),this.curve._wnafMul(this,e)},Ir.prototype.eq=function(e){if("affine"===e.type)return this.eq(e.toJ());if(this===e)return!0;var t=this.z.redSqr(),r=e.z.redSqr();if(0!==this.x.redMul(r).redISub(e.x.redMul(t)).cmpn(0))return!1;var n=t.redMul(this.z),i=r.redMul(e.z);return 0===this.y.redMul(i).redISub(e.y.redMul(n)).cmpn(0)},Ir.prototype.eqXToP=function(e){var t=this.z.redSqr(),r=e.toRed(this.curve.red).redMul(t);if(0===this.x.cmp(r))return!0;for(var n=e.clone(),i=this.curve.redN.redMul(t);;){if(n.iadd(this.curve.n),n.cmp(this.curve.p)>=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},Ir.prototype.inspect=function(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"},Ir.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var Nr=dr(function(e,t){var r=t;r.base=Er,r.short=Tr,r.mont=null,r.edwards=null}),Rr=dr(function(e,t){var r,n=t,i=gr.assert;function s(e){"short"===e.type?this.curve=new Nr.short(e):"edwards"===e.type?this.curve=new Nr.edwards(e):this.curve=new Nr.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,i(this.g.validate(),"Invalid curve"),i(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function o(e,t){Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get:function(){var r=new s(t);return Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:r}),r}})}n.PresetCurve=s,o("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:hr().sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),o("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:hr().sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),o("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:hr().sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),o("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:hr().sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),o("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:hr().sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),o("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hr().sha256,gRed:!1,g:["9"]}),o("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hr().sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{r=null.crash()}catch(e){r=void 0}o("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:hr().sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",r]})});function Or(e){if(!(this instanceof Or))return new Or(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=mr.toArray(e.entropy,e.entropyEnc||"hex"),r=mr.toArray(e.nonce,e.nonceEnc||"hex"),n=mr.toArray(e.pers,e.persEnc||"hex");fr(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,n)}var Cr=Or;Or.prototype._init=function(e,t,r){var n=e.concat(t).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i<this.V.length;i++)this.K[i]=0,this.V[i]=1;this._update(n),this._reseed=1,this.reseedInterval=281474976710656},Or.prototype._hmac=function(){return new(hr().hmac)(this.hash,this.K)},Or.prototype._update=function(e){var t=this._hmac().update(this.V).update([0]);e&&(t=t.update(e)),this.K=t.digest(),this.V=this._hmac().update(this.V).digest(),e&&(this.K=this._hmac().update(this.V).update([1]).update(e).digest(),this.V=this._hmac().update(this.V).digest())},Or.prototype.reseed=function(e,t,r,n){"string"!=typeof t&&(n=r,r=t,t=null),e=mr.toArray(e,t),r=mr.toArray(r,n),fr(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},Or.prototype.generate=function(e,t,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(n=r,r=t,t=null),r&&(r=mr.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length<e;)this.V=this._hmac().update(this.V).digest(),i=i.concat(this.V);var s=i.slice(0,e);return this._update(r),this._reseed++,mr.encode(s,t)};var Pr=gr.assert;function Mr(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}var Dr=Mr;Mr.fromPublic=function(e,t,r){return t instanceof Mr?t:new Mr(e,{pub:t,pubEnc:r})},Mr.fromPrivate=function(e,t,r){return t instanceof Mr?t:new Mr(e,{priv:t,privEnc:r})},Mr.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},Mr.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},Mr.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},Mr.prototype._importPrivate=function(e,t){this.priv=new(H())(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},Mr.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?Pr(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||Pr(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},Mr.prototype.derive=function(e){return e.validate()||Pr(e.validate(),"public point not validated"),e.mul(this.priv).getX()},Mr.prototype.sign=function(e,t,r){return this.ec.sign(e,this,t,r)},Mr.prototype.verify=function(e,t,r){return this.ec.verify(e,t,this,void 0,r)},Mr.prototype.inspect=function(){return"<Key priv: "+(this.priv&&this.priv.toString(16,2))+" pub: "+(this.pub&&this.pub.inspect())+" >"};var Br=gr.assert;function Lr(e,t){if(e instanceof Lr)return e;this._importDER(e,t)||(Br(e.r&&e.s,"Signature without r or s"),this.r=new(H())(e.r,16),this.s=new(H())(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}var Ur=Lr;function Fr(){this.place=0}function $r(e,t){var r=e[t.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;if(0===e[t.place])return!1;for(var i=0,s=0,o=t.place;s<n;s++,o++)i<<=8,i|=e[o],i>>>=0;return!(i<=127)&&(t.place=o,i)}function Hr(e){for(var t=0,r=e.length-1;!e[t]&&!(128&e[t+1])&&t<r;)t++;return 0===t?e:e.slice(t)}function Kr(e,t){if(t<128)e.push(t);else{var r=1+(Math.log(t)/Math.LN2>>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}Lr.prototype._importDER=function(e,t){e=gr.toArray(e,t);var r=new Fr;if(48!==e[r.place++])return!1;var n=$r(e,r);if(!1===n)return!1;if(n+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var i=$r(e,r);if(!1===i)return!1;if(128&e[r.place])return!1;var s=e.slice(r.place,i+r.place);if(r.place+=i,2!==e[r.place++])return!1;var o=$r(e,r);if(!1===o)return!1;if(e.length!==o+r.place)return!1;if(128&e[r.place])return!1;var a=e.slice(r.place,o+r.place);if(0===s[0]){if(!(128&s[1]))return!1;s=s.slice(1)}if(0===a[0]){if(!(128&a[1]))return!1;a=a.slice(1)}return this.r=new(H())(s),this.s=new(H())(a),this.recoveryParam=null,!0},Lr.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=Hr(t),r=Hr(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];Kr(n,t.length),(n=n.concat(t)).push(2),Kr(n,r.length);var i=n.concat(r),s=[48];return Kr(s,i.length),s=s.concat(i),gr.encode(s,e)};var qr=function(){throw new Error("unsupported")},jr=gr.assert;function zr(e){if(!(this instanceof zr))return new zr(e);"string"==typeof e&&(jr(Object.prototype.hasOwnProperty.call(Rr,e),"Unknown curve "+e),e=Rr[e]),e instanceof Rr.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}var Vr=zr;zr.prototype.keyPair=function(e){return new Dr(this,e)},zr.prototype.keyFromPrivate=function(e,t){return Dr.fromPrivate(this,e,t)},zr.prototype.keyFromPublic=function(e,t){return Dr.fromPublic(this,e,t)},zr.prototype.genKeyPair=function(e){e||(e={});for(var t=new Cr({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||qr(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new(H())(2));;){var i=new(H())(t.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},zr.prototype._truncateToN=function(e,t,r){var n;if(H().isBN(e)||"number"==typeof e)n=(e=new(H())(e,16)).byteLength();else if("object"==typeof e)n=e.length,e=new(H())(e,16);else{var i=e.toString();n=i.length+1>>>1,e=new(H())(i,16)}"number"!=typeof r&&(r=8*n);var s=r-this.n.bitLength();return s>0&&(e=e.ushrn(s)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},zr.prototype.sign=function(e,t,r,n){if("object"==typeof r&&(n=r,r=null),n||(n={}),"string"!=typeof e&&"number"!=typeof e&&!H().isBN(e)){jr("object"==typeof e&&e&&"number"==typeof e.length,"Expected message to be an array-like, a hex string, or a BN instance"),jr(e.length>>>0===e.length);for(var i=0;i<e.length;i++)jr((255&e[i])===e[i])}t=this.keyFromPrivate(t,r),e=this._truncateToN(e,!1,n.msgBitLength),jr(!e.isNeg(),"Can not sign a negative message");var s=this.n.byteLength(),o=t.getPrivate().toArray("be",s),a=e.toArray("be",s);jr(new(H())(a).eq(e),"Can not sign message");for(var c=new Cr({hash:this.hash,entropy:o,nonce:a,pers:n.pers,persEnc:n.persEnc||"utf8"}),u=this.n.sub(new(H())(1)),l=0;;l++){var h=n.k?n.k(l):new(H())(c.generate(this.n.byteLength()));if(!((h=this._truncateToN(h,!0)).cmpn(1)<=0||h.cmp(u)>=0)){var d=this.g.mul(h);if(!d.isInfinity()){var f=d.getX(),p=f.umod(this.n);if(0!==p.cmpn(0)){var m=h.invm(this.n).mul(p.mul(t.getPrivate()).iadd(e));if(0!==(m=m.umod(this.n)).cmpn(0)){var g=(d.getY().isOdd()?1:0)|(0!==f.cmp(p)?2:0);return n.canonical&&m.cmp(this.nh)>0&&(m=this.n.sub(m),g^=1),new Ur({r:p,s:m,recoveryParam:g})}}}}}},zr.prototype.verify=function(e,t,r,n,i){i||(i={}),e=this._truncateToN(e,!1,i.msgBitLength),r=this.keyFromPublic(r,n);var s=(t=new Ur(t,"hex")).r,o=t.s;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var a,c=o.invm(this.n),u=c.mul(e).umod(this.n),l=c.mul(s).umod(this.n);return this.curve._maxwellTrick?!(a=this.g.jmulAdd(u,r.getPublic(),l)).isInfinity()&&a.eqXToP(s):!(a=this.g.mulAdd(u,r.getPublic(),l)).isInfinity()&&0===a.getX().umod(this.n).cmp(s)},zr.prototype.recoverPubKey=function(e,t,r,n){jr((3&r)===r,"The recovery param is more than two bits"),t=new Ur(t,n);var i=this.n,s=new(H())(e),o=t.r,a=t.s,c=1&r,u=r>>1;if(o.cmp(this.curve.p.umod(this.curve.n))>=0&&u)throw new Error("Unable to find sencond key candinate");o=u?this.curve.pointFromX(o.add(this.curve.n),c):this.curve.pointFromX(o,c);var l=t.r.invm(i),h=i.sub(s).mul(l).umod(i),d=a.mul(l).umod(i);return this.g.mulAdd(h,o,d)},zr.prototype.getKeyRecoveryParam=function(e,t,r,n){if(null!==(t=new Ur(t,n)).recoveryParam)return t.recoveryParam;for(var i=0;i<4;i++){var s;try{s=this.recoverPubKey(e,t,i)}catch(e){continue}if(s.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var Gr=dr(function(e,t){var r=t;r.version="6.6.1",r.utils=gr,r.rand=function(){throw new Error("unsupported")},r.curve=Nr,r.curves=Rr,r.ec=Vr,r.eddsa=null}).ec;const Wr=new v("signing-key/5.8.0");let Jr=null;function Zr(){return Jr||(Jr=new Gr("secp256k1")),Jr}class Yr{constructor(e){ee(this,"curve","secp256k1"),ee(this,"privateKey",O(e)),32!==C(this.privateKey)&&Wr.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");const t=Zr().keyFromPrivate(_(this.privateKey));ee(this,"publicKey","0x"+t.getPublic(!1,"hex")),ee(this,"compressedPublicKey","0x"+t.getPublic(!0,"hex")),ee(this,"_isSigningKey",!0)}_addPoint(e){const t=Zr().keyFromPublic(_(this.publicKey)),r=Zr().keyFromPublic(_(e));return"0x"+t.pub.add(r.pub).encodeCompressed("hex")}signDigest(e){const t=Zr().keyFromPrivate(_(this.privateKey)),r=_(e);32!==r.length&&Wr.throwArgumentError("bad digest length","digest",e);const n=t.sign(r,{canonical:!0});return U({recoveryParam:n.recoveryParam,r:L("0x"+n.r.toString(16),32),s:L("0x"+n.s.toString(16),32)})}computeSharedSecret(e){const t=Zr().keyFromPrivate(_(this.privateKey)),r=Zr().keyFromPublic(_(Xr(e)));return L("0x"+t.derive(r.getPublic()).toString(16),32)}static isSigningKey(e){return!(!e||!e._isSigningKey)}}function Qr(e,t){const r=U(t),n={r:_(r.r),s:_(r.s)};return"0x"+Zr().recoverPubKey(_(e),n,r.recoveryParam).encode("hex",!1)}function Xr(e,t){const r=_(e);if(32===r.length){const e=new Yr(r);return t?"0x"+Zr().keyFromPrivate(r).getPublic(!0,"hex"):e.publicKey}return 33===r.length?t?O(r):"0x"+Zr().keyFromPublic(r).getPublic(!1,"hex"):65===r.length?t?"0x"+Zr().keyFromPublic(r).getPublic(!0,"hex"):O(r):Wr.throwArgumentError("invalid public or private key","key","[REDACTED]")}const en=new v("transactions/5.8.0");var tn;function rn(e){return"0x"===e?null:Pe(e)}function nn(e){return"0x"===e?ut:W.from(e)}!function(e){e[e.legacy=0]="legacy",e[e.eip2930=1]="eip2930",e[e.eip1559=2]="eip1559"}(tn||(tn={}));const sn=[{name:"nonce",maxLength:32,numeric:!0},{name:"gasPrice",maxLength:32,numeric:!0},{name:"gasLimit",maxLength:32,numeric:!0},{name:"to",length:20},{name:"value",maxLength:32,numeric:!0},{name:"data"}],on={chainId:!0,data:!0,gasLimit:!0,gasPrice:!0,nonce:!0,to:!0,type:!0,value:!0};function an(e){return Pe(P(ve(P(Xr(e),1)),12))}function cn(e,t){return an(Qr(_(e),t))}function un(e,t){const r=S(W.from(e).toHexString());return r.length>32&&en.throwArgumentError("invalid length for "+t,"transaction:"+t,e),r}function ln(e,t){return{address:Pe(e),storageKeys:(t||[]).map((t,r)=>(32!==C(t)&&en.throwArgumentError("invalid access list storageKey",`accessList[${e}:${r}]`,t),t.toLowerCase()))}}function hn(e){if(Array.isArray(e))return e.map((e,t)=>Array.isArray(e)?(e.length>2&&en.throwArgumentError("access list expected to be [ address, storageKeys[] ]",`value[${t}]`,e),ln(e[0],e[1])):ln(e.address,e.storageKeys));const t=Object.keys(e).map(t=>{const r=e[t].reduce((e,t)=>(e[t]=!0,e),{});return ln(t,Object.keys(r).sort())});return t.sort((e,t)=>e.address.localeCompare(t.address)),t}function dn(e){return hn(e).map(e=>[e.address,e.storageKeys])}function fn(e,t){if(null!=e.gasPrice){const t=W.from(e.gasPrice),r=W.from(e.maxFeePerGas||0);t.eq(r)||en.throwArgumentError("mismatch EIP-1559 gasPrice != maxFeePerGas","tx",{gasPrice:t,maxFeePerGas:r})}const r=[un(e.chainId||0,"chainId"),un(e.nonce||0,"nonce"),un(e.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),un(e.maxFeePerGas||0,"maxFeePerGas"),un(e.gasLimit||0,"gasLimit"),null!=e.to?Pe(e.to):"0x",un(e.value||0,"value"),e.data||"0x",dn(e.accessList||[])];if(t){const e=U(t);r.push(un(e.recoveryParam,"recoveryParam")),r.push(S(e.r)),r.push(S(e.s))}return M(["0x02",ke(r)])}function pn(e,t){const r=[un(e.chainId||0,"chainId"),un(e.nonce||0,"nonce"),un(e.gasPrice||0,"gasPrice"),un(e.gasLimit||0,"gasLimit"),null!=e.to?Pe(e.to):"0x",un(e.value||0,"value"),e.data||"0x",dn(e.accessList||[])];if(t){const e=U(t);r.push(un(e.recoveryParam,"recoveryParam")),r.push(S(e.r)),r.push(S(e.s))}return M(["0x01",ke(r)])}function mn(e,t){if(null==e.type||0===e.type)return null!=e.accessList&&en.throwArgumentError("untyped transactions do not support accessList; include type: 1","transaction",e),function(e,t){ne(e,on);const r=[];sn.forEach(function(t){let n=e[t.name]||[];const i={};t.numeric&&(i.hexPad="left"),n=_(O(n,i)),t.length&&n.length!==t.length&&n.length>0&&en.throwArgumentError("invalid length for "+t.name,"transaction:"+t.name,n),t.maxLength&&(n=S(n),n.length>t.maxLength&&en.throwArgumentError("invalid length for "+t.name,"transaction:"+t.name,n)),r.push(O(n))});let n=0;if(null!=e.chainId?(n=e.chainId,"number"!=typeof n&&en.throwArgumentError("invalid transaction.chainId","transaction",e)):t&&!A(t)&&t.v>28&&(n=Math.floor((t.v-35)/2)),0!==n&&(r.push(O(n)),r.push("0x"),r.push("0x")),!t)return ke(r);const i=U(t);let s=27+i.recoveryParam;return 0!==n?(r.pop(),r.pop(),r.pop(),s+=2*n+8,i.v>28&&i.v!==s&&en.throwArgumentError("transaction.chainId/signature.v mismatch","signature",t)):i.v!==s&&en.throwArgumentError("transaction.chainId/signature.v mismatch","signature",t),r.push(O(s)),r.push(S(_(i.r))),r.push(S(_(i.s))),ke(r)}(e,t);switch(e.type){case 1:return pn(e,t);case 2:return fn(e,t)}return en.throwError(`unsupported transaction type: ${e.type}`,v.errors.UNSUPPORTED_OPERATION,{operation:"serializeTransaction",transactionType:e.type})}function gn(e,t,r){try{const r=nn(t[0]).toNumber();if(0!==r&&1!==r)throw new Error("bad recid");e.v=r}catch(e){en.throwArgumentError("invalid v for transaction type: 1","v",t[0])}e.r=L(t[1],32),e.s=L(t[2],32);try{const t=ve(r(e));e.from=cn(t,{r:e.r,s:e.s,recoveryParam:e.v})}catch(e){}}function yn(e){const t=_(e);if(t[0]>127)return function(e){const t=Te(e);9!==t.length&&6!==t.length&&en.throwArgumentError("invalid raw transaction","rawTransaction",e);const r={nonce:nn(t[0]).toNumber(),gasPrice:nn(t[1]),gasLimit:nn(t[2]),to:rn(t[3]),value:nn(t[4]),data:t[5],chainId:0};if(6===t.length)return r;try{r.v=W.from(t[6]).toNumber()}catch(e){return r}if(r.r=L(t[7],32),r.s=L(t[8],32),W.from(r.r).isZero()&&W.from(r.s).isZero())r.chainId=r.v,r.v=0;else{r.chainId=Math.floor((r.v-35)/2),r.chainId<0&&(r.chainId=0);let n=r.v-27;const i=t.slice(0,6);0!==r.chainId&&(i.push(O(r.chainId)),i.push("0x"),i.push("0x"),n-=2*r.chainId+8);const s=ve(ke(i));try{r.from=cn(s,{r:O(r.r),s:O(r.s),recoveryParam:n})}catch(e){}r.hash=ve(e)}return r.type=null,r}(t);switch(t[0]){case 1:return function(e){const t=Te(e.slice(1));8!==t.length&&11!==t.length&&en.throwArgumentError("invalid component count for transaction type: 1","payload",O(e));const r={type:1,chainId:nn(t[0]).toNumber(),nonce:nn(t[1]).toNumber(),gasPrice:nn(t[2]),gasLimit:nn(t[3]),to:rn(t[4]),value:nn(t[5]),data:t[6],accessList:hn(t[7])};return 8===t.length||(r.hash=ve(e),gn(r,t.slice(8),pn)),r}(t);case 2:return function(e){const t=Te(e.slice(1));9!==t.length&&12!==t.length&&en.throwArgumentError("invalid component count for transaction type: 2","payload",O(e));const r=nn(t[2]),n=nn(t[3]),i={type:2,chainId:nn(t[0]).toNumber(),nonce:nn(t[1]).toNumber(),maxPriorityFeePerGas:r,maxFeePerGas:n,gasPrice:null,gasLimit:nn(t[4]),to:rn(t[5]),value:nn(t[6]),data:t[7],accessList:hn(t[8])};return 9===t.length||(i.hash=ve(e),gn(i,t.slice(9),fn)),i}(t)}return en.throwError(`unsupported transaction type: ${t[0]}`,v.errors.UNSUPPORTED_OPERATION,{operation:"parseTransaction",transactionType:t[0]})}var vn=function(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};const bn=new v("contracts/5.8.0"),wn={chainId:!0,data:!0,from:!0,gasLimit:!0,gasPrice:!0,nonce:!0,to:!0,value:!0,type:!0,accessList:!0,maxFeePerGas:!0,maxPriorityFeePerGas:!0,customData:!0,ccipReadEnabled:!0};function En(e,t){return vn(this,void 0,void 0,function*(){const r=yield t;"string"!=typeof r&&bn.throwArgumentError("invalid address or ENS name","name",r);try{return Pe(r)}catch(e){}e||bn.throwError("a provider or signer is needed to resolve ENS names",v.errors.UNSUPPORTED_OPERATION,{operation:"resolveName"});const n=yield e.resolveName(r);return null==n&&bn.throwArgumentError("resolver or addr is not configured for ENS name","name",r),n})}function An(e,t,r){return vn(this,void 0,void 0,function*(){return Array.isArray(r)?yield Promise.all(r.map((r,n)=>An(e,Array.isArray(t)?t[n]:t[r.name],r))):"address"===r.type?yield En(e,t):"tuple"===r.type?yield An(e,t,r.components):"array"===r.baseType?Array.isArray(t)?yield Promise.all(t.map(t=>An(e,t,r.arrayChildren))):Promise.reject(bn.makeError("invalid value for array",v.errors.INVALID_ARGUMENT,{argument:"value",value:t})):t})}function kn(e,t,r){return vn(this,void 0,void 0,function*(){let n={};r.length===t.inputs.length+1&&"object"==typeof r[r.length-1]&&(n=ie(r.pop())),bn.checkArgumentCount(r.length,t.inputs.length,"passed to contract"),e.signer?n.from?n.from=re({override:En(e.signer,n.from),signer:e.signer.getAddress()}).then(e=>vn(this,void 0,void 0,function*(){return Pe(e.signer)!==e.override&&bn.throwError("Contract with a Signer cannot override from",v.errors.UNSUPPORTED_OPERATION,{operation:"overrides.from"}),e.override})):n.from=e.signer.getAddress():n.from&&(n.from=En(e.provider,n.from));const i=yield re({args:An(e.signer||e.provider,r,t.inputs),address:e.resolvedAddress,overrides:re(n)||{}}),s=e.interface.encodeFunctionData(t,i.args),o={data:s,to:i.address},a=i.overrides;if(null!=a.nonce&&(o.nonce=W.from(a.nonce).toNumber()),null!=a.gasLimit&&(o.gasLimit=W.from(a.gasLimit)),null!=a.gasPrice&&(o.gasPrice=W.from(a.gasPrice)),null!=a.maxFeePerGas&&(o.maxFeePerGas=W.from(a.maxFeePerGas)),null!=a.maxPriorityFeePerGas&&(o.maxPriorityFeePerGas=W.from(a.maxPriorityFeePerGas)),null!=a.from&&(o.from=a.from),null!=a.type&&(o.type=a.type),null!=a.accessList&&(o.accessList=hn(a.accessList)),null==o.gasLimit&&null!=t.gas){let e=21e3;const r=_(s);for(let t=0;t<r.length;t++)e+=4,r[t]&&(e+=64);o.gasLimit=W.from(t.gas).add(e)}if(a.value){const e=W.from(a.value);e.isZero()||t.payable||bn.throwError("non-payable method cannot override value",v.errors.UNSUPPORTED_OPERATION,{operation:"overrides.value",value:n.value}),o.value=e}a.customData&&(o.customData=ie(a.customData)),a.ccipReadEnabled&&(o.ccipReadEnabled=!!a.ccipReadEnabled),delete n.nonce,delete n.gasLimit,delete n.gasPrice,delete n.from,delete n.value,delete n.type,delete n.accessList,delete n.maxFeePerGas,delete n.maxPriorityFeePerGas,delete n.customData,delete n.ccipReadEnabled;const c=Object.keys(n).filter(e=>null!=n[e]);return c.length&&bn.throwError(`cannot override ${c.map(e=>JSON.stringify(e)).join(",")}`,v.errors.UNSUPPORTED_OPERATION,{operation:"overrides",overrides:c}),o})}function xn(e,t){const r=t.wait.bind(t);t.wait=t=>r(t).then(t=>(t.events=t.logs.map(r=>{let n=ce(r),i=null;try{i=e.interface.parseLog(r)}catch(e){}return i&&(n.args=i.args,n.decode=(t,r)=>e.interface.decodeEventLog(i.eventFragment,t,r),n.event=i.name,n.eventSignature=i.signature),n.removeListener=()=>e.provider,n.getBlock=()=>e.provider.getBlock(t.blockHash),n.getTransaction=()=>e.provider.getTransaction(t.transactionHash),n.getTransactionReceipt=()=>Promise.resolve(t),n}),t))}function _n(e,t,r){const n=e.signer||e.provider;return function(...i){return vn(this,void 0,void 0,function*(){let s;if(i.length===t.inputs.length+1&&"object"==typeof i[i.length-1]){const e=ie(i.pop());null!=e.blockTag&&(s=yield e.blockTag),delete e.blockTag,i.push(e)}null!=e.deployTransaction&&(yield e._deployed(s));const o=yield kn(e,t,i),a=yield n.call(o,s);try{let n=e.interface.decodeFunctionResult(t,a);return r&&1===t.outputs.length&&(n=n[0]),n}catch(t){throw t.code===v.errors.CALL_EXCEPTION&&(t.address=e.address,t.args=i,t.transaction=o),t}})}}function Tn(e,t,r){return t.constant?_n(e,t,r):function(e,t){return function(...r){return vn(this,void 0,void 0,function*(){e.signer||bn.throwError("sending a transaction requires a signer",v.errors.UNSUPPORTED_OPERATION,{operation:"sendTransaction"}),null!=e.deployTransaction&&(yield e._deployed());const n=yield kn(e,t,r),i=yield e.signer.sendTransaction(n);return xn(e,i),i})}}(e,t)}function Sn(e){return!e.address||null!=e.topics&&0!==e.topics.length?(e.address||"*")+"@"+(e.topics?e.topics.map(e=>Array.isArray(e)?e.join("|"):e).join(":"):""):"*"}class In{constructor(e,t){ee(this,"tag",e),ee(this,"filter",t),this._listeners=[]}addListener(e,t){this._listeners.push({listener:e,once:t})}removeListener(e){let t=!1;this._listeners=this._listeners.filter(r=>!(!t&&r.listener===e&&(t=!0,1)))}removeAllListeners(){this._listeners=[]}listeners(){return this._listeners.map(e=>e.listener)}listenerCount(){return this._listeners.length}run(e){const t=this.listenerCount();return this._listeners=this._listeners.filter(t=>{const r=e.slice();return setTimeout(()=>{t.listener.apply(this,r)},0),!t.once}),t}prepareEvent(e){}getEmit(e){return[e]}}class Nn extends In{constructor(){super("error",null)}}class Rn extends In{constructor(e,t,r,n){const i={address:e};let s=t.getEventTopic(r);n?(s!==n[0]&&bn.throwArgumentError("topic mismatch","topics",n),i.topics=n.slice()):i.topics=[s],super(Sn(i),i),ee(this,"address",e),ee(this,"interface",t),ee(this,"fragment",r)}prepareEvent(e){super.prepareEvent(e),e.event=this.fragment.name,e.eventSignature=this.fragment.format(),e.decode=(e,t)=>this.interface.decodeEventLog(this.fragment,e,t);try{e.args=this.interface.decodeEventLog(this.fragment,e.data,e.topics)}catch(t){e.args=null,e.decodeError=t}}getEmit(e){const t=de(e.args);if(t.length)throw t[0].error;const r=(e.args||[]).slice();return r.push(e),r}}class On extends In{constructor(e,t){super("*",{address:e}),ee(this,"address",e),ee(this,"interface",t)}prepareEvent(e){super.prepareEvent(e);try{const t=this.interface.parseLog(e);e.event=t.name,e.eventSignature=t.signature,e.decode=(e,r)=>this.interface.decodeEventLog(t.eventFragment,e,r),e.args=t.args}catch(e){}}}class Cn{constructor(e,t,r){ee(this,"interface",te(new.target,"getInterface")(t)),null==r?(ee(this,"provider",null),ee(this,"signer",null)):cr.isSigner(r)?(ee(this,"provider",r.provider||null),ee(this,"signer",r)):nr.isProvider(r)?(ee(this,"provider",r),ee(this,"signer",null)):bn.throwArgumentError("invalid signer or provider","signerOrProvider",r),ee(this,"callStatic",{}),ee(this,"estimateGas",{}),ee(this,"functions",{}),ee(this,"populateTransaction",{}),ee(this,"filters",{});{const e={};Object.keys(this.interface.events).forEach(t=>{const r=this.interface.events[t];ee(this.filters,t,(...e)=>({address:this.address,topics:this.interface.encodeFilterTopics(r,e)})),e[r.name]||(e[r.name]=[]),e[r.name].push(t)}),Object.keys(e).forEach(t=>{const r=e[t];1===r.length?ee(this.filters,t,this.filters[r[0]]):bn.warn(`Duplicate definition of ${t} (${r.join(", ")})`)})}if(ee(this,"_runningEvents",{}),ee(this,"_wrappedEmits",{}),null==e&&bn.throwArgumentError("invalid contract address or ENS name","addressOrName",e),ee(this,"address",e),this.provider)ee(this,"resolvedAddress",En(this.provider,e));else try{ee(this,"resolvedAddress",Promise.resolve(Pe(e)))}catch(e){bn.throwError("provider is required to use ENS name as contract address",v.errors.UNSUPPORTED_OPERATION,{operation:"new Contract"})}this.resolvedAddress.catch(e=>{});const n={},i={};Object.keys(this.interface.functions).forEach(e=>{const t=this.interface.functions[e];if(i[e])bn.warn(`Duplicate ABI entry for ${JSON.stringify(e)}`);else{i[e]=!0;{const r=t.name;n[`%${r}`]||(n[`%${r}`]=[]),n[`%${r}`].push(e)}null==this[e]&&ee(this,e,Tn(this,t,!0)),null==this.functions[e]&&ee(this.functions,e,Tn(this,t,!1)),null==this.callStatic[e]&&ee(this.callStatic,e,_n(this,t,!0)),null==this.populateTransaction[e]&&ee(this.populateTransaction,e,function(e,t){return function(...r){return kn(e,t,r)}}(this,t)),null==this.estimateGas[e]&&ee(this.estimateGas,e,function(e,t){const r=e.signer||e.provider;return function(...n){return vn(this,void 0,void 0,function*(){r||bn.throwError("estimate require a provider or signer",v.errors.UNSUPPORTED_OPERATION,{operation:"estimateGas"});const i=yield kn(e,t,n);return yield r.estimateGas(i)})}}(this,t))}}),Object.keys(n).forEach(e=>{const t=n[e];if(t.length>1)return;e=e.substring(1);const r=t[0];try{null==this[e]&&ee(this,e,this[r])}catch(e){}null==this.functions[e]&&ee(this.functions,e,this.functions[r]),null==this.callStatic[e]&&ee(this.callStatic,e,this.callStatic[r]),null==this.populateTransaction[e]&&ee(this.populateTransaction,e,this.populateTransaction[r]),null==this.estimateGas[e]&&ee(this.estimateGas,e,this.estimateGas[r])})}static getContractAddress(e){return Be(e)}static getInterface(e){return er.isInterface(e)?e:new er(e)}deployed(){return this._deployed()}_deployed(e){return this._deployedPromise||(this.deployTransaction?this._deployedPromise=this.deployTransaction.wait().then(()=>this):this._deployedPromise=this.provider.getCode(this.address,e).then(e=>("0x"===e&&bn.throwError("contract not deployed",v.errors.UNSUPPORTED_OPERATION,{contractAddress:this.address,operation:"getDeployed"}),this))),this._deployedPromise}fallback(e){this.signer||bn.throwError("sending a transactions require a signer",v.errors.UNSUPPORTED_OPERATION,{operation:"sendTransaction(fallback)"});const t=ie(e||{});return["from","to"].forEach(function(e){null!=t[e]&&bn.throwError("cannot override "+e,v.errors.UNSUPPORTED_OPERATION,{operation:e})}),t.to=this.resolvedAddress,this.deployed().then(()=>this.signer.sendTransaction(t))}connect(e){"string"==typeof e&&(e=new ur(e,this.provider));const t=new this.constructor(this.address,this.interface,e);return this.deployTransaction&&ee(t,"deployTransaction",this.deployTransaction),t}attach(e){return new this.constructor(e,this.interface,this.signer||this.provider)}static isIndexed(e){return Yt.isIndexed(e)}_normalizeRunningEvent(e){return this._runningEvents[e.tag]?this._runningEvents[e.tag]:e}_getRunningEvent(e){if("string"==typeof e){if("error"===e)return this._normalizeRunningEvent(new Nn);if("event"===e)return this._normalizeRunningEvent(new In("event",null));if("*"===e)return this._normalizeRunningEvent(new On(this.address,this.interface));const t=this.interface.getEvent(e);return this._normalizeRunningEvent(new Rn(this.address,this.interface,t))}if(e.topics&&e.topics.length>0){try{const t=e.topics[0];if("string"!=typeof t)throw new Error("invalid topic");const r=this.interface.getEvent(t);return this._normalizeRunningEvent(new Rn(this.address,this.interface,r,e.topics))}catch(e){}const t={address:this.address,topics:e.topics};return this._normalizeRunningEvent(new In(Sn(t),t))}return this._normalizeRunningEvent(new On(this.address,this.interface))}_checkRunningEvents(e){if(0===e.listenerCount()){delete this._runningEvents[e.tag];const t=this._wrappedEmits[e.tag];t&&e.filter&&(this.provider.off(e.filter,t),delete this._wrappedEmits[e.tag])}}_wrapEvent(e,t,r){const n=ce(t);return n.removeListener=()=>{r&&(e.removeListener(r),this._checkRunningEvents(e))},n.getBlock=()=>this.provider.getBlock(t.blockHash),n.getTransaction=()=>this.provider.getTransaction(t.transactionHash),n.getTransactionReceipt=()=>this.provider.getTransactionReceipt(t.transactionHash),e.prepareEvent(n),n}_addEventListener(e,t,r){if(this.provider||bn.throwError("events require a provider or a signer with a provider",v.errors.UNSUPPORTED_OPERATION,{operation:"once"}),e.addListener(t,r),this._runningEvents[e.tag]=e,!this._wrappedEmits[e.tag]){const r=r=>{let n=this._wrapEvent(e,r,t);if(null==n.decodeError)try{const t=e.getEmit(n);this.emit(e.filter,...t)}catch(e){n.decodeError=e.error}null!=e.filter&&this.emit("event",n),null!=n.decodeError&&this.emit("error",n.decodeError,n)};this._wrappedEmits[e.tag]=r,null!=e.filter&&this.provider.on(e.filter,r)}}queryFilter(e,t,r){const n=this._getRunningEvent(e),i=ie(n.filter);return"string"==typeof t&&N(t,32)?(null!=r&&bn.throwArgumentError("cannot specify toBlock with blockhash","toBlock",r),i.blockHash=t):(i.fromBlock=null!=t?t:0,i.toBlock=null!=r?r:"latest"),this.provider.getLogs(i).then(e=>e.map(e=>this._wrapEvent(n,e,null)))}on(e,t){return this._addEventListener(this._getRunningEvent(e),t,!1),this}once(e,t){return this._addEventListener(this._getRunningEvent(e),t,!0),this}emit(e,...t){if(!this.provider)return!1;const r=this._getRunningEvent(e),n=r.run(t)>0;return this._checkRunningEvents(r),n}listenerCount(e){return this.provider?null==e?Object.keys(this._runningEvents).reduce((e,t)=>e+this._runningEvents[t].listenerCount(),0):this._getRunningEvent(e).listenerCount():0}listeners(e){if(!this.provider)return[];if(null==e){const e=[];for(let t in this._runningEvents)this._runningEvents[t].listeners().forEach(t=>{e.push(t)});return e}return this._getRunningEvent(e).listeners()}removeAllListeners(e){if(!this.provider)return this;if(null==e){for(const e in this._runningEvents){const t=this._runningEvents[e];t.removeAllListeners(),this._checkRunningEvents(t)}return this}const t=this._getRunningEvent(e);return t.removeAllListeners(),this._checkRunningEvents(t),this}off(e,t){if(!this.provider)return this;const r=this._getRunningEvent(e);return r.removeListener(t),this._checkRunningEvents(r),this}removeListener(e,t){return this.off(e,t)}}class Pn extends Cn{}class Mn{constructor(e,t,r){let n=null;n="string"==typeof t?t:x(t)?O(t):t&&"string"==typeof t.object?t.object:"!","0x"!==n.substring(0,2)&&(n="0x"+n),(!N(n)||n.length%2)&&bn.throwArgumentError("invalid bytecode","bytecode",t),r&&!cr.isSigner(r)&&bn.throwArgumentError("invalid signer","signer",r),ee(this,"bytecode",n),ee(this,"interface",te(new.target,"getInterface")(e)),ee(this,"signer",r||null)}getDeployTransaction(...e){let t={};if(e.length===this.interface.deploy.inputs.length+1&&"object"==typeof e[e.length-1]){t=ie(e.pop());for(const e in t)if(!wn[e])throw new Error("unknown transaction override "+e)}return["data","from","to"].forEach(e=>{null!=t[e]&&bn.throwError("cannot override "+e,v.errors.UNSUPPORTED_OPERATION,{operation:e})}),t.value&&(W.from(t.value).isZero()||this.interface.deploy.payable||bn.throwError("non-payable constructor cannot override value",v.errors.UNSUPPORTED_OPERATION,{operation:"overrides.value",value:t.value})),bn.checkArgumentCount(e.length,this.interface.deploy.inputs.length," in Contract constructor"),t.data=O(T([this.bytecode,this.interface.encodeDeploy(e)])),t}deploy(...e){return vn(this,void 0,void 0,function*(){let t={};e.length===this.interface.deploy.inputs.length+1&&(t=e.pop()),bn.checkArgumentCount(e.length,this.interface.deploy.inputs.length," in Contract constructor");const r=yield An(this.signer,e,this.interface.deploy.inputs);r.push(t);const n=this.getDeployTransaction(...r),i=yield this.signer.sendTransaction(n),s=te(this.constructor,"getContractAddress")(i),o=te(this.constructor,"getContract")(s,this.interface,this.signer);return xn(o,i),ee(o,"deployTransaction",i),o})}attach(e){return this.constructor.getContract(e,this.interface,this.signer)}connect(e){return new this.constructor(this.interface,this.bytecode,e)}static fromSolidity(e,t){null==e&&bn.throwError("missing compiler output",v.errors.MISSING_ARGUMENT,{argument:"compilerOutput"}),"string"==typeof e&&(e=JSON.parse(e));const r=e.abi;let n=null;return e.bytecode?n=e.bytecode:e.evm&&e.evm.bytecode&&(n=e.evm.bytecode),new this(r,n,t)}static getInterface(e){return Pn.getInterface(e)}static getContractAddress(e){return Be(e)}static getContract(e,t,r){return new Pn(e,t,r)}}const Dn=new v(K),Bn={},Ln=W.from(0),Un=W.from(-1);function Fn(e,t,r,n){const i={fault:t,operation:r};return void 0!==n&&(i.value=n),Dn.throwError(e,v.errors.NUMERIC_FAULT,i)}let $n="0";for(;$n.length<256;)$n+=$n;function Hn(e){if("number"!=typeof e)try{e=W.from(e).toNumber()}catch(e){}return"number"==typeof e&&e>=0&&e<=256&&!(e%1)?"1"+$n.substring(0,e):Dn.throwArgumentError("invalid decimal size","decimals",e)}function Kn(e,t){null==t&&(t=0);const r=Hn(t),n=(e=W.from(e)).lt(Ln);n&&(e=e.mul(Un));let i=e.mod(r).toString();for(;i.length<r.length-1;)i="0"+i;i=i.match(/^([0-9]*[1-9]|0)(0*)/)[1];const s=e.div(r).toString();return e=1===r.length?s:s+"."+i,n&&(e="-"+e),e}function qn(e,t){null==t&&(t=0);const r=Hn(t);"string"==typeof e&&e.match(/^-?[0-9.]+$/)||Dn.throwArgumentError("invalid decimal value","value",e);const n="-"===e.substring(0,1);n&&(e=e.substring(1)),"."===e&&Dn.throwArgumentError("missing value","value",e);const i=e.split(".");i.length>2&&Dn.throwArgumentError("too many decimal points","value",e);let s=i[0],o=i[1];for(s||(s="0"),o||(o="0");"0"===o[o.length-1];)o=o.substring(0,o.length-1);for(o.length>r.length-1&&Fn("fractional component exceeds decimals","underflow","parseFixed"),""===o&&(o="0");o.length<r.length-1;)o+="0";const a=W.from(s),c=W.from(o);let u=a.mul(r).add(c);return n&&(u=u.mul(Un)),u}class jn{constructor(e,t,r,n){e!==Bn&&Dn.throwError("cannot use FixedFormat constructor; use FixedFormat.from",v.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.signed=t,this.width=r,this.decimals=n,this.name=(t?"":"u")+"fixed"+String(r)+"x"+String(n),this._multiplier=Hn(n),Object.freeze(this)}static from(e){if(e instanceof jn)return e;"number"==typeof e&&(e=`fixed128x${e}`);let t=!0,r=128,n=18;if("string"==typeof e)if("fixed"===e);else if("ufixed"===e)t=!1;else{const i=e.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);i||Dn.throwArgumentError("invalid fixed format","format",e),t="u"!==i[1],r=parseInt(i[2]),n=parseInt(i[3])}else if(e){const i=(t,r,n)=>null==e[t]?n:(typeof e[t]!==r&&Dn.throwArgumentError("invalid fixed format ("+t+" not "+r+")","format."+t,e[t]),e[t]);t=i("signed","boolean",t),r=i("width","number",r),n=i("decimals","number",n)}return r%8&&Dn.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",r),n>80&&Dn.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",n),new jn(Bn,t,r,n)}}class zn{constructor(e,t,r,n){e!==Bn&&Dn.throwError("cannot use FixedNumber constructor; use FixedNumber.from",v.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=n,this._hex=t,this._value=r,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&Dn.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);const t=qn(this._value,this.format.decimals),r=qn(e._value,e.format.decimals);return zn.fromValue(t.add(r),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);const t=qn(this._value,this.format.decimals),r=qn(e._value,e.format.decimals);return zn.fromValue(t.sub(r),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);const t=qn(this._value,this.format.decimals),r=qn(e._value,e.format.decimals);return zn.fromValue(t.mul(r).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);const t=qn(this._value,this.format.decimals),r=qn(e._value,e.format.decimals);return zn.fromValue(t.mul(this.format._multiplier).div(r),this.format.decimals,this.format)}floor(){const e=this.toString().split(".");1===e.length&&e.push("0");let t=zn.from(e[0],this.format);const r=!e[1].match(/^(0*)$/);return this.isNegative()&&r&&(t=t.subUnsafe(Vn.toFormat(t.format))),t}ceiling(){const e=this.toString().split(".");1===e.length&&e.push("0");let t=zn.from(e[0],this.format);const r=!e[1].match(/^(0*)$/);return!this.isNegative()&&r&&(t=t.addUnsafe(Vn.toFormat(t.format))),t}round(e){null==e&&(e=0);const t=this.toString().split(".");if(1===t.length&&t.push("0"),(e<0||e>80||e%1)&&Dn.throwArgumentError("invalid decimal count","decimals",e),t[1].length<=e)return this;const r=zn.from("1"+$n.substring(0,e),this.format),n=Gn.toFormat(this.format);return this.mulUnsafe(r).addUnsafe(n).floor().divUnsafe(r)}isZero(){return"0.0"===this._value||"0"===this._value}isNegative(){return"-"===this._value[0]}toString(){return this._value}toHexString(e){return null==e?this._hex:(e%8&&Dn.throwArgumentError("invalid byte width","width",e),L(W.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString(),e/8))}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return zn.fromString(this._value,e)}static fromValue(e,t,r){return null!=r||null==t||function(e){return null!=e&&(W.isBigNumber(e)||"number"==typeof e&&e%1==0||"string"==typeof e&&!!e.match(/^-?[0-9]+$/)||N(e)||"bigint"==typeof e||x(e))}(t)||(r=t,t=null),null==t&&(t=0),null==r&&(r="fixed"),zn.fromString(Kn(e,t),jn.from(r))}static fromString(e,t){null==t&&(t="fixed");const r=jn.from(t),n=qn(e,r.decimals);!r.signed&&n.lt(Ln)&&Fn("unsigned value cannot be negative","overflow","value",e);let i=null;r.signed?i=n.toTwos(r.width).toHexString():(i=n.toHexString(),i=L(i,r.width/8));const s=Kn(n,r.decimals);return new zn(Bn,i,s,r)}static fromBytes(e,t){null==t&&(t="fixed");const r=jn.from(t);if(_(e).length>r.width/8)throw new Error("overflow");let n=W.from(e);r.signed&&(n=n.fromTwos(r.width));const i=n.toTwos((r.signed?0:1)+r.width).toHexString(),s=Kn(n,r.decimals);return new zn(Bn,i,s,r)}static from(e,t){if("string"==typeof e)return zn.fromString(e,t);if(x(e))return zn.fromBytes(e,t);try{return zn.fromValue(e,0,t)}catch(e){if(e.code!==v.errors.INVALID_ARGUMENT)throw e}return Dn.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!(!e||!e._isFixedNumber)}}const Vn=zn.from(1),Gn=zn.from("0.5");function Wn(e){return"string"==typeof e&&(e=je(e)),ve(T([je("Ethereum Signed Message:\n"),je(String(e.length)),e]))}const Jn="hash/5.8.0";const Zn=new v(Jn),Yn=new Uint8Array(32);Yn.fill(0);const Qn=W.from(-1),Xn=W.from(0),ei=W.from(1),ti=W.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),ri=L(ei.toHexString(),32),ni=L(Xn.toHexString(),32),ii={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},si=["name","version","chainId","verifyingContract","salt"];function oi(e){return function(t){return"string"!=typeof t&&Zn.throwArgumentError(`invalid domain value for ${JSON.stringify(e)}`,`domain.${e}`,t),t}}const ai={name:oi("name"),version:oi("version"),chainId:function(e){try{return W.from(e).toString()}catch(e){}return Zn.throwArgumentError('invalid domain value for "chainId"',"domain.chainId",e)},verifyingContract:function(e){try{return Pe(e).toLowerCase()}catch(e){}return Zn.throwArgumentError('invalid domain value "verifyingContract"',"domain.verifyingContract",e)},salt:function(e){try{const t=_(e);if(32!==t.length)throw new Error("bad length");return O(t)}catch(e){}return Zn.throwArgumentError('invalid domain value "salt"',"domain.salt",e)}};function ci(e){{const t=e.match(/^(u?)int(\d*)$/);if(t){const r=""===t[1],n=parseInt(t[2]||"256");(n%8!=0||n>256||t[2]&&t[2]!==String(n))&&Zn.throwArgumentError("invalid numeric width","type",e);const i=ti.mask(r?n-1:n),s=r?i.add(ei).mul(Qn):Xn;return function(t){const r=W.from(t);return(r.lt(s)||r.gt(i))&&Zn.throwArgumentError(`value out-of-bounds for ${e}`,"value",t),L(r.toTwos(256).toHexString(),32)}}}{const t=e.match(/^bytes(\d+)$/);if(t){const r=parseInt(t[1]);return(0===r||r>32||t[1]!==String(r))&&Zn.throwArgumentError("invalid bytes width","type",e),function(t){return _(t).length!==r&&Zn.throwArgumentError(`invalid length for ${e}`,"value",t),function(e){const t=_(e),r=t.length%32;return r?M([t,Yn.slice(r)]):O(t)}(t)}}}switch(e){case"address":return function(e){return L(Pe(e),32)};case"bool":return function(e){return e?ri:ni};case"bytes":return function(e){return ve(e)};case"string":return function(e){return Ze(e)}}return null}function ui(e,t){return`${e}(${t.map(({name:e,type:t})=>t+" "+e).join(",")})`}class li{constructor(e){ee(this,"types",Object.freeze(ce(e))),ee(this,"_encoderCache",{}),ee(this,"_types",{});const t={},r={},n={};Object.keys(e).forEach(e=>{t[e]={},r[e]=[],n[e]={}});for(const n in e){const i={};e[n].forEach(s=>{i[s.name]&&Zn.throwArgumentError(`duplicate variable name ${JSON.stringify(s.name)} in ${JSON.stringify(n)}`,"types",e),i[s.name]=!0;const o=s.type.match(/^([^\x5b]*)(\x5b|$)/)[1];o===n&&Zn.throwArgumentError(`circular type reference to ${JSON.stringify(o)}`,"types",e),ci(o)||(r[o]||Zn.throwArgumentError(`unknown type ${JSON.stringify(o)}`,"types",e),r[o].push(n),t[n][o]=!0)})}const i=Object.keys(r).filter(e=>0===r[e].length);0===i.length?Zn.throwArgumentError("missing primary type","types",e):i.length>1&&Zn.throwArgumentError(`ambiguous primary types or unused types: ${i.map(e=>JSON.stringify(e)).join(", ")}`,"types",e),ee(this,"primaryType",i[0]),function i(s,o){o[s]&&Zn.throwArgumentError(`circular type reference to ${JSON.stringify(s)}`,"types",e),o[s]=!0,Object.keys(t[s]).forEach(e=>{r[e]&&(i(e,o),Object.keys(o).forEach(t=>{n[t][e]=!0}))}),delete o[s]}(this.primaryType,{});for(const t in n){const r=Object.keys(n[t]);r.sort(),this._types[t]=ui(t,e[t])+r.map(t=>ui(t,e[t])).join("")}}getEncoder(e){let t=this._encoderCache[e];return t||(t=this._encoderCache[e]=this._getEncoder(e)),t}_getEncoder(e){{const t=ci(e);if(t)return t}const t=e.match(/^(.*)(\x5b(\d*)\x5d)$/);if(t){const e=t[1],r=this.getEncoder(e),n=parseInt(t[3]);return t=>{n>=0&&t.length!==n&&Zn.throwArgumentError("array length mismatch; expected length ${ arrayLength }","value",t);let i=t.map(r);return this._types[e]&&(i=i.map(ve)),ve(M(i))}}const r=this.types[e];if(r){const t=Ze(this._types[e]);return e=>{const n=r.map(({name:t,type:r})=>{const n=this.getEncoder(r)(e[t]);return this._types[r]?ve(n):n});return n.unshift(t),M(n)}}return Zn.throwArgumentError(`unknown type: ${e}`,"type",e)}encodeType(e){const t=this._types[e];return t||Zn.throwArgumentError(`unknown type: ${JSON.stringify(e)}`,"name",e),t}encodeData(e,t){return this.getEncoder(e)(t)}hashStruct(e,t){return ve(this.encodeData(e,t))}encode(e){return this.encodeData(this.primaryType,e)}hash(e){return this.hashStruct(this.primaryType,e)}_visit(e,t,r){if(ci(e))return r(e,t);const n=e.match(/^(.*)(\x5b(\d*)\x5d)$/);if(n){const e=n[1],i=parseInt(n[3]);return i>=0&&t.length!==i&&Zn.throwArgumentError("array length mismatch; expected length ${ arrayLength }","value",t),t.map(t=>this._visit(e,t,r))}const i=this.types[e];return i?i.reduce((e,{name:n,type:i})=>(e[n]=this._visit(i,t[n],r),e),{}):Zn.throwArgumentError(`unknown type: ${e}`,"type",e)}visit(e,t){return this._visit(this.primaryType,e,t)}static from(e){return new li(e)}static getPrimaryType(e){return li.from(e).primaryType}static hashStruct(e,t,r){return li.from(t).hashStruct(e,r)}static hashDomain(e){const t=[];for(const r in e){const n=ii[r];n||Zn.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(r)}`,"domain",e),t.push({name:r,type:n})}return t.sort((e,t)=>si.indexOf(e.name)-si.indexOf(t.name)),li.hashStruct("EIP712Domain",{EIP712Domain:t},e)}static encode(e,t,r){return M(["0x1901",li.hashDomain(e),li.from(t).hash(r)])}static hash(e,t,r){return ve(li.encode(e,t,r))}static resolveNames(e,t,r,n){return i=this,s=void 0,a=function*(){e=ie(e);const i={};e.verifyingContract&&!N(e.verifyingContract,20)&&(i[e.verifyingContract]="0x");const s=li.from(t);s.visit(r,(e,t)=>("address"!==e||N(t,20)||(i[t]="0x"),t));for(const e in i)i[e]=yield n(e);return e.verifyingContract&&i[e.verifyingContract]&&(e.verifyingContract=i[e.verifyingContract]),r=s.visit(r,(e,t)=>"address"===e&&i[t]?i[t]:t),{domain:e,value:r}},new((o=void 0)||(o=Promise))(function(e,t){function r(e){try{c(a.next(e))}catch(e){t(e)}}function n(e){try{c(a.throw(e))}catch(e){t(e)}}function c(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(r,n)}c((a=a.apply(i,s||[])).next())});var i,s,o,a}static getPayload(e,t,r){li.hashDomain(e);const n={},i=[];si.forEach(t=>{const r=e[t];null!=r&&(n[t]=ai[t](r),i.push({name:t,type:ii[t]}))});const s=li.from(t),o=ie(t);return o.EIP712Domain?Zn.throwArgumentError("types must not contain EIP712Domain type","types.EIP712Domain",t):o.EIP712Domain=i,s.encode(r),{types:o,domain:n,primaryType:s.primaryType,message:s.visit(r,(e,t)=>{if(e.match(/^bytes(\d*)/))return O(_(t));if(e.match(/^u?int/))return W.from(t).toString();switch(e){case"address":return t.toLowerCase();case"bool":return!!t;case"string":return"string"!=typeof t&&Zn.throwArgumentError("invalid string","value",t),t}return Zn.throwArgumentError("unsupported type","type",e)})}}}class hi{constructor(e){ee(this,"alphabet",e),ee(this,"base",e.length),ee(this,"_alphabetMap",{}),ee(this,"_leader",e.charAt(0));for(let t=0;t<e.length;t++)this._alphabetMap[e.charAt(t)]=t}encode(e){let t=_(e);if(0===t.length)return"";let r=[0];for(let e=0;e<t.length;++e){let n=t[e];for(let e=0;e<r.length;++e)n+=r[e]<<8,r[e]=n%this.base,n=n/this.base|0;for(;n>0;)r.push(n%this.base),n=n/this.base|0}let n="";for(let e=0;0===t[e]&&e<t.length-1;++e)n+=this._leader;for(let e=r.length-1;e>=0;--e)n+=this.alphabet[r[e]];return n}decode(e){if("string"!=typeof e)throw new TypeError("Expected String");let t=[];if(0===e.length)return new Uint8Array(t);t.push(0);for(let r=0;r<e.length;r++){let n=this._alphabetMap[e[r]];if(void 0===n)throw new Error("Non-base"+this.base+" character");let i=n;for(let e=0;e<t.length;++e)i+=t[e]*this.base,t[e]=255&i,i>>=8;for(;i>0;)t.push(255&i),i>>=8}for(let r=0;e[r]===this._leader&&r<e.length-1;++r)t.push(0);return _(new Uint8Array(t.reverse()))}}new hi("abcdefghijklmnopqrstuvwxyz234567");const di=new hi("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var fi;!function(e){e.sha256="sha256",e.sha512="sha512"}(fi||(fi={}));const pi=new v("sha2/5.8.0");function mi(e){return"0x"+hr().ripemd160().update(_(e)).digest("hex")}function gi(e){return"0x"+hr().sha256().update(_(e)).digest("hex")}function yi(e){return"0x"+hr().sha512().update(_(e)).digest("hex")}function vi(e,t,r){return fi[e]||pi.throwError("unsupported algorithm "+e,v.errors.UNSUPPORTED_OPERATION,{operation:"hmac",algorithm:e}),"0x"+hr().hmac(hr()[e],_(t)).update(_(r)).digest("hex")}function bi(e,t,r,n,i){let s;e=_(e),t=_(t);let o=1;const a=new Uint8Array(n),c=new Uint8Array(t.length+4);let u,l;c.set(t);for(let h=1;h<=o;h++){c[t.length]=h>>24&255,c[t.length+1]=h>>16&255,c[t.length+2]=h>>8&255,c[t.length+3]=255&h;let d=_(vi(i,e,c));s||(s=d.length,l=new Uint8Array(s),o=Math.ceil(n/s),u=n-(o-1)*s),l.set(d);for(let t=1;t<r;t++){d=_(vi(i,e,d));for(let e=0;e<s;e++)l[e]^=d[e]}const f=(h-1)*s,p=h===o?u:s;a.set(_(l).slice(0,p),f)}return O(a)}const wi=new v("wordlists/5.8.0");class Ei{constructor(e){wi.checkAbstract(new.target,Ei),ee(this,"locale",e)}split(e){return e.toLowerCase().split(/ +/g)}join(e){return e.join(" ")}static check(e){const t=[];for(let r=0;r<2048;r++){const n=e.getWord(r);if(r!==e.getWordIndex(n))return"0x";t.push(n)}return Ze(t.join("\n")+"\n")}static register(e,t){t||(t=e.locale)}}let Ai=null;function ki(e){if(null==Ai&&(Ai="AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo".replace(/([A-Z])/g," $1").toLowerCase().substring(1).split(" "),"0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60"!==Ei.check(e)))throw Ai=null,new Error("BIP39 Wordlist for en (English) FAILED")}const xi=new class extends Ei{constructor(){super("en")}getWord(e){return ki(this),Ai[e]}getWordIndex(e){return ki(this),Ai.indexOf(e)}};Ei.register(xi);const _i={en:xi},Ti=new v("hdnode/5.8.0"),Si=W.from("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ii=je("Bitcoin seed"),Ni=2147483648;function Ri(e){return(1<<e)-1<<8-e}function Oi(e){return(1<<e)-1}function Ci(e){return L(O(e),32)}function Pi(e){return di.encode(T([e,P(gi(gi(e)),0,4)]))}function Mi(e){if(null==e)return _i.en;if("string"==typeof e){const t=_i[e];return null==t&&Ti.throwArgumentError("unknown locale","wordlist",e),t}return e}const Di={},Bi="m/44'/60'/0'/0/0";class Li{constructor(e,t,r,n,i,s,o,a){if(e!==Di)throw new Error("HDNode constructor cannot be called directly");if(t){const e=new Yr(t);ee(this,"privateKey",e.privateKey),ee(this,"publicKey",e.compressedPublicKey)}else ee(this,"privateKey",null),ee(this,"publicKey",O(r));ee(this,"parentFingerprint",n),ee(this,"fingerprint",P(mi(gi(this.publicKey)),0,4)),ee(this,"address",an(this.publicKey)),ee(this,"chainCode",i),ee(this,"index",s),ee(this,"depth",o),null==a?(ee(this,"mnemonic",null),ee(this,"path",null)):"string"==typeof a?(ee(this,"mnemonic",null),ee(this,"path",a)):(ee(this,"mnemonic",a),ee(this,"path",a.path))}get extendedKey(){if(this.depth>=256)throw new Error("Depth too large!");return Pi(T([null!=this.privateKey?"0x0488ADE4":"0x0488B21E",O(this.depth),this.parentFingerprint,L(O(this.index),4),this.chainCode,null!=this.privateKey?T(["0x00",this.privateKey]):this.publicKey]))}neuter(){return new Li(Di,null,this.publicKey,this.parentFingerprint,this.chainCode,this.index,this.depth,this.path)}_derive(e){if(e>4294967295)throw new Error("invalid index - "+String(e));let t=this.path;t&&(t+="/"+(2147483647&e));const r=new Uint8Array(37);if(e&Ni){if(!this.privateKey)throw new Error("cannot derive child of neutered node");r.set(_(this.privateKey),1),t&&(t+="'")}else r.set(_(this.publicKey));for(let t=24;t>=0;t-=8)r[33+(t>>3)]=e>>24-t&255;const n=_(vi(fi.sha512,this.chainCode,r)),i=n.slice(0,32),s=n.slice(32);let o=null,a=null;this.privateKey?o=Ci(W.from(i).add(this.privateKey).mod(Si)):a=new Yr(O(i))._addPoint(this.publicKey);let c=t;const u=this.mnemonic;return u&&(c=Object.freeze({phrase:u.phrase,path:t,locale:u.locale||"en"})),new Li(Di,o,a,this.fingerprint,Ci(s),e,this.depth+1,c)}derivePath(e){const t=e.split("/");if(0===t.length||"m"===t[0]&&0!==this.depth)throw new Error("invalid path - "+e);"m"===t[0]&&t.shift();let r=this;for(let e=0;e<t.length;e++){const n=t[e];if(n.match(/^[0-9]+'$/)){const e=parseInt(n.substring(0,n.length-1));if(e>=Ni)throw new Error("invalid path index - "+n);r=r._derive(Ni+e)}else{if(!n.match(/^[0-9]+$/))throw new Error("invalid path component - "+n);{const e=parseInt(n);if(e>=Ni)throw new Error("invalid path index - "+n);r=r._derive(e)}}}return r}static _fromSeed(e,t){const r=_(e);if(r.length<16||r.length>64)throw new Error("invalid seed");const n=_(vi(fi.sha512,Ii,r));return new Li(Di,Ci(n.slice(0,32)),null,"0x00000000",Ci(n.slice(32)),0,0,t)}static fromMnemonic(e,t,r){return e=$i(Fi(e,r=Mi(r)),r),Li._fromSeed(Ui(e,t),{phrase:e,path:"m",locale:r.locale})}static fromSeed(e){return Li._fromSeed(e,null)}static fromExtendedKey(e){const t=di.decode(e);82===t.length&&Pi(t.slice(0,78))===e||Ti.throwArgumentError("invalid extended key","extendedKey","[REDACTED]");const r=t[4],n=O(t.slice(5,9)),i=parseInt(O(t.slice(9,13)).substring(2),16),s=O(t.slice(13,45)),o=t.slice(45,78);switch(O(t.slice(0,4))){case"0x0488b21e":case"0x043587cf":return new Li(Di,null,O(o),n,s,i,r,null);case"0x0488ade4":case"0x04358394 ":if(0!==o[0])break;return new Li(Di,O(o.slice(1)),null,n,s,i,r,null)}return Ti.throwArgumentError("invalid extended key","extendedKey","[REDACTED]")}}function Ui(e,t){t||(t="");const r=je("mnemonic"+t,Fe.NFKD);return bi(je(e,Fe.NFKD),r,2048,64,"sha512")}function Fi(e,t){t=Mi(t),Ti.checkNormalize();const r=t.split(e);if(r.length%3!=0)throw new Error("invalid mnemonic");const n=_(new Uint8Array(Math.ceil(11*r.length/8)));let i=0;for(let e=0;e<r.length;e++){let s=t.getWordIndex(r[e].normalize("NFKD"));if(-1===s)throw new Error("invalid mnemonic");for(let e=0;e<11;e++)s&1<<10-e&&(n[i>>3]|=1<<7-i%8),i++}const s=32*r.length/3,o=Ri(r.length/3);if((_(gi(n.slice(0,s/8)))[0]&o)!==(n[n.length-1]&o))throw new Error("invalid checksum");return O(n.slice(0,s/8))}function $i(e,t){if(t=Mi(t),(e=_(e)).length%4!=0||e.length<16||e.length>32)throw new Error("invalid entropy");const r=[0];let n=11;for(let t=0;t<e.length;t++)n>8?(r[r.length-1]<<=8,r[r.length-1]|=e[t],n-=8):(r[r.length-1]<<=n,r[r.length-1]|=e[t]>>8-n,r.push(e[t]&Oi(8-n)),n+=3);const i=e.length/4,s=_(gi(e))[0]&Ri(i);return r[r.length-1]<<=i,r[r.length-1]|=s>>8-i,t.join(r.map(e=>t.getWord(e)))}function Hi(e,t){try{return Fi(e,t),!0}catch(e){}return!1}function Ki(e){return("number"!=typeof e||e<0||e>=Ni||e%1)&&Ti.throwArgumentError("invalid account index","index",e),`m/44'/60'/${e}'/0/0`}const qi=new v("random/5.8.0"),ji=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof globalThis)return globalThis;throw new Error("unable to locate global object")}();let zi=ji.crypto||ji.msCrypto;function Vi(e){(e<=0||e>1024||e%1||e!=e)&&qi.throwArgumentError("invalid length","length",e);const t=new Uint8Array(e);return zi.getRandomValues(t),_(t)}zi&&zi.getRandomValues||(qi.warn("WARNING: Missing strong random number source"),zi={getRandomValues:function(e){return qi.throwError("no secure random source avaialble",v.errors.UNSUPPORTED_OPERATION,{operation:"crypto.getRandomValues"})}});var Gi=r(3725),Wi=r.n(Gi),Ji=r(3432),Zi=r.n(Ji);function Yi(e){return"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),_(e)}function Qi(e,t){for(e=String(e);e.length<t;)e="0"+e;return e}function Xi(e){return"string"==typeof e?je(e,Fe.NFKC):_(e)}function es(e,t){let r=e;const n=t.toLowerCase().split("/");for(let e=0;e<n.length;e++){let t=null;for(const i in r)if(i.toLowerCase()===n[e]){t=r[i];break}if(null===t)return null;r=t}return r}function ts(e){const t=_(e);t[6]=15&t[6]|64,t[8]=63&t[8]|128;const r=O(t);return[r.substring(2,10),r.substring(10,14),r.substring(14,18),r.substring(18,22),r.substring(22,34)].join("-")}const rs="json-wallets/5.8.0";const ns=new v(rs);function is(e){return null!=e&&e.mnemonic&&e.mnemonic.phrase}class ss extends ue{isKeystoreAccount(e){return!(!e||!e._isKeystoreAccount)}}function os(e,t){const r=Yi(es(e,"crypto/ciphertext"));if(O(ve(T([t.slice(16,32),r]))).substring(2)!==es(e,"crypto/mac").toLowerCase())throw new Error("invalid password");const n=function(e,t,r){if("aes-128-ctr"===es(e,"crypto/cipher")){const n=Yi(es(e,"crypto/cipherparams/iv")),i=new(Wi().Counter)(n);return _(new(Wi().ModeOfOperation.ctr)(t,i).decrypt(r))}return null}(e,t.slice(0,16),r);n||ns.throwError("unsupported cipher",v.errors.UNSUPPORTED_OPERATION,{operation:"decrypt"});const i=t.slice(32,64),s=an(n);if(e.address){let t=e.address.toLowerCase();if("0x"!==t.substring(0,2)&&(t="0x"+t),Pe(t)!==s)throw new Error("address mismatch")}const o={_isKeystoreAccount:!0,address:s,privateKey:O(n)};if("0.1"===es(e,"x-ethers/version")){const t=Yi(es(e,"x-ethers/mnemonicCiphertext")),r=Yi(es(e,"x-ethers/mnemonicCounter")),n=new(Wi().Counter)(r),s=new(Wi().ModeOfOperation.ctr)(i,n),a=es(e,"x-ethers/path")||Bi,c=es(e,"x-ethers/locale")||"en",u=_(s.decrypt(t));try{const e=$i(u,c),t=Li.fromMnemonic(e,null,c).derivePath(a);if(t.privateKey!=o.privateKey)throw new Error("mnemonic mismatch");o.mnemonic=t.mnemonic}catch(e){if(e.code!==v.errors.INVALID_ARGUMENT||"wordlist"!==e.argument)throw e}}return new ss(o)}function as(e,t,r,n,i){return _(bi(e,t,r,n,i))}function cs(e,t,r,n,i){return Promise.resolve(as(e,t,r,n,i))}function us(e,t,r,n,i){const s=Xi(t),o=es(e,"crypto/kdf");if(o&&"string"==typeof o){const t=function(e,t){return ns.throwArgumentError("invalid key-derivation function parameters",e,t)};if("scrypt"===o.toLowerCase()){const r=Yi(es(e,"crypto/kdfparams/salt")),a=parseInt(es(e,"crypto/kdfparams/n")),c=parseInt(es(e,"crypto/kdfparams/r")),u=parseInt(es(e,"crypto/kdfparams/p"));a&&c&&u||t("kdf",o),a&a-1&&t("N",a);const l=parseInt(es(e,"crypto/kdfparams/dklen"));return 32!==l&&t("dklen",l),n(s,r,a,c,u,64,i)}if("pbkdf2"===o.toLowerCase()){const n=Yi(es(e,"crypto/kdfparams/salt"));let i=null;const o=es(e,"crypto/kdfparams/prf");"hmac-sha256"===o?i="sha256":"hmac-sha512"===o?i="sha512":t("prf",o);const a=parseInt(es(e,"crypto/kdfparams/c")),c=parseInt(es(e,"crypto/kdfparams/dklen"));return 32!==c&&t("dklen",c),r(s,n,a,c,i)}}return ns.throwArgumentError("unsupported key-derivation function","kdf",o)}const ls=new v(rs);class hs extends ue{isCrowdsaleAccount(e){return!(!e||!e._isCrowdsaleAccount)}}function ds(e,t){const r=JSON.parse(e);t=Xi(t);const n=Pe(es(r,"ethaddr")),i=Yi(es(r,"encseed"));i&&i.length%16==0||ls.throwArgumentError("invalid encseed","json",e);const s=_(bi(t,t,2e3,32,"sha256")).slice(0,16),o=i.slice(0,16),a=i.slice(16),c=new(Wi().ModeOfOperation.cbc)(s,o),u=Wi().padding.pkcs7.strip(_(c.decrypt(a)));let l="";for(let e=0;e<u.length;e++)l+=String.fromCharCode(u[e]);const h=ve(je(l));return new hs({_isCrowdsaleAccount:!0,address:n,privateKey:h})}function fs(e){let t=null;try{t=JSON.parse(e)}catch(e){return!1}return t.encseed&&t.ethaddr}function ps(e){let t=null;try{t=JSON.parse(e)}catch(e){return!1}return!(!t.version||parseInt(t.version)!==t.version||3!==parseInt(t.version))}function ms(e){if(fs(e))try{return Pe(JSON.parse(e).ethaddr)}catch(e){return null}if(ps(e))try{return Pe(JSON.parse(e).address)}catch(e){return null}return null}function gs(e,t,r){if(fs(e)){r&&r(0);const n=ds(e,t);return r&&r(1),Promise.resolve(n)}return ps(e)?function(e,t,r){return n=this,i=void 0,o=function*(){const n=JSON.parse(e);return os(n,yield us(n,t,cs,Zi().scrypt,r))},new((s=void 0)||(s=Promise))(function(e,t){function r(e){try{c(o.next(e))}catch(e){t(e)}}function a(e){try{c(o.throw(e))}catch(e){t(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof s?n:new s(function(e){e(n)})).then(r,a)}c((o=o.apply(n,i||[])).next())});var n,i,s,o}(e,t,r):Promise.reject(new Error("invalid JSON wallet"))}var ys=function(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};const vs=new v("wallet/5.8.0");class bs extends cr{constructor(e,t){if(super(),null!=(r=e)&&N(r.privateKey,32)&&null!=r.address){const t=new Yr(e.privateKey);if(ee(this,"_signingKey",()=>t),ee(this,"address",an(this.publicKey)),this.address!==Pe(e.address)&&vs.throwArgumentError("privateKey/address mismatch","privateKey","[REDACTED]"),function(e){const t=e.mnemonic;return t&&t.phrase}(e)){const t=e.mnemonic;ee(this,"_mnemonic",()=>({phrase:t.phrase,path:t.path||Bi,locale:t.locale||"en"}));const r=this.mnemonic;an(Li.fromMnemonic(r.phrase,null,r.locale).derivePath(r.path).privateKey)!==this.address&&vs.throwArgumentError("mnemonic/address mismatch","privateKey","[REDACTED]")}else ee(this,"_mnemonic",()=>null)}else{if(Yr.isSigningKey(e))"secp256k1"!==e.curve&&vs.throwArgumentError("unsupported curve; must be secp256k1","privateKey","[REDACTED]"),ee(this,"_signingKey",()=>e);else{"string"==typeof e&&e.match(/^[0-9a-f]*$/i)&&64===e.length&&(e="0x"+e);const t=new Yr(e);ee(this,"_signingKey",()=>t)}ee(this,"_mnemonic",()=>null),ee(this,"address",an(this.publicKey))}var r;t&&!nr.isProvider(t)&&vs.throwArgumentError("invalid provider","provider",t),ee(this,"provider",t||null)}get mnemonic(){return this._mnemonic()}get privateKey(){return this._signingKey().privateKey}get publicKey(){return this._signingKey().publicKey}getAddress(){return Promise.resolve(this.address)}connect(e){return new bs(this,e)}signTransaction(e){return re(e).then(t=>{null!=t.from&&(Pe(t.from)!==this.address&&vs.throwArgumentError("transaction from address mismatch","transaction.from",e.from),delete t.from);const r=this._signingKey().signDigest(ve(mn(t)));return mn(t,r)})}signMessage(e){return ys(this,void 0,void 0,function*(){return F(this._signingKey().signDigest(Wn(e)))})}_signTypedData(e,t,r){return ys(this,void 0,void 0,function*(){const n=yield li.resolveNames(e,t,r,e=>(null==this.provider&&vs.throwError("cannot resolve ENS names without a provider",v.errors.UNSUPPORTED_OPERATION,{operation:"resolveName",value:e}),this.provider.resolveName(e)));return F(this._signingKey().signDigest(li.hash(n.domain,t,n.value)))})}encrypt(e,t,r){if("function"!=typeof t||r||(r=t,t={}),r&&"function"!=typeof r)throw new Error("invalid callback");return t||(t={}),function(e,t,r,n){try{if(Pe(e.address)!==an(e.privateKey))throw new Error("address/privateKey mismatch");if(is(e)){const t=e.mnemonic;if(Li.fromMnemonic(t.phrase,null,t.locale).derivePath(t.path||Bi).privateKey!=e.privateKey)throw new Error("mnemonic mismatch")}}catch(e){return Promise.reject(e)}"function"!=typeof r||n||(n=r,r={}),r||(r={});const i=_(e.privateKey),s=Xi(t);let o=null,a=null,c=null;if(is(e)){const t=e.mnemonic;o=_(Fi(t.phrase,t.locale||"en")),a=t.path||Bi,c=t.locale||"en"}let u=r.client;u||(u="ethers.js");let l=null;l=r.salt?_(r.salt):Vi(32);let h=null;if(r.iv){if(h=_(r.iv),16!==h.length)throw new Error("invalid iv")}else h=Vi(16);let d=null;if(r.uuid){if(d=_(r.uuid),16!==d.length)throw new Error("invalid uuid")}else d=Vi(16);let f=1<<17,p=8,m=1;return r.scrypt&&(r.scrypt.N&&(f=r.scrypt.N),r.scrypt.r&&(p=r.scrypt.r),r.scrypt.p&&(m=r.scrypt.p)),Zi().scrypt(s,l,f,p,m,64,n).then(t=>{const r=(t=_(t)).slice(0,16),n=t.slice(16,32),s=t.slice(32,64),g=new(Wi().Counter)(h),y=_(new(Wi().ModeOfOperation.ctr)(r,g).encrypt(i)),v=ve(T([n,y])),b={address:e.address.substring(2).toLowerCase(),id:ts(d),version:3,crypto:{cipher:"aes-128-ctr",cipherparams:{iv:O(h).substring(2)},ciphertext:O(y).substring(2),kdf:"scrypt",kdfparams:{salt:O(l).substring(2),n:f,dklen:32,p:m,r:p},mac:v.substring(2)}};if(o){const e=Vi(16),t=new(Wi().Counter)(e),r=_(new(Wi().ModeOfOperation.ctr)(s,t).encrypt(o)),n=new Date,i=n.getUTCFullYear()+"-"+Qi(n.getUTCMonth()+1,2)+"-"+Qi(n.getUTCDate(),2)+"T"+Qi(n.getUTCHours(),2)+"-"+Qi(n.getUTCMinutes(),2)+"-"+Qi(n.getUTCSeconds(),2)+".0Z";b["x-ethers"]={client:u,gethFilename:"UTC--"+i+"--"+b.address,mnemonicCounter:O(e).substring(2),mnemonicCiphertext:O(r).substring(2),path:a,locale:c,version:"0.1"}}return JSON.stringify(b)})}(this,e,t,r)}static createRandom(e){let t=Vi(16);e||(e={}),e.extraEntropy&&(t=_(P(ve(T([t,e.extraEntropy])),0,16)));const r=$i(t,e.locale);return bs.fromMnemonic(r,e.path,e.locale)}static fromEncryptedJson(e,t,r){return gs(e,t,r).then(e=>new bs(e))}static fromEncryptedJsonSync(e,t){return new bs(function(e,t){if(fs(e))return ds(e,t);if(ps(e))return function(e,t){const r=JSON.parse(e);return os(r,us(r,t,as,Zi().syncScrypt))}(e,t);throw new Error("invalid JSON wallet")}(e,t))}static fromMnemonic(e,t,r){return t||(t=Bi),new bs(Li.fromMnemonic(e,null,r).derivePath(t))}}function ws(e,t){return cn(Wn(e),t)}function Es(e,t,r,n){return cn(li.hash(e,t,r),n)}const As="0x0000000000000000000000000000000000000000",ks="0x0000000000000000000000000000000000000000000000000000000000000000",xs="Ξ",_s=new v("networks/5.8.0");function Ts(e){const t=function(t,r){null==r&&(r={});const n=[];if(t.InfuraProvider&&"-"!==r.infura)try{n.push(new t.InfuraProvider(e,r.infura))}catch(e){}if(t.EtherscanProvider&&"-"!==r.etherscan)try{n.push(new t.EtherscanProvider(e,r.etherscan))}catch(e){}if(t.AlchemyProvider&&"-"!==r.alchemy)try{n.push(new t.AlchemyProvider(e,r.alchemy))}catch(e){}if(t.PocketProvider&&"-"!==r.pocket){const i=["goerli","ropsten","rinkeby","sepolia"];try{const s=new t.PocketProvider(e,r.pocket);s.network&&-1===i.indexOf(s.network.name)&&n.push(s)}catch(e){}}if(t.CloudflareProvider&&"-"!==r.cloudflare)try{n.push(new t.CloudflareProvider(e))}catch(e){}if(t.AnkrProvider&&"-"!==r.ankr)try{const i=["ropsten"],s=new t.AnkrProvider(e,r.ankr);s.network&&-1===i.indexOf(s.network.name)&&n.push(s)}catch(e){}if(t.QuickNodeProvider&&"-"!==r.quicknode)try{n.push(new t.QuickNodeProvider(e,r.quicknode))}catch(e){}if(0===n.length)return null;if(t.FallbackProvider){let i=1;return null!=r.quorum?i=r.quorum:"homestead"===e&&(i=2),new t.FallbackProvider(n,i)}return n[0]};return t.renetwork=function(e){return Ts(e)},t}function Ss(e,t){const r=function(r,n){return r.JsonRpcProvider?new r.JsonRpcProvider(e,t):null};return r.renetwork=function(t){return Ss(e,t)},r}const Is={chainId:1,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"homestead",_defaultProvider:Ts("homestead")},Ns={chainId:3,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"ropsten",_defaultProvider:Ts("ropsten")},Rs={chainId:63,name:"classicMordor",_defaultProvider:Ss("https://www.ethercluster.com/mordor","classicMordor")},Os={unspecified:{chainId:0,name:"unspecified"},homestead:Is,mainnet:Is,morden:{chainId:2,name:"morden"},ropsten:Ns,testnet:Ns,rinkeby:{chainId:4,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"rinkeby",_defaultProvider:Ts("rinkeby")},kovan:{chainId:42,name:"kovan",_defaultProvider:Ts("kovan")},goerli:{chainId:5,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"goerli",_defaultProvider:Ts("goerli")},kintsugi:{chainId:1337702,name:"kintsugi"},sepolia:{chainId:11155111,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"sepolia",_defaultProvider:Ts("sepolia")},holesky:{chainId:17e3,name:"holesky",_defaultProvider:Ts("holesky")},classic:{chainId:61,name:"classic",_defaultProvider:Ss("https://www.ethercluster.com/etc","classic")},classicMorden:{chainId:62,name:"classicMorden"},classicMordor:Rs,classicTestnet:Rs,classicKotti:{chainId:6,name:"classicKotti",_defaultProvider:Ss("https://www.ethercluster.com/kotti","classicKotti")},xdai:{chainId:100,name:"xdai"},matic:{chainId:137,name:"matic",_defaultProvider:Ts("matic")},maticmum:{chainId:80001,name:"maticmum",_defaultProvider:Ts("maticmum")},optimism:{chainId:10,name:"optimism",_defaultProvider:Ts("optimism")},"optimism-kovan":{chainId:69,name:"optimism-kovan"},"optimism-goerli":{chainId:420,name:"optimism-goerli"},"optimism-sepolia":{chainId:11155420,name:"optimism-sepolia"},arbitrum:{chainId:42161,name:"arbitrum"},"arbitrum-rinkeby":{chainId:421611,name:"arbitrum-rinkeby"},"arbitrum-goerli":{chainId:421613,name:"arbitrum-goerli"},"arbitrum-sepolia":{chainId:421614,name:"arbitrum-sepolia"},bnb:{chainId:56,name:"bnb"},bnbt:{chainId:97,name:"bnbt"}};function Cs(e){if(null==e)return null;if("number"==typeof e){for(const t in Os){const r=Os[t];if(r.chainId===e)return{name:r.name,chainId:r.chainId,ensAddress:r.ensAddress||null,_defaultProvider:r._defaultProvider||null}}return{chainId:e,name:"unknown"}}if("string"==typeof e){const t=Os[e];return null==t?null:{name:t.name,chainId:t.chainId,ensAddress:t.ensAddress,_defaultProvider:t._defaultProvider||null}}const t=Os[e.name];if(!t)return"number"!=typeof e.chainId&&_s.throwArgumentError("invalid network chainId","network",e),e;0!==e.chainId&&e.chainId!==t.chainId&&_s.throwArgumentError("network chainId mismatch","network",e);let r=e._defaultProvider||null;var n;return null==r&&t._defaultProvider&&(r=(n=t._defaultProvider)&&"function"==typeof n.renetwork?t._defaultProvider.renetwork(e):t._defaultProvider),{name:e.name,chainId:t.chainId,ensAddress:e.ensAddress||t.ensAddress||null,_defaultProvider:r}}function Ps(e){e=atob(e);const t=[];for(let r=0;r<e.length;r++)t.push(e.charCodeAt(r));return _(t)}function Ms(e){e=_(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Ds(e,t){null==t&&(t=1);const r=[],n=r.forEach,i=function(e,t){n.call(e,function(e){t>0&&Array.isArray(e)?i(e,t-1):r.push(e)})};return i(e,t),r}function Bs(e){return 1&e?~e>>1:e>>1}function Ls(e,t){let r=Array(e);for(let n=0,i=-1;n<e;n++)r[n]=i+=1+t();return r}function Us(e,t){let r=Array(e);for(let n=0,i=0;n<e;n++)r[n]=i+=Bs(t());return r}function Fs(e,t){let r=Ls(e(),e),n=e(),i=Ls(n,e),s=function(e,t){let r=Array(e);for(let n=0;n<e;n++)r[n]=1+t();return r}(n,e);for(let e=0;e<n;e++)for(let t=0;t<s[e];t++)r.push(i[e]+t);return t?r.map(e=>t[e]):r}function $s(e,t,r){let n=Array(e).fill(void 0).map(()=>[]);for(let i=0;i<t;i++)Us(e,r).forEach((e,t)=>n[t].push(e));return n}function Hs(e,t){let r=1+t(),n=t(),i=function(e){let t=[];for(;;){let r=e();if(0==r)break;t.push(r)}return t}(t);return Ds($s(i.length,1+e,t).map((e,t)=>{const s=e[0],o=e.slice(1);return Array(i[t]).fill(void 0).map((e,t)=>{let i=t*n;return[s+t*r,o.map(e=>e+i)]})}))}function Ks(e,t){return $s(1+t(),1+e,t).map(e=>[e[0],e.slice(1)])}const qs=function(e){let t=0;return()=>e[t++]}(function(e){let t=0;function r(){return e[t++]<<8|e[t++]}let n=r(),i=1,s=[0,1];for(let e=1;e<n;e++)s.push(i+=r());let o=r(),a=t;t+=o;let c=0,u=0;function l(){return 0==c&&(u=u<<8|e[t++],c=8),u>>--c&1}const h=Math.pow(2,31),d=h>>>1,f=d>>1,p=h-1;let m=0;for(let e=0;e<31;e++)m=m<<1|l();let g=[],y=0,v=h;for(;;){let e=Math.floor(((m-y+1)*i-1)/v),t=0,r=n;for(;r-t>1;){let n=t+r>>>1;e<s[n]?r=n:t=n}if(0==t)break;g.push(t);let o=y+Math.floor(v*s[t]/i),a=y+Math.floor(v*s[t+1]/i)-1;for(;0==((o^a)&d);)m=m<<1&p|l(),o=o<<1&p,a=a<<1&p|1;for(;o&~a&f;)m=m&d|m<<1&p>>>1|l(),o=o<<1^d,a=(a^d)<<1|d|1;y=o,v=1+a-o}let b=n-4;return g.map(t=>{switch(t-b){case 3:return b+65792+(e[a++]<<16|e[a++]<<8|e[a++]);case 2:return b+256+(e[a++]<<8|e[a++]);case 1:return b+e[a++];default:return t-1}})}(Ps("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))),js=new Set(Fs(qs)),zs=new Set(Fs(qs)),Vs=function(e){let t=[];for(;;){let r=e();if(0==r)break;t.push(Hs(r,e))}for(;;){let r=e()-1;if(r<0)break;t.push(Ks(r,e))}return function(e){const t={};for(let r=0;r<e.length;r++){const n=e[r];t[n[0]]=n[1]}return t}(Ds(t))}(qs),Gs=function(e){let t=Fs(e).sort((e,t)=>e-t);return function r(){let n=[];for(;;){let i=Fs(e,t);if(0==i.length)break;n.push({set:new Set(i),node:r()})}n.sort((e,t)=>t.set.size-e.set.size);let i=e(),s=i%3;i=i/3|0;let o=!!(1&i);return i>>=1,{branches:n,valid:s,fe0f:o,save:1==i,check:2==i}}()}(qs);function Ws(e){return Je(e)}function Js(e){return e.filter(e=>65039!=e)}function Zs(e){for(let t of e.split(".")){let e=Ws(t);try{for(let t=e.lastIndexOf(95)-1;t>=0;t--)if(95!==e[t])throw new Error("underscore only allowed at start");if(e.length>=4&&e.every(e=>e<128)&&45===e[2]&&45===e[3])throw new Error("invalid label extension")}catch(e){throw new Error(`Invalid label "${t}": ${e.message}`)}}return e}function Ys(e,t){var r;let n,i,s=Gs,o=[],a=e.length;for(t&&(t.length=0);a;){let c=e[--a];if(s=null===(r=s.branches.find(e=>e.set.has(c)))||void 0===r?void 0:r.node,!s)break;if(s.save)i=c;else if(s.check&&c===i)break;o.push(c),s.fe0f&&(o.push(65039),a>0&&65039==e[a-1]&&a--),s.valid&&(n=o.slice(),2==s.valid&&n.splice(1,1),t&&t.push(...e.slice(a).reverse()),e.length=a)}return n}const Qs=new v(Jn),Xs=new Uint8Array(32);function eo(e){if(0===e.length)throw new Error("invalid ENS name; empty component");return e}function to(e){const t=je(function(e){return Zs(function(e,t){let r=Ws(e).reverse(),n=[];for(;r.length;){let e=Ys(r);if(e){n.push(...t(e));continue}let i=r.pop();if(js.has(i)){n.push(i);continue}if(zs.has(i))continue;let s=Vs[i];if(!s)throw new Error(`Disallowed codepoint: 0x${i.toString(16).toUpperCase()}`);n.push(...s)}return Zs(String.fromCodePoint(...n).normalize("NFC"))}(e,Js))}(e)),r=[];if(0===e.length)return r;let n=0;for(let e=0;e<t.length;e++)46===t[e]&&(r.push(eo(t.slice(n,e))),n=e+1);if(n>=t.length)throw new Error("invalid ENS name; empty component");return r.push(eo(t.slice(n))),r}function ro(e){try{return 0!==to(e).length}catch(e){}return!1}function no(e){"string"!=typeof e&&Qs.throwArgumentError("invalid ENS name; not a string","name",e);let t=Xs;const r=to(e);for(;r.length;)t=ve(T([t,ve(r.pop())]));return O(t)}function io(e){return O(T(to(e).map(e=>{if(e.length>63)throw new Error("invalid DNS encoded entry; length exceeds 63 bytes");const t=new Uint8Array(e.length+1);return t.set(e,1),t[0]=t.length-1,t})))+"00"}Xs.fill(0);function so(e,t){return r=this,n=void 0,s=function*(){null==t&&(t={});const r={method:t.method||"GET",headers:t.headers||{},body:t.body||void 0};if(!0!==t.skipFetchSetup&&(r.mode="cors",r.cache="no-cache",r.credentials="same-origin",r.redirect="follow",r.referrer="client"),null!=t.fetchOptions){const e=t.fetchOptions;e.mode&&(r.mode=e.mode),e.cache&&(r.cache=e.cache),e.credentials&&(r.credentials=e.credentials),e.redirect&&(r.redirect=e.redirect),e.referrer&&(r.referrer=e.referrer)}const n=yield fetch(e,r),i=yield n.arrayBuffer(),s={};return n.headers.forEach?n.headers.forEach((e,t)=>{s[t.toLowerCase()]=e}):n.headers.keys().forEach(e=>{s[e.toLowerCase()]=n.headers.get(e)}),{headers:s,statusCode:n.status,statusMessage:n.statusText,body:_(new Uint8Array(i))}},new((i=void 0)||(i=Promise))(function(e,t){function o(e){try{c(s.next(e))}catch(e){t(e)}}function a(e){try{c(s.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i(function(e){e(r)})).then(o,a)}c((s=s.apply(r,n||[])).next())});var r,n,i,s}const oo=new v("web/5.8.0");function ao(e){return new Promise(t=>{setTimeout(t,e)})}function co(e,t){if(null==e)return null;if("string"==typeof e)return e;if(A(e)){if(t&&("text"===t.split("/")[0]||"application/json"===t.split(";")[0].trim()))try{return We(e)}catch(e){}return O(e)}return e}function uo(e,t,r){const n="object"==typeof e&&null!=e.throttleLimit?e.throttleLimit:12;oo.assertArgument(n>0&&n%1==0,"invalid connection throttle limit","connection.throttleLimit",n);const i="object"==typeof e?e.throttleCallback:null,s="object"==typeof e&&"number"==typeof e.throttleSlotInterval?e.throttleSlotInterval:100;oo.assertArgument(s>0&&s%1==0,"invalid connection throttle slot interval","connection.throttleSlotInterval",s);const o="object"==typeof e&&!!e.errorPassThrough,a={};let c=null;const u={method:"GET"};let l=!1,h=12e4;if("string"==typeof e)c=e;else if("object"==typeof e){if(null!=e&&null!=e.url||oo.throwArgumentError("missing URL","connection.url",e),c=e.url,"number"==typeof e.timeout&&e.timeout>0&&(h=e.timeout),e.headers)for(const t in e.headers)a[t.toLowerCase()]={key:t,value:String(e.headers[t])},["if-none-match","if-modified-since"].indexOf(t.toLowerCase())>=0&&(l=!0);if(u.allowGzip=!!e.allowGzip,null!=e.user&&null!=e.password){"https:"!==c.substring(0,6)&&!0!==e.allowInsecureAuthentication&&oo.throwError("basic authentication requires a secure https url",v.errors.INVALID_ARGUMENT,{argument:"url",url:c,user:e.user,password:"[REDACTED]"});const t=e.user+":"+e.password;a.authorization={key:"Authorization",value:"Basic "+Ms(je(t))}}null!=e.skipFetchSetup&&(u.skipFetchSetup=!!e.skipFetchSetup),null!=e.fetchOptions&&(u.fetchOptions=ie(e.fetchOptions))}const d=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),f=c?c.match(d):null;if(f)try{const e={statusCode:200,statusMessage:"OK",headers:{"content-type":f[1]||"text/plain"},body:f[2]?Ps(f[3]):(p=f[3],je(p.replace(/%([0-9a-f][0-9a-f])/gi,(e,t)=>String.fromCharCode(parseInt(t,16)))))};let t=e.body;return r&&(t=r(e.body,e)),Promise.resolve(t)}catch(e){oo.throwError("processing response error",v.errors.SERVER_ERROR,{body:co(f[1],f[2]),error:e,requestBody:null,requestMethod:"GET",url:c})}var p;t&&(u.method="POST",u.body=t,null==a["content-type"]&&(a["content-type"]={key:"Content-Type",value:"application/octet-stream"}),null==a["content-length"]&&(a["content-length"]={key:"Content-Length",value:String(t.length)}));const m={};Object.keys(a).forEach(e=>{const t=a[e];m[t.key]=t.value}),u.headers=m;const g=function(){let e=null;return{promise:new Promise(function(t,r){h&&(e=setTimeout(()=>{null!=e&&(e=null,r(oo.makeError("timeout",v.errors.TIMEOUT,{requestBody:co(u.body,m["content-type"]),requestMethod:u.method,timeout:h,url:c})))},h))}),cancel:function(){null!=e&&(clearTimeout(e),e=null)}}}(),y=function(){return e=this,t=void 0,h=function*(){for(let e=0;e<n;e++){let t=null;try{if(t=yield so(c,u),e<n)if(301===t.statusCode||302===t.statusCode){const e=t.headers.location||"";if("GET"===u.method&&e.match(/^https:/)){c=t.headers.location;continue}}else if(429===t.statusCode){let r=!0;if(i&&(r=yield i(e,c)),r){let r=0;const n=t.headers["retry-after"];r="string"==typeof n&&n.match(/^[1-9][0-9]*$/)?1e3*parseInt(n):s*parseInt(String(Math.random()*Math.pow(2,e))),yield ao(r);continue}}}catch(e){t=e.response,null==t&&(g.cancel(),oo.throwError("missing response",v.errors.SERVER_ERROR,{requestBody:co(u.body,m["content-type"]),requestMethod:u.method,serverError:e,url:c}))}let a=t.body;if(l&&304===t.statusCode?a=null:!o&&(t.statusCode<200||t.statusCode>=300)&&(g.cancel(),oo.throwError("bad response",v.errors.SERVER_ERROR,{status:t.statusCode,headers:t.headers,body:co(a,t.headers?t.headers["content-type"]:null),requestBody:co(u.body,m["content-type"]),requestMethod:u.method,url:c})),r)try{const e=yield r(a,t);return g.cancel(),e}catch(r){if(r.throttleRetry&&e<n){let t=!0;if(i&&(t=yield i(e,c)),t){const t=s*parseInt(String(Math.random()*Math.pow(2,e)));yield ao(t);continue}}g.cancel(),oo.throwError("processing response error",v.errors.SERVER_ERROR,{body:co(a,t.headers?t.headers["content-type"]:null),error:r,requestBody:co(u.body,m["content-type"]),requestMethod:u.method,url:c})}return g.cancel(),a}return oo.throwError("failed response",v.errors.SERVER_ERROR,{requestBody:co(u.body,m["content-type"]),requestMethod:u.method,url:c})},new((a=void 0)||(a=Promise))(function(r,n){function i(e){try{o(h.next(e))}catch(e){n(e)}}function s(e){try{o(h.throw(e))}catch(e){n(e)}}function o(e){var t;e.done?r(e.value):(t=e.value,t instanceof a?t:new a(function(e){e(t)})).then(i,s)}o((h=h.apply(e,t||[])).next())});var e,t,a,h}();return Promise.race([g.promise,y])}function lo(e,t,r){let n=null;if(null!=t){n=je(t);const r="string"==typeof e?{url:e}:ie(e);r.headers?0!==Object.keys(r.headers).filter(e=>"content-type"===e.toLowerCase()).length||(r.headers=ie(r.headers),r.headers["content-type"]="application/json"):r.headers={"content-type":"application/json"},e=r}return uo(e,n,(e,t)=>{let n=null;if(null!=e)try{n=JSON.parse(We(e))}catch(t){oo.throwError("invalid JSON",v.errors.SERVER_ERROR,{body:e,error:t})}return r&&(n=r(n,t)),n})}function ho(e,t){return t||(t={}),null==(t=ie(t)).floor&&(t.floor=0),null==t.ceiling&&(t.ceiling=1e4),null==t.interval&&(t.interval=250),new Promise(function(r,n){let i=null,s=!1;const o=()=>!s&&(s=!0,i&&clearTimeout(i),!0);t.timeout&&(i=setTimeout(()=>{o()&&n(new Error("timeout"))},t.timeout));const a=t.retryLimit;let c=0;!function i(){return e().then(function(e){if(void 0!==e)o()&&r(e);else if(t.oncePoll)t.oncePoll.once("poll",i);else if(t.onceBlock)t.onceBlock.once("block",i);else if(!s){if(c++,c>a)return void(o()&&n(new Error("retry limit reached")));let e=t.interval*parseInt(String(Math.random()*Math.pow(2,c)));e<t.floor&&(e=t.floor),e>t.ceiling&&(e=t.ceiling),setTimeout(i,e)}return null},function(e){o()&&n(e)})}()})}var fo=r(8993),po=r.n(fo);const mo="providers/5.8.0",go=new v(mo);class yo{constructor(){this.formats=this.getDefaultFormats()}getDefaultFormats(){const e={},t=this.address.bind(this),r=this.bigNumber.bind(this),n=this.blockTag.bind(this),i=this.data.bind(this),s=this.hash.bind(this),o=this.hex.bind(this),a=this.number.bind(this),c=this.type.bind(this);return e.transaction={hash:s,type:c,accessList:yo.allowNull(this.accessList.bind(this),null),blockHash:yo.allowNull(s,null),blockNumber:yo.allowNull(a,null),transactionIndex:yo.allowNull(a,null),confirmations:yo.allowNull(a,null),from:t,gasPrice:yo.allowNull(r),maxPriorityFeePerGas:yo.allowNull(r),maxFeePerGas:yo.allowNull(r),gasLimit:r,to:yo.allowNull(t,null),value:r,nonce:a,data:i,r:yo.allowNull(this.uint256),s:yo.allowNull(this.uint256),v:yo.allowNull(a),creates:yo.allowNull(t,null),raw:yo.allowNull(i)},e.transactionRequest={from:yo.allowNull(t),nonce:yo.allowNull(a),gasLimit:yo.allowNull(r),gasPrice:yo.allowNull(r),maxPriorityFeePerGas:yo.allowNull(r),maxFeePerGas:yo.allowNull(r),to:yo.allowNull(t),value:yo.allowNull(r),data:yo.allowNull(e=>this.data(e,!0)),type:yo.allowNull(a),accessList:yo.allowNull(this.accessList.bind(this),null)},e.receiptLog={transactionIndex:a,blockNumber:a,transactionHash:s,address:t,topics:yo.arrayOf(s),data:i,logIndex:a,blockHash:s},e.receipt={to:yo.allowNull(this.address,null),from:yo.allowNull(this.address,null),contractAddress:yo.allowNull(t,null),transactionIndex:a,root:yo.allowNull(o),gasUsed:r,logsBloom:yo.allowNull(i),blockHash:s,transactionHash:s,logs:yo.arrayOf(this.receiptLog.bind(this)),blockNumber:a,confirmations:yo.allowNull(a,null),cumulativeGasUsed:r,effectiveGasPrice:yo.allowNull(r),status:yo.allowNull(a),type:c},e.block={hash:yo.allowNull(s),parentHash:s,number:a,timestamp:a,nonce:yo.allowNull(o),difficulty:this.difficulty.bind(this),gasLimit:r,gasUsed:r,miner:yo.allowNull(t),extraData:i,transactions:yo.allowNull(yo.arrayOf(s)),baseFeePerGas:yo.allowNull(r)},e.blockWithTransactions=ie(e.block),e.blockWithTransactions.transactions=yo.allowNull(yo.arrayOf(this.transactionResponse.bind(this))),e.filter={fromBlock:yo.allowNull(n,void 0),toBlock:yo.allowNull(n,void 0),blockHash:yo.allowNull(s,void 0),address:yo.allowNull(t,void 0),topics:yo.allowNull(this.topics.bind(this),void 0)},e.filterLog={blockNumber:yo.allowNull(a),blockHash:yo.allowNull(s),transactionIndex:a,removed:yo.allowNull(this.boolean.bind(this)),address:t,data:yo.allowFalsish(i,"0x"),topics:yo.arrayOf(s),transactionHash:s,logIndex:a},e}accessList(e){return hn(e||[])}number(e){return"0x"===e?0:W.from(e).toNumber()}type(e){return"0x"===e||null==e?0:W.from(e).toNumber()}bigNumber(e){return W.from(e)}boolean(e){if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===(e=e.toLowerCase()))return!0;if("false"===e)return!1}throw new Error("invalid boolean - "+e)}hex(e,t){return"string"==typeof e&&(t||"0x"===e.substring(0,2)||(e="0x"+e),N(e))?e.toLowerCase():go.throwArgumentError("invalid hash","value",e)}data(e,t){const r=this.hex(e,t);if(r.length%2!=0)throw new Error("invalid data; odd-length - "+e);return r}address(e){return Pe(e)}callAddress(e){if(!N(e,32))return null;const t=Pe(P(e,12));return t===As?null:t}contractAddress(e){return Be(e)}blockTag(e){if(null==e)return"latest";if("earliest"===e)return"0x0";switch(e){case"earliest":return"0x0";case"latest":case"pending":case"safe":case"finalized":return e}if("number"==typeof e||N(e))return D(e);throw new Error("invalid blockTag")}hash(e,t){const r=this.hex(e,t);return 32!==C(r)?go.throwArgumentError("invalid hash","value",e):r}difficulty(e){if(null==e)return null;const t=W.from(e);try{return t.toNumber()}catch(e){}return null}uint256(e){if(!N(e))throw new Error("invalid uint256");return L(e,32)}_block(e,t){null!=e.author&&null==e.miner&&(e.miner=e.author);const r=null!=e._difficulty?e._difficulty:e.difficulty,n=yo.check(t,e);return n._difficulty=null==r?null:W.from(r),n}block(e){return this._block(e,this.formats.block)}blockWithTransactions(e){return this._block(e,this.formats.blockWithTransactions)}transactionRequest(e){return yo.check(this.formats.transactionRequest,e)}transactionResponse(e){null!=e.gas&&null==e.gasLimit&&(e.gasLimit=e.gas),e.to&&W.from(e.to).isZero()&&(e.to="0x0000000000000000000000000000000000000000"),null!=e.input&&null==e.data&&(e.data=e.input),null==e.to&&null==e.creates&&(e.creates=this.contractAddress(e)),1!==e.type&&2!==e.type||null!=e.accessList||(e.accessList=[]);const t=yo.check(this.formats.transaction,e);if(null!=e.chainId){let r=e.chainId;N(r)&&(r=W.from(r).toNumber()),t.chainId=r}else{let r=e.networkId;null==r&&null==t.v&&(r=e.chainId),N(r)&&(r=W.from(r).toNumber()),"number"!=typeof r&&null!=t.v&&(r=(t.v-35)/2,r<0&&(r=0),r=parseInt(r)),"number"!=typeof r&&(r=0),t.chainId=r}return t.blockHash&&"x"===t.blockHash.replace(/0/g,"")&&(t.blockHash=null),t}transaction(e){return yn(e)}receiptLog(e){return yo.check(this.formats.receiptLog,e)}receipt(e){const t=yo.check(this.formats.receipt,e);if(null!=t.root)if(t.root.length<=4){const e=W.from(t.root).toNumber();0===e||1===e?(null!=t.status&&t.status!==e&&go.throwArgumentError("alt-root-status/status mismatch","value",{root:t.root,status:t.status}),t.status=e,delete t.root):go.throwArgumentError("invalid alt-root-status","value.root",t.root)}else 66!==t.root.length&&go.throwArgumentError("invalid root hash","value.root",t.root);return null!=t.status&&(t.byzantium=!0),t}topics(e){return Array.isArray(e)?e.map(e=>this.topics(e)):null!=e?this.hash(e,!0):null}filter(e){return yo.check(this.formats.filter,e)}filterLog(e){return yo.check(this.formats.filterLog,e)}static check(e,t){const r={};for(const n in e)try{const i=e[n](t[n]);void 0!==i&&(r[n]=i)}catch(e){throw e.checkKey=n,e.checkValue=t[n],e}return r}static allowNull(e,t){return function(r){return null==r?t:e(r)}}static allowFalsish(e,t){return function(r){return r?e(r):t}}static arrayOf(e){return function(t){if(!Array.isArray(t))throw new Error("not an array");const r=[];return t.forEach(function(t){r.push(e(t))}),r}}}function vo(e){return e&&"function"==typeof e.isCommunityResource}function bo(e){return vo(e)&&e.isCommunityResource()}let wo=!1;function Eo(){wo||(wo=!0,console.log("========= NOTICE ========="),console.log("Request-Rate Exceeded (this message will not be repeated)"),console.log(""),console.log("The default API keys for each service are provided as a highly-throttled,"),console.log("community resource for low-traffic projects and early prototyping."),console.log(""),console.log("While your application will continue to function, we highly recommended"),console.log("signing up for your own API keys to improve performance, increase your"),console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."),console.log(""),console.log("For more details: https://docs.ethers.io/api-keys/"),console.log("=========================="))}var Ao=function(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};const ko=new v(mo);function xo(e){return null==e?"null":(32!==C(e)&&ko.throwArgumentError("invalid topic","topic",e),e.toLowerCase())}function _o(e){for(e=e.slice();e.length>0&&null==e[e.length-1];)e.pop();return e.map(e=>{if(Array.isArray(e)){const t={};e.forEach(e=>{t[xo(e)]=!0});const r=Object.keys(t);return r.sort(),r.join("|")}return xo(e)}).join("&")}function To(e){if("string"==typeof e){if(32===C(e=e.toLowerCase()))return"tx:"+e;if(-1===e.indexOf(":"))return e}else{if(Array.isArray(e))return"filter:*:"+_o(e);if(rr.isForkEvent(e))throw ko.warn("not implemented"),new Error("not implemented");if(e&&"object"==typeof e)return"filter:"+(e.address||"*")+":"+_o(e.topics||[])}throw new Error("invalid event - "+e)}function So(){return(new Date).getTime()}function Io(e){return new Promise(t=>{setTimeout(t,e)})}const No=["block","network","pending","poll"];class Ro{constructor(e,t,r){ee(this,"tag",e),ee(this,"listener",t),ee(this,"once",r),this._lastBlockNumber=-2,this._inflight=!1}get event(){switch(this.type){case"tx":return this.hash;case"filter":return this.filter}return this.tag}get type(){return this.tag.split(":")[0]}get hash(){const e=this.tag.split(":");return"tx"!==e[0]?null:e[1]}get filter(){const e=this.tag.split(":");if("filter"!==e[0])return null;const t=e[1],r=""===(n=e[2])?[]:n.split(/&/g).map(e=>{if(""===e)return[];const t=e.split("|").map(e=>"null"===e?null:e);return 1===t.length?t[0]:t});var n;const i={};return r.length>0&&(i.topics=r),t&&"*"!==t&&(i.address=t),i}pollable(){return this.tag.indexOf(":")>=0||No.indexOf(this.tag)>=0}}const Oo={0:{symbol:"btc",p2pkh:0,p2sh:5,prefix:"bc"},2:{symbol:"ltc",p2pkh:48,p2sh:50,prefix:"ltc"},3:{symbol:"doge",p2pkh:30,p2sh:22},60:{symbol:"eth",ilk:"eth"},61:{symbol:"etc",ilk:"eth"},700:{symbol:"xdai",ilk:"eth"}};function Co(e){return L(W.from(e).toHexString(),32)}function Po(e){return di.encode(T([e,P(gi(gi(e)),0,4)]))}const Mo=new RegExp("^(ipfs)://(.*)$","i"),Do=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),Mo,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];function Bo(e,t){try{return We(Lo(e,t))}catch(e){}return null}function Lo(e,t){if("0x"===e)return null;const r=W.from(P(e,t,t+32)).toNumber(),n=W.from(P(e,r,r+32)).toNumber();return P(e,r+32,r+32+n)}function Uo(e){return e.match(/^ipfs:\/\/ipfs\//i)?e=e.substring(12):e.match(/^ipfs:\/\//i)?e=e.substring(7):ko.throwArgumentError("unsupported IPFS format","link",e),`https://gateway.ipfs.io/ipfs/${e}`}function Fo(e){const t=_(e);if(t.length>32)throw new Error("internal; should not happen");const r=new Uint8Array(32);return r.set(t,32-t.length),r}function $o(e){if(e.length%32==0)return e;const t=new Uint8Array(32*Math.ceil(e.length/32));return t.set(e),t}function Ho(e){const t=[];let r=0;for(let n=0;n<e.length;n++)t.push(null),r+=32;for(let n=0;n<e.length;n++){const i=_(e[n]);t[n]=Fo(r),t.push(Fo(i.length)),t.push($o(i)),r+=32+32*Math.ceil(i.length/32)}return M(t)}class Ko{constructor(e,t,r,n){ee(this,"provider",e),ee(this,"name",r),ee(this,"address",e.formatter.address(t)),ee(this,"_resolvedAddress",n)}supportsWildcard(){return this._supportsEip2544||(this._supportsEip2544=this.provider.call({to:this.address,data:"0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000"}).then(e=>W.from(e).eq(1)).catch(e=>{if(e.code===v.errors.CALL_EXCEPTION)return!1;throw this._supportsEip2544=null,e})),this._supportsEip2544}_fetch(e,t){return Ao(this,void 0,void 0,function*(){const r={to:this.address,ccipReadEnabled:!0,data:M([e,no(this.name),t||"0x"])};let n=!1;(yield this.supportsWildcard())&&(n=!0,r.data=M(["0x9061b923",Ho([io(this.name),r.data])]));try{let e=yield this.provider.call(r);return _(e).length%32==4&&ko.throwError("resolver threw error",v.errors.CALL_EXCEPTION,{transaction:r,data:e}),n&&(e=Lo(e,0)),e}catch(e){if(e.code===v.errors.CALL_EXCEPTION)return null;throw e}})}_fetchBytes(e,t){return Ao(this,void 0,void 0,function*(){const r=yield this._fetch(e,t);return null!=r?Lo(r,0):null})}_getAddress(e,t){const r=Oo[String(e)];if(null==r&&ko.throwError(`unsupported coin type: ${e}`,v.errors.UNSUPPORTED_OPERATION,{operation:`getAddress(${e})`}),"eth"===r.ilk)return this.provider.formatter.address(t);const n=_(t);if(null!=r.p2pkh){const e=t.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/);if(e){const t=parseInt(e[1],16);if(e[2].length===2*t&&t>=1&&t<=75)return Po(T([[r.p2pkh],"0x"+e[2]]))}}if(null!=r.p2sh){const e=t.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/);if(e){const t=parseInt(e[1],16);if(e[2].length===2*t&&t>=1&&t<=75)return Po(T([[r.p2sh],"0x"+e[2]]))}}if(null!=r.prefix){const e=n[1];let t=n[0];if(0===t?20!==e&&32!==e&&(t=-1):t=-1,t>=0&&n.length===2+e&&e>=1&&e<=75){const e=po().toWords(n.slice(2));return e.unshift(t),po().encode(r.prefix,e)}}return null}getAddress(e){return Ao(this,void 0,void 0,function*(){if(null==e&&(e=60),60===e)try{const e=yield this._fetch("0x3b3b57de");return"0x"===e||e===ks?null:this.provider.formatter.callAddress(e)}catch(e){if(e.code===v.errors.CALL_EXCEPTION)return null;throw e}const t=yield this._fetchBytes("0xf1cb7e06",Co(e));if(null==t||"0x"===t)return null;const r=this._getAddress(e,t);return null==r&&ko.throwError("invalid or unsupported coin data",v.errors.UNSUPPORTED_OPERATION,{operation:`getAddress(${e})`,coinType:e,data:t}),r})}getAvatar(){return Ao(this,void 0,void 0,function*(){const e=[{type:"name",content:this.name}];try{const t=yield this.getText("avatar");if(null==t)return null;for(let r=0;r<Do.length;r++){const n=t.match(Do[r]);if(null==n)continue;const i=n[1].toLowerCase();switch(i){case"https":return e.push({type:"url",content:t}),{linkage:e,url:t};case"data":return e.push({type:"data",content:t}),{linkage:e,url:t};case"ipfs":return e.push({type:"ipfs",content:t}),{linkage:e,url:Uo(t)};case"erc721":case"erc1155":{const r="erc721"===i?"0xc87b56dd":"0x0e89341c";e.push({type:i,content:t});const s=this._resolvedAddress||(yield this.getAddress()),o=(n[2]||"").split("/");if(2!==o.length)return null;const a=yield this.provider.formatter.address(o[0]),c=L(W.from(o[1]).toHexString(),32);if("erc721"===i){const t=this.provider.formatter.callAddress(yield this.provider.call({to:a,data:M(["0x6352211e",c])}));if(s!==t)return null;e.push({type:"owner",content:t})}else if("erc1155"===i){const t=W.from(yield this.provider.call({to:a,data:M(["0x00fdd58e",L(s,32),c])}));if(t.isZero())return null;e.push({type:"balance",content:t.toString()})}const u={to:this.provider.formatter.address(o[0]),data:M([r,c])};let l=Bo(yield this.provider.call(u),0);if(null==l)return null;e.push({type:"metadata-url-base",content:l}),"erc1155"===i&&(l=l.replace("{id}",c.substring(2)),e.push({type:"metadata-url-expanded",content:l})),l.match(/^ipfs:/i)&&(l=Uo(l)),e.push({type:"metadata-url",content:l});const h=yield lo(l);if(!h)return null;e.push({type:"metadata",content:JSON.stringify(h)});let d=h.image;if("string"!=typeof d)return null;if(d.match(/^(https:\/\/|data:)/i));else{if(null==d.match(Mo))return null;e.push({type:"url-ipfs",content:d}),d=Uo(d)}return e.push({type:"url",content:d}),{linkage:e,url:d}}}}}catch(e){}return null})}getContentHash(){return Ao(this,void 0,void 0,function*(){const e=yield this._fetchBytes("0xbc1c58d1");if(null==e||"0x"===e)return null;const t=e.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(t){const e=parseInt(t[3],16);if(t[4].length===2*e)return"ipfs://"+di.encode("0x"+t[1])}const r=e.match(/^0xe5010172(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(r){const e=parseInt(r[3],16);if(r[4].length===2*e)return"ipns://"+di.encode("0x"+r[1])}const n=e.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(n&&64===n[1].length)return"bzz://"+n[1];const i=e.match(/^0x90b2c605([0-9a-f]*)$/);if(i&&68===i[1].length){const e={"=":"","+":"-","/":"_"};return"sia://"+Ms("0x"+i[1]).replace(/[=+\/]/g,t=>e[t])}return ko.throwError("invalid or unsupported content hash data",v.errors.UNSUPPORTED_OPERATION,{operation:"getContentHash()",data:e})})}getText(e){return Ao(this,void 0,void 0,function*(){let t=je(e);t=T([Co(64),Co(t.length),t]),t.length%32!=0&&(t=T([t,L("0x",32-e.length%32)]));const r=yield this._fetchBytes("0x59d1d43c",O(t));return null==r||"0x"===r?null:We(r)})}}let qo=null,jo=1;class zo extends nr{constructor(e){if(super(),this._events=[],this._emitted={block:-2},this.disableCcipRead=!1,this.formatter=new.target.getFormatter(),ee(this,"anyNetwork","any"===e),this.anyNetwork&&(e=this.detectNetwork()),e instanceof Promise)this._networkPromise=e,e.catch(e=>{}),this._ready().catch(e=>{});else{const t=te(new.target,"getNetwork")(e);t?(ee(this,"_network",t),this.emit("network",t,null)):ko.throwArgumentError("invalid network","network",e)}this._maxInternalBlockNumber=-1024,this._lastBlockNumber=-2,this._maxFilterBlockRange=10,this._pollingInterval=4e3,this._fastQueryDate=0}_ready(){return Ao(this,void 0,void 0,function*(){if(null==this._network){let e=null;if(this._networkPromise)try{e=yield this._networkPromise}catch(e){}null==e&&(e=yield this.detectNetwork()),e||ko.throwError("no network detected",v.errors.UNKNOWN_ERROR,{}),null==this._network&&(this.anyNetwork?this._network=e:ee(this,"_network",e),this.emit("network",e,null))}return this._network})}get ready(){return ho(()=>this._ready().then(e=>e,e=>{if(e.code!==v.errors.NETWORK_ERROR||"noNetwork"!==e.event)throw e}))}static getFormatter(){return null==qo&&(qo=new yo),qo}static getNetwork(e){return Cs(null==e?"homestead":e)}ccipReadFetch(e,t,r){return Ao(this,void 0,void 0,function*(){if(this.disableCcipRead||0===r.length)return null;const n=e.to.toLowerCase(),i=t.toLowerCase(),s=[];for(let e=0;e<r.length;e++){const t=r[e],o=t.replace("{sender}",n).replace("{data}",i),a=t.indexOf("{data}")>=0?null:JSON.stringify({data:i,sender:n}),c=yield lo({url:o,errorPassThrough:!0},a,(e,t)=>(e.status=t.statusCode,e));if(c.data)return c.data;const u=c.message||"unknown error";if(c.status>=400&&c.status<500)return ko.throwError(`response not found during CCIP fetch: ${u}`,v.errors.SERVER_ERROR,{url:t,errorMessage:u});s.push(u)}return ko.throwError(`error encountered during CCIP fetch: ${s.map(e=>JSON.stringify(e)).join(", ")}`,v.errors.SERVER_ERROR,{urls:r,errorMessages:s})})}_getInternalBlockNumber(e){return Ao(this,void 0,void 0,function*(){if(yield this._ready(),e>0)for(;this._internalBlockNumber;){const t=this._internalBlockNumber;try{const r=yield t;if(So()-r.respTime<=e)return r.blockNumber;break}catch(e){if(this._internalBlockNumber===t)break}}const t=So(),r=re({blockNumber:this.perform("getBlockNumber",{}),networkError:this.getNetwork().then(e=>null,e=>e)}).then(({blockNumber:e,networkError:n})=>{if(n)throw this._internalBlockNumber===r&&(this._internalBlockNumber=null),n;const i=So();return(e=W.from(e).toNumber())<this._maxInternalBlockNumber&&(e=this._maxInternalBlockNumber),this._maxInternalBlockNumber=e,this._setFastBlockNumber(e),{blockNumber:e,reqTime:t,respTime:i}});return this._internalBlockNumber=r,r.catch(e=>{this._internalBlockNumber===r&&(this._internalBlockNumber=null)}),(yield r).blockNumber})}poll(){return Ao(this,void 0,void 0,function*(){const e=jo++,t=[];let r=null;try{r=yield this._getInternalBlockNumber(100+this.pollingInterval/2)}catch(e){return void this.emit("error",e)}if(this._setFastBlockNumber(r),this.emit("poll",e,r),r!==this._lastBlockNumber){if(-2===this._emitted.block&&(this._emitted.block=r-1),Math.abs(this._emitted.block-r)>1e3)ko.warn(`network block skew detected; skipping block events (emitted=${this._emitted.block} blockNumber${r})`),this.emit("error",ko.makeError("network block skew detected",v.errors.NETWORK_ERROR,{blockNumber:r,event:"blockSkew",previousBlockNumber:this._emitted.block})),this.emit("block",r);else for(let e=this._emitted.block+1;e<=r;e++)this.emit("block",e);this._emitted.block!==r&&(this._emitted.block=r,Object.keys(this._emitted).forEach(e=>{if("block"===e)return;const t=this._emitted[e];"pending"!==t&&r-t>12&&delete this._emitted[e]})),-2===this._lastBlockNumber&&(this._lastBlockNumber=r-1),this._events.forEach(e=>{switch(e.type){case"tx":{const r=e.hash;let n=this.getTransactionReceipt(r).then(e=>e&&null!=e.blockNumber?(this._emitted["t:"+r]=e.blockNumber,this.emit(r,e),null):null).catch(e=>{this.emit("error",e)});t.push(n);break}case"filter":if(!e._inflight){e._inflight=!0,-2===e._lastBlockNumber&&(e._lastBlockNumber=r-1);const n=e.filter;n.fromBlock=e._lastBlockNumber+1,n.toBlock=r;const i=n.toBlock-this._maxFilterBlockRange;i>n.fromBlock&&(n.fromBlock=i),n.fromBlock<0&&(n.fromBlock=0);const s=this.getLogs(n).then(t=>{e._inflight=!1,0!==t.length&&t.forEach(t=>{t.blockNumber>e._lastBlockNumber&&(e._lastBlockNumber=t.blockNumber),this._emitted["b:"+t.blockHash]=t.blockNumber,this._emitted["t:"+t.transactionHash]=t.blockNumber,this.emit(n,t)})}).catch(t=>{this.emit("error",t),e._inflight=!1});t.push(s)}}}),this._lastBlockNumber=r,Promise.all(t).then(()=>{this.emit("didPoll",e)}).catch(e=>{this.emit("error",e)})}else this.emit("didPoll",e)})}resetEventsBlock(e){this._lastBlockNumber=e-1,this.polling&&this.poll()}get network(){return this._network}detectNetwork(){return Ao(this,void 0,void 0,function*(){return ko.throwError("provider does not support network detection",v.errors.UNSUPPORTED_OPERATION,{operation:"provider.detectNetwork"})})}getNetwork(){return Ao(this,void 0,void 0,function*(){const e=yield this._ready(),t=yield this.detectNetwork();if(e.chainId!==t.chainId){if(this.anyNetwork)return this._network=t,this._lastBlockNumber=-2,this._fastBlockNumber=null,this._fastBlockNumberPromise=null,this._fastQueryDate=0,this._emitted.block=-2,this._maxInternalBlockNumber=-1024,this._internalBlockNumber=null,this.emit("network",t,e),yield Io(0),this._network;const r=ko.makeError("underlying network changed",v.errors.NETWORK_ERROR,{event:"changed",network:e,detectedNetwork:t});throw this.emit("error",r),r}return e})}get blockNumber(){return this._getInternalBlockNumber(100+this.pollingInterval/2).then(e=>{this._setFastBlockNumber(e)},e=>{}),null!=this._fastBlockNumber?this._fastBlockNumber:-1}get polling(){return null!=this._poller}set polling(e){e&&!this._poller?(this._poller=setInterval(()=>{this.poll()},this.pollingInterval),this._bootstrapPoll||(this._bootstrapPoll=setTimeout(()=>{this.poll(),this._bootstrapPoll=setTimeout(()=>{this._poller||this.poll(),this._bootstrapPoll=null},this.pollingInterval)},0))):!e&&this._poller&&(clearInterval(this._poller),this._poller=null)}get pollingInterval(){return this._pollingInterval}set pollingInterval(e){if("number"!=typeof e||e<=0||parseInt(String(e))!=e)throw new Error("invalid polling interval");this._pollingInterval=e,this._poller&&(clearInterval(this._poller),this._poller=setInterval(()=>{this.poll()},this._pollingInterval))}_getFastBlockNumber(){const e=So();return e-this._fastQueryDate>2*this._pollingInterval&&(this._fastQueryDate=e,this._fastBlockNumberPromise=this.getBlockNumber().then(e=>((null==this._fastBlockNumber||e>this._fastBlockNumber)&&(this._fastBlockNumber=e),this._fastBlockNumber))),this._fastBlockNumberPromise}_setFastBlockNumber(e){null!=this._fastBlockNumber&&e<this._fastBlockNumber||(this._fastQueryDate=So(),(null==this._fastBlockNumber||e>this._fastBlockNumber)&&(this._fastBlockNumber=e,this._fastBlockNumberPromise=Promise.resolve(e)))}waitForTransaction(e,t,r){return Ao(this,void 0,void 0,function*(){return this._waitForTransaction(e,null==t?1:t,r||0,null)})}_waitForTransaction(e,t,r,n){return Ao(this,void 0,void 0,function*(){const i=yield this.getTransactionReceipt(e);return(i?i.confirmations:0)>=t?i:new Promise((i,s)=>{const o=[];let a=!1;const c=function(){return!!a||(a=!0,o.forEach(e=>{e()}),!1)},u=e=>{e.confirmations<t||c()||i(e)};if(this.on(e,u),o.push(()=>{this.removeListener(e,u)}),n){let r=n.startBlock,i=null;const u=o=>Ao(this,void 0,void 0,function*(){a||(yield Io(1e3),this.getTransactionCount(n.from).then(l=>Ao(this,void 0,void 0,function*(){if(!a){if(l<=n.nonce)r=o;else{{const t=yield this.getTransaction(e);if(t&&null!=t.blockNumber)return}for(null==i&&(i=r-3,i<n.startBlock&&(i=n.startBlock));i<=o;){if(a)return;const r=yield this.getBlockWithTransactions(i);for(let i=0;i<r.transactions.length;i++){const o=r.transactions[i];if(o.hash===e)return;if(o.from===n.from&&o.nonce===n.nonce){if(a)return;const r=yield this.waitForTransaction(o.hash,t);if(c())return;let i="replaced";return o.data===n.data&&o.to===n.to&&o.value.eq(n.value)?i="repriced":"0x"===o.data&&o.from===o.to&&o.value.isZero()&&(i="cancelled"),void s(ko.makeError("transaction was replaced",v.errors.TRANSACTION_REPLACED,{cancelled:"replaced"===i||"cancelled"===i,reason:i,replacement:this._wrapTransaction(o),hash:e,receipt:r}))}}i++}}a||this.once("block",u)}}),e=>{a||this.once("block",u)}))});if(a)return;this.once("block",u),o.push(()=>{this.removeListener("block",u)})}if("number"==typeof r&&r>0){const e=setTimeout(()=>{c()||s(ko.makeError("timeout exceeded",v.errors.TIMEOUT,{timeout:r}))},r);e.unref&&e.unref(),o.push(()=>{clearTimeout(e)})}})})}getBlockNumber(){return Ao(this,void 0,void 0,function*(){return this._getInternalBlockNumber(0)})}getGasPrice(){return Ao(this,void 0,void 0,function*(){yield this.getNetwork();const e=yield this.perform("getGasPrice",{});try{return W.from(e)}catch(t){return ko.throwError("bad result from backend",v.errors.SERVER_ERROR,{method:"getGasPrice",result:e,error:t})}})}getBalance(e,t){return Ao(this,void 0,void 0,function*(){yield this.getNetwork();const r=yield re({address:this._getAddress(e),blockTag:this._getBlockTag(t)}),n=yield this.perform("getBalance",r);try{return W.from(n)}catch(e){return ko.throwError("bad result from backend",v.errors.SERVER_ERROR,{method:"getBalance",params:r,result:n,error:e})}})}getTransactionCount(e,t){return Ao(this,void 0,void 0,function*(){yield this.getNetwork();const r=yield re({address:this._getAddress(e),blockTag:this._getBlockTag(t)}),n=yield this.perform("getTransactionCount",r);try{return W.from(n).toNumber()}catch(e){return ko.throwError("bad result from backend",v.errors.SERVER_ERROR,{method:"getTransactionCount",params:r,result:n,error:e})}})}getCode(e,t){return Ao(this,void 0,void 0,function*(){yield this.getNetwork();const r=yield re({address:this._getAddress(e),blockTag:this._getBlockTag(t)}),n=yield this.perform("getCode",r);try{return O(n)}catch(e){return ko.throwError("bad result from backend",v.errors.SERVER_ERROR,{method:"getCode",params:r,result:n,error:e})}})}getStorageAt(e,t,r){return Ao(this,void 0,void 0,function*(){yield this.getNetwork();const n=yield re({address:this._getAddress(e),blockTag:this._getBlockTag(r),position:Promise.resolve(t).then(e=>D(e))}),i=yield this.perform("getStorageAt",n);try{return O(i)}catch(e){return ko.throwError("bad result from backend",v.errors.SERVER_ERROR,{method:"getStorageAt",params:n,result:i,error:e})}})}_wrapTransaction(e,t,r){if(null!=t&&32!==C(t))throw new Error("invalid response - sendTransaction");const n=e;return null!=t&&e.hash!==t&&ko.throwError("Transaction hash mismatch from Provider.sendTransaction.",v.errors.UNKNOWN_ERROR,{expectedHash:e.hash,returnedHash:t}),n.wait=(t,n)=>Ao(this,void 0,void 0,function*(){let i;null==t&&(t=1),null==n&&(n=0),0!==t&&null!=r&&(i={data:e.data,from:e.from,nonce:e.nonce,to:e.to,value:e.value,startBlock:r});const s=yield this._waitForTransaction(e.hash,t,n,i);return null==s&&0===t?null:(this._emitted["t:"+e.hash]=s.blockNumber,0===s.status&&ko.throwError("transaction failed",v.errors.CALL_EXCEPTION,{transactionHash:e.hash,transaction:e,receipt:s}),s)}),n}sendTransaction(e){return Ao(this,void 0,void 0,function*(){yield this.getNetwork();const t=yield Promise.resolve(e).then(e=>O(e)),r=this.formatter.transaction(e);null==r.confirmations&&(r.confirmations=0);const n=yield this._getInternalBlockNumber(100+2*this.pollingInterval);try{const e=yield this.perform("sendTransaction",{signedTransaction:t});return this._wrapTransaction(r,e,n)}catch(e){throw e.transaction=r,e.transactionHash=r.hash,e}})}_getTransactionRequest(e){return Ao(this,void 0,void 0,function*(){const t=yield e,r={};return["from","to"].forEach(e=>{null!=t[e]&&(r[e]=Promise.resolve(t[e]).then(e=>e?this._getAddress(e):null))}),["gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","value"].forEach(e=>{null!=t[e]&&(r[e]=Promise.resolve(t[e]).then(e=>e?W.from(e):null))}),["type"].forEach(e=>{null!=t[e]&&(r[e]=Promise.resolve(t[e]).then(e=>null!=e?e:null))}),t.accessList&&(r.accessList=this.formatter.accessList(t.accessList)),["data"].forEach(e=>{null!=t[e]&&(r[e]=Promise.resolve(t[e]).then(e=>e?O(e):null))}),this.formatter.transactionRequest(yield re(r))})}_getFilter(e){return Ao(this,void 0,void 0,function*(){e=yield e;const t={};return null!=e.address&&(t.address=this._getAddress(e.address)),["blockHash","topics"].forEach(r=>{null!=e[r]&&(t[r]=e[r])}),["fromBlock","toBlock"].forEach(r=>{null!=e[r]&&(t[r]=this._getBlockTag(e[r]))}),this.formatter.filter(yield re(t))})}_call(e,t,r){return Ao(this,void 0,void 0,function*(){r>=10&&ko.throwError("CCIP read exceeded maximum redirections",v.errors.SERVER_ERROR,{redirects:r,transaction:e});const n=e.to,i=yield this.perform("call",{transaction:e,blockTag:t});if(r>=0&&"latest"===t&&null!=n&&"0x556f1830"===i.substring(0,10)&&C(i)%32==4)try{const s=P(i,4),o=P(s,0,32);W.from(o).eq(n)||ko.throwError("CCIP Read sender did not match",v.errors.CALL_EXCEPTION,{name:"OffchainLookup",signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",transaction:e,data:i});const a=[],c=W.from(P(s,32,64)).toNumber(),u=W.from(P(s,c,c+32)).toNumber(),l=P(s,c+32);for(let t=0;t<u;t++){const r=Bo(l,32*t);null==r&&ko.throwError("CCIP Read contained corrupt URL string",v.errors.CALL_EXCEPTION,{name:"OffchainLookup",signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",transaction:e,data:i}),a.push(r)}const h=Lo(s,64);W.from(P(s,100,128)).isZero()||ko.throwError("CCIP Read callback selector included junk",v.errors.CALL_EXCEPTION,{name:"OffchainLookup",signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",transaction:e,data:i});const d=P(s,96,100),f=Lo(s,128),p=yield this.ccipReadFetch(e,h,a);null==p&&ko.throwError("CCIP Read disabled or provided no URLs",v.errors.CALL_EXCEPTION,{name:"OffchainLookup",signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",transaction:e,data:i});const m={to:n,data:M([d,Ho([p,f])])};return this._call(m,t,r+1)}catch(e){if(e.code===v.errors.SERVER_ERROR)throw e}try{return O(i)}catch(r){return ko.throwError("bad result from backend",v.errors.SERVER_ERROR,{method:"call",params:{transaction:e,blockTag:t},result:i,error:r})}})}call(e,t){return Ao(this,void 0,void 0,function*(){yield this.getNetwork();const r=yield re({transaction:this._getTransactionRequest(e),blockTag:this._getBlockTag(t),ccipReadEnabled:Promise.resolve(e.ccipReadEnabled)});return this._call(r.transaction,r.blockTag,r.ccipReadEnabled?0:-1)})}estimateGas(e){return Ao(this,void 0,void 0,function*(){yield this.getNetwork();const t=yield re({transaction:this._getTransactionRequest(e)}),r=yield this.perform("estimateGas",t);try{return W.from(r)}catch(e){return ko.throwError("bad result from backend",v.errors.SERVER_ERROR,{method:"estimateGas",params:t,result:r,error:e})}})}_getAddress(e){return Ao(this,void 0,void 0,function*(){"string"!=typeof(e=yield e)&&ko.throwArgumentError("invalid address or ENS name","name",e);const t=yield this.resolveName(e);return null==t&&ko.throwError("ENS name not configured",v.errors.UNSUPPORTED_OPERATION,{operation:`resolveName(${JSON.stringify(e)})`}),t})}_getBlock(e,t){return Ao(this,void 0,void 0,function*(){yield this.getNetwork(),e=yield e;let r=-128;const n={includeTransactions:!!t};if(N(e,32))n.blockHash=e;else try{n.blockTag=yield this._getBlockTag(e),N(n.blockTag)&&(r=parseInt(n.blockTag.substring(2),16))}catch(t){ko.throwArgumentError("invalid block hash or block tag","blockHashOrBlockTag",e)}return ho(()=>Ao(this,void 0,void 0,function*(){const e=yield this.perform("getBlock",n);if(null==e)return null!=n.blockHash&&null==this._emitted["b:"+n.blockHash]||null!=n.blockTag&&r>this._emitted.block?null:void 0;if(t){let t=null;for(let r=0;r<e.transactions.length;r++){const n=e.transactions[r];if(null==n.blockNumber)n.confirmations=0;else if(null==n.confirmations){null==t&&(t=yield this._getInternalBlockNumber(100+2*this.pollingInterval));let e=t-n.blockNumber+1;e<=0&&(e=1),n.confirmations=e}}const r=this.formatter.blockWithTransactions(e);return r.transactions=r.transactions.map(e=>this._wrapTransaction(e)),r}return this.formatter.block(e)}),{oncePoll:this})})}getBlock(e){return this._getBlock(e,!1)}getBlockWithTransactions(e){return this._getBlock(e,!0)}getTransaction(e){return Ao(this,void 0,void 0,function*(){yield this.getNetwork(),e=yield e;const t={transactionHash:this.formatter.hash(e,!0)};return ho(()=>Ao(this,void 0,void 0,function*(){const r=yield this.perform("getTransaction",t);if(null==r)return null==this._emitted["t:"+e]?null:void 0;const n=this.formatter.transactionResponse(r);if(null==n.blockNumber)n.confirmations=0;else if(null==n.confirmations){let e=(yield this._getInternalBlockNumber(100+2*this.pollingInterval))-n.blockNumber+1;e<=0&&(e=1),n.confirmations=e}return this._wrapTransaction(n)}),{oncePoll:this})})}getTransactionReceipt(e){return Ao(this,void 0,void 0,function*(){yield this.getNetwork(),e=yield e;const t={transactionHash:this.formatter.hash(e,!0)};return ho(()=>Ao(this,void 0,void 0,function*(){const r=yield this.perform("getTransactionReceipt",t);if(null==r)return null==this._emitted["t:"+e]?null:void 0;if(null==r.blockHash)return;const n=this.formatter.receipt(r);if(null==n.blockNumber)n.confirmations=0;else if(null==n.confirmations){let e=(yield this._getInternalBlockNumber(100+2*this.pollingInterval))-n.blockNumber+1;e<=0&&(e=1),n.confirmations=e}return n}),{oncePoll:this})})}getLogs(e){return Ao(this,void 0,void 0,function*(){yield this.getNetwork();const t=yield re({filter:this._getFilter(e)}),r=yield this.perform("getLogs",t);return r.forEach(e=>{null==e.removed&&(e.removed=!1)}),yo.arrayOf(this.formatter.filterLog.bind(this.formatter))(r)})}getEtherPrice(){return Ao(this,void 0,void 0,function*(){return yield this.getNetwork(),this.perform("getEtherPrice",{})})}_getBlockTag(e){return Ao(this,void 0,void 0,function*(){if("number"==typeof(e=yield e)&&e<0){e%1&&ko.throwArgumentError("invalid BlockTag","blockTag",e);let t=yield this._getInternalBlockNumber(100+2*this.pollingInterval);return t+=e,t<0&&(t=0),this.formatter.blockTag(t)}return this.formatter.blockTag(e)})}getResolver(e){return Ao(this,void 0,void 0,function*(){let t=e;for(;;){if(""===t||"."===t)return null;if("eth"!==e&&"eth"===t)return null;const r=yield this._getResolver(t,"getResolver");if(null!=r){const n=new Ko(this,r,e);return t===e||(yield n.supportsWildcard())?n:null}t=t.split(".").slice(1).join(".")}})}_getResolver(e,t){return Ao(this,void 0,void 0,function*(){null==t&&(t="ENS");const r=yield this.getNetwork();r.ensAddress||ko.throwError("network does not support ENS",v.errors.UNSUPPORTED_OPERATION,{operation:t,network:r.name});try{const t=yield this.call({to:r.ensAddress,data:"0x0178b8bf"+no(e).substring(2)});return this.formatter.callAddress(t)}catch(e){}return null})}resolveName(e){return Ao(this,void 0,void 0,function*(){e=yield e;try{return Promise.resolve(this.formatter.address(e))}catch(t){if(N(e))throw t}"string"!=typeof e&&ko.throwArgumentError("invalid ENS name","name",e);const t=yield this.getResolver(e);return t?yield t.getAddress():null})}lookupAddress(e){return Ao(this,void 0,void 0,function*(){e=yield e;const t=(e=this.formatter.address(e)).substring(2).toLowerCase()+".addr.reverse",r=yield this._getResolver(t,"lookupAddress");if(null==r)return null;const n=Bo(yield this.call({to:r,data:"0x691f3431"+no(t).substring(2)}),0);return(yield this.resolveName(n))!=e?null:n})}getAvatar(e){return Ao(this,void 0,void 0,function*(){let t=null;if(N(e)){const r=this.formatter.address(e).substring(2).toLowerCase()+".addr.reverse",n=yield this._getResolver(r,"getAvatar");if(!n)return null;t=new Ko(this,n,r);try{const e=yield t.getAvatar();if(e)return e.url}catch(e){if(e.code!==v.errors.CALL_EXCEPTION)throw e}try{const e=Bo(yield this.call({to:n,data:"0x691f3431"+no(r).substring(2)}),0);t=yield this.getResolver(e)}catch(e){if(e.code!==v.errors.CALL_EXCEPTION)throw e;return null}}else if(t=yield this.getResolver(e),!t)return null;const r=yield t.getAvatar();return null==r?null:r.url})}perform(e,t){return ko.throwError(e+" not implemented",v.errors.NOT_IMPLEMENTED,{operation:e})}_startEvent(e){this.polling=this._events.filter(e=>e.pollable()).length>0}_stopEvent(e){this.polling=this._events.filter(e=>e.pollable()).length>0}_addEventListener(e,t,r){const n=new Ro(To(e),t,r);return this._events.push(n),this._startEvent(n),this}on(e,t){return this._addEventListener(e,t,!1)}once(e,t){return this._addEventListener(e,t,!0)}emit(e,...t){let r=!1,n=[],i=To(e);return this._events=this._events.filter(e=>e.tag!==i||(setTimeout(()=>{e.listener.apply(this,t)},0),r=!0,!e.once||(n.push(e),!1))),n.forEach(e=>{this._stopEvent(e)}),r}listenerCount(e){if(!e)return this._events.length;let t=To(e);return this._events.filter(e=>e.tag===t).length}listeners(e){if(null==e)return this._events.map(e=>e.listener);let t=To(e);return this._events.filter(e=>e.tag===t).map(e=>e.listener)}off(e,t){if(null==t)return this.removeAllListeners(e);const r=[];let n=!1,i=To(e);return this._events=this._events.filter(e=>e.tag!==i||e.listener!=t||!!n||(n=!0,r.push(e),!1)),r.forEach(e=>{this._stopEvent(e)}),this}removeAllListeners(e){let t=[];if(null==e)t=this._events,this._events=[];else{const r=To(e);this._events=this._events.filter(e=>e.tag!==r||(t.push(e),!1))}return t.forEach(e=>{this._stopEvent(e)}),this}}var Vo=function(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};const Go=new v(mo),Wo=["call","estimateGas"];function Jo(e,t){if(null==e)return null;if("string"==typeof e.message&&e.message.match("reverted")){const r=N(e.data)?e.data:null;if(!t||r)return{message:e.message,data:r}}if("object"==typeof e){for(const r in e){const n=Jo(e[r],t);if(n)return n}return null}if("string"==typeof e)try{return Jo(JSON.parse(e),t)}catch(e){}return null}function Zo(e,t,r){const n=r.transaction||r.signedTransaction;if("call"===e){const e=Jo(t,!0);if(e)return e.data;Go.throwError("missing revert data in call exception; Transaction reverted without a reason string",v.errors.CALL_EXCEPTION,{data:"0x",transaction:n,error:t})}if("estimateGas"===e){let r=Jo(t.body,!1);null==r&&(r=Jo(t,!1)),r&&Go.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",v.errors.UNPREDICTABLE_GAS_LIMIT,{reason:r.message,method:e,transaction:n,error:t})}let i=t.message;throw t.code===v.errors.SERVER_ERROR&&t.error&&"string"==typeof t.error.message?i=t.error.message:"string"==typeof t.body?i=t.body:"string"==typeof t.responseText&&(i=t.responseText),i=(i||"").toLowerCase(),i.match(/insufficient funds|base fee exceeds gas limit|InsufficientFunds/i)&&Go.throwError("insufficient funds for intrinsic transaction cost",v.errors.INSUFFICIENT_FUNDS,{error:t,method:e,transaction:n}),i.match(/nonce (is )?too low/i)&&Go.throwError("nonce has already been used",v.errors.NONCE_EXPIRED,{error:t,method:e,transaction:n}),i.match(/replacement transaction underpriced|transaction gas price.*too low/i)&&Go.throwError("replacement fee too low",v.errors.REPLACEMENT_UNDERPRICED,{error:t,method:e,transaction:n}),i.match(/only replay-protected/i)&&Go.throwError("legacy pre-eip-155 transactions not supported",v.errors.UNSUPPORTED_OPERATION,{error:t,method:e,transaction:n}),Wo.indexOf(e)>=0&&i.match(/gas required exceeds allowance|always failing transaction|execution reverted|revert/)&&Go.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",v.errors.UNPREDICTABLE_GAS_LIMIT,{error:t,method:e,transaction:n}),t}function Yo(e){return new Promise(function(t){setTimeout(t,e)})}function Qo(e){if(e.error){const t=new Error(e.error.message);throw t.code=e.error.code,t.data=e.error.data,t}return e.result}function Xo(e){return e?e.toLowerCase():e}const ea={};class ta extends cr{constructor(e,t,r){if(super(),e!==ea)throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");ee(this,"provider",t),null==r&&(r=0),"string"==typeof r?(ee(this,"_address",this.provider.formatter.address(r)),ee(this,"_index",null)):"number"==typeof r?(ee(this,"_index",r),ee(this,"_address",null)):Go.throwArgumentError("invalid address or index","addressOrIndex",r)}connect(e){return Go.throwError("cannot alter JSON-RPC Signer connection",v.errors.UNSUPPORTED_OPERATION,{operation:"connect"})}connectUnchecked(){return new ra(ea,this.provider,this._address||this._index)}getAddress(){return this._address?Promise.resolve(this._address):this.provider.send("eth_accounts",[]).then(e=>(e.length<=this._index&&Go.throwError("unknown account #"+this._index,v.errors.UNSUPPORTED_OPERATION,{operation:"getAddress"}),this.provider.formatter.address(e[this._index])))}sendUncheckedTransaction(e){e=ie(e);const t=this.getAddress().then(e=>(e&&(e=e.toLowerCase()),e));if(null==e.gasLimit){const r=ie(e);r.from=t,e.gasLimit=this.provider.estimateGas(r)}return null!=e.to&&(e.to=Promise.resolve(e.to).then(e=>Vo(this,void 0,void 0,function*(){if(null==e)return null;const t=yield this.provider.resolveName(e);return null==t&&Go.throwArgumentError("provided ENS name resolves to null","tx.to",e),t}))),re({tx:re(e),sender:t}).then(({tx:t,sender:r})=>{null!=t.from?t.from.toLowerCase()!==r&&Go.throwArgumentError("from address mismatch","transaction",e):t.from=r;const n=this.provider.constructor.hexlifyTransaction(t,{from:!0});return this.provider.send("eth_sendTransaction",[n]).then(e=>e,e=>("string"==typeof e.message&&e.message.match(/user denied/i)&&Go.throwError("user rejected transaction",v.errors.ACTION_REJECTED,{action:"sendTransaction",transaction:t}),Zo("sendTransaction",e,n)))})}signTransaction(e){return Go.throwError("signing transactions is unsupported",v.errors.UNSUPPORTED_OPERATION,{operation:"signTransaction"})}sendTransaction(e){return Vo(this,void 0,void 0,function*(){const t=yield this.provider._getInternalBlockNumber(100+2*this.provider.pollingInterval),r=yield this.sendUncheckedTransaction(e);try{return yield ho(()=>Vo(this,void 0,void 0,function*(){const e=yield this.provider.getTransaction(r);if(null!==e)return this.provider._wrapTransaction(e,r,t)}),{oncePoll:this.provider})}catch(e){throw e.transactionHash=r,e}})}signMessage(e){return Vo(this,void 0,void 0,function*(){const t="string"==typeof e?je(e):e,r=yield this.getAddress();try{return yield this.provider.send("personal_sign",[O(t),r.toLowerCase()])}catch(t){throw"string"==typeof t.message&&t.message.match(/user denied/i)&&Go.throwError("user rejected signing",v.errors.ACTION_REJECTED,{action:"signMessage",from:r,messageData:e}),t}})}_legacySignMessage(e){return Vo(this,void 0,void 0,function*(){const t="string"==typeof e?je(e):e,r=yield this.getAddress();try{return yield this.provider.send("eth_sign",[r.toLowerCase(),O(t)])}catch(t){throw"string"==typeof t.message&&t.message.match(/user denied/i)&&Go.throwError("user rejected signing",v.errors.ACTION_REJECTED,{action:"_legacySignMessage",from:r,messageData:e}),t}})}_signTypedData(e,t,r){return Vo(this,void 0,void 0,function*(){const n=yield li.resolveNames(e,t,r,e=>this.provider.resolveName(e)),i=yield this.getAddress();try{return yield this.provider.send("eth_signTypedData_v4",[i.toLowerCase(),JSON.stringify(li.getPayload(n.domain,t,n.value))])}catch(e){throw"string"==typeof e.message&&e.message.match(/user denied/i)&&Go.throwError("user rejected signing",v.errors.ACTION_REJECTED,{action:"_signTypedData",from:i,messageData:{domain:n.domain,types:t,value:n.value}}),e}})}unlock(e){return Vo(this,void 0,void 0,function*(){const t=this.provider,r=yield this.getAddress();return t.send("personal_unlockAccount",[r.toLowerCase(),e,null])})}}class ra extends ta{sendTransaction(e){return this.sendUncheckedTransaction(e).then(e=>({hash:e,nonce:null,gasLimit:null,gasPrice:null,data:null,value:null,chainId:null,confirmations:0,from:null,wait:t=>this.provider.waitForTransaction(e,t)}))}}const na={chainId:!0,data:!0,gasLimit:!0,gasPrice:!0,nonce:!0,to:!0,value:!0,type:!0,accessList:!0,maxFeePerGas:!0,maxPriorityFeePerGas:!0};class ia extends zo{constructor(e,t){let r=t;null==r&&(r=new Promise((e,t)=>{setTimeout(()=>{this.detectNetwork().then(t=>{e(t)},e=>{t(e)})},0)})),super(r),e||(e=te(this.constructor,"defaultUrl")()),ee(this,"connection","string"==typeof e?Object.freeze({url:e}):Object.freeze(ie(e))),this._nextId=42}get _cache(){return null==this._eventLoopCache&&(this._eventLoopCache={}),this._eventLoopCache}static defaultUrl(){return"http://localhost:8545"}detectNetwork(){return this._cache.detectNetwork||(this._cache.detectNetwork=this._uncachedDetectNetwork(),setTimeout(()=>{this._cache.detectNetwork=null},0)),this._cache.detectNetwork}_uncachedDetectNetwork(){return Vo(this,void 0,void 0,function*(){yield Yo(0);let e=null;try{e=yield this.send("eth_chainId",[])}catch(t){try{e=yield this.send("net_version",[])}catch(e){}}if(null!=e){const t=te(this.constructor,"getNetwork");try{return t(W.from(e).toNumber())}catch(t){return Go.throwError("could not detect network",v.errors.NETWORK_ERROR,{chainId:e,event:"invalidNetwork",serverError:t})}}return Go.throwError("could not detect network",v.errors.NETWORK_ERROR,{event:"noNetwork"})})}getSigner(e){return new ta(ea,this,e)}getUncheckedSigner(e){return this.getSigner(e).connectUnchecked()}listAccounts(){return this.send("eth_accounts",[]).then(e=>e.map(e=>this.formatter.address(e)))}send(e,t){const r={method:e,params:t,id:this._nextId++,jsonrpc:"2.0"};this.emit("debug",{action:"request",request:ce(r),provider:this});const n=["eth_chainId","eth_blockNumber"].indexOf(e)>=0;if(n&&this._cache[e])return this._cache[e];const i=lo(this.connection,JSON.stringify(r),Qo).then(e=>(this.emit("debug",{action:"response",request:r,response:e,provider:this}),e),e=>{throw this.emit("debug",{action:"response",error:e,request:r,provider:this}),e});return n&&(this._cache[e]=i,setTimeout(()=>{this._cache[e]=null},0)),i}prepareRequest(e,t){switch(e){case"getBlockNumber":return["eth_blockNumber",[]];case"getGasPrice":return["eth_gasPrice",[]];case"getBalance":return["eth_getBalance",[Xo(t.address),t.blockTag]];case"getTransactionCount":return["eth_getTransactionCount",[Xo(t.address),t.blockTag]];case"getCode":return["eth_getCode",[Xo(t.address),t.blockTag]];case"getStorageAt":return["eth_getStorageAt",[Xo(t.address),L(t.position,32),t.blockTag]];case"sendTransaction":return["eth_sendRawTransaction",[t.signedTransaction]];case"getBlock":return t.blockTag?["eth_getBlockByNumber",[t.blockTag,!!t.includeTransactions]]:t.blockHash?["eth_getBlockByHash",[t.blockHash,!!t.includeTransactions]]:null;case"getTransaction":return["eth_getTransactionByHash",[t.transactionHash]];case"getTransactionReceipt":return["eth_getTransactionReceipt",[t.transactionHash]];case"call":return["eth_call",[te(this.constructor,"hexlifyTransaction")(t.transaction,{from:!0}),t.blockTag]];case"estimateGas":return["eth_estimateGas",[te(this.constructor,"hexlifyTransaction")(t.transaction,{from:!0})]];case"getLogs":return t.filter&&null!=t.filter.address&&(t.filter.address=Xo(t.filter.address)),["eth_getLogs",[t.filter]]}return null}perform(e,t){return Vo(this,void 0,void 0,function*(){if("call"===e||"estimateGas"===e){const e=t.transaction;if(e&&null!=e.type&&W.from(e.type).isZero()&&null==e.maxFeePerGas&&null==e.maxPriorityFeePerGas){const r=yield this.getFeeData();null==r.maxFeePerGas&&null==r.maxPriorityFeePerGas&&((t=ie(t)).transaction=ie(e),delete t.transaction.type)}}const r=this.prepareRequest(e,t);null==r&&Go.throwError(e+" not implemented",v.errors.NOT_IMPLEMENTED,{operation:e});try{return yield this.send(r[0],r[1])}catch(r){return Zo(e,r,t)}})}_startEvent(e){"pending"===e.tag&&this._startPending(),super._startEvent(e)}_startPending(){if(null!=this._pendingFilter)return;const e=this,t=this.send("eth_newPendingTransactionFilter",[]);this._pendingFilter=t,t.then(function(r){return function n(){e.send("eth_getFilterChanges",[r]).then(function(r){if(e._pendingFilter!=t)return null;let n=Promise.resolve();return r.forEach(function(t){e._emitted["t:"+t.toLowerCase()]="pending",n=n.then(function(){return e.getTransaction(t).then(function(t){return e.emit("pending",t),null})})}),n.then(function(){return Yo(1e3)})}).then(function(){if(e._pendingFilter==t)return setTimeout(function(){n()},0),null;e.send("eth_uninstallFilter",[r])}).catch(e=>{})}(),r}).catch(e=>{})}_stopEvent(e){"pending"===e.tag&&0===this.listenerCount("pending")&&(this._pendingFilter=null),super._stopEvent(e)}static hexlifyTransaction(e,t){const r=ie(na);if(t)for(const e in t)t[e]&&(r[e]=!0);ne(e,r);const n={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach(function(t){if(null==e[t])return;const r=D(W.from(e[t]));"gasLimit"===t&&(t="gas"),n[t]=r}),["from","to","data"].forEach(function(t){null!=e[t]&&(n[t]=O(e[t]))}),e.accessList&&(n.accessList=hn(e.accessList)),n}}let sa=null;try{if(sa=WebSocket,null==sa)throw new Error("inject please")}catch(e){const t=new v(mo);sa=function(){t.throwError("WebSockets not supported in this environment",v.errors.UNSUPPORTED_OPERATION,{operation:"new WebSocket()"})}}var oa=function(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};const aa=new v(mo);let ca=1;class ua extends ia{constructor(e,t){"any"===t&&aa.throwError("WebSocketProvider does not support 'any' network yet",v.errors.UNSUPPORTED_OPERATION,{operation:"network:any"}),super("string"==typeof e?e:"_websocket",t),this._pollingInterval=-1,this._wsReady=!1,ee(this,"_websocket","string"==typeof e?new sa(this.connection.url):e),ee(this,"_requests",{}),ee(this,"_subs",{}),ee(this,"_subIds",{}),ee(this,"_detectNetwork",super.detectNetwork()),this.websocket.onopen=()=>{this._wsReady=!0,Object.keys(this._requests).forEach(e=>{this.websocket.send(this._requests[e].payload)})},this.websocket.onmessage=e=>{const t=e.data,r=JSON.parse(t);if(null!=r.id){const e=String(r.id),n=this._requests[e];if(delete this._requests[e],void 0!==r.result)n.callback(null,r.result),this.emit("debug",{action:"response",request:JSON.parse(n.payload),response:r.result,provider:this});else{let e=null;r.error?(e=new Error(r.error.message||"unknown error"),ee(e,"code",r.error.code||null),ee(e,"response",t)):e=new Error("unknown error"),n.callback(e,void 0),this.emit("debug",{action:"response",error:e,request:JSON.parse(n.payload),provider:this})}}else if("eth_subscription"===r.method){const e=this._subs[r.params.subscription];e&&e.processFunc(r.params.result)}else console.warn("this should not happen")};const r=setInterval(()=>{this.emit("poll")},1e3);r.unref&&r.unref()}get websocket(){return this._websocket}detectNetwork(){return this._detectNetwork}get pollingInterval(){return 0}resetEventsBlock(e){aa.throwError("cannot reset events block on WebSocketProvider",v.errors.UNSUPPORTED_OPERATION,{operation:"resetEventBlock"})}set pollingInterval(e){aa.throwError("cannot set polling interval on WebSocketProvider",v.errors.UNSUPPORTED_OPERATION,{operation:"setPollingInterval"})}poll(){return oa(this,void 0,void 0,function*(){return null})}set polling(e){e&&aa.throwError("cannot set polling on WebSocketProvider",v.errors.UNSUPPORTED_OPERATION,{operation:"setPolling"})}send(e,t){const r=ca++;return new Promise((n,i)=>{const s=JSON.stringify({method:e,params:t,id:r,jsonrpc:"2.0"});this.emit("debug",{action:"request",request:JSON.parse(s),provider:this}),this._requests[String(r)]={callback:function(e,t){return e?i(e):n(t)},payload:s},this._wsReady&&this.websocket.send(s)})}static defaultUrl(){return"ws://localhost:8546"}_subscribe(e,t,r){return oa(this,void 0,void 0,function*(){let n=this._subIds[e];null==n&&(n=Promise.all(t).then(e=>this.send("eth_subscribe",e)),this._subIds[e]=n);const i=yield n;this._subs[i]={tag:e,processFunc:r}})}_startEvent(e){switch(e.type){case"block":this._subscribe("block",["newHeads"],e=>{const t=W.from(e.number).toNumber();this._emitted.block=t,this.emit("block",t)});break;case"pending":this._subscribe("pending",["newPendingTransactions"],e=>{this.emit("pending",e)});break;case"filter":this._subscribe(e.tag,["logs",this._getFilter(e.filter)],t=>{null==t.removed&&(t.removed=!1),this.emit(e.filter,this.formatter.filterLog(t))});break;case"tx":{const t=e=>{const t=e.hash;this.getTransactionReceipt(t).then(e=>{e&&this.emit(t,e)})};t(e),this._subscribe("tx",["newHeads"],e=>{this._events.filter(e=>"tx"===e.type).forEach(t)});break}case"debug":case"poll":case"willPoll":case"didPoll":case"error":break;default:console.log("unhandled:",e)}}_stopEvent(e){let t=e.tag;if("tx"===e.type){if(this._events.filter(e=>"tx"===e.type).length)return;t="tx"}else if(this.listenerCount(e.event))return;const r=this._subIds[t];r&&(delete this._subIds[t],r.then(e=>{this._subs[e]&&(delete this._subs[e],this.send("eth_unsubscribe",[e]))}))}destroy(){return oa(this,void 0,void 0,function*(){this.websocket.readyState===sa.CONNECTING&&(yield new Promise(e=>{this.websocket.onopen=function(){e(!0)},this.websocket.onerror=function(){e(!1)}})),this.websocket.close(1e3)})}}const la=new v(mo);class ha extends ia{detectNetwork(){const e=Object.create(null,{detectNetwork:{get:()=>super.detectNetwork}});return t=this,r=void 0,i=function*(){let t=this.network;return null==t&&(t=yield e.detectNetwork.call(this),t||la.throwError("no network detected",v.errors.UNKNOWN_ERROR,{}),null==this._network&&(ee(this,"_network",t),this.emit("network",t,null))),t},new((n=void 0)||(n=Promise))(function(e,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(e){e(r)})).then(o,a)}c((i=i.apply(t,r||[])).next())});var t,r,n,i}}class da extends ha{constructor(e,t){la.checkAbstract(new.target,da),e=te(new.target,"getNetwork")(e),t=te(new.target,"getApiKey")(t),super(te(new.target,"getUrl")(e,t),e),"string"==typeof t?ee(this,"apiKey",t):null!=t&&Object.keys(t).forEach(e=>{ee(this,e,t[e])})}_startPending(){la.warn("WARNING: API provider does not support pending filters")}isCommunityResource(){return!1}getSigner(e){return la.throwError("API provider does not support signing",v.errors.UNSUPPORTED_OPERATION,{operation:"getSigner"})}listAccounts(){return Promise.resolve([])}static getApiKey(e){return e}static getUrl(e,t){return la.throwError("not implemented; sub-classes must override getUrl",v.errors.NOT_IMPLEMENTED,{operation:"getUrl"})}}const fa=new v(mo),pa="_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";class ma extends ua{constructor(e,t){const r=new ga(e,t);super(r.connection.url.replace(/^http/i,"ws").replace(".alchemyapi.",".ws.alchemyapi."),r.network),ee(this,"apiKey",r.apiKey)}isCommunityResource(){return this.apiKey===pa}}class ga extends da{static getWebSocketProvider(e,t){return new ma(e,t)}static getApiKey(e){return null==e?pa:(e&&"string"!=typeof e&&fa.throwArgumentError("invalid apiKey","apiKey",e),e)}static getUrl(e,t){let r=null;switch(e.name){case"homestead":r="eth-mainnet.alchemyapi.io/v2/";break;case"goerli":r="eth-goerli.g.alchemy.com/v2/";break;case"sepolia":r="eth-sepolia.g.alchemy.com/v2/";break;case"matic":r="polygon-mainnet.g.alchemy.com/v2/";break;case"maticmum":r="polygon-mumbai.g.alchemy.com/v2/";break;case"arbitrum":r="arb-mainnet.g.alchemy.com/v2/";break;case"arbitrum-goerli":r="arb-goerli.g.alchemy.com/v2/";break;case"arbitrum-sepolia":r="arb-sepolia.g.alchemy.com/v2/";break;case"optimism":r="opt-mainnet.g.alchemy.com/v2/";break;case"optimism-goerli":r="opt-goerli.g.alchemy.com/v2/";break;case"optimism-sepolia":r="opt-sepolia.g.alchemy.com/v2/";break;default:fa.throwArgumentError("unsupported network","network",arguments[0])}return{allowGzip:!0,url:"https://"+r+t,throttleCallback:(e,r)=>(t===pa&&Eo(),Promise.resolve(!0))}}isCommunityResource(){return this.apiKey===pa}}const ya=new v(mo),va="9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972";function ba(e){switch(e){case"homestead":return"rpc.ankr.com/eth/";case"ropsten":return"rpc.ankr.com/eth_ropsten/";case"rinkeby":return"rpc.ankr.com/eth_rinkeby/";case"goerli":return"rpc.ankr.com/eth_goerli/";case"sepolia":return"rpc.ankr.com/eth_sepolia/";case"matic":return"rpc.ankr.com/polygon/";case"maticmum":return"rpc.ankr.com/polygon_mumbai/";case"optimism":return"rpc.ankr.com/optimism/";case"optimism-goerli":return"rpc.ankr.com/optimism_testnet/";case"optimism-sepolia":return"rpc.ankr.com/optimism_sepolia/";case"arbitrum":return"rpc.ankr.com/arbitrum/"}return ya.throwArgumentError("unsupported network","name",e)}class wa extends da{isCommunityResource(){return this.apiKey===va}static getApiKey(e){return null==e?va:e}static getUrl(e,t){null==t&&(t=va);const r={allowGzip:!0,url:"https://"+ba(e.name)+t,throttleCallback:(e,r)=>(t.apiKey===va&&Eo(),Promise.resolve(!0))};return null!=t.projectSecret&&(r.user="",r.password=t.projectSecret),r}}const Ea=new v(mo);class Aa extends da{static getApiKey(e){return null!=e&&Ea.throwArgumentError("apiKey not supported for cloudflare","apiKey",e),null}static getUrl(e,t){let r=null;return"homestead"===e.name?r="https://cloudflare-eth.com/":Ea.throwArgumentError("unsupported network","network",arguments[0]),r}perform(e,t){const r=Object.create(null,{perform:{get:()=>super.perform}});return n=this,i=void 0,o=function*(){return"getBlockNumber"===e?(yield r.perform.call(this,"getBlock",{blockTag:"latest"})).number:r.perform.call(this,e,t)},new((s=void 0)||(s=Promise))(function(e,t){function r(e){try{c(o.next(e))}catch(e){t(e)}}function a(e){try{c(o.throw(e))}catch(e){t(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof s?n:new s(function(e){e(n)})).then(r,a)}c((o=o.apply(n,i||[])).next())});var n,i,s,o}}var ka=function(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};const xa=new v(mo);function _a(e){const t={};for(let r in e){if(null==e[r])continue;let n=e[r];"type"===r&&0===n||(n={type:!0,gasLimit:!0,gasPrice:!0,maxFeePerGs:!0,maxPriorityFeePerGas:!0,nonce:!0,value:!0}[r]?D(O(n)):"accessList"===r?"["+hn(n).map(e=>`{address:"${e.address}",storageKeys:["${e.storageKeys.join('","')}"]}`).join(",")+"]":O(n),t[r]=n)}return t}function Ta(e){if(0==e.status&&("No records found"===e.message||"No transactions found"===e.message))return e.result;if(1!=e.status||"string"!=typeof e.message||!e.message.match(/^OK/)){const t=new Error("invalid response");throw t.result=JSON.stringify(e),(e.result||"").toLowerCase().indexOf("rate limit")>=0&&(t.throttleRetry=!0),t}return e.result}function Sa(e){if(e&&0==e.status&&"NOTOK"==e.message&&(e.result||"").toLowerCase().indexOf("rate limit")>=0){const t=new Error("throttled response");throw t.result=JSON.stringify(e),t.throttleRetry=!0,t}if("2.0"!=e.jsonrpc){const t=new Error("invalid response");throw t.result=JSON.stringify(e),t}if(e.error){const t=new Error(e.error.message||"unknown error");throw e.error.code&&(t.code=e.error.code),e.error.data&&(t.data=e.error.data),t}return e.result}function Ia(e){if("pending"===e)throw new Error("pending not supported");return"latest"===e?e:parseInt(e.substring(2),16)}function Na(e,t,r){if("call"===e&&t.code===v.errors.SERVER_ERROR){const e=t.error;if(e&&(e.message.match(/reverted/i)||e.message.match(/VM execution error/i))){let r=e.data;if(r&&(r="0x"+r.replace(/^.*0x/i,"")),N(r))return r;xa.throwError("missing revert data in call exception",v.errors.CALL_EXCEPTION,{error:t,data:"0x"})}}let n=t.message;throw t.code===v.errors.SERVER_ERROR&&(t.error&&"string"==typeof t.error.message?n=t.error.message:"string"==typeof t.body?n=t.body:"string"==typeof t.responseText&&(n=t.responseText)),n=(n||"").toLowerCase(),n.match(/insufficient funds/)&&xa.throwError("insufficient funds for intrinsic transaction cost",v.errors.INSUFFICIENT_FUNDS,{error:t,method:e,transaction:r}),n.match(/same hash was already imported|transaction nonce is too low|nonce too low/)&&xa.throwError("nonce has already been used",v.errors.NONCE_EXPIRED,{error:t,method:e,transaction:r}),n.match(/another transaction with same nonce/)&&xa.throwError("replacement fee too low",v.errors.REPLACEMENT_UNDERPRICED,{error:t,method:e,transaction:r}),n.match(/execution failed due to an exception|execution reverted/)&&xa.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",v.errors.UNPREDICTABLE_GAS_LIMIT,{error:t,method:e,transaction:r}),t}class Ra extends zo{constructor(e,t){super(e),ee(this,"baseUrl",this.getBaseUrl()),ee(this,"apiKey",t||null)}getBaseUrl(){switch(this.network?this.network.name:"invalid"){case"homestead":return"https://api.etherscan.io";case"goerli":return"https://api-goerli.etherscan.io";case"sepolia":return"https://api-sepolia.etherscan.io";case"matic":return"https://api.polygonscan.com";case"maticmum":return"https://api-testnet.polygonscan.com";case"arbitrum":return"https://api.arbiscan.io";case"arbitrum-goerli":return"https://api-goerli.arbiscan.io";case"optimism":return"https://api-optimistic.etherscan.io";case"optimism-goerli":return"https://api-goerli-optimistic.etherscan.io"}return xa.throwArgumentError("unsupported network","network",this.network.name)}getUrl(e,t){const r=Object.keys(t).reduce((e,r)=>{const n=t[r];return null!=n&&(e+=`&${r}=${n}`),e},""),n=this.apiKey?`&apikey=${this.apiKey}`:"";return`${this.baseUrl}/api?module=${e}${r}${n}`}getPostUrl(){return`${this.baseUrl}/api`}getPostData(e,t){return t.module=e,t.apikey=this.apiKey,t}fetch(e,t,r){return ka(this,void 0,void 0,function*(){const n=r?this.getPostUrl():this.getUrl(e,t),i=r?this.getPostData(e,t):null,s="proxy"===e?Sa:Ta;this.emit("debug",{action:"request",request:n,provider:this});const o={url:n,throttleSlotInterval:1e3,throttleCallback:(e,t)=>(this.isCommunityResource()&&Eo(),Promise.resolve(!0))};let a=null;i&&(o.headers={"content-type":"application/x-www-form-urlencoded; charset=UTF-8"},a=Object.keys(i).map(e=>`${e}=${i[e]}`).join("&"));const c=yield lo(o,a,s||Sa);return this.emit("debug",{action:"response",request:n,response:ce(c),provider:this}),c})}detectNetwork(){return ka(this,void 0,void 0,function*(){return this.network})}perform(e,t){const r=Object.create(null,{perform:{get:()=>super.perform}});return ka(this,void 0,void 0,function*(){switch(e){case"getBlockNumber":return this.fetch("proxy",{action:"eth_blockNumber"});case"getGasPrice":return this.fetch("proxy",{action:"eth_gasPrice"});case"getBalance":return this.fetch("account",{action:"balance",address:t.address,tag:t.blockTag});case"getTransactionCount":return this.fetch("proxy",{action:"eth_getTransactionCount",address:t.address,tag:t.blockTag});case"getCode":return this.fetch("proxy",{action:"eth_getCode",address:t.address,tag:t.blockTag});case"getStorageAt":return this.fetch("proxy",{action:"eth_getStorageAt",address:t.address,position:t.position,tag:t.blockTag});case"sendTransaction":return this.fetch("proxy",{action:"eth_sendRawTransaction",hex:t.signedTransaction},!0).catch(e=>Na("sendTransaction",e,t.signedTransaction));case"getBlock":if(t.blockTag)return this.fetch("proxy",{action:"eth_getBlockByNumber",tag:t.blockTag,boolean:t.includeTransactions?"true":"false"});throw new Error("getBlock by blockHash not implemented");case"getTransaction":return this.fetch("proxy",{action:"eth_getTransactionByHash",txhash:t.transactionHash});case"getTransactionReceipt":return this.fetch("proxy",{action:"eth_getTransactionReceipt",txhash:t.transactionHash});case"call":{if("latest"!==t.blockTag)throw new Error("EtherscanProvider does not support blockTag for call");const e=_a(t.transaction);e.module="proxy",e.action="eth_call";try{return yield this.fetch("proxy",e,!0)}catch(e){return Na("call",e,t.transaction)}}case"estimateGas":{const e=_a(t.transaction);e.module="proxy",e.action="eth_estimateGas";try{return yield this.fetch("proxy",e,!0)}catch(e){return Na("estimateGas",e,t.transaction)}}case"getLogs":{const e={action:"getLogs"};if(t.filter.fromBlock&&(e.fromBlock=Ia(t.filter.fromBlock)),t.filter.toBlock&&(e.toBlock=Ia(t.filter.toBlock)),t.filter.address&&(e.address=t.filter.address),t.filter.topics&&t.filter.topics.length>0&&(t.filter.topics.length>1&&xa.throwError("unsupported topic count",v.errors.UNSUPPORTED_OPERATION,{topics:t.filter.topics}),1===t.filter.topics.length)){const r=t.filter.topics[0];"string"==typeof r&&66===r.length||xa.throwError("unsupported topic format",v.errors.UNSUPPORTED_OPERATION,{topic0:r}),e.topic0=r}const r=yield this.fetch("logs",e);let n={};for(let e=0;e<r.length;e++){const t=r[e];if(null==t.blockHash){if(null==n[t.blockNumber]){const e=yield this.getBlock(t.blockNumber);e&&(n[t.blockNumber]=e.hash)}t.blockHash=n[t.blockNumber]}}return r}case"getEtherPrice":return"homestead"!==this.network.name?0:parseFloat((yield this.fetch("stats",{action:"ethprice"})).ethusd)}return r.perform.call(this,e,t)})}getHistory(e,t,r){return ka(this,void 0,void 0,function*(){const n={action:"txlist",address:yield this.resolveName(e),startblock:null==t?0:t,endblock:null==r?99999999:r,sort:"asc"};return(yield this.fetch("account",n)).map(e=>{["contractAddress","to"].forEach(function(t){""==e[t]&&delete e[t]}),null==e.creates&&null!=e.contractAddress&&(e.creates=e.contractAddress);const t=this.formatter.transactionResponse(e);return e.timeStamp&&(t.timestamp=parseInt(e.timeStamp)),t})})}isCommunityResource(){return null==this.apiKey}}function Oa(e){for(let t=(e=e.slice()).length-1;t>0;t--){const r=Math.floor(Math.random()*(t+1)),n=e[t];e[t]=e[r],e[r]=n}return e}var Ca=function(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};const Pa=new v(mo);function Ma(){return(new Date).getTime()}function Da(e){let t=null;for(let r=0;r<e.length;r++){const n=e[r];if(null==n)return null;t?t.name===n.name&&t.chainId===n.chainId&&(t.ensAddress===n.ensAddress||null==t.ensAddress&&null==n.ensAddress)||Pa.throwArgumentError("provider mismatch","networks",e):t=n}return t}function Ba(e,t){e=e.slice().sort();const r=Math.floor(e.length/2);if(e.length%2)return e[r];const n=e[r-1],i=e[r];return null!=t&&Math.abs(n-i)>t?null:(n+i)/2}function La(e){if(null===e)return"null";if("number"==typeof e||"boolean"==typeof e)return JSON.stringify(e);if("string"==typeof e)return e;if(W.isBigNumber(e))return e.toString();if(Array.isArray(e))return JSON.stringify(e.map(e=>La(e)));if("object"==typeof e){const t=Object.keys(e);return t.sort(),"{"+t.map(t=>{let r=e[t];return r="function"==typeof r?"[function]":La(r),JSON.stringify(t)+":"+r}).join(",")+"}"}throw new Error("unknown value type: "+typeof e)}let Ua=1;function Fa(e){let t=null,r=null,n=new Promise(n=>{t=function(){r&&(clearTimeout(r),r=null),n()},r=setTimeout(t,e)});return{cancel:t,getPromise:function(){return n},wait:e=>(n=n.then(e),n)}}const $a=[v.errors.CALL_EXCEPTION,v.errors.INSUFFICIENT_FUNDS,v.errors.NONCE_EXPIRED,v.errors.REPLACEMENT_UNDERPRICED,v.errors.UNPREDICTABLE_GAS_LIMIT],Ha=["address","args","errorArgs","errorSignature","method","transaction"];function Ka(e,t){const r={weight:e.weight};return Object.defineProperty(r,"provider",{get:()=>e.provider}),e.start&&(r.start=e.start),t&&(r.duration=t-e.start),e.done&&(e.error?r.error=e.error:r.result=e.result||null),r}function qa(e,t){return Ca(this,void 0,void 0,function*(){const r=e.provider;return null!=r.blockNumber&&r.blockNumber>=t||-1===t?r:ho(()=>new Promise((n,i)=>{setTimeout(function(){return r.blockNumber>=t?n(r):e.cancelled?n(null):n(void 0)},0)}),{oncePoll:r})})}function ja(e,t,r,n){return Ca(this,void 0,void 0,function*(){let i=e.provider;switch(r){case"getBlockNumber":case"getGasPrice":return i[r]();case"getEtherPrice":if(i.getEtherPrice)return i.getEtherPrice();break;case"getBalance":case"getTransactionCount":case"getCode":return n.blockTag&&N(n.blockTag)&&(i=yield qa(e,t)),i[r](n.address,n.blockTag||"latest");case"getStorageAt":return n.blockTag&&N(n.blockTag)&&(i=yield qa(e,t)),i.getStorageAt(n.address,n.position,n.blockTag||"latest");case"getBlock":return n.blockTag&&N(n.blockTag)&&(i=yield qa(e,t)),i[n.includeTransactions?"getBlockWithTransactions":"getBlock"](n.blockTag||n.blockHash);case"call":case"estimateGas":return n.blockTag&&N(n.blockTag)&&(i=yield qa(e,t)),"call"===r&&n.blockTag?i[r](n.transaction,n.blockTag):i[r](n.transaction);case"getTransaction":case"getTransactionReceipt":return i[r](n.transactionHash);case"getLogs":{let r=n.filter;return(r.fromBlock&&N(r.fromBlock)||r.toBlock&&N(r.toBlock))&&(i=yield qa(e,t)),i.getLogs(r)}}return Pa.throwError("unknown method error",v.errors.UNKNOWN_ERROR,{method:r,params:n})})}class za extends zo{constructor(e,t){0===e.length&&Pa.throwArgumentError("missing providers","providers",e);const r=e.map((e,t)=>{if(nr.isProvider(e)){const t=bo(e)?2e3:750,r=1;return Object.freeze({provider:e,weight:1,stallTimeout:t,priority:r})}const r=ie(e);null==r.priority&&(r.priority=1),null==r.stallTimeout&&(r.stallTimeout=bo(e)?2e3:750),null==r.weight&&(r.weight=1);const n=r.weight;return(n%1||n>512||n<1)&&Pa.throwArgumentError("invalid weight; must be integer in [1, 512]",`providers[${t}].weight`,n),Object.freeze(r)}),n=r.reduce((e,t)=>e+t.weight,0);null==t?t=n/2:t>n&&Pa.throwArgumentError("quorum will always fail; larger than total weight","quorum",t);let i=Da(r.map(e=>e.provider.network));null==i&&(i=new Promise((e,t)=>{setTimeout(()=>{this.detectNetwork().then(e,t)},0)})),super(i),ee(this,"providerConfigs",Object.freeze(r)),ee(this,"quorum",t),this._highestBlockNumber=-1}detectNetwork(){return Ca(this,void 0,void 0,function*(){return Da(yield Promise.all(this.providerConfigs.map(e=>e.provider.getNetwork())))})}perform(e,t){return Ca(this,void 0,void 0,function*(){if("sendTransaction"===e){const e=yield Promise.all(this.providerConfigs.map(e=>e.provider.sendTransaction(t.signedTransaction).then(e=>e.hash,e=>e)));for(let t=0;t<e.length;t++){const r=e[t];if("string"==typeof r)return r}throw e[0]}-1===this._highestBlockNumber&&"getBlockNumber"!==e&&(yield this.getBlockNumber());const r=function(e,t,r){let n=La;switch(t){case"getBlockNumber":return function(t){const r=t.map(e=>e.result);let n=Ba(t.map(e=>e.result),2);if(null!=n)return n=Math.ceil(n),r.indexOf(n+1)>=0&&n++,n>=e._highestBlockNumber&&(e._highestBlockNumber=n),e._highestBlockNumber};case"getGasPrice":return function(e){const t=e.map(e=>e.result);return t.sort(),t[Math.floor(t.length/2)]};case"getEtherPrice":return function(e){return Ba(e.map(e=>e.result))};case"getBalance":case"getTransactionCount":case"getCode":case"getStorageAt":case"call":case"estimateGas":case"getLogs":break;case"getTransaction":case"getTransactionReceipt":n=function(e){return null==e?null:((e=ie(e)).confirmations=-1,La(e))};break;case"getBlock":n=r.includeTransactions?function(e){return null==e?null:((e=ie(e)).transactions=e.transactions.map(e=>((e=ie(e)).confirmations=-1,e)),La(e))}:function(e){return null==e?null:La(e)};break;default:throw new Error("unknown method: "+t)}return function(e,t){return function(r){const n={};r.forEach(t=>{const r=e(t.result);n[r]||(n[r]={count:0,result:t.result}),n[r].count++});const i=Object.keys(n);for(let e=0;e<i.length;e++){const r=n[i[e]];if(r.count>=t)return r.result}}}(n,e.quorum)}(this,e,t),n=Oa(this.providerConfigs.map(ie));n.sort((e,t)=>e.priority-t.priority);const i=this._highestBlockNumber;let s=0,o=!0;for(;;){const a=Ma();let c=n.filter(e=>e.runner&&a-e.start<e.stallTimeout).reduce((e,t)=>e+t.weight,0);for(;c<this.quorum&&s<n.length;){const r=n[s++],o=Ua++;r.start=Ma(),r.staller=Fa(r.stallTimeout),r.staller.wait(()=>{r.staller=null}),r.runner=ja(r,i,e,t).then(n=>{r.done=!0,r.result=n,this.listenerCount("debug")&&this.emit("debug",{action:"request",rid:o,backend:Ka(r,Ma()),request:{method:e,params:ce(t)},provider:this})},n=>{r.done=!0,r.error=n,this.listenerCount("debug")&&this.emit("debug",{action:"request",rid:o,backend:Ka(r,Ma()),request:{method:e,params:ce(t)},provider:this})}),this.listenerCount("debug")&&this.emit("debug",{action:"request",rid:o,backend:Ka(r,null),request:{method:e,params:ce(t)},provider:this}),c+=r.weight}const u=[];n.forEach(e=>{!e.done&&e.runner&&(u.push(e.runner),e.staller&&u.push(e.staller.getPromise()))}),u.length&&(yield Promise.race(u));const l=n.filter(e=>e.done&&null==e.error);if(l.length>=this.quorum){const e=r(l);if(void 0!==e)return n.forEach(e=>{e.staller&&e.staller.cancel(),e.cancelled=!0}),e;o||(yield Fa(100).getPromise()),o=!1}const h=n.reduce((e,t)=>{if(!t.done||null==t.error)return e;const r=t.error.code;return $a.indexOf(r)>=0&&(e[r]||(e[r]={error:t.error,weight:0}),e[r].weight+=t.weight),e},{});if(Object.keys(h).forEach(e=>{const t=h[e];if(t.weight<this.quorum)return;n.forEach(e=>{e.staller&&e.staller.cancel(),e.cancelled=!0});const r=t.error,i={};Ha.forEach(e=>{null!=r[e]&&(i[e]=r[e])}),Pa.throwError(r.reason||r.message,e,i)}),0===n.filter(e=>!e.done).length)break}return n.forEach(e=>{e.staller&&e.staller.cancel(),e.cancelled=!0}),Pa.throwError("failed to meet quorum",v.errors.SERVER_ERROR,{method:e,params:t,results:n.map(e=>Ka(e)),provider:this})})}}const Va=null,Ga=new v(mo),Wa="84842078b09946638c03157f83405213";class Ja extends ua{constructor(e,t){const r=new Za(e,t),n=r.connection;n.password&&Ga.throwError("INFURA WebSocket project secrets unsupported",v.errors.UNSUPPORTED_OPERATION,{operation:"InfuraProvider.getWebSocketProvider()"}),super(n.url.replace(/^http/i,"ws").replace("/v3/","/ws/v3/"),e),ee(this,"apiKey",r.projectId),ee(this,"projectId",r.projectId),ee(this,"projectSecret",r.projectSecret)}isCommunityResource(){return this.projectId===Wa}}class Za extends da{static getWebSocketProvider(e,t){return new Ja(e,t)}static getApiKey(e){const t={apiKey:Wa,projectId:Wa,projectSecret:null};return null==e||("string"==typeof e?t.projectId=e:null!=e.projectSecret?(Ga.assertArgument("string"==typeof e.projectId,"projectSecret requires a projectId","projectId",e.projectId),Ga.assertArgument("string"==typeof e.projectSecret,"invalid projectSecret","projectSecret","[REDACTED]"),t.projectId=e.projectId,t.projectSecret=e.projectSecret):e.projectId&&(t.projectId=e.projectId),t.apiKey=t.projectId),t}static getUrl(e,t){let r=null;switch(e?e.name:"unknown"){case"homestead":r="mainnet.infura.io";break;case"goerli":r="goerli.infura.io";break;case"sepolia":r="sepolia.infura.io";break;case"matic":r="polygon-mainnet.infura.io";break;case"maticmum":r="polygon-mumbai.infura.io";break;case"optimism":r="optimism-mainnet.infura.io";break;case"optimism-goerli":r="optimism-goerli.infura.io";break;case"optimism-sepolia":r="optimism-sepolia.infura.io";break;case"arbitrum":r="arbitrum-mainnet.infura.io";break;case"arbitrum-goerli":r="arbitrum-goerli.infura.io";break;case"arbitrum-sepolia":r="arbitrum-sepolia.infura.io";break;default:Ga.throwError("unsupported network",v.errors.INVALID_ARGUMENT,{argument:"network",value:e})}const n={allowGzip:!0,url:"https://"+r+"/v3/"+t.projectId,throttleCallback:(e,r)=>(t.projectId===Wa&&Eo(),Promise.resolve(!0))};return null!=t.projectSecret&&(n.user="",n.password=t.projectSecret),n}isCommunityResource(){return this.projectId===Wa}}class Ya extends ia{send(e,t){const r={method:e,params:t,id:this._nextId++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const n={request:r,resolve:null,reject:null},i=new Promise((e,t)=>{n.resolve=e,n.reject=t});return this._pendingBatch.push(n),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(()=>{const e=this._pendingBatch;this._pendingBatch=null,this._pendingBatchAggregator=null;const t=e.map(e=>e.request);return this.emit("debug",{action:"requestBatch",request:ce(t),provider:this}),lo(this.connection,JSON.stringify(t)).then(r=>{this.emit("debug",{action:"response",request:t,response:r,provider:this}),e.forEach((e,t)=>{const n=r[t];if(n.error){const t=new Error(n.error.message);t.code=n.error.code,t.data=n.error.data,e.reject(t)}else e.resolve(n.result)})},r=>{this.emit("debug",{action:"response",error:r,request:t,provider:this}),e.forEach(e=>{e.reject(r)})})},10)),i}}const Qa=new v(mo);class Xa extends da{static getApiKey(e){return e&&"string"!=typeof e&&Qa.throwArgumentError("invalid apiKey","apiKey",e),e||"ETHERS_JS_SHARED"}static getUrl(e,t){Qa.warn("NodeSmith will be discontinued on 2019-12-20; please migrate to another platform.");let r=null;switch(e.name){case"homestead":r="https://ethereum.api.nodesmith.io/v1/mainnet/jsonrpc";break;case"ropsten":r="https://ethereum.api.nodesmith.io/v1/ropsten/jsonrpc";break;case"rinkeby":r="https://ethereum.api.nodesmith.io/v1/rinkeby/jsonrpc";break;case"goerli":r="https://ethereum.api.nodesmith.io/v1/goerli/jsonrpc";break;case"kovan":r="https://ethereum.api.nodesmith.io/v1/kovan/jsonrpc";break;default:Qa.throwArgumentError("unsupported network","network",arguments[0])}return r+"?apiKey="+t}}const ec=new v(mo),tc="62e1ad51b37b8e00394bda3b";class rc extends da{static getApiKey(e){const t={applicationId:null,loadBalancer:!0,applicationSecretKey:null};return null==e?t.applicationId=tc:"string"==typeof e?t.applicationId=e:null!=e.applicationSecretKey?(t.applicationId=e.applicationId,t.applicationSecretKey=e.applicationSecretKey):e.applicationId?t.applicationId=e.applicationId:ec.throwArgumentError("unsupported PocketProvider apiKey","apiKey",e),t}static getUrl(e,t){let r=null;switch(e?e.name:"unknown"){case"goerli":r="eth-goerli.gateway.pokt.network";break;case"homestead":r="eth-mainnet.gateway.pokt.network";break;case"kovan":r="poa-kovan.gateway.pokt.network";break;case"matic":r="poly-mainnet.gateway.pokt.network";break;case"maticmum":r="polygon-mumbai-rpc.gateway.pokt.network";break;case"rinkeby":r="eth-rinkeby.gateway.pokt.network";break;case"ropsten":r="eth-ropsten.gateway.pokt.network";break;default:ec.throwError("unsupported network",v.errors.INVALID_ARGUMENT,{argument:"network",value:e})}const n={headers:{},url:`https://${r}/v1/lb/${t.applicationId}`};return null!=t.applicationSecretKey&&(n.user="",n.password=t.applicationSecretKey),n}isCommunityResource(){return this.applicationId===tc}}const nc=new v(mo);class ic extends da{static getApiKey(e){return e&&"string"!=typeof e&&nc.throwArgumentError("invalid apiKey","apiKey",e),e||"919b412a057b5e9c9b6dce193c5a60242d6efadb"}static getUrl(e,t){let r=null;switch(e.name){case"homestead":r="ethers.quiknode.pro";break;case"goerli":r="ethers.ethereum-goerli.quiknode.pro";break;case"sepolia":r="ethers.ethereum-sepolia.quiknode.pro";break;case"holesky":r="ethers.ethereum-holesky.quiknode.pro";break;case"arbitrum":r="ethers.arbitrum-mainnet.quiknode.pro";break;case"arbitrum-goerli":r="ethers.arbitrum-goerli.quiknode.pro";break;case"arbitrum-sepolia":r="ethers.arbitrum-sepolia.quiknode.pro";break;case"base":r="ethers.base-mainnet.quiknode.pro";break;case"base-goerli":r="ethers.base-goerli.quiknode.pro";break;case"base-spolia":r="ethers.base-sepolia.quiknode.pro";break;case"bnb":r="ethers.bsc.quiknode.pro";break;case"bnbt":r="ethers.bsc-testnet.quiknode.pro";break;case"matic":r="ethers.matic.quiknode.pro";break;case"maticmum":r="ethers.matic-testnet.quiknode.pro";break;case"optimism":r="ethers.optimism.quiknode.pro";break;case"optimism-goerli":r="ethers.optimism-goerli.quiknode.pro";break;case"optimism-sepolia":r="ethers.optimism-sepolia.quiknode.pro";break;case"xdai":r="ethers.xdai.quiknode.pro";break;default:nc.throwArgumentError("unsupported network","network",arguments[0])}return"https://"+r+"/"+t}}const sc=new v(mo);let oc=1;function ac(e,t){const r="Web3LegacyFetcher";return function(e,n){const i={method:e,params:n,id:oc++,jsonrpc:"2.0"};return new Promise((e,n)=>{this.emit("debug",{action:"request",fetcher:r,request:ce(i),provider:this}),t(i,(t,s)=>{if(t)return this.emit("debug",{action:"response",fetcher:r,error:t,request:i,provider:this}),n(t);if(this.emit("debug",{action:"response",fetcher:r,request:i,response:s,provider:this}),s.error){const e=new Error(s.error.message);return e.code=s.error.code,e.data=s.error.data,n(e)}e(s.result)})})}}class cc extends ia{constructor(e,t){null==e&&sc.throwArgumentError("missing provider","provider",e);let r=null,n=null,i=null;"function"==typeof e?(r="unknown:",n=e):(r=e.host||e.path||"",!r&&e.isMetaMask&&(r="metamask"),i=e,e.request?(""===r&&(r="eip-1193:"),n=function(e){return function(t,r){null==r&&(r=[]);const n={method:t,params:r};return this.emit("debug",{action:"request",fetcher:"Eip1193Fetcher",request:ce(n),provider:this}),e.request(n).then(e=>(this.emit("debug",{action:"response",fetcher:"Eip1193Fetcher",request:n,response:e,provider:this}),e),e=>{throw this.emit("debug",{action:"response",fetcher:"Eip1193Fetcher",request:n,error:e,provider:this}),e})}}(e)):e.sendAsync?n=ac(0,e.sendAsync.bind(e)):e.send?n=ac(0,e.send.bind(e)):sc.throwArgumentError("unsupported provider","provider",e),r||(r="unknown:")),super(r,t),ee(this,"jsonRpcFetchFunc",n),ee(this,"provider",i)}send(e,t){return this.jsonRpcFetchFunc(e,t)}}const uc=new v(mo);function lc(e,t){if(null==e&&(e="homestead"),"string"==typeof e){const t=e.match(/^(ws|http)s?:/i);if(t)switch(t[1].toLowerCase()){case"http":case"https":return new ia(e);case"ws":case"wss":return new ua(e);default:uc.throwArgumentError("unsupported URL scheme","network",e)}}const r=Cs(e);return r&&r._defaultProvider||uc.throwError("unsupported getDefaultProvider network",v.errors.NETWORK_ERROR,{operation:"getDefaultProvider",network:e}),r._defaultProvider({FallbackProvider:za,AlchemyProvider:ga,AnkrProvider:wa,CloudflareProvider:Aa,EtherscanProvider:Ra,InfuraProvider:Za,JsonRpcProvider:ia,NodesmithProvider:Xa,PocketProvider:rc,QuickNodeProvider:ic,Web3Provider:cc,IpcProvider:Va},t)}const hc=new RegExp("^bytes([0-9]+)$"),dc=new RegExp("^(u?int)([0-9]*)$"),fc=new RegExp("^(.*)\\[([0-9]*)\\]$"),pc=new v("solidity/5.8.0");function mc(e,t,r){switch(e){case"address":return r?I(t,32):_(t);case"string":return je(t);case"bytes":return _(t);case"bool":return t=t?"0x01":"0x00",r?I(t,32):_(t)}let n=e.match(dc);if(n){let i=parseInt(n[2]||"256");return(n[2]&&String(i)!==n[2]||i%8!=0||0===i||i>256)&&pc.throwArgumentError("invalid number type","type",e),r&&(i=256),I(t=W.from(t).toTwos(i),i/8)}if(n=e.match(hc),n){const i=parseInt(n[1]);return(String(i)!==n[1]||0===i||i>32)&&pc.throwArgumentError("invalid bytes type","type",e),_(t).byteLength!==i&&pc.throwArgumentError(`invalid value for ${e}`,"value",t),r?_((t+"0000000000000000000000000000000000000000000000000000000000000000").substring(0,66)):t}if(n=e.match(fc),n&&Array.isArray(t)){const r=n[1];parseInt(n[2]||String(t.length))!=t.length&&pc.throwArgumentError(`invalid array length for ${e}`,"value",t);const i=[];return t.forEach(function(e){i.push(mc(r,e,!0))}),T(i)}return pc.throwArgumentError("invalid type","type",e)}function gc(e,t){e.length!=t.length&&pc.throwArgumentError("wrong number of values; expected ${ types.length }","values",t);const r=[];return e.forEach(function(e,n){r.push(mc(e,t[n]))}),O(T(r))}function yc(e,t){return ve(gc(e,t))}function vc(e,t){return gi(gc(e,t))}function bc(e,t){t||(t=function(e){return[parseInt(e,16)]});let r=0,n={};return e.split(",").forEach(e=>{let i=e.split(":");r+=parseInt(i[0],16),n[r]=t(i[1])}),n}function wc(e){let t=0;return e.split(",").map(e=>{let r=e.split("-");1===r.length?r[1]="0":""===r[1]&&(r[1]="1");let n=t+parseInt(r[0],16);return t=parseInt(r[1],16),{l:n,h:t}})}function Ec(e,t){let r=0;for(let n=0;n<t.length;n++){let i=t[n];if(r+=i.l,e>=r&&e<=r+i.h&&(e-r)%(i.d||1)===0){if(i.e&&-1!==i.e.indexOf(e-r))continue;return i}}return null}const Ac=wc("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),kc="ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(e=>parseInt(e,16)),xc=[{h:25,s:32,l:65},{h:30,s:32,e:[23],l:127},{h:54,s:1,e:[48],l:64,d:2},{h:14,s:1,l:57,d:2},{h:44,s:1,l:17,d:2},{h:10,s:1,e:[2,6,8],l:61,d:2},{h:16,s:1,l:68,d:2},{h:84,s:1,e:[18,24,66],l:19,d:2},{h:26,s:32,e:[17],l:435},{h:22,s:1,l:71,d:2},{h:15,s:80,l:40},{h:31,s:32,l:16},{h:32,s:1,l:80,d:2},{h:52,s:1,l:42,d:2},{h:12,s:1,l:55,d:2},{h:40,s:1,e:[38],l:15,d:2},{h:14,s:1,l:48,d:2},{h:37,s:48,l:49},{h:148,s:1,l:6351,d:2},{h:88,s:1,l:160,d:2},{h:15,s:16,l:704},{h:25,s:26,l:854},{h:25,s:32,l:55915},{h:37,s:40,l:1247},{h:25,s:-119711,l:53248},{h:25,s:-119763,l:52},{h:25,s:-119815,l:52},{h:25,s:-119867,e:[1,4,5,7,8,11,12,17],l:52},{h:25,s:-119919,l:52},{h:24,s:-119971,e:[2,7,8,17],l:52},{h:24,s:-120023,e:[2,7,13,15,16,17],l:52},{h:25,s:-120075,l:52},{h:25,s:-120127,l:52},{h:25,s:-120179,l:52},{h:25,s:-120231,l:52},{h:25,s:-120283,l:52},{h:25,s:-120335,l:52},{h:24,s:-119543,e:[17],l:56},{h:24,s:-119601,e:[17],l:58},{h:24,s:-119659,e:[17],l:58},{h:24,s:-119717,e:[17],l:58},{h:24,s:-119775,e:[17],l:58}],_c=bc("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),Tc=bc("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),Sc=bc("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",function(e){if(e.length%4!=0)throw new Error("bad data");let t=[];for(let r=0;r<e.length;r+=4)t.push(parseInt(e.substring(r,r+4),16));return t}),Ic=wc("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");function Nc(e){if(e.match(/^[a-z0-9-]*$/i)&&e.length<=59)return e.toLowerCase();let t=Je(e);var r;r=t.map(e=>{if(kc.indexOf(e)>=0)return[];if(e>=65024&&e<=65039)return[];let t=function(e){let t=Ec(e,xc);if(t)return[e+t.s];let r=_c[e];if(r)return r;let n=Tc[e];return n?[e+n[0]]:Sc[e]||null}(e);return t||[e]}),t=r.reduce((e,t)=>(t.forEach(t=>{e.push(t)}),e),[]),t=Je(Ge(t),Fe.NFKC),t.forEach(e=>{if(Ec(e,Ic))throw new Error("STRINGPREP_CONTAINS_PROHIBITED")}),t.forEach(e=>{if(Ec(e,Ac))throw new Error("STRINGPREP_CONTAINS_UNASSIGNED")});let n=Ge(t);if("-"===n.substring(0,1)||"--"===n.substring(2,4)||"-"===n.substring(n.length-1))throw new Error("invalid hyphen");return n}function Rc(e){const t=je(e);if(t.length>31)throw new Error("bytes32 string must be less than 32 bytes");return O(T([t,ks]).slice(0,32))}function Oc(e){const t=_(e);if(32!==t.length)throw new Error("invalid bytes32 - not 32 bytes long");if(0!==t[31])throw new Error("invalid bytes32 string - no null terminator");let r=31;for(;0===t[r-1];)r--;return We(t.slice(0,r))}const Cc=new v("units/5.8.0"),Pc=["wei","kwei","mwei","gwei","szabo","finney","ether"];function Mc(e){const t=String(e).split(".");(t.length>2||!t[0].match(/^-?[0-9]*$/)||t[1]&&!t[1].match(/^[0-9]*$/)||"."===e||"-."===e)&&Cc.throwArgumentError("invalid value","value",e);let r=t[0],n="";for("-"===r.substring(0,1)&&(n="-",r=r.substring(1));"0"===r.substring(0,1);)r=r.substring(1);""===r&&(r="0");let i="";for(2===t.length&&(i="."+(t[1]||"0"));i.length>2&&"0"===i[i.length-1];)i=i.substring(0,i.length-1);const s=[];for(;r.length;){if(r.length<=3){s.unshift(r);break}{const e=r.length-3;s.unshift(r.substring(e)),r=r.substring(0,e)}}return n+s.join(",")+i}function Dc(e,t){if("string"==typeof t){const e=Pc.indexOf(t);-1!==e&&(t=3*e)}return Kn(e,null!=t?t:18)}function Bc(e,t){if("string"!=typeof e&&Cc.throwArgumentError("value must be a string","value",e),"string"==typeof t){const e=Pc.indexOf(t);-1!==e&&(t=3*e)}return qn(e,null!=t?t:18)}function Lc(e){return Dc(e,18)}function Uc(e){return Bc(e,18)}const Fc="ethers/5.8.0",$c=new v(Fc);try{const e=window;null==e._ethers&&(e._ethers=c)}catch(e){}},9499(e,t,r){var n=t;n.utils=r(461),n.common=r(2191),n.sha=r(5746),n.ripemd=r(4169),n.hmac=r(1825),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},2191(e,t,r){"use strict";var n=r(461),i=r(7784);function s(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}t.BlockHash=s,s.prototype.update=function(e,t){if(e=n.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=n.join32(e,0,e.length-r,this.endian);for(var i=0;i<e.length;i+=this._delta32)this._update(e,i,i+this._delta32)}return this},s.prototype.digest=function(e){return this.update(this._pad()),i(null===this.pending),this._digest(e)},s.prototype._pad=function(){var e=this.pendingTotal,t=this._delta8,r=t-(e+this.padLength)%t,n=new Array(r+this.padLength);n[0]=128;for(var i=1;i<r;i++)n[i]=0;if(e<<=3,"big"===this.endian){for(var s=8;s<this.padLength;s++)n[i++]=0;n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=e>>>24&255,n[i++]=e>>>16&255,n[i++]=e>>>8&255,n[i++]=255&e}else for(n[i++]=255&e,n[i++]=e>>>8&255,n[i++]=e>>>16&255,n[i++]=e>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,s=8;s<this.padLength;s++)n[i++]=0;return n}},1825(e,t,r){"use strict";var n=r(461),i=r(7784);function s(e,t,r){if(!(this instanceof s))return new s(e,t,r);this.Hash=e,this.blockSize=e.blockSize/8,this.outSize=e.outSize/8,this.inner=null,this.outer=null,this._init(n.toArray(t,r))}e.exports=s,s.prototype._init=function(e){e.length>this.blockSize&&(e=(new this.Hash).update(e).digest()),i(e.length<=this.blockSize);for(var t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(this.inner=(new this.Hash).update(e),t=0;t<e.length;t++)e[t]^=106;this.outer=(new this.Hash).update(e)},s.prototype.update=function(e,t){return this.inner.update(e,t),this},s.prototype.digest=function(e){return this.outer.update(this.inner.digest()),this.outer.digest(e)}},4169(e,t,r){"use strict";var n=r(461),i=r(2191),s=n.rotl32,o=n.sum32,a=n.sum32_3,c=n.sum32_4,u=i.BlockHash;function l(){if(!(this instanceof l))return new l;u.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}function h(e,t,r,n){return e<=15?t^r^n:e<=31?t&r|~t&n:e<=47?(t|~r)^n:e<=63?t&n|r&~n:t^(r|~n)}function d(e){return e<=15?0:e<=31?1518500249:e<=47?1859775393:e<=63?2400959708:2840853838}function f(e){return e<=15?1352829926:e<=31?1548603684:e<=47?1836072691:e<=63?2053994217:0}n.inherits(l,u),t.ripemd160=l,l.blockSize=512,l.outSize=160,l.hmacStrength=192,l.padLength=64,l.prototype._update=function(e,t){for(var r=this.h[0],n=this.h[1],i=this.h[2],u=this.h[3],l=this.h[4],v=r,b=n,w=i,E=u,A=l,k=0;k<80;k++){var x=o(s(c(r,h(k,n,i,u),e[p[k]+t],d(k)),g[k]),l);r=l,l=u,u=s(i,10),i=n,n=x,x=o(s(c(v,h(79-k,b,w,E),e[m[k]+t],f(k)),y[k]),A),v=A,A=E,E=s(w,10),w=b,b=x}x=a(this.h[1],i,E),this.h[1]=a(this.h[2],u,A),this.h[2]=a(this.h[3],l,v),this.h[3]=a(this.h[4],r,b),this.h[4]=a(this.h[0],n,w),this.h[0]=x},l.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h,"little"):n.split32(this.h,"little")};var p=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],m=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],g=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],y=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]},5746(e,t,r){"use strict";t.sha1=r(2986),t.sha224=r(5393),t.sha256=r(536),t.sha384=r(2348),t.sha512=r(2157)},2986(e,t,r){"use strict";var n=r(461),i=r(2191),s=r(600),o=n.rotl32,a=n.sum32,c=n.sum32_5,u=s.ft_1,l=i.BlockHash,h=[1518500249,1859775393,2400959708,3395469782];function d(){if(!(this instanceof d))return new d;l.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}n.inherits(d,l),e.exports=d,d.blockSize=512,d.outSize=160,d.hmacStrength=80,d.padLength=64,d.prototype._update=function(e,t){for(var r=this.W,n=0;n<16;n++)r[n]=e[t+n];for(;n<r.length;n++)r[n]=o(r[n-3]^r[n-8]^r[n-14]^r[n-16],1);var i=this.h[0],s=this.h[1],l=this.h[2],d=this.h[3],f=this.h[4];for(n=0;n<r.length;n++){var p=~~(n/20),m=c(o(i,5),u(p,s,l,d),f,r[n],h[p]);f=d,d=l,l=o(s,30),s=i,i=m}this.h[0]=a(this.h[0],i),this.h[1]=a(this.h[1],s),this.h[2]=a(this.h[2],l),this.h[3]=a(this.h[3],d),this.h[4]=a(this.h[4],f)},d.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h,"big"):n.split32(this.h,"big")}},5393(e,t,r){"use strict";var n=r(461),i=r(536);function s(){if(!(this instanceof s))return new s;i.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}n.inherits(s,i),e.exports=s,s.blockSize=512,s.outSize=224,s.hmacStrength=192,s.padLength=64,s.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h.slice(0,7),"big"):n.split32(this.h.slice(0,7),"big")}},536(e,t,r){"use strict";var n=r(461),i=r(2191),s=r(600),o=r(7784),a=n.sum32,c=n.sum32_4,u=n.sum32_5,l=s.ch32,h=s.maj32,d=s.s0_256,f=s.s1_256,p=s.g0_256,m=s.g1_256,g=i.BlockHash,y=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function v(){if(!(this instanceof v))return new v;g.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=y,this.W=new Array(64)}n.inherits(v,g),e.exports=v,v.blockSize=512,v.outSize=256,v.hmacStrength=192,v.padLength=64,v.prototype._update=function(e,t){for(var r=this.W,n=0;n<16;n++)r[n]=e[t+n];for(;n<r.length;n++)r[n]=c(m(r[n-2]),r[n-7],p(r[n-15]),r[n-16]);var i=this.h[0],s=this.h[1],g=this.h[2],y=this.h[3],v=this.h[4],b=this.h[5],w=this.h[6],E=this.h[7];for(o(this.k.length===r.length),n=0;n<r.length;n++){var A=u(E,f(v),l(v,b,w),this.k[n],r[n]),k=a(d(i),h(i,s,g));E=w,w=b,b=v,v=a(y,A),y=g,g=s,s=i,i=a(A,k)}this.h[0]=a(this.h[0],i),this.h[1]=a(this.h[1],s),this.h[2]=a(this.h[2],g),this.h[3]=a(this.h[3],y),this.h[4]=a(this.h[4],v),this.h[5]=a(this.h[5],b),this.h[6]=a(this.h[6],w),this.h[7]=a(this.h[7],E)},v.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h,"big"):n.split32(this.h,"big")}},2348(e,t,r){"use strict";var n=r(461),i=r(2157);function s(){if(!(this instanceof s))return new s;i.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}n.inherits(s,i),e.exports=s,s.blockSize=1024,s.outSize=384,s.hmacStrength=192,s.padLength=128,s.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h.slice(0,12),"big"):n.split32(this.h.slice(0,12),"big")}},2157(e,t,r){"use strict";var n=r(461),i=r(2191),s=r(7784),o=n.rotr64_hi,a=n.rotr64_lo,c=n.shr64_hi,u=n.shr64_lo,l=n.sum64,h=n.sum64_hi,d=n.sum64_lo,f=n.sum64_4_hi,p=n.sum64_4_lo,m=n.sum64_5_hi,g=n.sum64_5_lo,y=i.BlockHash,v=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function b(){if(!(this instanceof b))return new b;y.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=v,this.W=new Array(160)}function w(e,t,r,n,i){var s=e&r^~e&i;return s<0&&(s+=4294967296),s}function E(e,t,r,n,i,s){var o=t&n^~t&s;return o<0&&(o+=4294967296),o}function A(e,t,r,n,i){var s=e&r^e&i^r&i;return s<0&&(s+=4294967296),s}function k(e,t,r,n,i,s){var o=t&n^t&s^n&s;return o<0&&(o+=4294967296),o}function x(e,t){var r=o(e,t,28)^o(t,e,2)^o(t,e,7);return r<0&&(r+=4294967296),r}function _(e,t){var r=a(e,t,28)^a(t,e,2)^a(t,e,7);return r<0&&(r+=4294967296),r}function T(e,t){var r=o(e,t,14)^o(e,t,18)^o(t,e,9);return r<0&&(r+=4294967296),r}function S(e,t){var r=a(e,t,14)^a(e,t,18)^a(t,e,9);return r<0&&(r+=4294967296),r}function I(e,t){var r=o(e,t,1)^o(e,t,8)^c(e,t,7);return r<0&&(r+=4294967296),r}function N(e,t){var r=a(e,t,1)^a(e,t,8)^u(e,t,7);return r<0&&(r+=4294967296),r}function R(e,t){var r=o(e,t,19)^o(t,e,29)^c(e,t,6);return r<0&&(r+=4294967296),r}function O(e,t){var r=a(e,t,19)^a(t,e,29)^u(e,t,6);return r<0&&(r+=4294967296),r}n.inherits(b,y),e.exports=b,b.blockSize=1024,b.outSize=512,b.hmacStrength=192,b.padLength=128,b.prototype._prepareBlock=function(e,t){for(var r=this.W,n=0;n<32;n++)r[n]=e[t+n];for(;n<r.length;n+=2){var i=R(r[n-4],r[n-3]),s=O(r[n-4],r[n-3]),o=r[n-14],a=r[n-13],c=I(r[n-30],r[n-29]),u=N(r[n-30],r[n-29]),l=r[n-32],h=r[n-31];r[n]=f(i,s,o,a,c,u,l,h),r[n+1]=p(i,s,o,a,c,u,l,h)}},b.prototype._update=function(e,t){this._prepareBlock(e,t);var r=this.W,n=this.h[0],i=this.h[1],o=this.h[2],a=this.h[3],c=this.h[4],u=this.h[5],f=this.h[6],p=this.h[7],y=this.h[8],v=this.h[9],b=this.h[10],I=this.h[11],N=this.h[12],R=this.h[13],O=this.h[14],C=this.h[15];s(this.k.length===r.length);for(var P=0;P<r.length;P+=2){var M=O,D=C,B=T(y,v),L=S(y,v),U=w(y,0,b,0,N),F=E(0,v,0,I,0,R),$=this.k[P],H=this.k[P+1],K=r[P],q=r[P+1],j=m(M,D,B,L,U,F,$,H,K,q),z=g(M,D,B,L,U,F,$,H,K,q);M=x(n,i),D=_(n,i),B=A(n,0,o,0,c),L=k(0,i,0,a,0,u);var V=h(M,D,B,L),G=d(M,D,B,L);O=N,C=R,N=b,R=I,b=y,I=v,y=h(f,p,j,z),v=d(p,p,j,z),f=c,p=u,c=o,u=a,o=n,a=i,n=h(j,z,V,G),i=d(j,z,V,G)}l(this.h,0,n,i),l(this.h,2,o,a),l(this.h,4,c,u),l(this.h,6,f,p),l(this.h,8,y,v),l(this.h,10,b,I),l(this.h,12,N,R),l(this.h,14,O,C)},b.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h,"big"):n.split32(this.h,"big")}},600(e,t,r){"use strict";var n=r(461).rotr32;function i(e,t,r){return e&t^~e&r}function s(e,t,r){return e&t^e&r^t&r}function o(e,t,r){return e^t^r}t.ft_1=function(e,t,r,n){return 0===e?i(t,r,n):1===e||3===e?o(t,r,n):2===e?s(t,r,n):void 0},t.ch32=i,t.maj32=s,t.p32=o,t.s0_256=function(e){return n(e,2)^n(e,13)^n(e,22)},t.s1_256=function(e){return n(e,6)^n(e,11)^n(e,25)},t.g0_256=function(e){return n(e,7)^n(e,18)^e>>>3},t.g1_256=function(e){return n(e,17)^n(e,19)^e>>>10}},461(e,t,r){"use strict";var n=r(7784),i=r(5615);function s(e,t){return 55296==(64512&e.charCodeAt(t))&&!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1))}function o(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function c(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}t.inherits=i,t.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),i=0;i<e.length;i+=2)r.push(parseInt(e[i]+e[i+1],16))}else for(var n=0,i=0;i<e.length;i++){var o=e.charCodeAt(i);o<128?r[n++]=o:o<2048?(r[n++]=o>>6|192,r[n++]=63&o|128):s(e,i)?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i<e.length;i++)r[i]=0|e[i];return r},t.toHex=function(e){for(var t="",r=0;r<e.length;r++)t+=a(e[r].toString(16));return t},t.htonl=o,t.toHex32=function(e,t){for(var r="",n=0;n<e.length;n++){var i=e[n];"little"===t&&(i=o(i)),r+=c(i.toString(16))}return r},t.zero2=a,t.zero8=c,t.join32=function(e,t,r,i){var s=r-t;n(s%4==0);for(var o=new Array(s/4),a=0,c=t;a<o.length;a++,c+=4){var u;u="big"===i?e[c]<<24|e[c+1]<<16|e[c+2]<<8|e[c+3]:e[c+3]<<24|e[c+2]<<16|e[c+1]<<8|e[c],o[a]=u>>>0}return o},t.split32=function(e,t){for(var r=new Array(4*e.length),n=0,i=0;n<e.length;n++,i+=4){var s=e[n];"big"===t?(r[i]=s>>>24,r[i+1]=s>>>16&255,r[i+2]=s>>>8&255,r[i+3]=255&s):(r[i+3]=s>>>24,r[i+2]=s>>>16&255,r[i+1]=s>>>8&255,r[i]=255&s)}return r},t.rotr32=function(e,t){return e>>>t|e<<32-t},t.rotl32=function(e,t){return e<<t|e>>>32-t},t.sum32=function(e,t){return e+t>>>0},t.sum32_3=function(e,t,r){return e+t+r>>>0},t.sum32_4=function(e,t,r,n){return e+t+r+n>>>0},t.sum32_5=function(e,t,r,n,i){return e+t+r+n+i>>>0},t.sum64=function(e,t,r,n){var i=e[t],s=n+e[t+1]>>>0,o=(s<n?1:0)+r+i;e[t]=o>>>0,e[t+1]=s},t.sum64_hi=function(e,t,r,n){return(t+n>>>0<t?1:0)+e+r>>>0},t.sum64_lo=function(e,t,r,n){return t+n>>>0},t.sum64_4_hi=function(e,t,r,n,i,s,o,a){var c=0,u=t;return c+=(u=u+n>>>0)<t?1:0,c+=(u=u+s>>>0)<s?1:0,e+r+i+o+(c+=(u=u+a>>>0)<a?1:0)>>>0},t.sum64_4_lo=function(e,t,r,n,i,s,o,a){return t+n+s+a>>>0},t.sum64_5_hi=function(e,t,r,n,i,s,o,a,c,u){var l=0,h=t;return l+=(h=h+n>>>0)<t?1:0,l+=(h=h+s>>>0)<s?1:0,l+=(h=h+a>>>0)<a?1:0,e+r+i+o+c+(l+=(h=h+u>>>0)<u?1:0)>>>0},t.sum64_5_lo=function(e,t,r,n,i,s,o,a,c,u){return t+n+s+a+u>>>0},t.rotr64_hi=function(e,t,r){return(t<<32-r|e>>>r)>>>0},t.rotr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0},t.shr64_hi=function(e,t,r){return e>>>r},t.shr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0}},9318(e,t){t.read=function(e,t,r,n,i){var s,o,a=8*i-n-1,c=(1<<a)-1,u=c>>1,l=-7,h=r?i-1:0,d=r?-1:1,f=e[t+h];for(h+=d,s=f&(1<<-l)-1,f>>=-l,l+=a;l>0;s=256*s+e[t+h],h+=d,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=n;l>0;o=256*o+e[t+h],h+=d,l-=8);if(0===s)s=1-u;else{if(s===c)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),s-=u}return(f?-1:1)*o*Math.pow(2,s-n)},t.write=function(e,t,r,n,i,s){var o,a,c,u=8*s-i-1,l=(1<<u)-1,h=l>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,p=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(o++,c/=2),o+h>=l?(a=0,o=l):o+h>=1?(a=(t*c-1)*Math.pow(2,i),o+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;e[r+f]=255&o,f+=p,o/=256,u-=8);e[r+f-p]|=128*m}},5615(e){"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},671(e,t,r){var n,i=r(9907);!function(){"use strict";var s="input is invalid type",o="object"==typeof window,a=o?window:{};a.JS_SHA3_NO_WINDOW&&(o=!1);var c=!o&&"object"==typeof self;!a.JS_SHA3_NO_NODE_JS&&"object"==typeof i&&i.versions&&i.versions.node?a=globalThis:c&&(a=self);var u=!a.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,h=!a.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,d="0123456789abcdef".split(""),f=[4,1024,262144,67108864],p=[0,8,16,24],m=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],y=[128,256],v=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136};!a.JS_SHA3_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!h||!a.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});for(var w=function(e,t,r){return function(n){return new D(e,t,e).update(n)[r]()}},E=function(e,t,r){return function(n,i){return new D(e,t,i).update(n)[r]()}},A=function(e,t,r){return function(t,n,i,s){return S["cshake"+e].update(t,n,i,s)[r]()}},k=function(e,t,r){return function(t,n,i,s){return S["kmac"+e].update(t,n,i,s)[r]()}},x=function(e,t,r,n){for(var i=0;i<v.length;++i){var s=v[i];e[s]=t(r,n,s)}return e},_=function(e,t){var r=w(e,t,"hex");return r.create=function(){return new D(e,t,e)},r.update=function(e){return r.create().update(e)},x(r,w,e,t)},T=[{name:"keccak",padding:[1,256,65536,16777216],bits:g,createMethod:_},{name:"sha3",padding:[6,1536,393216,100663296],bits:g,createMethod:_},{name:"shake",padding:[31,7936,2031616,520093696],bits:y,createMethod:function(e,t){var r=E(e,t,"hex");return r.create=function(r){return new D(e,t,r)},r.update=function(e,t){return r.create(t).update(e)},x(r,E,e,t)}},{name:"cshake",padding:f,bits:y,createMethod:function(e,t){var r=b[e],n=A(e,0,"hex");return n.create=function(n,i,s){return i||s?new D(e,t,n).bytepad([i,s],r):S["shake"+e].create(n)},n.update=function(e,t,r,i){return n.create(t,r,i).update(e)},x(n,A,e,t)}},{name:"kmac",padding:f,bits:y,createMethod:function(e,t){var r=b[e],n=k(e,0,"hex");return n.create=function(n,i,s){return new B(e,t,i).bytepad(["KMAC",s],r).bytepad([n],r)},n.update=function(e,t,r,i){return n.create(e,r,i).update(t)},x(n,k,e,t)}}],S={},I=[],N=0;N<T.length;++N)for(var R=T[N],O=R.bits,C=0;C<O.length;++C){var P=R.name+"_"+O[C];if(I.push(P),S[P]=R.createMethod(O[C],R.padding),"sha3"!==R.name){var M=R.name+O[C];I.push(M),S[M]=S[P]}}function D(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function B(e,t,r){D.call(this,e,t,r)}D.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(s);if(null===e)throw new Error(s);if(h&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||h&&ArrayBuffer.isView(e)))throw new Error(s);t=!0}for(var n,i,o=this.blocks,a=this.byteCount,c=e.length,u=this.blockCount,l=0,d=this.s;l<c;){if(this.reset)for(this.reset=!1,o[0]=this.block,n=1;n<u+1;++n)o[n]=0;if(t)for(n=this.start;l<c&&n<a;++l)o[n>>2]|=e[l]<<p[3&n++];else for(n=this.start;l<c&&n<a;++l)(i=e.charCodeAt(l))<128?o[n>>2]|=i<<p[3&n++]:i<2048?(o[n>>2]|=(192|i>>6)<<p[3&n++],o[n>>2]|=(128|63&i)<<p[3&n++]):i<55296||i>=57344?(o[n>>2]|=(224|i>>12)<<p[3&n++],o[n>>2]|=(128|i>>6&63)<<p[3&n++],o[n>>2]|=(128|63&i)<<p[3&n++]):(i=65536+((1023&i)<<10|1023&e.charCodeAt(++l)),o[n>>2]|=(240|i>>18)<<p[3&n++],o[n>>2]|=(128|i>>12&63)<<p[3&n++],o[n>>2]|=(128|i>>6&63)<<p[3&n++],o[n>>2]|=(128|63&i)<<p[3&n++]);if(this.lastByteIndex=n,n>=a){for(this.start=n-a,this.block=o[u],n=0;n<u;++n)d[n]^=o[n];L(d),this.reset=!0}else this.start=n}return this},D.prototype.encode=function(e,t){var r=255&e,n=1,i=[r];for(r=255&(e>>=8);r>0;)i.unshift(r),r=255&(e>>=8),++n;return t?i.push(n):i.unshift(n),this.update(i),i.length},D.prototype.encodeString=function(e){var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(s);if(null===e)throw new Error(s);if(h&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||h&&ArrayBuffer.isView(e)))throw new Error(s);t=!0}var n=0,i=e.length;if(t)n=i;else for(var o=0;o<e.length;++o){var a=e.charCodeAt(o);a<128?n+=1:a<2048?n+=2:a<55296||a>=57344?n+=3:(a=65536+((1023&a)<<10|1023&e.charCodeAt(++o)),n+=4)}return n+=this.encode(8*n),this.update(e),n},D.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var i=t-r%t,s=[];return s.length=i,this.update(s),this},D.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];L(n)}},D.prototype.toString=D.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a="";o<n;){for(s=0;s<t&&o<n;++s,++o)e=r[s],a+=d[e>>4&15]+d[15&e]+d[e>>12&15]+d[e>>8&15]+d[e>>20&15]+d[e>>16&15]+d[e>>28&15]+d[e>>24&15];o%t===0&&(L(r),s=0)}return i&&(e=r[s],a+=d[e>>4&15]+d[15&e],i>1&&(a+=d[e>>12&15]+d[e>>8&15]),i>2&&(a+=d[e>>20&15]+d[e>>16&15])),a},D.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o<n;){for(s=0;s<t&&o<n;++s,++o)c[o]=r[s];o%t===0&&L(r)}return i&&(c[s]=r[s],e=e.slice(0,a)),e},D.prototype.buffer=D.prototype.arrayBuffer,D.prototype.digest=D.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,i=this.outputBlocks,s=this.extraBytes,o=0,a=0,c=[];a<i;){for(o=0;o<r&&a<i;++o,++a)e=a<<2,t=n[o],c[e]=255&t,c[e+1]=t>>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r===0&&L(n)}return s&&(e=a<<2,t=n[o],c[e]=255&t,s>1&&(c[e+1]=t>>8&255),s>2&&(c[e+2]=t>>16&255)),c},B.prototype=new D,B.prototype.finalize=function(){return this.encode(this.outputBits,!0),D.prototype.finalize.call(this)};var L=function(e){var t,r,n,i,s,o,a,c,u,l,h,d,f,p,g,y,v,b,w,E,A,k,x,_,T,S,I,N,R,O,C,P,M,D,B,L,U,F,$,H,K,q,j,z,V,G,W,J,Z,Y,Q,X,ee,te,re,ne,ie,se,oe,ae,ce,ue,le;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],u=e[5]^e[15]^e[25]^e[35]^e[45],l=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|u>>>31),r=s^(u<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(l<<1|h>>>31),r=a^(h<<1|l>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|f>>>31),r=u^(f<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=l^(i<<1|s>>>31),r=h^(s<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,p=e[0],g=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,N=e[20]<<3|e[21]>>>29,R=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,q=e[40]<<18|e[41]>>>14,j=e[41]<<18|e[40]>>>14,D=e[2]<<1|e[3]>>>31,B=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,J=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,O=e[33]<<13|e[32]>>>19,C=e[32]<<13|e[33]>>>19,ue=e[42]<<2|e[43]>>>30,le=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,L=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,b=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,Y=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,P=e[45]<<29|e[44]>>>3,M=e[44]<<29|e[45]>>>3,_=e[6]<<28|e[7]>>>4,T=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,A=e[37]<<21|e[36]>>>11,X=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,z=e[8]<<27|e[9]>>>5,V=e[9]<<27|e[8]>>>5,S=e[18]<<20|e[19]>>>12,I=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,H=e[38]<<8|e[39]>>>24,K=e[39]<<8|e[38]>>>24,k=e[48]<<14|e[49]>>>18,x=e[49]<<14|e[48]>>>18,e[0]=p^~y&b,e[1]=g^~v&w,e[10]=_^~S&N,e[11]=T^~I&R,e[20]=D^~L&F,e[21]=B^~U&$,e[30]=z^~G&J,e[31]=V^~W&Z,e[40]=te^~ne&se,e[41]=re^~ie&oe,e[2]=y^~b&E,e[3]=v^~w&A,e[12]=S^~N&O,e[13]=I^~R&C,e[22]=L^~F&H,e[23]=U^~$&K,e[32]=G^~J&Y,e[33]=W^~Z&Q,e[42]=ne^~se&ae,e[43]=ie^~oe&ce,e[4]=b^~E&k,e[5]=w^~A&x,e[14]=N^~O&P,e[15]=R^~C&M,e[24]=F^~H&q,e[25]=$^~K&j,e[34]=J^~Y&X,e[35]=Z^~Q&ee,e[44]=se^~ae&ue,e[45]=oe^~ce&le,e[6]=E^~k&p,e[7]=A^~x&g,e[16]=O^~P&_,e[17]=C^~M&T,e[26]=H^~q&D,e[27]=K^~j&B,e[36]=Y^~X&z,e[37]=Q^~ee&V,e[46]=ae^~ue&te,e[47]=ce^~le&re,e[8]=k^~p&y,e[9]=x^~g&v,e[18]=P^~_&S,e[19]=M^~T&I,e[28]=q^~D&L,e[29]=j^~B&U,e[38]=X^~z&G,e[39]=ee^~V&W,e[48]=ue^~te&ne,e[49]=le^~re&ie,e[0]^=m[n],e[1]^=m[n+1]};if(u)e.exports=S;else{for(N=0;N<I.length;++N)a[I[N]]=S[I[N]];l&&(void 0===(n=function(){return S}.call(t,r,t,e))||(e.exports=n))}}()},7784(e){function t(e,t){if(!e)throw new Error(t||"Assertion failed")}e.exports=t,t.equal=function(e,t,r){if(e!=t)throw new Error(r||"Assertion failed: "+e+" != "+t)}},7250(e){var t=1e3,r=60*t,n=60*r,i=24*n,s=7*i;function o(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,a){a=a||{};var c,u,l=typeof e;if("string"===l&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*s;case"days":case"day":case"d":return a*i;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===l&&isFinite(e))return a.long?(c=e,(u=Math.abs(c))>=i?o(c,u,i,"day"):u>=n?o(c,u,n,"hour"):u>=r?o(c,u,r,"minute"):u>=t?o(c,u,t,"second"):c+" ms"):function(e){var s=Math.abs(e);return s>=i?Math.round(e/i)+"d":s>=n?Math.round(e/n)+"h":s>=r?Math.round(e/r)+"m":s>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},9907(e){var t,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function o(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"==typeof clearTimeout?clearTimeout:s}catch(e){r=s}}();var a,c=[],u=!1,l=-1;function h(){u&&a&&(u=!1,a.length?c=a.concat(c):l=-1,c.length&&d())}function d(){if(!u){var e=o(h);u=!0;for(var t=c.length;t;){for(a=c,c=[];++l<t;)a&&a[l].run();l=-1,t=c.length}a=null,u=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===s||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function p(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];c.push(new f(e,t)),1!==c.length||u||o(d)},f.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=p,n.addListener=p,n.once=p,n.off=p,n.removeListener=p,n.removeAllListeners=p,n.emit=p,n.prependListener=p,n.prependOnceListener=p,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},3432(e){"use strict";!function(){const t=2147483647;function r(e){const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);let r=1779033703,n=3144134277,i=1013904242,s=2773480762,o=1359893119,a=2600822924,c=528734635,u=1541459225;const l=new Uint32Array(64);function h(e){let h=0,d=e.length;for(;d>=64;){let f,p,m,g,y,v=r,b=n,w=i,E=s,A=o,k=a,x=c,_=u;for(p=0;p<16;p++)m=h+4*p,l[p]=(255&e[m])<<24|(255&e[m+1])<<16|(255&e[m+2])<<8|255&e[m+3];for(p=16;p<64;p++)f=l[p-2],g=(f>>>17|f<<15)^(f>>>19|f<<13)^f>>>10,f=l[p-15],y=(f>>>7|f<<25)^(f>>>18|f<<14)^f>>>3,l[p]=(g+l[p-7]|0)+(y+l[p-16]|0)|0;for(p=0;p<64;p++)g=(((A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7))+(A&k^~A&x)|0)+(_+(t[p]+l[p]|0)|0)|0,y=((v>>>2|v<<30)^(v>>>13|v<<19)^(v>>>22|v<<10))+(v&b^v&w^b&w)|0,_=x,x=k,k=A,A=E+g|0,E=w,w=b,b=v,v=g+y|0;r=r+v|0,n=n+b|0,i=i+w|0,s=s+E|0,o=o+A|0,a=a+k|0,c=c+x|0,u=u+_|0,h+=64,d-=64}}h(e);let d,f=e.length%64,p=e.length/536870912|0,m=e.length<<3,g=f<56?56:120,y=e.slice(e.length-f,e.length);for(y.push(128),d=f+1;d<g;d++)y.push(0);return y.push(p>>>24&255),y.push(p>>>16&255),y.push(p>>>8&255),y.push(p>>>0&255),y.push(m>>>24&255),y.push(m>>>16&255),y.push(m>>>8&255),y.push(m>>>0&255),h(y),[r>>>24&255,r>>>16&255,r>>>8&255,r>>>0&255,n>>>24&255,n>>>16&255,n>>>8&255,n>>>0&255,i>>>24&255,i>>>16&255,i>>>8&255,i>>>0&255,s>>>24&255,s>>>16&255,s>>>8&255,s>>>0&255,o>>>24&255,o>>>16&255,o>>>8&255,o>>>0&255,a>>>24&255,a>>>16&255,a>>>8&255,a>>>0&255,c>>>24&255,c>>>16&255,c>>>8&255,c>>>0&255,u>>>24&255,u>>>16&255,u>>>8&255,u>>>0&255]}function n(e,t,n){e=e.length<=64?e:r(e);const i=64+t.length+4,s=new Array(i),o=new Array(64);let a,c=[];for(a=0;a<64;a++)s[a]=54;for(a=0;a<e.length;a++)s[a]^=e[a];for(a=0;a<t.length;a++)s[64+a]=t[a];for(a=i-4;a<i;a++)s[a]=0;for(a=0;a<64;a++)o[a]=92;for(a=0;a<e.length;a++)o[a]^=e[a];function u(){for(let e=i-1;e>=i-4;e--){if(s[e]++,s[e]<=255)return;s[e]=0}}for(;n>=32;)u(),c=c.concat(r(o.concat(r(s)))),n-=32;return n>0&&(u(),c=c.concat(r(o.concat(r(s))).slice(0,n))),c}function i(e,t,r,n,i){let s;for(c(e,16*(2*r-1),i,0,16),s=0;s<2*r;s++)a(e,16*s,i,16),o(i,n),c(i,0,e,t+16*s,16);for(s=0;s<r;s++)c(e,t+2*s*16,e,16*s,16);for(s=0;s<r;s++)c(e,t+16*(2*s+1),e,16*(s+r),16)}function s(e,t){return e<<t|e>>>32-t}function o(e,t){c(e,0,t,0,16);for(let e=8;e>0;e-=2)t[4]^=s(t[0]+t[12],7),t[8]^=s(t[4]+t[0],9),t[12]^=s(t[8]+t[4],13),t[0]^=s(t[12]+t[8],18),t[9]^=s(t[5]+t[1],7),t[13]^=s(t[9]+t[5],9),t[1]^=s(t[13]+t[9],13),t[5]^=s(t[1]+t[13],18),t[14]^=s(t[10]+t[6],7),t[2]^=s(t[14]+t[10],9),t[6]^=s(t[2]+t[14],13),t[10]^=s(t[6]+t[2],18),t[3]^=s(t[15]+t[11],7),t[7]^=s(t[3]+t[15],9),t[11]^=s(t[7]+t[3],13),t[15]^=s(t[11]+t[7],18),t[1]^=s(t[0]+t[3],7),t[2]^=s(t[1]+t[0],9),t[3]^=s(t[2]+t[1],13),t[0]^=s(t[3]+t[2],18),t[6]^=s(t[5]+t[4],7),t[7]^=s(t[6]+t[5],9),t[4]^=s(t[7]+t[6],13),t[5]^=s(t[4]+t[7],18),t[11]^=s(t[10]+t[9],7),t[8]^=s(t[11]+t[10],9),t[9]^=s(t[8]+t[11],13),t[10]^=s(t[9]+t[8],18),t[12]^=s(t[15]+t[14],7),t[13]^=s(t[12]+t[15],9),t[14]^=s(t[13]+t[12],13),t[15]^=s(t[14]+t[13],18);for(let r=0;r<16;++r)e[r]+=t[r]}function a(e,t,r,n){for(let i=0;i<n;i++)r[i]^=e[t+i]}function c(e,t,r,n,i){for(;i--;)r[n++]=e[t++]}function u(e){if(!e||"number"!=typeof e.length)return!1;for(let t=0;t<e.length;t++){const r=e[t];if("number"!=typeof r||r%1||r<0||r>=256)return!1}return!0}function l(e,t){if("number"!=typeof e||e%1)throw new Error("invalid "+t);return e}function h(e,r,s,o,h,d,f){if(s=l(s,"N"),o=l(o,"r"),h=l(h,"p"),d=l(d,"dkLen"),0===s||s&s-1)throw new Error("N must be power of 2");if(s>t/128/o)throw new Error("N too large");if(o>t/128/h)throw new Error("r too large");if(!u(e))throw new Error("password must be an array or buffer");if(e=Array.prototype.slice.call(e),!u(r))throw new Error("salt must be an array or buffer");r=Array.prototype.slice.call(r);let p=n(e,r,128*h*o);const m=new Uint32Array(32*h*o);for(let e=0;e<m.length;e++){const t=4*e;m[e]=(255&p[t+3])<<24|(255&p[t+2])<<16|(255&p[t+1])<<8|255&p[t+0]}const g=new Uint32Array(64*o),y=new Uint32Array(32*o*s),v=32*o,b=new Uint32Array(16),w=new Uint32Array(16),E=h*s*2;let A,k,x=0,_=null,T=!1,S=0,I=0;const N=f?parseInt(1e3/o):4294967295,R="undefined"!=typeof setImmediate?setImmediate:setTimeout,O=function(){if(T)return f(new Error("cancelled"),x/E);let t;switch(S){case 0:k=32*I*o,c(m,k,g,0,v),S=1,A=0;case 1:t=s-A,t>N&&(t=N);for(let e=0;e<t;e++)c(g,0,y,(A+e)*v,v),i(g,v,o,b,w);if(A+=t,x+=t,f){const e=parseInt(1e3*x/E);if(e!==_){if(T=f(null,x/E),T)break;_=e}}if(A<s)break;A=0,S=2;case 2:t=s-A,t>N&&(t=N);for(let e=0;e<t;e++){const e=g[16*(2*o-1)]&s-1;a(y,e*v,g,v),i(g,v,o,b,w)}if(A+=t,x+=t,f){const e=parseInt(1e3*x/E);if(e!==_){if(T=f(null,x/E),T)break;_=e}}if(A<s)break;if(c(g,0,m,k,v),I++,I<h){S=0;break}p=[];for(let e=0;e<m.length;e++)p.push(255&m[e]),p.push(m[e]>>8&255),p.push(m[e]>>16&255),p.push(m[e]>>24&255);const r=n(e,p,d);return f&&f(null,1,r),r}f&&R(O)};if(!f)for(;;){const e=O();if(null!=e)return e}O()}const d={scrypt:function(e,t,r,n,i,s,o){return new Promise(function(a,c){let u=0;o&&o(0),h(e,t,r,n,i,s,function(e,t,r){if(e)c(e);else if(r)o&&1!==u&&o(1),a(new Uint8Array(r));else if(o&&t!==u)return u=t,o(t)})})},syncScrypt:function(e,t,r,n,i,s){return new Uint8Array(h(e,t,r,n,i,s))}};e.exports=d}()},3880(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SiweMessage=void 0;const n=r(2311),i=r(8708),s=r(1846),o=r(1386);t.SiweMessage=class{constructor(e){if("string"==typeof e){const t=new n.ParsedMessage(e);this.scheme=t.scheme,this.domain=t.domain,this.address=t.address,this.statement=t.statement,this.uri=t.uri,this.version=t.version,this.nonce=t.nonce,this.issuedAt=t.issuedAt,this.expirationTime=t.expirationTime,this.notBefore=t.notBefore,this.requestId=t.requestId,this.chainId=t.chainId,this.resources=t.resources}else this.scheme=null==e?void 0:e.scheme,this.domain=e.domain,this.address=e.address,this.statement=null==e?void 0:e.statement,this.uri=e.uri,this.version=e.version,this.chainId=e.chainId,this.nonce=e.nonce,this.issuedAt=null==e?void 0:e.issuedAt,this.expirationTime=null==e?void 0:e.expirationTime,this.notBefore=null==e?void 0:e.notBefore,this.requestId=null==e?void 0:e.requestId,this.resources=null==e?void 0:e.resources,"string"==typeof this.chainId&&(this.chainId=(0,n.parseIntegerNumber)(this.chainId)),this.nonce=this.nonce||(0,o.generateNonce)(),new n.ParsedMessage(this.prepareMessage())}toMessage(){const e=`${this.scheme?`${this.scheme}://${this.domain}`:this.domain} wants you to sign in with your Ethereum account:`,t=`URI: ${this.uri}`;let r=[e,this.address].join("\n");const n=`Version: ${this.version}`;this.nonce||(this.nonce=(0,o.generateNonce)());const i=[t,n,"Chain ID: "+this.chainId||0,`Nonce: ${this.nonce}`];if(this.issuedAt=this.issuedAt||(new Date).toISOString(),i.push(`Issued At: ${this.issuedAt}`),this.expirationTime){const e=`Expiration Time: ${this.expirationTime}`;i.push(e)}this.notBefore&&i.push(`Not Before: ${this.notBefore}`),this.requestId&&i.push(`Request ID: ${this.requestId}`),this.resources&&i.push(["Resources:",...this.resources.map(e=>`- ${e}`)].join("\n"));const s=i.join("\n");return r=[r,this.statement].join("\n\n"),void 0!==this.statement&&(r+="\n"),[r,s].join("\n")}prepareMessage(){let e;return this.version,e=this.toMessage(),e}async verify(e,t={suppressExceptions:!1}){return new Promise((r,n)=>{var a,c,u;const l=e=>t.suppressExceptions?r(e):n(e),h=(0,o.checkInvalidKeys)(e,s.VerifyParamsKeys);h.length>0&&l({success:!1,data:this,error:new Error(`${h.join(", ")} is/are not valid key(s) for VerifyParams.`)});const d=(0,o.checkInvalidKeys)(t,s.VerifyOptsKeys);d.length>0&&l({success:!1,data:this,error:new Error(`${d.join(", ")} is/are not valid key(s) for VerifyOpts.`)});const{signature:f,scheme:p,domain:m,nonce:g,time:y}=e;p&&p!==this.scheme&&l({success:!1,data:this,error:new s.SiweError(s.SiweErrorType.SCHEME_MISMATCH,p,this.scheme)}),m&&m!==this.domain&&l({success:!1,data:this,error:new s.SiweError(s.SiweErrorType.DOMAIN_MISMATCH,m,this.domain)}),g&&g!==this.nonce&&l({success:!1,data:this,error:new s.SiweError(s.SiweErrorType.NONCE_MISMATCH,g,this.nonce)});const v=new Date(y||new Date);if(this.expirationTime){const e=new Date(this.expirationTime);v.getTime()>=e.getTime()&&l({success:!1,data:this,error:new s.SiweError(s.SiweErrorType.EXPIRED_MESSAGE,`${v.toISOString()} < ${e.toISOString()}`,`${v.toISOString()} >= ${e.toISOString()}`)})}if(this.notBefore){const e=new Date(this.notBefore);v.getTime()<e.getTime()&&l({success:!1,data:this,error:new s.SiweError(s.SiweErrorType.NOT_YET_VALID_MESSAGE,`${v.toISOString()} >= ${e.toISOString()}`,`${v.toISOString()} < ${e.toISOString()}`)})}let b,w;try{b=this.prepareMessage()}catch(e){l({success:!1,data:this,error:e})}try{w=(0,i.verifyMessage)(b,f)}catch(e){console.error(e)}if(w===this.address)return r({success:!0,data:this});{const n=(0,o.checkContractWalletSignature)(this,f,t.provider).then(e=>e?{success:!0,data:this}:{success:!1,data:this,error:new s.SiweError(s.SiweErrorType.INVALID_SIGNATURE,w,`Resolved address to be ${this.address}`)}).catch(e=>({success:!1,data:this,error:e}));Promise.all([n,null===(u=null===(c=null===(a=null==t?void 0:t.verificationFallback)||void 0===a?void 0:a.call(t,e,t,this,n))||void 0===c?void 0:c.then(e=>e))||void 0===u?void 0:u.catch(e=>e)]).then(([e,t])=>{if(t){if(t.success)return r(t);l(t)}else{if(e.success)return r(e);l(e)}})}})}}},8708(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAddress=t.hashMessage=t.verifyMessage=void 0;const n=r(8367);let i=null,s=null,o=null;try{i=n.ethers.utils.verifyMessage,s=n.ethers.utils.hashMessage,o=n.ethers.utils.getAddress}catch(e){i=n.ethers.verifyMessage,s=n.ethers.hashMessage,o=n.ethers.getAddress}t.verifyMessage=i,t.hashMessage=s,t.getAddress=o},427(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(3880),t),i(r(1846),t),i(r(1386),t)},1846(e,t){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.SiweErrorType=t.SiweError=t.VerifyOptsKeys=t.VerifyParamsKeys=void 0,t.VerifyParamsKeys=["signature","scheme","domain","nonce","time"],t.VerifyOptsKeys=["provider","suppressExceptions","verificationFallback"],t.SiweError=class{constructor(e,t,r){this.type=e,this.expected=t,this.received=r}},(r=t.SiweErrorType||(t.SiweErrorType={})).EXPIRED_MESSAGE="Expired message.",r.INVALID_DOMAIN="Invalid domain.",r.SCHEME_MISMATCH="Scheme does not match provided scheme for verification.",r.DOMAIN_MISMATCH="Domain does not match provided domain for verification.",r.NONCE_MISMATCH="Nonce does not match provided nonce for verification.",r.INVALID_ADDRESS="Invalid address.",r.INVALID_URI="URI does not conform to RFC 3986.",r.INVALID_NONCE="Nonce size smaller then 8 characters or is not alphanumeric.",r.NOT_YET_VALID_MESSAGE="Message is not valid yet.",r.INVALID_SIGNATURE="Signature does not match address of the message.",r.INVALID_TIME_FORMAT="Invalid time format.",r.INVALID_MESSAGE_VERSION="Invalid message version.",r.UNABLE_TO_PARSE="Unable to parse the message."},1386(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkInvalidKeys=t.isValidISO8601Date=t.generateNonce=t.checkContractWalletSignature=void 0;const n=r(7687),i=r(8367),s=r(8708),o=["function isValidSignature(bytes32 _message, bytes _signature) public view returns (bytes4)"],a=/^(?<date>[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(.[0-9]+)?(([Zz])|([+|-]([01][0-9]|2[0-3]):[0-5][0-9]))$/;t.checkContractWalletSignature=async(e,t,r)=>{if(!r)return!1;const n=new i.Contract(e.address,o,r),a=(0,s.hashMessage)(e.prepareMessage());return"0x1626ba7e"===await n.isValidSignature(a,t)},t.generateNonce=()=>{const e=(0,n.randomStringForEntropy)(96);if(!e||e.length<8)throw new Error("Error during nonce creation.");return e},t.isValidISO8601Date=e=>{const t=a.exec(e);if(!t)return!1;const r=new Date(t.groups.date).toISOString(),n=a.exec(r);return t.groups.date===n.groups.date},t.checkInvalidKeys=(e,t)=>{const r=[];return Object.keys(e).forEach(e=>{t.includes(e)||r.push(e)}),r}},9332(e){"use strict";e.exports=require("./delegations-issued.cjs")},4212(e){"use strict";e.exports=require("@tinycloud/share-envelope/links")},5423(){},8379(){},4290(e){"use strict";var t,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})})(o,{DecryptTransportResponseError:()=>a}),e.exports=(t=o,((e,t,o,a)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of i(t))s.call(e,o)||void 0===o||r(e,o,{get:()=>t[o],enumerable:!(a=n(t,o))||a.enumerable});return e})(r({},"__esModule",{value:!0}),t));var a=class extends Error{constructor(e,t,r){super("Node decrypt request failed"),this.status=e,this.permissionHint=t,this.notFoundMessage=r,this.name="DecryptTransportResponseError"}}},9964(e,t,r){"use strict";r.d(t,{B4:()=>p,CQ:()=>E,CW:()=>w,Ei:()=>d,F8:()=>A,P5:()=>f,TH:()=>k,Vl:()=>v,Vr:()=>b,WM:()=>m,WQ:()=>y,im:()=>g,jm:()=>c,lD:()=>o,qh:()=>h,rE:()=>u,ry:()=>l,xn:()=>a});const n=BigInt(2**32-1),i=BigInt(32);function s(e,t=!1){return t?{h:Number(e&n),l:Number(e>>i&n)}:{h:0|Number(e>>i&n),l:0|Number(e&n)}}function o(e,t=!1){const r=e.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){const{h:r,l:a}=s(e[o],t);[n[o],i[o]]=[r,a]}return[n,i]}const a=(e,t,r)=>e>>>r,c=(e,t,r)=>e<<32-r|t>>>r,u=(e,t,r)=>e>>>r|t<<32-r,l=(e,t,r)=>e<<32-r|t>>>r,h=(e,t,r)=>e<<64-r|t>>>r-32,d=(e,t,r)=>e>>>r-32|t<<64-r,f=(e,t,r)=>e<<r|t>>>32-r,p=(e,t,r)=>t<<r|e>>>32-r,m=(e,t,r)=>t<<r-32|e>>>64-r,g=(e,t,r)=>e<<r-32|t>>>64-r;function y(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}}const v=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),b=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,w=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),E=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,A=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),k=(e,t,r,n,i,s)=>t+r+n+i+s+(e/2**32|0)|0},113(e,t,r){"use strict";r.r(t),r.d(t,{Keccak:()=>w,keccakP:()=>b,keccak_224:()=>T,keccak_256:()=>S,keccak_384:()=>I,keccak_512:()=>N,sha3_224:()=>A,sha3_256:()=>k,sha3_384:()=>x,sha3_512:()=>_,shake128:()=>O,shake256:()=>C});var n=r(9964),i=r(7997);const s=BigInt(0),o=BigInt(1),a=BigInt(2),c=BigInt(7),u=BigInt(256),l=BigInt(113),h=[],d=[],f=[];for(let e=0,t=o,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],h.push(2*(5*n+r)),d.push((e+1)*(e+2)/2%64);let i=s;for(let e=0;e<7;e++)t=(t<<o^(t>>c)*l)%u,t&a&&(i^=o<<(o<<BigInt(e))-o);f.push(i)}const p=(0,n.lD)(f,!0),m=p[0],g=p[1],y=(e,t,r)=>r>32?(0,n.WM)(e,t,r):(0,n.P5)(e,t,r),v=(e,t,r)=>r>32?(0,n.im)(e,t,r):(0,n.B4)(e,t,r);function b(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const n=(t+8)%10,i=(t+2)%10,s=r[i],o=r[i+1],a=y(s,o,1)^r[n],c=v(s,o,1)^r[n+1];for(let r=0;r<50;r+=10)e[t+r]^=a,e[t+r+1]^=c}let t=e[2],i=e[3];for(let r=0;r<24;r++){const n=d[r],s=y(t,i,n),o=v(t,i,n),a=h[r];t=e[a],i=e[a+1],e[a]=s,e[a+1]=o}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=m[n],e[1]^=g[n]}(0,i.clean)(r)}class w extends i.Hash{constructor(e,t,r,n=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=s,(0,i.anumber)(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=(0,i.u32)(this.state)}clone(){return this._cloneInto()}keccak(){(0,i.swap32IfBE)(this.state32),b(this.state32,this.rounds),(0,i.swap32IfBE)(this.state32),this.posOut=0,this.pos=0}update(e){(0,i.aexists)(this),e=(0,i.toBytes)(e),(0,i.abytes)(e);const{blockLen:t,state:r}=this,n=e.length;for(let i=0;i<n;){const s=Math.min(t-this.pos,n-i);for(let t=0;t<s;t++)r[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:n}=this;e[r]^=t,128&t&&r===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){(0,i.aexists)(this,!1),(0,i.abytes)(e),this.finish();const t=this.state,{blockLen:r}=this;for(let n=0,i=e.length;n<i;){this.posOut>=r&&this.keccak();const s=Math.min(r-this.posOut,i-n);e.set(t.subarray(this.posOut,this.posOut+s),n),this.posOut+=s,n+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,i.anumber)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,i.aoutput)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,(0,i.clean)(this.state)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:n,rounds:i,enableXOF:s}=this;return e||(e=new w(t,r,n,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=n,e.enableXOF=s,e.destroyed=this.destroyed,e}}const E=(e,t,r)=>(0,i.createHasher)(()=>new w(t,e,r)),A=(()=>E(6,144,28))(),k=(()=>E(6,136,32))(),x=(()=>E(6,104,48))(),_=(()=>E(6,72,64))(),T=(()=>E(1,144,28))(),S=(()=>E(1,136,32))(),I=(()=>E(1,104,48))(),N=(()=>E(1,72,64))(),R=(e,t,r)=>(0,i.createXOFer)((n={})=>new w(t,e,void 0===n.dkLen?r:n.dkLen,!0)),O=(()=>R(31,168,16))(),C=(()=>R(31,136,32))()},7997(e,t,r){"use strict";r.r(t),r.d(t,{Hash:()=>D,abytes:()=>o,aexists:()=>c,ahash:()=>a,anumber:()=>s,aoutput:()=>u,asyncLoop:()=>I,byteSwap:()=>y,byteSwap32:()=>w,byteSwapIfBE:()=>b,bytesToHex:()=>x,bytesToUtf8:()=>R,checkOpts:()=>M,clean:()=>d,concatBytes:()=>P,createHasher:()=>B,createOptHasher:()=>L,createView:()=>f,createXOFer:()=>U,hexToBytes:()=>T,isBytes:()=>i,isLE:()=>g,kdfInputToBytes:()=>C,nextTick:()=>S,randomBytes:()=>K,rotl:()=>m,rotr:()=>p,swap32IfBE:()=>E,swap8IfBE:()=>v,toBytes:()=>O,u32:()=>h,u8:()=>l,utf8ToBytes:()=>N,wrapConstructor:()=>F,wrapConstructorWithOpts:()=>$,wrapXOFConstructorWithOpts:()=>H});var n=r(4402);function i(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function s(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function o(e,...t){if(!i(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function a(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");s(e.outputLen),s(e.blockLen)}function c(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function u(e,t){o(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function l(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function h(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function d(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function f(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function p(e,t){return e<<32-t|e>>>t}function m(e,t){return e<<t|e>>>32-t>>>0}const g=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function y(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const v=g?e=>e:e=>y(e),b=v;function w(e){for(let t=0;t<e.length;t++)e[t]=y(e[t]);return e}const E=g?e=>e:w,A=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),k=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function x(e){if(o(e),A)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=k[e[r]];return t}function _(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function T(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(A)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,i=0;t<r;t++,i+=2){const r=_(e.charCodeAt(i)),s=_(e.charCodeAt(i+1));if(void 0===r||void 0===s){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}n[t]=16*r+s}return n}const S=async()=>{};async function I(e,t,r){let n=Date.now();for(let i=0;i<e;i++){r(i);const e=Date.now()-n;e>=0&&e<t||(await S(),n+=e)}}function N(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function R(e){return(new TextDecoder).decode(e)}function O(e){return"string"==typeof e&&(e=N(e)),o(e),e}function C(e){return"string"==typeof e&&(e=N(e)),o(e),e}function P(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];o(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.length}return r}function M(e,t){if(void 0!==t&&"[object Object]"!=={}.toString.call(t))throw new Error("options should be object or undefined");return Object.assign(e,t)}class D{}function B(e){const t=t=>e().update(O(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function L(e){const t=(t,r)=>e(r).update(O(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}function U(e){const t=(t,r)=>e(r).update(O(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}const F=B,$=L,H=U;function K(e=32){if(n.E&&"function"==typeof n.E.getRandomValues)return n.E.getRandomValues(new Uint8Array(e));if(n.E&&"function"==typeof n.E.randomBytes)return Uint8Array.from(n.E.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}},4402(e,t,r){"use strict";r.d(t,{E:()=>i});const n=()=>"undefined"!=typeof globalThis&&globalThis.crypto?globalThis.crypto:"undefined"!=typeof window&&window.crypto?window.crypto:"undefined"!=typeof self&&self.crypto?self.crypto:void 0,i={web:n(),node:void 0,getRandomValues:function(e){const t=n();if(t&&t.getRandomValues)return t.getRandomValues(e);throw new Error("crypto.getRandomValues is unavailable")}}}},n={};function i(e){var t=n[e];if(void 0!==t)return t.exports;var s=n[e]={id:e,loaded:!1,exports:{}};return r[e].call(s.exports,s,s.exports,i),s.loaded=!0,s.exports}i.amdO={},i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(r,n){if(1&n&&(r=this(r)),8&n)return r;if("object"==typeof r&&r){if(4&n&&r.__esModule)return r;if(16&n&&"function"==typeof r.then)return r}var s=Object.create(null);i.r(s);var o={};e=e||[null,t({}),t([]),t(t)];for(var a=2&n&&r;("object"==typeof a||"function"==typeof a)&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach(e=>o[e]=()=>r[e]);return o.default=()=>r,i.d(s,o),s},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var s={};(()=>{"use strict";i.r(s),i.d(s,{ModalManager:()=>Qd,showPermissionRequestModal:()=>ef,showSpaceCreationModal:()=>Xd});let e=0,t="";function r(){let r=!0;return 0===e&&(t=document.body.style.overflow),e+=1,document.body.style.overflow="hidden",()=>{r&&(r=!1,e-=1,0===e&&(document.body.style.overflow=t))}}function n(){let e=document.activeElement;for(;e instanceof HTMLElement&&e.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return e instanceof HTMLElement?e:null}function o(e){return Array.from(e.querySelectorAll("button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href]"))}function a(e,t,r){return 0===e?-1:r?t<=0?e-1:t-1:t<0||t>=e-1?0:t+1}function c(e,t){if(!e?.isConnected)return;const r=n();(null===r||r===document.body||t.contains(r))&&e.focus()}function u(e){const t=e.getBoundingClientRect();if(0===t.width||0===t.height)return!1;const r=e.getRootNode();if("function"!=typeof r.elementFromPoint)return!1;const n=r.elementFromPoint.call(r,t.left+t.width/2,t.top+t.height/2);return null!==n&&e.contains(n)}class l extends HTMLElement{constructor(e){super(),this.isVisible=!1,this.releaseScrollLock=null,this.opener=null,this.isCreating=!1,this.resolveResult=null,this.handleKeyDown=e=>{this.isVisible&&("Escape"!==e.key||this.isCreating?"Tab"===e.key&&this.trapTab(e):this.dismiss())},this.options=e,this.attachShadow({mode:"open"}),this.render(),this.completionPromise=new Promise(e=>{this.resolveResult=e})}getCompletionPromise(){return this.completionPromise}connectedCallback(){this.show(),this.setupEventListeners()}disconnectedCallback(){this.isVisible=!1,this.restoreFocus(),this.releaseLock(),document.removeEventListener("keydown",this.handleKeyDown)}render(){this.shadowRoot.innerHTML=`\n <style>${this.getModalStyles()}</style>\n <div class="modal-backdrop" data-state="hidden">\n <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="tc-space-title" aria-describedby="tc-space-description" tabindex="-1">\n <div class="modal-content">\n <div class="modal-header">\n <div class="modal-icon">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="1.5"/>\n <path d="M8 12l2 2 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </div>\n <h2 class="modal-title" id="tc-space-title">Create Your TinyCloud Space</h2>\n <button class="modal-close" aria-label="Close">\n <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>\n </svg>\n </button>\n </div>\n\n <div class="modal-body">\n <p class="modal-description" id="tc-space-description">\n A TinyCloud Space is your personal data container where only you control access.\n Your signature is required for any operations on the data stored there.\n </p>\n <p class="modal-subdescription">\n Sign a message to create your space and start storing data.\n </p>\n </div>\n\n <div class="modal-actions">\n <button class="modal-button modal-button--secondary" data-action="learn-more">\n Learn More\n </button>\n <button class="modal-button modal-button--primary" data-action="create">\n <span class="button-text">Create TinyCloud Space</span>\n <span class="button-spinner" data-state="hidden">\n <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-dasharray="9.42 9.42" opacity="0.25"/>\n <circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-dasharray="9.42 9.42" stroke-dashoffset="9.42">\n <animateTransform attributeName="transform" type="rotate" values="0 8 8;360 8 8" dur="1s" repeatCount="indefinite"/>\n </circle>\n </svg>\n </span>\n </button>\n </div>\n </div>\n </div>\n </div>\n `}getModalStyles(){return'\n :host {\n --modal-bg: hsl(0 0% 3.9%);\n --modal-border: hsl(0 0% 14.9%);\n --modal-foreground: hsl(0 0% 98%);\n --modal-muted: hsl(0 0% 63.9%);\n --modal-accent: hsl(217 91% 60%);\n --modal-accent-hover: hsl(217 91% 65%);\n --modal-secondary: hsl(0 0% 10%);\n --modal-secondary-hover: hsl(0 0% 15%);\n --modal-overlay: rgba(0, 0, 0, 0.5);\n }\n\n .modal-backdrop {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--modal-overlay);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n z-index: 2000000;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n overflow-y: auto;\n padding: 20px;\n opacity: 0;\n transition: opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n pointer-events: none;\n }\n\n .modal-backdrop[data-state="visible"] {\n opacity: 1;\n pointer-events: auto;\n }\n\n .modal-container {\n margin: auto;\n transform: scale(0.95) translateY(10px);\n transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n }\n\n .modal-backdrop[data-state="visible"] .modal-container {\n transform: scale(1) translateY(0);\n }\n\n .modal-content {\n background: var(--modal-bg);\n border: 1px solid var(--modal-border);\n border-radius: 16px;\n box-shadow:\n 0 25px 50px -12px rgba(0, 0, 0, 0.25),\n 0 0 0 1px rgba(255, 255, 255, 0.05);\n box-sizing: border-box;\n max-width: 480px;\n width: 100%;\n overflow-wrap: anywhere;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;\n color: var(--modal-foreground);\n }\n\n .modal-header {\n padding: 24px 24px 0 24px;\n display: flex;\n align-items: flex-start;\n gap: 16px;\n position: relative;\n }\n\n .modal-icon {\n flex-shrink: 0;\n width: 48px;\n height: 48px;\n background: var(--modal-accent);\n border-radius: 12px;\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n margin-top: 4px;\n }\n\n .modal-title {\n flex: 1;\n min-width: 0;\n font-size: 20px;\n font-weight: 600;\n line-height: 1.3;\n margin: 0;\n margin-top: 8px;\n }\n\n .modal-close {\n position: absolute;\n top: 0;\n right: 0;\n background: transparent;\n border: none;\n color: var(--modal-muted);\n cursor: pointer;\n padding: 8px;\n border-radius: 6px;\n opacity: 0.7;\n transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .modal-close:hover {\n opacity: 1;\n background: var(--modal-secondary);\n color: var(--modal-foreground);\n }\n\n .modal-body {\n padding: 24px;\n padding-top: 20px;\n }\n\n .modal-description {\n font-size: 16px;\n line-height: 1.5;\n margin: 0 0 12px 0;\n color: var(--modal-foreground);\n }\n\n .modal-subdescription {\n font-size: 14px;\n line-height: 1.4;\n margin: 0;\n color: var(--modal-muted);\n }\n\n .modal-actions {\n padding: 0 24px 24px 24px;\n display: flex;\n gap: 12px;\n justify-content: flex-end;\n }\n\n .modal-button {\n padding: 12px 20px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);\n border: 1px solid transparent;\n display: flex;\n align-items: center;\n gap: 8px;\n min-width: 100px;\n justify-content: center;\n position: relative;\n }\n\n .modal-button:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n\n .modal-button--secondary {\n background: var(--modal-secondary);\n border-color: var(--modal-border);\n color: var(--modal-foreground);\n }\n\n .modal-button--secondary:hover:not(:disabled) {\n background: var(--modal-secondary-hover);\n border-color: hsl(0 0% 25%);\n transform: translateY(-1px);\n }\n\n .modal-button--primary {\n background: var(--modal-accent);\n color: white;\n }\n\n .modal-button--primary:hover:not(:disabled) {\n background: var(--modal-accent-hover);\n transform: translateY(-1px);\n }\n\n .modal-button--primary:active:not(:disabled) {\n transform: translateY(0);\n }\n\n .button-spinner {\n display: none;\n }\n\n .button-spinner[data-state="visible"] {\n display: flex;\n }\n\n .modal-button[data-state="loading"] .button-text {\n opacity: 0;\n }\n\n .modal-button[data-state="loading"] .button-spinner {\n display: flex;\n position: absolute;\n }\n\n @media (max-width: 640px) {\n .modal-content {\n max-width: 100%;\n margin: 0 16px;\n border-radius: 12px;\n }\n\n .modal-header {\n padding: 20px 20px 0 20px;\n }\n\n .modal-body {\n padding: 20px;\n padding-top: 16px;\n }\n\n .modal-actions {\n padding: 0 20px 20px 20px;\n flex-direction: column-reverse;\n }\n\n .modal-button {\n width: 100%;\n }\n }\n .modal-container:focus { outline: none; }\n '}setupEventListeners(){const e=this.shadowRoot.querySelector(".modal-backdrop"),t=this.shadowRoot.querySelector(".modal-close"),r=this.shadowRoot.querySelector('[data-action="learn-more"]'),n=this.shadowRoot.querySelector('[data-action="create"]');e?.addEventListener("click",t=>{t.target!==e||this.isCreating||this.dismiss()}),t?.addEventListener("click",()=>{this.isCreating||this.dismiss()}),r?.addEventListener("click",()=>{window.open("https://tinycloud.xyz","_blank","noopener,noreferrer")}),n?.addEventListener("click",()=>{!this.isCreating&&n&&u(n)&&this.handleCreateSpace()}),document.addEventListener("keydown",this.handleKeyDown)}trapTab(e){if(!e.composedPath().includes(this))return;const t=this.shadowRoot,r=o(t),n=r.indexOf(t.activeElement);e.preventDefault();const i=a(r.length,n,e.shiftKey);i>=0&&r[i].focus()}async handleCreateSpace(){this.isCreating=!0;const e=this.shadowRoot.querySelector('[data-action="create"]');e.setAttribute("data-state","loading"),e.setAttribute("disabled","true");try{await this.options.onCreateSpace(),this.resolveResult?.({success:!0,dismissed:!1}),this.hide()}catch(e){console.error("[TinyCloud] Space creation failed:",e)}finally{this.isCreating=!1,e.removeAttribute("data-state"),e.removeAttribute("disabled")}}show(){this.isVisible||(this.opener=n()),this.isVisible=!0,this.releaseScrollLock||(this.releaseScrollLock=r()),this.shadowRoot.querySelector(".modal-container").focus(),requestAnimationFrame(()=>{const e=this.shadowRoot.querySelector(".modal-backdrop");e?.setAttribute("data-state","visible")})}hide(){const e=this.shadowRoot.querySelector(".modal-backdrop");e?.setAttribute("data-state","hidden"),this.restoreFocus(),setTimeout(()=>{this.remove(),this.releaseLock(),document.removeEventListener("keydown",this.handleKeyDown)},200),this.isVisible=!1}restoreFocus(){const e=this.opener;this.opener=null,c(e,this.shadowRoot)}releaseLock(){this.releaseScrollLock?.(),this.releaseScrollLock=null}dismiss(){try{this.resolveResult?.({success:!1,dismissed:!0}),this.options.onDismiss?.()}finally{this.hide()}}get isOpen(){return this.isVisible}}customElements.get("tinycloud-space-modal")||customElements.define("tinycloud-space-modal",l);class h extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const d="2.45.1";let f=({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,p=`viem@${d}`;class m extends Error{constructor(e,t={}){const r=t.cause instanceof m?t.cause.details:t.cause?.message?t.cause.message:t.details,n=t.cause instanceof m&&t.cause.docsPath||t.docsPath,i=f?.({...t,docsPath:n});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...r?[`Details: ${r}`]:[],...p?[`Version: ${p}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=n,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=d}walk(e){return g(this,e)}}function g(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?g(e.cause,t):t?null:e}class y extends m{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}function v(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}class b extends m{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function w(e,{dir:t,size:r=32}={}){return"string"==typeof e?function(e,{dir:t,size:r=32}={}){if(null===r)return e;const n=e.replace("0x","");if(n.length>2*r)throw new b({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n["right"===t?"padEnd":"padStart"](2*r,"0")}`}(e,{dir:t,size:r}):function(e,{dir:t,size:r=32}={}){if(null===r)return e;if(e.length>r)throw new b({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s="right"===t;n[s?i:r-i-1]=e[s?i:e.length-i-1]}return n}(e,{dir:t,size:r})}class E extends m{constructor({max:e,min:t,signed:r,size:n,value:i}){super(`Number "${i}" is not in safe ${n?`${8*n}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class A extends m{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function k(e){return v(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function x(e,{size:t}){if(k(e)>t)throw new A({givenSize:k(e),maxSize:t})}function _(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?s=r?(1n<<8n*BigInt(n)-1n)-1n:2n**(8n*BigInt(n))-1n:"number"==typeof e&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof s&&r?-s-1n:0;if(s&&i>s||i<o){const t="bigint"==typeof e?"n":"";throw new E({max:s?`${s}${t}`:void 0,min:`${o}${t}`,signed:r,size:n,value:`${e}${t}`})}const a=`0x${(r&&i<0?(1n<<BigInt(8*n))+BigInt(i):i).toString(16)}`;return n?w(a,{size:n}):a}const T=new TextEncoder;const S={zero:48,nine:57,A:65,F:70,a:97,f:102};function I(e){return e>=S.zero&&e<=S.nine?e-S.zero:e>=S.A&&e<=S.F?e-(S.A-10):e>=S.a&&e<=S.f?e-(S.a-10):void 0}function N(e,t={}){let r=e;t.size&&(x(r,{size:t.size}),r=w(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let e=0,t=0;e<i;e++){const r=I(n.charCodeAt(t++)),i=I(n.charCodeAt(t++));if(void 0===r||void 0===i)throw new m(`Invalid byte sequence ("${n[t-2]}${n[t-1]}" in "${n}").`);s[e]=16*r+i}return s}function R(e,t={}){const r=T.encode(e);return"number"==typeof t.size?(x(r,{size:t.size}),w(r,{dir:"right",size:t.size})):r}var O=i(113);const C=new h(8192);function P(e,t){if(C.has(`${e}.${t}`))return C.get(`${e}.${t}`);const r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),n=function(e){const t=(0,O.keccak_256)(v(e,{strict:!1})?function(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){return N(_(e,t))}(e,t):"boolean"==typeof e?function(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),"number"==typeof t.size?(x(r,{size:t.size}),w(r,{size:t.size})):r}(e,t):v(e)?N(e,t):R(e,t)}(e):e);return t}(R(r)),i=(t?r.substring(`${t}0x`.length):r).split("");for(let e=0;e<40;e+=2)n[e>>1]>>4>=8&&i[e]&&(i[e]=i[e].toUpperCase()),(15&n[e>>1])>=8&&i[e+1]&&(i[e+1]=i[e+1].toUpperCase());const s=`0x${i.join("")}`;return C.set(`${e}.${t}`,s),s}const M=/^0x[a-fA-F0-9]{40}$/,D=new h(8192);function B(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(D.has(n))return D.get(n);const i=!(!M.test(e)||e.toLowerCase()!==e&&r&&P(e)!==e);return D.set(n,i),i}var L=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function U(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function F(e){return e.slice(10,e.indexOf("/"))}function $(e){return e.slice(e.indexOf("/")+1)}function H(e){const t={};for(const r of L)F(r.urn)===e&&(t[U($(r.urn))]=r.urn);return t}var K=H("kv"),q={...H("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},j={...H("duckdb"),DESCRIBE:"tinycloud.duckdb/describe",EXECUTE:"tinycloud.duckdb/execute"},z=H("capabilities"),V=H("hooks"),G=H("encryption"),W=H("space"),J=L;["tinychat-4jq","share-2fz","tinycloud-secrets","openkey-tinycloud-demo"].map(e=>new RegExp(`^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)?${e}\\.pages\\.dev$`));var Z="applications",Y="account",Q="applications/",X="secrets",ee="default",te="public",re="agents",ne="tinycloud.encryption",ie=G.NETWORK_CREATE,se=[ee,Z,Y,X,te,re],oe={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:ee,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ee,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:ee,path:"",actions:["read","write"]}]},ae={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:Z,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Z,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:Z,path:"",actions:["read","write"]}]},ce={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:Y,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Y,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:Y,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:Y,path:"account",actions:["read","write","schema"]}]},ue={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:X,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:X,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:X,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:X,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:X,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:X,path:"",actions:["read"],skipPrefix:!0}]},le={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:te,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:te,path:"",actions:["get","list","metadata"]}]},he={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:re,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:re,path:"",actions:["get","put","del","list","metadata"]}]},de={[ee]:oe,[Z]:ae,[Y]:ce,[X]:ue,[te]:le,[re]:he};function fe(e,t=1){return function(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`Invalid EIP-155 chain ID: ${e}`)}(t),`did:pkh:eip155:${t}:${function(e){if(!B(e,{strict:!1}))throw new Error(`Invalid EVM address: ${e}`);return function(e){if(!B(e,{strict:!1}))throw new y({address:e});return P(e,void 0)}(e)}(e)}`}function pe(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function me(e,t,r){return!0===r||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function ge(e,t,r){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const r=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,n="read"===r||"get"===r?K.GET:"write"===r||"put"===r?K.PUT:"delete"===r||"del"===r?K.DEL:"list"===r?K.LIST:"metadata"===r?K.METADATA:void 0;if(void 0===n)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const i=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${i}`,actions:[n],skipPrefix:!0}})}(e).flatMap(e=>ge(e,t,r));const n=!0===e.skipPrefix||e.service===ne;return[{service:e.service,space:e.service===ne?"encryption":e.space??r,path:me(t,e.path,n),actions:e.actions.map(t=>function(e,t){return t.includes("/")?t:`${e}/${t}`}(e.service,t)),...void 0!==e.description?{description:e.description}:{}}]}function ye(e){const t=new Set(e.filter(e=>e.service!==ne).map(e=>e.space));return function(e){const t=new Map;for(const r of e){const e=`${r.service}\0${r.space}\0${r.path}`,n=t.get(e);if(n)for(const e of r.actions)n.actions.includes(e)||n.actions.push(e);else t.set(e,{...r,actions:[...r.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[z.READ]}))])}function ve(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const r=t.includeAccountRegistryPermissions??!0,n=e.map(pe),i=n.flatMap(e=>{const t=e.prefix??e.app_id,r=e.space??Z;return(e.permissions??[]).flatMap(e=>ge(e,t,r))});r&&i.push(...Ee.map(e=>({...e,actions:[...e.actions]})));const s=new Map;for(const e of n){const t=s.get(e.app_id)??[];t.push(pe(e)),s.set(e.app_id,t)}return{manifests:n,resources:ye(i),delegationTargets:[],registryRecords:r?[...s.entries()].map(([e,t])=>({key:`${Q}${e}`,app_id:e,manifests:t})):[],expiryMs:6048e5,includePublicSpace:n.some(e=>e.includePublicSpace??!0)}}([de[e]],{includeAccountRegistryPermissions:!1})}se.map(e=>({name:e,manifest:de[e],persistedAsApplication:e===X}));var be,we,Ee=Object.freeze([{service:"tinycloud.kv",space:Y,path:Q,actions:[K.GET,K.PUT,K.LIST]},{service:"tinycloud.kv",space:Y,path:"spaces/",actions:[K.GET,K.PUT,K.LIST]},{service:"tinycloud.kv",space:Y,path:"system/bootstrap/complete",actions:[K.GET,K.PUT]},{service:"tinycloud.delegation",space:Y,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:Y,path:"account",actions:[q.READ,q.WRITE,q.SCHEMA]},{service:"tinycloud.capabilities",space:Y,path:"",actions:[z.READ]}]),Ae=ve(ee),ke={...Ae,resources:[...Ae.resources,...Ee.map(e=>({...e,actions:[...e.actions]}))]},xe=Object.freeze(Object.fromEntries(se.map(e=>[e,e===ee?ke:ve(e)]))),_e=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[ie]}]);Object.freeze(se.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:xe[e].resources,...e===Y?{rawAbilities:_e}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[W.HOST]}])),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(be||(be={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(we||(we={}));const Te=be.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Se=e=>{switch(typeof e){case"undefined":return Te.undefined;case"string":return Te.string;case"number":return Number.isNaN(e)?Te.nan:Te.number;case"boolean":return Te.boolean;case"function":return Te.function;case"bigint":return Te.bigint;case"symbol":return Te.symbol;case"object":return Array.isArray(e)?Te.array:null===e?Te.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Te.promise:"undefined"!=typeof Map&&e instanceof Map?Te.map:"undefined"!=typeof Set&&e instanceof Set?Te.set:"undefined"!=typeof Date&&e instanceof Date?Te.date:Te.object;default:return Te.unknown}},Ie=be.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Ne extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(n);else if("invalid_return_type"===i.code)n(i.returnTypeError);else if("invalid_arguments"===i.code)n(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof Ne))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,be.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)if(n.path.length>0){const r=n.path[0];t[r]=t[r]||[],t[r].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Ne.create=e=>new Ne(e);const Re=(e,t)=>{let r;switch(e.code){case Ie.invalid_type:r=e.received===Te.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Ie.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,be.jsonStringifyReplacer)}`;break;case Ie.unrecognized_keys:r=`Unrecognized key(s) in object: ${be.joinValues(e.keys,", ")}`;break;case Ie.invalid_union:r="Invalid input";break;case Ie.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${be.joinValues(e.options)}`;break;case Ie.invalid_enum_value:r=`Invalid enum value. Expected ${be.joinValues(e.options)}, received '${e.received}'`;break;case Ie.invalid_arguments:r="Invalid function arguments";break;case Ie.invalid_return_type:r="Invalid function return type";break;case Ie.invalid_date:r="Invalid date";break;case Ie.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:be.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Ie.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Ie.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Ie.custom:r="Invalid input";break;case Ie.invalid_intersection_types:r="Intersection results could not be merged";break;case Ie.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Ie.not_finite:r="Number must be finite";break;default:r=t.defaultError,be.assertNever(e)}return{message:r}};let Oe=Re;function Ce(){return Oe}var Pe;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(Pe||(Pe={}));const Me=e=>{const{data:t,path:r,errorMaps:n,issueData:i}=e,s=[...r,...i.path||[]],o={...i,path:s};if(void 0!==i.message)return{...i,path:s,message:i.message};let a="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)a=e(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}};function De(e,t){const r=Ce(),n=Me({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Re?void 0:Re].filter(e=>!!e)});e.common.issues.push(n)}class Be{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return Le;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return Be.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:i}=n;if("aborted"===t.status)return Le;if("aborted"===i.status)return Le;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!n.alwaysSet||(r[t.value]=i.value)}return{status:e.value,value:r}}}const Le=Object.freeze({status:"aborted"}),Ue=e=>({status:"dirty",value:e}),Fe=e=>({status:"valid",value:e}),$e=e=>"aborted"===e.status,He=e=>"dirty"===e.status,Ke=e=>"valid"===e.status,qe=e=>"undefined"!=typeof Promise&&e instanceof Promise;class je{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ze=(e,t)=>{if(Ke(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Ne(e.common.issues);return this._error=t,this._error}}};function Ve(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??i.defaultError}:void 0===i.data?{message:s??n??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:s??r??i.defaultError}},description:i}}class Ge{get description(){return this._def.description}_getType(e){return Se(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Be,ctx:{common:e.parent.common,data:e.data,parsedType:Se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(qe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Se(e)},n=this._parseSync({data:e,path:r.path,parent:r});return ze(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Se(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Ke(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Ke(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Se(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(qe(n)?n:Promise.resolve(n));return ze(r,i)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const i=e(t),s=()=>n.addIssue({code:Ie.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(s(),!1)):!!i||(s(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new Jt({schema:this,typeName:or.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Zt.create(this,this._def)}nullable(){return Yt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Rt.create(this)}promise(){return Wt.create(this,this._def)}or(e){return Pt.create([this,e],this._def)}and(e){return Lt.create(this,e,this._def)}transform(e){return new Jt({...Ve(this._def),schema:this,typeName:or.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Qt({...Ve(this._def),innerType:this,defaultValue:t,typeName:or.ZodDefault})}brand(){return new tr({typeName:or.ZodBranded,type:this,...Ve(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Xt({...Ve(this._def),innerType:this,catchValue:t,typeName:or.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return rr.create(this,e)}readonly(){return nr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const We=/^c[^\s-]{8,}$/i,Je=/^[0-9a-z]+$/,Ze=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ye=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Qe=/^[a-z0-9_-]{21}$/i,Xe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,et=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,tt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let rt;const nt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,it=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,st=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ot=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,at=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ct=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ut="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",lt=new RegExp(`^${ut}$`);function ht(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function dt(e){return new RegExp(`^${ht(e)}$`)}function ft(e){let t=`${ut}T${ht(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function pt(e,t){return!("v4"!==t&&t||!nt.test(e))||!("v6"!==t&&t||!st.test(e))}function mt(e,t){if(!Xe.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!("object"!=typeof i||null===i||"typ"in i&&"JWT"!==i?.typ||!i.alg||t&&i.alg!==t)}catch{return!1}}function gt(e,t){return!("v4"!==t&&t||!it.test(e))||!("v6"!==t&&t||!ot.test(e))}class yt extends Ge{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Te.string){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.string,received:t.parsedType}),Le}const t=new Be;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const i=e.data.length>n.value,s=e.data.length<n.value;(i||s)&&(r=this._getOrReturnCtx(e,r),i?De(r,{code:Ie.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):s&&De(r,{code:Ie.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)tt.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"email",code:Ie.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)rt||(rt=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),rt.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"emoji",code:Ie.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)Ye.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"uuid",code:Ie.invalid_string,message:n.message}),t.dirty());else if("nanoid"===n.kind)Qe.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"nanoid",code:Ie.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)We.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"cuid",code:Ie.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)Je.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"cuid2",code:Ie.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)Ze.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"ulid",code:Ie.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),De(r,{validation:"url",code:Ie.invalid_string,message:n.message}),t.dirty()}else"regex"===n.kind?(n.regex.lastIndex=0,n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"regex",code:Ie.invalid_string,message:n.message}),t.dirty())):"trim"===n.kind?e.data=e.data.trim():"includes"===n.kind?e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty()):"toLowerCase"===n.kind?e.data=e.data.toLowerCase():"toUpperCase"===n.kind?e.data=e.data.toUpperCase():"startsWith"===n.kind?e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty()):"endsWith"===n.kind?e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty()):"datetime"===n.kind?ft(n).test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.invalid_string,validation:"datetime",message:n.message}),t.dirty()):"date"===n.kind?lt.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.invalid_string,validation:"date",message:n.message}),t.dirty()):"time"===n.kind?dt(n).test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.invalid_string,validation:"time",message:n.message}),t.dirty()):"duration"===n.kind?et.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"duration",code:Ie.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?pt(e.data,n.version)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"ip",code:Ie.invalid_string,message:n.message}),t.dirty()):"jwt"===n.kind?mt(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"jwt",code:Ie.invalid_string,message:n.message}),t.dirty()):"cidr"===n.kind?gt(e.data,n.version)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"cidr",code:Ie.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?at.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"base64",code:Ie.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?ct.test(e.data)||(r=this._getOrReturnCtx(e,r),De(r,{validation:"base64url",code:Ie.invalid_string,message:n.message}),t.dirty()):be.assertNever(n);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Ie.invalid_string,...Pe.errToObj(r)})}_addCheck(e){return new yt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Pe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Pe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Pe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Pe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Pe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Pe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Pe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Pe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Pe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Pe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Pe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Pe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Pe.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Pe.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Pe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Pe.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Pe.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Pe.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Pe.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Pe.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Pe.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Pe.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Pe.errToObj(t)})}nonempty(e){return this.min(1,Pe.errToObj(e))}trim(){return new yt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function vt(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}yt.create=e=>new yt({checks:[],typeName:or.ZodString,coerce:e?.coerce??!1,...Ve(e)});class bt extends Ge{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Te.number){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.number,received:t.parsedType}),Le}let t;const r=new Be;for(const n of this._def.checks)"int"===n.kind?be.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),De(t,{code:Ie.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),De(t,{code:Ie.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),De(t,{code:Ie.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"multipleOf"===n.kind?0!==vt(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),De(t,{code:Ie.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),De(t,{code:Ie.not_finite,message:n.message}),r.dirty()):be.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Pe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Pe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Pe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Pe.toString(t))}setLimit(e,t,r,n){return new bt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Pe.toString(n)}]})}_addCheck(e){return new bt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Pe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Pe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Pe.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Pe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Pe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Pe.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&be.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}bt.create=e=>new bt({checks:[],typeName:or.ZodNumber,coerce:e?.coerce||!1,...Ve(e)});class wt extends Ge{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Te.bigint)return this._getInvalidInput(e);let t;const r=new Be;for(const n of this._def.checks)"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),De(t,{code:Ie.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),De(t,{code:Ie.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),De(t,{code:Ie.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):be.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.bigint,received:t.parsedType}),Le}gte(e,t){return this.setLimit("min",e,!0,Pe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Pe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Pe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Pe.toString(t))}setLimit(e,t,r,n){return new wt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Pe.toString(n)}]})}_addCheck(e){return new wt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Pe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Pe.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}wt.create=e=>new wt({checks:[],typeName:or.ZodBigInt,coerce:e?.coerce??!1,...Ve(e)});class Et extends Ge{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==Te.boolean){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.boolean,received:t.parsedType}),Le}return Fe(e.data)}}Et.create=e=>new Et({typeName:or.ZodBoolean,coerce:e?.coerce||!1,...Ve(e)});class At extends Ge{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Te.date){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.date,received:t.parsedType}),Le}if(Number.isNaN(e.data.getTime()))return De(this._getOrReturnCtx(e),{code:Ie.invalid_date}),Le;const t=new Be;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),De(r,{code:Ie.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):be.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new At({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Pe.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Pe.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}At.create=e=>new At({checks:[],coerce:e?.coerce||!1,typeName:or.ZodDate,...Ve(e)});class kt extends Ge{_parse(e){if(this._getType(e)!==Te.symbol){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.symbol,received:t.parsedType}),Le}return Fe(e.data)}}kt.create=e=>new kt({typeName:or.ZodSymbol,...Ve(e)});class xt extends Ge{_parse(e){if(this._getType(e)!==Te.undefined){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.undefined,received:t.parsedType}),Le}return Fe(e.data)}}xt.create=e=>new xt({typeName:or.ZodUndefined,...Ve(e)});class _t extends Ge{_parse(e){if(this._getType(e)!==Te.null){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.null,received:t.parsedType}),Le}return Fe(e.data)}}_t.create=e=>new _t({typeName:or.ZodNull,...Ve(e)});class Tt extends Ge{constructor(){super(...arguments),this._any=!0}_parse(e){return Fe(e.data)}}Tt.create=e=>new Tt({typeName:or.ZodAny,...Ve(e)});class St extends Ge{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Fe(e.data)}}St.create=e=>new St({typeName:or.ZodUnknown,...Ve(e)});class It extends Ge{_parse(e){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.never,received:t.parsedType}),Le}}It.create=e=>new It({typeName:or.ZodNever,...Ve(e)});class Nt extends Ge{_parse(e){if(this._getType(e)!==Te.undefined){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.void,received:t.parsedType}),Le}return Fe(e.data)}}Nt.create=e=>new Nt({typeName:or.ZodVoid,...Ve(e)});class Rt extends Ge{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==Te.array)return De(t,{code:Ie.invalid_type,expected:Te.array,received:t.parsedType}),Le;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,i=t.data.length<n.exactLength.value;(e||i)&&(De(t,{code:e?Ie.too_big:Ie.too_small,minimum:i?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(De(t,{code:Ie.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(De(t,{code:Ie.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new je(t,e,t.path,r)))).then(e=>Be.mergeArray(r,e));const i=[...t.data].map((e,r)=>n.type._parseSync(new je(t,e,t.path,r)));return Be.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new Rt({...this._def,minLength:{value:e,message:Pe.toString(t)}})}max(e,t){return new Rt({...this._def,maxLength:{value:e,message:Pe.toString(t)}})}length(e,t){return new Rt({...this._def,exactLength:{value:e,message:Pe.toString(t)}})}nonempty(e){return this.min(1,e)}}function Ot(e){if(e instanceof Ct){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Zt.create(Ot(n))}return new Ct({...e._def,shape:()=>t})}return e instanceof Rt?new Rt({...e._def,type:Ot(e.element)}):e instanceof Zt?Zt.create(Ot(e.unwrap())):e instanceof Yt?Yt.create(Ot(e.unwrap())):e instanceof Ut?Ut.create(e.items.map(e=>Ot(e))):e}Rt.create=(e,t)=>new Rt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:or.ZodArray,...Ve(t)});class Ct extends Ge{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=be.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Te.object){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.object,received:t.parsedType}),Le}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof It&&"strip"===this._def.unknownKeys))for(const e in r.data)i.includes(e)||s.push(e);const o=[];for(const e of i){const t=n[e],i=r.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new je(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof It){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)s.length>0&&(De(r,{code:Ie.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const n=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new je(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>Be.mergeObjectSync(t,e)):Be.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return Pe.errToObj,new Ct({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:Pe.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new Ct({...this._def,unknownKeys:"strip"})}passthrough(){return new Ct({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ct({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ct({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:or.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ct({...this._def,catchall:e})}pick(e){const t={};for(const r of be.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Ct({...this._def,shape:()=>t})}omit(e){const t={};for(const r of be.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Ct({...this._def,shape:()=>t})}deepPartial(){return Ot(this)}partial(e){const t={};for(const r of be.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new Ct({...this._def,shape:()=>t})}required(e){const t={};for(const r of be.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Zt;)e=e._def.innerType;t[r]=e}return new Ct({...this._def,shape:()=>t})}keyof(){return zt(be.objectKeys(this.shape))}}Ct.create=(e,t)=>new Ct({shape:()=>e,unknownKeys:"strip",catchall:It.create(),typeName:or.ZodObject,...Ve(t)}),Ct.strictCreate=(e,t)=>new Ct({shape:()=>e,unknownKeys:"strict",catchall:It.create(),typeName:or.ZodObject,...Ve(t)}),Ct.lazycreate=(e,t)=>new Ct({shape:e,unknownKeys:"strip",catchall:It.create(),typeName:or.ZodObject,...Ve(t)});class Pt extends Ge{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new Ne(e.ctx.common.issues));return De(t,{code:Ie.invalid_union,unionErrors:r}),Le});{let e;const n=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},s=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=n.map(e=>new Ne(e));return De(t,{code:Ie.invalid_union,unionErrors:i}),Le}}get options(){return this._def.options}}Pt.create=(e,t)=>new Pt({options:e,typeName:or.ZodUnion,...Ve(t)});const Mt=e=>e instanceof qt?Mt(e.schema):e instanceof Jt?Mt(e.innerType()):e instanceof jt?[e.value]:e instanceof Vt?e.options:e instanceof Gt?be.objectValues(e.enum):e instanceof Qt?Mt(e._def.innerType):e instanceof xt?[void 0]:e instanceof _t?[null]:e instanceof Zt?[void 0,...Mt(e.unwrap())]:e instanceof Yt?[null,...Mt(e.unwrap())]:e instanceof tr||e instanceof nr?Mt(e.unwrap()):e instanceof Xt?Mt(e._def.innerType):[];class Dt extends Ge{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Te.object)return De(t,{code:Ie.invalid_type,expected:Te.object,received:t.parsedType}),Le;const r=this.discriminator,n=t.data[r],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(De(t,{code:Ie.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Le)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=Mt(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of t){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,r)}}return new Dt({typeName:or.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...Ve(r)})}}function Bt(e,t){const r=Se(e),n=Se(t);if(e===t)return{valid:!0,data:e};if(r===Te.object&&n===Te.object){const r=be.objectKeys(t),n=be.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of n){const n=Bt(e[r],t[r]);if(!n.valid)return{valid:!1};i[r]=n.data}return{valid:!0,data:i}}if(r===Te.array&&n===Te.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const i=Bt(e[n],t[n]);if(!i.valid)return{valid:!1};r.push(i.data)}return{valid:!0,data:r}}return r===Te.date&&n===Te.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class Lt extends Ge{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if($e(e)||$e(n))return Le;const i=Bt(e.value,n.value);return i.valid?((He(e)||He(n))&&t.dirty(),{status:t.value,value:i.data}):(De(r,{code:Ie.invalid_intersection_types}),Le)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Lt.create=(e,t,r)=>new Lt({left:e,right:t,typeName:or.ZodIntersection,...Ve(r)});class Ut extends Ge{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.array)return De(r,{code:Ie.invalid_type,expected:Te.array,received:r.parsedType}),Le;if(r.data.length<this._def.items.length)return De(r,{code:Ie.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Le;!this._def.rest&&r.data.length>this._def.items.length&&(De(r,{code:Ie.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new je(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>Be.mergeArray(t,e)):Be.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new Ut({...this._def,rest:e})}}Ut.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ut({items:e,typeName:or.ZodTuple,rest:null,...Ve(t)})};class Ft extends Ge{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.object)return De(r,{code:Ie.invalid_type,expected:Te.object,received:r.parsedType}),Le;const n=[],i=this._def.keyType,s=this._def.valueType;for(const e in r.data)n.push({key:i._parse(new je(r,e,r.path,e)),value:s._parse(new je(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?Be.mergeObjectAsync(t,n):Be.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new Ft(t instanceof Ge?{keyType:e,valueType:t,typeName:or.ZodRecord,...Ve(r)}:{keyType:yt.create(),valueType:e,typeName:or.ZodRecord,...Ve(t)})}}class $t extends Ge{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.map)return De(r,{code:Ie.invalid_type,expected:Te.map,received:r.parsedType}),Le;const n=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([e,t],s)=>({key:n._parse(new je(r,e,r.path,[s,"key"])),value:i._parse(new je(r,t,r.path,[s,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of s){const n=await r.key,i=await r.value;if("aborted"===n.status||"aborted"===i.status)return Le;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of s){const n=r.key,i=r.value;if("aborted"===n.status||"aborted"===i.status)return Le;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}}}}$t.create=(e,t,r)=>new $t({valueType:t,keyType:e,typeName:or.ZodMap,...Ve(r)});class Ht extends Ge{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.set)return De(r,{code:Ie.invalid_type,expected:Te.set,received:r.parsedType}),Le;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(De(r,{code:Ie.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(De(r,{code:Ie.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const i=this._def.valueType;function s(e){const r=new Set;for(const n of e){if("aborted"===n.status)return Le;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>i._parse(new je(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>s(e)):s(o)}min(e,t){return new Ht({...this._def,minSize:{value:e,message:Pe.toString(t)}})}max(e,t){return new Ht({...this._def,maxSize:{value:e,message:Pe.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ht.create=(e,t)=>new Ht({valueType:e,minSize:null,maxSize:null,typeName:or.ZodSet,...Ve(t)});class Kt extends Ge{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Te.function)return De(t,{code:Ie.invalid_type,expected:Te.function,received:t.parsedType}),Le;function r(e,r){return Me({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ce(),Re].filter(e=>!!e),issueData:{code:Ie.invalid_arguments,argumentsError:r}})}function n(e,r){return Me({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ce(),Re].filter(e=>!!e),issueData:{code:Ie.invalid_return_type,returnTypeError:r}})}const i={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof Wt){const e=this;return Fe(async function(...t){const o=new Ne([]),a=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(r(t,e)),o}),c=await Reflect.apply(s,this,a);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(n(c,e)),o})})}{const e=this;return Fe(function(...t){const o=e._def.args.safeParse(t,i);if(!o.success)throw new Ne([r(t,o.error)]);const a=Reflect.apply(s,this,o.data),c=e._def.returns.safeParse(a,i);if(!c.success)throw new Ne([n(a,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Kt({...this._def,args:Ut.create(e).rest(St.create())})}returns(e){return new Kt({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new Kt({args:e||Ut.create([]).rest(St.create()),returns:t||St.create(),typeName:or.ZodFunction,...Ve(r)})}}class qt extends Ge{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}qt.create=(e,t)=>new qt({getter:e,typeName:or.ZodLazy,...Ve(t)});class jt extends Ge{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return De(t,{received:t.data,code:Ie.invalid_literal,expected:this._def.value}),Le}return{status:"valid",value:e.data}}get value(){return this._def.value}}function zt(e,t){return new Vt({values:e,typeName:or.ZodEnum,...Ve(t)})}jt.create=(e,t)=>new jt({value:e,typeName:or.ZodLiteral,...Ve(t)});class Vt extends Ge{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return De(t,{expected:be.joinValues(r),received:t.parsedType,code:Ie.invalid_type}),Le}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return De(t,{received:t.data,code:Ie.invalid_enum_value,options:r}),Le}return Fe(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Vt.create(e,{...this._def,...t})}exclude(e,t=this._def){return Vt.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Vt.create=zt;class Gt extends Ge{_parse(e){const t=be.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Te.string&&r.parsedType!==Te.number){const e=be.objectValues(t);return De(r,{expected:be.joinValues(e),received:r.parsedType,code:Ie.invalid_type}),Le}if(this._cache||(this._cache=new Set(be.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=be.objectValues(t);return De(r,{received:r.data,code:Ie.invalid_enum_value,options:e}),Le}return Fe(e.data)}get enum(){return this._def.values}}Gt.create=(e,t)=>new Gt({values:e,typeName:or.ZodNativeEnum,...Ve(t)});class Wt extends Ge{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Te.promise&&!1===t.common.async)return De(t,{code:Ie.invalid_type,expected:Te.promise,received:t.parsedType}),Le;const r=t.parsedType===Te.promise?t.data:Promise.resolve(t.data);return Fe(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Wt.create=(e,t)=>new Wt({type:e,typeName:or.ZodPromise,...Ve(t)});class Jt extends Ge{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===or.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:e=>{De(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return Le;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?Le:"dirty"===n.status||"dirty"===t.value?Ue(n.value):n});{if("aborted"===t.value)return Le;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?Le:"dirty"===n.status||"dirty"===t.value?Ue(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?Le:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?Le:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ke(e))return Le;const s=n.transform(e.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>Ke(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:t.value,value:e})):Le)}be.assertNever(n)}}Jt.create=(e,t,r)=>new Jt({schema:e,typeName:or.ZodEffects,effect:t,...Ve(r)}),Jt.createWithPreprocess=(e,t,r)=>new Jt({schema:t,effect:{type:"preprocess",transform:e},typeName:or.ZodEffects,...Ve(r)});class Zt extends Ge{_parse(e){return this._getType(e)===Te.undefined?Fe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Zt.create=(e,t)=>new Zt({innerType:e,typeName:or.ZodOptional,...Ve(t)});class Yt extends Ge{_parse(e){return this._getType(e)===Te.null?Fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Yt.create=(e,t)=>new Yt({innerType:e,typeName:or.ZodNullable,...Ve(t)});class Qt extends Ge{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===Te.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Qt.create=(e,t)=>new Qt({innerType:e,typeName:or.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Ve(t)});class Xt extends Ge{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return qe(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Ne(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new Ne(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Xt.create=(e,t)=>new Xt({innerType:e,typeName:or.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Ve(t)});class er extends Ge{_parse(e){if(this._getType(e)!==Te.nan){const t=this._getOrReturnCtx(e);return De(t,{code:Ie.invalid_type,expected:Te.nan,received:t.parsedType}),Le}return{status:"valid",value:e.data}}}er.create=e=>new er({typeName:or.ZodNaN,...Ve(e)}),Symbol("zod_brand");class tr extends Ge{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class rr extends Ge{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?Le:"dirty"===e.status?(t.dirty(),Ue(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?Le:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new rr({in:e,out:t,typeName:or.ZodPipeline})}}class nr extends Ge{_parse(e){const t=this._def.innerType._parse(e),r=e=>(Ke(e)&&(e.value=Object.freeze(e.value)),e);return qe(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function ir(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function sr(e,t={},r){return e?Tt.create().superRefine((n,i)=>{const s=e(n);if(s instanceof Promise)return s.then(e=>{if(!e){const e=ir(t,n),s=e.fatal??r??!0;i.addIssue({code:"custom",...e,fatal:s})}});if(!s){const e=ir(t,n),s=e.fatal??r??!0;i.addIssue({code:"custom",...e,fatal:s})}}):Tt.create()}var or;nr.create=(e,t)=>new nr({innerType:e,typeName:or.ZodReadonly,...Ve(t)}),Ct.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(or||(or={}));const ar=yt.create,cr=bt.create,ur=(er.create,wt.create,Et.create),lr=At.create,hr=(kt.create,xt.create,_t.create),dr=(Tt.create,St.create),fr=(It.create,Nt.create,Rt.create),pr=Ct.create,mr=(Ct.strictCreate,Pt.create),gr=Dt.create,yr=(Lt.create,Ut.create),vr=Ft.create,br=($t.create,Ht.create,Kt.create),wr=qt.create,Er=jt.create,Ar=Vt.create,kr=(Gt.create,Wt.create,Jt.create,Zt.create,Yt.create,Jt.createWithPreprocess,rr.create,e=>At.create({...e,coerce:!0}));function xr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function _r(e,...t){if(!xr(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Tr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Sr(e,t){_r(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Ir(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Nr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Rr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}i(427);const Or=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Cr(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!xr(e))throw new Error("Uint8Array expected, got "+typeof e);e=Br(e)}return e}const Pr=(e,t)=>{function r(r,...n){if(_r(r),!Or)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?_r(t):_r(t,e.nonceLength)}const i=e.tagLength;i&&void 0!==n[1]&&_r(n[1]);const s=t(r,...n),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");_r(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,_r(e),o(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(_r(e),i&&e.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return o(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(r,e),r};function Mr(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+u,a,n)}function Dr(e){return e.byteOffset%4==0}function Br(e){return Uint8Array.from(e)}const Lr=16,Ur=new Uint8Array(16),Fr=Ir(Ur),$r=(e,t,r,n)=>({s3:r<<31|n>>>1,s2:t<<31|r>>>1,s1:e<<31|t>>>1,s0:e>>>1^225<<24&-(1&n)}),Hr=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Kr{constructor(e,t){this.blockLen=Lr,this.outputLen=Lr,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,_r(e=Cr(e),16);const r=Rr(e);let n=r.getUint32(0,!1),i=r.getUint32(4,!1),s=r.getUint32(8,!1),o=r.getUint32(12,!1);const a=[];for(let e=0;e<128;e++)a.push({s0:Hr(n),s1:Hr(i),s2:Hr(s),s3:Hr(o)}),({s0:n,s1:i,s2:s,s3:o}=$r(n,i,s,o));const c=(u=t||1024)>65536?8:u>1024?4:2;var u;if(![1,2,4,8].includes(c))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=c;const l=128/c,h=this.windowSize=2**c,d=[];for(let e=0;e<l;e++)for(let t=0;t<h;t++){let r=0,n=0,i=0,s=0;for(let o=0;o<c;o++){if(!(t>>>c-o-1&1))continue;const{s0:u,s1:l,s2:h,s3:d}=a[c*e+o];r^=u,n^=l,i^=h,s^=d}d.push({s0:r,s1:n,s2:i,s3:s})}this.t=d}_updateBlock(e,t,r,n){e^=this.s0,t^=this.s1,r^=this.s2,n^=this.s3;const{W:i,t:s,windowSize:o}=this;let a=0,c=0,u=0,l=0;const h=(1<<i)-1;let d=0;for(const f of[e,t,r,n])for(let e=0;e<4;e++){const t=f>>>8*e&255;for(let e=8/i-1;e>=0;e--){const r=t>>>i*e&h,{s0:n,s1:f,s2:p,s3:m}=s[d*o+r];a^=n,c^=f,u^=p,l^=m,d+=1}}this.s0=a,this.s1=c,this.s2=u,this.s3=l}update(e){Tr(this),_r(e=Cr(e));const t=Ir(e),r=Math.floor(e.length/Lr),n=e.length%Lr;for(let e=0;e<r;e++)this._updateBlock(t[4*e+0],t[4*e+1],t[4*e+2],t[4*e+3]);return n&&(Ur.set(e.subarray(r*Lr)),this._updateBlock(Fr[0],Fr[1],Fr[2],Fr[3]),Nr(Fr)),this}destroy(){const{t:e}=this;for(const t of e)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(e){Tr(this),Sr(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:i}=this,s=Ir(e);return s[0]=t,s[1]=r,s[2]=n,s[3]=i,e}digest(){const e=new Uint8Array(Lr);return this.digestInto(e),this.destroy(),e}}class qr extends Kr{constructor(e,t){_r(e=Cr(e));const r=function(e){e.reverse();const t=1&e[15];let r=0;for(let t=0;t<e.length;t++){const n=e[t];e[t]=n>>>1|r,r=(1&n)<<7}return e[0]^=225&-t,e}(Br(e));super(r,t),Nr(r)}update(e){e=Cr(e),Tr(this);const t=Ir(e),r=e.length%Lr,n=Math.floor(e.length/Lr);for(let e=0;e<n;e++)this._updateBlock(Hr(t[4*e+3]),Hr(t[4*e+2]),Hr(t[4*e+1]),Hr(t[4*e+0]));return r&&(Ur.set(e.subarray(n*Lr)),this._updateBlock(Hr(Fr[3]),Hr(Fr[2]),Hr(Fr[1]),Hr(Fr[0])),Nr(Fr)),this}digestInto(e){Tr(this),Sr(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:i}=this,s=Ir(e);return s[0]=t,s[1]=r,s[2]=n,s[3]=i,e.reverse()}}function jr(e){const t=(t,r)=>e(r,t.length).update(Cr(t)).digest(),r=e(new Uint8Array(16),0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(t,r)=>e(t,r),t}const zr=jr((e,t)=>new Kr(e,t)),Vr=(jr((e,t)=>new qr(e,t)),16),Gr=new Uint8Array(Vr);function Wr(e){return e<<1^283&-(e>>7)}function Jr(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=Wr(e);return r}const Zr=e=>e<<24|e>>>8,Yr=e=>e<<8|e>>>24;function Qr(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const r=new Uint32Array(256).map((r,n)=>t(e[n])),n=r.map(Yr),i=n.map(Yr),s=i.map(Yr),o=new Uint32Array(65536),a=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let u=0;u<256;u++){const l=256*t+u;o[l]=r[t]^n[u],a[l]=i[t]^s[u],c[l]=e[t]<<8|e[u]}return{sbox:e,sbox2:c,T0:r,T1:n,T2:i,T3:s,T01:o,T23:a}}const Xr=Qr((()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=Wr(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=255&(n^n>>4^n>>5^n>>6^n>>7^99)}return Nr(e),t})(),e=>Jr(e,3)<<24|e<<16|e<<8|Jr(e,2)),en=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=Wr(r))e[t]=r;return e})();function tn(e,t,r,n,i,s){return e[r<<8&65280|n>>>8&255]^t[i>>>8&65280|s>>>24&255]}function rn(e,t,r,n,i){return e[255&t|65280&r]|e[n>>>16&255|i>>>16&65280]<<16}function nn(e,t,r,n,i){const{sbox2:s,T01:o,T23:a}=Xr;let c=0;t^=e[c++],r^=e[c++],n^=e[c++],i^=e[c++];const u=e.length/4-2;for(let s=0;s<u;s++){const s=e[c++]^tn(o,a,t,r,n,i),u=e[c++]^tn(o,a,r,n,i,t),l=e[c++]^tn(o,a,n,i,t,r),h=e[c++]^tn(o,a,i,t,r,n);t=s,r=u,n=l,i=h}return{s0:e[c++]^rn(s,t,r,n,i),s1:e[c++]^rn(s,r,n,i,t),s2:e[c++]^rn(s,n,i,t,r),s3:e[c++]^rn(s,i,t,r,n)}}function sn(e,t,r,n,i){_r(r,Vr),_r(n),i=function(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!Dr(t))throw new Error("invalid output, must be aligned");return t}(n.length,i);const s=r,o=Ir(s),a=Rr(s),c=Ir(n),u=Ir(i),l=t?0:12,h=n.length;let d=a.getUint32(l,t),{s0:f,s1:p,s2:m,s3:g}=nn(e,o[0],o[1],o[2],o[3]);for(let r=0;r+4<=c.length;r+=4)u[r+0]=c[r+0]^f,u[r+1]=c[r+1]^p,u[r+2]=c[r+2]^m,u[r+3]=c[r+3]^g,d=d+1>>>0,a.setUint32(l,d,t),({s0:f,s1:p,s2:m,s3:g}=nn(e,o[0],o[1],o[2],o[3]));const y=Vr*Math.floor(c.length/4);if(y<h){const e=new Uint32Array([f,p,m,g]),t=(v=e,new Uint8Array(v.buffer,v.byteOffset,v.byteLength));for(let e=y,r=0;e<h;e++,r++)i[e]=n[e]^t[r];Nr(e)}var v;return i}function on(e,t,r,n,i){const s=i?i.length:0,o=e.create(r,n.length+s);i&&o.update(i);const a=function(e,t,r){!function(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}(r);const n=new Uint8Array(16),i=Rr(n);return Mr(i,0,BigInt(t),r),Mr(i,8,BigInt(e),r),n}(8*n.length,8*s,t);o.update(n),o.update(a);const c=o.digest();return Nr(a),c}const an=Pr({blockSize:16,nonceLength:12,tagLength:16,varSizeNonce:!0},function(e,t,r){if(t.length<8)throw new Error("aes/gcm: invalid nonce length");function n(e,t,n){const i=on(zr,!1,e,n,r);for(let e=0;e<t.length;e++)i[e]^=t[e];return i}function i(){const r=function(e){_r(e);const t=e.length;if(![16,24,32].includes(t))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+t);const{sbox2:r}=Xr,n=[];Dr(e)||n.push(e=Br(e));const i=Ir(e),s=i.length,o=e=>rn(r,e,e,e,e),a=new Uint32Array(t+28);a.set(i);for(let e=s;e<a.length;e++){let t=a[e-1];e%s===0?t=o(Zr(t))^en[e/s-1]:s>6&&e%s===4&&(t=o(t)),a[e]=a[e-s]^t}return Nr(...n),a}(e),n=Gr.slice(),i=Gr.slice();if(sn(r,!1,i,i,n),12===t.length)i.set(t);else{const e=Gr.slice();Mr(Rr(e),8,BigInt(8*t.length),!1);const r=zr.create(n).update(t).update(e);r.digestInto(i),r.destroy()}return{xk:r,authKey:n,counter:i,tagMask:sn(r,!1,i,Gr)}}return{encrypt(e){const{xk:t,authKey:r,counter:s,tagMask:o}=i(),a=new Uint8Array(e.length+16),c=[t,r,s,o];Dr(e)||c.push(e=Br(e)),sn(t,!1,s,e,a.subarray(0,e.length));const u=n(r,o,a.subarray(0,a.length-16));return c.push(u),a.set(u,e.length),Nr(...c),a},decrypt(e){const{xk:t,authKey:r,counter:s,tagMask:o}=i(),a=[t,r,o,s];Dr(e)||a.push(e=Br(e));const c=e.subarray(0,-16),u=e.subarray(-16),l=n(r,o,c);if(a.push(l),!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(l,u))throw new Error("aes/gcm: invalid ghash tag");const h=sn(t,!1,s,c);return Nr(...a),h}}});var cn=i(7997);function un(e,t,r){return e&t^~e&r}function ln(e,t,r){return e&t^e&r^t&r}class hn extends cn.Hash{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=(0,cn.createView)(this.buffer)}update(e){(0,cn.aexists)(this),e=(0,cn.toBytes)(e),(0,cn.abytes)(e);const{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);if(o===n){const t=(0,cn.createView)(e);for(;n<=i-s;s+=n)this.process(t,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){(0,cn.aexists)(this),(0,cn.aoutput)(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:i}=this;let{pos:s}=this;t[s++]=128,(0,cn.clean)(this.buffer.subarray(s)),this.padOffset>n-s&&(this.process(r,0),s=0);for(let e=s;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+u,a,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const o=(0,cn.createView)(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,u[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:i,destroyed:s,pos:o}=this;return e.destroyed=s,e.finished=i,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const dn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),fn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var pn=i(9964);const mn=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),gn=new Uint32Array(64);class yn extends hn{constructor(e=32){super(64,e,8,!1),this.A=0|dn[0],this.B=0|dn[1],this.C=0|dn[2],this.D=0|dn[3],this.E=0|dn[4],this.F=0|dn[5],this.G=0|dn[6],this.H=0|dn[7]}get(){const{A:e,B:t,C:r,D:n,E:i,F:s,G:o,H:a}=this;return[e,t,r,n,i,s,o,a]}set(e,t,r,n,i,s,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)gn[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=gn[e-15],r=gn[e-2],n=(0,cn.rotr)(t,7)^(0,cn.rotr)(t,18)^t>>>3,i=(0,cn.rotr)(r,17)^(0,cn.rotr)(r,19)^r>>>10;gn[e]=i+gn[e-7]+n+gn[e-16]|0}let{A:r,B:n,C:i,D:s,E:o,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+((0,cn.rotr)(o,6)^(0,cn.rotr)(o,11)^(0,cn.rotr)(o,25))+un(o,a,c)+mn[e]+gn[e]|0,l=((0,cn.rotr)(r,2)^(0,cn.rotr)(r,13)^(0,cn.rotr)(r,22))+ln(r,n,i)|0;u=c,c=a,a=o,o=s+t|0,s=i,i=n,n=r,r=t+l|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,s,o,a,c,u)}roundClean(){(0,cn.clean)(gn)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,cn.clean)(this.buffer)}}const vn=(()=>pn.lD(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),bn=(()=>vn[0])(),wn=(()=>vn[1])(),En=new Uint32Array(80),An=new Uint32Array(80);class kn extends hn{constructor(e=64){super(128,e,16,!1),this.Ah=0|fn[0],this.Al=0|fn[1],this.Bh=0|fn[2],this.Bl=0|fn[3],this.Ch=0|fn[4],this.Cl=0|fn[5],this.Dh=0|fn[6],this.Dl=0|fn[7],this.Eh=0|fn[8],this.El=0|fn[9],this.Fh=0|fn[10],this.Fl=0|fn[11],this.Gh=0|fn[12],this.Gl=0|fn[13],this.Hh=0|fn[14],this.Hl=0|fn[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:s,Dh:o,Dl:a,Eh:c,El:u,Fh:l,Fl:h,Gh:d,Gl:f,Hh:p,Hl:m}=this;return[e,t,r,n,i,s,o,a,c,u,l,h,d,f,p,m]}set(e,t,r,n,i,s,o,a,c,u,l,h,d,f,p,m){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|h,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|m}process(e,t){for(let r=0;r<16;r++,t+=4)En[r]=e.getUint32(t),An[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|En[e-15],r=0|An[e-15],n=pn.rE(t,r,1)^pn.rE(t,r,8)^pn.xn(t,r,7),i=pn.ry(t,r,1)^pn.ry(t,r,8)^pn.jm(t,r,7),s=0|En[e-2],o=0|An[e-2],a=pn.rE(s,o,19)^pn.qh(s,o,61)^pn.xn(s,o,6),c=pn.ry(s,o,19)^pn.Ei(s,o,61)^pn.jm(s,o,6),u=pn.CW(i,c,An[e-7],An[e-16]),l=pn.CQ(u,n,a,En[e-7],En[e-16]);En[e]=0|l,An[e]=0|u}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:o,Cl:a,Dh:c,Dl:u,Eh:l,El:h,Fh:d,Fl:f,Gh:p,Gl:m,Hh:g,Hl:y}=this;for(let e=0;e<80;e++){const t=pn.rE(l,h,14)^pn.rE(l,h,18)^pn.qh(l,h,41),v=pn.ry(l,h,14)^pn.ry(l,h,18)^pn.Ei(l,h,41),b=l&d^~l&p,w=h&f^~h&m,E=pn.F8(y,v,w,wn[e],An[e]),A=pn.TH(E,g,t,b,bn[e],En[e]),k=0|E,x=pn.rE(r,n,28)^pn.qh(r,n,34)^pn.qh(r,n,39),_=pn.ry(r,n,28)^pn.Ei(r,n,34)^pn.Ei(r,n,39),T=r&i^r&o^i&o,S=n&s^n&a^s&a;g=0|p,y=0|m,p=0|d,m=0|f,d=0|l,f=0|h,({h:l,l:h}=pn.WQ(0|c,0|u,0|A,0|k)),c=0|o,u=0|a,o=0|i,a=0|s,i=0|r,s=0|n;const I=pn.Vl(k,_,S);r=pn.Vr(I,A,x,T),n=0|I}({h:r,l:n}=pn.WQ(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=pn.WQ(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=pn.WQ(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:u}=pn.WQ(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:h}=pn.WQ(0|this.Eh,0|this.El,0|l,0|h)),({h:d,l:f}=pn.WQ(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:m}=pn.WQ(0|this.Gh,0|this.Gl,0|p,0|m)),({h:g,l:y}=pn.WQ(0|this.Hh,0|this.Hl,0|g,0|y)),this.set(r,n,i,s,o,a,c,u,l,h,d,f,p,m,g,y)}roundClean(){(0,cn.clean)(En,An)}destroy(){(0,cn.clean)(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const xn=(0,cn.createHasher)(()=>new yn),_n=(0,cn.createHasher)(()=>new kn),Tn=BigInt(0),Sn=BigInt(1);function In(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function Nn(e,t,r=""){const n=(0,cn.isBytes)(e),i=e?.length,s=void 0!==t;if(!n||s&&i!==t)throw new Error((r&&`"${r}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(n?`length=${i}`:"type="+typeof e));return e}function Rn(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Tn:BigInt("0x"+e)}function On(e){return(0,cn.abytes)(e),Rn((0,cn.bytesToHex)(Uint8Array.from(e).reverse()))}function Cn(e,t){return(0,cn.hexToBytes)(e.toString(16).padStart(2*t,"0"))}function Pn(e,t){return Cn(e,t).reverse()}function Mn(e,t,r){let n;if("string"==typeof t)try{n=(0,cn.hexToBytes)(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!(0,cn.isBytes)(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const i=n.length;if("number"==typeof r&&i!==r)throw new Error(e+" of length "+r+" expected, got "+i);return n}function Dn(e){return Uint8Array.from(e)}const Bn=e=>"bigint"==typeof e&&Tn<=e;function Ln(e,t,r,n){if(!function(e,t,r){return Bn(e)&&Bn(t)&&Bn(r)&&t<=e&&e<r}(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}const Un=e=>(Sn<<BigInt(e))-Sn;function Fn(e,t,r={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function n(t,r,n){const i=e[t];if(n&&void 0===i)return;const s=typeof i;if(s!==r||null===i)throw new Error(`param "${t}" is invalid: expected ${r}, got ${s}`)}Object.entries(t).forEach(([e,t])=>n(e,t,!1)),Object.entries(r).forEach(([e,t])=>n(e,t,!0))}const $n=()=>{throw new Error("not implemented")};function Hn(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(void 0!==i)return i;const s=e(r,...n);return t.set(r,s),s}}const Kn=BigInt(0),qn=BigInt(1),jn=BigInt(2),zn=BigInt(3),Vn=BigInt(4),Gn=BigInt(5),Wn=BigInt(7),Jn=BigInt(8),Zn=BigInt(9),Yn=BigInt(16);function Qn(e,t){const r=e%t;return r>=Kn?r:t+r}function Xn(e,t,r){let n=e;for(;t-- >Kn;)n*=n,n%=r;return n}function ei(e,t){if(e===Kn)throw new Error("invert: expected non-zero number");if(t<=Kn)throw new Error("invert: expected positive modulus, got "+t);let r=Qn(e,t),n=t,i=Kn,s=qn,o=qn,a=Kn;for(;r!==Kn;){const e=n/r,t=n%r,c=i-o*e,u=s-a*e;n=r,r=t,i=o,s=a,o=c,a=u}if(n!==qn)throw new Error("invert: does not exist");return Qn(i,t)}function ti(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function ri(e,t){const r=(e.ORDER+qn)/Vn,n=e.pow(t,r);return ti(e,n,t),n}function ni(e,t){const r=(e.ORDER-Gn)/Jn,n=e.mul(t,jn),i=e.pow(n,r),s=e.mul(t,i),o=e.mul(e.mul(s,jn),i),a=e.mul(s,e.sub(o,e.ONE));return ti(e,a,t),a}function ii(e){if(e<zn)throw new Error("sqrt is not defined for small field");let t=e-qn,r=0;for(;t%jn===Kn;)t/=jn,r++;let n=jn;const i=ui(e);for(;1===ci(i,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return ri;let s=i.pow(n,t);const o=(t+qn)/jn;return function(e,n){if(e.is0(n))return n;if(1!==ci(e,n))throw new Error("Cannot find square root");let i=r,a=e.mul(e.ONE,s),c=e.pow(n,t),u=e.pow(n,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,r=e.sqr(c);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===i)throw new Error("Cannot find square root");const n=qn<<BigInt(i-t-1),s=e.pow(a,n);i=t,a=e.sqr(s),c=e.mul(c,a),u=e.mul(u,s)}return u}}const si=(e,t)=>(Qn(e,t)&qn)===qn,oi=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ai(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce((t,r,i)=>e.is0(r)?t:(n[i]=t,e.mul(t,r)),e.ONE),s=e.inv(i);return t.reduceRight((t,r,i)=>e.is0(r)?t:(n[i]=e.mul(t,n[i]),e.mul(t,r)),s),n}function ci(e,t){const r=(e.ORDER-qn)/jn,n=e.pow(t,r),i=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function ui(e,t,r=!1,n={}){if(e<=Kn)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s,o,a=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(i=e.BITS),e.sqrt&&(s=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(i=t),n.sqrt&&(s=n.sqrt);const{nBitLength:c,nByteLength:u}=function(e,t){void 0!==t&&(0,cn.anumber)(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}(e,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const h=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:Un(c),ZERO:Kn,ONE:qn,allowedLengths:o,create:t=>Qn(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Kn<=t&&t<e},is0:e=>e===Kn,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&qn)===qn,neg:t=>Qn(-t,e),eql:(e,t)=>e===t,sqr:t=>Qn(t*t,e),add:(t,r)=>Qn(t+r,e),sub:(t,r)=>Qn(t-r,e),mul:(t,r)=>Qn(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Kn)throw new Error("invalid exponent, negatives unsupported");if(r===Kn)return e.ONE;if(r===qn)return t;let n=e.ONE,i=t;for(;r>Kn;)r&qn&&(n=e.mul(n,i)),i=e.sqr(i),r>>=qn;return n}(h,e,t),div:(t,r)=>Qn(t*ei(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>ei(t,e),sqrt:s||(t=>{return l||(l=(r=e)%Vn===zn?ri:r%Jn===Gn?ni:r%Yn===Zn?function(e){const t=ui(e),r=ii(e),n=r(t,t.neg(t.ONE)),i=r(t,n),s=r(t,t.neg(n)),o=(e+Wn)/Yn;return(e,t)=>{let r=e.pow(t,o),a=e.mul(r,n);const c=e.mul(r,i),u=e.mul(r,s),l=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);r=e.cmov(r,a,l),a=e.cmov(u,c,h);const d=e.eql(e.sqr(a),t),f=e.cmov(r,a,d);return ti(e,f,t),f}}(r):ii(r)),l(h,t);var r}),toBytes:e=>r?Pn(e,u):Cn(e,u),fromBytes:(t,n=!0)=>{if(o){if(!o.includes(t.length)||t.length>u)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(u);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+t.length);let i=r?On(t):function(e){return Rn((0,cn.bytesToHex)(e))}(t);if(a&&(i=Qn(i,e)),!n&&!h.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:e=>ai(h,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(h)}const li=BigInt(0),hi=BigInt(1);function di(e,t){const r=t.negate();return e?r:t}function fi(e,t){const r=ai(e.Fp,t.map(e=>e.Z));return t.map((t,n)=>e.fromAffine(t.toAffine(r[n])))}function pi(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function mi(e,t){pi(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Un(e),maxNumber:r,shiftBy:BigInt(e)}}function gi(e,t,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(e&i),c=e>>o;a>n&&(a-=s,c+=hi);const u=t*n;return{nextN:c,offset:u+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:u}}const yi=new WeakMap,vi=new WeakMap;function bi(e){return vi.get(e)||1}function wi(e){if(e!==li)throw new Error("invalid wNAF")}class Ei{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>li;)t&hi&&(r=r.add(n)),n=n.double(),t>>=hi;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=mi(t,this.bits),i=[];let s=e,o=s;for(let e=0;e<r;e++){o=s,i.push(o);for(let e=1;e<n;e++)o=o.add(s),i.push(o);s=o.double()}return i}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const s=mi(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:u,isNegF:l,offsetF:h}=gi(r,e,s);r=o,c?i=i.add(di(l,t[h])):n=n.add(di(u,t[a]))}return wi(r),{p:n,f:i}}wNAFUnsafe(e,t,r,n=this.ZERO){const i=mi(e,this.bits);for(let e=0;e<i.windows&&r!==li;e++){const{nextN:s,offset:o,isZero:a,isNeg:c}=gi(r,e,i);if(r=s,!a){const e=t[o];n=n.add(c?e.negate():e)}}return wi(r),n}getPrecomputes(e,t,r){let n=yi.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),yi.set(t,n))),n}cached(e,t,r){const n=bi(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const i=bi(e);return 1===i?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)}createCache(e,t){pi(t,this.bits),vi.set(e,t),yi.delete(e)}hasCache(e){return 1!==bi(e)}}function Ai(e,t,r,n){(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)})})(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)})}(n,t);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=function(e){let t;for(t=0;e>Tn;e>>=Sn,t+=1);return t}(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Un(c),l=new Array(Number(u)+1).fill(o);let h=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){l.fill(o);for(let t=0;t<s;t++){const i=n[t],s=Number(i>>BigInt(e)&u);l[s]=l[s].add(r[t])}let t=o;for(let e=l.length-1,r=o;e>0;e--)r=r.add(l[e]),t=t.add(r);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function ki(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){Fn(e,oi.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return ui(e,{isLE:r})}const xi=BigInt(0),_i=BigInt(1),Ti=BigInt(2),Si=BigInt(8);class Ii{constructor(e){this.ep=e}static fromBytes(e){$n()}static fromHex(e){$n()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return(0,cn.bytesToHex)(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}}function Ni(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:i}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:ui(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(e,function(e,t,r={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Fn(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:i,Fp:s,Fn:o}=e,a=r.randomBytes||cn.randomBytes,c=r.adjustScalarBytes||(e=>e),u=r.domain||((e,t,r)=>{if(In(r,"phflag"),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return o.create(On(e))}function h(e){const{head:r,prefix:n,scalar:s}=function(e){const r=g.secretKey;e=Mn("private key",e,r);const n=Mn("hashed private key",t(e),2*r),i=c(n.slice(0,r));return{head:i,prefix:n.slice(r,2*r),scalar:l(i)}}(e),o=i.multiply(s),a=o.toBytes();return{head:r,prefix:n,scalar:s,point:o,pointBytes:a}}function d(e){return h(e).pointBytes}function f(e=Uint8Array.of(),...r){const i=(0,cn.concatBytes)(...r);return l(t(u(i,Mn("context",e),!!n)))}const p={zip215:!0},m=s.BYTES,g={secretKey:m,publicKey:m,signature:2*m,seed:m};function y(e=a(g.seed)){return Nn(e,g.seed,"seed")}const v={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:function(e){return(0,cn.isBytes)(e)&&e.length===o.BYTES},isValidPublicKey:function(t,r){try{return!!e.fromBytes(t,r)}catch(e){return!1}},toMontgomery(t){const{y:r}=e.fromBytes(t),n=g.publicKey,i=32===n;if(!i&&57!==n)throw new Error("only defined for 25519 and 448");const o=i?s.div(_i+r,_i-r):s.div(r-_i,r+_i);return s.toBytes(o)},toMontgomerySecret(e){const r=g.secretKey;Nn(e,r);const n=t(e.subarray(0,r));return c(n).subarray(0,r)},randomPrivateKey:y,precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=v.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign:function(e,t,r={}){e=Mn("message",e),n&&(e=n(e));const{prefix:s,scalar:a,pointBytes:c}=h(t),u=f(r.context,s,e),l=i.multiply(u).toBytes(),d=f(r.context,l,c,e),p=o.create(u+d*a);if(!o.isValid(p))throw new Error("sign failed: invalid s");return Nn((0,cn.concatBytes)(l,o.toBytes(p)),g.signature,"result")},verify:function(t,r,s,o=p){const{context:a,zip215:c}=o,u=g.signature;t=Mn("signature",t,u),r=Mn("message",r),s=Mn("publicKey",s,g.publicKey),void 0!==c&&In(c,"zip215"),n&&(r=n(r));const l=u/2,h=t.subarray(0,l),d=On(t.subarray(l,u));let m,y,v;try{m=e.fromBytes(s,c),y=e.fromBytes(h,c),v=i.multiplyUnsafe(d)}catch(e){return!1}if(!c&&m.isSmallOrder())return!1;const b=f(a,y.toBytes(),m.toBytes(),r);return y.add(m.multiplyUnsafe(b)).subtract(v).clearCofactor().is0()},utils:v,Point:e,lengths:g})}(function(e,t={}){const r=function(e,t,r={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const r=t[e];if(!("bigint"==typeof r&&r>li))throw new Error(`CURVE.${e} must be positive bigint`)}const i=ki(t.p,r.Fp,n),s=ki(t.n,r.Fn,n),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!i.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:i,Fn:s}}("edwards",e,t,t.FpFnLE),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:o}=s;Fn(t,{},{uvRatio:"function"});const a=Ti<<BigInt(8*i.BYTES)-_i,c=e=>n.create(e),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:xi}}});if(!function(e,t,r,n){const i=e.sqr(r),s=e.sqr(n),o=e.add(e.mul(t.a,i),s),a=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(o,a)}(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(e,t,r=!1){return Ln("coordinate "+e,t,r?_i:xi,a),t}function h(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const d=Hn((e,t)=>{const{X:r,Y:i,Z:s}=e,o=e.is0();null==t&&(t=o?Si:n.inv(s));const a=c(r*t),u=c(i*t),l=n.mul(s,t);if(o)return{x:xi,y:_i};if(l!==_i)throw new Error("invZ was invalid");return{x:a,y:u}}),f=Hn(e=>{const{a:t,d:r}=s;if(e.is0())throw new Error("bad point: ZERO");const{X:n,Y:i,Z:o,T:a}=e,u=c(n*n),l=c(i*i),h=c(o*o),d=c(h*h),f=c(u*t);if(c(h*c(f+l))!==c(d+c(r*c(u*l))))throw new Error("bad point: equation left != right (1)");if(c(n*i)!==c(o*a))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(e,t,r,n){this.X=l("x",e),this.Y=l("y",t),this.Z=l("z",r,!0),this.T=l("t",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};return l("x",t),l("y",r),new p(t,r,_i,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:i,d:o}=s;e=Dn(Nn(e,r,"point")),In(t,"zip215");const l=Dn(e),h=e[r-1];l[r-1]=-129&h;const d=On(l),f=t?a:n.ORDER;Ln("point.y",d,xi,f);const m=c(d*d),g=c(m-_i),y=c(o*m-i);let{isValid:v,value:b}=u(g,y);if(!v)throw new Error("bad point: invalid y coordinate");const w=(b&_i)===_i,E=!!(128&h);if(!t&&b===xi&&E)throw new Error("bad point: x=0 and x_0=1");return E!==w&&(b=c(-b)),p.fromAffine({x:b,y:d})}static fromHex(e,t=!1){return p.fromBytes(Mn("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return m.createCache(this,e),t||this.multiply(Ti),this}assertValidity(){f(this)}equals(e){h(e);const{X:t,Y:r,Z:n}=this,{X:i,Y:s,Z:o}=e,a=c(t*o),u=c(i*n),l=c(r*o),d=c(s*n);return a===u&&l===d}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=s,{X:t,Y:r,Z:n}=this,i=c(t*t),o=c(r*r),a=c(Ti*c(n*n)),u=c(e*i),l=t+r,h=c(c(l*l)-i-o),d=u+o,f=d-a,m=u-o,g=c(h*f),y=c(d*m),v=c(h*m),b=c(f*d);return new p(g,y,b,v)}add(e){h(e);const{a:t,d:r}=s,{X:n,Y:i,Z:o,T:a}=this,{X:u,Y:l,Z:d,T:f}=e,m=c(n*u),g=c(i*l),y=c(a*r*f),v=c(o*d),b=c((n+i)*(u+l)-m-g),w=v-y,E=v+y,A=c(g-t*m),k=c(b*w),x=c(E*A),_=c(b*A),T=c(w*E);return new p(k,x,T,_)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:r}=m.cached(this,e,e=>fi(p,e));return fi(p,[t,r])[0]}multiplyUnsafe(e,t=p.ZERO){if(!i.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===xi?p.ZERO:this.is0()||e===_i?this:m.unsafe(this,e,e=>fi(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return o===_i?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&_i?128:0,r}toHex(){return(0,cn.bytesToHex)(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return fi(p,e)}static msm(e,t){return Ai(p,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,_i,c(s.Gx*s.Gy)),p.ZERO=new p(xi,_i,_i,xi),p.Fp=n,p.Fn=i;const m=new Ei(p,i.BITS);return p.BASE.precompute(8),p}(t,r),n,i))}(0,cn.utf8ToBytes)("HashToScalar-");const Ri=BigInt(0),Oi=BigInt(1),Ci=BigInt(2);const Pi=BigInt(0),Mi=BigInt(1),Di=BigInt(2),Bi=BigInt(3),Li=BigInt(5),Ui=BigInt(8),Fi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),$i=(()=>({p:Fi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ui,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Hi(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=Fi,o=e*e%s*e%s,a=Xn(o,Di,s)*o%s,c=Xn(a,Mi,s)*e%s,u=Xn(c,Li,s)*c%s,l=Xn(u,t,s)*u%s,h=Xn(l,r,s)*l%s,d=Xn(h,n,s)*h%s,f=Xn(d,i,s)*d%s,p=Xn(f,i,s)*d%s,m=Xn(p,t,s)*u%s;return{pow_p_5_8:Xn(m,Di,s)*e%s,b2:o}}function Ki(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const qi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ji(e,t){const r=Fi,n=Qn(t*t*t,r),i=Qn(n*n*t,r);let s=Qn(e*n*Hi(e*i).pow_p_5_8,r);const o=Qn(t*s*s,r),a=s,c=Qn(s*qi,r),u=o===e,l=o===Qn(-e,r),h=o===Qn(-e*qi,r);return u&&(s=a),(l||h)&&(s=c),si(s,r)&&(s=Qn(-s,r)),{isValid:u||l,value:s}}const zi=(()=>ui($i.p,{isLE:!0}))(),Vi=(()=>ui($i.n,{isLE:!0}))(),Gi=(()=>({...$i,Fp:zi,hash:_n,adjustScalarBytes:Ki,uvRatio:ji}))(),Wi=(()=>Ni(Gi))(),Ji=(()=>{const e=zi.ORDER;return function(e){const t=(Fn(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r}));var r;const{P:n,type:i,adjustScalarBytes:s,powPminus2:o,randomBytes:a}=t,c="x25519"===i;if(!c&&"x448"!==i)throw new Error("invalid type");const u=a||cn.randomBytes,l=c?255:448,h=c?32:56,d=c?BigInt(9):BigInt(5),f=c?BigInt(121665):BigInt(39081),p=c?Ci**BigInt(254):Ci**BigInt(447),m=c?BigInt(8)*Ci**BigInt(251)-Oi:BigInt(4)*Ci**BigInt(445)-Oi,g=p+m+Oi,y=e=>Qn(e,n),v=b(d);function b(e){return Pn(y(e),h)}function w(e,t){const r=function(e,t){Ln("u",e,Ri,n),Ln("scalar",t,p,g);const r=t,i=e;let s=Oi,a=Ri,c=e,u=Oi,h=Ri;for(let e=BigInt(l-1);e>=Ri;e--){const t=r>>e&Oi;h^=t,({x_2:s,x_3:c}=A(h,s,c)),({x_2:a,x_3:u}=A(h,a,u)),h=t;const n=s+a,o=y(n*n),l=s-a,d=y(l*l),p=o-d,m=c+u,g=y((c-u)*n),v=y(m*l),b=g+v,w=g-v;c=y(b*b),u=y(i*y(w*w)),s=y(o*d),a=y(p*(o+y(f*p)))}({x_2:s,x_3:c}=A(h,s,c)),({x_2:a,x_3:u}=A(h,a,u));const d=o(a);return y(s*d)}(function(e){const t=Mn("u coordinate",e,h);return c&&(t[31]&=127),y(On(t))}(t),function(e){return On(s(Mn("scalar",e,h)))}(e));if(r===Ri)throw new Error("invalid private or public key received");return b(r)}function E(e){return w(e,v)}function A(e,t,r){const n=y(e*(t-r));return{x_2:t=y(t-n),x_3:r=y(r+n)}}const k={secretKey:h,publicKey:h,seed:h},x=(e=u(h))=>((0,cn.abytes)(e,k.seed),e);return{keygen:function(e){const t=x(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>w(e,t),getPublicKey:e=>E(e),scalarMult:w,scalarMultBase:E,utils:{randomSecretKey:x,randomPrivateKey:x},GuBytes:v.slice(),lengths:k}}({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:r,b2:n}=Hi(t);return Qn(Xn(r,Bi,e)*n,e)},adjustScalarBytes:Ki})})(),Zi=qi,Yi=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Qi=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Xi=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),es=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ts=e=>ji(Mi,e),rs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),ns=e=>Wi.Point.Fp.create(On(e)&rs);function is(e){const{d:t}=$i,r=Fi,n=e=>zi.create(e),i=n(Zi*e*e),s=n((i+Mi)*Xi);let o=BigInt(-1);const a=n((o-t*i)*n(i+t));let{isValid:c,value:u}=ji(s,a),l=n(u*e);si(l,r)||(l=n(-l)),c||(u=l),c||(o=i);const h=n(o*(i-Mi)*es-a),d=u*u,f=n((u+u)*a),p=n(h*Yi),m=n(Mi-d),g=n(Mi+d);return new Wi.Point(n(f*g),n(m*p),n(p*g),n(f*m))}class ss extends Ii{constructor(e){super(e)}static fromAffine(e){return new ss(Wi.Point.fromAffine(e))}assertSame(e){if(!(e instanceof ss))throw new Error("RistrettoPoint expected")}init(e){return new ss(e)}static hashToCurve(e){return function(e){(0,cn.abytes)(e,64);const t=is(ns(e.subarray(0,32))),r=is(ns(e.subarray(32,64)));return new ss(t.add(r))}(Mn("ristrettoHash",e,64))}static fromBytes(e){(0,cn.abytes)(e,32);const{a:t,d:r}=$i,n=Fi,i=e=>zi.create(e),s=ns(e);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(zi.toBytes(s),e)||si(s,n))throw new Error("invalid ristretto255 encoding 1");const o=i(s*s),a=i(Mi+t*o),c=i(Mi-t*o),u=i(a*a),l=i(c*c),h=i(t*r*u-l),{isValid:d,value:f}=ts(i(h*l)),p=i(f*c),m=i(f*p*h);let g=i((s+s)*p);si(g,n)&&(g=i(-g));const y=i(a*m),v=i(g*y);if(!d||si(v,n)||y===Pi)throw new Error("invalid ristretto255 encoding 2");return new ss(new Wi.Point(g,y,Mi,v))}static fromHex(e){return ss.fromBytes(Mn("ristrettoHex",e,32))}static msm(e,t){return Ai(ss,Wi.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep;const i=Fi,s=e=>zi.create(e),o=s(s(r+t)*s(r-t)),a=s(e*t),c=s(a*a),{value:u}=ts(s(o*c)),l=s(u*o),h=s(u*a),d=s(l*h*n);let f;if(si(n*d,i)){let r=s(t*Zi),n=s(e*Zi);e=r,t=n,f=s(l*Qi)}else f=h;si(e*d,i)&&(t=s(-t));let p=s((r-t)*f);return si(p,i)&&(p=s(-p)),zi.toBytes(p)}equals(e){this.assertSame(e);const{X:t,Y:r}=this.ep,{X:n,Y:i}=e.ep,s=e=>zi.create(e),o=s(t*i)===s(r*n),a=s(r*i)===s(t*n);return o||a}is0(){return this.equals(ss.ZERO)}}ss.BASE=(()=>new ss(Wi.Point.BASE))(),ss.ZERO=(()=>new ss(Wi.Point.ZERO))(),ss.Fp=(()=>zi)(),ss.Fn=(()=>Vi)();class os extends cn.Hash{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,(0,cn.ahash)(e);const r=(0,cn.toBytes)(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),(0,cn.clean)(i)}update(e){return(0,cn.aexists)(this),this.iHash.update(e),this}digestInto(e){(0,cn.aexists)(this),(0,cn.abytes)(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:s,outputLen:o}=this;return e.finished=n,e.destroyed=i,e.blockLen=s,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const as=(e,t,r)=>new os(e,t).update(r).digest();as.create=(e,t)=>new os(e,t);const cs=Uint8Array.from([0]),us=Uint8Array.of(),ls=(e,t,r,n,i)=>function(e,t,r,n=32){(0,cn.ahash)(e),(0,cn.anumber)(n);const i=e.outputLen;if(n>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(n/i);void 0===r&&(r=us);const o=new Uint8Array(s*i),a=as.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let e=0;e<s;e++)cs[0]=e+1,c.update(0===e?us:u).update(r).update(cs).digestInto(u),o.set(u,i*e),a._cloneInto(c);return a.destroy(),c.destroy(),(0,cn.clean)(u,cs),o.slice(0,n)}(e,function(e,t,r){return(0,cn.ahash)(e),void 0===r&&(r=new Uint8Array(e.outputLen)),as(e,(0,cn.toBytes)(r),(0,cn.toBytes)(t))}(e,t,r),n,i),hs=xn;var ds=i(4290),fs={NOT_FOUND:"NOT_FOUND",AUTH_EXPIRED:"AUTH_EXPIRED",AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_DELEGATION_REVOKED:"AUTH_DELEGATION_REVOKED",AUTH_DELEGATION_ANCESTOR_REVOKED:"AUTH_DELEGATION_ANCESTOR_REVOKED",NETWORK_ERROR:"NETWORK_ERROR",NODE_NOT_RESPONDING:"NODE_NOT_RESPONDING",NODE_IDENTITY_MISMATCH:"NODE_IDENTITY_MISMATCH",PARTIAL_NODE_WRITE:"PARTIAL_NODE_WRITE",RESOURCE_NOT_ROUTED:"RESOURCE_NOT_ROUTED",TIMEOUT:"TIMEOUT",ABORTED:"ABORTED",INVALID_INPUT:"INVALID_INPUT",PERMISSION_DENIED:"PERMISSION_DENIED",NODE_BUSY:"NODE_BUSY",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",OUTCOME_UNKNOWN:"OUTCOME_UNKNOWN",KV_NOT_FOUND:"KV_NOT_FOUND",KV_WRITE_FAILED:"KV_WRITE_FAILED",KV_PRECONDITION_FAILED:"KV_PRECONDITION_FAILED",KV_CONFLICT:"KV_CONFLICT",KV_RESPONSE_TOO_LARGE:"KV_RESPONSE_TOO_LARGE",KV_SYNC_RESET_REQUIRED:"KV_SYNC_RESET_REQUIRED",KV_RETENTION_GRANT_REFUSED:"KV_RETENTION_GRANT_REFUSED",SQL_ERROR:"SQL_ERROR",SQL_PERMISSION_DENIED:"SQL_PERMISSION_DENIED",SQL_DATABASE_NOT_FOUND:"SQL_DATABASE_NOT_FOUND",SQL_RESPONSE_TOO_LARGE:"SQL_RESPONSE_TOO_LARGE",SQL_QUOTA_EXCEEDED:"SQL_QUOTA_EXCEEDED",SQL_INVALID_STATEMENT:"SQL_INVALID_STATEMENT",SQL_SCHEMA_ERROR:"SQL_SCHEMA_ERROR",SQL_READONLY_VIOLATION:"SQL_READONLY_VIOLATION",STORAGE_QUOTA_EXCEEDED:"STORAGE_QUOTA_EXCEEDED",STORAGE_LIMIT_REACHED:"STORAGE_LIMIT_REACHED",STORAGE_STATUS_UNAVAILABLE:"STORAGE_STATUS_UNAVAILABLE",DUCKDB_ERROR:"DUCKDB_ERROR",DUCKDB_PERMISSION_DENIED:"DUCKDB_PERMISSION_DENIED",DUCKDB_DATABASE_NOT_FOUND:"DUCKDB_DATABASE_NOT_FOUND",DUCKDB_RESPONSE_TOO_LARGE:"DUCKDB_RESPONSE_TOO_LARGE",DUCKDB_QUOTA_EXCEEDED:"DUCKDB_QUOTA_EXCEEDED",DUCKDB_INVALID_STATEMENT:"DUCKDB_INVALID_STATEMENT",DUCKDB_SCHEMA_ERROR:"DUCKDB_SCHEMA_ERROR",DUCKDB_READONLY_VIOLATION:"DUCKDB_READONLY_VIOLATION"};function ps(e){return{ok:!0,data:e}}function ms(e){return{ok:!1,error:e}}function gs(e,t,r,n){return{code:e,message:t,service:r,cause:n?.cause,meta:n?.meta}}var ys="[REDACTED]",vs=new Set(["duration","durationMs","endedAt","startedAt","status","timestamp","latencyMs","stalenessMs","count","changes","deleted","fetched","pages","lagMs","pendingCleared","partitions","remaining","expiryMs"]),bs=new Set(["authenticated","ok","persisted","purgePending"]),ws={source:["replica","network","none"],reason:["hit","absent","deleted","content_missing","coverage_incomplete","not_covered","pending_write","grant_missing","grant_expired","grant_revoked","grant_not_yet_valid","stale","replica_error","runtime_unsupported","replica_unavailable","unsupported_option","network_cursor","cursor_restart","aborted","REPLICA_BEHIND_OWN_WRITES","REPLICA_UNPROVEN_SINCE_START","NETWORK_REQUESTED","replica_gated","sign_out","account_switch","consent_expired","startup"],op:["get","list","put","delete","batchPut"],trigger:["start","interval","stale_read","manual","peer"],origin:["peer"],outcome:["found","not_found","error","committed","failed","ambiguous","ok","busy","aborted"],class:["offline","authority","storage","node","lifecycle"],state:["opened","grant_installed","grant_missing","runtime_unsupported","unavailable","revoked","recreated","purged","purge_failed","pending_store_error","pinned","pending_cleared","closed","idle","ready","gated"],action:["minted","renewed","renewal_refused","renewal_deferred","capped","expired","consent_deadline_reached","denied","deny_stale","deny_failed","database_deleted","marker_set","marker_cleared","unguarded","drained","erased","erase_failed","activation_blocked","activated","recovered"],gate:["not_established","stamp_stale","principal_mismatch","purge_pending","logout_pending","gate_unavailable"],kind:["value","missing_local","extra_local","keys","order"],coverage:["empty","bootstrapping","complete"],authority:["valid","expired","revoked","not-yet-valid"],code:["NETWORK_ERROR","TIMEOUT","ABORTED","REPLICA_BUSY","REPLICA_BEHIND_OWN_WRITES","REPLICA_UNPROVEN_SINCE_START","NETWORK_REQUESTED","INTEGRITY_ERROR","STORAGE_ERROR","REPLICA_CLOSED","RUNTIME_UNSUPPORTED","GRANT_EXPIRED","GRANT_REVOKED","GRANT_NOT_YET_VALID","GRANT_MISSING","GRANT_INVALID","SOURCE_CHANGED","PROTOCOL_ERROR","SCOPE_VIOLATION","NODE_ERROR","CONTENT_MISMATCH","STORAGE_FULL","REPLICA_GATED","RESET_REQUIRED","STORAGE_BUDGET","CONSENT_EXPIRED"],pendingState:["in_flight","committed","ambiguous"],strategy:["session","minted","installed"],verify:["match","diverged","error","aborted"]};function Es(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function As(e,t){try{return e[t]}catch{return ys}}function ks(e){if(null==e)return e;if("object"!=typeof e)return ys;try{if(function(e){try{return Array.isArray(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}catch{return!0}}(e))return ys;const t={};for(const r of vs){const n=Es(As(e,r));void 0!==n&&(t[r]=n)}for(const r of bs){const n=As(e,r);"boolean"==typeof n&&(t[r]=n)}for(const[r,n]of Object.entries(ws)){const i=As(e,r);"string"==typeof i&&n.includes(i)&&(t[r]=i)}void 0!==As(e,"url")&&(t.url=ys);const r=As(e,"error");return void 0!==r&&(t.error=function(e){if("object"!=typeof e||null===e)return{};const t=Es(As(e,"status"));return void 0!==t&&t>=100&&t<=599?{status:t}:{}}(r)),t}catch{return ys}}var xs="TinyCloud_debug";function _s(){return globalThis}function Ts(){const e=globalThis.performance?.now?.bind(globalThis.performance);return"function"==typeof e?e():Date.now()}function Ss(e){return!0===e||"true"===e||"1"===e}function Is(){const e=globalThis.process;return e?.env?.[xs]}function Ns(){if(_s().window===globalThis)try{return globalThis.localStorage}catch{return}}function Rs(e){const t=Ns();if(t)try{e?t.setItem(xs,"true"):t.removeItem(xs)}catch{}}var Os=new class{constructor(){this.enabled=Ss(_s()[xs])||Ss(function(){const e=Ns();if(e)try{return e.getItem(xs)}catch{return}}())||Ss(Is()),this.sequence=0,this.events=[],this.maxEvents=1e3}isEnabled(){return this.enabled||Ss(_s()[xs])||Ss(Is())}enable(e={}){this.enabled=!0,_s()[xs]=!0,!1!==e.persist&&Rs(!0),this.log("debug.enabled",{persisted:!1!==e.persist})}disable(e={}){this.log("debug.disabled",{persisted:!1!==e.persist}),this.enabled=!1,_s()[xs]=!1,!1!==e.persist&&Rs(!1)}clear(){this.events=[]}getLogs(){return[...this.events]}log(e,t,r){if(this.isEnabled())return this.record({event:e,data:t,message:r,level:"debug",timestamp:Date.now(),timestampIso:(new Date).toISOString()})}startTimer(e,t){if(!this.isEnabled())return{stop:()=>{}};const r=Ts();return this.log(`${e}.start`,t),{stop:t=>{const n=Ts();return this.record({event:`${e}.end`,data:t,durationMs:n-r,startedAt:r,endedAt:n,level:"debug",timestamp:Date.now(),timestampIso:(new Date).toISOString()})}}}async timeAsync(e,t,r){if(!this.isEnabled())return t();const n=this.startTimer(e,r);try{const e=await t();return n.stop({ok:!0}),e}catch(e){throw n.stop({ok:!1,error:e}),e}}time(e,t,r){if(!this.isEnabled())return t();const n=this.startTimer(e,r);try{const e=t();return n.stop({ok:!0}),e}catch(e){throw n.stop({ok:!1,error:e}),e}}record(e){const t={...e,...void 0===e.data?{}:{data:ks(e.data)},...void 0===e.message?{}:{message:"[REDACTED]"},sequence:++this.sequence};this.events.push(t),this.events.length>this.maxEvents&&this.events.splice(0,this.events.length-this.maxEvents);try{globalThis.console?.debug?.("[TinyCloud]",t.event,t)}catch{}return t}};function Cs(e){return Os.enable(e),Os}function Ps(e){return Os.disable(e),Os}function Ms(){return Os.getLogs()}function Ds(){Os.clear()}!function(){const e=_s();e.TinyCloudDebug=Os,e.enableTinyCloudDebug=Cs,e.disableTinyCloudDebug=Ps,e.getTinyCloudDebugLogs=Ms,e.clearTinyCloudDebugLogs=Ds}();var Bs=pr({code:ar(),message:ar(),service:ar(),cause:dr().optional(),meta:pr({}).passthrough().optional()});function Ls(e,t=Bs){return gr("ok",[pr({ok:Er(!0),data:e}),pr({ok:Er(!1),error:t})])}Ls(dr(),Bs);var Us,Fs=pr({etag:ar().optional(),contentType:ar().optional(),lastModified:ar().optional(),contentLength:cr().optional()});function $s(e){try{return JSON.parse(e)}catch{return{}}}function Hs(e,t,r,n,i){return i.message?qs(i.message):/<!doctype html/i.test(s=n)||/<html[\s>]/i.test(s)?524===r||/524\s*[:-]/i.test(n)||/a timeout occurred/i.test(n)?`${e} ${t} failed: upstream request timed out. Please retry.`:`${e} ${t} failed: upstream service returned an HTML error page (${r}).`:`${e} ${t} failed: ${r} - ${qs(n)}`;var s}function Ks(e,t,r){const n={status:e,statusText:t},i=qs(r);return i&&(n.responseSnippet=i.slice(0,300)),n}function qs(e){const t=e.replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,500)}...`:t}Us=dr(),pr({data:Us,headers:Fs}),Ls(pr({keys:fr(ar()),truncated:ur().optional(),nextCursor:ar().optional()})),pr({service:ar(),action:ar(),span:ar().optional(),key:ar().optional(),timestamp:cr()}),pr({service:ar(),action:ar(),span:ar().optional(),ok:ur(),duration:cr(),durationMs:cr().optional(),status:cr().optional()}),pr({service:ar(),span:ar().optional(),error:Bs}),pr({service:ar(),attempt:cr().int().positive(),maxAttempts:cr().int().positive(),error:Bs}),pr({span:ar(),ok:ur(),durationMs:cr(),service:ar().optional(),action:ar().optional(),status:cr().optional(),error:Bs.optional()}),pr({maxAttempts:cr().int().positive(),backoff:Ar(["none","linear","exponential"]),baseDelayMs:cr().nonnegative(),maxDelayMs:cr().nonnegative(),retryableErrors:fr(ar()),maxTotalMs:cr().positive().optional()}),pr({delegationHeader:pr({Authorization:ar()}),delegationCid:ar(),spaceId:ar(),verificationMethod:ar(),jwk:pr({}).passthrough()});var js="urn:tinycloud:encryption:",zs=/^[a-z0-9][a-z0-9-]*$/,Vs=/^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/,Gs=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Ws(e){if("string"!=typeof e||0===e.length)throw new Gs("networkId must be a non-empty string");if(!e.startsWith(js))throw new Gs(`networkId must start with ${js} (got ${JSON.stringify(e)})`);const t=e.slice(25),r=t.lastIndexOf(":");if(r<=0||r===t.length-1)throw new Gs(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const n=t.slice(0,r),i=t.slice(r+1);if(!n.startsWith("did:"))throw new Gs(`networkId ownerDid must be a DID (got ${JSON.stringify(n)})`);const s=n.split(":");if(s.length<3||s.some(e=>0===e.length))throw new Gs(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(n)})`);if(!zs.test(i))throw new Gs(`networkId name ${JSON.stringify(i)} must match ${zs.source}`);return{networkId:e,ownerDid:n,name:i}}function Js(e){const t=e.lastIndexOf(":"),r=e.slice(t+1),n=r.indexOf("/"),i=-1===n?r:r.slice(0,n),s=Ws(-1===n?e:`${e.slice(0,t+1)}${i}`);if(-1===n)return s;const o=r.slice(n+1),a=o.split("/"),c=o.endsWith("/");if(0===o.length||/[\u0000-\u001f\u007f\\]/.test(o)||a.some((e,t)=>"."===e||".."===e||0===e.length&&!(c&&t===a.length-1)))throw new Gs(`encryption resource has an invalid keyPath (got ${JSON.stringify(e)})`);return{...s,keyPath:o}}function Zs(e){const t=e.match(Vs);return t?{chainId:t[1],address:t[2].toLowerCase()}:null}function Ys(e,t){const r=Zs(e),n=Zs(t);return r&&n?r.chainId===n.chainId&&r.address===n.address:e===t}var Qs=Symbol(),Xs=new WeakMap;function eo(e,t){return e===Qs||"Invocation expired or not yet valid"===t.trim()?{invocationTimeRefused:!0}:void 0===e?void 0:{invocationProofCid:e}}Error,Error,Error,Error;var to={NODE_NOT_RESPONDING:!0,PARTIAL_NODE_WRITE:!0,NODE_IDENTITY_MISMATCH:!0,RESOURCE_NOT_ROUTED:!0,DECRYPTION_DEPENDENCY_UNAVAILABLE:!0,registry_unavailable:!0,node_not_found:!0,node_registry_entry_exists:!0};function ro(e){if("object"==typeof e&&null!==e&&"code"in e&&"message"in e&&"string"==typeof e.code&&"string"==typeof e.message&&(t=e.code,Object.prototype.hasOwnProperty.call(to,t))){const t="meta"in e?e.meta:void 0;let r="object"!=typeof t||null===t||Array.isArray(t)?void 0:t;return"NODE_NOT_RESPONDING"===e.code&&"hosts"in e&&Array.isArray(e.hosts)?r={...r,hosts:e.hosts}:"PARTIAL_NODE_WRITE"===e.code&&"succeeded"in e&&Array.isArray(e.succeeded)&&"failed"in e&&Array.isArray(e.failed)&&(r={...r,succeeded:e.succeeded,failed:e.failed}),{code:e.code,message:e.message,...e instanceof Error?{cause:e}:{},...r?{meta:r}:{}}}var t}function no(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t=e;if(Object.keys(t).sort().some(e=>!["actions","path","service","space"].includes(e)))return;if("tinycloud.kv"!==t.service&&"tinycloud.encryption"!==t.service)return;if("string"!=typeof t.path||0===t.path.length||t.path.includes("*"))return;if("tinycloud.kv"===t.service&&("string"!=typeof t.space||0===t.space.length||!t.path.startsWith("vault/")||t.path.endsWith("/")))return;if("tinycloud.encryption"===t.service&&(void 0!==t.space||!t.path.startsWith("urn:tinycloud:encryption:")||t.path.endsWith(":")))return;if(!Array.isArray(t.actions)||1!==t.actions.length||"string"!=typeof t.actions[0]||t.actions[0].includes("*"))return;const r="tinycloud.kv"===t.service?"tinycloud.kv/get":"tinycloud.encryption/decrypt";if(t.actions[0]!==r)return;const n="string"==typeof t.space?t.space:void 0;return{service:t.service,...void 0===n?{}:{space:n},path:t.path,actions:[t.actions[0]]}}function io(e){return{code:fs.AUTH_REQUIRED,message:"Authentication required. Please sign in first.",service:e}}function so(e,t,r,n){const i=n.trim(),[,s,o]=/^([a-z_]+)(?::\s*([a-z_]+):)?/.exec(i)??[];let a;if(503!==r.status||"sql_busy"!==s&&"unavailable_retryable"!==s&&"read_audit_busy"!==s)if(503===r.status&&"request_timeout"===s)a=fs.REQUEST_TIMEOUT;else{if(500!==r.status||"outcome_unknown"!==s)return;a=fs.OUTCOME_UNKNOWN}else a=fs.NODE_BUSY;const c=a!==fs.OUTCOME_UNKNOWN,u=r.headers.get("retry-after")?.trim();return gs(a,t,e,{meta:{...Ks(r.status,r.statusText,n),retryable:c,..."sql_busy"===s&&o?{stage:o}:{},...c&&u&&/^\d{1,9}$/.test(u)?{retryAfterMs:1e3*Number(u)}:{}}})}var oo=class extends Error{constructor(e){super(`Request timed out after ${e}ms.`),this.name="TimeoutError",this.timeoutMs=e}};function ao(e){return e instanceof oo||e instanceof Error&&"TimeoutError"===e.name&&"number"==typeof e.timeoutMs}function co(e,t,r){return void 0===t?{code:fs.TIMEOUT,message:"Request timed out.",service:e,...void 0===r?{}:{cause:r}}:{code:fs.TIMEOUT,message:`Request timed out after ${t}ms.`,service:e,...void 0===r?{}:{cause:r},meta:{timeoutMs:t}}}function uo(e){const t=e.match(/^Unauthorized Action:\s*(.+?)\s*\/\s*(tinycloud\.\S+)$/m);return t?{resource:t[1].trim(),action:t[2].trim()}:{}}var lo=new Set(J.map(({urn:e})=>e).filter(e=>!e.endsWith("/*"))),ho=new Set(J.map(({service:e})=>e.slice(10)));function fo(e,t,r){if("string"!=typeof e||0===e.length||e.length>1024)return!1;if("encryption"===t&&e.startsWith("urn:tinycloud:encryption:")){if(!/^[A-Za-z0-9_][A-Za-z0-9_.:/-]*$/.test(e)||e.includes("//")||e.split("/").some(e=>"."===e||".."===e))return!1;try{return Ws(e),!0}catch{return!1}}const n=function(e,t){if(0===e.length||e.length>1024||!ho.has(t)||/[\s\p{C}*#]/u.test(e)||e.includes("://"))return;const r=e.split("/");if(!/^tinycloud:[A-Za-z0-9][A-Za-z0-9:._-]*$/.test(r[0]))return;const n=r.findIndex((e,t)=>t>0&&ho.has(e));if(n<1||r[n]!==t)return;if(r.slice(1,n).some(e=>0===e.length||"."===e||".."===e))return;const i=r.slice(n+1);return i.some(e=>"."===e||".."===e)||"kv"!==t&&(0===i.length||""===i[i.length-1])?void 0:{space:r.slice(0,n).join("/"),path:i.join("/")}}(e,t);return void 0!==n&&(!n.path.endsWith("/")||"kv"===t&&"tinycloud.kv/list"===r)&&(""!==n.path||"kv"===t&&"tinycloud.kv/list"===r)}function po(e){const t=yo(e);if("unauthenticated"!==t&&"forbidden"!==t)return;const r=new Set;let n=e;for(let e=0;e<mo&&"object"==typeof n&&null!==n&&!r.has(n);e+=1){r.add(n);const e=n,t=go(e),i=e.meta;if((401===t||403===t||void 0===t&&e.code===fs.AUTH_UNAUTHORIZED)&&"object"==typeof i&&null!==i&&!Array.isArray(i)){const t=i,{resource:r,requiredAction:n}=t;if("string"==typeof n&&lo.has(n)){const i=n.slice(10,n.indexOf("/")),s=void 0===e.service?t.service:e.service;if(fo(r,i,n)&&(void 0===s||s===i||s===`tinycloud.${i}`))return{resource:r,requiredAction:n}}}n=e.cause}}var mo=8;function go(e){const t=e.meta,r=[e.status,e.statusCode,"object"==typeof t&&null!==t?t.status:void 0];for(const e of r)if("number"==typeof e&&Number.isInteger(e)&&e>=400&&e<=599)return e}function yo(e){const t=new Set;let r=!1,n=e;for(let e=0;e<mo&&"object"==typeof n&&null!==n&&!t.has(n);e+=1){t.add(n);const e=n,i=go(e);if(401===i)return"unauthenticated";if(403===i)return"forbidden";if(void 0!==i)return"other";e.code===fs.AUTH_UNAUTHORIZED&&(r=!0),n=e.cause}return r?"forbidden":void 0}function vo(e){const t=e.match(/Used:\s*(\d+)\s*bytes,\s*Limit:\s*(\d+)\s*bytes/i);if(t)return{usedBytes:parseInt(t[1],10),limitBytes:parseInt(t[2],10)}}var bo={storage_quota_exceeded:!0,storage_limit_reached:!0};function wo(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=0}function Eo(e){if("object"!=typeof e||null===e)return;const{usedBytes:t,limitBytes:r}=e;return wo(t)&&wo(r)?{usedBytes:t,limitBytes:r}:void 0}function Ao(e){let t;try{t=JSON.parse(e)}catch{return vo(e)}if("object"!=typeof t||null===t)return;const r=t,n="string"==typeof r.message?r.message:"",i=Eo(r.space)??vo(n),s="string"==typeof r.error&&!0===bo[r.error];if(!i&&!s)return;const o={...i},a=Eo(r.account);if(a){const e=r.account.plan;o.account="string"==typeof e&&""!==e?{...a,plan:e}:a}return o}function ko(e,t,r,n){const i={...r,...Ao(n)};return 402===t?function(e,t,r){return{code:fs.STORAGE_QUOTA_EXCEEDED,message:"TinyCloud storage is full, so this change was not saved. Reading still works. Free up space or upgrade your plan to save again.",service:e,meta:r}}(e,0,i):function(e,t,r){return{code:fs.STORAGE_LIMIT_REACHED,message:"This change is larger than the TinyCloud storage you have left, so it was not saved. Reading still works. Free up space or upgrade your plan to save it.",service:e,meta:r}}(e,0,i)}function xo(e,t,r=fs.NETWORK_ERROR){const n=ro(t);return n?{...n,service:e}:t instanceof Error?ao(t)?co(e,t.timeoutMs,t):"AbortError"===t.name?function(e){return{code:fs.ABORTED,message:"Request was aborted.",service:e}}(e):"TimeoutError"===t.name||t.message.toLowerCase().includes("timeout")?co(e):{code:r,message:t.message,service:e,cause:t}:{code:r,message:String(t),service:e}}var _o=class{constructor(){this.abortController=new AbortController,this._config={}}get config(){return this._config}initialize(e){this.context=e}onSessionChange(e){}onSignOut(){this.abortController.abort(),this.abortController=new AbortController}get abortSignal(){return this.combineSignals()}get isAuthenticated(){return this.context?.isAuthenticated??!1}get session(){if(!this.context?.session)throw new Error("Not authenticated");return this.context.session}requireAuth(){return this.isAuthenticated}emit(e,t){this.context?.emit(e,t)}emitRequest(e,t){const r=this.getServiceName();this.emit("service.request",{service:r,action:e,span:this.spanName(e),key:t,timestamp:Date.now()})}emitResponse(e,t,r,n){const i=this.getServiceName(),s=Date.now()-r,o=this.spanName(e);this.emit("service.response",{service:i,action:e,span:o,ok:t,duration:s,durationMs:s,status:n}),this.emit("telemetry.span",{span:o,service:i,action:e,ok:t,durationMs:s,status:n})}emitError(e,t){const r=t?this.spanName(t):void 0;this.emit("service.error",{service:this.getServiceName(),...r?{span:r}:{},error:e})}getServiceName(){return this.constructor.serviceName}spanName(e){return`sdk.${this.getServiceName()}.${e}`}combineSignals(...e){const t=new AbortController,r=[this.abortController.signal,this.context?.abortSignal,...e.filter(Boolean)].filter(Boolean);for(const e of r){if(e.aborted)return t.abort(e.reason),t.signal;e.addEventListener("abort",()=>t.abort(e.reason),{once:!0})}return t.signal}invokeWithRetry(e,t,{headers:r,...n}={}){const i=()=>{const e=t();return{method:"POST",...n,headers:Array.isArray(e)?[...e,...Object.entries(r??{})]:{...e,...r}}};return this.context.invokeWithRetry?this.context.invokeWithRetry(e,i):this.context.fetch(e,i())}createRequestSignal(e,t){const r=new AbortController,n=[];let i;const s=()=>{void 0!==i&&(clearTimeout(i),i=void 0);for(const e of n.splice(0))e()},o=e=>{s(),r.abort(e)},a={signal:r.signal,dispose:s},c=[this.abortController.signal,this.context?.abortSignal,this.context?.operationAbortSignal,e].filter(e=>void 0!==e);for(const e of c){if(e.aborted)return o(e.reason),a;const t=()=>o(e.reason);e.addEventListener("abort",t,{once:!0}),n.push(()=>e.removeEventListener("abort",t))}const u=t??this._config.timeout;return"number"==typeof u&&u>0&&u<=2147483647&&(i=setTimeout(()=>o(new oo(u)),u)),a}async withTelemetry(e,t,r){const n=Date.now();this.emitRequest(e,t);try{const t=await r();return t.ok?this.emitResponse(e,!0,n):(this.emitResponse(e,!1,n),this.emitError(t.error,e)),t}catch(t){const r=xo(this.getServiceName(),t);return this.emitResponse(e,!1,n),this.emitError(r,e),ms(r)}}},To=class e{constructor(e,t){this._kv=e,this._prefix=t.endsWith("/")?t.slice(0,-1):t}get prefix(){return this._prefix}getFullKey(e){const t=e.startsWith("/")?e:`/${e}`;return`${this._prefix}${t}`}async get(e,t){const r=this.getFullKey(e);return this._kv.get(r,{...t,prefix:""})}async batchGet(e,t){const r=await this._kv.batchGet(e.map(e=>this.getFullKey(e)),{...t,prefix:""});return r.ok?ps({...r.data,results:r.data.results.map((t,r)=>({...t,key:e[r]}))}):r}async put(e,t,r){const n=this.getFullKey(e);return this._kv.put(n,t,{...r,prefix:""})}async batchPut(e,t){return this._kv.batchPut(e.map(e=>({...e,key:this.getFullKey(e.key)})),{...t,prefix:""})}async list(e){const t=e?.removePrefix??!0;return this._kv.list({...e,prefix:this._prefix,removePrefix:t})}async changes(e){if(""===this._prefix.replace(/\/+$/,""))return ms(gs(fs.INVALID_INPUT,"KV changes needs a non-empty prefix; this view has none","kv"));const t=`${this._prefix}/`,r=await this._kv.changes({...e,prefix:t});return r.ok?ps({...r.data,changes:r.data.changes.map(e=>({...e,key:e.key.startsWith(t)?e.key.slice(t.length):e.key}))}):r}async delete(e,t){const r=this.getFullKey(e);return this._kv.delete(r,{...t,prefix:""})}async head(e,t){const r=this.getFullKey(e);return this._kv.head(r,{...t,prefix:""})}async batchHead(e,t){const r=await this._kv.batchHead(e.map(e=>this.getFullKey(e)),{...t,prefix:""});return r.ok?ps({...r.data,results:r.data.results.map((t,r)=>({...t,key:e[r]}))}):r}async createSignedReadUrl(e,t){const r=this.getFullKey(e);return this._kv.createSignedReadUrl(r,{...t,prefix:""})}withPrefix(t){const r=t.startsWith("/")?t:`/${t}`,n=`${this._prefix}${r}`;return new e(this._kv,n)}},So="tinycloud.kv/get",Io="tinycloud.kv/put",No="tinycloud.kv/list",Ro="tinycloud.kv/del",Oo="tinycloud.kv/metadata",Co="tinycloud.kv/sync";function Po(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Mo=new TextEncoder,Do=/^(?:Invalid invocation: )?delegation-(?:(revoked): [A-Za-z0-9]+|(ancestor-revoked): ancestor=[A-Za-z0-9]+ invoked=[A-Za-z0-9]+)$/,Bo=new Set(["delegation_revoked","parent_revoked","ancestor_revoked"]);function Lo(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Uo(e,t,r,n){if(413!==r)return;const i=n.split(":",1)[0].trim();let s;return s=i===`${e}_request_too_large`||i!==`${e}_response_too_large`&&["batch","executeStatement","import"].includes(t),s?`${e.toUpperCase()}_REQUEST_TOO_LARGE`:void 0}(class extends _o{constructor(e={}){super(),this.readThrough=null,this.readThroughReady=null,this._config=e}setReadThroughReady(e){const t=()=>{"function"==typeof e&&(e=Promise.resolve().then(e));const r=()=>{this.readThroughReady===t&&(this.readThroughReady=null)};return e.then(r,r)};this.readThroughReady=t,"function"!=typeof e&&t()}get config(){return this._config}setReadThrough(e){this.readThrough=e}handleQuotaErrorResponse(e,t,r){if((402===e.status||413===e.status)&&(413!==e.status||Ao(t)))return ms(ko("kv",e.status,{status:e.status,statusText:e.statusText,key:r},t))}async classifyNotFound(e,t){const r=await e.text();return/space not found/i.test(r)?ms(gs(fs.KV_NOT_FOUND,`KV ${e.status} - ${r}`,"kv",{meta:{status:e.status,statusText:e.statusText}})):ms(gs(fs.KV_NOT_FOUND,`Key not found: ${t}`,"kv"))}getFullPath(e,t){const r=t??this._config.prefix??"";return r?""===e?r:`${r}/${e}`:e}get host(){return this.context.hosts[0]}async invokeOperation(e,t,r,n,i){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"kv",e,t),{headers:i,body:r,signal:n})}serializePutValue(e,t){if(e instanceof Blob)return t&&e.type!==t?new Blob([e],{type:t}):e;if(e instanceof ArrayBuffer)return new Blob([e],{type:t??"application/octet-stream"});if(ArrayBuffer.isView(e)){const r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return new Blob([r],{type:t??"application/octet-stream"})}return"string"==typeof e?t?new Blob([e],{type:t}):e:JSON.stringify(e)}serializeBatchPutValue(e){const t=e.contentType;if(e.value instanceof Blob)return t&&e.value.type!==t?new Blob([e.value],{type:t}):e.value;if(e.value instanceof ArrayBuffer)return new Blob([e.value],{type:t??"application/octet-stream"});if(ArrayBuffer.isView(e.value)){const r=e.value,n=new Uint8Array(r.byteLength);return n.set(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),new Blob([n],{type:t??"application/octet-stream"})}if("string"==typeof e.value)return new Blob([e.value],{type:t??"text/plain;charset=UTF-8"});const r=JSON.stringify(e.value);if(void 0===r)throw new Error(`Cannot JSON serialize KV batch value for key "${e.key}"`);return new Blob([r],{type:t??"application/json"})}normalizeBatchPutResponse(e){if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.written)&&t.written.every(e=>"string"==typeof e)&&"number"==typeof t.count?{written:t.written,count:t.count}:void 0}createResponseHeaders(e){return{etag:e.get("etag")??void 0,contentType:e.get("content-type")??void 0,lastModified:e.get("last-modified")??void 0,contentLength:e.get("content-length")?parseInt(e.get("content-length"),10):void 0,get:t=>e.get(t)}}createBatchResponseHeaders(e){const t=new Map(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t]));return this.createResponseHeaders({get:e=>t.get(e.toLowerCase())??null})}parseBatchValue(e,t,r=!1,n=!1){const i=globalThis.atob(e),s=Uint8Array.from(i,e=>e.charCodeAt(0));if(n)return s;const o=(new TextDecoder).decode(s);if(r)return o;const a=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase())?.[1];return a?.includes("application/json")?JSON.parse(o):o}normalizeBatchReadResponse(e,t,r){if(!e||"object"!=typeof e)return;const n=e.results;if(!Array.isArray(n)||n.length!==t.length)return;for(const e of n){if(!e||"object"!=typeof e||"boolean"!=typeof e.ok)return;if(e.ok&&(!e.headers||"object"!=typeof e.headers||Object.values(e.headers).some(e=>"string"!=typeof e)||r&&"string"!=typeof e.dataBase64))return;if(!(e.ok||e.error&&"string"==typeof e.error.code&&"string"==typeof e.error.message))return}if(n.every(e=>"string"==typeof e.key)){const e=new Map(n.map(e=>[e.key,e]));if(e.size!==n.length)return;const r=[];for(const n of t){const t=e.get(n);if(!t)return;r.push(t)}return r}if(n.some(e=>void 0!==e.key))return;const i=t.map((e,t)=>t).sort((e,r)=>function(e,t){const r=Mo.encode(e),n=Mo.encode(t),i=Math.min(r.length,n.length);for(let e=0;e<i;e++)if(r[e]!==n[e])return r[e]-n[e];return r.length-n.length}(t[e],t[r])),s=new Array(n.length);for(let e=0;e<i.length;e++)s[i[e]]=n[e];return s}async batchRead(e,t,r){if(!this.requireAuth())return ms(io("kv"));if(0===e.length)return ps({results:[],count:0});if(e.length>100)return ms(gs(fs.INVALID_INPUT,"KV batch reads accept at most 100 keys","kv"));if(1===e.length){const n=e[0];return ps({results:[{key:n,result:t===So?await this.get(n,r):await this.head(n,r)}],count:1})}if(!this.context.invokeAny)return ms(gs(fs.INVALID_INPUT,"KV batch reads require SDK runtime support for multi-resource invocations","kv"));const n=t===So?r:void 0;if(void 0!==n?.maxResponseBytes&&(!Number.isSafeInteger(n.maxResponseBytes)||n.maxResponseBytes<=0))return ms(gs(fs.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const i=e.map(e=>this.getFullPath(e,r?.prefix));if(new Set(i).size!==i.length)return ms(gs(fs.INVALID_INPUT,"KV batch read received duplicate keys after prefix resolution","kv"));const s=this.createRequestSignal(r?.signal,r?.timeout);try{const r={};void 0!==n?.maxResponseBytes&&(r["x-tinycloud-max-response-bytes"]=String(n.maxResponseBytes));const o=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.session;return this.context.invokeAny(e,i.map(r=>({spaceId:e.spaceId,service:"kv",path:r,action:t})))},{headers:r,signal:s.signal});if(!o.ok){const r=401===o.status||403===o.status?await this.readAuthorizationText(o):await o.text();return 401===o.status||403===o.status?this.authorizationFailure(`Failed to batch read ${e.length} key(s)`,o,r,i,t):413===o.status?ms(gs(fs.KV_RESPONSE_TOO_LARGE,"A KV batch value exceeds the requested response limit","kv",{meta:{status:o.status,statusText:o.statusText}})):ms(gs(fs.NETWORK_ERROR,`Failed to batch read ${e.length} key(s): ${o.status} - ${r}`,"kv",{meta:{status:o.status,statusText:o.statusText}}))}const a=this.normalizeBatchReadResponse(await o.json(),i,t===So);if(!a)return ms(gs(fs.NETWORK_ERROR,"KV batch read response did not match the requested keys","kv"));const c=a.map((r,i)=>{if(!r.ok)return{key:e[i],result:ms(gs(r.error.code,r.error.message,"kv"))};const s=r.headers,o=t===Oo?void 0:this.parseBatchValue(r.dataBase64,s,n?.raw,n?.binary);return{key:e[i],result:ps({data:o,headers:this.createBatchResponseHeaders(s)})}});return ps({results:c,count:c.length})}catch(e){return ms(xo("kv",e))}finally{s.dispose()}}async parseResponse(e,t=!1,r=!1){if(!e.ok)return;if(r)return new Uint8Array(await e.arrayBuffer());if(t)return await e.text();const n=e.headers.get("content-type");if(n?.includes("application/json"))return await e.json();if(n?.startsWith("text/"))return await e.text();const i=await e.text();if(i)try{return JSON.parse(i)}catch{return i}}async createSignedReadUrlError(e,t,r){let n=e.statusText;try{const t=await e.text();t&&(n=t)}catch{}return 401===e.status||403===e.status?this.authorizationFailure(`Failed to create signed read URL for key ${JSON.stringify(t)}`,e,n,[r],So):ms(gs(400===e.status?fs.INVALID_INPUT:fs.NETWORK_ERROR,`Failed to create signed read URL for key ${JSON.stringify(t)}: ${e.status} - ${n}`,"kv",{meta:{status:e.status,statusText:e.statusText}}))}async readAuthorizationText(e){try{return await e.text()}catch{return""}}authorizationFailure(e,t,r,n,i,s={}){const{resource:o,action:a}=uo(r),c=n.find(e=>o===e||o===`${this.context.session.spaceId}/kv/${e}`),u=void 0!==c&&a===i?po({service:"kv",code:fs.AUTH_UNAUTHORIZED,meta:{status:t.status,resource:`${this.context.session.spaceId}/kv/${c}`,requiredAction:a}}):void 0,l=r.trim().length>0?r:t.statusText||"authorization failed",h=eo(Xs.get(t),r);return ms((d=`${e}: ${t.status} - ${l}`,f={status:t.status,...s,...u,...h},gs(fs.AUTH_UNAUTHORIZED,d,"kv",{meta:f})));var d,f}normalizeSignedReadUrlResponse(e){if(!e||"object"!=typeof e)return;const t=e;return"string"==typeof t.url&&"string"==typeof t.ticketId&&"string"==typeof t.expiresAt?{url:new URL(t.url,this.host).toString(),relativeUrl:t.url,ticketId:t.ticketId,expiresAt:t.expiresAt}:void 0}async get(e,t){return this.withTelemetry("get",e,async()=>{if("network"!==t?.source&&null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ms(io("kv"));if(void 0!==t?.maxResponseBytes&&(!Number.isSafeInteger(t.maxResponseBytes)||t.maxResponseBytes<=0))return ms(gs(fs.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const i=()=>this.getFromNetwork(e,r,t,n.signal);if("network"===t?.source){const e=this.readThrough;if(null===e)return await i();let t="error";const n=Date.now();try{const e=await i();return t=e.ok?"found":e.error.code===fs.KV_NOT_FOUND?"not_found":"error",e}finally{try{e.observeNetworkRequested({op:"get",space:this.context.session.spaceId,path:r,reason:"NETWORK_REQUESTED",outcome:t,latencyMs:Date.now()-n})}catch{}}}return null===this.readThrough?await i():await this.readThrough.get({space:this.context.session.spaceId,key:e,path:r,options:t,signal:n.signal,network:i})}catch(e){return ms(xo("kv",e))}finally{n.dispose()}})}async getFromNetwork(e,t,r,n){const i=await this.invokeOperation(t,So,void 0,n,void 0===r?.maxResponseBytes?void 0:{"x-tinycloud-max-response-bytes":String(r.maxResponseBytes)});if(!i.ok){if(401===i.status||403===i.status){const r=await this.readAuthorizationText(i),n=function(e){try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return;const r=t,n=r.error,i="object"==typeof n&&null!==n?n:void 0;return no(r.permissionHint)??no(i?.permissionHint)}catch{return}}(r),s="tinycloud.kv"===n?.service&&n.space===this.context.session.spaceId&&n.path===t?po({service:"kv",code:fs.AUTH_UNAUTHORIZED,meta:{status:i.status,resource:`${this.context.session.spaceId}/kv/${t}`,requiredAction:So}}):void 0;return this.authorizationFailure(`Failed to get key ${JSON.stringify(e)}`,i,r,[t],So,s?{permissionHint:n,...s}:{})}if(404===i.status)return this.classifyNotFound(i,e);const r=await i.text();if(413===i.status)return ms(gs(fs.KV_RESPONSE_TOO_LARGE,`KV value at key ${JSON.stringify(e)} exceeds the requested response limit`,"kv",{meta:{status:i.status,statusText:i.statusText}}));const n=`Failed to get key ${JSON.stringify(e)}: ${i.status} - ${r}`,s=so("kv",n,i,r);return ms(s||gs(fs.NETWORK_ERROR,n,"kv",{meta:{status:i.status,statusText:i.statusText}}))}return ps({data:await this.parseResponse(i,r?.raw,r?.binary),headers:this.createResponseHeaders(i.headers),...i.retry&&{retry:i.retry}})}async batchGet(e,t){return this.withTelemetry("batchGet",String(e.length),()=>this.batchRead(e,So,t))}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ms(io("kv"));if(void 0!==r?.ifMatch&&void 0!==r.ifNoneMatch)return ms(gs(fs.INVALID_INPUT,"KV put cannot combine ifMatch and ifNoneMatch","kv"));const n=this.getFullPath(e,r?.prefix),i=this.serializePutValue(t,r?.contentType),s=this.createRequestSignal(r?.signal,r?.timeout);try{const t=()=>this.putToNetwork(e,n,i,r,s.signal);return null===this.readThrough?await t():await this.readThrough.write({op:"put",space:this.context.session.spaceId,entries:[{path:n,body:i}],signal:s.signal,conditional:void 0!==r?.ifMatch||void 0!==r?.ifNoneMatch,network:t})}catch(e){return ms(xo("kv",e))}finally{s.dispose()}})}async putToNetwork(e,t,r,n,i){const s=await this.invokeOperation(t,Io,r,i,{...void 0===n?.ifMatch?{}:{"if-match":n.ifMatch},...void 0===n?.ifNoneMatch?{}:{"if-none-match":n.ifNoneMatch}});if(401===s.status||403===s.status)return this.authorizationFailure(`Failed to put key ${JSON.stringify(e)}`,s,await this.readAuthorizationText(s),[t],Io);if(!s.ok){const t=await s.text();if(412===s.status)return ms(gs(fs.KV_PRECONDITION_FAILED,`KV precondition failed for key ${JSON.stringify(e)}`,"kv",{meta:{status:s.status,statusText:s.statusText}}));const r=`Failed to put key ${JSON.stringify(e)}: ${s.status} - ${t}`,n=so("kv",r,s,t);if(n)return ms(n);return this.handleQuotaErrorResponse(s,t,e)||ms(gs(fs.KV_WRITE_FAILED,r,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return ps({data:void 0,headers:this.createResponseHeaders(s.headers),...s.retry&&{retry:s.retry}})}async batchPut(e,t){return this.withTelemetry("batchPut",String(e.length),async()=>{if(null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ms(io("kv"));if(0===e.length)return ps({written:[],count:0});if(!this.context.invokeAny)return ms(gs(fs.INVALID_INPUT,"KV batchPut requires SDK runtime support for multi-resource invocations","kv"));const r=this.context.session,n=e.map(e=>this.getFullPath(e.key,t?.prefix)),i=new Set;for(const e of n){if(i.has(e))return ms(gs(fs.INVALID_INPUT,`KV batchPut received duplicate key after prefix resolution: ${e}`,"kv"));i.add(e)}const s=this.createRequestSignal(t?.signal,t?.timeout);try{const t=()=>this.batchPutToNetwork(e,n,s.signal);if(null===this.readThrough)return await t();const i=e.map((e,t)=>({path:n[t],body:this.serializeBatchPutValue(e)}));return await this.readThrough.write({op:"batchPut",space:r.spaceId,entries:i,signal:s.signal,network:()=>this.batchPutToNetwork(e,n,s.signal,i)})}catch(e){const t=xo("kv",e);return ms({...t,meta:{...t.meta,requestMayHaveDispatched:!1}})}finally{s.dispose()}})}async batchPutToNetwork(e,t,r,n){const i=this.context.session;let s=!1;try{const o=new FormData;for(let r=0;r<e.length;r++)o.append(Lo(t[r]),n?.[r]?.body??this.serializeBatchPutValue(e[r]));const a=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.invokeAny(i,t.map(e=>({spaceId:i.spaceId,service:"kv",path:e,action:Io})));return s=!0,e},{body:o,signal:r});if(!a.ok){let r;try{r=await a.text()}catch(t){const r=t instanceof Error?t:new Error(String(t));return ms(gs(fs.KV_WRITE_FAILED,`Failed to batch put ${e.length} key(s): ${a.status} - <response body could not be read: ${r.message}>`,"kv",{cause:r,meta:{status:a.status,statusText:a.statusText}}))}if(401===a.status||403===a.status)return this.authorizationFailure(`Failed to batch put ${e.length} key(s)`,a,r,t,Io);return this.handleQuotaErrorResponse(a,r,"batch")||ms(gs(fs.KV_WRITE_FAILED,`Failed to batch put ${e.length} key(s): ${a.status} - ${r}`,"kv",{meta:{status:a.status,statusText:a.statusText}}))}let c;try{c=await a.json()}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=ao(t);return ms(gs(r?fs.TIMEOUT:fs.NETWORK_ERROR,r?`KV batchPut response body did not arrive in time: ${t.message}`:`KV batchPut response was not valid JSON: ${t.message}`,"kv",{cause:t,meta:{...r?{timeoutMs:t.timeoutMs}:{},requestMayHaveDispatched:!0,responseReceived:!0,status:a.status,outcome:"batch-unconfirmed"}}))}const u=this.normalizeBatchPutResponse(c);if(!u)return ms(gs(fs.NETWORK_ERROR,"KV batchPut response did not include matching written keys and count","kv",{meta:{requestMayHaveDispatched:!0,responseReceived:!0,status:a.status,outcome:"batch-unconfirmed"}}));const l=new Set(t),h=new Set(u.written);return u.count===t.length&&u.written.length===t.length&&h.size===t.length&&u.written.every(e=>l.has(e))?ps(u):ms(gs(fs.NETWORK_ERROR,`KV batchPut response did not confirm all ${t.length} requested key(s) were written`,"kv",{meta:{requestMayHaveDispatched:!0,responseReceived:!0,status:a.status,outcome:"batch-unconfirmed"}}))}catch(e){const t=xo("kv",e);return ms({...t,meta:{...t.meta,requestMayHaveDispatched:s}})}}async list(e){return this.withTelemetry("list",e?.prefix,async()=>{if("network"!==e?.source&&null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ms(io("kv"));if(void 0!==e?.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return ms(gs(fs.INVALID_INPUT,"KV list limit must be an integer from 1 through 1000","kv"));let t=e?.prefix??this._config.prefix??"";e?.path&&(t=t?`${t}/${e.path}`:e.path);const r=this.createRequestSignal(e?.signal,e?.timeout);try{const n=()=>this.listFromNetwork(t,e,r.signal);let i;if("network"===e?.source){const e=this.readThrough;if(null===e)i=await n();else{let r="error";const s=Date.now();try{i=await n(),r=i.ok?"found":"error"}finally{try{e.observeNetworkRequested({op:"list",space:this.context.session.spaceId,path:t,reason:"NETWORK_REQUESTED",outcome:r,latencyMs:Date.now()-s})}catch{}}}}else i=null===this.readThrough?await n():await this.readThrough.list({space:this.context.session.spaceId,listPath:t,options:e,signal:r.signal,network:n});return i.ok?this.finishList(i.data,t,e?.removePrefix):i}catch(e){return ms(xo("kv",e))}finally{r.dispose()}})}async listFromNetwork(e,t,r){const n=await this.invokeOperation(e,No,void 0,r,void 0===t?.limit&&void 0===t?.cursor?void 0:{...void 0===t?.limit?{}:{"x-tinycloud-limit":String(t.limit)},...void 0===t?.cursor?{}:{"x-tinycloud-cursor":t.cursor}});if(!n.ok){if(401===n.status||403===n.status)return this.authorizationFailure("Failed to list keys",n,await this.readAuthorizationText(n),[e],No);const t=await n.text(),r=`Failed to list keys: ${n.status} - ${t}`,i=so("kv",r,n,t);return ms(i||gs(fs.NETWORK_ERROR,r,"kv",{meta:{status:n.status,statusText:n.statusText}}))}return ps({keys:await this.parseResponse(n,t?.raw)??[],...null===n.headers.get("x-tinycloud-truncated")?{}:{truncated:"true"===n.headers.get("x-tinycloud-truncated")},...null===n.headers.get("x-tinycloud-next-cursor")?{}:{nextCursor:n.headers.get("x-tinycloud-next-cursor")??void 0}})}finishList(e,t,r){let n=e.keys;if(r&&t){const e=t.endsWith("/")?t:`${t}/`;n=n.map(t=>t.startsWith(e)?t.slice(e.length):t)}return ps({keys:n,...void 0===e.truncated?{}:{truncated:e.truncated},...void 0===e.nextCursor?{}:{nextCursor:e.nextCursor}})}async changes(e){return this.withTelemetry("changes",e?.prefix,async()=>{if(!this.requireAuth())return ms(io("kv"));if("string"!=typeof e?.prefix||0===e.prefix.length)return ms(gs(fs.INVALID_INPUT,"KV changes prefix must be a non-empty string","kv"));if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return ms(gs(fs.INVALID_INPUT,"KV changes limit must be an integer from 1 through 1000","kv"));const t="/"===e.prefix?"":e.prefix,r={};void 0!==e.limit&&(r["x-tinycloud-limit"]=String(e.limit)),void 0!==e.cursor&&(r["x-tinycloud-cursor"]=e.cursor),void 0!==e.retentionGrant&&(r["x-tinycloud-retention-grant"]=e.retentionGrant);const n=this.createRequestSignal(e.signal,e.timeout);try{const i=await this.invokeOperation(t,Co,void 0,n.signal,r);if(!i.ok)return await this.changesFailure(i,e.prefix,n.signal);const s=await i.text();let o;try{o=JSON.parse(s)}catch{o=void 0}const a=this.normalizeChangesResponse(o,e.prefix);return a?ps(a):ms(gs(fs.NETWORK_ERROR,"KV changes response was not a tinycloud.kv/sync page","kv",{meta:{status:i.status,statusText:i.statusText}}))}catch(e){return ms(xo("kv",e))}finally{n.dispose()}})}async changesFailure(e,t,r){if(404===e.status)return this.classifyNotFound(e,t);let n;try{n=await e.text()}catch(e){if(r.aborted)throw e;n=""}const i={status:e.status,statusText:e.statusText};let s,o;try{const e=JSON.parse(n),t=Po(e)?e.error:void 0;Po(t)&&("string"==typeof t.code&&(o=t.code),"string"==typeof t.reason&&(s=t.reason))}catch{}const a=`Failed to read KV changes for ${JSON.stringify(t)}`;if(410===e.status)return ms(gs(fs.KV_SYNC_RESET_REQUIRED,`${a}: the node requires a reset (${s??"reason not given"}); discard sync state and restart without a cursor`,"kv",{meta:{...i,reason:s}}));if(403===e.status&&"RETENTION_GRANT_REFUSED"===o)return ms(gs(fs.KV_RETENTION_GRANT_REFUSED,`${a}: the retention grant was refused (${s??"reason not given"})`,"kv",{meta:{...i,reason:s}}));if(401===e.status){const e=function(e){const t=Do.exec(function(e){const t=e.trim();if(!t.startsWith("{"))return t;try{const e=JSON.parse(t);if(Po(e)&&"string"==typeof e.code&&Bo.has(e.code)&&"string"==typeof e.error)return e.error}catch{}return t}(e));if(null!==t)return void 0!==t[1]?fs.AUTH_DELEGATION_REVOKED:fs.AUTH_DELEGATION_ANCESTOR_REVOKED}(n);if(void 0!==e)return ms(gs(e,`${a}: 401 - ${n}`,"kv",{meta:i}))}return 401===e.status||403===e.status?this.authorizationFailure(a,e,n,[t],Co):ms(gs(400===e.status?fs.INVALID_INPUT:fs.NETWORK_ERROR,`${a}: ${e.status} - ${n}`,"kv",{meta:i}))}normalizeChangesResponse(e,t){if(!Po(e))return;const{changes:r,more:n,cursor:i,source:s,authority:o}=e;if(!Array.isArray(r)||"boolean"!=typeof n||"string"!=typeof i||!Po(s)||"string"!=typeof s.nodeDid||"string"!=typeof s.space||"string"!=typeof s.prefix||!Po(o))return;const{notBefore:a,expiresAt:c,retainUntil:u}=o;if(null!==a&&"string"!=typeof a||null!==c&&"string"!=typeof c||null!==u&&"string"!=typeof u)return;const l=[];for(const e of r){if(!Po(e)||"string"!=typeof e.key)return;if(!0===e.deleted){l.push({key:e.key,deleted:!0});continue}const{metadata:t}=e;if(!1!==e.deleted||"string"!=typeof e.etag||!Po(t)||!Object.values(t).every(e=>"string"==typeof e))return;l.push({key:e.key,deleted:!1,etag:e.etag,metadata:t})}return{changes:l,more:n,cursor:i,source:{nodeDid:s.nodeDid,space:s.space,prefix:"/"===t&&""===s.prefix?"/":s.prefix},authority:{notBefore:a,expiresAt:c,retainUntil:u}}}async delete(e,t){return this.withTelemetry("delete",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ms(io("kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const i=()=>this.deleteFromNetwork(e,r,t,n.signal);return null===this.readThrough?await i():await this.readThrough.write({op:"delete",space:this.context.session.spaceId,entries:[{path:r}],signal:n.signal,conditional:void 0!==t?.ifMatch,network:i})}catch(e){return ms(xo("kv",e))}finally{n.dispose()}})}async deleteFromNetwork(e,t,r,n){const i=await this.invokeOperation(t,Ro,void 0,n,void 0===r?.ifMatch?void 0:{"if-match":r.ifMatch});if(!i.ok){if(401===i.status||403===i.status)return this.authorizationFailure(`Failed to delete key ${JSON.stringify(e)}`,i,await this.readAuthorizationText(i),[t],Ro);if(404===i.status)return this.classifyNotFound(i,e);const r=await i.text();if(412===i.status)return ms(gs(fs.KV_PRECONDITION_FAILED,`KV precondition failed for key ${JSON.stringify(e)}`,"kv",{meta:{status:i.status,statusText:i.statusText}}));const n=`Failed to delete key ${JSON.stringify(e)}: ${i.status} - ${r}`,s=so("kv",n,i,r);return ms(s||gs(fs.NETWORK_ERROR,n,"kv",{meta:{status:i.status,statusText:i.statusText}}))}return ps({data:void 0,headers:this.createResponseHeaders(i.headers),...i.retry&&{retry:i.retry}})}async head(e,t){return this.withTelemetry("head",e,async()=>{if(!this.requireAuth())return ms(io("kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeOperation(r,Oo,void 0,n.signal);if(!t.ok){if(401===t.status||403===t.status)return this.authorizationFailure(`Failed to get metadata for key ${JSON.stringify(e)}`,t,await this.readAuthorizationText(t),[r],Oo);if(404===t.status)return await this.classifyNotFound(t,e);const n=await t.text(),i=`Failed to get metadata for key ${JSON.stringify(e)}: ${t.status} - ${n}`,s=so("kv",i,t,n);return ms(s||gs(fs.NETWORK_ERROR,i,"kv",{meta:{status:t.status,statusText:t.statusText}}))}return ps({data:void 0,headers:this.createResponseHeaders(t.headers)})}catch(e){return ms(xo("kv",e))}finally{n.dispose()}})}async batchHead(e,t){return this.withTelemetry("batchHead",String(e.length),()=>this.batchRead(e,Oo,t))}async createSignedReadUrl(e,t){return this.withTelemetry("createSignedReadUrl",e,async()=>{if(!this.requireAuth())return ms(io("kv"));const r=this.getFullPath(e,t?.prefix),n=this.context.session,i={space:n.spaceId,path:r,ttl_seconds:t?.expiresInSeconds??Math.ceil(300)};void 0!==t?.contentHash&&(i.content_hash=t.contentHash),void 0!==t?.etag&&(i.etag=t.etag);const s=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeWithRetry(`${this.host}/signed/kv`,()=>this.context.invoke(n,"kv",r,So),{headers:{"content-type":"application/json"},body:JSON.stringify(i),signal:s.signal});if(!t.ok)return await this.createSignedReadUrlError(t,e,r);const o=this.normalizeSignedReadUrlResponse(await t.json());return o?ps(o):ms(gs(fs.NETWORK_ERROR,"Signed read URL response did not include url, ticketId, and expiresAt","kv"))}catch(e){return ms(xo("kv",e))}finally{s.dispose()}})}withPrefix(e){return new To(this,e)}}).serviceName="kv";var Fo=class{constructor(e,t){this.service=e,this.dbName=t}apply(e){return this.service.applyMigrationsOnDb(this.dbName,e)}},$o=class{constructor(e,t){this.service=e,this.name=t,this.migrations=new Fo(e,t)}async query(e,t,r){return this.service.queryOnDb(this.name,e,t,r)}async execute(e,t,r){return this.service.executeOnDb(this.name,e,t,r)}async batch(e,t){return this.service.batchOnDb(this.name,e,t)}async executeStatement(e,t,r){return this.service.executeStatementOnDb(this.name,e,t,r)}async export(e){return this.service.exportDb(this.name,e)}},Ho={READ:q.READ,WRITE:q.WRITE,SCHEMA:q.SCHEMA,ADMIN:q.ADMIN,SELECT:q.SELECT,EXECUTE:q.EXECUTE,EXPORT:q.EXPORT,ALL:q.ALL},Ko=new Set(["alter","create","drop"]),qo="__tinycloud_sql_migrations",jo=`CREATE TABLE IF NOT EXISTS ${qo} (\n key TEXT PRIMARY KEY,\n namespace TEXT NOT NULL,\n id TEXT NOT NULL,\n applied_at TEXT NOT NULL,\n statement_count INTEGER NOT NULL\n)`,zo="tinycloud.sql.migrations",Vo="000_metadata";function Go(e){return e.map(e=>e instanceof Uint8Array?Array.from(e):e)}function Wo(e){return/no such table/i.test(e)}function Jo(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Zo(e,t){return Array.isArray(e)?e[t]:e&&"object"==typeof e?Object.values(e)[t]:void 0}(class extends _o{constructor(e={}){super(),this.migrationLocks=new Map,this._config=e}get config(){return this._config}get defaultDbName(){return this._config.defaultDatabase??"default"}get host(){return this.context.hosts[0]}db(e){return new $o(this,e??this.defaultDbName)}async query(e,t,r){return this.queryOnDb(this.defaultDbName,e,t,r)}async execute(e,t,r){return this.executeOnDb(this.defaultDbName,e,t,r)}async batch(e,t){return this.batchOnDb(this.defaultDbName,e,t)}async applyMigrationsOnDb(e,t){const r=function(e){if(!e||"object"!=typeof e)return"SQL migrations require options";if(!e.namespace||"string"!=typeof e.namespace)return"SQL migrations require a non-empty namespace";if(!Array.isArray(e.migrations))return"SQL migrations require an ordered migrations array";const t=new Set;for(const r of e.migrations){if(!r.id||"string"!=typeof r.id)return"SQL migrations require every migration to have a non-empty id";if(t.has(r.id))return`Duplicate SQL migration id: ${r.id}`;if(t.add(r.id),!Array.isArray(r.sql))return`SQL migration ${r.id} requires a sql array`;for(const e of r.sql)if("string"!=typeof e){if(!e||"string"!=typeof e.sql||""===e.sql.trim())return`SQL migration ${r.id} contains an invalid statement`}else if(""===e.trim())return`SQL migration ${r.id} contains an empty statement`}return null}(t);if(r)return ms(gs(fs.INVALID_INPUT,r,"sql"));const n=`${e}\0${t.namespace}`,i=this.migrationLocks.get(n);if(i)return i;const s=this.applyMigrationsOnDbUnlocked(e,t);this.migrationLocks.set(n,s);try{return await s}finally{this.migrationLocks.delete(n)}}async queryOnDb(e,t,r,n){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return ms(io("sql"));const i=this.createRequestSignal(n?.signal);try{const s={action:"query",sql:t,params:Go(r??[])};void 0!==n?.maxRows&&(s.maxRows=n.maxRows),void 0!==n?.maxBytes&&(s.maxBytes=n.maxBytes);const o=this.actionForSql(t,Ho.READ),a=await this.invokeSQL(e,o,s,i.signal);if(!a.ok){const t=await this.handleErrorResponse(a,"query",e,[o]);return this.redactFailure(t,n?.redactErrors,a.status)}return ps(await a.json())}catch(e){return this.redactFailure(ms(xo("sql",e)),n?.redactErrors)}finally{i.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return ms(io("sql"));const i=this.createRequestSignal(n?.signal);try{const s={action:"execute",sql:t,params:Go(r??[])};n?.schema&&(s.schema=n.schema);const o=[this.actionForSql(t,Ho.WRITE),...(n?.schema??[]).map(e=>this.actionForSql(e,Ho.SCHEMA))],a=this.dedupeActions(o),c=await this.invokeSQL(e,a,s,i.signal);if(!c.ok){const t=await this.handleErrorResponse(c,"execute",e,a);return this.redactFailure(t,n?.redactErrors,c.status)}return ps(await c.json())}catch(e){return this.redactFailure(ms(xo("sql",e)),n?.redactErrors)}finally{i.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return ms(io("sql"));const n=this.createRequestSignal(r?.signal);try{const i=this.actionsForSqlBatch(t),s=await this.invokeSQL(e,i,{action:"batch",statements:t},n.signal);if(!s.ok){const t=await this.handleErrorResponse(s,"batch",e,i);return this.redactFailure(t,r?.redactErrors,s.status)}return ps(await s.json())}catch(e){return this.redactFailure(ms(xo("sql",e)),r?.redactErrors)}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return ms(io("sql"));const i=this.createRequestSignal(n?.signal);try{const n=await this.invokeSQL(e,Ho.WRITE,{action:"execute_statement",name:t,params:r??[]},i.signal);return n.ok?ps(await n.json()):await this.handleErrorResponse(n,"executeStatement",e,[Ho.WRITE])}catch(e){return ms(xo("sql",e))}finally{i.dispose()}})}async exportDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return ms(io("sql"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeSQL(e,Ho.READ,{action:"export"},r.signal);if(!t.ok)return await this.handleErrorResponse(t,"export",e,[Ho.READ]);const n=t;return"function"==typeof n.blob?ps(await n.blob()):ps(await t.text())}catch(e){return ms(xo("sql",e))}finally{r.dispose()}})}async applyMigrationsOnDbUnlocked(e,t){return this.withTelemetry("migrations.apply",e,async()=>{const r=await this.queryOnDb(e,`SELECT name FROM sqlite_master WHERE type='table' AND name='${qo}'`,[],{signal:t.signal});let n=r.ok?0===r.data.rows.length:r.error.code===fs.SQL_DATABASE_NOT_FOUND||Wo(r.error.message);if(!r.ok&&!n)return r;const i=new Set;if(!n){const r=await this.queryOnDb(e,`SELECT id FROM ${qo} WHERE namespace = ? ORDER BY applied_at, id`,[t.namespace],{signal:t.signal});if(n=!r.ok&&(r.error.code===fs.SQL_DATABASE_NOT_FOUND||Wo(r.error.message)),!r.ok&&!n)return r;if(r.ok)for(const e of r.data.rows){const t=Zo(e,0);"string"==typeof t&&i.add(t)}}const s=t.migrations.filter(e=>i.has(e.id)).map(e=>e.id),o=t.migrations.filter(e=>!i.has(e.id)),a=[];if(o.length>0&&n){const r=await this.ensureMigrationsTable(e,t.signal);if(!r.ok)return r}for(const r of o){const n=await this.applyOneMigration(e,t.namespace,r,t.signal);if(!n.ok)return n;a.push(r.id)}return ps({database:e,namespace:t.namespace,status:a.length>0?"applied":"already_current",applied:a,skipped:s})})}async applyOneMigration(e,t,r,n){const i=[...r.sql.map(e=>"string"==typeof e?{sql:e}:e),{sql:`INSERT OR REPLACE INTO ${qo} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[Jo(t,r.id),t,r.id,(new Date).toISOString(),r.sql.length]}],s=await this.batchOnDb(e,i,{signal:n});return s.ok?ps(void 0):s}async ensureMigrationsTable(e,t){const r=await this.batchOnDb(e,[{sql:jo},{sql:`INSERT OR REPLACE INTO ${qo} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[Jo(zo,Vo),zo,Vo,(new Date).toISOString(),1]}],{signal:t});return r.ok?ps(void 0):r}async invokeSQL(e,t,r,n){const i=Array.isArray(t)?t:[t];return this.invokeWithRetry(`${this.host}/invoke`,()=>{const t=this.context.session;return 1===i.length?this.context.invoke(t,"sql",e,i[0]):this.invokeSQLAny(t,e,i)},{headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n})}actionForSql(e,t){const r=function(e){let t=0;for(;t<e.length;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(e.startsWith("--",t)){const r=e.indexOf("\n",t+2);if(-1===r)return;t=r+1;continue}if(e.startsWith("/*",t)){const r=e.indexOf("*/",t+2);if(-1===r)return;t=r+2;continue}break}const r=/^[A-Za-z_]+/.exec(e.slice(t));return r?.[0].toLowerCase()}(e);return"pragma"===r?Ho.ADMIN:void 0!==r&&Ko.has(r)?Ho.SCHEMA:t}actionsForSqlBatch(e){return this.dedupeActions(e.map(e=>this.actionForSql(e.sql,Ho.WRITE)))}dedupeActions(e){return[...new Set(e)]}invokeSQLAny(e,t,r){if(!this.context.invokeAny)throw new Error(`SQL operation requires multiple permissions (${r.join(", ")}) but this SDK runtime does not support multi-resource invocations`);return this.context.invokeAny(e,r.map(r=>({spaceId:e.spaceId,service:"sql",path:t,action:r})))}redactFailure(e,t,r){if(!t||e.ok)return e;const n=e.error.code,i="string"==typeof n&&Object.prototype.hasOwnProperty.call(fs,n)?n:fs.SQL_ERROR,s="number"==typeof r&&Number.isInteger(r)&&r>=400&&r<=599?r:void 0;return ms(gs(i,"SQL operation failed","sql",void 0===s?void 0:{meta:{status:s}}))}async handleErrorResponse(e,t,r,n){const i=await e.text(),s=Ks(e.status,e.statusText,i);if(402===e.status)return ms(ko("sql",402,s,i));if(413===e.status&&Ao(i))return ms(ko("sql",413,s,i));const o=so("sql",`SQL ${t} failed: ${e.status} - ${i}`,e,i);if(o)return ms(o);const a=$s(i),c=Uo("sql",t,e.status,i)??this.mapHttpStatusToErrorCode(e.status,a.error),u=Hs("SQL",t,e.status,i,a);if(401===e.status){const{action:e}=uo(i);e&&n.includes(e)&&(s.requiredAction=e,s.resource=`${this.context.session.spaceId}/sql/${r}`)}return ms(gs(c,u,"sql",{meta:s}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return fs.SQL_ERROR;case 401:return fs.AUTH_UNAUTHORIZED;case 403:return"sql_readonly_violation"===t?fs.SQL_READONLY_VIOLATION:fs.SQL_PERMISSION_DENIED;case 404:return fs.SQL_DATABASE_NOT_FOUND;case 413:return fs.SQL_RESPONSE_TOO_LARGE;case 429:return fs.SQL_QUOTA_EXCEEDED;default:return fs.NETWORK_ERROR}}}).serviceName="sql";var Yo=class{constructor(e,t){this.service=e,this.name=t}async query(e,t,r){return this.service.queryOnDb(this.name,e,t,r)}async queryArrow(e,t,r){return this.service.queryArrowOnDb(this.name,e,t,r)}async execute(e,t,r){return this.service.executeOnDb(this.name,e,t,r)}async batch(e,t){return this.service.batchOnDb(this.name,e,t)}async executeStatement(e,t,r){return this.service.executeStatementOnDb(this.name,e,t,r)}async describe(e){return this.service.describeDb(this.name,e)}async export(e){return this.service.exportOnDb(this.name,e)}async import(e,t){return this.service.importOnDb(this.name,e,t)}},Qo={READ:j.READ,WRITE:j.WRITE,ADMIN:j.ADMIN,DESCRIBE:j.DESCRIBE,EXPORT:j.EXPORT,IMPORT:j.IMPORT,EXECUTE:j.EXECUTE,ALL:j.ALL};(class extends _o{constructor(e={}){super(),this._config=e}get config(){return this._config}get defaultDbName(){return this._config.defaultDatabase??"default"}get host(){return this.context.hosts[0]}db(e){return new Yo(this,e??this.defaultDbName)}async query(e,t,r){return this.queryOnDb(this.defaultDbName,e,t,r)}async queryArrow(e,t,r){return this.queryArrowOnDb(this.defaultDbName,e,t,r)}async execute(e,t,r){return this.executeOnDb(this.defaultDbName,e,t,r)}async batch(e,t){return this.batchOnDb(this.defaultDbName,e,t)}async queryOnDb(e,t,r,n){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return ms(io("duckdb"));const i=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Qo.READ,{action:"query",sql:t,params:r??[]},i.signal);return n.ok?ps(await n.json()):await this.handleErrorResponse(n,"query")}catch(e){return ms(xo("duckdb",e))}finally{i.dispose()}})}async queryArrowOnDb(e,t,r,n){return this.withTelemetry("queryArrow",e,async()=>{if(!this.requireAuth())return ms(io("duckdb"));const i=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Qo.READ,{action:"query",sql:t,params:r??[]},i.signal,{Accept:"application/vnd.apache.arrow.stream"});return n.ok?ps(await n.arrayBuffer()):await this.handleErrorResponse(n,"queryArrow")}catch(e){return ms(xo("duckdb",e))}finally{i.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return ms(io("duckdb"));const i=this.createRequestSignal(n?.signal);try{const s={action:"execute",sql:t,params:r??[]};n?.schema&&(s.schema=n.schema);const o=await this.invokeDuckDb(e,Qo.WRITE,s,i.signal);return o.ok?ps(await o.json()):await this.handleErrorResponse(o,"execute")}catch(e){return ms(xo("duckdb",e))}finally{i.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return ms(io("duckdb"));const n=this.createRequestSignal(r?.signal);try{const i={action:"batch",statements:t};void 0!==r?.transactional&&(i.transactional=r.transactional);const s=await this.invokeDuckDb(e,Qo.WRITE,i,n.signal);return s.ok?ps(await s.json()):await this.handleErrorResponse(s,"batch")}catch(e){return ms(xo("duckdb",e))}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return ms(io("duckdb"));const i=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Qo.WRITE,{action:"executeStatement",name:t,params:r??[]},i.signal);return n.ok?ps(await n.json()):await this.handleErrorResponse(n,"executeStatement")}catch(e){return ms(xo("duckdb",e))}finally{i.dispose()}})}async describeDb(e,t){return this.withTelemetry("describe",e,async()=>{if(!this.requireAuth())return ms(io("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,Qo.READ,{action:"describe"},r.signal);return t.ok?ps(await t.json()):await this.handleErrorResponse(t,"describe")}catch(e){return ms(xo("duckdb",e))}finally{r.dispose()}})}async exportOnDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return ms(io("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,Qo.EXPORT,{action:"export"},r.signal);return t.ok?ps(await t.blob()):await this.handleErrorResponse(t,"export")}catch(e){return ms(xo("duckdb",e))}finally{r.dispose()}})}async importOnDb(e,t,r){return this.withTelemetry("import",e,async()=>{if(!this.requireAuth())return ms(io("duckdb"));const n=this.createRequestSignal(r?.signal);try{const r=await this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,Qo.IMPORT),{headers:{"Content-Type":"application/x-duckdb"},body:new Blob([t]),signal:n.signal});return r.ok?ps(void 0):await this.handleErrorResponse(r,"import")}catch(e){return ms(xo("duckdb",e))}finally{n.dispose()}})}async invokeDuckDb(e,t,r,n,i){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,t),{headers:{"Content-Type":"application/json",...i},body:JSON.stringify(r),signal:n})}async handleErrorResponse(e,t){const r=await e.text(),n=Ks(e.status,e.statusText,r);if(402===e.status)return ms(ko("duckdb",402,n,r));if(413===e.status&&Ao(r))return ms(ko("duckdb",413,n,r));const i=so("duckdb",`DuckDB ${t} failed: ${e.status} - ${r}`,e,r);if(i)return ms(i);const s=$s(r),o=Uo("duckdb",t,e.status,r)??this.mapHttpStatusToErrorCode(e.status,s.error),a=Hs("DuckDB",t,e.status,r,s);if(401===e.status){const{resource:e,action:t}=uo(r);t&&(n.requiredAction=t),e&&(n.resource=e)}return ms(gs(o,a,"duckdb",{meta:n}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return fs.DUCKDB_ERROR;case 401:return fs.AUTH_UNAUTHORIZED;case 403:return"duckdb_readonly_violation"===t?fs.DUCKDB_READONLY_VIOLATION:fs.DUCKDB_PERMISSION_DENIED;case 404:return fs.DUCKDB_DATABASE_NOT_FOUND;case 413:return fs.DUCKDB_RESPONSE_TOO_LARGE;case 429:return fs.DUCKDB_QUOTA_EXCEEDED;default:return fs.NETWORK_ERROR}}}).serviceName="duckdb";var Xo=class{constructor(){this.values=[],this.waiters=[],this.closed=!1}[Symbol.asyncIterator](){return this}push(e){if(this.closed)return;const t=this.waiters.shift();t?t.resolve({value:e,done:!1}):this.values.push(e)}close(){if(!this.closed)for(this.closed=!0;this.waiters.length>0;){const e=this.waiters.shift();e?.resolve({value:void 0,done:!0})}}fail(e){if(!this.closed)for(this.closed=!0,this.failure=e;this.waiters.length>0;){const t=this.waiters.shift();t?.reject(e)}}next(){if(this.values.length>0){const e=this.values.shift();return Promise.resolve({value:e,done:!1})}return void 0!==this.failure?Promise.reject(this.failure):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function ea(e,t){const r=ga(t);return r?`${e}/${r}`:e}function ta(e){return"number"==typeof e&&e>=400&&e<500&&408!==e&&429!==e}(class extends _o{constructor(e={}){super(),this._subscribers=new Set,this._supervising=!1,this._sessionGeneration=0,this._streamGeneration=0,this._config=e}get config(){return this._config}get host(){return this._config.host??this.context.hosts[0]}async*subscribe(e,t={}){if(!this.requireAuth())throw new Error("Authentication required for hooks subscription");if(0===e.length)throw new Error("At least one hook subscription is required");const r=e.map(fa),n={requested:r,signatures:r.map(pa),ttlSeconds:t.ttlSeconds,onReady:t.onReady,queue:new Xo},i=()=>{this._subscribers.delete(n),n.queue.close(),this.wake()},{signal:s}=t;if(!s?.aborted){s?.addEventListener("abort",i,{once:!0}),this._subscribers.add(n),this.wake(),this._readyStream&&this.notifyReady(n,this._readyStream);try{for await(const e of n.queue)yield e}finally{s?.removeEventListener("abort",i),i()}}}async register(e){if(!this.requireAuth())return ms(io("hooks"));if("string"!=typeof e.secret||0===e.secret.trim().length)return ms(gs(fs.INVALID_INPUT,"Webhook secret is required","hooks",{meta:{field:"secret"}}));try{const t=await this.invokeWithRetry(`${this.host}/hooks/webhooks`,()=>this.createHookHeaders("tinycloud.hooks/register",ea(e.service,e.pathPrefix)),{headers:{"content-type":"application/json"},body:JSON.stringify({space:e.space,service:e.service,pathPrefix:ga(e.pathPrefix),abilities:e.abilities??[],callbackUrl:e.callbackUrl,secret:e.secret})});if(!t.ok)return ms(await ya("hooks","failed to register webhook",t));const r=wa(await t.json());return r?ps(r):ms(xo("hooks",new Error("Webhook registration response did not include a record")))}catch(e){return ms(xo("hooks",e))}}async list(e={}){if(!this.requireAuth())return ms(io("hooks"));try{const t=new URLSearchParams;if(e.space&&t.set("space",e.space),e.service&&t.set("service",e.service),e.pathPrefix){const r=ga(e.pathPrefix);r&&t.set("prefix",r)}const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks${t.size>0?`?${t.toString()}`:""}`,()=>this.createHookHeaders("tinycloud.hooks/list",e.service?ea(e.service,e.pathPrefix):"webhooks"),{method:"GET"});if(!r.ok)return ms(await ya("hooks","failed to list webhooks",r));const n=function(e){if(Array.isArray(e))return e.map(e=>wa(e)).filter(e=>null!==e);if(!e||"object"!=typeof e)return null;const t=e,r=Ea(t.webhooks)??Ea(t.subscriptions)??Ea(t.hooks)??Ea(t.data);if(r)return r;const n=Aa(t);return n?[n]:null}(await r.json());return n?ps(n):ms(xo("hooks",new Error("Webhook list response did not include records")))}catch(e){return ms(xo("hooks",e))}}async unregister(e,t={}){if(!this.requireAuth())return ms(io("hooks"));try{const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks/${encodeURIComponent(e)}`,()=>this.createHookHeaders("tinycloud.hooks/unregister",t.target?ea(t.target.service,t.target.pathPrefix):`webhooks/${e}`),{method:"DELETE"});return r.ok?ps(void 0):ms(await ya("hooks","failed to unregister webhook",r))}catch(e){return ms(xo("hooks",e))}}wake(){const e=this._phase;e&&e.key!==this.plan()?.key&&e.interrupt.abort(),this._supervising||0===this._subscribers.size||(this._supervising=!0,this.supervise().catch(()=>this.collapse()))}async supervise(){let e=0;for(;;){const t=this.plan();if(!t)return void(this._supervising=!1);const r={openedAt:0,delivered:!1},n=await this.phase(t.key,e=>this.attempt(t,e,r));(r.delivered||r.openedAt>0&&performance.now()-r.openedAt>=5e3)&&(e=0),n&&this.plan()?.key===t.key&&("stopped"!==n.kind?"refused"===n.kind&&n.terminal?(this.release(n.error),this.report(n.error)):("ended"!==n.kind&&this.report(n.error),e+=1,await this.phase(t.key,t=>this.pause(e,t))):this.release())}}async phase(e,t){const r=new AbortController;this._phase={key:e,interrupt:r};try{this.plan()?.key!==e&&r.abort();const n=await t(r.signal);return r.signal.aborted?void 0:n}finally{this._phase=void 0,r.abort()}}async attempt(e,t,r){let n,i="mint";const s=++this._streamGeneration,o=()=>!t.aborted&&!n?.signal.aborted&&this.plan()?.key===e.key;try{const a=this.context,c=a.abortSignal;if(this._lastContextSignal=c,!a.isAuthenticated||c?.aborted)return{kind:"stopped"};n=this.createRequestSignal(t,0);const u=this.host,l=function(e){return Array.isArray(e)?Object.fromEntries(e):{...e}}(this.createInvokeHeaders(e.subscriptions)),h=await na(n.signal,()=>a.fetch(`${u}/hooks/tickets`,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify({subscriptions:e.subscriptions,ttlSeconds:e.ttlSeconds}),signal:n.signal}));if(!o())return{kind:"stopped"};if(!h.ok){const e=h.status,t=Object.entries(l).find(([e])=>"authorization"===e.toLowerCase())?.[1],r=function(e,t){if((401===e||403===e)&&t)try{const e=t.split(".")[1],{prf:r,exp:n,nbf:i,iat:s}=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/"))),o=Date.now()/1e3;if(Number.isFinite(n)&&n<=o||Number.isFinite(i)&&i>o||Number.isFinite(s)&&s>o)return Qs;if(Number.isFinite(n)&&(null==i||Number.isFinite(i))&&(null==s||Number.isFinite(s))&&Array.isArray(r)&&1===r.length&&"string"==typeof r[0]&&r[0])return r[0]}catch{}}(e,t),i=await na(n.signal,()=>ya("hooks","failed to mint hook ticket",h,r));return o()?{kind:"refused",terminal:ta(e),error:i}:{kind:"stopped"}}const d=await na(n.signal,()=>h.json());if(!o())return{kind:"stopped"};const f=null!==d&&"object"==typeof d&&"ticket"in d?d.ticket:void 0;if("string"!=typeof f||0===f.length)throw new Error("Hook ticket response did not include a ticket");if(i="open",!o())return{kind:"stopped"};const p=await na(n.signal,()=>a.fetch(`${u}/hooks/events?ticket=${encodeURIComponent(f)}`,{method:"GET",headers:{accept:"text/event-stream"},signal:n.signal}));if(!o())return{kind:"stopped"};if(!p.ok)return{kind:"refused",terminal:!1,error:sa(p.status)};r.openedAt=performance.now();const m=async function*(e,t){if(!e)throw new Error("Hook stream response does not expose a readable body");const r=new TextDecoder;let n="";for await(const i of async function*(e,t){const r=e;if("function"==typeof r?.[Symbol.asyncIterator]){const e=r[Symbol.asyncIterator](),n=()=>{try{const t=e.return?.();t&&Promise.resolve(t).then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",n,{once:!0});try{for(;!t?.aborted;){const t=await e.next();if(t.done)break;yield t.value}}finally{t?.removeEventListener("abort",n),n()}return}const n=e;if("function"!=typeof n.getReader)throw new Error("Unsupported hook stream body type");const i=n.getReader(),s=()=>{try{const e=i.cancel?.();e&&e.then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",s,{once:!0});try{for(;!t?.aborted;){const{done:e,value:t}=await i.read();if(e)break;t&&(yield t)}}finally{t?.removeEventListener("abort",s),s(),i.releaseLock?.()}}(e,t)){n+=r.decode(i,{stream:!0}).replace(/\r\n/g,"\n");let e=n.indexOf("\n\n");for(;e>=0;){const t=n.slice(0,e);n=n.slice(e+2);const r=va(t);r&&(yield r),e=n.indexOf("\n\n")}}n+=r.decode();const i=va(n.trim());i&&(yield i)}(p.body,n.signal)[Symbol.asyncIterator]();try{for(;;){const t=await na(n.signal,()=>m.next());if(!o())return{kind:"stopped"};if(t.done)break;const i=t.value;if(!i.data)continue;if("ready"===i.event){const t=JSON.parse(i.data);if(null!==t&&"object"==typeof t&&"type"in t&&"ready"===t.type){this._readyStream={key:e.key,generation:s};for(const e of this._subscribers)this.notifyReady(e,this._readyStream)}continue}const a=ba(i);if(!o())return{kind:"stopped"};this.dispatch(a),r.delivered=!0}}finally{const e=m.return?.();e&&Promise.resolve(e).then(()=>{},()=>{})}return o()?{kind:"ended"}:{kind:"stopped"}}catch(e){return n?.signal.aborted||e===ra?{kind:"stopped"}:{kind:"failed",error:aa(i,e)}}finally{this._readyStream?.generation===s&&(this._readyStream=void 0)}}async pause(e,t){try{this._lastContextSignal=this.context.abortSignal}catch{}const r=this._lastContextSignal,n=[],i=[];try{const r=this._config.streamRetry,i=r?.delay?.(e)??function(e){const t=Math.min(250*2**Math.max(0,e-1),3e4);return t/2+Math.random()*(t/2)}(e);n.push((r?.wait??ha)(i,e,t))}catch{n.push(Promise.resolve())}i.push(da(t)),r&&i.push(da(r));try{await Promise.race([...n,...i.map(({promise:e})=>e)])}catch{}finally{for(const e of i)e.dispose()}await new Promise(e=>setTimeout(e,0))}plan(){if(0===this._subscribers.size)return;const e=new Map;let t;for(const r of this._subscribers)r.requested.forEach((t,n)=>e.set(r.signatures[n],t)),"number"==typeof r.ttlSeconds&&(t=Math.min(r.ttlSeconds,t??1/0));const r=[...e.keys()].sort();return{key:JSON.stringify([this._sessionGeneration,r,t??null]),subscriptions:r.map(t=>e.get(t)),ttlSeconds:t}}notifyReady(e,t){if(this._subscribers.has(e)&&e.readyGeneration!==t.generation&&this.plan()?.key===t.key&&!this._phase?.interrupt.signal.aborted){e.readyGeneration=t.generation;try{e.onReady?.()}catch{this.report(gs(fs.INVALID_INPUT,"Hook readiness callback failed","hooks"))}}}dispatch(e){for(const t of this._subscribers)ma(e,t.requested)&&t.queue.push(e)}release(e){const t=[...this._subscribers];this._subscribers.clear();for(const{queue:r}of t)e?r.fail(e):r.close()}report(e){e.meta&&"object"==typeof e.meta&&Object.freeze(e.meta),Object.freeze(e);try{this.emitError(e,"stream")}catch{}}collapse(){this._supervising=!1,this._phase?.interrupt.abort(),this._phase=void 0;const e=gs(fs.NETWORK_ERROR,"hook stream supervisor stopped unexpectedly","hooks");this.report(e),this.release(e)}onSessionChange(e){super.onSessionChange(e),this._sessionGeneration+=1,this.wake()}onSignOut(){super.onSignOut(),this.release(),this.wake()}createHookHeaders(e,t){return this.context.invoke(this.session,"hooks",t,e)}createInvokeHeaders(e){const t=e.map(e=>({spaceId:e.space,service:"hooks",path:e.pathPrefix?`${e.service}/${e.pathPrefix}`:e.service,action:"tinycloud.hooks/subscribe"}));if(this.context.invokeAny)return this.context.invokeAny(this.session,t);if(1===t.length){const e=t[0];return this.context.invoke(this.session,e.service,e.path,e.action)}throw new Error("This SDK runtime does not support multi-scope hook invocations")}}).serviceName="hooks";var ra=Symbol("hooks attempt superseded");async function na(e,t){if(e.aborted)throw"function"!=typeof t&&t.then(ia,()=>{}),ra;const r="function"==typeof t?t():t;return new Promise((t,n)=>{let i=!1;const s=()=>e.removeEventListener("abort",o),o=()=>{i||(i=!0,s(),n(ra))};e.addEventListener("abort",o,{once:!0}),r.then(e=>{i?ia(e):(i=!0,s(),t(e))},e=>{i||(i=!0,s(),n(e))})})}function ia(e){if(e instanceof Response&&e.body)try{e.body.cancel().then(()=>{},()=>{})}catch{}}function sa(e){const t="number"==typeof e?e:void 0;return gs(fs.NETWORK_ERROR,`hook stream open refused: ${t??"unknown status"}`,"hooks",{meta:{phase:"open",status:t}})}var oa=new Set(["Error","TypeError","AbortError","TimeoutError","SyntaxError","RangeError","NetworkError"]);function aa(e,t){const r=la(t,"name"),n="string"==typeof r&&oa.has(r)?r:"Error",i=ua(la(t,"code"))??ua(la(la(t,"cause"),"code"));return gs(fs.NETWORK_ERROR,`hook stream ${e} failed: ${n}${i?` (${i})`:""}`,"hooks",{meta:{phase:e,errorName:n,...i?{errorCode:i}:{}}})}var ca=new Set(["ECONNREFUSED","ECONNRESET","ECONNABORTED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","ENETDOWN","EADDRNOTAVAIL","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CLOSED","UND_ERR_ABORTED","UND_ERR_RESPONSE_STATUS_CODE","ERR_TLS_CERT_ALTNAME_INVALID","CERT_HAS_EXPIRED","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","ERR_SSL_WRONG_VERSION_NUMBER"]);function ua(e){return"string"==typeof e&&ca.has(e)?e:void 0}function la(e,t){if(null!==e&&("object"==typeof e||"function"==typeof e))try{return Reflect.get(e,t)}catch{return}}var ha=(e,t,r)=>((e,t,r=!1)=>new Promise(n=>{const i=()=>{clearTimeout(s),t.removeEventListener("abort",i),n()},s=setTimeout(i,e);r&&s.unref?.(),t.aborted?i():t.addEventListener("abort",i)}))(e,r,!0);function da(e){let t;const r=new Promise(e=>{t=e}),n=()=>t();return e.aborted?t():e.addEventListener("abort",n,{once:!0}),{promise:r,dispose:()=>e.removeEventListener("abort",n)}}function fa(e){return{...e,pathPrefix:"kv"===e.service?ga(e.pathPrefix):e.pathPrefix?.replace(/^\/+/,"")||void 0,abilities:e.abilities?[...e.abilities]:[]}}function pa(e){return JSON.stringify({space:e.space,service:e.service,pathPrefix:e.pathPrefix??"",abilities:[...e.abilities??[]].sort()})}function ma(e,t){return t.some(t=>function(e,t){if(e.space!==t.space)return!1;if(e.service!==t.service)return!1;if("sql"===e.service||"duckdb"===e.service){const r=t.pathPrefix,n=e.databasePath??e.path;if(r&&"/"!==r&&(!n||(r.endsWith("/")?!n.startsWith(r):n!==r)))return!1}else if(t.pathPrefix){const r=t.pathPrefix.endsWith("/")?t.pathPrefix:`${t.pathPrefix}/`;if(e.path&&e.path!==t.pathPrefix&&!e.path.startsWith(r))return!1}const r=t.abilities??[];return!(r.length>0&&!r.includes(e.ability))}(e,t))}function ga(e){if(!e)return;const t=e.replace(/^\/+|\/+$/g,"");return t.length>0?t:void 0}async function ya(e,t,r,n){let i=r.statusText;try{const e=await r.text();e&&(i=e)}catch{}return gs(408===r.status||504===r.status?fs.TIMEOUT:fs.NETWORK_ERROR,`${t}: ${r.status} ${i}`,e,{meta:{status:r.status,statusText:r.statusText,...401===r.status||403===r.status?eo(n,i):void 0}})}function va(e){if(!e)return null;let t,r="message";const n=[];for(const i of e.split("\n")){if(!i||i.startsWith(":"))continue;const[e,...s]=i.split(":"),o=s.join(":").replace(/^ /,"");switch(e){case"event":r=o;break;case"id":t=o;break;case"data":n.push(o)}}return 0===n.length?null:{event:r,id:t,data:n.join("\n")}}function ba(e){const t=JSON.parse(e.data);return{type:"write",id:t.id??e.id??"",space:t.space??"",service:t.service??"",ability:t.ability??"",path:t.path,databasePath:"string"==typeof t.databasePath?t.databasePath:void 0,actor:t.actor??"",epoch:t.epoch??"",eventIndex:t.eventIndex??0,timestamp:t.timestamp??""}}function wa(e){if(!e||"object"!=typeof e)return null;const t=e;return Aa(t)??wa(t.webhook)??wa(t.hook)??wa(t.subscription)??wa(t.data)??null}function Ea(e){return Array.isArray(e)?e.map(e=>wa(e)).filter(e=>null!==e):null}function Aa(e){const t=ka(e,"id"),r=ka(e,"space")??ka(e,"spaceId"),n=ka(e,"service"),i=ka(e,"callbackUrl")??ka(e,"callback_url");return t&&r&&n&&i?{id:t,space:r,service:n,pathPrefix:xa(e,"pathPrefix")??xa(e,"path_prefix"),abilities:Ta(e,"abilities")??Sa(e,"abilitiesJson")??Sa(e,"abilities_json"),callbackUrl:i,active:_a(e,"active")??!0,createdAt:ka(e,"createdAt")??ka(e,"created_at")??(new Date).toISOString(),subscriberDid:xa(e,"subscriberDid")??xa(e,"subscriber_did")}:null}function ka(e,t){const r=e[t];return"string"==typeof r?r:void 0}function xa(e,t){return ka(e,t)}function _a(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function Ta(e,t){const r=e[t];if(!Array.isArray(r))return;const n=r.filter(e=>"string"==typeof e);return n.length===r.length?n:void 0}function Sa(e,t){const r=e[t];if("string"==typeof r)try{const e=JSON.parse(r);if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e);return t.length===e.length?t:void 0}catch{return}}function Ia(e){return void 0===e?"":Na(e)}function Na(e){if(null===e)return"null";switch(typeof e){case"boolean":case"number":case"string":return JSON.stringify(e);case"object":{if(Array.isArray(e))return`[${e.map(Na).join(",")}]`;const t=Object.keys(e).sort(),r=[];for(const n of t){const t=e[n];void 0!==t&&r.push(`${JSON.stringify(n)}:${Na(t)}`)}return`{${r.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}var Ra="0123456789abcdef";function Oa(e){let t="";for(let r=0;r<e.length;r++){const n=e[r];t+=Ra[n>>4&15]+Ra[15&n]}return t}function Ca(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let n=0;n<e.length;n+=3){const i=e[n],s=n+1<e.length?e[n+1]:0,o=n+2<e.length?e[n+2]:0;r+=t[i>>2&63],r+=t[63&(i<<4|s>>4)],r+=n+1<e.length?t[63&(s<<2|o>>6)]:"=",r+=n+2<e.length?t[63&o]:"="}return r}function Pa(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),r=t.length;if(r%4!=0)throw new Error("invalid base64 input");const n=r/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),i=new Uint8Array(n),s={};for(let e=0;e<64;e++)s["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]]=e;let o=0;for(let e=0;e<r;e+=4){const r=s[t[e]]??0,a=s[t[e+1]]??0,c="="===t[e+2]?0:s[t[e+2]]??0,u=r<<2|a>>4,l=(15&a)<<4|c>>2,h=(3&c)<<6|("="===t[e+3]?0:s[t[e+3]]??0);o<n&&(i[o++]=u),o<n&&(i[o++]=l),o<n&&(i[o++]=h)}return i}function Ma(e){return(new TextEncoder).encode(e)}function Da(e,t){return Oa(e(Ma(Ia(t))))}var Ba=/^[A-Z][A-Z0-9_]{0,63}$/,La="secrets/scoped/",Ua="tinychat-bot-history",Fa=new Set(["default","global",Ua]),$a=/^[a-z0-9]+(-[a-z0-9]+)*$/;Object.freeze(["default","global","scoped",Ua]);var Ha=`${La}${Ua}/bot-history`;function Ka(e){return function(e,t,r=!1){if(t.test(e))return{name:e};const n=e.split("/");if(3!==n.length||"scoped"!==n[0])return;const[,i,s]=n;if(s&&t.test(s)){if(r&&i&&((o=i).length>64&&$a.test(o)))return{name:s,scope:i,scopeTooLong:!0};try{const e=function(e){if(void 0===e)return;const t=e.trim();if(""===t)throw new Error("Secret scope must be non-empty; omit scope for global secrets.");const r=t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(""===r)throw new Error("Secret scope must contain at least one letter or number.");if(Fa.has(r))throw new Error(`Secret scope ${JSON.stringify(e)} is reserved; omit scope for global secrets.`);if(r.length>64)throw new Error(`Secret scope ${JSON.stringify(r)} is longer than 64 characters.`);return r}(i);if(void 0===e||e!==i)return;return{name:s,scope:e}}catch{return}}var o}(e,Ba)}var qa={masterMessage:e=>`tinycloud-vault-master-v1:${e}`,identityMessage:"tinycloud-encryption-identity-v1"},ja="x-vault-version",za="x-vault-cipher",Va="x-vault-key-id",Ga="x-vault-content-type",Wa="x-vault-kdf",Ja="x-vault-key-rotation",Za="x-vault-grant-version",Ya="x-vault-grantor",Qa="signatures",Xa="__wrap_key__";function ec(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof crypto&&void 0!==crypto.subtle}catch{return!1}}function tc(){return new Promise((e,t)=>{const r=indexedDB.open("tinycloud-vault-cache",1);r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains(Qa)||e.createObjectStore(Qa)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}function rc(e,t){return new Promise((r,n)=>{const i=e.transaction(Qa,"readonly").objectStore(Qa).get(t);i.onsuccess=()=>r(i.result),i.onerror=()=>n(i.error)})}function nc(e,t,r){return new Promise((n,i)=>{const s=e.transaction(Qa,"readwrite").objectStore(Qa).put(r,t);s.onsuccess=()=>n(),s.onerror=()=>i(s.error)})}function ic(e,t){return new Promise((r,n)=>{const i=e.transaction(Qa,"readwrite").objectStore(Qa).delete(t);i.onsuccess=()=>r(),i.onerror=()=>n(i.error)})}async function sc(e){const t=await rc(e,Xa);if(t)return t;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await nc(e,Xa,r),r}function oc(e){return`sig:${e}`}async function ac(e){if(!ec())return null;try{const t=await tc(),r=await rc(t,oc(e));if(!r)return null;const n=await sc(t);return await async function(e,t){const r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t.iv},e,t.ciphertext);return new Uint8Array(r)}(n,r)}catch{return null}}async function cc(e,t){if(ec())try{const r=await tc(),n=await sc(r),i=await async function(e,t){const r=crypto.getRandomValues(new Uint8Array(12));return{iv:r,ciphertext:new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,t))}}(n,t);await nc(r,oc(e),i)}catch{}}async function uc(e){if(ec())try{const t=await tc();if(e)await ic(t,oc(e));else{const e=await function(e){return new Promise((t,r)=>{const n=e.transaction(Qa,"readonly").objectStore(Qa).getAllKeys();n.onsuccess=()=>t(n.result.filter(e=>"string"==typeof e)),n.onerror=()=>r(n.error)})}(t);for(const r of e)r.startsWith("sig:")&&await ic(t,r)}}catch{}}function lc(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function hc(e){return(new TextEncoder).encode(e)}function dc(e){return(new TextDecoder).decode(e)}function fc(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}function pc(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function mc(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function gc(e){return null!==e&&"object"==typeof e&&"data"in e?e.data:e}function yc(e){return"number"==typeof e.meta?.status}function vc(e){switch(e.code){case"DECRYPTION_FAILED":return e.message??"Decryption failed";case"KEY_NOT_FOUND":return e.message??`Key not found: ${e.key}`;case"INTEGRITY_ERROR":return e.message??"Integrity check failed";case"GRANT_NOT_FOUND":return e.message??`Grant not found: ${e.grantor} / ${e.key}`;case"VAULT_LOCKED":return e.message??"Vault is locked";case"PUBLIC_KEY_NOT_FOUND":return e.message??`Public key not found for ${e.did}`;case"STORAGE_ERROR":return e.message??e.cause.message;case"ALREADY_EXISTS":return e.message??`A value already exists at ${e.key}`;case"AUTH_UNAUTHORIZED":case"PERMISSION_DENIED":case"AAD_MISMATCH":case"ETAG_MISMATCH":case"INVALID_ETAG":case"OUTCOME_UNKNOWN":case"NODE_BUSY":case"STORAGE_QUOTA_EXCEEDED":case"STORAGE_LIMIT_REACHED":return e.message;default:return e.message??e.code}}function bc(e){return{ok:!1,error:{...e,service:"vault",message:vc(e)}}}function wc(e){return Object.assign(new Error(e.message),{name:"ServiceError",code:e.code,service:e.service,...void 0!==e.meta?{meta:e.meta}:{},...void 0!==e.cause?{cause:e.cause}:{}})}function Ec(e){return e.replace(/0x[0-9a-fA-F]{40}/g,e=>e.toLowerCase())}function Ac(e,t,r,n){if(!0!==n?.expectAad&&void 0===n?.keyPath)return"ok";const i=function(e,t,r){const n=e;if("object"!=typeof n||null===n||Array.isArray(n)||!["networkId","alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"].every(e=>"string"==typeof n[e]&&""!==n[e])||!Number.isInteger(n.keyVersion)||void 0!==n.aad&&"string"!=typeof n.aad)return"corrupt";let i="";try{"string"==typeof n.aad&&(i=dc(Pa(n.aad)))}catch{}const s=`:${r}`;return i.endsWith(s)&&Ec(i.slice(0,-s.length))===Ec(`tinycloud.vault:${t}`)?"ok":"mismatch"}(e,t,r);if("mismatch"!==i||void 0===n?.keyPath)return i;const{keyPath:s,aad:o}=e;return void 0===s&&void 0===o?"ok":i}var kc=[500,502,503,504,520,522,524];function xc(e,t){const r=ro(t);if(r)return bc(r);if(t.code===fs.STORAGE_QUOTA_EXCEEDED||t.code===fs.STORAGE_LIMIT_REACHED)return bc({code:t.code,message:t.message,meta:t.meta});const n=`${e}: ${t.message}`;return t.code===fs.AUTH_UNAUTHORIZED?bc({code:"unauthenticated"===yo(t)?"AUTH_UNAUTHORIZED":"PERMISSION_DENIED",message:n,...void 0!==t.meta?{meta:t.meta}:{},cause:wc(t)}):bc({code:"STORAGE_ERROR",cause:new Error(n,{cause:wc(t)}),...void 0!==t.meta?{meta:t.meta}:{}})}function _c(e){return"not_found"===e||"permission_required"===e||"aad_mismatch"===e?e:"read_failed"}function Tc(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}(class extends _o{constructor(e){super(),this.masterKey=null,this.encryptionIdentity=null,this._isUnlocked=!1,this.unlockInFlight=null,this.vaultConfig=e,this._config=e}get config(){return this._config}get isUnlocked(){return this.usesNetworkEncryption||this._isUnlocked}get publicKey(){if(this.usesNetworkEncryption)throw new Error("Network-encrypted vaults do not expose a local public key");if(!this.encryptionIdentity)throw new Error("Vault is locked");return this.encryptionIdentity.publicKey}get crypto(){return this.vaultConfig.crypto}get tc(){return this.vaultConfig.tc}get networkEncryption(){return this.vaultConfig.encryption}get usesNetworkEncryption(){return void 0!==this.networkEncryption}get host(){return this.tc.hosts[0]}async decryptCapabilityProof(){const e=this.networkEncryption?.decryptCapabilityProof;return"function"==typeof e?await e():e??{proofs:[]}}async namedKeys(){const e=this.networkEncryption?.namedKeys;if(void 0===e)throw new Error("Named-key encryption is not configured");return e()}async decryptStored(e,t){const r=this.networkEncryption,{keyPath:n,networkId:i}=Object(e);if(void 0===n)return t?.namedKeyOnly?{ok:!1,error:{code:"LEGACY_ENVELOPE",message:"Envelope is sealed to the network key, not this record's own key"}}:r.service.decryptEnvelope(e,await this.decryptCapabilityProof());if(2!==e.v||n!==t?.keyPath||Ec(String(i))!==Ec(r.networkId))return{ok:!1,error:{code:"INVALID_ENVELOPE",message:"Envelope is sealed to another key"}};try{return{ok:!0,data:await(await this.namedKeys()).decrypt(e)}}catch(e){if(ro(e))throw e;const{code:t,status:r,message:s}=e;return{ok:!1,error:401===r||403===r?{code:"DECRYPT_DENIED",message:String(s),permissionHint:{service:"tinycloud.encryption",path:`${i}/${n}`,actions:["tinycloud.encryption/decrypt"]}}:{code:"INVALID_ENVELOPE"===t?t:"DECRYPT_FAILED",message:String(s)}}}}serializeValue(e,t){let r;return r=e instanceof Uint8Array?e:t?.serialize?t.serialize(e):hc("string"==typeof e?e:JSON.stringify(e)),{plaintext:r,contentType:t?.contentType??(e instanceof Uint8Array?"application/octet-stream":"application/json")}}deserializeValue(e,t,r){return r?.raw?e:r?.deserialize?r.deserialize(e):"application/json"===t?JSON.parse(dc(e)):e}async unlock(e){if(this.usesNetworkEncryption)return this._isUnlocked=!0,{ok:!0,data:void 0};const t=function(e){return"object"==typeof e&&null!==e&&"function"==typeof e.signMessage}(e)?e:void 0;if(this._isUnlocked&&this.masterKey&&(this.encryptionIdentity||!t))return{ok:!0,data:void 0};if(this.unlockInFlight)return this.unlockInFlight;this.unlockInFlight=this.withTelemetry("unlock",void 0,async()=>{const e=this.vaultConfig.spaceId,r=qa,n=`vault-master:${e}`,i=`vault-identity:${this.tc.address}`;try{if(!this.masterKey){let i=await ac(n);if(!i){if(!t)return bc({code:"VAULT_LOCKED",message:"Signer is required when no cached master signature exists"});i=hc(await t.signMessage(r.masterMessage(e))),await cc(n,i)}this.masterKey=this.crypto.deriveKey(i,this.crypto.sha256(hc(e)),hc("vault-master"))}const s=this.tc.makePublicSpaceId(this.tc.address,this.tc.chainId);let o=null;try{const e=await this.tc.readPublicSpace(this.host,s,".well-known/vault-pubkey");e.ok&&e.data&&(o=e.data)}catch{}if(o)this.encryptionIdentity={publicKey:mc(o),privateKey:new Uint8Array(0)};else{let e=await ac(i);if(!e){if(!t)return this.encryptionIdentity=null,this._isUnlocked=!0,ps(void 0);e=hc(await t.signMessage(r.identityMessage)),await cc(i,e)}const n=this.crypto.deriveKey(e,hc("tinycloud-x25519"),hc("encryption-identity"));this.encryptionIdentity=this.crypto.x25519FromSeed(n);try{const e=pc(this.encryptionIdentity.publicKey);await this.tc.ensurePublicSpace(),await this.tc.publicKV.put(".well-known/vault-pubkey",e),await this.tc.publicKV.put(".well-known/vault-version","1"),await this.tc.publicKV.put(".well-known/vault-space",this.vaultConfig.spaceId)}catch{}}return this._isUnlocked=!0,ps(void 0)}catch(e){return this.masterKey=null,this.encryptionIdentity=null,bc({code:"STORAGE_ERROR",cause:lc(e)})}});try{return await this.unlockInFlight}finally{this.unlockInFlight=null}}async clearCache(e){e?await uc(`vault-master:${e}`):await uc()}lock(){this.masterKey=null,this.encryptionIdentity=null,this._isUnlocked=!1}onSignOut(){this.lock(),super.onSignOut()}async putNetworkEncrypted(e,t,r){const n=this.networkEncryption;if(!n)return bc({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});if(void 0!==r?.ifMatch){if(void 0!==r.ifNoneMatch)return bc({code:"STORAGE_ERROR",cause:new Error("ifMatch cannot be combined with ifNoneMatch")});if(!/^"[^"\s]+"$/.test(r.ifMatch))return bc({code:"INVALID_ETAG",key:e,message:r.ifMatch.startsWith("W/")?'ifMatch is a weak etag (W/"..."): the node only issues strong etags, so the etag was weakened in transit (a proxy or CDN rewrote it). Read it from a connection that preserves strong ETags':"ifMatch must be the strong, quoted ETag returned by a network read (VaultEntry.etag), passed exactly as returned"})}try{const{plaintext:i,contentType:s}=this.serializeValue(t,r),o={[ja]:"2",[za]:"tinycloud-network-envelope",[Ga]:s,...r?.metadata??{}},a=hc(`tinycloud.vault:${this.vaultConfig.spaceId}:${e}`),c=void 0===r?.keyPath?await n.service.encryptToNetwork(n.networkId,i,{aad:a,metadata:o}):{ok:!0,data:await(await this.namedKeys()).encrypt(r.keyPath,i,{networkId:n.networkId,aad:a,metadata:o,ensureKey:!0})};if(!c.ok){const e=ro(c.error);return bc(e||{code:"STORAGE_ERROR",cause:new Error(c.error.message)})}const u=`vault/${e}`,l=JSON.stringify(c.data),h=void 0!==r?.ifMatch?{ifMatch:r.ifMatch}:void 0!==r?.ifNoneMatch?{ifNoneMatch:r.ifNoneMatch}:void 0,d=void 0!==h?await this.tc.kv.put(u,l,h):await this.tc.kv.put(u,l);if(!d.ok){if(void 0!==r?.ifNoneMatch&&d.error.code===fs.KV_PRECONDITION_FAILED)return bc({code:"ALREADY_EXISTS",key:e,...void 0!==d.error.meta?{meta:d.error.meta}:{},cause:wc(d.error)});if(void 0!==r?.ifMatch){const t=function(e,t){const r=t.meta?.status,n=t.code===fs.KV_PRECONDITION_FAILED?"ETAG_MISMATCH":t.code===fs.KV_WRITE_FAILED&&400===r?"INVALID_ETAG":t.code===fs.OUTCOME_UNKNOWN||t.code===fs.KV_WRITE_FAILED&&"number"==typeof r&&kc.includes(r)||(t.code===fs.NETWORK_ERROR||t.code===fs.TIMEOUT)&&void 0===r&&!1!==t.meta?.requestMayHaveDispatched?"OUTCOME_UNKNOWN":t.code===fs.NODE_BUSY||t.code===fs.REQUEST_TIMEOUT?"NODE_BUSY":void 0;if(void 0!==n)return bc({code:n,key:e,message:t.message,...void 0!==t.meta?{meta:t.meta}:{},cause:wc(t)})}(e,d.error);if(void 0!==t)return t}return xc("Failed to store encrypted value",d.error)}return{ok:!0,data:void 0}}catch(e){const t=ro(e);return bc(t||{code:"STORAGE_ERROR",cause:lc(e)})}}async getNetworkEncrypted(e,t){if(!this.networkEncryption)return bc({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!r.ok){const t=ro(r.error);return bc(t||{code:"KEY_NOT_FOUND",key:e})}const n=gc(r.data),i="string"==typeof n?JSON.parse(n):n,s=Ac(i,this.vaultConfig.spaceId,e,t);if("corrupt"===s)return bc({code:"DECRYPTION_FAILED",message:"envelope is malformed"});if("mismatch"===s)return bc({code:"AAD_MISMATCH",key:e,message:`Envelope at ${e} is not bound to this space and key`});const o=await this.decryptStored(i,t);if(!o.ok){const t=ro(o.error);if(t)return bc(t);const{code:r,message:n,permissionHint:i}=o.error;return bc("LEGACY_ENVELOPE"===r?{code:r,key:e,message:n}:"DECRYPT_DENIED"===r&&void 0!==i?{code:r,key:e,message:n,permissionHint:i}:{code:"DECRYPTION_FAILED",message:n})}const a=i.metadata??{},c=a[Ga]??"application/json",u=a[Va]??i.encryptedSymmetricKeyHash.slice(0,16),l=this.deserializeValue(o.data,c,t),h="network"===t?.source?r.data.headers?.etag:void 0;return{ok:!0,data:{value:l,metadata:a,keyId:u,...void 0===h?{}:{etag:h}}}}catch(e){const t=ro(e);return bc(t||{code:"STORAGE_ERROR",cause:lc(e)})}}async readNetworkEncrypted(e,t){const r=await this.fetchNetworkEnvelope(e);if("fetched"!==r.status)return r;const{envelope:n,etag:i}=r,s=Ac(n,this.vaultConfig.spaceId,e,t);if("ok"!==s)return{status:"corrupt"===s?"corrupt_envelope":"aad_mismatch"};const o=await this.openStored(n,t);if("opened"!==o.status)return o;try{const e=n.metadata??{},r=e[Ga]??"application/json",s=e[Va]??n.encryptedSymmetricKeyHash.slice(0,16);return{status:"ok",entry:{value:this.deserializeValue(o.plaintext,r,t),metadata:e,keyId:s,...void 0===i?{}:{etag:i}}}}catch{return{status:"invalid_payload"}}}async resealToKey(e,t,r){const n=e.startsWith("secrets/")?Ka(e.slice(8)):void 0;if(void 0===n||function(e,t){if(!Ba.test(e)||void 0!==t&&(!$a.test(t)||t.length>64))throw new Error("A secret's key needs a name and scope of at most 64 bytes, scope in canonical form");if(void 0===t&&"SCOPED"===e)throw new Error(`Secret name ${JSON.stringify(e)} is reserved.`);if(t===Ua)throw new Error(`Secret scope ${JSON.stringify(t)} is reserved.`);return`${void 0===t?"secrets/":`${La}${t}/`}${e.toLowerCase()}`}(n.name,n.scope)!==t)throw new Error(`resealToKey: ${JSON.stringify(t)} is not the own key of ${JSON.stringify(e)}`);const i=this.networkEncryption;if(!i||!this.requireAuth())return{status:"skipped",reason:"read_failed"};const s=`tinycloud.vault:${this.vaultConfig.spaceId}:${e}`;for(let n=0;;n++){const o=await this.fetchNetworkEnvelope(e);if("fetched"!==o.status)return{status:"skipped",reason:_c(o.status)};const{envelope:a,etag:c}=o,u=Ac(a,this.vaultConfig.spaceId,e,{keyPath:t});if("ok"!==u)return{status:"skipped",reason:"corrupt"===u?"read_failed":"aad_mismatch"};if(a.keyPath===t&&2===a.v&&Ec(String(a.networkId))===Ec(i.networkId))return{status:"already"};if(!0===r?.dryRun)return{status:"pending"};if(void 0===c)return{status:"skipped",reason:"write_failed"};const l=await this.openStored(a,{keyPath:t});if("opened"!==l.status)return{status:"skipped",reason:_c(l.status)};let h,d,f;try{h=await this.namedKeys(),d=await h.encrypt(t,l.plaintext,{networkId:i.networkId,aad:hc(s),metadata:a.metadata??{},ensureKey:!0})}catch(e){if(ro(e))throw e;const{status:t}=e;return{status:"skipped",reason:401===t||403===t?"permission_required":"write_failed"}}try{if(!Tc(await h.decrypt(d),l.plaintext))return{status:"skipped",reason:"verify_failed"}}catch(e){if(ro(e))throw e;return{status:"skipped",reason:"verify_failed"}}try{f=await this.tc.kv.put(`vault/${e}`,JSON.stringify(d),{ifMatch:c})}catch(e){if(ro(e))throw e;return{status:"skipped",reason:"write_failed"}}if(f.ok)return{status:"moved"};if(ro(f.error))throw f.error;if(f.error.code!==fs.KV_PRECONDITION_FAILED)return{status:"skipped",reason:"write_failed"};if(n>0)return{status:"skipped",reason:"conflict"}}}async fetchNetworkEnvelope(e){if(!this.networkEncryption||!this.requireAuth())return{status:"read_failed"};let t;try{t=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"})}catch(e){if(ro(e))throw e;return{status:"node_unreachable"}}if(!t.ok){if(ro(t.error))throw t.error;const e=no(t.error.meta?.permissionHint);return"AUTH_UNAUTHORIZED"===t.error.code&&void 0!==e?{status:"permission_required",hint:e}:"NOT_FOUND"!==t.error.code&&"KV_NOT_FOUND"!==t.error.code||yc(t.error)?"NODE_NOT_RESPONDING"===t.error.code||"NETWORK_ERROR"===t.error.code||"TIMEOUT"===t.error.code||"ABORTED"===t.error.code?yc(t.error)?{status:"read_failed"}:{status:"node_unreachable"}:{status:"read_failed"}:{status:"not_found"}}try{const e=gc(t.data);return{status:"fetched",envelope:"string"==typeof e?JSON.parse(e):e,etag:t.data.headers?.etag}}catch{return{status:"corrupt_envelope"}}}async openStored(e,t){let r;try{r=await this.decryptStored(e,t)}catch(e){if(ro(e))throw e;return{status:"decrypt_failed"}}if(r.ok)return{status:"opened",plaintext:r.data};if(ro(r.error))throw r.error;const n=no(r.error.permissionHint);return"DECRYPT_DENIED"===r.error.code&&void 0!==n?{status:"permission_required",hint:n}:"INVALID_ENVELOPE"===r.error.code?{status:"corrupt_envelope"}:"LEGACY_ENVELOPE"===r.error.code?{status:"legacy_envelope"}:"NODE_NOT_RESPONDING"===r.error.code||"TRANSPORT_ERROR"===r.error.code?{status:"node_unreachable"}:{status:"decrypt_failed"}}async headNetworkEncrypted(e){if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"});if(!t.ok)return bc({code:"KEY_NOT_FOUND",key:e});const r=gc(t.data);return{ok:!0,data:("string"==typeof r?JSON.parse(r):r).metadata??{}}}catch(e){return bc({code:"STORAGE_ERROR",cause:lc(e)})}}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(this.usesNetworkEncryption)return this.putNetworkEncrypted(e,t,r);if(void 0!==r?.ifNoneMatch)return bc({code:"STORAGE_ERROR",cause:new Error("ifNoneMatch is only supported by network-encrypted vaults")});if(void 0!==r?.ifMatch)return bc({code:"STORAGE_ERROR",cause:new Error("ifMatch is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return bc({code:"VAULT_LOCKED",message:"Vault must be unlocked before storing data"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{let n;n=t instanceof Uint8Array?t:r?.serialize?r.serialize(t):hc("string"==typeof t?t:JSON.stringify(t));const i=r?.contentType??(t instanceof Uint8Array?"application/octet-stream":"application/json"),s=this.crypto.randomBytes(32),o=fc(this.crypto.sha256(s)).slice(0,16),a=this.crypto.encrypt(s,n),c=this.crypto.encrypt(this.masterKey,s),u={[ja]:"1",[za]:"aes-256-gcm",[Va]:o,[Ga]:i,[Wa]:"hkdf-sha256",[Ja]:this.vaultConfig.keyRotation??"per-write",...r?.metadata??{}},l=JSON.stringify({keyId:o,contentType:i,...u}),h=JSON.stringify({key:pc(c),metadata:l}),d=await this.tc.kv.put(`keys/${e}`,h);if(!d.ok)return xc("Failed to store key blob",d.error);const f=JSON.stringify({data:pc(a),metadata:u}),p=await this.tc.kv.put(`vault/${e}`,f);return p.ok?ps(void 0):xc("Failed to store encrypted value",p.error)}catch(e){return bc({code:"STORAGE_ERROR",cause:lc(e)})}})}async get(e,t){return this.withTelemetry("get",e,async()=>{if(this.usesNetworkEncryption)return this.getNetworkEncrypted(e,t);if(!0===t?.expectAad)return bc({code:"STORAGE_ERROR",cause:new Error("expectAad is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return bc({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading data"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.tc.kv.get(`keys/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!r.ok)return bc({code:"KEY_NOT_FOUND",key:e});const n=mc(JSON.parse(r.data.data).key),i=this.crypto.decrypt(this.masterKey,n),s=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!s.ok)return bc({code:"KEY_NOT_FOUND",key:e});const o=JSON.parse(s.data.data),a=mc(o.data),c=this.crypto.decrypt(i,a),u=o.metadata??{},l=u[Ga]??"application/json",h=u[Va]??"";let d;return d=t?.raw?c:t?.deserialize?t.deserialize(c):"application/json"===l?JSON.parse(dc(c)):c,ps({value:d,metadata:u,keyId:h})}catch(e){return e instanceof Error&&e.message.includes("decryption")?bc({code:"DECRYPTION_FAILED",message:e.message}):bc({code:"STORAGE_ERROR",cause:lc(e)})}})}async delete(e){return this.withTelemetry("delete",e,async()=>{if(!this.isUnlocked)return bc({code:"VAULT_LOCKED",message:"Vault must be unlocked before deleting data"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{if(this.usesNetworkEncryption){const t=await this.tc.kv.delete(`vault/${e}`);if(!t.ok){const r=ro(t.error);return bc(r||{code:"KEY_NOT_FOUND",key:e})}return ps(void 0)}const[t,r]=await Promise.all([this.tc.kv.delete(`keys/${e}`),this.tc.kv.delete(`vault/${e}`)]);if(!t.ok&&!r.ok){const n=ro(t.error)??ro(r.error);return bc(n||{code:"KEY_NOT_FOUND",key:e})}return ps(void 0)}catch(e){const t=ro(e);return bc(t||{code:"STORAGE_ERROR",cause:lc(e)})}})}async list(e){const t=await this.listPage(e);return t.ok?{ok:!0,data:t.data.keys}:t}async listPage(e){return this.withTelemetry("list",e?.prefix,async()=>{if(!this.isUnlocked)return bc({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing data"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=e?.prefix?`vault/${e.prefix}`:"vault/",r=await this.tc.kv.list({prefix:t,removePrefix:!0,...void 0===e?.limit?{}:{limit:e.limit},...void 0===e?.source?{}:{source:e.source},...void 0===e?.cursor?{}:{cursor:e.cursor}});if(!r.ok){const e=ro(r.error);return bc(e||{code:"STORAGE_ERROR",cause:new Error(`Failed to list vault keys: ${r.error.message}`)})}let n=r.data.keys;if(e?.removePrefix&&e.prefix){const t=e.prefix.endsWith("/")?e.prefix:`${e.prefix}/`;n=n.map(e=>e.startsWith(t)?e.slice(t.length):e)}return ps({keys:n,truncated:!0===r.data.truncated,...void 0===r.data.nextCursor?{}:{nextCursor:r.data.nextCursor}})}catch(e){const t=ro(e);return bc(t||{code:"STORAGE_ERROR",cause:lc(e)})}})}async head(e){return this.withTelemetry("head",e,async()=>{if(this.usesNetworkEncryption)return this.headNetworkEncrypted(e);if(!this._isUnlocked)return bc({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading metadata"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0});if(!t.ok)return bc({code:"KEY_NOT_FOUND",key:e});return ps(JSON.parse(t.data.data).metadata??{})}catch(e){return bc({code:"STORAGE_ERROR",cause:lc(e)})}})}async putMany(e){return Promise.all(e.map(e=>this.put(e.key,e.value,e.options)))}async getMany(e,t){return Promise.all(e.map(e=>this.get(e,t)))}async reencrypt(e,t,r){return this.withTelemetry("reencrypt",e,async()=>{if(this.usesNetworkEncryption)return bc({code:"STORAGE_ERROR",cause:new Error("Vault key grants are deprecated for network-encrypted vaults; grant tinycloud.encryption/decrypt on the network plus KV access to vault data.")});if(!this._isUnlocked||!this.masterKey)return bc({code:"VAULT_LOCKED",message:"Vault must be unlocked before granting access"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=await this.resolvePublicKey(t);if(!n.ok)return n;const i=n.data,s=await this.tc.kv.get(`keys/${e}`,{raw:!0});if(!s.ok)return bc({code:"KEY_NOT_FOUND",key:e});const o=mc(JSON.parse(s.data.data).key),a=this.crypto.decrypt(this.masterKey,o),c=this.crypto.randomBytes(32),u=this.crypto.x25519FromSeed(c),l=this.crypto.x25519Dh(u.privateKey,i),h=this.crypto.deriveKey(l,hc("tinycloud-x25519"),hc("vault-grant")),d=this.crypto.encrypt(h,a),f=function(...e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}(u.publicKey,d),p=JSON.stringify({grant:pc(f),spaceId:this.vaultConfig.spaceId,metadata:{[Za]:"1",[Ya]:this.tc.did,...r?.metadata??{}}}),m=await this.tc.kv.put(`grants/${t}/${e}`,p);return m.ok?ps(void 0):xc("Failed to store grant",m.error)}catch(e){return bc({code:"STORAGE_ERROR",cause:lc(e)})}})}async grant(e,t,r){return this.reencrypt(e,t,r)}async getShared(e,t,r){return this.withTelemetry("getShared",t,async()=>{if(!0===r?.expectAad)return bc({code:"STORAGE_ERROR",cause:new Error("expectAad is not supported by getShared: the AAD binds the grantor's space, which this vault does not know")});if(this.usesNetworkEncryption){const e=r?.kv;if(!e)return bc({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv.")});const n=this.networkEncryption;if(!n)return bc({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const i=await e.get(`vault/${t}`,{raw:!0});if(!i.ok)return bc({code:"KEY_NOT_FOUND",key:t});const s=gc(i.data),o="string"==typeof s?JSON.parse(s):s,a=await this.decryptCapabilityProof(),c=await n.service.decryptEnvelope(o,a);if(!c.ok)return bc({code:"DECRYPTION_FAILED",message:c.error.message});const u=o.metadata??{},l=u[Ga]??"application/json",h=u[Va]??o.encryptedSymmetricKeyHash.slice(0,16);return{ok:!0,data:{value:this.deserializeValue(c.data,l,r),metadata:u,keyId:h}}}catch(e){return bc({code:"STORAGE_ERROR",cause:lc(e)})}}if(!this._isUnlocked||!this.masterKey||!this.encryptionIdentity)return bc({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading shared data"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=this.tc.did,i=r?.kv;if(!i)return bc({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv. Use useDelegation() to get delegated access, then pass { kv: access.kv }.")});const s=await i.get(`grants/${n}/${t}`,{raw:!0});if(!s.ok)return bc({code:"GRANT_NOT_FOUND",grantor:e,key:t});const o=mc(("string"==typeof s.data?.data?JSON.parse(s.data.data):s.data?.data).grant),a=o.slice(0,32),c=o.slice(32),u=this.crypto.x25519Dh(this.encryptionIdentity.privateKey,a),l=this.crypto.deriveKey(u,hc("tinycloud-x25519"),hc("vault-grant")),h=this.crypto.decrypt(l,c),d=await i.get(`vault/${t}`,{raw:!0});if(!d.ok)return bc({code:"KEY_NOT_FOUND",key:t});const f="string"==typeof d.data?.data?JSON.parse(d.data.data):d.data?.data,p=mc(f.data),m=this.crypto.decrypt(h,p),g=f.metadata??{},y=g[Ga]??"application/json",v=g[Va]??"";let b;return b=r?.raw?m:r?.deserialize?r.deserialize(m):"application/json"===y?JSON.parse(dc(m)):m,ps({value:b,metadata:g,keyId:v})}catch(e){return e instanceof Error&&e.message.includes("decryption")?bc({code:"DECRYPTION_FAILED",message:e.message}):bc({code:"STORAGE_ERROR",cause:lc(e)})}})}async resolvePublicKey(e){try{const t=this.parseDID(e);if(!t)return bc({code:"PUBLIC_KEY_NOT_FOUND",did:e});const r=this.tc.makePublicSpaceId(t.address,t.chainId),n=await this.tc.readPublicSpace(this.host,r,".well-known/vault-pubkey");return n.ok?{ok:!0,data:mc(n.data)}:bc({code:"PUBLIC_KEY_NOT_FOUND",did:e})}catch(t){return bc({code:"PUBLIC_KEY_NOT_FOUND",did:e})}}async listGrants(e){return this.withTelemetry("listGrants",e,async()=>{if(this.usesNetworkEncryption)return{ok:!0,data:[]};if(!this._isUnlocked)return bc({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing grants"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.list({prefix:"grants/",removePrefix:!0});if(!t.ok)return bc({code:"STORAGE_ERROR",cause:new Error(`Failed to list grants: ${t.error.message}`)});const r=[];for(const n of t.data.keys)if(n.endsWith(`/${e}`)){const t=n.slice(0,n.length-e.length-1);t&&r.push(t)}return ps(r)}catch(e){return bc({code:"STORAGE_ERROR",cause:lc(e)})}})}async revoke(e,t){return this.withTelemetry("revoke",e,async()=>{if(this.usesNetworkEncryption)return bc({code:"STORAGE_ERROR",cause:new Error("Vault key grants are deprecated for network-encrypted vaults; revoke KV and tinycloud.encryption/decrypt grants instead.")});if(!this._isUnlocked||!this.masterKey)return bc({code:"VAULT_LOCKED",message:"Vault must be unlocked before revoking access"});if(!this.requireAuth())return bc({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.listGrants(e);if(!r.ok)return r;const n=r.data.filter(e=>e!==t),i=(await this.tc.kv.delete(`grants/${t}/${e}`),await this.get(e));if(!i.ok)return i;const s=i.data,o=this.crypto.randomBytes(32),a=fc(this.crypto.sha256(o)).slice(0,16);let c;c=s.value instanceof Uint8Array?s.value:hc(JSON.stringify(s.value));const u=this.crypto.encrypt(o,c),l=this.crypto.encrypt(this.masterKey,o),h={...s.metadata,[Va]:a},d=JSON.stringify({key:pc(l),metadata:JSON.stringify({keyId:a,...h})}),f=await this.tc.kv.put(`keys/${e}`,d);if(!f.ok)return xc("Failed to store rotated key blob",f.error);const p=JSON.stringify({data:pc(u),metadata:h}),m=await this.tc.kv.put(`vault/${e}`,p);if(!m.ok)return xc("Failed to store re-encrypted value",m.error);for(const t of n)(await this.reencrypt(e,t)).ok;return ps(void 0)}catch(e){return bc({code:"STORAGE_ERROR",cause:lc(e)})}})}parseDID(e){const t=e.split(":");if(5!==t.length||"did"!==t[0]||"pkh"!==t[1]||"eip155"!==t[2])return null;const r=parseInt(t[3],10),n=t[4];return isNaN(r)||!n?null:{address:n,chainId:r}}}).serviceName="vault";var Sc="tinycloud.encryption.decrypt/v1",Ic="tinycloud.encryption.decrypt-result/v1";function Nc(e){switch(e.code){case"NETWORK_NOT_FOUND":return e.message??`Network not found: ${e.networkId??e.name??"<unknown>"}`;case"NETWORK_NOT_ACTIVE":return e.message??`Network not active (state=${e.state})`;case"INVALID_NETWORK_ID":case"INVALID_ENVELOPE":case"DECRYPT_DENIED":case"INVALID_RESPONSE":case"INVALID_INPUT":return e.message;case"RESPONSE_SIGNATURE_INVALID":return e.message??"Node response signature failed to verify";case"RESPONSE_BINDING_MISMATCH":return e.message??`Node response binding mismatch on field ${JSON.stringify(e.field)}`;case"TRANSPORT_ERROR":return e.message??e.cause.message;default:return e.message??e.code}}function Rc(e){return{...e,service:"encryption",message:Nc(e)}}function Oc(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function Cc(e,t,r,n){let i;try{i=Ws(e.networkId)}catch(e){return{ok:!1,error:Rc({code:"INVALID_NETWORK_ID",message:`descriptor networkId is malformed: ${e instanceof Error?e.message:String(e)}`})}}if(i.name!==n||!Ys(i.ownerDid,r))return{ok:!1,error:Rc({code:"INVALID_NETWORK_ID",message:`descriptor networkId ${JSON.stringify(e.networkId)} does not match expected ${JSON.stringify(t)}`})};const s=function(e){if("string"==typeof e.ownerDid&&e.ownerDid.length>0)return e.ownerDid;const t=e;return"string"==typeof t.principal&&t.principal.length>0?t.principal:void 0}(e);return void 0!==s&&Ys(s,r)&&Ys(s,i.ownerDid)?e.name!==n?{ok:!1,error:Rc({code:"INVALID_NETWORK_ID",message:"descriptor name does not match networkId name"})}:"string"!=typeof e.publicEncryptionKey||0===e.publicEncryptionKey.length?{ok:!1,error:Rc({code:"INVALID_NETWORK_ID",message:"descriptor publicEncryptionKey must be a non-empty string"})}:{ok:!0,data:{...e,ownerDid:s}}:{ok:!1,error:Rc({code:"INVALID_NETWORK_ID",message:"descriptor ownerDid does not match networkId ownerDid"})}}function Pc(e){return"active"===e.state||"rotating"===e.state?{ok:!0,data:e}:{ok:!1,error:Rc({code:"NETWORK_NOT_ACTIVE",state:e.state})}}var Mc="x25519-hkdf-aes256gcm/v2",Dc=Ma("TCW2"),Bc=Ma("tinycloud.encryption.key-wrap/v2");function Lc(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let r=0;for(const n of e)t.set(n,r),r+=n.length;return t}function Uc(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}function Fc(e){if("string"!=typeof e)throw new Error("Invalid key wrap encoding");const t=Pa(e);if(32!==t.length||Ca(t)!==e)throw new Error("Invalid key wrap encoding");return t}function $c(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=55296&&r<=56319){const r=e.charCodeAt(++t);if(!(r>=56320&&r<=57343))return!1}else if(r>=56320&&r<=57343)return!1}return!0}function Hc(e){if("network-key"!==e.purpose&&"receiver-key"!==e.purpose||"string"!=typeof e.networkId||"string"!=typeof e.keyPath||!$c(e.networkId)||!$c(e.keyPath)||!Number.isSafeInteger(e.keyVersion)||e.keyVersion<=0||!e.metadata||"object"!=typeof e.metadata||Array.isArray(e.metadata)||Object.entries(e.metadata).some(([e,t])=>!$c(e)||"string"!=typeof t||!$c(t)))throw new Error("Invalid key wrap context");if(""!==e.networkId){const t=Js(""===e.keyPath?e.networkId:`${e.networkId}/${e.keyPath}`);if(t.networkId!==e.networkId||(t.keyPath??"")!==e.keyPath||e.keyPath.endsWith("/"))throw new Error("Invalid key wrap resource")}}function Kc(e){return e.length>=4&&Dc.every((t,r)=>e[r]===t)}function qc(e){if(!Kc(e)||e.length<8)throw new Error("Invalid v2 key wrap frame");const t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(4);if(0===t||t>65536||e.length<8+t+12+16)throw new Error("Invalid v2 key wrap length");const r=e.subarray(8,8+t),n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r)),i=["v","alg","kdf","aead","salt","ephemeralPublicKey","recipientPublicKey","purpose","networkId","keyPath","keyVersion","metadata"].sort();if(!n||"object"!=typeof n||Array.isArray(n)||Object.keys(n).sort().join(",")!==i.join(",")||2!==n.v||n.alg!==Mc||"hkdf-sha256"!==n.kdf||"aes-256-gcm"!==n.aead)throw new Error("Invalid v2 key wrap header");if(Hc(n),Fc(n.salt),Fc(n.ephemeralPublicKey),Fc(n.recipientPublicKey),!Uc(r,Ma(Ia({...n}))))throw new Error("Non-canonical v2 key wrap header");const s=8+t;return{header:n,aad:e.subarray(0,s),nonce:e.subarray(s,s+12),ciphertext:e.subarray(s+12)}}function jc(e,t){Hc(t);for(const r of["purpose","networkId","keyPath","keyVersion"])if(e[r]!==t[r])throw new Error("Key wrap context mismatch");if(Ia(e.metadata)!==Ia(t.metadata))throw new Error("Key wrap metadata mismatch")}function zc(e,t,r=!1){if("x25519-aes256gcm/v1"!==t&&t!==Mc)throw new Error("Unsupported key wrap algorithm");if(r&&t!==Mc)throw new Error("V2 network key wrap required");if(Kc(e)!==(t===Mc))throw new Error("Key wrap algorithm mismatch");t===Mc&&qc(e)}function Vc(e,t=!1){const r=Pa(e.encryptedSymmetricKey);zc(r,e.alg,t),e.alg===Mc&&jc(qc(r).header,{purpose:"network-key",networkId:e.networkId,keyPath:e.keyPath??"",keyVersion:e.keyVersion,metadata:e.metadata??{}})}function Gc(e){return{ok:!0,data:e}}function Wc(e){return{ok:!1,error:e}}function Jc(e){return Rc("NODE_NOT_RESPONDING"===e.code||"TRANSPORT_ERROR"===e.code&&"AbortError"!==e.cause.name?{...e,code:"DECRYPTION_DEPENDENCY_UNAVAILABLE",message:"The decryption service isn't responding right now. Please try again."}:e)}(class extends _o{constructor(e){super(),this._config=e}get config(){return this._config}get crypto(){return this._config.crypto}async discoverNetwork(e,t){this.assertActive();const r=await async function(e){let t,r,n;try{if(e.identifier.startsWith("urn:tinycloud:encryption:")){const i=Ws(e.identifier);t=i.networkId,r=i.ownerDid,n=i.name}else{if(void 0===e.ownerDid)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"discoverNetwork requires `ownerDid` when identifier is a bare network name"})};t=`urn:tinycloud:encryption:${e.ownerDid}:${e.identifier}`;const i=Ws(t);r=i.ownerDid,n=i.name}}catch(e){if(e instanceof Gs)return{ok:!1,error:Rc({code:"INVALID_NETWORK_ID",message:e.message})};throw e}if(void 0!==e.node)try{const i=await e.node.fetchByNetworkId(t);if(null!==i){const e=Cc(i,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"node"}}:e}}catch(e){const t=ro(e);return t?{ok:!1,error:Rc(t)}:{ok:!1,error:Rc({code:"TRANSPORT_ERROR",cause:e instanceof Error?e:new Error(String(e))})}}if(void 0!==e.wellKnown)try{const i=await e.wellKnown.fetchWellKnown(r,function(e){if(!zs.test(e))throw new Gs(`network name ${JSON.stringify(e)} must match ${zs.source}`);return`.well-known/encryption/network/${e}`}(n));if(null!==i){const e=Cc(i,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"well-known"}}:e}}catch(e){const t=ro(e);if(t)return{ok:!1,error:Rc(t)}}return{ok:!1,error:Rc({code:"NETWORK_NOT_FOUND",networkId:t,name:n})}}({identifier:e,...void 0!==t?{ownerDid:t}:{},...void 0!==this._config.node?{node:this._config.node}:{},...void 0!==this._config.wellKnown?{wellKnown:this._config.wellKnown}:{}});return this.assertActive(),r.ok?Gc(r.data.descriptor):r}async encryptToNetwork(e,t,r){try{this.assertActive();const n=await this.discoverNetwork(e);if(!n.ok)return n;const i=Pc(n.data);if(!i.ok)return i;const s=i.data,o=Pa(s.publicEncryptionKey);return Gc(function(e,t){if(Js(void 0===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`).keyPath!==t.keyPath||t.keyPath?.endsWith("/"))throw new Gs("keyPath must name an exact encryption key");const r=t.keyWrapV2?Mc:"x25519-aes256gcm/v1";if(void 0!==t.alg&&t.alg!==r)throw new Error("Algorithm does not match keyWrapV2");const n=t.keyVersion??1,i=e.randomBytes(32),s=e.authEncrypt(i,t.plaintext,t.aad),o=t.keyWrapV2?function(e,t,r){if(Hc(r),32!==e.length)throw new Error("Invalid recipient public key");const n=(0,cn.randomBytes)(32),i=Ji.getPublicKey(n),s=(0,cn.randomBytes)(32),o=Ma(Ia({...{...r,v:2,alg:Mc,kdf:"hkdf-sha256",aead:"aes-256-gcm",salt:Ca(s),ephemeralPublicKey:Ca(i),recipientPublicKey:Ca(e)}}));if(o.length>65536)throw new Error("Key wrap header too large");const a=new Uint8Array(8);a.set(Dc),new DataView(a.buffer).setUint32(4,o.length);const c=Lc(a,o),u=(0,cn.randomBytes)(12);let l;try{const r=Ji.getSharedSecret(n,e);try{if(r.every(e=>0===e))throw new Error("Invalid key agreement");l=ls(hs,r,s,Lc(Bc,i,e),32)}finally{r.fill(0)}return Lc(c,u,an(l,u,c).encrypt(t))}finally{n.fill(0),l?.fill(0)}}(t.networkPublicKey,i,{purpose:"network-key",networkId:t.networkId,keyPath:t.keyPath??"",keyVersion:n,metadata:t.metadata??{}}):e.sealToNetworkKey(t.networkPublicKey,i),a=Ca(o),c=Da(e.sha256,a);return{envelope:{v:1,networkId:t.networkId,...void 0!==t.keyPath?{keyPath:t.keyPath}:{},alg:r,keyVersion:n,encryptedSymmetricKey:a,encryptedSymmetricKeyHash:c,ciphertext:Ca(s),...void 0!==t.aad?{aad:Ca(t.aad)}:{},...void 0!==t.metadata?{metadata:t.metadata}:{}},symmetricKey:i}}(this.crypto,{networkId:s.networkId,...void 0!==r?.keyPath?{keyPath:r.keyPath}:{},networkPublicKey:o,plaintext:t,...void 0!==r?.aad?{aad:r.aad}:{},keyWrapV2:r?.keyWrapV2??this._config.keyWrapV2??!1,...void 0!==r?.alg?{alg:r.alg}:{},keyVersion:r?.keyVersion??s.keyVersion,...void 0!==r?.metadata?{metadata:r.metadata}:{}}).envelope)}catch(e){const t=ro(e);return Wc(Rc(t||{code:"TRANSPORT_ERROR",cause:Oc(e)}))}}async decryptEnvelope(e,t,r){try{this.assertActive();const i=function(e,t,r=!1){if(null===t||"object"!=typeof t)return{ok:!1,error:Rc({code:"INVALID_ENVELOPE",message:"envelope must be an object"})};const n=t;if(1!==n.v)return{ok:!1,error:Rc({code:"INVALID_ENVELOPE",message:`envelope.v must be 1 (got ${n.v})`})};try{if(void 0!==Js(n.networkId).keyPath)throw new Error("networkId must identify the network root");if(void 0!==n.keyPath){if("string"!=typeof n.keyPath)throw new Error("keyPath must be a string");if(Js(`${n.networkId}/${n.keyPath}`).keyPath!==n.keyPath||n.keyPath.endsWith("/"))throw new Error("keyPath must name an exact encryption key")}}catch(e){return{ok:!1,error:Rc({code:"INVALID_ENVELOPE",message:`envelope encryption resource is malformed: ${e instanceof Error?e.message:String(e)}`})}}for(const e of["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"])if("string"!=typeof n[e]||0===n[e].length)return{ok:!1,error:Rc({code:"INVALID_ENVELOPE",message:`envelope.${e} must be a non-empty string`})};if("number"!=typeof n.keyVersion||!Number.isInteger(n.keyVersion))return{ok:!1,error:Rc({code:"INVALID_ENVELOPE",message:"envelope.keyVersion must be an integer"})};if(Da(e.sha256,n.encryptedSymmetricKey)!==n.encryptedSymmetricKeyHash)return{ok:!1,error:Rc({code:"INVALID_ENVELOPE",message:"envelope.encryptedSymmetricKeyHash does not match canonical hash of encryptedSymmetricKey"})};try{Vc(n,r)}catch{return{ok:!1,error:Rc({code:"INVALID_ENVELOPE",message:"Envelope key wrap context is invalid"})}}return{ok:!0,data:n}}(this.crypto,e,this._config.requireKeyWrapV2??!1);if(!i.ok)return i;if(void 0!==r?.aad&&i.data.aad!==Ca(r.aad))return Wc(Rc({code:"INVALID_INPUT",message:"decryptEnvelope aad does not match the envelope"}));let s;if(void 0!==r?.descriptor)s=r.descriptor;else{const t=await this.discoverNetwork(e.networkId);if(!t.ok)return Wc(Jc(t.error));s=t.data}const o=Pc(s);if(!o.ok)return o;const a=this._config.resolveTargetNode?await this._config.resolveTargetNode(e.networkId):r?.targetNode??s.members[0]?.nodeId;if(void 0===a)return Wc(Rc({code:"INVALID_INPUT",message:"no target node available from descriptor"}));if(this._config.resolveTargetNode&&(void 0!==r?.targetNode&&r.targetNode!==a||!s.members.some(e=>e.nodeId===a)))return Wc(Rc({code:"INVALID_INPUT",message:"Encryption destination does not match the registry"}));const c=function(e){const t=e.crypto.randomBytes(32);return e.crypto.x25519FromSeed(t)}({crypto:this.crypto}),u=Ca(c.publicKey),l=Da(this.crypto.sha256,u),h={type:Sc,targetNode:a,networkId:e.networkId,...void 0!==e.keyPath?{keyPath:e.keyPath}:{},alg:e.alg,keyVersion:e.keyVersion,encryptedSymmetricKey:e.encryptedSymmetricKey,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:u,receiverPublicKeyHash:l},d={canonicalBody:Ia((n={crypto:this.crypto,body:h,receiverPublicKey:c.publicKey}).body),bodyHash:Da(n.crypto.sha256,n.body),receiverPublicKeyHash:Da(n.crypto.sha256,n.body.receiverPublicKey)},f=function(e){const t=void 0!==e.canonicalBody?Oa(e.crypto.sha256(Ma(e.canonicalBody))):Da(e.crypto.sha256,e.body),r=Da(e.crypto.sha256,e.body.receiverPublicKey);return{type:Sc,targetNode:e.body.targetNode,networkId:e.body.networkId,...void 0!==e.body.keyPath?{keyPath:e.body.keyPath}:{},bodyHash:t,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKeyHash:r,alg:e.body.alg,keyVersion:e.body.keyVersion}}({crypto:this.crypto,body:h,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:c.publicKey,canonicalBody:d.canonicalBody}),p=await async function(e,t,r){const n=function(e,t){if(t.body.type!==Sc)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:`body.type must be ${Sc}`})};if(t.facts.type!==Sc)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:`facts.type must be ${Sc}`})};if(t.facts.targetNode!==t.targetNode)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"facts.targetNode must equal targetNode — the UCAN audience binds the request to a single node"})};if(t.body.targetNode!==t.targetNode)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"body.targetNode must equal targetNode"})};if(t.facts.networkId!==t.networkId)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"facts.networkId must equal networkId"})};if(t.body.networkId!==t.networkId)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"body.networkId must equal networkId"})};if(t.facts.keyPath!==t.body.keyPath)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"facts.keyPath must equal body.keyPath"})};if(t.facts.alg!==t.body.alg)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"facts.alg must equal body.alg"})};if(t.facts.keyVersion!==t.body.keyVersion)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"facts.keyVersion must equal body.keyVersion"})};if(t.facts.encryptedSymmetricKeyHash!==t.body.encryptedSymmetricKeyHash)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"facts.encryptedSymmetricKeyHash must equal body.encryptedSymmetricKeyHash"})};if(t.facts.receiverPublicKeyHash!==t.body.receiverPublicKeyHash)return{ok:!1,error:Rc({code:"INVALID_INPUT",message:"facts.receiverPublicKeyHash must equal body.receiverPublicKeyHash"})};try{if(void 0!==Js(t.networkId).keyPath)throw new Gs("networkId must identify the network root")}catch(e){return{ok:!1,error:Rc({code:"INVALID_NETWORK_ID",message:e instanceof Error?e.message:String(e)})}}try{if(Js(void 0===t.body.keyPath?t.body.networkId:`${t.body.networkId}/${t.body.keyPath}`).keyPath!==t.body.keyPath||t.body.keyPath?.endsWith("/"))throw new Gs("keyPath must name an exact encryption key")}catch(e){return{ok:!1,error:Rc({code:"INVALID_INPUT",message:e instanceof Error?e.message:String(e)})}}const r=Ia(t.body);return Da(e.sha256,t.body)!==t.facts.bodyHash?{ok:!1,error:Rc({code:"INVALID_INPUT",message:"facts.bodyHash does not match the canonical body hash"})}:{ok:!0,data:t,canonicalBody:r}}(e,r);if(!n.ok)return n;try{const e=await t.signDecryptInvocation(n.data);return e.authorization&&e.invocationCid?e.canonicalBody!==n.canonicalBody?{ok:!1,error:Rc({code:"INVALID_INPUT",message:"decrypt-invocation signer returned a canonicalBody that does not match the SDK's canonicalization — signer must use the SDK-provided body"})}:{ok:!0,data:e}:{ok:!1,error:Rc({code:"INVALID_INPUT",message:"decrypt-invocation signer returned an empty authorization or invocationCid"})}}catch(e){return{ok:!1,error:Rc({code:"TRANSPORT_ERROR",cause:e instanceof Error?e:new Error(String(e)),message:`failed to sign decrypt invocation: ${e instanceof Error?e.message:String(e)}`})}}}(this.crypto,this._config.signer,{targetNode:a,networkId:e.networkId,body:h,facts:f,proof:t});if(this.assertActive(),!p.ok)return"TRANSPORT_ERROR"!==p.error.code?p:Wc(Rc({code:"INVALID_INPUT",message:"Unable to build decrypt request"}));let m;try{m=await this._config.transport.postDecrypt({targetNode:a,networkId:e.networkId,authorization:p.data.authorization,canonicalBody:p.data.canonicalBody,signal:this.abortSignal}),this.assertActive()}catch(t){const r=ro(t);return r?Wc(Jc(r)):t instanceof ds.DecryptTransportResponseError?Wc(Rc(404===t.status?{code:"NETWORK_NOT_FOUND",networkId:e.networkId,message:t.notFoundMessage}:401===t.status||403===t.status?{code:"DECRYPT_DENIED",message:"Node denied decrypt request",...void 0===t.permissionHint?{}:{permissionHint:t.permissionHint}}:{code:"INVALID_RESPONSE",message:"Node decrypt request failed"})):Wc(Jc({code:"TRANSPORT_ERROR",cause:Oc(t)}))}const g=function(e){const{crypto:t,request:r,facts:n,invocationCid:i,requestBodyHash:s,response:o}=e;if(o.type!==Ic)return{ok:!1,error:Rc({code:"INVALID_RESPONSE",message:`response.type must be ${Ic}`})};if(o.targetNode!==r.targetNode)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(o.networkId!==r.networkId)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(o.nodeId!==r.targetNode)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if("x25519-aes256gcm/v1"!==o.alg&&o.alg!==Mc)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(o.keyVersion!==r.keyVersion)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(o.encryptedSymmetricKeyHash!==r.encryptedSymmetricKeyHash)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(o.receiverPublicKeyHash!==r.receiverPublicKeyHash)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(o.invocationCid!==i)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const a=Oa(t.sha256(Ma(`${i}${s}`)));if(o.requestHash!==a)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(n.encryptedSymmetricKeyHash!==o.encryptedSymmetricKeyHash||n.receiverPublicKeyHash!==o.receiverPublicKeyHash||n.networkId!==o.networkId||n.targetNode!==o.targetNode||n.alg!==r.alg||n.keyVersion!==o.keyVersion)return{ok:!1,error:Rc({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const c=(new TextEncoder).encode(function(e){const{nodeSignature:t,...r}=e;return Ia(r)}(o)),u=Pa(o.nodeSignature);return t.verifyNodeSignature(o.nodeId,c,u)?{ok:!0,data:o}:{ok:!1,error:Rc({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:this.crypto,request:h,facts:f,invocationCid:p.data.invocationCid,requestBodyHash:f.bodyHash,response:m});if(!g.ok)return g;const y=function(e,t,r,n){const i=Pa(r.wrappedKey);if(zc(i,r.alg),r.alg===Mc){if(!n)throw new Error("V2 response requires expected key context");return function(e,t,r){const{header:n,aad:i,nonce:s,ciphertext:o}=qc(t);jc(n,r);const a=Ji.getPublicKey(e);if(!Uc(a,Fc(n.recipientPublicKey)))throw new Error("Key wrap recipient mismatch");const c=function(e,t,r,n){const i=Ji.getSharedSecret(e,t);if(i.every(e=>0===e))throw new Error("Invalid key agreement");try{return ls(hs,i,n,Lc(Bc,t,r),32)}finally{i.fill(0)}}(e,Fc(n.ephemeralPublicKey),a,Fc(n.salt));try{return an(c,s,i).decrypt(o)}finally{c.fill(0)}}(t,i,n)}return e.openWithReceiverKey(t,i)}(this.crypto,c.privateKey,g.data,{purpose:"receiver-key",networkId:h.networkId,keyPath:h.keyPath??"",keyVersion:h.keyVersion,metadata:{}}),v=function(e,t,r){Vc(t);const n=Pa(t.ciphertext),i=void 0!==t.aad?Pa(t.aad):void 0;return e.authDecrypt(r,n,i)}(this.crypto,e,y);return Gc(v)}catch(e){const t=ro(e);return Wc(t?Jc(t):Rc({code:"INVALID_RESPONSE",message:"Local decryption failed"}))}var n}assertActive(){this._config.assertActive?.()}}).serviceName="encryption",i(7250);var Zc="urn:tinycloud:encryption:",Yc=/^[a-z0-9][a-z0-9-]*$/,Qc=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Xc(e){if("string"!=typeof e||0===e.length)throw new Qc("networkId must be a non-empty string");if(!e.startsWith(Zc))throw new Qc(`networkId must start with ${Zc} (got ${JSON.stringify(e)})`);const t=e.slice(25),r=t.lastIndexOf(":");if(r<=0||r===t.length-1)throw new Qc(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const n=t.slice(0,r),i=t.slice(r+1);if(!n.startsWith("did:"))throw new Qc(`networkId ownerDid must be a DID (got ${JSON.stringify(n)})`);const s=n.split(":");if(s.length<3||s.some(e=>0===e.length))throw new Qc(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(n)})`);if(!Yc.test(i))throw new Qc(`networkId name ${JSON.stringify(i)} must match ${Yc.source}`);return{networkId:e,ownerDid:n,name:i}}var eu=Zc,tu="[a-z0-9][a-z0-9._-]{0,63}",ru=new RegExp(`^${tu}(?:/${tu}){0,7}$`),nu=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,iu=/^(did:[a-z0-9]+:[A-Za-z0-9._:-]+):([^:/]+)(?:\/(.*))?$/s,su="did:pkh:eip155:",ou=(Object.freeze(["tinycloud.encryption/decrypt","tinycloud.encryption/key.create","tinycloud.encryption/key.block","tinycloud.encryption/key.unblock"]),class extends Error{constructor(e,t){super(t),this.name="EncryptionResourceError",this.code=e}});function au(e){if(!e.startsWith(su))return e;const t=e.slice(15),r=t.indexOf(":"),n=-1===r?"":t.slice(0,r),i=-1===r?"":t.slice(r+1);if(!/^\d+$/.test(n)||!/^0x[a-fA-F0-9]{40}$/.test(i))throw new ou("bad_owner",`owner DID is not a valid did:pkh:eip155 (got ${JSON.stringify(e)})`);const s=BigInt(n);if(0n===s||s>18446744073709551615n)throw new ou("bad_owner",`did:pkh:eip155 chain id must be a positive u64 (got ${JSON.stringify(n)})`);const o=fe(i,1).slice(17);return`${su}${s}:${o}`}function cu(e){const t=au(e);if(t!==e)throw new ou("non_canonical_owner",`owner DID is not canonical (expected ${t})`)}function uu(e,t){if(0===e.length)throw new ou("empty_path",`${t} must not be empty`);if((new TextEncoder).encode(e).length>255)throw new ou("path_too_long",`${t} exceeds 255 bytes`);if(!ru.test(e))throw new ou("bad_path",`${t} ${JSON.stringify(e)} must match ${ru.source}`);const r=e.split("/");if("apps"===r[0]&&r.length<("key path"===t?3:2))throw new ou("bad_path",`${t} ${JSON.stringify(e)} under apps/ needs ${"key path"===t?"apps/<id>/<name>":"apps/<id>/"}`)}function lu(e){if("string"!=typeof e||!e.startsWith(eu))throw new ou("not_encryption_urn",`resource must start with ${eu}`);const t=e.slice(25),r=iu.exec(t);if(null===r)throw new ou("malformed",`resource is not <ownerDid>:<network>[/<path>] (got ${JSON.stringify(e)})`);const n=r[1],i=r[2],s=r[3];if(void 0===s){const e=au(n),t=`${eu}${e}:${i}`;try{Xc(t)}catch(e){if(e instanceof Qc)throw new ou("bad_network",e.message);throw e}return{kind:"network",ownerDid:e,network:i,networkId:t}}if(!nu.test(i))throw new ou("bad_network",`network ${JSON.stringify(i)} must match ${nu.source}`);cu(n);const o=`${eu}${n}:${i}`;if(s.endsWith("/")){const e=s.slice(0,-1);return uu(e,"prefix"),{kind:"prefix",ownerDid:n,network:i,networkId:o,prefix:e}}return uu(s,"key path"),{kind:"key",ownerDid:n,network:i,networkId:o,path:s}}i(1048).Buffer;var hu=Object.defineProperty,du=(e,t)=>{for(var r in t)hu(e,r,{get:t[r],enumerable:!0})},fu=(e,t,r)=>((e,t,r)=>t in e?hu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r),pu=pr({domain:ar().nullable().optional(),avatarUrl:ar().nullable().optional()});pr({domain:ar().optional(),uri:ar().optional(),chainId:cr().optional(),statement:ar().optional(),nonce:ar().optional(),expirationTime:ar().optional(),notBefore:ar().optional(),requestId:ar().optional(),resources:fr(ar()).optional()}).passthrough(),pr({address:ar(),walletAddress:ar(),chainId:cr(),sessionKey:ar(),siwe:ar(),signature:ar(),ens:pu.optional()}),Error,Object.hasOwn??Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);Error,Error;var mu={};function gu(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}du(mu,{base32:()=>_u,base32hex:()=>Nu,base32hexpad:()=>Ou,base32hexpadupper:()=>Cu,base32hexupper:()=>Ru,base32pad:()=>Su,base32padupper:()=>Iu,base32upper:()=>Tu,base32z:()=>Pu}),new Uint8Array(0);var yu=class{constructor(e,t,r){fu(this,"name"),fu(this,"prefix"),fu(this,"baseEncode"),this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},vu=class{constructor(e,t,r){fu(this,"name"),fu(this,"prefix"),fu(this,"baseDecode"),fu(this,"prefixCodePoint"),this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return wu(this,e)}},bu=class{constructor(e){fu(this,"decoders"),this.decoders=e}or(e){return wu(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function wu(e,t){return new bu({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Eu=class{constructor(e,t,r,n){fu(this,"name"),fu(this,"prefix"),fu(this,"baseEncode"),fu(this,"baseDecode"),fu(this,"encoder"),fu(this,"decoder"),this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new yu(e,t,r),this.decoder=new vu(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Au({name:e,prefix:t,encode:r,decode:n}){return new Eu(e,t,r,n)}function ku({name:e,prefix:t,alphabet:r}){const{encode:n,decode:i}=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(255!==r[o])throw new TypeError(s+" is ambiguous");r[o]=i}var a=e.length,c=e.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,i=0;e[t]===c;)n++,t++;for(var s=(e.length-t)*u+1>>>0,o=new Uint8Array(s);e[t];){var l=r[e.charCodeAt(t)];if(255===l)return;for(var h=0,d=s-1;(0!==l||h<i)&&-1!==d;d--,h++)l+=a*o[d]>>>0,o[d]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");i=h,t++}if(" "!==e[t]){for(var f=s-i;f!==s&&0===o[f];)f++;for(var p=new Uint8Array(n+(s-f)),m=n;f!==s;)p[m++]=o[f++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,s=t.length;i!==s&&0===t[i];)i++,r++;for(var o=(s-i)*l+1>>>0,u=new Uint8Array(o);i!==s;){for(var h=t[i],d=0,f=o-1;(0!==h||d<n)&&-1!==f;f--,d++)h+=256*u[f]>>>0,u[f]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,i++}for(var p=o-n;p!==o&&0===u[p];)p++;for(var m=c.repeat(r);p<o;++p)m+=e.charAt(u[p]);return m},decodeUnsafe:h,decode:function(e){var r=h(e);if(r)return r;throw new Error(`Non-${t} character`)}}}(r,e);return Au({prefix:t,name:e,encode:n,decode:e=>gu(i(e))})}function xu({name:e,prefix:t,bitsPerChar:r,alphabet:n}){const i=function(e){const t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(n);return Au({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],i=(1<<r)-1;let s="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>r;)o-=r,s+=t[i&a>>o];if(0!==o&&(s+=t[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s}(e,n,r),decode:t=>function(e,t,r,n){let i=e.length;for(;"="===e[i-1];)--i;const s=new Uint8Array(i*r/8|0);let o=0,a=0,c=0;for(let u=0;u<i;++u){const i=t[e[u]];if(void 0===i)throw new SyntaxError(`Non-${n} character`);a=a<<r|i,o+=r,o>=8&&(o-=8,s[c++]=255&a>>o)}if(o>=r||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return s}(t,i,r,e)})}var _u=xu({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Tu=xu({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Su=xu({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Iu=xu({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Nu=xu({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ru=xu({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ou=xu({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Cu=xu({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Pu=xu({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Mu={};du(Mu,{base36:()=>Du,base36upper:()=>Bu});var Du=ku({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Bu=ku({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Lu={};du(Lu,{base58btc:()=>Uu,base58flickr:()=>Fu});var Uu=ku({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Fu=ku({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),$u=128,Hu=-128,Ku=Math.pow(2,31),qu=128,ju=127,zu=Math.pow(2,7),Vu=Math.pow(2,14),Gu=Math.pow(2,21),Wu=Math.pow(2,28),Ju=Math.pow(2,35),Zu=Math.pow(2,42),Yu=Math.pow(2,49),Qu=Math.pow(2,56),Xu=Math.pow(2,63),el={encode:function e(t,r,n){r=r||[];for(var i=n=n||0;t>=Ku;)r[n++]=255&t|$u,t/=128;for(;t&Hu;)r[n++]=255&t|$u,t>>>=7;return r[n]=0|t,e.bytes=n-i+1,r},decode:function e(t,r){var n,i=0,s=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],i+=s<28?(n&ju)<<s:(n&ju)*Math.pow(2,s),s+=7}while(n>=qu);return e.bytes=o-r,i},encodingLength:function(e){return e<zu?1:e<Vu?2:e<Gu?3:e<Wu?4:e<Ju?5:e<Zu?6:e<Yu?7:e<Qu?8:e<Xu?9:10}};function tl(e,t=0){return[el.decode(e,t),el.decode.bytes]}function rl(e,t,r=0){return el.encode(e,t,r),t}function nl(e){return el.encodingLength(e)}function il(e,t){const r=t.byteLength,n=nl(e),i=n+nl(r),s=new Uint8Array(i+r);return rl(e,s,0),rl(r,s,n),s.set(t,i),new sl(e,r,t,s)}var sl=class{constructor(e,t,r,n){fu(this,"code"),fu(this,"size"),fu(this,"digest"),fu(this,"bytes"),this.code=e,this.size=t,this.digest=r,this.bytes=n}};function ol(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==Uu.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const i=t.get(n);if(null==i){const i=r.encode(e).slice(1);return t.set(n,i),i}return i}(r,ul(e),t??Uu.encoder):function(e,t,r){const{prefix:n}=r,i=t.get(n);if(null==i){const i=r.encode(e);return t.set(n,i),i}return i}(r,ul(e),t??_u.encoder)}var al,cl=new WeakMap;function ul(e){const t=cl.get(e);if(null==t){const t=new Map;return cl.set(e,t),t}return t}var ll=class e{constructor(e,t,r,n){fu(this,"code"),fu(this,"version"),fu(this,"multihash"),fu(this,"bytes"),fu(this,"/"),fu(this,al,"CID"),this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:t,multihash:r}=this;if(t!==hl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==dl)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:t,digest:r}=this.multihash,n=il(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e.bytes,r.bytes)}}(e.multihash,r.multihash)}toString(e){return ol(this,e)}toJSON(){return{"/":ol(this)}}link(){return this}[(al=Symbol.toStringTag,Symbol.for("nodejs.util.inspect.custom"))](){return`CID(${this.toString()})`}static asCID(t){if(null==t)return null;const r=t;if(r instanceof e)return r;if(null!=r["/"]&&r["/"]===r.bytes||r.asCID===r){const{version:t,code:n,multihash:i,bytes:s}=r;return new e(t,n,i,s??fl(t,n,i.bytes))}if(!0===r[pl]){const{version:t,multihash:n,code:i}=r,s=function(e){const t=gu(e),[r,n]=tl(t),[i,s]=tl(t.subarray(n)),o=t.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new sl(r,i,o,t)}(n);return e.create(t,i,s)}return null}static create(t,r,n){if("number"!=typeof r)throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:if(r!==hl)throw new Error(`Version 0 CID must use dag-pb (code: ${hl}) block encoding`);return new e(t,r,n,n.bytes);case 1:{const i=fl(t,r,n.bytes);return new e(t,r,n,i)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,hl,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){const[r,n]=e.decodeFirst(t);if(0!==n.length)throw new Error("Incorrect length");return r}static decodeFirst(t){const r=e.inspectBytes(t),n=r.size-r.multihashSize,i=gu(t.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");const s=i.subarray(r.multihashSize-r.digestSize),o=new sl(r.multihashCode,r.digestSize,s,i);return[0===r.version?e.createV0(o):e.createV1(r.codec,o),t.subarray(r.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=tl(e.subarray(t));return t+=n,r};let n=r(),i=hl;if(18===n?(n=0,t=0):i=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const s=t,o=r(),a=r(),c=t+a;return{version:n,codec:i,multihashCode:o,digestSize:a,multihashSize:c-s,size:c}}static parse(t,r){const[n,i]=function(e,t){switch(e[0]){case"Q":{const r=t??Uu;return[Uu.prefix,r.decode(`${Uu.prefix}${e}`)]}case Uu.prefix:{const r=t??Uu;return[Uu.prefix,r.decode(e)]}case _u.prefix:{const r=t??_u;return[_u.prefix,r.decode(e)]}case Du.prefix:{const r=t??Du;return[Du.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(t,r),s=e.decode(i);if(0===s.version&&"Q"!==t[0])throw Error("Version 0 CID string must not include multibase prefix");return ul(s).set(n,t),s}},hl=112,dl=18;function fl(e,t,r){const n=nl(e),i=n+nl(t),s=new Uint8Array(i+r.byteLength);return rl(e,s,0),rl(t,s,n),s.set(r,i),s}var pl=Symbol.for("@ipld/js-cid/CID"),ml=(new TextEncoder,Error,Object.hasOwn??Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty),new Set(["tinycloud.kv","tinycloud.sql","tinycloud.vfs"])),gl=new Map;for(const e of J){if(!ml.has(e.service))continue;if(void 0!==e.aliasOf||void 0!==e.implies||e.urn.endsWith("/*"))continue;const t=gl.get(e.service);void 0!==t?t.add(e.urn):gl.set(e.service,new Set([e.urn]))}var yl={};du(yl,{base10:()=>vl});var vl=ku({prefix:"9",name:"base10",alphabet:"0123456789"}),bl={};du(bl,{base16:()=>wl,base16upper:()=>El});var wl=xu({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),El=xu({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Al={};du(Al,{base2:()=>kl});var kl=xu({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),xl={};du(xl,{base256emoji:()=>Il});var _l=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Tl=_l.reduce((e,t,r)=>(e[r]=t,e),[]),Sl=_l.reduce((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]),Il=Au({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+Tl[t],"")},decode:function(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw new Error(`Invalid character: ${r}`);const n=Sl[e];if(null==n)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}}),Nl={};du(Nl,{base64:()=>Rl,base64pad:()=>Ol,base64url:()=>Cl,base64urlpad:()=>Pl});var Rl=xu({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ol=xu({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Cl=xu({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Pl=xu({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Ml={};du(Ml,{base8:()=>Dl});var Dl=xu({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Bl={};du(Bl,{identity:()=>Ll});var Ll=Au({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)});du((new TextEncoder,new TextDecoder,{}),{identity:()=>Fl});var Ul=gu,Fl={code:0,name:"identity",encode:Ul,digest:function(e,t){if(null!=t?.truncate&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return il(0,Ul(e))}};function $l({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:i}){return new Hl(e,t,r,n,i)}du({},{sha256:()=>jl,sha512:()=>zl});var Hl=class{constructor(e,t,r,n,i){fu(this,"name"),fu(this,"code"),fu(this,"encode"),fu(this,"minDigestLength"),fu(this,"maxDigestLength"),this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??20,this.maxDigestLength=i}digest(e,t){if(null!=t?.truncate){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(null!=this.maxDigestLength&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Kl(r,this.code,t?.truncate):r.then(e=>Kl(e,this.code,t?.truncate))}throw Error("Unknown type, must be binary type")}};function Kl(e,t,r){if(null!=r&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return il(t,e)}function ql(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var jl=$l({name:"sha2-256",code:18,encode:ql("SHA-256")}),zl=$l({name:"sha2-512",code:19,encode:ql("SHA-512")}),Vl={...Bl,...Al,...Ml,...yl,...bl,...mu,...Mu,...Lu,...Nl,...xl};new TextEncoder,Object.hasOwn??Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);Error,Object.hasOwn??Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty),pr({alg:Er("EdDSA"),jwk:pr({alg:Er("EdDSA"),crv:Er("Ed25519"),kty:Er("OKP"),x:ar().min(1)}).strict(),typ:Er("JWT"),ucv:Er("0.10.0")}).strict(),pr({att:vr(vr(fr(dr()).min(1))),aud:ar().min(1),exp:cr().int(),fct:fr(vr(dr())).length(1),iss:ar().min(1),nbf:cr().int(),nnc:ar().min(1),prf:fr(ar().min(1))}).strict(),vr(vr(fr(dr()).min(1)));var Gl=["schema-invalid","challenge-not-found","challenge-expired","challenge-nonce-consumed","presentation-expired","presentation-audience-mismatch","presentation-evidence-missing","digest-mismatch","evidence-requirement-unknown","evidence-requirement-duplicate","holder-signature-invalid","holder-signature-signer-mismatch","id-mismatch","requested-capabilities-exceeded","requested-capabilities-hash-mismatch","evidence-authority-missing","evidence-credential-invalid","evidence-domain-invalid","evidence-domain-missing","evidence-freshness-expired","evidence-freshness-unestablishable","evidence-issuer-missing","evidence-issuer-untrusted","evidence-presentation-invalid","evidence-requirements-invalid","evidence-verifier-unsupported","enrollment-binding-mismatch","enrollment-expired","enrollment-not-yet-valid","enrollment-out-of-scope","enrollment-revoked","enrollment-revoked-irreversible","enrollment-status-rollback","signature-invalid","signer-not-authorized","audience-mismatch","capability-not-contained","evidence-invalid","evidence-missing","evidence-stale","evidence-subject-mismatch","evidence-untrusted","grant-ttl-exceeds-policy","holder-did-mismatch","holder-key-not-permitted","holder-signature-invalid","owner-mismatch","policy-expired","policy-inactive","policy-not-found","policy-not-satisfied","policy-revoked","policy-status-rollback","rate-limited"],Wl=(Error,wr(()=>mr([ar(),cr().finite(),ur(),hr(),fr(Wl),vr(Wl)]))),Jl=ar().refine(e=>void 0!==function(e){if(!/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.test(e))return;const t=Date.parse(e);if(Number.isNaN(t))return;const r=new Date(t).toISOString().replace(".000Z","Z"),n=Date.parse(e);return Date.parse(r)===n?t:void 0}(e),{message:"must be strict RFC 3339 date-time with timezone"}),Zl=pr({schema:ar(),engineRecordId:ar(),ownerDid:ar(),endpoint:ar(),audience:ar(),supportedPolicyVersions:fr(ar()),supportedEvidenceVerifiers:fr(ar()),grantIssuerDid:ar(),expiresAt:Jl,signature:pr({suite:ar(),signerDid:ar(),value:ar()}).strict()}).strict(),Yl=pr({endpoint:ar().url(),audience:ar(),supportedEvidenceVerifiers:yr([Er("w3c.vc/credential/v1")]),signedRecord:Zl}).strict(),Ql=pr({schema:Er("xyz.tinycloud.exchange/owner-node-endpoint/v1"),endpoint:ar().url(),spaceId:ar().min(1)}).strict(),Xl=pr({resourceType:ar(),resourceId:ar(),requestedCapabilities:fr(Wl).min(1)}).strict(),eh=(pr({schema:Er("xyz.tinycloud.exchange/transcript-bootstrap/v0"),policyId:ar(),policyEngine:Yl,ownerNode:Ql,resourceHint:Xl}).strict(),pr({suite:ar(),signerDid:ar(),value:ar()}).strict()),th=pr({schema:Er("xyz.tinycloud.policy/challenge/v0"),challengeId:ar(),policyId:ar(),audience:ar(),nonce:ar().min(16),challengeExpiresAt:Jl,acceptedSuites:fr(ar()).min(1),requestedCapabilitiesTemplate:fr(Wl).optional(),signature:eh}).strict(),rh=(pr({challenge:th}).strict(),pr({schema:Er("xyz.tinycloud.policy-engine/denial/v0"),code:Ar(Gl),message:ar().optional()}).strict(),pr({error:pr({code:Ar(Gl),message:ar().optional()}).strict()}).strict(),pr({delegationId:ar(),issuanceId:ar().min(1),issuerDid:ar(),holderDid:ar(),policyId:ar(),capabilityHashHex:ar().regex(/^[0-9a-f]{64}$/),revocationMode:Er("refresh_only"),issuedAt:Jl,expiresAt:Jl,terminal:ur(),encoded:ar()}).strict());pr({delegation:rh}).strict(),pr({cid:ar().min(1),activated:fr(ar()),skipped:fr(ar())}).strict(),pr({rows:fr(Wl)}).strict(),pr({value:Wl}).strict(),new Map([{name:"listen.getConversation",sql:"SELECT id, title, source, source_id, source_url, started_at, ended_at, duration_secs, summary, metadata, transcript_json, transcript_text, created_at, updated_at FROM conversation WHERE id = ?",fixedParams:[{index:0,value:"{conversationId}"}]},{name:"listen.listParticipants",sql:"SELECT id, name, email, speaker_label FROM participant WHERE conversation_id = ? ORDER BY COALESCE(speaker_label, name), id",fixedParams:[{index:0,value:"{conversationId}"}]}].map(e=>[e.name,e]));var nh=pr({kty:ar(),crv:ar().optional(),x:ar().optional(),y:ar().optional(),d:ar().optional(),e:ar().optional(),n:ar().optional(),kid:ar().optional(),alg:ar().optional(),use:ar().optional(),key_ops:fr(ar()).optional()}),ih=Ar(["main","session","ingested"]),sh=pr({id:ar(),did:ar(),type:ih,jwk:nh.optional(),priority:cr()}),oh=(pr({code:ar(),message:ar(),service:Er("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>sr(t=>t instanceof e,t))(Error).optional(),meta:vr(ar(),dr()).optional()}),pr({cid:ar(),delegateDID:ar(),spaceId:ar(),path:ar(),actions:fr(ar()),caveats:fr(vr(ar(),dr())).optional(),expiry:kr(),isRevoked:ur(),delegatorDID:ar().optional(),createdAt:kr().optional(),parentCid:ar().optional(),allowSubDelegation:ur().optional(),authHeader:ar().optional()})),ah=pr({cid:ar().min(1),lease_cid:ar().min(1),generation:cr().int().nonnegative().safe(),previous_stamp_cid:ar().min(1),new_end:cr().int().nonnegative().safe(),signed_bytes:ar().min(1),signature:ar().min(1)}).strict(),ch=(pr({cid:ar().min(1),status:Ar(["active","revoked","expired","unavailable","not_found"]),exists:ur(),active:ur(),revoked:ur(),expired:ur(),effective_expiry:cr().int().nullable().optional(),renewal_history:fr(ah).optional()}).strict().superRefine((e,t)=>{("active"===e.status?e.exists&&e.active&&!e.revoked&&!e.expired:"revoked"===e.status?e.exists&&!e.active&&e.revoked&&!e.expired:"expired"===e.status?e.exists&&!e.active&&!e.revoked&&e.expired:"unavailable"===e.status?e.exists&&!e.active&&!e.revoked&&!e.expired:!(e.exists||e.active||e.revoked||e.expired))||t.addIssue({code:Ie.custom,message:"delegation status flags do not match status"})}),pr({revoked:Er(!0),cid:ar().min(1)}).strict(),pr({resource:ar().min(1),actions:fr(ar()),caveats:fr(vr(ar(),dr()))}).strict()),uh=ar().datetime({offset:!0}).transform(e=>new Date(e)),lh=pr({cid:ar().min(1),direction:Ar(["granted","received"]),delegatorDid:ar().min(1),delegateDid:ar().min(1),resources:fr(ch),parents:fr(ar()),issuedAt:uh.nullable(),notBefore:uh.nullable(),expiresAt:uh.nullable(),status:Ar(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:uh.nullable().optional(),revokedBy:ar().optional(),revokedAncestorCid:ar().optional()}).strict(),hh=(pr({schemaVersion:Er(2),items:fr(lh),nextCursor:ar().optional()}).strict(),pr({direction:Ar(["granted","received","all","issued"]).optional(),status:Ar(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:ar().trim().min(1).optional(),limit:cr().int().min(1).max(100).optional(),cursor:ar().min(1).optional()}).strict(),pr({resource:ar(),action:ar(),keys:fr(sh),delegation:oh,expiresAt:kr().optional()}),pr({cid:ar(),spaceId:ar(),delegator:ar(),delegatee:ar(),keyId:ar().optional(),path:ar(),actions:fr(ar()),expiry:kr().optional(),notBefore:kr().optional(),isRevoked:ur(),createdAt:kr(),parentCid:ar().optional()}),pr({delegateDID:ar(),path:ar(),actions:fr(ar()),expiry:kr().optional(),disableSubDelegation:ur().optional(),statement:ar().optional()})),dh=(fr(oh),pr({root:oh,chain:fr(oh),leaf:oh}),Ar(["granted","received","all"])),fh=(pr({direction:dh.optional(),path:ar().optional(),actions:fr(ar()).optional(),includeRevoked:ur().optional(),delegator:ar().optional(),delegatee:ar().optional(),validAt:kr().optional(),limit:cr().optional(),cursor:ar().optional()}),Ar(["owned","delegated"])),ph=(pr({id:ar(),name:ar().optional(),owner:ar(),type:fh,permissions:fr(ar()).optional(),expiresAt:kr().optional()}),Ar(["base64","compact","ipfs"]));pr({token:ar(),url:ar(),delegation:oh,schema:ph,expiresAt:kr().optional(),description:ar().optional()}),function(e){pr({data:e,delegation:oh,spaceId:ar(),path:ar()})}(dr());var mh=pr({persist:ur().optional(),validateChain:ur().optional(),keyName:ar().optional(),createSessionKey:ur().optional(),priority:cr().optional()}),gh=(pr({includePlacement:ur().optional(),path:ar().optional(),actions:fr(ar()).optional(),resources:fr(pr({path:ar(),actions:fr(ar()).optional()})).optional(),expiry:kr().optional(),schema:ph.optional(),description:ar().optional(),baseUrl:ar().optional(),allowSubDelegation:ur().optional()}),pr({hosts:fr(ar()),accountSpaceId:ar().min(1).optional(),session:dr().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),invoke:dr().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),invokeAny:dr().refine(e=>void 0===e||"function"==typeof e,{message:"Expected an invokeAny function or undefined"}).optional(),signOwnerRevocation:sr().optional(),sessionInvocationSigner:sr().optional(),resourceTransport:sr().optional(),fetch:dr().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),pr({createSessionKey:dr().refine(e=>"function"==typeof e,{message:"Expected a function"}),getJWK:dr().refine(e=>"function"==typeof e,{message:"Expected a function"}),getDID:dr().refine(e=>"function"==typeof e,{message:"Expected a function"})})),yh=(pr({siwe:ar(),signature:ar(),version:cr(),cid:ar().optional()}),pr({service:ar(),space:ar(),path:ar(),actions:fr(ar()),caveats:fr(vr(ar(),dr())).optional()}));pr({session:dr().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:ar(),spaceId:ar(),abilities:vr(ar(),vr(ar(),fr(ar()))),expirationSecs:cr(),notBeforeSecs:cr().optional(),disableSubDelegation:ur().optional()}),pr({delegation:ar(),cid:ar(),delegateDID:ar(),expiry:kr(),resources:fr(yh)});var vh=6048e5,bh=pr({service:ar().min(1),space:ar().min(1),path:ar(),actions:fr(ar().min(1)).min(1),caveats:fr(vr(dr())).optional()}).strict();function wh(e=0){return new Uint8Array(e)}pr({cid:ar().min(1),delegationHeader:pr({Authorization:ar().min(1)}).strict(),ownerAddress:ar().min(1),chainId:cr().int().nonnegative(),host:ar().url().optional(),spaceId:ar().min(1),path:ar(),actions:fr(ar().min(1)).min(1),caveats:fr(vr(dr())).optional(),expiry:kr(),delegateDID:ar().min(1),delegatorDID:ar().min(1).optional(),parentCid:ar().min(1).optional(),disableSubDelegation:ur().optional(),resources:fr(bh).min(1).optional()}).strict();Math.pow(2,7),Math.pow(2,14),Math.pow(2,21),Math.pow(2,28),Math.pow(2,35),Math.pow(2,42),Math.pow(2,49);function Eh(e,t){null==t&&(t=e.reduce((e,t)=>e+t.length,0));const r=wh(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Ah(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var kh=Ah("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),xh=Ah("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{const t=wh((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),_h={utf8:kh,"utf-8":kh,hex:Vl.base16,latin1:xh,ascii:xh,binary:xh,...Vl};function Th(e,t="utf8"){const r=_h[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}function Sh(e,t="utf8"){const r=_h[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}var Ih=class extends Error{constructor(){super(...arguments),fu(this,"name","InvalidMultiaddrError")}};fu(Ih,"name","InvalidMultiaddrError");var Nh=class extends Error{constructor(){super(...arguments),fu(this,"name","ValidationError")}};fu(Nh,"name","ValidationError");var Rh=class extends Error{constructor(){super(...arguments),fu(this,"name","InvalidParametersError")}};fu(Rh,"name","InvalidParametersError");var Oh=class extends Error{constructor(){super(...arguments),fu(this,"name","UnknownProtocolError")}};fu(Oh,"name","UnknownProtocolError");var Ch=new class{constructor(){fu(this,"index",0),fu(this,"input","")}new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{const t=this.readChar();if(t===e)return t})}readSeparator(e,t,r){return this.readAtomically(()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()})}readNumber(e,t,r,n){return this.readAtomically(()=>{let i=0,s=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*n)-1;for(;;){const r=this.readAtomically(()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r});if(void 0===r)break;if(i*=e,i+=r,i>c)return;if(s+=1,void 0!==t&&s>t)return}return 0===s||!r&&a&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(void 0===r)return;e[t]=r}return e})}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,()=>this.readIPv4Addr());if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,()=>this.readNumber(16,4,!0,2));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically(()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const i=new Uint8Array(14),s=16-(r+2),[o]=e(i.subarray(0,s));return t.set(i.subarray(0,o),16-o),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function Ph(e){return Boolean(function(e){if(!(e.length>15))return Ch.new(e).parseWith(()=>Ch.readIPv4Addr())}(e))}function Mh(e){return t=>Sh(t,e)}function Dh(e){return t=>Th(t,e)}function Bh(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Lh(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function Uh(e){const t=e.subarray(0,e.length-2),r=e.subarray(e.length-2);return`${Sh(t,"base32")}:${Bh(r)}`}var Fh,$h=function(e){e=e.toString().trim();const t=new Uint8Array(4);return e.split(/\./g).forEach((e,r)=>{const n=parseInt(e,10);if(isNaN(n)||n<0||n>255)throw new Ih("Invalid byte value in IP address");t[r]=n}),t},Hh=Object.values(Vl).map(e=>e.decoder),Kh=function(){let e=Hh[0].or(Hh[1]);return Hh.slice(2).forEach(t=>e=e.or(t)),e}(),qh=function(...e){return t=>{for(const r of e)r(t)}}(function(e){if(parseInt(e).toString()!==e)throw new Nh("Value must be an integer")},function(e){if(e<0)throw new Nh("Value must be a positive integer, or zero")},e=>{if(e>65535)throw new Nh("Value must be smaller than or equal to 65535")}),jh=-1,zh=new class{constructor(){fu(this,"protocolsByCode",new Map),fu(this,"protocolsByName",new Map)}getProtocol(e){let t;if(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e),null==t)throw new Oh(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){const t=this.protocolsByCode.get(e);null!=t&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(e=>{this.protocolsByName.delete(e)}))}};[{code:4,name:"ip4",size:32,valueToBytes:$h,bytesToValue:function(e){if(4!==e.byteLength)throw new Ih("IPv4 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate:e=>{if(!Ph(e))throw new Nh(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Lh,bytesToValue:Bh,validate:qh},{code:273,name:"udp",size:16,valueToBytes:Lh,bytesToValue:Bh,validate:qh},{code:33,name:"dccp",size:16,valueToBytes:Lh,bytesToValue:Bh,validate:qh},{code:41,name:"ip6",size:128,valueToBytes:function(e){let t=0;const r=(e=e.toString().trim()).split(":",8);let n;for(n=0;n<r.length;n++){let e;Ph(r[n])&&(e=$h(r[n]),r[n]=Sh(e.subarray(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,Sh(e.subarray(2,4),"base16"))}if(""===r[0])for(;r.length<8;)r.unshift("0");else if(""===r[r.length-1])for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&""!==r[n];n++);const e=[n,1];for(n=9-r.length;n>0;n--)e.push("0");r.splice.apply(r,e)}const i=new Uint8Array(t+16);for(n=0;n<r.length;n++){""===r[n]&&(r[n]="0");const e=parseInt(r[n],16);if(isNaN(e)||e<0||e>65535)throw new Ih("Invalid byte value in IP address");i[t++]=e>>8&255,i[t++]=255&e}return i},bytesToValue:function(e){if(16!==e.byteLength)throw new Ih("IPv6 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r+=2){const n=e[r],i=e[r+1],s=`${n.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;t.push(s)}const r=t.join(":");try{const e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ih(`Invalid IPv6 address "${r}"`)}},stringToValue:function(e){try{const t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new Ih(`Invalid IPv6 address "${e}"`)}},validate:e=>{if(!Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Ch.new(e).parseWith(()=>Ch.readIPv6Addr())}(e)))throw new Nh(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:jh},{code:43,name:"ipcidr",size:8,bytesToValue:Mh("base10"),valueToBytes:Dh("base10")},{code:53,name:"dns",size:jh},{code:54,name:"dns4",size:jh},{code:55,name:"dns6",size:jh},{code:56,name:"dnsaddr",size:jh},{code:132,name:"sctp",size:16,valueToBytes:Lh,bytesToValue:Bh,validate:qh},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:jh,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:jh,bytesToValue:Mh("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Dh("base58btc")(e):ll.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Uh,valueToBytes:function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=Th(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const i=Lh(n);return Eh([r,i],r.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:Uh,valueToBytes:function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=_u.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const i=Lh(n);return Eh([r,i],r.length+i.length)}},{code:446,name:"garlic64",size:jh},{code:447,name:"garlic32",size:jh},{code:448,name:"tls"},{code:449,name:"sni",size:jh},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:jh,bytesToValue:(Fh=Cl,e=>Fh.encoder.encode(e)),valueToBytes:function(e){return Kh.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:jh,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:jh}].forEach(e=>{zh.addProtocol(e)});var Vh=Symbol.for("@multiformats/multiaddr");new WeakMap,new WeakMap,new WeakMap;var Gh="[a-fA-F\\d:]",Wh=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${Gh})|(?<=${Gh})(?=\\s|$))`:"",Jh="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Zh="[a-fA-F\\d]{1,4}",Yh=`\n(?:\n(?:${Zh}:){7}(?:${Zh}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${Zh}:){6}(?:${Jh}|:${Zh}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${Zh}:){5}(?::${Jh}|(?::${Zh}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${Zh}:){4}(?:(?::${Zh}){0,1}:${Jh}|(?::${Zh}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${Zh}:){3}(?:(?::${Zh}){0,2}:${Jh}|(?::${Zh}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${Zh}:){2}(?:(?::${Zh}){0,3}:${Jh}|(?::${Zh}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${Zh}:){1}(?:(?::${Zh}){0,4}:${Jh}|(?::${Zh}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${Zh}){0,5}:${Jh}|(?::${Zh}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Qh=new RegExp(`(?:^${Jh}$)|(?:^${Yh}$)`),Xh=new RegExp(`^${Jh}$`),ed=new RegExp(`^${Yh}$`),td=e=>e&&e.exact?Qh:new RegExp(`(?:${Wh(e)}${Jh}${Wh(e)})|(?:${Wh(e)}${Yh}${Wh(e)})`,"g");td.v4=e=>e&&e.exact?Xh:new RegExp(`${Wh(e)}${Jh}${Wh(e)}`,"g"),td.v6=e=>e&&e.exact?ed:new RegExp(`${Wh(e)}${Yh}${Wh(e)}`,"g");var{toString:rd}=Object.prototype;Error;Error,Error,function(){const e=new Map}(),Math.ceil(525600),Error;var nd=pr({key:nh.refine(e=>"string"==typeof e.d&&e.d.length>0,{message:"JWK must include private key (d parameter)"}),keyDid:ar().min(1,"keyDid is required"),delegation:oh,path:ar().min(1,"path is required"),resources:fr(pr({path:ar().min(1),actions:fr(ar().min(1)).min(1)})).min(2).max(16).optional(),host:ar().url("host must be a valid URL"),spaceId:ar().min(1,"spaceId is required"),version:Er(1)});gr("version",[nd,nd.extend({version:Er(2),placement:sr(e=>null!==e&&"object"==typeof e)})]),pr({autoSubdelegate:ur().optional(),useSessionKey:ur().optional(),ingestOptions:mh.optional()}),pr({hosts:fr(ar().url()).min(1,"At least one host URL is required"),session:dr().refine(e=>void 0===e||null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object or undefined"}).optional(),invoke:dr().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),fetch:dr().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional(),keyProvider:gh,registry:dr().refine(e=>null!==e&&"object"==typeof e,{message:"Expected an ICapabilityKeyRegistry object"}),createKVService:dr().refine(e=>"function"==typeof e,{message:"Expected a createKVService factory function"}),baseUrl:ar().optional(),createDelegation:dr().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a createDelegation function or undefined"}).optional(),createDelegationWasm:dr().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a createDelegationWasm function or undefined"}).optional(),computeCid:dr().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a computeCid function or undefined"}).optional(),pathPrefix:ar().optional(),sessionExpiry:lr().optional(),onRootDelegationNeeded:dr().refine(e=>void 0===e||"function"==typeof e,{message:"Expected an onRootDelegationNeeded function or undefined"}).optional()});var id=class extends Error{constructor(e){super(`Manifest validation failed: ${e}`),this.name="ManifestValidationError"}},sd="tinycloud.vault",od=Object.freeze({kv:"tinycloud.kv",space:"tinycloud.space",sql:"tinycloud.sql",duckdb:"tinycloud.duckdb",capabilities:"tinycloud.capabilities",hooks:"tinycloud.hooks",encryption:"tinycloud.encryption",delegation:"tinycloud.delegation"}),ad="tinycloud.encryption",cd="encryption";function ud(e){return e.service===ad?function(e){if("string"!=typeof e.path||!e.path.startsWith("urn:tinycloud:encryption:"))throw new id(`tinycloud.encryption entries require path to be a networkId URN (got ${JSON.stringify(e.path)})`);const t=e.path.endsWith("/share/"),r=e.path.indexOf("/");if(-1!==r&&!t)return[hd(e,e.path.slice(0,r),e.path.slice(r+1))];try{const r=Ws(t?e.path.slice(0,-7):e.path);if(t&&"default"!==r.name)throw new Error("share prefix requires default network")}catch{throw new id("tinycloud.encryption entries require a valid networkId URN")}const n=[];for(const t of e.actions)if("decrypt"!==t&&"tinycloud.encryption/decrypt"!==t)if("network.create"!==t&&"tinycloud.encryption/network.create"!==t){if("network.revoke"!==t&&"tinycloud.encryption/network.revoke"!==t){if(t.includes("/"))throw new id(`unknown encryption action ${JSON.stringify(t)}; expected decrypt, network.create, or network.revoke`);throw new id(`unknown encryption action ${JSON.stringify(t)}; expected decrypt, network.create, or network.revoke`)}n.push("tinycloud.encryption/network.revoke")}else n.push("tinycloud.encryption/network.create");else n.push("tinycloud.encryption/decrypt");const i=[],s=new Set;for(const e of n)s.has(e)||(i.push(e),s.add(e));if(t&&i.some(e=>"tinycloud.encryption/decrypt"!==e))throw new id("share prefix only supports decrypt");return[{service:ad,space:cd,path:e.path,actions:i,skipPrefix:!0,...void 0!==e.expiry?{expiry:e.expiry}:{},...void 0!==e.description?{description:e.description}:{}}]}(e):e.service!==sd?[{...e,actions:(t=e.service,r=e.actions,r.map(e=>e.includes("/")?e:`${t}/${e}`))}]:function(e){const t=new Map;for(const r of e.actions){const e=fd(r);for(const r of e.bases){const n=t.get(r)??[];n.includes(e.action)||n.push(e.action),t.set(r,n)}}return[...t.entries()].map(([t,r])=>({...e,service:"tinycloud.kv",path:pd(t,e.path),actions:r,skipPrefix:!0}))}(e);var t,r}Object.freeze(Object.fromEntries(Object.entries(od).map(([e,t])=>[t,e])));var ld=/^[a-z][a-z0-9_]{0,63}$/;function hd(e,t,r){if(r!==Ha&&!function(e){const t=e.split("/"),r=t[t.length-1];return!(t.length<2||"secrets"!==t[0]||!ld.test(r)||t.some(e=>e.length>64)||void 0===Ka([...t.slice(1,-1),r.toUpperCase()].join("/")))}(r)){if("secrets"===r||r.startsWith("secrets/"))throw new id("secret keys must be exact: secrets/<name> or secrets/scoped/<scope>/<name>, with the name in lower case");throw new id("named keys go in manifest.keys")}let n;try{const e=lu(t);if("network"!==e.kind||"default"!==e.network)throw new Error("not the default network");n=function(e,t){const r=function(e){let t;try{t=Xc(e)}catch(e){if(e instanceof Qc)throw new ou("bad_network",e.message);throw e}return cu(t.ownerDid),t.networkId}(e);uu(t,"key path");const n=`${r}/${t}`;return function(e,t){if(lu(e).networkId!==t)throw new ou("malformed",`built resource does not round-trip (got ${JSON.stringify(e)})`)}(n,r),n}(e.networkId,r)}catch{throw new id("secret key entries require the owner's default network")}const i=[];for(const t of e.actions){const e=t.startsWith("tinycloud.encryption/")?t:`tinycloud.encryption/${t}`;if("tinycloud.encryption/decrypt"!==e&&"tinycloud.encryption/key.create"!==e)throw new id(`unknown secret key action ${JSON.stringify(t)}; expected decrypt or key.create`);i.includes(e)||i.push(e)}if(0===i.length)throw new id("secret key entries need decrypt or key.create");return{service:ad,space:cd,path:n,actions:i,skipPrefix:!0,...void 0!==e.expiry?{expiry:e.expiry}:{},...void 0!==e.description?{description:e.description}:{}}}var dd="[a-z0-9][a-z0-9._-]{0,63}";function fd(e){const t=function(e){if(e.startsWith(`${sd}/`))return e.slice(`${sd}/`.length);if(e.startsWith("tinycloud.kv/"))return e.slice(13);if(e.includes("/"))throw new id(`unknown vault action ${JSON.stringify(e)}; expected a tinycloud.vault or tinycloud.kv action`);return e}(e);if("read"===t||"get"===t)return{bases:["vault"],action:"tinycloud.kv/get"};if("write"===t||"put"===t)return{bases:["vault"],action:"tinycloud.kv/put"};if("delete"===t||"del"===t)return{bases:["vault"],action:"tinycloud.kv/del"};if("list"===t)return{bases:["vault"],action:"tinycloud.kv/list"};if("head"===t)return{bases:["vault"],action:"tinycloud.kv/get"};if("metadata"===t)return{bases:["vault"],action:"tinycloud.kv/metadata"};throw new id(`unknown vault action ${JSON.stringify(e)}; expected read, write, delete, get, put, del, list, head, or metadata`)}function pd(e,t){return`${e}/${t.startsWith("/")?t.slice(1):t}`}new RegExp(`^${dd}$`),new RegExp(`^${dd}(?:/${dd}){2,7}$`),Error,Error,Error,Math.ceil(139810172),Error,(new TextEncoder).encode("tinycloud-share-envelope-v1"),Error,Error;var md=gr("kind",[pr({kind:Er("exactEmail"),value:ar().min(1)}).strict(),pr({kind:Er("emailDomain"),value:ar().min(1)}).strict(),pr({kind:Er("recipientDid"),value:ar().regex(/^did:[a-z0-9]+:.+$/)}).strict(),pr({kind:Er("bearer")}).strict()]),gd=gr("kind",[pr({kind:Er("exact"),path:ar().min(1)}).strict(),pr({kind:Er("prefix"),path:ar().min(1)}).strict()]),yd=Ar(["read","list","edit"]),vd=(pr({recipientMatcher:md,spaceId:ar().min(1),resource:gd,actions:fr(yd).min(1),expiresAt:lr()}).strict(),pr({trustedOrigins:fr(ar().url()).min(1),maxInlineBytes:cr().int().positive().optional(),maxArtifactBytes:cr().int().positive().optional(),maxContentBytes:cr().int().positive().optional(),maxSealedContentBytes:cr().int().positive().optional()}).strict(),Ar(["tinycloud.kv/get","tinycloud.kv/metadata","tinycloud.kv/list","tinycloud.kv/put"])),bd=Ar(["tinycloud.kv/get","tinycloud.kv/metadata","tinycloud.kv/list","tinycloud.kv/put","tinycloud.sql/read"]),wd=gr("kind",[pr({kind:Er("kv"),action:vd,space:ar().min(1),path:ar().min(1)}).strict(),pr({kind:Er("sql"),action:Er("tinycloud.sql/read"),space:ar().min(1),database:ar().min(1),path:ar().min(1),statement:ar().min(1),arguments:vr(cr().int().safe()),argumentsDigest:ar().min(1)}).strict()]),Ed=gr("kind",[pr({kind:Er("exactEmail"),value:ar().min(1)}).strict(),pr({kind:Er("emailDomain"),value:ar().min(1)}).strict(),pr({kind:Er("recipientDid"),value:ar().regex(/^did:[a-z0-9]+:.+$/)}).strict()]),Ad=pr({version:Er(2),nonce:ar().min(1),jti:ar().min(1),senderDid:ar().min(1),recipientMatcher:Ed,targetOrigin:ar().url(),nodeAudience:ar().min(1),shareCid:ar().min(1),shareId:ar().min(1),delegationCid:ar().min(1),authorityMaterialHandle:ar().min(1),authorityMaterialDigest:ar().min(1),contentSource:wd,contentSourceDigest:ar().min(1),actions:fr(bd).min(1).refine(e=>new Set(e).size===e.length),resource:pr({kind:Ar(["exact","prefix"]),value:ar().min(1)}).strict(),expiresAt:ar().datetime({offset:!0}),requestBodyDigest:ar().min(1)}).strict(),kd=(pr({request:Ad,proof:pr({alg:Er("EdDSA"),kid:ar().min(1),signature:ar().min(1)}).strict()}).strict(),pr({type:Er("TinyCloudShareAddressedDelegation"),version:Er(2),nonce:ar().min(1),jti:ar().min(1),policyCid:ar().min(1),policyBytes:ar().min(1),policyDigest:ar().min(1),delegationCid:ar().min(1),delegationBytes:ar().min(1),delegationDigest:ar().min(1),authorityMaterialHandle:ar().min(1),authorityMaterialDigest:ar().min(1),actions:fr(bd).min(1).refine(e=>new Set(e).size===e.length),resource:pr({kind:Ar(["exact","prefix"]),value:ar().min(1)}).strict(),expiresAt:ar().datetime({offset:!0}),proof:pr({alg:Er("EdDSA"),kid:ar().min(1),signature:ar().min(1)}).strict()}).strict(),pr({path:ar().min(1),kind:Ar(["file","folder"])}).strict()),xd={type:Er("TinyCloudShareInvokeResponse"),version:Er(2),resource:ar().min(1)};gr("action",[pr({...xd,action:Er("tinycloud.kv/metadata"),metadata:vr(ar()),etag:ar().min(1).nullable()}).strict(),pr({...xd,action:Er("tinycloud.kv/get"),mediaType:ar().min(1),content:ar(),bodyDigest:ar().min(1),etag:ar().min(1).nullable()}).strict(),pr({...xd,action:Er("tinycloud.kv/list"),entries:fr(kd),nextCursor:ar().min(1).nullable()}).strict(),pr({...xd,action:Er("tinycloud.kv/put"),etag:ar().min(1),bodyDigest:ar().min(1),contentType:ar().min(1)}).strict()]),Error,Object.freeze({"xyz.tinycloud.policy/delegationMode":"terminal"});var _d=/^0x[a-fA-F0-9]{40}$/,Td=pr({domain:ar().nullable().optional(),avatarUrl:ar().nullable().optional()}),Sd=pr({delegationHeader:pr({Authorization:ar()}),delegationCid:ar(),spaceId:ar(),spaces:vr(ar(),ar()).optional(),verificationMethod:ar()});pr({address:ar().regex(_d,"Invalid Ethereum address"),chainId:cr().int().positive(),sessionKey:ar(),siwe:ar(),signature:ar(),tinycloudSession:Sd.optional(),expiresAt:ar().datetime({offset:!0}),createdAt:ar().datetime({offset:!0}),version:ar(),ens:Td.optional(),tinycloudHosts:fr(ar()).optional(),activatedHosts:fr(ar()).optional(),spaceHosting:Ar(["hosted","not-hosted"]).optional(),replicaStamp:pr({incarnation:ar().min(1),lifecycleEpoch:cr().int().nonnegative()}).strict().optional()}),pr({address:ar().regex(_d,"Invalid Ethereum address"),chainId:cr().int().positive(),sessionKey:ar(),spaceId:ar(),spaces:vr(ar(),ar()).optional(),delegationCid:ar(),delegationHeader:pr({Authorization:ar()}),verificationMethod:ar(),jwk:pr({}).passthrough(),siwe:ar(),signature:ar()}),pr({id:ar(),name:ar(),createKV:br(),createVault:br(),createSecrets:br().optional(),createDelegations:br(),createSharing:br(),getInfo:br()}),pr({hosts:fr(ar()),session:dr(),invoke:br(),fetch:br().optional(),resourceTransport:sr(e=>"function"==typeof e).optional(),capabilityRegistry:dr().optional(),createKVService:br().optional(),createVaultService:br().optional(),createSecretsService:br().optional(),userDid:ar().optional(),sharingService:dr().optional(),createDelegation:br().optional(),onSpaceRegistered:br().optional(),isStorageFull:br().optional()}),hh.extend({spaceId:ar()});var Id=pr({delegator:ar(),delegate:ar(),parents:fr(mr([ar(),fr(cr())])),expiry:ar().optional(),not_before:ar().optional(),issued_at:ar().optional(),capabilities:fr(pr({resource:ar(),ability:ar()}))}),Nd=(vr(ar(),Id),pr({id:ar(),name:ar().optional(),owner:ar(),createdAt:ar().optional()}));fr(Nd),pr({id:ar(),name:ar(),owner:ar(),createdAt:ar().optional()}),pr({id:ar(),name:ar().optional(),owner:ar(),type:Ar(["owned","delegated"]).optional(),permissions:fr(ar()).optional(),expiresAt:ar().optional()}),Error,new class{async confirmSpaceCreation(){return!0}},Error,Error,Error,TypeError;var Rd="(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])",Od=(new RegExp(`^${Rd}(\\.${Rd}){3}$`),"[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?");new RegExp(`^${Od}(\\.${Od})*$`),Error,Error,Error;Error;const Cd="tinycloud.encryption",Pd={line:(e,t,r)=>`${e} ${t}, for up to ${r}.`,unknownAction:e=>`use “${e}” on`,and:"and",resource:{key:e=>`the key ${e} (only this key)`,keyPrefix:e=>`any key under ${e}`,network:e=>`the whole encryption network ${e}, not just one key`,exactPath:e=>e,pathPrefix:e=>`everything under ${e}`,everything:"everything",inSpace:(e,t)=>`${e} in the ${t} space`},actions:{encryptionKey:{"key.create":"create",decrypt:"decrypt with","key.block":"block","key.unblock":"unblock"},encryptionNetwork:{"network.create":"create","network.revoke":"revoke",decrypt:"decrypt data encrypted to","key.create":"create keys on","key.block":"block keys on","key.unblock":"unblock keys on"},"tinycloud.kv":{get:"read",list:"list",metadata:"read the metadata of",put:"write",del:"delete",delete:"delete"},"tinycloud.sql":{read:"read",select:"read",write:"write to",schema:"change the schema of",admin:"administer",execute:"run statements on",export:"export","*":"fully use"},"tinycloud.duckdb":{read:"read",select:"read",describe:"describe",write:"write to",import:"import data into",export:"export",admin:"administer",execute:"run statements on","*":"fully use"},"tinycloud.capabilities":{read:"read the capability records of"},"tinycloud.hooks":{subscribe:"subscribe to hooks on",list:"list hooks on",register:"register hooks on",unregister:"remove hooks on"},"tinycloud.delegation":{list:"see the delegations of",status:"check the delegations of"}},units:{day:["day","days"],hour:["hour","hours"],minute:["minute","minutes"],second:["second","seconds"]},captionSource:e=>`Label from ${e}:`,details:{key:{scope:"This key only",summary:"This permission covers only the key shown below."},keyPrefix:{scope:"Keys under this prefix only",summary:"This permission covers only the keys under the prefix shown below."}}},Md=/[\u0000-\u001f\u007f-\u009f\u061c\u180e\u200b-\u200f\u2028-\u202e\u2060-\u2064\u2066-\u2069\ufeff\u{e0000}-\u{e007f}]/gu;function Dd(e){return e.replace(Md,e=>`\\u{${e.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}}`)}function Bd(e){return{...e,service:Dd(e.service),...void 0===e.space?{}:{space:Dd(e.space)},path:Dd(e.path),actions:e.actions.map(Dd)}}const Ld=/^urn:tinycloud:encryption:[^/]+\/secrets(?:\/|$)/;function Ud(e){if(Fd(e.service)!==Cd)return;const t=e.path.indexOf("/"),r=-1===t?"":e.path.slice(t+1);if(""===r){const r=-1===t?e.path:e.path.slice(0,t);return{kind:"network",name:r.slice(r.lastIndexOf(":")+1)}}return r.endsWith("/")?{kind:"keyPrefix",prefix:r}:{kind:"key",keyPath:r}}function Fd(e){return od[e]??e}function $d(e){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} ${Pd.and} ${e[e.length-1]}`}class Hd extends HTMLElement{constructor(e){super(),this.isVisible=!1,this.releaseScrollLock=null,this.opener=null,this.resolveResult=null,this.handleKeyDown=e=>{this.isVisible&&("Escape"===e.key?this.dismiss():"Tab"===e.key&&this.trapTab(e))},this.options=e,this.attachShadow({mode:"open"}),this.render(),this.completionPromise=new Promise(e=>{this.resolveResult=e})}getCompletionPromise(){return this.completionPromise}connectedCallback(){this.show(),this.setupEventListeners()}disconnectedCallback(){this.isVisible=!1,this.restoreFocus(),this.releaseLock(),document.removeEventListener("keydown",this.handleKeyDown)}render(){const e=this.options.additional.map(e=>this.renderEntry(Bd(e))).join(""),t=function(e,t){let r;try{r=function(e){return e.flatMap(ud)}(e).some(e=>e.service===Cd&&Ld.test(e.path))}catch{r=!1}return r?Math.min(t??36e5,6048e5):t??vh}(this.options.additional,this.options.expiryMs),r=this.options.additional.map(e=>`<li class="permission-line" data-role="permission-line">${Vd(function(e,t){const r=Bd(e),n=Ud(r),i=function(e,t){const r=Fd(e.service),n=e.actions.map(t=>t.startsWith(`${r}/`)?t.slice(r.length+1):t.startsWith(`${e.service}/`)?t.slice(e.service.length+1):t),i=Object.keys(t).filter(e=>n.includes(e)).map(e=>t[e]),s=n.filter(e=>!Object.prototype.hasOwnProperty.call(t,e)).map(Pd.unknownAction);return[...new Set([...i,...s])]}(r,void 0===n?Pd.actions[Fd(r.service)]??{}:Pd.actions["network"===n.kind?"encryptionNetwork":"encryptionKey"]),s=Pd.line($d(i),void 0===n?function(e){const{resource:t}=Pd,r=""===e.path||"/"===e.path?t.everything:e.path.endsWith("/")?t.pathPrefix(e.path):t.exactPath(e.path);return void 0===e.space||""===e.space?r:t.inSpace(r,e.space)}(r):function(e){switch(e.kind){case"network":return Pd.resource.network(e.name);case"keyPrefix":return Pd.resource.keyPrefix(e.prefix);case"key":return Pd.resource.key(e.keyPath)}}(n),function(e){let t=Math.ceil(e/1e3);const r=[];for(const[e,n]of[["day",86400],["hour",3600],["minute",60],["second",1]]){const i=Math.floor(t/n);t-=i*n,i>0&&r.push(`${i} ${Pd.units[e][1===i?0:1]}`)}return $d(r)}(t));return s.charAt(0).toUpperCase()+s.slice(1)}(e,t))}</li>`).join(""),n=Dd(this.options.appName),i=void 0===this.options.onBehalfOf?void 0:Dd(this.options.onBehalfOf),s=function(e){if("string"!=typeof e)return;const t=e.replace(/\s+/g," ").replace(Md,"").trim(),r=Array.from(t);return 0!==r.length?r.length>120?`${r.slice(0,119).join("")}…`:t:void 0}(this.options.caption),o=void 0===s?"":`<p class="app-caption" data-role="app-caption"><span class="app-caption-source">${Vd(Pd.captionSource(n))}</span> <span data-role="app-caption-text"></span></p>`,a=Vd(n),c=void 0===i?void 0:Vd(i),u=void 0===c?`${a} is requesting additional permissions`:`${c} in ${a} is asking for more access`,l=void 0===c?"This app is asking you to grant scoped permission. Review what it will be allowed to do before approving.":`Review what ${c} will be allowed to do before you approve.`,h=!1===this.options.allowSuppression?"":'<label class="suppression-option">\n <input type="checkbox" class="suppression-checkbox" data-role="suppress-prompt" />\n <span>Do not show me again for 30 days</span>\n </label>',d=this.options.appIcon?`<img class="app-icon" src="${f=this.options.appIcon,Vd(f)}" alt="" />`:'<div class="app-icon app-icon--placeholder">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/>\n </svg>\n </div>';var f;this.shadowRoot.innerHTML=`\n <style>${this.getModalStyles()}</style>\n <div class="modal-backdrop" data-state="hidden">\n <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="tc-permission-title" aria-describedby="tc-permission-description" tabindex="-1">\n <div class="modal-content">\n <div class="modal-header">\n ${d}\n <h2 class="modal-title" id="tc-permission-title">${u}</h2>\n <button class="modal-close" aria-label="Close">\n <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>\n </svg>\n </button>\n </div>\n\n <div class="modal-body">\n <p class="modal-description" id="tc-permission-description">\n ${l}\n </p>\n <ul class="permission-lines">${r}</ul>\n ${o}\n <ul class="permission-list">${e}</ul>\n ${h}\n </div>\n\n <div class="modal-actions">\n <button class="modal-button modal-button--secondary" data-action="decline">\n Decline\n </button>\n <button class="modal-button modal-button--primary" data-action="approve">\n Approve\n </button>\n </div>\n </div>\n </div>\n </div>\n `,void 0!==s&&(this.shadowRoot.querySelector('[data-role="app-caption-text"]').textContent=s)}renderEntry(e){const t=Ud(e),r=void 0===t||"network"===t.kind?void 0:Pd.details[t.kind],n=r?.scope??jd(e),i=""===e.path?"/":e.path,s=e.actions.map(t=>function(e,t){const r=function(e,t){return t.includes("/")?t:t.startsWith(`${e}.`)?`${e}/${t.slice(e.length+1)}`:`${e}/${t}`}(e.service,t),n=function(e,t){return t.startsWith(`${e}/`)||t.startsWith(`${e}.`)?t.slice(e.length+1):t}(e.service,t),i=function(e,t){if("tinycloud.kv"!==e.service||"secrets"!==e.space)return;const r=function(e){const t="vault/secrets/";if("vault/secrets"===e)return"all secrets";if(!e.startsWith(t))return;const r=e.slice(14);if(""===r)return"all secrets";const n="scoped/";if(r.startsWith(n)){const[e,...t]=r.slice(7).split("/"),n=t.join("/");if(""!==e&&""!==n)return`the scoped secret ${n} in ${e}`}return`the secret ${r}`}(e.path);if(void 0!==r)switch(t){case"tinycloud.kv/get":return{title:"Read an encrypted secret",description:`Allows this app to read the encrypted secret record for ${r}. Decrypting it still requires encryption-network decrypt permission.`};case"tinycloud.kv/put":return{title:"Write a secret",description:`Allows this app to create or update the encrypted secret record for ${r}.`};case"tinycloud.kv/del":return{title:"Delete a secret",description:`Allows this app to remove the encrypted secret record for ${r}.`};case"tinycloud.kv/list":return{title:"List secrets",description:`Allows this app to list encrypted secret records under ${r}.`};case"tinycloud.kv/metadata":return{title:"Read secret metadata",description:`Allows this app to inspect metadata for encrypted secret records under ${r}.`};default:return}}(e,r)??qd[r]??function(e,t){return{title:"tinycloud.delegation"===e?"Manage your delegations"+(""===t?"":` (${t})`):`Use ${zd(e).replace(/ permission$/,"")}`,description:`Allows this app to perform ${t} on the resource shown below.`}}(e.service,n);return{canonicalAction:r,displayAction:n,...i}}(e,t)),o=void 0!==r?"":s.map(e=>`\n <li class="permission-summary-item">\n <div class="permission-summary-row">\n <span class="permission-summary-label">Permission</span>\n <strong class="permission-summary-title">${Vd(e.title)}</strong>\n </div>\n <p class="permission-summary-description">${Vd(e.description)}</p>\n </li>\n `).join(""),a=[["Service",e.service],["Scope",n],["Resource",i],["Actions",s.map(e=>e.canonicalAction).join(", ")]].map(([e,t])=>`\n <div class="dictionary-row">\n <dt>${Vd(e)}</dt>\n <dd>${Vd(t)}</dd>\n </div>\n `).join(""),c=function(e){if("string"!=typeof e)return;const t=e.replace(/\s+/g," ").trim(),r=Array.from(t);return 0!==r.length?r.length<=140?{line:Dd(t)}:{line:Dd(`${r.slice(0,139).join("").trimEnd()}…`),full:Dd(t)}:void 0}(e.description);return`\n <li class="permission-entry">\n ${void 0===c?"":`<p class="entry-description" data-role="entry-description">${Vd(c.line)}</p>`}${""===o?"":`<ul class="permission-summary-list">${o}</ul>`}\n <details class="technical-details">\n <summary>Show technical details</summary>\n ${void 0===c?.full?"":`<p class="entry-summary" data-role="entry-description-full">${Vd(c.full)}</p>`}<p class="entry-summary">${Vd(r?.summary??function(e){if("tinycloud.encryption"===e.service)return"This permission applies to an encryption network, not a TinyCloud data space.";return`This permission applies to the ${jd(e)} TinyCloud space and the resource path shown below.`}(e))}</p>\n <dl class="permission-dictionary">${a}</dl>\n </details>\n </li>\n `}getModalStyles(){return'\n :host {\n --modal-bg: hsl(0 0% 3.9%);\n --modal-border: hsl(0 0% 14.9%);\n --modal-foreground: hsl(0 0% 98%);\n --modal-muted: hsl(0 0% 63.9%);\n --modal-accent: hsl(217 91% 60%);\n --modal-accent-hover: hsl(217 91% 65%);\n --modal-secondary: hsl(0 0% 10%);\n --modal-secondary-hover: hsl(0 0% 15%);\n --modal-overlay: rgba(0, 0, 0, 0.5);\n }\n .modal-backdrop {\n position: fixed; top: 0; left: 0; right: 0; bottom: 0;\n background: var(--modal-overlay);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n z-index: 2000000;\n display: flex; align-items: flex-start; justify-content: center; overflow-y: auto;\n padding: 20px; opacity: 0;\n transition: opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n pointer-events: none;\n }\n .modal-backdrop[data-state="visible"] { opacity: 1; pointer-events: auto; }\n .modal-container {\n margin: auto;\n transform: scale(0.95) translateY(10px);\n transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n }\n .modal-container:focus { outline: none; }\n .modal-backdrop[data-state="visible"] .modal-container { transform: scale(1) translateY(0); }\n .modal-content {\n background: var(--modal-bg);\n border: 1px solid var(--modal-border);\n border-radius: 16px;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(255, 255, 255, 0.05);\n box-sizing: border-box; max-width: 520px; width: 100%;\n overflow-wrap: anywhere;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;\n color: var(--modal-foreground);\n }\n .modal-header {\n padding: 24px 24px 0 24px;\n display: flex; align-items: flex-start; gap: 16px; position: relative;\n }\n .app-icon {\n flex-shrink: 0; width: 48px; height: 48px;\n border-radius: 12px; object-fit: cover;\n background: var(--modal-secondary);\n }\n .app-icon--placeholder {\n display: flex; align-items: center; justify-content: center;\n background: var(--modal-accent); color: white;\n }\n .modal-title {\n flex: 1; min-width: 0; font-size: 18px; font-weight: 600; line-height: 1.3;\n margin: 0; margin-top: 4px;\n }\n .modal-close {\n position: absolute; top: 0; right: 0;\n background: transparent; border: none;\n color: var(--modal-muted); cursor: pointer;\n padding: 8px; border-radius: 6px; opacity: 0.7;\n transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);\n display: flex; align-items: center; justify-content: center;\n }\n .modal-close:hover { opacity: 1; background: var(--modal-secondary); color: var(--modal-foreground); }\n .modal-body { padding: 20px 24px; }\n .modal-description {\n font-size: 14px; line-height: 1.5; margin: 0 0 16px 0; color: var(--modal-muted);\n }\n .permission-lines {\n list-style: none; padding: 0; margin: 0 0 12px 0;\n display: flex; flex-direction: column; gap: 8px;\n font-size: 15px; font-weight: 600; line-height: 1.4; color: var(--modal-foreground);\n }\n .app-caption {\n font-size: 13px; line-height: 1.45; color: var(--modal-muted);\n margin: 0 0 12px 0;\n }\n .app-caption-source { font-weight: 600; }\n .permission-list {\n list-style: none; padding: 0; margin: 0;\n display: flex; flex-direction: column; gap: 10px;\n max-height: 320px; overflow-y: auto;\n }\n .permission-entry {\n background: var(--modal-secondary);\n border: 1px solid var(--modal-border);\n border-radius: 10px; padding: 14px;\n }\n .suppression-option {\n display: flex; align-items: center; gap: 10px;\n margin-top: 16px; color: var(--modal-muted);\n font-size: 13px; line-height: 1.4; cursor: pointer;\n }\n .suppression-checkbox {\n width: 16px; height: 16px; flex: 0 0 auto;\n margin: 0; accent-color: var(--modal-accent);\n }\n .suppression-option:hover { color: var(--modal-foreground); }\n .entry-summary {\n font-size: 13px; line-height: 1.45; color: var(--modal-muted);\n margin: 10px 0;\n }\n .entry-description {\n font-size: 13px; line-height: 1.45; color: var(--modal-muted);\n margin: 0 0 12px 0;\n }\n .permission-summary-list {\n list-style: none; padding: 0; margin: 0;\n display: flex; flex-direction: column; gap: 10px;\n }\n .permission-summary-item {\n display: flex; flex-direction: column; gap: 6px;\n }\n .permission-summary-row {\n display: grid; grid-template-columns: 88px minmax(0, 1fr);\n gap: 10px; align-items: baseline;\n }\n .permission-summary-label {\n font-size: 12px; color: var(--modal-muted);\n }\n .permission-summary-title {\n font-size: 15px; font-weight: 600; color: var(--modal-foreground);\n line-height: 1.35;\n }\n .permission-summary-description {\n font-size: 13px; line-height: 1.45; color: var(--modal-muted);\n margin: 0;\n }\n .technical-details {\n margin-top: 12px;\n border-top: 1px solid var(--modal-border);\n padding-top: 10px;\n }\n .technical-details:first-child { margin-top: 0; border-top: 0; padding-top: 0; }\n .technical-details summary {\n cursor: pointer; color: var(--modal-muted); font-size: 12px;\n user-select: none;\n }\n .technical-details summary:hover { color: var(--modal-foreground); }\n .technical-details[open] summary { margin-bottom: 8px; }\n .permission-dictionary {\n margin: 0; padding: 0;\n border: 1px solid var(--modal-border);\n border-radius: 8px; overflow: hidden;\n }\n .dictionary-row {\n display: grid; grid-template-columns: 86px 1fr;\n border-top: 1px solid var(--modal-border);\n }\n .dictionary-row:first-child { border-top: 0; }\n .dictionary-row dt,\n .dictionary-row dd {\n margin: 0; padding: 8px 10px; font-size: 12px; line-height: 1.4;\n }\n .dictionary-row dt {\n color: var(--modal-muted); background: var(--modal-bg);\n }\n .dictionary-row dd {\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, "Cascadia Mono", monospace;\n color: var(--modal-foreground); word-break: break-all;\n }\n .modal-actions {\n padding: 0 24px 24px 24px;\n display: flex; gap: 12px; justify-content: flex-end;\n }\n .modal-button {\n padding: 12px 20px; border-radius: 8px;\n font-size: 14px; font-weight: 500; cursor: pointer;\n transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);\n border: 1px solid transparent;\n display: flex; align-items: center; gap: 8px;\n min-width: 100px; justify-content: center;\n }\n .modal-button--secondary {\n background: var(--modal-secondary);\n border-color: var(--modal-border);\n color: var(--modal-foreground);\n }\n .modal-button--secondary:hover {\n background: var(--modal-secondary-hover);\n border-color: hsl(0 0% 25%);\n transform: translateY(-1px);\n }\n .modal-button--primary { background: var(--modal-accent); color: white; }\n .modal-button--primary:hover { background: var(--modal-accent-hover); transform: translateY(-1px); }\n .modal-button--primary:active { transform: translateY(0); }\n @media (max-width: 640px) {\n .modal-content { max-width: 100%; margin: 0 16px; border-radius: 12px; }\n .modal-header { padding: 20px 20px 0 20px; }\n .modal-body { padding: 16px 20px; }\n .modal-actions { padding: 0 20px 20px 20px; flex-direction: column-reverse; }\n .modal-button { width: 100%; }\n .permission-summary-row { grid-template-columns: 1fr; gap: 3px; }\n .dictionary-row { grid-template-columns: 1fr; }\n .dictionary-row dd { padding-top: 0; }\n }\n '}setupEventListeners(){const e=this.shadowRoot.querySelector(".modal-backdrop"),t=this.shadowRoot.querySelector(".modal-close"),r=this.shadowRoot.querySelector('[data-action="decline"]'),n=this.shadowRoot.querySelector('[data-action="approve"]');e?.addEventListener("click",t=>{t.target===e&&this.dismiss()}),t?.addEventListener("click",()=>this.dismiss()),r?.addEventListener("click",()=>this.dismiss()),n?.addEventListener("click",()=>{n&&u(n)&&this.handleApprove()}),document.addEventListener("keydown",this.handleKeyDown)}trapTab(e){if(!e.composedPath().includes(this))return;const t=this.shadowRoot,r=o(t),n=r.indexOf(t.activeElement);e.preventDefault();const i=a(r.length,n,e.shiftKey);i>=0&&r[i].focus()}handleApprove(){const e=this.shadowRoot.querySelector('[data-role="suppress-prompt"]');this.resolveResult?.({approved:!0,suppressPromptFor30Days:!0===e?.checked}),this.hide()}show(){this.isVisible||(this.opener=n()),this.isVisible=!0,this.releaseScrollLock||(this.releaseScrollLock=r()),this.shadowRoot.querySelector(".modal-container").focus(),requestAnimationFrame(()=>{const e=this.shadowRoot.querySelector(".modal-backdrop");e?.setAttribute("data-state","visible")})}hide(){const e=this.shadowRoot.querySelector(".modal-backdrop");e?.setAttribute("data-state","hidden"),this.restoreFocus(),setTimeout(()=>{this.remove(),this.releaseLock(),document.removeEventListener("keydown",this.handleKeyDown)},200),this.isVisible=!1}restoreFocus(){const e=this.opener;this.opener=null,c(e,this.shadowRoot)}releaseLock(){this.releaseScrollLock?.(),this.releaseScrollLock=null}dismiss(){try{this.resolveResult?.({approved:!1}),this.options.onDismiss?.()}finally{this.hide()}}get isOpen(){return this.isVisible}}const Kd={"tinycloud.encryption":"Encryption network permission","tinycloud.kv":"Key-value storage permission","tinycloud.sql":"SQL storage permission","tinycloud.duckdb":"DuckDB storage permission","tinycloud.capabilities":"Capability registry permission","tinycloud.hooks":"Hook permission"},qd={[G.DECRYPT]:{title:"Decrypt data keys for this network",description:"Allows this app to ask a TinyCloud node to unwrap encrypted data keys for data encrypted to this network. The app still needs separate data-read permission to fetch encrypted records."},[G.NETWORK_CREATE]:{title:"Create an encryption network",description:"Allows this app to create or initialize an encryption network that data can be encrypted to. The network key is managed by TinyCloud nodes and used later for delegated decrypt requests."},[G.NETWORK_REVOKE]:{title:"Revoke an encryption network",description:"Allows this app to revoke or disable an encryption network so future decrypt requests for that network are denied."},[K.GET]:{title:"Read key-value data",description:"Allows this app to read values at the selected key or key prefix in the requested space."},[K.PUT]:{title:"Write key-value data",description:"Allows this app to create or replace values at the selected key or key prefix in the requested space."},[K.DEL]:{title:"Delete key-value data",description:"Allows this app to remove values at the selected key or key prefix in the requested space."},[K.LIST]:{title:"List key-value entries",description:"Allows this app to list keys under the selected key-value prefix in the requested space."},[K.METADATA]:{title:"Read key-value metadata",description:"Allows this app to inspect metadata for keys without necessarily reading the stored value."},[q.READ]:{title:"Read SQL data",description:"Allows this app to read rows and query results from the selected SQL database in the requested space."},[q.WRITE]:{title:"Write SQL data",description:"Allows this app to insert, update, or delete rows in the selected SQL database."},[q.SCHEMA]:{title:"Change SQL schema",description:"Allows this app to create, alter, or drop SQL tables, indexes, and schema objects."},[q.ADMIN]:{title:"Administer SQL storage",description:"Allows this app to perform administrative SQL operations for the selected database."},[q.SELECT]:{title:"Select SQL rows",description:"Allows this app to run SELECT queries against the selected SQL database."},[q.EXECUTE]:{title:"Execute SQL statements",description:"Allows this app to execute SQL statements against the selected database."},[q.EXPORT]:{title:"Export SQL data",description:"Allows this app to export data from the selected SQL database."},[q.ALL]:{title:"Full SQL access",description:"Allows this app to read, write, administer, and export the selected SQL database."},[j.READ]:{title:"Read DuckDB data",description:"Allows this app to read data and query results from the selected DuckDB database."},[j.WRITE]:{title:"Write DuckDB data",description:"Allows this app to write data to the selected DuckDB database."},[j.ADMIN]:{title:"Administer DuckDB storage",description:"Allows this app to perform administrative operations for the selected DuckDB database."},[j.DESCRIBE]:{title:"Describe DuckDB data",description:"Allows this app to inspect tables, columns, and metadata in the selected DuckDB database."},[j.EXPORT]:{title:"Export DuckDB data",description:"Allows this app to export data from the selected DuckDB database."},[j.IMPORT]:{title:"Import DuckDB data",description:"Allows this app to import data into the selected DuckDB database."},[j.EXECUTE]:{title:"Execute DuckDB statements",description:"Allows this app to execute statements against the selected DuckDB database."},[j.ALL]:{title:"Full DuckDB access",description:"Allows this app to read, write, administer, import, export, and execute statements on the selected DuckDB database."},[z.READ]:{title:"Read delegated capabilities",description:"Allows this app to read capability and delegation records for the selected scope."},"tinycloud.delegation/list":{title:"See which apps and links can reach your data, and the names of what each can reach",description:"See who has access to your data, what it reaches (by name) and when it ends. Keys and contents aren't shown."},[V.SUBSCRIBE]:{title:"Subscribe to hooks",description:"Allows this app to receive hook events for the selected hook scope."},[V.REGISTER]:{title:"Register hooks",description:"Allows this app to register hook handlers for the selected hook scope."},[V.LIST]:{title:"List hooks",description:"Allows this app to list registered hooks for the selected hook scope."},[V.UNREGISTER]:{title:"Unregister hooks",description:"Allows this app to remove registered hook handlers for the selected hook scope."}};function jd(e){return void 0!==e.space&&""!==e.space?e.space:"tinycloud.encryption"===e.service?"network-scoped":"unscoped"}function zd(e){return Kd[e]??`${e} permission`}function Vd(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var Gd;"undefined"==typeof customElements||customElements.get("tinycloud-permission-request-modal")||customElements.define("tinycloud-permission-request-modal",Hd);const Wd=Symbol.for("tinycloud.web-sdk.prompt-state"),Jd=(Gd=globalThis)[Wd]??(Gd[Wd]={open:new Set,layer:void 0});const Zd=Symbol.for("tinycloud.web-sdk.modals"),Yd={uiEnabled:!0};class Qd{constructor(){this.activeModal=null,this.releaseActivePrompt=null}static getInstance(){return Qd.instance||(Qd.instance=new Qd),Qd.instance}showSpaceCreationModal(e,t=Yd){this.displaceActiveModal();const r=new l({...e,onDismiss:()=>{this.clearActive(r),e.onDismiss?.()}});return this.present(r,t,()=>r.dismiss())?r.getCompletionPromise().finally(()=>{this.clearActive(r)}):(e.onDismiss?.(),Promise.resolve({success:!1,dismissed:!0}))}showPermissionRequestModal(e,t=Yd){this.displaceActiveModal();const r=new Hd({...e,onDismiss:()=>{this.clearActive(r),e.onDismiss?.()}});return this.present(r,t,()=>r.dismiss())?r.getCompletionPromise().finally(()=>{this.clearActive(r)}):(e.onDismiss?.(),Promise.resolve({approved:!1}))}present(e,t,r){const n=function(e,t,r){const n=function(e){return function(){try{return"undefined"!=typeof window&&"undefined"!=typeof document&&window.top===window&&"null"!==window.location.origin}catch{return!1}}()?e.uiEnabled&&void 0!==Jd.layer?void 0:"ui-disabled":"ui-unavailable-frame"}(e);if(void 0!==n)return console.warn(`[tinycloud] ${n}`),{refusal:n};Jd.layer?.appendChild(t);const i={scope:e,dismiss:r,element:t};return Jd.open.add(i),{release:()=>{Jd.open.delete(i),Jd.layer?.dispatchEvent(new Event("tinycloud-prompt-settled"))}}}(t,e,r);return!("refusal"in n)&&(this.activeModal=e,this.releaseActivePrompt=n.release,!0)}clearActive(e){this.activeModal===e&&(this.releaseActivePrompt?.(),this.releaseActivePrompt=null,this.activeModal=null)}displaceActiveModal(){try{this.closeActiveModal()}catch(e){queueMicrotask(()=>{throw e})}}closeActiveModal(){const e=this.activeModal;if(e)try{e.isOpen&&e.dismiss()}finally{e.remove(),this.clearActive(e)}}hasActiveModal(){return null!==this.activeModal}}const Xd=(e,t)=>Qd.getInstance().showSpaceCreationModal(e,t),ef=(e,t)=>Qd.getInstance().showPermissionRequestModal(e,t);globalThis[Zd]={showPermissionRequestModal:ef,showSpaceCreationModal:Xd,closeActiveModal:()=>Qd.getInstance().closeActiveModal()}})(),module.exports=s})();
|
|
1
|
+
(()=>{"use strict";var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{ModalManager:()=>we,showPermissionRequestModal:()=>Se,showSpaceCreationModal:()=>xe});let n=0,i="";function o(){let e=!0;return 0===n&&(i=document.body.style.overflow),n+=1,document.body.style.overflow="hidden",()=>{e&&(e=!1,n-=1,0===n&&(document.body.style.overflow=i))}}function s(){let e=document.activeElement;for(;e instanceof HTMLElement&&e.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return e instanceof HTMLElement?e:null}function a(e){return Array.from(e.querySelectorAll("button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href]"))}function r(e,t,n){return 0===e?-1:n?t<=0?e-1:t-1:t<0||t>=e-1?0:t+1}function c(e,t){if(!e?.isConnected)return;const n=s();(null===n||n===document.body||t.contains(n))&&e.focus()}function l(e){const t=e.getBoundingClientRect();if(0===t.width||0===t.height)return!1;const n=e.getRootNode();if("function"!=typeof n.elementFromPoint)return!1;const i=n.elementFromPoint.call(n,t.left+t.width/2,t.top+t.height/2);return null!==i&&e.contains(i)}class d extends HTMLElement{constructor(e){super(),this.isVisible=!1,this.releaseScrollLock=null,this.opener=null,this.isCreating=!1,this.resolveResult=null,this.handleKeyDown=e=>{this.isVisible&&("Escape"!==e.key||this.isCreating?"Tab"===e.key&&this.trapTab(e):this.dismiss())},this.options=e,this.attachShadow({mode:"open"}),this.render(),this.completionPromise=new Promise(e=>{this.resolveResult=e})}getCompletionPromise(){return this.completionPromise}connectedCallback(){this.show(),this.setupEventListeners()}disconnectedCallback(){this.isVisible=!1,this.restoreFocus(),this.releaseLock(),document.removeEventListener("keydown",this.handleKeyDown)}render(){this.shadowRoot.innerHTML=`\n <style>${this.getModalStyles()}</style>\n <div class="modal-backdrop" data-state="hidden">\n <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="tc-space-title" aria-describedby="tc-space-description" tabindex="-1">\n <div class="modal-content">\n <div class="modal-header">\n <div class="modal-icon">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="1.5"/>\n <path d="M8 12l2 2 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </div>\n <h2 class="modal-title" id="tc-space-title">Create Your TinyCloud Space</h2>\n <button class="modal-close" aria-label="Close">\n <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>\n </svg>\n </button>\n </div>\n\n <div class="modal-body">\n <p class="modal-description" id="tc-space-description">\n A TinyCloud Space is your personal data container where only you control access.\n Your signature is required for any operations on the data stored there.\n </p>\n <p class="modal-subdescription">\n Sign a message to create your space and start storing data.\n </p>\n </div>\n\n <div class="modal-actions">\n <button class="modal-button modal-button--secondary" data-action="learn-more">\n Learn More\n </button>\n <button class="modal-button modal-button--primary" data-action="create">\n <span class="button-text">Create TinyCloud Space</span>\n <span class="button-spinner" data-state="hidden">\n <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-dasharray="9.42 9.42" opacity="0.25"/>\n <circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-dasharray="9.42 9.42" stroke-dashoffset="9.42">\n <animateTransform attributeName="transform" type="rotate" values="0 8 8;360 8 8" dur="1s" repeatCount="indefinite"/>\n </circle>\n </svg>\n </span>\n </button>\n </div>\n </div>\n </div>\n </div>\n `}getModalStyles(){return'\n :host {\n --modal-bg: hsl(0 0% 3.9%);\n --modal-border: hsl(0 0% 14.9%);\n --modal-foreground: hsl(0 0% 98%);\n --modal-muted: hsl(0 0% 63.9%);\n --modal-accent: hsl(217 91% 60%);\n --modal-accent-hover: hsl(217 91% 65%);\n --modal-secondary: hsl(0 0% 10%);\n --modal-secondary-hover: hsl(0 0% 15%);\n --modal-overlay: rgba(0, 0, 0, 0.5);\n }\n\n .modal-backdrop {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--modal-overlay);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n z-index: 2000000;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n overflow-y: auto;\n padding: 20px;\n opacity: 0;\n transition: opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n pointer-events: none;\n }\n\n .modal-backdrop[data-state="visible"] {\n opacity: 1;\n pointer-events: auto;\n }\n\n .modal-container {\n margin: auto;\n transform: scale(0.95) translateY(10px);\n transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n }\n\n .modal-backdrop[data-state="visible"] .modal-container {\n transform: scale(1) translateY(0);\n }\n\n .modal-content {\n background: var(--modal-bg);\n border: 1px solid var(--modal-border);\n border-radius: 16px;\n box-shadow:\n 0 25px 50px -12px rgba(0, 0, 0, 0.25),\n 0 0 0 1px rgba(255, 255, 255, 0.05);\n box-sizing: border-box;\n max-width: 480px;\n width: 100%;\n overflow-wrap: anywhere;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;\n color: var(--modal-foreground);\n }\n\n .modal-header {\n padding: 24px 24px 0 24px;\n display: flex;\n align-items: flex-start;\n gap: 16px;\n position: relative;\n }\n\n .modal-icon {\n flex-shrink: 0;\n width: 48px;\n height: 48px;\n background: var(--modal-accent);\n border-radius: 12px;\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n margin-top: 4px;\n }\n\n .modal-title {\n flex: 1;\n min-width: 0;\n font-size: 20px;\n font-weight: 600;\n line-height: 1.3;\n margin: 0;\n margin-top: 8px;\n }\n\n .modal-close {\n position: absolute;\n top: 0;\n right: 0;\n background: transparent;\n border: none;\n color: var(--modal-muted);\n cursor: pointer;\n padding: 8px;\n border-radius: 6px;\n opacity: 0.7;\n transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .modal-close:hover {\n opacity: 1;\n background: var(--modal-secondary);\n color: var(--modal-foreground);\n }\n\n .modal-body {\n padding: 24px;\n padding-top: 20px;\n }\n\n .modal-description {\n font-size: 16px;\n line-height: 1.5;\n margin: 0 0 12px 0;\n color: var(--modal-foreground);\n }\n\n .modal-subdescription {\n font-size: 14px;\n line-height: 1.4;\n margin: 0;\n color: var(--modal-muted);\n }\n\n .modal-actions {\n padding: 0 24px 24px 24px;\n display: flex;\n gap: 12px;\n justify-content: flex-end;\n }\n\n .modal-button {\n padding: 12px 20px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);\n border: 1px solid transparent;\n display: flex;\n align-items: center;\n gap: 8px;\n min-width: 100px;\n justify-content: center;\n position: relative;\n }\n\n .modal-button:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n\n .modal-button--secondary {\n background: var(--modal-secondary);\n border-color: var(--modal-border);\n color: var(--modal-foreground);\n }\n\n .modal-button--secondary:hover:not(:disabled) {\n background: var(--modal-secondary-hover);\n border-color: hsl(0 0% 25%);\n transform: translateY(-1px);\n }\n\n .modal-button--primary {\n background: var(--modal-accent);\n color: white;\n }\n\n .modal-button--primary:hover:not(:disabled) {\n background: var(--modal-accent-hover);\n transform: translateY(-1px);\n }\n\n .modal-button--primary:active:not(:disabled) {\n transform: translateY(0);\n }\n\n .button-spinner {\n display: none;\n }\n\n .button-spinner[data-state="visible"] {\n display: flex;\n }\n\n .modal-button[data-state="loading"] .button-text {\n opacity: 0;\n }\n\n .modal-button[data-state="loading"] .button-spinner {\n display: flex;\n position: absolute;\n }\n\n @media (max-width: 640px) {\n .modal-content {\n max-width: 100%;\n margin: 0 16px;\n border-radius: 12px;\n }\n\n .modal-header {\n padding: 20px 20px 0 20px;\n }\n\n .modal-body {\n padding: 20px;\n padding-top: 16px;\n }\n\n .modal-actions {\n padding: 0 20px 20px 20px;\n flex-direction: column-reverse;\n }\n\n .modal-button {\n width: 100%;\n }\n }\n .modal-container:focus { outline: none; }\n '}setupEventListeners(){const e=this.shadowRoot.querySelector(".modal-backdrop"),t=this.shadowRoot.querySelector(".modal-close"),n=this.shadowRoot.querySelector('[data-action="learn-more"]'),i=this.shadowRoot.querySelector('[data-action="create"]');e?.addEventListener("click",t=>{t.target!==e||this.isCreating||this.dismiss()}),t?.addEventListener("click",()=>{this.isCreating||this.dismiss()}),n?.addEventListener("click",()=>{window.open("https://tinycloud.xyz","_blank","noopener,noreferrer")}),i?.addEventListener("click",()=>{!this.isCreating&&i&&l(i)&&this.handleCreateSpace()}),document.addEventListener("keydown",this.handleKeyDown)}trapTab(e){if(!e.composedPath().includes(this))return;const t=this.shadowRoot,n=a(t),i=n.indexOf(t.activeElement);e.preventDefault();const o=r(n.length,i,e.shiftKey);o>=0&&n[o].focus()}async handleCreateSpace(){this.isCreating=!0;const e=this.shadowRoot.querySelector('[data-action="create"]');e.setAttribute("data-state","loading"),e.setAttribute("disabled","true");try{await this.options.onCreateSpace(),this.resolveResult?.({success:!0,dismissed:!1}),this.hide()}catch(e){console.error("[TinyCloud] Space creation failed:",e)}finally{this.isCreating=!1,e.removeAttribute("data-state"),e.removeAttribute("disabled")}}show(){this.isVisible||(this.opener=s()),this.isVisible=!0,this.releaseScrollLock||(this.releaseScrollLock=o()),this.shadowRoot.querySelector(".modal-container").focus(),requestAnimationFrame(()=>{const e=this.shadowRoot.querySelector(".modal-backdrop");e?.setAttribute("data-state","visible")})}hide(){const e=this.shadowRoot.querySelector(".modal-backdrop");e?.setAttribute("data-state","hidden"),this.restoreFocus(),setTimeout(()=>{this.remove(),this.releaseLock(),document.removeEventListener("keydown",this.handleKeyDown)},200),this.isVisible=!1}restoreFocus(){const e=this.opener;this.opener=null,c(e,this.shadowRoot)}releaseLock(){this.releaseScrollLock?.(),this.releaseScrollLock=null}dismiss(){try{this.resolveResult?.({success:!1,dismissed:!0}),this.options.onDismiss?.()}finally{this.hide()}}get isOpen(){return this.isVisible}}customElements.get("tinycloud-space-modal")||customElements.define("tinycloud-space-modal",d);var p=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function u(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function h(e){return e.slice(10,e.indexOf("/"))}function m(e){return e.slice(e.indexOf("/")+1)}function y(e){const t={};for(const n of p)h(n.urn)===e&&(t[u(m(n.urn))]=n.urn);return t}var v=y("kv"),f={...y("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},b={...y("duckdb"),DESCRIBE:"tinycloud.duckdb/describe",EXECUTE:"tinycloud.duckdb/execute"},g=y("capabilities"),k=y("hooks"),w=y("encryption"),x=y("space");["tinychat-4jq","share-2fz","tinycloud-secrets","openkey-tinycloud-demo"].map(e=>new RegExp(`^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)?${e}\\.pages\\.dev$`));var S="applications",A="account",E="applications/",R="secrets",$="default",L="public",T="agents",D="tinycloud.encryption",q=w.NETWORK_CREATE,C=[$,S,A,R,L,T],P={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:$,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:$,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:$,path:"",actions:["read","write"]}]},M={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:S,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:S,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:S,path:"",actions:["read","write"]}]},z={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:A,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:A,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:A,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:A,path:"account",actions:["read","write","schema"]}]},j={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:R,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:R,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:R,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:R,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:R,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:R,path:"",actions:["read"],skipPrefix:!0}]},O={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:L,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:L,path:"",actions:["get","list","metadata"]}]},B={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:T,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:T,path:"",actions:["get","put","del","list","metadata"]}]},I={[$]:P,[S]:M,[A]:z,[R]:j,[L]:O,[T]:B};function W(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function K(e,t,n){return!0===n||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function U(e,t,n){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const n=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,i="read"===n||"get"===n?v.GET:"write"===n||"put"===n?v.PUT:"delete"===n||"del"===n?v.DEL:"list"===n?v.LIST:"metadata"===n?v.METADATA:void 0;if(void 0===i)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const o=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${o}`,actions:[i],skipPrefix:!0}})}(e).flatMap(e=>U(e,t,n));const i=!0===e.skipPrefix||e.service===D;return[{service:e.service,space:e.service===D?"encryption":e.space??n,path:K(t,e.path,i),actions:e.actions.map(t=>function(e,t){return t.includes("/")?t:`${e}/${t}`}(e.service,t)),...void 0!==e.description?{description:e.description}:{}}]}function Q(e){const t=new Set(e.filter(e=>e.service!==D).map(e=>e.space));return function(e){const t=new Map;for(const n of e){const e=`${n.service}\0${n.space}\0${n.path}`,i=t.get(e);if(i)for(const e of n.actions)i.actions.includes(e)||i.actions.push(e);else t.set(e,{...n,actions:[...n.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[g.READ]}))])}function _(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const n=t.includeAccountRegistryPermissions??!0,i=e.map(W),o=i.flatMap(e=>{const t=e.prefix??e.app_id,n=e.space??S;return(e.permissions??[]).flatMap(e=>U(e,t,n))});n&&o.push(...F.map(e=>({...e,actions:[...e.actions]})));const s=new Map;for(const e of i){const t=s.get(e.app_id)??[];t.push(W(e)),s.set(e.app_id,t)}return{manifests:i,resources:Q(o),delegationTargets:[],registryRecords:n?[...s.entries()].map(([e,t])=>({key:`${E}${e}`,app_id:e,manifests:t})):[],expiryMs:6048e5,includePublicSpace:i.some(e=>e.includePublicSpace??!0)}}([I[e]],{includeAccountRegistryPermissions:!1})}C.map(e=>({name:e,manifest:I[e],persistedAsApplication:e===R}));var F=Object.freeze([{service:"tinycloud.kv",space:A,path:E,actions:[v.GET,v.PUT,v.LIST]},{service:"tinycloud.kv",space:A,path:"spaces/",actions:[v.GET,v.PUT,v.LIST]},{service:"tinycloud.kv",space:A,path:"system/bootstrap/complete",actions:[v.GET,v.PUT]},{service:"tinycloud.delegation",space:A,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:A,path:"account",actions:[f.READ,f.WRITE,f.SCHEMA]},{service:"tinycloud.capabilities",space:A,path:"",actions:[g.READ]}]),V=_($),N={...V,resources:[...V.resources,...F.map(e=>({...e,actions:[...e.actions]}))]},Y=Object.freeze(Object.fromEntries(C.map(e=>[e,e===$?N:_(e)]))),H=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[q]}]);Object.freeze(C.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:Y[e].resources,...e===A?{rawAbilities:H}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[x.HOST]}]));const G=require("./index.cjs"),X="tinycloud.encryption",J={line:(e,t,n)=>`${e} ${t}, for up to ${n}.`,unknownAction:e=>`use “${e}” on`,and:"and",resource:{key:e=>`the key ${e} (only this key)`,keyPrefix:e=>`any key under ${e}`,network:e=>`the whole encryption network ${e}, not just one key`,exactPath:e=>e,pathPrefix:e=>`everything under ${e}`,everything:"everything",inSpace:(e,t)=>`${e} in the ${t} space`},actions:{encryptionKey:{"key.create":"create",decrypt:"decrypt with","key.block":"block","key.unblock":"unblock"},encryptionNetwork:{"network.create":"create","network.revoke":"revoke",decrypt:"decrypt data encrypted to","key.create":"create keys on","key.block":"block keys on","key.unblock":"unblock keys on"},"tinycloud.kv":{get:"read",list:"list",metadata:"read the metadata of",put:"write",del:"delete",delete:"delete"},"tinycloud.sql":{read:"read",select:"read",write:"write to",schema:"change the schema of",admin:"administer",execute:"run statements on",export:"export","*":"fully use"},"tinycloud.duckdb":{read:"read",select:"read",describe:"describe",write:"write to",import:"import data into",export:"export",admin:"administer",execute:"run statements on","*":"fully use"},"tinycloud.capabilities":{read:"read the capability records of"},"tinycloud.hooks":{subscribe:"subscribe to hooks on",list:"list hooks on",register:"register hooks on",unregister:"remove hooks on"},"tinycloud.delegation":{list:"see the delegations of",status:"check the delegations of"}},units:{day:["day","days"],hour:["hour","hours"],minute:["minute","minutes"],second:["second","seconds"]},captionSource:e=>`Label from ${e}:`,details:{key:{scope:"This key only",summary:"This permission covers only the key shown below."},keyPrefix:{scope:"Keys under this prefix only",summary:"This permission covers only the keys under the prefix shown below."}}},Z=/[\u0000-\u001f\u007f-\u009f\u061c\u180e\u200b-\u200f\u2028-\u202e\u2060-\u2064\u2066-\u2069\ufeff\u{e0000}-\u{e007f}]/gu;function ee(e){return e.replace(Z,e=>`\\u{${e.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}}`)}function te(e){return{...e,service:ee(e.service),...void 0===e.space?{}:{space:ee(e.space)},path:ee(e.path),actions:e.actions.map(ee)}}const ne=864e5,ie=7*ne,oe=/^urn:tinycloud:encryption:[^/]+\/secrets(?:\/|$)/,se=7*ne,ae={kv:"tinycloud.kv",space:"tinycloud.space",sql:"tinycloud.sql",duckdb:"tinycloud.duckdb",capabilities:"tinycloud.capabilities",hooks:"tinycloud.hooks",encryption:"tinycloud.encryption",delegation:"tinycloud.delegation"};function re(e){if(ce(e.service)!==X)return;const t=e.path.indexOf("/"),n=-1===t?"":e.path.slice(t+1);if(""===n){const n=-1===t?e.path:e.path.slice(0,t);return{kind:"network",name:n.slice(n.lastIndexOf(":")+1)}}return n.endsWith("/")?{kind:"keyPrefix",prefix:n}:{kind:"key",keyPath:n}}function ce(e){return ae[e]??e}function le(e){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} ${J.and} ${e[e.length-1]}`}class de extends HTMLElement{constructor(e){super(),this.isVisible=!1,this.releaseScrollLock=null,this.opener=null,this.resolveResult=null,this.handleKeyDown=e=>{this.isVisible&&("Escape"===e.key?this.dismiss():"Tab"===e.key&&this.trapTab(e))},this.options=e,this.attachShadow({mode:"open"}),this.render(),this.completionPromise=new Promise(e=>{this.resolveResult=e})}getCompletionPromise(){return this.completionPromise}connectedCallback(){this.show(),this.setupEventListeners()}disconnectedCallback(){this.isVisible=!1,this.restoreFocus(),this.releaseLock(),document.removeEventListener("keydown",this.handleKeyDown)}render(){const e=this.options.additional.map(e=>this.renderEntry(te(e))).join(""),t=function(e,t){let n;try{n=(0,G.expandPermissionEntries)(e).some(e=>e.service===X&&oe.test(e.path))}catch{n=!1}return n?Math.min(t??36e5,ie):t??se}(this.options.additional,this.options.expiryMs),n=this.options.additional.map(e=>`<li class="permission-line" data-role="permission-line">${ye(function(e,t){const n=te(e),i=re(n),o=function(e,t){const n=ce(e.service),i=e.actions.map(t=>t.startsWith(`${n}/`)?t.slice(n.length+1):t.startsWith(`${e.service}/`)?t.slice(e.service.length+1):t),o=Object.keys(t).filter(e=>i.includes(e)).map(e=>t[e]),s=i.filter(e=>!Object.prototype.hasOwnProperty.call(t,e)).map(J.unknownAction);return[...new Set([...o,...s])]}(n,void 0===i?J.actions[ce(n.service)]??{}:J.actions["network"===i.kind?"encryptionNetwork":"encryptionKey"]),s=J.line(le(o),void 0===i?function(e){const{resource:t}=J,n=""===e.path||"/"===e.path?t.everything:e.path.endsWith("/")?t.pathPrefix(e.path):t.exactPath(e.path);return void 0===e.space||""===e.space?n:t.inSpace(n,e.space)}(n):function(e){switch(e.kind){case"network":return J.resource.network(e.name);case"keyPrefix":return J.resource.keyPrefix(e.prefix);case"key":return J.resource.key(e.keyPath)}}(i),function(e){let t=Math.ceil(e/1e3);const n=[];for(const[e,i]of[["day",86400],["hour",3600],["minute",60],["second",1]]){const o=Math.floor(t/i);t-=o*i,o>0&&n.push(`${o} ${J.units[e][1===o?0:1]}`)}return le(n)}(t));return s.charAt(0).toUpperCase()+s.slice(1)}(e,t))}</li>`).join(""),i=ee(this.options.appName),o=void 0===this.options.onBehalfOf?void 0:ee(this.options.onBehalfOf),s=function(e){if("string"!=typeof e)return;const t=e.replace(/\s+/g," ").replace(Z,"").trim(),n=Array.from(t);return 0!==n.length?n.length>120?`${n.slice(0,119).join("")}…`:t:void 0}(this.options.caption),a=void 0===s?"":`<p class="app-caption" data-role="app-caption"><span class="app-caption-source">${ye(J.captionSource(i))}</span> <span data-role="app-caption-text"></span></p>`,r=ye(i),c=void 0===o?void 0:ye(o),l=void 0===c?`${r} is requesting additional permissions`:`${c} in ${r} is asking for more access`,d=void 0===c?"This app is asking you to grant scoped permission. Review what it will be allowed to do before approving.":`Review what ${c} will be allowed to do before you approve.`,p=!1===this.options.allowSuppression?"":'<label class="suppression-option">\n <input type="checkbox" class="suppression-checkbox" data-role="suppress-prompt" />\n <span>Do not show me again for 30 days</span>\n </label>',u=this.options.appIcon?`<img class="app-icon" src="${h=this.options.appIcon,ye(h)}" alt="" />`:'<div class="app-icon app-icon--placeholder">\n <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/>\n </svg>\n </div>';var h;this.shadowRoot.innerHTML=`\n <style>${this.getModalStyles()}</style>\n <div class="modal-backdrop" data-state="hidden">\n <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="tc-permission-title" aria-describedby="tc-permission-description" tabindex="-1">\n <div class="modal-content">\n <div class="modal-header">\n ${u}\n <h2 class="modal-title" id="tc-permission-title">${l}</h2>\n <button class="modal-close" aria-label="Close">\n <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>\n </svg>\n </button>\n </div>\n\n <div class="modal-body">\n <p class="modal-description" id="tc-permission-description">\n ${d}\n </p>\n <ul class="permission-lines">${n}</ul>\n ${a}\n <ul class="permission-list">${e}</ul>\n ${p}\n </div>\n\n <div class="modal-actions">\n <button class="modal-button modal-button--secondary" data-action="decline">\n Decline\n </button>\n <button class="modal-button modal-button--primary" data-action="approve">\n Approve\n </button>\n </div>\n </div>\n </div>\n </div>\n `,void 0!==s&&(this.shadowRoot.querySelector('[data-role="app-caption-text"]').textContent=s)}renderEntry(e){const t=re(e),n=void 0===t||"network"===t.kind?void 0:J.details[t.kind],i=n?.scope??he(e),o=""===e.path?"/":e.path,s=e.actions.map(t=>function(e,t){const n=function(e,t){return t.includes("/")?t:t.startsWith(`${e}.`)?`${e}/${t.slice(e.length+1)}`:`${e}/${t}`}(e.service,t),i=function(e,t){return t.startsWith(`${e}/`)||t.startsWith(`${e}.`)?t.slice(e.length+1):t}(e.service,t),o=function(e,t){if("tinycloud.kv"!==e.service||"secrets"!==e.space)return;const n=function(e){const t="vault/secrets/";if("vault/secrets"===e)return"all secrets";if(!e.startsWith(t))return;const n=e.slice(14);if(""===n)return"all secrets";const i="scoped/";if(n.startsWith(i)){const[e,...t]=n.slice(7).split("/"),i=t.join("/");if(""!==e&&""!==i)return`the scoped secret ${i} in ${e}`}return`the secret ${n}`}(e.path);if(void 0!==n)switch(t){case"tinycloud.kv/get":return{title:"Read an encrypted secret",description:`Allows this app to read the encrypted secret record for ${n}. Decrypting it still requires encryption-network decrypt permission.`};case"tinycloud.kv/put":return{title:"Write a secret",description:`Allows this app to create or update the encrypted secret record for ${n}.`};case"tinycloud.kv/del":return{title:"Delete a secret",description:`Allows this app to remove the encrypted secret record for ${n}.`};case"tinycloud.kv/list":return{title:"List secrets",description:`Allows this app to list encrypted secret records under ${n}.`};case"tinycloud.kv/metadata":return{title:"Read secret metadata",description:`Allows this app to inspect metadata for encrypted secret records under ${n}.`};default:return}}(e,n)??ue[n]??function(e,t){return{title:"tinycloud.delegation"===e?"Manage your delegations"+(""===t?"":` (${t})`):`Use ${me(e).replace(/ permission$/,"")}`,description:`Allows this app to perform ${t} on the resource shown below.`}}(e.service,i);return{canonicalAction:n,displayAction:i,...o}}(e,t)),a=void 0!==n?"":s.map(e=>`\n <li class="permission-summary-item">\n <div class="permission-summary-row">\n <span class="permission-summary-label">Permission</span>\n <strong class="permission-summary-title">${ye(e.title)}</strong>\n </div>\n <p class="permission-summary-description">${ye(e.description)}</p>\n </li>\n `).join(""),r=[["Service",e.service],["Scope",i],["Resource",o],["Actions",s.map(e=>e.canonicalAction).join(", ")]].map(([e,t])=>`\n <div class="dictionary-row">\n <dt>${ye(e)}</dt>\n <dd>${ye(t)}</dd>\n </div>\n `).join(""),c=function(e){if("string"!=typeof e)return;const t=e.replace(/\s+/g," ").trim(),n=Array.from(t);return 0!==n.length?n.length<=140?{line:ee(t)}:{line:ee(`${n.slice(0,139).join("").trimEnd()}…`),full:ee(t)}:void 0}(e.description);return`\n <li class="permission-entry">\n ${void 0===c?"":`<p class="entry-description" data-role="entry-description">${ye(c.line)}</p>`}${""===a?"":`<ul class="permission-summary-list">${a}</ul>`}\n <details class="technical-details">\n <summary>Show technical details</summary>\n ${void 0===c?.full?"":`<p class="entry-summary" data-role="entry-description-full">${ye(c.full)}</p>`}<p class="entry-summary">${ye(n?.summary??function(e){if("tinycloud.encryption"===e.service)return"This permission applies to an encryption network, not a TinyCloud data space.";return`This permission applies to the ${he(e)} TinyCloud space and the resource path shown below.`}(e))}</p>\n <dl class="permission-dictionary">${r}</dl>\n </details>\n </li>\n `}getModalStyles(){return'\n :host {\n --modal-bg: hsl(0 0% 3.9%);\n --modal-border: hsl(0 0% 14.9%);\n --modal-foreground: hsl(0 0% 98%);\n --modal-muted: hsl(0 0% 63.9%);\n --modal-accent: hsl(217 91% 60%);\n --modal-accent-hover: hsl(217 91% 65%);\n --modal-secondary: hsl(0 0% 10%);\n --modal-secondary-hover: hsl(0 0% 15%);\n --modal-overlay: rgba(0, 0, 0, 0.5);\n }\n .modal-backdrop {\n position: fixed; top: 0; left: 0; right: 0; bottom: 0;\n background: var(--modal-overlay);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n z-index: 2000000;\n display: flex; align-items: flex-start; justify-content: center; overflow-y: auto;\n padding: 20px; opacity: 0;\n transition: opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n pointer-events: none;\n }\n .modal-backdrop[data-state="visible"] { opacity: 1; pointer-events: auto; }\n .modal-container {\n margin: auto;\n transform: scale(0.95) translateY(10px);\n transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n }\n .modal-container:focus { outline: none; }\n .modal-backdrop[data-state="visible"] .modal-container { transform: scale(1) translateY(0); }\n .modal-content {\n background: var(--modal-bg);\n border: 1px solid var(--modal-border);\n border-radius: 16px;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(255, 255, 255, 0.05);\n box-sizing: border-box; max-width: 520px; width: 100%;\n overflow-wrap: anywhere;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;\n color: var(--modal-foreground);\n }\n .modal-header {\n padding: 24px 24px 0 24px;\n display: flex; align-items: flex-start; gap: 16px; position: relative;\n }\n .app-icon {\n flex-shrink: 0; width: 48px; height: 48px;\n border-radius: 12px; object-fit: cover;\n background: var(--modal-secondary);\n }\n .app-icon--placeholder {\n display: flex; align-items: center; justify-content: center;\n background: var(--modal-accent); color: white;\n }\n .modal-title {\n flex: 1; min-width: 0; font-size: 18px; font-weight: 600; line-height: 1.3;\n margin: 0; margin-top: 4px;\n }\n .modal-close {\n position: absolute; top: 0; right: 0;\n background: transparent; border: none;\n color: var(--modal-muted); cursor: pointer;\n padding: 8px; border-radius: 6px; opacity: 0.7;\n transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);\n display: flex; align-items: center; justify-content: center;\n }\n .modal-close:hover { opacity: 1; background: var(--modal-secondary); color: var(--modal-foreground); }\n .modal-body { padding: 20px 24px; }\n .modal-description {\n font-size: 14px; line-height: 1.5; margin: 0 0 16px 0; color: var(--modal-muted);\n }\n .permission-lines {\n list-style: none; padding: 0; margin: 0 0 12px 0;\n display: flex; flex-direction: column; gap: 8px;\n font-size: 15px; font-weight: 600; line-height: 1.4; color: var(--modal-foreground);\n }\n .app-caption {\n font-size: 13px; line-height: 1.45; color: var(--modal-muted);\n margin: 0 0 12px 0;\n }\n .app-caption-source { font-weight: 600; }\n .permission-list {\n list-style: none; padding: 0; margin: 0;\n display: flex; flex-direction: column; gap: 10px;\n max-height: 320px; overflow-y: auto;\n }\n .permission-entry {\n background: var(--modal-secondary);\n border: 1px solid var(--modal-border);\n border-radius: 10px; padding: 14px;\n }\n .suppression-option {\n display: flex; align-items: center; gap: 10px;\n margin-top: 16px; color: var(--modal-muted);\n font-size: 13px; line-height: 1.4; cursor: pointer;\n }\n .suppression-checkbox {\n width: 16px; height: 16px; flex: 0 0 auto;\n margin: 0; accent-color: var(--modal-accent);\n }\n .suppression-option:hover { color: var(--modal-foreground); }\n .entry-summary {\n font-size: 13px; line-height: 1.45; color: var(--modal-muted);\n margin: 10px 0;\n }\n .entry-description {\n font-size: 13px; line-height: 1.45; color: var(--modal-muted);\n margin: 0 0 12px 0;\n }\n .permission-summary-list {\n list-style: none; padding: 0; margin: 0;\n display: flex; flex-direction: column; gap: 10px;\n }\n .permission-summary-item {\n display: flex; flex-direction: column; gap: 6px;\n }\n .permission-summary-row {\n display: grid; grid-template-columns: 88px minmax(0, 1fr);\n gap: 10px; align-items: baseline;\n }\n .permission-summary-label {\n font-size: 12px; color: var(--modal-muted);\n }\n .permission-summary-title {\n font-size: 15px; font-weight: 600; color: var(--modal-foreground);\n line-height: 1.35;\n }\n .permission-summary-description {\n font-size: 13px; line-height: 1.45; color: var(--modal-muted);\n margin: 0;\n }\n .technical-details {\n margin-top: 12px;\n border-top: 1px solid var(--modal-border);\n padding-top: 10px;\n }\n .technical-details:first-child { margin-top: 0; border-top: 0; padding-top: 0; }\n .technical-details summary {\n cursor: pointer; color: var(--modal-muted); font-size: 12px;\n user-select: none;\n }\n .technical-details summary:hover { color: var(--modal-foreground); }\n .technical-details[open] summary { margin-bottom: 8px; }\n .permission-dictionary {\n margin: 0; padding: 0;\n border: 1px solid var(--modal-border);\n border-radius: 8px; overflow: hidden;\n }\n .dictionary-row {\n display: grid; grid-template-columns: 86px 1fr;\n border-top: 1px solid var(--modal-border);\n }\n .dictionary-row:first-child { border-top: 0; }\n .dictionary-row dt,\n .dictionary-row dd {\n margin: 0; padding: 8px 10px; font-size: 12px; line-height: 1.4;\n }\n .dictionary-row dt {\n color: var(--modal-muted); background: var(--modal-bg);\n }\n .dictionary-row dd {\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, "Cascadia Mono", monospace;\n color: var(--modal-foreground); word-break: break-all;\n }\n .modal-actions {\n padding: 0 24px 24px 24px;\n display: flex; gap: 12px; justify-content: flex-end;\n }\n .modal-button {\n padding: 12px 20px; border-radius: 8px;\n font-size: 14px; font-weight: 500; cursor: pointer;\n transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);\n border: 1px solid transparent;\n display: flex; align-items: center; gap: 8px;\n min-width: 100px; justify-content: center;\n }\n .modal-button--secondary {\n background: var(--modal-secondary);\n border-color: var(--modal-border);\n color: var(--modal-foreground);\n }\n .modal-button--secondary:hover {\n background: var(--modal-secondary-hover);\n border-color: hsl(0 0% 25%);\n transform: translateY(-1px);\n }\n .modal-button--primary { background: var(--modal-accent); color: white; }\n .modal-button--primary:hover { background: var(--modal-accent-hover); transform: translateY(-1px); }\n .modal-button--primary:active { transform: translateY(0); }\n @media (max-width: 640px) {\n .modal-content { max-width: 100%; margin: 0 16px; border-radius: 12px; }\n .modal-header { padding: 20px 20px 0 20px; }\n .modal-body { padding: 16px 20px; }\n .modal-actions { padding: 0 20px 20px 20px; flex-direction: column-reverse; }\n .modal-button { width: 100%; }\n .permission-summary-row { grid-template-columns: 1fr; gap: 3px; }\n .dictionary-row { grid-template-columns: 1fr; }\n .dictionary-row dd { padding-top: 0; }\n }\n '}setupEventListeners(){const e=this.shadowRoot.querySelector(".modal-backdrop"),t=this.shadowRoot.querySelector(".modal-close"),n=this.shadowRoot.querySelector('[data-action="decline"]'),i=this.shadowRoot.querySelector('[data-action="approve"]');e?.addEventListener("click",t=>{t.target===e&&this.dismiss()}),t?.addEventListener("click",()=>this.dismiss()),n?.addEventListener("click",()=>this.dismiss()),i?.addEventListener("click",()=>{i&&l(i)&&this.handleApprove()}),document.addEventListener("keydown",this.handleKeyDown)}trapTab(e){if(!e.composedPath().includes(this))return;const t=this.shadowRoot,n=a(t),i=n.indexOf(t.activeElement);e.preventDefault();const o=r(n.length,i,e.shiftKey);o>=0&&n[o].focus()}handleApprove(){const e=this.shadowRoot.querySelector('[data-role="suppress-prompt"]');this.resolveResult?.({approved:!0,suppressPromptFor30Days:!0===e?.checked}),this.hide()}show(){this.isVisible||(this.opener=s()),this.isVisible=!0,this.releaseScrollLock||(this.releaseScrollLock=o()),this.shadowRoot.querySelector(".modal-container").focus(),requestAnimationFrame(()=>{const e=this.shadowRoot.querySelector(".modal-backdrop");e?.setAttribute("data-state","visible")})}hide(){const e=this.shadowRoot.querySelector(".modal-backdrop");e?.setAttribute("data-state","hidden"),this.restoreFocus(),setTimeout(()=>{this.remove(),this.releaseLock(),document.removeEventListener("keydown",this.handleKeyDown)},200),this.isVisible=!1}restoreFocus(){const e=this.opener;this.opener=null,c(e,this.shadowRoot)}releaseLock(){this.releaseScrollLock?.(),this.releaseScrollLock=null}dismiss(){try{this.resolveResult?.({approved:!1}),this.options.onDismiss?.()}finally{this.hide()}}get isOpen(){return this.isVisible}}const pe={"tinycloud.encryption":"Encryption network permission","tinycloud.kv":"Key-value storage permission","tinycloud.sql":"SQL storage permission","tinycloud.duckdb":"DuckDB storage permission","tinycloud.capabilities":"Capability registry permission","tinycloud.hooks":"Hook permission"},ue={[w.DECRYPT]:{title:"Decrypt data keys for this network",description:"Allows this app to ask a TinyCloud node to unwrap encrypted data keys for data encrypted to this network. The app still needs separate data-read permission to fetch encrypted records."},[w.NETWORK_CREATE]:{title:"Create an encryption network",description:"Allows this app to create or initialize an encryption network that data can be encrypted to. The network key is managed by TinyCloud nodes and used later for delegated decrypt requests."},[w.NETWORK_REVOKE]:{title:"Revoke an encryption network",description:"Allows this app to revoke or disable an encryption network so future decrypt requests for that network are denied."},[v.GET]:{title:"Read key-value data",description:"Allows this app to read values at the selected key or key prefix in the requested space."},[v.PUT]:{title:"Write key-value data",description:"Allows this app to create or replace values at the selected key or key prefix in the requested space."},[v.DEL]:{title:"Delete key-value data",description:"Allows this app to remove values at the selected key or key prefix in the requested space."},[v.LIST]:{title:"List key-value entries",description:"Allows this app to list keys under the selected key-value prefix in the requested space."},[v.METADATA]:{title:"Read key-value metadata",description:"Allows this app to inspect metadata for keys without necessarily reading the stored value."},[f.READ]:{title:"Read SQL data",description:"Allows this app to read rows and query results from the selected SQL database in the requested space."},[f.WRITE]:{title:"Write SQL data",description:"Allows this app to insert, update, or delete rows in the selected SQL database."},[f.SCHEMA]:{title:"Change SQL schema",description:"Allows this app to create, alter, or drop SQL tables, indexes, and schema objects."},[f.ADMIN]:{title:"Administer SQL storage",description:"Allows this app to perform administrative SQL operations for the selected database."},[f.SELECT]:{title:"Select SQL rows",description:"Allows this app to run SELECT queries against the selected SQL database."},[f.EXECUTE]:{title:"Execute SQL statements",description:"Allows this app to execute SQL statements against the selected database."},[f.EXPORT]:{title:"Export SQL data",description:"Allows this app to export data from the selected SQL database."},[f.ALL]:{title:"Full SQL access",description:"Allows this app to read, write, administer, and export the selected SQL database."},[b.READ]:{title:"Read DuckDB data",description:"Allows this app to read data and query results from the selected DuckDB database."},[b.WRITE]:{title:"Write DuckDB data",description:"Allows this app to write data to the selected DuckDB database."},[b.ADMIN]:{title:"Administer DuckDB storage",description:"Allows this app to perform administrative operations for the selected DuckDB database."},[b.DESCRIBE]:{title:"Describe DuckDB data",description:"Allows this app to inspect tables, columns, and metadata in the selected DuckDB database."},[b.EXPORT]:{title:"Export DuckDB data",description:"Allows this app to export data from the selected DuckDB database."},[b.IMPORT]:{title:"Import DuckDB data",description:"Allows this app to import data into the selected DuckDB database."},[b.EXECUTE]:{title:"Execute DuckDB statements",description:"Allows this app to execute statements against the selected DuckDB database."},[b.ALL]:{title:"Full DuckDB access",description:"Allows this app to read, write, administer, import, export, and execute statements on the selected DuckDB database."},[g.READ]:{title:"Read delegated capabilities",description:"Allows this app to read capability and delegation records for the selected scope."},"tinycloud.delegation/list":{title:"See which apps and links can reach your data, and the names of what each can reach",description:"See who has access to your data, what it reaches (by name) and when it ends. Keys and contents aren't shown."},[k.SUBSCRIBE]:{title:"Subscribe to hooks",description:"Allows this app to receive hook events for the selected hook scope."},[k.REGISTER]:{title:"Register hooks",description:"Allows this app to register hook handlers for the selected hook scope."},[k.LIST]:{title:"List hooks",description:"Allows this app to list registered hooks for the selected hook scope."},[k.UNREGISTER]:{title:"Unregister hooks",description:"Allows this app to remove registered hook handlers for the selected hook scope."}};function he(e){return void 0!==e.space&&""!==e.space?e.space:"tinycloud.encryption"===e.service?"network-scoped":"unscoped"}function me(e){return pe[e]??`${e} permission`}function ye(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var ve;"undefined"==typeof customElements||customElements.get("tinycloud-permission-request-modal")||customElements.define("tinycloud-permission-request-modal",de);const fe=Symbol.for("tinycloud.web-sdk.prompt-state"),be=(ve=globalThis)[fe]??(ve[fe]={open:new Set,layer:void 0});const ge=Symbol.for("tinycloud.web-sdk.modals"),ke={uiEnabled:!0};class we{constructor(){this.activeModal=null,this.releaseActivePrompt=null}static getInstance(){return we.instance||(we.instance=new we),we.instance}showSpaceCreationModal(e,t=ke){this.displaceActiveModal();const n=new d({...e,onDismiss:()=>{this.clearActive(n),e.onDismiss?.()}});return this.present(n,t,()=>n.dismiss())?n.getCompletionPromise().finally(()=>{this.clearActive(n)}):(e.onDismiss?.(),Promise.resolve({success:!1,dismissed:!0}))}showPermissionRequestModal(e,t=ke){this.displaceActiveModal();const n=new de({...e,onDismiss:()=>{this.clearActive(n),e.onDismiss?.()}});return this.present(n,t,()=>n.dismiss())?n.getCompletionPromise().finally(()=>{this.clearActive(n)}):(e.onDismiss?.(),Promise.resolve({approved:!1}))}present(e,t,n){const i=function(e,t,n){const i=function(e){return function(){try{return"undefined"!=typeof window&&"undefined"!=typeof document&&window.top===window&&"null"!==window.location.origin}catch{return!1}}()?e.uiEnabled&&void 0!==be.layer?void 0:"ui-disabled":"ui-unavailable-frame"}(e);if(void 0!==i)return console.warn(`[tinycloud] ${i}`),{refusal:i};be.layer?.appendChild(t);const o={scope:e,dismiss:n,element:t};return be.open.add(o),{release:()=>{be.open.delete(o),be.layer?.dispatchEvent(new Event("tinycloud-prompt-settled"))}}}(t,e,n);return!("refusal"in i)&&(this.activeModal=e,this.releaseActivePrompt=i.release,!0)}clearActive(e){this.activeModal===e&&(this.releaseActivePrompt?.(),this.releaseActivePrompt=null,this.activeModal=null)}displaceActiveModal(){try{this.closeActiveModal()}catch(e){queueMicrotask(()=>{throw e})}}closeActiveModal(){const e=this.activeModal;if(e)try{e.isOpen&&e.dismiss()}finally{e.remove(),this.clearActive(e)}}hasActiveModal(){return null!==this.activeModal}}const xe=(e,t)=>we.getInstance().showSpaceCreationModal(e,t),Se=(e,t)=>we.getInstance().showPermissionRequestModal(e,t);globalThis[ge]={showPermissionRequestModal:Se,showSpaceCreationModal:xe,closeActiveModal:()=>we.getInstance().closeActiveModal()},module.exports=t})();
|