Spaccogram/webk/public/index-CbCftUfG.js.map

1 line
584 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{"version":3,"mappings":";gsDAaaA,GAAe,CAAC,mBAAoB,mBAAmB,EACvDC,GAA0B,UAEjCC,GAAU,KAAK,IAAI,EAAG,UAAU,qBAAuB,CAAC,EAExDC,EAAM,CACV,GAAI,QACJ,KAAM,mCACN,QAAS,QACT,YAAa,cACb,MAAO,IACP,gBAAiB,QACjB,SAAU,OACV,aAAc,KACd,QAASH,GACT,SAAU,EACV,aAAcA,GAAa,SAAS,SAAS,QAAQ,EACrD,OAAQ,IACR,QAAAE,GACA,cAAeA,EACjB,EAEGC,EAAI,eACLA,EAAI,GAAK,KACTA,EAAI,KAAO,oCC/Bb,SAAwBC,IAAoB,CACtC,gBAAS,eAAoC,MAC9C,SAAS,cAAmC,OACtC,IAGF,EACT,CCFA,SAAwBC,GAAYC,EAAe,CAEjD,GADAA,MAAU,OAAO,OACdA,EAAO,CAORA,EAAQA,EAAM,eAAiBA,EAE3B,IACCA,EAAM,iBAAiBA,EAAM,gBAAgB,EAC7CA,EAAM,gBAAgBA,EAAM,eAAe,EAC9CA,EAAM,YAAc,GACpBA,EAAM,aAAe,QACV,CAAC,CAChB,CAEO,QACT,CCxBA,MAAMC,GAAsB,iBAAkB,QAAY,OAAO,eAAiB,oBAAoB,cCPhGC,GAAM,OAAO,OAAY,IAAc,OAAS,KCQzCC,GAAa,UAAY,UAAU,UAAY,KAC/CC,GAAW,UAAU,UAAU,OAAO,uBAAuB,IAAM,GACnEC,GAAa,UAAU,UAAU,YAAc,UAAQ,SAAS,IAAM,GACtEC,GAAc,SAAS,KAAK,UAAU,SAAS,GAAK,aAAa,KAAK,UAAU,MAAM,EACtFC,IAAoB,IAAM,CACjC,IACF,MAAO,CAAC,UAAU,UAAU,MAAM,gCAAgC,EAAE,CAAC,OAC1D,CACb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AAQ,IAAI,sBAAuB,KAAK,MAAQ,GAAI,EACpD88B,EAAqB,SAAS,eAAe,cAAc,EAAGzkC,GAAW,IACxE,MAAMyc,EAAA,WAAO,sBAAgB,4CAAG,QAAQ,MAAM,CAEnD,CAAC","names":["MAIN_DOMAINS","DEFAULT_BACKGROUND_SLUG","threads","App","blurActiveElement","cancelEvent","event","IS_TOUCH_SUPPORTED","ctx","USER_AGENT","IS_APPLE","IS_ANDROID","IS_CHROMIUM","CHROMIUM_VERSION","IS_APPLE_MOBILE","IS_SAFARI","IS_FIREFOX","IS_MOBILE_SAFARI","IS_MOBILE","findUpClassName","el","className","fastRafCallbacks","fastRaf","callback","currentCallbacks","cb","fastRafConventionalCallbacks","processing","fastRafConventional","i","rafPromise","fastRafPromise","resolve","doubleRaf","fixSafariStickyInput","input","IS_STICKY_INPUT_BUGGED","key","startY","o","onTouchMove","e","touch","scrollable","y","scrolled","scrollTop","scrollHeight","clientHeight","nextScrollTop","lastFocusOutTimeStamp","fixSafariStickyInputFocusing","FontFamilyName","FontFamily","FontSize","FontWeight","FontFull","noop","pause","ms","TGICO_CLASS","_tgico","icon","texts","cache","fonts","loadFonts","types","promises","type","_texts","font","weights","weight","_promises","text","_a","_b","IS_EMOJI_SUPPORTED","makeWorkerURL","url","value","setWorkerProxy","workerHandler","target","args","w","toggleAttributePolyfill","name","force","NULL_PEER_ID","REPLIES_PEER_ID","REPLIES_HIDDEN_CHANNEL_ID","HIDDEN_PEER_ID","SERVICE_PEER_ID","MUTE_UNTIL","BOT_START_PARAM","MAX_FILE_SAVE_SIZE","THUMB_TYPE_FULL","TOPIC_COLORS","ATTACH_MENU_BOT_ICON_NAME","MESSAGE_ID_OFFSET","GENERAL_TOPIC_ID","CAN_HIDE_TOPIC","T_ME_PREFIXES","SEND_WHEN_ONLINE_TIMESTAMP","SERVER_IMAGE_MIME_TYPES","STARS_CURRENCY","FOLDER_ID_ALL","FOLDER_ID_ARCHIVE","REAL_FOLDERS","TEST_NO_STORIES","EventListenerBase","reuseResults","options","listenerObject","obj","l","listener","result","error","err","collectResults","arr","listeners","Modes","IS_BETA","DEBUG","MOUNT_CLASS_TO","tabId","indexOfAndSplice","array","item","idx","IS_SERVICE_WORKER","IS_WEB_WORKER","IS_WORKER","getWindowClients","postMessage","notifyServiceWorker","all","notifyWorker","CACHED_ERRORS","makeError","_logTimer","dT","LogTypes","LOG_LEVELS","IS_WEBKIT","STYLES_SUPPORTED","LOGGER_STYLES","methods","logger","prefix","ignoreDebugReset","style","originalPrefix","originalStyle","log","method","logType","newPrefix","level","acc","v","prefixCache","_type","prefix2","USE_LOCKS","SuperMessagePort","logSuffix","task","source","taskId","deferred","payload","previousResolve","ret","reject","pingResolve","newEvent","id","innerTask","resultTaskPayload","resultTask","ackTask","isPromise","cached","port","promise","lock","port2","portTasks","tasks","batchTask","ports","transfer","withAck","_void","interval","MTProtoMessagePort","RootScope","isNew","isPremium","status","settings","rootScope","deferredHelper","deferredPromise","_resolve","_reject","bindPromiseToDeferred","throttle","fn","shouldRunFirst","isPending","clear","_args","safeAssign","object","fromObject","_IDB","db","createNew","createIndexes","os","store","indexNames","indexName","index","createObjectStore","request","finished","calledNew","transaction","instance","preserve","storage","IDB","IDBStorage","storeName","entryName","isArray","objectStore","mode","perf","onError","timeout","onComplete","results","requests","r","waitForTransactionComplete","callbackResult","length","left","onRequestFinished","THROTTLE_TIME","_AppStorage","set","keys","values","useCache","p","onlyLocal","canUseStorage","saveLocal","enabled","clearWrite","names","AppStorage","DATABASE_STATE","StateStorage","stateStorage","deepEqual","x","ignoreKeys","ignoreSet","okok","ok","tx","capitalizeFirstLetter","string","SKIP_PROTOCOLS","matchUrlProtocol","protocol","originalString","ALPHA_CHARS_REG_EXP","ALPHA_NUMERIC_REG_EXP","DOMAIN_ADD_CHARS","URL_ALPHANUMERIC_REG_EXP_PART","URL_PROTOCOL_REG_EXP_PART","URL_REG_EXP","USERNAME_REG_EXP","TIMESTAMP_REG_EXP","BOT_COMMAND_REG_EXP","FULL_REG_EXP","emojiRegExp","EMAIL_REG_EXP","MARKDOWN_REG_EXP","SITE_HASHTAGS","MARKDOWN_ENTITIES","PASS_CONFLICTING_ENTITIES","PASS_SINGLE_CONFLICTING_ENTITIES","PHONE_NUMBER_REG_EXP","wrapUrl","unsafe","out","tgMeMatch","tgMatch","onclick","u","fullPath","path","setInnerHTML","elem","html","setDirection","getDirection","setBlankToAnchor","anchor","sharedConfig","equalFn","a","b","$PROXY","$TRACK","signalOptions","runEffects","runQueue","STALE","PENDING","UNOWNED","NO_INIT","Owner","Transition","ExternalSourceConfig","Listener","Updates","Effects","ExecCount","createRoot","detachedOwner","owner","unowned","current","root","updateFn","untrack","cleanNode","runUpdates","createSignal","setter","writeSignal","readSignal","createComputed","c","createComputation","updateComputation","createRenderEffect","createEffect","runUserEffects","createReaction","onInvalidate","tracking","createMemo","createResource","pSource","pFetcher","pOptions","fetcher","pr","initP","scheduled","resolved","dynamic","contexts","setValue","setError","track","trigger","state","setState","loadEnd","completeLoad","read","SuspenseContext","load","refetching","lookup","castError","s","batch","on","deps","prevInput","defer","prevValue","onMount","onCleanup","getListener","getOwner","runWithOwner","prev","prevListener","handleError","startTransition","t","transPending","setTransPending","useTransition","createContext","defaultValue","createProvider","useContext","context","children","memo","resolveChildren","updates","lookUpstream","sSlot","node","isComp","TransitionRunning","markDownstream","time","runComputation","nextValue","init","pure","runTop","ancestors","wait","res","completeUpdates","queue","userLength","ignore","obs","n","props","FALLBACK","dispose","d","mapArray","list","mapFn","items","mapped","disposers","len","indexes","newItems","j","newLen","newIndices","newIndicesNext","temp","tempdisposers","tempIndexes","start","end","newEnd","disposer","mapper","createComponent","Comp","trueFn","propTraps","_","property","receiver","resolveSource","resolveSources","mergeProps","sources","proxy","sourcesMap","defined","sourceKeys","desc","definedKeys","splitProps","blocked","k","otherObject","objects","propName","isDefaultDesc","objectIndex","narrowedError","For","fallback","Show","keyed","condition","child","langPack","UNSUPPORTED_LANG_PACK_KEY","I18n","pluralRules","cacheLangPackPromise","setRTL","rtl","setLangCode","langCode","getCacheLangPack","applyLangPack","loadLocalLangPack","updateAmPm","dateTimeFormat","getDateTimeFormat","date","amText","pmText","setTimeFormat","format","haveToUpdate","cachedDateTimeFormats","element","IntlDateElement","defaultCode","__vitePreload","lang","langSign","countries","strings","formatLocalStrings","saveLangPack","loadLangPack","web","managers","getStrings","pushTo","getLangPack","langPack1","langPack2","localLangPack1","localLangPack2","_Intl","currentLangCode","country","langPackKey","pushNextArgument","indexHolder","arg","superFormatter","str","regExp","lastIndex","match","p1","p2","p3","p4","offset","wrappedUrl","formatted","plain","IntlElementBase","IntlElement","json","hours","i18n","i18n_","_i18n","I18n$1","joinElementsWith","elements","joiner","isLast","join","useLast","joined","isAnyChat","peerId","isUser","isChat","newMethod","originMethod","bufferConcats","tmp","lastLength","onFinally","reason","WebpWorkerController","data","fileName","bytes","convertPromise","webpWorkerController","LocalStorage","lastError","stringified","_LocalStorageController","LocalStorageController","sessionStorage","isSwipingBackSafari","AppNavigationController","hash","wasIndex","good","single","appNavigationController","AppRuntimeManager","appRuntimeManager","copy","clonedObj","prop","IS_SHARED_WORKER_SUPPORTED","FOCUS_EVENT_NAME","IdleController","idle","idleController","CHECK_INSTANCE_INTERVAL","DEACTIVATE_TIMEOUT","MULTIPLE_TABS_THRESHOLD","IS_MULTIPLE_TABS_SUPPORTED","SingleInstance","newInstance","curInstance","build","apiManagerProxy","singleInstance","clearMessageId","messageId","toServer","getServerMessageId","PING_PUSH_INTERVAL","WebPushApiManager","reg","subscription","ACTIONS_LANG_MAP","action","successful","newSettings","subscriptionObj","mid","webPushApiManager","loadScript","script","tsNow","seconds","TelegramMeWebManager","canRedirect","curValue","ts","telegramMeWebManager","IS_WEBRTC_SUPPORTED","IS_CALL_SUPPORTED","CAN_USE_TRANSFERABLES","CAN_USE_TRANSFERABLES$1","IS_CANVAS_FILTER_SUPPORTED","IS_GEOLOCATION_SUPPORTED","IS_GROUP_CALL_SUPPORTED","IS_WEBP_SUPPORTED","IMAGE_MIME_TYPES_SUPPORTED","possible","mime","img","supported","IMAGE_MIME_TYPES_SUPPORTED_PROMISE","mimeTypes","video","IS_WEBM_SUPPORTED","IS_MOV_SUPPORTED","IS_H265_SUPPORTED","VIDEO_MIME_TYPES_SUPPORTED","MEDIA_MIME_TYPES_SUPPORTED","IS_PARALLAX_SUPPORTED","IS_SCREEN_SHARING_SUPPORTED","IS_VIBRATE_SUPPORTED","audio","IS_OPUS_SUPPORTED","IS_APPLE_MX","extension","renderer","IS_APPLE_MX$1","IS_LIVE_STREAM_SUPPORTED","ENVIRONMENT","IS_VIDEO_SUPPORTED","userAgent","getTimeFormat","offsetWidth","arrays","nextRandomUint","bits","randomLong","STATE_VERSION","BUILD","DEFAULT_THEME","makeDefaultAppTheme","baseTheme","highlightingColor","STATE_INIT","compareVersion","v1","v2","s1","s2","isObject","validateInitObject","initObject","currentObject","onReplace","previousKey","ignorePaths","_path","recordPromise","description","recordPromiseBound","REFRESH_EVERY","ALL_KEYS","REFRESH_KEYS","loadStateInner","totalPerf","pushedKeys","pushToState","replaceState","_state","auth","stateId","sessionBuild","authKeyFingerprint","baseDcAuthKey","shiftedWebKAuth","resetStorages","resetState","preserveKeys","_authKeyFingerprint","autoDownloadSettings","oldTypes","mediaType","peerTypeSettings","peerType","missingKey","newVersion","oldVersion","migrated","oldThemes","oldTheme","oldBackground","newTheme","getColorFromHex","hex","colors","wallPaper","wallPaperSettings","changed","theme","loadState","OpusDecodeController","typedArray","keepAlive","kill","pages","withWaveform","dataBlob","opusDecodeController","CryptoMessagePort","sendPortIndex","cryptoMessagePort","toArray","blobSafeMimeType","mimeType","blobConstruct","blobParts","safeMimeType","MemoryWriter","size","saveFileCallback","part","endOffset","newBytes","saveToStorage","blob","parts","_CacheStorageController","dbName","response","rejected","fileSize","CacheStorageController","toggleStorages","ServiceMessagePort","DEEP_PATH_JOINER","joinDeepPath","splitDeepPath","setDeepProperty","deleteIfUndefined","splitted","lastObject","lastKey","FILENAME_JOINER","getFileNameByLocation","location","ext","geoPoint","isWebFileLocation","getThumbKey","media","generateEmptyThumb","getStickerThumbKey","docId","toneIndex","callbackify","smth","isLegacyMessageId","$RAW","$NODE","$HAS","$SELF","wrap$1","proxyTraps$1","isWrappable","proto","unwrap","unwrapped","getNodes","symbol","nodes","getNode","proxyDescriptor$1","trackSelf","ownKeys","tracked","setProperty","deleting","mergeStoreNode","updateArray","next","updatePath","traversed","partType","from","to","by","createStore","unwrappedStore","wrappedStore","setStore","$ROOT","applyState","parent","merge","previous","keyVal","targetKeys","previousKeys","reconcile","appState","_setAppState","setAppState","setAppStateSilent","useAppState","getObjectKeysAndSort","sort","ids","createMemoOrReturn","valueOrGetter","usePeer","useChat","chatId","reconcilePeer","peer","reconcilePeers","peers","ApiManagerProxy","mirror","message","groupedId","_mid","previousMessage","map","storageTask","language","toClear","cacheName","iframe","onFinish","onLoad","serviceWorker","ServiceWorkerURL","registration","FIX_KEY","swfix","controller","worker","get","pathnameSplitted","pre","originals","originalUrl","createWorker","constructor","attachWorkerToPort","firstWorker","messagePort","stateResult","thumbSize","reaction","availableReactions","availableReaction","minMid","mids","userId","saved","photo","overwrite","appConfig","isPremiumPurchaseBlocked","apiManagerProxy$1","DEBUG_MANAGER_REQUESTS","createProxy","ack","createProxyProxy","proxied","getProxiedManagers","clamp","min","max","rgbToHsv","g","h","hsvToRgb","f","rgbaToHsla","hslaToString","hsla","hslaToRgba","hue2rgb","q","hslaStringToRgba","alpha","val","hexaToRgba","hexa","hexToRgb","hexaToHsla","rgba","rgbaToHexa","hslaStringToHexa","hslaStringToHex","mixColors","color1","color2","computePerceivedBrightness","color","getAverageColor","getAccentColor","baseHsv","baseColor","elementColor","hsvTemp3","hsvTemp4","dist","changeColorAccent","accentHsv","isDarkTheme","colorHsv","newColor","origBrightness","newBrightness","fallbackAmount","changeBrightness","amount","getHexColorFromTelegramColor","getRgbColorFromTelegramColor","getColorsFromWallPaper","rgbaToRgb","bg","calculateLuminance","rgb","getTextColor","luminance","calculateOpacity","targetContrast","targetTextLuminance","adaptiveOpacity","calcImageInBox","imageW","imageH","boxW","boxH","noZoom","makeMediaSize","boxedImageW","boxedImageH","MediaSize","width","height","boxSize","fitted","ScreenSize","ScreenSize2","MOBILE_SIZE","MEDIUM_SIZE","LARGE_SIZE","CUSTOM_EMOJI_SIZE","ESG_CUSTOM_EMOJI_SIZE","EMOJI_STATUS_SIZE","MediaSizes","innerWidth","activeScreen","wasScreen","mediaSizes","CustomProperties","night","customProperties","createUnifiedSignal","getter","WindowSize","windowSize","LiteMode","liteMode","appColorMap","colorMap","ThemeController","coordinates","themeColorElem","darkModeMediaQuery","checkDarkMode","highlightingRgba","silent","isNight","wasApplied","reverse","transition","endRadius","appliedColors","_options","lightenAlpha","darkenAlpha","mixColor","saveToCache","appColor","lightenedRgb","darkenedHsla","properties","currentTheme","themes","themeSettings","newAppTheme","baseColors","hsvTemp1","hsvTemp2","newAccentRgb","newAccentHex","applyAppColor","finalize","messageLightenAlpha","baseMessageColor","baseMessageOutBackgroundColor","myMessagesAccent","nextColor","accentColor2","newMessageOutBackgroundColor","messageOutBackgroundColorHsl","themePropertiesMap","themeParams","themeController","OverlayCounter","overlayCounter","parseUriParams","uri","parseUriParamsLine","line","params","IS_INSTALL_PROMPT_SUPPORTED","cacheInstallPrompt","deferredPrompt","outcome","getInstallPrompt","months","days","monthsLocalized","daysLocalized","ONE_DAY","ONE_DAY_MINUTES","ONE_WEEK_MINUTES","getWeekDays","getMonths","fillLocalizedDates","getWeekNumber","dayNum","yearStart","formatDate","today","formatDateAccordingToTodayNew","now","timestamp","formatTimeOptions","formatFullSentTimeRaw","diff","timeEl","formatTime","dateEl","formatFullSentTime","capitalize","noToday","fragment","getFullDate","fullYear","formatMonthsDuration","bold","isYears","minYear","yearPattern","anyLetterRegExp","monthPattern","monthYearOrDayPattern","yearOrDayAndMonthPattern","shortDate","longDate","numberOfDaysEachMonth","fillTipDates","query","dates","haystack","year","month","day","minDate","maxDate","dayOfWeek","getDayOfWeek","currentDay","distance","formatWeekLong","matches","g1","g2","k1","selectedYear","createForMonthYear","createForDayMonth","g3","currentYear","validDateForMonth","formatterYearMax","getMonth","formatterMonthYear","isLeapYear","formatterDayMonth","USE_NATIVE_SCROLL","IS_OVERLAY_SCROLL_SUPPORTED","USE_CUSTOM_SCROLL","manifest","setViewportVH","lastVH","setVH","vh","preparePrint","chat","chatClone","bubbles","bubblesInner","printable","removePrint","toggleResizeMode","wasTabId","langPromise","fadeInWhenFontsReady","authState","urlSearchParams","placeholder","webPushApiManager$1","meModule","pushModule","pagePromise"],"ignoreList":[27],"sources":["../src/config/app.ts","../src/helpers/dom/blurActiveElement.ts","../src/helpers/dom/cancelEvent.ts","../src/environment/touchSupport.ts","../src/environment/ctx.ts","../src/environment/userAgent.ts","../src/helpers/dom/findUpClassName.ts","../src/helpers/schedulers.ts","../src/helpers/dom/fixSafariStickyInput.ts","../src/helpers/dom/fixSafariStickyInputFocusing.ts","../src/config/font.ts","../src/helpers/noop.ts","../src/helpers/schedulers/pause.ts","../src/helpers/tgico.ts","../src/helpers/dom/loadFonts.ts","../src/environment/emojiSupport.ts","../src/helpers/setWorkerProxy.ts","../src/helpers/dom/toggleAttributePolyfill.ts","../src/lib/mtproto/mtproto_config.ts","../src/helpers/eventListenerBase.ts","../src/config/modes.ts","../src/config/debug.ts","../src/config/tabId.ts","../src/helpers/array/indexOfAndSplice.ts","../src/helpers/context.ts","../src/helpers/makeError.ts","../src/helpers/dT.ts","../src/lib/logger.ts","../src/lib/mtproto/superMessagePort.ts","../src/lib/mtproto/mtprotoMessagePort.ts","../src/lib/rootScope.ts","../src/helpers/cancellablePromise.ts","../src/helpers/schedulers/throttle.ts","../src/helpers/object/safeAssign.ts","../src/lib/files/idb.ts","../src/lib/storage.ts","../src/config/databases/state.ts","../src/lib/stateStorage.ts","../src/helpers/object/deepEqual.ts","../src/helpers/string/capitalizeFirstLetter.ts","../src/lib/richTextProcessor/matchUrlProtocol.ts","../src/vendor/emoji/regex.ts","../src/lib/richTextProcessor/index.ts","../src/lib/richTextProcessor/wrapUrl.ts","../src/helpers/dom/setInnerHTML.ts","../src/lib/richTextProcessor/setBlankToAnchor.ts","../src/vendor/solid/dist/solid.js","../src/lib/langPack.ts","../src/lib/appManagers/utils/peers/isAnyChat.ts","../src/lib/appManagers/utils/peers/isUser.ts","../src/helpers/peerIdPolyfill.ts","../src/helpers/bytes/bufferConcats.ts","../src/lib/polyfill.ts","../src/lib/webp/webpWorkerController.ts","../src/lib/localStorage.ts","../src/lib/sessionStorage.ts","../src/helpers/dom/isSwipingBackSafari.ts","../src/components/appNavigationController.ts","../src/lib/appManagers/appRuntimeManager.ts","../src/helpers/object/copy.ts","../src/environment/sharedWorkerSupport.ts","../src/helpers/idleController.ts","../src/lib/mtproto/singleInstance.ts","../src/lib/appManagers/utils/messageId/clearMessageId.ts","../src/lib/appManagers/utils/messageId/getServerMessageId.ts","../src/lib/mtproto/webPushApiManager.ts","../src/helpers/dom/loadScript.ts","../src/helpers/tsNow.ts","../src/lib/mtproto/telegramMeWebManager.ts","../src/environment/webrtcSupport.ts","../src/environment/callSupport.ts","../src/environment/canUseTransferables.ts","../src/environment/canvasFilterSupport.ts","../src/environment/geolocationSupport.ts","../src/environment/groupCallSupport.ts","../src/environment/webpSupport.ts","../src/environment/imageMimeTypesSupport.ts","../src/environment/videoSupport.ts","../src/environment/videoMimeTypesSupport.ts","../src/environment/mediaMimeTypesSupport.ts","../src/environment/parallaxSupport.ts","../src/environment/screenSharingSupport.ts","../src/environment/vibrateSupport.ts","../src/environment/opusSupport.ts","../src/environment/appleMx.ts","../src/environment/liveStreamSupport.ts","../src/environment/index.ts","../src/helpers/getTimeFormat.ts","../src/helpers/random.ts","../src/config/state.ts","../src/helpers/compareVersion.ts","../src/helpers/object/isObject.ts","../src/helpers/object/validateInitObject.ts","../src/helpers/recordPromise.ts","../src/lib/appManagers/utils/state/loadState.ts","../src/lib/opusDecodeController.ts","../src/lib/crypto/cryptoMessagePort.ts","../src/helpers/array/toArray.ts","../src/helpers/blob/blobSafeMimeType.ts","../src/helpers/blob/blobConstruct.ts","../src/lib/files/memoryWriter.ts","../src/lib/files/cacheStorage.ts","../src/helpers/toggleStorages.ts","../src/lib/serviceWorker/serviceMessagePort.ts","../src/helpers/object/setDeepProperty.ts","../src/helpers/fileName.ts","../src/lib/appManagers/utils/webFiles/isWebFileLocation.ts","../src/lib/storages/utils/thumbs/getThumbKey.ts","../src/lib/storages/utils/thumbs/generateEmptyThumb.ts","../src/lib/storages/utils/thumbs/getStickerThumbKey.ts","../src/helpers/callbackify.ts","../src/lib/appManagers/utils/messageId/isLegacyMessageId.ts","../src/vendor/solid/store/dist/store.js","../src/stores/appState.ts","../src/helpers/object/getObjectKeysAndSort.ts","../src/stores/peers.ts","../src/lib/mtproto/mtprotoworker.ts","../src/lib/appManagers/getProxiedManagers.ts","../src/helpers/number/clamp.ts","../src/helpers/color.ts","../src/helpers/calcImageInBox.ts","../src/helpers/mediaSize.ts","../src/helpers/mediaSizes.ts","../src/helpers/dom/customProperties.ts","../src/helpers/solid/createUnifiedSignal.ts","../src/helpers/windowSize.ts","../src/helpers/liteMode.ts","../src/helpers/themeController.ts","../src/helpers/overlayCounter.ts","../src/helpers/string/parseUriParams.ts","../src/environment/installPrompt.ts","../src/helpers/dom/installPrompt.ts","../src/helpers/date.ts","../src/environment/overlayScrollSupport.ts","../src/index.ts"],"sourcesContent":["/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport type {TrueDcId} from '../types';\n\nexport const MAIN_DOMAINS = ['web.telegram.org', 'webk.telegram.org'];\nexport const DEFAULT_BACKGROUND_SLUG = 'pattern';\n\nconst threads = Math.min(4, navigator.hardwareConcurrency ?? 4);\n\nconst App = {\n id: +import.meta.env.VITE_API_ID,\n hash: import.meta.env.VITE_API_HASH,\n version: import.meta.env.VITE_VERSION,\n versionFull: import.meta.env.VITE_VERSION_FULL,\n build: +import.meta.env.VITE_BUILD,\n langPackVersion: '5.5.8',\n langPack: 'webk',\n langPackCode: 'en',\n domains: MAIN_DOMAINS,\n baseDcId: 2 as TrueDcId,\n isMainDomain: MAIN_DOMAINS.includes(location.hostname),\n suffix: 'K',\n threads,\n cryptoWorkers: threads\n};\n\nif(App.isMainDomain) { // use Webogram credentials then\n App.id = 2496;\n App.hash = '8da85b0d5bfe62527e5b244c209159c3';\n}\n\nexport default App;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nexport default function blurActiveElement() {\n if((document.activeElement as HTMLInputElement)?.blur) {\n (document.activeElement as HTMLInputElement).blur();\n return true;\n }\n\n return false;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nexport default function cancelEvent(event?: Event) {\n event ||= window.event;\n if(event) {\n // 'input' event will have cancelable=false, but we still need to preventDefault\n // if(!event.cancelable) {\n // return false;\n // }\n\n // @ts-ignore\n event = event.originalEvent || event;\n\n try {\n if(event.stopPropagation) event.stopPropagation();\n if(event.preventDefault) event.preventDefault();\n event.returnValue = false;\n event.cancelBubble = true;\n } catch(err) {}\n }\n\n return false;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\n// @ts-ignore\nconst IS_TOUCH_SUPPORTED = ('ontouchstart' in window) || (window.DocumentTouch && document instanceof DocumentTouch)/* || true */;\nexport default IS_TOUCH_SUPPORTED;\n","const ctx = typeof(window) !== 'undefined' ? window : self;\n\nexport default ctx;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport ctx from './ctx';\n\nexport const USER_AGENT = navigator ? navigator.userAgent : null;\nexport const IS_APPLE = navigator.userAgent.search(/OS X|iPhone|iPad|iOS/i) !== -1;\nexport const IS_ANDROID = navigator.userAgent.toLowerCase().indexOf('android') !== -1;\nexport const IS_CHROMIUM = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);\nexport const CHROMIUM_VERSION = (() => {\n try {\n return +navigator.userAgent.match(/Chrom(?:e|ium)\\/(.+?)(?:\\s|\\.)/)[1];\n } catch(err) {\n }\n})();\n\n// https://stackoverflow.com/a/58065241\nexport const IS_APPLE_MOBILE = (/iPad|iPhone|iPod/.test(navigator.platform) ||\n (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&\n !(ctx as any).MSStream;\n\nexport const IS_SAFARI = !!('safari' in ctx) || !!(USER_AGENT && (/\\b(iPad|iPhone|iPod)\\b/.test(USER_AGENT) || (!!USER_AGENT.match('Safari') && !USER_AGENT.match('Chrome'))))/* || true */;\nexport const IS_FIREFOX = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;\n\nexport const IS_MOBILE_SAFARI = IS_SAFARI && IS_APPLE_MOBILE;\n\nexport const IS_MOBILE = (navigator.maxTouchPoints === undefined || navigator.maxTouchPoints > 0) && navigator.userAgent.search(/iOS|iPhone OS|Android|BlackBerry|BB10|Series ?[64]0|J2ME|MIDP|opera mini|opera mobi|mobi.+Gecko|Windows Phone/i) != -1;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\n// export function findUpClassName<T>(el: any, className: string): T;\nexport default function findUpClassName(el: EventTarget | {closest: (selector: string) => any}, className: string): HTMLElement {\n return (el as any).closest('.' + className);\n /* if(el.classList.contains(className)) return el; // 03.02.2020\n\n while(el.parentElement) {\n el = el.parentElement;\n if(el.classList.contains(className))\n return el;\n }\n return null; */\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\n// * Jolly Cobra's schedulers\nimport {NoneToVoidFunction} from '../types';\n\n/*\nexport function throttleWithTickEnd<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n} */\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nexport function fastRaf(callback: NoneToVoidFunction) {\n if(!fastRafCallbacks) {\n fastRafCallbacks = [callback];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n fastRafCallbacks = undefined;\n currentCallbacks.forEach((cb) => cb());\n });\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nlet fastRafConventionalCallbacks: NoneToVoidFunction[] | undefined, processing = false;\nexport function fastRafConventional(callback: NoneToVoidFunction) {\n if(!fastRafConventionalCallbacks) {\n fastRafConventionalCallbacks = [callback];\n\n requestAnimationFrame(() => {\n processing = true;\n for(let i = 0; i < fastRafConventionalCallbacks.length; ++i) {\n fastRafConventionalCallbacks[i]();\n }\n\n fastRafConventionalCallbacks = undefined;\n processing = false;\n });\n } else if(processing) {\n callback();\n } else {\n fastRafConventionalCallbacks.push(callback);\n }\n}\n\nlet rafPromise: Promise<void>;\nexport function fastRafPromise() {\n if(rafPromise) return rafPromise;\n\n rafPromise = new Promise<void>((resolve) => fastRaf(() => resolve()));\n rafPromise.then(() => {\n rafPromise = undefined;\n });\n\n return rafPromise;\n}\n\nexport function doubleRaf() {\n return new Promise<void>((resolve) => {\n fastRaf(() => {\n fastRaf(resolve);\n });\n });\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {doubleRaf} from '../schedulers';\n\nexport default function fixSafariStickyInput(input: HTMLElement) {\n input.style.transform = 'translateY(-99999px)';\n /* input.style.position = 'fixed';\n input.style.top = '-99999px';\n input.style.left = '0'; */\n input.focus();\n\n // setTimeout(() => {\n doubleRaf().then(() => {\n // fastSmoothScroll(findUpClassName(input, 'scrollable-y') || window as any, document.activeElement as HTMLElement, 'start', 4, undefined, FocusDirection.Static);\n /* input.style.position = '';\n input.style.top = ''; */\n input.style.transform = '';\n // fastSmoothScroll(findUpClassName(input, 'scrollable-y') || window as any, document.activeElement as HTMLElement, 'start', 4, undefined, FocusDirection.Static);\n\n /* setTimeout(() => {\n fastSmoothScroll(findUpClassName(input, 'scrollable-y') || window as any, document.activeElement as HTMLElement, 'start', 4);\n }, 50); */\n });\n // }, 0);\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport IS_TOUCH_SUPPORTED from '../../environment/touchSupport';\nimport {IS_MOBILE, IS_SAFARI} from '../../environment/userAgent';\nimport findUpClassName from './findUpClassName';\nimport fixSafariStickyInput from './fixSafariStickyInput';\n\nexport const IS_STICKY_INPUT_BUGGED = IS_SAFARI && IS_MOBILE && IS_TOUCH_SUPPORTED && false;\n\nif(IS_STICKY_INPUT_BUGGED) {\n const key: 'clientY' | 'pageY' = 'clientY';\n let startY = 0;\n const o = {capture: true, passive: false};\n const onTouchMove = (e: TouchEvent) => {\n const touch = e.touches[0];\n\n // console.log('touchmove y', touch[key], startY);\n\n const scrollable = findUpClassName(touch.target, 'scrollable-y');\n if(scrollable) {\n const y = touch[key];\n const scrolled = startY - y;\n\n /* if(y < startY) {\n startY = y;\n } */\n\n const scrollTop = scrollable.scrollTop;\n const scrollHeight = scrollable.scrollHeight;\n const clientHeight = scrollable.clientHeight;\n const nextScrollTop = scrollTop ? Math.round(scrollTop + scrollable.clientHeight + scrolled) : scrollTop + scrolled;\n // const needCancel = scrollHeight !== clientHeight ? (scrollTop && diff <= 1) || (scrollTop - diff) < 0 : true;\n const needCancel = scrollHeight === clientHeight || nextScrollTop >= scrollHeight || nextScrollTop <= 0;\n if(needCancel) {\n e.preventDefault();\n }\n\n // console.log('touchmove with scrollable', scrollTop, startY, scrolled, nextScrollTop, needCancel, e.cancelable);\n } else {\n e.preventDefault();\n\n // console.log('touchmove no scrollable', e, touch);\n }\n\n // if(e.target === document.documentElement || e.target === document.body) e.preventDefault();\n };\n\n // let el = document.createElement('div');\n // document.body.prepend(el);\n // let a = 0;\n\n // let hasFocus = false;\n let lastFocusOutTimeStamp = 0;\n document.addEventListener('focusin', (e) => {\n if(!(e.target as HTMLElement).classList.contains('is-sticky-input-bugged') || (e.timeStamp - lastFocusOutTimeStamp) < 50/* && document.activeElement === input */) {\n return;\n }\n\n // console.log('focusin', e, e.timeStamp);\n\n // hasFocus = true;\n // document.body.classList.add('is-keyboard-opened');\n\n // el.innerText = 'focusin ' + ++a;\n\n /* a < 2 && */fixSafariStickyInput(e.target as HTMLElement);\n\n document.addEventListener('touchmove', onTouchMove, o);\n document.addEventListener('touchstart', (e) => {\n if(e.touches.length > 1) return;\n const touchStart = e.touches[0];\n\n startY = touchStart[key];\n });\n }, {passive: true});\n\n document.addEventListener('focusout', (e) => {\n // console.log('focusout', e, e.timeStamp);\n document.removeEventListener('touchmove', onTouchMove, o);\n\n lastFocusOutTimeStamp = e.timeStamp;\n\n // el.innerText = 'focusout ' + ++a;\n\n // if(hasFocus) {\n // hasFocus = false;\n // document.body.classList.remove('is-keyboard-opened');\n // }\n }, {passive: true});\n\n document.addEventListener('visibilitychange', () => {\n // console.log('window visibilitychange');\n if(document.activeElement &&\n document.activeElement.classList.contains('is-sticky-input-bugged') &&\n (document.activeElement as HTMLElement).blur) {\n fixSafariStickyInput(document.activeElement as HTMLElement);\n }\n\n /* blurActiveElement();\n window.scrollTo(0, 0);\n setVH(); */\n }, {passive: true});\n}\n\nexport default function fixSafariStickyInputFocusing(input: HTMLElement) {\n if(!IS_STICKY_INPUT_BUGGED) return;\n input.classList.add('is-sticky-input-bugged');\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nexport const FontFamilyName = 'Roboto';\nexport const FontFamily = FontFamilyName + ', -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen-Sans, Ubuntu, Cantarell, \"Helvetica Neue\", sans-serif';\nexport const FontSize = '16px';\nexport const FontWeight = '400';\nexport const FontFull = `${FontWeight} ${FontSize} ${FontFamily}`;\n","export default function noop() {}\n","export default function pause(ms: number) {\n return new Promise<void>((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n","export const TGICO_CLASS = 'tgico';\nexport default function tgico(icon: Icon) {\n return [TGICO_CLASS, _tgico(icon)];\n}\n\nexport function _tgico(icon: Icon) {\n return TGICO_CLASS + '-' + icon;\n}\n\nexport function tgico_(icon: Icon) {\n return tgico(icon).join(' ');\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {FontFamilyName} from '../../config/font';\nimport noop from '../noop';\nimport pause from '../schedulers/pause';\nimport {TGICO_CLASS} from '../tgico';\n\nconst texts = ['b', 'б'];\ntype FontType = 'text' | 'icons' | 'monospace';\n\nconst cache: {\n [key: string]: {\n [text: string]: Promise<any>\n }\n} = {};\n\nconst fonts: {[type in FontType]: string} = {\n text: FontFamilyName,\n icons: TGICO_CLASS,\n monospace: 'Roboto Mono'\n};\n\nexport default function loadFonts(types: {[type in FontType]?: string[] | 'all'} = {\n text: texts,\n icons: undefined,\n monospace: texts\n}): Promise<any> {\n if(!('fonts' in document)) {\n return Promise.resolve();\n }\n\n const promises: Promise<any>[] = [];\n for(const type in types) {\n let _texts = types[type as FontType];\n if(_texts === 'all') {\n _texts = texts;\n }\n\n const font = fonts[type as FontType];\n const weights = type === 'icons' ? [500] : [400, 500];\n for(const weight of weights) {\n const _promises = (_texts || [undefined]).map((text) => {\n const key = [weight, '1rem', font].join(' ');\n const promise = (cache[key] ??= {})[text || ''] ??= document.fonts.load(key, text);\n return promise;\n });\n promises.push(..._promises);\n }\n }\n\n return Promise.race([\n Promise.all(promises).catch(noop),\n pause(1000)\n ]);\n}\n","const IS_EMOJI_SUPPORTED = navigator.userAgent.search(/OS X|iPhone|iPad|iOS/i) !== -1/* && false *//* || true */;\n\nexport default IS_EMOJI_SUPPORTED;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nexport function makeWorkerURL(url: string | URL) {\n if(!(url instanceof URL)) {\n url = new URL(url + '', location.href);\n }\n\n if(location.search && url.protocol !== 'blob:') {\n const params = new URLSearchParams(location.search);\n params.forEach((value, key) => {\n (url as URL).searchParams.set(key, value);\n });\n }\n\n // exclude useless params\n (url as URL).searchParams.delete('swfix');\n\n return url;\n}\n\nexport default function setWorkerProxy() {\n // * hook worker constructor to set search parameters (test, debug, etc)\n const workerHandler = {\n construct(target: any, args: any) {\n args[0] = makeWorkerURL(args[0]);\n return new target(...args);\n }\n };\n\n [\n Worker,\n typeof(SharedWorker) !== 'undefined' && SharedWorker\n ].filter(Boolean).forEach((w) => {\n window[w.name as any] = new Proxy(w, workerHandler);\n });\n}\n\nsetWorkerProxy();\n","export default function toggleAttributePolyfill() {\n if(!Element.prototype.toggleAttribute) {\n Element.prototype.toggleAttribute = function(name, force) {\n if(force !== void 0) force = !!force;\n\n if(this.hasAttribute(name)) {\n if(force) return true;\n\n this.removeAttribute(name);\n return false;\n }\n if(force === false) return false;\n\n this.setAttribute(name, '');\n return true;\n };\n }\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {MyDialogFilter} from '../storages/filters';\n\n/**\n * Legacy Webogram's format, don't change dcID to camelCase. date is timestamp\n */\nexport type UserAuth = {dcID: number | string, date: number, id: PeerId};\nexport type REAL_FOLDER_ID = 0 | 1;\n\nexport const NULL_PEER_ID: PeerId = 0;\nexport const REPLIES_PEER_ID: PeerId = 1271266957;\nexport const REPLIES_HIDDEN_CHANNEL_ID: ChatId = 777;\nexport const HIDDEN_PEER_ID: PeerId = 2666000;\nexport const SERVICE_PEER_ID: PeerId = 777000;\nexport const MUTE_UNTIL = 0x7FFFFFFF;\nexport const BOT_START_PARAM = '';\nexport const MAX_FILE_SAVE_SIZE = 20 * 1024 * 1024;\nexport const THUMB_TYPE_FULL = '';\nexport const TOPIC_COLORS = [0x6FB9F0, 0xFFD67E, 0xCB86DB, 0x8EEE98, 0xFF93B2, 0xFB6F5F];\nexport const ATTACH_MENU_BOT_ICON_NAME = 'default_static';\nexport const MESSAGE_ID_OFFSET = 0x100000000;\nexport const GENERAL_TOPIC_ID = MESSAGE_ID_OFFSET + 1;\nexport const CAN_HIDE_TOPIC = false;\nexport const T_ME_PREFIXES = new Set(['web', 'k', 'z', 'a']);\nexport const SEND_WHEN_ONLINE_TIMESTAMP = 0x7FFFFFFE;\nexport const SERVER_IMAGE_MIME_TYPES = new Set(['image/jpeg', 'image/png', 'image/bmp', 'image/gif']);\nexport const STARS_CURRENCY = 'XTR';\n\nexport const FOLDER_ID_ALL: REAL_FOLDER_ID = 0;\nexport const FOLDER_ID_ARCHIVE: REAL_FOLDER_ID = 1;\nexport const REAL_FOLDERS: Set<number> = new Set([FOLDER_ID_ALL, FOLDER_ID_ARCHIVE]);\nexport const START_LOCAL_ID = Math.max(...Array.from(REAL_FOLDERS)) + 1 as MyDialogFilter['localId'];\n\nexport const TEST_NO_STORIES = false;\nexport const TEST_NO_SAVED = false;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\n// import { MOUNT_CLASS_TO } from \"../config/debug\";\nimport type {ArgumentTypes, SuperReturnType} from '../types';\n\n// class EventSystem {\n// wm: WeakMap<any, Record<any, Set<any>>> = new WeakMap();\n\n// add(target: any, event: any, listener: any) {\n// let listeners = this.wm.get(target);\n// if (listeners === undefined) {\n// listeners = {};\n// }\n// let listenersForEvent = listeners[event];\n// if (listenersForEvent === undefined) {\n// listenersForEvent = new Set();\n// }\n// listenersForEvent.add(listener);\n// listeners[event] = listenersForEvent;\n// //target.addEventListener(event, listener);\n// this.wm.set(target, listeners);\n// };\n\n// remove(target: any, event: any, listener: any) {\n// let listeners = this.wm.get(target);\n// if (!listeners) return;\n// let listenersForEvent = listeners[event];\n// if (!listenersForEvent) return;\n// listenersForEvent.delete(listener);\n// };\n\n// /* fire(target, event) {\n// let listeners = this.wm.get(target);\n// if (!listeners) return;\n// let listenersForEvent = listeners[event];\n// if (!listenersForEvent) return;\n// for (let handler of handlers) {\n// setTimeout(handler, 0, event, target); // we use a setTimeout here because we want event triggering to be asynchronous.\n// }\n// }; */\n// }\n\n// console.log = () => {};\n\n// const e = new EventSystem();\n// MOUNT_CLASS_TO.e = e;\n\nexport type EventListenerListeners = Record<string, Function>;\n// export type EventListenerListeners = Record<string, (...args: any[]) => any>;\n// export type EventListenerListeners = {[name in string]: Function};\n\n/**\n * Better not to remove listeners during setting\n * Should add listener callback only once\n */\n\ntype ListenerObject<T> = {callback: T, options: boolean | AddEventListenerOptions};\n\n// type EventLitenerCallback<T> = (data: T) =>\n// export default class EventListenerBase<Listeners extends {[name: string]: Function}> {\nexport default class EventListenerBase<Listeners extends EventListenerListeners> {\n protected listeners: Partial<{\n [k in keyof Listeners]: Set<ListenerObject<Listeners[k]>>\n }>;\n protected listenerResults: Partial<{\n [k in keyof Listeners]: ArgumentTypes<Listeners[k]>\n }>;\n\n private reuseResults: boolean;\n\n constructor(reuseResults?: boolean) {\n this._constructor(reuseResults);\n }\n\n public _constructor(reuseResults?: boolean): any {\n this.reuseResults = reuseResults;\n this.listeners = {};\n this.listenerResults = {};\n }\n\n public addEventListener<T extends keyof Listeners>(name: T, callback: Listeners[T], options?: boolean | AddEventListenerOptions) {\n const listenerObject: ListenerObject<Listeners[T]> = {callback, options};\n (this.listeners[name] ??= new Set()).add(listenerObject); // ! add before because if you don't, you won't be able to delete it from callback\n\n if(this.listenerResults.hasOwnProperty(name)) {\n callback(...this.listenerResults[name]);\n\n if((options as AddEventListenerOptions)?.once) {\n this.listeners[name].delete(listenerObject);\n return;\n }\n }\n\n // e.add(this, name, {callback, once});\n }\n\n public addMultipleEventsListeners(obj: {\n [name in keyof Listeners]?: Listeners[name]\n }) {\n for(const i in obj) {\n this.addEventListener(i, obj[i]);\n }\n }\n\n public removeEventListener<T extends keyof Listeners>(\n name: T,\n callback: Listeners[T],\n options?: boolean | AddEventListenerOptions\n ) {\n if(this.listeners[name]) {\n for(const l of this.listeners[name]) {\n if(l.callback === callback) {\n this.listeners[name].delete(l);\n break;\n }\n }\n }\n // e.remove(this, name, callback);\n }\n\n protected invokeListenerCallback<T extends keyof Listeners, L extends ListenerObject<any>>(\n name: T,\n listener: L,\n ...args: ArgumentTypes<L['callback']>\n ) {\n let result: any, error: any;\n try {\n result = listener.callback(...args);\n } catch(err) {\n error = err;\n // console.error('listener callback error', err);\n }\n\n if((listener.options as AddEventListenerOptions)?.once) {\n this.removeEventListener(name, listener.callback);\n }\n\n if(error) {\n throw error;\n }\n\n return result;\n }\n\n private _dispatchEvent<T extends keyof Listeners>(\n name: T,\n collectResults: boolean,\n ...args: ArgumentTypes<Listeners[T]>\n ) {\n if(this.reuseResults) {\n this.listenerResults[name] = args;\n }\n\n const arr: Array<SuperReturnType<Listeners[typeof name]>> = collectResults && [];\n\n const listeners = this.listeners[name];\n if(listeners) {\n for(const listener of listeners) {\n const result = this.invokeListenerCallback(name, listener, ...args);\n if(arr) {\n arr.push(result);\n }\n }\n }\n\n return arr;\n }\n\n public dispatchResultableEvent<T extends keyof Listeners>(name: T, ...args: ArgumentTypes<Listeners[T]>) {\n return this._dispatchEvent(name, true, ...args);\n }\n\n // * must be protected, but who cares\n public dispatchEvent<L extends EventListenerListeners = Listeners, T extends keyof L = keyof L>(\n name: T,\n ...args: ArgumentTypes<L[T]>\n ) {\n // @ts-ignore\n this._dispatchEvent(name, false, ...args);\n }\n\n public cleanup() {\n this.listeners = {};\n this.listenerResults = {};\n }\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport type {TransportType} from '../lib/mtproto/dcConfigurator';\n\nconst Modes = {\n test: location.search.indexOf('test=1') > 0/* || true */,\n debug: location.search.indexOf('debug=1') > 0,\n http: false,\n ssl: true, // location.search.indexOf('ssl=1') > 0 || location.protocol === 'https:' && location.search.indexOf('ssl=0') === -1,\n asServiceWorker: !!import.meta.env.VITE_MTPROTO_SW,\n transport: 'websocket' as TransportType,\n noSharedWorker: location.search.indexOf('noSharedWorker=1') > 0,\n multipleTransports: !!(import.meta.env.VITE_MTPROTO_AUTO && import.meta.env.VITE_MTPROTO_HAS_HTTP && import.meta.env.VITE_MTPROTO_HAS_WS)\n};\n\nif(import.meta.env.VITE_MTPROTO_HAS_HTTP) {\n const httpOnly = Modes.http = location.search.indexOf('http=1') > 0;\n if(httpOnly) {\n Modes.multipleTransports = false;\n }\n}\n\n// * start with HTTP first\nif(Modes.multipleTransports) {\n Modes.http = true;\n}\n\nif(Modes.http) {\n Modes.transport = 'https';\n}\n\nexport default Modes;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport Modes from './modes';\n\nexport const IS_BETA = import.meta.env.DEV;\nexport const DEBUG = (IS_BETA || Modes.debug)/* && false */;\nconst ctx: any = typeof(window) !== 'undefined' ? window : self;\nexport const MOUNT_CLASS_TO: any = DEBUG || true/* && false */ ? ctx : {};\nexport default DEBUG;\n\n// let m = DEBUG;\n/* if(!DEBUG) {\n ctx.sandpitTurtle = () => {\n //if(!m) {\n for(let i in MOUNT_CLASS_TO) {\n ctx[i] = MOUNT_CLASS_TO[i];\n }\n //m = true;\n //}\n\n //DEBUG = !DEBUG;\n };\n} */\n\n/* export const superDebug = (object: any, key: string) => {\n var d = object[key];\n var beforeStr = '', afterStr = '';\n for(var r of d) {\n beforeStr += r.before.hex + '\\n';\n afterStr += r.after.hex + '\\n';\n }\n\n beforeStr = beforeStr.trim();\n afterStr = afterStr.trim();\n //var beforeStr = d.map((r) => r.before.hex).join('\\n');\n //var afterStr = d.map((r) => r.after.hex).join('\\n');\n\n var dada = (name: string, str: string) => {\n var a = document.createElement('a');\n a.target = '_blank';\n a.download = name + '.txt';\n a.href = URL.createObjectURL(new Blob([str], {\n type: 'text/plain'\n }));\n document.body.append(a);\n a.click();\n };\n\n dada(key + '_' + 'before', beforeStr);\n dada(key + '_' + 'after', afterStr);\n}\n\nMOUNT_CLASS_TO.superDebug = superDebug; */\n","const tabId = Date.now() % Math.random() * 100000000 | 0;\nexport default tabId;\n","export default function indexOfAndSplice<T>(array: Array<T>, item: T) {\n const idx = array.indexOf(item);\n const spliced = idx === -1 ? undefined : array.splice(idx, 1);\n return spliced?.[0];\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\n// в SW может быть сразу две переменных TRUE\nexport const IS_SERVICE_WORKER = typeof ServiceWorkerGlobalScope !== 'undefined' && self instanceof ServiceWorkerGlobalScope;\nexport const IS_WEB_WORKER = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope && !IS_SERVICE_WORKER;\nexport const IS_WORKER = IS_WEB_WORKER || IS_SERVICE_WORKER;\n\nexport const getWindowClients = () => {\n return (self as any as ServiceWorkerGlobalScope)\n .clients\n .matchAll({includeUncontrolled: false, type: 'window'});\n};\n\nexport const getLastWindowClient = () => getWindowClients().then((windowClients) => windowClients.slice(-1)[0]);\n\nconst postMessage = (listener: WindowClient | DedicatedWorkerGlobalScope, ...args: any[]) => {\n try {\n // @ts-ignore\n listener.postMessage(...args);\n } catch(err) {\n console.error('[worker] postMessage error:', err, args);\n }\n};\n\nconst notifyServiceWorker = (all: boolean, ...args: any[]) => {\n getWindowClients().then((listeners) => {\n if(!listeners.length) {\n // console.trace('no listeners?', self, listeners);\n return;\n }\n\n listeners.slice(all ? 0 : -1).forEach((listener) => {\n postMessage(listener, ...args);\n });\n });\n};\n\nconst notifyWorker = (...args: any[]) => {\n postMessage(self as any as DedicatedWorkerGlobalScope, ...args);\n};\n\nconst noop = () => {};\n\nexport const notifySomeone = IS_SERVICE_WORKER ? notifyServiceWorker.bind(null, false) : (IS_WEB_WORKER ? notifyWorker : noop);\nexport const notifyAll = IS_SERVICE_WORKER ? notifyServiceWorker.bind(null, true) : (IS_WEB_WORKER ? notifyWorker : noop);\n","const CACHED_ERRORS: {[key in Error['type']]?: ApiError} = {};\nexport default function makeError(type: Error['type']) {\n return CACHED_ERRORS[type] ??= {\n type\n };\n}\n","const _logTimer = Date.now();\nexport default function dT() {\n return '[' + ((Date.now() - _logTimer) / 1000).toFixed(3) + ']';\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport DEBUG from '../config/debug';\nimport {IS_FIREFOX, IS_SAFARI} from '../environment/userAgent';\nimport {IS_SERVICE_WORKER, IS_WEB_WORKER} from '../helpers/context';\nimport dT from '../helpers/dT';\n\nexport enum LogTypes {\n None = 0,\n Error = 1,\n Warn = 2,\n Log = 4,\n Debug = 8\n};\n\nexport const LOG_LEVELS = [LogTypes.None, LogTypes.Error, LogTypes.Warn, LogTypes.Log, LogTypes.Debug];\n\nconst IS_WEBKIT = IS_SAFARI || IS_FIREFOX;\n\n// let getCallerFunctionNameFromLine: (line: string) => string;\n// if(IS_WEBKIT) {\n// getCallerFunctionNameFromLine = (line) => {\n// const splitted = line.split('@');\n// return splitted[0];\n// };\n// } else {\n// getCallerFunctionNameFromLine = (line: string) => {\n// const splitted = line.trim().split(' ');\n// if(splitted.length === 3) {\n// return splitted[1].slice(splitted[1].lastIndexOf('.') + 1);\n// }\n// };\n// }\n\nconst STYLES_SUPPORTED = !IS_WEBKIT;\n// const LINE_INDEX = IS_WEBKIT ? 2 : 3;\n\n// function getCallerFunctionName() {\n// const stack = new Error().stack;\n// const lines = stack.split('\\n');\n// const line = lines[LINE_INDEX] || lines[lines.length - 1];\n// // const match = line.match(/\\.([^\\.]+?)\\s/);\n// // line = match ? match[1] : line.trim();\n// const caller = getCallerFunctionNameFromLine(line) || '<anonymous>';\n// return '[' + caller + ']';\n// }\n\nexport const LOGGER_STYLES = {\n reset: '\\x1b[0m',\n bright: '\\x1b[1m',\n dim: '\\x1b[2m',\n underscore: '\\x1b[4m',\n blink: '\\x1b[5m',\n reverse: '\\x1b[7m',\n hidden: '\\x1b[8m',\n // Foreground (text) colors\n fg: {\n black: '\\x1b[30m',\n red: '\\x1b[31m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n magenta: '\\x1b[35m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m'\n },\n // Background colors\n bg: {\n black: '\\x1b[40m',\n red: '\\x1b[41m',\n green: '\\x1b[42m',\n yellow: '\\x1b[43m',\n blue: '\\x1b[44m',\n magenta: '\\x1b[45m',\n cyan: '\\x1b[46m',\n white: '\\x1b[47m'\n }\n};\n\nexport type Logger = {\n (...args: any[]): void;\n warn(...args: any[]): void;\n info(...args: any[]): void;\n error(...args: any[]): void;\n trace(...args: any[]): void;\n debug(...args: any[]): void;\n assert(...args: any[]): void;\n // log(...args: any[]): void;\n group(...args: any[]): void;\n groupCollapsed(...args: any[]): void;\n groupEnd(...args: any[]): void;\n setPrefix(newPrefix: string): void;\n setLevel(level: 0 | 1 | 2 | 3 | 4): void;\n bindPrefix(prefix: string, type?: LogTypes): Logger;\n};\n\nconst methods: ['debug' | 'info' | 'warn' | 'error' | 'assert' | 'trace'/* | 'log' */ | 'group' | 'groupCollapsed' | 'groupEnd', LogTypes][] = [\n ['debug', LogTypes.Debug],\n ['info', LogTypes.Log],\n ['warn', LogTypes.Warn],\n ['error', LogTypes.Error],\n ['assert', LogTypes.Error],\n ['trace', LogTypes.Log],\n ['group', LogTypes.Log],\n ['groupCollapsed', LogTypes.Log],\n ['groupEnd', LogTypes.Log]\n // [\"log\", LogTypes.Log]\n];\n\nexport function logger(prefix: string, type: LogTypes = LogTypes.Log | LogTypes.Warn | LogTypes.Error, ignoreDebugReset = false, style = ''): Logger {\n let originalPrefix: string;\n if(!DEBUG && !ignoreDebugReset/* || true */) {\n type = LogTypes.Error;\n }\n\n if(!STYLES_SUPPORTED) {\n style = '';\n } else if(!style) {\n if(IS_SERVICE_WORKER) style = LOGGER_STYLES.fg.yellow;\n else if(IS_WEB_WORKER) style = LOGGER_STYLES.fg.cyan;\n }\n\n const originalStyle = style;\n if(style) style = `%s ${style}%s`;\n else style = '%s';\n\n // level = LogLevels.log | LogLevels.warn | LogLevels.error | LogLevels.debug\n\n const log: Logger = function(...args: any[]) {\n return type & LogTypes.Log && console.log(style, dT(), prefix, /* getCallerFunctionName(), */ ...args);\n } as any;\n\n methods.forEach(([method, logType]) => {\n log[method] = function(...args: any[]) {\n return type & logType && console[method](style, dT(), prefix, /* getCallerFunctionName(), */ ...args);\n };\n });\n\n log.setPrefix = function(newPrefix: string) {\n originalPrefix = newPrefix;\n prefix = '[' + newPrefix + ']';\n };\n\n log.setPrefix(prefix);\n\n log.setLevel = function(level: 0 | 1 | 2 | 3 | 4) {\n type = LOG_LEVELS.slice(0, level + 1).reduce((acc, v) => acc | v, 0) as any;\n };\n\n const prefixCache: {[prefix: string]: Logger} = {};\n log.bindPrefix = function(prefix: string, _type = type) {\n return prefixCache[prefix] ??= logger(\n // `${originalPrefix}] ${LOGGER_STYLES.fg.magenta}[${prefix}`,\n `${originalPrefix}] ${STYLES_SUPPORTED && originalStyle ? LOGGER_STYLES.reset : ''}[${prefix}`,\n // `${originalPrefix}] [${prefix}`,\n _type,\n ignoreDebugReset,\n // originalStyle || LOGGER_STYLES.reset\n originalStyle\n // LOGGER_STYLES.reset\n );\n };\n\n return log;\n};\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport DEBUG from '../../config/debug';\nimport tabId from '../../config/tabId';\nimport ctx from '../../environment/ctx';\nimport indexOfAndSplice from '../../helpers/array/indexOfAndSplice';\nimport {IS_WORKER} from '../../helpers/context';\nimport EventListenerBase from '../../helpers/eventListenerBase';\nimport makeError from '../../helpers/makeError';\nimport {Awaited, WorkerTaskTemplate, WorkerTaskVoidTemplate} from '../../types';\nimport {logger} from '../logger';\n\ntype SuperMessagePortTask = WorkerTaskTemplate & {\n transfer?: Transferable[]\n};\n\ninterface InvokeTask extends SuperMessagePortTask {\n type: 'invoke',\n payload: WorkerTaskVoidTemplate & {withAck?: boolean, void?: boolean}\n}\n\ninterface ResultTask extends SuperMessagePortTask {\n type: 'result',\n payload: {\n taskId: number,\n result?: any,\n error?: any\n }\n}\n\ninterface AckTask extends SuperMessagePortTask {\n type: 'ack',\n payload: {\n cached: boolean,\n taskId: number\n result?: any,\n error?: any,\n }\n}\n\ninterface PingTask extends SuperMessagePortTask {\n type: 'ping'\n}\n\ninterface PongTask extends SuperMessagePortTask {\n type: 'pong'\n}\n\ninterface BatchTask extends SuperMessagePortTask {\n type: 'batch',\n payload: Task[]\n}\n\ninterface CloseTask extends SuperMessagePortTask {\n type: 'close'\n}\n\n// interface OpenTask extends SuperMessagePortTask {\n// type: 'open'\n// }\n\ninterface LockTask extends SuperMessagePortTask {\n type: 'lock',\n payload: string\n}\n\ntype Task = InvokeTask | ResultTask | AckTask | PingTask | PongTask | BatchTask | CloseTask/* | OpenTask */ | LockTask;\ntype TaskMap = {\n [type in Task as type['type']]?: (task: Extract<Task, type>, source: MessageEventSource, event: MessageEvent<any>) => void | Promise<any>\n};\n\nexport type AckedResult<T> = {\n cached: boolean,\n result: Promise<T>\n};\n// export type AckedResult<T> = {\n// cached: true,\n// result: T\n// } | {\n// cached: false,\n// result: Promise<T>\n// };\n\ntype ListenPort = WindowProxy | MessagePort | ServiceWorker | Worker | ServiceWorkerContainer;\ntype SendPort = Pick<MessageEventSource, 'postMessage'>/* WindowProxy | MessagePort | ServiceWorker | Worker */;\n\nexport type MessageListenPort = ListenPort;\nexport type MessageSendPort = SendPort;\n\ntype ListenerCallback = (payload: any, source: MessageEventSource, event: MessageEvent<any>) => any;\ntype Listeners = Record<string, ListenerCallback>;\n\nconst USE_LOCKS = true;\nconst USE_BATCHING = true;\n\n// const PING_INTERVAL = DEBUG && false ? 0x7FFFFFFF : 5000;\n// const PING_TIMEOUT = DEBUG && false ? 0x7FFFFFFF : 10000;\n\nexport default class SuperMessagePort<\n Workers extends Listeners,\n Masters extends Listeners,\n IsMaster extends boolean,\n Receive extends Listeners = IsMaster extends true ? Masters : Workers,\n Send extends Listeners = IsMaster extends true ? Workers : Masters\n> extends EventListenerBase<Receive> {\n protected listenPorts: Array<ListenPort>;\n protected sendPorts: Array<SendPort>;\n protected pingResolves: Map<SendPort, () => void>;\n\n protected taskId: number;\n protected awaiting: {\n [id: number]: {\n resolve: any,\n reject: any,\n taskType: string,\n port?: SendPort\n }\n };\n protected pending: Map<SendPort, Task[]>;\n\n protected log: ReturnType<typeof logger>;\n protected debug: boolean;\n protected releasingPending: boolean;\n\n protected processTaskMap: TaskMap;\n\n protected onPortDisconnect: (source: MessageEventSource) => void;\n // protected onPortConnect: (source: MessageEventSource) => void;\n\n protected heldLocks: Map<SendPort, {resolve: () => void, id: string}>;\n protected requestedLocks: Map<string, SendPort>;\n\n constructor(protected logSuffix?: string) {\n super(false);\n\n this.listenPorts = [];\n this.sendPorts = [];\n this.pingResolves = new Map();\n this.taskId = 0;\n this.awaiting = {};\n this.pending = new Map();\n this.log = logger('MP' + (logSuffix ? '-' + logSuffix : ''));\n this.debug = DEBUG;\n this.heldLocks = new Map();\n this.requestedLocks = new Map();\n\n this.processTaskMap = {\n result: this.processResultTask,\n ack: this.processAckTask,\n invoke: this.processInvokeTask,\n ping: this.processPingTask,\n pong: this.processPongTask,\n close: this.processCloseTask,\n // open: this.processOpenTask,\n lock: this.processLockTask,\n batch: this.processBatchTask\n };\n }\n\n public setOnPortDisconnect(callback: (source: MessageEventSource) => void) {\n this.onPortDisconnect = callback;\n }\n\n // public setOnPortConnect(callback: (source: MessageEventSource) => void) {\n // this.onPortConnect = callback;\n // }\n\n public attachPort(port: MessageEventSource) {\n this.attachListenPort(port);\n this.attachSendPort(port);\n }\n\n public attachListenPort(port: ListenPort) {\n this.listenPorts.push(port);\n port.addEventListener('message', this.onMessage as any);\n }\n\n public attachSendPort(port: SendPort) {\n this.log.warn('attaching send port');\n\n (port as MessagePort).start?.();\n\n this.sendPorts.push(port);\n // this.sendPing(port);\n\n // const task = this.createTask('open', undefined);\n // this.postMessage(port, task);\n\n if(typeof(window) !== 'undefined' && USE_LOCKS) {\n if('locks' in navigator) {\n const id = ['lock', tabId, this.logSuffix || '', Math.random() * 0x7FFFFFFF | 0].join('-');\n this.log.warn('created lock', id);\n const promise = new Promise<void>((resolve) => this.heldLocks.set(port, {resolve, id}))\n .then(() => this.heldLocks.delete(port));\n navigator.locks.request(id, () => {\n this.resendLockTask(port);\n return promise;\n });\n } else {\n window.addEventListener('beforeunload', () => {\n const task = this.createTask('close', undefined);\n this.postMessage(undefined, task);\n });\n }\n }\n\n this.releasePending();\n }\n\n public resendLockTask(port: SendPort) {\n const lock = this.heldLocks.get(port);\n if(!lock) {\n return;\n }\n\n this.pushTask(this.createTask('lock', lock.id), port);\n }\n\n // ! Can't rely on ping because timers can be suspended\n // protected sendPing(port: SendPort, loop = IS_WORKER) {\n // let timeout: number;\n // const promise = new Promise<void>((resolve, reject) => {\n // this.pingResolves.set(port, resolve);\n // this.pushTask(this.createTask('ping', undefined), port);\n\n // timeout = ctx.setTimeout(() => {\n // reject();\n // }, PING_TIMEOUT);\n // });\n\n // promise.then(() => {\n // // this.log('got pong');\n\n // clearTimeout(timeout);\n // this.pingResolves.delete(port);\n\n // if(loop) {\n // this.sendPingWithTimeout(port);\n // }\n // }, () => {\n // this.pingResolves.delete(port);\n // this.detachPort(port);\n // });\n // }\n\n // protected sendPingWithTimeout(port: SendPort, timeout = PING_INTERVAL) {\n // ctx.setTimeout(() => {\n // if(!this.sendPorts.includes(port)) {\n // return;\n // }\n\n // this.sendPing(port);\n // }, timeout);\n // }\n\n public detachPort(port: ListenPort) {\n this.log.warn('disconnecting port');\n\n indexOfAndSplice(this.listenPorts, port);\n indexOfAndSplice(this.sendPorts, port as any);\n\n port.removeEventListener?.('message', this.onMessage as any);\n (port as MessagePort).close?.();\n\n this.onPortDisconnect?.(port as any);\n\n const heldLock = this.heldLocks.get(port as SendPort);\n heldLock?.resolve();\n\n const error = makeError('PORT_DISCONNECTED');\n for(const id in this.awaiting) {\n const task = this.awaiting[id];\n if(task.port === port) {\n task.reject(error);\n delete this.awaiting[id];\n }\n }\n }\n\n protected postMessage(port: SendPort | SendPort[], task: Task) {\n const ports = Array.isArray(port) ? port : (port ? [port] : this.sendPorts);\n ports.forEach((port) => {\n if(import.meta.env.MODE === 'test') {\n return;\n }\n\n port.postMessage(task, task.transfer as any);\n });\n }\n\n protected onMessage = (event: MessageEvent) => {\n const task: Task = event.data;\n // this.log('got message', task);\n\n const source: MessageEventSource = event.source || event.currentTarget as any; // can have no source\n\n // @ts-ignore\n this.processTaskMap[task.type](task, source, event);\n };\n\n protected async releasePending() {\n // return;\n\n if(/* !this.listenPorts.length || !this.sendPorts.length || */this.releasingPending) {\n return;\n }\n\n this.releasingPending = true;\n // const perf = performance.now();\n\n if(USE_BATCHING) {\n await Promise.resolve();\n }\n // await pause(0);\n\n this.debug && this.log.debug('releasing tasks, length:', this.pending.size/* , performance.now() - perf */);\n\n this.pending.forEach((portTasks, port) => {\n let tasks: Task[] = portTasks;\n if(USE_BATCHING) {\n let batchTask: BatchTask;\n tasks = [];\n portTasks.forEach((task) => {\n if(task.transfer) {\n batchTask = undefined;\n tasks.push(task);\n } else {\n if(!batchTask) {\n batchTask = this.createTask('batch', []);\n tasks.push(batchTask);\n }\n\n batchTask.payload.push(task);\n }\n });\n }\n\n const ports = port ? [port] : this.sendPorts;\n if(!ports.length) {\n return;\n }\n\n tasks.forEach((task) => {\n // if(USE_BATCHING && task.type === 'batch') {\n // this.log(`batching ${task.payload.length} tasks`);\n // }\n\n try {\n // if(IS_SERVICE_WORKER && !port) {\n // notifyAll(task);\n // } else {\n this.postMessage(ports, task);\n // }\n } catch(err) {\n this.log.error('postMessage error:', err, task, ports);\n }\n });\n\n this.pending.delete(port);\n });\n\n this.debug && this.log.debug('released tasks');\n\n this.releasingPending = false;\n }\n\n protected processResultTask = (task: ResultTask) => {\n const {taskId, result, error} = task.payload;\n const deferred = this.awaiting[taskId];\n if(!deferred) {\n return;\n }\n\n this.debug && this.log.debug('done', deferred.taskType, result, error);\n 'error' in task.payload ? deferred.reject(error) : deferred.resolve(result);\n delete this.awaiting[taskId];\n };\n\n protected processAckTask = (task: AckTask) => {\n const payload = task.payload;\n const deferred = this.awaiting[payload.taskId];\n if(!deferred) {\n return;\n }\n\n // * will finish the init promise with incoming result\n const previousResolve: (acked: AckedResult<any>) => void = deferred.resolve;\n // const previousReject = deferred.reject;\n\n // if(payload.cached) {\n // if('result' in payload) {\n // previousResolve({\n // cached: true,\n // result: payload.result\n // });\n // } else {\n // previousReject(payload.error);\n // }\n // } else {\n // const ret: AckedResult<any> = {\n // cached: false,\n // result: new Promise((resolve, reject) => {\n // deferred.resolve = resolve;\n // deferred.reject = reject;\n // })\n // };\n\n // previousResolve(ret);\n // }\n\n const ret: AckedResult<any> = {\n cached: payload.cached,\n result: payload.cached ? ('result' in payload ? Promise.resolve(payload.result) : Promise.reject(payload.error)) : new Promise((resolve, reject) => {\n deferred.resolve = resolve;\n deferred.reject = reject;\n })\n };\n\n previousResolve(ret);\n\n if(payload.cached) {\n delete this.awaiting[payload.taskId];\n }\n };\n\n protected processPingTask = (task: PingTask, source: MessageEventSource, event: MessageEvent) => {\n this.pushTask(this.createTask('pong', undefined), event.source);\n };\n\n protected processPongTask = (task: PongTask, source: MessageEventSource, event: MessageEvent) => {\n const pingResolve = this.pingResolves.get(source);\n if(pingResolve) {\n this.pingResolves.delete(source);\n pingResolve();\n }\n };\n\n protected processCloseTask = (task: CloseTask, source: MessageEventSource, event: MessageEvent) => {\n this.detachPort(source);\n };\n\n protected processBatchTask = (task: BatchTask, source: MessageEventSource, event: MessageEvent) => {\n if(!USE_BATCHING) {\n return;\n }\n\n const newEvent: MessageEvent = {data: event.data, source: event.source, currentTarget: event.currentTarget} as any;\n task.payload.forEach((task) => {\n // @ts-ignore\n newEvent.data = task;\n this.onMessage(newEvent);\n });\n };\n\n // * it's just an 'open' callback, DO NOT attach port from here\n // protected processOpenTask = (task: OpenTask, source: MessageEventSource, event: MessageEvent) => {\n // this.onPortConnect?.(source);\n // };\n\n protected processLockTask = (task: LockTask, source: MessageEventSource, event: MessageEvent) => {\n const id = task.payload;\n if(this.requestedLocks.has(id)) {\n return;\n }\n\n this.requestedLocks.set(id, source);\n navigator.locks.request(id, () => {\n this.processCloseTask(undefined, source, undefined);\n this.requestedLocks.delete(id);\n });\n };\n\n protected processInvokeTask = async(task: InvokeTask, source: MessageEventSource, event: MessageEvent) => {\n const id = task.id;\n const innerTask = task.payload;\n\n let resultTaskPayload: ResultTask['payload'];\n let resultTask: ResultTask, ackTask: AckTask;\n if(!innerTask.void) {\n resultTaskPayload = {taskId: id};\n resultTask = this.createTask('result', resultTaskPayload);\n }\n\n if(innerTask.withAck) {\n ackTask = this.createTask('ack', {\n taskId: id,\n cached: true\n });\n }\n\n let isPromise: boolean;\n try {\n const listeners = this.listeners[innerTask.type];\n if(!listeners?.size) {\n throw new Error('no listener');\n }\n\n const listener = listeners.values().next().value;\n\n // @ts-ignore\n let result = this.invokeListenerCallback(innerTask.type, listener, innerTask.payload, source, event);\n if(innerTask.void) {\n return;\n }\n\n isPromise = result instanceof Promise;\n\n if(ackTask) {\n const cached = !isPromise;\n ackTask.payload.cached = cached;\n if(cached) ackTask.payload.result = result;\n this.pushTask(ackTask, source);\n\n if(cached) {\n return;\n }\n }\n\n if(isPromise) {\n result = await result;\n }\n\n resultTaskPayload.result = result;\n } catch(error) {\n this.log.error('worker task error:', error, task);\n if(innerTask.void) {\n return;\n }\n\n if(ackTask && ackTask.payload.cached) {\n ackTask.payload.error = error;\n this.pushTask(ackTask, source);\n return;\n }\n\n resultTaskPayload.error = error;\n }\n\n this.pushTask(resultTask, source);\n };\n\n protected createTask<T extends Task['type'], K extends Task = Parameters<TaskMap[T]>[0]>(type: T, payload: K['payload'], transfer?: Transferable[]): K {\n return {\n type,\n payload,\n id: this.taskId++,\n transfer\n } as K;\n }\n\n protected createInvokeTask(type: string, payload: any, withAck?: boolean, _void?: boolean, transfer?: Transferable[]): InvokeTask {\n return this.createTask('invoke', {\n type,\n payload,\n withAck,\n void: _void\n }, transfer);\n }\n\n protected pushTask(task: Task, port?: SendPort) {\n let tasks = this.pending.get(port);\n if(!tasks) {\n this.pending.set(port, tasks = []);\n }\n\n tasks.push(task);\n this.releasePending();\n }\n\n public invokeVoid<T extends keyof Send>(type: T, payload: Parameters<Send[T]>[0], port?: SendPort, transfer?: Transferable[]) {\n const task = this.createInvokeTask(type as string, payload, undefined, true, transfer);\n this.pushTask(task, port);\n }\n\n public invoke<T extends keyof Send>(type: T, payload: Parameters<Send[T]>[0], withAck?: false, port?: SendPort, transfer?: Transferable[]): Promise<Awaited<ReturnType<Send[T]>>>;\n public invoke<T extends keyof Send>(type: T, payload: Parameters<Send[T]>[0], withAck?: true, port?: SendPort, transfer?: Transferable[]): Promise<AckedResult<Awaited<ReturnType<Send[T]>>>>;\n public invoke<T extends keyof Send>(type: T, payload: Parameters<Send[T]>[0], withAck?: boolean, port?: SendPort, transfer?: Transferable[]) {\n this.debug && this.log.debug('start', type, payload);\n\n let task: InvokeTask;\n const promise = new Promise<Awaited<ReturnType<Send[T]>>>((resolve, reject) => {\n task = this.createInvokeTask(type as string, payload, withAck, undefined, transfer);\n this.awaiting[task.id] = {resolve, reject, taskType: type as string, port};\n this.pushTask(task, port);\n });\n\n if(IS_WORKER) {\n promise.finally(() => {\n clearInterval(interval);\n });\n\n const interval = ctx.setInterval(() => {\n this.log.error('task still has no result', task, port);\n }, 60e3);\n } else if(false) {\n // let timedOut = false;\n const startTime = Date.now();\n promise.finally(() => {\n const elapsedTime = Date.now() - startTime;\n if(elapsedTime >= TIMEOUT) {\n this.log.error(`task was processing ${Date.now() - startTime}ms`, task.payload.payload, port);\n }/* else {\n clearTimeout(timeout);\n } */\n });\n\n const TIMEOUT = 10;\n // const timeout = ctx.setTimeout(() => {\n // timedOut = true;\n // // this.log.error(`task is processing more than ${TIMEOUT} milliseconds`, task, port);\n // }, TIMEOUT);\n }\n\n return promise;\n }\n\n public invokeExceptSource<T extends keyof Send>(type: T, payload: Parameters<Send[T]>[0], source?: SendPort) {\n const ports = this.sendPorts.slice();\n indexOfAndSplice(ports, source);\n\n ports.forEach((target) => {\n this.invokeVoid(type, payload, target);\n });\n }\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport type {getEnvironment} from '../../environment/utils';\nimport type loadState from '../appManagers/utils/state/loadState';\nimport type {StoragesResults} from '../appManagers/utils/storages/loadStorages';\nimport type {LocalStorageProxyTask} from '../localStorage';\nimport type {Awaited} from '../../types';\nimport type {Mirrors, MirrorTaskPayload, NotificationBuildTaskPayload, TabState} from './mtprotoworker';\nimport type toggleStorages from '../../helpers/toggleStorages';\nimport SuperMessagePort from './superMessagePort';\n\nexport type MTProtoManagerTaskPayload = {name: string, method: string, args: any[]};\n\ntype MTProtoBroadcastEvent = {\n event: (payload: {name: string, args: any[]}, source: MessageEventSource) => void\n};\n\nexport default class MTProtoMessagePort<Master extends boolean = true> extends SuperMessagePort<{\n environment: (environment: ReturnType<typeof getEnvironment>) => void,\n crypto: (payload: {method: string, args: any[]}) => Promise<any>,\n state: (payload: {userId: UserId} & Awaited<ReturnType<typeof loadState>> & {storagesResults?: StoragesResults}) => void,\n manager: (payload: MTProtoManagerTaskPayload) => any,\n toggleStorages: (payload: {enabled: boolean, clearWrite: boolean}) => ReturnType<typeof toggleStorages>,\n serviceWorkerOnline: (online: boolean) => void,\n serviceWorkerPort: (payload: void, source: MessageEventSource, event: MessageEvent) => void,\n cryptoPort: (payload: void, source: MessageEventSource, event: MessageEvent) => void,\n createObjectURL: (blob: Blob) => string,\n tabState: (payload: TabState, source: MessageEventSource) => void,\n createProxyWorkerURLs: (payload: {originalUrl: string, blob: Blob}) => string[],\n} & MTProtoBroadcastEvent, {\n convertWebp: (payload: {fileName: string, bytes: Uint8Array}) => Promise<Uint8Array>,\n convertOpus: (payload: {fileName: string, bytes: Uint8Array}) => Promise<Uint8Array>,\n localStorageProxy: (payload: LocalStorageProxyTask['payload']) => Promise<any>,\n mirror: (payload: MirrorTaskPayload) => void,\n notificationBuild: (payload: NotificationBuildTaskPayload) => void,\n receivedServiceMessagePort: (payload: void) => void,\n // hello: () => void\n} & MTProtoBroadcastEvent, Master> {\n private static INSTANCE: MTProtoMessagePort;\n\n constructor() {\n super('MTPROTO');\n\n MTProtoMessagePort.INSTANCE = this;\n\n MOUNT_CLASS_TO && (MOUNT_CLASS_TO.mtprotoMessagePort = this);\n }\n\n public static getInstance<Master extends boolean>() {\n return this.INSTANCE as MTProtoMessagePort<Master>;\n }\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {Message, StickerSet, Update, NotifyPeer, PeerNotifySettings, PollResults, Poll, WebPage, GroupCall, GroupCallParticipant, ReactionCount, MessagePeerReaction, PhoneCall, Config, Reaction, AttachMenuBot, PeerSettings, StoryItem, PeerStories, SavedDialog, SavedReactionTag} from '../layer';\nimport type {Dialog, ForumTopic, MessagesStorageKey, MyMessage} from './appManagers/appMessagesManager';\nimport type {MyDialogFilter} from './storages/filters';\nimport type {AnyDialog, Folder} from './storages/dialogs';\nimport type {UserTyping} from './appManagers/appProfileManager';\nimport type {MyDraftMessage} from './appManagers/appDraftsManager';\nimport type {ConnectionStatusChange} from './mtproto/connectionStatus';\nimport type {GroupCallId} from './appManagers/appGroupCallsManager';\nimport type {AppManagers} from './appManagers/managers';\nimport type {State} from '../config/state';\nimport type {Progress} from './appManagers/appDownloadManager';\nimport type {CallId} from './appManagers/appCallsManager';\nimport type {MyDocument} from './appManagers/appDocsManager';\nimport type {MTAppConfig} from './mtproto/appConfig';\nimport type StoriesCacheType from './appManagers/utils/stories/cacheType';\nimport type {StoriesListPosition} from './appManagers/appStoriesManager';\nimport {NULL_PEER_ID, UserAuth} from './mtproto/mtproto_config';\nimport EventListenerBase from '../helpers/eventListenerBase';\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport MTProtoMessagePort from './mtproto/mtprotoMessagePort';\nimport {IS_WORKER} from '../helpers/context';\nimport {RtmpCallInstance} from './calls/rtmpCallsController';\n\nexport type BroadcastEvents = {\n 'chat_full_update': ChatId,\n 'chat_update': ChatId,\n 'chat_toggle_forum': {chatId: ChatId, enabled: boolean},\n 'chat_participant': Update.updateChannelParticipant,\n 'chat_participation': {chatId: ChatId, left: boolean},\n 'chat_requests': {requestsPending: number, recentRequesters: UserId[], chatId: ChatId}\n\n 'channel_update': ChatId,\n\n 'user_update': UserId,\n 'user_auth': UserAuth,\n 'user_full_update': UserId,\n\n 'attach_menu_bot': AttachMenuBot,\n\n 'emoji_status_change': void,\n\n 'peer_pinned_messages': {peerId: PeerId, mids?: number[], pinned?: boolean, unpinAll?: true},\n 'peer_pinned_hidden': {peerId: PeerId, maxId: number},\n 'peer_typings': {peerId: PeerId, threadId?: number, typings: UserTyping[]},\n 'peer_block': {peerId: PeerId, blocked?: boolean, blockedMyStoriesFrom?: boolean},\n 'peer_title_edit': {peerId: PeerId, threadId?: number},\n 'peer_bio_edit': PeerId,\n 'peer_deleted': PeerId, // left chat, deleted user dialog, left channel\n 'peer_full_update': PeerId,\n 'peer_settings': {peerId: PeerId, settings: PeerSettings},\n 'peer_stories': {peerId: PeerId, available: boolean},\n 'peer_stories_hidden': {peerId: PeerId, hidden: boolean},\n\n 'filter_delete': MyDialogFilter,\n 'filter_update': MyDialogFilter,\n 'filter_new': MyDialogFilter,\n 'filter_order': number[],\n 'filter_joined': MyDialogFilter,\n\n 'folder_unread': Omit<Folder, 'dialogs' | 'dispatchUnreadTimeout'>,\n\n 'dialog_draft': {peerId: PeerId, dialog: Dialog | ForumTopic, drop: boolean, draft: MyDraftMessage | undefined},\n 'dialog_unread': {peerId: PeerId, dialog: Dialog | ForumTopic},\n 'dialog_flush': {peerId: PeerId, dialog: Dialog},\n 'dialog_drop': AnyDialog,\n 'dialog_migrate': {migrateFrom: PeerId, migrateTo: PeerId},\n // 'dialog_top': Dialog,\n 'dialog_notify_settings': Dialog | ForumTopic,\n // 'dialog_order': {dialog: Dialog, pos: number},\n 'dialogs_multiupdate': Map<PeerId, {dialog?: Dialog, topics?: Map<number, ForumTopic>, saved?: Map<PeerId, SavedDialog>}>,\n\n 'history_append': {storageKey: MessagesStorageKey, message: Message.message},\n 'history_update': {storageKey: MessagesStorageKey, message: MyMessage, sequential?: boolean},\n 'history_reply_markup': {peerId: PeerId},\n 'history_multiappend': MyMessage,\n // 'history_delete': {peerId: PeerId, msgs: Map<number, {savedPeerId?: PeerId}>},\n 'history_delete': {peerId: PeerId, msgs: Set<number>},\n 'history_forbidden': PeerId,\n 'history_reload': PeerId,\n 'history_count': {historyKey: string, count: number},\n 'history_delete_key': {historyKey: string, mid: number},\n // 'history_request': void,\n\n 'message_edit': {storageKey: MessagesStorageKey, peerId: PeerId, mid: number, message: MyMessage},\n 'message_sent': {storageKey: MessagesStorageKey, tempId: number, tempMessage: any, mid: number, message: MyMessage},\n 'message_error': {storageKey: MessagesStorageKey, peerId: PeerId, tempId: number, error: ApiError},\n 'message_transcribed': {peerId: PeerId, mid: number, text: string, pending?: boolean},\n 'messages_views': {peerId: PeerId, mid: number, views: number}[],\n 'messages_reactions': {message: Message.message, changedResults: ReactionCount[], removedResults: ReactionCount[]}[],\n 'messages_pending': void,\n 'messages_read': void,\n 'messages_downloaded': {peerId: PeerId, mids: number[]},\n 'messages_media_read': {peerId: PeerId, mids: number[]},\n\n 'story_update': {peerId: PeerId, story: StoryItem, modifiedPinned?: boolean, modifiedArchive?: boolean, modifiedPinnedToTop?: boolean},\n 'story_deleted': {peerId: PeerId, id: number},\n 'story_expired': {peerId: PeerId, id: number},\n 'story_new': {peerId: PeerId, story: StoryItem, cacheType: StoriesCacheType, maxReadId: number},\n 'stories_stories': PeerStories,\n 'stories_read': {peerId: PeerId, maxReadId: number},\n 'stories_downloaded': {peerId: PeerId, ids: number[]},\n 'stories_position': {peerId: PeerId, position: StoriesListPosition},\n\n 'replies_updated': Message.message,\n 'replies_short_update': Message.message,\n\n 'scheduled_new': Message.message,\n 'scheduled_delete': {peerId: PeerId, mids: number[]},\n\n 'grouped_edit': {peerId: PeerId, groupedId: string, deletedMids: number[], messages: Message.message[]},\n\n 'stickers_installed': StickerSet.stickerSet,\n 'stickers_deleted': StickerSet.stickerSet,\n 'stickers_updated': {type: 'recent' | 'faved', stickers: MyDocument[]},\n 'stickers_top': Long,\n 'stickers_order': {type: 'masks' | 'emojis' | 'stickers', order: Long[]},\n 'sticker_updated': {type: 'recent' | 'faved', document: MyDocument, faved: boolean},\n\n 'gifs_updated': MyDocument[],\n 'gif_updated': {document: MyDocument, saved: boolean},\n\n 'state_cleared': void,\n 'state_synchronized': void,\n 'state_synchronizing': void,\n\n 'contacts_update': UserId,\n 'avatar_update': {peerId: PeerId, threadId?: number},\n 'poll_update': {poll: Poll, results: PollResults},\n 'invalidate_participants': ChatId,\n // 'channel_settings': {channelId: number},\n 'webpage_updated': {id: WebPage.webPage['id'], msgs: {peerId: PeerId, mid: number, isScheduled: boolean}[]},\n\n 'connection_status_change': ConnectionStatusChange,\n 'settings_updated': {key: string, value: any, settings: State['settings']},\n 'draft_updated': {peerId: PeerId, threadId: number, draft: MyDraftMessage | undefined, force?: boolean},\n\n 'background_change': void,\n\n 'privacy_update': Update.updatePrivacy,\n\n 'notify_settings': Update.updateNotifySettings,\n 'notify_peer_type_settings': {key: Exclude<NotifyPeer['_'], 'notifyPeer'>, settings: PeerNotifySettings},\n\n 'notification_reset': string,\n 'notification_cancel': string,\n\n 'language_change': string,\n\n 'theme_change': {x: number, y: number} | void,\n 'theme_changed': void,\n\n 'media_play': void,\n\n 'emoji_recent': {emoji: AppEmoji, deleted?: boolean},\n\n 'download_progress': Progress,\n 'document_downloading': DocId,\n 'document_downloaded': DocId,\n\n 'choosing_sticker': boolean\n\n 'group_call_update': GroupCall,\n 'group_call_participant': {groupCallId: GroupCallId, participant: GroupCallParticipant},\n // 'group_call_video_track_added': {instance: GroupCallInstance}\n\n 'call_update': PhoneCall,\n 'call_signaling': {callId: CallId, data: Uint8Array},\n\n 'rtmp_call_update': RtmpCallInstance,\n\n 'quick_reaction': Reaction,\n\n 'service_notification': Update.updateServiceNotification,\n\n 'logging_out': void,\n\n 'payment_sent': {peerId: PeerId, mid: number, receiptMessage: Message.messageService},\n\n 'web_view_result_sent': Long,\n\n 'premium_toggle': boolean,\n 'premium_toggle_private': {isNew: boolean, isPremium: boolean},\n\n 'saved_tags': {savedPeerId: PeerId, tags: SavedReactionTag[]},\n 'saved_tags_clear': void,\n\n 'stars_balance': Long,\n\n 'file_speed_limited': {increaseTimes: number, isUpload: boolean},\n\n 'config': Config,\n 'app_config': MTAppConfig,\n 'managers_ready': void // ! inner\n};\n\nexport type BroadcastEventsListeners = {\n [name in keyof BroadcastEvents]: (e: BroadcastEvents[name]) => void\n};\n\nexport class RootScope extends EventListenerBase<BroadcastEventsListeners> {\n public myId: PeerId;\n private connectionStatus: {[name: string]: ConnectionStatusChange};\n public settings: State['settings'];\n public managers: AppManagers;\n public premium: boolean;\n\n constructor() {\n super();\n\n this.myId = NULL_PEER_ID;\n this.connectionStatus = {};\n this.premium = false;\n\n this.addEventListener('user_auth', ({id}) => {\n this.myId = id.toPeerId();\n });\n\n this.addEventListener('premium_toggle_private', ({isNew, isPremium}) => {\n this.premium = isPremium;\n if(!isNew) { // * only on change\n this.dispatchEventSingle('premium_toggle', isPremium);\n }\n });\n\n this.addEventListener('connection_status_change', (status) => {\n this.connectionStatus[status.name] = status;\n });\n\n this.dispatchEvent = (e, ...args) => {\n super.dispatchEvent(e, ...args);\n MTProtoMessagePort.getInstance().invokeVoid('event', {name: e as string, args});\n };\n\n if(!IS_WORKER) {\n this.addEventListener('settings_updated', ({settings}) => {\n this.settings = settings;\n });\n }\n }\n\n public getConnectionStatus() {\n return this.connectionStatus;\n }\n\n public getPremium() {\n return this.premium;\n }\n\n public dispatchEventSingle(...args: any[]) {\n // @ts-ignore\n super.dispatchEvent(...args);\n }\n}\n\nconst rootScope = new RootScope();\nMOUNT_CLASS_TO.rootScope = rootScope;\nexport default rootScope;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport noop from './noop';\n\nexport interface CancellablePromise<T> extends Promise<T> {\n resolve?: (value: T) => void,\n reject?: (...args: any[]) => void,\n cancel?: (reason?: any) => void,\n\n notify?: (...args: any[]) => void,\n notifyAll?: (...args: any[]) => void,\n lastNotify?: any,\n listeners?: Array<(...args: any[]) => void>,\n addNotifyListener?: (callback: (...args: any[]) => void) => void,\n\n isFulfilled?: boolean,\n isRejected?: boolean,\n\n onFinish?: () => void,\n _resolve?: (value: T) => void,\n _reject?: (...args: any[]) => void\n}\n\nconst deferredHelper = {\n isFulfilled: false,\n isRejected: false,\n\n notify: () => {},\n notifyAll: function(...args: any[]) {\n this.lastNotify = args;\n this.listeners?.forEach((callback: any) => callback(...args));\n },\n\n addNotifyListener: function(callback: (...args: any[]) => void) {\n if(this.lastNotify) {\n callback(...this.lastNotify);\n }\n\n (this.listeners ??= []).push(callback);\n },\n\n resolve: function(value) {\n if(this.isFulfilled || this.isRejected) return;\n\n this.isFulfilled = true;\n this._resolve(value);\n this.onFinish();\n },\n\n reject: function(...args) {\n if(this.isRejected || this.isFulfilled) return;\n\n this.isRejected = true;\n this._reject(...args);\n this.onFinish();\n },\n\n onFinish: function() {\n this.notify = this.notifyAll = this.lastNotify = null;\n if(this.listeners) this.listeners.length = 0;\n\n if(this.cancel) {\n this.cancel = noop;\n }\n }\n} as CancellablePromise<any>;\n\nexport default function deferredPromise<T>() {\n let resolve: (value: T) => void, reject: (...args: any[]) => void;\n const deferred: CancellablePromise<T> = new Promise<T>((_resolve, _reject) => {\n resolve = _resolve, reject = _reject;\n });\n\n Object.assign(deferred, deferredHelper);\n deferred._resolve = resolve;\n deferred._reject = reject;\n\n return deferred;\n}\n\nexport function bindPromiseToDeferred<T>(promise: Promise<T>, deferred: CancellablePromise<T>) {\n promise.then(deferred.resolve.bind(deferred), deferred.reject.bind(deferred));\n}\n\n(self as any).deferredPromise = deferredPromise;\n","// * Jolly Cobra's schedulers\n\nimport {AnyToVoidFunction} from '../../types';\n\nexport default function throttle<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true\n) {\n let interval: number | null = null;\n let isPending: boolean;\n let args: Parameters<F>;\n\n const clear = () => {\n clearInterval(interval!);\n interval = null;\n };\n\n const ret = (..._args: Parameters<F>) => {\n isPending = true;\n args = _args;\n\n if(!interval) {\n if(shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n interval = setInterval(() => {\n if(!isPending) {\n clear();\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms) as any;\n }\n };\n\n ret.clear = clear;\n\n return ret;\n}\n","export default function safeAssign<T>(object: T, fromObject: any) {\n if(fromObject) {\n for(const i in fromObject) {\n if(fromObject[i] !== undefined) {\n // @ts-ignore\n object[i] = fromObject[i];\n }\n }\n }\n\n return object;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport {Database} from '../../config/databases';\nimport Modes from '../../config/modes';\nimport makeError from '../../helpers/makeError';\nimport safeAssign from '../../helpers/object/safeAssign';\nimport {logger} from '../logger';\n\n/**\n * https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex\n */\nexport type IDBIndex = {\n indexName: string,\n keyPath: string,\n objectParameters: IDBIndexParameters\n};\n\nexport type IDBStore = {\n name: string,\n indexes?: IDBIndex[]\n};\n\nexport type IDBOptions = {\n name?: string,\n storeName: string,\n stores?: IDBStore[],\n version?: number\n};\n\nconst DEBUG = false;\n\nexport class IDB {\n private static INSTANCES: IDB[] = [];\n private openDbPromise: Promise<IDBDatabase>;\n private db: IDBDatabase;\n private storageIsAvailable: boolean;\n private log: ReturnType<typeof logger>;\n private name: string;\n private version: number;\n private stores: IDBStore[];\n\n constructor(db: Database<any>) {\n safeAssign(this, db);\n\n if(Modes.test) {\n this.name += '_test';\n }\n\n this.storageIsAvailable = true;\n this.log = logger(['IDB', db.name].join('-'));\n this.log('constructor');\n\n this.openDatabase(true);\n\n IDB.INSTANCES.push(this);\n }\n\n public isAvailable() {\n return this.storageIsAvailable;\n }\n\n public openDatabase(createNew = false): Promise<IDBDatabase> {\n if(this.openDbPromise && !createNew) {\n return this.openDbPromise;\n }\n\n const createIndexes = (os: IDBObjectStore, store: IDBStore) => {\n const indexNames = Array.from(os.indexNames);\n for(const indexName of indexNames) {\n os.deleteIndex(indexName);\n }\n\n if(!store.indexes?.length) {\n return;\n }\n\n for(const index of store.indexes) {\n if(os.indexNames.contains(index.indexName)) {\n continue;\n }\n\n os.createIndex(index.indexName, index.keyPath, index.objectParameters);\n }\n };\n\n const createObjectStore = (db: IDBDatabase, store: IDBStore) => {\n const os = db.createObjectStore(store.name);\n createIndexes(os, store);\n };\n\n try {\n var request = indexedDB.open(this.name, this.version);\n\n if(!request) {\n return Promise.reject();\n }\n } catch(error) {\n this.log.error('error opening db', (error as Error).message);\n this.storageIsAvailable = false;\n return Promise.reject(error);\n }\n\n let finished = false;\n setTimeout(() => {\n if(!finished) {\n request.onerror(makeError('IDB_CREATE_TIMEOUT') as Event);\n }\n }, 3000);\n\n return this.openDbPromise = new Promise<IDBDatabase>((resolve, reject) => {\n request.onsuccess = (event) => {\n finished = true;\n const db = request.result;\n let calledNew = false;\n\n this.log('Opened');\n\n db.onerror = (error) => {\n this.storageIsAvailable = false;\n this.log.error('Error creating/accessing IndexedDB database', error);\n reject(error);\n };\n\n db.onclose = (e) => {\n this.log.error('closed:', e);\n !calledNew && this.openDatabase();\n };\n\n db.onabort = (e) => {\n this.log.error('abort:', e);\n const transaction = e.target as IDBTransaction;\n\n this.openDatabase(calledNew = true);\n\n if(transaction.onerror) {\n transaction.onerror(e);\n }\n\n db.close();\n };\n\n db.onversionchange = (e) => {\n this.log.error('onversionchange, lol?');\n };\n\n resolve(this.db = db);\n };\n\n request.onerror = (event) => {\n finished = true;\n this.storageIsAvailable = false;\n this.log.error('Error creating/accessing IndexedDB database', event);\n reject(event);\n };\n\n request.onupgradeneeded = (event) => {\n finished = true;\n this.log.warn('performing idb upgrade from', event.oldVersion, 'to', event.newVersion);\n\n const target = event.target as IDBOpenDBRequest;\n const db = target.result;\n this.stores.forEach((store) => {\n /* if(db.objectStoreNames.contains(store.name)) {\n //if(event.oldVersion === 1) {\n db.deleteObjectStore(store.name);\n //}\n } */\n\n if(!db.objectStoreNames.contains(store.name)) {\n createObjectStore(db, store);\n } else {\n const txn = target.transaction;\n const os = txn.objectStore(store.name);\n createIndexes(os, store);\n }\n });\n };\n });\n }\n\n public static create<T extends Database<any>>(db: T) {\n return this.INSTANCES.find((instance) => instance.name === db.name) ?? new IDB(db);\n }\n\n public static closeDatabases(preserve?: IDB) {\n this.INSTANCES.forEach((storage) => {\n if(preserve && preserve === storage) {\n return;\n }\n\n const db = storage.db;\n if(db) {\n db.onclose = () => {};\n db.close();\n }\n });\n }\n}\n\nexport default class IDBStorage<T extends Database<any>, StoreName extends string = T['stores'][0]['name']> {\n private log: ReturnType<typeof logger>;\n private storeName: T['stores'][0]['name'];\n private idb: IDB;\n\n constructor(db: T, storeName: typeof db['stores'][0]['name']) {\n this.storeName = storeName;\n this.log = logger(['IDB', db.name, storeName].join('-'));\n this.idb = IDB.create(db);\n }\n\n /**\n * ! WARNING ! function requires at least one opened connection\n */\n /* public static clearObjectStores() {\n const storage = this.STORAGES[0];\n this.closeDatabases(storage);\n\n const names = Array.from(storage.db.objectStoreNames);\n const promises = names.map((name) => storage.clear(name));\n return Promise.all(promises);\n } */\n\n /* public static deleteDatabase() {\n this.closeDatabases();\n\n const storages = this.STORAGES;\n const dbNames = Array.from(new Set(storages.map((storage) => storage.name)));\n const promises = dbNames.map((dbName) => {\n return new Promise<void>((resolve, reject) => {\n const deleteRequest = indexedDB.deleteDatabase(dbName);\n\n deleteRequest.onerror = () => {\n reject();\n };\n\n deleteRequest.onsuccess = () => {\n resolve();\n };\n });\n });\n\n return Promise.all(promises);\n } */\n\n public delete(entryName: string | string[], storeName?: StoreName): Promise<void> {\n // return Promise.resolve();\n const isArray = Array.isArray(entryName);\n if(!isArray) {\n entryName = [].concat(entryName);\n }\n\n return this.getObjectStore('readwrite', (objectStore) => {\n const promises = (entryName as string[]).map((entryName) => objectStore.delete(entryName));\n return isArray ? promises : promises[0];\n }, DEBUG ? 'delete: ' + (entryName as string[]).join(', ') : '', storeName);\n }\n\n public clear(storeName?: StoreName): Promise<void> {\n return this.getObjectStore('readwrite', (objectStore) => objectStore.clear(), DEBUG ? 'clear' : '', storeName);\n }\n\n public save(entryName: string | string[], value: any | any[], storeName?: StoreName) {\n // const handleError = (error: Error) => {\n // this.log.error('save: transaction error:', entryName, value, db, error, error && error.name);\n // if((!error || error.name === 'InvalidStateError')/* && false */) {\n // setTimeout(() => {\n // this.save(entryName, value);\n // }, 2e3);\n // } else {\n // //console.error('IndexedDB saveFile transaction error:', error, error && error.name);\n // }\n // };\n\n const isArray = Array.isArray(entryName);\n if(!isArray) {\n entryName = [].concat(entryName);\n value = [].concat(value);\n }\n\n return this.getObjectStore('readwrite', (objectStore) => {\n const promises = (entryName as string[]).map((entryName, idx) => objectStore.put(value[idx], entryName));\n return isArray ? promises : promises[0];\n }, DEBUG ? 'save: ' + (entryName as string[]).join(', ') : '', storeName);\n }\n\n // public saveFile(fileName: string, blob: Blob | Uint8Array) {\n // //return Promise.resolve(blobConstruct([blob]));\n // if(!(blob instanceof Blob)) {\n // blob = blobConstruct(blob);\n // }\n\n // return this.save(fileName, blob);\n // }\n\n /* public saveFileBase64(db: IDBDatabase, fileName: string, blob: Blob | any): Promise<Blob> {\n if(this.getBlobSize(blob) > 10 * 1024 * 1024) {\n return Promise.reject();\n }\n\n if(!(blob instanceof Blob)) {\n var safeMimeType = blobSafeMimeType(blob.type || 'image/jpeg');\n var address = 'data:' + safeMimeType + ';base64,' + bytesToBase64(blob);\n return this.storagePutB64String(db, fileName, address).then(() => {\n return blob;\n });\n }\n\n try {\n var reader = new FileReader();\n } catch (e) {\n this.storageIsAvailable = false;\n return Promise.reject();\n }\n\n let promise = new Promise<Blob>((resolve, reject) => {\n reader.onloadend = () => {\n this.storagePutB64String(db, fileName, reader.result as string).then(() => {\n resolve(blob);\n }, reject);\n }\n\n reader.onerror = reject;\n });\n\n\n try {\n reader.readAsDataURL(blob);\n } catch (e) {\n this.storageIsAvailable = false;\n return Promise.reject();\n }\n\n return promise;\n }\n\n public storagePutB64String(db: IDBDatabase, fileName: string, b64string: string) {\n try {\n var objectStore = db.transaction([this.storeName], 'readwrite')\n .objectStore(this.storeName);\n var request = objectStore.put(b64string, fileName);\n } catch(error) {\n this.storageIsAvailable = false;\n return Promise.reject(error);\n }\n\n return new Promise((resolve, reject) => {\n request.onsuccess = function(event) {\n resolve();\n };\n\n request.onerror = reject;\n });\n }\n\n public getBlobSize(blob: any) {\n return blob.size || blob.byteLength || blob.length;\n } */\n\n public get<T>(entryName: string[], storeName?: StoreName): Promise<T[]>;\n public get<T>(entryName: string, storeName?: StoreName): Promise<T>;\n public get<T>(entryName: string | string[], storeName?: StoreName): Promise<T> | Promise<T[]> {\n // return Promise.reject();\n\n const isArray = Array.isArray(entryName);\n if(!isArray) {\n if(!entryName) {\n return undefined;\n }\n\n entryName = [].concat(entryName);\n } else if(!entryName.length) {\n return Promise.resolve([]) as any;\n }\n\n return this.getObjectStore<T>('readonly', (objectStore) => {\n const promises = (entryName as string[]).map((entryName) => objectStore.get(entryName));\n return isArray ? promises : promises[0];\n }, DEBUG ? 'get: ' + (entryName as string[]).join(', ') : '', storeName);\n }\n\n private getObjectStore<T>(\n mode: IDBTransactionMode,\n callback: (objectStore: IDBObjectStore) => IDBRequest | IDBRequest[],\n log?: string,\n storeName = this.storeName\n ) {\n let perf: number;\n\n if(log) {\n perf = performance.now();\n this.log(log + ': start');\n }\n\n return this.idb.openDatabase().then((db) => {\n return new Promise<T>((resolve, reject) => {\n /* if(mode === 'readwrite') {\n return;\n } */\n\n // * https://developer.chrome.com/blog/indexeddb-durability-mode-now-defaults-to-relaxed\n const transaction = db.transaction([storeName], mode, {durability: 'relaxed'});\n\n const onError = () => {\n clearTimeout(timeout);\n reject(transaction.error);\n };\n\n // let resolved = false;\n const onComplete = (/* what: string */) => {\n clearTimeout(timeout);\n\n if(log) {\n this.log(log + ': end', performance.now() - perf/* , what */);\n }\n\n // if(resolved) {\n // return;\n // }\n\n // resolved = true;\n const results = requests.map((r) => r.result);\n resolve(isArray ? results : results[0]);\n };\n\n transaction.onerror = onError;\n\n // * have to wait while clearing or setting something\n const waitForTransactionComplete = mode === 'readwrite';\n if(waitForTransactionComplete) {\n transaction.oncomplete = () => onComplete(/* 'transaction' */);\n }\n\n const timeout = setTimeout(() => {\n this.log.error('transaction not finished', transaction, log);\n }, 10000);\n\n /* transaction.addEventListener('abort', (e) => {\n //handleError();\n this.log.error('IndexedDB: transaction abort!', transaction.error);\n }); */\n\n const callbackResult = callback(transaction.objectStore(storeName));\n\n const isArray = Array.isArray(callbackResult);\n const requests: IDBRequest[] = isArray ? callbackResult : [].concat(callbackResult) as any;\n\n if(waitForTransactionComplete) {\n return;\n }\n\n const length = requests.length;\n let left = length;\n\n const onRequestFinished = () => {\n if(transaction.error) {\n return;\n }\n\n if(!--left) {\n onComplete(/* 'requests' */);\n }\n };\n\n for(let i = 0; i < length; ++i) {\n const request = requests[i];\n request.onerror = onError;\n request.onsuccess = onRequestFinished;\n }\n });\n });\n }\n\n public getAll<T>(storeName?: StoreName): Promise<T[]> {\n return this.getObjectStore<T[]>('readonly', (objectStore) => objectStore.getAll(), DEBUG ? 'getAll' : '', storeName);\n }\n\n /* public getAllKeys(): Promise<Array<string>> {\n console.time('getAllEntries');\n return this.openDatabase().then((db) => {\n var objectStore = db.transaction([this.storeName], 'readonly')\n .objectStore(this.storeName);\n var request = objectStore.getAllKeys();\n\n return new Promise((resolve, reject) => {\n request.onsuccess = function(event) {\n // @ts-ignore\n var result = event.target.result;\n resolve(result);\n console.timeEnd('getAllEntries');\n }\n\n request.onerror = reject;\n });\n });\n } */\n\n /* public isFileExists(fileName: string): Promise<boolean> {\n console.time('isFileExists');\n return this.openDatabase().then((db) => {\n var objectStore = db.transaction([this.storeName], 'readonly')\n .objectStore(this.storeName);\n var request = objectStore.openCursor(fileName);\n\n return new Promise((resolve, reject) => {\n request.onsuccess = function(event) {\n // @ts-ignore\n var cursor = event.target.result;\n resolve(!!cursor);\n console.timeEnd('isFileExists');\n }\n\n request.onerror = reject;\n });\n });\n } */\n\n /* public getFileWriter(fileName: string, mimeType: string) {\n var fakeWriter = FileManager.getFakeFileWriter(mimeType, (blob) => {\n return this.saveFile(fileName, blob);\n });\n\n return Promise.resolve(fakeWriter);\n } */\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport {Database} from '../config/databases';\nimport {MOUNT_CLASS_TO} from '../config/debug';\n// import DATABASE_SESSION from \"../config/databases/session\";\nimport deferredPromise, {CancellablePromise} from '../helpers/cancellablePromise';\nimport {IS_WORKER} from '../helpers/context';\nimport throttle from '../helpers/schedulers/throttle';\n// import { WorkerTaskTemplate } from \"../types\";\nimport IDBStorage from './files/idb';\n\nfunction noop() {}\n\n/* export interface LocalStorageProxySetTask extends WorkerTaskTemplate {\n type: 'localStorageProxy',\n payload: {\n type: 'set',\n keys: string[],\n values: any[]\n }\n};\n\nexport interface LocalStorageProxyDeleteTask extends WorkerTaskTemplate {\n type: 'localStorageProxy',\n payload: {\n type: 'delete',\n keys: string[]\n }\n}; */\n\nconst THROTTLE_TIME = 16;\n\n/* Storage extends {[name: string]: any} *//* Storage extends Record<string, any> */\nexport default class AppStorage<\n Storage extends Record<string, any>,\n T extends Database<any>\n> {\n private static STORAGES: AppStorage<any, Database<any>>[] = [];\n private storage: IDBStorage<T>;// new CacheStorageController('session');\n\n // private cache: Partial<{[key: string]: Storage[typeof key]}> = {};\n private cache: Partial<Storage> = {};\n private useStorage: boolean;\n private savingFreezed: boolean;\n\n private getPromises: Map<keyof Storage, CancellablePromise<Storage[keyof Storage]>> = new Map();\n private getThrottled: () => void;\n\n private keysToSet: Set<keyof Storage> = new Set();\n private saveThrottled: () => void;\n private saveDeferred = deferredPromise<void>();\n\n private keysToDelete: Set<keyof Storage> = new Set();\n private deleteThrottled: () => void;\n private deleteDeferred = deferredPromise<void>();\n\n constructor(private db: T, private storeName: typeof db['stores'][number]['name']) {\n this.storage = new IDBStorage<T>(db, storeName);\n\n if(AppStorage.STORAGES.length) {\n this.useStorage = AppStorage.STORAGES[0].useStorage;\n } else {\n this.useStorage = true;\n }\n\n this.savingFreezed = false;\n\n AppStorage.STORAGES.push(this);\n\n this.saveThrottled = throttle(async() => {\n const deferred = this.saveDeferred;\n this.saveDeferred = deferredPromise();\n\n const set = this.keysToSet;\n if(set.size) {\n const keys = Array.from(set.values()) as string[];\n set.clear();\n\n const values = keys.map((key) => this.cache[key]);\n try {\n // console.log('setItem: will set', key/* , value */);\n // await this.cacheStorage.delete(key); // * try to prevent memory leak in Chrome leading to 'Unexpected internal error.'\n // await this.storage.save(key, new Response(value, {headers: {'Content-Type': 'application/json'}}));\n\n /* if(db === DATABASE_SESSION && !('localStorage' in self)) { // * support legacy Webogram's localStorage\n self.postMessage({\n type: 'localStorageProxy',\n payload: {\n type: 'set',\n keys,\n values\n }\n } as LocalStorageProxySetTask);\n } */\n\n await this.storage.save(keys, values);\n // console.log('setItem: have set', key/* , value */);\n } catch(e) {\n // this.useCS = false;\n console.error('[AS]: set error:', e, keys, values);\n }\n }\n\n deferred.resolve();\n\n if(set.size) {\n this.saveThrottled();\n }\n }, THROTTLE_TIME, false);\n\n this.deleteThrottled = throttle(async() => {\n const deferred = this.deleteDeferred;\n this.deleteDeferred = deferredPromise();\n\n const set = this.keysToDelete;\n if(set.size) {\n const keys = Array.from(set.values()) as string[];\n set.clear();\n\n try {\n /* if(db === DATABASE_SESSION && !('localStorage' in self)) { // * support legacy Webogram's localStorage\n self.postMessage({\n type: 'localStorageProxy',\n payload: {\n type: 'delete',\n keys\n }\n } as LocalStorageProxyDeleteTask);\n } */\n\n await this.storage.delete(keys);\n } catch(e) {\n console.error('[AS]: delete error:', e, keys);\n }\n }\n\n deferred.resolve();\n\n if(set.size) {\n this.deleteThrottled();\n }\n }, THROTTLE_TIME, false);\n\n this.getThrottled = throttle(async() => {\n const keys = Array.from(this.getPromises.keys());\n\n // const perf = performance.now();\n this.storage.get(keys as string[]).then((values) => {\n for(let i = 0, length = keys.length; i < length; ++i) {\n const key = keys[i];\n const deferred = this.getPromises.get(key);\n if(deferred) {\n // @ts-ignore\n deferred.resolve(this.cache[key] = values[i]);\n this.getPromises.delete(key);\n }\n }\n\n // console.log('[AS]: get time', keys, performance.now() - perf);\n }, (error: ApiError) => {\n const ignoreErrors: Set<ErrorType> = new Set(['NO_ENTRY_FOUND', 'STORAGE_OFFLINE']);\n if(!ignoreErrors.has(error.type)) {\n this.useStorage = false;\n console.error('[AS]: get error:', error, keys, storeName);\n }\n\n for(let i = 0, length = keys.length; i < length; ++i) {\n const key = keys[i];\n const deferred = this.getPromises.get(key);\n if(deferred) {\n // deferred.reject(error);\n deferred.resolve(undefined);\n this.getPromises.delete(key);\n }\n }\n }).finally(() => {\n if(this.getPromises.size) {\n this.getThrottled();\n }\n });\n }, THROTTLE_TIME, false);\n }\n\n public isAvailable() {\n return this.useStorage;\n }\n\n public getCache() {\n return this.cache;\n }\n\n public getFromCache<T extends keyof Storage>(key: T) {\n return this.cache[key];\n }\n\n public setToCache(key: keyof Storage, value: Storage[typeof key]) {\n return this.cache[key] = value;\n }\n\n public async get<T extends keyof Storage>(key: T, useCache = true): Promise<Storage[T]> {\n if(this.cache.hasOwnProperty(key) && useCache) {\n return this.getFromCache(key);\n } else if(this.useStorage) {\n const r = this.getPromises.get(key);\n if(r) return r as any;\n\n const p = deferredPromise<Storage[T]>();\n this.getPromises.set(key, p as any);\n\n this.getThrottled();\n\n return p;\n }/* else {\n throw 'something went wrong';\n } */\n }\n\n public getAll() {\n return this.storage.getAll().catch(() => []);\n }\n\n public set(obj: Partial<Storage>, onlyLocal = false) {\n // console.log('storageSetValue', obj, callback, arguments);\n\n const canUseStorage = this.useStorage && !onlyLocal && !this.savingFreezed;\n for(const key in obj) {\n if(obj.hasOwnProperty(key)) {\n const value = obj[key];\n this.setToCache(key, value);\n\n // let perf = /* DEBUG */false ? performance.now() : 0;\n // value = JSON.stringify(value);\n\n // if(perf) {\n // let elapsedTime = performance.now() - perf;\n // if(elapsedTime > 10) {\n // console.warn('LocalStorage set: stringify time by JSON.stringify:', elapsedTime, key);\n // }\n // }\n\n /* perf = performance.now();\n value = stringify(value);\n console.log('LocalStorage set: stringify time by own stringify:', performance.now() - perf); */\n\n if(canUseStorage) {\n this.keysToSet.add(key);\n this.keysToDelete.delete(key);\n this.saveThrottled();\n }\n }\n }\n\n return canUseStorage ? this.saveDeferred : Promise.resolve();\n }\n\n public delete(key: keyof Storage, saveLocal = false) {\n /* if(!this.cache.hasOwnProperty(key)) {\n return;\n } */\n\n // ! it is needed here\n key = '' + (key as string);\n\n if(!saveLocal) {\n delete this.cache[key];\n }\n\n if(this.useStorage) {\n this.keysToSet.delete(key);\n this.keysToDelete.add(key);\n this.deleteThrottled();\n }\n\n return this.useStorage ? this.deleteDeferred : Promise.resolve();\n }\n\n public clear(saveLocal = false) {\n if(!saveLocal) {\n for(const i in this.cache) {\n delete this.cache[i];\n }\n }\n\n return this.storage.clear().catch(noop);\n }\n\n public static toggleStorage(enabled: boolean, clearWrite: boolean) {\n return Promise.all(this.STORAGES.map((storage) => {\n storage.useStorage = enabled;\n\n if(!IS_WORKER || !clearWrite) {\n return;\n }\n\n if(!enabled) {\n storage.keysToSet.clear();\n storage.keysToDelete.clear();\n storage.getPromises.forEach((deferred) => deferred.resolve(undefined));\n storage.getPromises.clear();\n return storage.clear(true);\n } else {\n return storage.set(storage.cache);\n }\n })).catch(noop);\n }\n\n public static freezeSaving<T extends Database<any>>(callback: () => any, names: T['stores'][number]['name'][]) {\n this.STORAGES.forEach((storage) => storage.savingFreezed = true);\n try {\n callback();\n } catch(err) {\n console.error('freezeSaving callback error:', err);\n }\n this.STORAGES.forEach((storage) => storage.savingFreezed = false);\n }\n\n /* public deleteDatabase() {\n return IDBStorage.deleteDatabase().catch(noop);\n } */\n}\n\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.AppStorage = AppStorage);\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {Database} from '.';\nimport type {IDBIndex} from '../../lib/files/idb';\n\nconst DATABASE_STATE: Database<'session' | 'stickerSets' | 'users' | 'chats' | 'messages' | 'dialogs'> = {\n name: 'tweb',\n version: 7,\n stores: [{\n name: 'session'\n }, {\n name: 'stickerSets'\n }, {\n name: 'users'\n }, {\n name: 'chats'\n }, {\n name: 'dialogs'\n // indexes: [\n // ...(new Array(20 + 2).fill(0)).map((_, idx) => {\n // const name = `index_${idx}`;\n // const index: IDBIndex = {\n // indexName: name,\n // keyPath: name,\n // objectParameters: {}\n // };\n\n // return index\n // })\n // ]\n }, {\n name: 'messages'\n }]\n};\n\nexport default DATABASE_STATE;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {ChatSavedPosition} from './appManagers/appImManager';\nimport type {AppDraftsManager} from './appManagers/appDraftsManager';\nimport type {State} from '../config/state';\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport {LangPackDifference} from '../layer';\nimport AppStorage from './storage';\nimport DATABASE_STATE from '../config/databases/state';\n\nclass StateStorage extends AppStorage<{\n chatPositions: {\n [peerId_threadId: string]: ChatSavedPosition\n },\n langPack: LangPackDifference,\n drafts: AppDraftsManager['drafts'],\n user_auth: any, // support old webk format\n} & State, typeof DATABASE_STATE> {\n constructor() {\n super(DATABASE_STATE, 'session');\n }\n}\n\nconst stateStorage = new StateStorage();\nMOUNT_CLASS_TO.stateStorage = stateStorage;\nexport default stateStorage;\n","/**\n * ignores `undefined` properties\n */\nexport default function deepEqual<T>(x: T, y: T, ignoreKeys?: (keyof T)[]): boolean {\n const ignoreSet = ignoreKeys && new Set(ignoreKeys);\n const okok = (obj: any) => Object.keys(obj).filter((key) => obj[key] !== undefined);\n const ok = ignoreKeys ? (obj: any) => okok(obj).filter((key) => !ignoreSet.has(key as any)) : okok,\n tx = typeof x,\n ty = typeof y;\n return x && y && tx === 'object' && tx === ty ? (\n ok(x).length === ok(y).length &&\n ok(x).every((key) => deepEqual((x as any)[key], (y as any)[key], ignoreKeys))\n ) : (x === y);\n}\n","export default function capitalizeFirstLetter(string: string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\n","const SKIP_PROTOCOLS: Set<string> = new Set([\n 'javascript:'\n]);\nexport default function matchUrlProtocol(text: string) {\n if(!text) {\n return null;\n }\n\n try {\n const protocol = new URL(text).protocol;\n if(SKIP_PROTOCOLS.has(protocol)) {\n return null;\n }\n\n return protocol;\n } catch(err) {\n return null;\n }\n}\n","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n\nconst originalString = '((?:\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f?\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f?\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f?\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f?\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f?\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\ud83e\\udef1\\ud83c\\udffb\\u200d\\ud83e\\udef2\\ud83c[\\udffc-\\udfff]|\\ud83e\\udef1\\ud83c\\udffc\\u200d\\ud83e\\udef2\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\udef1\\ud83c\\udffd\\u200d\\ud83e\\udef2\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\udef1\\ud83c\\udffe\\u200d\\ud83e\\udef2\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\udef1\\ud83c\\udfff\\u200d\\ud83e\\udef2\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f?\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f?\\u200d\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc8f\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc91\\ud83c[\\udffb-\\udfff]|\\ud83e\\udd1d\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d\\udc8f\\udc91]|\\ud83e\\udd1d)|(?:\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1)(?:\\ud83c[\\udffb-\\udfff])?\\u200d(?:\\u2695\\ufe0f?|\\u2696\\ufe0f?|\\u2708\\ufe0f?|\\ud83c[\\udf3e\\udf73\\udf7c\\udf84\\udf93\\udfa4\\udfa8\\udfeb\\udfed]|\\ud83d[\\udcbb\\udcbc\\udd27\\udd2c\\ude80\\ude92]|\\ud83e[\\uddaf-\\uddb3\\uddbc\\uddbd])|(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75]|\\u26f9)(?:(?:\\ud83c[\\udffb-\\udfff]|\\ufe0f?)\\u200d[\\u2640\\u2642]\\ufe0f?)|(?:\\ud83c[\\udfc3\\udfc4\\udfca]|\\ud83d[\\udc6e\\udc70\\udc71\\udc73\\udc77\\udc81\\udc82\\udc86\\udc87\\ude45-\\ude47\\ude4b\\ude4d\\ude4e\\udea3\\udeb4-\\udeb6]|\\ud83e[\\udd26\\udd35\\udd37-\\udd39\\udd3d\\udd3e\\uddb8\\uddb9\\uddcd-\\uddcf\\uddd4\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f?|(?:\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83c\\udff3\\ufe0f?\\u200d\\u26a7\\ufe0f?|\\ud83c\\udff3\\ufe0f?\\u200d\\ud83c\\udf08|\\ud83d\\ude36\\u200d\\ud83c\\udf2b\\ufe0f?|\\u2764\\ufe0f?\\u200d\\ud83d\\udd25|\\u2764\\ufe0f?\\u200d\\ud83e\\ude79|\\ud83c\\udff4\\u200d\\u2620\\ufe0f?|\\ud83d\\udc15\\u200d\\ud83e\\uddba|\\ud83d\\udc3b\\u200d\\u2744\\ufe0f?|\\ud83d\\udc41\\u200d\\ud83d\\udde8|\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc6f\\u200d\\u2640\\ufe0f?|\\ud83d\\udc6f\\u200d\\u2642\\ufe0f?|\\ud83d\\ude2e\\u200d\\ud83d\\udca8|\\ud83d\\ude35\\u200d\\ud83d\\udcab|\\ud83e\\udd3c\\u200d\\u2640\\ufe0f?|\\ud83e\\udd3c\\u200d\\u2642\\ufe0f?|\\ud83e\\uddde\\u200d\\u2640\\ufe0f?|\\ud83e\\uddde\\u200d\\u2642\\ufe0f?|\\ud83e\\udddf\\u200d\\u2640\\ufe0f?|\\ud83e\\udddf\\u200d\\u2642\\ufe0f?|\\ud83d\\udc08\\u200d\\u2b1b)|[#*0-9]\\ufe0f??\\u20e3|(?:[©®\\u2122\\u265f]\\ufe0f?)|(?:\\ud83c[\\udc04\\udd70\\udd71\\udd7e\\udd7f\\ude02\\ude1a\\ude2f\\ude37\\udf21\\udf24-\\udf2c\\udf36\\udf7d\\udf96\\udf97\\udf99-\\udf9b\\udf9e\\udf9f\\udfcd\\udfce\\udfd4-\\udfdf\\udff3\\udff5\\udff7]|\\ud83d[\\udc3f\\udc41\\udcfd\\udd49\\udd4a\\udd6f\\udd70\\udd73\\udd76-\\udd79\\udd87\\udd8a-\\udd8d\\udda5\\udda8\\uddb1\\uddb2\\uddbc\\uddc2-\\uddc4\\uddd1-\\uddd3\\udddc-\\uddde\\udde1\\udde3\\udde8\\uddef\\uddf3\\uddfa\\udecb\\udecd-\\udecf\\udee0-\\udee5\\udee9\\udef0\\udef3]|[\\u203c\\u2049\\u2139\\u2194-\\u2199\\u21a9\\u21aa\\u231a\\u231b\\u2328\\u23cf\\u23ed-\\u23ef\\u23f1\\u23f2\\u23f8-\\u23fa\\u24c2\\u25aa\\u25ab\\u25b6\\u25c0\\u25fb-\\u25fe\\u2600-\\u2604\\u260e\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262a\\u262e\\u262f\\u2638-\\u263a\\u2640\\u2642\\u2648-\\u2653\\u2660\\u2663\\u2665\\u2666\\u2668\\u267b\\u267f\\u2692-\\u2697\\u2699\\u269b\\u269c\\u26a0\\u26a1\\u26a7\\u26aa\\u26ab\\u26b0\\u26b1\\u26bd\\u26be\\u26c4\\u26c5\\u26c8\\u26cf\\u26d1\\u26d3\\u26d4\\u26e9\\u26ea\\u26f0-\\u26f5\\u26f8\\u26fa\\u26fd\\u2702\\u2708\\u2709\\u270f\\u2712\\u2714\\u2716\\u271d\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u2764\\u27a1\\u2934\\u2935\\u2b05-\\u2b07\\u2b1b\\u2b1c\\u2b50\\u2b55\\u3030\\u303d\\u3297\\u3299])(?:\\ufe0f?|(?!\\ufe0e))|(?:(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75\\udd90]|[\\u261d\\u26f7\\u26f9\\u270c\\u270d])(?:\\ufe0f?|(?!\\ufe0e))|(?:\\ud83c[\\udf85\\udfc2-\\udfc4\\udfc7\\udfca]|\\ud83d[\\udc42\\udc43\\udc46-\\udc50\\udc66-\\udc69\\udc6e\\udc70-\\udc78\\udc7c\\udc81-\\udc83\\udc85-\\udc87\\udcaa\\udd7a\\udd95\\udd96\\ude45-\\ude47\\ude4b-\\ude4f\\udea3\\udeb4-\\udeb6\\udec0\\udecc]|\\ud83e[\\udd0c\\udd0f\\udd18-\\udd1c\\udd1e\\udd1f\\udd26\\udd30-\\udd39\\udd3d\\udd3e\\udd77\\uddb5\\uddb6\\uddb8\\uddb9\\uddbb\\uddcd-\\uddcf\\uddd1-\\udddd\\udec3-\\udec5\\udef0-\\udef6]|[\\u270a\\u270b]))(?:\\ud83c[\\udffb-\\udfff])?|(?:\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc65\\udb40\\udc6e\\udb40\\udc67\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc73\\udb40\\udc63\\udb40\\udc74\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc77\\udb40\\udc6c\\udb40\\udc73\\udb40\\udc7f|\\ud83c\\udde6\\ud83c[\\udde8-\\uddec\\uddee\\uddf1\\uddf2\\uddf4\\uddf6-\\uddfa\\uddfc\\uddfd\\uddff]|\\ud83c\\udde7\\ud83c[\\udde6\\udde7\\udde9-\\uddef\\uddf1-\\uddf4\\uddf6-\\uddf9\\uddfb\\uddfc\\uddfe\\uddff]|\\ud83c\\udde8\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\uddee\\uddf0-\\uddf5\\uddf7\\uddfa-\\uddff]|\\ud83c\\udde9\\ud83c[\\uddea\\uddec\\uddef\\uddf0\\uddf2\\uddf4\\uddff]|\\ud83c\\uddea\\ud83c[\\udde6\\udde8\\uddea\\uddec\\udded\\uddf7-\\uddfa]|\\ud83c\\uddeb\\ud83c[\\uddee-\\uddf0\\uddf2\\uddf4\\uddf7]|\\ud83c\\uddec\\ud83c[\\udde6\\udde7\\udde9-\\uddee\\uddf1-\\uddf3\\uddf5-\\uddfa\\uddfc\\uddfe]|\\ud83c\\udded\\ud83c[\\uddf0\\uddf2\\uddf3\\uddf7\\uddf9\\uddfa]|\\ud83c\\uddee\\ud83c[\\udde8-\\uddea\\uddf1-\\uddf4\\uddf6-\\uddf9]|\\ud83c\\uddef\\ud83c[\\uddea\\uddf2\\uddf4\\uddf5]|\\ud83c\\uddf0\\ud83c[\\uddea\\uddec-\\uddee\\uddf2\\uddf3\\uddf5\\uddf7\\uddfc\\uddfe\\uddff]|\\ud83c\\uddf1\\ud83c[\\udde6-\\udde8\\uddee\\uddf0\\uddf7-\\uddfb\\uddfe]|\\ud83c\\uddf2\\ud83c[\\udde6\\udde8-\\udded\\uddf0-\\uddff]|\\ud83c\\uddf3\\ud83c[\\udde6\\udde8\\uddea-\\uddec\\uddee\\uddf1\\uddf4\\uddf5\\uddf7\\uddfa\\uddff]|\\ud83c\\uddf4\\ud83c\\uddf2|\\ud83c\\uddf5\\ud83c[\\udde6\\uddea-\\udded\\uddf0-\\uddf3\\uddf7-\\uddf9\\uddfc\\uddfe]|\\ud83c\\uddf6\\ud83c\\udde6|\\ud83c\\uddf7\\ud83c[\\uddea\\uddf4\\uddf8\\uddfa\\uddfc]|\\ud83c\\uddf8\\ud83c[\\udde6-\\uddea\\uddec-\\uddf4\\uddf7-\\uddf9\\uddfb\\uddfd-\\uddff]|\\ud83c\\uddf9\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\udded\\uddef-\\uddf4\\uddf7\\uddf9\\uddfb\\uddfc\\uddff]|\\ud83c\\uddfa\\ud83c[\\udde6\\uddec\\uddf2\\uddf3\\uddf8\\uddfe\\uddff]|\\ud83c\\uddfb\\ud83c[\\udde6\\udde8\\uddea\\uddec\\uddee\\uddf3\\uddfa]|\\ud83c\\uddfc\\ud83c[\\uddeb\\uddf8]|\\ud83c\\uddfd\\ud83c\\uddf0|\\ud83c\\uddfe\\ud83c[\\uddea\\uddf9]|\\ud83c\\uddff\\ud83c[\\udde6\\uddf2\\uddfc]|\\ud83c[\\udccf\\udd8e\\udd91-\\udd9a\\udde6-\\uddff\\ude01\\ude32-\\ude36\\ude38-\\ude3a\\ude50\\ude51\\udf00-\\udf20\\udf2d-\\udf35\\udf37-\\udf7c\\udf7e-\\udf84\\udf86-\\udf93\\udfa0-\\udfc1\\udfc5\\udfc6\\udfc8\\udfc9\\udfcf-\\udfd3\\udfe0-\\udff0\\udff4\\udff8-\\udfff]|\\ud83d[\\udc00-\\udc3e\\udc40\\udc44\\udc45\\udc51-\\udc65\\udc6a\\udc6f\\udc79-\\udc7b\\udc7d-\\udc80\\udc84\\udc88-\\udc8e\\udc90\\udc92-\\udca9\\udcab-\\udcfc\\udcff-\\udd3d\\udd4b-\\udd4e\\udd50-\\udd67\\udda4\\uddfb-\\ude44\\ude48-\\ude4a\\ude80-\\udea2\\udea4-\\udeb3\\udeb7-\\udebf\\udec1-\\udec5\\uded0-\\uded2\\uded5-\\uded7\\udedd-\\udedf\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb\\udff0]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcc\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7c\\ude80-\\ude86\\ude90-\\udeac\\udeb0-\\udeba\\udec0-\\udec2\\uded0-\\uded9\\udee0-\\udee7]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f)';\nexport default originalString;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport emojiRegExp from '../../vendor/emoji/regex';\nimport {MessageEntity} from '../../layer';\n\nconst EmojiHelper = {\n emojiMap: (code: string) => { return code; },\n shortcuts: [] as any,\n emojis: [] as any\n};\n\nexport const ALPHA_CHARS_REG_EXP = 'a-z' +\n '\\\\u00c0-\\\\u00d6\\\\u00d8-\\\\u00f6\\\\u00f8-\\\\u00ff' + // Latin-1\n '\\\\u0100-\\\\u024f' + // Latin Extended A and B\n '\\\\u0253\\\\u0254\\\\u0256\\\\u0257\\\\u0259\\\\u025b\\\\u0263\\\\u0268\\\\u026f\\\\u0272\\\\u0289\\\\u028b' + // IPA Extensions\n '\\\\u02bb' + // Hawaiian\n '\\\\u0300-\\\\u036f' + // Combining diacritics\n '\\\\u1e00-\\\\u1eff' + // Latin Extended Additional (mostly for Vietnamese)\n '\\\\u0400-\\\\u04ff\\\\u0500-\\\\u0527' + // Cyrillic\n '\\\\u2de0-\\\\u2dff\\\\ua640-\\\\ua69f' + // Cyrillic Extended A/B\n '\\\\u0591-\\\\u05bf\\\\u05c1-\\\\u05c2\\\\u05c4-\\\\u05c5\\\\u05c7' +\n '\\\\u05d0-\\\\u05ea\\\\u05f0-\\\\u05f4' + // Hebrew\n '\\\\ufb1d-\\\\ufb28\\\\ufb2a-\\\\ufb36\\\\ufb38-\\\\ufb3c\\\\ufb3e\\\\ufb40-\\\\ufb41' +\n '\\\\ufb43-\\\\ufb44\\\\ufb46-\\\\ufb4f' + // Hebrew Pres. Forms\n '\\\\u0610-\\\\u061a\\\\u0620-\\\\u065f\\\\u066e-\\\\u06d3\\\\u06d5-\\\\u06dc' +\n '\\\\u06de-\\\\u06e8\\\\u06ea-\\\\u06ef\\\\u06fa-\\\\u06fc\\\\u06ff' + // Arabic\n '\\\\u0750-\\\\u077f\\\\u08a0\\\\u08a2-\\\\u08ac\\\\u08e4-\\\\u08fe' + // Arabic Supplement and Extended A\n '\\\\ufb50-\\\\ufbb1\\\\ufbd3-\\\\ufd3d\\\\ufd50-\\\\ufd8f\\\\ufd92-\\\\ufdc7\\\\ufdf0-\\\\ufdfb' + // Pres. Forms A\n '\\\\ufe70-\\\\ufe74\\\\ufe76-\\\\ufefc' + // Pres. Forms B\n '\\\\u200c' + // Zero-Width Non-Joiner\n '\\\\u0e01-\\\\u0e3a\\\\u0e40-\\\\u0e4e' + // Thai\n '\\\\u1100-\\\\u11ff\\\\u3130-\\\\u3185\\\\uA960-\\\\uA97F\\\\uAC00-\\\\uD7AF\\\\uD7B0-\\\\uD7FF' + // Hangul (Korean)\n '\\\\u3003\\\\u3005\\\\u303b' + // Kanji/Han iteration marks\n '\\\\uff21-\\\\uff3a\\\\uff41-\\\\uff5a' + // full width Alphabet\n '\\\\uff66-\\\\uff9f' + // half width Katakana\n '\\\\uffa1-\\\\uffdc'; // half width Hangul (Korean)\nexport const ALPHA_NUMERIC_REG_EXP = '0-9\\_' + ALPHA_CHARS_REG_EXP;\nexport const DOMAIN_ADD_CHARS = '\\u00b7';\n// Based on Regular Expression for URL validation by Diego Perini\nexport const URL_ALPHANUMERIC_REG_EXP_PART = '[' + ALPHA_CHARS_REG_EXP + '0-9]';\nexport const URL_PROTOCOL_REG_EXP_PART = '((?:https?|ftp)://|mailto:)?';\nexport const URL_REG_EXP = URL_PROTOCOL_REG_EXP_PART +\n // user:pass authentication\n '(?:' + URL_ALPHANUMERIC_REG_EXP_PART + '{1,64}(?::' + URL_ALPHANUMERIC_REG_EXP_PART + '{0,64})?@)?' +\n '(?:' +\n // sindresorhus/ip-regexp\n '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(?:\\\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])){3}' +\n '|' +\n // host name\n URL_ALPHANUMERIC_REG_EXP_PART + '[' + ALPHA_CHARS_REG_EXP + DOMAIN_ADD_CHARS + '0-9\\-]{0,64}' +\n // domain name\n '(?:\\\\.' + URL_ALPHANUMERIC_REG_EXP_PART + '[' + ALPHA_CHARS_REG_EXP + DOMAIN_ADD_CHARS + '0-9\\-]{0,64}){0,10}' +\n // TLD identifier\n '(?:\\\\.(xn--[0-9a-z]{2,16}|[' + ALPHA_CHARS_REG_EXP + ']{2,24}))' +\n ')' +\n // port number\n '(?::\\\\d{2,5})?' +\n // resource path\n '(?:/(?:\\\\S{0,255}[^\\\\s.;,(\\\\[\\\\]{}<>\"\\'])?)?';\nexport const URL_PROTOCOL_REG_EXP = new RegExp('^' + URL_PROTOCOL_REG_EXP_PART.slice(0, -1), 'i');\nexport const USERNAME_REG_EXP = '[a-zA-Z\\\\d_]{5,32}';\n// export const TIMESTAMP_REG_EXP = '(?:\\\\s|^)((?:\\\\d{1,2}:)?(?:[0-5]?[0-9]):(?:[0-5][0-9]))(?:\\\\s|$)';\nexport const TIMESTAMP_REG_EXP = '(?:\\\\s|^)((?:(\\\\d{1,2}):(?:[0-5]?[0-9])|(?:\\\\d{1,2}|\\\\d{3,})):(?:[0-5][0-9]))(?:\\\\s|$)';\nexport const BOT_COMMAND_REG_EXP = '\\\\/([a-zA-Z\\\\d_]{1,32})(?:@(' + USERNAME_REG_EXP + '))?(\\\\b|$)';\nexport const FULL_REG_EXP = new RegExp('(^| )(@)(' + USERNAME_REG_EXP + ')|(' + URL_REG_EXP + ')|(\\\\n)|(' + emojiRegExp + ')|(^|[\\\\s\\\\(\\\\]])(#[' + ALPHA_NUMERIC_REG_EXP + ']{2,64})|(^|\\\\s)' + BOT_COMMAND_REG_EXP + '|' + TIMESTAMP_REG_EXP + '', 'i');\nexport const EMAIL_REG_EXP = /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n// const markdownTestRegExp = /[`_*@~]/;\nexport const MARKDOWN_REG_EXP = /(^|\\s|\\n)(````?)([\\s\\S]+?)(````?)([\\s\\n\\.,:?!;]|$)|(^|\\s|\\x01)(`|~~|\\*\\*|__|_-_|\\|\\|)([^\\n]+?)\\7([\\x01\\s\\.,:?!;]|$)|@(\\d+)\\s*\\((.+?)\\)|(\\[(.+?)\\]\\((.+?)\\))/m;\nexport const SITE_HASHTAGS: {[siteName: string]: string} = {\n 'Telegram': 'tg://search_hashtag?hashtag={1}',\n 'Twitter': 'https://twitter.com/hashtag/{1}',\n 'Instagram': 'https://instagram.com/explore/tags/{1}/',\n 'Google Plus': 'https://plus.google.com/explore/{1}'\n};\n\n// export const SITE_MENTIONS: {[siteName in 'Telegram' | 'Twitter' | 'Instagram' | 'GitHub']: string} = {\n// Telegram: '#{1}',\n// Twitter: 'https://twitter.com/{1}',\n// Instagram: 'https://instagram.com/{1}/',\n// GitHub: 'https://github.com/{1}'\n// };\n\nexport const MARKDOWN_ENTITIES: {[markdown: string]: MessageEntity['_']} = {\n '`': 'messageEntityCode',\n '``': 'messageEntityPre',\n '**': 'messageEntityBold',\n '__': 'messageEntityItalic',\n '~~': 'messageEntityStrike',\n '_-_': 'messageEntityUnderline',\n '||': 'messageEntitySpoiler'\n};\n\nexport const MARKDOWN_ENTITIES_TYPES = new Set(Object.values(MARKDOWN_ENTITIES));\n\nexport const PASS_CONFLICTING_ENTITIES: Set<MessageEntity['_']> = new Set([\n 'messageEntityEmoji',\n 'messageEntityLinebreak',\n 'messageEntityCaret'\n]);\nexport const PASS_SINGLE_CONFLICTING_ENTITIES = new Set(PASS_CONFLICTING_ENTITIES);\nfor(const i in MARKDOWN_ENTITIES) {\n PASS_CONFLICTING_ENTITIES.add(MARKDOWN_ENTITIES[i]);\n}\n\nexport const PHONE_NUMBER_REG_EXP = /^\\+\\d+$/;\n\nexport const LOCAL_ENTITIES = new Set<MessageEntity['_']>([\n 'messageEntityLinebreak',\n 'messageEntityCaret',\n 'messageEntityHighlight',\n 'messageEntityBotCommand',\n 'messageEntityTimestamp'\n]);\n\n/* export function parseEmojis(text: string) {\n return text.replace(/:([a-z0-9\\-\\+\\*_]+?):/gi, function (all, shortcut) {\n var emojiCode = EmojiHelper.shortcuts[shortcut]\n if (emojiCode !== undefined) {\n return EmojiHelper.emojis[emojiCode][0]\n }\n return all\n })\n} */\n\n\n/* export function replaceUrlEncodings(urlWithEncoded: string) {\n return urlWithEncoded.replace(/(%[A-Z\\d]{2})+/g, (str) => {\n try {\n return decodeURIComponent(str);\n } catch (e) {\n return str;\n }\n });\n} */\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type addAnchorListener from '../../helpers/addAnchorListener';\nimport {PHONE_NUMBER_REG_EXP} from '.';\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport matchUrlProtocol from './matchUrlProtocol';\nimport {T_ME_PREFIXES} from '../mtproto/mtproto_config';\n\nexport default function wrapUrl(url: string, unsafe?: number | boolean) {\n if(!matchUrlProtocol(url)) {\n url = 'https://' + url;\n }\n\n const out: {url: string, onclick?: Parameters<typeof addAnchorListener>[0]['name']} = {url};\n let tgMeMatch, telescoPeMatch, tgMatch;\n let onclick: typeof out['onclick'];\n /* if(unsafe === 2) {\n url = 'tg://unsafe_url?url=' + encodeURIComponent(url);\n } else */if((tgMeMatch = url.match(/^(?:https?:\\/\\/)?(?:(.+?)\\.)?(?:(?:web|k|z|a)\\.)?t(?:elegram)?\\.me(?:\\/(.+))?/))) {\n const u = new URL(url);\n let prefix = tgMeMatch[1];\n if(prefix && T_ME_PREFIXES.has(tgMeMatch[1])) {\n prefix = undefined;\n }\n\n if(prefix) {\n u.pathname = prefix + (u.pathname === '/' ? '' : u.pathname);\n }\n\n const fullPath = u.pathname.slice(1);\n const path = fullPath.split('/');\n\n if(path[0] && path[0][0] === '$' && path[0].length > 1) {\n onclick = 'invoice';\n } else if(/^\\+/.test(fullPath) && !PHONE_NUMBER_REG_EXP.test(fullPath)) { // second regexp is for phone numbers (t.me/+38050...)\n onclick = 'joinchat';\n } else if(path[0]) switch(path[0]) {\n case 'm':\n case 'addlist':\n case 'joinchat':\n case 'addstickers':\n case 'addemoji':\n case 'voicechat':\n case 'invoice':\n case 'boost':\n case 'giftcode':\n if(path.length !== 1 && !prefix) {\n onclick = path[0];\n break;\n }\n\n default:\n if(path.length <= 2 || path[1]?.match(/^\\d+(?:\\?(?:comment|thread)=\\d+)?$/) || path[1] === 's') {\n onclick = 'im';\n break;\n }\n\n break;\n }\n } else if((telescoPeMatch = url.match(/^(?:https?:\\/\\/)?telesco\\.pe\\/([^/?]+)\\/(\\d+)/))) {\n onclick = 'im';\n } else if((tgMatch = url.match(/tg:(?:\\/\\/)?(.+?)(?:\\?|$)/))) {\n onclick = 'tg_' + tgMatch[1] as any;\n }/* else if(unsafe) {\n url = 'tg://unsafe_url?url=' + encodeURIComponent(url);\n } */\n\n if(!(window as any)[onclick]) {\n onclick = undefined;\n }\n\n out.onclick = onclick;\n return out;\n}\n\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.wrapUrl = wrapUrl);\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\n// import I18n from '../../lib/langPack';\n\nexport default function setInnerHTML(elem: Element, html: string | DocumentFragment | Element) {\n setDirection(elem);\n if(html === undefined) {\n elem.replaceChildren();\n } else if(typeof(html) === 'string') {\n if(!html) elem.replaceChildren();\n else elem.textContent = html;\n } else {\n elem.replaceChildren(html);\n }\n}\n\nexport function setDirection(elem: Element) {\n // if(!I18n.isRTL) {\n elem.setAttribute('dir', 'auto');\n // }\n}\n\nexport function getDirection(): 'auto' {\n return 'auto';\n}\n","export default function setBlankToAnchor(anchor: HTMLAnchorElement) {\n anchor.target = '_blank';\n anchor.rel = 'noopener noreferrer';\n return anchor;\n}\n","let taskIdCounter = 1,\n isCallbackScheduled = false,\n isPerformingWork = false,\n taskQueue = [],\n currentTask = null,\n shouldYieldToHost = null,\n yieldInterval = 5,\n deadline = 0,\n maxYieldInterval = 300,\n scheduleCallback = null,\n scheduledCallback = null;\nconst maxSigned31BitInt = 1073741823;\nfunction setupScheduler() {\n const channel = new MessageChannel(),\n port = channel.port2;\n scheduleCallback = () => port.postMessage(null);\n channel.port1.onmessage = () => {\n if (scheduledCallback !== null) {\n const currentTime = performance.now();\n deadline = currentTime + yieldInterval;\n const hasTimeRemaining = true;\n try {\n const hasMoreWork = scheduledCallback(hasTimeRemaining, currentTime);\n if (!hasMoreWork) {\n scheduledCallback = null;\n } else port.postMessage(null);\n } catch (error) {\n port.postMessage(null);\n throw error;\n }\n }\n };\n if (navigator && navigator.scheduling && navigator.scheduling.isInputPending) {\n const scheduling = navigator.scheduling;\n shouldYieldToHost = () => {\n const currentTime = performance.now();\n if (currentTime >= deadline) {\n if (scheduling.isInputPending()) {\n return true;\n }\n return currentTime >= maxYieldInterval;\n } else {\n return false;\n }\n };\n } else {\n shouldYieldToHost = () => performance.now() >= deadline;\n }\n}\nfunction enqueue(taskQueue, task) {\n function findIndex() {\n let m = 0;\n let n = taskQueue.length - 1;\n while (m <= n) {\n const k = n + m >> 1;\n const cmp = task.expirationTime - taskQueue[k].expirationTime;\n if (cmp > 0) m = k + 1;else if (cmp < 0) n = k - 1;else return k;\n }\n return m;\n }\n taskQueue.splice(findIndex(), 0, task);\n}\nfunction requestCallback(fn, options) {\n if (!scheduleCallback) setupScheduler();\n let startTime = performance.now(),\n timeout = maxSigned31BitInt;\n if (options && options.timeout) timeout = options.timeout;\n const newTask = {\n id: taskIdCounter++,\n fn,\n startTime,\n expirationTime: startTime + timeout\n };\n enqueue(taskQueue, newTask);\n if (!isCallbackScheduled && !isPerformingWork) {\n isCallbackScheduled = true;\n scheduledCallback = flushWork;\n scheduleCallback();\n }\n return newTask;\n}\nfunction cancelCallback(task) {\n task.fn = null;\n}\nfunction flushWork(hasTimeRemaining, initialTime) {\n isCallbackScheduled = false;\n isPerformingWork = true;\n try {\n return workLoop(hasTimeRemaining, initialTime);\n } finally {\n currentTask = null;\n isPerformingWork = false;\n }\n}\nfunction workLoop(hasTimeRemaining, initialTime) {\n let currentTime = initialTime;\n currentTask = taskQueue[0] || null;\n while (currentTask !== null) {\n if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {\n break;\n }\n const callback = currentTask.fn;\n if (callback !== null) {\n currentTask.fn = null;\n const didUserCallbackTimeout = currentTask.expirationTime <= currentTime;\n callback(didUserCallbackTimeout);\n currentTime = performance.now();\n if (currentTask === taskQueue[0]) {\n taskQueue.shift();\n }\n } else taskQueue.shift();\n currentTask = taskQueue[0] || null;\n }\n return currentTask !== null;\n}\n\nconst sharedConfig = {\n context: undefined,\n registry: undefined\n};\nfunction setHydrateContext(context) {\n sharedConfig.context = context;\n}\nfunction nextHydrateContext() {\n return {\n ...sharedConfig.context,\n id: `${sharedConfig.context.id}${sharedConfig.context.count++}-`,\n count: 0\n };\n}\n\nconst equalFn = (a, b) => a === b;\nconst $PROXY = Symbol(\"solid-proxy\");\nconst $TRACK = Symbol(\"solid-track\");\nconst $DEVCOMP = Symbol(\"solid-dev-component\");\nconst signalOptions = {\n equals: equalFn\n};\nlet ERROR = null;\nlet runEffects = runQueue;\nconst STALE = 1;\nconst PENDING = 2;\nconst UNOWNED = {\n owned: null,\n cleanups: null,\n context: null,\n owner: null\n};\nconst NO_INIT = {};\nvar Owner = null;\nlet Transition = null;\nlet Scheduler = null;\nlet ExternalSourceConfig = null;\nlet Listener = null;\nlet Updates = null;\nlet Effects = null;\nlet ExecCount = 0;\nfunction createRoot(fn, detachedOwner) {\n const listener = Listener,\n owner = Owner,\n unowned = fn.length === 0,\n current = detachedOwner === undefined ? owner : detachedOwner,\n root = unowned ? UNOWNED : {\n owned: null,\n cleanups: null,\n context: current ? current.context : null,\n owner: current\n },\n updateFn = unowned ? fn : () => fn(() => untrack(() => cleanNode(root)));\n Owner = root;\n Listener = null;\n try {\n return runUpdates(updateFn, true);\n } finally {\n Listener = listener;\n Owner = owner;\n }\n}\nfunction createSignal(value, options) {\n options = options ? Object.assign({}, signalOptions, options) : signalOptions;\n const s = {\n value,\n observers: null,\n observerSlots: null,\n comparator: options.equals || undefined\n };\n const setter = value => {\n if (typeof value === \"function\") {\n if (Transition && Transition.running && Transition.sources.has(s)) value = value(s.tValue);else value = value(s.value);\n }\n return writeSignal(s, value);\n };\n return [readSignal.bind(s), setter];\n}\nfunction createComputed(fn, value, options) {\n const c = createComputation(fn, value, true, STALE);\n if (Scheduler && Transition && Transition.running) Updates.push(c);else updateComputation(c);\n}\nfunction createRenderEffect(fn, value, options) {\n const c = createComputation(fn, value, false, STALE);\n if (Scheduler && Transition && Transition.running) Updates.push(c);else updateComputation(c);\n}\nfunction createEffect(fn, value, options) {\n runEffects = runUserEffects;\n const c = createComputation(fn, value, false, STALE),\n s = SuspenseContext && useContext(SuspenseContext);\n if (s) c.suspense = s;\n if (!options || !options.render) c.user = true;\n Effects ? Effects.push(c) : updateComputation(c);\n}\nfunction createReaction(onInvalidate, options) {\n let fn;\n const c = createComputation(() => {\n fn ? fn() : untrack(onInvalidate);\n fn = undefined;\n }, undefined, false, 0),\n s = SuspenseContext && useContext(SuspenseContext);\n if (s) c.suspense = s;\n c.user = true;\n return tracking => {\n fn = tracking;\n updateComputation(c);\n };\n}\nfunction createMemo(fn, value, options) {\n options = options ? Object.assign({}, signalOptions, options) : signalOptions;\n const c = createComputation(fn, value, true, 0);\n c.observers = null;\n c.observerSlots = null;\n c.comparator = options.equals || undefined;\n if (Scheduler && Transition && Transition.running) {\n c.tState = STALE;\n Updates.push(c);\n } else updateComputation(c);\n return readSignal.bind(c);\n}\nfunction isPromise(v) {\n return v && typeof v === \"object\" && \"then\" in v;\n}\nfunction createResource(pSource, pFetcher, pOptions) {\n let source;\n let fetcher;\n let options;\n if (arguments.length === 2 && typeof pFetcher === \"object\" || arguments.length === 1) {\n source = true;\n fetcher = pSource;\n options = pFetcher || {};\n } else {\n source = pSource;\n fetcher = pFetcher;\n options = pOptions || {};\n }\n let pr = null,\n initP = NO_INIT,\n id = null,\n loadedUnderTransition = false,\n scheduled = false,\n resolved = (\"initialValue\" in options),\n dynamic = typeof source === \"function\" && createMemo(source);\n const contexts = new Set(),\n [value, setValue] = (options.storage || createSignal)(options.initialValue),\n [error, setError] = createSignal(undefined),\n [track, trigger] = createSignal(undefined, {\n equals: false\n }),\n [state, setState] = createSignal(resolved ? \"ready\" : \"unresolved\");\n if (sharedConfig.context) {\n id = `${sharedConfig.context.id}${sharedConfig.context.count++}`;\n let v;\n if (options.ssrLoadFrom === \"initial\") initP = options.initialValue;else if (sharedConfig.load && (v = sharedConfig.load(id))) initP = v;\n }\n function loadEnd(p, v, error, key) {\n if (pr === p) {\n pr = null;\n key !== undefined && (resolved = true);\n if ((p === initP || v === initP) && options.onHydrated) queueMicrotask(() => options.onHydrated(key, {\n value: v\n }));\n initP = NO_INIT;\n if (Transition && p && loadedUnderTransition) {\n Transition.promises.delete(p);\n loadedUnderTransition = false;\n runUpdates(() => {\n Transition.running = true;\n completeLoad(v, error);\n }, false);\n } else completeLoad(v, error);\n }\n return v;\n }\n function completeLoad(v, err) {\n runUpdates(() => {\n if (err === undefined) setValue(() => v);\n setState(err !== undefined ? \"errored\" : resolved ? \"ready\" : \"unresolved\");\n setError(err);\n for (const c of contexts.keys()) c.decrement();\n contexts.clear();\n }, false);\n }\n function read() {\n const c = SuspenseContext && useContext(SuspenseContext),\n v = value(),\n err = error();\n if (err !== undefined && !pr) throw err;\n if (Listener && !Listener.user && c) {\n createComputed(() => {\n track();\n if (pr) {\n if (c.resolved && Transition && loadedUnderTransition) Transition.promises.add(pr);else if (!contexts.has(c)) {\n c.increment();\n contexts.add(c);\n }\n }\n });\n }\n return v;\n }\n function load(refetching = true) {\n if (refetching !== false && scheduled) return;\n scheduled = false;\n const lookup = dynamic ? dynamic() : source;\n loadedUnderTransition = Transition && Transition.running;\n if (lookup == null || lookup === false) {\n loadEnd(pr, untrack(value));\n return;\n }\n if (Transition && pr) Transition.promises.delete(pr);\n const p = initP !== NO_INIT ? initP : untrack(() => fetcher(lookup, {\n value: value(),\n refetching\n }));\n if (!isPromise(p)) {\n loadEnd(pr, p, undefined, lookup);\n return p;\n }\n pr = p;\n if (\"value\" in p) {\n if (p.status === \"success\") loadEnd(pr, p.value, undefined, lookup);else loadEnd(pr, undefined, undefined, lookup);\n return p;\n }\n scheduled = true;\n queueMicrotask(() => scheduled = false);\n runUpdates(() => {\n setState(resolved ? \"refreshing\" : \"pending\");\n trigger();\n }, false);\n return p.then(v => loadEnd(p, v, undefined, lookup), e => loadEnd(p, undefined, castError(e), lookup));\n }\n Object.defineProperties(read, {\n state: {\n get: () => state()\n },\n error: {\n get: () => error()\n },\n loading: {\n get() {\n const s = state();\n return s === \"pending\" || s === \"refreshing\";\n }\n },\n latest: {\n get() {\n if (!resolved) return read();\n const err = error();\n if (err && !pr) throw err;\n return value();\n }\n }\n });\n if (dynamic) createComputed(() => load(false));else load(false);\n return [read, {\n refetch: load,\n mutate: setValue\n }];\n}\nfunction createDeferred(source, options) {\n let t,\n timeout = options ? options.timeoutMs : undefined;\n const node = createComputation(() => {\n if (!t || !t.fn) t = requestCallback(() => setDeferred(() => node.value), timeout !== undefined ? {\n timeout\n } : undefined);\n return source();\n }, undefined, true);\n const [deferred, setDeferred] = createSignal(Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value, options);\n updateComputation(node);\n setDeferred(() => Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value);\n return deferred;\n}\nfunction createSelector(source, fn = equalFn, options) {\n const subs = new Map();\n const node = createComputation(p => {\n const v = source();\n for (const [key, val] of subs.entries()) if (fn(key, v) !== fn(key, p)) {\n for (const c of val.values()) {\n c.state = STALE;\n if (c.pure) Updates.push(c);else Effects.push(c);\n }\n }\n return v;\n }, undefined, true, STALE);\n updateComputation(node);\n return key => {\n const listener = Listener;\n if (listener) {\n let l;\n if (l = subs.get(key)) l.add(listener);else subs.set(key, l = new Set([listener]));\n onCleanup(() => {\n l.delete(listener);\n !l.size && subs.delete(key);\n });\n }\n return fn(key, Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value);\n };\n}\nfunction batch(fn) {\n return runUpdates(fn, false);\n}\nfunction untrack(fn) {\n if (!ExternalSourceConfig && Listener === null) return fn();\n const listener = Listener;\n Listener = null;\n try {\n if (ExternalSourceConfig) return ExternalSourceConfig.untrack(fn);\n return fn();\n } finally {\n Listener = listener;\n }\n}\nfunction on(deps, fn, options) {\n const isArray = Array.isArray(deps);\n let prevInput;\n let defer = options && options.defer;\n return prevValue => {\n let input;\n if (isArray) {\n input = Array(deps.length);\n for (let i = 0; i < deps.length; i++) input[i] = deps[i]();\n } else input = deps();\n if (defer) {\n defer = false;\n return prevValue;\n }\n const result = untrack(() => fn(input, prevInput, prevValue));\n prevInput = input;\n return result;\n };\n}\nfunction onMount(fn) {\n createEffect(() => untrack(fn));\n}\nfunction onCleanup(fn) {\n if (Owner === null) ;else if (Owner.cleanups === null) Owner.cleanups = [fn];else Owner.cleanups.push(fn);\n return fn;\n}\nfunction catchError(fn, handler) {\n ERROR || (ERROR = Symbol(\"error\"));\n Owner = createComputation(undefined, undefined, true);\n Owner.context = {\n ...Owner.context,\n [ERROR]: [handler]\n };\n if (Transition && Transition.running) Transition.sources.add(Owner);\n try {\n return fn();\n } catch (err) {\n handleError(err);\n } finally {\n Owner = Owner.owner;\n }\n}\nfunction getListener() {\n return Listener;\n}\nfunction getOwner() {\n return Owner;\n}\nfunction runWithOwner(o, fn) {\n const prev = Owner;\n const prevListener = Listener;\n Owner = o;\n Listener = null;\n try {\n return runUpdates(fn, true);\n } catch (err) {\n handleError(err);\n } finally {\n Owner = prev;\n Listener = prevListener;\n }\n}\nfunction enableScheduling(scheduler = requestCallback) {\n Scheduler = scheduler;\n}\nfunction startTransition(fn) {\n if (Transition && Transition.running) {\n fn();\n return Transition.done;\n }\n const l = Listener;\n const o = Owner;\n return Promise.resolve().then(() => {\n Listener = l;\n Owner = o;\n let t;\n if (Scheduler || SuspenseContext) {\n t = Transition || (Transition = {\n sources: new Set(),\n effects: [],\n promises: new Set(),\n disposed: new Set(),\n queue: new Set(),\n running: true\n });\n t.done || (t.done = new Promise(res => t.resolve = res));\n t.running = true;\n }\n runUpdates(fn, false);\n Listener = Owner = null;\n return t ? t.done : undefined;\n });\n}\nconst [transPending, setTransPending] = /*@__PURE__*/createSignal(false);\nfunction useTransition() {\n return [transPending, startTransition];\n}\nfunction resumeEffects(e) {\n Effects.push.apply(Effects, e);\n e.length = 0;\n}\nfunction createContext(defaultValue, options) {\n const id = Symbol(\"context\");\n return {\n id,\n Provider: createProvider(id),\n defaultValue\n };\n}\nfunction useContext(context) {\n return Owner && Owner.context && Owner.context[context.id] !== undefined ? Owner.context[context.id] : context.defaultValue;\n}\nfunction children(fn) {\n const children = createMemo(fn);\n const memo = createMemo(() => resolveChildren(children()));\n memo.toArray = () => {\n const c = memo();\n return Array.isArray(c) ? c : c != null ? [c] : [];\n };\n return memo;\n}\nlet SuspenseContext;\nfunction getSuspenseContext() {\n return SuspenseContext || (SuspenseContext = createContext());\n}\nfunction enableExternalSource(factory, untrack = fn => fn()) {\n if (ExternalSourceConfig) {\n const {\n factory: oldFactory,\n untrack: oldUntrack\n } = ExternalSourceConfig;\n ExternalSourceConfig = {\n factory: (fn, trigger) => {\n const oldSource = oldFactory(fn, trigger);\n const source = factory(x => oldSource.track(x), trigger);\n return {\n track: x => source.track(x),\n dispose() {\n source.dispose();\n oldSource.dispose();\n }\n };\n },\n untrack: fn => oldUntrack(() => untrack(fn))\n };\n } else {\n ExternalSourceConfig = {\n factory,\n untrack\n };\n }\n}\nfunction readSignal() {\n const runningTransition = Transition && Transition.running;\n if (this.sources && (runningTransition ? this.tState : this.state)) {\n if ((runningTransition ? this.tState : this.state) === STALE) updateComputation(this);else {\n const updates = Updates;\n Updates = null;\n runUpdates(() => lookUpstream(this), false);\n Updates = updates;\n }\n }\n if (Listener) {\n const sSlot = this.observers ? this.observers.length : 0;\n if (!Listener.sources) {\n Listener.sources = [this];\n Listener.sourceSlots = [sSlot];\n } else {\n Listener.sources.push(this);\n Listener.sourceSlots.push(sSlot);\n }\n if (!this.observers) {\n this.observers = [Listener];\n this.observerSlots = [Listener.sources.length - 1];\n } else {\n this.observers.push(Listener);\n this.observerSlots.push(Listener.sources.length - 1);\n }\n }\n if (runningTransition && Transition.sources.has(this)) return this.tValue;\n return this.value;\n}\nfunction writeSignal(node, value, isComp) {\n let current = Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value;\n if (!node.comparator || !node.comparator(current, value)) {\n if (Transition) {\n const TransitionRunning = Transition.running;\n if (TransitionRunning || !isComp && Transition.sources.has(node)) {\n Transition.sources.add(node);\n node.tValue = value;\n }\n if (!TransitionRunning) node.value = value;\n } else node.value = value;\n if (node.observers && node.observers.length) {\n runUpdates(() => {\n for (let i = 0; i < node.observers.length; i += 1) {\n const o = node.observers[i];\n const TransitionRunning = Transition && Transition.running;\n if (TransitionRunning && Transition.disposed.has(o)) continue;\n if (TransitionRunning ? !o.tState : !o.state) {\n if (o.pure) Updates.push(o);else Effects.push(o);\n if (o.observers) markDownstream(o);\n }\n if (!TransitionRunning) o.state = STALE;else o.tState = STALE;\n }\n if (Updates.length > 10e5) {\n Updates = [];\n if (false) ;\n throw new Error();\n }\n }, false);\n }\n }\n return value;\n}\nfunction updateComputation(node) {\n if (!node.fn) return;\n cleanNode(node);\n const time = ExecCount;\n runComputation(node, Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value, time);\n if (Transition && !Transition.running && Transition.sources.has(node)) {\n queueMicrotask(() => {\n runUpdates(() => {\n Transition && (Transition.running = true);\n Listener = Owner = node;\n runComputation(node, node.tValue, time);\n Listener = Owner = null;\n }, false);\n });\n }\n}\nfunction runComputation(node, value, time) {\n let nextValue;\n const owner = Owner,\n listener = Listener;\n Listener = Owner = node;\n try {\n nextValue = node.fn(value);\n } catch (err) {\n if (node.pure) {\n if (Transition && Transition.running) {\n node.tState = STALE;\n node.tOwned && node.tOwned.forEach(cleanNode);\n node.tOwned = undefined;\n } else {\n node.state = STALE;\n node.owned && node.owned.forEach(cleanNode);\n node.owned = null;\n }\n }\n node.updatedAt = time + 1;\n return handleError(err);\n } finally {\n Listener = listener;\n Owner = owner;\n }\n if (!node.updatedAt || node.updatedAt <= time) {\n if (node.updatedAt != null && \"observers\" in node) {\n writeSignal(node, nextValue, true);\n } else if (Transition && Transition.running && node.pure) {\n Transition.sources.add(node);\n node.tValue = nextValue;\n } else node.value = nextValue;\n node.updatedAt = time;\n }\n}\nfunction createComputation(fn, init, pure, state = STALE, options) {\n const c = {\n fn,\n state: state,\n updatedAt: null,\n owned: null,\n sources: null,\n sourceSlots: null,\n cleanups: null,\n value: init,\n owner: Owner,\n context: Owner ? Owner.context : null,\n pure\n };\n if (Transition && Transition.running) {\n c.state = 0;\n c.tState = state;\n }\n if (Owner === null) ;else if (Owner !== UNOWNED) {\n if (Transition && Transition.running && Owner.pure) {\n if (!Owner.tOwned) Owner.tOwned = [c];else Owner.tOwned.push(c);\n } else {\n if (!Owner.owned) Owner.owned = [c];else Owner.owned.push(c);\n }\n }\n if (ExternalSourceConfig && c.fn) {\n const [track, trigger] = createSignal(undefined, {\n equals: false\n });\n const ordinary = ExternalSourceConfig.factory(c.fn, trigger);\n onCleanup(() => ordinary.dispose());\n const triggerInTransition = () => startTransition(trigger).then(() => inTransition.dispose());\n const inTransition = ExternalSourceConfig.factory(c.fn, triggerInTransition);\n c.fn = x => {\n track();\n return Transition && Transition.running ? inTransition.track(x) : ordinary.track(x);\n };\n }\n return c;\n}\nfunction runTop(node) {\n const runningTransition = Transition && Transition.running;\n if ((runningTransition ? node.tState : node.state) === 0) return;\n if ((runningTransition ? node.tState : node.state) === PENDING) return lookUpstream(node);\n if (node.suspense && untrack(node.suspense.inFallback)) return node.suspense.effects.push(node);\n const ancestors = [node];\n while ((node = node.owner) && (!node.updatedAt || node.updatedAt < ExecCount)) {\n if (runningTransition && Transition.disposed.has(node)) return;\n if (runningTransition ? node.tState : node.state) ancestors.push(node);\n }\n for (let i = ancestors.length - 1; i >= 0; i--) {\n node = ancestors[i];\n if (runningTransition) {\n let top = node,\n prev = ancestors[i + 1];\n while ((top = top.owner) && top !== prev) {\n if (Transition.disposed.has(top)) return;\n }\n }\n if ((runningTransition ? node.tState : node.state) === STALE) {\n updateComputation(node);\n } else if ((runningTransition ? node.tState : node.state) === PENDING) {\n const updates = Updates;\n Updates = null;\n runUpdates(() => lookUpstream(node, ancestors[0]), false);\n Updates = updates;\n }\n }\n}\nfunction runUpdates(fn, init) {\n if (Updates) return fn();\n let wait = false;\n if (!init) Updates = [];\n if (Effects) wait = true;else Effects = [];\n ExecCount++;\n try {\n const res = fn();\n completeUpdates(wait);\n return res;\n } catch (err) {\n if (!wait) Effects = null;\n Updates = null;\n handleError(err);\n }\n}\nfunction completeUpdates(wait) {\n if (Updates) {\n if (Scheduler && Transition && Transition.running) scheduleQueue(Updates);else runQueue(Updates);\n Updates = null;\n }\n if (wait) return;\n let res;\n if (Transition) {\n if (!Transition.promises.size && !Transition.queue.size) {\n const sources = Transition.sources;\n const disposed = Transition.disposed;\n Effects.push.apply(Effects, Transition.effects);\n res = Transition.resolve;\n for (const e of Effects) {\n \"tState\" in e && (e.state = e.tState);\n delete e.tState;\n }\n Transition = null;\n runUpdates(() => {\n for (const d of disposed) cleanNode(d);\n for (const v of sources) {\n v.value = v.tValue;\n if (v.owned) {\n for (let i = 0, len = v.owned.length; i < len; i++) cleanNode(v.owned[i]);\n }\n if (v.tOwned) v.owned = v.tOwned;\n delete v.tValue;\n delete v.tOwned;\n v.tState = 0;\n }\n setTransPending(false);\n }, false);\n } else if (Transition.running) {\n Transition.running = false;\n Transition.effects.push.apply(Transition.effects, Effects);\n Effects = null;\n setTransPending(true);\n return;\n }\n }\n const e = Effects;\n Effects = null;\n if (e.length) runUpdates(() => runEffects(e), false);\n if (res) res();\n}\nfunction runQueue(queue) {\n for (let i = 0; i < queue.length; i++) runTop(queue[i]);\n}\nfunction scheduleQueue(queue) {\n for (let i = 0; i < queue.length; i++) {\n const item = queue[i];\n const tasks = Transition.queue;\n if (!tasks.has(item)) {\n tasks.add(item);\n Scheduler(() => {\n tasks.delete(item);\n runUpdates(() => {\n Transition.running = true;\n runTop(item);\n }, false);\n Transition && (Transition.running = false);\n });\n }\n }\n}\nfunction runUserEffects(queue) {\n let i,\n userLength = 0;\n for (i = 0; i < queue.length; i++) {\n const e = queue[i];\n if (!e.user) runTop(e);else queue[userLength++] = e;\n }\n if (sharedConfig.context) {\n if (sharedConfig.count) {\n sharedConfig.effects || (sharedConfig.effects = []);\n sharedConfig.effects.push(...queue.slice(0, userLength));\n return;\n } else if (sharedConfig.effects) {\n queue = [...sharedConfig.effects, ...queue];\n userLength += sharedConfig.effects.length;\n delete sharedConfig.effects;\n }\n setHydrateContext();\n }\n for (i = 0; i < userLength; i++) runTop(queue[i]);\n}\nfunction lookUpstream(node, ignore) {\n const runningTransition = Transition && Transition.running;\n if (runningTransition) node.tState = 0;else node.state = 0;\n for (let i = 0; i < node.sources.length; i += 1) {\n const source = node.sources[i];\n if (source.sources) {\n const state = runningTransition ? source.tState : source.state;\n if (state === STALE) {\n if (source !== ignore && (!source.updatedAt || source.updatedAt < ExecCount)) runTop(source);\n } else if (state === PENDING) lookUpstream(source, ignore);\n }\n }\n}\nfunction markDownstream(node) {\n const runningTransition = Transition && Transition.running;\n for (let i = 0; i < node.observers.length; i += 1) {\n const o = node.observers[i];\n if (runningTransition ? !o.tState : !o.state) {\n if (runningTransition) o.tState = PENDING;else o.state = PENDING;\n if (o.pure) Updates.push(o);else Effects.push(o);\n o.observers && markDownstream(o);\n }\n }\n}\nfunction cleanNode(node) {\n let i;\n if (node.sources) {\n while (node.sources.length) {\n const source = node.sources.pop(),\n index = node.sourceSlots.pop(),\n obs = source.observers;\n if (obs && obs.length) {\n const n = obs.pop(),\n s = source.observerSlots.pop();\n if (index < obs.length) {\n n.sourceSlots[s] = index;\n obs[index] = n;\n source.observerSlots[index] = s;\n }\n }\n }\n }\n if (Transition && Transition.running && node.pure) {\n if (node.tOwned) {\n for (i = node.tOwned.length - 1; i >= 0; i--) cleanNode(node.tOwned[i]);\n delete node.tOwned;\n }\n reset(node, true);\n } else if (node.owned) {\n for (i = node.owned.length - 1; i >= 0; i--) cleanNode(node.owned[i]);\n node.owned = null;\n }\n if (node.cleanups) {\n for (i = node.cleanups.length - 1; i >= 0; i--) node.cleanups[i]();\n node.cleanups = null;\n }\n if (Transition && Transition.running) node.tState = 0;else node.state = 0;\n}\nfunction reset(node, top) {\n if (!top) {\n node.tState = 0;\n Transition.disposed.add(node);\n }\n if (node.owned) {\n for (let i = 0; i < node.owned.length; i++) reset(node.owned[i]);\n }\n}\nfunction castError(err) {\n if (err instanceof Error) return err;\n return new Error(typeof err === \"string\" ? err : \"Unknown error\", {\n cause: err\n });\n}\nfunction runErrors(err, fns, owner) {\n try {\n for (const f of fns) f(err);\n } catch (e) {\n handleError(e, owner && owner.owner || null);\n }\n}\nfunction handleError(err, owner = Owner) {\n const fns = ERROR && owner && owner.context && owner.context[ERROR];\n const error = castError(err);\n if (!fns) {\n console.error(\"solid error\", error);\n return;\n }\n if (Effects) Effects.push({\n fn() {\n runErrors(error, fns, owner);\n },\n state: STALE\n });else runErrors(error, fns, owner);\n}\nfunction resolveChildren(children) {\n if (typeof children === \"function\" && !children.length) return resolveChildren(children());\n if (Array.isArray(children)) {\n const results = [];\n for (let i = 0; i < children.length; i++) {\n const result = resolveChildren(children[i]);\n Array.isArray(result) ? results.push.apply(results, result) : results.push(result);\n }\n return results;\n }\n return children;\n}\nfunction createProvider(id, options) {\n return function provider(props) {\n let res;\n createRenderEffect(() => res = untrack(() => {\n Owner.context = {\n ...Owner.context,\n [id]: props.value\n };\n return children(() => props.children);\n }), undefined);\n return res;\n };\n}\nfunction onError(fn) {\n ERROR || (ERROR = Symbol(\"error\"));\n if (Owner === null) ;else if (Owner.context === null || !Owner.context[ERROR]) {\n Owner.context = {\n ...Owner.context,\n [ERROR]: [fn]\n };\n mutateContext(Owner, ERROR, [fn]);\n } else Owner.context[ERROR].push(fn);\n}\nfunction mutateContext(o, key, value) {\n if (o.owned) {\n for (let i = 0; i < o.owned.length; i++) {\n if (o.owned[i].context === o.context) mutateContext(o.owned[i], key, value);\n if (!o.owned[i].context) {\n o.owned[i].context = o.context;\n mutateContext(o.owned[i], key, value);\n } else if (!o.owned[i].context[key]) {\n o.owned[i].context[key] = value;\n mutateContext(o.owned[i], key, value);\n }\n }\n }\n}\n\nfunction observable(input) {\n return {\n subscribe(observer) {\n if (!(observer instanceof Object) || observer == null) {\n throw new TypeError(\"Expected the observer to be an object.\");\n }\n const handler = typeof observer === \"function\" ? observer : observer.next && observer.next.bind(observer);\n if (!handler) {\n return {\n unsubscribe() {}\n };\n }\n const dispose = createRoot(disposer => {\n createEffect(() => {\n const v = input();\n untrack(() => handler(v));\n });\n return disposer;\n });\n if (getOwner()) onCleanup(dispose);\n return {\n unsubscribe() {\n dispose();\n }\n };\n },\n [Symbol.observable || \"@@observable\"]() {\n return this;\n }\n };\n}\nfunction from(producer) {\n const [s, set] = createSignal(undefined, {\n equals: false\n });\n if (\"subscribe\" in producer) {\n const unsub = producer.subscribe(v => set(() => v));\n onCleanup(() => \"unsubscribe\" in unsub ? unsub.unsubscribe() : unsub());\n } else {\n const clean = producer(set);\n onCleanup(clean);\n }\n return s;\n}\n\nconst FALLBACK = Symbol(\"fallback\");\nfunction dispose(d) {\n for (let i = 0; i < d.length; i++) d[i]();\n}\nfunction mapArray(list, mapFn, options = {}) {\n let items = [],\n mapped = [],\n disposers = [],\n len = 0,\n indexes = mapFn.length > 1 ? [] : null;\n onCleanup(() => dispose(disposers));\n return () => {\n let newItems = list() || [],\n i,\n j;\n newItems[$TRACK];\n return untrack(() => {\n let newLen = newItems.length,\n newIndices,\n newIndicesNext,\n temp,\n tempdisposers,\n tempIndexes,\n start,\n end,\n newEnd,\n item;\n if (newLen === 0) {\n if (len !== 0) {\n dispose(disposers);\n disposers = [];\n items = [];\n mapped = [];\n len = 0;\n indexes && (indexes = []);\n }\n if (options.fallback) {\n items = [FALLBACK];\n mapped[0] = createRoot(disposer => {\n disposers[0] = disposer;\n return options.fallback();\n });\n len = 1;\n }\n }\n else if (len === 0) {\n mapped = new Array(newLen);\n for (j = 0; j < newLen; j++) {\n items[j] = newItems[j];\n mapped[j] = createRoot(mapper);\n }\n len = newLen;\n } else {\n temp = new Array(newLen);\n tempdisposers = new Array(newLen);\n indexes && (tempIndexes = new Array(newLen));\n for (start = 0, end = Math.min(len, newLen); start < end && items[start] === newItems[start]; start++);\n for (end = len - 1, newEnd = newLen - 1; end >= start && newEnd >= start && items[end] === newItems[newEnd]; end--, newEnd--) {\n temp[newEnd] = mapped[end];\n tempdisposers[newEnd] = disposers[end];\n indexes && (tempIndexes[newEnd] = indexes[end]);\n }\n newIndices = new Map();\n newIndicesNext = new Array(newEnd + 1);\n for (j = newEnd; j >= start; j--) {\n item = newItems[j];\n i = newIndices.get(item);\n newIndicesNext[j] = i === undefined ? -1 : i;\n newIndices.set(item, j);\n }\n for (i = start; i <= end; i++) {\n item = items[i];\n j = newIndices.get(item);\n if (j !== undefined && j !== -1) {\n temp[j] = mapped[i];\n tempdisposers[j] = disposers[i];\n indexes && (tempIndexes[j] = indexes[i]);\n j = newIndicesNext[j];\n newIndices.set(item, j);\n } else disposers[i]();\n }\n for (j = start; j < newLen; j++) {\n if (j in temp) {\n mapped[j] = temp[j];\n disposers[j] = tempdisposers[j];\n if (indexes) {\n indexes[j] = tempIndexes[j];\n indexes[j](j);\n }\n } else mapped[j] = createRoot(mapper);\n }\n mapped = mapped.slice(0, len = newLen);\n items = newItems.slice(0);\n }\n return mapped;\n });\n function mapper(disposer) {\n disposers[j] = disposer;\n if (indexes) {\n const [s, set] = createSignal(j);\n indexes[j] = set;\n return mapFn(newItems[j], s);\n }\n return mapFn(newItems[j]);\n }\n };\n}\nfunction indexArray(list, mapFn, options = {}) {\n let items = [],\n mapped = [],\n disposers = [],\n signals = [],\n len = 0,\n i;\n onCleanup(() => dispose(disposers));\n return () => {\n const newItems = list() || [];\n newItems[$TRACK];\n return untrack(() => {\n if (newItems.length === 0) {\n if (len !== 0) {\n dispose(disposers);\n disposers = [];\n items = [];\n mapped = [];\n len = 0;\n signals = [];\n }\n if (options.fallback) {\n items = [FALLBACK];\n mapped[0] = createRoot(disposer => {\n disposers[0] = disposer;\n return options.fallback();\n });\n len = 1;\n }\n return mapped;\n }\n if (items[0] === FALLBACK) {\n disposers[0]();\n disposers = [];\n items = [];\n mapped = [];\n len = 0;\n }\n for (i = 0; i < newItems.length; i++) {\n if (i < items.length && items[i] !== newItems[i]) {\n signals[i](() => newItems[i]);\n } else if (i >= items.length) {\n mapped[i] = createRoot(mapper);\n }\n }\n for (; i < items.length; i++) {\n disposers[i]();\n }\n len = signals.length = disposers.length = newItems.length;\n items = newItems.slice(0);\n return mapped = mapped.slice(0, len);\n });\n function mapper(disposer) {\n disposers[i] = disposer;\n const [s, set] = createSignal(newItems[i]);\n signals[i] = set;\n return mapFn(s, i);\n }\n };\n}\n\nlet hydrationEnabled = false;\nfunction enableHydration() {\n hydrationEnabled = true;\n}\nfunction createComponent(Comp, props) {\n if (hydrationEnabled) {\n if (sharedConfig.context) {\n const c = sharedConfig.context;\n setHydrateContext(nextHydrateContext());\n const r = untrack(() => Comp(props || {}));\n setHydrateContext(c);\n return r;\n }\n }\n return untrack(() => Comp(props || {}));\n}\nfunction trueFn() {\n return true;\n}\nconst propTraps = {\n get(_, property, receiver) {\n if (property === $PROXY) return receiver;\n return _.get(property);\n },\n has(_, property) {\n if (property === $PROXY) return true;\n return _.has(property);\n },\n set: trueFn,\n deleteProperty: trueFn,\n getOwnPropertyDescriptor(_, property) {\n return {\n configurable: true,\n enumerable: true,\n get() {\n return _.get(property);\n },\n set: trueFn,\n deleteProperty: trueFn\n };\n },\n ownKeys(_) {\n return _.keys();\n }\n};\nfunction resolveSource(s) {\n return !(s = typeof s === \"function\" ? s() : s) ? {} : s;\n}\nfunction resolveSources() {\n for (let i = 0, length = this.length; i < length; ++i) {\n const v = this[i]();\n if (v !== undefined) return v;\n }\n}\nfunction mergeProps(...sources) {\n let proxy = false;\n for (let i = 0; i < sources.length; i++) {\n const s = sources[i];\n proxy = proxy || !!s && $PROXY in s;\n sources[i] = typeof s === \"function\" ? (proxy = true, createMemo(s)) : s;\n }\n if (proxy) {\n return new Proxy({\n get(property) {\n for (let i = sources.length - 1; i >= 0; i--) {\n const v = resolveSource(sources[i])[property];\n if (v !== undefined) return v;\n }\n },\n has(property) {\n for (let i = sources.length - 1; i >= 0; i--) {\n if (property in resolveSource(sources[i])) return true;\n }\n return false;\n },\n keys() {\n const keys = [];\n for (let i = 0; i < sources.length; i++) keys.push(...Object.keys(resolveSource(sources[i])));\n return [...new Set(keys)];\n }\n }, propTraps);\n }\n const sourcesMap = {};\n const defined = Object.create(null);\n for (let i = sources.length - 1; i >= 0; i--) {\n const source = sources[i];\n if (!source) continue;\n const sourceKeys = Object.getOwnPropertyNames(source);\n for (let i = sourceKeys.length - 1; i >= 0; i--) {\n const key = sourceKeys[i];\n if (key === \"__proto__\" || key === \"constructor\") continue;\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!defined[key]) {\n defined[key] = desc.get ? {\n enumerable: true,\n configurable: true,\n get: resolveSources.bind(sourcesMap[key] = [desc.get.bind(source)])\n } : desc.value !== undefined ? desc : undefined;\n } else {\n const sources = sourcesMap[key];\n if (sources) {\n if (desc.get) sources.push(desc.get.bind(source));else if (desc.value !== undefined) sources.push(() => desc.value);\n }\n }\n }\n }\n const target = {};\n const definedKeys = Object.keys(defined);\n for (let i = definedKeys.length - 1; i >= 0; i--) {\n const key = definedKeys[i],\n desc = defined[key];\n if (desc && desc.get) Object.defineProperty(target, key, desc);else target[key] = desc ? desc.value : undefined;\n }\n return target;\n}\nfunction splitProps(props, ...keys) {\n if ($PROXY in props) {\n const blocked = new Set(keys.length > 1 ? keys.flat() : keys[0]);\n const res = keys.map(k => {\n return new Proxy({\n get(property) {\n return k.includes(property) ? props[property] : undefined;\n },\n has(property) {\n return k.includes(property) && property in props;\n },\n keys() {\n return k.filter(property => property in props);\n }\n }, propTraps);\n });\n res.push(new Proxy({\n get(property) {\n return blocked.has(property) ? undefined : props[property];\n },\n has(property) {\n return blocked.has(property) ? false : property in props;\n },\n keys() {\n return Object.keys(props).filter(k => !blocked.has(k));\n }\n }, propTraps));\n return res;\n }\n const otherObject = {};\n const objects = keys.map(() => ({}));\n for (const propName of Object.getOwnPropertyNames(props)) {\n const desc = Object.getOwnPropertyDescriptor(props, propName);\n const isDefaultDesc = !desc.get && !desc.set && desc.enumerable && desc.writable && desc.configurable;\n let blocked = false;\n let objectIndex = 0;\n for (const k of keys) {\n if (k.includes(propName)) {\n blocked = true;\n isDefaultDesc ? objects[objectIndex][propName] = desc.value : Object.defineProperty(objects[objectIndex], propName, desc);\n }\n ++objectIndex;\n }\n if (!blocked) {\n isDefaultDesc ? otherObject[propName] = desc.value : Object.defineProperty(otherObject, propName, desc);\n }\n }\n return [...objects, otherObject];\n}\nfunction lazy(fn) {\n let comp;\n let p;\n const wrap = props => {\n const ctx = sharedConfig.context;\n if (ctx) {\n const [s, set] = createSignal();\n sharedConfig.count || (sharedConfig.count = 0);\n sharedConfig.count++;\n (p || (p = fn())).then(mod => {\n setHydrateContext(ctx);\n sharedConfig.count--;\n set(() => mod.default);\n setHydrateContext();\n });\n comp = s;\n } else if (!comp) {\n const [s] = createResource(() => (p || (p = fn())).then(mod => mod.default));\n comp = s;\n }\n let Comp;\n return createMemo(() => (Comp = comp()) && untrack(() => {\n if (false) ;\n if (!ctx) return Comp(props);\n const c = sharedConfig.context;\n setHydrateContext(ctx);\n const r = Comp(props);\n setHydrateContext(c);\n return r;\n }));\n };\n wrap.preload = () => p || ((p = fn()).then(mod => comp = () => mod.default), p);\n return wrap;\n}\nlet counter = 0;\nfunction createUniqueId() {\n const ctx = sharedConfig.context;\n return ctx ? `${ctx.id}${ctx.count++}` : `cl-${counter++}`;\n}\n\nconst narrowedError = name => `Stale read from <${name}>.`;\nfunction For(props) {\n const fallback = \"fallback\" in props && {\n fallback: () => props.fallback\n };\n return createMemo(mapArray(() => props.each, props.children, fallback || undefined));\n}\nfunction Index(props) {\n const fallback = \"fallback\" in props && {\n fallback: () => props.fallback\n };\n return createMemo(indexArray(() => props.each, props.children, fallback || undefined));\n}\nfunction Show(props) {\n const keyed = props.keyed;\n const condition = createMemo(() => props.when, undefined, {\n equals: (a, b) => keyed ? a === b : !a === !b\n });\n return createMemo(() => {\n const c = condition();\n if (c) {\n const child = props.children;\n const fn = typeof child === \"function\" && child.length > 0;\n return fn ? untrack(() => child(keyed ? c : () => {\n if (!untrack(condition)) throw narrowedError(\"Show\");\n return props.when;\n })) : child;\n }\n return props.fallback;\n }, undefined, undefined);\n}\nfunction Switch(props) {\n let keyed = false;\n const equals = (a, b) => (keyed ? a[1] === b[1] : !a[1] === !b[1]) && a[2] === b[2];\n const conditions = children(() => props.children),\n evalConditions = createMemo(() => {\n let conds = conditions();\n if (!Array.isArray(conds)) conds = [conds];\n for (let i = 0; i < conds.length; i++) {\n const c = conds[i].when;\n if (c) {\n keyed = !!conds[i].keyed;\n return [i, c, conds[i]];\n }\n }\n return [-1];\n }, undefined, {\n equals\n });\n return createMemo(() => {\n const [index, when, cond] = evalConditions();\n if (index < 0) return props.fallback;\n const c = cond.children;\n const fn = typeof c === \"function\" && c.length > 0;\n return fn ? untrack(() => c(keyed ? when : () => {\n if (untrack(evalConditions)[0] !== index) throw narrowedError(\"Match\");\n return cond.when;\n })) : c;\n }, undefined, undefined);\n}\nfunction Match(props) {\n return props;\n}\nlet Errors;\nfunction resetErrorBoundaries() {\n Errors && [...Errors].forEach(fn => fn());\n}\nfunction ErrorBoundary(props) {\n let err;\n if (sharedConfig.context && sharedConfig.load) err = sharedConfig.load(sharedConfig.context.id + sharedConfig.context.count);\n const [errored, setErrored] = createSignal(err, undefined);\n Errors || (Errors = new Set());\n Errors.add(setErrored);\n onCleanup(() => Errors.delete(setErrored));\n return createMemo(() => {\n let e;\n if (e = errored()) {\n const f = props.fallback;\n return typeof f === \"function\" && f.length ? untrack(() => f(e, () => setErrored())) : f;\n }\n return catchError(() => props.children, setErrored);\n }, undefined, undefined);\n}\n\nconst suspenseListEquals = (a, b) => a.showContent === b.showContent && a.showFallback === b.showFallback;\nconst SuspenseListContext = createContext();\nfunction SuspenseList(props) {\n let [wrapper, setWrapper] = createSignal(() => ({\n inFallback: false\n })),\n show;\n const listContext = useContext(SuspenseListContext);\n const [registry, setRegistry] = createSignal([]);\n if (listContext) {\n show = listContext.register(createMemo(() => wrapper()().inFallback));\n }\n const resolved = createMemo(prev => {\n const reveal = props.revealOrder,\n tail = props.tail,\n {\n showContent = true,\n showFallback = true\n } = show ? show() : {},\n reg = registry(),\n reverse = reveal === \"backwards\";\n if (reveal === \"together\") {\n const all = reg.every(inFallback => !inFallback());\n const res = reg.map(() => ({\n showContent: all && showContent,\n showFallback\n }));\n res.inFallback = !all;\n return res;\n }\n let stop = false;\n let inFallback = prev.inFallback;\n const res = [];\n for (let i = 0, len = reg.length; i < len; i++) {\n const n = reverse ? len - i - 1 : i,\n s = reg[n]();\n if (!stop && !s) {\n res[n] = {\n showContent,\n showFallback\n };\n } else {\n const next = !stop;\n if (next) inFallback = true;\n res[n] = {\n showContent: next,\n showFallback: !tail || next && tail === \"collapsed\" ? showFallback : false\n };\n stop = true;\n }\n }\n if (!stop) inFallback = false;\n res.inFallback = inFallback;\n return res;\n }, {\n inFallback: false\n });\n setWrapper(() => resolved);\n return createComponent(SuspenseListContext.Provider, {\n value: {\n register: inFallback => {\n let index;\n setRegistry(registry => {\n index = registry.length;\n return [...registry, inFallback];\n });\n return createMemo(() => resolved()[index], undefined, {\n equals: suspenseListEquals\n });\n }\n },\n get children() {\n return props.children;\n }\n });\n}\nfunction Suspense(props) {\n let counter = 0,\n show,\n ctx,\n p,\n flicker,\n error;\n const [inFallback, setFallback] = createSignal(false),\n SuspenseContext = getSuspenseContext(),\n store = {\n increment: () => {\n if (++counter === 1) setFallback(true);\n },\n decrement: () => {\n if (--counter === 0) setFallback(false);\n },\n inFallback,\n effects: [],\n resolved: false\n },\n owner = getOwner();\n if (sharedConfig.context && sharedConfig.load) {\n const key = sharedConfig.context.id + sharedConfig.context.count;\n let ref = sharedConfig.load(key);\n if (ref) {\n if (typeof ref !== \"object\" || ref.status !== \"success\") p = ref;else sharedConfig.gather(key);\n }\n if (p && p !== \"$$f\") {\n const [s, set] = createSignal(undefined, {\n equals: false\n });\n flicker = s;\n p.then(() => {\n if (sharedConfig.done) return set();\n sharedConfig.gather(key);\n setHydrateContext(ctx);\n set();\n setHydrateContext();\n }, err => {\n error = err;\n set();\n });\n }\n }\n const listContext = useContext(SuspenseListContext);\n if (listContext) show = listContext.register(store.inFallback);\n let dispose;\n onCleanup(() => dispose && dispose());\n return createComponent(SuspenseContext.Provider, {\n value: store,\n get children() {\n return createMemo(() => {\n if (error) throw error;\n ctx = sharedConfig.context;\n if (flicker) {\n flicker();\n return flicker = undefined;\n }\n if (ctx && p === \"$$f\") setHydrateContext();\n const rendered = createMemo(() => props.children);\n return createMemo(prev => {\n const inFallback = store.inFallback(),\n {\n showContent = true,\n showFallback = true\n } = show ? show() : {};\n if ((!inFallback || p && p !== \"$$f\") && showContent) {\n store.resolved = true;\n dispose && dispose();\n dispose = ctx = p = undefined;\n resumeEffects(store.effects);\n return rendered();\n }\n if (!showFallback) return;\n if (dispose) return prev;\n return createRoot(disposer => {\n dispose = disposer;\n if (ctx) {\n setHydrateContext({\n id: ctx.id + \"f\",\n count: 0\n });\n ctx = undefined;\n }\n return props.fallback;\n }, owner);\n });\n });\n }\n });\n}\n\nconst DEV = undefined;\n\nexport { $DEVCOMP, $PROXY, $TRACK, DEV, ErrorBoundary, For, Index, Match, Show, Suspense, SuspenseList, Switch, batch, cancelCallback, catchError, children, createComponent, createComputed, createContext, createDeferred, createEffect, createMemo, createReaction, createRenderEffect, createResource, createRoot, createSelector, createSignal, createUniqueId, enableExternalSource, enableHydration, enableScheduling, equalFn, from, getListener, getOwner, indexArray, lazy, mapArray, mergeProps, observable, on, onCleanup, onError, onMount, requestCallback, resetErrorBoundaries, runWithOwner, sharedConfig, splitProps, startTransition, untrack, useContext, useTransition };\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type lang from '../lang';\nimport type langSign from '../langSign';\nimport type {State} from '../config/state';\nimport DEBUG, {MOUNT_CLASS_TO} from '../config/debug';\nimport {HelpCountriesList, HelpCountry, LangPackDifference, LangPackString} from '../layer';\nimport stateStorage from './stateStorage';\nimport App from '../config/app';\nimport rootScope from './rootScope';\nimport {IS_MOBILE} from '../environment/userAgent';\nimport deepEqual from '../helpers/object/deepEqual';\nimport safeAssign from '../helpers/object/safeAssign';\nimport capitalizeFirstLetter from '../helpers/string/capitalizeFirstLetter';\nimport matchUrlProtocol from './richTextProcessor/matchUrlProtocol';\nimport wrapUrl from './richTextProcessor/wrapUrl';\nimport {setDirection} from '../helpers/dom/setInnerHTML';\nimport setBlankToAnchor from './richTextProcessor/setBlankToAnchor';\nimport {createSignal} from 'solid-js';\n\nexport const langPack: {[actionType: string]: LangPackKey} = {\n 'messageActionChatCreate': 'ActionCreateGroup',\n 'messageActionChatCreateYou': 'ActionYouCreateGroup',\n 'messageActionChatEditTitle': 'ActionChangedTitle',\n 'messageActionChatEditPhoto': 'ActionChangedPhoto',\n 'messageActionChatEditVideo': 'ActionChangedVideo',\n 'messageActionChatDeletePhoto': 'ActionRemovedPhoto',\n 'messageActionChatReturn': 'ActionAddUserSelf',\n 'messageActionChatReturnYou': 'ActionAddUserSelfYou',\n 'messageActionChatJoined': 'ActionAddUserSelfMega',\n 'messageActionChatJoinedYou': 'ChannelMegaJoined',\n 'messageActionChatAddUser': 'ActionAddUser',\n 'messageActionChatAddUsers': 'ActionAddUser',\n 'messageActionChatLeave': 'ActionLeftUser',\n 'messageActionChatLeaveYou': 'YouLeft',\n 'messageActionChatDeleteUser': 'ActionKickUser',\n 'messageActionChatJoinedByLink': 'ActionInviteUser',\n 'messageActionPinMessage': 'Chat.Service.Group.UpdatedPinnedMessage',\n 'messageActionContactSignUp': 'Chat.Service.PeerJoinedTelegram',\n 'messageActionChannelCreate': 'ActionCreateChannel',\n 'messageActionChannelEditTitle': 'Chat.Service.Channel.UpdatedTitle',\n 'messageActionChannelEditPhoto': 'Chat.Service.Channel.UpdatedPhoto',\n 'messageActionChannelEditVideo': 'Chat.Service.Channel.UpdatedVideo',\n 'messageActionChannelDeletePhoto': 'Chat.Service.Channel.RemovedPhoto',\n 'messageActionHistoryClear': 'HistoryCleared',\n 'messageActionDiscussionStarted': 'DiscussionStarted',\n 'messageActionGiveawayLaunch': 'BoostingGiveawayJustStarted',\n 'messageActionChannelJoined': 'ChannelJoined',\n\n 'messageActionChannelMigrateFrom': 'ActionMigrateFromGroup',\n\n 'messageActionPhoneCall.video_in_ok': 'ChatList.Service.VideoCall.incoming',\n 'messageActionPhoneCall.video_out_ok': 'ChatList.Service.VideoCall.outgoing',\n 'messageActionPhoneCall.video_missed': 'ChatList.Service.VideoCall.Missed',\n 'messageActionPhoneCall.video_cancelled': 'ChatList.Service.VideoCall.Cancelled',\n 'messageActionPhoneCall.in_ok': 'ChatList.Service.Call.incoming',\n 'messageActionPhoneCall.out_ok': 'ChatList.Service.Call.outgoing',\n 'messageActionPhoneCall.missed': 'ChatList.Service.Call.Missed',\n 'messageActionPhoneCall.cancelled': 'ChatList.Service.Call.Cancelled',\n\n 'messageActionGroupCall.started': 'Chat.Service.VoiceChatStarted.Channel',\n 'messageActionGroupCall.started_by': 'Chat.Service.VoiceChatStarted',\n 'messageActionGroupCall.started_byYou': 'Chat.Service.VoiceChatStartedYou',\n 'messageActionGroupCall.ended': 'Chat.Service.VoiceChatFinished.Channel',\n 'messageActionGroupCall.ended_by': 'Chat.Service.VoiceChatFinished',\n 'messageActionGroupCall.ended_byYou': 'Chat.Service.VoiceChatFinishedYou',\n\n 'messageActionBotAllowed': 'Chat.Service.BotPermissionAllowed'\n};\n\nexport type LangPackKey = /* string | */keyof typeof lang | keyof typeof langSign;\n\nexport type FormatterArgument = string | number | Node | FormatterArgument[];\nexport type FormatterArguments = FormatterArgument[];\n\nexport const UNSUPPORTED_LANG_PACK_KEY: LangPackKey = IS_MOBILE ? 'Message.Unsupported.Mobile' : 'Message.Unsupported.Desktop';\n\nnamespace I18n {\n export const strings: Map<LangPackKey, LangPackString> = new Map();\n export const countriesList: HelpCountry[] = [];\n let pluralRules: Intl.PluralRules;\n\n let cacheLangPackPromise: Promise<LangPackDifference>;\n export let lastRequestedLangCode: string;\n export let lastRequestedNormalizedLangCode: string;\n export let lastAppliedLangCode: string;\n export let requestedServerLanguage = false;\n export let timeFormat: State['settings']['timeFormat'];\n export let isRTL = false;\n\n export const [langCodeNormalized, setLangCodeNormalized] = createSignal<TranslatableLanguageISO>();\n\n export function setRTL(rtl: boolean) {\n isRTL = rtl;\n }\n\n function setLangCode(langCode: string) {\n lastRequestedLangCode = langCode;\n lastRequestedNormalizedLangCode = langCode.split('-')[0];\n setLangCodeNormalized(lastRequestedNormalizedLangCode.split('-')[0] as any);\n }\n\n export function getCacheLangPack(): Promise<LangPackDifference> {\n if(cacheLangPackPromise) return cacheLangPackPromise;\n return cacheLangPackPromise = Promise.all([\n stateStorage.get('langPack') as Promise<LangPackDifference>,\n polyfillPromise\n ]).then(([langPack]) => {\n if(!langPack/* || true */) {\n return loadLocalLangPack();\n } else if(DEBUG && false) {\n return getLangPack(langPack.lang_code);\n }/* else if(langPack.appVersion !== App.langPackVersion) {\n return getLangPack(langPack.lang_code);\n } */\n\n if(!lastRequestedLangCode) {\n setLangCode(langPack.lang_code);\n }\n\n applyLangPack(langPack);\n return langPack;\n }).finally(() => {\n cacheLangPackPromise = undefined;\n });\n }\n\n function updateAmPm() {\n if(timeFormat === 'h12') {\n try {\n const dateTimeFormat = getDateTimeFormat({hour: 'numeric', minute: 'numeric', hour12: true});\n const date = new Date();\n date.setHours(0);\n const amText = dateTimeFormat.format(date);\n amPmCache.am = amText.split(/\\s/)[1];\n date.setHours(12);\n const pmText = dateTimeFormat.format(date);\n amPmCache.pm = pmText.split(/\\s/)[1];\n } catch(err) {\n console.error('cannot get am/pm', err);\n amPmCache = {am: 'AM', pm: 'PM'};\n }\n }\n }\n\n export function setTimeFormat(\n format: State['settings']['timeFormat'],\n haveToUpdate = !!timeFormat && timeFormat !== format\n ) {\n timeFormat = format;\n\n updateAmPm();\n\n if(haveToUpdate) {\n cachedDateTimeFormats.clear();\n const elements = Array.from(document.querySelectorAll(`.i18n`)) as HTMLElement[];\n elements.forEach((element) => {\n const instance = weakMap.get(element);\n\n if(instance instanceof IntlDateElement) {\n instance.update();\n }\n });\n }\n }\n\n export function loadLocalLangPack() {\n const defaultCode = App.langPackCode;\n setLangCode(defaultCode);\n return Promise.all([\n import('../lang'),\n import('../langSign'),\n import('../countries')\n ]).then(([lang, langSign, countries]) => {\n const strings: LangPackString[] = [];\n formatLocalStrings(lang.default, strings);\n formatLocalStrings(langSign.default, strings);\n\n const langPack: LangPackDifference = {\n _: 'langPackDifference',\n from_version: 0,\n lang_code: defaultCode,\n strings,\n version: 0,\n local: true,\n countries: countries.default\n };\n return saveLangPack(langPack);\n });\n }\n\n export function loadLangPack(langCode: string, web?: boolean) {\n web = true;\n requestedServerLanguage = true;\n const managers = rootScope.managers;\n return Promise.all([\n managers.apiManager.invokeApiCacheable('langpack.getLangPack', {\n lang_code: langCode,\n lang_pack: web ? 'web' : App.langPack\n }),\n !web && managers.apiManager.invokeApiCacheable('langpack.getLangPack', {\n lang_code: langCode,\n lang_pack: 'android'\n }),\n import('../lang'),\n import('../langSign'),\n managers.apiManager.invokeApiCacheable('help.getCountriesList', {\n lang_code: langCode,\n hash: 0\n }) as Promise<HelpCountriesList.helpCountriesList>,\n polyfillPromise\n ]);\n }\n\n export function getStrings(langCode: string, strings: string[]) {\n return rootScope.managers.apiManager.invokeApi('langpack.getStrings', {\n lang_pack: App.langPack,\n lang_code: langCode,\n keys: strings\n });\n }\n\n export function formatLocalStrings(strings: any, pushTo: LangPackString[] = []) {\n for(const i in strings) {\n // @ts-ignore\n const v = strings[i];\n if(typeof(v) === 'string') {\n pushTo.push({\n _: 'langPackString',\n key: i,\n value: v\n });\n } else {\n pushTo.push({\n _: 'langPackStringPluralized',\n key: i,\n ...v\n });\n }\n }\n\n return pushTo;\n }\n\n export function getLangPack(langCode: string, web?: boolean) {\n setLangCode(langCode);\n return loadLangPack(langCode, web).then(([langPack1, langPack2, localLangPack1, localLangPack2, countries, _]) => {\n let strings: LangPackString[] = [];\n\n [localLangPack1, localLangPack2].forEach((l) => {\n formatLocalStrings(l.default as any, strings);\n });\n\n strings = strings.concat(...[langPack1.strings, langPack2.strings].filter(Boolean));\n\n langPack1.strings = strings;\n langPack1.countries = countries;\n return saveLangPack(langPack1);\n });\n }\n\n export function saveLangPack(langPack: LangPackDifference) {\n langPack.appVersion = App.langPackVersion;\n\n return stateStorage.set({langPack}).then(() => {\n applyLangPack(langPack);\n return langPack;\n });\n }\n\n export const polyfillPromise = (function checkIfPolyfillNeeded() {\n if(typeof(Intl) !== 'undefined' && typeof(Intl.PluralRules) !== 'undefined'/* && false */) {\n return Promise.resolve();\n } else {\n return import('./pluralPolyfill').then((_Intl) => {\n (window as any).Intl = Object.assign(typeof(Intl) !== 'undefined' ? Intl : {}, _Intl.default);\n });\n }\n })();\n\n export function applyLangPack(langPack: LangPackDifference) {\n const currentLangCode = lastRequestedLangCode;\n if(langPack.lang_code !== currentLangCode) {\n return;\n }\n\n try {\n pluralRules = new Intl.PluralRules(lastRequestedNormalizedLangCode);\n } catch(err) {\n console.error('pluralRules error', err);\n pluralRules = new Intl.PluralRules(lastRequestedNormalizedLangCode.split('-', 1)[0]);\n }\n\n try {\n pluralRules = new Intl.PluralRules(langPack.lang_code);\n } catch(err) {\n console.error('pluralRules error', err);\n pluralRules = new Intl.PluralRules(langPack.lang_code.split('-', 1)[0]);\n }\n\n strings.clear();\n\n for(const string of langPack.strings) {\n strings.set(string.key as LangPackKey, string);\n }\n\n if(langPack.countries) {\n countriesList.length = 0;\n countriesList.push(...langPack.countries.countries);\n\n langPack.countries.countries.forEach((country) => {\n if(country.name) {\n const langPackKey: any = country.default_name;\n strings.set(langPackKey, {\n _: 'langPackString',\n key: langPackKey,\n value: country.name\n });\n }\n });\n }\n\n if(lastAppliedLangCode !== currentLangCode) {\n if(lastAppliedLangCode && rootScope.myId) {\n rootScope.managers.appReactionsManager.resetAvailableReactions();\n rootScope.managers.appUsersManager.indexMyself();\n rootScope.managers.dialogsStorage.indexMyDialog();\n }\n\n lastAppliedLangCode = currentLangCode;\n cachedDateTimeFormats.clear();\n updateAmPm();\n rootScope.dispatchEvent('language_change', currentLangCode);\n }\n\n const elements = Array.from(document.querySelectorAll(`.i18n`)) as HTMLElement[];\n elements.forEach((element) => {\n const instance = weakMap.get(element);\n\n if(instance) {\n instance.update();\n }\n });\n }\n\n function pushNextArgument(out: ReturnType<typeof superFormatter>, args: FormatterArguments, indexHolder: {i: number}, i?: number) {\n const arg = args[i === undefined ? indexHolder.i++ : i];\n if(Array.isArray(arg)) {\n out.push(...arg as any);\n } else {\n out.push(arg);\n }\n }\n\n export function superFormatter(input: string, args?: FormatterArguments, indexHolder?: {i: number}): Exclude<FormatterArgument, FormatterArgument[]>[] {\n if(!indexHolder) { // set starting index for arguments without order\n indexHolder = {i: 0};\n const indexes = input.match(/(%|un)\\d+/g);\n if(indexes?.length) {\n indexHolder.i = Math.max(...indexes.map((str) => +str.replace(/\\D/g, '')));\n }\n }\n\n const out: ReturnType<typeof superFormatter> = [];\n const regExp = /(\\*\\*|__)(.+?)\\1|(\\n)|(\\[.+?\\]\\(.*?\\))|un\\d|%\\d\\$.|%\\S/g;\n\n let lastIndex = 0;\n input.replace(regExp, (match, p1: any, p2: any, p3: any, p4: string, offset: number, string: string) => {\n // console.table({match, p1, p2, offset, string});\n\n if(offset > lastIndex) {\n out.push(string.slice(lastIndex, offset));\n }\n\n if(p1) {\n // offset += p1.length;\n let element: HTMLElement;\n switch(p1) {\n case '**': {\n element = document.createElement('b');\n break;\n }\n\n case '__': {\n element = document.createElement('i');\n break;\n }\n }\n\n element.append(...superFormatter(p2, args, indexHolder) as any);\n out.push(element);\n } else if(p3) {\n out.push(document.createElement('br'));\n } else if(p4) {\n const idx = p4.lastIndexOf(']');\n const text = p4.slice(1, idx);\n\n const url = p4.slice(idx + 2, p4.length - 1);\n let a: HTMLAnchorElement;\n if(url && matchUrlProtocol(url)) {\n a = document.createElement('a');\n const wrappedUrl = wrapUrl(url);\n a.href = wrappedUrl.url;\n if(wrappedUrl.onclick) a.setAttribute('onclick', wrappedUrl.onclick + '(this)');\n setBlankToAnchor(a);\n } else {\n a = args[indexHolder.i++] as HTMLAnchorElement;\n\n if(a instanceof DocumentFragment) { // right after wrapRichText\n a = a.firstChild as any;\n }\n\n if(typeof(a) !== 'string') {\n a.textContent = ''; // reset content\n }\n }\n\n const formatted = superFormatter(text, args, indexHolder) as any;\n if(typeof(a) === 'string') {\n out.push(...formatted);\n } else {\n a.append(...formatted);\n out.push(a);\n }\n } else if(args) {\n const index = match.replace(/\\D/g, '');\n pushNextArgument(\n out,\n args,\n indexHolder,\n !index || Number.isNaN(+index) ? undefined : Math.min(args.length - 1, +index - 1)\n );\n }\n\n lastIndex = offset + match.length;\n return '';\n });\n\n if(lastIndex !== input.length) {\n out.push(input.slice(lastIndex));\n }\n\n return out;\n }\n\n export function format(key: LangPackKey, plain: true, args?: FormatterArguments): string;\n export function format(key: LangPackKey, plain?: false, args?: FormatterArguments): ReturnType<typeof superFormatter>;\n export function format(key: LangPackKey, plain = false, args?: FormatterArguments): ReturnType<typeof superFormatter> | string {\n const str = strings.get(key);\n let input: string;\n if(str) {\n if(str._ === 'langPackStringPluralized' && args?.length) {\n let v = args[0] as number | string;\n if(typeof(v) === 'string') v = +v.replace(/\\D/g, '');\n const s = pluralRules.select(v);\n // @ts-ignore\n input = str[s + '_value'] || str['other_value'];\n } else if(str._ === 'langPackString') {\n input = str.value;\n } else {\n // input = '[' + key + ']';\n input = key;\n }\n } else {\n // input = '[' + key + ']';\n input = key;\n }\n\n const result = superFormatter(input, args);\n if(plain) { // * let's try a hack now... (don't want to replace []() entity)\n return result.map((item) => item instanceof Node ? item.textContent : item).join('');\n } else {\n return result;\n }\n\n /* if(plain) {\n if(args?.length) {\n const regExp = /un\\d|%\\d\\$.|%./g;\n let i = 0;\n input = input.replace(regExp, (match, offset, string) => {\n return '' + args[i++];\n });\n }\n\n return input;\n } else {\n return superFormatter(input, args);\n } */\n }\n\n export const weakMap: WeakMap<HTMLElement, IntlElementBase<IntlElementBaseOptions>> = new WeakMap();\n\n export type IntlElementBaseOptions = {\n element?: HTMLElement,\n property?: 'innerText' | 'innerHTML' | 'placeholder' | 'textContent',\n };\n\n abstract class IntlElementBase<Options extends IntlElementBaseOptions> {\n public element: IntlElementBaseOptions['element'];\n public property: IntlElementBaseOptions['property'];\n\n constructor(options?: Options) {\n this.element = options?.element || document.createElement('span');\n this.element.classList.add('i18n');\n\n this.property = options?.property;\n\n weakMap.set(this.element, this);\n }\n\n abstract update(options?: Options): void;\n }\n\n export type IntlElementOptions = IntlElementBaseOptions & {\n key?: LangPackKey,\n args?: FormatterArguments\n };\n export class IntlElement extends IntlElementBase<IntlElementOptions> {\n public key: IntlElementOptions['key'];\n public args: IntlElementOptions['args'];\n\n constructor(options: IntlElementOptions = {}) {\n super({...options, property: options.property ?? 'innerHTML'});\n\n if(options?.key) {\n this.update(options);\n }\n }\n\n public update(options?: IntlElementOptions) {\n safeAssign(this, options);\n\n if(this.property === 'innerHTML') {\n this.element.replaceChildren(...format(this.key, false, this.args) as any);\n if(this.args?.length) {\n this.element.normalize();\n }\n } else {\n // @ts-ignore\n const v = this.element[this.property];\n const formatted = format(this.key, true, this.args);\n\n // * hasOwnProperty won't work here\n if(v === undefined) this.element.dataset[this.property] = formatted;\n else (this.element as HTMLInputElement)[this.property] = formatted;\n }\n }\n\n public compareAndUpdate(options?: IntlElementOptions) {\n if(this.key === options.key && deepEqual(this.args, options.args)) {\n return;\n }\n\n return this.update(options);\n }\n }\n\n const cachedDateTimeFormats: Map<string, Intl.DateTimeFormat> = new Map();\n export function getDateTimeFormat(options: Intl.DateTimeFormatOptions = {}) {\n const json = JSON.stringify(options);\n let dateTimeFormat = cachedDateTimeFormats.get(json);\n if(!dateTimeFormat) {\n dateTimeFormat = new Intl.DateTimeFormat(lastRequestedNormalizedLangCode + '-u-hc-' + timeFormat, options);\n cachedDateTimeFormats.set(json, dateTimeFormat);\n }\n\n return dateTimeFormat;\n }\n\n export let amPmCache = {am: 'AM', pm: 'PM'};\n export type IntlDateElementOptions = IntlElementBaseOptions & {\n date?: Date,\n options: Intl.DateTimeFormatOptions\n };\n export class IntlDateElement extends IntlElementBase<IntlDateElementOptions> {\n public date: IntlDateElementOptions['date'];\n public options: IntlDateElementOptions['options'];\n\n constructor(options: IntlDateElementOptions) {\n super({...options, property: options.property ?? 'textContent'});\n setDirection(this.element);\n\n if(options?.date) {\n this.update(options);\n }\n }\n\n public update(options?: IntlDateElementOptions) {\n safeAssign(this, options);\n\n let text: string;\n if(this.options.hour && this.options.minute && Object.keys(this.options).length === 2/* && false */) {\n const hours = this.date.getHours();\n text = ('0' + (timeFormat === 'h12' ? (hours % 12) || 12 : hours)).slice(-2) + ':' + ('0' + this.date.getMinutes()).slice(-2);\n // if(this.options.second) {\n // text += ':' + ('0' + this.date.getSeconds()).slice(-2);\n // }\n\n if(timeFormat === 'h12') {\n text += ' ' + (hours < 12 ? amPmCache.am : amPmCache.pm);\n }\n } else {\n // * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle#adding_an_hour_cycle_via_the_locale_string\n const dateTimeFormat = getDateTimeFormat(this.options);\n text = capitalizeFirstLetter(dateTimeFormat.format(this.date));\n }\n\n (this.element as any)[this.property] = text;\n }\n }\n\n export function i18n(key: LangPackKey, args?: FormatterArguments) {\n return new IntlElement({key, args}).element;\n }\n\n export function i18n_(options: IntlElementOptions) {\n return new IntlElement(options).element;\n }\n\n export function _i18n(element: HTMLElement, key: LangPackKey, args?: FormatterArguments, property?: IntlElementOptions['property']) {\n return new IntlElement({element, key, args, property}).element;\n }\n}\n\nexport {I18n};\nexport default I18n;\n\nconst i18n = I18n.i18n;\nexport {i18n};\n\nconst i18n_ = I18n.i18n_;\nexport {i18n_};\n\nconst _i18n = I18n._i18n;\nexport {_i18n};\n\nexport function joinElementsWith<T extends Node | string | Array<Node | string>>(\n elements: T[],\n joiner: T | string | ((isLast: boolean) => T)\n): T[] {\n const arr = elements.slice(0, 1) as T[];\n for(let i = 1; i < elements.length; ++i) {\n const isLast = (elements.length - 1) === i;\n arr.push(typeof(joiner) === 'function' ? (joiner as any)(isLast) : joiner);\n arr.push(elements[i]);\n }\n\n return arr;\n}\n\n\nexport function join(elements: (Node | string)[], useLast: boolean, plain: true): string;\nexport function join(elements: (Node | string)[], useLast?: boolean, plain?: false): (string | Node)[];\nexport function join(elements: (Node | string)[], useLast: boolean, plain: boolean): string | (string | Node)[];\nexport function join(elements: (Node | string)[], useLast = true, plain?: boolean): string | (string | Node)[] {\n const joined = joinElementsWith(elements, (isLast) => {\n const langPackKey: LangPackKey = isLast && useLast ? 'AutoDownloadSettings.LastDelimeter' : 'AutoDownloadSettings.Delimeter';\n return plain ? I18n.format(langPackKey, true) : i18n(langPackKey);\n });\n\n return plain ? joined.join('') : joined;\n}\n\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.I18n = I18n);\n","export default function isAnyChat(peerId: PeerId) {\n return +peerId < 0;\n}\n","export default function isUser(peerId: PeerId) {\n return +peerId >= 0;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport isAnyChat from '../lib/appManagers/utils/peers/isAnyChat';\nimport isUser from '../lib/appManagers/utils/peers/isUser';\n\nString.prototype.toUserId = function() {\n return (+this).toUserId();\n};\n\nString.prototype.toChatId = function() {\n return (+this).toChatId();\n};\n\nString.prototype.toPeerId = function(isChat?: boolean) {\n return (+this).toPeerId(isChat);\n};\n\nString.prototype.isPeerId = function() {\n return /^[\\d-]/.test(this.toString());\n};\n\n// * don't return just 'this', because Firefox returns empty `Number` class\nNumber.prototype.toUserId = function() {\n return +this;\n};\n\nNumber.prototype.toChatId = function() {\n return Math.abs(this as any);\n};\n\n// * don't return just 'this', because Firefox returns empty `Number` class\nNumber.prototype.toPeerId = function(isChat?: boolean) {\n return isChat === undefined ? +this : (isChat ? -Math.abs(this as number) : +this);\n};\n\nNumber.prototype.isPeerId = function() {\n return true;\n};\n\n[\n ['isUser' as const, isUser],\n ['isAnyChat' as const, isAnyChat]\n].forEach((value) => {\n const newMethod = Array.isArray(value) ? value[0] : value;\n const originMethod = Array.isArray(value) ? value[1] : value;\n // @ts-ignore\n String.prototype[newMethod] = function() {\n // @ts-ignore\n // eslint-disable-next-line no-useless-call\n return originMethod.call(null, this.toString());\n };\n\n // @ts-ignore\n Number.prototype[newMethod] = function() {\n // * don't use just 'this', because Firefox returns empty `Number` class\n // @ts-ignore\n // eslint-disable-next-line no-useless-call\n return originMethod.call(null, +this);\n };\n});\n\ndeclare global {\n interface String {\n toUserId(): UserId;\n toChatId(): ChatId;\n toPeerId(isChat?: boolean): PeerId;\n isPeerId(): this is string;\n\n isUser(): boolean;\n isAnyChat(): boolean;\n }\n\n interface Number {\n toUserId(): UserId;\n toChatId(): ChatId;\n toPeerId(isChat?: boolean): PeerId;\n isPeerId(): this is PeerId;\n\n isUser(): boolean;\n isAnyChat(): boolean;\n }\n}\n\nexport {};\n","export default function bufferConcats(...args: (ArrayBuffer | Uint8Array | number[])[]) {\n const length = args.reduce((acc, v) => acc + ((v as ArrayBuffer).byteLength || (v as Uint8Array).length), 0);\n\n const tmp = new Uint8Array(length);\n\n let lastLength = 0;\n args.forEach((b) => {\n tmp.set(b instanceof ArrayBuffer ? new Uint8Array(b) : b, lastLength);\n lastLength += (b as ArrayBuffer).byteLength || (b as Uint8Array).length;\n });\n\n return tmp/* .buffer */;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport bufferConcats from '../helpers/bytes/bufferConcats';\n\nUint8Array.prototype.concat = function(...args: Array<Uint8Array | ArrayBuffer | number[]>) {\n return bufferConcats(this, ...args);\n};\n\n/* Uint8Array.prototype.toString = function() {\n return String.fromCharCode.apply(null, [...this]);\n}; */\n\nUint8Array.prototype.toJSON = function() {\n return [...this];\n // return {type: 'bytes', value: [...this]};\n};\n\nPromise.prototype.finally = Promise.prototype.finally || function<T>(this: Promise<T>, fn: () => any) {\n const onFinally = (callback: typeof fn) => Promise.resolve(fn()).then(callback);\n return this.then(\n result => onFinally(() => result),\n reason => onFinally(() => Promise.reject(reason))\n );\n};\n\ndeclare global {\n interface Uint8Array {\n concat: (...args: Array<Uint8Array | ArrayBuffer | number[]>) => Uint8Array,\n // toString: () => string,\n toJSON: () => number[],\n // toJSON: () => {type: 'bytes', value: number[]},\n }\n\n interface Promise<T> {\n finally: (onfinally?: () => void) => Promise<T>;\n }\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport deferredPromise, {CancellablePromise} from '../../helpers/cancellablePromise';\nimport {WorkerTaskVoidTemplate} from '../../types';\n\nexport interface ConvertWebPTask extends WorkerTaskVoidTemplate {\n type: 'convertWebp',\n payload: {\n fileName: string,\n bytes: Uint8Array\n }\n};\n\nexport class WebpWorkerController {\n private worker: Worker;\n private convertPromises: {[fileName: string]: CancellablePromise<Uint8Array>} = {};\n\n private init() {\n this.worker = new Worker(new URL('./webp.worker.ts', import.meta.url), {type: 'module'});\n this.worker.addEventListener('message', (e) => {\n const task = e.data as ConvertWebPTask;\n const payload = task.payload;\n\n const promise = this.convertPromises[payload.fileName];\n if(promise) {\n payload.bytes ? promise.resolve(payload.bytes) : promise.reject();\n delete this.convertPromises[payload.fileName];\n }\n });\n }\n\n private postMessage(data: ConvertWebPTask) {\n if(this.init) {\n this.init();\n this.init = null;\n }\n\n this.worker.postMessage(data);\n }\n\n public convert(fileName: string, bytes: Uint8Array) {\n if(this.convertPromises.hasOwnProperty(fileName)) {\n return this.convertPromises[fileName];\n }\n\n const convertPromise = deferredPromise<Uint8Array>();\n\n this.postMessage({type: 'convertWebp', payload: {fileName, bytes}});\n\n return this.convertPromises[fileName] = convertPromise;\n }\n}\n\nconst webpWorkerController = new WebpWorkerController();\nMOUNT_CLASS_TO.webpWorkerController = webpWorkerController;\nexport default webpWorkerController;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport Modes from '../config/modes';\nimport {IS_WORKER} from '../helpers/context';\nimport makeError from '../helpers/makeError';\nimport {WorkerTaskTemplate} from '../types';\nimport MTProtoMessagePort from './mtproto/mtprotoMessagePort';\n// import { stringify } from '../helpers/json';\n\nclass LocalStorage<Storage extends Record<string, any>> {\n private prefix = '';\n private cache: Partial<Storage> = {};\n private useStorage = true;\n\n constructor(/* private preserveKeys: (keyof Storage)[] */) {\n if(Modes.test) {\n this.prefix = 't_';\n }\n }\n\n public get<T extends keyof Storage>(key: T, useCache = true): Storage[T] {\n if(this.cache.hasOwnProperty(key) && useCache) {\n return this.cache[key];\n } else if(this.useStorage) {\n let value: Storage[T];\n try {\n value = localStorage.getItem(this.prefix + (key as string)) as any;\n } catch(err) {\n this.useStorage = false;\n throw makeError('STORAGE_OFFLINE');\n }\n\n if(value !== null) {\n try {\n value = JSON.parse(value);\n } catch(err) {\n // console.error(err);\n }\n } else {\n value = undefined;\n }\n\n return value;\n } else {\n throw makeError('STORAGE_OFFLINE');\n }\n }\n\n public set(obj: Partial<Storage>, onlyLocal = false) {\n let lastError: any;\n for(const key in obj) {\n if(obj.hasOwnProperty(key)) {\n const value = obj[key];\n this.cache[key] = value;\n\n if(!onlyLocal) {\n try {\n if(!this.useStorage) {\n throw makeError('STORAGE_OFFLINE');\n }\n\n const stringified = JSON.stringify(value);\n localStorage.setItem(this.prefix + key, stringified);\n } catch(err) {\n this.useStorage = false;\n lastError = err;\n }\n }\n }\n }\n\n if(lastError) {\n throw lastError;\n }\n }\n\n public delete(key: keyof Storage, saveLocal = false) {\n // ! it is needed here\n key = '' + (key as string);\n\n if(!saveLocal) {\n delete this.cache[key];\n }\n\n // if(this.useStorage) {\n try {\n localStorage.removeItem(this.prefix + (key as string));\n } catch(err) {\n\n }\n // }\n }\n\n /* public clear(preserveKeys: (keyof Storage)[] = this.preserveKeys) {\n // if(this.useStorage) {\n try {\n let obj: Partial<Storage> = {};\n if(preserveKeys) {\n preserveKeys.forEach((key) => {\n const value = this.get(key);\n if(value !== undefined) {\n obj[key] = value;\n }\n });\n }\n\n localStorage.clear();\n\n if(preserveKeys) {\n this.set(obj);\n }\n } catch(err) {\n\n }\n // }\n } */\n\n public clear() {\n const keys: string[] = ['dc', 'server_time_offset', 'xt_instance', 'user_auth', 'state_id', 'k_build'];\n for(let i = 1; i <= 5; ++i) {\n keys.push(`dc${i}_server_salt`);\n keys.push(`dc${i}_auth_key`);\n keys.push(`dc${i}_hash`); // only for WebA\n }\n\n for(const key of keys) {\n this.delete(key, true);\n }\n }\n\n public toggleStorage(enabled: boolean, clearWrite: boolean) {\n this.useStorage = enabled;\n\n if(!clearWrite) {\n return;\n }\n\n if(!enabled) {\n this.clear();\n } else {\n return this.set(this.cache);\n }\n }\n}\n\nexport interface LocalStorageProxyTask extends WorkerTaskTemplate {\n type: 'localStorageProxy',\n payload: {\n type: 'set' | 'get' | 'delete' | 'clear' | 'toggleStorage',\n args: any[]\n }\n};\n\nexport interface LocalStorageProxyTaskResponse extends WorkerTaskTemplate {\n type: 'localStorageProxy',\n payload: any\n};\n\nexport default class LocalStorageController<Storage extends Record<string, any>> {\n private static STORAGES: LocalStorageController<any>[] = [];\n // private log = (...args: any[]) => console.log('[SW LS]', ...args);\n // private log = (...args: any[]) => {};\n\n private storage: LocalStorage<Storage>;\n\n constructor(/* private preserveKeys: (keyof Storage)[] = [] */) {\n LocalStorageController.STORAGES.push(this);\n\n if(!IS_WORKER) {\n this.storage = new LocalStorage(/* preserveKeys */);\n }\n }\n\n private async proxy<T>(type: LocalStorageProxyTask['payload']['type'], ...args: LocalStorageProxyTask['payload']['args']): Promise<T> {\n if(IS_WORKER) {\n const port = MTProtoMessagePort.getInstance<false>();\n return port.invoke('localStorageProxy', {type, args});\n }\n\n args = Array.prototype.slice.call(args);\n\n // @ts-ignore\n return this.storage[type].apply(this.storage, args as any);\n }\n\n public get<T extends keyof Storage>(key: T, useCache?: boolean) {\n return this.proxy<Storage[T]>('get', key, useCache);\n }\n\n public set(obj: Partial<Storage>, onlyLocal?: boolean) {\n return this.proxy<void>('set', obj, onlyLocal);\n }\n\n public delete(key: keyof Storage, saveLocal?: boolean) {\n return this.proxy<void>('delete', key, saveLocal);\n }\n\n public clear(/* preserveKeys?: (keyof Storage)[] */) {\n return this.proxy<void>('clear'/* , preserveKeys */);\n }\n\n public toggleStorage(enabled: boolean, clearWrite: boolean) {\n return this.proxy<void>('toggleStorage', enabled, clearWrite);\n }\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {AppInstance} from './mtproto/singleInstance';\nimport type {UserAuth} from './mtproto/mtproto_config';\nimport type {DcId} from '../types';\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport LocalStorageController from './localStorage';\n\nconst sessionStorage = new LocalStorageController<{\n dc: DcId,\n user_auth: UserAuth,\n state_id: number,\n dc1_auth_key: string,\n dc2_auth_key: string,\n dc3_auth_key: string,\n dc4_auth_key: string,\n dc5_auth_key: string,\n dc1_server_salt: string,\n dc2_server_salt: string,\n dc3_server_salt: string,\n dc4_server_salt: string,\n dc5_server_salt: string,\n auth_key_fingerprint: string, // = dc${App.baseDcId}_auth_key.slice(0, 8)\n server_time_offset: number,\n xt_instance: AppInstance,\n kz_version: 'K' | 'Z',\n tgme_sync: {\n canRedirect: boolean,\n ts: number\n },\n k_build: number\n}>(/* ['kz_version'] */);\nMOUNT_CLASS_TO.appStorage = sessionStorage;\nexport default sessionStorage;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {IS_MOBILE_SAFARI} from '../../environment/userAgent';\n\nexport default function isSwipingBackSafari(e: TouchEvent | MouseEvent) {\n return IS_MOBILE_SAFARI && e instanceof TouchEvent && e.touches[0].clientX < 30;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport {IS_MOBILE_SAFARI} from '../environment/userAgent';\nimport {logger} from '../lib/logger';\nimport blurActiveElement from '../helpers/dom/blurActiveElement';\nimport cancelEvent from '../helpers/dom/cancelEvent';\nimport isSwipingBackSafari from '../helpers/dom/isSwipingBackSafari';\nimport indexOfAndSplice from '../helpers/array/indexOfAndSplice';\n\nexport type NavigationItem = {\n type: 'left' | 'right' | 'im' | 'chat' | 'popup' | 'media' | 'menu' |\n 'esg' | 'multiselect' | 'input-helper' | 'autocomplete-helper' | 'markup' |\n 'global-search' | 'voice' | 'mobile-search' | 'filters' | 'global-search-focus' |\n 'toast' | 'dropdown' | 'forum' | 'stories' | 'stories-focus' | 'topbar-search',\n onPop: (canAnimate: boolean) => boolean | void,\n onEscape?: () => boolean,\n noHistory?: boolean,\n noBlurOnPop?: boolean,\n};\n\nexport class AppNavigationController {\n private navigations: Array<NavigationItem>;\n private id: number;\n private manual: boolean;\n private log: ReturnType<typeof logger>;\n private debug: boolean;\n private currentHash: string; // have to start with # if not empty\n private overriddenHash: string; // have to start with # if not empty\n private isPossibleSwipe: boolean;\n public onHashChange: () => void;\n\n constructor() {\n this.navigations = [];\n this.id = Date.now();\n this.manual = false;\n this.log = logger('NC');\n this.debug = true;\n this.currentHash = window.location.hash;\n this.overriddenHash = '';\n this.isPossibleSwipe = false;\n\n window.addEventListener('popstate', this.onPopState);\n window.addEventListener('keydown', this.onKeyDown, {capture: true, passive: false});\n\n if(IS_MOBILE_SAFARI) {\n const options = {passive: true};\n window.addEventListener('touchstart', this.onTouchStart, options);\n }\n\n history.scrollRestoration = 'manual';\n\n this.pushState(); // * push init state\n }\n\n private onPopState = (e: PopStateEvent) => {\n const hash = window.location.hash;\n const id: number = e.state;\n this.debug && this.log('popstate', e, this.isPossibleSwipe, hash);\n if(hash !== this.currentHash) {\n this.debug && this.log.warn(`hash changed, new=${hash}, current=${this.currentHash}, overridden=${this.overriddenHash}`);\n // fix for returning to wrong hash (e.g. chat -> archive -> chat -> 3x back)\n if(id === this.id && this.overriddenHash && this.overriddenHash !== hash) {\n this.overrideHash(this.overriddenHash);\n } else if(id/* === this.id */ && !this.overriddenHash && hash) {\n this.overrideHash();\n } else {\n this.currentHash = hash;\n this.onHashChange && this.onHashChange();\n // this.replaceState();\n return;\n }\n }\n\n if(id !== this.id/* && !this.navigations.length */) {\n this.pushState();\n\n if(!this.navigations.length) {\n return;\n }\n }\n\n const item = this.navigations.pop();\n if(!item) {\n this.pushState();\n return;\n }\n\n this.manual = !this.isPossibleSwipe;\n this.handleItem(item, this.navigations.length);\n // this.pushState(); // * prevent adding forward arrow\n };\n\n private onKeyDown = (e: KeyboardEvent) => {\n const item = this.navigations[this.navigations.length - 1];\n if(!item) return;\n if(e.key === 'Escape' && (item.onEscape ? item.onEscape() : true)) {\n cancelEvent(e);\n this.back(item.type);\n }\n };\n\n private onTouchStart = (e: TouchEvent) => {\n if(e.touches.length > 1) return;\n this.debug && this.log('touchstart');\n\n if(isSwipingBackSafari(e)) {\n this.isPossibleSwipe = true;\n\n window.addEventListener('touchend', () => {\n setTimeout(() => {\n this.isPossibleSwipe = false;\n }, 100);\n }, {passive: true, once: true});\n }\n\n /* const detach = () => {\n window.removeEventListener('touchend', onTouchEnd);\n window.removeEventListener('touchmove', onTouchMove);\n };\n\n let moved = false;\n const onTouchMove = (e: TouchEvent) => {\n this.debug && this.log('touchmove');\n if(e.touches.length > 1) {\n detach();\n return;\n }\n\n moved = true;\n };\n\n const onTouchEnd = (e: TouchEvent) => {\n this.debug && this.log('touchend');\n if(e.touches.length > 1 || !moved) {\n detach();\n return;\n }\n\n isPossibleSwipe = true;\n doubleRaf().then(() => {\n isPossibleSwipe = false;\n });\n\n detach();\n };\n\n window.addEventListener('touchend', onTouchEnd, options);\n window.addEventListener('touchmove', onTouchMove, options); */\n };\n\n public overrideHash(hash: string = '') {\n if(hash && hash[0] !== '#') hash = '#' + hash;\n else if(hash === '#') hash = '';\n\n if(this.currentHash === hash) {\n return;\n }\n\n this.overriddenHash = this.currentHash = hash;\n this.replaceState();\n this.pushState();\n }\n\n private handleItem(item: NavigationItem, wasIndex = this.navigations.indexOf(item)) {\n const good = item.onPop(!this.manual ? false : undefined);\n this.debug && this.log('popstate, navigation:', item, this.navigations);\n if(good === false) { // insert item on the same place, because .push can have different index if new item has appeared\n this.spliceItems(Math.min(this.navigations.length, wasIndex), 0, item);\n } else if(!item.noBlurOnPop) {\n blurActiveElement(); // no better place for it\n }\n\n this.manual = false;\n }\n\n public findItemByType(type: NavigationItem['type']) {\n for(let i = this.navigations.length - 1; i >= 0; --i) {\n const item = this.navigations[i];\n if(item.type === type) {\n return {item, index: i};\n }\n }\n }\n\n public back(type?: NavigationItem['type']) {\n if(type) {\n const ret = this.findItemByType(type);\n if(ret) {\n this.backByItem(ret.item, ret.index);\n return;\n }\n }\n\n history.back();\n }\n\n public backByItem(item: NavigationItem, index = this.navigations.indexOf(item)) {\n if(index === -1) {\n return;\n }\n\n this.manual = true;\n // ! commented because 'popstate' event will be fired with delay\n // if(index !== (this.navigations.length - 1)) {\n this.navigations.splice(index, 1);\n this.handleItem(item, index);\n // }\n }\n\n private onItemAdded(item: NavigationItem) {\n this.debug && this.log('onItemAdded', item, this.navigations);\n\n if(!item.noHistory) {\n this.pushState();\n }\n }\n\n public pushItem(item: NavigationItem) {\n this.navigations.push(item);\n this.onItemAdded(item);\n }\n\n public unshiftItem(item: NavigationItem) {\n this.navigations.unshift(item);\n this.onItemAdded(item);\n }\n\n public spliceItems(index: number, length: number, ...items: NavigationItem[]) {\n this.navigations.splice(index, length, ...items);\n items.forEach((item) => {\n this.onItemAdded(item);\n });\n }\n\n public pushState() {\n this.debug && this.log('push');\n this.manual = false;\n history.pushState(this.id, '');\n }\n\n public replaceState() {\n this.debug && this.log.warn('replace');\n\n const url = location.origin + location.pathname + location.search + this.overriddenHash;\n history.replaceState(this.id, '', url);\n }\n\n public removeItem(item: NavigationItem) {\n if(!item) {\n return;\n }\n\n indexOfAndSplice(this.navigations, item);\n }\n\n public removeByType(type: NavigationItem['type'], single = false) {\n for(let i = this.navigations.length - 1; i >= 0; --i) {\n const item = this.navigations[i];\n if(item.type === type) {\n this.navigations.splice(i, 1);\n\n if(single) {\n break;\n }\n }\n }\n }\n}\n\nconst appNavigationController = new AppNavigationController();\nMOUNT_CLASS_TO.appNavigationController = appNavigationController;\nexport default appNavigationController;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport appNavigationController from '../../components/appNavigationController';\n\nexport class AppRuntimeManager {\n public reload() {\n try {\n appNavigationController.spliceItems(0, Infinity);\n appNavigationController.overrideHash();\n location.reload();\n } catch(e) {};\n\n // if(window.chrome && chrome.runtime && chrome.runtime.reload) {\n // chrome.runtime.reload();\n // }\n }\n\n public close() {\n try {\n window.close();\n } catch(e) {}\n }\n\n /**\n * Better to call from event\n */\n public focus() {\n // // @ts-ignore\n // if(window.navigator.mozApps && document.hidden) {\n // // Get app instance and launch it to bring app to foreground\n // // @ts-ignore\n // window.navigator.mozApps.getSelf().onsuccess = function() {\n // this.result.launch();\n // };\n // } else {\n // // @ts-ignore\n // if(window.chrome && chrome.app && chrome.app.window) {\n // // @ts-ignore\n // chrome.app.window.current().focus();\n // }\n\n window.focus();\n // }\n }\n}\n\nconst appRuntimeManager = new AppRuntimeManager();\nexport default appRuntimeManager;\n","export default function copy<T>(obj: T): T {\n // in case of premitives\n if(obj === null || typeof(obj) !== 'object') {\n return obj;\n }\n\n // date objects should be\n if(obj instanceof Date) {\n return new Date(obj.getTime()) as any;\n }\n\n // handle Array\n if(Array.isArray(obj)) {\n // @ts-ignore\n const clonedArr: T = obj.map((el) => copy(el)) as any as T;\n return clonedArr;\n }\n\n if(ArrayBuffer.isView(obj)) {\n // @ts-ignore\n return obj.slice();\n }\n\n // lastly, handle objects\n // @ts-ignore\n const clonedObj = new obj.constructor();\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n clonedObj[prop] = copy(obj[prop]);\n }\n }\n return clonedObj;\n}\n","import Modes from '../config/modes';\n\nconst IS_SHARED_WORKER_SUPPORTED = typeof(SharedWorker) !== 'undefined' && !Modes.noSharedWorker/* && false */;\n\nexport default IS_SHARED_WORKER_SUPPORTED;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport IS_TOUCH_SUPPORTED from '../environment/touchSupport';\nimport EventListenerBase from './eventListenerBase';\n\nconst FOCUS_EVENT_NAME = IS_TOUCH_SUPPORTED ? 'touchstart' : 'mousemove';\nconst DO_NOT_IDLE = false;\n\nexport class IdleController extends EventListenerBase<{\n change: (idle: boolean) => void\n}> {\n private _isIdle: boolean;\n\n private focusPromise: Promise<void>;\n private focusResolve: () => void;\n\n constructor() {\n super();\n\n this._isIdle = true;\n this.focusPromise = Promise.resolve();\n this.focusResolve = () => {};\n\n window.addEventListener('blur', () => {\n this.isIdle = true;\n\n window.addEventListener('focus', () => {\n this.isIdle = false;\n }, {once: true});\n });\n\n // * Prevent setting online after reloading page\n window.addEventListener(FOCUS_EVENT_NAME, () => {\n this.isIdle = false;\n }, {once: true, passive: true});\n\n this.addEventListener('change', (idle) => {\n if(idle) {\n this.focusPromise = new Promise((resolve) => {\n this.focusResolve = resolve;\n });\n } else {\n this.focusResolve();\n }\n });\n }\n\n public getFocusPromise() {\n return this.focusPromise;\n }\n\n public get isIdle() {\n return this._isIdle;\n }\n\n public set isIdle(value: boolean) {\n if(this._isIdle === value) {\n return;\n }\n\n if(DO_NOT_IDLE && value) {\n return;\n }\n\n this._isIdle = value;\n this.dispatchEvent('change', value);\n }\n}\n\nconst idleController = new IdleController();\nexport default idleController;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport App from '../../config/app';\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport tabId from '../../config/tabId';\nimport IS_SHARED_WORKER_SUPPORTED from '../../environment/sharedWorkerSupport';\nimport EventListenerBase from '../../helpers/eventListenerBase';\nimport idleController from '../../helpers/idleController';\nimport {logger} from '../logger';\nimport rootScope from '../rootScope';\nimport sessionStorage from '../sessionStorage';\nimport apiManagerProxy from './mtprotoworker';\n\nexport type AppInstance = {\n id: number,\n idle: boolean,\n time: number\n};\n\nexport type InstanceDeactivateReason = 'version' | 'tabs';\n\nconst CHECK_INSTANCE_INTERVAL = 5000;\nconst DEACTIVATE_TIMEOUT = 30000;\nconst MULTIPLE_TABS_THRESHOLD = 20000;\nconst IS_MULTIPLE_TABS_SUPPORTED = IS_SHARED_WORKER_SUPPORTED;\n\nexport class SingleInstance extends EventListenerBase<{\n activated: () => void,\n deactivated: (reason: InstanceDeactivateReason) => void\n}> {\n private instanceId: number;\n private started: boolean;\n private masterInstance: boolean;\n private deactivateTimeout: number;\n private deactivated: InstanceDeactivateReason;\n private log = logger('INSTANCE');\n\n constructor() {\n super(false);\n\n this.log = logger('INSTANCE');\n this.instanceId = tabId;\n }\n\n public get deactivatedReason() {\n return this.deactivated;\n }\n\n public start() {\n this.reset();\n\n if(!this.started/* && !Config.Navigator.mobile && !Config.Modes.packed */) {\n this.started = true;\n\n idleController.addEventListener('change', this.checkInstance);\n setInterval(this.checkInstance, CHECK_INSTANCE_INTERVAL);\n this.checkInstance();\n\n try {\n document.documentElement.addEventListener('beforeunload', this.clearInstance);\n } catch(e) {}\n }\n }\n\n private reset() {\n this.masterInstance = false;\n this.clearDeactivateTimeout();\n this.deactivated = undefined;\n }\n\n private clearInstance = () => {\n if(this.masterInstance && !this.deactivated) {\n this.log.warn('clear master instance');\n sessionStorage.delete('xt_instance');\n }\n };\n\n public activateInstance() {\n if(this.deactivated) {\n this.reset();\n this.checkInstance(false);\n this.dispatchEvent('activated');\n }\n }\n\n private deactivateInstance(reason: InstanceDeactivateReason) {\n if(this.masterInstance || this.deactivated) {\n return;\n }\n\n this.log.warn('deactivate', reason);\n this.clearDeactivateTimeout();\n this.deactivated = reason;\n\n this.dispatchEvent('deactivated', reason);\n }\n\n private clearDeactivateTimeout() {\n if(this.deactivateTimeout) {\n clearTimeout(this.deactivateTimeout);\n this.deactivateTimeout = 0;\n }\n }\n\n private checkInstance = async(idle = idleController.isIdle) => {\n if(this.deactivated) {\n return;\n }\n\n const time = Date.now();\n const newInstance: AppInstance = {\n id: this.instanceId,\n idle,\n time\n };\n\n const [curInstance, build = App.build] = await Promise.all([\n sessionStorage.get('xt_instance', false),\n sessionStorage.get('k_build', false)\n ]);\n\n if(build > App.build) {\n this.masterInstance = false;\n rootScope.managers.networkerFactory.stopAll();\n this.deactivateInstance('version');\n apiManagerProxy.toggleStorages(false, false);\n return;\n } else if(IS_MULTIPLE_TABS_SUPPORTED) {\n sessionStorage.set({xt_instance: newInstance});\n return;\n }\n\n // this.log('check instance', newInstance, curInstance)\n if(!idle ||\n !curInstance ||\n curInstance.id === this.instanceId ||\n curInstance.time < (time - MULTIPLE_TABS_THRESHOLD)) {\n sessionStorage.set({xt_instance: newInstance});\n\n if(!this.masterInstance) {\n this.masterInstance = true;\n rootScope.managers.networkerFactory.startAll();\n this.log.warn('now master instance', newInstance);\n }\n\n this.clearDeactivateTimeout();\n } else if(this.masterInstance) {\n this.masterInstance = false;\n rootScope.managers.networkerFactory.stopAll();\n this.log.warn('now idle instance', newInstance);\n this.deactivateTimeout ||= window.setTimeout(() => this.deactivateInstance('tabs'), DEACTIVATE_TIMEOUT);\n }\n };\n}\n\nconst singleInstance = new SingleInstance();\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.singleInstance = singleInstance);\nexport default singleInstance;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MESSAGE_ID_OFFSET} from '../../../mtproto/mtproto_config';\n\nexport default function clearMessageId(messageId: number, toServer?: boolean) {\n if(messageId === undefined) {\n return;\n }\n\n messageId = +messageId.toFixed(0);\n if(!toServer) {\n return messageId;\n }\n\n return messageId < MESSAGE_ID_OFFSET ? messageId : messageId % MESSAGE_ID_OFFSET;\n // const q = MESSAGE_ID_OFFSET;\n // if(messageId < q) { // id 0 -> mid 0xFFFFFFFF, so 0xFFFFFFFF must convert to 0\n // return messageId;\n // }\n\n // const l = MESSAGE_ID_INCREMENT - 1;\n // const used = messageId & l;\n // if(used !== l) {\n // messageId -= used + 1;\n // }\n\n // return toServer ? (messageId - q) / MESSAGE_ID_INCREMENT : messageId;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport clearMessageId from './clearMessageId';\n\n/**\n * * will ignore outgoing offset\n */\nexport default function getServerMessageId(messageId: number) {\n return clearMessageId(messageId, true);\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport type {PushNotificationObject} from '../serviceWorker/push';\nimport type {ServicePushPingTaskPayload} from '../serviceWorker/serviceMessagePort';\nimport type {NotificationSettings} from '../appManagers/uiNotificationsManager';\nimport type ServiceMessagePort from '../serviceWorker/serviceMessagePort';\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport {logger} from '../logger';\nimport I18n, {LangPackKey} from '../langPack';\nimport {IS_MOBILE} from '../../environment/userAgent';\nimport appRuntimeManager from '../appManagers/appRuntimeManager';\nimport copy from '../../helpers/object/copy';\nimport singleInstance from './singleInstance';\nimport EventListenerBase from '../../helpers/eventListenerBase';\nimport getServerMessageId from '../appManagers/utils/messageId/getServerMessageId';\n\nexport type PushSubscriptionNotifyType = 'init' | 'subscribe' | 'unsubscribe';\nexport type PushSubscriptionNotifyEvent = `push_${PushSubscriptionNotifyType}`;\n\nexport type PushSubscriptionNotify = {\n tokenType: number,\n tokenValue: string\n};\n\nconst PING_PUSH_INTERVAL = 10000;\n\nexport class WebPushApiManager extends EventListenerBase<{\n push_notification_click: (n: PushNotificationObject) => void,\n push_init: (n: PushSubscriptionNotify) => void,\n push_subscribe: (n: PushSubscriptionNotify) => void,\n push_unsubscribe: (n: PushSubscriptionNotify) => void\n}> {\n public isAvailable = true;\n private isPushEnabled = false;\n private localNotificationsAvailable = true;\n private started = false;\n private settings: NotificationSettings & {baseUrl?: string} = {} as any;\n private isAliveTO: any;\n private isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;\n private userVisibleOnly = this.isFirefox ? false : true;\n private log = logger('PUSH-API');\n\n public serviceMessagePort: ServiceMessagePort<true>;\n\n constructor() {\n super(false);\n\n if(!('PushManager' in window) ||\n !('Notification' in window) ||\n !('serviceWorker' in navigator)) {\n this.log.warn('Push messaging is not supported.');\n this.isAvailable = false;\n this.localNotificationsAvailable = false;\n }\n\n if(this.isAvailable && Notification.permission === 'denied') {\n this.log.warn('The user has blocked notifications.');\n }\n }\n\n public start() {\n if(!this.started) {\n this.started = true;\n this.getSubscription();\n this.setUpServiceWorkerChannel();\n }\n }\n\n public setLocalNotificationsDisabled() {\n this.localNotificationsAvailable = false;\n }\n\n public getSubscription() {\n if(!this.isAvailable) {\n return;\n }\n\n navigator.serviceWorker.ready.then((reg) => {\n reg.pushManager.getSubscription().then((subscription) => {\n this.isPushEnabled = !!subscription;\n this.pushSubscriptionNotify('init', subscription);\n }).catch((err) => {\n this.log.error('Error during getSubscription()', err);\n });\n });\n }\n\n public subscribe = () => {\n if(!this.isAvailable) {\n return;\n }\n\n navigator.serviceWorker.ready.then((reg) => {\n reg.pushManager.subscribe({userVisibleOnly: this.userVisibleOnly}).then((subscription) => {\n // The subscription was successful\n this.isPushEnabled = true;\n this.pushSubscriptionNotify('subscribe', subscription);\n }).catch((e) => {\n if(Notification.permission === 'denied') {\n this.log('Permission for Notifications was denied');\n } else {\n this.log('Unable to subscribe to push.', e);\n if(!this.userVisibleOnly) {\n this.userVisibleOnly = true;\n setTimeout(this.subscribe, 0);\n }\n }\n });\n });\n }\n\n public unsubscribe() {\n if(!this.isAvailable) {\n return;\n }\n\n navigator.serviceWorker.ready.then((reg) => {\n reg.pushManager.getSubscription().then((subscription) => {\n this.isPushEnabled = false;\n\n if(subscription) {\n this.pushSubscriptionNotify('unsubscribe', subscription);\n\n setTimeout(() => {\n subscription.unsubscribe().then((successful) => {\n this.isPushEnabled = false;\n }).catch((e) => {\n this.log.error('Unsubscription error: ', e);\n });\n }, 3000);\n }\n }).catch((e) => {\n this.log.error('Error thrown while unsubscribing from ' +\n 'push messaging.', e);\n });\n });\n }\n\n public forceUnsubscribe() {\n if(!this.isAvailable) {\n return;\n }\n\n navigator.serviceWorker.ready.then((reg) => {\n reg.pushManager.getSubscription().then((subscription) => {\n this.log.warn('force unsubscribe', subscription);\n if(!subscription) {\n return;\n }\n\n subscription.unsubscribe().then((successful) => {\n this.log.warn('force unsubscribe successful', successful);\n this.isPushEnabled = false;\n }).catch((e) => {\n this.log.error('Unsubscription error: ', e);\n });\n }).catch((e) => {\n this.log.error('Error thrown while unsubscribing from ' +\n 'push messaging.', e);\n });\n });\n }\n\n public isAliveNotify = () => {\n if(!this.isAvailable || singleInstance.deactivatedReason) {\n return;\n }\n\n this.settings.baseUrl = (location.href || '').replace(/#.*$/, '');\n\n const lang: ServicePushPingTaskPayload['lang'] = {} as any;\n const ACTIONS_LANG_MAP: Record<keyof ServicePushPingTaskPayload['lang'], LangPackKey> = {\n push_action_mute1d: IS_MOBILE ? 'PushNotification.Action.Mute1d.Mobile' : 'PushNotification.Action.Mute1d',\n push_action_settings: IS_MOBILE ? 'PushNotification.Action.Settings.Mobile' : 'PushNotification.Action.Settings',\n push_message_nopreview: 'PushNotification.Message.NoPreview'\n };\n\n for(const action in ACTIONS_LANG_MAP) {\n lang[action as keyof typeof ACTIONS_LANG_MAP] = I18n.format(ACTIONS_LANG_MAP[action as keyof typeof ACTIONS_LANG_MAP], true);\n }\n\n this.serviceMessagePort.invokeVoid('pushPing', {\n localNotifications: this.localNotificationsAvailable,\n lang: lang,\n settings: this.settings\n });\n\n this.isAliveTO = setTimeout(this.isAliveNotify, PING_PUSH_INTERVAL);\n }\n\n public setSettings(newSettings: WebPushApiManager['settings']) {\n this.settings = copy(newSettings);\n clearTimeout(this.isAliveTO);\n this.isAliveNotify();\n }\n\n public hidePushNotifications() {\n if(!this.isAvailable) {\n return;\n }\n\n this.serviceMessagePort.invokeVoid('notificationsClear', undefined);\n }\n\n public setUpServiceWorkerChannel() {\n if(!this.isAvailable) {\n return;\n }\n\n this.serviceMessagePort.addEventListener('pushClick', (payload) => {\n if(singleInstance.deactivatedReason) {\n appRuntimeManager.reload();\n return;\n }\n\n this.dispatchEvent('push_notification_click', payload);\n });\n\n navigator.serviceWorker.ready.then(this.isAliveNotify);\n }\n\n public pushSubscriptionNotify(event: PushSubscriptionNotifyType, subscription?: PushSubscription) {\n if(subscription) {\n const subscriptionObj: PushSubscriptionJSON = subscription.toJSON();\n if(!subscriptionObj ||\n !subscriptionObj.endpoint ||\n !subscriptionObj.keys ||\n !subscriptionObj.keys.p256dh ||\n !subscriptionObj.keys.auth) {\n this.log.warn('Invalid push subscription', subscriptionObj);\n this.unsubscribe();\n this.isAvailable = false;\n this.pushSubscriptionNotify(event);\n return;\n }\n\n this.log.warn('Push', event, subscriptionObj);\n this.dispatchEvent(('push_' + event) as PushSubscriptionNotifyEvent, {\n tokenType: 10,\n tokenValue: JSON.stringify(subscriptionObj)\n });\n } else {\n this.log.warn('Push', event, false);\n this.dispatchEvent(('push_' + event) as PushSubscriptionNotifyEvent, false as any);\n }\n }\n\n public ignorePushByMid(peerId: PeerId, mid: number) {\n if(!this.isAvailable) {\n return;\n }\n\n this.serviceMessagePort.invokeVoid('shownNotification', peerId + '_' + getServerMessageId(mid));\n }\n}\n\nconst webPushApiManager = new WebPushApiManager();\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.webPushApiManager = webPushApiManager);\nexport default webPushApiManager;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nexport default function loadScript(url: string) {\n const script = document.createElement('script');\n const promise = new Promise<HTMLScriptElement>((resolve) => {\n script.onload = script.onerror = () => {\n resolve(script);\n };\n });\n script.src = url;\n document.body.appendChild(script);\n return promise;\n}\n","export default function tsNow(seconds?: true) {\n const t = Date.now();\n return seconds ? t / 1000 | 0 : t;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport App from '../../config/app';\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport Modes from '../../config/modes';\nimport loadScript from '../../helpers/dom/loadScript';\nimport tsNow from '../../helpers/tsNow';\nimport sessionStorage from '../sessionStorage';\n\nexport class TelegramMeWebManager {\n private disabled = /* false && */(Modes.test || !App.domains.includes(location.hostname));\n\n public setAuthorized(canRedirect: boolean) {\n if(this.disabled) {\n return;\n }\n\n return sessionStorage.get('tgme_sync').then((curValue) => {\n const ts = tsNow(true);\n if(\n canRedirect &&\n curValue?.canRedirect === canRedirect &&\n (curValue.ts + 86400) > ts\n ) {\n return;\n }\n\n sessionStorage.set({\n tgme_sync: {\n canRedirect,\n ts\n }\n });\n\n const path = `_websync_?authed=${canRedirect ? '1' : '0'}&version=${encodeURIComponent(App.version + ' ' + App.suffix)}`;\n const urls = [\n '//telegram.me/' + path,\n '//t.me/' + path\n ];\n\n const promises = urls.map((url) => {\n return loadScript(url).then((script) => {\n script.remove();\n });\n });\n\n return Promise.all(promises);\n });\n }\n}\n\nconst telegramMeWebManager = new TelegramMeWebManager();\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.telegramMeWebManager = telegramMeWebManager);\nexport default telegramMeWebManager;\n","import {IS_FIREFOX} from './userAgent';\n\nconst IS_WEBRTC_SUPPORTED = !!(typeof(RTCPeerConnection) !== 'undefined' && !IS_FIREFOX);\n\nexport default IS_WEBRTC_SUPPORTED;\n","import IS_WEBRTC_SUPPORTED from './webrtcSupport';\n\nconst IS_CALL_SUPPORTED = IS_WEBRTC_SUPPORTED;\n\nexport default IS_CALL_SUPPORTED;\n","import {IS_SAFARI} from './userAgent';\n\n/*\n * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to\n * transfer data between WebWorkers and the main thread.\n * https://github.com/mapbox/mapbox-gl-js/issues/8771\n *\n * This should be removed once the underlying Safari issue is fixed.\n */\n\nlet CAN_USE_TRANSFERABLES: boolean;\nif(!IS_SAFARI) CAN_USE_TRANSFERABLES = true;\nelse {\n try {\n const match = navigator.userAgent.match(/Version\\/(.+?) /);\n CAN_USE_TRANSFERABLES = +match[1] >= 14;\n } catch(err) {\n CAN_USE_TRANSFERABLES = false;\n }\n}\n\nexport default CAN_USE_TRANSFERABLES;\n","const IS_CANVAS_FILTER_SUPPORTED = 'filter' in (document.createElement('canvas').getContext('2d') || {});\n\nexport default IS_CANVAS_FILTER_SUPPORTED;\n","const IS_GEOLOCATION_SUPPORTED = !!navigator?.geolocation?.getCurrentPosition && false;\n\nexport default IS_GEOLOCATION_SUPPORTED;\n","import IS_WEBRTC_SUPPORTED from './webrtcSupport';\n\nconst IS_GROUP_CALL_SUPPORTED = IS_WEBRTC_SUPPORTED;\n\nexport default IS_GROUP_CALL_SUPPORTED;\n","const IS_WEBP_SUPPORTED = document.createElement('canvas').toDataURL('image/webp').startsWith('data:image/webp');\n\nexport default IS_WEBP_SUPPORTED;\n","import IS_WEBP_SUPPORTED from './webpSupport';\n\nconst IMAGE_MIME_TYPES_SUPPORTED = new Set([\n 'image/jpeg',\n 'image/png',\n 'image/bmp'\n]);\n\nif(IS_WEBP_SUPPORTED) {\n IMAGE_MIME_TYPES_SUPPORTED.add('image/webp');\n}\n\nconst possible: [string, string][] = [\n ['image/jxl', 'data:image/jxl;base64,/woIAAAMABKIAgC4AF3lEgAAFSqjjBu8nOv58kOHxbSN6wxttW1hSaLIODZJJ3BIEkkaoCUzGM6qJAE='],\n ['image/avif', 'data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A=']\n];\n\nconst promises = possible.map(([mime, data]) => {\n const img = new Image();\n const promise = new Promise<string>((resolve) => {\n img.onload = img.onerror = () => {\n const supported = img.height === 2;\n resolve(supported ? mime : undefined);\n };\n });\n img.src = data;\n return promise;\n});\n\nexport const IMAGE_MIME_TYPES_SUPPORTED_PROMISE = Promise.all(promises).then((mimeTypes) => mimeTypes.filter(Boolean));\n\nexport default IMAGE_MIME_TYPES_SUPPORTED;\n","import {IS_SAFARI, IS_APPLE_MOBILE} from './userAgent';\n\nconst video = document.createElement('video');\nconst IS_WEBM_SUPPORTED = !!video.canPlayType('video/webm') && !IS_SAFARI && !IS_APPLE_MOBILE;\n// mov is not supported in Chrome on macOS\nconst IS_MOV_SUPPORTED = !!video.canPlayType('video/quicktime') || IS_SAFARI || IS_APPLE_MOBILE;\nconst IS_H265_SUPPORTED = !!video.canPlayType('video/mp4; codecs=\"hev1\"');\n\nexport {\n IS_WEBM_SUPPORTED,\n IS_MOV_SUPPORTED,\n IS_H265_SUPPORTED\n};\n","import {IS_MOV_SUPPORTED} from './videoSupport';\n\nexport type VIDEO_MIME_TYPE = 'image/gif' | 'video/mp4' | 'video/webm' | 'video/quicktime';\nconst VIDEO_MIME_TYPES_SUPPORTED: Set<VIDEO_MIME_TYPE> = new Set([\n 'image/gif', // have to display it as video\n 'video/mp4',\n 'video/webm'\n]);\n\nif(IS_MOV_SUPPORTED) {\n VIDEO_MIME_TYPES_SUPPORTED.add('video/quicktime');\n}\n\nexport default VIDEO_MIME_TYPES_SUPPORTED;\n","import IMAGE_MIME_TYPES_SUPPORTED from './imageMimeTypesSupport';\nimport VIDEO_MIME_TYPES_SUPPORTED from './videoMimeTypesSupport';\n\nconst arr = [...IMAGE_MIME_TYPES_SUPPORTED].concat([...VIDEO_MIME_TYPES_SUPPORTED]);\n\nconst MEDIA_MIME_TYPES_SUPPORTED = new Set(arr);\n\nexport default MEDIA_MIME_TYPES_SUPPORTED;\n","import {IS_FIREFOX} from './userAgent';\n\nconst IS_PARALLAX_SUPPORTED = !IS_FIREFOX && false;\n\nexport default IS_PARALLAX_SUPPORTED;\n","const IS_SCREEN_SHARING_SUPPORTED = !!('getDisplayMedia' in (navigator?.mediaDevices || {}));\n\nexport default IS_SCREEN_SHARING_SUPPORTED;\n","const IS_VIBRATE_SUPPORTED = !!navigator?.vibrate;\n\nexport default IS_VIBRATE_SUPPORTED;\n","const audio = document.createElement('audio');\nconst IS_OPUS_SUPPORTED = !!(audio.canPlayType && audio.canPlayType('audio/ogg;').replace(/no/, ''))/* && false */;\n\nexport default IS_OPUS_SUPPORTED;\n","let IS_APPLE_MX = false;\n\ntry {\n // Awesome detect from https://stackoverflow.com/a/65412357\n const ctx = document.createElement('canvas').getContext('webgl');\n const extension = ctx.getExtension('WEBGL_debug_renderer_info');\n const renderer: string = extension && ctx.getParameter(extension.UNMASKED_RENDERER_WEBGL) || '';\n if((renderer.match(/Apple/) && !renderer.match(/Apple GPU/)) ||\n ctx.getSupportedExtensions().indexOf('WEBGL_compressed_texture_s3tc_srgb') === -1) {\n IS_APPLE_MX = true;\n }\n} catch(err) {\n\n}\n\nexport default IS_APPLE_MX;\n","const IS_LIVE_STREAM_SUPPORTED = 'serviceWorker' in navigator;\n\nexport default IS_LIVE_STREAM_SUPPORTED;\n","import IS_CALL_SUPPORTED from './callSupport';\nimport CAN_USE_TRANSFERABLES from './canUseTransferables';\nimport IS_CANVAS_FILTER_SUPPORTED from './canvasFilterSupport';\nimport IS_EMOJI_SUPPORTED from './emojiSupport';\nimport IS_GEOLOCATION_SUPPORTED from './geolocationSupport';\nimport IS_GROUP_CALL_SUPPORTED from './groupCallSupport';\nimport IMAGE_MIME_TYPES_SUPPORTED from './imageMimeTypesSupport';\nimport MEDIA_MIME_TYPES_SUPPORTED from './mediaMimeTypesSupport';\nimport IS_PARALLAX_SUPPORTED from './parallaxSupport';\nimport IS_SCREEN_SHARING_SUPPORTED from './screenSharingSupport';\nimport IS_TOUCH_SUPPORTED from './touchSupport';\nimport IS_VIBRATE_SUPPORTED from './vibrateSupport';\nimport VIDEO_MIME_TYPES_SUPPORTED from './videoMimeTypesSupport';\nimport IS_WEBP_SUPPORTED from './webpSupport';\nimport IS_WEBRTC_SUPPORTED from './webrtcSupport';\nimport * as userAgent from './userAgent';\nimport IS_OPUS_SUPPORTED from './opusSupport';\nimport IS_SHARED_WORKER_SUPPORTED from './sharedWorkerSupport';\nimport IS_APPLE_MX from './appleMx';\nimport IS_LIVE_STREAM_SUPPORTED from './liveStreamSupport';\nimport * as IS_VIDEO_SUPPORTED from './videoSupport';\n\nconst ENVIRONMENT = {\n CAN_USE_TRANSFERABLES,\n IS_APPLE_MX,\n IS_CALL_SUPPORTED,\n IS_CANVAS_FILTER_SUPPORTED,\n IS_EMOJI_SUPPORTED,\n IS_GEOLOCATION_SUPPORTED,\n IS_GROUP_CALL_SUPPORTED,\n IS_PARALLAX_SUPPORTED,\n IS_SCREEN_SHARING_SUPPORTED,\n IS_TOUCH_SUPPORTED,\n ...IS_VIDEO_SUPPORTED,\n IS_VIBRATE_SUPPORTED,\n IS_OPUS_SUPPORTED,\n IS_SHARED_WORKER_SUPPORTED,\n IS_WEBP_SUPPORTED,\n IS_WEBRTC_SUPPORTED,\n IS_LIVE_STREAM_SUPPORTED,\n IMAGE_MIME_TYPES_SUPPORTED,\n MEDIA_MIME_TYPES_SUPPORTED,\n VIDEO_MIME_TYPES_SUPPORTED,\n ...userAgent\n};\n\nexport default ENVIRONMENT;\n","// https://stackoverflow.com/a/61676104\nexport default function getTimeFormat(): 'h12' | 'h23' {\n const t = document.createElement('input');\n t.type = 'time';\n t.value = '15:00';\n t.style.visibility = 'hidden';\n document.body.append(t);\n const offsetWidth = t.offsetWidth;\n t.remove();\n const timeFormat = offsetWidth > 110 ? 'h12' : 'h23';\n // console.log('timeFormat', timeFormat, offsetWidth);\n return timeFormat;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nconst arrays = {\n 8: new Uint8Array(1),\n 16: new Uint16Array(1),\n 32: new Uint32Array(1)\n};\nexport function nextRandomUint(bits: 8 | 16 | 32) {\n const array = arrays[bits];\n crypto.getRandomValues(array);\n return array[0];\n}\n\nexport function randomLong() {\n return '' + nextRandomUint(32) + nextRandomUint(32) % 0xFFFFFF;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {LiteModeKey} from '../helpers/liteMode';\nimport type {AppMediaPlaybackController} from '../components/appMediaPlaybackController';\nimport type {TopPeerType, MyTopPeer} from '../lib/appManagers/appUsersManager';\nimport type {AccountThemes, AutoDownloadSettings, BaseTheme, NotifyPeer, PeerNotifySettings, Theme, ThemeSettings, WallPaper} from '../layer';\nimport type DialogsStorage from '../lib/storages/dialogs';\nimport type FiltersStorage from '../lib/storages/filters';\nimport type {AuthState, Modify} from '../types';\nimport {IS_MOBILE} from '../environment/userAgent';\nimport getTimeFormat from '../helpers/getTimeFormat';\nimport {nextRandomUint} from '../helpers/random';\nimport App from './app';\nimport {MTAppConfig} from '../lib/mtproto/appConfig';\n\nconst STATE_VERSION = App.version;\nconst BUILD = App.build;\n\n// ! DEPRECATED\nexport type Background = {\n type?: 'color' | 'image' | 'default', // ! DEPRECATED\n blur: boolean,\n highlightingColor?: string,\n color?: string,\n slug?: string, // image slug\n intensity?: number, // pattern intensity\n id: string | number, // wallpaper id\n};\n\nexport type AppTheme = Modify<Theme, {\n name: 'day' | 'night' | 'system',\n settings?: Modify<ThemeSettings, {\n highlightingColor: string\n }>\n}>;\n\nexport type AutoDownloadPeerTypeSettings = {\n contacts: boolean,\n private: boolean,\n groups: boolean,\n channels: boolean\n};\n\nexport type State = {\n allDialogsLoaded: DialogsStorage['allDialogsLoaded'],\n pinnedOrders: DialogsStorage['pinnedOrders'],\n // contactsList: UserId[],\n contactsListCachedTime: number,\n updates: Partial<{\n seq: number,\n pts: number,\n date: number\n }>,\n // filters?: FiltersStorage['filters'], // ! DEPRECATED\n filtersArr?: FiltersStorage['filtersArr'],\n maxSeenMsgId: number,\n stateCreatedTime: number,\n recentEmoji: string[],\n recentCustomEmoji: DocId[],\n topPeersCache: {\n [type in TopPeerType]?: {\n peers: MyTopPeer[],\n cachedTime: number\n }\n },\n recentSearch: PeerId[],\n version: typeof STATE_VERSION,\n build: typeof BUILD,\n authState: AuthState,\n hiddenPinnedMessages: {[peerId: PeerId]: number},\n settings: {\n messagesTextSize: number,\n distanceUnit: 'kilometers' | 'miles',\n sendShortcut: 'enter' | 'ctrlEnter',\n animationsEnabled?: boolean, // ! DEPRECATED\n autoDownload: {\n contacts?: boolean, // ! DEPRECATED\n private?: boolean, // ! DEPRECATED\n groups?: boolean, // ! DEPRECATED\n channels?: boolean, // ! DEPRECATED\n photo: AutoDownloadPeerTypeSettings,\n video: AutoDownloadPeerTypeSettings,\n file: AutoDownloadPeerTypeSettings\n },\n autoDownloadNew: AutoDownloadSettings,\n autoPlay?: { // ! DEPRECATED\n gifs: boolean,\n videos: boolean\n },\n stickers: {\n suggest: 'all' | 'installed' | 'none',\n dynamicPackOrder: boolean,\n loop: boolean\n },\n emoji: {\n suggest: boolean,\n big: boolean\n },\n background?: Background, // ! DEPRECATED\n themes: AppTheme[],\n theme: AppTheme['name'],\n notifications: {\n sound: boolean\n },\n nightTheme?: boolean, // ! DEPRECATED\n timeFormat: 'h12' | 'h23',\n liteMode: {[key in LiteModeKey]: boolean},\n savedAsForum: boolean\n },\n playbackParams: ReturnType<AppMediaPlaybackController['getPlaybackParams']>,\n keepSigned: boolean,\n chatContextMenuHintWasShown: boolean,\n hideChatJoinRequests: {[peerId: PeerId]: number},\n stateId: number,\n notifySettings: {[k in Exclude<NotifyPeer['_'], 'notifyPeer'>]?: PeerNotifySettings.peerNotifySettings},\n confirmedWebViews: BotId[],\n seenTooltips: {\n storySound: boolean\n },\n hiddenSimilarChannels: number[],\n appConfig: MTAppConfig,\n accountThemes: AccountThemes.accountThemes,\n translations: {\n peers: {[peerId: PeerId]: string},\n enabledPeers: {[peerId: PeerId]: boolean},\n enabled: boolean,\n showInMenu: boolean,\n doNotTranslate: TranslatableLanguageISO[]\n },\n shownUploadSpeedTimestamp?: number\n};\n\n// const BACKGROUND_DAY_MOBILE: Background = {\n// blur: false,\n// slug: '',\n// color: '#dbddbb,#6ba587,#d5d88d,#88b884',\n// highlightingColor: 'hsla(86.4, 43.846153%, 45.117647%, .4)',\n// intensity: 0,\n// id: '1'\n// };\n\n// const BACKGROUND_NIGHT_MOBILE: Background = {\n// blur: false,\n// slug: '',\n// color: '#0f0f0f',\n// highlightingColor: 'hsla(0, 0%, 3.82353%, 0.4)',\n// intensity: 0,\n// id: '-1'\n// };\n\nexport const DEFAULT_THEME: Theme = {\n _: 'theme',\n access_hash: '',\n id: '',\n settings: [{\n _: 'themeSettings',\n pFlags: {},\n base_theme: {_: 'baseThemeClassic'},\n accent_color: 0x3390ec,\n message_colors: [0x5CA853],\n wallpaper: {\n _: 'wallPaper',\n pFlags: {\n default: true,\n pattern: true\n },\n access_hash: '',\n document: undefined,\n id: '',\n slug: 'pattern',\n settings: {\n _: 'wallPaperSettings',\n pFlags: {},\n intensity: 50,\n background_color: 0xdbddbb,\n second_background_color: 0x6ba587,\n third_background_color: 0xd5d88d,\n fourth_background_color: 0x88b884\n }\n }\n }, {\n _: 'themeSettings',\n pFlags: {},\n base_theme: {_: 'baseThemeNight'},\n accent_color: 0x8774E1,\n message_colors: [0x8774E1],\n wallpaper: {\n _: 'wallPaper',\n pFlags: {\n default: true,\n pattern: true,\n dark: true\n },\n access_hash: '',\n document: undefined,\n id: '',\n slug: 'pattern',\n settings: {\n _: 'wallPaperSettings',\n pFlags: {},\n intensity: -50,\n background_color: 0xfec496,\n second_background_color: 0xdd6cb9,\n third_background_color: 0x962fbf,\n fourth_background_color: 0x4f5bd5\n }\n }\n }],\n slug: '',\n title: '',\n emoticon: '🏠',\n pFlags: {default: true}\n};\n\nconst makeDefaultAppTheme = (\n name: AppTheme['name'],\n baseTheme: BaseTheme['_'],\n highlightingColor: string\n): AppTheme => {\n return {\n ...DEFAULT_THEME,\n name,\n settings: {\n ...DEFAULT_THEME.settings.find((s) => s.base_theme._ === baseTheme),\n highlightingColor\n }\n };\n};\n\nexport const STATE_INIT: State = {\n allDialogsLoaded: {},\n pinnedOrders: {},\n // contactsList: [],\n contactsListCachedTime: 0,\n updates: {},\n filtersArr: [],\n maxSeenMsgId: 0,\n stateCreatedTime: Date.now(),\n recentEmoji: [],\n recentCustomEmoji: [],\n topPeersCache: {},\n recentSearch: [],\n version: STATE_VERSION,\n build: BUILD,\n authState: {\n _: IS_MOBILE ? 'authStateSignIn' : 'authStateSignQr'\n },\n hiddenPinnedMessages: {},\n settings: {\n messagesTextSize: 16,\n distanceUnit: 'kilometers',\n sendShortcut: 'enter',\n autoDownload: {\n photo: {\n contacts: true,\n private: true,\n groups: true,\n channels: true\n },\n video: {\n contacts: true,\n private: true,\n groups: true,\n channels: true\n },\n file: {\n contacts: true,\n private: true,\n groups: true,\n channels: true\n }\n },\n autoDownloadNew: {\n _: 'autoDownloadSettings',\n file_size_max: 3145728,\n pFlags: {\n video_preload_large: true,\n audio_preload_next: true\n },\n photo_size_max: 1048576,\n video_size_max: 15728640,\n video_upload_maxbitrate: 100,\n small_queue_active_operations_max: 0,\n large_queue_active_operations_max: 0\n },\n stickers: {\n suggest: 'all',\n dynamicPackOrder: true,\n loop: true\n },\n emoji: {\n suggest: true,\n big: true\n },\n themes: [\n makeDefaultAppTheme('day', 'baseThemeClassic', 'hsla(86.4, 43.846153%, 45.117647%, .4)'),\n makeDefaultAppTheme('night', 'baseThemeNight', 'hsla(299.142857, 44.166666%, 37.470588%, .4)')\n ],\n theme: 'system',\n notifications: {\n sound: false\n },\n timeFormat: getTimeFormat(),\n liteMode: {\n all: false,\n animations: false,\n chat: false,\n chat_background: false,\n chat_spoilers: false,\n effects: false,\n effects_premiumstickers: false,\n effects_reactions: false,\n effects_emoji: false,\n emoji: false,\n emoji_messages: false,\n emoji_panel: false,\n gif: false,\n stickers: false,\n stickers_chat: false,\n stickers_panel: false,\n video: false\n },\n savedAsForum: false\n },\n playbackParams: {\n volume: 1,\n muted: false,\n playbackRate: 1,\n playbackRates: {\n voice: 1,\n video: 1,\n audio: 1\n },\n loop: false,\n round: false\n },\n keepSigned: true,\n chatContextMenuHintWasShown: false,\n hideChatJoinRequests: {},\n stateId: nextRandomUint(32),\n notifySettings: {},\n confirmedWebViews: [],\n seenTooltips: {\n storySound: false\n },\n hiddenSimilarChannels: [],\n appConfig: {} as any,\n accountThemes: {} as any,\n translations: {\n peers: {},\n enabledPeers: {},\n enabled: true,\n showInMenu: true,\n doNotTranslate: []\n }\n};\n","export default function compareVersion(v1: string, v2: string): number {\n v1 = v1.split(' ', 1)[0];\n v2 = v2.split(' ', 1)[0];\n const s1 = v1.split('.');\n const s2 = v2.split('.');\n\n for(let i = 0; i < s1.length; ++i) {\n const v1 = +s1[i];\n const v2 = +s2[i];\n if(v1 > v2) return 1;\n else if(v1 < v2) return -1;\n }\n\n return 0;\n}\n","export default function isObject<T extends Record<any, any>>(object: any): object is T {\n return typeof(object) === 'object' && object !== null;\n}\n","import copy from './copy';\nimport isObject from './isObject';\n\nexport default function validateInitObject(\n initObject: any,\n currentObject: any,\n onReplace?: (key: string) => void,\n previousKey?: string,\n ignorePaths?: Set<string>,\n path?: string\n) {\n for(const key in initObject) {\n const _path = path ? `${path}.${key}` : key;\n if(ignorePaths?.has(_path)) {\n continue;\n }\n\n if(typeof(currentObject[key]) !== typeof(initObject[key])) {\n currentObject[key] = copy(initObject[key]);\n onReplace?.(previousKey || key);\n } else if(isObject(initObject[key])) {\n validateInitObject(initObject[key], currentObject[key], onReplace, previousKey || key, ignorePaths, _path);\n }\n }\n}\n","import {logger} from '../lib/logger';\nimport dT from './dT';\n\nexport function recordPromise<T extends Promise<any>>(promise: T, description: string, log?: ReturnType<typeof logger> | Console) {\n const perf = performance.now();\n (log || console).warn(dT(), 'start', description);\n promise.then(() => {\n (log || console).warn(dT(), 'end', description, performance.now() - perf);\n });\n return promise;\n}\n\nexport function recordPromiseBound(log: ReturnType<typeof logger> | Console) {\n return (...args: [Parameters<typeof recordPromise>[0], Parameters<typeof recordPromise>[1]]) => {\n return recordPromise(...args, log);\n };\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport App from '../../../../config/app';\nimport DEBUG from '../../../../config/debug';\nimport {AutoDownloadPeerTypeSettings, State, STATE_INIT, Background, AppTheme} from '../../../../config/state';\nimport compareVersion from '../../../../helpers/compareVersion';\nimport copy from '../../../../helpers/object/copy';\nimport validateInitObject from '../../../../helpers/object/validateInitObject';\nimport {UserAuth} from '../../../mtproto/mtproto_config';\nimport rootScope from '../../../rootScope';\nimport stateStorage from '../../../stateStorage';\nimport sessionStorage from '../../../sessionStorage';\nimport {recordPromiseBound} from '../../../../helpers/recordPromise';\n// import RESET_STORAGES_PROMISE from \"../storages/resetStoragesPromise\";\nimport {StoragesResults} from '../storages/loadStorages';\nimport {LogTypes, logger} from '../../../logger';\nimport {WallPaper} from '../../../../layer';\n\nconst REFRESH_EVERY = 24 * 60 * 60 * 1000; // 1 day\n// const REFRESH_EVERY = 1e3;\n// const REFRESH_EVERY_WEEK = 24 * 60 * 60 * 1000 * 7; // 7 days\n\nconst STATE_VERSION = STATE_INIT.version;\nconst BUILD = STATE_INIT.build;\n\nconst ALL_KEYS = Object.keys(STATE_INIT) as any as Array<keyof State>;\n\nconst REFRESH_KEYS: Array<keyof State> = [\n 'contactsListCachedTime',\n 'stateCreatedTime',\n 'maxSeenMsgId',\n 'filtersArr'\n];\n\n// const REFRESH_KEYS_WEEK = ['dialogs', 'allDialogsLoaded', 'updates', 'pinnedOrders'] as any as Array<keyof State>;\n\nasync function loadStateInner() {\n const log = logger('STATE-LOADER', LogTypes.Error);\n\n const totalPerf = performance.now();\n const recordPromise = recordPromiseBound(log);\n\n const promises = ALL_KEYS.map((key) => recordPromise(stateStorage.get(key), 'state ' + key))\n .concat(\n recordPromise(sessionStorage.get('user_auth'), 'auth'),\n recordPromise(sessionStorage.get('state_id'), 'auth'),\n recordPromise(sessionStorage.get('k_build'), 'auth'),\n recordPromise(sessionStorage.get('auth_key_fingerprint'), 'auth'),\n recordPromise(sessionStorage.get(`dc${App.baseDcId}_auth_key`), 'auth')\n )\n .concat( // support old webk format\n recordPromise(stateStorage.get('user_auth'), 'old auth')\n );\n\n const arr = await Promise.all(promises);\n log.warn('promises', performance.now() - totalPerf);\n // await new Promise((resolve) => setTimeout(resolve, 3e3));\n /* const self = this;\n const skipHandleKeys = new Set(['isProxy', 'filters', 'drafts']);\n const getHandler = (path?: string) => {\n return {\n get(target: any, key: any) {\n if(key === 'isProxy') {\n return true;\n }\n\n const prop = target[key];\n\n if(prop !== undefined && !skipHandleKeys.has(key) && !prop.isProxy && typeof(prop) === 'object') {\n target[key] = new Proxy(prop, getHandler(path || key));\n return target[key];\n }\n\n return prop;\n },\n set(target: any, key: any, value: any) {\n console.log('Setting', target, `.${key} to equal`, value, path);\n\n target[key] = value;\n\n // @ts-ignore\n self.pushToState(path || key, path ? self.state[path] : value, false);\n\n return true;\n }\n };\n }; */\n\n // const pushed: {key: keyof State, value: State[keyof State]}[] = [];\n const pushedKeys: (keyof State)[] = [];\n const pushToState = <T extends keyof State>(key: T, value: State[T]) => {\n // appStateManager.pushToState(key, value);\n state[key] = value;\n // pushed.push({key, value});\n pushedKeys.push(key);\n };\n\n const replaceState = (_state: State) => {\n // pushed.length = 0;\n pushedKeys.length = 0;\n state = _state;\n pushedKeys.push(...Object.keys(state) as any as typeof pushedKeys);\n // state = appStateManager.setState(_state);\n // appStateManager.storage.set(state);\n };\n\n // let state: State = appStateManager.setState({} as any);\n let state: State = {} as any;\n\n // ! then can't store false values\n for(let i = 0, length = ALL_KEYS.length; i < length; ++i) {\n const key = ALL_KEYS[i];\n const value = arr[i];\n if(value !== undefined) {\n // @ts-ignore\n state[key] = value;\n } else {\n pushToState(key, copy(STATE_INIT[key]));\n }\n }\n\n arr.splice(0, ALL_KEYS.length);\n\n // * Read auth\n let auth = arr.shift() as UserAuth | number;\n const stateId = arr.shift() as number;\n const sessionBuild = arr.shift() as number;\n const authKeyFingerprint = arr.shift() as string;\n const baseDcAuthKey = arr.shift() as string;\n const shiftedWebKAuth = arr.shift() as UserAuth | number;\n if(!auth && shiftedWebKAuth) { // support old webk auth\n auth = shiftedWebKAuth;\n const keys: string[] = ['dc', 'server_time_offset', 'xt_instance'];\n for(let i = 1; i <= 5; ++i) {\n keys.push(`dc${i}_server_salt`);\n keys.push(`dc${i}_auth_key`);\n }\n\n const values = await Promise.all(keys.map((key) => stateStorage.get(key as any)));\n keys.push('user_auth');\n values.push(typeof(auth) === 'number' || typeof(auth) === 'string' ? {dcID: values[0] || App.baseDcId, date: Date.now() / 1000 | 0, id: auth.toPeerId(false)} as UserAuth : auth);\n\n const obj: any = {};\n keys.forEach((key, idx) => {\n obj[key] = values[idx];\n });\n\n await sessionStorage.set(obj);\n }\n\n /* if(!auth) { // try to read Webogram's session from localStorage\n try {\n const keys = Object.keys(localStorage);\n for(let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n let value: any;\n try {\n value = localStorage.getItem(key);\n value = JSON.parse(value);\n } catch(err) {\n //console.error(err);\n }\n\n sessionStorage.set({\n [key as any]: value\n });\n }\n\n auth = sessionStorage.getFromCache('user_auth');\n } catch(err) {\n this.log.error('localStorage import error', err);\n }\n } */\n\n if(auth) {\n // ! Warning ! DON'T delete this\n state.authState = {_: 'authStateSignedIn'};\n rootScope.dispatchEvent('user_auth', typeof(auth) === 'number' || typeof(auth) === 'string' ?\n {dcID: 0, date: Date.now() / 1000 | 0, id: auth.toPeerId(false)} :\n auth); // * support old version\n }\n\n const resetStorages: Set<keyof StoragesResults> = new Set();\n const resetState = (preserveKeys: (keyof State)[]) => {\n preserveKeys.push('authState', 'stateId');\n const preserve: Map<keyof State, State[keyof State]> = new Map(\n preserveKeys.map((key) => [key, state[key]])\n );\n\n state = copy(STATE_INIT);\n\n preserve.forEach((value, key) => {\n // @ts-ignore\n state[key] = value;\n });\n\n const r: (keyof StoragesResults)[] = ['chats', 'dialogs', 'users'];\n for(const key of r) {\n resetStorages.add(key);\n // this.storagesResults[key as keyof AppStateManager['storagesResults']].length = 0;\n }\n\n replaceState(state);\n };\n\n if(state.stateId !== stateId) {\n if(stateId !== undefined) {\n resetState([]);\n }\n\n await sessionStorage.set({\n state_id: state.stateId\n });\n }\n\n if(baseDcAuthKey) {\n const _authKeyFingerprint = baseDcAuthKey.slice(0, 8);\n if(!authKeyFingerprint) { // * migration, preserve settings\n resetState(['settings']);\n } else if(authKeyFingerprint !== _authKeyFingerprint) {\n resetState([]);\n }\n\n if(authKeyFingerprint !== _authKeyFingerprint) {\n await sessionStorage.set({\n auth_key_fingerprint: _authKeyFingerprint\n });\n }\n }\n\n const time = Date.now();\n if((state.stateCreatedTime + REFRESH_EVERY) < time) {\n if(DEBUG) {\n log('will refresh state', state.stateCreatedTime, time);\n }\n\n const r = (keys: typeof REFRESH_KEYS) => {\n keys.forEach((key) => {\n pushToState(key, copy(STATE_INIT[key]));\n\n // const s = appStateManager.storagesResults[key as keyof AppStateManager['storagesResults']];\n // if(s?.length) {\n // appStateManager.resetStorages.add(key as keyof AppStateManager['storagesResults']);\n // s.length = 0;\n // }\n });\n };\n\n r(REFRESH_KEYS);\n\n /* if((state.stateCreatedTime + REFRESH_EVERY_WEEK) < time) {\n if(DEBUG) {\n this.log('will refresh updates');\n }\n\n r(REFRESH_KEYS_WEEK);\n } */\n }\n\n // state = this.state = new Proxy(state, getHandler());\n\n // * migrate auto download settings\n const autoDownloadSettings = state.settings.autoDownload;\n if(autoDownloadSettings?.private !== undefined) {\n const oldTypes = [\n 'contacts' as const,\n 'private' as const,\n 'groups' as const,\n 'channels' as const\n ];\n\n const mediaTypes = [\n 'photo' as const,\n 'video' as const,\n 'file' as const\n ];\n\n mediaTypes.forEach((mediaType) => {\n const peerTypeSettings: AutoDownloadPeerTypeSettings = autoDownloadSettings[mediaType] = {} as any;\n oldTypes.forEach((peerType) => {\n peerTypeSettings[peerType] = autoDownloadSettings[peerType];\n });\n });\n\n oldTypes.forEach((peerType) => {\n delete autoDownloadSettings[peerType];\n });\n\n pushToState('settings', state.settings);\n }\n\n const SKIP_VALIDATING_PATHS: Set<string> = new Set([\n 'settings.themes'\n ]);\n validateInitObject(STATE_INIT, state, (missingKey) => {\n pushToState(missingKey as keyof State, state[missingKey as keyof State]);\n }, undefined, SKIP_VALIDATING_PATHS);\n\n let newVersion: string, oldVersion: string;\n if(state.version !== STATE_VERSION || state.build !== BUILD/* || true */) {\n // reset filters and dialogs if version is older\n if(state.build < 322) {\n pushToState('allDialogsLoaded', copy(STATE_INIT.allDialogsLoaded));\n pushToState('pinnedOrders', copy(STATE_INIT.pinnedOrders));\n pushToState('filtersArr', copy(STATE_INIT.filtersArr));\n\n resetStorages.add('dialogs');\n }\n\n if(compareVersion(state.version, '1.7.1') === -1) {\n let migrated = false;\n // * migrate backgrounds (March 13, 2022; to version 1.3.0)\n if(compareVersion(state.version, '1.3.0') === -1) {\n migrated = true;\n state.settings.theme = copy(STATE_INIT.settings.theme);\n state.settings.themes = copy(STATE_INIT.settings.themes);\n } else if(compareVersion(state.version, '1.7.1') === -1) { // * migrate backgrounds (January 25th, 2023; to version 1.7.1)\n migrated = true;\n const oldThemes = state.settings.themes as any as Array<{\n name: AppTheme['name'],\n background: Background\n }>;\n\n state.settings.themes = copy(STATE_INIT.settings.themes);\n\n try {\n oldThemes.forEach((oldTheme) => {\n const oldBackground = oldTheme.background;\n if(!oldBackground) {\n return;\n }\n\n const newTheme = state.settings.themes.find((t) => t.name === oldTheme.name);\n newTheme.settings.highlightingColor = oldBackground.highlightingColor;\n\n const getColorFromHex = (hex: string) => hex && parseInt(hex.slice(1), 16);\n\n const colors = (oldBackground.color || '').split(',').map(getColorFromHex);\n\n if(oldBackground.color && !oldBackground.slug) {\n newTheme.settings.wallpaper = {\n _: 'wallPaperNoFile',\n id: 0,\n pFlags: {},\n settings: {\n _: 'wallPaperSettings',\n pFlags: {}\n }\n };\n } else {\n const wallPaper: WallPaper.wallPaper = {\n _: 'wallPaper',\n id: 0,\n access_hash: 0,\n slug: oldBackground.slug,\n document: {} as any,\n pFlags: {},\n settings: {\n _: 'wallPaperSettings',\n pFlags: {}\n }\n };\n\n const wallPaperSettings = wallPaper.settings;\n newTheme.settings.wallpaper = wallPaper;\n if(oldBackground.slug && !oldBackground.color) {\n wallPaperSettings.pFlags.blur = oldBackground.blur || undefined;\n } else if(oldBackground.intensity) {\n wallPaperSettings.intensity = oldBackground.intensity;\n wallPaper.pFlags.pattern = true;\n wallPaper.pFlags.dark = oldBackground.intensity < 0 || undefined;\n }\n }\n\n if(colors.length) {\n const wallPaperSettings = newTheme.settings.wallpaper.settings;\n wallPaperSettings.background_color = colors[0];\n wallPaperSettings.second_background_color = colors[1];\n wallPaperSettings.third_background_color = colors[2];\n wallPaperSettings.fourth_background_color = colors[3];\n }\n });\n } catch(err) {\n console.error('migrating themes error', err);\n }\n }\n\n if(migrated) {\n pushToState('settings', state.settings);\n }\n }\n\n if(state.build < 309) {\n state.settings.liteMode.animations = !state.settings.animationsEnabled;\n state.settings.liteMode.video = !state.settings.autoPlay.videos;\n state.settings.liteMode.gif = !state.settings.autoPlay.gifs;\n }\n\n if(state.build < 312 && typeof(state.settings.stickers.suggest) === 'boolean') {\n state.settings.stickers.suggest = state.settings.stickers.suggest ? 'all' : 'none';\n }\n\n // fix typo\n if(state.build <= 432) {\n let changed = false;\n try {\n for(const theme of state.settings.themes) {\n if(!theme.settings.highlightingColor) {\n theme.settings.highlightingColor = (theme.settings as any).highlightningColor;\n delete (theme.settings as any).highlightningColor;\n changed = true;\n }\n }\n } catch(err) {}\n\n if(changed) {\n pushToState('settings', state.settings);\n }\n }\n\n state.appConfig = copy(STATE_INIT.appConfig);\n\n if(compareVersion(state.version, STATE_VERSION) !== 0) {\n newVersion = STATE_VERSION;\n oldVersion = state.version;\n }\n\n pushToState('version', STATE_VERSION);\n pushToState('build', BUILD);\n }\n\n if(sessionBuild !== BUILD && (!sessionBuild || sessionBuild < BUILD)) {\n sessionStorage.set({k_build: BUILD});\n }\n\n // ! probably there is better place for it\n rootScope.settings = state.settings;\n\n if(DEBUG) {\n log('state res', state, copy(state));\n }\n\n // return resolve();\n\n log.warn('total', performance.now() - totalPerf);\n\n // RESET_STORAGES_PROMISE.resolve(appStateManager.resetStorages);\n\n return {state, resetStorages, newVersion, oldVersion, pushedKeys};\n}\n\nlet promise: ReturnType<typeof loadStateInner>;\nexport default function loadState() {\n return promise ??= loadStateInner();\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport IS_OPUS_SUPPORTED from '../environment/opusSupport';\nimport {IS_SAFARI} from '../environment/userAgent';\nimport {Modify} from '../types';\nimport {logger, LogTypes} from './logger';\nimport apiManagerProxy from './mtproto/mtprotoworker';\nimport type {ConvertWebPTask} from './webp/webpWorkerController';\n\ntype Result = {\n bytes: Uint8Array,\n waveform?: Uint8Array\n};\n\ntype Task = {\n pages: Uint8Array,\n withWaveform: boolean,\n waveform?: Uint8Array,\n callback: {resolve: (result: Result) => void, reject: (err: any) => void},\n timeout: number\n};\n\nexport interface ConvertOpusTask extends Modify<ConvertWebPTask, {type: 'convertOpus'}> {\n type: 'convertOpus'\n}\n\nexport class OpusDecodeController {\n private worker: Worker;\n private wavWorker: Worker;\n private sampleRate = 48000;\n private tasks: Array<Task> = [];\n private keepAlive = false;\n private log = logger('OPUS', LogTypes.Error);\n\n public isPlaySupported() {\n return IS_OPUS_SUPPORTED;\n }\n\n public loadWavWorker() {\n if(this.wavWorker) return;\n\n this.wavWorker = new Worker('waveWorker.min.js');\n this.wavWorker.addEventListener('message', (e) => {\n const data = e.data;\n\n this.log('[WAV] got message:', data);\n if(data && data.page) {\n const bytes = data.page;\n this.onTaskEnd(this.tasks.shift(), bytes);\n }\n });\n }\n\n public loadWorker() {\n if(this.worker) return;\n\n this.worker = new Worker('decoderWorker.min.js');\n this.worker.addEventListener('message', (e) => {\n const data = e.data;\n\n this.log('[DECODER] got message', data);\n if(data.type === 'done') {\n // this.log('[DECODER] send done to wav');\n this.wavWorker.postMessage({command: 'done'});\n\n if(data.waveform) {\n this.tasks[0].waveform = data.waveform;\n }\n } else { // e.data contains decoded buffers as float32 values\n // this.log('[DECODER] send encode to wav');\n this.wavWorker.postMessage({\n command: 'encode',\n buffers: e.data\n }, IS_SAFARI ? undefined : data.map((typedArray: Uint8Array) => typedArray.buffer));\n }\n });\n }\n\n public setKeepAlive(keepAlive: boolean) {\n this.keepAlive = keepAlive;\n if(this.keepAlive) {\n this.loadWorker();\n this.loadWavWorker();\n } else if(!this.tasks.length) {\n this.terminateWorkers();\n }\n }\n\n public onTaskEnd(task: Task, result?: Uint8Array) {\n if(!result) {\n task.callback.reject('timeout');\n } else {\n clearTimeout(task.timeout);\n task.callback.resolve({bytes: result, waveform: task.waveform});\n }\n\n if(this.tasks.length) {\n this.executeNewTask(this.tasks[0]);\n }\n\n this.terminateWorkers();\n }\n\n public terminateWorkers(kill = false) {\n if((this.keepAlive || this.tasks.length) && !kill) return;\n\n if(this.worker) {\n this.worker.terminate();\n this.worker = null;\n }\n\n if(this.wavWorker) {\n this.wavWorker.terminate();\n this.wavWorker = null;\n }\n }\n\n public executeNewTask(task: Task) {\n this.worker.postMessage({\n command: 'init',\n decoderSampleRate: this.sampleRate,\n outputBufferSampleRate: this.sampleRate\n });\n\n this.wavWorker.postMessage({\n command: 'init',\n wavBitDepth: 16,\n wavSampleRate: this.sampleRate\n });\n\n // console.log('sending command to worker:', task);\n // setTimeout(() => {\n this.log('[DECODER] send decode');\n this.worker.postMessage({\n command: 'decode',\n pages: task.pages,\n waveform: task.withWaveform\n }, IS_SAFARI ? undefined : [task.pages.buffer]);\n // }, 1e3);\n\n task.timeout = window.setTimeout(() => {\n this.log.error('decode timeout'/* , task */);\n\n this.terminateWorkers(true);\n if(this.tasks.length) {\n this.loadWorker();\n this.loadWavWorker();\n }\n\n this.onTaskEnd(this.tasks.shift());\n }, 10e3);\n }\n\n public pushDecodeTask(pages: Uint8Array, withWaveform: boolean) {\n return new Promise<Result>((resolve, reject) => {\n const task = {\n pages,\n withWaveform,\n callback: {resolve, reject},\n timeout: 0\n };\n\n this.loadWorker();\n this.loadWavWorker();\n\n if(this.tasks.push(task) === 1) {\n this.executeNewTask(task);\n }\n });\n }\n\n public async decode(typedArray: Uint8Array, withWaveform = false) {\n return this.pushDecodeTask(typedArray, withWaveform).then(async(result) => {\n const dataBlob = new Blob([result.bytes], {type: 'audio/wav'});\n return {url: await apiManagerProxy.invoke('createObjectURL', dataBlob), waveform: result.waveform};\n });\n }\n}\n\nconst opusDecodeController = new OpusDecodeController();\nMOUNT_CLASS_TO.opusDecodeController = opusDecodeController;\nexport default opusDecodeController;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {CryptoMethods} from './crypto_methods';\nimport SuperMessagePort from '../mtproto/superMessagePort';\nimport {Awaited} from '../../types';\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport {IS_WORKER} from '../../helpers/context';\n\ntype CryptoEvent = {\n invoke: <T extends keyof CryptoMethods>(payload: {method: T, args: Parameters<CryptoMethods[T]>}) => ReturnType<CryptoMethods[T]>,\n port: (payload: void, source: MessageEventSource, event: MessageEvent) => void,\n terminate: () => void\n};\n\nexport class CryptoMessagePort<Master extends boolean = false> extends SuperMessagePort<CryptoEvent, CryptoEvent, Master> {\n private lastIndex: number;\n\n constructor() {\n super('CRYPTO');\n this.lastIndex = -1;\n }\n\n public invokeCryptoNew<T extends keyof CryptoMethods>({method, args, transfer}: {\n method: T,\n args: Parameters<CryptoMethods[T]>,\n transfer?: Transferable[]\n }): Promise<Awaited<ReturnType<CryptoMethods[T]>>> {\n const payload = {method, args};\n const listeners = this.listeners['invoke'];\n if(listeners?.size) { // already in worker\n // try {\n let result: any = listeners.values().next().value.callback(payload);\n if(!IS_WORKER && !(result instanceof Promise)) {\n result = Promise.resolve(result);\n }\n\n return result;\n // } catch(err) {\n // return Promise.reject(err);\n // }\n }\n\n const sendPortIndex = method === 'aes-encrypt' || method === 'aes-decrypt' ?\n this.lastIndex = (this.lastIndex + 1) % this.sendPorts.length :\n 0;\n // @ts-ignore\n return this.invoke('invoke', payload, undefined, this.sendPorts[sendPortIndex], transfer);\n }\n\n public invokeCrypto<T extends keyof CryptoMethods>(method: T, ...args: Parameters<CryptoMethods[T]>): Promise<Awaited<ReturnType<CryptoMethods[T]>>> {\n return this.invokeCryptoNew({method, args});\n }\n}\n\nconst cryptoMessagePort = new CryptoMessagePort<false>();\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.cryptoMessagePort = cryptoMessagePort);\nexport default cryptoMessagePort;\n","export default function toArray<T>(value: T | T[]): T[] {\n return Array.isArray(value) ? value : [value];\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\n// https://www.iana.org/assignments/media-types/media-types.xhtml\nexport default function blobSafeMimeType(mimeType: string) {\n if([\n 'image/jpeg',\n 'image/png',\n 'image/gif',\n 'image/svg+xml',\n 'image/webp',\n 'image/bmp',\n 'image/avif',\n 'image/jxl',\n 'video/mp4',\n 'video/webm',\n 'video/quicktime',\n 'audio/ogg',\n 'audio/mpeg',\n 'audio/mp4',\n 'audio/wav', // though it is not in list\n 'application/json',\n 'application/pdf'\n ].indexOf(mimeType) === -1) {\n return 'application/octet-stream';\n }\n\n return mimeType;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport toArray from '../array/toArray';\nimport blobSafeMimeType from './blobSafeMimeType';\n\nexport default function blobConstruct<T extends Uint8Array | string>(blobParts: Array<T> | T, mimeType: string = ''): Blob {\n blobParts = toArray(blobParts);\n const safeMimeType = blobSafeMimeType(mimeType);\n const blob = new Blob(blobParts, {type: safeMimeType});\n return blob;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport blobConstruct from '../../helpers/blob/blobConstruct';\nimport StreamWriter from './streamWriter';\n\nexport default class MemoryWriter implements StreamWriter {\n private bytes: Uint8Array;\n\n constructor(\n private mimeType: string,\n private size: number,\n private saveFileCallback?: (blob: Blob) => Promise<Blob>\n ) {\n this.bytes = new Uint8Array(size);\n }\n\n public async write(part: Uint8Array, offset: number) {\n // sometimes file size can be bigger than the prov\n const endOffset = offset + part.byteLength;\n if(endOffset > this.bytes.byteLength) {\n const newBytes = new Uint8Array(endOffset);\n newBytes.set(this.bytes, 0);\n this.bytes = newBytes;\n }\n\n this.bytes.set(part, offset);\n };\n\n public truncate() {\n this.bytes = new Uint8Array();\n }\n\n public trim(size: number) {\n this.bytes = this.bytes.slice(0, size);\n }\n\n public finalize(saveToStorage = true) {\n const blob = blobConstruct(this.bytes, this.mimeType);\n\n if(saveToStorage && this.saveFileCallback) {\n this.saveFileCallback(blob);\n }\n\n return blob;\n }\n\n public getParts() {\n return this.bytes;\n }\n\n public replaceParts(parts: Uint8Array) {\n this.bytes = parts;\n }\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport Modes from '../../config/modes';\nimport blobConstruct from '../../helpers/blob/blobConstruct';\nimport MemoryWriter from './memoryWriter';\nimport FileManager from './memoryWriter';\nimport FileStorage from './fileStorage';\nimport makeError from '../../helpers/makeError';\nimport deferredPromise from '../../helpers/cancellablePromise';\n\nexport type CacheStorageDbName = 'cachedFiles' | 'cachedStreamChunks' | 'cachedAssets';\n\nexport default class CacheStorageController implements FileStorage {\n private static STORAGES: CacheStorageController[] = [];\n private openDbPromise: Promise<Cache>;\n\n private useStorage = true;\n\n // private log: ReturnType<typeof logger> = logger('CS');\n\n constructor(private dbName: CacheStorageDbName) {\n if(Modes.test) {\n this.dbName += '_test';\n }\n\n if(CacheStorageController.STORAGES.length) {\n this.useStorage = CacheStorageController.STORAGES[0].useStorage;\n }\n\n this.openDatabase();\n CacheStorageController.STORAGES.push(this);\n }\n\n private openDatabase(): Promise<Cache> {\n return this.openDbPromise ?? (this.openDbPromise = caches.open(this.dbName));\n }\n\n public delete(entryName: string) {\n return this.timeoutOperation((cache) => cache.delete('/' + entryName));\n }\n\n public deleteAll() {\n return caches.delete(this.dbName);\n }\n\n public get(entryName: string) {\n return this.timeoutOperation((cache) => cache.match('/' + entryName));\n }\n\n public save(entryName: string, response: Response) {\n // return new Promise((resolve) => {}); // DEBUG\n return this.timeoutOperation((cache) => cache.put('/' + entryName, response));\n }\n\n public getFile(fileName: string, method: 'blob' | 'json' | 'text' = 'blob'): Promise<any> {\n // if(method === 'blob') {\n // return Promise.reject(makeError('NO_ENTRY_FOUND'));\n // }\n\n // const str = `get fileName: ${fileName}`;\n // console.time(str);\n return this.get(fileName).then((response) => {\n if(!response) {\n // console.warn('getFile:', response, fileName);\n throw makeError('NO_ENTRY_FOUND');\n }\n\n const promise = response[method]();\n // promise.then(() => {\n // console.timeEnd(str);\n // });\n return promise;\n });\n }\n\n public saveFile(fileName: string, blob: Blob | Uint8Array) {\n // return Promise.resolve(blobConstruct([blob]));\n if(!(blob instanceof Blob)) {\n blob = blobConstruct(blob);\n }\n\n const response = new Response(blob, {\n headers: {\n 'Content-Length': '' + blob.size\n }\n });\n\n return this.save(fileName, response).then(() => blob as Blob);\n }\n\n public timeoutOperation<T>(callback: (cache: Cache) => Promise<T>) {\n if(!this.useStorage) {\n return Promise.reject(makeError('STORAGE_OFFLINE'));\n }\n\n return new Promise<T>(async(resolve, reject) => {\n let rejected = false;\n const timeout = setTimeout(() => {\n reject();\n // console.warn('CACHESTORAGE TIMEOUT');\n rejected = true;\n }, 15e3);\n\n try {\n const cache = await this.openDatabase();\n if(!cache) {\n this.useStorage = false;\n this.openDbPromise = undefined;\n throw 'no cache?';\n }\n\n const res = await callback(cache);\n\n if(rejected) return;\n resolve(res);\n } catch(err) {\n reject(err);\n }\n\n clearTimeout(timeout);\n });\n }\n\n public prepareWriting(fileName: string, fileSize: number, mimeType: string) {\n return {\n deferred: deferredPromise<Blob>(),\n getWriter: () => {\n const writer = new MemoryWriter(mimeType, fileSize, (blob) => {\n return this.saveFile(fileName, blob).catch(() => blob);\n });\n\n return writer;\n }\n };\n }\n\n public static toggleStorage(enabled: boolean, clearWrite: boolean) {\n return Promise.all(this.STORAGES.map((storage) => {\n storage.useStorage = enabled;\n\n if(!clearWrite) {\n return;\n }\n\n if(!enabled) {\n return storage.deleteAll();\n }\n }));\n }\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport CacheStorageController from '../lib/files/cacheStorage';\nimport AppStorage from '../lib/storage';\nimport sessionStorage from '../lib/sessionStorage';\nimport noop from './noop';\n\nexport default function toggleStorages(enabled: boolean, clearWrite: boolean) {\n return Promise.all([\n AppStorage.toggleStorage(enabled, clearWrite),\n CacheStorageController.toggleStorage(enabled, clearWrite),\n sessionStorage.toggleStorage(enabled, clearWrite)\n ]).then(noop, noop);\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {WebPushApiManager} from '../mtproto/webPushApiManager';\nimport type {PushNotificationObject} from './push';\nimport type {MyUploadFile} from '../mtproto/apiFileManager';\nimport SuperMessagePort from '../mtproto/superMessagePort';\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport {InputFileLocation, InputGroupCall} from '../../layer';\nimport {GroupCallRtmpState} from '../appManagers/appGroupCallsManager';\n\nexport type ServicePushPingTaskPayload = {\n localNotifications: boolean,\n lang: {\n push_action_mute1d: string\n push_action_settings: string\n push_message_nopreview: string\n },\n settings: WebPushApiManager['settings']\n};\n\nexport type ServiceRequestFilePartTaskPayload = {\n docId: DocId,\n dcId: number,\n offset: number,\n limit: number\n};\n\nexport type ServiceRequestRtmpPartTaskPayload = {\n request: InputFileLocation.inputGroupCallStream,\n dcId: number,\n};\n\nexport type ServiceDownloadTaskPayload = {\n headers: any,\n id: string\n};\n\nexport type ServiceEvent = {\n port: (payload: void, source: MessageEventSource, event: MessageEvent) => void\n};\n\nexport default class ServiceMessagePort<Master extends boolean = false> extends SuperMessagePort<{\n // from main thread to service worker\n notificationsClear: () => void,\n toggleStorages: (payload: {enabled: boolean, clearWrite: boolean}) => void,\n pushPing: (payload: ServicePushPingTaskPayload, source: MessageEventSource, event: MessageEvent) => void,\n hello: (payload: void, source: MessageEventSource, event: MessageEvent) => void,\n shownNotification: (payload: string) => void,\n leaveRtmpCall: (payload: [Long, boolean]) => void,\n toggleStreamInUse: (payload: {url: string, inUse: boolean}) => void,\n\n // from mtproto worker\n download: (payload: ServiceDownloadTaskPayload) => void,\n downloadChunk: (payload: {id: ServiceDownloadTaskPayload['id'], chunk: Uint8Array}) => void\n downloadFinalize: (payload: ServiceDownloadTaskPayload['id']) => void,\n downloadCancel: (payload: ServiceDownloadTaskPayload['id']) => void\n}, {\n // to main thread\n pushClick: (payload: PushNotificationObject) => void,\n hello: (payload: void, source: MessageEventSource) => void,\n share: (payload: ShareData) => void,\n rtmpStreamTime: (payload: {callId: Long, time: string}) => void,\n rtmpStreamDestroyed: (payload: Long) => void,\n downloadRequestReceived: (payload: string) => void,\n\n // to mtproto worker\n requestFilePart: (payload: ServiceRequestFilePartTaskPayload) => MaybePromise<MyUploadFile>,\n cancelFilePartRequests: (payload: DocId) => void,\n requestRtmpState: (payload: InputGroupCall) => MaybePromise<GroupCallRtmpState>,\n requestRtmpPart: (payload: ServiceRequestRtmpPartTaskPayload) => MaybePromise<MyUploadFile>,\n} & ServiceEvent, Master> {\n constructor() {\n super('SERVICE');\n\n MOUNT_CLASS_TO && (MOUNT_CLASS_TO.serviceMessagePort = this);\n }\n}\n","export const DEEP_PATH_JOINER = '\\x01';\n\nexport function joinDeepPath(...args: any[]) {\n return args.join(DEEP_PATH_JOINER);\n}\n\nexport function splitDeepPath(path: string) {\n return path.split(DEEP_PATH_JOINER);\n}\n\nexport default function setDeepProperty(\n object: any,\n key: string,\n value?: any,\n deleteIfUndefined?: boolean\n) {\n const splitted = key.split(DEEP_PATH_JOINER);\n const length = splitted.length;\n let lastObject = object/* , fractalPart: string */; // fix fractal number key\n for(let i = 0; i < length - 1; ++i) {\n const part = splitted[i];\n // if(fractalPart) {\n // part = fractalPart + '.' + part;\n // fractalPart = undefined;\n // } else if(!Number.isNaN(+part)) {\n // fractalPart = part;\n // continue;\n // }\n lastObject = lastObject[part] ??= {};\n }\n\n const lastKey = /* (fractalPart ? fractalPart + '.' : '') + */splitted[length - 1];\n if(value === undefined && deleteIfUndefined/* && arguments.length === 2 */) {\n delete lastObject[lastKey];\n } else {\n lastObject[lastKey] = value;\n }\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {InputFileLocation, InputGeoPoint, InputStickerSet, InputWebFileLocation} from '../layer';\nimport type {DownloadOptions} from '../lib/mtproto/apiFileManager';\n\nconst FILENAME_JOINER = '_';\n\nexport function getFileNameByLocation(location: InputFileLocation | InputWebFileLocation, options?: Partial<{\n fileName: string,\n downloadId: string\n}>) {\n const fileName = '';// (options?.fileName || '').split('.');\n const ext = fileName[fileName.length - 1] || '';\n\n let str: string;\n switch(location._) {\n case 'inputPhotoFileLocation': {\n str = ['photo', fileName[0], location.id, location.thumb_size].filter(Boolean).join(FILENAME_JOINER);\n break;\n }\n\n case 'inputDocumentFileLocation': {\n str = ['document', fileName[0], location.id, location.thumb_size].filter(Boolean).join(FILENAME_JOINER);\n break;\n }\n\n case 'inputPeerPhotoFileLocation':\n str = ['peerPhoto', location.photo_id, location.pFlags.big ? 'big' : 'small'].join(FILENAME_JOINER);\n break;\n\n case 'inputStickerSetThumb': {\n const id = (location.stickerset as InputStickerSet.inputStickerSetID).id ||\n (location.stickerset as InputStickerSet.inputStickerSetShortName).short_name ||\n (location.stickerset as InputStickerSet.inputStickerSetDice).emoticon ||\n location.stickerset._;\n str = ['stickerSetThumb', id, location.thumb_version].join(FILENAME_JOINER);\n break;\n }\n\n case 'inputFileLocation': {\n str = [location.volume_id, location.local_id].join(FILENAME_JOINER);\n break;\n }\n\n case 'inputWebFileLocation': {\n str = ['webFile', location.url].join(FILENAME_JOINER);\n break;\n }\n\n case 'inputWebFileGeoPointLocation': {\n const geoPoint = location.geo_point as InputGeoPoint.inputGeoPoint;\n str = ['geoPoint', geoPoint.lat, geoPoint.long, location.w, location.h, location.zoom, location.scale].join(FILENAME_JOINER);\n break;\n }\n\n default: {\n console.error('Unrecognized location:', location);\n str = '';\n break;\n }\n }\n\n return str + (options?.downloadId ? '_download' : '') + (ext ? '.' + ext : ext);\n}\n\nexport type FileURLType = 'photo' | 'thumb' | 'document' | 'stream' | 'download';\nexport function getFileURL(type: FileURLType, options: DownloadOptions) {\n // console.log('getFileURL', location);\n // const perf = performance.now();\n const encoded = encodeURIComponent(JSON.stringify(options));\n // console.log('getFileURL encode:', performance.now() - perf, encoded);\n\n return /* '/' + */type + '/' + encoded;\n}\n","import {InputWebFileLocation} from '../../../../layer';\n\nexport default function isWebFileLocation(location: any): location is InputWebFileLocation {\n return location?._.includes('inputWebFile');\n}\n","import type {MyPhoto} from '../../../appManagers/appPhotosManager';\nimport type {ThumbStorageMedia} from '../../thumbs';\nimport type {WebDocument} from '../../../../layer';\nimport {getFileNameByLocation} from '../../../../helpers/fileName';\nimport isWebFileLocation from '../../../appManagers/utils/webFiles/isWebFileLocation';\n\nexport default function getThumbKey(media: ThumbStorageMedia) {\n if(isWebFileLocation(media)) {\n return getFileNameByLocation(media);\n }\n\n return media._ + ((media as MyPhoto).id ?? (media as WebDocument).url);\n}\n","import type {ThumbCache} from '../../thumbs';\n\nexport default function generateEmptyThumb(type: string): ThumbCache {\n return {downloaded: 0, url: '', type};\n}\n","export default function getStickerThumbKey(docId: DocId, toneIndex?: number | string) {\n return docId + (toneIndex !== undefined ? '-' + toneIndex : '');\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {Awaited} from '../types';\n\nexport default function callbackify<T extends Awaited<any>, R>(\n smth: T,\n callback: (result: Awaited<T>) => R\n): T extends Promise<any> ? Promise<Awaited<R>> : R {\n if(smth instanceof Promise) {\n // @ts-ignore\n return smth.then(callback);\n } else {\n return callback(smth as any) as any;\n }\n}\n","import {MESSAGE_ID_OFFSET} from '../../../mtproto/mtproto_config';\n\nexport default function isLegacyMessageId(messageId: number) {\n return typeof(messageId) === 'number' && messageId < MESSAGE_ID_OFFSET;\n}\n","import { $PROXY, $TRACK, getListener, batch, createSignal } from 'solid-js';\n\nconst $RAW = Symbol(\"store-raw\"),\n $NODE = Symbol(\"store-node\"),\n $HAS = Symbol(\"store-has\"),\n $SELF = Symbol(\"store-self\");\nfunction wrap$1(value) {\n let p = value[$PROXY];\n if (!p) {\n Object.defineProperty(value, $PROXY, {\n value: p = new Proxy(value, proxyTraps$1)\n });\n if (!Array.isArray(value)) {\n const keys = Object.keys(value),\n desc = Object.getOwnPropertyDescriptors(value);\n for (let i = 0, l = keys.length; i < l; i++) {\n const prop = keys[i];\n if (desc[prop].get) {\n Object.defineProperty(value, prop, {\n enumerable: desc[prop].enumerable,\n get: desc[prop].get.bind(p)\n });\n }\n }\n }\n }\n return p;\n}\nfunction isWrappable(obj) {\n let proto;\n return obj != null && typeof obj === \"object\" && (obj[$PROXY] || !(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype || Array.isArray(obj));\n}\nfunction unwrap(item, set = new Set()) {\n let result, unwrapped, v, prop;\n if (result = item != null && item[$RAW]) return result;\n if (!isWrappable(item) || set.has(item)) return item;\n if (Array.isArray(item)) {\n if (Object.isFrozen(item)) item = item.slice(0);else set.add(item);\n for (let i = 0, l = item.length; i < l; i++) {\n v = item[i];\n if ((unwrapped = unwrap(v, set)) !== v) item[i] = unwrapped;\n }\n } else {\n if (Object.isFrozen(item)) item = Object.assign({}, item);else set.add(item);\n const keys = Object.keys(item),\n desc = Object.getOwnPropertyDescriptors(item);\n for (let i = 0, l = keys.length; i < l; i++) {\n prop = keys[i];\n if (desc[prop].get) continue;\n v = item[prop];\n if ((unwrapped = unwrap(v, set)) !== v) item[prop] = unwrapped;\n }\n }\n return item;\n}\nfunction getNodes(target, symbol) {\n let nodes = target[symbol];\n if (!nodes) Object.defineProperty(target, symbol, {\n value: nodes = Object.create(null)\n });\n return nodes;\n}\nfunction getNode(nodes, property, value) {\n if (nodes[property]) return nodes[property];\n const [s, set] = createSignal(value, {\n equals: false,\n internal: true\n });\n s.$ = set;\n return nodes[property] = s;\n}\nfunction proxyDescriptor$1(target, property) {\n const desc = Reflect.getOwnPropertyDescriptor(target, property);\n if (!desc || desc.get || !desc.configurable || property === $PROXY || property === $NODE) return desc;\n delete desc.value;\n delete desc.writable;\n desc.get = () => target[$PROXY][property];\n return desc;\n}\nfunction trackSelf(target) {\n getListener() && getNode(getNodes(target, $NODE), $SELF)();\n}\nfunction ownKeys(target) {\n trackSelf(target);\n return Reflect.ownKeys(target);\n}\nconst proxyTraps$1 = {\n get(target, property, receiver) {\n if (property === $RAW) return target;\n if (property === $PROXY) return receiver;\n if (property === $TRACK) {\n trackSelf(target);\n return receiver;\n }\n const nodes = getNodes(target, $NODE);\n const tracked = nodes[property];\n let value = tracked ? tracked() : target[property];\n if (property === $NODE || property === $HAS || property === \"__proto__\") return value;\n if (!tracked) {\n const desc = Object.getOwnPropertyDescriptor(target, property);\n if (getListener() && (typeof value !== \"function\" || target.hasOwnProperty(property)) && !(desc && desc.get)) value = getNode(nodes, property, value)();\n }\n return isWrappable(value) ? wrap$1(value) : value;\n },\n has(target, property) {\n if (property === $RAW || property === $PROXY || property === $TRACK || property === $NODE || property === $HAS || property === \"__proto__\") return true;\n getListener() && getNode(getNodes(target, $HAS), property)();\n return property in target;\n },\n set() {\n return true;\n },\n deleteProperty() {\n return true;\n },\n ownKeys: ownKeys,\n getOwnPropertyDescriptor: proxyDescriptor$1\n};\nfunction setProperty(state, property, value, deleting = false) {\n if (!deleting && state[property] === value) return;\n const prev = state[property],\n len = state.length;\n if (value === undefined) {\n delete state[property];\n if (state[$HAS] && state[$HAS][property] && prev !== undefined) state[$HAS][property].$();\n } else {\n state[property] = value;\n if (state[$HAS] && state[$HAS][property] && prev === undefined) state[$HAS][property].$();\n }\n let nodes = getNodes(state, $NODE),\n node;\n if (node = getNode(nodes, property, prev)) node.$(() => value);\n if (Array.isArray(state) && state.length !== len) {\n for (let i = state.length; i < len; i++) (node = nodes[i]) && node.$();\n (node = getNode(nodes, \"length\", len)) && node.$(state.length);\n }\n (node = nodes[$SELF]) && node.$();\n}\nfunction mergeStoreNode(state, value) {\n const keys = Object.keys(value);\n for (let i = 0; i < keys.length; i += 1) {\n const key = keys[i];\n setProperty(state, key, value[key]);\n }\n}\nfunction updateArray(current, next) {\n if (typeof next === \"function\") next = next(current);\n next = unwrap(next);\n if (Array.isArray(next)) {\n if (current === next) return;\n let i = 0,\n len = next.length;\n for (; i < len; i++) {\n const value = next[i];\n if (current[i] !== value) setProperty(current, i, value);\n }\n setProperty(current, \"length\", len);\n } else mergeStoreNode(current, next);\n}\nfunction updatePath(current, path, traversed = []) {\n let part,\n prev = current;\n if (path.length > 1) {\n part = path.shift();\n const partType = typeof part,\n isArray = Array.isArray(current);\n if (Array.isArray(part)) {\n for (let i = 0; i < part.length; i++) {\n updatePath(current, [part[i]].concat(path), traversed);\n }\n return;\n } else if (isArray && partType === \"function\") {\n for (let i = 0; i < current.length; i++) {\n if (part(current[i], i)) updatePath(current, [i].concat(path), traversed);\n }\n return;\n } else if (isArray && partType === \"object\") {\n const {\n from = 0,\n to = current.length - 1,\n by = 1\n } = part;\n for (let i = from; i <= to; i += by) {\n updatePath(current, [i].concat(path), traversed);\n }\n return;\n } else if (path.length > 1) {\n updatePath(current[part], path, [part].concat(traversed));\n return;\n }\n prev = current[part];\n traversed = [part].concat(traversed);\n }\n let value = path[0];\n if (typeof value === \"function\") {\n value = value(prev, traversed);\n if (value === prev) return;\n }\n if (part === undefined && value == undefined) return;\n value = unwrap(value);\n if (part === undefined || isWrappable(prev) && isWrappable(value) && !Array.isArray(value)) {\n mergeStoreNode(prev, value);\n } else setProperty(current, part, value);\n}\nfunction createStore(...[store, options]) {\n const unwrappedStore = unwrap(store || {});\n const isArray = Array.isArray(unwrappedStore);\n const wrappedStore = wrap$1(unwrappedStore);\n function setStore(...args) {\n batch(() => {\n isArray && args.length === 1 ? updateArray(unwrappedStore, args[0]) : updatePath(unwrappedStore, args);\n });\n }\n return [wrappedStore, setStore];\n}\n\nfunction proxyDescriptor(target, property) {\n const desc = Reflect.getOwnPropertyDescriptor(target, property);\n if (!desc || desc.get || desc.set || !desc.configurable || property === $PROXY || property === $NODE) return desc;\n delete desc.value;\n delete desc.writable;\n desc.get = () => target[$PROXY][property];\n desc.set = v => target[$PROXY][property] = v;\n return desc;\n}\nconst proxyTraps = {\n get(target, property, receiver) {\n if (property === $RAW) return target;\n if (property === $PROXY) return receiver;\n if (property === $TRACK) {\n trackSelf(target);\n return receiver;\n }\n const nodes = getNodes(target, $NODE);\n const tracked = nodes[property];\n let value = tracked ? tracked() : target[property];\n if (property === $NODE || property === $HAS || property === \"__proto__\") return value;\n if (!tracked) {\n const desc = Object.getOwnPropertyDescriptor(target, property);\n const isFunction = typeof value === \"function\";\n if (getListener() && (!isFunction || target.hasOwnProperty(property)) && !(desc && desc.get)) value = getNode(nodes, property, value)();else if (value != null && isFunction && value === Array.prototype[property]) {\n return (...args) => batch(() => Array.prototype[property].apply(receiver, args));\n }\n }\n return isWrappable(value) ? wrap(value) : value;\n },\n has(target, property) {\n if (property === $RAW || property === $PROXY || property === $TRACK || property === $NODE || property === $HAS || property === \"__proto__\") return true;\n getListener() && getNode(getNodes(target, $HAS), property)();\n return property in target;\n },\n set(target, property, value) {\n batch(() => setProperty(target, property, unwrap(value)));\n return true;\n },\n deleteProperty(target, property) {\n batch(() => setProperty(target, property, undefined, true));\n return true;\n },\n ownKeys: ownKeys,\n getOwnPropertyDescriptor: proxyDescriptor\n};\nfunction wrap(value) {\n let p = value[$PROXY];\n if (!p) {\n Object.defineProperty(value, $PROXY, {\n value: p = new Proxy(value, proxyTraps)\n });\n const keys = Object.keys(value),\n desc = Object.getOwnPropertyDescriptors(value);\n const proto = Object.getPrototypeOf(value);\n const isClass = value !== null && typeof value === \"object\" && !Array.isArray(value) && proto !== Object.prototype;\n if (isClass) {\n const descriptors = Object.getOwnPropertyDescriptors(proto);\n keys.push(...Object.keys(descriptors));\n Object.assign(desc, descriptors);\n }\n for (let i = 0, l = keys.length; i < l; i++) {\n const prop = keys[i];\n if (isClass && prop === \"constructor\") continue;\n if (desc[prop].get) {\n const get = desc[prop].get.bind(p);\n Object.defineProperty(value, prop, {\n get,\n configurable: true\n });\n }\n if (desc[prop].set) {\n const og = desc[prop].set,\n set = v => batch(() => og.call(p, v));\n Object.defineProperty(value, prop, {\n set,\n configurable: true\n });\n }\n }\n }\n return p;\n}\nfunction createMutable(state, options) {\n const unwrappedStore = unwrap(state || {});\n const wrappedStore = wrap(unwrappedStore);\n return wrappedStore;\n}\nfunction modifyMutable(state, modifier) {\n batch(() => modifier(unwrap(state)));\n}\n\nconst $ROOT = Symbol(\"store-root\");\nfunction applyState(target, parent, property, merge, key) {\n const previous = parent[property];\n if (target === previous) return;\n const isArray = Array.isArray(target);\n if (property !== $ROOT && (!isWrappable(target) || !isWrappable(previous) || isArray !== Array.isArray(previous) || key && target[key] !== previous[key])) {\n setProperty(parent, property, target);\n return;\n }\n if (isArray) {\n if (target.length && previous.length && (!merge || key && target[0] && target[0][key] != null)) {\n let i, j, start, end, newEnd, item, newIndicesNext, keyVal;\n for (start = 0, end = Math.min(previous.length, target.length); start < end && (previous[start] === target[start] || key && previous[start] && target[start] && previous[start][key] === target[start][key]); start++) {\n applyState(target[start], previous, start, merge, key);\n }\n const temp = new Array(target.length),\n newIndices = new Map();\n for (end = previous.length - 1, newEnd = target.length - 1; end >= start && newEnd >= start && (previous[end] === target[newEnd] || key && previous[start] && target[start] && previous[end][key] === target[newEnd][key]); end--, newEnd--) {\n temp[newEnd] = previous[end];\n }\n if (start > newEnd || start > end) {\n for (j = start; j <= newEnd; j++) setProperty(previous, j, target[j]);\n for (; j < target.length; j++) {\n setProperty(previous, j, temp[j]);\n applyState(target[j], previous, j, merge, key);\n }\n if (previous.length > target.length) setProperty(previous, \"length\", target.length);\n return;\n }\n newIndicesNext = new Array(newEnd + 1);\n for (j = newEnd; j >= start; j--) {\n item = target[j];\n keyVal = key && item ? item[key] : item;\n i = newIndices.get(keyVal);\n newIndicesNext[j] = i === undefined ? -1 : i;\n newIndices.set(keyVal, j);\n }\n for (i = start; i <= end; i++) {\n item = previous[i];\n keyVal = key && item ? item[key] : item;\n j = newIndices.get(keyVal);\n if (j !== undefined && j !== -1) {\n temp[j] = previous[i];\n j = newIndicesNext[j];\n newIndices.set(keyVal, j);\n }\n }\n for (j = start; j < target.length; j++) {\n if (j in temp) {\n setProperty(previous, j, temp[j]);\n applyState(target[j], previous, j, merge, key);\n } else setProperty(previous, j, target[j]);\n }\n } else {\n for (let i = 0, len = target.length; i < len; i++) {\n applyState(target[i], previous, i, merge, key);\n }\n }\n if (previous.length > target.length) setProperty(previous, \"length\", target.length);\n return;\n }\n const targetKeys = Object.keys(target);\n for (let i = 0, len = targetKeys.length; i < len; i++) {\n applyState(target[targetKeys[i]], previous, targetKeys[i], merge, key);\n }\n const previousKeys = Object.keys(previous);\n for (let i = 0, len = previousKeys.length; i < len; i++) {\n if (target[previousKeys[i]] === undefined) setProperty(previous, previousKeys[i], undefined);\n }\n}\nfunction reconcile(value, options = {}) {\n const {\n merge,\n key = \"id\"\n } = options,\n v = unwrap(value);\n return state => {\n if (!isWrappable(state) || !isWrappable(v)) return v;\n const res = applyState(v, {\n [$ROOT]: state\n }, $ROOT, merge, key);\n return res === undefined ? state : res;\n };\n}\nconst producers = new WeakMap();\nconst setterTraps = {\n get(target, property) {\n if (property === $RAW) return target;\n const value = target[property];\n let proxy;\n return isWrappable(value) ? producers.get(value) || (producers.set(value, proxy = new Proxy(value, setterTraps)), proxy) : value;\n },\n set(target, property, value) {\n setProperty(target, property, unwrap(value));\n return true;\n },\n deleteProperty(target, property) {\n setProperty(target, property, undefined, true);\n return true;\n }\n};\nfunction produce(fn) {\n return state => {\n if (isWrappable(state)) {\n let proxy;\n if (!(proxy = producers.get(state))) {\n producers.set(state, proxy = new Proxy(state, setterTraps));\n }\n fn(proxy);\n }\n return state;\n };\n}\n\nconst DEV = undefined;\n\nexport { $RAW, DEV, createMutable, createStore, modifyMutable, produce, reconcile, unwrap };\n","import {createRoot} from 'solid-js';\nimport {createStore, reconcile, unwrap} from 'solid-js/store';\nimport {State} from '../config/state';\nimport rootScope from '../lib/rootScope';\n\nconst [appState, _setAppState] = createRoot(() => createStore<State>({} as any));\n\nconst setAppState: typeof _setAppState = (...args: any[]) => {\n const key = args[0];\n // @ts-ignore\n _setAppState(...args);\n // @ts-ignore\n rootScope.managers.appStateManager.setByKey(key, unwrap(appState[key]));\n};\n\nconst setAppStateSilent = (key: any, value?: any) => {\n if(typeof(key) === 'object') {\n _setAppState(key);\n return;\n }\n\n _setAppState(key, reconcile(value));\n};\n\nconst useAppState = () => [appState, setAppState] as const;\n\nexport {\n appState,\n useAppState,\n setAppState,\n setAppStateSilent\n};\n","export default function getObjectKeysAndSort(object: {[key: string]: any} | Map<number, any>, sort: 'asc' | 'desc' = 'asc') {\n if(!object) return [];\n const ids = object instanceof Map ? [...object.keys()] : Object.keys(object).map((i) => +i);\n if(sort === 'asc') return ids.sort((a, b) => a - b);\n else return ids.sort((a, b) => b - a);\n}\n","// import {Accessor, createMemo} from 'solid-js';\nimport {Accessor, createMemo} from 'solid-js';\nimport {createStore, reconcile} from 'solid-js/store';\nimport {Chat, User} from '../layer';\n\ntype Peer = Chat | User;\n\nconst [state, setState] = createStore<{[peerId: PeerId]: Peer}>({});\n\ntype ValueOrGetter<T> = T | Accessor<T>;\n\nfunction createMemoOrReturn<T extends ValueOrGetter<any>, R, V = T extends Accessor<infer V> ? V : T>(valueOrGetter: T, callback: (value: V) => R): T extends Accessor<any> ? Accessor<R> : R {\n // @ts-ignore\n return typeof(valueOrGetter) === 'function' ? createMemo(() => callback((valueOrGetter as Accessor<T>)())) : callback(valueOrGetter);\n}\n\nexport function usePeer<T extends ValueOrGetter<PeerId>>(peerId: T) {\n return createMemoOrReturn(peerId, (peerId) => state[peerId]);\n}\n\nexport function useChat<T extends ValueOrGetter<ChatId>>(chatId: T) {\n return createMemoOrReturn<T, Chat>(chatId, (chatId) => state[chatId?.toPeerId(true)] as Chat);\n}\n\nexport function useUser<T extends ValueOrGetter<UserId>>(userId: T) {\n return createMemoOrReturn<T, User>(userId, (userId) => state[userId?.toPeerId(false)] as User);\n}\n\nexport function reconcilePeer(peerId: PeerId, peer: Peer) {\n setState(peerId, reconcile(peer));\n}\n\nexport function reconcilePeers(peers: {[peerId: PeerId]: Peer}) {\n setState(/* reconcile */(peers));\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {Awaited} from '../../types';\nimport type {CacheStorageDbName} from '../files/cacheStorage';\nimport type {State} from '../../config/state';\nimport type {Chat, ChatPhoto, Message, MessagePeerReaction, PeerNotifySettings, User, UserProfilePhoto} from '../../layer';\nimport type {CryptoMethods} from '../crypto/crypto_methods';\nimport type {ThumbStorageMedia} from '../storages/thumbs';\nimport type ThumbsStorage from '../storages/thumbs';\nimport type {AppReactionsManager} from '../appManagers/appReactionsManager';\nimport type {MessagesStorageKey} from '../appManagers/appMessagesManager';\nimport type {AppAvatarsManager, PeerPhotoSize} from '../appManagers/appAvatarsManager';\nimport rootScope from '../rootScope';\nimport webpWorkerController from '../webp/webpWorkerController';\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport sessionStorage from '../sessionStorage';\nimport webPushApiManager from './webPushApiManager';\nimport appRuntimeManager from '../appManagers/appRuntimeManager';\nimport telegramMeWebManager from './telegramMeWebManager';\nimport pause from '../../helpers/schedulers/pause';\nimport ENVIRONMENT from '../../environment';\nimport loadState from '../appManagers/utils/state/loadState';\nimport opusDecodeController from '../opusDecodeController';\nimport MTProtoMessagePort from './mtprotoMessagePort';\nimport cryptoMessagePort from '../crypto/cryptoMessagePort';\nimport SuperMessagePort from './superMessagePort';\nimport IS_SHARED_WORKER_SUPPORTED from '../../environment/sharedWorkerSupport';\nimport toggleStorages from '../../helpers/toggleStorages';\nimport idleController from '../../helpers/idleController';\nimport ServiceMessagePort from '../serviceWorker/serviceMessagePort';\nimport deferredPromise, {CancellablePromise} from '../../helpers/cancellablePromise';\nimport {makeWorkerURL} from '../../helpers/setWorkerProxy';\nimport ServiceWorkerURL from '../../../sw?worker&url';\nimport setDeepProperty, {splitDeepPath} from '../../helpers/object/setDeepProperty';\nimport getThumbKey from '../storages/utils/thumbs/getThumbKey';\nimport {NULL_PEER_ID, THUMB_TYPE_FULL} from './mtproto_config';\nimport generateEmptyThumb from '../storages/utils/thumbs/generateEmptyThumb';\nimport getStickerThumbKey from '../storages/utils/thumbs/getStickerThumbKey';\nimport callbackify from '../../helpers/callbackify';\nimport isLegacyMessageId from '../appManagers/utils/messageId/isLegacyMessageId';\nimport {MTAppConfig} from './appConfig';\nimport {setAppStateSilent} from '../../stores/appState';\nimport getObjectKeysAndSort from '../../helpers/object/getObjectKeysAndSort';\nimport {reconcilePeer, reconcilePeers} from '../../stores/peers';\n\nconst TEST_NO_STREAMING = false;\n\nexport type Mirrors = {\n state: State,\n thumbs: ThumbsStorage['thumbsCache'],\n stickerThumbs: ThumbsStorage['stickerCachedThumbs'],\n availableReactions: AppReactionsManager['availableReactions'] | Promise<AppReactionsManager['availableReactions']>,\n messages: {\n [type in string]: {\n [mid in number]: Message.message | Message.messageService\n }\n },\n groupedMessages: {\n [groupedId in string]: Map<number, Message.message | Message.messageService>\n },\n peers: {\n [peerId in PeerId]: Exclude<Chat, Chat.chatEmpty> | User.user\n },\n avatars: AppAvatarsManager['savedAvatarURLs']\n};\n\nexport type MirrorTaskPayload<\n T extends keyof Mirrors = keyof Mirrors\n // K extends keyof Mirrors[T] = keyof Mirrors[T],\n // J extends Mirrors[T][K] = Mirrors[T][K]\n> = {\n name: T,\n // key?: K,\n key?: string,\n value?: any\n};\n\nexport type NotificationBuildTaskPayload = {\n message: Message.message | Message.messageService,\n fwdCount?: number,\n peerReaction?: MessagePeerReaction,\n peerTypeNotifySettings?: PeerNotifySettings\n};\n\nexport type TabState = {\n chatPeerIds: PeerId[],\n idleStartTime: number,\n};\n\nclass ApiManagerProxy extends MTProtoMessagePort {\n // private worker: /* Window */Worker;\n // private sockets: Map<number, Socket> = new Map();\n private mirrors: Mirrors;\n\n public newVersion: string;\n public oldVersion: string;\n\n private tabState: TabState;\n\n public share: ShareData;\n\n public serviceMessagePort: ServiceMessagePort<true>;\n private lastServiceWorker: ServiceWorker;\n\n private pingServiceWorkerPromise: CancellablePromise<void>;\n\n private processMirrorTaskMap: {\n [type in keyof Mirrors]?: (payload: MirrorTaskPayload) => void\n };\n\n private appConfig: MaybePromise<MTAppConfig>;\n\n constructor() {\n super();\n\n this.mirrors = {\n state: undefined,\n thumbs: {},\n stickerThumbs: {},\n availableReactions: undefined,\n messages: {},\n groupedMessages: {},\n peers: {},\n avatars: {}\n };\n\n this.processMirrorTaskMap = {\n messages: (payload) => {\n const message = payload.value as Message.message | Message.messageService;\n let mid: number, groupedId: string;\n if(message) {\n mid = message.mid;\n groupedId = (message as Message.message).grouped_id;\n } else {\n const [key, _mid] = splitDeepPath(payload.key);\n mid = +_mid;\n const previousMessage = this.mirrors.messages[key]?.[mid];\n if(!previousMessage) {\n return;\n }\n\n groupedId = (previousMessage as Message.message).grouped_id;\n }\n\n if(!groupedId) {\n return;\n }\n\n const map = this.mirrors.groupedMessages[groupedId] ??= new Map();\n if(!message) {\n map.delete(mid);\n\n if(!map.size) {\n delete this.mirrors.groupedMessages[groupedId];\n }\n } else {\n map.set(mid, message);\n }\n },\n\n state: (payload) => {\n if(payload.key) {\n setAppStateSilent(payload.key, payload.value);\n } else {\n console.error(payload);\n }\n },\n\n peers: (payload) => {\n if(payload.key) {\n reconcilePeer(payload.key.toPeerId(), payload.value as any);\n } else {\n reconcilePeers(payload.value);\n }\n }\n };\n\n this.tabState = {\n chatPeerIds: [],\n idleStartTime: 0\n };\n\n this.log('constructor');\n\n if(!import.meta.env.VITE_MTPROTO_SW) {\n this.registerWorker();\n }\n\n this.registerServiceWorker();\n this.registerCryptoWorker();\n\n // const perf = performance.now();\n this.addMultipleEventsListeners({\n convertWebp: ({fileName, bytes}) => {\n return webpWorkerController.convert(fileName, bytes);\n },\n\n convertOpus: ({fileName, bytes}) => {\n return opusDecodeController.pushDecodeTask(bytes, false).then((result) => result.bytes);\n },\n\n event: ({name, args}) => {\n // @ts-ignore\n rootScope.dispatchEventSingle(name, ...args);\n },\n\n localStorageProxy: (payload) => {\n const storageTask = payload;\n return (sessionStorage[storageTask.type] as any)(...storageTask.args);\n },\n\n mirror: this.onMirrorTask,\n\n receivedServiceMessagePort: () => {\n this.log.warn('mtproto worker received service message port');\n }\n\n // hello: () => {\n // this.log.error('time hello', performance.now() - perf);\n // }\n });\n\n // this.addTaskListener('socketProxy', (task) => {\n // const socketTask = task.payload;\n // const id = socketTask.id;\n // //console.log('socketProxy', socketTask, id);\n\n // if(socketTask.type === 'send') {\n // const socket = this.sockets.get(id);\n // socket.send(socketTask.payload);\n // } else if(socketTask.type === 'close') { // will remove from map in onClose\n // const socket = this.sockets.get(id);\n // socket.close();\n // } else if(socketTask.type === 'setup') {\n // const socket = new Socket(socketTask.payload.dcId, socketTask.payload.url, socketTask.payload.logSuffix);\n\n // const onOpen = () => {\n // //console.log('socketProxy onOpen');\n // this.postMessage({\n // type: 'socketProxy',\n // payload: {\n // type: 'open',\n // id\n // }\n // });\n // };\n // const onClose = () => {\n // this.postMessage({\n // type: 'socketProxy',\n // payload: {\n // type: 'close',\n // id\n // }\n // });\n\n // socket.removeEventListener('open', onOpen);\n // socket.removeEventListener('close', onClose);\n // socket.removeEventListener('message', onMessage);\n // this.sockets.delete(id);\n // };\n // const onMessage = (buffer: ArrayBuffer) => {\n // this.postMessage({\n // type: 'socketProxy',\n // payload: {\n // type: 'message',\n // id,\n // payload: buffer\n // }\n // });\n // };\n\n // socket.addEventListener('open', onOpen);\n // socket.addEventListener('close', onClose);\n // socket.addEventListener('message', onMessage);\n // this.sockets.set(id, socket);\n // }\n // });\n\n rootScope.addEventListener('language_change', (language) => {\n rootScope.managers.networkerFactory.setLanguage(language);\n rootScope.managers.appAttachMenuBotsManager.onLanguageChange();\n });\n\n window.addEventListener('online', () => {\n rootScope.managers.networkerFactory.forceReconnectTimeout();\n });\n\n rootScope.addEventListener('logging_out', () => {\n const toClear: CacheStorageDbName[] = ['cachedFiles', 'cachedStreamChunks'];\n Promise.all([\n toggleStorages(false, true),\n sessionStorage.clear(),\n Promise.race([\n telegramMeWebManager.setAuthorized(false),\n pause(3000)\n ]),\n webPushApiManager.forceUnsubscribe(),\n Promise.all(toClear.map((cacheName) => caches.delete(cacheName)))\n ]).finally(() => {\n appRuntimeManager.reload();\n });\n });\n\n idleController.addEventListener('change', (idle) => {\n this.updateTabStateIdle(idle);\n });\n this.updateTabStateIdle(idleController.isIdle);\n\n // this.sendState();\n }\n\n public sendEnvironment() {\n this.log('Passing environment:', ENVIRONMENT);\n this.invoke('environment', ENVIRONMENT);\n }\n\n public pingServiceWorkerWithIframe() {\n if(this.pingServiceWorkerPromise) {\n return this.pingServiceWorkerPromise;\n }\n\n const promise = this.pingServiceWorkerPromise = deferredPromise<void>();\n const iframe = document.createElement('iframe');\n iframe.hidden = true;\n const onFinish = () => {\n clearTimeout(timeout);\n setTimeout(() => { // ping once in 10 seconds\n this.pingServiceWorkerPromise = undefined;\n }, 10e3);\n\n iframe.removeEventListener('load', onLoad);\n iframe.removeEventListener('error', onError);\n iframe.remove();\n };\n const onLoad = () => {\n onFinish();\n promise.resolve();\n };\n const onError = () => {\n onFinish();\n promise.reject();\n };\n iframe.addEventListener('load', onLoad);\n iframe.addEventListener('error', onError);\n iframe.src = 'ping/' + (Math.random() * 0xFFFFFFFF | 0) + '.nocache';\n document.body.append(iframe);\n\n const timeout = window.setTimeout(onError, 1500);\n return promise;\n }\n\n private attachServiceWorker(serviceWorker: ServiceWorker) {\n if(this.lastServiceWorker === serviceWorker) {\n this.log.warn('trying to attach same service worker');\n return;\n }\n\n this.lastServiceWorker && this.serviceMessagePort.detachPort(this.lastServiceWorker);\n this.serviceMessagePort.attachSendPort(this.lastServiceWorker = serviceWorker);\n this.serviceMessagePort.invokeVoid('hello', undefined);\n }\n\n private _registerServiceWorker() {\n // if(import.meta.env.DEV && IS_SAFARI) {\n // return;\n // }\n\n navigator.serviceWorker.register(\n // * doesn't work\n // new URL('../../../sw.ts', import.meta.url),\n // '../../../sw',\n ServiceWorkerURL,\n {type: 'module', scope: './'}\n ).then((registration) => {\n if(TEST_NO_STREAMING) {\n throw 1;\n }\n\n this.log('SW registered', registration);\n\n const url = new URL(window.location.href);\n const FIX_KEY = 'swfix';\n const swfix = +url.searchParams.get(FIX_KEY) || 0;\n if(registration.active && !navigator.serviceWorker.controller) {\n if(swfix >= 3) {\n throw new Error('no controller');\n }\n\n // ! doubtful fix for hard refresh\n return registration.unregister().then(() => {\n url.searchParams.set(FIX_KEY, '' + (swfix + 1));\n window.location.href = url.toString();\n });\n }\n\n if(swfix) {\n url.searchParams.delete(FIX_KEY);\n history.pushState(undefined, '', url);\n }\n\n const sw = registration.installing || registration.waiting || registration.active;\n sw.addEventListener('statechange', (e) => {\n this.log('SW statechange', e);\n });\n\n const controller = navigator.serviceWorker.controller || registration.installing || registration.waiting || registration.active;\n this.attachServiceWorker(controller);\n\n if(import.meta.env.VITE_MTPROTO_SW) {\n this.onWorkerFirstMessage(controller);\n }\n }).catch((err) => {\n this.log.error('SW registration failed!', err);\n\n this.invokeVoid('serviceWorkerOnline', false);\n });\n }\n\n private registerServiceWorker() {\n if(!('serviceWorker' in navigator)) return;\n\n this.serviceMessagePort = webPushApiManager.serviceMessagePort = new ServiceMessagePort<true>();\n\n // this.addMultipleEventsListeners({\n // hello: () => {\n // // this.serviceMessagePort.invokeVoid('port', undefined);\n // }\n // });\n\n // ! I hate webpack - it won't load it by using worker.register, only navigator.serviceWorker will do it.\n const worker = navigator.serviceWorker;\n this._registerServiceWorker();\n\n // worker.startMessages();\n\n worker.addEventListener('controllerchange', () => {\n this.log.warn('controllerchange');\n\n const controller = worker.controller;\n this.attachServiceWorker(controller);\n\n controller.addEventListener('error', (e) => {\n this.log.error('controller error:', e);\n });\n });\n\n if(import.meta.env.VITE_MTPROTO_SW) {\n this.attachListenPort(worker);\n } else {\n this.serviceMessagePort.attachListenPort(worker);\n this.serviceMessagePort.addMultipleEventsListeners({\n port: (payload, source, event) => {\n this.log.warn('got service worker port');\n this.invokeVoid('serviceWorkerPort', undefined, undefined, [event.ports[0]]);\n },\n\n hello: (payload, source) => {\n this.serviceMessagePort.resendLockTask(source);\n },\n\n share: (payload) => {\n this.log('will try to share something');\n this.share = payload;\n }\n });\n }\n\n worker.addEventListener('messageerror', (e) => {\n this.log.error('SW messageerror:', e);\n });\n }\n\n private async registerCryptoWorker() {\n const get = (url: string) => {\n return fetch(url).then((response) => response.text()).then((text) => {\n const pathnameSplitted = location.pathname.split('/');\n pathnameSplitted[pathnameSplitted.length - 1] = '';\n const pre = location.origin + pathnameSplitted.join('/');\n text = text.replace(/(import (?:.+? from )?['\"])\\//g, '$1' + pre);\n const blob = new Blob([text], {type: 'application/javascript'});\n return blob;\n });\n };\n\n const workerHandler = {\n construct(target: any, args: any): any {\n return {\n url: makeWorkerURL(args[0]).toString()\n };\n }\n };\n\n const originals = [\n Worker,\n typeof(SharedWorker) !== 'undefined' && SharedWorker\n ].filter(Boolean);\n originals.forEach((w) => window[w.name as any] = new Proxy(w, workerHandler));\n\n const worker: SharedWorker | Worker = new Worker(\n new URL('../crypto/crypto.worker.ts', import.meta.url),\n {type: 'module'}\n );\n\n originals.forEach((w) => window[w.name as any] = w as any);\n\n const originalUrl = (worker as any).url;\n\n const createWorker = (url: string) => new constructor(url, {type: 'module'});\n const attachWorkerToPort = (worker: SharedWorker | Worker) => this.attachWorkerToPort(worker, cryptoMessagePort, 'crypto');\n const constructor = IS_SHARED_WORKER_SUPPORTED ? SharedWorker : Worker;\n\n // let cryptoWorkers = workers.length;\n cryptoMessagePort.addEventListener('port', (payload, source, event) => {\n this.invokeVoid('cryptoPort', undefined, undefined, [event.ports[0]]);\n // .then((attached) => {\n // if(!attached && cryptoWorkers-- > 1) {\n // this.log.error('terminating unneeded crypto worker');\n\n // cryptoMessagePort.invokeVoid('terminate', undefined, source);\n // const worker = workers.find((worker) => (worker as SharedWorker).port === source || (worker as any) === source);\n // if((worker as SharedWorker).port) (worker as SharedWorker).port.close();\n // else (worker as Worker).terminate();\n // cryptoMessagePort.detachPort(source);\n // }\n // });\n });\n\n const firstWorker = createWorker(originalUrl);\n attachWorkerToPort(firstWorker);\n\n const blob = await get(originalUrl);\n const urlsPromise = await this.invoke('createProxyWorkerURLs', {originalUrl, blob});\n const workers = urlsPromise.slice(1).map(createWorker);\n workers.forEach(attachWorkerToPort);\n }\n\n private registerWorker() {\n if(import.meta.env.VITE_MTPROTO_SW) {\n return;\n }\n\n let worker: SharedWorker | Worker;\n if(IS_SHARED_WORKER_SUPPORTED) {\n worker = new SharedWorker(\n new URL('./mtproto.worker.ts', import.meta.url),\n {type: 'module'}\n );\n } else {\n worker = new Worker(\n new URL('./mtproto.worker.ts', import.meta.url),\n {type: 'module'}\n );\n }\n\n this.onWorkerFirstMessage(worker);\n }\n\n private attachWorkerToPort(worker: SharedWorker | Worker, messagePort: SuperMessagePort<any, any, any>, type: string) {\n const port: MessagePort = (worker as SharedWorker).port || worker as any;\n messagePort.attachPort(port);\n\n worker.addEventListener('error', (err) => {\n this.log.error(type, 'worker error', err);\n });\n }\n\n private onWorkerFirstMessage(worker: any) {\n this.log('set webWorker');\n\n // this.worker = worker;\n if(import.meta.env.VITE_MTPROTO_SW) {\n this.attachSendPort(worker);\n } else {\n this.attachWorkerToPort(worker, this, 'mtproto');\n }\n }\n\n private loadState() {\n return Promise.all([\n loadState().then((stateResult) => {\n this.newVersion = stateResult.newVersion;\n this.oldVersion = stateResult.oldVersion;\n this.mirrors['state'] = stateResult.state;\n setAppStateSilent(stateResult.state);\n return stateResult;\n })\n // loadStorages(createStorages()),\n ]);\n }\n\n public sendState() {\n return this.loadState().then((result) => {\n const [stateResult] = result;\n this.invoke('state', {...stateResult, userId: rootScope.myId.toUserId()});\n return result;\n });\n }\n\n public invokeCrypto<Method extends keyof CryptoMethods>(method: Method, ...args: Parameters<CryptoMethods[typeof method]>): Promise<Awaited<ReturnType<CryptoMethods[typeof method]>>> {\n if(!import.meta.env.VITE_MTPROTO_WORKER) {\n return;\n }\n\n return cryptoMessagePort.invokeCrypto(method, ...args);\n }\n\n public async toggleStorages(enabled: boolean, clearWrite: boolean) {\n await toggleStorages(enabled, clearWrite);\n this.invoke('toggleStorages', {enabled, clearWrite});\n this.serviceMessagePort?.invokeVoid('toggleStorages', {enabled, clearWrite});\n }\n\n public async getMirror<T extends keyof Mirrors>(name: T) {\n const mirror = this.mirrors[name];\n return mirror;\n }\n\n public getState() {\n return this.getMirror('state');\n }\n\n public getCacheContext(\n media: ThumbStorageMedia,\n thumbSize: string = THUMB_TYPE_FULL,\n key = getThumbKey(media)\n ) {\n const cache = this.mirrors.thumbs[key];\n return cache?.[thumbSize] || generateEmptyThumb(thumbSize);\n }\n\n public getStickerCachedThumb(docId: DocId, toneIndex: string | number) {\n const key = getStickerThumbKey(docId, toneIndex);\n return this.mirrors.stickerThumbs[key];\n }\n\n public getAvailableReactions() {\n return this.mirrors.availableReactions ||= rootScope.managers.appReactionsManager.getAvailableReactions();\n }\n\n public getReaction(reaction: string) {\n return callbackify(this.getAvailableReactions(), (availableReactions) => {\n return availableReactions.find((availableReaction) => availableReaction.reaction === reaction);\n });\n }\n\n public getMessageFromStorage(key: MessagesStorageKey, mid: number) {\n // * use global storage instead\n if(key.endsWith('history') && isLegacyMessageId(mid)) {\n key = this.getGlobalHistoryMessagesStorage();\n }\n\n const cache = this.mirrors.messages[key];\n return cache?.[mid];\n }\n\n public getGroupsFirstMessage(message: Message.message) {\n if(!message?.grouped_id) return message;\n\n const storage = this.mirrors.groupedMessages[message.grouped_id];\n let minMid = Number.MAX_SAFE_INTEGER;\n for(const [mid, message] of storage) {\n if(message.mid < minMid) {\n minMid = message.mid;\n }\n }\n\n return storage.get(minMid);\n }\n\n public getMidsByGroupedId(groupedId: string, sort: 'asc' | 'desc' = 'asc') {\n return getObjectKeysAndSort(this.mirrors.groupedMessages[groupedId], sort);\n }\n\n public getMessagesByGroupedId(groupedId: string) {\n const mids = this.getMidsByGroupedId(groupedId, 'asc');\n const storage = this.mirrors.groupedMessages[groupedId];\n // return mids.map((mid) => this.getMessageFromStorage(storage, mid) as Message.message);\n return mids.map((mid) => storage.get(mid) as Message.message);\n }\n\n public getHistoryMessagesStorage(peerId: PeerId): MessagesStorageKey {\n return `${peerId}_history`;\n }\n\n public getGlobalHistoryMessagesStorage(): MessagesStorageKey {\n return this.getHistoryMessagesStorage(NULL_PEER_ID);\n }\n\n public getMessageById(messageId: number) {\n if(isLegacyMessageId(messageId)) {\n return this.getMessageFromStorage(this.getGlobalHistoryMessagesStorage(), messageId);\n }\n }\n\n public getMessageByPeer(peerId: PeerId, messageId: number) {\n if(!peerId) {\n return this.getMessageById(messageId);\n }\n\n return this.getMessageFromStorage(this.getHistoryMessagesStorage(peerId), messageId);\n }\n\n public getPeer(peerId: PeerId) {\n return this.mirrors.peers[peerId];\n }\n\n public getUser(userId: UserId) {\n return this.mirrors.peers[userId.toPeerId(false)] as User.user;\n }\n\n public getChat(chatId: ChatId) {\n return this.mirrors.peers[chatId.toPeerId(true)] as Exclude<Chat, Chat.chatEmpty>;\n }\n\n public isForum(peerId: PeerId) {\n const peer = this.getPeer(peerId);\n return !!(peer as Chat.channel)?.pFlags?.forum;\n }\n\n public isAvatarCached(peerId: PeerId, size?: PeerPhotoSize) {\n const saved = this.mirrors.avatars[peerId];\n if(size === undefined) {\n return !!saved;\n }\n\n return !!(saved && saved[size] && !(saved[size] instanceof Promise));\n }\n\n public loadAvatar(peerId: PeerId, photo: UserProfilePhoto.userProfilePhoto | ChatPhoto.chatPhoto, size: PeerPhotoSize) {\n const saved = this.mirrors.avatars[peerId] ??= {};\n return saved[size] ??= rootScope.managers.appAvatarsManager.loadAvatar(peerId, photo, size);\n }\n\n public getAppConfig(overwrite?: boolean) {\n if(overwrite) {\n this.appConfig = undefined;\n }\n\n if(!this.appConfig) {\n const promise = rootScope.managers.apiManager.getAppConfig().then((appConfig) => {\n if(this.appConfig === promise) {\n this.appConfig = appConfig;\n }\n\n return appConfig;\n });\n\n return this.appConfig = promise;\n }\n\n return this.appConfig;\n }\n\n public isPremiumFeaturesHidden(): MaybePromise<boolean> {\n return callbackify(this.isPremiumPurchaseBlocked(), (isPremiumPurchaseBlocked) => {\n return isPremiumPurchaseBlocked && !rootScope.premium;\n });\n }\n\n public isPremiumPurchaseBlocked(): MaybePromise<boolean> {\n return callbackify(this.getAppConfig(), (appConfig) => {\n return !!appConfig.premium_purchase_blocked;\n });\n }\n\n public updateTabState<T extends keyof TabState>(key: T, value: TabState[T]) {\n this.tabState[key] = value;\n this.invokeVoid('tabState', this.tabState);\n }\n\n public updateTabStateIdle(idle: boolean) {\n this.updateTabState('idleStartTime', idle ? Date.now() : 0);\n }\n\n private onMirrorTask = (payload: MirrorTaskPayload) => {\n const {name, key, value} = payload;\n this.processMirrorTaskMap[name]?.(payload);\n if(!payload.hasOwnProperty('key')) {\n this.mirrors[name] = value;\n return;\n }\n\n const mirror = this.mirrors[name] ??= {} as any;\n setDeepProperty(mirror, key, value, true);\n };\n}\n\ninterface ApiManagerProxy extends MTProtoMessagePort<true> {}\n\nconst apiManagerProxy = new ApiManagerProxy();\nMOUNT_CLASS_TO.apiManagerProxy = apiManagerProxy;\nexport default apiManagerProxy;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type createManagers from './createManagers';\nimport type {AckedResult} from '../mtproto/superMessagePort';\nimport {ModifyFunctionsToAsync} from '../../types';\nimport apiManagerProxy from '../mtproto/mtprotoworker';\nimport DEBUG from '../../config/debug';\nimport dT from '../../helpers/dT';\nimport noop from '../../helpers/noop';\nimport copy from '../../helpers/object/copy';\n\n// let stats: {\n// [manager: string]: {\n// [method: string]: {\n// times: number[],\n// byArgs: {\n// [args: string]: number[]\n// }\n// }\n// }\n// } = {};\n\n// let sentCount = 0;\n// let sentMethods: {[key: string]: number} = {};\n// let sentMethods2: {[key: string]: number} = {};\n// function collectStats(manager: string, method: string, args: any[], promise: Promise<any>) {\n// ++sentCount;\n\n// const key = [manager, method].join('-');\n// if(!sentMethods[key]) sentMethods[key] = 0;\n// ++sentMethods[key];\n\n// const key2 = [('00000' + sentCount).slice(-5), key].join('-');\n\n// const byManager = stats[manager] ??= {};\n// const byMethod = byManager[method] ??= {times: [], byArgs: {}};\n\n// const perf = performance.now();\n// promise.catch(noop).finally(() => {\n// const time = performance.now() - perf;\n// byMethod.times.push(time);\n\n// sentMethods2[key2] = time;\n\n// try {\n// const argsString = JSON.stringify(args);\n// byMethod.byArgs[argsString].push(time);\n// } catch(err) {}\n// });\n// }\n\n// setInterval(() => {\n// console.log(\n// dT(),\n// '[PROXY] stats',\n// ...[\n// stats,\n// sentCount,\n// sentMethods,\n// sentMethods2\n// ].map(copy),\n// Object.entries(sentMethods).sort((a, b) => b[1] - a[1])\n// );\n// sentCount = 0;\n// stats = {};\n// sentMethods = {};\n// sentMethods2 = {};\n// }, 2000);\n\nconst DEBUG_MANAGER_REQUESTS: {[managerName: string]: Set<string>} = {\n // appProfileManager: new Set(['getProfile', 'getProfileByPeerId'])\n // appPeersManager: new Set(['getPeer'])\n // appChatsManager: new Set(['getChat'])\n // appMessagesManager: new Set(['getMessageByPeer', 'getGroupsFirstMessage'])\n};\n\nfunction createProxy(/* source: T, */name: string, ack?: boolean) {\n const proxy = new Proxy({}, {\n get: (target, p, receiver) => {\n // console.log('get', target, p, receiver);\n // @ts-ignore\n // const value = source[p];\n // if(typeof(value) !== 'function') {\n // return value;\n // }\n\n return (...args: any[]) => {\n const promise = apiManagerProxy.invoke('manager', {\n name,\n method: p as string,\n args\n }, ack as any);\n\n if(DEBUG) {\n if(DEBUG_MANAGER_REQUESTS[name]?.has(p as any)) {\n console.warn('manager request', name, p, args, ack);\n }\n }\n\n // collectStats(name, p as string, args, promise);\n\n return promise;\n\n // @ts-ignore\n // return Promise.resolve(value.call(source, ...args));\n };\n }\n });\n\n return proxy;\n}\n\ntype AA<T> = {\n [key in keyof T]: T[key] extends (...args: infer A) => infer R ? (...args: A) => Promise<AckedResult<Awaited<R>>> : never\n};\n\ntype T = Awaited<ReturnType<typeof createManagers>>;\ntype ProxiedManagers = {\n [name in keyof T]?: ModifyFunctionsToAsync<T[name]>;\n} & {\n acknowledged?: {\n [name in keyof T]?: AA<T[name]>;\n }\n};\n\nfunction createProxyProxy(proxied: any, ack?: boolean) {\n return new Proxy(proxied, {\n get: (target, p, receiver) => {\n // @ts-ignore\n return target[p] ??= createProxy(p as string, ack);\n }\n });\n}\n\nlet proxied: ProxiedManagers;\nexport default function getProxiedManagers() {\n if(proxied) {\n return proxied;\n }\n\n proxied = createProxyProxy({}, false);\n proxied.acknowledged = createProxyProxy({}, true);\n return proxied;\n}\n","export default function clamp(v: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, v));\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {WallPaper} from '../layer';\nimport clamp from './number/clamp';\n\nexport type ColorHsla = {\n h: number,\n s: number,\n l: number,\n a: number\n};\n\nexport type ColorRgba = [number, number, number, number];\nexport type ColorRgb = [number, number, number];\n\n/**\n * https://stackoverflow.com/a/54070620/6758968\n * r, g, b in [0, 255]\n * @returns h in [0,360) and s, v in [0,1]\n */\nexport function rgbToHsv(r: number, g: number, b: number): [number, number, number] {\n r /= 255, g /= 255, b /= 255;\n const v = Math.max(r, g, b),\n c = v - Math.min(r, g, b);\n const h = c && ((v === r) ? (g - b ) / c : ((v == g) ? 2 + (b - r) / c : 4 + (r - g) / c));\n return [60 * (h < 0 ? h + 6 : h), v && c / v, v];\n}\n\n/**\n * https://stackoverflow.com/a/54024653/6758968\n * @param h [0, 360]\n * @param s [0, 1]\n * @param v [0, 1]\n * @returns r, g, b in [0, 255]\n */\nexport function hsvToRgb(h: number, s: number, v: number): ColorRgb {\n const f = (n: number, k: number = (n + h / 60) % 6) => Math.round((v - v * s * Math.max(Math.min(k, 4 - k, 1), 0)) * 255);\n return [f(5), f(3), f(1)];\n}\n\n/**\n * @returns h [0, 360], s [0, 100], l [0, 100], a [0, 1]\n */\nexport function rgbaToHsla(r: number, g: number, b: number, a: number = 1): ColorHsla {\n r /= 255, g /= 255, b /= 255;\n const max = Math.max(r, g, b),\n min = Math.min(r, g, b);\n let h: number, s: number;\n const l = (max + min) / 2;\n\n if(max === min) {\n h = s = 0; // achromatic\n } else {\n const d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch(max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n\n return {\n h: h * 360,\n s: s * 100,\n l: l * 100,\n a\n };\n}\n\nexport function hslaToString(hsla: ColorHsla) {\n return `hsla(${hsla.h}, ${hsla.s}%, ${hsla.l}%, ${hsla.a})`;\n}\n\n// * https://stackoverflow.com/a/9493060/6758968\n/**\n * Converts an HSL color value to RGB. Conversion formula\n * adapted from http://en.wikipedia.org/wiki/HSL_color_space.\n *\n * @param {number} h The hue [0, 360]\n * @param {number} s The saturation [0, 1]\n * @param {number} l The lightness [0, 1]\n * @return {Array} The RGB representation [0, 255]\n */\nexport function hslaToRgba(h: number, s: number, l: number, a: number): ColorRgba {\n h /= 360, s /= 100, l /= 100;\n let r: number, g: number, b: number;\n\n if(s === 0) {\n r = g = b = l; // achromatic\n } else {\n const hue2rgb = function hue2rgb(p: number, q: number, t: number) {\n if(t < 0) t += 1;\n if(t > 1) t -= 1;\n if(t < 1/6) return p + (q - p) * 6 * t;\n if(t < 1/2) return q;\n if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;\n return p;\n }\n\n const q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n const p = 2 * l - q;\n r = hue2rgb(p, q, h + 1/3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1/3);\n }\n\n return [r, g, b, a].map((v) => Math.round(v * 255)) as ColorRgba;\n}\n\nexport function hslaStringToRgba(hsla: string) {\n const splitted = hsla.slice(5, -1).split(', ');\n const alpha = +splitted.pop();\n const arr = splitted.map((val) => {\n if(val.endsWith('%')) {\n return +val.slice(0, -1);\n }\n\n return +val;\n });\n\n return hslaToRgba(arr[0], arr[1], arr[2], alpha);\n}\n\nexport function hexaToRgba(hexa: string) {\n const arr: ColorRgba = [] as any;\n const offset = hexa[0] === '#' ? 1 : 0;\n if(hexa.length === (5 + offset)) {\n hexa = (offset ? '#' : '') + '0' + hexa.slice(offset);\n }\n\n if(hexa.length === (3 + offset)) {\n for(let i = offset; i < hexa.length; ++i) {\n arr.push(parseInt(hexa[i] + hexa[i], 16));\n }\n } else if(hexa.length === (4 + offset)) {\n for(let i = offset; i < (hexa.length - 1); ++i) {\n arr.push(parseInt(hexa[i] + hexa[i], 16));\n }\n\n arr.push(parseInt(hexa[hexa.length - 1], 16));\n } else {\n for(let i = offset; i < hexa.length; i += 2) {\n arr.push(parseInt(hexa.slice(i, i + 2), 16));\n }\n }\n\n return arr;\n}\n\nexport function hexToRgb(hex: string) {\n return hexaToRgba(hex.slice(0, 7)) as any as ColorRgb;\n}\n\nexport function hexaToHsla(hexa: string) {\n const rgba = hexaToRgba(hexa);\n return rgbaToHsla(rgba[0], rgba[1], rgba[2], rgba[3]);\n}\n\nexport function rgbaToHexa(rgba: ColorRgba | ColorRgb) {\n return '#' + rgba.map((v) => ('0' + v.toString(16)).slice(-2)).join('');\n}\n\nexport function hslaStringToHexa(hsla: string) {\n return rgbaToHexa(hslaStringToRgba(hsla));\n}\n\nexport function hslaStringToHex(hsla: string) {\n return hslaStringToHexa(hsla).slice(0, -2);\n}\n\n/**\n * @param weight [0, 1]\n */\nexport function mixColors(color1: ColorRgb, color2: ColorRgb, weight: number) {\n const out = new Array<number>(3) as ColorRgb;\n for(let i = 0; i < 3; ++i) {\n const v1 = color1[i], v2 = color2[i];\n out[i] = Math.floor(v2 + (v1 - v2) * weight);\n }\n\n return out;\n}\n\nexport function computePerceivedBrightness(color: ColorRgb) {\n return (color[0] * 0.2126 + color[1] * 0.7152 + color[2] * 0.0722) / 255;\n}\n\nexport function getAverageColor(color1: ColorRgb, color2: ColorRgb): ColorRgb {\n return color1.map((v, i) => Math.round((v + color2[i]) / 2)) as ColorRgb;\n}\n\nexport function getAccentColor(baseHsv: number[], baseColor: ColorRgb, elementColor: ColorRgb): ColorRgb {\n const hsvTemp3 = rgbToHsv(...baseColor);\n const hsvTemp4 = rgbToHsv(...elementColor);\n\n const dist = Math.min(1.5 * hsvTemp3[1] / baseHsv[1], 1);\n\n hsvTemp3[0] = Math.min(360, hsvTemp4[0] - hsvTemp3[0] + baseHsv[0]);\n hsvTemp3[1] = Math.min(1, hsvTemp4[1] * baseHsv[1] / hsvTemp3[1]);\n hsvTemp3[2] = Math.min(1, (hsvTemp4[2] / hsvTemp3[2] + dist - 1) * baseHsv[2] / dist);\n if(hsvTemp3[2] < 0.3) {\n return elementColor;\n }\n return hsvToRgb(...hsvTemp3);\n}\n\nexport function changeColorAccent(baseHsv: number[], accentHsv: number[], color: ColorRgb, isDarkTheme: boolean) {\n const colorHsv = rgbToHsv(...color);\n\n const diffH = Math.min(Math.abs(colorHsv[0] - baseHsv[0]), Math.abs(colorHsv[0] - baseHsv[0] - 360));\n if(diffH > 30) {\n return color;\n }\n\n const dist = baseHsv[1] ? Math.min(1.5 * colorHsv[1] / baseHsv[1], 1) : 0;\n\n colorHsv[0] = Math.min(360, colorHsv[0] + accentHsv[0] - baseHsv[0]);\n colorHsv[1] = baseHsv[1] ? Math.min(1, colorHsv[1] * accentHsv[1] / baseHsv[1]) : 0;\n colorHsv[2] = baseHsv[2] ? Math.min(1, colorHsv[2] * (1 - dist + dist * accentHsv[2] / baseHsv[2])) : 0;\n\n let newColor = hsvToRgb(...colorHsv);\n\n const origBrightness = computePerceivedBrightness(color);\n const newBrightness = computePerceivedBrightness(newColor);\n\n // We need to keep colors lighter in dark themes and darker in light themes\n const needRevertBrightness = isDarkTheme ? origBrightness > newBrightness : origBrightness < newBrightness;\n\n if(needRevertBrightness) {\n const amountOfNew = 0.6;\n const fallbackAmount = (1 - amountOfNew) * origBrightness / newBrightness + amountOfNew;\n newColor = changeBrightness(newColor, fallbackAmount);\n }\n\n return newColor;\n}\n\nexport function changeBrightness(color: ColorRgb, amount: number) {\n return color.map((v) => clamp(Math.round(v * amount), 0, 255)) as ColorRgb;\n}\n\nexport function getHexColorFromTelegramColor(color: number) {\n const hex = (color < 0 ? 0xFFFFFF + color : color).toString(16);\n return '#' + (hex.length >= 6 ? hex : '0'.repeat(6 - hex.length) + hex);\n}\n\nexport function getRgbColorFromTelegramColor(color: number) {\n return hexToRgb(getHexColorFromTelegramColor(color));\n}\n\nexport function getColorsFromWallPaper(wallPaper: WallPaper) {\n return wallPaper.settings ? [\n wallPaper.settings.background_color,\n wallPaper.settings.second_background_color,\n wallPaper.settings.third_background_color,\n wallPaper.settings.fourth_background_color\n ].filter(Boolean).map(getHexColorFromTelegramColor).join(',') : '';\n}\n\nexport function rgbaToRgb(rgba: ColorRgba, bg: ColorRgb): ColorRgb {\n const a = rgba[3];\n return rgba.slice(0, 3).map((color, idx) => {\n return clamp(Math.round((a * (color / 255) + (a * (bg[idx] / 255))) * 255), 0, 255);\n }) as ColorRgb;\n}\n\nexport function calculateLuminance(rgb: ColorRgb) {\n const [r, g, b] = rgb;\n const luminance = (0.2126 * r / 255 + 0.7152 * g / 255 + 0.0722 * b / 255);\n return luminance;\n}\n\nexport function getTextColor(luminance: number): ColorRgb {\n return luminance > 0.5 ? [0, 0, 0] : [255, 255, 255];\n}\n\nexport function calculateOpacity(luminance: number, targetContrast: number) {\n const targetTextLuminance = luminance > 0.5 ? 0 : 1;\n const adaptiveOpacity = (luminance - targetTextLuminance + targetContrast) / targetContrast;\n const opacity = +Math.max(0.5, Math.min(0.64, adaptiveOpacity)).toFixed(2);\n\n return opacity;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n *\n * Originally from:\n * https://github.com/zhukov/webogram\n * Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>\n * https://github.com/zhukov/webogram/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport {makeMediaSize} from './mediaSize';\n\nexport default function calcImageInBox(imageW: number, imageH: number, boxW: number, boxH: number, noZoom = true) {\n if(imageW < boxW && imageH < boxH && noZoom) {\n return makeMediaSize(imageW, imageH);\n }\n\n let boxedImageW = boxW;\n let boxedImageH = boxH;\n\n if((imageW / imageH) > (boxW / boxH)) {\n boxedImageH = (imageH * boxW / imageW) | 0;\n } else {\n boxedImageW = (imageW * boxH / imageH) | 0;\n if(boxedImageW > boxW) {\n boxedImageH = (boxedImageH * boxW / boxedImageW) | 0;\n boxedImageW = boxW;\n }\n }\n\n if(noZoom && boxedImageW >= imageW && boxedImageH >= imageH) {\n boxedImageW = imageW;\n boxedImageH = imageH;\n }\n\n return makeMediaSize(boxedImageW, boxedImageH);\n}\n\nMOUNT_CLASS_TO.calcImageInBox = calcImageInBox;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport calcImageInBox from './calcImageInBox';\n\nexport class MediaSize {\n constructor(public width = 0, public height = width) {\n\n }\n\n public aspect(boxSize: MediaSize, fitted: boolean) {\n return calcImageInBox(this.width, this.height, boxSize.width, boxSize.height, fitted);\n }\n\n public aspectFitted(boxSize: MediaSize) {\n return this.aspect(boxSize, true);\n }\n\n public aspectCovered(boxSize: MediaSize) {\n return this.aspect(boxSize, false);\n }\n}\n\nexport function makeMediaSize(width?: number, height?: number): MediaSize {\n return new MediaSize(width, height);\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport EventListenerBase from './eventListenerBase';\nimport {makeMediaSize, MediaSize} from './mediaSize';\n\ntype MediaTypeSizes = {\n regular: MediaSize,\n webpage: MediaSize,\n album: MediaSize,\n esgSticker: MediaSize,\n animatedSticker: MediaSize,\n staticSticker: MediaSize,\n emojiSticker: MediaSize,\n poll: MediaSize,\n round: MediaSize,\n documentName: MediaSize,\n invoice: MediaSize,\n extendedInvoice: MediaSize,\n customEmoji: MediaSize,\n esgCustomEmoji: MediaSize,\n emojiStatus: MediaSize,\n popupSticker: MediaSize\n};\n\nexport type MediaSizeType = keyof MediaTypeSizes;\n\nexport enum ScreenSize {\n mobile,\n medium,\n large\n}\n\nconst MOBILE_SIZE = 600;\nconst MEDIUM_SIZE = 1275;\nconst LARGE_SIZE = 1680;\n\nconst CUSTOM_EMOJI_SIZE = makeMediaSize(20, 20);\nconst ESG_CUSTOM_EMOJI_SIZE = makeMediaSize(36, 36);\nconst EMOJI_STATUS_SIZE = makeMediaSize(18, 18);\n\nclass MediaSizes extends EventListenerBase<{\n changeScreen: (from: ScreenSize, to: ScreenSize) => void,\n resize: () => void\n}> {\n private screenSizes: {key: ScreenSize, value: number}[] = [\n {key: ScreenSize.mobile, value: MOBILE_SIZE},\n {key: ScreenSize.medium, value: MEDIUM_SIZE},\n {key: ScreenSize.large, value: LARGE_SIZE}\n ];\n\n private sizes: {[k in 'desktop' | 'handhelds']: MediaTypeSizes} = {\n handhelds: {\n regular: makeMediaSize(340, 340),\n webpage: makeMediaSize(340, 200),\n album: makeMediaSize(340, 0),\n esgSticker: makeMediaSize(68, 68),\n animatedSticker: makeMediaSize(180, 180),\n staticSticker: makeMediaSize(180, 180),\n emojiSticker: makeMediaSize(112, 112),\n poll: makeMediaSize(240, 0),\n round: makeMediaSize(240, 240),\n documentName: makeMediaSize(200, 0),\n invoice: makeMediaSize(340, 340),\n extendedInvoice: makeMediaSize(340, 340),\n customEmoji: CUSTOM_EMOJI_SIZE,\n esgCustomEmoji: ESG_CUSTOM_EMOJI_SIZE,\n emojiStatus: EMOJI_STATUS_SIZE,\n popupSticker: makeMediaSize(68, 68)\n },\n desktop: {\n regular: makeMediaSize(420, 400),\n webpage: makeMediaSize(420, 380),\n album: makeMediaSize(420, 0),\n esgSticker: makeMediaSize(72, 72),\n animatedSticker: makeMediaSize(200, 200),\n staticSticker: makeMediaSize(200, 200),\n emojiSticker: makeMediaSize(112, 112),\n poll: makeMediaSize(330, 0),\n round: makeMediaSize(280, 280),\n documentName: makeMediaSize(240, 0),\n invoice: makeMediaSize(320, 320),\n extendedInvoice: makeMediaSize(420, 400),\n customEmoji: CUSTOM_EMOJI_SIZE,\n esgCustomEmoji: ESG_CUSTOM_EMOJI_SIZE,\n emojiStatus: EMOJI_STATUS_SIZE,\n popupSticker: makeMediaSize(80, 80)\n }\n };\n\n public isMobile = false;\n public active: MediaTypeSizes;\n public activeScreen: ScreenSize;\n private rAF: number;\n\n constructor() {\n super();\n\n window.addEventListener('resize', () => {\n if(this.rAF) window.cancelAnimationFrame(this.rAF);\n this.rAF = window.requestAnimationFrame(() => {\n this.handleResize();\n this.rAF = 0;\n });\n });\n this.handleResize();\n }\n\n private handleResize = () => {\n const innerWidth = window.innerWidth;\n // this.isMobile = innerWidth <= 720;\n\n let activeScreen = this.screenSizes[0].key;\n for(let i = this.screenSizes.length - 1; i >= 0; --i) {\n if(this.screenSizes[i].value < innerWidth) {\n activeScreen = (this.screenSizes[i + 1] || this.screenSizes[i]).key;\n break;\n }\n }\n\n const wasScreen = this.activeScreen;\n this.activeScreen = activeScreen;\n this.isMobile = this.activeScreen === ScreenSize.mobile;\n this.active = this.isMobile ? this.sizes.handhelds : this.sizes.desktop;\n\n // console.time('esg');\n // const computedStyle = window.getComputedStyle(document.documentElement);\n // this.active.esgSticker.width = parseFloat(computedStyle.getPropertyValue('--esg-sticker-size'));\n // console.timeEnd('esg');\n\n if(wasScreen !== activeScreen) {\n // console.log('changeScreen', this.activeScreen, activeScreen);\n\n if(wasScreen !== undefined) {\n this.dispatchEvent('changeScreen', wasScreen, activeScreen);\n }\n }\n\n if(wasScreen !== undefined) {\n this.dispatchEvent('resize');\n }\n\n /* if(this.isMobile) {\n for(let i in this.active) {\n // @ts-ignore\n let size = this.active[i];\n size.width = innerWidth\n }\n } */\n };\n}\n\nconst mediaSizes = new MediaSizes();\nMOUNT_CLASS_TO.mediaSizes = mediaSizes;\nexport default mediaSizes;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../../config/debug';\nimport rootScope from '../../lib/rootScope';\nimport mediaSizes from '../mediaSizes';\n\nexport type CustomProperty = string;\n\nexport class CustomProperties {\n private cache: {[k in CustomProperty]?: [string, string]};\n private computedStyle: CSSStyleDeclaration;\n private nightComputedStyle: CSSStyleDeclaration;\n private nightElement: HTMLElement;\n\n constructor() {\n this.cache = {};\n\n this.nightElement = document.createElement('div');\n this.nightElement.className = 'night';\n this.nightElement.style.display = 'none';\n document.body.append(this.nightElement);\n\n rootScope.addEventListener('theme_changed', this.resetCache);\n mediaSizes.addEventListener('resize', this.resetCache);\n }\n\n protected resetCache = () => {\n this.computedStyle = undefined;\n const cache = this.cache;\n this.cache = {};\n\n for(const i in cache) {\n this.getProperty(i as CustomProperty);\n }\n };\n\n public getProperty(name: CustomProperty, night?: boolean) {\n const values = this.cache[name];\n const index = night ? 1 : 0;\n if(values?.[index]) {\n return values[index];\n }\n\n this.computedStyle ??= window.getComputedStyle(document.documentElement);\n this.nightComputedStyle ??= window.getComputedStyle(this.nightElement)\n\n const value = (night ? this.nightComputedStyle : this.computedStyle).getPropertyValue('--' + name).trim();\n return this.setPropertyCache(name, value, night);\n }\n\n public getPropertyAsColor(name: CustomProperty) {\n const value = this.getProperty(name);\n if(value[0] === '#') {\n return value;\n }\n\n return `rgb(${value})`;\n }\n\n public getPropertyAsSize(name: CustomProperty) {\n const value = this.getProperty(name);\n let size: number;\n\n if(value[value.length - 1] === '%') {\n\n } else if(value.indexOf('rem')) {\n size = +value.replace('rem', '') * 16;\n } else {\n size = +value.replace('px', '');\n }\n\n return size;\n }\n\n public setPropertyCache(name: CustomProperty, value: string, night?: boolean) {\n return (this.cache[name] ??= [] as any)[night ? 1 : 0] = value;\n }\n}\n\nconst customProperties = new CustomProperties();\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.customProperties = customProperties);\nexport default customProperties;\n","import {createSignal, Setter} from 'solid-js';\n\n/**\n * do not use getter in JSX\n */\nexport default function createUnifiedSignal<T = any>(...args: Partial<Parameters<typeof createSignal<T>>>) {\n const [getter, setter] = createSignal<T>(...args);\n return <A extends Parameters<Setter<T>>>(...args: Partial<A>) => {\n // @ts-ignore\n if(args.length === 0) {\n return getter();\n }\n\n // @ts-ignore\n return setter(...args);\n };\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport {IS_WORKER} from './context';\nimport createUnifiedSignal from './solid/createUnifiedSignal';\n\nexport class WindowSize {\n private _width: ReturnType<typeof createUnifiedSignal<number>>;\n private _height: ReturnType<typeof createUnifiedSignal<number>>;\n // private rAF: number;\n private viewport: VisualViewport | Window;\n\n constructor() {\n if(IS_WORKER) {\n return;\n }\n\n this._width = createUnifiedSignal();\n this._height = createUnifiedSignal();\n\n this.viewport = /* 'visualViewport' in window ? window.visualViewport : */window;\n const set = () => {\n this.setDimensions();\n\n // if(this.width === undefined) {\n // this.setDimensions();\n // return;\n // }\n\n // if(this.rAF) window.cancelAnimationFrame(this.rAF);\n // this.rAF = window.requestAnimationFrame(() => {\n // this.rAF = 0;\n\n // batch(() => {\n // this.setDimensions();\n // });\n // });\n };\n this.viewport.addEventListener('resize', set);\n set();\n }\n\n private setDimensions() {\n const w = this.viewport;\n this._width((w as VisualViewport).width || (w as Window).innerWidth);\n this._height((w as VisualViewport).height || (w as Window).innerHeight);\n }\n\n public get width() {\n return this._width();\n }\n\n public get height() {\n return this._height();\n }\n}\n\nconst windowSize = new WindowSize();\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.windowSize = windowSize);\nexport default windowSize;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport rootScope from '../lib/rootScope';\n\nexport type LiteModeKey = 'all' | 'gif' | 'video' |\n 'emoji' | 'emoji_panel' | 'emoji_messages' |\n 'effects' | 'effects_reactions' | 'effects_premiumstickers' | 'effects_emoji' |\n 'stickers' | 'stickers_panel' | 'stickers_chat' |\n 'chat' | 'chat_background' | 'chat_spoilers' | 'animations';\n\nexport class LiteMode {\n public isEnabled() {\n return !!(rootScope.settings && rootScope.settings.liteMode.all);\n }\n\n public isAvailable(key: LiteModeKey) {\n return !!(rootScope.settings && !rootScope.settings.liteMode.all && !rootScope.settings.liteMode[key]);\n }\n}\n\nconst liteMode = new LiteMode();\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.liteMode = liteMode);\nexport default liteMode;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport type {AppTheme} from '../config/state';\nimport type {Theme} from '../layer';\nimport type AppBackgroundTab from '../components/sidebarLeft/tabs/background';\nimport IS_TOUCH_SUPPORTED from '../environment/touchSupport';\nimport rootScope from '../lib/rootScope';\nimport {changeColorAccent, ColorRgb, getAccentColor, getAverageColor, getHexColorFromTelegramColor, getRgbColorFromTelegramColor, hexToRgb, hslaStringToHex, hslaStringToRgba, hslaToRgba, hsvToRgb, mixColors, rgbaToHexa, rgbaToHsla, rgbToHsv} from './color';\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport customProperties from './dom/customProperties';\nimport {TelegramWebViewTheme} from '../types';\nimport {joinDeepPath} from './object/setDeepProperty';\nimport windowSize from './windowSize';\nimport liteMode from './liteMode';\n\nexport type AppColorName = 'primary-color' | 'message-out-primary-color' |\n 'surface-color' | 'danger-color' | 'primary-text-color' |\n 'secondary-text-color' | 'message-out-background-color' |\n 'saved-color' | 'message-background-color' | 'green-color';\ntype AppColor = {\n rgb?: boolean,\n light?: boolean,\n lightFilled?: boolean,\n dark?: boolean,\n darkRgb?: boolean,\n darkFilled?: boolean\n};\n\nconst appColorMap: {[name in AppColorName]: AppColor} = {\n // 'background-color': {},\n 'primary-color': {\n rgb: true,\n light: true,\n lightFilled: true,\n dark: true,\n darkRgb: true\n },\n 'message-out-primary-color': {\n lightFilled: true,\n rgb: true\n },\n 'surface-color': {\n rgb: true\n },\n 'danger-color': {\n rgb: true,\n light: true,\n dark: true\n },\n 'primary-text-color': {\n rgb: true\n },\n 'secondary-text-color': {\n light: true,\n lightFilled: true,\n rgb: true\n },\n 'message-background-color': {\n light: true,\n lightFilled: true,\n dark: true,\n darkFilled: true\n },\n 'message-out-background-color': {\n light: true,\n lightFilled: true,\n dark: true,\n darkFilled: true,\n rgb: true\n },\n 'saved-color': {\n lightFilled: true\n },\n 'green-color': {}\n};\n\nconst colorMap: {\n [name in AppTheme['name']]?: {\n [name in AppColorName]?: string\n }\n} = {\n day: {\n // 'background-color': '#f4f4f5',\n 'primary-color': '#3390ec',\n 'message-out-primary-color': '#5CA853',\n 'message-background-color': '#ffffff',\n 'surface-color': '#ffffff',\n 'danger-color': '#df3f40',\n 'primary-text-color': '#000000',\n 'secondary-text-color': '#707579',\n 'saved-color': '#359AD4',\n 'green-color': '#70b768'\n },\n night: {\n // 'background-color': '#181818',\n 'primary-color': '#8774E1',\n 'message-out-primary-color': '#8774E1',\n 'message-background-color': '#212121',\n 'surface-color': '#212121',\n 'danger-color': '#ff595a',\n 'primary-text-color': '#ffffff',\n 'secondary-text-color': '#aaaaaa',\n 'saved-color': '#8774E1',\n 'green-color': '#5CC85E'\n }\n};\n\nexport class ThemeController {\n private themeColor: string;\n private _themeColorElem: Element;\n private systemTheme: AppTheme['name'];\n private styleElement: HTMLStyleElement;\n public AppBackgroundTab: typeof AppBackgroundTab;\n private applied: boolean;\n\n constructor() {\n rootScope.addEventListener('theme_change', (coordinates) => {\n this.setTheme(typeof(coordinates) === 'object' ? coordinates : undefined);\n });\n\n rootScope.addEventListener('theme_changed', () => {\n this.setWorkerThemeParams();\n });\n\n // rootScope.addEventListener('settings_updated', ())\n }\n\n private setWorkerThemeParams() {\n rootScope.managers.apiManager.setThemeParams({\n _: 'dataJSON',\n data: JSON.stringify(this.getThemeParamsForWebView())\n });\n }\n\n private get themeColorElem() {\n if(this._themeColorElem !== undefined) {\n return this._themeColorElem;\n }\n\n return this._themeColorElem = document.head.querySelector('[name=\"theme-color\"]') as Element || null;\n }\n\n public setThemeColor(color = this.themeColor) {\n if(!color) {\n color = this.isNight() ? '#212121' : '#ffffff';\n }\n\n const themeColorElem = this.themeColorElem;\n if(themeColorElem) {\n themeColorElem.setAttribute('content', color);\n }\n }\n\n public setThemeListener() {\n try {\n const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n const checkDarkMode = () => {\n // const theme = this.getTheme();\n this.systemTheme = darkModeMediaQuery.matches ? 'night' : 'day';\n // const newTheme = this.getTheme();\n\n if(rootScope.myId) {\n rootScope.dispatchEvent('theme_change');\n } else {\n this.setTheme();\n }\n };\n\n if('addEventListener' in darkModeMediaQuery) {\n darkModeMediaQuery.addEventListener('change', checkDarkMode);\n } else if('addListener' in darkModeMediaQuery) {\n (darkModeMediaQuery as any).addListener(checkDarkMode);\n }\n\n checkDarkMode();\n } catch(err) {\n\n }\n }\n\n public applyHighlightingColor({\n hsla,\n element = document.documentElement\n }: {\n hsla?: string,\n element?: HTMLElement\n } = {}) {\n if(!hsla) {\n hsla = 'hsla(85.5319, 36.9171%, 40.402%, .4)';\n const theme = this.getTheme();\n if(theme.settings?.highlightingColor) {\n hsla = theme.settings.highlightingColor;\n }\n }\n\n const highlightingRgba = hslaStringToRgba(hsla);\n element.style.setProperty('--message-highlighting-color', hsla);\n element.style.setProperty('--message-highlighting-color-rgb', highlightingRgba.slice(0, 3).join(','));\n element.style.setProperty('--message-highlighting-alpha', '' + highlightingRgba[3] / 255);\n\n if(!IS_TOUCH_SUPPORTED && hsla) {\n this.themeColor = hslaStringToHex(hsla);\n }\n }\n\n public _setTheme(silent?: boolean) {\n const isNight = this.isNight();\n const colorScheme = document.head.querySelector('[name=\"color-scheme\"]');\n colorScheme?.setAttribute('content', isNight ? 'dark' : 'light');\n\n document.documentElement.classList.toggle('night', isNight);\n this.setThemeColor();\n const theme = this.getTheme();\n this.applyTheme(theme);\n\n let style = this.styleElement;\n if(!style) {\n style = this.styleElement = document.createElement('style');\n document.head.append(style);\n }\n\n const e = document.createElement('div');\n this.applyTheme(rootScope.settings.themes.find((theme) => theme.name === 'night'), e, true);\n style.textContent = `.night {${e.style.cssText}}`;\n\n this.applyHighlightingColor();\n !silent && rootScope.dispatchEventSingle('theme_changed');\n }\n\n public setTheme(coordinates?: {x: number, y: number}) {\n if(!('startViewTransition' in document) || !this.applied) {\n const silent = !this.applied;\n const wasApplied = this.applied;\n this.applied = true;\n\n this._setTheme(silent);\n if(!wasApplied) {\n this.setWorkerThemeParams();\n }\n\n return;\n }\n\n if(!liteMode.isAvailable('animations')) {\n coordinates = undefined;\n }\n\n const reverse = !this.isNight();\n if(coordinates) {\n document.documentElement.classList.add('no-view-transition');\n document.documentElement.classList.toggle('reverse', reverse);\n void document.documentElement.offsetLeft; // reflow\n }\n\n const transition = (document as any).startViewTransition(() => {\n this._setTheme();\n });\n\n if(!coordinates) {\n return;\n }\n\n const {x, y} = coordinates;\n // Get the distance to the furthest corner\n const endRadius = Math.hypot(\n Math.max(x, windowSize.width - x),\n Math.max(y, windowSize.height - y)\n );\n\n transition.ready.then(() => {\n document.documentElement.animate({\n clipPath: [\n `circle(0 at ${x}px ${y}px)`,\n `circle(${endRadius}px at ${x}px ${y}px)`\n ]\n }, {\n duration: 500,\n easing: 'ease-in-out',\n pseudoElement: `::view-transition-${reverse ? 'old' : 'new'}(root)`,\n direction: reverse ? 'reverse' : 'normal'\n });\n });\n\n transition.finished.finally(() => {\n document.documentElement.classList.remove('no-view-transition', 'reverse');\n });\n }\n\n public async switchTheme(name: AppTheme['name'], coordinates?: {x: number, y: number}) {\n await rootScope.managers.appStateManager.setByKey(joinDeepPath('settings', 'theme'), name);\n rootScope.dispatchEvent('theme_change', coordinates);\n }\n\n public isNight() {\n return this.getTheme().name === 'night';\n }\n\n public getTheme(name: AppTheme['name'] = rootScope.settings.theme === 'system' ? this.systemTheme : rootScope.settings.theme) {\n return rootScope.settings.themes.find((t) => t.name === name);\n }\n\n // theme applier\n private bindColorApplier(options: Pick<Parameters<ThemeController['applyAppColor']>[0], 'element' | 'isNight' | 'saveToCache'>) {\n const appliedColors: Set<AppColorName> = new Set();\n return {\n applyAppColor: (_options: Omit<Parameters<ThemeController['applyAppColor']>[0], keyof typeof options>) => {\n appliedColors.add(_options.name);\n return this.applyAppColor({..._options, ...options});\n },\n finalize: () => {\n const isNight = options.isNight;\n for(const name in appColorMap) {\n if(!appliedColors.has(name as AppColorName)) {\n this.applyAppColor({\n name: name as AppColorName,\n hex: colorMap[isNight ? 'night' : 'day'][name as AppColorName],\n ...options\n });\n }\n }\n }\n };\n };\n\n public applyAppColor({\n name,\n hex,\n element,\n lightenAlpha = 0.08,\n darkenAlpha = lightenAlpha,\n mixColor,\n isNight = this.isNight(),\n saveToCache\n }: {\n name: AppColorName,\n hex: string,\n element: HTMLElement,\n lightenAlpha?: number\n darkenAlpha?: number,\n mixColor?: ColorRgb,\n isNight?: boolean,\n saveToCache?: boolean\n }) {\n const appColor = appColorMap[name];\n const rgb = hexToRgb(hex);\n const hsla = rgbaToHsla(...rgb);\n\n mixColor ??= hexToRgb(colorMap[isNight ? 'night' : 'day']['surface-color']);\n const lightenedRgb = mixColors(rgb, mixColor, lightenAlpha);\n\n const darkenedHsla: typeof hsla = {\n ...hsla,\n l: hsla.l - darkenAlpha * 100\n };\n\n const properties: [string, string][] = [\n [name, hex],\n appColor.rgb && [name + '-rgb', rgb.join(',')],\n appColor.light && ['light-' + name, `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${lightenAlpha})`],\n appColor.lightFilled && ['light-filled-' + name, rgbaToHexa(lightenedRgb)],\n appColor.dark && ['dark-' + name, `hsl(${darkenedHsla.h}, ${darkenedHsla.s}%, ${darkenedHsla.l}%)`]\n // appColor.darkFilled && ['dark-' + name, `hsl(${darkenedHsla.h}, ${darkenedHsla.s}%, ${darkenedHsla.l}%)`]\n ];\n\n saveToCache ??= element === document.documentElement;\n properties.filter(Boolean).forEach(([name, value]) => {\n element.style.setProperty('--' + name, value);\n\n if(saveToCache) {\n customProperties.setPropertyCache(name as AppColorName, value, isNight);\n }\n });\n }\n\n public async applyNewTheme(theme: Theme) {\n const isNight = this.isNightTheme(theme);\n const currentTheme = this.getTheme();\n const themes = rootScope.settings.themes;\n const themeSettings = theme.settings.find((themeSettings) => themeSettings.base_theme._ === (isNight ? 'baseThemeNight' : 'baseThemeClassic'));\n const newAppTheme: AppTheme = {\n ...theme,\n name: currentTheme.name,\n settings: {\n ...themeSettings,\n highlightingColor: ''\n }\n };\n\n await this.AppBackgroundTab.setBackgroundDocument(themeSettings.wallpaper, newAppTheme.settings);\n themes[themes.indexOf(currentTheme)] = newAppTheme;\n await rootScope.managers.appStateManager.setByKey(joinDeepPath('settings', 'themes'), rootScope.settings.themes);\n rootScope.dispatchEvent('theme_change');\n }\n\n private isNightTheme(theme: Theme | AppTheme) {\n return (theme as AppTheme).name === 'night' || this.isNight();\n }\n\n public getThemeSettings(theme: Theme | AppTheme, isNight?: boolean) {\n isNight ??= this.isNightTheme(theme);\n const themeSettings = Array.isArray(theme.settings) ?\n theme.settings.find((settings) => settings.base_theme._ === (isNight ? 'baseThemeNight' : 'baseThemeClassic')) :\n theme.settings;\n return themeSettings;\n }\n\n public applyTheme(theme: Theme | AppTheme, element = document.documentElement, saveToCache?: boolean) {\n const isNight = this.isNightTheme(theme);\n const themeSettings = this.getThemeSettings(theme, isNight);\n const baseColors = colorMap[isNight ? 'night' : 'day'];\n\n let hsvTemp1 = rgbToHsv(...hexToRgb(baseColors['primary-color'])); // primary base\n let hsvTemp2 = rgbToHsv(...getRgbColorFromTelegramColor(themeSettings.accent_color)); // new primary\n\n const newAccentRgb = changeColorAccent(\n hsvTemp1,\n hsvTemp2,\n hexToRgb(baseColors['primary-color']),\n !isNight\n );\n const newAccentHex = rgbaToHexa(newAccentRgb);\n\n const {applyAppColor, finalize} = this.bindColorApplier({element, isNight, saveToCache});\n\n applyAppColor({\n name: 'primary-color',\n hex: newAccentHex,\n darkenAlpha: 0.04\n });\n\n applyAppColor({\n name: 'saved-color',\n hex: newAccentHex,\n lightenAlpha: 0.64,\n mixColor: [255, 255, 255]\n });\n\n if(!themeSettings.message_colors?.length) {\n return;\n }\n\n const messageLightenAlpha = isNight ? 1 : 0.12;\n const baseMessageColor = hexToRgb(baseColors['message-out-primary-color']);\n hsvTemp1 = rgbToHsv(...baseMessageColor);\n const baseMessageOutBackgroundColor = mixColors(baseMessageColor, hexToRgb(baseColors['surface-color']), messageLightenAlpha);\n\n const firstColor = getRgbColorFromTelegramColor(themeSettings.message_colors[0]);\n\n let myMessagesAccent = firstColor;\n if(themeSettings.message_colors.length > 1) {\n // const w = getAccentColor(hsvTemp1, baseMessageOutBackgroundColor, myMessagesAccent);\n\n themeSettings.message_colors.slice(1).forEach((nextColor) => {\n myMessagesAccent = getAverageColor(myMessagesAccent, getRgbColorFromTelegramColor(nextColor));\n });\n\n myMessagesAccent = getAccentColor(hsvTemp1, baseMessageOutBackgroundColor, myMessagesAccent);\n\n // console.log('www', rgbaToHexa(w), rgbaToHexa(myMessagesAccent));\n }\n\n const o = myMessagesAccent;\n hsvTemp2 = rgbToHsv(...o);\n\n // const c = changeColorAccent(\n // hsvTemp1,\n // hsvTemp2,\n // baseMessageOutBackgroundColor\n // );\n\n // console.log(o, c, rgbaToHexa(o), rgbaToHexa(c));\n\n const accentColor2 = themeSettings.outbox_accent_color !== undefined && rgbToHsv(...getRgbColorFromTelegramColor(themeSettings.outbox_accent_color));\n\n let newMessageOutBackgroundColor = mixColors(myMessagesAccent, hexToRgb(baseColors['surface-color']), messageLightenAlpha);\n\n if(!isNight/* || true */) {\n const messageOutBackgroundColorHsl = rgbaToHsla(...newMessageOutBackgroundColor);\n messageOutBackgroundColorHsl.s = Math.min(messageOutBackgroundColorHsl.s + (isNight ? 8 : 63), 100);\n newMessageOutBackgroundColor = hslaToRgba(messageOutBackgroundColorHsl.h, messageOutBackgroundColorHsl.s, messageOutBackgroundColorHsl.l, messageOutBackgroundColorHsl.a).slice(0, 3) as ColorRgb;\n }\n\n applyAppColor({\n name: 'message-out-background-color',\n hex: rgbaToHexa(newMessageOutBackgroundColor),\n lightenAlpha: messageLightenAlpha\n });\n\n applyAppColor({\n name: 'message-out-primary-color',\n hex: isNight ? '#ffffff' : rgbaToHexa(accentColor2 ? hsvToRgb(...accentColor2) : myMessagesAccent),\n mixColor: newMessageOutBackgroundColor\n });\n\n // if(accentColor2) {\n // console.log(rgbaToHexa(myMessagesAccent), rgbaToHexa(hsvToRgb(...accentColor2)));\n // }\n\n finalize();\n }\n\n public getThemeParamsForWebView() {\n const themePropertiesMap: {[key in keyof TelegramWebViewTheme]: string} = {\n bg_color: 'surface-color',\n button_color: 'primary-color',\n button_text_color: '#ffffff',\n hint_color: 'secondary-text-color',\n link_color: 'link-color',\n secondary_bg_color: 'background-color-true',\n text_color: 'primary-text-color',\n header_bg_color: 'surface-color',\n accent_text_color: 'primary-color',\n section_bg_color: 'surface-color',\n section_header_text_color: 'primary-color',\n subtitle_text_color: 'secondary-text-color',\n destructive_text_color: 'danger-color'\n };\n\n const themeParams: TelegramWebViewTheme = {} as any;\n for(const key in themePropertiesMap) {\n const value = themePropertiesMap[key as keyof TelegramWebViewTheme];\n themeParams[key as keyof TelegramWebViewTheme] = value[0] === '#' ? value : customProperties.getProperty(value as AppColorName);\n }\n\n return themeParams;\n }\n}\n\nconst themeController = new ThemeController();\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.themeController = themeController);\nexport default themeController;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport EventListenerBase from './eventListenerBase';\n\nexport class OverlayCounter extends EventListenerBase<{\n change: (isActive: boolean) => void\n}> {\n public overlaysActive = 0;\n public hasDarkOverlays = 0;\n\n get isOverlayActive() {\n return this.overlaysActive > 0;\n }\n\n set isOverlayActive(value: boolean) {\n this.overlaysActive += value ? 1 : -1;\n this.dispatchEvent('change', this.isOverlayActive);\n }\n\n get isDarkOverlayActive() {\n return this.hasDarkOverlays > 0;\n }\n\n set isDarkOverlayActive(value: boolean) {\n this.hasDarkOverlays += value ? 1 : -1;\n this.isOverlayActive = value;\n }\n}\n\nconst overlayCounter = new OverlayCounter();\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.overlayCounter = overlayCounter);\nexport default overlayCounter;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nexport default function parseUriParams(uri: string, splitted = uri.split('?')) {\n return parseUriParamsLine(splitted?.[1]);\n}\n\nexport function parseUriParamsLine(line: string) {\n const params: any = {};\n if(!line) {\n return params;\n }\n\n line.split('&').forEach((item) => {\n const [key, value = ''] = item.split('=');\n params[key] = decodeURIComponent(value);\n });\n\n return params;\n}\n","const IS_INSTALL_PROMPT_SUPPORTED = 'onbeforeinstallprompt' in window;\nexport default IS_INSTALL_PROMPT_SUPPORTED;\n","let callback: () => Promise<void>;\nexport default function cacheInstallPrompt() {\n window.addEventListener('beforeinstallprompt', (deferredPrompt: any) => {\n callback = async() => {\n deferredPrompt.prompt();\n const {outcome} = await deferredPrompt.userChoice;\n const installed = outcome === 'accepted';\n if(installed) {\n callback = undefined;\n }\n };\n });\n}\n\nexport function getInstallPrompt() {\n return callback;\n}\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\nimport {MOUNT_CLASS_TO} from '../config/debug';\nimport I18n, {i18n} from '../lib/langPack';\nimport capitalizeFirstLetter from './string/capitalizeFirstLetter';\n\nexport const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\nexport const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nexport const monthsLocalized = months.slice();\nexport const daysLocalized = days.slice();\n\nexport const ONE_DAY = 86400;\nexport const ONE_DAY_MINUTES = 1440;\nexport const ONE_WEEK = 604800;\nexport const ONE_WEEK_MINUTES = 10080;\n\nexport function getWeekDays() {\n const dateTimeFormat = I18n.getDateTimeFormat({weekday: 'long'});\n const date = new Date(Date.UTC(2017, 0, 2));\n const out: string[] = [];\n for(let i = 0; i < 7; ++i) {\n out.push(capitalizeFirstLetter(dateTimeFormat.format(date)));\n date.setDate(date.getDate() + 1);\n }\n return out;\n}\n\nexport function getMonths() {\n const dateTimeFormat = I18n.getDateTimeFormat({month: 'long'});\n const date = new Date(Date.UTC(2017, 0, 1));\n const out: string[] = [];\n for(let i = 0; i < 12; ++i) {\n out.push(capitalizeFirstLetter(dateTimeFormat.format(date)));\n date.setMonth(date.getMonth() + 1);\n }\n return out;\n}\n\nexport function fillLocalizedDates() {\n monthsLocalized.splice(0, monthsLocalized.length, ...getMonths());\n daysLocalized.splice(0, daysLocalized.length, ...getWeekDays());\n}\n\n// https://stackoverflow.com/a/6117889\nexport const getWeekNumber = (date: Date) => {\n const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));\n const dayNum = d.getUTCDay() || 7;\n d.setUTCDate(d.getUTCDate() + 4 - dayNum);\n const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));\n return Math.ceil((((d.getTime() - yearStart.getTime()) / ONE_DAY) + 1) / 7);\n};\n\nexport function formatDate(date: Date, today?: Date) {\n if(!today) {\n today = new Date();\n today.setHours(0, 0, 0, 0);\n }\n\n const options: Intl.DateTimeFormatOptions = {\n day: 'numeric',\n month: 'long'\n };\n\n if(date.getFullYear() !== today.getFullYear()) {\n options.year = 'numeric';\n }\n\n return new I18n.IntlDateElement({\n date,\n options\n }).element;\n}\n\nexport function formatDateAccordingToTodayNew(time: Date) {\n const today = new Date();\n const now = today.getTime() / 1000 | 0;\n const timestamp = time.getTime() / 1000 | 0;\n\n const options: Intl.DateTimeFormatOptions = {};\n if((now - timestamp) < ONE_DAY && today.getDate() === time.getDate()) { // if the same day\n options.hour = options.minute = '2-digit';\n } else if(today.getFullYear() !== time.getFullYear()) { // different year\n options.year = options.day = 'numeric';\n options.month = '2-digit';\n } else if((now - timestamp) < (ONE_DAY * 7) && getWeekNumber(today) === getWeekNumber(time)) { // current week\n options.weekday = 'short';\n } else { // same year\n options.month = 'short';\n options.day = 'numeric';\n }\n\n return new I18n.IntlDateElement({\n date: time,\n options\n }).element;\n}\n\nconst formatTimeOptions: Intl.DateTimeFormatOptions = {\n hour: '2-digit',\n minute: '2-digit'\n};\n\nexport function formatFullSentTimeRaw(timestamp: number, options: {\n capitalize?: boolean\n noToday?: boolean,\n combined?: boolean\n} = {}) {\n if(options.combined) {\n options.noToday = true;\n }\n\n const date = new Date();\n const time = new Date(timestamp * 1000);\n const now = date.getTime() / 1000 | 0;\n const diff = now - timestamp;\n\n const timeEl = options.combined ? undefined : formatTime(time);\n\n let dateEl: HTMLElement;\n if(!options.noToday && diff < ONE_DAY && date.getDate() === time.getDate()) { // if the same day\n dateEl = i18n(options.capitalize ? 'Date.Today' : 'Peer.Status.Today');\n } else if(!options.noToday && diff > 0 && diff < (ONE_DAY * 2) && new Date(date.getTime() - ONE_DAY * 1000).getDate() === time.getDate()) { // yesterday\n dateEl = i18n(options.capitalize ? 'Yesterday' : 'Peer.Status.Yesterday');\n\n if(options.capitalize) {\n dateEl.style.textTransform = 'capitalize';\n }\n } else if(date.getFullYear() !== time.getFullYear()) { // different year\n dateEl = new I18n.IntlDateElement({\n date: time,\n options: {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n ...(options.combined ? formatTimeOptions: {})\n }\n }).element;\n // dateStr = months[time.getMonth()].slice(0, 3) + ' ' + time.getDate() + ', ' + time.getFullYear();\n } else {\n dateEl = new I18n.IntlDateElement({\n date: time,\n options: {\n month: 'short',\n day: 'numeric',\n ...(options.combined ? formatTimeOptions: {})\n }\n }).element;\n // dateStr = months[time.getMonth()].slice(0, 3) + ' ' + time.getDate();\n }\n\n return {dateEl, timeEl};\n}\n\nexport function formatFullSentTime(timestamp: number, capitalize = true, noToday = false) {\n const {dateEl, timeEl} = formatFullSentTimeRaw(timestamp, {\n capitalize,\n noToday\n });\n\n const fragment = document.createDocumentFragment();\n fragment.append(dateEl, ' ', i18n('ScheduleController.at'), ' ', timeEl);\n return fragment;\n}\n\nexport function formatTime(date: Date) {\n return new I18n.IntlDateElement({\n date,\n options: formatTimeOptions\n }).element;\n}\n\nMOUNT_CLASS_TO && (MOUNT_CLASS_TO.formatDateAccordingToTodayNew = formatDateAccordingToTodayNew);\n\nexport const getFullDate = (date: Date, options: Partial<{\n noTime: true,\n noSeconds: true,\n monthAsNumber: true,\n leadingZero: true,\n shortYear: boolean\n}> = {}) => {\n const joiner = options.monthAsNumber ? '.' : ' ';\n const time = ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + (options.noSeconds ? '' : ':' + ('0' + date.getSeconds()).slice(-2));\n const fullYear = date.getFullYear();\n\n return (options.leadingZero ? ('0' + date.getDate()).slice(-2) : date.getDate()) +\n joiner + (options.monthAsNumber ? ('0' + (date.getMonth() + 1)).slice(-2) : months[date.getMonth()]) +\n joiner + (('' + fullYear).slice(options.shortYear ? 2 : 0)) +\n (options.noTime ? '' : ', ' + time);\n};\n\nexport function formatMonthsDuration(months: number, bold?: boolean) {\n const isYears = months >= 12 && !(months % 12);\n return i18n(\n bold ? (isYears ? 'BoldYears' : 'BoldMonths') : (isYears ? 'Years' : 'Months'),\n [isYears ? months / 12 : months]\n );\n}\n\n// https://github.com/DrKLO/Telegram/blob/d52b2c921abd3c1e8d6368858313ad0cb0468c07/TMessagesProj/src/main/java/org/telegram/ui/Adapters/FiltersView.java\nconst minYear = 2013;\nconst yearPattern = new RegExp('20[0-9]{1,2}');\nconst anyLetterRegExp = `\\\\p{L}`;\nconst monthPattern = new RegExp(`(${anyLetterRegExp}{3,})`, 'iu');\nconst monthYearOrDayPattern = new RegExp(`(${anyLetterRegExp}{3,}) ([0-9]{0,4})`, 'iu');\nconst yearOrDayAndMonthPattern = new RegExp(`([0-9]{0,4}) (${anyLetterRegExp}{2,})`, 'iu');\nconst shortDate = new RegExp('^([0-9]{1,4})(\\\\.| |/|\\\\-)([0-9]{1,4})$', 'i');\nconst longDate = new RegExp('^([0-9]{1,2})(\\\\.| |/|\\\\-)([0-9]{1,2})(\\\\.| |/|\\\\-)([0-9]{1,4})$', 'i');\nconst numberOfDaysEachMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nexport type DateData = {\n title: string,\n minDate: number,\n maxDate: number,\n};\nexport function fillTipDates(query: string, dates: DateData[]) {\n const q = query.trim().toLowerCase();\n\n if(q.length < 3) {\n return;\n }\n\n if(['today', I18n.format('Peer.Status.Today', true)].some((haystack) => haystack.indexOf(q) === 0)) {\n const date = new Date();\n const year = date.getFullYear();\n const month = date.getMonth();\n const day = date.getDate();\n date.setFullYear(year, month, day);\n date.setHours(0, 0, 0);\n\n const minDate = date.getTime();\n date.setFullYear(year, month, day + 1);\n date.setHours(0, 0, 0);\n\n const maxDate = date.getTime() - 1;\n dates.push({\n title: I18n.format('Date.Today', true),\n minDate,\n maxDate\n });\n return;\n }\n\n if(['yesterday', I18n.format('Peer.Status.Yesterday', true)].some((haystack) => haystack.indexOf(q) === 0)) {\n const date = new Date();\n const year = date.getFullYear();\n const month = date.getMonth();\n const day = date.getDate();\n date.setFullYear(year, month, day);\n date.setHours(0, 0, 0);\n\n const minDate = date.getTime() - 86400000;\n date.setFullYear(year, month, day + 1);\n date.setHours(0, 0, 0);\n\n const maxDate = date.getTime() - 86400001;\n dates.push({\n title: capitalizeFirstLetter(I18n.format('Yesterday', true)),\n minDate,\n maxDate\n });\n return;\n }\n\n const dayOfWeek = getDayOfWeek(q);\n if(dayOfWeek >= 0) {\n const date = new Date();\n const now = date.getTime();\n const currentDay = date.getDay();\n const distance = dayOfWeek - currentDay;\n date.setDate(date.getDate() + distance);\n if(date.getTime() > now) {\n date.setTime(date.getTime() - 604800000);\n }\n const year = date.getFullYear()\n const month = date.getMonth();\n const day = date.getDate();\n date.setFullYear(year, month, day);\n date.setHours(0, 0, 0);\n\n const minDate = date.getTime();\n date.setFullYear(year, month, day + 1);\n date.setHours(0, 0, 0);\n\n const maxDate = date.getTime() - 1;\n dates.push({\n title: formatWeekLong(minDate),\n minDate,\n maxDate\n });\n return;\n }\n\n let matches: any[];\n if((matches = shortDate.exec(q)) !== null) {\n const g1 = matches[1];\n const g2 = matches[3];\n const k = parseInt(g1);\n const k1 = parseInt(g2);\n if(k > 0 && k <= 31) {\n if(k1 >= minYear && k <= 12) {\n const selectedYear = k1;\n const month = k - 1;\n createForMonthYear(dates, month, selectedYear);\n return;\n } else if(k1 <= 12) {\n const day = k - 1;\n const month = k1 - 1;\n createForDayMonth(dates, day, month);\n }\n } else if(k >= minYear && k1 <= 12) {\n const selectedYear = k;\n const month = k1 - 1;\n createForMonthYear(dates, month, selectedYear);\n }\n\n return;\n }\n\n if((matches = longDate.exec(q)) !== null) {\n const g1 = matches[1];\n const g2 = matches[3];\n const g3 = matches[5];\n if(!matches[2] === matches[4]) {\n return;\n }\n\n const day = parseInt(g1);\n const month = parseInt(g2) - 1;\n let year = parseInt(g3);\n if(year >= 10 && year <= 99) {\n year += 2000;\n }\n\n const currentYear = new Date().getFullYear();\n if(validDateForMonth(day - 1, month) && year >= minYear && year <= currentYear) {\n const date = new Date();\n date.setFullYear(year, month, day);\n date.setHours(0, 0, 0);\n\n const minDate = date.getTime();\n date.setFullYear(year, month, day + 1);\n date.setHours(0, 0, 0);\n\n const maxDate = date.getTime() - 1;\n dates.push({\n title: formatterYearMax(minDate),\n minDate,\n maxDate\n });\n return;\n }\n\n return;\n }\n\n if((matches = monthYearOrDayPattern.exec(q)) !== null) {\n const g1 = matches[1];\n const g2 = matches[2];\n const month = getMonth(g1);\n if(month >= 0) {\n const k = +g2 || new Date().getUTCFullYear();\n if(k > 0 && k <= 31) {\n const day = k - 1;\n createForDayMonth(dates, day, month);\n return;\n } else if(k >= minYear) {\n const selectedYear = k;\n createForMonthYear(dates, month, selectedYear);\n return;\n }\n }\n }\n\n if((matches = yearOrDayAndMonthPattern.exec(q)) !== null) {\n const g1 = matches[1];\n const g2 = matches[2];\n const month = getMonth(g2);\n if(month >= 0) {\n const k = +g1;\n if(k > 0 && k <= 31) {\n const day = k - 1;\n createForDayMonth(dates, day, month);\n return;\n } else if(k >= minYear) {\n const selectedYear = k;\n createForMonthYear(dates, month, selectedYear);\n }\n }\n }\n\n if((matches = monthPattern.exec(q)) !== null) {\n const g1 = matches[1];\n const month = getMonth(g1);\n if(month >= 0) {\n const currentYear = new Date().getFullYear();\n for(let i = currentYear; i >= minYear; --i) {\n createForMonthYear(dates, month, i);\n }\n }\n }\n\n if((matches = yearPattern.exec(q)) !== null) {\n let selectedYear = +matches[0];\n const currentYear = new Date().getFullYear();\n if(selectedYear < minYear) {\n selectedYear = minYear;\n for(let i = currentYear; i >= selectedYear; i--) {\n const date = new Date();\n date.setFullYear(i, 0, 1);\n date.setHours(0, 0, 0);\n\n const minDate = date.getTime();\n date.setFullYear(i + 1, 0, 1);\n date.setHours(0, 0, 0);\n\n const maxDate = date.getTime() - 1;\n dates.push({\n title: '' + i,\n minDate,\n maxDate\n });\n }\n } else if(selectedYear <= currentYear) {\n const date = new Date();\n date.setFullYear(selectedYear, 0, 1);\n date.setHours(0, 0, 0);\n\n const minDate = date.getTime();\n date.setFullYear(selectedYear + 1, 0, 1);\n date.setHours(0, 0, 0);\n\n const maxDate = date.getTime() - 1;\n dates.push({\n title: '' + selectedYear,\n minDate,\n maxDate\n });\n }\n\n return;\n }\n}\n\nfunction createForMonthYear(dates: DateData[], month: number, selectedYear: number) {\n const currentYear = new Date().getFullYear();\n const today = Date.now();\n if(selectedYear >= minYear && selectedYear <= currentYear) {\n const date = new Date();\n date.setFullYear(selectedYear, month, 1);\n date.setHours(0, 0, 0);\n const minDate = date.getTime();\n if(minDate > today) {\n return;\n }\n date.setMonth(date.getMonth() + 1);\n const maxDate = date.getTime() - 1;\n\n dates.push({\n title: formatterMonthYear(minDate),\n minDate,\n maxDate\n });\n }\n}\n\nfunction createForDayMonth(dates: DateData[], day: number, month: number) {\n if(validDateForMonth(day, month)) {\n const currentYear = new Date().getFullYear();\n const today = Date.now();\n\n for(let i = currentYear; i >= minYear; i--) {\n if(month === 1 && day === 28 && !isLeapYear(i)) {\n continue;\n }\n\n const date = new Date();\n date.setFullYear(i, month, day + 1);\n date.setHours(0, 0, 0);\n\n const minDate = date.getTime();\n if(minDate > today) {\n continue;\n }\n\n date.setFullYear(i, month, day + 2);\n date.setHours(0, 0, 0);\n const maxDate = date.getTime() - 1;\n if(i === currentYear) {\n dates.push({\n title: formatterDayMonth(minDate),\n minDate,\n maxDate\n });\n } else {\n dates.push({\n title: formatterYearMax(minDate),\n minDate,\n maxDate\n });\n }\n }\n }\n}\n\nfunction formatterMonthYear(timestamp: number) {\n const date = new Date(timestamp);\n return monthsLocalized[date.getMonth()]/* .slice(0, 3) */ + ' ' + date.getFullYear();\n}\n\nfunction formatterDayMonth(timestamp: number) {\n const date = new Date(timestamp);\n return monthsLocalized[date.getMonth()]/* .slice(0, 3) */ + ' ' + date.getDate();\n}\n\nfunction formatterYearMax(timestamp: number) {\n const date = new Date(timestamp);\n return ('0' + date.getDate()).slice(-2) + '.' + ('0' + (date.getMonth() + 1)).slice(-2) + '.' + date.getFullYear();\n}\n\nfunction formatWeekLong(timestamp: number) {\n const date = new Date(timestamp);\n return daysLocalized[date.getDay()];\n}\n\nfunction validDateForMonth(day: number, month: number) {\n if(month >= 0 && month < 12) {\n if(day >= 0 && day < numberOfDaysEachMonth[month]) {\n return true;\n }\n }\n return false;\n}\n\nfunction isLeapYear(year: number) {\n return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);\n}\n\nfunction getMonth(q: string) {\n q = q.toLowerCase();\n for(let i = 0; i < 12; i++) {\n if([months[i], monthsLocalized[i]].some((month) => month.toLowerCase().indexOf(q) === 0)) {\n return i;\n }\n }\n return -1;\n}\n\nfunction getDayOfWeek(q: string) {\n const c = new Date();\n if(q.length <= 3) {\n return -1;\n }\n\n for(let i = 0; i < 7; i++) {\n c.setDate(c.getDate() + 1);\n\n if(formatWeekLong(c.getTime()).toLowerCase().indexOf(q) === 0) {\n return c.getDay();\n }\n }\n return -1;\n}\n\nMOUNT_CLASS_TO.fillTipDates = fillTipDates;\n","import {CHROMIUM_VERSION, IS_CHROMIUM, IS_FIREFOX, IS_MOBILE, IS_MOBILE_SAFARI, IS_SAFARI} from './userAgent';\n\nexport const USE_NATIVE_SCROLL = /* IS_APPLE || */IS_MOBILE/* || true */;\nexport const IS_OVERLAY_SCROLL_SUPPORTED = IS_MOBILE || (!IS_CHROMIUM && (!IS_SAFARI || IS_MOBILE_SAFARI)/* && !IS_FIREFOX */) || CHROMIUM_VERSION < 113;\nexport const USE_CUSTOM_SCROLL = !USE_NATIVE_SCROLL && !IS_OVERLAY_SCROLL_SUPPORTED;\n","/*\n * https://github.com/morethanwords/tweb\n * Copyright (C) 2019-2021 Eduard Kuzmenko\n * https://github.com/morethanwords/tweb/blob/master/LICENSE\n */\n\n/* @refresh reload */\n\nimport App from './config/app';\nimport blurActiveElement from './helpers/dom/blurActiveElement';\nimport cancelEvent from './helpers/dom/cancelEvent';\nimport {IS_STICKY_INPUT_BUGGED} from './helpers/dom/fixSafariStickyInputFocusing';\nimport loadFonts from './helpers/dom/loadFonts';\nimport IS_EMOJI_SUPPORTED from './environment/emojiSupport';\nimport {IS_ANDROID, IS_APPLE, IS_APPLE_MOBILE, IS_FIREFOX, IS_MOBILE, IS_MOBILE_SAFARI, IS_SAFARI} from './environment/userAgent';\nimport './materialize.scss';\nimport './scss/style.scss';\nimport pause from './helpers/schedulers/pause';\nimport setWorkerProxy from './helpers/setWorkerProxy';\nimport toggleAttributePolyfill from './helpers/dom/toggleAttributePolyfill';\nimport rootScope from './lib/rootScope';\nimport IS_TOUCH_SUPPORTED from './environment/touchSupport';\nimport I18n from './lib/langPack';\nimport './helpers/peerIdPolyfill';\nimport './lib/polyfill';\nimport apiManagerProxy from './lib/mtproto/mtprotoworker';\nimport getProxiedManagers from './lib/appManagers/getProxiedManagers';\nimport themeController from './helpers/themeController';\nimport overlayCounter from './helpers/overlayCounter';\nimport singleInstance from './lib/mtproto/singleInstance';\nimport {parseUriParamsLine} from './helpers/string/parseUriParams';\nimport Modes from './config/modes';\nimport {AuthState} from './types';\nimport {IS_BETA} from './config/debug';\nimport IS_INSTALL_PROMPT_SUPPORTED from './environment/installPrompt';\nimport cacheInstallPrompt from './helpers/dom/installPrompt';\nimport {fillLocalizedDates} from './helpers/date';\nimport {nextRandomUint} from './helpers/random';\nimport {IS_OVERLAY_SCROLL_SUPPORTED, USE_CUSTOM_SCROLL, USE_NATIVE_SCROLL} from './environment/overlayScrollSupport';\nimport IMAGE_MIME_TYPES_SUPPORTED, {IMAGE_MIME_TYPES_SUPPORTED_PROMISE} from './environment/imageMimeTypesSupport';\nimport MEDIA_MIME_TYPES_SUPPORTED from './environment/mediaMimeTypesSupport';\n// import appNavigationController from './components/appNavigationController';\n\nIMAGE_MIME_TYPES_SUPPORTED_PROMISE.then((mimeTypes) => {\n mimeTypes.forEach((mimeType) => {\n IMAGE_MIME_TYPES_SUPPORTED.add(mimeType);\n MEDIA_MIME_TYPES_SUPPORTED.add(mimeType);\n });\n\n console.log('Supported image mime types', IMAGE_MIME_TYPES_SUPPORTED);\n apiManagerProxy.sendEnvironment();\n});\n\n/* false && */document.addEventListener('DOMContentLoaded', async() => {\n // * Randomly choose a version if user came from google\n try {\n if(\n App.isMainDomain &&\n document.referrer &&\n /(^|\\.)(google|bing|duckduckgo|ya|yandex)\\./i.test(new URL(document.referrer).host)\n ) {\n const version = localStorage.getItem('kz_version');\n if(version === 'Z' || nextRandomUint(8) > 127) {\n localStorage.setItem('kz_version', 'Z');\n location.href = 'https://web.telegram.org/a/';\n } else {\n localStorage.setItem('kz_version', 'K');\n }\n }\n } catch(err) {}\n\n toggleAttributePolyfill();\n\n // polyfill for replaceChildren\n if((Node as any).prototype.replaceChildren === undefined) {\n (Node as any).prototype.replaceChildren = function(...nodes: any[]) {\n this.textContent = '';\n // while(this.lastChild) {\n // this.removeChild(this.lastChild);\n // }\n if(nodes) {\n this.append(...nodes);\n }\n }\n }\n\n rootScope.managers = getProxiedManagers();\n\n const manifest = document.getElementById('manifest') as HTMLLinkElement;\n if(manifest) manifest.href = `site${IS_APPLE && !IS_APPLE_MOBILE ? '_apple' : ''}.webmanifest?v=jw3mK7G9Aq`;\n\n singleInstance.start();\n\n // We listen to the resize event (https://css-tricks.com/the-trick-to-viewport-units-on-mobile/)\n const w = window.visualViewport || window; // * handle iOS keyboard\n let setViewportVH = false/* , hasFocus = false */;\n let lastVH: number;\n const setVH = () => {\n let vh = (setViewportVH && !overlayCounter.isOverlayActive ? (w as VisualViewport).height || (w as Window).innerHeight : window.innerHeight) * 0.01;\n vh = +vh.toFixed(2);\n if(lastVH === vh) {\n return;\n } else if(IS_TOUCH_SUPPORTED && lastVH < vh && (vh - lastVH) > 1) {\n blurActiveElement(); // (Android) fix blurring inputs when keyboard is being closed (e.g. closing keyboard by back arrow and touching a bubble)\n }\n\n lastVH = vh;\n\n // const vh = document.documentElement.scrollHeight * 0.01;\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n // console.log('setVH', vh, setViewportVH ? w : window);\n\n /* if(setViewportVH && userAgent.isSafari && touchSupport.isTouchSupported && document.activeElement && (document.activeElement as HTMLElement).blur) {\n const rect = document.activeElement.getBoundingClientRect();\n if(rect.top < 0 || rect.bottom >= (w as any).height) {\n fastSmoothScroll(findUpClassName(document.activeElement, 'scrollable-y') || window as any, document.activeElement as HTMLElement, 'center', 4, undefined, FocusDirection.Static);\n }\n } */\n };\n\n setWorkerProxy;\n\n // const [_, touchSupport, userAgent, _rootScope, _appStateManager, _I18n, __/* , ___ */] = await Promise.all([\n // import('./lib/polyfill'),\n // import('./environment/touchSupport'),\n // import('./environment/userAgent'),\n // import('./lib/rootScope'),\n // import('./lib/appManagers/appStateManager'),\n // import('./lib/langPack'),\n // import('./helpers/peerIdPolyfill'),\n // // import('./helpers/cacheFunctionPolyfill')\n // ]);\n\n /* const {IS_TOUCH_SUPPORTED} = touchSupport;\n const {IS_FIREFOX, IS_MOBILE, IS_APPLE, IS_SAFARI, IS_APPLE_MOBILE, IS_ANDROID} = userAgent;\n const rootScope = _rootScope.default;\n const appStateManager = _appStateManager.default;\n const I18n = _I18n.default; */\n\n window.addEventListener('resize', setVH);\n setVH();\n\n const preparePrint = () => {\n const chat = document.querySelector('.chat.active');\n if(!chat) {\n return;\n }\n\n const chatClone = chat.cloneNode(true) as HTMLElement;\n chatClone.querySelectorAll('.chat-input, .chat-background').forEach((element) => element.remove());\n const bubbles = chatClone.querySelector('.bubbles');\n const bubblesInner = bubbles.querySelector('.bubbles-inner');\n bubbles.replaceChildren(bubblesInner);\n const video = bubbles.querySelectorAll<HTMLVideoElement>('video');\n video.forEach((video) => (video.muted = true));\n const printable = document.createElement('div');\n printable.setAttribute('id', 'printable');\n printable.append(chatClone);\n document.body.append(printable);\n };\n const removePrint = () => {\n const printContent = document.getElementById('printable');\n printContent?.remove();\n };\n window.addEventListener('beforeprint', preparePrint);\n window.addEventListener('afterprint', removePrint);\n\n if(IS_STICKY_INPUT_BUGGED) {\n const toggleResizeMode = () => {\n setViewportVH = tabId === 1 && IS_STICKY_INPUT_BUGGED && !overlayCounter.isOverlayActive;\n setVH();\n\n if(w !== window) {\n if(setViewportVH) {\n window.removeEventListener('resize', setVH);\n w.addEventListener('resize', setVH);\n } else {\n w.removeEventListener('resize', setVH);\n window.addEventListener('resize', setVH);\n }\n }\n };\n\n let tabId: number;\n (window as any).onImTabChange = (id: number) => {\n const wasTabId = tabId !== undefined;\n tabId = id;\n\n if(wasTabId || tabId === 1) {\n toggleResizeMode();\n }\n };\n\n overlayCounter.addEventListener('change', () => {\n toggleResizeMode();\n });\n }\n\n if(IS_FIREFOX && !IS_EMOJI_SUPPORTED) {\n document.addEventListener('dragstart', (e) => {\n const target = e.target as HTMLElement;\n if(target.tagName === 'IMG' && target.classList.contains('emoji')) {\n cancelEvent(e);\n return false;\n }\n });\n }\n\n if(IS_EMOJI_SUPPORTED) {\n document.documentElement.classList.add('native-emoji');\n }\n\n if(USE_NATIVE_SCROLL) {\n document.documentElement.classList.add('native-scroll');\n } else if(IS_OVERLAY_SCROLL_SUPPORTED) {\n document.documentElement.classList.add('overlay-scroll');\n } else if(USE_CUSTOM_SCROLL) {\n document.documentElement.classList.add('custom-scroll');\n }\n\n // document.documentElement.style.setProperty('--quote-icon', `\"${getIconContent('quote')}\"`);\n\n // prevent firefox image dragging\n document.addEventListener('dragstart', (e) => {\n if((e.target as HTMLElement)?.tagName === 'IMG') {\n e.preventDefault();\n return false;\n }\n });\n\n // restrict contextmenu on images (e.g. webp stickers)\n document.addEventListener('contextmenu', (e) => {\n if((e.target as HTMLElement).tagName === 'IMG' && !(window as any).appMediaViewer) {\n cancelEvent(e);\n }\n });\n\n if(IS_FIREFOX) {\n document.documentElement.classList.add('is-firefox', 'no-backdrop');\n }\n\n if(IS_MOBILE) {\n document.documentElement.classList.add('is-mobile');\n }\n\n if(IS_APPLE) {\n if(IS_SAFARI) {\n document.documentElement.classList.add('is-safari');\n }\n\n // document.documentElement.classList.add('emoji-supported');\n\n if(IS_APPLE_MOBILE) {\n document.documentElement.classList.add('is-ios');\n } else {\n document.documentElement.classList.add('is-mac');\n }\n } else if(IS_ANDROID) {\n document.documentElement.classList.add('is-android');\n\n // force losing focus on input blur\n // focusin and focusout are not working on mobile\n\n // const onInResize = () => {\n // hasFocus = true;\n // window.addEventListener('resize', onOutResize, {once: true});\n // };\n\n // const onOutResize = () => {\n // hasFocus = false;\n // blurActiveElement();\n // };\n\n // let hasFocus = false;\n // document.addEventListener('touchend', (e) => {\n // const input = (e.target as HTMLElement).closest('[contenteditable=\"true\"], input');\n // if(!input) {\n // return;\n // }\n\n // if(document.activeElement !== input && !hasFocus) {\n // console.log('input click', e, document.activeElement, input, input.matches(':focus'));\n // window.addEventListener('resize', onInResize, {once: true});\n // }\n // });\n }\n\n if(!IS_TOUCH_SUPPORTED) {\n document.documentElement.classList.add('no-touch');\n } else {\n document.documentElement.classList.add('is-touch');\n /* document.addEventListener('touchmove', (event: any) => {\n event = event.originalEvent || event;\n if(event.scale && event.scale !== 1) {\n event.preventDefault();\n }\n }, {capture: true, passive: false}); */\n }\n\n if(IS_INSTALL_PROMPT_SUPPORTED) {\n cacheInstallPrompt();\n }\n\n const perf = performance.now();\n\n // await pause(1000000);\n\n const langPromise = I18n.getCacheLangPack();\n\n const [stateResult, langPack] = await Promise.all([\n // loadState(),\n apiManagerProxy.sendState().then(([stateResult]) => stateResult),\n langPromise\n ]);\n I18n.setTimeFormat(stateResult.state.settings.timeFormat);\n\n rootScope.managers.rootScope.getPremium().then((isPremium) => {\n rootScope.premium = isPremium;\n });\n\n themeController.setThemeListener();\n\n if(langPack.appVersion !== App.langPackVersion) {\n I18n.getLangPack(langPack.lang_code);\n } else {\n fillLocalizedDates();\n }\n\n rootScope.addEventListener('language_change', () => {\n fillLocalizedDates();\n });\n\n /**\n * won't fire if font is loaded too fast\n */\n function fadeInWhenFontsReady(elem: HTMLElement, promise: Promise<any>) {\n elem.style.opacity = '0';\n\n promise.then(() => {\n window.requestAnimationFrame(() => {\n elem.style.opacity = '';\n });\n });\n }\n\n console.log('got state, time:', performance.now() - perf);\n\n await IMAGE_MIME_TYPES_SUPPORTED_PROMISE;\n\n if(langPack.lang_code === 'ar' || langPack.lang_code === 'fa' && IS_BETA && false) {\n document.documentElement.classList.add('is-rtl');\n document.documentElement.dir = 'rtl';\n document.documentElement.lang = langPack.lang_code;\n I18n.setRTL(true);\n } else {\n document.documentElement.dir = 'ltr';\n }\n\n let authState = stateResult.state.authState;\n\n const hash = location.hash;\n const splitted = hash.split('?');\n const params = parseUriParamsLine(splitted[1] ?? splitted[0].slice(1));\n if(params.tgWebAuthToken && authState._ !== 'authStateSignedIn') {\n const data: AuthState.signImport['data'] = {\n token: params.tgWebAuthToken,\n dcId: +params.tgWebAuthDcId,\n userId: params.tgWebAuthUserId.toUserId(),\n isTest: params.tgWebAuthTest !== undefined && !!+params.tgWebAuthTest,\n tgAddr: params.tgaddr\n };\n\n if(data.isTest !== Modes.test) {\n const urlSearchParams = new URLSearchParams(location.search);\n if(+params.tgWebAuthTest) {\n urlSearchParams.set('test', '1');\n } else {\n urlSearchParams.delete('test');\n }\n\n location.search = urlSearchParams.toString();\n return;\n }\n\n rootScope.managers.appStateManager.pushToState('authState', authState = {_: 'authStateSignImport', data});\n\n // appNavigationController.overrideHash('?tgaddr=' + encodeURIComponent(params.tgaddr));\n }\n\n if(authState._ !== 'authStateSignedIn'/* || 1 === 1 */) {\n console.log('Will mount auth page:', authState._, Date.now() / 1000);\n\n const el = document.getElementById('auth-pages');\n let scrollable: HTMLElement;\n if(el) {\n scrollable = el.querySelector('.scrollable') as HTMLElement;\n if((!IS_TOUCH_SUPPORTED || IS_MOBILE_SAFARI)) {\n scrollable.classList.add('no-scrollbar');\n }\n\n // * don't remove this line\n scrollable.style.opacity = '0';\n\n const placeholder = document.createElement('div');\n placeholder.classList.add('auth-placeholder');\n\n scrollable.prepend(placeholder);\n scrollable.append(placeholder.cloneNode());\n }\n\n try {\n await Promise.all([\n import('./lib/mtproto/telegramMeWebManager'),\n import('./lib/mtproto/webPushApiManager')\n ]).then(([meModule, pushModule]) => {\n meModule.default.setAuthorized(false);\n pushModule.default.forceUnsubscribe();\n });\n } catch(err) {\n\n }\n\n let pagePromise: Promise<void>;\n // langPromise.then(async() => {\n switch(authState._) {\n case 'authStateSignIn':\n pagePromise = (await import('./pages/pageSignIn')).default.mount();\n break;\n case 'authStateSignQr':\n pagePromise = (await import('./pages/pageSignQR')).default.mount();\n break;\n case 'authStateAuthCode':\n pagePromise = (await import('./pages/pageAuthCode')).default.mount(authState.sentCode);\n break;\n case 'authStatePassword':\n pagePromise = (await import('./pages/pagePassword')).default.mount();\n break;\n case 'authStateSignUp':\n pagePromise = (await import('./pages/pageSignUp')).default.mount(authState.authCode);\n break;\n case 'authStateSignImport':\n pagePromise = (await import('./pages/pageSignImport')).default.mount(authState.data);\n break;\n }\n // });\n\n if(scrollable) {\n // wait for text appear\n if(pagePromise) {\n await pagePromise;\n }\n\n const promise = 'fonts' in document ?\n Promise.race([\n pause(1000),\n document.fonts.ready\n ]) :\n Promise.resolve();\n fadeInWhenFontsReady(scrollable, promise);\n }\n\n /* setTimeout(async() => {\n (await import('./pages/pageAuthCode')).default.mount({\n \"_\": \"auth.sentCode\",\n \"pFlags\": {},\n \"flags\": 6,\n \"type\": {\n \"_\": \"auth.sentCodeTypeSms\",\n \"length\": 5\n },\n \"phone_code_hash\": \"\",\n \"next_type\": {\n \"_\": \"auth.codeTypeCall\"\n },\n \"timeout\": 120,\n \"phone_number\": \"\"\n });\n\n (await import('./pages/pageSignQR')).default.mount();\n\n (await import('./pages/pagePassword')).default.mount();\n\n (await import('./pages/pageSignUp')).default.mount({\n \"phone_code_hash\": \"\",\n \"phone_number\": \"\"\n });\n }, 500); */\n } else {\n console.log('Will mount IM page:', Date.now() / 1000);\n fadeInWhenFontsReady(document.getElementById('main-columns'), loadFonts());\n (await import('./pages/pageIm')).default.mount();\n }\n});\n"],"file":"index-CbCftUfG.js"}