import*as Bindings from"../bindings/bindings.js";import*as SDK from"../sdk/sdk.js";import*as Snippets from"../snippets/snippets.js";import*as UI from"../ui/ui.js";import*as Workspace from"../workspace/workspace.js";import{Plugin}from"./Plugin.js";export class JavaScriptCompilerPlugin extends Plugin{constructor(e,i){super(),this._textEditor=e,this._uiSourceCode=i,this._compiling=!1,this._recompileScheduled=!1,this._timeout=null,this._message=null,this._disposed=!1,this._textEditor.addEventListener(UI.TextEditor.Events.TextChanged,this._scheduleCompile,this),(this._uiSourceCode.hasCommits()||this._uiSourceCode.isDirty())&&this._scheduleCompile()}static accepts(e){if("js"===e.extension())return!0;if(Snippets.ScriptSnippetFileSystem.isSnippetsUISourceCode(e))return!0;for(const i of SDK.SDKModel.TargetManager.instance().models(SDK.DebuggerModel.DebuggerModel))if(Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().scriptFile(e,i))return!0;return!1}_scheduleCompile(){this._compiling?this._recompileScheduled=!0:(this._timeout&&clearTimeout(this._timeout),this._timeout=window.setTimeout(this._compile.bind(this),CompileDelay))}_findRuntimeModel(){const e=SDK.SDKModel.TargetManager.instance().models(SDK.DebuggerModel.DebuggerModel);for(let t=0;t<e.length;++t){if(Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().scriptFile(this._uiSourceCode,e[t]))return e[t].runtimeModel()}const i=SDK.SDKModel.TargetManager.instance().mainTarget();return i?i.model(SDK.RuntimeModel.RuntimeModel):null}async _compile(){const e=this._findRuntimeModel();if(!e)return;const i=UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext);if(!i)return;const t=this._textEditor.text();if(t.length>102400)return;this._compiling=!0;const s=await e.compileScript(t,"",!1,i.id);if(this._compiling=!1,this._recompileScheduled)return this._recompileScheduled=!1,void this._scheduleCompile();if(this._message&&this._uiSourceCode.removeMessage(this._message),this._disposed||!s||!s.exceptionDetails)return;const o=s.exceptionDetails,n=SDK.RuntimeModel.RuntimeModel.simpleTextFromException(o);this._message=this._uiSourceCode.addLineMessage(Workspace.UISourceCode.Message.Level.Error,n,o.lineNumber,o.columnNumber),this._compilationFinishedForTest()}_compilationFinishedForTest(){}dispose(){this._textEditor.removeEventListener(UI.TextEditor.Events.TextChanged,this._scheduleCompile,this),this._message&&this._uiSourceCode.removeMessage(this._message),this._disposed=!0,this._timeout&&clearTimeout(this._timeout)}}export const CompileDelay=1e3;