/*! For license information please see extension.js.LICENSE.txt */ (()=>{var __webpack_modules__={60592:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createCellFrom=t.cloneCell=t.generateInteractiveCode=t.createCodeCell=t.createErrorOutputFromFailureInfo=t.createErrorOutput=t.createMarkdownCell=t.uncommentMagicCommands=void 0;const r=n(50361);n(30895);const i=n(44007);function o(e){return/^#\s*!/.test(e)?/^#\s*!\s*%%?/.test(e)?e.replace(/^#\s*!\s*/,""):e.replace(/^#\s*/,""):e}function s(e){var t,n,i;const o=r(e),s=Array.isArray(o.source)||"string"==typeof o.source?o.source:"";switch(e.cell_type){case"code":return{cell_type:"code",metadata:null!==(t=o.metadata)&&void 0!==t?t:{},execution_count:"number"==typeof o.execution_count?o.execution_count:null,outputs:Array.isArray(o.outputs)?o.outputs:[],source:s};case"markdown":return{cell_type:"markdown",metadata:null!==(n=o.metadata)&&void 0!==n?n:{},source:s,attachments:o.attachments};case"raw":return{cell_type:"raw",metadata:null!==(i=o.metadata)&&void 0!==i?i:{},source:s,attachments:o.attachments};default:return o}}t.uncommentMagicCommands=o,t.createMarkdownCell=function(e,t=!1){return e=Array.isArray(e)?e:[e],{cell_type:"markdown",metadata:{},source:t?e:(0,i.generateMarkdownFromCodeLines)(e)}},t.createErrorOutput=function(e){return{output_type:"error",ename:e.name||e.message||"Error",evalue:e.message||e.name||"Error",traceback:(e.stack||"").splitLines()}},t.createErrorOutputFromFailureInfo=function(e){return{output_type:"error",ename:e.message||"Error",evalue:e.message||"Error",traceback:[]}},t.createCodeCell=function(e,t){const n="boolean"==typeof t&&t;return e=e||"",{cell_type:"code",execution_count:null,metadata:{},outputs:"boolean"==typeof t?[]:t||[],source:Array.isArray(e)?(0,i.appendLineFeed)(e,"\n",n?o:void 0):e}},t.generateInteractiveCode=function(e,t,n){const r=e.splitLines({trim:!1,removeEmptyEntries:!1}),s=n.stripFirstMarkerNoConcat(r),a=(0,i.removeLinesFromFrontAndBackNoConcat)(s);return(0,i.appendLineFeed)(a,"\n",t.magicCommandsAsComments?o:void 0).join("")},t.cloneCell=s,t.createCellFrom=function(e,t){const n=e.cell_type===t?s(e):{source:e.source,cell_type:t,metadata:r(e.metadata)};switch(t){case"code":{const e=n;return e.execution_count=null,e.outputs=[],e}case"markdown":case"raw":return n;default:throw new Error(`Unsupported target type, ${t}`)}}},83474:(e,t)=>{"use strict";var n,r,i,o,s,a,c,l,u,d,p;Object.defineProperty(t,"__esModule",{value:!0}),t.defaultNotebookFormat=t.DataScienceStartupTime=t.JupyterCommands=t.CodeSnippets=t.Identifiers=t.VSCodeNativeTelemetry=t.NativeMouseCommandTelemetry=t.NativeKeyboardCommandTelemetry=t.Telemetry=t.RegExpValues=t.EditorContexts=t.CodeLensCommands=t.Commands=t.VSCodeKnownNotebookLanguages=t.jupyterLanguageToMonacoLanguageMapping=t.KnownKernelLanguageAliases=t.LanguagesSupportedByPythonkernel=t.PylanceExtension=t.PythonExtension=t.KernelInterruptDaemonModule=t.KernelLauncherDaemonModule=t.JupyterDaemonModule=t.JUPYTER_OUTPUT_CHANNEL=t.DefaultTheme=void 0,t.DefaultTheme="Default Light+",t.JUPYTER_OUTPUT_CHANNEL="JUPYTER_OUTPUT_CHANNEL",t.JupyterDaemonModule="vscode_datascience_helpers.jupyter_daemon",t.KernelLauncherDaemonModule="vscode_datascience_helpers.kernel_launcher_daemon",t.KernelInterruptDaemonModule="vscode_datascience_helpers.kernel_interrupt_daemon",t.PythonExtension="ms-python.python",t.PylanceExtension="ms-python.vscode-pylance",t.LanguagesSupportedByPythonkernel=["python","html","xml","javascript","markdown","latex","shellscript","bat","powershell","kusto","ruby","sql","perl","raw"],t.KnownKernelLanguageAliases=new Map([["qsharp","q#"],["csharp","c#"],["fsharp","f#"],["c++11","c++"],["c++12","c++"],["c++14","c++"]]),t.jupyterLanguageToMonacoLanguageMapping=new Map([["bash","shellscript"],["c#","csharp"],["f#","fsharp"],["q#","qsharp"],["c++11","c++"],["c++12","c++"],["c++14","c++"]]),t.VSCodeKnownNotebookLanguages=["python","r","julia","c++","c#","f#","q#","powershell","java","scala","haskell","bash","cling","rust","sas","sos"],function(e){e.RunAllCells="jupyter.runallcells",e.RunAllCellsAbove="jupyter.runallcellsabove",e.RunCellAndAllBelow="jupyter.runcellandallbelow",e.RunAllCellsAbovePalette="jupyter.runallcellsabove.palette",e.RunCellAndAllBelowPalette="jupyter.runcurrentcellandallbelow.palette",e.RunToLine="jupyter.runtoline",e.RunFromLine="jupyter.runfromline",e.RunCell="jupyter.runcell",e.RunCurrentCell="jupyter.runcurrentcell",e.RunCurrentCellAdvance="jupyter.runcurrentcelladvance",e.CreateNewInteractive="jupyter.createnewinteractive",e.ImportNotebook="jupyter.importnotebook",e.ImportNotebookFile="jupyter.importnotebookfile",e.SelectJupyterURI="jupyter.selectjupyteruri",e.SelectNativeJupyterUriFromToolBar="jupyter.selectNativeJupyterUriFromToolBar",e.SelectJupyterCommandLine="jupyter.selectjupytercommandline",e.ExportFileAsNotebook="jupyter.exportfileasnotebook",e.ExportFileAndOutputAsNotebook="jupyter.exportfileandoutputasnotebook",e.InterruptKernel="jupyter.interruptkernel",e.RestartKernel="jupyter.restartkernel",e.NotebookEditorUndoCells="jupyter.notebookeditor.undocells",e.NotebookEditorRedoCells="jupyter.notebookeditor.redocells",e.NotebookEditorRemoveAllCells="jupyter.notebookeditor.removeallcells",e.NotebookEditorInterruptKernel="jupyter.notebookeditor.interruptkernel",e.NotebookEditorRestartKernel="jupyter.notebookeditor.restartkernel",e.NotebookEditorRunAllCells="jupyter.notebookeditor.runallcells",e.NotebookEditorRunSelectedCell="jupyter.notebookeditor.runselectedcell",e.NotebookEditorAddCellBelow="jupyter.notebookeditor.addcellbelow",e.ExpandAllCells="jupyter.expandallcells",e.CollapseAllCells="jupyter.collapseallcells",e.ExportOutputAsNotebook="jupyter.exportoutputasnotebook",e.ExecSelectionInInteractiveWindow="jupyter.execSelectionInteractive",e.RunFileInInteractiveWindows="jupyter.runFileInteractive",e.DebugFileInInteractiveWindows="jupyter.debugFileInteractive",e.AddCellBelow="jupyter.addcellbelow",e.DebugCurrentCellPalette="jupyter.debugcurrentcell.palette",e.DebugCell="jupyter.debugcell",e.DebugStepOver="jupyter.debugstepover",e.DebugContinue="jupyter.debugcontinue",e.DebugStop="jupyter.debugstop",e.RunCurrentCellAndAddBelow="jupyter.runcurrentcellandaddbelow",e.InsertCellBelowPosition="jupyter.insertCellBelowPosition",e.InsertCellBelow="jupyter.insertCellBelow",e.InsertCellAbove="jupyter.insertCellAbove",e.DeleteCells="jupyter.deleteCells",e.SelectCell="jupyter.selectCell",e.SelectCellContents="jupyter.selectCellContents",e.ExtendSelectionByCellAbove="jupyter.extendSelectionByCellAbove",e.ExtendSelectionByCellBelow="jupyter.extendSelectionByCellBelow",e.MoveCellsUp="jupyter.moveCellsUp",e.MoveCellsDown="jupyter.moveCellsDown",e.ChangeCellToMarkdown="jupyter.changeCellToMarkdown",e.ChangeCellToCode="jupyter.changeCellToCode",e.GotoNextCellInFile="jupyter.gotoNextCellInFile",e.GotoPrevCellInFile="jupyter.gotoPrevCellInFile",e.ScrollToCell="jupyter.scrolltocell",e.CreateNewNotebook="jupyter.createnewnotebook",e.ViewJupyterOutput="jupyter.viewOutput",e.ExportAsPythonScript="jupyter.exportAsPythonScript",e.ExportToHTML="jupyter.exportToHTML",e.ExportToPDF="jupyter.exportToPDF",e.Export="jupyter.export",e.NativeNotebookExport="jupyter.notebookeditor.export",e.LatestExtension="jupyter.latestExtension",e.EnableLoadingWidgetsFrom3rdPartySource="jupyter.enableLoadingWidgetScriptsFromThirdPartySource",e.NotebookEditorExpandAllCells="jupyter.notebookeditor.expandallcells",e.NotebookEditorCollapseAllCells="jupyter.notebookeditor.collapseallcells",e.EnableDebugLogging="jupyter.enableDebugLogging",e.ResetLoggingLevel="jupyter.resetLoggingLevel",e.CreateGitHubIssue="jupyter.createGitHubIssue",e.SubmitGitHubIssue="jupyter.submitGitHubIssue",e.ShowDataViewer="jupyter.showDataViewer",e.RefreshDataViewer="jupyter.refreshDataViewer",e.ClearSavedJupyterUris="jupyter.clearSavedJupyterUris",e.OpenVariableView="jupyter.openVariableView",e.OpenOutlineView="jupyter.openOutlineView",e.InteractiveClearAll="jupyter.interactive.clearAllCells",e.InteractiveRemoveCell="jupyter.interactive.removeCell",e.InteractiveGoToCode="jupyter.interactive.goToCode",e.InteractiveCopyCell="jupyter.interactive.copyCell",e.InteractiveExportAsNotebook="jupyter.interactive.exportasnotebook",e.InteractiveExportAs="jupyter.interactive.exportas",e.DebugNotebook="jupyter.debugNotebook",e.RunByLine="jupyter.runByLine",e.RunAndDebugCell="jupyter.runAndDebugCell",e.RunByLineNext="jupyter.runByLineNext",e.RunByLineStop="jupyter.runByLineStop",e.ReplayPylanceLog="jupyter.replayPylanceLog",e.ReplayPylanceLogStep="jupyter.replayPylanceLogStep"}(n=t.Commands||(t.Commands={})),(p=t.CodeLensCommands||(t.CodeLensCommands={})).DefaultDesignLenses=[n.RunCurrentCell,n.RunAllCellsAbove,n.DebugCell],p.DefaultDebuggingLenses=[n.DebugContinue,n.DebugStop,n.DebugStepOver],p.DebuggerCommands=[n.DebugContinue,n.DebugStop,n.DebugStepOver],(d=t.EditorContexts||(t.EditorContexts={})).HasCodeCells="jupyter.hascodecells",d.HaveInteractiveCells="jupyter.haveinteractivecells",d.HaveRedoableCells="jupyter.haveredoablecells",d.HaveInteractive="jupyter.haveinteractive",d.IsInteractiveActive="jupyter.isinteractiveactive",d.OwnsSelection="jupyter.ownsSelection",d.HaveNativeCells="jupyter.havenativecells",d.HaveNativeRedoableCells="jupyter.havenativeredoablecells",d.HaveNative="jupyter.havenative",d.IsNativeActive="jupyter.isnativeactive",d.IsInteractiveOrNativeActive="jupyter.isinteractiveornativeactive",d.IsPythonOrNativeActive="jupyter.ispythonornativeactive",d.IsPythonOrInteractiveActive="jupyter.ispythonorinteractiveeactive",d.IsPythonOrInteractiveOrNativeActive="jupyter.ispythonorinteractiveornativeeactive",d.CanRestartNotebookKernel="jupyter.notebookeditor.canrestartNotebookkernel",d.CanInterruptNotebookKernel="jupyter.notebookeditor.canInterruptNotebookKernel",d.CanRestartInteractiveWindowKernel="jupyter.interactive.canRestartNotebookKernel",d.CanInterruptInteractiveWindowKernel="jupyter.interactive.canInterruptNotebookKernel",d.DebuggingInProgress="jupyter.notebookeditor.debuggingInProgress",d.RunByLineInProgress="jupyter.notebookeditor.runByLineInProgress",d.IsPythonNotebook="jupyter.ispythonnotebook",d.IsJupyterKernelSelected="jupyter.kernel.isjupyter",d.IsDataViewerActive="jupyter.dataViewerActive",d.HasNativeNotebookOrInteractiveWindowOpen="jupyter.hasNativeNotebookOrInteractiveWindowOpen",d.ZmqAvailable="jupyter.zmqavailable",d.ReplayLogLoaded="jupyter.replayLogLoaded",(u=t.RegExpValues||(t.RegExpValues={})).PythonCellMarker=/^(#\s*%%|#\s*\|#\s*In\[\d*?\]|#\s*In\[ \])/,u.PythonMarkdownCellMarker=/^(#\s*%%\s*\[markdown\]|#\s*\)/,u.UrlPatternRegEx="(?https?:\\/\\/)((\\(.+\\s+or\\s+(?.+)\\))|(?[^\\s]+))(?:.+)",u.HttpPattern=/https?:\/\//,u.ShapeSplitterRegEx=/.*,\s*(\d+).*/,u.SvgHeightRegex=/(\{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseForComments=t.generateMarkdownFromCodeLines=t.appendLineFeed=t.formatStreamText=t.stripComments=t.removeLinesFromFrontAndBack=t.removeLinesFromFrontAndBackNoConcat=t.splitMultilineString=t.concatMultilineString=void 0;const r=n(95063),i="'''",o='"""';function s(e){let t=e.length,n=-1;return e.forEach(((e,r)=>{e.trim()&&(t=r,n<0&&(n=r))})),n>=0?e.slice(n,t+1):[]}function a(e,t="\n",n){return e.map(((r,i)=>{const o=n?n(r):r;return i===e.length-1?`${o}`:`${o}${t}`}))}function c(e,t,n){let r,s,a=0;for(const c of e){const e=c.trim(),l=e.startsWith(i)?i:e.startsWith(o)?o:void 0,u=e.includes(i)?i:e.includes(o)?o:void 0;if(s)s===u&&(s=void 0),n(c,a);else if(r)r===l&&(r=void 0),r&&t(c,a);else if(u&&!l){const t=e.indexOf(u);s=e.lastIndexOf(u)!==t?void 0:u,n(c,a)}else if(l){const n=e.indexOf(l,3);r=n>=0?void 0:l,e.length>3&&t(e.slice(3,n>=0?n:void 0),a)}else e.startsWith("#")?t(e.slice(1),a):n(c,a);a+=1}}t.concatMultilineString=function(e){if(Array.isArray(e)){let t="";for(let n=0;n0){const e=t.split("\n");return e.map(((t,n)=>ne.length>0))}return[]},t.removeLinesFromFrontAndBackNoConcat=s,t.removeLinesFromFrontAndBack=function(e){return s(Array.isArray(e)?e:e.splitLines({trim:!1,removeEmptyEntries:!1})).join("\n")},t.stripComments=function(e){let t="";return c(e.splitLines({trim:!1,removeEmptyEntries:!1}),(e=>r.noop),(e=>t=t.concat(`${e}\n`))),t},t.formatStreamText=function(e){return function(e){for(e=e.replace(/\r+\n/gm,"\n");e.search(/\r[^$]/g)>-1;){var t=e.match(/^(.*)\r+/m)[1],n=e.match(/\r+(.*)$/m)[1];n+=t.slice(n.length,t.length),e=e.replace(/\r+.*$/m,"\r").replace(/^.*\r/m,n)}return e}(function(e){let t=e;do{t=(e=t).replace(/[^\n]\x08/gm,"")}while(t.lengtht.push(e)),(e=>(0,r.noop)())),t}(e.slice(e.length>1?1:0)))},t.parseForComments=c},18430:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isValidSliceExpression=t.validateSliceExpression=t.fullSliceExpression=t.preselectedSliceExpression=t.sliceRegEx=void 0;const r=n(55516);function i(e,n){if(e.startsWith("[")&&e.endsWith("]")){let i;const o=e.substring(1,e.length-1).split(",").map(((e,r)=>{var o;const s=t.sliceRegEx.exec(e);if((null===(o=null==s?void 0:s.groups)||void 0===o?void 0:o.Start)&&!s.groups.Stop){const e=parseInt(s.groups.Start),t=n[r];return(e>=0&&e>=t||e<0&&e<-t)&&(i={shapeIndex:r,value:e}),e}}));if(i){const{shapeIndex:e,value:t}=i,o=(0,r.getLocString)("DataScience.sliceIndexError","Index {0} out of range for axis {1} with {2} elements");return(0,r.format)(o,t.toString(),e.toString(),n[e].toString())}if(o&&o.length!==n.length){const e=(0,r.getLocString)("DataScience.sliceMismatchedAxesError","Expected {0} axes, got {1} in slice expression");return(0,r.format)(e,n.length.toString(),o.length.toString())}}return""}t.sliceRegEx=/^\s*((?-?\d+:)|(?-?:\d+)|(?:(?-?\d+)(?::(?-?\d+))?(?::(?-?\d+))?))\s*$/,t.preselectedSliceExpression=function(e){let t=e.length-2;return"["+e.map((()=>t>0?(t-=1,"0"):":")).join(", ")+"]"},t.fullSliceExpression=function(e){return"["+e.map((()=>":")).join(", ")+"]"},t.validateSliceExpression=i,t.isValidSliceExpression=function(e,t){return""===i(e,t)}},55516:(e,t)=>{"use strict";let n;Object.defineProperty(t,"__esModule",{value:!0}),t.format=t.storeLocStrings=t.getLocString=void 0,t.getLocString=function(e,t){return n&&n.hasOwnProperty(e)?n[e]:t},t.storeLocStrings=function(e){n=e},t.format=function(e,...t){return e.replace(/{(\d+)}/g,((e,n)=>void 0===t[n]?e:t[n]))}},44538:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.NotebookCellLanguageService=t.LastSavedNotebookCellLanguage=void 0;const o=n(86700),s=n(66828),a=n(98501),c=n(13395),l=n(97784),u=n(46318),d=n(71733),p=n(28735),h=n(72858),f=n(83474),m=n(93828),g=n(82232);t.LastSavedNotebookCellLanguage="DATASCIENCE.LAST_SAVED_CELL_LANGUAGE";let v=class{constructor(e,t,n,r){this.vscNotebook=e,this.disposables=t,this.globalMemento=n,this.pythonExtensionChecker=r}getPreferredLanguage(e){var t,n;const r=(null===(t=null==e?void 0:e.language_info)||void 0===t?void 0:t.name)||(null===(n=null==e?void 0:e.kernelspec)||void 0===n?void 0:n.language)||this.lastSavedNotebookCellLanguage,i=this.pythonExtensionChecker.isPythonExtensionInstalled?l.PYTHON_LANGUAGE:"plaintext";return(0,h.translateKernelLanguageToMonaco)(r||i)}async activate(){this.vscNotebook.onDidSaveNotebookDocument(this.onDidSaveNotebookDocument,this,this.disposables)}getSupportedLanguages(e){if((0,m.isPythonKernelConnection)(e))return f.LanguagesSupportedByPythonkernel;{const t=(0,h.translateKernelLanguageToMonaco)((0,m.getKernelConnectionLanguage)(e)||"");return t&&f.VSCodeKnownNotebookLanguages.includes(t)?[t]:[]}}get lastSavedNotebookCellLanguage(){return this.globalMemento.get(t.LastSavedNotebookCellLanguage)}async onDidSaveNotebookDocument(e){if(!(0,g.isJupyterNotebook)(e))return;const n=this.getLanguageOfFirstCodeCell(e);n&&n!==this.lastSavedNotebookCellLanguage&&await this.globalMemento.update(t.LastSavedNotebookCellLanguage,n)}getLanguageOfFirstCodeCell(e){var t;try{return(0,m.getLanguageInNotebookMetadata)((0,g.getNotebookMetadata)(e))||(null===(t=e.getCells().find((e=>e.kind===s.NotebookCellKind.Code)))||void 0===t?void 0:t.document.languageId)}catch(e){(0,u.traceWarning)("Failed to determine language of first cell",e)}}};r([(0,p.swallowExceptions)("Saving last saved cell language")],v.prototype,"onDidSaveNotebookDocument",null),v=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IVSCodeNotebook)),i(1,(0,o.inject)(d.IDisposableRegistry)),i(2,(0,o.inject)(d.IMemento)),i(2,(0,o.named)(d.GLOBAL_MEMENTO)),i(3,(0,o.inject)(a.IPythonExtensionChecker))],v),t.NotebookCellLanguageService=v},86044:(e,t,n)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.mapJupyterKind=void 0,n(30895),function(e){e[e.Method=0]="Method",e[e.Function=1]="Function",e[e.Constructor=2]="Constructor",e[e.Field=3]="Field",e[e.Variable=4]="Variable",e[e.Class=5]="Class",e[e.Struct=6]="Struct",e[e.Interface=7]="Interface",e[e.Module=8]="Module",e[e.Property=9]="Property",e[e.Event=10]="Event",e[e.Operator=11]="Operator",e[e.Unit=12]="Unit",e[e.Value=13]="Value",e[e.Constant=14]="Constant",e[e.Enum=15]="Enum",e[e.EnumMember=16]="EnumMember",e[e.Keyword=17]="Keyword",e[e.Text=18]="Text",e[e.Color=19]="Color",e[e.File=20]="File",e[e.Reference=21]="Reference",e[e.Customcolor=22]="Customcolor",e[e.Folder=23]="Folder",e[e.TypeParameter=24]="TypeParameter",e[e.Snippet=25]="Snippet"}(r||(r={})),t.mapJupyterKind=new Map([["method",r.Method],["function",r.Function],["constructor",r.Constructor],["field",r.Field],["variable",r.Variable],["class",r.Class],["struct",r.Struct],["interface",r.Interface],["module",r.Module],["property",r.Property],["event",r.Event],["operator",r.Operator],["unit",r.Unit],["value",r.Value],["constant",r.Constant],["enum",r.Enum],["enumMember",r.EnumMember],["keyword",r.Keyword],["text",r.Text],["color",r.Color],["file",r.File],["reference",r.Reference],["customcolor",r.Customcolor],["folder",r.Folder],["typeParameter",r.TypeParameter],["snippet",r.Snippet],["",r.Field]])},7753:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.NotebookCellBangInstallDiagnosticsProvider=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(97784),l=n(2687),u=n(71733),d=n(35952),p=n(73913),h=n(82232),f=d.DataScience.percentPipCondaInstallInsteadOfBang().format("pip"),m=d.DataScience.percentPipCondaInstallInsteadOfBang().format("conda"),g=d.DataScience.matplotlibWidgetInsteadOfOther(),v="Jupyter";let y=class{constructor(e,t,n){this.notebooks=e,this.documents=n,this.disposables=[],this.notebooksProcessed=new WeakMap,this.cellsToProcess=new Set,this.problems=s.languages.createDiagnosticCollection(v),this.disposables.push(this.problems),t.push(this)}dispose(){(0,l.disposeAllDisposables)(this.disposables),this.problems.dispose()}activate(){this.disposables.push(s.languages.registerCodeActionsProvider(c.PYTHON_LANGUAGE,this)),this.disposables.push(s.languages.registerHoverProvider(c.PYTHON_LANGUAGE,this)),this.documents.onDidChangeTextDocument((e=>{const t=(0,h.getAssociatedJupyterNotebook)(e.document);if(!t)return;const n=t.getCells().find((t=>t.document===e.document));n&&this.analyzeNotebookCell(n)}),this,this.disposables),this.notebooks.onDidCloseNotebookDocument((e=>{this.problems.delete(e.uri);const t=this.notebooksProcessed.get(e);this.notebooksProcessed.delete(e),t&&t.forEach(((e,t)=>this.problems.delete(s.Uri.parse(t))))}),this,this.disposables),this.notebooks.onDidOpenNotebookDocument((e=>this.analyzeNotebook(e)),this,this.disposables),this.notebooks.onDidChangeNotebookDocument((e=>{if("changeCells"===e.type){const t=this.notebooksProcessed.get(e.document);e.changes.forEach((e=>{e.deletedItems.forEach((e=>{null==t||t.delete(e.document.uri.toString())})),e.items.forEach((e=>this.queueCellForProcessing(e)))}))}}),this,this.disposables),this.notebooks.notebookDocuments.map((e=>this.analyzeNotebook(e)))}provideHover(e,t,n){const r=(0,h.getAssociatedJupyterNotebook)(e);if((null==r?void 0:r.notebookType)!==p.JupyterNotebookView)return;const i=this.problems.get(e.uri);if(!i)return;const o=i.find((e=>e.message===f||e.message===m));if(!o||!o.range.contains(t))return;const a=o.message===f?"pip":"conda";return new s.Hover(d.DataScience.pipCondaInstallHoverWarning().format(a,"https://aka.ms/jupyterCellMagicBangInstall"),o.range)}provideCodeActions(e,t,n,r){if(!(0,h.getAssociatedJupyterNotebook)(e))return[];const i=[];return n.diagnostics.forEach((t=>{switch(t.message){case f:i.push(this.createReplaceCodeAction(e,"pip",t));break;case m:i.push(this.createReplaceCodeAction(e,"conda",t));break;case g:i.push(this.createGotoWikiAction(e,s.Uri.parse("https://aka.ms/vscodejupytermatplotlibwidget"),t))}})),i}createReplaceCodeAction(e,t,n){const r=new s.CodeAction(d.DataScience.replacePipCondaInstallCodeAction().format(t),s.CodeActionKind.QuickFix);r.isPreferred=!0,r.diagnostics=[n];const i=new s.WorkspaceEdit;return i.replace(e.uri,new s.Range(n.range.start,new s.Position(n.range.start.line,n.range.start.character+1)),"%"),r.edit=i,r}createGotoWikiAction(e,t,n){const r=new s.CodeAction(d.DataScience.matplotlibWidgetCodeActionTitle(),s.CodeActionKind.QuickFix);return r.isPreferred=!0,r.diagnostics=[n],r.command={title:d.DataScience.matplotlibWidgetCodeActionTitle(),command:"vscode.open",arguments:[t]},r}analyzeNotebook(e){e.notebookType===p.JupyterNotebookView&&e.getCells().forEach(((e,t)=>t<100?this.queueCellForProcessing(e):void 0))}queueCellForProcessing(e){this.cellsToProcess.add(e),this.analyzeNotebookCells()}analyzeNotebookCells(){if(0===this.cellsToProcess.size)return;const e=this.cellsToProcess.values().next().value;this.cellsToProcess.delete(e),this.analyzeNotebookCell(e),setTimeout((()=>this.analyzeNotebookCells()),0)}analyzeNotebookCell(e){var t;if(e.kind!==s.NotebookCellKind.Code||e.document.languageId!==c.PYTHON_LANGUAGE||e.notebook.isClosed||e.document.isClosed)return;if((null===(t=this.notebooksProcessed.get(e.notebook))||void 0===t?void 0:t.get(e.document.uri.toString()))===e.document.version)return;this.problems.delete(e.document.uri);const n=this.notebooksProcessed.get(e.notebook)||new Map;n.set(e.document.uri.toString(),e.document.version),this.notebooksProcessed.set(e.notebook,n);for(let t=0;t=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.EmptyNotebookCellLanguageService=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(97784),l=n(46318),u=n(71733),d=n(95063),p=n(72858),h=n(52194),f=n(82232),m=n(24453);let g=class{constructor(e,t,n){this.notebook=e,this.disposables=t,this.notebookControllerManager=n}async activate(){this.notebookControllerManager.onNotebookControllerSelected(this.onDidChangeNotebookController,this,this.disposables)}async onDidChangeNotebookController(e){const t=e.notebook,n=e.controller.connection;if(!(0,f.isJupyterNotebook)(t))return;const r=this.notebook.notebookEditors.find((e=>e.document===t));if(!r)return;const i=t.getCells().filter((e=>e.kind===s.NotebookCellKind.Code&&0===e.document.getText().trim().length)),o=t.getCells().filter((e=>e.kind===s.NotebookCellKind.Code)).length;if(0===i.length||i.length!==o)return;let a;const u=n.kind;switch(n.kind){case"connectToLiveKernel":a=n.kernelModel.language;break;case"startUsingRemoteKernelSpec":case"startUsingLocalKernelSpec":a=n.kernelSpec.language;break;case"startUsingPythonInterpreter":a=c.PYTHON_LANGUAGE;break;default:return void(0,l.traceError)(`Unsupported kernel kind encountered ${u}`)}if(!a)return;const m=(0,p.translateKernelLanguageToMonaco)(a);(0,h.chainWithPendingUpdates)(r.document,(async()=>{await i.map((async e=>{if(m.toLowerCase()!==e.document.languageId)return s.languages.setTextDocumentLanguage(e.document,m).then(d.noop,d.noop)}))})).then(d.noop,d.noop)}};g=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IVSCodeNotebook)),i(1,(0,o.inject)(u.IDisposableRegistry)),i(2,(0,o.inject)(m.INotebookControllerManager))],g),t.EmptyNotebookCellLanguageService=g},2519:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileBasedCancellationStrategy=void 0;const r=n(6113),i=n(57147),o=n(22037),s=n(71017),a=n(52847);function c(e){return s.join(o.tmpdir(),"python-languageserver-cancellation",e)}function l(e,t){return s.join(c(e),`cancellation-${String(t)}.tmp`)}function u(e){try{e()}catch(e){}}class d{constructor(e){this.folderName=e;const t=c(e);u((()=>i.mkdirSync(t,{recursive:!0})))}sendCancellation(e,t){const n=l(this.folderName,t);u((()=>i.writeFileSync(n,"",{flag:"w"})))}cleanup(e){u((()=>i.unlinkSync(l(this.folderName,e))))}dispose(){const e=c(this.folderName);function t(e){const n=i.lstatSync(e);if(n)if(n.isDirectory()&&!n.isSymbolicLink()){for(const n of i.readdirSync(e))t(s.join(e,n));i.rmdirSync(e)}else i.unlinkSync(e)}u((()=>t(e)))}}t.FileBasedCancellationStrategy=class{constructor(){const e=(0,r.randomBytes)(21).toString("hex");this._sender=new d(e)}get receiver(){return a.CancellationReceiverStrategy.Message}get sender(){return this._sender}getCommandLineArguments(){return[`--cancellationReceive=file:${this._sender.folderName}`]}dispose(){this._sender.dispose()}}},2040:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.IntellisenseProvider=void 0;const o=n(86700),s=n(66828),a=n(98501),c=n(13395),l=n(71733),u=n(5448),d=n(48497),p=n(79262),h=n(82232),f=n(24453),m=n(46526);let g=class{constructor(e,t,n,r,i,o,s,a,c){this.disposables=e,this.notebookControllerManager=t,this.notebooks=n,this.interpreterService=r,this.workspaceService=i,this.extensionChecker=o,this.interactiveWindowProvider=s,this.configService=a,this.isPreRelease=c,this.servers=new Map,this.activeInterpreterCache=new Map,this.interpreterIdCache=new Map,this.knownControllers=new WeakMap}activate(){this.notebookControllerManager.onNotebookControllerSelected(this.controllerChanged,this,this.disposables),this.notebooks.onDidOpenNotebookDocument(this.openedNotebook,this,this.disposables),this.notebooks.onDidCloseNotebookDocument(this.closedNotebook,this,this.disposables),this.notebooks.notebookDocuments.forEach((e=>this.openedNotebook(e).ignoreErrors())),this.getActiveInterpreterSync(void 0),this.interpreterService.onDidChangeInterpreter(this.handleInterpreterChange,this,this.disposables),this.workspaceService.onDidChangeConfiguration(this.onDidChangeConfiguration,this,this.disposables)}async getLanguageClient(e){const t=this.notebookControllerManager.getSelectedNotebookController(e),n=t?t.connection.interpreter:await this.interpreterService.getActiveInterpreter(e.uri),r=n?this.getInterpreterIdFromCache(n):void 0,i=r?await this.servers.get(r):void 0;return null==i?void 0:i.client}handleInterpreterChange(){const e=[...this.activeInterpreterCache.keys()];this.activeInterpreterCache.clear(),e.forEach((e=>this.getActiveInterpreterSync(e)))}getActiveInterpreterSync(e){var t;if(!this.extensionChecker.isPythonExtensionInstalled)return;const n=(null===(t=this.workspaceService.getWorkspaceFolder(e?s.Uri.file(e):void 0))||void 0===t?void 0:t.uri)||(this.workspaceService.rootPath?s.Uri.file(this.workspaceService.rootPath):void 0),r=n?n.fsPath:"";return this.activeInterpreterCache.has(r)||this.interpreterService.getActiveInterpreter(n).then((e=>{this.activeInterpreterCache.set(r,e)})).ignoreErrors(),this.activeInterpreterCache.get(r)}async controllerChanged(e){const t=await this.ensureLanguageServer(e.controller.connection.interpreter,e.notebook),n=this.knownControllers.get(e.notebook),r=n?n.connection.interpreter:this.getActiveInterpreterSync(e.notebook.uri.fsPath),i=r?this.getInterpreterIdFromCache(r):void 0,o=i?await this.servers.get(i):void 0;o&&(null==t?void 0:t.interpreterId)!=o.interpreterId&&o.stopWatching(e.notebook),t&&t.startWatching(e.notebook),this.knownControllers.set(e.notebook,e.controller)}async openedNotebook(e){if((0,h.isJupyterNotebook)(e)&&this.extensionChecker.isPythonExtensionInstalled){const t=this.notebookControllerManager.getSelectedNotebookController(e);t&&this.knownControllers.set(e,t),this.getActiveInterpreterSync(e.uri.fsPath);const n=(null==t?void 0:t.connection.interpreter)||await this.interpreterService.getActiveInterpreter(e.uri),r=await this.ensureLanguageServer(n,e);r&&r.startWatching(e)}}closedNotebook(e){this.knownControllers.delete(e)}getInterpreterIdFromCache(e){let t=this.interpreterIdCache.get(e.path);return t||(t=(0,p.getInterpreterId)(e),this.interpreterIdCache.set(e.path,t)),t}shouldAllowIntellisense(e,t,n){const r=(0,h.findAssociatedNotebookDocument)(e,this.notebooks,this.interactiveWindowProvider),i=r?this.notebookControllerManager.getSelectedNotebookController(r):void 0,o=i?i.connection.interpreter:this.getActiveInterpreterSync(e.fsPath);let s=o?this.getInterpreterIdFromCache(o):void 0;if(t!==s&&("startUsingRemoteKernelSpec"===(null==i?void 0:i.connection.kind)||"connectToLiveKernel"===(null==i?void 0:i.connection.kind))){const t=this.getActiveInterpreterSync(e.fsPath);s=t?this.getInterpreterIdFromCache(t):void 0}const a=null==r?void 0:r.getCells().find((t=>t.document.uri.toString()===e.toString()));return t==s&&(!a||"python"===a.document.languageId)}getNotebookHeader(e){let t=this.configService.getSettings(e).runStartupCommands;return Array.isArray(t)&&(t=t.join("\n")),t?t.replace(/\\n/g,"\n").replace(/\\r/g,"\r"):""}async ensureLanguageServer(e,t){const n=this.configService.getSettings(t.uri).pylanceHandlesNotebooks||await this.isPreRelease?"pylance":"jupyter",r=e?(0,p.getInterpreterId)(e):void 0;if(r&&!this.servers.has(r)&&e){const i=m.LanguageServer.createLanguageServer(n,e,this.shouldAllowIntellisense.bind(this),this.getNotebookHeader.bind(this)).then((e=>(null==e||e.startWatching(t),e)));this.servers.set(r,i)}return r?this.servers.get(r):void 0}onDidChangeConfiguration(e){(e.affectsConfiguration("jupyter.pylanceHandlesNotebooks")||e.affectsConfiguration("python.languageServer"))&&(this.servers.forEach((e=>e.then((e=>null==e?void 0:e.dispose())))),this.servers.clear(),this.notebooks.notebookDocuments.forEach((e=>this.openedNotebook(e).ignoreErrors())))}};g=r([(0,o.injectable)(),i(0,(0,o.inject)(l.IDisposableRegistry)),i(1,(0,o.inject)(f.INotebookControllerManager)),i(2,(0,o.inject)(c.IVSCodeNotebook)),i(3,(0,o.inject)(d.IInterpreterService)),i(4,(0,o.inject)(c.IWorkspaceService)),i(5,(0,o.inject)(a.IPythonExtensionChecker)),i(6,(0,o.inject)(u.IInteractiveWindowProvider)),i(7,(0,o.inject)(l.IConfigurationService)),i(8,(0,o.inject)(l.IsPreRelease))],g),t.IntellisenseProvider=g},46526:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LanguageServer=void 0;const r=n(66828),i=n(52847),o=n(71017),s=n(55674),a=n(2519),c=n(1730),l=n(71171),u=n(97784),d=n(46318),p=n(79262),h=n(95063),f=n(7744);function m(e,t){return void 0===e[t]&&(e[t]={}),e[t]}class g{constructor(){this._commands=new Map}get registrationType(){return i.ExecuteCommandRequest.type}fillClientCapabilities(e){m(m(e,"workspace"),"executeCommand").dynamicRegistration=!0}initialize(e){e.executeCommandProvider&&this.register({id:l(),registerOptions:Object.assign({},e.executeCommandProvider)})}register(e){(0,d.traceInfo)("Registering dummy command feature")}unregister(e){let t=this._commands.get(e);t&&t.forEach((e=>e.dispose()))}dispose(){this._commands.forEach((e=>{e.forEach((e=>e.dispose()))})),this._commands.clear()}}class v{constructor(e,t,n,i){this.client=e,this.interpreter=t,this.middleware=n,this.disposables=i,this._interpreterId=(0,p.getInterpreterId)(t),r.notebooks.onDidChangeNotebookCells(this.onDidChangeNotebookCells,this,i)}async dispose(){this.disposables.forEach((e=>e.dispose())),this.middleware.dispose(),await this.client.stop()}get interpreterId(){return this._interpreterId}stopWatching(e){this.middleware.stopWatching(e)}startWatching(e){this.middleware.startWatching(e)}static async createLanguageServer(e,t,n,o){const s=new a.FileBasedCancellationStrategy,l=await v.createServerOptions(t,s);if(l){let a;const d=r.window.createOutputChannel(`${t.displayName||"notebook"}-languageserver`),m=(0,p.getInterpreterId)(t),y="jupyter"==e?(0,c.createNotebookMiddleware)((()=>a),(()=>h.noop),u.NOTEBOOK_SELECTOR,t.path,(e=>n(e,m,t.path)),o):(0,c.createPylanceMiddleware)((()=>a),u.NOTEBOOK_SELECTOR,t.path,(e=>n(e,m,t.path)),o),b={documentSelector:u.NOTEBOOK_SELECTOR,workspaceFolder:void 0,synchronize:{configurationSection:u.PYTHON_LANGUAGE},outputChannel:d,revealOutputChannelOn:i.RevealOutputChannelOn.Never,middleware:y,connectionOptions:{cancellationStrategy:s},initializationOptions:{notebookServer:!0}};a=new i.LanguageClient("notebook-intellisense",l,b);const _=a._features.filter((e=>{var t;return"workspace/executeCommand"!=(null===(t=e.registrationType)||void 0===t?void 0:t.method)}));_.push(new g),a._features=_;const w=a.start();for(;a&&!a.initializeResult;)await(0,f.sleep)(100);return a&&await a.onReady(),new v(a,t,y,[w,s,d])}s.dispose()}onDidChangeNotebookCells(e){this.middleware.refresh(e.document)}static async createServerOptions(e,t){const n=r.workspace.getConfiguration("python");return n&&"Jedi"===n.get("languageServer")?v.createJediLSPServerOptions(e):v.createPylanceServerOptions(t)}static async createJediLSPServerOptions(e){const t=r.extensions.getExtension("ms-python.python");if(t){const n=o.join(t.extensionPath,"pythonFiles","run-jedi-language-server.py");if(await s.pathExists(n))return{command:e.path||"python",args:[n]}}}static async createPylanceServerOptions(e){const t=r.extensions.getExtension("ms-python.vscode-pylance");if(t){const n=o.join(t.extensionPath,"dist"),r=o.join(n,"server.bundle.js"),a=o.join(n,"server.js"),c=await s.pathExists(a)?a:r,l={execArgv:["--nolazy","--inspect=6617"]};return{run:{module:r,transport:i.TransportKind.ipc,args:e.getCommandLineArguments()},debug:{module:c,transport:i.TransportKind.ipc,options:l,args:e.getCommandLineArguments()}}}}}t.LanguageServer=v},96600:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReplayService=void 0;const o=n(86700),s=n(22037),a=n(66828),c=n(52881),l=n(13395),u=n(97784),d=n(19773),p=n(46318),h=n(60593),f=n(71733),m=n(83474),g=n(7744);let v=class{constructor(e,t,n,r,i){this.commandService=e,this.disposableRegistry=t,this.appShell=n,this.fs=r,this.configService=i,this.steps=[],this.index=-1}async activate(){this.disposableRegistry.push(this.commandService.registerCommand(m.Commands.ReplayPylanceLog,this.replayPylanceLog,this)),this.disposableRegistry.push(this.commandService.registerCommand(m.Commands.ReplayPylanceLogStep,this.step,this)),this.isLogActive=new d.ContextKey(m.EditorContexts.ReplayLogLoaded,this.commandService),this.isLogActive.set(!1)}async replayPylanceLog(){var e;if(a.window.activeNotebookEditor){const t=await this.appShell.showOpenDialog({title:"Open Pylance Output Log"});t&&1===t.length&&(this.activeNotebook=a.window.activeNotebookEditor.document,this.steps=await this.parsePylanceLogSteps(t[0].fsPath),this.index=-1,null===(e=this.isLogActive)||void 0===e||e.set(!0))}else this.appShell.showErrorMessage("Command should be run with a jupyter notebook open")}async step(){var e,t,n,r,i,o,s;if(this.steps.length-1>this.index&&this.steps.length>0&&this.activeNotebook===(null===(e=a.window.activeNotebookEditor)||void 0===e?void 0:e.document)&&this.activeNotebook){this.appShell.showInformationMessage(`Replaying step ${this.index+2} of ${this.steps.length}`),this.index+=1;let e=this.steps[this.index],o=e.contentChanges[0];if(e.textDocument.uri.includes("_NotebookConcat_")&&this.activeNotebook){const n=await this.getConverter();if(e.textDocument.uri=null===(t=n.getConcatDocument(this.activeNotebook.cellAt(0).document.uri.toString()).concatUri)||void 0===t?void 0:t.toString(),n){const t={textDocument:{version:e.textDocument.version,uri:n.toNotebookUri(e.textDocument.uri,o.range)},contentChanges:[{text:o.text,range:n.toNotebookRange(e.textDocument.uri,o.range),rangeLength:o.rangeLength}]};if(o.text.startsWith("import IPython\nIPython.get_ipython()\n")){const e=o.text.slice("import IPython\nIPython.get_ipython()\n".length).replace(" # type: ignore",""),n=this.activeNotebook.getCells().find((e=>t.textDocument.uri===e.document.uri.toString()));n&&(t.contentChanges=[{text:e,range:new a.Range(new a.Position(0,0),new a.Position(n.document.lineCount,0)),rangeLength:n.document.getText().length}])}n.handleChange(t),e=t,o=t.contentChanges[0]}}else{const t=/(#ch\d+)/.exec(e.textDocument.uri),n=null!=t&&t.length>1?this.activeNotebook.cellAt(0).document.uri.toString().replace(/(#ch\d+)/,t[1]):e.textDocument.uri;e.textDocument.uri=n}(0,p.traceInfo)(`*** Replaying step: ${JSON.stringify(e,void 0," ")}`);let s=null===(n=this.activeNotebook)||void 0===n?void 0:n.getCells().find((t=>t.document.uri.toString()===e.textDocument.uri));if(!s){const e=this.activeNotebook.cellCount,t=new a.WorkspaceEdit,n=new a.NotebookCellData(a.NotebookCellKind.Code,"",u.PYTHON_LANGUAGE);n.outputs=[],n.metadata={},t.replaceNotebookCells(this.activeNotebook.uri,new a.NotebookRange(e,e),[n]),await a.workspace.applyEdit(t),s=this.activeNotebook.cellAt(this.activeNotebook.cellCount-1)}const c=new a.NotebookRange(s.index,s.index+1);null===(r=a.window.activeNotebookEditor)||void 0===r||r.revealRange(c,a.NotebookEditorRevealType.InCenterIfOutsideViewport),await(0,g.waitForCondition)((async()=>void 0!==a.window.visibleTextEditors.find((e=>e.document===s.document))),3e3,10);const l=a.window.visibleTextEditors.find((e=>e.document===s.document));if(l){const e=new a.Range(new a.Position(o.range.start.line,o.range.start.character),new a.Position(o.range.end.line,o.range.end.character));l.revealRange(e,a.TextEditorRevealType.InCenterIfOutsideViewport),l.selection=new a.Selection(e.start,e.start),await(0,g.sleep)(100),await l.edit((t=>{""==o.text?t.delete(e):o.rangeLength>0?t.replace(e,o.text):t.insert(e.start,o.text)}))}this.steps.length===this.index&&(null===(i=this.isLogActive)||void 0===i||i.set(!1),this.steps=[],this.index=-1)}else(null===(o=this.activeNotebook)||void 0===o?void 0:o.toString())!==(null===(s=a.window.activeNotebookEditor)||void 0===s?void 0:s.document.uri.toString())&&this.index[\s\S]*?\n\})/g;let i=null;for(;null!=(i=r.exec(t));)if(i.index===r.lastIndex&&r.lastIndex++,i.groups&&i.groups.json_event){const e=JSON.parse(i.groups.json_event);n.push(e)}return n}getNotebookHeader(e){let t=this.configService.getSettings(e).runStartupCommands;return Array.isArray(t)&&(t=t.join("\n")),t?t.replace(/\\n/g,"\n").replace(/\\r/g,"\r"):""}async getConverter(){if(!this.converter&&this.activeNotebook){const e=c.createConverter((e=>this.getNotebookHeader(this.activeNotebook.uri)),(()=>s.platform()));this.activeNotebook.getCells().filter((e=>a.languages.match(u.NOTEBOOK_SELECTOR,e.document)>0)).forEach((t=>{e.handleOpen({textDocument:{uri:t.document.uri.toString(),text:t.document.getText(),languageId:t.document.languageId,version:t.document.version}})})),this.converter=e}return this.converter}};v=r([(0,o.injectable)(),i(0,(0,o.inject)(l.ICommandManager)),i(1,(0,o.inject)(f.IDisposableRegistry)),i(2,(0,o.inject)(l.IApplicationShell)),i(3,(0,o.inject)(h.IFileSystem)),i(4,(0,o.inject)(f.IConfigurationService))],v),t.LogReplayService=v},36816:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.filterCompletions=t.generateSortString=t.PythonKernelCompletionProvider=void 0;const o=n(86700),s=n(66828),a=n(92850),c=n(13395),l=n(33149),u=n(46318),d=n(29140),p=n(71733),h=n(7744),f=n(95063),m=n(88319),g=n(4036),v=n(5448),y=n(43367),b=n(82232),_=n(24453),w=n(86044);let S=class{constructor(e,t,n,r,i,o){this.vscodeNotebook=e,this.kernelProvider=t,this.interactiveWindowProvider=n,this.languageClientProvider=r,this.allowStringFilter=!1;const a=i.getSettings().pythonCompletionTriggerCharacters;this.allowStringFilter=null!=a&&(a.includes("'")||a.includes('"')),s.workspace.onDidChangeConfiguration((e=>{if(e.affectsConfiguration("jupyter.pythonCompletionTriggerCharacters")){const e=i.getSettings().pythonCompletionTriggerCharacters;this.allowStringFilter=null!=e&&(e.includes("'")||e.includes('"'))}}),this,o)}async provideCompletionItems(e,t,n,r){if(!(0,f.isNotebookCell)(e))return[];const i=(0,b.findAssociatedNotebookDocument)(e.uri,this.vscodeNotebook,this.interactiveWindowProvider);if(!i)return(0,u.traceError)(`Notebook not found for Cell ${(0,d.getDisplayPath)(e.uri)}`),[];const o=this.kernelProvider.get(i);if(!o||!o.session)return(0,u.traceError)(`Live Notebook not available for ${(0,d.getDisplayPath)(i.uri)}`),[];const a=parseInt(process.env.VSC_JUPYTER_IntellisenseTimeout||"0",10)||g.Settings.IntellisenseTimeout;(0,u.traceInfoIfCI)(`Notebook completion request for ${e.getText()}, ${e.offsetAt(t)}`);const[c,l]=await Promise.all([(0,h.waitForPromise)(this.getJupyterCompletion(o.session,e.getText(),e.offsetAt(t),n),a),(0,h.waitForPromise)(this.getPylanceCompletions(e,t,r,n),a)]);if(!c)return(0,u.traceInfoIfCI)("Notebook completions not found."),[];(0,u.traceInfoIfCI)(`Completions found, filtering the list: ${JSON.stringify(c)}.`);let p=[];const m=c.metadata?c.metadata._jupyter_types_experimental:[];return p=Array.isArray(m)&&m.length>=c.matches.length&&m.every((e=>"number"==typeof e.start&&"number"==typeof e.end&&"string"==typeof e.text))?m.map(((t,n)=>({label:t.text,itemText:t.text,range:new s.Range(e.positionAt(t.start),e.positionAt(t.end)),kind:t.type?w.mapJupyterKind.get(t.type):s.CompletionItemKind.Field,sortText:C(n)}))):c.matches.map(((e,t)=>({label:e,itemText:e,sortText:C(t)}))),k(r.triggerCharacter,this.allowStringFilter,p,l,e,t)}async getJupyterCompletion(e,t,n,r){const i=new m.StopWatch;if("busy"===e.status)return{matches:[],cursor:{start:0,end:0},metadata:{}};const o=await Promise.race([e.requestComplete({code:t,cursor_pos:n}),(0,l.createPromiseFromCancellation)({defaultValue:void 0,cancelAction:"resolve",token:r})]);return(0,u.traceInfoIfCI)(`Got jupyter notebook completions. Is cancel? ${null==r?void 0:r.isCancellationRequested}: ${o?JSON.stringify(o):"empty"}`),(0,u.traceVerbose)(`Jupyter completion time: ${i.elapsedTime}`),o&&o.content&&"matches"in o.content?{matches:o.content.matches,cursor:{start:o.content.cursor_start,end:o.content.cursor_end},metadata:o.content.metadata}:{matches:[],cursor:{start:0,end:0},metadata:{}}}async getPylanceCompletions(e,t,n,r){const i=(0,b.getAssociatedJupyterNotebook)(e);if(i){const o=await this.languageClientProvider.getLanguageClient(i);if(o){const i=o.getFeature(a.CompletionRequest.method).getProvider(e);if(i){const o=await i.provideCompletionItems(e,t,r,n);return o&&"items"in o?o.items:o}}}}};function C(e){return e>=300?"ZZZZZZZ":e<=25?`A${String.fromCharCode(65+e)}`:`${String.fromCharCode(65+Math.ceil(e/25))}${String.fromCharCode(65+e%25)}`}function k(e,t,n,r,i,o){let a=n;const c=0===o.character?void 0:new s.Range(o.line,o.character-1,o.line,o.character),l="."===(c?i.getText(c):void 0),d=i.getWordRangeAtPosition(l||"."===e?new s.Position(o.line,o.character-1):o),p=d&&c?d.union(c):void 0,h=p?i.getText(p):i.lineAt(o.line).text,f=h.endsWith(".")||l,m=t&&("'"==e||'"'==e||function(e,t){const n=e.indexOf('"'),r=e.indexOf("'"),i=e.lastIndexOf('"'),o=e.lastIndexOf("'"),s=n>=0?n:r,a=i>=0?i:o;return s>=0&&t.character>s&&t.character<=a}(h,o));if(m&&(a=a.filter((e=>e.itemText.includes(".")||e.itemText.endsWith("/")))),a=a.map(((e,t)=>{if(e.itemText.startsWith("%")||e.itemText.startsWith("!"))return{...e,sortText:`ZZZ${e.sortText}`};if(m)return e;const n=h?e.itemText.indexOf(h):-1;let r,i,o;if(h&&f&&e.itemText.includes(h)){r=e.itemText.substring(e.itemText.indexOf(h)+(f?h.length:0)),i=e.itemText.substring(e.itemText.indexOf(h)+h.length);const t=("string"==typeof e.label?e.label.length:e.label.label.length)-i.length;o=e.range&&"start"in e.range?new s.Range(new s.Position(e.range.start.line,e.range.start.character+t),e.range.end):e.range}if(!i&&n>0){r=e.itemText.substring(e.itemText.indexOf(h)+(f?h.length:0)),i=e.itemText.substring(e.itemText.indexOf(h)+h.length);const t=("string"==typeof e.label?e.label.length:e.label.label.length)-i.length;o=e.range&&"start"in e.range?new s.Range(new s.Position(e.range.start.line,e.range.start.character+t),e.range.end):e.range}return r&&i&&o&&(e.label=r,e.itemText=i,e.insertText=i,e.filterText=f?`.${i}`:i,e.range=o,e.sortText=C(t)),e})),a=m?a.map((e=>e.itemText.endsWith("/")?{...e,command:{command:"editor.action.triggerSuggest",title:""}}:(e.itemText.includes(" ")&&(e.itemText=e.itemText.replace(/\\ /g," "),"string"==typeof e.label?e.label=e.label.replace(/\\ /g," "):e.label.label=e.label.label.replace(/\\ /g," ")),e))):a.filter((e=>!e.itemText.includes(".")&&!e.itemText.endsWith("/"))),r){const e=new Set(r.map((e=>e.label.toString())));a=a.filter((t=>!e.has(t.itemText)))}return(0,u.traceVerbose)(`Jupyter completions for ${h} at pos ${o.line}:${o.character} with trigger: ${e}\n ${n.map((e=>e.label)).join(",")}`),(0,u.traceVerbose)(`Jupyter results for ${h} at pos ${o.line}:${o.character} with trigger: ${e}\n ${a.map((e=>e.label)).join(",")}`),a}S=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IVSCodeNotebook)),i(1,(0,o.inject)(y.IKernelProvider)),i(2,(0,o.inject)(v.IInteractiveWindowProvider)),i(3,(0,o.inject)(_.INotebookLanguageClientProvider)),i(4,(0,o.inject)(p.IConfigurationService)),i(5,(0,o.inject)(p.IDisposableRegistry))],S),t.PythonKernelCompletionProvider=S,t.generateSortString=C,t.filterCompletions=k},35005:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.PythonKernelCompletionProviderRegistration=void 0;const o=n(86700),s=n(66828),a=n(97784),c=n(71733),l=n(36816),u=[".","%"];let d=class{constructor(e,t,n){this.disposables=e,this.config=t,this.completionProvider=n}async activate(){var e;let t=(null===(e=this.config.getSettings().pythonCompletionTriggerCharacters)||void 0===e?void 0:e.split(""))||u;(t.includes('"')||t.includes("'"))&&(t=[...t,"/"]),this.registerCompletionItemProvider(t)}registerCompletionItemProvider(e){const t=s.languages.registerCompletionItemProvider(a.NOTEBOOK_SELECTOR,this.completionProvider,...e);this.disposables.push(t)}};d=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IDisposableRegistry)),i(1,(0,o.inject)(c.IConfigurationService)),i(2,(0,o.inject)(l.PythonKernelCompletionProvider))],d),t.PythonKernelCompletionProviderRegistration=d},59859:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerTypes=void 0;const r=n(78277),i=n(36816),o=n(35005);t.registerTypes=function(e,t){e.addSingleton(i.PythonKernelCompletionProvider,i.PythonKernelCompletionProvider),e.addSingleton(r.IExtensionSingleActivationService,o.PythonKernelCompletionProviderRegistration)}},10177:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ActiveEditorContextService=void 0;const o=n(86700),s=n(43367),a=n(82232),c=n(13395),l=n(97784),u=n(19773),d=n(71733),p=n(95063),h=n(4036),f=n(41292),m=n(73913),g=n(24453),v=n(5448);let y=class{constructor(e,t,n,r,i,o,s){this.interactiveProvider=e,this.docManager=t,this.commandManager=n,this.vscNotebook=i,this.kernelProvider=o,this.controllers=s,this.disposables=[],this.isPythonFileActive=!1,r.push(this),this.nativeContext=new u.ContextKey(h.EditorContexts.IsNativeActive,this.commandManager),this.canRestartNotebookKernelContext=new u.ContextKey(h.EditorContexts.CanRestartNotebookKernel,this.commandManager),this.canInterruptNotebookKernelContext=new u.ContextKey(h.EditorContexts.CanInterruptNotebookKernel,this.commandManager),this.canRestartInteractiveWindowKernelContext=new u.ContextKey(h.EditorContexts.CanRestartInteractiveWindowKernel,this.commandManager),this.canInterruptInteractiveWindowKernelContext=new u.ContextKey(h.EditorContexts.CanInterruptInteractiveWindowKernel,this.commandManager),this.interactiveContext=new u.ContextKey(h.EditorContexts.IsInteractiveActive,this.commandManager),this.interactiveOrNativeContext=new u.ContextKey(h.EditorContexts.IsInteractiveOrNativeActive,this.commandManager),this.pythonOrNativeContext=new u.ContextKey(h.EditorContexts.IsPythonOrNativeActive,this.commandManager),this.pythonOrInteractiveContext=new u.ContextKey(h.EditorContexts.IsPythonOrInteractiveActive,this.commandManager),this.pythonOrInteractiveOrNativeContext=new u.ContextKey(h.EditorContexts.IsPythonOrInteractiveOrNativeActive,this.commandManager),this.hasNativeNotebookCells=new u.ContextKey(h.EditorContexts.HaveNativeCells,this.commandManager),this.isPythonNotebook=new u.ContextKey(h.EditorContexts.IsPythonNotebook,this.commandManager),this.isJupyterKernelSelected=new u.ContextKey(h.EditorContexts.IsJupyterKernelSelected,this.commandManager),this.hasNativeNotebookOrInteractiveWindowOpen=new u.ContextKey(h.EditorContexts.HasNativeNotebookOrInteractiveWindowOpen,this.commandManager)}dispose(){this.disposables.forEach((e=>e.dispose()))}async activate(){var e;this.docManager.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor,this,this.disposables),this.kernelProvider.onKernelStatusChanged(this.onDidKernelStatusChange,this,this.disposables),this.interactiveProvider.onDidChangeActiveInteractiveWindow(this.onDidChangeActiveInteractiveWindow,this,this.disposables),this.vscNotebook.activeNotebookEditor&&this.onDidChangeActiveNotebookEditor(this.vscNotebook.activeNotebookEditor),this.interactiveProvider.activeWindow&&this.onDidChangeActiveInteractiveWindow(),this.vscNotebook.onDidChangeActiveNotebookEditor(this.onDidChangeActiveNotebookEditor,this,this.disposables),(null===(e=this.docManager.activeTextEditor)||void 0===e?void 0:e.document.languageId)===l.PYTHON_LANGUAGE&&this.onDidChangeActiveTextEditor(this.docManager.activeTextEditor),this.vscNotebook.onDidChangeNotebookEditorSelection(this.updateNativeNotebookInteractiveWindowOpenContext,this,this.disposables),this.vscNotebook.onDidOpenNotebookDocument(this.updateNativeNotebookInteractiveWindowOpenContext,this,this.disposables),this.vscNotebook.onDidCloseNotebookDocument(this.updateNativeNotebookInteractiveWindowOpenContext,this,this.disposables),this.controllers.onNotebookControllerSelectionChanged((()=>this.updateSelectedKernelContext()),this,this.disposables),this.updateSelectedKernelContext()}updateNativeNotebookCellContext(){var e;const t=((null===(e=this.vscNotebook.activeNotebookEditor)||void 0===e?void 0:e.document.cellCount)||0)>0;this.hasNativeNotebookCells.set(t).ignoreErrors()}onDidChangeActiveInteractiveWindow(e){this.interactiveContext.set(!!e).ignoreErrors(),this.updateNativeNotebookInteractiveWindowOpenContext(),this.updateMergedContexts(),this.updateContextOfActiveInteractiveWindowKernel()}onDidChangeActiveNotebookEditor(e){const t=!!e&&e.document.notebookType===m.JupyterNotebookView;this.nativeContext.set(t).ignoreErrors(),this.isPythonNotebook.set(!(!e||!t)&&(0,a.isPythonNotebook)((0,a.getNotebookMetadata)(e.document))).ignoreErrors(),this.updateContextOfActiveNotebookKernel(e),this.updateContextOfActiveInteractiveWindowKernel(),this.updateNativeNotebookInteractiveWindowOpenContext(),this.updateNativeNotebookCellContext(),this.updateMergedContexts()}updateNativeNotebookInteractiveWindowOpenContext(){this.hasNativeNotebookOrInteractiveWindowOpen.set(this.vscNotebook.notebookDocuments.some((e=>e.notebookType===m.JupyterNotebookView||e.notebookType===m.InteractiveWindowView))).ignoreErrors()}updateContextOfActiveNotebookKernel(e){const t=e&&e.document.notebookType===m.JupyterNotebookView?this.kernelProvider.get(e.document):void 0;if(t){const e="unknown"!==t.status;this.canRestartNotebookKernelContext.set(!!e).ignoreErrors();const n="busy"===t.status;this.canInterruptNotebookKernelContext.set(!!n).ignoreErrors()}else this.canRestartNotebookKernelContext.set(!1).ignoreErrors(),this.canInterruptNotebookKernelContext.set(!1).ignoreErrors();this.updateSelectedKernelContext()}updateSelectedKernelContext(){var e,t,n;const r=(null===(e=this.vscNotebook.activeNotebookEditor)||void 0===e?void 0:e.document)||(null===(n=null===(t=(0,f.getActiveInteractiveWindow)(this.interactiveProvider))||void 0===t?void 0:t.notebookEditor)||void 0===n?void 0:n.document);r&&(0,a.isJupyterNotebook)(r)&&this.controllers.getSelectedNotebookController(r)?this.isJupyterKernelSelected.set(!0).catch(p.noop):this.isJupyterKernelSelected.set(!1).catch(p.noop)}updateContextOfActiveInteractiveWindowKernel(){var e,t;const n=null===(t=null===(e=(0,f.getActiveInteractiveWindow)(this.interactiveProvider))||void 0===e?void 0:e.notebookEditor)||void 0===t?void 0:t.document,r=n?this.kernelProvider.get(n):void 0;if(r){const e="unknown"!==r.status;this.canRestartInteractiveWindowKernelContext.set(!!e).ignoreErrors();const t="busy"===r.status;this.canInterruptInteractiveWindowKernelContext.set(!!t).ignoreErrors()}else this.canRestartInteractiveWindowKernelContext.set(!1).ignoreErrors(),this.canInterruptInteractiveWindowKernelContext.set(!1).ignoreErrors();this.updateSelectedKernelContext()}onDidKernelStatusChange({kernel:e}){var t;e.notebookDocument.notebookType===m.InteractiveWindowView?this.updateContextOfActiveInteractiveWindowKernel():e.notebookDocument.notebookType===m.JupyterNotebookView&&e.notebookDocument===(null===(t=this.vscNotebook.activeNotebookEditor)||void 0===t?void 0:t.document)&&this.updateContextOfActiveNotebookKernel(this.vscNotebook.activeNotebookEditor)}onDidChangeActiveTextEditor(e){this.isPythonFileActive=(null==e?void 0:e.document.languageId)===l.PYTHON_LANGUAGE&&!(0,p.isNotebookCell)(e.document.uri),this.updateNativeNotebookCellContext(),this.updateMergedContexts(),this.updateContextOfActiveInteractiveWindowKernel()}updateMergedContexts(){this.interactiveOrNativeContext.set(!0===this.nativeContext.value||!0===this.interactiveContext.value).ignoreErrors(),this.pythonOrNativeContext.set(!0===this.nativeContext.value||!0===this.isPythonFileActive).ignoreErrors(),this.pythonOrInteractiveContext.set(!0===this.interactiveContext.value||!0===this.isPythonFileActive).ignoreErrors(),this.pythonOrInteractiveOrNativeContext.set(!0===this.nativeContext.value||!0===this.interactiveContext.value&&!0===this.isPythonFileActive).ignoreErrors()}};y=r([(0,o.injectable)(),i(0,(0,o.inject)(v.IInteractiveWindowProvider)),i(1,(0,o.inject)(c.IDocumentManager)),i(2,(0,o.inject)(c.ICommandManager)),i(3,(0,o.inject)(d.IDisposableRegistry)),i(4,(0,o.inject)(c.IVSCodeNotebook)),i(5,(0,o.inject)(s.IKernelProvider)),i(6,(0,o.inject)(g.INotebookControllerManager))],y),t.ActiveEditorContextService=y},23646:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CommandRegistry=void 0;const o=n(86700),s=n(66828),a=n(43367),c=n(32467),l=n(38006),u=n(13395),d=n(46318),p=n(60593),h=n(71733),f=n(35952),m=n(95063),g=n(48497),v=n(62907),y=n(97045),b=n(36336),_=n(4036),w=n(60150),S=n(13396),C=n(5448),k=n(15910);let E=class{constructor(e,t,n,r,i,o,s,a,c,u,d,p,h,f,m,g,v,y,b,_){this.documentManager=e,this.dataScienceCodeLensProvider=t,this.commandListeners=n,this.commandManager=r,this.debugService=i,this.configService=o,this.appShell=s,this.jupyterOutput=a,this.exportCommand=c,this.fs=u,this.jupyterVariableDataProviderFactory=d,this.dataViewerFactory=p,this.serverUriStorage=h,this.variableProvider=f,this.workspace=m,this.interactiveWindowProvider=g,this.errorHandler=v,this.dataViewerDependencyService=y,this.interpreterService=b,this.kernelProvider=_,this.disposables=[],this.dataViewerChecker=new l.DataViewerChecker(o,s),this.workspace.isTrusted||this.workspace.onDidGrantWorkspaceTrust(this.registerCommandsIfTrusted,this,this.disposables)}register(){this.registerCommandsIfTrusted(),this.registerCommand(_.Commands.InsertCellBelowPosition,this.insertCellBelowPosition),this.registerCommand(_.Commands.InsertCellBelow,this.insertCellBelow),this.registerCommand(_.Commands.InsertCellAbove,this.insertCellAbove),this.registerCommand(_.Commands.DeleteCells,this.deleteCells),this.registerCommand(_.Commands.SelectCell,this.selectCell),this.registerCommand(_.Commands.SelectCellContents,this.selectCellContents),this.registerCommand(_.Commands.ExtendSelectionByCellAbove,this.extendSelectionByCellAbove),this.registerCommand(_.Commands.ExtendSelectionByCellBelow,this.extendSelectionByCellBelow),this.registerCommand(_.Commands.MoveCellsUp,this.moveCellsUp),this.registerCommand(_.Commands.MoveCellsDown,this.moveCellsDown),this.registerCommand(_.Commands.ChangeCellToMarkdown,this.changeCellToMarkdown),this.registerCommand(_.Commands.ChangeCellToCode,this.changeCellToCode),this.registerCommand(_.Commands.GotoNextCellInFile,this.gotoNextCellInFile),this.registerCommand(_.Commands.GotoPrevCellInFile,this.gotoPrevCellInFile),this.registerCommand(_.Commands.AddCellBelow,this.addCellBelow),this.registerCommand(_.Commands.CreateNewNotebook,this.createNewNotebook),this.registerCommand(_.Commands.ViewJupyterOutput,this.viewJupyterOutput),this.registerCommand(_.Commands.LatestExtension,this.openPythonExtensionPage),this.registerCommand(_.Commands.EnableDebugLogging,this.enableDebugLogging),this.registerCommand(_.Commands.ResetLoggingLevel,this.resetLoggingLevel),this.registerCommand(_.Commands.EnableLoadingWidgetsFrom3rdPartySource,this.enableLoadingWidgetScriptsFromThirdParty),this.registerCommand(_.Commands.ClearSavedJupyterUris,this.clearJupyterUris),this.commandListeners&&this.commandListeners.forEach((e=>{e.register(this.commandManager)}))}dispose(){this.disposables.forEach((e=>e.dispose()))}registerCommandsIfTrusted(){this.workspace.isTrusted&&(this.exportCommand.register(),this.registerCommand(_.Commands.RunAllCells,this.runAllCells),this.registerCommand(_.Commands.RunCell,this.runCell),this.registerCommand(_.Commands.RunCurrentCell,this.runCurrentCell),this.registerCommand(_.Commands.RunCurrentCellAdvance,this.runCurrentCellAndAdvance),this.registerCommand(_.Commands.ExecSelectionInInteractiveWindow,(e=>{this.runSelectionOrLine(e)})),this.registerCommand(_.Commands.RunAllCellsAbove,this.runAllCellsAbove),this.registerCommand(_.Commands.RunCellAndAllBelow,this.runCellAndAllBelow),this.registerCommand(_.Commands.RunAllCellsAbovePalette,this.runAllCellsAboveFromCursor),this.registerCommand(_.Commands.RunCellAndAllBelowPalette,this.runCellAndAllBelowFromCursor),this.registerCommand(_.Commands.RunCurrentCellAndAddBelow,this.runCurrentCellAndAddBelow),this.registerCommand(_.Commands.DebugCell,this.debugCell),this.registerCommand(_.Commands.DebugStepOver,this.debugStepOver),this.registerCommand(_.Commands.DebugContinue,this.debugContinue),this.registerCommand(_.Commands.DebugStop,this.debugStop),this.registerCommand(_.Commands.DebugCurrentCellPalette,this.debugCurrentCellFromCursor),this.registerCommand(_.Commands.OpenVariableView,this.openVariableView),this.registerCommand(_.Commands.OpenOutlineView,this.openOutlineView),this.registerCommand(_.Commands.ShowDataViewer,this.onVariablePanelShowDataViewerRequest),this.registerCommand(_.Commands.RunToLine,this.runToLine),this.registerCommand(_.Commands.RunFromLine,this.runFromLine),this.registerCommand(_.Commands.RunFileInInteractiveWindows,this.runFileInteractive),this.registerCommand(_.Commands.DebugFileInInteractiveWindows,this.debugFileInteractive))}registerCommand(e,t){const n=this.commandManager.registerCommand(e,t,this);this.disposables.push(n)}getCodeWatcher(e){if(e){const t=this.documentManager.textDocuments.filter((t=>this.fs.arePathsSame(t.uri,e)));if(t&&1===t.length)return this.dataScienceCodeLensProvider.getCodeWatcher(t[0]);if(t&&t.length>1)throw new Error(f.DataScience.documentMismatch().format(e.fsPath))}}async enableDebugLogging(){this.configService.getSettings().logging.level!==v.LogLevel.Debug&&(await this.configService.updateSetting("logging.level","debug",void 0,s.ConfigurationTarget.Global),this.commandManager.executeCommand("jupyter.reloadVSCode",f.DataScience.reloadRequired()).then(m.noop,m.noop))}async resetLoggingLevel(){this.configService.getSettings().logging.level!==v.LogLevel.Error&&(await this.configService.updateSetting("logging.level","error",void 0,s.ConfigurationTarget.Global),this.commandManager.executeCommand("jupyter.reloadVSCode",f.DataScience.reloadRequired()).then(m.noop,m.noop))}enableLoadingWidgetScriptsFromThirdParty(){this.configService.getSettings(void 0).widgetScriptSources.length>0||this.configService.updateSetting("widgetScriptSources",["jsdelivr.com","unpkg.com"],void 0,s.ConfigurationTarget.Global).then((()=>{this.appShell.showInformationMessage(f.DataScience.loadThirdPartyWidgetScriptsPostEnabled()).then(m.noop,m.noop)})).catch(m.noop)}async clearJupyterUris(){return this.serverUriStorage.clearUriList()}async runAllCells(e){let t=this.getCodeWatcher(e);return t||(t=this.getCurrentCodeWatcher()),t?t.runAllCells():void 0}async runFileInteractive(e){let t=this.getCodeWatcher(e);return t||(t=this.getCurrentCodeWatcher()),t?t.runFileInteractive():void 0}async debugFileInteractive(e){let t=this.getCodeWatcher(e);return t||(t=this.getCurrentCodeWatcher()),t?t.debugFileInteractive():void 0}async runCell(e,t,n,r,i){const o=this.getCodeWatcher(e);if(o)return o.runCell(new s.Range(t,n,r,i))}async runAllCellsAbove(e,t,n){if(e){const r=this.getCodeWatcher(e);if(r)return r.runAllCellsAbove(t,n)}}async runCellAndAllBelow(e,t,n){if(e){const r=this.getCodeWatcher(e);if(r)return r.runCellAndAllBelow(t,n)}}async runToLine(){const e=this.getCurrentCodeWatcher(),t=this.documentManager.activeTextEditor;if(e&&t&&t.selection)return e.runToLine(t.selection.start.line)}async runFromLine(){const e=this.getCurrentCodeWatcher(),t=this.documentManager.activeTextEditor;if(e&&t&&t.selection)return e.runFromLine(t.selection.start.line)}async runCurrentCell(){const e=this.getCurrentCodeWatcher();return e?e.runCurrentCell():void 0}async runCurrentCellAndAdvance(){const e=this.getCurrentCodeWatcher();return e?e.runCurrentCellAndAdvance():void 0}async runSelectionOrLine(e){const t=this.getCurrentCodeWatcher();return t?t.runSelectionOrLine(this.documentManager.activeTextEditor,(0,m.isUri)(e)?void 0:e):void 0}async debugCell(e,t,n,r,i){if(e){const o=this.getCodeWatcher(e);if(o)return o.debugCell(new s.Range(t,n,r,i))}}async debugStepOver(){this.debugService.activeDebugSession&&this.commandManager.executeCommand("workbench.action.debug.stepOver")}async debugStop(e){if(this.debugService.activeDebugSession){const t=this.interactiveWindowProvider.windows.find((t=>{var n;return(null===(n=t.owner)||void 0===n?void 0:n.toString())==e.toString()}));if(t&&t.notebookDocument){const e=this.kernelProvider.get(t.notebookDocument);e&&await e.interrupt()}this.commandManager.executeCommand("workbench.action.debug.stop")}}async debugContinue(){this.debugService.activeDebugSession&&this.commandManager.executeCommand("workbench.action.debug.continue")}async addCellBelow(){var e;await(null===(e=this.getCurrentCodeWatcher())||void 0===e?void 0:e.addEmptyCellToBottom())}async runCurrentCellAndAddBelow(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.runCurrentCellAndAddBelow()}async insertCellBelowPosition(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.insertCellBelowPosition()}async insertCellBelow(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.insertCellBelow()}async insertCellAbove(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.insertCellAbove()}async deleteCells(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.deleteCells()}async selectCell(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.selectCell()}async selectCellContents(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.selectCellContents()}async extendSelectionByCellAbove(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.extendSelectionByCellAbove()}async extendSelectionByCellBelow(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.extendSelectionByCellBelow()}async moveCellsUp(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.moveCellsUp()}async moveCellsDown(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.moveCellsDown()}async changeCellToMarkdown(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.changeCellToMarkdown()}async changeCellToCode(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.changeCellToCode()}async gotoNextCellInFile(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.gotoNextCell()}async gotoPrevCellInFile(){var e;null===(e=this.getCurrentCodeWatcher())||void 0===e||e.gotoPreviousCell()}async runAllCellsAboveFromCursor(){const e=this.getCurrentCodeLens();if(e){const t=this.getCurrentCodeWatcher();if(t)return t.runAllCellsAbove(e.range.start.line,e.range.start.character)}}async runCellAndAllBelowFromCursor(){const e=this.getCurrentCodeLens();if(e){const t=this.getCurrentCodeWatcher();if(t)return t.runCellAndAllBelow(e.range.start.line,e.range.start.character)}}async debugCurrentCellFromCursor(){if(this.getCurrentCodeLens()){const e=this.getCurrentCodeWatcher();if(e)return e.debugCurrentCell()}}async createNewNotebook(){this.appShell.showInformationMessage('This command has been deprecated and will eventually be removed, please use ["Create: New Jupyter Notebook"](command:workbench.action.openGlobalKeybindings?%5B%22@command:ipynb.newUntitledIpynb%22%5D) instead.').then(m.noop,m.noop),await s.commands.executeCommand("ipynb.newUntitledIpynb")}viewJupyterOutput(){this.jupyterOutput.show(!0)}getCurrentCodeLens(){const e=this.documentManager.activeTextEditor,t=this.getCurrentCodeWatcher();if(e&&t)return t.getCodeLenses().find((t=>t.range.end.line>=e.selection.anchor.line&&t.range.start.line<=e.selection.anchor.line))}getCurrentCodeWatcher(){const e=this.documentManager.activeTextEditor;if(e&&e.document)return this.dataScienceCodeLensProvider.getCodeWatcher(e.document)}openPythonExtensionPage(){s.env.openExternal(s.Uri.parse("https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter"))}async openVariableView(){return this.commandManager.executeCommand("jupyterViewVariables.focus")}async openOutlineView(){return this.commandManager.executeCommand("outline.focus")}async onVariablePanelShowDataViewerRequest(e){var t;if((0,y.sendTelemetryEvent)(b.EventName.OPEN_DATAVIEWER_FROM_VARIABLE_WINDOW_REQUEST),this.debugService.activeDebugSession)try{if(this.debugService.activeDebugSession.configuration.python){const e=await this.interpreterService.getInterpreterDetails(this.debugService.activeDebugSession.configuration.python);e&&await this.dataViewerDependencyService.checkAndInstallMissingDependencies(e)}const n=(0,c.convertDebugProtocolVariableToIJupyterVariable)(e.variable),r=await this.variableProvider.getFullVariable(n),i=await this.jupyterVariableDataProviderFactory.create(r),o=await i.getDataFrameInfo(),s=null===(t=null==o?void 0:o.columns)||void 0===t?void 0:t.length;if(s&&await this.dataViewerChecker.isRequestedColumnSizeAllowed(s)){const e=`${f.DataScience.dataExplorerTitle()} - ${r.name}`;await this.dataViewerFactory.create(i,e),(0,y.sendTelemetryEvent)(b.EventName.OPEN_DATAVIEWER_FROM_VARIABLE_WINDOW_SUCCESS)}}catch(e){(0,y.sendTelemetryEvent)(b.EventName.OPEN_DATAVIEWER_FROM_VARIABLE_WINDOW_ERROR,void 0,void 0,e),(0,d.traceError)(e),this.errorHandler.handleError(e)}}};r([(0,y.captureTelemetry)(_.Telemetry.DebugStepOver)],E.prototype,"debugStepOver",null),r([(0,y.captureTelemetry)(_.Telemetry.DebugStop)],E.prototype,"debugStop",null),r([(0,y.captureTelemetry)(_.Telemetry.DebugContinue)],E.prototype,"debugContinue",null),r([(0,y.captureTelemetry)(_.Telemetry.AddCellBelow)],E.prototype,"addCellBelow",null),E=r([(0,o.injectable)(),i(0,(0,o.inject)(u.IDocumentManager)),i(1,(0,o.inject)(C.IDataScienceCodeLensProvider)),i(2,(0,o.multiInject)(C.IDataScienceCommandListener)),i(2,(0,o.optional)()),i(3,(0,o.inject)(u.ICommandManager)),i(4,(0,o.inject)(u.IDebugService)),i(5,(0,o.inject)(h.IConfigurationService)),i(6,(0,o.inject)(u.IApplicationShell)),i(7,(0,o.inject)(h.IOutputChannel)),i(7,(0,o.named)(_.JUPYTER_OUTPUT_CHANNEL)),i(8,(0,o.inject)(k.ExportCommands)),i(9,(0,o.inject)(p.IFileSystem)),i(10,(0,o.inject)(C.IJupyterVariableDataProviderFactory)),i(11,(0,o.inject)(S.IDataViewerFactory)),i(12,(0,o.inject)(C.IJupyterServerUriStorage)),i(13,(0,o.inject)(C.IJupyterVariables)),i(13,(0,o.named)(_.Identifiers.DEBUGGER_VARIABLES)),i(14,(0,o.inject)(u.IWorkspaceService)),i(15,(0,o.inject)(C.IInteractiveWindowProvider)),i(16,(0,o.inject)(C.IDataScienceErrorHandler)),i(17,(0,o.inject)(w.DataViewerDependencyService)),i(18,(0,o.inject)(g.IInterpreterService)),i(19,(0,o.inject)(a.IKernelProvider))],E),t.CommandRegistry=E},15910:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExportCommands=void 0;const o=n(86700),s=n(55516),a=n(13395),c=n(46318),l=n(60593),u=n(35952),d=n(95063),p=n(97045),h=n(4036),f=n(70214),m=n(41292),g=n(82232),v=n(24453),y=n(5448);let b=class{constructor(e,t,n,r,i,o,s){this.commandManager=e,this.fileConverter=t,this.applicationShell=n,this.fs=r,this.notebooks=i,this.interactiveProvider=o,this.controllers=s,this.disposables=[]}register(){this.registerCommand(h.Commands.ExportAsPythonScript,((e,t)=>this.export(e,f.ExportFormat.python,void 0,t))),this.registerCommand(h.Commands.ExportToHTML,((e,t,n)=>this.export(e,f.ExportFormat.html,t,n))),this.registerCommand(h.Commands.ExportToPDF,((e,t,n)=>this.export(e,f.ExportFormat.pdf,t,n))),this.registerCommand(h.Commands.Export,((e,t,n)=>this.export(e,void 0,t,n))),this.registerCommand(h.Commands.NativeNotebookExport,(e=>this.nativeNotebookExport(e)))}dispose(){this.disposables.forEach((e=>e.dispose()))}registerCommand(e,t){const n=this.commandManager.registerCommand(e,t,this);this.disposables.push(n)}async nativeNotebookExport(e){var t,n,r,i;const o=(0,d.isUri)(e)?e:null===(t=null==e?void 0:e.notebookEditor)||void 0===t?void 0:t.notebookUri,s=o?this.notebooks.notebookDocuments.find((e=>this.fs.arePathsSame(e.uri,o))):null===(n=this.notebooks.activeNotebookEditor)||void 0===n?void 0:n.document;if(s){const e=(null===(r=this.controllers.getSelectedNotebookController(s))||void 0===r?void 0:r.connection.interpreter)||(null===(i=this.controllers.getPreferredNotebookController(s))||void 0===i?void 0:i.connection.interpreter);return this.export(s,void 0,void 0,e)}return this.export(void 0,void 0,void 0,void 0)}async export(e,t,n,r){var i,o,s,a;if(!e){if(!(e=(null===(i=this.notebooks.activeNotebookEditor)||void 0===i?void 0:i.document)||(null===(o=(0,m.getActiveInteractiveWindow)(this.interactiveProvider))||void 0===o?void 0:o.notebookDocument)))return void(0,c.traceInfo)("Export called without a valid exportable document active");r=r||(null===(s=this.controllers.getSelectedNotebookController(e))||void 0===s?void 0:s.connection.interpreter)||(null===(a=this.controllers.getPreferredNotebookController(e))||void 0===a?void 0:a.connection.interpreter),t&&(0,p.sendTelemetryEvent)(h.Telemetry.ExportNotebookAsCommand,void 0,{format:t})}if(t)await this.fileConverter.export(t,e,n,r);else{const t=await this.showExportQuickPickMenu(e,n,r).then((e=>e));void 0!==t?t.handler():(0,p.sendTelemetryEvent)(h.Telemetry.ClickedExportNotebookAsQuickPick)}}getExportQuickPickItems(e,t,n){const r=[];return(n||e.metadata&&(0,g.isPythonNotebook)((0,g.getNotebookMetadata)(e)))&&r.push({label:u.DataScience.exportPythonQuickPickLabel(),picked:!0,handler:()=>{(0,p.sendTelemetryEvent)(h.Telemetry.ClickedExportNotebookAsQuickPick,void 0,{format:f.ExportFormat.python}),this.commandManager.executeCommand(h.Commands.ExportAsPythonScript,e,n)}}),r.push({label:u.DataScience.exportHTMLQuickPickLabel(),picked:!1,handler:()=>{(0,p.sendTelemetryEvent)(h.Telemetry.ClickedExportNotebookAsQuickPick,void 0,{format:f.ExportFormat.html}),this.commandManager.executeCommand(h.Commands.ExportToHTML,e,t,n)}},{label:u.DataScience.exportPDFQuickPickLabel(),picked:!1,handler:()=>{(0,p.sendTelemetryEvent)(h.Telemetry.ClickedExportNotebookAsQuickPick,void 0,{format:f.ExportFormat.pdf}),this.commandManager.executeCommand(h.Commands.ExportToPDF,e,t,n)}}),r}async showExportQuickPickMenu(e,t,n){const r=this.getExportQuickPickItems(e,t,n),i={ignoreFocusOut:!1,matchOnDescription:!0,matchOnDetail:!0,placeHolder:(0,s.getLocString)("DataScience.exportAsQuickPickPlaceholder","Export As...")};return this.applicationShell.showQuickPick(r,i)}};b=r([(0,o.injectable)(),i(0,(0,o.inject)(a.ICommandManager)),i(1,(0,o.inject)(f.IFileConverter)),i(2,(0,o.inject)(a.IApplicationShell)),i(3,(0,o.inject)(l.IFileSystem)),i(4,(0,o.inject)(a.IVSCodeNotebook)),i(5,(0,o.inject)(y.IInteractiveWindowProvider)),i(6,(0,o.inject)(v.INotebookControllerManager))],b),t.ExportCommands=b},48734:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CellHashProviderFactory=void 0;const o=n(86700),s=n(13395),a=n(60593),c=n(71733),l=n(29474),u=n(43367),d=n(5448),p=n(28443);let h=class{constructor(e,t,n,r,i,o){this.documentManager=e,this.configService=t,this.debugService=n,this.fs=r,this.svcContainer=i,this.listeners=o,this.cellHashProvidersIndexedByKernels=new WeakMap}get kernelProvider(){return this._kernelProvider||(this._kernelProvider=this.svcContainer.get(u.IKernelProvider)),this._kernelProvider}get cellHashProviders(){const e=new Set;return this.kernelProvider.kernels.forEach((t=>{const n=this.get(t);n&&e.add(n)})),Array.from(e)}getOrCreate(e){const t=this.get(e);if(t)return t;const n=new p.CellHashProvider(this.documentManager,this.configService,this.debugService,this.fs,this.listeners,e);return this.cellHashProvidersIndexedByKernels.set(e,n),n}get(e){return this.cellHashProvidersIndexedByKernels.get(e)}};h=r([(0,o.injectable)(),i(0,(0,o.inject)(s.IDocumentManager)),i(1,(0,o.inject)(c.IConfigurationService)),i(2,(0,o.inject)(s.IDebugService)),i(3,(0,o.inject)(a.IFileSystem)),i(4,(0,o.inject)(l.IServiceContainer)),i(5,(0,o.multiInject)(d.ICellHashListener)),i(5,(0,o.optional)())],h),t.CellHashProviderFactory=h},28443:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CellHashProvider=void 0;const r=n(33715),i=n(66828),o=n(35952),s=n(44007),a=n(60592),c=n(46318),l=n(83099),u=n(79041),d=n(73909),p=n(73913),h=n(31134),f=n(58967),m=n(3522),g=/(;32m[ ->]*?)(\d+)(.*)/g;t.CellHashProvider=class{constructor(e,t,n,r,o,s){this.documentManager=e,this.configService=t,this.debugService=n,this.fs=r,this.listeners=o,this.kernel=s,this.postEmitter=new i.EventEmitter,this.executionCount=0,this.hashes=new Map,this.updateEventEmitter=new i.EventEmitter,this.traceBackRegexes=new Map,this.disposables=[],this.executionCounts=new Map,this.documentManager.onDidChangeTextDocument(this.onChangedDocument.bind(this)),this.disposables.push(s.onRestarted((()=>this.onKernelRestarted()))),s.onPreExecute(this.onPreExecute,this,this.disposables)}dispose(){this.hashes.clear(),this.traceBackRegexes.clear(),this.disposables.forEach((e=>e.dispose()))}get updated(){return this.updateEventEmitter.event}get postMessage(){return this.postEmitter.event}getHashes(){return[...this.hashes.entries()].map((e=>({uri:i.Uri.parse(e[0]),hashes:e[1].filter((e=>!e.deleted))}))).filter((e=>e.hashes.length>0))}onKernelRestarted(){this.hashes.clear(),this.traceBackRegexes.clear(),this.executionCount=0,this.updateEventEmitter.fire(),this.executionCounts.clear()}onPreExecute(e){if(e.kind===i.NotebookCellKind.Code&&e.notebook.notebookType!==p.InteractiveWindowView){const t=this.extractExecutableLines(e);t.length>0&&t.find((e=>e.trim().length>0))&&this.executionCounts.set(this.executionCounts.size+1,e.document.uri.toString())}}async addCellHash(e){var t,n;if(e.kind!==i.NotebookCellKind.Code)return;const r=this.extractExecutableLines(e);return r.length>0&&r.find((e=>e.trim().length>0))&&(this.executionCount+=1,null===(n=null===(t=(0,d.getInteractiveCellMetadata)(e))||void 0===t?void 0:t.interactive)||void 0===n?void 0:n.uristring)?this.generateHash(e,this.executionCount):void 0}extractExecutableLines(e){var t,n;const r=this.configService.getSettings((0,l.getCellResource)(e)),i=new u.CellMatcher(r),o=(0,s.splitMultilineString)(null!==(n=null===(t=e.metadata.interactive)||void 0===t?void 0:t.originalSource)&&void 0!==n?n:e.document.getText());return r.magicCommandsAsComments&&o.forEach(((e,t)=>o[t]=(0,a.uncommentMagicCommands)(e))),o.length>0&&(i.isCode(o[0])||i.isMarkdown(o[0]))?o.slice(1):o}async generateHash(e,t){var n;if(void 0===e.metadata.interactive)return;const{line:o,uristring:s}=e.metadata.interactive,a=null===(n=(0,d.getInteractiveCellMetadata)(e))||void 0===n?void 0:n.id,l=this.documentManager.textDocuments.find((e=>e.uri.toString()===s));if(l&&a){const{stripped:n,trueStartLine:u}=this.extractStrippedLines(e),d=l.lineAt(u),p=l.lineAt(Math.min(u+n.length-1,l.lineCount-1));let h=0;for(;he.replace(/[ \t\r]+\n$/g,"\n"))).join(""),realCode:w,runtimeLine:y,runtimeFile:C,id:a,timestamp:Date.now()};(0,c.traceInfo)(`Adding hash for ${t} = ${k.hash} with ${n.length} lines`);let E=this.hashes.get(s);E||(E=[]);let x=!1;for(let e=0;e=t.line&&k.line<=t.endLine?(E.splice(e,1,k),x=!0):t.line>k.line&&(E.splice(e,0,k),x=!0)}if(x||E.push(k),this.hashes.set(s,E),!this.traceBackRegexes.has(s)){const e=i.Uri.parse(s),t=new RegExp(`\\[.*?;32m${m(e.fsPath)}`),n=new RegExp(`\\[.*?;32m${m(this.fs.getDisplayName(e.fsPath))}`);this.traceBackRegexes.set(s,[t,n])}if(this.listeners){const e=this.getHashes();await Promise.all(this.listeners.map((t=>t.hashesUpdated(e)))),this.updateEventEmitter.fire()}return k}}getExecutionCount(){return this.executionCount}incExecutionCount(){this.executionCount+=1}getRuntimeFile(e,t){return``}onChangedDocument(e){const t=this.hashes.get(e.document.uri.toString());if(t){const n=e.document.getText();e.contentChanges.forEach((e=>{this.handleContentChange(n,e,t)}))}}extractStrippedLines(e){var t,n;const r=(0,s.splitMultilineString)(null===(t=e.metadata.interactive)||void 0===t?void 0:t.originalSource),i=this.extractExecutableLines(e);let o=null===(n=e.metadata.interactive)||void 0===n?void 0:n.line;for(let e=0;e0;){const e=i[c],t=i[l];if(0!==e.length&&"\n"!==e||0!==t.length&&"\n"!==t)break;i.splice(c,1),c-=1,l-=1}!i[c].endsWith("\n")&&i[c].length>0&&(i[c]=`${i[c]}\n`);for(let e=0;e{n.endOffseto?(n.line+=r,n.endLine+=r,n.startOffset+=i,n.endOffset+=i):n.startOffset===o?n.deleted||t.rangeLength>0||0===r?n.deleted=e.substr(n.startOffset,n.endOffset-n.startOffset)!==n.realCode:(n.line+=r,n.endLine+=r,n.startOffset+=i,n.endOffset+=i):n.deleted=e.substr(n.startOffset,n.endOffset-n.startOffset)!==n.realCode)}))}addHiddenLines(e,t,n,r){return this.debugService.activeDebugSession&&this.configService.getSettings((0,l.getCellResource)(e)).stopOnFirstLineWhileDebugging?(t.splice(0,0,"breakpoint()\n"),{runtimeLine:2,debuggerStartLine:n+1}):{runtimeLine:1,debuggerStartLine:r+1}}modifyTraceback(e){return Array.isArray(e)?e.map(this.modifyTracebackFrame.bind(this)):[]}findCellOffset(e,t){if(e)for(const n of e)if(n.trimmedRightCode.indexOf(t)>=0)return n.firstNonBlankLineIndex}modifyTracebackFrame(e){return/^[Input|File].*?\n.*/.test(e)?this.modifyTracebackFrameIPython8(e):this.modifyTracebackFrameIPython7(e)}modifyTracebackFrameIPython8(e){e=(e=(e=e.replace(/\u001b\[4\dm/g,"")).replace(/\u001b\[38;.*?\d+m/g,"")).replace(/(;32m[ ->]*?)(\d+)(.*)\n/g,((e,t,n,r)=>`${t}${n}${r=r.replace(/\u001b\[3\d+m/g,"")}\n`)),(0,c.traceInfoIfCI)(`Trace frame to match: ${e}`);const t=/^Input.*?\[.*32mIn\s+\[(\d+).*?0;36m(.*?)\n.*/.exec(e);if(t&&t.length>1){const n=parseInt(t[1]);let r,s;for(let e of this.hashes.entries())if(s=e[1].find((e=>e.executionCount===n)),s){r=i.Uri.parse(e[0]);break}if(s&&r)return e.replace(g,((e,t,n,i)=>{const o=parseInt(n,10),a=s.firstNonBlankLineIndex+o-1;return`${t}${a+1}${i}`})).replace(/.*?\n/,`${r.fsPath} in ${t[2]}\n`);if(this.kernel&&this.kernel.notebookDocument.notebookType!==p.InteractiveWindowView){const s=this.executionCounts.get(n),a=this.kernel.notebookDocument.getCells().findIndex((e=>e.document.uri.toString()===s));if(s&&a>=0)return r=i.Uri.parse(s),e.replace(g,((e,t,n,r)=>{const i=parseInt(n,10);return`${t}${i}${r}`})).replace(/.*?\n/,`${o.DataScience.cellAtFormat().format(r.fsPath,(a+1).toString())} in ${t[2]}\n`)}}const n=/^File.*?\[\d;32m(.*):\d+.*\u001b.*\n/.exec(e);if(n&&n.length>1){const t=f(n[1]),r=i.Uri.file(t);return e.replace(g,((e,t,n,i)=>{const o=parseInt(n,10);return`${t}${o}${i}`}))}return e}modifyTracebackFrameIPython7(e){const t=[...this.traceBackRegexes.entries()],n=t.find((t=>t[1].some((t=>t.test(e)))));if(n){let t="";const r=/(;32m[ ->]*?)(\d+)(.*)/g;for(let n=r.exec(e);n&&n.length>3;n=r.exec(e))t=`${t}${(0,h.stripAnsi)(n[3]).substr(1)}\n`;const i=this.findCellOffset(this.hashes.get(n[0]),t);if(void 0!==i)return e.replace(g,((e,t,r,o)=>{const s=parseInt(r,10),a=i+s-1;return`${t}${a+1}${o}`}))}else{const n=t.find((t=>{const n=i.Uri.parse(t[0]);return e.includes(n.fsPath)}));if(n){const t=this.findCellOffset(this.hashes.get(n[0]),e);if(t)return e.replace(g,((e,r,i,o)=>{const s=parseInt(i,10),a=t+s-1;return`${r}${a+1}${o}`}))}}return e}}},97879:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.generateCommand=t.CodeLensFactory=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(46318),l=n(71733),u=n(35952),d=n(83099),p=n(4036),h=n(73909),f=n(43367),m=n(73913),g=n(48734);let v=class{constructor(e,t,n,r,i,o,a){this.configService=e,this.documentManager=t,this.workspace=n,this.cellHashProviderFactory=o,this.updateEvent=new s.EventEmitter,this.notebookData=new Map,this.codeLensCache=new Map,this.documentManager.onDidCloseTextDocument(this.onClosedDocument,this,i),this.workspace.onDidGrantWorkspaceTrust((()=>this.codeLensCache.clear()),this,i),this.configService.getSettings(void 0).onDidChange(this.onChangedSettings,this,i),r.onDidChangeNotebookCellExecutionState(this.onDidChangeNotebookCellExecutionState,this,i),a.onDidDisposeKernel((e=>this.notebookData.delete(e.notebookDocument.uri.toString())),this,i)}get updateRequired(){return this.updateEvent.event}createCodeLenses(e){const t=this.getCodeLensCacheData(e);return[...t.documentLenses,...t.gotoCellLens]}getCellRanges(e){return this.getCodeLensCacheData(e).cellRanges}getCodeLensCacheData(e){const t=e.uri.toString();let n=this.codeLensCache.get(t),r=!1;n||(n={cachedDocumentVersion:void 0,cachedExecutionCounts:new Set,documentLenses:[],cellRanges:[],gotoCellLens:[]},r=!0,this.codeLensCache.set(t,n)),n.cachedDocumentVersion!==e.version&&(n.cellRanges=(0,d.generateCellRangesFromDocument)(e,this.configService.getSettings(e.uri)),n.documentLenses=[],n.gotoCellLens=[],n.cachedDocumentVersion=e.version,r=!0);const i=this.getDocumentExecutionCounts(t);if((i.length!==n.cachedExecutionCounts.size||i.find((e=>!(null==n?void 0:n.cachedExecutionCounts.has(e)))))&&(n.gotoCellLens=[],n.cachedExecutionCounts=new Set(i),r=!0),0===n.documentLenses.length&&r&&n.cellRanges.length){(0,c.traceInfoIfCI)(`Generating new code lenses for version ${e.version} of document ${e.uri}`);const t=this.enumerateCommands(e.uri);let r=!0;n.cellRanges.forEach((i=>{t.forEach((t=>{const o=this.createCodeLens(e,i,t,r);o&&(null==n||n.documentLenses.push(o))})),r=!1}))}if(r&&0===n.gotoCellLens.length&&n.cellRanges.length&&this.configService.getSettings(e.uri).addGotoCodeLenses){const t=this.getHashes();t&&t.length&&n.cellRanges.forEach((r=>{const i=this.createExecutionLens(e,r.range,t);i&&(null==n||n.gotoCellLens.push(i))}))}return n}getDocumentExecutionCounts(e){return[...this.notebookData.values()].map((t=>t.documentExecutionCounts.get(e))).filter((e=>void 0!==e))}onDidChangeNotebookCellExecutionState(e){var t;if(e.cell.notebook.notebookType!==m.InteractiveWindowView)return;if(e.state!==s.NotebookCellExecutionState.Idle||!(null===(t=e.cell.executionSummary)||void 0===t?void 0:t.executionOrder))return;const n=(0,h.getInteractiveCellMetadata)(e.cell);let r=this.notebookData.get(e.cell.notebook.uri.toString());r||(r={cellExecutionCounts:new Map,documentExecutionCounts:new Map},this.notebookData.set(e.cell.notebook.uri.toString(),r)),void 0!==r&&void 0!==n&&(r.cellExecutionCounts.set(n.id,e.cell.executionSummary.executionOrder),r.documentExecutionCounts.set(n.interactive.uristring,e.cell.executionSummary.executionOrder),this.updateEvent.fire())}getHashProviders(){return this.cellHashProviderFactory.cellHashProviders}getHashes(){const e=this.getHashProviders();return e&&e.length?e.map((e=>e.getHashes())).reduce(((e,t)=>[...e,...t])):[]}onClosedDocument(e){this.codeLensCache.delete(e.uri.toString())}onChangedSettings(){this.codeLensCache.clear(),this.updateEvent.fire()}enumerateCommands(e){let t;const n=this.configService.getSettings(e).codeLenses;t=n?n.split(",").map((e=>e.trim())):p.CodeLensCommands.DefaultDesignLenses;const r=this.configService.getSettings(e).debugCodeLenses;if(t=r?t.concat(r.split(",").map((e=>e.trim()))):t.concat(p.CodeLensCommands.DefaultDebuggingLenses),!this.workspace.isTrusted){const e=[...p.CodeLensCommands.DebuggerCommands,...p.CodeLensCommands.DebuggerCommands,p.Commands.RunAllCells,p.Commands.RunAllCellsAbove,p.Commands.RunAllCellsAbovePalette,p.Commands.RunCellAndAllBelowPalette,p.Commands.RunCurrentCell,p.Commands.RunCurrentCellAdvance,p.Commands.RunCurrentCellAndAddBelow,p.Commands.RunFileInInteractiveWindows,p.Commands.InterruptKernel,p.Commands.RunToLine,p.Commands.RunCell,p.Commands.DebugCell,p.Commands.DebugContinue,p.Commands.DebugStepOver,p.Commands.DebugStop,p.Commands.RunCellAndAllBelowPalette];t=t.filter((t=>!e.includes(t)))}return t}createCodeLens(e,t,n,r){if(s.workspace.notebookDocuments.find((t=>t.uri.toString()===e.uri.toString())))return;const{range:i,cell_type:o}=t;switch(n){case p.Commands.RunCurrentCellAndAddBelow:return this.generateCodeLens(i,p.Commands.RunCurrentCellAndAddBelow,u.DataScience.runCurrentCellAndAddBelow());case p.Commands.AddCellBelow:return this.generateCodeLens(i,p.Commands.AddCellBelow,u.DataScience.addCellBelowCommandTitle(),[e.uri,i.start.line]);case p.Commands.DebugCurrentCellPalette:return this.generateCodeLens(i,p.Commands.DebugCurrentCellPalette,u.DataScience.debugCellCommandTitle());case p.Commands.DebugCell:if("code"!==o)break;return this.generateCodeLens(i,p.Commands.DebugCell,u.DataScience.debugCellCommandTitle(),[e.uri,i.start.line,i.start.character,i.end.line,i.end.character]);case p.Commands.DebugStepOver:if("code"!==o)break;return this.generateCodeLens(i,p.Commands.DebugStepOver,u.DataScience.debugStepOverCommandTitle(),[e.uri]);case p.Commands.DebugContinue:if("code"!==o)break;return this.generateCodeLens(i,p.Commands.DebugContinue,u.DataScience.debugContinueCommandTitle(),[e.uri]);case p.Commands.DebugStop:if("code"!==o)break;return this.generateCodeLens(i,p.Commands.DebugStop,u.DataScience.debugStopCommandTitle(),[e.uri]);case p.Commands.RunCurrentCell:case p.Commands.RunCell:return this.generateCodeLens(i,p.Commands.RunCell,u.DataScience.runCellLensCommandTitle(),[e.uri,i.start.line,i.start.character,i.end.line,i.end.character]);case p.Commands.RunAllCells:return this.generateCodeLens(i,p.Commands.RunAllCells,u.DataScience.runAllCellsLensCommandTitle(),[e.uri,i.start.line,i.start.character]);case p.Commands.RunAllCellsAbovePalette:case p.Commands.RunAllCellsAbove:return r?this.generateCodeLens(i,p.Commands.RunCellAndAllBelow,u.DataScience.runCellAndAllBelowLensCommandTitle(),[e.uri,i.start.line,i.start.character]):this.generateCodeLens(i,p.Commands.RunAllCellsAbove,u.DataScience.runAllCellsAboveLensCommandTitle(),[e.uri,i.start.line,i.start.character]);case p.Commands.RunCellAndAllBelowPalette:case p.Commands.RunCellAndAllBelow:return this.generateCodeLens(i,p.Commands.RunCellAndAllBelow,u.DataScience.runCellAndAllBelowLensCommandTitle(),[e.uri,i.start.line,i.start.character]);default:(0,c.traceWarning)(`Invalid command for code lens ${n}`)}}findMatchingCellExecutionCount(e){const t=[...this.notebookData.values()].find((t=>t.cellExecutionCounts.get(e)));return null==t?void 0:t.cellExecutionCounts.get(e)}createExecutionLens(e,t,n){const r=n.filter((t=>t.uri.toString()===e.uri.toString())).map((e=>e.hashes)).flat();if(r){const n=r.filter((e=>e.line-2===t.start.line)).sort(((e,t)=>e.timestamp-t.timestamp));if(n&&n.length){const r=n[n.length-1],i=this.findMatchingCellExecutionCount(r.id);if(void 0!==i)return this.generateCodeLens(t,p.Commands.ScrollToCell,u.DataScience.scrollToCellTitleFormatMessage().format(i.toString()),[e.uri,r.id])}}}generateCodeLens(e,t,n,r){return new s.CodeLens(e,y(t,n,r))}};function y(e,t,n){return{arguments:n,title:t,command:e}}v=r([(0,o.injectable)(),i(0,(0,o.inject)(l.IConfigurationService)),i(1,(0,o.inject)(a.IDocumentManager)),i(2,(0,o.inject)(a.IWorkspaceService)),i(3,(0,o.inject)(a.IVSCodeNotebook)),i(4,(0,o.inject)(l.IDisposableRegistry)),i(5,(0,o.inject)(g.CellHashProviderFactory)),i(6,(0,o.inject)(f.IKernelProvider))],v),t.CodeLensFactory=v,t.generateCommand=y},52396:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataScienceCodeLensProvider=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(19773),l=n(2687),u=n(60593),d=n(71733),p=n(95063),h=n(88319),f=n(29474),m=n(97045),g=n(4036),v=n(5448),y=n(46318),b=n(97784);let _=class{constructor(e,t,n,r,i,o,a,c,u){this.serviceContainer=e,this.debugLocationTracker=t,this.documentManager=n,this.configuration=r,this.commandManager=i,this.debugService=a,this.fs=c,this.totalExecutionTimeInMs=0,this.totalGetCodeLensCalls=0,this.activeCodeWatchers=[],this.didChangeCodeLenses=new s.EventEmitter,o.push(this),o.push(u.onDidGrantWorkspaceTrust((()=>{(0,l.disposeAllDisposables)(this.activeCodeWatchers),this.activeCodeWatchers=[],this.didChangeCodeLenses.fire()}))),o.push(this.debugService.onDidChangeActiveDebugSession(this.onChangeDebugSession.bind(this))),o.push(this.documentManager.onDidCloseTextDocument(this.onDidCloseTextDocument.bind(this))),o.push(this.debugLocationTracker.updated(this.onDebugLocationUpdated.bind(this)))}dispose(){this.totalGetCodeLensCalls>0&&(0,m.sendTelemetryEvent)(g.Telemetry.CodeLensAverageAcquisitionTime,this.totalExecutionTimeInMs/this.totalGetCodeLensCalls)}get onDidChangeCodeLenses(){return this.didChangeCodeLenses.event}provideCodeLenses(e,t){return e.uri.scheme!=b.PYTHON_FILE.scheme&&e.uri.scheme!==b.PYTHON_UNTITLED.scheme?[]:this.getCodeLensTimed(e)}getCodeWatcher(e){return this.matchWatcher(e.uri)}onDebugLocationUpdated(){this.didChangeCodeLenses.fire()}onChangeDebugSession(e){this.didChangeCodeLenses.fire()}onDidCloseTextDocument(e){const t=this.activeCodeWatchers.findIndex((t=>t.uri&&t.uri.toString()===e.uri.toString()));t>=0&&this.activeCodeWatchers.splice(t,1)}getCodeLensTimed(e){const t=new h.StopWatch,n=this.getCodeLens(e);return this.totalExecutionTimeInMs+=t.elapsedTime,this.totalGetCodeLensCalls+=1,new c.ContextKey(g.EditorContexts.HasCodeCells,this.commandManager).set(n&&n.length>0).catch(p.noop),this.configuration.getSettings(e.uri).enableCellCodeLens?this.adjustDebuggingLenses(e,n):[]}adjustDebuggingLenses(e,t){const n=g.CodeLensCommands.DebuggerCommands;if(!this.debugService.activeDebugSession)return t.filter((e=>!!e.command&&!n.includes(e.command.command)));{const r=this.debugLocationTracker.getLocation(this.debugService.activeDebugSession);if(r&&this.fs.areLocalPathsSame(r.fileName,e.uri.fsPath))return t.filter((e=>{const t=new s.Position(r.lineNumber-1,r.column-1);return e.range.contains(t)})).filter((e=>!!e.command&&n.includes(e.command.command)))}return[]}getCodeLens(e){const t=this.matchWatcher(e.uri);return t?t.getCodeLenses():((0,y.traceInfoIfCI)(`Creating a new watcher for document ${e.uri}`),this.createNewCodeWatcher(e).getCodeLenses())}matchWatcher(e){const t=this.activeCodeWatchers.findIndex((t=>t.uri&&t.uri.toString()==e.toString()));if(t>=0)return this.activeCodeWatchers[t];const n=this.documentManager.textDocuments.filter((t=>t.uri.toString()===e.toString()));return n&&n.length>0?((0,y.traceInfoIfCI)(`creating new code watcher with matching document ${e}`),this.createNewCodeWatcher(n[0])):void 0}createNewCodeWatcher(e){const t=this.serviceContainer.get(v.ICodeWatcher);return t.setDocument(e),t.codeLensUpdated(this.onWatcherUpdated.bind(this)),this.activeCodeWatchers.push(t),t}onWatcherUpdated(){this.didChangeCodeLenses.fire()}};_=r([(0,o.injectable)(),i(0,(0,o.inject)(f.IServiceContainer)),i(1,(0,o.inject)(v.IDebugLocationTracker)),i(2,(0,o.inject)(a.IDocumentManager)),i(3,(0,o.inject)(d.IConfigurationService)),i(4,(0,o.inject)(a.ICommandManager)),i(5,(0,o.inject)(d.IDisposableRegistry)),i(6,(0,o.inject)(a.IDebugService)),i(7,(0,o.inject)(u.IFileSystem)),i(8,(0,o.inject)(a.IWorkspaceService))],_),t.DataScienceCodeLensProvider=_},10712:function(e,t,n){"use strict";var r,i=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CodeWatcher=void 0;const s=n(86700),a=n(66828),c=n(13395),l=n(60593),u=n(71733),d=n(28735),p=n(35952),h=n(95063),f=n(88319),m=n(36462),g=n(86909),v=n(97045),y=n(85969),b=n(79041),_=n(4036),w=n(44584),S=n(5448);let C=r=class{constructor(e,t,n,r,i,o,s){this.interactiveWindowProvider=e,this.fs=t,this.configService=n,this.documentManager=r,this.executionHelper=i,this.dataScienceErrorHandler=o,this.codeLensFactory=s,this.version=-1,this.codeLenses=[],this.cells=[],this.codeLensUpdatedEvent=new a.EventEmitter}setDocument(e){this.document=e,this.version=e.version,this.codeLenses=this.codeLensFactory.createCodeLenses(e),this.cells=this.codeLensFactory.getCellRanges(e),this.updateRequiredDisposable=this.codeLensFactory.updateRequired(this.onCodeLensFactoryUpdated.bind(this)),this.closeDocumentDisposable=this.documentManager.onDidCloseTextDocument(this.onDocumentClosed.bind(this))}get codeLensUpdated(){return this.codeLensUpdatedEvent.event}get uri(){var e;return null===(e=this.document)||void 0===e?void 0:e.uri}getVersion(){return this.version}getCodeLenses(){const e=this.document;return e&&e.version!=this.version&&(this.codeLenses=this.codeLensFactory.createCodeLenses(e),this.cells=this.codeLensFactory.getCellRanges(e),this.version=e.version),this.codeLenses}async debugCurrentCell(){if(this.documentManager.activeTextEditor&&this.documentManager.activeTextEditor.document)return this.runMatchingCell(this.documentManager.activeTextEditor.selection,!1,!0)}dispose(){var e,t;this.codeLensUpdatedEvent.dispose(),null===(e=this.closeDocumentDisposable)||void 0===e||e.dispose(),null===(t=this.updateRequiredDisposable)||void 0===t||t.dispose()}async runAllCells(){const e=await this.getActiveInteractiveWindow(),t=this.codeLenses.filter((e=>e.command&&e.command.command===_.Commands.RunCell&&e.command.arguments&&e.command.arguments.length>=5));let n=t.length,r=Promise.resolve(!0);for(const i of t){let o=new a.Range(i.command.arguments[1],i.command.arguments[2],i.command.arguments[3],i.command.arguments[4]);if(this.document){n===t.length&&(o=new a.Range(new a.Position(0,0),o.end));const i=this.document.getText(o);n-=1,r=this.addCode(e,i,this.document.uri,o.start.line,n)}}if(await r,0===t.length)return this.runFileInteractiveInternal(!1)}async runFileInteractive(){return this.runFileInteractiveInternal(!1)}async debugFileInteractive(){return this.runFileInteractiveInternal(!0)}async runAllCellsAbove(e,t){const n=await this.getActiveInteractiveWindow(),r=this.codeLenses.filter((e=>e.command&&e.command.command===_.Commands.RunCell));let i=r.findIndex((n=>n.range.start.line>=e&&n.range.start.character>=t));i<0&&(i=r.length);const o=i;let s=Promise.resolve(!0);for(const e of r){if(!(i>0&&this.document))break;{let t=new a.Range(e.range.start,e.range.end);i===o&&(t=new a.Range(new a.Position(0,0),t.end)),i-=1;const r=this.document.getText(t);s=this.addCode(n,r,this.document.uri,e.range.start.line,i)}}await s}async runCellAndAllBelow(e,t){const n=await this.getActiveInteractiveWindow(),r=this.codeLenses.filter((e=>e.command&&e.command.command===_.Commands.RunCell)),i=r.findIndex((n=>n.range.start.line>=e&&n.range.start.character>=t));let o=i>0?r.length-i:r.length,s=Promise.resolve(!0);for(let e=i;e>=0&&e0&&this.document){const t=r[e];o-=1;const i=this.document.getText(t.range);s=this.addCode(n,i,this.document.uri,t.range.start.line,o)}await s}async runSelectionOrLine(e,t){if(this.document&&e&&this.fs.arePathsSame(e.document.uri,this.document.uri)){const n=await this.getActiveInteractiveWindow();let r;if(r=void 0===t||(0,h.isUri)(t)?await this.executionHelper.getSelectedTextToExecute(e):t,!r)return;const i=await this.executionHelper.normalizeLines(r);if(!i||0===i.trim().length)return;await this.addCode(n,i,this.document.uri,e.selection.start.line,0,e)}}async runToLine(e){if(this.document&&e>0){const t=await this.getActiveInteractiveWindow(),n=this.document.lineAt(e-1),r=this.document.getText(new a.Range(0,0,n.range.end.line,n.range.end.character));r&&r.trim().length&&await this.addCode(t,r,this.document.uri,0,0)}}async runFromLine(e){if(this.document&&e{let o=!0;for(let s=e.selection.end.line+1;sthis.advanceToRange(new a.Range(i,i))))}insertCellBelowPosition(){const e=this.documentManager.activeTextEditor;e&&e.selection&&this.insertCell(e,e.selection.end.line+1)}insertCellBelow(){const e=this.documentManager.activeTextEditor;if(e&&e.selection){const t=this.getCellFromPosition(e.selection.end);t?this.insertCell(e,t.range.end.line+1):this.insertCell(e,e.selection.end.line+1)}}insertCellAbove(){const e=this.documentManager.activeTextEditor;if(e&&e.selection){const t=this.getCellFromPosition(e.selection.start);t?this.insertCell(e,t.range.start.line):this.insertCell(e,e.selection.start.line)}}deleteCells(){const e=this.documentManager.activeTextEditor;if(!e||!e.selection)return;const t=this.getStartEndCells(e.selection);if(!t)return;const n=t[0],r=t[1];let i=0,o=0,s=r.range.end.line+1,c=0;n.range.start.line>0&&(i=n.range.start.line-1,o=e.document.lineAt(i).range.end.character,s=r.range.end.line,c=r.range.end.character);const l=new a.Range(new a.Position(i,o),new a.Position(s,c));e.edit((e=>{e.replace(l,""),this.codeLensUpdatedEvent.fire()}))}selectCell(){const e=this.documentManager.activeTextEditor;if(e&&e.selection){const t=this.getStartEndCells(e.selection);if(t){const n=t[0],r=t[1];e.selection.anchor.isBeforeOrEqual(e.selection.active)?e.selection=new a.Selection(n.range.start,r.range.end):e.selection=new a.Selection(r.range.end,n.range.start)}}}selectCellContents(){const e=this.documentManager.activeTextEditor;if(!e||!e.selection)return;const t=this.getStartEndCellIndex(e.selection);if(!t)return;const n=t[0],r=t[1],i=e.selection.anchor.isBeforeOrEqual(e.selection.active),o=this.cells,s=[];for(let t=n;t<=r;t+=1){const n=o[t];let r=n.range.start.line+1,c=0,l=n.range.end.line,u=n.range.end.character;n.range.start.line===n.range.end.line&&(r=n.range.start.line,c=e.document.lineAt(r).range.end.character,l=r,u=c),i?s.push(new a.Selection(r,c,l,u)):s.push(new a.Selection(l,u,r,c))}e.selections=s}extendSelectionByCellAbove(){const e=this.documentManager.activeTextEditor;if(!e||!e.selection)return;const t=e.selection,n=this.getStartEndCellIndex(e.selection);if(!n)return;const r=e.selection.anchor.isBefore(e.selection.active),i=this.cells,o=n[0],s=n[1],c=i[o],l=i[s];if(c.range.start.isEqual(t.start)&&l.range.end.isEqual(t.end)){let t;r&&o0&&(t=i[o-1],e.selection=new a.Selection(l.range.end,t.range.start)),t&&e.revealRange(t.range,a.TextEditorRevealType.Default)}else{let t;t=r?othis.changeCellTo(e,t,"markdown")))}changeCellToCode(){this.applyToCells(((e,t,n)=>this.changeCellTo(e,t,"code")))}gotoNextCell(){const e=this.documentManager.activeTextEditor;if(!e||!e.selection)return;const t=e.selection,n=this.getCurrentCellLens(t.start),r=this.getNextCellLens(t.start);n&&r&&this.advanceToRange(r.range)}gotoPreviousCell(){const e=this.documentManager.activeTextEditor;if(!e||!e.selection)return;const t=e.selection,n=this.getCurrentCellLens(t.start),r=this.getPreviousCellLens(t.start);n&&r&&this.advanceToRange(r.range)}applyToCells(e){const t=this.documentManager.activeTextEditor,n=this.getStartEndCellIndex(null==t?void 0:t.selection);if(!t||!n)return;const r=this.cells,i=n[0],o=n[1];for(let n=i;n<=o;n+=1)e(t,r[n],n)}changeCellTo(e,t,n){if("raw"===n)throw Error("Cell Type raw not implemented");if(t.cell_type===n)return;const r=new b.CellMatcher(this.configService.getSettings(e.document.uri)),i=e.document.lineAt(t.range.start.line),o=e.document.getText(i.range),s=this.getDefaultCellMarker(e.document.uri),c="markdown"===n?r.codeExecRegEx.exec(o):r.markdownExecRegEx.exec(o);if(!c)return;const l=c[c.length-1],u="markdown"===n?`${s} [markdown]${l}`:`${s}${l}`;e.edit((async r=>{r.replace(i.range,u),t.cell_type=n,t.range.start.line(n&&(t.selection=new a.Selection(e.range.start.line+u.start.line,u.start.character,e.range.start.line+u.end.line,u.end.character)),n)))}}else{if(i===o.length-1)return!1;{const e=o[i+1],n=this.exchangeTextLines(t,l,e.range),r=e.range.end.line-e.range.start.line-(l.end.line-l.start.line);p=n.then((n=>(n&&(t.selection=new a.Selection(e.range.start.line+r+u.start.line,u.start.character,e.range.start.line+r+u.end.line,u.end.character)),n)))}}return p.then((e=>(e&&d&&(t.selection=new a.Selection(t.selection.active,t.selection.anchor)),!0)))}exchangeTextLines(e,t,n){const r=t.start.line,i=t.end.line,o=n.start.line,s=n.end.line;if(i>=o)throw RangeError(`Above lines must be fully above not ${i} <= ${o}`);const c=new a.Range(r,0,i,e.document.lineAt(i).range.end.character),l=e.document.getText(c),u=new a.Range(o,0,s,e.document.lineAt(s).range.end.character),d=e.document.getText(u);let p="";if(i+1{e.replace(f,h),this.codeLensUpdatedEvent.fire()}))}getStartEndCells(e){const t=this.getStartEndCellIndex(e);if(t)return[this.getCellFromIndex(t[0]),this.getCellFromIndex(t[1])]}getStartEndCellIndex(e){if(!e)return;let t=this.getCellIndex(e.start),n=t;if(e.start.line!==e.end.line&&(n=this.getCellIndex(e.end)),-1===t){if(-1===n)return;{t=0;const n=this.getCellFromIndex(0);if(e.start.line>n.range.start.line)throw RangeError(`Should not be able to pick a range with an end in a cell and start after a cell. ${e.start.line} > ${n.range.end.line}`)}}return t>=0&&n>=0?[t,n]:void 0}insertCell(e,t){const n=this.getDefaultCellMarker(e.document.uri),r=t>=e.document.lineCount?`\n${n}\n`:`${n}\n\n`,i=new a.Position(t,0),o=new a.Position(t+1,0);e.edit((e=>{e.insert(i,r),this.codeLensUpdatedEvent.fire()})),e.selection=new a.Selection(o,o)}getDefaultCellMarker(e){return this.configService.getSettings(e).defaultCellMarker||_.Identifiers.DefaultCodeCellMarker}onCodeLensFactoryUpdated(){this.document&&(this.codeLenses=this.codeLensFactory.createCodeLenses(this.document),this.cells=this.codeLensFactory.getCellRanges(this.document)),this.codeLensUpdatedEvent.fire()}onDocumentClosed(e){var t,n;this.document&&this.fs.arePathsSame(e.uri,this.document.uri)&&(this.codeLensUpdatedEvent.dispose(),null===(t=this.closeDocumentDisposable)||void 0===t||t.dispose(),null===(n=this.updateRequiredDisposable)||void 0===n||n.dispose())}getActiveInteractiveWindow(){var e;return this.interactiveWindowProvider.getOrCreate(null===(e=this.document)||void 0===e?void 0:e.uri)}async addCode(e,t,n,r,i,o,s){let a=!1;const c=new f.StopWatch;try{a=s?await e.debugCode(t,n,r,o):await e.addCode(t,n,r,o)}catch(t){t instanceof w.InteractiveCellResultError?await this.addErrorMessage(e,(e=>{const t=e.document.getCells().find((e=>{var t,i,o,s;return(null===(i=null===(t=e.metadata)||void 0===t?void 0:t.interactive)||void 0===i?void 0:i.uristring)===n.toString()&&(null===(s=null===(o=e.metadata)||void 0===o?void 0:o.interactive)||void 0===s?void 0:s.line)===r}));return t?t.index+1:-1}),i):await this.dataScienceErrorHandler.handleError(t)}finally{this.sendPerceivedCellExecute(c)}return a}async addErrorMessage(e,t,n){if(n>0){const r=p.DataScience.cellStopOnErrorFormatMessage().format(n.toString());try{await e.addMessage(r,t)}catch(e){await this.dataScienceErrorHandler.handleError(e)}}}sendPerceivedCellExecute(e){e&&(r.sentExecuteCellTelemetry?(0,v.sendTelemetryEvent)(_.Telemetry.ExecuteCellPerceivedWarm,e.elapsedTime):(r.sentExecuteCellTelemetry=!0,(0,v.sendTelemetryEvent)(_.Telemetry.ExecuteCellPerceivedCold,e.elapsedTime)))}async runMatchingCell(e,t,n){const r=this.getCurrentCellLens(e.start),i=this.getNextCellLens(e.start);if(r){if(t){const e=this.documentManager.activeTextEditor,{newCellOnRunLast:t}=this.configService.getSettings(null==e?void 0:e.document.uri);i?this.advanceToRange(i.range):t&&e&&this.insertCell(e,r.range.end.line+1)}if(this.document){const e=await this.getActiveInteractiveWindow(),t=this.document.getText(r.range);await this.addCode(e,t,this.document.uri,r.range.start.line,0,this.documentManager.activeTextEditor,n)}}}getCellIndex(e){return this.cells.findIndex((t=>e&&t.range.contains(e)))}getCellFromIndex(e){const t=this.cells,n=function(e,t){if(t<=0)throw new RangeError(`Length must be > 0 not ${t}`);return e<0&&(e+=t),e<0?0:e>=t?t-1:e}(e,t.length);return t[n]}getCellFromPosition(e){if(!e){const t=this.documentManager.activeTextEditor;t&&t.selection&&(e=t.selection.active)}if(e){const t=this.getCellIndex(e);if(t>=0)return this.cells[t]}}getCurrentCellLens(e){return this.codeLenses.find((t=>t.range.contains(e)&&void 0!==t.command&&t.command.command===_.Commands.RunCell))}getNextCellLens(e){const t=this.codeLenses.findIndex((t=>t.range.contains(e)&&void 0!==t.command&&t.command.command===_.Commands.RunCell));if(t>=0)return this.codeLenses.find(((e,n)=>void 0!==e.command&&e.command.command===_.Commands.RunCell&&n>t))}getPreviousCellLens(e){const t=this.codeLenses.findIndex((t=>t.range.contains(e)&&void 0!==t.command&&t.command.command===_.Commands.RunCell));if(t>=1)return this.codeLenses.find(((e,n)=>void 0!==e.command&&nthis.addCode(t,this.document.getText(n.range),this.document.uri,n.range.start.line,0,void 0,e)));await Promise.all(n)}else await this.addCode(t,n,this.document.uri,0,0,void 0,e)}}advanceToRange(e){const t=this.documentManager.activeTextEditor,n=new a.Selection(e.start,e.start);t&&(t.selection=n,t.revealRange(e,a.TextEditorRevealType.Default))}};C.sentExecuteCellTelemetry=!1,i([(0,v.captureTelemetry)(_.Telemetry.DebugCurrentCell)],C.prototype,"debugCurrentCell",null),i([(0,v.captureTelemetry)(_.Telemetry.RunAllCells)],C.prototype,"runAllCells",null),i([(0,v.captureTelemetry)(_.Telemetry.RunFileInteractive)],C.prototype,"runFileInteractive",null),i([(0,v.captureTelemetry)(_.Telemetry.DebugFileInteractive)],C.prototype,"debugFileInteractive",null),i([(0,v.captureTelemetry)(_.Telemetry.RunAllCellsAbove)],C.prototype,"runAllCellsAbove",null),i([(0,v.captureTelemetry)(_.Telemetry.RunCellAndAllBelow)],C.prototype,"runCellAndAllBelow",null),i([(0,v.captureTelemetry)(_.Telemetry.RunSelectionOrLine)],C.prototype,"runSelectionOrLine",null),i([(0,v.captureTelemetry)(_.Telemetry.RunToLine)],C.prototype,"runToLine",null),i([(0,v.captureTelemetry)(_.Telemetry.RunFromLine)],C.prototype,"runFromLine",null),i([m.traceDecorators.verbose("CodeWatcher::runCell",g.TraceOptions.BeforeCall)],C.prototype,"runCell",null),i([(0,v.captureTelemetry)(_.Telemetry.DebugCurrentCell)],C.prototype,"debugCell",null),i([(0,v.captureTelemetry)(_.Telemetry.RunCurrentCell)],C.prototype,"runCurrentCell",null),i([(0,v.captureTelemetry)(_.Telemetry.RunCurrentCellAndAdvance)],C.prototype,"runCurrentCellAndAdvance",null),i([(0,v.captureTelemetry)(_.Telemetry.RunCurrentCellAndAddBelow)],C.prototype,"runCurrentCellAndAddBelow",null),i([(0,v.captureTelemetry)(_.Telemetry.InsertCellBelowPosition)],C.prototype,"insertCellBelowPosition",null),i([(0,v.captureTelemetry)(_.Telemetry.InsertCellBelow)],C.prototype,"insertCellBelow",null),i([(0,v.captureTelemetry)(_.Telemetry.InsertCellAbove)],C.prototype,"insertCellAbove",null),i([(0,v.captureTelemetry)(_.Telemetry.DeleteCells)],C.prototype,"deleteCells",null),i([(0,v.captureTelemetry)(_.Telemetry.SelectCell)],C.prototype,"selectCell",null),i([(0,v.captureTelemetry)(_.Telemetry.SelectCellContents)],C.prototype,"selectCellContents",null),i([(0,v.captureTelemetry)(_.Telemetry.ExtendSelectionByCellAbove)],C.prototype,"extendSelectionByCellAbove",null),i([(0,v.captureTelemetry)(_.Telemetry.ExtendSelectionByCellBelow)],C.prototype,"extendSelectionByCellBelow",null),i([(0,v.captureTelemetry)(_.Telemetry.MoveCellsUp)],C.prototype,"moveCellsUp",null),i([(0,v.captureTelemetry)(_.Telemetry.MoveCellsDown)],C.prototype,"moveCellsDown",null),i([(0,v.captureTelemetry)(_.Telemetry.ChangeCellToMarkdown)],C.prototype,"changeCellToMarkdown",null),i([(0,v.captureTelemetry)(_.Telemetry.ChangeCellToCode)],C.prototype,"changeCellToCode",null),i([(0,v.captureTelemetry)(_.Telemetry.GotoNextCellInFile)],C.prototype,"gotoNextCell",null),i([(0,v.captureTelemetry)(_.Telemetry.GotoPrevCellInFile)],C.prototype,"gotoPreviousCell",null),i([(0,d.chainable)()],C.prototype,"getActiveInteractiveWindow",null),C=r=i([(0,s.injectable)(),o(0,(0,s.inject)(S.IInteractiveWindowProvider)),o(1,(0,s.inject)(l.IFileSystem)),o(2,(0,s.inject)(u.IConfigurationService)),o(3,(0,s.inject)(c.IDocumentManager)),o(4,(0,s.inject)(y.ICodeExecutionHelper)),o(5,(0,s.inject)(S.IDataScienceErrorHandler)),o(6,(0,s.inject)(S.ICodeLensFactory))],C),t.CodeWatcher=C},5127:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Decorator=void 0;const o=n(86700),s=n(66828),a=n(98501),c=n(13395),l=n(97784),u=n(71733),d=n(83099),p=n(82232);let h=class{constructor(e,t,n,r){this.documentManager=e,this.configuration=n,this.extensionChecker=r,this.computeDecorations(),t.push(this),t.push(this.configuration.getSettings(void 0).onDidChange(this.settingsChanged,this)),t.push(this.documentManager.onDidChangeActiveTextEditor(this.changedEditor,this)),t.push(this.documentManager.onDidChangeTextEditorSelection(this.changedSelection,this)),t.push(this.documentManager.onDidChangeTextDocument(this.changedDocument,this)),this.settingsChanged()}activate(){return Promise.resolve()}dispose(){this.timer&&clearTimeout(this.timer)}settingsChanged(){this.documentManager.activeTextEditor&&this.triggerUpdate(this.documentManager.activeTextEditor)}changedEditor(){this.triggerUpdate(void 0)}changedDocument(e){this.documentManager.activeTextEditor&&e.document===this.documentManager.activeTextEditor.document&&this.triggerUpdate(this.documentManager.activeTextEditor)}changedSelection(e){e.textEditor&&e.textEditor.selection.anchor&&this.triggerUpdate(e.textEditor)}triggerUpdate(e){this.timer&&clearTimeout(this.timer),this.timer=setTimeout((()=>this.update(e)),100)}computeDecorations(){this.currentCellTopUnfocused=this.documentManager.createTextEditorDecorationType({borderColor:new s.ThemeColor("interactive.inactiveCodeBorder"),borderWidth:"2px 0px 0px 0px",borderStyle:"solid",isWholeLine:!0}),this.currentCellBottomUnfocused=this.documentManager.createTextEditorDecorationType({borderColor:new s.ThemeColor("interactive.inactiveCodeBorder"),borderWidth:"0px 0px 1px 0px",borderStyle:"solid",isWholeLine:!0}),this.currentCellTop=this.documentManager.createTextEditorDecorationType({borderColor:new s.ThemeColor("interactive.activeCodeBorder"),borderWidth:"2px 0px 0px 0px",borderStyle:"solid",isWholeLine:!0}),this.currentCellBottom=this.documentManager.createTextEditorDecorationType({borderColor:new s.ThemeColor("interactive.activeCodeBorder"),borderWidth:"0px 0px 1px 0px",borderStyle:"solid",isWholeLine:!0})}update(e){const t=void 0===e?this.documentManager.visibleTextEditors:[e];for(const e of t)if(e&&e.document&&e.document.languageId===l.PYTHON_LANGUAGE&&!(0,p.getAssociatedJupyterNotebook)(e.document)&&this.currentCellTop&&this.currentCellBottom&&this.currentCellTopUnfocused&&this.currentCellBottomUnfocused&&this.extensionChecker.isPythonExtensionInstalled){const t=this.configuration.getSettings(e.document.uri);if(t.decorateCells){const n=(0,d.generateCellRangesFromDocument)(e.document,t).map((e=>e.range)).filter((t=>t.contains(e.selection.anchor))),r=n.length>0?[new s.Range(n[0].start,n[0].start)]:[],i=n.length>0?[new s.Range(n[0].end,n[0].end)]:[];this.documentManager.activeTextEditor===e?(e.setDecorations(this.currentCellTop,r),e.setDecorations(this.currentCellBottom,i),e.setDecorations(this.currentCellTopUnfocused,[]),e.setDecorations(this.currentCellBottomUnfocused,[])):(e.setDecorations(this.currentCellTop,[]),e.setDecorations(this.currentCellBottom,[]),e.setDecorations(this.currentCellTopUnfocused,r),e.setDecorations(this.currentCellBottomUnfocused,i))}else e.setDecorations(this.currentCellTop,[]),e.setDecorations(this.currentCellBottom,[]),e.setDecorations(this.currentCellTopUnfocused,[]),e.setDecorations(this.currentCellBottomUnfocused,[])}}};h=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IDocumentManager)),i(1,(0,o.inject)(u.IDisposableRegistry)),i(2,(0,o.inject)(u.IConfigurationService)),i(3,(0,o.inject)(a.IPythonExtensionChecker))],h),t.Decorator=h},99326:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.HoverProvider=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(33149),l=n(97784),u=n(46318),d=n(60593),p=n(71733),h=n(7744),f=n(88319),m=n(97045),g=n(4036),v=n(73909),y=n(43367),b=n(73913),_=n(5448);let w=class{constructor(e,t,n,r,i,o){this.variableProvider=e,this.interactiveProvider=t,this.fs=n,this.notebook=r,this.disposables=i,this.kernelProvider=o,this.runFiles=new Set,this.stopWatch=new f.StopWatch}activate(){this.notebook.onDidChangeNotebookCellExecutionState(this.onDidChangeNotebookCellExecutionState,this,this.disposables),this.kernelProvider.onDidRestartKernel((()=>this.runFiles.clear()),this,this.disposables)}dispose(){this.hoverProviderRegistration&&this.hoverProviderRegistration.dispose()}async onDidChangeNotebookCellExecutionState(e){try{if(e.cell.notebook.notebookType!==b.InteractiveWindowView)return;const t=this.runFiles.size,n=(0,v.getInteractiveCellMetadata)(e.cell);void 0!==n&&this.runFiles.add(n.interactive.uristring),t!==this.runFiles.size&&await this.initializeHoverProvider()}catch(e){(0,u.traceError)(e)}}async provideHover(e,t,n){const r=(0,h.sleep)(300).then((()=>{}));this.stopWatch.reset();const i=await Promise.race([r,this.getVariableHover(e,t,n)]);return(0,m.sendTelemetryEvent)(g.Telemetry.InteractiveFileTooltipsPerf,this.stopWatch.elapsedTime,{isResultNull:!!i}),i}async initializeHoverProvider(){this.hoverProviderRegistration||(this.hoverProviderRegistration=s.languages.registerHoverProvider(l.PYTHON,this))}getVariableHover(e,t,n){return c.Cancellation.race((async n=>{const r=e.getWordRangeAtPosition(t);if(r){const t=e.getText(r);if(t){const r=this.getMatchingKernels(e);if(r.length){const e=await Promise.race(r.map((e=>this.variableProvider.getVariableProperties(t,e,n)))),i=Object.entries(e);if(i.length>0){const e=i.reduce(((e,t)=>e+`${t[0]}: ${t[1]}\n`),"```\n")+"```";return{contents:[new s.MarkdownString(e)]}}}}}}),n)}getMatchingKernels(e){let t=this.interactiveProvider.windows.filter((t=>t.owner&&this.fs.arePathsSame(t.owner,e.uri))).map((e=>{var t;return null===(t=e.notebookUri)||void 0===t?void 0:t.toString()}));if(!Array.isArray(t)||0==t.length)return[];const n=new Set;return this.notebook.notebookDocuments.filter((e=>t.includes(e.uri.toString()))).forEach((e=>{const t=this.kernelProvider.get(e);t&&n.add(t)})),Array.from(n)}};w=r([(0,o.injectable)(),i(0,(0,o.inject)(_.IJupyterVariables)),i(0,(0,o.named)(g.Identifiers.KERNEL_VARIABLES)),i(1,(0,o.inject)(_.IInteractiveWindowProvider)),i(2,(0,o.inject)(d.IFileSystem)),i(3,(0,o.inject)(a.IVSCodeNotebook)),i(4,(0,o.inject)(p.IDisposableRegistry)),i(5,(0,o.inject)(y.IKernelProvider))],w),t.HoverProvider=w},41292:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getActiveInteractiveWindow=void 0;const r=n(66828),i=n(97784);t.getActiveInteractiveWindow=function(e){if(e.activeWindow)return e.activeWindow;if(void 0===r.window.activeTextEditor)return;const t=r.window.activeTextEditor.document.uri;return t.scheme!==i.NotebookCellScheme?e.get(t):void 0}},88286:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getInteractiveWindowTitle=t.createInteractiveIdentity=void 0;const r=n(71017),i=n(71171),o=n(66828);n(30895);const s=n(35952);let a=[],c=0;t.createInteractiveIdentity=function(){return(c>0||a.length<=0)&&a.push(i()),c+=1,o.Uri.parse(`history://${a[a.length-1]}`)},t.getInteractiveWindowTitle=function(e){return s.DataScience.interactiveWindowTitleFormat().format(r.basename(e.fsPath))}},73909:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.InteractiveWindow=t.getInteractiveCellMetadata=void 0;const i=n(71017),o=n(66828),s=n(97784);n(30895);const a=n(46318),c=n(71171),l=n(95063),u=n(83099),d=n(79041),p=n(4036),h=n(70214),f=n(43367),m=n(88286),g=n(44007),v=n(60592),y=n(32417),b=n(73913),_=n(28735),w=n(44584),S=n(35952),C=n(7744),k=n(93828),E=n(65725),x=n(52194),T=n(82232);function D(e){if(void 0!==e.metadata.interactive)return e.metadata}t.getInteractiveCellMetadata=D;class I{constructor(e,t,n,r,i,s,a,c,l,u,p,h,f,m){this.documentManager=e,this.fs=t,this.configuration=n,this.commandManager=r,this.jupyterExporter=i,this.workspaceService=s,this.extensionChecker=l,this.exportDialog=u,this.notebookControllerManager=p,this.serviceContainer=h,this.interactiveWindowDebugger=f,this.originalConnection=m,this._onDidChangeViewState=new o.EventEmitter,this.closedEvent=new o.EventEmitter,this._submitters=[],this.mode="multiple",this.internalDisposables=[],this.kernelDisposables=[],this._kernelPromise=(0,C.createDeferred)(),this.pendingNotebookScrolls=[],this._kernelEventHook=this.kernelEventHook.bind(this),this._owner=a,this.mode=c,a&&this._submitters.push(a),this._editorReadyPromise=this.createReadyPromise(m),o.workspace.onDidCloseNotebookDocument((e=>{e===this._notebookDocument&&this.closedEvent.fire()}),this.internalDisposables),this.cellMatcher=new d.CellMatcher(this.configuration.getSettings(this.owningResource))}get ready(){return this._editorReadyPromise.then((e=>{}))}get onDidChangeViewState(){return this._onDidChangeViewState.event}get closed(){return this.closedEvent.event}get owner(){return this._owner}get submitters(){return this._submitters}get notebookUri(){var e;return null===(e=this._notebookDocument)||void 0===e?void 0:e.uri}get notebookEditor(){return this._notebookEditor}get notebookDocument(){return this._notebookDocument}async createReadyPromise(e){const t=await this.getPreferredController(e),n=await this.createEditor(t);return n&&t&&(await this.insertSysInfoMessage(n.document,t.connection,E.SysInfoReason.Start),this.startKernel(n.document,t).ignoreErrors()),n}async startKernel(e,t){if(t.id!==this._kernelConnectionId){this._kernelConnectionId=t.id;const n=this.insertSysInfoMessage(e,t.connection,E.SysInfoReason.Start);try{(0,y.initializeInteractiveOrNotebookTelemetryBasedOnUserAction)(this.owner,t.connection);const r=await(0,k.connectToKernel)(t,this.serviceContainer,this.owner,e);this._kernelConnectMetadata={...r.kernelConnectionMetadata},this._kernelConnectionId=r.controller.id,this.updateSysInfoMessage(this.getSysInfoMessage(r.kernelConnectionMetadata,E.SysInfoReason.Start),!1,n),this._kernelPromise.resolved&&this._kernelPromise.value===r||(r.addEventHook(this._kernelEventHook),this.kernelDisposables.push({dispose:()=>{r.removeEventHook(this._kernelEventHook)}}),r.onRestarted((async()=>{(0,a.traceInfoIfCI)("Restart event handled in IW"),this.fileInKernel=void 0;const t=Promise.resolve(null==e?void 0:e.cellAt(e.cellCount-1));try{await this.runInitialization(r,this.owner)}finally{this.finishSysInfoMessage(r,t,E.SysInfoReason.Restart)}}),this,this.kernelDisposables),this.kernelDisposables.push(r)),this.fileInKernel=void 0,await this.runInitialization(r,this.owner),this.finishSysInfoMessage(r,n,E.SysInfoReason.Start),this._kernelPromise.resolve(r)}catch(e){this.finishSysInfoMessage(e,n,E.SysInfoReason.Start),this._kernelPromise.resolve(void 0),this.disconnectKernel(),this._kernelConnectionId=t.id}}}async kernelEventHook(e){"willRestart"===e&&this._notebookDocument&&this._kernelConnectMetadata&&(this._insertSysInfoPromise=void 0,this.insertSysInfoMessage(this._notebookDocument,this._kernelConnectMetadata,E.SysInfoReason.Restart))}getSysInfoMessage(e,t){var n;const r=null===(n=e.interpreter)||void 0===n?void 0:n.displayName;return t===E.SysInfoReason.Restart?r?S.DataScience.restartingKernelCustomHeader().format(r):S.DataScience.restartingKernelHeader():r?S.DataScience.startingNewKernelCustomHeader().format(r):S.DataScience.startingNewKernelHeader()}async insertSysInfoMessage(e,t,n){if(!this._insertSysInfoPromise){const r=async()=>{const r=this.getSysInfoMessage(t,n);return await(0,x.chainWithPendingUpdates)(e,(t=>{const n=new o.NotebookCellData(o.NotebookCellKind.Markup,r,s.MARKDOWN_LANGUAGE);n.metadata={isInteractiveWindowMessageCell:!0,isPlaceholder:!0},t.replaceNotebookCells(e.uri,new o.NotebookRange(e.cellCount,e.cellCount),[n])})),e.cellAt(e.cellCount-1)};this._insertSysInfoPromise=r()}return this._insertSysInfoPromise}updateSysInfoMessage(e,t,n){n.then((n=>(0,x.chainWithPendingUpdates)(this._notebookDocument,(r=>{if(void 0!==n&&n.index>=0&&n.kind===o.NotebookCellKind.Markup&&n.metadata.isInteractiveWindowMessageCell&&n.metadata.isPlaceholder)return r.replace(n.document.uri,new o.Range(0,0,n.document.lineCount,0),e),void r.replaceNotebookCellMetadata(this._notebookDocument.uri,n.index,{isInteractiveWindowMessageCell:!0,isPlaceholder:!t})})))).ignoreErrors()}finishSysInfoMessage(e,t,n){var r,i;const o="info"in e?null===(r=e.kernelConnectionMetadata.interpreter)||void 0===r?void 0:r.displayName:"",s="info"in e&&"ok"===(null===(i=e.info)||void 0===i?void 0:i.status)?e.info:void 0,a=s?s.banner.split("\n").join(" \n"):e.toString(),c=n==E.SysInfoReason.Restart?S.DataScience.restartedKernelHeader().format(o||""):a;this.updateSysInfoMessage(c,!0,t)}async getPreferredController(e){return e?this.notebookControllerManager.getControllerForConnection(e,"interactive"):await this.notebookControllerManager.getActiveInterpreterOrDefaultController(b.InteractiveWindowView,this.owner)}async createEditor(e){const t=e?`${s.JVSC_EXTENSION_ID}/${e.id}`:void 0;(0,a.traceInfo)(`Starting interactive window with controller ID ${t}`);const n=void 0!==this.owner,{inputUri:r,notebookEditor:i}=await this.commandManager.executeCommand("interactive.open",{viewColumn:o.ViewColumn.Beside,preserveFocus:n},void 0,t,this.owner&&"perFile"===this.mode?(0,m.getInteractiveWindowTitle)(this.owner):void 0);if(!i)throw new Error("Failed to request creation of interactive window from VS Code.");return this._notebookEditor=i,this._notebookDocument=i.document,this._inputUri=r,this.internalDisposables.push(o.window.onDidChangeActiveNotebookEditor((e=>{e===this._notebookEditor&&this._onDidChangeViewState.fire()}))),o.window.activeNotebookEditor===this._notebookEditor&&this._onDidChangeViewState.fire(),this.listenForControllerSelection(i.document),i}registerControllerChangeListener(e,t){const n=e.controller.onDidChangeSelectedNotebooks((e=>{!1===e.selected&&e.notebook===t&&(n.dispose(),this.disconnectKernel())}),this,this.internalDisposables)}listenForControllerSelection(e){const t=this.notebookControllerManager.getSelectedNotebookController(e);void 0!==t&&this.registerControllerChangeListener(t,e),this.notebookControllerManager.onNotebookControllerSelected((t=>{t.notebook===e&&(this.registerControllerChangeListener(t.controller,e),t.controller.id!==this._kernelConnectionId&&(this.disconnectKernel(),this.startKernel(t.notebook,t.controller).ignoreErrors()))}),this,this.internalDisposables)}async show(){await this.commandManager.executeCommand("interactive.open",{preserveFocus:!0},this.notebookUri,void 0,void 0)}get inputUri(){return this._inputUri}dispose(){this.internalDisposables.forEach((e=>e.dispose())),this.disconnectKernel()}async addMessage(e,t){const n=await this._editorReadyPromise,r=new o.WorkspaceEdit,i=new o.NotebookCellData(o.NotebookCellKind.Markup,e,s.MARKDOWN_LANGUAGE);i.metadata={isInteractiveWindowMessageCell:!0};const a=t?t(n):-1,c=a>=0?a:n.document.cellCount;r.replaceNotebookCells(n.document.uri,new o.NotebookRange(c,c),[i]),await o.workspace.applyEdit(r)}changeMode(e){this.mode!==e&&(this.mode=e)}async addCode(e,t,n){return this.submitCodeImpl(e,t,n,!1)}async debugCode(e,t,n){let r=!0;const i=t.fsPath,o=this.documentManager.textDocuments.find((e=>this.fs.areLocalPathsSame(e.fileName,i)));if(o&&o.isUntitled){const e=[...this.documentManager.textDocuments];if(r=await o.save(),r){const n=this.documentManager.textDocuments.filter((t=>-1===e.indexOf(t)));n&&n.length>0&&(t=n[0].uri,await this.documentManager.openTextDocument(t))}}return!r||this.submitCodeImpl(e,t,n,!0)}async submitCodeImpl(e,t,n,r){if(0===this.cellMatcher.stripFirstMarker(e).trim().length)return!0;this.updateOwners(t);const i=e.splitLines({trim:!1}),o=new d.CellMatcher(this.configuration.getSettings(t));let s=-1;o.isMarkdown(i[0])&&(0,g.parseForComments)(i,((e,t)=>(0,l.noop)()),((e,t)=>{e&&e.length>0&&-1===s&&(s=t)}));const a=(s>0?[i.slice(0,s).join("\n"),i.slice(s).join("\n")]:[e]).map((e=>{const i=this.addNotebookCell(e,t,n);return this.createExecutionPromise(i,r)}));return a[a.length-1]}disconnectKernel(){this.kernelDisposables.forEach((e=>e.dispose())),this.kernelDisposables=[],this._kernelPromise.resolved&&(this._kernelPromise=(0,C.createDeferred)())}async createExecutionPromise(e,t){(0,a.traceInfoIfCI)("InteractiveWindow.ts.createExecutionPromise.start");const[n,{cell:r,wasScrolled:i},o]=await Promise.all([this._kernelPromise.promise,e,this._editorReadyPromise]);if(!n)return!1;let s,c=!0;const l=this.configuration.getSettings(this.owningResource);(l.alwaysScrollOnNewCell||i)&&this.revealCell(r,o,!1);try{t&&(await this.interactiveWindowDebugger.attach(n),s=n.onPreExecute((e=>{e===r&&this.interactiveWindowDebugger.enable(n)}))),(0,a.traceInfoIfCI)("InteractiveWindow.ts.createExecutionPromise.kernel.executeCell"),c=await n.executeCell(r)!==f.NotebookCellRunState.Error,(0,a.traceInfoIfCI)("InteractiveWindow.ts.createExecutionPromise.kernel.executeCell.finished"),(l.alwaysScrollOnNewCell||i)&&this.revealCell(r,o,!1)}finally{t&&await this.interactiveWindowDebugger.detach(n),s&&s.dispose(),(0,a.traceInfoIfCI)("InteractiveWindow.ts.createExecutionPromise.end")}if(!c)throw new w.InteractiveCellResultError;return c}async runInitialization(e,t){t?(await this.setFileInKernel(t.fsPath,e),(0,a.traceInfoIfCI)("file in kernel set for IW")):(0,a.traceInfoIfCI)("Unable to run initialization for IW")}async expandAllCells(){const e=await this._editorReadyPromise;await Promise.all(e.document.getCells().map((async(t,n)=>{await this.commandManager.executeCommand("notebook.cell.expandCellInput",{ranges:[{start:n,end:n+1}],document:e.document.uri})})))}async collapseAllCells(){const e=await this._editorReadyPromise;await Promise.all(e.document.getCells().map((async(t,n)=>{t.kind===o.NotebookCellKind.Code&&await this.commandManager.executeCommand("notebook.cell.collapseCellInput",{ranges:[{start:n,end:n+1}],document:e.document.uri})})))}async scrollToCell(e){const t=await this._editorReadyPromise;await this.show();const n=t.document.getCells().find((t=>{var n;return(null===(n=D(t))||void 0===n?void 0:n.id)===e}));n&&this.revealCell(n,t,!0)}revealCell(e,t,n){const r=new o.NotebookRange(e.index,e.index+1);this.pendingNotebookScrolls.push(r);const i=n?o.notebooks.createNotebookEditorDecorationType({backgroundColor:new o.ThemeColor("peekViewEditor.background"),top:{}}):void 0;setTimeout((()=>{t.revealRange(r,o.NotebookEditorRevealType.Default),this.pendingNotebookScrolls.shift(),i&&(t.setDecorations(i,r),setTimeout((()=>{i.dispose()}),2e3))}),200)}async hasCell(e){const t=await this._editorReadyPromise;return!!t&&t.document.getCells().some((t=>{var n;return(null===(n=D(t))||void 0===n?void 0:n.id)===e}))}get owningResource(){if(this.owner)return this.owner;const e=this.workspaceService.rootPath;return e?o.Uri.file(e):void 0}async setFileInKernel(e,t){("perFile"!==this.mode||this.fileInKernel)&&(this.fileInKernel&&this.fs.areLocalPathsSame(this.fileInKernel,e)||"perFile"===this.mode)?(0,a.traceInfoIfCI)(`Not Initializing __file__ in setFileInKernel with ${e} for mode ${this.mode} currently ${this.fileInKernel}`):((0,a.traceInfoIfCI)(`Initializing __file__ in setFileInKernel with ${e} for mode ${this.mode}`),this.fileInKernel=e,await t.executeHidden(`__file__ = '${e.replace(/\\/g,"\\\\")}'`))}updateOwners(e){this._owner||(this._owner=e),this._submitters.find((t=>t.toString()==e.toString()))||this._submitters.push(e)}async addNotebookCell(e,t,n){var r,i;const a=await this._editorReadyPromise,l=a.document,u=null!=(null==a?void 0:a.visibleRanges.find((e=>e.end===a.document.cellCount)))||null!=this.pendingNotebookScrolls.find((e=>e.end==a.document.cellCount-1)),d=this.configuration.getSettings(this.owningResource),p=this.cellMatcher.getCellType(e)===s.MARKDOWN_LANGUAGE,h=p?(0,g.generateMarkdownFromCodeLines)(e.splitLines()).join(""):(0,v.generateInteractiveCode)(e,d,this.cellMatcher),f=this.cellMatcher.getFirstMarker(e),m=null!==(i=null===(r=o.workspace.textDocuments.find((e=>{var t;return e.uri.toString()===(null===(t=this.owner)||void 0===t?void 0:t.toString())})))||void 0===r?void 0:r.languageId)&&void 0!==i?i:s.PYTHON_LANGUAGE,y=new o.NotebookCellData(p?o.NotebookCellKind.Markup:o.NotebookCellKind.Code,h,p?s.MARKDOWN_LANGUAGE:m);y.metadata={interactiveWindowCellMarker:f,interactive:{uristring:t.toString(),line:n,originalSource:e},id:c()},await(0,x.chainWithPendingUpdates)(l,(e=>{e.replaceNotebookCells(l.uri,new o.NotebookRange(l.cellCount,l.cellCount),[y])}));const b=l.cellAt(l.cellCount-1);return(d.alwaysScrollOnNewCell||u)&&this.revealCell(b,a,!1),{cell:b,wasScrolled:u}}async export(){const e=await this._editorReadyPromise;if(!this.extensionChecker.isPythonExtensionInstalled)return this.extensionChecker.showPythonExtensionInstallRequiredPrompt();const{magicCommandsAsComments:t}=this.configuration.getSettings(this.owningResource),n=(0,u.generateCellsFromNotebookDocument)(e.document,t);if(n&&this.exportDialog){const e=await this.exportDialog.showDialog(h.ExportFormat.ipynb,this.owningResource);e&&await this.jupyterExporter.exportToFile(n,e.fsPath)}}async exportAs(){const e=await this._kernelPromise.promise;if(!this.extensionChecker.isPythonExtensionInstalled)return this.extensionChecker.showPythonExtensionInstallRequiredPrompt();const t={orig_nbformat:p.defaultNotebookFormat.major};let n;if(e&&(0,T.updateNotebookMetadata)(t,e.kernelConnectionMetadata),this.submitters&&this.submitters.length){const e=this.submitters[this.submitters.length-1];n=i.basename(e.fsPath,i.extname(e.fsPath))}this.commandManager.executeCommand(p.Commands.Export,this.notebookDocument,n,null==e?void 0:e.kernelConnectionMetadata.interpreter).then(l.noop,l.noop)}}r([(0,_.chainable)()],I.prototype,"addMessage",null),r([(0,_.chainable)()],I.prototype,"createExecutionPromise",null),r([(0,_.chainable)()],I.prototype,"addNotebookCell",null),t.InteractiveWindow=I},47190:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InteractiveWindowCommandListener=void 0,n(30895);const o=n(86700),s=n(66828),a=n(13395),c=n(97784),l=n(46318),u=n(60593),d=n(71733),p=n(35952),h=n(97045),f=n(89878),m=n(83099),g=n(4036),v=n(70214),y=n(75550),b=n(5448),_=n(41292),w=n(24453),S=n(73913),C=n(52194);let k=class{constructor(e,t,n,r,i,o,s,a,c,l,u,d,p,h,f,m,g){this.disposableRegistry=e,this.interactiveWindowProvider=t,this.jupyterExporter=n,this.jupyterExecution=r,this.documentManager=i,this.applicationShell=o,this.fileSystem=s,this.configuration=a,this.statusProvider=c,this.dataScienceErrorHandler=l,this.ipynbProvider=u,this.fileConverter=d,this.exportDialog=p,this.clipboard=h,this.notebook=f,this.commandManager=m,this.controllerManager=g}register(e){let t=e.registerCommand(g.Commands.CreateNewInteractive,(e=>this.createNewInteractiveWindow(e)));this.disposableRegistry.push(t),t=e.registerCommand(g.Commands.ImportNotebook,((e,t=f.CommandSource.commandPalette)=>this.listenForErrors((()=>e?this.importNotebookOnFile(e):this.importNotebook())))),this.disposableRegistry.push(t),t=e.registerCommand(g.Commands.ImportNotebookFile,((e,t=f.CommandSource.commandPalette)=>this.listenForErrors((()=>e?this.importNotebookOnFile(e):this.importNotebook())))),this.disposableRegistry.push(t),t=e.registerCommand(g.Commands.ExportFileAsNotebook,((e,t=f.CommandSource.commandPalette)=>this.listenForErrors((()=>{if(e)return this.exportFile(e);{const e=this.documentManager.activeTextEditor;if(e&&e.document.languageId===c.PYTHON_LANGUAGE)return this.exportFile(e.document.uri)}return Promise.resolve()})))),this.disposableRegistry.push(t),t=e.registerCommand(g.Commands.ExportFileAndOutputAsNotebook,((e,t=f.CommandSource.commandPalette)=>this.listenForErrors((()=>{if(e)return this.exportFileAndOutput(e);{const e=this.documentManager.activeTextEditor;if(e&&e.document.languageId===c.PYTHON_LANGUAGE)return this.exportFileAndOutput(e.document.uri)}return Promise.resolve()})))),this.disposableRegistry.push(t),this.disposableRegistry.push(e.registerCommand(g.Commands.ExpandAllCells,(async e=>{var t;return this.expandAllCells(null===(t=null==e?void 0:e.notebookEditor)||void 0===t?void 0:t.notebookUri)}))),this.disposableRegistry.push(e.registerCommand(g.Commands.CollapseAllCells,(async e=>{var t;return this.collapseAllCells(null===(t=null==e?void 0:e.notebookEditor)||void 0===t?void 0:t.notebookUri)}))),this.disposableRegistry.push(e.registerCommand(g.Commands.ExportOutputAsNotebook,(()=>this.exportCells()))),this.disposableRegistry.push(e.registerCommand(g.Commands.InteractiveExportAsNotebook,(e=>{var t;return this.export(null===(t=null==e?void 0:e.notebookEditor)||void 0===t?void 0:t.notebookUri)}))),this.disposableRegistry.push(e.registerCommand(g.Commands.InteractiveExportAs,(e=>{var t;return this.exportAs(null===(t=null==e?void 0:e.notebookEditor)||void 0===t?void 0:t.notebookUri)}))),this.disposableRegistry.push(e.registerCommand(g.Commands.ScrollToCell,((e,t)=>this.scrollToCell(e,t)))),this.disposableRegistry.push(e.registerCommand(g.Commands.InteractiveClearAll,this.clearAllCellsInInteractiveWindow,this)),this.disposableRegistry.push(e.registerCommand(g.Commands.InteractiveRemoveCell,this.removeCellInInteractiveWindow,this)),this.disposableRegistry.push(e.registerCommand(g.Commands.InteractiveGoToCode,this.goToCodeInInteractiveWindow,this)),this.disposableRegistry.push(e.registerCommand(g.Commands.InteractiveCopyCell,this.copyCellInInteractiveWindow,this))}async listenForErrors(e){let t;try{return t=await e(),t}catch(e){(0,l.traceError)("listenForErrors",e),this.dataScienceErrorHandler.handleError(e)}return t}async exportFile(e){if(e&&e.fsPath&&e.fsPath.length>0){const t=this.documentManager.activeTextEditor;if(t&&this.fileSystem.arePathsSame(t.document.uri,e)){const n=(0,m.generateCellsFromDocument)(t.document,this.configuration.getSettings(t.document.uri));if(n){const r=await this.exportDialog.showDialog(v.ExportFormat.ipynb,e);if(await this.waitForStatus((async()=>{if(r){let e;this.configuration.getSettings(t.document.uri).changeDirOnImportExport&&(e=r);const i=await this.jupyterExporter.translateToNotebook(n,null==e?void 0:e.fsPath);await this.fileSystem.writeFile(r,JSON.stringify(i))}}),p.DataScience.exportingFormat(),e.fsPath),r&&r.fsPath){const e=p.DataScience.exportOpenQuestion1();await this.applicationShell.showInformationMessage(p.DataScience.exportDialogComplete().format(r.fsPath),e)===e&&await this.ipynbProvider.open(r)}}}}}async exportFileAndOutput(e){if(e&&e.fsPath&&e.fsPath.length>0&&await this.jupyterExecution.isNotebookSupported()){const t=this.documentManager.activeTextEditor;if(t&&t.document&&this.fileSystem.arePathsSame(t.document.uri,e)){const n=(0,m.generateCellsFromDocument)(t.document,this.configuration.getSettings(t.document.uri));if(n){const r=await this.exportDialog.showDialog(v.ExportFormat.ipynb,e);if(!r)return;await this.waitForStatus((async()=>{if(r){let e;this.configuration.getSettings(t.document.uri).changeDirOnImportExport&&(e=r);const i=await this.jupyterExporter.translateToNotebook(n,null==e?void 0:e.fsPath);await this.fileSystem.writeFile(r,JSON.stringify(i))}}),p.DataScience.exportingFormat(),e.fsPath),await this.notebook.showNotebookDocument(r,{preserveFocus:!1,viewColumn:s.ViewColumn.Beside});const i=await this.controllerManager.getActiveInterpreterOrDefaultController(S.JupyterNotebookView,e);return i&&await this.commandManager.executeCommand("notebook.selectKernel",{id:i.id,extension:c.JVSC_EXTENSION_ID}),await this.commandManager.executeCommand("notebook.execute"),r}}}else await this.dataScienceErrorHandler.handleError(new y.JupyterInstallError(p.DataScience.jupyterNotSupported().format(await this.jupyterExecution.getNotebookError())))}async expandAllCells(e){const t=this.getTargetInteractiveWindow(e);(0,l.traceInfo)(`Expanding all cells in interactive window with uri ${null==t?void 0:t.notebookUri}`),t&&await t.expandAllCells()}async collapseAllCells(e){const t=this.getTargetInteractiveWindow(e);(0,l.traceInfo)(`Collapsing all cells in interactive window with uri ${null==t?void 0:t.notebookUri}`),t&&await t.collapseAllCells()}exportCells(){const e=this.interactiveWindowProvider.activeWindow;e&&e.export()}exportAs(e){const t=this.getTargetInteractiveWindow(e);t&&t.exportAs()}export(e){const t=this.getTargetInteractiveWindow(e);t&&t.export()}async createNewInteractiveWindow(e){await this.interactiveWindowProvider.getOrCreate(void 0,e)}waitForStatus(e,t,n,r){const i=n?t.format(n):t;return this.statusProvider.waitWithStatus(e,i,void 0,r)}async importNotebook(){const e={};e[p.DataScience.importDialogFilter()]=["ipynb"];const t=await this.applicationShell.showOpenDialog({openLabel:p.DataScience.importDialogTitle(),filters:e});t&&t.length>0&&await this.waitForStatus((async()=>{await this.fileConverter.importIpynb(t[0])}),p.DataScience.importingFormat(),t[0].fsPath)}async importNotebookOnFile(e){e.fsPath&&e.fsPath.length>0&&await this.waitForStatus((async()=>{await this.fileConverter.importIpynb(e)}),p.DataScience.importingFormat(),e.fsPath)}async scrollToCell(e,t){if(t&&e){const n=this.interactiveWindowProvider.windows.filter((t=>t.submitters.findIndex((t=>this.fileSystem.areLocalPathsSame(t.fsPath,e.fsPath)))>=0));for(let e=0;ee.uri.toString()===r.toString()));if(!i)return;const o=new s.WorkspaceEdit;o.replaceNotebookCells(i.uri,new s.NotebookRange(0,i.cellCount),[]),await s.workspace.applyEdit(o)}async removeCellInInteractiveWindow(e){var t,n;const r=(0,_.getActiveInteractiveWindow)(this.interactiveWindowProvider),i=void 0===e?null===(t=null==r?void 0:r.notebookEditor)||void 0===t?void 0:t.selections:[new s.NotebookRange(e.index,e.index+1)],o=void 0===e?null===(n=null==r?void 0:r.notebookEditor)||void 0===n?void 0:n.document:e.notebook;void 0!==i&&void 0!==o&&await(0,C.chainWithPendingUpdates)(o,(e=>{i.forEach((t=>e.replaceNotebookCells(o.uri,t,[])))}))}async goToCodeInInteractiveWindow(e){var t;if(e&&(null===(t=e.metadata)||void 0===t?void 0:t.interactive)){const t=s.Uri.parse(e.metadata.interactive.uristring),n=e.metadata.interactive.line,r=await this.documentManager.showTextDocument(t,{viewColumn:s.ViewColumn.One});r&&(r.revealRange(new s.Range(n,0,n,0)),r.selection=new s.Selection(new s.Position(n,0),new s.Position(n,0)))}}async copyCellInInteractiveWindow(e){var t;if(e){const n=this.configuration.getSettings(e.notebook.uri),r=[null!==(t=e.metadata.interactiveWindowCellMarker)&&void 0!==t?t:n.defaultCellMarker,e.document.getText()].join("\n");await this.clipboard.writeText(r)}}getTargetInteractiveWindow(e){let t;return t=void 0!==e?this.interactiveWindowProvider.windows.find((t=>{var n;return(null===(n=t.notebookUri)||void 0===n?void 0:n.toString())===e.toString()})):(0,_.getActiveInteractiveWindow)(this.interactiveWindowProvider),t}};r([(0,h.captureTelemetry)(g.Telemetry.ExportPythonFileInteractive,void 0,!1)],k.prototype,"exportFile",null),r([(0,h.captureTelemetry)(g.Telemetry.ExportPythonFileAndOutputInteractive,void 0,!1)],k.prototype,"exportFileAndOutput",null),r([(0,h.captureTelemetry)(g.Telemetry.CreateNewInteractive,void 0,!1)],k.prototype,"createNewInteractiveWindow",null),r([(0,h.captureTelemetry)(g.Telemetry.ImportNotebook,{scope:"command"},!1)],k.prototype,"importNotebook",null),r([(0,h.captureTelemetry)(g.Telemetry.ImportNotebook,{scope:"file"},!1)],k.prototype,"importNotebookOnFile",null),k=r([(0,o.injectable)(),i(0,(0,o.inject)(d.IDisposableRegistry)),i(1,(0,o.inject)(b.IInteractiveWindowProvider)),i(2,(0,o.inject)(b.INotebookExporter)),i(3,(0,o.inject)(b.IJupyterExecution)),i(4,(0,o.inject)(a.IDocumentManager)),i(5,(0,o.inject)(a.IApplicationShell)),i(6,(0,o.inject)(u.IFileSystem)),i(7,(0,o.inject)(d.IConfigurationService)),i(8,(0,o.inject)(b.IStatusProvider)),i(9,(0,o.inject)(b.IDataScienceErrorHandler)),i(10,(0,o.inject)(b.INotebookEditorProvider)),i(11,(0,o.inject)(v.IFileConverter)),i(12,(0,o.inject)(v.IExportDialog)),i(13,(0,o.inject)(a.IClipboard)),i(14,(0,o.inject)(a.IVSCodeNotebook)),i(15,(0,o.inject)(a.ICommandManager)),i(16,(0,o.inject)(w.INotebookControllerManager))],k),t.InteractiveWindowCommandListener=k},39519:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InteractiveWindowProvider=t.AskedForPerFileSettingKey=void 0;const o=n(86700),s=n(66828),a=n(98501),c=n(13395),l=n(46318),u=n(60593),d=n(71733),p=n(28735),h=n(35952),f=n(95063),m=n(29474),g=n(70214),v=n(24453),y=n(5448),b=n(73909);t.AskedForPerFileSettingKey="ds_asked_per_file_interactive";let _=class{constructor(e,t,n,r,i,o,a,c,l){this.serviceContainer=e,this.disposables=n,this.fs=r,this.configService=i,this.globalMemento=o,this.appShell=a,this.workspaceService=c,this.notebookControllerManager=l,this._onDidChangeActiveInteractiveWindow=new s.EventEmitter,this._onDidCreateInteractiveWindow=new s.EventEmitter,this._windows=[],t.push(this)}get onDidChangeActiveInteractiveWindow(){return this._onDidChangeActiveInteractiveWindow.event}get onDidCreateInteractiveWindow(){return this._onDidCreateInteractiveWindow.event}get activeWindow(){return this._windows.find((e=>{var t,n;return void 0!==s.window.activeNotebookEditor&&(null===(t=e.notebookUri)||void 0===t?void 0:t.toString())===(null===(n=s.window.activeNotebookEditor)||void 0===n?void 0:n.document.uri.toString())}))}get windows(){return this._windows}async getOrCreate(e,t){if(!this.workspaceService.isTrusted)throw new Error("Worksapce not trusted");const n=await this.getInteractiveMode(e);let r=this.getExisting(e,n,t);return r||(r=this.create(e,n,t)),await r.ready,r}get(e){const t=this.configService.getSettings(e).interactiveWindowMode;return this.getExisting(e,t)}async dispose(){return(0,f.noop)()}create(e,t,n){const r=new b.InteractiveWindow(this.serviceContainer.get(c.IDocumentManager),this.serviceContainer.get(u.IFileSystem),this.serviceContainer.get(d.IConfigurationService),this.serviceContainer.get(c.ICommandManager),this.serviceContainer.get(y.INotebookExporter),this.serviceContainer.get(c.IWorkspaceService),e,t,this.serviceContainer.get(a.IPythonExtensionChecker),this.serviceContainer.get(g.IExportDialog),this.notebookControllerManager,this.serviceContainer,this.serviceContainer.get(y.IInteractiveWindowDebugger),n);this._windows.push(r),this.lastActiveInteractiveWindow=r;const i=r.closed(this.onInteractiveWindowClosed.bind(this,r));return this.disposables.push(r),this.disposables.push(i),this.disposables.push(r.onDidChangeViewState(this.raiseOnDidChangeActiveInteractiveWindow.bind(this))),this._onDidCreateInteractiveWindow.fire(r),r}async getInteractiveMode(e){var n;let r=this.configService.getSettings(e).interactiveWindowMode;if("multiple"===r&&e&&!this.globalMemento.get(t.AskedForPerFileSettingKey)&&1===this._windows.length&&(null===(n=this._windows[0].owner)||void 0===n?void 0:n.fsPath)!==e.fsPath){this.globalMemento.update(t.AskedForPerFileSettingKey,!0).then(f.noop,f.noop);const n=[h.DataScience.interactiveWindowModeBannerSwitchYes(),h.DataScience.interactiveWindowModeBannerSwitchNo()];await this.appShell.showInformationMessage(h.DataScience.interactiveWindowModeBannerTitle(),...n)===n[0]&&(r="perFile",this._windows[0].changeMode(r),await this.configService.updateSetting("interactiveWindowMode",r,e,s.ConfigurationTarget.Global))}return r}getExisting(e,t,n){return"single"===t?this._windows.length>0?this._windows[0]:void 0:"multiple"===t?e?this.activeWindow||this.lastActiveInteractiveWindow||this._windows[0]:void 0:this._windows.find((t=>{var r;return!(e||t.owner||n)||!!(e&&t.owner&&this.fs.areLocalPathsSame(e.fsPath,t.owner.fsPath))&&(!n||(null===(r=t.originalConnection)||void 0===r?void 0:r.id)===n.id)}))}raiseOnDidChangeActiveInteractiveWindow(){this.lastActiveInteractiveWindow=this.activeWindow?this.activeWindow:this.lastActiveInteractiveWindow,this._onDidChangeActiveInteractiveWindow.fire(this.activeWindow)}onInteractiveWindowClosed(e){var t;(0,l.traceInfo)(`Closing interactive window: ${null===(t=e.notebookUri)||void 0===t?void 0:t.toString()}`),e.dispose(),this._windows=this._windows.filter((t=>t!==e)),this.lastActiveInteractiveWindow===e&&(this.lastActiveInteractiveWindow=this._windows[0]),this.raiseOnDidChangeActiveInteractiveWindow()}};r([(0,p.chainable)()],_.prototype,"getOrCreate",null),_=r([(0,o.injectable)(),i(0,(0,o.inject)(m.IServiceContainer)),i(1,(0,o.inject)(d.IAsyncDisposableRegistry)),i(2,(0,o.inject)(d.IDisposableRegistry)),i(3,(0,o.inject)(u.IFileSystem)),i(4,(0,o.inject)(d.IConfigurationService)),i(5,(0,o.inject)(d.IMemento)),i(5,(0,o.named)(d.GLOBAL_MEMENTO)),i(6,(0,o.inject)(c.IApplicationShell)),i(7,(0,o.inject)(c.IWorkspaceService)),i(8,(0,o.inject)(v.INotebookControllerManager))],_),t.InteractiveWindowProvider=_},74384:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerTypes=void 0;const r=n(78277),i=n(5448),o=n(23646),s=n(15910),a=n(48734),c=n(97879),l=n(52396),u=n(10712),d=n(5127),p=n(99326),h=n(47190),f=n(39519);t.registerTypes=function(e){e.addSingleton(i.IInteractiveWindowProvider,f.InteractiveWindowProvider),e.addSingleton(i.IDataScienceCommandListener,h.InteractiveWindowCommandListener),e.addSingleton(o.CommandRegistry,o.CommandRegistry),e.addSingleton(r.IExtensionSyncActivationService,p.HoverProvider),e.add(i.ICodeWatcher,u.CodeWatcher),e.addSingleton(i.ICodeLensFactory,c.CodeLensFactory),e.addSingleton(i.IDataScienceCodeLensProvider,l.DataScienceCodeLensProvider),e.addSingleton(r.IExtensionSingleActivationService,d.Decorator),e.addSingleton(s.ExportCommands,s.ExportCommands),e.addSingleton(a.CellHashProviderFactory,a.CellHashProviderFactory)}},80529:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseJupyterSession=t.JupyterSessionStartError=void 0;const r=n(37875),i=n(66828),o=n(3108),s=n(2687),a=n(46318),c=n(7744),l=n(35952),u=n(95063),d=n(72858),p=n(51129),h=n(97045),f=n(83474),m=n(1593),g=n(83044),v=n(46120),y=n(14311),b=n(34645),_=n(93865);class w extends o.WrappedError{constructor(e){super(e.message,e),(0,h.sendTelemetryEvent)(f.Telemetry.StartSessionFailedJupyter,void 0,void 0,e,!0)}}t.JupyterSessionStartError=w,t.BaseJupyterSession=class{constructor(e,t,n,o,s){this.resource=e,this.kernelConnectionMetadata=t,this.restartSessionUsed=n,this.workingDirectory=o,this.interruptTimeout=s,this._disposed=new i.EventEmitter,this.disposables=[],this.onStatusChangedEvent=new i.EventEmitter,this.connected=!1,this._kernelSocket=new r.ReplaySubject,this.ioPubEventEmitter=new i.EventEmitter,this.chainingExecute=new _.ChainingExecuteRequester,this.statusHandler=this.onStatusChanged.bind(this),this.ioPubHandler=(e,t)=>this.ioPubEventEmitter.fire(t),this.unhandledMessageHandler=(e,t)=>{(0,a.traceInfo)(`Unhandled message found: ${t.header.msg_type}`)}}get disposed(){return!0===this._isDisposed}get onDidDispose(){return this._disposed.event}get session(){return this._session}get kernel(){var e;return(null===(e=this._session)||void 0===e?void 0:e.kernel)||void 0}get kernelSocket(){return this._kernelSocket}get onSessionStatusChanged(){return this.onStatusChangedEvent.event}get onIOPubMessage(){return this.ioPubEventEmitter||(this.ioPubEventEmitter=new i.EventEmitter),this.ioPubEventEmitter.event}get status(){return this.getServerStatus()}get isConnected(){return this.connected}async dispose(){await this.shutdownImplementation(!1)}async shutdown(){await this.shutdownImplementation(!0)}async interrupt(){this.session&&this.session.kernel&&((0,a.traceInfo)(`Interrupting kernel: ${this.session.kernel.name}`),await Promise.race([this.session.kernel.interrupt(),(0,c.sleep)(this.interruptTimeout).then((()=>{throw new v.KernelInterruptTimeoutError(this.kernelConnectionMetadata)}))]))}async requestKernelInfo(){var e,t;if(!this.session)throw new Error("Cannot request KernelInfo, Session not initialized.");if(null===(e=this.session.kernel)||void 0===e?void 0:e.info){const e={content:await this.session.kernel.info,channel:"shell",metadata:{},parent_header:{},header:{}};return Promise.resolve(e)}return null===(t=this.session.kernel)||void 0===t?void 0:t.requestKernelInfo()}async restart(){var e,t,n;if((null===(e=this.session)||void 0===e?void 0:e.isRemoteSession)&&this.session.kernel)return await this.session.kernel.restart(),void this.setSession(this.session,!0);if(this.restartSessionPromise||this.startRestartSession(!1),!this.restartSessionPromise)throw new y.SessionDisposedError;{(0,a.traceInfo)(`Restarting ${null===(n=null===(t=this.session)||void 0===t?void 0:t.kernel)||void 0===n?void 0:n.id}`);const e=this.session,r=this.statusHandler,i=await this.restartSessionPromise.promise;this.setSession(i),i.kernel&&(this.restartSessionUsed(i.kernel),(0,a.traceInfo)(`Got new session ${i.kernel.id}`),i.statusChanged.connect(this.statusHandler)),this.restartSessionPromise.token.dispose(),this.restartSessionPromise=void 0,(0,a.traceInfo)("Started new restart session"),r&&e&&e.statusChanged.disconnect(r),this.shutdownSession(e,void 0,!1).ignoreErrors()}}requestExecute(e,t,n){var r;if(!(null===(r=this.session)||void 0===r?void 0:r.kernel))throw new y.SessionDisposedError;return this.chainingExecute.requestExecute(this.session.kernel,e,t,n)}requestDebug(e,t){var n;if(!(null===(n=this.session)||void 0===n?void 0:n.kernel))throw new y.SessionDisposedError;return this.session.kernel.requestDebug(e,t)}requestInspect(e){var t;if(!(null===(t=this.session)||void 0===t?void 0:t.kernel))throw new y.SessionDisposedError;return this.session.kernel.requestInspect(e)}requestComplete(e){var t;if(!(null===(t=this.session)||void 0===t?void 0:t.kernel))throw new y.SessionDisposedError;return this.session.kernel.requestComplete(e)}sendInputReply(e){this.session&&this.session.kernel&&this.session.kernel.sendInputReply(e)}registerCommTarget(e,t){if(!this.session||!this.session.kernel)throw new y.SessionDisposedError;this.session.kernel.registerCommTarget(e,t)}registerMessageHook(e,t){var n;if(null===(n=this.session)||void 0===n?void 0:n.kernel)return this.session.kernel.registerMessageHook(e,t);throw new y.SessionDisposedError}removeMessageHook(e,t){var n;if(null===(n=this.session)||void 0===n?void 0:n.kernel)return this.session.kernel.removeMessageHook(e,t);throw new y.SessionDisposedError}async waitForIdleOnSession(e,t,n){var r,i;if(!e||!e.kernel)throw new m.JupyterInvalidKernelError(this.kernelConnectionMetadata);{const o=n?void 0:p.KernelProgressReporter.reportProgress(this.resource,l.DataScience.waitingForJupyterSessionToBeIdle());try{(0,a.traceInfo)(`Waiting for idle on (kernel): ${e.kernel.id} -> ${e.kernel.status}`);const s=(0,c.createDeferred)(),l=(e,t)=>{(0,a.traceVerbose)(`Got status ${t} in waitForIdleOnSession`),"idle"==t&&s.resolve(t)};null===(r=e.kernel.statusChanged)||void 0===r||r.connect(l),"idle"==e.kernel.status&&s.resolve(e.kernel.status);const u=await Promise.race([s.promise,(0,c.sleep)(t)]);if(null===(i=e.kernel.statusChanged)||void 0===i||i.disconnect(l),(0,a.traceInfo)(`Finished waiting for idle on (kernel): ${e.kernel.id} -> ${e.kernel.status}`),"idle"==u.toString())return;throw(0,a.traceError)(`Shutting down after failing to wait for idle on (kernel): ${e.kernel.id} -> ${e.kernel.status}`),this.shutdownSession(e,this.statusHandler,n).ignoreErrors(),new g.JupyterWaitForIdleError(this.kernelConnectionMetadata)}finally{null==o||o.dispose()}}}setSession(e,t=!1){const n=this._session;n&&(this.ioPubHandler&&n.iopubMessage.disconnect(this.ioPubHandler),this.unhandledMessageHandler&&n.unhandledMessage.disconnect(this.unhandledMessageHandler),this.statusHandler&&n.statusChanged.disconnect(this.statusHandler)),this._session=e,e&&(e.statusChanged.connect(this.statusHandler),e.iopubMessage&&e.iopubMessage.connect(this.ioPubHandler),e.unhandledMessage&&e.unhandledMessage.connect(this.unhandledMessageHandler),(t||n!==e)&&e.kernel&&this._kernelSocket.next({options:{clientId:e.kernel.clientId,id:e.kernel.id,model:{...e.kernel.model},userName:e.kernel.username},socket:e.kernelSocketInformation.socket}))}async shutdownSession(e,t,n,r){var i,o,s;if(e&&e.kernel){const l=`${e.kernel.id}, ${null===(i=e.kernelConnectionMetadata)||void 0===i?void 0:i.id}`;(0,a.traceVerbose)(`shutdownSession ${l} - start`);try{if(t&&e.statusChanged.disconnect(t),!this.canShutdownSession(e,n,r))return(0,a.traceVerbose)(`Session cannot be shutdown ${null===(o=e.kernelConnectionMetadata)||void 0===o?void 0:o.id}`),void e.dispose();try{(0,a.traceVerbose)(`Session can be shutdown ${null===(s=e.kernelConnectionMetadata)||void 0===s?void 0:s.id}`),(0,b.suppressShutdownErrors)(e.kernel),e.isDisposed||await(0,c.waitForPromise)(e.shutdown(),1e3)}catch(e){(0,u.noop)()}e&&!e.isDisposed&&e.dispose()}catch(e){(0,a.traceWarning)(e)}(0,a.traceVerbose)(`shutdownSession ${l} - shutdown complete`)}}async shutdownImplementation(e){if(this._isDisposed=!0,this.session){try{if((0,a.traceVerbose)("Shutdown session - current session"),await this.shutdownSession(this.session,this.statusHandler,!1,e),(0,a.traceVerbose)("Shutdown session - get restart session"),this.restartSessionPromise){this.restartSessionPromise.token.cancel();const e=await this.restartSessionPromise.promise;this.restartSessionPromise.token.dispose(),(0,a.traceVerbose)("Shutdown session - shutdown restart session"),await this.shutdownSession(e,void 0,!0)}}catch(e){(0,u.noop)()}this.setSession(void 0),this.restartSessionPromise=void 0,this.onStatusChangedEvent.fire("dead"),this._disposed.fire(),this._disposed.dispose(),this.onStatusChangedEvent.dispose()}(0,s.disposeAllDisposables)(this.disposables),(0,a.traceVerbose)("Shutdown session -- complete")}canShutdownSession(e,t,n){var r;return!("connectToLiveKernel"===(null===(r=e.kernelConnectionMetadata)||void 0===r?void 0:r.kind)&&!n||!t&&(!e.resource||"interactive"!==(0,d.getResourceType)(e.resource))&&e.resource&&"notebook"===(0,d.getResourceType)(e.resource)&&!0===e.isRemoteSession&&!n)}getServerStatus(){var e,t;return this.disposed?"dead":(null===(e=this.session)||void 0===e?void 0:e.kernel)?this.session.kernel.status:((0,a.traceInfoIfCI)(`Kernel status not started because real session is ${this.session?"defined":"undefined"} & real kernel is ${(null===(t=this.session)||void 0===t?void 0:t.kernel)?"defined":"undefined"}`),"unknown")}onStatusChanged(e){const t=this.getServerStatus();(0,a.traceInfoIfCI)(`Server Status = ${t}`),this.onStatusChangedEvent.fire(t)}}},93865:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChainingExecuteRequester=void 0;const r=n(82159);t.ChainingExecuteRequester=class{requestExecute(e,t,n,i){var o;const s=this.previousExecute&&(null===(o=this.previousKernel)||void 0===o?void 0:o.id)===e.id?new r.DelayedFutureExecute(e,this.previousExecute,t,n,i):e.requestExecute(t,n,i);return this.previousExecute=s,this.previousKernel=e,s.done.then((()=>{this.previousExecute==s&&(this.previousExecute=void 0,this.previousKernel=void 0)})).catch((()=>{this.previousExecute==s&&(this.previousExecute=void 0,this.previousKernel=void 0)})),s}}},82159:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelayedFutureExecute=void 0;const r=n(33149),i=n(46318),o=n(7744);t.DelayedFutureExecute=class{constructor(e,t,n,i,s){var a;this.kernelConnection=e,this.content=n,this.disposeOnDone=i,this.metadata=s,this.doneDeferred=(0,o.createDeferred)(),this.pendingHooks=[],this.pendingInputReplies=[],this.disposed=!1,t.done.then((()=>this.requestExecute())).catch((e=>this.doneDeferred.reject(e))),this.statusChangedHandler=(e,t)=>{"unknown"!==t&&"restarting"!==t&&"dead"!==t&&"autorestarting"!==t||this.doneDeferred.reject(new r.CancellationError)},null===(a=e.statusChanged)||void 0===a||a.connect(this.statusChangedHandler),this.statusChangedHandler(e,e.status)}get msg(){return this.requestFuture?this.requestFuture.msg:{content:this.content,channel:"shell",header:{date:Date.now.toString(),msg_id:"1",session:this.kernelConnection.id,msg_type:"execute_request",username:"",version:"1"},parent_header:{},metadata:{}}}get done(){return this.doneDeferred.promise}set onReply(e){this.requestFuture?this.requestFuture.onReply=e:this.pendingOnReply=e}set onIOPub(e){this.requestFuture?this.requestFuture.onIOPub=e:this.pendingOnIOPub=e}set onStdin(e){this.requestFuture?this.requestFuture.onStdin=e:this.pendingOnStdin=e}registerMessageHook(e){this.requestFuture?this.requestFuture.registerMessageHook(e):this.pendingHooks.push(e)}removeMessageHook(e){this.pendingHooks=this.pendingHooks.filter((t=>t!=e)),this.requestFuture&&this.requestFuture.removeMessageHook(e)}sendInputReply(e){this.requestFuture?this.requestFuture.sendInputReply(e):this.pendingInputReplies.push(e)}get isDisposed(){return this.disposed}dispose(){this.disposed=!0,this.kernelConnection.statusChanged.disconnect(this.statusChangedHandler),this.requestFuture&&(this.requestFuture.dispose(),this.requestFuture=void 0,this.clear())}clear(){this.pendingInputReplies=[],this.pendingHooks=[],this.pendingOnReply=void 0,this.pendingOnIOPub=void 0,this.pendingOnStdin=void 0}requestExecute(){if(this.requestFuture)throw new Error("ChainedFuture already executed. Can't execute more than once.");(0,i.traceInfoIfCI)(`DelayedFuture is starting request now for ${this.content}.`),this.requestFuture=this.kernelConnection.requestExecute(this.content,this.disposeOnDone,this.metadata),this.requestFuture&&(this.pendingOnReply&&(this.requestFuture.onReply=this.pendingOnReply),this.pendingOnIOPub&&(this.requestFuture.onIOPub=this.pendingOnIOPub),this.pendingOnStdin&&(this.requestFuture.onStdin=this.pendingOnStdin),this.pendingHooks.length&&this.pendingHooks.forEach((e=>{var t;return null===(t=this.requestFuture)||void 0===t?void 0:t.registerMessageHook(e)})),this.pendingInputReplies&&this.pendingInputReplies.forEach((e=>{var t;return null===(t=this.requestFuture)||void 0===t?void 0:t.sendInputReply(e)})),this.requestFuture.done.then((e=>this.doneDeferred.resolve(e))).catch((e=>this.doneDeferred.reject(e))),this.clear())}}},8095:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KernelSocketWrapper=void 0,t.KernelSocketWrapper=function(e){return class extends e{constructor(...e){super(...e),this.msgChain=Promise.resolve(),this.sendChain=Promise.resolve(),this.receiveHooks=[],this.sendHooks=[]}sendToRealKernel(e,t){super.send(e,t)}send(e,t){this.sendHooks?this.sendChain=this.sendChain.then((()=>Promise.all(this.sendHooks.map((n=>n(e,t)))))).then((()=>super.send(e,t))):super.send(e,t)}emit(e,...t){return"message"===e&&this.receiveHooks.length?(this.msgChain=this.msgChain.then((()=>Promise.all(this.receiveHooks.map((e=>e(t[0])))))).then((()=>super.emit(e,...t))),!0):super.emit(e,...t)}addReceiveHook(e){this.receiveHooks.push(e)}removeReceiveHook(e){this.receiveHooks=this.receiveHooks.filter((t=>t!==e))}addSendHook(e){this.sendHooks.push(e)}removeSendHook(e){this.sendHooks=this.sendHooks.filter((t=>t!==e))}}}},53711:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InteractiveWindowDebugger=void 0;const o=n(86700),s=n(98501),a=n(46318),c=n(60593),l=n(71733),u=n(35952),d=n(5448),p=n(83474),h=n(18218),f=n(28025),m=n(93828),g=n(92201),v=n(43367);let y=class{constructor(e,t,n,r){this.debuggerPathProvider=e,this.configService=t,this.debugService=n,this.platform=r,this.configs=new WeakMap,this.debuggingActive=!1,this.debuggerPackage="debugpy",this.enableDebuggerCode="import debugpy;debugpy.listen(('localhost', 0))",this.waitForDebugClientCode="import debugpy;debugpy.wait_for_client()",this.tracingEnableCode="from debugpy import trace_this_thread;trace_this_thread(True)",this.tracingDisableCode="from debugpy import trace_this_thread;trace_this_thread(False)"}async attach(e){var t;if(!e.session)throw new Error("Notebook not initialized");const n=this.configService.getSettings(e.resourceUri),r=null===(t=e.kernelConnectionMetadata.interpreter)||void 0===t?void 0:t.path;return this.startDebugSession((e=>this.debugService.startDebugging(void 0,e)),e,{justMyCode:n.debugJustMyCode,python:r})}async detach(e){e.session&&this.configs.get(e.notebookDocument)&&((0,a.traceInfo)("stop debugging"),this.debuggingActive=!1,this.debugService.stop(),"dead"!==e.status&&"unknown"!==e.status&&this.disable(e))}async hashesUpdated(e){this.debugService.activeDebugSession&&this.debuggingActive&&((0,a.traceInfoIfCI)("Sending debug request for source map"),await Promise.all(e.map((async e=>{if(this.debuggingActive)return this.debugService.activeDebugSession.customRequest("setPydevdSourceMap",this.buildSourceMap(e))}))))}enable(e){e.session&&(0,m.executeSilently)(e.session,this.tracingEnableCode,{traceErrors:!0,traceErrorsMessage:"Execute_request failure enabling tracing code for IW",telemetryName:p.Telemetry.InteractiveWindowDebugSetupCodeFailure}).ignoreErrors()}disable(e){e.session&&(0,m.executeSilently)(e.session,this.tracingDisableCode,{traceErrors:!0,traceErrorsMessage:"Execute_request failure disabling tracing code for IW",telemetryName:p.Telemetry.InteractiveWindowDebugSetupCodeFailure}).ignoreErrors()}async startDebugSession(e,t,n){if((0,a.traceInfo)("start debugging"),!t.session)return;const r=await this.connect(t,n);if(r&&((0,a.traceInfo)("connected to notebook during debugging"),this.debuggingActive=await e(r),this.debuggingActive)){this.debugService.removeBreakpoints([]);const e=await(0,m.executeSilently)(t.session,this.waitForDebugClientCode,{traceErrors:!0,traceErrorsMessage:"Execute_request failure starting debug session for IW",telemetryName:p.Telemetry.InteractiveWindowDebugSetupCodeFailure});e.some((e=>"error"===e.output_type))?(0,a.traceWarning)(`${this.debuggerPackage} not found in path.`):(0,a.traceInfo)(`import startup: ${(0,g.getPlainTextOrStreamOutput)(e)}`),await this.disable(t)}}async connect(e,t){if(!e)return;const n=e.notebookDocument;let r=this.configs.get(n);if(r)return{...r,...t};if((0,a.traceInfo)("enable debugger attach"),await this.appendDebuggerPaths(e),r={type:"python",name:"IPython",request:"attach",...t},(0,v.isLocalConnection)(e.kernelConnectionMetadata)){const{host:t,port:n}=await this.connectToLocal(e);r.host=t,r.port=n}else{const{host:t,port:n}=await this.connectToRemote(e);r.host=t,r.port=n}if(r.port){this.configs.set(e.notebookDocument,r);const t=[],i=()=>{this.configs.delete(n),t.forEach((e=>e.dispose()))};t.push(e.onDisposed(i)),t.push(e.onRestarted(i))}return r}async calculateDebuggerPathList(e){const t=[];let n=this.configService.getSettings(e.resourceUri).debugpyDistPath;if(n&&(this.platform.isWindows&&(n=n.replace(/\\/g,"\\\\")),t.push(n)),(0,v.isLocalConnection)(e.kernelConnectionMetadata)){let e=await this.debuggerPathProvider.getDebuggerPath();this.platform.isWindows&&(e=e.replace(/\\/g,"\\\\")),t.push(e)}if(t&&t.length>0)return t.reduce(((e,t)=>0===e.length?`'${t}'`:`${e}, '${t}'`),"")}async appendDebuggerPaths(e){const t=await this.calculateDebuggerPathList(e);if(t&&t.length>0){const n=e.session?await(0,m.executeSilently)(e.session,`import sys\r\nsys.path.extend([${t}])\r\nsys.path`,{traceErrors:!0,traceErrorsMessage:"Execute_request failure appending debugger paths for IW",telemetryName:p.Telemetry.InteractiveWindowDebugSetupCodeFailure}):[];(0,a.traceInfo)(`Appending paths: ${(0,g.getPlainTextOrStreamOutput)(n)}`)}}buildSourceMap(e){const t={source:{path:e.uri.fsPath},pydevdSourceMaps:[]};return t.pydevdSourceMaps=e.hashes.map((e=>({line:e.debuggerStartLine,endLine:e.endLine,runtimeSource:{path:e.runtimeFile},runtimeLine:e.runtimeLine}))),t}async connectToLocal(e){const t=e.session?await(0,m.executeSilently)(e.session,this.enableDebuggerCode,{traceErrors:!0,traceErrorsMessage:"Execute_request failure enabling debugging for IW",telemetryName:p.Telemetry.InteractiveWindowDebugSetupCodeFailure}):[];if(t.length>0){let e=(0,g.getPlainTextOrStreamOutput)(t);if(e){e=e.trimQuotes();const t=/\('(.*?)', ([0-9]*)\)/.exec(e);if(t)return{port:parseInt(t[2],10),host:t[1]}}}if(t.length>0&&"error"===t[0].output_type){const n=t[0];throw new h.JupyterDebuggerNotInstalledError(this.debuggerPackage,n.ename,e.kernelConnectionMetadata)}throw new h.JupyterDebuggerNotInstalledError(u.DataScience.jupyterDebuggerOutputParseError().format(this.debuggerPackage),void 0,e.kernelConnectionMetadata)}async connectToRemote(e){throw new f.JupyterDebuggerRemoteNotSupportedError(e.kernelConnectionMetadata)}};y=r([(0,o.injectable)(),i(0,(0,o.inject)(s.IPythonDebuggerPathProvider)),i(1,(0,o.inject)(l.IConfigurationService)),i(2,(0,o.inject)(d.IJupyterDebugService)),i(2,(0,o.named)(p.Identifiers.MULTIPLEXING_DEBUGSERVICE)),i(3,(0,o.inject)(c.IPlatformService))],y),t.InteractiveWindowDebugger=y},3598:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterDebugService=void 0;const o=n(86700),s=n(41808),a=n(71017),c=n(71171),l=n(66828),u=n(46318),d=n(71733),p=n(7744),h=n(95063),f=n(46488),m=n(85109);class g{constructor(e,t,n){this._id=e,this._configuration=t,this.customRequestHandler=n,this._name="JupyterDebugSession",(0,h.noop)()}get id(){return this._id}get type(){return"python"}get name(){return this._name}get workspaceFolder(){}get configuration(){return this._configuration}customRequest(e,t){return this.customRequestHandler(e,t)}getDebugProtocolBreakpoint(e){return Promise.resolve(void 0)}}let v=class{constructor(e,t){this.protocolParser=e,this.sequence=1,this.breakpointEmitter=new l.EventEmitter,this.debugAdapterTrackerFactories=[],this.debugAdapterTrackers=[],this.sessionChangedEvent=new l.EventEmitter,this.sessionStartedEvent=new l.EventEmitter,this.sessionTerminatedEvent=new l.EventEmitter,this.sessionCustomEvent=new l.EventEmitter,this.breakpointsChangedEvent=new l.EventEmitter,this._breakpoints=[],t.push(this)}dispose(){this.socket&&(this.socket.end(),this.socket=void 0)}get activeDebugSession(){return this.session}get activeDebugConsole(){return{append(e){(0,h.noop)()},appendLine(e){(0,h.noop)()}}}get breakpoints(){return this._breakpoints}get onDidChangeActiveDebugSession(){return this.sessionChangedEvent.event}get onDidStartDebugSession(){return this.sessionStartedEvent.event}get onDidReceiveDebugSessionCustomEvent(){return this.sessionCustomEvent.event}get onDidTerminateDebugSession(){return this.sessionTerminatedEvent.event}get onDidChangeBreakpoints(){return this.breakpointsChangedEvent.event}registerDebugConfigurationProvider(e,t){return{dispose:()=>{(0,h.noop)()}}}registerDebugAdapterTrackerFactory(e,t){return this.debugAdapterTrackerFactories.push(t),{dispose:()=>{this.debugAdapterTrackerFactories=this.debugAdapterTrackerFactories.filter((e=>e!==t))}}}startRunByLine(e){return this.startDebugging(void 0,e)}startDebugging(e,t,n){const r=t;return r.port?(this.session=new g(c(),r,this.sendCustomRequest.bind(this)),this.sessionChangedEvent.fire(this.session),this.debugAdapterTrackers=this.debugAdapterTrackerFactories.map((e=>e.createDebugAdapterTracker(this.session))),this.socket=s.createConnection(r.port),this.protocolParser.connect(this.socket),this.protocolParser.on("event_stopped",this.onBreakpoint.bind(this)),this.protocolParser.on("event_output",this.onOutput.bind(this)),this.protocolParser.on("event_terminated",this.sendToTrackers.bind(this)),this.socket.on("error",this.onError.bind(this)),this.socket.on("close",this.onClose.bind(this)),this.sendStartSequence(r,this.session.id).then((()=>!0))):Promise.resolve(!0)}addBreakpoints(e){this._breakpoints=this._breakpoints.concat(e)}removeBreakpoints(e){(0,h.noop)()}get onBreakpointHit(){return this.breakpointEmitter.event}async continue(){await this.sendMessage("continue",{threadId:0}),this.sendToTrackers({type:"event",event:"continue"})}async step(){await this.sendMessage("stepIn",{threadId:this._stoppedThreadId?this._stoppedThreadId:1}),this.sendToTrackers({type:"event",event:"stepIn"})}async getStack(){const e=(0,p.createDeferred)();return this.protocolParser.once("response_stackTrace",(t=>{var n;this.sendToTrackers(t);const r=t,i=r.body.stackFrames?r.body.stackFrames:[];e.resolve(i),this._topFrameId=null===(n=i[0])||void 0===n?void 0:n.id})),await this.emitMessage("stackTrace",{threadId:this._stoppedThreadId?this._stoppedThreadId:1,startFrame:0,levels:1}),e.promise}async requestVariables(){await this.getStack();const e=(0,p.createDeferred)();let t=0;return this.protocolParser.once("response_scopes",(e=>{this.sendToTrackers(e),e&&(t=e.body.scopes[0].variablesReference),this.emitMessage("variables",{threadId:this._stoppedThreadId?this._stoppedThreadId:1,variablesReference:t}).ignoreErrors()})),this.protocolParser.once("response_variables",(t=>{this.sendToTrackers(t),e.resolve()})),await this.emitMessage("scopes",{frameId:this._topFrameId?this._topFrameId:1}),e.promise}stop(){this.onClose()}sendToTrackers(e){"request"===e.type?this.debugAdapterTrackers.forEach((t=>{t.onWillReceiveMessage&&t.onWillReceiveMessage(e)})):this.debugAdapterTrackers.forEach((t=>t.onDidSendMessage(e)))}sendCustomRequest(e,t){return this.sendMessage(e,t)}async sendStartSequence(e,t){(0,u.traceInfo)("Sending debugger initialize..."),await this.sendInitialize(),this._breakpoints.length>0&&((0,u.traceInfo)("Sending breakpoints"),await this.sendBreakpoints()),(0,u.traceInfo)("Sending debugger attach...");const n=this.sendAttach(e,t);return(0,u.traceInfo)("Sending configuration done"),await this.sendConfigurationDone(),(0,u.traceInfo)("Session started."),n.then((()=>{this.sessionStartedEvent.fire(this.session)}))}sendBreakpoints(){const e=this._breakpoints.map((e=>e)),t=e[0].location.uri.fsPath;return this.sendMessage("setBreakpoints",{source:{name:a.basename(t),path:t},lines:e.map((e=>e.location.range.start.line)),breakpoints:e.map((e=>({line:e.location.range.start.line}))),sourceModified:!0})}sendAttach(e,t){return this.sendMessage("attach",{debugOptions:["RedirectOutput","FixFilePathCase","WindowsClient","ShowReturnValue"],workspaceFolder:f.EXTENSION_ROOT_DIR,__sessionId:t,...e})}sendConfigurationDone(){return this.sendMessage("configurationDone")}sendInitialize(){return this.sendMessage("initialize",{clientID:"vscode",clientName:"Visual Studio Code",adapterID:"python",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0,supportsVariableType:!0,supportsVariablePaging:!0,supportsRunInTerminalRequest:!0,locale:"en-us"})}sendDisconnect(){return this.sendMessage("disconnect",{})}sendMessage(e,t){var n;const r=(0,p.createDeferred)(),i=this.sessionTerminatedEvent.event((()=>{r.resolve({body:{}})})),o=this.sequence;return this.protocolParser.on(`response_${e}`,(e=>{e.request_seq===o&&(this.sendToTrackers(e),(0,u.traceInfo)(`Received response from debugger: ${JSON.stringify(t)}`),i.dispose(),r.resolve(e.body))})),null===(n=this.socket)||void 0===n||n.on("error",(e=>r.reject(e))),this.emitMessage(e,t).catch((t=>{(0,u.traceError)(`Exception attempting to emit ${e} to debugger: `,t)})),r.promise}emitMessage(e,t){return new Promise(((n,r)=>{try{if(this.socket){const r={command:e,arguments:t,type:"request",seq:this.sequence};this.sequence+=1;const i=JSON.stringify(r);(0,u.traceInfo)(`Sending request to debugger: ${i}`);const o=`Content-Length: ${i.length}\r\n\r\n${i}`;this.socket.write(o,(e=>{this.sendToTrackers(r),n()}))}}catch(e){r(e)}}))}onBreakpoint(e){this._stoppedThreadId=e.body.threadId,this.sendToTrackers(e),this.breakpointEmitter.fire()}onOutput(e){this.sendToTrackers(e),(0,u.traceInfo)(JSON.stringify(e))}onError(e){this.sendToTrackers(e),(0,u.traceInfo)(JSON.stringify(e))}onClose(){this.socket&&(this.sessionTerminatedEvent.fire(this.activeDebugSession),this.session=void 0,this.sessionChangedEvent.fire(void 0),this.debugAdapterTrackers.forEach((e=>e.onExit?e.onExit(0,void 0):(0,h.noop)())),this.debugAdapterTrackers=[],this.sendDisconnect().ignoreErrors(),this.socket.destroy(),this.socket=void 0)}};v=r([(0,o.injectable)(),i(0,(0,o.inject)(m.IProtocolParser)),i(1,(0,o.inject)(d.IDisposableRegistry))],v),t.JupyterDebugService=v},93828:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.connectToKernel=t.wrapKernelMethodImpl=t.wrapKernelMethod=t.handleKernelError=t.notifyAndRestartDeadKernel=t.executeSilently=t.sendTelemetryForPythonKernelExecutable=t._findPreferredKernel=t.compareKernels=t.findPreferredKernel=t.getInterpreterHashInMetadata=t.isLocalLaunch=t.cleanEnvironment=t.detectDefaultKernelName=t.areKernelConnectionsEqual=t.createInterpreterKernelSpec=t.getKernelRegistrationInfo=t.getInterpreterWorkspaceFolder=t.getInterpreterKernelSpecName=t.getLanguageInKernelSpec=t.getLanguageInNotebookMetadata=t.getKernelConnectionLanguage=t.isPythonKernelSpec=t.isPythonKernelConnection=t.getInterpreterFromKernelConnectionMetadata=t.getKernelConnectionPath=t.getRemoteKernelSessionInformation=t.getKernelPathFromKernelConnection=t.getNameOfKernelConnection=t.getDisplayNameOrNameOfKernelConnection=t.getSysInfoReasonHeader=t.getKernelId=t.kernelConnectionMetadataHasKernelModel=t.kernelConnectionMetadataHasKernelSpec=t.findIndexOfConnectionFile=t.connectionFilePlaceholder=void 0;const r=n(71017),i=n(84266),o=n(50361),s=n(43367),a=n(66828),c=n(13395),l=n(97784),u=n(46318),d=n(29140),p=n(71733),h=n(7744),f=n(35952),m=n(72858),g=n(4036),v=n(65725),y=n(32417),b=n(5448),_=n(79262),w=n(97045),S=n(70403),C=n(44007),k=n(83474),E=n(17927),x=n(29299),T=n(69930),D=n(31092),I=n(80797),P=n(21687),R=n(82232),M=n(24453),O=n(18556),L=n(17261),N=n(58021);function A(e){return"connectToLiveKernel"!==e.kind}function j(e){return"connectToLiveKernel"===e.kind}function F(e){var t,n,r,i,o,s,a;const c=function(e){var t,n;if(!e)return"";const r="connectToLiveKernel"===e.kind?e.kernelModel.display_name:null===(t=e.kernelSpec)||void 0===t?void 0:t.display_name,i="connectToLiveKernel"===e.kind?e.kernelModel.name:null===(n=e.kernelSpec)||void 0===n?void 0:n.name,o="startUsingPythonInterpreter"===e.kind?e.interpreter.displayName:void 0;return r||i||o||""}(e);if(!e)return c;switch(e.kind){case"connectToLiveKernel":{const o=(0,D.removeNotebookSuffixAddedByExtension)((null===(n=null===(t=e.kernelModel)||void 0===t?void 0:t.notebook)||void 0===n?void 0:n.path)||(null===(i=null===(r=e.kernelModel)||void 0===r?void 0:r.model)||void 0===i?void 0:i.path)||"");return o?`${c} (${o})`:c}case"startUsingRemoteKernelSpec":case"startUsingLocalKernelSpec":if((null===(o=e.interpreter)||void 0===o?void 0:o.envType)&&e.interpreter.envType!==P.EnvironmentType.Global){const t=U(e.interpreter);if(e.kernelSpec.language===l.PYTHON_LANGUAGE){const t=`Python ${(0,S.getTelemetrySafeVersion)((null===(s=e.interpreter.version)||void 0===s?void 0:s.raw)||"")||""}`.trim();return e.interpreter.envName?`${c} (${t})`:c}return t?`${c} (${t})`:c}return c;case"startUsingPythonInterpreter":if(e.interpreter.envType&&e.interpreter.envType!==P.EnvironmentType.Global){const t=`Python ${(0,S.getTelemetrySafeVersion)((null===(a=e.interpreter.version)||void 0===a?void 0:a.raw)||"")||""}`.trim();if(e.kernelSpec.display_name&&"registeredByNewVersionOfExtForCustomKernelSpec"===$(e.kernelSpec))return e.kernelSpec.display_name;const n=t.trim(),r=U(e.interpreter);return r?`${r} (${n})`:n}}return c}function U(e){let t=e.envName;return e.envPath&&e.envType===P.EnvironmentType.Conda&&!e.envName&&(t=r.basename(e.envPath)),t}function q(e){var t,n,r,i;if(!e)return;const o=j(e)?e.kernelModel:void 0,s=A(e)?e.kernelSpec:void 0;return"startUsingPythonInterpreter"===e.kind||("startUsingRemoteKernelSpec"===e.kind||"startUsingLocalKernelSpec"===e.kind)&&e.kernelSpec.language===l.PYTHON_LANGUAGE?(null===(n=null===(t=null==s?void 0:s.metadata)||void 0===t?void 0:t.interpreter)||void 0===n?void 0:n.path)||(null==s?void 0:s.interpreterPath)||(null==s?void 0:s.path):(null==o?void 0:o.path)||(null==s?void 0:s.path)||(null===(i=null===(r=null==s?void 0:s.metadata)||void 0===r?void 0:r.interpreter)||void 0===i?void 0:i.path)||(null==s?void 0:s.interpreterPath)}function W(e){if(!e)return!1;if("startUsingPythonInterpreter"===e.kind)return!0;const t=j(e)?e.kernelModel:void 0,n=A(e)?e.kernelSpec:void 0;return(null==t?void 0:t.language)===l.PYTHON_LANGUAGE||H(n)}function H(e){return((null==e?void 0:e.language)||"").toLowerCase()===l.PYTHON_LANGUAGE}function Y(e){if(!e)return;if("startUsingPythonInterpreter"===e.kind)return l.PYTHON_LANGUAGE;const t=j(e)?e.kernelModel:void 0,n=A(e)?e.kernelSpec:void 0;return(null==t?void 0:t.language)||V(n)}function V(e){return null==e?void 0:e.language}t.connectionFilePlaceholder="{connection_file}",t.findIndexOfConnectionFile=function(e){return e.argv.findIndex((e=>e.includes(t.connectionFilePlaceholder)))},t.kernelConnectionMetadataHasKernelSpec=A,t.kernelConnectionMetadataHasKernelModel=j,t.getKernelId=function(e,t,n){var i,o,s;t=H(e)?t:void 0;let a=e.name;const c=$(e);if(c&&a.includes(B)&&(a=a.substring(a.indexOf(B)),"registeredByNewVersionOfExtForCustomKernelSpec"===c)){const t=(null===(o=null===(i=e.metadata)||void 0===i?void 0:i.vscode)||void 0===o?void 0:o.originalSpecFile)||(null===(s=e.metadata)||void 0===s?void 0:s.originalSpecFile);t&&(a=`${a}#${r.basename(r.dirname(t))}`)}let l="";return l=H(e)?e.argv.slice(1).filter((e=>!["-f","{connection_file}"].includes(e))).join("#").toLowerCase():e.argv.join("#").toLowerCase(),`${n?`${n}.`:""}${e.id||""}.${a}.${(0,_.getNormalizedInterpreterPath)(e.interpreterPath||e.path)}.${(0,_.getNormalizedInterpreterPath)(null==t?void 0:t.path)||""}.${l}`},t.getSysInfoReasonHeader=function(e,t){const n=F(t);switch(e){case v.SysInfoReason.Start:case v.SysInfoReason.New:return f.DataScience.startedNewKernelHeader().format(n);case v.SysInfoReason.Restart:return f.DataScience.restartedKernelHeader().format(n);case v.SysInfoReason.Interrupt:return f.DataScience.pythonInterruptFailedHeader();case v.SysInfoReason.Connect:return f.DataScience.connectKernelHeader().format(n);default:return(0,u.traceError)("Invalid SysInfoReason"),""}},t.getDisplayNameOrNameOfKernelConnection=F,t.getNameOfKernelConnection=function(e,t=""){var n;return e?"connectToLiveKernel"===e.kind?e.kernelModel.name:null===(n=e.kernelSpec)||void 0===n?void 0:n.name:t},t.getKernelPathFromKernelConnection=q,t.getRemoteKernelSessionInformation=function(e,t=""){return"connectToLiveKernel"===(null==e?void 0:e.kind)?f.DataScience.jupyterSelectURIRunningDetailFormat().format(e.kernelModel.lastActivityTime.toLocaleString(),e.kernelModel.numberOfConnections.toString()):t},t.getKernelConnectionPath=function(e,t,n){var r;if("connectToLiveKernel"===(null==e?void 0:e.kind))return;const i=q(e),o=1===(null===(r=n.workspaceFolders)||void 0===r?void 0:r.length)?n.workspaceFolders[0].uri.fsPath:void 0;return i?t.getDisplayName(i,o):""},t.getInterpreterFromKernelConnectionMetadata=function(e){var t,n;if(!e)return;if(e.interpreter)return e.interpreter;const r=j(e)?e.kernelModel:void 0;if(null===(t=null==r?void 0:r.metadata)||void 0===t?void 0:t.interpreter)return r.metadata.interpreter;const i=A(e)?e.kernelSpec:void 0;return null===(n=null==i?void 0:i.metadata)||void 0===n?void 0:n.interpreter},t.isPythonKernelConnection=W,t.isPythonKernelSpec=H,t.getKernelConnectionLanguage=Y,t.getLanguageInNotebookMetadata=function(e){var t;if(e)return V(e.kernelspec)||(null===(t=e.language_info)||void 0===t?void 0:t.name)},t.getLanguageInKernelSpec=V;const B="jvsc74a57bd0";function K(e){const t=((null==e?void 0:e.sysVersion)?(0,S.getTelemetrySafeVersion)(e.sysVersion)||"3":"").replace(/\./g,"");return e?`${e?`python${t}`:""}${B}${(0,_.getInterpreterHash)(e)}`:"python3"}function $(e){var t,n,i,o;if(e.isRegisteredByVSC)return e.isRegisteredByVSC;if(!e.name)return;const s=(null===(n=null===(t=e.metadata)||void 0===t?void 0:t.vscode)||void 0===n?void 0:n.originalSpecFile)||(null===(i=e.metadata)||void 0===i?void 0:i.originalSpecFile),a=s?r.basename(r.dirname(s)):e.name,c=(0,I.isDefaultKernelSpec)({...e,name:a})?Object.keys(e.env||{}).length>0:"string"==typeof s&&!s.includes(B);return e.name.includes(B)?c?"registeredByNewVersionOfExtForCustomKernelSpec":"registeredByNewVersionOfExt":(null===(o=e.metadata)||void 0===o?void 0:o.interpreter)&&-1!==e.name.toLowerCase().search(/[a-f0-9]{32}$/)?"registeredByOldVersionOfExt":void 0}function z(e){if("object"==typeof e&&"interpreter"in e&&e.interpreter&&"object"==typeof e.interpreter&&"hash"in e.interpreter)return e.interpreter.hash}function J(e,t,n,i,o,s,a){var c,u,d,p,h,f,m,g,v,y,b,_,w,S,C,k,E,x,T,D,I,P,R;if(s.kind===a.kind&&"connectToLiveKernel"===a.kind)return 0;if("connectToLiveKernel"===s.kind)return-1;if("connectToLiveKernel"===a.kind)return 1;if(!(null==i?void 0:i.kernelspec)){if(t)if(t===l.PYTHON_LANGUAGE&&s.kernelSpec.language===a.kernelSpec.language&&s.kernelSpec.language===t);else{if(s.kernelSpec.language===a.kernelSpec.language&&s.kernelSpec.language===t)return 0;if(s.kernelSpec.language===t)return 1;if(a.kernelSpec.language===t)return-1}return s===o?1:a===o?-1:0}const M=(null===(u=null===(c=s.kernelSpec.metadata)||void 0===c?void 0:c.vscode)||void 0===u?void 0:u.originalSpecFile)||(null===(d=s.kernelSpec.metadata)||void 0===d?void 0:d.originalSpecFile),O=(null===(h=null===(p=a.kernelSpec.metadata)||void 0===p?void 0:p.vscode)||void 0===h?void 0:h.originalSpecFile)||(null===(f=a.kernelSpec.metadata)||void 0===f?void 0:f.originalSpecFile),L=(null===(g=null===(m=s.kernelSpec.metadata)||void 0===m?void 0:m.vscode)||void 0===g?void 0:g.originalDisplayName)||(null===(v=s.kernelSpec)||void 0===v?void 0:v.display_name)||"",N=(null===(b=null===(y=a.kernelSpec.metadata)||void 0===y?void 0:y.vscode)||void 0===b?void 0:b.originalDisplayName)||(null===(_=a.kernelSpec)||void 0===_?void 0:_.display_name)||"",A=M?r.basename(r.dirname(M)):(null===(w=s.kernelSpec)||void 0===w?void 0:w.display_name)||"",j=O?r.basename(r.dirname(O)):(null===(S=a.kernelSpec)||void 0===S?void 0:S.display_name)||"";if(t&&t!==l.PYTHON_LANGUAGE)return s.kernelSpec.language&&a.kernelSpec.language&&s.kernelSpec.language!==t&&a.kernelSpec.language!==t?0:s.kernelSpec.language===t&&a.kernelSpec.language!==t?1:s.kernelSpec.language!==t&&a.kernelSpec.language===t?-1:A&&A===j&&L===N?0:A&&A===(null===(C=i.kernelspec)||void 0===C?void 0:C.name)&&L===i.kernelspec.display_name?1:j&&j===(null===(k=i.kernelspec)||void 0===k?void 0:k.name)&&N===i.kernelspec.display_name?-1:A&&A===(null===(E=i.kernelspec)||void 0===E?void 0:E.name)?1:j&&j===(null===(x=i.kernelspec)||void 0===x?void 0:x.name)?-1:L&&L===(null===(T=i.kernelspec)||void 0===T?void 0:T.display_name)?1:N&&N===(null===(D=i.kernelspec)||void 0===D?void 0:D.display_name)?-1:s===o?1:a===o?-1:0;if(!n&&t){if(A&&L&&A!==j&&L!==N&&"startUsingLocalKernelSpec"===s.kind&&s.kernelSpec.language!==l.PYTHON_LANGUAGE&&A===i.kernelspec.name&&L===i.kernelspec.display_name)return 1;if(j&&N&&A!==j&&L!==N&&"startUsingLocalKernelSpec"===a.kind&&a.kernelSpec.language!==l.PYTHON_LANGUAGE&&j===i.kernelspec.name&&N===i.kernelspec.display_name)return-1}if(s.kernelSpec.language&&a.kernelSpec.language){if(s.kernelSpec.language!==a.kernelSpec.language)return s.kernelSpec.language===l.PYTHON_LANGUAGE?1:-1;if(s.kernelSpec.language!==l.PYTHON_LANGUAGE)return 0}if(null===(I=null==i?void 0:i.kernelspec)||void 0===I?void 0:I.name){let e=G(s,a,A,j,i,o);if("number"==typeof e)return e;if("startUsingRemoteKernelSpec"!==s.kind&&"startUsingRemoteKernelSpec"===a.kind)return 1;if("startUsingRemoteKernelSpec"===s.kind&&"startUsingRemoteKernelSpec"!==a.kind)return-1;if("startUsingRemoteKernelSpec"===s.kind&&"startUsingRemoteKernelSpec"===a.kind)return s===o?1:a===o?-1:0;if(e=G(s,a,(null===(P=s.interpreter)||void 0===P?void 0:P.envName)||"",(null===(R=a.interpreter)||void 0===R?void 0:R.envName)||"",i,o),"number"==typeof e)return e}if("startUsingRemoteKernelSpec"!==s.kind&&"startUsingRemoteKernelSpec"===a.kind)return 1;if("startUsingRemoteKernelSpec"===s.kind&&"startUsingRemoteKernelSpec"!==a.kind)return-1;if("startUsingRemoteKernelSpec"===s.kind&&"startUsingRemoteKernelSpec"===a.kind)return 0;const F=Q(s,a,i),U=X(s,a,i);if(F>=0&&U>0)return 1;if(F>0&&U>=0)return 1;if(F<=0&&U<0)return-1;if(F<0&&U<=0)return-1;if(F<0&&U>0)return s===o?1:a===o?-1:0;if(0===F&&0===U){if(s===o)return 1;if(a===o)return-1}return s===o?1:a===o?-1:0}function G(e,t,n,r,i,o){var s,a,c,l,u,d,p,h,f,m,g,v,y,b,_,w,S;const C=Q(e,t,i),k=X(e,t,i);if(null===(s=null==i?void 0:i.kernelspec)||void 0===s?void 0:s.name)if(i.kernelspec.name.toLowerCase().match(I.isDefaultPythonKernelSpecName)){const s="connectToLiveKernel"!==e.kind?$(e.kernelSpec):"",E="connectToLiveKernel"!==t.kind?$(t.kernelSpec):"",x=parseInt(i.kernelspec.name.toLowerCase().replace("python",""),10);if(x&&(null===(c=null===(a=e.interpreter)||void 0===a?void 0:a.version)||void 0===c?void 0:c.major)===(null===(u=null===(l=t.interpreter)||void 0===l?void 0:l.version)||void 0===u?void 0:u.major)&&e.kind===t.kind&&0===C&&0===k)return e===o?1:t===o?-1:function(e,t){if("connectToLiveKernel"===e.kind||"connectToLiveKernel"===t.kind)return"connectToLiveKernel"!==e.kind?1:"connectToLiveKernel"!==t.kind?-1:0;const n=$(e.kernelSpec),r=$(t.kernelSpec);return n===r?0:"registeredByNewVersionOfExtForCustomKernelSpec"===r?1:"registeredByNewVersionOfExtForCustomKernelSpec"===n?-1:0}(e,t);if(x&&(null===(p=null===(d=e.interpreter)||void 0===d?void 0:d.version)||void 0===p?void 0:p.major)!==(null===(f=null===(h=t.interpreter)||void 0===h?void 0:h.version)||void 0===f?void 0:f.major)&&(null===(g=null===(m=e.interpreter)||void 0===m?void 0:m.version)||void 0===g?void 0:g.major)===x&&"startUsingRemoteKernelSpec"!==e.kind&&C>=0&&k>=0)return 1;if(x&&(null===(y=null===(v=e.interpreter)||void 0===v?void 0:v.version)||void 0===y?void 0:y.major)!==(null===(_=null===(b=t.interpreter)||void 0===b?void 0:b.version)||void 0===_?void 0:_.major)&&(null===(S=null===(w=t.interpreter)||void 0===w?void 0:w.version)||void 0===S?void 0:S.major)===x&&"startUsingRemoteKernelSpec"!==t.kind&&C<=0&&k<=0)return-1;if(n===i.kernelspec.name&&C>=0&&k>=0)return 1;if("startUsingPythonInterpreter"===e.kind&&"registeredByNewVersionOfExtForCustomKernelSpec"!==s&&n===e.kernelSpec.display_name&&C>=0&&k>=0)return 1;if(r===i.kernelspec.name&&C<=0&&k<=0)return-1;if("startUsingPythonInterpreter"===t.kind&&"registeredByNewVersionOfExtForCustomKernelSpec"!==E&&n===t.kernelSpec.display_name&&C<=0&&k<=0)return 1;if(k>0)return 1;if(k<0)return-1}else{if(n===r&&n===i.kernelspec.name)return C>=0&&k>=0?1:C<0&&k<0?-1:k;if(n===i.kernelspec.name)return C>=0&&k>=0?1:C<0&&k<0?-1:e===o?1:t===o?-1:k;if(r===i.kernelspec.name)return C>0&&k>0?1:C<=0&&k<=0?-1:e===o?1:t===o?-1:k}}function X(e,t,n){if("connectToLiveKernel"===e.kind&&"connectToLiveKernel"===t.kind)return 0;if("connectToLiveKernel"===e.kind)return-1;if("connectToLiveKernel"===t.kind)return 1;const r=$(e.kernelSpec),i=$(t.kernelSpec),o=!!Z(e,n),s=!!Z(t,n);return o||s?o&&s&&e.kind===t.kind&&r===i?0:o&&!s?1:!o&&s?-1:"startUsingPythonInterpreter"===e.kind&&e.kind!==t.kind&&"registeredByNewVersionOfExtForCustomKernelSpec"!==r?1:"startUsingPythonInterpreter"===t.kind&&t.kind!==e.kind&&"registeredByNewVersionOfExtForCustomKernelSpec"!==i?-1:"startUsingPythonInterpreter"===e.kind&&e.kind!==t.kind?1:"startUsingPythonInterpreter"===t.kind&&t.kind!==e.kind?-1:"startUsingLocalKernelSpec"===e.kind&&e.kind!==t.kind||"startUsingLocalKernelSpec"===t.kind&&e.kind!==t.kind?1:0:0}function Q(e,t,n){var r,i,o,s,a,c,l,u,d,p,h,f,m,g,v,y,b,_,w,S,C,k,E;if("connectToLiveKernel"===e.kind&&"connectToLiveKernel"===t.kind)return 0;if("connectToLiveKernel"===e.kind)return-1;if("connectToLiveKernel"===t.kind)return 1;if(!(null===(r=null==n?void 0:n.kernelspec)||void 0===r?void 0:r.display_name))return 0;if((0,I.isDefaultKernelSpec)({argv:[],display_name:n.kernelspec.display_name,name:n.kernelspec.name,path:""})){const r=$(e.kernelSpec),y=$(t.kernelSpec);if(r===y&&e.kind===t.kind);else{if("registeredByNewVersionOfExtForCustomKernelSpec"!==r&&"registeredByNewVersionOfExtForCustomKernelSpec"===y&&"startUsingPythonInterpreter"===e.kind)return 1;if("registeredByNewVersionOfExtForCustomKernelSpec"!==y&&"registeredByNewVersionOfExtForCustomKernelSpec"===r&&"startUsingPythonInterpreter"===t.kind)return-1}return(null===(o=null===(i=e.kernelSpec.metadata)||void 0===i?void 0:i.vscode)||void 0===o?void 0:o.originalDisplayName)&&(null===(a=null===(s=e.kernelSpec.metadata)||void 0===s?void 0:s.vscode)||void 0===a?void 0:a.originalDisplayName)===(null===(l=null===(c=t.kernelSpec.metadata)||void 0===c?void 0:c.vscode)||void 0===l?void 0:l.originalDisplayName)?0:(null===(d=null===(u=e.kernelSpec.metadata)||void 0===u?void 0:u.vscode)||void 0===d?void 0:d.originalDisplayName)&&(null===(h=null===(p=e.kernelSpec.metadata)||void 0===p?void 0:p.vscode)||void 0===h?void 0:h.originalDisplayName)===n.kernelspec.display_name?1:(null===(m=null===(f=t.kernelSpec.metadata)||void 0===f?void 0:f.vscode)||void 0===m?void 0:m.originalDisplayName)&&(null===(v=null===(g=t.kernelSpec.metadata)||void 0===g?void 0:g.vscode)||void 0===v?void 0:v.originalDisplayName)===n.kernelspec.display_name?-1:0}return e.kernelSpec.display_name===t.kernelSpec.display_name&&(null===(b=null===(y=e.kernelSpec.metadata)||void 0===y?void 0:y.vscode)||void 0===b?void 0:b.originalDisplayName)===(null===(w=null===(_=t.kernelSpec.metadata)||void 0===_?void 0:_.vscode)||void 0===w?void 0:w.originalDisplayName)?0:e.kernelSpec.display_name===n.kernelspec.display_name||(null===(C=null===(S=e.kernelSpec.metadata)||void 0===S?void 0:S.vscode)||void 0===C?void 0:C.originalDisplayName)===n.kernelspec.display_name?1:t.kernelSpec.display_name===n.kernelspec.display_name||(null===(E=null===(k=t.kernelSpec.metadata)||void 0===k?void 0:k.vscode)||void 0===E?void 0:E.originalDisplayName)===n.kernelspec.display_name?-1:0}function Z(e,t){const n=z(t);return n&&("startUsingLocalKernelSpec"===e.kind||"startUsingRemoteKernelSpec"===e.kind||"startUsingPythonInterpreter"===e.kind)&&e.interpreter&&(0,_.getInterpreterHash)(e.interpreter)===n}async function ee(e,t,r){(0,u.traceInfo)(`Executing silently Code (${e.status}) = ${t.substring(0,100).splitLines().join("\\n")}`);const i=n(36879),o=e.requestExecute({code:t.replace(/\r\n/g,"\n"),silent:!1,stop_on_error:!1,allow_stdin:!0,store_history:!1},!0),s=[];o.onIOPub=e=>{if(i.KernelMessage.isStreamMsg(e))if((0,u.traceInfoIfCI)(`Got io pub message (stream), ${e.content.text.substr(0,100).splitLines().join("\\n")}`),s.length>0&&"stream"===s[s.length-1].output_type&&s[s.length-1].name===e.content.name)s[s.length-1].text+=e.content.text;else{const t={name:e.content.name,text:e.content.text,output_type:"stream"};s.push(t)}else if(i.KernelMessage.isExecuteResultMsg(e)){(0,u.traceInfoIfCI)("Got io pub message (execresult)}");const t={data:e.content.data,execution_count:e.content.execution_count,metadata:e.content.metadata,output_type:"execute_result"};s.push(t)}else if(i.KernelMessage.isDisplayDataMsg(e)){(0,u.traceInfoIfCI)("Got io pub message (displaydata)}");const t={data:e.content.data,metadata:e.content.metadata,output_type:"display_data"};s.push(t)}else if(i.KernelMessage.isErrorMsg(e)){(0,u.traceInfoIfCI)(`Got io pub message (error), ${e.content.ename},${e.content.evalue}, ${e.content.traceback.join().substring(0,100)}}`);const t={ename:e.content.ename,evalue:e.content.evalue,traceback:e.content.traceback,output_type:"error"};s.push(t)}else(0,u.traceInfoIfCI)(`Got io pub message (${e.header.msg_type})`)},await o.done;const a=t.substring(0,100).splitLines().join("\\n");return r&&function(e,t,n){e.filter((e=>"error"===e.output_type)).forEach((e=>{const r=e,i=`${r.ename}: ${r.evalue} \n ${r.traceback.map((e=>` ${e}`)).join("\n")}`,o=`${t.traceErrorsMessage||""} ${n} ${i}`;t.traceErrors?(0,u.traceError)(o):(0,u.traceWarning)(o),t.telemetryName&&(0,w.sendTelemetryEvent)(t.telemetryName,void 0,{ename:r.ename,evalue:r.evalue})}))}(s,r,a),(0,u.traceInfo)(`Executing silently Code (completed) = ${a}`),s}async function te(e,t){const n=t.get(c.IApplicationShell),r=t.get(c.ICommandManager),i=t.get(b.IStatusProvider);let o=!1;switch(await n.showErrorMessage(f.DataScience.cannotRunCellKernelIsDead().format(F(e.kernelConnectionMetadata)),{modal:!0},f.DataScience.showJupyterLogs(),f.DataScience.restartKernel())){case f.DataScience.restartKernel():{const t=i.set(f.DataScience.restartingKernelStatus());try{await e.restart(),o=!0}finally{t.dispose()}break}case f.DataScience.showJupyterLogs():r.executeCommand(k.Commands.ViewJupyterOutput)}return o}async function ne(e,t,n,r,i,o){const a=e.get(p.IMemento,p.GLOBAL_MEMENTO),l=e.get(b.IDataScienceErrorHandler);let u=o;o.connection.interpreter&&"start"===n&&(0,E.clearInstalledIntoInterpreterMemento)(a,x.Product.ipykernel,o.connection.interpreter.path).ignoreErrors();const d=await l.handleKernelError(t,"start",o.connection,r),f=(0,s.isLocalConnection)(null==o?void 0:o.connection);switch(e.get(b.IRawNotebookProvider).isSupported&&f&&"start"===n&&(0,y.sendKernelTelemetryEvent)(r,k.Telemetry.RawKernelSessionStartNoIpykernel,{reason:d}),i.dispose().ignoreErrors(),d){case b.KernelInterpreterDependencyResponse.cancel:case b.KernelInterpreterDependencyResponse.failed:throw t;case b.KernelInterpreterDependencyResponse.selectDifferentKernel:{const n=await async function(e,t){const n=t.get(c.ICommandManager),r=t.get(c.IVSCodeNotebook),i=(0,O.findNotebookEditor)(e,r,t.get(b.IInteractiveWindowProvider)),o=t.get(M.INotebookControllerManager);let s;const a=(0,h.createDeferred)(),l=o.onNotebookControllerSelected((e=>a.resolve(e.controller)));return await(0,O.selectKernel)(e,r,t.get(b.IInteractiveWindowProvider),n)&&i&&(s=await a.promise),l.dispose(),s}(r,e);if(!n)throw t;u=n;break}}return u}t.getInterpreterKernelSpecName=K,t.getInterpreterWorkspaceFolder=function(e,t){const n=t.getWorkspaceFolder(a.Uri.file(e.path));return(null==n?void 0:n.uri.fsPath)||t.rootPath},t.getKernelRegistrationInfo=$,t.createInterpreterKernelSpec=function(e,n){const i={name:K(e),language:"python",display_name:(null==e?void 0:e.displayName)||"Python 3",metadata:{interpreter:e},argv:["python","-m","ipykernel_launcher","-f",t.connectionFilePlaceholder],env:{},resources:{}},o=n&&i.name?r.join(n,i.name,"kernel.json"):void 0;return new T.JupyterKernelSpec(i,o,null==e?void 0:e.path,"registeredByNewVersionOfExt")},t.areKernelConnectionsEqual=function(e,t){return!((e||t)&&(!e&&t||e&&!t||(null==e?void 0:e.id)!==(null==t?void 0:t.id)))},t.detectDefaultKernelName=function(e){return i("python\\s*(?(\\d+))","g").exec(e.toLowerCase())},t.cleanEnvironment=function(e){const t=o(e);return t.env&&Object.keys(t.env).forEach((e=>{if(t.env){const n=t.env[e];null!=n&&(t.env[e]=n.toString())}})),t},t.isLocalLaunch=function(e){const t=e.getSettings(void 0).jupyterServerType;return!t||t.toLowerCase()===g.Settings.JupyterServerLocalLaunch},t.getInterpreterHashInMetadata=z,t.findPreferredKernel=function(e,t,n,r,i){var o,s,a,c,p,h,f;if((0,u.traceInfo)(`Find preferred kernel for ${(0,d.getDisplayPath)(t)} with metadata ${JSON.stringify(n||{})} & preferred interpreter ${(0,d.getDisplayPath)(null==r?void 0:r.path)}`),0===e.length)return;if(t&&i){const n=i.getPreferredRemoteKernelId(t),r=n&&e.find((e=>"connectToLiveKernel"===e.kind&&e.kernelModel.id===n));if(r)return r}const g=r&&function(e,t){if(!e||0===t.length)return;const n=t.filter((t=>"startUsingPythonInterpreter"===t.kind&&"registeredByNewVersionOfExtForCustomKernelSpec"!==$(t.kernelSpec)&&(0,_.getInterpreterHash)(t.interpreter)===(0,_.getInterpreterHash)(e)&&t.interpreter.envName===e.envName));if(n.length>1&&((0,u.traceError)(`More than one kernel spec matches the interpreter ${e.path}.`,n),l.isCI))throw new Error("More than one kernelspec matches the intererpreter");return n.length?n[0]:void 0}(r,e);if((0,u.traceInfoIfCI)(`preferredInterpreterKernelSpecIndex = ${null==g?void 0:g.id}`),!n||!(null==n?void 0:n.kernelspec))if("notebook"===(0,m.getResourceType)(t)){if(g&&!i)return g}else{if(g)return g;(0,w.sendTelemetryEvent)(k.Telemetry.FailedToFindKernelSpecInterpreterForInteractive)}(null===(o=null==n?void 0:n.language_info)||void 0===o?void 0:o.name)||null===(s=null==n?void 0:n.kernelspec)||void 0===s||s.language;const v=(null===(a=null==n?void 0:n.language_info)||void 0===a?void 0:a.name)||(null===(c=null==n?void 0:n.kernelspec)||void 0===c?void 0:c.language);let y=v;y="interactive"===(0,m.getResourceType)(t)?l.PYTHON_LANGUAGE:n&&!(0,R.isPythonNotebook)(n)&&y?null===(f=(null===(p=null==n?void 0:n.kernelspec)||void 0===p?void 0:p.language)||(null===(h=null==n?void 0:n.language_info)||void 0===h?void 0:h.name))||void 0===f?void 0:f.toLowerCase():l.PYTHON_LANGUAGE,e.sort(((e,t)=>J(0,y,v,n,g,e,t)));let b=e[e.length-1];return y&&y!==l.PYTHON_LANGUAGE&&!(null==n?void 0:n.kernelspec)&&"connectToLiveKernel"!==b.kind&&b.kernelSpec.language&&b.kernelSpec.language!==y?b=void 0:(0,u.traceInfoIfCI)(l.isCI,`Preferred kernel is ${JSON.stringify(e[0])}`),b},t.compareKernels=J,t._findPreferredKernel=function(e,t,n,r,i){var o,s,a,c,p,h,f,g,v,y,b,S,C,E,x,T,D,P,M,O,L,N,A,j,U,q,W,V,B;(0,u.traceInfo)(`Find preferred kernel for ${(0,d.getDisplayPath)(t)} with metadata ${JSON.stringify(n||{})} & preferred interpreter ${(0,d.getDisplayPath)(null==r?void 0:r.path)}`);let J=-1;if(J<0&&t&&i){const n=i.getPreferredRemoteKernelId(t);n&&(J=e.findIndex((e=>"connectToLiveKernel"===e.kind&&e.kernelModel.id===n)))}if(!n&&"interactive"===(0,m.getResourceType)(t)&&r){const t=e.find((e=>"startUsingPythonInterpreter"===e.kind&&(0,_.areInterpreterPathsSame)(e.interpreter.path,r.path)));if(t)return t;(0,w.sendTelemetryEvent)(k.Telemetry.FailedToFindKernelSpecInterpreterForInteractive)}if(J<0){const d=!!(null===(o=null==n?void 0:n.language_info)||void 0===o?void 0:o.name);let w;w="interactive"===(0,m.getResourceType)(t)?l.PYTHON_LANGUAGE:n&&!(0,R.isPythonNotebook)(n)&&d?null===(c=(null===(s=null==n?void 0:n.kernelspec)||void 0===s?void 0:s.language)||(null===(a=null==n?void 0:n.language_info)||void 0===a?void 0:a.name))||void 0===c?void 0:c.toLowerCase():l.PYTHON_LANGUAGE;let k=-1;const G=r?e.findIndex((e=>!("startUsingPythonInterpreter"!==e.kind||!e.kernelSpec||e.kernelSpec.language!==l.PYTHON_LANGUAGE||!(0,_.areInterpreterPathsSame)(e.interpreter.path,r.path)))):-1;if((0,u.traceInfoIfCI)(`preferredInterpreterKernelSpecIndex = ${G}`),"notebook"===(0,m.getResourceType)(t)&&G>=0&&!i&&!(null==n?void 0:n.kernelspec))return(0,u.traceInfoIfCI)("Using preferred interpreter as there's no kernelspec in notebook metadata"),e[G];for(let t=0;e&&t<(null==e?void 0:e.length);t+=1){const i=e[t],o="connectToLiveKernel"!==i.kind?i.kernelSpec:void 0,s=Y(i);let a=-1,c=0;if(o){(0,u.traceInfoIfCI)(`Checking kernel Spec ${JSON.stringify(o)}`),(0,u.traceInfoIfCI)(`isPythonKernelSpec(spec) = ${H(o)}`),(0,u.traceInfoIfCI)(`isKernelRegisteredByUs(spec) = ${$(o)}`),!n&&("registeredByNewVersionOfExt"===$(o)||"registeredByNewVersionOfExtForCustomKernelSpec"===$(o))&&H(o)&&r&&o.name.includes(K(r))&&((0,u.traceInfoIfCI)("Increased score by +100 for matching names without notebook metadata"),a+=100),(null===(p=null==n?void 0:n.kernelspec)||void 0===p?void 0:p.name)&&$(o)&&n.kernelspec.name===o.name&&((0,u.traceInfoIfCI)("Increased score by +100 for matching names in notbeook metadata"),a+=100);const e=z(n);if("startUsingLocalKernelSpec"!==i.kind&&"startUsingRemoteKernelSpec"!==i.kind&&"startUsingPythonInterpreter"!==i.kind||!i.interpreter||(0,_.getInterpreterHash)(i.interpreter)!==e||((0,u.traceInfoIfCI)("Increased score by +100 for matching interpreter in notbeook metadata"),a+=100),o&&o.path&&o.path.length>0&&r&&(0,_.areInterpreterPathsSame)(o.path,r.path)&&w===l.PYTHON_LANGUAGE&&((0,u.traceInfoIfCI)(`Increased score by ${n?1:8} for matching spec.path in notbeook metadata`),a+=n?1:8),o.display_name&&o.display_name===(null===(h=null==n?void 0:n.kernelspec)||void 0===h?void 0:h.display_name)&&((0,u.traceInfoIfCI)("Increased score by +16 for matching display_name with metadata"),a+=16),(null===(f=i.interpreter)||void 0===f?void 0:f.envName)&&(null===(g=i.interpreter)||void 0===g?void 0:g.envName)===(null===(v=null==n?void 0:n.kernelspec)||void 0===v?void 0:v.name)&&w===l.PYTHON_LANGUAGE&&!(null===(y=null==n?void 0:n.kernelspec)||void 0===y?void 0:y.name.toLowerCase().match(I.isDefaultPythonKernelSpecName))&&((0,u.traceInfoIfCI)("Increased score by +16 for matching env name"),a+=16),o.display_name&&o.display_name===(null==r?void 0:r.displayName)&&!(null===(b=null==n?void 0:n.kernelspec)||void 0===b?void 0:b.display_name)&&w===l.PYTHON_LANGUAGE&&((0,u.traceInfoIfCI)("Increased score by +16 for matching display_name with interpreter"),a+=10),a<=0&&w&&s===(w||"")&&((0,u.traceVerbose)(`findPreferredKernel score for speclanguage=${w}, ${F(i)} is ${a}`),(0,u.traceInfoIfCI)("Increased score by +1 for matching language"),c=1,a=1),r&&r.version&&o&&o.name&&w===l.PYTHON_LANGUAGE&&!$(o)){const e=/\D+(\d+)/.exec(o.name);if(e&&null!==e&&e.length>0){const t=parseInt(e[1][0],10);t&&t===r.version.major&&((0,u.traceInfoIfCI)("Increased score by +4 for matching major version"),a+=4)}}if(w===l.PYTHON_LANGUAGE&&((null===(C=null===(S=i.interpreter)||void 0===S?void 0:S.sysVersion)||void 0===C?void 0:C.startsWith("3"))||3===(null===(x=null===(E=i.interpreter)||void 0===E?void 0:E.version)||void 0===x?void 0:x.major)||(null===(D=null===(T=i.interpreter)||void 0===T?void 0:T.displayName)||void 0===D?void 0:D.toLowerCase().includes("python 3"))||(null===(M=null===(P=i.interpreter)||void 0===P?void 0:P.displayName)||void 0===M?void 0:M.toLowerCase().includes("python3"))||(null===(L=null===(O=i.interpreter)||void 0===O?void 0:O.path)||void 0===L?void 0:L.toLowerCase().includes("python3"))||o.argv[0].toLocaleLowerCase().includes("python3")))if((0,u.traceInfoIfCI)("Increased score by +1 for matching major version 3"),a+=1,c+=1,(0,u.traceVerbose)(`findPreferredKernel score for Python3, ${F(i)} is ${a}`),"object"==typeof n&&"interpreter"in n&&n.interpreter&&"object"==typeof n.interpreter&&"startUsingPythonInterpreter"===i.kind){const e=n.interpreter;(null===(N=e.version)||void 0===N?void 0:N.raw)&&(null===(A=e.version)||void 0===A?void 0:A.raw)===(null===(j=i.interpreter.version)||void 0===j?void 0:j.raw)&&((0,u.traceInfoIfCI)("Increased score by +3 for matching raw version in notebook metadata interpreter"),a+=3)}else(null===(q=null===(U=i.interpreter)||void 0===U?void 0:U.version)||void 0===q?void 0:q.raw)&&(null===(V=null===(W=i.interpreter)||void 0===W?void 0:W.version)||void 0===V?void 0:V.raw)===(null===(B=null==r?void 0:r.version)||void 0===B?void 0:B.raw)&&((0,u.traceInfoIfCI)("Increased score by +3 for matching raw version in preferred interpreter"),a+=3);!(null==n?void 0:n.kernelspec)&&r&&(0,_.areInterpreterPathsSame)(o.interpreterPath,null==r?void 0:r.path)&&((0,u.traceInfoIfCI)("Increased score by +10 for matching spec.interpreterPath"),a+=10)}(0,u.traceVerbose)(`findPreferredKernel score for ${F(i)} is ${a}`),5===c&&5===a&&("startUsingPythonInterpreter"===i.kind||("startUsingLocalKernelSpec"===i.kind||"startUsingRemoteKernelSpec"===i.kind)&&i.kernelSpec.language===l.PYTHON_LANGUAGE)&&G>=0&&k<=2?J=G:a>k&&(J=t,k=a)}}return(0,u.traceInfoIfCI)(l.isCI&&J>=0,`Preferred kernel is ${JSON.stringify(e[J])}`),J>=0?e[J]:void 0},t.sendTelemetryForPythonKernelExecutable=async function(e,t,n,r){if(e.session&&n.interpreter&&W(n)&&("startUsingLocalKernelSpec"===n.kind||"startUsingPythonInterpreter"===n.kind)){try{(0,u.traceVerbose)("Begin sendTelemetryForPythonKernelExecutable");const i=await ee(e.session,"import sys\nprint(sys.executable)");if(0===i.length)return;const o=i[0];if("stdout"!==o.name&&"stream"!==o.output_type)return;const s=(0,C.concatMultilineString)(o.text).trim().toLowerCase(),a=(0,_.areInterpreterPathsSame)(n.interpreter.path.toLowerCase(),s.toLowerCase());if((0,w.sendTelemetryEvent)(k.Telemetry.PythonKerneExecutableMatches,void 0,{match:a?"true":"false",kernelConnectionType:n.kind}),(0,y.trackKernelResourceInformation)(t,{interpreterMatchesKernel:a}),a)return;r.createActivatedEnvironment({interpreter:n.interpreter,allowEnvironmentFetchExceptions:!0}).then((async e=>{var r;const i=await e.exec(["-c","import sys;print(sys.executable)"],{throwOnStdErr:!1});if(i.stdout.trim().length>0){const e=(0,_.areInterpreterPathsSame)(i.stdout.trim().toLowerCase(),s);(0,w.sendTelemetryEvent)(k.Telemetry.PythonKerneExecutableMatches,void 0,{match:e?"true":"false",kernelConnectionType:n.kind}),(0,y.trackKernelResourceInformation)(t,{interpreterMatchesKernel:e}),e||(0,u.traceError)(`Interpreter started by kernel does not match expectation, expected ${(0,d.getDisplayPath)(null===(r=n.interpreter)||void 0===r?void 0:r.path)}, got ${(0,d.getDisplayPath)(s)}`)}})).catch((e=>(0,u.traceError)("Failed to compare interpreters",e)))}catch(e){(0,u.traceError)("Failed to compare interpreters",e)}(0,u.traceVerbose)("End sendTelemetryForPythonKernelExecutable")}},t.executeSilently=ee,t.notifyAndRestartDeadKernel=te,t.handleKernelError=ne;const re=new WeakMap;async function ie(e,t,n,r=new L.DisplayOptions(!1),i){var o;const{kernel:s,controller:a,deadKernelAction:c}=await i;if("dead"===s.status||"terminating"===s.status&&!s.disposed&&!s.disposing){if((null===(o=re.get(n))||void 0===o?void 0:o.kernel.promise)===i&&re.delete(n),"deadKernelWasNoRestarted"===c)throw new N.KernelDeadError(s.kernelConnectionMetadata);return"deadKernelWasRestarted"===c?s:oe(a,"start",e,t,n,r)}return s}async function oe(e,t,n,r,i,o=new L.DisplayOptions(!1)){var s,a,c,l;let u=re.get(i);if(!o.disableUI&&(null==u?void 0:u.options.disableUI)&&(u.options.disableUI=!1),!o.disableUI&&(null==u?void 0:u.kernel.resolved)&&((null===(a=null===(s=null==u?void 0:u.kernel.value)||void 0===s?void 0:s.kernel)||void 0===a?void 0:a.disposed)||(null===(l=null===(c=null==u?void 0:u.kernel.value)||void 0===c?void 0:c.kernel)||void 0===l?void 0:l.disposing))&&(re.delete(i),u=void 0),u&&"restart"!==t&&"interrupt"!==t)return ie(n,r,i,o,u.kernel.promise);const d=se(e,t,n,r,i,o),p=(0,h.createDeferredFromPromise)(d);return d.then((e=>{e.kernel.onDisposed((()=>{var e;(null===(e=re.get(i))||void 0===e?void 0:e.kernel)===p&&re.delete(i)}))})).catch((()=>{var e;(null===(e=re.get(i))||void 0===e?void 0:e.kernel)===p&&re.delete(i)})),re.set(i,{kernel:p,options:o}),ie(n,r,i,o,p.promise)}async function se(e,t,n,r,i,o=new L.DisplayOptions(!1)){const a=n.get(s.IKernelProvider);let c,l=e,u=function(e,t){switch(e){case"start":return e=>e.start(t);case"interrupt":return e=>e.interrupt();case"restart":return e=>e.restart()}}(t,o),d=t;for(;void 0===c;){c=a.getOrCreate(i,{metadata:l.connection,controller:l.controller,resourceUri:r});const e=e=>"dead"===e.status||"terminating"===e.status&&!e.disposed&&!e.disposing;try{if("restart"!==t&&e(c)&&!o.disableUI)return{kernel:c,controller:l,deadKernelAction:await te(c,n)?"deadKernelWasRestarted":"deadKernelWasNoRestarted"};await u(c),e(c)&&!o.disableUI&&await te(c,n)}catch(e){if(o.disableUI)throw e;l=await ne(n,e,d,r,c,l),u=e=>e.start(o),d="start",c=void 0}}return{kernel:c,controller:l}}t.wrapKernelMethod=oe,t.wrapKernelMethodImpl=se,t.connectToKernel=async function(e,t,n,r,i=new L.DisplayOptions(!1)){return oe(e,"start",t,n,r,i)}},41759:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InstallationChannelManager=void 0;const o=n(86700),s=n(21687),a=n(13395),c=n(60593),l=n(35952),u=n(29474),d=n(29299);let p=class{constructor(e){this.serviceContainer=e}async getInstallationChannel(e,t){const n=await this.getInstallationChannels(t);if(n.length>=1)return n[0];0!==n.length||await this.showNoInstallersMessage(t)}async getInstallationChannels(e){const t=this.serviceContainer.getAll(d.IModuleInstaller),n=[];if(0===t.length)return[];t.sort(((e,t)=>t.priority-e.priority));let r=t[0].priority;for(const i of t){if(i.priority!==r){if(n.length>0)break;r=i.priority}await i.isSupported(e)&&n.push(i)}return n}async showNoInstallersMessage(e){const t=this.serviceContainer.get(a.IApplicationShell),n=l.Installer.searchForHelp();let r;if(r=e.envType===s.EnvironmentType.Conda?await t.showErrorMessage(l.Installer.noCondaOrPipInstaller(),l.Installer.searchForHelp()):await t.showErrorMessage(l.Installer.noPipInstaller(),l.Installer.searchForHelp()),r===n){const n=this.serviceContainer.get(c.IPlatformService),r=n.isWindows?"Windows":n.isMac?"MacOS":"Linux";t.openUrl(`https://www.bing.com/search?q=Install Pip ${r} ${e.envType===s.EnvironmentType.Conda?"Conda":""}`)}}};p=r([(0,o.injectable)(),i(0,(0,o.inject)(u.IServiceContainer))],p),t.InstallationChannelManager=p},58318:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CondaInstaller=void 0;const o=n(86700),s=n(21687),a=n(89114),c=n(29474),l=n(47745),u=n(29299),d=n(71017);let p=class extends l.ModuleInstaller{constructor(e){super(e)}get name(){return"Conda"}get displayName(){return"Conda"}get type(){return u.ModuleInstallerType.Conda}get priority(){return 0}async isSupported(e){if(!1===this._isCondaAvailable)return!1;const t=this.serviceContainer.get(a.CondaService);return this._isCondaAvailable=await t.isCondaAvailable(),!!this._isCondaAvailable&&e.envType===s.EnvironmentType.Conda}async getExecutionArgs(e,t,n=0){const r=this.serviceContainer.get(a.CondaService),i=await r.getCondaBatchFile(),o=t.envName,s=this.getEnvironmentPath(t),c=[n&u.ModuleInstallFlags.upgrade?"update":"install"];return[u.Product.ipykernel,u.Product.pandas,u.Product.nbconvert,u.Product.jupyter,u.Product.notebook].map(l.translateProductToModule).includes(e)&&c.push("-c","conda-forge"),o?(c.push("--name"),c.push(o.toCommandArgument())):s&&(c.push("--prefix"),c.push(s.fileToCommandArgument())),n&u.ModuleInstallFlags.updateDependencies&&c.push("--update-deps"),n&u.ModuleInstallFlags.reInstall&&c.push("--force-reinstall"),c.push(e),c.push("-y"),{exe:i,args:c}}getEnvironmentPath(e){const t=d.dirname(e.path),n=d.basename(t);return-1!==["BIN","SCRIPTS"].indexOf(n.toUpperCase())?d.join(t,".."):t}};p=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IServiceContainer))],p),t.CondaInstaller=p},47745:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.translateProductToModule=t.ModuleInstaller=void 0;const r=n(66828),i=n(13395),o=n(97784),s=n(46318),a=n(12698),c=n(71733),l=n(7744),u=n(35952),d=n(75213),p=n(34347),h=n(29299);function f(e){switch(e){case h.Product.jupyter:return"jupyter";case h.Product.notebook:return"notebook";case h.Product.pandas:return"pandas";case h.Product.ipykernel:return"ipykernel";case h.Product.nbconvert:return"nbconvert";case h.Product.kernelspec:return"kernelspec";case h.Product.pip:return"pip";case h.Product.ensurepip:return"ensurepip";default:throw new Error(`Product ${e} cannot be installed as a Python Module.`)}}t.ModuleInstaller=class{constructor(e){this.serviceContainer=e}async installModule(e,t,n,o){const c="string"==typeof e?e:f(e),h=await this.getExecutionArgs(c,t,o),m=this.serviceContainer.get(a.IPythonExecutionFactory),g=this.serviceContainer.get(a.IProcessServiceFactory),v=this.serviceContainer.get(p.IEnvironmentActivationService),y=this.serviceContainer.get(d.IEnvironmentVariablesService);if(n.token.isCancellationRequested)return;const b=this.serviceContainer.get(i.IApplicationShell),_={location:r.ProgressLocation.Notification,cancellable:!0,title:u.Products.installingModule().format(c)};await b.withProgress(_,(async(e,r)=>(async(e,r)=>{const i=(0,l.createDeferred)();let o,a;if(r.onCancellationRequested((()=>{n.cancel(),i.resolve()})),h.useShellExec){const e=await g.create(void 0);if(n.token.isCancellationRequested)return;try{const t=await e.shellExec(h.args.join(" "),{cwd:h.cwd});(0,s.traceInfo)(t.stdout),i.resolve()}catch(e){i.reject(e)}}else if(h.exe){const e=await v.getActivatedEnvironmentVariables(void 0,t,!1);if(n.token.isCancellationRequested)return;const i={...process.env};y.mergeVariables(e||{},i),y.mergePaths(e||{},i);const s=await g.create(void 0);if(n.token.isCancellationRequested)return;o=s.execObservable(h.exe,h.args,{encoding:"utf-8",token:r,env:i,cwd:h.cwd})}else{const e=await m.createActivatedEnvironment({interpreter:t});if(n.token.isCancellationRequested)return;o=e.execObservable(h.args,{encoding:"utf-8",token:r,cwd:h.cwd})}return o&&o.out.subscribe({next:t=>{null==e||e.report({message:t.out}),(0,s.traceInfo)(t.out),"stderr"===t.source&&(a=t.out)},complete:()=>{var e,t;0!==(null===(e=null==o?void 0:o.proc)||void 0===e?void 0:e.exitCode)?i.reject(a||(null===(t=null==o?void 0:o.proc)||void 0===t?void 0:t.exitCode)):i.resolve()},error:e=>{i.reject(e)}}),i.promise})(e,r)))}elevatedInstall(e,t){const r=this.serviceContainer.get(c.IOutputChannel,o.STANDARD_OUTPUT_CHANNEL),a=`"${e.replace(/\\/g,"/")}" ${t.join(" ")}`;(0,s.traceInfo)(`[Elevated] ${a}`),n(37012).exec(a,{name:"VS Code Jupyter"},(async(e,t,n)=>{if(e){const t=this.serviceContainer.get(i.IApplicationShell);await t.showErrorMessage(e)}else r.show(),t&&(0,s.traceInfo)(t),n&&(0,s.traceError)(`Warning: ${n}`)}))}},t.translateProductToModule=f},11705:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.PipEnvInstaller=t.pipenvName=void 0;const o=n(86700),s=n(21687),a=n(13395),c=n(95063),l=n(48497),u=n(47745),d=n(29299),p=n(22014),h=n(93828),f=n(29474);t.pipenvName="pipenv";let m=class extends u.ModuleInstaller{constructor(e,t){super(e),this.workspaceService=t}get name(){return"pipenv"}get type(){return d.ModuleInstallerType.Pipenv}get displayName(){return t.pipenvName}get priority(){return 10}async isSupported(e){if((0,c.isResource)(e)){const t=await this.serviceContainer.get(l.IInterpreterService).getActiveInterpreter(e),n=e?this.serviceContainer.get(a.IWorkspaceService).getWorkspaceFolder(e):void 0;return!(!t||!n||t.envType!==s.EnvironmentType.Pipenv)&&(0,p.isPipenvEnvironmentRelatedToFolder)(t.path,n.uri.fsPath)}return e.envType===s.EnvironmentType.Pipenv}async getExecutionArgs(e,n,r=0){return{args:[r&d.ModuleInstallFlags.reInstall||r&d.ModuleInstallFlags.updateDependencies||r&d.ModuleInstallFlags.upgrade?"update":"install",e,"--dev"],exe:t.pipenvName,cwd:(0,h.getInterpreterWorkspaceFolder)(n,this.workspaceService)}}};m=r([(0,o.injectable)(),i(0,(0,o.inject)(f.IServiceContainer)),i(1,(0,o.inject)(a.IWorkspaceService))],m),t.PipEnvInstaller=m},76695:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.PipInstaller=void 0;const o=n(86700),s=n(47745),a=n(71017),c=n(13395),l=n(78047),u=n(12698),d=n(29299),p=n(21687),h=n(29474);let f=class extends s.ModuleInstaller{constructor(e){super(e)}get name(){return"Pip"}get type(){return d.ModuleInstallerType.Pip}get displayName(){return"Pip"}get priority(){return 0}async isSupported(e){switch(e.envType){case p.EnvironmentType.Conda:case p.EnvironmentType.Pipenv:case p.EnvironmentType.Poetry:return!1}return this.isPipAvailable(e)}async getExecutionArgs(e,t,n=0){if(e===(0,s.translateProductToModule)(d.Product.pip)){const e=this.serviceContainer.get(d.IInstaller);return await e.isInstalled(d.Product.ensurepip,t)?{args:["-m","ensurepip"]}:{args:[a.join(l._SCRIPTS_DIR,"get-pip.py")]}}const r=[],i=this.serviceContainer.get(c.IWorkspaceService).getConfiguration("http").get("proxy","");return i.length>0&&(r.push("--proxy"),r.push(i)),r.push("install","-U"),n&d.ModuleInstallFlags.reInstall&&r.push("--force-reinstall"),{args:["-m","pip",...r,e]}}isPipAvailable(e){return this.serviceContainer.get(u.IPythonExecutionFactory).create({resource:void 0,interpreter:e}).then((e=>e.isModuleInstalled("pip"))).catch((()=>!1))}};f=r([(0,o.injectable)(),i(0,(0,o.inject)(h.IServiceContainer))],f),t.PipInstaller=f},22014:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPipenvEnvironmentRelatedToFolder=t.isPipenvEnvironment=t._getAssociatedPipfile=void 0;const r=n(71017),i=n(46318),o=n(49754),s=n(75453);async function a(e,t){const n=(0,o.getEnvironmentVariable)("PIPENV_PIPFILE")||"Pipfile";let a=t.lookIntoParentDirectories?function(){const e=(0,o.getEnvironmentVariable)("PIPENV_MAX_DEPTH");if(void 0===e)return 3;const t=parseInt(e,10);return isNaN(t)?((0,i.traceError)(`PIPENV_MAX_DEPTH is incorrectly set. Converting value '${e}' to number results in NaN`),1):t}():1;for(;a>0&&!(0,s.arePathsSame)(e,r.dirname(e));){const t=r.join(e,n);if(await(0,s.pathExists)(t))return t;e=r.dirname(e),a-=1}}async function c(e){const t=r.dirname(r.dirname(e)),n=await async function(e){const t=r.join(e,".project");if(!await(0,s.pathExists)(t))return;const n=await(0,s.readFile)(t);if(await(0,s.pathExists)(n))return n;(0,i.traceError)(`The .project file inside environment folder: ${e} doesn't contain a valid path to the project`)}(t);if(void 0!==n)return r.basename((0,s.normCasePath)(t)).startsWith(`${r.basename((0,s.normCasePath)(n))}-`)?a(n,{lookIntoParentDirectories:!1}):void 0}t._getAssociatedPipfile=a,t.isPipenvEnvironment=async function(e){return!!await async function(e){const t=r.dirname(r.dirname(e));if(".venv"===r.basename(t))return a(r.dirname(t),{lookIntoParentDirectories:!1})}(e)||!!await c(e)},t.isPipenvEnvironmentRelatedToFolder=async function(e,t){const n=await c(e);if(!n)return!1;const r=void 0===(0,o.getEnvironmentVariable)("PIPENV_NO_INHERIT"),i=await a(t,{lookIntoParentDirectories:r});return!!i&&(0,s.arePathsSame)(n,i)}},68639:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.isPoetryEnvironmentRelatedToFolder=t.Poetry=t.isPoetryEnvironment=t.localPoetryEnvDirName=void 0;const i=n(71017),o=n(97784),s=n(46318),a=n(28735),c=n(49754),l=n(88319),u=n(75453),d=/^(.+)-(.+)-py(\d).(\d){1,2}$/;t.localPoetryEnvDirName=".venv",t.isPoetryEnvironment=async function(e){return!!await async function(e){const t=(0,u.getEnvironmentDirFromPath)(e);return!!d.test(i.basename(t))&&(0,u.isVirtualenvEnvironment)(e)}(e)||!!await async function(e){const n=(0,u.getEnvironmentDirFromPath)(e);return i.basename(n)===t.localPoetryEnvDirName&&!!h(i.dirname(n))}(e)};class p{constructor(e,t){this.command=e,this.cwd=t,this.fixCwd()}static async getPoetry(e){if(h(e))return(void 0===p.poetryPromise.get(e)||(0,o.isTestExecution)())&&p.poetryPromise.set(e,p.locate(e)),p.poetryPromise.get(e)}static async locate(e){(0,s.traceVerbose)(`Getting poetry for cwd ${e}`);for(const t of function*(){const e=(0,u.getPythonSetting)("poetryPath");e&&"poetry"!==e&&(yield e),yield"poetry";const t=(0,c.getUserHomeDir)();if(t){const e=i.join(t,".poetry","bin","poetry");(0,u.pathExistsSync)(e)&&(yield e)}}()){(0,s.traceVerbose)(`Probing poetry binary for ${e}: ${t}`);const n=new p(t,e);if(void 0!==await n.getEnvList())return(0,s.traceVerbose)(`Found poetry via filesystem probing for ${e}: ${t}`),n;(0,s.traceVerbose)(`Failed to find poetry for ${e}: ${t}`)}(0,s.traceVerbose)(`No poetry binary found for ${e}`)}async getEnvList(){return this.getEnvListCached(this.command,this.cwd)}async getEnvListCached(e,t){const n=await this.safeShellExecute(`${e} env list --full-path`);if(!n)return;const r="(Activated)";return(await Promise.all(n.stdout.splitLines().map((async e=>{e.endsWith(r)&&(e=e.slice(0,-r.length));const t=e.trim();return await(0,u.pathExists)(t)?t:void 0})))).filter((e=>void 0!==e)).map((e=>e))}async getActiveEnvPath(){return this.getActiveEnvPathCached(this.cwd)}async getActiveEnvPathCached(e){const t=await this.safeShellExecute(`${this.command} env info -p`,!0);if(t)return t.stdout.trim()}async getVirtualenvsPathSetting(){const e=await this.safeShellExecute(`${this.command} config virtualenvs.path`);if(e)return e.stdout.trim()}fixCwd(){if((0,c.getOSType)()===c.OSType.Windows&&/^[a-z]:/.test(this.cwd)){const e=this.cwd.split(":");e[0]=e[0].toUpperCase(),this.cwd=e.join(":")}}async safeShellExecute(e,t=!1){const n=new l.StopWatch,r=await(0,u.shellExecute)(e,{cwd:this.cwd,throwOnStdErr:!0,timeout:5e4}).catch((e=>{t?(0,s.traceVerbose)(e):(0,s.traceError)(e)}));return(0,s.traceVerbose)(`Time taken to run ${e} in ms`,n.elapsedTime),r}}function h(e){const t=i.join(e,"pyproject.toml");return!!(0,u.pathExistsSync)(t)&&!!(0,u.readFileSync)(t).includes("[tool.poetry]")}p.poetryPromise=new Map,r([(0,a.cache)(3e4)],p.prototype,"getEnvListCached",null),r([(0,a.cache)(2e4)],p.prototype,"getActiveEnvPathCached",null),t.Poetry=p,t.isPoetryEnvironmentRelatedToFolder=async function(e,t,n){const r=n?new p(n,t):await p.getPoetry(t),i=await(null==r?void 0:r.getActiveEnvPath());return!!i&&(0,u.isParentPath)(e,i)}},31226:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.PoetryInstaller=t.poetryName=void 0;const o=n(86700),s=n(21687),a=n(13395),c=n(71733),l=n(93828),u=n(29474),d=n(47745),p=n(68639),h=n(29299);t.poetryName="poetry";let f=class extends d.ModuleInstaller{constructor(e,t,n){super(e),this.workspaceService=t,this.configurationService=n}get name(){return"poetry"}get type(){return h.ModuleInstallerType.Poetry}get displayName(){return t.poetryName}get priority(){return 10}async isSupported(e){if(e.envType!==s.EnvironmentType.Poetry)return!1;const t=(0,l.getInterpreterWorkspaceFolder)(e,this.workspaceService);return!!t&&(0,p.isPoetryEnvironmentRelatedToFolder)(e.path,t,this.configurationService.getSettings(void 0).poetryPath)}async getExecutionArgs(e,t){return{useShellExec:!0,args:[this.configurationService.getSettings(void 0).poetryPath,"add","--dev",e],cwd:(0,l.getInterpreterWorkspaceFolder)(t,this.workspaceService)}}};f=r([(0,o.injectable)(),i(0,(0,o.inject)(u.IServiceContainer)),i(1,(0,o.inject)(a.IWorkspaceService)),i(2,(0,o.inject)(c.IConfigurationService))],f),t.PoetryInstaller=f},17927:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProductInstaller=t.DataScienceInstaller=t.isModulePresentInEnvironment=t.isModulePresentInEnvironmentCache=t.clearInstalledIntoInterpreterMemento=t.trackPackageInstalledIntoInterpreter=void 0;const o=n(86700),s=n(36625),a=n(66828),c=n(47745),l=n(13982),u=n(29299),d=n(36462),p=n(86909),h=n(13395),f=n(46318),m=n(12698),g=n(71733),v=n(95063),y=n(29474),b=n(97045),_=n(64412),w=n(79262),S=n(83474),C=n(97784),k=n(7744);async function E(e,t,n){if((0,v.isResource)(n))return;const r=`${(0,w.getInterpreterHash)(n)}#${l.ProductNames.get(t)}`;await e.update(r,!0)}t.trackPackageInstalledIntoInterpreter=E,t.clearInstalledIntoInterpreterMemento=async function(e,t,n){const r=`${(0,w.getInterpreterHash)({path:n})}#${l.ProductNames.get(t)}`;await e.update(r,void 0)},t.isModulePresentInEnvironmentCache=function(e,t,n){const r=`${(0,w.getInterpreterHash)(n)}#${l.ProductNames.get(t)}`;return e.get(r,!1)},t.isModulePresentInEnvironment=async function(e,t,n){const r=`${(0,w.getInterpreterHash)(n)}#${l.ProductNames.get(t)}`;if(e.get(r,!1))return!0;const i=(0,c.translateProductToModule)(t),o=_.InterpreterPackages.getPackageVersion(n,i).then((e=>"string"==typeof e?"found":"notfound")).catch((e=>(0,f.traceError)("Failed to get interpreter package version",e)));try{const e=await Promise.race([(0,k.sleep)(500),o]);if("string"==typeof e)return"found"===e}catch(e){(0,f.traceError)(`Failed to check if package exists ${l.ProductNames.get(t)}`)}};class x{constructor(e,t){this.serviceContainer=e,this.appShell=e.get(h.IApplicationShell),this.configService=e.get(g.IConfigurationService),this.workspaceService=e.get(h.IWorkspaceService),this.productService=e.get(u.IProductService),this.persistentStateFactory=e.get(g.IPersistentStateFactory)}async install(e,t,n,r,i){const o=this.serviceContainer.get(u.IInstallationChannelManager),s=await o.getInstallationChannel(e,t);if(!s)return u.InstallerResponse.Ignore;if(n.token.isCancellationRequested)return u.InstallerResponse.Cancelled;let a=!0===r?u.ModuleInstallFlags.updateDependencies|u.ModuleInstallFlags.reInstall:void 0;return!0===i&&(a=a?a|u.ModuleInstallFlags.installPipIfRequired:u.ModuleInstallFlags.installPipIfRequired),await s.installModule(e,t,n,a),n.token.isCancellationRequested?u.InstallerResponse.Cancelled:this.isInstalled(e,t).then((e=>e?u.InstallerResponse.Installed:u.InstallerResponse.Ignore))}async isProductVersionCompatible(e,t,n){const r=await this.getProductSemVer(e,n);return r?s.satisfies(r,t)?u.ProductInstallStatus.Installed:u.ProductInstallStatus.NeedsUpgrade:u.ProductInstallStatus.NotInstalled}async getProductSemVer(e,t){const n=this.getExecutableNameFromSettings(e,void 0);let r;if(this.isExecutableAModule(e,void 0)){const e=await this.serviceContainer.get(m.IPythonExecutionFactory).createActivatedEnvironment({interpreter:t,allowEnvironmentFetchExceptions:!0}),i=["-c",`import ${n}; print(${n}.__version__)`];r=(await e.exec(i,{mergeStdOutErr:!0})).stdout.trim()}else{const e=await this.serviceContainer.get(m.IProcessServiceFactory).create(void 0);r=(await e.exec(n,["--version"],{mergeStdOutErr:!0})).stdout.trim()}if(!r)return null;try{return s.coerce(r)}catch(t){return(0,f.traceError)(`Unable to parse version ${r} for product ${e}: `,t),null}}async isInstalled(e,t){const n=this.getExecutableNameFromSettings(e,void 0);return this.isExecutableAModule(e,void 0)?(await this.serviceContainer.get(m.IPythonExecutionFactory).createActivatedEnvironment({resource:void 0,interpreter:t,allowEnvironmentFetchExceptions:!0})).isModuleInstalled(n):(await this.serviceContainer.get(m.IProcessServiceFactory).create(void 0)).exec(n,["--version"],{mergeStdOutErr:!0}).then((()=>!0)).catch((()=>!1))}getExecutableNameFromSettings(e,t){const n=this.productService.getProductType(e);return this.serviceContainer.get(u.IProductPathService,n).getExecutableNameFromSettings(e,t)}isExecutableAModule(e,t){const n=this.productService.getProductType(e);return this.serviceContainer.get(u.IProductPathService,n).isExecutableAModule(e,t)}}r([d.traceDecorators.verbose("Checking if product is installed"),i(1,(0,p.logValue)("path"))],x.prototype,"isInstalled",null);class T extends x{}t.DataScienceInstaller=T;let D=class{constructor(e,t,n,r){this.serviceContainer=e,this.interpreterPackages=t,this.memento=n,this.output=r,this._onInstalled=new a.EventEmitter,this.productService=e.get(u.IProductService)}get onInstalled(){return this._onInstalled.event}dispose(){}async install(e,t,n,r,i){t&&this.interpreterPackages.trackPackages(t);let o="installed";try{const s=await this.createInstaller(e).install(e,t,n,r,i);switch(E(this.memento,e,t).catch(v.noop),s===u.InstallerResponse.Installed&&this._onInstalled.fire({product:e,resource:t}),s){case u.InstallerResponse.Cancelled:o="cancelled";break;case u.InstallerResponse.Installed:o="installed";break;case u.InstallerResponse.Ignore:o="ignored";break;case u.InstallerResponse.Disabled:o="disabled"}return s}catch(e){throw o="failed",e}finally{(0,b.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:o,moduleName:l.ProductNames.get(e)})}}async isInstalled(e,t){return this.createInstaller(e).isInstalled(e,t)}translateProductToModuleName(e){return(0,c.translateProductToModule)(e)}createInstaller(e){if(this.productService.getProductType(e)===u.ProductType.DataScience)return new T(this.serviceContainer,this.output);throw new Error(`Unknown product ${e}`)}};D=r([(0,o.injectable)(),i(0,(0,o.inject)(y.IServiceContainer)),i(1,(0,o.inject)(_.InterpreterPackages)),i(2,(0,o.inject)(g.IMemento)),i(2,(0,o.named)(g.GLOBAL_MEMENTO)),i(3,(0,o.inject)(g.IOutputChannel)),i(3,(0,o.named)(C.STANDARD_OUTPUT_CHANNEL))],D),t.ProductInstaller=D},13982:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProductNames=void 0;const r=n(29299);t.ProductNames=new Map,t.ProductNames.set(r.Product.jupyter,"jupyter"),t.ProductNames.set(r.Product.notebook,"notebook"),t.ProductNames.set(r.Product.ipykernel,"ipykernel"),t.ProductNames.set(r.Product.nbconvert,"nbconvert"),t.ProductNames.set(r.Product.kernelspec,"kernelspec"),t.ProductNames.set(r.Product.pandas,"pandas"),t.ProductNames.set(r.Product.pip,"pip"),t.ProductNames.set(r.Product.ensurepip,"ensurepip")},18342:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataScienceProductPathService=t.BaseProductPathsService=void 0;const o=n(86700),s=n(71017),a=n(71733),c=n(29474),l=n(29299);class u{constructor(e){this.serviceContainer=e,this.configService=e.get(a.IConfigurationService),this.productInstaller=e.get(l.IInstaller)}isExecutableAModule(e,t){if(e===l.Product.kernelspec)return!1;let n;try{n=this.productInstaller.translateProductToModuleName(e,l.ModuleNamePurpose.run)}catch(e){}const r=this.getExecutableNameFromSettings(e,t);return"string"==typeof n&&n.length>0&&s.basename(r)===r}}t.BaseProductPathsService=u;let d=class extends u{constructor(e){super(e)}getExecutableNameFromSettings(e,t){return this.productInstaller.translateProductToModuleName(e,l.ModuleNamePurpose.run)}};d=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IServiceContainer))],d),t.DataScienceProductPathService=d},51023:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.ProductService=void 0;const i=n(86700),o=n(29299);let s=class{constructor(){this.ProductTypes=new Map,this.ProductTypes.set(o.Product.jupyter,o.ProductType.DataScience),this.ProductTypes.set(o.Product.notebook,o.ProductType.DataScience),this.ProductTypes.set(o.Product.ipykernel,o.ProductType.DataScience),this.ProductTypes.set(o.Product.nbconvert,o.ProductType.DataScience),this.ProductTypes.set(o.Product.kernelspec,o.ProductType.DataScience),this.ProductTypes.set(o.Product.pandas,o.ProductType.DataScience),this.ProductTypes.set(o.Product.pip,o.ProductType.DataScience),this.ProductTypes.set(o.Product.ensurepip,o.ProductType.DataScience)}getProductType(e){return this.ProductTypes.get(e)}};s=r([(0,i.injectable)()],s),t.ProductService=s},33816:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerInstallerTypes=void 0;const r=n(41759),i=n(58318),o=n(11705),s=n(76695),a=n(31226),c=n(17927),l=n(18342),u=n(51023),d=n(29299);t.registerInstallerTypes=function(e){e.addSingleton(d.IModuleInstaller,i.CondaInstaller),e.addSingleton(d.IModuleInstaller,s.PipInstaller),e.addSingleton(d.IModuleInstaller,o.PipEnvInstaller),e.addSingleton(d.IModuleInstaller,a.PoetryInstaller),e.addSingleton(d.IInstallationChannelManager,r.InstallationChannelManager),e.addSingleton(d.IProductService,u.ProductService),e.addSingleton(d.IInstaller,c.ProductInstaller),e.addSingleton(d.IProductPathService,l.DataScienceProductPathService,d.ProductType.DataScience)}},29299:(e,t)=>{"use strict";var n,r,i,o,s,a,c;Object.defineProperty(t,"__esModule",{value:!0}),t.IInstaller=t.ModuleInstallFlags=t.IProductPathService=t.IProductService=t.IInstallationChannelManager=t.IPythonInstallation=t.IModuleInstaller=t.ProductType=t.ModuleInstallerType=t.ModuleNamePurpose=t.ProductInstallStatus=t.Product=t.InstallerResponse=void 0,(c=t.InstallerResponse||(t.InstallerResponse={}))[c.Installed=0]="Installed",c[c.Disabled=1]="Disabled",c[c.Ignore=2]="Ignore",c[c.Cancelled=3]="Cancelled",(a=t.Product||(t.Product={}))[a.jupyter=18]="jupyter",a[a.ipykernel=19]="ipykernel",a[a.notebook=20]="notebook",a[a.kernelspec=21]="kernelspec",a[a.nbconvert=22]="nbconvert",a[a.pandas=23]="pandas",a[a.pip=27]="pip",a[a.ensurepip=28]="ensurepip",(s=t.ProductInstallStatus||(t.ProductInstallStatus={}))[s.Installed=0]="Installed",s[s.NotInstalled=1]="NotInstalled",s[s.NeedsUpgrade=2]="NeedsUpgrade",(o=t.ModuleNamePurpose||(t.ModuleNamePurpose={}))[o.install=1]="install",o[o.run=2]="run",(i=t.ModuleInstallerType||(t.ModuleInstallerType={})).Unknown="Unknown",i.Conda="Conda",i.Pip="Pip",i.Poetry="Poetry",i.Pipenv="Pipenv",(r=t.ProductType||(t.ProductType={})).Linter="Linter",r.Formatter="Formatter",r.TestFramework="TestFramework",r.RefactoringLibrary="RefactoringLibrary",r.DataScience="DataScience",t.IModuleInstaller=Symbol("IModuleInstaller"),t.IPythonInstallation=Symbol("IPythonInstallation"),t.IInstallationChannelManager=Symbol("IInstallationChannelManager"),t.IProductService=Symbol("IProductService"),t.IProductPathService=Symbol("IProductPathService"),(n=t.ModuleInstallFlags||(t.ModuleInstallFlags={}))[n.upgrade=1]="upgrade",n[n.updateDependencies=2]="updateDependencies",n[n.reInstall=4]="reInstall",n[n.installPipIfRequired=8]="installPipIfRequired",t.IInstaller=Symbol("IInstaller")},55518:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CDNWidgetScriptSourceProvider=void 0;const r=n(58181),i=n(33715),o=n(71017),s=n(66828),a=n(46318),c=n(7744),l=n(14220),u="https://cdn.jsdelivr.net/npm/",d=n(50202);t.CDNWidgetScriptSourceProvider=class{constructor(e,t,n){this.configurationSettings=e,this.localResourceUriConverter=t,this.fs=n,this.cache=new Map}get cdnProviders(){return this.configurationSettings.getSettings(void 0).widgetScriptSources}dispose(){this.cache.clear()}async getWidgetScriptSource(e,t){const n=this.getModuleKey(e,t);return this.cache.get(n)||this.cache.set(n,this.getWidgetScriptSourceImplementation(e,t)),this.cache.get(n)}async getWidgetScriptSourceImplementation(e,t){const n=this.getModuleKey(e,t),r=o.join(this.localResourceUriConverter.rootScriptFolder.fsPath,n,"index.js");let i;if((0,a.traceInfo)(`${l.ConsoleForegroundColors.Green}Searching for Widget Script ${e}#${t} at path: ${r}`),r&&await this.fs.localFileExists(r))return(0,a.traceInfo)(`${l.ConsoleForegroundColors.Green}Widget Script ${e}#${t} found at path: ${r}`),{moduleName:e,scriptUri:(await this.localResourceUriConverter.asWebviewUri(s.Uri.file(r))).toString(),source:"cdn"};try{if((0,a.traceInfo)(`${l.ConsoleForegroundColors.Green}Widget Script ${e}#${t} searching`),await this.fs.createLocalDirectory(o.dirname(r)),i=await this.downloadFastestCDN(e,t),i){(0,a.traceInfo)(`${l.ConsoleForegroundColors.Green}Wiget ${e} successfully downloaded to temp file ${i.filePath}`),(0,a.traceInfoIfCI)(`Widget Script downloaded for ${e}:${t}, already downloaded ${await this.fs.localFileExists(r)}`),await this.fs.localFileExists(r)||((0,a.traceInfo)(`${l.ConsoleForegroundColors.Green}Wiget ${e} being copied into ${r}`),await this.fs.copyLocal(i.filePath,r));const n=(await this.localResourceUriConverter.asWebviewUri(s.Uri.file(r))).toString();return(0,a.traceInfo)(`${l.ConsoleForegroundColors.Green}Wiget ${e} downloaded into ${n} from cdn (${r})`),{moduleName:e,scriptUri:n,source:"cdn"}}return{moduleName:e}}catch(t){return(0,a.traceError)("Error downloading from CDN: ",t),{moduleName:e}}finally{if(i)try{i.dispose()}catch(e){}}}async downloadFastestCDN(e,t){const n=(0,c.createDeferred)();return Promise.all(this.cdnProviders.map((r=>this.downloadFromCDN(e,t,r).then((e=>{!n.resolved&&e&&n.resolve(e)}))))).then((e=>{n.resolved||n.resolve(void 0)})).ignoreErrors(),n.promise}async downloadFromCDN(e,t,n){const r=await this.generateDownloadUri(e,t,n);if(r)try{return await this.downloadFile(r)}catch(e){}}async generateDownloadUri(e,t,n){const r=function(e){switch(e){case"unpkg.com":return"https://unpkg.com/";case"jsdelivr.com":return u}}(n);if(r)return function(e,t,n){let r=t,i="index",o=t.indexOf("/");return-1!==o&&"@"===t[0]&&(o=t.indexOf("/",o+1)),-1!==o&&(i=t.substr(o+1),r=t.substr(0,o)),e===u&&(n.startsWith("^")&&(n=n.slice(1)),i.endsWith(".js")||(i=i.concat(".js"))),`${e}${r}@${n}/dist/${i}`}(r,e,t)}getModuleKey(e,t){return d((0,i.sha256)().update(`${e}${t}`).digest("hex"))}async downloadFile(e){const t=await this.fs.createTemporaryLocalFile(".js");let n=5,i=!1;for(;n>0&&!i;)try{(0,a.traceInfo)(`${l.ConsoleForegroundColors.Green}Downloading from CDN ${e} into ${t.filePath}`),await r(e,o.dirname(t.filePath),{filename:o.basename(t.filePath)}),(0,a.traceInfo)(`${l.ConsoleForegroundColors.Green}Successfully downloaded from CDN ${e} into ${t.filePath}`),i=!0}catch(t){(0,a.traceInfo)(`Error downloading from ${e}: `,t)}finally{n-=1}if(i)return t;t.dispose()}}},46962:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CommonMessageCoordinator=void 0;const r=n(66828),i=n(13395),o=n(97784),s=n(46318),a=n(60593),c=n(12698),l=n(71733),u=n(35952),d=n(95063),p=n(31134),h=n(65725),f=n(48497),m=n(14220),g=n(97045),v=n(70403),y=n(83474),b=n(43367),_=n(2596),w=n(14813);class S{constructor(e,t){this.document=e,this.serviceContainer=t,this.cachedMessages=[],this.postEmitter=new r.EventEmitter,this.disposables=this.serviceContainer.get(l.IDisposableRegistry),this.jupyterOutput=this.serviceContainer.get(l.IOutputChannel,o.STANDARD_OUTPUT_CHANNEL),this.appShell=this.serviceContainer.get(i.IApplicationShell,i.IApplicationShell),this.commandManager=this.serviceContainer.get(i.ICommandManager),this.configService=this.serviceContainer.get(l.IConfigurationService)}get postMessage(){return this.listeningToPostMessageEvent=!0,this.postEmitter.event}static async create(e,t){const n=new S(e,t);return await n.initialize(),(0,s.traceVerbose)("Created and initailized CommonMessageCoordinator"),n}dispose(){var e,t;null===(e=this.ipyWidgetMessageDispatcher)||void 0===e||e.dispose(),null===(t=this.ipyWidgetScriptSource)||void 0===t||t.dispose()}onMessage(e,t){e===h.InteractiveWindowMessages.IPyWidgetLoadSuccess?this.sendLoadSucceededTelemetry(t):e===h.InteractiveWindowMessages.IPyWidgetLoadFailure?this.handleWidgetLoadFailure(t):e===h.InteractiveWindowMessages.IPyWidgetWidgetVersionNotSupported?this.sendUnsupportedWidgetVersionFailureTelemetry(t):e===h.InteractiveWindowMessages.IPyWidgetRenderFailure?this.sendRenderFailureTelemetry(t):e===h.InteractiveWindowMessages.IPyWidgetUnhandledKernelMessage&&this.handleUnhandledMessage(t),this.getIPyWidgetMessageDispatcher().receiveMessage({message:e,payload:t}),this.getIPyWidgetScriptSource().onMessage(e,t)}async initialize(){(0,s.traceVerbose)("initialize CommonMessageCoordinator");const e=this.getIPyWidgetScriptSource().initialize();await e.then((()=>this.getIPyWidgetMessageDispatcher().initialize()))}sendLoadSucceededTelemetry(e){try{(0,g.sendTelemetryEvent)(y.Telemetry.IPyWidgetLoadSuccess,0,{moduleHash:(0,v.getTelemetrySafeHashedString)(e.moduleName),moduleVersion:e.moduleVersion})}catch(e){}}handleWidgetLoadFailure(e){try{let t=e.error.toString();const n=this.configService.getSettings(void 0).widgetScriptSources.length>0;if(e.isOnline){if(!n){const n=u.Common.moreInfo(),r=u.DataScience.enableCDNForWidgetsButton();t=u.DataScience.enableCDNForWidgetsSetting().format(e.moduleName,e.moduleVersion),this.appShell.showErrorMessage(t,r,n).then((e=>{switch(e){case n:this.appShell.openUrl("https://aka.ms/PVSCIPyWidgets");break;case r:this.commandManager.executeCommand(y.Commands.EnableLoadingWidgetsFrom3rdPartySource)}}),d.noop)}}else t=u.DataScience.loadClassFailedWithNoInternet().format(e.moduleName,e.moduleVersion),this.appShell.showErrorMessage(t).then(d.noop,d.noop);(0,s.traceError)(`Widget load failure ${t}`,e),(0,g.sendTelemetryEvent)(y.Telemetry.IPyWidgetLoadFailure,0,{isOnline:e.isOnline,moduleHash:(0,v.getTelemetrySafeHashedString)(e.moduleName),moduleVersion:e.moduleVersion,timedout:e.timedout})}catch(e){}}sendUnsupportedWidgetVersionFailureTelemetry(e){try{(0,g.sendTelemetryEvent)(y.Telemetry.IPyWidgetWidgetVersionNotSupportedLoadFailure,0,{moduleHash:(0,v.getTelemetrySafeHashedString)(e.moduleName),moduleVersion:e.moduleVersion})}catch(e){}}sendRenderFailureTelemetry(e){try{(0,s.traceError)("Error rendering a widget: ",e),(0,g.sendTelemetryEvent)(y.Telemetry.IPyWidgetRenderFailure)}catch(e){}}handleUnhandledMessage(e){if("status"!==e.header.msg_type)try{if("error"===e.header.msg_type){const t=e;t.content.traceback=t.content.traceback.map(p.stripAnsi)}(0,s.traceInfo)(`Unhandled widget kernel message: ${e.header.msg_type} ${e.content}`),this.jupyterOutput.appendLine(u.DataScience.unhandledMessage().format(e.header.msg_type,JSON.stringify(e.content))),(0,g.sendTelemetryEvent)(y.Telemetry.IPyWidgetUnhandledMessage,void 0,{msg_type:e.header.msg_type})}catch(e){}}getIPyWidgetMessageDispatcher(){return this.ipyWidgetMessageDispatcher||(this.ipyWidgetMessageDispatcher=this.serviceContainer.get(_.IPyWidgetMessageDispatcherFactory).create(this.document),this.disposables.push(this.ipyWidgetMessageDispatcher.postMessage(this.cacheOrSend,this))),this.ipyWidgetMessageDispatcher}getIPyWidgetScriptSource(){return this.ipyWidgetScriptSource||(this.ipyWidgetScriptSource=new w.IPyWidgetScriptSource(this.document,this.serviceContainer.get(b.IKernelProvider),this.serviceContainer.get(l.IDisposableRegistry),this.serviceContainer.get(a.IFileSystem),this.serviceContainer.get(f.IInterpreterService),this.serviceContainer.get(l.IConfigurationService),this.serviceContainer.get(l.IHttpClient),this.serviceContainer.get(i.IApplicationShell),this.serviceContainer.get(i.IWorkspaceService),this.serviceContainer.get(l.IPersistentStateFactory),this.serviceContainer.get(l.IExtensionContext),this.serviceContainer.get(c.IPythonExecutionFactory)),this.disposables.push(this.ipyWidgetScriptSource.postMessage(this.cacheOrSend,this))),this.ipyWidgetScriptSource}cacheOrSend(e){if(!this.listeningToPostMessageEvent)return(0,s.traceInfoIfCI)(`${m.ConsoleForegroundColors.Green}Queuing messages (no listenerts)`),void this.cachedMessages.push(e);this.cachedMessages.forEach((e=>this.postEmitter.fire(e))),this.cachedMessages=[],this.postEmitter.fire(e)}}t.CommonMessageCoordinator=S},9972:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WIDGET_MIMETYPE=void 0,t.WIDGET_MIMETYPE="application/vnd.jupyter.widget-view+json"},67666:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IPyWidgetMessageDispatcher=void 0;const r=n(73837),i=n(71171),o=n(66828),s=n(46318),a=n(7744),c=n(95063),l=n(16880),u=n(65725),d=n(97045),p=n(83474),h=n(9972);t.IPyWidgetMessageDispatcher=class{constructor(e,t){this.kernelProvider=e,this.document=t,this.commTargetsRegistered=new Set,this.pendingTargetNames=new Set,this._postMessageEmitter=new o.EventEmitter,this.messageHooks=new Map,this.pendingHookRemovals=new Map,this.messageHookRequests=new Map,this.disposables=[],this.disposed=!1,this.pendingMessages=[],this.subscribedToKernelSocket=!1,this.waitingMessageIds=new Map,this.totalWaitTime=0,this.totalWaitedMessages=0,this.hookCount=0,this.outputWidgetIds=new Set,this.isUsingIPyWidgets=!1,this.pendingTargetNames.add("jupyter.widget"),e.onDidStartKernel((e=>{e.notebookDocument===t&&this.initialize()}),this,this.disposables),this.mirrorSend=this.mirrorSend.bind(this),this.onKernelSocketMessage=this.onKernelSocketMessage.bind(this);const r=n(642);this.deserialize=r.deserialize}get postMessage(){return this._postMessageEmitter.event}dispose(){for(this.sendOverheadTelemetry(),this.disposed=!0;this.disposables.length;){const e=this.disposables.shift();null==e||e.dispose()}}receiveMessage(e){switch(process.env.VSC_JUPYTER_LOG_IPYWIDGETS&&e.message.includes("IPyWidgets_")&&(0,s.traceInfoIfCI)(`IPyWidgetMessage: ${r.inspect(e)}`),e.message){case u.IPyWidgetMessages.IPyWidgets_logMessage:(0,s.traceInfoIfCI)(`Widget Message: ${e.payload}`);break;case u.IPyWidgetMessages.IPyWidgets_Ready:this.sendKernelOptions(),this.initialize();break;case u.IPyWidgetMessages.IPyWidgets_msg:this.sendRawPayloadToKernelSocket(e.payload);break;case u.IPyWidgetMessages.IPyWidgets_binary_msg:this.sendRawPayloadToKernelSocket((0,l.deserializeDataViews)(e.payload)[0]);break;case u.IPyWidgetMessages.IPyWidgets_msg_received:this.onKernelSocketResponse(e.payload);break;case u.IPyWidgetMessages.IPyWidgets_registerCommTarget:this.registerCommTarget(e.payload);break;case u.IPyWidgetMessages.IPyWidgets_RegisterMessageHook:this.registerMessageHook(e.payload);break;case u.IPyWidgetMessages.IPyWidgets_RemoveMessageHook:this.possiblyRemoveMessageHook(e.payload);break;case u.IPyWidgetMessages.IPyWidgets_MessageHookResult:this.handleMessageHookResponse(e.payload);break;case u.IPyWidgetMessages.IPyWidgets_iopub_msg_handled:this.iopubMessageHandled(e.payload)}}sendRawPayloadToKernelSocket(e){this.pendingMessages.push(e),this.sendPendingMessages()}registerCommTarget(e){this.pendingTargetNames.add(e),this.initialize()}initialize(){this.jupyterLab||(this.jupyterLab=n(36879));const e=this.getKernel();e&&(this.subscribeToKernelSocket(e),this.registerCommTargets(e)),(0,s.traceVerbose)("IPyWidgetMessageDispatcher.initialize")}raisePostMessage(e,t){this._postMessageEmitter.fire({message:e,payload:t})}subscribeToKernelSocket(e){!this.subscribedToKernelSocket&&e.session&&(this.subscribedToKernelSocket=!0,e.session.kernelSocket.subscribe((t=>{var n,r,i,o,s,a;if(null===(r=null===(n=this.kernelSocketInfo)||void 0===n?void 0:n.socket)||void 0===r||r.removeReceiveHook(this.onKernelSocketMessage),null===(o=null===(i=this.kernelSocketInfo)||void 0===i?void 0:i.socket)||void 0===o||o.removeSendHook(this.mirrorSend),this.kernelWasConnectedAtLeastOnce){for(;this.pendingMessages.length;)this.pendingMessages.shift();this.waitingMessageIds.forEach((e=>e.resultPromise.resolve())),this.waitingMessageIds.clear(),this.messageHookRequests.forEach((e=>e.resolve(!1))),this.messageHookRequests.clear(),this.messageHooks.clear(),this.sendRestartKernel()}t&&t.socket?(this.kernelWasConnectedAtLeastOnce=!0,this.kernelSocketInfo=t,null===(s=this.kernelSocketInfo.socket)||void 0===s||s.addReceiveHook(this.onKernelSocketMessage),null===(a=this.kernelSocketInfo.socket)||void 0===a||a.addSendHook(this.mirrorSend),this.sendKernelOptions(),this.registerCommTargets(e),this.sendPendingMessages()):this.kernelSocketInfo=void 0})))}sendKernelOptions(){this.kernelSocketInfo&&this.raisePostMessage(u.IPyWidgetMessages.IPyWidgets_kernelOptions,this.kernelSocketInfo.options)}async mirrorSend(e,t){if("string"==typeof e&&e.includes("shell")&&e.includes("execute_request")){const t=Date.now(),n=this.deserialize(e);if("shell"===n.channel&&"execute_request"===n.header.msg_type){const e=this.mirrorExecuteRequest(n);this.isUsingIPyWidgets&&await e,this.totalWaitTime=Date.now()-t,this.totalWaitedMessages+=1}}}sendRestartKernel(){this.raisePostMessage(u.IPyWidgetMessages.IPyWidgets_onRestartKernel,void 0)}mirrorExecuteRequest(e){const t=(0,a.createDeferred)();return this.waitingMessageIds.set(e.header.msg_id,{startTime:Date.now(),resultPromise:t}),this.raisePostMessage(u.IPyWidgetMessages.IPyWidgets_mirror_execute,{id:e.header.msg_id,msg:e}),t.promise}messageNeedsFullHandle(e){var t,n,r,i;return"iopub"===e.channel&&"comm_msg"===(null===(t=e.header)||void 0===t?void 0:t.msg_type)&&"update"===(null===(r=null===(n=e.content)||void 0===n?void 0:n.data)||void 0===r?void 0:r.method)&&this.outputWidgetIds.has(null===(i=e.content)||void 0===i?void 0:i.comm_id)}iopubMessageHandled(e){const t=e.id;this.fullHandleMessage&&this.fullHandleMessage.id===t&&(this.fullHandleMessage.promise.resolve(),this.fullHandleMessage=void 0)}async onKernelSocketMessage(e){var t,n,r,o,s,c,d,f,m;const g=i(),v=(0,a.createDeferred)();if(this.waitingMessageIds.set(g,{startTime:Date.now(),resultPromise:v}),"string"==typeof e?this.raisePostMessage(u.IPyWidgetMessages.IPyWidgets_msg,{id:g,data:e}):this.raisePostMessage(u.IPyWidgetMessages.IPyWidgets_binary_msg,{id:g,data:(0,l.serializeDataViews)([e])}),"string"!=typeof e||e.includes(h.WIDGET_MIMETYPE)||e.includes(p.Identifiers.DefaultCommTarget)||e.includes("comm_open")||e.includes("comm_close")||e.includes("comm_msg")){const i=this.deserialize(e);i&&i.content&&i.content.data&&(i.content.data[h.WIDGET_MIMETYPE]||i.content.target_name===p.Identifiers.DefaultCommTarget)&&(this.isUsingIPyWidgets=!0);const l="comm_open"===(null===(t=i.header)||void 0===t?void 0:t.msg_type)&&"@jupyter-widgets/output"===(null===(o=null===(r=null===(n=i.content)||void 0===n?void 0:n.data)||void 0===r?void 0:r.state)||void 0===o?void 0:o._model_module)&&"OutputModel"===(null===(d=null===(c=null===(s=i.content)||void 0===s?void 0:s.data)||void 0===c?void 0:c.state)||void 0===d?void 0:d._model_name),u="comm_close"===(null===(f=i.header)||void 0===f?void 0:f.msg_type)&&this.outputWidgetIds.has(null===(m=i.content)||void 0===m?void 0:m.comm_id);l?this.outputWidgetIds.add(i.content.comm_id):u?this.outputWidgetIds.delete(i.content.comm_id):this.messageNeedsFullHandle(i)&&(this.fullHandleMessage={id:i.header.msg_id,promise:(0,a.createDeferred)()},await v.promise,await this.fullHandleMessage.promise.promise,this.fullHandleMessage=void 0)}}onKernelSocketResponse(e){const t=this.waitingMessageIds.get(e.id);t&&(this.waitingMessageIds.delete(e.id),this.totalWaitTime+=Date.now()-t.startTime,this.totalWaitedMessages+=1,t.resultPromise.resolve())}sendPendingMessages(){var e,t;if((null===(e=this.kernel)||void 0===e?void 0:e.session)&&this.kernelSocketInfo)for(;this.pendingMessages.length;)try{null===(t=this.kernelSocketInfo.socket)||void 0===t||t.sendToRealKernel(this.pendingMessages[0]),this.pendingMessages.shift()}catch(e){return void(0,s.traceError)("Failed to send message to Kernel",e)}}registerCommTargets(e){for(var t;this.pendingTargetNames.size>0;){const n=Array.from([...this.pendingTargetNames.values()]).shift();if(n){if(this.commTargetsRegistered.has(n))return;(0,s.traceVerbose)(`Registering commtarget ${n}`),this.commTargetsRegistered.add(n),this.pendingTargetNames.delete(n),n!==p.Identifiers.DefaultCommTarget&&(null===(t=e.session)||void 0===t||t.registerCommTarget(n,c.noop))}}}getKernel(){var e,t;return this.document&&!(null===(e=this.kernel)||void 0===e?void 0:e.session)&&(this.kernel=this.kernelProvider.get(this.document),null===(t=this.kernel)||void 0===t||t.onDisposed((()=>this.kernel=void 0))),this.kernel&&!this.kernelRestartHandlerAttached&&(this.kernelRestartHandlerAttached=!0,this.disposables.push(this.kernel.onRestarted(this.handleKernelRestarts,this))),this.kernel}async handleKernelRestarts(){var e;!this.disposed&&0!==this.commTargetsRegistered.size&&(null===(e=this.kernel)||void 0===e?void 0:e.session)&&(Array.from(this.commTargetsRegistered.keys()).forEach((e=>{this.commTargetsRegistered.delete(e),this.pendingTargetNames.add(e)})),this.subscribeToKernelSocket(this.kernel),this.registerCommTargets(this.kernel))}registerMessageHook(e){var t,n;try{if((null===(t=this.kernel)||void 0===t?void 0:t.session)&&!this.messageHooks.has(e)){this.hookCount+=1;const t=this.messageHookCallback.bind(this);this.messageHooks.set(e,t),null===(n=this.kernel)||void 0===n||n.session.registerMessageHook(e,t)}}finally{this.raisePostMessage(u.IPyWidgetMessages.IPyWidgets_ExtensionOperationHandled,{id:e,type:u.IPyWidgetMessages.IPyWidgets_RegisterMessageHook})}}possiblyRemoveMessageHook(e){try{e.lastHookedMsgId?this.pendingHookRemovals.set(e.lastHookedMsgId,e.hookMsgId):this.removeMessageHook(e.hookMsgId)}finally{this.raisePostMessage(u.IPyWidgetMessages.IPyWidgets_ExtensionOperationHandled,{id:e.hookMsgId,type:u.IPyWidgetMessages.IPyWidgets_RemoveMessageHook})}}removeMessageHook(e){var t,n;if((null===(t=this.kernel)||void 0===t?void 0:t.session)&&this.messageHooks.has(e)){const t=this.messageHooks.get(e);this.messageHooks.delete(e),null===(n=this.kernel)||void 0===n||n.session.removeMessageHook(e,t)}}async messageHookCallback(e){const t=(0,a.createDeferred)(),n=i(),r=e.parent_header.msg_id;if(this.messageHooks.has(r)?(this.messageHookRequests.set(n,t),this.raisePostMessage(u.IPyWidgetMessages.IPyWidgets_MessageHookCall,{requestId:n,parentId:r,msg:e})):t.resolve(!0),this.pendingHookRemovals.has(e.header.msg_id)){const t=this.pendingHookRemovals.get(e.header.msg_id);this.pendingHookRemovals.delete(e.header.msg_id),this.removeMessageHook(t)}return t.promise}handleMessageHookResponse(e){const t=this.messageHookRequests.get(e.requestId);t&&(this.messageHookRequests.delete(e.requestId),t.resolve(!!e.msgType.includes("comm")||e.result))}sendOverheadTelemetry(){(0,d.sendTelemetryEvent)(p.Telemetry.IPyWidgetOverhead,0,{totalOverheadInMs:this.totalWaitTime,numberOfMessagesWaitedOn:this.totalWaitedMessages,averageWaitTime:this.totalWaitTime/this.totalWaitedMessages,numberOfRegisteredHooks:this.hookCount})}}},2596:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.IPyWidgetMessageDispatcherFactory=void 0;const o=n(86700),s=n(66828),a=n(71733),c=n(65725),l=n(43367),u=n(67666);class d{constructor(e,t){this.baseMulticaster=e,this.oldMessages=t,this._postMessageEmitter=new s.EventEmitter,this.disposables=[],e.postMessage(this.raisePostMessage,this,this.disposables)}get postMessage(){return this._postMessageEmitter.event}dispose(){for(;this.disposables.length;){const e=this.disposables.shift();null==e||e.dispose()}}initialize(){return this.baseMulticaster.initialize()}receiveMessage(e){this.baseMulticaster.receiveMessage(e)}raisePostMessage(e){this.oldMessages.forEach((e=>{this._postMessageEmitter.fire(e)})),this.oldMessages=[],this._postMessageEmitter.fire(e)}}let p=class{constructor(e,t){this.kernelProvider=t,this.messageDispatchers=new WeakMap,this.messagesPerNotebook=new WeakMap,this.disposed=!1,this.disposables=[],e.push(this),t.onDidDisposeKernel(this.trackDisposingOfKernels,this,e)}dispose(){var e;for(this.disposed=!0;this.disposables.length;)null===(e=this.disposables.shift())||void 0===e||e.dispose()}create(e){let t=this.messageDispatchers.get(e);t||(t=new u.IPyWidgetMessageDispatcher(this.kernelProvider,e),this.messageDispatchers.set(e,t),this.disposables.push(t.postMessage((t=>this.onMessage(t,e)),this)));let n=[];e&&this.messagesPerNotebook.get(e)&&(n=this.messagesPerNotebook.get(e)||[]);const r=new d(t,n);return this.disposables.push(r),r}trackDisposingOfKernels(e){if(this.disposed)return;const t=this.messageDispatchers.get(e.notebookDocument);this.messageDispatchers.delete(e.notebookDocument),null==t||t.dispose()}onMessage(e,t){t&&(this.messagesPerNotebook.set(t,this.messagesPerNotebook.get(t)||[]),e.message!==c.IPyWidgetMessages.IPyWidgets_kernelOptions&&e.message!==c.IPyWidgetMessages.IPyWidgets_registerCommTarget||this.messagesPerNotebook.get(t).push(e))}};p=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IDisposableRegistry)),i(1,(0,o.inject)(l.IKernelProvider))],p),t.IPyWidgetMessageDispatcherFactory=p},14813:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IPyWidgetScriptSource=void 0;const r=n(33715),i=n(71017),o=n(66828),s=n(46318),a=n(7744),c=n(65725),l=n(14220),u=n(97045),d=n(83474),p=n(23895),h=n(49754),f=n(50202);t.IPyWidgetScriptSource=class{constructor(e,t,n,r,a,c,l,u,d,p,h,f){this.document=e,this.kernelProvider=t,this.fs=r,this.interpreterService=a,this.configurationSettings=c,this.httpClient=l,this.appShell=u,this.workspaceService=d,this.stateFactory=p,this.factory=f,this.resourcesMappedToExtensionFolder=new Map,this.postEmitter=new o.EventEmitter,this.disposables=[],this.pendingModuleRequests=new Map,this.uriConversionPromises=new Map,this._rootScriptFolder=i.join(h.extensionPath,"tmp","scripts"),this.targetWidgetScriptsFolder=i.join(this._rootScriptFolder,"nbextensions"),this.createTargetWidgetScriptsFolder=this.fs.localDirectoryExists(this.targetWidgetScriptsFolder).then((async e=>(e||await this.fs.createLocalDirectory(this.targetWidgetScriptsFolder),this.targetWidgetScriptsFolder))),n.push(this),this.kernelProvider.onDidStartKernel((e=>{e.notebookDocument===this.document&&this.initialize().catch(s.traceError.bind("Failed to initialize"))}),this,this.disposables)}get postMessage(){return this.postEmitter.event}get rootScriptFolder(){return o.Uri.file(this._rootScriptFolder)}async asWebviewUri(e){if(!this.isInScriptPath(e.fsPath)){if(this.document&&!this.resourcesMappedToExtensionFolder.has(e.fsPath)){const t=(0,a.createDeferred)();this.resourcesMappedToExtensionFolder.set(e.fsPath,t.promise);try{const n=await this.fs.getFileHash(e.fsPath),a=f((0,r.sha256)().update(`${e.fsPath}${n}`).digest("hex")),c=await this.createTargetWidgetScriptsFolder,l=o.Uri.file(i.join(c,`${a}${i.basename(e.fsPath)}`));await this.fs.localFileExists(l.fsPath)||await this.fs.copyLocal(e.fsPath,l.fsPath),(0,s.traceInfo)(`Widget Script file ${e.fsPath} mapped to ${l.fsPath}`),t.resolve(l)}catch(n){(0,s.traceError)(`Failed to map widget Script file ${e.fsPath}`),t.reject(n)}}e=await this.resourcesMappedToExtensionFolder.get(e.fsPath)}const t=e.toString();return this.uriConversionPromises.has(t)||(this.uriConversionPromises.set(t,(0,a.createDeferred)()),this.postEmitter.fire({message:c.InteractiveWindowMessages.ConvertUriForUseInWebViewRequest,payload:e})),this.uriConversionPromises.get(t).promise}dispose(){for(var e;this.disposables.length;)null===(e=this.disposables.shift())||void 0===e||e.dispose()}onMessage(e,t){if(e===c.InteractiveWindowMessages.ConvertUriForUseInWebViewResponse){const e=t;e&&this.uriConversionPromises.get(e.request.toString())&&this.uriConversionPromises.get(e.request.toString()).resolve(e.response)}else if(e===c.IPyWidgetMessages.IPyWidgets_WidgetScriptSourceRequest&&t){const{moduleName:e,moduleVersion:n}=t;(0,s.traceInfo)(`${l.ConsoleForegroundColors.Green}Fetch Script for ${JSON.stringify(t)}`),this.sendWidgetSource(e,n).catch(s.traceError.bind(void 0,"Failed to send widget sources upon ready"))}}async initialize(){this.jupyterLab||(this.jupyterLab=n(36879)),this.kernel||(this.kernel=await this.kernelProvider.get(this.document)),this.kernel&&(this.scriptProvider||(this.scriptProvider=new p.IPyWidgetScriptSourceProvider(this.kernel,this,this.fs,this.interpreterService,this.appShell,this.configurationSettings,this.workspaceService,this.stateFactory,this.httpClient,this.factory),this.initializeNotebook(),(0,s.traceVerbose)("IPyWidgetScriptSource.initialize")))}async sendWidgetSource(e,t="*"){if(!e||e.startsWith("@jupyter"))return;if(!this.kernel||!this.scriptProvider)return void this.pendingModuleRequests.set(e,t);let n={moduleName:e};try{(0,s.traceInfo)(`${l.ConsoleForegroundColors.Green}Fetch Script for ${e}`),n=await this.scriptProvider.getWidgetScriptSource(e,t)}catch(e){(0,s.traceError)("Failed to get widget source due to an error",e),(0,u.sendTelemetryEvent)(d.Telemetry.HashedIPyWidgetScriptDiscoveryError)}finally{(0,s.traceInfo)(`${l.ConsoleForegroundColors.Green}Script for ${e}, is ${n.scriptUri} from ${n.source}`),this.postEmitter.fire({message:c.IPyWidgetMessages.IPyWidgets_WidgetScriptSourceResponse,payload:n})}}initializeNotebook(){this.kernel&&(this.kernel.onDisposed((()=>this.dispose())),this.handlePendingRequests())}handlePendingRequests(){const e=Array.from(this.pendingModuleRequests.keys());for(;e.length;){const t=e.shift();if(t){const e=this.pendingModuleRequests.get(t);this.pendingModuleRequests.delete(t),this.sendWidgetSource(t,e).catch(s.traceError.bind(`Failed to send WidgetScript for ${t}`))}}}isInScriptPath(e){const t=i.normalize(this._rootScriptFolder);return e=i.normalize(e),(0,h.getOSType)()===h.OSType.Windows?e.toUpperCase().startsWith(t.toUpperCase()):e.startsWith(t)}}},23895:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IPyWidgetScriptSourceProvider=void 0;const r=n(66828);n(30895);const i=n(46318),o=n(7744),s=n(35952),a=n(95063),c=n(97045),l=n(70403),u=n(83474),d=n(55518),p=n(51970),h=n(37625);t.IPyWidgetScriptSourceProvider=class{constructor(e,t,n,r,i,o,s,a,c,l){this.kernel=e,this.localResourceUriConverter=t,this.fs=n,this.interpreterService=r,this.appShell=i,this.configurationSettings=o,this.workspaceService=s,this.stateFactory=a,this.httpClient=c,this.factory=l,this.notifiedUserAboutWidgetScriptNotFound=new Set,this.userConfiguredCDNAtLeastOnce=this.stateFactory.createGlobalPersistentState("IPYWidgetCDNConfigured",!1),this.neverWarnAboutScriptsNotFoundOnCDN=this.stateFactory.createGlobalPersistentState("IPYWidgetNotFoundOnCDN",!1)}get configuredScriptSources(){return this.configurationSettings.getSettings(void 0).widgetScriptSources}initialize(){this.workspaceService.onDidChangeConfiguration(this.onSettingsChagned.bind(this))}dispose(){this.disposeScriptProviders()}async getWidgetScriptSource(e,t){await this.configureWidgets(),this.scriptProviders||this.rebuildProviders();const n=(this.scriptProviders||[]).slice();let r={moduleName:e};for(;n.length;){const i=n.shift();if(!i)continue;const o=await i.getWidgetScriptSource(e,t);if(o.scriptUri){r=o;break}}return(0,c.sendTelemetryEvent)(u.Telemetry.HashedIPyWidgetNameUsed,void 0,{hashedName:(0,l.getTelemetrySafeHashedString)(r.moduleName),source:r.source,cdnSearched:this.configuredScriptSources.length>0}),r.scriptUri||(0,i.traceError)(`Script source for Widget ${e}@${t} not found`),this.handleWidgetSourceNotFoundOnCDN(r,t).ignoreErrors(),r}async handleWidgetSourceNotFoundOnCDN(e,t){if("cdn"!==e.source&&!0!==this.neverWarnAboutScriptsNotFoundOnCDN.value&&!this.notifiedUserAboutWidgetScriptNotFound.has(e.moduleName)&&0!==this.configuredScriptSources.length)switch(this.notifiedUserAboutWidgetScriptNotFound.add(e.moduleName),await this.appShell.showWarningMessage(s.DataScience.widgetScriptNotFoundOnCDNWidgetMightNotWork().format(e.moduleName,t,JSON.stringify(this.configuredScriptSources)),s.Common.ok(),s.Common.doNotShowAgain(),s.Common.reportThisIssue())){case s.Common.doNotShowAgain():return this.neverWarnAboutScriptsNotFoundOnCDN.updateValue(!0);case s.Common.reportThisIssue():return this.appShell.openUrl("https://aka.ms/CreatePVSCDataScienceIssue");default:(0,a.noop)()}}onSettingsChagned(e){e.affectsConfiguration("jupyter.widgetScriptSources")&&this.rebuildProviders()}disposeScriptProviders(){for(;this.scriptProviders&&this.scriptProviders.length;){const e=this.scriptProviders.shift();e&&e.dispose()}}rebuildProviders(){this.disposeScriptProviders();const e=[];switch(this.configuredScriptSources.length>0&&e.push(new d.CDNWidgetScriptSourceProvider(this.configurationSettings,this.localResourceUriConverter,this.fs)),this.kernel.kernelConnectionMetadata.kind){case"connectToLiveKernel":case"startUsingRemoteKernelSpec":e.push(new h.RemoteWidgetScriptSourceProvider(this.kernel.kernelConnectionMetadata.baseUrl,this.httpClient));break;default:e.push(new p.LocalWidgetScriptSourceProvider(this.kernel,this.localResourceUriConverter,this.fs,this.interpreterService,this.factory))}this.scriptProviders=e}async configureWidgets(){if(0!==this.configuredScriptSources.length)return;if(this.userConfiguredCDNAtLeastOnce.value)return;if(this.configurationPromise)return this.configurationPromise.promise;this.configurationPromise=(0,o.createDeferred)(),(0,c.sendTelemetryEvent)(u.Telemetry.IPyWidgetPromptToUseCDN);const e=await this.appShell.showInformationMessage(s.DataScience.useCDNForWidgets(),s.Common.ok(),s.Common.cancel(),s.Common.doNotShowAgain());let t="dismissed";switch(e){case s.Common.ok():t="ok",await Promise.all([this.updateScriptSources(["jsdelivr.com","unpkg.com"]),this.userConfiguredCDNAtLeastOnce.updateValue(!0)]);break;case s.Common.doNotShowAgain():t="doNotShowAgain",await Promise.all([this.updateScriptSources([]),this.userConfiguredCDNAtLeastOnce.updateValue(!0)]);break;default:t=e===s.Common.cancel()?"cancel":"dismissed"}(0,c.sendTelemetryEvent)(u.Telemetry.IPyWidgetPromptToUseCDNSelection,void 0,{selection:t}),this.configurationPromise.resolve()}async updateScriptSources(e){await this.configurationSettings.updateSetting("widgetScriptSources",e,void 0,r.ConfigurationTarget.Global)}}},51970:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalWidgetScriptSourceProvider=void 0;const i=n(71017),o=n(66828),s=n(46318),a=n(97045),c=n(83474),l=n(93828);class u{constructor(e,t,n,r,i){this.kernel=e,this.localResourceUriConverter=t,this.fs=n,this.interpreterService=r,this.factory=i}async getWidgetScriptSource(e){return(await this.getWidgetScriptSources()).find((t=>t.moduleName.toLowerCase()===e.toLowerCase()))||{moduleName:e}}dispose(){}async getWidgetScriptSources(e){return!e&&this.cachedWidgetScripts?this.cachedWidgetScripts:this.cachedWidgetScripts=this.getWidgetScriptSourcesWithoutCache()}async getWidgetScriptSourcesWithoutCache(){const e=await this.getSysPrefixOfKernel();if(!e)return[];const t=i.join(e,"share","jupyter","nbextensions"),n=(await this.fs.searchLocal(`*${i.sep}index.js`,t)).filter((e=>2===e.split("/").length||((0,s.traceError)("Incorrect file found when searching for nnbextension entrypoints"),!1))).map((async e=>{const n=e.split("/")[0],r=o.Uri.file(i.join(t,e));return{moduleName:n,scriptUri:(await this.localResourceUriConverter.asWebviewUri(r)).toString(),source:"local"}}));return Promise.all(n)}async getSysPrefixOfKernel(){const e=this.kernel.kernelConnectionMetadata;if(!e)return;const t=(0,l.getInterpreterFromKernelConnectionMetadata)(e);if(null==t?void 0:t.sysPrefix)return null==t?void 0:t.sysPrefix;if(!(0,l.isPythonKernelConnection)(e))return;const n=(null==t?void 0:t.path)||(0,l.getKernelPathFromKernelConnection)(e);if(!n)return;const r=await this.interpreterService.getInterpreterDetails(n).catch(s.traceError.bind(`Failed to get interpreter details for Kernel/Interpreter ${n}`));if(r&&!r.sysPrefix){const e=await this.factory.createActivatedEnvironment({interpreter:r}),t=await e.getInterpreterInformation();return null==t?void 0:t.sysPrefix}return r?null==r?void 0:r.sysPrefix:void 0}}r([(0,a.captureTelemetry)(c.Telemetry.DiscoverIPyWidgetNamesLocalPerf)],u.prototype,"getWidgetScriptSourcesWithoutCache",null),t.LocalWidgetScriptSourceProvider=u},94137:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.NotebookIPyWidgetCoordinator=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(33149),l=n(2687),u=n(46318),d=n(29140),p=n(71733),h=n(7744),f=n(95063),m=n(65725),g=n(29474),v=n(14220),y=n(46962);class b{constructor(e,t){this.editor=e,this.pendingMessages=[],this.disposables=[],this._onDidReceiveMessage=new s.EventEmitter,this.changeController(t)}changeController(e){var t;this.controller!==e&&(null===(t=this.controllerMessageHandler)||void 0===t||t.dispose(),this.controller=e,this.controllerMessageHandler=e.onDidReceiveMessage((t=>{t.editor===this.editor&&this.controller===e&&(this.eventHandlerListening?(this.sendPendingMessages(),this._onDidReceiveMessage.fire(t.message)):this.pendingMessages.push(t.message))}),this,this.disposables))}dispose(){(0,l.disposeAllDisposables)(this.disposables)}get onDidReceiveMessage(){return this.eventHandlerListening=!0,setTimeout((()=>this.sendPendingMessages()),0),this._onDidReceiveMessage.event}postMessage(e){return this.controller.postMessage(e,this.editor)}asWebviewUri(e){return this.controller.asWebviewUri(e)}sendPendingMessages(){if(this.pendingMessages.length){let e=this.pendingMessages.shift();for(;e;)this._onDidReceiveMessage.fire(e),e=this.pendingMessages.shift()}}}let _=class{constructor(e,t,n,r){this.serviceContainer=e,this.asyncDisposableRegistry=n,this.notebook=r,this.messageCoordinators=new WeakMap,this.attachedEditors=new WeakMap,this.notebookDisposables=new WeakMap,this.selectedNotebookController=new WeakMap,this.previouslyInitialized=new WeakSet,this.notebookCommunications=new WeakMap,this.notebookEditors=new WeakMap,r.onDidChangeVisibleNotebookEditors(this.onDidChangeVisibleNotebookEditors,this,t),r.onDidCloseNotebookDocument(this.onDidCloseNotebookDocument,this,t)}setActiveController(e,t){if(this.selectedNotebookController.get(e)===t)return;(0,u.traceInfo)(`Setting setActiveController for ${(0,d.getDisplayPath)(e.uri)}`);const n=this.messageCoordinators.get(e);n&&(this.messageCoordinators.delete(e),this.attachedEditors.delete(e),this.notebook.notebookEditors.filter((t=>t.document===e)).forEach((e=>{const t=this.notebookCommunications.get(e);this.previouslyInitialized.delete(e),this.notebookCommunications.delete(e),t&&t.dispose()})),n.then((e=>e.dispose())).catch(f.noop)),this.selectedNotebookController.set(e,t),(this.notebookEditors.get(e)||[]).filter((e=>this.notebookCommunications.has(e))).map((e=>this.notebookCommunications.get(e))).forEach((e=>e.changeController(t))),this.notebook.notebookEditors.forEach((e=>this.initializeNotebookCommunication(e)))}initializeNotebookCommunication(e){const t=e.document,n=this.selectedNotebookController.get(t);if(!n)return void(0,u.traceVerbose)(`No controller, hence notebook communications cannot be initialized for editor ${(0,d.getDisplayPath)(e.document.uri)}`);if(this.notebookCommunications.has(e))return void(0,u.traceVerbose)(`notebook communications already initialized for editor ${(0,d.getDisplayPath)(e.document.uri)}`);(0,u.traceVerbose)(`Intiailize notebook communications for editor ${(0,d.getDisplayPath)(e.document.uri)}`);const r=new b(e,n);this.addNotebookDiposables(t,[r]),this.notebookCommunications.set(e,r);const{token:i}=new s.CancellationTokenSource;this.resolveKernel(t,r,i).catch(f.noop)}resolveKernel(e,t,n){(0,u.traceVerbose)(`Resolving notebook UI Comms (resolve) for ${(0,d.getDisplayPath)(e.uri)}`);let r=this.messageCoordinators.get(e);return void 0===r&&(r=y.CommonMessageCoordinator.create(e,this.serviceContainer),this.messageCoordinators.set(e,r),this.asyncDisposableRegistry.push({dispose:async()=>null==r?void 0:r.then((e=>e.dispose())).catch(f.noop)})),c.Cancellation.race((()=>r.then(this.attachCoordinator.bind(this,e,t))),n)}addNotebookDiposables(e,t){const n=this.notebookDisposables.get(e)||[];n.push(...t),this.notebookDisposables.set(e,n)}async onDidChangeVisibleNotebookEditors(e){e.forEach((e=>this.initializeNotebookCommunication(e)))}onDidCloseNotebookDocument(e){const t=this.notebookEditors.get(e)||[];(0,l.disposeAllDisposables)(this.notebookDisposables.get(e)||[]),t.forEach((e=>{var t;return null===(t=this.notebookCommunications.get(e))||void 0===t?void 0:t.dispose()}));const n=this.messageCoordinators.get(e);null==n||n.then((e=>e.dispose())),this.messageCoordinators.delete(e),this.attachedEditors.delete(e)}attachCoordinator(e,t,n){const r=(0,h.createDeferred)(),i=this.attachedEditors.get(e)||new Set;if(this.attachedEditors.set(e,i),i.has(t.editor)||this.previouslyInitialized.has(t.editor))(0,u.traceVerbose)(`Coordinator already attached for ${(0,d.getDisplayPath)(e.uri)}`),r.resolve();else{i.add(t.editor);const o=[];(0,u.traceVerbose)(`Attach Coordinator for ${(0,d.getDisplayPath)(e.uri)}`),n.postMessage((e=>{(0,u.traceInfoIfCI)(`${v.ConsoleForegroundColors.Green}Widget Coordinator sent ${e.message}`),e.message===m.InteractiveWindowMessages.ConvertUriForUseInWebViewRequest?n.onMessage(m.InteractiveWindowMessages.ConvertUriForUseInWebViewResponse,{request:e.payload,response:t.asWebviewUri(e.payload)}):t.postMessage({type:e.message,payload:e.payload})}),this,o),t.onDidReceiveMessage((e=>{(0,u.traceInfoIfCI)(`${v.ConsoleForegroundColors.Green}Widget Coordinator received ${e.type}`),n.onMessage(e.type,e.payload),e.type===m.IPyWidgetMessages.IPyWidgets_Ready&&(r.resolve(),this.previouslyInitialized.add(t.editor))}),this,o),t.postMessage({type:m.IPyWidgetMessages.IPyWidgets_IsReadyRequest,payload:void 0}).then(f.noop,f.noop),this.addNotebookDiposables(e,o)}return r.promise}};_=r([(0,o.injectable)(),i(0,(0,o.inject)(g.IServiceContainer)),i(1,(0,o.inject)(p.IDisposableRegistry)),i(2,(0,o.inject)(p.IAsyncDisposableRegistry)),i(3,(0,o.inject)(a.IVSCodeNotebook))],_),t.NotebookIPyWidgetCoordinator=_},37625:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteWidgetScriptSourceProvider=void 0;const r=n(46318);class i{constructor(e,t){this.baseUrl=e,this.httpClient=t}dispose(){}async getWidgetScriptSource(e,t){const n=`${this.baseUrl}nbextensions/${e}/index.js`;return await this.getUrlForWidget(n)?{moduleName:e,scriptUri:n,source:"cdn"}:((0,r.traceWarning)(`Widget Script not found for ${e}@${t}`),{moduleName:e})}async getUrlForWidget(e){if(i.validUrls.has(e))return i.validUrls.get(e);const t=await this.httpClient.exists(e);return i.validUrls.set(e,t),t}}t.RemoteWidgetScriptSourceProvider=i,i.validUrls=new Map},8043:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterExporter=void 0;const o=n(86700),s=n(22037),a=n(71017),c=n(66828),l=n(13395),u=n(46318),d=n(60593),p=n(71733),h=n(35952),f=n(79041),m=n(72858),g=n(5448),v=n(44007),y=n(60592),b=n(83474);let _=class{constructor(e,t,n,r,i,o,c,l){this.jupyterExecution=e,this.workspaceService=t,this.configService=n,this.fileSystem=r,this.platform=i,this.applicationShell=o,this.ipynbProvider=c,this.errorHandler=l,this.addDirectoryChangeCell=async(e,t)=>{const n=await this.calculateDirectoryChange(t,e);if(n){const t=b.CodeSnippets.ChangeDirectory.join(s.EOL).format(h.DataScience.exportChangeDirectoryComment(),b.CodeSnippets.ChangeDirectoryCommentIdentifier,n);return[{data:(0,y.createCodeCell)(t)},...e]}return e},this.firstWorkspaceFolder=async e=>{var t;for(const n of e){const e=null===(t=n.uri)||void 0===t?void 0:t.fsPath;if(e&&a.isAbsolute(e)&&await this.fileSystem.localFileExists(e))for(const t of this.workspaceService.workspaceFolders)if(e.toLowerCase().startsWith(t.uri.fsPath.toLowerCase()))return t.uri.fsPath}},this.calculateDirectoryChange=async(e,t)=>{let n;if(!t.find((e=>(0,v.concatMultilineString)(e.data.source).includes(b.CodeSnippets.ChangeDirectoryCommentIdentifier)))){const r=a.dirname(e);if(this.workspaceService.hasWorkspaceFolders){const e=await this.firstWorkspaceFolder(t);e&&a.isAbsolute(e)&&r&&a.isAbsolute(r)&&(n=a.relative(r,e))}}return n&&!a.isAbsolute(n)?(this.platform.isWindows&&(n=n.replace("\\","\\\\")),n):void 0},this.pruneCells=(e,t)=>e.map((e=>this.pruneCell(e,t))),this.pruneCell=(e,t)=>{const n=(0,m.pruneCell)({...e.data});return n.source=this.pruneSource(e.data.source,t),n},this.pruneSource=(e,t)=>{if(Array.isArray(e)&&e.length>0){if(t.isCell(e[0]))return e.slice(1)}else{const n=e.toString().split("\n").map((e=>`${e}\n`));if(n.length>0&&t.isCell(n[0]))return n.slice(1)}return e},this.extractPythonMainVersion=async()=>{const e=await this.jupyterExecution.getUsableJupyterPython();return e&&e.version?e.version.major:3}}dispose(){}async exportToFile(e,t,n=!0){let r;this.configService.getSettings().changeDirOnImportExport&&(r=t);const i=await this.translateToNotebook(e,r);try{const e=JSON.stringify(i);if(await this.fileSystem.writeFile(c.Uri.file(t),e),!n)return;const r=h.DataScience.exportOpenQuestion1();this.applicationShell.showInformationMessage(h.DataScience.exportDialogComplete().format(t),r).then((async e=>{try{e===r&&await this.ipynbProvider.open(c.Uri.file(t))}catch(e){await this.errorHandler.handleError(e)}}))}catch(e){(0,u.traceError)("Error in exporting notebook file"),this.applicationShell.showInformationMessage(h.DataScience.exportDialogFailed().format(e))}}async translateToNotebook(e,t,n){t&&this.configService.getSettings().changeDirOnImportExport&&(e=await this.addDirectoryChangeCell(e,t));const r=await this.extractPythonMainVersion(),i={language_info:{codemirror_mode:{name:"ipython",version:r},file_extension:".py",mimetype:"text/x-python",name:"python",nbconvert_exporter:"python",pygments_lexer:`ipython${r}`,version:r},orig_nbformat:b.defaultNotebookFormat.major,kernelspec:n},o=new f.CellMatcher(this.configService.getSettings());return{cells:this.pruneCells(e,o),nbformat:b.defaultNotebookFormat.major,nbformat_minor:b.defaultNotebookFormat.minor,metadata:i}}};_=r([(0,o.injectable)(),i(0,(0,o.inject)(g.IJupyterExecution)),i(1,(0,o.inject)(l.IWorkspaceService)),i(2,(0,o.inject)(p.IConfigurationService)),i(3,(0,o.inject)(d.IFileSystem)),i(4,(0,o.inject)(d.IPlatformService)),i(5,(0,o.inject)(l.IApplicationShell)),i(6,(0,o.inject)(g.INotebookEditorProvider)),i(7,(0,o.inject)(g.IDataScienceErrorHandler))],_),t.JupyterExporter=_},94996:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterImporter=void 0,n(30895);const o=n(86700),s=n(22037),a=n(71017),c=n(13395),l=n(46318),u=n(60593),d=n(71733),p=n(35952),h=n(5448),f=n(83474),m=n(95063);let g=class{constructor(e,t,n,r,i,o,a){this.fs=e,this.disposableRegistry=t,this.configuration=n,this.workspaceService=r,this.platform=i,this.nbConvertDependencyChecker=o,this.exportToPythonService=a,this.isDisposed=!1,this.nbconvertBaseTemplateFormat="{%- extends '{0}' -%}\n{% block codecell %}\n{1}\n{{ super() }}\n{% endblock codecell %}\n{% block in_prompt %}{% endblock in_prompt %}\n{% block input %}{{ cell.source | ipython2python }}{% endblock input %}\n{% block markdowncell scoped %}{1} [markdown]\n{{ cell.source | comment_lines }}\n{% endblock markdowncell %}",this.nbconvert5Null="null.tpl",this.nbconvert6Null="base/null.j2",this.dispose=()=>{this.isDisposed=!0},this.addInstructionComments=e=>p.DataScience.instructionComments().format(this.defaultCellMarker).concat(e),this.addIPythonImport=e=>f.CodeSnippets.ImportIPython.format(this.defaultCellMarker,e),this.addDirectoryChange=(e,t)=>f.CodeSnippets.ChangeDirectory.join(s.EOL).format(p.DataScience.importChangeDirectoryComment().format(this.defaultCellMarker),f.CodeSnippets.ChangeDirectoryCommentIdentifier,t).concat(e)}async importFromFile(e,t){let n;this.configuration.getSettings().changeDirOnImportExport&&(n=await this.calculateDirectoryChange(e));const r=await this.nbConvertDependencyChecker.getNbConvertVersion(t);if(r){let i;r.major>=6?(this.template6Promise||(this.template6Promise=this.createTemplateFile(!0)),i=await this.template6Promise):(this.template5Promise||(this.template5Promise=this.createTemplateFile(!1)),i=await this.template5Promise);let o=await this.exportToPythonService.exportNotebookToPython(e,t,i);return o.includes("get_ipython()")&&(o=this.addIPythonImport(o)),n&&(o=this.addDirectoryChange(o,n)),this.addInstructionComments(o)}throw new Error(p.DataScience.jupyterNbConvertNotSupported())}get defaultCellMarker(){return this.configuration.getSettings().defaultCellMarker||f.Identifiers.DefaultCodeCellMarker}async calculateDirectoryChange(e){let t;try{if(!(await this.fs.readFile(e)).includes(f.CodeSnippets.ChangeDirectoryCommentIdentifier)){const n=a.dirname(e.fsPath);if(this.workspaceService.hasWorkspaceFolders){const e=this.workspaceService.workspaceFolders[0].uri.fsPath;e&&a.isAbsolute(e)&&n&&a.isAbsolute(n)&&(t=a.relative(e,n))}}return t&&!a.isAbsolute(t)?(this.platform.isWindows&&(t=t.replace("\\","\\\\")),t):void 0}catch(e){(0,l.traceError)(e)}}async createTemplateFile(e){const t=await this.fs.createTemporaryLocalFile(".tpl");if(t)try{return this.disposableRegistry.push(t),await this.fs.appendLocalFile(t.filePath,this.nbconvertBaseTemplateFormat.format(e?this.nbconvert6Null:this.nbconvert5Null,this.defaultCellMarker)),t.filePath}catch(e){(0,m.noop)()}}};g=r([(0,o.injectable)(),i(0,(0,o.inject)(u.IFileSystem)),i(1,(0,o.inject)(d.IDisposableRegistry)),i(2,(0,o.inject)(d.IConfigurationService)),i(3,(0,o.inject)(c.IWorkspaceService)),i(4,(0,o.inject)(u.IPlatformService)),i(5,(0,o.inject)(h.INbConvertInterpreterDependencyChecker)),i(6,(0,o.inject)(h.INbConvertExportToPythonService))],g),t.JupyterImporter=g},48083:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterCommandFactory=t.InterpreterJupyterKernelSpecCommand=t.InterpreterJupyterNotebookCommand=void 0;const o=n(86700),s=n(71017),a=n(46318),c=n(12698),l=n(46488),u=n(83474);class d{constructor(e,t,n,r,i){this.moduleName=e,this.args=t,this.pythonExecutionFactory=n,this._interpreter=r,this.interpreterPromise=Promise.resolve(this._interpreter),this.pythonLauncher=this.interpreterPromise.then((async r=>{if(i){const i=await n.createDaemon({daemonModule:u.JupyterDaemonModule,interpreter:r});if("jupyter"===e.toLowerCase()&&t.join(" ").toLowerCase().startsWith("-m jupyter notebook")||"notebook"===e.toLowerCase()&&t.join(" ").toLowerCase().startsWith("-m notebook"))try{if((await i.exec([s.join(l.EXTENSION_ROOT_DIR,"pythonFiles","vscode_datascience_helpers","jupyter_nbInstalled.py")],{})).stdout.toLowerCase().includes("available"))return i}catch(e){(0,a.traceError)("Checking whether notebook is importable failed",e)}}return n.createActivatedEnvironment({interpreter:this._interpreter})}))}interpreter(){return this.interpreterPromise}async exec(e,t){const n={...t},r=await this.pythonLauncher,i=[...this.args,...e],o=i[1];return i.shift(),i.shift(),r.execModule(o,i,n)}}class p extends d{constructor(e,t,n,r,i){super(e,t,n,r,i)}}t.InterpreterJupyterNotebookCommand=p;class h extends d{constructor(e,t,n,r,i){super(e,t,n,r,i)}async exec(e,t){let n,r={stdout:""};try{r=await super.exec(e,t)}catch(e){n=e}if(!r.stderr&&!n)return r;const i=()=>{if(n)throw(0,a.traceError)("Exception attempting to enumerate kernelspecs: ",n),n;return r},o=await this.interpreter();if(!o||"jupyter"!==this.moduleName.toLowerCase()||this.args.join(" ").toLowerCase()!==`-m jupyter ${u.JupyterCommands.KernelSpecCommand}`.toLowerCase())return i();try{if("list --json"===e.join(" ").toLowerCase())return r=await this.getKernelSpecList(o,t),r;if("--version"===e.join(" ").toLowerCase())return r=await this.getKernelSpecVersion(o,t),r}catch(e){(0,a.traceError)("Failed to get a list of the kernelspec using python script",e)}return i()}async getKernelSpecList(e,t){return(await this.pythonExecutionFactory.createActivatedEnvironment({interpreter:e})).exec([s.join(l.EXTENSION_ROOT_DIR,"pythonFiles","vscode_datascience_helpers","getJupyterKernels.py")],{...t,throwOnStdErr:!0})}async getKernelSpecVersion(e,t){return(await this.pythonExecutionFactory.createActivatedEnvironment({interpreter:e})).exec([s.join(l.EXTENSION_ROOT_DIR,"pythonFiles","vscode_datascience_helpers","getJupyterKernelspecVersion.py")],{...t,throwOnStdErr:!0})}}t.InterpreterJupyterKernelSpecCommand=h;let f=class{constructor(e){this.executionFactory=e}createInterpreterCommand(e,t,n,r,i){return e===u.JupyterCommands.NotebookCommand?new p(t,n,this.executionFactory,r,i):e===u.JupyterCommands.KernelSpecCommand?new h(t,n,this.executionFactory,r,i):new d(t,n,this.executionFactory,r,i)}};f=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IPythonExecutionFactory))],f),t.JupyterCommandFactory=f},74607:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterInterpreterDependencyService=t.getMessageForLibrariesNotInstalled=t.JupyterInterpreterDependencyResponse=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(33149),l=n(46318),u=n(35952),d=n(95063),p=n(4036),h=n(8599),f=n(74721),m=n(5448),g=n(21687),v=n(97045),y=n(83474),b=n(13982),_=n(29299);var w;function S(e,t){const n=e.map((e=>b.ProductNames.get(e))).filter((e=>!!e)).map((e=>e));switch(n.length){case 0:return"";case 1:return t?u.DataScience.libraryRequiredToLaunchJupyterNotInstalledInterpreter().format(t,n[0]):u.DataScience.libraryRequiredToLaunchJupyterNotInstalled().format(n[0]);default:{const e=n.pop();return t?u.DataScience.librariesRequiredToLaunchJupyterNotInstalledInterpreter().format(t,`${n.join(", ")} ${u.Common.and()} ${e}`):u.DataScience.librariesRequiredToLaunchJupyterNotInstalled().format(`${n.join(", ")} ${u.Common.and()} ${e}`)}}}!function(e){e[e.ok=0]="ok",e[e.selectAnotherInterpreter=1]="selectAnotherInterpreter",e[e.cancel=2]="cancel"}(w=t.JupyterInterpreterDependencyResponse||(t.JupyterInterpreterDependencyResponse={})),t.getMessageForLibrariesNotInstalled=S;let C=class{constructor(e,t,n){this.applicationShell=e,this.installer=t,this.commandFactory=n,this.dependenciesInstalledInInterpreter=new Set}async installMissingDependencies(e,t){const n=new s.CancellationTokenSource;try{const t=e.envType===g.EnvironmentType.Conda?Promise.resolve(void 0):this.installer.isInstalled(_.Product.pip,e),[r,i]=await Promise.all([this.getDependenciesNotInstalled(e,void 0),t]);if(0===r.length)return w.ok;const o=S(!1===i?[_.Product.pip].concat(r):r,e.displayName);switch((0,v.sendTelemetryEvent)(y.Telemetry.PythonModuleInstall,void 0,{action:"displayed",moduleName:b.ProductNames.get(_.Product.jupyter),pythonEnvType:e.envType}),(0,v.sendTelemetryEvent)(y.Telemetry.JupyterNotInstalledErrorShown),await this.applicationShell.showErrorMessage(o,{modal:!0},u.DataScience.jupyterInstall(),u.DataScience.selectDifferentJupyterInterpreter())){case u.DataScience.jupyterInstall():{r.includes(_.Product.kernelspec)&&!r.includes(_.Product.jupyter)&&r.push(_.Product.jupyter);const t=r.filter((e=>e!==_.Product.kernelspec));t.sort(((e,t)=>e===_.Product.jupyter?-1:t===_.Product.jupyter?1:e===_.Product.notebook?-1:t===_.Product.notebook?1:0));let o=t.shift();const s=(0,c.createPromiseFromCancellation)({cancelAction:"resolve",defaultValue:_.InstallerResponse.Ignore,token:n.token});for(;o;){if(await Promise.race([this.installer.install(o,e,n,void 0,!1===i),s])!==_.InstallerResponse.Installed)return w.cancel;o=t.shift()}return(0,v.sendTelemetryEvent)(y.Telemetry.UserInstalledJupyter),this.checkKernelSpecAvailability(e)}case u.DataScience.selectDifferentJupyterInterpreter():return(0,v.sendTelemetryEvent)(y.Telemetry.UserDidNotInstallJupyter),w.selectAnotherInterpreter;case u.DataScience.pythonInteractiveHelpLink():return this.applicationShell.openUrl(p.HelpLinks.PythonInteractiveHelpLink),(0,v.sendTelemetryEvent)(y.Telemetry.UserDidNotInstallJupyter),w.cancel;default:return(0,v.sendTelemetryEvent)(y.Telemetry.UserDidNotInstallJupyter),w.cancel}}finally{n.dispose()}}async areDependenciesInstalled(e,t){return this.getDependenciesNotInstalled(e,t).then((e=>0===e.length))}async getDependenciesNotInstalled(e,t){if(this.dependenciesInstalledInInterpreter.has(e.path))return[];const n=[];if(await Promise.race([Promise.all([this.installer.isInstalled(_.Product.jupyter,e).then((e=>e?(0,d.noop)():n.push(_.Product.jupyter))),this.installer.isInstalled(_.Product.notebook,e).then((e=>e?(0,d.noop)():n.push(_.Product.notebook)))]),(0,c.createPromiseFromCancellation)({cancelAction:"resolve",defaultValue:void 0,token:t})]),n.length>0)return n;if(c.Cancellation.isCanceled(t))return[];const r=await this.isKernelSpecAvailable(e,t).then((e=>e?[]:[_.Product.kernelspec]));return 0===r.length&&this.dependenciesInstalledInInterpreter.add(e.path),r}async isKernelSpecAvailable(e,t){return this.commandFactory.createInterpreterCommand(y.JupyterCommands.KernelSpecCommand,"jupyter",["-m","jupyter","kernelspec"],e,!1).exec(["--version"],{throwOnStdErr:!0}).then((()=>!0)).catch((e=>((0,l.traceError)("Kernel spec not found: ",e),(0,v.sendTelemetryEvent)(y.Telemetry.KernelSpecNotFound),!1)))}async checkKernelSpecAvailability(e,t){return await this.isKernelSpecAvailable(e)?w.ok:((0,v.sendTelemetryEvent)(y.Telemetry.JupyterInstalledButNotKernelSpecModule),c.Cancellation.isCanceled(t)?w.cancel:await this.applicationShell.showErrorMessage(u.DataScience.jupyterKernelSpecModuleNotFound().format(e.path),u.DataScience.selectDifferentJupyterInterpreter(),u.Common.cancel())===u.DataScience.selectDifferentJupyterInterpreter()?w.selectAnotherInterpreter:w.cancel)}};r([(0,h.reportAction)(f.ReportableAction.InstallingMissingDependencies)],C.prototype,"installMissingDependencies",null),C=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IApplicationShell)),i(1,(0,o.inject)(_.IInstaller)),i(2,(0,o.inject)(m.IJupyterCommandFactory))],C),t.JupyterInterpreterDependencyService=C},80340:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterInterpreterOldCacheStateStore=void 0;const o=n(86700),s=n(13395),a=n(71733);let c=class{constructor(e,t){this.workspace=e;const n=t.createWorkspacePersistentState("DS-VSC-JupyterInterpreter"),r=t.createGlobalPersistentState("DS-VSC-JupyterInterpreter");this.workspaceJupyterInterpreter={state:n},this.globalJupyterInterpreter={state:r}}get cacheStore(){return this.workspace.hasWorkspaceFolders?this.workspaceJupyterInterpreter:this.globalJupyterInterpreter}getCachedInterpreterPath(){return this.cacheStore.state.value}async clearCache(){await this.cacheStore.state.updateValue(void 0)}};c=r([(0,o.injectable)(),i(0,(0,o.inject)(s.IWorkspaceService)),i(1,(0,o.inject)(a.IPersistentStateFactory))],c),t.JupyterInterpreterOldCacheStateStore=c},55903:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterInterpreterSelectionCommand=void 0;const o=n(86700),s=n(13395),a=n(71733),c=n(97045),l=n(83474),u=n(78140);let d=class{constructor(e,t,n){this.service=e,this.cmdManager=t,this.disposables=n}async activate(){this.disposables.push(this.cmdManager.registerCommand("jupyter.selectJupyterInterpreter",(()=>{(0,c.sendTelemetryEvent)(l.Telemetry.SelectJupyterInterpreterCommand),this.service.selectInterpreter().ignoreErrors()})))}};d=r([(0,o.injectable)(),i(0,(0,o.inject)(u.JupyterInterpreterService)),i(1,(0,o.inject)(s.ICommandManager)),i(2,(0,o.inject)(a.IDisposableRegistry))],d),t.JupyterInterpreterSelectionCommand=d},28433:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterInterpreterSelector=void 0;const o=n(86700),s=n(13395),a=n(33149),c=n(71733),l=n(35952),u=n(18395),d=n(66260);let p=class{constructor(e,t,n,r,i){this.interpreterSelector=e,this.applicationShell=t,this.interpreterSelectionState=n,this.workspace=r,this.pathUtils=i}async selectInterpreter(e){const t=this.workspace.getWorkspaceFolder(void 0),n=this.interpreterSelectionState.selectedPythonPath?this.pathUtils.getDisplayName(this.interpreterSelectionState.selectedPythonPath,null==t?void 0:t.uri.fsPath):void 0,r=await this.interpreterSelector.getSuggestions(void 0);if(a.Cancellation.isCanceled(e))return;const i={matchOnDetail:!0,matchOnDescription:!0,placeHolder:n?l.DataScience.currentlySelectedJupyterInterpreterForPlaceholder().format(n):""},o=await this.applicationShell.showQuickPick(r,i);return o?o.interpreter:void 0}};p=r([(0,o.injectable)(),i(0,(0,o.inject)(u.IInterpreterSelector)),i(1,(0,o.inject)(s.IApplicationShell)),i(2,(0,o.inject)(d.JupyterInterpreterStateStore)),i(3,(0,o.inject)(s.IWorkspaceService)),i(4,(0,o.inject)(c.IPathUtils))],p),t.JupyterInterpreterSelector=p},78140:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterInterpreterService=void 0;const o=n(86700),s=n(66828),a=n(33149);n(30895);const c=n(95063),l=n(48497),u=n(97045),d=n(83474),p=n(74607),h=n(80340),f=n(28433),m=n(66260);let g=class{constructor(e,t,n,r,i){this.oldVersionCacheStateStore=e,this.interpreterSelectionState=t,this.jupyterInterpreterSelector=n,this.interpreterConfiguration=r,this.interpreterService=i,this._onDidChangeInterpreter=new s.EventEmitter}get onDidChangeInterpreter(){return this._onDidChangeInterpreter.event}async getSelectedInterpreter(e){return await this.setInitialInterpreter(e),this._selectedInterpreter}async setInitialInterpreter(e){return this.getInitialInterpreterPromise||(this.getInitialInterpreterPromise=this.getInitialInterpreterImpl(e).then((e=>(e&&this.changeSelectedInterpreterProperty(e),e)))),this.getInitialInterpreterPromise}async selectInterpreter(){const e=await this.jupyterInterpreterSelector.selectInterpreter();if(e)switch(await this.interpreterConfiguration.installMissingDependencies(e,void 0)){case p.JupyterInterpreterDependencyResponse.ok:return await this.setAsSelectedInterpreter(e),e;case p.JupyterInterpreterDependencyResponse.cancel:return void(0,u.sendTelemetryEvent)(d.Telemetry.SelectJupyterInterpreter,void 0,{result:"installationCancelled"});default:return this.selectInterpreter()}else(0,u.sendTelemetryEvent)(d.Telemetry.SelectJupyterInterpreter,void 0,{result:"notSelected"})}async installMissingDependencies(e){const t=await this.getSelectedInterpreter();let n=t;if(!n&&(n=await this.interpreterService.getActiveInterpreter(void 0),!n))return await this.selectInterpreter(),p.JupyterInterpreterDependencyResponse.selectAnotherInterpreter;const r=await this.interpreterConfiguration.installMissingDependencies(n,e);return r===p.JupyterInterpreterDependencyResponse.selectAnotherInterpreter?(n=await this.selectInterpreter(),n?p.JupyterInterpreterDependencyResponse.ok:p.JupyterInterpreterDependencyResponse.cancel):(r===p.JupyterInterpreterDependencyResponse.ok&&n!==t&&await this.setAsSelectedInterpreter(n),r)}async setAsSelectedInterpreter(e){await this.setInitialInterpreter(),this.changeSelectedInterpreterProperty(e)}getInterpreterFromChangeOfOlderVersionOfExtension(){const e=this.oldVersionCacheStateStore.getCachedInterpreterPath();if(e)return this.oldVersionCacheStateStore.clearCache().ignoreErrors(),e}changeSelectedInterpreterProperty(e){this._selectedInterpreter=e,this._onDidChangeInterpreter.fire(e),this.interpreterSelectionState.updateSelectedPythonPath(e.path),(0,u.sendTelemetryEvent)(d.Telemetry.SelectJupyterInterpreter,void 0,{result:"selected"})}async validateInterpreterPath(e,t){try{const n=(0,a.createPromiseFromCancellation)({cancelAction:"resolve",defaultValue:void 0,token:t}),r=await Promise.race([this.interpreterService.getInterpreterDetails(e,void 0),n]);if(r&&await this.interpreterConfiguration.areDependenciesInstalled(r,t))return r}catch(e){(0,c.noop)()}}async getInitialInterpreterImpl(e){let t;const n=this.getInterpreterFromChangeOfOlderVersionOfExtension();if(n&&(t=await this.validateInterpreterPath(n,e)),!t&&this.interpreterSelectionState.selectedPythonPath&&(t=await this.validateInterpreterPath(this.interpreterSelectionState.selectedPythonPath,e),t||this.interpreterSelectionState.updateSelectedPythonPath(void 0)),!t){const n=await this.interpreterService.getActiveInterpreter(void 0);n&&await this.interpreterConfiguration.areDependenciesInstalled(n,e)&&(t=n)}return t}};g=r([(0,o.injectable)(),i(0,(0,o.inject)(h.JupyterInterpreterOldCacheStateStore)),i(1,(0,o.inject)(m.JupyterInterpreterStateStore)),i(2,(0,o.inject)(f.JupyterInterpreterSelector)),i(3,(0,o.inject)(p.JupyterInterpreterDependencyService)),i(4,(0,o.inject)(l.IInterpreterService))],g),t.JupyterInterpreterService=g},66260:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MigrateJupyterInterpreterStateService=t.JupyterInterpreterStateStore=void 0;const o=n(86700),s=n(98501),a=n(71733),c=n(95063),l="INTERPRETER_PATH_SELECTED_FOR_JUPYTER_SERVER",u="INTERPRETER_PATH_WAS_SELECTED_FOR_JUPYTER_SERVER";let d=class{constructor(e){this.memento=e}get interpreterSetAtleastOnce(){return!!this.selectedPythonPath||this.memento.get(u,!1)}get selectedPythonPath(){return this._interpreterPath||this.memento.get(l,void 0)}updateSelectedPythonPath(e){this._interpreterPath=e,this.memento.update(l,e).then(c.noop,c.noop),this.memento.update(u,!0).then(c.noop,c.noop)}};d=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IMemento)),i(0,(0,o.named)(a.GLOBAL_MEMENTO))],d),t.JupyterInterpreterStateStore=d;let p=class{constructor(e,t,n,r){this.api=e,this.memento=t,this.checker=n,this.disposables=r}async activate(){this.activateBackground().catch(c.noop),this.api.onDidActivatePythonExtension(this.activateBackground,this,this.disposables)}async activateBackground(){!this.memento.get(l)&&this.checker.isPythonExtensionActive&&await this.migrateSettings()}async migrateSettings(){if(this.settingsMigrated)return;this.settingsMigrated=!0;const e=(await this.api.getApi()).getInterpreterPathSelectedForJupyterServer();await this.memento.update(l,e),await this.memento.update(u,!0)}};p=r([(0,o.injectable)(),i(0,(0,o.inject)(s.IPythonApiProvider)),i(1,(0,o.inject)(a.IMemento)),i(1,(0,o.named)(a.GLOBAL_MEMENTO)),i(2,(0,o.inject)(s.IPythonExtensionChecker)),i(3,(0,o.inject)(a.IDisposableRegistry))],p),t.MigrateJupyterInterpreterStateService=p},2655:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterInterpreterSubCommandExecutionService=void 0;const o=n(86700),s=n(71017),a=n(46318),c=n(12698),l=n(71733),u=n(35952),d=n(95063),p=n(46488),h=n(34347),f=n(48497),m=n(97045),g=n(83474),v=n(75550),y=n(29299),b=n(78985),_=n(74607),w=n(78140);let S=class{constructor(e,t,n,r,i,o,s,a){this.jupyterInterpreter=e,this.interpreterService=t,this.jupyterDependencyService=n,this.pythonExecutionFactory=r,this.jupyterOutputChannel=i,this.pathUtils=o,this.jupyterPaths=s,this.activationHelper=a}async refreshCommands(){(0,d.noop)()}async isNotebookSupported(e){const t=await this.jupyterInterpreter.getSelectedInterpreter(e);return!!t&&this.jupyterDependencyService.areDependenciesInstalled(t,e)}async getReasonForJupyterNotebookNotBeingSupported(e){let t=await this.jupyterInterpreter.getSelectedInterpreter(e);if(!t&&(t=await this.interpreterService.getActiveInterpreter(void 0),!t))return(0,m.sendTelemetryEvent)(g.Telemetry.SelectJupyterInterpreterMessageDisplayed),u.DataScience.selectJupyterInterpreter();const n=await this.jupyterDependencyService.getDependenciesNotInstalled(t,e);return 0===n.length?"":1===n.length&&n[0]===y.Product.kernelspec?u.DataScience.jupyterKernelSpecModuleNotFound().format(t.path):(0,_.getMessageForLibrariesNotInstalled)(n,t.displayName)}async getSelectedInterpreter(e){return this.jupyterInterpreter.getSelectedInterpreter(e)}async startNotebook(e,t){const n=await this.getSelectedInterpreterAndThrowIfNotAvailable(t.token);this.jupyterOutputChannel.appendLine(u.DataScience.startingJupyterLogMessage().format(this.pathUtils.getDisplayName(n.path),e.join(" ")));const r=await this.pythonExecutionFactory.createDaemon({daemonModule:g.JupyterDaemonModule,interpreter:n}),i={...t};i.token=void 0;const o=await this.activationHelper.getActivatedEnvironmentVariables(void 0,n,!0)||process.env,a=(process.env.JUPYTER_PATH||o.JUPYTER_PATH||"").split(s.delimiter).filter((e=>e.trim().length));return a.push(s.dirname(await this.jupyterPaths.getKernelSpecTempRegistrationFolder())),i.env={...o,JUPYTER_PATH:a.join(s.delimiter)},r.execModuleObservable("jupyter",["notebook"].concat(e),i)}async getRunningJupyterServers(e){const t=await this.getSelectedInterpreterAndThrowIfNotAvailable(e),n=await this.pythonExecutionFactory.createDaemon({daemonModule:g.JupyterDaemonModule,interpreter:t}),r={mergeStdOutErr:!0,token:e},i=s.join(p.EXTENSION_ROOT_DIR,"pythonFiles","vscode_datascience_helpers","getServerInfo.py"),o=await n.exec([i],r);let c;try{c=JSON.parse(o.stdout.trim())}catch(e){return void(0,a.traceWarning)("Failed to parse JSON when getting server info out from getServerInfo.py",e)}return c}async installMissingDependencies(e){return this.jupyterInterpreter.installMissingDependencies(e)}async getSelectedInterpreterAndThrowIfNotAvailable(e){const t=await this.jupyterInterpreter.getSelectedInterpreter(e);if(!t){const e=await this.getReasonForJupyterNotebookNotBeingSupported();throw new v.JupyterInstallError(e)}return t}};S=r([(0,o.injectable)(),i(0,(0,o.inject)(w.JupyterInterpreterService)),i(1,(0,o.inject)(f.IInterpreterService)),i(2,(0,o.inject)(_.JupyterInterpreterDependencyService)),i(3,(0,o.inject)(c.IPythonExecutionFactory)),i(4,(0,o.inject)(l.IOutputChannel)),i(4,(0,o.named)(g.JUPYTER_OUTPUT_CHANNEL)),i(5,(0,o.inject)(l.IPathUtils)),i(6,(0,o.inject)(b.JupyterPaths)),i(7,(0,o.inject)(h.IEnvironmentActivationService))],S),t.JupyterInterpreterSubCommandExecutionService=S},14970:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.NbConvertExportToPythonService=void 0;const o=n(86700),s=n(46318),a=n(12698),c=n(8599),l=n(74721),u=n(83474);let d=class{constructor(e){this.pythonExecutionFactory=e}async exportNotebookToPython(e,t,n,r){const i=await this.pythonExecutionFactory.createDaemon({daemonModule:u.JupyterDaemonModule,interpreter:t}),o=n?[e.fsPath,"--to","python","--stdout","--template",n]:[e.fsPath,"--to","python","--stdout"];return i.execModule("jupyter",["nbconvert"].concat(o),{throwOnStdErr:!1,encoding:"utf8",token:r}).then((e=>{if(""===e.stdout)throw(0,s.traceError)("nbconvert zero size output"),new Error(e.stderr);return e.stdout}))}};r([(0,c.reportAction)(l.ReportableAction.ExportNotebookToPython)],d.prototype,"exportNotebookToPython",null),d=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IPythonExecutionFactory))],d),t.NbConvertExportToPythonService=d},96937:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.NbConvertInterpreterDependencyChecker=void 0;const o=n(86700),s=n(72858),a=n(5448),c=n(83474),l=n(29299);let u=class{constructor(e,t){this.installer=e,this.commandFactory=t,this.nbconvertInstalledInInterpreter=new Set}async isNbConvertInstalled(e,t){if(this.nbconvertInstalledInInterpreter.has(e.path))return!0;const n=!!await this.installer.isInstalled(l.Product.nbconvert,e)&&!!await this.installer.isInstalled(l.Product.jupyter,e);return!0===n&&this.nbconvertInstalledInInterpreter.add(e.path),n}async getNbConvertVersion(e,t){const n=this.commandFactory.createInterpreterCommand(c.JupyterCommands.ConvertCommand,"jupyter",["-m","jupyter","nbconvert"],e,!1),r=await n.exec(["--version"],{throwOnStdErr:!0});return(0,s.parseSemVer)(r.stdout)}};u=r([(0,o.injectable)(),i(0,(0,o.inject)(l.IInstaller)),i(1,(0,o.inject)(a.IJupyterCommandFactory))],u),t.NbConvertInterpreterDependencyChecker=u},88200:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CellOutputMimeTypeTracker=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(2687),l=n(71733),u=n(97045),d=n(70403),p=n(83474),h=n(82232),f=n(85564);let m=class{constructor(e,t){this.vscNotebook=e,this.pendingChecks=new Map,this.sentMimeTypes=new Set,this.disposables=[],t.push(this),this.vscNotebook.onDidOpenNotebookDocument(this.onDidOpenCloseDocument,this,this.disposables),this.vscNotebook.onDidCloseNotebookDocument(this.onDidOpenCloseDocument,this,this.disposables),this.vscNotebook.onDidSaveNotebookDocument(this.onDidOpenCloseDocument,this,this.disposables),this.vscNotebook.onDidChangeNotebookCellExecutionState(this.onDidChangeNotebookCellExecutionState,this,this.disposables)}async activate(){}dispose(){(0,c.disposeAllDisposables)(this.disposables),this.pendingChecks.clear()}async onDidChangeNotebookCellExecutionState(e){(0,h.isJupyterNotebook)(e.cell.notebook)&&this.scheduleCheck(e.cell.document.uri.toString(),this.checkCell.bind(this,e.cell))}onDidOpenCloseDocument(e){(0,h.isJupyterNotebook)(e)&&e.getCells().forEach((e=>{e.kind===s.NotebookCellKind.Code&&e.outputs.forEach((e=>e.items.forEach((e=>this.sendTelemetry(e.mime)))))}))}getCellOutputMimeTypes(e){var t,n,r;if(e.kind===s.NotebookCellKind.Markup)return["markdown"];if("raw"===e.document.languageId)return[];const i=(0,h.createJupyterCellFromVSCNotebookCell)(e).outputs;return Array.isArray(i)&&(null===(t=e.executionSummary)||void 0===t?void 0:t.executionOrder)&&(null===(n=e.executionSummary)||void 0===n?void 0:n.executionOrder)>0&&(null===(r=e.executionSummary)||void 0===r?void 0:r.success)?f(i.map(this.getOutputMimeTypes.bind(this))):[]}getOutputMimeTypes(e){switch(e.output_type){case"error":return[];case"stream":return["stream"];case"display_data":case"update_display_data":case"execute_result":const t=e.data;return t?Object.keys(t):[];default:return["unrecognized_cell_output"]}}scheduleCheck(e,t){const n=this.pendingChecks.get(e);n&&(clearTimeout(n),this.pendingChecks.delete(e)),this.pendingChecks.set(e,setTimeout(t,5e3))}checkCell(e){this.pendingChecks.delete(e.document.uri.toString()),this.getCellOutputMimeTypes(e).forEach(this.sendTelemetry.bind(this))}sendTelemetry(e){if(this.sentMimeTypes.has(e))return;this.sentMimeTypes.add(e);const t=(0,d.getTelemetrySafeHashedString)(e),n=e.toLowerCase(),r={hashedName:t,hasText:n.includes("text"),hasLatex:n.includes("latex"),hasHtml:n.includes("html"),hasSvg:n.includes("svg"),hasXml:n.includes("xml"),hasJson:n.includes("json"),hasImage:n.includes("image"),hasGeo:n.includes("geo"),hasPlotly:n.includes("plotly"),hasVega:n.includes("vega"),hasWidget:n.includes("widget"),hasJupyter:n.includes("jupyter"),hasVnd:n.includes("vnd")};(0,u.sendTelemetryEvent)(p.Telemetry.HashedCellOutputMimeType,void 0,r)}};r([(0,u.captureTelemetry)(p.Telemetry.HashedCellOutputMimeTypePerf)],m.prototype,"checkCell",null),m=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IVSCodeNotebook)),i(1,(0,o.inject)(l.IDisposableRegistry))],m),t.CellOutputMimeTypeTracker=m},74843:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterKernelService=void 0;const o=n(86700),s=n(71017),a=n(33149);n(30895);const c=n(46318),l=n(29140),u=n(60593),d=n(95063),p=n(75213),h=n(5448),f=n(34347),m=n(36462),g=n(86909),v=n(97045),y=n(83474),b=n(42283),_=n(93828),w=n(78985);let S=class{constructor(e,t,n,r,i){this.kernelDependencyService=e,this.fs=t,this.activationHelper=n,this.envVarsService=r,this.jupyterPaths=i}async ensureKernelIsUsable(e,t,n,r){if((0,c.traceVerbose)("Check if a kernel is usable"),"connectToLiveKernel"!==t.kind&&t.interpreter&&"startUsingRemoteKernelSpec"!==t.kind){const i=await this.kernelDependencyService.installMissingDependencies(e,t,n,r,!0);switch(i){case h.KernelInterpreterDependencyResponse.cancel:case h.KernelInterpreterDependencyResponse.selectDifferentKernel:case h.KernelInterpreterDependencyResponse.failed:case h.KernelInterpreterDependencyResponse.uiHidden:throw new b.JupyterKernelDependencyError(i,t)}}var i=void 0;"connectToLiveKernel"!==t.kind&&"startUsingRemoteKernelSpec"!==t.kind&&t.kernelSpec&&t.interpreter&&((i=t.kernelSpec.specFile)&&await this.fs.localFileExists(i)?t.interpreter&&i&&s.basename(s.dirname(i)).toLowerCase()!=t.kernelSpec.name.toLowerCase()&&(i=await this.registerKernel(t,r)):i=await this.registerKernel(t,r)),"connectToLiveKernel"!==t.kind&&"startUsingRemoteKernelSpec"!==t.kind&&t.kernelSpec&&t.interpreter&&i&&((0,c.traceInfoIfCI)(`updateKernelEnvironment ${t.interpreter.displayName}, ${(0,l.getDisplayPath)(t.interpreter.path)} for ${t.id}`),await this.updateKernelEnvironment(e,t.interpreter,t.kernelSpec,i,r))}async registerKernel(e,t){var n,r,i,o,a,u,d;const p=await this.jupyterPaths.getKernelSpecTempRegistrationFolder();if(!e.kernelSpec||t.isCancellationRequested||!e.kernelSpec.name)return;const h=s.join(p,e.kernelSpec.name,"kernel.json");if(await this.fs.localFileExists(h))return h;const f={...e.kernelSpec};e.kernelSpec.specFile&&!this.fs.areLocalPathsSame(h,e.kernelSpec.specFile)&&(f.metadata=f.metadata||{},f.metadata={...f.metadata,vscode:{...f.metadata.vscode||{},originalSpecFile:(null===(r=null===(n=e.kernelSpec.metadata)||void 0===n?void 0:n.vscode)||void 0===r?void 0:r.originalSpecFile)||e.kernelSpec.specFile,originalDisplayName:(null===(o=null===(i=e.kernelSpec.metadata)||void 0===i?void 0:i.vscode)||void 0===o?void 0:o.originalDisplayName)||e.kernelSpec.display_name}}),e.interpreter&&(f.metadata={...f.metadata,interpreter:e.interpreter}),(0,c.traceInfo)(`RegisterKernel for ${e.id} into ${(0,l.getDisplayPath)(h)}`);try{await this.fs.writeLocalFile(h,JSON.stringify(f,void 0,4))}catch(e){throw(0,v.sendTelemetryEvent)(y.Telemetry.FailedToUpdateKernelSpec,void 0,void 0,e,!0),e}if(t.isCancellationRequested)return;const m=(null===(u=null===(a=f.metadata)||void 0===a?void 0:a.vscode)||void 0===u?void 0:u.originalSpecFile)||(null===(d=f.metadata)||void 0===d?void 0:d.originalSpecFile);if(m){const e=s.dirname(m),t=s.dirname(h),n=await this.fs.searchLocal("*.*[^json]",e);await Promise.all(n.map((async n=>{const r=s.join(e,n),i=s.join(t,n);await this.fs.copyLocal(r,i)})))}return(0,v.sendTelemetryEvent)(y.Telemetry.RegisterAndUseInterpreterAsKernel),h}async updateKernelEnvironment(e,t,n,r,i,o){var u;const p=await this.jupyterPaths.getKernelSpecTempRegistrationFolder(),h=n;if(r&&p){const f=s.basename(r).toLowerCase()===n.name.toLowerCase()?r:s.join(p,n.name,"kernel.json");if(!await this.fs.localFileExists(f))return;let m=JSON.parse(await this.fs.readLocalFile(f)),g=!1;if((null===(u=m.metadata)||void 0===u?void 0:u.interpreter)||o){"conda"===m.argv[0].toLowerCase()?(0,c.traceInfo)("Spec argv[0], not updated as it is using conda."):((0,c.traceInfo)(`Spec argv[0] updated from '${m.argv[0]}' to '${(0,l.getDisplayPath)(t.path)}'`),m.argv[0]=t.path);const[r,o]=await Promise.all([this.activationHelper.getActivatedEnvironmentVariables(e,t,!0).catch(d.noop).then((e=>e||{})),this.activationHelper.hasActivationCommands(e,t)]);let u="registeredByNewVersionOfExtForCustomKernelSpec"===(0,_.getKernelRegistrationInfo)(n)&&m.env||{};if(u=Object.assign({...r},u),r.PATH&&(u.PATH=r.PATH),r.Path&&(u.Path=r.Path),m.env=Object.assign(u,m.env),m.env&&this.envVarsService.prependPath(m.env,s.dirname(t.path)),m.env&&Object.keys(m.env).length>0&&o?((0,c.traceInfo)(`Adding env Variable PYTHONNOUSERSITE to ${(0,l.getDisplayPath)(t.path)}`),m.env.PYTHONNOUSERSITE="True"):delete m.env.PYTHONNOUSERSITE,a.Cancellation.isCanceled(i))return;m.metadata=m.metadata||{},m.metadata.interpreter=t,g=!0}if(m.env&&(m=(0,_.cleanEnvironment)(m),g=!0),g)try{await this.fs.writeLocalFile(f,JSON.stringify(m,void 0,2))}catch(e){throw(0,v.sendTelemetryEvent)(y.Telemetry.FailedToUpdateKernelSpec,void 0,void 0,e,!0),e}h.metadata=m.metadata}}};r([i(1,(0,g.logValue)("id")),i(2,(0,g.logValue)("disableUI")),i(3,(0,g.ignoreLogging)())],S.prototype,"ensureKernelIsUsable",null),r([(0,v.captureTelemetry)(y.Telemetry.RegisterInterpreterAsKernel,void 0,!0),m.traceDecorators.error("Failed to register an interpreter as a kernel")],S.prototype,"registerKernel",null),S=r([(0,o.injectable)(),i(0,(0,o.inject)(h.IKernelDependencyService)),i(1,(0,o.inject)(u.IFileSystem)),i(2,(0,o.inject)(f.IEnvironmentActivationService)),i(3,(0,o.inject)(p.IEnvironmentVariablesService)),i(4,(0,o.inject)(w.JupyterPaths))],S),t.JupyterKernelService=S},69930:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterKernelSpec=void 0,t.JupyterKernelSpec=class{constructor(e,t,n,r){this.specFile=t,this.interpreterPath=n,this.isRegisteredByVSC=r,this.name=e.name,this.argv=e.argv,this.language=e.language,this.path=e.argv&&e.argv.length>0?e.argv[0]:"",this.display_name=e.display_name,this.metadata=e.metadata,this.env=e.env,this.interrupt_mode=e.interrupt_mode}}},44718:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterUriProviderRegistration=void 0;const o=n(86700),s=n(71733),a=n(35952),c=n(42714);let l=class{constructor(e){this.extensions=e,this.providers=new Map}async getProviders(){return await this.checkOtherExtensions(),Promise.all([...this.providers.values()])}registerProvider(e){if(this.providers.has(e.id))throw new Error(`IJupyterUriProvider already exists with id ${e.id}`);this.providers.set(e.id,this.createProvider(e))}async getJupyterServerUri(e,t){await this.checkOtherExtensions();const n=this.providers.get(e);if(n)return(await n).getServerUri(t);throw new Error(a.DataScience.unknownServerUri())}checkOtherExtensions(){return this.loadedOtherExtensionsPromise||(this.loadedOtherExtensionsPromise=this.loadOtherExtensions()),this.loadedOtherExtensionsPromise}async loadOtherExtensions(){const e=this.extensions.all.filter((e=>{var t,n;return null===(n=null===(t=e.packageJSON)||void 0===t?void 0:t.contributes)||void 0===n?void 0:n.pythonRemoteServerProvider})).map((e=>e.isActive?Promise.resolve():e.activate()));await Promise.all(e)}async createProvider(e){const t=await this.extensions.determineExtensionFromCallStack();return new c.JupyterUriProviderWrapper(e,t.extensionId)}};l=r([(0,o.injectable)(),i(0,(0,o.inject)(s.IExtensions))],l),t.JupyterUriProviderRegistration=l},42714:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterUriProviderWrapper=void 0;const r=n(35952);t.JupyterUriProviderWrapper=class{constructor(e,t){this.provider=e,this.packageName=t}get id(){return this.provider.id}getQuickPickEntryItems(){return this.provider.getQuickPickEntryItems().map((e=>({...e,description:r.DataScience.uriProviderDescriptionFormat().format(e.description||"",this.packageName),original:e})))}handleQuickPick(e,t){return e.original?this.provider.handleQuickPick(e.original,t):this.provider.handleQuickPick(e,t)}getServerUri(e){return this.provider.getServerUri(e)}}},61741:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.computeWorkingDirectory=t.createRemoteConnectionInfo=t.expandWorkingDir=void 0,n(30895);const r=n(55674),i=n(71017),o=n(66828),s=n(30544),a=n(76817),c=n(95063);t.expandWorkingDir=function(e,t,n){if(e)return new s.SystemVariables(t?o.Uri.file(t):void 0,n.rootPath,n).resolve(e);if(t)return i.dirname(t);const r=n.getWorkspaceFolder(void 0);return r?r.uri.fsPath:process.cwd()},t.createRemoteConnectionInfo=function(e,t){let n;try{n=new URL(e),"/lab"===n.pathname&&(e=e.replace("lab","")),n=new URL(e)}catch(e){throw e}const r=t(e),i=r?r.baseUrl:`${n.protocol}//${n.host}${n.pathname}`,o=r?r.token:`${n.searchParams.get("token")}`;return{type:"jupyter",baseUrl:i,token:o,hostName:r?new URL(r.baseUrl).hostname:n.hostname,localLaunch:!1,displayName:r&&r.displayName?r.displayName:(0,a.getJupyterConnectionDisplayName)(o,i),disconnected:e=>({dispose:c.noop}),dispose:c.noop,rootDirectory:"",getAuthHeader:r?()=>{var n;return null===(n=t(e))||void 0===n?void 0:n.authorizationHeader}:void 0,url:e}},t.computeWorkingDirectory=async function(e,t){var n;const o=!(!e||"file"!==e.scheme)&&await r.pathExists(e.fsPath);return e&&"file"===e.scheme&&await r.pathExists(i.dirname(e.fsPath))&&e&&e.fsPath.includes(".")?i.dirname(e.fsPath):o&&e&&(await r.stat(e.fsPath)).isDirectory()?e.fsPath:(null===(n=t.getWorkspaceFolder(e))||void 0===n?void 0:n.uri.fsPath)||t.rootPath||process.cwd()}},27294:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterCommandLineSelector=void 0;const o=n(86700),s=n(24837),a=n(66828),c=n(13395),l=n(71733),u=n(35952),d=n(88220),p=n(97045),h=n(83474);let f=class{constructor(e,t,n,r,i){this.multiStepFactory=e,this.configuration=t,this.appShell=r,this.commandManager=i,this.defaultLabel=`$(zap) ${u.DataScience.jupyterCommandLineDefaultLabel()}`,this.customLabel=`$(gear) ${u.DataScience.jupyterCommandLineCustomLabel()}`,this.validate=async e=>{},n.onDidChangeConfiguration(this.onDidChangeConfiguration.bind(this))}selectJupyterCommandLine(e){return this.multiStepFactory.create().run(this.startSelectingCommandLine.bind(this,e),{})}async onDidChangeConfiguration(e){if(e.affectsConfiguration("jupyter.jupyterCommandLineArguments")){const e=u.DataScience.jupyterCommandLineReloadAnswer();await this.appShell.showInformationMessage(u.DataScience.jupyterCommandLineReloadQuestion(),e)===e&&this.commandManager.executeCommand("workbench.action.reloadWindow")}}async startSelectingCommandLine(e,t,n){if((await t.showQuickPick({placeholder:u.DataScience.jupyterCommandLineQuickPickPlaceholder(),items:this.getPickList(),title:u.DataScience.jupyterCommandLineQuickPickTitle()})).label!==this.defaultLabel)return this.selectCustomCommandLine.bind(this,e);await this.setJupyterCommandLine("")}async selectCustomCommandLine(e,t,n){const r=await t.showInputBox({title:u.DataScience.jupyterCommandLinePrompt(),value:this.configuration.getSettings(e).jupyterCommandLineArguments.join(" "),validate:this.validate,prompt:""});r&&await this.setJupyterCommandLine(r)}async setJupyterCommandLine(e){e&&(0,p.sendTelemetryEvent)(h.Telemetry.JupyterCommandLineNonDefault);const t=(0,s.default)(e);await this.configuration.updateSetting("jupyterCommandLineArguments",t,void 0,a.ConfigurationTarget.Workspace)}getPickList(){const e=[];return e.push({label:this.defaultLabel,detail:u.DataScience.jupyterCommandLineDefaultDetail()}),e.push({label:this.customLabel,detail:u.DataScience.jupyterCommandLineCustomDetail()}),e}};r([(0,p.captureTelemetry)(h.Telemetry.SelectJupyterURI)],f.prototype,"selectJupyterCommandLine",null),f=r([(0,o.injectable)(),i(0,(0,o.inject)(d.IMultiStepInputFactory)),i(1,(0,o.inject)(l.IConfigurationService)),i(2,(0,o.inject)(c.IWorkspaceService)),i(3,(0,o.inject)(c.IApplicationShell)),i(4,(0,o.inject)(c.ICommandManager))],f),t.JupyterCommandLineSelector=f},76817:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getJupyterConnectionDisplayName=t.JupyterConnectionWaiter=void 0,n(30895);const r=n(66828),i=n(71733),o=n(33149),s=n(46318),a=n(60593),c=n(7744),l=n(35952),u=n(83474),d=n(71008),p=n(84266)(u.RegExpValues.UrlPatternRegEx);t.JupyterConnectionWaiter=class{constructor(e,t,n,p,h,f){this.launchResult=e,this.notebookDir=t,this.rootDir=n,this.getServerInfo=p,this.cancelToken=f,this.stderr=[],this.connectionDisposed=!1,this.subscriptions=[],this.extractConnectionInformation=e=>{this.output(e),u.RegExpValues.HttpPattern.exec(e)&&this.notebookDir&&this.startPromise&&!this.startPromise.completed&&this.getServerInfo&&this.getServerInfo(this.cancelToken).then((t=>this.getJupyterURL(t,e))).catch((e=>(0,s.traceWarning)("Failed to get server info",e)))},this.launchTimedOut=()=>{this.startPromise.completed||this.rejectStartPromise(l.DataScience.jupyterLaunchTimedOut())},this.resolveStartPromise=(e,t,n)=>{if(clearTimeout(this.launchTimeout),!this.startPromise.rejected){const r=this.createConnection(e,t,n,this.launchResult),i=r.dispose.bind(r);r.dispose=()=>(this.connectionDisposed=!0,i()),this.startPromise.resolve(r)}},this.rejectStartPromise=e=>{clearTimeout(this.launchTimeout),this.startPromise.resolved||(e="string"==typeof e?e:e.message,this.startPromise.reject(o.Cancellation.isCanceled(this.cancelToken)?new r.CancellationError:new d.JupyterConnectError(e,this.stderr.join("\n"))))},this.configService=h.get(i.IConfigurationService),this.fs=h.get(a.IFileSystem),f&&f.onCancellationRequested((()=>this.startPromise.reject(new r.CancellationError))),this.startPromise=(0,c.createDeferred)();const m=this.configService.getSettings(void 0).jupyterLaunchTimeout;this.launchTimeout=setTimeout((()=>{this.launchTimedOut()}),m);let g="0";e.proc&&e.proc.on("exit",(e=>g=e?e.toString():"0"));let v="";this.subscriptions.push(e.out.subscribe((e=>{"stderr"===e.source?(v+=e.out,this.stderr.push(e.out),this.extractConnectionInformation(v)):this.output(e.out)}),(e=>this.rejectStartPromise(e)),(()=>this.rejectStartPromise(l.DataScience.jupyterServerCrashed().format(g)))))}dispose(){clearTimeout(this.launchTimeout),this.subscriptions.forEach((e=>e.unsubscribe()))}waitForConnection(){return this.startPromise.promise}createConnection(e,t,n,r){return new h(e,t,n,this.rootDir,r,this.launchResult.proc)}output(e){this.connectionDisposed||(0,s.traceInfo)(e.toString("utf8"))}getJupyterURL(e,t){if(e&&e.length>0&&!this.startPromise.completed){const t=e.find((e=>this.fs.areLocalPathsSame(this.notebookDir,e.notebook_dir)));if(t){const e=t.url,n=t.token,r=t.hostname;this.resolveStartPromise(e,n,r)}}this.startPromise.completed||this.getJupyterURLFromString(t)}getJupyterURLFromString(e){const t=p.exec(e),r=t.groups();if(t&&!this.startPromise.completed&&r&&(r.LOCAL||r.IP)){const e=r.LOCAL?r.LOCAL:r.IP,t=`${r.PREFIX}${e}${r.REST}`,i=n(57310).URL;let o;try{o=new i(t)}catch(e){return(0,s.traceError)(`Failed to parse ${t}`,e),void this.rejectStartPromise(l.DataScience.jupyterLaunchNoURL())}this.resolveStartPromise(`${o.protocol}//${o.host}${o.pathname}`,`${o.searchParams.get("token")}`,o.hostname)}}};class h{constructor(e,t,n,i,o,s){this.baseUrl=e,this.token=t,this.hostName=n,this.rootDirectory=i,this.disposable=o,this.localLaunch=!0,this.type="jupyter",this.eventEmitter=new r.EventEmitter,s&&s.on("exit",(e=>{const t="number"==typeof e?e:0;this.eventEmitter.fire(t)}))}get displayName(){return f(this.token,this.baseUrl)}get disconnected(){return this.eventEmitter.event}dispose(){this.disposable&&this.disposable.dispose()}}function f(e,t){return`${t}${e.length>0?`?token=${e}`:""}`}t.getJupyterConnectionDisplayName=f},33360:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterExecutionBase=void 0;const i=n(71017),o=n(71171),s=n(33149),a=n(3108),c=n(46318),l=n(35952),u=n(96188),d=n(83044),p=n(5448),h=n(97045),f=n(83474),m=n(61741),g=["localhost","127.0.0.1","::1"];class v{constructor(e,t,n,r,i,o){if(this.interpreterService=e,this.disposableRegistry=t,this.workspace=n,this.configuration=r,this.notebookStarter=i,this.serviceContainer=o,this.disposed=!1,this.uriToJupyterServerUri=new Map,this.pendingTimeouts=[],this.jupyterInterpreterService=o.get(p.IJupyterSubCommandExecutionService),this.jupyterPickerRegistration=o.get(p.IJupyterUriProviderRegistration),this.disposableRegistry.push(this.interpreterService.onDidChangeInterpreter((()=>this.onSettingsChanged()))),this.disposableRegistry.push(this),n){const e=n.onDidChangeConfiguration((e=>{e.affectsConfiguration("python.dataScience",void 0)&&this.onSettingsChanged(),e.affectsConfiguration("jupyter.jupyterServerType",void 0)&&this.clearTimeouts()}));this.disposableRegistry.push(e)}}dispose(){return this.disposed=!0,this.clearTimeouts(),Promise.resolve()}async refreshCommands(){await this.jupyterInterpreterService.refreshCommands()}isNotebookSupported(e){return this.jupyterInterpreterService.isNotebookSupported(e)}async getNotebookError(){return this.jupyterInterpreterService.getReasonForJupyterNotebookNotBeingSupported()}async getUsableJupyterPython(e){return this.usablePythonInterpreter||this.disposed||(this.usablePythonInterpreter=await s.Cancellation.race((()=>this.jupyterInterpreterService.getSelectedInterpreter(e)),e)),this.usablePythonInterpreter}connectToNotebookServer(e,t){return s.Cancellation.race((async()=>{let n,r;(0,c.traceInfo)("Connecting to server");const i=!e||!e.uri;let o=1;const s=Math.max(1,this.configuration.getSettings(void 0).jupyterLaunchRetries);let m;for(;o<=s&&!this.disposed;){try{return r=await this.startOrConnect(e,t),!r.localLaunch&&g.includes(r.hostName.toLowerCase())&&(0,h.sendTelemetryEvent)(f.Telemetry.ConnectRemoteJupyterViaLocalHost),n=this.serviceContainer.get(p.INotebookServer),(0,c.traceInfo)("Connecting to process server"),await n.connect(r,t),(0,c.traceInfo)("Connection complete server"),(0,h.sendTelemetryEvent)(i?f.Telemetry.ConnectLocalJupyter:f.Telemetry.ConnectRemoteJupyter),n}catch(e){if(m=e,n&&((0,c.traceInfo)(`Killing server because of error ${e}`),await n.dispose()),!(e instanceof d.JupyterWaitForIdleError&&o=0?((0,h.sendTelemetryEvent)(f.Telemetry.ConnectRemoteSelfCertFailedJupyter),new u.JupyterSelfCertsError(r.baseUrl)):a.WrappedError.from(l.DataScience.jupyterNotebookRemoteConnectFailed().format(r.baseUrl,e),e))}throw e}(0,c.traceInfo)("Retry because of wait for idle problem."),null==r||r.dispose(),o+=1}throw m}}),t)}getServer(e){return Promise.resolve(void 0)}async startOrConnect(e,t){if(e&&e.uri)return await this.updateServerUri(e.uri),(0,m.createRemoteConnectionInfo)(e.uri,this.getServerUri.bind(this));{(0,c.traceInfo)("Launching server");const n=!(!e||e.skipUsingDefaultConfig),r=(0,m.expandWorkingDir)(e.workingDir,this.workspace.rootPath?i.join(this.workspace.rootPath,`${o()}.txt`):void 0,this.workspace),a=await this.startNotebookServer(e.resource,n,this.configuration.getSettings(void 0).jupyterCommandLineArguments,r,t);if(a)return a;throw s.Cancellation.throwIfCanceled(t),new Error(l.DataScience.jupyterNotebookFailure().format(""))}}async startNotebookServer(e,t,n,r,i){return this.notebookStarter.start(e,t,n,r,i)}onSettingsChanged(){this.usablePythonInterpreter=void 0}extractJupyterServerHandleAndId(e){const t=new URL(e),n=t.searchParams.get(f.Identifiers.REMOTE_URI_ID_PARAM),r=t.searchParams.get(f.Identifiers.REMOTE_URI_HANDLE_PARAM);return n&&r?{handle:r,id:n}:void 0}clearTimeouts(){this.pendingTimeouts.forEach((e=>clearTimeout(e))),this.pendingTimeouts=[]}getServerUri(e){if(this.extractJupyterServerHandleAndId(e))return this.uriToJupyterServerUri.get(e)}async updateServerUri(e){const t=this.extractJupyterServerHandleAndId(e);if(t){const n=await this.jupyterPickerRegistration.getJupyterServerUri(t.id,t.handle);if(this.uriToJupyterServerUri.set(e,n),n.expiration){const t=n.expiration.getTime()-Date.now();t>0&&t<6048e5&&this.pendingTimeouts.push(setTimeout((()=>this.updateServerUri(e).ignoreErrors()),t))}}}}r([(0,h.captureTelemetry)(f.Telemetry.StartJupyter)],v.prototype,"startNotebookServer",null),t.JupyterExecutionBase=v},30640:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterNotebook=void 0;const r=n(50361);t.JupyterNotebook=class{constructor(e,t){this.session=e,this.__connection=r(t)}get connection(){return this.__connection}}},85797:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterNotebookProvider=void 0;const o=n(86700),s=n(14311),a=n(5448),c=n(43367),l=n(33149);let u=class{constructor(e,t){this.serverProvider=e,this.serverStorage=t}async connect(e){const t=await this.serverProvider.getOrCreateServer({ui:e.ui,resource:e.resource,token:e.token,localJupyter:"localJupyter"===e.kind}),n=await(null==t?void 0:t.getConnectionInfo());return n&&"remoteJupyter"===e.kind&&this.serverStorage.addToUriList(n.url||n.displayName,Date.now(),n.displayName),n}async createNotebook(e){const t=await this.serverProvider.getOrCreateServer({ui:e.ui,resource:e.resource,token:e.token,localJupyter:(0,c.isLocalConnection)(e.kernelConnection)});if(l.Cancellation.throwIfCanceled(e.token),t)return t.createNotebook(e.resource,e.kernelConnection,e.token,e.ui);throw new s.SessionDisposedError}};u=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IJupyterServerProvider)),i(1,(0,o.inject)(a.IJupyterServerUriStorage))],u),t.JupyterNotebookProvider=u},58584:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterPasswordConnect=void 0;const o=n(95687),s=n(86700),a=n(36292),c=n(57310),l=n(66828),u=n(13395),d=n(71733),p=n(35952),h=n(88220),f=n(97045),m=n(83474);let g=class{constructor(e,t,n,r){this.appShell=e,this.multiStepFactory=t,this.asyncDisposableRegistry=n,this.configService=r,this.savedConnectInfo=new Map,this.fetchFunction=a.default}getPasswordConnectionInfo(e,t){if(!e||e.length<1)return Promise.resolve(void 0);t&&(this.fetchFunction=t);let n=e;"/"!==n[n.length-1]&&(n=`${n}/`);let r=this.savedConnectInfo.get(n);return r||(r=this.getNonCachedPasswordConnectionInfo(n),this.savedConnectInfo.set(n,r)),r}getSessionCookieString(e,t,n){return`_xsrf=${e}; ${t}=${n}`}async getNonCachedPasswordConnectionInfo(e){return await this.isJupyterHub(e)?this.getJupyterHubConnectionInfo(e):this.getJupyterConnectionInfo(e)}async getJupyterHubConnectionInfo(e){const t=await this.getUserNameAndPassword();if(t.username||t.password){return await this.getJupyterHubConnectionInfoFromLogin(e,t.username,t.password)||this.getJupyterHubConnectionInfoFromApi(e,t.username,t.password)}}async getJupyterHubConnectionInfoFromLogin(e,t,n){const r=new URL(e),i=`${r.protocol}//${r.host}`,o=new c.URLSearchParams;o.append("username",t||""),o.append("password",n||"");let s=await this.makeRequest(`${i}/hub/login?next=`,{method:"POST",headers:{Connection:"keep-alive",Referer:`${i}/hub/login`,"content-type":"application/x-www-form-urlencoded;charset=UTF-8"},body:o.toString(),redirect:"manual"});if(s&&302===s.status){const e=[...this.getCookies(s).entries()].reduce(((e,t)=>`${e};${t[0]}=${t[1]}`),"");if(s=await this.makeRequest(`${i}/hub/api/users/${t}/tokens`,{method:"POST",headers:{Connection:"keep-alive",Cookie:e,Referer:`${i}/hub/login`}}),s.ok&&200===s.status){const n=await s.json();if(n&&n.token&&n.id)return await this.makeRequest(`${i}/hub/api/users/${t}/server`,{method:"POST",headers:{Connection:"keep-alive",Cookie:e,Referer:`${i}/hub/login`}}),this.asyncDisposableRegistry.push({dispose:async()=>{this.makeRequest(`${i}/hub/api/users/${t}/tokens/${n.id}`,{method:"DELETE",headers:{Connection:"keep-alive",Cookie:e,Referer:`${i}/hub/login`}}).ignoreErrors()}}),{requestHeaders:{},remappedBaseUrl:`${i}/user/${t}`,remappedToken:n.token}}}}async getJupyterHubConnectionInfoFromApi(e,t,n){const r=new URL(e),i=`${r.protocol}//${r.host}`,o=await this.makeRequest(`${i}/hub/api/authorizations/token`,{method:"POST",headers:{Connection:"keep-alive","content-type":"application/json;charset=UTF-8"},body:`{ "username": "${t||""}", "password": "${n||""}" }`,redirect:"manual"});if(o.ok&&200===o.status){const e=await o.json();if(e&&e.user&&e.user.server&&e.token)return{requestHeaders:{},remappedBaseUrl:`${i}${e.user.server}`,remappedToken:e.token}}}async getJupyterConnectionInfo(e){let t,n,r;if(!await this.needPassword(e))return{};{let i=await this.getUserPassword();if(!i)return{};if(t=await this.getXSRFToken(e,""),t){const o=await this.getSessionCookie(e,t,i);n=o.sessionCookieName,r=o.sessionCookieValue}else n="authservice_session",r=i,t=await this.getXSRFToken(e,`${n}=${r}`);i=void 0}if(t&&n&&r)return(0,f.sendTelemetryEvent)(m.Telemetry.GetPasswordSuccess),{requestHeaders:{Cookie:this.getSessionCookieString(t,n,r),"X-XSRFToken":t}};(0,f.sendTelemetryEvent)(m.Telemetry.GetPasswordFailure)}addAllowUnauthorized(e,t,n){if(e.startsWith("https")&&t){const e=new o.Agent({rejectUnauthorized:!1});return{...n,agent:e}}return n}async getUserNameAndPassword(){const e=this.multiStepFactory.create(),t={username:"",password:""};return await e.run(this.getUserNameMultiStep.bind(this),t),t}async getUserNameMultiStep(e,t){if(t.username=await e.showInputBox({title:p.DataScience.jupyterSelectUserAndPasswordTitle(),prompt:p.DataScience.jupyterSelectUserPrompt(),validate:this.validateUserNameOrPassword,value:""}),t.username)return this.getPasswordMultiStep.bind(this)}async validateUserNameOrPassword(e){}async getPasswordMultiStep(e,t){t.password=await e.showInputBox({title:p.DataScience.jupyterSelectUserAndPasswordTitle(),prompt:p.DataScience.jupyterSelectPasswordPrompt(),validate:this.validateUserNameOrPassword,value:"",password:!0})}async getUserPassword(){return this.appShell.showInputBox({prompt:p.DataScience.jupyterSelectPasswordPrompt(),ignoreFocusOut:!0,password:!0})}async getXSRFToken(e,t){var n;let r,i,o=`${e}login?`;""!=t?(o=`${e}tree`,i={Connection:"keep-alive",Cookie:t}):i={Connection:"keep-alive"};const s=await this.makeRequest(o,{method:"get",redirect:"manual",headers:i});if(void 0!==s&&s.ok){const e=this.getCookies(s);e.has("_xsrf")&&(r=null===(n=e.get("_xsrf"))||void 0===n?void 0:n.split(";")[0])}return r}async needPassword(e){return 200!==(await this.makeRequest(`${e}tree?`,{method:"get",redirect:"manual",headers:{Connection:"keep-alive"}})).status}async makeRequest(e,t){const n=this.configService.getSettings(void 0).allowUnauthorizedRemoteConnection;try{return await this.fetchFunction(e,this.addAllowUnauthorized(e,!!n,t))}catch(n){if(n.message.indexOf("reason: self signed certificate")>=0){const r=p.DataScience.jupyterSelfCertEnable(),i=p.DataScience.jupyterSelfCertClose(),o=await this.appShell.showErrorMessage(p.DataScience.jupyterSelfCertFail().format(n.message),r,i);if(o===r)return(0,f.sendTelemetryEvent)(m.Telemetry.SelfCertsMessageEnabled),await this.configService.updateSetting("allowUnauthorizedRemoteConnection",!0,void 0,l.ConfigurationTarget.Workspace),this.fetchFunction(e,this.addAllowUnauthorized(e,!0,t));o===i&&(0,f.sendTelemetryEvent)(m.Telemetry.SelfCertsMessageClose)}throw n}}async isJupyterHub(e){return!!e.toLowerCase().includes("/user/")||200===(await this.makeRequest(`${e}hub/api`,{method:"get",redirect:"manual",headers:{Connection:"keep-alive"}})).status}async getSessionCookie(e,t,n){let r,i;const o=new c.URLSearchParams;o.append("_xsrf",t),o.append("password",n);const s=await this.makeRequest(`${e}login?`,{method:"post",headers:{Cookie:`_xsrf=${t}`,Connection:"keep-alive","content-type":"application/x-www-form-urlencoded;charset=UTF-8"},body:o.toString(),redirect:"manual"});if(302===s.status){const e=this.getCookies(s);e.size>0&&(r=e.entries().next().value[0],i=e.entries().next().value[1])}return{sessionCookieName:r,sessionCookieValue:i}}getCookies(e){const t=new Map,n=e.headers.raw()["set-cookie"];return n&&n.forEach((e=>{const n=e.substring(0,e.indexOf("=")),r=e.substring(e.indexOf("=")+1);t.set(n,r)})),t}};r([(0,f.captureTelemetry)(m.Telemetry.GetPasswordAttempt)],g.prototype,"getPasswordConnectionInfo",null),g=r([(0,s.injectable)(),i(0,(0,s.inject)(u.IApplicationShell)),i(1,(0,s.inject)(h.IMultiStepInputFactory)),i(2,(0,s.inject)(d.IAsyncDisposableRegistry)),i(3,(0,s.inject)(d.IConfigurationService))],g),t.JupyterPasswordConnect=g},10600:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.HostJupyterExecution=void 0,n(30895);const o=n(71171),s=n(33360),a=n(56747),c=n(52706),l=n(86700),u=n(13395),d=n(46318),p=n(60593),h=n(71733),f=n(28735),m=n(48497),g=n(29474);let v=class extends s.JupyterExecutionBase{constructor(e,t,n,r,i,s,a,l){super(e,t,i,s,a,l),this._disposed=!1,this._id=o(),this.serverCache=new c.ServerCache(s,i,r),n.push(this)}clearCache(){this.serverCache.clearCache()}async dispose(){(0,d.traceInfo)(`Disposing HostJupyterExecution ${this._id}`),this._disposed||(this._disposed=!0,(0,d.traceInfo)(`Disposing super HostJupyterExecution ${this._id}`),await super.dispose(),this.serverCache&&((0,d.traceInfo)(`Cleaning up server cache ${this._id}`),await this.serverCache.dispose())),(0,d.traceInfo)(`Finished disposing HostJupyterExecution ${this._id}`)}async hostConnectToNotebookServer(e,t){if(!this._disposed)return super.connectToNotebookServer(await this.serverCache.generateDefaultOptions(e),t)}async connectToNotebookServer(e,t){if(!this._disposed)return this.serverCache.getOrCreate(this.hostConnectToNotebookServer.bind(this),e,t)}async getServer(e){if(!this._disposed)return this.serverCache.get(e)}};r([(0,f.testOnlyMethod)()],v.prototype,"clearCache",null),v=r([(0,l.injectable)(),i(0,(0,l.inject)(m.IInterpreterService)),i(1,(0,l.inject)(h.IDisposableRegistry)),i(2,(0,l.inject)(h.IAsyncDisposableRegistry)),i(3,(0,l.inject)(p.IFileSystem)),i(4,(0,l.inject)(u.IWorkspaceService)),i(5,(0,l.inject)(h.IConfigurationService)),i(6,(0,l.inject)(a.NotebookStarter)),i(7,(0,l.inject)(g.IServiceContainer))],v),t.HostJupyterExecution=v},14231:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.HostJupyterServer=void 0,n(30895);const o=n(86700),s=n(13395),a=n(97784),c=n(46318),l=n(71733),u=n(7744),d=n(35952),p=n(88319),h=n(14311),f=n(32417),m=n(5448),g=n(83474),v=n(43367),y=n(61741),b=n(30640),_=n(95063),w=n(33149),S=n(29140);let C=class{constructor(e,t,n,r,i){this.asyncRegistry=e,this.sessionManagerFactory=t,this.workspaceService=n,this.jupyterOutputChannel=r,this.disposables=i,this.connectPromise=(0,u.createDeferred)(),this.notebooks=new Set,this.disposed=!1,this.asyncRegistry.push(this)}async dispose(){this.disposed||(this.disposed=!0,(0,c.traceInfo)("Disposing HostJupyterServer"),await this.shutdown(),(0,c.traceInfo)("Finished disposing HostJupyterServer"))}get isDisposed(){return this.disposed}throwIfDisposedOrCancelled(e){if(this.isDisposed)throw new h.SessionDisposedError;w.Cancellation.throwIfCanceled(e)}async createNotebookInstance(e,t,n,r,i){this.throwIfDisposedOrCancelled(r);const o=(0,u.createDeferred)();this.trackDisposable(o.promise);const s=async()=>{const o=await this.computeLaunchInfo();this.throwIfDisposedOrCancelled(r);const s=(0,v.isLocalConnection)(n)?await(0,y.computeWorkingDirectory)(e,this.workspaceService):"";this.throwIfDisposedOrCancelled(r);const a=await t.startNew(e,n,s,i,r);return this.throwIfDisposedOrCancelled(r),(0,c.traceInfo)(`Started session for kernel ${n.id}`),{connection:o,session:a}};try{const{connection:e,session:t}=await s();if(this.throwIfDisposedOrCancelled(r),t){const r=new b.JupyterNotebook(t,e);(0,c.traceInfo)(`Finished connecting kernel ${n.id}`),o.resolve(r)}else o.reject(this.getDisposedError())}catch(e){o.reject(e)}return o.promise}async computeLaunchInfo(){let e=await this.waitForConnect();if(!e)throw this.getDisposedError();return e}async connect(e,t){(0,c.traceInfo)(`Connecting server kernel ${e.baseUrl}`),this.connection=e,this.connectPromise.resolve(e),this.connectionInfoDisconnectHandler=this.connection.disconnected((e=>{try{this.serverExitCode=e,(0,c.traceError)(d.DataScience.jupyterServerCrashed().format(e.toString())),this.shutdown().ignoreErrors()}catch(e){(0,_.noop)()}})),this.logRemoteOutput(d.DataScience.connectingToJupyterUri().format(e.baseUrl)),this.sessionManager=await this.sessionManagerFactory.create(e)}async createNotebook(e,t,n,r){var i;if(this.throwIfDisposedOrCancelled(n),(0,c.traceInfoIfCI)(`HostJupyterServer.createNotebook for ${(0,S.getDisplayPath)(e)} with ui.disableUI=${r.disableUI}, cancelToken.isCancellationRequested=${n.isCancellationRequested}`),!this.sessionManager||this.isDisposed)throw new h.SessionDisposedError;const o=new p.StopWatch;try{const s=await this.createNotebookInstance(e,this.sessionManager,t,n,r);this.throwIfDisposedOrCancelled(n);const a=(null===(i=this.connection)||void 0===i?void 0:i.baseUrl)||"";return this.logRemoteOutput(d.DataScience.createdNewNotebook().format(a)),(0,f.sendKernelTelemetryEvent)(e,g.Telemetry.JupyterCreatingNotebook,o.elapsedTime),s}catch(t){throw(0,f.sendKernelTelemetryEvent)(e,g.Telemetry.JupyterCreatingNotebook,o.elapsedTime,void 0,t),t}}async shutdown(){try{this.connectionInfoDisconnectHandler&&(this.connectionInfoDisconnectHandler.dispose(),this.connectionInfoDisconnectHandler=void 0),(0,c.traceInfo)("Shutting down notebooks");const e=await Promise.all([...this.notebooks.values()]);await Promise.all(e.map((e=>null==e?void 0:e.session.dispose()))),(0,c.traceInfo)("Shut down session manager : "+(this.sessionManager?"existing":"undefined")),this.sessionManager&&(1e4===await Promise.race([(0,u.sleep)(1e4),this.sessionManager.dispose()])&&(0,c.traceError)("Session shutdown timed out."),this.sessionManager=void 0),this.connection&&this.connection&&((0,c.traceInfo)("Shutdown server - dispose conn info"),this.connection.dispose(),this.connection=void 0)}catch(e){(0,c.traceError)("Error during shutdown: ",e)}}waitForConnect(){return this.connectPromise.promise}getConnectionInfo(){if(this.connection)return{...this.connection,dispose:_.noop}}getDisposedError(){return this.serverExitCode?new Error(d.DataScience.jupyterServerCrashed().format(this.serverExitCode.toString())):new h.SessionDisposedError}trackDisposable(e){e.then((t=>{t.session.onDidDispose((()=>this.notebooks.delete(e)),this,this.disposables)})).catch((()=>this.notebooks.delete(e))),this.notebooks.add(e)}logRemoteOutput(e){var t;(null===(t=this.connection)||void 0===t?void 0:t.localLaunch)||this.jupyterOutputChannel.appendLine(e)}};C=r([(0,o.injectable)(),i(0,(0,o.inject)(l.IAsyncDisposableRegistry)),i(1,(0,o.inject)(m.IJupyterSessionManagerFactory)),i(2,(0,o.inject)(s.IWorkspaceService)),i(3,(0,o.inject)(l.IOutputChannel)),i(3,(0,o.named)(a.STANDARD_OUTPUT_CHANNEL)),i(4,(0,o.inject)(l.IDisposableRegistry))],C),t.HostJupyterServer=C},52706:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.ServerCache=void 0,n(30895);const i=n(46318),o=n(28735),s=n(87605),a=n(7744);class c{constructor(e,t,n){this.configService=e,this.workspace=t,this.fs=n,this.cache=new Map,this.disposed=!1}clearCache(){this.cache.clear()}async getOrCreate(e,t,n){const r=await this.generateDefaultOptions(t),i=this.generateKey(r);let o;return o=this.cache.get(i),o||(o={promise:e(t,n),options:r,resolved:!1},this.cache.set(i,o)),o.promise.then((e=>{if(!e)return void this.cache.delete(i);const t=e.dispose.bind(e);return e.dispose=()=>(this.cache.delete(i),t()),o&&(o.resolved=!0),e})).catch((e=>{throw this.cache.delete(i),e}))}async get(e){var t;const n=await this.generateDefaultOptions(e),r=this.generateKey(n);if(this.cache.has(r))return null===(t=this.cache.get(r))||void 0===t?void 0:t.promise}async dispose(){if(!this.disposed){this.disposed=!0;const e=[...this.cache.values()];this.cache.clear(),await Promise.all(e.map((async e=>{try{const t=await Promise.race([e.promise,(0,a.sleep)(1e3)]);"number"!=typeof t?await t.dispose():(0,i.traceInfo)("ServerCache Dispose, no server")}catch(e){(0,i.traceError)("Dispose error in ServerCache: ",e)}})))}}async generateDefaultOptions(e){return{uri:e?e.uri:void 0,resource:null==e?void 0:e.resource,skipUsingDefaultConfig:!!e&&e.skipUsingDefaultConfig,workingDir:e&&e.workingDir?e.workingDir:await(0,s.calculateWorkingDirectory)(this.configService,this.workspace,this.fs,e.resource),ui:e.ui,localJupyter:e.localJupyter}}generateKey(e){return`uri=${e.uri?e.uri.toString():""};useFlag=${e.skipUsingDefaultConfig?"true":"false"};local=${e.localJupyter};workingDir=${e.workingDir}`}}r([(0,o.testOnlyMethod)()],c.prototype,"clearCache",null),t.ServerCache=c},61412:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.NotebookProvider=void 0;const o=n(86700),s=n(98501),a=n(71733),c=n(4036),l=n(17261),u=n(32417),d=n(5448),p=n(83474),h=n(43367),f=n(33149);let m=class{constructor(e,t,n,r){this.rawNotebookProvider=e,this.jupyterNotebookProvider=t,this.extensionChecker=n,this.configService=r,this.startupUi=new l.DisplayOptions(!0)}async connect(e){const t=this.configService.getSettings(void 0).jupyterServerType;e.ui.disableUI||(this.startupUi.disableUI=!1);const n=e.ui.onDidChangeDisableUI((()=>{e.ui.disableUI||(this.startupUi.disableUI=!1,n.dispose())}));if(this.rawNotebookProvider.isSupported&&"localJupyter"===e.kind)throw new Error("Connect method should not be invoked for local Connections when Raw is supported");if(this.extensionChecker.isPythonExtensionInstalled||t===c.Settings.JupyterServerRemoteLaunch)return this.jupyterNotebookProvider.connect(e).finally((()=>n.dispose()));n.dispose(),await this.extensionChecker.showPythonExtensionInstallRequiredPrompt()}async createNotebook(e){const t=(0,h.isLocalConnection)(e.kernelConnection),n=this.rawNotebookProvider.isSupported&&t;if(!n&&!await this.jupyterNotebookProvider.connect({resource:e.resource,token:e.token,ui:e.ui,kind:t?"localJupyter":"remoteJupyter"}))return;f.Cancellation.throwIfCanceled(e.token),(0,u.trackKernelResourceInformation)(e.resource,{kernelConnection:e.kernelConnection});const r=n?this.rawNotebookProvider.createNotebook(e.document,e.resource,e.kernelConnection,e.ui,e.token):this.jupyterNotebookProvider.createNotebook(e);return(0,u.sendKernelTelemetryWhenDone)(e.resource,p.Telemetry.NotebookStart,r,void 0,{disableUI:!0===e.ui.disableUI}),r}};m=r([(0,o.injectable)(),i(0,(0,o.inject)(d.IRawNotebookProvider)),i(1,(0,o.inject)(d.IJupyterNotebookProvider)),i(2,(0,o.inject)(s.IPythonExtensionChecker)),i(3,(0,o.inject)(a.IConfigurationService))],m),t.NotebookProvider=m},54369:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.NotebookServerProvider=void 0;const o=n(86700),s=n(66828),a=n(2687),c=n(46318),l=n(71733),u=n(28735),d=n(35952),p=n(4036),h=n(17261),f=n(75550),m=n(51129),g=n(5448),v=n(48497),y=n(10473);let b=class{constructor(e,t,n,r,i,o){this.configuration=e,this.jupyterExecution=t,this.interpreterService=n,this.serverUriStorage=r,this.serverSelector=i,this.disposables=o,this.serverPromise={},this.ui=new h.DisplayOptions(!0),r.onDidChangeUri((()=>{this.serverPromise.remote=void 0}),this,this.disposables)}clearCache(){this.serverPromise.local=void 0,this.serverPromise.remote=void 0}async getOrCreateServer(e){const t=await this.getNotebookServerOptions(e.resource,!0===e.localJupyter);if(e.localJupyter&&!t.uri){const e=await this.jupyterExecution.getServer(t);if(e)return e}return this.createServer(e)}async createServer(e){e.ui.disableUI||(this.ui.disableUI=!1),e.ui.onDidChangeDisableUI((()=>this.ui.disableUI=e.ui.disableUI),this,this.disposables);const t=e.localJupyter?"local":"remote";this.serverPromise[t]||(this.serverPromise[t]=this.startServer(e.resource,e.token,e.localJupyter));try{const n=await this.serverPromise[t];return!n&&e.token.isCancellationRequested&&delete this.serverPromise[t],n}catch(e){throw this.serverPromise[t]=void 0,e}}async startServer(e,t,n){const r=await this.getNotebookServerOptions(e,n);(0,c.traceInfo)("Checking for server existence."),r.uri===p.Settings.JupyterServerRemoteLaunch&&(await this.serverSelector.selectJupyterURI(!0),r.uri=await this.serverUriStorage.getUri());const i=[];let o;const l=async()=>{this.ui.disableUI||o||(o=await this.jupyterExecution.getServer(r)?m.KernelProgressReporter.createProgressReporter(e,d.DataScience.connectingToJupyter()):m.KernelProgressReporter.createProgressReporter(e,d.DataScience.startingJupyter()),i.push(o))};this.ui.disableUI&&this.ui.onDidChangeDisableUI(l,this,i);try{if(await l(),(0,c.traceInfo)("Checking for server usability."),!await this.checkUsable(r))throw(0,c.traceInfo)("Server not usable (should ask for install now)"),new f.JupyterInstallError(d.DataScience.jupyterNotSupported().format(await this.jupyterExecution.getNotebookError()));(0,c.traceInfo)("Starting notebook server.");const e=await this.jupyterExecution.connectToNotebookServer(r,t);return(0,c.traceInfo)("Server started."),e}catch(e){if((0,a.disposeAllDisposables)(i),t.isCancellationRequested&&e instanceof s.CancellationError)return;throw await this.jupyterExecution.refreshCommands(),e}finally{(0,a.disposeAllDisposables)(i)}}async checkUsable(e){try{return!(e&&!e.uri)||!!await this.jupyterExecution.getUsableJupyterPython()}catch(e){const t=await this.interpreterService.getActiveInterpreter(void 0);if(t){const n=t.displayName?t.displayName:t.path;throw new Error(d.DataScience.jupyterNotSupportedBecauseOfEnvironment().format(n,e.toString()))}throw new f.JupyterInstallError(d.DataScience.jupyterNotSupported().format(await this.jupyterExecution.getNotebookError()))}}async getNotebookServerOptions(e,t){let n=await this.serverUriStorage.getUri();const r=this.configuration.getSettings(void 0).useDefaultConfigForJupyter;return(t||n&&n.toLowerCase()===p.Settings.JupyterServerLocalLaunch)&&(n=void 0),{uri:n,resource:e,skipUsingDefaultConfig:!r,ui:this.ui,localJupyter:t}}};r([(0,u.testOnlyMethod)()],b.prototype,"clearCache",null),b=r([(0,o.injectable)(),i(0,(0,o.inject)(l.IConfigurationService)),i(1,(0,o.inject)(g.IJupyterExecution)),i(2,(0,o.inject)(v.IInterpreterService)),i(3,(0,o.inject)(g.IJupyterServerUriStorage)),i(4,(0,o.inject)(y.JupyterServerSelector)),i(5,(0,o.inject)(l.IDisposableRegistry))],b),t.NotebookServerProvider=b},56747:function(e,t,n){"use strict";var r,i=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.NotebookStarter=void 0;const s=n(32081),a=n(57310),c=n(86700),l=n(22037),u=n(71017),d=n(71171),p=n(66828),h=n(33149),f=n(2687),m=n(46318),g=n(60593),v=n(71733),y=n(35952),b=n(88319),_=n(71008),w=n(75550),S=n(51129),C=n(74721),k=n(5448),E=n(29474),x=n(97045),T=n(83474),D=n(76817),I=n(3108);let P=r=class{constructor(e,t,n,r){this.jupyterInterpreterService=e,this.fs=t,this.serviceContainer=n,this.jupyterOutputChannel=r,this.disposables=[]}static get usedPorts(){return Array.from(r._usedPorts)}dispose(){for(;this.disposables.length>0;){const e=this.disposables.shift();try{e&&e.dispose()}catch(e){}}}async start(e,t,n,i,o){(0,m.traceInfo)("Starting Notebook");let s,c=0;const l=[],u=S.KernelProgressReporter.reportProgress(e,C.ReportableAction.NotebookStart);try{const e=this.generateTempDir();e.then((e=>this.disposables.push(e))).ignoreErrors();const d=await this.generateArguments(t,n,e,i);h.Cancellation.throwIfCanceled(o),(0,m.traceInfo)("Starting Jupyter Notebook");const g=new b.StopWatch,[v,y]=await Promise.all([this.jupyterInterpreterService.startNotebook(d||[],{throwOnStdErr:!1,encoding:"utf8",token:o}),e]);v.proc&&(v.proc.on("exit",(e=>c=e)),v.out.subscribe((e=>this.jupyterOutputChannel.append(e.out)))),v&&o.onCancellationRequested((()=>{v.dispose()}),this,l),(0,m.traceInfo)("Waiting for Jupyter Notebook"),s=new D.JupyterConnectionWaiter(v,y.path,i,this.jupyterInterpreterService.getRunningJupyterServers.bind(this.jupyterInterpreterService),this.serviceContainer,o),h.Cancellation.throwIfCanceled(o);const _=await Promise.race([s.waitForConnection(),(0,h.createPromiseFromCancellation)({cancelAction:"reject",token:o})]);if(!_)throw new p.CancellationError;(0,x.sendTelemetryEvent)(T.Telemetry.StartJupyterProcess,g.elapsedTime);try{const e=parseInt(a.parse(_.baseUrl).port||"0",10);e&&!isNaN(e)&&(v.proc&&v.proc.on("exit",(()=>r._usedPorts.delete(e))),r._usedPorts.add(e))}catch(e){(0,m.traceError)(`Parsing failed ${_.baseUrl}`,e)}return(0,f.disposeAllDisposables)(l),_}catch(e){if((0,f.disposeAllDisposables)(l),e instanceof p.CancellationError||e instanceof _.JupyterConnectError)throw e;if(!await this.jupyterInterpreterService.isNotebookSupported())throw new w.JupyterInstallError(await this.jupyterInterpreterService.getReasonForJupyterNotebookNotBeingSupported());throw 0!==c?new Error(y.DataScience.jupyterServerCrashed().format(null==c?void 0:c.toString())):I.WrappedError.from(y.DataScience.jupyterNotebookFailure().format(e),e)}finally{u.dispose(),null==s||s.dispose()}}async generateDefaultArguments(e,t,n){const r=[];r.push(Promise.resolve("--no-browser")),r.push(Promise.resolve(this.getNotebookDirArgument(n))),r.push(Promise.resolve("--KernelManager.autorestart=False")),e&&r.push(this.getConfigArgument(t)),r.push(Promise.resolve("--NotebookApp.iopub_data_rate_limit=10000000000.0"));const[i,o]=await Promise.all([Promise.all(r),this.getDockerArguments()]);return[...i,...o,...process.env&&process.env.VSCODE_JUPYTER_DEBUG_JUPYTER?["--debug"]:[]]}async generateCustomArguments(e){return["--no-browser","--NotebookApp.iopub_data_rate_limit=10000000000.0","--KernelManager.autorestart=False",...e]}async generateArguments(e,t,n,r){return t&&0!==t.length?this.generateCustomArguments(t):this.generateDefaultArguments(e,n,r)}getNotebookDirArgument(e){return`--notebook-dir="${e.replace(/\\/g,"\\\\")}"`}async getConfigArgument(e){const t=await e,n=u.join(t.path,"jupyter_notebook_config.py");return await this.fs.writeLocalFile(n,""),(0,m.traceInfo)(`Generating custom default config at ${n}`),`--config=${n}`}async getDockerArguments(){const e=[];try{const t=await this.fs.readLocalFile("/proc/self/cgroup").catch((()=>""));return t.includes("docker")||t.includes("kubepods")?(e.push("--ip"),e.push("127.0.0.1"),new Promise((t=>{s.exec("id",{encoding:"utf-8"},((n,r)=>{r&&r.toString().includes("(root)")&&e.push("--allow-root"),t(e)}))}))):e}catch(t){return e}}async generateTempDir(){const e=u.join(l.tmpdir(),d());return await this.fs.createLocalDirectory(e),{path:e,dispose:async()=>{let t=0;for(;t<10;)try{await this.fs.deleteLocalDirectory(e),t=10}catch(e){t+=1}}}}};P._usedPorts=new Set,P=r=i([(0,c.injectable)(),o(0,(0,c.inject)(k.IJupyterSubCommandExecutionService)),o(1,(0,c.inject)(g.IFileSystem)),o(2,(0,c.inject)(E.IServiceContainer)),o(3,(0,c.inject)(v.IOutputChannel)),o(3,(0,c.named)(T.JUPYTER_OUTPUT_CHANNEL))],P),t.NotebookStarter=P},13658:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ServerPreload=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(97784),l=n(46318),u=n(71733),d=n(17261),p=n(82232),h=n(5448),f=n(93828),m=n(43367),g="last-notebook-created";let v=class{constructor(e,t,n,r,i,o,s,a,c){this.interactiveProvider=t,this.configService=n,this.notebookProvider=r,this.workspace=i,this.disposables=o,this.rawNotebookProvider=s,this.mementoStorage=a,this.kernelProvider=c,e.onDidOpenNotebookDocument(this.onDidOpenNotebook.bind(this),this,o),this.interactiveProvider.onDidChangeActiveInteractiveWindow(this.onDidOpenOrCloseInteractive.bind(this))}activate(){return this.checkDateForServerStart(),this.disposables.push(this.kernelProvider.onDidStartKernel(this.kernelStarted,this)),Promise.resolve()}get lastNotebookCreated(){const e=this.mementoStorage.get(g);return e?new Date(e):void 0}checkDateForServerStart(){this.shouldAutoStartStartServer(this.lastNotebookCreated)&&this.createServerIfNecessary().ignoreErrors()}shouldAutoStartStartServer(e){if(!e)return!1;const t=(new Date).getTime()-e.getTime();return Math.floor(t/864e5)<=7}async createServerIfNecessary(){if(!this.workspace.isTrusted||this.rawNotebookProvider.isSupported)return;const e=new s.CancellationTokenSource,t=new d.DisplayOptions(!0);try{(0,l.traceInfo)("Attempting to start a server because of preload conditions ..."),this.configService.getSettings(void 0).disableJupyterAutoStart||await this.notebookProvider.connect({resource:void 0,ui:t,kind:"localJupyter",token:e.token})}catch(e){(0,l.traceError)("Error starting server in serverPreload: ",e)}finally{t.dispose(),e.dispose()}}onDidOpenNotebook(e){(0,p.isJupyterNotebook)(e)&&this.createServerIfNecessary().ignoreErrors()}onDidOpenOrCloseInteractive(e){e&&this.createServerIfNecessary().ignoreErrors()}kernelStarted(e){const t=(0,f.getKernelConnectionLanguage)(e.kernelConnectionMetadata);this.mementoStorage.update(g,Date.now()),t===c.PYTHON_LANGUAGE&&this.mementoStorage.update("last-python-notebook-created",Date.now())}};v=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IVSCodeNotebook)),i(1,(0,o.inject)(h.IInteractiveWindowProvider)),i(2,(0,o.inject)(u.IConfigurationService)),i(3,(0,o.inject)(h.INotebookProvider)),i(4,(0,o.inject)(a.IWorkspaceService)),i(5,(0,o.inject)(u.IDisposableRegistry)),i(6,(0,o.inject)(h.IRawNotebookProvider)),i(7,(0,o.inject)(u.IMemento)),i(7,(0,o.named)(u.WORKSPACE_MEMENTO)),i(8,(0,o.inject)(m.IKernelProvider))],v),t.ServerPreload=v},91060:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterServerUriStorage=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(71733),l=n(4036);let u=class{constructor(e,t,n,r,i,o){this.configService=e,this.workspaceService=t,this.crypto=n,this.encryptedStorage=r,this.appEnv=i,this.globalMemento=o,this._onDidChangeUri=new s.EventEmitter,this.getUri().ignoreErrors()}get onDidChangeUri(){return this._onDidChangeUri.event}async addToUriList(e,t,n){const r=(await this.getSavedUriList()).filter(((t,n)=>t.uri!==e&&nt.uri!==e));return this.updateMemento(t)}async updateMemento(e){const t=e.sort(((e,t)=>t.time-e.time)),n=t.map(((e,t)=>({index:t,time:e.time})));await this.globalMemento.update(l.Settings.JupyterServerUriList,n);const r=t.map((e=>`${e.uri}${l.Settings.JupyterServerRemoteLaunchNameSeparator}${e.displayName&&e.displayName!==e.uri?e.displayName:l.Settings.JupyterServerRemoteLaunchUriEqualsDisplayName}`)).join(l.Settings.JupyterServerRemoteLaunchUriSeparator);return this.encryptedStorage.store(l.Settings.JupyterServerRemoteLaunchService,l.Settings.JupyterServerRemoteLaunchUriListKey,r)}async getSavedUriList(){const e=this.globalMemento.get(l.Settings.JupyterServerUriList);if(e&&e.length>0){const t=await this.encryptedStorage.retrieve(l.Settings.JupyterServerRemoteLaunchService,l.Settings.JupyterServerRemoteLaunchUriListKey);if(t){const n=t.split(l.Settings.JupyterServerRemoteLaunchUriSeparator),r=[];for(let t=0;t=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterServerSelector=void 0;const o=n(86700),s=n(96486),a=n(66828),c=n(13395),l=n(46318),u=n(35952),d=n(88220),p=n(4036),h=n(5448),f=n(36462),m=n(97045),g=n(83474),v="https://hostname:8080/?token=849d61a414abafab97bc4aab1f3547755ddc232c2b8cb7fe";let y=class{constructor(e,t,n,r){this.clipboard=e,this.multiStepFactory=t,this.extraUriProviders=n,this.serverUriStorage=r,this.localLabel=`$(zap) ${u.DataScience.jupyterSelectURINoneLabel()}`,this.newLabel=`$(server) ${u.DataScience.jupyterSelectURINewLabel()}`,this.remoteLabel=`$(server) ${u.DataScience.jupyterSelectURIRemoteLabel()}`,this.validateSelectJupyterURI=async e=>{try{if(new URL(e),!e.toLowerCase().includes("http"))throw new Error("Has to be http")}catch(e){return u.DataScience.jupyterSelectURIInvalidURI()}}}selectJupyterURI(e,t="nonUser"){return(0,m.sendTelemetryEvent)(g.Telemetry.SetJupyterURIUIDisplayed,void 0,{commandSource:t}),this.multiStepFactory.create().run(this.startSelectingURI.bind(this,e),{})}async setJupyterURIToLocal(){await this.serverUriStorage.setUri(p.Settings.JupyterServerLocalLaunch)}async setJupyterURIToRemote(e){await this.serverUriStorage.setUri(e),(0,m.sendTelemetryEvent)(g.Telemetry.SetJupyterURIToUserSpecified,void 0,{azure:e.toLowerCase().includes("azure")})}async startSelectingURI(e,t,n){const r=await this.serverUriStorage.getUri(),i=await this.getUriPickList(e,r),o=i.find((e=>e.url===r||e.label===this.localLabel&&r===p.Settings.JupyterServerLocalLaunch)),c=r===p.Settings.JupyterServerLocalLaunch?u.DataScience.jupyterSelectURINoneLabel():null==o?void 0:o.label,d=c?u.DataScience.jupyterSelectURIQuickPickCurrent().format(c):u.DataScience.jupyterSelectURIQuickPickPlaceholder();let h=Promise.resolve();const f=new a.EventEmitter,m=await t.showQuickPick({placeholder:d,items:i,activeItem:o,title:e?u.DataScience.jupyterSelectURIQuickPickTitle():u.DataScience.jupyterSelectURIQuickPickTitleRemoteOnly(),onDidTriggerItemButton:e=>{const t=e.item.url;t&&e.button.tooltip===u.DataScience.removeRemoteJupyterServerEntryInQuickPick()&&(h=h.then((()=>this.serverUriStorage.removeUri(t).catch((e=>(0,l.traceError)("Failed to update Uri list",e))))),i.splice(i.indexOf(e.item),1),f.fire(i.concat([])))},onDidChangeItems:f.event});if(await h.catch((e=>(0,l.traceError)("Failed to update Uri list",e))),m.label===this.localLabel)await this.setJupyterURIToLocal();else{if(m.newChoice||m.provider)return m.provider?this.selectProviderURI.bind(this,m.provider,m):this.selectRemoteURI.bind(this);await this.setJupyterURIToRemote((0,s.isNil)(m.url)?m.label:m.url)}}async selectProviderURI(e,t,n,r){const i=await e.handleQuickPick(t,!0);if("back"===i)throw d.InputFlowAction.back;i&&await this.handleProviderQuickPick(e.id,i)}async handleProviderQuickPick(e,t){if(t){const n=this.generateUriFromRemoteProvider(e,t);await this.setJupyterURIToRemote(n)}}generateUriFromRemoteProvider(e,t){return`${g.Identifiers.REMOTE_URI}?${g.Identifiers.REMOTE_URI_ID_PARAM}=${e}&${g.Identifiers.REMOTE_URI_HANDLE_PARAM}=${encodeURI(t)}`}async selectRemoteURI(e,t){let n=v;try{const e=await this.clipboard.readText().catch((()=>"")),t=a.Uri.parse(e.trim(),!0);n=e&&t&&t.scheme.toLowerCase().startsWith("http")?e:v}catch(e){}const r=await e.showInputBox({title:u.DataScience.jupyterSelectURIPrompt(),value:n||v,validate:this.validateSelectJupyterURI,prompt:""});r&&await this.setJupyterURIToRemote(r)}async getUriPickList(e,t){let n=[];const r=await this.extraUriProviders.getProviders();r&&r.forEach((e=>{const t=e.getQuickPickEntryItems().map((t=>({...t,newChoice:!1,provider:e})));n=n.concat(t)}));let i=[];return e?(i.push({label:this.localLabel,detail:u.DataScience.jupyterSelectURINoneDetail(),newChoice:!1}),i=i.concat(n),i.push({label:this.newLabel,detail:u.DataScience.jupyterSelectURINewDetail(),newChoice:!0})):(i=i.concat(n),i.push({label:this.remoteLabel,detail:u.DataScience.jupyterSelectURIRemoteDetail(),newChoice:!0})),(await this.serverUriStorage.getSavedUriList()).forEach((e=>{if(e.uri){const n=new Date(e.time),r=t===e.uri;i.push({label:(0,s.isNil)(e.displayName)?e.uri:e.displayName,detail:u.DataScience.jupyterSelectURIMRUDetail().format(n.toLocaleString()),newChoice:!1,url:e.uri,buttons:r?[]:[{iconPath:new a.ThemeIcon("trash"),tooltip:u.DataScience.removeRemoteJupyterServerEntryInQuickPick()}]})}})),i}};r([(0,m.captureTelemetry)(g.Telemetry.SelectJupyterURI),f.traceDecorators.error("Failed to select Jupyter Uri")],y.prototype,"selectJupyterURI",null),r([(0,m.captureTelemetry)(g.Telemetry.SetJupyterURIToLocal)],y.prototype,"setJupyterURIToLocal",null),y=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IClipboard)),i(1,(0,o.inject)(d.IMultiStepInputFactory)),i(2,(0,o.inject)(h.IJupyterUriProviderRegistration)),i(3,(0,o.inject)(h.IJupyterServerUriStorage))],y),t.JupyterServerSelector=y},85943:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createAuthorizingRequest=void 0;const r=n(36292);t.createAuthorizingRequest=function(e){class t extends r.Request{constructor(t,n){super(t,n);const r=this.headers,i=e();Object.keys(i).forEach((e=>r.append(e,i[e].toString()))),r.set("Content-Type","application/json");const o=r.append.bind(r);r.append=(e,t)=>{"authorization"!==e.toLowerCase()&&o(e,t)}}}return t}},31092:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterSession=t.removeNotebookSuffixAddedByExtension=void 0;const i=n(71017),o=n(71171),s=n(74389),a=n(33149),c=n(3108),l=n(46318),u=n(7744),d=n(35952),p=n(17261),h=n(1593),f=n(14311),m=n(97045),g=n(83474),v=n(80529),y=n(93828),b=n(43367),_=n(42908),w=n(29140),S="-jvsc-";t.removeNotebookSuffixAddedByExtension=function(e){if(e.includes(S)){const t=/[a-f0-9]$/;if(-1!==e.substring(e.lastIndexOf(S)+S.length).search(t))return`${e.substring(0,e.lastIndexOf(S))}.ipynb`}return e};class C extends v.BaseJupyterSession{constructor(e,t,n,r,i,o,s,a,c,l,u,d,p){super(e,n,c,l,p),this.connInfo=t,this.specsManager=r,this.sessionManager=i,this.contentsManager=o,this.outputChannel=s,this.restartSessionCreated=a,this.workingDirectory=l,this.idleTimeout=u,this.kernelService=d}waitForIdle(e){return this.waitForIdleOnSession(this.session,e)}get kernel(){var e;return(null===(e=this.session)||void 0===e?void 0:e.kernel)||void 0}get kernelId(){var e,t;return(null===(t=null===(e=this.session)||void 0===e?void 0:e.kernel)||void 0===t?void 0:t.id)||""}async connect(e){var t;this.setSession(await this.createNewKernelSession(e)),null===(t=this.session)||void 0===t||t.statusChanged.connect(this.statusHandler),this.connected=!0}async createNewKernelSession(e){var t;let n;try{this.kernelConnectionMetadata&&"connectToLiveKernel"===this.kernelConnectionMetadata.kind&&this.kernelConnectionMetadata.kernelModel.id&&this.kernelConnectionMetadata.kernelModel.model?(n=this.sessionManager.connectTo({...this.kernelConnectionMetadata.kernelModel,model:this.kernelConnectionMetadata.kernelModel.model}),n.kernelConnectionMetadata=this.kernelConnectionMetadata,n.kernelSocketInformation={socket:_.JupyterWebSockets.get(this.kernelConnectionMetadata.id),options:{clientId:"",id:this.kernelConnectionMetadata.id,model:{...this.kernelConnectionMetadata.kernelModel.model},userName:""}},n.isRemoteSession=!0,n.resource=this.resource,await(0,u.waitForCondition)((async()=>{var e;return"connected"===(null===(e=null==n?void 0:n.kernel)||void 0===e?void 0:e.connectionStatus)}),this.idleTimeout,100)):((0,l.traceVerbose)(`createNewKernelSession ${null===(t=this.kernelConnectionMetadata)||void 0===t?void 0:t.id}`),n=await this.createSession(e),n.resource=this.resource,await this.waitForIdleOnSession(n,this.idleTimeout))}catch(t){const n=e.ui.disableUI?l.traceVerbose:l.traceError;throw t instanceof c.BaseError?(n("Failed to change kernel, re-throwing",t),t):(n("Failed to change kernel",t),new h.JupyterInvalidKernelError(this.kernelConnectionMetadata))}return n}async createRestartSession(e,t,n){var r;if(!t||!this.contentsManager||!this.sessionManager)throw new f.SessionDisposedError;let i;const o=new p.DisplayOptions(e);try{return(0,l.traceVerbose)(`JupyterSession.createNewKernelSession 0, id is ${null===(r=this.kernelConnectionMetadata)||void 0===r?void 0:r.id}`),i=await this.createSession({token:n,ui:o}),await this.waitForIdleOnSession(i,this.idleTimeout),i.kernel&&this.restartSessionCreated(i.kernel),i}catch(e){throw(0,l.traceInfo)(`Error waiting for restart session: ${e}`),i&&this.shutdownSession(i,void 0,!0).ignoreErrors(),i=void 0,e}finally{o.dispose()}}startRestartSession(e){if(!this.restartSessionPromise&&this.session&&this.contentsManager){const t=new s.CancellationTokenSource,n=this.createRestartSession(e,this.session,t.token);this.restartSessionPromise={token:t,promise:n},n.finally((()=>t.dispose()))}}async createBackingFile(){let e;const t=i.relative(this.connInfo.rootDirectory,this.workingDirectory).replace(/\\/g,"/"),n=(0,b.isLocalConnection)(this.kernelConnectionMetadata)&&!t.startsWith("..")?{type:"notebook",path:t}:{type:"notebook"},r=this.resource?`${i.basename(this.resource.fsPath,".ipynb")}-jvsc-${o()}.ipynb`:`${d.DataScience.defaultNotebookName()}-${o()}.ipynb`;try{e=await this.contentsManager.newUntitled(n);const t=i.dirname(e.path);e=await this.contentsManager.rename(e.path,t.length&&"."!==t?`${t}/${r}`:r)}catch(t){if((0,b.isLocalConnection)(this.kernelConnectionMetadata))try{e=await this.contentsManager.newUntitled({type:"notebook"});const t=i.dirname(e.path);e=await this.contentsManager.rename(e.path,t.length&&"."!==t?`${t}/${r}`:r)}catch(e){}else(0,l.traceError)(`Backing file not supported: ${t}`)}if(e)return e}async createSession(e){var t,n,r,i,s,c;(0,l.traceInfoIfCI)(`JupyterSession.createSession for ${(0,w.getDisplayPath)(this.resource)}, options.ui.disableUI=${e.ui.disableUI}`);const u=await this.createBackingFile();if((null===(t=this.kernelConnectionMetadata)||void 0===t?void 0:t.interpreter)&&(0,b.isLocalConnection)(this.kernelConnectionMetadata))try{(0,l.traceInfoIfCI)(`JupyterSession.createSession ${this.kernelConnectionMetadata.id} for ${(0,w.getDisplayPath)(this.resource)}, options.ui.disableUI=${e.ui.disableUI}`),await this.kernelService.ensureKernelIsUsable(this.resource,this.kernelConnectionMetadata,e.ui,e.token)}catch(e){throw this.connInfo&&u&&this.contentsManager.delete(u.path).ignoreErrors(),e}const p=null!==(s=null!==(n=(0,y.getNameOfKernelConnection)(this.kernelConnectionMetadata))&&void 0!==n?n:null===(i=null===(r=this.specsManager)||void 0===r?void 0:r.specs)||void 0===i?void 0:i.default)&&void 0!==s?s:"",h={path:(null==u?void 0:u.path)||`${o()}.ipynb`,kernel:{name:p},name:o(),type:"notebook"};return(0,l.traceInfo)(`Starting a new session for kernel id = ${null===(c=this.kernelConnectionMetadata)||void 0===c?void 0:c.id}, name = ${p} for ${(0,w.getDisplayPath)(this.resource)}`),a.Cancellation.race((()=>this.sessionManager.startNew(h,{kernelConnectionOptions:{handleComms:!0}}).then((async e=>{var t;if(e.kernel){this.logRemoteOutput(d.DataScience.createdNewKernel().format(this.connInfo.baseUrl,(null===(t=null==e?void 0:e.kernel)||void 0===t?void 0:t.id)||""));const n=e;return n.resource=this.resource,n.kernelConnectionMetadata=this.kernelConnectionMetadata,n.kernelSocketInformation={get socket(){return _.JupyterWebSockets.get(e.kernel.id)},options:{clientId:e.kernel.clientId,id:e.kernel.id,model:{...e.kernel.model},userName:e.kernel.username}},(0,b.isLocalConnection)(this.kernelConnectionMetadata)||(n.isRemoteSession=!0),n}throw new v.JupyterSessionStartError(new Error("No kernel created"))})).catch((e=>Promise.reject(new v.JupyterSessionStartError(e)))).finally((()=>{this.connInfo&&u&&this.contentsManager.delete(u.path).ignoreErrors()}))),e.token)}logRemoteOutput(e){(0,b.isLocalConnection)(this.kernelConnectionMetadata)||this.outputChannel.appendLine(e)}}r([(0,m.captureTelemetry)(g.Telemetry.WaitForIdleJupyter,void 0,!0)],C.prototype,"waitForIdle",null),t.JupyterSession=C},1632:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterSessionManager=void 0;const r=n(95687),i=n(36292),o=n(66828),s=n(46318),a=n(35952),c=n(14311),l=n(93828),u=n(69930),d=n(85943),p=n(31092),h=n(42908),f=n(7744);class m{constructor(e,t,n,r,i,s,a,c){this.jupyterPasswordConnect=e,this.failOnPassword=n,this.outputChannel=r,this.configService=i,this.appShell=s,this.stateFactory=a,this.kernelService=c,this.restartSessionCreatedEvent=new o.EventEmitter,this.restartSessionUsedEvent=new o.EventEmitter,this.userAllowsInsecureConnections=this.stateFactory.createGlobalPersistentState("DataScienceAllowInsecureConnections",!1)}get jupyterlab(){return this._jupyterlab||(this._jupyterlab=n(36879)),this._jupyterlab}get onRestartSessionCreated(){return this.restartSessionCreatedEvent.event}get onRestartSessionUsed(){return this.restartSessionUsedEvent.event}async dispose(){(0,s.traceInfo)("Disposing session manager");try{this.contentsManager&&((0,s.traceInfo)("SessionManager - dispose contents manager"),this.contentsManager.dispose(),this.contentsManager=void 0),this.sessionManager&&!this.sessionManager.isDisposed&&((0,s.traceInfo)("ShutdownSessionAndConnection - dispose session manager"),await Promise.race([(0,f.sleep)(1e4),this.sessionManager.ready]),this.sessionManager.dispose(),this.sessionManager=void 0)}catch(e){(0,s.traceError)("Exception on session manager shutdown: ",e)}finally{(0,s.traceInfo)("Finished disposing jupyter session manager")}}async initialize(e){this.connInfo=e,this.serverSettings=await this.getServerConnectSettings(e),this.specsManager=new this.jupyterlab.KernelSpecManager({serverSettings:this.serverSettings}),this.kernelManager=new this.jupyterlab.KernelManager({serverSettings:this.serverSettings}),this.sessionManager=new this.jupyterlab.SessionManager({serverSettings:this.serverSettings,kernelManager:this.kernelManager}),this.contentsManager=new this.jupyterlab.ContentsManager({serverSettings:this.serverSettings})}async getRunningSessions(){if(!this.sessionManager)return[];await this.sessionManager.refreshRunning();const e=[],t=this.sessionManager.running();let n=t.next();for(;n;)e.push(n),n=t.next();return e}async getRunningKernels(){const e=await this.jupyterlab.KernelAPI.listRunning(this.serverSettings),t=new Set;return e.map((e=>{const t=e;return{id:e.id,name:e.name,lastActivityTime:t.last_activity?new Date(Date.parse(t.last_activity.toString())):new Date,numberOfConnections:t.connections?parseInt(t.connections.toString(),10):0}})).filter((e=>!t.has(e.id)&&(t.add(e.id),!0)))}async startNew(e,t,n,r,i){if(!(this.connInfo&&this.sessionManager&&this.contentsManager&&this.serverSettings&&this.specsManager))throw new c.SessionDisposedError;const o=new p.JupyterSession(e,this.connInfo,t,this.specsManager,this.sessionManager,this.contentsManager,this.outputChannel,this.restartSessionCreatedEvent.fire.bind(this.restartSessionCreatedEvent),this.restartSessionUsedEvent.fire.bind(this.restartSessionUsedEvent),n,this.configService.getSettings(e).jupyterLaunchTimeout,this.kernelService,this.configService.getSettings(e).jupyterInterruptTimeout);try{await o.connect({token:i,ui:r})}finally{o.isConnected||await o.dispose()}return o}async getKernelSpecs(){var e,t,n;if(!this.connInfo||!this.sessionManager||!this.contentsManager)throw new c.SessionDisposedError;try{const r=(null===(e=this.specsManager)||void 0===e?void 0:e.specs)&&Object.keys(this.specsManager.specs.kernelspecs).length?this.specsManager.specs.kernelspecs:{};await Promise.race([(0,f.sleep)(1e4),this.sessionManager.ready]),await Promise.race([(0,f.sleep)(1e4),null===(t=this.specsManager)||void 0===t?void 0:t.refreshSpecs()]);const i=(null===(n=this.specsManager)||void 0===n?void 0:n.specs)&&Object.keys(this.specsManager.specs.kernelspecs).length?this.specsManager.specs.kernelspecs:r,o=Object.keys(i);return o&&o.length?o.map((e=>{const t=i[e];return new u.JupyterKernelSpec(t)})):((0,s.traceError)(`SessionManager cannot enumerate kernelspecs. Returning default ${JSON.stringify(i)}.`),[(0,l.createInterpreterKernelSpec)()])}catch(e){return(0,s.traceError)("SessionManager:getKernelSpecs failure: ",e),[]}}async getServerConnectSettings(e){let t={baseUrl:e.baseUrl,appUrl:"",wsUrl:e.baseUrl.replace("http","ws")};await this.secureConnectionCheck(e);let n,o={cache:"no-store",credentials:"same-origin"},c=i.Request;if(e.getAuthHeader&&(c=(0,d.createAuthorizingRequest)(e.getAuthHeader)),""!==e.token&&"null"!==e.token||e.getAuthHeader)t={...t,token:e.token,appendToken:!0};else{if(this.failOnPassword)throw new Error("Password request not allowed.");t={...t,token:""};const r=await this.jupyterPasswordConnect.getPasswordConnectionInfo(e.baseUrl);if(r&&r.requestHeaders)o={...o,headers:r.requestHeaders},n=r.requestHeaders.Cookie||"",r.remappedBaseUrl&&(t.baseUrl=r.remappedBaseUrl,t.wsUrl=r.remappedBaseUrl.replace("http","ws")),r.remappedToken&&(t.token=r.remappedToken);else{if(!r)throw new Error(a.DataScience.passwordFailure());t={...t,token:e.token}}}const l=this.configService.getSettings(void 0).allowUnauthorizedRemoteConnection;if(e.baseUrl.startsWith("https")&&l){const e=new r.Agent({rejectUnauthorized:!1});o={...o,agent:e}}return t={...t,init:o,WebSocket:(0,h.createJupyterWebSocket)(n,l,e.getAuthHeader),fetch:i.default,Request:c,Headers:i.Headers},(0,s.traceInfo)(`Creating server with settings : ${JSON.stringify(t)}`),this.jupyterlab.ServerConnection.makeSettings(t)}async insecureServerWarningPrompt(){const e=a.DataScience.insecureSessionMessage(),t=[a.Common.bannerLabelYes(),a.Common.bannerLabelNo(),a.Common.doNotShowAgain()];switch(await this.appShell.showWarningMessage(e,...t)){case a.Common.bannerLabelYes():return!0;case a.Common.doNotShowAgain():return await this.userAllowsInsecureConnections.updateValue(!0),!0;case a.Common.bannerLabelNo():default:return!1}}async secureConnectionCheck(e){if(this.userAllowsInsecureConnections.value)return;if(e.localLaunch||e.baseUrl.startsWith("https")||"null"!==e.token)return;let t=m.secureServers.get(e.baseUrl);if(void 0===t&&(t=this.insecureServerWarningPrompt(),m.secureServers.set(e.baseUrl,t)),!await t)throw new Error(a.DataScience.insecureSessionDenied())}}t.JupyterSessionManager=m,m.secureServers=new Map},77721:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterSessionManagerFactory=void 0;const o=n(86700),s=n(66828),a=n(1632),c=n(13395),l=n(71733),u=n(5448),d=n(83474),p=n(74843);let h=class{constructor(e,t,n,r,i,o,a){this.jupyterPasswordConnect=e,this.config=t,this.jupyterOutput=n,this.appShell=r,this.stateFactory=i,this.disposableRegistry=o,this.kernelService=a,this.restartSessionCreatedEvent=new s.EventEmitter,this.restartSessionUsedEvent=new s.EventEmitter}async create(e,t){const n=new a.JupyterSessionManager(this.jupyterPasswordConnect,this.config,t,this.jupyterOutput,this.config,this.appShell,this.stateFactory,this.kernelService);return await n.initialize(e),this.disposableRegistry.push(n.onRestartSessionCreated(this.restartSessionCreatedEvent.fire.bind(this.restartSessionCreatedEvent))),this.disposableRegistry.push(n.onRestartSessionUsed(this.restartSessionUsedEvent.fire.bind(this.restartSessionUsedEvent))),n}get onRestartSessionCreated(){return this.restartSessionCreatedEvent.event}get onRestartSessionUsed(){return this.restartSessionUsedEvent.event}};h=r([(0,o.injectable)(),i(0,(0,o.inject)(u.IJupyterPasswordConnect)),i(1,(0,o.inject)(l.IConfigurationService)),i(2,(0,o.inject)(l.IOutputChannel)),i(2,(0,o.named)(d.JUPYTER_OUTPUT_CHANNEL)),i(3,(0,o.inject)(c.IApplicationShell)),i(4,(0,o.inject)(l.IPersistentStateFactory)),i(5,(0,o.inject)(l.IDisposableRegistry)),i(6,(0,o.inject)(p.JupyterKernelService))],h),t.JupyterSessionManagerFactory=h},42908:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createJupyterWebSocket=t.JupyterWebSockets=void 0;const r=n(8777),i=n(46318),o=n(95063),s=n(8095);t.JupyterWebSockets=new Map,t.createJupyterWebSocket=function(e,n,a){class c extends((0,s.KernelSocketWrapper)(r)){constructor(r,s){let c,l,u={};if(n&&(u={...u,rejectUnauthorized:!1}),e&&(c={Cookie:e}),a){const e=a();c=c?{...c,...e}:e}c&&(u={...u,headers:c}),super(r,s,u);const d=/.*\/kernels\/(.*)\/.*/.exec(r);d&&d.length>1&&(this.kernelId=d[1]),this.kernelId?(t.JupyterWebSockets.set(this.kernelId,this),this.on("close",(()=>{l&&this.timer!==l&&clearInterval(l),t.JupyterWebSockets.get(this.kernelId)===this&&t.JupyterWebSockets.delete(this.kernelId)}))):(0,i.traceError)("KernelId not extracted from Kernel WebSocket URL"),l=this.timer=setInterval((()=>this.ping(o.noop)),3e4)}}return c}},92201:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getPlainTextOrStreamOutput=t.Kernel=void 0;const r=n(71171),i=n(37875),o=n(66828),s=n(3108),a=n(2687),c=n(46318),l=n(29140),u=n(7744),d=n(35952),p=n(95063),h=n(88319),f=n(4036),m=n(17261),g=n(71008),v=n(73913),y=n(51129),b=n(32417),_=n(5448),w=n(87605),S=n(97045),C=n(44007),k=n(83474),E=n(93828),x=n(61741),T=n(43367),D=n(86593),I=n(82232),P=n(33149);t.Kernel=class{constructor(e,t,n,s,a,c,l,u,d,p,h,f,g,v,y,b){this.notebookDocument=e,this.resourceUri=t,this.kernelConnectionMetadata=n,this.notebookProvider=s,this.disposables=a,this.launchTimeout=c,this.appShell=u,this.fs=d,this.controller=p,this.configService=h,this.workspaceService=g,this.cellHashProviderFactory=v,this.pythonExecutionFactory=y,this.statusProvider=b,this._kernelSocket=new i.ReplaySubject,this._onStatusChanged=new o.EventEmitter,this._onRestarted=new o.EventEmitter,this._onStarted=new o.EventEmitter,this._onDisposed=new o.EventEmitter,this._onPreExecute=new o.EventEmitter,this.hookedNotebookForEvents=new WeakSet,this.eventHooks=[],this.startCancellation=new o.CancellationTokenSource,this.startupUI=new m.DisplayOptions(!0),this.id=`${r()}#${n.id}`,this.kernelExecution=new D.KernelExecution(this,u,n,l,a,p,f,v),this.kernelExecution.onPreExecute((e=>this._onPreExecute.fire(e)),this,a)}get connection(){var e;return null===(e=this.notebook)||void 0===e?void 0:e.connection}get onStatusChanged(){return this._onStatusChanged.event}get onRestarted(){return this._onRestarted.event}get onStarted(){return this._onStarted.event}get onDisposed(){return this._onDisposed.event}get onPreExecute(){return this._onPreExecute.event}get startedAtLeastOnce(){return this._startedAtLeastOnce}get info(){return this._info}get status(){var e,t,n;return this._notebookPromise&&!this.notebook?"starting":null!==(n=null===(t=null===(e=this.notebook)||void 0===e?void 0:e.session)||void 0===t?void 0:t.status)&&void 0!==n?n:this.isKernelDead?"dead":"unknown"}get disposed(){var e;return!0===this._disposed||!0===(null===(e=this.notebook)||void 0===e?void 0:e.session.disposed)}get disposing(){return!0===this._disposing}get kernelSocket(){return this._kernelSocket.asObservable()}get session(){var e;return null===(e=this.notebook)||void 0===e?void 0:e.session}get pendingCells(){return this.kernelExecution.queue}addEventHook(e){this.eventHooks.push(e)}removeEventHook(e){this.eventHooks=this.eventHooks.filter((t=>t!==e))}async executeCell(e){(0,I.traceCellMessage)(e,`kernel.executeCell, ${(0,l.getDisplayPath)(e.notebook.uri)}`),(0,b.sendKernelTelemetryEvent)(this.resourceUri,k.Telemetry.ExecuteCell);const t=new h.StopWatch,n=this.startNotebook().then((e=>e.session)),r=this.kernelExecution.executeCell(n,e);return this.trackNotebookCellPerceivedColdTime(t,n,r).catch(p.noop),r.then((t=>(0,c.traceInfo)(`Cell ${e.index} executed with state ${t}`))),r}async executeHidden(e){(0,c.traceInfoIfCI)(`Execute hidden code ${e}`);const t=new h.StopWatch,n=this.startNotebook().then((e=>e.session)),r=n.then((t=>(0,E.executeSilently)(t,e)));return this.trackNotebookCellPerceivedColdTime(t,n,r).catch(p.noop),r}async start(e){await this.startNotebook(e)}async interrupt(){var e;await Promise.all(this.eventHooks.map((e=>e("willInterrupt")))),(0,b.trackKernelResourceInformation)(this.resourceUri,{interruptKernel:!0}),this.restarting&&((0,c.traceInfo)(`Interrupt requested & currently restarting ${(this.resourceUri||this.notebookDocument.uri).toString()}`),await this.restarting.promise),(0,c.traceInfo)(`Interrupt requested ${(this.resourceUri||this.notebookDocument.uri).toString()}`),this.startCancellation.cancel();const t=this.kernelExecution.interrupt(null===(e=this._notebookPromise)||void 0===e?void 0:e.then((e=>e.session))),n=this.statusProvider.set(d.DataScience.interruptKernelStatus());let r;try{if((0,c.traceInfo)(`Interrupt requested & sent for ${(0,l.getDisplayPath)(this.notebookDocument.uri)} in notebookEditor.`),r=await t,r===_.InterruptResult.TimedOut){const e=d.DataScience.restartKernelAfterInterruptMessage(),t=d.DataScience.restartKernelMessageYes(),n=d.DataScience.restartKernelMessageNo();await this.appShell.showInformationMessage(e,{modal:!0},t,n)===t&&await this.restart()}}finally{n.dispose()}}async dispose(){if((0,c.traceInfoIfCI)(`Dispose Kernel ${(0,l.getDisplayPath)(this.notebookDocument.uri)}`),this._disposing=!0,this.disposingPromise)return this.disposingPromise;this._ignoreNotebookDisposedErrors=!0,this.startCancellation.cancel(),this.disposingPromise=(async()=>{(0,c.traceInfo)(`Dispose kernel ${(this.resourceUri||this.notebookDocument.uri).toString()}`),this.restarting=void 0;const e=[];e.push(this.kernelExecution.cancel()),this.notebook=this.notebook?this.notebook:this._notebookPromise?await this._notebookPromise:void 0,this._notebookPromise=void 0,this.notebook&&(e.push(this.notebook.session.dispose().catch(p.noop)),this.notebook=void 0),this._disposed=!0,this._onDisposed.fire(),this._onStatusChanged.fire("dead"),this.kernelExecution.dispose(),await Promise.all(e)})(),await this.disposingPromise}async restart(){var e;if(this.restarting)return this.restarting.promise;await Promise.all(this.eventHooks.map((e=>e("willRestart")))),(0,c.traceInfo)(`Restart requested ${this.notebookDocument.uri}`),this.startCancellation.cancel();const t=this.statusProvider.set(d.DataScience.restartingKernelStatus().format("")),n=y.KernelProgressReporter.createProgressReporter(this.resourceUri,d.DataScience.restartingKernelStatus().format(`: ${(0,E.getDisplayNameOrNameOfKernelConnection)(this.kernelConnectionMetadata)}`)),r=new h.StopWatch;try{await(this._notebookPromise?this.kernelExecution.restart(null===(e=this._notebookPromise)||void 0===e?void 0:e.then((e=>e.session))):this.start(new m.DisplayOptions(!1))),(0,c.traceInfoIfCI)(`Restarted ${(0,l.getDisplayPath)(this.notebookDocument.uri)}`),(0,b.sendKernelTelemetryEvent)(this.resourceUri,k.Telemetry.NotebookRestart,r.elapsedTime)}catch(e){(0,c.traceError)(`Restart failed ${(0,l.getDisplayPath)(this.notebookDocument.uri)}`,e),this._ignoreNotebookDisposedErrors=!0;const t=this.notebook;throw this.notebook=void 0,this._notebookPromise=void 0,this.restarting=void 0,(0,b.sendKernelTelemetryEvent)(this.resourceUri,k.Telemetry.NotebookRestart,r.elapsedTime,void 0,e),await(null==t?void 0:t.session.dispose().catch(p.noop)),this._ignoreNotebookDisposedErrors=!1,e}finally{t.dispose(),n.dispose()}await this.initializeAfterStart(this.notebook,this.notebookDocument),(0,c.traceInfoIfCI)(`Initialized after restart ${this.notebookDocument.uri}`),this._onRestarted.fire(),(0,c.traceInfoIfCI)(`Event fired after restart ${this.notebookDocument.uri}`)}async trackNotebookCellPerceivedColdTime(e,t,n){this.perceivedJupyterStartupTelemetryCaptured||await t&&(this.perceivedJupyterStartupTelemetryCaptured||(this.perceivedJupyterStartupTelemetryCaptured=!0,(0,S.sendTelemetryEvent)(k.Telemetry.PerceivedJupyterStartupNotebook,e.elapsedTime),n.finally((()=>(0,S.sendTelemetryEvent)(k.Telemetry.StartExecuteNotebookCellPerceivedCold,e.elapsedTime)))))}async startNotebook(e=new m.DisplayOptions(!1)){return this._startedAtLeastOnce=!0,(0,c.traceInfoIfCI)(`Start Notebook (options.disableUI=${e.disableUI}) for ${(0,l.getDisplayPath)(this.notebookDocument.uri)}.`),e.disableUI||(this.startupUI.disableUI=!1),e.onDidChangeDisableUI((()=>{!e.disableUI&&this.startupUI.disableUI&&(this.startupUI.disableUI=!1)})),this.startupUI.disableUI?this.startupUI.onDidChangeDisableUI((()=>{this.disposing||this.disposed||this.startupUI.disableUI||(0,b.initializeInteractiveOrNotebookTelemetryBasedOnUserAction)(this.resourceUri,this.kernelConnectionMetadata)}),this,this.disposables):(0,b.initializeInteractiveOrNotebookTelemetryBasedOnUserAction)(this.resourceUri,this.kernelConnectionMetadata),this.restarting&&await this.restarting.promise,this._notebookPromise||(this.startCancellation.token.isCancellationRequested&&((0,c.traceInfoIfCI)(`Create new cancellation token for ${(0,l.getDisplayPath)(this.notebookDocument.uri)}`),this.startCancellation=new o.CancellationTokenSource),this._notebookPromise=this.createNotebook(new h.StopWatch).catch((e=>{throw(0,c.traceInfoIfCI)(`Failed to create Notebook in Kernel.startNotebook for ${(0,l.getDisplayPath)(this.notebookDocument.uri)}`),this.startCancellation.cancel(),this._notebookPromise=void 0,e}))),this._notebookPromise}async createNotebook(e){let t=[];try{(0,c.traceInfo)(`Starting Notebook in kernel.ts id = ${this.kernelConnectionMetadata.id} for ${(0,l.getDisplayPath)(this.notebookDocument.uri)}`),this.createProgressIndicator(t),this.isKernelDead=!1,this._onStatusChanged.fire("starting");const n=await this.notebookProvider.createNotebook({document:this.notebookDocument,resource:this.resourceUri,ui:this.startupUI,kernelConnection:this.kernelConnectionMetadata,token:this.startCancellation.token});if(P.Cancellation.throwIfCanceled(this.startCancellation.token),!n)throw new Error("Kernel has not been started");return await this.initializeAfterStart(n,this.notebookDocument),(0,b.sendKernelTelemetryEvent)(this.resourceUri,k.Telemetry.PerceivedJupyterStartupNotebook,e.elapsedTime),this.notebook=n,this._onStarted.fire(),n}catch(e){if(this.startupUI.disableUI?(0,c.traceVerbose)(`failed to create INotebook in kernel, UI Disabled = ${this.startupUI.disableUI}`,e):(0,c.traceError)(`failed to create INotebook in kernel, UI Disabled = ${this.startupUI.disableUI}`,e),P.Cancellation.throwIfCanceled(this.startCancellation.token),e instanceof g.JupyterConnectError)throw e;const t=d.DataScience.sessionStartFailedWithKernel().format((0,E.getDisplayNameOrNameOfKernelConnection)(this.kernelConnectionMetadata));throw s.WrappedError.from(t+" "+("message"in e?e.message:e.toString()),e)}finally{(0,a.disposeAllDisposables)(t)}}createProgressIndicator(e){const t=y.KernelProgressReporter.createProgressReporter(this.resourceUri,d.DataScience.connectingToKernel().format((0,E.getDisplayNameOrNameOfKernelConnection)(this.kernelConnectionMetadata)),this.startupUI.disableUI);e.push(t),this.startupUI.disableUI&&this.startupUI.onDidChangeDisableUI((()=>{this.disposing||this.disposed||this.startupUI.disableUI||t.show&&t.show()}),this,e)}async initializeAfterStart(e,t){if((0,c.traceVerbose)(`Started running kernel initialization for ${(0,l.getDisplayPath)(this.notebookDocument.uri)}`),e){if(!this.hookedNotebookForEvents.has(e)){this.hookedNotebookForEvents.add(e),e.session.kernelSocket.subscribe(this._kernelSocket),e.session.onDidDispose((()=>{if((0,c.traceInfoIfCI)(`Kernel got disposed as a result of notebook.onDisposed ${(this.resourceUri||this.notebookDocument.uri).toString()}`),!this._ignoreNotebookDisposedErrors){(0,c.traceInfo)(`Kernel got disposed as a result of notebook.onDisposed ${(this.resourceUri||this.notebookDocument.uri).toString()} & _ignoreNotebookDisposedErrors = false.`);const t=this.notebook===e;this._notebookPromise=void 0,this.notebook=void 0,t&&(this.isKernelDead=!0,this._onStatusChanged.fire("dead"))}}));const t=e=>{(0,c.traceVerbose)(`IKernel Status change to ${e}`),this._onStatusChanged.fire(e)};this.disposables.push(e.session.onSessionStatusChanged(t))}if((0,E.isPythonKernelConnection)(this.kernelConnectionMetadata)&&(e.session.registerCommTarget(k.Identifiers.DefaultCommTarget,p.noop),this.requestEmptyCompletions(),(0,T.isLocalConnection)(this.kernelConnectionMetadata)&&await(0,E.sendTelemetryForPythonKernelExecutable)(this,this.resourceUri,this.kernelConnectionMetadata,this.pythonExecutionFactory)),"connectToLiveKernel"!==this.kernelConnectionMetadata.kind){const n=await this.gatherInternalStartupCode(t);await this.executeSilently(e,n,{traceErrors:!0,traceErrorsMessage:"Error executing jupyter extension internal startup code",telemetryName:k.Telemetry.KernelStartupCodeFailure}),await this.executeSilently(e,this.getUserStartupCommands(),{traceErrors:!0,traceErrorsMessage:"Error executing user defined startup code",telemetryName:k.Telemetry.UserStartupCodeFailure})}try{(0,c.traceVerbose)("Requesting Kernel info");const t=[],n={banner:"",help_links:[],implementation:"",implementation_version:"",language_info:{name:"",version:""},protocol_version:"",status:"ok"};t.push(e.session.requestKernelInfo().then((e=>null==e?void 0:e.content))),"connectToLiveKernel"===this.kernelConnectionMetadata.kind&&t.push((0,u.sleep)(5e3).then((()=>n)));const r=await Promise.race(t);r===n?(0,c.traceWarning)("Failed to Kernel info in a timely manner, defaulting to empty info!"):(0,c.traceVerbose)("Got Kernel info"),this._info=r}catch(e){(0,c.traceWarning)("Failed to request KernelInfo",e)}"connectToLiveKernel"!==this.kernelConnectionMetadata.kind&&((0,c.traceVerbose)("End running kernel initialization, now waiting for idle"),await e.session.waitForIdle(this.launchTimeout),(0,c.traceVerbose)("End running kernel initialization, session is idle"))}else(0,c.traceVerbose)("Not running kernel initialization")}async gatherInternalStartupCode(e){var t;const n=[];if((0,E.isPythonKernelConnection)(this.kernelConnectionMetadata)){const[i,o]=await Promise.all([this.getUpdateWorkingDirectoryAndPathCode(this.resourceUri),this.getDebugCellHook(e)]);n.push(...o),(0,T.isLocalConnection)(this.kernelConnectionMetadata)&&n.push(...k.CodeSnippets.AppendSitePackages.splitLines({trim:!1})),n.push(...i);const s=null===(t=this.resourceUri)||void 0===t?void 0:t.fsPath;s&&n.push(`__vsc_ipynb_file__ = "${s.replace(/\\/g,"\\\\")}"`),n.push(k.CodeSnippets.DisableJedi),n.push(...(r=this.getMatplotLibInitializeCode(),r&&0!==r.length?((r=r.map((e=>` ${e}`))).unshift("try:"),r.push("except:"," print('Failed to initialize matplotlib startup code. Matplotlib might be missing.')"),r):r))}var r;return n}requestEmptyCompletions(){var e;null===(e=this.session)||void 0===e||e.requestComplete({code:"__file__.",cursor_pos:9})}getMatplotLibInitializeCode(){const e=[],t=this.configService.getSettings(this.resourceUri);if(t&&t.themeMatplotlibPlots){(0,c.traceInfoIfCI)(`Initialize config for plots for ${(this.resourceUri||this.notebookDocument.uri).toString()}`);const n=k.CodeSnippets.MatplotLibInit;(0,c.traceInfo)(`Initialize matplotlib for ${(this.resourceUri||this.notebookDocument.uri).toString()}`),e.push(...n.splitLines({trim:!1}));const r=this.appShell.activeColorTheme.kind===o.ColorThemeKind.Dark;t.ignoreVscodeTheme||e.push(r?"matplotlib.style.use('dark_background')":`matplotlib.rcParams.update(${k.Identifiers.MatplotLibDefaultParams})`)}return t.generateSVGPlots&&(e.push(...k.CodeSnippets.AppendSVGFigureFormat.splitLines({trim:!1})),(0,c.traceInfo)("Add SVG to matplotlib figure formats")),e}async getDebugCellHook(e){if(e.notebookType===v.InteractiveWindowView){if(await this.fs.localFileExists(f.AddRunCellHook.ScriptPath))return(await this.fs.readLocalFile(f.AddRunCellHook.ScriptPath)).splitLines({trim:!1});(0,c.traceError)(`Cannot run non-existant script file: ${f.AddRunCellHook.ScriptPath}`)}return[]}getUserStartupCommands(){let e=this.configService.getSettings(this.resourceUri).runStartupCommands;return Array.isArray(e)&&(e=e.join("\n")),e?e.replace(/\\n/g,"\n").splitLines({trim:!1}):[]}async getUpdateWorkingDirectoryAndPathCode(e){if(((0,T.isLocalConnection)(this.kernelConnectionMetadata)||(0,T.isLocalHostConnection)(this.kernelConnectionMetadata))&&"connectToLiveKernel"!==this.kernelConnectionMetadata.kind){let t=await(0,w.calculateWorkingDirectory)(this.configService,this.workspaceService,this.fs,e);if(t&&await this.fs.localDirectoryExists(t))return(0,c.traceInfo)("UpdateWorkingDirectoryAndPath in Kernel"),this.getChangeDirectoryCode(t);if(e&&await this.fs.localFileExists(e.fsPath)&&(t=(0,x.expandWorkingDir)(t,e.fsPath,this.workspaceService),t&&await this.fs.localDirectoryExists(t)))return(0,c.traceInfo)("UpdateWorkingDirectoryAndPath in Kernel"),this.getChangeDirectoryCode(t)}return[]}getChangeDirectoryCode(e){return((0,T.isLocalConnection)(this.kernelConnectionMetadata)||(0,T.isLocalHostConnection)(this.kernelConnectionMetadata))&&(0,E.isPythonKernelConnection)(this.kernelConnectionMetadata)?k.CodeSnippets.UpdateCWDAndPath.format(e).splitLines({trim:!1}):[]}async executeSilently(e,t,n){e&&0!==t.join("").trim().length?await(0,E.executeSilently)(e.session,t.join("\n"),n):(0,c.traceVerbose)(`Not executing startup notebook: ${e?"Object":"undefined"}, code: ${t}`)}},t.getPlainTextOrStreamOutput=function(e){if(e.length>0){const t=e[0].data;if(t&&t.hasOwnProperty("text/plain"))return(0,C.concatMultilineString)(t["text/plain"]);if("stream"===e[0].output_type){const t=e[0];return(0,C.concatMultilineString)(t.text)}}}},45028:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelCommandListener=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(55170),l=n(46318),u=n(71733),d=n(35952),p=n(24453),h=n(32417),f=n(5448),m=n(29474),g=n(97045),v=n(83474),y=n(93828),b=n(31092),_=n(92513),w=n(43367);let S=class{constructor(e,t,n,r,i,o,s,a,c){this.statusProvider=e,this.disposableRegistry=t,this.applicationShell=n,this.kernelProvider=r,this.interactiveWindowProvider=i,this.configurationService=o,this.serviceContainer=s,this.notebookControllerManager=a,this.errorHandler=c,this.kernelInterruptedDontAskToRestart=!1,this.kernelsStartedSuccessfully=new WeakSet,this.kernelRestartProgress=new WeakMap,this.pendingRestartInterrupt=new WeakMap}register(e){this.disposableRegistry.push(e.registerCommand(v.Commands.NotebookEditorInterruptKernel,(e=>{var t;e&&"notebookEditor"in e?this.interruptKernel(null===(t=null==e?void 0:e.notebookEditor)||void 0===t?void 0:t.notebookUri):this.interruptKernel(e)}))),this.disposableRegistry.push(e.registerCommand(v.Commands.NotebookEditorRestartKernel,(e=>{var t;e&&"notebookEditor"in e?this.restartKernel(null===(t=null==e?void 0:e.notebookEditor)||void 0===t?void 0:t.notebookUri):this.restartKernel(e)}))),this.disposableRegistry.push(e.registerCommand(v.Commands.InterruptKernel,(e=>{var t;return this.interruptKernel(null===(t=null==e?void 0:e.notebookEditor)||void 0===t?void 0:t.notebookUri)}))),this.disposableRegistry.push(e.registerCommand(v.Commands.RestartKernel,(e=>{var t;return this.restartKernel(null===(t=null==e?void 0:e.notebookEditor)||void 0===t?void 0:t.notebookUri)}))),this.disposableRegistry.push(this.kernelProvider.onKernelStatusChanged(this.onKernelStatusChanged,this)),this.disposableRegistry.push(this.kernelProvider.onDidStartKernel(this.onDidStartKernel,this)),this.disposableRegistry.push(this.kernelProvider.onDidDisposeKernel((e=>{var t;null===(t=this.kernelRestartProgress.get(e))||void 0===t||t.dispose(),this.kernelRestartProgress.delete(e)}),this)),this.disposableRegistry.push(this.kernelProvider.onDidRestartKernel((e=>{var t;null===(t=this.kernelRestartProgress.get(e))||void 0===t||t.dispose(),this.kernelRestartProgress.delete(e)}),this))}async interruptKernel(e){var t,n,r,i,o,a;const c=null!==(i=null!==(n=null!=e?e:null===(t=s.window.activeNotebookEditor)||void 0===t?void 0:t.document.uri)&&void 0!==n?n:null===(r=this.interactiveWindowProvider.activeWindow)||void 0===r?void 0:r.notebookUri)&&void 0!==i?i:(null===(o=s.window.activeTextEditor)||void 0===o?void 0:o.document.uri)&&(null===(a=this.interactiveWindowProvider.get(s.window.activeTextEditor.document.uri))||void 0===a?void 0:a.notebookUri),u=s.workspace.notebookDocuments.find((e=>e.uri.toString()===(null==c?void 0:c.toString())));if(void 0===u)return;const d=this.kernelProvider.get(u);d?await this.wrapKernelMethod("interrupt",d):(0,l.traceInfo)("Interrupt requested & no kernel.")}async restartKernel(e){var t,n,r,i,o,a;const c=null!==(i=null!==(n=null!=e?e:null===(t=s.window.activeNotebookEditor)||void 0===t?void 0:t.document.uri)&&void 0!==n?n:null===(r=this.interactiveWindowProvider.activeWindow)||void 0===r?void 0:r.notebookUri)&&void 0!==i?i:(null===(o=s.window.activeTextEditor)||void 0===o?void 0:o.document.uri)&&(null===(a=this.interactiveWindowProvider.get(s.window.activeTextEditor.document.uri))||void 0===a?void 0:a.notebookUri),l=s.workspace.notebookDocuments.find((e=>e.uri.toString()===(null==c?void 0:c.toString())));if(void 0===l)return;(0,g.sendTelemetryEvent)(v.Telemetry.RestartKernelCommand);const u=this.kernelProvider.get(l);if(u)if((0,h.trackKernelResourceInformation)(u.resourceUri,{restartKernel:!0}),await this.shouldAskForRestart(l.uri)){const e=d.DataScience.restartKernelMessage(),t=d.DataScience.restartKernelMessageYes(),n=d.DataScience.restartKernelMessageDontAskAgain(),r=d.DataScience.restartKernelMessageNo(),i=await this.applicationShell.showInformationMessage(e,{modal:!0},t,n,r);i===n?(await this.disableAskForRestart(l.uri),this.wrapKernelMethod("restart",u)):i===t&&this.wrapKernelMethod("restart",u)}else this.wrapKernelMethod("restart",u)}async wrapKernelMethod(e,t){const n=this.pendingRestartInterrupt.get(t);if(n)return n;const r=(async()=>{const n=t.pendingCells[0],r=this.notebookControllerManager.getSelectedNotebookController(t.notebookDocument);try{await(0,y.wrapKernelMethod)(r,e,this.serviceContainer,t.resourceUri,t.notebookDocument)}catch(r){n?(0,c.displayErrorsInCell)(n,t.controller,await this.errorHandler.getErrorMessageForDisplayInCell(r,e),!1):this.applicationShell.showErrorMessage(r.toString())}})();return r.finally((()=>{this.pendingRestartInterrupt.get(t)===r&&this.pendingRestartInterrupt.delete(t)})),this.pendingRestartInterrupt.set(t,r),r}async shouldAskForRestart(e){if(this.kernelInterruptedDontAskToRestart)return!1;const t=this.configurationService.getSettings(e);return t&&!0===t.askForKernelRestart}async disableAskForRestart(e){this.configurationService.getSettings(e)&&this.configurationService.updateSetting("askForKernelRestart",!1,void 0,s.ConfigurationTarget.Global).ignoreErrors()}onDidStartKernel(e){this.kernelsStartedSuccessfully.add(e)}onKernelStatusChanged({kernel:e}){var t;if(this.kernelsStartedSuccessfully.has(e))if((null==e?void 0:e.session)&&(null==e?void 0:e.session)instanceof _.RawJupyterSession&&"dead"===e.status&&!e.disposed&&!e.disposing&&this.applicationShell.showErrorMessage(d.DataScience.kernelDiedWithoutError().format((0,y.getDisplayNameOrNameOfKernelConnection)(e.kernelConnectionMetadata))),"autorestarting"===e.status&&e.session&&e.session instanceof b.JupyterSession){const t=this.statusProvider.set(d.DataScience.restartingKernelStatus().format(""));this.kernelRestartProgress.set(e,t)}else"starting"!==e.status&&"busy"!==e.status&&"unknown"!==e.status&&(null===(t=this.kernelRestartProgress.get(e))||void 0===t||t.dispose(),this.kernelRestartProgress.delete(e))}};S=r([(0,o.injectable)(),i(0,(0,o.inject)(f.IStatusProvider)),i(1,(0,o.inject)(u.IDisposableRegistry)),i(2,(0,o.inject)(a.IApplicationShell)),i(3,(0,o.inject)(w.IKernelProvider)),i(4,(0,o.inject)(f.IInteractiveWindowProvider)),i(5,(0,o.inject)(u.IConfigurationService)),i(6,(0,o.inject)(m.IServiceContainer)),i(7,(0,o.inject)(p.INotebookControllerManager)),i(8,(0,o.inject)(f.IDataScienceErrorHandler))],S),t.KernelCommandListener=S},12109:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KernelConnectionWrapper=void 0;const r=n(4016),i=n(66828);t.KernelConnectionWrapper=class{constructor(e,t){this.kernel=e,this.statusChanged=new r.Signal(this),this.connectionStatusChanged=new r.Signal(this),this.iopubMessage=new r.Signal(this),this.unhandledMessage=new r.Signal(this),this.anyMessage=new r.Signal(this),this.disposed=new r.Signal(this);const n=()=>{this.statusChanged.emit(e.status),"dead"!==e.status||e.disposed||e.disposing||this.connectionStatusChanged.emit("disconnected")};e.onDisposed((()=>{n(),this.disposed.emit()}),this,t),e.onStarted(n,this,t),e.onRestarted(n,this,t),e.onStatusChanged(n,this,t),this._previousKernelConnection=e.session.kernel,this.startHandleKernelMessages(e.session.kernel),t.push(new i.Disposable((()=>{this.possibleKernelConnection&&this.stopHandlingKernelMessages(this.possibleKernelConnection)})))}get serverSettings(){return(this.possibleKernelConnection||this._previousKernelConnection).serverSettings}get possibleKernelConnection(){var e,t;return(null===(e=this.kernel.session)||void 0===e?void 0:e.kernel)===this._kernelConnection?this._kernelConnection:(this.stopHandlingKernelMessages(this._kernelConnection),(null===(t=this.kernel.session)||void 0===t?void 0:t.kernel)?(this.startHandleKernelMessages(this.kernel.session.kernel),this._kernelConnection):void 0)}getKernelConnection(){if(!this.possibleKernelConnection)throw new Error(`Kernel connection is not available, status = ${this.status}, connection = ${this.connectionStatus}`);return this.possibleKernelConnection}get id(){return(this.possibleKernelConnection||this._previousKernelConnection).id}get name(){return(this.possibleKernelConnection||this._previousKernelConnection).name}get isDisposed(){return this.kernel.disposed}get model(){return(this.possibleKernelConnection||this._previousKernelConnection).model}get username(){return(this.possibleKernelConnection||this._previousKernelConnection).username}get clientId(){return(this.possibleKernelConnection||this._previousKernelConnection).clientId}get status(){var e;return(null===(e=this.possibleKernelConnection)||void 0===e?void 0:e.status)||"dead"}get connectionStatus(){var e;return(null===(e=this.possibleKernelConnection)||void 0===e?void 0:e.connectionStatus)||"disconnected"}get info(){return(this.possibleKernelConnection||this._previousKernelConnection).info}get spec(){return(this.possibleKernelConnection||this._previousKernelConnection).spec}get handleComms(){return(this.possibleKernelConnection||this._previousKernelConnection).handleComms}sendShellMessage(e,t,n){return this.getKernelConnection().sendShellMessage(e,t,n)}sendControlMessage(e,t,n){return this.getKernelConnection().sendControlMessage(e,t,n)}reconnect(){return this.getKernelConnection().reconnect()}requestKernelInfo(){return this.getKernelConnection().requestKernelInfo()}requestComplete(e){return this.getKernelConnection().requestComplete(e)}requestInspect(e){return this.getKernelConnection().requestInspect(e)}requestHistory(e){return this.getKernelConnection().requestHistory(e)}requestExecute(e,t,n){return this.getKernelConnection().requestExecute(e,t,n)}requestDebug(e,t){return this.getKernelConnection().requestDebug(e,t)}requestIsComplete(e){return this.getKernelConnection().requestIsComplete(e)}requestCommInfo(e){return this.getKernelConnection().requestCommInfo(e)}sendInputReply(e){return this.getKernelConnection().sendInputReply(e)}createComm(e,t){return this.getKernelConnection().createComm(e,t)}hasComm(e){return this.getKernelConnection().hasComm(e)}registerCommTarget(e,t){return this.getKernelConnection().registerCommTarget(e,t)}removeCommTarget(e,t){return this.getKernelConnection().removeCommTarget(e,t)}registerMessageHook(e,t){return this.getKernelConnection().registerMessageHook(e,t)}removeMessageHook(e,t){return this.getKernelConnection().removeMessageHook(e,t)}async shutdown(){var e;"startUsingRemoteKernelSpec"!==this.kernel.kernelConnectionMetadata.kind&&"connectToLiveKernel"!==this.kernel.kernelConnectionMetadata.kind||await(null===(e=this.kernel.session)||void 0===e?void 0:e.shutdown()),await this.kernel.dispose()}clone(e){throw new Error("Method not implemented.")}dispose(){this.kernel.dispose()}async interrupt(){var e,t;if(this.stopHandlingKernelMessages(this.possibleKernelConnection),await this.kernel.interrupt(),!(null===(e=this.kernel.session)||void 0===e?void 0:e.kernel))throw new Error("Restart failed");this.startHandleKernelMessages(null===(t=this.kernel.session)||void 0===t?void 0:t.kernel)}async restart(){var e,t;if(this.possibleKernelConnection&&this.stopHandlingKernelMessages(this.possibleKernelConnection),await this.kernel.restart(),!(null===(e=this.kernel.session)||void 0===e?void 0:e.kernel))throw new Error("Restart failed");this.startHandleKernelMessages(null===(t=this.kernel.session)||void 0===t?void 0:t.kernel)}startHandleKernelMessages(e){this._kernelConnection=e,e.anyMessage.connect(this.onAnyMessage,this),e.iopubMessage.connect(this.onIOPubMessage,this),e.unhandledMessage.connect(this.onUnhandledMessage,this)}stopHandlingKernelMessages(e){e.anyMessage.disconnect(this.onAnyMessage,this),e.iopubMessage.disconnect(this.onIOPubMessage,this),e.unhandledMessage.disconnect(this.onUnhandledMessage,this)}onAnyMessage(e,t){e===this.possibleKernelConnection&&this.anyMessage.emit(t)}onIOPubMessage(e,t){e===this.possibleKernelConnection&&this.iopubMessage.emit(t)}onUnhandledMessage(e,t){e===this.possibleKernelConnection&&this.unhandledMessage.emit(t)}}},59633:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelDependencyService=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(33149),l=n(46318),u=n(29140),d=n(71733),p=n(35952),h=n(72858),f=n(51129),m=n(5448),g=n(29474),v=n(36462),y=n(86909),b=n(21687),_=n(97045),w=n(70403),S=n(83474),C=n(17927),k=n(13982),E=n(29299),x=n(95063);let T=class{constructor(e,t,n,r,i,o){this.appShell=e,this.installer=t,this.memento=n,this.isCodeSpace=r,this.rawSupport=i,this.serviceContainer=o,this.installPromises=new Map}async installMissingDependencies(e,t,n,r,i){var o;if((0,l.traceInfo)(`installMissingDependencies ${(0,u.getDisplayPath)(null===(o=t.interpreter)||void 0===o?void 0:o.path)}, ui.disabled=${n.disableUI} for resource ${(0,u.getDisplayPath)(e)}`),"connectToLiveKernel"===t.kind||"startUsingRemoteKernelSpec"===t.kind||void 0===t.interpreter)return m.KernelInterpreterDependencyResponse.ok;if(await f.KernelProgressReporter.wrapAndReportProgress(e,p.DataScience.validatingKernelDependencies(),(()=>this.areDependenciesInstalled(t,r,i))))return m.KernelInterpreterDependencyResponse.ok;if(null==r?void 0:r.isCancellationRequested)return m.KernelInterpreterDependencyResponse.cancel;let a=this.installPromises.get(t.interpreter.path);if(!a){const i=new s.CancellationTokenSource,o=r.onCancellationRequested((()=>{i.cancel(),o.dispose()}));a=f.KernelProgressReporter.wrapAndReportProgress(e,p.DataScience.installingMissingDependencies(),(()=>this.runInstaller(e,t.interpreter,n,i))),a.finally((()=>{o.dispose(),i.dispose()})).catch(x.noop),this.installPromises.set(t.interpreter.path,a)}let c=m.KernelInterpreterDependencyResponse.failed;try{c=await a,r.isCancellationRequested&&(c=m.KernelInterpreterDependencyResponse.cancel)}catch(e){(0,l.traceInfoIfCI)("Failed to install kernel dependency",e),c=m.KernelInterpreterDependencyResponse.failed}finally{this.installPromises.delete(t.interpreter.path)}return c}async areDependenciesInstalled(e,t,n){if("connectToLiveKernel"===e.kind||"startUsingRemoteKernelSpec"===e.kind||void 0===e.interpreter)return!0;if(!n&&this.rawSupport.isSupported&&(0,C.isModulePresentInEnvironmentCache)(this.memento,E.Product.ipykernel,e.interpreter))return(0,l.traceInfo)(`IPyKernel found previously in this environment ${(0,u.getDisplayPath)(e.interpreter.path)}`),!0;const r=this.installer.isInstalled(E.Product.ipykernel,e.interpreter).then((e=>!0===e));return r.then((t=>{t&&(0,C.trackPackageInstalledIntoInterpreter)(this.memento,E.Product.ipykernel,e.interpreter)})),Promise.race([r,(0,c.createPromiseFromCancellation)({token:t,defaultValue:!1,cancelAction:"resolve"})])}async runInstaller(e,t,n,r){if((0,l.traceInfoIfCI)(`Run Installer for ${(0,u.getDisplayPath)(e)} ui.disableUI=${n.disableUI}, cancelTokenSource.token.isCancellationRequested=${r.token.isCancellationRequested}`),n.disableUI)return m.KernelInterpreterDependencyResponse.uiHidden;const[i,o]=await Promise.all([(0,C.isModulePresentInEnvironment)(this.memento,E.Product.ipykernel,t),t.envType===b.EnvironmentType.Conda?void 0:await this.installer.isInstalled(E.Product.pip,t)]);if(r.token.isCancellationRequested)return m.KernelInterpreterDependencyResponse.cancel;const s=i?p.DataScience.libraryRequiredToLaunchJupyterKernelNotInstalledInterpreterAndRequiresUpdate():p.DataScience.libraryRequiredToLaunchJupyterKernelNotInstalledInterpreter(),a=!1===o?[E.Product.ipykernel,E.Product.pip]:[E.Product.ipykernel],d=s.format(t.displayName||t.path,a.map((e=>k.ProductNames.get(e))).join(` ${p.Common.and()} `)),f=a.map((e=>k.ProductNames.get(e))).join(", "),g=e?(0,h.getResourceType)(e):void 0,v=e?(0,w.getTelemetrySafeHashedString)(e.toString()):void 0;(0,_.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:"displayed",moduleName:f,resourceType:g,resourceHash:v,pythonEnvType:t.envType});const y=(0,c.createPromiseFromCancellation)({cancelAction:"resolve",defaultValue:void 0,token:r.token}),x=p.DataScience.selectKernel(),T=e?[p.Common.install(),x]:[p.Common.install()];try{this.isCodeSpace||(0,_.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:"prompted",moduleName:f,resourceType:g,resourceHash:v,pythonEnvType:t.envType}),(0,l.traceInfoIfCI)(`Prompting user for install (this.isCodeSpace=${this.isCodeSpace}).`);const e=this.isCodeSpace?p.Common.install():await Promise.race([this.appShell.showInformationMessage(d,{modal:!0},...T),y]);if(r.token.isCancellationRequested)return(0,_.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:"dismissed",moduleName:f,resourceType:g,resourceHash:v,pythonEnvType:t.envType}),m.KernelInterpreterDependencyResponse.cancel;if(e===x)return(0,_.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:"differentKernel",moduleName:f,resourceType:g,resourceHash:v,pythonEnvType:t.envType}),m.KernelInterpreterDependencyResponse.selectDifferentKernel;if(e===p.Common.install()){(0,_.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:"install",moduleName:f,resourceType:g,resourceHash:v,pythonEnvType:t.envType});const e=(0,c.createPromiseFromCancellation)({cancelAction:"resolve",defaultValue:E.InstallerResponse.Cancelled,token:r.token}),n=await Promise.race([this.installer.install(E.Product.ipykernel,t,r,!0===i,!1===o),e]);if(n===E.InstallerResponse.Installed)return(0,_.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:"installed",moduleName:f,resourceType:g,resourceHash:v,pythonEnvType:t.envType}),m.KernelInterpreterDependencyResponse.ok;if(n===E.InstallerResponse.Ignore)return(0,_.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:"failed",moduleName:f,resourceType:g,resourceHash:v,pythonEnvType:t.envType}),m.KernelInterpreterDependencyResponse.failed}return(0,_.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:"dismissed",moduleName:f,resourceType:g,resourceHash:v,pythonEnvType:t.envType}),m.KernelInterpreterDependencyResponse.cancel}catch(e){throw(0,l.traceError)(`Failed to install ${f}`,e),(0,_.sendTelemetryEvent)(S.Telemetry.PythonModuleInstall,void 0,{action:"error",moduleName:f,resourceType:g,resourceHash:v,pythonEnvType:t.envType}),e}}};r([v.traceDecorators.verbose("Install Missing Dependencies"),i(3,(0,y.ignoreLogging)())],T.prototype,"installMissingDependencies",null),r([v.traceDecorators.verbose("Are Dependencies Installed"),i(0,(0,y.logValue)("id"))],T.prototype,"areDependenciesInstalled",null),T=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IApplicationShell)),i(1,(0,o.inject)(E.IInstaller)),i(2,(0,o.inject)(d.IMemento)),i(2,(0,o.named)(d.GLOBAL_MEMENTO)),i(3,(0,o.inject)(d.IsCodeSpace)),i(4,(0,o.inject)(m.IRawNotebookSupportedService)),i(5,(0,o.inject)(g.IServiceContainer))],T),t.KernelDependencyService=T},39295:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelProvider=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(46318),l=n(29140),u=n(60593),d=n(12698),p=n(71733),h=n(95063),f=n(48734),m=n(73913),g=n(5448),v=n(19865),y=n(92201);let b=class{constructor(e,t,n,r,i,o,a,c,l,u,d,p){this.asyncDisposables=e,this.disposables=t,this.notebookProvider=n,this.configService=r,this.appShell=i,this.fs=o,this.outputTracker=a,this.workspaceService=c,this.cellHashProviderFactory=l,this.notebook=u,this.pythonExecutionFactory=d,this.statusProvider=p,this.kernelsByNotebook=new WeakMap,this.pendingDisposables=new Set,this._onDidRestartKernel=new s.EventEmitter,this._onDidStartKernel=new s.EventEmitter,this._onDidDisposeKernel=new s.EventEmitter,this._onKernelStatusChanged=new s.EventEmitter,this.onKernelStatusChanged=this._onKernelStatusChanged.event,this.asyncDisposables.push(this),this.notebook.onDidCloseNotebookDocument(this.disposeOldKernel,this,t)}get kernels(){const e=new Set;return this.notebook.notebookDocuments.forEach((t=>{const n=this.get(t);n&&e.add(n)})),Array.from(e)}get onDidDisposeKernel(){return this._onDidDisposeKernel.event}get onDidRestartKernel(){return this._onDidRestartKernel.event}get onDidStartKernel(){return this._onDidStartKernel.event}get(e){var t;return null===(t=this.kernelsByNotebook.get(e))||void 0===t?void 0:t.kernel}async dispose(){(0,c.traceInfoIfCI)("Disposing all kernels from kernel provider");const e=Array.from(this.pendingDisposables.values());this.pendingDisposables.clear(),await Promise.all(e),await Promise.all(this.kernels.map((e=>e.dispose()))),this._onDidDisposeKernel.dispose(),this._onDidRestartKernel.dispose(),this._onKernelStatusChanged.dispose()}getOrCreate(e,t){const n=this.kernelsByNotebook.get(e);if(n&&n.options.metadata.id===t.metadata.id)return n.kernel;const r=e.notebookType===m.InteractiveWindowView?t.resourceUri:e.uri;this.disposeOldKernel(e);const i=this.configService.getSettings(r).jupyterLaunchTimeout,o=this.configService.getSettings(r).jupyterInterruptTimeout,s=new y.Kernel(e,r,t.metadata,this.notebookProvider,this.disposables,i,o,this.appShell,this.fs,t.controller,this.configService,this.outputTracker,this.workspaceService,this.cellHashProviderFactory,this.pythonExecutionFactory,this.statusProvider);return s.onRestarted((()=>this._onDidRestartKernel.fire(s)),this,this.disposables),s.onDisposed((()=>this._onDidDisposeKernel.fire(s)),this,this.disposables),s.onStarted((()=>this._onDidStartKernel.fire(s)),this,this.disposables),s.onStatusChanged((e=>this._onKernelStatusChanged.fire({kernel:s,status:e})),this,this.disposables),this.asyncDisposables.push(s),this.kernelsByNotebook.set(e,{options:t,kernel:s}),this.deleteMappingIfKernelIsDisposed(e,s),s}deleteMappingIfKernelIsDisposed(e,t){t.onDisposed((()=>{var n;(null===(n=this.kernelsByNotebook.get(e))||void 0===n?void 0:n.kernel)===t&&(this.kernelsByNotebook.delete(e),(0,c.traceVerbose)(`Kernel got disposed, hence there is no longer a kernel associated with ${(0,l.getDisplayPath)(e.uri)}`,(0,l.getDisplayPath)(t.notebookDocument.uri))),this.pendingDisposables.delete(t)}),this,this.disposables)}disposeOldKernel(e){(0,c.traceInfoIfCI)(`Disposing kernel associated with ${(0,l.getDisplayPath)(e.uri)}, isClosed=${e.isClosed}`);const t=this.kernelsByNotebook.get(e);t&&(this.pendingDisposables.add(t.kernel),t.kernel.dispose().catch((e=>(0,c.traceWarning)("Failed to dispose old kernel",e))).finally((()=>this.pendingDisposables.delete(t.kernel))).catch(h.noop)),this.kernelsByNotebook.delete(e)}};b=r([(0,o.injectable)(),i(0,(0,o.inject)(p.IAsyncDisposableRegistry)),i(1,(0,o.inject)(p.IDisposableRegistry)),i(2,(0,o.inject)(g.INotebookProvider)),i(3,(0,o.inject)(p.IConfigurationService)),i(4,(0,o.inject)(a.IApplicationShell)),i(5,(0,o.inject)(u.IFileSystem)),i(6,(0,o.inject)(v.CellOutputDisplayIdTracker)),i(7,(0,o.inject)(a.IWorkspaceService)),i(8,(0,o.inject)(f.CellHashProviderFactory)),i(9,(0,o.inject)(a.IVSCodeNotebook)),i(10,(0,o.inject)(d.IPythonExecutionFactory)),i(11,(0,o.inject)(g.IStatusProvider))],b),t.KernelProvider=b},78985:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterPaths=t.baseKernelPath=void 0;const o=n(86700),s=n(71017),a=n(60593),c=n(71733),l=n(75213),u=n(72858),d=n(36462),p=s.join("AppData","Roaming","jupyter","kernels"),h=s.join(".local","share","jupyter","kernels"),f=s.join("Library","Jupyter","kernels");t.baseKernelPath=s.join("share","jupyter","kernels");const m="CACHE_KEY_FOR_JUPYTER_KERNELSPEC_ROOT_PATH.",g="CACHE_KEY_FOR_JUPYTER_PATHS_.";let v=class{constructor(e,t,n,r,i,o,s){this.platformService=e,this.pathUtils=t,this.envVarsProvider=n,this.globalState=i,this.fs=o,this.context=s,this.envVarsProvider.onDidEnvironmentVariablesChange((()=>{this.cachedJupyterPaths=void 0}),this,r)}async getKernelSpecTempRegistrationFolder(){const e=s.join(this.context.extensionUri.fsPath,"temp","jupyter","kernels");return await this.fs.ensureLocalDir(e),e}async getKernelSpecRootPath(){return this.cachedKernelSpecRootPath=this.cachedKernelSpecRootPath||(async()=>this.platformService.isWindows?(0,u.tryGetRealPath)(s.join(this.pathUtils.home,p)):this.platformService.isMac?s.join(this.pathUtils.home,f):s.join(this.pathUtils.home,h))(),this.cachedKernelSpecRootPath.then((e=>{e&&this.globalState.update(m,e)})),this.globalState.get(m)?this.globalState.get(m):this.cachedKernelSpecRootPath}async getKernelSpecRootPaths(e){const t=new Set(await this.getJupyterPathPaths(e));if(this.platformService.isWindows){const e=await this.getKernelSpecRootPath();e&&t.add(e),process.env.ALLUSERSPROFILE&&t.add(s.join(process.env.ALLUSERSPROFILE,"jupyter","kernels"))}else{const e=this.platformService.isMac?f:h;t.add(s.join("/","usr","share","jupyter","kernels")),t.add(s.join("/","usr","local","share","jupyter","kernels")),t.add(s.join(this.pathUtils.home,e))}return Array.from(t)}async getJupyterPathPaths(e){return this.cachedJupyterPaths=this.cachedJupyterPaths||(async()=>{const t=new Set,n=await this.envVarsProvider.getEnvironmentVariables();if(null==e?void 0:e.isCancellationRequested)return[];const r=n.JUPYTER_PATH?n.JUPYTER_PATH.split(s.delimiter).map((e=>s.join(e,"kernels"))):[];return r.length>0&&r.forEach((async e=>{const n=await(0,u.tryGetRealPath)(e);n&&t.add(n)})),Array.from(t)})(),this.cachedJupyterPaths.then((e=>{e.length>0&&this.globalState.update(g,e)})),this.globalState.get(g,[]).length>0?this.globalState.get(g,[]):this.cachedJupyterPaths}};r([d.traceDecorators.verbose("Getting Jupyter KernelSpec Root Path")],v.prototype,"getKernelSpecRootPath",null),r([d.traceDecorators.verbose("Get Kernelspec root path")],v.prototype,"getKernelSpecRootPaths",null),r([d.traceDecorators.verbose("Get Jupyter Paths")],v.prototype,"getJupyterPathPaths",null),v=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IPlatformService)),i(1,(0,o.inject)(c.IPathUtils)),i(2,(0,o.inject)(l.IEnvironmentVariablesProvider)),i(3,(0,o.inject)(c.IDisposableRegistry)),i(4,(0,o.inject)(c.IMemento)),i(4,(0,o.named)(c.GLOBAL_MEMENTO)),i(5,(0,o.inject)(a.IFileSystem)),i(6,(0,o.inject)(c.IExtensionContext))],v),t.JupyterPaths=v},8998:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalKernelFinder=void 0;const o=n(86700),s=n(93828),a=n(80797),c=n(47680),l=n(98501),u=n(33149),d=n(97784),p=n(46318),h=n(60593),f=n(71733),m=n(72858),g=n(82232),v=n(58363),y=n(48497),b=n(36462),_=n(86909),w=n(79262),S=n(97045),C=n(70403),k=n(83474),E=n(28735),x=n(95063),T="JUPYTER_GLOBAL_KERNELSPECS_V2",D="LOCAL_KERNEL_SPEC_CONNECTIONS_CACHE_KEY_V2";let I=class{constructor(e,t,n,r,i,o){this.interpreterService=e,this.extensionChecker=t,this.nonPythonKernelFinder=n,this.pythonKernelFinder=r,this.globalState=i,this.fs=o,this.lastFetchedKernelsWithoutCache=[]}async findKernel(e,t,n){const r=(0,m.getResourceType)(e),i="interactive"===r?d.PYTHON_LANGUAGE:(0,C.getTelemetrySafeLanguage)((0,s.getLanguageInNotebookMetadata)(t)||"");try{const o=this.findPreferredLocalKernelConnectionFromCache(t),a=this.listKernels(e,n,"useCache");if(o&&o.interpreter&&await this.fs.localFileExists(o.interpreter.path))return(0,p.traceInfo)(`Preferred kernel connection found in cache ${o.id}`),o;const c=await a,l=((0,g.isPythonNotebook)(t)||"interactive"===r)&&this.extensionChecker.isPythonExtensionInstalled?await this.interpreterService.getActiveInterpreter(e):void 0,u=(0,s.findPreferredKernel)(c,e,t,l,void 0);if((0,S.sendTelemetryEvent)(k.Telemetry.PreferredKernel,void 0,{result:u?"found":"notfound",resourceType:r,language:i,hasActiveInterpreter:!!l}),u)return(0,p.traceInfo)(`findKernel found ${(0,s.getDisplayNameOrNameOfKernelConnection)(u)}`),u}catch(e){return(0,S.sendTelemetryEvent)(k.Telemetry.PreferredKernel,void 0,{result:"failed",resourceType:r,language:i},e,!0),void(0,p.traceError)("findKernel crashed",e)}}async listKernels(e,t,n="ignoreCache"){const r="ignoreCache"===n?Promise.resolve([]):this.listValidKernelsFromGlobalCache(t);let i;const o=this.listKernelsWithoutCache(e,t);let s=[];if("ignoreCache"===n)s=await o;else{let e;r.then((t=>{e=t,i=!0})).catch(x.noop),await Promise.race([r,o]),s=Array.isArray(e)&&e.length>0?e:await o}return s=this.filterKernels(s),(0,v.sendKernelListTelemetry)(e,s),i||this.cacheLocalKernelConnections(s),s}async cacheLocalKernelConnections(e){const t=this.globalState.get(D,[]),n=new Map;t.forEach((e=>n.set(e.id,e))),e.forEach((e=>n.set(e.id,e))),await this.globalState.update(D,Array.from(n.values()))}findPreferredLocalKernelConnectionFromCache(e){if(!e)return;const t=(0,s.getInterpreterHashInMetadata)(e);if(!t)return;const n=this.globalState.get(D,[]).find((e=>e.interpreter&&(0,w.getInterpreterHash)(e.interpreter)===t));return(null==n?void 0:n.interpreter)?n:void 0}async listKernelsWithoutCache(e,t){let[n,r]=await Promise.all([this.nonPythonKernelFinder.listKernelSpecs(!1,t),this.pythonKernelFinder.listKernelSpecs(e,!0,t)]);const i=this.filterKernels(n.concat(r));return this.lastFetchedKernelsWithoutCache=i,this.globalState.update(T,i).then(x.noop,(e=>{console.error("Failed to update global kernel cache",e)})),i}async listValidKernelsFromGlobalCache(e){const t=this.lastFetchedKernelsWithoutCache.length?this.lastFetchedKernelsWithoutCache:this.globalState.get(T,[]),n=[],r=Promise.all(t.map((async e=>{var t,r;let i=!1;const o=[];(null===(t=e.interpreter)||void 0===t?void 0:t.path)&&o.push(this.fs.localFileExists(e.interpreter.path).then((e=>{e||(i=!0)})).catch(x.noop)),"startUsingLocalKernelSpec"===e.kind&&(null===(r=e.kernelSpec)||void 0===r?void 0:r.specFile)&&o.push(this.fs.localFileExists(e.kernelSpec.specFile).then((e=>{e||(i=!0)})).catch(x.noop)),await Promise.all(o),i||n.push(e)})));return e?await Promise.race([r,(0,u.createPromiseFromCancellation)({token:e,cancelAction:"resolve",defaultValue:void 0})]):await r,n}filterKernels(e){return e.filter((({kernelSpec:e})=>!e||!e.argv[0].toLowerCase().endsWith("xpython")||((0,p.traceInfo)("Hiding xeus kernelspec"),!1)))}};r([b.traceDecorators.verbose("Find kernel spec",_.TraceOptions.BeforeCall|_.TraceOptions.Arguments),(0,S.captureTelemetry)(k.Telemetry.KernelFinderPerf),i(2,(0,_.ignoreLogging)())],I.prototype,"findKernel",null),r([b.traceDecorators.error("List kernels failed"),i(1,(0,_.ignoreLogging)())],I.prototype,"listKernels",null),r([(0,E.swallowExceptions)("CacheLocalKernelConnections")],I.prototype,"cacheLocalKernelConnections",null),r([(0,S.captureTelemetry)(k.Telemetry.KernelListingPerf,{kind:"local"})],I.prototype,"listKernelsWithoutCache",null),I=r([(0,o.injectable)(),i(0,(0,o.inject)(y.IInterpreterService)),i(1,(0,o.inject)(l.IPythonExtensionChecker)),i(2,(0,o.inject)(c.LocalKnownPathKernelSpecFinder)),i(3,(0,o.inject)(a.LocalPythonAndRelatedNonPythonKernelSpecFinder)),i(4,(0,o.inject)(f.IMemento)),i(4,(0,o.named)(f.GLOBAL_MEMENTO)),i(5,(0,o.inject)(h.IFileSystem))],I),t.LocalKernelFinder=I},14238:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.loadKernelSpec=t.LocalKernelSpecFinderBase=t.oldKernelsSpecFolderName=t.isDefaultPythonKernelSpecSpecName=void 0;const o=n(71017),s=n(97784),a=n(46318),c=n(29140),l=n(28735),u=n(95063),d=n(36462),p=n(86909),h=n(93828),f=n(69930);t.isDefaultPythonKernelSpecSpecName=/python\s\d*.?\d*$/,t.oldKernelsSpecFolderName="__old_vscode_kernelspecs";class m{constructor(e,t,n,r){this.fs=e,this.workspaceService=t,this.extensionChecker=n,this.globalState=r,this.kernelSpecCache=new Map,this.pathToKernelSpec=new Map}get oldKernelSpecsFolder(){return this._oldKernelSpecsFolder||this.globalState.get("OLD_KERNEL_SPECS_FOLDER__","")}set oldKernelSpecsFolder(e){this._oldKernelSpecsFolder=e,this.globalState.update("OLD_KERNEL_SPECS_FOLDER__",e)}clearCache(){this.kernelSpecCache.clear()}async listKernelsWithCache(e,t,n,r){const i=this.kernelSpecCache.get(e);if(i&&!r){if(i.usesPython&&i.wasPythonExtInstalled===this.extensionChecker.isPythonExtensionInstalled)return i.promise;if(!i.usesPython)return i.promise}const o=n().then((t=>{const n=new Map;return(0,a.traceInfoIfCI)(`Kernel specs for ${(null==e?void 0:e.toString())||"undefined"} are \n ${JSON.stringify(t,void 0,4)}`),t.map((e=>{n.has(e.id)||n.set(e.id,e)})),Array.from(n.values()).sort(((e,t)=>{const n=e.kernelSpec.display_name.toUpperCase(),r=t.kernelSpec.display_name.toUpperCase();return n===r?0:n{var n;const i=t&&r&&(0,h.getKernelRegistrationInfo)(t)&&t.specFile&&o.dirname(o.dirname(t.specFile))===r;if(t&&!i)return t;(null==t?void 0:t.specFile)&&i&&this.deleteOldKernelSpec(t.specFile).catch(u.noop),this.pathToKernelSpec.delete(e),this.cache=null===(n=this.cache)||void 0===n?void 0:n.filter((t=>t.kernelSpecFile!==e))}))}async deleteOldKernelSpec(e){const n=o.basename(o.dirname(e)),r=o.join(o.dirname(o.dirname(e)),t.oldKernelsSpecFolderName);this.oldKernelSpecsFolder=r;const i=o.join(r,n,o.basename(e));await this.fs.ensureLocalDir(o.dirname(i)),await this.fs.copyLocal(e,i).catch(u.noop),await this.fs.deleteLocalFile(e),(0,a.traceInfo)(`Old KernelSpec '${e}' deleted and backup stored in ${r}`)}async loadKernelSpec(e,t,n){return g(e,this.fs,t,n)}async findKernelSpecsInPaths(e,t){const n=await Promise.all(e.map((async e=>{const t="string"==typeof e?e:e.kernelSearchPath;if(await this.fs.localDirectoryExists(t)){const n=await this.fs.searchLocal("**/kernel.json",t,!0);return{interpreter:"string"==typeof e?void 0:e.interpreter,kernelSpecFiles:n.map((e=>o.join(t,e)))}}})));if(null==t?void 0:t.isCancellationRequested)return[];const r=[];return n.forEach((e=>{if(e)for(const t of e.kernelSpecFiles)r.push({interpreter:e.interpreter,kernelSpecFile:t})})),r}}async function g(e,n,r,i){var l,u,d,p;if(e.includes(t.oldKernelsSpecFolderName))return;let m;try{(0,a.traceVerbose)(`Loading kernelspec from ${(0,c.getDisplayPath)(e)} for ${(0,c.getDisplayPath)(null==r?void 0:r.path)}`),m=JSON.parse(await n.readLocalFile(e))}catch(t){return void(0,a.traceError)(`Failed to parse kernelspec ${e}`,t)}if(null==i?void 0:i.isCancellationRequested)return;if(m.name=r?(0,h.getInterpreterKernelSpecName)(r):m.name,!m.display_name.toLowerCase().match(t.isDefaultPythonKernelSpecSpecName)&&m.language===s.PYTHON_LANGUAGE&&m.argv.length>2){const e=m.argv.slice(1).map((e=>e.toLowerCase())).filter((e=>!["-m","ipykernel","ipykernel_launcher","-f","{connection_file}"].includes(e)));e.length&&(m.name=`${m.name}.${e.join("#")}`)}m.metadata=m.metadata||{},m.metadata.vscode=m.metadata.vscode||{},m.metadata.vscode.originalSpecFile||(m.metadata.vscode.originalSpecFile=e),m.metadata.vscode.originalDisplayName||(m.metadata.vscode.originalDisplayName=m.display_name),m.metadata.originalSpecFile&&(m.metadata.vscode.originalSpecFile=m.metadata.originalSpecFile,delete m.metadata.originalSpecFile);const g=new f.JupyterKernelSpec(m,e,(null==r?void 0:r.path)||(null===(u=null===(l=null==m?void 0:m.metadata)||void 0===l?void 0:l.interpreter)||void 0===u?void 0:u.path),(0,h.getKernelRegistrationInfo)(m));g.name=(null==m?void 0:m.name)||o.basename(o.dirname(e));const v=(null==r?void 0:r.path)||(null===(p=null===(d=null==m?void 0:m.metadata)||void 0===d?void 0:d.interpreter)||void 0===p?void 0:p.path);return!v||await n.localFileExists(v)?g:void 0}r([(0,l.testOnlyMethod)()],m.prototype,"clearCache",null),r([d.traceDecorators.error("List kernels failed"),i(2,(0,p.ignoreLogging)())],m.prototype,"listKernelsWithCache",null),t.LocalKernelSpecFinderBase=m,t.loadKernelSpec=g},47680:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalKnownPathKernelSpecFinder=void 0;const o=n(86700),s=n(93828),a=n(14238),c=n(78985),l=n(98501),u=n(13395),d=n(97784),p=n(46318),h=n(60593),f=n(71733),m=n(97045),g=n(83474);let v=class extends a.LocalKernelSpecFinderBase{constructor(e,t,n,r,i){super(e,t,r,i),this.jupyterPaths=n,this.oldKernelSpecsFolder&&(0,p.traceInfo)(`Old kernelspecs (created by Jupyter extension) stored in directory ${this.oldKernelSpecsFolder}`)}async listKernelSpecs(e,t){return this.listKernelsWithCache(e?"IncludePythonV2":"ExcludePythonV2",!1,(async()=>(await this.findKernelSpecs(t)).filter((t=>!!e||t.language!==d.PYTHON_LANGUAGE)).map((e=>({kind:"startUsingLocalKernelSpec",kernelSpec:e,interpreter:void 0,id:(0,s.getKernelId)(e)})))))}async findKernelSpecs(e){let t=[];const[n,r]=await Promise.all([this.jupyterPaths.getKernelSpecRootPaths(e),this.jupyterPaths.getKernelSpecRootPath()]),i=await this.findKernelSpecsInPaths(n,e);await Promise.all(i.map((async n=>{try{const i=await this.getKernelSpec(n.kernelSpecFile,n.interpreter,r,e);i&&t.push(i)}catch(e){(0,p.traceError)(`Failed to load kernelspec for ${n.kernelSpecFile}`,e)}})));const o=new Set;t.forEach((e=>{var t,n;(null===(t=e.metadata)||void 0===t?void 0:t.originalSpecFile)&&o.add(null===(n=e.metadata)||void 0===n?void 0:n.originalSpecFile)})),t=t.filter((e=>!e.specFile||!o.has(e.specFile)));const s=[],a=new Map;return t.forEach((e=>{const t=a.get(e.display_name);t&&t.path!==e.path?s.push(e):t||(s.push(e),a.set(e.display_name,e))})),s}};r([(0,m.captureTelemetry)(g.Telemetry.KernelListingPerf,{kind:"localKernelSpec"})],v.prototype,"listKernelSpecs",null),v=r([(0,o.injectable)(),i(0,(0,o.inject)(h.IFileSystem)),i(1,(0,o.inject)(u.IWorkspaceService)),i(2,(0,o.inject)(c.JupyterPaths)),i(3,(0,o.inject)(l.IPythonExtensionChecker)),i(4,(0,o.inject)(f.IMemento)),i(4,(0,o.named)(f.GLOBAL_MEMENTO))],v),t.LocalKnownPathKernelSpecFinder=v},80797:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalPythonAndRelatedNonPythonKernelSpecFinder=t.isDefaultKernelSpec=t.isDefaultPythonKernelSpecName=void 0;const o=n(86700),s=n(71017),a=n(93828),c=n(14238),l=n(78985),u=n(47680),d=n(98501),p=n(13395),h=n(97784),f=n(46318),m=n(29140),g=n(60593),v=n(71733),y=n(48497),b=n(79262),_=n(97045),w=n(83474);function S(e){var n,r,i,o,a;const c=(null===(r=null===(n=e.metadata)||void 0===n?void 0:n.vscode)||void 0===r?void 0:r.originalSpecFile)||(null===(i=e.metadata)||void 0===i?void 0:i.originalSpecFile),l=c?s.basename(s.dirname(c)):e.name||"",u=(null===(a=null===(o=e.metadata)||void 0===o?void 0:o.vscode)||void 0===a?void 0:a.originalDisplayName)||e.display_name||"";return!(!l.toLowerCase().match(t.isDefaultPythonKernelSpecName)&&"python 3 (ipykernel)"!==u.toLowerCase()&&"python 3"!==u.toLowerCase())}t.isDefaultPythonKernelSpecName=/^python\d*.?\d*$/,t.isDefaultKernelSpec=S;let C=class extends c.LocalKernelSpecFinderBase{constructor(e,t,n,r,i,o,s){super(t,n,i,s),this.interpreterService=e,this.jupyterPaths=r,this.kernelSpecsFromKnownLocations=o}async listKernelSpecs(e,t,n){const r=this.workspaceService.getWorkspaceFolderIdentifier(e,(null==e?void 0:e.fsPath)||this.workspaceService.rootPath)||"root";return this.listKernelsWithCache(r,!0,(()=>this.listKernelsImplementation(e,n)),t)}async listKernelsImplementation(e,t){const n=this.extensionChecker.isPythonExtensionInstalled?await this.interpreterService.getInterpreters(e):[];return(0,f.traceInfoIfCI)(`listKernelsImplementation for ${null==e?void 0:e.toString()}: ${n.map((e=>e.path)).join("\n")}`),0!==n.length&&this.extensionChecker.isPythonExtensionInstalled?this.listPythonAndRelatedNonPythonKernelSpecs(e,n,t):this.listGlobalPythonKernelSpecs(!1,t)}async listGlobalPythonKernelSpecs(e,t){return(await this.kernelSpecsFromKnownLocations.listKernelSpecs(!0,t)).filter((e=>e.kernelSpec.language===h.PYTHON_LANGUAGE)).filter((t=>!!e||!(0,a.getKernelRegistrationInfo)(t.kernelSpec))).map((e=>e))}async listPythonAndRelatedNonPythonKernelSpecs(e,t,n){const[r,i,o,s]=await Promise.all([this.findKernelSpecsInInterpreters(t,n),this.interpreterService.getActiveInterpreter(e),this.listGlobalPythonKernelSpecs(!0,n),this.jupyterPaths.getKernelSpecTempRegistrationFolder()]),c=o.filter((e=>(0,a.getKernelRegistrationInfo)(e.kernelSpec)));let l=[...t];const u=!!(t.length>0||i),d=new Map;return await Promise.all(o.filter((e=>{const t=(0,a.getKernelRegistrationInfo)(e.kernelSpec);return!(t||!((e=>{if(e.kernelSpec.language!==h.PYTHON_LANGUAGE)return!1;const t=e.kernelSpec.argv.map((e=>e.toLowerCase())),n=t.indexOf("-m");if(-1===n)return!1;const r=t.length-1>=n?t[n+1]:void 0;return!!r&&"ipykernel_launcher"!==r})(e)||Object.keys(e.kernelSpec.env||{}).length>0))||!t&&e.kernelSpec.language===h.PYTHON_LANGUAGE&&!S(e.kernelSpec)})).map((async e=>{const n=await this.findMatchingInterpreter(e.kernelSpec,t);if(!n)return void(0,f.traceVerbose)(`Kernel Spec for ${e.kernelSpec.display_name} ignored as we cannot find a matching interpreter ${JSON.stringify(e)}`);const r={kind:"startUsingLocalKernelSpec",kernelSpec:e.kernelSpec,interpreter:n,id:(0,a.getKernelId)(e.kernelSpec,n)};d.set(r.id,r)}))),await Promise.all([...r,...c.map((e=>e.kernelSpec))].filter((e=>!(e.language===h.PYTHON_LANGUAGE&&u&&(!e.env||0===Object.keys(e.env).length)&&S(e)&&((0,f.traceVerbose)(`Hiding default kernel spec '${e.display_name}', '${e.name}', ${(0,m.getDisplayPath)(e.argv[0])}`),1)))).map((async e=>{var n,r,o,s,c,u,d,p;const g=await this.findMatchingInterpreter(e,t);if(g){const t={kind:"startUsingPythonInterpreter",kernelSpec:e,interpreter:g,id:(0,a.getKernelId)(e,g)},n=(0,a.getKernelRegistrationInfo)(t.kernelSpec);return"registeredByNewVersionOfExt"!==n&&"registeredByOldVersionOfExt"!==n||(l=l.filter((e=>g!==e))),t}{let t=e.language===h.PYTHON_LANGUAGE?i:void 0;if(e.language===h.PYTHON_LANGUAGE&&(null===(r=null===(n=e.metadata)||void 0===n?void 0:n.interpreter)||void 0===r?void 0:r.path)&&!(0,b.areInterpreterPathsSame)(null===(s=null===(o=e.metadata)||void 0===o?void 0:o.interpreter)||void 0===s?void 0:s.path,null==i?void 0:i.path))try{t=await this.interpreterService.getInterpreterDetails(null===(u=null===(c=e.metadata)||void 0===c?void 0:c.interpreter)||void 0===u?void 0:u.path)}catch(t){return void(0,f.traceError)(`Failed to get interpreter details for Kernel Spec ${(0,m.getDisplayPath)(e.specFile)} with interpreter path ${(0,m.getDisplayPath)(null===(p=null===(d=e.metadata)||void 0===d?void 0:d.interpreter)||void 0===p?void 0:p.path)}`,t)}return{kind:"startUsingLocalKernelSpec",kernelSpec:e,interpreter:t,id:(0,a.getKernelId)(e,t)}}})).map((async e=>{const t=await e;t&&!d.has(t.id)&&d.set(t.id,t)}))),[...Array.from(d.values()),...l.map((e=>{const t=(0,a.createInterpreterKernelSpec)(e,s);return{kind:"startUsingPythonInterpreter",kernelSpec:t,interpreter:e,id:(0,a.getKernelId)(t,e)}}))].sort(((e,t)=>{var n,r;return e.kernelSpec.display_name.toUpperCase()===t.kernelSpec.display_name.toUpperCase()?0:(0,b.areInterpreterPathsSame)(null===(n=e.interpreter)||void 0===n?void 0:n.path,null==i?void 0:i.path)&&e.kernelSpec.display_name.toUpperCase()===(null===(r=null==i?void 0:i.displayName)||void 0===r?void 0:r.toUpperCase())?-1:1}))}async findMatchingInterpreter(e,t){if(e.language&&e.language!==h.PYTHON_LANGUAGE)return void(0,f.traceInfoIfCI)(`Kernel ${e.name} is not python based so does not have an interpreter.`);const n=t.find((t=>{var n,r,i,o;return!(!(null===(r=null===(n=e.metadata)||void 0===n?void 0:n.interpreter)||void 0===r?void 0:r.path)||!(0,b.areInterpreterPathsSame)(null===(o=null===(i=e.metadata)||void 0===i?void 0:i.interpreter)||void 0===o?void 0:o.path,t.path,void 0,this.fs)||((0,f.traceVerbose)(`Kernel ${e.name} matches ${t.displayName} based on metadata path.`),0))}));if(n)return n;const r=e&&Array.isArray(e.argv)&&e.argv.length>0?e.argv[0]:void 0;if(r&&s.basename(r)!==r){const n=t.find((t=>!!(0,b.areInterpreterPathsSame)(r,t.path,void 0,this.fs)&&((0,f.traceVerbose)(`Kernel ${e.name} matches ${t.displayName} based on path in argv.`),!0)));if(n)return n;const i=await this.interpreterService.getInterpreterDetails(r);if(i)return i}if(e.interpreterPath){const n=t.find((t=>!(!e.interpreterPath||!this.fs.areLocalPathsSame(e.interpreterPath,t.path)||((0,f.traceVerbose)(`Kernel ${e.name} matches ${t.displayName} based on interpreter path.`),0))));if(n)return n}return t.find((t=>e.display_name===t.displayName?((0,f.traceVerbose)(`Kernel ${e.name} matches ${t.displayName} based on display name.`),!0):((0,f.traceInfoIfCI)(`Kernel ${e.name} does not match ${t.displayName} interpreter.`),!1)))}async findKernelSpecsInInterpreters(e,t){(0,f.traceInfoIfCI)(`Finding kernel specs for interpreters: ${e.map((e=>e.path)).join("\n")}`);const[n,r,i]=await Promise.all([this.findKernelPathsOfAllInterpreters(e),this.jupyterPaths.getKernelSpecRootPaths(),this.jupyterPaths.getKernelSpecRootPath()]),o=n.filter((e=>!r.includes(e.kernelSearchPath)));(0,f.traceInfoIfCI)(`Finding kernel specs for paths: ${o.map((e=>e.interpreter?e.interpreter.path:e)).join("\n")}`);const s=await this.findKernelSpecsInPaths(o,t);let a=[];await Promise.all(s.map((async e=>{const n=await this.getKernelSpec(e.kernelSpecFile,e.interpreter,i,t);n&&a.push(n)})));const c=new Set;a.forEach((e=>{var t,n;(null===(t=e.metadata)||void 0===t?void 0:t.originalSpecFile)&&c.add(null===(n=e.metadata)||void 0===n?void 0:n.originalSpecFile)})),a=a.filter((e=>!e.specFile||!c.has(e.specFile)));const l=[],u=new Map;return a.forEach((e=>{const t=u.get(e.display_name);t&&t.path!==e.path?l.push(e):t||(l.push(e),u.set(e.display_name,e))})),(0,f.traceInfoIfCI)(`Finding kernel specs unique results: ${l.map((e=>e.interpreterPath)).join("\n")}`),l}async findKernelPathsOfAllInterpreters(e){const t=new Set;return e.map((e=>({interpreter:e,kernelSearchPath:s.join(e.sysPrefix,l.baseKernelPath)}))).filter((e=>!t.has(e.kernelSearchPath)&&(t.add(e.kernelSearchPath),!0)))}};r([(0,_.captureTelemetry)(w.Telemetry.KernelListingPerf,{kind:"localPython"})],C.prototype,"listKernelSpecs",null),C=r([(0,o.injectable)(),i(0,(0,o.inject)(y.IInterpreterService)),i(1,(0,o.inject)(g.IFileSystem)),i(2,(0,o.inject)(p.IWorkspaceService)),i(3,(0,o.inject)(l.JupyterPaths)),i(4,(0,o.inject)(d.IPythonExtensionChecker)),i(5,(0,o.inject)(u.LocalKnownPathKernelSpecFinder)),i(6,(0,o.inject)(v.IMemento)),i(6,(0,o.named)(v.GLOBAL_MEMENTO))],C),t.LocalPythonAndRelatedNonPythonKernelSpecFinder=C},40196:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.PreferredRemoteKernelIdProvider=t.MaximumKernelIdListSize=t.ActiveKernelIdList=void 0;const o=n(86700),s=n(96486),a=n(46318),c=n(29140),l=n(71733),u=n(97045),d=n(83474);t.ActiveKernelIdList="Active_Kernel_Id_List",t.MaximumKernelIdListSize=100;let p=class{constructor(e,t){this.globalMemento=e,this.crypto=t}getPreferredRemoteKernelId(e){const n=this.globalMemento.get(t.ActiveKernelIdList,[]);if(n){const t=this.crypto.createHash(e.toString(),"string"),r=n.find((e=>e.fileHash===t));return(0,a.traceInfo)(`Preferred Remote kernel for ${(0,c.getDisplayPath)(e)} is ${null==r?void 0:r.kernelId}`),null==r?void 0:r.kernelId}}async storePreferredRemoteKernelId(e,n){const r=(0,s.cloneDeep)(this.globalMemento.get(t.ActiveKernelIdList,[])),i=this.crypto.createHash(e.toString(),"string"),o=r.findIndex((e=>e.fileHash===i));for(o>=0&&r.splice(o,1),n&&r.push({fileHash:i,kernelId:n}),(0,u.sendTelemetryEvent)(d.Telemetry.NumberOfSavedRemoteKernelIds,void 0,{count:r.length});r.length>t.MaximumKernelIdListSize;)r.shift();(0,a.traceInfo)(`Storing Preferred remote kernel for ${(0,c.getDisplayPath)(e)} is ${n}`),await this.globalMemento.update(t.ActiveKernelIdList,r)}};p=r([(0,o.injectable)(),i(0,(0,o.inject)(l.IMemento)),i(0,(0,o.named)(l.GLOBAL_MEMENTO)),i(1,(0,o.inject)(l.ICryptoUtils))],p),t.PreferredRemoteKernelIdProvider=p},23120:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PythonKernelInterruptDaemon=void 0;const r=n(74389),i=n(46318),o=n(33988);class s extends o.BasePythonDaemon{constructor(e,t,n,r,i){super(e,t,n,r,i)}async interrupt(){const e=new r.RequestType0("interrupt_kernel");await this.sendRequestWithoutArgs(e)}async kill(){if((0,i.traceInfo)("kill daemon"),this.killed)return;this.killed=!0;const e=new r.RequestType0("kill_kernel");await this.sendRequestWithoutArgs(e)}async getInterruptHandle(){(0,i.traceInfo)("get interrupthandle daemon");const e=new r.RequestType0("get_handle");return await this.sendRequestWithoutArgs(e)}}t.PythonKernelInterruptDaemon=s},45456:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteKernelFinder=void 0;const o=n(57310),s=n(86700),a=n(93828),c=n(97784),l=n(46318),u=n(71733),d=n(72858),p=n(58363),h=n(5448),f=n(48497),m=n(36462),g=n(86909),v=n(97045),y=n(70403),b=n(83474),_=n(40196);let w=class{constructor(e,t,n,r){this.preferredRemoteKernelIdProvider=t,this.jupyterSessionManagerFactory=n,this.interpreterService=r,this.kernelIdsToHide=new Set,e.push(this.jupyterSessionManagerFactory.onRestartSessionCreated(this.addKernelToIgnoreList.bind(this))),e.push(this.jupyterSessionManagerFactory.onRestartSessionUsed(this.removeKernelFromIgnoreList.bind(this)))}async findKernel(e,t,n,r){const i=(0,d.getResourceType)(e),o="interactive"===i?c.PYTHON_LANGUAGE:(0,y.getTelemetrySafeLanguage)((0,a.getLanguageInNotebookMetadata)(n)||"");try{const r=await this.listKernels(e,t),s=(0,a.findPreferredKernel)(r,e,n,void 0,this.preferredRemoteKernelIdProvider);return(0,v.sendTelemetryEvent)(b.Telemetry.PreferredKernel,void 0,{result:s?"found":"notfound",resourceType:i,language:o}),s}catch(e){(0,v.sendTelemetryEvent)(b.Telemetry.PreferredKernel,void 0,{result:"failed",resourceType:i,language:o},e,!0),(0,l.traceError)("findKernel crashed",e)}}async listKernels(e,t){let n;if(t&&"jupyter"===t.type)try{n=await this.jupyterSessionManagerFactory.create(t);const[r,i,o]=await Promise.all([n.getRunningKernels(),n.getKernelSpecs(),n.getRunningSessions()]),s=await Promise.all(i.map((async e=>({kind:"startUsingRemoteKernelSpec",interpreter:await this.getInterpreter(e,t.baseUrl),kernelSpec:e,id:(0,a.getKernelId)(e,void 0,t.baseUrl),baseUrl:t.baseUrl})))),c=[...o.map((e=>{var n,o;const s=e.kernel,a=s.last_activity?new Date(Date.parse(s.last_activity.toString())):new Date,c=s.connections?parseInt(s.connections.toString(),10):0,l=r.find((t=>{var n;return t.id===(null===(n=e.kernel)||void 0===n?void 0:n.id)}))||{},u=i.find((t=>{var n;return t.name===(null===(n=e.kernel)||void 0===n?void 0:n.name)}))||{};return{kind:"connectToLiveKernel",kernelModel:{...e.kernel,...u,...l,name:(null===(n=e.kernel)||void 0===n?void 0:n.name)||"",lastActivityTime:a,numberOfConnections:c,model:e},baseUrl:t.baseUrl,id:(null===(o=e.kernel)||void 0===o?void 0:o.id)||""}})).filter((e=>!this.kernelIdsToHide.has(e.kernelModel.id||""))),...s];return(0,l.traceInfoIfCI)(`Kernel specs for ${(null==e?void 0:e.toString())||"undefined"} are \n ${JSON.stringify(c,void 0,4)}`),(0,p.sendKernelListTelemetry)(e,c),c}finally{n&&await n.dispose()}return(0,p.sendKernelListTelemetry)(e,[]),[]}addKernelToIgnoreList(e){this.kernelIdsToHide.add(e.id),this.kernelIdsToHide.add(e.clientId)}removeKernelFromIgnoreList(e){this.kernelIdsToHide.delete(e.id),this.kernelIdsToHide.delete(e.clientId)}async getInterpreter(e,t){const n=new o.URL(t);if("localhost"===n.hostname.toLocaleLowerCase()||"127.0.0.1"===n.hostname)return this.interpreterService.getInterpreterDetails(e.argv[0])}};r([m.traceDecorators.verbose("Find remote kernel spec"),(0,v.captureTelemetry)(b.Telemetry.KernelFinderPerf),(0,v.captureTelemetry)(b.Telemetry.KernelListingPerf,{kind:"remote"}),i(3,(0,g.ignoreLogging)())],w.prototype,"findKernel",null),w=r([(0,s.injectable)(),i(0,(0,s.inject)(u.IDisposableRegistry)),i(1,(0,s.inject)(_.PreferredRemoteKernelIdProvider)),i(2,(0,s.inject)(h.IJupyterSessionManagerFactory)),i(3,(0,s.inject)(f.IInterpreterService))],w),t.RemoteKernelFinder=w},57961:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelEnvironmentVariablesService=void 0;const o=n(86700),s=n(71017),a=n(46318),c=n(29140),l=n(95063),u=n(75213),d=n(34347),p=n(48497);let h=class{constructor(e,t,n,r){this.interpreterService=e,this.envActivation=t,this.envVarsService=n,this.customEnvVars=r}async getEnvironmentVariables(e,t,n){let r=n.env&&Object.keys(n.env).length>0?n.env:void 0;if(!t){if(!n.interpreterPath)return(0,a.traceInfo)(`No custom variables for Kernel as interpreter path is not defined for kernel ${n.display_name}`),r;t=await this.interpreterService.getInterpreterDetails(n.interpreterPath).catch((e=>{(0,a.traceError)("Failed to fetch interpreter information for interpreter that owns a kernel",e)}))}let[i,o,u]=await Promise.all([this.customEnvVars.getCustomEnvironmentVariables(e).catch(l.noop),t?this.envActivation.getActivatedEnvironmentVariables(e,t,!1).catch((e=>{(0,a.traceError)("Failed to get env variables for interpreter, hence no variables for Kernel",e)})):void 0,!!t&&this.envActivation.hasActivationCommands(e,t)]);if(!o&&0===Object.keys(i||{}).length){if((0,a.traceInfo)("No custom variables nor do we have a conda environment"),t){const e=r||process.env;return this.envVarsService.prependPath(e,s.dirname(t.path)),e}return r}const d=null!=o;o=o||{};const p={...process.env};r=r||{},i=i||{},this.envVarsService.mergeVariables(o,p),this.envVarsService.mergeVariables(r,p),this.envVarsService.mergeVariables(i,p);let h=Object.keys(o).find((e=>"path"==e.toLowerCase()));const f=Object.keys(p).find((e=>"path"==e.toLowerCase()))||h;return h&&f&&(p[f]=o[h]),o.PYTHONPATH&&(p.PYTHONPATH=o.PYTHONPATH),h=Object.keys(i).find((e=>"path"==e.toLowerCase())),h&&i[h]&&this.envVarsService.appendPath(p,i[h]),h=Object.keys(r).find((e=>"path"==e.toLowerCase())),h&&r[h]&&this.envVarsService.appendPath(p,r[h]),i.PYTHONPATH&&this.envVarsService.appendPythonPath(p,i.PYTHONPATH),r.PYTHONPATH&&this.envVarsService.appendPythonPath(p,r.PYTHONPATH),t&&this.envVarsService.prependPath(p,s.dirname(t.path)),t&&d&&u?((0,a.traceInfo)(`Adding env Variable PYTHONNOUSERSITE to ${(0,c.getDisplayPath)(t.path)}`),p.PYTHONNOUSERSITE="True"):delete p.PYTHONNOUSERSITE,p}};h=r([(0,o.injectable)(),i(0,(0,o.inject)(p.IInterpreterService)),i(1,(0,o.inject)(d.IEnvironmentActivationService)),i(2,(0,o.inject)(u.IEnvironmentVariablesService)),i(3,(0,o.inject)(u.IEnvironmentVariablesProvider))],h),t.KernelEnvironmentVariablesService=h},36515:function(e,t,n){"use strict";var r,i=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelLauncher=void 0;const s=n(55674),a=n(86700),c=n(22037),l=n(71017),u=n(22351),d=n(73837),p=n(71171),h=n(66828),f=n(98501),m=n(33149),g=n(97784),v=n(55170),y=n(46318),b=n(29140),_=n(60593),w=n(12698),S=n(71733),C=n(28735),k=n(35952),E=n(32417),x=n(97045),T=n(83474),D=n(43367),I=n(57961),P=n(35169),R="kernelLauncherPortStart_{0}.tmp";let M=r=class{constructor(e,t,n,r,i,o,s){this.processExecutionFactory=e,this.fs=t,this.extensionChecker=n,this.kernelEnvVarsService=r,this.disposables=i,this.pythonExecFactory=o,this.configService=s}static get usedPorts(){return Array.from(r._usedPorts)}static async cleanupStartPort(){try{const e=await r.startPortPromise;(0,y.traceInfo)(`Cleaning up port start file : ${e}`);const t=l.join(c.tmpdir(),R.format(e.toString()));await s.remove(t)}catch(e){(0,y.traceInfo)("Kernel port mutex failed to cleanup: ",e)}}static async computeStartPort(){if((0,g.isTestExecution)()){let e=9e3,t=0;for(;0===t&&e<65e3;)try{const n=l.join(c.tmpdir(),R.format(e.toString()));await s.open(n,"wx"),t=e}catch(t){e+=1e3}return(0,y.traceInfo)(`Computed port start for KernelLauncher is : ${t}`),t}return 9e3}async launch(e,t,n,r,i){const o=(async()=>(this.logIPyKernelPath(n,e),await this.launchProcess(e,n,r,t,i)))();return(0,E.sendKernelTelemetryWhenDone)(n,T.Telemetry.KernelLauncherPerf,o),o}async logIPyKernelPath(e,t){const n=t.interpreter;if(!(0,D.isLocalConnection)(t)||!n)return;const r=await this.pythonExecFactory.createActivatedEnvironment({interpreter:n,resource:e}),i=await r.exec(["-c",'import ipykernel; print(ipykernel.__version__); print("5dc3a68c-e34e-4080-9c3e-2a532b2ccb4d"); print(ipykernel.__file__)'],{}),o=(0,b.getDisplayPath)(n.path);if(i.stdout){const e=i.stdout.trim().split("5dc3a68c-e34e-4080-9c3e-2a532b2ccb4d").map((e=>e.trim())).filter((e=>e.length>0));2===e.length?((0,y.traceInfo)(`ipykernel version ${e[0]} for ${o}`),(0,y.traceInfo)(`ipykernel location ${(0,b.getDisplayPath)(e[1])} for ${o}`)):(0,y.traceInfo)(`ipykernel version & path ${i.stdout.trim()} for ${o}`)}i.stderr&&(0,y.traceWarning)(`Stderr output when getting ipykernel version & path ${i.stderr.trim()} for ${o}`)}async launchProcess(e,t,n,i,o){const s=await Promise.race([this.getKernelConnection(e),(0,m.createPromiseFromCancellation)({cancelAction:"resolve",defaultValue:void 0,token:o})]);if(!s||(null==o?void 0:o.isCancellationRequested))throw new h.CancellationError;const a=t?l.basename(t.fsPath):"",c=this.configService.getSettings(t),u=c.logKernelOutputSeparately?h.window.createOutputChannel(k.DataScience.kernelConsoleOutputChannel().format(a)):void 0;null==u||u.clear();const d=new P.KernelProcess(this.processExecutionFactory,s,e,this.fs,t,this.extensionChecker,this.kernelEnvVarsService,this.pythonExecFactory,u,c);try{await Promise.race([d.launch(n,i,o),(0,m.createPromiseFromCancellation)({token:o,cancelAction:"reject"})])}catch(e){throw d.dispose(),m.Cancellation.throwIfCanceled(o),e}const p=d.exited((({exitCode:e,reason:t})=>{(0,x.sendTelemetryEvent)(T.Telemetry.RawKernelSessionKernelProcessExited,void 0,{exitCode:e,exitReason:(0,v.getTelemetrySafeErrorMessageFromPythonTraceback)(t)}),r._usedPorts.delete(s.control_port),r._usedPorts.delete(s.hb_port),r._usedPorts.delete(s.iopub_port),r._usedPorts.delete(s.shell_port),r._usedPorts.delete(s.stdin_port),p.dispose()}),this,this.disposables);if(null==o?void 0:o.isCancellationRequested)throw await d.dispose(),new h.CancellationError;return d}async chainGetConnectionPorts(){return this.portChain&&await this.portChain,this.portChain=this.getConnectionPorts(),this.portChain}static async findNextFreePort(e){const t=await r.getPorts(5,{host:"127.0.0.1",port:e});if(t.some((e=>r._usedPorts.has(e)))){const e=Math.max(...r._usedPorts,...t);return r.findNextFreePort(e)}return t.forEach((e=>r._usedPorts.add(e))),t}async getConnectionPorts(){const e=await r.startPortPromise,t=await r.findNextFreePort(e);return(0,y.traceInfo)(`Kernel launching with ports ${t.toString()}. Start port is ${e}`),t}async getKernelConnection(e){var t;const n=await this.chainGetConnectionPorts();return{key:p(),signature_scheme:"hmac-sha256",transport:"tcp",ip:"127.0.0.1",hb_port:n[0],control_port:n[1],shell_port:n[2],stdin_port:n[3],iopub_port:n[4],kernel_name:(null===(t=e.kernelSpec)||void 0===t?void 0:t.name)||"python"}}};M.startPortPromise=r.computeStartPort(),M._usedPorts=new Set,M.getPorts=(0,d.promisify)(u.getPorts),i([(0,C.swallowExceptions)("Failed to capture IPyKernel version and path")],M.prototype,"logIPyKernelPath",null),M=r=i([(0,a.injectable)(),o(0,(0,a.inject)(w.IProcessServiceFactory)),o(1,(0,a.inject)(_.IFileSystem)),o(2,(0,a.inject)(f.IPythonExtensionChecker)),o(3,(0,a.inject)(I.KernelEnvironmentVariablesService)),o(4,(0,a.inject)(S.IDisposableRegistry)),o(5,(0,a.inject)(w.IPythonExecutionFactory)),o(6,(0,a.inject)(S.IConfigurationService))],M),t.KernelLauncher=M},35169:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelProcess=void 0;const o=n(77282),s=n(55674),a=n(36276),c=n(22037),l=n(66828),u=n(93828),d=n(33149),p=n(55170),h=n(3108),f=n(46318),m=n(7744),g=n(35952),v=n(95063),y=n(72462),b=n(58744),_=n(90742),w=n(36462),S=n(86909),C=n(97045),k=n(83474),E=n(23120);class x{constructor(e,t,n,r,i,o,s,a,c,u){this.processExecutionFactory=e,this._connection=t,this.fileSystem=r,this.resource=i,this.extensionChecker=o,this.kernelEnvVarsService=s,this.pythonExecFactory=a,this.outputChannel=c,this.jupyterSettings=u,this.exitEvent=new l.EventEmitter,this._interruptSignalHandle=0,this._kernelConnectionMetadata=n}get exited(){return this.exitEvent.event}get kernelConnectionMetadata(){return this._kernelConnectionMetadata}get connection(){return this._connection}get isPythonKernel(){return(0,u.isPythonKernelConnection)(this.kernelConnectionMetadata)}get canInterrupt(){return"message"!==this._kernelConnectionMetadata.kernelSpec.interrupt_mode}async interrupt(){if(!this.canInterrupt)throw new Error("Kernel interrupt not supported in KernelProcess.ts");if("message"!==this._kernelConnectionMetadata.kernelSpec.interrupt_mode&&this._process&&!this._interruptSignalHandle)(0,f.traceInfo)("Interrupting kernel via SIGINT"),(0,o.kill)(this._process.pid,"SIGINT");else{if("message"!==this._kernelConnectionMetadata.kernelSpec.interrupt_mode&&this._process&&this._interruptSignalHandle&&(0,u.isPythonKernelConnection)(this._kernelConnectionMetadata))return(0,f.traceInfo)("Interrupting kernel via custom event (Win32)"),this.fireWin32InterruptEvent();(0,f.traceError)("No process to interrupt in KernleProcess.ts")}}async launch(e,t,r){var i,o;if(this.launchedOnce)throw new Error("Kernel has already been launched.");this.launchedOnce=!0,await this.updateConnectionArgs(),d.Cancellation.throwIfCanceled(r);const s=await this.launchAsObservable(e,r);if(r.isCancellationRequested)throw new l.CancellationError;let a="",c="",u="",v=!1;const w=(0,m.createDeferred)();s.proc.on("exit",(e=>{e=e||void 0,(0,f.traceVerbose)("KernelProcess Exit",`Exit - ${e}`,u),this.disposed||(v||(this.exitEvent.fire({exitCode:e||void 0,reason:(0,p.getTelemetrySafeErrorMessageFromPythonTraceback)(u)||u}),v=!0),r.isCancellationRequested||((0,f.traceInfoIfCI)("KernelProcessExitedError raised",c),w.reject(new _.KernelProcessExitedError(e||-1,c,this.kernelConnectionMetadata))))})),null===(i=s.proc.stdout)||void 0===i||i.on("data",(e=>{(0,f.traceVerbose)(`KernelProcess output: ${(e||"").toString()}`),this.sendToOutput((e||"").toString())})),null===(o=s.proc.stderr)||void 0===o||o.on("data",(e=>{u+=e.toString(),(0,f.traceVerbose)(`KernelProcess error: ${(e||"").toString()}`),this.sendToOutput((e||"").toString())})),s.out.subscribe((e=>{"stderr"===e.source?(c+=e.out,(0,f.traceWarning)(`StdErr from Kernel Process ${e.out}`)):(a+=e.out,(0,f.traceInfo)(`Kernel Output: ${a}`)),this.sendToOutput(e.out)}),(e=>{this.disposed?(0,f.traceInfo)("Kernel died",e,c):((0,f.traceError)("Kernel died",e,c),w.reject(e))}),(()=>{console.error("Completed")}));try{const e=n(79151),i=Promise.all([e.waitUntilUsed(this.connection.shell_port,200,t),e.waitUntilUsed(this.connection.iopub_port,200,t)]).catch((e=>{if(!r.isCancellationRequested)return(0,f.traceError)("waitUntilUsed timed out",e),Promise.reject(new b.KernelPortNotUsedTimeoutError(this.kernelConnectionMetadata))}));await Promise.race([i,w.promise,(0,d.createPromiseFromCancellation)({token:r,cancelAction:"reject"})])}catch(e){if((0,f.traceError)("Disposing kernel process due to an error",e),(0,f.traceError)(u||c),this.dispose(),!(null==r?void 0:r.isCancellationRequested)&&e instanceof h.BaseError)throw e;{(null==r?void 0:r.isCancellationRequested)&&(0,f.traceWarning)("User cancelled the kernel launch");const t=(0,p.getErrorMessageFromPythonTraceback)(u||c)||(u||c).substring(0,100);throw(0,f.traceInfoIfCI)("KernelDiedError raised",t,u+"\n"+c+"\n"),new y.KernelDiedError(g.DataScience.kernelDied().format(t),u+"\n"+c+"\n",e,this.kernelConnectionMetadata)}}}async dispose(){this.disposed||((0,f.traceInfo)("Dispose Kernel process"),this.disposed=!0,(0,v.swallowExceptions)((()=>{var e,t;null===(e=this._interruptDaemon)||void 0===e||e.kill(),null===(t=this._process)||void 0===t||t.kill(),this.exitEvent.fire({})})),(0,v.swallowExceptions)((async()=>this.connectionFile?s.remove(this.connectionFile):(0,v.noop)())))}sendToOutput(e){this.outputChannel&&this.outputChannel.append(e)}get launchKernelSpec(){if(this._launchKernelSpec)return this._launchKernelSpec;let e=this._kernelConnectionMetadata.kernelSpec;if(!e)throw new Error("KernelSpec cannot be empty in KernelProcess.ts");return Array.isArray(e.argv)?this._launchKernelSpec={...e,argv:[...e.argv]}:((0,f.traceError)("KernelSpec.argv in KernelProcess is undefined"),this._launchKernelSpec=void 0),this._launchKernelSpec}async updateConnectionArgs(){const e=(0,u.findIndexOfConnectionFile)(this.launchKernelSpec);if(-1===e)throw new Error(`Connection file not found in kernelspec json args, ${this.launchKernelSpec.argv.join(" ")}`);if(this.isPythonKernel&&0===e&&"-f"!==this.launchKernelSpec.argv[e-1])throw new Error(`Connection file not found in kernelspec json args, ${this.launchKernelSpec.argv.join(" ")}`);if(this.isPythonKernel)this.launchKernelSpec.argv.splice(e-1,2),this.launchKernelSpec.argv.push(...this.addPythonConnectionArgs());else{const t=await this.fileSystem.createTemporaryLocalFile(".json");if(this.connectionFile=t.filePath,await t.dispose(),await this.fileSystem.writeLocalFile(this.connectionFile,JSON.stringify(this._connection)),this.launchKernelSpec.argv[e].includes("--connection-file")){const t=this.connectionFile.includes(" ")?`"${this.connectionFile}"`:this.connectionFile;this.launchKernelSpec.argv[e]=this.launchKernelSpec.argv[e].replace(u.connectionFilePlaceholder,t)}else this.launchKernelSpec.argv[e]=this.launchKernelSpec.argv[e].replace(u.connectionFilePlaceholder,this.connectionFile)}}addPythonConnectionArgs(){const e=[];return e.push(`--ip=${this._connection.ip}`),e.push(`--stdin=${this._connection.stdin_port}`),e.push(`--control=${this._connection.control_port}`),e.push(`--hb=${this._connection.hb_port}`),e.push(`--Session.signature_scheme="${this._connection.signature_scheme}"`),e.push(`--Session.key=b"${this._connection.key}"`),e.push(`--shell=${this._connection.shell_port}`),e.push(`--transport="${this._connection.transport}"`),e.push(`--iopub=${this._connection.iopub_port}`),e.push(`--f=${a.tmpNameSync({postfix:".json"})}`),e}async launchAsObservable(e,t){let n;if(this.isPythonKernel&&this.extensionChecker.isPythonExtensionInstalled&&this._kernelConnectionMetadata.interpreter){const r=this.pythonExecFactory.createActivatedEnvironment({resource:this.resource,interpreter:this._kernelConnectionMetadata.interpreter});let[i,o,a]=await Promise.all([r,s.pathExists(e),this.kernelEnvVarsService.getEnvironmentVariables(this.resource,this._kernelConnectionMetadata.interpreter,this._kernelConnectionMetadata.kernelSpec)]);if("win32"===c.platform()){a=a||process.env;const e=await this.getWin32InterruptHandle();a.JPY_INTERRUPT_EVENT=`${e}`}const l=this.launchKernelSpec.argv.slice(1);this.jupyterSettings.enablePythonKernelLogging&&l.push("--debug"),n=i.execObservable(l,{cwd:o?e:process.cwd(),env:a}),d.Cancellation.throwIfCanceled(t)}if(!n){const r=this.launchKernelSpec.argv[0];(0,f.traceInfo)(`Launching Raw Kernel & not daemon ${this.launchKernelSpec.display_name} # ${r}`);const i=(0,d.createPromiseFromCancellation)({token:t,cancelAction:"reject"}),[o,s]=await Promise.all([Promise.race([this.processExecutionFactory.create(this.resource),i]),Promise.race([this.kernelEnvVarsService.getEnvironmentVariables(this.resource,void 0,this.launchKernelSpec),i])]),a=this.launchKernelSpec.argv.slice(1).map((e=>e.includes("--connection-file")?e:e.includes(" ")?`"${e}"`:e));n=o.execObservable(r,a,{env:s,cwd:e})}if(!n||!n.proc)throw new Error("KernelProcess failed to launch");return this._process=n.proc,n}async getWin32InterruptHandle(){if(!this._interruptSignalHandle){const e=await this.pythonExecFactory.createDaemon({daemonModule:k.KernelInterruptDaemonModule,resource:this.resource,interpreter:this._kernelConnectionMetadata.interpreter,daemonClass:E.PythonKernelInterruptDaemon,dedicated:!0});"kill"in e&&(this._interruptDaemon=e),this._interruptDaemon&&(this._interruptSignalHandle=await this._interruptDaemon.getInterruptHandle())}return this._interruptSignalHandle}async fireWin32InterruptEvent(){if(this._interruptDaemon)return this._interruptDaemon.interrupt()}}r([(0,C.captureTelemetry)(k.Telemetry.RawKernelProcessLaunch,void 0,!0)],x.prototype,"launch",null),r([w.traceDecorators.verbose("Launching kernel in kernelProcess.ts",S.TraceOptions.Arguments|S.TraceOptions.BeforeCall),i(1,(0,S.ignoreLogging)())],x.prototype,"launchAsObservable",null),t.KernelProcess=x},45990:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.HostRawNotebookProvider=void 0,n(30895);const o=n(66828),s=n(71171),a=n(5448),c=n(86700),l=n(98501),u=n(13395),d=n(97784),p=n(46318),h=n(29140),f=n(71733),m=n(7744),g=n(35952),v=n(32417),y=n(97045),b=n(83474),_=n(93828),w=n(61741),S=n(30640),C=n(46975),k=n(92513),E=n(95063),x=n(33149);class T{constructor(){this.type="raw",this.localLaunch=!0,this.displayName=""}}let D=class{constructor(e,t,n,r,i,o,a,c){this.asyncRegistry=e,this.configService=t,this.workspaceService=n,this.kernelLauncher=r,this.outputChannel=i,this.rawNotebookSupportedService=o,this.extensionChecker=a,this.disposables=c,this.notebooks=new Set,this.rawConnection=new T,this._id=s(),this.disposed=!1,this.asyncRegistry.push(this)}get id(){return this._id}async dispose(){if(!this.disposed){this.disposed=!0,(0,p.traceInfo)(`Shutting down notebooks for ${this.id}`);const e=await Promise.all([...this.notebooks.values()]);await Promise.all(e.map((e=>null==e?void 0:e.session.dispose())))}}async connect(e){return this.rawConnection}get isSupported(){return this.rawNotebookSupportedService.isSupported}async createNotebook(e,t,n,r,i){(0,p.traceInfo)(`Creating raw notebook for ${(0,h.getDisplayPath)(e.uri)}`);const s=(0,m.createDeferred)();let a;this.trackDisposable(s.promise),(0,p.traceInfo)(`Getting preferred kernel for ${(0,h.getDisplayPath)(e.uri)}`);try{const c=!!n;n&&(0,_.isPythonKernelConnection)(n)&&"startUsingLocalKernelSpec"===n.kind&&(n.interpreter||(0,y.sendTelemetryEvent)(b.Telemetry.AttemptedToLaunchRawKernelWithoutInterpreter,void 0,{pythonExtensionInstalled:this.extensionChecker.isPythonExtensionInstalled})),(0,p.traceInfo)(`Computing working directory ${(0,h.getDisplayPath)(e.uri)}`);const l=await(0,w.computeWorkingDirectory)(t,this.workspaceService);x.Cancellation.throwIfCanceled(i);const u=this.configService.getSettings(t).jupyterLaunchTimeout,d=this.configService.getSettings(t).jupyterInterruptTimeout;if(a=new k.RawJupyterSession(this.kernelLauncher,t,this.outputChannel,E.noop,l,d,n,u),c||(0,v.trackKernelResourceInformation)(t,{kernelConnection:n}),(0,p.traceVerbose)(`Connecting to raw session for ${(0,h.getDisplayPath)(e.uri)} with connection ${n.id}`),await a.connect({token:i,ui:r}),i.isCancellationRequested)throw new o.CancellationError;if(a.isConnected){const e=new S.JupyterNotebook(a,this.rawConnection);(0,p.traceInfo)(`Finished connecting ${this.id}`),s.resolve(e)}else s.reject(new Error(g.DataScience.rawConnectionBrokenError()))}catch(e){null==a||a.dispose().catch((e=>{(0,p.traceError)(`Failed to dispose of raw session on launch error: ${e} `)})),s.reject(e)}return s.promise}trackDisposable(e){e.then((t=>{t.session.onDidDispose((()=>{this.notebooks.delete(e)}),this,this.disposables)})),this.notebooks.add(e)}};r([(0,y.captureTelemetry)(b.Telemetry.RawKernelCreatingNotebook,void 0,!0)],D.prototype,"createNotebook",null),D=r([(0,c.injectable)(),i(0,(0,c.inject)(f.IAsyncDisposableRegistry)),i(1,(0,c.inject)(f.IConfigurationService)),i(2,(0,c.inject)(u.IWorkspaceService)),i(3,(0,c.inject)(C.IKernelLauncher)),i(4,(0,c.inject)(f.IOutputChannel)),i(4,(0,c.named)(d.STANDARD_OUTPUT_CHANNEL)),i(5,(0,c.inject)(a.IRawNotebookSupportedService)),i(6,(0,c.inject)(l.IPythonExtensionChecker)),i(7,(0,c.inject)(f.IDisposableRegistry))],D),t.HostRawNotebookProvider=D},92513:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.RawJupyterSession=void 0;const i=n(66828),o=n(33149),s=n(55170),a=n(46318),c=n(29140),l=n(7744),u=n(35952),d=n(88319),p=n(17261),h=n(51129),f=n(32417),m=n(97045),g=n(83474),v=n(93828),y=n(80529),b=n(23429);class _ extends y.BaseJupyterSession{constructor(e,t,n,r,i,o,s,a){super(t,s,r,i,o),this.kernelLauncher=e,this.outputChannel=n,this.launchTimeout=a,this.processExitHandler=new WeakMap}get atleastOneCellExecutedSuccessfully(){return!!(this.session&&this.session instanceof b.RawSession)&&this.session.atleastOneCellExecutedSuccessfully}get status(){return this.terminatingStatus&&"dead"!==super.status?this.terminatingStatus:super.status}get kernelId(){var e,t;return(null===(t=null===(e=this.session)||void 0===e?void 0:e.kernel)||void 0===t?void 0:t.id)||""}async waitForIdle(e){if(this.session)return this.waitForIdleOnSession(this.session,e)}async connect(e){var t;let n;(0,f.trackKernelResourceInformation)(this.resource,{kernelConnection:this.kernelConnectionMetadata});const r=new d.StopWatch;try{n=await this.startRawSession(e),o.Cancellation.throwIfCanceled(e.token),(0,f.sendKernelTelemetryEvent)(this.resource,g.Telemetry.RawKernelSessionStartSuccess),(0,f.sendKernelTelemetryEvent)(this.resource,g.Telemetry.RawKernelSessionStart,r.elapsedTime),(0,a.traceInfo)("Raw session started and connected"),this.setSession(n),null===(t=this.session)||void 0===t||t.statusChanged.connect(this.statusHandler),this.outputChannel.appendLine(u.DataScience.kernelStarted().format((0,v.getDisplayNameOrNameOfKernelConnection)(this.kernelConnectionMetadata)))}catch(e){throw this.connected=!1,e instanceof i.CancellationError?((0,f.sendKernelTelemetryEvent)(this.resource,g.Telemetry.RawKernelSessionStart,r.elapsedTime,void 0,e),(0,f.sendKernelTelemetryEvent)(this.resource,g.Telemetry.RawKernelSessionStartUserCancel),(0,a.traceInfo)("Starting of raw session cancelled by user"),e):e instanceof l.TimedOutError?((0,f.sendKernelTelemetryEvent)(this.resource,g.Telemetry.RawKernelSessionStart,r.elapsedTime,void 0,e),(0,f.sendKernelTelemetryEvent)(this.resource,g.Telemetry.RawKernelSessionStartTimeout),(0,a.traceError)("Raw session failed to start in given timeout"),e):((0,f.sendKernelTelemetryEvent)(this.resource,g.Telemetry.RawKernelSessionStart,r.elapsedTime,void 0,e),(0,f.sendKernelTelemetryEvent)(this.resource,g.Telemetry.RawKernelSessionStartException,void 0,void 0,e),(0,a.traceError)(`Failed to connect raw kernel session: ${e}`),e)}finally{(0,f.sendKernelTelemetryEvent)(this.resource,g.Telemetry.RawKernelSessionConnect,r.elapsedTime)}this.connected=!0}shutdownSession(e,t,n){const r=e&&this.processExitHandler.get(e);null==r||r.dispose();const i=(new Error).stack;return super.shutdownSession(e,t,n).then((()=>{if((0,m.sendTelemetryEvent)(g.Telemetry.RawKernelSessionShutdown,void 0,{isRequestToShutdownRestartSession:n,stacktrace:i}),e)return e.kernelProcess.dispose()}))}setSession(e){if(super.setSession(e),!e)return;this.terminatingStatus=void 0;const t=e.kernelProcess.exited((({exitCode:t,reason:n})=>{e===this.session&&((0,m.sendTelemetryEvent)(g.Telemetry.RawKernelSessionKernelProcessExited,void 0,{exitCode:t,exitReason:(0,s.getTelemetrySafeErrorMessageFromPythonTraceback)(n)}),(0,a.traceError)(`Raw kernel process exited code: ${t}`),this.terminatingStatus="terminating",this.onStatusChangedEvent.fire("terminating"),this.setSession(void 0),this.shutdownSession(e,this.statusHandler,!1).catch((e=>{(0,a.traceError)(`Error shutting down jupyter session: ${e}`)})).finally((()=>{this.terminatingStatus&&(this.terminatingStatus="dead",this.onStatusChangedEvent.fire("dead"))})))}));this.disposables.push(t),this.processExitHandler.set(e,t)}startRestartSession(e){if(!this.restartSessionPromise){const t=new i.CancellationTokenSource,n=this.createRestartSession(e,t.token);this.restartSessionPromise={token:t,promise:n},n.finally((()=>t.dispose()))}}async createRestartSession(e,t){if(!this.kernelConnectionMetadata||"connectToLiveKernel"===this.kernelConnectionMetadata.kind)throw new Error("Unsupported - unable to restart live kernel sessions using raw kernel.");return this.startRawSession({token:t,ui:new p.DisplayOptions(e)})}async startRawSession(e){var t;if("startUsingLocalKernelSpec"!==this.kernelConnectionMetadata.kind&&"startUsingPythonInterpreter"!==this.kernelConnectionMetadata.kind)throw new Error(`Unable to start Raw Kernels for Kernel Connection of type ${this.kernelConnectionMetadata.kind}`);(0,a.traceInfo)(`Starting raw kernel ${(0,v.getDisplayNameOrNameOfKernelConnection)(this.kernelConnectionMetadata)} for interpreter ${(0,c.getDisplayPath)(null===(t=this.kernelConnectionMetadata.interpreter)||void 0===t?void 0:t.path)}`),this.terminatingStatus=void 0;const n=await h.KernelProgressReporter.wrapAndReportProgress(this.resource,u.DataScience.connectingToKernel().format((0,v.getDisplayNameOrNameOfKernelConnection)(this.kernelConnectionMetadata)),(()=>this.kernelLauncher.launch(this.kernelConnectionMetadata,this.launchTimeout,this.resource,this.workingDirectory,e.token)));return h.KernelProgressReporter.wrapAndReportProgress(this.resource,u.DataScience.waitingForJupyterSessionToBeIdle(),(()=>this.postStartRawSession(e,n)))}async postStartRawSession(e,t){const n=new b.RawSession(t,this.resource);try{(0,a.traceVerbose)("Waiting for Raw Session to be ready in postStartRawSession"),await Promise.race([n.waitForReady(),(0,o.createPromiseFromCancellation)({cancelAction:"reject",token:e.token})]),(0,a.traceVerbose)("Successfully waited for Raw Session to be ready in postStartRawSession")}catch(r){if((0,a.traceError)("Failed waiting for Raw Session to be ready",r),t.dispose(),n.dispose(),r instanceof i.CancellationError||e.token.isCancellationRequested)throw new i.CancellationError;throw r}(0,a.traceVerbose)(`Kernel status before requesting kernel info and after ready is ${n.kernel.status}`);const r=new d.StopWatch;let s=(0,l.createDeferred)(),c=1;for(c=1;c<=2;c++){s=(0,l.createDeferred)();const r=()=>s.resolve(!0);n.iopubMessage.connect(r);try{(0,a.traceVerbose)("Sending request for kernelinfo"),await Promise.race([Promise.all([n.kernel.requestKernelInfo(),s.promise]),(0,l.sleep)(Math.min(this.launchTimeout,1500)),(0,o.createPromiseFromCancellation)({cancelAction:"reject",token:e.token})])}catch(e){throw(0,a.traceError)("Failed to request kernel info",e),t.dispose(),n.dispose(),e}finally{n.iopubMessage.disconnect(r)}if(s.completed){(0,a.traceVerbose)("Got response for requestKernelInfo");break}(0,a.traceVerbose)("Did not get a response for requestKernelInfo")}return s.completed?(0,a.traceVerbose)("Successfully compelted postStartRawSession"):(0,a.traceWarning)(`Didn't get response for requestKernelInfo after ${r.elapsedTime}ms.`),(0,m.sendTelemetryEvent)(g.Telemetry.RawKernelInfoResonse,r.elapsedTime,{attempts:c,timedout:!s.completed}),n}}r([(0,m.captureTelemetry)(g.Telemetry.RawKernelStartRawSession,void 0,!0)],_.prototype,"startRawSession",null),t.RawJupyterSession=_},34645:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createRawKernel=t.RawKernel=t.suppressShutdownErrors=void 0;const r=n(50361),i=n(71171),o=n(97784),s=n(46318),a=n(95063),c=n(93828),l=n(93466);function u(e){if((0,o.isTestExecution)()){const t=e;if(t&&t._futures){const e=t._futures;e&&e.forEach((e=>{void 0!==e._status&&(e._status|=4)}))}t&&t._reconnectLimit&&(t._reconnectLimit=0)}}t.suppressShutdownErrors=u;class d{constructor(e,t,n){this.realKernel=e,this.kernelProcess=n,this.socket=t,t.emit("open")}get statusChanged(){return this.realKernel.statusChanged}get iopubMessage(){return this.realKernel.iopubMessage}get unhandledMessage(){return this.realKernel.unhandledMessage}get connectionStatusChanged(){return this.realKernel.connectionStatusChanged}get connectionStatus(){return this.realKernel.connectionStatus}get anyMessage(){return this.realKernel.anyMessage}get serverSettings(){return this.realKernel.serverSettings}get id(){return this.realKernel.id}get name(){return this.realKernel.name}get model(){return this.realKernel.model}get username(){return this.realKernel.username}get clientId(){return this.realKernel.clientId}get status(){return this.realKernel.status}get info(){return this.realKernel.info}get handleComms(){return this.realKernel.handleComms}get isDisposed(){return this.realKernel.isDisposed}createComm(e,t){return this.realKernel.createComm(e,t)}hasComm(e){return this.realKernel.hasComm(e)}clone(e){return h(this.kernelProcess,(null==e?void 0:e.clientId)||this.clientId)}get disposed(){return this.realKernel.disposed}async shutdown(){u(this.realKernel),await this.kernelProcess.dispose(),this.socket.dispose()}get spec(){if("startUsingLocalKernelSpec"===this.kernelProcess.kernelConnectionMetadata.kind){const e=r(this.kernelProcess.kernelConnectionMetadata.kernelSpec),t="resources"in e?e.resources:{};return{...e,resources:t}}return(0,s.traceError)("Fetching kernel spec from raw kernel using JLab API"),this.realKernel.spec}sendShellMessage(e,t,n){return this.realKernel.sendShellMessage(e,t,n)}sendControlMessage(e,t,n){return this.realKernel.sendControlMessage(e,t,n)}reconnect(){throw new Error("Reconnect is not supported.")}async interrupt(){if(this.kernelProcess.canInterrupt)return this.kernelProcess.interrupt();if("message"===this.kernelProcess.kernelConnectionMetadata.kernelSpec.interrupt_mode){(0,s.traceInfo)("Interrupting kernel with a shell message");const e=n(36879).KernelMessage.createMessage({msgType:"interrupt_request",channel:"shell",username:this.realKernel.username,session:this.realKernel.clientId,content:{}});await this.realKernel.sendShellMessage(e,!0,!0).done.catch((e=>(0,s.traceError)("Failed to interrupt via a message",e)))}else(0,s.traceError)("Kernel interrupt not supported")}restart(){throw new Error("This method should not be called. Restart is implemented at a higher level")}requestKernelInfo(){return this.realKernel.requestKernelInfo()}requestComplete(e){return this.realKernel.requestComplete(e)}requestInspect(e){return this.realKernel.requestInspect(e)}requestHistory(e){return this.realKernel.requestHistory(e)}requestExecute(e,t,n){return this.realKernel.requestExecute(e,t,n)}requestDebug(e,t){return this.realKernel.requestDebug(e,t)}requestIsComplete(e){return this.realKernel.requestIsComplete(e)}requestCommInfo(e){return this.realKernel.requestCommInfo(e)}sendInputReply(e){return this.realKernel.sendInputReply(e)}registerCommTarget(e,t){return this.realKernel.registerCommTarget(e,t)}removeCommTarget(e,t){return this.realKernel.removeCommTarget(e,t)}dispose(){(0,a.swallowExceptions)((()=>this.realKernel.dispose())),(0,a.swallowExceptions)((()=>this.socket.dispose()))}registerMessageHook(e,t){this.realKernel.registerMessageHook(e,t)}removeMessageHook(e,t){this.realKernel.removeMessageHook(e,t)}}let p;function h(e,t){const r=n(36879),o=n(642);let s;class a extends l.RawSocket{constructor(){super(e.connection,o.serialize,o.deserialize),s=this}}const u=r.ServerConnection.makeSettings({WebSocket:a,wsUrl:"RAW"});p||(p=n(60153));const h=new p.KernelConnection({serverSettings:u,clientId:t,handleComms:!0,username:i(),model:{name:(0,c.getNameOfKernelConnection)(e.kernelConnectionMetadata)||"python3",id:i()}});return new d(h,s,e)}t.RawKernel=d,t.createRawKernel=h},5433:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RawNotebookSupportedService=void 0;const o=n(86700),s=n(46318),a=n(71733),c=n(97045),l=n(83474);let u=class{constructor(e){this.configuration=e}get isSupported(){return this.isSupportedForLocalLaunch()}isSupportedForLocalLaunch(){return!this.isZQMDisabled()&&this.zmqSupported()}isZQMDisabled(){return this.configuration.getSettings().disableZMQSupport}zmqSupported(){if("boolean"==typeof this._isSupported)return this._isSupported;if("true"===(process.env.VSC_JUPYTER_NON_RAW_NATIVE_TEST||"").toLowerCase())return!1;try{n(92747),(0,s.traceInfo)("ZMQ install verified."),(0,c.sendTelemetryEvent)(l.Telemetry.ZMQSupported),this._isSupported=!0}catch(e){(0,s.traceError)("Exception while attempting zmq :",e),(0,c.sendTelemetryEvent)(l.Telemetry.ZMQNotSupported),this._isSupported=!1}return this._isSupported}};u=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IConfigurationService))],u),t.RawNotebookSupportedService=u},23429:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RawSession=void 0;const r=n(71171),i=n(55170);n(30895);const o=n(46318),s=n(7744),a=n(95063),c=n(41738),l=n(97045),u=n(83474),d=n(34645);t.RawSession=class{constructor(e,t){this.kernelProcess=e,this.resource=t,this.isDisposed=!1,this.kernelConnectionMetadata=e.kernelConnectionMetadata;const i=this.signaling=n(4016);this._statusChanged=new i.Signal(this),this._kernelChanged=new i.Signal(this),this._ioPubMessage=new i.Signal(this),this._terminated=new i.Signal(this),this._connectionStatusChanged=new i.Signal(this),this._id=r(),this._clientID=r(),this._kernel=(0,d.createRawKernel)(e,this._clientID),this._kernel.statusChanged.connect(this.onKernelStatus,this),this._kernel.iopubMessage.connect(this.onIOPubMessage,this),this._kernel.connectionStatusChanged.connect(this.onKernelConnectionStatus,this),this.exitHandler=e.exited(this.handleUnhandledExitingOfKernelProcess,this)}get atleastOneCellExecutedSuccessfully(){return!0===this.cellExecutedSuccessfully}get jupyterLabServices(){return this._jupyterLabServices||(this._jupyterLabServices=n(36879)),this._jupyterLabServices}get connectionStatus(){return this._kernel.connectionStatus}get connectionStatusChanged(){return this._kernel.connectionStatusChanged}get disposed(){return this._kernel.disposed}async dispose(){const e=(new Error).stack;(0,l.sendTelemetryEvent)(u.Telemetry.RawKernelSessionDisposed,void 0,{stacktrace:e}),this.isDisposing=!0,this.isDisposed||(this.exitHandler.dispose(),await this._kernel.shutdown(),this._kernel.dispose(),await this.kernelProcess.dispose().catch(a.noop)),this.isDisposed=!0,this.signaling.Signal.disconnectAll(this)}get id(){return this._id}get kernel(){return this._kernel}get kernelSocketInformation(){return{socket:this._kernel.socket,options:{id:this._kernel.id,clientId:this._clientID,userName:"",model:this._kernel.model}}}get statusChanged(){return this._statusChanged}async waitForReady(){(0,o.traceVerbose)(`Waiting for Raw session to be ready, currently ${this.connectionStatus}`);const e=(0,s.createDeferred)(),t=(t,n)=>{"connected"==n?((0,o.traceVerbose)("Raw session connected"),e.resolve(n)):(0,o.traceVerbose)(`Raw session not connected, status: ${n}`)};this.connectionStatusChanged.connect(t),"connected"===this.connectionStatus&&((0,o.traceVerbose)("Raw session connected"),e.resolve(this.connectionStatus)),(0,o.traceVerbose)("Waiting for Raw session to be ready for 30s");const n=await Promise.race([e.promise,(0,s.sleep)(3e4)]);if(this.connectionStatusChanged.disconnect(t),(0,o.traceVerbose)(`Waited for Raw session to be ready & got ${n}`),"connected"!==n.toString())throw new c.KernelConnectionTimeoutError(this.kernelConnectionMetadata)}shutdown(){return this.dispose()}get terminated(){return this._terminated}get kernelChanged(){return this._kernelChanged}get propertyChanged(){throw new Error("Not yet implemented")}get iopubMessage(){return this._ioPubMessage}get unhandledMessage(){return this._kernel.unhandledMessage}get anyMessage(){return this._kernel.anyMessage}get path(){throw new Error("Not yet implemented")}get name(){return this.kernel.name}get type(){return"notebook"}get serverSettings(){return this.kernel.serverSettings}get model(){var e;return{id:this._id,name:this._kernel.name,path:(null===(e=this.kernelProcess.kernelConnectionMetadata.interpreter)||void 0===e?void 0:e.path)||"kernel_path",type:"notebook",kernel:this._kernel.model}}get status(){return this.kernel.status}setPath(e){throw new Error("Not yet implemented")}setName(e){throw new Error("Not yet implemented")}setType(e){throw new Error("Not yet implemented")}changeKernel(e){throw new Error("Not yet implemented")}onKernelStatus(e,t){(0,o.traceInfoIfCI)(`RawSession status changed to ${t}`),this._statusChanged.emit(t)}onIOPubMessage(e,t){!this.cellExecutedSuccessfully&&"execute_result"===t.header.msg_type&&t.content&&(this.jupyterLabServices.KernelMessage.isExecuteResultMsg(t)||this.jupyterLabServices.KernelMessage.isExecuteInputMsg(t))&&t.content.execution_count&&(this.cellExecutedSuccessfully=!0),this._ioPubMessage.emit(t)}onKernelConnectionStatus(e,t){this._connectionStatusChanged.emit(t)}handleUnhandledExitingOfKernelProcess(e){this.isDisposing||((0,o.traceError)(`Disposing session as kernel process died ExitCode: ${e.exitCode}, Reason: ${e.reason}`),(0,l.sendTelemetryEvent)(u.Telemetry.RawKernelSessionKernelProcessExited,void 0,{exitCode:e.exitCode,exitReason:(0,i.getTelemetrySafeErrorMessageFromPythonTraceback)(e.reason)}),this.dispose().ignoreErrors())}}},93466:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RawSocket=void 0;const r=n(67684),i=n(71171),o=n(46318),s=n(95063);t.RawSocket=class{constructor(e,t,n){this.connection=e,this.serialize=t,this.deserialize=n,this.onopen=s.noop,this.onerror=s.noop,this.onclose=s.noop,this.onmessage=s.noop,this.receiveHooks=[],this.sendHooks=[],this.msgChain=Promise.resolve(),this.sendChain=Promise.resolve(),this.closed=!1,this.channels=this.generateChannels(e)}dispose(){this.closed||this.close()}close(){this.closed=!0;const e=e=>{try{e.close()}catch(e){(0,o.traceError)("Error during socket shutdown",e)}};e(this.channels.control),e(this.channels.iopub),e(this.channels.shell),e(this.channels.stdin)}emit(e,...t){switch(e){case"message":this.onmessage({data:t[0],type:"message",target:this});break;case"close":this.onclose({wasClean:!0,code:0,reason:"",target:this});break;case"error":this.onerror({error:"",message:"to do",type:"error",target:this});break;case"open":this.onopen({target:this})}return!0}sendToRealKernel(e,t){const n=this.deserialize(e);this.sendMessage(n,!0)}send(e,t){this.sendMessage(e,!1)}addReceiveHook(e){this.receiveHooks.push(e)}removeReceiveHook(e){this.receiveHooks=this.receiveHooks.filter((t=>t!==e))}addSendHook(e){this.sendHooks.push(e)}removeSendHook(e){this.sendHooks=this.sendHooks.filter((t=>t!==e))}generateChannel(e,t,n){const r=n();return r.connect(function(e,t){const n="tcp"===e.transport?":":"-",r=e[`${t}_port`];if(!r)throw new Error(`Port not found for channel "${t}"`);return`${e.transport}://${e.ip}${n}${r}`}(e,t)),this.processSocketMessages(t,r).catch(o.traceError.bind(`Failed to read messages from channel ${t}`)),r}async processSocketMessages(e,t){for await(const n of t){if(this.closed)break;this.onIncomingMessage(e,n)}}generateChannels(e){const t=n(92747),r=i(),o={iopub:this.generateChannel(e,"iopub",(()=>new t.Subscriber({maxMessageSize:-1,receiveHighWaterMark:0}))),shell:this.generateChannel(e,"shell",(()=>new t.Dealer({routingId:r,sendHighWaterMark:0,receiveHighWaterMark:0,maxMessageSize:-1}))),control:this.generateChannel(e,"control",(()=>new t.Dealer({routingId:r,sendHighWaterMark:0,receiveHighWaterMark:0,maxMessageSize:-1}))),stdin:this.generateChannel(e,"stdin",(()=>new t.Dealer({routingId:r,sendHighWaterMark:0,receiveHighWaterMark:0,maxMessageSize:-1})))};return o.iopub.subscribe(),o}onIncomingMessage(e,t){const n=this.closed?{}:r.decode(t,this.connection.key,this.connection.signature_scheme);n.channel=e,this.receiveHooks.length?this.msgChain=this.msgChain.then((()=>{const e=this.serialize(n);return Promise.all(this.receiveHooks.map((t=>t(e))))})).then((()=>this.fireOnMessage(n))):this.msgChain=this.msgChain.then((()=>this.fireOnMessage(n)))}fireOnMessage(e){this.closed||this.onmessage({data:e,type:"message",target:this})}sendMessage(e,t){const n=r.encode(e,this.connection.key,this.connection.signature_scheme);if(!t&&this.sendHooks.length){const t=this.serialize(e);this.sendChain=this.sendChain.then((()=>Promise.all(this.sendHooks.map((e=>e(t,s.noop)))))).then((()=>this.postToSocket(e.channel,n)))}else this.sendChain=this.sendChain.then((()=>{this.postToSocket(e.channel,n)}))}postToSocket(e,t){const n=this.channels[e];n?n.send(t).catch((e=>{(0,o.traceError)("Error communicating with the kernel",e)})):(0,o.traceError)(`Attempting to send message on invalid channel: ${e}`)}}},46975:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IRemoteKernelFinder=t.ILocalKernelFinder=t.IKernelLauncher=void 0,t.IKernelLauncher=Symbol("IKernelLauncher"),t.ILocalKernelFinder=Symbol("ILocalKernelFinder"),t.IRemoteKernelFinder=Symbol("IRemoteKernelFinder")},74280:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerTypes=void 0;const r=n(66828),i=n(83474),o=n(78277),s=n(98501),a=n(14579),c=n(55978),l=n(13395),u=n(97784),d=n(71733),p=n(78176),h=n(89538),f=n(96735),m=n(5448),g=n(74321),v=n(85109),y=n(97045),b=n(53711),_=n(3598),w=n(93828),S=n(33816),C=n(2596),k=n(94137),E=n(8043),x=n(94996),T=n(48083),D=n(74607),I=n(80340),P=n(55903),R=n(28433),M=n(78140),O=n(66260),L=n(2655),N=n(14970),A=n(96937),j=n(88200),F=n(74843),U=n(44718),q=n(27294),W=n(85797),H=n(58584),Y=n(10600),V=n(14231),B=n(61412),K=n(54369),$=n(56747),z=n(13658),J=n(91060),G=n(10473),X=n(77721),Q=n(45028),Z=n(59633),ee=n(78985),te=n(8998),ne=n(47680),re=n(80797),ie=n(40196),oe=n(45456),se=n(57961),ae=n(36515),ce=n(45990),le=n(5433),ue=n(46975),de=n(24025),pe=n(32467),he=n(22350),fe=n(8488),me=n(47073),ge=n(49113);t.registerTypes=function(e,t){var n,ve,ye,be;e.addSingleton(m.IRawNotebookSupportedService,le.RawNotebookSupportedService);const _e="insiders"===e.get(l.IApplicationEnvironment).channel,we=null===(n=r.extensions.getExtension(u.JVSC_EXTENSION_ID))||void 0===n?void 0:n.packageJSON,Se=null===(be=null===(ye=null===(ve=null==we?void 0:we.engines)||void 0===ve?void 0:ve.vscode)||void 0===ye?void 0:ye.toLowerCase())||void 0===be?void 0:be.endsWith("insider");(0,y.setSharedProperty)("isInsiderExtension",_e&&Se?"true":"false"),(0,y.setSharedProperty)("ds_notebookeditor","native");const Ce=(0,w.isLocalLaunch)(e.get(d.IConfigurationService));(0,y.setSharedProperty)("localOrRemoteConnection",Ce?"local":"remote");const ke=e.get(s.IPythonExtensionChecker);(0,y.setSharedProperty)("isPythonExtensionInstalled",ke.isPythonExtensionInstalled?"true":"false");const Ee=e.get(m.IRawNotebookSupportedService);(0,y.setSharedProperty)("rawKernelSupported",Ee.isSupported?"true":"false"),e.addSingleton(k.NotebookIPyWidgetCoordinator,k.NotebookIPyWidgetCoordinator),e.add(m.IJupyterCommandFactory,T.JupyterCommandFactory),e.add(m.INotebookExporter,E.JupyterExporter),e.add(m.INotebookImporter,x.JupyterImporter),e.add(m.INotebookServer,V.HostJupyterServer),e.addSingleton(ie.PreferredRemoteKernelIdProvider,ie.PreferredRemoteKernelIdProvider),e.addSingleton(m.IRawNotebookProvider,ce.HostRawNotebookProvider),e.addSingleton(m.IJupyterNotebookProvider,W.JupyterNotebookProvider),e.addSingleton(ue.IKernelLauncher,ae.KernelLauncher),e.addSingleton(se.KernelEnvironmentVariablesService,se.KernelEnvironmentVariablesService),e.addSingleton(ue.ILocalKernelFinder,te.LocalKernelFinder),e.addSingleton(ee.JupyterPaths,ee.JupyterPaths),e.addSingleton(ne.LocalKnownPathKernelSpecFinder,ne.LocalKnownPathKernelSpecFinder),e.addSingleton(re.LocalPythonAndRelatedNonPythonKernelSpecFinder,re.LocalPythonAndRelatedNonPythonKernelSpecFinder),e.addSingleton(ue.IRemoteKernelFinder,oe.RemoteKernelFinder),e.addSingleton(o.IExtensionSingleActivationService,j.CellOutputMimeTypeTracker),e.addSingleton(o.IExtensionSingleActivationService,P.JupyterInterpreterSelectionCommand),e.addSingleton(o.IExtensionSingleActivationService,me.PreWarmActivatedJupyterEnvironmentVariables),e.addSingleton(o.IExtensionSingleActivationService,O.MigrateJupyterInterpreterStateService),e.addSingleton(m.IDataScienceCommandListener,Q.KernelCommandListener),e.addSingleton(m.IInteractiveWindowDebugger,b.InteractiveWindowDebugger,void 0,[m.ICellHashListener]),e.addSingleton(m.IJupyterExecution,Y.HostJupyterExecution),e.addSingleton(m.IJupyterPasswordConnect,H.JupyterPasswordConnect),e.addSingleton(m.IJupyterSessionManagerFactory,X.JupyterSessionManagerFactory),e.addSingleton(o.IExtensionSingleActivationService,de.DebuggerVariableRegistration),e.addSingleton(m.IJupyterVariables,he.JupyterVariables,i.Identifiers.ALL_VARIABLES),e.addSingleton(m.IJupyterVariables,fe.KernelVariables,i.Identifiers.KERNEL_VARIABLES),e.addSingleton(m.IJupyterVariables,pe.DebuggerVariables,i.Identifiers.DEBUGGER_VARIABLES),e.addSingleton(m.IKernelVariableRequester,ge.PythonVariablesRequester,i.Identifiers.PYTHON_VARIABLES_REQUESTER),e.addSingleton(q.JupyterCommandLineSelector,q.JupyterCommandLineSelector),e.addSingleton(a.JupyterCommandLineSelectorCommand,a.JupyterCommandLineSelectorCommand),e.addSingleton(D.JupyterInterpreterDependencyService,D.JupyterInterpreterDependencyService),e.addSingleton(m.INbConvertInterpreterDependencyChecker,A.NbConvertInterpreterDependencyChecker),e.addSingleton(m.INbConvertExportToPythonService,N.NbConvertExportToPythonService),e.addSingleton(I.JupyterInterpreterOldCacheStateStore,I.JupyterInterpreterOldCacheStateStore),e.addSingleton(R.JupyterInterpreterSelector,R.JupyterInterpreterSelector),e.addSingleton(M.JupyterInterpreterService,M.JupyterInterpreterService),e.addSingleton(O.JupyterInterpreterStateStore,O.JupyterInterpreterStateStore),e.addSingleton(G.JupyterServerSelector,G.JupyterServerSelector),e.addSingleton(c.JupyterServerSelectorCommand,c.JupyterServerSelectorCommand),e.addSingleton(F.JupyterKernelService,F.JupyterKernelService),e.addSingleton(m.IJupyterServerProvider,K.NotebookServerProvider),e.addSingleton(C.IPyWidgetMessageDispatcherFactory,C.IPyWidgetMessageDispatcherFactory),e.addSingleton(m.IJupyterInterpreterDependencyManager,L.JupyterInterpreterSubCommandExecutionService),e.addSingleton(m.IJupyterSubCommandExecutionService,L.JupyterInterpreterSubCommandExecutionService),e.addSingleton(m.IKernelDependencyService,Z.KernelDependencyService),e.add(v.IProtocolParser,g.ProtocolParser),e.addSingleton(m.IJupyterDebugService,f.MultiplexingDebugService,i.Identifiers.MULTIPLEXING_DEBUGSERVICE),e.addSingleton(m.IJupyterDebugService,_.JupyterDebugService,i.Identifiers.RUN_BY_LINE_DEBUGSERVICE),e.add(m.IJupyterVariableDataProvider,p.JupyterVariableDataProvider),e.addSingleton(m.IJupyterVariableDataProviderFactory,h.JupyterVariableDataProviderFactory),e.addSingleton(m.IJupyterUriProviderRegistration,U.JupyterUriProviderRegistration),e.addSingleton(m.IJupyterServerUriStorage,J.JupyterServerUriStorage),e.addSingleton($.NotebookStarter,$.NotebookStarter),e.addSingleton(m.INotebookProvider,B.NotebookProvider),e.addSingleton(o.IExtensionSingleActivationService,z.ServerPreload),(0,S.registerInstallerTypes)(e)}},43367:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IKernelProvider=t.isLocalHostConnection=t.isLocalConnection=t.NotebookCellRunState=void 0;const r=n(57310);var i;(i=t.NotebookCellRunState||(t.NotebookCellRunState={})).Idle="Idle",i.Success="Success",i.Error="Error",t.isLocalConnection=function(e){return"startUsingLocalKernelSpec"===e.kind||"startUsingPythonInterpreter"===e.kind},t.isLocalHostConnection=function(e){if("connectToLiveKernel"===e.kind||"startUsingRemoteKernelSpec"===e.kind){const t=new r.URL(e.baseUrl);return"localhost"===t.hostname.toLocaleLowerCase()||"127.0.0.1"===t.hostname}return!1},t.IKernelProvider=Symbol("IKernelProvider")},24025:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DebuggerVariableRegistration=void 0;const o=n(86700),s=n(97784),a=n(71733),c=n(5448),l=n(30662),u=n(83474);let d=class{constructor(e,t,n){this.debugService=e,this.disposables=t,this.debugVariables=n}activate(){return this.disposables.push(this.debugService.registerDebugAdapterTrackerFactory(s.PYTHON_LANGUAGE,this)),this.disposables.push(this.debugService.registerDebugAdapterTrackerFactory(l.pythonKernelDebugAdapter,this)),Promise.resolve()}createDebugAdapterTracker(e){return this.debugVariables}};d=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IJupyterDebugService)),i(0,(0,o.named)(u.Identifiers.MULTIPLEXING_DEBUGSERVICE)),i(1,(0,o.inject)(a.IDisposableRegistry)),i(2,(0,o.inject)(c.IJupyterVariables)),i(2,(0,o.named)(u.Identifiers.DEBUGGER_VARIABLES))],d),t.DebuggerVariableRegistration=d},32467:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.convertDebugProtocolVariableToIJupyterVariable=t.DebuggerVariables=void 0;const o=n(86700),s=n(71017),a=n(66828),c=n(13395),l=n(46318),u=n(71733),d=n(4036),p=n(70469),h=n(5448),f=n(78323),m=n(97045),g=n(83474),v=n(49113),y=new Set(["DataFrame","list","dict","ndarray","Series","Tensor","EagerTensor","DataArray"]),b=new Set(["In","Out","exit","quit"]);let _=class extends p.DebugLocationTracker{constructor(e,t,n,r){super(void 0),this.debugService=e,this.debuggingManager=t,this.configService=n,this.vscNotebook=r,this.refreshEventEmitter=new a.EventEmitter,this.lastKnownVariables=[],this.importedDataFrameScriptsIntoKernel=new Set,this.importedGetVariableInfoScriptsIntoKernel=new Set,this.watchedNotebooks=new Map,this.debuggingStarted=!1,this.currentVariablesReference=0,this.currentSeqNumsForVariables=new Set,this.debuggingManager.onDoneDebugging((()=>this.refreshEventEmitter.fire()),this)}get refreshRequired(){return this.refreshEventEmitter.event}get active(){return(void 0!==this.debugService.activeDebugSession||this.activeNotebookIsDebugging())&&this.debuggingStarted}async getVariables(e,t){t&&this.watchKernel(t);const n={executionCount:e.executionCount,pageStartIndex:0,pageResponse:[],totalCount:0,refreshCount:e.refreshCount};if(this.active){const t=e.sortColumn,r=(n,r)=>{const i=n[t]?n[t]:"",o=r[t]?r[t]:"";return e.sortAscending?i.localeCompare(o,void 0,{sensitivity:"base"}):o.localeCompare(i,void 0,{sensitivity:"base"})};this.lastKnownVariables.sort(r);const i=e.startIndex?e.startIndex:0,o=e.pageSize?e.pageSize:100;n.pageStartIndex=i;for(let e=i;et.name===e));return n&&(null==t?void 0:t.notebookDocument.uri.fsPath.endsWith(".ipynb"))&&(0,m.sendTelemetryEvent)(g.Telemetry.RunByLineVariableHover),n}}async getDataFrameInfo(e,t,n,r){var i;if(!this.active)return e;r&&(e=await this.getFullVariable(e)),t&&this.watchKernel(t),await this.importDataFrameScripts();let o=e.name;n&&(o=`${e.name}${n}`);const a=await this.evaluate(`${d.DataFrameLoading.DataFrameInfoImportFunc}(${o})`,e.frameId);let c=t?s.basename(t.notebookDocument.uri.fsPath):"";return!c&&(null===(i=this.debugLocation)||void 0===i?void 0:i.fileName)&&(c=s.basename(this.debugLocation.fileName)),a?{...e,...JSON.parse(a.result),maximumRowChunkSize:100,fileName:c}:e}async getDataFrameRows(e,t,n,r,i){if(n-t>100)throw new Error("Debugger cannot provide more than 100 rows at once");if(!this.debugService.activeDebugSession||void 0===e.columns)return{data:[]};r&&this.watchKernel(r);let o=e.name;i&&(o=`${e.name}${i}`),await this.importDataFrameScripts();const s=await this.evaluate(`${d.DataFrameLoading.DataFrameRowImportFunc}(${o}, ${t}, ${n})`,e.frameId);return(0,v.parseDataFrame)(JSON.parse(s.result))}onWillReceiveMessage(e){super.onWillReceiveMessage(e),"request"===e.type&&"variables"===e.command&&e.arguments&&this.currentVariablesReference===e.arguments.variablesReference&&this.currentSeqNumsForVariables.add(e.seq)}onDidSendMessage(e){var t;if(super.onDidSendMessage(e),"response"===e.type&&"initialize"===e.command)this.debuggingStarted=!0;else if("event"===e.type&&"stopped"===e.event&&this.activeNotebookIsDebugging())this.handleNotebookVariables(e);else if("response"===e.type&&"scopes"===e.command&&e.body&&e.body.scopes){const t=e.body.scopes[0].variablesReference;t!==this.currentVariablesReference&&(this.currentVariablesReference=t,this.currentSeqNumsForVariables.clear())}else if("response"===e.type&&"variables"===e.command&&e.body)this.currentSeqNumsForVariables.has(e.request_seq)&&this.updateVariables(void 0,e),this.monkeyPatchDataViewableVariables(e);else if("event"===e.type&&"terminated"===e.event){this.lastKnownVariables=[],this.topMostFrameId=0,this.debuggingStarted=!1,this.refreshEventEmitter.fire();const e=null===(t=this.debugService.activeDebugSession)||void 0===t?void 0:t.id;e&&(this.importedDataFrameScriptsIntoKernel.delete(e),this.importedGetVariableInfoScriptsIntoKernel.delete(e))}}watchKernel(e){const t=e.notebookDocument.uri.toString();if(!this.watchedNotebooks.has(t)){const n=[];n.push(e.onRestarted(this.resetImport.bind(this,t))),n.push(e.onDisposed((()=>{this.resetImport(t),n.forEach((e=>e.dispose())),this.watchedNotebooks.delete(t)}))),this.watchedNotebooks.set(t,n)}}resetImport(e){this.importedDataFrameScriptsIntoKernel.delete(e),this.importedGetVariableInfoScriptsIntoKernel.delete(e)}async evaluate(e,t){if(this.debugService.activeDebugSession){const n=await this.debugService.activeDebugSession.customRequest("evaluate",{expression:e,frameId:this.topMostFrameId||t,context:"repl",format:{rawString:!0}});return n&&"None"!==n.result?n:void(0,l.traceError)(`Cannot evaluate ${e}`)}throw Error("Debugger is not active, cannot evaluate.")}async importDataFrameScripts(){var e;try{const t=null===(e=this.debugService.activeDebugSession)||void 0===e?void 0:e.id;t&&!this.importedDataFrameScriptsIntoKernel.has(t)&&(await this.evaluate(d.DataFrameLoading.DataFrameSysImport),this.importedDataFrameScriptsIntoKernel.add(t))}catch(e){(0,l.traceError)("Error attempting to import in debugger",e)}}async importGetVariableInfoScripts(){var e;try{const t=null===(e=this.debugService.activeDebugSession)||void 0===e?void 0:e.id;t&&!this.importedGetVariableInfoScriptsIntoKernel.has(t)&&(await this.evaluate(d.GetVariableInfo.GetVariableInfoSysImport),this.importedGetVariableInfoScriptsIntoKernel.add(t))}catch(e){(0,l.traceError)("Error attempting to import in debugger",e)}}async getFullVariable(e){await this.importGetVariableInfoScripts();const t=await this.evaluate(`${d.GetVariableInfo.VariableInfoImportFunc}(${e.name})`,e.frameId);return t&&t.result?{...e,truncated:!1,...JSON.parse(t.result)}:e}monkeyPatchDataViewableVariables(e){e.body.variables.forEach((e=>{e.type&&y.has(e.type)&&(e.__vscodeVariableMenuContext="viewableInDataViewer")}))}updateVariables(e,t){var n;const r=this.configService.getSettings(e).variableExplorerExclude?null===(n=this.configService.getSettings().variableExplorerExclude)||void 0===n?void 0:n.split(";"):[],i=t.body.variables.filter((e=>!(!(e.name&&e.type&&e.value)||r&&r.includes(e.type)||e.name.startsWith("_")||b.has(e.name)||"NoneType"===e.type)));this.lastKnownVariables=i.map((e=>w(e))),this.refreshEventEmitter.fire()}activeNotebookIsDebugging(){const e=this.vscNotebook.activeNotebookEditor;return!!e&&this.debuggingManager.isDebugging(e.document)}async handleNotebookVariables(e){var t;const n=null===(t=this.vscNotebook.activeNotebookEditor)||void 0===t?void 0:t.document,r=e.body.threadId;if(n){const e=await this.debuggingManager.getDebugSession(n);if(e){const t=await e.customRequest("stackTrace",{threadId:r,startFrame:0,levels:1});if(t&&t.stackFrames[0]){const r=t.stackFrames[0];let i;if(this.debuggingManager.getDebugMode(n)===f.KernelDebugMode.RunByLine){const t=this.debuggingManager.getDebugCell(n);r.source&&t&&r.source.path===t.document.uri.toString()&&(i=await e.customRequest("scopes",{frameId:r.id}))}else{const t=s.basename(n.uri.toString());r.source&&r.source.path&&r.source.path.includes(t)&&(i=await e.customRequest("scopes",{frameId:r.id}))}i&&(i.scopes.forEach((t=>{e.customRequest("variables",{variablesReference:t.variablesReference})})),this.refreshEventEmitter.fire())}}}}};function w(e){var t;return{name:null!==(t=e.evaluateName)&&void 0!==t?t:e.name,type:e.type,count:0,shape:"",size:0,supportsDataExplorer:y.has(e.type||""),value:e.value,truncated:!0,frameId:e.variablesReference}}_=r([(0,o.injectable)(),i(0,(0,o.inject)(h.IJupyterDebugService)),i(0,(0,o.named)(g.Identifiers.MULTIPLEXING_DEBUGSERVICE)),i(1,(0,o.inject)(f.IDebuggingManager)),i(2,(0,o.inject)(u.IConfigurationService)),i(3,(0,o.inject)(c.IVSCodeNotebook))],_),t.DebuggerVariables=_,t.convertDebugProtocolVariableToIJupyterVariable=w},22350:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.JupyterVariables=void 0;const o=n(86700),s=n(66828),a=n(71733),c=n(5448),l=n(97045),u=n(83474);let d=class{constructor(e,t,n){this.kernelVariables=t,this.debuggerVariables=n,this.refreshEventEmitter=new s.EventEmitter,e.push(n.refreshRequired(this.fireRefresh.bind(this))),e.push(t.refreshRequired(this.fireRefresh.bind(this)))}get refreshRequired(){return this.refreshEventEmitter.event}async getVariables(e,t){return this.variableHandler.getVariables(e,t)}async getFullVariable(e,t){return this.variableHandler.getFullVariable(e,t)}async getMatchingVariable(e,t,n){return this.variableHandler.getMatchingVariable(e,t,n)}async getDataFrameInfo(e,t,n,r){return this.variableHandler.getDataFrameInfo(e,t,n,r)}async getDataFrameRows(e,t,n,r,i){return this.variableHandler.getDataFrameRows(e,t,n,r,i)}get variableHandler(){return this.debuggerVariables.active?this.debuggerVariables:this.kernelVariables}fireRefresh(){this.refreshEventEmitter.fire()}};r([(0,l.captureTelemetry)(u.Telemetry.VariableExplorerFetchTime,void 0,!0)],d.prototype,"getVariables",null),d=r([(0,o.injectable)(),i(0,(0,o.inject)(a.IDisposableRegistry)),i(1,(0,o.inject)(c.IJupyterVariables)),i(1,(0,o.named)(u.Identifiers.KERNEL_VARIABLES)),i(2,(0,o.inject)(c.IJupyterVariables)),i(2,(0,o.named)(u.Identifiers.DEBUGGER_VARIABLES))],d),t.JupyterVariables=d},8488:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelVariables=void 0;const o=n(86700),s=n(66828),a=n(97784),c=n(85058),l=n(71733),u=n(7744),d=n(5448),p=n(83474),h=n(93828),f=/.*?\[.*?;31mType:.*?\[0m\s+(\w+)/,m=/.*?\[.*?;31mValue:.*?\[0m\s+(.*)/,g=/.*?\[.*?;31mString form:.*?\[0m\s*?([\s\S]+?)\n(.*\[.*;31m?)/,v=/.*?\[.*?;31mDocstring:.*?\[0m\s+(.*)/,y=/.*?\[.*?;31mLength:.*?\[0m\s+(.*)/,b=/^\s+\[(\d+) rows x (\d+) columns\]/m,_=new Set(["DataFrame","list","dict","ndarray","Series","Tensor","EagerTensor","DataArray"]);let w=class{constructor(e,t,n,r){this.configService=e,this.experimentService=t,this.disposables=r,this.variableRequesters=new Map,this.notebookState=new WeakMap,this.refreshEventEmitter=new s.EventEmitter,this.variableRequesters.set(a.PYTHON_LANGUAGE,n)}get refreshRequired(){return this.refreshEventEmitter.event}async getVariables(e,t){return this.getVariablesBasedOnKernel(t,e)}async getMatchingVariable(e,t,n){const r=this.notebookState.get(t.notebookDocument);if(r){let i=r.variables.find((t=>t.name===e));return i&&!i.value&&(i=await this.getVariableValueFromKernel(i,t,n)),i}{const r=await this.getVariableNamesAndTypesFromKernel(t,n);if(r){const i=r.find((t=>t.name===e));if(i)return this.getVariableValueFromKernel({name:e,value:void 0,supportsDataExplorer:!1,type:i.type,size:0,count:0,shape:"",truncated:!0},t,n)}}}async getDataFrameInfo(e,t,n,r){const i=(0,h.getKernelConnectionLanguage)(null==t?void 0:t.kernelConnectionMetadata)||a.PYTHON_LANGUAGE,o=this.variableRequesters.get(i);if(o){r&&(e=await this.getFullVariable(e,t));let i=e.name;return n&&(i=`${e.name}${n}`),o.getDataFrameInfo(e,t,i)}return e}async getDataFrameRows(e,t,n,r,i){const o=(0,h.getKernelConnectionLanguage)(null==r?void 0:r.kernelConnectionMetadata)||a.PYTHON_LANGUAGE,s=this.variableRequesters.get(o);if(s){let o=e.name;return i&&(o=`${e.name}${i}`),s.getDataFrameRows(t,n,r,o)}return{data:[]}}async getFullVariable(e,t,n){const r=(0,h.getKernelConnectionLanguage)(null==t?void 0:t.kernelConnectionMetadata)||a.PYTHON_LANGUAGE,i=this.variableRequesters.get(r);return i?i.getFullVariable(e,t,n):e}async getVariablesBasedOnKernel(e,t){var n;let r=this.notebookState.get(e.notebookDocument);r&&r.currentExecutionCount===t.executionCount||(r={currentExecutionCount:t.executionCount,variables:(await this.getVariableNamesAndTypesFromKernel(e)).map((e=>({name:e.name,value:void 0,supportsDataExplorer:!1,type:e.type,size:0,shape:"",count:0,truncated:!0})))});const i=this.configService.getSettings(e.resourceUri).variableExplorerExclude?null===(n=this.configService.getSettings().variableExplorerExclude)||void 0===n?void 0:n.split(";"):[],o={executionCount:t.executionCount,pageStartIndex:-1,pageResponse:[],totalCount:0,refreshCount:t.refreshCount};if(r){const n=t.sortColumn,s=(e,r)=>{const i=e[n]?e[n]:"",o=r[n]?r[n]:"";return t.sortAscending?i.localeCompare(o,void 0,{sensitivity:"base"}):o.localeCompare(i,void 0,{sensitivity:"base"})};r.variables.sort(s);const a=t.startIndex?t.startIndex:0,c=t.pageSize?t.pageSize:100;o.pageStartIndex=a;for(let t=a;t=0?r.variables.splice(t,1):(r.variables[t]=n,o.pageResponse.push(n),t+=1)}this.notebookState.set(e.notebookDocument,r),o.totalCount=r.variables.length}return o}async getVariableProperties(e,t,n){const r=await this.getMatchingVariable(e,t,n),i=this.configService.getSettings().variableTooltipFields,o=(0,h.getKernelConnectionLanguage)(t.kernelConnectionMetadata)||a.PYTHON_LANGUAGE,s=i[o],c=await this.inEnhancedTooltipsExperiment(),l=this.variableRequesters.get(o);return l?l.getVariableProperties(e,t,n,r,s,c):{}}async getVariableNamesAndTypesFromKernel(e,t){const n=(0,h.getKernelConnectionLanguage)(e.kernelConnectionMetadata)||a.PYTHON_LANGUAGE,r=this.variableRequesters.get(n);return r?r.getVariableNamesAndTypesFromKernel(e,t):[]}inspect(e,t,n=0,r){const i=(0,u.createDeferred)();try{e.requestInspect({code:t,cursor_pos:n,detail_level:0}).then((e=>{e&&"ok"===e.content.status?i.resolve(e.content.data):i.resolve(void 0)})).catch((e=>{i.reject(e)}))}catch(e){i.reject(e)}return r&&this.disposables.push(r.onCancellationRequested((()=>i.reject(new s.CancellationError)))),i.promise}async getVariableValueFromKernel(e,t,n){let r={...e};if(!t.disposed&&t.session){const i=await this.inspect(t.session,e.name,0,n);if(i&&i.hasOwnProperty("text/plain")){const e=i["text/plain"].toString(),t=f.exec(e),n=m.exec(e),o=g.exec(e),s=v.exec(e),a=y.exec(e),c=b.exec(e);t&&(r.type=t[1]),r.value=n?n[1]:o?o[1]:s?s[1]:"",a&&(r.count=parseInt(a[1],10)),c&&(r.shape=`(${c[1]}, ${c[2]})`)}i&&i.type&&(r.type=i.type.toString()),i&&i.value&&(r.value=i.value.toString()),_.has(r.type)&&(r.supportsDataExplorer=!0)}return r.type&&r.count&&!r.shape&&(0,h.isPythonKernelConnection)(t.kernelConnectionMetadata)&&r.supportsDataExplorer&&"list"!==r.type&&(r=await this.getFullVariable(r,t)),r}async inEnhancedTooltipsExperiment(){return this.enhancedTooltipsExperimentPromise||(this.enhancedTooltipsExperimentPromise=await this.experimentService.inExperiment(c.Experiments.EnhancedTooltips)),this.enhancedTooltipsExperimentPromise}};w=r([(0,o.injectable)(),i(0,(0,o.inject)(l.IConfigurationService)),i(1,(0,o.inject)(l.IExperimentService)),i(2,(0,o.inject)(d.IKernelVariableRequester)),i(2,(0,o.named)(p.Identifiers.PYTHON_VARIABLES_REQUESTER)),i(3,(0,o.inject)(l.IDisposableRegistry))],w),t.KernelVariables=w},47073:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.PreWarmActivatedJupyterEnvironmentVariables=void 0;const o=n(86700),s=n(98501),a=n(13395),c=n(89114),l=n(71733),u=n(95063),d=n(75213),p=n(5448),h=n(34347),f=n(78140);let m=class{constructor(e,t,n,r,i,o,s,a,c,l){this.activationService=e,this.jupyterInterpreterService=t,this.disposables=n,this.extensionChecker=r,this.apiProvider=i,this.rawNotebookSupported=o,this.envVarsProvider=s,this.workspace=a,this.condaService=c,this.pythonChecker=l}async activate(){var e,t;this.rawNotebookSupported.isSupported||(this.disposables.push(this.jupyterInterpreterService.onDidChangeInterpreter((()=>this.preWarmInterpreterVariables().catch(u.noop)))),this.preWarmInterpreterVariables().ignoreErrors(),this.apiProvider.onDidActivatePythonExtension(this.preWarmInterpreterVariables,this,this.disposables)),this.pythonChecker.isPythonExtensionInstalled&&((null!==(t=null===(e=this.workspace.workspaceFolders)||void 0===e?void 0:e.length)&&void 0!==t?t:0)<=5&&(this.envVarsProvider.getEnvironmentVariables(void 0),(this.workspace.workspaceFolders||[]).forEach((e=>{this.envVarsProvider.getEnvironmentVariables(e.uri)}))),this.condaService.getCondaFile(),this.condaService.getCondaVersion())}async preWarmInterpreterVariables(){if(!this.extensionChecker.isPythonExtensionActive)return;const e=await this.jupyterInterpreterService.getSelectedInterpreter();e&&this.activationService.getActivatedEnvironmentVariables(void 0,e).ignoreErrors()}};m=r([(0,o.injectable)(),i(0,(0,o.inject)(h.IEnvironmentActivationService)),i(1,(0,o.inject)(f.JupyterInterpreterService)),i(2,(0,o.inject)(l.IDisposableRegistry)),i(3,(0,o.inject)(s.IPythonExtensionChecker)),i(4,(0,o.inject)(s.IPythonApiProvider)),i(5,(0,o.inject)(p.IRawNotebookSupportedService)),i(6,(0,o.inject)(d.IEnvironmentVariablesProvider)),i(7,(0,o.inject)(a.IWorkspaceService)),i(8,(0,o.inject)(c.CondaService)),i(9,(0,o.inject)(s.IPythonExtensionChecker))],m),t.PreWarmActivatedJupyterEnvironmentVariables=m},49113:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.PythonVariablesRequester=t.parseDataFrame=void 0;const o=n(86700),s=n(71017),a=n(46318),c=n(60593),l=n(35952),u=n(31134),d=n(4036),p=n(37233),h=n(83474),f=n(93828);function m(e){const t=e.index,n=e.columns;return{data:e.data.map(((e,r)=>{const i={index:t[r]};return n.forEach(((t,n)=>{i[t]=e[n]})),i}))}}t.parseDataFrame=m;let g=class{constructor(e){this.fs=e,this.importedDataFrameScripts=new WeakMap,this.importedGetVariableInfoScripts=new WeakMap}async getDataFrameInfo(e,t,n){await this.importDataFrameScripts(t);const r=t.session?await(0,f.executeSilently)(t.session,`import builtins\nbuiltins.print(${d.DataFrameLoading.DataFrameInfoFunc}(${n}))`,{traceErrors:!0,traceErrorsMessage:"Failure in execute_request for getDataFrameInfo",telemetryName:h.Telemetry.PythonVariableFetchingCodeFailure}):[],i=s.basename(t.notebookDocument.uri.path);return{...e,...this.deserializeJupyterResult(r),fileName:i}}async getDataFrameRows(e,t,n,r){await this.importDataFrameScripts(n);const i=n.session?await(0,f.executeSilently)(n.session,`import builtins\nbuiltins.print(${d.DataFrameLoading.DataFrameRowFunc}(${r}, ${e}, ${t}))`,{traceErrors:!0,traceErrorsMessage:"Failure in execute_request for getDataFrameRows",telemetryName:h.Telemetry.PythonVariableFetchingCodeFailure}):[];return m(this.deserializeJupyterResult(i))}async getVariableProperties(e,t,n,r,i,o){await this.importGetVariableInfoScripts(t);let s={};if(r&&r.value){const n=null==r?void 0:r.type;if(n&&n in i&&o){const e="["+i[n].reduce(((e,t)=>e+`"${t}", `),"")+"]",o=t.session?await(0,f.executeSilently)(t.session,`import builtins\nbuiltins.print(${d.GetVariableInfo.VariablePropertiesFunc}(${r.name}, ${e}))`,{traceErrors:!0,traceErrorsMessage:"Failure in execute_request for getVariableProperties",telemetryName:h.Telemetry.PythonVariableFetchingCodeFailure}):[];s={...s,...this.deserializeJupyterResult(o)}}else s[`${e}`]=r.value}return s}async getVariableNamesAndTypesFromKernel(e,t){if(e.session){await this.importGetVariableInfoScripts(e);const t=e.session?await(0,f.executeSilently)(e.session,`import builtins\n_rwho_ls = %who_ls\nbuiltins.print(${d.GetVariableInfo.VariableTypesFunc}(_rwho_ls))`,{traceErrors:!0,traceErrorsMessage:"Failure in execute_request for getVariableNamesAndTypesFromKernel",telemetryName:h.Telemetry.PythonVariableFetchingCodeFailure}):[],n=this.deserializeJupyterResult(t),r=[];for(const[e,t]of Object.entries(n)){const n={name:e,value:void 0,supportsDataExplorer:!1,type:t||"",size:0,shape:"",count:0,truncated:!0};r.push(n)}return r}return[]}async getFullVariable(e,t,n){await this.importGetVariableInfoScripts(t);const r=t.session?await(0,f.executeSilently)(t.session,`import builtins\nbuiltins.print(${d.GetVariableInfo.VariableInfoFunc}(${e.name}))`,{traceErrors:!0,traceErrorsMessage:"Failure in execute_request for getFullVariable",telemetryName:h.Telemetry.PythonVariableFetchingCodeFailure}):[];return{...e,...this.deserializeJupyterResult(r)}}async importDataFrameScripts(e){const t=e.notebookDocument;if(!this.importedDataFrameScripts.get(t)){const n=[],r=()=>{this.importedDataFrameScripts.delete(t),n.forEach((e=>e.dispose()))};n.push(e.onDisposed(r)),n.push(e.onRestarted(r)),await this.runScriptFile(e,d.DataFrameLoading.ScriptPath),this.importedDataFrameScripts.set(e.notebookDocument,!0)}}async importGetVariableInfoScripts(e){const t=e.notebookDocument;if(!this.importedGetVariableInfoScripts.get(t)){const n=[],r=()=>{this.importedGetVariableInfoScripts.delete(t),n.forEach((e=>e.dispose()))};n.push(e.onDisposed(r)),n.push(e.onRestarted(r)),await this.runScriptFile(e,d.GetVariableInfo.ScriptPath),this.importedGetVariableInfoScripts.set(e.notebookDocument,!0)}}async runScriptFile(e,t){if(await this.fs.localFileExists(t)){const n=await this.fs.readLocalFile(t);return e.session?(0,f.executeSilently)(e.session,n):[]}(0,a.traceError)("Cannot run non-existant script file")}extractJupyterResultText(e){if(e.length>0){const t=e[0];if(t&&"stream"===t.output_type&&"stderr"===t.name&&t.hasOwnProperty("text")){const e=t.text;if(e.includes("iopub_data_rate_limit"))throw new p.JupyterDataRateLimitError;{const t=l.DataScience.jupyterGetVariablesExecutionError().format(e);throw(0,a.traceError)(t),new Error(t)}}if(t&&"execute_result"===t.output_type){const e=t.data;if(e&&e.hasOwnProperty("text/plain"))return e["text/plain"]}if(t&&"stream"===t.output_type&&t.hasOwnProperty("text"))return t.text;if(t&&"error"===t.output_type&&t.hasOwnProperty("traceback")){const e=t.traceback.map(u.stripAnsi).join("\r\n"),n=l.DataScience.jupyterGetVariablesExecutionError().format(e);throw(0,a.traceError)(n),new Error(n)}}throw new Error(l.DataScience.jupyterGetVariablesBadResults())}deserializeJupyterResult(e){const t=this.extractJupyterResultText(e);return JSON.parse(t)}};g=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IFileSystem))],g),t.PythonVariablesRequester=g},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InteractiveWindowView=t.JupyterNotebookView=void 0,t.JupyterNotebookView="jupyter-notebook",t.InteractiveWindowView="interactive"},41098:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelFilterService=void 0;const o=n(86700),s=n(66828),a=n(13395),c=n(2687),l=n(46318),u=n(71733);let d=class{constructor(e,t,n,r){this.config=e,this.workspace=t,this.pathUtils=r,this.disposables=[],this._onDidChange=new s.EventEmitter,n.push(this)}get onDidChange(){return this._onDidChange.event}dispose(){this._onDidChange.dispose(),(0,c.disposeAllDisposables)(this.disposables)}isKernelHidden(e){const t=this.getFilters();return"connectToLiveKernel"!==e.kind&&"startUsingRemoteKernelSpec"!==e.kind&&t.some((t=>"startUsingLocalKernelSpec"===e.kind&&"jupyterKernelspec"===t.type&&e.kernelSpec.specFile?t.path.toLowerCase()===this.pathUtils.getDisplayName(e.kernelSpec.specFile).toLowerCase():"startUsingPythonInterpreter"===e.kind&&"pythonEnvironment"===t.type&&t.path.toLowerCase()===this.pathUtils.getDisplayName(e.interpreter.path).toLowerCase()))}getFilters(){if(!this.workspace.workspaceFolders||0===this.workspace.workspaceFolders.length)return this.workspace.getConfiguration("jupyter",void 0).get("kernels.filter",[]);const e=[];return this.workspace.workspaceFolders.forEach((t=>{e.push(...this.workspace.getConfiguration("jupyter",t.uri).get("kernels.filter",[]))})),e}async storeHiddenKernels(e){const t=new Set,n=e.map((e=>{const n=this.translateConnectionToFilter(e);if(n&&!t.has(null==n?void 0:n.path))return t.add(n.path),n})).filter((e=>!!e)).map((e=>e)),r=(this.workspace.workspaceFolders||[]).map((e=>e.uri));r.length>0?await Promise.all(r.map((e=>this.config.updateSetting("kernels.filter",n,e,s.ConfigurationTarget.Workspace)))):await this.config.updateSetting("kernels.filter",n,void 0,s.ConfigurationTarget.Global),this._onDidChange.fire()}translateConnectionToFilter(e){if("connectToLiveKernel"!==e.kind)return"startUsingLocalKernelSpec"===e.kind&&e.kernelSpec.specFile?{path:this.pathUtils.getDisplayName(e.kernelSpec.specFile),type:"jupyterKernelspec"}:"startUsingPythonInterpreter"===e.kind?{path:this.pathUtils.getDisplayName(e.interpreter.path),type:"pythonEnvironment"}:void 0;(0,l.traceVerbose)("Hiding default or live kernels via filter is not supported")}};d=r([(0,o.injectable)(),i(0,(0,o.inject)(u.IConfigurationService)),i(1,(0,o.inject)(a.IWorkspaceService)),i(2,(0,o.inject)(u.IDisposableRegistry)),i(3,(0,o.inject)(u.IPathUtils))],d),t.KernelFilterService=d},56807:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelFilterUI=void 0;const o=n(86700),s=n(13395),a=n(2687),c=n(71733),l=n(35952),u=n(95063),d=n(93828),p=n(24453),h=n(41098);let f=class{constructor(e,t,n,r,i,o,s){this.controllers=e,this.commandManager=t,this.appShell=n,this.kernelFilter=i,this.pathUtils=o,this.workspace=s,this.disposables=[],r.push(this)}activate(){this.disposables.push(this.commandManager.registerCommand("jupyter.filterKernels",this.showUI,this))}dispose(){(0,a.disposeAllDisposables)(this.disposables)}async showUI(){const e=this.appShell.createQuickPick(),t=new Set;let n=!1;e.canSelectMany=!1,e.placeholder=l.DataScience.kernelFilterPlaceholder(),e.busy=!0,e.enabled=!1,this.controllers.kernelConnections.then((r=>{if(n)return;const i=r.filter((e=>!t.has(e.id)&&(t.add(e.id),!0))).map((e=>({label:(0,d.getDisplayNameOrNameOfKernelConnection)(e),picked:!this.kernelFilter.isKernelHidden(e),description:(0,d.getKernelConnectionPath)(e,this.pathUtils,this.workspace),detail:"connectToLiveKernel"===e.kind?(0,d.getRemoteKernelSessionInformation)(e):"",connection:e})));i.sort(((e,t)=>e.label.localeCompare(t.label))),e.canSelectMany=!0,e.activeItems=i,e.items=i,e.matchOnDescription=!0,e.matchOnDetail=!0,e.sortByLabel=!0,e.selectedItems=i.filter((e=>e.picked)),e.placeholder=l.DataScience.kernelFilterPlaceholder(),e.enabled=!0,e.busy=!1})).catch(u.noop);const r=[];e.show(),e.onDidHide((()=>{n=!0,(0,a.disposeAllDisposables)(r)}),this,r),e.onDidAccept((()=>{n=!0,e.hide(),(0,a.disposeAllDisposables)(r);const t=new Set(e.selectedItems.map((e=>e.connection))),i=e.items.map((e=>e.connection)).filter((e=>!t.has(e)));this.kernelFilter.storeHiddenKernels(i.map((e=>e)))}),this,r)}};f=r([(0,o.injectable)(),i(0,(0,o.inject)(p.INotebookControllerManager)),i(1,(0,o.inject)(s.ICommandManager)),i(2,(0,o.inject)(s.IApplicationShell)),i(3,(0,o.inject)(c.IDisposableRegistry)),i(4,(0,o.inject)(h.KernelFilterService)),i(5,(0,o.inject)(c.IPathUtils)),i(6,(0,o.inject)(s.IWorkspaceService))],f),t.KernelFilterUI=f},18556:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findNotebookEditor=t.switchKernel=t.selectKernel=void 0;const r=n(97784),i=n(46318),o=n(72858),s=n(41292);function a(e,t,n){var r,i,a;const c="notebook"===(0,o.getResourceType)(e)?t.notebookDocuments.find((t=>t.uri.toString()===(null==e?void 0:e.toString()))):void 0,l=c&&(null===(r=t.activeNotebookEditor)||void 0===r?void 0:r.document)===c?t.activeNotebookEditor:void 0,u=e&&"interactive"===(0,o.getResourceType)(e)?null===(i=null==n?void 0:n.get(e))||void 0===i?void 0:i.notebookEditor:void 0,d="interactive"===(0,o.getResourceType)(e)&&n?null===(a=(0,s.getActiveInteractiveWindow)(n))||void 0===a?void 0:a.notebookEditor:void 0;return l||u||d}t.selectKernel=async function(e,t,n,r){const o=a(e,t,n);return o?r.executeCommand("notebook.selectKernel",{notebookEditor:o}):((0,i.traceError)("Unable to select kernel as the Notebook document could not be identified"),!1)},t.switchKernel=async function(e,t,n,o,s){if(a(e,t,n))return o.executeCommand("notebook.selectKernel",{id:s.id,extension:r.JVSC_EXTENSION_ID});(0,i.traceError)("Unable to select kernel as the Notebook document could not be identified")},t.findNotebookEditor=a},73440:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.LiveKernelSwitcher=void 0;const o=n(86700),s=n(13395),a=n(46318),c=n(71733),l=n(43367),u=n(24453),d=n(18556);let p=class{constructor(e,t,n,r,i,o){this.disposables=e,this.kernelProvider=t,this.vscNotebook=n,this.controllerManager=r,this.memento=i,this.commandManager=o}async activate(){this.controllerManager.remoteRefreshed(this.onLiveRefresh,this,this.disposables),this.vscNotebook.onDidOpenNotebookDocument(this.onDidOpenNotebook,this,this.disposables)}getKey(e){return`jupyter-notebook-remote-session-${e.fsPath}`}onDidOpenNotebook(e){const t=this.getKey(e.uri),n=this.memento.get(t);n&&this.controllerManager.kernelConnections.then((async r=>{const i=this.controllerManager.getSelectedNotebookController(e),o=r.find((e=>e.id===n));o&&(null==i?void 0:i.id)!==o.id?await(0,d.switchKernel)(e.uri,this.vscNotebook,void 0,this.commandManager,o):await this.memento.update(t,void 0)})).catch((e=>(0,a.traceError)(e)))}onLiveRefresh(e){this.vscNotebook.notebookDocuments.forEach((async t=>{const n=this.kernelProvider.get(t);if(n){const r=e.find((e=>{var t;return e.kernelModel.id===(null===(t=n.session)||void 0===t?void 0:t.kernelId)}));if(r){const e=this.getKey(t.uri);await this.memento.update(e,r.id)}}}))}};p=r([(0,o.injectable)(),i(0,(0,o.inject)(c.IDisposableRegistry)),i(1,(0,o.inject)(l.IKernelProvider)),i(2,(0,o.inject)(s.IVSCodeNotebook)),i(3,(0,o.inject)(u.INotebookControllerManager)),i(4,(0,o.inject)(c.IMemento)),i(4,(0,o.named)(c.WORKSPACE_MEMENTO)),i(5,(0,o.inject)(s.ICommandManager))],p),t.LiveKernelSwitcher=p},32520:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoPythonKernelsNotebookController=void 0;const r=n(2687),i=n(35952),o=n(95063),s=n(97045),a=n(83474),c=n(82232);t.NoPythonKernelsNotebookController=class{constructor(e,t,n,r,i,o){this.notebookApi=t,this.commandManager=n,this.pythonExtensionChecker=i,this.appShell=o,this.disposables=[],r.push(this),this.controller=this.notebookApi.createNotebookController(`NoPythonController_${e}`,e,"Python 3",this.handleExecution.bind(this)),this.disposables.push(this.controller),this.controller.description="",this.controller.detail="python3",this.controller.supportedLanguages=a.LanguagesSupportedByPythonkernel}dispose(){(0,r.disposeAllDisposables)(this.disposables)}async updateNotebookAffinity(e,t){this.controller.updateNotebookAffinity(e,t),this.updateLabels(e)}updateLabels(e){var t,n;const r=(0,c.getNotebookMetadata)(e);(0,c.isPythonNotebook)(r)&&(this.controller.label=(null===(t=null==r?void 0:r.kernelspec)||void 0===t?void 0:t.display_name)||(null===(n=null==r?void 0:r.kernelspec)||void 0===n?void 0:n.name)||this.controller.label)}async handleExecution(e){this.pythonExtensionChecker.isPythonExtensionInstalled?await this.handleExecutionWithoutPython():await this.handleExecutionWithoutPythonExtension()}async handleExecutionWithoutPythonExtension(){(0,s.sendTelemetryEvent)(a.Telemetry.PythonExtensionNotInstalled,void 0,{action:"displayed"}),await this.appShell.showInformationMessage(i.DataScience.pythonExtensionRequiredToRunNotebook(),{modal:!0},i.Common.install())===i.Common.install()?((0,s.sendTelemetryEvent)(a.Telemetry.PythonExtensionNotInstalled,void 0,{action:"download"}),this.commandManager.executeCommand("extension.open",a.PythonExtension).then(o.noop,o.noop)):(0,s.sendTelemetryEvent)(a.Telemetry.PythonExtensionNotInstalled,void 0,{action:"dismissed"})}async handleExecutionWithoutPython(){(0,s.sendTelemetryEvent)(a.Telemetry.PythonNotInstalled,void 0,{action:"displayed"}),await this.appShell.showErrorMessage(i.DataScience.pythonNotInstalledNonMarkdown(),{modal:!0},i.Common.install())===i.Common.install()?((0,s.sendTelemetryEvent)(a.Telemetry.PythonNotInstalled,void 0,{action:"download"}),this.appShell.openUrl("https://www.python.org/downloads")):(0,s.sendTelemetryEvent)(a.Telemetry.PythonNotInstalled,void 0,{action:"dismissed"})}}},83867:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.NotebookControllerManager=void 0;const o=n(86700),s=n(66828),a=n(66828),c=n(98501),l=n(13395),u=n(97784),d=n(46318),p=n(29140),h=n(89114),f=n(71733),m=n(7744),g=n(28735),v=n(35952),y=n(95063),b=n(88319),_=n(17261),w=n(58363),S=n(32417),C=n(5448),k=n(48497),E=n(29474),x=n(36462),T=n(21687),D=n(97045),I=n(83474),P=n(44538),R=n(93828),M=n(94137),O=n(10473),L=n(40196),N=n(46975),A=n(43367),j=n(73913),F=n(82232),U=n(41098),q=n(32520),W=n(70720);let H=class{constructor(e,t,n,r,i,o,s,c,l,u,d,p,h,f,m,g,v,y,b,_,w,S,C,k,E,x){this.notebook=e,this.disposables=t,this.extensions=n,this.localKernelFinder=r,this.configuration=i,this.notebookProvider=o,this.commandManager=s,this.context=c,this.kernelProvider=l,this.preferredRemoteKernelIdProvider=u,this.remoteKernelFinder=d,this.pathUtils=p,this.widgetCoordinator=h,this.languageService=f,this.workspace=m,this.extensionChecker=g,this.docManager=v,this.pythonApi=y,this.interpreters=b,this.appShell=_,this.kernelFilter=w,this.browser=S,this.condaService=C,this.jupyterServerSelector=k,this.serverUriStorage=E,this.serviceContainer=x,this._onNotebookControllerSelectionChanged=new a.EventEmitter,this.interactiveControllerIdSuffix=" (Interactive)",this.registeredControllers=new Map,this.selectedControllers=new Map,this.preferredControllers=new Map,this.remoteRefreshedEmitter=new a.EventEmitter,this._onNotebookControllerSelected=new a.EventEmitter,this.disposables.push(this._onNotebookControllerSelected),this.disposables.push(this._onNotebookControllerSelectionChanged),this.kernelFilter.onDidChange(this.onDidChangeKernelFilter,this,this.disposables)}get allKernelConnections(){return Array.from(this.registeredControllers.values()).map((e=>e.connection))}get onNotebookControllerSelectionChanged(){return this._onNotebookControllerSelectionChanged.event}get kernelConnections(){return this.loadNotebookControllers().then((()=>this.allKernelConnections))}get controllersLoaded(){return!0===this._controllersLoaded}get remoteRefreshed(){return this.remoteRefreshedEmitter.event}get isLocalLaunch(){return(0,R.isLocalLaunch)(this.configuration)}async getActiveInterpreterOrDefaultController(e,t){return this.isLocalLaunch?((0,d.traceInfoIfCI)("CreateActiveInterpreterController"),this.createActiveInterpreterController(e,t)):((0,d.traceInfoIfCI)("CreateDefaultRemoteController"),this.createDefaultRemoteController())}getControllerForConnection(e,t){const n="jupyter-notebook"===t?e.id:`${e.id}${this.interactiveControllerIdSuffix}`;return this.registeredControllers.get(n)}get onNotebookControllerSelected(){return this._onNotebookControllerSelected.event}getSelectedNotebookController(e){return this.selectedControllers.get(e.uri.toString())}getPreferredNotebookController(e){return this.preferredControllers.get(e)}activate(){this.notebook.onDidOpenNotebookDocument(this.onDidOpenNotebookDocument,this,this.disposables),this.notebook.notebookDocuments.forEach((e=>this.onDidOpenNotebookDocument(e).catch(y.noop))),this.extensions.onDidChange(this.onDidChangeExtensions,this,this.disposables),this.condaService.onCondaEnvironmentsChanged(this.onDidChangeCondaEnvironments,this,this.disposables)}registeredNotebookControllers(){return Array.from(this.registeredControllers.values())}async loadNotebookControllers(e){if(!this.controllersPromise||e){const e=new b.StopWatch;this.loadLocalNotebookControllersImpl("ignoreCache").catch((e=>(0,d.traceError)("Failed to fetch controllers without cache",e))).finally((()=>{let e;this._controllersLoaded=!0,this.interpreters.onDidChangeInterpreters((()=>{e&&clearTimeout(e),e=setTimeout((()=>this.loadLocalNotebookControllersImpl("ignoreCache").catch((e=>(0,d.traceError)("Failed to re-query python kernels after changes to list of interpreters",e)))),1e3)}),this,this.disposables)}));const t=[this.loadLocalNotebookControllersImpl("useCache")];this.isLocalLaunch||t.push(this.loadRemoteNotebookControllersImpl()),this.controllersPromise=Promise.all(t).then((()=>(0,y.noop)())).catch((e=>{throw(0,d.traceError)("Error loading notebook controllers",e),e})).finally((()=>{if(!this.isLocalLaunch){const e=new a.CancellationTokenSource;this.updateRemoteConnections(e.token).catch(y.noop).finally((()=>e.dispose()))}(0,w.sendKernelListTelemetry)(s.Uri.file("test.ipynb"),Array.from(this.registeredControllers.values()).map((e=>e.connection)),e),(0,d.traceInfoIfCI)(`Providing notebook controllers with length ${this.registeredControllers.size}.`)}))}return this.controllersPromise}getOrCreateControllerForActiveInterpreter(e,t){const n=(0,R.createInterpreterKernelSpec)(e),r={kind:"startUsingPythonInterpreter",kernelSpec:n,interpreter:e,id:(0,R.getKernelId)(n,e)};return this.createNotebookControllers([r],"interactive"===t),this.registeredNotebookControllers().find((e=>e.controller.notebookType===t&&"startUsingPythonInterpreter"===e.connection.kind&&e.connection.id===r.id))}async onDidChangeCondaEnvironments(){if(!this.extensionChecker.isPythonExtensionInstalled)return;const e=(await this.interpreters.getInterpreters()).filter((e=>e.envType===T.EnvironmentType.Conda)).length;await this.interpreters.refreshInterpreters(),await this.loadNotebookControllers(!0),await(0,m.waitForCondition)((async()=>(await this.interpreters.getInterpreters()).filter((e=>e.envType===T.EnvironmentType.Conda)).length>e||(await this.interpreters.refreshInterpreters(),!1)),15e3,5e3),await this.loadNotebookControllers(!0)}async createActiveInterpreterController(e,t){const n=await this.pythonApi.getApi(),r=await n.getActiveInterpreter(t);if(r)return(0,d.traceInfo)(`Creating controller for ${e} with interpreter ${(0,p.getDisplayPath)(r.path)}`),this.getOrCreateControllerForActiveInterpreter(r,e);(0,d.traceWarning)(`Unable to create a controller for ${e} without an active interpreter.`)}async createDefaultRemoteController(){await this.loadNotebookControllers();const e=this.registeredNotebookControllers();if(0===e.length)return void(0,d.traceError)("No remote controllers");let t,n,r;return e.forEach((e=>{"startUsingRemoteKernelSpec"===e.connection.kind&&("python"===e.connection.kernelSpec.name?n=e:"python3"===e.connection.kernelSpec.name?t=e:e.connection.kernelSpec.language===u.PYTHON_LANGUAGE&&(r=e))})),t||n||r||e[0]}async loadLocalNotebookControllersImpl(e){const t=new a.CancellationTokenSource;this.wasPythonInstalledWhenFetchingControllers=this.extensionChecker.isPythonExtensionInstalled;let n=await this.localKernelFinder.listKernels(void 0,t.token,e).catch((e=>((0,d.traceError)("Failed to get local kernel connections",e),[])));n=n.filter((e=>!this.kernelFilter.isKernelHidden(e))),this.createNotebookControllers(n),n.some((e=>(0,R.isPythonKernelConnection)(e)))?this.removeNoPythonControllers():this.registerNoPythonControllers()}async loadRemoteNotebookControllersImpl(){const e=new a.CancellationTokenSource;this.wasPythonInstalledWhenFetchingControllers=this.extensionChecker.isPythonExtensionInstalled;let t=await this.getRemoteKernelConnectionMetadata(e.token);t=t.filter((e=>!this.kernelFilter.isKernelHidden(e))),this.createNotebookControllers(t)}removeNoPythonControllers(){var e,t;null===(e=this.notebookNoPythonController)||void 0===e||e.dispose(),null===(t=this.interactiveNoPythonController)||void 0===t||t.dispose(),this.notebookNoPythonController=void 0,this.interactiveNoPythonController=void 0}registerNoPythonControllers(){this.notebookNoPythonController||(this.notebookNoPythonController=new q.NoPythonKernelsNotebookController(j.JupyterNotebookView,this.notebook,this.commandManager,this.disposables,this.extensionChecker,this.appShell),this.interactiveNoPythonController=new q.NoPythonKernelsNotebookController(j.InteractiveWindowView,this.notebook,this.commandManager,this.disposables,this.extensionChecker,this.appShell),this.disposables.push(this.interactiveNoPythonController),this.disposables.push(this.notebookNoPythonController))}async onDidChangeExtensions(){this.isLocalLaunch&&this.controllersPromise&&!this.wasPythonInstalledWhenFetchingControllers&&this.extensionChecker.isPythonExtensionInstalled&&(this.controllersPromise=void 0,await this.loadNotebookControllers())}removeRemoteKernelControllers(){Array.from(this.registeredControllers.values()).filter((e=>!(0,A.isLocalConnection)(e.connection))).forEach((e=>{this.registeredControllers.delete(e.connection.id),e.dispose()}))}reloadControllersAfterChangingRemote(){if(this.handlerAddedForChangesToRemoteKernelUri)return;this.handlerAddedForChangesToRemoteKernelUri=!0;let e=this.isLocalLaunch;const t=async()=>{if(this.isLocalLaunch)return this.removeRemoteKernelControllers(),e||this.loadRemoteNotebookControllersImpl(),void(e=!0);e=!1;const t=new a.CancellationTokenSource;let n=await this.getRemoteKernelConnectionMetadata(t.token);await this.updateRemoteConnections(t.token,n),t.dispose();const r=this.allKernelConnections.filter((e=>"connectToLiveKernel"===e.kind));this.remoteRefreshedEmitter.fire(r)};this.serverUriStorage.onDidChangeUri(t,this,this.disposables),this.kernelProvider.onDidStartKernel(t,this,this.disposables),this.kernelProvider.onDidDisposeKernel((()=>{t(),setTimeout(t,2e3)}),this,this.disposables)}async onDidOpenNotebookDocument(e){if(e.notebookType!==j.JupyterNotebookView&&e.notebookType!==j.InteractiveWindowView||!this.workspace.isTrusted)return;const t=new a.CancellationTokenSource,n=this.notebook.onDidCloseNotebookDocument((n=>n===e?t.cancel():void 0),this,this.disposables);(0,d.traceInfoIfCI)(`Clear controller mapping for ${(0,p.getDisplayPath)(e.uri)}`);const r=this.loadNotebookControllers();this.isLocalLaunch||r.finally((()=>{this.isLocalLaunch||this.failedToFetchRemoteKernels&&this.appShell.showErrorMessage(v.DataScience.jupyterRemoteConnectFailedModalMessage(),{modal:!0},v.DataScience.changeJupyterRemoteConnection(),v.DataScience.showJupyterLogs()).then((e=>{switch(e){case v.DataScience.changeJupyterRemoteConnection():this.jupyterServerSelector.selectJupyterURI(!0,"prompt");break;case v.DataScience.showJupyterLogs():this.commandManager.executeCommand("jupyter.viewOutput")}}))})),(0,F.isPythonNotebook)((0,F.getNotebookMetadata)(e))&&this.extensionChecker.isPythonExtensionInstalled&&this.createActiveInterpreterController(j.JupyterNotebookView,e.uri).catch(y.noop);try{let i,o;if(e.notebookType===j.JupyterNotebookView){if(this.reloadControllersAfterChangingRemote(),this.isLocalLaunch||this.localKernelFinder.findPreferredLocalKernelConnectionFromCache((0,F.getNotebookMetadata)(e)))i=await this.localKernelFinder.findKernel(e.uri,(0,F.getNotebookMetadata)(e),t.token);else{await this.updateRemoteConnections(t.token);const n=new _.DisplayOptions(!1);try{const r=await this.notebookProvider.connect({resource:e.uri,ui:n,kind:"remoteJupyter",token:t.token});i=await this.remoteKernelFinder.findKernel(e.uri,r,(0,F.getNotebookMetadata)(e),t.token)}finally{n.dispose()}}if(t.token.isCancellationRequested&&!i)return void(0,d.traceInfo)("Find preferred kernel cancelled");if(!i)return void(0,d.traceInfoIfCI)(`PreferredConnection not found for NotebookDocument: ${(0,p.getDisplayPath)(e.uri)}`);(0,d.traceInfo)(`PreferredConnection: ${i.id} found for NotebookDocument: ${(0,p.getDisplayPath)(e.uri)}`),Array.from(this.registeredControllers.values()).find((e=>(null==i?void 0:i.id)===e.connection.id))||((0,d.traceInfo)(`Early registration of controller for Kernel connection ${i.id}`),this.createNotebookControllers([i]))}else{await r;const t=await this.getActiveInterpreterOrDefaultController("interactive",e.uri);i=null==t?void 0:t.connection}if(i){const t="interactive"===e.notebookType?`${i.id}${this.interactiveControllerIdSuffix}`:i.id;o=this.registeredControllers.get(t)}o?((0,d.traceInfo)(`TargetController found ID: ${o.id} for document ${(0,p.getDisplayPath)(e.uri)}`),await o.updateNotebookAffinity(e,s.NotebookControllerAffinity.Preferred),(0,S.trackKernelResourceInformation)(e.uri,{kernelConnection:i,isPreferredKernel:!0}),this.preferredControllers.set(e,o)):(0,d.traceInfoIfCI)(`TargetController not found ID: ${null==i?void 0:i.id} for document ${(0,p.getDisplayPath)(e.uri)}`)}catch(e){(0,d.traceError)("Failed to find & set preferred controllers",e)}finally{n.dispose()}}onDidChangeKernelFilter(){const e=this.allKernelConnections.filter((e=>!this.kernelFilter.isKernelHidden(e)));this.createNotebookControllers(e),Array.from(this.registeredControllers.values()).forEach((e=>{this.kernelFilter.isKernelHidden(e.connection)&&!this.isControllerAttachedToADocument(e)&&e.dispose()}))}isControllerAttachedToADocument(e){return this.notebook.notebookDocuments.some((t=>e.isAssociatedWithDocument(t)))}createNotebookControllers(e,t){e.map((e=>({connection:e,label:(0,R.getDisplayNameOrNameOfKernelConnection)(e)}))).forEach((e=>{this.createNotebookController(e.connection,e.label,t)}))}createNotebookController(e,t,n){try{[[e.id,j.JupyterNotebookView],[`${e.id}${this.interactiveControllerIdSuffix}`,j.InteractiveWindowView]].filter((([t])=>{const n=this.registeredControllers.get(t);return!n||(!(0,R.isPythonKernelConnection)(e)||"startUsingLocalKernelSpec"!==e.kind&&"startUsingPythonInterpreter"!==e.kind||n.updateInterpreterDetails(e),!1)})).forEach((([r,i])=>{let o=!1;if("connectToLiveKernel"===e.kind&&(o=(i!==j.InteractiveWindowView||!n)&&this.kernelFilter.isKernelHidden(e)),o)return;const s=new W.VSCodeNotebookController(e,r,i,t,this.notebook,this.commandManager,this.kernelProvider,this.preferredRemoteKernelIdProvider,this.context,this.pathUtils,this.disposables,this.languageService,this.workspace,this.configuration,this.widgetCoordinator,this.docManager,this.appShell,this.browser,this.extensionChecker,this.serviceContainer);s.onNotebookControllerSelected(this.handleOnNotebookControllerSelected,this,this.disposables),s.onNotebookControllerSelectionChanged((()=>this._onNotebookControllerSelectionChanged.fire()),this,this.disposables),s.onDidDispose((()=>{this.registeredControllers.delete(s.id)}),this,this.disposables),this.disposables.push(s),this.registeredControllers.set(s.id,s)}))}catch(t){(0,D.sendTelemetryEvent)(I.Telemetry.FailedToCreateNotebookController,void 0,{kind:e.kind},t,!0),(0,d.traceError)(`Failed to create notebook controller for ${e.id}`,t)}}async handleOnNotebookControllerSelected(e){var t;(0,d.traceInfoIfCI)(`Controller ${null===(t=e.controller)||void 0===t?void 0:t.id} selected`),this.selectedControllers.set(e.notebook.uri.toString(),e.controller),this._onNotebookControllerSelected.fire(e)}async getRemoteKernelConnectionMetadata(e){const t=new _.DisplayOptions(!1);try{const n=await this.notebookProvider.connect({resource:void 0,ui:t,kind:"remoteJupyter",token:e}),r=await this.remoteKernelFinder.listKernels(void 0,n,e);return this.failedToFetchRemoteKernels=!1,r}catch(e){return this.failedToFetchRemoteKernels=!0,(0,d.traceError)("Failed to get remote kernel connections",e),[]}finally{t.dispose()}}async updateRemoteConnections(e,t){if((0,d.traceInfoIfCI)("Updating remote connections"),await this.loadNotebookControllers(),t=t||await this.getRemoteKernelConnectionMetadata(e),(0,d.traceInfoIfCI)(`Current remote connections, ${JSON.stringify(t)}`),e.isCancellationRequested||!t)return(0,d.traceInfo)("Cancelled loading notebook controllers"),[];t.forEach((e=>{const t=this.registeredControllers.get(e.id);t&&"connectToLiveKernel"===e.kind&&t.updateRemoteKernelDetails(e);const n=this.registeredControllers.get(`${e.id}${this.interactiveControllerIdSuffix}`);n&&"connectToLiveKernel"===e.kind&&n.updateRemoteKernelDetails(e)}));const n=t.filter((e=>!this.registeredControllers.has(e.id))),r=Array.from(this.registeredControllers.values()).filter((e=>!(0,A.isLocalConnection)(e.connection))).filter((e=>!t.some((t=>t.id===e.connection.id))));n.length>0&&n.map((e=>({connection:e,label:(0,R.getDisplayNameOrNameOfKernelConnection)(e)}))).forEach((e=>{this.createNotebookController(e.connection,e.label)})),r.forEach((e=>{this.registeredControllers.delete(e.id),(0,d.traceInfoIfCI)(`Disposing controller ${e.id}`),e.dispose()}))}};r([(0,g.debounceAsync)(1e3)],H.prototype,"onDidChangeCondaEnvironments",null),r([x.traceDecorators.verbose("Get default Remote Controller")],H.prototype,"createDefaultRemoteController",null),H=r([(0,o.injectable)(),i(0,(0,o.inject)(l.IVSCodeNotebook)),i(1,(0,o.inject)(f.IDisposableRegistry)),i(2,(0,o.inject)(f.IExtensions)),i(3,(0,o.inject)(N.ILocalKernelFinder)),i(4,(0,o.inject)(f.IConfigurationService)),i(5,(0,o.inject)(C.INotebookProvider)),i(6,(0,o.inject)(l.ICommandManager)),i(7,(0,o.inject)(f.IExtensionContext)),i(8,(0,o.inject)(A.IKernelProvider)),i(9,(0,o.inject)(L.PreferredRemoteKernelIdProvider)),i(10,(0,o.inject)(N.IRemoteKernelFinder)),i(11,(0,o.inject)(f.IPathUtils)),i(12,(0,o.inject)(M.NotebookIPyWidgetCoordinator)),i(13,(0,o.inject)(P.NotebookCellLanguageService)),i(14,(0,o.inject)(l.IWorkspaceService)),i(15,(0,o.inject)(c.IPythonExtensionChecker)),i(16,(0,o.inject)(l.IDocumentManager)),i(17,(0,o.inject)(c.IPythonApiProvider)),i(18,(0,o.inject)(k.IInterpreterService)),i(19,(0,o.inject)(l.IApplicationShell)),i(20,(0,o.inject)(U.KernelFilterService)),i(21,(0,o.inject)(f.IBrowserService)),i(22,(0,o.inject)(h.CondaService)),i(23,(0,o.inject)(O.JupyterServerSelector)),i(24,(0,o.inject)(C.IJupyterServerUriStorage)),i(25,(0,o.inject)(E.IServiceContainer))],H),t.NotebookControllerManager=H},44587:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteSwitcher=void 0;const o=n(86700),s=n(96486),a=n(66828),c=n(13395),l=n(71733),u=n(35952),d=n(4036),p=n(5448),h=n(83474),f=n(10473),m=n(82232),g=n(24453);let v=class{constructor(e,t,n,r,i,o,s,a){this.serverUriStorage=e,this.documentManager=t,this.notebook=n,this.commandManager=r,this.disposableRegistry=i,this.appShell=o,this.serverSelector=s,this.notebookControllerManager=a,this.disposables=[],this.disposableRegistry.push(this)}dispose(){this.disposables.forEach((e=>e.dispose()))}async activate(){this.disposables.push(this.commandManager.registerCommand(h.Commands.SelectNativeJupyterUriFromToolBar,this.onToolBarCommand,this)),this.statusBarItem=this.appShell.createStatusBarItem(a.StatusBarAlignment.Right,1e3),this.notebook.onDidChangeActiveNotebookEditor(this.updateStatusBar.bind(this),this.disposables),this.documentManager.onDidChangeActiveTextEditor(this.updateStatusBar.bind(this),this.disposables),this.serverUriStorage.onDidChangeUri(this.updateStatusBar.bind(this),this.disposables),this.notebookControllerManager.onNotebookControllerSelected(this.updateStatusBar.bind(this),this,this.disposables),this.disposables.push(this.statusBarItem),this.updateStatusBar().catch(s.noop)}async onToolBarCommand(){await this.serverSelector.selectJupyterURI(!0,"nativeNotebookToolbar")}async updateStatusBar(){if(!this.notebook.activeNotebookEditor||!(0,m.isJupyterNotebook)(this.notebook.activeNotebookEditor.document))return void this.statusBarItem.hide();this.statusBarItem.show();const e=await this.serverUriStorage.getUri(),t=e===d.Settings.JupyterServerLocalLaunch?u.DataScience.jupyterNativeNotebookUriStatusLabelForLocal():u.DataScience.jupyterNativeNotebookUriStatusLabelForRemote(),n=e===d.Settings.JupyterServerLocalLaunch?"":` (${e})`,r=`${u.DataScience.specifyLocalOrRemoteJupyterServerForConnections()}${n}`;this.statusBarItem.text=`$(debug-disconnect) ${t}`,this.statusBarItem.tooltip=r,this.statusBarItem.command={command:h.Commands.SelectJupyterURI,title:t,tooltip:r,arguments:[void 0,"nativeNotebookStatusBar"]},this.statusBarItem.command}};v=r([(0,o.injectable)(),i(0,(0,o.inject)(p.IJupyterServerUriStorage)),i(1,(0,o.inject)(c.IDocumentManager)),i(2,(0,o.inject)(c.IVSCodeNotebook)),i(3,(0,o.inject)(c.ICommandManager)),i(4,(0,o.inject)(l.IDisposableRegistry)),i(5,(0,o.inject)(c.IApplicationShell)),i(6,(0,o.inject)(f.JupyterServerSelector)),i(7,(0,o.inject)(g.INotebookControllerManager))],v),t.RemoteSwitcher=v},70720:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.VSCodeNotebookController=void 0;const i=n(71017),o=n(66828),s=n(97784),a=n(2687),c=n(46318),l=n(29140),u=n(7744),d=n(28735),p=n(35952),h=n(95063),f=n(72858),m=n(32417),g=n(5448),v=n(36462),y=n(86909),b=n(14220),_=n(21687),w=n(83474),S=n(55170),C=n(3108),k=n(65725),E=n(93828),x=n(43367),T=n(73913),D=n(31283),I=n(82232),P=n(17261),R=n(58021);class M{constructor(e,t,n,r,i,s,a,c,l,u,d,h,f,m,g,v,y,b,w,S){this.kernelConnection=e,this.notebookApi=i,this.commandManager=s,this.kernelProvider=a,this.preferredRemoteKernelIdProvider=c,this.context=l,this.pathUtils=u,this.languageService=h,this.workspace=f,this.configuration=m,this.widgetCoordinator=g,this.documentManager=v,this.appShell=y,this.browser=b,this.extensionChecker=w,this.serviceContainer=S,this._onNotebookControllerSelectionChanged=new o.EventEmitter,this._onDidDispose=new o.EventEmitter,this.disposables=[],this.notebookKernels=new WeakMap,this.isDisposed=!1,this.runningCellExecutions=new Map,this.associatedDocuments=new WeakMap,d.push(this),this._onNotebookControllerSelected=new o.EventEmitter,this.controller=this.notebookApi.createNotebookController(t,n,r,this.handleExecution.bind(this),this.getRendererScripts()),this.controller.interruptHandler=this.handleInterrupt.bind(this),this.controller.description=(0,E.getKernelConnectionPath)(e,this.pathUtils,this.workspace),this.controller.detail="connectToLiveKernel"===e.kind?(0,E.getRemoteKernelSessionInformation)(e):"",this.controller.kind=function(e){switch(e.kind){case"connectToLiveKernel":return p.DataScience.kernelCategoryForJupyterSession();case"startUsingRemoteKernelSpec":return p.DataScience.kernelCategoryForRemoteJupyterKernel();case"startUsingLocalKernelSpec":return p.DataScience.kernelCategoryForJupyterKernel();case"startUsingPythonInterpreter":if("registeredByNewVersionOfExtForCustomKernelSpec"===(0,E.getKernelRegistrationInfo)(e.kernelSpec))return p.DataScience.kernelCategoryForJupyterKernel();switch(e.interpreter.envType){case _.EnvironmentType.Conda:return p.DataScience.kernelCategoryForConda();case _.EnvironmentType.Pipenv:return p.DataScience.kernelCategoryForPipEnv();case _.EnvironmentType.Poetry:return p.DataScience.kernelCategoryForPoetry();case _.EnvironmentType.Pyenv:return p.DataScience.kernelCategoryForPyEnv();case _.EnvironmentType.Venv:case _.EnvironmentType.VirtualEnv:case _.EnvironmentType.VirtualEnvWrapper:return p.DataScience.kernelCategoryForVirtual();default:return p.DataScience.kernelCategoryForGlobal()}}}(e),this.controller.supportsExecutionOrder=!0,this.controller.supportedLanguages=this.languageService.getSupportedLanguages(e),this.controller.onDidChangeSelectedNotebooks(this.onDidChangeSelectedNotebooks,this,this.disposables)}get id(){return this.controller.id}get label(){return this.controller.label}get connection(){return this.kernelConnection}get onNotebookControllerSelected(){return this._onNotebookControllerSelected.event}get onNotebookControllerSelectionChanged(){return this._onNotebookControllerSelectionChanged.event}get onDidReceiveMessage(){return this.controller.onDidReceiveMessage}get onDidDispose(){return this._onDidDispose.event}isAssociatedWithDocument(e){return this.associatedDocuments.has(e)}updateRemoteKernelDetails(e){this.controller.detail=(0,E.getRemoteKernelSessionInformation)(e)}updateInterpreterDetails(e){this.controller.label=(0,E.getDisplayNameOrNameOfKernelConnection)(e)}asWebviewUri(e){return this.controller.asWebviewUri(e)}postMessage(e,t){const n=e&&"message"in e?e.message:"";return(0,c.traceInfoIfCI)(`${b.ConsoleForegroundColors.Green}Posting message to Notebook UI ${n}`),this.controller.postMessage(e,t)}dispose(){this.isDisposed||(this.isDisposed=!0,this._onNotebookControllerSelected.dispose(),this._onNotebookControllerSelectionChanged.dispose(),this.controller.dispose()),this._onDidDispose.fire(),this._onDidDispose.dispose(),(0,a.disposeAllDisposables)(this.disposables)}updateMetadata(e){e.id===this.kernelConnection.id&&(this.kernelConnection=e,this.controller.detail="connectToLiveKernel"===this.kernelConnection.kind?(0,E.getRemoteKernelSessionInformation)(this.kernelConnection):"")}async updateNotebookAffinity(e,t){(0,c.traceInfo)(`Setting controller affinity for ${(0,l.getDisplayPath)(e.uri)} ${this.id}`),this.controller.updateNotebookAffinity(e,t)}async handleExecution(e,t){e.length<1?(0,c.traceInfoIfCI)("No cells passed to handleExecution"):(e=e.filter((e=>!(e.index<0&&((0,c.traceWarning)(`Attempting to run a cell with index ${e.index}, kind ${e.kind}, text = ${e.document.getText()}`),1)))),(0,c.traceInfoIfCI)(`VSCodeNotebookController::handleExecution for ${(0,l.getDisplayPath)(t.uri)} for cells ${e.length} with data ${e.map((e=>e.document.getText())).join("\n#CELL\n")}`),this.workspace.isTrusted&&((0,m.initializeInteractiveOrNotebookTelemetryBasedOnUserAction)(t.uri,this.connection),(0,m.sendKernelTelemetryEvent)(t.uri,w.Telemetry.ExecuteCell),(0,c.traceInfo)(`Execute Cells request ${e.map((e=>e.index)).join(", ")}`),await Promise.all(e.map((e=>this.executeCell(t,e))))))}warnWhenUsingOutdatedPython(){var e;const t=null===(e=this.kernelConnection.interpreter)||void 0===e?void 0:e.version;!t||t.major>=4||"startUsingLocalKernelSpec"!==this.kernelConnection.kind&&"startUsingPythonInterpreter"!==this.kernelConnection.kind||(t.major<3||3===t.major&&t.minor<=5)&&this.appShell.showWarningMessage(p.DataScience.warnWhenSelectingKernelWithUnSupportedPythonVersion(),p.Common.learnMore()).then((e=>{if(e===p.Common.learnMore())return this.browser.launch("https://aka.ms/jupyterUnSupportedPythonKernelVersions")}))}async onDidChangeSelectedNotebooks(e){if((0,c.traceInfoIfCI)(`NotebookController selection event called for notebook ${e.notebook.uri.toString()} & controller ${this.id}. Selected ${e.selected} `),this.associatedDocuments.has(e.notebook)&&e.selected)return;if(!e.selected){const t=this.kernelProvider.get(e.notebook);return(null==t?void 0:t.kernelConnectionMetadata.id)===this.kernelConnection.id&&((0,c.traceInfo)(`Disposing kernel ${this.kernelConnection.id} for notebook ${(0,l.getDisplayPath)(e.notebook.uri)} due to selection of another kernel or closing of the notebook`),t.dispose()),this.associatedDocuments.delete(e.notebook),void this._onNotebookControllerSelectionChanged.fire()}if(!(0,I.isJupyterNotebook)(e.notebook)&&e.notebook.notebookType!==T.InteractiveWindowView)return;if(!this.workspace.isTrusted)return;this.warnWhenUsingOutdatedPython();const t=(0,u.createDeferred)();this.associatedDocuments.set(e.notebook,t.promise),this.widgetCoordinator.setActiveController(e.notebook,this),await this.onDidSelectController(e.notebook),await this.updateCellLanguages(e.notebook),this._onNotebookControllerSelected.fire({notebook:e.notebook,controller:this}),this._onNotebookControllerSelectionChanged.fire(),(0,c.traceVerbose)("Controller selection change completed"),t.resolve()}async updateCellLanguages(e){const t=this.controller.supportedLanguages;if(!t||0===(null==t?void 0:t.length))return;const n=(0,E.isPythonKernelConnection)(this.kernelConnection)?s.PYTHON_LANGUAGE:t[0];await Promise.all(e.getCells().filter((e=>e.kind===o.NotebookCellKind.Code)).map((async e=>{t.includes(e.document.languageId)||await o.languages.setTextDocumentLanguage(e.document,n).then(h.noop,h.noop)})))}getRendererScripts(){const e=[];return e.push((0,i.join)(this.context.extensionPath,"out","datascience-ui","ipywidgetsKernel","require.js")),this.context.extensionMode===o.ExtensionMode.Development||this.context.extensionMode===o.ExtensionMode.Test?(e.push((0,i.join)(this.context.extensionPath,"out","datascience-ui","widgetTester","widgetTester.js")),e.push((0,i.join)(this.context.extensionPath,"node_modules","@vscode","jupyter-ipywidgets","dist","ipywidgets.js"))):e.push((0,i.join)(this.context.extensionPath,"out","node_modules","@vscode","jupyter-ipywidgets","dist","ipywidgets.js")),e.push((0,i.join)(this.context.extensionPath,"out","datascience-ui","ipywidgetsKernel","ipywidgetsKernel.js"),(0,i.join)(this.context.extensionPath,"out","fontAwesome","fontAwesomeLoader.js")),e.map((e=>new o.NotebookRendererScript(o.Uri.file(e))))}handleInterrupt(e){e.getCells().forEach((e=>(0,I.traceCellMessage)(e,"Cell cancellation requested"))),this.commandManager.executeCommand(w.Commands.NotebookEditorInterruptKernel,e.uri).then(h.noop,(e=>console.error(e)))}startCellExecutionIfNecessary(e,t){let n=this.runningCellExecutions.get(e.notebook);if(!n||n.cell===e){null==n||n.end(void 0,void 0),n=D.CellExecutionCreator.getOrCreate(e,t),this.runningCellExecutions.set(e.notebook,n);const r=n.end.bind(n);n.end=(t,n)=>{this.runningCellExecutions.delete(e.notebook),r(t,n)},n.start((new Date).getTime()),n.clearOutput(e)}}async executeCell(e,t){(0,c.traceInfo)(`Execute Cell ${t.index} ${(0,l.getDisplayPath)(t.notebook.uri)}`),this.startCellExecutionIfNecessary(t,this.controller);let n,r="start",i=this.controller;try{return n=await this.connectToKernel(e,new P.DisplayOptions(!1)),n&&n.controller.id!==i.id&&(i=n.controller,this.startCellExecutionIfNecessary(t,n.controller)),r="execution",n.controller.id===this.id&&this.updateKernelInfoInNotebookWhenAvailable(n,e),await n.executeCell(t)}catch(e){const n=this.serviceContainer.get(g.IDataScienceErrorHandler),s=(e=C.WrappedError.unwrap(e))instanceof o.CancellationError||e instanceof o.CancellationError||e instanceof R.KernelDeadError;return(0,S.displayErrorsInCell)(t,i,await n.getErrorMessageForDisplayInCell(e,r),s),o.NotebookCellExecutionState.Idle}}async connectToKernel(e,t){return(0,E.connectToKernel)(this,this.serviceContainer,e.uri,e,t)}updateKernelInfoInNotebookWhenAvailable(e,t){if(this.notebookKernels.get(t)===e)return;let n;this.notebookKernels.set(t,e);const r=[];this.notebookApi.onDidCloseNotebookDocument((e=>{e===t&&(0,a.disposeAllDisposables)(r)}),this,r);const i=()=>{const e=null==n?void 0:n.options.id;e&&!(0,x.isLocalConnection)(this.kernelConnection)&&((0,c.traceInfo)(`Updating preferred kernel for remote notebook ${e}`),this.preferredRemoteKernelIdProvider.storePreferredRemoteKernelId(t.uri,e).catch(h.noop))},o=e.onDisposed((()=>(0,a.disposeAllDisposables)(r))),s=e.kernelSocket.subscribe((e=>{n=e,i()})),l=e.onStatusChanged((async()=>{!e.disposed&&e.info&&this.associatedDocuments.has(t)&&(await(0,I.updateNotebookDocumentMetadata)(t,this.documentManager,e.kernelConnectionMetadata,e.info),"startUsingLocalKernelSpec"!==this.kernelConnection.kind&&"startUsingRemoteKernelSpec"!==this.kernelConnection.kind||"ok"!==e.info.status?(0,a.disposeAllDisposables)(r):i())}));r.push({dispose:()=>s.unsubscribe()}),r.push({dispose:()=>l.dispose()}),r.push({dispose:()=>null==o?void 0:o.dispose()})}async onDidSelectController(e){const t=this.connection,n=this.kernelProvider.get(e);if(n&&(0,E.areKernelConnectionsEqual)(n.kernelConnectionMetadata,t))return void(0,c.traceInfo)("Switch kernel did not change kernel.");switch(this.connection.kind){case"startUsingPythonInterpreter":(0,f.sendNotebookOrKernelLanguageTelemetry)(w.Telemetry.SwitchToExistingKernel,s.PYTHON_LANGUAGE);break;case"connectToLiveKernel":(0,f.sendNotebookOrKernelLanguageTelemetry)(w.Telemetry.SwitchToExistingKernel,this.connection.kernelModel.language);break;case"startUsingLocalKernelSpec":case"startUsingRemoteKernelSpec":(0,f.sendNotebookOrKernelLanguageTelemetry)(w.Telemetry.SwitchToExistingKernel,this.connection.kernelSpec.language)}if((0,m.sendKernelTelemetryEvent)(e.uri,w.Telemetry.SwitchKernel),n){const t=(0,x.isLocalConnection)(this.kernelConnection)?w.Telemetry.SelectLocalJupyterKernel:w.Telemetry.SelectRemoteJupyterKernel;(0,m.sendKernelTelemetryEvent)(e.uri,t),this.notebookApi.notebookEditors.filter((t=>t.document===e)).forEach((e=>this.postMessage({message:k.IPyWidgetMessages.IPyWidgets_onKernelChanged,payload:void 0},e)))}if(await(0,I.updateNotebookDocumentMetadata)(e,this.documentManager,t),e.notebookType===T.InteractiveWindowView)return;const r=this.kernelProvider.getOrCreate(e,{metadata:t,controller:this.controller,resourceUri:e.uri});(0,c.traceInfo)(`KernelProvider switched kernel to id = ${r.kernelConnectionMetadata.id}`),(0,E.isPythonKernelConnection)(this.kernelConnection)&&!this.extensionChecker.isPythonExtensionInstalled||!this.configuration.getSettings(void 0).disableJupyterAutoStart&&(0,x.isLocalConnection)(this.kernelConnection)&&this.connectToKernel(e,new P.DisplayOptions(!0)).catch(h.noop)}}r([v.traceDecorators.verbose("VSCodeNotebookController::handleExecution",y.TraceOptions.BeforeCall)],M.prototype,"handleExecution",null),r([(0,d.chainable)()],M.prototype,"connectToKernel",null),t.VSCodeNotebookController=M},19865:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CellOutputDisplayIdTracker=void 0;const o=n(86700),s=n(13395),a=n(82232);let c=class{constructor(e){this.displayIdCellOutputMappingPerDocument=new WeakMap,this.cellToDisplayIdMapping=new WeakMap,e.onDidChangeNotebookDocument((e=>{(0,a.isJupyterNotebook)(e.document)&&"changeCellOutputs"===e.type&&e.cells.filter((e=>0===e.outputs.length)).map((e=>{var t;const n=this.cellToDisplayIdMapping.get(e);n&&(this.cellToDisplayIdMapping.delete(e),null===(t=this.displayIdCellOutputMappingPerDocument.get(e.notebook))||void 0===t||t.delete(n))}))}))}trackOutputByDisplayId(e,t,n){let r=this.displayIdCellOutputMappingPerDocument.get(e.notebook);r||(r=new Map,this.displayIdCellOutputMappingPerDocument.set(e.notebook,r)),r.set(t,{output:n,cell:e}),this.cellToDisplayIdMapping.set(e,t)}getMappedOutput(e,t){const n=this.displayIdCellOutputMappingPerDocument.get(e);if(!n)return;const r=n.get(t);return(null==r?void 0:r.cell.document.isClosed)||null==r?void 0:r.output}};c=r([(0,o.injectable)(),i(0,(0,o.inject)(s.IVSCodeNotebook))],c),t.CellOutputDisplayIdTracker=c},23430:function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.CellExecution=t.CellExecutionFactory=void 0;const i=n(64063),o=n(66828),s=n(31283),a=n(55170),c=n(3108),l=n(2687),u=n(46318),d=n(2013),p=n(7744),h=n(35952),f=n(88319),m=n(73913),g=n(82232),v=n(97045),y=n(44007),b=n(60592),_=n(83474),w=n(28735),S=n(95063),C=n(93828),k=n(43367),E=n(44241);t.CellExecutionFactory=class{constructor(e,t,n,r,i,o){this.kernel=e,this.appShell=t,this.disposables=n,this.controller=r,this.outputTracker=i,this.cellHashProviderFactory=o}create(e,t){return x.fromCell(e,this.appShell,t,this.disposables,this.controller,this.outputTracker,this.cellHashProviderFactory.getOrCreate(this.kernel))}};class x{constructor(e,t,n,r,i,a,c){this.cell=e,this.applicationService=t,this.kernelConnection=n,this.controller=i,this.outputDisplayIdTracker=a,this.cellHashProvider=c,this.stopWatch=new f.StopWatch,this.stopWatchForTelemetry=new f.StopWatch,this._result=(0,p.createDeferred)(),this.cancelHandled=!1,this.disposables=[],this.prompts=new Set,this._preExecuteEmitter=new o.EventEmitter,r.push(this),o.workspace.onDidCloseTextDocument((e=>{var t;if(e===this.cell.document){try{null===(t=this.request)||void 0===t||t.dispose()}catch(e){(0,u.traceError)(`Error during cell execution dispose: ${e}`)}this.started&&!this._completed&&this.completedDueToCancellation()}}),this,this.disposables),o.notebooks.onDidChangeCellOutputs((e=>{e.cells.includes(this.cell)&&0===this.cell.outputs.length&&this.clearLastUsedStreamOutput()}),this,this.disposables),g.NotebookCellStateTracker.setCellState(e,o.NotebookCellExecutionState.Idle),this.canExecuteCell()&&(this.execution=s.CellExecutionCreator.getOrCreate(e,this.controller),g.NotebookCellStateTracker.setCellState(e,o.NotebookCellExecutionState.Pending))}get result(){return this._result.promise}get preExecute(){return this._preExecuteEmitter.event}static fromCell(e,t,n,r,i,o,s){return new x(e,t,n,r,i,o,s)}async start(e){var t,n,r;if(this.cancelHandled)(0,g.traceCellMessage)(this.cell,"Not starting as it was cancelled");else{if((0,g.traceCellMessage)(this.cell,"Start execution"),(0,u.traceInfoIfCI)(`Cell Exec contents ${this.cell.document.getText().substring(0,50)}...`),!this.canExecuteCell())return null===(t=this.execution)||void 0===t||t.end(void 0),this.execution=void 0,void this._result.resolve();if(this.started)return(0,g.traceCellMessage)(this.cell,"Cell has already been started yet CellExecution.Start invoked again"),(0,u.traceError)(`Cell has already been started yet CellExecution.Start invoked again ${this.cell.index}`),this.result;this.started=!0,this.startTime=(new Date).getTime(),x.activeNotebookCellExecution.set(this.cell.notebook,this.execution),null===(n=this.execution)||void 0===n||n.start(this.startTime),g.NotebookCellStateTracker.setCellState(this.cell,o.NotebookCellExecutionState.Executing),this.clearLastUsedStreamOutput(),await(null===(r=this.execution)||void 0===r?void 0:r.clearOutput()),this.stopWatch.reset(),this.execute(e).catch((e=>this.completedWithErrors(e))).finally((()=>this.dispose())).catch(S.noop)}}async cancel(e=!1){if(!this.cancelHandled){if(this.prompts.forEach((e=>e.cancel())),this.started&&!e)return(0,g.traceCellMessage)(this.cell,"Cell is already running, waiting for it to finish or kernel to start"),void await this.result;this.cancelHandled||this._completed||((0,g.traceCellMessage)(this.cell,"Execution cancelled"),this.cancelHandled=!0,this.completedDueToCancellation(),this.dispose())}}dispose(){(0,g.traceCellMessage)(this.cell,"Execution disposed"),(0,l.disposeAllDisposables)(this.disposables),this.prompts.forEach((e=>e.dispose())),this.prompts.clear()}clearLastUsedStreamOutput(){this.lastUsedStreamOutput=void 0}completedWithErrors(e){var t,n,r;if((0,u.traceWarning)("Cell completed with errors",e),(0,g.traceCellMessage)(this.cell,"Completed with errors"),this.sendPerceivedCellExecute(),(0,g.traceCellMessage)(this.cell,"Update with error state & output"),e instanceof c.BaseError){const t=(0,a.analyzeKernelErrors)(o.workspace.workspaceFolders||[],e,(0,C.getDisplayNameOrNameOfKernelConnection)(this.kernelConnection),null===(n=this.kernelConnection.interpreter)||void 0===n?void 0:n.sysPrefix);t&&(null===(r=this.execution)||void 0===r||r.appendOutput([(0,g.translateErrorOutput)((0,b.createErrorOutputFromFailureInfo)(t))]).then(S.noop,S.noop))}else null===(t=this.execution)||void 0===t||t.appendOutput([(0,g.translateErrorOutput)((0,b.createErrorOutput)(e))]).then(S.noop,S.noop);this.endCellTask("failed"),this._completed=!0,(0,g.traceCellMessage)(this.cell,"Completed with errors, & resolving"),this._result.resolve(k.NotebookCellRunState.Error)}get isEmptyCodeCell(){return 0===this.cell.document.getText().trim().length}completedSuccessfully(){(0,g.traceCellMessage)(this.cell,"Completed successfully"),this.sendPerceivedCellExecute();let e=this.isEmptyCodeCell?k.NotebookCellRunState.Idle:k.NotebookCellRunState.Success,t="success";this.cellHasErrorsInOutput&&(t="failed",e=k.NotebookCellRunState.Error),this.endCellTask(t),this._completed=!0,(0,g.traceCellMessage)(this.cell,`Completed successfully & resolving with status = ${t}`),this._result.resolve(e)}endCellTask(e){var t,n,r;this.isEmptyCodeCell?(this.execution&&(this.execution.executionOrder=void 0),null===(t=this.execution)||void 0===t||t.end(void 0)):"success"===e||"failed"===e?(this.endTime=(new Date).getTime(),null===(n=this.execution)||void 0===n||n.end("success"===e,this.endTime)):null===(r=this.execution)||void 0===r||r.end(void 0),x.activeNotebookCellExecution.get(this.cell.notebook)===this.execution&&x.activeNotebookCellExecution.set(this.cell.notebook,void 0),g.NotebookCellStateTracker.setCellState(this.cell,o.NotebookCellExecutionState.Idle),this.execution=void 0}createTemporaryTask(){var e,t;if(this.cell.document.isClosed)return;return x.activeNotebookCellExecution.get(this.cell.notebook)||(this.previousResultsToRestore={...this.cell.executionSummary||{}},this.temporaryExecution=s.CellExecutionCreator.getOrCreate(this.cell,this.controller),null===(e=this.temporaryExecution)||void 0===e||e.start(),(null===(t=this.previousResultsToRestore)||void 0===t?void 0:t.executionOrder)&&this.execution&&(this.execution.executionOrder=this.previousResultsToRestore.executionOrder),this.temporaryExecution)}endTemporaryTask(){var e,t,n;(null===(e=this.previousResultsToRestore)||void 0===e?void 0:e.executionOrder)&&this.execution&&(this.execution.executionOrder=this.previousResultsToRestore.executionOrder),this.previousResultsToRestore&&this.temporaryExecution?(this.previousResultsToRestore.executionOrder&&(this.temporaryExecution.executionOrder=this.previousResultsToRestore.executionOrder),this.temporaryExecution.end(this.previousResultsToRestore.success,null===(t=this.previousResultsToRestore.timing)||void 0===t?void 0:t.endTime)):null===(n=this.temporaryExecution)||void 0===n||n.end(void 0),this.previousResultsToRestore=void 0,this.temporaryExecution=void 0}completedDueToCancellation(){(0,g.traceCellMessage)(this.cell,"Completed due to cancellation"),this.endCellTask("cancelled"),this._completed=!0,(0,g.traceCellMessage)(this.cell,"Cell cancelled & resolving"),this._result.resolve(k.NotebookCellRunState.Idle)}sendPerceivedCellExecute(){const e={notebook:!0};x.sentExecuteCellTelemetry?(0,v.sendTelemetryEvent)(_.Telemetry.ExecuteCellPerceivedWarm,this.stopWatchForTelemetry.elapsedTime,e):(x.sentExecuteCellTelemetry=!0,(0,v.sendTelemetryEvent)(_.Telemetry.ExecuteCellPerceivedCold,this.stopWatchForTelemetry.elapsedTime,e))}canExecuteCell(){return!((0,C.isPythonKernelConnection)(this.kernelConnection)&&"raw"===this.cell.document.languageId||this.cell.document.isClosed)}async execute(e){(0,g.traceCellMessage)(this.cell,"Send code for execution"),await this.executeCodeCell(this.cell.document.getText().replace(/\r\n/g,"\n"),e)}async executeCodeCell(e,t){var n,r;if(0===e.trim().length||this.cell.document.isClosed)return(0,g.traceCellMessage)(this.cell,"Empty cell execution"),this.completedSuccessfully();const i={cellId:this.cell.document.uri.toString(),...(null===(r=null===(n=this.cell.metadata)||void 0===n?void 0:n.custom)||void 0===r?void 0:r.metadata)||{}};try{let n;this.cell.notebook.notebookType===m.InteractiveWindowView&&(n=await this.cellHashProvider.addCellHash(this.cell)),this._preExecuteEmitter.fire(this.cell),this.request=t.requestExecute({code:(null==n?void 0:n.code)||e,silent:!1,stop_on_error:!1,allow_stdin:!0,store_history:!0},!1,i)}catch(e){return(0,u.traceError)(`Cell execution failed without request, for cell Index ${this.cell.index}`,e),this.completedWithErrors(e)}const o=new d.RefBool(!1),s=this.request;s.onIOPub=e=>{this.cell.document.isClosed&&s.dispose(),this.handleIOPub(o,e)},s.onReply=e=>{this.cell.document.isClosed&&s.dispose(),this.handleReply(o,e)},s.onStdin=this.handleInputRequest.bind(this,t);try{(0,g.traceCellMessage)(this.cell,"Wait for jupyter execution"),await s.done,(0,g.traceCellMessage)(this.cell,"Jupyter execution completed"),this.completedSuccessfully(),(0,g.traceCellMessage)(this.cell,"Executed successfully in executeCell")}catch(e){e&&e instanceof Error&&(e.message.includes("Canceled")||e.message.includes(h.Common.canceled()))?((0,u.traceWarning)("Error in waiting for cell to complete",e),(0,g.traceCellMessage)(this.cell,"Cancellation execution error"),this.completedWithErrors(e)):((0,u.traceError)("Error in waiting for cell to complete",e),(0,g.traceCellMessage)(this.cell,"Some other execution error"),this.completedWithErrors(e))}}handleIOPub(e,t){const r=n(36879);try{if(r.KernelMessage.isExecuteResultMsg(t))(0,u.traceInfoIfCI)("KernelMessage = ExecuteResult"),this.handleExecuteResult(t,e);else if(r.KernelMessage.isExecuteInputMsg(t))this.handleExecuteInput(t,e);else if(r.KernelMessage.isStatusMsg(t)){(0,u.traceInfoIfCI)("KernelMessage = StatusMessage");const n=t;this.handleStatusMessage(n,e)}else r.KernelMessage.isStreamMsg(t)?((0,u.traceInfoIfCI)("KernelMessage = StreamMessage",`Cell Index ${this.cell.index}, Stream '${t.content.name}`,t.content.text),this.handleStreamMessage(t,e)):r.KernelMessage.isDisplayDataMsg(t)?((0,u.traceInfoIfCI)("KernelMessage = DisplayMessage"),this.handleDisplayData(t,e)):r.KernelMessage.isUpdateDisplayDataMsg(t)?((0,u.traceInfoIfCI)("KernelMessage = UpdateDisplayMessage"),this.handleUpdateDisplayDataMessage(t)):r.KernelMessage.isClearOutputMsg(t)?((0,u.traceInfoIfCI)("KernelMessage = CleanOutput"),this.handleClearOutput(t,e)):r.KernelMessage.isErrorMsg(t)?((0,u.traceInfoIfCI)("KernelMessage = ErrorMessage"),this.handleError(t,e)):r.KernelMessage.isCommOpenMsg(t)||r.KernelMessage.isCommMsgMsg(t)||r.KernelMessage.isCommCloseMsg(t)||(0,u.traceWarning)(`Unknown message ${t.header.msg_type} : hasData=${"data"in t.content}`);"execution_count"in t.content&&"number"==typeof t.content.execution_count&&this.execution&&((0,u.traceInfoIfCI)(`Exec Count = ${t.content.execution_count}`),this.execution.executionOrder=t.content.execution_count)}catch(e){(0,u.traceError)(`Cell (index = ${this.cell.index}) execution completed with errors (2).`,e),this.completedWithErrors(e)}}addToCellData(e,t){var n,r,i;const o=(0,g.cellOutputToVSCCellOutput)(e),s="transient"in e&&"object"==typeof e.transient&&e.transient&&"display_id"in e.transient&&"string"==typeof(null===(n=e.transient)||void 0===n?void 0:n.display_id)?null===(r=e.transient)||void 0===r?void 0:r.display_id:void 0;if(this.cell.document.isClosed)return;(0,g.traceCellMessage)(this.cell,"Update output"),t.value&&(this.clearLastUsedStreamOutput(),null===(i=this.execution)||void 0===i||i.clearOutput().then(S.noop,S.noop),t.update(!1)),s&&this.outputDisplayIdTracker.trackOutputByDisplayId(this.cell,s,o);const a=this.execution||this.createTemporaryTask();this.clearLastUsedStreamOutput(),(0,g.traceCellMessage)(this.cell,"Append output in addToCellData"),null==a||a.appendOutput([o]).then(S.noop,S.noop),this.endTemporaryTask()}async handleInputRequest(e,t){if(t.content&&"prompt"in t.content){const n=new o.CancellationTokenSource;this.prompts.add(n);const r=null!==t.content.password&&t.content.password;await this.applicationService.showInputBox({prompt:t.content.prompt?t.content.prompt.toString():"",ignoreFocusOut:!0,password:r},n.token).then((t=>{e.sendInputReply({value:t||"",status:"ok"})}),S.noop),this.prompts.delete(n)}}handleExecuteResult(e,t){this.addToCellData({output_type:"execute_result",data:e.content.data,metadata:e.content.metadata,transient:e.content.transient,execution_count:e.content.execution_count},t)}handleExecuteReply(e,t){const n=e.content;n.payload&&n.payload.forEach((e=>{e.source&&"set_next_input"===e.source&&"text"in e&&"replace"in e&&this.handleSetNextInput(e),e.data&&e.data.hasOwnProperty("text/plain")&&this.addToCellData({output_type:"stream",text:e.data["text/plain"].toString(),name:"stdout",metadata:{},execution_count:n.execution_count},t)}))}handleSetNextInput(e){const t=new o.WorkspaceEdit;if(e.replace)t.replace(this.cell.document.uri,new o.Range(this.cell.document.lineAt(0).range.start,this.cell.document.lineAt(this.cell.document.lineCount-1).range.end),e.text);else{(0,g.traceCellMessage)(this.cell,"Create new cell after current");const n=new o.NotebookCellData(o.NotebookCellKind.Code,e.text,this.cell.document.languageId);n.outputs=[],n.metadata={},t.replaceNotebookCells(this.cell.notebook.uri,new o.NotebookRange(this.cell.index+1,this.cell.index+1),[n])}o.workspace.applyEdit(t).then(S.noop,S.noop)}handleExecuteInput(e,t){e.content.execution_count&&this.execution&&(this.execution.executionOrder=e.content.execution_count)}handleStatusMessage(e,t){(0,g.traceCellMessage)(this.cell,`Kernel switching to ${e.content.execution_state}`)}handleStreamMessage(e,t){var n;(0,g.traceCellMessage)(this.cell,"Update streamed output");const r=this.execution||this.createTemporaryTask(),i=t.value;if(i&&((0,g.traceCellMessage)(this.cell,"Clear cell output"),this.clearLastUsedStreamOutput(),null==r||r.clearOutput().then(S.noop,S.noop),t.update(!1)),(null===(n=this.lastUsedStreamOutput)||void 0===n?void 0:n.stream)===e.content.name){let t=this.lastUsedStreamOutput.text,n=e.content.text;const i=`${String.fromCharCode(27)}[A`;if(e.content.text.startsWith(i)){const e=t.splitLines({trim:!1,removeEmptyEntries:!1});e.length&&e.pop(),t=e.join("\n"),n=n.substring(i.length)}this.lastUsedStreamOutput.text=(0,y.formatStreamText)((0,y.concatMultilineString)(`${t}${n}`));const o=(0,g.cellOutputToVSCCellOutput)({output_type:"stream",name:e.content.name,text:this.lastUsedStreamOutput.text});(0,g.traceCellMessage)(this.cell,`Replace output items ${this.lastUsedStreamOutput.text.substring(0,100)}`),null==r||r.replaceOutputItems(o.items,this.lastUsedStreamOutput.output).then(S.noop,S.noop)}else if(i){const t=(0,y.formatStreamText)((0,y.concatMultilineString)(e.content.text)),n=(0,g.cellOutputToVSCCellOutput)({output_type:"stream",name:e.content.name,text:t});this.lastUsedStreamOutput={output:n,stream:e.content.name,text:t},(0,g.traceCellMessage)(this.cell,`Replace output ${this.lastUsedStreamOutput.text.substring(0,100)}`),null==r||r.replaceOutput([n]).then(S.noop,S.noop)}else{const t=(0,y.formatStreamText)((0,y.concatMultilineString)(e.content.text)),n=(0,g.cellOutputToVSCCellOutput)({output_type:"stream",name:e.content.name,text:t});this.lastUsedStreamOutput={output:n,stream:e.content.name,text:t},(0,g.traceCellMessage)(this.cell,`Append output ${this.lastUsedStreamOutput.text.substring(0,100)}`),null==r||r.appendOutput([n]).then(S.noop,S.noop)}this.endTemporaryTask()}handleDisplayData(e,t){const n={output_type:"display_data",data:(0,E.handleTensorBoardDisplayDataOutput)(e.content.data),metadata:e.content.metadata,transient:e.content.transient};this.addToCellData(n,t)}handleClearOutput(e,t){if(e&&e.content.wait)t.update(!0);else{const e=this.execution||this.createTemporaryTask();this.clearLastUsedStreamOutput(),null==e||e.clearOutput().then(S.noop,S.noop),this.endTemporaryTask()}}handleError(e,t){const n={output_type:"error",ename:e.content.ename,evalue:e.content.evalue,traceback:this.cellHashProvider.modifyTraceback(e.content.traceback)};this.addToCellData(n,t),this.cellHasErrorsInOutput=!0}handleReply(e,t){n(36879).KernelMessage.isExecuteReplyMsg(t)&&(this.handleExecuteReply(t,e),"execution_count"in t.content&&"number"==typeof t.content.execution_count&&this.execution&&(this.execution.executionOrder=t.content.execution_count))}handleUpdateDisplayDataMessage(e){const t=e.content.transient.display_id;if(!t)return;const n=this.outputDisplayIdTracker.getMappedOutput(this.cell.notebook,t);if(!n)return;const r=(0,g.translateCellDisplayOutput)(n),o=(0,g.cellOutputToVSCCellOutput)({...r,data:e.content.data,metadata:e.content.metadata});if(0===n.items.length&&0===o.items.length)return;if(n.items.length===o.items.length){let e=!0;for(let t=0;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CellExecutionCreator=void 0;class n{constructor(e,t,n){this._impl=e,this.controllerId=t,this._endCallback=n,this.started=!1}get cell(){return this._impl.cell}get token(){return this._impl.token}get executionOrder(){return this._impl.executionOrder}set executionOrder(e){this._impl.executionOrder=e}start(e){this.started||(this.started=!0,this._impl.start(e))}end(e,t){if(this._endCallback)try{this._impl.end(e,t)}finally{this._endCallback(),this._endCallback=void 0}}clearOutput(e){return this._impl.clearOutput(e)}replaceOutput(e,t){return this._impl.replaceOutput(e,t)}appendOutput(e,t){return this._impl.appendOutput(e,t)}replaceOutputItems(e,t){return this._impl.replaceOutputItems(e,t)}appendOutputItems(e,t){return this._impl.appendOutputItems(e,t)}}class r{static getOrCreate(e,t){let n;const i=e.document.uri.toString();if(n=r._map.get(i),n){if(n.controllerId!==t.id){const o=n;o.end(void 0),n=r.create(i,e,t),o.started&&n.start((new Date).getTime())}}else n=r.create(i,e,t);return n}static create(e,t,i){const o=new n(i.createNotebookCellExecution(t),i.id,(()=>{r._map.delete(e)}));return r._map.set(e,o),o}}t.CellExecutionCreator=r,r._map=new Map},93073:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CellExecutionQueue=void 0;const r=n(66828),i=n(46318),o=n(95063),s=n(82232),a=n(43367);t.CellExecutionQueue=class{constructor(e,t,n){this.session=e,this.executionFactory=t,this.metadata=n,this.queueOfCellsToExecute=[],this.cancelledOrCompletedWithErrors=!1,this.startedRunningCells=!1,this._onPreExecute=new r.EventEmitter,this.disposables=[]}get isEmpty(){return 0===this.queueOfCellsToExecute.length}get failed(){return this.cancelledOrCompletedWithErrors}get queue(){return this.queueOfCellsToExecute.map((e=>e.cell))}dispose(){this.disposables.forEach((e=>e.dispose()))}get onPreExecute(){return this._onPreExecute.event}queueCell(e){if(this.queueOfCellsToExecute.find((t=>t.cell===e)))return void(0,s.traceCellMessage)(e,"Use existing cell execution");const t=this.executionFactory.create(e,this.metadata);t.preExecute((e=>this._onPreExecute.fire(e)),this,this.disposables),this.queueOfCellsToExecute.push(t),(0,s.traceCellMessage)(e,"User queued cell for execution"),this.startExecutingCells()}async cancel(e){this.cancelledOrCompletedWithErrors=!0,(0,i.traceInfo)("Cancel pending cells"),await Promise.all(this.queueOfCellsToExecute.map((t=>t.cancel(e)))),this.queueOfCellsToExecute.splice(0,this.queueOfCellsToExecute.length)}async waitForCompletion(e){const t=Array.isArray(e)&&e.length>0?this.queueOfCellsToExecute.filter((t=>e.includes(t.cell))):this.queueOfCellsToExecute;return Promise.all(t.map((e=>e.result)))}startExecutingCells(){this.startedRunningCells||this.start().catch(o.noop),this.startedRunningCells=!0}async start(){try{await this.executeQueuedCells()}catch(e){(0,i.traceError)("Failed to execute cells in CellExecutionQueue",e),this.cancelledOrCompletedWithErrors=!0,await this.cancel()}}async executeQueuedCells(){let e;const t=await this.session;for(this.queueOfCellsToExecute.forEach((e=>(0,s.traceCellMessage)(e.cell,"Ready to execute")));this.queueOfCellsToExecute.length;){const n=this.queueOfCellsToExecute[0];let r;(0,s.traceCellMessage)(n.cell,"Before Execute individual cell");try{n.cell.notebook.isClosed?e=!0:this.cancelledOrCompletedWithErrors||(await n.start(t),r=await n.result)}finally{(0,s.traceCellMessage)(n.cell,`After Execute individual cell ${r}`);const e=this.queueOfCellsToExecute.indexOf(n);e>=0&&this.queueOfCellsToExecute.splice(e,1)}if(e||this.cancelledOrCompletedWithErrors||r===a.NotebookCellRunState.Error){this.cancelledOrCompletedWithErrors=!0,(0,i.traceInfo)(`Cancel all remaining cells ${this.cancelledOrCompletedWithErrors} || ${r} || ${e}`),await this.cancel();break}if("dead"===t.status||"terminating"===t.status){this.cancelledOrCompletedWithErrors=!0,(0,i.traceInfo)("Cancel all remaining cells due to dead kernel"),await this.cancel();break}}}}},44241:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleTensorBoardDisplayDataOutput=void 0,t.handleTensorBoardDisplayDataOutput=function(e){if(e.hasOwnProperty("text/html")){const t=e["text/html"];"string"==typeof t&&t.includes('