heap_snapshot_worker.js 198 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. const _loadedScripts={};(function(){const baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();const REMOTE_MODULE_FALLBACK_REVISION='@010ddcfda246975d194964ccf20038ebbdec6084';class Runtime{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(let i=0;i<descriptors.length;++i){this._registerModule(descriptors[i]);}}
  2. static _loadResourcePromise(url,asBinary){return new Promise(load);function load(fulfill,reject){const xhr=new XMLHttpRequest();xhr.open('GET',url,true);if(asBinary){xhr.responseType='arraybuffer';}
  3. xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE){return;}
  4. const{response}=e.target;const text=asBinary?new TextDecoder().decode(response):response;const status=/^HTTP\/1.1 404/.test(text)?404:xhr.status;if([0,200,304].indexOf(status)===-1)
  5. {reject(new Error('While loading from url '+url+' server responded with a status of '+status));}else{fulfill(response);}}
  6. xhr.send(null);}}
  7. static loadResourcePromise(url){return Runtime._loadResourcePromise(url,false);}
  8. static loadBinaryResourcePromise(url){return Runtime._loadResourcePromise(url,true);}
  9. static loadResourcePromiseWithFallback(url){return Runtime.loadResourcePromise(url).catch(err=>{const urlWithFallbackVersion=url.replace(/@[0-9a-f]{40}/,REMOTE_MODULE_FALLBACK_REVISION);if(urlWithFallbackVersion===url||!url.includes('audits_worker_module')){throw err;}
  10. return Runtime.loadResourcePromise(urlWithFallbackVersion);});}
  11. static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1){return path;}
  12. const normalizedSegments=[];const segments=path.split('/');for(let i=0;i<segments.length;i++){const segment=segments[i];if(segment==='.'){continue;}else if(segment==='..'){normalizedSegments.pop();}else if(segment){normalizedSegments.push(segment);}}
  13. let normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/'){return normalizedPath;}
  14. if(path[0]==='/'&&normalizedPath){normalizedPath='/'+normalizedPath;}
  15. if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..')){normalizedPath=normalizedPath+'/';}
  16. return normalizedPath;}
  17. static getResourceURL(scriptName,base){const sourceURL=(base||self._importScriptPathPrefix)+scriptName;const schemaIndex=sourceURL.indexOf('://')+3;let pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1){pathIndex=sourceURL.length;}
  18. return sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));}
  19. static _loadScriptsPromise(scriptNames,base){const promises=[];const urls=[];const sources=new Array(scriptNames.length);let scriptToEval=0;for(let i=0;i<scriptNames.length;++i){const scriptName=scriptNames[i];const sourceURL=Runtime.getResourceURL(scriptName,base);if(_loadedScripts[sourceURL]){continue;}
  20. urls.push(sourceURL);const loadResourcePromise=base?Runtime.loadResourcePromiseWithFallback(sourceURL):Runtime.loadResourcePromise(sourceURL);promises.push(loadResourcePromise.then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));}
  21. return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}}
  22. function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;}
  23. self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}}
  24. static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;}
  25. const sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}}
  26. static async appStarted(){return Runtime._appStartedPromise;}
  27. static async startApplication(appName){console.timeStamp('Root.Runtime.startApplication');const allDescriptorsByName={};for(let i=0;i<Root.allDescriptors.length;++i){const d=Root.allDescriptors[i];allDescriptorsByName[d['name']]=d;}
  28. if(!Root.applicationDescriptor){let data=await Runtime.loadResourcePromise(appName+'.json');Root.applicationDescriptor=JSON.parse(data);let descriptor=Root.applicationDescriptor;while(descriptor.extends){data=await Runtime.loadResourcePromise(descriptor.extends+'.json');descriptor=JSON.parse(data);Root.applicationDescriptor.modules=descriptor.modules.concat(Root.applicationDescriptor.modules);}}
  29. const configuration=Root.applicationDescriptor.modules;const moduleJSONPromises=[];const coreModuleNames=[];for(let i=0;i<configuration.length;++i){const descriptor=configuration[i];const name=descriptor['name'];const moduleJSON=allDescriptorsByName[name];if(moduleJSON){moduleJSONPromises.push(Promise.resolve(moduleJSON));}else{moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));}
  30. if(descriptor['type']==='autostart'){coreModuleNames.push(name);}}
  31. const moduleDescriptors=await Promise.all(moduleJSONPromises);for(let i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';}
  32. self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames){await self.runtime._loadAutoStartModules(coreModuleNames);}
  33. Runtime._appStartedPromiseCallback();}
  34. static startWorker(appName){return Root.Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}}
  35. static queryParam(name){return Runtime._queryParamsObject.get(name);}
  36. static queryParamsString(){return location.search;}
  37. static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}}
  38. static _assert(value,message){if(value){return;}
  39. Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);}
  40. static setPlatform(platform){Runtime._platform=platform;}
  41. static _isDescriptorEnabled(descriptor){const activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*'){return Runtime.experiments.supportEnabled();}
  42. if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1))){return false;}
  43. if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment)){return false;}
  44. const condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition)){return false;}
  45. if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1))){return false;}
  46. return true;}
  47. static resolveSourceURL(path){let sourceURL=self.location.href;if(self.location.search){sourceURL=sourceURL.replace(self.location.search,'');}
  48. sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';}
  49. static setL10nCallback(localizationFunction){Runtime._l10nCallback=localizationFunction;}
  50. useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend')){Runtime._remoteBase+='debug/';}}
  51. module(moduleName){return this._modulesMap[moduleName];}
  52. _registerModule(descriptor){const module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;}
  53. loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();}
  54. _loadAutoStartModules(moduleNames){const promises=[];for(let i=0;i<moduleNames.length;++i){promises.push(this.loadModulePromise(moduleNames[i]));}
  55. return Promise.all(promises);}
  56. _checkExtensionApplicability(extension,predicate){if(!predicate){return false;}
  57. const contextTypes=extension.descriptor().contextTypes;if(!contextTypes){return true;}
  58. for(let i=0;i<contextTypes.length;++i){const contextType=this._resolve(contextTypes[i]);const isMatching=!!contextType&&predicate(contextType);if(isMatching){return true;}}
  59. return false;}
  60. isExtensionApplicableToContext(extension,context){if(!context){return true;}
  61. return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}}
  62. isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes){return true;}
  63. return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}}
  64. extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type){return false;}
  65. if(!extension.enabled()){return false;}
  66. return!context||extension.isApplicable(context);}
  67. function orderComparator(extension1,extension2){const order1=extension1.descriptor()['order']||0;const order2=extension2.descriptor()['order']||0;return order1-order2;}
  68. function titleComparator(extension1,extension2){const title1=extension1.title()||'';const title2=extension2.title()||'';return title1.localeCompare(title2);}}
  69. extension(type,context){return this.extensions(type,context)[0]||null;}
  70. allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));}
  71. _resolve(typeName){if(!this._cachedTypeClasses[typeName]){const path=typeName.split('.');let object=self;for(let i=0;object&&(i<path.length);++i){object=object[path[i]];}
  72. if(object){this._cachedTypeClasses[typeName]=(object);}}
  73. return this._cachedTypeClasses[typeName]||null;}
  74. sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction&&Object.getOwnPropertySymbols(constructorFunction).includes(Runtime._instanceSymbol)){return constructorFunction[Runtime._instanceSymbol];}
  75. const instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}}
  76. Runtime._queryParamsObject=new URLSearchParams(Runtime.queryParamsString());Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';class ModuleDescriptor{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.modules;this.condition;this.remote;}}
  77. class RuntimeExtensionDescriptor{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}}
  78. const specialCases={'sdk':'SDK','js_sdk':'JSSDK','browser_sdk':'BrowserSDK','ui':'UI','object_ui':'ObjectUI','javascript_metadata':'JavaScriptMetadata','perf_ui':'PerfUI','har_importer':'HARImporter','sdk_test_runner':'SDKTestRunner','cpu_profiler_test_runner':'CPUProfilerTestRunner'};class Module{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();const extensions=(descriptor.extensions);for(let i=0;extensions&&i<extensions.length;++i){const extension=new Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);}
  79. this._loadedForTest=false;}
  80. name(){return this._name;}
  81. enabled(){return Runtime._isDescriptorEnabled(this._descriptor);}
  82. resource(name){const fullName=this._name+'/'+name;const content=Runtime.cachedResources[fullName];if(!content){throw new Error(fullName+' not preloaded. Check module.json');}
  83. return content;}
  84. _loadPromise(){if(!this.enabled()){return Promise.reject(new Error('Module '+this._name+' is not enabled'));}
  85. if(this._pendingLoadPromise){return this._pendingLoadPromise;}
  86. const dependencies=this._descriptor.dependencies;const dependencyPromises=[];for(let i=0;dependencies&&i<dependencies.length;++i){dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());}
  87. this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadModules.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;}
  88. _loadResources(){const resources=this._descriptor['resources'];if(!resources||!resources.length){return Promise.resolve();}
  89. const promises=[];for(let i=0;i<resources.length;++i){const url=this._modularizeURL(resources[i]);const isHtml=url.endsWith('.html');promises.push(Runtime._loadResourceIntoCache(url,!isHtml));}
  90. return Promise.all(promises).then(undefined);}
  91. _loadModules(){if(!this._descriptor.modules||!this._descriptor.modules.length){return Promise.resolve();}
  92. const namespace=this._computeNamespace();self[namespace]=self[namespace]||{};if(typeof WorkerGlobalScope!=='undefined'&&self instanceof WorkerGlobalScope){return Promise.resolve();}
  93. return eval(`import('./${this._name}/${this._name}.js')`);}
  94. _loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length){return Promise.resolve();}
  95. const namespace=this._computeNamespace();self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());}
  96. _computeNamespace(){return specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');}
  97. _modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);}
  98. _remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;}
  99. fetchResource(resourceName){const base=this._remoteBase();const sourceURL=Runtime.getResourceURL(this._modularizeURL(resourceName),base);return base?Runtime.loadResourcePromiseWithFallback(sourceURL):Runtime.loadResourcePromise(sourceURL);}
  100. substituteURL(value){const base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}}
  101. class Extension{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;}
  102. descriptor(){return this._descriptor;}
  103. module(){return this._module;}
  104. enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());}
  105. _typeClass(){if(!this._hasTypeClass){return null;}
  106. return this._module._manager._resolve(this._type.substring(1));}
  107. isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);}
  108. instance(){return this._module._loadPromise().then(this._createInstance.bind(this));}
  109. canInstantiate(){return!!(this._className||this._factoryName);}
  110. _createInstance(){const className=this._className||this._factoryName;if(!className){throw new Error('Could not instantiate extension with no class');}
  111. const constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function)){throw new Error('Could not instantiate: '+className);}
  112. if(this._className){return this._module._manager.sharedInstance(constructorFunction);}
  113. return new constructorFunction(this);}
  114. title(){const title=this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];if(title&&Runtime._l10nCallback){return Runtime._l10nCallback(title);}
  115. return title;}
  116. hasContextType(contextType){const contextTypes=this.descriptor().contextTypes;if(!contextTypes){return false;}
  117. for(let i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i])){return true;}}
  118. return false;}}
  119. class ExperimentsSupport{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};this._serverEnabled=new Set();}
  120. allConfigurableExperiments(){const result=[];for(let i=0;i<this._experiments.length;i++){const experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name]){result.push(experiment);}}
  121. return result;}
  122. supportEnabled(){return this._supportEnabled;}
  123. _setExperimentsSetting(value){if(!self.localStorage){return;}
  124. self.localStorage['experiments']=JSON.stringify(value);}
  125. register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));}
  126. isEnabled(experimentName){this._checkExperiment(experimentName);if(Runtime._experimentsSetting()[experimentName]===false){return false;}
  127. if(this._enabledTransiently[experimentName]){return true;}
  128. if(this._serverEnabled.has(experimentName)){return true;}
  129. if(!this.supportEnabled()){return false;}
  130. return!!Runtime._experimentsSetting()[experimentName];}
  131. setEnabled(experimentName,enabled){this._checkExperiment(experimentName);const experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);}
  132. setDefaultExperiments(experimentNames){for(let i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}}
  133. setServerEnabledExperiments(experimentNames){for(const experiment of experimentNames){this._checkExperiment(experiment);this._serverEnabled.add(experiment);}}
  134. enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;}
  135. clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};this._serverEnabled.clear();}
  136. cleanUpStaleExperiments(){const experimentsSetting=Runtime._experimentsSetting();const cleanedUpExperimentSetting={};for(let i=0;i<this._experiments.length;++i){const experimentName=this._experiments[i].name;if(experimentsSetting[experimentName]){cleanedUpExperimentSetting[experimentName]=true;}}
  137. this._setExperimentsSetting(cleanedUpExperimentSetting);}
  138. _checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}}
  139. class Experiment{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;}
  140. isEnabled(){return this._experiments.isEnabled(this.name);}
  141. setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}}
  142. Runtime.experiments=new ExperimentsSupport();Runtime._appStartedPromiseCallback;Runtime._appStartedPromise=new Promise(fulfil=>Runtime._appStartedPromiseCallback=fulfil);Runtime._l10nCallback;Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){const versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch){Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}}})();self.Root=self.Root||{};Root=Root||{};Root.allDescriptors=[];Root.applicationDescriptor=undefined;Root.Runtime=Runtime;Root.runtime;Root.Runtime.ModuleDescriptor=ModuleDescriptor;Root.Runtime.ExtensionDescriptor=RuntimeExtensionDescriptor;Root.Runtime.Extension=Extension;Root.Runtime.Module=Module;Root.Runtime.ExperimentsSupport=ExperimentsSupport;Root.Runtime.Experiment=Experiment;Root.allDescriptors.push(...[{"dependencies":[],"modules":["heap_snapshot_model.js","HeapSnapshotModel.js"],"name":"heap_snapshot_model","scripts":[]},{"dependencies":[],"modules":["platform.js","utilities.js"],"name":"platform","scripts":[]},{"dependencies":["heap_snapshot_model","platform","common"],"modules":["heap_snapshot_worker.js","AllocationProfile.js","HeapSnapshot.js","HeapSnapshotLoader.js","HeapSnapshotWorkerDispatcher.js","HeapSnapshotWorker.js"],"name":"heap_snapshot_worker","scripts":[]},{"dependencies":["platform"],"modules":["text_utils.js","Text.js","TextUtils.js","TextRange.js"],"name":"text_utils","scripts":[]},{"dependencies":["text_utils","platform"],"modules":["common.js","common-legacy.js","EventTarget.js","Object.js","Worker.js","TextDictionary.js","Color.js","Console.js","ContentProvider.js","ParsedURL.js","Progress.js","UIString.js","ResourceType.js","Settings.js","StaticContentProvider.js","SegmentedRange.js","Throttler.js","Trie.js","Revealer.js","App.js","AppProvider.js","JavaScriptMetaData.js","Linkifier.js","QueryParamHandler.js","Revealer.js","Runnable.js","StringOutputStream.js","CharacterIdMap.js"],"name":"common","scripts":[]}]);Root.applicationDescriptor={"has_html":false,"modules":[{"type":"autostart","name":"heap_snapshot_model"},{"type":"autostart","name":"platform"},{"type":"autostart","name":"heap_snapshot_worker"},{"type":"autostart","name":"text_utils"},{"type":"autostart","name":"common"}]};(function(){'use strict';self.mod=function(m,n){return((m%n)+n)%n;};String.prototype.findAll=function(string){const matches=[];let i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);}
  143. return matches;};String.prototype.reverse=function(){return this.split('').reverse().join('');};String.prototype.replaceControlCharacters=function(){return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,'�');};String.prototype.isWhitespace=function(){return/^\s*$/.test(this);};String.prototype.computeLineEndings=function(){const endings=this.findAll('\n');endings.push(this.length);return endings;};String.prototype.escapeCharacters=function(chars){let foundChar=false;for(let i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}}
  144. if(!foundChar){return String(this);}
  145. let result='';for(let i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1){result+='\\';}
  146. result+=this.charAt(i);}
  147. return result;};String.regexSpecialCharacters=function(){return'^[]{}()\\.^$*+?|-,';};String.prototype.escapeForRegExp=function(){return this.escapeCharacters(String.regexSpecialCharacters());};String.filterRegex=function(query){const toEscape=String.regexSpecialCharacters();let regexString='';for(let i=0;i<query.length;++i){let c=query.charAt(i);if(toEscape.indexOf(c)!==-1){c='\\'+c;}
  148. if(i){regexString+='[^\\0'+c+']*';}
  149. regexString+=c;}
  150. return new RegExp(regexString,'i');};String.escapeInvalidUnicodeCharacters=function(text){if(!String._invalidCharactersRegExp){let invalidCharacters='';for(let i=0xfffe;i<=0x10ffff;i+=0x10000){invalidCharacters+=String.fromCodePoint(i,i+1);}
  151. String._invalidCharactersRegExp=new RegExp(`[${invalidCharacters}\uD800-\uDFFF\uFDD0-\uFDEF]`,'gu');}
  152. let result='';let lastPos=0;while(true){const match=String._invalidCharactersRegExp.exec(text);if(!match){break;}
  153. result+=text.substring(lastPos,match.index)+'\\u'+text.charCodeAt(match.index).toString(16);if(match.index+1<String._invalidCharactersRegExp.lastIndex){result+='\\u'+text.charCodeAt(match.index+1).toString(16);}
  154. lastPos=String._invalidCharactersRegExp.lastIndex;}
  155. return result+text.substring(lastPos);};String.prototype.escapeHTML=function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');};String.prototype.unescapeHTML=function(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&#58;/g,':').replace(/&quot;/g,'"').replace(/&#60;/g,'<').replace(/&#62;/g,'>').replace(/&amp;/g,'&');};String.prototype.collapseWhitespace=function(){return this.replace(/[\s\xA0]+/g,' ');};String.prototype.trimMiddle=function(maxLength){if(this.length<=maxLength){return String(this);}
  156. let leftHalf=maxLength>>1;let rightHalf=maxLength-leftHalf-1;if(this.codePointAt(this.length-rightHalf-1)>=0x10000){--rightHalf;++leftHalf;}
  157. if(leftHalf>0&&this.codePointAt(leftHalf-1)>=0x10000){--leftHalf;}
  158. return this.substr(0,leftHalf)+'\u2026'+this.substr(this.length-rightHalf,rightHalf);};String.prototype.trimEndWithMaxLength=function(maxLength){if(this.length<=maxLength){return String(this);}
  159. return this.substr(0,maxLength-1)+'\u2026';};String.prototype.trimURL=function(baseURLDomain){let result=this.replace(/^(https|http|file):\/\//i,'');if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase())){result=result.substr(baseURLDomain.length);}}
  160. return result;};String.prototype.toTitleCase=function(){return this.substring(0,1).toUpperCase()+this.substring(1);};String.prototype.compareTo=function(other){if(this>other){return 1;}
  161. if(this<other){return-1;}
  162. return 0;};String.prototype.removeURLFragment=function(){let fragmentIndex=this.indexOf('#');if(fragmentIndex===-1){fragmentIndex=this.length;}
  163. return this.substring(0,fragmentIndex);};String.hashCode=function(string){if(!string){return 0;}
  164. const p=((1<<30)*4-5);const z=0x5033d967;const z2=0x59d2f15d;let s=0;let zi=1;for(let i=0;i<string.length;i++){const xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;}
  165. s=(s+zi*(p-1))%p;return Math.abs(s|0);};String.isDigitAt=function(string,index){const c=string.charCodeAt(index);return(48<=c&&c<=57);};String.prototype.toBase64=function(){function encodeBits(b){return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;}
  166. const encoder=new TextEncoder();const data=encoder.encode(this.toString());const n=data.length;let encoded='';if(n===0){return encoded;}
  167. let shift;let v=0;for(let i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}}
  168. if(shift===0){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);}else if(shift===1){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);}
  169. return encoded;};String.naturalOrderComparator=function(a,b){const chunk=/^\d+|^\D+/;let chunka,chunkb,anum,bnum;while(1){if(a){if(!b){return 1;}}else{if(b){return-1;}else{return 0;}}
  170. chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum){return-1;}
  171. if(bnum&&!anum){return 1;}
  172. if(anum&&bnum){const diff=chunka-chunkb;if(diff){return diff;}
  173. if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb)
  174. {return chunka.length-chunkb.length;}else{return chunkb.length-chunka.length;}}}else if(chunka!==chunkb){return(chunka<chunkb)?-1:1;}
  175. a=a.substring(chunka.length);b=b.substring(chunkb.length);}};String.caseInsensetiveComparator=function(a,b){a=a.toUpperCase();b=b.toUpperCase();if(a===b){return 0;}
  176. return a>b?1:-1;};Number.constrain=function(num,min,max){if(num<min){num=min;}else if(num>max){num=max;}
  177. return num;};Number.gcd=function(a,b){if(b===0){return a;}else{return Number.gcd(b,a%b);}};Number.toFixedIfFloating=function(value){if(!value||isNaN(value)){return value;}
  178. const number=Number(value);return number%1?number.toFixed(3):String(number);};Date.prototype.isValid=function(){return!isNaN(this.getTime());};Date.prototype.toISO8601Compact=function(){function leadZero(x){return(x>9?'':'0')+x;}
  179. return this.getFullYear()+leadZero(this.getMonth()+1)+leadZero(this.getDate())+'T'+
  180. leadZero(this.getHours())+leadZero(this.getMinutes())+leadZero(this.getSeconds());};Object.defineProperty(Array.prototype,'remove',{value:function(value,firstOnly){let index=this.indexOf(value);if(index===-1){return false;}
  181. if(firstOnly){this.splice(index,1);return true;}
  182. for(let i=index+1,n=this.length;i<n;++i){if(this[i]!==value){this[index++]=this[i];}}
  183. this.length=index;return true;}});Object.defineProperty(Array.prototype,'pushAll',{value:function(array){for(let i=0;i<array.length;++i){this.push(array[i]);}}});Object.defineProperty(Array.prototype,'rotate',{value:function(index){const result=[];for(let i=index;i<index+this.length;++i){result.push(this[i%this.length]);}
  184. return result;}});Object.defineProperty(Array.prototype,'sortNumbers',{value:function(){function numericComparator(a,b){return a-b;}
  185. this.sort(numericComparator);}});(function(){const partition={value:function(comparator,left,right,pivotIndex){function swap(array,i1,i2){const temp=array[i1];array[i1]=array[i2];array[i2]=temp;}
  186. const pivotValue=this[pivotIndex];swap(this,right,pivotIndex);let storeIndex=left;for(let i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}}
  187. swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,'partition',partition);Object.defineProperty(Uint32Array.prototype,'partition',partition);const sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight){function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight){if(right<=left){return;}
  188. const pivotIndex=Math.floor(Math.random()*(right-left))+left;const pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex){quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);}
  189. if(pivotNewIndex<sortWindowRight){quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);}}
  190. if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound){this.sort(comparator);}else{quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);}
  191. return this;}};Object.defineProperty(Array.prototype,'sortRange',sortRange);Object.defineProperty(Uint32Array.prototype,'sortRange',sortRange);})();Object.defineProperty(Array.prototype,'lowerBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
  192. comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>0){l=m+1;}else{r=m;}}
  193. return r;}});Object.defineProperty(Array.prototype,'upperBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
  194. comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>=0){l=m+1;}else{r=m;}}
  195. return r;}});Object.defineProperty(Uint32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Int32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Int32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,'binaryIndexOf',{value:function(value,comparator){const index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,'select',{value:function(field){const result=new Array(this.length);for(let i=0;i<this.length;++i){result[i]=this[i][field];}
  196. return result;}});Object.defineProperty(Array.prototype,'peekLast',{value:function(){return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect){const result=[];let i=0;let j=0;while(i<array1.length&&j<array2.length){const compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue){result.push(compareValue<=0?array1[i]:array2[j]);}
  197. if(compareValue<=0){i++;}
  198. if(compareValue>=0){j++;}}
  199. if(mergeNotIntersect){while(i<array1.length){result.push(array1[i++]);}
  200. while(j<array2.length){result.push(array2[j++]);}}
  201. return result;}
  202. Object.defineProperty(Array.prototype,'intersectOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,'mergeOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg){return String.vsprintf(format,Array.prototype.slice.call(arguments,1));};String.tokenizeFormatString=function(format,formatters){const tokens=[];function addStringToken(str){if(!str){return;}
  203. if(tokens.length&&tokens[tokens.length-1].type==='string'){tokens[tokens.length-1].value+=str;}else{tokens.push({type:'string',value:str});}}
  204. function addSpecifierToken(specifier,precision,substitutionIndex){tokens.push({type:'specifier',specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});}
  205. function addAnsiColor(code){const types={3:'color',9:'colorLight',4:'bgColor',10:'bgColorLight'};const colorCodes=['black','red','green','yellow','blue','magenta','cyan','lightGray','','default'];const colorCodesLight=['darkGray','lightRed','lightGreen','lightYellow','lightBlue','lightMagenta','lightCyan','white',''];const colors={color:colorCodes,colorLight:colorCodesLight,bgColor:colorCodes,bgColorLight:colorCodesLight};const type=types[Math.floor(code/10)];if(!type){return;}
  206. const color=colors[type][code%10];if(!color){return;}
  207. tokens.push({type:'specifier',specifier:'c',value:{description:(type.startsWith('bg')?'background : ':'color: ')+color}});}
  208. let textStart=0;let substitutionIndex=0;const re=new RegExp(`%%|%(?:(\\d+)\\$)?(?:\\.(\\d*))?([${Object.keys(formatters).join('')}])|\\u001b\\[(\\d+)m`,'g');for(let match=re.exec(format);!!match;match=re.exec(format)){const matchStart=match.index;if(matchStart>textStart){addStringToken(format.substring(textStart,matchStart));}
  209. if(match[0]==='%%'){addStringToken('%');}else if(match[0].startsWith('%')){const[_,substitionString,precisionString,specifierString]=match;if(substitionString&&Number(substitionString)>0){substitutionIndex=Number(substitionString)-1;}
  210. const precision=precisionString?Number(precisionString):-1;addSpecifierToken(specifierString,precision,substitutionIndex);++substitutionIndex;}else{const code=Number(match[4]);addAnsiColor(code);}
  211. textStart=matchStart+match[0].length;}
  212. addStringToken(format.substring(textStart));return tokens;};String.standardFormatters={d:function(substitution){return!isNaN(substitution)?substitution:0;},f:function(substitution,token){if(substitution&&token.precision>-1){substitution=substitution.toFixed(token.precision);}
  213. return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution){return substitution;}};String.vsprintf=function(format,substitutions){return String.format(format,substitutions,String.standardFormatters,'',function(a,b){return a+b;}).formattedResult;};String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat){if(!format||((!substitutions||!substitutions.length)&&format.search(/\u001b\[(\d+)m/)===-1)){return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};}
  214. function prettyFunctionName(){return'String.format("'+format+'", "'+Array.prototype.join.call(substitutions,'", "')+'")';}
  215. function warn(msg){console.warn(prettyFunctionName()+': '+msg);}
  216. function error(msg){console.error(prettyFunctionName()+': '+msg);}
  217. let result=initialValue;const tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);const usedSubstitutionIndexes={};for(let i=0;i<tokens.length;++i){const token=tokens[i];if(token.type==='string'){result=append(result,token.value);continue;}
  218. if(token.type!=='specifier'){error('Unknown token type "'+token.type+'" found.');continue;}
  219. if(!token.value&&token.substitutionIndex>=substitutions.length){error('not enough substitution arguments. Had '+substitutions.length+' but needed '+
  220. (token.substitutionIndex+1)+', so substitution was skipped.');result=append(result,'%'+(token.precision>-1?token.precision:'')+token.specifier);continue;}
  221. if(!token.value){usedSubstitutionIndexes[token.substitutionIndex]=true;}
  222. if(!(token.specifier in formatters)){warn('unsupported format character \u201C'+token.specifier+'\u201D. Treating as a string.');result=append(result,token.value?'':substitutions[token.substitutionIndex]);continue;}
  223. result=append(result,formatters[token.specifier](token.value||substitutions[token.substitutionIndex],token));}
  224. const unusedSubstitutions=[];for(let i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes){continue;}
  225. unusedSubstitutions.push(substitutions[i]);}
  226. return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};};self.createSearchRegex=function(query,caseSensitive,isRegex){const regexFlags=caseSensitive?'g':'gi';let regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}}
  227. if(!regexObject){regexObject=self.createPlainTextSearchRegex(query,regexFlags);}
  228. return regexObject;};self.createPlainTextSearchRegex=function(query,flags){const regexSpecialCharacters=String.regexSpecialCharacters();let regex='';for(let i=0;i<query.length;++i){const c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1){regex+='\\';}
  229. regex+=c;}
  230. return new RegExp(regex,flags||'');};self.countRegexMatches=function(regex,content){let text=content;let result=0;let match;while(text&&(match=regex.exec(text))){if(match[0].length>0){++result;}
  231. text=text.substring(match.index+1);}
  232. return result;};self.spacesPadding=function(spacesCount){return'\xA0'.repeat(spacesCount);};self.numberToStringWithSpacesPadding=function(value,symbolsCount){const numberString=value.toString();const paddingLength=Math.max(0,symbolsCount-numberString.length);return self.spacesPadding(paddingLength)+numberString;};Set.prototype.valuesArray=function(){return Array.from(this.values());};Set.prototype.firstValue=function(){if(!this.size){return null;}
  233. return this.values().next().value;};Set.prototype.addAll=function(iterable){for(const e of iterable){this.add(e);}};Set.prototype.containsAll=function(iterable){for(const e of iterable){if(!this.has(e)){return false;}}
  234. return true;};Map.prototype.remove=function(key){const value=this.get(key);this.delete(key);return value;};Map.prototype.valuesArray=function(){return Array.from(this.values());};Map.prototype.keysArray=function(){return Array.from(this.keys());};Map.prototype.inverse=function(){const result=new Platform.Multimap();for(const key of this.keys()){const value=this.get(key);result.set(value,key);}
  235. return result;};const Multimap=class{constructor(){this._map=new Map();}
  236. set(key,value){let set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);}
  237. set.add(value);}
  238. get(key){return this._map.get(key)||new Set();}
  239. has(key){return this._map.has(key);}
  240. hasValue(key,value){const set=this._map.get(key);if(!set){return false;}
  241. return set.has(value);}
  242. get size(){return this._map.size;}
  243. delete(key,value){const values=this.get(key);if(!values){return false;}
  244. const result=values.delete(value);if(!values.size){this._map.delete(key);}
  245. return result;}
  246. deleteAll(key){this._map.delete(key);}
  247. keysArray(){return this._map.keysArray();}
  248. valuesArray(){const result=[];const keys=this.keysArray();for(let i=0;i<keys.length;++i){result.pushAll(this.get(keys[i]).valuesArray());}
  249. return result;}
  250. clear(){this._map.clear();}};self.loadXHR=function(url){return new Promise(load);function load(successCallback,failureCallback){function onReadyStateChanged(){if(xhr.readyState!==XMLHttpRequest.DONE){return;}
  251. if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;}
  252. xhr.onreadystatechange=null;successCallback(xhr.responseText);}
  253. const xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open('GET',url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}};self.suppressUnused=function(value){};self.setImmediate=function(callback){const args=[...arguments].slice(1);Promise.resolve().then(()=>callback(...args));return 0;};Promise.prototype.spread=function(callback){return this.then(spreadPromise);function spreadPromise(arg){return callback.apply(null,arg);}};Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});};Map.prototype.diff=function(other,isEqual){const leftKeys=this.keysArray();const rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);const removed=[];const added=[];const equal=[];let leftIndex=0;let rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){const leftKey=leftKeys[leftIndex];const rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;}
  254. if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;}
  255. added.push(other.get(rightKey));++rightIndex;}
  256. while(leftIndex<leftKeys.length){const leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));}
  257. while(rightIndex<rightKeys.length){const rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));}
  258. return{added:added,removed:removed,equal:equal};};self.runOnWindowLoad=function(callback){function windowLoaded(){self.removeEventListener('DOMContentLoaded',windowLoaded,false);callback();}
  259. if(document.readyState==='complete'||document.readyState==='interactive'){callback();}else{self.addEventListener('DOMContentLoaded',windowLoaded,false);}};const _singletonSymbol=Symbol('singleton');self.singleton=function(constructorFunction){if(_singletonSymbol in constructorFunction){return constructorFunction[_singletonSymbol];}
  260. const instance=new constructorFunction();constructorFunction[_singletonSymbol]=instance;return instance;};self.base64ToSize=function(content){if(!content){return 0;}
  261. let size=content.length*3/4;if(content[content.length-1]==='='){size--;}
  262. if(content.length>1&&content[content.length-2]==='='){size--;}
  263. return size;};self.Platform=self.Platform||{};Platform=Platform||{};Platform.Multimap=Multimap;class Text{constructor(value){this._value=value;}
  264. lineEndings(){if(!this._lineEndings){this._lineEndings=this._value.computeLineEndings();}
  265. return this._lineEndings;}
  266. value(){return this._value;}
  267. lineCount(){const lineEndings=this.lineEndings();return lineEndings.length;}
  268. offsetFromPosition(lineNumber,columnNumber){return(lineNumber?this.lineEndings()[lineNumber-1]+1:0)+columnNumber;}
  269. positionFromOffset(offset){const lineEndings=this.lineEndings();const lineNumber=lineEndings.lowerBound(offset);return{lineNumber:lineNumber,columnNumber:offset-(lineNumber&&(lineEndings[lineNumber-1]+1))};}
  270. lineAt(lineNumber){const lineEndings=this.lineEndings();const lineStart=lineNumber>0?lineEndings[lineNumber-1]+1:0;const lineEnd=lineEndings[lineNumber];let lineContent=this._value.substring(lineStart,lineEnd);if(lineContent.length>0&&lineContent.charAt(lineContent.length-1)==='\r'){lineContent=lineContent.substring(0,lineContent.length-1);}
  271. return lineContent;}
  272. toSourceRange(range){const start=this.offsetFromPosition(range.startLine,range.startColumn);const end=this.offsetFromPosition(range.endLine,range.endColumn);return new TextUtils.SourceRange(start,end-start);}
  273. toTextRange(sourceRange){const cursor=new TextCursor(this.lineEndings());const result=TextUtils.TextRange.createFromLocation(0,0);cursor.resetTo(sourceRange.offset);result.startLine=cursor.lineNumber();result.startColumn=cursor.columnNumber();cursor.advance(sourceRange.offset+sourceRange.length);result.endLine=cursor.lineNumber();result.endColumn=cursor.columnNumber();return result;}
  274. replaceRange(range,replacement){const sourceRange=this.toSourceRange(range);return this._value.substring(0,sourceRange.offset)+replacement+
  275. this._value.substring(sourceRange.offset+sourceRange.length);}
  276. extract(range){const sourceRange=this.toSourceRange(range);return this._value.substr(sourceRange.offset,sourceRange.length);}}
  277. class TextCursor{constructor(lineEndings){this._lineEndings=lineEndings;this._offset=0;this._lineNumber=0;this._columnNumber=0;}
  278. advance(offset){this._offset=offset;while(this._lineNumber<this._lineEndings.length&&this._lineEndings[this._lineNumber]<this._offset){++this._lineNumber;}
  279. this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
  280. offset(){return this._offset;}
  281. resetTo(offset){this._offset=offset;this._lineNumber=this._lineEndings.lowerBound(offset);this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
  282. lineNumber(){return this._lineNumber;}
  283. columnNumber(){return this._columnNumber;}}
  284. self.TextUtils=self.TextUtils||{};TextUtils=TextUtils||{};TextUtils.Text=Text;TextUtils.TextCursor=TextCursor;TextUtils.Text.Position;class TextRange{constructor(startLine,startColumn,endLine,endColumn){this.startLine=startLine;this.startColumn=startColumn;this.endLine=endLine;this.endColumn=endColumn;}
  285. static createFromLocation(line,column){return new TextRange(line,column,line,column);}
  286. static fromObject(serializedTextRange){return new TextRange(serializedTextRange.startLine,serializedTextRange.startColumn,serializedTextRange.endLine,serializedTextRange.endColumn);}
  287. static comparator(range1,range2){return range1.compareTo(range2);}
  288. static fromEdit(oldRange,newText){let endLine=oldRange.startLine;let endColumn=oldRange.startColumn+newText.length;const lineEndings=newText.computeLineEndings();if(lineEndings.length>1){endLine=oldRange.startLine+lineEndings.length-1;const len=lineEndings.length;endColumn=lineEndings[len-1]-lineEndings[len-2]-1;}
  289. return new TextRange(oldRange.startLine,oldRange.startColumn,endLine,endColumn);}
  290. isEmpty(){return this.startLine===this.endLine&&this.startColumn===this.endColumn;}
  291. immediatelyPrecedes(range){if(!range){return false;}
  292. return this.endLine===range.startLine&&this.endColumn===range.startColumn;}
  293. immediatelyFollows(range){if(!range){return false;}
  294. return range.immediatelyPrecedes(this);}
  295. follows(range){return(range.endLine===this.startLine&&range.endColumn<=this.startColumn)||range.endLine<this.startLine;}
  296. get linesCount(){return this.endLine-this.startLine;}
  297. collapseToEnd(){return new TextRange(this.endLine,this.endColumn,this.endLine,this.endColumn);}
  298. collapseToStart(){return new TextRange(this.startLine,this.startColumn,this.startLine,this.startColumn);}
  299. normalize(){if(this.startLine>this.endLine||(this.startLine===this.endLine&&this.startColumn>this.endColumn)){return new TextRange(this.endLine,this.endColumn,this.startLine,this.startColumn);}else{return this.clone();}}
  300. clone(){return new TextRange(this.startLine,this.startColumn,this.endLine,this.endColumn);}
  301. serializeToObject(){const serializedTextRange={};serializedTextRange.startLine=this.startLine;serializedTextRange.startColumn=this.startColumn;serializedTextRange.endLine=this.endLine;serializedTextRange.endColumn=this.endColumn;return serializedTextRange;}
  302. compareTo(other){if(this.startLine>other.startLine){return 1;}
  303. if(this.startLine<other.startLine){return-1;}
  304. if(this.startColumn>other.startColumn){return 1;}
  305. if(this.startColumn<other.startColumn){return-1;}
  306. return 0;}
  307. compareToPosition(lineNumber,columnNumber){if(lineNumber<this.startLine||(lineNumber===this.startLine&&columnNumber<this.startColumn)){return-1;}
  308. if(lineNumber>this.endLine||(lineNumber===this.endLine&&columnNumber>this.endColumn)){return 1;}
  309. return 0;}
  310. equal(other){return this.startLine===other.startLine&&this.endLine===other.endLine&&this.startColumn===other.startColumn&&this.endColumn===other.endColumn;}
  311. relativeTo(line,column){const relative=this.clone();if(this.startLine===line){relative.startColumn-=column;}
  312. if(this.endLine===line){relative.endColumn-=column;}
  313. relative.startLine-=line;relative.endLine-=line;return relative;}
  314. relativeFrom(line,column){const relative=this.clone();if(this.startLine===0){relative.startColumn+=column;}
  315. if(this.endLine===0){relative.endColumn+=column;}
  316. relative.startLine+=line;relative.endLine+=line;return relative;}
  317. rebaseAfterTextEdit(originalRange,editedRange){console.assert(originalRange.startLine===editedRange.startLine);console.assert(originalRange.startColumn===editedRange.startColumn);const rebase=this.clone();if(!this.follows(originalRange)){return rebase;}
  318. const lineDelta=editedRange.endLine-originalRange.endLine;const columnDelta=editedRange.endColumn-originalRange.endColumn;rebase.startLine+=lineDelta;rebase.endLine+=lineDelta;if(rebase.startLine===editedRange.endLine){rebase.startColumn+=columnDelta;}
  319. if(rebase.endLine===editedRange.endLine){rebase.endColumn+=columnDelta;}
  320. return rebase;}
  321. toString(){return JSON.stringify(this);}
  322. containsLocation(lineNumber,columnNumber){if(this.startLine===this.endLine){return this.startLine===lineNumber&&this.startColumn<=columnNumber&&columnNumber<=this.endColumn;}
  323. if(this.startLine===lineNumber){return this.startColumn<=columnNumber;}
  324. if(this.endLine===lineNumber){return columnNumber<=this.endColumn;}
  325. return this.startLine<lineNumber&&lineNumber<this.endLine;}}
  326. class SourceRange{constructor(offset,length){this.offset=offset;this.length=length;}}
  327. class SourceEdit{constructor(sourceURL,oldRange,newText){this.sourceURL=sourceURL;this.oldRange=oldRange;this.newText=newText;}
  328. static comparator(edit1,edit2){return TextRange.comparator(edit1.oldRange,edit2.oldRange);}
  329. newRange(){return TextRange.fromEdit(this.oldRange,this.newText);}}
  330. self.TextUtils=self.TextUtils||{};TextUtils=TextUtils||{};TextUtils.TextRange=TextRange;TextUtils.SourceRange=SourceRange;TextUtils.SourceEdit=SourceEdit;const Utils={isStopChar:function(char){return(char>' '&&char<'0')||(char>'9'&&char<'A')||(char>'Z'&&char<'_')||(char>'_'&&char<'a')||(char>'z'&&char<='~');},isWordChar:function(char){return!TextUtils.TextUtils.isStopChar(char)&&!TextUtils.TextUtils.isSpaceChar(char);},isSpaceChar:function(char){return TextUtils.TextUtils._SpaceCharRegex.test(char);},isWord:function(word){for(let i=0;i<word.length;++i){if(!TextUtils.TextUtils.isWordChar(word.charAt(i))){return false;}}
  331. return true;},isOpeningBraceChar:function(char){return char==='('||char==='{';},isClosingBraceChar:function(char){return char===')'||char==='}';},isBraceChar:function(char){return TextUtils.TextUtils.isOpeningBraceChar(char)||TextUtils.TextUtils.isClosingBraceChar(char);},textToWords:function(text,isWordChar,wordCallback){let startWord=-1;for(let i=0;i<text.length;++i){if(!isWordChar(text.charAt(i))){if(startWord!==-1){wordCallback(text.substring(startWord,i));}
  332. startWord=-1;}else if(startWord===-1){startWord=i;}}
  333. if(startWord!==-1){wordCallback(text.substring(startWord));}},lineIndent:function(line){let indentation=0;while(indentation<line.length&&TextUtils.TextUtils.isSpaceChar(line.charAt(indentation))){++indentation;}
  334. return line.substr(0,indentation);},isUpperCase:function(text){return text===text.toUpperCase();},isLowerCase:function(text){return text===text.toLowerCase();},splitStringByRegexes(text,regexes){const matches=[];const globalRegexes=[];for(let i=0;i<regexes.length;i++){const regex=regexes[i];if(!regex.global){globalRegexes.push(new RegExp(regex.source,regex.flags?regex.flags+'g':'g'));}else{globalRegexes.push(regex);}}
  335. doSplit(text,0,0);return matches;function doSplit(text,regexIndex,startIndex){if(regexIndex>=globalRegexes.length){matches.push({value:text,position:startIndex,regexIndex:-1,captureGroups:[]});return;}
  336. const regex=globalRegexes[regexIndex];let currentIndex=0;let result;regex.lastIndex=0;while((result=regex.exec(text))!==null){const stringBeforeMatch=text.substring(currentIndex,result.index);if(stringBeforeMatch){doSplit(stringBeforeMatch,regexIndex+1,startIndex+currentIndex);}
  337. const match=result[0];matches.push({value:match,position:startIndex+result.index,regexIndex:regexIndex,captureGroups:result.slice(1)});currentIndex=result.index+match.length;}
  338. const stringAfterMatches=text.substring(currentIndex);if(stringAfterMatches){doSplit(stringAfterMatches,regexIndex+1,startIndex+currentIndex);}}}};class FilterParser{constructor(keys){this._keys=keys;}
  339. static cloneFilter(filter){return{key:filter.key,text:filter.text,regex:filter.regex,negative:filter.negative};}
  340. parse(query){const splitResult=TextUtils.TextUtils.splitStringByRegexes(query,[TextUtils.TextUtils._keyValueFilterRegex,TextUtils.TextUtils._regexFilterRegex,TextUtils.TextUtils._textFilterRegex]);const filters=[];for(let i=0;i<splitResult.length;i++){const regexIndex=splitResult[i].regexIndex;if(regexIndex===-1){continue;}
  341. const result=splitResult[i].captureGroups;if(regexIndex===0){if(this._keys.indexOf((result[1]))!==-1){filters.push({key:result[1],text:result[2],negative:!!result[0]});}else{filters.push({text:result[1]+':'+result[2],negative:!!result[0]});}}else if(regexIndex===1){try{filters.push({regex:new RegExp(result[1],'i'),negative:!!result[0]});}catch(e){filters.push({text:'/'+result[1]+'/',negative:!!result[0]});}}else if(regexIndex===2){filters.push({text:result[1],negative:!!result[0]});}}
  342. return filters;}}
  343. Utils._keyValueFilterRegex=/(?:^|\s)(\-)?([\w\-]+):([^\s]+)/;Utils._regexFilterRegex=/(?:^|\s)(\-)?\/([^\s]+)\//;Utils._textFilterRegex=/(?:^|\s)(\-)?([^\s]+)/;Utils._SpaceCharRegex=/\s/;Utils.Indent={TwoSpaces:' ',FourSpaces:' ',EightSpaces:' ',TabCharacter:'\t'};class BalancedJSONTokenizer{constructor(callback,findMultiple){this._callback=callback;this._index=0;this._balance=0;this._buffer='';this._findMultiple=findMultiple||false;this._closingDoubleQuoteRegex=/[^\\](?:\\\\)*"/g;}
  344. write(chunk){this._buffer+=chunk;const lastIndex=this._buffer.length;const buffer=this._buffer;let index;for(index=this._index;index<lastIndex;++index){const character=buffer[index];if(character==='"'){this._closingDoubleQuoteRegex.lastIndex=index;if(!this._closingDoubleQuoteRegex.test(buffer)){break;}
  345. index=this._closingDoubleQuoteRegex.lastIndex-1;}else if(character==='{'){++this._balance;}else if(character==='}'){--this._balance;if(this._balance<0){this._reportBalanced();return false;}
  346. if(!this._balance){this._lastBalancedIndex=index+1;if(!this._findMultiple){break;}}}else if(character===']'&&!this._balance){this._reportBalanced();return false;}}
  347. this._index=index;this._reportBalanced();return true;}
  348. _reportBalanced(){if(!this._lastBalancedIndex){return;}
  349. this._callback(this._buffer.slice(0,this._lastBalancedIndex));this._buffer=this._buffer.slice(this._lastBalancedIndex);this._index-=this._lastBalancedIndex;this._lastBalancedIndex=0;}
  350. remainder(){return this._buffer;}}
  351. class TokenizerFactory{createTokenizer(mimeType){}}
  352. function isMinified(text){const kMaxNonMinifiedLength=500;let linesToCheck=10;let lastPosition=0;do{let eolIndex=text.indexOf('\n',lastPosition);if(eolIndex<0){eolIndex=text.length;}
  353. if(eolIndex-lastPosition>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#'){return true;}
  354. lastPosition=eolIndex+1;}while(--linesToCheck>=0&&lastPosition<text.length);linesToCheck=10;lastPosition=text.length;do{let eolIndex=text.lastIndexOf('\n',lastPosition);if(eolIndex<0){eolIndex=0;}
  355. if(lastPosition-eolIndex>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#'){return true;}
  356. lastPosition=eolIndex-1;}while(--linesToCheck>=0&&lastPosition>0);return false;}
  357. self.TextUtils=self.TextUtils||{};TextUtils=TextUtils||{};TextUtils.TextUtils=Utils;TextUtils.FilterParser=FilterParser;TextUtils.BalancedJSONTokenizer=BalancedJSONTokenizer;TextUtils.TokenizerFactory=TokenizerFactory;TextUtils.isMinified=isMinified;TextUtils.FilterParser.ParsedFilter;class App{presentUI(document){}}
  358. self.Common=self.Common||{};Common=Common||{};Common.App=App;class AppProvider{createApp(){}}
  359. self.Common=self.Common||{};Common=Common||{};Common.AppProvider=AppProvider;class CharacterIdMap{constructor(){this._elementToCharacter=new Map();this._characterToElement=new Map();this._charCode=33;}
  360. toChar(object){let character=this._elementToCharacter.get(object);if(!character){if(this._charCode>=0xFFFF){throw new Error('CharacterIdMap ran out of capacity!');}
  361. character=String.fromCharCode(this._charCode++);this._elementToCharacter.set(object,character);this._characterToElement.set(character,object);}
  362. return character;}
  363. fromChar(character){const object=this._characterToElement.get(character);if(object===undefined){return null;}
  364. return object;}}
  365. self.Common=self.Common||{};Common=Common||{};Common.CharacterIdMap=CharacterIdMap;class Color{constructor(rgba,format,originalText){this._rgba=rgba;this._originalText=originalText||null;this._originalTextIsValid=!!this._originalText;this._format=format;if(typeof this._rgba[3]==='undefined'){this._rgba[3]=1;}
  366. for(let i=0;i<4;++i){if(this._rgba[i]<0){this._rgba[i]=0;this._originalTextIsValid=false;}
  367. if(this._rgba[i]>1){this._rgba[i]=1;this._originalTextIsValid=false;}}}
  368. static parse(text){const value=text.toLowerCase().replace(/\s+/g,'');const simple=/^(?:#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(\w+))$/i;let match=value.match(simple);if(match){if(match[1]){let hex=match[1].toLowerCase();let format;if(hex.length===3){format=Format.ShortHEX;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2);}else if(hex.length===4){format=Format.ShortHEXA;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2)+
  369. hex.charAt(3)+hex.charAt(3);}else if(hex.length===6){format=Format.HEX;}else{format=Format.HEXA;}
  370. const r=parseInt(hex.substring(0,2),16);const g=parseInt(hex.substring(2,4),16);const b=parseInt(hex.substring(4,6),16);let a=1;if(hex.length===8){a=parseInt(hex.substring(6,8),16)/255;}
  371. return new Color([r/255,g/255,b/255,a],format,text);}
  372. if(match[2]){const nickname=match[2].toLowerCase();if(nickname in Nicknames){const rgba=Nicknames[nickname];const color=Color.fromRGBA(rgba);color._format=Format.Nickname;color._originalText=text;return color;}
  373. return null;}
  374. return null;}
  375. match=text.toLowerCase().match(/^\s*(?:(rgba?)|(hsla?))\((.*)\)\s*$/);if(match){const components=match[3].trim();let values=components.split(/\s*,\s*/);if(values.length===1){values=components.split(/\s+/);if(values[3]==='/'){values.splice(3,1);if(values.length!==4){return null;}}else if((values.length>2&&values[2].indexOf('/')!==-1)||(values.length>3&&values[3].indexOf('/')!==-1)){const alpha=values.slice(2,4).join('');values=values.slice(0,2).concat(alpha.split(/\//)).concat(values.slice(4));}else if(values.length>=4){return null;}}
  376. if(values.length!==3&&values.length!==4||values.indexOf('')>-1){return null;}
  377. const hasAlpha=(values[3]!==undefined);if(match[1]){const rgba=[Color._parseRgbNumeric(values[0]),Color._parseRgbNumeric(values[1]),Color._parseRgbNumeric(values[2]),hasAlpha?Color._parseAlphaNumeric(values[3]):1];if(rgba.indexOf(null)>-1){return null;}
  378. return new Color(rgba,hasAlpha?Format.RGBA:Format.RGB,text);}
  379. if(match[2]){const hsla=[Color._parseHueNumeric(values[0]),Color._parseSatLightNumeric(values[1]),Color._parseSatLightNumeric(values[2]),hasAlpha?Color._parseAlphaNumeric(values[3]):1];if(hsla.indexOf(null)>-1){return null;}
  380. const rgba=[];Color.hsl2rgb(hsla,rgba);return new Color(rgba,hasAlpha?Format.HSLA:Format.HSL,text);}}
  381. return null;}
  382. static fromRGBA(rgba){return new Color([rgba[0]/255,rgba[1]/255,rgba[2]/255,rgba[3]],Format.RGBA);}
  383. static fromHSVA(hsva){const rgba=[];Color.hsva2rgba(hsva,rgba);return new Color(rgba,Format.HSLA);}
  384. static _parsePercentOrNumber(value){if(isNaN(value.replace('%',''))){return null;}
  385. const parsed=parseFloat(value);if(value.indexOf('%')!==-1){if(value.indexOf('%')!==value.length-1){return null;}
  386. return parsed/100;}
  387. return parsed;}
  388. static _parseRgbNumeric(value){const parsed=Color._parsePercentOrNumber(value);if(parsed===null){return null;}
  389. if(value.indexOf('%')!==-1){return parsed;}
  390. return parsed/255;}
  391. static _parseHueNumeric(value){const angle=value.replace(/(deg|g?rad|turn)$/,'');if(isNaN(angle)||value.match(/\s+(deg|g?rad|turn)/)){return null;}
  392. const number=parseFloat(angle);if(value.indexOf('turn')!==-1){return number%1;}else if(value.indexOf('grad')!==-1){return(number/400)%1;}else if(value.indexOf('rad')!==-1){return(number/(2*Math.PI))%1;}
  393. return(number/360)%1;}
  394. static _parseSatLightNumeric(value){if(value.indexOf('%')!==value.length-1||isNaN(value.replace('%',''))){return null;}
  395. const parsed=parseFloat(value);return Math.min(1,parsed/100);}
  396. static _parseAlphaNumeric(value){return Color._parsePercentOrNumber(value);}
  397. static _hsva2hsla(hsva,out_hsla){const h=hsva[0];let s=hsva[1];const v=hsva[2];const t=(2-s)*v;if(v===0||s===0){s=0;}else{s*=v/(t<1?t:2-t);}
  398. out_hsla[0]=h;out_hsla[1]=s;out_hsla[2]=t/2;out_hsla[3]=hsva[3];}
  399. static hsl2rgb(hsl,out_rgb){const h=hsl[0];let s=hsl[1];const l=hsl[2];function hue2rgb(p,q,h){if(h<0){h+=1;}else if(h>1){h-=1;}
  400. if((h*6)<1){return p+(q-p)*h*6;}else if((h*2)<1){return q;}else if((h*3)<2){return p+(q-p)*((2/3)-h)*6;}else{return p;}}
  401. if(s<0){s=0;}
  402. let q;if(l<=0.5){q=l*(1+s);}else{q=l+s-(l*s);}
  403. const p=2*l-q;const tr=h+(1/3);const tg=h;const tb=h-(1/3);out_rgb[0]=hue2rgb(p,q,tr);out_rgb[1]=hue2rgb(p,q,tg);out_rgb[2]=hue2rgb(p,q,tb);out_rgb[3]=hsl[3];}
  404. static hsva2rgba(hsva,out_rgba){Color._hsva2hsla(hsva,Color.hsva2rgba._tmpHSLA);Color.hsl2rgb(Color.hsva2rgba._tmpHSLA,out_rgba);for(let i=0;i<Color.hsva2rgba._tmpHSLA.length;i++){Color.hsva2rgba._tmpHSLA[i]=0;}}
  405. static luminance(rgba){const rSRGB=rgba[0];const gSRGB=rgba[1];const bSRGB=rgba[2];const r=rSRGB<=0.03928?rSRGB/12.92:Math.pow(((rSRGB+0.055)/1.055),2.4);const g=gSRGB<=0.03928?gSRGB/12.92:Math.pow(((gSRGB+0.055)/1.055),2.4);const b=bSRGB<=0.03928?bSRGB/12.92:Math.pow(((bSRGB+0.055)/1.055),2.4);return 0.2126*r+0.7152*g+0.0722*b;}
  406. static blendColors(fgRGBA,bgRGBA,out_blended){const alpha=fgRGBA[3];out_blended[0]=((1-alpha)*bgRGBA[0])+(alpha*fgRGBA[0]);out_blended[1]=((1-alpha)*bgRGBA[1])+(alpha*fgRGBA[1]);out_blended[2]=((1-alpha)*bgRGBA[2])+(alpha*fgRGBA[2]);out_blended[3]=alpha+(bgRGBA[3]*(1-alpha));}
  407. static calculateContrastRatio(fgRGBA,bgRGBA){Color.blendColors(fgRGBA,bgRGBA,Color.calculateContrastRatio._blendedFg);const fgLuminance=Color.luminance(Color.calculateContrastRatio._blendedFg);const bgLuminance=Color.luminance(bgRGBA);const contrastRatio=(Math.max(fgLuminance,bgLuminance)+0.05)/(Math.min(fgLuminance,bgLuminance)+0.05);for(let i=0;i<Color.calculateContrastRatio._blendedFg.length;i++){Color.calculateContrastRatio._blendedFg[i]=0;}
  408. return contrastRatio;}
  409. static desiredLuminance(luminance,contrast,lighter){function computeLuminance(){if(lighter){return(luminance+0.05)*contrast-0.05;}else{return(luminance+0.05)/contrast-0.05;}}
  410. let desiredLuminance=computeLuminance();if(desiredLuminance<0||desiredLuminance>1){lighter=!lighter;desiredLuminance=computeLuminance();}
  411. return desiredLuminance;}
  412. static detectColorFormat(color){const cf=Format;let format;const formatSetting=Common.moduleSetting('colorFormat').get();if(formatSetting===cf.Original){format=cf.Original;}else if(formatSetting===cf.RGB){format=(color.hasAlpha()?cf.RGBA:cf.RGB);}else if(formatSetting===cf.HSL){format=(color.hasAlpha()?cf.HSLA:cf.HSL);}else if(formatSetting===cf.HEX){format=color.detectHEXFormat();}else{format=cf.RGBA;}
  413. return format;}
  414. format(){return this._format;}
  415. hsla(){if(this._hsla){return this._hsla;}
  416. const r=this._rgba[0];const g=this._rgba[1];const b=this._rgba[2];const max=Math.max(r,g,b);const min=Math.min(r,g,b);const diff=max-min;const add=max+min;let h;if(min===max){h=0;}else if(r===max){h=((1/6*(g-b)/diff)+1)%1;}else if(g===max){h=(1/6*(b-r)/diff)+1/3;}else{h=(1/6*(r-g)/diff)+2/3;}
  417. const l=0.5*add;let s;if(l===0){s=0;}else if(l===1){s=0;}else if(l<=0.5){s=diff/add;}else{s=diff/(2-add);}
  418. this._hsla=[h,s,l,this._rgba[3]];return this._hsla;}
  419. canonicalHSLA(){const hsla=this.hsla();return[Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]];}
  420. hsva(){const hsla=this.hsla();const h=hsla[0];let s=hsla[1];const l=hsla[2];s*=l<0.5?l:1-l;return[h,s!==0?2*s/(l+s):0,(l+s),hsla[3]];}
  421. hasAlpha(){return this._rgba[3]!==1;}
  422. detectHEXFormat(){let canBeShort=true;for(let i=0;i<4;++i){const c=Math.round(this._rgba[i]*255);if(c%17){canBeShort=false;break;}}
  423. const hasAlpha=this.hasAlpha();const cf=Format;if(canBeShort){return hasAlpha?cf.ShortHEXA:cf.ShortHEX;}
  424. return hasAlpha?cf.HEXA:cf.HEX;}
  425. asString(format){if(format===this._format&&this._originalTextIsValid){return this._originalText;}
  426. if(!format){format=this._format;}
  427. function toRgbValue(value){return Math.round(value*255);}
  428. function toHexValue(value){const hex=Math.round(value*255).toString(16);return hex.length===1?'0'+hex:hex;}
  429. function toShortHexValue(value){return(Math.round(value*255)/17).toString(16);}
  430. switch(format){case Format.Original:return this._originalText;case Format.RGB:if(this.hasAlpha()){return null;}
  431. return String.sprintf('rgb(%d, %d, %d)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]));case Format.RGBA:return String.sprintf('rgba(%d, %d, %d, %f)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]),this._rgba[3]);case Format.HSL:if(this.hasAlpha()){return null;}
  432. const hsl=this.hsla();return String.sprintf('hsl(%d, %d%, %d%)',Math.round(hsl[0]*360),Math.round(hsl[1]*100),Math.round(hsl[2]*100));case Format.HSLA:const hsla=this.hsla();return String.sprintf('hsla(%d, %d%, %d%, %f)',Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]);case Format.HEXA:return String.sprintf('#%s%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2]),toHexValue(this._rgba[3])).toLowerCase();case Format.HEX:if(this.hasAlpha()){return null;}
  433. return String.sprintf('#%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2])).toLowerCase();case Format.ShortHEXA:const hexFormat=this.detectHEXFormat();if(hexFormat!==Format.ShortHEXA&&hexFormat!==Format.ShortHEX){return null;}
  434. return String.sprintf('#%s%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2]),toShortHexValue(this._rgba[3])).toLowerCase();case Format.ShortHEX:if(this.hasAlpha()){return null;}
  435. if(this.detectHEXFormat()!==Format.ShortHEX){return null;}
  436. return String.sprintf('#%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2])).toLowerCase();case Format.Nickname:return this.nickname();}
  437. return this._originalText;}
  438. rgba(){return this._rgba.slice();}
  439. canonicalRGBA(){const rgba=new Array(4);for(let i=0;i<3;++i){rgba[i]=Math.round(this._rgba[i]*255);}
  440. rgba[3]=this._rgba[3];return rgba;}
  441. nickname(){if(!Color._rgbaToNickname){Color._rgbaToNickname={};for(const nickname in Nicknames){let rgba=Nicknames[nickname];if(rgba.length!==4){rgba=rgba.concat(1);}
  442. Color._rgbaToNickname[rgba]=nickname;}}
  443. return Color._rgbaToNickname[this.canonicalRGBA()]||null;}
  444. toProtocolRGBA(){const rgba=this.canonicalRGBA();const result={r:rgba[0],g:rgba[1],b:rgba[2]};if(rgba[3]!==1){result.a=rgba[3];}
  445. return result;}
  446. invert(){const rgba=[];rgba[0]=1-this._rgba[0];rgba[1]=1-this._rgba[1];rgba[2]=1-this._rgba[2];rgba[3]=this._rgba[3];return new Color(rgba,Format.RGBA);}
  447. setAlpha(alpha){const rgba=this._rgba.slice();rgba[3]=alpha;return new Color(rgba,Format.RGBA);}
  448. blendWith(fgColor){const rgba=[];Color.blendColors(fgColor._rgba,this._rgba,rgba);return new Color(rgba,Format.RGBA);}}
  449. const Regex=/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g;const Format={Original:'original',Nickname:'nickname',HEX:'hex',ShortHEX:'shorthex',HEXA:'hexa',ShortHEXA:'shorthexa',RGB:'rgb',RGBA:'rgba',HSL:'hsl',HSLA:'hsla'};const Nicknames={'aliceblue':[240,248,255],'antiquewhite':[250,235,215],'aqua':[0,255,255],'aquamarine':[127,255,212],'azure':[240,255,255],'beige':[245,245,220],'bisque':[255,228,196],'black':[0,0,0],'blanchedalmond':[255,235,205],'blue':[0,0,255],'blueviolet':[138,43,226],'brown':[165,42,42],'burlywood':[222,184,135],'cadetblue':[95,158,160],'chartreuse':[127,255,0],'chocolate':[210,105,30],'coral':[255,127,80],'cornflowerblue':[100,149,237],'cornsilk':[255,248,220],'crimson':[237,20,61],'cyan':[0,255,255],'darkblue':[0,0,139],'darkcyan':[0,139,139],'darkgoldenrod':[184,134,11],'darkgray':[169,169,169],'darkgrey':[169,169,169],'darkgreen':[0,100,0],'darkkhaki':[189,183,107],'darkmagenta':[139,0,139],'darkolivegreen':[85,107,47],'darkorange':[255,140,0],'darkorchid':[153,50,204],'darkred':[139,0,0],'darksalmon':[233,150,122],'darkseagreen':[143,188,143],'darkslateblue':[72,61,139],'darkslategray':[47,79,79],'darkslategrey':[47,79,79],'darkturquoise':[0,206,209],'darkviolet':[148,0,211],'deeppink':[255,20,147],'deepskyblue':[0,191,255],'dimgray':[105,105,105],'dimgrey':[105,105,105],'dodgerblue':[30,144,255],'firebrick':[178,34,34],'floralwhite':[255,250,240],'forestgreen':[34,139,34],'fuchsia':[255,0,255],'gainsboro':[220,220,220],'ghostwhite':[248,248,255],'gold':[255,215,0],'goldenrod':[218,165,32],'gray':[128,128,128],'grey':[128,128,128],'green':[0,128,0],'greenyellow':[173,255,47],'honeydew':[240,255,240],'hotpink':[255,105,180],'indianred':[205,92,92],'indigo':[75,0,130],'ivory':[255,255,240],'khaki':[240,230,140],'lavender':[230,230,250],'lavenderblush':[255,240,245],'lawngreen':[124,252,0],'lemonchiffon':[255,250,205],'lightblue':[173,216,230],'lightcoral':[240,128,128],'lightcyan':[224,255,255],'lightgoldenrodyellow':[250,250,210],'lightgreen':[144,238,144],'lightgray':[211,211,211],'lightgrey':[211,211,211],'lightpink':[255,182,193],'lightsalmon':[255,160,122],'lightseagreen':[32,178,170],'lightskyblue':[135,206,250],'lightslategray':[119,136,153],'lightslategrey':[119,136,153],'lightsteelblue':[176,196,222],'lightyellow':[255,255,224],'lime':[0,255,0],'limegreen':[50,205,50],'linen':[250,240,230],'magenta':[255,0,255],'maroon':[128,0,0],'mediumaquamarine':[102,205,170],'mediumblue':[0,0,205],'mediumorchid':[186,85,211],'mediumpurple':[147,112,219],'mediumseagreen':[60,179,113],'mediumslateblue':[123,104,238],'mediumspringgreen':[0,250,154],'mediumturquoise':[72,209,204],'mediumvioletred':[199,21,133],'midnightblue':[25,25,112],'mintcream':[245,255,250],'mistyrose':[255,228,225],'moccasin':[255,228,181],'navajowhite':[255,222,173],'navy':[0,0,128],'oldlace':[253,245,230],'olive':[128,128,0],'olivedrab':[107,142,35],'orange':[255,165,0],'orangered':[255,69,0],'orchid':[218,112,214],'palegoldenrod':[238,232,170],'palegreen':[152,251,152],'paleturquoise':[175,238,238],'palevioletred':[219,112,147],'papayawhip':[255,239,213],'peachpuff':[255,218,185],'peru':[205,133,63],'pink':[255,192,203],'plum':[221,160,221],'powderblue':[176,224,230],'purple':[128,0,128],'rebeccapurple':[102,51,153],'red':[255,0,0],'rosybrown':[188,143,143],'royalblue':[65,105,225],'saddlebrown':[139,69,19],'salmon':[250,128,114],'sandybrown':[244,164,96],'seagreen':[46,139,87],'seashell':[255,245,238],'sienna':[160,82,45],'silver':[192,192,192],'skyblue':[135,206,235],'slateblue':[106,90,205],'slategray':[112,128,144],'slategrey':[112,128,144],'snow':[255,250,250],'springgreen':[0,255,127],'steelblue':[70,130,180],'tan':[210,180,140],'teal':[0,128,128],'thistle':[216,191,216],'tomato':[255,99,71],'turquoise':[64,224,208],'violet':[238,130,238],'wheat':[245,222,179],'white':[255,255,255],'whitesmoke':[245,245,245],'yellow':[255,255,0],'yellowgreen':[154,205,50],'transparent':[0,0,0,0],};const PageHighlight={Content:Color.fromRGBA([111,168,220,.66]),ContentLight:Color.fromRGBA([111,168,220,.5]),ContentOutline:Color.fromRGBA([9,83,148]),Padding:Color.fromRGBA([147,196,125,.55]),PaddingLight:Color.fromRGBA([147,196,125,.4]),Border:Color.fromRGBA([255,229,153,.66]),BorderLight:Color.fromRGBA([255,229,153,.5]),Margin:Color.fromRGBA([246,178,107,.66]),MarginLight:Color.fromRGBA([246,178,107,.5]),EventTarget:Color.fromRGBA([255,196,196,.66]),Shape:Color.fromRGBA([96,82,177,0.8]),ShapeMargin:Color.fromRGBA([96,82,127,.6]),CssGrid:Color.fromRGBA([0x4b,0,0x82,1])};class Generator{constructor(hueSpace,satSpace,lightnessSpace,alphaSpace){this._hueSpace=hueSpace||{min:0,max:360};this._satSpace=satSpace||67;this._lightnessSpace=lightnessSpace||80;this._alphaSpace=alphaSpace||1;this._colors=new Map();}
  450. setColorForID(id,color){this._colors.set(id,color);}
  451. colorForID(id){let color=this._colors.get(id);if(!color){color=this._generateColorForID(id);this._colors.set(id,color);}
  452. return color;}
  453. _generateColorForID(id){const hash=String.hashCode(id);const h=this._indexToValueInSpace(hash,this._hueSpace);const s=this._indexToValueInSpace(hash>>8,this._satSpace);const l=this._indexToValueInSpace(hash>>16,this._lightnessSpace);const a=this._indexToValueInSpace(hash>>24,this._alphaSpace);return`hsla(${h}, ${s}%, ${l}%, ${a})`;}
  454. _indexToValueInSpace(index,space){if(typeof space==='number'){return space;}
  455. const count=space.count||space.max-space.min;index%=count;return space.min+Math.floor(index/(count-1)*(space.max-space.min));}}
  456. Color.hsva2rgba._tmpHSLA=[0,0,0,0];Color.calculateContrastRatio._blendedFg=[0,0,0,0];self.Common=self.Common||{};Common=Common||{};Common.Color=Color;Common.Color.Regex=Regex;Common.Color.Format=Format;Common.Color.Nicknames=Nicknames;Common.Color.PageHighlight=PageHighlight;Common.Color.Generator=Generator;function removeEventListeners(eventList){for(const eventInfo of eventList){eventInfo.eventTarget.removeEventListener(eventInfo.eventType,eventInfo.listener,eventInfo.thisObject);}
  457. eventList.splice(0);}
  458. class EventTarget{addEventListener(eventType,listener,thisObject){}
  459. once(eventType){}
  460. removeEventListener(eventType,listener,thisObject){}
  461. hasEventListeners(eventType){}
  462. dispatchEventToListeners(eventType,eventData){}}
  463. self.Common=self.Common||{};Common=Common||{};Common.EventTarget=EventTarget;EventTarget.removeEventListeners=removeEventListeners;Common.EventTarget.EventDescriptor;Common.Event;class ObjectWrapper{constructor(){this._listeners;}
  464. addEventListener(eventType,listener,thisObject){if(!listener){console.assert(false);}
  465. if(!this._listeners){this._listeners=new Map();}
  466. if(!this._listeners.has(eventType)){this._listeners.set(eventType,[]);}
  467. this._listeners.get(eventType).push({thisObject:thisObject,listener:listener});return{eventTarget:this,eventType:eventType,thisObject:thisObject,listener:listener};}
  468. once(eventType){return new Promise(resolve=>{const descriptor=this.addEventListener(eventType,event=>{this.removeEventListener(eventType,descriptor.listener);resolve(event.data);});});}
  469. removeEventListener(eventType,listener,thisObject){console.assert(listener);if(!this._listeners||!this._listeners.has(eventType)){return;}
  470. const listeners=this._listeners.get(eventType);for(let i=0;i<listeners.length;++i){if(listeners[i].listener===listener&&listeners[i].thisObject===thisObject){listeners[i].disposed=true;listeners.splice(i--,1);}}
  471. if(!listeners.length){this._listeners.delete(eventType);}}
  472. hasEventListeners(eventType){return!!(this._listeners&&this._listeners.has(eventType));}
  473. dispatchEventToListeners(eventType,eventData){if(!this._listeners||!this._listeners.has(eventType)){return;}
  474. const event=({data:eventData});const listeners=this._listeners.get(eventType).slice(0);for(let i=0;i<listeners.length;++i){if(!listeners[i].disposed){listeners[i].listener.call(listeners[i].thisObject,event);}}}}
  475. self.Common=self.Common||{};Common=Common||{};Common.Object=ObjectWrapper;Common.Object._listenerCallbackTuple;class Console extends ObjectWrapper{constructor(){super();this._messages=[];}
  476. addMessage(text,level,show){const message=new Message(text,level||MessageLevel.Info,Date.now(),show||false);this._messages.push(message);this.dispatchEventToListeners(Events.MessageAdded,message);}
  477. log(text){this.addMessage(text,MessageLevel.Info);}
  478. warn(text){this.addMessage(text,MessageLevel.Warning);}
  479. error(text){this.addMessage(text,MessageLevel.Error,true);}
  480. messages(){return this._messages;}
  481. show(){this.showPromise();}
  482. showPromise(){return Common.Revealer.reveal(this);}}
  483. const Events={MessageAdded:Symbol('messageAdded')};const MessageLevel={Info:'info',Warning:'warning',Error:'error'};class Message{constructor(text,level,timestamp,show){this.text=text;this.level=level;this.timestamp=(typeof timestamp==='number')?timestamp:Date.now();this.show=show;}}
  484. self.Common=self.Common||{};Common=Common||{};Common.console=new Console();Common.Console=Console;Common.Console.Events=Events;Common.Console.MessageLevel=MessageLevel;Common.Console.Message=Message;class ParsedURL{constructor(url){this.isValid=false;this.url=url;this.scheme='';this.user='';this.host='';this.port='';this.path='';this.queryParams='';this.fragment='';this.folderPathComponents='';this.lastPathComponent='';const isBlobUrl=this.url.startsWith('blob:');const urlToMatch=isBlobUrl?url.substring(5):url;const match=urlToMatch.match(ParsedURL._urlRegex());if(match){this.isValid=true;if(isBlobUrl){this._blobInnerScheme=match[2].toLowerCase();this.scheme='blob';}else{this.scheme=match[2].toLowerCase();}
  485. this.user=match[3];this.host=match[4];this.port=match[5];this.path=match[6]||'/';this.queryParams=match[7]||'';this.fragment=match[8];}else{if(this.url.startsWith('data:')){this.scheme='data';return;}
  486. if(this.url.startsWith('blob:')){this.scheme='blob';return;}
  487. if(this.url==='about:blank'){this.scheme='about';return;}
  488. this.path=this.url;}
  489. const lastSlashIndex=this.path.lastIndexOf('/');if(lastSlashIndex!==-1){this.folderPathComponents=this.path.substring(0,lastSlashIndex);this.lastPathComponent=this.path.substring(lastSlashIndex+1);}else{this.lastPathComponent=this.path;}}
  490. static platformPathToURL(fileSystemPath){fileSystemPath=fileSystemPath.replace(/\\/g,'/');if(!fileSystemPath.startsWith('file://')){if(fileSystemPath.startsWith('/')){fileSystemPath='file://'+fileSystemPath;}else{fileSystemPath='file:///'+fileSystemPath;}}
  491. return fileSystemPath;}
  492. static urlToPlatformPath(fileURL,isWindows){console.assert(fileURL.startsWith('file://'),'This must be a file URL.');if(isWindows){return fileURL.substr('file:///'.length).replace(/\//g,'\\');}
  493. return fileURL.substr('file://'.length);}
  494. static urlWithoutHash(url){const hashIndex=url.indexOf('#');if(hashIndex!==-1){return url.substr(0,hashIndex);}
  495. return url;}
  496. static _urlRegex(){if(ParsedURL._urlRegexInstance){return ParsedURL._urlRegexInstance;}
  497. const schemeRegex=/([A-Za-z][A-Za-z0-9+.-]*):\/\//;const userRegex=/(?:([A-Za-z0-9\-._~%!$&'()*+,;=:]*)@)?/;const hostRegex=/((?:\[::\d?\])|(?:[^\s\/:]*))/;const portRegex=/(?::([\d]+))?/;const pathRegex=/(\/[^#?]*)?/;const queryRegex=/(?:\?([^#]*))?/;const fragmentRegex=/(?:#(.*))?/;ParsedURL._urlRegexInstance=new RegExp('^('+schemeRegex.source+userRegex.source+hostRegex.source+portRegex.source+')'+pathRegex.source+
  498. queryRegex.source+fragmentRegex.source+'$');return ParsedURL._urlRegexInstance;}
  499. static extractPath(url){const parsedURL=url.asParsedURL();return parsedURL?parsedURL.path:'';}
  500. static extractOrigin(url){const parsedURL=url.asParsedURL();return parsedURL?parsedURL.securityOrigin():'';}
  501. static extractExtension(url){url=ParsedURL.urlWithoutHash(url);const indexOfQuestionMark=url.indexOf('?');if(indexOfQuestionMark!==-1){url=url.substr(0,indexOfQuestionMark);}
  502. const lastIndexOfSlash=url.lastIndexOf('/');if(lastIndexOfSlash!==-1){url=url.substr(lastIndexOfSlash+1);}
  503. const lastIndexOfDot=url.lastIndexOf('.');if(lastIndexOfDot!==-1){url=url.substr(lastIndexOfDot+1);const lastIndexOfPercent=url.indexOf('%');if(lastIndexOfPercent!==-1){return url.substr(0,lastIndexOfPercent);}
  504. return url;}
  505. return'';}
  506. static extractName(url){let index=url.lastIndexOf('/');const pathAndQuery=index!==-1?url.substr(index+1):url;index=pathAndQuery.indexOf('?');return index<0?pathAndQuery:pathAndQuery.substr(0,index);}
  507. static completeURL(baseURL,href){const trimmedHref=href.trim();if(trimmedHref.startsWith('data:')||trimmedHref.startsWith('blob:')||trimmedHref.startsWith('javascript:')||trimmedHref.startsWith('mailto:')){return href;}
  508. const parsedHref=trimmedHref.asParsedURL();if(parsedHref&&parsedHref.scheme){return trimmedHref;}
  509. const parsedURL=baseURL.asParsedURL();if(!parsedURL){return null;}
  510. if(parsedURL.isDataURL()){return href;}
  511. if(href.length>1&&href.charAt(0)==='/'&&href.charAt(1)==='/'){return parsedURL.scheme+':'+href;}
  512. const securityOrigin=parsedURL.securityOrigin();const pathText=parsedURL.path;const queryText=parsedURL.queryParams?'?'+parsedURL.queryParams:'';if(!href.length){return securityOrigin+pathText+queryText;}
  513. if(href.charAt(0)==='#'){return securityOrigin+pathText+queryText+href;}
  514. if(href.charAt(0)==='?'){return securityOrigin+pathText+href;}
  515. let hrefPath=href.match(/^[^#?]*/)[0];const hrefSuffix=href.substring(hrefPath.length);if(hrefPath.charAt(0)!=='/'){hrefPath=parsedURL.folderPathComponents+'/'+hrefPath;}
  516. return securityOrigin+Root.Runtime.normalizePath(hrefPath)+hrefSuffix;}
  517. static splitLineAndColumn(string){const beforePathMatch=string.match(ParsedURL._urlRegex());let beforePath='';let pathAndAfter=string;if(beforePathMatch){beforePath=beforePathMatch[1];pathAndAfter=string.substring(beforePathMatch[1].length);}
  518. const lineColumnRegEx=/(?::(\d+))?(?::(\d+))?$/;const lineColumnMatch=lineColumnRegEx.exec(pathAndAfter);let lineNumber;let columnNumber;console.assert(lineColumnMatch);if(typeof(lineColumnMatch[1])==='string'){lineNumber=parseInt(lineColumnMatch[1],10);lineNumber=isNaN(lineNumber)?undefined:lineNumber-1;}
  519. if(typeof(lineColumnMatch[2])==='string'){columnNumber=parseInt(lineColumnMatch[2],10);columnNumber=isNaN(columnNumber)?undefined:columnNumber-1;}
  520. return{url:beforePath+pathAndAfter.substring(0,pathAndAfter.length-lineColumnMatch[0].length),lineNumber:lineNumber,columnNumber:columnNumber};}
  521. static isRelativeURL(url){return!(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url));}
  522. get displayName(){if(this._displayName){return this._displayName;}
  523. if(this.isDataURL()){return this.dataURLDisplayName();}
  524. if(this.isBlobURL()){return this.url;}
  525. if(this.isAboutBlank()){return this.url;}
  526. this._displayName=this.lastPathComponent;if(!this._displayName){this._displayName=(this.host||'')+'/';}
  527. if(this._displayName==='/'){this._displayName=this.url;}
  528. return this._displayName;}
  529. dataURLDisplayName(){if(this._dataURLDisplayName){return this._dataURLDisplayName;}
  530. if(!this.isDataURL()){return'';}
  531. this._dataURLDisplayName=this.url.trimEndWithMaxLength(20);return this._dataURLDisplayName;}
  532. isAboutBlank(){return this.url==='about:blank';}
  533. isDataURL(){return this.scheme==='data';}
  534. isBlobURL(){return this.url.startsWith('blob:');}
  535. lastPathComponentWithFragment(){return this.lastPathComponent+(this.fragment?'#'+this.fragment:'');}
  536. domain(){if(this.isDataURL()){return'data:';}
  537. return this.host+(this.port?':'+this.port:'');}
  538. securityOrigin(){if(this.isDataURL()){return'data:';}
  539. const scheme=this.isBlobURL()?this._blobInnerScheme:this.scheme;return scheme+'://'+this.domain();}
  540. urlWithoutScheme(){if(this.scheme&&this.url.startsWith(this.scheme+'://')){return this.url.substring(this.scheme.length+3);}
  541. return this.url;}}
  542. String.prototype.asParsedURL=function(){const parsedURL=new ParsedURL(this.toString());if(parsedURL.isValid){return parsedURL;}
  543. return null;};self.Common=self.Common||{};Common=Common||{};Common.ParsedURL=ParsedURL;function UIString(string,vararg){return String.vsprintf(Common.localize(string),Array.prototype.slice.call(arguments,1));}
  544. function serializeUIString(string,values=[]){const messageParts=[string];const serializedMessage={messageParts,values};return JSON.stringify(serializedMessage);}
  545. function deserializeUIString(serializedMessage){if(!serializedMessage){return{};}
  546. return JSON.parse(serializedMessage);}
  547. function localize(string){return string;}
  548. class UIStringFormat{constructor(format){this._localizedFormat=localize(format);this._tokenizedFormat=String.tokenizeFormatString(this._localizedFormat,String.standardFormatters);}
  549. static _append(a,b){return a+b;}
  550. format(vararg){return String.format(this._localizedFormat,arguments,String.standardFormatters,'',UIStringFormat._append,this._tokenizedFormat).formattedResult;}}
  551. const _substitutionStrings=new WeakMap();function ls$1(strings,vararg){if(typeof strings==='string'){return strings;}
  552. let substitutionString=_substitutionStrings.get(strings);if(!substitutionString){substitutionString=strings.join('%s');_substitutionStrings.set(strings,substitutionString);}
  553. return UIString(substitutionString,...Array.prototype.slice.call(arguments,1));}
  554. self.ls=ls$1;self.Common=self.Common||{};Common=Common||{};Common.UIStringFormat=UIStringFormat;Common.UIString=UIString;Common.serializeUIString=serializeUIString;Common.deserializeUIString=deserializeUIString;Common.localize=localize;class ResourceType{constructor(name,title,category,isTextType){this._name=name;this._title=title;this._category=category;this._isTextType=isTextType;}
  555. static fromMimeType(mimeType){if(!mimeType){return resourceTypes.Other;}
  556. if(mimeType.startsWith('text/html')){return resourceTypes.Document;}
  557. if(mimeType.startsWith('text/css')){return resourceTypes.Stylesheet;}
  558. if(mimeType.startsWith('image/')){return resourceTypes.Image;}
  559. if(mimeType.startsWith('text/')){return resourceTypes.Script;}
  560. if(mimeType.includes('font')){return resourceTypes.Font;}
  561. if(mimeType.includes('script')){return resourceTypes.Script;}
  562. if(mimeType.includes('octet')){return resourceTypes.Other;}
  563. if(mimeType.includes('application')){return resourceTypes.Script;}
  564. return resourceTypes.Other;}
  565. static fromURL(url){return ResourceType._resourceTypeByExtension.get(ParsedURL.extractExtension(url))||null;}
  566. static fromName(name){for(const resourceTypeId in resourceTypes){const resourceType=resourceTypes[resourceTypeId];if(resourceType.name()===name){return resourceType;}}
  567. return null;}
  568. static mimeFromURL(url){const name=ParsedURL.extractName(url);if(ResourceType._mimeTypeByName.has(name)){return ResourceType._mimeTypeByName.get(name);}
  569. const ext=ParsedURL.extractExtension(url).toLowerCase();return ResourceType._mimeTypeByExtension.get(ext);}
  570. static mimeFromExtension(ext){return ResourceType._mimeTypeByExtension.get(ext);}
  571. name(){return this._name;}
  572. title(){return this._title;}
  573. category(){return this._category;}
  574. isTextType(){return this._isTextType;}
  575. isScript(){return this._name==='script'||this._name==='sm-script';}
  576. hasScripts(){return this.isScript()||this.isDocument();}
  577. isStyleSheet(){return this._name==='stylesheet'||this._name==='sm-stylesheet';}
  578. isDocument(){return this._name==='document';}
  579. isDocumentOrScriptOrStyleSheet(){return this.isDocument()||this.isScript()||this.isStyleSheet();}
  580. isFromSourceMap(){return this._name.startsWith('sm-');}
  581. toString(){return this._name;}
  582. canonicalMimeType(){if(this.isDocument()){return'text/html';}
  583. if(this.isScript()){return'text/javascript';}
  584. if(this.isStyleSheet()){return'text/css';}
  585. return'';}}
  586. class ResourceCategory{constructor(title,shortTitle){this.title=title;this.shortTitle=shortTitle;}}
  587. const resourceCategories={XHR:new ResourceCategory(ls$1`XHR and Fetch`,ls$1`XHR`),Script:new ResourceCategory(ls$1`Scripts`,ls$1`JS`),Stylesheet:new ResourceCategory(ls$1`Stylesheets`,ls$1`CSS`),Image:new ResourceCategory(ls$1`Images`,ls$1`Img`),Media:new ResourceCategory(ls$1`Media`,ls$1`Media`),Font:new ResourceCategory(ls$1`Fonts`,ls$1`Font`),Document:new ResourceCategory(ls$1`Documents`,ls$1`Doc`),WebSocket:new ResourceCategory(ls$1`WebSockets`,ls$1`WS`),Manifest:new ResourceCategory(ls$1`Manifest`,ls$1`Manifest`),Other:new ResourceCategory(ls$1`Other`,ls$1`Other`)};const resourceTypes={XHR:new ResourceType('xhr',ls$1`XHR`,resourceCategories.XHR,true),Fetch:new ResourceType('fetch',ls$1`Fetch`,resourceCategories.XHR,true),EventSource:new ResourceType('eventsource',ls$1`EventSource`,resourceCategories.XHR,true),Script:new ResourceType('script',ls$1`Script`,resourceCategories.Script,true),Stylesheet:new ResourceType('stylesheet',ls$1`Stylesheet`,resourceCategories.Stylesheet,true),Image:new ResourceType('image',ls$1`Image`,resourceCategories.Image,false),Media:new ResourceType('media',ls$1`Media`,resourceCategories.Media,false),Font:new ResourceType('font',ls$1`Font`,resourceCategories.Font,false),Document:new ResourceType('document',ls$1`Document`,resourceCategories.Document,true),TextTrack:new ResourceType('texttrack',ls$1`TextTrack`,resourceCategories.Other,true),WebSocket:new ResourceType('websocket',ls$1`WebSocket`,resourceCategories.WebSocket,false),Other:new ResourceType('other',ls$1`Other`,resourceCategories.Other,false),SourceMapScript:new ResourceType('sm-script',ls$1`Script`,resourceCategories.Script,true),SourceMapStyleSheet:new ResourceType('sm-stylesheet',ls$1`Stylesheet`,resourceCategories.Stylesheet,true),Manifest:new ResourceType('manifest',ls$1`Manifest`,resourceCategories.Manifest,true),SignedExchange:new ResourceType('signed-exchange',ls$1`SignedExchange`,resourceCategories.Other,false)};const _mimeTypeByName=new Map([['Cakefile','text/x-coffeescript']]);const _resourceTypeByExtension=new Map([['js',resourceTypes.Script],['mjs',resourceTypes.Script],['css',resourceTypes.Stylesheet],['xsl',resourceTypes.Stylesheet],['jpeg',resourceTypes.Image],['jpg',resourceTypes.Image],['svg',resourceTypes.Image],['gif',resourceTypes.Image],['png',resourceTypes.Image],['ico',resourceTypes.Image],['tiff',resourceTypes.Image],['tif',resourceTypes.Image],['bmp',resourceTypes.Image],['webp',resourceTypes.Media],['ttf',resourceTypes.Font],['otf',resourceTypes.Font],['ttc',resourceTypes.Font],['woff',resourceTypes.Font]]);const _mimeTypeByExtension=new Map([['js','text/javascript'],['mjs','text/javascript'],['css','text/css'],['html','text/html'],['htm','text/html'],['xml','application/xml'],['xsl','application/xml'],['asp','application/x-aspx'],['aspx','application/x-aspx'],['jsp','application/x-jsp'],['c','text/x-c++src'],['cc','text/x-c++src'],['cpp','text/x-c++src'],['h','text/x-c++src'],['m','text/x-c++src'],['mm','text/x-c++src'],['coffee','text/x-coffeescript'],['dart','text/javascript'],['ts','text/typescript'],['tsx','text/typescript-jsx'],['json','application/json'],['gyp','application/json'],['gypi','application/json'],['cs','text/x-csharp'],['java','text/x-java'],['less','text/x-less'],['php','text/x-php'],['phtml','application/x-httpd-php'],['py','text/x-python'],['sh','text/x-sh'],['scss','text/x-scss'],['vtt','text/vtt'],['ls','text/x-livescript'],['md','text/markdown'],['cljs','text/x-clojure'],['cljc','text/x-clojure'],['cljx','text/x-clojure'],['styl','text/x-styl'],['jsx','text/jsx'],['jpeg','image/jpeg'],['jpg','image/jpeg'],['svg','image/svg+xml'],['gif','image/gif'],['webp','image/webp'],['png','image/png'],['ico','image/ico'],['tiff','image/tiff'],['tif','image/tif'],['bmp','image/bmp'],['ttf','font/opentype'],['otf','font/opentype'],['ttc','font/opentype'],['woff','application/font-woff']]);self.Common=self.Common||{};Common=Common||{};Common.resourceTypes=resourceTypes;Common.resourceCategories=resourceCategories;Common.ResourceCategory=ResourceCategory;Common.ResourceType=ResourceType;Common.ResourceType._mimeTypeByName=_mimeTypeByName;Common.ResourceType._resourceTypeByExtension=_resourceTypeByExtension;Common.ResourceType._mimeTypeByExtension=_mimeTypeByExtension;class ContentProvider{contentURL(){}
  588. contentType(){}
  589. contentEncoded(){}
  590. requestContent(){}
  591. searchInContent(query,caseSensitive,isRegex){}}
  592. class SearchMatch{constructor(lineNumber,lineContent){this.lineNumber=lineNumber;this.lineContent=lineContent;}}
  593. const performSearchInContent=function(content,query,caseSensitive,isRegex){const regex=createSearchRegex(query,caseSensitive,isRegex);const text=new TextUtils.Text(content);const result=[];for(let i=0;i<text.lineCount();++i){const lineContent=text.lineAt(i);regex.lastIndex=0;if(regex.exec(lineContent)){result.push(new SearchMatch(i,lineContent));}}
  594. return result;};const contentAsDataURL=function(content,mimeType,contentEncoded,charset){const maxDataUrlSize=1024*1024;if(content===null||content.length>maxDataUrlSize){return null;}
  595. return'data:'+mimeType+(charset?';charset='+charset:'')+(contentEncoded?';base64':'')+','+
  596. content;};self.Common=self.Common||{};Common=Common||{};Common.ContentProvider=ContentProvider;Common.ContentProvider.SearchMatch=SearchMatch;Common.ContentProvider.performSearchInContent=performSearchInContent;Common.ContentProvider.contentAsDataURL=contentAsDataURL;Common.DeferredContent;class JavaScriptMetaData{signaturesForNativeFunction(name){}
  597. signaturesForInstanceMethod(name,receiverClassName){}
  598. signaturesForStaticMethod(name,receiverConstructorName){}}
  599. self.Common=self.Common||{};Common=Common||{};Common.JavaScriptMetadata=JavaScriptMetaData;class Linkifier{linkify(object,options){}
  600. static linkify(object,options){if(!object){return Promise.reject(new Error('Can\'t linkify '+object));}
  601. return self.runtime.extension(Linkifier,object).instance().then(linkifier=>linkifier.linkify(object,options));}}
  602. self.Common=self.Common||{};Common=Common||{};Common.Linkifier=Linkifier;Common.Linkifier.Options;class Progress{setTotalWork(totalWork){}
  603. setTitle(title){}
  604. setWorked(worked,title){}
  605. worked(worked){}
  606. done(){}
  607. isCanceled(){return false;}}
  608. class CompositeProgress{constructor(parent){this._parent=parent;this._children=[];this._childrenDone=0;this._parent.setTotalWork(1);this._parent.setWorked(0);}
  609. _childDone(){if(++this._childrenDone!==this._children.length){return;}
  610. this._parent.done();}
  611. createSubProgress(weight){const child=new SubProgress(this,weight);this._children.push(child);return child;}
  612. _update(){let totalWeights=0;let done=0;for(let i=0;i<this._children.length;++i){const child=this._children[i];if(child._totalWork){done+=child._weight*child._worked/child._totalWork;}
  613. totalWeights+=child._weight;}
  614. this._parent.setWorked(done/totalWeights);}}
  615. class SubProgress{constructor(composite,weight){this._composite=composite;this._weight=weight||1;this._worked=0;}
  616. isCanceled(){return this._composite._parent.isCanceled();}
  617. setTitle(title){this._composite._parent.setTitle(title);}
  618. done(){this.setWorked(this._totalWork);this._composite._childDone();}
  619. setTotalWork(totalWork){this._totalWork=totalWork;this._composite._update();}
  620. setWorked(worked,title){this._worked=worked;if(typeof title!=='undefined'){this.setTitle(title);}
  621. this._composite._update();}
  622. worked(worked){this.setWorked(this._worked+(worked||1));}}
  623. class ProgressProxy{constructor(delegate,doneCallback){this._delegate=delegate;this._doneCallback=doneCallback;}
  624. isCanceled(){return this._delegate?this._delegate.isCanceled():false;}
  625. setTitle(title){if(this._delegate){this._delegate.setTitle(title);}}
  626. done(){if(this._delegate){this._delegate.done();}
  627. if(this._doneCallback){this._doneCallback();}}
  628. setTotalWork(totalWork){if(this._delegate){this._delegate.setTotalWork(totalWork);}}
  629. setWorked(worked,title){if(this._delegate){this._delegate.setWorked(worked,title);}}
  630. worked(worked){if(this._delegate){this._delegate.worked(worked);}}}
  631. self.Common=self.Common||{};Common=Common||{};Common.Progress=Progress;Common.CompositeProgress=CompositeProgress;Common.SubProgress=SubProgress;Common.ProgressProxy=ProgressProxy;class QueryParamHandler{handleQueryParam(value){}}
  632. self.Common=self.Common||{};Common=Common||{};Common.QueryParamHandler=QueryParamHandler;class Revealer{reveal(object,omitFocus){}}
  633. const reveal=function(revealable,omitFocus){if(!revealable){return Promise.reject(new Error('Can\'t reveal '+revealable));}
  634. return self.runtime.allInstances(Revealer,revealable).then(reveal);function reveal(revealers){const promises=[];for(let i=0;i<revealers.length;++i){promises.push(revealers[i].reveal((revealable),omitFocus));}
  635. return Promise.race(promises);}};const revealDestination=function(revealable){const extension=self.runtime.extension(Revealer,revealable);if(!extension){return null;}
  636. return extension.descriptor()['destination'];};self.Common=self.Common||{};Common=Common||{};Common.Revealer=Revealer;Common.Revealer.reveal=reveal;Common.Revealer.revealDestination=revealDestination;class Runnable{run(){}}
  637. self.Common=self.Common||{};Common=Common||{};Common.Runnable=Runnable;class Segment{constructor(begin,end,data){if(begin>end){throw new Error('Invalid segment');}
  638. this.begin=begin;this.end=end;this.data=data;}
  639. intersects(that){return this.begin<that.end&&that.begin<this.end;}}
  640. class SegmentedRange{constructor(mergeCallback){this._segments=[];this._mergeCallback=mergeCallback;}
  641. append(newSegment){let startIndex=this._segments.lowerBound(newSegment,(a,b)=>a.begin-b.begin);let endIndex=startIndex;let merged=null;if(startIndex>0){const precedingSegment=this._segments[startIndex-1];merged=this._tryMerge(precedingSegment,newSegment);if(merged){--startIndex;newSegment=merged;}else if(this._segments[startIndex-1].end>=newSegment.begin){if(newSegment.end<precedingSegment.end){this._segments.splice(startIndex,0,new Segment(newSegment.end,precedingSegment.end,precedingSegment.data));}
  642. precedingSegment.end=newSegment.begin;}}
  643. while(endIndex<this._segments.length&&this._segments[endIndex].end<=newSegment.end){++endIndex;}
  644. if(endIndex<this._segments.length){merged=this._tryMerge(newSegment,this._segments[endIndex]);if(merged){endIndex++;newSegment=merged;}else if(newSegment.intersects(this._segments[endIndex])){this._segments[endIndex].begin=newSegment.end;}}
  645. this._segments.splice(startIndex,endIndex-startIndex,newSegment);}
  646. appendRange(that){that.segments().forEach(segment=>this.append(segment));}
  647. segments(){return this._segments;}
  648. _tryMerge(first,second){const merged=this._mergeCallback&&this._mergeCallback(first,second);if(!merged){return null;}
  649. merged.begin=first.begin;merged.end=Math.max(first.end,second.end);return merged;}}
  650. self.Common=self.Common||{};Common=Common||{};Common.Segment=Segment;Common.SegmentedRange=SegmentedRange;class Settings{constructor(globalStorage,localStorage){this._globalStorage=globalStorage;this._localStorage=localStorage;this._sessionStorage=new SettingsStorage({});this._eventSupport=new ObjectWrapper();this._registry=new Map();this._moduleSettings=new Map();self.runtime.extensions('setting').forEach(this._registerModuleSetting.bind(this));}
  651. _registerModuleSetting(extension){const descriptor=extension.descriptor();const settingName=descriptor['settingName'];const isRegex=descriptor['settingType']==='regex';const defaultValue=descriptor['defaultValue'];let storageType;switch(descriptor['storageType']){case('local'):storageType=SettingStorageType.Local;break;case('session'):storageType=SettingStorageType.Session;break;case('global'):storageType=SettingStorageType.Global;break;default:storageType=SettingStorageType.Global;}
  652. const setting=isRegex?this.createRegExpSetting(settingName,defaultValue,undefined,storageType):this.createSetting(settingName,defaultValue,storageType);if(extension.title()){setting.setTitle(extension.title());}
  653. if(descriptor['userActionCondition']){setting.setRequiresUserAction(!!Root.Runtime.queryParam(descriptor['userActionCondition']));}
  654. setting._extension=extension;this._moduleSettings.set(settingName,setting);}
  655. moduleSetting(settingName){const setting=this._moduleSettings.get(settingName);if(!setting){throw new Error('No setting registered: '+settingName);}
  656. return setting;}
  657. settingForTest(settingName){const setting=this._registry.get(settingName);if(!setting){throw new Error('No setting registered: '+settingName);}
  658. return setting;}
  659. createSetting(key,defaultValue,storageType){const storage=this._storageFromType(storageType);if(!this._registry.get(key)){this._registry.set(key,new Setting(this,key,defaultValue,this._eventSupport,storage));}
  660. return(this._registry.get(key));}
  661. createLocalSetting(key,defaultValue){return this.createSetting(key,defaultValue,SettingStorageType.Local);}
  662. createRegExpSetting(key,defaultValue,regexFlags,storageType){if(!this._registry.get(key)){this._registry.set(key,new RegExpSetting(this,key,defaultValue,this._eventSupport,this._storageFromType(storageType),regexFlags));}
  663. return(this._registry.get(key));}
  664. clearAll(){this._globalStorage.removeAll();this._localStorage.removeAll();const versionSetting=Common.settings.createSetting(VersionController._currentVersionName,0);versionSetting.set(VersionController.currentVersion);}
  665. _storageFromType(storageType){switch(storageType){case(SettingStorageType.Local):return this._localStorage;case(SettingStorageType.Session):return this._sessionStorage;case(SettingStorageType.Global):return this._globalStorage;}
  666. return this._globalStorage;}}
  667. class SettingsStorage{constructor(object,setCallback,removeCallback,removeAllCallback,storagePrefix){this._object=object;this._setCallback=setCallback||function(){};this._removeCallback=removeCallback||function(){};this._removeAllCallback=removeAllCallback||function(){};this._storagePrefix=storagePrefix||'';}
  668. set(name,value){name=this._storagePrefix+name;this._object[name]=value;this._setCallback(name,value);}
  669. has(name){name=this._storagePrefix+name;return name in this._object;}
  670. get(name){name=this._storagePrefix+name;return this._object[name];}
  671. remove(name){name=this._storagePrefix+name;delete this._object[name];this._removeCallback(name);}
  672. removeAll(){this._object={};this._removeAllCallback();}
  673. _dumpSizes(){Common.console.log('Ten largest settings: ');const sizes={__proto__:null};for(const key in this._object){sizes[key]=this._object[key].length;}
  674. const keys=Object.keys(sizes);function comparator(key1,key2){return sizes[key2]-sizes[key1];}
  675. keys.sort(comparator);for(let i=0;i<10&&i<keys.length;++i){Common.console.log('Setting: \''+keys[i]+'\', size: '+sizes[keys[i]]);}}}
  676. class Setting{constructor(settings,name,defaultValue,eventSupport,storage){this._settings=settings;this._name=name;this._defaultValue=defaultValue;this._eventSupport=eventSupport;this._storage=storage;this._title='';this._extension=null;}
  677. addChangeListener(listener,thisObject){return this._eventSupport.addEventListener(this._name,listener,thisObject);}
  678. removeChangeListener(listener,thisObject){this._eventSupport.removeEventListener(this._name,listener,thisObject);}
  679. get name(){return this._name;}
  680. title(){return this._title;}
  681. setTitle(title){this._title=title;}
  682. setRequiresUserAction(requiresUserAction){this._requiresUserAction=requiresUserAction;}
  683. get(){if(this._requiresUserAction&&!this._hadUserAction){return this._defaultValue;}
  684. if(typeof this._value!=='undefined'){return this._value;}
  685. this._value=this._defaultValue;if(this._storage.has(this._name)){try{this._value=JSON.parse(this._storage.get(this._name));}catch(e){this._storage.remove(this._name);}}
  686. return this._value;}
  687. set(value){this._hadUserAction=true;this._value=value;try{const settingString=JSON.stringify(value);try{this._storage.set(this._name,settingString);}catch(e){this._printSettingsSavingError(e.message,this._name,settingString);}}catch(e){Common.console.error('Cannot stringify setting with name: '+this._name+', error: '+e.message);}
  688. this._eventSupport.dispatchEventToListeners(this._name,value);}
  689. remove(){this._settings._registry.delete(this._name);this._settings._moduleSettings.delete(this._name);this._storage.remove(this._name);}
  690. extension(){return this._extension;}
  691. _printSettingsSavingError(message,name,value){const errorMessage='Error saving setting with name: '+this._name+', value length: '+value.length+'. Error: '+message;console.error(errorMessage);Common.console.error(errorMessage);this._storage._dumpSizes();}}
  692. class RegExpSetting extends Setting{constructor(settings,name,defaultValue,eventSupport,storage,regexFlags){super(settings,name,defaultValue?[{pattern:defaultValue}]:[],eventSupport,storage);this._regexFlags=regexFlags;}
  693. get(){const result=[];const items=this.getAsArray();for(let i=0;i<items.length;++i){const item=items[i];if(item.pattern&&!item.disabled){result.push(item.pattern);}}
  694. return result.join('|');}
  695. getAsArray(){return super.get();}
  696. set(value){this.setAsArray([{pattern:value}]);}
  697. setAsArray(value){delete this._regex;super.set(value);}
  698. asRegExp(){if(typeof this._regex!=='undefined'){return this._regex;}
  699. this._regex=null;try{const pattern=this.get();if(pattern){this._regex=new RegExp(pattern,this._regexFlags||'');}}catch(e){}
  700. return this._regex;}}
  701. class VersionController{static get _currentVersionName(){return'inspectorVersion';}
  702. static get currentVersion(){return 28;}
  703. updateVersion(){const localStorageVersion=window.localStorage?window.localStorage[VersionController._currentVersionName]:0;const versionSetting=Common.settings.createSetting(VersionController._currentVersionName,0);const currentVersion=VersionController.currentVersion;const oldVersion=versionSetting.get()||parseInt(localStorageVersion||'0',10);if(oldVersion===0){versionSetting.set(currentVersion);return;}
  704. const methodsToRun=this._methodsToRunToUpdateVersion(oldVersion,currentVersion);for(let i=0;i<methodsToRun.length;++i){this[methodsToRun[i]].call(this);}
  705. versionSetting.set(currentVersion);}
  706. _methodsToRunToUpdateVersion(oldVersion,currentVersion){const result=[];for(let i=oldVersion;i<currentVersion;++i){result.push('_updateVersionFrom'+i+'To'+(i+1));}
  707. return result;}
  708. _updateVersionFrom0To1(){this._clearBreakpointsWhenTooMany(Common.settings.createLocalSetting('breakpoints',[]),500000);}
  709. _updateVersionFrom1To2(){Common.settings.createSetting('previouslyViewedFiles',[]).set([]);}
  710. _updateVersionFrom2To3(){Common.settings.createSetting('fileSystemMapping',{}).set({});Common.settings.createSetting('fileMappingEntries',[]).remove();}
  711. _updateVersionFrom3To4(){const advancedMode=Common.settings.createSetting('showHeaSnapshotObjectsHiddenProperties',false);Common.moduleSetting('showAdvancedHeapSnapshotProperties').set(advancedMode.get());advancedMode.remove();}
  712. _updateVersionFrom4To5(){const settingNames={'FileSystemViewSidebarWidth':'fileSystemViewSplitViewState','elementsSidebarWidth':'elementsPanelSplitViewState','StylesPaneSplitRatio':'stylesPaneSplitViewState','heapSnapshotRetainersViewSize':'heapSnapshotSplitViewState','InspectorView.splitView':'InspectorView.splitViewState','InspectorView.screencastSplitView':'InspectorView.screencastSplitViewState','Inspector.drawerSplitView':'Inspector.drawerSplitViewState','layerDetailsSplitView':'layerDetailsSplitViewState','networkSidebarWidth':'networkPanelSplitViewState','sourcesSidebarWidth':'sourcesPanelSplitViewState','scriptsPanelNavigatorSidebarWidth':'sourcesPanelNavigatorSplitViewState','sourcesPanelSplitSidebarRatio':'sourcesPanelDebuggerSidebarSplitViewState','timeline-details':'timelinePanelDetailsSplitViewState','timeline-split':'timelinePanelRecorsSplitViewState','timeline-view':'timelinePanelTimelineStackSplitViewState','auditsSidebarWidth':'auditsPanelSplitViewState','layersSidebarWidth':'layersPanelSplitViewState','profilesSidebarWidth':'profilesPanelSplitViewState','resourcesSidebarWidth':'resourcesPanelSplitViewState'};const empty={};for(const oldName in settingNames){const newName=settingNames[oldName];const oldNameH=oldName+'H';let newValue=null;const oldSetting=Common.settings.createSetting(oldName,empty);if(oldSetting.get()!==empty){newValue=newValue||{};newValue.vertical={};newValue.vertical.size=oldSetting.get();oldSetting.remove();}
  713. const oldSettingH=Common.settings.createSetting(oldNameH,empty);if(oldSettingH.get()!==empty){newValue=newValue||{};newValue.horizontal={};newValue.horizontal.size=oldSettingH.get();oldSettingH.remove();}
  714. if(newValue){Common.settings.createSetting(newName,{}).set(newValue);}}}
  715. _updateVersionFrom5To6(){const settingNames={'debuggerSidebarHidden':'sourcesPanelSplitViewState','navigatorHidden':'sourcesPanelNavigatorSplitViewState','WebInspector.Drawer.showOnLoad':'Inspector.drawerSplitViewState'};for(const oldName in settingNames){const oldSetting=Common.settings.createSetting(oldName,null);if(oldSetting.get()===null){oldSetting.remove();continue;}
  716. const newName=settingNames[oldName];const invert=oldName==='WebInspector.Drawer.showOnLoad';const hidden=oldSetting.get()!==invert;oldSetting.remove();const showMode=hidden?'OnlyMain':'Both';const newSetting=Common.settings.createSetting(newName,{});const newValue=newSetting.get()||{};newValue.vertical=newValue.vertical||{};newValue.vertical.showMode=showMode;newValue.horizontal=newValue.horizontal||{};newValue.horizontal.showMode=showMode;newSetting.set(newValue);}}
  717. _updateVersionFrom6To7(){const settingNames={'sourcesPanelNavigatorSplitViewState':'sourcesPanelNavigatorSplitViewState','elementsPanelSplitViewState':'elementsPanelSplitViewState','stylesPaneSplitViewState':'stylesPaneSplitViewState','sourcesPanelDebuggerSidebarSplitViewState':'sourcesPanelDebuggerSidebarSplitViewState'};const empty={};for(const name in settingNames){const setting=Common.settings.createSetting(name,empty);const value=setting.get();if(value===empty){continue;}
  718. if(value.vertical&&value.vertical.size&&value.vertical.size<1){value.vertical.size=0;}
  719. if(value.horizontal&&value.horizontal.size&&value.horizontal.size<1){value.horizontal.size=0;}
  720. setting.set(value);}}
  721. _updateVersionFrom7To8(){}
  722. _updateVersionFrom8To9(){const settingNames=['skipStackFramesPattern','workspaceFolderExcludePattern'];for(let i=0;i<settingNames.length;++i){const setting=Common.settings.createSetting(settingNames[i],'');let value=setting.get();if(!value){return;}
  723. if(typeof value==='string'){value=[value];}
  724. for(let j=0;j<value.length;++j){if(typeof value[j]==='string'){value[j]={pattern:value[j]};}}
  725. setting.set(value);}}
  726. _updateVersionFrom9To10(){if(!window.localStorage){return;}
  727. for(const key in window.localStorage){if(key.startsWith('revision-history')){window.localStorage.removeItem(key);}}}
  728. _updateVersionFrom10To11(){const oldSettingName='customDevicePresets';const newSettingName='customEmulatedDeviceList';const oldSetting=Common.settings.createSetting(oldSettingName,undefined);const list=oldSetting.get();if(!Array.isArray(list)){return;}
  729. const newList=[];for(let i=0;i<list.length;++i){const value=list[i];const device={};device['title']=value['title'];device['type']='unknown';device['user-agent']=value['userAgent'];device['capabilities']=[];if(value['touch']){device['capabilities'].push('touch');}
  730. if(value['mobile']){device['capabilities'].push('mobile');}
  731. device['screen']={};device['screen']['vertical']={width:value['width'],height:value['height']};device['screen']['horizontal']={width:value['height'],height:value['width']};device['screen']['device-pixel-ratio']=value['deviceScaleFactor'];device['modes']=[];device['show-by-default']=true;device['show']='Default';newList.push(device);}
  732. if(newList.length){Common.settings.createSetting(newSettingName,[]).set(newList);}
  733. oldSetting.remove();}
  734. _updateVersionFrom11To12(){this._migrateSettingsFromLocalStorage();}
  735. _updateVersionFrom12To13(){this._migrateSettingsFromLocalStorage();Common.settings.createSetting('timelineOverviewMode','').remove();}
  736. _updateVersionFrom13To14(){const defaultValue={'throughput':-1,'latency':0};Common.settings.createSetting('networkConditions',defaultValue).set(defaultValue);}
  737. _updateVersionFrom14To15(){const setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});const oldValue=setting.get();const newValue={};for(const fileSystemPath in oldValue){newValue[fileSystemPath]=[];for(const entry of oldValue[fileSystemPath]){newValue[fileSystemPath].push(entry.path);}}
  738. setting.set(newValue);}
  739. _updateVersionFrom15To16(){const setting=Common.settings.createSetting('InspectorView.panelOrder',{});const tabOrders=setting.get();for(const key of Object.keys(tabOrders)){tabOrders[key]=(tabOrders[key]+1)*10;}
  740. setting.set(tabOrders);}
  741. _updateVersionFrom16To17(){const setting=Common.settings.createSetting('networkConditionsCustomProfiles',[]);const oldValue=setting.get();const newValue=[];if(Array.isArray(oldValue)){for(const preset of oldValue){if(typeof preset.title==='string'&&typeof preset.value==='object'&&typeof preset.value.throughput==='number'&&typeof preset.value.latency==='number'){newValue.push({title:preset.title,value:{download:preset.value.throughput,upload:preset.value.throughput,latency:preset.value.latency}});}}}
  742. setting.set(newValue);}
  743. _updateVersionFrom17To18(){const setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});const oldValue=setting.get();const newValue={};for(const oldKey in oldValue){let newKey=oldKey.replace(/\\/g,'/');if(!newKey.startsWith('file://')){if(newKey.startsWith('/')){newKey='file://'+newKey;}else{newKey='file:///'+newKey;}}
  744. newValue[newKey]=oldValue[oldKey];}
  745. setting.set(newValue);}
  746. _updateVersionFrom18To19(){const defaultColumns={status:true,type:true,initiator:true,size:true,time:true};const visibleColumnSettings=Common.settings.createSetting('networkLogColumnsVisibility',defaultColumns);const visibleColumns=visibleColumnSettings.get();visibleColumns.name=true;visibleColumns.timeline=true;const configs={};for(const columnId in visibleColumns){if(!visibleColumns.hasOwnProperty(columnId)){continue;}
  747. configs[columnId.toLowerCase()]={visible:visibleColumns[columnId]};}
  748. const newSetting=Common.settings.createSetting('networkLogColumns',{});newSetting.set(configs);visibleColumnSettings.remove();}
  749. _updateVersionFrom19To20(){const oldSetting=Common.settings.createSetting('InspectorView.panelOrder',{});const newSetting=Common.settings.createSetting('panel-tabOrder',{});newSetting.set(oldSetting.get());oldSetting.remove();}
  750. _updateVersionFrom20To21(){const networkColumns=Common.settings.createSetting('networkLogColumns',{});const columns=(networkColumns.get());delete columns['timeline'];delete columns['waterfall'];networkColumns.set(columns);}
  751. _updateVersionFrom21To22(){const breakpointsSetting=Common.settings.createLocalSetting('breakpoints',[]);const breakpoints=breakpointsSetting.get();for(const breakpoint of breakpoints){breakpoint['url']=breakpoint['sourceFileId'];delete breakpoint['sourceFileId'];}
  752. breakpointsSetting.set(breakpoints);}
  753. _updateVersionFrom22To23(){}
  754. _updateVersionFrom23To24(){const oldSetting=Common.settings.createSetting('searchInContentScripts',false);const newSetting=Common.settings.createSetting('searchInAnonymousAndContentScripts',false);newSetting.set(oldSetting.get());oldSetting.remove();}
  755. _updateVersionFrom24To25(){const defaultColumns={status:true,type:true,initiator:true,size:true,time:true};const networkLogColumnsSetting=Common.settings.createSetting('networkLogColumns',defaultColumns);const columns=networkLogColumnsSetting.get();delete columns.product;networkLogColumnsSetting.set(columns);}
  756. _updateVersionFrom25To26(){const oldSetting=Common.settings.createSetting('messageURLFilters',{});const urls=Object.keys(oldSetting.get());const textFilter=urls.map(url=>`-url:${url}`).join(' ');if(textFilter){const textFilterSetting=Common.settings.createSetting('console.textFilter','');const suffix=textFilterSetting.get()?` ${textFilterSetting.get()}`:'';textFilterSetting.set(`${textFilter}${suffix}`);}
  757. oldSetting.remove();}
  758. _updateVersionFrom26To27(){function renameKeyInObjectSetting(settingName,from,to){const setting=Common.settings.createSetting(settingName,{});const value=setting.get();if(from in value){value[to]=value[from];delete value[from];setting.set(value);}}
  759. function renameInStringSetting(settingName,from,to){const setting=Common.settings.createSetting(settingName,'');const value=setting.get();if(value===from){setting.set(to);}}
  760. renameKeyInObjectSetting('panel-tabOrder','audits2','audits');renameKeyInObjectSetting('panel-closeableTabs','audits2','audits');renameInStringSetting('panel-selectedTab','audits2','audits');}
  761. _updateVersionFrom27To28(){const setting=Common.settings.createSetting('uiTheme','systemPreferred');if(setting.get()==='default'){setting.set('systemPreferred');}}
  762. _migrateSettingsFromLocalStorage(){const localSettings=new Set(['advancedSearchConfig','breakpoints','consoleHistory','domBreakpoints','eventListenerBreakpoints','fileSystemMapping','lastSelectedSourcesSidebarPaneTab','previouslyViewedFiles','savedURLs','watchExpressions','workspaceExcludedFolders','xhrBreakpoints']);if(!window.localStorage){return;}
  763. for(const key in window.localStorage){if(localSettings.has(key)){continue;}
  764. const value=window.localStorage[key];window.localStorage.removeItem(key);Common.settings._globalStorage[key]=value;}}
  765. _clearBreakpointsWhenTooMany(breakpointsSetting,maxBreakpointsCount){if(breakpointsSetting.get().length>maxBreakpointsCount){breakpointsSetting.set([]);}}}
  766. const SettingStorageType={Global:Symbol('Global'),Local:Symbol('Local'),Session:Symbol('Session')};function moduleSetting(settingName){return Common.settings.moduleSetting(settingName);}
  767. function settingForTest(settingName){return Common.settings.settingForTest(settingName);}
  768. self.Common=self.Common||{};Common=Common||{};Common.Settings=Settings;Common.SettingsStorage=SettingsStorage;Common.Setting=Setting;Common.RegExpSetting=RegExpSetting;Common.settingForTest=settingForTest;Common.VersionController=VersionController;Common.moduleSetting=moduleSetting;Common.SettingStorageType=SettingStorageType;Common.settings;class StaticContentProvider{constructor(contentURL,contentType,lazyContent){this._contentURL=contentURL;this._contentType=contentType;this._lazyContent=lazyContent;}
  769. static fromString(contentURL,contentType,content){const lazyContent=()=>Promise.resolve({content,isEncoded:false});return new StaticContentProvider(contentURL,contentType,lazyContent);}
  770. contentURL(){return this._contentURL;}
  771. contentType(){return this._contentType;}
  772. contentEncoded(){return Promise.resolve(false);}
  773. requestContent(){return this._lazyContent();}
  774. async searchInContent(query,caseSensitive,isRegex){const{content}=(await this._lazyContent());return content?ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex):[];}}
  775. self.Common=self.Common||{};Common=Common||{};Common.StaticContentProvider=StaticContentProvider;class OutputStream{async write(data){}
  776. async close(){}}
  777. class StringOutputStream{constructor(){this._data='';}
  778. async write(chunk){this._data+=chunk;}
  779. async close(){}
  780. data(){return this._data;}}
  781. self.Common=self.Common||{};Common=Common||{};Common.OutputStream=OutputStream;Common.StringOutputStream=StringOutputStream;class Trie{constructor(){this.clear();}
  782. add(word){let node=this._root;++this._wordsInSubtree[this._root];for(let i=0;i<word.length;++i){const edge=word[i];let next=this._edges[node][edge];if(!next){if(this._freeNodes.length){next=this._freeNodes.pop();}else{next=this._size++;this._isWord.push(false);this._wordsInSubtree.push(0);this._edges.push({__proto__:null});}
  783. this._edges[node][edge]=next;}
  784. ++this._wordsInSubtree[next];node=next;}
  785. this._isWord[node]=true;}
  786. remove(word){if(!this.has(word)){return false;}
  787. let node=this._root;--this._wordsInSubtree[this._root];for(let i=0;i<word.length;++i){const edge=word[i];const next=this._edges[node][edge];if(!--this._wordsInSubtree[next]){delete this._edges[node][edge];this._freeNodes.push(next);}
  788. node=next;}
  789. this._isWord[node]=false;return true;}
  790. has(word){let node=this._root;for(let i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node){return false;}}
  791. return this._isWord[node];}
  792. words(prefix){prefix=prefix||'';let node=this._root;for(let i=0;i<prefix.length;++i){node=this._edges[node][prefix[i]];if(!node){return[];}}
  793. const results=[];this._dfs(node,prefix,results);return results;}
  794. _dfs(node,prefix,results){if(this._isWord[node]){results.push(prefix);}
  795. const edges=this._edges[node];for(const edge in edges){this._dfs(edges[edge],prefix+edge,results);}}
  796. longestPrefix(word,fullWordOnly){let node=this._root;let wordIndex=0;for(let i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node){break;}
  797. if(!fullWordOnly||this._isWord[node]){wordIndex=i+1;}}
  798. return word.substring(0,wordIndex);}
  799. clear(){this._size=1;this._root=0;this._edges=[{__proto__:null}];this._isWord=[false];this._wordsInSubtree=[0];this._freeNodes=[];}}
  800. self.Common=self.Common||{};Common=Common||{};Common.Trie=Trie;class TextDictionary{constructor(){this._words=new Map();this._index=new Trie();}
  801. addWord(word){let count=this._words.get(word)||0;++count;this._words.set(word,count);this._index.add(word);}
  802. removeWord(word){let count=this._words.get(word)||0;if(!count){return;}
  803. if(count===1){this._words.delete(word);this._index.remove(word);return;}
  804. --count;this._words.set(word,count);}
  805. wordsWithPrefix(prefix){return this._index.words(prefix);}
  806. hasWord(word){return this._words.has(word);}
  807. wordCount(word){return this._words.get(word)||0;}
  808. reset(){this._words.clear();this._index.clear();}}
  809. self.Common=self.Common||{};Common=Common||{};Common.TextDictionary=TextDictionary;class Throttler{constructor(timeout){this._timeout=timeout;this._isRunningProcess=false;this._asSoonAsPossible=false;this._process=null;this._lastCompleteTime=0;this._schedulePromise=new Promise(fulfill=>{this._scheduleResolve=fulfill;});}
  810. _processCompleted(){this._lastCompleteTime=this._getTime();this._isRunningProcess=false;if(this._process){this._innerSchedule(false);}
  811. this._processCompletedForTests();}
  812. _processCompletedForTests(){}
  813. _onTimeout(){delete this._processTimeout;this._asSoonAsPossible=false;this._isRunningProcess=true;Promise.resolve().then(this._process).catch(console.error.bind(console)).then(this._processCompleted.bind(this)).then(this._scheduleResolve);this._schedulePromise=new Promise(fulfill=>{this._scheduleResolve=fulfill;});this._process=null;}
  814. schedule(process,asSoonAsPossible){this._process=process;const hasScheduledTasks=!!this._processTimeout||this._isRunningProcess;const okToFire=this._getTime()-this._lastCompleteTime>this._timeout;asSoonAsPossible=!!asSoonAsPossible||(!hasScheduledTasks&&okToFire);const forceTimerUpdate=asSoonAsPossible&&!this._asSoonAsPossible;this._asSoonAsPossible=this._asSoonAsPossible||asSoonAsPossible;this._innerSchedule(forceTimerUpdate);return this._schedulePromise;}
  815. _innerSchedule(forceTimerUpdate){if(this._isRunningProcess){return;}
  816. if(this._processTimeout&&!forceTimerUpdate){return;}
  817. if(this._processTimeout){this._clearTimeout(this._processTimeout);}
  818. const timeout=this._asSoonAsPossible?0:this._timeout;this._processTimeout=this._setTimeout(this._onTimeout.bind(this),timeout);}
  819. _clearTimeout(timeoutId){clearTimeout(timeoutId);}
  820. _setTimeout(operation,timeout){return setTimeout(operation,timeout);}
  821. _getTime(){return window.performance.now();}}
  822. self.Common=self.Common||{};Common=Common||{};Common.Throttler=Throttler;Common.Throttler.FinishCallback;class WorkerWrapper{constructor(appName){let url=appName+'.js';url+=Root.Runtime.queryParamsString();this._workerPromise=new Promise(fulfill=>{this._worker=new Worker(url);this._worker.onmessage=onMessage.bind(this);function onMessage(event){console.assert(event.data==='workerReady');this._worker.onmessage=null;fulfill(this._worker);this._worker=null;}});}
  823. postMessage(message){this._workerPromise.then(worker=>{if(!this._disposed){worker.postMessage(message);}});}
  824. dispose(){this._disposed=true;this._workerPromise.then(worker=>worker.terminate());}
  825. terminate(){this.dispose();}
  826. set onmessage(listener){this._workerPromise.then(worker=>worker.onmessage=listener);}
  827. set onerror(listener){this._workerPromise.then(worker=>worker.onerror=listener);}}
  828. self.Common=self.Common||{};Common=Common||{};Common.Worker=WorkerWrapper;const HeapSnapshotProgressEvent={Update:'ProgressUpdate',BrokenSnapshot:'BrokenSnapshot'};const baseSystemDistance=100000000;class AllocationNodeCallers{constructor(nodesWithSingleCaller,branchingCallers){this.nodesWithSingleCaller=nodesWithSingleCaller;this.branchingCallers=branchingCallers;}}
  829. class SerializedAllocationNode{constructor(nodeId,functionName,scriptName,scriptId,line,column,count,size,liveCount,liveSize,hasChildren){this.id=nodeId;this.name=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;this.count=count;this.size=size;this.liveCount=liveCount;this.liveSize=liveSize;this.hasChildren=hasChildren;}}
  830. class AllocationStackFrame{constructor(functionName,scriptName,scriptId,line,column){this.functionName=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;}}
  831. class Node{constructor(id,name,distance,nodeIndex,retainedSize,selfSize,type){this.id=id;this.name=name;this.distance=distance;this.nodeIndex=nodeIndex;this.retainedSize=retainedSize;this.selfSize=selfSize;this.type=type;this.canBeQueried=false;this.detachedDOMTreeNode=false;}}
  832. class Edge{constructor(name,node,type,edgeIndex){this.name=name;this.node=node;this.type=type;this.edgeIndex=edgeIndex;}}
  833. class Aggregate{constructor(){this.count;this.distance;this.self;this.maxRet;this.type;this.name;this.idxs;}}
  834. class AggregateForDiff{constructor(){this.indexes=[];this.ids=[];this.selfSizes=[];}}
  835. class Diff{constructor(){this.addedCount=0;this.removedCount=0;this.addedSize=0;this.removedSize=0;this.deletedIndexes=[];this.addedIndexes=[];}}
  836. class DiffForClass{constructor(){this.addedCount;this.removedCount;this.addedSize;this.removedSize;this.deletedIndexes;this.addedIndexes;this.countDelta;this.sizeDelta;}}
  837. class ComparatorConfig{constructor(){this.fieldName1;this.ascending1;this.fieldName2;this.ascending2;}}
  838. class WorkerCommand{constructor(){this.callId;this.disposition;this.objectId;this.newObjectId;this.methodName;this.methodArguments;this.source;}}
  839. class ItemsRange{constructor(startPosition,endPosition,totalLength,items){this.startPosition=startPosition;this.endPosition=endPosition;this.totalLength=totalLength;this.items=items;}}
  840. class StaticData{constructor(nodeCount,rootNodeIndex,totalSize,maxJSObjectId){this.nodeCount=nodeCount;this.rootNodeIndex=rootNodeIndex;this.totalSize=totalSize;this.maxJSObjectId=maxJSObjectId;}}
  841. class Statistics{constructor(){this.total;this.v8heap;this.native;this.code;this.jsArrays;this.strings;this.system;}}
  842. class NodeFilter{constructor(minNodeId,maxNodeId){this.minNodeId=minNodeId;this.maxNodeId=maxNodeId;this.allocationNodeId;}
  843. equals(o){return this.minNodeId===o.minNodeId&&this.maxNodeId===o.maxNodeId&&this.allocationNodeId===o.allocationNodeId;}}
  844. class SearchConfig{constructor(query,caseSensitive,isRegex,shouldJump,jumpBackward){this.query=query;this.caseSensitive=caseSensitive;this.isRegex=isRegex;this.shouldJump=shouldJump;this.jumpBackward=jumpBackward;}}
  845. class Samples{constructor(timestamps,lastAssignedIds,sizes){this.timestamps=timestamps;this.lastAssignedIds=lastAssignedIds;this.sizes=sizes;}}
  846. class Location{constructor(scriptId,lineNumber,columnNumber){this.scriptId=scriptId;this.lineNumber=lineNumber;this.columnNumber=columnNumber;}}
  847. self.HeapSnapshotModel=self.HeapSnapshotModel||{};HeapSnapshotModel=HeapSnapshotModel||{};HeapSnapshotModel.HeapSnapshotProgressEvent=HeapSnapshotProgressEvent;HeapSnapshotModel.baseSystemDistance=baseSystemDistance;HeapSnapshotModel.AllocationNodeCallers=AllocationNodeCallers;HeapSnapshotModel.SerializedAllocationNode=SerializedAllocationNode;HeapSnapshotModel.AllocationStackFrame=AllocationStackFrame;HeapSnapshotModel.Node=Node;HeapSnapshotModel.Edge=Edge;HeapSnapshotModel.Aggregate=Aggregate;HeapSnapshotModel.AggregateForDiff=AggregateForDiff;HeapSnapshotModel.Diff=Diff;HeapSnapshotModel.DiffForClass=DiffForClass;HeapSnapshotModel.ComparatorConfig=ComparatorConfig;HeapSnapshotModel.WorkerCommand=WorkerCommand;HeapSnapshotModel.ItemsRange=ItemsRange;HeapSnapshotModel.StaticData=StaticData;HeapSnapshotModel.Statistics=Statistics;HeapSnapshotModel.NodeFilter=NodeFilter;HeapSnapshotModel.SearchConfig=SearchConfig;HeapSnapshotModel.Samples=Samples;HeapSnapshotModel.Location=Location;class AllocationProfile{constructor(profile,liveObjectStats){this._strings=profile.strings;this._liveObjectStats=liveObjectStats;this._nextNodeId=1;this._functionInfos=[];this._idToNode={};this._idToTopDownNode={};this._collapsedTopNodeIdToFunctionInfo={};this._traceTops=null;this._buildFunctionAllocationInfos(profile);this._traceTree=this._buildAllocationTree(profile,liveObjectStats);}
  848. _buildFunctionAllocationInfos(profile){const strings=this._strings;const functionInfoFields=profile.snapshot.meta.trace_function_info_fields;const functionNameOffset=functionInfoFields.indexOf('name');const scriptNameOffset=functionInfoFields.indexOf('script_name');const scriptIdOffset=functionInfoFields.indexOf('script_id');const lineOffset=functionInfoFields.indexOf('line');const columnOffset=functionInfoFields.indexOf('column');const functionInfoFieldCount=functionInfoFields.length;const rawInfos=profile.trace_function_infos;const infoLength=rawInfos.length;const functionInfos=this._functionInfos=new Array(infoLength/functionInfoFieldCount);let index=0;for(let i=0;i<infoLength;i+=functionInfoFieldCount){functionInfos[index++]=new FunctionAllocationInfo(strings[rawInfos[i+functionNameOffset]],strings[rawInfos[i+scriptNameOffset]],rawInfos[i+scriptIdOffset],rawInfos[i+lineOffset],rawInfos[i+columnOffset]);}}
  849. _buildAllocationTree(profile,liveObjectStats){const traceTreeRaw=profile.trace_tree;const functionInfos=this._functionInfos;const idToTopDownNode=this._idToTopDownNode;const traceNodeFields=profile.snapshot.meta.trace_node_fields;const nodeIdOffset=traceNodeFields.indexOf('id');const functionInfoIndexOffset=traceNodeFields.indexOf('function_info_index');const allocationCountOffset=traceNodeFields.indexOf('count');const allocationSizeOffset=traceNodeFields.indexOf('size');const childrenOffset=traceNodeFields.indexOf('children');const nodeFieldCount=traceNodeFields.length;function traverseNode(rawNodeArray,nodeOffset,parent){const functionInfo=functionInfos[rawNodeArray[nodeOffset+functionInfoIndexOffset]];const id=rawNodeArray[nodeOffset+nodeIdOffset];const stats=liveObjectStats[id];const liveCount=stats?stats.count:0;const liveSize=stats?stats.size:0;const result=new TopDownAllocationNode(id,functionInfo,rawNodeArray[nodeOffset+allocationCountOffset],rawNodeArray[nodeOffset+allocationSizeOffset],liveCount,liveSize,parent);idToTopDownNode[id]=result;functionInfo.addTraceTopNode(result);const rawChildren=rawNodeArray[nodeOffset+childrenOffset];for(let i=0;i<rawChildren.length;i+=nodeFieldCount){result.children.push(traverseNode(rawChildren,i,result));}
  850. return result;}
  851. return traverseNode(traceTreeRaw,0,null);}
  852. serializeTraceTops(){if(this._traceTops){return this._traceTops;}
  853. const result=this._traceTops=[];const functionInfos=this._functionInfos;for(let i=0;i<functionInfos.length;i++){const info=functionInfos[i];if(info.totalCount===0){continue;}
  854. const nodeId=this._nextNodeId++;const isRoot=i===0;result.push(this._serializeNode(nodeId,info,info.totalCount,info.totalSize,info.totalLiveCount,info.totalLiveSize,!isRoot));this._collapsedTopNodeIdToFunctionInfo[nodeId]=info;}
  855. result.sort(function(a,b){return b.size-a.size;});return result;}
  856. serializeCallers(nodeId){let node=this._ensureBottomUpNode(nodeId);const nodesWithSingleCaller=[];while(node.callers().length===1){node=node.callers()[0];nodesWithSingleCaller.push(this._serializeCaller(node));}
  857. const branchingCallers=[];const callers=node.callers();for(let i=0;i<callers.length;i++){branchingCallers.push(this._serializeCaller(callers[i]));}
  858. return new HeapSnapshotModel.AllocationNodeCallers(nodesWithSingleCaller,branchingCallers);}
  859. serializeAllocationStack(traceNodeId){let node=this._idToTopDownNode[traceNodeId];const result=[];while(node){const functionInfo=node.functionInfo;result.push(new HeapSnapshotModel.AllocationStackFrame(functionInfo.functionName,functionInfo.scriptName,functionInfo.scriptId,functionInfo.line,functionInfo.column));node=node.parent;}
  860. return result;}
  861. traceIds(allocationNodeId){return this._ensureBottomUpNode(allocationNodeId).traceTopIds;}
  862. _ensureBottomUpNode(nodeId){let node=this._idToNode[nodeId];if(!node){const functionInfo=this._collapsedTopNodeIdToFunctionInfo[nodeId];node=functionInfo.bottomUpRoot();delete this._collapsedTopNodeIdToFunctionInfo[nodeId];this._idToNode[nodeId]=node;}
  863. return node;}
  864. _serializeCaller(node){const callerId=this._nextNodeId++;this._idToNode[callerId]=node;return this._serializeNode(callerId,node.functionInfo,node.allocationCount,node.allocationSize,node.liveCount,node.liveSize,node.hasCallers());}
  865. _serializeNode(nodeId,functionInfo,count,size,liveCount,liveSize,hasChildren){return new HeapSnapshotModel.SerializedAllocationNode(nodeId,functionInfo.functionName,functionInfo.scriptName,functionInfo.scriptId,functionInfo.line,functionInfo.column,count,size,liveCount,liveSize,hasChildren);}}
  866. class TopDownAllocationNode{constructor(id,functionInfo,count,size,liveCount,liveSize,parent){this.id=id;this.functionInfo=functionInfo;this.allocationCount=count;this.allocationSize=size;this.liveCount=liveCount;this.liveSize=liveSize;this.parent=parent;this.children=[];}}
  867. class BottomUpAllocationNode{constructor(functionInfo){this.functionInfo=functionInfo;this.allocationCount=0;this.allocationSize=0;this.liveCount=0;this.liveSize=0;this.traceTopIds=[];this._callers=[];}
  868. addCaller(traceNode){const functionInfo=traceNode.functionInfo;let result;for(let i=0;i<this._callers.length;i++){const caller=this._callers[i];if(caller.functionInfo===functionInfo){result=caller;break;}}
  869. if(!result){result=new BottomUpAllocationNode(functionInfo);this._callers.push(result);}
  870. return result;}
  871. callers(){return this._callers;}
  872. hasCallers(){return this._callers.length>0;}}
  873. class FunctionAllocationInfo{constructor(functionName,scriptName,scriptId,line,column){this.functionName=functionName;this.scriptName=scriptName;this.scriptId=scriptId;this.line=line;this.column=column;this.totalCount=0;this.totalSize=0;this.totalLiveCount=0;this.totalLiveSize=0;this._traceTops=[];}
  874. addTraceTopNode(node){if(node.allocationCount===0){return;}
  875. this._traceTops.push(node);this.totalCount+=node.allocationCount;this.totalSize+=node.allocationSize;this.totalLiveCount+=node.liveCount;this.totalLiveSize+=node.liveSize;}
  876. bottomUpRoot(){if(!this._traceTops.length){return null;}
  877. if(!this._bottomUpTree){this._buildAllocationTraceTree();}
  878. return this._bottomUpTree;}
  879. _buildAllocationTraceTree(){this._bottomUpTree=new BottomUpAllocationNode(this);for(let i=0;i<this._traceTops.length;i++){let node=this._traceTops[i];let bottomUpNode=this._bottomUpTree;const count=node.allocationCount;const size=node.allocationSize;const liveCount=node.liveCount;const liveSize=node.liveSize;const traceId=node.id;while(true){bottomUpNode.allocationCount+=count;bottomUpNode.allocationSize+=size;bottomUpNode.liveCount+=liveCount;bottomUpNode.liveSize+=liveSize;bottomUpNode.traceTopIds.push(traceId);node=node.parent;if(node===null){break;}
  880. bottomUpNode=bottomUpNode.addCaller(node);}}}}
  881. self.HeapSnapshotWorker=self.HeapSnapshotWorker||{};HeapSnapshotWorker=HeapSnapshotWorker||{};HeapSnapshotWorker.AllocationProfile=AllocationProfile;HeapSnapshotWorker.TopDownAllocationNode=TopDownAllocationNode;HeapSnapshotWorker.BottomUpAllocationNode=BottomUpAllocationNode;HeapSnapshotWorker.FunctionAllocationInfo=FunctionAllocationInfo;class HeapSnapshotItem{itemIndex(){}
  882. serialize(){}}
  883. class HeapSnapshotEdge{constructor(snapshot,edgeIndex){this._snapshot=snapshot;this._edges=snapshot.containmentEdges;this.edgeIndex=edgeIndex||0;}
  884. clone(){return new HeapSnapshotEdge(this._snapshot,this.edgeIndex);}
  885. hasStringName(){throw new Error('Not implemented');}
  886. name(){throw new Error('Not implemented');}
  887. node(){return this._snapshot.createNode(this.nodeIndex());}
  888. nodeIndex(){return this._edges[this.edgeIndex+this._snapshot._edgeToNodeOffset];}
  889. toString(){return'HeapSnapshotEdge: '+this.name();}
  890. type(){return this._snapshot._edgeTypes[this.rawType()];}
  891. itemIndex(){return this.edgeIndex;}
  892. serialize(){return new HeapSnapshotModel.Edge(this.name(),this.node().serialize(),this.type(),this.edgeIndex);}
  893. rawType(){return this._edges[this.edgeIndex+this._snapshot._edgeTypeOffset];}}
  894. class HeapSnapshotItemIterator{hasNext(){}
  895. item(){}
  896. next(){}}
  897. class HeapSnapshotItemIndexProvider{itemForIndex(newIndex){}}
  898. class HeapSnapshotNodeIndexProvider{constructor(snapshot){this._node=snapshot.createNode();}
  899. itemForIndex(index){this._node.nodeIndex=index;return this._node;}}
  900. class HeapSnapshotEdgeIndexProvider{constructor(snapshot){this._edge=snapshot.createEdge(0);}
  901. itemForIndex(index){this._edge.edgeIndex=index;return this._edge;}}
  902. class HeapSnapshotRetainerEdgeIndexProvider{constructor(snapshot){this._retainerEdge=snapshot.createRetainingEdge(0);}
  903. itemForIndex(index){this._retainerEdge.setRetainerIndex(index);return this._retainerEdge;}}
  904. class HeapSnapshotEdgeIterator{constructor(node){this._sourceNode=node;this.edge=node._snapshot.createEdge(node.edgeIndexesStart());}
  905. hasNext(){return this.edge.edgeIndex<this._sourceNode.edgeIndexesEnd();}
  906. item(){return this.edge;}
  907. next(){this.edge.edgeIndex+=this.edge._snapshot._edgeFieldsCount;}}
  908. class HeapSnapshotRetainerEdge{constructor(snapshot,retainerIndex){this._snapshot=snapshot;this.setRetainerIndex(retainerIndex);}
  909. clone(){return new HeapSnapshotRetainerEdge(this._snapshot,this.retainerIndex());}
  910. hasStringName(){return this._edge().hasStringName();}
  911. name(){return this._edge().name();}
  912. node(){return this._node();}
  913. nodeIndex(){return this._retainingNodeIndex;}
  914. retainerIndex(){return this._retainerIndex;}
  915. setRetainerIndex(retainerIndex){if(retainerIndex===this._retainerIndex){return;}
  916. this._retainerIndex=retainerIndex;this._globalEdgeIndex=this._snapshot._retainingEdges[retainerIndex];this._retainingNodeIndex=this._snapshot._retainingNodes[retainerIndex];this._edgeInstance=null;this._nodeInstance=null;}
  917. set edgeIndex(edgeIndex){this.setRetainerIndex(edgeIndex);}
  918. _node(){if(!this._nodeInstance){this._nodeInstance=this._snapshot.createNode(this._retainingNodeIndex);}
  919. return this._nodeInstance;}
  920. _edge(){if(!this._edgeInstance){this._edgeInstance=this._snapshot.createEdge(this._globalEdgeIndex);}
  921. return this._edgeInstance;}
  922. toString(){return this._edge().toString();}
  923. itemIndex(){return this._retainerIndex;}
  924. serialize(){return new HeapSnapshotModel.Edge(this.name(),this.node().serialize(),this.type(),this._globalEdgeIndex);}
  925. type(){return this._edge().type();}}
  926. class HeapSnapshotRetainerEdgeIterator{constructor(retainedNode){const snapshot=retainedNode._snapshot;const retainedNodeOrdinal=retainedNode.ordinal();const retainerIndex=snapshot._firstRetainerIndex[retainedNodeOrdinal];this._retainersEnd=snapshot._firstRetainerIndex[retainedNodeOrdinal+1];this.retainer=snapshot.createRetainingEdge(retainerIndex);}
  927. hasNext(){return this.retainer.retainerIndex()<this._retainersEnd;}
  928. item(){return this.retainer;}
  929. next(){this.retainer.setRetainerIndex(this.retainer.retainerIndex()+1);}}
  930. class HeapSnapshotNode{constructor(snapshot,nodeIndex){this._snapshot=snapshot;this.nodeIndex=nodeIndex||0;}
  931. distance(){return this._snapshot._nodeDistances[this.nodeIndex/this._snapshot._nodeFieldCount];}
  932. className(){throw new Error('Not implemented');}
  933. classIndex(){throw new Error('Not implemented');}
  934. dominatorIndex(){const nodeFieldCount=this._snapshot._nodeFieldCount;return this._snapshot._dominatorsTree[this.nodeIndex/this._snapshot._nodeFieldCount]*nodeFieldCount;}
  935. edges(){return new HeapSnapshotEdgeIterator(this);}
  936. edgesCount(){return(this.edgeIndexesEnd()-this.edgeIndexesStart())/this._snapshot._edgeFieldsCount;}
  937. id(){throw new Error('Not implemented');}
  938. isRoot(){return this.nodeIndex===this._snapshot._rootNodeIndex;}
  939. name(){return this._snapshot.strings[this._name()];}
  940. retainedSize(){return this._snapshot._retainedSizes[this.ordinal()];}
  941. retainers(){return new HeapSnapshotRetainerEdgeIterator(this);}
  942. retainersCount(){const snapshot=this._snapshot;const ordinal=this.ordinal();return snapshot._firstRetainerIndex[ordinal+1]-snapshot._firstRetainerIndex[ordinal];}
  943. selfSize(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeSelfSizeOffset];}
  944. type(){return this._snapshot._nodeTypes[this.rawType()];}
  945. traceNodeId(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeTraceNodeIdOffset];}
  946. itemIndex(){return this.nodeIndex;}
  947. serialize(){return new HeapSnapshotModel.Node(this.id(),this.name(),this.distance(),this.nodeIndex,this.retainedSize(),this.selfSize(),this.type());}
  948. _name(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeNameOffset];}
  949. edgeIndexesStart(){return this._snapshot._firstEdgeIndexes[this.ordinal()];}
  950. edgeIndexesEnd(){return this._snapshot._firstEdgeIndexes[this.ordinal()+1];}
  951. ordinal(){return this.nodeIndex/this._snapshot._nodeFieldCount;}
  952. _nextNodeIndex(){return this.nodeIndex+this._snapshot._nodeFieldCount;}
  953. rawType(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeTypeOffset];}}
  954. class HeapSnapshotNodeIterator{constructor(node){this.node=node;this._nodesLength=node._snapshot.nodes.length;}
  955. hasNext(){return this.node.nodeIndex<this._nodesLength;}
  956. item(){return this.node;}
  957. next(){this.node.nodeIndex=this.node._nextNodeIndex();}}
  958. class HeapSnapshotIndexRangeIterator{constructor(itemProvider,indexes){this._itemProvider=itemProvider;this._indexes=indexes;this._position=0;}
  959. hasNext(){return this._position<this._indexes.length;}
  960. item(){const index=this._indexes[this._position];return this._itemProvider.itemForIndex(index);}
  961. next(){++this._position;}}
  962. class HeapSnapshotFilteredIterator{constructor(iterator,filter){this._iterator=iterator;this._filter=filter;this._skipFilteredItems();}
  963. hasNext(){return this._iterator.hasNext();}
  964. item(){return this._iterator.item();}
  965. next(){this._iterator.next();this._skipFilteredItems();}
  966. _skipFilteredItems(){while(this._iterator.hasNext()&&!this._filter(this._iterator.item())){this._iterator.next();}}}
  967. class HeapSnapshotProgress{constructor(dispatcher){this._dispatcher=dispatcher;}
  968. updateStatus(status){this._sendUpdateEvent(Common.serializeUIString(status));}
  969. updateProgress(title,value,total){const percentValue=((total?(value/total):0)*100).toFixed(0);this._sendUpdateEvent(Common.serializeUIString(title,[percentValue]));}
  970. reportProblem(error){if(this._dispatcher){this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotProgressEvent.BrokenSnapshot,error);}}
  971. _sendUpdateEvent(serializedText){if(this._dispatcher){this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotProgressEvent.Update,serializedText);}}}
  972. class HeapSnapshotProblemReport{constructor(title){this._errors=[title];}
  973. addError(error){if(this._errors.length>100){return;}
  974. this._errors.push(error);}
  975. toString(){return this._errors.join('\n ');}}
  976. class HeapSnapshot{constructor(profile,progress){this.nodes=profile.nodes;this.containmentEdges=profile.edges;this._metaNode=profile.snapshot.meta;this._rawSamples=profile.samples;this._samples=null;this.strings=profile.strings;this._locations=profile.locations;this._progress=progress;this._noDistance=-5;this._rootNodeIndex=0;if(profile.snapshot.root_index){this._rootNodeIndex=profile.snapshot.root_index;}
  977. this._snapshotDiffs={};this._aggregatesForDiff=null;this._aggregates={};this._aggregatesSortedFlags={};this._profile=profile;}
  978. initialize(){const meta=this._metaNode;this._nodeTypeOffset=meta.node_fields.indexOf('type');this._nodeNameOffset=meta.node_fields.indexOf('name');this._nodeIdOffset=meta.node_fields.indexOf('id');this._nodeSelfSizeOffset=meta.node_fields.indexOf('self_size');this._nodeEdgeCountOffset=meta.node_fields.indexOf('edge_count');this._nodeTraceNodeIdOffset=meta.node_fields.indexOf('trace_node_id');this._nodeFieldCount=meta.node_fields.length;this._nodeTypes=meta.node_types[this._nodeTypeOffset];this._nodeArrayType=this._nodeTypes.indexOf('array');this._nodeHiddenType=this._nodeTypes.indexOf('hidden');this._nodeObjectType=this._nodeTypes.indexOf('object');this._nodeNativeType=this._nodeTypes.indexOf('native');this._nodeConsStringType=this._nodeTypes.indexOf('concatenated string');this._nodeSlicedStringType=this._nodeTypes.indexOf('sliced string');this._nodeCodeType=this._nodeTypes.indexOf('code');this._nodeSyntheticType=this._nodeTypes.indexOf('synthetic');this._edgeFieldsCount=meta.edge_fields.length;this._edgeTypeOffset=meta.edge_fields.indexOf('type');this._edgeNameOffset=meta.edge_fields.indexOf('name_or_index');this._edgeToNodeOffset=meta.edge_fields.indexOf('to_node');this._edgeTypes=meta.edge_types[this._edgeTypeOffset];this._edgeTypes.push('invisible');this._edgeElementType=this._edgeTypes.indexOf('element');this._edgeHiddenType=this._edgeTypes.indexOf('hidden');this._edgeInternalType=this._edgeTypes.indexOf('internal');this._edgeShortcutType=this._edgeTypes.indexOf('shortcut');this._edgeWeakType=this._edgeTypes.indexOf('weak');this._edgeInvisibleType=this._edgeTypes.indexOf('invisible');const location_fields=meta.location_fields||[];this._locationIndexOffset=location_fields.indexOf('object_index');this._locationScriptIdOffset=location_fields.indexOf('script_id');this._locationLineOffset=location_fields.indexOf('line');this._locationColumnOffset=location_fields.indexOf('column');this._locationFieldCount=location_fields.length;this.nodeCount=this.nodes.length/this._nodeFieldCount;this._edgeCount=this.containmentEdges.length/this._edgeFieldsCount;this._retainedSizes=new Float64Array(this.nodeCount);this._firstEdgeIndexes=new Uint32Array(this.nodeCount+1);this._retainingNodes=new Uint32Array(this._edgeCount);this._retainingEdges=new Uint32Array(this._edgeCount);this._firstRetainerIndex=new Uint32Array(this.nodeCount+1);this._nodeDistances=new Int32Array(this.nodeCount);this._firstDominatedNodeIndex=new Uint32Array(this.nodeCount+1);this._dominatedNodes=new Uint32Array(this.nodeCount-1);this._progress.updateStatus(ls`Building edge indexes\u2026`);this._buildEdgeIndexes();this._progress.updateStatus(ls`Building retainers\u2026`);this._buildRetainers();this._progress.updateStatus(ls`Calculating node flags\u2026`);this.calculateFlags();this._progress.updateStatus(ls`Calculating distances\u2026`);this.calculateDistances();this._progress.updateStatus(ls`Building postorder index\u2026`);const result=this._buildPostOrderIndex();this._progress.updateStatus(ls`Building dominator tree\u2026`);this._dominatorsTree=this._buildDominatorTree(result.postOrderIndex2NodeOrdinal,result.nodeOrdinal2PostOrderIndex);this._progress.updateStatus(ls`Calculating retained sizes\u2026`);this._calculateRetainedSizes(result.postOrderIndex2NodeOrdinal);this._progress.updateStatus(ls`Building dominated nodes\u2026`);this._buildDominatedNodes();this._progress.updateStatus(ls`Calculating statistics\u2026`);this.calculateStatistics();this._progress.updateStatus(ls`Calculating samples\u2026`);this._buildSamples();this._progress.updateStatus(ls`Building locations\u2026`);this._buildLocationMap();this._progress.updateStatus(ls`Finished processing.`);if(this._profile.snapshot.trace_function_count){this._progress.updateStatus(ls`Building allocation statistics\u2026`);const nodes=this.nodes;const nodesLength=nodes.length;const nodeFieldCount=this._nodeFieldCount;const node=this.rootNode();const liveObjects={};for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;const traceNodeId=node.traceNodeId();let stats=liveObjects[traceNodeId];if(!stats){liveObjects[traceNodeId]=stats={count:0,size:0,ids:[]};}
  979. stats.count++;stats.size+=node.selfSize();stats.ids.push(node.id());}
  980. this._allocationProfile=new HeapSnapshotWorker.AllocationProfile(this._profile,liveObjects);this._progress.updateStatus(ls`Done`);}}
  981. _buildEdgeIndexes(){const nodes=this.nodes;const nodeCount=this.nodeCount;const firstEdgeIndexes=this._firstEdgeIndexes;const nodeFieldCount=this._nodeFieldCount;const edgeFieldsCount=this._edgeFieldsCount;const nodeEdgeCountOffset=this._nodeEdgeCountOffset;firstEdgeIndexes[nodeCount]=this.containmentEdges.length;for(let nodeOrdinal=0,edgeIndex=0;nodeOrdinal<nodeCount;++nodeOrdinal){firstEdgeIndexes[nodeOrdinal]=edgeIndex;edgeIndex+=nodes[nodeOrdinal*nodeFieldCount+nodeEdgeCountOffset]*edgeFieldsCount;}}
  982. _buildRetainers(){const retainingNodes=this._retainingNodes;const retainingEdges=this._retainingEdges;const firstRetainerIndex=this._firstRetainerIndex;const containmentEdges=this.containmentEdges;const edgeFieldsCount=this._edgeFieldsCount;const nodeFieldCount=this._nodeFieldCount;const edgeToNodeOffset=this._edgeToNodeOffset;const firstEdgeIndexes=this._firstEdgeIndexes;const nodeCount=this.nodeCount;for(let toNodeFieldIndex=edgeToNodeOffset,l=containmentEdges.length;toNodeFieldIndex<l;toNodeFieldIndex+=edgeFieldsCount){const toNodeIndex=containmentEdges[toNodeFieldIndex];if(toNodeIndex%nodeFieldCount){throw new Error('Invalid toNodeIndex '+toNodeIndex);}
  983. ++firstRetainerIndex[toNodeIndex/nodeFieldCount];}
  984. for(let i=0,firstUnusedRetainerSlot=0;i<nodeCount;i++){const retainersCount=firstRetainerIndex[i];firstRetainerIndex[i]=firstUnusedRetainerSlot;retainingNodes[firstUnusedRetainerSlot]=retainersCount;firstUnusedRetainerSlot+=retainersCount;}
  985. firstRetainerIndex[nodeCount]=retainingNodes.length;let nextNodeFirstEdgeIndex=firstEdgeIndexes[0];for(let srcNodeOrdinal=0;srcNodeOrdinal<nodeCount;++srcNodeOrdinal){const firstEdgeIndex=nextNodeFirstEdgeIndex;nextNodeFirstEdgeIndex=firstEdgeIndexes[srcNodeOrdinal+1];const srcNodeIndex=srcNodeOrdinal*nodeFieldCount;for(let edgeIndex=firstEdgeIndex;edgeIndex<nextNodeFirstEdgeIndex;edgeIndex+=edgeFieldsCount){const toNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];if(toNodeIndex%nodeFieldCount){throw new Error('Invalid toNodeIndex '+toNodeIndex);}
  986. const firstRetainerSlotIndex=firstRetainerIndex[toNodeIndex/nodeFieldCount];const nextUnusedRetainerSlotIndex=firstRetainerSlotIndex+(--retainingNodes[firstRetainerSlotIndex]);retainingNodes[nextUnusedRetainerSlotIndex]=srcNodeIndex;retainingEdges[nextUnusedRetainerSlotIndex]=edgeIndex;}}}
  987. createNode(nodeIndex){throw new Error('Not implemented');}
  988. createEdge(edgeIndex){throw new Error('Not implemented');}
  989. createRetainingEdge(retainerIndex){throw new Error('Not implemented');}
  990. _allNodes(){return new HeapSnapshotNodeIterator(this.rootNode());}
  991. rootNode(){return this.createNode(this._rootNodeIndex);}
  992. get rootNodeIndex(){return this._rootNodeIndex;}
  993. get totalSize(){return this.rootNode().retainedSize();}
  994. _getDominatedIndex(nodeIndex){if(nodeIndex%this._nodeFieldCount){throw new Error('Invalid nodeIndex: '+nodeIndex);}
  995. return this._firstDominatedNodeIndex[nodeIndex/this._nodeFieldCount];}
  996. _createFilter(nodeFilter){const minNodeId=nodeFilter.minNodeId;const maxNodeId=nodeFilter.maxNodeId;const allocationNodeId=nodeFilter.allocationNodeId;let filter;if(typeof allocationNodeId==='number'){filter=this._createAllocationStackFilter(allocationNodeId);filter.key='AllocationNodeId: '+allocationNodeId;}else if(typeof minNodeId==='number'&&typeof maxNodeId==='number'){filter=this._createNodeIdFilter(minNodeId,maxNodeId);filter.key='NodeIdRange: '+minNodeId+'..'+maxNodeId;}
  997. return filter;}
  998. search(searchConfig,nodeFilter){const query=searchConfig.query;function filterString(matchedStringIndexes,string,index){if(string.indexOf(query)!==-1){matchedStringIndexes.add(index);}
  999. return matchedStringIndexes;}
  1000. const regexp=searchConfig.isRegex?new RegExp(query):createPlainTextSearchRegex(query,'i');function filterRegexp(matchedStringIndexes,string,index){if(regexp.test(string)){matchedStringIndexes.add(index);}
  1001. return matchedStringIndexes;}
  1002. const stringFilter=(searchConfig.isRegex||!searchConfig.caseSensitive)?filterRegexp:filterString;const stringIndexes=this.strings.reduce(stringFilter,new Set());if(!stringIndexes.size){return[];}
  1003. const filter=this._createFilter(nodeFilter);const nodeIds=[];const nodesLength=this.nodes.length;const nodes=this.nodes;const nodeNameOffset=this._nodeNameOffset;const nodeIdOffset=this._nodeIdOffset;const nodeFieldCount=this._nodeFieldCount;const node=this.rootNode();for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;if(filter&&!filter(node)){continue;}
  1004. if(stringIndexes.has(nodes[nodeIndex+nodeNameOffset])){nodeIds.push(nodes[nodeIndex+nodeIdOffset]);}}
  1005. return nodeIds;}
  1006. aggregatesWithFilter(nodeFilter){const filter=this._createFilter(nodeFilter);const key=filter?filter.key:'allObjects';return this.aggregates(false,key,filter);}
  1007. _createNodeIdFilter(minNodeId,maxNodeId){function nodeIdFilter(node){const id=node.id();return id>minNodeId&&id<=maxNodeId;}
  1008. return nodeIdFilter;}
  1009. _createAllocationStackFilter(bottomUpAllocationNodeId){const traceIds=this._allocationProfile.traceIds(bottomUpAllocationNodeId);if(!traceIds.length){return undefined;}
  1010. const set={};for(let i=0;i<traceIds.length;i++){set[traceIds[i]]=true;}
  1011. function traceIdFilter(node){return!!set[node.traceNodeId()];}
  1012. return traceIdFilter;}
  1013. aggregates(sortedIndexes,key,filter){let aggregatesByClassName=key&&this._aggregates[key];if(!aggregatesByClassName){const aggregates=this._buildAggregates(filter);this._calculateClassesRetainedSize(aggregates.aggregatesByClassIndex,filter);aggregatesByClassName=aggregates.aggregatesByClassName;if(key){this._aggregates[key]=aggregatesByClassName;}}
  1014. if(sortedIndexes&&(!key||!this._aggregatesSortedFlags[key])){this._sortAggregateIndexes(aggregatesByClassName);if(key){this._aggregatesSortedFlags[key]=sortedIndexes;}}
  1015. return aggregatesByClassName;}
  1016. allocationTracesTops(){return this._allocationProfile.serializeTraceTops();}
  1017. allocationNodeCallers(nodeId){return this._allocationProfile.serializeCallers(nodeId);}
  1018. allocationStack(nodeIndex){const node=this.createNode(nodeIndex);const allocationNodeId=node.traceNodeId();if(!allocationNodeId){return null;}
  1019. return this._allocationProfile.serializeAllocationStack(allocationNodeId);}
  1020. aggregatesForDiff(){if(this._aggregatesForDiff){return this._aggregatesForDiff;}
  1021. const aggregatesByClassName=this.aggregates(true,'allObjects');this._aggregatesForDiff={};const node=this.createNode();for(const className in aggregatesByClassName){const aggregate=aggregatesByClassName[className];const indexes=aggregate.idxs;const ids=new Array(indexes.length);const selfSizes=new Array(indexes.length);for(let i=0;i<indexes.length;i++){node.nodeIndex=indexes[i];ids[i]=node.id();selfSizes[i]=node.selfSize();}
  1022. this._aggregatesForDiff[className]={indexes:indexes,ids:ids,selfSizes:selfSizes};}
  1023. return this._aggregatesForDiff;}
  1024. isUserRoot(node){return true;}
  1025. calculateDistances(filter){const nodeCount=this.nodeCount;const distances=this._nodeDistances;const noDistance=this._noDistance;for(let i=0;i<nodeCount;++i){distances[i]=noDistance;}
  1026. const nodesToVisit=new Uint32Array(this.nodeCount);let nodesToVisitLength=0;for(let iter=this.rootNode().edges();iter.hasNext();iter.next()){const node=iter.edge.node();if(this.isUserRoot(node)){distances[node.ordinal()]=1;nodesToVisit[nodesToVisitLength++]=node.nodeIndex;}}
  1027. this._bfs(nodesToVisit,nodesToVisitLength,distances,filter);distances[this.rootNode().ordinal()]=nodesToVisitLength>0?HeapSnapshotModel.baseSystemDistance:0;nodesToVisit[0]=this.rootNode().nodeIndex;nodesToVisitLength=1;this._bfs(nodesToVisit,nodesToVisitLength,distances,filter);}
  1028. _bfs(nodesToVisit,nodesToVisitLength,distances,filter){const edgeFieldsCount=this._edgeFieldsCount;const nodeFieldCount=this._nodeFieldCount;const containmentEdges=this.containmentEdges;const firstEdgeIndexes=this._firstEdgeIndexes;const edgeToNodeOffset=this._edgeToNodeOffset;const edgeTypeOffset=this._edgeTypeOffset;const nodeCount=this.nodeCount;const edgeWeakType=this._edgeWeakType;const noDistance=this._noDistance;let index=0;const edge=this.createEdge(0);const node=this.createNode(0);while(index<nodesToVisitLength){const nodeIndex=nodesToVisit[index++];const nodeOrdinal=nodeIndex/nodeFieldCount;const distance=distances[nodeOrdinal]+1;const firstEdgeIndex=firstEdgeIndexes[nodeOrdinal];const edgesEnd=firstEdgeIndexes[nodeOrdinal+1];node.nodeIndex=nodeIndex;for(let edgeIndex=firstEdgeIndex;edgeIndex<edgesEnd;edgeIndex+=edgeFieldsCount){const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(edgeType===edgeWeakType){continue;}
  1029. const childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];const childNodeOrdinal=childNodeIndex/nodeFieldCount;if(distances[childNodeOrdinal]!==noDistance){continue;}
  1030. edge.edgeIndex=edgeIndex;if(filter&&!filter(node,edge)){continue;}
  1031. distances[childNodeOrdinal]=distance;nodesToVisit[nodesToVisitLength++]=childNodeIndex;}}
  1032. if(nodesToVisitLength>nodeCount){throw new Error('BFS failed. Nodes to visit ('+nodesToVisitLength+') is more than nodes count ('+nodeCount+')');}}
  1033. _buildAggregates(filter){const aggregates={};const aggregatesByClassName={};const classIndexes=[];const nodes=this.nodes;const nodesLength=nodes.length;const nodeNativeType=this._nodeNativeType;const nodeFieldCount=this._nodeFieldCount;const selfSizeOffset=this._nodeSelfSizeOffset;const nodeTypeOffset=this._nodeTypeOffset;const node=this.rootNode();const nodeDistances=this._nodeDistances;for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;if(filter&&!filter(node)){continue;}
  1034. const selfSize=nodes[nodeIndex+selfSizeOffset];if(!selfSize&&nodes[nodeIndex+nodeTypeOffset]!==nodeNativeType){continue;}
  1035. const classIndex=node.classIndex();const nodeOrdinal=nodeIndex/nodeFieldCount;const distance=nodeDistances[nodeOrdinal];if(!(classIndex in aggregates)){const nodeType=node.type();const nameMatters=nodeType==='object'||nodeType==='native';const value={count:1,distance:distance,self:selfSize,maxRet:0,type:nodeType,name:nameMatters?node.name():null,idxs:[nodeIndex]};aggregates[classIndex]=value;classIndexes.push(classIndex);aggregatesByClassName[node.className()]=value;}else{const clss=aggregates[classIndex];clss.distance=Math.min(clss.distance,distance);++clss.count;clss.self+=selfSize;clss.idxs.push(nodeIndex);}}
  1036. for(let i=0,l=classIndexes.length;i<l;++i){const classIndex=classIndexes[i];aggregates[classIndex].idxs=aggregates[classIndex].idxs.slice();}
  1037. return{aggregatesByClassName:aggregatesByClassName,aggregatesByClassIndex:aggregates};}
  1038. _calculateClassesRetainedSize(aggregates,filter){const rootNodeIndex=this._rootNodeIndex;const node=this.createNode(rootNodeIndex);const list=[rootNodeIndex];const sizes=[-1];const classes=[];const seenClassNameIndexes={};const nodeFieldCount=this._nodeFieldCount;const nodeTypeOffset=this._nodeTypeOffset;const nodeNativeType=this._nodeNativeType;const dominatedNodes=this._dominatedNodes;const nodes=this.nodes;const firstDominatedNodeIndex=this._firstDominatedNodeIndex;while(list.length){const nodeIndex=list.pop();node.nodeIndex=nodeIndex;let classIndex=node.classIndex();const seen=!!seenClassNameIndexes[classIndex];const nodeOrdinal=nodeIndex/nodeFieldCount;const dominatedIndexFrom=firstDominatedNodeIndex[nodeOrdinal];const dominatedIndexTo=firstDominatedNodeIndex[nodeOrdinal+1];if(!seen&&(!filter||filter(node))&&(node.selfSize()||nodes[nodeIndex+nodeTypeOffset]===nodeNativeType)){aggregates[classIndex].maxRet+=node.retainedSize();if(dominatedIndexFrom!==dominatedIndexTo){seenClassNameIndexes[classIndex]=true;sizes.push(list.length);classes.push(classIndex);}}
  1039. for(let i=dominatedIndexFrom;i<dominatedIndexTo;i++){list.push(dominatedNodes[i]);}
  1040. const l=list.length;while(sizes[sizes.length-1]===l){sizes.pop();classIndex=classes.pop();seenClassNameIndexes[classIndex]=false;}}}
  1041. _sortAggregateIndexes(aggregates){const nodeA=this.createNode();const nodeB=this.createNode();for(const clss in aggregates){aggregates[clss].idxs.sort((idxA,idxB)=>{nodeA.nodeIndex=idxA;nodeB.nodeIndex=idxB;return nodeA.id()<nodeB.id()?-1:1;});}}
  1042. _isEssentialEdge(nodeIndex,edgeType){return edgeType!==this._edgeWeakType&&(edgeType!==this._edgeShortcutType||nodeIndex===this._rootNodeIndex);}
  1043. _buildPostOrderIndex(){const nodeFieldCount=this._nodeFieldCount;const nodeCount=this.nodeCount;const rootNodeOrdinal=this._rootNodeIndex/nodeFieldCount;const edgeFieldsCount=this._edgeFieldsCount;const edgeTypeOffset=this._edgeTypeOffset;const edgeToNodeOffset=this._edgeToNodeOffset;const firstEdgeIndexes=this._firstEdgeIndexes;const containmentEdges=this.containmentEdges;const mapAndFlag=this.userObjectsMapAndFlag();const flags=mapAndFlag?mapAndFlag.map:null;const flag=mapAndFlag?mapAndFlag.flag:0;const stackNodes=new Uint32Array(nodeCount);const stackCurrentEdge=new Uint32Array(nodeCount);const postOrderIndex2NodeOrdinal=new Uint32Array(nodeCount);const nodeOrdinal2PostOrderIndex=new Uint32Array(nodeCount);const visited=new Uint8Array(nodeCount);let postOrderIndex=0;let stackTop=0;stackNodes[0]=rootNodeOrdinal;stackCurrentEdge[0]=firstEdgeIndexes[rootNodeOrdinal];visited[rootNodeOrdinal]=1;let iteration=0;while(true){++iteration;while(stackTop>=0){const nodeOrdinal=stackNodes[stackTop];const edgeIndex=stackCurrentEdge[stackTop];const edgesEnd=firstEdgeIndexes[nodeOrdinal+1];if(edgeIndex<edgesEnd){stackCurrentEdge[stackTop]+=edgeFieldsCount;const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(!this._isEssentialEdge(nodeOrdinal*nodeFieldCount,edgeType)){continue;}
  1044. const childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];const childNodeOrdinal=childNodeIndex/nodeFieldCount;if(visited[childNodeOrdinal]){continue;}
  1045. const nodeFlag=!flags||(flags[nodeOrdinal]&flag);const childNodeFlag=!flags||(flags[childNodeOrdinal]&flag);if(nodeOrdinal!==rootNodeOrdinal&&childNodeFlag&&!nodeFlag){continue;}
  1046. ++stackTop;stackNodes[stackTop]=childNodeOrdinal;stackCurrentEdge[stackTop]=firstEdgeIndexes[childNodeOrdinal];visited[childNodeOrdinal]=1;}else{nodeOrdinal2PostOrderIndex[nodeOrdinal]=postOrderIndex;postOrderIndex2NodeOrdinal[postOrderIndex++]=nodeOrdinal;--stackTop;}}
  1047. if(postOrderIndex===nodeCount||iteration>1){break;}
  1048. const errors=new HeapSnapshotProblemReport(`Heap snapshot: ${
  1049. nodeCount - postOrderIndex} nodes are unreachable from the root. Following nodes have only weak retainers:`);const dumpNode=this.rootNode();--postOrderIndex;stackTop=0;stackNodes[0]=rootNodeOrdinal;stackCurrentEdge[0]=firstEdgeIndexes[rootNodeOrdinal+1];for(let i=0;i<nodeCount;++i){if(visited[i]||!this._hasOnlyWeakRetainers(i)){continue;}
  1050. stackNodes[++stackTop]=i;stackCurrentEdge[stackTop]=firstEdgeIndexes[i];visited[i]=1;dumpNode.nodeIndex=i*nodeFieldCount;const retainers=[];for(let it=dumpNode.retainers();it.hasNext();it.next()){retainers.push(`${it.item().node().name()}@${it.item().node().id()}.${it.item().name()}`);}
  1051. errors.addError(`${dumpNode.name()} @${dumpNode.id()} weak retainers: ${retainers.join(', ')}`);}
  1052. console.warn(errors.toString());}
  1053. if(postOrderIndex!==nodeCount){const errors=new HeapSnapshotProblemReport('Still found '+(nodeCount-postOrderIndex)+' unreachable nodes in heap snapshot:');const dumpNode=this.rootNode();--postOrderIndex;for(let i=0;i<nodeCount;++i){if(visited[i]){continue;}
  1054. dumpNode.nodeIndex=i*nodeFieldCount;errors.addError(dumpNode.name()+' @'+dumpNode.id());nodeOrdinal2PostOrderIndex[i]=postOrderIndex;postOrderIndex2NodeOrdinal[postOrderIndex++]=i;}
  1055. nodeOrdinal2PostOrderIndex[rootNodeOrdinal]=postOrderIndex;postOrderIndex2NodeOrdinal[postOrderIndex++]=rootNodeOrdinal;console.warn(errors.toString());}
  1056. return{postOrderIndex2NodeOrdinal:postOrderIndex2NodeOrdinal,nodeOrdinal2PostOrderIndex:nodeOrdinal2PostOrderIndex};}
  1057. _hasOnlyWeakRetainers(nodeOrdinal){const edgeTypeOffset=this._edgeTypeOffset;const edgeWeakType=this._edgeWeakType;const edgeShortcutType=this._edgeShortcutType;const containmentEdges=this.containmentEdges;const retainingEdges=this._retainingEdges;const beginRetainerIndex=this._firstRetainerIndex[nodeOrdinal];const endRetainerIndex=this._firstRetainerIndex[nodeOrdinal+1];for(let retainerIndex=beginRetainerIndex;retainerIndex<endRetainerIndex;++retainerIndex){const retainerEdgeIndex=retainingEdges[retainerIndex];const retainerEdgeType=containmentEdges[retainerEdgeIndex+edgeTypeOffset];if(retainerEdgeType!==edgeWeakType&&retainerEdgeType!==edgeShortcutType){return false;}}
  1058. return true;}
  1059. _buildDominatorTree(postOrderIndex2NodeOrdinal,nodeOrdinal2PostOrderIndex){const nodeFieldCount=this._nodeFieldCount;const firstRetainerIndex=this._firstRetainerIndex;const retainingNodes=this._retainingNodes;const retainingEdges=this._retainingEdges;const edgeFieldsCount=this._edgeFieldsCount;const edgeTypeOffset=this._edgeTypeOffset;const edgeToNodeOffset=this._edgeToNodeOffset;const firstEdgeIndexes=this._firstEdgeIndexes;const containmentEdges=this.containmentEdges;const rootNodeIndex=this._rootNodeIndex;const mapAndFlag=this.userObjectsMapAndFlag();const flags=mapAndFlag?mapAndFlag.map:null;const flag=mapAndFlag?mapAndFlag.flag:0;const nodesCount=postOrderIndex2NodeOrdinal.length;const rootPostOrderedIndex=nodesCount-1;const noEntry=nodesCount;const dominators=new Uint32Array(nodesCount);for(let i=0;i<rootPostOrderedIndex;++i){dominators[i]=noEntry;}
  1060. dominators[rootPostOrderedIndex]=rootPostOrderedIndex;const affected=new Uint8Array(nodesCount);let nodeOrdinal;{nodeOrdinal=this._rootNodeIndex/nodeFieldCount;const endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];for(let edgeIndex=firstEdgeIndexes[nodeOrdinal];edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(!this._isEssentialEdge(this._rootNodeIndex,edgeType)){continue;}
  1061. const childNodeOrdinal=containmentEdges[edgeIndex+edgeToNodeOffset]/nodeFieldCount;affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]]=1;}}
  1062. let changed=true;while(changed){changed=false;for(let postOrderIndex=rootPostOrderedIndex-1;postOrderIndex>=0;--postOrderIndex){if(affected[postOrderIndex]===0){continue;}
  1063. affected[postOrderIndex]=0;if(dominators[postOrderIndex]===rootPostOrderedIndex){continue;}
  1064. nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];const nodeFlag=!flags||(flags[nodeOrdinal]&flag);let newDominatorIndex=noEntry;const beginRetainerIndex=firstRetainerIndex[nodeOrdinal];const endRetainerIndex=firstRetainerIndex[nodeOrdinal+1];let orphanNode=true;for(let retainerIndex=beginRetainerIndex;retainerIndex<endRetainerIndex;++retainerIndex){const retainerEdgeIndex=retainingEdges[retainerIndex];const retainerEdgeType=containmentEdges[retainerEdgeIndex+edgeTypeOffset];const retainerNodeIndex=retainingNodes[retainerIndex];if(!this._isEssentialEdge(retainerNodeIndex,retainerEdgeType)){continue;}
  1065. orphanNode=false;const retainerNodeOrdinal=retainerNodeIndex/nodeFieldCount;const retainerNodeFlag=!flags||(flags[retainerNodeOrdinal]&flag);if(retainerNodeIndex!==rootNodeIndex&&nodeFlag&&!retainerNodeFlag){continue;}
  1066. let retanerPostOrderIndex=nodeOrdinal2PostOrderIndex[retainerNodeOrdinal];if(dominators[retanerPostOrderIndex]!==noEntry){if(newDominatorIndex===noEntry){newDominatorIndex=retanerPostOrderIndex;}else{while(retanerPostOrderIndex!==newDominatorIndex){while(retanerPostOrderIndex<newDominatorIndex){retanerPostOrderIndex=dominators[retanerPostOrderIndex];}
  1067. while(newDominatorIndex<retanerPostOrderIndex){newDominatorIndex=dominators[newDominatorIndex];}}}
  1068. if(newDominatorIndex===rootPostOrderedIndex){break;}}}
  1069. if(orphanNode){newDominatorIndex=rootPostOrderedIndex;}
  1070. if(newDominatorIndex!==noEntry&&dominators[postOrderIndex]!==newDominatorIndex){dominators[postOrderIndex]=newDominatorIndex;changed=true;nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];const beginEdgeToNodeFieldIndex=firstEdgeIndexes[nodeOrdinal]+edgeToNodeOffset;const endEdgeToNodeFieldIndex=firstEdgeIndexes[nodeOrdinal+1];for(let toNodeFieldIndex=beginEdgeToNodeFieldIndex;toNodeFieldIndex<endEdgeToNodeFieldIndex;toNodeFieldIndex+=edgeFieldsCount){const childNodeOrdinal=containmentEdges[toNodeFieldIndex]/nodeFieldCount;affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]]=1;}}}}
  1071. const dominatorsTree=new Uint32Array(nodesCount);for(let postOrderIndex=0,l=dominators.length;postOrderIndex<l;++postOrderIndex){nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];dominatorsTree[nodeOrdinal]=postOrderIndex2NodeOrdinal[dominators[postOrderIndex]];}
  1072. return dominatorsTree;}
  1073. _calculateRetainedSizes(postOrderIndex2NodeOrdinal){const nodeCount=this.nodeCount;const nodes=this.nodes;const nodeSelfSizeOffset=this._nodeSelfSizeOffset;const nodeFieldCount=this._nodeFieldCount;const dominatorsTree=this._dominatorsTree;const retainedSizes=this._retainedSizes;for(let nodeOrdinal=0;nodeOrdinal<nodeCount;++nodeOrdinal){retainedSizes[nodeOrdinal]=nodes[nodeOrdinal*nodeFieldCount+nodeSelfSizeOffset];}
  1074. for(let postOrderIndex=0;postOrderIndex<nodeCount-1;++postOrderIndex){const nodeOrdinal=postOrderIndex2NodeOrdinal[postOrderIndex];const dominatorOrdinal=dominatorsTree[nodeOrdinal];retainedSizes[dominatorOrdinal]+=retainedSizes[nodeOrdinal];}}
  1075. _buildDominatedNodes(){const indexArray=this._firstDominatedNodeIndex;const dominatedNodes=this._dominatedNodes;const nodeFieldCount=this._nodeFieldCount;const dominatorsTree=this._dominatorsTree;let fromNodeOrdinal=0;let toNodeOrdinal=this.nodeCount;const rootNodeOrdinal=this._rootNodeIndex/nodeFieldCount;if(rootNodeOrdinal===fromNodeOrdinal){fromNodeOrdinal=1;}else if(rootNodeOrdinal===toNodeOrdinal-1){toNodeOrdinal=toNodeOrdinal-1;}else{throw new Error('Root node is expected to be either first or last');}
  1076. for(let nodeOrdinal=fromNodeOrdinal;nodeOrdinal<toNodeOrdinal;++nodeOrdinal){++indexArray[dominatorsTree[nodeOrdinal]];}
  1077. let firstDominatedNodeIndex=0;for(let i=0,l=this.nodeCount;i<l;++i){const dominatedCount=dominatedNodes[firstDominatedNodeIndex]=indexArray[i];indexArray[i]=firstDominatedNodeIndex;firstDominatedNodeIndex+=dominatedCount;}
  1078. indexArray[this.nodeCount]=dominatedNodes.length;for(let nodeOrdinal=fromNodeOrdinal;nodeOrdinal<toNodeOrdinal;++nodeOrdinal){const dominatorOrdinal=dominatorsTree[nodeOrdinal];let dominatedRefIndex=indexArray[dominatorOrdinal];dominatedRefIndex+=(--dominatedNodes[dominatedRefIndex]);dominatedNodes[dominatedRefIndex]=nodeOrdinal*nodeFieldCount;}}
  1079. _buildSamples(){const samples=this._rawSamples;if(!samples||!samples.length){return;}
  1080. const sampleCount=samples.length/2;const sizeForRange=new Array(sampleCount);const timestamps=new Array(sampleCount);const lastAssignedIds=new Array(sampleCount);const timestampOffset=this._metaNode.sample_fields.indexOf('timestamp_us');const lastAssignedIdOffset=this._metaNode.sample_fields.indexOf('last_assigned_id');for(let i=0;i<sampleCount;i++){sizeForRange[i]=0;timestamps[i]=(samples[2*i+timestampOffset])/1000;lastAssignedIds[i]=samples[2*i+lastAssignedIdOffset];}
  1081. const nodes=this.nodes;const nodesLength=nodes.length;const nodeFieldCount=this._nodeFieldCount;const node=this.rootNode();for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){node.nodeIndex=nodeIndex;const nodeId=node.id();if(nodeId%2===0){continue;}
  1082. const rangeIndex=lastAssignedIds.lowerBound(nodeId);if(rangeIndex===sampleCount){continue;}
  1083. sizeForRange[rangeIndex]+=node.selfSize();}
  1084. this._samples=new HeapSnapshotModel.Samples(timestamps,lastAssignedIds,sizeForRange);}
  1085. _buildLocationMap(){const map=new Map();const locations=this._locations;for(let i=0;i<locations.length;i+=this._locationFieldCount){const nodeIndex=locations[i+this._locationIndexOffset];const scriptId=locations[i+this._locationScriptIdOffset];const line=locations[i+this._locationLineOffset];const col=locations[i+this._locationColumnOffset];map.set(nodeIndex,new HeapSnapshotModel.Location(scriptId,line,col));}
  1086. this._locationMap=map;}
  1087. getLocation(nodeIndex){return this._locationMap.get(nodeIndex)||null;}
  1088. getSamples(){return this._samples;}
  1089. calculateFlags(){throw new Error('Not implemented');}
  1090. calculateStatistics(){throw new Error('Not implemented');}
  1091. userObjectsMapAndFlag(){throw new Error('Not implemented');}
  1092. calculateSnapshotDiff(baseSnapshotId,baseSnapshotAggregates){let snapshotDiff=this._snapshotDiffs[baseSnapshotId];if(snapshotDiff){return snapshotDiff;}
  1093. snapshotDiff={};const aggregates=this.aggregates(true,'allObjects');for(const className in baseSnapshotAggregates){const baseAggregate=baseSnapshotAggregates[className];const diff=this._calculateDiffForClass(baseAggregate,aggregates[className]);if(diff){snapshotDiff[className]=diff;}}
  1094. const emptyBaseAggregate=new HeapSnapshotModel.AggregateForDiff();for(const className in aggregates){if(className in baseSnapshotAggregates){continue;}
  1095. snapshotDiff[className]=this._calculateDiffForClass(emptyBaseAggregate,aggregates[className]);}
  1096. this._snapshotDiffs[baseSnapshotId]=snapshotDiff;return snapshotDiff;}
  1097. _calculateDiffForClass(baseAggregate,aggregate){const baseIds=baseAggregate.ids;const baseIndexes=baseAggregate.indexes;const baseSelfSizes=baseAggregate.selfSizes;const indexes=aggregate?aggregate.idxs:[];let i=0;let j=0;const l=baseIds.length;const m=indexes.length;const diff=new HeapSnapshotModel.Diff();const nodeB=this.createNode(indexes[j]);while(i<l&&j<m){const nodeAId=baseIds[i];if(nodeAId<nodeB.id()){diff.deletedIndexes.push(baseIndexes[i]);diff.removedCount++;diff.removedSize+=baseSelfSizes[i];++i;}else if(nodeAId>nodeB.id()){diff.addedIndexes.push(indexes[j]);diff.addedCount++;diff.addedSize+=nodeB.selfSize();nodeB.nodeIndex=indexes[++j];}else{++i;nodeB.nodeIndex=indexes[++j];}}
  1098. while(i<l){diff.deletedIndexes.push(baseIndexes[i]);diff.removedCount++;diff.removedSize+=baseSelfSizes[i];++i;}
  1099. while(j<m){diff.addedIndexes.push(indexes[j]);diff.addedCount++;diff.addedSize+=nodeB.selfSize();nodeB.nodeIndex=indexes[++j];}
  1100. diff.countDelta=diff.addedCount-diff.removedCount;diff.sizeDelta=diff.addedSize-diff.removedSize;if(!diff.addedCount&&!diff.removedCount){return null;}
  1101. return diff;}
  1102. _nodeForSnapshotObjectId(snapshotObjectId){for(let it=this._allNodes();it.hasNext();it.next()){if(it.node.id()===snapshotObjectId){return it.node;}}
  1103. return null;}
  1104. nodeClassName(snapshotObjectId){const node=this._nodeForSnapshotObjectId(snapshotObjectId);if(node){return node.className();}
  1105. return null;}
  1106. idsOfObjectsWithName(name){const ids=[];for(let it=this._allNodes();it.hasNext();it.next()){if(it.item().name()===name){ids.push(it.item().id());}}
  1107. return ids;}
  1108. createEdgesProvider(nodeIndex){const node=this.createNode(nodeIndex);const filter=this.containmentEdgesFilter();const indexProvider=new HeapSnapshotEdgeIndexProvider(this);return new HeapSnapshotEdgesProvider(this,filter,node.edges(),indexProvider);}
  1109. createEdgesProviderForTest(nodeIndex,filter){const node=this.createNode(nodeIndex);const indexProvider=new HeapSnapshotEdgeIndexProvider(this);return new HeapSnapshotEdgesProvider(this,filter,node.edges(),indexProvider);}
  1110. retainingEdgesFilter(){return null;}
  1111. containmentEdgesFilter(){return null;}
  1112. createRetainingEdgesProvider(nodeIndex){const node=this.createNode(nodeIndex);const filter=this.retainingEdgesFilter();const indexProvider=new HeapSnapshotRetainerEdgeIndexProvider(this);return new HeapSnapshotEdgesProvider(this,filter,node.retainers(),indexProvider);}
  1113. createAddedNodesProvider(baseSnapshotId,className){const snapshotDiff=this._snapshotDiffs[baseSnapshotId];const diffForClass=snapshotDiff[className];return new HeapSnapshotNodesProvider(this,diffForClass.addedIndexes);}
  1114. createDeletedNodesProvider(nodeIndexes){return new HeapSnapshotNodesProvider(this,nodeIndexes);}
  1115. createNodesProviderForClass(className,nodeFilter){return new HeapSnapshotNodesProvider(this,this.aggregatesWithFilter(nodeFilter)[className].idxs);}
  1116. _maxJsNodeId(){const nodeFieldCount=this._nodeFieldCount;const nodes=this.nodes;const nodesLength=nodes.length;let id=0;for(let nodeIndex=this._nodeIdOffset;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){const nextId=nodes[nodeIndex];if(nextId%2===0){continue;}
  1117. if(id<nextId){id=nextId;}}
  1118. return id;}
  1119. updateStaticData(){return new HeapSnapshotModel.StaticData(this.nodeCount,this._rootNodeIndex,this.totalSize,this._maxJsNodeId());}}
  1120. const HeapSnapshotMetainfo=class{constructor(){this.node_fields=[];this.node_types=[];this.edge_fields=[];this.edge_types=[];this.trace_function_info_fields=[];this.trace_node_fields=[];this.sample_fields=[];this.type_strings={};}};class HeapSnapshotHeader{constructor(){this.title='';this.meta=new HeapSnapshotMetainfo();this.node_count=0;this.edge_count=0;this.trace_function_count=0;}}
  1121. class HeapSnapshotItemProvider{constructor(iterator,indexProvider){this._iterator=iterator;this._indexProvider=indexProvider;this._isEmpty=!iterator.hasNext();this._iterationOrder=null;this._currentComparator=null;this._sortedPrefixLength=0;this._sortedSuffixLength=0;}
  1122. _createIterationOrder(){if(this._iterationOrder){return;}
  1123. this._iterationOrder=[];for(let iterator=this._iterator;iterator.hasNext();iterator.next()){this._iterationOrder.push(iterator.item().itemIndex());}}
  1124. isEmpty(){return this._isEmpty;}
  1125. serializeItemsRange(begin,end){this._createIterationOrder();if(begin>end){throw new Error('Start position > end position: '+begin+' > '+end);}
  1126. if(end>this._iterationOrder.length){end=this._iterationOrder.length;}
  1127. if(this._sortedPrefixLength<end&&begin<this._iterationOrder.length-this._sortedSuffixLength){this.sort(this._currentComparator,this._sortedPrefixLength,this._iterationOrder.length-1-this._sortedSuffixLength,begin,end-1);if(begin<=this._sortedPrefixLength){this._sortedPrefixLength=end;}
  1128. if(end>=this._iterationOrder.length-this._sortedSuffixLength){this._sortedSuffixLength=this._iterationOrder.length-begin;}}
  1129. let position=begin;const count=end-begin;const result=new Array(count);for(let i=0;i<count;++i){const itemIndex=this._iterationOrder[position++];const item=this._indexProvider.itemForIndex(itemIndex);result[i]=item.serialize();}
  1130. return new HeapSnapshotModel.ItemsRange(begin,end,this._iterationOrder.length,result);}
  1131. sortAndRewind(comparator){this._currentComparator=comparator;this._sortedPrefixLength=0;this._sortedSuffixLength=0;}}
  1132. class HeapSnapshotEdgesProvider extends HeapSnapshotItemProvider{constructor(snapshot,filter,edgesIter,indexProvider){const iter=filter?new HeapSnapshotFilteredIterator(edgesIter,(filter)):edgesIter;super(iter,indexProvider);this.snapshot=snapshot;}
  1133. sort(comparator,leftBound,rightBound,windowLeft,windowRight){const fieldName1=comparator.fieldName1;const fieldName2=comparator.fieldName2;const ascending1=comparator.ascending1;const ascending2=comparator.ascending2;const edgeA=(this._iterator.item()).clone();const edgeB=edgeA.clone();const nodeA=this.snapshot.createNode();const nodeB=this.snapshot.createNode();function compareEdgeFieldName(ascending,indexA,indexB){edgeA.edgeIndex=indexA;edgeB.edgeIndex=indexB;if(edgeB.name()==='__proto__'){return-1;}
  1134. if(edgeA.name()==='__proto__'){return 1;}
  1135. const result=edgeA.hasStringName()===edgeB.hasStringName()?(edgeA.name()<edgeB.name()?-1:(edgeA.name()>edgeB.name()?1:0)):(edgeA.hasStringName()?-1:1);return ascending?result:-result;}
  1136. function compareNodeField(fieldName,ascending,indexA,indexB){edgeA.edgeIndex=indexA;nodeA.nodeIndex=edgeA.nodeIndex();const valueA=nodeA[fieldName]();edgeB.edgeIndex=indexB;nodeB.nodeIndex=edgeB.nodeIndex();const valueB=nodeB[fieldName]();const result=valueA<valueB?-1:(valueA>valueB?1:0);return ascending?result:-result;}
  1137. function compareEdgeAndNode(indexA,indexB){let result=compareEdgeFieldName(ascending1,indexA,indexB);if(result===0){result=compareNodeField(fieldName2,ascending2,indexA,indexB);}
  1138. if(result===0){return indexA-indexB;}
  1139. return result;}
  1140. function compareNodeAndEdge(indexA,indexB){let result=compareNodeField(fieldName1,ascending1,indexA,indexB);if(result===0){result=compareEdgeFieldName(ascending2,indexA,indexB);}
  1141. if(result===0){return indexA-indexB;}
  1142. return result;}
  1143. function compareNodeAndNode(indexA,indexB){let result=compareNodeField(fieldName1,ascending1,indexA,indexB);if(result===0){result=compareNodeField(fieldName2,ascending2,indexA,indexB);}
  1144. if(result===0){return indexA-indexB;}
  1145. return result;}
  1146. if(fieldName1==='!edgeName'){this._iterationOrder.sortRange(compareEdgeAndNode,leftBound,rightBound,windowLeft,windowRight);}else if(fieldName2==='!edgeName'){this._iterationOrder.sortRange(compareNodeAndEdge,leftBound,rightBound,windowLeft,windowRight);}else{this._iterationOrder.sortRange(compareNodeAndNode,leftBound,rightBound,windowLeft,windowRight);}}}
  1147. class HeapSnapshotNodesProvider extends HeapSnapshotItemProvider{constructor(snapshot,nodeIndexes){const indexProvider=new HeapSnapshotNodeIndexProvider(snapshot);const it=new HeapSnapshotIndexRangeIterator(indexProvider,nodeIndexes);super(it,indexProvider);this.snapshot=snapshot;}
  1148. nodePosition(snapshotObjectId){this._createIterationOrder();const node=this.snapshot.createNode();let i=0;for(;i<this._iterationOrder.length;i++){node.nodeIndex=this._iterationOrder[i];if(node.id()===snapshotObjectId){break;}}
  1149. if(i===this._iterationOrder.length){return-1;}
  1150. const targetNodeIndex=this._iterationOrder[i];let smallerCount=0;const compare=this._buildCompareFunction(this._currentComparator);for(let i=0;i<this._iterationOrder.length;i++){if(compare(this._iterationOrder[i],targetNodeIndex)<0){++smallerCount;}}
  1151. return smallerCount;}
  1152. _buildCompareFunction(comparator){const nodeA=this.snapshot.createNode();const nodeB=this.snapshot.createNode();const fieldAccessor1=nodeA[comparator.fieldName1];const fieldAccessor2=nodeA[comparator.fieldName2];const ascending1=comparator.ascending1?1:-1;const ascending2=comparator.ascending2?1:-1;function sortByNodeField(fieldAccessor,ascending){const valueA=fieldAccessor.call(nodeA);const valueB=fieldAccessor.call(nodeB);return valueA<valueB?-ascending:(valueA>valueB?ascending:0);}
  1153. function sortByComparator(indexA,indexB){nodeA.nodeIndex=indexA;nodeB.nodeIndex=indexB;let result=sortByNodeField(fieldAccessor1,ascending1);if(result===0){result=sortByNodeField(fieldAccessor2,ascending2);}
  1154. return result||indexA-indexB;}
  1155. return sortByComparator;}
  1156. sort(comparator,leftBound,rightBound,windowLeft,windowRight){this._iterationOrder.sortRange(this._buildCompareFunction(comparator),leftBound,rightBound,windowLeft,windowRight);}}
  1157. class JSHeapSnapshot extends HeapSnapshot{constructor(profile,progress){super(profile,progress);this._nodeFlags={canBeQueried:1,detachedDOMTreeNode:2,pageObject:4};this._lazyStringCache={};this.initialize();}
  1158. createNode(nodeIndex){return new JSHeapSnapshotNode(this,nodeIndex===undefined?-1:nodeIndex);}
  1159. createEdge(edgeIndex){return new JSHeapSnapshotEdge(this,edgeIndex);}
  1160. createRetainingEdge(retainerIndex){return new JSHeapSnapshotRetainerEdge(this,retainerIndex);}
  1161. containmentEdgesFilter(){return edge=>!edge.isInvisible();}
  1162. retainingEdgesFilter(){const containmentEdgesFilter=this.containmentEdgesFilter();function filter(edge){return containmentEdgesFilter(edge)&&!edge.node().isRoot()&&!edge.isWeak();}
  1163. return filter;}
  1164. calculateFlags(){this._flags=new Uint32Array(this.nodeCount);this._markDetachedDOMTreeNodes();this._markQueriableHeapObjects();this._markPageOwnedNodes();}
  1165. calculateDistances(){function filter(node,edge){if(node.isHidden()){return edge.name()!=='sloppy_function_map'||node.rawName()!=='system / NativeContext';}
  1166. if(node.isArray()){if(node.rawName()!=='(map descriptors)'){return true;}
  1167. const index=edge.name();return index<2||(index%3)!==1;}
  1168. return true;}
  1169. super.calculateDistances(filter);}
  1170. isUserRoot(node){return node.isUserRoot()||node.isDocumentDOMTreesRoot();}
  1171. userObjectsMapAndFlag(){return{map:this._flags,flag:this._nodeFlags.pageObject};}
  1172. _flagsOfNode(node){return this._flags[node.nodeIndex/this._nodeFieldCount];}
  1173. _markDetachedDOMTreeNodes(){const nodes=this.nodes;const nodesLength=nodes.length;const nodeFieldCount=this._nodeFieldCount;const nodeNativeType=this._nodeNativeType;const nodeTypeOffset=this._nodeTypeOffset;const flag=this._nodeFlags.detachedDOMTreeNode;const node=this.rootNode();for(let nodeIndex=0,ordinal=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount,ordinal++){const nodeType=nodes[nodeIndex+nodeTypeOffset];if(nodeType!==nodeNativeType){continue;}
  1174. node.nodeIndex=nodeIndex;if(node.name().startsWith('Detached ')){this._flags[ordinal]|=flag;}}}
  1175. _markQueriableHeapObjects(){const flag=this._nodeFlags.canBeQueried;const hiddenEdgeType=this._edgeHiddenType;const internalEdgeType=this._edgeInternalType;const invisibleEdgeType=this._edgeInvisibleType;const weakEdgeType=this._edgeWeakType;const edgeToNodeOffset=this._edgeToNodeOffset;const edgeTypeOffset=this._edgeTypeOffset;const edgeFieldsCount=this._edgeFieldsCount;const containmentEdges=this.containmentEdges;const nodeFieldCount=this._nodeFieldCount;const firstEdgeIndexes=this._firstEdgeIndexes;const flags=this._flags;const list=[];for(let iter=this.rootNode().edges();iter.hasNext();iter.next()){if(iter.edge.node().isUserRoot()){list.push(iter.edge.node().nodeIndex/nodeFieldCount);}}
  1176. while(list.length){const nodeOrdinal=list.pop();if(flags[nodeOrdinal]&flag){continue;}
  1177. flags[nodeOrdinal]|=flag;const beginEdgeIndex=firstEdgeIndexes[nodeOrdinal];const endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];for(let edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];const childNodeOrdinal=childNodeIndex/nodeFieldCount;if(flags[childNodeOrdinal]&flag){continue;}
  1178. const type=containmentEdges[edgeIndex+edgeTypeOffset];if(type===hiddenEdgeType||type===invisibleEdgeType||type===internalEdgeType||type===weakEdgeType){continue;}
  1179. list.push(childNodeOrdinal);}}}
  1180. _markPageOwnedNodes(){const edgeShortcutType=this._edgeShortcutType;const edgeElementType=this._edgeElementType;const edgeToNodeOffset=this._edgeToNodeOffset;const edgeTypeOffset=this._edgeTypeOffset;const edgeFieldsCount=this._edgeFieldsCount;const edgeWeakType=this._edgeWeakType;const firstEdgeIndexes=this._firstEdgeIndexes;const containmentEdges=this.containmentEdges;const nodeFieldCount=this._nodeFieldCount;const nodesCount=this.nodeCount;const flags=this._flags;const pageObjectFlag=this._nodeFlags.pageObject;const nodesToVisit=new Uint32Array(nodesCount);let nodesToVisitLength=0;const rootNodeOrdinal=this._rootNodeIndex/nodeFieldCount;const node=this.rootNode();for(let edgeIndex=firstEdgeIndexes[rootNodeOrdinal],endEdgeIndex=firstEdgeIndexes[rootNodeOrdinal+1];edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];const nodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];if(edgeType===edgeElementType){node.nodeIndex=nodeIndex;if(!node.isDocumentDOMTreesRoot()){continue;}}else if(edgeType!==edgeShortcutType){continue;}
  1181. const nodeOrdinal=nodeIndex/nodeFieldCount;nodesToVisit[nodesToVisitLength++]=nodeOrdinal;flags[nodeOrdinal]|=pageObjectFlag;}
  1182. while(nodesToVisitLength){const nodeOrdinal=nodesToVisit[--nodesToVisitLength];const beginEdgeIndex=firstEdgeIndexes[nodeOrdinal];const endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];for(let edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const childNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];const childNodeOrdinal=childNodeIndex/nodeFieldCount;if(flags[childNodeOrdinal]&pageObjectFlag){continue;}
  1183. const type=containmentEdges[edgeIndex+edgeTypeOffset];if(type===edgeWeakType){continue;}
  1184. nodesToVisit[nodesToVisitLength++]=childNodeOrdinal;flags[childNodeOrdinal]|=pageObjectFlag;}}}
  1185. calculateStatistics(){const nodeFieldCount=this._nodeFieldCount;const nodes=this.nodes;const nodesLength=nodes.length;const nodeTypeOffset=this._nodeTypeOffset;const nodeSizeOffset=this._nodeSelfSizeOffset;const nodeNativeType=this._nodeNativeType;const nodeCodeType=this._nodeCodeType;const nodeConsStringType=this._nodeConsStringType;const nodeSlicedStringType=this._nodeSlicedStringType;const distances=this._nodeDistances;let sizeNative=0;let sizeCode=0;let sizeStrings=0;let sizeJSArrays=0;let sizeSystem=0;const node=this.rootNode();for(let nodeIndex=0;nodeIndex<nodesLength;nodeIndex+=nodeFieldCount){const nodeSize=nodes[nodeIndex+nodeSizeOffset];const ordinal=nodeIndex/nodeFieldCount;if(distances[ordinal]>=HeapSnapshotModel.baseSystemDistance){sizeSystem+=nodeSize;continue;}
  1186. const nodeType=nodes[nodeIndex+nodeTypeOffset];node.nodeIndex=nodeIndex;if(nodeType===nodeNativeType){sizeNative+=nodeSize;}else if(nodeType===nodeCodeType){sizeCode+=nodeSize;}else if(nodeType===nodeConsStringType||nodeType===nodeSlicedStringType||node.type()==='string'){sizeStrings+=nodeSize;}else if(node.name()==='Array'){sizeJSArrays+=this._calculateArraySize(node);}}
  1187. this._statistics=new HeapSnapshotModel.Statistics();this._statistics.total=this.totalSize;this._statistics.v8heap=this.totalSize-sizeNative;this._statistics.native=sizeNative;this._statistics.code=sizeCode;this._statistics.jsArrays=sizeJSArrays;this._statistics.strings=sizeStrings;this._statistics.system=sizeSystem;}
  1188. _calculateArraySize(node){let size=node.selfSize();const beginEdgeIndex=node.edgeIndexesStart();const endEdgeIndex=node.edgeIndexesEnd();const containmentEdges=this.containmentEdges;const strings=this.strings;const edgeToNodeOffset=this._edgeToNodeOffset;const edgeTypeOffset=this._edgeTypeOffset;const edgeNameOffset=this._edgeNameOffset;const edgeFieldsCount=this._edgeFieldsCount;const edgeInternalType=this._edgeInternalType;for(let edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex;edgeIndex+=edgeFieldsCount){const edgeType=containmentEdges[edgeIndex+edgeTypeOffset];if(edgeType!==edgeInternalType){continue;}
  1189. const edgeName=strings[containmentEdges[edgeIndex+edgeNameOffset]];if(edgeName!=='elements'){continue;}
  1190. const elementsNodeIndex=containmentEdges[edgeIndex+edgeToNodeOffset];node.nodeIndex=elementsNodeIndex;if(node.retainersCount()===1){size+=node.selfSize();}
  1191. break;}
  1192. return size;}
  1193. getStatistics(){return this._statistics;}}
  1194. class JSHeapSnapshotNode extends HeapSnapshotNode{constructor(snapshot,nodeIndex){super(snapshot,nodeIndex);}
  1195. canBeQueried(){const flags=this._snapshot._flagsOfNode(this);return!!(flags&this._snapshot._nodeFlags.canBeQueried);}
  1196. rawName(){return super.name();}
  1197. name(){const snapshot=this._snapshot;if(this.rawType()===snapshot._nodeConsStringType){let string=snapshot._lazyStringCache[this.nodeIndex];if(typeof string==='undefined'){string=this._consStringName();snapshot._lazyStringCache[this.nodeIndex]=string;}
  1198. return string;}
  1199. return this.rawName();}
  1200. _consStringName(){const snapshot=this._snapshot;const consStringType=snapshot._nodeConsStringType;const edgeInternalType=snapshot._edgeInternalType;const edgeFieldsCount=snapshot._edgeFieldsCount;const edgeToNodeOffset=snapshot._edgeToNodeOffset;const edgeTypeOffset=snapshot._edgeTypeOffset;const edgeNameOffset=snapshot._edgeNameOffset;const strings=snapshot.strings;const edges=snapshot.containmentEdges;const firstEdgeIndexes=snapshot._firstEdgeIndexes;const nodeFieldCount=snapshot._nodeFieldCount;const nodeTypeOffset=snapshot._nodeTypeOffset;const nodeNameOffset=snapshot._nodeNameOffset;const nodes=snapshot.nodes;const nodesStack=[];nodesStack.push(this.nodeIndex);let name='';while(nodesStack.length&&name.length<1024){const nodeIndex=nodesStack.pop();if(nodes[nodeIndex+nodeTypeOffset]!==consStringType){name+=strings[nodes[nodeIndex+nodeNameOffset]];continue;}
  1201. const nodeOrdinal=nodeIndex/nodeFieldCount;const beginEdgeIndex=firstEdgeIndexes[nodeOrdinal];const endEdgeIndex=firstEdgeIndexes[nodeOrdinal+1];let firstNodeIndex=0;let secondNodeIndex=0;for(let edgeIndex=beginEdgeIndex;edgeIndex<endEdgeIndex&&(!firstNodeIndex||!secondNodeIndex);edgeIndex+=edgeFieldsCount){const edgeType=edges[edgeIndex+edgeTypeOffset];if(edgeType===edgeInternalType){const edgeName=strings[edges[edgeIndex+edgeNameOffset]];if(edgeName==='first'){firstNodeIndex=edges[edgeIndex+edgeToNodeOffset];}else if(edgeName==='second'){secondNodeIndex=edges[edgeIndex+edgeToNodeOffset];}}}
  1202. nodesStack.push(secondNodeIndex);nodesStack.push(firstNodeIndex);}
  1203. return name;}
  1204. className(){const type=this.type();switch(type){case'hidden':return'(system)';case'object':case'native':return this.name();case'code':return'(compiled code)';default:return'('+type+')';}}
  1205. classIndex(){const snapshot=this._snapshot;const nodes=snapshot.nodes;const type=nodes[this.nodeIndex+snapshot._nodeTypeOffset];if(type===snapshot._nodeObjectType||type===snapshot._nodeNativeType){return nodes[this.nodeIndex+snapshot._nodeNameOffset];}
  1206. return-1-type;}
  1207. id(){const snapshot=this._snapshot;return snapshot.nodes[this.nodeIndex+snapshot._nodeIdOffset];}
  1208. isHidden(){return this.rawType()===this._snapshot._nodeHiddenType;}
  1209. isArray(){return this.rawType()===this._snapshot._nodeArrayType;}
  1210. isSynthetic(){return this.rawType()===this._snapshot._nodeSyntheticType;}
  1211. isUserRoot(){return!this.isSynthetic();}
  1212. isDocumentDOMTreesRoot(){return this.isSynthetic()&&this.name()==='(Document DOM trees)';}
  1213. serialize(){const result=super.serialize();const flags=this._snapshot._flagsOfNode(this);if(flags&this._snapshot._nodeFlags.canBeQueried){result.canBeQueried=true;}
  1214. if(flags&this._snapshot._nodeFlags.detachedDOMTreeNode){result.detachedDOMTreeNode=true;}
  1215. return result;}}
  1216. class JSHeapSnapshotEdge extends HeapSnapshotEdge{constructor(snapshot,edgeIndex){super(snapshot,edgeIndex);}
  1217. clone(){const snapshot=(this._snapshot);return new JSHeapSnapshotEdge(snapshot,this.edgeIndex);}
  1218. hasStringName(){if(!this.isShortcut()){return this._hasStringName();}
  1219. return isNaN(parseInt(this._name(),10));}
  1220. isElement(){return this.rawType()===this._snapshot._edgeElementType;}
  1221. isHidden(){return this.rawType()===this._snapshot._edgeHiddenType;}
  1222. isWeak(){return this.rawType()===this._snapshot._edgeWeakType;}
  1223. isInternal(){return this.rawType()===this._snapshot._edgeInternalType;}
  1224. isInvisible(){return this.rawType()===this._snapshot._edgeInvisibleType;}
  1225. isShortcut(){return this.rawType()===this._snapshot._edgeShortcutType;}
  1226. name(){const name=this._name();if(!this.isShortcut()){return String(name);}
  1227. const numName=parseInt(name,10);return String(isNaN(numName)?name:numName);}
  1228. toString(){const name=this.name();switch(this.type()){case'context':return'->'+name;case'element':return'['+name+']';case'weak':return'[['+name+']]';case'property':return name.indexOf(' ')===-1?'.'+name:'["'+name+'"]';case'shortcut':if(typeof name==='string'){return name.indexOf(' ')===-1?'.'+name:'["'+name+'"]';}else{return'['+name+']';}
  1229. case'internal':case'hidden':case'invisible':return'{'+name+'}';}
  1230. return'?'+name+'?';}
  1231. _hasStringName(){const type=this.rawType();const snapshot=this._snapshot;return type!==snapshot._edgeElementType&&type!==snapshot._edgeHiddenType;}
  1232. _name(){return this._hasStringName()?this._snapshot.strings[this._nameOrIndex()]:this._nameOrIndex();}
  1233. _nameOrIndex(){return this._edges[this.edgeIndex+this._snapshot._edgeNameOffset];}
  1234. rawType(){return this._edges[this.edgeIndex+this._snapshot._edgeTypeOffset];}}
  1235. class JSHeapSnapshotRetainerEdge extends HeapSnapshotRetainerEdge{constructor(snapshot,retainerIndex){super(snapshot,retainerIndex);}
  1236. clone(){const snapshot=(this._snapshot);return new JSHeapSnapshotRetainerEdge(snapshot,this.retainerIndex());}
  1237. isHidden(){return this._edge().isHidden();}
  1238. isInternal(){return this._edge().isInternal();}
  1239. isInvisible(){return this._edge().isInvisible();}
  1240. isShortcut(){return this._edge().isShortcut();}
  1241. isWeak(){return this._edge().isWeak();}}
  1242. (function disableLoggingForTest(){if(self.Root&&self.Root.Runtime&&Root.Runtime.queryParam('test')){console.warn=()=>undefined;}})();self.HeapSnapshotWorker=self.HeapSnapshotWorker||{};HeapSnapshotWorker=HeapSnapshotWorker||{};HeapSnapshotWorker.HeapSnapshotItem=HeapSnapshotItem;HeapSnapshotWorker.HeapSnapshotEdge=HeapSnapshotEdge;HeapSnapshotWorker.HeapSnapshotItemIterator=HeapSnapshotItemIterator;HeapSnapshotWorker.HeapSnapshotItemIndexProvider=HeapSnapshotItemIndexProvider;HeapSnapshotWorker.HeapSnapshotNodeIndexProvider=HeapSnapshotNodeIndexProvider;HeapSnapshotWorker.HeapSnapshotEdgeIndexProvider=HeapSnapshotEdgeIndexProvider;HeapSnapshotWorker.HeapSnapshotRetainerEdgeIndexProvider=HeapSnapshotRetainerEdgeIndexProvider;HeapSnapshotWorker.HeapSnapshotEdgeIterator=HeapSnapshotEdgeIterator;HeapSnapshotWorker.HeapSnapshotRetainerEdge=HeapSnapshotRetainerEdge;HeapSnapshotWorker.HeapSnapshotRetainerEdgeIterator=HeapSnapshotRetainerEdgeIterator;HeapSnapshotWorker.HeapSnapshotNode=HeapSnapshotNode;HeapSnapshotWorker.HeapSnapshotNodeIterator=HeapSnapshotNodeIterator;HeapSnapshotWorker.HeapSnapshotIndexRangeIterator=HeapSnapshotIndexRangeIterator;HeapSnapshotWorker.HeapSnapshotFilteredIterator=HeapSnapshotFilteredIterator;HeapSnapshotWorker.HeapSnapshotProgress=HeapSnapshotProgress;HeapSnapshotWorker.HeapSnapshotProblemReport=HeapSnapshotProblemReport;HeapSnapshotWorker.HeapSnapshot=HeapSnapshot;HeapSnapshotWorker.HeapSnapshotHeader=HeapSnapshotHeader;HeapSnapshotWorker.HeapSnapshotItemProvider=HeapSnapshotItemProvider;HeapSnapshotWorker.HeapSnapshotEdgesProvider=HeapSnapshotEdgesProvider;HeapSnapshotWorker.HeapSnapshotNodesProvider=HeapSnapshotNodesProvider;HeapSnapshotWorker.JSHeapSnapshot=JSHeapSnapshot;HeapSnapshotWorker.JSHeapSnapshotNode=JSHeapSnapshotNode;HeapSnapshotWorker.JSHeapSnapshotEdge=JSHeapSnapshotEdge;HeapSnapshotWorker.JSHeapSnapshotRetainerEdge=JSHeapSnapshotRetainerEdge;HeapSnapshotWorker.HeapSnapshot.AggregatedInfo;class HeapSnapshotLoader{constructor(dispatcher){this._reset();this._progress=new HeapSnapshotWorker.HeapSnapshotProgress(dispatcher);this._buffer='';this._dataCallback=null;this._done=false;this._parseInput();}
  1243. dispose(){this._reset();}
  1244. _reset(){this._json='';this._snapshot={};}
  1245. close(){this._done=true;if(this._dataCallback){this._dataCallback('');}}
  1246. buildSnapshot(){this._progress.updateStatus(ls`Processing snapshot\u2026`);const result=new HeapSnapshotWorker.JSHeapSnapshot(this._snapshot,this._progress);this._reset();return result;}
  1247. _parseUintArray(){let index=0;const char0='0'.charCodeAt(0);const char9='9'.charCodeAt(0);const closingBracket=']'.charCodeAt(0);const length=this._json.length;while(true){while(index<length){const code=this._json.charCodeAt(index);if(char0<=code&&code<=char9){break;}else if(code===closingBracket){this._json=this._json.slice(index+1);return false;}
  1248. ++index;}
  1249. if(index===length){this._json='';return true;}
  1250. let nextNumber=0;const startIndex=index;while(index<length){const code=this._json.charCodeAt(index);if(char0>code||code>char9){break;}
  1251. nextNumber*=10;nextNumber+=(code-char0);++index;}
  1252. if(index===length){this._json=this._json.slice(startIndex);return true;}
  1253. this._array[this._arrayIndex++]=nextNumber;}}
  1254. _parseStringsArray(){this._progress.updateStatus(ls`Parsing strings\u2026`);const closingBracketIndex=this._json.lastIndexOf(']');if(closingBracketIndex===-1){throw new Error('Incomplete JSON');}
  1255. this._json=this._json.slice(0,closingBracketIndex+1);this._snapshot.strings=JSON.parse(this._json);}
  1256. write(chunk){this._buffer+=chunk;if(!this._dataCallback){return;}
  1257. this._dataCallback(this._buffer);this._dataCallback=null;this._buffer='';}
  1258. _fetchChunk(){return this._done?Promise.resolve(this._buffer):new Promise(r=>this._dataCallback=r);}
  1259. async _findToken(token,startIndex){while(true){const pos=this._json.indexOf(token,startIndex||0);if(pos!==-1){return pos;}
  1260. startIndex=this._json.length-token.length+1;this._json+=await this._fetchChunk();}}
  1261. async _parseArray(name,title,length){const nameIndex=await this._findToken(name);const bracketIndex=await this._findToken('[',nameIndex);this._json=this._json.slice(bracketIndex+1);this._array=length?new Uint32Array(length):[];this._arrayIndex=0;while(this._parseUintArray()){this._progress.updateProgress(title,this._arrayIndex,this._array.length);this._json+=await this._fetchChunk();}
  1262. const result=this._array;this._array=null;return result;}
  1263. async _parseInput(){const snapshotToken='"snapshot"';const snapshotTokenIndex=await this._findToken(snapshotToken);if(snapshotTokenIndex===-1){throw new Error('Snapshot token not found');}
  1264. this._progress.updateStatus(ls`Loading snapshot info\u2026`);const json=this._json.slice(snapshotTokenIndex+snapshotToken.length+1);this._jsonTokenizer=new TextUtils.BalancedJSONTokenizer(metaJSON=>{this._json=this._jsonTokenizer.remainder();this._jsonTokenizer=null;this._snapshot.snapshot=(JSON.parse(metaJSON));});this._jsonTokenizer.write(json);while(this._jsonTokenizer){this._jsonTokenizer.write(await this._fetchChunk());}
  1265. this._snapshot.nodes=await this._parseArray('"nodes"',ls`Loading nodes\u2026 %d%%`,this._snapshot.snapshot.meta.node_fields.length*this._snapshot.snapshot.node_count);this._snapshot.edges=await this._parseArray('"edges"',ls`Loading edges\u2026 %d%%`,this._snapshot.snapshot.meta.edge_fields.length*this._snapshot.snapshot.edge_count);if(this._snapshot.snapshot.trace_function_count){this._snapshot.trace_function_infos=await this._parseArray('"trace_function_infos"',ls`Loading allocation traces\u2026 %d%%`,this._snapshot.snapshot.meta.trace_function_info_fields.length*this._snapshot.snapshot.trace_function_count);const thisTokenEndIndex=await this._findToken(':');const nextTokenIndex=await this._findToken('"',thisTokenEndIndex);const openBracketIndex=this._json.indexOf('[');const closeBracketIndex=this._json.lastIndexOf(']',nextTokenIndex);this._snapshot.trace_tree=JSON.parse(this._json.substring(openBracketIndex,closeBracketIndex+1));this._json=this._json.slice(closeBracketIndex+1);}
  1266. if(this._snapshot.snapshot.meta.sample_fields){this._snapshot.samples=await this._parseArray('"samples"',ls`Loading samples\u2026`);}
  1267. if(this._snapshot.snapshot.meta['location_fields']){this._snapshot.locations=await this._parseArray('"locations"',ls`Loading locations\u2026`);}else{this._snapshot.locations=[];}
  1268. this._progress.updateStatus(ls`Loading strings\u2026`);const stringsTokenIndex=await this._findToken('"strings"');const bracketIndex=await this._findToken('[',stringsTokenIndex);this._json=this._json.slice(bracketIndex);while(!this._done){this._json+=await this._fetchChunk();}
  1269. this._parseStringsArray();}}
  1270. self.HeapSnapshotWorker=self.HeapSnapshotWorker||{};HeapSnapshotWorker=HeapSnapshotWorker||{};HeapSnapshotWorker.HeapSnapshotLoader=HeapSnapshotLoader;class HeapSnapshotWorkerDispatcher{constructor(globalObject,postMessage){this._objects=[];this._global=globalObject;this._postMessage=postMessage;}
  1271. _findFunction(name){const path=name.split('.');let result=this._global;for(let i=0;i<path.length;++i){result=result[path[i]];}
  1272. return result;}
  1273. sendEvent(name,data){this._postMessage({eventName:name,data:data});}
  1274. dispatchMessage(event){const data=(event.data);const response={callId:data.callId};try{switch(data.disposition){case'create':const constructorFunction=this._findFunction(data.methodName);this._objects[data.objectId]=new constructorFunction(this);break;case'dispose':delete this._objects[data.objectId];break;case'getter':{const object=this._objects[data.objectId];const result=object[data.methodName];response.result=result;break;}
  1275. case'factory':{const object=this._objects[data.objectId];const result=object[data.methodName].apply(object,data.methodArguments);if(result){this._objects[data.newObjectId]=result;}
  1276. response.result=!!result;break;}
  1277. case'method':{const object=this._objects[data.objectId];response.result=object[data.methodName].apply(object,data.methodArguments);break;}
  1278. case'evaluateForTest':try{response.result=self.eval(data.source);}catch(e){response.result=e.toString();}
  1279. break;}}catch(e){response.error=e.toString();response.errorCallStack=e.stack;if(data.methodName){response.errorMethodName=data.methodName;}}
  1280. this._postMessage(response);}}
  1281. self.HeapSnapshotWorker=self.HeapSnapshotWorker||{};HeapSnapshotWorker=HeapSnapshotWorker||{};HeapSnapshotWorker.HeapSnapshotWorkerDispatcher=HeapSnapshotWorkerDispatcher;function postMessageWrapper(message){postMessage(message);}
  1282. const dispatcher=new HeapSnapshotWorker.HeapSnapshotWorkerDispatcher(self,postMessageWrapper);function installMessageEventListener(listener){self.addEventListener('message',listener,false);}
  1283. installMessageEventListener(dispatcher.dispatchMessage.bind(dispatcher));if(!self.Root||!self.Root.Runtime){self.importScripts('Runtime.js');}
  1284. Root.Runtime.startWorker('heap_snapshot_worker');}());;