@dxos/shell 0.4.10-main.dd2b9ae → 0.4.10-main.dfa0529
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/bundle/{index-Ds8vbDTs.mjs → index-BhenUoML.mjs} +2 -2
- package/dist/bundle/{index-Ds8vbDTs.mjs.map → index-BhenUoML.mjs.map} +1 -1
- package/dist/bundle/{index-CaK84FtA.mjs → index-DLLGn1Su.mjs} +41 -39
- package/dist/bundle/index-DLLGn1Su.mjs.map +1 -0
- package/dist/bundle/shell.mjs +1 -1
- package/dist/bundle/shell.umd.js +2 -2
- package/dist/bundle/shell.umd.js.map +1 -1
- package/package.json +21 -21
- package/dist/bundle/index-CaK84FtA.mjs.map +0 -1
package/dist/bundle/shell.umd.js
CHANGED
|
@@ -843,7 +843,7 @@ button {
|
|
|
843
843
|
background-color: #61493f;
|
|
844
844
|
}
|
|
845
845
|
|
|
846
|
-
`;function $e5534fc185f7111e$export$2e2bcd8739ae039($){const I=React.useRef(null),U=React.useRef(null);return U.current&&U.current.update($),React.useEffect(()=>(U.current=new $efa000751917694d$export$2e2bcd8739ae039({...$,ref:I}),()=>{U.current=null}),[]),React.createElement("div",{ref:I})}const EmojiPickerToolbarButton=({disabled:$,defaultEmoji:I,emoji:U,onChangeEmoji:q,classNames:G})=>{const{t:K}=useTranslation("os"),[Y,J]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:U,onChange:q,defaultProp:I}),[X,Z]=React.useState(!1),Q=React.useRef(!1),[ee,te]=React.useState(!1);return React.createElement(Tooltip.Root,{open:ee,onOpenChange:ne=>{Q.current?(te(!1),Q.current=!1):te(ne)}},React.createElement(Popover.Root,{open:X,onOpenChange:ne=>{Z(ne),Q.current=!0}},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Popover.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:["gap-2 text-2xl plb-1",G],disabled:$},React.createElement("span",{className:"sr-only"},K("select emoji label")),React.createElement(react.ImageSquare,{className:getSize(5)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},K("select emoji label"),React.createElement(Tooltip.Arrow,null))),React.createElement(Popover.Content,{side:"bottom",onKeyDownCapture:ne=>{ne.key==="Escape"&&(ne.stopPropagation(),Z(!1),Q.current=!0)}},React.createElement($e5534fc185f7111e$export$2e2bcd8739ae039,{data:emojiData,onEmojiSelect:({native:ne})=>{ne&&(J(ne),Z(!1))},autoFocus:!0,maxFrequentRows:0,noCountryFlags:!0}),React.createElement(Popover.Arrow,null))))},HuePreview=({hue:$})=>{const{tx:I}=useThemeContext();return React.createElement("svg",{width:12,height:12,viewBox:"0 0 12 12"},React.createElement("rect",{x:0,y:0,width:12,height:12,className:I("hue.fill","select--hue__preview",{hue:$})}))},HuePickerToolbarButton=({disabled:$,hue:I,onChangeHue:U,classNames:q,defaultHue:G})=>{const{t:K}=useTranslation("os"),[Y,J]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:I,onChange:U,defaultProp:G}),[X,Z]=React.useState(!1),Q=React.useRef(!1),[ee,te]=React.useState(!1);return React.createElement(Tooltip.Root,{open:ee,onOpenChange:ne=>{Q.current?(te(!1),Q.current=!1):te(ne)}},React.createElement(DropdownMenu2.Root,{modal:!1,open:X,onOpenChange:ne=>{Z(ne),Q.current=!0}},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:mx("gap-2 plb-1",q),disabled:$},React.createElement("span",{className:"sr-only"},K("select hue label")),React.createElement(react.Palette,{className:getSize(5)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},K("select hue label"),React.createElement(Tooltip.Arrow,null))),React.createElement(DropdownMenu2.Content,{side:"bottom"},React.createElement(DropdownMenu2.Viewport,null,Object.keys(hueTokenThemes).map(ne=>React.createElement(DropdownMenu2.CheckboxItem,{key:ne,checked:ne===Y,onCheckedChange:()=>J(ne)},React.createElement(HuePreview,{hue:ne}),React.createElement("span",{className:"grow"},K(`${ne} label`)),React.createElement(DropdownMenu2.ItemIndicator,null,React.createElement(react.Check,null))))),React.createElement(DropdownMenu2.Arrow,null))))};var data={adjectives:["abundant","accessible","accomplished","accurate","achievable","adaptable","adaptive","adequate","adjustable","admirable","admiring","adorable","adored","adoring","adroit","adulatory","advanced","advantageous","adventurous","affable","affectionate","affirmative","affluent","affordable","agile","agreeable","alluring","altruistic","amazed","amazing","ambitious","amenable","amiable","amicable","ample","amusing","angelic","appealing","appreciable","appreciated","appreciative","appropriate","ardent","articulate","artistic","assuring","astonished","astonishing","astounded","astounding","athletic","attentive","attractive","audible","auspicious","authentic","autonomous","available","avid","awed","awesome","awestruck","beauteous","beautiful","believable","beloved","beneficent","beneficial","benevolent","blameless","blissful","blithe","bonny","booming","boundless","bountiful","brainiest","brainy","brave","breathtaking","bright","brighter","brightest","brilliant","brisk","brotherly","bullish","buoyant","calm","calming","capable","captivating","carefree","catchy","celebrated","celebratory","champion","charismatic","charitable","charming","chaste","cheaper","cheapest","cheerful","cheery","cherished","chivalrous","classic","classy","clean","cleaner","cleanest","cleanly","clear","cleared","clearer","clever","coherent","cohesive","colorful","comely","comfortable","comforting","comfy","commendable","commodious","compact","compatible","competitive","compliant","conciliatory","concise","confident","congenial","considerate","consistent","constructive","consummate","contrasty","convenient","convincing","cool","coolest","cooperative","correct","courageous","courteous","courtly","cozy","creative","credible","crisp","crisper","cushy","cute","daring","darling","dashing","dauntless","dazzled","dazzling","decent","decisive","dedicated","defeated","deft","delectable","delicate","delicious","delighted","delightful","dependable","deserving","desirable","desirous","detachable","devout","dexterous","dextrous","dignified","diligent","diplomatic","distinctive","diversified","divine","dominated","dumbfounded","durable","dynamic","eager","earnest","eased","easy","easygoing","ebullient","economical","ecstatic","educated","effective","efficacious","efficient","effortless","effusive","elated","elegant","elite","eloquent","eminent","enchanted","enchanting","encouraging","endearing","endorsed","energetic","engaging","engrossing","enhanced","enjoyable","enraptured","enterprising","entertaining","enthralled","enthusiastic","enticing","entranced","entrancing","enviable","envious","equitable","erudite","ethical","euphoric","evaluative","eventful","everlasting","evocative","exalted","exalting","exceeding","excellent","exceptional","excited","exciting","exemplary","exhilarating","expansive","exquisite","exuberant","exultant","fabulous","fair","faithful","famed","famous","fancier","fancy","fantastic","fascinating","fashionable","fast","faster","fastest","faultless","favorable","favored","favorite","fearless","feasible","feisty","felicitous","fertile","fervent","fervid","festive","fiery","fine","finer","finest","firmer","flashy","flatter","flattering","flawless","flexible","flourishing","fluent","fond","foolproof","foremost","formidable","fortuitous","fortunate","fragrant","free","freed","fresh","fresher","freshest","friendly","frugal","fruitful","fun","funny","futuristic","gainful","gallant","galore","generous","genial","gentle","gentlest","genuine","gifted","glad","glamorous","gleeful","glimmering","glistening","glorious","glowing","godlike","gold","golden","good","goodly","gorgeous","graceful","gracious","grand","grateful","gratified","gratifying","great","greatest","guiltless","gutsy","halcyon","hale","hallowed","handier","handsome","handy","happier","happy","hardier","hardy","harmless","harmonious","healthful","healthy","heartening","heartfelt","heartwarming","heavenly","helpful","heroic","hilarious","holy","honest","honorable","honored","hopeful","hospitable","hot","hottest","humane","humble","humorous","humourous","ideal","idolized","idyllic","illuminating","illustrious","imaginative","immaculate","immense","impartial","impassioned","impeccable","important","impressed","impressive","improved","improving","incredible","indebted","indulgent","industrious","inestimable","inexpensive","infallible","influential","ingenious","ingenuous","innocuous","innovative","insightful","inspiring","instructive","instrumental","intelligent","intelligible","interesting","intimate","intricate","intriguing","intuitive","invaluable","inventive","invigorating","invincible","inviolable","inviolate","invulnerable","irresistible","jolly","jovial","joyful","joyous","jubilant","judicious","keen","kindly","laudable","lavish","lawful","leading","lean","legendary","lighter","likable","like","liked","lionhearted","lively","logical","lovable","loved","lovely","loving","loyal","lucid","luckier","luckiest","lucky","lucrative","luminous","lush","lustrous","luxuriant","luxurious","luxury","lyrical","magic","magical","magnanimous","magnificent","majestic","manageable","marvellous","marvelous","masterful","matchless","mature","meaningful","memorable","merciful","meritorious","merry","mesmerized","mesmerizing","meticulous","mighty","miraculous","modern","modest","momentous","monumental","motivated","navigable","neat","neatest","nice","nifty","nimble","noble","noiseless","noteworthy","nourishing","observant","obtainable","optimal","optimistic","opulent","orderly","organized","outstanding","overjoyed","painless","palatial","pampered","panoramic","paramount","passionate","patient","patri","peaceable","peaceful","peerless","peppy","perfect","permissible","personalized","phenomenal","picturesque","playful","pleasant","pleased","pleasing","pleasurable","plentiful","plush","poetic","poignant","poised","polished","polite","popular","portable","posh","positive","powerful","praiseworthy","praising","precious","precise","preeminent","preferable","premier","prestigious","pretty","priceless","principled","privileged","prize","proactive","prodigious","productive","proficient","profound","progressive","prolific","prominent","promised","promising","prompt","proper","propitious","prosperous","protective","proud","proven","prudent","punctual","pure","purposeful","quaint","qualified","quicker","quiet","quieter","radiant","rapid","rapt","rapturous","rational","reachable","readable","ready","realistic","realizable","reasonable","reasoned","receptive","recommended","redeeming","refined","reformed","refreshed","refreshing","regal","rejoicing","relaxed","reliable","remarkable","renewed","renowned","replaceable","reputable","resilient","resolute","resounding","resourceful","respectable","respectful","resplendent","responsive","restful","restored","retractable","reverent","rewarding","rich","righteous","rightful","robust","romantic","roomier","rosy","safe","saintly","salutary","sane","satisfactory","satisfied","satisfying","scenic","seamless","seasoned","secure","selective","sensational","sensible","sensitive","serene","sexy","sharp","sharper","sharpest","shiny","significant","silent","simpler","simplest","simplified","sincere","skilled","skillful","sleek","slick","smart","smarter","smartest","smelly","smiling","smitten","smooth","smoother","smoothest","snappy","snazzy","sociable","soft","softer","solid","soulful","spacious","sparkling","spectacular","speedy","spellbinding","spellbound","spirited","spiritual","splendid","spontaneous","sporty","spotless","sprightly","stable","stainless","stately","statuesque","staunch","steadfast","steadiest","steady","stellar","stimulating","stimulative","streamlined","striking","strong","stronger","strongest","stunned","stunning","stupendous","sturdier","sturdy","stylish","stylized","suave","sublime","subsidized","substantive","succeeding","successful","sufficient","suitable","sumptuous","super","superb","superior","supple","supportive","supreme","surreal","sustainable","swankier","swankiest","swanky","sweeping","sweet","sweetheart","swift","talented","tantalizing","tempting","tenacious","tender","terrific","thankful","thinner","thoughtful","thrifty","thrilled","thrilling","thriving","tidy","timely","titillating","tolerable","top","topnotch","tough","tougher","toughest","tranquil","transparent","trendy","triumphal","triumphant","trusted","trusting","trustworthy","trusty","truthful","twinkly","unabashed","unaffected","unassailable","unbeatable","unbiased","unbound","undamaged","undaunted","undisputable","undisputed","unencumbered","unequivocal","unfettered","unlimited","unmatched","unparalleled","unreal","unrestricted","unrivaled","unselfish","unwavering","upbeat","upscale","usable","useful","valiant","valuable","verifiable","veritable","versatile","vibrant","victorious","viewable","vigilant","virtuous","visionary","vivacious","vivid","warm","warmer","warmhearted","wealthy","welcome","wholesome","wieldy","winning","wise","witty","wonderful","wondrous","workable","worth","worthwhile","worthy","young","youthful","zippy"],animals:["aardvark","albatross","alligator","angelfish","angora","ant","anteater","antelope","armadillo","avocet","baboon","badger","bandicoot","barnacle","barracuda","bat","beagle","bear","beaver","bee","beetle","bird","bison","bloodhound","boar","bobcat","bonobo","buffalo","bulldog","bullfrog","butterfly","buzzard","camel","cat","caterpillar","catfish","cattle","centipede","chameleon","cheetah","chicken","chihuahua","chimpanzee","chin","chinchilla","chipmunk","civet","clam","cockroach","coon","coral","corgi","cougar","cow","coyote","crab","crane","cuttlefish","dachshund","dalmatian","dane","deer","devil","dingo","dodo","dog","dogfish","dollar","dolphin","donkey","dormouse","dragon","dragonfly","duck","dugong","eagle","earwig","eel","elephant","emperor","emu","falcon","ferret","fish","flamingo","flounder","fly","forest","fowl","fox","foxhound","frog","gar","gecko","gerbil","gharial","gibbon","giraffe","goat","goose","gopher","gorilla","grasshopper","greyhound","grouse","guppy","hamster","hare","hedgehog","heron","hippopotamus","hornet","horse","hound","hummingbird","husky","hyena","hyrax","ibis","iguana","impala","insect","jackal","jaguar","jellyfish","kangaroo","kingfisher","kiwi","koala","kudu","labradoodle","ladybird","lemming","lemur","leopard","liger","lion","lionfish","lizard","llama","lobster","lynx","macaque","macaw","magpie","malamute","maltese","mammoth","manatee","mandrill","markhor","marmoset","mastiff","mayfly","meerkat","millipede","mole","mongoose","monkey","monster","moorhen","moose","moth","mouse","mule","newt","nightingale","ocelot","octopus","okapi","orangutan","ostrich","otter","owl","oyster","panda","panther","parrot","peacock","pelican","penguin","pheasant","pig","pike","piranha","platypus","pointer","poodle","porcupine","possum","prawn","puffin","pug","puma","quail","rabbit","raccoon","rat","rattlesnake","ray","reindeer","retriever","rhinoceros","robin","rottweiler","russel","salamander","scorpion","seahorse","seal","shark","sheep","sheepdog","shrew","shrimp","skater","skunk","sloth","slug","snail","snake","snowshoe","spaniel","sparrow","spider","sponge","squid","squirrel","squirt","starfish","stingray","stoat","swan","tapir","tarantula","termite","terrier","tiger","toad","tortoise","toucan","tuatara","turkey","turtle","uakari","urchin","vole","vulture","wallaby","walrus","warthog","wasp","weasel","whale","whippet","wildebeest","wolf","wolfhound","wolverine","wombat","woodlouse","woodpecker","worm","yak","zebra","zebu","zonkey","zorse"]},capitalize=$=>$.charAt(0).toUpperCase()+$.slice(1),generateName=$=>{const I=$.length*2/3,U=$.substring(0,I),q=$.substring(I),G=capitalize(data.adjectives[parseInt(U,16)%data.adjectives.length]),K=capitalize(data.animals[parseInt(q,16)%data.animals.length]);return`${G} ${K}`};const IdentityListItem=React.forwardRef(({identity:$,presence:I,onClick:U,classNames:q,...G},K)=>{var Z,Q,ee,te,ne;const Y=keyToFallback($.identityKey),J=useId("identityListItem__label"),X=((Z=$.profile)==null?void 0:Z.displayName)??generateName($.identityKey.toHex());return React.createElement(ListItem.Root,{...G,classNames:mx("flex gap-2 pis-3 pie-1 items-center",U&&"cursor-pointer",q),onClick:()=>U==null?void 0:U(),"data-testid":"identity-list-item",labelId:J,ref:K},React.createElement(Avatar.Root,{status:I===echo.SpaceMember.PresenceState.ONLINE?"active":"inactive",labelId:J,hue:((ee=(Q=$.profile)==null?void 0:Q.data)==null?void 0:ee.hue)||Y.hue},React.createElement(Avatar.Frame,{classNames:"place-self-center"},React.createElement(Avatar.Fallback,{text:((ne=(te=$.profile)==null?void 0:te.data)==null?void 0:ne.emoji)||Y.emoji})),React.createElement(Avatar.Label,{classNames:"text-sm truncate pli-2"},X)))}),SpaceMemberList=({spaceKey:$,includeSelf:I,onSelect:U})=>{const q=reactClient.useClient(),G=echo.useMembers($),K=React.useMemo(()=>I?G.sort(Y=>Y.identity.identityKey.equals(q.halo.identity.get().identityKey)?-1:1):G.filter(Y=>!Y.identity.identityKey.equals(q.halo.identity.get().identityKey)),[G]);return React.createElement(SpaceMemberListImpl,{members:K,onSelect:U})},SpaceMemberListImpl=({members:$,onSelect:I})=>{const{t:U}=useTranslation("os"),q=$.filter(G=>G.identity);return q.length>0?React.createElement(List,{classNames:"flex flex-col gap-2","data-testid":"space-members-list"},q.map(G=>React.createElement(IdentityListItem,{key:G.identity.identityKey.toHex(),identity:G.identity,presence:G.presence,onClick:I&&(()=>I(G))}))):React.createElement("div",{role:"none",className:"grow flex items-center p-2"},React.createElement("p",{className:mx(descriptionText,"text-center is-full mlb-2")},U("empty space members message")))},iconProps={weight:"duotone",width:24,height:24,x:8,y:8},DeviceListItem=React.forwardRef(({device:$,onClickAdd:I,onClickEdit:U,onClickReset:q,onClickJoinExisting:G,classNames:K,...Y},J)=>{var ne;const{t:X}=useTranslation("os"),Z=keyToFallback($.deviceKey),Q=useId("identityListItem__label"),ee=$.profile?X("device name placeholder",{os:$.profile.os,platform:$.profile.platform}):generateName($.deviceKey.toHex()),te=$.kind===halo.DeviceKind.CURRENT;return React.createElement(ListItem.Root,{...Y,classNames:["flex gap-2 items-center mlb-2",K],"data-testid":`device-list-item${te?"-current":""}`,labelId:Q,ref:J},React.createElement(Avatar.Root,{status:$.presence===halo.Device.PresenceState.ONLINE?"active":"inactive",labelId:Q,hue:Z.hue,variant:"square"},React.createElement(Avatar.Frame,{classNames:"place-self-center"},(ne=$.profile)!=null&&ne.type?$.profile.type===halo.DeviceType.BROWSER?React.createElement(react.Compass,{...iconProps}):$.profile.type===halo.DeviceType.NATIVE?React.createElement(react.Desktop,{...iconProps}):[halo.DeviceType.AGENT,halo.DeviceType.AGENT_MANAGED].includes($.profile.type)?React.createElement(react.Robot,{...iconProps}):$.profile.type===halo.DeviceType.MOBILE?React.createElement(react.DeviceMobile,{...iconProps}):React.createElement(react.Devices,{...iconProps}):React.createElement(Avatar.Fallback,{text:Z.emoji})),te&&React.createElement(Tag,{color:"primary"},X("current device tag label")),React.createElement(Avatar.Label,{classNames:"flex-1 text-sm truncate"},ee),$.kind===halo.DeviceKind.CURRENT&&React.createElement(DropdownMenu2.Root,null,React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Button,{variant:"ghost",classNames:"pli-0 is-[--rail-action] bs-[--rail-action]","data-testid":`device-list-item${te?"-current":""}.options`},React.createElement("span",{className:"sr-only"},X("more options label")),React.createElement(react.DotsThree,{className:getSize(5)}))),React.createElement(DropdownMenu2.Content,null,React.createElement(DropdownMenu2.Viewport,null,React.createElement(DropdownMenu2.Item,{"data-testid":"device-list-item-current.join-existing",onClick:G},React.createElement(react.Intersect,{className:getSize(5)}),X("choose join new identity label")),React.createElement(DropdownMenu2.Item,{"data-testid":"device-list-item-current.reset",onClick:q},React.createElement(react.Power,{className:getSize(5)}),X("reset device label")))))))}),DeviceList=({devices:$,onClickAdd:I,onClickEdit:U,onClickReset:q,onClickJoinExisting:G})=>{const{t:K}=useTranslation("os");return React.createElement(React.Fragment,null,React.createElement("h2",{className:mx(descriptionText,"text-center mbs-4")},K("devices heading")),$.length>0&&React.createElement(List,null,$.map(Y=>React.createElement(DeviceListItem,{key:Y.deviceKey.toHex(),device:Y,onClickEdit:()=>U==null?void 0:U(Y),onClickReset:q,onClickJoinExisting:G}))),React.createElement(Button,{variant:"ghost",classNames:"justify-start gap-2 !pis-0 !pie-3","data-testid":"devices-panel.create-invitation",onClick:I},React.createElement("div",{role:"img",className:mx(getSize(8),"m-1 rounded-sm surface-input grid place-items-center")},React.createElement(react.Plus,{weight:"light",className:getSize(6)})),React.createElement("span",{className:"grow font-medium text-start"},K("choose add device label")),React.createElement(react.CaretRight,{weight:"bold",className:getSize(4)})))},minutesInMonth=43200,minutesInDay=1440;function getTimezoneOffsetInMilliseconds($){const I=toDate($),U=new Date(Date.UTC(I.getFullYear(),I.getMonth(),I.getDate(),I.getHours(),I.getMinutes(),I.getSeconds(),I.getMilliseconds()));return U.setUTCFullYear(I.getFullYear()),+$-+U}function compareAsc($,I){const U=toDate($),q=toDate(I),G=U.getTime()-q.getTime();return G<0?-1:G>0?1:G}function differenceInCalendarMonths($,I){const U=toDate($),q=toDate(I),G=U.getFullYear()-q.getFullYear(),K=U.getMonth()-q.getMonth();return G*12+K}function getRoundingMethod($){return I=>{const q=($?Math[$]:Math.trunc)(I);return q===0?0:q}}function differenceInMilliseconds($,I){return+toDate($)-+toDate(I)}function endOfDay($){const I=toDate($);return I.setHours(23,59,59,999),I}function endOfMonth($){const I=toDate($),U=I.getMonth();return I.setFullYear(I.getFullYear(),U+1,0),I.setHours(23,59,59,999),I}function isLastDayOfMonth($){const I=toDate($);return+endOfDay(I)==+endOfMonth(I)}function differenceInMonths($,I){const U=toDate($),q=toDate(I),G=compareAsc(U,q),K=Math.abs(differenceInCalendarMonths(U,q));let Y;if(K<1)Y=0;else{U.getMonth()===1&&U.getDate()>27&&U.setDate(30),U.setMonth(U.getMonth()-G*K);let J=compareAsc(U,q)===-G;isLastDayOfMonth(toDate($))&&K===1&&compareAsc($,q)===1&&(J=!1),Y=G*(K-Number(J))}return Y===0?0:Y}function differenceInSeconds($,I,U){const q=differenceInMilliseconds($,I)/1e3;return getRoundingMethod(U==null?void 0:U.roundingMethod)(q)}function formatDistance($,I,U){const q=getDefaultOptions(),G=(U==null?void 0:U.locale)??q.locale??enUS$1,K=2520,Y=compareAsc($,I);if(isNaN(Y))throw new RangeError("Invalid time value");const J=Object.assign({},U,{addSuffix:U==null?void 0:U.addSuffix,comparison:Y});let X,Z;Y>0?(X=toDate(I),Z=toDate($)):(X=toDate($),Z=toDate(I));const Q=differenceInSeconds(Z,X),ee=(getTimezoneOffsetInMilliseconds(Z)-getTimezoneOffsetInMilliseconds(X))/1e3,te=Math.round((Q-ee)/60);let ne;if(te<2)return U!=null&&U.includeSeconds?Q<5?G.formatDistance("lessThanXSeconds",5,J):Q<10?G.formatDistance("lessThanXSeconds",10,J):Q<20?G.formatDistance("lessThanXSeconds",20,J):Q<40?G.formatDistance("halfAMinute",0,J):Q<60?G.formatDistance("lessThanXMinutes",1,J):G.formatDistance("xMinutes",1,J):te===0?G.formatDistance("lessThanXMinutes",1,J):G.formatDistance("xMinutes",te,J);if(te<45)return G.formatDistance("xMinutes",te,J);if(te<90)return G.formatDistance("aboutXHours",1,J);if(te<minutesInDay){const ie=Math.round(te/60);return G.formatDistance("aboutXHours",ie,J)}else{if(te<K)return G.formatDistance("xDays",1,J);if(te<minutesInMonth){const ie=Math.round(te/minutesInDay);return G.formatDistance("xDays",ie,J)}else if(te<minutesInMonth*2)return ne=Math.round(te/minutesInMonth),G.formatDistance("aboutXMonths",ne,J)}if(ne=differenceInMonths(Z,X),ne<12){const ie=Math.round(te/minutesInMonth);return G.formatDistance("xMonths",ie,J)}else{const ie=ne%12,oe=Math.trunc(ne/12);return ie<3?G.formatDistance("aboutXYears",oe,J):ie<9?G.formatDistance("overXYears",oe,J):G.formatDistance("almostXYears",oe+1,J)}}function formatDistanceToNow($,I){return formatDistance($,Date.now(),I)}var LogLevel;(function($){$[$.TRACE=5]="TRACE",$[$.DEBUG=10]="DEBUG",$[$.INFO=11]="INFO",$[$.WARN=12]="WARN",$[$.ERROR=13]="ERROR"})(LogLevel||(LogLevel={}));var QueryLogsRequest;(function($){(function(I){I[I.INCLUSIVE=1]="INCLUSIVE",I[I.EXPLICIT=2]="EXPLICIT"})($.MatchingOptions||($.MatchingOptions={}))})(QueryLogsRequest||(QueryLogsRequest={}));var SystemStatus;(function($){$[$.ACTIVE=0]="ACTIVE",$[$.INACTIVE=1]="INACTIVE"})(SystemStatus||(SystemStatus={}));var GetDiagnosticsRequest;(function($){(function(I){I[I.NONE=0]="NONE",I[I.TRUNCATE=1]="TRUNCATE",I[I.HUMANIZE=2]="HUMANIZE"})($.KEY_OPTION||($.KEY_OPTION={}))})(GetDiagnosticsRequest||(GetDiagnosticsRequest={}));var Platform;(function($){(function(I){I[I.BROWSER=0]="BROWSER",I[I.SHARED_WORKER=1]="SHARED_WORKER",I[I.NODE=2]="NODE"})($.PLATFORM_TYPE||($.PLATFORM_TYPE={}))})(Platform||(Platform={}));var DeviceKind;(function($){$[$.CURRENT=0]="CURRENT",$[$.TRUSTED=1]="TRUSTED"})(DeviceKind||(DeviceKind={}));var Device;(function($){(function(I){I[I.OFFLINE=0]="OFFLINE",I[I.ONLINE=1]="ONLINE",I[I.REMOVED=2]="REMOVED"})($.PresenceState||($.PresenceState={}))})(Device||(Device={}));var SpaceMember;(function($){(function(I){I[I.OFFLINE=0]="OFFLINE",I[I.ONLINE=1]="ONLINE",I[I.REMOVED=2]="REMOVED"})($.PresenceState||($.PresenceState={}))})(SpaceMember||(SpaceMember={}));var SpaceState;(function($){$[$.INACTIVE=2]="INACTIVE",$[$.ACTIVE=6]="ACTIVE",$[$.CLOSED=1]="CLOSED",$[$.CONTROL_ONLY=7]="CONTROL_ONLY",$[$.INITIALIZING=4]="INITIALIZING",$[$.READY=3]="READY",$[$.ERROR=5]="ERROR"})(SpaceState||(SpaceState={}));var CreateEpochRequest;(function($){(function(I){I[I.NONE=0]="NONE",I[I.INIT_AUTOMERGE=1]="INIT_AUTOMERGE",I[I.PRUNE_AUTOMERGE_ROOT_HISTORY=2]="PRUNE_AUTOMERGE_ROOT_HISTORY",I[I.FRAGMENT_AUTOMERGE_ROOT=3]="FRAGMENT_AUTOMERGE_ROOT"})($.Migration||($.Migration={}))})(CreateEpochRequest||(CreateEpochRequest={}));var Invitation;(function($){(function(I){I[I.INTERACTIVE=0]="INTERACTIVE",I[I.DELEGATED=1]="DELEGATED",I[I.MULTIUSE=2]="MULTIUSE"})($.Type||($.Type={})),function(I){I[I.DEVICE=0]="DEVICE",I[I.SPACE=1]="SPACE"}($.Kind||($.Kind={})),function(I){I[I.NONE=0]="NONE",I[I.SHARED_SECRET=1]="SHARED_SECRET",I[I.KNOWN_PUBLIC_KEY=2]="KNOWN_PUBLIC_KEY"}($.AuthMethod||($.AuthMethod={})),function(I){I[I.INIT=0]="INIT",I[I.CONNECTING=1]="CONNECTING",I[I.CONNECTED=2]="CONNECTED",I[I.READY_FOR_AUTHENTICATION=3]="READY_FOR_AUTHENTICATION",I[I.AUTHENTICATING=4]="AUTHENTICATING",I[I.SUCCESS=5]="SUCCESS",I[I.CANCELLED=6]="CANCELLED",I[I.TIMEOUT=7]="TIMEOUT",I[I.ERROR=8]="ERROR",I[I.EXPIRED=9]="EXPIRED"}($.State||($.State={}))})(Invitation||(Invitation={}));var QueryInvitationsResponse;(function($){(function(I){I[I.ADDED=0]="ADDED",I[I.REMOVED=1]="REMOVED",I[I.SAVED=2]="SAVED",I[I.LOAD_COMPLETE=3]="LOAD_COMPLETE"})($.Action||($.Action={})),function(I){I[I.CREATED=0]="CREATED",I[I.ACCEPTED=1]="ACCEPTED"}($.Type||($.Type={}))})(QueryInvitationsResponse||(QueryInvitationsResponse={}));var ConnectionState$2;(function($){$[$.OFFLINE=0]="OFFLINE",$[$.ONLINE=1]="ONLINE"})(ConnectionState$2||(ConnectionState$2={}));var ContextDisposedError=class extends Error{constructor(){super("Context disposed.")}};function _ts_decorate$7($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$8="/home/runner/work/dxos/dxos/packages/common/context/src/context.ts",MAX_SAFE_DISPOSE_CALLBACKS=300,_a$1,_b,Context=(_n=class{constructor({onError:I=G=>{if(!(G instanceof ContextDisposedError))throw this.dispose(),G},attributes:U={},parent:q}={}){this._disposeCallbacks=[],this._isDisposed=!1,this._disposePromise=void 0,this._parent=null,this.maxSafeDisposeCallbacks=MAX_SAFE_DISPOSE_CALLBACKS,this[_a$1]="Context",this[_b]=()=>this.toString(),this._onError=I,this._attributes=U,q!==void 0&&(this._parent=q)}static default(){return new _n}get disposed(){return this._isDisposed}get disposeCallbacksLength(){return this._disposeCallbacks.length}onDispose(I){return this._isDisposed&&(async()=>{try{await I()}catch(U){log$2.catch(U,void 0,{F:__dxlog_file$8,L:88,S:this,C:(q,G)=>q(...G)})}})(),this._disposeCallbacks.push(I),this._disposeCallbacks.length>this.maxSafeDisposeCallbacks&&log$2.warn("Context has a large number of dispose callbacks. This might be a memory leak.",{count:this._disposeCallbacks.length,safeThreshold:this.maxSafeDisposeCallbacks},{F:__dxlog_file$8,L:95,S:this,C:(U,q)=>U(...q)}),()=>{const U=this._disposeCallbacks.indexOf(I);U!==-1&&this._disposeCallbacks.splice(U,1)}}dispose(){if(this._disposePromise)return this._disposePromise;this._isDisposed=!0;let I;this._disposePromise=new Promise(G=>{I=G});const U=[],q=Array.from(this._disposeCallbacks).reverse();for(const G of q)U.push((async()=>{try{await G()}catch(K){log$2.catch(K,void 0,{F:__dxlog_file$8,L:138,S:this,C:(Y,J)=>Y(...J)})}})());return this._disposeCallbacks.length=0,Promise.all(U).then(()=>{I()}),this._disposePromise}raise(I){if(!this._isDisposed)try{this._onError(I)}catch(U){Promise.reject(U)}}derive({onError:I,attributes:U}={}){const q=new _n({onError:async K=>{if(!I)this.raise(K);else try{await I(K)}catch{this.raise(K)}},attributes:U}),G=this.onDispose(()=>q.dispose());return q.onDispose(G),q}getAttribute(I){if(I in this._attributes)return this._attributes[I];if(this._parent!==null)return this._parent.getAttribute(I)}toString(){return`Context(${this._isDisposed?"disposed":"active"})`}},_a$1=Symbol.toStringTag,_b=export_inspect.custom,_n);Context=_ts_decorate$7([safeInstanceof("Context")],Context);var cancelWithContext=($,I)=>{let U;return Promise.race([I,new Promise((q,G)=>{U=$.onDispose(()=>G(new ContextDisposedError))})]).finally(()=>U==null?void 0:U())},LifecycleState;(function($){$.CLOSED="CLOSED",$.OPEN="OPEN",$.ERROR="ERROR"})(LifecycleState||(LifecycleState={}));var Observable$2={};Object.defineProperty(Observable$2,"__esModule",{value:!0}),Observable$2.Observable=void 0;const hasSymbol=$=>!!Symbol[$],getSymbol=$=>hasSymbol($)?Symbol[$]:"@@"+$,SymbolIterator=getSymbol("iterator"),SymbolObservable=getSymbol("observable"),SymbolSpecies=getSymbol("species");function getMethod($,I){let U=$[I];if(U!=null){if(typeof U!="function")throw new TypeError(U+" is not a function");return U}}function getSpecies($){let I=$.constructor;return I!==void 0&&(I=I[SymbolSpecies],I===null&&(I=void 0)),I!==void 0?I:Observable$1}function isObservable$1($){return $ instanceof Observable$1}function hostReportError($){hostReportError.log?hostReportError.log($):setTimeout(()=>{throw $})}function enqueue($){Promise.resolve().then(()=>{try{$()}catch(I){hostReportError(I)}})}function cleanupSubscription($){let I=$._cleanup;if(I!==void 0&&($._cleanup=void 0,!!I))try{if(typeof I=="function")I();else{let U=getMethod(I,"unsubscribe");U&&U.call(I)}}catch(U){hostReportError(U)}}function closeSubscription($){$._observer=void 0,$._queue=void 0,$._state="closed"}function flushSubscription($){let I=$._queue;if(I){$._queue=void 0,$._state="ready";for(let U=0;U<I.length&&(notifySubscription($,I[U].type,I[U].value),$._state!=="closed");++U);}}function notifySubscription($,I,U){$._state="running";let q=$._observer;try{let G=getMethod(q,I);switch(I){case"next":G&&G.call(q,U);break;case"error":if(closeSubscription($),G)G.call(q,U);else throw U;break;case"complete":closeSubscription($),G&&G.call(q);break}}catch(G){hostReportError(G)}$._state==="closed"?cleanupSubscription($):$._state==="running"&&($._state="ready")}function onNotify($,I,U){if($._state!=="closed"){if($._state==="buffering"){$._queue.push({type:I,value:U});return}if($._state!=="ready"){$._state="buffering",$._queue=[{type:I,value:U}],enqueue(()=>flushSubscription($));return}notifySubscription($,I,U)}}class Subscription{constructor(I,U){this._cleanup=void 0,this._observer=I,this._queue=void 0,this._state="initializing";let q=this,G={get closed(){return q._state==="closed"},next(K){onNotify(q,"next",K)},error(K){onNotify(q,"error",K)},complete(){onNotify(q,"complete")}};try{this._cleanup=U.call(void 0,G)}catch(K){G.error(K)}this._state==="initializing"&&(this._state="ready")}get closed(){return this._state==="closed"}unsubscribe(){this._state!=="closed"&&(closeSubscription(this),cleanupSubscription(this))}}let Observable$1=class dr{constructor(I){if(!(this instanceof dr))throw new TypeError("Observable cannot be called as a function");if(typeof I!="function")throw new TypeError("Observable initializer must be a function");this._subscriber=I}subscribe(I){return(typeof I!="object"||I===null)&&(I={next:I,error:arguments[1],complete:arguments[2]}),new Subscription(I,this._subscriber)}forEach(I){return new Promise((U,q)=>{if(typeof I!="function"){q(new TypeError(I+" is not a function"));return}function G(){K.unsubscribe(),U()}let K=this.subscribe({next(Y){try{I(Y,G)}catch(J){q(J),K.unsubscribe()}},error:q,complete:U})})}map(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>this.subscribe({next(G){try{G=I(G)}catch(K){return q.error(K)}q.next(G)},error(G){q.error(G)},complete(){q.complete()}}))}filter(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>this.subscribe({next(G){try{if(!I(G))return}catch(K){return q.error(K)}q.next(G)},error(G){q.error(G)},complete(){q.complete()}}))}reduce(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this),q=arguments.length>1,G=!1,Y=arguments[1];return new U(J=>this.subscribe({next(X){let Z=!G;if(G=!0,!Z||q)try{Y=I(Y,X)}catch(Q){return J.error(Q)}else Y=X},error(X){J.error(X)},complete(){if(!G&&!q)return J.error(new TypeError("Cannot reduce an empty sequence"));J.next(Y),J.complete()}}))}async all(){let I=[];return await this.forEach(U=>I.push(U)),I}concat(...I){let U=getSpecies(this);return new U(q=>{let G,K=0;function Y(J){G=J.subscribe({next(X){q.next(X)},error(X){q.error(X)},complete(){K===I.length?(G=void 0,q.complete()):Y(U.from(I[K++]))}})}return Y(this),()=>{G&&(G.unsubscribe(),G=void 0)}})}flatMap(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>{let G=[],K=this.subscribe({next(J){if(I)try{J=I(J)}catch(Z){return q.error(Z)}let X=U.from(J).subscribe({next(Z){q.next(Z)},error(Z){q.error(Z)},complete(){let Z=G.indexOf(X);Z>=0&&G.splice(Z,1),Y()}});G.push(X)},error(J){q.error(J)},complete(){Y()}});function Y(){K.closed&&G.length===0&&q.complete()}return()=>{G.forEach(J=>J.unsubscribe()),K.unsubscribe()}})}[SymbolObservable](){return this}static from(I){let U=typeof this=="function"?this:dr;if(I==null)throw new TypeError(I+" is not an object");let q=getMethod(I,SymbolObservable);if(q){let G=q.call(I);if(Object(G)!==G)throw new TypeError(G+" is not an object");return isObservable$1(G)&&G.constructor===U?G:new U(K=>G.subscribe(K))}if(hasSymbol("iterator")&&(q=getMethod(I,SymbolIterator),q))return new U(G=>{enqueue(()=>{if(!G.closed){for(let K of q.call(I))if(G.next(K),G.closed)return;G.complete()}})});if(Array.isArray(I))return new U(G=>{enqueue(()=>{if(!G.closed){for(let K=0;K<I.length;++K)if(G.next(I[K]),G.closed)return;G.complete()}})});throw new TypeError(I+" is not observable")}static of(...I){let U=typeof this=="function"?this:dr;return new U(q=>{enqueue(()=>{if(!q.closed){for(let G=0;G<I.length;++G)if(q.next(I[G]),q.closed)return;q.complete()}})})}static get[SymbolSpecies](){return this}};Observable$2.Observable=Observable$1,Object.defineProperty(Observable$1,Symbol("extensions"),{value:{symbol:SymbolObservable,hostReportError},configurable:!0});var zenObservable=Observable$2.Observable;const Observable=getDefaultExportFromCjs(zenObservable);var readableBrowser={exports:{}},events={exports:{}},R=typeof Reflect=="object"?Reflect:null,ReflectApply=R&&typeof R.apply=="function"?R.apply:function(I,U,q){return Function.prototype.apply.call(I,U,q)},ReflectOwnKeys;R&&typeof R.ownKeys=="function"?ReflectOwnKeys=R.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(I){return Object.getOwnPropertyNames(I).concat(Object.getOwnPropertySymbols(I))}:ReflectOwnKeys=function(I){return Object.getOwnPropertyNames(I)};function ProcessEmitWarning($){console&&console.warn&&console.warn($)}var NumberIsNaN=Number.isNaN||function(I){return I!==I};function EventEmitter$1(){EventEmitter$1.init.call(this)}events.exports=EventEmitter$1,events.exports.once=once$2,EventEmitter$1.EventEmitter=EventEmitter$1,EventEmitter$1.prototype._events=void 0,EventEmitter$1.prototype._eventsCount=0,EventEmitter$1.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener($){if(typeof $!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof $)}Object.defineProperty(EventEmitter$1,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function($){if(typeof $!="number"||$<0||NumberIsNaN($))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+$+".");defaultMaxListeners=$}}),EventEmitter$1.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter$1.prototype.setMaxListeners=function(I){if(typeof I!="number"||I<0||NumberIsNaN(I))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+I+".");return this._maxListeners=I,this};function _getMaxListeners($){return $._maxListeners===void 0?EventEmitter$1.defaultMaxListeners:$._maxListeners}EventEmitter$1.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter$1.prototype.emit=function(I){for(var U=[],q=1;q<arguments.length;q++)U.push(arguments[q]);var G=I==="error",K=this._events;if(K!==void 0)G=G&&K.error===void 0;else if(!G)return!1;if(G){var Y;if(U.length>0&&(Y=U[0]),Y instanceof Error)throw Y;var J=new Error("Unhandled error."+(Y?" ("+Y.message+")":""));throw J.context=Y,J}var X=K[I];if(X===void 0)return!1;if(typeof X=="function")ReflectApply(X,this,U);else for(var Z=X.length,Q=arrayClone(X,Z),q=0;q<Z;++q)ReflectApply(Q[q],this,U);return!0};function _addListener($,I,U,q){var G,K,Y;if(checkListener(U),K=$._events,K===void 0?(K=$._events=Object.create(null),$._eventsCount=0):(K.newListener!==void 0&&($.emit("newListener",I,U.listener?U.listener:U),K=$._events),Y=K[I]),Y===void 0)Y=K[I]=U,++$._eventsCount;else if(typeof Y=="function"?Y=K[I]=q?[U,Y]:[Y,U]:q?Y.unshift(U):Y.push(U),G=_getMaxListeners($),G>0&&Y.length>G&&!Y.warned){Y.warned=!0;var J=new Error("Possible EventEmitter memory leak detected. "+Y.length+" "+String(I)+" listeners added. Use emitter.setMaxListeners() to increase limit");J.name="MaxListenersExceededWarning",J.emitter=$,J.type=I,J.count=Y.length,ProcessEmitWarning(J)}return $}EventEmitter$1.prototype.addListener=function(I,U){return _addListener(this,I,U,!1)},EventEmitter$1.prototype.on=EventEmitter$1.prototype.addListener,EventEmitter$1.prototype.prependListener=function(I,U){return _addListener(this,I,U,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap($,I,U){var q={fired:!1,wrapFn:void 0,target:$,type:I,listener:U},G=onceWrapper.bind(q);return G.listener=U,q.wrapFn=G,G}EventEmitter$1.prototype.once=function(I,U){return checkListener(U),this.on(I,_onceWrap(this,I,U)),this},EventEmitter$1.prototype.prependOnceListener=function(I,U){return checkListener(U),this.prependListener(I,_onceWrap(this,I,U)),this},EventEmitter$1.prototype.removeListener=function(I,U){var q,G,K,Y,J;if(checkListener(U),G=this._events,G===void 0)return this;if(q=G[I],q===void 0)return this;if(q===U||q.listener===U)--this._eventsCount===0?this._events=Object.create(null):(delete G[I],G.removeListener&&this.emit("removeListener",I,q.listener||U));else if(typeof q!="function"){for(K=-1,Y=q.length-1;Y>=0;Y--)if(q[Y]===U||q[Y].listener===U){J=q[Y].listener,K=Y;break}if(K<0)return this;K===0?q.shift():spliceOne(q,K),q.length===1&&(G[I]=q[0]),G.removeListener!==void 0&&this.emit("removeListener",I,J||U)}return this},EventEmitter$1.prototype.off=EventEmitter$1.prototype.removeListener,EventEmitter$1.prototype.removeAllListeners=function(I){var U,q,G;if(q=this._events,q===void 0)return this;if(q.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):q[I]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete q[I]),this;if(arguments.length===0){var K=Object.keys(q),Y;for(G=0;G<K.length;++G)Y=K[G],Y!=="removeListener"&&this.removeAllListeners(Y);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(U=q[I],typeof U=="function")this.removeListener(I,U);else if(U!==void 0)for(G=U.length-1;G>=0;G--)this.removeListener(I,U[G]);return this};function _listeners($,I,U){var q=$._events;if(q===void 0)return[];var G=q[I];return G===void 0?[]:typeof G=="function"?U?[G.listener||G]:[G]:U?unwrapListeners(G):arrayClone(G,G.length)}EventEmitter$1.prototype.listeners=function(I){return _listeners(this,I,!0)},EventEmitter$1.prototype.rawListeners=function(I){return _listeners(this,I,!1)},EventEmitter$1.listenerCount=function($,I){return typeof $.listenerCount=="function"?$.listenerCount(I):listenerCount.call($,I)},EventEmitter$1.prototype.listenerCount=listenerCount;function listenerCount($){var I=this._events;if(I!==void 0){var U=I[$];if(typeof U=="function")return 1;if(U!==void 0)return U.length}return 0}EventEmitter$1.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone($,I){for(var U=new Array(I),q=0;q<I;++q)U[q]=$[q];return U}function spliceOne($,I){for(;I+1<$.length;I++)$[I]=$[I+1];$.pop()}function unwrapListeners($){for(var I=new Array($.length),U=0;U<I.length;++U)I[U]=$[U].listener||$[U];return I}function once$2($,I){return new Promise(function(U,q){function G(Y){$.removeListener(I,K),q(Y)}function K(){typeof $.removeListener=="function"&&$.removeListener("error",G),U([].slice.call(arguments))}eventTargetAgnosticAddListener($,I,K,{once:!0}),I!=="error"&&addErrorHandlerIfEventEmitter($,G,{once:!0})})}function addErrorHandlerIfEventEmitter($,I,U){typeof $.on=="function"&&eventTargetAgnosticAddListener($,"error",I,U)}function eventTargetAgnosticAddListener($,I,U,q){if(typeof $.on=="function")q.once?$.once(I,U):$.on(I,U);else if(typeof $.addEventListener=="function")$.addEventListener(I,function G(K){q.once&&$.removeEventListener(I,G),U(K)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof $)}var eventsExports=events.exports,streamBrowser=eventsExports.EventEmitter,buffer={},base64Js={};base64Js.byteLength=byteLength,base64Js.toByteArray=toByteArray,base64Js.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i$2=0,len=code.length;i$2<len;++i$2)lookup[i$2]=code[i$2],revLookup[code.charCodeAt(i$2)]=i$2;revLookup[45]=62,revLookup[95]=63;function getLens($){var I=$.length;if(I%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var U=$.indexOf("=");U===-1&&(U=I);var q=U===I?0:4-U%4;return[U,q]}function byteLength($){var I=getLens($),U=I[0],q=I[1];return(U+q)*3/4-q}function _byteLength($,I,U){return(I+U)*3/4-U}function toByteArray($){var I,U=getLens($),q=U[0],G=U[1],K=new Arr(_byteLength($,q,G)),Y=0,J=G>0?q-4:q,X;for(X=0;X<J;X+=4)I=revLookup[$.charCodeAt(X)]<<18|revLookup[$.charCodeAt(X+1)]<<12|revLookup[$.charCodeAt(X+2)]<<6|revLookup[$.charCodeAt(X+3)],K[Y++]=I>>16&255,K[Y++]=I>>8&255,K[Y++]=I&255;return G===2&&(I=revLookup[$.charCodeAt(X)]<<2|revLookup[$.charCodeAt(X+1)]>>4,K[Y++]=I&255),G===1&&(I=revLookup[$.charCodeAt(X)]<<10|revLookup[$.charCodeAt(X+1)]<<4|revLookup[$.charCodeAt(X+2)]>>2,K[Y++]=I>>8&255,K[Y++]=I&255),K}function tripletToBase64($){return lookup[$>>18&63]+lookup[$>>12&63]+lookup[$>>6&63]+lookup[$&63]}function encodeChunk$1($,I,U){for(var q,G=[],K=I;K<U;K+=3)q=($[K]<<16&16711680)+($[K+1]<<8&65280)+($[K+2]&255),G.push(tripletToBase64(q));return G.join("")}function fromByteArray($){for(var I,U=$.length,q=U%3,G=[],K=16383,Y=0,J=U-q;Y<J;Y+=K)G.push(encodeChunk$1($,Y,Y+K>J?J:Y+K));return q===1?(I=$[U-1],G.push(lookup[I>>2]+lookup[I<<4&63]+"==")):q===2&&(I=($[U-2]<<8)+$[U-1],G.push(lookup[I>>10]+lookup[I>>4&63]+lookup[I<<2&63]+"=")),G.join("")}var ieee754={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ieee754.read=function($,I,U,q,G){var K,Y,J=G*8-q-1,X=(1<<J)-1,Z=X>>1,Q=-7,ee=U?G-1:0,te=U?-1:1,ne=$[I+ee];for(ee+=te,K=ne&(1<<-Q)-1,ne>>=-Q,Q+=J;Q>0;K=K*256+$[I+ee],ee+=te,Q-=8);for(Y=K&(1<<-Q)-1,K>>=-Q,Q+=q;Q>0;Y=Y*256+$[I+ee],ee+=te,Q-=8);if(K===0)K=1-Z;else{if(K===X)return Y?NaN:(ne?-1:1)*(1/0);Y=Y+Math.pow(2,q),K=K-Z}return(ne?-1:1)*Y*Math.pow(2,K-q)},ieee754.write=function($,I,U,q,G,K){var Y,J,X,Z=K*8-G-1,Q=(1<<Z)-1,ee=Q>>1,te=G===23?Math.pow(2,-24)-Math.pow(2,-77):0,ne=q?0:K-1,ie=q?1:-1,oe=I<0||I===0&&1/I<0?1:0;for(I=Math.abs(I),isNaN(I)||I===1/0?(J=isNaN(I)?1:0,Y=Q):(Y=Math.floor(Math.log(I)/Math.LN2),I*(X=Math.pow(2,-Y))<1&&(Y--,X*=2),Y+ee>=1?I+=te/X:I+=te*Math.pow(2,1-ee),I*X>=2&&(Y++,X/=2),Y+ee>=Q?(J=0,Y=Q):Y+ee>=1?(J=(I*X-1)*Math.pow(2,G),Y=Y+ee):(J=I*Math.pow(2,ee-1)*Math.pow(2,G),Y=0));G>=8;$[U+ne]=J&255,ne+=ie,J/=256,G-=8);for(Y=Y<<G|J,Z+=G;Z>0;$[U+ne]=Y&255,ne+=ie,Y/=256,Z-=8);$[U+ne-ie]|=oe*128};/*!
|
|
846
|
+
`;function $e5534fc185f7111e$export$2e2bcd8739ae039($){const I=React.useRef(null),U=React.useRef(null);return U.current&&U.current.update($),React.useEffect(()=>(U.current=new $efa000751917694d$export$2e2bcd8739ae039({...$,ref:I}),()=>{U.current=null}),[]),React.createElement("div",{ref:I})}const EmojiPickerToolbarButton=({disabled:$,defaultEmoji:I,emoji:U,onChangeEmoji:q,classNames:G})=>{const{t:K}=useTranslation("os"),[Y,J]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:U,onChange:q,defaultProp:I}),[X,Z]=React.useState(!1),Q=React.useRef(!1),[ee,te]=React.useState(!1);return React.createElement(Tooltip.Root,{open:ee,onOpenChange:ne=>{Q.current?(te(!1),Q.current=!1):te(ne)}},React.createElement(Popover.Root,{open:X,onOpenChange:ne=>{Z(ne),Q.current=!0}},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Popover.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:["gap-2 text-2xl plb-1",G],disabled:$},React.createElement("span",{className:"sr-only"},K("select emoji label")),React.createElement(react.ImageSquare,{className:getSize(5)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},K("select emoji label"),React.createElement(Tooltip.Arrow,null))),React.createElement(Popover.Content,{side:"bottom",onKeyDownCapture:ne=>{ne.key==="Escape"&&(ne.stopPropagation(),Z(!1),Q.current=!0)}},React.createElement($e5534fc185f7111e$export$2e2bcd8739ae039,{data:emojiData,onEmojiSelect:({native:ne})=>{ne&&(J(ne),Z(!1))},autoFocus:!0,maxFrequentRows:0,noCountryFlags:!0}),React.createElement(Popover.Arrow,null))))},HuePreview=({hue:$})=>{const{tx:I}=useThemeContext();return React.createElement("svg",{width:12,height:12,viewBox:"0 0 12 12"},React.createElement("rect",{x:0,y:0,width:12,height:12,className:I("hue.fill","select--hue__preview",{hue:$})}))},HuePickerToolbarButton=({disabled:$,hue:I,onChangeHue:U,classNames:q,defaultHue:G})=>{const{t:K}=useTranslation("os"),[Y,J]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:I,onChange:U,defaultProp:G}),[X,Z]=React.useState(!1),Q=React.useRef(!1),[ee,te]=React.useState(!1);return React.createElement(Tooltip.Root,{open:ee,onOpenChange:ne=>{Q.current?(te(!1),Q.current=!1):te(ne)}},React.createElement(DropdownMenu2.Root,{modal:!1,open:X,onOpenChange:ne=>{Z(ne),Q.current=!0}},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:mx("gap-2 plb-1",q),disabled:$},React.createElement("span",{className:"sr-only"},K("select hue label")),React.createElement(react.Palette,{className:getSize(5)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},K("select hue label"),React.createElement(Tooltip.Arrow,null))),React.createElement(DropdownMenu2.Content,{side:"bottom"},React.createElement(DropdownMenu2.Viewport,null,Object.keys(hueTokenThemes).map(ne=>React.createElement(DropdownMenu2.CheckboxItem,{key:ne,checked:ne===Y,onCheckedChange:()=>J(ne)},React.createElement(HuePreview,{hue:ne}),React.createElement("span",{className:"grow"},K(`${ne} label`)),React.createElement(DropdownMenu2.ItemIndicator,null,React.createElement(react.Check,null))))),React.createElement(DropdownMenu2.Arrow,null))))};var data={adjectives:["abundant","accessible","accomplished","accurate","achievable","adaptable","adaptive","adequate","adjustable","admirable","admiring","adorable","adored","adoring","adroit","adulatory","advanced","advantageous","adventurous","affable","affectionate","affirmative","affluent","affordable","agile","agreeable","alluring","altruistic","amazed","amazing","ambitious","amenable","amiable","amicable","ample","amusing","angelic","appealing","appreciable","appreciated","appreciative","appropriate","ardent","articulate","artistic","assuring","astonished","astonishing","astounded","astounding","athletic","attentive","attractive","audible","auspicious","authentic","autonomous","available","avid","awed","awesome","awestruck","beauteous","beautiful","believable","beloved","beneficent","beneficial","benevolent","blameless","blissful","blithe","bonny","booming","boundless","bountiful","brainiest","brainy","brave","breathtaking","bright","brighter","brightest","brilliant","brisk","brotherly","bullish","buoyant","calm","calming","capable","captivating","carefree","catchy","celebrated","celebratory","champion","charismatic","charitable","charming","chaste","cheaper","cheapest","cheerful","cheery","cherished","chivalrous","classic","classy","clean","cleaner","cleanest","cleanly","clear","cleared","clearer","clever","coherent","cohesive","colorful","comely","comfortable","comforting","comfy","commendable","commodious","compact","compatible","competitive","compliant","conciliatory","concise","confident","congenial","considerate","consistent","constructive","consummate","contrasty","convenient","convincing","cool","coolest","cooperative","correct","courageous","courteous","courtly","cozy","creative","credible","crisp","crisper","cushy","cute","daring","darling","dashing","dauntless","dazzled","dazzling","decent","decisive","dedicated","defeated","deft","delectable","delicate","delicious","delighted","delightful","dependable","deserving","desirable","desirous","detachable","devout","dexterous","dextrous","dignified","diligent","diplomatic","distinctive","diversified","divine","dominated","dumbfounded","durable","dynamic","eager","earnest","eased","easy","easygoing","ebullient","economical","ecstatic","educated","effective","efficacious","efficient","effortless","effusive","elated","elegant","elite","eloquent","eminent","enchanted","enchanting","encouraging","endearing","endorsed","energetic","engaging","engrossing","enhanced","enjoyable","enraptured","enterprising","entertaining","enthralled","enthusiastic","enticing","entranced","entrancing","enviable","envious","equitable","erudite","ethical","euphoric","evaluative","eventful","everlasting","evocative","exalted","exalting","exceeding","excellent","exceptional","excited","exciting","exemplary","exhilarating","expansive","exquisite","exuberant","exultant","fabulous","fair","faithful","famed","famous","fancier","fancy","fantastic","fascinating","fashionable","fast","faster","fastest","faultless","favorable","favored","favorite","fearless","feasible","feisty","felicitous","fertile","fervent","fervid","festive","fiery","fine","finer","finest","firmer","flashy","flatter","flattering","flawless","flexible","flourishing","fluent","fond","foolproof","foremost","formidable","fortuitous","fortunate","fragrant","free","freed","fresh","fresher","freshest","friendly","frugal","fruitful","fun","funny","futuristic","gainful","gallant","galore","generous","genial","gentle","gentlest","genuine","gifted","glad","glamorous","gleeful","glimmering","glistening","glorious","glowing","godlike","gold","golden","good","goodly","gorgeous","graceful","gracious","grand","grateful","gratified","gratifying","great","greatest","guiltless","gutsy","halcyon","hale","hallowed","handier","handsome","handy","happier","happy","hardier","hardy","harmless","harmonious","healthful","healthy","heartening","heartfelt","heartwarming","heavenly","helpful","heroic","hilarious","holy","honest","honorable","honored","hopeful","hospitable","hot","hottest","humane","humble","humorous","humourous","ideal","idolized","idyllic","illuminating","illustrious","imaginative","immaculate","immense","impartial","impassioned","impeccable","important","impressed","impressive","improved","improving","incredible","indebted","indulgent","industrious","inestimable","inexpensive","infallible","influential","ingenious","ingenuous","innocuous","innovative","insightful","inspiring","instructive","instrumental","intelligent","intelligible","interesting","intimate","intricate","intriguing","intuitive","invaluable","inventive","invigorating","invincible","inviolable","inviolate","invulnerable","irresistible","jolly","jovial","joyful","joyous","jubilant","judicious","keen","kindly","laudable","lavish","lawful","leading","lean","legendary","lighter","likable","like","liked","lionhearted","lively","logical","lovable","loved","lovely","loving","loyal","lucid","luckier","luckiest","lucky","lucrative","luminous","lush","lustrous","luxuriant","luxurious","luxury","lyrical","magic","magical","magnanimous","magnificent","majestic","manageable","marvellous","marvelous","masterful","matchless","mature","meaningful","memorable","merciful","meritorious","merry","mesmerized","mesmerizing","meticulous","mighty","miraculous","modern","modest","momentous","monumental","motivated","navigable","neat","neatest","nice","nifty","nimble","noble","noiseless","noteworthy","nourishing","observant","obtainable","optimal","optimistic","opulent","orderly","organized","outstanding","overjoyed","painless","palatial","pampered","panoramic","paramount","passionate","patient","patri","peaceable","peaceful","peerless","peppy","perfect","permissible","personalized","phenomenal","picturesque","playful","pleasant","pleased","pleasing","pleasurable","plentiful","plush","poetic","poignant","poised","polished","polite","popular","portable","posh","positive","powerful","praiseworthy","praising","precious","precise","preeminent","preferable","premier","prestigious","pretty","priceless","principled","privileged","prize","proactive","prodigious","productive","proficient","profound","progressive","prolific","prominent","promised","promising","prompt","proper","propitious","prosperous","protective","proud","proven","prudent","punctual","pure","purposeful","quaint","qualified","quicker","quiet","quieter","radiant","rapid","rapt","rapturous","rational","reachable","readable","ready","realistic","realizable","reasonable","reasoned","receptive","recommended","redeeming","refined","reformed","refreshed","refreshing","regal","rejoicing","relaxed","reliable","remarkable","renewed","renowned","replaceable","reputable","resilient","resolute","resounding","resourceful","respectable","respectful","resplendent","responsive","restful","restored","retractable","reverent","rewarding","rich","righteous","rightful","robust","romantic","roomier","rosy","safe","saintly","salutary","sane","satisfactory","satisfied","satisfying","scenic","seamless","seasoned","secure","selective","sensational","sensible","sensitive","serene","sexy","sharp","sharper","sharpest","shiny","significant","silent","simpler","simplest","simplified","sincere","skilled","skillful","sleek","slick","smart","smarter","smartest","smelly","smiling","smitten","smooth","smoother","smoothest","snappy","snazzy","sociable","soft","softer","solid","soulful","spacious","sparkling","spectacular","speedy","spellbinding","spellbound","spirited","spiritual","splendid","spontaneous","sporty","spotless","sprightly","stable","stainless","stately","statuesque","staunch","steadfast","steadiest","steady","stellar","stimulating","stimulative","streamlined","striking","strong","stronger","strongest","stunned","stunning","stupendous","sturdier","sturdy","stylish","stylized","suave","sublime","subsidized","substantive","succeeding","successful","sufficient","suitable","sumptuous","super","superb","superior","supple","supportive","supreme","surreal","sustainable","swankier","swankiest","swanky","sweeping","sweet","sweetheart","swift","talented","tantalizing","tempting","tenacious","tender","terrific","thankful","thinner","thoughtful","thrifty","thrilled","thrilling","thriving","tidy","timely","titillating","tolerable","top","topnotch","tough","tougher","toughest","tranquil","transparent","trendy","triumphal","triumphant","trusted","trusting","trustworthy","trusty","truthful","twinkly","unabashed","unaffected","unassailable","unbeatable","unbiased","unbound","undamaged","undaunted","undisputable","undisputed","unencumbered","unequivocal","unfettered","unlimited","unmatched","unparalleled","unreal","unrestricted","unrivaled","unselfish","unwavering","upbeat","upscale","usable","useful","valiant","valuable","verifiable","veritable","versatile","vibrant","victorious","viewable","vigilant","virtuous","visionary","vivacious","vivid","warm","warmer","warmhearted","wealthy","welcome","wholesome","wieldy","winning","wise","witty","wonderful","wondrous","workable","worth","worthwhile","worthy","young","youthful","zippy"],animals:["aardvark","albatross","alligator","angelfish","angora","ant","anteater","antelope","armadillo","avocet","baboon","badger","bandicoot","barnacle","barracuda","bat","beagle","bear","beaver","bee","beetle","bird","bison","bloodhound","boar","bobcat","bonobo","buffalo","bulldog","bullfrog","butterfly","buzzard","camel","cat","caterpillar","catfish","cattle","centipede","chameleon","cheetah","chicken","chihuahua","chimpanzee","chin","chinchilla","chipmunk","civet","clam","cockroach","coon","coral","corgi","cougar","cow","coyote","crab","crane","cuttlefish","dachshund","dalmatian","dane","deer","devil","dingo","dodo","dog","dogfish","dollar","dolphin","donkey","dormouse","dragon","dragonfly","duck","dugong","eagle","earwig","eel","elephant","emperor","emu","falcon","ferret","fish","flamingo","flounder","fly","forest","fowl","fox","foxhound","frog","gar","gecko","gerbil","gharial","gibbon","giraffe","goat","goose","gopher","gorilla","grasshopper","greyhound","grouse","guppy","hamster","hare","hedgehog","heron","hippopotamus","hornet","horse","hound","hummingbird","husky","hyena","hyrax","ibis","iguana","impala","insect","jackal","jaguar","jellyfish","kangaroo","kingfisher","kiwi","koala","kudu","labradoodle","ladybird","lemming","lemur","leopard","liger","lion","lionfish","lizard","llama","lobster","lynx","macaque","macaw","magpie","malamute","maltese","mammoth","manatee","mandrill","markhor","marmoset","mastiff","mayfly","meerkat","millipede","mole","mongoose","monkey","monster","moorhen","moose","moth","mouse","mule","newt","nightingale","ocelot","octopus","okapi","orangutan","ostrich","otter","owl","oyster","panda","panther","parrot","peacock","pelican","penguin","pheasant","pig","pike","piranha","platypus","pointer","poodle","porcupine","possum","prawn","puffin","pug","puma","quail","rabbit","raccoon","rat","rattlesnake","ray","reindeer","retriever","rhinoceros","robin","rottweiler","russel","salamander","scorpion","seahorse","seal","shark","sheep","sheepdog","shrew","shrimp","skater","skunk","sloth","slug","snail","snake","snowshoe","spaniel","sparrow","spider","sponge","squid","squirrel","squirt","starfish","stingray","stoat","swan","tapir","tarantula","termite","terrier","tiger","toad","tortoise","toucan","tuatara","turkey","turtle","uakari","urchin","vole","vulture","wallaby","walrus","warthog","wasp","weasel","whale","whippet","wildebeest","wolf","wolfhound","wolverine","wombat","woodlouse","woodpecker","worm","yak","zebra","zebu","zonkey","zorse"]},capitalize=$=>$.charAt(0).toUpperCase()+$.slice(1),generateName=$=>{const I=$.length*2/3,U=$.substring(0,I),q=$.substring(I),G=capitalize(data.adjectives[parseInt(U,16)%data.adjectives.length]),K=capitalize(data.animals[parseInt(q,16)%data.animals.length]);return`${G} ${K}`};const IdentityListItem=React.forwardRef(({identity:$,presence:I,onClick:U,classNames:q,...G},K)=>{var Z,Q,ee,te,ne;const Y=keyToFallback($.identityKey),J=useId("identityListItem__label"),X=((Z=$.profile)==null?void 0:Z.displayName)??generateName($.identityKey.toHex());return React.createElement(ListItem.Root,{...G,classNames:mx("flex gap-2 pis-3 pie-1 items-center",U&&"cursor-pointer",q),onClick:()=>U==null?void 0:U(),"data-testid":"identity-list-item",labelId:J,ref:K},React.createElement(Avatar.Root,{status:I===echo.SpaceMember.PresenceState.ONLINE?"active":"inactive",labelId:J,hue:((ee=(Q=$.profile)==null?void 0:Q.data)==null?void 0:ee.hue)||Y.hue},React.createElement(Avatar.Frame,{classNames:"place-self-center"},React.createElement(Avatar.Fallback,{text:((ne=(te=$.profile)==null?void 0:te.data)==null?void 0:ne.emoji)||Y.emoji})),React.createElement(Avatar.Label,{classNames:"text-sm truncate pli-2"},X)))}),SpaceMemberList=({spaceKey:$,includeSelf:I,onSelect:U})=>{const q=reactClient.useClient(),G=echo.useMembers($),K=React.useMemo(()=>I?G.sort(Y=>Y.identity.identityKey.equals(q.halo.identity.get().identityKey)?-1:1):G.filter(Y=>!Y.identity.identityKey.equals(q.halo.identity.get().identityKey)),[G]);return React.createElement(SpaceMemberListImpl,{members:K,onSelect:U})},SpaceMemberListImpl=({members:$,onSelect:I})=>{const{t:U}=useTranslation("os"),q=$.filter(G=>G.identity);return q.length>0?React.createElement(List,{classNames:"flex flex-col gap-2","data-testid":"space-members-list"},q.map(G=>React.createElement(IdentityListItem,{key:G.identity.identityKey.toHex(),identity:G.identity,presence:G.presence,onClick:I&&(()=>I(G))}))):React.createElement("div",{role:"none",className:"grow flex items-center p-2"},React.createElement("p",{className:mx(descriptionText,"text-center is-full mlb-2")},U("empty space members message")))},iconProps={weight:"duotone",width:24,height:24,x:8,y:8},DeviceListItem=React.forwardRef(({device:$,onClickAdd:I,onClickEdit:U,onClickReset:q,onClickJoinExisting:G,classNames:K,...Y},J)=>{var ne;const{t:X}=useTranslation("os"),Z=keyToFallback($.deviceKey),Q=useId("identityListItem__label"),ee=$.profile?X("device name placeholder",{os:$.profile.os,platform:$.profile.platform}):generateName($.deviceKey.toHex()),te=$.kind===halo.DeviceKind.CURRENT;return React.createElement(ListItem.Root,{...Y,classNames:["flex gap-2 items-center mlb-2",K],"data-testid":`device-list-item${te?"-current":""}`,labelId:Q,ref:J},React.createElement(Avatar.Root,{status:$.presence===halo.Device.PresenceState.ONLINE?"active":"inactive",labelId:Q,hue:Z.hue,variant:"square"},React.createElement(Avatar.Frame,{classNames:"place-self-center"},(ne=$.profile)!=null&&ne.type?$.profile.type===halo.DeviceType.BROWSER?React.createElement(react.Compass,{...iconProps}):$.profile.type===halo.DeviceType.NATIVE?React.createElement(react.Desktop,{...iconProps}):[halo.DeviceType.AGENT,halo.DeviceType.AGENT_MANAGED].includes($.profile.type)?React.createElement(react.Robot,{...iconProps}):$.profile.type===halo.DeviceType.MOBILE?React.createElement(react.DeviceMobile,{...iconProps}):React.createElement(react.Devices,{...iconProps}):React.createElement(Avatar.Fallback,{text:Z.emoji})),te&&React.createElement(Tag,{color:"primary"},X("current device tag label")),React.createElement(Avatar.Label,{classNames:"flex-1 text-sm truncate"},ee),$.kind===halo.DeviceKind.CURRENT&&React.createElement(DropdownMenu2.Root,null,React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Button,{variant:"ghost",classNames:"pli-0 is-[--rail-action] bs-[--rail-action]","data-testid":`device-list-item${te?"-current":""}.options`},React.createElement("span",{className:"sr-only"},X("more options label")),React.createElement(react.DotsThree,{className:getSize(5)}))),React.createElement(DropdownMenu2.Content,null,React.createElement(DropdownMenu2.Viewport,null,React.createElement(DropdownMenu2.Item,{"data-testid":"device-list-item-current.join-existing",onClick:G},React.createElement(react.Intersect,{className:getSize(5)}),X("choose join new identity label")),React.createElement(DropdownMenu2.Item,{"data-testid":"device-list-item-current.reset",onClick:q},React.createElement(react.Power,{className:getSize(5)}),X("reset device label")))))))}),DeviceList=({devices:$,onClickAdd:I,onClickEdit:U,onClickReset:q,onClickJoinExisting:G})=>{const{t:K}=useTranslation("os");return React.createElement(React.Fragment,null,React.createElement("h2",{className:mx(descriptionText,"text-center mbs-4")},K("devices heading")),$.length>0&&React.createElement(List,null,$.map(Y=>React.createElement(DeviceListItem,{key:Y.deviceKey.toHex(),device:Y,onClickEdit:()=>U==null?void 0:U(Y),onClickReset:q,onClickJoinExisting:G}))),React.createElement(Button,{variant:"ghost",classNames:"justify-start gap-2 !pis-0 !pie-3","data-testid":"devices-panel.create-invitation",onClick:I},React.createElement("div",{role:"img",className:mx(getSize(8),"m-1 rounded-sm surface-input grid place-items-center")},React.createElement(react.Plus,{weight:"light",className:getSize(6)})),React.createElement("span",{className:"grow font-medium text-start"},K("choose add device label")),React.createElement(react.CaretRight,{weight:"bold",className:getSize(4)})))},minutesInMonth=43200,minutesInDay=1440;function getTimezoneOffsetInMilliseconds($){const I=toDate($),U=new Date(Date.UTC(I.getFullYear(),I.getMonth(),I.getDate(),I.getHours(),I.getMinutes(),I.getSeconds(),I.getMilliseconds()));return U.setUTCFullYear(I.getFullYear()),+$-+U}function compareAsc($,I){const U=toDate($),q=toDate(I),G=U.getTime()-q.getTime();return G<0?-1:G>0?1:G}function differenceInCalendarMonths($,I){const U=toDate($),q=toDate(I),G=U.getFullYear()-q.getFullYear(),K=U.getMonth()-q.getMonth();return G*12+K}function getRoundingMethod($){return I=>{const q=($?Math[$]:Math.trunc)(I);return q===0?0:q}}function differenceInMilliseconds($,I){return+toDate($)-+toDate(I)}function endOfDay($){const I=toDate($);return I.setHours(23,59,59,999),I}function endOfMonth($){const I=toDate($),U=I.getMonth();return I.setFullYear(I.getFullYear(),U+1,0),I.setHours(23,59,59,999),I}function isLastDayOfMonth($){const I=toDate($);return+endOfDay(I)==+endOfMonth(I)}function differenceInMonths($,I){const U=toDate($),q=toDate(I),G=compareAsc(U,q),K=Math.abs(differenceInCalendarMonths(U,q));let Y;if(K<1)Y=0;else{U.getMonth()===1&&U.getDate()>27&&U.setDate(30),U.setMonth(U.getMonth()-G*K);let J=compareAsc(U,q)===-G;isLastDayOfMonth(toDate($))&&K===1&&compareAsc($,q)===1&&(J=!1),Y=G*(K-Number(J))}return Y===0?0:Y}function differenceInSeconds($,I,U){const q=differenceInMilliseconds($,I)/1e3;return getRoundingMethod(U==null?void 0:U.roundingMethod)(q)}function formatDistance($,I,U){const q=getDefaultOptions(),G=(U==null?void 0:U.locale)??q.locale??enUS$1,K=2520,Y=compareAsc($,I);if(isNaN(Y))throw new RangeError("Invalid time value");const J=Object.assign({},U,{addSuffix:U==null?void 0:U.addSuffix,comparison:Y});let X,Z;Y>0?(X=toDate(I),Z=toDate($)):(X=toDate($),Z=toDate(I));const Q=differenceInSeconds(Z,X),ee=(getTimezoneOffsetInMilliseconds(Z)-getTimezoneOffsetInMilliseconds(X))/1e3,te=Math.round((Q-ee)/60);let ne;if(te<2)return U!=null&&U.includeSeconds?Q<5?G.formatDistance("lessThanXSeconds",5,J):Q<10?G.formatDistance("lessThanXSeconds",10,J):Q<20?G.formatDistance("lessThanXSeconds",20,J):Q<40?G.formatDistance("halfAMinute",0,J):Q<60?G.formatDistance("lessThanXMinutes",1,J):G.formatDistance("xMinutes",1,J):te===0?G.formatDistance("lessThanXMinutes",1,J):G.formatDistance("xMinutes",te,J);if(te<45)return G.formatDistance("xMinutes",te,J);if(te<90)return G.formatDistance("aboutXHours",1,J);if(te<minutesInDay){const ie=Math.round(te/60);return G.formatDistance("aboutXHours",ie,J)}else{if(te<K)return G.formatDistance("xDays",1,J);if(te<minutesInMonth){const ie=Math.round(te/minutesInDay);return G.formatDistance("xDays",ie,J)}else if(te<minutesInMonth*2)return ne=Math.round(te/minutesInMonth),G.formatDistance("aboutXMonths",ne,J)}if(ne=differenceInMonths(Z,X),ne<12){const ie=Math.round(te/minutesInMonth);return G.formatDistance("xMonths",ie,J)}else{const ie=ne%12,oe=Math.trunc(ne/12);return ie<3?G.formatDistance("aboutXYears",oe,J):ie<9?G.formatDistance("overXYears",oe,J):G.formatDistance("almostXYears",oe+1,J)}}function formatDistanceToNow($,I){return formatDistance($,Date.now(),I)}var RPC_TIMEOUT=2e4,LogLevel;(function($){$[$.TRACE=5]="TRACE",$[$.DEBUG=10]="DEBUG",$[$.INFO=11]="INFO",$[$.WARN=12]="WARN",$[$.ERROR=13]="ERROR"})(LogLevel||(LogLevel={}));var QueryLogsRequest;(function($){(function(I){I[I.INCLUSIVE=1]="INCLUSIVE",I[I.EXPLICIT=2]="EXPLICIT"})($.MatchingOptions||($.MatchingOptions={}))})(QueryLogsRequest||(QueryLogsRequest={}));var SystemStatus;(function($){$[$.ACTIVE=0]="ACTIVE",$[$.INACTIVE=1]="INACTIVE"})(SystemStatus||(SystemStatus={}));var GetDiagnosticsRequest;(function($){(function(I){I[I.NONE=0]="NONE",I[I.TRUNCATE=1]="TRUNCATE",I[I.HUMANIZE=2]="HUMANIZE"})($.KEY_OPTION||($.KEY_OPTION={}))})(GetDiagnosticsRequest||(GetDiagnosticsRequest={}));var Platform;(function($){(function(I){I[I.BROWSER=0]="BROWSER",I[I.SHARED_WORKER=1]="SHARED_WORKER",I[I.NODE=2]="NODE"})($.PLATFORM_TYPE||($.PLATFORM_TYPE={}))})(Platform||(Platform={}));var DeviceKind;(function($){$[$.CURRENT=0]="CURRENT",$[$.TRUSTED=1]="TRUSTED"})(DeviceKind||(DeviceKind={}));var Device;(function($){(function(I){I[I.OFFLINE=0]="OFFLINE",I[I.ONLINE=1]="ONLINE",I[I.REMOVED=2]="REMOVED"})($.PresenceState||($.PresenceState={}))})(Device||(Device={}));var SpaceMember;(function($){(function(I){I[I.OFFLINE=0]="OFFLINE",I[I.ONLINE=1]="ONLINE",I[I.REMOVED=2]="REMOVED"})($.PresenceState||($.PresenceState={}))})(SpaceMember||(SpaceMember={}));var SpaceState;(function($){$[$.INACTIVE=2]="INACTIVE",$[$.ACTIVE=6]="ACTIVE",$[$.CLOSED=1]="CLOSED",$[$.CONTROL_ONLY=7]="CONTROL_ONLY",$[$.INITIALIZING=4]="INITIALIZING",$[$.READY=3]="READY",$[$.ERROR=5]="ERROR"})(SpaceState||(SpaceState={}));var CreateEpochRequest;(function($){(function(I){I[I.NONE=0]="NONE",I[I.INIT_AUTOMERGE=1]="INIT_AUTOMERGE",I[I.PRUNE_AUTOMERGE_ROOT_HISTORY=2]="PRUNE_AUTOMERGE_ROOT_HISTORY",I[I.FRAGMENT_AUTOMERGE_ROOT=3]="FRAGMENT_AUTOMERGE_ROOT"})($.Migration||($.Migration={}))})(CreateEpochRequest||(CreateEpochRequest={}));var Invitation;(function($){(function(I){I[I.INTERACTIVE=0]="INTERACTIVE",I[I.DELEGATED=1]="DELEGATED",I[I.MULTIUSE=2]="MULTIUSE"})($.Type||($.Type={})),function(I){I[I.DEVICE=0]="DEVICE",I[I.SPACE=1]="SPACE"}($.Kind||($.Kind={})),function(I){I[I.NONE=0]="NONE",I[I.SHARED_SECRET=1]="SHARED_SECRET",I[I.KNOWN_PUBLIC_KEY=2]="KNOWN_PUBLIC_KEY"}($.AuthMethod||($.AuthMethod={})),function(I){I[I.INIT=0]="INIT",I[I.CONNECTING=1]="CONNECTING",I[I.CONNECTED=2]="CONNECTED",I[I.READY_FOR_AUTHENTICATION=3]="READY_FOR_AUTHENTICATION",I[I.AUTHENTICATING=4]="AUTHENTICATING",I[I.SUCCESS=5]="SUCCESS",I[I.CANCELLED=6]="CANCELLED",I[I.TIMEOUT=7]="TIMEOUT",I[I.ERROR=8]="ERROR",I[I.EXPIRED=9]="EXPIRED"}($.State||($.State={}))})(Invitation||(Invitation={}));var QueryInvitationsResponse;(function($){(function(I){I[I.ADDED=0]="ADDED",I[I.REMOVED=1]="REMOVED",I[I.SAVED=2]="SAVED",I[I.LOAD_COMPLETE=3]="LOAD_COMPLETE"})($.Action||($.Action={})),function(I){I[I.CREATED=0]="CREATED",I[I.ACCEPTED=1]="ACCEPTED"}($.Type||($.Type={}))})(QueryInvitationsResponse||(QueryInvitationsResponse={}));var ConnectionState$2;(function($){$[$.OFFLINE=0]="OFFLINE",$[$.ONLINE=1]="ONLINE"})(ConnectionState$2||(ConnectionState$2={}));var ContextDisposedError=class extends Error{constructor(){super("Context disposed.")}};function _ts_decorate$7($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$8="/home/runner/work/dxos/dxos/packages/common/context/src/context.ts",MAX_SAFE_DISPOSE_CALLBACKS=300,_a$1,_b,Context=(_n=class{constructor({onError:I=G=>{if(!(G instanceof ContextDisposedError))throw this.dispose(),G},attributes:U={},parent:q}={}){this._disposeCallbacks=[],this._isDisposed=!1,this._disposePromise=void 0,this._parent=null,this.maxSafeDisposeCallbacks=MAX_SAFE_DISPOSE_CALLBACKS,this[_a$1]="Context",this[_b]=()=>this.toString(),this._onError=I,this._attributes=U,q!==void 0&&(this._parent=q)}static default(){return new _n}get disposed(){return this._isDisposed}get disposeCallbacksLength(){return this._disposeCallbacks.length}onDispose(I){return this._isDisposed&&(async()=>{try{await I()}catch(U){log$2.catch(U,void 0,{F:__dxlog_file$8,L:88,S:this,C:(q,G)=>q(...G)})}})(),this._disposeCallbacks.push(I),this._disposeCallbacks.length>this.maxSafeDisposeCallbacks&&log$2.warn("Context has a large number of dispose callbacks. This might be a memory leak.",{count:this._disposeCallbacks.length,safeThreshold:this.maxSafeDisposeCallbacks},{F:__dxlog_file$8,L:95,S:this,C:(U,q)=>U(...q)}),()=>{const U=this._disposeCallbacks.indexOf(I);U!==-1&&this._disposeCallbacks.splice(U,1)}}async dispose(){if(this._disposePromise)return this._disposePromise;this._isDisposed=!0;let I;this._disposePromise=new Promise(q=>{I=q});const U=Array.from(this._disposeCallbacks).reverse();this._disposeCallbacks.length=0;for(const q of U)try{await q()}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$8,L:136,S:this,C:(K,Y)=>K(...Y)})}I()}raise(I){if(!this._isDisposed)try{this._onError(I)}catch(U){Promise.reject(U)}}derive({onError:I,attributes:U}={}){const q=new _n({onError:async K=>{if(!I)this.raise(K);else try{await I(K)}catch{this.raise(K)}},attributes:U}),G=this.onDispose(()=>q.dispose());return q.onDispose(G),q}getAttribute(I){if(I in this._attributes)return this._attributes[I];if(this._parent!==null)return this._parent.getAttribute(I)}toString(){return`Context(${this._isDisposed?"disposed":"active"})`}},_a$1=Symbol.toStringTag,_b=export_inspect.custom,_n);Context=_ts_decorate$7([safeInstanceof("Context")],Context);var cancelWithContext=($,I)=>{let U;return Promise.race([I,new Promise((q,G)=>{U=$.onDispose(()=>G(new ContextDisposedError))})]).finally(()=>U==null?void 0:U())},LifecycleState;(function($){$.CLOSED="CLOSED",$.OPEN="OPEN",$.ERROR="ERROR"})(LifecycleState||(LifecycleState={}));var Observable$2={};Object.defineProperty(Observable$2,"__esModule",{value:!0}),Observable$2.Observable=void 0;const hasSymbol=$=>!!Symbol[$],getSymbol=$=>hasSymbol($)?Symbol[$]:"@@"+$,SymbolIterator=getSymbol("iterator"),SymbolObservable=getSymbol("observable"),SymbolSpecies=getSymbol("species");function getMethod($,I){let U=$[I];if(U!=null){if(typeof U!="function")throw new TypeError(U+" is not a function");return U}}function getSpecies($){let I=$.constructor;return I!==void 0&&(I=I[SymbolSpecies],I===null&&(I=void 0)),I!==void 0?I:Observable$1}function isObservable$1($){return $ instanceof Observable$1}function hostReportError($){hostReportError.log?hostReportError.log($):setTimeout(()=>{throw $})}function enqueue($){Promise.resolve().then(()=>{try{$()}catch(I){hostReportError(I)}})}function cleanupSubscription($){let I=$._cleanup;if(I!==void 0&&($._cleanup=void 0,!!I))try{if(typeof I=="function")I();else{let U=getMethod(I,"unsubscribe");U&&U.call(I)}}catch(U){hostReportError(U)}}function closeSubscription($){$._observer=void 0,$._queue=void 0,$._state="closed"}function flushSubscription($){let I=$._queue;if(I){$._queue=void 0,$._state="ready";for(let U=0;U<I.length&&(notifySubscription($,I[U].type,I[U].value),$._state!=="closed");++U);}}function notifySubscription($,I,U){$._state="running";let q=$._observer;try{let G=getMethod(q,I);switch(I){case"next":G&&G.call(q,U);break;case"error":if(closeSubscription($),G)G.call(q,U);else throw U;break;case"complete":closeSubscription($),G&&G.call(q);break}}catch(G){hostReportError(G)}$._state==="closed"?cleanupSubscription($):$._state==="running"&&($._state="ready")}function onNotify($,I,U){if($._state!=="closed"){if($._state==="buffering"){$._queue.push({type:I,value:U});return}if($._state!=="ready"){$._state="buffering",$._queue=[{type:I,value:U}],enqueue(()=>flushSubscription($));return}notifySubscription($,I,U)}}class Subscription{constructor(I,U){this._cleanup=void 0,this._observer=I,this._queue=void 0,this._state="initializing";let q=this,G={get closed(){return q._state==="closed"},next(K){onNotify(q,"next",K)},error(K){onNotify(q,"error",K)},complete(){onNotify(q,"complete")}};try{this._cleanup=U.call(void 0,G)}catch(K){G.error(K)}this._state==="initializing"&&(this._state="ready")}get closed(){return this._state==="closed"}unsubscribe(){this._state!=="closed"&&(closeSubscription(this),cleanupSubscription(this))}}let Observable$1=class dr{constructor(I){if(!(this instanceof dr))throw new TypeError("Observable cannot be called as a function");if(typeof I!="function")throw new TypeError("Observable initializer must be a function");this._subscriber=I}subscribe(I){return(typeof I!="object"||I===null)&&(I={next:I,error:arguments[1],complete:arguments[2]}),new Subscription(I,this._subscriber)}forEach(I){return new Promise((U,q)=>{if(typeof I!="function"){q(new TypeError(I+" is not a function"));return}function G(){K.unsubscribe(),U()}let K=this.subscribe({next(Y){try{I(Y,G)}catch(J){q(J),K.unsubscribe()}},error:q,complete:U})})}map(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>this.subscribe({next(G){try{G=I(G)}catch(K){return q.error(K)}q.next(G)},error(G){q.error(G)},complete(){q.complete()}}))}filter(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>this.subscribe({next(G){try{if(!I(G))return}catch(K){return q.error(K)}q.next(G)},error(G){q.error(G)},complete(){q.complete()}}))}reduce(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this),q=arguments.length>1,G=!1,Y=arguments[1];return new U(J=>this.subscribe({next(X){let Z=!G;if(G=!0,!Z||q)try{Y=I(Y,X)}catch(Q){return J.error(Q)}else Y=X},error(X){J.error(X)},complete(){if(!G&&!q)return J.error(new TypeError("Cannot reduce an empty sequence"));J.next(Y),J.complete()}}))}async all(){let I=[];return await this.forEach(U=>I.push(U)),I}concat(...I){let U=getSpecies(this);return new U(q=>{let G,K=0;function Y(J){G=J.subscribe({next(X){q.next(X)},error(X){q.error(X)},complete(){K===I.length?(G=void 0,q.complete()):Y(U.from(I[K++]))}})}return Y(this),()=>{G&&(G.unsubscribe(),G=void 0)}})}flatMap(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>{let G=[],K=this.subscribe({next(J){if(I)try{J=I(J)}catch(Z){return q.error(Z)}let X=U.from(J).subscribe({next(Z){q.next(Z)},error(Z){q.error(Z)},complete(){let Z=G.indexOf(X);Z>=0&&G.splice(Z,1),Y()}});G.push(X)},error(J){q.error(J)},complete(){Y()}});function Y(){K.closed&&G.length===0&&q.complete()}return()=>{G.forEach(J=>J.unsubscribe()),K.unsubscribe()}})}[SymbolObservable](){return this}static from(I){let U=typeof this=="function"?this:dr;if(I==null)throw new TypeError(I+" is not an object");let q=getMethod(I,SymbolObservable);if(q){let G=q.call(I);if(Object(G)!==G)throw new TypeError(G+" is not an object");return isObservable$1(G)&&G.constructor===U?G:new U(K=>G.subscribe(K))}if(hasSymbol("iterator")&&(q=getMethod(I,SymbolIterator),q))return new U(G=>{enqueue(()=>{if(!G.closed){for(let K of q.call(I))if(G.next(K),G.closed)return;G.complete()}})});if(Array.isArray(I))return new U(G=>{enqueue(()=>{if(!G.closed){for(let K=0;K<I.length;++K)if(G.next(I[K]),G.closed)return;G.complete()}})});throw new TypeError(I+" is not observable")}static of(...I){let U=typeof this=="function"?this:dr;return new U(q=>{enqueue(()=>{if(!q.closed){for(let G=0;G<I.length;++G)if(q.next(I[G]),q.closed)return;q.complete()}})})}static get[SymbolSpecies](){return this}};Observable$2.Observable=Observable$1,Object.defineProperty(Observable$1,Symbol("extensions"),{value:{symbol:SymbolObservable,hostReportError},configurable:!0});var zenObservable=Observable$2.Observable;const Observable=getDefaultExportFromCjs(zenObservable);var readableBrowser={exports:{}},events={exports:{}},R=typeof Reflect=="object"?Reflect:null,ReflectApply=R&&typeof R.apply=="function"?R.apply:function(I,U,q){return Function.prototype.apply.call(I,U,q)},ReflectOwnKeys;R&&typeof R.ownKeys=="function"?ReflectOwnKeys=R.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(I){return Object.getOwnPropertyNames(I).concat(Object.getOwnPropertySymbols(I))}:ReflectOwnKeys=function(I){return Object.getOwnPropertyNames(I)};function ProcessEmitWarning($){console&&console.warn&&console.warn($)}var NumberIsNaN=Number.isNaN||function(I){return I!==I};function EventEmitter$1(){EventEmitter$1.init.call(this)}events.exports=EventEmitter$1,events.exports.once=once$2,EventEmitter$1.EventEmitter=EventEmitter$1,EventEmitter$1.prototype._events=void 0,EventEmitter$1.prototype._eventsCount=0,EventEmitter$1.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener($){if(typeof $!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof $)}Object.defineProperty(EventEmitter$1,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function($){if(typeof $!="number"||$<0||NumberIsNaN($))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+$+".");defaultMaxListeners=$}}),EventEmitter$1.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter$1.prototype.setMaxListeners=function(I){if(typeof I!="number"||I<0||NumberIsNaN(I))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+I+".");return this._maxListeners=I,this};function _getMaxListeners($){return $._maxListeners===void 0?EventEmitter$1.defaultMaxListeners:$._maxListeners}EventEmitter$1.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter$1.prototype.emit=function(I){for(var U=[],q=1;q<arguments.length;q++)U.push(arguments[q]);var G=I==="error",K=this._events;if(K!==void 0)G=G&&K.error===void 0;else if(!G)return!1;if(G){var Y;if(U.length>0&&(Y=U[0]),Y instanceof Error)throw Y;var J=new Error("Unhandled error."+(Y?" ("+Y.message+")":""));throw J.context=Y,J}var X=K[I];if(X===void 0)return!1;if(typeof X=="function")ReflectApply(X,this,U);else for(var Z=X.length,Q=arrayClone(X,Z),q=0;q<Z;++q)ReflectApply(Q[q],this,U);return!0};function _addListener($,I,U,q){var G,K,Y;if(checkListener(U),K=$._events,K===void 0?(K=$._events=Object.create(null),$._eventsCount=0):(K.newListener!==void 0&&($.emit("newListener",I,U.listener?U.listener:U),K=$._events),Y=K[I]),Y===void 0)Y=K[I]=U,++$._eventsCount;else if(typeof Y=="function"?Y=K[I]=q?[U,Y]:[Y,U]:q?Y.unshift(U):Y.push(U),G=_getMaxListeners($),G>0&&Y.length>G&&!Y.warned){Y.warned=!0;var J=new Error("Possible EventEmitter memory leak detected. "+Y.length+" "+String(I)+" listeners added. Use emitter.setMaxListeners() to increase limit");J.name="MaxListenersExceededWarning",J.emitter=$,J.type=I,J.count=Y.length,ProcessEmitWarning(J)}return $}EventEmitter$1.prototype.addListener=function(I,U){return _addListener(this,I,U,!1)},EventEmitter$1.prototype.on=EventEmitter$1.prototype.addListener,EventEmitter$1.prototype.prependListener=function(I,U){return _addListener(this,I,U,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap($,I,U){var q={fired:!1,wrapFn:void 0,target:$,type:I,listener:U},G=onceWrapper.bind(q);return G.listener=U,q.wrapFn=G,G}EventEmitter$1.prototype.once=function(I,U){return checkListener(U),this.on(I,_onceWrap(this,I,U)),this},EventEmitter$1.prototype.prependOnceListener=function(I,U){return checkListener(U),this.prependListener(I,_onceWrap(this,I,U)),this},EventEmitter$1.prototype.removeListener=function(I,U){var q,G,K,Y,J;if(checkListener(U),G=this._events,G===void 0)return this;if(q=G[I],q===void 0)return this;if(q===U||q.listener===U)--this._eventsCount===0?this._events=Object.create(null):(delete G[I],G.removeListener&&this.emit("removeListener",I,q.listener||U));else if(typeof q!="function"){for(K=-1,Y=q.length-1;Y>=0;Y--)if(q[Y]===U||q[Y].listener===U){J=q[Y].listener,K=Y;break}if(K<0)return this;K===0?q.shift():spliceOne(q,K),q.length===1&&(G[I]=q[0]),G.removeListener!==void 0&&this.emit("removeListener",I,J||U)}return this},EventEmitter$1.prototype.off=EventEmitter$1.prototype.removeListener,EventEmitter$1.prototype.removeAllListeners=function(I){var U,q,G;if(q=this._events,q===void 0)return this;if(q.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):q[I]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete q[I]),this;if(arguments.length===0){var K=Object.keys(q),Y;for(G=0;G<K.length;++G)Y=K[G],Y!=="removeListener"&&this.removeAllListeners(Y);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(U=q[I],typeof U=="function")this.removeListener(I,U);else if(U!==void 0)for(G=U.length-1;G>=0;G--)this.removeListener(I,U[G]);return this};function _listeners($,I,U){var q=$._events;if(q===void 0)return[];var G=q[I];return G===void 0?[]:typeof G=="function"?U?[G.listener||G]:[G]:U?unwrapListeners(G):arrayClone(G,G.length)}EventEmitter$1.prototype.listeners=function(I){return _listeners(this,I,!0)},EventEmitter$1.prototype.rawListeners=function(I){return _listeners(this,I,!1)},EventEmitter$1.listenerCount=function($,I){return typeof $.listenerCount=="function"?$.listenerCount(I):listenerCount.call($,I)},EventEmitter$1.prototype.listenerCount=listenerCount;function listenerCount($){var I=this._events;if(I!==void 0){var U=I[$];if(typeof U=="function")return 1;if(U!==void 0)return U.length}return 0}EventEmitter$1.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone($,I){for(var U=new Array(I),q=0;q<I;++q)U[q]=$[q];return U}function spliceOne($,I){for(;I+1<$.length;I++)$[I]=$[I+1];$.pop()}function unwrapListeners($){for(var I=new Array($.length),U=0;U<I.length;++U)I[U]=$[U].listener||$[U];return I}function once$2($,I){return new Promise(function(U,q){function G(Y){$.removeListener(I,K),q(Y)}function K(){typeof $.removeListener=="function"&&$.removeListener("error",G),U([].slice.call(arguments))}eventTargetAgnosticAddListener($,I,K,{once:!0}),I!=="error"&&addErrorHandlerIfEventEmitter($,G,{once:!0})})}function addErrorHandlerIfEventEmitter($,I,U){typeof $.on=="function"&&eventTargetAgnosticAddListener($,"error",I,U)}function eventTargetAgnosticAddListener($,I,U,q){if(typeof $.on=="function")q.once?$.once(I,U):$.on(I,U);else if(typeof $.addEventListener=="function")$.addEventListener(I,function G(K){q.once&&$.removeEventListener(I,G),U(K)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof $)}var eventsExports=events.exports,streamBrowser=eventsExports.EventEmitter,buffer={},base64Js={};base64Js.byteLength=byteLength,base64Js.toByteArray=toByteArray,base64Js.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i$2=0,len=code.length;i$2<len;++i$2)lookup[i$2]=code[i$2],revLookup[code.charCodeAt(i$2)]=i$2;revLookup[45]=62,revLookup[95]=63;function getLens($){var I=$.length;if(I%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var U=$.indexOf("=");U===-1&&(U=I);var q=U===I?0:4-U%4;return[U,q]}function byteLength($){var I=getLens($),U=I[0],q=I[1];return(U+q)*3/4-q}function _byteLength($,I,U){return(I+U)*3/4-U}function toByteArray($){var I,U=getLens($),q=U[0],G=U[1],K=new Arr(_byteLength($,q,G)),Y=0,J=G>0?q-4:q,X;for(X=0;X<J;X+=4)I=revLookup[$.charCodeAt(X)]<<18|revLookup[$.charCodeAt(X+1)]<<12|revLookup[$.charCodeAt(X+2)]<<6|revLookup[$.charCodeAt(X+3)],K[Y++]=I>>16&255,K[Y++]=I>>8&255,K[Y++]=I&255;return G===2&&(I=revLookup[$.charCodeAt(X)]<<2|revLookup[$.charCodeAt(X+1)]>>4,K[Y++]=I&255),G===1&&(I=revLookup[$.charCodeAt(X)]<<10|revLookup[$.charCodeAt(X+1)]<<4|revLookup[$.charCodeAt(X+2)]>>2,K[Y++]=I>>8&255,K[Y++]=I&255),K}function tripletToBase64($){return lookup[$>>18&63]+lookup[$>>12&63]+lookup[$>>6&63]+lookup[$&63]}function encodeChunk$1($,I,U){for(var q,G=[],K=I;K<U;K+=3)q=($[K]<<16&16711680)+($[K+1]<<8&65280)+($[K+2]&255),G.push(tripletToBase64(q));return G.join("")}function fromByteArray($){for(var I,U=$.length,q=U%3,G=[],K=16383,Y=0,J=U-q;Y<J;Y+=K)G.push(encodeChunk$1($,Y,Y+K>J?J:Y+K));return q===1?(I=$[U-1],G.push(lookup[I>>2]+lookup[I<<4&63]+"==")):q===2&&(I=($[U-2]<<8)+$[U-1],G.push(lookup[I>>10]+lookup[I>>4&63]+lookup[I<<2&63]+"=")),G.join("")}var ieee754={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ieee754.read=function($,I,U,q,G){var K,Y,J=G*8-q-1,X=(1<<J)-1,Z=X>>1,Q=-7,ee=U?G-1:0,te=U?-1:1,ne=$[I+ee];for(ee+=te,K=ne&(1<<-Q)-1,ne>>=-Q,Q+=J;Q>0;K=K*256+$[I+ee],ee+=te,Q-=8);for(Y=K&(1<<-Q)-1,K>>=-Q,Q+=q;Q>0;Y=Y*256+$[I+ee],ee+=te,Q-=8);if(K===0)K=1-Z;else{if(K===X)return Y?NaN:(ne?-1:1)*(1/0);Y=Y+Math.pow(2,q),K=K-Z}return(ne?-1:1)*Y*Math.pow(2,K-q)},ieee754.write=function($,I,U,q,G,K){var Y,J,X,Z=K*8-G-1,Q=(1<<Z)-1,ee=Q>>1,te=G===23?Math.pow(2,-24)-Math.pow(2,-77):0,ne=q?0:K-1,ie=q?1:-1,oe=I<0||I===0&&1/I<0?1:0;for(I=Math.abs(I),isNaN(I)||I===1/0?(J=isNaN(I)?1:0,Y=Q):(Y=Math.floor(Math.log(I)/Math.LN2),I*(X=Math.pow(2,-Y))<1&&(Y--,X*=2),Y+ee>=1?I+=te/X:I+=te*Math.pow(2,1-ee),I*X>=2&&(Y++,X/=2),Y+ee>=Q?(J=0,Y=Q):Y+ee>=1?(J=(I*X-1)*Math.pow(2,G),Y=Y+ee):(J=I*Math.pow(2,ee-1)*Math.pow(2,G),Y=0));G>=8;$[U+ne]=J&255,ne+=ie,J/=256,G-=8);for(Y=Y<<G|J,Z+=G;Z>0;$[U+ne]=Y&255,ne+=ie,Y/=256,Z-=8);$[U+ne-ie]|=oe*128};/*!
|
|
847
847
|
* The buffer module from node.js, for the browser.
|
|
848
848
|
*
|
|
849
849
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
@@ -920,7 +920,7 @@ ${(G=K.stack)==null?void 0:G.split(`
|
|
|
920
920
|
|
|
921
921
|
Error happened in the stream at:
|
|
922
922
|
${X.getStack()}`,Y(Q)):Y()};return this._outgoingRequests.set(q,new PendingRpcRequest(J,Z,!0)),this._sendMessage({request:{id:q,method:$,payload:I,stream:!0}}).catch(Q=>{Y(Q)}),()=>{this._sendMessage({streamClose:{id:q}}).catch(Q=>{log$2.catch(Q,void 0,{F:__dxlog_file$5,L:465,S:this,C:(ee,te)=>ee(...te)})})}})}async _sendMessage($,I){log$2("sending message",{type:Object.keys($)[0]},{F:__dxlog_file$5,L:472,S:this,C:(U,q)=>U(...q)}),await this._params.port.send(RpcMessage.encode($,{preserveAny:!0}),I)}async _callHandler($){try{invariant(typeof $.id=="number",void 0,{F:__dxlog_file$5,L:478,S:this,A:["typeof req.id === 'number'",""]}),invariant($.payload,void 0,{F:__dxlog_file$5,L:479,S:this,A:["req.payload",""]}),invariant($.method,void 0,{F:__dxlog_file$5,L:480,S:this,A:["req.method",""]});const I=await this._params.callHandler($.method,$.payload);return{id:$.id,payload:I}}catch(I){return{id:$.id,error:protocols.encodeError(I)}}}_callStreamHandler($,I){try{invariant(this._params.streamHandler,"Requests with streaming responses are not supported.",{F:__dxlog_file$5,L:497,S:this,A:["this._params.streamHandler","'Requests with streaming responses are not supported.'"]}),invariant(typeof $.id=="number",void 0,{F:__dxlog_file$5,L:498,S:this,A:["typeof req.id === 'number'",""]}),invariant($.payload,void 0,{F:__dxlog_file$5,L:499,S:this,A:["req.payload",""]}),invariant($.method,void 0,{F:__dxlog_file$5,L:500,S:this,A:["req.method",""]});const U=this._params.streamHandler($.method,$.payload);U.onReady(()=>{I({id:$.id,streamReady:!0})}),U.subscribe(q=>{I({id:$.id,payload:q})},q=>{I(q?{id:$.id,error:protocols.encodeError(q)}:{id:$.id,close:!0})}),this._localStreams.set($.id,U)}catch(U){I({id:$.id,error:protocols.encodeError(U)})}}};_ts_decorate$5([synchronized],RpcPeer.prototype,"open",null);var throwIfNotOpen=$=>{switch($){case"OPENED":return;case"INITIAL":throw new protocols.RpcNotOpenError;case"CLOSED":throw new protocols.RpcClosedError}},__dxlog_file2$4="/home/runner/work/dxos/dxos/packages/core/mesh/rpc/src/service.ts",ProtoRpcPeer=class{constructor($,I){this.rpc=$,this._peer=I}async open(){await this._peer.open()}async close(){await this._peer.close()}async abort(){await this._peer.abort()}},createProtoRpcPeer=({requested:$,exposed:I,handlers:U,encodingOptions:q,...G})=>{const K={};if(I){invariant(U,void 0,{F:__dxlog_file2$4,L:93,S:void 0,A:["handlers",""]});for(const X of Object.keys(I)){const Z=I[X].serviceProto.fullName.slice(1),Q=U[X];K[Z]=I[X].createServer(Q,q)}}const Y=new RpcPeer({...G,callHandler:(X,Z)=>{const[Q,ee]=parseMethodName(X);if(!K[Q])throw new Error(`Service not supported: ${Q}`);return K[Q].call(ee,Z)},streamHandler:(X,Z)=>{const[Q,ee]=parseMethodName(X);if(!K[Q])throw new Error(`Service not supported: ${Q}`);return K[Q].callStream(ee,Z)}}),J={};if($)for(const X of Object.keys($)){const Z=$[X].serviceProto.fullName.slice(1);J[X]=$[X].createClient({call:(Q,ee,te)=>Y.call(`${Z}.${Q}`,ee,te),callStream:(Q,ee,te)=>Y.callStream(`${Z}.${Q}`,ee,te)},q)}return new ProtoRpcPeer(J,Y)},parseMethodName=$=>{const I=$.lastIndexOf("."),U=$.slice(0,I),q=$.slice(I+1);if(U.length===0||q.length===0)throw new Error(`Invalid method: ${$}`);return[U,q]},createBundledRpcServer=({services:$,handlers:I,...U})=>{const q={};for(const G of Object.keys($)){const K=$[G].serviceProto.fullName.slice(1);q[K]=$[G].createServer(I[G])}return new RpcPeer({...U,callHandler:(G,K)=>{const[Y,J]=parseMethodName(G);if(!q[Y])throw new Error(`Service not supported: ${Y}`);return q[Y].call(J,K)},streamHandler:(G,K)=>{const[Y,J]=parseMethodName(G);if(!q[Y])throw new Error(`Service not supported: ${Y}`);return q[Y].callStream(J,K)}})};protocols.schema.getCodecForType("dxos.mesh.messaging.ReliablePayload"),protocols.schema.getCodecForType("dxos.mesh.messaging.Acknowledgement");var __dxlog_file2$3="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts",SIGNAL_KEEPALIVE_INTERVAL=1e4,SignalRPCClient=class{constructor({url:$,callbacks:I={}}){this._connectTrigger=new Trigger,this._closed=!1,this._closeComplete=new Trigger;const U=PublicKey.random().toHex();log$2.trace("dxos.mesh.signal-rpc-client.constructor",protocols.trace.begin({id:U}),{F:__dxlog_file2$3,L:55,S:this,C:(q,G)=>q(...G)}),this._url=$,this._callbacks=I,this._socket=new WebSocket2(this._url),this._rpc=createProtoRpcPeer({requested:{Signal:protocols.schema.getService("dxos.mesh.signal.Signal")},noHandshake:!0,port:{send:q=>{if(!this._closed)try{this._socket.send(q)}catch(G){log$2.warn("send error",G,{F:__dxlog_file2$3,L:74,S:this,C:(K,Y)=>K(...Y)})}},subscribe:q=>{this._socket.onmessage=async G=>{typeof Blob<"u"&&G.data instanceof Blob?q(export_Buffer.from(await G.data.arrayBuffer())):q(G.data)}}},encodingOptions:{preserveAny:!0}}),this._socket.onopen=async()=>{var q,G,K,Y;try{await this._rpc.open(),log$2(`RPC open ${this._url}`,void 0,{F:__dxlog_file2$3,L:95,S:this,C:(J,X)=>J(...X)}),(G=(q=this._callbacks).onConnected)==null||G.call(q),this._connectTrigger.wake(),this._keepaliveCtx=new Context,scheduleTaskInterval(this._keepaliveCtx,async()=>{var J;(J=this._socket)==null||J.send("__ping__")},SIGNAL_KEEPALIVE_INTERVAL)}catch(J){(Y=(K=this._callbacks).onError)==null||Y.call(K,J)}},this._socket.onclose=async()=>{var q,G;log$2(`Disconnected ${this._url}`,void 0,{F:__dxlog_file2$3,L:116,S:this,C:(K,Y)=>K(...Y)}),(G=(q=this._callbacks).onDisconnected)==null||G.call(q),this._closeComplete.wake(),await this.close()},this._socket.onerror=async q=>{var G,K,Y;if(!this._closed){(K=(G=this._callbacks).onError)==null||K.call(G,q.error??new Error(q.message)),this._connectTrigger.reset();try{await((Y=this._rpc)==null?void 0:Y.close())}catch(J){log$2.catch(J,void 0,{F:__dxlog_file2$3,L:134,S:this,C:(X,Z)=>X(...Z)})}this._closed=!0,log$2.warn(q.message??"Socket error",{url:this._url},{F:__dxlog_file2$3,L:138,S:this,C:(J,X)=>J(...X)})}},log$2.trace("dxos.mesh.signal-rpc-client.constructor",protocols.trace.end({id:U}),{F:__dxlog_file2$3,L:141,S:this,C:(q,G)=>q(...G)})}async close(){var $,I,U,q;await(($=this._keepaliveCtx)==null?void 0:$.dispose()),this._closed=!0;try{await((I=this._rpc)==null?void 0:I.close()),(((U=this._socket)==null?void 0:U.readyState)===WebSocket2.OPEN||((q=this._socket)==null?void 0:q.readyState)===WebSocket2.CONNECTING)&&this._socket.close(),await this._closeComplete.wait({timeout:1e3})}catch(G){log$2.warn("close error",G,{F:__dxlog_file2$3,L:156,S:this,C:(K,Y)=>K(...Y)})}}async join({topic:$,peerId:I}){var q,G;log$2("join",{topic:$,peerId:I},{F:__dxlog_file2$3,L:161,S:this,C:(K,Y)=>K(...Y)}),await this._connectTrigger.wait(),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$3,L:163,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$3,L:164,S:this,A:["this._rpc","'Rpc is not initialized'"]});const U=this._rpc.rpc.Signal.join({swarm:$.asUint8Array(),peer:I.asUint8Array(),metadata:(G=(q=this._callbacks)==null?void 0:q.getMetadata)==null?void 0:G.call(q)});return await U.waitUntilReady(),U}async receiveMessages($){log$2("receiveMessages",{peerId:$},{F:__dxlog_file2$3,L:175,S:this,C:(U,q)=>U(...q)}),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$3,L:176,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),await this._connectTrigger.wait(),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$3,L:178,S:this,A:["this._rpc","'Rpc is not initialized'"]});const I=this._rpc.rpc.Signal.receiveMessages({peer:$.asUint8Array()});return await I.waitUntilReady(),I}async sendMessage({author:$,recipient:I,payload:U}){var q,G;log$2("sendMessage",{author:$,recipient:I,payload:U},{F:__dxlog_file2$3,L:187,S:this,C:(K,Y)=>K(...Y)}),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$3,L:188,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),await this._connectTrigger.wait(),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$3,L:190,S:this,A:["this._rpc","'Rpc is not initialized'"]}),await this._rpc.rpc.Signal.sendMessage({author:$.asUint8Array(),recipient:I.asUint8Array(),payload:U,metadata:(G=(q=this._callbacks)==null?void 0:q.getMetadata)==null?void 0:G.call(q)})}},__dxlog_file3$3="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-client.ts",DEFAULT_RECONNECT_TIMEOUT=100,MAX_RECONNECT_TIMEOUT=5e3,ERROR_RECONCILE_DELAY=1e3,RECONCILE_INTERVAL=5e3,SignalClient=class{constructor($,I,U,q){if(this._host=$,this._onMessage=I,this._onSwarmEvent=U,this._getMetadata=q,this._state=SignalState.CLOSED,this._reconnectAfter=DEFAULT_RECONNECT_TIMEOUT,this._connectionStarted=new Date,this._lastStateChange=new Date,this._clientReady=new Trigger,this.statusChanged=new Event$1,this.commandTrace=new Event$1,this._swarmStreams=new ComplexMap(({topic:G,peerId:K})=>G.toHex()+K.toHex()),this._joinedTopics=new ComplexSet(({topic:G,peerId:K})=>G.toHex()+K.toHex()),this._messageStreams=new ComplexMap(G=>G.toHex()),this._subscribedMessages=new ComplexSet(({peerId:G})=>G.toHex()),this._reconciled=new Event$1,this._instanceId=PublicKey.random().toHex(),this._performance={sentMessages:0,receivedMessages:0,reconnectCounter:0,joinCounter:0,leaveCounter:0},!this._host.startsWith("wss://")&&!this._host.startsWith("ws://"))throw new Error(`Signal server requires a websocket URL. Provided: ${this._host}`)}open(){log$2.trace("dxos.mesh.signal-client.open",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file3$3,L:136,S:this,C:($,I)=>$(...I)}),![SignalState.CONNECTED,SignalState.CONNECTING].includes(this._state)&&(this._ctx=new Context({onError:$=>{var I;this._state===SignalState.CLOSED||(I=this._ctx)!=null&&I.disposed||(this._state===SignalState.CONNECTED&&log$2.warn("SignalClient error:",$,{F:__dxlog_file3$3,L:148,S:this,C:(U,q)=>U(...q)}),this._scheduleReconcileAfterError())}}),this._reconcileTask=new DeferredTask(this._ctx,async()=>{await this._reconcileSwarmSubscriptions(),await this._reconcileMessageSubscriptions(),this._reconciled.emit()}),scheduleTaskInterval(this._ctx,async()=>{this._state===SignalState.CONNECTED&&this._reconcileTask.schedule()},RECONCILE_INTERVAL),this._reconnectTask=new DeferredTask(this._ctx,async()=>{await this._reconnect()}),this._setState(SignalState.CONNECTING),this._createClient(),log$2.trace("dxos.mesh.signal-client.open",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file3$3,L:177,S:this,C:($,I)=>$(...I)}))}async close(){var $,I;log$2("closing...",void 0,{F:__dxlog_file3$3,L:181,S:this,C:(U,q)=>U(...q)}),![SignalState.CLOSED].includes(this._state)&&(await(($=this._ctx)==null?void 0:$.dispose()),this._clientReady.reset(),await((I=this._client)==null?void 0:I.close()),this._client=void 0,this._setState(SignalState.CLOSED),log$2("closed",void 0,{F:__dxlog_file3$3,L:192,S:this,C:(U,q)=>U(...q)}))}getStatus(){var $;return{host:this._host,state:this._state,error:($=this._lastError)==null?void 0:$.message,reconnectIn:this._reconnectAfter,connectionStarted:this._connectionStarted,lastStateChange:this._lastStateChange}}async join({topic:$,peerId:I}){log$2("joining",{topic:$,peerId:I},{F:__dxlog_file3$3,L:207,S:this,C:(U,q)=>U(...q)}),this._performance.joinCounter++,this._joinedTopics.add({topic:$,peerId:I}),this._reconcileTask.schedule()}async leave({topic:$,peerId:I}){var U;this._performance.leaveCounter++,log$2("leaving",{topic:$,peerId:I},{F:__dxlog_file3$3,L:215,S:this,C:(q,G)=>q(...G)}),(U=this._swarmStreams.get({topic:$,peerId:I}))==null||U.close(),this._swarmStreams.delete({topic:$,peerId:I}),this._joinedTopics.delete({topic:$,peerId:I})}async sendMessage($){this._performance.sentMessages++,await this._clientReady.wait(),invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$3,L:224,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]}),await this._client.sendMessage($)}async subscribeMessages($){log$2("subscribing to messages",{peerId:$},{F:__dxlog_file3$3,L:229,S:this,C:(I,U)=>I(...U)}),this._subscribedMessages.add({peerId:$}),this._reconcileTask.schedule()}async unsubscribeMessages($){var I;log$2("unsubscribing from messages",{peerId:$},{F:__dxlog_file3$3,L:235,S:this,C:(U,q)=>U(...q)}),this._subscribedMessages.delete({peerId:$}),(I=this._messageStreams.get($))==null||I.close(),this._messageStreams.delete($)}_scheduleReconcileAfterError(){scheduleTask(this._ctx,()=>{this._reconcileTask.schedule()},ERROR_RECONCILE_DELAY)}_setState($){this._state=$,this._lastStateChange=new Date,log$2("signal state changed",{status:this.getStatus()},{F:__dxlog_file3$3,L:254,S:this,C:(I,U)=>I(...U)}),this.statusChanged.emit(this.getStatus())}_createClient(){log$2("creating client",{host:this._host,state:this._state},{F:__dxlog_file3$3,L:259,S:this,C:($,I)=>$(...I)}),invariant(!this._client,"Client already created",{F:__dxlog_file3$3,L:260,S:this,A:["!this._client","'Client already created'"]}),this._connectionStarted=new Date,this._connectionCtx=this._ctx.derive(),this._connectionCtx.onDispose(async()=>{log$2("connection context disposed",void 0,{F:__dxlog_file3$3,L:267,S:this,C:($,I)=>$(...I)}),await Promise.all(Array.from(this._swarmStreams.values()).map($=>$.close())),await Promise.all(Array.from(this._messageStreams.values()).map($=>$.close())),this._swarmStreams.clear(),this._messageStreams.clear()});try{this._client=new SignalRPCClient({url:this._host,callbacks:{onConnected:()=>{log$2("socket connected",void 0,{F:__dxlog_file3$3,L:279,S:this,C:($,I)=>$(...I)}),this._lastError=void 0,this._reconnectAfter=DEFAULT_RECONNECT_TIMEOUT,this._setState(SignalState.CONNECTED),this._clientReady.wake(),this._reconcileTask.schedule()},onDisconnected:()=>{if(log$2("socket disconnected",{state:this._state},{F:__dxlog_file3$3,L:288,S:this,C:($,I)=>$(...I)}),this._state===SignalState.ERROR){this._setState(SignalState.DISCONNECTED);return}this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._setState(SignalState.DISCONNECTED),this._reconnectTask.schedule()},onError:$=>{log$2("socket error",{error:$,state:this._state},{F:__dxlog_file3$3,L:303,S:this,C:(I,U)=>I(...U)}),this._lastError=$,this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._setState(SignalState.ERROR),this._reconnectTask.schedule()},getMetadata:this._getMetadata}})}catch($){this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._lastError=$,this._setState(SignalState.DISCONNECTED),this._reconnectTask.schedule()}}_incrementReconnectTimeout(){this._reconnectAfter*=2,this._reconnectAfter=Math.min(this._reconnectAfter,MAX_RECONNECT_TIMEOUT)}async _reconnect(){var $,I;if(log$2(`reconnecting in ${this._reconnectAfter}ms`,{state:this._state},{F:__dxlog_file3$3,L:331,S:this,C:(U,q)=>U(...q)}),this._performance.reconnectCounter++,this._state===SignalState.RECONNECTING){log$2.warn("Signal api already reconnecting.",void 0,{F:__dxlog_file3$3,L:335,S:this,C:(U,q)=>U(...q)});return}this._state!==SignalState.CLOSED&&(this._clientReady.reset(),await(($=this._connectionCtx)==null?void 0:$.dispose()),(I=this._client)==null||I.close().catch(()=>{}),this._client=void 0,await cancelWithContext(this._ctx,sleep(this._reconnectAfter)),this._setState(SignalState.RECONNECTING),this._createClient())}async _reconcileSwarmSubscriptions(){var I;await asyncTimeout(cancelWithContext(this._connectionCtx,this._clientReady.wait()),5e3);const $=this._client;invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$3,L:360,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]});for(const{topic:U,peerId:q}of this._swarmStreams.keys())this._joinedTopics.has({topic:U,peerId:q})||((I=this._swarmStreams.get({topic:U,peerId:q}))==null||I.close(),this._swarmStreams.delete({topic:U,peerId:q}));for(const{topic:U,peerId:q}of this._joinedTopics.values()){if(this._swarmStreams.has({topic:U,peerId:q}))continue;const G=await asyncTimeout(cancelWithContext(this._connectionCtx,$.join({topic:U,peerId:q})),5e3);G.subscribe(async K=>{log$2("swarm event",{swarmEvent:K},{F:__dxlog_file3$3,L:387,S:this,C:(Y,J)=>Y(...J)}),await this._onSwarmEvent({topic:U,swarmEvent:K})}),this._swarmStreams.set({topic:U,peerId:q},G)}}async _reconcileMessageSubscriptions(){var I;await asyncTimeout(cancelWithContext(this._connectionCtx,this._clientReady.wait()),5e3);const $=this._client;invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$3,L:400,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]});for(const U of this._messageStreams.keys())this._subscribedMessages.has({peerId:U})||((I=this._messageStreams.get(U))==null||I.close(),this._messageStreams.delete(U));for(const{peerId:U}of this._subscribedMessages.values()){if(this._messageStreams.has(U))continue;const q=await asyncTimeout(cancelWithContext(this._connectionCtx,$.receiveMessages(U)),5e3);q.subscribe(async G=>{this._performance.receivedMessages++,await this._onMessage({author:PublicKey.from(G.author),recipient:PublicKey.from(G.recipient),payload:G.payload})}),this._messageStreams.set(U,q)}}};function _ts_decorate$4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$2="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/websocket-signal-manager.ts",MAX_SERVER_FAILURES=5,WSS_SIGNAL_SERVER_REBOOT_DELAY=3e3,WebsocketSignalManager=class{constructor($,I){this._hosts=$,this._getMetadata=I,this._servers=new Map,this._opened=!1,this.failureCount=new Map,this.statusChanged=new Event$1,this.commandTrace=new Event$1,this.swarmEvent=new Event$1,this.onMessage=new Event$1,this._instanceId=PublicKey.random().toHex(),log$2("Created WebsocketSignalManager",{hosts:this._hosts},{F:__dxlog_file5$2,L:49,S:this,C:(U,q)=>U(...q)});for(const U of this._hosts){if(this._servers.has(U.server))continue;const q=new SignalClient(U.server,async G=>this.onMessage.emit(G),async G=>this.swarmEvent.emit(G),this._getMetadata);q.statusChanged.on(()=>this.statusChanged.emit(this.getStatus())),this._servers.set(U.server,q),this.failureCount.set(U.server,0),q.commandTrace.on(G=>this.commandTrace.emit(G))}}async open(){this._opened||(log$2("open signal manager",{hosts:this._hosts},{F:__dxlog_file5$2,L:73,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.websocket-signal-manager.open",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file5$2,L:74,S:this,C:($,I)=>$(...I)}),this._initContext(),[...this._servers.values()].forEach($=>$.open()),this._opened=!0,log$2.trace("dxos.mesh.websocket-signal-manager.open",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file5$2,L:81,S:this,C:($,I)=>$(...I)}))}async close(){this._opened&&(this._opened=!1,await this._ctx.dispose(),await Promise.all(Array.from(this._servers.values()).map($=>$.close())))}async restartServer($){log$2("Restarting server",{serverName:$},{F:__dxlog_file5$2,L:97,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"server already closed",{F:__dxlog_file5$2,L:98,S:this,A:["this._opened","'server already closed'"]});const I=this._servers.get($);invariant(I,"server not found",{F:__dxlog_file5$2,L:101,S:this,A:["server","'server not found'"]}),await I.close(),await sleep(WSS_SIGNAL_SERVER_REBOOT_DELAY),await I.open()}getStatus(){return Array.from(this._servers.values()).map($=>$.getStatus())}async join({topic:$,peerId:I}){log$2("Join",{topic:$,peerId:I},{F:__dxlog_file5$2,L:114,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:115,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(U=>U.join({topic:$,peerId:I}))}async leave({topic:$,peerId:I}){log$2("leaving",{topic:$,peerId:I},{F:__dxlog_file5$2,L:121,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:122,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(U=>U.leave({topic:$,peerId:I}))}async sendMessage({author:$,recipient:I,payload:U}){log$2(`Signal ${I.truncate()}`,void 0,{F:__dxlog_file5$2,L:136,S:this,C:(q,G)=>q(...G)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:137,S:this,A:["this._opened","'Closed'"]}),this._forEachServer(async(q,G)=>{q.sendMessage({author:$,recipient:I,payload:U}).catch(K=>{K instanceof protocols.RateLimitExceededError?log$2.info("WSS rate limit exceeded",{err:K},{F:__dxlog_file5$2,L:142,S:this,C:(Y,J)=>Y(...J)}):K instanceof protocols.TimeoutError||K.constructor.name==="TimeoutError"?(log$2.info("WSS sendMessage timeout",{err:K},{F:__dxlog_file5$2,L:144,S:this,C:(Y,J)=>Y(...J)}),this.checkServerFailure(G)):(log$2.info(`error sending to ${G}`,{err:K},{F:__dxlog_file5$2,L:147,S:this,C:(Y,J)=>Y(...J)}),this.checkServerFailure(G))})})}async checkServerFailure($){const I=this.failureCount.get($)??0;if(I>MAX_SERVER_FAILURES){log$2.warn(`Too many failures sending to ${$} (${I} > ${MAX_SERVER_FAILURES}), restarting`,void 0,{F:__dxlog_file5$2,L:158,S:this,C:(U,q)=>U(...q)}),await this.restartServer($),this.failureCount.set($,0);return}this.failureCount.set($,(this.failureCount.get($)??0)+1)}async subscribeMessages($){log$2(`Subscribed for message stream peerId=${$}`,void 0,{F:__dxlog_file5$2,L:167,S:this,C:(I,U)=>I(...U)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:168,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(async I=>I.subscribeMessages($))}async unsubscribeMessages($){log$2(`Subscribed for message stream peerId=${$}`,void 0,{F:__dxlog_file5$2,L:174,S:this,C:(I,U)=>I(...U)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:175,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(async I=>I.unsubscribeMessages($))}_initContext(){this._ctx=new Context({onError:$=>log$2.catch($,void 0,{F:__dxlog_file5$2,L:182,S:this,C:(I,U)=>I(...U)})})}async _forEachServer($){return Promise.all(Array.from(this._servers.entries()).map(([I,U])=>$(U,I)))}};_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"open",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"close",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"join",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"leave",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"checkServerFailure",null);var __dxlog_file6="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/utils.ts",setIdentityTags=({identityService:$,devicesService:I,setTag:U})=>{$.queryIdentity().subscribe(q=>{var G;if(!((G=q==null?void 0:q.identity)!=null&&G.identityKey)){log$2("empty response from identity service",{idqr:q},{F:__dxlog_file6,L:21,S:void 0,C:(K,Y)=>K(...Y)});return}U("identityKey",q.identity.identityKey.truncate())}),I.queryDevices().subscribe(q=>{if(!q||!q.devices||q.devices.length===0){log$2("empty response from device service",{device:q},{F:__dxlog_file6,L:30,S:void 0,C:(K,Y)=>K(...Y)});return}invariant(q,"empty response from device service",{F:__dxlog_file6,L:33,S:void 0,A:["dqr","'empty response from device service'"]});const G=q.devices.find(K=>K.kind===DeviceKind.CURRENT);if(!G){log$2("no current device",{device:q},{F:__dxlog_file6,L:37,S:void 0,C:(K,Y)=>K(...Y)});return}U("deviceKey",G.deviceKey.truncate())})};function dist($,I){if($.length!==I.length)throw new Error("Inputs should have the same length");for(var U=Buffer.allocUnsafe($.length),q=0;q<$.length;q++)U[q]=$[q]^I[q];return U}dist.compare=function $(I,U){if(I.length!==U.length)throw new Error("Inputs should have the same length");for(var q=0;q<I.length;q++)if(I[q]!==U[q])return I[q]<U[q]?-1:1;return 0},dist.gt=function $(I,U){return dist.compare(I,U)===1},dist.lt=function $(I,U){return dist.compare(I,U)===-1},dist.eq=function $(I,U){return dist.compare(I,U)===0};var browser$2={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var $=1e3,I=$*60,U=I*60,q=U*24,G=q*7,K=q*365.25;ms=function(Q,ee){ee=ee||{};var te=typeof Q;if(te==="string"&&Q.length>0)return Y(Q);if(te==="number"&&isFinite(Q))return ee.long?X(Q):J(Q);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(Q))};function Y(Q){if(Q=String(Q),!(Q.length>100)){var ee=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(Q);if(ee){var te=parseFloat(ee[1]),ne=(ee[2]||"ms").toLowerCase();switch(ne){case"years":case"year":case"yrs":case"yr":case"y":return te*K;case"weeks":case"week":case"w":return te*G;case"days":case"day":case"d":return te*q;case"hours":case"hour":case"hrs":case"hr":case"h":return te*U;case"minutes":case"minute":case"mins":case"min":case"m":return te*I;case"seconds":case"second":case"secs":case"sec":case"s":return te*$;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return te;default:return}}}}function J(Q){var ee=Math.abs(Q);return ee>=q?Math.round(Q/q)+"d":ee>=U?Math.round(Q/U)+"h":ee>=I?Math.round(Q/I)+"m":ee>=$?Math.round(Q/$)+"s":Q+"ms"}function X(Q){var ee=Math.abs(Q);return ee>=q?Z(Q,ee,q,"day"):ee>=U?Z(Q,ee,U,"hour"):ee>=I?Z(Q,ee,I,"minute"):ee>=$?Z(Q,ee,$,"second"):Q+" ms"}function Z(Q,ee,te,ne){var ie=ee>=te*1.5;return Math.round(Q/te)+" "+ne+(ie?"s":"")}return ms}function setup($){U.debug=U,U.default=U,U.coerce=X,U.disable=K,U.enable=G,U.enabled=Y,U.humanize=requireMs(),U.destroy=Z,Object.keys($).forEach(Q=>{U[Q]=$[Q]}),U.names=[],U.skips=[],U.formatters={};function I(Q){let ee=0;for(let te=0;te<Q.length;te++)ee=(ee<<5)-ee+Q.charCodeAt(te),ee|=0;return U.colors[Math.abs(ee)%U.colors.length]}U.selectColor=I;function U(Q){let ee,te=null,ne,ie;function oe(...ce){if(!oe.enabled)return;const fe=oe,se=Number(new Date),de=se-(ee||se);fe.diff=de,fe.prev=ee,fe.curr=se,ee=se,ce[0]=U.coerce(ce[0]),typeof ce[0]!="string"&&ce.unshift("%O");let ue=0;ce[0]=ce[0].replace(/%([a-zA-Z%])/g,(ve,me)=>{if(ve==="%%")return"%";ue++;const be=U.formatters[me];if(typeof be=="function"){const _e=ce[ue];ve=be.call(fe,_e),ce.splice(ue,1),ue--}return ve}),U.formatArgs.call(fe,ce),(fe.log||U.log).apply(fe,ce)}return oe.namespace=Q,oe.useColors=U.useColors(),oe.color=U.selectColor(Q),oe.extend=q,oe.destroy=U.destroy,Object.defineProperty(oe,"enabled",{enumerable:!0,configurable:!1,get:()=>te!==null?te:(ne!==U.namespaces&&(ne=U.namespaces,ie=U.enabled(Q)),ie),set:ce=>{te=ce}}),typeof U.init=="function"&&U.init(oe),oe}function q(Q,ee){const te=U(this.namespace+(typeof ee>"u"?":":ee)+Q);return te.log=this.log,te}function G(Q){U.save(Q),U.namespaces=Q,U.names=[],U.skips=[];let ee;const te=(typeof Q=="string"?Q:"").split(/[\s,]+/),ne=te.length;for(ee=0;ee<ne;ee++)te[ee]&&(Q=te[ee].replace(/\*/g,".*?"),Q[0]==="-"?U.skips.push(new RegExp("^"+Q.slice(1)+"$")):U.names.push(new RegExp("^"+Q+"$")))}function K(){const Q=[...U.names.map(J),...U.skips.map(J).map(ee=>"-"+ee)].join(",");return U.enable(""),Q}function Y(Q){if(Q[Q.length-1]==="*")return!0;let ee,te;for(ee=0,te=U.skips.length;ee<te;ee++)if(U.skips[ee].test(Q))return!1;for(ee=0,te=U.names.length;ee<te;ee++)if(U.names[ee].test(Q))return!0;return!1}function J(Q){return Q.toString().substring(2,Q.toString().length-2).replace(/\.\*\?$/,"*")}function X(Q){return Q instanceof Error?Q.stack||Q.message:Q}function Z(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return U.enable(U.load()),U}var common=setup;(function($,I){I.formatArgs=q,I.save=G,I.load=K,I.useColors=U,I.storage=Y(),I.destroy=(()=>{let X=!1;return()=>{X||(X=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),I.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function U(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function q(X){if(X[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+X[0]+(this.useColors?"%c ":" ")+"+"+$.exports.humanize(this.diff),!this.useColors)return;const Z="color: "+this.color;X.splice(1,0,Z,"color: inherit");let Q=0,ee=0;X[0].replace(/%[a-zA-Z%]/g,te=>{te!=="%%"&&(Q++,te==="%c"&&(ee=Q))}),X.splice(ee,0,Z)}I.log=console.debug||console.log||(()=>{});function G(X){try{X?I.storage.setItem("debug",X):I.storage.removeItem("debug")}catch{}}function K(){let X;try{X=I.storage.getItem("debug")}catch{}return!X&&typeof process<"u"&&"env"in process&&(X=process.env.DEBUG),X}function Y(){try{return localStorage}catch{}}$.exports=common(I);const{formatters:J}=$.exports;J.j=function(X){try{return JSON.stringify(X)}catch(Z){return"[UnexpectedJSONParseError]: "+Z.message}}})(browser$2,browser$2.exports);var browserExports$1=browser$2.exports,getBrowserRtc=function $(){if(typeof globalThis>"u")return null;var I={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return I.RTCPeerConnection?I:null},browser$1={exports:{}},MAX_BYTES=65536,MAX_UINT32=4294967295;function oldBrowser(){throw new Error(`Secure random number generation is not supported by this browser.
|
|
923
|
-
Use Chrome, Firefox or Internet Explorer 11`)}var Buffer$2=requireSafeBuffer().Buffer,crypto=commonjsGlobal.crypto||commonjsGlobal.msCrypto;crypto&&crypto.getRandomValues?browser$1.exports=randomBytes:browser$1.exports=oldBrowser;function randomBytes($,I){if($>MAX_UINT32)throw new RangeError("requested too many random bytes");var U=Buffer$2.allocUnsafe($);if($>0)if($>MAX_BYTES)for(var q=0;q<$;q+=MAX_BYTES)crypto.getRandomValues(U.slice(q,q+MAX_BYTES));else crypto.getRandomValues(U);return typeof I=="function"?process.nextTick(function(){I(null,U)}):U}var browserExports=browser$1.exports;/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let promise;var queueMicrotask_1=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:commonjsGlobal):$=>(promise||(promise=Promise.resolve())).then($).catch(I=>setTimeout(()=>{throw I},0));function assign$3($,I){for(const U in I)Object.defineProperty($,U,{value:I[U],enumerable:!0,configurable:!0});return $}function createError($,I,U){if(!$||typeof $=="string")throw new TypeError("Please pass an Error to err-code");U||(U={}),typeof I=="object"&&(U=I,I=""),I&&(U.code=I);try{return assign$3($,U)}catch{U.message=$.message,U.stack=$.stack;const G=function(){};return G.prototype=Object.create(Object.getPrototypeOf($)),assign$3(new G,U)}}var errCode$1=createError;/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const debug=browserExports$1("simple-peer"),getBrowserRTC=getBrowserRtc,randombytes=browserExports,stream$1=readableBrowserExports,queueMicrotask$1=queueMicrotask_1,errCode=errCode$1,{Buffer:Buffer$1}=buffer,MAX_BUFFERED_AMOUNT$1=64*1024,ICECOMPLETE_TIMEOUT=5*1e3,CHANNEL_CLOSING_TIMEOUT=5*1e3;function filterTrickle($){return $.replace(/a=ice-options:trickle\s\n/g,"")}function warn$1($){console.warn($)}let Peer$1=class pr extends stream$1.Duplex{constructor(I){if(I=Object.assign({allowHalfOpen:!1},I),super(I),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",I),this.channelName=I.initiator?I.channelName||randombytes(20).toString("hex"):null,this.initiator=I.initiator||!1,this.channelConfig=I.channelConfig||pr.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},pr.config,I.config),this.offerOptions=I.offerOptions||{},this.answerOptions=I.answerOptions||{},this.sdpTransform=I.sdpTransform||(U=>U),this.streams=I.streams||(I.stream?[I.stream]:[]),this.trickle=I.trickle!==void 0?I.trickle:!0,this.allowHalfTrickle=I.allowHalfTrickle!==void 0?I.allowHalfTrickle:!1,this.iceCompleteTimeout=I.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=I.wrtc&&typeof I.wrtc=="object"?I.wrtc:getBrowserRTC(),!this._wrtc)throw errCode(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(U){this.destroy(errCode(U,"ERR_PC_CONSTRUCTOR"));return}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=U=>{this._onIceCandidate(U)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(U=>{this.destroy(errCode(U,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=U=>{this._setupData(U)},this.streams&&this.streams.forEach(U=>{this.addStream(U)}),this._pc.ontrack=U=>{this._onTrack(U)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof I=="string")try{I=JSON.parse(I)}catch{I={}}this._debug("signal()"),I.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),I.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(I.transceiverRequest.kind,I.transceiverRequest.init)),I.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(I.candidate):this._pendingCandidates.push(I.candidate)),I.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(I)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(U=>{this._addIceCandidate(U)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(U=>{this.destroy(errCode(U,"ERR_SET_REMOTE_DESCRIPTION"))}),!I.sdp&&!I.candidate&&!I.renegotiate&&!I.transceiverRequest&&this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(I){const U=new this._wrtc.RTCIceCandidate(I);this._pc.addIceCandidate(U).catch(q=>{!U.address||U.address.endsWith(".local")?warn$1("Ignoring unsupported ICE candidate."):this.destroy(errCode(q,"ERR_ADD_ICE_CANDIDATE"))})}send(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(I)}}addTransceiver(I,U){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(I,U),this._needsNegotiation()}catch(q){this.destroy(errCode(q,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:I,init:U}})}}addStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),I.getTracks().forEach(U=>{this.addTrack(U,I)})}}addTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const q=this._senderMap.get(I)||new Map;let G=q.get(U);if(!G)G=this._pc.addTrack(I,U),q.set(U,G),this._senderMap.set(I,q),this._needsNegotiation();else throw G.removed?errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(I,U,q){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const G=this._senderMap.get(I),K=G?G.get(q):null;if(!K)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");U&&this._senderMap.set(U,G),K.replaceTrack!=null?K.replaceTrack(U):this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const q=this._senderMap.get(I),G=q?q.get(U):null;if(!G)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{G.removed=!0,this._pc.removeTrack(G)}catch(K){K.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(G):this.destroy(errCode(K,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),I.getTracks().forEach(U=>{this.removeTrack(U,I)})}}_needsNegotiation(){this._debug("_needsNegotiation"),!this._batchedNegotiation&&(this._batchedNegotiation=!0,queueMicrotask$1(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(I){this._destroy(I,()=>{})}_destroy(I,U){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",I&&(I.message||I)),queueMicrotask$1(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",I&&(I.message||I)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,I&&this.emit("error",I),this.emit("close"),U()}))}_setupData(I){if(!I.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=I.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT$1),this.channelName=this._channel.label,this._channel.onmessage=q=>{this._onChannelMessage(q)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=q=>{const G=q.error instanceof Error?q.error:new Error(`Datachannel error: ${q.message} ${q.filename}:${q.lineno}:${q.colno}`);this.destroy(errCode(G,"ERR_DATA_CHANNEL"))};let U=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(U&&this._onChannelClose(),U=!0):U=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(I,U,q){if(this.destroyed)return q(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(I)}catch(G){return this.destroy(errCode(G,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=q):q(null)}else this._debug("write before connect"),this._chunk=I,this._cb=q}_onFinish(){if(this.destroyed)return;const I=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?I():this.once("connect",I)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp})},q=()=>{this._debug("createOffer success"),!this.destroyed&&(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(I=>{!I.mid&&I.sender.track&&!I.requested&&(I.requested=!0,this.addTransceiver(I.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp}),this.initiator||this._requestMissingTransceivers()},q=()=>{this.destroyed||(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const I=this._pc.iceConnectionState,U=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",I,U),this.emit("iceStateChange",I,U),(I==="connected"||I==="completed")&&(this._pcReady=!0,this._maybeReady()),I==="failed"&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),I==="closed"&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(I){const U=q=>(Object.prototype.toString.call(q.values)==="[object Array]"&&q.values.forEach(G=>{Object.assign(q,G)}),q);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(q=>{const G=[];q.forEach(K=>{G.push(U(K))}),I(null,G)},q=>I(q)):this._pc.getStats.length>0?this._pc.getStats(q=>{if(this.destroyed)return;const G=[];q.result().forEach(K=>{const Y={};K.names().forEach(J=>{Y[J]=K.stat(J)}),Y.id=K.id,Y.type=K.type,Y.timestamp=K.timestamp,G.push(U(Y))}),I(null,G)},q=>I(q)):I(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const I=()=>{this.destroyed||this.getStats((U,q)=>{if(this.destroyed)return;U&&(q=[]);const G={},K={},Y={};let J=!1;q.forEach(Z=>{(Z.type==="remotecandidate"||Z.type==="remote-candidate")&&(G[Z.id]=Z),(Z.type==="localcandidate"||Z.type==="local-candidate")&&(K[Z.id]=Z),(Z.type==="candidatepair"||Z.type==="candidate-pair")&&(Y[Z.id]=Z)});const X=Z=>{J=!0;let Q=K[Z.localCandidateId];Q&&(Q.ip||Q.address)?(this.localAddress=Q.ip||Q.address,this.localPort=Number(Q.port)):Q&&Q.ipAddress?(this.localAddress=Q.ipAddress,this.localPort=Number(Q.portNumber)):typeof Z.googLocalAddress=="string"&&(Q=Z.googLocalAddress.split(":"),this.localAddress=Q[0],this.localPort=Number(Q[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let ee=G[Z.remoteCandidateId];ee&&(ee.ip||ee.address)?(this.remoteAddress=ee.ip||ee.address,this.remotePort=Number(ee.port)):ee&&ee.ipAddress?(this.remoteAddress=ee.ipAddress,this.remotePort=Number(ee.portNumber)):typeof Z.googRemoteAddress=="string"&&(ee=Z.googRemoteAddress.split(":"),this.remoteAddress=ee[0],this.remotePort=Number(ee[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(q.forEach(Z=>{Z.type==="transport"&&Z.selectedCandidatePairId&&X(Y[Z.selectedCandidatePairId]),(Z.type==="googCandidatePair"&&Z.googActiveConnection==="true"||(Z.type==="candidatepair"||Z.type==="candidate-pair")&&Z.selected)&&X(Z)}),!J&&(!Object.keys(Y).length||Object.keys(K).length)){setTimeout(I,100);return}else this._connecting=!1,this._connected=!0;if(this._chunk){try{this.send(this._chunk)}catch(Q){return this.destroy(errCode(Q,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const Z=this._cb;this._cb=null,Z(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};I()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(I=>{this._pc.removeTrack(I),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(I){this.destroyed||(I.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:I.candidate.candidate,sdpMLineIndex:I.candidate.sdpMLineIndex,sdpMid:I.candidate.sdpMid}}):!I.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),I.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(I){if(this.destroyed)return;let U=I.data;U instanceof ArrayBuffer&&(U=Buffer$1.from(U)),this.push(U)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const I=this._cb;this._cb=null,I(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(I){this.destroyed||I.streams.forEach(U=>{this._debug("on track"),this.emit("track",I.track,U),this._remoteTracks.push({track:I.track,stream:U}),!this._remoteStreams.some(q=>q.id===U.id)&&(this._remoteStreams.push(U),queueMicrotask$1(()=>{this._debug("on stream"),this.emit("stream",U)}))})}_debug(){const I=[].slice.call(arguments);I[0]="["+this._id+"] "+I[0],debug.apply(null,I)}};Peer$1.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer$1.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer$1.channelConfig={};var ConnectionState$1;(function($){$[$.INVALID=0]="INVALID",$[$.CONNECTING=1]="CONNECTING",$[$.CONNECTED=2]="CONNECTED",$[$.CLOSED=3]="CLOSED"})(ConnectionState$1||(ConnectionState$1={}));var emitterComponent=Emitter$1;function Emitter$1($){if($)return mixin($)}function mixin($){for(var I in Emitter$1.prototype)$[I]=Emitter$1.prototype[I];return $}Emitter$1.prototype.on=Emitter$1.prototype.addEventListener=function($,I){return this._callbacks=this._callbacks||{},(this._callbacks[$]=this._callbacks[$]||[]).push(I),this},Emitter$1.prototype.once=function($,I){var U=this;this._callbacks=this._callbacks||{};function q(){U.off($,q),I.apply(this,arguments)}return q.fn=I,this.on($,q),this},Emitter$1.prototype.off=Emitter$1.prototype.removeListener=Emitter$1.prototype.removeAllListeners=Emitter$1.prototype.removeEventListener=function($,I){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var U=this._callbacks[$];if(!U)return this;if(arguments.length==1)return delete this._callbacks[$],this;for(var q,G=0;G<U.length;G++)if(q=U[G],q===I||q.fn===I){U.splice(G,1);break}return this},Emitter$1.prototype.emit=function($){this._callbacks=this._callbacks||{};var I=[].slice.call(arguments,1),U=this._callbacks[$];if(U){U=U.slice(0);for(var q=0,G=U.length;q<G;++q)U[q].apply(this,I)}return this},Emitter$1.prototype.listeners=function($){return this._callbacks=this._callbacks||{},this._callbacks[$]||[]},Emitter$1.prototype.hasListeners=function($){return!!this.listeners($).length};var Emitter=emitterComponent;function Stream(){Emitter.call(this)}Stream.prototype=new Emitter;var stream=Stream;Stream.Stream=Stream,Stream.prototype.pipe=function($,I){var U=this;function q(Q){$.writable&&$.write(Q)===!1&&U.pause&&U.pause()}U.on("data",q);function G(){U.readable&&U.resume&&U.resume()}$.on("drain",G),!$._isStdio&&(!I||I.end!==!1)&&(U.on("end",Y),U.on("close",J));var K=!1;function Y(){K||(K=!0,$.end())}function J(){K||(K=!0,typeof $.destroy=="function"&&$.destroy())}function X(Q){if(Z(),!this.hasListeners("error"))throw Q}U.on("error",X),$.on("error",X);function Z(){U.off("data",q),$.off("drain",G),U.off("end",Y),U.off("close",J),U.off("error",X),$.off("error",X),U.off("end",Z),U.off("close",Z),$.off("end",Z),$.off("close",Z)}return U.on("end",Z),U.on("close",Z),$.on("end",Z),$.on("close",Z),$.emit("pipe",U),$};var encode_1=encode,MSB$1=128,REST$1=127,MSBALL=~REST$1,INT=Math.pow(2,31);function encode($,I,U){if(Number.MAX_SAFE_INTEGER&&$>Number.MAX_SAFE_INTEGER)throw encode.bytes=0,new RangeError("Could not encode varint");I=I||[],U=U||0;for(var q=U;$>=INT;)I[U++]=$&255|MSB$1,$/=128;for(;$&MSBALL;)I[U++]=$&255|MSB$1,$>>>=7;return I[U]=$|0,encode.bytes=U-q+1,I}var decode=read,MSB=128,REST=127;function read($,q){var U=0,q=q||0,G=0,K=q,Y,J=$.length;do{if(K>=J||G>49)throw read.bytes=0,new RangeError("Could not decode varint");Y=$[K++],U+=G<28?(Y&REST)<<G:(Y&REST)*Math.pow(2,G),G+=7}while(Y>=MSB);return read.bytes=K-q,U}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function($){return $<N1?1:$<N2?2:$<N3?3:$<N4?4:$<N5?5:$<N6?6:$<N7?7:$<N8?8:$<N9?9:10},varint={encode:encode_1,decode,encodingLength:length},__dxlog_file$4="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/control-extension.ts",HEARTBEAT_RTT_WARN_THRESH=1e4,ControlExtension=class{constructor($,I,U){this.opts=$,this.localPeerId=I,this.remotePeerId=U,this._ctx=new Context({onError:q=>{this._extensionContext.close(q)}}),this.onExtensionRegistered=new Callback}async registerExtension($){await this._rpc.rpc.Control.registerExtension({name:$})}async onOpen($){this._extensionContext=$,this._rpc=createProtoRpcPeer({requested:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},exposed:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},handlers:{Control:{registerExtension:async I=>{this.onExtensionRegistered.call(I.name)},heartbeat:async I=>(log$2("received heartbeat request",{ts:I.requestTimestamp,localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:66,S:this,C:(U,q)=>U(...q)}),{requestTimestamp:I.requestTimestamp})}},port:await $.createPort("rpc",{contentType:'application/x-protobuf; messageType="dxos.rpc.Message"'}),timeout:this.opts.heartbeatTimeout}),await this._rpc.open(),scheduleTaskInterval(this._ctx,async()=>{const I=new Date;try{const U=await asyncTimeout(this._rpc.rpc.Control.heartbeat({requestTimestamp:I}),this.opts.heartbeatTimeout),q=Date.now();U.requestTimestamp instanceof Date&&(q-U.requestTimestamp.getTime()>(HEARTBEAT_RTT_WARN_THRESH<this.opts.heartbeatTimeout?HEARTBEAT_RTT_WARN_THRESH:this.opts.heartbeatTimeout/2)?log$2.warn(`heartbeat RTT for Teleport > ${HEARTBEAT_RTT_WARN_THRESH/1e3}s`,{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:103,S:this,C:(G,K)=>G(...K)}):log$2("heartbeat RTT",{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:109,S:this,C:(G,K)=>G(...K)}))}catch(U){const q=Date.now();if(U instanceof protocols.RpcClosedError){log$2("ignoring RpcClosedError in heartbeat",void 0,{F:__dxlog_file$4,L:119,S:this,C:(G,K)=>G(...K)});return}U instanceof TimeoutError?(log$2("timeout waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:123,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U)):(log$2.info("other error waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:126,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U))}},this.opts.heartbeatInterval)}async onClose($){await this._ctx.dispose(),await this._rpc.close()}async onAbort($){await this._ctx.dispose(),await this._rpc.abort()}},__dxlog_file2$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/framer.ts",FRAME_LENGTH_SIZE=2,Framer=class{constructor(){this._messageCb=void 0,this._subscribeCb=void 0,this._buffer=void 0,this._sendCallbacks=[],this._bytesSent=0,this._bytesReceived=0,this._writable=!0,this.drain=new Event$1,this._stream=new readableBrowserExports.Duplex({objectMode:!1,read:()=>{this._processResponseQueue()},write:($,I,U)=>{invariant(!this._subscribeCb,"Internal Framer bug. Concurrent writes detected.",{F:__dxlog_file2$2,L:40,S:this,A:["!this._subscribeCb","'Internal Framer bug. Concurrent writes detected.'"]}),this._bytesReceived+=$.length,this._buffer&&this._buffer.length>0?this._buffer=export_Buffer.concat([this._buffer,$]):this._buffer=$,this._messageCb?(this._popFrames(),U()):this._subscribeCb=()=>{this._popFrames(),this._subscribeCb=void 0,U()}}}),this.port={send:$=>new Promise(I=>{const U=encodeFrame($);this._bytesSent+=U.length,this._writable=this._stream.push(U),this._writable?I():this._sendCallbacks.push(I)}),subscribe:$=>{var I;return invariant(!this._messageCb,"Rpc port already has a message listener.",{F:__dxlog_file2$2,L:79,S:this,A:["!this._messageCb","'Rpc port already has a message listener.'"]}),this._messageCb=$,(I=this._subscribeCb)==null||I.call(this),()=>{this._messageCb=void 0}}}}get stream(){return this._stream}get bytesSent(){return this._bytesSent}get bytesReceived(){return this._bytesReceived}get writable(){return this._writable}_processResponseQueue(){const $=this._sendCallbacks;this._sendCallbacks=[],this._writable=!0,this.drain.emit(),$.forEach(I=>I())}_popFrames(){let $=0;for(;$<this._buffer.length;){const I=decodeFrame(this._buffer,$);if(!I)break;$+=I.bytesConsumed,this._messageCb(I.payload)}$<this._buffer.length?this._buffer=this._buffer.subarray($):this._buffer=void 0}destroy(){this._stream.readableLength>0&&log$2.info("framer destroyed while there are still read bytes in the buffer.",void 0,{F:__dxlog_file2$2,L:140,S:this,C:($,I)=>$(...I)}),this._stream.writableLength>0&&log$2.warn("framer destroyed while there are still write bytes in the buffer.",void 0,{F:__dxlog_file2$2,L:143,S:this,C:($,I)=>$(...I)}),this._stream.destroy()}},decodeFrame=($,I)=>{if($.length<I+FRAME_LENGTH_SIZE)return;const U=$.readUInt16BE(I),q=FRAME_LENGTH_SIZE+U;return $.length<I+q?void 0:{payload:$.subarray(I+FRAME_LENGTH_SIZE,I+q),bytesConsumed:q}},encodeFrame=$=>{const I=export_Buffer.allocUnsafe(FRAME_LENGTH_SIZE+$.length);return I.writeUInt16BE($.length,0),I.set($,FRAME_LENGTH_SIZE),I},__dxlog_file3$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/balancer.ts",MAX_CHUNK_SIZE=8192,Balancer=class{constructor($){this._sysChannelId=$,this._lastCallerIndex=0,this._channels=[],this._framer=new Framer,this._sendBuffers=new Map,this._receiveBuffers=new Map,this._sending=!1,this.incomingData=new Event$1,this.stream=this._framer.stream,this._channels.push($),this._framer.port.subscribe(this._processIncomingMessage.bind(this))}get bytesSent(){return this._framer.bytesSent}get bytesReceived(){return this._framer.bytesReceived}get buffersCount(){return this._sendBuffers.size}addChannel($){this._channels.push($)}pushData($,I,U){this._enqueueChunk($,I,U),this._sendChunks().catch(q=>log$2.catch(q,void 0,{F:__dxlog_file3$2,L:75,S:this,C:(G,K)=>G(...K)}))}destroy(){this._sendBuffers.size!==0&&log$2.info("destroying balancer with pending calls",void 0,{F:__dxlog_file3$2,L:80,S:this,C:($,I)=>$(...I)}),this._sendBuffers.clear(),this._framer.destroy()}_processIncomingMessage($){const{channelId:I,dataLength:U,chunk:q}=decodeChunk($,G=>!this._receiveBuffers.has(G));if(!this._receiveBuffers.has(I))q.length<U?this._receiveBuffers.set(I,{buffer:export_Buffer.from(q),msgLength:U}):this.incomingData.emit(q);else{const G=this._receiveBuffers.get(I);if(G.buffer=export_Buffer.concat([G.buffer,q]),G.buffer.length<G.msgLength)return;const K=G.buffer;this._receiveBuffers.delete(I),this.incomingData.emit(K)}}_getNextCallerId(){if(this._sendBuffers.has(this._sysChannelId))return this._sysChannelId;const $=this._lastCallerIndex;return this._lastCallerIndex=(this._lastCallerIndex+1)%this._channels.length,this._channels[$]}_enqueueChunk($,I,U){if(!this._channels.includes(U))throw new Error(`Unknown channel ${U}`);this._sendBuffers.has(U)||this._sendBuffers.set(U,[]);const q=this._sendBuffers.get(U),G=[];for(let K=0;K<$.length;K+=MAX_CHUNK_SIZE)G.push($.subarray(K,K+MAX_CHUNK_SIZE));G.forEach((K,Y)=>{const J=encodeChunk({chunk:K,channelId:U,dataLength:Y===0?$.length:void 0});q.push({msg:J,trigger:Y===G.length-1?I:void 0})})}_getNextChunk(){let $;for(;this._sendBuffers.size>0;){const I=this._getNextCallerId(),U=this._sendBuffers.get(I);if(U&&($=U.shift(),!!$))return U.length===0&&this._sendBuffers.delete(I),$}return null}async _sendChunks(){var I,U;if(this._sending)return;this._sending=!0;let $;for($=this._getNextChunk();$;){this._framer.writable||(log$2("PAUSE for drain",void 0,{F:__dxlog_file3$2,L:179,S:this,C:(q,G)=>q(...G)}),await this._framer.drain.waitForCount(1),log$2("RESUME for drain",void 0,{F:__dxlog_file3$2,L:181,S:this,C:(q,G)=>q(...G)}));try{await this._framer.port.send($.msg),(I=$.trigger)==null||I.wake()}catch(q){log$2("Error sending chunk",{err:q},{F:__dxlog_file3$2,L:187,S:this,C:(G,K)=>G(...K)}),(U=$.trigger)==null||U.throw(q)}$=this._getNextChunk()}invariant(this._sendBuffers.size===0,"sendBuffers not empty",{F:__dxlog_file3$2,L:192,S:this,A:["this._sendBuffers.size === 0","'sendBuffers not empty'"]}),this._sending=!1}},encodeChunk=({channelId:$,dataLength:I,chunk:U})=>{const q=varint.encodingLength($),G=I?varint.encodingLength(I):0,K=export_Buffer.allocUnsafe(q+G+U.length);return varint.encode($,K),I&&varint.encode(I,K,q),K.set(U,q+G),K},decodeChunk=($,I)=>{const U=varint.decode($);let q,G=varint.decode.bytes;I(U)&&(q=varint.decode($,G),G+=varint.decode.bytes);const K=$.subarray(G);return{channelId:U,dataLength:q,chunk:K}};function _ts_decorate$3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts",Command=protocols.schema.getCodecForType("dxos.mesh.muxer.Command"),DEFAULT_SEND_COMMAND_TIMEOUT=6e4,DESTROY_COMMAND_SEND_TIMEOUT=5e3,STATS_INTERVAL=1e3,MAX_SAFE_FRAME_SIZE=1e6,SYSTEM_CHANNEL_ID=0,GRACEFUL_CLOSE_TIMEOUT=3e3,Muxer=class{constructor(){this._balancer=new Balancer(SYSTEM_CHANNEL_ID),this._channelsByLocalId=new Map,this._channelsByTag=new Map,this._ctx=new Context,this._nextId=1,this._closing=!1,this._destroying=!1,this._disposed=!1,this._lastStats=void 0,this._lastChannelStats=new Map,this.afterClosed=new Event$1,this.statsUpdated=new Event$1,this.stream=this._balancer.stream,this._balancer.incomingData.on(async $=>{await this._handleCommand(Command.decode($))})}setSessionId($){this._sessionId=$}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}async createStream($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:151,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});const q=new readableBrowserExports.Duplex({write:(G,K,Y)=>{this._sendData(U,G).then(()=>Y()).catch(Y)},read:()=>{}});U.push=G=>{U.stats.bytesReceived+=G.length,q.push(G)},U.destroy=G=>{G&&q.listeners("error").length>0?q.destroy(G):q.destroy()};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(G){throw this._destroyChannel(U,G),G}return q}async createPort($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:211,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});let q=[],G;U.push=Y=>{U.stats.bytesReceived+=Y.length,G?G(Y):q.push(Y)};const K={send:async(Y,J)=>{await this._sendData(U,Y,J)},subscribe:Y=>{invariant(!G,"Only one subscriber is allowed",{F:__dxlog_file4$2,L:233,S:this,A:["!callback","'Only one subscriber is allowed'"]}),G=Y;for(const J of q)Y(J);q=[]}};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(Y){throw this._destroyChannel(U,Y),Y}return K}async close($){if(this._destroying){log$2("already destroying, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:266,S:this,C:(I,U)=>I(...U)});return}if(this._closing){log$2("already closing, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:270,S:this,C:(I,U)=>I(...U)});return}this._closing=!0,await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID,DESTROY_COMMAND_SEND_TIMEOUT).catch(async I=>{log$2("error sending close command",{err:I},{F:__dxlog_file4$2,L:285,S:this,C:(U,q)=>U(...q)}),await this._dispose(I)}),await asyncTimeout(this._dispose($),GRACEFUL_CLOSE_TIMEOUT,new protocols.TimeoutError("gracefully closing muxer"))}async destroy($){if(this._destroying){log$2("already destroying, ignoring destroy request",void 0,{F:__dxlog_file4$2,L:298,S:this,C:(I,U)=>I(...U)});return}this._destroying=!0,this._ctx.dispose(),this._closing?(log$2("destroy cancelling graceful close",void 0,{F:__dxlog_file4$2,L:304,S:this,C:(I,U)=>I(...U)}),this._closing=!1):await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID).catch(async I=>{log$2("error sending courtesy close command",{err:I},{F:__dxlog_file4$2,L:317,S:this,C:(U,q)=>U(...q)})}),this._dispose($).catch(I=>{log$2("error disposing after destroy",{err:I},{F:__dxlog_file4$2,L:322,S:this,C:(U,q)=>U(...q)})})}async _dispose($){var I;if(this._disposed){log$2("already destroyed, ignoring dispose request",void 0,{F:__dxlog_file4$2,L:330,S:this,C:(U,q)=>U(...q)});return}this._ctx.dispose(),await this._balancer.destroy();for(const U of this._channelsByTag.values())(I=U.destroy)==null||I.call(U,$);this._disposed=!0,await this._emitStats(),this.afterClosed.emit($),this._channelsByLocalId.clear(),this._channelsByTag.clear()}async _handleCommand($){if(this._disposed){log$2.warn("Received command after disposed",{cmd:$},{F:__dxlog_file4$2,L:353,S:this,C:(I,U)=>I(...U)});return}if($.close){this._closing?log$2("received close from peer, already closing",void 0,{F:__dxlog_file4$2,L:362,S:this,C:(I,U)=>I(...U)}):(log$2("received peer close, initiating my own graceful close",void 0,{F:__dxlog_file4$2,L:359,S:this,C:(I,U)=>I(...U)}),await this.close(new Error("received peer close")));return}if($.openChannel){const I=this._getOrCreateStream({tag:$.openChannel.tag,contentType:$.openChannel.contentType});I.remoteId=$.openChannel.id;for(const U of I.buffer)await this._sendCommand({data:{channelId:I.remoteId,data:U}},I.id);I.buffer=[]}else if($.data){const I=this._channelsByLocalId.get($.data.channelId)??failUndefined();if(!I.push){log$2.warn("Received data for channel before it was opened",{tag:I.tag},{F:__dxlog_file4$2,L:391,S:this,C:(U,q)=>U(...q)});return}I.push($.data.data)}}async _sendCommand($,I=-1,U=DEFAULT_SEND_COMMAND_TIMEOUT){if(this._disposed){log$2.info("ignoring sendCommand after disposed",{cmd:$},{F:__dxlog_file4$2,L:400,S:this,C:(q,G)=>q(...G)});return}try{const q=new Trigger;this._balancer.pushData(Command.encode($),q,I),await q.wait({timeout:U})}catch(q){await this.destroy(q)}}_getOrCreateStream($){this._channelsByTag.size===0&&scheduleTaskInterval(this._ctx,async()=>this._emitStats(),STATS_INTERVAL);let I=this._channelsByTag.get($.tag);return I||(I={id:this._nextId++,remoteId:null,tag:$.tag,contentType:$.contentType,buffer:[],push:null,destroy:null,stats:{bytesSent:0,bytesReceived:0}},this._channelsByTag.set(I.tag,I),this._channelsByLocalId.set(I.id,I),this._balancer.addChannel(I.id)),I}async _sendData($,I,U){if(I.length>MAX_SAFE_FRAME_SIZE&&log$2.warn("frame size exceeds maximum safe value",{size:I.length,threshold:MAX_SAFE_FRAME_SIZE},{F:__dxlog_file4$2,L:441,S:this,C:(q,G)=>q(...G)}),$.stats.bytesSent+=I.length,$.remoteId===null){$.buffer.push(I);return}await this._sendCommand({data:{channelId:$.remoteId,data:I}},$.id,U)}_destroyChannel($,I){$.destroy&&$.destroy(I),this._channelsByLocalId.delete($.id),this._channelsByTag.delete($.tag)}async _emitStats(){if(this._disposed||this._destroying){if(!this._lastStats)return;const K=this._lastStats;this._lastStats=void 0,K.readBufferSize=0,K.writeBufferSize=0;for(const Y of K.channels)Y.writeBufferSize=0;this.statsUpdated.emit(K),this._lastChannelStats.clear();return}const $=this._balancer.bytesSent,I=this._balancer.bytesReceived,U=Date.now(),q=this._lastStats?(U-this._lastStats.timestamp)/1e3:0,G=(K,Y)=>Y?{bytesSentRate:q?(K.bytesSent-Y.bytesSent)/q:void 0,bytesReceivedRate:q?(K.bytesReceived-Y.bytesReceived)/q:void 0}:{};this._lastStats={timestamp:U,channels:Array.from(this._channelsByTag.values()).map(K=>{const Y={id:K.id,tag:K.tag,contentType:K.contentType,writeBufferSize:K.buffer.length,bytesSent:K.stats.bytesSent,bytesReceived:K.stats.bytesReceived,...G(K.stats,this._lastChannelStats.get(K.id))};return this._lastChannelStats.set(K.id,Y),Y}),bytesSent:$,bytesReceived:I,...G({bytesSent:$,bytesReceived:I},this._lastStats),readBufferSize:this._balancer.stream.readableLength,writeBufferSize:this._balancer.stream.writableLength},this.statsUpdated.emit(this._lastStats)}};_ts_decorate$3([logInfo],Muxer.prototype,"sessionIdString",null);function _ts_decorate2$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$1="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/teleport.ts",CONTROL_HEARTBEAT_INTERVAL=1e4,CONTROL_HEARTBEAT_TIMEOUT=6e4,Teleport=class{constructor({initiator:$,localPeerId:I,remotePeerId:U}){this._ctx=new Context({onError:q=>{this.destroy(q).catch(()=>{log$2.error("Error during destroy",q,{F:__dxlog_file5$1,L:39,S:this,C:(G,K)=>G(...K)})})}}),this._muxer=new Muxer,this._extensions=new Map,this._remoteExtensions=new Set,this._open=!1,this._destroying=!1,this._aborting=!1,invariant(typeof $=="boolean",void 0,{F:__dxlog_file5$1,L:56,S:this,A:["typeof initiator === 'boolean'",""]}),invariant(PublicKey.isPublicKey(I),void 0,{F:__dxlog_file5$1,L:57,S:this,A:["PublicKey.isPublicKey(localPeerId)",""]}),invariant(PublicKey.isPublicKey(U),void 0,{F:__dxlog_file5$1,L:58,S:this,A:["PublicKey.isPublicKey(remotePeerId)",""]}),this.initiator=$,this.localPeerId=I,this.remotePeerId=U,this._control=new ControlExtension({heartbeatInterval:CONTROL_HEARTBEAT_INTERVAL,heartbeatTimeout:CONTROL_HEARTBEAT_TIMEOUT,onTimeout:()=>{this._destroying||this._aborting||(log$2.info("abort teleport due to onTimeout in ControlExtension",void 0,{F:__dxlog_file5$1,L:71,S:this,C:(q,G)=>q(...G)}),this.abort(new protocols.TimeoutError("control extension")).catch(q=>log$2.catch(q,void 0,{F:__dxlog_file5$1,L:72,S:this,C:(G,K)=>G(...K)})))}},this.localPeerId,this.remotePeerId),this._control.onExtensionRegistered.set(async q=>{if(log$2("remote extension",{name:q},{F:__dxlog_file5$1,L:80,S:this,C:(G,K)=>G(...K)}),invariant(!this._remoteExtensions.has(q),"Remote extension already exists",{F:__dxlog_file5$1,L:81,S:this,A:["!this._remoteExtensions.has(name)","'Remote extension already exists'"]}),this._remoteExtensions.add(q),this._extensions.has(q))try{await this._openExtension(q)}catch(G){await this.destroy(G)}}),this._muxer.stream.on("close",async()=>{if(this._destroying||this._aborting){log$2("destroy teleport due to muxer stream close, skipping due to already destroying/aborting",void 0,{F:__dxlog_file5$1,L:97,S:this,C:(q,G)=>q(...G)});return}await this.destroy()}),this._muxer.stream.on("error",async q=>{await this.destroy(q)}),this._muxer.statsUpdated.on(q=>{log$2.trace("dxos.mesh.teleport.stats",{localPeerId:I,remotePeerId:U,bytesSent:q.bytesSent,bytesSentRate:q.bytesSentRate,bytesReceived:q.bytesReceived,bytesReceivedRate:q.bytesReceivedRate,channels:q.channels},{F:__dxlog_file5$1,L:110,S:this,C:(G,K)=>G(...K)})})}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}get stream(){return this._muxer.stream}get stats(){return this._muxer.statsUpdated}async open($=PublicKey.random()){this._sessionId=$,log$2("open",void 0,{F:__dxlog_file5$1,L:144,S:this,C:(I,U)=>I(...U)}),this._setExtension("dxos.mesh.teleport.control",this._control),await this._openExtension("dxos.mesh.teleport.control"),this._open=!0,this._muxer.setSessionId($)}async close($){await this.destroy($)}async abort($){if(!(this._aborting||this._destroying)&&(this._aborting=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onAbort($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:173,S:this,C:(q,G)=>q(...G)})}await this._muxer.destroy($)}}async destroy($){if(!(this._destroying||this._aborting)&&(this._destroying=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onClose($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:197,S:this,C:(q,G)=>q(...G)})}await this._muxer.close()}}addExtension($,I){if(!this._open)throw new Error("Not open");log$2("addExtension",{name:$},{F:__dxlog_file5$1,L:209,S:this,C:(U,q)=>U(...q)}),this._setExtension($,I),scheduleTask(this._ctx,async()=>{try{await this._control.registerExtension($)}catch(U){if(U instanceof protocols.RpcClosedError)return;throw U}}),this._remoteExtensions.has($)&&scheduleTask(this._ctx,async()=>{await this._openExtension($)})}_setExtension($,I){invariant(!$.includes("/"),"Invalid extension name",{F:__dxlog_file5$1,L:233,S:this,A:["!extensionName.includes('/')","'Invalid extension name'"]}),invariant(!this._extensions.has($),"Extension already exists",{F:__dxlog_file5$1,L:234,S:this,A:["!this._extensions.has(extensionName)","'Extension already exists'"]}),this._extensions.set($,I)}async _openExtension($){log$2("open extension",{extensionName:$},{F:__dxlog_file5$1,L:239,S:this,C:(q,G)=>q(...G)});const I=this._extensions.get($)??failUndefined(),U={initiator:this.initiator,localPeerId:this.localPeerId,remotePeerId:this.remotePeerId,createPort:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:247,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createPort(`${$}/${q}`,G)),createStream:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:251,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createStream(`${$}/${q}`,G)),close:q=>{runInContextAsync(this._ctx,async()=>{await this.close(q)})}};await I.onOpen(U),log$2("extension opened",{extensionName:$},{F:__dxlog_file5$1,L:262,S:this,C:(q,G)=>q(...G)})}};_ts_decorate2$2([logInfo],Teleport.prototype,"sessionIdString",null),_ts_decorate2$2([synchronized],Teleport.prototype,"abort",null),_ts_decorate2$2([synchronized],Teleport.prototype,"destroy",null);var __require=($=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy($,{get:(I,U)=>(typeof require<"u"?require:I)[U]}):$)(function($){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')});function _ts_decorate$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$3="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection.ts",STARTING_SIGNALLING_DELAY=10,TRANSPORT_CONNECTION_TIMEOUT=1e4,TRANSPORT_STATS_INTERVAL=5e3,MAX_SIGNALLING_DELAY=300,ConnectionState;(function($){$.CREATED="CREATED",$.INITIAL="INITIAL",$.CONNECTING="CONNECTING",$.CONNECTED="CONNECTED",$.CLOSING="CLOSING",$.CLOSED="CLOSED",$.ABORTING="ABORTING",$.ABORTED="ABORTED"})(ConnectionState||(ConnectionState={}));var Connection=class{constructor($,I,U,q,G,K,Y,J,X){this.topic=$,this.ownId=I,this.remoteId=U,this.sessionId=q,this.initiator=G,this._signalMessaging=K,this._protocol=Y,this._transportFactory=J,this._callbacks=X,this._ctx=new Context,this.connectedTimeoutContext=new Context,this._state="CREATED",this._incomingSignalBuffer=[],this._outgoingSignalBuffer=[],this.stateChanged=new Event$1,this.errors=new ErrorStream,this._instanceId=PublicKey.random().toHex(),this.transportStats=new Event$1,this._signalSendTask=new DeferredTask(this._ctx,async()=>{await this._flushSignalBuffer()}),this._signallingDelay=STARTING_SIGNALLING_DELAY,log$2.trace("dxos.mesh.connection.construct",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:134,S:this,C:(Z,Q)=>Z(...Q)})}get sessionIdString(){return this.sessionId.truncate()}get state(){return this._state}get transport(){return this._transport}get protocol(){return this._protocol}async openConnection(){invariant(this._state==="INITIAL","Invalid state.",{F:__dxlog_file$3,L:164,S:this,A:["this._state === ConnectionState.INITIAL","'Invalid state.'"]}),log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file$3,L:165,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.connection.open",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:166,S:this,C:($,I)=>$(...I)}),this._changeState("CONNECTING"),this._protocol.open(this.sessionId).catch($=>{this.errors.raise($)}),this._protocol.stream.on("close",()=>{log$2("protocol stream closed",void 0,{F:__dxlog_file$3,L:183,S:this,C:($,I)=>$(...I)}),this.close(new protocols.ProtocolError("protocol stream closed")).catch($=>this.errors.raise($))}),scheduleTask(this.connectedTimeoutContext,async()=>{log$2.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect, aborting`,void 0,{F:__dxlog_file$3,L:190,S:this,C:($,I)=>$(...I)}),await this.abort(new protocols.TimeoutError(`${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect`)).catch($=>this.errors.raise($))},TRANSPORT_CONNECTION_TIMEOUT),invariant(!this._transport,void 0,{F:__dxlog_file$3,L:198,S:this,A:["!this._transport",""]}),this._transport=this._transportFactory.createTransport({initiator:this.initiator,stream:this._protocol.stream,sendSignal:async $=>this._sendSignal($),sessionId:this.sessionId}),await this._transport.open(),this._transport.connected.once(async()=>{var $,I;this._changeState("CONNECTED"),await this.connectedTimeoutContext.dispose(),(I=($=this._callbacks)==null?void 0:$.onConnected)==null||I.call($),scheduleTaskInterval(this._ctx,async()=>this._emitTransportStats(),TRANSPORT_STATS_INTERVAL)}),this._transport.closed.once(()=>{this._transport=void 0,log$2("abort triggered by transport close",void 0,{F:__dxlog_file$3,L:218,S:this,C:($,I)=>$(...I)}),this.abort().catch($=>this.errors.raise($))}),this._transport.errors.handle(async $=>{log$2("transport error:",{err:$},{F:__dxlog_file$3,L:223,S:this,C:(I,U)=>I(...U)}),this.closeReason||(this.closeReason=$==null?void 0:$.message),$ instanceof protocols.ConnectionResetError?(log$2.info("aborting due to transport ConnectionResetError",void 0,{F:__dxlog_file$3,L:230,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.ConnectivityError?(log$2.info("aborting due to transport ConnectivityError",void 0,{F:__dxlog_file$3,L:233,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.UnknownProtocolError&&log$2.warn("unsure what to do with UnknownProtocolError, will keep on truckin",{err:$},{F:__dxlog_file$3,L:236,S:this,C:(I,U)=>I(...U)}),this._state!=="CLOSED"&&this._state!=="CLOSING"&&(await this.connectedTimeoutContext.dispose(),this.errors.raise($))});for(const $ of this._incomingSignalBuffer)this._transport.onSignal($);this._incomingSignalBuffer=[],log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file$3,L:252,S:this,C:($,I)=>$(...I)})}async abort($){var I,U,q;if(log$2("aborting...",{err:$},{F:__dxlog_file$3,L:259,S:this,C:(G,K)=>G(...K)}),this._state==="CLOSED"||this._state==="ABORTED"){log$2(`abort ignored: already ${this._state}`,this.closeReason,{F:__dxlog_file$3,L:261,S:this,C:(G,K)=>G(...K)});return}await this.connectedTimeoutContext.dispose(),this._changeState("ABORTING"),this.closeReason||(this.closeReason=$==null?void 0:$.message),await this._ctx.dispose();try{log$2("aborting protocol... ",void 0,{F:__dxlog_file$3,L:275,S:this,C:(G,K)=>G(...K)}),await this._protocol.abort()}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:278,S:this,C:(K,Y)=>K(...Y)})}try{await((I=this._transport)==null?void 0:I.close())}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:285,S:this,C:(K,Y)=>K(...Y)})}try{(q=(U=this._callbacks)==null?void 0:U.onClosed)==null||q.call(U,$)}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:291,S:this,C:(K,Y)=>K(...Y)})}this._changeState("ABORTED")}async close($){var U,q,G,K;if(this.closeReason?this.closeReason+=`; ${$==null?void 0:$.message}`:this.closeReason=$==null?void 0:$.message,this._state==="CLOSED"||this._state==="ABORTING"||this._state==="ABORTED")return;const I=this._state;if(this._changeState("CLOSING"),await this.connectedTimeoutContext.dispose(),await this._ctx.dispose(),log$2("closing...",{peerId:this.ownId},{F:__dxlog_file$3,L:316,S:this,C:(Y,J)=>Y(...J)}),I==="CONNECTED"){try{await this._protocol.close()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:323,S:this,C:(J,X)=>J(...X)})}try{await((U=this._transport)==null?void 0:U.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:330,S:this,C:(J,X)=>J(...X)})}}else{log$2.info(`graceful close requested when we were in ${I} state? aborting`,void 0,{F:__dxlog_file$3,L:333,S:this,C:(Y,J)=>Y(...J)});try{await this._protocol.abort()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:337,S:this,C:(J,X)=>J(...X)})}try{await((q=this._transport)==null?void 0:q.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:342,S:this,C:(J,X)=>J(...X)})}}log$2("closed",{peerId:this.ownId},{F:__dxlog_file$3,L:346,S:this,C:(Y,J)=>Y(...J)}),this._changeState("CLOSED"),(K=(G=this._callbacks)==null?void 0:G.onClosed)==null||K.call(G,$)}_sendSignal($){this._outgoingSignalBuffer.push($),this._signalSendTask.schedule()}async _flushSignalBuffer(){var $;if(this._outgoingSignalBuffer.length!==0)try{await cancelWithContext(this._ctx,sleep(this._signallingDelay)),this._signallingDelay=Math.min(this._signallingDelay*2,MAX_SIGNALLING_DELAY);const I=[...this._outgoingSignalBuffer];this._outgoingSignalBuffer.length=0,await this._signalMessaging.signal({author:this.ownId,recipient:this.remoteId,sessionId:this.sessionId,topic:this.topic,data:{signalBatch:{signals:I}}})}catch(I){if(I instanceof protocols.CancelledError||I instanceof Error&&(($=I.message)!=null&&$.includes("CANCELLED")))return;log$2.info("signal message failed to deliver",{err:I},{F:__dxlog_file$3,L:384,S:this,C:(U,q)=>U(...q)}),await this.close(new protocols.ConnectivityError("signal message failed to deliver",I))}}async signal($){var U,q;if(invariant($.sessionId,void 0,{F:__dxlog_file$3,L:393,S:this,A:["msg.sessionId",""]}),!$.sessionId.equals(this.sessionId)){log$2("dropping signal for incorrect session id",void 0,{F:__dxlog_file$3,L:395,S:this,C:(G,K)=>G(...K)});return}invariant($.data.signal||$.data.signalBatch,void 0,{F:__dxlog_file$3,L:398,S:this,A:["msg.data.signal || msg.data.signalBatch",""]}),invariant((U=$.author)==null?void 0:U.equals(this.remoteId),void 0,{F:__dxlog_file$3,L:399,S:this,A:["msg.author?.equals(this.remoteId)",""]}),invariant((q=$.recipient)==null?void 0:q.equals(this.ownId),void 0,{F:__dxlog_file$3,L:400,S:this,A:["msg.recipient?.equals(this.ownId)",""]});const I=$.data.signalBatch?$.data.signalBatch.signals??[]:[$.data.signal];for(const G of I)G&&(["CREATED","INITIAL"].includes(this.state)?(log$2("buffered signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:409,S:this,C:(K,Y)=>K(...Y)}),this._incomingSignalBuffer.push(G)):(invariant(this._transport,"Connection not ready to accept signals.",{F:__dxlog_file$3,L:412,S:this,A:["this._transport","'Connection not ready to accept signals.'"]}),log$2("received signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:413,S:this,C:(K,Y)=>K(...Y)}),await this._transport.onSignal(G)))}initiate(){this._changeState("INITIAL")}_changeState($){log$2("stateChanged",{from:this._state,to:$,peerId:this.ownId},{F:__dxlog_file$3,L:424,S:this,C:(I,U)=>I(...U)}),invariant($!==this._state,"Already in this state.",{F:__dxlog_file$3,L:425,S:this,A:["state !== this._state","'Already in this state.'"]}),this._state=$,this.stateChanged.emit($)}async _emitTransportStats(){var I;const $=await((I=this.transport)==null?void 0:I.getStats());$&&this.transportStats.emit($)}};_ts_decorate$2([logInfo],Connection.prototype,"sessionIdString",null),_ts_decorate$2([synchronized],Connection.prototype,"abort",null),_ts_decorate$2([synchronized],Connection.prototype,"close",null);var __dxlog_file2$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts",SwarmMessage=protocols.schema.getCodecForType("dxos.mesh.swarm.SwarmMessage"),SwarmMessenger=class{constructor({sendMessage:$,onSignal:I,onOffer:U,topic:q}){this._ctx=new Context,this._offerRecords=new ComplexMap(G=>G.toHex()),this._sendMessage=$,this._onSignal=I,this._onOffer=U,this._topic=q}async receiveMessage({author:$,recipient:I,payload:U}){var G,K,Y,J;if(U.type_url!=="dxos.mesh.swarm.SwarmMessage")return;const q=SwarmMessage.decode(U.value);this._topic.equals(q.topic)&&(log$2("received",{from:$,to:I,msg:q},{F:__dxlog_file2$1,L:69,S:this,C:(X,Z)=>X(...Z)}),(G=q.data)!=null&&G.offer?await this._handleOffer({author:$,recipient:I,message:q}):(K=q.data)!=null&&K.answer?await this._resolveAnswers(q):(Y=q.data)!=null&&Y.signal?await this._handleSignal({author:$,recipient:I,message:q}):(J=q.data)!=null&&J.signalBatch?await this._handleSignal({author:$,recipient:I,message:q}):log$2.warn("unknown message",{message:q},{F:__dxlog_file2$1,L:80,S:this,C:(X,Z)=>X(...Z)}))}async signal($){var I,U;invariant(((I=$.data)==null?void 0:I.signal)||((U=$.data)==null?void 0:U.signalBatch),"Invalid message",{F:__dxlog_file2$1,L:85,S:this,A:["message.data?.signal || message.data?.signalBatch","'Invalid message'"]}),await this._sendReliableMessage({author:$.author,recipient:$.recipient,message:$})}async offer($){const I={...$,messageId:PublicKey.random()};return new Promise((U,q)=>{this._offerRecords.set(I.messageId,{resolve:U}),this._sendReliableMessage({author:$.author,recipient:$.recipient,message:I}).catch(G=>q(G))})}async _sendReliableMessage({author:$,recipient:I,message:U}){const q={...U,messageId:U.messageId??PublicKey.random()};log$2("sending",{from:$,to:I,msg:q},{F:__dxlog_file2$1,L:123,S:this,C:(G,K)=>G(...K)}),await this._sendMessage({author:$,recipient:I,payload:{type_url:"dxos.mesh.swarm.SwarmMessage",value:SwarmMessage.encode(q)}})}async _resolveAnswers($){var U,q,G;invariant((q=(U=$.data)==null?void 0:U.answer)==null?void 0:q.offerMessageId,"No offerMessageId",{F:__dxlog_file2$1,L:135,S:this,A:["message.data?.answer?.offerMessageId","'No offerMessageId'"]});const I=this._offerRecords.get($.data.answer.offerMessageId);I&&(this._offerRecords.delete($.data.answer.offerMessageId),invariant((G=$.data)==null?void 0:G.answer,"No answer",{F:__dxlog_file2$1,L:139,S:this,A:["message.data?.answer","'No answer'"]}),log$2("resolving",{answer:$.data.answer},{F:__dxlog_file2$1,L:140,S:this,C:(K,Y)=>K(...Y)}),I.resolve($.data.answer))}async _handleOffer({author:$,recipient:I,message:U}){invariant(U.data.offer,"No offer",{F:__dxlog_file2$1,L:154,S:this,A:["message.data.offer","'No offer'"]});const q={author:$,recipient:I,...U,data:{offer:U.data.offer}},G=await this._onOffer(q);G.offerMessageId=U.messageId;try{await this._sendReliableMessage({author:I,recipient:$,message:{topic:U.topic,sessionId:U.sessionId,data:{answer:G}}})}catch(K){K instanceof protocols.TimeoutError?log$2.info("timeout sending answer to offer",{err:K},{F:__dxlog_file2$1,L:175,S:this,C:(Y,J)=>Y(...J)}):log$2.info("error sending answer to offer",{err:K},{F:__dxlog_file2$1,L:177,S:this,C:(Y,J)=>Y(...J)})}}async _handleSignal({author:$,recipient:I,message:U}){invariant(U.messageId,void 0,{F:__dxlog_file2$1,L:191,S:this,A:["message.messageId",""]}),invariant(U.data.signal||U.data.signalBatch,"Invalid message",{F:__dxlog_file2$1,L:192,S:this,A:["message.data.signal || message.data.signalBatch","'Invalid message'"]});const q={author:$,recipient:I,...U,data:{signal:U.data.signal,signalBatch:U.data.signalBatch}};await this._onSignal(q)}};function _ts_decorate2$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file3$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts",ConnectionDisplacedError=class extends protocols.SystemError{constructor(){super("Connection displaced by remote initiator.")}},CONNECTION_COUNTS_STABLE_AFTER=5e3,Peer=class{constructor($,I,U,q,G,K,Y,J){this.id=$,this.topic=I,this.localPeerId=U,this._signalMessaging=q,this._protocolProvider=G,this._transportFactory=K,this._connectionLimiter=Y,this._callbacks=J,this._availableAfter=0,this.availableToConnect=!0,this._ctx=new Context,this.advertizing=!1,this.initiating=!1,this.connectionDisplaced=new Event$1}async onOffer($){var U;const I=$.author;if(this.connection&&![ConnectionState.CREATED,ConnectionState.INITIAL,ConnectionState.CONNECTING].includes(this.connection.state))return log$2.info(`received offer when connection already in ${this.connection.state} state`,void 0,{F:__dxlog_file3$1,L:114,S:this,C:(q,G)=>q(...G)}),{accept:!1};if(this.connection||this.initiating)if(I.toHex()<this.localPeerId.toHex())log$2("close local connection",{localPeerId:this.id,topic:this.topic,remotePeerId:this.localPeerId,sessionId:(U=this.connection)==null?void 0:U.sessionId},{F:__dxlog_file3$1,L:123,S:this,C:(q,G)=>q(...G)}),this.connection&&await this.closeConnection(new ConnectionDisplacedError);else return{accept:!1};if(await this._callbacks.onOffer(I)&&!this.connection){invariant($.sessionId,void 0,{F:__dxlog_file3$1,L:143,S:this,A:["message.sessionId",""]});const q=this._createConnection(!1,$.sessionId);try{await this._connectionLimiter.connecting($.sessionId),q.initiate(),await q.openConnection()}catch(G){G instanceof protocols.CancelledError||log$2.info("connection error",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,err:G},{F:__dxlog_file3$1,L:153,S:this,C:(K,Y)=>K(...Y)}),await this.closeConnection(G)}return{accept:!0}}return{accept:!1}}async initiateConnection(){invariant(!this.initiating,"Initiation in progress.",{F:__dxlog_file3$1,L:170,S:this,A:["!this.initiating","'Initiation in progress.'"]}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3$1,L:171,S:this,A:["!this.connection","'Already connected.'"]});const $=PublicKey.random();log$2("initiating...",{id:this.id,topic:this.topic,peerId:this.id,sessionId:$},{F:__dxlog_file3$1,L:173,S:this,C:(q,G)=>q(...G)});const I=this._createConnection(!0,$);this.initiating=!0;let U;try{if(await this._connectionLimiter.connecting($),I.initiate(),U=await this._signalMessaging.offer({author:this.localPeerId,recipient:this.id,sessionId:$,topic:this.topic,data:{offer:{}}}),log$2("received",{answer:U,topic:this.topic,ownId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:190,S:this,C:(q,G)=>q(...G)}),I.state!==ConnectionState.INITIAL){log$2("ignoring response",void 0,{F:__dxlog_file3$1,L:192,S:this,C:(q,G)=>q(...G)});return}}catch(q){throw log$2("initiation error: send offer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:196,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{if(!U.accept){this._callbacks.onRejected();return}}catch(q){throw log$2("initiation error: accept answer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:209,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{log$2("opening connection as initiator",void 0,{F:__dxlog_file3$1,L:222,S:this,C:(q,G)=>q(...G)}),await I.openConnection(),this._callbacks.onAccepted()}catch(q){throw log$2("initiation error: open connection",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:226,S:this,C:(G,K)=>G(...K)}),log$2.warn("closing connection due to unhandled error on openConnection",{err:q},{F:__dxlog_file3$1,L:233,S:this,C:(G,K)=>G(...K)}),await this.closeConnection(q),q}finally{this.initiating=!1}}_createConnection($,I){var q;log$2("creating connection",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,sessionId:I},{F:__dxlog_file3$1,L:247,S:this,C:(G,K)=>G(...K)}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3$1,L:254,S:this,A:["!this.connection","'Already connected.'"]});const U=new Connection(this.topic,this.localPeerId,this.id,I,$,this._signalMessaging,this._protocolProvider({initiator:$,localPeerId:this.localPeerId,remotePeerId:this.id,topic:this.topic}),this._transportFactory,{onConnected:()=>{this.availableToConnect=!0,this._lastConnectionTime=Date.now(),this._callbacks.onConnected(),this._connectionLimiter.doneConnecting(I),log$2.trace("dxos.mesh.connection.connected",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3$1,L:273,S:this,C:(G,K)=>G(...K)})},onClosed:G=>{log$2("connection closed",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$},{F:__dxlog_file3$1,L:282,S:this,C:(K,Y)=>K(...Y)}),this._connectionLimiter.doneConnecting(I),invariant(this.connection===U,"Connection mismatch (race condition).",{F:__dxlog_file3$1,L:287,S:this,A:["this.connection === connection","'Connection mismatch (race condition).'"]}),log$2.trace("dxos.mesh.connection.closed",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3$1,L:289,S:this,C:(K,Y)=>K(...Y)}),G instanceof ConnectionDisplacedError?this.connectionDisplaced.emit(this.connection):(this._lastConnectionTime&&this._lastConnectionTime+CONNECTION_COUNTS_STABLE_AFTER<Date.now()?this._availableAfter=0:(this.availableToConnect=!1,this._availableAfter=increaseInterval(this._availableAfter)),this._callbacks.onDisconnected(),scheduleTask(this._connectionCtx,()=>{this.availableToConnect=!0,this._callbacks.onPeerAvailable()},this._availableAfter)),this.connection=void 0}});return this._callbacks.onInitiated(U),(q=this._connectionCtx)==null||q.dispose(),this._connectionCtx=this._ctx.derive(),U.errors.handle(G=>{log$2.info("connection error, closing",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,err:G},{F:__dxlog_file3$1,L:329,S:this,C:(K,Y)=>K(...Y)}),log$2.trace("dxos.mesh.connection.error",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$,err:G},{F:__dxlog_file3$1,L:336,S:this,C:(K,Y)=>K(...Y)}),this.closeConnection(G)}),this.connection=U,U}async closeConnection($){if(!this.connection)return;const I=this.connection;log$2("closing...",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3$1,L:361,S:this,C:(U,q)=>U(...q)}),await I.close($),log$2("closed",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3$1,L:367,S:this,C:(U,q)=>U(...q)})}async onSignal($){if(!this.connection){log$2("dropping signal message for non-existent connection",{message:$},{F:__dxlog_file3$1,L:372,S:this,C:(I,U)=>I(...U)});return}await this.connection.signal($)}async destroy($){var I;await this._ctx.dispose(),log$2("Destroying peer",{peerId:this.id,topic:this.topic},{F:__dxlog_file3$1,L:382,S:this,C:(U,q)=>U(...q)}),await((I=this==null?void 0:this.connection)==null?void 0:I.close($))}};_ts_decorate2$1([synchronized],Peer.prototype,"destroy",null);var increaseInterval=$=>$===0?50:$<500?500:$<1e3?1e3:$<5e3?5e3:1e4;function _ts_decorate3$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts",INITIATION_DELAY=100,getClassName=$=>Object.getPrototypeOf($).constructor.name,Swarm=class{constructor($,I,U,q,G,K,Y,J,X=INITIATION_DELAY){this._topic=$,this._ownPeerId=I,this._topology=U,this._protocolProvider=q,this._messenger=G,this._transportFactory=K,this._label=Y,this._connectionLimiter=J,this._initiationDelay=X,this._ctx=new Context,this._listeningHandle=void 0,this._peers=new ComplexMap(PublicKey.hash),this._instanceId=PublicKey.random().toHex(),this.connectionAdded=new Event$1,this.disconnected=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.begin({id:this._instanceId,data:{topic:this._topic.toHex(),peerId:this._ownPeerId.toHex()}}),{F:__dxlog_file4$1,L:89,S:this,C:(Z,Q)=>Z(...Q)}),log$2("creating swarm",{peerId:I},{F:__dxlog_file4$1,L:93,S:this,C:(Z,Q)=>Z(...Q)}),U.init(this._getSwarmController()),this._swarmMessenger=new SwarmMessenger({sendMessage:async Z=>await this._messenger.sendMessage(Z),onSignal:async Z=>await this.onSignal(Z),onOffer:async Z=>await this.onOffer(Z),topic:this._topic}),log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file4$1,L:102,S:this,C:(Z,Q)=>Z(...Q)})}get connections(){return Array.from(this._peers.values()).map($=>$.connection).filter(isNotNullOrUndefined)}get ownPeerId(){return this._ownPeerId}get label(){return this._label}get topic(){return this._topic}async open(){invariant(!this._listeningHandle,void 0,{F:__dxlog_file4$1,L:129,S:this,A:["!this._listeningHandle",""]}),this._listeningHandle=await this._messenger.listen({peerId:this._ownPeerId,payloadType:"dxos.mesh.swarm.SwarmMessage",onMessage:async $=>{await this._swarmMessenger.receiveMessage($).catch(I=>log$2.info("Error while receiving message",{err:I},{F:__dxlog_file4$1,L:137,S:this,C:(U,q)=>U(...q)}))}})}async destroy(){var $;log$2("destroying...",void 0,{F:__dxlog_file4$1,L:143,S:this,C:(I,U)=>I(...U)}),await(($=this._listeningHandle)==null?void 0:$.unsubscribe()),this._listeningHandle=void 0,await this._ctx.dispose(),await this._topology.destroy(),await Promise.all(Array.from(this._peers.keys()).map(I=>this._destroyPeer(I,"swarm destroyed"))),log$2("destroyed",void 0,{F:__dxlog_file4$1,L:150,S:this,C:(I,U)=>I(...U)})}async setTopology($){invariant(!this._ctx.disposed,"Swarm is offline",{F:__dxlog_file4$1,L:154,S:this,A:["!this._ctx.disposed","'Swarm is offline'"]}),$!==this._topology&&(log$2("setting topology",{previous:getClassName(this._topology),topology:getClassName($)},{F:__dxlog_file4$1,L:158,S:this,C:(I,U)=>I(...U)}),await this._topology.destroy(),this._topology=$,this._topology.init(this._getSwarmController()),this._topology.update())}onSwarmEvent($){var I;if(log$2("swarm event",{swarmEvent:$},{F:__dxlog_file4$1,L:171,S:this,C:(U,q)=>U(...q)}),this._ctx.disposed){log$2("swarm event ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:174,S:this,C:(U,q)=>U(...q)});return}if($.peerAvailable){const U=PublicKey.from($.peerAvailable.peer);if(log$2("new peer",{peerId:U},{F:__dxlog_file4$1,L:180,S:this,C:(q,G)=>q(...G)}),!U.equals(this._ownPeerId)){const q=this._getOrCreatePeer(U);q.advertizing=!0}}else if($.peerLeft){const U=this._peers.get(PublicKey.from($.peerLeft.peer));U?(U.advertizing=!1,((I=U.connection)==null?void 0:I.state)!==ConnectionState.CONNECTED&&this._destroyPeer(U.id,"peer left").catch(q=>log$2.catch(q,void 0,{F:__dxlog_file4$1,L:191,S:this,C:(G,K)=>G(...K)}))):log$2("received peerLeft but no peer found",{peer:$.peerLeft.peer},{F:__dxlog_file4$1,L:194,S:this,C:(q,G)=>q(...G)})}this._topology.update()}async onOffer($){var q,G;if(log$2("offer",{message:$},{F:__dxlog_file4$1,L:203,S:this,C:(K,Y)=>K(...Y)}),this._ctx.disposed)return log$2("ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:205,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(invariant($.author,void 0,{F:__dxlog_file4$1,L:210,S:this,A:["message.author",""]}),!((q=$.recipient)!=null&&q.equals(this._ownPeerId)))return log$2("rejecting offer with incorrect peerId",{message:$},{F:__dxlog_file4$1,L:212,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(!((G=$.topic)!=null&&G.equals(this._topic)))return log$2("rejecting offer with incorrect topic",{message:$},{F:__dxlog_file4$1,L:216,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};const U=await this._getOrCreatePeer($.author).onOffer($);return this._topology.update(),U}async onSignal($){var U,q;if(log$2("signal",{message:$},{F:__dxlog_file4$1,L:227,S:this,C:(G,K)=>G(...K)}),this._ctx.disposed){log$2.info("ignored for offline swarm",void 0,{F:__dxlog_file4$1,L:229,S:this,C:(G,K)=>G(...K)});return}invariant((U=$.recipient)==null?void 0:U.equals(this._ownPeerId),`Invalid signal peer id expected=${this.ownPeerId}, actual=${$.recipient}`,{F:__dxlog_file4$1,L:232,S:this,A:["message.recipient?.equals(this._ownPeerId)","`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"]}),invariant((q=$.topic)==null?void 0:q.equals(this._topic),void 0,{F:__dxlog_file4$1,L:236,S:this,A:["message.topic?.equals(this._topic)",""]}),invariant($.author,void 0,{F:__dxlog_file4$1,L:237,S:this,A:["message.author",""]}),await this._getOrCreatePeer($.author).onSignal($)}async goOffline(){await this._ctx.dispose(),await Promise.all([...this._peers.keys()].map($=>this._destroyPeer($,"goOffline")))}async goOnline(){this._ctx=new Context}_getOrCreatePeer($){let I=this._peers.get($);return I||(I=new Peer($,this._topic,this._ownPeerId,this._swarmMessenger,this._protocolProvider,this._transportFactory,this._connectionLimiter,{onInitiated:U=>{this.connectionAdded.emit(U)},onConnected:()=>{this.connected.emit($)},onDisconnected:async()=>{I.advertizing||await this._destroyPeer(I.id,"peer disconnected"),this.disconnected.emit($),this._topology.update()},onRejected:()=>{this._peers.has($)&&(log$2("peer rejected connection",{peerId:$},{F:__dxlog_file4$1,L:286,S:this,C:(U,q)=>U(...q)}),this._destroyPeer($,"peer rejected connection"))},onAccepted:()=>{this._topology.update()},onOffer:U=>this._topology.onOffer(U),onPeerAvailable:()=>{this._topology.update()}}),this._peers.set($,I)),I}async _destroyPeer($,I){invariant(this._peers.has($),void 0,{F:__dxlog_file4$1,L:308,S:this,A:["this._peers.has(peerId)",""]}),await this._peers.get($).destroy(new Error(I)),this._peers.delete($)}_getSwarmController(){return{getState:()=>({ownPeerId:this._ownPeerId,connected:Array.from(this._peers.values()).filter($=>$.connection).map($=>$.id),candidates:Array.from(this._peers.values()).filter($=>!$.connection&&$.advertizing&&$.availableToConnect).map($=>$.id)}),connect:$=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{try{await this._initiateConnection($)}catch(I){log$2("initiation error",I,{F:__dxlog_file4$1,L:334,S:this,C:(U,q)=>U(...q)})}})},disconnect:async $=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{await this._closeConnection($),this._topology.update()})}}}async _initiateConnection($){const I=this._ctx;if($.toHex()<this._ownPeerId.toHex()&&(log$2("initiation delay",{remoteId:$},{F:__dxlog_file4$1,L:361,S:this,C:(q,G)=>q(...G)}),await sleep(this._initiationDelay)),I.disposed)return;const U=this._getOrCreatePeer($);U.connection||(log$2("initiating connection...",{remoteId:$},{F:__dxlog_file4$1,L:375,S:this,C:(q,G)=>q(...G)}),await U.initiateConnection(),this._topology.update(),log$2("initiated",{remoteId:$},{F:__dxlog_file4$1,L:378,S:this,C:(q,G)=>q(...G)}))}async _closeConnection($){const I=this._peers.get($);I&&await I.closeConnection()}};_ts_decorate3$1([logInfo],Swarm.prototype,"_instanceId",void 0),_ts_decorate3$1([logInfo],Swarm.prototype,"ownPeerId",null),_ts_decorate3$1([logInfo],Swarm.prototype,"topic",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onSwarmEvent",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onOffer",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOffline",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOnline",null);var EventType;(function($){$.CONNECTION_STATE_CHANGED="CONNECTION_STATE_CHANGED",$.PROTOCOL_ERROR="PROTOCOL_ERROR",$.PROTOCOL_EXTENSIONS_INITIALIZED="PROTOCOL_EXTENSIONS_INITIALIZED",$.PROTOCOL_EXTENSIONS_HANDSHAKE="PROTOCOL_EXTENSIONS_HANDSHAKE",$.PROTOCOL_HANDSHAKE="PROTOCOL_HANDSHAKE"})(EventType||(EventType={}));function _ts_decorate4$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file11="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts",MEMORY_TRANSPORT_DELAY=1,createStreamDelay=$=>new readableBrowserExports.Transform({objectMode:!0,transform:(I,U,q)=>{setTimeout(()=>q(null,I),$)}}),MemoryTransport=(Zn=class{constructor(I){this._options=I,this._instanceId=PublicKey.random(),this._remote=new Trigger,this._outgoingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._incomingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._closed=!1,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,invariant(!Zn._connections.has(this._instanceId),"Duplicate memory connection",{F:__dxlog_file11,L:64,S:this,A:["!MemoryTransport._connections.has(this._instanceId)","'Duplicate memory connection'"]}),Zn._connections.set(this._instanceId,this)}get isOpen(){return!this._closed}async open(){if(log$2("opening...",void 0,{F:__dxlog_file11,L:74,S:this,C:(I,U)=>I(...U)}),this._options.initiator){log$2("sending signal",void 0,{F:__dxlog_file11,L:78,S:this,C:(I,U)=>I(...U)});try{await this._options.sendSignal({payload:{transportId:this._instanceId.toHex()}})}catch(I){this._closed||this.errors.raise(toError(I))}}else this._remote.wait({timeout:this._options.timeout??1e3}).then(I=>{if(!this._closed){if(this._remoteInstanceId=I,this._remoteConnection=Zn._connections.get(this._remoteInstanceId),!this._remoteConnection){this._closed=!0,this.closed.emit();return}invariant(!this._remoteConnection._remoteConnection,`Remote already connected: ${this._remoteInstanceId}`,{F:__dxlog_file11,L:104,S:this,A:["!this._remoteConnection._remoteConnection","`Remote already connected: ${this._remoteInstanceId}`"]}),this._remoteConnection._remoteConnection=this,this._remoteConnection._remoteInstanceId=this._instanceId,log$2("connected",void 0,{F:__dxlog_file11,L:108,S:this,C:(U,q)=>U(...q)}),this._options.stream.pipe(this._outgoingDelay).pipe(this._remoteConnection._options.stream).pipe(this._incomingDelay).pipe(this._options.stream),this.connected.emit(),this._remoteConnection.connected.emit()}}).catch(I=>{this._closed||this.errors.raise(I)})}async close(){log$2("closing...",void 0,{F:__dxlog_file11,L:129,S:this,C:(I,U)=>I(...U)}),this._closed=!0,Zn._connections.delete(this._instanceId),this._remoteConnection&&(this._remoteConnection._closed=!0,Zn._connections.delete(this._remoteInstanceId),this._options.stream.unpipe(this._incomingDelay),this._incomingDelay.unpipe(this._remoteConnection._options.stream),this._remoteConnection._options.stream.unpipe(this._outgoingDelay),this._outgoingDelay.unpipe(this._options.stream),this._options.stream.unpipe(this._outgoingDelay),this._remoteConnection.closed.emit(),this._remoteConnection._remoteConnection=void 0,this._remoteConnection=void 0),this.closed.emit(),log$2("closed",void 0,{F:__dxlog_file11,L:157,S:this,C:(I,U)=>I(...U)})}async onSignal({payload:I}){if(log$2("received signal",{payload:I},{F:__dxlog_file11,L:161,S:this,C:(q,G)=>q(...G)}),!(I!=null&&I.transportId))return;const U=I.transportId;if(U){const q=PublicKey.fromHex(U);this._remote.wake(q)}}async getDetails(){return this._instanceId.toHex()}async getStats(){return{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0}}},Zn._connections=new ComplexMap(PublicKey.hash),Zn);_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_instanceId",void 0),_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_remoteInstanceId",void 0);var toError=$=>$ instanceof Error?$:new Error(String($)),TransportKind;(function($){$.SIMPLE_PEER="SIMPLE_PEER",$.SIMPLE_PEER_PROXY="SIMPLE_PEER_PROXY",$.LIBDATACHANNEL="LIBDATACHANNEL",$.MEMORY="MEMORY",$.TCP="TCP"})(TransportKind||(TransportKind={}));var wrtc=null;try{wrtc=__require("@koush/wrtc")}catch{}function _ts_decorate5$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file15="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts",DATACHANNEL_LABEL="dxos.mesh.transport",MAX_BUFFERED_AMOUNT=64*1024,MAX_MESSAGE_SIZE=64*1024,LibDataChannelTransport=(rr=class{constructor(I){this._options=I,this._closed=!1,this._connected=!1,this._writeCallback=null,this._readyForCandidates=new Trigger,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream}get isOpen(){return!!this._peer&&!this._closed}async open(){this._closed&&this.errors.raise(new Error("connection already closed"));const{RTCPeerConnection:I}=(await importESM("node-datachannel/polyfill")).default;this._options.webrtcConfig?this._options.webrtcConfig.iceServers=this._options.webrtcConfig.iceServers??[]:this._options.webrtcConfig={iceServers:[]},this._peer=new I(this._options.webrtcConfig),this._peer.onicecandidateerror=U=>{log$2.error("peer.onicecandidateerror",{event:U},{F:__dxlog_file15,L:77,S:this,C:(q,G)=>q(...G)})},this._peer.onconnectionstatechange=U=>{var q;log$2.debug("peer.onconnectionstatechange",{event:U,peerConnectionState:(q=this._peer)==null?void 0:q.connectionState,transportConnectionState:this._connected},{F:__dxlog_file15,L:81,S:this,C:(G,K)=>G(...K)})},this._peer.onicecandidate=async U=>{if(log$2.debug("peer.onicecandidate",{event:U},{F:__dxlog_file15,L:91,S:this,C:(q,G)=>q(...G)}),U.candidate)try{await this._options.sendSignal({payload:{data:{type:"candidate",candidate:{candidate:U.candidate.candidate,sdpMLineIndex:U.candidate.sdpMLineIndex??0,sdpMid:U.candidate.sdpMid??0}}}})}catch(q){log$2.info("signaling error",{err:q},{F:__dxlog_file15,L:108,S:this,C:(G,K)=>G(...K)})}},this._options.initiator?(invariant(this._peer,"not open",{F:__dxlog_file15,L:114,S:this,A:["this._peer","'not open'"]}),this._peer.createOffer().then(async U=>{var q;this._closed||(((q=this._peer)==null?void 0:q.connectionState)!=="connecting"&&(log$2.error("peer not connecting",{peer:this._peer},{F:__dxlog_file15,L:125,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"))),log$2.debug("creating offer",{peer:this._peer,offer:U},{F:__dxlog_file15,L:129,S:this,C:(G,K)=>G(...K)}),await this._peer.setLocalDescription(U),await this._options.sendSignal({payload:{data:{type:U.type,sdp:U.sdp}}}))}).catch(U=>{this.errors.raise(U)}),this._handleChannel(this._peer.createDataChannel(DATACHANNEL_LABEL)),log$2.debug("created data channel",void 0,{F:__dxlog_file15,L:139,S:this,C:(U,q)=>U(...q)}),this._peer.ondatachannel=()=>{this.errors.raise(new Error("unexpected ondatachannel event for initiator"))}):this._peer.ondatachannel=U=>{log$2.debug("peer.ondatachannel (non-initiator)",{event:U},{F:__dxlog_file15,L:145,S:this,C:(q,G)=>q(...G)}),U.channel.label!==DATACHANNEL_LABEL&&this.errors.raise(new Error(`unexpected channel label ${U.channel.label}`)),this._handleChannel(U.channel)},rr._instanceCount++}async close(){await this._close(),--rr._instanceCount===0&&(await importESM("node-datachannel")).cleanup()}async _close(){var I;if(!this._closed){await this._disconnectStreams();try{(I=this._peer)==null||I.close()}catch(U){this.errors.raise(U)}this._peer=void 0,this._closed=!0,this.closed.emit()}}_handleChannel(I){this._channel=I,this._channel.onopen=()=>{log$2.debug("channel.onopen",void 0,{F:__dxlog_file15,L:190,S:this,C:(q,G)=>q(...G)});const U=new stream.Duplex({read:()=>{},write:async(q,G,K)=>{q.length>MAX_MESSAGE_SIZE&&this.errors.raise(new Error(`message too large: ${q.length} > ${MAX_MESSAGE_SIZE}`));try{I.send(q)}catch(Y){this.errors.raise(Y),await this._close()}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._writeCallback!==null&&log$2.error("consumer trying to write before we are ready for more data",void 0,{F:__dxlog_file15,L:207,S:this,C:(Y,J)=>Y(...J)}),this._writeCallback=K):K()}});U.pipe(this._options.stream).pipe(U),this._stream=U,this._connected=!0,this.connected.emit()},this._channel.onclose=async U=>{log$2.info("channel.onclose",{err:U},{F:__dxlog_file15,L:223,S:this,C:(q,G)=>q(...G)}),await this._close()},this._channel.onerror=async U=>{this.errors.raise(new Error("channel error: "+U.toString())),await this._close()},this._channel.onbufferedamountlow=()=>{const U=this._writeCallback;this._writeCallback=null,U==null||U()},this._channel.onmessage=U=>{let q=U.data;q instanceof ArrayBuffer&&(q=export_Buffer.from(q)),this._stream.push(q)}}async onSignal(I){invariant(this._peer,"not open",{F:__dxlog_file15,L:249,S:this,A:["this._peer","'not open'"]});try{const U=I.payload.data;switch(U.type){case"offer":{if(this._peer.connectionState!=="new"){log$2.error("received offer but peer not in state new",{peer:this._peer},{F:__dxlog_file15,L:256,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));break}try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp});const q=await this._peer.createAnswer();await this._peer.setLocalDescription(q),await this._options.sendSignal({payload:{data:{type:q.type,sdp:q.sdp}}}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle offer from signalling server",{err:q},{F:__dxlog_file15,L:268,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling offer"))}break}case"answer":try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle answer from signalling server",{err:q},{F:__dxlog_file15,L:279,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling answer"))}break;case"candidate":await this._readyForCandidates.wait(),await this._peer.addIceCandidate({candidate:U.candidate.candidate});break;default:log$2.error("unhandled signal type",{type:U.type,signal:I},{F:__dxlog_file15,L:290,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error(`unhandled signal type ${U.type}`))}}catch(U){log$2.catch(U,void 0,{F:__dxlog_file15,L:294,S:this,C:(q,G)=>q(...G)})}}async getDetails(){const I=await this._getStats(),U=I==null?void 0:I.remoteCandidate;return U?U.candidateType==="relay"?`${U.ip}:${U.port} relay for ${U.relatedAddress}:${U.relatedPort}`:`${U.ip}:${U.port} ${U.candidateType}`:"unavailable"}async getStats(){const I=await this._getStats();return I?{bytesSent:I.transport.bytesSent,bytesReceived:I.transport.bytesReceived,packetsSent:0,packetsReceived:0,rawStats:I.raw}:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rawStats:{}}}async _getStats(){invariant(this._peer,"not open",{F:__dxlog_file15,L:334,S:this,A:["this._peer","'not open'"]});const I=await this._peer.getStats(),U=Array.from(I.entries()),q=U.filter(J=>J[1].type==="transport")[0][1],G=U.filter(J=>J[0]===q.selectedCandidatePairId);let K,Y;return G.length>0&&(K=G[0][1],Y=U.filter(J=>J[0]===K.remoteCandidateId)[0][1]),{transport:q,selectedCandidatePair:K,remoteCandidate:Y,raw:Object.fromEntries(I)}}async _disconnectStreams(){var I,U,q,G;(G=(q=(U=(I=this._options.stream).unpipe)==null?void 0:U.call(I,this._stream))==null?void 0:q.unpipe)==null||G.call(q,this._options.stream)}},rr._instanceCount=0,rr);_ts_decorate5$1([synchronized],LibDataChannelTransport.prototype,"_close",null);var importESM=Function("path","return import(path)"),uaParser={exports:{}};(function($,I){(function(U,q){var G="1.0.35",K="",Y="?",J="function",X="undefined",Z="object",Q="string",ee="major",te="model",ne="name",ie="type",oe="vendor",ce="version",fe="architecture",se="console",de="mobile",ue="tablet",pe="smarttv",ve="wearable",me="embedded",be=350,_e="Amazon",Se="Apple",xe="ASUS",ke="BlackBerry",De="Browser",Be="Chrome",Ve="Edge",nt="Firefox",ot="Google",ft="Huawei",it="LG",ut="Microsoft",et="Motorola",Ue="Opera",We="Samsung",tt="Sharp",vt="Sony",je="Xiaomi",ze="Zebra",Ae="Facebook",Re="Chromium OS",Ce="Mac OS",ge=function(St,Ut){var le={};for(var re in St)Ut[re]&&Ut[re].length%2===0?le[re]=Ut[re].concat(St[re]):le[re]=St[re];return le},ye=function(St){for(var Ut={},le=0;le<St.length;le++)Ut[St[le].toUpperCase()]=St[le];return Ut},Me=function(St,Ut){return typeof St===Q?Ke(Ut).indexOf(Ke(St))!==-1:!1},Ke=function(St){return St.toLowerCase()},st=function(St){return typeof St===Q?St.replace(/[^\d\.]/g,K).split(".")[0]:q},dt=function(St,Ut){if(typeof St===Q)return St=St.replace(/^\s\s*/,K),typeof Ut===X?St:St.substring(0,be)},$t=function(St,Ut){for(var le=0,re,ae,he,we,Ee,Le;le<Ut.length&&!Ee;){var bt=Ut[le],Lt=Ut[le+1];for(re=ae=0;re<bt.length&&!Ee&&bt[re];)if(Ee=bt[re++].exec(St),Ee)for(he=0;he<Lt.length;he++)Le=Ee[++ae],we=Lt[he],typeof we===Z&&we.length>0?we.length===2?typeof we[1]==J?this[we[0]]=we[1].call(this,Le):this[we[0]]=we[1]:we.length===3?typeof we[1]===J&&!(we[1].exec&&we[1].test)?this[we[0]]=Le?we[1].call(this,Le,we[2]):q:this[we[0]]=Le?Le.replace(we[1],we[2]):q:we.length===4&&(this[we[0]]=Le?we[3].call(this,Le.replace(we[1],we[2])):q):this[we]=Le||q;le+=2}},Et=function(St,Ut){for(var le in Ut)if(typeof Ut[le]===Z&&Ut[le].length>0){for(var re=0;re<Ut[le].length;re++)if(Me(Ut[le][re],St))return le===Y?q:le}else if(Me(Ut[le],St))return le===Y?q:le;return St},rt={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},jt={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Gt={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[ce,[ne,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[ce,[ne,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[ne,ce],[/opios[\/ ]+([\w\.]+)/i],[ce,[ne,Ue+" Mini"]],[/\bopr\/([\w\.]+)/i],[ce,[ne,Ue]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[ne,ce],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[ce,[ne,"UC"+De]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[ce,[ne,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[ce,[ne,"WeChat"]],[/konqueror\/([\w\.]+)/i],[ce,[ne,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[ce,[ne,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[ce,[ne,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[ne,/(.+)/,"$1 Secure "+De],ce],[/\bfocus\/([\w\.]+)/i],[ce,[ne,nt+" Focus"]],[/\bopt\/([\w\.]+)/i],[ce,[ne,Ue+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[ce,[ne,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[ce,[ne,"Dolphin"]],[/coast\/([\w\.]+)/i],[ce,[ne,Ue+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[ce,[ne,"MIUI "+De]],[/fxios\/([-\w\.]+)/i],[ce,[ne,nt]],[/\bqihu|(qi?ho?o?|360)browser/i],[[ne,"360 "+De]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[ne,/(.+)/,"$1 "+De],ce],[/(comodo_dragon)\/([\w\.]+)/i],[[ne,/_/g," "],ce],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[ne,ce],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[ne],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[ne,Ae],ce],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[ne,ce],[/\bgsa\/([\w\.]+) .*safari\//i],[ce,[ne,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[ce,[ne,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[ce,[ne,Be+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[ne,Be+" WebView"],ce],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[ce,[ne,"Android "+De]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[ne,ce],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[ce,[ne,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[ce,ne],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[ne,[ce,Et,rt]],[/(webkit|khtml)\/([\w\.]+)/i],[ne,ce],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[ne,"Netscape"],ce],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[ce,[ne,nt+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[ne,ce],[/(cobalt)\/([\w\.]+)/i],[ne,[ce,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[fe,"amd64"]],[/(ia32(?=;))/i],[[fe,Ke]],[/((?:i[346]|x)86)[;\)]/i],[[fe,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[fe,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[fe,"armhf"]],[/windows (ce|mobile); ppc;/i],[[fe,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[fe,/ower/,K,Ke]],[/(sun4\w)[;\)]/i],[[fe,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[fe,Ke]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[te,[oe,We],[ie,ue]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[te,[oe,We],[ie,de]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[te,[oe,Se],[ie,de]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[te,[oe,Se],[ie,ue]],[/(macintosh);/i],[te,[oe,Se]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[te,[oe,tt],[ie,de]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[te,[oe,ft],[ie,ue]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[te,[oe,ft],[ie,de]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,de]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,ue]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[te,[oe,"OPPO"],[ie,de]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[te,[oe,"Vivo"],[ie,de]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[te,[oe,"Realme"],[ie,de]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[te,[oe,et],[ie,de]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[te,[oe,et],[ie,ue]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[te,[oe,it],[ie,ue]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[te,[oe,it],[ie,de]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[te,[oe,"Lenovo"],[ie,ue]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[te,/_/g," "],[oe,"Nokia"],[ie,de]],[/(pixel c)\b/i],[te,[oe,ot],[ie,ue]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[te,[oe,ot],[ie,de]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[te,[oe,vt],[ie,de]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[te,"Xperia Tablet"],[oe,vt],[ie,ue]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[te,[oe,"OnePlus"],[ie,de]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[te,[oe,_e],[ie,ue]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[te,/(.+)/g,"Fire Phone $1"],[oe,_e],[ie,de]],[/(playbook);[-\w\),; ]+(rim)/i],[te,oe,[ie,ue]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[te,[oe,ke],[ie,de]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[te,[oe,xe],[ie,ue]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[te,[oe,xe],[ie,de]],[/(nexus 9)/i],[te,[oe,"HTC"],[ie,ue]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[oe,[te,/_/g," "],[ie,de]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[te,[oe,"Acer"],[ie,ue]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[te,[oe,"Meizu"],[ie,de]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[oe,te,[ie,de]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[oe,te,[ie,ue]],[/(surface duo)/i],[te,[oe,ut],[ie,ue]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[te,[oe,"Fairphone"],[ie,de]],[/(u304aa)/i],[te,[oe,"AT&T"],[ie,de]],[/\bsie-(\w*)/i],[te,[oe,"Siemens"],[ie,de]],[/\b(rct\w+) b/i],[te,[oe,"RCA"],[ie,ue]],[/\b(venue[\d ]{2,7}) b/i],[te,[oe,"Dell"],[ie,ue]],[/\b(q(?:mv|ta)\w+) b/i],[te,[oe,"Verizon"],[ie,ue]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[te,[oe,"Barnes & Noble"],[ie,ue]],[/\b(tm\d{3}\w+) b/i],[te,[oe,"NuVision"],[ie,ue]],[/\b(k88) b/i],[te,[oe,"ZTE"],[ie,ue]],[/\b(nx\d{3}j) b/i],[te,[oe,"ZTE"],[ie,de]],[/\b(gen\d{3}) b.+49h/i],[te,[oe,"Swiss"],[ie,de]],[/\b(zur\d{3}) b/i],[te,[oe,"Swiss"],[ie,ue]],[/\b((zeki)?tb.*\b) b/i],[te,[oe,"Zeki"],[ie,ue]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[oe,"Dragon Touch"],te,[ie,ue]],[/\b(ns-?\w{0,9}) b/i],[te,[oe,"Insignia"],[ie,ue]],[/\b((nxa|next)-?\w{0,9}) b/i],[te,[oe,"NextBook"],[ie,ue]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[oe,"Voice"],te,[ie,de]],[/\b(lvtel\-)?(v1[12]) b/i],[[oe,"LvTel"],te,[ie,de]],[/\b(ph-1) /i],[te,[oe,"Essential"],[ie,de]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[te,[oe,"Envizen"],[ie,ue]],[/\b(trio[-\w\. ]+) b/i],[te,[oe,"MachSpeed"],[ie,ue]],[/\btu_(1491) b/i],[te,[oe,"Rotor"],[ie,ue]],[/(shield[\w ]+) b/i],[te,[oe,"Nvidia"],[ie,ue]],[/(sprint) (\w+)/i],[oe,te,[ie,de]],[/(kin\.[onetw]{3})/i],[[te,/\./g," "],[oe,ut],[ie,de]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[te,[oe,ze],[ie,ue]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[te,[oe,ze],[ie,de]],[/smart-tv.+(samsung)/i],[oe,[ie,pe]],[/hbbtv.+maple;(\d+)/i],[[te,/^/,"SmartTV"],[oe,We],[ie,pe]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[oe,it],[ie,pe]],[/(apple) ?tv/i],[oe,[te,Se+" TV"],[ie,pe]],[/crkey/i],[[te,Be+"cast"],[oe,ot],[ie,pe]],[/droid.+aft(\w)( bui|\))/i],[te,[oe,_e],[ie,pe]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[te,[oe,tt],[ie,pe]],[/(bravia[\w ]+)( bui|\))/i],[te,[oe,vt],[ie,pe]],[/(mitv-\w{5}) bui/i],[te,[oe,je],[ie,pe]],[/Hbbtv.*(technisat) (.*);/i],[oe,te,[ie,pe]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[oe,dt],[te,dt],[ie,pe]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[ie,pe]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[oe,te,[ie,se]],[/droid.+; (shield) bui/i],[te,[oe,"Nvidia"],[ie,se]],[/(playstation [345portablevi]+)/i],[te,[oe,vt],[ie,se]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[te,[oe,ut],[ie,se]],[/((pebble))app/i],[oe,te,[ie,ve]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[te,[oe,Se],[ie,ve]],[/droid.+; (glass) \d/i],[te,[oe,ot],[ie,ve]],[/droid.+; (wt63?0{2,3})\)/i],[te,[oe,ze],[ie,ve]],[/(quest( 2| pro)?)/i],[te,[oe,Ae],[ie,ve]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[oe,[ie,me]],[/(aeobc)\b/i],[te,[oe,_e],[ie,me]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[te,[ie,de]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[te,[ie,ue]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[ie,ue]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[ie,de]],[/(android[-\w\. ]{0,9});.+buil/i],[te,[oe,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[ce,[ne,Ve+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[ce,[ne,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[ne,ce],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[ce,ne]],os:[[/microsoft (windows) (vista|xp)/i],[ne,ce],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[ne,[ce,Et,jt]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[ne,"Windows"],[ce,Et,jt]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[ce,/_/g,"."],[ne,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[ne,Ce],[ce,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[ce,ne],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[ne,ce],[/\(bb(10);/i],[ce,[ne,ke]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[ce,[ne,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[ce,[ne,nt+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[ce,[ne,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[ce,[ne,"watchOS"]],[/crkey\/([\d\.]+)/i],[ce,[ne,Be+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[ne,Re],ce],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[ne,ce],[/(sunos) ?([\w\.\d]*)/i],[[ne,"Solaris"],ce],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[ne,ce]]},At=function(St,Ut){if(typeof St===Z&&(Ut=St,St=q),!(this instanceof At))return new At(St,Ut).getResult();var le=typeof U!==X&&U.navigator?U.navigator:q,re=St||(le&&le.userAgent?le.userAgent:K),ae=le&&le.userAgentData?le.userAgentData:q,he=Ut?ge(Gt,Ut):Gt,we=le&&le.userAgent==re;return this.getBrowser=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.browser),Ee[ee]=st(Ee[ce]),we&&le&&le.brave&&typeof le.brave.isBrave==J&&(Ee[ne]="Brave"),Ee},this.getCPU=function(){var Ee={};return Ee[fe]=q,$t.call(Ee,re,he.cpu),Ee},this.getDevice=function(){var Ee={};return Ee[oe]=q,Ee[te]=q,Ee[ie]=q,$t.call(Ee,re,he.device),we&&!Ee[ie]&&ae&&ae.mobile&&(Ee[ie]=de),we&&Ee[te]=="Macintosh"&&le&&typeof le.standalone!==X&&le.maxTouchPoints&&le.maxTouchPoints>2&&(Ee[te]="iPad",Ee[ie]=ue),Ee},this.getEngine=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.engine),Ee},this.getOS=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.os),we&&!Ee[ne]&&ae&&ae.platform!="Unknown"&&(Ee[ne]=ae.platform.replace(/chrome os/i,Re).replace(/macos/i,Ce)),Ee},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return re},this.setUA=function(Ee){return re=typeof Ee===Q&&Ee.length>be?dt(Ee,be):Ee,this},this.setUA(re),this};At.VERSION=G,At.BROWSER=ye([ne,ce,ee]),At.CPU=ye([fe]),At.DEVICE=ye([te,oe,ie,se,de,pe,ue,ve,me]),At.ENGINE=At.OS=ye([ne,ce]),$.exports&&(I=$.exports=At),I.UAParser=At;var zt=typeof U!==X&&(U.jQuery||U.Zepto);if(zt&&!zt.ua){var nn=new At;zt.ua=nn.getResult(),zt.ua.get=function(){return nn.getUA()},zt.ua.set=function(St){nn.setUA(St);var Ut=nn.getResult();for(var le in Ut)zt.ua[le]=Ut[le]}}})(typeof window=="object"?window:commonjsGlobal)})(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,__dxlog_file$2="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/iframe.ts",browser,os$1;if(typeof navigator<"u"){const $=new uaParserExports.UAParser(navigator.userAgent);browser=$.getBrowser().name,os$1=$.getOS().name}var sendToIFrame=($,I,U)=>{if(!$.contentWindow){log$2("IFrame content window missing",{origin:I},{F:__dxlog_file$2,L:24,S:void 0,C:(q,G)=>q(...G)});return}browser==="Chrome"&&os$1==="iOS"?$.contentWindow.postMessage(U,I):$.contentWindow.postMessage(U,I,[U.payload])},sendToParentWindow=($,I)=>{browser==="Chrome"&&os$1==="iOS"?window.parent.postMessage(I,$):window.parent.postMessage(I,$,[I.payload])},createIFramePort=({channel:$,iframe:I,origin:U,onOrigin:q})=>({send:async G=>{if(!U){log$2("no origin set",{channel:$},{F:__dxlog_file$2,L:62,S:void 0,C:(J,X)=>J(...X)});return}log$2("sending",{channel:$,data:G.length},{F:__dxlog_file$2,L:66,S:void 0,C:(J,X)=>J(...X)});const K=G.buffer.slice(G.byteOffset,G.byteOffset+G.byteLength),Y={channel:$,payload:K};I?sendToIFrame(I,U,Y):sendToParentWindow(U,Y)},subscribe:G=>{const K=Y=>{if(!I&&Y.source!==window.parent)return;if(I&&Y.source!==I.contentWindow)return;const X=Y.data&&typeof Y.data=="object"&&"channel"in Y.data&&"payload"in Y.data?Y.data:void 0;(X==null?void 0:X.channel)===$&&(U||(U=Y.origin,q==null||q(U)),log$2("received",X,{F:__dxlog_file$2,L:98,S:void 0,C:(Z,Q)=>Z(...Q)}),G(new Uint8Array(X.payload)))};return window.addEventListener("message",K),()=>window.removeEventListener("message",K)}}),createIFrame=($,I,{hidden:U=!0,allow:q}={})=>{const G=()=>{const K=document.createElement("iframe");return K.id=I,K.src=$,U&&K.setAttribute("style","display: none;"),q&&K.setAttribute("allow",q),document.body.appendChild(K),K};return document.getElementById(I)??G()},__dxlog_file2="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/worker.ts",createWorkerPort=({port:$,channel:I,subscribe:U})=>({send:async q=>{const G=q.buffer.slice(q.byteOffset,q.byteOffset+q.byteLength);$.postMessage({channel:I,payload:G},[G])},subscribe:U??(q=>{const G=K=>{const Y=K.data;I&&Y.channel!==I||(log$2.debug("Recieved message",Y,{F:__dxlog_file2,L:46,S:void 0,C:(J,X)=>J(...X)}),q(new Uint8Array(Y.payload)))};return $.onmessage=G,()=>{$.onmessage=null}})});function _ts_decorate$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$1="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/agent.ts",getUnixSocket=($,I="unix")=>`${I}://`+clientProtocol.getProfilePath(clientProtocol.DX_RUNTIME,$,"agent.sock"),AgentClientServiceProvider=class{constructor($){this._profile=$,this.closed=new Event$1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._client.rpc}async open(){const{WebsocketRpcClient:$}=await Promise.resolve().then(()=>index);this._client=new $({url:getUnixSocket(this._profile,"ws+unix"),requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{}}),await this._client.open()}async close(){var $;try{await(($=this._client)==null?void 0:$.close())}catch(I){log$2.warn("Failed to close",I,{F:__dxlog_file$1,L:69,S:this,C:(U,q)=>U(...q)})}}};AgentClientServiceProvider=_ts_decorate$1([trace.resource({annotation:clientServices.ClientServicesProviderResource})],AgentClientServiceProvider);function _ts_decorate2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var LocalClientServices=class{constructor($){this.closed=new Event$1,this._ctx=new Context,this.signalMetadataTags={runtime:"local-client-services"},this._isOpen=!1,this._params=$,typeof window>"u"?this.signalMetadataTags.origin="undefined":globalThis.__args?(this.signalMetadataTags.runtime="native",this.signalMetadataTags.origin=window.location.origin):this.signalMetadataTags.origin=window.location.origin}get descriptors(){return clientProtocol.clientServiceBundle}get services(){var $;return(($=this._host)==null?void 0:$.services)??{}}get host(){return this._host}async open(){if(this._isOpen)return;const{ClientServicesHost:$}=await import("@dxos/client-services");this._host=new $({...this._params,callbacks:{...this._params.callbacks,onReset:async()=>{var I,U;this.closed.emit(void 0),await((U=(I=this._params.callbacks)==null?void 0:I.onReset)==null?void 0:U.call(I))}}}),await this._host.open(this._ctx),this._isOpen=!0,setIdentityTags({identityService:this._host.services.IdentityService,devicesService:this._host.services.DevicesService,setTag:(I,U)=>{this.signalMetadataTags[I]=U}})}async close(){var $;this._isOpen&&(await(($=this._host)==null?void 0:$.close()),this._isOpen=!1)}};_ts_decorate2([trace.info()],LocalClientServices.prototype,"_isOpen",void 0),_ts_decorate2([synchronized],LocalClientServices.prototype,"open",null),_ts_decorate2([synchronized],LocalClientServices.prototype,"close",null),LocalClientServices=_ts_decorate2([trace.resource({annotation:clientServices.ClientServicesProviderResource})],LocalClientServices);var IFrameManager=class{constructor({source:$,onOpen:I,onMessage:U}){this._source=$,this._onOpen=I,this._onMessage=U,this._messageHandler=this._messageHandler.bind(this)}get source(){return this._source}get iframe(){return this._iframe}async open(){var I;if(this._iframe)return;window.addEventListener("message",this._messageHandler);const $=`__DXOS_CLIENT_${PublicKey.random().toHex()}__`;this._iframe=createIFrame(this._source.toString(),$,{allow:"clipboard-read; clipboard-write"}),await((I=this._onOpen)==null?void 0:I.call(this))}async close(){var $;window.removeEventListener("message",this._messageHandler),($=this._iframe)==null||$.remove(),this._iframe=void 0}async _messageHandler($){var I;(I=this._onMessage)==null||I.call(this,$)}},__dxlog_file3="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/shell-manager.ts",shellStyles=Object.entries({display:"none",position:"fixed",top:0,left:0,width:"100vw",height:"100vh",border:0,"z-index":60}).reduce(($,[I,U])=>`${$}${I}: ${U};`,""),ShellManager=class{constructor($,I=clientProtocol.DEFAULT_SHELL_CHANNEL){this._iframeManager=$,this._channel=I,this.contextUpdate=new Event$1,this._display=ShellDisplay.NONE}get display(){return this._display}async setLayout($){var I;log$2("set layout",$,{F:__dxlog_file3,L:50,S:this,C:(U,q)=>U(...q)}),this._display=ShellDisplay.FULLSCREEN,this.contextUpdate.emit({display:this._display}),await((I=this._shellRpc)==null?void 0:I.rpc.ShellService.setLayout($))}async open(){if(this._shellRpc)return;await this._iframeManager.open();const $=this._iframeManager.iframe;$.setAttribute("style",shellStyles),$.setAttribute("name","dxos-shell"),$.setAttribute("data-testid","dxos-shell"),this.contextUpdate.on(({display:q,reload:G})=>{G&&window.location.reload(),$.style.display=q===ShellDisplay.NONE?"none":"",q===ShellDisplay.NONE&&$.blur()});const I=this._iframeManager.source.origin==="null"?this._iframeManager.source.toString().split("/").slice(0,3).join("/"):this._iframeManager.source.origin,U=createIFramePort({origin:I,channel:this._channel,iframe:this._iframeManager.iframe});this._shellRpc=createProtoRpcPeer({requested:clientProtocol.shellServiceBundle,exposed:clientProtocol.appServiceBundle,handlers:{AppService:{setContext:async q=>{log$2("set context",q,{F:__dxlog_file3,L:97,S:this,C:(G,K)=>G(...K)}),q.display&&(this._display=q.display),this.contextUpdate.emit(q)}}},port:U}),await this._shellRpc.open()}async close(){var $;this._shellRpc&&(await(($=this._shellRpc)==null?void 0:$.close()),this._shellRpc=void 0)}};function _ts_decorate3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var IFrameClientServicesHost=class{constructor({host:$,source:I=clientProtocol.DEFAULT_VAULT_URL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT}){this.closed=new Event$1,this._host=$,this._source=I,this._vault=U,this._timeout=q;const G=new Trigger;this._iframeManager=new IFrameManager({source:new URL(this._source,window.location.origin),onOpen:async()=>{var K,Y,J;await asyncTimeout(G.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(J=(Y=(K=this._iframeManager)==null?void 0:K.iframe)==null?void 0:Y.contentWindow)==null||J.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin)},onMessage:K=>{var X,Z,Q;const{channel:Y,payload:J}=K.data;if(Y===this._vault){if(J==="loaded")G.wake();else if(J==="client"){const ee=new MessageChannel,te=createBundledRpcServer({services:this._host.descriptors,handlers:this._host.services,port:createWorkerPort({port:ee.port1})});(Q=(Z=(X=this._iframeManager)==null?void 0:X.iframe)==null?void 0:Z.contentWindow)==null||Q.postMessage({channel:this._vault,payload:{command:"port",port:ee.port2}},this._iframeManager.source.origin,[ee.port2]),te.open()}}}}),this._shellManager=new ShellManager(this._iframeManager)}get descriptors(){return this._host.descriptors}get services(){return this._host.services}async open(){await this._host.open(new Context),await this._shellManager.open()}async close(){await this._shellManager.close(),await this._iframeManager.close(),await this._host.close(new Context)}};IFrameClientServicesHost=_ts_decorate3([trace.resource()],IFrameClientServicesHost);function _ts_decorate4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/service-proxy.ts",ClientServicesProxy=class{constructor($,I=3e4){this._port=$,this._timeout=I,this.closed=new Event$1}get proxy(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file4,L:30,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file4,L:39,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy.rpc}async open(){this._proxy||(this._proxy=createProtoRpcPeer({requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{},port:this._port}),await asyncTimeout(this._proxy.open(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Failed to establish dxrpc connection",{timeout:this._timeout})))}async close(){this._proxy&&(await this._proxy.close(),this._proxy=void 0)}};ClientServicesProxy=_ts_decorate4([trace.resource({annotation:clientServices.ClientServicesProviderResource})],ClientServicesProxy);function _ts_decorate5($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/iframe-service-proxy.ts",IFrameClientServicesProxy=class{constructor({source:$=clientProtocol.DEFAULT_VAULT_URL,shell:I=clientProtocol.DEFAULT_SHELL_CHANNEL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT,logFilter:G="error,warn"}={}){this.closed=new Event$1,this._instanceId=PublicKey.random().toHex(),this._source=$,this._shell=I,this._vault=U,this._logFilter=parseFilter(G),this._timeout=q;const K=new Trigger,Y=new Trigger;this._iframeManager=new IFrameManager({source:new URL(typeof this._shell=="string"?this._source:`${this._source}#disableshell`,window.location.origin),onOpen:async()=>{var X,Z;await asyncTimeout(K.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(Z=(X=this._iframeManager.iframe)==null?void 0:X.contentWindow)==null||Z.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin);const J=await asyncTimeout(Y.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to provide MessagePort"));this._appPort=createWorkerPort({port:J})},onMessage:async J=>{const{channel:X,payload:Z}=J.data;X===this._vault&&(Z==="loaded"?K.wake():(Z==null?void 0:Z.command)==="init"&&Y.wake(Z.port))}}),typeof this._shell=="string"&&(this._shellManager=new ShellManager(this._iframeManager))}get proxy(){return this._clientServicesProxy.proxy}get descriptors(){return this._clientServicesProxy.descriptors}get services(){return this._clientServicesProxy.services}async open(){var $;this._clientServicesProxy||(log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file5,L:141,S:this,C:(I,U)=>I(...U)}),await this._iframeManager.open(),this._clientServicesProxy=new ClientServicesProxy(this._appPort),await this._clientServicesProxy.open(),this._loggingStream=this._clientServicesProxy.services.LoggingService.queryLogs({filters:this._logFilter}),this._loggingStream.subscribe(I=>{switch(I.level){case LogLevel.DEBUG:log$2.debug(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:153,S:this,C:(U,q)=>U(...q)});break;case LogLevel.INFO:log$2.info(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:156,S:this,C:(U,q)=>U(...q)});break;case LogLevel.WARN:log$2.warn(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:159,S:this,C:(U,q)=>U(...q)});break;case LogLevel.ERROR:log$2.error(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:162,S:this,C:(U,q)=>U(...q)});break}}),await(($=this._shellManager)==null?void 0:$.open()))}async close(){var $,I,U;await(($=this._shellManager)==null?void 0:$.close()),await this._iframeManager.close(),await((I=this._loggingStream)==null?void 0:I.close()),await((U=this._clientServicesProxy)==null?void 0:U.close()),this._clientServicesProxy=void 0,log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file5,L:176,S:this,C:(q,G)=>q(...G)})}};IFrameClientServicesProxy=_ts_decorate5([trace.resource()],IFrameClientServicesProxy);function _ts_decorate6($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file7="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/worker-client-services.ts",WorkerClientServices=class{constructor({config:$,createWorker:I,logFilter:U="error,warn",observabilityGroup:q,signalTelemetryEnabled:G}){this.closed=new Event$1,this.joinedSpace=new Event$1,this._isOpen=!1,this._config=$,this._createWorker=I,this._logFilter=parseFilter(U),this._observabilityGroup=q,this._signalTelemetryEnabled=G??!1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._services.services}get runtime(){return this._runtime}async open(){if(this._isOpen)return;log$2("opening...",void 0,{F:__dxlog_file7,L:87,S:this,C:(K,Y)=>K(...Y)});const{SharedWorkerConnection:$}=await import("@dxos/client-services"),I=new Trigger,U=this._createWorker();U.port.postMessage({dxlog:localStorage.getItem("dxlog")}),U.port.onmessage=K=>{const{command:Y,payload:J}=K.data;Y==="init"&&I.wake(J)};const{systemPort:q,appPort:G}=await I.wait();this._runtime=new $({config:this._config,systemPort:createWorkerPort({port:q})}),await this._runtime.open({origin:location.origin,observabilityGroup:this._observabilityGroup,signalTelemetryEnabled:this._signalTelemetryEnabled}),this._services=new ClientServicesProxy(createWorkerPort({port:G})),await this._services.open(),navigator.locks.request(LOCK_KEY,()=>{log$2("terminated",void 0,{F:__dxlog_file7,L:114,S:this,C:(K,Y)=>K(...Y)}),this._isOpen&&this.closed.emit(new Error("Shared worker terminated."))}),this._loggingStream=this._services.services.LoggingService.queryLogs({filters:this._logFilter}),this._loggingStream.subscribe(K=>{switch(K.level){case LogLevel.DEBUG:log$2.debug(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.INFO:log$2.info(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.WARN:log$2.warn(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.ERROR:log$2.error(K.message,K.context,mapLogMeta(K.meta));break}}),log$2("opened",void 0,{F:__dxlog_file7,L:140,S:this,C:(K,Y)=>K(...Y)}),this._isOpen=!0}async close(){var $;this._isOpen&&(log$2("closing...",void 0,{F:__dxlog_file7,L:150,S:this,C:(I,U)=>I(...U)}),await(($=this._loggingStream)==null?void 0:$.close()),await this._runtime.close(),await this._services.close(),log$2("closed",void 0,{F:__dxlog_file7,L:155,S:this,C:(I,U)=>I(...U)}),this._isOpen=!1)}};_ts_decorate6([trace.info()],WorkerClientServices.prototype,"_isOpen",void 0),_ts_decorate6([synchronized],WorkerClientServices.prototype,"open",null),_ts_decorate6([synchronized],WorkerClientServices.prototype,"close",null),WorkerClientServices=_ts_decorate6([trace.resource()],WorkerClientServices);var mapLogMeta=$=>$&&{F:$.file,L:$.line,S:$.scope},i$1=Symbol.for("preact-signals");function t(){if(s$1>1)s$1--;else{for(var $,I=!1;h$1!==void 0;){var U=h$1;for(h$1=void 0,f++;U!==void 0;){var q=U.o;if(U.o=void 0,U.f&=-3,!(8&U.f)&&c(U))try{U.c()}catch(G){I||($=G,I=!0)}U=q}}if(f=0,s$1--,I)throw $}}var o=void 0,h$1=void 0,s$1=0,f=0,v$1=0;function e($){if(o!==void 0){var I=$.n;if(I===void 0||I.t!==o)return I={i:0,S:$,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:I},o.s!==void 0&&(o.s.n=I),o.s=I,$.n=I,32&o.f&&$.S(I),I;if(I.i===-1)return I.i=0,I.n!==void 0&&(I.n.p=I.p,I.p!==void 0&&(I.p.n=I.n),I.p=o.s,I.n=void 0,o.s.n=I,o.s=I),I}}function u($){this.v=$,this.i=0,this.n=void 0,this.t=void 0}u.prototype.brand=i$1,u.prototype.h=function(){return!0},u.prototype.S=function($){this.t!==$&&$.e===void 0&&($.x=this.t,this.t!==void 0&&(this.t.e=$),this.t=$)},u.prototype.U=function($){if(this.t!==void 0){var I=$.e,U=$.x;I!==void 0&&(I.x=U,$.e=void 0),U!==void 0&&(U.e=I,$.x=void 0),$===this.t&&(this.t=U)}},u.prototype.subscribe=function($){var I=this;return E(function(){var U=I.value,q=o;o=void 0;try{$(U)}finally{o=q}})},u.prototype.valueOf=function(){return this.value},u.prototype.toString=function(){return this.value+""},u.prototype.toJSON=function(){return this.value},u.prototype.peek=function(){var $=o;o=void 0;try{return this.value}finally{o=$}},Object.defineProperty(u.prototype,"value",{get:function(){var $=e(this);return $!==void 0&&($.i=this.i),this.v},set:function($){if($!==this.v){if(f>100)throw new Error("Cycle detected");this.v=$,this.i++,v$1++,s$1++;try{for(var I=this.t;I!==void 0;I=I.x)I.t.N()}finally{t()}}}});function c($){for(var I=$.s;I!==void 0;I=I.n)if(I.S.i!==I.i||!I.S.h()||I.S.i!==I.i)return!0;return!1}function a($){for(var I=$.s;I!==void 0;I=I.n){var U=I.S.n;if(U!==void 0&&(I.r=U),I.S.n=I,I.i=-1,I.n===void 0){$.s=I;break}}}function l($){for(var I=$.s,U=void 0;I!==void 0;){var q=I.p;I.i===-1?(I.S.U(I),q!==void 0&&(q.n=I.n),I.n!==void 0&&(I.n.p=q)):U=I,I.S.n=I.r,I.r!==void 0&&(I.r=void 0),I=q}$.s=U}function y($){u.call(this,void 0),this.x=$,this.s=void 0,this.g=v$1-1,this.f=4}(y.prototype=new u).h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===v$1))return!0;if(this.g=v$1,this.f|=1,this.i>0&&!c(this))return this.f&=-2,!0;var $=o;try{a(this),o=this;var I=this.x();(16&this.f||this.v!==I||this.i===0)&&(this.v=I,this.f&=-17,this.i++)}catch(U){this.v=U,this.f|=16,this.i++}return o=$,l(this),this.f&=-2,!0},y.prototype.S=function($){if(this.t===void 0){this.f|=36;for(var I=this.s;I!==void 0;I=I.n)I.S.S(I)}u.prototype.S.call(this,$)},y.prototype.U=function($){if(this.t!==void 0&&(u.prototype.U.call(this,$),this.t===void 0)){this.f&=-33;for(var I=this.s;I!==void 0;I=I.n)I.S.U(I)}},y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var $=this.t;$!==void 0;$=$.x)$.t.N()}},Object.defineProperty(y.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var $=e(this);if(this.h(),$!==void 0&&($.i=this.i),16&this.f)throw this.v;return this.v}});function _($){var I=$.u;if($.u=void 0,typeof I=="function"){s$1++;var U=o;o=void 0;try{I()}catch(q){throw $.f&=-2,$.f|=8,g($),q}finally{o=U,t()}}}function g($){for(var I=$.s;I!==void 0;I=I.n)I.S.U(I);$.x=void 0,$.s=void 0,_($)}function p$1($){if(o!==this)throw new Error("Out-of-order effect");l(this),o=$,this.f&=-2,8&this.f&&g(this),t()}function b$1($){this.x=$,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32}b$1.prototype.c=function(){var $=this.S();try{if(8&this.f||this.x===void 0)return;var I=this.x();typeof I=="function"&&(this.u=I)}finally{$()}},b$1.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,_(this),a(this),s$1++;var $=o;return o=this,p$1.bind(this,$)},b$1.prototype.N=function(){2&this.f||(this.f|=2,this.o=h$1,h$1=this)},b$1.prototype.d=function(){this.f|=8,1&this.f||g(this)};function E($){var I=new b$1($);try{I.c()}catch(U){throw I.d(),U}return I.d.bind(I)}var shim={exports:{}},useSyncExternalStoreShim_production_min={};/**
|
|
923
|
+
Use Chrome, Firefox or Internet Explorer 11`)}var Buffer$2=requireSafeBuffer().Buffer,crypto=commonjsGlobal.crypto||commonjsGlobal.msCrypto;crypto&&crypto.getRandomValues?browser$1.exports=randomBytes:browser$1.exports=oldBrowser;function randomBytes($,I){if($>MAX_UINT32)throw new RangeError("requested too many random bytes");var U=Buffer$2.allocUnsafe($);if($>0)if($>MAX_BYTES)for(var q=0;q<$;q+=MAX_BYTES)crypto.getRandomValues(U.slice(q,q+MAX_BYTES));else crypto.getRandomValues(U);return typeof I=="function"?process.nextTick(function(){I(null,U)}):U}var browserExports=browser$1.exports;/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let promise;var queueMicrotask_1=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:commonjsGlobal):$=>(promise||(promise=Promise.resolve())).then($).catch(I=>setTimeout(()=>{throw I},0));function assign$3($,I){for(const U in I)Object.defineProperty($,U,{value:I[U],enumerable:!0,configurable:!0});return $}function createError($,I,U){if(!$||typeof $=="string")throw new TypeError("Please pass an Error to err-code");U||(U={}),typeof I=="object"&&(U=I,I=""),I&&(U.code=I);try{return assign$3($,U)}catch{U.message=$.message,U.stack=$.stack;const G=function(){};return G.prototype=Object.create(Object.getPrototypeOf($)),assign$3(new G,U)}}var errCode$1=createError;/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const debug=browserExports$1("simple-peer"),getBrowserRTC=getBrowserRtc,randombytes=browserExports,stream$1=readableBrowserExports,queueMicrotask$1=queueMicrotask_1,errCode=errCode$1,{Buffer:Buffer$1}=buffer,MAX_BUFFERED_AMOUNT$1=64*1024,ICECOMPLETE_TIMEOUT=5*1e3,CHANNEL_CLOSING_TIMEOUT=5*1e3;function filterTrickle($){return $.replace(/a=ice-options:trickle\s\n/g,"")}function warn$1($){console.warn($)}let Peer$1=class pr extends stream$1.Duplex{constructor(I){if(I=Object.assign({allowHalfOpen:!1},I),super(I),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",I),this.channelName=I.initiator?I.channelName||randombytes(20).toString("hex"):null,this.initiator=I.initiator||!1,this.channelConfig=I.channelConfig||pr.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},pr.config,I.config),this.offerOptions=I.offerOptions||{},this.answerOptions=I.answerOptions||{},this.sdpTransform=I.sdpTransform||(U=>U),this.streams=I.streams||(I.stream?[I.stream]:[]),this.trickle=I.trickle!==void 0?I.trickle:!0,this.allowHalfTrickle=I.allowHalfTrickle!==void 0?I.allowHalfTrickle:!1,this.iceCompleteTimeout=I.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=I.wrtc&&typeof I.wrtc=="object"?I.wrtc:getBrowserRTC(),!this._wrtc)throw errCode(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(U){this.destroy(errCode(U,"ERR_PC_CONSTRUCTOR"));return}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=U=>{this._onIceCandidate(U)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(U=>{this.destroy(errCode(U,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=U=>{this._setupData(U)},this.streams&&this.streams.forEach(U=>{this.addStream(U)}),this._pc.ontrack=U=>{this._onTrack(U)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof I=="string")try{I=JSON.parse(I)}catch{I={}}this._debug("signal()"),I.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),I.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(I.transceiverRequest.kind,I.transceiverRequest.init)),I.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(I.candidate):this._pendingCandidates.push(I.candidate)),I.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(I)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(U=>{this._addIceCandidate(U)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(U=>{this.destroy(errCode(U,"ERR_SET_REMOTE_DESCRIPTION"))}),!I.sdp&&!I.candidate&&!I.renegotiate&&!I.transceiverRequest&&this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(I){const U=new this._wrtc.RTCIceCandidate(I);this._pc.addIceCandidate(U).catch(q=>{!U.address||U.address.endsWith(".local")?warn$1("Ignoring unsupported ICE candidate."):this.destroy(errCode(q,"ERR_ADD_ICE_CANDIDATE"))})}send(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(I)}}addTransceiver(I,U){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(I,U),this._needsNegotiation()}catch(q){this.destroy(errCode(q,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:I,init:U}})}}addStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),I.getTracks().forEach(U=>{this.addTrack(U,I)})}}addTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const q=this._senderMap.get(I)||new Map;let G=q.get(U);if(!G)G=this._pc.addTrack(I,U),q.set(U,G),this._senderMap.set(I,q),this._needsNegotiation();else throw G.removed?errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(I,U,q){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const G=this._senderMap.get(I),K=G?G.get(q):null;if(!K)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");U&&this._senderMap.set(U,G),K.replaceTrack!=null?K.replaceTrack(U):this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const q=this._senderMap.get(I),G=q?q.get(U):null;if(!G)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{G.removed=!0,this._pc.removeTrack(G)}catch(K){K.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(G):this.destroy(errCode(K,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),I.getTracks().forEach(U=>{this.removeTrack(U,I)})}}_needsNegotiation(){this._debug("_needsNegotiation"),!this._batchedNegotiation&&(this._batchedNegotiation=!0,queueMicrotask$1(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(I){this._destroy(I,()=>{})}_destroy(I,U){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",I&&(I.message||I)),queueMicrotask$1(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",I&&(I.message||I)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,I&&this.emit("error",I),this.emit("close"),U()}))}_setupData(I){if(!I.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=I.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT$1),this.channelName=this._channel.label,this._channel.onmessage=q=>{this._onChannelMessage(q)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=q=>{const G=q.error instanceof Error?q.error:new Error(`Datachannel error: ${q.message} ${q.filename}:${q.lineno}:${q.colno}`);this.destroy(errCode(G,"ERR_DATA_CHANNEL"))};let U=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(U&&this._onChannelClose(),U=!0):U=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(I,U,q){if(this.destroyed)return q(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(I)}catch(G){return this.destroy(errCode(G,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=q):q(null)}else this._debug("write before connect"),this._chunk=I,this._cb=q}_onFinish(){if(this.destroyed)return;const I=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?I():this.once("connect",I)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp})},q=()=>{this._debug("createOffer success"),!this.destroyed&&(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(I=>{!I.mid&&I.sender.track&&!I.requested&&(I.requested=!0,this.addTransceiver(I.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp}),this.initiator||this._requestMissingTransceivers()},q=()=>{this.destroyed||(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const I=this._pc.iceConnectionState,U=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",I,U),this.emit("iceStateChange",I,U),(I==="connected"||I==="completed")&&(this._pcReady=!0,this._maybeReady()),I==="failed"&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),I==="closed"&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(I){const U=q=>(Object.prototype.toString.call(q.values)==="[object Array]"&&q.values.forEach(G=>{Object.assign(q,G)}),q);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(q=>{const G=[];q.forEach(K=>{G.push(U(K))}),I(null,G)},q=>I(q)):this._pc.getStats.length>0?this._pc.getStats(q=>{if(this.destroyed)return;const G=[];q.result().forEach(K=>{const Y={};K.names().forEach(J=>{Y[J]=K.stat(J)}),Y.id=K.id,Y.type=K.type,Y.timestamp=K.timestamp,G.push(U(Y))}),I(null,G)},q=>I(q)):I(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const I=()=>{this.destroyed||this.getStats((U,q)=>{if(this.destroyed)return;U&&(q=[]);const G={},K={},Y={};let J=!1;q.forEach(Z=>{(Z.type==="remotecandidate"||Z.type==="remote-candidate")&&(G[Z.id]=Z),(Z.type==="localcandidate"||Z.type==="local-candidate")&&(K[Z.id]=Z),(Z.type==="candidatepair"||Z.type==="candidate-pair")&&(Y[Z.id]=Z)});const X=Z=>{J=!0;let Q=K[Z.localCandidateId];Q&&(Q.ip||Q.address)?(this.localAddress=Q.ip||Q.address,this.localPort=Number(Q.port)):Q&&Q.ipAddress?(this.localAddress=Q.ipAddress,this.localPort=Number(Q.portNumber)):typeof Z.googLocalAddress=="string"&&(Q=Z.googLocalAddress.split(":"),this.localAddress=Q[0],this.localPort=Number(Q[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let ee=G[Z.remoteCandidateId];ee&&(ee.ip||ee.address)?(this.remoteAddress=ee.ip||ee.address,this.remotePort=Number(ee.port)):ee&&ee.ipAddress?(this.remoteAddress=ee.ipAddress,this.remotePort=Number(ee.portNumber)):typeof Z.googRemoteAddress=="string"&&(ee=Z.googRemoteAddress.split(":"),this.remoteAddress=ee[0],this.remotePort=Number(ee[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(q.forEach(Z=>{Z.type==="transport"&&Z.selectedCandidatePairId&&X(Y[Z.selectedCandidatePairId]),(Z.type==="googCandidatePair"&&Z.googActiveConnection==="true"||(Z.type==="candidatepair"||Z.type==="candidate-pair")&&Z.selected)&&X(Z)}),!J&&(!Object.keys(Y).length||Object.keys(K).length)){setTimeout(I,100);return}else this._connecting=!1,this._connected=!0;if(this._chunk){try{this.send(this._chunk)}catch(Q){return this.destroy(errCode(Q,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const Z=this._cb;this._cb=null,Z(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};I()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(I=>{this._pc.removeTrack(I),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(I){this.destroyed||(I.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:I.candidate.candidate,sdpMLineIndex:I.candidate.sdpMLineIndex,sdpMid:I.candidate.sdpMid}}):!I.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),I.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(I){if(this.destroyed)return;let U=I.data;U instanceof ArrayBuffer&&(U=Buffer$1.from(U)),this.push(U)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const I=this._cb;this._cb=null,I(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(I){this.destroyed||I.streams.forEach(U=>{this._debug("on track"),this.emit("track",I.track,U),this._remoteTracks.push({track:I.track,stream:U}),!this._remoteStreams.some(q=>q.id===U.id)&&(this._remoteStreams.push(U),queueMicrotask$1(()=>{this._debug("on stream"),this.emit("stream",U)}))})}_debug(){const I=[].slice.call(arguments);I[0]="["+this._id+"] "+I[0],debug.apply(null,I)}};Peer$1.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer$1.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer$1.channelConfig={};var ConnectionState$1;(function($){$[$.INVALID=0]="INVALID",$[$.CONNECTING=1]="CONNECTING",$[$.CONNECTED=2]="CONNECTED",$[$.CLOSED=3]="CLOSED"})(ConnectionState$1||(ConnectionState$1={}));var emitterComponent=Emitter$1;function Emitter$1($){if($)return mixin($)}function mixin($){for(var I in Emitter$1.prototype)$[I]=Emitter$1.prototype[I];return $}Emitter$1.prototype.on=Emitter$1.prototype.addEventListener=function($,I){return this._callbacks=this._callbacks||{},(this._callbacks[$]=this._callbacks[$]||[]).push(I),this},Emitter$1.prototype.once=function($,I){var U=this;this._callbacks=this._callbacks||{};function q(){U.off($,q),I.apply(this,arguments)}return q.fn=I,this.on($,q),this},Emitter$1.prototype.off=Emitter$1.prototype.removeListener=Emitter$1.prototype.removeAllListeners=Emitter$1.prototype.removeEventListener=function($,I){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var U=this._callbacks[$];if(!U)return this;if(arguments.length==1)return delete this._callbacks[$],this;for(var q,G=0;G<U.length;G++)if(q=U[G],q===I||q.fn===I){U.splice(G,1);break}return this},Emitter$1.prototype.emit=function($){this._callbacks=this._callbacks||{};var I=[].slice.call(arguments,1),U=this._callbacks[$];if(U){U=U.slice(0);for(var q=0,G=U.length;q<G;++q)U[q].apply(this,I)}return this},Emitter$1.prototype.listeners=function($){return this._callbacks=this._callbacks||{},this._callbacks[$]||[]},Emitter$1.prototype.hasListeners=function($){return!!this.listeners($).length};var Emitter=emitterComponent;function Stream(){Emitter.call(this)}Stream.prototype=new Emitter;var stream=Stream;Stream.Stream=Stream,Stream.prototype.pipe=function($,I){var U=this;function q(Q){$.writable&&$.write(Q)===!1&&U.pause&&U.pause()}U.on("data",q);function G(){U.readable&&U.resume&&U.resume()}$.on("drain",G),!$._isStdio&&(!I||I.end!==!1)&&(U.on("end",Y),U.on("close",J));var K=!1;function Y(){K||(K=!0,$.end())}function J(){K||(K=!0,typeof $.destroy=="function"&&$.destroy())}function X(Q){if(Z(),!this.hasListeners("error"))throw Q}U.on("error",X),$.on("error",X);function Z(){U.off("data",q),$.off("drain",G),U.off("end",Y),U.off("close",J),U.off("error",X),$.off("error",X),U.off("end",Z),U.off("close",Z),$.off("end",Z),$.off("close",Z)}return U.on("end",Z),U.on("close",Z),$.on("end",Z),$.on("close",Z),$.emit("pipe",U),$};var encode_1=encode,MSB$1=128,REST$1=127,MSBALL=~REST$1,INT=Math.pow(2,31);function encode($,I,U){if(Number.MAX_SAFE_INTEGER&&$>Number.MAX_SAFE_INTEGER)throw encode.bytes=0,new RangeError("Could not encode varint");I=I||[],U=U||0;for(var q=U;$>=INT;)I[U++]=$&255|MSB$1,$/=128;for(;$&MSBALL;)I[U++]=$&255|MSB$1,$>>>=7;return I[U]=$|0,encode.bytes=U-q+1,I}var decode=read,MSB=128,REST=127;function read($,q){var U=0,q=q||0,G=0,K=q,Y,J=$.length;do{if(K>=J||G>49)throw read.bytes=0,new RangeError("Could not decode varint");Y=$[K++],U+=G<28?(Y&REST)<<G:(Y&REST)*Math.pow(2,G),G+=7}while(Y>=MSB);return read.bytes=K-q,U}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function($){return $<N1?1:$<N2?2:$<N3?3:$<N4?4:$<N5?5:$<N6?6:$<N7?7:$<N8?8:$<N9?9:10},varint={encode:encode_1,decode,encodingLength:length},__dxlog_file$4="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/control-extension.ts",HEARTBEAT_RTT_WARN_THRESH=1e4,ControlExtension=class{constructor($,I,U){this.opts=$,this.localPeerId=I,this.remotePeerId=U,this._ctx=new Context({onError:q=>{this._extensionContext.close(q)}}),this.onExtensionRegistered=new Callback}async registerExtension($){await this._rpc.rpc.Control.registerExtension({name:$})}async onOpen($){this._extensionContext=$,this._rpc=createProtoRpcPeer({requested:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},exposed:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},handlers:{Control:{registerExtension:async I=>{this.onExtensionRegistered.call(I.name)},heartbeat:async I=>(log$2("received heartbeat request",{ts:I.requestTimestamp,localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:66,S:this,C:(U,q)=>U(...q)}),{requestTimestamp:I.requestTimestamp})}},port:await $.createPort("rpc",{contentType:'application/x-protobuf; messageType="dxos.rpc.Message"'}),timeout:this.opts.heartbeatTimeout}),await this._rpc.open(),scheduleTaskInterval(this._ctx,async()=>{const I=new Date;try{const U=await asyncTimeout(this._rpc.rpc.Control.heartbeat({requestTimestamp:I}),this.opts.heartbeatTimeout),q=Date.now();U.requestTimestamp instanceof Date&&(q-U.requestTimestamp.getTime()>(HEARTBEAT_RTT_WARN_THRESH<this.opts.heartbeatTimeout?HEARTBEAT_RTT_WARN_THRESH:this.opts.heartbeatTimeout/2)?log$2.warn(`heartbeat RTT for Teleport > ${HEARTBEAT_RTT_WARN_THRESH/1e3}s`,{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:103,S:this,C:(G,K)=>G(...K)}):log$2("heartbeat RTT",{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:109,S:this,C:(G,K)=>G(...K)}))}catch(U){const q=Date.now();if(U instanceof protocols.RpcClosedError){log$2("ignoring RpcClosedError in heartbeat",void 0,{F:__dxlog_file$4,L:119,S:this,C:(G,K)=>G(...K)});return}U instanceof TimeoutError?(log$2("timeout waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:123,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U)):(log$2.info("other error waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:126,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U))}},this.opts.heartbeatInterval)}async onClose($){await this._ctx.dispose(),await this._rpc.close()}async onAbort($){await this._ctx.dispose(),await this._rpc.abort()}},__dxlog_file2$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/framer.ts",FRAME_LENGTH_SIZE=2,Framer=class{constructor(){this._messageCb=void 0,this._subscribeCb=void 0,this._buffer=void 0,this._sendCallbacks=[],this._bytesSent=0,this._bytesReceived=0,this._writable=!0,this.drain=new Event$1,this._stream=new readableBrowserExports.Duplex({objectMode:!1,read:()=>{this._processResponseQueue()},write:($,I,U)=>{invariant(!this._subscribeCb,"Internal Framer bug. Concurrent writes detected.",{F:__dxlog_file2$2,L:40,S:this,A:["!this._subscribeCb","'Internal Framer bug. Concurrent writes detected.'"]}),this._bytesReceived+=$.length,this._buffer&&this._buffer.length>0?this._buffer=export_Buffer.concat([this._buffer,$]):this._buffer=$,this._messageCb?(this._popFrames(),U()):this._subscribeCb=()=>{this._popFrames(),this._subscribeCb=void 0,U()}}}),this.port={send:$=>new Promise(I=>{const U=encodeFrame($);this._bytesSent+=U.length,this._writable=this._stream.push(U),this._writable?I():this._sendCallbacks.push(I)}),subscribe:$=>{var I;return invariant(!this._messageCb,"Rpc port already has a message listener.",{F:__dxlog_file2$2,L:79,S:this,A:["!this._messageCb","'Rpc port already has a message listener.'"]}),this._messageCb=$,(I=this._subscribeCb)==null||I.call(this),()=>{this._messageCb=void 0}}}}get stream(){return this._stream}get bytesSent(){return this._bytesSent}get bytesReceived(){return this._bytesReceived}get writable(){return this._writable}_processResponseQueue(){const $=this._sendCallbacks;this._sendCallbacks=[],this._writable=!0,this.drain.emit(),$.forEach(I=>I())}_popFrames(){let $=0;for(;$<this._buffer.length;){const I=decodeFrame(this._buffer,$);if(!I)break;$+=I.bytesConsumed,this._messageCb(I.payload)}$<this._buffer.length?this._buffer=this._buffer.subarray($):this._buffer=void 0}destroy(){this._stream.readableLength>0&&log$2.info("framer destroyed while there are still read bytes in the buffer.",void 0,{F:__dxlog_file2$2,L:140,S:this,C:($,I)=>$(...I)}),this._stream.writableLength>0&&log$2.warn("framer destroyed while there are still write bytes in the buffer.",void 0,{F:__dxlog_file2$2,L:143,S:this,C:($,I)=>$(...I)}),this._stream.destroy()}},decodeFrame=($,I)=>{if($.length<I+FRAME_LENGTH_SIZE)return;const U=$.readUInt16BE(I),q=FRAME_LENGTH_SIZE+U;return $.length<I+q?void 0:{payload:$.subarray(I+FRAME_LENGTH_SIZE,I+q),bytesConsumed:q}},encodeFrame=$=>{const I=export_Buffer.allocUnsafe(FRAME_LENGTH_SIZE+$.length);return I.writeUInt16BE($.length,0),I.set($,FRAME_LENGTH_SIZE),I},__dxlog_file3$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/balancer.ts",MAX_CHUNK_SIZE=8192,Balancer=class{constructor($){this._sysChannelId=$,this._lastCallerIndex=0,this._channels=[],this._framer=new Framer,this._sendBuffers=new Map,this._receiveBuffers=new Map,this._sending=!1,this.incomingData=new Event$1,this.stream=this._framer.stream,this._channels.push($),this._framer.port.subscribe(this._processIncomingMessage.bind(this))}get bytesSent(){return this._framer.bytesSent}get bytesReceived(){return this._framer.bytesReceived}get buffersCount(){return this._sendBuffers.size}addChannel($){this._channels.push($)}pushData($,I,U){this._enqueueChunk($,I,U),this._sendChunks().catch(q=>log$2.catch(q,void 0,{F:__dxlog_file3$2,L:75,S:this,C:(G,K)=>G(...K)}))}destroy(){this._sendBuffers.size!==0&&log$2.info("destroying balancer with pending calls",void 0,{F:__dxlog_file3$2,L:80,S:this,C:($,I)=>$(...I)}),this._sendBuffers.clear(),this._framer.destroy()}_processIncomingMessage($){const{channelId:I,dataLength:U,chunk:q}=decodeChunk($,G=>!this._receiveBuffers.has(G));if(!this._receiveBuffers.has(I))q.length<U?this._receiveBuffers.set(I,{buffer:export_Buffer.from(q),msgLength:U}):this.incomingData.emit(q);else{const G=this._receiveBuffers.get(I);if(G.buffer=export_Buffer.concat([G.buffer,q]),G.buffer.length<G.msgLength)return;const K=G.buffer;this._receiveBuffers.delete(I),this.incomingData.emit(K)}}_getNextCallerId(){if(this._sendBuffers.has(this._sysChannelId))return this._sysChannelId;const $=this._lastCallerIndex;return this._lastCallerIndex=(this._lastCallerIndex+1)%this._channels.length,this._channels[$]}_enqueueChunk($,I,U){if(!this._channels.includes(U))throw new Error(`Unknown channel ${U}`);this._sendBuffers.has(U)||this._sendBuffers.set(U,[]);const q=this._sendBuffers.get(U),G=[];for(let K=0;K<$.length;K+=MAX_CHUNK_SIZE)G.push($.subarray(K,K+MAX_CHUNK_SIZE));G.forEach((K,Y)=>{const J=encodeChunk({chunk:K,channelId:U,dataLength:Y===0?$.length:void 0});q.push({msg:J,trigger:Y===G.length-1?I:void 0})})}_getNextChunk(){let $;for(;this._sendBuffers.size>0;){const I=this._getNextCallerId(),U=this._sendBuffers.get(I);if(U&&($=U.shift(),!!$))return U.length===0&&this._sendBuffers.delete(I),$}return null}async _sendChunks(){var I,U;if(this._sending)return;this._sending=!0;let $;for($=this._getNextChunk();$;){this._framer.writable||(log$2("PAUSE for drain",void 0,{F:__dxlog_file3$2,L:179,S:this,C:(q,G)=>q(...G)}),await this._framer.drain.waitForCount(1),log$2("RESUME for drain",void 0,{F:__dxlog_file3$2,L:181,S:this,C:(q,G)=>q(...G)}));try{await this._framer.port.send($.msg),(I=$.trigger)==null||I.wake()}catch(q){log$2("Error sending chunk",{err:q},{F:__dxlog_file3$2,L:187,S:this,C:(G,K)=>G(...K)}),(U=$.trigger)==null||U.throw(q)}$=this._getNextChunk()}invariant(this._sendBuffers.size===0,"sendBuffers not empty",{F:__dxlog_file3$2,L:192,S:this,A:["this._sendBuffers.size === 0","'sendBuffers not empty'"]}),this._sending=!1}},encodeChunk=({channelId:$,dataLength:I,chunk:U})=>{const q=varint.encodingLength($),G=I?varint.encodingLength(I):0,K=export_Buffer.allocUnsafe(q+G+U.length);return varint.encode($,K),I&&varint.encode(I,K,q),K.set(U,q+G),K},decodeChunk=($,I)=>{const U=varint.decode($);let q,G=varint.decode.bytes;I(U)&&(q=varint.decode($,G),G+=varint.decode.bytes);const K=$.subarray(G);return{channelId:U,dataLength:q,chunk:K}};function _ts_decorate$3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts",Command=protocols.schema.getCodecForType("dxos.mesh.muxer.Command"),DEFAULT_SEND_COMMAND_TIMEOUT=6e4,DESTROY_COMMAND_SEND_TIMEOUT=5e3,STATS_INTERVAL=1e3,MAX_SAFE_FRAME_SIZE=1e6,SYSTEM_CHANNEL_ID=0,GRACEFUL_CLOSE_TIMEOUT=3e3,Muxer=class{constructor(){this._balancer=new Balancer(SYSTEM_CHANNEL_ID),this._channelsByLocalId=new Map,this._channelsByTag=new Map,this._ctx=new Context,this._nextId=1,this._closing=!1,this._destroying=!1,this._disposed=!1,this._lastStats=void 0,this._lastChannelStats=new Map,this.afterClosed=new Event$1,this.statsUpdated=new Event$1,this.stream=this._balancer.stream,this._balancer.incomingData.on(async $=>{await this._handleCommand(Command.decode($))})}setSessionId($){this._sessionId=$}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}async createStream($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:151,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});const q=new readableBrowserExports.Duplex({write:(G,K,Y)=>{this._sendData(U,G).then(()=>Y()).catch(Y)},read:()=>{}});U.push=G=>{U.stats.bytesReceived+=G.length,q.push(G)},U.destroy=G=>{G&&q.listeners("error").length>0?q.destroy(G):q.destroy()};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(G){throw this._destroyChannel(U,G),G}return q}async createPort($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:211,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});let q=[],G;U.push=Y=>{U.stats.bytesReceived+=Y.length,G?G(Y):q.push(Y)};const K={send:async(Y,J)=>{await this._sendData(U,Y,J)},subscribe:Y=>{invariant(!G,"Only one subscriber is allowed",{F:__dxlog_file4$2,L:233,S:this,A:["!callback","'Only one subscriber is allowed'"]}),G=Y;for(const J of q)Y(J);q=[]}};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(Y){throw this._destroyChannel(U,Y),Y}return K}async close($){if(this._destroying){log$2("already destroying, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:266,S:this,C:(I,U)=>I(...U)});return}if(this._closing){log$2("already closing, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:270,S:this,C:(I,U)=>I(...U)});return}this._closing=!0,await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID,DESTROY_COMMAND_SEND_TIMEOUT).catch(async I=>{log$2("error sending close command",{err:I},{F:__dxlog_file4$2,L:285,S:this,C:(U,q)=>U(...q)}),await this._dispose(I)}),await asyncTimeout(this._dispose($),GRACEFUL_CLOSE_TIMEOUT,new protocols.TimeoutError("gracefully closing muxer"))}async destroy($){if(this._destroying){log$2("already destroying, ignoring destroy request",void 0,{F:__dxlog_file4$2,L:298,S:this,C:(I,U)=>I(...U)});return}this._destroying=!0,this._ctx.dispose(),this._closing?(log$2("destroy cancelling graceful close",void 0,{F:__dxlog_file4$2,L:304,S:this,C:(I,U)=>I(...U)}),this._closing=!1):await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID).catch(async I=>{log$2("error sending courtesy close command",{err:I},{F:__dxlog_file4$2,L:317,S:this,C:(U,q)=>U(...q)})}),this._dispose($).catch(I=>{log$2("error disposing after destroy",{err:I},{F:__dxlog_file4$2,L:322,S:this,C:(U,q)=>U(...q)})})}async _dispose($){var I;if(this._disposed){log$2("already destroyed, ignoring dispose request",void 0,{F:__dxlog_file4$2,L:330,S:this,C:(U,q)=>U(...q)});return}this._ctx.dispose(),await this._balancer.destroy();for(const U of this._channelsByTag.values())(I=U.destroy)==null||I.call(U,$);this._disposed=!0,await this._emitStats(),this.afterClosed.emit($),this._channelsByLocalId.clear(),this._channelsByTag.clear()}async _handleCommand($){if(this._disposed){log$2.warn("Received command after disposed",{cmd:$},{F:__dxlog_file4$2,L:353,S:this,C:(I,U)=>I(...U)});return}if($.close){this._closing?log$2("received close from peer, already closing",void 0,{F:__dxlog_file4$2,L:362,S:this,C:(I,U)=>I(...U)}):(log$2("received peer close, initiating my own graceful close",void 0,{F:__dxlog_file4$2,L:359,S:this,C:(I,U)=>I(...U)}),await this.close(new Error("received peer close")));return}if($.openChannel){const I=this._getOrCreateStream({tag:$.openChannel.tag,contentType:$.openChannel.contentType});I.remoteId=$.openChannel.id;for(const U of I.buffer)await this._sendCommand({data:{channelId:I.remoteId,data:U}},I.id);I.buffer=[]}else if($.data){const I=this._channelsByLocalId.get($.data.channelId)??failUndefined();if(!I.push){log$2.warn("Received data for channel before it was opened",{tag:I.tag},{F:__dxlog_file4$2,L:391,S:this,C:(U,q)=>U(...q)});return}I.push($.data.data)}}async _sendCommand($,I=-1,U=DEFAULT_SEND_COMMAND_TIMEOUT){if(this._disposed){log$2.info("ignoring sendCommand after disposed",{cmd:$},{F:__dxlog_file4$2,L:400,S:this,C:(q,G)=>q(...G)});return}try{const q=new Trigger;this._balancer.pushData(Command.encode($),q,I),await q.wait({timeout:U})}catch(q){await this.destroy(q)}}_getOrCreateStream($){this._channelsByTag.size===0&&scheduleTaskInterval(this._ctx,async()=>this._emitStats(),STATS_INTERVAL);let I=this._channelsByTag.get($.tag);return I||(I={id:this._nextId++,remoteId:null,tag:$.tag,contentType:$.contentType,buffer:[],push:null,destroy:null,stats:{bytesSent:0,bytesReceived:0}},this._channelsByTag.set(I.tag,I),this._channelsByLocalId.set(I.id,I),this._balancer.addChannel(I.id)),I}async _sendData($,I,U){if(I.length>MAX_SAFE_FRAME_SIZE&&log$2.warn("frame size exceeds maximum safe value",{size:I.length,threshold:MAX_SAFE_FRAME_SIZE},{F:__dxlog_file4$2,L:441,S:this,C:(q,G)=>q(...G)}),$.stats.bytesSent+=I.length,$.remoteId===null){$.buffer.push(I);return}await this._sendCommand({data:{channelId:$.remoteId,data:I}},$.id,U)}_destroyChannel($,I){$.destroy&&$.destroy(I),this._channelsByLocalId.delete($.id),this._channelsByTag.delete($.tag)}async _emitStats(){if(this._disposed||this._destroying){if(!this._lastStats)return;const K=this._lastStats;this._lastStats=void 0,K.readBufferSize=0,K.writeBufferSize=0;for(const Y of K.channels)Y.writeBufferSize=0;this.statsUpdated.emit(K),this._lastChannelStats.clear();return}const $=this._balancer.bytesSent,I=this._balancer.bytesReceived,U=Date.now(),q=this._lastStats?(U-this._lastStats.timestamp)/1e3:0,G=(K,Y)=>Y?{bytesSentRate:q?(K.bytesSent-Y.bytesSent)/q:void 0,bytesReceivedRate:q?(K.bytesReceived-Y.bytesReceived)/q:void 0}:{};this._lastStats={timestamp:U,channels:Array.from(this._channelsByTag.values()).map(K=>{const Y={id:K.id,tag:K.tag,contentType:K.contentType,writeBufferSize:K.buffer.length,bytesSent:K.stats.bytesSent,bytesReceived:K.stats.bytesReceived,...G(K.stats,this._lastChannelStats.get(K.id))};return this._lastChannelStats.set(K.id,Y),Y}),bytesSent:$,bytesReceived:I,...G({bytesSent:$,bytesReceived:I},this._lastStats),readBufferSize:this._balancer.stream.readableLength,writeBufferSize:this._balancer.stream.writableLength},this.statsUpdated.emit(this._lastStats)}};_ts_decorate$3([logInfo],Muxer.prototype,"sessionIdString",null);function _ts_decorate2$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$1="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/teleport.ts",CONTROL_HEARTBEAT_INTERVAL=1e4,CONTROL_HEARTBEAT_TIMEOUT=6e4,Teleport=class{constructor({initiator:$,localPeerId:I,remotePeerId:U}){this._ctx=new Context({onError:q=>{this.destroy(q).catch(()=>{log$2.error("Error during destroy",q,{F:__dxlog_file5$1,L:39,S:this,C:(G,K)=>G(...K)})})}}),this._muxer=new Muxer,this._extensions=new Map,this._remoteExtensions=new Set,this._open=!1,this._destroying=!1,this._aborting=!1,invariant(typeof $=="boolean",void 0,{F:__dxlog_file5$1,L:56,S:this,A:["typeof initiator === 'boolean'",""]}),invariant(PublicKey.isPublicKey(I),void 0,{F:__dxlog_file5$1,L:57,S:this,A:["PublicKey.isPublicKey(localPeerId)",""]}),invariant(PublicKey.isPublicKey(U),void 0,{F:__dxlog_file5$1,L:58,S:this,A:["PublicKey.isPublicKey(remotePeerId)",""]}),this.initiator=$,this.localPeerId=I,this.remotePeerId=U,this._control=new ControlExtension({heartbeatInterval:CONTROL_HEARTBEAT_INTERVAL,heartbeatTimeout:CONTROL_HEARTBEAT_TIMEOUT,onTimeout:()=>{this._destroying||this._aborting||(log$2.info("abort teleport due to onTimeout in ControlExtension",void 0,{F:__dxlog_file5$1,L:71,S:this,C:(q,G)=>q(...G)}),this.abort(new protocols.TimeoutError("control extension")).catch(q=>log$2.catch(q,void 0,{F:__dxlog_file5$1,L:72,S:this,C:(G,K)=>G(...K)})))}},this.localPeerId,this.remotePeerId),this._control.onExtensionRegistered.set(async q=>{if(log$2("remote extension",{name:q},{F:__dxlog_file5$1,L:80,S:this,C:(G,K)=>G(...K)}),invariant(!this._remoteExtensions.has(q),"Remote extension already exists",{F:__dxlog_file5$1,L:81,S:this,A:["!this._remoteExtensions.has(name)","'Remote extension already exists'"]}),this._remoteExtensions.add(q),this._extensions.has(q))try{await this._openExtension(q)}catch(G){await this.destroy(G)}}),this._muxer.stream.on("close",async()=>{if(this._destroying||this._aborting){log$2("destroy teleport due to muxer stream close, skipping due to already destroying/aborting",void 0,{F:__dxlog_file5$1,L:97,S:this,C:(q,G)=>q(...G)});return}await this.destroy()}),this._muxer.stream.on("error",async q=>{await this.destroy(q)}),this._muxer.statsUpdated.on(q=>{log$2.trace("dxos.mesh.teleport.stats",{localPeerId:I,remotePeerId:U,bytesSent:q.bytesSent,bytesSentRate:q.bytesSentRate,bytesReceived:q.bytesReceived,bytesReceivedRate:q.bytesReceivedRate,channels:q.channels},{F:__dxlog_file5$1,L:110,S:this,C:(G,K)=>G(...K)})})}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}get stream(){return this._muxer.stream}get stats(){return this._muxer.statsUpdated}async open($=PublicKey.random()){this._sessionId=$,log$2("open",void 0,{F:__dxlog_file5$1,L:144,S:this,C:(I,U)=>I(...U)}),this._setExtension("dxos.mesh.teleport.control",this._control),await this._openExtension("dxos.mesh.teleport.control"),this._open=!0,this._muxer.setSessionId($)}async close($){await this.destroy($)}async abort($){if(!(this._aborting||this._destroying)&&(this._aborting=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onAbort($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:173,S:this,C:(q,G)=>q(...G)})}await this._muxer.destroy($)}}async destroy($){if(!(this._destroying||this._aborting)&&(this._destroying=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onClose($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:197,S:this,C:(q,G)=>q(...G)})}await this._muxer.close()}}addExtension($,I){if(!this._open)throw new Error("Not open");log$2("addExtension",{name:$},{F:__dxlog_file5$1,L:209,S:this,C:(U,q)=>U(...q)}),this._setExtension($,I),scheduleTask(this._ctx,async()=>{try{await this._control.registerExtension($)}catch(U){if(U instanceof protocols.RpcClosedError)return;throw U}}),this._remoteExtensions.has($)&&scheduleTask(this._ctx,async()=>{await this._openExtension($)})}_setExtension($,I){invariant(!$.includes("/"),"Invalid extension name",{F:__dxlog_file5$1,L:233,S:this,A:["!extensionName.includes('/')","'Invalid extension name'"]}),invariant(!this._extensions.has($),"Extension already exists",{F:__dxlog_file5$1,L:234,S:this,A:["!this._extensions.has(extensionName)","'Extension already exists'"]}),this._extensions.set($,I)}async _openExtension($){log$2("open extension",{extensionName:$},{F:__dxlog_file5$1,L:239,S:this,C:(q,G)=>q(...G)});const I=this._extensions.get($)??failUndefined(),U={initiator:this.initiator,localPeerId:this.localPeerId,remotePeerId:this.remotePeerId,createPort:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:247,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createPort(`${$}/${q}`,G)),createStream:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:251,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createStream(`${$}/${q}`,G)),close:q=>{runInContextAsync(this._ctx,async()=>{await this.close(q)})}};await I.onOpen(U),log$2("extension opened",{extensionName:$},{F:__dxlog_file5$1,L:262,S:this,C:(q,G)=>q(...G)})}};_ts_decorate2$2([logInfo],Teleport.prototype,"sessionIdString",null),_ts_decorate2$2([synchronized],Teleport.prototype,"abort",null),_ts_decorate2$2([synchronized],Teleport.prototype,"destroy",null);var __require=($=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy($,{get:(I,U)=>(typeof require<"u"?require:I)[U]}):$)(function($){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')});function _ts_decorate$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$3="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection.ts",STARTING_SIGNALLING_DELAY=10,TRANSPORT_CONNECTION_TIMEOUT=1e4,TRANSPORT_STATS_INTERVAL=5e3,MAX_SIGNALLING_DELAY=300,ConnectionState;(function($){$.CREATED="CREATED",$.INITIAL="INITIAL",$.CONNECTING="CONNECTING",$.CONNECTED="CONNECTED",$.CLOSING="CLOSING",$.CLOSED="CLOSED",$.ABORTING="ABORTING",$.ABORTED="ABORTED"})(ConnectionState||(ConnectionState={}));var Connection=class{constructor($,I,U,q,G,K,Y,J,X){this.topic=$,this.ownId=I,this.remoteId=U,this.sessionId=q,this.initiator=G,this._signalMessaging=K,this._protocol=Y,this._transportFactory=J,this._callbacks=X,this._ctx=new Context,this.connectedTimeoutContext=new Context,this._state="CREATED",this._incomingSignalBuffer=[],this._outgoingSignalBuffer=[],this.stateChanged=new Event$1,this.errors=new ErrorStream,this._instanceId=PublicKey.random().toHex(),this.transportStats=new Event$1,this._signalSendTask=new DeferredTask(this._ctx,async()=>{await this._flushSignalBuffer()}),this._signallingDelay=STARTING_SIGNALLING_DELAY,log$2.trace("dxos.mesh.connection.construct",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:134,S:this,C:(Z,Q)=>Z(...Q)})}get sessionIdString(){return this.sessionId.truncate()}get state(){return this._state}get transport(){return this._transport}get protocol(){return this._protocol}async openConnection(){invariant(this._state==="INITIAL","Invalid state.",{F:__dxlog_file$3,L:164,S:this,A:["this._state === ConnectionState.INITIAL","'Invalid state.'"]}),log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file$3,L:165,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.connection.open",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:166,S:this,C:($,I)=>$(...I)}),this._changeState("CONNECTING"),this._protocol.open(this.sessionId).catch($=>{this.errors.raise($)}),this._protocol.stream.on("close",()=>{log$2("protocol stream closed",void 0,{F:__dxlog_file$3,L:183,S:this,C:($,I)=>$(...I)}),this.close(new protocols.ProtocolError("protocol stream closed")).catch($=>this.errors.raise($))}),scheduleTask(this.connectedTimeoutContext,async()=>{log$2.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect, aborting`,void 0,{F:__dxlog_file$3,L:190,S:this,C:($,I)=>$(...I)}),await this.abort(new protocols.TimeoutError(`${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect`)).catch($=>this.errors.raise($))},TRANSPORT_CONNECTION_TIMEOUT),invariant(!this._transport,void 0,{F:__dxlog_file$3,L:198,S:this,A:["!this._transport",""]}),this._transport=this._transportFactory.createTransport({initiator:this.initiator,stream:this._protocol.stream,sendSignal:async $=>this._sendSignal($),sessionId:this.sessionId}),await this._transport.open(),this._transport.connected.once(async()=>{var $,I;this._changeState("CONNECTED"),await this.connectedTimeoutContext.dispose(),(I=($=this._callbacks)==null?void 0:$.onConnected)==null||I.call($),scheduleTaskInterval(this._ctx,async()=>this._emitTransportStats(),TRANSPORT_STATS_INTERVAL)}),this._transport.closed.once(()=>{this._transport=void 0,log$2("abort triggered by transport close",void 0,{F:__dxlog_file$3,L:218,S:this,C:($,I)=>$(...I)}),this.abort().catch($=>this.errors.raise($))}),this._transport.errors.handle(async $=>{log$2("transport error:",{err:$},{F:__dxlog_file$3,L:223,S:this,C:(I,U)=>I(...U)}),this.closeReason||(this.closeReason=$==null?void 0:$.message),$ instanceof protocols.ConnectionResetError?(log$2.info("aborting due to transport ConnectionResetError",void 0,{F:__dxlog_file$3,L:230,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.ConnectivityError?(log$2.info("aborting due to transport ConnectivityError",void 0,{F:__dxlog_file$3,L:233,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.UnknownProtocolError&&log$2.warn("unsure what to do with UnknownProtocolError, will keep on truckin",{err:$},{F:__dxlog_file$3,L:236,S:this,C:(I,U)=>I(...U)}),this._state!=="CLOSED"&&this._state!=="CLOSING"&&(await this.connectedTimeoutContext.dispose(),this.errors.raise($))});for(const $ of this._incomingSignalBuffer)this._transport.onSignal($);this._incomingSignalBuffer=[],log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file$3,L:252,S:this,C:($,I)=>$(...I)})}async abort($){var I,U,q;if(log$2("aborting...",{err:$},{F:__dxlog_file$3,L:259,S:this,C:(G,K)=>G(...K)}),this._state==="CLOSED"||this._state==="ABORTED"){log$2(`abort ignored: already ${this._state}`,this.closeReason,{F:__dxlog_file$3,L:261,S:this,C:(G,K)=>G(...K)});return}await this.connectedTimeoutContext.dispose(),this._changeState("ABORTING"),this.closeReason||(this.closeReason=$==null?void 0:$.message),await this._ctx.dispose();try{log$2("aborting protocol... ",void 0,{F:__dxlog_file$3,L:275,S:this,C:(G,K)=>G(...K)}),await this._protocol.abort()}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:278,S:this,C:(K,Y)=>K(...Y)})}try{await((I=this._transport)==null?void 0:I.close())}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:285,S:this,C:(K,Y)=>K(...Y)})}try{(q=(U=this._callbacks)==null?void 0:U.onClosed)==null||q.call(U,$)}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:291,S:this,C:(K,Y)=>K(...Y)})}this._changeState("ABORTED")}async close($){var U,q,G,K;if(this.closeReason?this.closeReason+=`; ${$==null?void 0:$.message}`:this.closeReason=$==null?void 0:$.message,this._state==="CLOSED"||this._state==="ABORTING"||this._state==="ABORTED")return;const I=this._state;if(this._changeState("CLOSING"),await this.connectedTimeoutContext.dispose(),await this._ctx.dispose(),log$2("closing...",{peerId:this.ownId},{F:__dxlog_file$3,L:316,S:this,C:(Y,J)=>Y(...J)}),I==="CONNECTED"){try{await this._protocol.close()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:323,S:this,C:(J,X)=>J(...X)})}try{await((U=this._transport)==null?void 0:U.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:330,S:this,C:(J,X)=>J(...X)})}}else{log$2.info(`graceful close requested when we were in ${I} state? aborting`,void 0,{F:__dxlog_file$3,L:333,S:this,C:(Y,J)=>Y(...J)});try{await this._protocol.abort()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:337,S:this,C:(J,X)=>J(...X)})}try{await((q=this._transport)==null?void 0:q.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:342,S:this,C:(J,X)=>J(...X)})}}log$2("closed",{peerId:this.ownId},{F:__dxlog_file$3,L:346,S:this,C:(Y,J)=>Y(...J)}),this._changeState("CLOSED"),(K=(G=this._callbacks)==null?void 0:G.onClosed)==null||K.call(G,$)}_sendSignal($){this._outgoingSignalBuffer.push($),this._signalSendTask.schedule()}async _flushSignalBuffer(){var $;if(this._outgoingSignalBuffer.length!==0)try{await cancelWithContext(this._ctx,sleep(this._signallingDelay)),this._signallingDelay=Math.min(this._signallingDelay*2,MAX_SIGNALLING_DELAY);const I=[...this._outgoingSignalBuffer];this._outgoingSignalBuffer.length=0,await this._signalMessaging.signal({author:this.ownId,recipient:this.remoteId,sessionId:this.sessionId,topic:this.topic,data:{signalBatch:{signals:I}}})}catch(I){if(I instanceof protocols.CancelledError||I instanceof Error&&(($=I.message)!=null&&$.includes("CANCELLED")))return;log$2.info("signal message failed to deliver",{err:I},{F:__dxlog_file$3,L:384,S:this,C:(U,q)=>U(...q)}),await this.close(new protocols.ConnectivityError("signal message failed to deliver",I))}}async signal($){var U,q;if(invariant($.sessionId,void 0,{F:__dxlog_file$3,L:393,S:this,A:["msg.sessionId",""]}),!$.sessionId.equals(this.sessionId)){log$2("dropping signal for incorrect session id",void 0,{F:__dxlog_file$3,L:395,S:this,C:(G,K)=>G(...K)});return}invariant($.data.signal||$.data.signalBatch,void 0,{F:__dxlog_file$3,L:398,S:this,A:["msg.data.signal || msg.data.signalBatch",""]}),invariant((U=$.author)==null?void 0:U.equals(this.remoteId),void 0,{F:__dxlog_file$3,L:399,S:this,A:["msg.author?.equals(this.remoteId)",""]}),invariant((q=$.recipient)==null?void 0:q.equals(this.ownId),void 0,{F:__dxlog_file$3,L:400,S:this,A:["msg.recipient?.equals(this.ownId)",""]});const I=$.data.signalBatch?$.data.signalBatch.signals??[]:[$.data.signal];for(const G of I)G&&(["CREATED","INITIAL"].includes(this.state)?(log$2("buffered signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:409,S:this,C:(K,Y)=>K(...Y)}),this._incomingSignalBuffer.push(G)):(invariant(this._transport,"Connection not ready to accept signals.",{F:__dxlog_file$3,L:412,S:this,A:["this._transport","'Connection not ready to accept signals.'"]}),log$2("received signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:413,S:this,C:(K,Y)=>K(...Y)}),await this._transport.onSignal(G)))}initiate(){this._changeState("INITIAL")}_changeState($){log$2("stateChanged",{from:this._state,to:$,peerId:this.ownId},{F:__dxlog_file$3,L:424,S:this,C:(I,U)=>I(...U)}),invariant($!==this._state,"Already in this state.",{F:__dxlog_file$3,L:425,S:this,A:["state !== this._state","'Already in this state.'"]}),this._state=$,this.stateChanged.emit($)}async _emitTransportStats(){var I;const $=await((I=this.transport)==null?void 0:I.getStats());$&&this.transportStats.emit($)}};_ts_decorate$2([logInfo],Connection.prototype,"sessionIdString",null),_ts_decorate$2([synchronized],Connection.prototype,"abort",null),_ts_decorate$2([synchronized],Connection.prototype,"close",null);var __dxlog_file2$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts",SwarmMessage=protocols.schema.getCodecForType("dxos.mesh.swarm.SwarmMessage"),SwarmMessenger=class{constructor({sendMessage:$,onSignal:I,onOffer:U,topic:q}){this._ctx=new Context,this._offerRecords=new ComplexMap(G=>G.toHex()),this._sendMessage=$,this._onSignal=I,this._onOffer=U,this._topic=q}async receiveMessage({author:$,recipient:I,payload:U}){var G,K,Y,J;if(U.type_url!=="dxos.mesh.swarm.SwarmMessage")return;const q=SwarmMessage.decode(U.value);this._topic.equals(q.topic)&&(log$2("received",{from:$,to:I,msg:q},{F:__dxlog_file2$1,L:69,S:this,C:(X,Z)=>X(...Z)}),(G=q.data)!=null&&G.offer?await this._handleOffer({author:$,recipient:I,message:q}):(K=q.data)!=null&&K.answer?await this._resolveAnswers(q):(Y=q.data)!=null&&Y.signal?await this._handleSignal({author:$,recipient:I,message:q}):(J=q.data)!=null&&J.signalBatch?await this._handleSignal({author:$,recipient:I,message:q}):log$2.warn("unknown message",{message:q},{F:__dxlog_file2$1,L:80,S:this,C:(X,Z)=>X(...Z)}))}async signal($){var I,U;invariant(((I=$.data)==null?void 0:I.signal)||((U=$.data)==null?void 0:U.signalBatch),"Invalid message",{F:__dxlog_file2$1,L:85,S:this,A:["message.data?.signal || message.data?.signalBatch","'Invalid message'"]}),await this._sendReliableMessage({author:$.author,recipient:$.recipient,message:$})}async offer($){const I={...$,messageId:PublicKey.random()};return new Promise((U,q)=>{this._offerRecords.set(I.messageId,{resolve:U}),this._sendReliableMessage({author:$.author,recipient:$.recipient,message:I}).catch(G=>q(G))})}async _sendReliableMessage({author:$,recipient:I,message:U}){const q={...U,messageId:U.messageId??PublicKey.random()};log$2("sending",{from:$,to:I,msg:q},{F:__dxlog_file2$1,L:123,S:this,C:(G,K)=>G(...K)}),await this._sendMessage({author:$,recipient:I,payload:{type_url:"dxos.mesh.swarm.SwarmMessage",value:SwarmMessage.encode(q)}})}async _resolveAnswers($){var U,q,G;invariant((q=(U=$.data)==null?void 0:U.answer)==null?void 0:q.offerMessageId,"No offerMessageId",{F:__dxlog_file2$1,L:135,S:this,A:["message.data?.answer?.offerMessageId","'No offerMessageId'"]});const I=this._offerRecords.get($.data.answer.offerMessageId);I&&(this._offerRecords.delete($.data.answer.offerMessageId),invariant((G=$.data)==null?void 0:G.answer,"No answer",{F:__dxlog_file2$1,L:139,S:this,A:["message.data?.answer","'No answer'"]}),log$2("resolving",{answer:$.data.answer},{F:__dxlog_file2$1,L:140,S:this,C:(K,Y)=>K(...Y)}),I.resolve($.data.answer))}async _handleOffer({author:$,recipient:I,message:U}){invariant(U.data.offer,"No offer",{F:__dxlog_file2$1,L:154,S:this,A:["message.data.offer","'No offer'"]});const q={author:$,recipient:I,...U,data:{offer:U.data.offer}},G=await this._onOffer(q);G.offerMessageId=U.messageId;try{await this._sendReliableMessage({author:I,recipient:$,message:{topic:U.topic,sessionId:U.sessionId,data:{answer:G}}})}catch(K){K instanceof protocols.TimeoutError?log$2.info("timeout sending answer to offer",{err:K},{F:__dxlog_file2$1,L:175,S:this,C:(Y,J)=>Y(...J)}):log$2.info("error sending answer to offer",{err:K},{F:__dxlog_file2$1,L:177,S:this,C:(Y,J)=>Y(...J)})}}async _handleSignal({author:$,recipient:I,message:U}){invariant(U.messageId,void 0,{F:__dxlog_file2$1,L:191,S:this,A:["message.messageId",""]}),invariant(U.data.signal||U.data.signalBatch,"Invalid message",{F:__dxlog_file2$1,L:192,S:this,A:["message.data.signal || message.data.signalBatch","'Invalid message'"]});const q={author:$,recipient:I,...U,data:{signal:U.data.signal,signalBatch:U.data.signalBatch}};await this._onSignal(q)}};function _ts_decorate2$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file3$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts",ConnectionDisplacedError=class extends protocols.SystemError{constructor(){super("Connection displaced by remote initiator.")}},CONNECTION_COUNTS_STABLE_AFTER=5e3,Peer=class{constructor($,I,U,q,G,K,Y,J){this.id=$,this.topic=I,this.localPeerId=U,this._signalMessaging=q,this._protocolProvider=G,this._transportFactory=K,this._connectionLimiter=Y,this._callbacks=J,this._availableAfter=0,this.availableToConnect=!0,this._ctx=new Context,this.advertizing=!1,this.initiating=!1,this.connectionDisplaced=new Event$1}async onOffer($){var U;const I=$.author;if(this.connection&&![ConnectionState.CREATED,ConnectionState.INITIAL,ConnectionState.CONNECTING].includes(this.connection.state))return log$2.info(`received offer when connection already in ${this.connection.state} state`,void 0,{F:__dxlog_file3$1,L:114,S:this,C:(q,G)=>q(...G)}),{accept:!1};if(this.connection||this.initiating)if(I.toHex()<this.localPeerId.toHex())log$2("close local connection",{localPeerId:this.id,topic:this.topic,remotePeerId:this.localPeerId,sessionId:(U=this.connection)==null?void 0:U.sessionId},{F:__dxlog_file3$1,L:123,S:this,C:(q,G)=>q(...G)}),this.connection&&await this.closeConnection(new ConnectionDisplacedError);else return{accept:!1};if(await this._callbacks.onOffer(I)&&!this.connection){invariant($.sessionId,void 0,{F:__dxlog_file3$1,L:143,S:this,A:["message.sessionId",""]});const q=this._createConnection(!1,$.sessionId);try{await this._connectionLimiter.connecting($.sessionId),q.initiate(),await q.openConnection()}catch(G){G instanceof protocols.CancelledError||log$2.info("connection error",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,err:G},{F:__dxlog_file3$1,L:153,S:this,C:(K,Y)=>K(...Y)}),await this.closeConnection(G)}return{accept:!0}}return{accept:!1}}async initiateConnection(){invariant(!this.initiating,"Initiation in progress.",{F:__dxlog_file3$1,L:170,S:this,A:["!this.initiating","'Initiation in progress.'"]}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3$1,L:171,S:this,A:["!this.connection","'Already connected.'"]});const $=PublicKey.random();log$2("initiating...",{id:this.id,topic:this.topic,peerId:this.id,sessionId:$},{F:__dxlog_file3$1,L:173,S:this,C:(q,G)=>q(...G)});const I=this._createConnection(!0,$);this.initiating=!0;let U;try{if(await this._connectionLimiter.connecting($),I.initiate(),U=await this._signalMessaging.offer({author:this.localPeerId,recipient:this.id,sessionId:$,topic:this.topic,data:{offer:{}}}),log$2("received",{answer:U,topic:this.topic,ownId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:190,S:this,C:(q,G)=>q(...G)}),I.state!==ConnectionState.INITIAL){log$2("ignoring response",void 0,{F:__dxlog_file3$1,L:192,S:this,C:(q,G)=>q(...G)});return}}catch(q){throw log$2("initiation error: send offer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:196,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{if(!U.accept){this._callbacks.onRejected();return}}catch(q){throw log$2("initiation error: accept answer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:209,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{log$2("opening connection as initiator",void 0,{F:__dxlog_file3$1,L:222,S:this,C:(q,G)=>q(...G)}),await I.openConnection(),this._callbacks.onAccepted()}catch(q){throw log$2("initiation error: open connection",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:226,S:this,C:(G,K)=>G(...K)}),log$2.warn("closing connection due to unhandled error on openConnection",{err:q},{F:__dxlog_file3$1,L:233,S:this,C:(G,K)=>G(...K)}),await this.closeConnection(q),q}finally{this.initiating=!1}}_createConnection($,I){var q;log$2("creating connection",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,sessionId:I},{F:__dxlog_file3$1,L:247,S:this,C:(G,K)=>G(...K)}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3$1,L:254,S:this,A:["!this.connection","'Already connected.'"]});const U=new Connection(this.topic,this.localPeerId,this.id,I,$,this._signalMessaging,this._protocolProvider({initiator:$,localPeerId:this.localPeerId,remotePeerId:this.id,topic:this.topic}),this._transportFactory,{onConnected:()=>{this.availableToConnect=!0,this._lastConnectionTime=Date.now(),this._callbacks.onConnected(),this._connectionLimiter.doneConnecting(I),log$2.trace("dxos.mesh.connection.connected",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3$1,L:273,S:this,C:(G,K)=>G(...K)})},onClosed:G=>{log$2("connection closed",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$},{F:__dxlog_file3$1,L:282,S:this,C:(K,Y)=>K(...Y)}),this._connectionLimiter.doneConnecting(I),invariant(this.connection===U,"Connection mismatch (race condition).",{F:__dxlog_file3$1,L:287,S:this,A:["this.connection === connection","'Connection mismatch (race condition).'"]}),log$2.trace("dxos.mesh.connection.closed",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3$1,L:289,S:this,C:(K,Y)=>K(...Y)}),G instanceof ConnectionDisplacedError?this.connectionDisplaced.emit(this.connection):(this._lastConnectionTime&&this._lastConnectionTime+CONNECTION_COUNTS_STABLE_AFTER<Date.now()?this._availableAfter=0:(this.availableToConnect=!1,this._availableAfter=increaseInterval(this._availableAfter)),this._callbacks.onDisconnected(),scheduleTask(this._connectionCtx,()=>{this.availableToConnect=!0,this._callbacks.onPeerAvailable()},this._availableAfter)),this.connection=void 0}});return this._callbacks.onInitiated(U),(q=this._connectionCtx)==null||q.dispose(),this._connectionCtx=this._ctx.derive(),U.errors.handle(G=>{log$2.info("connection error, closing",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,err:G},{F:__dxlog_file3$1,L:329,S:this,C:(K,Y)=>K(...Y)}),log$2.trace("dxos.mesh.connection.error",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$,err:G},{F:__dxlog_file3$1,L:336,S:this,C:(K,Y)=>K(...Y)}),this.closeConnection(G)}),this.connection=U,U}async closeConnection($){if(!this.connection)return;const I=this.connection;log$2("closing...",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3$1,L:361,S:this,C:(U,q)=>U(...q)}),await I.close($),log$2("closed",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3$1,L:367,S:this,C:(U,q)=>U(...q)})}async onSignal($){if(!this.connection){log$2("dropping signal message for non-existent connection",{message:$},{F:__dxlog_file3$1,L:372,S:this,C:(I,U)=>I(...U)});return}await this.connection.signal($)}async destroy($){var I;await this._ctx.dispose(),log$2("Destroying peer",{peerId:this.id,topic:this.topic},{F:__dxlog_file3$1,L:382,S:this,C:(U,q)=>U(...q)}),await((I=this==null?void 0:this.connection)==null?void 0:I.close($))}};_ts_decorate2$1([synchronized],Peer.prototype,"destroy",null);var increaseInterval=$=>$===0?50:$<500?500:$<1e3?1e3:$<5e3?5e3:1e4;function _ts_decorate3$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts",INITIATION_DELAY=100,getClassName=$=>Object.getPrototypeOf($).constructor.name,Swarm=class{constructor($,I,U,q,G,K,Y,J,X=INITIATION_DELAY){this._topic=$,this._ownPeerId=I,this._topology=U,this._protocolProvider=q,this._messenger=G,this._transportFactory=K,this._label=Y,this._connectionLimiter=J,this._initiationDelay=X,this._ctx=new Context,this._listeningHandle=void 0,this._peers=new ComplexMap(PublicKey.hash),this._instanceId=PublicKey.random().toHex(),this.connectionAdded=new Event$1,this.disconnected=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.begin({id:this._instanceId,data:{topic:this._topic.toHex(),peerId:this._ownPeerId.toHex()}}),{F:__dxlog_file4$1,L:89,S:this,C:(Z,Q)=>Z(...Q)}),log$2("creating swarm",{peerId:I},{F:__dxlog_file4$1,L:93,S:this,C:(Z,Q)=>Z(...Q)}),U.init(this._getSwarmController()),this._swarmMessenger=new SwarmMessenger({sendMessage:async Z=>await this._messenger.sendMessage(Z),onSignal:async Z=>await this.onSignal(Z),onOffer:async Z=>await this.onOffer(Z),topic:this._topic}),log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file4$1,L:102,S:this,C:(Z,Q)=>Z(...Q)})}get connections(){return Array.from(this._peers.values()).map($=>$.connection).filter(isNotNullOrUndefined)}get ownPeerId(){return this._ownPeerId}get label(){return this._label}get topic(){return this._topic}async open(){invariant(!this._listeningHandle,void 0,{F:__dxlog_file4$1,L:129,S:this,A:["!this._listeningHandle",""]}),this._listeningHandle=await this._messenger.listen({peerId:this._ownPeerId,payloadType:"dxos.mesh.swarm.SwarmMessage",onMessage:async $=>{await this._swarmMessenger.receiveMessage($).catch(I=>log$2.info("Error while receiving message",{err:I},{F:__dxlog_file4$1,L:137,S:this,C:(U,q)=>U(...q)}))}})}async destroy(){var $;log$2("destroying...",void 0,{F:__dxlog_file4$1,L:143,S:this,C:(I,U)=>I(...U)}),await(($=this._listeningHandle)==null?void 0:$.unsubscribe()),this._listeningHandle=void 0,await this._ctx.dispose(),await this._topology.destroy(),await Promise.all(Array.from(this._peers.keys()).map(I=>this._destroyPeer(I,"swarm destroyed"))),log$2("destroyed",void 0,{F:__dxlog_file4$1,L:150,S:this,C:(I,U)=>I(...U)})}async setTopology($){invariant(!this._ctx.disposed,"Swarm is offline",{F:__dxlog_file4$1,L:154,S:this,A:["!this._ctx.disposed","'Swarm is offline'"]}),$!==this._topology&&(log$2("setting topology",{previous:getClassName(this._topology),topology:getClassName($)},{F:__dxlog_file4$1,L:158,S:this,C:(I,U)=>I(...U)}),await this._topology.destroy(),this._topology=$,this._topology.init(this._getSwarmController()),this._topology.update())}onSwarmEvent($){var I;if(log$2("swarm event",{swarmEvent:$},{F:__dxlog_file4$1,L:171,S:this,C:(U,q)=>U(...q)}),this._ctx.disposed){log$2("swarm event ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:174,S:this,C:(U,q)=>U(...q)});return}if($.peerAvailable){const U=PublicKey.from($.peerAvailable.peer);if(log$2("new peer",{peerId:U},{F:__dxlog_file4$1,L:180,S:this,C:(q,G)=>q(...G)}),!U.equals(this._ownPeerId)){const q=this._getOrCreatePeer(U);q.advertizing=!0}}else if($.peerLeft){const U=this._peers.get(PublicKey.from($.peerLeft.peer));U?(U.advertizing=!1,((I=U.connection)==null?void 0:I.state)!==ConnectionState.CONNECTED&&this._destroyPeer(U.id,"peer left").catch(q=>log$2.catch(q,void 0,{F:__dxlog_file4$1,L:191,S:this,C:(G,K)=>G(...K)}))):log$2("received peerLeft but no peer found",{peer:$.peerLeft.peer},{F:__dxlog_file4$1,L:194,S:this,C:(q,G)=>q(...G)})}this._topology.update()}async onOffer($){var q,G;if(log$2("offer",{message:$},{F:__dxlog_file4$1,L:203,S:this,C:(K,Y)=>K(...Y)}),this._ctx.disposed)return log$2("ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:205,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(invariant($.author,void 0,{F:__dxlog_file4$1,L:210,S:this,A:["message.author",""]}),!((q=$.recipient)!=null&&q.equals(this._ownPeerId)))return log$2("rejecting offer with incorrect peerId",{message:$},{F:__dxlog_file4$1,L:212,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(!((G=$.topic)!=null&&G.equals(this._topic)))return log$2("rejecting offer with incorrect topic",{message:$},{F:__dxlog_file4$1,L:216,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};const U=await this._getOrCreatePeer($.author).onOffer($);return this._topology.update(),U}async onSignal($){var U,q;if(log$2("signal",{message:$},{F:__dxlog_file4$1,L:227,S:this,C:(G,K)=>G(...K)}),this._ctx.disposed){log$2.info("ignored for offline swarm",void 0,{F:__dxlog_file4$1,L:229,S:this,C:(G,K)=>G(...K)});return}invariant((U=$.recipient)==null?void 0:U.equals(this._ownPeerId),`Invalid signal peer id expected=${this.ownPeerId}, actual=${$.recipient}`,{F:__dxlog_file4$1,L:232,S:this,A:["message.recipient?.equals(this._ownPeerId)","`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"]}),invariant((q=$.topic)==null?void 0:q.equals(this._topic),void 0,{F:__dxlog_file4$1,L:236,S:this,A:["message.topic?.equals(this._topic)",""]}),invariant($.author,void 0,{F:__dxlog_file4$1,L:237,S:this,A:["message.author",""]}),await this._getOrCreatePeer($.author).onSignal($)}async goOffline(){await this._ctx.dispose(),await Promise.all([...this._peers.keys()].map($=>this._destroyPeer($,"goOffline")))}async goOnline(){this._ctx=new Context}_getOrCreatePeer($){let I=this._peers.get($);return I||(I=new Peer($,this._topic,this._ownPeerId,this._swarmMessenger,this._protocolProvider,this._transportFactory,this._connectionLimiter,{onInitiated:U=>{this.connectionAdded.emit(U)},onConnected:()=>{this.connected.emit($)},onDisconnected:async()=>{I.advertizing||await this._destroyPeer(I.id,"peer disconnected"),this.disconnected.emit($),this._topology.update()},onRejected:()=>{this._peers.has($)&&(log$2("peer rejected connection",{peerId:$},{F:__dxlog_file4$1,L:286,S:this,C:(U,q)=>U(...q)}),this._destroyPeer($,"peer rejected connection"))},onAccepted:()=>{this._topology.update()},onOffer:U=>this._topology.onOffer(U),onPeerAvailable:()=>{this._topology.update()}}),this._peers.set($,I)),I}async _destroyPeer($,I){invariant(this._peers.has($),void 0,{F:__dxlog_file4$1,L:308,S:this,A:["this._peers.has(peerId)",""]}),await this._peers.get($).destroy(new Error(I)),this._peers.delete($)}_getSwarmController(){return{getState:()=>({ownPeerId:this._ownPeerId,connected:Array.from(this._peers.values()).filter($=>$.connection).map($=>$.id),candidates:Array.from(this._peers.values()).filter($=>!$.connection&&$.advertizing&&$.availableToConnect).map($=>$.id)}),connect:$=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{try{await this._initiateConnection($)}catch(I){log$2("initiation error",I,{F:__dxlog_file4$1,L:334,S:this,C:(U,q)=>U(...q)})}})},disconnect:async $=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{await this._closeConnection($),this._topology.update()})}}}async _initiateConnection($){const I=this._ctx;if($.toHex()<this._ownPeerId.toHex()&&(log$2("initiation delay",{remoteId:$},{F:__dxlog_file4$1,L:361,S:this,C:(q,G)=>q(...G)}),await sleep(this._initiationDelay)),I.disposed)return;const U=this._getOrCreatePeer($);U.connection||(log$2("initiating connection...",{remoteId:$},{F:__dxlog_file4$1,L:375,S:this,C:(q,G)=>q(...G)}),await U.initiateConnection(),this._topology.update(),log$2("initiated",{remoteId:$},{F:__dxlog_file4$1,L:378,S:this,C:(q,G)=>q(...G)}))}async _closeConnection($){const I=this._peers.get($);I&&await I.closeConnection()}};_ts_decorate3$1([logInfo],Swarm.prototype,"_instanceId",void 0),_ts_decorate3$1([logInfo],Swarm.prototype,"ownPeerId",null),_ts_decorate3$1([logInfo],Swarm.prototype,"topic",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onSwarmEvent",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onOffer",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOffline",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOnline",null);var EventType;(function($){$.CONNECTION_STATE_CHANGED="CONNECTION_STATE_CHANGED",$.PROTOCOL_ERROR="PROTOCOL_ERROR",$.PROTOCOL_EXTENSIONS_INITIALIZED="PROTOCOL_EXTENSIONS_INITIALIZED",$.PROTOCOL_EXTENSIONS_HANDSHAKE="PROTOCOL_EXTENSIONS_HANDSHAKE",$.PROTOCOL_HANDSHAKE="PROTOCOL_HANDSHAKE"})(EventType||(EventType={}));function _ts_decorate4$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file11="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts",MEMORY_TRANSPORT_DELAY=1,createStreamDelay=$=>new readableBrowserExports.Transform({objectMode:!0,transform:(I,U,q)=>{setTimeout(()=>q(null,I),$)}}),MemoryTransport=(Zn=class{constructor(I){this._options=I,this._instanceId=PublicKey.random(),this._remote=new Trigger,this._outgoingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._incomingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._closed=!1,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,invariant(!Zn._connections.has(this._instanceId),"Duplicate memory connection",{F:__dxlog_file11,L:64,S:this,A:["!MemoryTransport._connections.has(this._instanceId)","'Duplicate memory connection'"]}),Zn._connections.set(this._instanceId,this)}get isOpen(){return!this._closed}async open(){if(log$2("opening...",void 0,{F:__dxlog_file11,L:74,S:this,C:(I,U)=>I(...U)}),this._options.initiator){log$2("sending signal",void 0,{F:__dxlog_file11,L:78,S:this,C:(I,U)=>I(...U)});try{await this._options.sendSignal({payload:{transportId:this._instanceId.toHex()}})}catch(I){this._closed||this.errors.raise(toError(I))}}else this._remote.wait({timeout:this._options.timeout??1e3}).then(I=>{if(!this._closed){if(this._remoteInstanceId=I,this._remoteConnection=Zn._connections.get(this._remoteInstanceId),!this._remoteConnection){this._closed=!0,this.closed.emit();return}invariant(!this._remoteConnection._remoteConnection,`Remote already connected: ${this._remoteInstanceId}`,{F:__dxlog_file11,L:104,S:this,A:["!this._remoteConnection._remoteConnection","`Remote already connected: ${this._remoteInstanceId}`"]}),this._remoteConnection._remoteConnection=this,this._remoteConnection._remoteInstanceId=this._instanceId,log$2("connected",void 0,{F:__dxlog_file11,L:108,S:this,C:(U,q)=>U(...q)}),this._options.stream.pipe(this._outgoingDelay).pipe(this._remoteConnection._options.stream).pipe(this._incomingDelay).pipe(this._options.stream),this.connected.emit(),this._remoteConnection.connected.emit()}}).catch(I=>{this._closed||this.errors.raise(I)})}async close(){log$2("closing...",void 0,{F:__dxlog_file11,L:129,S:this,C:(I,U)=>I(...U)}),this._closed=!0,Zn._connections.delete(this._instanceId),this._remoteConnection&&(this._remoteConnection._closed=!0,Zn._connections.delete(this._remoteInstanceId),this._options.stream.unpipe(this._incomingDelay),this._incomingDelay.unpipe(this._remoteConnection._options.stream),this._remoteConnection._options.stream.unpipe(this._outgoingDelay),this._outgoingDelay.unpipe(this._options.stream),this._options.stream.unpipe(this._outgoingDelay),this._remoteConnection.closed.emit(),this._remoteConnection._remoteConnection=void 0,this._remoteConnection=void 0),this.closed.emit(),log$2("closed",void 0,{F:__dxlog_file11,L:157,S:this,C:(I,U)=>I(...U)})}async onSignal({payload:I}){if(log$2("received signal",{payload:I},{F:__dxlog_file11,L:161,S:this,C:(q,G)=>q(...G)}),!(I!=null&&I.transportId))return;const U=I.transportId;if(U){const q=PublicKey.fromHex(U);this._remote.wake(q)}}async getDetails(){return this._instanceId.toHex()}async getStats(){return{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0}}},Zn._connections=new ComplexMap(PublicKey.hash),Zn);_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_instanceId",void 0),_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_remoteInstanceId",void 0);var toError=$=>$ instanceof Error?$:new Error(String($)),TransportKind;(function($){$.SIMPLE_PEER="SIMPLE_PEER",$.SIMPLE_PEER_PROXY="SIMPLE_PEER_PROXY",$.LIBDATACHANNEL="LIBDATACHANNEL",$.MEMORY="MEMORY",$.TCP="TCP"})(TransportKind||(TransportKind={}));var wrtc=null;try{wrtc=__require("@koush/wrtc")}catch{}function _ts_decorate5$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file15="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts",DATACHANNEL_LABEL="dxos.mesh.transport",MAX_BUFFERED_AMOUNT=64*1024,MAX_MESSAGE_SIZE=64*1024,LibDataChannelTransport=(rr=class{constructor(I){this._options=I,this._closed=!1,this._connected=!1,this._writeCallback=null,this._readyForCandidates=new Trigger,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream}get isOpen(){return!!this._peer&&!this._closed}async open(){this._closed&&this.errors.raise(new Error("connection already closed"));const{RTCPeerConnection:I}=(await importESM("node-datachannel/polyfill")).default;this._options.webrtcConfig?this._options.webrtcConfig.iceServers=this._options.webrtcConfig.iceServers??[]:this._options.webrtcConfig={iceServers:[]},this._peer=new I(this._options.webrtcConfig),this._peer.onicecandidateerror=U=>{log$2.error("peer.onicecandidateerror",{event:U},{F:__dxlog_file15,L:77,S:this,C:(q,G)=>q(...G)})},this._peer.onconnectionstatechange=U=>{var q;log$2.debug("peer.onconnectionstatechange",{event:U,peerConnectionState:(q=this._peer)==null?void 0:q.connectionState,transportConnectionState:this._connected},{F:__dxlog_file15,L:81,S:this,C:(G,K)=>G(...K)})},this._peer.onicecandidate=async U=>{if(log$2.debug("peer.onicecandidate",{event:U},{F:__dxlog_file15,L:91,S:this,C:(q,G)=>q(...G)}),U.candidate)try{await this._options.sendSignal({payload:{data:{type:"candidate",candidate:{candidate:U.candidate.candidate,sdpMLineIndex:U.candidate.sdpMLineIndex??0,sdpMid:U.candidate.sdpMid??0}}}})}catch(q){log$2.info("signaling error",{err:q},{F:__dxlog_file15,L:108,S:this,C:(G,K)=>G(...K)})}},this._options.initiator?(invariant(this._peer,"not open",{F:__dxlog_file15,L:114,S:this,A:["this._peer","'not open'"]}),this._peer.createOffer().then(async U=>{var q;this._closed||(((q=this._peer)==null?void 0:q.connectionState)!=="connecting"&&(log$2.error("peer not connecting",{peer:this._peer},{F:__dxlog_file15,L:125,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"))),log$2.debug("creating offer",{peer:this._peer,offer:U},{F:__dxlog_file15,L:129,S:this,C:(G,K)=>G(...K)}),await this._peer.setLocalDescription(U),await this._options.sendSignal({payload:{data:{type:U.type,sdp:U.sdp}}}))}).catch(U=>{this.errors.raise(U)}),this._handleChannel(this._peer.createDataChannel(DATACHANNEL_LABEL)),log$2.debug("created data channel",void 0,{F:__dxlog_file15,L:139,S:this,C:(U,q)=>U(...q)}),this._peer.ondatachannel=()=>{this.errors.raise(new Error("unexpected ondatachannel event for initiator"))}):this._peer.ondatachannel=U=>{log$2.debug("peer.ondatachannel (non-initiator)",{event:U},{F:__dxlog_file15,L:145,S:this,C:(q,G)=>q(...G)}),U.channel.label!==DATACHANNEL_LABEL&&this.errors.raise(new Error(`unexpected channel label ${U.channel.label}`)),this._handleChannel(U.channel)},rr._instanceCount++}async close(){await this._close(),--rr._instanceCount===0&&(await importESM("node-datachannel")).cleanup()}async _close(){var I;if(!this._closed){await this._disconnectStreams();try{(I=this._peer)==null||I.close()}catch(U){this.errors.raise(U)}this._peer=void 0,this._closed=!0,this.closed.emit()}}_handleChannel(I){this._channel=I,this._channel.onopen=()=>{log$2.debug("channel.onopen",void 0,{F:__dxlog_file15,L:190,S:this,C:(q,G)=>q(...G)});const U=new stream.Duplex({read:()=>{},write:async(q,G,K)=>{q.length>MAX_MESSAGE_SIZE&&this.errors.raise(new Error(`message too large: ${q.length} > ${MAX_MESSAGE_SIZE}`));try{I.send(q)}catch(Y){this.errors.raise(Y),await this._close()}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._writeCallback!==null&&log$2.error("consumer trying to write before we are ready for more data",void 0,{F:__dxlog_file15,L:207,S:this,C:(Y,J)=>Y(...J)}),this._writeCallback=K):K()}});U.pipe(this._options.stream).pipe(U),this._stream=U,this._connected=!0,this.connected.emit()},this._channel.onclose=async U=>{log$2.info("channel.onclose",{err:U},{F:__dxlog_file15,L:223,S:this,C:(q,G)=>q(...G)}),await this._close()},this._channel.onerror=async U=>{this.errors.raise(new Error("channel error: "+U.toString())),await this._close()},this._channel.onbufferedamountlow=()=>{const U=this._writeCallback;this._writeCallback=null,U==null||U()},this._channel.onmessage=U=>{let q=U.data;q instanceof ArrayBuffer&&(q=export_Buffer.from(q)),this._stream.push(q)}}async onSignal(I){invariant(this._peer,"not open",{F:__dxlog_file15,L:249,S:this,A:["this._peer","'not open'"]});try{const U=I.payload.data;switch(U.type){case"offer":{if(this._peer.connectionState!=="new"){log$2.error("received offer but peer not in state new",{peer:this._peer},{F:__dxlog_file15,L:256,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));break}try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp});const q=await this._peer.createAnswer();await this._peer.setLocalDescription(q),await this._options.sendSignal({payload:{data:{type:q.type,sdp:q.sdp}}}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle offer from signalling server",{err:q},{F:__dxlog_file15,L:268,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling offer"))}break}case"answer":try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle answer from signalling server",{err:q},{F:__dxlog_file15,L:279,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling answer"))}break;case"candidate":await this._readyForCandidates.wait(),await this._peer.addIceCandidate({candidate:U.candidate.candidate});break;default:log$2.error("unhandled signal type",{type:U.type,signal:I},{F:__dxlog_file15,L:290,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error(`unhandled signal type ${U.type}`))}}catch(U){log$2.catch(U,void 0,{F:__dxlog_file15,L:294,S:this,C:(q,G)=>q(...G)})}}async getDetails(){const I=await this._getStats(),U=I==null?void 0:I.remoteCandidate;return U?U.candidateType==="relay"?`${U.ip}:${U.port} relay for ${U.relatedAddress}:${U.relatedPort}`:`${U.ip}:${U.port} ${U.candidateType}`:"unavailable"}async getStats(){const I=await this._getStats();return I?{bytesSent:I.transport.bytesSent,bytesReceived:I.transport.bytesReceived,packetsSent:0,packetsReceived:0,rawStats:I.raw}:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rawStats:{}}}async _getStats(){invariant(this._peer,"not open",{F:__dxlog_file15,L:334,S:this,A:["this._peer","'not open'"]});const I=await this._peer.getStats(),U=Array.from(I.entries()),q=U.filter(J=>J[1].type==="transport")[0][1],G=U.filter(J=>J[0]===q.selectedCandidatePairId);let K,Y;return G.length>0&&(K=G[0][1],Y=U.filter(J=>J[0]===K.remoteCandidateId)[0][1]),{transport:q,selectedCandidatePair:K,remoteCandidate:Y,raw:Object.fromEntries(I)}}async _disconnectStreams(){var I,U,q,G;(G=(q=(U=(I=this._options.stream).unpipe)==null?void 0:U.call(I,this._stream))==null?void 0:q.unpipe)==null||G.call(q,this._options.stream)}},rr._instanceCount=0,rr);_ts_decorate5$1([synchronized],LibDataChannelTransport.prototype,"_close",null);var importESM=Function("path","return import(path)"),uaParser={exports:{}};(function($,I){(function(U,q){var G="1.0.35",K="",Y="?",J="function",X="undefined",Z="object",Q="string",ee="major",te="model",ne="name",ie="type",oe="vendor",ce="version",fe="architecture",se="console",de="mobile",ue="tablet",pe="smarttv",ve="wearable",me="embedded",be=350,_e="Amazon",Se="Apple",xe="ASUS",ke="BlackBerry",De="Browser",Be="Chrome",Ve="Edge",nt="Firefox",ot="Google",ft="Huawei",it="LG",ut="Microsoft",et="Motorola",Ue="Opera",We="Samsung",tt="Sharp",vt="Sony",je="Xiaomi",ze="Zebra",Ae="Facebook",Re="Chromium OS",Ce="Mac OS",ge=function(St,Ut){var le={};for(var re in St)Ut[re]&&Ut[re].length%2===0?le[re]=Ut[re].concat(St[re]):le[re]=St[re];return le},ye=function(St){for(var Ut={},le=0;le<St.length;le++)Ut[St[le].toUpperCase()]=St[le];return Ut},Me=function(St,Ut){return typeof St===Q?Ke(Ut).indexOf(Ke(St))!==-1:!1},Ke=function(St){return St.toLowerCase()},st=function(St){return typeof St===Q?St.replace(/[^\d\.]/g,K).split(".")[0]:q},dt=function(St,Ut){if(typeof St===Q)return St=St.replace(/^\s\s*/,K),typeof Ut===X?St:St.substring(0,be)},$t=function(St,Ut){for(var le=0,re,ae,he,we,Ee,Le;le<Ut.length&&!Ee;){var bt=Ut[le],Lt=Ut[le+1];for(re=ae=0;re<bt.length&&!Ee&&bt[re];)if(Ee=bt[re++].exec(St),Ee)for(he=0;he<Lt.length;he++)Le=Ee[++ae],we=Lt[he],typeof we===Z&&we.length>0?we.length===2?typeof we[1]==J?this[we[0]]=we[1].call(this,Le):this[we[0]]=we[1]:we.length===3?typeof we[1]===J&&!(we[1].exec&&we[1].test)?this[we[0]]=Le?we[1].call(this,Le,we[2]):q:this[we[0]]=Le?Le.replace(we[1],we[2]):q:we.length===4&&(this[we[0]]=Le?we[3].call(this,Le.replace(we[1],we[2])):q):this[we]=Le||q;le+=2}},Et=function(St,Ut){for(var le in Ut)if(typeof Ut[le]===Z&&Ut[le].length>0){for(var re=0;re<Ut[le].length;re++)if(Me(Ut[le][re],St))return le===Y?q:le}else if(Me(Ut[le],St))return le===Y?q:le;return St},rt={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},jt={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Gt={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[ce,[ne,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[ce,[ne,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[ne,ce],[/opios[\/ ]+([\w\.]+)/i],[ce,[ne,Ue+" Mini"]],[/\bopr\/([\w\.]+)/i],[ce,[ne,Ue]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[ne,ce],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[ce,[ne,"UC"+De]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[ce,[ne,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[ce,[ne,"WeChat"]],[/konqueror\/([\w\.]+)/i],[ce,[ne,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[ce,[ne,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[ce,[ne,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[ne,/(.+)/,"$1 Secure "+De],ce],[/\bfocus\/([\w\.]+)/i],[ce,[ne,nt+" Focus"]],[/\bopt\/([\w\.]+)/i],[ce,[ne,Ue+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[ce,[ne,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[ce,[ne,"Dolphin"]],[/coast\/([\w\.]+)/i],[ce,[ne,Ue+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[ce,[ne,"MIUI "+De]],[/fxios\/([-\w\.]+)/i],[ce,[ne,nt]],[/\bqihu|(qi?ho?o?|360)browser/i],[[ne,"360 "+De]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[ne,/(.+)/,"$1 "+De],ce],[/(comodo_dragon)\/([\w\.]+)/i],[[ne,/_/g," "],ce],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[ne,ce],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[ne],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[ne,Ae],ce],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[ne,ce],[/\bgsa\/([\w\.]+) .*safari\//i],[ce,[ne,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[ce,[ne,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[ce,[ne,Be+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[ne,Be+" WebView"],ce],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[ce,[ne,"Android "+De]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[ne,ce],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[ce,[ne,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[ce,ne],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[ne,[ce,Et,rt]],[/(webkit|khtml)\/([\w\.]+)/i],[ne,ce],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[ne,"Netscape"],ce],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[ce,[ne,nt+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[ne,ce],[/(cobalt)\/([\w\.]+)/i],[ne,[ce,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[fe,"amd64"]],[/(ia32(?=;))/i],[[fe,Ke]],[/((?:i[346]|x)86)[;\)]/i],[[fe,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[fe,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[fe,"armhf"]],[/windows (ce|mobile); ppc;/i],[[fe,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[fe,/ower/,K,Ke]],[/(sun4\w)[;\)]/i],[[fe,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[fe,Ke]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[te,[oe,We],[ie,ue]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[te,[oe,We],[ie,de]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[te,[oe,Se],[ie,de]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[te,[oe,Se],[ie,ue]],[/(macintosh);/i],[te,[oe,Se]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[te,[oe,tt],[ie,de]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[te,[oe,ft],[ie,ue]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[te,[oe,ft],[ie,de]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,de]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,ue]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[te,[oe,"OPPO"],[ie,de]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[te,[oe,"Vivo"],[ie,de]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[te,[oe,"Realme"],[ie,de]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[te,[oe,et],[ie,de]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[te,[oe,et],[ie,ue]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[te,[oe,it],[ie,ue]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[te,[oe,it],[ie,de]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[te,[oe,"Lenovo"],[ie,ue]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[te,/_/g," "],[oe,"Nokia"],[ie,de]],[/(pixel c)\b/i],[te,[oe,ot],[ie,ue]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[te,[oe,ot],[ie,de]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[te,[oe,vt],[ie,de]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[te,"Xperia Tablet"],[oe,vt],[ie,ue]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[te,[oe,"OnePlus"],[ie,de]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[te,[oe,_e],[ie,ue]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[te,/(.+)/g,"Fire Phone $1"],[oe,_e],[ie,de]],[/(playbook);[-\w\),; ]+(rim)/i],[te,oe,[ie,ue]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[te,[oe,ke],[ie,de]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[te,[oe,xe],[ie,ue]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[te,[oe,xe],[ie,de]],[/(nexus 9)/i],[te,[oe,"HTC"],[ie,ue]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[oe,[te,/_/g," "],[ie,de]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[te,[oe,"Acer"],[ie,ue]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[te,[oe,"Meizu"],[ie,de]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[oe,te,[ie,de]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[oe,te,[ie,ue]],[/(surface duo)/i],[te,[oe,ut],[ie,ue]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[te,[oe,"Fairphone"],[ie,de]],[/(u304aa)/i],[te,[oe,"AT&T"],[ie,de]],[/\bsie-(\w*)/i],[te,[oe,"Siemens"],[ie,de]],[/\b(rct\w+) b/i],[te,[oe,"RCA"],[ie,ue]],[/\b(venue[\d ]{2,7}) b/i],[te,[oe,"Dell"],[ie,ue]],[/\b(q(?:mv|ta)\w+) b/i],[te,[oe,"Verizon"],[ie,ue]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[te,[oe,"Barnes & Noble"],[ie,ue]],[/\b(tm\d{3}\w+) b/i],[te,[oe,"NuVision"],[ie,ue]],[/\b(k88) b/i],[te,[oe,"ZTE"],[ie,ue]],[/\b(nx\d{3}j) b/i],[te,[oe,"ZTE"],[ie,de]],[/\b(gen\d{3}) b.+49h/i],[te,[oe,"Swiss"],[ie,de]],[/\b(zur\d{3}) b/i],[te,[oe,"Swiss"],[ie,ue]],[/\b((zeki)?tb.*\b) b/i],[te,[oe,"Zeki"],[ie,ue]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[oe,"Dragon Touch"],te,[ie,ue]],[/\b(ns-?\w{0,9}) b/i],[te,[oe,"Insignia"],[ie,ue]],[/\b((nxa|next)-?\w{0,9}) b/i],[te,[oe,"NextBook"],[ie,ue]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[oe,"Voice"],te,[ie,de]],[/\b(lvtel\-)?(v1[12]) b/i],[[oe,"LvTel"],te,[ie,de]],[/\b(ph-1) /i],[te,[oe,"Essential"],[ie,de]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[te,[oe,"Envizen"],[ie,ue]],[/\b(trio[-\w\. ]+) b/i],[te,[oe,"MachSpeed"],[ie,ue]],[/\btu_(1491) b/i],[te,[oe,"Rotor"],[ie,ue]],[/(shield[\w ]+) b/i],[te,[oe,"Nvidia"],[ie,ue]],[/(sprint) (\w+)/i],[oe,te,[ie,de]],[/(kin\.[onetw]{3})/i],[[te,/\./g," "],[oe,ut],[ie,de]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[te,[oe,ze],[ie,ue]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[te,[oe,ze],[ie,de]],[/smart-tv.+(samsung)/i],[oe,[ie,pe]],[/hbbtv.+maple;(\d+)/i],[[te,/^/,"SmartTV"],[oe,We],[ie,pe]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[oe,it],[ie,pe]],[/(apple) ?tv/i],[oe,[te,Se+" TV"],[ie,pe]],[/crkey/i],[[te,Be+"cast"],[oe,ot],[ie,pe]],[/droid.+aft(\w)( bui|\))/i],[te,[oe,_e],[ie,pe]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[te,[oe,tt],[ie,pe]],[/(bravia[\w ]+)( bui|\))/i],[te,[oe,vt],[ie,pe]],[/(mitv-\w{5}) bui/i],[te,[oe,je],[ie,pe]],[/Hbbtv.*(technisat) (.*);/i],[oe,te,[ie,pe]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[oe,dt],[te,dt],[ie,pe]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[ie,pe]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[oe,te,[ie,se]],[/droid.+; (shield) bui/i],[te,[oe,"Nvidia"],[ie,se]],[/(playstation [345portablevi]+)/i],[te,[oe,vt],[ie,se]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[te,[oe,ut],[ie,se]],[/((pebble))app/i],[oe,te,[ie,ve]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[te,[oe,Se],[ie,ve]],[/droid.+; (glass) \d/i],[te,[oe,ot],[ie,ve]],[/droid.+; (wt63?0{2,3})\)/i],[te,[oe,ze],[ie,ve]],[/(quest( 2| pro)?)/i],[te,[oe,Ae],[ie,ve]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[oe,[ie,me]],[/(aeobc)\b/i],[te,[oe,_e],[ie,me]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[te,[ie,de]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[te,[ie,ue]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[ie,ue]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[ie,de]],[/(android[-\w\. ]{0,9});.+buil/i],[te,[oe,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[ce,[ne,Ve+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[ce,[ne,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[ne,ce],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[ce,ne]],os:[[/microsoft (windows) (vista|xp)/i],[ne,ce],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[ne,[ce,Et,jt]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[ne,"Windows"],[ce,Et,jt]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[ce,/_/g,"."],[ne,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[ne,Ce],[ce,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[ce,ne],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[ne,ce],[/\(bb(10);/i],[ce,[ne,ke]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[ce,[ne,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[ce,[ne,nt+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[ce,[ne,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[ce,[ne,"watchOS"]],[/crkey\/([\d\.]+)/i],[ce,[ne,Be+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[ne,Re],ce],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[ne,ce],[/(sunos) ?([\w\.\d]*)/i],[[ne,"Solaris"],ce],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[ne,ce]]},At=function(St,Ut){if(typeof St===Z&&(Ut=St,St=q),!(this instanceof At))return new At(St,Ut).getResult();var le=typeof U!==X&&U.navigator?U.navigator:q,re=St||(le&&le.userAgent?le.userAgent:K),ae=le&&le.userAgentData?le.userAgentData:q,he=Ut?ge(Gt,Ut):Gt,we=le&&le.userAgent==re;return this.getBrowser=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.browser),Ee[ee]=st(Ee[ce]),we&&le&&le.brave&&typeof le.brave.isBrave==J&&(Ee[ne]="Brave"),Ee},this.getCPU=function(){var Ee={};return Ee[fe]=q,$t.call(Ee,re,he.cpu),Ee},this.getDevice=function(){var Ee={};return Ee[oe]=q,Ee[te]=q,Ee[ie]=q,$t.call(Ee,re,he.device),we&&!Ee[ie]&&ae&&ae.mobile&&(Ee[ie]=de),we&&Ee[te]=="Macintosh"&&le&&typeof le.standalone!==X&&le.maxTouchPoints&&le.maxTouchPoints>2&&(Ee[te]="iPad",Ee[ie]=ue),Ee},this.getEngine=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.engine),Ee},this.getOS=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.os),we&&!Ee[ne]&&ae&&ae.platform!="Unknown"&&(Ee[ne]=ae.platform.replace(/chrome os/i,Re).replace(/macos/i,Ce)),Ee},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return re},this.setUA=function(Ee){return re=typeof Ee===Q&&Ee.length>be?dt(Ee,be):Ee,this},this.setUA(re),this};At.VERSION=G,At.BROWSER=ye([ne,ce,ee]),At.CPU=ye([fe]),At.DEVICE=ye([te,oe,ie,se,de,pe,ue,ve,me]),At.ENGINE=At.OS=ye([ne,ce]),$.exports&&(I=$.exports=At),I.UAParser=At;var zt=typeof U!==X&&(U.jQuery||U.Zepto);if(zt&&!zt.ua){var nn=new At;zt.ua=nn.getResult(),zt.ua.get=function(){return nn.getUA()},zt.ua.set=function(St){nn.setUA(St);var Ut=nn.getResult();for(var le in Ut)zt.ua[le]=Ut[le]}}})(typeof window=="object"?window:commonjsGlobal)})(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,__dxlog_file$2="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/iframe.ts",browser,os$1;if(typeof navigator<"u"){const $=new uaParserExports.UAParser(navigator.userAgent);browser=$.getBrowser().name,os$1=$.getOS().name}var sendToIFrame=($,I,U)=>{if(!$.contentWindow){log$2("IFrame content window missing",{origin:I},{F:__dxlog_file$2,L:24,S:void 0,C:(q,G)=>q(...G)});return}browser==="Chrome"&&os$1==="iOS"?$.contentWindow.postMessage(U,I):$.contentWindow.postMessage(U,I,[U.payload])},sendToParentWindow=($,I)=>{browser==="Chrome"&&os$1==="iOS"?window.parent.postMessage(I,$):window.parent.postMessage(I,$,[I.payload])},createIFramePort=({channel:$,iframe:I,origin:U,onOrigin:q})=>({send:async G=>{if(!U){log$2("no origin set",{channel:$},{F:__dxlog_file$2,L:62,S:void 0,C:(J,X)=>J(...X)});return}log$2("sending",{channel:$,data:G.length},{F:__dxlog_file$2,L:66,S:void 0,C:(J,X)=>J(...X)});const K=G.buffer.slice(G.byteOffset,G.byteOffset+G.byteLength),Y={channel:$,payload:K};I?sendToIFrame(I,U,Y):sendToParentWindow(U,Y)},subscribe:G=>{const K=Y=>{if(!I&&Y.source!==window.parent)return;if(I&&Y.source!==I.contentWindow)return;const X=Y.data&&typeof Y.data=="object"&&"channel"in Y.data&&"payload"in Y.data?Y.data:void 0;(X==null?void 0:X.channel)===$&&(U||(U=Y.origin,q==null||q(U)),log$2("received",X,{F:__dxlog_file$2,L:98,S:void 0,C:(Z,Q)=>Z(...Q)}),G(new Uint8Array(X.payload)))};return window.addEventListener("message",K),()=>window.removeEventListener("message",K)}}),createIFrame=($,I,{hidden:U=!0,allow:q}={})=>{const G=()=>{const K=document.createElement("iframe");return K.id=I,K.src=$,U&&K.setAttribute("style","display: none;"),q&&K.setAttribute("allow",q),document.body.appendChild(K),K};return document.getElementById(I)??G()},__dxlog_file2="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/worker.ts",createWorkerPort=({port:$,channel:I,subscribe:U})=>({send:async q=>{const G=q.buffer.slice(q.byteOffset,q.byteOffset+q.byteLength);$.postMessage({channel:I,payload:G},[G])},subscribe:U??(q=>{const G=K=>{const Y=K.data;I&&Y.channel!==I||(log$2.debug("Recieved message",Y,{F:__dxlog_file2,L:46,S:void 0,C:(J,X)=>J(...X)}),q(new Uint8Array(Y.payload)))};return $.onmessage=G,()=>{$.onmessage=null}})});function _ts_decorate$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$1="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/agent.ts",getUnixSocket=($,I="unix")=>`${I}://`+clientProtocol.getProfilePath(clientProtocol.DX_RUNTIME,$,"agent.sock"),AgentClientServiceProvider=class{constructor($){this._profile=$,this.closed=new Event$1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._client.rpc}async open(){const{WebsocketRpcClient:$}=await Promise.resolve().then(()=>index);this._client=new $({url:getUnixSocket(this._profile,"ws+unix"),requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{}}),await this._client.open()}async close(){var $;try{await(($=this._client)==null?void 0:$.close())}catch(I){log$2.warn("Failed to close",I,{F:__dxlog_file$1,L:69,S:this,C:(U,q)=>U(...q)})}}};AgentClientServiceProvider=_ts_decorate$1([trace.resource({annotation:clientServices.ClientServicesProviderResource})],AgentClientServiceProvider);function _ts_decorate2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var LocalClientServices=class{constructor($){this.closed=new Event$1,this._ctx=new Context,this.signalMetadataTags={runtime:"local-client-services"},this._isOpen=!1,this._params=$,typeof window>"u"?this.signalMetadataTags.origin="undefined":globalThis.__args?(this.signalMetadataTags.runtime="native",this.signalMetadataTags.origin=window.location.origin):this.signalMetadataTags.origin=window.location.origin}get descriptors(){return clientProtocol.clientServiceBundle}get services(){var $;return(($=this._host)==null?void 0:$.services)??{}}get host(){return this._host}async open(){if(this._isOpen)return;const{ClientServicesHost:$}=await import("@dxos/client-services");this._host=new $({...this._params,callbacks:{...this._params.callbacks,onReset:async()=>{var I,U;this.closed.emit(void 0),await((U=(I=this._params.callbacks)==null?void 0:I.onReset)==null?void 0:U.call(I))}}}),await this._host.open(this._ctx),this._isOpen=!0,setIdentityTags({identityService:this._host.services.IdentityService,devicesService:this._host.services.DevicesService,setTag:(I,U)=>{this.signalMetadataTags[I]=U}})}async close(){var $;this._isOpen&&(await(($=this._host)==null?void 0:$.close()),this._isOpen=!1)}};_ts_decorate2([trace.info()],LocalClientServices.prototype,"_isOpen",void 0),_ts_decorate2([synchronized],LocalClientServices.prototype,"open",null),_ts_decorate2([synchronized],LocalClientServices.prototype,"close",null),LocalClientServices=_ts_decorate2([trace.resource({annotation:clientServices.ClientServicesProviderResource})],LocalClientServices);var IFrameManager=class{constructor({source:$,onOpen:I,onMessage:U}){this._source=$,this._onOpen=I,this._onMessage=U,this._messageHandler=this._messageHandler.bind(this)}get source(){return this._source}get iframe(){return this._iframe}async open(){var I;if(this._iframe)return;window.addEventListener("message",this._messageHandler);const $=`__DXOS_CLIENT_${PublicKey.random().toHex()}__`;this._iframe=createIFrame(this._source.toString(),$,{allow:"clipboard-read; clipboard-write"}),await((I=this._onOpen)==null?void 0:I.call(this))}async close(){var $;window.removeEventListener("message",this._messageHandler),($=this._iframe)==null||$.remove(),this._iframe=void 0}async _messageHandler($){var I;(I=this._onMessage)==null||I.call(this,$)}},__dxlog_file3="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/shell-manager.ts",shellStyles=Object.entries({display:"none",position:"fixed",top:0,left:0,width:"100vw",height:"100vh",border:0,"z-index":60}).reduce(($,[I,U])=>`${$}${I}: ${U};`,""),ShellManager=class{constructor($,I=clientProtocol.DEFAULT_SHELL_CHANNEL){this._iframeManager=$,this._channel=I,this.contextUpdate=new Event$1,this._display=ShellDisplay.NONE}get display(){return this._display}async setLayout($){var I;log$2("set layout",$,{F:__dxlog_file3,L:51,S:this,C:(U,q)=>U(...q)}),this._display=ShellDisplay.FULLSCREEN,this.contextUpdate.emit({display:this._display}),await((I=this._shellRpc)==null?void 0:I.rpc.ShellService.setLayout($,{timeout:RPC_TIMEOUT}))}async open(){if(this._shellRpc)return;await this._iframeManager.open();const $=this._iframeManager.iframe;$.setAttribute("style",shellStyles),$.setAttribute("name","dxos-shell"),$.setAttribute("data-testid","dxos-shell"),this.contextUpdate.on(({display:q,reload:G})=>{G&&window.location.reload(),$.style.display=q===ShellDisplay.NONE?"none":"",q===ShellDisplay.NONE&&$.blur()});const I=this._iframeManager.source.origin==="null"?this._iframeManager.source.toString().split("/").slice(0,3).join("/"):this._iframeManager.source.origin,U=createIFramePort({origin:I,channel:this._channel,iframe:this._iframeManager.iframe});this._shellRpc=createProtoRpcPeer({requested:clientProtocol.shellServiceBundle,exposed:clientProtocol.appServiceBundle,handlers:{AppService:{setContext:async q=>{log$2("set context",q,{F:__dxlog_file3,L:98,S:this,C:(G,K)=>G(...K)}),q.display&&(this._display=q.display),this.contextUpdate.emit(q)}}},port:U}),await this._shellRpc.open()}async close(){var $;this._shellRpc&&(await(($=this._shellRpc)==null?void 0:$.close()),this._shellRpc=void 0)}};function _ts_decorate3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var IFrameClientServicesHost=class{constructor({host:$,source:I=clientProtocol.DEFAULT_VAULT_URL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT}){this.closed=new Event$1,this._host=$,this._source=I,this._vault=U,this._timeout=q;const G=new Trigger;this._iframeManager=new IFrameManager({source:new URL(this._source,window.location.origin),onOpen:async()=>{var K,Y,J;await asyncTimeout(G.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(J=(Y=(K=this._iframeManager)==null?void 0:K.iframe)==null?void 0:Y.contentWindow)==null||J.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin)},onMessage:K=>{var X,Z,Q;const{channel:Y,payload:J}=K.data;if(Y===this._vault){if(J==="loaded")G.wake();else if(J==="client"){const ee=new MessageChannel,te=createBundledRpcServer({services:this._host.descriptors,handlers:this._host.services,port:createWorkerPort({port:ee.port1})});(Q=(Z=(X=this._iframeManager)==null?void 0:X.iframe)==null?void 0:Z.contentWindow)==null||Q.postMessage({channel:this._vault,payload:{command:"port",port:ee.port2}},this._iframeManager.source.origin,[ee.port2]),te.open()}}}}),this._shellManager=new ShellManager(this._iframeManager)}get descriptors(){return this._host.descriptors}get services(){return this._host.services}async open(){await this._host.open(new Context),await this._shellManager.open()}async close(){await this._shellManager.close(),await this._iframeManager.close(),await this._host.close(new Context)}};IFrameClientServicesHost=_ts_decorate3([trace.resource()],IFrameClientServicesHost);function _ts_decorate4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/service-proxy.ts",ClientServicesProxy=class{constructor($,I=3e4){this._port=$,this._timeout=I,this.closed=new Event$1}get proxy(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file4,L:30,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file4,L:39,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy.rpc}async open(){this._proxy||(this._proxy=createProtoRpcPeer({requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{},port:this._port}),await asyncTimeout(this._proxy.open(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Failed to establish dxrpc connection",{timeout:this._timeout})))}async close(){this._proxy&&(await this._proxy.close(),this._proxy=void 0)}};ClientServicesProxy=_ts_decorate4([trace.resource({annotation:clientServices.ClientServicesProviderResource})],ClientServicesProxy);function _ts_decorate5($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/iframe-service-proxy.ts",IFrameClientServicesProxy=class{constructor({source:$=clientProtocol.DEFAULT_VAULT_URL,shell:I=clientProtocol.DEFAULT_SHELL_CHANNEL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT,logFilter:G="error,warn"}={}){this.closed=new Event$1,this._instanceId=PublicKey.random().toHex(),this._source=$,this._shell=I,this._vault=U,this._logFilter=parseFilter(G),this._timeout=q;const K=new Trigger,Y=new Trigger;this._iframeManager=new IFrameManager({source:new URL(typeof this._shell=="string"?this._source:`${this._source}#disableshell`,window.location.origin),onOpen:async()=>{var X,Z;await asyncTimeout(K.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(Z=(X=this._iframeManager.iframe)==null?void 0:X.contentWindow)==null||Z.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin);const J=await asyncTimeout(Y.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to provide MessagePort"));this._appPort=createWorkerPort({port:J})},onMessage:async J=>{const{channel:X,payload:Z}=J.data;X===this._vault&&(Z==="loaded"?K.wake():(Z==null?void 0:Z.command)==="init"&&Y.wake(Z.port))}}),typeof this._shell=="string"&&(this._shellManager=new ShellManager(this._iframeManager))}get proxy(){return this._clientServicesProxy.proxy}get descriptors(){return this._clientServicesProxy.descriptors}get services(){return this._clientServicesProxy.services}async open(){var $;this._clientServicesProxy||(log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file5,L:142,S:this,C:(I,U)=>I(...U)}),await this._iframeManager.open(),this._clientServicesProxy=new ClientServicesProxy(this._appPort),await this._clientServicesProxy.open(),this._loggingStream=this._clientServicesProxy.services.LoggingService.queryLogs({filters:this._logFilter},{timeout:RPC_TIMEOUT}),this._loggingStream.subscribe(I=>{switch(I.level){case LogLevel.DEBUG:log$2.debug(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:157,S:this,C:(U,q)=>U(...q)});break;case LogLevel.INFO:log$2.info(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:160,S:this,C:(U,q)=>U(...q)});break;case LogLevel.WARN:log$2.warn(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:163,S:this,C:(U,q)=>U(...q)});break;case LogLevel.ERROR:log$2.error(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:166,S:this,C:(U,q)=>U(...q)});break}}),await(($=this._shellManager)==null?void 0:$.open()))}async close(){var $,I,U;await(($=this._shellManager)==null?void 0:$.close()),await this._iframeManager.close(),await((I=this._loggingStream)==null?void 0:I.close()),await((U=this._clientServicesProxy)==null?void 0:U.close()),this._clientServicesProxy=void 0,log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file5,L:180,S:this,C:(q,G)=>q(...G)})}};IFrameClientServicesProxy=_ts_decorate5([trace.resource()],IFrameClientServicesProxy);function _ts_decorate6($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file7="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/worker-client-services.ts",WorkerClientServices=class{constructor({config:$,createWorker:I,logFilter:U="error,warn",observabilityGroup:q,signalTelemetryEnabled:G}){this.closed=new Event$1,this.joinedSpace=new Event$1,this._isOpen=!1,this._config=$,this._createWorker=I,this._logFilter=parseFilter(U),this._observabilityGroup=q,this._signalTelemetryEnabled=G??!1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._services.services}get runtime(){return this._runtime}async open(){if(this._isOpen)return;log$2("opening...",void 0,{F:__dxlog_file7,L:88,S:this,C:(K,Y)=>K(...Y)});const{SharedWorkerConnection:$}=await import("@dxos/client-services"),I=new Trigger,U=this._createWorker();U.port.postMessage({dxlog:localStorage.getItem("dxlog")}),U.port.onmessage=K=>{const{command:Y,payload:J}=K.data;Y==="init"&&I.wake(J)};const{systemPort:q,appPort:G}=await I.wait();this._runtime=new $({config:this._config,systemPort:createWorkerPort({port:q})}),await this._runtime.open({origin:location.origin,observabilityGroup:this._observabilityGroup,signalTelemetryEnabled:this._signalTelemetryEnabled}),this._services=new ClientServicesProxy(createWorkerPort({port:G})),await this._services.open(),navigator.locks.request(LOCK_KEY,()=>{log$2("terminated",void 0,{F:__dxlog_file7,L:115,S:this,C:(K,Y)=>K(...Y)}),this._isOpen&&this.closed.emit(new Error("Shared worker terminated."))}),this._loggingStream=this._services.services.LoggingService.queryLogs({filters:this._logFilter},{timeout:RPC_TIMEOUT}),this._loggingStream.subscribe(K=>{switch(K.level){case LogLevel.DEBUG:log$2.debug(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.INFO:log$2.info(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.WARN:log$2.warn(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.ERROR:log$2.error(K.message,K.context,mapLogMeta(K.meta));break}}),log$2("opened",void 0,{F:__dxlog_file7,L:144,S:this,C:(K,Y)=>K(...Y)}),this._isOpen=!0}async close(){var $;this._isOpen&&(log$2("closing...",void 0,{F:__dxlog_file7,L:154,S:this,C:(I,U)=>I(...U)}),await(($=this._loggingStream)==null?void 0:$.close()),await this._runtime.close(),await this._services.close(),log$2("closed",void 0,{F:__dxlog_file7,L:159,S:this,C:(I,U)=>I(...U)}),this._isOpen=!1)}};_ts_decorate6([trace.info()],WorkerClientServices.prototype,"_isOpen",void 0),_ts_decorate6([synchronized],WorkerClientServices.prototype,"open",null),_ts_decorate6([synchronized],WorkerClientServices.prototype,"close",null),WorkerClientServices=_ts_decorate6([trace.resource()],WorkerClientServices);var mapLogMeta=$=>$&&{F:$.file,L:$.line,S:$.scope},i$1=Symbol.for("preact-signals");function t(){if(s$1>1)s$1--;else{for(var $,I=!1;h$1!==void 0;){var U=h$1;for(h$1=void 0,f++;U!==void 0;){var q=U.o;if(U.o=void 0,U.f&=-3,!(8&U.f)&&c(U))try{U.c()}catch(G){I||($=G,I=!0)}U=q}}if(f=0,s$1--,I)throw $}}var o=void 0,h$1=void 0,s$1=0,f=0,v$1=0;function e($){if(o!==void 0){var I=$.n;if(I===void 0||I.t!==o)return I={i:0,S:$,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:I},o.s!==void 0&&(o.s.n=I),o.s=I,$.n=I,32&o.f&&$.S(I),I;if(I.i===-1)return I.i=0,I.n!==void 0&&(I.n.p=I.p,I.p!==void 0&&(I.p.n=I.n),I.p=o.s,I.n=void 0,o.s.n=I,o.s=I),I}}function u($){this.v=$,this.i=0,this.n=void 0,this.t=void 0}u.prototype.brand=i$1,u.prototype.h=function(){return!0},u.prototype.S=function($){this.t!==$&&$.e===void 0&&($.x=this.t,this.t!==void 0&&(this.t.e=$),this.t=$)},u.prototype.U=function($){if(this.t!==void 0){var I=$.e,U=$.x;I!==void 0&&(I.x=U,$.e=void 0),U!==void 0&&(U.e=I,$.x=void 0),$===this.t&&(this.t=U)}},u.prototype.subscribe=function($){var I=this;return E(function(){var U=I.value,q=o;o=void 0;try{$(U)}finally{o=q}})},u.prototype.valueOf=function(){return this.value},u.prototype.toString=function(){return this.value+""},u.prototype.toJSON=function(){return this.value},u.prototype.peek=function(){var $=o;o=void 0;try{return this.value}finally{o=$}},Object.defineProperty(u.prototype,"value",{get:function(){var $=e(this);return $!==void 0&&($.i=this.i),this.v},set:function($){if($!==this.v){if(f>100)throw new Error("Cycle detected");this.v=$,this.i++,v$1++,s$1++;try{for(var I=this.t;I!==void 0;I=I.x)I.t.N()}finally{t()}}}});function c($){for(var I=$.s;I!==void 0;I=I.n)if(I.S.i!==I.i||!I.S.h()||I.S.i!==I.i)return!0;return!1}function a($){for(var I=$.s;I!==void 0;I=I.n){var U=I.S.n;if(U!==void 0&&(I.r=U),I.S.n=I,I.i=-1,I.n===void 0){$.s=I;break}}}function l($){for(var I=$.s,U=void 0;I!==void 0;){var q=I.p;I.i===-1?(I.S.U(I),q!==void 0&&(q.n=I.n),I.n!==void 0&&(I.n.p=q)):U=I,I.S.n=I.r,I.r!==void 0&&(I.r=void 0),I=q}$.s=U}function y($){u.call(this,void 0),this.x=$,this.s=void 0,this.g=v$1-1,this.f=4}(y.prototype=new u).h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===v$1))return!0;if(this.g=v$1,this.f|=1,this.i>0&&!c(this))return this.f&=-2,!0;var $=o;try{a(this),o=this;var I=this.x();(16&this.f||this.v!==I||this.i===0)&&(this.v=I,this.f&=-17,this.i++)}catch(U){this.v=U,this.f|=16,this.i++}return o=$,l(this),this.f&=-2,!0},y.prototype.S=function($){if(this.t===void 0){this.f|=36;for(var I=this.s;I!==void 0;I=I.n)I.S.S(I)}u.prototype.S.call(this,$)},y.prototype.U=function($){if(this.t!==void 0&&(u.prototype.U.call(this,$),this.t===void 0)){this.f&=-33;for(var I=this.s;I!==void 0;I=I.n)I.S.U(I)}},y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var $=this.t;$!==void 0;$=$.x)$.t.N()}},Object.defineProperty(y.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var $=e(this);if(this.h(),$!==void 0&&($.i=this.i),16&this.f)throw this.v;return this.v}});function _($){var I=$.u;if($.u=void 0,typeof I=="function"){s$1++;var U=o;o=void 0;try{I()}catch(q){throw $.f&=-2,$.f|=8,g($),q}finally{o=U,t()}}}function g($){for(var I=$.s;I!==void 0;I=I.n)I.S.U(I);$.x=void 0,$.s=void 0,_($)}function p$1($){if(o!==this)throw new Error("Out-of-order effect");l(this),o=$,this.f&=-2,8&this.f&&g(this),t()}function b$1($){this.x=$,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32}b$1.prototype.c=function(){var $=this.S();try{if(8&this.f||this.x===void 0)return;var I=this.x();typeof I=="function"&&(this.u=I)}finally{$()}},b$1.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,_(this),a(this),s$1++;var $=o;return o=this,p$1.bind(this,$)},b$1.prototype.N=function(){2&this.f||(this.f|=2,this.o=h$1,h$1=this)},b$1.prototype.d=function(){this.f|=8,1&this.f||g(this)};function E($){var I=new b$1($);try{I.c()}catch(U){throw I.d(),U}return I.d.bind(I)}var shim={exports:{}},useSyncExternalStoreShim_production_min={};/**
|
|
924
924
|
* @license React
|
|
925
925
|
* use-sync-external-store-shim.production.min.js
|
|
926
926
|
*
|