ucode-lsp 0.6.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +187 -0
- package/bin/ucode-lsp.js +9 -0
- package/dist/cli.js +1 -0
- package/dist/server.js +1 -0
- package/man/ucode-lsp.1 +298 -0
- package/package.json +102 -0
- package/scripts/postinstall.sh +15 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{var e={20:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NotebookDocuments=t.NotebookSyncFeature=void 0;const r=n(8828),i=n(1662);t.NotebookSyncFeature=e=>class extends e{get synchronization(){return{onDidOpenNotebookDocument:e=>this.connection.onNotification(r.DidOpenNotebookDocumentNotification.type,t=>{e(t)}),onDidChangeNotebookDocument:e=>this.connection.onNotification(r.DidChangeNotebookDocumentNotification.type,t=>{e(t)}),onDidSaveNotebookDocument:e=>this.connection.onNotification(r.DidSaveNotebookDocumentNotification.type,t=>{e(t)}),onDidCloseNotebookDocument:e=>this.connection.onNotification(r.DidCloseNotebookDocumentNotification.type,t=>{e(t)})}}};class o{onDidOpenTextDocument(e){return this.openHandler=e,r.Disposable.create(()=>{this.openHandler=void 0})}openTextDocument(e){this.openHandler&&this.openHandler(e)}onDidChangeTextDocument(e){return this.changeHandler=e,r.Disposable.create(()=>{this.changeHandler=e})}changeTextDocument(e){this.changeHandler&&this.changeHandler(e)}onDidCloseTextDocument(e){return this.closeHandler=e,r.Disposable.create(()=>{this.closeHandler=void 0})}closeTextDocument(e){this.closeHandler&&this.closeHandler(e)}onWillSaveTextDocument(){return o.NULL_DISPOSE}onWillSaveTextDocumentWaitUntil(){return o.NULL_DISPOSE}onDidSaveTextDocument(){return o.NULL_DISPOSE}}o.NULL_DISPOSE=Object.freeze({dispose:()=>{}}),t.NotebookDocuments=class{constructor(e){e instanceof i.TextDocuments?this._cellTextDocuments=e:this._cellTextDocuments=new i.TextDocuments(e),this.notebookDocuments=new Map,this.notebookCellMap=new Map,this._onDidOpen=new r.Emitter,this._onDidChange=new r.Emitter,this._onDidSave=new r.Emitter,this._onDidClose=new r.Emitter}get cellTextDocuments(){return this._cellTextDocuments}getCellTextDocument(e){return this._cellTextDocuments.get(e.document)}getNotebookDocument(e){return this.notebookDocuments.get(e)}getNotebookCell(e){const t=this.notebookCellMap.get(e);return t&&t[0]}findNotebookDocumentForCell(e){const t="string"==typeof e?e:e.document,n=this.notebookCellMap.get(t);return n&&n[1]}get onDidOpen(){return this._onDidOpen.event}get onDidSave(){return this._onDidSave.event}get onDidChange(){return this._onDidChange.event}get onDidClose(){return this._onDidClose.event}listen(e){const t=new o,n=[];return n.push(this.cellTextDocuments.listen(t)),n.push(e.notebooks.synchronization.onDidOpenNotebookDocument(e=>{this.notebookDocuments.set(e.notebookDocument.uri,e.notebookDocument);for(const n of e.cellTextDocuments)t.openTextDocument({textDocument:n});this.updateCellMap(e.notebookDocument),this._onDidOpen.fire(e.notebookDocument)})),n.push(e.notebooks.synchronization.onDidChangeNotebookDocument(e=>{const n=this.notebookDocuments.get(e.notebookDocument.uri);if(void 0===n)return;n.version=e.notebookDocument.version;const r=n.metadata;let i=!1;const o=e.change;void 0!==o.metadata&&(i=!0,n.metadata=o.metadata);const s=[],a=[],c=[],l=[];if(void 0!==o.cells){const e=o.cells;if(void 0!==e.structure){const r=e.structure.array;if(n.cells.splice(r.start,r.deleteCount,...void 0!==r.cells?r.cells:[]),void 0!==e.structure.didOpen)for(const n of e.structure.didOpen)t.openTextDocument({textDocument:n}),s.push(n.uri);if(e.structure.didClose)for(const n of e.structure.didClose)t.closeTextDocument({textDocument:n}),a.push(n.uri)}if(void 0!==e.data){const t=new Map(e.data.map(e=>[e.document,e]));for(let e=0;e<=n.cells.length;e++){const r=t.get(n.cells[e].document);if(void 0!==r){const i=n.cells.splice(e,1,r);if(c.push({old:i[0],new:r}),t.delete(r.document),0===t.size)break}}}if(void 0!==e.textContent)for(const n of e.textContent)t.changeTextDocument({textDocument:n.document,contentChanges:n.changes}),l.push(n.document.uri)}this.updateCellMap(n);const u={notebookDocument:n};i&&(u.metadata={old:r,new:n.metadata});const p=[];for(const e of s)p.push(this.getNotebookCell(e));const d=[];for(const e of a)d.push(this.getNotebookCell(e));const m=[];for(const e of l)m.push(this.getNotebookCell(e));(p.length>0||d.length>0||c.length>0||m.length>0)&&(u.cells={added:p,removed:d,changed:{data:c,textContent:m}}),void 0===u.metadata&&void 0===u.cells||this._onDidChange.fire(u)})),n.push(e.notebooks.synchronization.onDidSaveNotebookDocument(e=>{const t=this.notebookDocuments.get(e.notebookDocument.uri);void 0!==t&&this._onDidSave.fire(t)})),n.push(e.notebooks.synchronization.onDidCloseNotebookDocument(e=>{const n=this.notebookDocuments.get(e.notebookDocument.uri);if(void 0!==n){this._onDidClose.fire(n);for(const n of e.cellTextDocuments)t.closeTextDocument({textDocument:n});this.notebookDocuments.delete(e.notebookDocument.uri);for(const e of n.cells)this.notebookCellMap.delete(e.document)}})),r.Disposable.create(()=>{n.forEach(e=>e.dispose())})}updateCellMap(e){for(const t of e.cells)this.notebookCellMap.set(t.document,[t,e])}}},192:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=n(9023),i=n(5866);class o extends i.AbstractMessageBuffer{constructor(e="utf-8"){super(e)}emptyBuffer(){return o.emptyBuffer}fromString(e,t){return Buffer.from(e,t)}toString(e,t){return e instanceof Buffer?e.toString(t):new r.TextDecoder(t).decode(e)}asNative(e,t){return void 0===t?e instanceof Buffer?e:Buffer.from(e):e instanceof Buffer?e.slice(0,t):Buffer.from(e,0,t)}allocNative(e){return Buffer.allocUnsafe(e)}}o.emptyBuffer=Buffer.allocUnsafe(0);class s{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),i.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),i.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),i.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),i.Disposable.create(()=>this.stream.off("data",e))}}class a{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),i.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),i.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),i.Disposable.create(()=>this.stream.off("end",e))}write(e,t){return new Promise((n,r)=>{const i=e=>{null==e?n():r(e)};"string"==typeof e?this.stream.write(e,t,i):this.stream.write(e,i)})}end(){this.stream.end()}}const c=Object.freeze({messageBuffer:Object.freeze({create:e=>new o(e)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(e,t)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(e,void 0,0),t.charset))}catch(e){return Promise.reject(e)}}}),decoder:Object.freeze({name:"application/json",decode:(e,t)=>{try{return e instanceof Buffer?Promise.resolve(JSON.parse(e.toString(t.charset))):Promise.resolve(JSON.parse(new r.TextDecoder(t.charset).decode(e)))}catch(e){return Promise.reject(e)}}})}),stream:Object.freeze({asReadableStream:e=>new s(e),asWritableStream:e=>new a(e)}),console,timer:Object.freeze({setTimeout(e,t,...n){const r=setTimeout(e,t,...n);return{dispose:()=>clearTimeout(r)}},setImmediate(e,...t){const n=setImmediate(e,...t);return{dispose:()=>clearImmediate(n)}},setInterval(e,t,...n){const r=setInterval(e,t,...n);return{dispose:()=>clearInterval(r)}}})});function l(){return c}!function(e){e.install=function(){i.RAL.install(c)}}(l||(l={})),t.default=l},204:e=>{function t(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=204,e.exports=t},557:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.attachPartialResult=t.ProgressFeature=t.attachWorkDone=void 0;const r=n(8828),i=n(6116);class o{constructor(e,t){this._connection=e,this._token=t,o.Instances.set(this._token,this)}begin(e,t,n,i){let o={kind:"begin",title:e,percentage:t,message:n,cancellable:i};this._connection.sendProgress(r.WorkDoneProgress.type,this._token,o)}report(e,t){let n={kind:"report"};"number"==typeof e?(n.percentage=e,void 0!==t&&(n.message=t)):n.message=e,this._connection.sendProgress(r.WorkDoneProgress.type,this._token,n)}done(){o.Instances.delete(this._token),this._connection.sendProgress(r.WorkDoneProgress.type,this._token,{kind:"end"})}}o.Instances=new Map;class s extends o{constructor(e,t){super(e,t),this._source=new r.CancellationTokenSource}get token(){return this._source.token}done(){this._source.dispose(),super.done()}cancel(){this._source.cancel()}}class a{constructor(){}begin(){}report(){}done(){}}class c extends a{constructor(){super(),this._source=new r.CancellationTokenSource}get token(){return this._source.token}done(){this._source.dispose()}cancel(){this._source.cancel()}}var l;t.attachWorkDone=function(e,t){if(void 0===t||void 0===t.workDoneToken)return new a;const n=t.workDoneToken;return delete t.workDoneToken,new o(e,n)},t.ProgressFeature=e=>class extends e{constructor(){super(),this._progressSupported=!1}initialize(e){super.initialize(e),!0===e?.window?.workDoneProgress&&(this._progressSupported=!0,this.connection.onNotification(r.WorkDoneProgressCancelNotification.type,e=>{let t=o.Instances.get(e.token);(t instanceof s||t instanceof c)&&t.cancel()}))}attachWorkDoneProgress(e){return void 0===e?new a:new o(this.connection,e)}createWorkDoneProgress(){if(this._progressSupported){const e=(0,i.generateUuid)();return this.connection.sendRequest(r.WorkDoneProgressCreateRequest.type,{token:e}).then(()=>new s(this.connection,e))}return Promise.resolve(new c)}},function(e){e.type=new r.ProgressType}(l||(l={}));class u{constructor(e,t){this._connection=e,this._token=t}report(e){this._connection.sendProgress(l.type,this._token,e)}}t.attachPartialResult=function(e,t){if(void 0===t||void 0===t.partialResultToken)return;const n=t.partialResultToken;return delete t.partialResultToken,new u(e,n)}},692:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ImplementationRequest=void 0;const r=n(2834);var i;!function(e){e.method="textDocument/implementation",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.ImplementationRequest=i={}))},720:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.LSPErrorCodes=t.createProtocolConnection=void 0,i(n(5174),t),i(n(6616),t),i(n(2834),t),i(n(1138),t);var o,s=n(7614);Object.defineProperty(t,"createProtocolConnection",{enumerable:!0,get:function(){return s.createProtocolConnection}}),function(e){e.lspReservedErrorRangeStart=-32899,e.RequestFailed=-32803,e.ServerCancelled=-32802,e.ContentModified=-32801,e.RequestCancelled=-32800,e.lspReservedErrorRangeEnd=-32800}(o||(t.LSPErrorCodes=o={}))},857:e=>{"use strict";e.exports=require("os")},958:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteableStreamMessageWriter=t.AbstractMessageWriter=t.MessageWriter=void 0;const r=n(4017),i=n(6204),o=n(2968),s=n(3537);var a,c;!function(e){e.is=function(e){let t=e;return t&&i.func(t.dispose)&&i.func(t.onClose)&&i.func(t.onError)&&i.func(t.write)}}(a||(t.MessageWriter=a={}));class l{constructor(){this.errorEmitter=new s.Emitter,this.closeEmitter=new s.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,n){this.errorEmitter.fire([this.asError(e),t,n])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:new Error(`Writer received error. Reason: ${i.string(e.message)?e.message:"unknown"}`)}}t.AbstractMessageWriter=l,function(e){e.fromOptions=function(e){return void 0===e||"string"==typeof e?{charset:e??"utf-8",contentTypeEncoder:(0,r.default)().applicationJson.encoder}:{charset:e.charset??"utf-8",contentEncoder:e.contentEncoder,contentTypeEncoder:e.contentTypeEncoder??(0,r.default)().applicationJson.encoder}}}(c||(c={})),t.WriteableStreamMessageWriter=class extends l{constructor(e,t){super(),this.writable=e,this.options=c.fromOptions(t),this.errorCount=0,this.writeSemaphore=new o.Semaphore(1),this.writable.onError(e=>this.fireError(e)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(e=>void 0!==this.options.contentEncoder?this.options.contentEncoder.encode(e):e).then(t=>{const n=[];return n.push("Content-Length: ",t.byteLength.toString(),"\r\n"),n.push("\r\n"),this.doWrite(e,n,t)},e=>{throw this.fireError(e),e}))}async doWrite(e,t,n){try{return await this.writable.write(t.join(""),"ascii"),this.writable.write(n)}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){this.writable.end()}}},1138:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkspaceSymbolRequest=t.CodeActionResolveRequest=t.CodeActionRequest=t.DocumentSymbolRequest=t.DocumentHighlightRequest=t.ReferencesRequest=t.DefinitionRequest=t.SignatureHelpRequest=t.SignatureHelpTriggerKind=t.HoverRequest=t.CompletionResolveRequest=t.CompletionRequest=t.CompletionTriggerKind=t.PublishDiagnosticsNotification=t.WatchKind=t.RelativePattern=t.FileChangeType=t.DidChangeWatchedFilesNotification=t.WillSaveTextDocumentWaitUntilRequest=t.WillSaveTextDocumentNotification=t.TextDocumentSaveReason=t.DidSaveTextDocumentNotification=t.DidCloseTextDocumentNotification=t.DidChangeTextDocumentNotification=t.TextDocumentContentChangeEvent=t.DidOpenTextDocumentNotification=t.TextDocumentSyncKind=t.TelemetryEventNotification=t.LogMessageNotification=t.ShowMessageRequest=t.ShowMessageNotification=t.MessageType=t.DidChangeConfigurationNotification=t.ExitNotification=t.ShutdownRequest=t.InitializedNotification=t.InitializeErrorCodes=t.InitializeRequest=t.WorkDoneProgressOptions=t.TextDocumentRegistrationOptions=t.StaticRegistrationOptions=t.PositionEncodingKind=t.FailureHandlingKind=t.ResourceOperationKind=t.UnregistrationRequest=t.RegistrationRequest=t.DocumentSelector=t.NotebookCellTextDocumentFilter=t.NotebookDocumentFilter=t.TextDocumentFilter=void 0,t.MonikerRequest=t.MonikerKind=t.UniquenessLevel=t.WillDeleteFilesRequest=t.DidDeleteFilesNotification=t.WillRenameFilesRequest=t.DidRenameFilesNotification=t.WillCreateFilesRequest=t.DidCreateFilesNotification=t.FileOperationPatternKind=t.LinkedEditingRangeRequest=t.ShowDocumentRequest=t.SemanticTokensRegistrationType=t.SemanticTokensRefreshRequest=t.SemanticTokensRangeRequest=t.SemanticTokensDeltaRequest=t.SemanticTokensRequest=t.TokenFormat=t.CallHierarchyPrepareRequest=t.CallHierarchyOutgoingCallsRequest=t.CallHierarchyIncomingCallsRequest=t.WorkDoneProgressCancelNotification=t.WorkDoneProgressCreateRequest=t.WorkDoneProgress=t.SelectionRangeRequest=t.DeclarationRequest=t.FoldingRangeRefreshRequest=t.FoldingRangeRequest=t.ColorPresentationRequest=t.DocumentColorRequest=t.ConfigurationRequest=t.DidChangeWorkspaceFoldersNotification=t.WorkspaceFoldersRequest=t.TypeDefinitionRequest=t.ImplementationRequest=t.ApplyWorkspaceEditRequest=t.ExecuteCommandRequest=t.PrepareRenameRequest=t.RenameRequest=t.PrepareSupportDefaultBehavior=t.DocumentOnTypeFormattingRequest=t.DocumentRangesFormattingRequest=t.DocumentRangeFormattingRequest=t.DocumentFormattingRequest=t.DocumentLinkResolveRequest=t.DocumentLinkRequest=t.CodeLensRefreshRequest=t.CodeLensResolveRequest=t.CodeLensRequest=t.WorkspaceSymbolResolveRequest=void 0,t.InlineCompletionRequest=t.DidCloseNotebookDocumentNotification=t.DidSaveNotebookDocumentNotification=t.DidChangeNotebookDocumentNotification=t.NotebookCellArrayChange=t.DidOpenNotebookDocumentNotification=t.NotebookDocumentSyncRegistrationType=t.NotebookDocument=t.NotebookCell=t.ExecutionSummary=t.NotebookCellKind=t.DiagnosticRefreshRequest=t.WorkspaceDiagnosticRequest=t.DocumentDiagnosticRequest=t.DocumentDiagnosticReportKind=t.DiagnosticServerCancellationData=t.InlayHintRefreshRequest=t.InlayHintResolveRequest=t.InlayHintRequest=t.InlineValueRefreshRequest=t.InlineValueRequest=t.TypeHierarchySupertypesRequest=t.TypeHierarchySubtypesRequest=t.TypeHierarchyPrepareRequest=void 0;const r=n(2834),i=n(6616),o=n(8176),s=n(692);Object.defineProperty(t,"ImplementationRequest",{enumerable:!0,get:function(){return s.ImplementationRequest}});const a=n(6543);Object.defineProperty(t,"TypeDefinitionRequest",{enumerable:!0,get:function(){return a.TypeDefinitionRequest}});const c=n(8393);Object.defineProperty(t,"WorkspaceFoldersRequest",{enumerable:!0,get:function(){return c.WorkspaceFoldersRequest}}),Object.defineProperty(t,"DidChangeWorkspaceFoldersNotification",{enumerable:!0,get:function(){return c.DidChangeWorkspaceFoldersNotification}});const l=n(2938);Object.defineProperty(t,"ConfigurationRequest",{enumerable:!0,get:function(){return l.ConfigurationRequest}});const u=n(8214);Object.defineProperty(t,"DocumentColorRequest",{enumerable:!0,get:function(){return u.DocumentColorRequest}}),Object.defineProperty(t,"ColorPresentationRequest",{enumerable:!0,get:function(){return u.ColorPresentationRequest}});const p=n(1392);Object.defineProperty(t,"FoldingRangeRequest",{enumerable:!0,get:function(){return p.FoldingRangeRequest}}),Object.defineProperty(t,"FoldingRangeRefreshRequest",{enumerable:!0,get:function(){return p.FoldingRangeRefreshRequest}});const d=n(1888);Object.defineProperty(t,"DeclarationRequest",{enumerable:!0,get:function(){return d.DeclarationRequest}});const m=n(6749);Object.defineProperty(t,"SelectionRangeRequest",{enumerable:!0,get:function(){return m.SelectionRangeRequest}});const h=n(8953);Object.defineProperty(t,"WorkDoneProgress",{enumerable:!0,get:function(){return h.WorkDoneProgress}}),Object.defineProperty(t,"WorkDoneProgressCreateRequest",{enumerable:!0,get:function(){return h.WorkDoneProgressCreateRequest}}),Object.defineProperty(t,"WorkDoneProgressCancelNotification",{enumerable:!0,get:function(){return h.WorkDoneProgressCancelNotification}});const f=n(6675);Object.defineProperty(t,"CallHierarchyIncomingCallsRequest",{enumerable:!0,get:function(){return f.CallHierarchyIncomingCallsRequest}}),Object.defineProperty(t,"CallHierarchyOutgoingCallsRequest",{enumerable:!0,get:function(){return f.CallHierarchyOutgoingCallsRequest}}),Object.defineProperty(t,"CallHierarchyPrepareRequest",{enumerable:!0,get:function(){return f.CallHierarchyPrepareRequest}});const g=n(1612);Object.defineProperty(t,"TokenFormat",{enumerable:!0,get:function(){return g.TokenFormat}}),Object.defineProperty(t,"SemanticTokensRequest",{enumerable:!0,get:function(){return g.SemanticTokensRequest}}),Object.defineProperty(t,"SemanticTokensDeltaRequest",{enumerable:!0,get:function(){return g.SemanticTokensDeltaRequest}}),Object.defineProperty(t,"SemanticTokensRangeRequest",{enumerable:!0,get:function(){return g.SemanticTokensRangeRequest}}),Object.defineProperty(t,"SemanticTokensRefreshRequest",{enumerable:!0,get:function(){return g.SemanticTokensRefreshRequest}}),Object.defineProperty(t,"SemanticTokensRegistrationType",{enumerable:!0,get:function(){return g.SemanticTokensRegistrationType}});const y=n(4198);Object.defineProperty(t,"ShowDocumentRequest",{enumerable:!0,get:function(){return y.ShowDocumentRequest}});const T=n(5714);Object.defineProperty(t,"LinkedEditingRangeRequest",{enumerable:!0,get:function(){return T.LinkedEditingRangeRequest}});const _=n(8754);Object.defineProperty(t,"FileOperationPatternKind",{enumerable:!0,get:function(){return _.FileOperationPatternKind}}),Object.defineProperty(t,"DidCreateFilesNotification",{enumerable:!0,get:function(){return _.DidCreateFilesNotification}}),Object.defineProperty(t,"WillCreateFilesRequest",{enumerable:!0,get:function(){return _.WillCreateFilesRequest}}),Object.defineProperty(t,"DidRenameFilesNotification",{enumerable:!0,get:function(){return _.DidRenameFilesNotification}}),Object.defineProperty(t,"WillRenameFilesRequest",{enumerable:!0,get:function(){return _.WillRenameFilesRequest}}),Object.defineProperty(t,"DidDeleteFilesNotification",{enumerable:!0,get:function(){return _.DidDeleteFilesNotification}}),Object.defineProperty(t,"WillDeleteFilesRequest",{enumerable:!0,get:function(){return _.WillDeleteFilesRequest}});const N=n(3821);Object.defineProperty(t,"UniquenessLevel",{enumerable:!0,get:function(){return N.UniquenessLevel}}),Object.defineProperty(t,"MonikerKind",{enumerable:!0,get:function(){return N.MonikerKind}}),Object.defineProperty(t,"MonikerRequest",{enumerable:!0,get:function(){return N.MonikerRequest}});const R=n(1679);Object.defineProperty(t,"TypeHierarchyPrepareRequest",{enumerable:!0,get:function(){return R.TypeHierarchyPrepareRequest}}),Object.defineProperty(t,"TypeHierarchySubtypesRequest",{enumerable:!0,get:function(){return R.TypeHierarchySubtypesRequest}}),Object.defineProperty(t,"TypeHierarchySupertypesRequest",{enumerable:!0,get:function(){return R.TypeHierarchySupertypesRequest}});const E=n(8998);Object.defineProperty(t,"InlineValueRequest",{enumerable:!0,get:function(){return E.InlineValueRequest}}),Object.defineProperty(t,"InlineValueRefreshRequest",{enumerable:!0,get:function(){return E.InlineValueRefreshRequest}});const b=n(4182);Object.defineProperty(t,"InlayHintRequest",{enumerable:!0,get:function(){return b.InlayHintRequest}}),Object.defineProperty(t,"InlayHintResolveRequest",{enumerable:!0,get:function(){return b.InlayHintResolveRequest}}),Object.defineProperty(t,"InlayHintRefreshRequest",{enumerable:!0,get:function(){return b.InlayHintRefreshRequest}});const v=n(8577);Object.defineProperty(t,"DiagnosticServerCancellationData",{enumerable:!0,get:function(){return v.DiagnosticServerCancellationData}}),Object.defineProperty(t,"DocumentDiagnosticReportKind",{enumerable:!0,get:function(){return v.DocumentDiagnosticReportKind}}),Object.defineProperty(t,"DocumentDiagnosticRequest",{enumerable:!0,get:function(){return v.DocumentDiagnosticRequest}}),Object.defineProperty(t,"WorkspaceDiagnosticRequest",{enumerable:!0,get:function(){return v.WorkspaceDiagnosticRequest}}),Object.defineProperty(t,"DiagnosticRefreshRequest",{enumerable:!0,get:function(){return v.DiagnosticRefreshRequest}});const S=n(5887);Object.defineProperty(t,"NotebookCellKind",{enumerable:!0,get:function(){return S.NotebookCellKind}}),Object.defineProperty(t,"ExecutionSummary",{enumerable:!0,get:function(){return S.ExecutionSummary}}),Object.defineProperty(t,"NotebookCell",{enumerable:!0,get:function(){return S.NotebookCell}}),Object.defineProperty(t,"NotebookDocument",{enumerable:!0,get:function(){return S.NotebookDocument}}),Object.defineProperty(t,"NotebookDocumentSyncRegistrationType",{enumerable:!0,get:function(){return S.NotebookDocumentSyncRegistrationType}}),Object.defineProperty(t,"DidOpenNotebookDocumentNotification",{enumerable:!0,get:function(){return S.DidOpenNotebookDocumentNotification}}),Object.defineProperty(t,"NotebookCellArrayChange",{enumerable:!0,get:function(){return S.NotebookCellArrayChange}}),Object.defineProperty(t,"DidChangeNotebookDocumentNotification",{enumerable:!0,get:function(){return S.DidChangeNotebookDocumentNotification}}),Object.defineProperty(t,"DidSaveNotebookDocumentNotification",{enumerable:!0,get:function(){return S.DidSaveNotebookDocumentNotification}}),Object.defineProperty(t,"DidCloseNotebookDocumentNotification",{enumerable:!0,get:function(){return S.DidCloseNotebookDocumentNotification}});const C=n(7861);var A,O,L,I,D,k,P,x,w,M,F,U,K,G,B,W,$,j,q,V,H,Y,X,z,J,Q,Z,ee,te,ne,re,ie,oe,se,ae,ce,le,ue,pe,de,me,he,fe,ge,ye,Te,_e,Ne,Re,Ee,be,ve,Se,Ce,Ae,Oe,Le,Ie,De,ke,Pe,xe,we,Me,Fe;Object.defineProperty(t,"InlineCompletionRequest",{enumerable:!0,get:function(){return C.InlineCompletionRequest}}),function(e){e.is=function(e){const t=e;return o.string(t)||o.string(t.language)||o.string(t.scheme)||o.string(t.pattern)}}(A||(t.TextDocumentFilter=A={})),function(e){e.is=function(e){const t=e;return o.objectLiteral(t)&&(o.string(t.notebookType)||o.string(t.scheme)||o.string(t.pattern))}}(O||(t.NotebookDocumentFilter=O={})),function(e){e.is=function(e){const t=e;return o.objectLiteral(t)&&(o.string(t.notebook)||O.is(t.notebook))&&(void 0===t.language||o.string(t.language))}}(L||(t.NotebookCellTextDocumentFilter=L={})),function(e){e.is=function(e){if(!Array.isArray(e))return!1;for(let t of e)if(!o.string(t)&&!A.is(t)&&!L.is(t))return!1;return!0}}(I||(t.DocumentSelector=I={})),function(e){e.method="client/registerCapability",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType(e.method)}(D||(t.RegistrationRequest=D={})),function(e){e.method="client/unregisterCapability",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType(e.method)}(k||(t.UnregistrationRequest=k={})),function(e){e.Create="create",e.Rename="rename",e.Delete="delete"}(P||(t.ResourceOperationKind=P={})),function(e){e.Abort="abort",e.Transactional="transactional",e.TextOnlyTransactional="textOnlyTransactional",e.Undo="undo"}(x||(t.FailureHandlingKind=x={})),function(e){e.UTF8="utf-8",e.UTF16="utf-16",e.UTF32="utf-32"}(w||(t.PositionEncodingKind=w={})),function(e){e.hasId=function(e){const t=e;return t&&o.string(t.id)&&t.id.length>0}}(M||(t.StaticRegistrationOptions=M={})),function(e){e.is=function(e){const t=e;return t&&(null===t.documentSelector||I.is(t.documentSelector))}}(F||(t.TextDocumentRegistrationOptions=F={})),function(e){e.is=function(e){const t=e;return o.objectLiteral(t)&&(void 0===t.workDoneProgress||o.boolean(t.workDoneProgress))},e.hasWorkDoneProgress=function(e){const t=e;return t&&o.boolean(t.workDoneProgress)}}(U||(t.WorkDoneProgressOptions=U={})),function(e){e.method="initialize",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(K||(t.InitializeRequest=K={})),function(e){e.unknownProtocolVersion=1}(G||(t.InitializeErrorCodes=G={})),function(e){e.method="initialized",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(B||(t.InitializedNotification=B={})),function(e){e.method="shutdown",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType0(e.method)}(W||(t.ShutdownRequest=W={})),function(e){e.method="exit",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType0(e.method)}($||(t.ExitNotification=$={})),function(e){e.method="workspace/didChangeConfiguration",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(j||(t.DidChangeConfigurationNotification=j={})),function(e){e.Error=1,e.Warning=2,e.Info=3,e.Log=4,e.Debug=5}(q||(t.MessageType=q={})),function(e){e.method="window/showMessage",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolNotificationType(e.method)}(V||(t.ShowMessageNotification=V={})),function(e){e.method="window/showMessageRequest",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType(e.method)}(H||(t.ShowMessageRequest=H={})),function(e){e.method="window/logMessage",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolNotificationType(e.method)}(Y||(t.LogMessageNotification=Y={})),function(e){e.method="telemetry/event",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolNotificationType(e.method)}(X||(t.TelemetryEventNotification=X={})),function(e){e.None=0,e.Full=1,e.Incremental=2}(z||(t.TextDocumentSyncKind=z={})),function(e){e.method="textDocument/didOpen",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(J||(t.DidOpenTextDocumentNotification=J={})),function(e){e.isIncremental=function(e){let t=e;return null!=t&&"string"==typeof t.text&&void 0!==t.range&&(void 0===t.rangeLength||"number"==typeof t.rangeLength)},e.isFull=function(e){let t=e;return null!=t&&"string"==typeof t.text&&void 0===t.range&&void 0===t.rangeLength}}(Q||(t.TextDocumentContentChangeEvent=Q={})),function(e){e.method="textDocument/didChange",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(Z||(t.DidChangeTextDocumentNotification=Z={})),function(e){e.method="textDocument/didClose",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(ee||(t.DidCloseTextDocumentNotification=ee={})),function(e){e.method="textDocument/didSave",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(te||(t.DidSaveTextDocumentNotification=te={})),function(e){e.Manual=1,e.AfterDelay=2,e.FocusOut=3}(ne||(t.TextDocumentSaveReason=ne={})),function(e){e.method="textDocument/willSave",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(re||(t.WillSaveTextDocumentNotification=re={})),function(e){e.method="textDocument/willSaveWaitUntil",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(ie||(t.WillSaveTextDocumentWaitUntilRequest=ie={})),function(e){e.method="workspace/didChangeWatchedFiles",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(oe||(t.DidChangeWatchedFilesNotification=oe={})),function(e){e.Created=1,e.Changed=2,e.Deleted=3}(se||(t.FileChangeType=se={})),function(e){e.is=function(e){const t=e;return o.objectLiteral(t)&&(i.URI.is(t.baseUri)||i.WorkspaceFolder.is(t.baseUri))&&o.string(t.pattern)}}(ae||(t.RelativePattern=ae={})),function(e){e.Create=1,e.Change=2,e.Delete=4}(ce||(t.WatchKind=ce={})),function(e){e.method="textDocument/publishDiagnostics",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolNotificationType(e.method)}(le||(t.PublishDiagnosticsNotification=le={})),function(e){e.Invoked=1,e.TriggerCharacter=2,e.TriggerForIncompleteCompletions=3}(ue||(t.CompletionTriggerKind=ue={})),function(e){e.method="textDocument/completion",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(pe||(t.CompletionRequest=pe={})),function(e){e.method="completionItem/resolve",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(de||(t.CompletionResolveRequest=de={})),function(e){e.method="textDocument/hover",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(me||(t.HoverRequest=me={})),function(e){e.Invoked=1,e.TriggerCharacter=2,e.ContentChange=3}(he||(t.SignatureHelpTriggerKind=he={})),function(e){e.method="textDocument/signatureHelp",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(fe||(t.SignatureHelpRequest=fe={})),function(e){e.method="textDocument/definition",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(ge||(t.DefinitionRequest=ge={})),function(e){e.method="textDocument/references",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(ye||(t.ReferencesRequest=ye={})),function(e){e.method="textDocument/documentHighlight",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Te||(t.DocumentHighlightRequest=Te={})),function(e){e.method="textDocument/documentSymbol",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(_e||(t.DocumentSymbolRequest=_e={})),function(e){e.method="textDocument/codeAction",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Ne||(t.CodeActionRequest=Ne={})),function(e){e.method="codeAction/resolve",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Re||(t.CodeActionResolveRequest=Re={})),function(e){e.method="workspace/symbol",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Ee||(t.WorkspaceSymbolRequest=Ee={})),function(e){e.method="workspaceSymbol/resolve",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(be||(t.WorkspaceSymbolResolveRequest=be={})),function(e){e.method="textDocument/codeLens",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(ve||(t.CodeLensRequest=ve={})),function(e){e.method="codeLens/resolve",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Se||(t.CodeLensResolveRequest=Se={})),function(e){e.method="workspace/codeLens/refresh",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType0(e.method)}(Ce||(t.CodeLensRefreshRequest=Ce={})),function(e){e.method="textDocument/documentLink",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Ae||(t.DocumentLinkRequest=Ae={})),function(e){e.method="documentLink/resolve",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Oe||(t.DocumentLinkResolveRequest=Oe={})),function(e){e.method="textDocument/formatting",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Le||(t.DocumentFormattingRequest=Le={})),function(e){e.method="textDocument/rangeFormatting",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Ie||(t.DocumentRangeFormattingRequest=Ie={})),function(e){e.method="textDocument/rangesFormatting",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(De||(t.DocumentRangesFormattingRequest=De={})),function(e){e.method="textDocument/onTypeFormatting",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(ke||(t.DocumentOnTypeFormattingRequest=ke={})),function(e){e.Identifier=1}(Pe||(t.PrepareSupportDefaultBehavior=Pe={})),function(e){e.method="textDocument/rename",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(xe||(t.RenameRequest=xe={})),function(e){e.method="textDocument/prepareRename",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(we||(t.PrepareRenameRequest=we={})),function(e){e.method="workspace/executeCommand",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(Me||(t.ExecuteCommandRequest=Me={})),function(e){e.method="workspace/applyEdit",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType("workspace/applyEdit")}(Fe||(t.ApplyWorkspaceEditRequest=Fe={}))},1276:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InlineCompletionFeature=void 0;const r=n(8828);t.InlineCompletionFeature=e=>class extends e{get inlineCompletion(){return{on:e=>this.connection.onRequest(r.InlineCompletionRequest.type,(t,n)=>e(t,n,this.attachWorkDoneProgress(t)))}}}},1327:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.createConnection=t.Files=void 0;const o=n(7975),s=n(8867),a=n(7874),c=n(3911),l=n(3538);var u;i(n(3538),t),i(n(2861),t),function(e){e.uriToFilePath=c.uriToFilePath,e.resolveGlobalNodePath=c.resolveGlobalNodePath,e.resolveGlobalYarnPath=c.resolveGlobalYarnPath,e.resolve=c.resolve,e.resolveModulePath=c.resolveModulePath}(u||(t.Files=u={}));let p,d=!1;!function(){const e="--clientProcessId";function t(e){try{let t=parseInt(e);isNaN(t)||(p=setInterval(()=>{try{process.kill(t,0)}catch(e){process.exit(d?0:1)}},3e3))}catch(e){}}for(let n=2;n<process.argv.length;n++){let r=process.argv[n];if(r===e&&n+1<process.argv.length)return void t(process.argv[n+1]);{let n=r.split("=");n[0]===e&&t(n[1])}}}();const m={initialize:e=>{const t=e.processId;s.number(t)&&void 0===p&&setInterval(()=>{try{process.kill(t,0)}catch(e){process.exit(d?0:1)}},3e3)},get shutdownReceived(){return d},set shutdownReceived(e){d=e},exit:e=>{process.exit(e)}};t.createConnection=function(e,t,n,r){let i,c,u,p;return void 0!==e&&"features"===e.__brand&&(i=e,e=t,t=n,n=r),l.ConnectionStrategy.is(e)||l.ConnectionOptions.is(e)?p=e:(c=e,u=t,p=n),function(e,t,n,r){let i=!1;if(!e&&!t&&process.argv.length>2){let n,r,o=process.argv.slice(2);for(let s=0;s<o.length;s++){let a=o[s];if("--node-ipc"===a){e=new l.IPCMessageReader(process),t=new l.IPCMessageWriter(process);break}if("--stdio"===a){i=!0,e=process.stdin,t=process.stdout;break}if("--socket"===a){n=parseInt(o[s+1]);break}if("--pipe"===a){r=o[s+1];break}var c=a.split("=");if("--socket"===c[0]){n=parseInt(c[1]);break}if("--pipe"===c[0]){r=c[1];break}}if(n){let r=(0,l.createServerSocketTransport)(n);e=r[0],t=r[1]}else if(r){let n=(0,l.createServerPipeTransport)(r);e=n[0],t=n[1]}}var u="Use arguments of createConnection or set command line parameters: '--node-ipc', '--stdio' or '--socket={number}'";if(!e)throw new Error("Connection input stream is not set. "+u);if(!t)throw new Error("Connection output stream is not set. "+u);if(s.func(e.read)&&s.func(e.on)){let t=e;t.on("end",()=>{process.exit(d?0:1)}),t.on("close",()=>{process.exit(d?0:1)})}return(0,a.createConnection)(r=>{const s=(0,l.createProtocolConnection)(e,t,r,n);return i&&function(e){function t(e){return e.map(e=>"string"==typeof e?e:(0,o.inspect)(e)).join(" ")}const n=new Map;console.assert=function(n,...r){if(!n)if(0===r.length)e.error("Assertion failed");else{const[n,...i]=r;e.error(`Assertion failed: ${n} ${t(i)}`)}},console.count=function(t="default"){const r=String(t);let i=n.get(r)??0;i+=1,n.set(r,i),e.log(`${r}: ${r}`)},console.countReset=function(e){void 0===e?n.clear():n.delete(String(e))},console.debug=function(...n){e.log(t(n))},console.dir=function(t,n){e.log((0,o.inspect)(t,n))},console.log=function(...n){e.log(t(n))},console.error=function(...n){e.error(t(n))},console.trace=function(...n){const r=(new Error).stack.replace(/(.+\n){2}/,"");let i="Trace";0!==n.length&&(i+=`: ${t(n)}`),e.log(`${i}\n${r}`)},console.warn=function(...n){e.warn(t(n))}}(r),s},m,r)}(c,u,p,i)}},1392:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FoldingRangeRefreshRequest=t.FoldingRangeRequest=void 0;const r=n(2834);var i,o;!function(e){e.method="textDocument/foldingRange",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.FoldingRangeRequest=i={})),function(e){e.method="workspace/foldingRange/refresh",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType0(e.method)}(o||(t.FoldingRangeRefreshRequest=o={}))},1612:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SemanticTokensRefreshRequest=t.SemanticTokensRangeRequest=t.SemanticTokensDeltaRequest=t.SemanticTokensRequest=t.SemanticTokensRegistrationType=t.TokenFormat=void 0;const r=n(2834);var i,o,s,a,c,l;!function(e){e.Relative="relative"}(i||(t.TokenFormat=i={})),function(e){e.method="textDocument/semanticTokens",e.type=new r.RegistrationType(e.method)}(o||(t.SemanticTokensRegistrationType=o={})),function(e){e.method="textDocument/semanticTokens/full",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method),e.registrationMethod=o.method}(s||(t.SemanticTokensRequest=s={})),function(e){e.method="textDocument/semanticTokens/full/delta",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method),e.registrationMethod=o.method}(a||(t.SemanticTokensDeltaRequest=a={})),function(e){e.method="textDocument/semanticTokens/range",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method),e.registrationMethod=o.method}(c||(t.SemanticTokensRangeRequest=c={})),function(e){e.method="workspace/semanticTokens/refresh",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType0(e.method)}(l||(t.SemanticTokensRefreshRequest=l={}))},1662:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TextDocuments=void 0;const r=n(8828);t.TextDocuments=class{constructor(e){this._configuration=e,this._syncedDocuments=new Map,this._onDidChangeContent=new r.Emitter,this._onDidOpen=new r.Emitter,this._onDidClose=new r.Emitter,this._onDidSave=new r.Emitter,this._onWillSave=new r.Emitter}get onDidOpen(){return this._onDidOpen.event}get onDidChangeContent(){return this._onDidChangeContent.event}get onWillSave(){return this._onWillSave.event}onWillSaveWaitUntil(e){this._willSaveWaitUntil=e}get onDidSave(){return this._onDidSave.event}get onDidClose(){return this._onDidClose.event}get(e){return this._syncedDocuments.get(e)}all(){return Array.from(this._syncedDocuments.values())}keys(){return Array.from(this._syncedDocuments.keys())}listen(e){e.__textDocumentSync=r.TextDocumentSyncKind.Incremental;const t=[];return t.push(e.onDidOpenTextDocument(e=>{const t=e.textDocument,n=this._configuration.create(t.uri,t.languageId,t.version,t.text);this._syncedDocuments.set(t.uri,n);const r=Object.freeze({document:n});this._onDidOpen.fire(r),this._onDidChangeContent.fire(r)})),t.push(e.onDidChangeTextDocument(e=>{const t=e.textDocument,n=e.contentChanges;if(0===n.length)return;const{version:r}=t;if(null==r)throw new Error(`Received document change event for ${t.uri} without valid version identifier`);let i=this._syncedDocuments.get(t.uri);void 0!==i&&(i=this._configuration.update(i,n,r),this._syncedDocuments.set(t.uri,i),this._onDidChangeContent.fire(Object.freeze({document:i})))})),t.push(e.onDidCloseTextDocument(e=>{let t=this._syncedDocuments.get(e.textDocument.uri);void 0!==t&&(this._syncedDocuments.delete(e.textDocument.uri),this._onDidClose.fire(Object.freeze({document:t})))})),t.push(e.onWillSaveTextDocument(e=>{let t=this._syncedDocuments.get(e.textDocument.uri);void 0!==t&&this._onWillSave.fire(Object.freeze({document:t,reason:e.reason}))})),t.push(e.onWillSaveTextDocumentWaitUntil((e,t)=>{let n=this._syncedDocuments.get(e.textDocument.uri);return void 0!==n&&this._willSaveWaitUntil?this._willSaveWaitUntil(Object.freeze({document:n,reason:e.reason}),t):[]})),t.push(e.onDidSaveTextDocument(e=>{let t=this._syncedDocuments.get(e.textDocument.uri);void 0!==t&&this._onDidSave.fire(Object.freeze({document:t}))})),r.Disposable.create(()=>{t.forEach(e=>e.dispose())})}}},1679:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TypeHierarchySubtypesRequest=t.TypeHierarchySupertypesRequest=t.TypeHierarchyPrepareRequest=void 0;const r=n(2834);var i,o,s;!function(e){e.method="textDocument/prepareTypeHierarchy",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.TypeHierarchyPrepareRequest=i={})),function(e){e.method="typeHierarchy/supertypes",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(o||(t.TypeHierarchySupertypesRequest=o={})),function(e){e.method="typeHierarchy/subtypes",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(s||(t.TypeHierarchySubtypesRequest=s={}))},1815:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InlineValueFeature=void 0;const r=n(8828);t.InlineValueFeature=e=>class extends e{get inlineValue(){return{refresh:()=>this.connection.sendRequest(r.InlineValueRefreshRequest.type),on:e=>this.connection.onRequest(r.InlineValueRequest.type,(t,n)=>e(t,n,this.attachWorkDoneProgress(t)))}}}},1888:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DeclarationRequest=void 0;const r=n(2834);var i;!function(e){e.method="textDocument/declaration",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.DeclarationRequest=i={}))},2112:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkspaceFoldersFeature=void 0;const r=n(8828);t.WorkspaceFoldersFeature=e=>class extends e{constructor(){super(),this._notificationIsAutoRegistered=!1}initialize(e){super.initialize(e);let t=e.workspace;t&&t.workspaceFolders&&(this._onDidChangeWorkspaceFolders=new r.Emitter,this.connection.onNotification(r.DidChangeWorkspaceFoldersNotification.type,e=>{this._onDidChangeWorkspaceFolders.fire(e.event)}))}fillServerCapabilities(e){super.fillServerCapabilities(e);const t=e.workspace?.workspaceFolders?.changeNotifications;this._notificationIsAutoRegistered=!0===t||"string"==typeof t}getWorkspaceFolders(){return this.connection.sendRequest(r.WorkspaceFoldersRequest.type)}get onDidChangeWorkspaceFolders(){if(!this._onDidChangeWorkspaceFolders)throw new Error("Client doesn't support sending workspace folder change events.");return this._notificationIsAutoRegistered||this._unregistration||(this._unregistration=this.connection.client.register(r.DidChangeWorkspaceFoldersNotification.type)),this._onDidChangeWorkspaceFolders.event}}},2655:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SemanticTokensBuilder=t.SemanticTokensDiff=t.SemanticTokensFeature=void 0;const r=n(8828);t.SemanticTokensFeature=e=>class extends e{get semanticTokens(){return{refresh:()=>this.connection.sendRequest(r.SemanticTokensRefreshRequest.type),on:e=>{const t=r.SemanticTokensRequest.type;return this.connection.onRequest(t,(n,r)=>e(n,r,this.attachWorkDoneProgress(n),this.attachPartialResultProgress(t,n)))},onDelta:e=>{const t=r.SemanticTokensDeltaRequest.type;return this.connection.onRequest(t,(n,r)=>e(n,r,this.attachWorkDoneProgress(n),this.attachPartialResultProgress(t,n)))},onRange:e=>{const t=r.SemanticTokensRangeRequest.type;return this.connection.onRequest(t,(n,r)=>e(n,r,this.attachWorkDoneProgress(n),this.attachPartialResultProgress(t,n)))}}}};class i{constructor(e,t){this.originalSequence=e,this.modifiedSequence=t}computeDiff(){const e=this.originalSequence.length,t=this.modifiedSequence.length;let n=0;for(;n<t&&n<e&&this.originalSequence[n]===this.modifiedSequence[n];)n++;if(n<t&&n<e){let r=e-1,i=t-1;for(;r>=n&&i>=n&&this.originalSequence[r]===this.modifiedSequence[i];)r--,i--;(r<n||i<n)&&(r++,i++);const o=r-n+1,s=this.modifiedSequence.slice(n,i+1);return 1===s.length&&s[0]===this.originalSequence[r]?[{start:n,deleteCount:o-1}]:[{start:n,deleteCount:o,data:s}]}return n<t?[{start:n,deleteCount:0,data:this.modifiedSequence.slice(n)}]:n<e?[{start:n,deleteCount:e-n}]:[]}}t.SemanticTokensDiff=i,t.SemanticTokensBuilder=class{constructor(){this._prevData=void 0,this.initialize()}initialize(){this._id=Date.now(),this._prevLine=0,this._prevChar=0,this._data=[],this._dataLen=0}push(e,t,n,r,i){let o=e,s=t;this._dataLen>0&&(o-=this._prevLine,0===o&&(s-=this._prevChar)),this._data[this._dataLen++]=o,this._data[this._dataLen++]=s,this._data[this._dataLen++]=n,this._data[this._dataLen++]=r,this._data[this._dataLen++]=i,this._prevLine=e,this._prevChar=t}get id(){return this._id.toString()}previousResult(e){this.id===e&&(this._prevData=this._data),this.initialize()}build(){return this._prevData=void 0,{resultId:this.id,data:this._data}}canBuildEdits(){return void 0!==this._prevData}buildEdits(){return void 0!==this._prevData?{resultId:this.id,edits:new i(this._prevData,this._data).computeDiff()}:this.build()}}},2697:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileOperationsFeature=void 0;const r=n(8828);t.FileOperationsFeature=e=>class extends e{onDidCreateFiles(e){return this.connection.onNotification(r.DidCreateFilesNotification.type,t=>{e(t)})}onDidRenameFiles(e){return this.connection.onNotification(r.DidRenameFilesNotification.type,t=>{e(t)})}onDidDeleteFiles(e){return this.connection.onNotification(r.DidDeleteFilesNotification.type,t=>{e(t)})}onWillCreateFiles(e){return this.connection.onRequest(r.WillCreateFilesRequest.type,(t,n)=>e(t,n))}onWillRenameFiles(e){return this.connection.onRequest(r.WillRenameFilesRequest.type,(t,n)=>e(t,n))}onWillDeleteFiles(e){return this.connection.onRequest(r.WillDeleteFilesRequest.type,(t,n)=>e(t,n))}}},2834:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProtocolNotificationType=t.ProtocolNotificationType0=t.ProtocolRequestType=t.ProtocolRequestType0=t.RegistrationType=t.MessageDirection=void 0;const r=n(5174);var i;!function(e){e.clientToServer="clientToServer",e.serverToClient="serverToClient",e.both="both"}(i||(t.MessageDirection=i={})),t.RegistrationType=class{constructor(e){this.method=e}};class o extends r.RequestType0{constructor(e){super(e)}}t.ProtocolRequestType0=o;class s extends r.RequestType{constructor(e){super(e,r.ParameterStructures.byName)}}t.ProtocolRequestType=s;class a extends r.NotificationType0{constructor(e){super(e)}}t.ProtocolNotificationType0=a;class c extends r.NotificationType{constructor(e){super(e,r.ParameterStructures.byName)}}t.ProtocolNotificationType=c},2861:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.ProposedFeatures=t.NotebookDocuments=t.TextDocuments=t.SemanticTokensBuilder=void 0;const o=n(2655);Object.defineProperty(t,"SemanticTokensBuilder",{enumerable:!0,get:function(){return o.SemanticTokensBuilder}});const s=n(1276);i(n(8828),t);const a=n(1662);Object.defineProperty(t,"TextDocuments",{enumerable:!0,get:function(){return a.TextDocuments}});const c=n(20);var l;Object.defineProperty(t,"NotebookDocuments",{enumerable:!0,get:function(){return c.NotebookDocuments}}),i(n(7874),t),function(e){e.all={__brand:"features",languages:s.InlineCompletionFeature}}(l||(t.ProposedFeatures=l={}))},2874:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DiagnosticFeature=void 0;const r=n(8828);t.DiagnosticFeature=e=>class extends e{get diagnostics(){return{refresh:()=>this.connection.sendRequest(r.DiagnosticRefreshRequest.type),on:e=>this.connection.onRequest(r.DocumentDiagnosticRequest.type,(t,n)=>e(t,n,this.attachWorkDoneProgress(t),this.attachPartialResultProgress(r.DocumentDiagnosticRequest.partialResult,t))),onWorkspace:e=>this.connection.onRequest(r.WorkspaceDiagnosticRequest.type,(t,n)=>e(t,n,this.attachWorkDoneProgress(t),this.attachPartialResultProgress(r.WorkspaceDiagnosticRequest.partialResult,t)))}}}},2936:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MonikerFeature=void 0;const r=n(8828);t.MonikerFeature=e=>class extends e{get moniker(){return{on:e=>{const t=r.MonikerRequest.type;return this.connection.onRequest(t,(n,r)=>e(n,r,this.attachWorkDoneProgress(n),this.attachPartialResultProgress(t,n)))}}}}},2938:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConfigurationRequest=void 0;const r=n(2834);var i;!function(e){e.method="workspace/configuration",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType(e.method)}(i||(t.ConfigurationRequest=i={}))},2968:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Semaphore=void 0;const r=n(4017);t.Semaphore=class{constructor(e=1){if(e<=0)throw new Error("Capacity must be greater than 0");this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,n)=>{this._waiting.push({thunk:e,resolve:t,reject:n}),this.runNext()})}get active(){return this._active}runNext(){0!==this._waiting.length&&this._active!==this._capacity&&(0,r.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(0===this._waiting.length||this._active===this._capacity)return;const e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{const t=e.thunk();t instanceof Promise?t.then(t=>{this._active--,e.resolve(t),this.runNext()},t=>{this._active--,e.reject(t),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}}},3498:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.Disposable=void 0,function(e){e.create=function(e){return{dispose:e}}}(n||(t.Disposable=n={}))},3537:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Emitter=t.Event=void 0;const r=n(4017);var i;!function(e){const t={dispose(){}};e.None=function(){return t}}(i||(t.Event=i={}));class o{add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let r=0,i=this._callbacks.length;r<i;r++)if(this._callbacks[r]===e){if(this._contexts[r]===t)return this._callbacks.splice(r,1),void this._contexts.splice(r,1);n=!0}if(n)throw new Error("When adding a listener with a context, you should remove it with the same context")}invoke(...e){if(!this._callbacks)return[];const t=[],n=this._callbacks.slice(0),i=this._contexts.slice(0);for(let o=0,s=n.length;o<s;o++)try{t.push(n[o].apply(i[o],e))}catch(e){(0,r.default)().console.error(e)}return t}isEmpty(){return!this._callbacks||0===this._callbacks.length}dispose(){this._callbacks=void 0,this._contexts=void 0}}class s{constructor(e){this._options=e}get event(){return this._event||(this._event=(e,t,n)=>{this._callbacks||(this._callbacks=new o),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,t);const r={dispose:()=>{this._callbacks&&(this._callbacks.remove(e,t),r.dispose=s._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(n)&&n.push(r),r}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}}t.Emitter=s,s._noop=function(){}},3538:(e,t,n)=>{"use strict";e.exports=n(8828)},3623:(e,t)=>{"use strict";var n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.LRUCache=t.LinkedMap=t.Touch=void 0,function(e){e.None=0,e.First=1,e.AsOld=e.First,e.Last=2,e.AsNew=e.Last}(r||(t.Touch=r={}));class i{constructor(){this[n]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,t=r.None){const n=this._map.get(e);if(n)return t!==r.None&&this.touch(n,t),n.value}set(e,t,n=r.None){let i=this._map.get(e);if(i)i.value=t,n!==r.None&&this.touch(i,n);else{switch(i={key:e,value:t,next:void 0,previous:void 0},n){case r.None:this.addItemLast(i);break;case r.First:this.addItemFirst(i);break;case r.Last:default:this.addItemLast(i)}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){const t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");const e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){const n=this._state;let r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==n)throw new Error("LinkedMap got modified during iteration.");r=r.next}}keys(){const e=this._state;let t=this._head;const n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){const e={value:t.key,done:!1};return t=t.next,e}return{value:void 0,done:!0}}};return n}values(){const e=this._state;let t=this._head;const n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){const e={value:t.value,done:!1};return t=t.next,e}return{value:void 0,done:!0}}};return n}entries(){const e=this._state;let t=this._head;const n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){const e={value:[t.key,t.value],done:!1};return t=t.next,e}return{value:void 0,done:!0}}};return n}[(n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(0===e)return void this.clear();let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(this._head||this._tail){if(!this._head)throw new Error("Invalid list");e.next=this._head,this._head.previous=e}else this._tail=e;this._head=e,this._state++}addItemLast(e){if(this._head||this._tail){if(!this._tail)throw new Error("Invalid list");e.previous=this._tail,this._tail.next=e}else this._head=e;this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw new Error("Invalid list");e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw new Error("Invalid list");e.previous.next=void 0,this._tail=e.previous}else{const t=e.next,n=e.previous;if(!t||!n)throw new Error("Invalid list");t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw new Error("Invalid list");if(t===r.First||t===r.Last)if(t===r.First){if(e===this._head)return;const t=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(t===r.Last){if(e===this._tail)return;const t=e.next,n=e.previous;e===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}toJSON(){const e=[];return this.forEach((t,n)=>{e.push([n,t])}),e}fromJSON(e){this.clear();for(const[t,n]of e)this.set(t,n)}}t.LinkedMap=i,t.LRUCache=class extends i{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,t=r.AsNew){return super.get(e,t)}peek(e){return super.get(e,r.None)}set(e,t){return super.set(e,t,r.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}}},3821:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MonikerRequest=t.MonikerKind=t.UniquenessLevel=void 0;const r=n(2834);var i,o,s;!function(e){e.document="document",e.project="project",e.group="group",e.scheme="scheme",e.global="global"}(i||(t.UniquenessLevel=i={})),function(e){e.$import="import",e.$export="export",e.local="local"}(o||(t.MonikerKind=o={})),function(e){e.method="textDocument/moniker",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(s||(t.MonikerRequest=s={}))},3911:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveModulePath=t.FileSystem=t.resolveGlobalYarnPath=t.resolveGlobalNodePath=t.resolve=t.uriToFilePath=void 0;const r=n(7016),i=n(6928),o=n(9896),s=n(5317);function a(){return"win32"===process.platform}function c(e,t,n,r){const a="NODE_PATH",c=["var p = process;","p.on('message',function(m){","if(m.c==='e'){","p.exit(0);","}","else if(m.c==='rs'){","try{","var r=require.resolve(m.a);","p.send({c:'r',s:true,r:r});","}","catch(err){","p.send({c:'r',s:false});","}","}","});"].join("");return new Promise((l,u)=>{let p=process.env,d=Object.create(null);Object.keys(p).forEach(e=>d[e]=p[e]),t&&o.existsSync(t)&&(d[a]?d[a]=t+i.delimiter+d[a]:d[a]=t,r&&r(`NODE_PATH value is: ${d[a]}`)),d.ELECTRON_RUN_AS_NODE="1";try{let t=(0,s.fork)("",[],{cwd:n,env:d,execArgv:["-e",c]});if(void 0===t.pid)return void u(new Error(`Starting process to resolve node module ${e} failed`));t.on("error",e=>{u(e)}),t.on("message",n=>{"r"===n.c&&(t.send({c:"e"}),n.s?l(n.r):u(new Error(`Failed to resolve module: ${e}`)))});let r={c:"rs",a:e};t.send(r)}catch(e){u(e)}})}function l(e){let t="npm";const n=Object.create(null);Object.keys(process.env).forEach(e=>n[e]=process.env[e]),n.NO_UPDATE_NOTIFIER="true";const r={encoding:"utf8",env:n};a()&&(t="npm.cmd",r.shell=!0);let o=()=>{};try{process.on("SIGPIPE",o);let n=(0,s.spawnSync)(t,["config","get","prefix"],r).stdout;if(!n)return void(e&&e("'npm config get prefix' didn't return a value."));let c=n.trim();return e&&e(`'npm config get prefix' value is: ${c}`),c.length>0?a()?i.join(c,"node_modules"):i.join(c,"lib","node_modules"):void 0}catch(e){return}finally{process.removeListener("SIGPIPE",o)}}var u;t.uriToFilePath=function(e){let t=r.parse(e);if("file:"!==t.protocol||!t.path)return;let n=t.path.split("/");for(var o=0,s=n.length;o<s;o++)n[o]=decodeURIComponent(n[o]);if("win32"===process.platform&&n.length>1){let e=n[0],t=n[1];0===e.length&&t.length>1&&":"===t[1]&&n.shift()}return i.normalize(n.join("/"))},t.resolve=c,t.resolveGlobalNodePath=l,t.resolveGlobalYarnPath=function(e){let t="yarn",n={encoding:"utf8"};a()&&(t="yarn.cmd",n.shell=!0);let r=()=>{};try{process.on("SIGPIPE",r);let o=(0,s.spawnSync)(t,["global","dir","--json"],n),a=o.stdout;if(!a)return void(e&&(e("'yarn global dir' didn't return a value."),o.stderr&&e(o.stderr)));let c=a.trim().split(/\r?\n/);for(let e of c)try{let t=JSON.parse(e);if("log"===t.type)return i.join(t.data,"node_modules")}catch(e){}return}catch(e){return}finally{process.removeListener("SIGPIPE",r)}},function(e){let t;function n(){return void 0!==t||(t=!("win32"===process.platform||o.existsSync(__filename.toUpperCase())&&o.existsSync(__filename.toLowerCase()))),t}e.isCaseSensitive=n,e.isParent=function(e,t){return n()?0===i.normalize(t).indexOf(i.normalize(e)):0===i.normalize(t).toLowerCase().indexOf(i.normalize(e).toLowerCase())}}(u||(t.FileSystem=u={})),t.resolveModulePath=function(e,t,n,r){return n?(i.isAbsolute(n)||(n=i.join(e,n)),c(t,n,n,r).then(e=>u.isParent(n,e)?e:Promise.reject(new Error(`Failed to load ${t} from node path location.`))).then(void 0,n=>c(t,l(r),e,r))):c(t,l(r),e,r)}},3918:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CallHierarchyFeature=void 0;const r=n(8828);t.CallHierarchyFeature=e=>class extends e{get callHierarchy(){return{onPrepare:e=>this.connection.onRequest(r.CallHierarchyPrepareRequest.type,(t,n)=>e(t,n,this.attachWorkDoneProgress(t),void 0)),onIncomingCalls:e=>{const t=r.CallHierarchyIncomingCallsRequest.type;return this.connection.onRequest(t,(n,r)=>e(n,r,this.attachWorkDoneProgress(n),this.attachPartialResultProgress(t,n)))},onOutgoingCalls:e=>{const t=r.CallHierarchyOutgoingCallsRequest.type;return this.connection.onRequest(t,(n,r)=>e(n,r,this.attachWorkDoneProgress(n),this.attachPartialResultProgress(t,n)))}}}}},4017:(e,t)=>{"use strict";let n;function r(){if(void 0===n)throw new Error("No runtime abstraction layer installed");return n}Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.install=function(e){if(void 0===e)throw new Error("No runtime abstraction layer provided");n=e}}(r||(r={})),t.default=r},4182:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InlayHintRefreshRequest=t.InlayHintResolveRequest=t.InlayHintRequest=void 0;const r=n(2834);var i,o,s;!function(e){e.method="textDocument/inlayHint",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.InlayHintRequest=i={})),function(e){e.method="inlayHint/resolve",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(o||(t.InlayHintResolveRequest=o={})),function(e){e.method="workspace/inlayHint/refresh",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType0(e.method)}(s||(t.InlayHintRefreshRequest=s={}))},4198:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShowDocumentRequest=void 0;const r=n(2834);var i;!function(e){e.method="window/showDocument",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType(e.method)}(i||(t.ShowDocumentRequest=i={}))},4635:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InlayHintFeature=void 0;const r=n(8828);t.InlayHintFeature=e=>class extends e{get inlayHint(){return{refresh:()=>this.connection.sendRequest(r.InlayHintRefreshRequest.type),on:e=>this.connection.onRequest(r.InlayHintRequest.type,(t,n)=>e(t,n,this.attachWorkDoneProgress(t))),resolve:e=>this.connection.onRequest(r.InlayHintResolveRequest.type,(t,n)=>e(t,n))}}}},5026:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TypeHierarchyFeature=void 0;const r=n(8828);t.TypeHierarchyFeature=e=>class extends e{get typeHierarchy(){return{onPrepare:e=>this.connection.onRequest(r.TypeHierarchyPrepareRequest.type,(t,n)=>e(t,n,this.attachWorkDoneProgress(t),void 0)),onSupertypes:e=>{const t=r.TypeHierarchySupertypesRequest.type;return this.connection.onRequest(t,(n,r)=>e(n,r,this.attachWorkDoneProgress(n),this.attachPartialResultProgress(t,n)))},onSubtypes:e=>{const t=r.TypeHierarchySubtypesRequest.type;return this.connection.onRequest(t,(n,r)=>e(n,r,this.attachWorkDoneProgress(n),this.attachPartialResultProgress(t,n)))}}}}},5104:(e,t,n)=>{"use strict";e.exports=n(5174)},5174:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.createMessageConnection=t.createServerSocketTransport=t.createClientSocketTransport=t.createServerPipeTransport=t.createClientPipeTransport=t.generateRandomPipeName=t.StreamMessageWriter=t.StreamMessageReader=t.SocketMessageWriter=t.SocketMessageReader=t.PortMessageWriter=t.PortMessageReader=t.IPCMessageWriter=t.IPCMessageReader=void 0;const o=n(192);o.default.install();const s=n(6928),a=n(857),c=n(6982),l=n(9278),u=n(5866);i(n(5866),t);class p extends u.AbstractMessageReader{constructor(e){super(),this.process=e;let t=this.process;t.on("error",e=>this.fireError(e)),t.on("close",()=>this.fireClose())}listen(e){return this.process.on("message",e),u.Disposable.create(()=>this.process.off("message",e))}}t.IPCMessageReader=p;class d extends u.AbstractMessageWriter{constructor(e){super(),this.process=e,this.errorCount=0;const t=this.process;t.on("error",e=>this.fireError(e)),t.on("close",()=>this.fireClose)}write(e){try{return"function"==typeof this.process.send&&this.process.send(e,void 0,void 0,t=>{t?(this.errorCount++,this.handleError(t,e)):this.errorCount=0}),Promise.resolve()}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}}t.IPCMessageWriter=d;class m extends u.AbstractMessageReader{constructor(e){super(),this.onData=new u.Emitter,e.on("close",()=>this.fireClose),e.on("error",e=>this.fireError(e)),e.on("message",e=>{this.onData.fire(e)})}listen(e){return this.onData.event(e)}}t.PortMessageReader=m;class h extends u.AbstractMessageWriter{constructor(e){super(),this.port=e,this.errorCount=0,e.on("close",()=>this.fireClose()),e.on("error",e=>this.fireError(e))}write(e){try{return this.port.postMessage(e),Promise.resolve()}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}}t.PortMessageWriter=h;class f extends u.ReadableStreamMessageReader{constructor(e,t="utf-8"){super((0,o.default)().stream.asReadableStream(e),t)}}t.SocketMessageReader=f;class g extends u.WriteableStreamMessageWriter{constructor(e,t){super((0,o.default)().stream.asWritableStream(e),t),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}}t.SocketMessageWriter=g;class y extends u.ReadableStreamMessageReader{constructor(e,t){super((0,o.default)().stream.asReadableStream(e),t)}}t.StreamMessageReader=y;class T extends u.WriteableStreamMessageWriter{constructor(e,t){super((0,o.default)().stream.asWritableStream(e),t)}}t.StreamMessageWriter=T;const _=process.env.XDG_RUNTIME_DIR,N=new Map([["linux",107],["darwin",103]]);t.generateRandomPipeName=function(){const e=(0,c.randomBytes)(21).toString("hex");if("win32"===process.platform)return`\\\\.\\pipe\\vscode-jsonrpc-${e}-sock`;let t;t=_?s.join(_,`vscode-ipc-${e}.sock`):s.join(a.tmpdir(),`vscode-${e}.sock`);const n=N.get(process.platform);return void 0!==n&&t.length>n&&(0,o.default)().console.warn(`WARNING: IPC handle "${t}" is longer than ${n} characters.`),t},t.createClientPipeTransport=function(e,t="utf-8"){let n;const r=new Promise((e,t)=>{n=e});return new Promise((i,o)=>{let s=(0,l.createServer)(e=>{s.close(),n([new f(e,t),new g(e,t)])});s.on("error",o),s.listen(e,()=>{s.removeListener("error",o),i({onConnected:()=>r})})})},t.createServerPipeTransport=function(e,t="utf-8"){const n=(0,l.createConnection)(e);return[new f(n,t),new g(n,t)]},t.createClientSocketTransport=function(e,t="utf-8"){let n;const r=new Promise((e,t)=>{n=e});return new Promise((i,o)=>{const s=(0,l.createServer)(e=>{s.close(),n([new f(e,t),new g(e,t)])});s.on("error",o),s.listen(e,"127.0.0.1",()=>{s.removeListener("error",o),i({onConnected:()=>r})})})},t.createServerSocketTransport=function(e,t="utf-8"){const n=(0,l.createConnection)(e,"127.0.0.1");return[new f(n,t),new g(n,t)]},t.createMessageConnection=function(e,t,n,r){n||(n=u.NullLogger);const i=function(e){const t=e;return void 0!==t.read&&void 0!==t.addListener}(e)?new y(e):e,o=function(e){const t=e;return void 0!==t.write&&void 0!==t.addListener}(t)?new T(t):t;return u.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,u.createMessageConnection)(i,o,n,r)}},5317:e=>{"use strict";e.exports=require("child_process")},5595:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractMessageBuffer=void 0,t.AbstractMessageBuffer=class{constructor(e="utf-8"){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){const t="string"==typeof e?this.fromString(e,this._encoding):e;this._chunks.push(t),this._totalLength+=t.byteLength}tryReadHeaders(e=!1){if(0===this._chunks.length)return;let t=0,n=0,r=0,i=0;e:for(;n<this._chunks.length;){const e=this._chunks[n];for(r=0;r<e.length;){switch(e[r]){case 13:switch(t){case 0:t=1;break;case 2:t=3;break;default:t=0}break;case 10:switch(t){case 1:t=2;break;case 3:t=4,r++;break e;default:t=0}break;default:t=0}r++}i+=e.byteLength,n++}if(4!==t)return;const o=this._read(i+r),s=new Map,a=this.toString(o,"ascii").split("\r\n");if(a.length<2)return s;for(let t=0;t<a.length-2;t++){const n=a[t],r=n.indexOf(":");if(-1===r)throw new Error(`Message header must separate key and value using ':'\n${n}`);const i=n.substr(0,r),o=n.substr(r+1).trim();s.set(e?i.toLowerCase():i,o)}return s}tryReadBody(e){if(!(this._totalLength<e))return this._read(e)}get numberOfBytes(){return this._totalLength}_read(e){if(0===e)return this.emptyBuffer();if(e>this._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===e){const t=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(t)}if(this._chunks[0].byteLength>e){const t=this._chunks[0],n=this.asNative(t,e);return this._chunks[0]=t.slice(e),this._totalLength-=e,n}const t=this.allocNative(e);let n=0;for(;e>0;){const r=this._chunks[0];if(r.byteLength>e){const i=r.slice(0,e);t.set(i,n),n+=e,this._chunks[0]=r.slice(e),this._totalLength-=e,e-=e}else t.set(r,n),n+=r.byteLength,this._chunks.shift(),this._totalLength-=r.byteLength,e-=r.byteLength}return t}}},5663:(e,t,n)=>{"use strict";e.exports=n(1327)},5714:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LinkedEditingRangeRequest=void 0;const r=n(2834);var i;!function(e){e.method="textDocument/linkedEditingRange",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.LinkedEditingRangeRequest=i={}))},5866:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressType=t.ProgressToken=t.createMessageConnection=t.NullLogger=t.ConnectionOptions=t.ConnectionStrategy=t.AbstractMessageBuffer=t.WriteableStreamMessageWriter=t.AbstractMessageWriter=t.MessageWriter=t.ReadableStreamMessageReader=t.AbstractMessageReader=t.MessageReader=t.SharedArrayReceiverStrategy=t.SharedArraySenderStrategy=t.CancellationToken=t.CancellationTokenSource=t.Emitter=t.Event=t.Disposable=t.LRUCache=t.Touch=t.LinkedMap=t.ParameterStructures=t.NotificationType9=t.NotificationType8=t.NotificationType7=t.NotificationType6=t.NotificationType5=t.NotificationType4=t.NotificationType3=t.NotificationType2=t.NotificationType1=t.NotificationType0=t.NotificationType=t.ErrorCodes=t.ResponseError=t.RequestType9=t.RequestType8=t.RequestType7=t.RequestType6=t.RequestType5=t.RequestType4=t.RequestType3=t.RequestType2=t.RequestType1=t.RequestType0=t.RequestType=t.Message=t.RAL=void 0,t.MessageStrategy=t.CancellationStrategy=t.CancellationSenderStrategy=t.CancellationReceiverStrategy=t.ConnectionError=t.ConnectionErrors=t.LogTraceNotification=t.SetTraceNotification=t.TraceFormat=t.TraceValues=t.Trace=void 0;const r=n(6344);Object.defineProperty(t,"Message",{enumerable:!0,get:function(){return r.Message}}),Object.defineProperty(t,"RequestType",{enumerable:!0,get:function(){return r.RequestType}}),Object.defineProperty(t,"RequestType0",{enumerable:!0,get:function(){return r.RequestType0}}),Object.defineProperty(t,"RequestType1",{enumerable:!0,get:function(){return r.RequestType1}}),Object.defineProperty(t,"RequestType2",{enumerable:!0,get:function(){return r.RequestType2}}),Object.defineProperty(t,"RequestType3",{enumerable:!0,get:function(){return r.RequestType3}}),Object.defineProperty(t,"RequestType4",{enumerable:!0,get:function(){return r.RequestType4}}),Object.defineProperty(t,"RequestType5",{enumerable:!0,get:function(){return r.RequestType5}}),Object.defineProperty(t,"RequestType6",{enumerable:!0,get:function(){return r.RequestType6}}),Object.defineProperty(t,"RequestType7",{enumerable:!0,get:function(){return r.RequestType7}}),Object.defineProperty(t,"RequestType8",{enumerable:!0,get:function(){return r.RequestType8}}),Object.defineProperty(t,"RequestType9",{enumerable:!0,get:function(){return r.RequestType9}}),Object.defineProperty(t,"ResponseError",{enumerable:!0,get:function(){return r.ResponseError}}),Object.defineProperty(t,"ErrorCodes",{enumerable:!0,get:function(){return r.ErrorCodes}}),Object.defineProperty(t,"NotificationType",{enumerable:!0,get:function(){return r.NotificationType}}),Object.defineProperty(t,"NotificationType0",{enumerable:!0,get:function(){return r.NotificationType0}}),Object.defineProperty(t,"NotificationType1",{enumerable:!0,get:function(){return r.NotificationType1}}),Object.defineProperty(t,"NotificationType2",{enumerable:!0,get:function(){return r.NotificationType2}}),Object.defineProperty(t,"NotificationType3",{enumerable:!0,get:function(){return r.NotificationType3}}),Object.defineProperty(t,"NotificationType4",{enumerable:!0,get:function(){return r.NotificationType4}}),Object.defineProperty(t,"NotificationType5",{enumerable:!0,get:function(){return r.NotificationType5}}),Object.defineProperty(t,"NotificationType6",{enumerable:!0,get:function(){return r.NotificationType6}}),Object.defineProperty(t,"NotificationType7",{enumerable:!0,get:function(){return r.NotificationType7}}),Object.defineProperty(t,"NotificationType8",{enumerable:!0,get:function(){return r.NotificationType8}}),Object.defineProperty(t,"NotificationType9",{enumerable:!0,get:function(){return r.NotificationType9}}),Object.defineProperty(t,"ParameterStructures",{enumerable:!0,get:function(){return r.ParameterStructures}});const i=n(3623);Object.defineProperty(t,"LinkedMap",{enumerable:!0,get:function(){return i.LinkedMap}}),Object.defineProperty(t,"LRUCache",{enumerable:!0,get:function(){return i.LRUCache}}),Object.defineProperty(t,"Touch",{enumerable:!0,get:function(){return i.Touch}});const o=n(3498);Object.defineProperty(t,"Disposable",{enumerable:!0,get:function(){return o.Disposable}});const s=n(3537);Object.defineProperty(t,"Event",{enumerable:!0,get:function(){return s.Event}}),Object.defineProperty(t,"Emitter",{enumerable:!0,get:function(){return s.Emitter}});const a=n(7279);Object.defineProperty(t,"CancellationTokenSource",{enumerable:!0,get:function(){return a.CancellationTokenSource}}),Object.defineProperty(t,"CancellationToken",{enumerable:!0,get:function(){return a.CancellationToken}});const c=n(7007);Object.defineProperty(t,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return c.SharedArraySenderStrategy}}),Object.defineProperty(t,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return c.SharedArrayReceiverStrategy}});const l=n(6558);Object.defineProperty(t,"MessageReader",{enumerable:!0,get:function(){return l.MessageReader}}),Object.defineProperty(t,"AbstractMessageReader",{enumerable:!0,get:function(){return l.AbstractMessageReader}}),Object.defineProperty(t,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return l.ReadableStreamMessageReader}});const u=n(958);Object.defineProperty(t,"MessageWriter",{enumerable:!0,get:function(){return u.MessageWriter}}),Object.defineProperty(t,"AbstractMessageWriter",{enumerable:!0,get:function(){return u.AbstractMessageWriter}}),Object.defineProperty(t,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return u.WriteableStreamMessageWriter}});const p=n(5595);Object.defineProperty(t,"AbstractMessageBuffer",{enumerable:!0,get:function(){return p.AbstractMessageBuffer}});const d=n(6072);Object.defineProperty(t,"ConnectionStrategy",{enumerable:!0,get:function(){return d.ConnectionStrategy}}),Object.defineProperty(t,"ConnectionOptions",{enumerable:!0,get:function(){return d.ConnectionOptions}}),Object.defineProperty(t,"NullLogger",{enumerable:!0,get:function(){return d.NullLogger}}),Object.defineProperty(t,"createMessageConnection",{enumerable:!0,get:function(){return d.createMessageConnection}}),Object.defineProperty(t,"ProgressToken",{enumerable:!0,get:function(){return d.ProgressToken}}),Object.defineProperty(t,"ProgressType",{enumerable:!0,get:function(){return d.ProgressType}}),Object.defineProperty(t,"Trace",{enumerable:!0,get:function(){return d.Trace}}),Object.defineProperty(t,"TraceValues",{enumerable:!0,get:function(){return d.TraceValues}}),Object.defineProperty(t,"TraceFormat",{enumerable:!0,get:function(){return d.TraceFormat}}),Object.defineProperty(t,"SetTraceNotification",{enumerable:!0,get:function(){return d.SetTraceNotification}}),Object.defineProperty(t,"LogTraceNotification",{enumerable:!0,get:function(){return d.LogTraceNotification}}),Object.defineProperty(t,"ConnectionErrors",{enumerable:!0,get:function(){return d.ConnectionErrors}}),Object.defineProperty(t,"ConnectionError",{enumerable:!0,get:function(){return d.ConnectionError}}),Object.defineProperty(t,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return d.CancellationReceiverStrategy}}),Object.defineProperty(t,"CancellationSenderStrategy",{enumerable:!0,get:function(){return d.CancellationSenderStrategy}}),Object.defineProperty(t,"CancellationStrategy",{enumerable:!0,get:function(){return d.CancellationStrategy}}),Object.defineProperty(t,"MessageStrategy",{enumerable:!0,get:function(){return d.MessageStrategy}});const m=n(4017);t.RAL=m.default},5887:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DidCloseNotebookDocumentNotification=t.DidSaveNotebookDocumentNotification=t.DidChangeNotebookDocumentNotification=t.NotebookCellArrayChange=t.DidOpenNotebookDocumentNotification=t.NotebookDocumentSyncRegistrationType=t.NotebookDocument=t.NotebookCell=t.ExecutionSummary=t.NotebookCellKind=void 0;const r=n(6616),i=n(8176),o=n(2834);var s,a,c,l,u,p,d,m,h,f;!function(e){e.Markup=1,e.Code=2,e.is=function(e){return 1===e||2===e}}(s||(t.NotebookCellKind=s={})),function(e){e.create=function(e,t){const n={executionOrder:e};return!0!==t&&!1!==t||(n.success=t),n},e.is=function(e){const t=e;return i.objectLiteral(t)&&r.uinteger.is(t.executionOrder)&&(void 0===t.success||i.boolean(t.success))},e.equals=function(e,t){return e===t||null!=e&&null!=t&&e.executionOrder===t.executionOrder&&e.success===t.success}}(a||(t.ExecutionSummary=a={})),function(e){function t(e,n){if(e===n)return!0;if(null==e||null==n)return!1;if(typeof e!=typeof n)return!1;if("object"!=typeof e)return!1;const r=Array.isArray(e),o=Array.isArray(n);if(r!==o)return!1;if(r&&o){if(e.length!==n.length)return!1;for(let r=0;r<e.length;r++)if(!t(e[r],n[r]))return!1}if(i.objectLiteral(e)&&i.objectLiteral(n)){const r=Object.keys(e),i=Object.keys(n);if(r.length!==i.length)return!1;if(r.sort(),i.sort(),!t(r,i))return!1;for(let i=0;i<r.length;i++){const o=r[i];if(!t(e[o],n[o]))return!1}}return!0}e.create=function(e,t){return{kind:e,document:t}},e.is=function(e){const t=e;return i.objectLiteral(t)&&s.is(t.kind)&&r.DocumentUri.is(t.document)&&(void 0===t.metadata||i.objectLiteral(t.metadata))},e.diff=function(e,n){const r=new Set;return e.document!==n.document&&r.add("document"),e.kind!==n.kind&&r.add("kind"),e.executionSummary!==n.executionSummary&&r.add("executionSummary"),void 0===e.metadata&&void 0===n.metadata||t(e.metadata,n.metadata)||r.add("metadata"),void 0===e.executionSummary&&void 0===n.executionSummary||a.equals(e.executionSummary,n.executionSummary)||r.add("executionSummary"),r}}(c||(t.NotebookCell=c={})),function(e){e.create=function(e,t,n,r){return{uri:e,notebookType:t,version:n,cells:r}},e.is=function(e){const t=e;return i.objectLiteral(t)&&i.string(t.uri)&&r.integer.is(t.version)&&i.typedArray(t.cells,c.is)}}(l||(t.NotebookDocument=l={})),function(e){e.method="notebookDocument/sync",e.messageDirection=o.MessageDirection.clientToServer,e.type=new o.RegistrationType(e.method)}(u||(t.NotebookDocumentSyncRegistrationType=u={})),function(e){e.method="notebookDocument/didOpen",e.messageDirection=o.MessageDirection.clientToServer,e.type=new o.ProtocolNotificationType(e.method),e.registrationMethod=u.method}(p||(t.DidOpenNotebookDocumentNotification=p={})),function(e){e.is=function(e){const t=e;return i.objectLiteral(t)&&r.uinteger.is(t.start)&&r.uinteger.is(t.deleteCount)&&(void 0===t.cells||i.typedArray(t.cells,c.is))},e.create=function(e,t,n){const r={start:e,deleteCount:t};return void 0!==n&&(r.cells=n),r}}(d||(t.NotebookCellArrayChange=d={})),function(e){e.method="notebookDocument/didChange",e.messageDirection=o.MessageDirection.clientToServer,e.type=new o.ProtocolNotificationType(e.method),e.registrationMethod=u.method}(m||(t.DidChangeNotebookDocumentNotification=m={})),function(e){e.method="notebookDocument/didSave",e.messageDirection=o.MessageDirection.clientToServer,e.type=new o.ProtocolNotificationType(e.method),e.registrationMethod=u.method}(h||(t.DidSaveNotebookDocumentNotification=h={})),function(e){e.method="notebookDocument/didClose",e.messageDirection=o.MessageDirection.clientToServer,e.type=new o.ProtocolNotificationType(e.method),e.registrationMethod=u.method}(f||(t.DidCloseNotebookDocumentNotification=f={}))},6007:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FoldingRangeFeature=void 0;const r=n(8828);t.FoldingRangeFeature=e=>class extends e{get foldingRange(){return{refresh:()=>this.connection.sendRequest(r.FoldingRangeRefreshRequest.type),on:e=>{const t=r.FoldingRangeRequest.type;return this.connection.onRequest(t,(n,r)=>e(n,r,this.attachWorkDoneProgress(n),this.attachPartialResultProgress(t,n)))}}}}},6072:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createMessageConnection=t.ConnectionOptions=t.MessageStrategy=t.CancellationStrategy=t.CancellationSenderStrategy=t.CancellationReceiverStrategy=t.RequestCancellationReceiverStrategy=t.IdCancellationReceiverStrategy=t.ConnectionStrategy=t.ConnectionError=t.ConnectionErrors=t.LogTraceNotification=t.SetTraceNotification=t.TraceFormat=t.TraceValues=t.Trace=t.NullLogger=t.ProgressType=t.ProgressToken=void 0;const r=n(4017),i=n(6204),o=n(6344),s=n(3623),a=n(3537),c=n(7279);var l,u,p,d,m,h,f,g,y,T,_,N,R,E,b,v,S,C,A;!function(e){e.type=new o.NotificationType("$/cancelRequest")}(l||(l={})),function(e){e.is=function(e){return"string"==typeof e||"number"==typeof e}}(u||(t.ProgressToken=u={})),function(e){e.type=new o.NotificationType("$/progress")}(p||(p={})),t.ProgressType=class{constructor(){}},function(e){e.is=function(e){return i.func(e)}}(d||(d={})),t.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}}),function(e){e[e.Off=0]="Off",e[e.Messages=1]="Messages",e[e.Compact=2]="Compact",e[e.Verbose=3]="Verbose"}(m||(t.Trace=m={})),function(e){e.Off="off",e.Messages="messages",e.Compact="compact",e.Verbose="verbose"}(h||(t.TraceValues=h={})),function(e){e.fromString=function(t){if(!i.string(t))return e.Off;switch(t=t.toLowerCase()){case"off":default:return e.Off;case"messages":return e.Messages;case"compact":return e.Compact;case"verbose":return e.Verbose}},e.toString=function(t){switch(t){case e.Off:return"off";case e.Messages:return"messages";case e.Compact:return"compact";case e.Verbose:return"verbose";default:return"off"}}}(m||(t.Trace=m={})),function(e){e.Text="text",e.JSON="json"}(f||(t.TraceFormat=f={})),function(e){e.fromString=function(t){return i.string(t)&&"json"===(t=t.toLowerCase())?e.JSON:e.Text}}(f||(t.TraceFormat=f={})),function(e){e.type=new o.NotificationType("$/setTrace")}(g||(t.SetTraceNotification=g={})),function(e){e.type=new o.NotificationType("$/logTrace")}(y||(t.LogTraceNotification=y={})),function(e){e[e.Closed=1]="Closed",e[e.Disposed=2]="Disposed",e[e.AlreadyListening=3]="AlreadyListening"}(T||(t.ConnectionErrors=T={}));class O extends Error{constructor(e,t){super(t),this.code=e,Object.setPrototypeOf(this,O.prototype)}}t.ConnectionError=O,function(e){e.is=function(e){const t=e;return t&&i.func(t.cancelUndispatched)}}(_||(t.ConnectionStrategy=_={})),function(e){e.is=function(e){const t=e;return t&&(void 0===t.kind||"id"===t.kind)&&i.func(t.createCancellationTokenSource)&&(void 0===t.dispose||i.func(t.dispose))}}(N||(t.IdCancellationReceiverStrategy=N={})),function(e){e.is=function(e){const t=e;return t&&"request"===t.kind&&i.func(t.createCancellationTokenSource)&&(void 0===t.dispose||i.func(t.dispose))}}(R||(t.RequestCancellationReceiverStrategy=R={})),function(e){e.Message=Object.freeze({createCancellationTokenSource:e=>new c.CancellationTokenSource}),e.is=function(e){return N.is(e)||R.is(e)}}(E||(t.CancellationReceiverStrategy=E={})),function(e){e.Message=Object.freeze({sendCancellation:(e,t)=>e.sendNotification(l.type,{id:t}),cleanup(e){}}),e.is=function(e){const t=e;return t&&i.func(t.sendCancellation)&&i.func(t.cleanup)}}(b||(t.CancellationSenderStrategy=b={})),function(e){e.Message=Object.freeze({receiver:E.Message,sender:b.Message}),e.is=function(e){const t=e;return t&&E.is(t.receiver)&&b.is(t.sender)}}(v||(t.CancellationStrategy=v={})),function(e){e.is=function(e){const t=e;return t&&i.func(t.handleMessage)}}(S||(t.MessageStrategy=S={})),function(e){e.is=function(e){const t=e;return t&&(v.is(t.cancellationStrategy)||_.is(t.connectionStrategy)||S.is(t.messageStrategy))}}(C||(t.ConnectionOptions=C={})),function(e){e[e.New=1]="New",e[e.Listening=2]="Listening",e[e.Closed=3]="Closed",e[e.Disposed=4]="Disposed"}(A||(A={})),t.createMessageConnection=function(e,n,h,_){const R=void 0!==h?h:t.NullLogger;let E=0,b=0,C=0;const L="2.0";let I;const D=new Map;let k;const P=new Map,x=new Map;let w,M,F=new s.LinkedMap,U=new Map,K=new Set,G=new Map,B=m.Off,W=f.Text,$=A.New;const j=new a.Emitter,q=new a.Emitter,V=new a.Emitter,H=new a.Emitter,Y=new a.Emitter,X=_&&_.cancellationStrategy?_.cancellationStrategy:v.Message;function z(e){if(null===e)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+e.toString()}function J(e){}function Q(){return $===A.Listening}function Z(){return $===A.Closed}function ee(){return $===A.Disposed}function te(){$!==A.New&&$!==A.Listening||($=A.Closed,q.fire(void 0))}function ne(){w||0===F.size||(w=(0,r.default)().timer.setImmediate(()=>{w=void 0,function(){if(0===F.size)return;const e=F.shift();try{const t=_?.messageStrategy;S.is(t)?t.handleMessage(e,re):re(e)}finally{ne()}}()}))}function re(e){o.Message.isRequest(e)?function(e){if(ee())return;function t(t,r,i){const s={jsonrpc:L,id:e.id};t instanceof o.ResponseError?s.error=t.toJson():s.result=void 0===t?null:t,se(s,r,i),n.write(s).catch(()=>R.error("Sending response failed."))}function r(t,r,i){const o={jsonrpc:L,id:e.id,error:t.toJson()};se(o,r,i),n.write(o).catch(()=>R.error("Sending response failed."))}!function(e){if(B!==m.Off&&M)if(W===f.Text){let t;B!==m.Verbose&&B!==m.Compact||!e.params||(t=`Params: ${oe(e.params)}\n\n`),M.log(`Received request '${e.method} - (${e.id})'.`,t)}else ce("receive-request",e)}(e);const s=D.get(e.method);let a,c;s&&(a=s.type,c=s.handler);const l=Date.now();if(c||I){const s=e.id??String(Date.now()),u=N.is(X.receiver)?X.receiver.createCancellationTokenSource(s):X.receiver.createCancellationTokenSource(e);null!==e.id&&K.has(e.id)&&u.cancel(),null!==e.id&&G.set(s,u);try{let p;if(c)if(void 0===e.params){if(void 0!==a&&0!==a.numberOfParams)return void r(new o.ResponseError(o.ErrorCodes.InvalidParams,`Request ${e.method} defines ${a.numberOfParams} params but received none.`),e.method,l);p=c(u.token)}else if(Array.isArray(e.params)){if(void 0!==a&&a.parameterStructures===o.ParameterStructures.byName)return void r(new o.ResponseError(o.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by name but received parameters by position`),e.method,l);p=c(...e.params,u.token)}else{if(void 0!==a&&a.parameterStructures===o.ParameterStructures.byPosition)return void r(new o.ResponseError(o.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by position but received parameters by name`),e.method,l);p=c(e.params,u.token)}else I&&(p=I(e.method,e.params,u.token));const d=p;p?d.then?d.then(n=>{G.delete(s),t(n,e.method,l)},t=>{G.delete(s),t instanceof o.ResponseError?r(t,e.method,l):t&&i.string(t.message)?r(new o.ResponseError(o.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${t.message}`),e.method,l):r(new o.ResponseError(o.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,l)}):(G.delete(s),t(p,e.method,l)):(G.delete(s),function(t,r,i){void 0===t&&(t=null);const o={jsonrpc:L,id:e.id,result:t};se(o,r,i),n.write(o).catch(()=>R.error("Sending response failed."))}(p,e.method,l))}catch(n){G.delete(s),n instanceof o.ResponseError?t(n,e.method,l):n&&i.string(n.message)?r(new o.ResponseError(o.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${n.message}`),e.method,l):r(new o.ResponseError(o.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,l)}}else r(new o.ResponseError(o.ErrorCodes.MethodNotFound,`Unhandled method ${e.method}`),e.method,l)}(e):o.Message.isNotification(e)?function(e){if(ee())return;let t,n;if(e.method===l.type.method){const t=e.params.id;return K.delete(t),void ae(e)}{const r=P.get(e.method);r&&(n=r.handler,t=r.type)}if(n||k)try{if(ae(e),n)if(void 0===e.params)void 0!==t&&0!==t.numberOfParams&&t.parameterStructures!==o.ParameterStructures.byName&&R.error(`Notification ${e.method} defines ${t.numberOfParams} params but received none.`),n();else if(Array.isArray(e.params)){const r=e.params;e.method===p.type.method&&2===r.length&&u.is(r[0])?n({token:r[0],value:r[1]}):(void 0!==t&&(t.parameterStructures===o.ParameterStructures.byName&&R.error(`Notification ${e.method} defines parameters by name but received parameters by position`),t.numberOfParams!==e.params.length&&R.error(`Notification ${e.method} defines ${t.numberOfParams} params but received ${r.length} arguments`)),n(...r))}else void 0!==t&&t.parameterStructures===o.ParameterStructures.byPosition&&R.error(`Notification ${e.method} defines parameters by position but received parameters by name`),n(e.params);else k&&k(e.method,e.params)}catch(t){t.message?R.error(`Notification handler '${e.method}' failed with message: ${t.message}`):R.error(`Notification handler '${e.method}' failed unexpectedly.`)}else V.fire(e)}(e):o.Message.isResponse(e)?function(e){if(!ee())if(null===e.id)e.error?R.error(`Received response message without id: Error is: \n${JSON.stringify(e.error,void 0,4)}`):R.error("Received response message without id. No further error information provided.");else{const t=e.id,n=U.get(t);if(function(e,t){if(B!==m.Off&&M)if(W===f.Text){let n;if(B!==m.Verbose&&B!==m.Compact||(e.error&&e.error.data?n=`Error data: ${oe(e.error.data)}\n\n`:e.result?n=`Result: ${oe(e.result)}\n\n`:void 0===e.error&&(n="No result returned.\n\n")),t){const r=e.error?` Request failed: ${e.error.message} (${e.error.code}).`:"";M.log(`Received response '${t.method} - (${e.id})' in ${Date.now()-t.timerStart}ms.${r}`,n)}else M.log(`Received response ${e.id} without active response promise.`,n)}else ce("receive-response",e)}(e,n),void 0!==n){U.delete(t);try{if(e.error){const t=e.error;n.reject(new o.ResponseError(t.code,t.message,t.data))}else{if(void 0===e.result)throw new Error("Should never happen.");n.resolve(e.result)}}catch(e){e.message?R.error(`Response handler '${n.method}' failed with message: ${e.message}`):R.error(`Response handler '${n.method}' failed unexpectedly.`)}}}}(e):function(e){if(!e)return void R.error("Received empty message.");R.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(e,null,4)}`);const t=e;if(i.string(t.id)||i.number(t.id)){const e=t.id,n=U.get(e);n&&n.reject(new Error("The received response has neither a result nor an error property."))}}(e)}e.onClose(te),e.onError(function(e){j.fire([e,void 0,void 0])}),n.onClose(te),n.onError(function(e){j.fire(e)});const ie=e=>{try{if(o.Message.isNotification(e)&&e.method===l.type.method){const t=e.params.id,r=z(t),i=F.get(r);if(o.Message.isRequest(i)){const o=_?.connectionStrategy,s=o&&o.cancelUndispatched?o.cancelUndispatched(i,J):void 0;if(s&&(void 0!==s.error||void 0!==s.result))return F.delete(r),G.delete(t),s.id=i.id,se(s,e.method,Date.now()),void n.write(s).catch(()=>R.error("Sending response for canceled message failed."))}const s=G.get(t);if(void 0!==s)return s.cancel(),void ae(e);K.add(t)}!function(e,t){var n;o.Message.isRequest(t)?e.set(z(t.id),t):o.Message.isResponse(t)?e.set(null===(n=t.id)?"res-unknown-"+(++C).toString():"res-"+n.toString(),t):e.set("not-"+(++b).toString(),t)}(F,e)}finally{ne()}};function oe(e){if(null!=e)switch(B){case m.Verbose:return JSON.stringify(e,null,4);case m.Compact:return JSON.stringify(e);default:return}}function se(e,t,n){if(B!==m.Off&&M)if(W===f.Text){let r;B!==m.Verbose&&B!==m.Compact||(e.error&&e.error.data?r=`Error data: ${oe(e.error.data)}\n\n`:e.result?r=`Result: ${oe(e.result)}\n\n`:void 0===e.error&&(r="No result returned.\n\n")),M.log(`Sending response '${t} - (${e.id})'. Processing request took ${Date.now()-n}ms`,r)}else ce("send-response",e)}function ae(e){if(B!==m.Off&&M&&e.method!==y.type.method)if(W===f.Text){let t;B!==m.Verbose&&B!==m.Compact||(t=e.params?`Params: ${oe(e.params)}\n\n`:"No parameters provided.\n\n"),M.log(`Received notification '${e.method}'.`,t)}else ce("receive-notification",e)}function ce(e,t){if(!M||B===m.Off)return;const n={isLSPMessage:!0,type:e,message:t,timestamp:Date.now()};M.log(n)}function le(){if(Z())throw new O(T.Closed,"Connection is closed.");if(ee())throw new O(T.Disposed,"Connection is disposed.")}function ue(e){return void 0===e?null:e}function pe(e){return null===e?void 0:e}function de(e){return null!=e&&!Array.isArray(e)&&"object"==typeof e}function me(e,t){switch(e){case o.ParameterStructures.auto:return de(t)?pe(t):[ue(t)];case o.ParameterStructures.byName:if(!de(t))throw new Error("Received parameters by name but param is not an object literal.");return pe(t);case o.ParameterStructures.byPosition:return[ue(t)];default:throw new Error(`Unknown parameter structure ${e.toString()}`)}}function he(e,t){let n;const r=e.numberOfParams;switch(r){case 0:n=void 0;break;case 1:n=me(e.parameterStructures,t[0]);break;default:n=[];for(let e=0;e<t.length&&e<r;e++)n.push(ue(t[e]));if(t.length<r)for(let e=t.length;e<r;e++)n.push(null)}return n}const fe={sendNotification:(e,...t)=>{let r,s;if(le(),i.string(e)){r=e;const n=t[0];let i=0,a=o.ParameterStructures.auto;o.ParameterStructures.is(n)&&(i=1,a=n);let c=t.length;const l=c-i;switch(l){case 0:s=void 0;break;case 1:s=me(a,t[i]);break;default:if(a===o.ParameterStructures.byName)throw new Error(`Received ${l} parameters for 'by Name' notification parameter structure.`);s=t.slice(i,c).map(e=>ue(e))}}else{const n=t;r=e.method,s=he(e,n)}const a={jsonrpc:L,method:r,params:s};return function(e){if(B!==m.Off&&M)if(W===f.Text){let t;B!==m.Verbose&&B!==m.Compact||(t=e.params?`Params: ${oe(e.params)}\n\n`:"No parameters provided.\n\n"),M.log(`Sending notification '${e.method}'.`,t)}else ce("send-notification",e)}(a),n.write(a).catch(e=>{throw R.error("Sending notification failed."),e})},onNotification:(e,t)=>{let n;return le(),i.func(e)?k=e:t&&(i.string(e)?(n=e,P.set(e,{type:void 0,handler:t})):(n=e.method,P.set(e.method,{type:e,handler:t}))),{dispose:()=>{void 0!==n?P.delete(n):k=void 0}}},onProgress:(e,t,n)=>{if(x.has(t))throw new Error(`Progress handler for token ${t} already registered`);return x.set(t,n),{dispose:()=>{x.delete(t)}}},sendProgress:(e,t,n)=>fe.sendNotification(p.type,{token:t,value:n}),onUnhandledProgress:H.event,sendRequest:(e,...t)=>{let r,s,a;if(le(),function(){if(!Q())throw new Error("Call listen() first.")}(),i.string(e)){r=e;const n=t[0],i=t[t.length-1];let l=0,u=o.ParameterStructures.auto;o.ParameterStructures.is(n)&&(l=1,u=n);let p=t.length;c.CancellationToken.is(i)&&(p-=1,a=i);const d=p-l;switch(d){case 0:s=void 0;break;case 1:s=me(u,t[l]);break;default:if(u===o.ParameterStructures.byName)throw new Error(`Received ${d} parameters for 'by Name' request parameter structure.`);s=t.slice(l,p).map(e=>ue(e))}}else{const n=t;r=e.method,s=he(e,n);const i=e.numberOfParams;a=c.CancellationToken.is(n[i])?n[i]:void 0}const l=E++;let u;a&&(u=a.onCancellationRequested(()=>{const e=X.sender.sendCancellation(fe,l);return void 0===e?(R.log(`Received no promise from cancellation strategy when cancelling id ${l}`),Promise.resolve()):e.catch(()=>{R.log(`Sending cancellation messages for id ${l} failed`)})}));const p={jsonrpc:L,id:l,method:r,params:s};return function(e){if(B!==m.Off&&M)if(W===f.Text){let t;B!==m.Verbose&&B!==m.Compact||!e.params||(t=`Params: ${oe(e.params)}\n\n`),M.log(`Sending request '${e.method} - (${e.id})'.`,t)}else ce("send-request",e)}(p),"function"==typeof X.sender.enableCancellation&&X.sender.enableCancellation(p),new Promise(async(e,t)=>{const i={method:r,timerStart:Date.now(),resolve:t=>{e(t),X.sender.cleanup(l),u?.dispose()},reject:e=>{t(e),X.sender.cleanup(l),u?.dispose()}};try{await n.write(p),U.set(l,i)}catch(e){throw R.error("Sending request failed."),i.reject(new o.ResponseError(o.ErrorCodes.MessageWriteError,e.message?e.message:"Unknown reason")),e}})},onRequest:(e,t)=>{le();let n=null;return d.is(e)?(n=void 0,I=e):i.string(e)?(n=null,void 0!==t&&(n=e,D.set(e,{handler:t,type:void 0}))):void 0!==t&&(n=e.method,D.set(e.method,{type:e,handler:t})),{dispose:()=>{null!==n&&(void 0!==n?D.delete(n):I=void 0)}}},hasPendingResponse:()=>U.size>0,trace:async(e,t,n)=>{let r=!1,o=f.Text;void 0!==n&&(i.boolean(n)?r=n:(r=n.sendNotification||!1,o=n.traceFormat||f.Text)),B=e,W=o,M=B===m.Off?void 0:t,!r||Z()||ee()||await fe.sendNotification(g.type,{value:m.toString(e)})},onError:j.event,onClose:q.event,onUnhandledNotification:V.event,onDispose:Y.event,end:()=>{n.end()},dispose:()=>{if(ee())return;$=A.Disposed,Y.fire(void 0);const t=new o.ResponseError(o.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(const e of U.values())e.reject(t);U=new Map,G=new Map,K=new Set,F=new s.LinkedMap,i.func(n.dispose)&&n.dispose(),i.func(e.dispose)&&e.dispose()},listen:()=>{le(),function(){if(Q())throw new O(T.AlreadyListening,"Connection is already listening")}(),$=A.Listening,e.listen(ie)},inspect:()=>{(0,r.default)().console.log("inspect")}};return fe.onNotification(y.type,e=>{if(B===m.Off||!M)return;const t=B===m.Verbose||B===m.Compact;M.log(e.message,t?e.verbose:void 0)}),fe.onNotification(p.type,e=>{const t=x.get(e.token);t?t(e.value):H.fire(e)}),fe}},6116:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateUuid=t.parse=t.isUUID=t.v4=t.empty=void 0;class n{constructor(e){this._value=e}asHex(){return this._value}equals(e){return this.asHex()===e.asHex()}}class r extends n{static _oneOf(e){return e[Math.floor(e.length*Math.random())]}static _randomHex(){return r._oneOf(r._chars)}constructor(){super([r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),"-",r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),"-","4",r._randomHex(),r._randomHex(),r._randomHex(),"-",r._oneOf(r._timeHighBits),r._randomHex(),r._randomHex(),r._randomHex(),"-",r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex(),r._randomHex()].join(""))}}function i(){return new r}r._chars=["0","1","2","3","4","5","6","6","7","8","9","a","b","c","d","e","f"],r._timeHighBits=["8","9","a","b"],t.empty=new n("00000000-0000-0000-0000-000000000000"),t.v4=i;const o=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function s(e){return o.test(e)}t.isUUID=s,t.parse=function(e){if(!s(e))throw new Error("invalid uuid");return new n(e)},t.generateUuid=function(){return i().asHex()}},6204:(e,t)=>{"use strict";function n(e){return"string"==typeof e||e instanceof String}function r(e){return Array.isArray(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.stringArray=t.array=t.func=t.error=t.number=t.string=t.boolean=void 0,t.boolean=function(e){return!0===e||!1===e},t.string=n,t.number=function(e){return"number"==typeof e||e instanceof Number},t.error=function(e){return e instanceof Error},t.func=function(e){return"function"==typeof e},t.array=r,t.stringArray=function(e){return r(e)&&e.every(e=>n(e))}},6344:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Message=t.NotificationType9=t.NotificationType8=t.NotificationType7=t.NotificationType6=t.NotificationType5=t.NotificationType4=t.NotificationType3=t.NotificationType2=t.NotificationType1=t.NotificationType0=t.NotificationType=t.RequestType9=t.RequestType8=t.RequestType7=t.RequestType6=t.RequestType5=t.RequestType4=t.RequestType3=t.RequestType2=t.RequestType1=t.RequestType=t.RequestType0=t.AbstractMessageSignature=t.ParameterStructures=t.ResponseError=t.ErrorCodes=void 0;const r=n(6204);var i,o;!function(e){e.ParseError=-32700,e.InvalidRequest=-32600,e.MethodNotFound=-32601,e.InvalidParams=-32602,e.InternalError=-32603,e.jsonrpcReservedErrorRangeStart=-32099,e.serverErrorStart=-32099,e.MessageWriteError=-32099,e.MessageReadError=-32098,e.PendingResponseRejected=-32097,e.ConnectionInactive=-32096,e.ServerNotInitialized=-32002,e.UnknownErrorCode=-32001,e.jsonrpcReservedErrorRangeEnd=-32e3,e.serverErrorEnd=-32e3}(i||(t.ErrorCodes=i={}));class s extends Error{constructor(e,t,n){super(t),this.code=r.number(e)?e:i.UnknownErrorCode,this.data=n,Object.setPrototypeOf(this,s.prototype)}toJson(){const e={code:this.code,message:this.message};return void 0!==this.data&&(e.data=this.data),e}}t.ResponseError=s;class a{constructor(e){this.kind=e}static is(e){return e===a.auto||e===a.byName||e===a.byPosition}toString(){return this.kind}}t.ParameterStructures=a,a.auto=new a("auto"),a.byPosition=new a("byPosition"),a.byName=new a("byName");class c{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return a.auto}}t.AbstractMessageSignature=c,t.RequestType0=class extends c{constructor(e){super(e,0)}},t.RequestType=class extends c{constructor(e,t=a.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},t.RequestType1=class extends c{constructor(e,t=a.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},t.RequestType2=class extends c{constructor(e){super(e,2)}},t.RequestType3=class extends c{constructor(e){super(e,3)}},t.RequestType4=class extends c{constructor(e){super(e,4)}},t.RequestType5=class extends c{constructor(e){super(e,5)}},t.RequestType6=class extends c{constructor(e){super(e,6)}},t.RequestType7=class extends c{constructor(e){super(e,7)}},t.RequestType8=class extends c{constructor(e){super(e,8)}},t.RequestType9=class extends c{constructor(e){super(e,9)}},t.NotificationType=class extends c{constructor(e,t=a.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},t.NotificationType0=class extends c{constructor(e){super(e,0)}},t.NotificationType1=class extends c{constructor(e,t=a.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},t.NotificationType2=class extends c{constructor(e){super(e,2)}},t.NotificationType3=class extends c{constructor(e){super(e,3)}},t.NotificationType4=class extends c{constructor(e){super(e,4)}},t.NotificationType5=class extends c{constructor(e){super(e,5)}},t.NotificationType6=class extends c{constructor(e){super(e,6)}},t.NotificationType7=class extends c{constructor(e){super(e,7)}},t.NotificationType8=class extends c{constructor(e){super(e,8)}},t.NotificationType9=class extends c{constructor(e){super(e,9)}},function(e){e.isRequest=function(e){const t=e;return t&&r.string(t.method)&&(r.string(t.id)||r.number(t.id))},e.isNotification=function(e){const t=e;return t&&r.string(t.method)&&void 0===e.id},e.isResponse=function(e){const t=e;return t&&(void 0!==t.result||!!t.error)&&(r.string(t.id)||r.number(t.id)||null===t.id)}}(o||(t.Message=o={}))},6543:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TypeDefinitionRequest=void 0;const r=n(2834);var i;!function(e){e.method="textDocument/typeDefinition",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.TypeDefinitionRequest=i={}))},6558:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableStreamMessageReader=t.AbstractMessageReader=t.MessageReader=void 0;const r=n(4017),i=n(6204),o=n(3537),s=n(2968);var a,c;!function(e){e.is=function(e){let t=e;return t&&i.func(t.listen)&&i.func(t.dispose)&&i.func(t.onError)&&i.func(t.onClose)&&i.func(t.onPartialMessage)}}(a||(t.MessageReader=a={}));class l{constructor(){this.errorEmitter=new o.Emitter,this.closeEmitter=new o.Emitter,this.partialMessageEmitter=new o.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:new Error(`Reader received error. Reason: ${i.string(e.message)?e.message:"unknown"}`)}}t.AbstractMessageReader=l,function(e){e.fromOptions=function(e){let t,n;const i=new Map;let o;const s=new Map;if(void 0===e||"string"==typeof e)t=e??"utf-8";else{if(t=e.charset??"utf-8",void 0!==e.contentDecoder&&(n=e.contentDecoder,i.set(n.name,n)),void 0!==e.contentDecoders)for(const t of e.contentDecoders)i.set(t.name,t);if(void 0!==e.contentTypeDecoder&&(o=e.contentTypeDecoder,s.set(o.name,o)),void 0!==e.contentTypeDecoders)for(const t of e.contentTypeDecoders)s.set(t.name,t)}return void 0===o&&(o=(0,r.default)().applicationJson.decoder,s.set(o.name,o)),{charset:t,contentDecoder:n,contentDecoders:i,contentTypeDecoder:o,contentTypeDecoders:s}}}(c||(c={})),t.ReadableStreamMessageReader=class extends l{constructor(e,t){super(),this.readable=e,this.options=c.fromOptions(t),this.buffer=(0,r.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new s.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;const t=this.readable.onData(e=>{this.onData(e)});return this.readable.onError(e=>this.fireError(e)),this.readable.onClose(()=>this.fireClose()),t}onData(e){try{for(this.buffer.append(e);;){if(-1===this.nextMessageLength){const e=this.buffer.tryReadHeaders(!0);if(!e)return;const t=e.get("content-length");if(!t)return void this.fireError(new Error(`Header must provide a Content-Length property.\n${JSON.stringify(Object.fromEntries(e))}`));const n=parseInt(t);if(isNaN(n))return void this.fireError(new Error(`Content-Length value must be a number. Got ${t}`));this.nextMessageLength=n}const e=this.buffer.tryReadBody(this.nextMessageLength);if(void 0===e)return void this.setPartialMessageTimer();this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{const t=void 0!==this.options.contentDecoder?await this.options.contentDecoder.decode(e):e,n=await this.options.contentTypeDecoder.decode(t,this.options);this.callback(n)}).catch(e=>{this.fireError(e)})}}catch(e){this.fireError(e)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),this._partialMessageTimeout<=0||(this.partialMessageTimer=(0,r.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}}},6616:(e,t,n)=>{var r,i,o;!function(s){if("object"==typeof e.exports){var a=s(n(204),t);void 0!==a&&(e.exports=a)}else i=[n,t],void 0===(o="function"==typeof(r=s)?r.apply(t,i):r)||(e.exports=o)}(function(e,t){"use strict";var n,r,i,o,s,a,c,l,u,p,d,m,h,f,g,y,T,_,N,R,E,b,v,S,C,A,O,L;Object.defineProperty(t,"__esModule",{value:!0}),t.TextDocument=t.EOL=t.WorkspaceFolder=t.InlineCompletionContext=t.SelectedCompletionInfo=t.InlineCompletionTriggerKind=t.InlineCompletionList=t.InlineCompletionItem=t.StringValue=t.InlayHint=t.InlayHintLabelPart=t.InlayHintKind=t.InlineValueContext=t.InlineValueEvaluatableExpression=t.InlineValueVariableLookup=t.InlineValueText=t.SemanticTokens=t.SemanticTokenModifiers=t.SemanticTokenTypes=t.SelectionRange=t.DocumentLink=t.FormattingOptions=t.CodeLens=t.CodeAction=t.CodeActionContext=t.CodeActionTriggerKind=t.CodeActionKind=t.DocumentSymbol=t.WorkspaceSymbol=t.SymbolInformation=t.SymbolTag=t.SymbolKind=t.DocumentHighlight=t.DocumentHighlightKind=t.SignatureInformation=t.ParameterInformation=t.Hover=t.MarkedString=t.CompletionList=t.CompletionItem=t.CompletionItemLabelDetails=t.InsertTextMode=t.InsertReplaceEdit=t.CompletionItemTag=t.InsertTextFormat=t.CompletionItemKind=t.MarkupContent=t.MarkupKind=t.TextDocumentItem=t.OptionalVersionedTextDocumentIdentifier=t.VersionedTextDocumentIdentifier=t.TextDocumentIdentifier=t.WorkspaceChange=t.WorkspaceEdit=t.DeleteFile=t.RenameFile=t.CreateFile=t.TextDocumentEdit=t.AnnotatedTextEdit=t.ChangeAnnotationIdentifier=t.ChangeAnnotation=t.TextEdit=t.Command=t.Diagnostic=t.CodeDescription=t.DiagnosticTag=t.DiagnosticSeverity=t.DiagnosticRelatedInformation=t.FoldingRange=t.FoldingRangeKind=t.ColorPresentation=t.ColorInformation=t.Color=t.LocationLink=t.Location=t.Range=t.Position=t.uinteger=t.integer=t.URI=t.DocumentUri=void 0,function(e){e.is=function(e){return"string"==typeof e}}(n||(t.DocumentUri=n={})),function(e){e.is=function(e){return"string"==typeof e}}(r||(t.URI=r={})),function(e){e.MIN_VALUE=-2147483648,e.MAX_VALUE=2147483647,e.is=function(t){return"number"==typeof t&&e.MIN_VALUE<=t&&t<=e.MAX_VALUE}}(i||(t.integer=i={})),function(e){e.MIN_VALUE=0,e.MAX_VALUE=2147483647,e.is=function(t){return"number"==typeof t&&e.MIN_VALUE<=t&&t<=e.MAX_VALUE}}(o||(t.uinteger=o={})),function(e){e.create=function(e,t){return e===Number.MAX_VALUE&&(e=o.MAX_VALUE),t===Number.MAX_VALUE&&(t=o.MAX_VALUE),{line:e,character:t}},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&Ie.uinteger(t.line)&&Ie.uinteger(t.character)}}(s||(t.Position=s={})),function(e){e.create=function(e,t,n,r){if(Ie.uinteger(e)&&Ie.uinteger(t)&&Ie.uinteger(n)&&Ie.uinteger(r))return{start:s.create(e,t),end:s.create(n,r)};if(s.is(e)&&s.is(t))return{start:e,end:t};throw new Error("Range#create called with invalid arguments[".concat(e,", ").concat(t,", ").concat(n,", ").concat(r,"]"))},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&s.is(t.start)&&s.is(t.end)}}(a||(t.Range=a={})),function(e){e.create=function(e,t){return{uri:e,range:t}},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&a.is(t.range)&&(Ie.string(t.uri)||Ie.undefined(t.uri))}}(c||(t.Location=c={})),function(e){e.create=function(e,t,n,r){return{targetUri:e,targetRange:t,targetSelectionRange:n,originSelectionRange:r}},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&a.is(t.targetRange)&&Ie.string(t.targetUri)&&a.is(t.targetSelectionRange)&&(a.is(t.originSelectionRange)||Ie.undefined(t.originSelectionRange))}}(l||(t.LocationLink=l={})),function(e){e.create=function(e,t,n,r){return{red:e,green:t,blue:n,alpha:r}},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&Ie.numberRange(t.red,0,1)&&Ie.numberRange(t.green,0,1)&&Ie.numberRange(t.blue,0,1)&&Ie.numberRange(t.alpha,0,1)}}(u||(t.Color=u={})),function(e){e.create=function(e,t){return{range:e,color:t}},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&a.is(t.range)&&u.is(t.color)}}(p||(t.ColorInformation=p={})),function(e){e.create=function(e,t,n){return{label:e,textEdit:t,additionalTextEdits:n}},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&Ie.string(t.label)&&(Ie.undefined(t.textEdit)||R.is(t))&&(Ie.undefined(t.additionalTextEdits)||Ie.typedArray(t.additionalTextEdits,R.is))}}(d||(t.ColorPresentation=d={})),function(e){e.Comment="comment",e.Imports="imports",e.Region="region"}(m||(t.FoldingRangeKind=m={})),function(e){e.create=function(e,t,n,r,i,o){var s={startLine:e,endLine:t};return Ie.defined(n)&&(s.startCharacter=n),Ie.defined(r)&&(s.endCharacter=r),Ie.defined(i)&&(s.kind=i),Ie.defined(o)&&(s.collapsedText=o),s},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&Ie.uinteger(t.startLine)&&Ie.uinteger(t.startLine)&&(Ie.undefined(t.startCharacter)||Ie.uinteger(t.startCharacter))&&(Ie.undefined(t.endCharacter)||Ie.uinteger(t.endCharacter))&&(Ie.undefined(t.kind)||Ie.string(t.kind))}}(h||(t.FoldingRange=h={})),function(e){e.create=function(e,t){return{location:e,message:t}},e.is=function(e){var t=e;return Ie.defined(t)&&c.is(t.location)&&Ie.string(t.message)}}(f||(t.DiagnosticRelatedInformation=f={})),function(e){e.Error=1,e.Warning=2,e.Information=3,e.Hint=4}(g||(t.DiagnosticSeverity=g={})),function(e){e.Unnecessary=1,e.Deprecated=2}(y||(t.DiagnosticTag=y={})),function(e){e.is=function(e){var t=e;return Ie.objectLiteral(t)&&Ie.string(t.href)}}(T||(t.CodeDescription=T={})),function(e){e.create=function(e,t,n,r,i,o){var s={range:e,message:t};return Ie.defined(n)&&(s.severity=n),Ie.defined(r)&&(s.code=r),Ie.defined(i)&&(s.source=i),Ie.defined(o)&&(s.relatedInformation=o),s},e.is=function(e){var t,n=e;return Ie.defined(n)&&a.is(n.range)&&Ie.string(n.message)&&(Ie.number(n.severity)||Ie.undefined(n.severity))&&(Ie.integer(n.code)||Ie.string(n.code)||Ie.undefined(n.code))&&(Ie.undefined(n.codeDescription)||Ie.string(null===(t=n.codeDescription)||void 0===t?void 0:t.href))&&(Ie.string(n.source)||Ie.undefined(n.source))&&(Ie.undefined(n.relatedInformation)||Ie.typedArray(n.relatedInformation,f.is))}}(_||(t.Diagnostic=_={})),function(e){e.create=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i={title:e,command:t};return Ie.defined(n)&&n.length>0&&(i.arguments=n),i},e.is=function(e){var t=e;return Ie.defined(t)&&Ie.string(t.title)&&Ie.string(t.command)}}(N||(t.Command=N={})),function(e){e.replace=function(e,t){return{range:e,newText:t}},e.insert=function(e,t){return{range:{start:e,end:e},newText:t}},e.del=function(e){return{range:e,newText:""}},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&Ie.string(t.newText)&&a.is(t.range)}}(R||(t.TextEdit=R={})),function(e){e.create=function(e,t,n){var r={label:e};return void 0!==t&&(r.needsConfirmation=t),void 0!==n&&(r.description=n),r},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&Ie.string(t.label)&&(Ie.boolean(t.needsConfirmation)||void 0===t.needsConfirmation)&&(Ie.string(t.description)||void 0===t.description)}}(E||(t.ChangeAnnotation=E={})),function(e){e.is=function(e){var t=e;return Ie.string(t)}}(b||(t.ChangeAnnotationIdentifier=b={})),function(e){e.replace=function(e,t,n){return{range:e,newText:t,annotationId:n}},e.insert=function(e,t,n){return{range:{start:e,end:e},newText:t,annotationId:n}},e.del=function(e,t){return{range:e,newText:"",annotationId:t}},e.is=function(e){var t=e;return R.is(t)&&(E.is(t.annotationId)||b.is(t.annotationId))}}(v||(t.AnnotatedTextEdit=v={})),function(e){e.create=function(e,t){return{textDocument:e,edits:t}},e.is=function(e){var t=e;return Ie.defined(t)&&k.is(t.textDocument)&&Array.isArray(t.edits)}}(S||(t.TextDocumentEdit=S={})),function(e){e.create=function(e,t,n){var r={kind:"create",uri:e};return void 0===t||void 0===t.overwrite&&void 0===t.ignoreIfExists||(r.options=t),void 0!==n&&(r.annotationId=n),r},e.is=function(e){var t=e;return t&&"create"===t.kind&&Ie.string(t.uri)&&(void 0===t.options||(void 0===t.options.overwrite||Ie.boolean(t.options.overwrite))&&(void 0===t.options.ignoreIfExists||Ie.boolean(t.options.ignoreIfExists)))&&(void 0===t.annotationId||b.is(t.annotationId))}}(C||(t.CreateFile=C={})),function(e){e.create=function(e,t,n,r){var i={kind:"rename",oldUri:e,newUri:t};return void 0===n||void 0===n.overwrite&&void 0===n.ignoreIfExists||(i.options=n),void 0!==r&&(i.annotationId=r),i},e.is=function(e){var t=e;return t&&"rename"===t.kind&&Ie.string(t.oldUri)&&Ie.string(t.newUri)&&(void 0===t.options||(void 0===t.options.overwrite||Ie.boolean(t.options.overwrite))&&(void 0===t.options.ignoreIfExists||Ie.boolean(t.options.ignoreIfExists)))&&(void 0===t.annotationId||b.is(t.annotationId))}}(A||(t.RenameFile=A={})),function(e){e.create=function(e,t,n){var r={kind:"delete",uri:e};return void 0===t||void 0===t.recursive&&void 0===t.ignoreIfNotExists||(r.options=t),void 0!==n&&(r.annotationId=n),r},e.is=function(e){var t=e;return t&&"delete"===t.kind&&Ie.string(t.uri)&&(void 0===t.options||(void 0===t.options.recursive||Ie.boolean(t.options.recursive))&&(void 0===t.options.ignoreIfNotExists||Ie.boolean(t.options.ignoreIfNotExists)))&&(void 0===t.annotationId||b.is(t.annotationId))}}(O||(t.DeleteFile=O={})),function(e){e.is=function(e){var t=e;return t&&(void 0!==t.changes||void 0!==t.documentChanges)&&(void 0===t.documentChanges||t.documentChanges.every(function(e){return Ie.string(e.kind)?C.is(e)||A.is(e)||O.is(e):S.is(e)}))}}(L||(t.WorkspaceEdit=L={}));var I,D,k,P,x,w,M,F,U,K,G,B,W,$,j,q,V,H,Y,X,z,J,Q,Z,ee,te,ne,re,ie,oe,se,ae,ce,le,ue,pe,de,me,he,fe,ge,ye,Te,_e,Ne,Re,Ee,be,ve,Se,Ce,Ae=function(){function e(e,t){this.edits=e,this.changeAnnotations=t}return e.prototype.insert=function(e,t,n){var r,i;if(void 0===n?r=R.insert(e,t):b.is(n)?(i=n,r=v.insert(e,t,n)):(this.assertChangeAnnotations(this.changeAnnotations),i=this.changeAnnotations.manage(n),r=v.insert(e,t,i)),this.edits.push(r),void 0!==i)return i},e.prototype.replace=function(e,t,n){var r,i;if(void 0===n?r=R.replace(e,t):b.is(n)?(i=n,r=v.replace(e,t,n)):(this.assertChangeAnnotations(this.changeAnnotations),i=this.changeAnnotations.manage(n),r=v.replace(e,t,i)),this.edits.push(r),void 0!==i)return i},e.prototype.delete=function(e,t){var n,r;if(void 0===t?n=R.del(e):b.is(t)?(r=t,n=v.del(e,t)):(this.assertChangeAnnotations(this.changeAnnotations),r=this.changeAnnotations.manage(t),n=v.del(e,r)),this.edits.push(n),void 0!==r)return r},e.prototype.add=function(e){this.edits.push(e)},e.prototype.all=function(){return this.edits},e.prototype.clear=function(){this.edits.splice(0,this.edits.length)},e.prototype.assertChangeAnnotations=function(e){if(void 0===e)throw new Error("Text edit change is not configured to manage change annotations.")},e}(),Oe=function(){function e(e){this._annotations=void 0===e?Object.create(null):e,this._counter=0,this._size=0}return e.prototype.all=function(){return this._annotations},Object.defineProperty(e.prototype,"size",{get:function(){return this._size},enumerable:!1,configurable:!0}),e.prototype.manage=function(e,t){var n;if(b.is(e)?n=e:(n=this.nextId(),t=e),void 0!==this._annotations[n])throw new Error("Id ".concat(n," is already in use."));if(void 0===t)throw new Error("No annotation provided for id ".concat(n));return this._annotations[n]=t,this._size++,n},e.prototype.nextId=function(){return this._counter++,this._counter.toString()},e}(),Le=function(){function e(e){var t=this;this._textEditChanges=Object.create(null),void 0!==e?(this._workspaceEdit=e,e.documentChanges?(this._changeAnnotations=new Oe(e.changeAnnotations),e.changeAnnotations=this._changeAnnotations.all(),e.documentChanges.forEach(function(e){if(S.is(e)){var n=new Ae(e.edits,t._changeAnnotations);t._textEditChanges[e.textDocument.uri]=n}})):e.changes&&Object.keys(e.changes).forEach(function(n){var r=new Ae(e.changes[n]);t._textEditChanges[n]=r})):this._workspaceEdit={}}return Object.defineProperty(e.prototype,"edit",{get:function(){return this.initDocumentChanges(),void 0!==this._changeAnnotations&&(0===this._changeAnnotations.size?this._workspaceEdit.changeAnnotations=void 0:this._workspaceEdit.changeAnnotations=this._changeAnnotations.all()),this._workspaceEdit},enumerable:!1,configurable:!0}),e.prototype.getTextEditChange=function(e){if(k.is(e)){if(this.initDocumentChanges(),void 0===this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.");var t={uri:e.uri,version:e.version};if(!(r=this._textEditChanges[t.uri])){var n={textDocument:t,edits:i=[]};this._workspaceEdit.documentChanges.push(n),r=new Ae(i,this._changeAnnotations),this._textEditChanges[t.uri]=r}return r}if(this.initChanges(),void 0===this._workspaceEdit.changes)throw new Error("Workspace edit is not configured for normal text edit changes.");var r;if(!(r=this._textEditChanges[e])){var i=[];this._workspaceEdit.changes[e]=i,r=new Ae(i),this._textEditChanges[e]=r}return r},e.prototype.initDocumentChanges=function(){void 0===this._workspaceEdit.documentChanges&&void 0===this._workspaceEdit.changes&&(this._changeAnnotations=new Oe,this._workspaceEdit.documentChanges=[],this._workspaceEdit.changeAnnotations=this._changeAnnotations.all())},e.prototype.initChanges=function(){void 0===this._workspaceEdit.documentChanges&&void 0===this._workspaceEdit.changes&&(this._workspaceEdit.changes=Object.create(null))},e.prototype.createFile=function(e,t,n){if(this.initDocumentChanges(),void 0===this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.");var r,i,o;if(E.is(t)||b.is(t)?r=t:n=t,void 0===r?i=C.create(e,n):(o=b.is(r)?r:this._changeAnnotations.manage(r),i=C.create(e,n,o)),this._workspaceEdit.documentChanges.push(i),void 0!==o)return o},e.prototype.renameFile=function(e,t,n,r){if(this.initDocumentChanges(),void 0===this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.");var i,o,s;if(E.is(n)||b.is(n)?i=n:r=n,void 0===i?o=A.create(e,t,r):(s=b.is(i)?i:this._changeAnnotations.manage(i),o=A.create(e,t,r,s)),this._workspaceEdit.documentChanges.push(o),void 0!==s)return s},e.prototype.deleteFile=function(e,t,n){if(this.initDocumentChanges(),void 0===this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.");var r,i,o;if(E.is(t)||b.is(t)?r=t:n=t,void 0===r?i=O.create(e,n):(o=b.is(r)?r:this._changeAnnotations.manage(r),i=O.create(e,n,o)),this._workspaceEdit.documentChanges.push(i),void 0!==o)return o},e}();t.WorkspaceChange=Le,function(e){e.create=function(e){return{uri:e}},e.is=function(e){var t=e;return Ie.defined(t)&&Ie.string(t.uri)}}(I||(t.TextDocumentIdentifier=I={})),function(e){e.create=function(e,t){return{uri:e,version:t}},e.is=function(e){var t=e;return Ie.defined(t)&&Ie.string(t.uri)&&Ie.integer(t.version)}}(D||(t.VersionedTextDocumentIdentifier=D={})),function(e){e.create=function(e,t){return{uri:e,version:t}},e.is=function(e){var t=e;return Ie.defined(t)&&Ie.string(t.uri)&&(null===t.version||Ie.integer(t.version))}}(k||(t.OptionalVersionedTextDocumentIdentifier=k={})),function(e){e.create=function(e,t,n,r){return{uri:e,languageId:t,version:n,text:r}},e.is=function(e){var t=e;return Ie.defined(t)&&Ie.string(t.uri)&&Ie.string(t.languageId)&&Ie.integer(t.version)&&Ie.string(t.text)}}(P||(t.TextDocumentItem=P={})),function(e){e.PlainText="plaintext",e.Markdown="markdown",e.is=function(t){var n=t;return n===e.PlainText||n===e.Markdown}}(x||(t.MarkupKind=x={})),function(e){e.is=function(e){var t=e;return Ie.objectLiteral(e)&&x.is(t.kind)&&Ie.string(t.value)}}(w||(t.MarkupContent=w={})),function(e){e.Text=1,e.Method=2,e.Function=3,e.Constructor=4,e.Field=5,e.Variable=6,e.Class=7,e.Interface=8,e.Module=9,e.Property=10,e.Unit=11,e.Value=12,e.Enum=13,e.Keyword=14,e.Snippet=15,e.Color=16,e.File=17,e.Reference=18,e.Folder=19,e.EnumMember=20,e.Constant=21,e.Struct=22,e.Event=23,e.Operator=24,e.TypeParameter=25}(M||(t.CompletionItemKind=M={})),function(e){e.PlainText=1,e.Snippet=2}(F||(t.InsertTextFormat=F={})),function(e){e.Deprecated=1}(U||(t.CompletionItemTag=U={})),function(e){e.create=function(e,t,n){return{newText:e,insert:t,replace:n}},e.is=function(e){var t=e;return t&&Ie.string(t.newText)&&a.is(t.insert)&&a.is(t.replace)}}(K||(t.InsertReplaceEdit=K={})),function(e){e.asIs=1,e.adjustIndentation=2}(G||(t.InsertTextMode=G={})),function(e){e.is=function(e){var t=e;return t&&(Ie.string(t.detail)||void 0===t.detail)&&(Ie.string(t.description)||void 0===t.description)}}(B||(t.CompletionItemLabelDetails=B={})),function(e){e.create=function(e){return{label:e}}}(W||(t.CompletionItem=W={})),function(e){e.create=function(e,t){return{items:e||[],isIncomplete:!!t}}}($||(t.CompletionList=$={})),function(e){e.fromPlainText=function(e){return e.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")},e.is=function(e){var t=e;return Ie.string(t)||Ie.objectLiteral(t)&&Ie.string(t.language)&&Ie.string(t.value)}}(j||(t.MarkedString=j={})),function(e){e.is=function(e){var t=e;return!!t&&Ie.objectLiteral(t)&&(w.is(t.contents)||j.is(t.contents)||Ie.typedArray(t.contents,j.is))&&(void 0===e.range||a.is(e.range))}}(q||(t.Hover=q={})),function(e){e.create=function(e,t){return t?{label:e,documentation:t}:{label:e}}}(V||(t.ParameterInformation=V={})),function(e){e.create=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i={label:e};return Ie.defined(t)&&(i.documentation=t),Ie.defined(n)?i.parameters=n:i.parameters=[],i}}(H||(t.SignatureInformation=H={})),function(e){e.Text=1,e.Read=2,e.Write=3}(Y||(t.DocumentHighlightKind=Y={})),function(e){e.create=function(e,t){var n={range:e};return Ie.number(t)&&(n.kind=t),n}}(X||(t.DocumentHighlight=X={})),function(e){e.File=1,e.Module=2,e.Namespace=3,e.Package=4,e.Class=5,e.Method=6,e.Property=7,e.Field=8,e.Constructor=9,e.Enum=10,e.Interface=11,e.Function=12,e.Variable=13,e.Constant=14,e.String=15,e.Number=16,e.Boolean=17,e.Array=18,e.Object=19,e.Key=20,e.Null=21,e.EnumMember=22,e.Struct=23,e.Event=24,e.Operator=25,e.TypeParameter=26}(z||(t.SymbolKind=z={})),function(e){e.Deprecated=1}(J||(t.SymbolTag=J={})),function(e){e.create=function(e,t,n,r,i){var o={name:e,kind:t,location:{uri:r,range:n}};return i&&(o.containerName=i),o}}(Q||(t.SymbolInformation=Q={})),function(e){e.create=function(e,t,n,r){return void 0!==r?{name:e,kind:t,location:{uri:n,range:r}}:{name:e,kind:t,location:{uri:n}}}}(Z||(t.WorkspaceSymbol=Z={})),function(e){e.create=function(e,t,n,r,i,o){var s={name:e,detail:t,kind:n,range:r,selectionRange:i};return void 0!==o&&(s.children=o),s},e.is=function(e){var t=e;return t&&Ie.string(t.name)&&Ie.number(t.kind)&&a.is(t.range)&&a.is(t.selectionRange)&&(void 0===t.detail||Ie.string(t.detail))&&(void 0===t.deprecated||Ie.boolean(t.deprecated))&&(void 0===t.children||Array.isArray(t.children))&&(void 0===t.tags||Array.isArray(t.tags))}}(ee||(t.DocumentSymbol=ee={})),function(e){e.Empty="",e.QuickFix="quickfix",e.Refactor="refactor",e.RefactorExtract="refactor.extract",e.RefactorInline="refactor.inline",e.RefactorRewrite="refactor.rewrite",e.Source="source",e.SourceOrganizeImports="source.organizeImports",e.SourceFixAll="source.fixAll"}(te||(t.CodeActionKind=te={})),function(e){e.Invoked=1,e.Automatic=2}(ne||(t.CodeActionTriggerKind=ne={})),function(e){e.create=function(e,t,n){var r={diagnostics:e};return null!=t&&(r.only=t),null!=n&&(r.triggerKind=n),r},e.is=function(e){var t=e;return Ie.defined(t)&&Ie.typedArray(t.diagnostics,_.is)&&(void 0===t.only||Ie.typedArray(t.only,Ie.string))&&(void 0===t.triggerKind||t.triggerKind===ne.Invoked||t.triggerKind===ne.Automatic)}}(re||(t.CodeActionContext=re={})),function(e){e.create=function(e,t,n){var r={title:e},i=!0;return"string"==typeof t?(i=!1,r.kind=t):N.is(t)?r.command=t:r.edit=t,i&&void 0!==n&&(r.kind=n),r},e.is=function(e){var t=e;return t&&Ie.string(t.title)&&(void 0===t.diagnostics||Ie.typedArray(t.diagnostics,_.is))&&(void 0===t.kind||Ie.string(t.kind))&&(void 0!==t.edit||void 0!==t.command)&&(void 0===t.command||N.is(t.command))&&(void 0===t.isPreferred||Ie.boolean(t.isPreferred))&&(void 0===t.edit||L.is(t.edit))}}(ie||(t.CodeAction=ie={})),function(e){e.create=function(e,t){var n={range:e};return Ie.defined(t)&&(n.data=t),n},e.is=function(e){var t=e;return Ie.defined(t)&&a.is(t.range)&&(Ie.undefined(t.command)||N.is(t.command))}}(oe||(t.CodeLens=oe={})),function(e){e.create=function(e,t){return{tabSize:e,insertSpaces:t}},e.is=function(e){var t=e;return Ie.defined(t)&&Ie.uinteger(t.tabSize)&&Ie.boolean(t.insertSpaces)}}(se||(t.FormattingOptions=se={})),function(e){e.create=function(e,t,n){return{range:e,target:t,data:n}},e.is=function(e){var t=e;return Ie.defined(t)&&a.is(t.range)&&(Ie.undefined(t.target)||Ie.string(t.target))}}(ae||(t.DocumentLink=ae={})),function(e){e.create=function(e,t){return{range:e,parent:t}},e.is=function(t){var n=t;return Ie.objectLiteral(n)&&a.is(n.range)&&(void 0===n.parent||e.is(n.parent))}}(ce||(t.SelectionRange=ce={})),function(e){e.namespace="namespace",e.type="type",e.class="class",e.enum="enum",e.interface="interface",e.struct="struct",e.typeParameter="typeParameter",e.parameter="parameter",e.variable="variable",e.property="property",e.enumMember="enumMember",e.event="event",e.function="function",e.method="method",e.macro="macro",e.keyword="keyword",e.modifier="modifier",e.comment="comment",e.string="string",e.number="number",e.regexp="regexp",e.operator="operator",e.decorator="decorator"}(le||(t.SemanticTokenTypes=le={})),function(e){e.declaration="declaration",e.definition="definition",e.readonly="readonly",e.static="static",e.deprecated="deprecated",e.abstract="abstract",e.async="async",e.modification="modification",e.documentation="documentation",e.defaultLibrary="defaultLibrary"}(ue||(t.SemanticTokenModifiers=ue={})),function(e){e.is=function(e){var t=e;return Ie.objectLiteral(t)&&(void 0===t.resultId||"string"==typeof t.resultId)&&Array.isArray(t.data)&&(0===t.data.length||"number"==typeof t.data[0])}}(pe||(t.SemanticTokens=pe={})),function(e){e.create=function(e,t){return{range:e,text:t}},e.is=function(e){var t=e;return null!=t&&a.is(t.range)&&Ie.string(t.text)}}(de||(t.InlineValueText=de={})),function(e){e.create=function(e,t,n){return{range:e,variableName:t,caseSensitiveLookup:n}},e.is=function(e){var t=e;return null!=t&&a.is(t.range)&&Ie.boolean(t.caseSensitiveLookup)&&(Ie.string(t.variableName)||void 0===t.variableName)}}(me||(t.InlineValueVariableLookup=me={})),function(e){e.create=function(e,t){return{range:e,expression:t}},e.is=function(e){var t=e;return null!=t&&a.is(t.range)&&(Ie.string(t.expression)||void 0===t.expression)}}(he||(t.InlineValueEvaluatableExpression=he={})),function(e){e.create=function(e,t){return{frameId:e,stoppedLocation:t}},e.is=function(e){var t=e;return Ie.defined(t)&&a.is(e.stoppedLocation)}}(fe||(t.InlineValueContext=fe={})),function(e){e.Type=1,e.Parameter=2,e.is=function(e){return 1===e||2===e}}(ge||(t.InlayHintKind=ge={})),function(e){e.create=function(e){return{value:e}},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&(void 0===t.tooltip||Ie.string(t.tooltip)||w.is(t.tooltip))&&(void 0===t.location||c.is(t.location))&&(void 0===t.command||N.is(t.command))}}(ye||(t.InlayHintLabelPart=ye={})),function(e){e.create=function(e,t,n){var r={position:e,label:t};return void 0!==n&&(r.kind=n),r},e.is=function(e){var t=e;return Ie.objectLiteral(t)&&s.is(t.position)&&(Ie.string(t.label)||Ie.typedArray(t.label,ye.is))&&(void 0===t.kind||ge.is(t.kind))&&void 0===t.textEdits||Ie.typedArray(t.textEdits,R.is)&&(void 0===t.tooltip||Ie.string(t.tooltip)||w.is(t.tooltip))&&(void 0===t.paddingLeft||Ie.boolean(t.paddingLeft))&&(void 0===t.paddingRight||Ie.boolean(t.paddingRight))}}(Te||(t.InlayHint=Te={})),function(e){e.createSnippet=function(e){return{kind:"snippet",value:e}}}(_e||(t.StringValue=_e={})),function(e){e.create=function(e,t,n,r){return{insertText:e,filterText:t,range:n,command:r}}}(Ne||(t.InlineCompletionItem=Ne={})),function(e){e.create=function(e){return{items:e}}}(Re||(t.InlineCompletionList=Re={})),function(e){e.Invoked=0,e.Automatic=1}(Ee||(t.InlineCompletionTriggerKind=Ee={})),function(e){e.create=function(e,t){return{range:e,text:t}}}(be||(t.SelectedCompletionInfo=be={})),function(e){e.create=function(e,t){return{triggerKind:e,selectedCompletionInfo:t}}}(ve||(t.InlineCompletionContext=ve={})),function(e){e.is=function(e){var t=e;return Ie.objectLiteral(t)&&r.is(t.uri)&&Ie.string(t.name)}}(Se||(t.WorkspaceFolder=Se={})),t.EOL=["\n","\r\n","\r"],function(e){function t(e,n){if(e.length<=1)return e;var r=e.length/2|0,i=e.slice(0,r),o=e.slice(r);t(i,n),t(o,n);for(var s=0,a=0,c=0;s<i.length&&a<o.length;){var l=n(i[s],o[a]);e[c++]=l<=0?i[s++]:o[a++]}for(;s<i.length;)e[c++]=i[s++];for(;a<o.length;)e[c++]=o[a++];return e}e.create=function(e,t,n,r){return new De(e,t,n,r)},e.is=function(e){var t=e;return!!(Ie.defined(t)&&Ie.string(t.uri)&&(Ie.undefined(t.languageId)||Ie.string(t.languageId))&&Ie.uinteger(t.lineCount)&&Ie.func(t.getText)&&Ie.func(t.positionAt)&&Ie.func(t.offsetAt))},e.applyEdits=function(e,n){for(var r=e.getText(),i=t(n,function(e,t){var n=e.range.start.line-t.range.start.line;return 0===n?e.range.start.character-t.range.start.character:n}),o=r.length,s=i.length-1;s>=0;s--){var a=i[s],c=e.offsetAt(a.range.start),l=e.offsetAt(a.range.end);if(!(l<=o))throw new Error("Overlapping edit");r=r.substring(0,c)+a.newText+r.substring(l,r.length),o=c}return r}}(Ce||(t.TextDocument=Ce={}));var Ie,De=function(){function e(e,t,n,r){this._uri=e,this._languageId=t,this._version=n,this._content=r,this._lineOffsets=void 0}return Object.defineProperty(e.prototype,"uri",{get:function(){return this._uri},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"languageId",{get:function(){return this._languageId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"version",{get:function(){return this._version},enumerable:!1,configurable:!0}),e.prototype.getText=function(e){if(e){var t=this.offsetAt(e.start),n=this.offsetAt(e.end);return this._content.substring(t,n)}return this._content},e.prototype.update=function(e,t){this._content=e.text,this._version=t,this._lineOffsets=void 0},e.prototype.getLineOffsets=function(){if(void 0===this._lineOffsets){for(var e=[],t=this._content,n=!0,r=0;r<t.length;r++){n&&(e.push(r),n=!1);var i=t.charAt(r);n="\r"===i||"\n"===i,"\r"===i&&r+1<t.length&&"\n"===t.charAt(r+1)&&r++}n&&t.length>0&&e.push(t.length),this._lineOffsets=e}return this._lineOffsets},e.prototype.positionAt=function(e){e=Math.max(Math.min(e,this._content.length),0);var t=this.getLineOffsets(),n=0,r=t.length;if(0===r)return s.create(0,e);for(;n<r;){var i=Math.floor((n+r)/2);t[i]>e?r=i:n=i+1}var o=n-1;return s.create(o,e-t[o])},e.prototype.offsetAt=function(e){var t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;var n=t[e.line],r=e.line+1<t.length?t[e.line+1]:this._content.length;return Math.max(Math.min(n+e.character,r),n)},Object.defineProperty(e.prototype,"lineCount",{get:function(){return this.getLineOffsets().length},enumerable:!1,configurable:!0}),e}();!function(e){var t=Object.prototype.toString;e.defined=function(e){return void 0!==e},e.undefined=function(e){return void 0===e},e.boolean=function(e){return!0===e||!1===e},e.string=function(e){return"[object String]"===t.call(e)},e.number=function(e){return"[object Number]"===t.call(e)},e.numberRange=function(e,n,r){return"[object Number]"===t.call(e)&&n<=e&&e<=r},e.integer=function(e){return"[object Number]"===t.call(e)&&-2147483648<=e&&e<=2147483647},e.uinteger=function(e){return"[object Number]"===t.call(e)&&0<=e&&e<=2147483647},e.func=function(e){return"[object Function]"===t.call(e)},e.objectLiteral=function(e){return null!==e&&"object"==typeof e},e.typedArray=function(e,t){return Array.isArray(e)&&e.every(t)}}(Ie||(Ie={}))})},6675:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CallHierarchyOutgoingCallsRequest=t.CallHierarchyIncomingCallsRequest=t.CallHierarchyPrepareRequest=void 0;const r=n(2834);var i,o,s;!function(e){e.method="textDocument/prepareCallHierarchy",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.CallHierarchyPrepareRequest=i={})),function(e){e.method="callHierarchy/incomingCalls",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(o||(t.CallHierarchyIncomingCallsRequest=o={})),function(e){e.method="callHierarchy/outgoingCalls",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(s||(t.CallHierarchyOutgoingCallsRequest=s={}))},6749:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionRangeRequest=void 0;const r=n(2834);var i;!function(e){e.method="textDocument/selectionRange",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.SelectionRangeRequest=i={}))},6928:e=>{"use strict";e.exports=require("path")},6982:e=>{"use strict";e.exports=require("crypto")},7007:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharedArrayReceiverStrategy=t.SharedArraySenderStrategy=void 0;const r=n(7279);var i;!function(e){e.Continue=0,e.Cancelled=1}(i||(i={})),t.SharedArraySenderStrategy=class{constructor(){this.buffers=new Map}enableCancellation(e){if(null===e.id)return;const t=new SharedArrayBuffer(4);new Int32Array(t,0,1)[0]=i.Continue,this.buffers.set(e.id,t),e.$cancellationData=t}async sendCancellation(e,t){const n=this.buffers.get(t);if(void 0===n)return;const r=new Int32Array(n,0,1);Atomics.store(r,0,i.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};class o{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===i.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}}class s{constructor(e){this.token=new o(e)}cancel(){}dispose(){}}t.SharedArrayReceiverStrategy=class{constructor(){this.kind="request"}createCancellationTokenSource(e){const t=e.$cancellationData;return void 0===t?new r.CancellationTokenSource:new s(t)}}},7016:e=>{"use strict";e.exports=require("url")},7279:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationTokenSource=t.CancellationToken=void 0;const r=n(4017),i=n(6204),o=n(3537);var s;!function(e){e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:o.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:o.Event.None}),e.is=function(t){const n=t;return n&&(n===e.None||n===e.Cancelled||i.boolean(n.isCancellationRequested)&&!!n.onCancellationRequested)}}(s||(t.CancellationToken=s={}));const a=Object.freeze(function(e,t){const n=(0,r.default)().timer.setTimeout(e.bind(t),0);return{dispose(){n.dispose()}}});class c{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?a:(this._emitter||(this._emitter=new o.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}}t.CancellationTokenSource=class{get token(){return this._token||(this._token=new c),this._token}cancel(){this._token?this._token.cancel():this._token=s.Cancelled}dispose(){this._token?this._token instanceof c&&this._token.dispose():this._token=s.None}}},7614:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createProtocolConnection=void 0;const r=n(5174);t.createProtocolConnection=function(e,t,n,i){return r.ConnectionStrategy.is(i)&&(i={connectionStrategy:i}),(0,r.createMessageConnection)(e,t,n,i)}},7861:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InlineCompletionRequest=void 0;const r=n(2834);var i;!function(e){e.method="textDocument/inlineCompletion",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.InlineCompletionRequest=i={}))},7874:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createConnection=t.combineFeatures=t.combineNotebooksFeatures=t.combineLanguagesFeatures=t.combineWorkspaceFeatures=t.combineWindowFeatures=t.combineClientFeatures=t.combineTracerFeatures=t.combineTelemetryFeatures=t.combineConsoleFeatures=t._NotebooksImpl=t._LanguagesImpl=t.BulkUnregistration=t.BulkRegistration=t.ErrorMessageTracker=void 0;const r=n(8828),i=n(8867),o=n(6116),s=n(557),a=n(8491),c=n(2112),l=n(3918),u=n(2655),p=n(8817),d=n(2697),m=n(8517),h=n(5026),f=n(1815),g=n(6007),y=n(4635),T=n(2874),_=n(20),N=n(2936);function R(e){if(null!==e)return e}t.ErrorMessageTracker=class{constructor(){this._messages=Object.create(null)}add(e){let t=this._messages[e];t||(t=0),t++,this._messages[e]=t}sendErrors(e){Object.keys(this._messages).forEach(t=>{e.window.showErrorMessage(t)})}};class E{constructor(){}rawAttach(e){this._rawConnection=e}attach(e){this._connection=e}get connection(){if(!this._connection)throw new Error("Remote is not attached to a connection yet.");return this._connection}fillServerCapabilities(e){}initialize(e){}error(e){this.send(r.MessageType.Error,e)}warn(e){this.send(r.MessageType.Warning,e)}info(e){this.send(r.MessageType.Info,e)}log(e){this.send(r.MessageType.Log,e)}debug(e){this.send(r.MessageType.Debug,e)}send(e,t){this._rawConnection&&this._rawConnection.sendNotification(r.LogMessageNotification.type,{type:e,message:t}).catch(()=>{(0,r.RAL)().console.error("Sending log message failed")})}}const b=(0,p.ShowDocumentFeature)((0,s.ProgressFeature)(class{constructor(){}attach(e){this._connection=e}get connection(){if(!this._connection)throw new Error("Remote is not attached to a connection yet.");return this._connection}initialize(e){}fillServerCapabilities(e){}showErrorMessage(e,...t){let n={type:r.MessageType.Error,message:e,actions:t};return this.connection.sendRequest(r.ShowMessageRequest.type,n).then(R)}showWarningMessage(e,...t){let n={type:r.MessageType.Warning,message:e,actions:t};return this.connection.sendRequest(r.ShowMessageRequest.type,n).then(R)}showInformationMessage(e,...t){let n={type:r.MessageType.Info,message:e,actions:t};return this.connection.sendRequest(r.ShowMessageRequest.type,n).then(R)}}));var v,S;!function(e){e.create=function(){return new C}}(v||(t.BulkRegistration=v={}));class C{constructor(){this._registrations=[],this._registered=new Set}add(e,t){const n=i.string(e)?e:e.method;if(this._registered.has(n))throw new Error(`${n} is already added to this registration`);const r=o.generateUuid();this._registrations.push({id:r,method:n,registerOptions:t||{}}),this._registered.add(n)}asRegistrationParams(){return{registrations:this._registrations}}}!function(e){e.create=function(){return new A(void 0,[])}}(S||(t.BulkUnregistration=S={}));class A{constructor(e,t){this._connection=e,this._unregistrations=new Map,t.forEach(e=>{this._unregistrations.set(e.method,e)})}get isAttached(){return!!this._connection}attach(e){this._connection=e}add(e){this._unregistrations.set(e.method,e)}dispose(){let e=[];for(let t of this._unregistrations.values())e.push(t);let t={unregisterations:e};this._connection.sendRequest(r.UnregistrationRequest.type,t).catch(()=>{this._connection.console.info("Bulk unregistration failed.")})}disposeSingle(e){const t=i.string(e)?e:e.method,n=this._unregistrations.get(t);if(!n)return!1;let o={unregisterations:[n]};return this._connection.sendRequest(r.UnregistrationRequest.type,o).then(()=>{this._unregistrations.delete(t)},e=>{this._connection.console.info(`Un-registering request handler for ${n.id} failed.`)}),!0}}class O{attach(e){this._connection=e}get connection(){if(!this._connection)throw new Error("Remote is not attached to a connection yet.");return this._connection}initialize(e){}fillServerCapabilities(e){}register(e,t,n){return e instanceof C?this.registerMany(e):e instanceof A?this.registerSingle1(e,t,n):this.registerSingle2(e,t)}registerSingle1(e,t,n){const s=i.string(t)?t:t.method,a=o.generateUuid();let c={registrations:[{id:a,method:s,registerOptions:n||{}}]};return e.isAttached||e.attach(this.connection),this.connection.sendRequest(r.RegistrationRequest.type,c).then(t=>(e.add({id:a,method:s}),e),e=>(this.connection.console.info(`Registering request handler for ${s} failed.`),Promise.reject(e)))}registerSingle2(e,t){const n=i.string(e)?e:e.method,s=o.generateUuid();let a={registrations:[{id:s,method:n,registerOptions:t||{}}]};return this.connection.sendRequest(r.RegistrationRequest.type,a).then(e=>r.Disposable.create(()=>{this.unregisterSingle(s,n).catch(()=>{this.connection.console.info(`Un-registering capability with id ${s} failed.`)})}),e=>(this.connection.console.info(`Registering request handler for ${n} failed.`),Promise.reject(e)))}unregisterSingle(e,t){let n={unregisterations:[{id:e,method:t}]};return this.connection.sendRequest(r.UnregistrationRequest.type,n).catch(()=>{this.connection.console.info(`Un-registering request handler for ${e} failed.`)})}registerMany(e){let t=e.asRegistrationParams();return this.connection.sendRequest(r.RegistrationRequest.type,t).then(()=>new A(this._connection,t.registrations.map(e=>({id:e.id,method:e.method}))),e=>(this.connection.console.info("Bulk registration failed."),Promise.reject(e)))}}const L=(0,d.FileOperationsFeature)((0,c.WorkspaceFoldersFeature)((0,a.ConfigurationFeature)(class{constructor(){}attach(e){this._connection=e}get connection(){if(!this._connection)throw new Error("Remote is not attached to a connection yet.");return this._connection}initialize(e){}fillServerCapabilities(e){}applyEdit(e){let t=(n=e)&&n.edit?e:{edit:e};var n;return this.connection.sendRequest(r.ApplyWorkspaceEditRequest.type,t)}})));class I{constructor(){this._trace=r.Trace.Off}attach(e){this._connection=e}get connection(){if(!this._connection)throw new Error("Remote is not attached to a connection yet.");return this._connection}initialize(e){}fillServerCapabilities(e){}set trace(e){this._trace=e}log(e,t){this._trace!==r.Trace.Off&&this.connection.sendNotification(r.LogTraceNotification.type,{message:e,verbose:this._trace===r.Trace.Verbose?t:void 0}).catch(()=>{})}}class D{constructor(){}attach(e){this._connection=e}get connection(){if(!this._connection)throw new Error("Remote is not attached to a connection yet.");return this._connection}initialize(e){}fillServerCapabilities(e){}logEvent(e){this.connection.sendNotification(r.TelemetryEventNotification.type,e).catch(()=>{this.connection.console.log("Sending TelemetryEventNotification failed")})}}class k{constructor(){}attach(e){this._connection=e}get connection(){if(!this._connection)throw new Error("Remote is not attached to a connection yet.");return this._connection}initialize(e){}fillServerCapabilities(e){}attachWorkDoneProgress(e){return(0,s.attachWorkDone)(this.connection,e)}attachPartialResultProgress(e,t){return(0,s.attachPartialResult)(this.connection,t)}}t._LanguagesImpl=k;const P=(0,g.FoldingRangeFeature)((0,N.MonikerFeature)((0,T.DiagnosticFeature)((0,y.InlayHintFeature)((0,f.InlineValueFeature)((0,h.TypeHierarchyFeature)((0,m.LinkedEditingRangeFeature)((0,u.SemanticTokensFeature)((0,l.CallHierarchyFeature)(k)))))))));class x{constructor(){}attach(e){this._connection=e}get connection(){if(!this._connection)throw new Error("Remote is not attached to a connection yet.");return this._connection}initialize(e){}fillServerCapabilities(e){}attachWorkDoneProgress(e){return(0,s.attachWorkDone)(this.connection,e)}attachPartialResultProgress(e,t){return(0,s.attachPartialResult)(this.connection,t)}}t._NotebooksImpl=x;const w=(0,_.NotebookSyncFeature)(x);function M(e,t){return function(n){return t(e(n))}}function F(e,t){return function(n){return t(e(n))}}function U(e,t){return function(n){return t(e(n))}}function K(e,t){return function(n){return t(e(n))}}function G(e,t){return function(n){return t(e(n))}}function B(e,t){return function(n){return t(e(n))}}function W(e,t){return function(n){return t(e(n))}}function $(e,t){return function(n){return t(e(n))}}t.combineConsoleFeatures=M,t.combineTelemetryFeatures=F,t.combineTracerFeatures=U,t.combineClientFeatures=K,t.combineWindowFeatures=G,t.combineWorkspaceFeatures=B,t.combineLanguagesFeatures=W,t.combineNotebooksFeatures=$,t.combineFeatures=function(e,t){function n(e,t,n){return e&&t?n(e,t):e||t}return{__brand:"features",console:n(e.console,t.console,M),tracer:n(e.tracer,t.tracer,U),telemetry:n(e.telemetry,t.telemetry,F),client:n(e.client,t.client,K),window:n(e.window,t.window,G),workspace:n(e.workspace,t.workspace,B),languages:n(e.languages,t.languages,W),notebooks:n(e.notebooks,t.notebooks,$)}},t.createConnection=function(e,t,n){const o=n&&n.console?new(n.console(E)):new E,a=e(o);o.rawAttach(a);const c=n&&n.tracer?new(n.tracer(I)):new I,l=n&&n.telemetry?new(n.telemetry(D)):new D,u=n&&n.client?new(n.client(O)):new O,p=n&&n.window?new(n.window(b)):new b,d=n&&n.workspace?new(n.workspace(L)):new L,m=n&&n.languages?new(n.languages(P)):new P,h=n&&n.notebooks?new(n.notebooks(w)):new w,f=[o,c,l,u,p,d,m,h];let g,y,T,_={listen:()=>a.listen(),sendRequest:(e,...t)=>a.sendRequest(i.string(e)?e:e.method,...t),onRequest:(e,t)=>a.onRequest(e,t),sendNotification:(e,t)=>{const n=i.string(e)?e:e.method;return a.sendNotification(n,t)},onNotification:(e,t)=>a.onNotification(e,t),onProgress:a.onProgress,sendProgress:a.sendProgress,onInitialize:e=>(y=e,{dispose:()=>{y=void 0}}),onInitialized:e=>a.onNotification(r.InitializedNotification.type,e),onShutdown:e=>(g=e,{dispose:()=>{g=void 0}}),onExit:e=>(T=e,{dispose:()=>{T=void 0}}),get console(){return o},get telemetry(){return l},get tracer(){return c},get client(){return u},get window(){return p},get workspace(){return d},get languages(){return m},get notebooks(){return h},onDidChangeConfiguration:e=>a.onNotification(r.DidChangeConfigurationNotification.type,e),onDidChangeWatchedFiles:e=>a.onNotification(r.DidChangeWatchedFilesNotification.type,e),__textDocumentSync:void 0,onDidOpenTextDocument:e=>a.onNotification(r.DidOpenTextDocumentNotification.type,e),onDidChangeTextDocument:e=>a.onNotification(r.DidChangeTextDocumentNotification.type,e),onDidCloseTextDocument:e=>a.onNotification(r.DidCloseTextDocumentNotification.type,e),onWillSaveTextDocument:e=>a.onNotification(r.WillSaveTextDocumentNotification.type,e),onWillSaveTextDocumentWaitUntil:e=>a.onRequest(r.WillSaveTextDocumentWaitUntilRequest.type,e),onDidSaveTextDocument:e=>a.onNotification(r.DidSaveTextDocumentNotification.type,e),sendDiagnostics:e=>a.sendNotification(r.PublishDiagnosticsNotification.type,e),onHover:e=>a.onRequest(r.HoverRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),void 0)),onCompletion:e=>a.onRequest(r.CompletionRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onCompletionResolve:e=>a.onRequest(r.CompletionResolveRequest.type,e),onSignatureHelp:e=>a.onRequest(r.SignatureHelpRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),void 0)),onDeclaration:e=>a.onRequest(r.DeclarationRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onDefinition:e=>a.onRequest(r.DefinitionRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onTypeDefinition:e=>a.onRequest(r.TypeDefinitionRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onImplementation:e=>a.onRequest(r.ImplementationRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onReferences:e=>a.onRequest(r.ReferencesRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onDocumentHighlight:e=>a.onRequest(r.DocumentHighlightRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onDocumentSymbol:e=>a.onRequest(r.DocumentSymbolRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onWorkspaceSymbol:e=>a.onRequest(r.WorkspaceSymbolRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onWorkspaceSymbolResolve:e=>a.onRequest(r.WorkspaceSymbolResolveRequest.type,e),onCodeAction:e=>a.onRequest(r.CodeActionRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onCodeActionResolve:e=>a.onRequest(r.CodeActionResolveRequest.type,(t,n)=>e(t,n)),onCodeLens:e=>a.onRequest(r.CodeLensRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onCodeLensResolve:e=>a.onRequest(r.CodeLensResolveRequest.type,(t,n)=>e(t,n)),onDocumentFormatting:e=>a.onRequest(r.DocumentFormattingRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),void 0)),onDocumentRangeFormatting:e=>a.onRequest(r.DocumentRangeFormattingRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),void 0)),onDocumentOnTypeFormatting:e=>a.onRequest(r.DocumentOnTypeFormattingRequest.type,(t,n)=>e(t,n)),onRenameRequest:e=>a.onRequest(r.RenameRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),void 0)),onPrepareRename:e=>a.onRequest(r.PrepareRenameRequest.type,(t,n)=>e(t,n)),onDocumentLinks:e=>a.onRequest(r.DocumentLinkRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onDocumentLinkResolve:e=>a.onRequest(r.DocumentLinkResolveRequest.type,(t,n)=>e(t,n)),onDocumentColor:e=>a.onRequest(r.DocumentColorRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onColorPresentation:e=>a.onRequest(r.ColorPresentationRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onFoldingRanges:e=>a.onRequest(r.FoldingRangeRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onSelectionRanges:e=>a.onRequest(r.SelectionRangeRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),(0,s.attachPartialResult)(a,t))),onExecuteCommand:e=>a.onRequest(r.ExecuteCommandRequest.type,(t,n)=>e(t,n,(0,s.attachWorkDone)(a,t),void 0)),dispose:()=>a.dispose()};for(let e of f)e.attach(_);return a.onRequest(r.InitializeRequest.type,e=>{t.initialize(e),i.string(e.trace)&&(c.trace=r.Trace.fromString(e.trace));for(let t of f)t.initialize(e.capabilities);if(y){let t=y(e,(new r.CancellationTokenSource).token,(0,s.attachWorkDone)(a,e),void 0);return(n=t,n instanceof Promise?n:i.thenable(n)?new Promise((e,t)=>{n.then(t=>e(t),e=>t(e))}):Promise.resolve(n)).then(e=>{if(e instanceof r.ResponseError)return e;let t=e;t||(t={capabilities:{}});let n=t.capabilities;n||(n={},t.capabilities=n),void 0===n.textDocumentSync||null===n.textDocumentSync?n.textDocumentSync=i.number(_.__textDocumentSync)?_.__textDocumentSync:r.TextDocumentSyncKind.None:i.number(n.textDocumentSync)||i.number(n.textDocumentSync.change)||(n.textDocumentSync.change=i.number(_.__textDocumentSync)?_.__textDocumentSync:r.TextDocumentSyncKind.None);for(let e of f)e.fillServerCapabilities(n);return t})}{let e={capabilities:{textDocumentSync:r.TextDocumentSyncKind.None}};for(let t of f)t.fillServerCapabilities(e.capabilities);return e}var n}),a.onRequest(r.ShutdownRequest.type,()=>(t.shutdownReceived=!0,g?g((new r.CancellationTokenSource).token):void 0)),a.onNotification(r.ExitNotification.type,()=>{try{T&&T()}finally{t.shutdownReceived?t.exit(0):t.exit(1)}}),a.onNotification(r.SetTraceNotification.type,e=>{c.trace=r.Trace.fromString(e.value)}),_}},7975:e=>{"use strict";e.exports=require("node:util")},8176:(e,t)=>{"use strict";function n(e){return"string"==typeof e||e instanceof String}function r(e){return Array.isArray(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.objectLiteral=t.typedArray=t.stringArray=t.array=t.func=t.error=t.number=t.string=t.boolean=void 0,t.boolean=function(e){return!0===e||!1===e},t.string=n,t.number=function(e){return"number"==typeof e||e instanceof Number},t.error=function(e){return e instanceof Error},t.func=function(e){return"function"==typeof e},t.array=r,t.stringArray=function(e){return r(e)&&e.every(e=>n(e))},t.typedArray=function(e,t){return Array.isArray(e)&&e.every(t)},t.objectLiteral=function(e){return null!==e&&"object"==typeof e}},8214:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorPresentationRequest=t.DocumentColorRequest=void 0;const r=n(2834);var i,o;!function(e){e.method="textDocument/documentColor",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.DocumentColorRequest=i={})),function(e){e.method="textDocument/colorPresentation",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(o||(t.ColorPresentationRequest=o={}))},8393:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DidChangeWorkspaceFoldersNotification=t.WorkspaceFoldersRequest=void 0;const r=n(2834);var i,o;!function(e){e.method="workspace/workspaceFolders",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType0(e.method)}(i||(t.WorkspaceFoldersRequest=i={})),function(e){e.method="workspace/didChangeWorkspaceFolders",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(o||(t.DidChangeWorkspaceFoldersNotification=o={}))},8491:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConfigurationFeature=void 0;const r=n(8828),i=n(8867);t.ConfigurationFeature=e=>class extends e{getConfiguration(e){return e?i.string(e)?this._getConfiguration({section:e}):this._getConfiguration(e):this._getConfiguration({})}_getConfiguration(e){let t={items:Array.isArray(e)?e:[e]};return this.connection.sendRequest(r.ConfigurationRequest.type,t).then(t=>Array.isArray(t)?Array.isArray(e)?t:t[0]:Array.isArray(e)?[]:null)}}},8517:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LinkedEditingRangeFeature=void 0;const r=n(8828);t.LinkedEditingRangeFeature=e=>class extends e{onLinkedEditingRange(e){return this.connection.onRequest(r.LinkedEditingRangeRequest.type,(t,n)=>e(t,n,this.attachWorkDoneProgress(t),void 0))}}},8577:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DiagnosticRefreshRequest=t.WorkspaceDiagnosticRequest=t.DocumentDiagnosticRequest=t.DocumentDiagnosticReportKind=t.DiagnosticServerCancellationData=void 0;const r=n(5174),i=n(8176),o=n(2834);var s,a,c,l,u;!function(e){e.is=function(e){const t=e;return t&&i.boolean(t.retriggerRequest)}}(s||(t.DiagnosticServerCancellationData=s={})),function(e){e.Full="full",e.Unchanged="unchanged"}(a||(t.DocumentDiagnosticReportKind=a={})),function(e){e.method="textDocument/diagnostic",e.messageDirection=o.MessageDirection.clientToServer,e.type=new o.ProtocolRequestType(e.method),e.partialResult=new r.ProgressType}(c||(t.DocumentDiagnosticRequest=c={})),function(e){e.method="workspace/diagnostic",e.messageDirection=o.MessageDirection.clientToServer,e.type=new o.ProtocolRequestType(e.method),e.partialResult=new r.ProgressType}(l||(t.WorkspaceDiagnosticRequest=l={})),function(e){e.method="workspace/diagnostic/refresh",e.messageDirection=o.MessageDirection.serverToClient,e.type=new o.ProtocolRequestType0(e.method)}(u||(t.DiagnosticRefreshRequest=u={}))},8754:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WillDeleteFilesRequest=t.DidDeleteFilesNotification=t.DidRenameFilesNotification=t.WillRenameFilesRequest=t.DidCreateFilesNotification=t.WillCreateFilesRequest=t.FileOperationPatternKind=void 0;const r=n(2834);var i,o,s,a,c,l,u;!function(e){e.file="file",e.folder="folder"}(i||(t.FileOperationPatternKind=i={})),function(e){e.method="workspace/willCreateFiles",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(o||(t.WillCreateFilesRequest=o={})),function(e){e.method="workspace/didCreateFiles",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(s||(t.DidCreateFilesNotification=s={})),function(e){e.method="workspace/willRenameFiles",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(a||(t.WillRenameFilesRequest=a={})),function(e){e.method="workspace/didRenameFiles",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(c||(t.DidRenameFilesNotification=c={})),function(e){e.method="workspace/didDeleteFiles",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolNotificationType(e.method)}(l||(t.DidDeleteFilesNotification=l={})),function(e){e.method="workspace/willDeleteFiles",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(u||(t.WillDeleteFilesRequest=u={}))},8817:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShowDocumentFeature=void 0;const r=n(8828);t.ShowDocumentFeature=e=>class extends e{showDocument(e){return this.connection.sendRequest(r.ShowDocumentRequest.type,e)}}},8828:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.createProtocolConnection=void 0;const o=n(5104);i(n(5104),t),i(n(720),t),t.createProtocolConnection=function(e,t,n,r){return(0,o.createMessageConnection)(e,t,n,r)}},8867:(e,t)=>{"use strict";function n(e){return"string"==typeof e||e instanceof String}function r(e){return"function"==typeof e}function i(e){return Array.isArray(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.thenable=t.typedArray=t.stringArray=t.array=t.func=t.error=t.number=t.string=t.boolean=void 0,t.boolean=function(e){return!0===e||!1===e},t.string=n,t.number=function(e){return"number"==typeof e||e instanceof Number},t.error=function(e){return e instanceof Error},t.func=r,t.array=i,t.stringArray=function(e){return i(e)&&e.every(e=>n(e))},t.typedArray=function(e,t){return Array.isArray(e)&&e.every(t)},t.thenable=function(e){return e&&r(e.then)}},8953:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkDoneProgressCancelNotification=t.WorkDoneProgressCreateRequest=t.WorkDoneProgress=void 0;const r=n(5174),i=n(2834);var o,s,a;!function(e){e.type=new r.ProgressType,e.is=function(t){return t===e.type}}(o||(t.WorkDoneProgress=o={})),function(e){e.method="window/workDoneProgress/create",e.messageDirection=i.MessageDirection.serverToClient,e.type=new i.ProtocolRequestType(e.method)}(s||(t.WorkDoneProgressCreateRequest=s={})),function(e){e.method="window/workDoneProgress/cancel",e.messageDirection=i.MessageDirection.clientToServer,e.type=new i.ProtocolNotificationType(e.method)}(a||(t.WorkDoneProgressCancelNotification=a={}))},8998:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InlineValueRefreshRequest=t.InlineValueRequest=void 0;const r=n(2834);var i,o;!function(e){e.method="textDocument/inlineValue",e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method)}(i||(t.InlineValueRequest=i={})),function(e){e.method="workspace/inlineValue/refresh",e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType0(e.method)}(o||(t.InlineValueRefreshRequest=o={}))},9023:e=>{"use strict";e.exports=require("util")},9278:e=>{"use strict";e.exports=require("net")},9896:e=>{"use strict";e.exports=require("fs")}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,n),o.exports}n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";var e,t=n(5663);class r{constructor(e,t,n,r){this._uri=e,this._languageId=t,this._version=n,this._content=r,this._lineOffsets=void 0}get uri(){return this._uri}get languageId(){return this._languageId}get version(){return this._version}getText(e){if(e){const t=this.offsetAt(e.start),n=this.offsetAt(e.end);return this._content.substring(t,n)}return this._content}update(e,t){for(const t of e)if(r.isIncremental(t)){const e=a(t.range),n=this.offsetAt(e.start),r=this.offsetAt(e.end);this._content=this._content.substring(0,n)+t.text+this._content.substring(r,this._content.length);const i=Math.max(e.start.line,0),s=Math.max(e.end.line,0);let c=this._lineOffsets;const l=o(t.text,!1,n);if(s-i===l.length)for(let e=0,t=l.length;e<t;e++)c[e+i+1]=l[e];else l.length<1e4?c.splice(i+1,s-i,...l):this._lineOffsets=c=c.slice(0,i+1).concat(l,c.slice(s+1));const u=t.text.length-(r-n);if(0!==u)for(let e=i+1+l.length,t=c.length;e<t;e++)c[e]=c[e]+u}else{if(!r.isFull(t))throw new Error("Unknown change event received");this._content=t.text,this._lineOffsets=void 0}this._version=t}getLineOffsets(){return void 0===this._lineOffsets&&(this._lineOffsets=o(this._content,!0)),this._lineOffsets}positionAt(e){e=Math.max(Math.min(e,this._content.length),0);const t=this.getLineOffsets();let n=0,r=t.length;if(0===r)return{line:0,character:e};for(;n<r;){const i=Math.floor((n+r)/2);t[i]>e?r=i:n=i+1}const i=n-1;return{line:i,character:(e=this.ensureBeforeEOL(e,t[i]))-t[i]}}offsetAt(e){const t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;const n=t[e.line];if(e.character<=0)return n;const r=e.line+1<t.length?t[e.line+1]:this._content.length,i=Math.min(n+e.character,r);return this.ensureBeforeEOL(i,n)}ensureBeforeEOL(e,t){for(;e>t&&s(this._content.charCodeAt(e-1));)e--;return e}get lineCount(){return this.getLineOffsets().length}static isIncremental(e){const t=e;return null!=t&&"string"==typeof t.text&&void 0!==t.range&&(void 0===t.rangeLength||"number"==typeof t.rangeLength)}static isFull(e){const t=e;return null!=t&&"string"==typeof t.text&&void 0===t.range&&void 0===t.rangeLength}}function i(e,t){if(e.length<=1)return e;const n=e.length/2|0,r=e.slice(0,n),o=e.slice(n);i(r,t),i(o,t);let s=0,a=0,c=0;for(;s<r.length&&a<o.length;){const n=t(r[s],o[a]);e[c++]=n<=0?r[s++]:o[a++]}for(;s<r.length;)e[c++]=r[s++];for(;a<o.length;)e[c++]=o[a++];return e}function o(e,t,n=0){const r=t?[n]:[];for(let t=0;t<e.length;t++){const i=e.charCodeAt(t);s(i)&&(13===i&&t+1<e.length&&10===e.charCodeAt(t+1)&&t++,r.push(n+t+1))}return r}function s(e){return 13===e||10===e}function a(e){const t=e.start,n=e.end;return t.line>n.line||t.line===n.line&&t.character>n.character?{start:n,end:t}:e}function c(e){const t=a(e.range);return t!==e.range?{newText:e.newText,range:t}:e}!function(e){e.create=function(e,t,n,i){return new r(e,t,n,i)},e.update=function(e,t,n){if(e instanceof r)return e.update(t,n),e;throw new Error("TextDocument.update: document must be created by TextDocument.create")},e.applyEdits=function(e,t){const n=e.getText(),r=i(t.map(c),(e,t)=>{const n=e.range.start.line-t.range.start.line;return 0===n?e.range.start.character-t.range.start.character:n});let o=0;const s=[];for(const t of r){const r=e.offsetAt(t.range.start);if(r<o)throw new Error("Overlapping edit");r>o&&s.push(n.substring(o,r)),t.newText.length&&s.push(t.newText),o=e.offsetAt(t.range.end)}return s.push(n.substr(o)),s.join("")}}(e||(e={}));var l,u=n(9896),p=n(6928);!function(e){e[e.TK_LEXP=1]="TK_LEXP",e[e.TK_REXP=2]="TK_REXP",e[e.TK_LSTM=3]="TK_LSTM",e[e.TK_RSTM=4]="TK_RSTM",e[e.TK_IF=5]="TK_IF",e[e.TK_ELSE=6]="TK_ELSE",e[e.TK_COMMA=7]="TK_COMMA",e[e.TK_ASSIGN=8]="TK_ASSIGN",e[e.TK_ASADD=9]="TK_ASADD",e[e.TK_ASSUB=10]="TK_ASSUB",e[e.TK_ASMUL=11]="TK_ASMUL",e[e.TK_ASDIV=12]="TK_ASDIV",e[e.TK_ASMOD=13]="TK_ASMOD",e[e.TK_ASLEFT=14]="TK_ASLEFT",e[e.TK_ASRIGHT=15]="TK_ASRIGHT",e[e.TK_ASBAND=16]="TK_ASBAND",e[e.TK_ASBXOR=17]="TK_ASBXOR",e[e.TK_ASBOR=18]="TK_ASBOR",e[e.TK_QMARK=19]="TK_QMARK",e[e.TK_COLON=20]="TK_COLON",e[e.TK_OR=21]="TK_OR",e[e.TK_AND=22]="TK_AND",e[e.TK_BOR=23]="TK_BOR",e[e.TK_BXOR=24]="TK_BXOR",e[e.TK_BAND=25]="TK_BAND",e[e.TK_EQS=26]="TK_EQS",e[e.TK_NES=27]="TK_NES",e[e.TK_EQ=28]="TK_EQ",e[e.TK_NE=29]="TK_NE",e[e.TK_LT=30]="TK_LT",e[e.TK_LE=31]="TK_LE",e[e.TK_GT=32]="TK_GT",e[e.TK_GE=33]="TK_GE",e[e.TK_IN=34]="TK_IN",e[e.TK_LSHIFT=35]="TK_LSHIFT",e[e.TK_RSHIFT=36]="TK_RSHIFT",e[e.TK_ADD=37]="TK_ADD",e[e.TK_SUB=38]="TK_SUB",e[e.TK_MUL=39]="TK_MUL",e[e.TK_DIV=40]="TK_DIV",e[e.TK_MOD=41]="TK_MOD",e[e.TK_EXP=42]="TK_EXP",e[e.TK_NOT=43]="TK_NOT",e[e.TK_COMPL=44]="TK_COMPL",e[e.TK_INC=45]="TK_INC",e[e.TK_DEC=46]="TK_DEC",e[e.TK_DOT=47]="TK_DOT",e[e.TK_LBRACK=48]="TK_LBRACK",e[e.TK_RBRACK=49]="TK_RBRACK",e[e.TK_LPAREN=50]="TK_LPAREN",e[e.TK_RPAREN=51]="TK_RPAREN",e[e.TK_TEXT=52]="TK_TEXT",e[e.TK_LBRACE=53]="TK_LBRACE",e[e.TK_RBRACE=54]="TK_RBRACE",e[e.TK_SCOL=55]="TK_SCOL",e[e.TK_ENDIF=56]="TK_ENDIF",e[e.TK_ELIF=57]="TK_ELIF",e[e.TK_WHILE=58]="TK_WHILE",e[e.TK_ENDWHILE=59]="TK_ENDWHILE",e[e.TK_FOR=60]="TK_FOR",e[e.TK_ENDFOR=61]="TK_ENDFOR",e[e.TK_FUNC=62]="TK_FUNC",e[e.TK_LABEL=63]="TK_LABEL",e[e.TK_ENDFUNC=64]="TK_ENDFUNC",e[e.TK_TRY=65]="TK_TRY",e[e.TK_CATCH=66]="TK_CATCH",e[e.TK_SWITCH=67]="TK_SWITCH",e[e.TK_CASE=68]="TK_CASE",e[e.TK_DEFAULT=69]="TK_DEFAULT",e[e.TK_ELLIP=70]="TK_ELLIP",e[e.TK_RETURN=71]="TK_RETURN",e[e.TK_BREAK=72]="TK_BREAK",e[e.TK_CONTINUE=73]="TK_CONTINUE",e[e.TK_LOCAL=74]="TK_LOCAL",e[e.TK_ARROW=75]="TK_ARROW",e[e.TK_TRUE=76]="TK_TRUE",e[e.TK_FALSE=77]="TK_FALSE",e[e.TK_NUMBER=78]="TK_NUMBER",e[e.TK_DOUBLE=79]="TK_DOUBLE",e[e.TK_STRING=80]="TK_STRING",e[e.TK_REGEXP=81]="TK_REGEXP",e[e.TK_NULL=82]="TK_NULL",e[e.TK_THIS=83]="TK_THIS",e[e.TK_DELETE=84]="TK_DELETE",e[e.TK_CONST=85]="TK_CONST",e[e.TK_QLBRACK=86]="TK_QLBRACK",e[e.TK_QLPAREN=87]="TK_QLPAREN",e[e.TK_QDOT=88]="TK_QDOT",e[e.TK_ASEXP=89]="TK_ASEXP",e[e.TK_ASAND=90]="TK_ASAND",e[e.TK_ASOR=91]="TK_ASOR",e[e.TK_ASNULLISH=92]="TK_ASNULLISH",e[e.TK_NULLISH=93]="TK_NULLISH",e[e.TK_PLACEH=94]="TK_PLACEH",e[e.TK_EXPORT=95]="TK_EXPORT",e[e.TK_IMPORT=96]="TK_IMPORT",e[e.TK_FROM=97]="TK_FROM",e[e.TK_TEMPLATE=98]="TK_TEMPLATE",e[e.TK_COMMENT=99]="TK_COMMENT",e[e.TK_NEWLINE=100]="TK_NEWLINE",e[e.TK_LET=101]="TK_LET",e[e.TK_EOF=102]="TK_EOF",e[e.TK_ERROR=103]="TK_ERROR",e[e.TK_UNKNOWN=104]="TK_UNKNOWN"}(l||(l={}));const d={if:l.TK_IF,else:l.TK_ELSE,elif:l.TK_ELIF,endif:l.TK_ENDIF,while:l.TK_WHILE,endwhile:l.TK_ENDWHILE,for:l.TK_FOR,endfor:l.TK_ENDFOR,in:l.TK_IN,function:l.TK_FUNC,endfunction:l.TK_ENDFUNC,return:l.TK_RETURN,break:l.TK_BREAK,continue:l.TK_CONTINUE,let:l.TK_LOCAL,const:l.TK_CONST,true:l.TK_TRUE,false:l.TK_FALSE,null:l.TK_NULL,this:l.TK_THIS,delete:l.TK_DELETE,try:l.TK_TRY,catch:l.TK_CATCH,switch:l.TK_SWITCH,case:l.TK_CASE,default:l.TK_DEFAULT,export:l.TK_EXPORT,import:l.TK_IMPORT,from:l.TK_FROM},m={"{{":l.TK_LEXP,"}}":l.TK_REXP,"{%":l.TK_LSTM,"%}":l.TK_RSTM,",":l.TK_COMMA,"=":l.TK_ASSIGN,"+=":l.TK_ASADD,"-=":l.TK_ASSUB,"*=":l.TK_ASMUL,"/=":l.TK_ASDIV,"%=":l.TK_ASMOD,"<<=":l.TK_ASLEFT,">>=":l.TK_ASRIGHT,"&=":l.TK_ASBAND,"^=":l.TK_ASBXOR,"|=":l.TK_ASBOR,"**=":l.TK_ASEXP,"&&=":l.TK_ASAND,"||=":l.TK_ASOR,"??=":l.TK_ASNULLISH,"?":l.TK_QMARK,":":l.TK_COLON,"||":l.TK_OR,"&&":l.TK_AND,"|":l.TK_BOR,"^":l.TK_BXOR,"&":l.TK_BAND,"===":l.TK_EQS,"!==":l.TK_NES,"==":l.TK_EQ,"!=":l.TK_NE,"<":l.TK_LT,"<=":l.TK_LE,">":l.TK_GT,">=":l.TK_GE,"<<":l.TK_LSHIFT,">>":l.TK_RSHIFT,"+":l.TK_ADD,"-":l.TK_SUB,"*":l.TK_MUL,"/":l.TK_DIV,"%":l.TK_MOD,"**":l.TK_EXP,"!":l.TK_NOT,"~":l.TK_COMPL,"++":l.TK_INC,"--":l.TK_DEC,".":l.TK_DOT,"[":l.TK_LBRACK,"]":l.TK_RBRACK,"(":l.TK_LPAREN,")":l.TK_RPAREN,"{":l.TK_LBRACE,"}":l.TK_RBRACE,";":l.TK_SCOL,"...":l.TK_ELLIP,"=>":l.TK_ARROW,"?.[":l.TK_QLBRACK,"?.(":l.TK_QLPAREN,"?.":l.TK_QDOT,"??":l.TK_NULLISH,"${":l.TK_PLACEH};function h(e){return e in d}function f(e){return/[a-zA-Z0-9_$]/.test(e)}function g(e){return/[0-9]/.test(e)}function y(e){return/[0-9a-fA-F]/.test(e)}function T(e){return/[01]/.test(e)}function _(e){return/[ \t\r\n\f\v]/.test(e)}function N(e){return"\n"===e||"\r"===e}var R;!function(e){e[e.UC_LEX_IDENTIFY_BLOCK=0]="UC_LEX_IDENTIFY_BLOCK",e[e.UC_LEX_BLOCK_EXPRESSION_EMIT_TAG=1]="UC_LEX_BLOCK_EXPRESSION_EMIT_TAG",e[e.UC_LEX_BLOCK_STATEMENT_EMIT_TAG=2]="UC_LEX_BLOCK_STATEMENT_EMIT_TAG",e[e.UC_LEX_BLOCK_COMMENT=3]="UC_LEX_BLOCK_COMMENT",e[e.UC_LEX_IDENTIFY_TOKEN=4]="UC_LEX_IDENTIFY_TOKEN",e[e.UC_LEX_PLACEHOLDER_START=5]="UC_LEX_PLACEHOLDER_START",e[e.UC_LEX_PLACEHOLDER_END=6]="UC_LEX_PLACEHOLDER_END",e[e.UC_LEX_EOF=7]="UC_LEX_EOF"}(R||(R={}));class E{state=R.UC_LEX_IDENTIFY_BLOCK;source;pos=0;line=1;column=1;noRegexp=!1;noKeyword=!1;lastOffset=0;buffer="";errors=[];templates=[];eofEmitted=!1;constructor(e,t){this.source=e,t?.rawMode&&(this.state=R.UC_LEX_IDENTIFY_TOKEN)}comments=[];tokenize(){const e=[];let t;for(;null!==(t=this.nextToken());){if(t.type===l.TK_EOF){e.push(t);break}t.type===l.TK_COMMENT?this.comments.push(t):e.push(t)}return e}nextToken(){switch(this.state){case R.UC_LEX_IDENTIFY_BLOCK:return this.identifyBlock();case R.UC_LEX_BLOCK_EXPRESSION_EMIT_TAG:return this.blockExpressionEmitTag();case R.UC_LEX_BLOCK_STATEMENT_EMIT_TAG:return this.blockStatementEmitTag();case R.UC_LEX_BLOCK_COMMENT:return this.blockComment();case R.UC_LEX_IDENTIFY_TOKEN:return this.identifyToken();case R.UC_LEX_PLACEHOLDER_START:return this.placeholderStart();case R.UC_LEX_PLACEHOLDER_END:return this.placeholderEnd();case R.UC_LEX_EOF:return this.eofEmitted?null:(this.eofEmitted=!0,this.emitToken(l.TK_EOF));default:return null}}identifyBlock(){if(this.pos>=this.source.length)return this.state=R.UC_LEX_EOF,this.emitBuffer(l.TK_TEXT);const e=this.peekChar();if("{"===e){const e=this.peekChar(1);if("{"===e){const e=this.emitBuffer(l.TK_TEXT);return this.state=R.UC_LEX_BLOCK_EXPRESSION_EMIT_TAG,e}if("%"===e){const e=this.emitBuffer(l.TK_TEXT);return this.state=R.UC_LEX_BLOCK_STATEMENT_EMIT_TAG,e}if("#"===e){const e=this.emitBuffer(l.TK_TEXT);return this.state=R.UC_LEX_BLOCK_COMMENT,e}}return this.buffer+=this.nextChar(),this.updatePosition(e),this.identifyBlock()}blockExpressionEmitTag(){return this.nextChar(),this.nextChar(),this.state=R.UC_LEX_IDENTIFY_TOKEN,this.emitToken(l.TK_LEXP)}blockStatementEmitTag(){return this.nextChar(),this.nextChar(),this.state=R.UC_LEX_IDENTIFY_TOKEN,this.emitToken(l.TK_LSTM)}blockComment(){for(this.nextChar(),this.nextChar();this.pos<this.source.length;){const e=this.peekChar();if("#"===e&&"}"===this.peekChar(1)){this.nextChar(),this.nextChar();break}this.nextChar(),this.updatePosition(e)}return this.state=R.UC_LEX_IDENTIFY_BLOCK,this.blockComment()}identifyToken(){if(1===this.line&&1===this.column&&"#"===this.peekChar()&&"!"===this.peekChar(1))return this.parseShebang();if(this.skipWhitespace(),this.pos>=this.source.length)return this.state=R.UC_LEX_EOF,this.emitToken(l.TK_EOF);const e=this.peekChar();if("}"===e&&"}"===this.peekChar(1))return this.nextChar(),this.nextChar(),this.state=R.UC_LEX_IDENTIFY_BLOCK,this.emitToken(l.TK_REXP);if("%"===e&&"}"===this.peekChar(1))return this.nextChar(),this.nextChar(),this.state=R.UC_LEX_IDENTIFY_BLOCK,this.emitToken(l.TK_RSTM);if("$"===e&&"{"===this.peekChar(1))return this.nextChar(),this.nextChar(),this.state=R.UC_LEX_PLACEHOLDER_START,this.nextToken();if(g(e))return this.parseNumber();if('"'===e||"'"===e)return this.parseString(e);if("`"===e)return this.parseTemplateLiteral();if("/"===e&&"/"===this.peekChar(1))return this.parseLineComment();if("/"===e&&"*"===this.peekChar(1))return this.parseBlockComment();if("/"===e&&!this.noRegexp){const e=this.peekChar(1);if(""===e||N(e)){const e=this.pos;return this.nextChar(),this.emitToken(l.TK_ERROR,"Unexpected token '/'. Did you mean to use a comment '//'?",e)}const t=this.source.substring(this.pos+1);if(/^\s*\/\*/.test(t)){const e=this.pos;return this.nextChar(),this.emitToken(l.TK_ERROR,"Unexpected token '/' before block comment. Did you mean to use a comment '//'?",e)}const n=new RegExp(`^\\s*(${["export","import","function","let","const","if","while","for","return","break","continue","try","switch","class"].join("|")})\\b`),r=t.match(n);if(r){const e=this.pos;return this.nextChar(),this.emitToken(l.TK_ERROR,`Unexpected token '/' before '${r[1]}'. Did you mean to use a comment '//'?`,e)}const i=/^\s*$/m,o=t.indexOf("\n"),s=-1===o?t:t.substring(0,o);if(i.test(s)){const e=this.pos;return this.nextChar(),this.emitToken(l.TK_ERROR,"Unexpected token '/'. Did you mean to use a comment '//'?",e)}return this.parseRegex()}if(/[a-zA-Z_$]/.test(e))return this.parseIdentifier();const t=this.parseOperator();if(t){if(this.templates.length>0)if(t.type===l.TK_LBRACE){const e=this.templates.length-1;this.templates[e]=(this.templates[e]??0)+1}else if(t.type===l.TK_RBRACE){const e=this.templates.length-1,t=this.templates[e]??0;0===t?(this.templates.pop(),this.state=R.UC_LEX_PLACEHOLDER_END):this.templates[e]=t-1}return t}return this.nextChar(),this.emitToken(l.TK_ERROR,`Unexpected character: ${e}`)}parseNumber(){const e=this.pos;let t="",n=!1;if("0"===this.peekChar()&&("x"===this.peekChar(1)||"X"===this.peekChar(1))){for(t+=this.nextChar(),t+=this.nextChar();y(this.peekChar());)t+=this.nextChar();return this.emitToken(l.TK_NUMBER,parseInt(t,16),e)}if("0"===this.peekChar()&&("b"===this.peekChar(1)||"B"===this.peekChar(1))){for(t+=this.nextChar(),t+=this.nextChar();T(this.peekChar());)t+=this.nextChar();return this.emitToken(l.TK_NUMBER,parseInt(t,2),e)}if("0"===this.peekChar()&&("o"===this.peekChar(1)||"O"===this.peekChar(1))){for(t+=this.nextChar(),t+=this.nextChar();g(this.peekChar())&&parseInt(this.peekChar())<8;)t+=this.nextChar();return this.emitToken(l.TK_NUMBER,parseInt(t,8),e)}for(;g(this.peekChar());)t+=this.nextChar();if("."===this.peekChar())for(n=!0,t+=this.nextChar();g(this.peekChar());)t+=this.nextChar();if("e"===this.peekChar()||"E"===this.peekChar())for(n=!0,t+=this.nextChar(),"+"!==this.peekChar()&&"-"!==this.peekChar()||(t+=this.nextChar());g(this.peekChar());)t+=this.nextChar();const r=n?parseFloat(t):parseInt(t,10);return this.emitToken(n?l.TK_DOUBLE:l.TK_NUMBER,r,e)}parseString(e){const t=this.pos;let n="";for(this.nextChar();this.pos<this.source.length;){const r=this.peekChar();if(r===e)return this.nextChar(),this.emitToken(l.TK_STRING,n,t);if("\\"===r){this.nextChar();const e=this.nextChar();switch(e){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case'"':n+='"';break;case"'":n+="'";break;default:n+=e}}else n+=this.nextChar()}return this.emitToken(l.TK_ERROR,"Unterminated string",t)}parseTemplateLiteral(){const e=this.pos;let t="";for(this.nextChar();this.pos<this.source.length;){const n=this.peekChar();if("`"===n)return this.nextChar(),this.emitToken(l.TK_TEMPLATE,t,e);if("\\"===n){this.nextChar();const e=this.nextChar();switch(e){case"n":t+="\n";break;case"t":t+="\t";break;case"r":t+="\r";break;case"\\":t+="\\";break;case"`":t+="`";break;case"$":t+="$";break;default:t+=e}}else{if("$"===n&&"{"===this.peekChar(1))return this.emitToken(l.TK_TEMPLATE,t,e);t+=this.nextChar()}}return this.emitToken(l.TK_ERROR,"Unterminated template literal",e)}parseRegex(){const e=this.pos;let t="",n=!1;for(this.nextChar(),t+="/";this.pos<this.source.length;){const r=this.peekChar();if("/"===r&&!n){t+=this.nextChar();const n=new Set(["g","i","s"]);for(;this.pos<this.source.length&&/[a-zA-Z]/.test(this.peekChar());){const e=this.peekChar();if(!n.has(e)){const t=this.pos;return this.nextChar(),this.emitToken(l.TK_ERROR,`Unsupported regex flag '${e}'. Supported flags are: g, i, s`,t)}t+=this.nextChar()}return this.emitToken(l.TK_REGEXP,t,e)}if(N(r))return this.pos=e+1,this.emitToken(l.TK_ERROR,"Unexpected token '/'. Did you mean to use a comment '//'?",e);"\\"===r?(t+=this.nextChar(),this.pos<this.source.length&&(t+=this.nextChar())):("["!==r||n?"]"===r&&n&&(n=!1):n=!0,t+=this.nextChar())}return this.emitToken(l.TK_ERROR,"Unterminated regex",e)}parseLineComment(){const e=this.pos;let t="";for(this.nextChar(),this.nextChar();this.pos<this.source.length&&!N(this.peekChar());)t+=this.nextChar();return this.emitToken(l.TK_COMMENT,t,e)}parseBlockComment(){const e=this.pos;let t="";for(this.nextChar(),this.nextChar();this.pos<this.source.length-1;){if("*"===this.peekChar()&&"/"===this.peekChar(1))return this.nextChar(),this.nextChar(),this.emitToken(l.TK_COMMENT,t,e);const n=this.nextChar();t+=n,this.updatePosition(n)}return this.emitToken(l.TK_ERROR,"Unterminated comment",e)}parseShebang(){const e=this.pos;for(;this.pos<this.source.length&&!N(this.peekChar());)this.nextChar();return this.pos<this.source.length&&N(this.peekChar())&&this.updatePosition(this.nextChar()),this.emitToken(l.TK_COMMENT,"shebang",e)}parseIdentifier(){const e=this.pos;let t="";for(;this.pos<this.source.length&&f(this.peekChar());)t+=this.nextChar();if(!this.noKeyword&&h(t)){const n=d[t];if(n)return this.emitToken(n,t,e)}return this.emitToken(l.TK_LABEL,t,e)}parseOperator(){const e=this.pos;for(let t=3;t>=1;t--){const n=this.source.substring(this.pos,this.pos+t);if(n in m){for(let e=0;e<t;e++)this.nextChar();const r=m[n];if(r)return this.emitToken(r,n,e)}}return null}placeholderStart(){this.state=R.UC_LEX_IDENTIFY_TOKEN,this.templates.push(0);const e=this.pos-2;return{type:l.TK_PLACEH,pos:e,end:this.pos,value:"${",line:this.line,column:this.column}}placeholderEnd(){return this.state=R.UC_LEX_IDENTIFY_TOKEN,this.continueTemplateLiteral()}continueTemplateLiteral(){const e=this.pos;let t="";for(;this.pos<this.source.length;){const n=this.peekChar();if("`"===n)return this.nextChar(),this.state=R.UC_LEX_IDENTIFY_TOKEN,this.emitToken(l.TK_TEMPLATE,t,e);if("\\"===n){this.nextChar();const e=this.nextChar();switch(e){case"n":t+="\n";break;case"t":t+="\t";break;case"r":t+="\r";break;case"\\":t+="\\";break;case"`":t+="`";break;case"$":t+="$";break;default:t+=e}}else{if("$"===n&&"{"===this.peekChar(1))return this.emitToken(l.TK_TEMPLATE,t,e);t+=this.nextChar()}}return this.emitToken(l.TK_ERROR,"Unterminated template literal",e)}skipWhitespace(){for(;this.pos<this.source.length&&_(this.peekChar());){const e=this.nextChar();this.updatePosition(e)}}peekChar(e=0){const t=this.pos+e;return t<this.source.length&&this.source[t]||""}nextChar(){return this.pos>=this.source.length?"":this.source[this.pos++]||""}updatePosition(e){N(e)?(this.line++,this.column=1):this.column++}emitToken(e,t,n){const r=n??this.pos,i=this.pos;return this.updateNoRegexpFlag(e),this.updateNoKeywordFlag(e),{type:e,value:t||"",pos:r,end:i,line:this.line,column:this.column}}updateNoRegexpFlag(e){e===l.TK_LABEL||e===l.TK_NUMBER||e===l.TK_DOUBLE||e===l.TK_STRING||e===l.TK_RPAREN||e===l.TK_RBRACK||e===l.TK_RBRACE||e===l.TK_TRUE||e===l.TK_FALSE||e===l.TK_NULL||e===l.TK_THIS||e===l.TK_INC||e===l.TK_DEC?this.noRegexp=!0:e===l.TK_LPAREN||e===l.TK_LBRACK||e===l.TK_COMMA||e===l.TK_ASSIGN||e===l.TK_EQ||e===l.TK_NE||e===l.TK_LT||e===l.TK_LE||e===l.TK_GT||e===l.TK_GE||e===l.TK_AND||e===l.TK_OR||e===l.TK_NOT||e===l.TK_BAND||e===l.TK_BOR||e===l.TK_BXOR||e===l.TK_ADD||e===l.TK_SUB||e===l.TK_MUL||e===l.TK_MOD||e===l.TK_RETURN||e===l.TK_IF||e===l.TK_WHILE||e===l.TK_FOR||e===l.TK_CASE||e===l.TK_COLON||e===l.TK_QMARK?this.noRegexp=!1:e!==l.TK_LBRACE&&e!==l.TK_SCOL||(this.noRegexp=!1)}updateNoKeywordFlag(e){e===l.TK_DOT?this.noKeyword=!0:(e===l.TK_LABEL&&this.noKeyword||this.noKeyword&&e!==l.TK_LABEL)&&(this.noKeyword=!1)}emitBuffer(e,t){if(0===this.buffer.length&&e===l.TK_TEXT)return null;let n=this.buffer;if(t)for(;n.length>0&&t.includes(n[n.length-1]||"");)n=n.slice(0,-1);const r=this.emitToken(e,n||"",this.lastOffset);return this.buffer="",r}getErrors(){return this.errors}}const b=new Map([["print","Print any of the given values to stdout.\n\n**Parameters:**\n- `...values` - Arbitrary values to print\n\n**Returns:** `number` - The amount of bytes written"],["printf","Print formatted string to stdout.\n\n**Parameters:**\n- `format` - Format string\n- `...args` - Arguments for formatting\n\n**Returns:** `number` - The amount of bytes written"],["sprintf","Return formatted string.\n\n**Parameters:**\n- `format` - Format string\n- `...args` - Arguments for formatting\n\n**Returns:** `string` - The formatted string"],["length",'Determine the length of the given object, array or string.\n\n**Parameters:**\n- `x` - The input object, array, or string\n\n**Returns:** `number|null` - The length of the input\n\n**Example:**\n```ucode\nlength("test") // 4\nlength([true, false, null, 123, "test"]) // 5\n```'],["substr","Extract substring from string.\n\n**Parameters:**\n- `string` - The input string\n- `start` - Start position\n- `length` - Length of substring (optional)\n\n**Returns:** `string` - The extracted substring"],["split","Split string into array of substrings.\n\n**Parameters:**\n- `string` - The input string\n- `separator` - String or regex to split on\n- `limit` - Maximum number of splits (optional)\n\n**Returns:** `array | null` - Array of substrings, or null if separator is missing or string is not a string"],["join","Join array elements into string.\n\n**Parameters:**\n- `separator` - String to join with\n- `array` - Array to join\n\n**Returns:** `string` - The joined string\n\n**Note:** Parameter order is `join(separator, array)` - different from JavaScript!"],["trim","Remove whitespace from both ends of string.\n\n**Parameters:**\n- `string` - The input string\n\n**Returns:** `string` - The trimmed string"],["ltrim","Remove whitespace from left end of string.\n\n**Parameters:**\n- `string` - The input string\n\n**Returns:** `string` - The left-trimmed string"],["rtrim","Remove whitespace from right end of string.\n\n**Parameters:**\n- `string` - The input string\n\n**Returns:** `string` - The right-trimmed string"],["chr","Convert ASCII code to character.\n\n**Parameters:**\n- `code` - ASCII code number\n\n**Returns:** `string` - The character"],["ord","Get ASCII code of character.\n\n**Parameters:**\n- `char` - The character\n\n**Returns:** `number` - The ASCII code"],["uc","Convert string to uppercase.\n\n**Parameters:**\n- `string` - The string to convert\n\n**Returns:** `string` - Uppercase string"],["lc","Convert string to lowercase.\n\n**Parameters:**\n- `string` - The string to convert\n\n**Returns:** `string` - Lowercase string"],["type",'Get type of value.\n\n**Parameters:**\n- `value` - The value to check\n\n**Returns:** `string` - Type name ("object", "array", "string", "number", "boolean", "function", "null")'],["keys","Get array of object keys.\n\n**Parameters:**\n- `object` - The object\n\n**Returns:** `array|null` - Array of property names, or null if not an object"],["values","Get array of object values.\n\n**Parameters:**\n- `object` - The object\n\n**Returns:** `array|null` - Array of property values, or null if not an object"],["push","Add elements to end of array.\n\n**Parameters:**\n- `array` - The array\n- `...values` - Values to add\n\n**Returns:** `number` - New length of array"],["pop","Remove and return last element from array.\n\n**Parameters:**\n- `array` - The array\n\n**Returns:** `*` - The removed element"],["shift","Remove and return first element from array.\n\n**Parameters:**\n- `array` - The array\n\n**Returns:** `*` - The removed element"],["unshift","Add elements to beginning of array.\n\n**Parameters:**\n- `array` - The array\n- `...values` - Values to add\n\n**Returns:** `number` - New length of array"],["filter",'**filter(array, callback)** - Filter array elements using a predicate function.\n\n**Parameters:**\n- `array` (array): The array to filter\n- `callback` (function): Function called for each element. Should return truthy to keep element. Receives (value, index, array)\n\n**Returns:** `array | null` - New filtered array, or null if first argument is not an array\n\n**Example:**\n```ucode\n// Filter even numbers\nlet evens = filter([1, 2, 3, 4, 5], n => n % 2 == 0);\n// Result: [2, 4]\n\n// Filter with index\nlet result = filter(["a", "b", "c"], (val, idx) => idx > 0);\n// Result: ["b", "c"]\n```'],["index","Find index of substring or element.\n\n**Parameters:**\n- `haystack` - String or array to search in\n- `needle` - Value to search for\n\n**Returns:** `number` - Index of first occurrence, or -1 if not found\n\n**Note:** Parameter order is `index(haystack, needle)`"],["require","Load and return module.\n\n**Parameters:**\n- `module` - Module name or path\n\n**Returns:** `*` - The loaded module"],["include","Include and execute a ucode file.\n\n**Parameters:**\n- `path` (string) - Path to file\n- `scope` (object, optional) - Variables to make available in included file\n\n**Returns:** `*` - Result of included file"],["json","Parse JSON string or stringify value.\n\n**Parameters:**\n- `value` - String to parse or value to stringify\n\n**Returns:** `*` - Parsed object or JSON string"],["match","Match string against regex.\n\n**Parameters:**\n- `string` - The string to match\n- `regex` - Regular expression\n\n**Returns:** `array|null` - Match results or null"],["replace","Replace occurrences in string.\n\n**Parameters:**\n- `string` - The string\n- `search` - String or regex to search for\n- `replacement` - Replacement string\n\n**Returns:** `string` - String with replacements"],["system",'**system(command, timeout?)** - Execute shell command or program.\n\n**Parameters:**\n- `command` (string | array): Command to execute. String passed to `/bin/sh -c`, array used as execv() argument vector\n- `timeout` (number, optional): Timeout in milliseconds. Program terminated by SIGKILL if exceeded\n\n**Returns:** `number` - Exit code (positive) or negative signal number if terminated by signal\n\n**Examples:**\n```ucode\n// Execute through shell\nsystem("echo Hello && exit 3"); // Returns 3\n\n// Execute argument vector\nsystem(["/usr/bin/date", "+%s"]); // Returns 0\n\n// With timeout\nsystem("sleep 3", 1000); // Returns -9 (SIGKILL)\n```'],["time","Get current Unix timestamp.\n\n**Returns:** `number` - Current time in seconds since epoch"],["sleep","Pause execution for specified seconds.\n\n**Parameters:**\n- `seconds` - Number of seconds to sleep\n\n**Returns:** `null`"],["localtime","Convert timestamp to local time components.\n\n**Parameters:**\n- `timestamp` - Unix timestamp (optional, defaults to current time)\n\n**Returns:** `object` - Time components: [year, month, day, hour, minute, second, weekday, yearday]"],["gmtime","Convert timestamp to UTC time components.\n\n**Parameters:**\n- `timestamp` - Unix timestamp (optional, defaults to current time)\n\n**Returns:** `object` - Time components: [year, month, day, hour, minute, second, weekday, yearday]"],["timelocal","Convert local time components to timestamp.\n\n**Parameters:**\n- `timeObject` - Object of time components [year, month, day, hour, minute, second]\n\n**Returns:** `number` - Unix timestamp"],["timegm","Convert UTC time components to timestamp.\n\n**Parameters:**\n- `timeObject` - Object of time components [year, month, day, hour, minute, second]\n\n**Returns:** `number` - Unix timestamp"],["min","Find minimum value from numbers.\n\n**Parameters:**\n- `...numbers` - Numbers to compare\n\n**Returns:** `number` - The smallest number"],["max","Find maximum value from numbers.\n\n**Parameters:**\n- `...numbers` - Numbers to compare\n\n**Returns:** `number` - The largest number"],["uniq","Remove duplicate values from array.\n\n**Parameters:**\n- `array` - The input array\n\n**Returns:** `array` - Array with unique values"],["b64enc","Encode string to Base64.\n\n**Parameters:**\n- `string` - String to encode\n\n**Returns:** `string` - Base64 encoded string"],["b64dec","Decode Base64 string.\n\n**Parameters:**\n- `string` - Base64 string to decode\n\n**Returns:** `string` - Decoded string"],["hexenc","Encode string to hexadecimal.\n\n**Parameters:**\n- `string` - String to encode\n\n**Returns:** `string` - Hexadecimal encoded string"],["hexdec",'Decode hexadecimal string.\n\n**Parameters:**\n- `hexstring` (string) - Hexadecimal string to decode\n- `skipchars` (string) *optional* - Characters to skip during decoding (default: " \\t\n")\n\n**Returns:** `string` - Decoded string, or null if invalid\n\n**Examples:**\n```ucode\nhexdec("48656c6c6f20776f726c64210a"); // "Hello world!\n"\nhexdec("44:55:66:77:33:44", ":"); // "DUfw3D"\n```'],["hex",'Parse hexadecimal string to integer.\n\n**Parameters:**\n- `hexstring` - Hexadecimal string to parse (e.g., "0xff")\n\n**Returns:** `integer` - Parsed integer value'],["uchr","Convert Unicode code point to character.\n\n**Parameters:**\n- `code` - Unicode code point\n\n**Returns:** `string` - The Unicode character"],["iptoarr",'Convert IP address string to array of components.\n\n**Parameters:**\n- `ipString` - IP address string (IPv4 or IPv6)\n\n**Returns:** `array` - Array of IP address components\n\n**Example:**\n```ucode\niptoarr("192.168.1.1") // [192, 168, 1, 1]\n```'],["arrtoip",'Convert array of IP components to IP address string.\n\n**Parameters:**\n- `ipArray` - Array of IP address components\n\n**Returns:** `string` - IP address string\n\n**Example:**\n```ucode\narrtoip([192, 168, 1, 1]) // "192.168.1.1"\n```'],["int",'Convert value to integer.\n\n**Parameters:**\n- `value` - String or number to convert to integer\n\n**Returns:** `number` - Integer value\n\n**Example:**\n```ucode\nint("123") // 123\nint(45.67) // 45\nint("-89") // -89\n```'],["loadstring",'Load and execute uCode from string.\n\n**Parameters:**\n- `code` - String containing uCode source code\n\n**Returns:** `*` - Result of executed code\n\n**Example:**\n```ucode\nloadstring("return 42")() // 42\n```'],["loadfile",'Load and execute uCode from file.\n\n**Parameters:**\n- `path` - Path to uCode file\n\n**Returns:** `*` - Result of executed file\n\n**Example:**\n```ucode\nloadfile("script.uc")()\n```'],["wildcard",'Match the given **subject** string against a shell-style wildcard (glob) **pattern**. This is pure string matching — it never touches the filesystem.\n\n**Parameters**\n- `subject` — String to test (other types are coerced to string)\n- `pattern` — Glob pattern. Supports `*`, `?`, bracket sets `[abc]`, ranges `[a-z]`, negation `[!abc]`/`[^abc]`, and POSIX character classes inside bracket sets (e.g. `[[:alpha:]]`).\n- `nocase` (boolean, optional) — If truthy, match case-insensitively.\n\n**Returns**\n- `boolean` — `true` if the pattern matches the subject; otherwise `false`.\n\n**Supported syntax (quick reference)**\n- `*` matches any sequence (including empty)\n- `?` matches any single character\n- `[abc]` matches one of the listed characters; `[-ab]` or `[ab-]` include a literal `-`\n- `[a-z]` matches a range; use `[A-Za-z]` (not `[A-z]`) to avoid punctuation\n- `[!set]` or `[^set]` negates the set\n- **POSIX classes** (must be inside `[...]`): `[[:alpha:]]`, `[[:alnum:]]`, `[[:digit:]]`, `[[:space:]]`, `[[:upper:]]`, `[[:lower:]]`, `[[:punct:]]`, `[[:xdigit:]]`, `[[:blank:]]`, `[[:graph:]]`, `[[:print:]]`, `[[:cntrl:]]`\n- `\\` escapes the next character (e.g., match a literal `[` with `\\[`)\n\n**Examples**\n```ucode\nwildcard("document.txt", "*.txt") // true\nwildcard("test1", "test?") // true\nwildcard("5files", "[0-9]*") // true (range)\nwildcard("FILE.TXT", "*.txt", true) // true (case-insensitive)\n\n// POSIX character classes (must be inside brackets)\nwildcard("hello", "[[:alpha:]]*") // true (letters)\nwildcard("var_42", "var_[[:digit:]][[:digit:]]") // true (two digits)\nwildcard("_tmp", "[![:alnum:]]*") // true (first char not alnum)\nwildcard("line\\tbreak", "*[[:space:]]*") // true (tab/newline/space)\n\n// Escaping special characters\nwildcard("file[1].txt", "file\\\\[1\\\\].txt") // true (literal square brackets)\n\n// Safer alpha range\nwildcard("Z", "[A-Za-z]") // true\n```\n**Notes**\n- `*` and `?` are **literals** inside bracket sets (e.g. `[a*?]`).\n- Avoid `[A-z]`; it spans punctuation between `Z` and `a`. Use `[A-Za-z]` instead.\n'],["regexp",'Compile a regular expression from pattern string.\n\n**Parameters:**\n- `pattern` - Regular expression pattern string\n- `flags` - Optional flags string ("i", "g", "s")\n\n**Returns:** `regexp` - Compiled regular expression object\n\n**Example:**\n```ucode\nlet re = regexp("[0-9]+", "g");\nmatch("test123", re); // ["123"]\n```'],["assert",'Assert that a condition is true, throw exception if false.\n\n**Parameters:**\n- `condition` - Value to test for truthiness\n- `message` - Optional error message string\n\n**Returns:** `*` - The condition value if truthy\n\n**Throws:** Exception if condition is falsy\n\n**Example:**\n```ucode\nassert(x > 0, "x must be positive");\nassert(array.length > 0);\n```'],["call",'Invoke a function with modified context and environment.\n\n**Parameters:**\n- `function` - Function to invoke\n- `thisContext` - Value for "this" context (optional)\n- `environment` - Global environment object (optional)\n- `...args` - Arguments to pass to function\n\n**Returns:** `*` - Result of function call\n\n**Example:**\n```ucode\ncall(myFunction, null, null, arg1, arg2);\n```'],["signal",'Set up signal handlers for Unix signals.\n\n**Parameters:**\n- `signal` - Signal number or name (with/without "SIG" prefix)\n- `handler` - Handler function (optional)\n\n**Returns:** `*` - Previous handler or signal behavior\n\n**Example:**\n```ucode\nsignal(15, function() { print("SIGTERM received"); });\nsignal("SIGINT", exitHandler);\n```'],["clock","**clock([monotonic])** - Reads the current second and microsecond value of the system clock.\n\nBy default, the realtime clock is queried which might skew forwards or backwards due to NTP changes, system sleep modes etc. If a truish value is passed as argument, the monotonic system clock is queried instead, which will return the monotonically increasing time since some arbitrary point in the past (usually the system boot time).\n\nReturns a two element array containing the full seconds as the first element and the nanosecond fraction as the second element.\n\nReturns `null` if a monotonic clock value is requested and the system does not implement this clock type.\n\n**Parameters:**\n- `monotonic` (boolean, optional): Whether to query the monotonic system clock\n\n**Returns:** `number[] | null` - Two element array [seconds, nanoseconds] or null if monotonic clock unavailable\n\n**Example:**\n```ucode\nclock(); // [ 1647954926, 798269464 ]\nclock(true); // [ 474751, 527959975 ]\n```"],["sourcepath","Get the path of the current source file.\n\n**Parameters:**\n- `depth` (number, optional): Stack depth to look up (default: 0)\n- `dironly` (boolean, optional): Return directory name only (default: false)\n\n**Returns:** `string` - Absolute path to source file or directory\n\n**Example:**\n```ucode\nlet currentFile = sourcepath();\nlet parentDir = sourcepath(1, true);\n```"],["gc",'Interact with the mark and sweep garbage collector of the running ucode VM.\n\n**Signature:** `gc(operation?, interval?)`\n\n**Parameters:**\n- `operation` (string): Operation to perform. Default: `collect`.\n- `interval` (integer): Number of objects allocated before collecting garbage.\n\n**Operations:**\n- `collect` - Perform a complete GC cycle. Returns `true`.\n- `start` - (Re-)start periodic GC. Optional integer interval `1..65535`; `0` or omitted uses default `1000`. Returns `true` if GC was previously stopped and is now started or if the interval changed; otherwise `false`.\n- `stop` - Stop periodic GC. Returns `true` if it was running; otherwise `false`.\n- `count` - Count active complex object references. Returns the number.\n\n**Default:** If `operation` is omitted, behaves like `collect`.\n\n**Notes:** Extra arguments are ignored. Invalid arguments return `null`.\n\n**Examples:**\n```ucode\ngc(); // true\ngc("start"); // true\ngc("start", 500); // true\ngc("stop"); // true\nn = gc("count"); // e.g. 42\n```\n'],["die",'Terminate script execution with optional message.\n\n**Parameters:**\n- `message` (string, optional): Error message to display before termination\n\n**Returns:** Never returns (terminates execution)\n\n**Example:**\n```ucode\nif (critical_error) {\n die("Critical error occurred");\n}\n```'],["exists",'Check if a variable or property exists.\n\n**Parameters:**\n- `object` (object): Object to check\n- `property` (string): Property name to check for\n\n**Returns:** `boolean` - True if property exists, false otherwise\n\n**Example:**\n```ucode\nlet obj = { name: "test", value: null };\nexists(obj, "name"); // true\nexists(obj, "missing"); // false\n```'],["exit","Terminate script execution with exit code.\n\n**Parameters:**\n- `code` (number, optional): Exit code (default: 0)\n\n**Returns:** Never returns (terminates execution)\n\n**Example:**\n```ucode\nif (error_condition) {\n exit(1);\n}\nexit(0); // Success\n```"],["getenv",'Get environment variable value.\n\n**Parameters:**\n- `name` (string): Environment variable name\n\n**Returns:** `string | null` - Environment variable value or null if not found\n\n**Example:**\n```ucode\nlet path = getenv("PATH");\nlet home = getenv("HOME");\nlet missing = getenv("DOES_NOT_EXIST"); // null\n```'],["map",'Transform array elements using callback function.\n\n**Parameters:**\n- `array` (array): The array to transform\n- `callback` (function): Function called for each element. Receives (value, index, array)\n\n**Returns:** `array | null` - New array with transformed elements, or null if first argument is not an array\n\n**Example:**\n```ucode\n// Double all numbers\nlet doubled = map([1, 2, 3, 4], n => n * 2);\n// Result: [2, 4, 6, 8]\n\n// Transform with index\nlet indexed = map(["a", "b", "c"], (val, idx) => `${idx}: ${val}`);\n// Result: ["0: a", "1: b", "2: c"]\n```'],["reverse",'Reverse array or string.\n\n**Parameters:**\n- `value` (array | string): Array or string to reverse\n\n**Returns:** `array | string | null` - Reversed copy, or null if invalid input\n\n**Example:**\n```ucode\nreverse([1, 2, 3, 4]); // [4, 3, 2, 1]\nreverse("hello"); // "olleh"\nreverse(123); // null\n```'],["rindex",'Find last index of substring or element.\n\n**Parameters:**\n- `haystack` - String or array to search in\n- `needle` - Value to search for\n\n**Returns:** `number` - Index of last occurrence, or -1 if not found\n\n**Example:**\n```ucode\nrindex("hello world hello", "hello"); // 12\nrindex([1, 2, 3, 2, 1], 2); // 3\nrindex("test", "missing"); // -1\n```'],["sort",'Sort array elements in place.\n\n**Parameters:**\n- `array` (array): Array to sort\n- `compare` (function, optional): Comparison function\n\n**Returns:** `array | null` - The sorted array, or null if invalid input\n\n**Example:**\n```ucode\n// Sort numbers\nsort([3, 1, 4, 2]); // [1, 2, 3, 4]\n\n// Sort with custom compare\nsort(["apple", "Banana", "cherry"], (a, b) => {\n return lc(a) < lc(b) ? -1 : (lc(a) > lc(b) ? 1 : 0);\n});\n```'],["splice",'Change array contents by adding/removing elements.\n\n**Parameters:**\n- `array` (array): Array to modify\n- `start` (number): Start index\n- `deleteCount` (number, optional): Number of elements to remove\n- `...items` (any, optional): Items to add\n\n**Returns:** `array | null` - Array of removed elements, or null if invalid input\n\n**Example:**\n```ucode\nlet arr = [1, 2, 3, 4, 5];\n// Remove 2 elements starting at index 1\nlet removed = splice(arr, 1, 2); // [2, 3]\n// arr is now [1, 4, 5]\n\n// Insert elements\nsplice(arr, 1, 0, "a", "b"); // []\n// arr is now [1, "a", "b", 4, 5]\n```'],["slice",'Extract section of array or string.\n\n**Parameters:**\n- `value` (array | string): Array or string to slice\n- `start` (number): Start index (inclusive)\n- `end` (number, optional): End index (exclusive)\n\n**Returns:** `array | string | null` - Extracted section, or null if invalid input\n\n**Example:**\n```ucode\nslice([1, 2, 3, 4, 5], 1, 4); // [2, 3, 4]\nslice("hello world", 0, 5); // "hello"\nslice([1, 2, 3], 1); // [2, 3]\n```'],["warn",'Print warning message to stderr.\n\n**Parameters:**\n- `...values` - Values to print as warning\n\n**Returns:** `null`\n\n**Example:**\n```ucode\nwarn("This is a warning message");\nwarn("Warning:", error_code, "occurred");\n```'],["trace",'Print stack trace for debugging.\n\n**Parameters:**\n- `message` (string, optional): Optional message to include\n\n**Returns:** `null`\n\n**Example:**\n```ucode\nfunction problematic_function() {\n trace("Debug trace point");\n // ... rest of function\n}\n```'],["proto","Get or set prototype of object.\n\n**Parameters:**\n- `object` (object): Object to inspect/modify\n- `prototype` (object, optional): New prototype to set\n\n**Returns:** `object | null` - Current/previous prototype, or null if invalid\n\n**Example:**\n```ucode\nlet obj = {};\nlet current_proto = proto(obj); // Get current prototype\nproto(obj, new_prototype); // Set new prototype\n```"],["render",'Render template string with context.\n\n**Parameters:**\n- `template` (string): Template string to render\n- `context` (object, optional): Variables for template substitution\n\n**Returns:** `string | null` - Rendered string, or null on error\n\n**Example:**\n```ucode\nlet template = "Hello {{name}}, you have {{count}} messages";\nlet context = { name: "Alice", count: 5 };\nrender(template, context); // "Hello Alice, you have 5 messages"\n```']]),v=(new Map([["error",'**error()** - Get error information for the last fs operation.\n\n**Returns:** `string|null` - Description of the last error, or null if no error\n\n**Example:**\n```ucode\nunlink("/path/does/not/exist");\nprint(error()); // "No such file or directory"\n```'],["open",'**open(path, mode, perm)** - Open a file and return a file handle.\n\n**Parameters:**\n- `path` (string): Path to the file\n- `mode` (string): Open mode ("r", "w", "a", "r+", "w+", "a+")\n- `perm` (number): File creation permissions (optional, default 0o666)\n\n**Returns:** `object|null` - File handle object or null on error\n\n**Example:**\n```ucode\nlet file = open("/tmp/test.txt", "w");\nif (file) {\n file.write("Hello World");\n file.close();\n}\n```'],["fdopen",'**fdopen(fd, mode)** - Create a file handle from a file descriptor.\n\n**Parameters:**\n- `fd` (number): File descriptor number\n- `mode` (string): Open mode ("r", "w", "a")\n\n**Returns:** `object|null` - File handle object or null on error\n\n**Example:**\n```ucode\nlet stdin = fdopen(0, "r");\n```'],["opendir",'**opendir(path)** - Open a directory for reading.\n\n**Parameters:**\n- `path` (string): Path to the directory\n\n**Returns:** `object|null` - Directory handle object or null on error\n\n**Example:**\n```ucode\nlet dir = opendir("/etc");\nif (dir) {\n let entry;\n while ((entry = dir.read()) !== null) {\n print(entry);\n }\n dir.close();\n}\n```'],["popen",'**popen(command, mode)** - Open a pipe to a command.\n\n**Parameters:**\n- `command` (string): Command to execute\n- `mode` (string): Pipe mode ("r" for reading, "w" for writing)\n\n**Returns:** `object|null` - Process handle object or null on error\n\n**Example:**\n```ucode\nlet proc = popen("ls -la", "r");\nif (proc) {\n let output = proc.read("all");\n let exitCode = proc.close();\n}\n```'],["readlink",'**readlink(path)** - Read the target of a symbolic link.\n\n**Parameters:**\n- `path` (string): Path to the symbolic link\n\n**Returns:** `string|null` - Target path or null on error\n\n**Example:**\n```ucode\nlet target = readlink("/sys/class/net/eth0");\n```'],["stat",'**stat(path)** - Get information about a file or directory.\n\n**Parameters:**\n- `path` (string): Path to the file or directory\n\n**Returns:** `object|null` - Stat object with file information or null on error\n\n**Example:**\n```ucode\nlet info = stat("/etc/passwd");\nif (info) {\n print("Size:", info.size);\n print("Type:", info.type);\n}\n```'],["lstat",'**lstat(path)** - Get information about a file (don\'t follow symlinks).\n\n**Parameters:**\n- `path` (string): Path to the file or directory\n\n**Returns:** `object|null` - Stat object with file information or null on error\n\n**Example:**\n```ucode\nlet info = lstat("/etc/passwd");\n```'],["mkdir",'**mkdir(path, mode)** - Create a new directory.\n\n**Parameters:**\n- `path` (string): Path for the new directory\n- `mode` (number): Directory permissions (optional, default 0o777)\n\n**Returns:** `boolean|null` - true on success, null on error\n\n**Example:**\n```ucode\nif (mkdir("/tmp/newdir", 0o755)) {\n print("Directory created");\n}\n```'],["rmdir",'**rmdir(path)** - Remove a directory.\n\n**Parameters:**\n- `path` (string): Path to the directory to remove\n\n**Returns:** `boolean|null` - true on success, null on error\n\n**Example:**\n```ucode\nif (rmdir("/tmp/olddir")) {\n print("Directory removed");\n}\n```'],["symlink",'**symlink(target, path)** - Create a symbolic link.\n\n**Parameters:**\n- `target` (string): Target of the symbolic link\n- `path` (string): Path for the new symbolic link\n\n**Returns:** `boolean|null` - true on success, null on error\n\n**Example:**\n```ucode\nif (symlink("/target/file", "/path/to/symlink")) {\n print("Symlink created");\n}\n```'],["unlink",'**unlink(path)** - Remove a file.\n\n**Parameters:**\n- `path` (string): Path to the file to remove\n\n**Returns:** `boolean|null` - true on success, null on error\n\n**Example:**\n```ucode\nif (unlink("/tmp/tempfile")) {\n print("File removed");\n}\n```'],["getcwd",'**getcwd()** - Get the current working directory.\n\n**Returns:** `string|null` - Current working directory path or null on error\n\n**Example:**\n```ucode\nlet cwd = getcwd();\nprint("Current directory:", cwd);\n```'],["chdir",'**chdir(path)** - Change the current working directory.\n\n**Parameters:**\n- `path` (string): Path to the new working directory\n\n**Returns:** `boolean|null` - true on success, null on error\n\n**Example:**\n```ucode\nif (chdir("/new/directory")) {\n print("Changed directory");\n}\n```'],["chmod",'**chmod(path, mode)** - Change file permissions.\n\n**Parameters:**\n- `path` (string): Path to the file\n- `mode` (number): New permissions\n\n**Returns:** `boolean|null` - true on success, null on error\n\n**Example:**\n```ucode\nif (chmod("/path/to/file", 0o644)) {\n print("Permissions changed");\n}\n```'],["chown",'**chown(path, uid, gid)** - Change file ownership.\n\n**Parameters:**\n- `path` (string): Path to the file\n- `uid` (number): New user ID\n- `gid` (number): New group ID\n\n**Returns:** `boolean|null` - true on success, null on error\n\n**Example:**\n```ucode\nif (chown("/path/to/file", 1000, 1000)) {\n print("Ownership changed");\n}\n```'],["rename",'**rename(oldpath, newpath)** - Rename or move a file.\n\n**Parameters:**\n- `oldpath` (string): Current path\n- `newpath` (string): New path\n\n**Returns:** `boolean|null` - true on success, null on error\n\n**Example:**\n```ucode\nif (rename("/old/path", "/new/path")) {\n print("File renamed");\n}\n```'],["glob",'**glob(pattern)** - Find pathnames matching a pattern.\n\n**Parameters:**\n- `pattern` (string): Glob pattern to match\n\n**Returns:** `array|null` - Array of matching paths or null on error\n\n**Example:**\n```ucode\nlet files = glob("/tmp/*.txt");\nfor (let file in files) {\n print(file);\n}\n```'],["dirname",'**dirname(path)** - Get the directory part of a path.\n\n**Parameters:**\n- `path` (string): File path\n\n**Returns:** `string|null` - Directory name or null on invalid input\n\n**Example:**\n```ucode\nlet dir = dirname("/path/to/file.txt"); // "/path/to"\n```'],["basename",'**basename(path)** - Get the filename part of a path.\n\n**Parameters:**\n- `path` (string): File path\n\n**Returns:** `string|null` - Base name or null on invalid input\n\n**Example:**\n```ucode\nlet name = basename("/path/to/file.txt"); // "file.txt"\n```'],["lsdir",'**lsdir(path)** - List directory contents.\n\n**Parameters:**\n- `path` (string): Path to the directory\n\n**Returns:** `array|null` - Array of file names or null on error\n\n**Example:**\n```ucode\nlet files = lsdir("/etc");\nfor (let file in files) {\n print(file);\n}\n```'],["mkstemp",'**mkstemp(template)** - Create a temporary file.\n\n**Parameters:**\n- `template` (string): Template for the temporary filename\n\n**Returns:** `object|null` - File handle for temporary file or null on error\n\n**Example:**\n```ucode\nlet tempFile = mkstemp("/tmp/tempXXXXXX");\nif (tempFile) {\n tempFile.write("temporary data");\n tempFile.close();\n}\n```'],["access",'**access(path, mode)** - Check file accessibility.\n\n**Parameters:**\n- `path` (string): Path to the file\n- `mode` (string): Access mode to check ("r", "w", "x", "f")\n\n**Returns:** `boolean|null` - true if accessible, false if not, null on error\n\n**Example:**\n```ucode\nif (access("/etc/passwd", "r")) {\n print("File is readable");\n}\n```'],["readfile",'**readfile(path)** - Read the contents of a file.\n\n**Parameters:**\n- `path` (string): Path to the file to read\n\n**Returns:** `string|null` - File contents or null on error\n\n**Example:**\n```ucode\nlet content = readfile("/etc/hostname");\nif (content) {\n print("Hostname:", trim(content));\n}\n```'],["writefile",'**writefile(path, data)** - Write data to a file.\n\n**Parameters:**\n- `path` (string): Path to the file\n- `data` (string): Data to write\n\n**Returns:** `number|null` - Number of bytes written or null on error\n\n**Example:**\n```ucode\nlet bytes = writefile("/tmp/output.txt", "Hello World!");\nif (bytes) {\n print("Wrote", bytes, "bytes");\n}\n```'],["realpath",'**realpath(path)** - Resolve a pathname to its canonical form.\n\n**Parameters:**\n- `path` (string): Path to resolve\n\n**Returns:** `string|null` - Absolute path or null on error\n\n**Example:**\n```ucode\nlet resolved = realpath("../relative/path");\n```'],["pipe","**pipe()** - Create a pipe (returns array of file descriptors).\n\n**Returns:** `array|null` - Array of [readfd, writefd] or null on error\n\n**Example:**\n```ucode\nlet [readfd, writefd] = pipe();\nif (readfd && writefd) {\n // Use the pipe\n}\n```"],["dup2",'**dup2(oldfd, newfd)** - Duplicate a file descriptor.\n\nDuplicates the file descriptor `oldfd` to `newfd`. If `newfd` was previously open, it is silently closed before being reused.\n\n**Parameters:**\n- `oldfd` (number): The file descriptor to duplicate\n- `newfd` (number): The file descriptor number to duplicate to\n\n**Returns:** `boolean|null` - true on success, null on error\n\n**Example:**\n```ucode\nconst logfile = open("/tmp/error.log", "w");\ndup2(logfile.fileno(), 2);\nlogfile.close();\n```'],["mkdtemp",'**mkdtemp(template)** - Create a unique temporary directory.\n\nCreates a temporary directory based on the given template. The template must end with XXXXXX, which is replaced with a unique string.\n\n**Parameters:**\n- `template` (string, optional): Path template (default "/tmp/XXXXXX")\n\n**Returns:** `string|null` - Path of the created directory or null on error\n\n**Example:**\n```ucode\nconst tmpdir = mkdtemp("/tmp/myapp-XXXXXX");\nprint(tmpdir); // e.g., "/tmp/myapp-a1b2c3"\n```']]),new Map([["memdump",'**memdump(file)** - Write a memory dump report to the given file.\n\n**Parameters:**\n- `file` (string | module:fs.file | module:fs.proc): Output file path or file handle\n\n**Returns:** `boolean | null` - true on success, null on error\n\n**Example:**\n```ucode\nif (memdump("/tmp/memory.dump")) {\n print("Memory dump written");\n}\n```'],["traceback",'**traceback([level])** - Generate a stack trace from the current execution point.\n\n**Parameters:**\n- `level` (number, optional): Stack frame level to start from (default: 1)\n\n**Returns:** `module:debug.StackTraceEntry[]` - Array of stack trace entries\n\n**Example:**\n```ucode\nlet trace = traceback(1);\nfor (let frame in trace) {\n print("Function:", frame.function, "Line:", frame.line);\n}\n```'],["sourcepos",'**sourcepos()** - Get the current source position information.\n\n**Returns:** `module:debug.SourcePosition | null` - Source position object or null\n\n**Example:**\n```ucode\nlet pos = sourcepos();\nif (pos) {\n print("File:", pos.filename, "Line:", pos.line);\n}\n```'],["getinfo",'**getinfo(value)** - Get detailed information about a value.\n\n**Parameters:**\n- `value` (any): The value to inspect\n\n**Returns:** `module:debug.ValueInformation | null` - Value information object or null\n\n**Example:**\n```ucode\nlet info = getinfo(myFunction);\nif (info) {\n print("Type:", info.type, "Address:", info.address);\n}\n```'],["getlocal",'**getlocal([level], variable)** - Get the value of a local variable.\n\n**Parameters:**\n- `level` (number, optional): Stack frame level (default: 1)\n- `variable` (string | number): Variable name or index\n\n**Returns:** `module:debug.LocalInfo | null` - Local variable information or null\n\n**Example:**\n```ucode\nlet localInfo = getlocal(1, "myVar");\nif (localInfo) {\n print("Value:", localInfo.value);\n}\n```'],["setlocal",'**setlocal([level], variable, [value])** - Set the value of a local variable.\n\n**Parameters:**\n- `level` (number, optional): Stack frame level (default: 1)\n- `variable` (string | number): Variable name or index\n- `value` (any, optional): New value to set (default: null)\n\n**Returns:** `module:debug.LocalInfo | null` - Updated local variable information or null\n\n**Example:**\n```ucode\nlet result = setlocal(1, "myVar", "new value");\nif (result) {\n print("Variable updated:", result.name);\n}\n```'],["getupval",'**getupval(target, variable)** - Get the value of an upvalue (closure variable).\n\n**Parameters:**\n- `target` (function | number): Target function or stack level\n- `variable` (string | number): Variable name or index\n\n**Returns:** `module:debug.UpvalInfo | null` - Upvalue information or null\n\n**Example:**\n```ucode\nlet upval = getupval(myFunction, "closureVar");\nif (upval) {\n print("Upvalue:", upval.value);\n}\n```'],["setupval",'**setupval(target, variable, value)** - Set the value of an upvalue (closure variable).\n\n**Parameters:**\n- `target` (function | number): Target function or stack level\n- `variable` (string | number): Variable name or index\n- `value` (any): New value to set\n\n**Returns:** `module:debug.UpvalInfo | null` - Updated upvalue information or null\n\n**Example:**\n```ucode\nlet result = setupval(myFunction, "closureVar", "new value");\nif (result) {\n print("Upvalue updated:", result.name);\n}\n```']]),new Map([["md5",'**md5(str)** - Calculate MD5 hash of string.\n\n**Parameters:**\n- `str` (string): The string to hash\n\n**Returns:** `string | null` - MD5 hash string or null if invalid input\n\n**Example:**\n```ucode\nmd5("This is a test"); // "ce114e4501d2f4e2dcea3e17b546f339"\nmd5(123); // null\n```'],["sha1",'**sha1(str)** - Calculate SHA1 hash of string.\n\n**Parameters:**\n- `str` (string): The string to hash\n\n**Returns:** `string | null` - SHA1 hash string or null if invalid input\n\n**Example:**\n```ucode\nsha1("This is a test"); // "a54d88e06612d820bc3be72877c74f257b561b19"\nsha1(123); // null\n```'],["sha256",'**sha256(str)** - Calculate SHA256 hash of string.\n\n**Parameters:**\n- `str` (string): The string to hash\n\n**Returns:** `string | null` - SHA256 hash string or null if invalid input\n\n**Example:**\n```ucode\nsha256("This is a test"); // "c7be1ed902fb8dd4d48997c6452f5d7e509fbcdbe2808b16bcf4edce4c07d14e"\nsha256(123); // null\n```'],["md5_file",'**md5_file(path)** - Calculate MD5 hash of file.\n\n**Parameters:**\n- `path` (string): Path to the file\n\n**Returns:** `string | null` - MD5 hash string or null if error occurred\n\n**Example:**\n```ucode\nmd5_file("/etc/passwd"); // Returns file hash\nmd5_file("/nonexistent"); // null\n```'],["sha1_file",'**sha1_file(path)** - Calculate SHA1 hash of file.\n\n**Parameters:**\n- `path` (string): Path to the file\n\n**Returns:** `string | null` - SHA1 hash string or null if error occurred\n\n**Example:**\n```ucode\nsha1_file("/etc/passwd"); // Returns file hash\nsha1_file("/nonexistent"); // null\n```'],["sha256_file",'**sha256_file(path)** - Calculate SHA256 hash of file.\n\n**Parameters:**\n- `path` (string): Path to the file\n\n**Returns:** `string | null` - SHA256 hash string or null if error occurred\n\n**Example:**\n```ucode\nsha256_file("/etc/passwd"); // Returns file hash\nsha256_file("/nonexistent"); // null\n```'],["md2",'**md2(str)** - Calculate MD2 hash of string (extended).\n\n**Parameters:**\n- `str` (string): The string to hash\n\n**Returns:** `string | null` - MD2 hash string or null if invalid input\n\n**Example:**\n```ucode\nmd2("This is a test"); // "dc378580fd0722e56b82666a6994c718"\nmd2(123); // null\n```'],["md4",'**md4(str)** - Calculate MD4 hash of string (extended).\n\n**Parameters:**\n- `str` (string): The string to hash\n\n**Returns:** `string | null` - MD4 hash string or null if invalid input\n\n**Example:**\n```ucode\nmd4("This is a test"); // "3b487cf6856af7e330bc4b1b7d977ef8"\nmd4(123); // null\n```'],["sha384",'**sha384(str)** - Calculate SHA384 hash of string (extended).\n\n**Parameters:**\n- `str` (string): The string to hash\n\n**Returns:** `string | null` - SHA384 hash string or null if invalid input\n\n**Example:**\n```ucode\nsha384("This is a test"); // Returns long SHA384 hash\nsha384(123); // null\n```'],["sha512",'**sha512(str)** - Calculate SHA512 hash of string (extended).\n\n**Parameters:**\n- `str` (string): The string to hash\n\n**Returns:** `string | null` - SHA512 hash string or null if invalid input\n\n**Example:**\n```ucode\nsha512("This is a test"); // Returns long SHA512 hash\nsha512(123); // null\n```'],["md2_file",'**md2_file(path)** - Calculate MD2 hash of file (extended).\n\n**Parameters:**\n- `path` (string): Path to the file\n\n**Returns:** `string | null` - MD2 hash string or null if error occurred\n\n**Example:**\n```ucode\nmd2_file("/etc/passwd"); // Returns file hash\n```'],["md4_file",'**md4_file(path)** - Calculate MD4 hash of file (extended).\n\n**Parameters:**\n- `path` (string): Path to the file\n\n**Returns:** `string | null` - MD4 hash string or null if error occurred\n\n**Example:**\n```ucode\nmd4_file("/etc/passwd"); // Returns file hash\n```'],["sha384_file",'**sha384_file(path)** - Calculate SHA384 hash of file (extended).\n\n**Parameters:**\n- `path` (string): Path to the file\n\n**Returns:** `string | null` - SHA384 hash string or null if error occurred\n\n**Example:**\n```ucode\nsha384_file("/etc/passwd"); // Returns file hash\n```'],["sha512_file",'**sha512_file(path)** - Calculate SHA512 hash of file (extended).\n\n**Parameters:**\n- `path` (string): Path to the file\n\n**Returns:** `string | null` - SHA512 hash string or null if error occurred\n\n**Example:**\n```ucode\nsha512_file("/etc/passwd"); // Returns file hash\n```']]),new Map([["openlog",'**openlog(ident, options, facility)** - Open connection to system logger.\n\n**Parameters:**\n- `ident` (string, optional): String identifying the program name\n- `options` (number|string|string[], optional): Logging options to use\n- `facility` (number|string, optional): The facility for log messages (default: "user")\n\n**Returns:** `boolean` - true if system openlog() was invoked, false on invalid arguments\n\n**Example:**\n```ucode\n// Using constants\nopenlog("myapp", LOG_PID | LOG_NDELAY, LOG_LOCAL0);\n\n// Using option names\nopenlog("myapp", ["pid", "ndelay"], "user");\n```'],["syslog",'**syslog(priority, format, ...args)** - Log a message to the system logger.\n\n**Parameters:**\n- `priority` (number|string): Log message priority\n- `format` (any): The sprintf-like format string or value to log\n- `...args` (any, optional): Arguments for format string\n\n**Returns:** `boolean` - true if message was logged, false on invalid priority or empty message\n\n**Example:**\n```ucode\n// Using constants\nsyslog(LOG_ERR, "User %s encountered error: %d", username, errorCode);\n\n// Using priority names\nsyslog("info", "System started successfully");\n\n// Implicit stringification\nsyslog("debug", { status: "running", pid: 1234 });\n```'],["closelog","**closelog()** - Close connection to system logger.\n\n**Returns:** `null`\n\n**Example:**\n```ucode\ncloselog();\n```"],["ulog_open",'**ulog_open(channels, facility, ident)** - Configure ulog logger (OpenWrt specific).\n\n**Parameters:**\n- `channels` (number|string|string[], optional): Log channels to use\n- `facility` (number|string, optional): The facility for log messages\n- `ident` (string, optional): String identifying the program name\n\n**Returns:** `boolean` - true if ulog was configured, false on invalid arguments\n\n**Example:**\n```ucode\n// Log to dmesg and stderr\nulog_open(["stdio", "kmsg"], "daemon", "my-program");\n\n// Use numeric constants\nulog_open(ULOG_SYSLOG, LOG_LOCAL0);\n```'],["ulog",'**ulog(priority, format, ...args)** - Log a message via ulog mechanism (OpenWrt specific).\n\n**Parameters:**\n- `priority` (number|string): Log message priority\n- `format` (any): The sprintf-like format string or value to log\n- `...args` (any, optional): Arguments for format string\n\n**Returns:** `boolean` - true if message was logged, false on invalid priority or empty message\n\n**Example:**\n```ucode\n// Using constants\nulog(LOG_ERR, "User %s encountered error: %d", username, errorCode);\n\n// Using priority names\nulog("info", "System started successfully");\n\n// Implicit stringification\nulog("debug", { status: "running", pid: 1234 });\n```'],["ulog_close","**ulog_close()** - Close ulog logger (OpenWrt specific).\n\n**Returns:** `null`\n\n**Example:**\n```ucode\nulog_close();\n```"],["ulog_threshold",'**ulog_threshold(priority)** - Set ulog priority threshold (OpenWrt specific).\n\n**Parameters:**\n- `priority` (number|string, optional): The priority threshold to configure\n\n**Returns:** `boolean` - true if threshold was set, false on invalid priority\n\n**Example:**\n```ucode\n// Set threshold to "warning" or more severe\nulog_threshold(LOG_WARNING);\n\n// Using priority name\nulog_threshold("debug");\n```'],["INFO",'**INFO(format, ...args)** - Convenience wrapper for ulog(LOG_INFO, ...).\n\n**Parameters:**\n- `format` (any): The sprintf-like format string or value to log\n- `...args` (any, optional): Arguments for format string\n\n**Returns:** `boolean` - true if message was logged, false on error\n\n**Example:**\n```ucode\nINFO("System initialization complete");\nINFO("User %s logged in", username);\n```'],["NOTE",'**NOTE(format, ...args)** - Convenience wrapper for ulog(LOG_NOTICE, ...).\n\n**Parameters:**\n- `format` (any): The sprintf-like format string or value to log\n- `...args` (any, optional): Arguments for format string\n\n**Returns:** `boolean` - true if message was logged, false on error\n\n**Example:**\n```ucode\nNOTE("Configuration change detected");\nNOTE("Service %s restarted", serviceName);\n```'],["WARN",'**WARN(format, ...args)** - Convenience wrapper for ulog(LOG_WARNING, ...).\n\n**Parameters:**\n- `format` (any): The sprintf-like format string or value to log\n- `...args` (any, optional): Arguments for format string\n\n**Returns:** `boolean` - true if message was logged, false on error\n\n**Example:**\n```ucode\nWARN("Low disk space detected");\nWARN("Connection timeout for %s", hostname);\n```'],["ERR",'**ERR(format, ...args)** - Convenience wrapper for ulog(LOG_ERR, ...).\n\n**Parameters:**\n- `format` (any): The sprintf-like format string or value to log\n- `...args` (any, optional): Arguments for format string\n\n**Returns:** `boolean` - true if message was logged, false on error\n\n**Example:**\n```ucode\nERR("Failed to connect to database");\nERR("Invalid configuration: %s", errorMessage);\n```']]),new Map([["abs",'**abs(number)** - Returns the absolute value of the given numeric value.\n\n**Parameters:**\n- `number` (number): The number to return the absolute value for\n\n**Returns:** `number` - The absolute value or NaN if the argument cannot be converted to a number\n\n**Example:**\n```ucode\nabs(-42); // 42\nabs(3.14); // 3.14\nabs("abc"); // NaN\n```'],["atan2","**atan2(y, x)** - Calculates the principal value of the arc tangent of y/x.\n\n**Parameters:**\n- `y` (number): The y value\n- `x` (number): The x value\n\n**Returns:** `number` - The arc tangent result in radians (range [-π, π])\n\n**Example:**\n```ucode\natan2(1, 1); // π/4 (45 degrees)\natan2(0, 1); // 0\natan2(1, 0); // π/2\n```"],["cos","**cos(x)** - Calculates the cosine of x, where x is given in radians.\n\n**Parameters:**\n- `x` (number): Radians value to calculate cosine for\n\n**Returns:** `number` - The cosine value or NaN if x cannot be converted to a number\n\n**Example:**\n```ucode\ncos(0); // 1\ncos(3.14159/2); // ~0 (cos(π/2))\ncos(3.14159); // -1 (cos(π))\n```"],["exp","**exp(x)** - Calculates e (base of natural logarithms) raised to the power of x.\n\n**Parameters:**\n- `x` (number): Power to raise e to\n\n**Returns:** `number` - The exponential value or NaN if x cannot be converted to a number\n\n**Example:**\n```ucode\nexp(0); // 1 (e^0)\nexp(1); // ~2.718 (e^1)\nexp(2); // ~7.389 (e^2)\n```"],["log","**log(x)** - Calculates the natural logarithm of x.\n\n**Parameters:**\n- `x` (number): Value to calculate natural logarithm of\n\n**Returns:** `number` - The natural logarithm or NaN if x cannot be converted to a number or is negative\n\n**Example:**\n```ucode\nlog(1); // 0 (ln(1))\nlog(2.718); // ~1 (ln(e))\nlog(10); // ~2.303\n```"],["sin","**sin(x)** - Calculates the sine of x, where x is given in radians.\n\n**Parameters:**\n- `x` (number): Radians value to calculate sine for\n\n**Returns:** `number` - The sine value or NaN if x cannot be converted to a number\n\n**Example:**\n```ucode\nsin(0); // 0\nsin(3.14159/2); // 1 (sin(π/2))\nsin(3.14159); // ~0 (sin(π))\n```"],["sqrt","**sqrt(x)** - Calculates the nonnegative square root of x.\n\n**Parameters:**\n- `x` (number): Value to calculate square root for\n\n**Returns:** `number` - The square root or NaN if x cannot be converted to a number or is negative\n\n**Example:**\n```ucode\nsqrt(4); // 2\nsqrt(9); // 3\nsqrt(-1); // NaN\n```"],["pow","**pow(x, y)** - Calculates the value of x raised to the power of y.\n\n**Parameters:**\n- `x` (number): The base value\n- `y` (number): The power value\n\n**Returns:** `number` - The result of x^y or NaN if either argument cannot be converted to a number\n\n**Example:**\n```ucode\npow(2, 3); // 8 (2^3)\npow(4, 0.5); // 2 (4^0.5 = √4)\npow(10, 2); // 100\n```"],["rand","**rand([a[, b]])** - Produces a pseudo-random number.\n\nWithout arguments, returns a pseudo-random integer in the range 0 to RAND_MAX (at least 32767).\nWith a single argument `a`, returns a random number in the range 0 to `a` inclusive.\nWith two arguments `a, b`, returns a random number in the range `a` to `b` inclusive.\n\n**Parameters:**\n- `a` (number, optional): End of range (or start if `b` is given)\n- `b` (number, optional): End of range\n\n**Returns:** `number`\n\n**Example:**\n```ucode\nrand(); // e.g., 1804 (integer 0..RAND_MAX)\nrand(100); // e.g., 73.5 (double 0..100)\nrand(1, 10); // e.g., 5.2 (double 1..10)\n```"],["srand","**srand(seed)** - Seeds the pseudo-random number generator.\n\n**Parameters:**\n- `seed` (number): The seed value for the random number generator\n\n**Returns:** `null`\n\n**Example:**\n```ucode\nsrand(42); // Seed with 42\nrand(); // Predictable sequence\nsrand(42); // Same seed\nrand(); // Same first value\n```"],["isnan","**isnan(x)** - Tests whether x is a NaN (not a number) double value.\n\n**Parameters:**\n- `x` (number): The value to test\n\n**Returns:** `boolean` - true if the value is NaN, otherwise false\n\n**Example:**\n```ucode\nisnan(42); // false\nisnan(sqrt(-1)); // true\nisnan(0/0); // true\n```"]]),new Map([["request",'**request(cmd, flags?, payload?)** - Send a netlink request to the routing subsystem.\n\n**Parameters:**\n- `cmd` (integer): The RTM_* command to execute\n- `flags` (integer, optional): Request flags (NLM_F_*)\n- `payload` (object, optional): Command-specific attributes\n\n**Returns:** `object | null` - The response object or null on error\n\n**Example:**\n```ucode\n// Get all routes\nlet routes = request(RTM_GETROUTE, NLM_F_DUMP);\n\n// Add a new route\nlet result = request(RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL, {\n dst: "192.168.1.0/24",\n gateway: "192.168.1.1",\n oif: 2\n});\n```'],["listener",'**listener(callback, cmds?, groups?)** - Create an event listener for routing netlink messages.\n\n**Parameters:**\n- `callback` (function): Function called when events are received\n- `cmds` (array, optional): Array of RTM_* command constants to listen for\n- `groups` (array, optional): Array of multicast groups to join\n\n**Returns:** `rtnl.listener` - Listener object\n\n**Example:**\n```ucode\n// Listen for route changes\nlet l = listener(function(msg) {\n printf("Route event: %J\\\n", msg);\n}, [RTM_NEWROUTE, RTM_DELROUTE]);\n\n// Listen for link changes\nlet linkListener = listener(function(msg) {\n printf("Link event: %J\\\n", msg);\n}, [RTM_NEWLINK, RTM_DELLINK]);\n```'],["error",'**error()** - Returns the last rtnl error message, or null if no error occurred.\n\n**Returns:** `string | null` - The error message or null\n\n**Example:**\n```ucode\nlet result = request(RTM_GETROUTE, NLM_F_DUMP);\nif (!result) {\n let errorMsg = error();\n printf("RTNL error: %s\\\n", errorMsg);\n}\n```']]),new Map([["error",'**error()** - Returns the last nl80211 error message, or null if no error occurred.\n\n**Returns:** `string | null` - The error message or null\n\n**Example:**\n```ucode\nlet result = request(NL80211_CMD_GET_WIPHY, NLM_F_DUMP);\nif (!result) {\n let errorMsg = error();\n printf("NL80211 error: %s\n", errorMsg);\n}\n```'],["request","**request(cmd, flags?, payload?)** - Sends a netlink request to the nl80211 subsystem.\n\n**Parameters:**\n- `cmd` (integer): The NL80211_CMD_* command to execute\n- `flags` (integer, optional): Request flags (NLM_F_*)\n- `payload` (object, optional): Command-specific attributes\n\n**Returns:** `object | null` - The response object or null on error\n\n**Example:**\n```ucode\n// Get all wireless interfaces\nlet interfaces = request(NL80211_CMD_GET_INTERFACE, NLM_F_DUMP);\n```"],["waitfor","**waitfor(cmds, timeout?)** - Waits for specific nl80211 commands to be received.\n\n**Parameters:**\n- `cmds` (array): Array of NL80211_CMD_* constants to wait for\n- `timeout` (integer, optional): Maximum wait time in milliseconds\n\n**Returns:** `object | null` - The received message object or null on timeout\n\n**Example:**\n```ucode\n// Wait for scan results with 10 second timeout\nlet scanResults = waitfor([NL80211_CMD_NEW_SCAN_RESULTS], 10000);\n```"],["listener",'**listener(callback, cmds)** - Creates an event listener for nl80211 messages.\n\n**Parameters:**\n- `callback` (function): Function called when events are received\n- `cmds` (array): Array of NL80211_CMD_* constants to listen for\n\n**Returns:** `nl80211.listener` - Listener object with set_commands() and close() methods\n\n**Example:**\n```ucode\nlet l = listener(function(msg) {\n printf("WiFi event: %J\n", msg);\n}, [NL80211_CMD_NEW_STATION, NL80211_CMD_DEL_STATION]);\n```']]),new Map([["NLM_F_ACK","Request an acknowledgment on errors"],["NLM_F_ACK_TLVS","Extended ACK TLVs were included"],["NLM_F_APPEND","Append the new entry to the end of the list"],["NLM_F_ATOMIC","Use atomic operations"],["NLM_F_CAPPED","Dump was capped"],["NLM_F_CREATE","Create if it does not exist"],["NLM_F_DUMP","Dump the table"],["NLM_F_DUMP_FILTERED","Dump was filtered"],["NLM_F_DUMP_INTR","Dump was interrupted"],["NLM_F_ECHO","Echo this request"],["NLM_F_EXCL","Do not touch, if it exists"],["NLM_F_MATCH","Dump all matching entries"],["NLM_F_MULTI","Multipart message"],["NLM_F_NONREC","Do not delete recursively"],["NLM_F_REPLACE","Replace existing matching object"],["NLM_F_REQUEST","This message is a request"],["NLM_F_ROOT","Specify tree root"],["NL80211_IFTYPE_ADHOC","Ad-hoc network interface type"],["NL80211_IFTYPE_STATION","Station (client) interface type"],["NL80211_IFTYPE_AP","Access Point interface type"],["NL80211_IFTYPE_AP_VLAN","Access Point VLAN interface type"],["NL80211_IFTYPE_WDS","Wireless Distribution System interface type"],["NL80211_IFTYPE_MONITOR","Monitor interface type (packet capture)"],["NL80211_IFTYPE_MESH_POINT","Mesh point interface type"],["NL80211_IFTYPE_P2P_CLIENT","P2P client interface type"],["NL80211_IFTYPE_P2P_GO","P2P Group Owner interface type"],["NL80211_IFTYPE_P2P_DEVICE","P2P device interface type"],["NL80211_IFTYPE_OCB","Outside Context of a BSS interface type"],["NL80211_CMD_GET_WIPHY","Get wireless physical device information"],["NL80211_CMD_SET_WIPHY","Set wireless physical device configuration"],["NL80211_CMD_NEW_WIPHY","Create new wireless physical device"],["NL80211_CMD_DEL_WIPHY","Delete wireless physical device"],["NL80211_CMD_GET_INTERFACE","Get wireless interface information"],["NL80211_CMD_SET_INTERFACE","Set wireless interface configuration"],["NL80211_CMD_NEW_INTERFACE","Create new wireless interface"],["NL80211_CMD_DEL_INTERFACE","Delete wireless interface"],["NL80211_CMD_GET_STATION","Get station information"],["NL80211_CMD_SET_STATION","Set station configuration"],["NL80211_CMD_NEW_STATION","Create new station"],["NL80211_CMD_DEL_STATION","Delete station"],["NL80211_CMD_GET_SCAN","Get scan results"],["NL80211_CMD_TRIGGER_SCAN","Trigger a scan"],["NL80211_CMD_NEW_SCAN_RESULTS","New scan results available"],["NL80211_CMD_CONNECT","Connect to an access point"],["NL80211_CMD_DISCONNECT","Disconnect from an access point"],["NL80211_CMD_START_AP","Start access point mode"],["NL80211_CMD_STOP_AP","Stop access point mode"],["HWSIM_CMD_REGISTER","Register with the wireless hardware simulator"],["HWSIM_CMD_FRAME","Send a frame through the hardware simulator"],["HWSIM_CMD_TX_INFO_FRAME","Send transmission info frame"],["HWSIM_CMD_NEW_RADIO","Create new simulated radio"],["HWSIM_CMD_DEL_RADIO","Delete simulated radio"],["HWSIM_CMD_GET_RADIO","Get simulated radio information"]]),new Map([["deflate","**deflate(str_or_resource, gzip?, level?)** - Compresses data in Zlib or gzip format.\n\n**Parameters:**\n- `str_or_resource` (string | object): The string or resource object to be compressed. If an object with a read() method is given, it will be read in chunks for incremental compression\n- `gzip` (boolean, optional, default: false): Add a gzip header if true (creates gzip-compliant output), otherwise defaults to Zlib format\n- `level` (number, optional, default: Z_DEFAULT_COMPRESSION): The compression level (0-9) where 0=no compression, 1=fastest, 9=best compression\n\n**Returns:** `string | null` - The compressed data as a string, or null on error\n\n**Example:**\n```ucode\n// deflate content using default compression\nconst deflated = deflate(content);\n\n// deflate content with gzip format and fastest compression\nconst deflated = deflate(content, true, Z_BEST_SPEED);\n```"],["inflate","**inflate(str_or_resource)** - Decompresses data in Zlib or gzip format.\n\n**Parameters:**\n- `str_or_resource` (string | object): The string or resource object to be decompressed. If an object with a read() method is given, it will be read in chunks for incremental decompression\n\n**Returns:** `string | null` - The decompressed data as a string, or null on error\n\n**Example:**\n```ucode\n// inflate compressed data\nconst inflated = inflate(compressed_data);\n```"],["deflater",'**deflater(gzip?, level?)** - Initializes a deflate stream for streaming compression.\n\n**Parameters:**\n- `gzip` (boolean, optional, default: false): Add a gzip header if true (creates gzip-compliant output), otherwise defaults to Zlib format\n- `level` (number, optional, default: Z_DEFAULT_COMPRESSION): The compression level (0-9)\n\n**Returns:** `zlib.deflate | null` - A stream handle that can be used with write() and read() methods, or null on error\n\n**Example:**\n```ucode\n// create streaming deflate\nconst zstrmd = deflater(true, Z_BEST_SPEED);\nzstrmd.write("data", Z_NO_FLUSH);\nconst compressed = zstrmd.read();\n```'],["inflater","**inflater()** - Initializes an inflate stream for streaming decompression.\n\n**Returns:** `zlib.inflate | null` - A stream handle that can be used with write() and read() methods for streaming decompression. Can process either Zlib or gzip data, or null on error\n\n**Example:**\n```ucode\n// create streaming inflate\nconst zstrmi = inflater();\nzstrmi.write(compressed_data, Z_NO_FLUSH);\nconst decompressed = zstrmi.read();\n```"]]),new Map([["query","**query(names, options?)** - Perform DNS queries for specified domain names.\n\n**Parameters:**\n- `names` (string | string[]): Domain name(s) to query. Can be a single domain name string or an array of domain name strings. IP addresses can also be provided for reverse DNS lookups\n- `options` (object, optional): Query options object with properties:\n - `type` (string[], optional): Array of DNS record types: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT', 'ANY'\n - `nameserver` (string[], optional): Array of DNS nameserver addresses (e.g., '8.8.8.8#53')\n - `timeout` (number, optional, default: 5000): Total timeout in milliseconds\n - `retries` (number, optional, default: 2): Number of retry attempts\n - `edns_maxsize` (number, optional, default: 4096): Maximum UDP packet size for EDNS\n\n**Returns:** `object` - Object containing DNS query results organized by domain name\n\n**Example:**\n```ucode\n// Basic lookup\nconst result = query([\"example.com\"]);\n\n// Specific record types\nconst mx = query([\"example.com\"], { type: [\"MX\"] });\n\n// Reverse DNS\nconst ptr = query([\"192.0.2.1\"], { type: [\"PTR\"] });\n```"],["error",'**error()** - Get the last error message from DNS operations.\n\n**Returns:** `string | null` - A descriptive error message for the last failed operation, or null if no error occurred\n\n**Example:**\n```ucode\nconst result = query("example.org", { nameserver: ["invalid.server"] });\nconst err = error();\nif (err) {\n print("DNS query failed: ", err, "\n");\n}\n```']]),new Map([["create","**create(domain?, type?, protocol?)** - Creates a network socket instance with the specified domain, type, and protocol.\n\n**Parameters:**\n- `domain` (number, optional): Communication domain (default: AF_INET). Values include AF_INET, AF_INET6, AF_UNIX, AF_PACKET\n- `type` (number, optional): Socket type (default: SOCK_STREAM). Values include SOCK_STREAM, SOCK_DGRAM, SOCK_RAW. Can be OR-ed with SOCK_NONBLOCK or SOCK_CLOEXEC\n- `protocol` (number, optional): Protocol to be used (default: 0)\n\n**Returns:** `socket | null` - Socket instance or null on error\n\n**Example:**\n```ucode\n// Create TCP socket\nlet tcp_sock = create(AF_INET, SOCK_STREAM);\n\n// Create UDP socket\nlet udp_sock = create(AF_INET, SOCK_DGRAM);\n\n// Create non-blocking TCP socket\nlet nb_sock = create(AF_INET, SOCK_STREAM | SOCK_NONBLOCK);\n```"],["connect",'**connect(host, service?, hints?, timeout?)** - Creates a network socket and connects it to the specified host and service.\n\n**Parameters:**\n- `host` (string | number[] | SocketAddress): Host to connect to. Can be IP address, hostname, SocketAddress object, or IP array from iptoarr()\n- `service` (string | number, optional): Service name or port number. Optional if host is a SocketAddress\n- `hints` (object, optional): Connection preferences with properties family, socktype, protocol, flags\n- `timeout` (number, optional): Connection timeout in milliseconds (default: -1 for no timeout)\n\n**Returns:** `socket | null` - Connected socket instance or null on error\n\n**Example:**\n```ucode\n// Connect to HTTP server\nlet conn = connect("example.org", 80);\n\n// Connect with IPv6 preference\nlet conn = connect("example.com", 80, { family: AF_INET6 });\n\n// Connect UDP socket\nlet udp = connect("192.168.1.1", 53, { socktype: SOCK_DGRAM });\n```'],["listen",'**listen(host?, service?, hints?, backlog?, reuseaddr?)** - Binds a listening network socket to the specified host and service.\n\n**Parameters:**\n- `host` (string | number[] | SocketAddress, optional): Host to bind to. If omitted, binds to all interfaces\n- `service` (string | number, optional): Service name or port number\n- `hints` (object, optional): Socket preferences with properties family, socktype, protocol, flags\n- `backlog` (number, optional): Maximum length of pending connections queue (default: 128)\n- `reuseaddr` (boolean, optional): Whether to set SO_REUSEADDR option\n\n**Returns:** `socket | null` - Listening socket instance or null on error\n\n**Example:**\n```ucode\n// Listen on all interfaces, port 8080\nlet server = listen("localhost", 8080);\n\n// Listen IPv6 only\nlet server = listen("::1", 8080, { family: AF_INET6 });\n\n// Listen on UNIX domain socket\nlet server = listen({ path: "/tmp/server.sock" });\n```'],["sockaddr",'**sockaddr(address)** - Parses the provided address value into a socket address representation.\n\n**Parameters:**\n- `address` (string | number[] | SocketAddress): Address to parse. Can be IP string with optional port, IP array, or address object\n\n**Returns:** `SocketAddress | null` - Parsed socket address object or null on error\n\n**Example:**\n```ucode\n// Parse IP with port\nlet addr = sockaddr("192.168.1.1:8080");\n\n// Parse IPv6 with port\nlet addr = sockaddr("[fe80::1%eth0]:8080");\n\n// Parse IP array\nlet addr = sockaddr([192, 168, 1, 1]);\n\n// Parse UNIX socket path\nlet addr = sockaddr("/var/run/daemon.sock");\n```'],["nameinfo",'**nameinfo(address, flags?)** - Resolves the given network address into hostname and service name.\n\n**Parameters:**\n- `address` (string | SocketAddress): Network address to resolve\n- `flags` (number, optional): Resolution flags (NI_* constants)\n\n**Returns:** `{hostname: string, service: string} | null` - Resolved hostname and service or null on error\n\n**Example:**\n```ucode\n// Resolve IP address\nlet result = nameinfo("192.168.1.1:80");\nprint(result.hostname, result.service);\n\n// Force numeric output\nlet result = nameinfo("8.8.8.8:53", NI_NUMERICHOST);\n```'],["addrinfo",'**addrinfo(hostname, service?, hints?)** - Resolves the given hostname and optional service name into a list of network addresses.\n\n**Parameters:**\n- `hostname` (string): Hostname to resolve\n- `service` (string, optional): Service name to resolve\n- `hints` (object, optional): Resolution hints with properties family, socktype, protocol, flags\n\n**Returns:** `AddressInfo[] | null` - Array of resolved addresses or null on error\n\n**Example:**\n```ucode\n// Resolve all addresses\nlet addresses = addrinfo("example.org");\n\n// Resolve IPv4 addresses for HTTP\nlet ipv4 = addrinfo("example.com", "http", { family: AF_INET });\n\n// Resolve for TCP sockets\nlet tcp = addrinfo("localhost", "8080", { socktype: SOCK_STREAM });\n```'],["poll","**poll(timeout, ...sockets)** - Polls a number of sockets for state changes.\n\n**Parameters:**\n- `timeout` (number): Timeout in milliseconds. 0 for immediate return, negative for infinite wait\n- `sockets` (...socket | PollSpec): Socket instances or [socket, flags] tuples to poll\n\n**Returns:** `PollSpec[] | null` - Array of [socket, events] tuples for sockets with pending events, or null on error\n\n**Example:**\n```ucode\n// Poll sockets with 10 second timeout\nlet events = poll(10000, sock1, sock2);\n\n// Poll with specific events\nlet events = poll(5000, [sock1, POLLIN], [sock2, POLLOUT]);\n```"],["error",'**error(numeric?)** - Query error information for socket operations.\n\n**Parameters:**\n- `numeric` (boolean, optional): Return numeric error code instead of description\n\n**Returns:** `string | number | null` - Error description, error code, or null if no error\n\n**Example:**\n```ucode\nlet sock = create(AF_INET, SOCK_STREAM);\nif (!sock.connect("invalid.host", 80)) {\n print("Error:", error());\n print("Code:", error(true));\n}\n```'],["strerror",'**strerror(code)** - Returns a string containing a description of the error code.\n\n**Parameters:**\n- `code` (number): Error code (positive for errno, negative for EAI_* constants)\n\n**Returns:** `string | null` - Error description or null for unknown codes\n\n**Example:**\n```ucode\nprint(strerror(-2)); // "Name or service not known"\nprint(strerror(113)); // "No route to host"\n```']]),new Map([["error",'**error(numeric?)** - Retrieve the last ubus error.\n\n**Parameters:**\n- `numeric` (boolean, optional): Return error code as integer if true, otherwise return formatted error message\n\n**Returns:** `integer | string | null` - Error code, error message, or null if no error occurred\n\n**Example:**\n```ucode\nimport { connect, error } from "ubus";\nlet conn = connect("/invalid/socket");\nif (!conn) {\n print("Error:", error());\n print("Code:", error(true));\n}\n```'],["connect",'**connect(socket?, timeout?)** - Establish a connection to the ubus daemon.\n\n**Parameters:**\n- `socket` (string, optional): Path to ubus socket (default: system socket)\n- `timeout` (integer, optional): Connection timeout in seconds (default: 30)\n\n**Returns:** `object` - Connection object for further ubus operations\n\n**Example:**\n```ucode\nimport { connect } from "ubus";\nlet conn = connect();\nif (conn) {\n let objects = conn.list();\n print("Available objects:", length(objects));\n}\n```'],["open_channel",'**open_channel(fd, cb?, disconnect_cb?, timeout?)** - Create a ubus channel connection using an existing file descriptor.\n\n**Parameters:**\n- `fd` (integer): File descriptor for the channel\n- `cb` (function, optional): Callback function for incoming requests\n- `disconnect_cb` (function, optional): Callback function for disconnect events\n- `timeout` (integer, optional): Timeout in seconds (default: 30)\n\n**Returns:** `object` - Channel object for bidirectional communication\n\n**Example:**\n```ucode\nimport { open_channel } from "ubus";\nlet channel = open_channel(socket_fd, function(req) {\n print("Received request:", req.method);\n});\n```'],["guard",'**guard(handler?)** - Set or get the global ubus exception handler.\n\n**Parameters:**\n- `handler` (function, optional): Exception handler function to set\n\n**Returns:** `function | boolean` - Current handler if no arguments, true if handler was set successfully\n\n**Example:**\n```ucode\nimport { guard } from "ubus";\n// Set exception handler\nguard(function(ex) {\n print("ubus exception:", ex.message);\n});\n\n// Get current handler\nlet currentHandler = guard();\n```']]),new Map([["error",'**error()** - Query error information.\n\n**Returns:** `string | null` - Description of the last occurred error or null if there is no error information\n\n**Example:**\n```ucode\n// Trigger error\nconst ctx = cursor();\nctx.set("not_existing_config", "test", "1");\n\n// Print error (should yield "Entry not found")\nprint(error(), "\n");\n```'],["cursor",'**cursor([config_dir], [delta_dir], [config2_dir], [flags])** - Instantiate uci cursor.\n\n**Parameters:**\n- `config_dir` (string, optional): The directory to search for configuration files (default: "/etc/config")\n- `delta_dir` (string, optional): The directory to save delta records in (default: "/tmp/.uci")\n- `config2_dir` (string, optional): The directory to keep override config files in (default: "/var/run/uci")\n- `flags` (object, optional): Parser flags object with properties "strict" and "print_errors"\n\n**Returns:** `uci.cursor | null` - The instantiated cursor on success, null on error\n\n**Example:**\n```ucode\nimport { cursor } from "uci";\n\nlet ctx = cursor();\nlet hostname = ctx.get_first("system", "system", "hostname");\n\n// Custom configuration\nlet custom_ctx = cursor("/tmp/config", "/tmp/delta");\n```']]),new Map([["error","**error()** - Returns the last I/O error message.\n\n**Returns:** `string|null` - Error message string or null if no error occurred"],["new","**new(fd, [takeOver])** - Create an io.handle from an existing file descriptor number.\n\n**Parameters:**\n- `fd` (number): The file descriptor number\n- `takeOver` (boolean, optional): If true, the handle will close the fd when garbage collected (default: false)\n\n**Returns:** `io.handle|null` - A new handle or null on error"],["open","**open(path, [flags], [mode])** - Open a file using POSIX open() semantics.\n\n**Parameters:**\n- `path` (string): The path to open\n- `flags` (number, optional): POSIX open flags (O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, etc.) (default: O_RDONLY)\n- `mode` (number, optional): File mode for new files (default: 0666)\n\n**Returns:** `io.handle|null` - A new handle or null on error"],["from","**from(source)** - Create an io.handle from an existing file handle resource.\n\n**Parameters:**\n- `source` (resource): An fs.file, fs.proc, fs.dir, or io.handle resource\n\n**Returns:** `io.handle|null` - A new handle wrapping the extracted fd, or null on error"],["pipe","**pipe()** - Create a pipe.\n\n**Returns:** `array|null` - Array of [read_handle, write_handle] io.handle objects, or null on error"]]),new Map([...b]));var S,C,A;function O(e){const t=[...new Set(e)];return 0===t.length?C.UNKNOWN:1===t.length?t[0]:{type:C.UNION,types:t}}function L(e){return"object"==typeof e&&e.type===C.UNION}function I(e){return L(e)?e.types:D(e)?[C.ARRAY]:[e]}function D(e){return"object"==typeof e&&null!==e&&e.type===C.ARRAY&&"elementType"in e}function k(e){return{type:C.ARRAY,elementType:e}}function P(e){return D(e)?e.elementType:C.UNKNOWN}function x(e){if(L(e))return e.types.map(e=>x(e)).join(" | ");if(D(e))return`array<${x(e.elementType)}>`;if("object"==typeof e){if("moduleName"in e){const t=e;return t.moduleName.startsWith("fs.")||t.moduleName.startsWith("uci.")||t.moduleName.startsWith("io.")?t.moduleName:`${t.moduleName} module`}if("isDefaultImport"in e)return"object";const t=e;if("type"in t&&"string"==typeof t.type)return t.type}return e}!function(e){e.VARIABLE="variable",e.FUNCTION="function",e.PARAMETER="parameter",e.BUILTIN="builtin",e.IMPORTED="imported",e.MODULE="module"}(S||(S={})),(A=C||(C={})).INTEGER="integer",A.DOUBLE="double",A.STRING="string",A.BOOLEAN="boolean",A.ARRAY="array",A.OBJECT="object",A.FUNCTION="function",A.REGEX="regex",A.NULL="null",A.UNKNOWN="unknown",A.UNION="union";class w{scopes=[];currentScope=0;globalScope=new Map;allSymbols=[];constructor(){this.scopes.push(this.globalScope),this.initializeBuiltins()}initializeBuiltins(){const e=[{name:"print",returnType:C.INTEGER,params:[C.UNKNOWN]},{name:"printf",returnType:C.INTEGER,params:[C.STRING,C.UNKNOWN]},{name:"sprintf",returnType:C.STRING,params:[C.STRING,C.UNKNOWN]},{name:"length",returnType:C.INTEGER,params:[C.UNKNOWN]},{name:"substr",returnType:C.STRING,params:[C.STRING,C.INTEGER,C.INTEGER]},{name:"split",returnType:C.ARRAY,params:[C.STRING,C.STRING]},{name:"join",returnType:C.STRING,params:[C.STRING,C.ARRAY]},{name:"trim",returnType:C.STRING,params:[C.STRING]},{name:"ltrim",returnType:C.STRING,params:[C.STRING,C.STRING]},{name:"rtrim",returnType:C.STRING,params:[C.STRING,C.STRING]},{name:"chr",returnType:C.STRING,params:[C.INTEGER]},{name:"ord",returnType:C.INTEGER,params:[C.STRING]},{name:"uc",returnType:C.STRING,params:[C.STRING]},{name:"lc",returnType:C.STRING,params:[C.STRING]},{name:"type",returnType:C.STRING,params:[C.UNKNOWN]},{name:"keys",returnType:C.ARRAY,params:[C.OBJECT]},{name:"values",returnType:C.ARRAY,params:[C.OBJECT]},{name:"push",returnType:C.INTEGER,params:[C.ARRAY,C.UNKNOWN]},{name:"pop",returnType:C.UNKNOWN,params:[C.ARRAY]},{name:"shift",returnType:C.UNKNOWN,params:[C.ARRAY]},{name:"unshift",returnType:C.INTEGER,params:[C.ARRAY,C.UNKNOWN]},{name:"index",returnType:C.INTEGER,params:[C.UNKNOWN,C.UNKNOWN]},{name:"require",returnType:C.UNKNOWN,params:[C.STRING]},{name:"include",returnType:C.UNKNOWN,params:[C.STRING]},{name:"json",returnType:C.UNKNOWN,params:[C.UNKNOWN]},{name:"match",returnType:C.ARRAY,params:[C.STRING,C.REGEX]},{name:"replace",returnType:C.STRING,params:[C.STRING,C.STRING,C.STRING]},{name:"system",returnType:C.INTEGER,params:[C.STRING]},{name:"time",returnType:C.INTEGER,params:[]},{name:"sleep",returnType:C.NULL,params:[C.INTEGER]},{name:"localtime",returnType:C.OBJECT,params:[C.INTEGER]},{name:"gmtime",returnType:C.OBJECT,params:[C.INTEGER]},{name:"timelocal",returnType:C.INTEGER,params:[C.OBJECT]},{name:"timegm",returnType:C.INTEGER,params:[C.OBJECT]},{name:"min",returnType:C.INTEGER,params:[C.INTEGER]},{name:"max",returnType:C.INTEGER,params:[C.INTEGER]},{name:"uniq",returnType:C.ARRAY,params:[C.ARRAY]},{name:"b64enc",returnType:C.STRING,params:[C.STRING]},{name:"b64dec",returnType:C.STRING,params:[C.STRING]},{name:"hexenc",returnType:C.STRING,params:[C.STRING]},{name:"hexdec",returnType:C.STRING,params:[C.STRING,C.STRING]},{name:"hex",returnType:C.INTEGER,params:[C.STRING]},{name:"uchr",returnType:C.STRING,params:[C.INTEGER]},{name:"iptoarr",returnType:C.ARRAY,params:[C.STRING]},{name:"arrtoip",returnType:C.STRING,params:[C.ARRAY]},{name:"int",returnType:C.INTEGER,params:[C.UNKNOWN]},{name:"loadstring",returnType:C.FUNCTION,params:[C.STRING]},{name:"loadfile",returnType:C.FUNCTION,params:[C.STRING]},{name:"wildcard",returnType:C.BOOLEAN,params:[C.STRING,C.STRING]},{name:"regexp",returnType:C.REGEX,params:[C.STRING,C.STRING]},{name:"assert",returnType:C.NULL,params:[C.UNKNOWN,C.STRING]},{name:"call",returnType:C.UNKNOWN,params:[C.FUNCTION,C.UNKNOWN]},{name:"signal",returnType:C.UNKNOWN,params:[C.INTEGER,C.FUNCTION]},{name:"clock",returnType:C.DOUBLE,params:[]},{name:"sourcepath",returnType:C.STRING,params:[C.INTEGER,C.BOOLEAN]},{name:"gc",returnType:C.NULL,params:[]}];for(const t of e)this.globalScope.set(t.name,{name:t.name,type:S.BUILTIN,dataType:C.FUNCTION,returnType:t.returnType,scope:0,declared:!0,used:!1,node:{type:"Identifier",start:0,end:0,name:t.name},declaredAt:0,usedAt:[]});this.globalScope.set("ARGV",{name:"ARGV",type:S.VARIABLE,dataType:k(C.STRING),scope:0,declared:!0,used:!1,node:{type:"Identifier",start:0,end:0,name:"ARGV"},declaredAt:0,usedAt:[]}),this.globalScope.set("NaN",{name:"NaN",type:S.VARIABLE,dataType:C.DOUBLE,scope:0,declared:!0,used:!1,node:{type:"Identifier",start:0,end:0,name:"NaN"},declaredAt:0,usedAt:[]}),this.globalScope.set("Infinity",{name:"Infinity",type:S.VARIABLE,dataType:C.DOUBLE,scope:0,declared:!0,used:!1,node:{type:"Identifier",start:0,end:0,name:"Infinity"},declaredAt:0,usedAt:[]}),this.globalScope.set("REQUIRE_SEARCH_PATH",{name:"REQUIRE_SEARCH_PATH",type:S.VARIABLE,dataType:C.ARRAY,scope:0,declared:!0,used:!1,node:{type:"Identifier",start:0,end:0,name:"REQUIRE_SEARCH_PATH"},declaredAt:0,usedAt:[]}),this.globalScope.set("modules",{name:"modules",type:S.VARIABLE,dataType:C.OBJECT,scope:0,declared:!0,used:!1,node:{type:"Identifier",start:0,end:0,name:"modules"},declaredAt:0,usedAt:[]}),this.globalScope.set("global",{name:"global",type:S.VARIABLE,dataType:C.OBJECT,scope:0,declared:!0,used:!1,node:{type:"Identifier",start:0,end:0,name:"global"},declaredAt:0,usedAt:[],propertyTypes:new Map})}enterScope(){this.scopes.push(new Map),this.currentScope++}exitScope(e){if(this.scopes.length>1){if(void 0!==e){const t=this.scopes[this.scopes.length-1];if(t)for(const n of t.values())n.scopeEnd=e}this.scopes.pop(),this.currentScope--}}declare(e,t,n,r,i){const o=this.scopes[this.scopes.length-1];if(!o)return!1;if(o.has(e))return!1;const s={name:e,type:t,dataType:n,scope:this.currentScope,declared:!0,used:!1,node:r,declaredAt:r.start,usedAt:[],...i&&{initNode:i}};return o.set(e,s),this.allSymbols.push(s),!0}lookupInCurrentScope(e){const t=this.scopes[this.scopes.length-1];return t&&t.get(e)||null}getScopeCount(){return this.scopes.length}lookup(e){for(let t=this.scopes.length-1;t>=0;t--){const n=this.scopes[t];if(n){const t=n.get(e);if(t)return t}}return null}lookupAtPosition(e,t){let n=null;for(const r of this.allSymbols)if(r.name===e&&void 0!==r.declaredAt&&r.declaredAt<=t){if(void 0!==r.scopeEnd&&t>r.scopeEnd)continue;(!n||r.declaredAt>n.declaredAt)&&(n=r)}if(!n)for(let n=this.scopes.length-1;n>=0;n--){const r=this.scopes[n];if(r){const n=r.get(e);if(n&&void 0!==n.declaredAt&&n.declaredAt<=t)return n}}return n}debugLookup(e){console.log(`[SYMBOL_DEBUG] Looking up '${e}' in ${this.scopes.length} scopes:`);for(let t=this.scopes.length-1;t>=0;t--){const n=this.scopes[t];if(n){const r=n.get(e),i=Array.from(n.keys());console.log(`[SYMBOL_DEBUG] Scope ${t}: ${i.length} symbols [${i.join(", ")}] - ${e}: ${r?"FOUND":"NOT FOUND"}`),r&&console.log(`[SYMBOL_DEBUG] Symbol details: type=${r.type}, dataType=${JSON.stringify(r.dataType)}`)}}}updateSymbolType(e,t){for(let n=this.scopes.length-1;n>=0;n--){const r=this.scopes[n];if(r){const n=r.get(e);if(n)return n.dataType=t,n.currentType=void 0,n.currentTypeEffectiveFrom=void 0,!0}}return!1}forceGlobalDeclaration(e,t,n){const r=this.scopes[0];if(!r)return;const i=r.get(e);if(i)return void(i.dataType=n);const o=this.lookup(e);let s,a;o?(s=o.node,a=o.declaredAt):(s={type:"Identifier",start:0,end:0,name:e},a=0);const c={name:e,type:t,dataType:n,scope:0,declared:!0,used:!!o&&o.used,node:s,declaredAt:a,usedAt:o?o.usedAt:[]};r.set(e,c),o&&0!==o.scope&&(o.dataType=n)}markUsed(e,t){let n=!1;for(const r of this.scopes){const i=r.get(e);i&&(i.used=!0,i.usedAt.push(t),n=!0)}return n}checkShadowing(e){for(let t=this.scopes.length-2;t>=0;t--){const n=this.scopes[t];if(n){const t=n.get(e);if(t)return t}}return null}getUnusedVariables(){const e=[];for(const t of this.scopes)for(const n of t.values())n.used||n.type===S.BUILTIN||e.push(n);return e}getCurrentScope(){return this.currentScope}getCurrentScopeSymbols(){return this.scopes[this.scopes.length-1]||new Map}getAllSymbols(){const e=[];for(const t of this.scopes)for(const n of t.values())e.push(n);return e}getSymbolsAtPosition(e){const t=new Map;for(let n=this.scopes.length-1;n>=0;n--){const r=this.scopes[n];if(r)for(const n of r.values())n.declaredAt<=e&&!t.has(n.name)&&t.set(n.name,n)}for(const n of this.allSymbols)if(!t.has(n.name)&&n.declaredAt<=e&&(void 0===n.scopeEnd||e<=n.scopeEnd)){const e=t.get(n.name);(!e||n.declaredAt>e.declaredAt)&&t.set(n.name,n)}return Array.from(t.values())}}class M{isDefinitelyFalsy(e){return e===C.NULL}isDefinitelyTruthy(e){return e===C.ARRAY||e===C.OBJECT||e===C.FUNCTION||e===C.REGEX}inferLogicalOrType(e,t){return this.isDefinitelyTruthy(e)?e:this.isDefinitelyFalsy(e)||e===C.UNKNOWN&&t!==C.UNKNOWN?t:e===t?e:O([e,t])}inferLogicalAndType(e,t){return this.isDefinitelyFalsy(e)?e:this.isDefinitelyTruthy(e)?t:e===t?e:O([e,t])}inferLogicalOrFullType(e,t){if("object"==typeof e&&"object"==typeof t&&"moduleName"in e&&"moduleName"in t&&e.moduleName===t.moduleName)return e;const n=I(e),r=I(t),i=[];for(const e of n)if(this.isDefinitelyTruthy(e))i.includes(e)||i.push(e);else if(this.isDefinitelyFalsy(e))for(const e of r)i.includes(e)||i.push(e);else{i.includes(e)||i.push(e);for(const e of r)i.includes(e)||i.push(e)}return 0===i.length?C.UNKNOWN:1===i.length?i[0]:O(i)}inferLogicalAndFullType(e,t){const n=I(e),r=I(t),i=[];for(const e of n)if(this.isDefinitelyFalsy(e))i.includes(e)||i.push(e);else if(this.isDefinitelyTruthy(e))for(const e of r)i.includes(e)||i.push(e);else{i.includes(e)||i.push(e);for(const e of r)i.includes(e)||i.push(e)}return 0===i.length?C.UNKNOWN:1===i.length?i[0]:O(i)}getLogicalOperatorExamples(){return[{operation:"||",leftType:C.NULL,rightType:C.INTEGER,resultType:C.INTEGER,explanation:"null || 42 → always returns 42 (integer)"},{operation:"||",leftType:C.ARRAY,rightType:C.STRING,resultType:C.ARRAY,explanation:'[] || "hello" → always returns [] (array)'},{operation:"||",leftType:C.INTEGER,rightType:C.STRING,resultType:O([C.INTEGER,C.STRING]),explanation:'42 || "hello" → could return either based on integer value'},{operation:"&&",leftType:C.NULL,rightType:C.INTEGER,resultType:C.NULL,explanation:"null && 42 → always returns null"},{operation:"&&",leftType:C.ARRAY,rightType:C.STRING,resultType:C.STRING,explanation:'[] && "hello" → always returns "hello" (string)'},{operation:"&&",leftType:C.INTEGER,rightType:C.STRING,resultType:O([C.INTEGER,C.STRING]),explanation:'42 && "hello" → could return either based on integer value'}]}}const F=new M,U=new class{inferAdditionType(e,t){return e===C.STRING||t===C.STRING?C.STRING:this.inferNumericResultType(e,t)}inferArithmeticType(e,t,n){return this.inferNumericResultType(e,t)}inferNumericResultType(e,t){return e===C.DOUBLE||t===C.DOUBLE||this.canProduceFloatingPointSpecial(e,t)?C.DOUBLE:this.areValidIntegerOperands(e,t)?C.INTEGER:e===C.UNKNOWN||t===C.UNKNOWN?C.UNKNOWN:C.DOUBLE}canProduceFloatingPointSpecial(e,t){return e===C.STRING||t===C.STRING||e===C.ARRAY||t===C.ARRAY||e===C.OBJECT||t===C.OBJECT||e===C.FUNCTION||t===C.FUNCTION||e===C.REGEX||t===C.REGEX}areValidIntegerOperands(e,t){const n=new Set([C.INTEGER,C.BOOLEAN,C.NULL]);return n.has(e)&&n.has(t)}isValidArithmeticOperation(e,t,n){return!0}getArithmeticExplanation(e,t,n){if("+"===n&&(e===C.STRING||t===C.STRING))return"String concatenation: converts both operands to strings";if(e===C.DOUBLE||t===C.DOUBLE)return"Numeric promotion: result promoted to double";const r=[];return e===C.BOOLEAN&&r.push("boolean → 0/1"),t===C.BOOLEAN&&r.push("boolean → 0/1"),e===C.NULL&&r.push("null → 0"),t===C.NULL&&r.push("null → 0"),r.length>0?`Type coercion: ${r.join(", ")}`:this.canProduceFloatingPointSpecial(e,t)?"May produce NaN due to invalid numeric conversion":"Standard arithmetic operation"}getArithmeticExamples(){return[{leftType:C.STRING,rightType:C.INTEGER,operator:"+",resultType:C.STRING,example:'"hello" + 42 → "hello42"',explanation:"String concatenation"},{leftType:C.INTEGER,rightType:C.DOUBLE,operator:"+",resultType:C.DOUBLE,example:"42 + 3.14 → 45.14",explanation:"Numeric promotion to double"},{leftType:C.NULL,rightType:C.INTEGER,operator:"+",resultType:C.INTEGER,example:"null + 42 → 42",explanation:"null coerces to 0"},{leftType:C.STRING,rightType:C.INTEGER,operator:"-",resultType:C.DOUBLE,example:'"abc" - 5 → NaN',explanation:"Invalid string conversion produces NaN"},{leftType:C.BOOLEAN,rightType:C.INTEGER,operator:"*",resultType:C.INTEGER,example:"true * 5 → 5",explanation:"Boolean coerces to 1"},{leftType:C.ARRAY,rightType:C.INTEGER,operator:"/",resultType:C.DOUBLE,example:"[1,2,3] / 2 → NaN",explanation:"Array cannot convert to number"}]}};var K;function G(e){const t=[],n=/%([#0\- +]*)(\*|\d*)?(?:\.(\*|\d*))?(?:hh?|ll?|[zjt])?([diouxXeEfFgGaAcspJn%])/g;let r;for(;null!==(r=n.exec(e));){const e=r[4],n=r[0],i=r[1]||"",o=r[2]||"",s=r[3]||"",a=r.index+n.length;if("%"===e){t.push({specifier:"%",expectedTypes:[],position:r.index,endPosition:a,flags:"",width:"",precision:"",fullMatch:n});continue}let c=[];switch(e){case"d":case"i":case"u":case"o":case"x":case"X":case"e":case"E":case"f":case"F":case"g":case"G":case"a":case"A":c=[C.INTEGER,C.DOUBLE,C.BOOLEAN];break;case"c":c=[C.INTEGER,C.STRING];break;case"s":case"J":case"n":case"p":c=[]}"*"===r[2]&&t.push({specifier:"*",expectedTypes:[C.INTEGER],position:r.index,endPosition:a,flags:i,width:o,precision:s,fullMatch:n}),"*"===r[3]&&t.push({specifier:"*",expectedTypes:[C.INTEGER],position:r.index,endPosition:a,flags:i,width:o,precision:s,fullMatch:n}),t.push({specifier:e,expectedTypes:c,position:r.index,endPosition:a,flags:i,width:o,precision:s,fullMatch:n})}return t}!function(e){e.UNDEFINED_VARIABLE="UC1001",e.UNDEFINED_FUNCTION="UC1002",e.VARIABLE_REDECLARATION="UC1003",e.PARAMETER_REDECLARATION="UC1004",e.VARIABLE_SHADOWING="UC1005",e.UNUSED_VARIABLE="UC1006",e.FUNCTION_REDECLARATION="UC1007",e.SHADOWING_BUILTIN="UC1008",e.TYPE_MISMATCH="UC2001",e.INVALID_OPERATION="UC2002",e.INVALID_PARAMETER_COUNT="UC2003",e.INVALID_PARAMETER_TYPE="UC2004",e.INVALID_RETURN_TYPE="UC2005",e.FORMAT_ARG_COUNT_MISMATCH="UC2006",e.FORMAT_TYPE_MISMATCH="UC2007",e.INVALID_IMPORT="UC3001",e.MODULE_NOT_FOUND="UC3002",e.INVALID_EXPORT="UC3003",e.CIRCULAR_DEPENDENCY="UC3004",e.EXPORT_NOT_FOUND="UC3005",e.UNREACHABLE_CODE="UC4001",e.INVALID_BREAK="UC4002",e.INVALID_CONTINUE="UC4003",e.INVALID_RETURN="UC4004",e.INVALID_PROPERTY_ACCESS="UC5001",e.INVALID_METHOD_CALL="UC5002",e.PROPERTY_NOT_FOUND="UC5003",e.METHOD_NOT_FOUND="UC5004",e.SYNTAX_ERROR="UC6001",e.UNEXPECTED_TOKEN="UC6002",e.MISSING_SEMICOLON="UC6003",e.PARSER_ERROR="UC6004",e.JSDOC_UNKNOWN_TYPE="UC7001",e.JSDOC_PARAM_MISMATCH="UC7002",e.JSDOC_MISSING_ANNOTATIONS="UC7003",e.INTERNAL_ERROR="UC9001",e.ANALYSIS_ERROR="UC9002"}(K||(K={}));const B=new Set(["INT","ILL","ABRT","FPE","SEGV","TERM","HUP","QUIT","TRAP","KILL","PIPE","ALRM","STKFLT","PWR","BUS","SYS","URG","STOP","TSTP","CONT","CHLD","TTIN","TTOU","POLL","XFSZ","XCPU","VTALRM","PROF","USR1","USR2"]),W=new Set(["KILL","STOP"]);class ${errors=[];warnings=[];narrowedReturnType=null;inTruthinessContext=!1;strictMode=!1;constructor(){}setStrictMode(e){this.strictMode=e}pushTypeMismatch(e,t,n){this.errors.push({message:e,start:t,end:n,severity:"error"})}narrowForArgType(e,t,n){if(!e)return;const r=this.getNodeType(e);if(t.includes(r))this.narrowedReturnType=n;else if(r===C.UNKNOWN)this.narrowedReturnType=O([n,C.NULL]);else if(r.includes(" | ")){const e=r.split(" | ").map(e=>e.trim()).every(e=>t.includes(e));this.narrowedReturnType=e?n:O([n,C.NULL])}else this.narrowedReturnType=C.NULL}preserveArrayElementType(e){if(!e||this.narrowedReturnType!==C.ARRAY)return;const t=this.getNodeFullType(e);t&&D(t)&&(this.narrowedReturnType=t)}checkArgumentCount(e,t,n){return!(e.arguments.length<n&&(this.errors.push({message:`Function '${t}' expects at least ${n} argument(s), got ${e.arguments.length}`,start:e.start,end:e.end,severity:"error"}),1))}validateNumericArgument(e,t,n){if(!e)return!0;const r=this.getNodeType(e);if(i=r,![C.NULL,C.BOOLEAN,C.INTEGER,C.DOUBLE,C.STRING,C.UNKNOWN].includes(i))return this.pushTypeMismatch(`Argument ${n} of ${t}() cannot be a ${r.toLowerCase()}. It must be a value convertible to a number.`,e.start,e.end),!1;var i;if(r===C.STRING&&"Literal"===e.type){const r=e;if("string"==typeof r.value&&!function(e){const t=e.trim();return""!==t&&/^[+-]?(\d*\.?\d+([eE][+-]?\d+)?|0[xX][0-9a-fA-F]+|0[bB][01]+|0[oO]?[0-7]+)$/.test(t)}(r.value))return this.pushTypeMismatch(`String "${r.value}" cannot be converted to a number for ${t}() argument ${n}.`,e.start,e.end),!1}return!0}validateArgumentType(e,t,n,r,i,o){if(!e)return!0;let s=e.start,a=e.end,c=null,l=null,u=!1;if("||"===e.operator&&e.left&&e.right&&(u=this.getNodeType(e.right).split(" | ").map(e=>e.trim()).every(e=>r.includes(e)),s=e.left.start,a=e.left.end,c=e.right.start,l=e.right.end,u&&!this.strictMode))return!0;const p=this.getNodeType(e),d=i&&!this.strictMode?[...r,...i]:r,m=p.split(" | ").map(e=>e.trim());if(m.length>1){const h=m.some(e=>e!==C.UNKNOWN&&d.includes(e)),f=m.filter(e=>!d.includes(e));if(!h&&!m.includes(C.UNKNOWN)){const e=o||`Function '${t}' expects ${r.join(" or ")} for argument ${n}, but got ${p.toLowerCase()}`;return this.errors.push({message:e,start:s,end:a,severity:"error"}),!1}if(f.length>0){const d=o||`Argument ${n} of ${t}() may be ${f.join(" | ")}. Use a type guard to narrow to ${r.join(" | ")}.`,m=null!=c?this.getVariableName(e.left):this.getVariableName(e),h={functionName:t,argumentIndex:n-1,expectedType:r.join(" | "),expectedTypes:[...r],actualType:p,variableName:m,argumentOffset:s};i&&i.length>0&&(h.toleratedTypes=[...i]),u&&null!=c&&null!=l&&(h.fallbackStart=c,h.fallbackEnd=l,h.fullExprStart=e.start,h.fullExprEnd=e.end),this.strictMode?this.errors.push({message:d,start:s,end:a,severity:"error",code:"nullable-argument",data:h}):this.warnings.push({message:d,start:s,end:a,severity:"warning",code:"nullable-argument",data:h})}}else if(p===C.UNKNOWN){if(this.strictMode||!this.inTruthinessContext){const d=o||`Argument ${n} of ${t}() is unknown. Use a type guard to narrow to ${r.join(" | ")}.`,m=null!=c?this.getVariableName(e.left):this.getVariableName(e),h={functionName:t,argumentIndex:n-1,expectedType:r.join(" | "),expectedTypes:[...r],actualType:p,variableName:m,argumentOffset:s};i&&i.length>0&&(h.toleratedTypes=[...i]),u&&null!=c&&null!=l&&(h.fallbackStart=c,h.fallbackEnd=l,h.fullExprStart=e.start,h.fullExprEnd=e.end),this.strictMode?this.errors.push({message:d,start:s,end:a,severity:"error",code:"incompatible-function-argument",data:h}):this.warnings.push({message:d,start:s,end:a,severity:"warning",code:"incompatible-function-argument",data:h})}}else if(!d.includes(p)){const e=o||`Function '${t}' expects ${r.join(" or ")} for argument ${n}, but got ${p.toLowerCase()}`;return this.errors.push({message:e,start:s,end:a,severity:"error"}),!1}return!0}isKnownTruish(e){if("Literal"===e.type){const t=e;switch(t.literalType){case"null":return!1;case"boolean":return!0===t.value;case"number":return 0!==t.value;case"string":return""!==t.value;case"double":return 0!==t.value&&!isNaN(t.value);default:return!0}}return!0}getVariableName(e){if("Identifier"===e.type)return e.name;if("MemberExpression"===e.type)return this.getDottedPath(e);if("BinaryExpression"===e.type){const t=e;if("||"===t.operator||"??"===t.operator)return this.getVariableName(t.left)}return null}getDottedPath(e){if("Identifier"===e.type)return e.name;if("MemberExpression"===e.type){const t=e;if(t.computed)return null;const n=this.getDottedPath(t.object);return n&&"Identifier"===t.property?.type?`${n}.${t.property.name}`:null}return null}validateLengthFunction(e){if(!this.checkArgumentCount(e,"length",1))return!0;const t=e.arguments[0];return this.narrowForArgType(t,[C.STRING,C.ARRAY,C.OBJECT],C.INTEGER),this.validateArgumentType(t,"length",1,[C.STRING,C.ARRAY,C.OBJECT],[C.NULL]),!0}validateIndexFunction(e){return!this.checkArgumentCount(e,"index",2)||(this.narrowForArgType(e.arguments[0],[C.STRING,C.ARRAY],C.INTEGER),this.validateArgumentType(e.arguments[0],"index",1,[C.STRING,C.ARRAY]),!0)}validateRindexFunction(e){return!this.checkArgumentCount(e,"rindex",2)||(this.narrowForArgType(e.arguments[0],[C.STRING,C.ARRAY],C.INTEGER),this.validateArgumentType(e.arguments[0],"rindex",1,[C.STRING,C.ARRAY]),!0)}validateMatchFunction(e){if(!this.checkArgumentCount(e,"match",2))return!0;this.narrowForArgType(e.arguments[1],[C.REGEX],C.ARRAY),this.narrowedReturnType===C.ARRAY&&(this.narrowedReturnType=k(C.STRING)),this.validateArgumentType(e.arguments[0],"match",1,[C.STRING]);const t=e.arguments[1];if(t){const e=this.getNodeType(t);if(e!==C.REGEX&&e!==C.UNKNOWN){if("Literal"===t.type){const e=t;if("string"===e.literalType){const n=e.value;return this.pushTypeMismatch(`Function 'match' expects regex for argument 2, but got string.\nDid you mean: /${n}/`,t.start,t.end),!0}}this.validateArgumentType(t,"match",2,[C.REGEX])}}return!0}validateSplitFunction(e){if(!this.checkArgumentCount(e,"split",2))return!0;const t=e.arguments[0],n=e.arguments[1],r=t?this.getNodeType(t):C.UNKNOWN,i=n?this.getNodeType(n):C.UNKNOWN,o=r===C.STRING,s=i===C.STRING||i===C.REGEX;if(this.narrowedReturnType=o&&s?k(C.STRING):O([C.ARRAY,C.NULL]),t&&this.validateArgumentType(t,"split",1,[C.STRING]),n&&this.validateArgumentType(n,"split",2,[C.STRING,C.REGEX]),3===e.arguments.length){const t=e.arguments[2];t&&this.validateArgumentType(t,"split",3,[C.INTEGER])}return!0}validateReplaceFunction(e){return!this.checkArgumentCount(e,"replace",3)||(this.validateArgumentType(e.arguments[1],"replace",2,[C.STRING,C.REGEX]),this.validateArgumentType(e.arguments[2],"replace",3,[C.STRING,C.FUNCTION]),!0)}validateDieFunction(e){return!0}validateLcFunction(e){return this.checkArgumentCount(e,"lc",1),!0}validateUcFunction(e){return this.checkArgumentCount(e,"uc",1),!0}validateLoadstringFunction(e){if(1!==e.arguments.length)return this.errors.push({message:`loadstring() expects 1 argument, got ${e.arguments.length}`,start:e.start,end:e.end,severity:"error"}),!0;const t=e.arguments[0];return!t||(this.validateArgumentType(t,"loadstring",1,[C.STRING]),!0)}validateHexencFunction(e){return this.checkArgumentCount(e,"hexenc",1),!0}validateJoinFunction(e){return!this.checkArgumentCount(e,"join",2)||(e.arguments[1]&&this.narrowForArgType(e.arguments[1],[C.ARRAY],C.STRING),this.validateArgumentType(e.arguments[0],"join",1,[C.STRING]),this.validateArgumentType(e.arguments[1],"join",2,[C.ARRAY]),!0)}validateExistsFunction(e){return!this.checkArgumentCount(e,"exists",2)||(this.validateExistsArg(e.arguments[0]),this.validateArgumentType(e.arguments[1],"exists",2,[C.STRING]),!0)}validateExistsArg(e){if(!e)return;const t=this.getNodeType(e),n=t.split(" | ").map(e=>e.trim()),r=[C.OBJECT,C.NULL,C.UNKNOWN],i=n.filter(e=>!r.includes(e));i.length>0&&i.length===n.length?this.errors.push({message:`Function 'exists' expects object for argument 1, but got ${t.toLowerCase()}`,start:e.start,end:e.end,severity:"error"}):i.length>0&&(n.includes(C.OBJECT)||n.includes(C.UNKNOWN)||this.errors.push({message:`Function 'exists' expects object for argument 1, but got ${t.toLowerCase()}`,start:e.start,end:e.end,severity:"error"}))}validateAssertFunction(e){if(0===e.arguments.length)this.warnings.push({message:"Empty assert() will always fail - consider adding a condition",start:e.start,end:e.end,severity:"warning"});else{const t=e.arguments[0];t&&!this.isKnownTruish(t)&&this.warnings.push({message:"assert() with falsy value will always fail - consider adding a condition",start:t.start,end:t.end,severity:"warning"})}return!0}validateRegexpFunction(e){if(!this.checkArgumentCount(e,"regexp",1))return!0;if(this.validateArgumentType(e.arguments[0],"regexp",1,[C.STRING]),e.arguments.length>1&&this.validateArgumentType(e.arguments[1],"regexp",2,[C.STRING])){const t=e.arguments[1];if(t&&"Literal"===t.type){const e=t;if("string"===e.literalType){const n=e.value,r=new Set(["i","s","g"]),i=[];for(const e of n)r.has(e)||i.push(e);if(i.length>0){const e=[...new Set(i)];this.errors.push({message:`Unrecognized flag characters: ${e.map(e=>`'${e}'`).join(", ")}`,start:t.start,end:t.end,severity:"error"})}}}}return!0}validateWildcardFunction(e){if(!this.checkArgumentCount(e,"wildcard",2))return!0;this.narrowForArgType(e.arguments[1],[C.STRING],C.BOOLEAN),this.validateArgumentType(e.arguments[1],"wildcard",2,[C.STRING]);const t=e.arguments[1];if(t&&"Literal"===t.type){const e=t;if("string"===e.literalType){const n=String(e.value??""),r=e.valueStart??t.start+1,i=e.valueEnd??t.end-1;let o=!1,s=!1;const a=(e,t,n,s)=>{o||="error"===e;const a=Math.min(i,Math.max(r,r+n)),c=Math.min(i,Math.max(a,r+(s??n+1)));"warning"===e?this.warnings.push({message:t,start:a,end:c,severity:e}):"error"===e&&this.errors.push({message:t,start:a,end:c,severity:e})},c=new Set(["alnum","alpha","blank","cntrl","digit","graph","lower","print","punct","space","upper","xdigit"]);for(let e=0;e+1<n.length;e++)"*"===n[e]&&"*"===n[e+1]&&a("warning",`Redundant '*' at position ${e}. Prefer a single '*' unless you truly want back-to-back globs.`,e,e+2);const l=!0;let u=0;for(;u<n.length;){const e=n[u];if(l&&"\\"===e){if(u+1<n.length){u+=2;continue}a("warning","Trailing backslash escapes nothing and is treated as a literal '\\'. If you intended to escape a character, add it after the '\\'.",u),u+=1}else if("*"!==e&&"?"!==e){if("["===e){const e=u;let t=u+1,r=!1,i=null;const o=t<n.length&&("!"===n[t]||"^"===n[t]);o&&t++,t<n.length&&"]"===n[t]&&-1!==n.indexOf("]",t+1)&&(r=!0,i="]",t++);let p=!1;for(;t<n.length;)if(l&&"\\"===n[t]){if(t+1<n.length&&n[t+1]){r=!0,i=n[t+1]??null,t+=2;continue}t+=1}else{if("["===n[t]&&t+1<n.length&&":"===n[t+1]){const e=t+2,o=n.indexOf(":]",e);if(-1===o){const r=n.indexOf("]",t+2);if(-1!==r){const i=n.slice(e,r),o=i.toLowerCase(),s=c.has(i)||c.has(o);s&&a("error","POSIX character class appears to be missing the trailing ':]'."+(s?` Did you mean '[[:${o}:]]'?`:" Use the form '[[:class:]]'."),t,r+1),t+=1;continue}a("error","Unterminated character class. Expected ':]' to close '[:class:]'. Add ':]' to close the class.",t,Math.min(t+2,n.length)),t+=1;continue}{const s=n.slice(e,o);if(!c.has(s)&&!c.has(s.toLowerCase())){const e=s.toLowerCase(),n=c.has(e)?` Did you mean '[:${e}:]'?`:"";a("error",`Unknown POSIX character class '[:${s}:]'. Allowed: ${Array.from(c).join(", ")}.`+n,t,o+2)}r=!0,i=null,t=o+2;continue}}if("*"!==n[t]&&"?"!==n[t]||!n[t]){if("]"===n[t]){p=!0,t++;break}if("-"===n[t]){if(!r||t+1>=n.length||"]"===n[t+1]){r=!0,i="-",t+=1;continue}let e=t+1,o=null,s=!1;if(e<n.length&&(l&&"\\"===n[e]&&e+1<n.length?(s="]"!==n[e+1],o=s?n[e+1]??null:null):"]"!==n[e]&&(s=!0,o="["===n[e]&&e+1<n.length&&":"===n[e+1]?null:n[e]??null)),s){if(i&&o){const e=i.charCodeAt(0),n=o.charCodeAt(0);i>="A"&&i<="Z"&&o>="a"&&o<="z"&&e<n&&a("warning",`Suspicious range '${i}-${o}' spans punctuation (between 'Z' and 'a'). Prefer '[A-Za-z]'.`,t-1,t+2),e>n&&a("warning",`Descending range '${i}-${o}' likely matches nothing under byte collation. Did you mean '${o}-${i}' or escape '-' as '\\-'?`,t-1,t+2)}if(t+=1,l&&"\\"===n[t]&&t+1<n.length)t+=2;else if("["===n[t]&&t+1<n.length&&":"===n[t+1]){let e=t+2,r=!1;for(;e+1<n.length;){if(":"===n[e]&&"]"===n[e+1]){r=!0;break}e++}t=r?e+2:t+1}else t+=1;r=!0,i=null;continue}a("error","Malformed range: '-' must have a character on both sides inside '[...]'. Move '-' to the start/end to make it literal (e.g., '[-a]' or '[a-]'), or provide both endpoints (e.g., 'a-z').",t),r=!0,i="-",t+=1;continue}r=!0,i=n[t]??null,t+=1}else a("warning",`'${n[t]}' is literal inside '[...]', not a wildcard.`,t),r=!0,i=n[t]??null,t+=1}if(p){r||a("error",o?"Negated bracket expression has no items. Add at least one character, range, or class (e.g., '[!a-z]', '[^[:digit:]]'). To exclude only ']', write '[!]]' or '[^]]'.":"Empty bracket expression '[]' is invalid. To match a literal ']', use '[]]' (']' as the first item), or escape ']' outside brackets as '\\]'.",e,t),s=!0;const l=n.slice(e+1,t-1),p=/^:([A-Za-z]+):$/.exec(l);if(p&&p[1]){const n=p[1],r=n.toLowerCase();c.has(n)||c.has(r)?a("error",`POSIX character class used without outer brackets. Use '[[:${r}:]]', not '[:${n}:]'.`,e,t):a("warning",`Looks like a POSIX character class '[:${n}:]' used without outer brackets, but '${n}' is not a standard POSIX class. Allowed: ${Array.from(c).join(", ")}.`,e,t)}console.log(i),u=t;continue}a("error","Unclosed bracket expression. Add a matching ']' to close the '[' opened here.",e),u=e+1;continue}u+=1}else s=!0,u+=1}o||s||this.warnings.push({message:`Wildcard pattern '${n}' contains no wildcard characters. Consider adding '*', '?' or a bracket expression '[...]' if you intended a pattern.`,start:t.start,end:t.end,severity:"warning"})}}return!0}validateLocaltimeFunction(e){return this.validateArgumentType(e.arguments[0],"localtime",1,[C.INTEGER,C.DOUBLE]),!0}validateGmtimeFunction(e){return this.validateArgumentType(e.arguments[0],"gmtime",1,[C.INTEGER,C.DOUBLE]),!0}validateTimelocalFunction(e){return!this.checkArgumentCount(e,"timelocal",1)||(this.validateArgumentType(e.arguments[0],"timelocal",1,[C.OBJECT]),!0)}validateTypelocalFunction(e){return this.checkArgumentCount(e,"type",1),!0}validateTimegmFunction(e){return!this.checkArgumentCount(e,"timegm",1)||(this.validateArgumentType(e.arguments[0],"timegm",1,[C.OBJECT]),!0)}validateJsonFunction(e){return!this.checkArgumentCount(e,"json",1)||(this.validateArgumentType(e.arguments[0],"json",1,[C.STRING,C.OBJECT],void 0,"Function 'json' expects string or object as argument"),!0)}validateCallFunction(e){return!this.checkArgumentCount(e,"call",1)||(this.validateArgumentType(e.arguments[0],"call",1,[C.FUNCTION]),e.arguments.length>=3&&this.validateArgumentType(e.arguments[2],"call",3,[C.OBJECT,C.NULL]),!0)}validateClockFunction(e){return e.arguments[0]&&this.isKnownTruish(e.arguments[0]),!0}validateSignalFunction(e){if(!this.checkArgumentCount(e,"signal",1))return!0;const t=e.arguments[0];let n=null;if(t){const e=this.getNodeType(t);if("Literal"===t.type){const r=t;if(null!==r.value)if(n=r.value,e===C.INTEGER)"number"==typeof r.value&&(r.value<1||r.value>31)&&this.errors.push({message:`Signal number must be between 1 and 31, got ${r.value}`,start:t.start,end:t.end,severity:"error"});else if(e===C.STRING){if("string"==typeof r.value){let e=r.value.toUpperCase().replace(/^SIG/,"");B.has(e)||W.has(e)||this.errors.push({message:`Invalid signal name "${r.value}"`,start:t.start,end:t.end,severity:"error"})}}else e===C.DOUBLE?this.pushTypeMismatch("signal() first parameter cannot be a double",t.start,t.end):this.validateArgumentType(t,"signal",1,[C.INTEGER,C.STRING])}else this.validateArgumentType(t,"signal",1,[C.INTEGER,C.STRING])}if(2===e.arguments.length){const r=e.arguments[1];if(r){if(this.getNodeType(r)===C.STRING&&"Literal"===r.type){const e=r;"string"==typeof e.value&&"ignore"!==e.value&&"default"!==e.value&&this.warnings.push({message:`Invalid signal handler string "${e.value}". Did you mean 'ignore' or 'default'?`,start:r.start,end:r.end,severity:"warning"})}else this.validateArgumentType(r,"signal",2,[C.FUNCTION,C.STRING]);if(n&&t){let e=String(n).toUpperCase().replace(/^SIG/,"");W.has(e)&&this.warnings.push({message:`Signal '${e}' cannot be caught or ignored.`,start:t.start,end:t.end,severity:"warning"})}}}return!0}validateSystemFunction(e){return!this.checkArgumentCount(e,"system",1)||(this.validateArgumentType(e.arguments[0],"system",1,[C.STRING,C.ARRAY]),e.arguments.length>1&&this.validateArgumentType(e.arguments[1],"system",2,[C.INTEGER,C.DOUBLE]),!0)}validateSleepFunction(e){return!this.checkArgumentCount(e,"sleep",1)||(this.validateNumericArgument(e.arguments[0],"sleep",1),!0)}validateMinFunction(e){return this.checkArgumentCount(e,"min",1),!0}validateMaxFunction(e){return this.checkArgumentCount(e,"max",1),!0}validateUniqFunction(e){return!this.checkArgumentCount(e,"uniq",1)||(this.narrowForArgType(e.arguments[0],[C.ARRAY],C.ARRAY),this.preserveArrayElementType(e.arguments[0]),this.validateArgumentType(e.arguments[0],"uniq",1,[C.ARRAY]),!0)}validatePrintfFunction(e){return!this.checkArgumentCount(e,"printf",1)||(this.validateArgumentType(e.arguments[0],"printf",1,[C.STRING]),this.validateFormatString(e,"printf"),!0)}validateSprintfFunction(e){return!this.checkArgumentCount(e,"sprintf",1)||(this.validateArgumentType(e.arguments[0],"sprintf",1,[C.STRING]),this.validateFormatString(e,"sprintf"),!0)}validateFormatString(e,t){const n=e.arguments[0];if(!n||"Literal"!==n.type)return;const r=n;if("string"!=typeof r.value)return;const i=G(r.value).filter(e=>"%"!==e.specifier),o=e.arguments.slice(1),s=i.length,a=o.length;if(s>a)this.warnings.push({message:`${t}(): format string has ${s} specifier(s) but only ${a} argument(s) provided`,start:n.start,end:n.end,severity:"warning",code:K.FORMAT_ARG_COUNT_MISMATCH});else if(s<a){const e=o[s],n=o[a-1];this.warnings.push({message:`${t}(): format string has ${s} specifier(s) but ${a} argument(s) provided (extra arguments are ignored)`,start:e.start,end:n.end,severity:"warning",code:K.FORMAT_ARG_COUNT_MISMATCH})}for(let e=0;e<Math.min(s,a);e++){const n=i[e];if(0===n.expectedTypes.length)continue;const r=o[e];if(!r)continue;const s=this.getNodeType(r);if(s!==C.UNKNOWN&&!s.includes(" | ")&&!n.expectedTypes.includes(s)){const i=n.expectedTypes.map(e=>e.toLowerCase()).join(" or ");this.warnings.push({message:`${t}(): argument ${e+2} has type '${s.toLowerCase()}' but format specifier '%${n.specifier}' expects ${i}`,start:r.start,end:r.end,severity:"warning",code:K.FORMAT_TYPE_MISMATCH})}}}validateIptoarrFunction(e){return!this.checkArgumentCount(e,"iptoarr",1)||(this.narrowForArgType(e.arguments[0],[C.STRING],C.ARRAY),this.narrowedReturnType===C.ARRAY&&(this.narrowedReturnType=k(C.INTEGER)),this.validateArgumentType(e.arguments[0],"iptoarr",1,[C.STRING]),!0)}validateArrtoipFunction(e){return!this.checkArgumentCount(e,"arrtoip",1)||(this.narrowForArgType(e.arguments[0],[C.ARRAY],C.STRING),this.validateArgumentType(e.arguments[0],"arrtoip",1,[C.ARRAY]),!0)}validateIntFunction(e){return 1!==e.arguments.length?(this.errors.push({message:`int() expects 1 argument, got ${e.arguments.length}`,start:e.start,end:e.end,severity:"error"}),!0):(e.arguments[0]&&this.validateArgumentType(e.arguments[0],"int",1,[C.STRING,C.INTEGER,C.DOUBLE]),!0)}validateHexFunction(e){return 1!==e.arguments.length?(this.errors.push({message:`hex() expects 1 argument, got ${e.arguments.length}`,start:e.start,end:e.end,severity:"error"}),!0):(e.arguments[0]&&this.validateArgumentType(e.arguments[0],"hex",1,[C.STRING]),!0)}validateChrFunction(e){if(this.checkArgumentCount(e,"chr",1)&&e.arguments[0])for(let t=0;t<e.arguments.length;t++){const n=e.arguments[t];n&&this.validateNumericArgument(n,"chr",t)}return!0}validateOrdFunction(e){return!this.checkArgumentCount(e,"ord",1)||(e.arguments.length>=1&&e.arguments[0]&&(this.narrowForArgType(e.arguments[0],[C.STRING],C.INTEGER),this.validateArgumentType(e.arguments[0],"ord",1,[C.STRING]),e.arguments.length>=2&&e.arguments[1]&&this.validateArgumentType(e.arguments[1],"ord",2,[C.INTEGER,C.DOUBLE])),!0)}validateUchrFunction(e){return this.checkArgumentCount(e,"uchr",1),e.arguments[0]&&this.validateArgumentType(e.arguments[0],"uchr",1,[C.STRING,C.INTEGER,C.DOUBLE]),!0}validateRequireFunction(e){return 1!==e.arguments.length?(this.errors.push({message:`require() expects 1 argument, got ${e.arguments.length}`,start:e.start,end:e.end,severity:"error"}),!0):(e.arguments[0]&&this.validateArgumentType(e.arguments[0],"require",1,[C.STRING]),!0)}validateIncludeFunction(e){return e.arguments.length<1||e.arguments.length>2?(this.errors.push({message:`include() expects 1-2 arguments, got ${e.arguments.length}`,start:e.start,end:e.end,severity:"error"}),!0):(e.arguments[0]&&this.validateArgumentType(e.arguments[0],"include",1,[C.STRING]),e.arguments[1]&&this.validateArgumentType(e.arguments[1],"include",2,[C.OBJECT]),!0)}validateHexdecFunction(e){return this.checkArgumentCount(e,"hexdec",1)&&e.arguments[0]&&(this.narrowForArgType(e.arguments[0],[C.STRING],C.STRING),this.validateArgumentType(e.arguments[0],"hexdec",1,[C.STRING])),!0}validateB64encFunction(e){return this.checkArgumentCount(e,"b64enc",1)&&e.arguments[0]&&(this.narrowForArgType(e.arguments[0],[C.STRING],C.STRING),this.validateArgumentType(e.arguments[0],"b64enc",1,[C.STRING])),!0}validateB64decFunction(e){return this.checkArgumentCount(e,"b64dec",1)&&e.arguments[0]&&(this.narrowForArgType(e.arguments[0],[C.STRING],C.STRING),this.validateArgumentType(e.arguments[0],"b64dec",1,[C.STRING])),!0}validateLoadfileFunction(e){if(1!==e.arguments.length)return this.errors.push({message:`loadfile() expects 1 argument, got ${e.arguments.length}`,start:e.start,end:e.end,severity:"error"}),!0;const t=e.arguments[0];return!t||(this.narrowForArgType(t,[C.STRING],C.FUNCTION),this.validateArgumentType(t,"loadfile",1,[C.STRING]),!0)}validateSourcepathFunction(e){const t=e.arguments.length;return t>=1&&(this.validateNumericArgument(e.arguments[0],"sourcepath",1),t>=2&&e.arguments[1]&&this.isKnownTruish(e.arguments[1])),!0}validateGcFunction(e){const t=e.arguments.length;if(t>=1&&e.arguments[0]&&"Literal"===e.arguments[0].type){const i=e.arguments[0];if("string"==typeof i.value&&"collect"!==i.value&&"start"!==i.value&&"stop"!==i.value&&"count"!==i.value&&this.errors.push({message:`Invalid garbage collection command "${i.value}". Did you mean 'collect', or 'start', 'stop', or 'count'?`,start:e.arguments[0].start,end:e.arguments[0].end,severity:"error"}),t>=2&&e.arguments[1])if("Literal"===e.arguments[1].type){const t=e.arguments[1];var n="",r=!1;"string"==typeof i.value&&"start"===i.value?"number"==typeof t.value?(t.value<0||t.value>65535)&&(n=`Invalid garbage collection interval ${t.value}. The acceptable range is 1-65535. 0 for default (1000).`,r=!0):"number"==typeof e.arguments[1]||(n=`Invalid garbage collection interval ${t.value} of type ${typeof t.value}. The acceptable range is 1-65535. 0 for default (1000).`,r=!0):(n=`Invalid garbage collection argument ${t.value}. Argument is only used for 'start' command.`,r=!0),r&&this.errors.push({message:n,start:e.arguments[1].start,end:e.arguments[1].end,severity:"error"})}else e.arguments[1].type}return!0}validatePushFunction(e){if(!this.checkArgumentCount(e,"push",1))return!0;if(this.validateArgumentType(e.arguments[0],"push",1,[C.ARRAY]),e.arguments.length>=2){const t=e.arguments[e.arguments.length-1];if(t){const e=this.getNodeFullType(t);if(e)this.narrowedReturnType=e;else{const e=this.getNodeType(t);e!==C.UNKNOWN&&(this.narrowedReturnType=e)}}}return!0}validatePopFunction(e){if(!this.checkArgumentCount(e,"pop",1))return!0;const t=e.arguments[0]?this.getNodeFullType(e.arguments[0]):null;return t&&D(t)&&(this.narrowedReturnType=P(t)),this.validateArgumentType(e.arguments[0],"pop",1,[C.ARRAY]),!0}validateShiftFunction(e){if(!this.checkArgumentCount(e,"shift",1))return!0;const t=e.arguments[0]?this.getNodeFullType(e.arguments[0]):null;return t&&D(t)&&(this.narrowedReturnType=P(t)),this.validateArgumentType(e.arguments[0],"shift",1,[C.ARRAY]),!0}validateUnshiftFunction(e){if(!this.checkArgumentCount(e,"unshift",1))return!0;if(this.validateArgumentType(e.arguments[0],"unshift",1,[C.ARRAY]),e.arguments.length>=2){const t=e.arguments[e.arguments.length-1];if(t){const e=this.getNodeFullType(t);if(e)this.narrowedReturnType=e;else{const e=this.getNodeType(t);e!==C.UNKNOWN&&(this.narrowedReturnType=e)}}}return!0}validateSliceFunction(e){return!this.checkArgumentCount(e,"slice",1)||(this.narrowForArgType(e.arguments[0],[C.ARRAY],C.ARRAY),this.preserveArrayElementType(e.arguments[0]),this.validateArgumentType(e.arguments[0],"slice",1,[C.ARRAY]),e.arguments.length>=2&&e.arguments[1]&&this.validateArgumentType(e.arguments[1],"slice",2,[C.INTEGER,C.DOUBLE]),e.arguments.length>=3&&e.arguments[2]&&this.validateArgumentType(e.arguments[2],"slice",3,[C.INTEGER,C.DOUBLE]),!0)}validateSpliceFunction(e){return!this.checkArgumentCount(e,"splice",2)||(this.narrowForArgType(e.arguments[0],[C.ARRAY],C.ARRAY),this.preserveArrayElementType(e.arguments[0]),this.validateArgumentType(e.arguments[0],"splice",1,[C.ARRAY]),this.validateArgumentType(e.arguments[1],"splice",2,[C.INTEGER,C.DOUBLE]),e.arguments.length>=3&&e.arguments[2]&&this.validateArgumentType(e.arguments[2],"splice",3,[C.INTEGER,C.DOUBLE]),!0)}validateSortFunction(e){return!this.checkArgumentCount(e,"sort",1)||(this.narrowForArgType(e.arguments[0],[C.ARRAY],C.ARRAY),this.preserveArrayElementType(e.arguments[0]),this.validateArgumentType(e.arguments[0],"sort",1,[C.ARRAY]),e.arguments.length>=2&&e.arguments[1]&&this.validateArgumentType(e.arguments[1],"sort",2,[C.FUNCTION]),!0)}validateReverseFunction(e){if(!this.checkArgumentCount(e,"reverse",1))return!0;const t=e.arguments[0],n=this.getNodeType(t);if(n===C.ARRAY)this.narrowedReturnType=C.ARRAY,this.preserveArrayElementType(t);else if(n===C.STRING)this.narrowedReturnType=C.STRING;else if(n===C.UNKNOWN)this.narrowedReturnType=O([C.ARRAY,C.STRING,C.NULL]);else if(n.includes(" | ")){const e=n.split(" | ").map(e=>e.trim()),t=[C.ARRAY,C.STRING],r=e.filter(e=>t.includes(e)),i=e.some(e=>!t.includes(e));r.length>0&&i?this.narrowedReturnType=O([...r,C.NULL]):r.length>0?this.narrowedReturnType=O(r):this.narrowedReturnType=C.NULL}else this.narrowedReturnType=C.NULL;return this.validateArgumentType(t,"reverse",1,[C.ARRAY,C.STRING]),!0}validateFilterFunction(e){return!this.checkArgumentCount(e,"filter",2)||(this.narrowForArgType(e.arguments[0],[C.ARRAY],C.ARRAY),this.preserveArrayElementType(e.arguments[0]),this.validateArgumentType(e.arguments[0],"filter",1,[C.ARRAY]),this.validateArgumentType(e.arguments[1],"filter",2,[C.FUNCTION]),!0)}validateMapFunction(e){return!this.checkArgumentCount(e,"map",2)||(this.narrowForArgType(e.arguments[0],[C.ARRAY],C.ARRAY),this.validateArgumentType(e.arguments[0],"map",1,[C.ARRAY]),this.validateArgumentType(e.arguments[1],"map",2,[C.FUNCTION]),!0)}validateKeysFunction(e){return!this.checkArgumentCount(e,"keys",1)||(this.narrowForArgType(e.arguments[0],[C.OBJECT],C.ARRAY),this.narrowedReturnType===C.ARRAY&&(this.narrowedReturnType=k(C.STRING)),this.validateArgumentType(e.arguments[0],"keys",1,[C.OBJECT]),!0)}validateValuesFunction(e){return!this.checkArgumentCount(e,"values",1)||(this.narrowForArgType(e.arguments[0],[C.OBJECT],C.ARRAY),this.validateArgumentType(e.arguments[0],"values",1,[C.OBJECT]),!0)}validateTrimFunction(e){return!this.checkArgumentCount(e,"trim",1)||(this.narrowForArgType(e.arguments[0],[C.STRING],C.STRING),this.validateArgumentType(e.arguments[0],"trim",1,[C.STRING]),e.arguments.length>1&&this.validateArgumentType(e.arguments[1],"trim",2,[C.STRING]),!0)}validateLtrimFunction(e){return!this.checkArgumentCount(e,"ltrim",1)||(this.narrowForArgType(e.arguments[0],[C.STRING],C.STRING),this.validateArgumentType(e.arguments[0],"ltrim",1,[C.STRING]),e.arguments.length>1&&this.validateArgumentType(e.arguments[1],"ltrim",2,[C.STRING]),!0)}validateRtrimFunction(e){return!this.checkArgumentCount(e,"rtrim",1)||(this.narrowForArgType(e.arguments[0],[C.STRING],C.STRING),this.validateArgumentType(e.arguments[0],"rtrim",1,[C.STRING]),e.arguments.length>1&&this.validateArgumentType(e.arguments[1],"rtrim",2,[C.STRING]),!0)}validateSubstrFunction(e){return!this.checkArgumentCount(e,"substr",2)||(this.narrowForArgType(e.arguments[0],[C.STRING],C.STRING),this.validateArgumentType(e.arguments[0],"substr",1,[C.STRING]),this.validateArgumentType(e.arguments[1],"substr",2,[C.INTEGER,C.DOUBLE]),e.arguments.length>2&&this.validateArgumentType(e.arguments[2],"substr",3,[C.INTEGER,C.DOUBLE]),!0)}getErrors(){return this.errors}resetErrors(){this.errors=[]}getWarnings(){return this.warnings}resetWarnings(){this.warnings=[]}getNodeType(e){return C.UNKNOWN}getNodeFullType(e){return null}setTypeChecker(e){this.getNodeType=e}setFullTypeChecker(e){this.getNodeFullType=e}}class j{isUnionTypeCompatibleWith(e,t){return L(e)?I(e).some(e=>this.isTypeCompatible(e,t)):this.isTypeCompatible(e,t)}isTypeCompatibleWithUnion(e,t){return L(t)?I(t).some(t=>this.isTypeCompatible(e,t)):this.isTypeCompatible(e,t)}areUnionTypesCompatible(e,t){if(!L(e)||!L(t))return!1;const n=I(e),r=I(t);return n.every(e=>r.some(t=>this.isTypeCompatible(e,t)))}isNumericType(e){return e===C.INTEGER||e===C.DOUBLE}isArithmeticType(e){return e===C.INTEGER||e===C.DOUBLE||e===C.BOOLEAN}isIntegerType(e){return e===C.INTEGER}getNumericResultType(e,t){return e===C.DOUBLE||t===C.DOUBLE?C.DOUBLE:C.INTEGER}isTypeCompatible(e,t){if(L(e)&&L(t))return this.areUnionTypesCompatible(e,t);if(L(e))return this.isUnionTypeCompatibleWith(e,t);if(L(t))return this.isTypeCompatibleWithUnion(e,t);const n=e,r=t;return n===r||r===C.UNKNOWN||n===C.UNKNOWN||n===C.INTEGER&&r===C.DOUBLE}isSimpleTypeCompatible(e,t){return e===t||t===C.UNKNOWN||e===C.UNKNOWN||e===C.INTEGER&&t===C.DOUBLE}canAssign(e,t){return this.isTypeCompatible(t,e)}canAddTypes(e,t){return!(!this.isArithmeticType(e)||!this.isArithmeticType(t))||e===C.STRING||t===C.STRING||e===C.UNKNOWN||t===C.UNKNOWN}canPerformArithmetic(e,t){const n=this.isArithmeticType(e)||e===C.UNKNOWN,r=this.isArithmeticType(t)||t===C.UNKNOWN;return n&&r}canPerformBitwiseOp(e,t){return!0}canUseInOperator(e,t){return t===C.OBJECT||t===C.ARRAY||t===C.UNKNOWN}getArithmeticResultType(e,t,n){return"+"!==n||e!==C.STRING&&t!==C.STRING?this.isArithmeticType(e)&&this.isArithmeticType(t)?e===C.DOUBLE||t===C.DOUBLE?C.DOUBLE:C.INTEGER:C.UNKNOWN:C.STRING}getComparisonResultType(){return C.BOOLEAN}getLogicalResultType(){return C.BOOLEAN}getBitwiseResultType(){return C.INTEGER}getUnaryResultType(e,t){switch(t){case"+":case"-":return e===C.UNKNOWN?C.UNKNOWN:this.isArithmeticType(e)?e===C.BOOLEAN?C.INTEGER:e:e===C.STRING?C.DOUBLE:C.UNKNOWN;case"!":return C.BOOLEAN;case"~":return e===C.UNKNOWN?C.UNKNOWN:e===C.INTEGER||e===C.BOOLEAN||e===C.DOUBLE?C.INTEGER:C.UNKNOWN;case"++":case"--":return e===C.UNKNOWN?C.UNKNOWN:this.isArithmeticType(e)?e===C.BOOLEAN?C.INTEGER:e:C.UNKNOWN;default:return C.UNKNOWN}}isValidAssignmentTarget(e){return"Identifier"===e||"MemberExpression"===e}isValidCallTarget(e){return e===C.FUNCTION||e===C.UNKNOWN}getArrayElementType(e){return C.ARRAY,C.UNKNOWN}getObjectPropertyType(e){return C.OBJECT,C.UNKNOWN}isIterableType(e){return e===C.ARRAY||e===C.OBJECT||e===C.STRING}getTernaryResultType(e,t){return e===t?e:O([e,t])}getCommonType(e){if(0===e.length)return C.NULL;const t=e.filter(e=>void 0!==e);return 0===t.length?C.NULL:1===t.length?t[0]:t.every(e=>this.isNumericType(e))?t.some(e=>e===C.DOUBLE)?C.DOUBLE:C.INTEGER:O(t)}}const q=new Map([["message",{name:"message",type:"string",description:"Error message describing what went wrong"}],["stacktrace",{name:"stacktrace",type:"array",description:"Array of stack frame objects with filename, line, byte, function (optional), and context (optional) properties"}],["type",{name:"type",type:"string",description:"Type of the exception (e.g., 'TypeError', 'ReferenceError', etc.)"}]]),V={typeName:"exception",isPropertyBased:!0,methods:new Map,properties:q,formatPropertyDoc:(e,t)=>{let n=`**(exception property) ${t.name}**: \`${t.type}\`\n\n${t.description}`;return"stacktrace"===e&&(n+="\n\n**Stack Frame Structure:**\n",n+="- `filename` (string) - Source file path\n",n+="- `line` (number) - Line number in the file\n",n+="- `byte` (number) - Byte offset in the file\n",n+="- `function` (string, optional) - Function name if available\n",n+="- `context` (string, optional) - Additional context information\n\n",n+="**Example:**\n",n+="```ucode\n",n+="try {\n",n+=" riskyOperation();\n",n+="} catch (e) {\n",n+=" for (let frame in e.stacktrace) {\n",n+=' print("File: " + frame.filename + ", Line: " + frame.line);\n',n+=" }\n",n+="}\n",n+="```"),n}},H=e=>{const t=q.get(e);return t?`**(exception property) ${t.name}**: \`${t.type}\`\n\n${t.description}`:""};function Y(){return C.OBJECT}var X;!function(e){e.FS_PROC="fs.proc",e.FS_DIR="fs.dir",e.FS_FILE="fs.file",e.FS_STATVFS="fs.statvfs"}(X||(X={}));const z={typeName:"fs.proc",methods:new Map([["read",{name:"read",parameters:[{name:"amount",type:"number | string",optional:!1}],returnType:"string",description:'Read data from the process handle. Parameter can be: a number (bytes to read), "line" (read until newline), "all" (read until EOF), or a single character (read until that character). Returns a string containing the read data, empty string on EOF, or null on error.'}],["write",{name:"write",parameters:[{name:"data",type:"any",optional:!1}],returnType:"integer",description:"Write data to the process handle"}],["close",{name:"close",parameters:[],returnType:"integer",description:"Close the process handle and get exit code"}],["flush",{name:"flush",parameters:[],returnType:"boolean",description:"Flush buffered data"}],["fileno",{name:"fileno",parameters:[],returnType:"integer",description:"Get the underlying file descriptor number"}],["error",{name:"error",parameters:[],returnType:"string",description:"Get error information"}]]),formatDoc:(e,t)=>`**fs.proc.${t.name}()**: \`${t.returnType}\`\n\n${t.description}`},J={typeName:"fs.dir",methods:new Map([["read",{name:"read",parameters:[],returnType:"string",description:"Read the next directory entry"}],["tell",{name:"tell",parameters:[],returnType:"integer",description:"Get current read position"}],["seek",{name:"seek",parameters:[{name:"position",type:"integer",optional:!1}],returnType:"boolean",description:"Set read position"}],["close",{name:"close",parameters:[],returnType:"boolean",description:"Close the directory handle"}],["fileno",{name:"fileno",parameters:[],returnType:"integer",description:"Get the underlying file descriptor number"}],["error",{name:"error",parameters:[],returnType:"string",description:"Get error information"}]]),formatDoc:(e,t)=>`**fs.dir.${t.name}()**: \`${t.returnType}\`\n\n${t.description}`},Q={typeName:"fs.file",methods:new Map([["read",{name:"read",parameters:[{name:"amount",type:"number | string",optional:!1}],returnType:"string",description:'Read data from the file handle. Parameter can be: a number (bytes to read), "line" (read until newline), "all" (read until EOF), or a single character (read until that character). Returns a string containing the read data, empty string on EOF, or null on error.'}],["write",{name:"write",parameters:[{name:"data",type:"any",optional:!1}],returnType:"integer",description:"Write data to the file handle"}],["seek",{name:"seek",parameters:[{name:"offset",type:"integer",optional:!0},{name:"whence",type:"integer",optional:!0}],returnType:"boolean",description:"Set file read position"}],["tell",{name:"tell",parameters:[],returnType:"integer",description:"Get current file position"}],["close",{name:"close",parameters:[],returnType:"boolean",description:"Close the file handle"}],["flush",{name:"flush",parameters:[],returnType:"boolean",description:"Flush buffered data"}],["fileno",{name:"fileno",parameters:[],returnType:"integer",description:"Get the underlying file descriptor number"}],["isatty",{name:"isatty",parameters:[],returnType:"boolean",description:"Check if the file handle refers to a TTY device"}],["truncate",{name:"truncate",parameters:[{name:"offset",type:"integer",optional:!0}],returnType:"boolean",description:"Truncate file to given size"}],["lock",{name:"lock",parameters:[{name:"operation",type:"string",optional:!1}],returnType:"boolean",description:"Lock or unlock the file"}],["error",{name:"error",parameters:[],returnType:"string",description:"Get error information"}],["ioctl",{name:"ioctl",parameters:[{name:"direction",type:"integer",optional:!1},{name:"type",type:"integer",optional:!1},{name:"number",type:"integer",optional:!1},{name:"value",type:"any",optional:!0}],returnType:"any",description:"Perform ioctl operation on the file (Linux only)"}]]),formatDoc:(e,t)=>`**fs.file.${t.name}()**: \`${t.returnType}\`\n\n${t.description}`};function Z(e){return{type:C.OBJECT,moduleName:e}}function ee(e){const t=te.get(e);if(!t)return null;for(const e of Object.values(X))if(t.returnType.includes(e))return e;return null}X.FS_PROC,X.FS_DIR,X.FS_FILE;const te=new Map([["error",{name:"error",parameters:[],returnType:"string | null",description:"Returns the last filesystem error message, or null if no error occurred"}],["open",{name:"open",parameters:[{name:"path",type:"string",optional:!1},{name:"mode",type:"string",optional:!0,defaultValue:"r"},{name:"perm",type:"number",optional:!0,defaultValue:438}],returnType:"fs.file | null",description:"Opens a file and returns a file handle. Mode can be 'r' (read), 'w' (write), 'a' (append), etc."}],["fdopen",{name:"fdopen",parameters:[{name:"fd",type:"number",optional:!1},{name:"mode",type:"string",optional:!0,defaultValue:"r"}],returnType:"fs.file | null",description:"Creates a file handle from a file descriptor"}],["opendir",{name:"opendir",parameters:[{name:"path",type:"string",optional:!1}],returnType:"fs.dir | null",description:"Opens a directory and returns a directory handle"}],["popen",{name:"popen",parameters:[{name:"command",type:"string",optional:!1},{name:"mode",type:"string",optional:!0,defaultValue:"r"}],returnType:"fs.proc | null",description:"Opens a process pipe and returns a process handle"}],["readlink",{name:"readlink",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Reads the target of a symbolic link"}],["stat",{name:"stat",parameters:[{name:"path",type:"string",optional:!1}],returnType:"object | null",description:"Gets file status information (follows symbolic links)"}],["lstat",{name:"lstat",parameters:[{name:"path",type:"string",optional:!1}],returnType:"object | null",description:"Gets file status information (does not follow symbolic links)"}],["mkdir",{name:"mkdir",parameters:[{name:"path",type:"string",optional:!1},{name:"mode",type:"number",optional:!0,defaultValue:493}],returnType:"boolean",description:"Creates a directory. Returns true on success, false on failure"}],["rmdir",{name:"rmdir",parameters:[{name:"path",type:"string",optional:!1}],returnType:"boolean",description:"Removes an empty directory. Returns true on success, false on failure"}],["symlink",{name:"symlink",parameters:[{name:"target",type:"string",optional:!1},{name:"linkpath",type:"string",optional:!1}],returnType:"boolean",description:"Creates a symbolic link. Returns true on success, false on failure"}],["unlink",{name:"unlink",parameters:[{name:"path",type:"string",optional:!1}],returnType:"boolean",description:"Removes a file or symbolic link. Returns true on success, false on failure"}],["getcwd",{name:"getcwd",parameters:[],returnType:"string | null",description:"Gets the current working directory path"}],["chdir",{name:"chdir",parameters:[{name:"path",type:"string",optional:!1}],returnType:"boolean",description:"Changes the current working directory. Returns true on success, false on failure"}],["chmod",{name:"chmod",parameters:[{name:"path",type:"string",optional:!1},{name:"mode",type:"number",optional:!1}],returnType:"boolean | null",description:"Changes file permissions. Returns true on success, false on failure"}],["chown",{name:"chown",parameters:[{name:"path",type:"string",optional:!1},{name:"uid",type:"number",optional:!1},{name:"gid",type:"number",optional:!1}],returnType:"boolean | null",description:"Changes file ownership. Returns true on success, null on failure"}],["rename",{name:"rename",parameters:[{name:"oldpath",type:"string",optional:!1},{name:"newpath",type:"string",optional:!1}],returnType:"boolean",description:"Renames or moves a file. Returns true on success, false on failure"}],["glob",{name:"glob",parameters:[{name:"pattern",type:"string",optional:!1}],returnType:"array | null",description:"Finds files matching a pattern using shell wildcards"}],["dirname",{name:"dirname",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string",description:"Returns the directory portion of a path"}],["basename",{name:"basename",parameters:[{name:"path",type:"string",optional:!1},{name:"suffix",type:"string",optional:!0}],returnType:"string",description:"Returns the filename portion of a path, optionally removing suffix"}],["lsdir",{name:"lsdir",parameters:[{name:"path",type:"string",optional:!1}],returnType:"array | null",description:"Lists directory contents as an array of filenames"}],["mkstemp",{name:"mkstemp",parameters:[{name:"template",type:"string",optional:!1}],returnType:"fs.file | null",description:"Creates a unique temporary file and returns a file handle"}],["access",{name:"access",parameters:[{name:"path",type:"string",optional:!1},{name:"mode",type:"number",optional:!0,defaultValue:0}],returnType:"boolean",description:"Tests file accessibility. Returns true if accessible, false otherwise"}],["readfile",{name:"readfile",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Reads the entire contents of a file as a string"}],["writefile",{name:"writefile",parameters:[{name:"path",type:"string",optional:!1},{name:"content",type:"string",optional:!1},{name:"mode",type:"number",optional:!0,defaultValue:420}],returnType:"boolean",description:"Writes content to a file. Returns true on success, false on failure"}],["realpath",{name:"realpath",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Resolves a path to its canonical absolute form"}],["pipe",{name:"pipe",parameters:[],returnType:"array | null",description:"Creates a pipe and returns an array with read and write file handles"}],["dup2",{name:"dup2",parameters:[{name:"oldfd",type:"number",optional:!1},{name:"newfd",type:"number",optional:!1}],returnType:"boolean | null",description:"Duplicates file descriptor oldfd to newfd. Returns true on success, null on error"}],["mkdtemp",{name:"mkdtemp",parameters:[{name:"template",type:"string",optional:!0,defaultValue:"/tmp/XXXXXX"}],returnType:"string | null",description:"Creates a unique temporary directory using the given template. Returns the path of the created directory on success, null on error"}],["getcwd",{name:"getcwd",parameters:[],returnType:"string | null",description:"Gets the current working directory path"}],["chdir",{name:"chdir",parameters:[{name:"path",type:"string",optional:!1}],returnType:"boolean | null",description:"Changes the current working directory"}],["rename",{name:"rename",parameters:[{name:"oldpath",type:"string",optional:!1},{name:"newpath",type:"string",optional:!1}],returnType:"boolean | null",description:"Renames a file or directory"}],["symlink",{name:"symlink",parameters:[{name:"target",type:"string",optional:!1},{name:"linkpath",type:"string",optional:!1}],returnType:"boolean | null",description:"Creates a symbolic link"}],["glob",{name:"glob",parameters:[{name:"patterns",type:"string",optional:!1}],returnType:"array | null",description:"Matches file paths using glob patterns (variadic function)"}],["statvfs",{name:"statvfs",parameters:[{name:"path",type:"string",optional:!1}],returnType:"fs.statvfs | null",description:"Queries filesystem statistics for a given pathname. Returns an object with properties: bsize, frsize, blocks, bfree, bavail, files, ffree, favail, fsid, flag, namemax, freesize (frsize * bfree), totalsize (frsize * blocks). On Linux, an additional `type` field (filesystem magic number) is provided. Returns null on failure."}]]),ne=new Map([["bsize",{name:"bsize",type:"integer",description:"File system block size"}],["frsize",{name:"frsize",type:"integer",description:"Fragment size"}],["blocks",{name:"blocks",type:"integer",description:"Total number of blocks in the filesystem"}],["bfree",{name:"bfree",type:"integer",description:"Total number of free blocks"}],["bavail",{name:"bavail",type:"integer",description:"Free blocks available to unprivileged users"}],["files",{name:"files",type:"integer",description:"Total number of file nodes (inodes)"}],["ffree",{name:"ffree",type:"integer",description:"Total number of free file nodes"}],["favail",{name:"favail",type:"integer",description:"Free file nodes available to unprivileged users"}],["fsid",{name:"fsid",type:"integer",description:"File system ID"}],["flag",{name:"flag",type:"integer",description:"Mount flags (bitmask of ST_* constants)"}],["namemax",{name:"namemax",type:"integer",description:"Maximum filename length"}],["freesize",{name:"freesize",type:"integer",description:"Free space in bytes (frsize * bfree)"}],["totalsize",{name:"totalsize",type:"integer",description:"Total filesystem size in bytes (frsize * blocks)"}],["type",{name:"type",type:"integer",description:"Filesystem magic number from statfs (Linux only)"}]]);new class{getPropertyNames(){return Array.from(ne.keys())}getProperty(e){return ne.get(e)}getPropertyDocumentation(e){const t=ne.get(e);return t?`**(fs.statvfs property) ${t.name}**: \`${t.type}\`\n\n${t.description}`:""}};const re=new Map([["ST_RDONLY",1],["ST_NOSUID",2],["ST_NODEV",4],["ST_NOEXEC",8],["ST_SYNCHRONOUS",16],["ST_MANDLOCK",64],["ST_NOATIME",1024],["ST_NODIRATIME",2048],["ST_RELATIME",4096],["ST_NOSYMFOLLOW",256]]),ie=new Map([["ST_RDONLY","**(constant) ST_RDONLY** = 1\n\nRead-only filesystem"],["ST_NOSUID","**(constant) ST_NOSUID** = 2\n\nDo not allow set-user-identifier or set-group-identifier bits"],["ST_NODEV","**(constant) ST_NODEV** = 4\n\nDo not allow device files (Linux only)"],["ST_NOEXEC","**(constant) ST_NOEXEC** = 8\n\nDo not allow execution of binaries (Linux only)"],["ST_SYNCHRONOUS","**(constant) ST_SYNCHRONOUS** = 16\n\nSynchronous writes (Linux only)"],["ST_MANDLOCK","**(constant) ST_MANDLOCK** = 64\n\nMandatory locking (Linux only)"],["ST_NOATIME","**(constant) ST_NOATIME** = 1024\n\nDo not update access times (Linux only)"],["ST_NODIRATIME","**(constant) ST_NODIRATIME** = 2048\n\nDo not update directory access times (Linux only)"],["ST_RELATIME","**(constant) ST_RELATIME** = 4096\n\nUpdate access times relative to modification time (Linux only)"],["ST_NOSYMFOLLOW","**(constant) ST_NOSYMFOLLOW** = 256\n\nDo not follow symbolic links (Linux only)"]]);class oe{static instance;constructor(){}static getInstance(){return oe.instance||(oe.instance=new oe),oe.instance}getFunctionNames(){return Array.from(te.keys())}getFunction(e){return te.get(e)}isFsModuleFunction(e){return te.has(e)}getFunctionDocumentation(e){const t=te.get(e);if(!t)return"";const n=t.parameters.map(e=>{const t=e.optional?`${e.name}?: ${e.type}`:`${e.name}: ${e.type}`;return void 0!==e.defaultValue?`${t} = ${e.defaultValue}`:t}).join(", ");return`**fs.${t.name}(${n}): ${t.returnType}**\n\n${t.description}`}}const se=oe.getInstance(),ae={name:"fs",functions:te,constantDocumentation:ie,documentation:'## FS Module\n\n**File system operations for ucode scripts**\n\nThe fs module provides comprehensive file system functionality for reading, writing, and manipulating files and directories.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { open, readlink, stat } from \'fs\';\n\nlet file = open("file.txt", "r");\nlet target = readlink("/sys/class/net/eth0");\nlet info = stat("/etc/passwd");\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as fs from \'fs\';\n\nlet file = fs.open("file.txt", "r");\nlet content = file.read("all");\nfile.close();\n```\n\n### Available Functions\n\n**File operations:**\n- **`open()`** - Open files for reading/writing\n- **`fdopen()`** - Associate file descriptor with handle\n- **`popen()`** - Execute commands and handle I/O\n\n**Directory operations:**\n- **`opendir()`** - Open directories for reading\n- **`mkdir()`** - Create directories\n- **`rmdir()`** - Remove directories\n\n**File system information:**\n- **`stat()`** - Get file/directory information\n- **`lstat()`** - Get info without following symlinks\n- **`readlink()`** - Read symbolic link targets\n- **`statvfs()`** - Query filesystem statistics\n\n**File manipulation:**\n- **`unlink()`** - Remove files\n- **`symlink()`** - Create symbolic links\n- **`chmod()`** - Change file permissions\n- **`chown()`** - Change file ownership\n\n**Utility functions:**\n- **`error()`** - Get last error information\n- **`getcwd()`** - Get current working directory\n- **`chdir()`** - Change current directory\n\n### File Handle Objects\n\n- **`fs.file`** - File handles with read/write/seek methods\n- **`fs.proc`** - Process handles for command execution\n- **`fs.dir`** - Directory handles for listing entries\n\n*Hover over individual function names for detailed parameter and return type information.*',importValidation:{isValid:e=>te.has(e)||re.has(e),getValidImports:()=>[...Array.from(te.keys()),...Array.from(re.keys())]}},ce={typeName:"fs.statvfs",isPropertyBased:!0,methods:new Map,properties:ne,formatPropertyDoc:(e,t)=>`**(fs.statvfs property) ${t.name}**: \`${t.type}\`\n\n${t.description}`},le=e=>e;const ue="effect/GlobalValue";let pe;const de=(e,t)=>(pe||(globalThis[ue]??=new Map,pe=globalThis[ue]),pe.has(e)||pe.set(e,t()),pe.get(e)),me=e=>"function"==typeof e,he=function(e,t){if("function"==typeof e)return function(){return e(arguments)?t.apply(this,arguments):e=>t(e,...arguments)};switch(e){case 0:case 1:throw new RangeError(`Invalid arity ${e}`);case 2:return function(e,n){return arguments.length>=2?t(e,n):function(n){return t(n,e)}};case 3:return function(e,n,r){return arguments.length>=3?t(e,n,r):function(r){return t(r,e,n)}};case 4:return function(e,n,r,i){return arguments.length>=4?t(e,n,r,i):function(i){return t(i,e,n,r)}};case 5:return function(e,n,r,i,o){return arguments.length>=5?t(e,n,r,i,o):function(o){return t(o,e,n,r,i)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);const n=arguments;return function(e){return t(e,...n)}}}}(2,(e,t)=>{return((e=>"object"==typeof e&&null!==e)(n=e)||me(n))&&t in e;var n});Symbol.iterator;class fe{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new fe(this.self)}}const ge=Symbol.for("effect/Utils/YieldWrap");class ye{#e;constructor(e){this.#e=e}[ge](){return this.#e}}const Te=de("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),_e=de(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),Ne=Symbol.for("effect/Hash"),Re=e=>{if(!0===Te.enabled)return 0;switch(typeof e){case"number":return Ce(e);case"bigint":return Ae(e.toString(10));case"boolean":case"symbol":return Ae(String(e));case"string":return Ae(e);case"undefined":return Ae("undefined");case"function":case"object":return null===e?Ae("null"):e instanceof Date?Number.isNaN(e.getTime())?Ae("Invalid Date"):Re(e.toISOString()):e instanceof URL?Re(e.href):Se(e)?e[Ne]():Ee(e);default:throw new Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},Ee=e=>(_e.has(e)||_e.set(e,Ce(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER))),_e.get(e)),be=e=>t=>53*t^e,ve=e=>3221225471&e|e>>>1&1073741824,Se=e=>he(e,Ne),Ce=e=>{if(e!=e||e===1/0)return 0;let t=0|e;for(t!==e&&(t^=4294967295*e);e>4294967295;)t^=e/=4294967295;return ve(t)},Ae=e=>{let t=5381,n=e.length;for(;n;)t=33*t^e.charCodeAt(--n);return ve(t)},Oe=function(){if(1===arguments.length){const e=arguments[0];return function(t){return Object.defineProperty(e,Ne,{value:()=>t,enumerable:!1}),t}}const e=arguments[0],t=arguments[1];return Object.defineProperty(e,Ne,{value:()=>t,enumerable:!1}),t},Le=Symbol.for("effect/Equal");function Ie(){return 1===arguments.length?e=>De(e,arguments[0]):De(arguments[0],arguments[1])}function De(e,t){if(e===t)return!0;const n=typeof e;if(n!==typeof t)return!1;if("object"===n||"function"===n){if(null!==e&&null!==t){if(ke(e)&&ke(t))return!(Re(e)!==Re(t)||!e[Le](t))||!(!Te.enabled||!Te.tester)&&Te.tester(e,t);if(e instanceof Date&&t instanceof Date){const n=e.getTime(),r=t.getTime();return n===r||Number.isNaN(n)&&Number.isNaN(r)}if(e instanceof URL&&t instanceof URL)return e.href===t.href}if(Te.enabled){if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>De(e,t[n]));if(Object.getPrototypeOf(e)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){const n=Object.keys(e),r=Object.keys(t);if(n.length===r.length){for(const r of n)if(!(r in t)||!De(e[r],t[r]))return!!Te.tester&&Te.tester(e,t);return!0}}return!!Te.tester&&Te.tester(e,t)}}return!(!Te.enabled||!Te.tester)&&Te.tester(e,t)}const ke=e=>he(e,Le),Pe=Symbol.for("nodejs.util.inspect.custom"),xe=e=>{try{if(he(e,"toJSON")&&me(e.toJSON)&&0===e.toJSON.length)return e.toJSON();if(Array.isArray(e))return e.map(xe)}catch{return{}}return Ue(e)},we=e=>JSON.stringify(e,null,2),Me=Symbol.for("effect/Inspectable/Redactable"),Fe=de("effect/Inspectable/redactableState",()=>({fiberRefs:void 0})),Ue=e=>(e=>"object"==typeof e&&null!==e&&Me in e)(e)&&void 0!==Fe.fiberRefs?e[Me](Fe.fiberRefs):e,Ke=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let e=0,r=t.length;e<r;e++)n=t[e](n);return n}}};const Ge=()=>"3.19.19",Be=Symbol.for("effect/Effect"),We=Symbol.for("effect/Stream"),$e=Symbol.for("effect/Sink"),je=Symbol.for("effect/Channel"),qe={_R:e=>e,_E:e=>e,_A:e=>e,_V:Ge()},Ve={[Be]:qe,[We]:qe,[$e]:{_A:e=>e,_In:e=>e,_L:e=>e,_E:e=>e,_R:e=>e},[je]:{_Env:e=>e,_InErr:e=>e,_InElem:e=>e,_InDone:e=>e,_OutErr:e=>e,_OutElem:e=>e,_OutDone:e=>e},[Le](e){return this===e},[Ne](){return Oe(this,Ee(this))},[Symbol.iterator](){return new fe(new ye(this))},pipe(){return Ke(this,arguments)}},He=(Ne,Le,Symbol.for("effect/Option")),Ye={...Ve,[He]:{_A:e=>e},[Pe](){return this.toJSON()},toString(){return we(this.toJSON())}},Xe=Object.assign(Object.create(Ye),{_tag:"Some",_op:"Some",[Le](e){return Qe(e)&&et(e)&&Ie(this.value,e.value)},[Ne](){return Oe(this,be(Re(this._tag))(Re(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:xe(this.value)}}}),ze=Re("None"),Je=Object.assign(Object.create(Ye),{_tag:"None",_op:"None",[Le]:e=>Qe(e)&&Ze(e),[Ne]:()=>ze,toJSON(){return{_id:"Option",_tag:this._tag}}}),Qe=e=>he(e,He),Ze=e=>"None"===e._tag,et=e=>"Some"===e._tag,tt=Object.create(Je),nt=Symbol.for("effect/Either"),rt={...Ve,[nt]:{_R:e=>e},[Pe](){return this.toJSON()},toString(){return we(this.toJSON())}},it=Object.assign(Object.create(rt),{_tag:"Right",_op:"Right",[Le](e){return st(e)&&ct(e)&&Ie(this.right,e.right)},[Ne](){return be(Re(this._tag))(Re(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:xe(this.right)}}}),ot=Object.assign(Object.create(rt),{_tag:"Left",_op:"Left",[Le](e){return st(e)&&at(e)&&Ie(this.left,e.left)},[Ne](){return be(Re(this._tag))(Re(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:xe(this.left)}}}),st=e=>he(e,nt),at=e=>"Left"===e._tag,ct=e=>"Right"===e._tag,lt=()=>tt,ut=e=>{const t=Object.create(Xe);return t.value=e,t},pt=et,dt=e=>null==e?lt():ut(e);function mt(e){const t=Array.from(e.functions.keys()),n=e.constants?Array.from(e.constants.keys()):[],r=[...t,...n];return{moduleName:e.name,getFunctionNames:()=>t,getFunction:t=>dt(e.functions.get(t)),getFunctionDocumentation:t=>{const n=e.functions.get(t);return n?ut(function(e,t){let n=`**${function(e,t){const n=t.parameters.map(e=>e.optional&&void 0!==e.defaultValue?`[${e.name}: ${e.type}] = ${e.defaultValue}`:e.optional?`[${e.name}: ${e.type}]`:`${e.name}: ${e.type}`).join(", ");return`${t.name}(${n}): ${t.returnType}`}(0,t)}**\n\n${t.description}\n\n`;return t.parameters.length>0&&(n+="**Parameters:**\n",t.parameters.forEach(e=>{const t=e.optional?" (optional)":"",r=void 0!==e.defaultValue?` (default: ${e.defaultValue})`:"";n+=`- \`${e.name}\` (${e.type}${t}${r})\n`}),n+="\n"),n+=`**Returns:** \`${t.returnType}\``,n}(e.name,n)):lt()},getConstantNames:()=>n,getConstantDocumentation:t=>{if(e.constantDocumentation){const n=e.constantDocumentation.get(t);if(n)return ut(n)}if(e.constants){const n=e.constants.get(t);if(n)return ut(`**(constant) ${n.name}** = ${n.value}\n\n${n.description}`)}return lt()},isValidImport:e.importValidation?.isValid??(e=>r.includes(e)),getValidImports:e.importValidation?.getValidImports??(()=>r),getModuleDocumentation:()=>e.documentation}}function ht(e){if(e.isPropertyBased&&e.properties){const t=Array.from(e.properties.keys());return{objectType:e.typeName,isPropertyBased:!0,getMethodNames:()=>t,getMethod:t=>{const n=e.properties.get(t);return n?ut({name:n.name,parameters:[],returnType:n.type,description:n.description}):lt()},getMethodDocumentation:t=>{const n=e.properties.get(t);if(!n)return lt();const r=e.formatPropertyDoc?e.formatPropertyDoc(t,n):function(e,t){return`**(${e} property) ${t.name}**: \`${t.type}\`\n\n${t.description}`}(e.typeName,n);return ut(r)}}}const t=Array.from(e.methods.keys());return{objectType:e.typeName,...void 0!==e.isPropertyBased?{isPropertyBased:e.isPropertyBased}:{},getMethodNames:()=>t,getMethod:t=>dt(e.methods.get(t)),getMethodDocumentation:t=>{const n=e.methods.get(t);if(!n)return lt();const r=e.formatDoc?e.formatDoc(t,n):function(e,t){const n=t.parameters.map(e=>{const t=e.optional?`${e.name}?: ${e.type}`:`${e.name}: ${e.type}`;return void 0!==e.defaultValue?`${t} = ${e.defaultValue}`:t}).join(", ");return`**${e.includes(".")?e.split(".")[1]:e}.${t.name}(${n}): ${t.returnType}**\n\n${t.description}`}(e.typeName,n);return ut(r)}}}const ft=new Map([["request",{name:"request",parameters:[{name:"cmd",type:"integer",optional:!1},{name:"flags",type:"integer",optional:!0},{name:"payload",type:"object",optional:!0}],returnType:"object | null",description:'Send a netlink request to the routing subsystem. The cmd parameter specifies the RTM_* command to execute. Optional flags can modify the request behavior (NLM_F_*). The payload object contains command-specific attributes.\n\n**Example:**\n```ucode\n// Get all routes\nlet routes = request(RTM_GETROUTE, NLM_F_DUMP);\n\n// Add a new route\nlet result = request(RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL, {\n dst: "192.168.1.0/24",\n gateway: "192.168.1.1",\n oif: 2\n});\n```'}],["listener",{name:"listener",parameters:[{name:"callback",type:"function",optional:!1},{name:"cmds",type:"array",optional:!0},{name:"groups",type:"array",optional:!0}],returnType:"rtnl.listener",description:'Create an event listener for routing netlink messages. The callback function is called when events are received. Optional cmds array contains RTM_* command constants to listen for. Optional groups array contains multicast groups to join.\n\n**Example:**\n```ucode\n// Listen for route changes\nlet l = listener(function(msg) {\n printf("Route event: %J\\n", msg);\n}, [RTM_NEWROUTE, RTM_DELROUTE]);\n\n// Listen for link changes\nlet linkListener = listener(function(msg) {\n printf("Link event: %J\\n", msg);\n}, [RTM_NEWLINK, RTM_DELLINK]);\n```'}],["error",{name:"error",parameters:[],returnType:"string | null",description:'Returns the last rtnl error message, or null if no error occurred. This is typically called after a failed rtnl operation to get detailed error information.\n\n**Example:**\n```ucode\nlet result = request(RTM_GETROUTE, NLM_F_DUMP);\nif (!result) {\n let errorMsg = error();\n printf("RTNL error: %s\\n", errorMsg);\n}\n```'}]]),gt=new Map([["RTNL_FAMILY_IPMR",{name:"RTNL_FAMILY_IPMR",value:128,type:"integer",description:"IP multicast routing family"}],["RTNL_FAMILY_IP6MR",{name:"RTNL_FAMILY_IP6MR",value:129,type:"integer",description:"IPv6 multicast routing family"}],["RTNL_FAMILY_MAX",{name:"RTNL_FAMILY_MAX",value:129,type:"integer",description:"Maximum RTNL family value"}],["RTM_BASE",{name:"RTM_BASE",value:16,type:"integer",description:"Base RTM message type"}],["RTM_NEWLINK",{name:"RTM_NEWLINK",value:16,type:"integer",description:"Create new network interface"}],["RTM_DELLINK",{name:"RTM_DELLINK",value:17,type:"integer",description:"Delete network interface"}],["RTM_GETLINK",{name:"RTM_GETLINK",value:18,type:"integer",description:"Get network interface information"}],["RTM_SETLINK",{name:"RTM_SETLINK",value:19,type:"integer",description:"Set network interface configuration"}],["RTM_NEWADDR",{name:"RTM_NEWADDR",value:20,type:"integer",description:"Add new address"}],["RTM_DELADDR",{name:"RTM_DELADDR",value:21,type:"integer",description:"Delete address"}],["RTM_GETADDR",{name:"RTM_GETADDR",value:22,type:"integer",description:"Get address information"}],["RTM_NEWROUTE",{name:"RTM_NEWROUTE",value:24,type:"integer",description:"Add new route"}],["RTM_DELROUTE",{name:"RTM_DELROUTE",value:25,type:"integer",description:"Delete route"}],["RTM_GETROUTE",{name:"RTM_GETROUTE",value:26,type:"integer",description:"Get route information"}],["RTM_NEWNEIGH",{name:"RTM_NEWNEIGH",value:28,type:"integer",description:"Add new neighbor entry"}],["RTM_DELNEIGH",{name:"RTM_DELNEIGH",value:29,type:"integer",description:"Delete neighbor entry"}],["RTM_GETNEIGH",{name:"RTM_GETNEIGH",value:30,type:"integer",description:"Get neighbor information"}],["RTM_NEWRULE",{name:"RTM_NEWRULE",value:32,type:"integer",description:"Add new routing rule"}],["RTM_DELRULE",{name:"RTM_DELRULE",value:33,type:"integer",description:"Delete routing rule"}],["RTM_GETRULE",{name:"RTM_GETRULE",value:34,type:"integer",description:"Get routing rule information"}],["RTM_NEWQDISC",{name:"RTM_NEWQDISC",value:36,type:"integer",description:"Add new queueing discipline"}],["RTM_DELQDISC",{name:"RTM_DELQDISC",value:37,type:"integer",description:"Delete queueing discipline"}],["RTM_GETQDISC",{name:"RTM_GETQDISC",value:38,type:"integer",description:"Get queueing discipline information"}],["RTM_NEWTCLASS",{name:"RTM_NEWTCLASS",value:40,type:"integer",description:"Add new traffic class"}],["RTM_DELTCLASS",{name:"RTM_DELTCLASS",value:41,type:"integer",description:"Delete traffic class"}],["RTM_GETTCLASS",{name:"RTM_GETTCLASS",value:42,type:"integer",description:"Get traffic class information"}],["RTM_NEWTFILTER",{name:"RTM_NEWTFILTER",value:44,type:"integer",description:"Add new traffic filter"}],["RTM_DELTFILTER",{name:"RTM_DELTFILTER",value:45,type:"integer",description:"Delete traffic filter"}],["RTM_GETTFILTER",{name:"RTM_GETTFILTER",value:46,type:"integer",description:"Get traffic filter information"}],["RTM_NEWACTION",{name:"RTM_NEWACTION",value:48,type:"integer",description:"Add new traffic control action"}],["RTM_DELACTION",{name:"RTM_DELACTION",value:49,type:"integer",description:"Delete traffic control action"}],["RTM_GETACTION",{name:"RTM_GETACTION",value:50,type:"integer",description:"Get traffic control action information"}],["RTM_NEWPREFIX",{name:"RTM_NEWPREFIX",value:52,type:"integer",description:"Add new prefix"}],["RTM_GETMULTICAST",{name:"RTM_GETMULTICAST",value:58,type:"integer",description:"Get multicast information"}],["RTM_GETANYCAST",{name:"RTM_GETANYCAST",value:62,type:"integer",description:"Get anycast information"}],["RTM_NEWNEIGHTBL",{name:"RTM_NEWNEIGHTBL",value:64,type:"integer",description:"Create new neighbor table"}],["RTM_GETNEIGHTBL",{name:"RTM_GETNEIGHTBL",value:66,type:"integer",description:"Get neighbor table information"}],["RTM_SETNEIGHTBL",{name:"RTM_SETNEIGHTBL",value:67,type:"integer",description:"Set neighbor table configuration"}],["RTM_NEWNDUSEROPT",{name:"RTM_NEWNDUSEROPT",value:68,type:"integer",description:"New neighbor discovery user option"}],["RTM_NEWADDRLABEL",{name:"RTM_NEWADDRLABEL",value:72,type:"integer",description:"Add new address label"}],["RTM_DELADDRLABEL",{name:"RTM_DELADDRLABEL",value:73,type:"integer",description:"Delete address label"}],["RTM_GETADDRLABEL",{name:"RTM_GETADDRLABEL",value:74,type:"integer",description:"Get address label information"}],["RTM_GETDCB",{name:"RTM_GETDCB",value:78,type:"integer",description:"Get DCB information"}],["RTM_SETDCB",{name:"RTM_SETDCB",value:79,type:"integer",description:"Set DCB configuration"}],["RTM_NEWNETCONF",{name:"RTM_NEWNETCONF",value:80,type:"integer",description:"New network configuration"}],["RTM_DELNETCONF",{name:"RTM_DELNETCONF",value:81,type:"integer",description:"Delete network configuration"}],["RTM_GETNETCONF",{name:"RTM_GETNETCONF",value:82,type:"integer",description:"Get network configuration"}],["RTM_NEWMDB",{name:"RTM_NEWMDB",value:84,type:"integer",description:"Add new multicast database entry"}],["RTM_DELMDB",{name:"RTM_DELMDB",value:85,type:"integer",description:"Delete multicast database entry"}],["RTM_GETMDB",{name:"RTM_GETMDB",value:86,type:"integer",description:"Get multicast database information"}],["RTM_NEWNSID",{name:"RTM_NEWNSID",value:88,type:"integer",description:"Add new network namespace ID"}],["RTM_DELNSID",{name:"RTM_DELNSID",value:89,type:"integer",description:"Delete network namespace ID"}],["RTM_GETNSID",{name:"RTM_GETNSID",value:90,type:"integer",description:"Get network namespace ID"}],["RTM_NEWSTATS",{name:"RTM_NEWSTATS",value:92,type:"integer",description:"New statistics"}],["RTM_GETSTATS",{name:"RTM_GETSTATS",value:94,type:"integer",description:"Get statistics"}],["RTM_NEWCACHEREPORT",{name:"RTM_NEWCACHEREPORT",value:96,type:"integer",description:"New cache report"}],["RTM_NEWCHAIN",{name:"RTM_NEWCHAIN",value:100,type:"integer",description:"Add new chain"}],["RTM_DELCHAIN",{name:"RTM_DELCHAIN",value:101,type:"integer",description:"Delete chain"}],["RTM_GETCHAIN",{name:"RTM_GETCHAIN",value:102,type:"integer",description:"Get chain information"}],["RTM_NEWNEXTHOP",{name:"RTM_NEWNEXTHOP",value:104,type:"integer",description:"Add new next hop"}],["RTM_DELNEXTHOP",{name:"RTM_DELNEXTHOP",value:105,type:"integer",description:"Delete next hop"}],["RTM_GETNEXTHOP",{name:"RTM_GETNEXTHOP",value:106,type:"integer",description:"Get next hop information"}],["RTM_NEWLINKPROP",{name:"RTM_NEWLINKPROP",value:108,type:"integer",description:"Add new link property"}],["RTM_DELLINKPROP",{name:"RTM_DELLINKPROP",value:109,type:"integer",description:"Delete link property"}],["RTM_GETLINKPROP",{name:"RTM_GETLINKPROP",value:110,type:"integer",description:"Get link property information"}],["RTM_NEWVLAN",{name:"RTM_NEWVLAN",value:112,type:"integer",description:"Add new VLAN"}],["RTM_DELVLAN",{name:"RTM_DELVLAN",value:113,type:"integer",description:"Delete VLAN"}],["RTM_GETVLAN",{name:"RTM_GETVLAN",value:114,type:"integer",description:"Get VLAN information"}],["RTN_UNSPEC",{name:"RTN_UNSPEC",value:0,type:"integer",description:"Unknown route type"}],["RTN_UNICAST",{name:"RTN_UNICAST",value:1,type:"integer",description:"Gateway or direct route"}],["RTN_LOCAL",{name:"RTN_LOCAL",value:2,type:"integer",description:"Accept locally"}],["RTN_BROADCAST",{name:"RTN_BROADCAST",value:3,type:"integer",description:"Accept locally as broadcast"}],["RTN_ANYCAST",{name:"RTN_ANYCAST",value:4,type:"integer",description:"Accept locally as broadcast, but send as unicast"}],["RTN_MULTICAST",{name:"RTN_MULTICAST",value:5,type:"integer",description:"Multicast route"}],["RTN_BLACKHOLE",{name:"RTN_BLACKHOLE",value:6,type:"integer",description:"Drop packets"}],["RTN_UNREACHABLE",{name:"RTN_UNREACHABLE",value:7,type:"integer",description:"Destination unreachable"}],["RTN_PROHIBIT",{name:"RTN_PROHIBIT",value:8,type:"integer",description:"Administratively prohibited"}],["RTN_THROW",{name:"RTN_THROW",value:9,type:"integer",description:"Not in this table"}],["RTN_NAT",{name:"RTN_NAT",value:10,type:"integer",description:"Translate this address"}],["RTN_XRESOLVE",{name:"RTN_XRESOLVE",value:11,type:"integer",description:"Use external resolver"}],["RTPROT_UNSPEC",{name:"RTPROT_UNSPEC",value:0,type:"integer",description:"Unspecified protocol"}],["RTPROT_REDIRECT",{name:"RTPROT_REDIRECT",value:1,type:"integer",description:"Route installed by ICMP redirects"}],["RTPROT_KERNEL",{name:"RTPROT_KERNEL",value:2,type:"integer",description:"Route installed by kernel"}],["RTPROT_BOOT",{name:"RTPROT_BOOT",value:3,type:"integer",description:"Route installed during boot"}],["RTPROT_STATIC",{name:"RTPROT_STATIC",value:4,type:"integer",description:"Route installed by administrator"}],["RTPROT_GATED",{name:"RTPROT_GATED",value:8,type:"integer",description:"GateD routing daemon"}],["RTPROT_RA",{name:"RTPROT_RA",value:9,type:"integer",description:"RDISC/ND router advertisements"}],["RTPROT_MRT",{name:"RTPROT_MRT",value:10,type:"integer",description:"Merit MRT routing daemon"}],["RTPROT_ZEBRA",{name:"RTPROT_ZEBRA",value:11,type:"integer",description:"Zebra routing daemon"}],["RTPROT_BIRD",{name:"RTPROT_BIRD",value:12,type:"integer",description:"BIRD routing daemon"}],["RTPROT_DNROUTED",{name:"RTPROT_DNROUTED",value:13,type:"integer",description:"DECnet routing daemon"}],["RTPROT_XORP",{name:"RTPROT_XORP",value:14,type:"integer",description:"XORP routing daemon"}],["RTPROT_NTK",{name:"RTPROT_NTK",value:15,type:"integer",description:"Netsukuku routing daemon"}],["RTPROT_DHCP",{name:"RTPROT_DHCP",value:16,type:"integer",description:"DHCP client"}],["RTPROT_MROUTED",{name:"RTPROT_MROUTED",value:17,type:"integer",description:"Multicast daemon"}],["RTPROT_KEEPALIVED",{name:"RTPROT_KEEPALIVED",value:18,type:"integer",description:"Keepalived daemon"}],["RTPROT_BABEL",{name:"RTPROT_BABEL",value:42,type:"integer",description:"Babel routing daemon"}],["RTPROT_BGP",{name:"RTPROT_BGP",value:186,type:"integer",description:"BGP routing protocol"}],["RTPROT_ISIS",{name:"RTPROT_ISIS",value:187,type:"integer",description:"ISIS routing protocol"}],["RTPROT_OSPF",{name:"RTPROT_OSPF",value:188,type:"integer",description:"OSPF routing protocol"}],["RTPROT_RIP",{name:"RTPROT_RIP",value:189,type:"integer",description:"RIP routing protocol"}],["RTPROT_EIGRP",{name:"RTPROT_EIGRP",value:192,type:"integer",description:"EIGRP routing protocol"}],["RT_SCOPE_UNIVERSE",{name:"RT_SCOPE_UNIVERSE",value:0,type:"integer",description:"Global route"}],["RT_SCOPE_SITE",{name:"RT_SCOPE_SITE",value:200,type:"integer",description:"Site-local route"}],["RT_SCOPE_LINK",{name:"RT_SCOPE_LINK",value:253,type:"integer",description:"Link-local route"}],["RT_SCOPE_HOST",{name:"RT_SCOPE_HOST",value:254,type:"integer",description:"Host-local route"}],["RT_SCOPE_NOWHERE",{name:"RT_SCOPE_NOWHERE",value:255,type:"integer",description:"Nowhere route"}],["RT_TABLE_UNSPEC",{name:"RT_TABLE_UNSPEC",value:0,type:"integer",description:"Unspecified routing table"}],["RT_TABLE_COMPAT",{name:"RT_TABLE_COMPAT",value:252,type:"integer",description:"Compatibility routing table"}],["RT_TABLE_DEFAULT",{name:"RT_TABLE_DEFAULT",value:253,type:"integer",description:"Default routing table"}],["RT_TABLE_MAIN",{name:"RT_TABLE_MAIN",value:254,type:"integer",description:"Main routing table"}],["RT_TABLE_LOCAL",{name:"RT_TABLE_LOCAL",value:255,type:"integer",description:"Local routing table"}],["RT_TABLE_MAX",{name:"RT_TABLE_MAX",value:4294967295,type:"integer",description:"Maximum routing table value"}],["RTM_F_NOTIFY",{name:"RTM_F_NOTIFY",value:256,type:"integer",description:"Notify user of route change"}],["RTM_F_CLONED",{name:"RTM_F_CLONED",value:512,type:"integer",description:"This route is cloned"}],["RTM_F_EQUALIZE",{name:"RTM_F_EQUALIZE",value:1024,type:"integer",description:"Multipath equalizer"}],["RTM_F_PREFIX",{name:"RTM_F_PREFIX",value:2048,type:"integer",description:"Prefix addresses"}],["RTM_F_LOOKUP_TABLE",{name:"RTM_F_LOOKUP_TABLE",value:4096,type:"integer",description:"Set rtm_table to FIB lookup result"}],["RTM_F_FIB_MATCH",{name:"RTM_F_FIB_MATCH",value:8192,type:"integer",description:"Return full fib lookup match"}],["RTM_F_OFFLOAD",{name:"RTM_F_OFFLOAD",value:16384,type:"integer",description:"Route is offloaded"}],["RTM_F_TRAP",{name:"RTM_F_TRAP",value:32768,type:"integer",description:"Route is trapping packets"}],["RTM_F_OFFLOAD_FAILED",{name:"RTM_F_OFFLOAD_FAILED",value:536870912,type:"integer",description:"Route offload failed"}],["RTA_UNSPEC",{name:"RTA_UNSPEC",value:0,type:"integer",description:"Unspecified attribute"}],["RTA_DST",{name:"RTA_DST",value:1,type:"integer",description:"Destination address"}],["RTA_SRC",{name:"RTA_SRC",value:2,type:"integer",description:"Source address"}],["RTA_IIF",{name:"RTA_IIF",value:3,type:"integer",description:"Input interface index"}],["RTA_OIF",{name:"RTA_OIF",value:4,type:"integer",description:"Output interface index"}],["RTA_GATEWAY",{name:"RTA_GATEWAY",value:5,type:"integer",description:"Gateway address"}],["RTA_PRIORITY",{name:"RTA_PRIORITY",value:6,type:"integer",description:"Route priority"}],["RTA_PREFSRC",{name:"RTA_PREFSRC",value:7,type:"integer",description:"Preferred source address"}],["RTA_METRICS",{name:"RTA_METRICS",value:8,type:"integer",description:"Route metrics"}],["RTA_MULTIPATH",{name:"RTA_MULTIPATH",value:9,type:"integer",description:"Multipath route data"}],["RTA_PROTOINFO",{name:"RTA_PROTOINFO",value:10,type:"integer",description:"Protocol info (deprecated)"}],["RTA_FLOW",{name:"RTA_FLOW",value:11,type:"integer",description:"Route flow"}],["RTA_CACHEINFO",{name:"RTA_CACHEINFO",value:12,type:"integer",description:"Route cache information"}],["RTA_SESSION",{name:"RTA_SESSION",value:13,type:"integer",description:"Session data (deprecated)"}],["RTA_MP_ALGO",{name:"RTA_MP_ALGO",value:14,type:"integer",description:"Multipath algorithm (deprecated)"}],["RTA_TABLE",{name:"RTA_TABLE",value:15,type:"integer",description:"Routing table ID"}],["RTA_MARK",{name:"RTA_MARK",value:16,type:"integer",description:"Netfilter mark"}],["RTA_MFC_STATS",{name:"RTA_MFC_STATS",value:17,type:"integer",description:"Multicast forwarding cache stats"}],["RTA_VIA",{name:"RTA_VIA",value:18,type:"integer",description:"Gateway in different AF"}],["RTA_NEWDST",{name:"RTA_NEWDST",value:19,type:"integer",description:"New destination for redirect"}],["RTA_PREF",{name:"RTA_PREF",value:20,type:"integer",description:"Route preference"}],["RTA_ENCAP_TYPE",{name:"RTA_ENCAP_TYPE",value:21,type:"integer",description:"Encapsulation type"}],["RTA_ENCAP",{name:"RTA_ENCAP",value:22,type:"integer",description:"Encapsulation data"}],["RTA_EXPIRES",{name:"RTA_EXPIRES",value:23,type:"integer",description:"Route expiration time"}],["RTA_PAD",{name:"RTA_PAD",value:24,type:"integer",description:"Padding for alignment"}],["RTA_UID",{name:"RTA_UID",value:25,type:"integer",description:"User ID"}],["RTA_TTL_PROPAGATE",{name:"RTA_TTL_PROPAGATE",value:26,type:"integer",description:"TTL propagation"}],["RTA_IP_PROTO",{name:"RTA_IP_PROTO",value:27,type:"integer",description:"IP protocol"}],["RTA_SPORT",{name:"RTA_SPORT",value:28,type:"integer",description:"Source port"}],["RTA_DPORT",{name:"RTA_DPORT",value:29,type:"integer",description:"Destination port"}],["RTA_NH_ID",{name:"RTA_NH_ID",value:30,type:"integer",description:"Next hop ID"}],["RTNH_F_DEAD",{name:"RTNH_F_DEAD",value:1,type:"integer",description:"Nexthop is dead (used by multipath)"}],["RTNH_F_PERVASIVE",{name:"RTNH_F_PERVASIVE",value:2,type:"integer",description:"Do recursive gateway lookup"}],["RTNH_F_ONLINK",{name:"RTNH_F_ONLINK",value:4,type:"integer",description:"Gateway is forced on link"}],["RTNH_F_OFFLOAD",{name:"RTNH_F_OFFLOAD",value:8,type:"integer",description:"Nexthop is offloaded"}],["RTNH_F_LINKDOWN",{name:"RTNH_F_LINKDOWN",value:16,type:"integer",description:"Carrier-down on nexthop"}],["RTNH_F_UNRESOLVED",{name:"RTNH_F_UNRESOLVED",value:32,type:"integer",description:"The entry is unresolved (ipmr)"}],["RTNH_F_TRAP",{name:"RTNH_F_TRAP",value:64,type:"integer",description:"Nexthop is trapping packets"}],["BRIDGE_FLAGS_MASTER",{name:"BRIDGE_FLAGS_MASTER",value:1,type:"integer",description:"Bridge command to/from master"}],["BRIDGE_FLAGS_SELF",{name:"BRIDGE_FLAGS_SELF",value:2,type:"integer",description:"Bridge command to/from lowerdev"}],["BRIDGE_MODE_UNSPEC",{name:"BRIDGE_MODE_UNSPEC",value:0,type:"integer",description:"Unspecified bridge mode"}],["BRIDGE_MODE_HAIRPIN",{name:"BRIDGE_MODE_HAIRPIN",value:1,type:"integer",description:"Hairpin bridge mode"}],["BRIDGE_MODE_VEB",{name:"BRIDGE_MODE_VEB",value:0,type:"integer",description:"Default loopback mode"}],["BRIDGE_MODE_VEPA",{name:"BRIDGE_MODE_VEPA",value:1,type:"integer",description:"802.1Qbg defined VEPA mode"}],["BRIDGE_MODE_UNDEF",{name:"BRIDGE_MODE_UNDEF",value:65535,type:"integer",description:"Mode undefined"}],["BRIDGE_VLAN_INFO_MASTER",{name:"BRIDGE_VLAN_INFO_MASTER",value:1,type:"integer",description:"Operate on Bridge device as well"}],["BRIDGE_VLAN_INFO_PVID",{name:"BRIDGE_VLAN_INFO_PVID",value:2,type:"integer",description:"VLAN is PVID, ingress untagged"}],["BRIDGE_VLAN_INFO_UNTAGGED",{name:"BRIDGE_VLAN_INFO_UNTAGGED",value:4,type:"integer",description:"VLAN egresses untagged"}],["BRIDGE_VLAN_INFO_RANGE_BEGIN",{name:"BRIDGE_VLAN_INFO_RANGE_BEGIN",value:8,type:"integer",description:"VLAN is start of vlan range"}],["BRIDGE_VLAN_INFO_RANGE_END",{name:"BRIDGE_VLAN_INFO_RANGE_END",value:16,type:"integer",description:"VLAN is end of vlan range"}],["BRIDGE_VLAN_INFO_BRENTRY",{name:"BRIDGE_VLAN_INFO_BRENTRY",value:32,type:"integer",description:"Global bridge VLAN entry"}],["MACVLAN_MODE_BRIDGE",{name:"MACVLAN_MODE_BRIDGE",value:4,type:"integer",description:"Talk to bridge ports directly"}],["LINK_XSTATS_TYPE_BRIDGE",{name:"LINK_XSTATS_TYPE_BRIDGE",value:1,type:"integer",description:"Bridge extended statistics type"}],["NLM_F_REQUEST",{name:"NLM_F_REQUEST",value:1,type:"integer",description:"This message is a request"}],["NLM_F_MULTI",{name:"NLM_F_MULTI",value:2,type:"integer",description:"Multipart message"}],["NLM_F_ACK",{name:"NLM_F_ACK",value:4,type:"integer",description:"Request an acknowledgment on errors"}],["NLM_F_ECHO",{name:"NLM_F_ECHO",value:8,type:"integer",description:"Echo this request"}],["NLM_F_DUMP_INTR",{name:"NLM_F_DUMP_INTR",value:16,type:"integer",description:"Dump was interrupted"}],["NLM_F_DUMP_FILTERED",{name:"NLM_F_DUMP_FILTERED",value:32,type:"integer",description:"Dump was filtered"}],["NLM_F_ROOT",{name:"NLM_F_ROOT",value:256,type:"integer",description:"Specify tree root"}],["NLM_F_MATCH",{name:"NLM_F_MATCH",value:512,type:"integer",description:"Dump all matching entries"}],["NLM_F_DUMP",{name:"NLM_F_DUMP",value:768,type:"integer",description:"Dump the table"}],["NLM_F_ATOMIC",{name:"NLM_F_ATOMIC",value:1024,type:"integer",description:"Use atomic operations"}],["NLM_F_CREATE",{name:"NLM_F_CREATE",value:1024,type:"integer",description:"Create if it does not exist"}],["NLM_F_EXCL",{name:"NLM_F_EXCL",value:512,type:"integer",description:"Do not touch, if it exists"}],["NLM_F_REPLACE",{name:"NLM_F_REPLACE",value:256,type:"integer",description:"Replace existing matching object"}],["NLM_F_STRICT_CHK",{name:"NLM_F_STRICT_CHK",value:32768,type:"integer",description:"Strict parameter checking"}],["AF_UNSPEC",{name:"AF_UNSPEC",value:0,type:"integer",description:"Unspecified address family"}],["AF_INET",{name:"AF_INET",value:2,type:"integer",description:"IPv4 address family"}],["AF_INET6",{name:"AF_INET6",value:10,type:"integer",description:"IPv6 address family"}],["AF_MPLS",{name:"AF_MPLS",value:28,type:"integer",description:"MPLS address family"}],["AF_BRIDGE",{name:"AF_BRIDGE",value:7,type:"integer",description:"Bridge address family"}],["RTNLGRP_NONE",{name:"RTNLGRP_NONE",value:0,type:"integer",description:"No multicast group"}],["RTNLGRP_LINK",{name:"RTNLGRP_LINK",value:1,type:"integer",description:"Link layer multicast group"}],["RTNLGRP_NOTIFY",{name:"RTNLGRP_NOTIFY",value:2,type:"integer",description:"Routing notify multicast group"}],["RTNLGRP_NEIGH",{name:"RTNLGRP_NEIGH",value:3,type:"integer",description:"Neighbor multicast group"}],["RTNLGRP_TC",{name:"RTNLGRP_TC",value:4,type:"integer",description:"Traffic control multicast group"}],["RTNLGRP_IPV4_IFADDR",{name:"RTNLGRP_IPV4_IFADDR",value:5,type:"integer",description:"IPv4 interface address multicast group"}],["RTNLGRP_IPV4_MROUTE",{name:"RTNLGRP_IPV4_MROUTE",value:6,type:"integer",description:"IPv4 multicast route group"}],["RTNLGRP_IPV4_ROUTE",{name:"RTNLGRP_IPV4_ROUTE",value:7,type:"integer",description:"IPv4 route multicast group"}],["RTNLGRP_IPV4_RULE",{name:"RTNLGRP_IPV4_RULE",value:8,type:"integer",description:"IPv4 rule multicast group"}],["RTNLGRP_IPV6_IFADDR",{name:"RTNLGRP_IPV6_IFADDR",value:9,type:"integer",description:"IPv6 interface address multicast group"}],["RTNLGRP_IPV6_MROUTE",{name:"RTNLGRP_IPV6_MROUTE",value:10,type:"integer",description:"IPv6 multicast route group"}],["RTNLGRP_IPV6_ROUTE",{name:"RTNLGRP_IPV6_ROUTE",value:11,type:"integer",description:"IPv6 route multicast group"}],["RTNLGRP_IPV6_IFINFO",{name:"RTNLGRP_IPV6_IFINFO",value:12,type:"integer",description:"IPv6 interface info multicast group"}],["RTNLGRP_DECnet_IFADDR",{name:"RTNLGRP_DECnet_IFADDR",value:13,type:"integer",description:"DECnet interface address multicast group"}],["RTNLGRP_DECnet_ROUTE",{name:"RTNLGRP_DECnet_ROUTE",value:15,type:"integer",description:"DECnet route multicast group"}],["RTNLGRP_DECnet_RULE",{name:"RTNLGRP_DECnet_RULE",value:16,type:"integer",description:"DECnet rule multicast group"}],["RTNLGRP_IPV6_PREFIX",{name:"RTNLGRP_IPV6_PREFIX",value:18,type:"integer",description:"IPv6 prefix multicast group"}],["RTNLGRP_IPV6_RULE",{name:"RTNLGRP_IPV6_RULE",value:19,type:"integer",description:"IPv6 rule multicast group"}],["RTNLGRP_ND_USEROPT",{name:"RTNLGRP_ND_USEROPT",value:20,type:"integer",description:"Neighbor discovery user option multicast group"}],["RTNLGRP_PHONET_IFADDR",{name:"RTNLGRP_PHONET_IFADDR",value:21,type:"integer",description:"Phonet interface address multicast group"}],["RTNLGRP_PHONET_ROUTE",{name:"RTNLGRP_PHONET_ROUTE",value:22,type:"integer",description:"Phonet route multicast group"}],["RTNLGRP_DCB",{name:"RTNLGRP_DCB",value:23,type:"integer",description:"DCB multicast group"}],["RTNLGRP_IPV4_NETCONF",{name:"RTNLGRP_IPV4_NETCONF",value:24,type:"integer",description:"IPv4 network configuration multicast group"}],["RTNLGRP_IPV6_NETCONF",{name:"RTNLGRP_IPV6_NETCONF",value:25,type:"integer",description:"IPv6 network configuration multicast group"}],["RTNLGRP_MDB",{name:"RTNLGRP_MDB",value:26,type:"integer",description:"Multicast database multicast group"}],["RTNLGRP_MPLS_ROUTE",{name:"RTNLGRP_MPLS_ROUTE",value:27,type:"integer",description:"MPLS route multicast group"}],["RTNLGRP_NSID",{name:"RTNLGRP_NSID",value:28,type:"integer",description:"Network namespace ID multicast group"}],["RTNLGRP_MPLS_NETCONF",{name:"RTNLGRP_MPLS_NETCONF",value:29,type:"integer",description:"MPLS network configuration multicast group"}],["RTNLGRP_IPV4_MROUTE_R",{name:"RTNLGRP_IPV4_MROUTE_R",value:30,type:"integer",description:"IPv4 multicast route resolver multicast group"}],["RTNLGRP_IPV6_MROUTE_R",{name:"RTNLGRP_IPV6_MROUTE_R",value:31,type:"integer",description:"IPv6 multicast route resolver multicast group"}],["RTNLGRP_NEXTHOP",{name:"RTNLGRP_NEXTHOP",value:32,type:"integer",description:"Next hop multicast group"}],["RTNLGRP_BRVLAN",{name:"RTNLGRP_BRVLAN",value:33,type:"integer",description:"Bridge VLAN multicast group"}],["TCA_ROOT_UNSPEC",{name:"TCA_ROOT_UNSPEC",value:0,type:"integer",description:"Unspecified TC action root"}],["TCA_ROOT_TAB",{name:"TCA_ROOT_TAB",value:1,type:"integer",description:"TC action table"}],["TCA_ROOT_FLAGS",{name:"TCA_ROOT_FLAGS",value:2,type:"integer",description:"TC action root flags"}],["TCA_ROOT_COUNT",{name:"TCA_ROOT_COUNT",value:3,type:"integer",description:"TC action root count"}],["TCA_ROOT_TIME_DELTA",{name:"TCA_ROOT_TIME_DELTA",value:4,type:"integer",description:"TC action root time delta in msecs"}],["TCA_FLAG_LARGE_DUMP_ON",{name:"TCA_FLAG_LARGE_DUMP_ON",value:1,type:"integer",description:"Large dump flag"}],["TCA_ACT_FLAG_LARGE_DUMP_ON",{name:"TCA_ACT_FLAG_LARGE_DUMP_ON",value:1,type:"integer",description:"Large dump flag for actions"}],["TCA_ACT_FLAG_TERSE_DUMP",{name:"TCA_ACT_FLAG_TERSE_DUMP",value:2,type:"integer",description:"Terse dump flag for actions"}],["RTEXT_FILTER_VF",{name:"RTEXT_FILTER_VF",value:1,type:"integer",description:"Virtual function filter"}],["RTEXT_FILTER_BRVLAN",{name:"RTEXT_FILTER_BRVLAN",value:2,type:"integer",description:"Bridge VLAN filter"}],["RTEXT_FILTER_BRVLAN_COMPRESSED",{name:"RTEXT_FILTER_BRVLAN_COMPRESSED",value:4,type:"integer",description:"Bridge VLAN compressed filter"}],["RTEXT_FILTER_SKIP_STATS",{name:"RTEXT_FILTER_SKIP_STATS",value:8,type:"integer",description:"Skip statistics filter"}],["RTEXT_FILTER_MRP",{name:"RTEXT_FILTER_MRP",value:16,type:"integer",description:"Media Redundancy Protocol filter"}],["RTEXT_FILTER_CFM_CONFIG",{name:"RTEXT_FILTER_CFM_CONFIG",value:32,type:"integer",description:"Connectivity Fault Management config filter"}],["RTEXT_FILTER_CFM_STATUS",{name:"RTEXT_FILTER_CFM_STATUS",value:64,type:"integer",description:"Connectivity Fault Management status filter"}]]),yt={name:"rtnl",functions:ft,constants:gt,documentation:"## RTNL Module\n\n**Routing Netlink functionality for ucode scripts**\n\nThe rtnl module provides routing netlink functionality for ucode, allowing you to interact with the Linux kernel's routing and network interface subsystem.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { request, listener, error, RTM_GETROUTE, NLM_F_DUMP } from 'rtnl';\n\nlet routes = request(RTM_GETROUTE, NLM_F_DUMP);\nif (!routes) print('Error: ', error(), '\\n');\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as rtnl from 'rtnl';\n\nlet routes = rtnl.request(rtnl.RTM_GETROUTE, rtnl.NLM_F_DUMP);\n```\n\n### Available Functions\n\n- **`request()`** - Send a netlink request to the routing subsystem\n- **`listener()`** - Create an event listener for routing netlink messages\n- **`error()`** - Get the last rtnl error message\n\n*Hover over individual function and constant names for detailed information.*",importValidation:{isValid:e=>ft.has(e)||gt.has(e)||"const"===e,getValidImports:()=>[...Array.from(ft.keys()),...Array.from(gt.keys()),"const"]}},Tt=()=>Array.from(gt.keys()),_t=e=>gt.get(e),Nt=e=>{const t=gt.get(e);return t?`**${t.name}** = \`${t.value}\`\n\n*${t.type}*\n\n${t.description}`:""},Rt=new Map([["error",{name:"error",parameters:[],returnType:"string | null",description:'Returns the last nl80211 error message, or null if no error occurred. This is typically called after a failed nl80211 operation to get detailed error information.\n\n**Example:**\n```ucode\nlet result = request(NL80211_CMD_GET_WIPHY);\nif (!result) {\n let errorMsg = error();\n printf("NL80211 error: %s\\n", errorMsg);\n}\n```'}],["request",{name:"request",parameters:[{name:"cmd",type:"integer",optional:!1},{name:"flags",type:"integer",optional:!0},{name:"payload",type:"object",optional:!0}],returnType:"object | null",description:'Sends a netlink request to the nl80211 subsystem. The cmd parameter specifies the NL80211_CMD_* command to execute. Optional flags can modify the request behavior (NLM_F_*). The payload object contains command-specific attributes.\n\n**Example:**\n```ucode\n// Get wiphy information\nlet wiphy = request(NL80211_CMD_GET_WIPHY, NLM_F_DUMP);\n\n// Start access point\nlet result = request(NL80211_CMD_START_AP, NLM_F_ACK, {\n ssid: "MyAP",\n channel: 6\n});\n```'}],["waitfor",{name:"waitfor",parameters:[{name:"cmds",type:"array",optional:!1},{name:"timeout",type:"integer",optional:!0}],returnType:"object | null",description:'Waits for specific nl80211 commands to be received. The cmds array contains NL80211_CMD_* constants to wait for. Optional timeout specifies the maximum wait time in milliseconds. Returns the received message object or null on timeout.\n\n**Example:**\n```ucode\n// Wait for scan completion\nlet result = waitfor([NL80211_CMD_NEW_SCAN_RESULTS, NL80211_CMD_SCAN_ABORTED], 5000);\nif (result) {\n printf("Scan completed: %J\\n", result);\n} else {\n printf("Scan timeout\\n");\n}\n```'}],["listener",{name:"listener",parameters:[{name:"callback",type:"function",optional:!1},{name:"cmds",type:"array",optional:!1}],returnType:"nl80211.listener",description:'Creates an event listener for nl80211 messages. The callback function is called when any of the specified commands (NL80211_CMD_* constants) are received. Returns a listener object with set_commands() and close() methods.\n\n**Example:**\n```ucode\n// Listen for scan results\nlet l = listener(function(msg) {\n printf("Scan event: %J\\n", msg);\n}, [NL80211_CMD_NEW_SCAN_RESULTS]);\n\n// Listen for connection events\nlet connListener = listener(function(msg) {\n printf("Connection event: %J\\n", msg);\n}, [NL80211_CMD_CONNECT, NL80211_CMD_DISCONNECT]);\n```'}]]),Et=new Map([["NLM_F_ACK",{name:"NLM_F_ACK",value:4,type:"integer",description:"Request an acknowledgment on errors"}],["NLM_F_ACK_TLVS",{name:"NLM_F_ACK_TLVS",value:512,type:"integer",description:"Extended ACK TLVs were included"}],["NLM_F_APPEND",{name:"NLM_F_APPEND",value:2048,type:"integer",description:"Append the new entry to the end of the list"}],["NLM_F_ATOMIC",{name:"NLM_F_ATOMIC",value:1024,type:"integer",description:"Use atomic operations"}],["NLM_F_CAPPED",{name:"NLM_F_CAPPED",value:256,type:"integer",description:"Dump was capped"}],["NLM_F_CREATE",{name:"NLM_F_CREATE",value:1024,type:"integer",description:"Create if it does not exist"}],["NLM_F_DUMP",{name:"NLM_F_DUMP",value:768,type:"integer",description:"Dump the table"}],["NLM_F_DUMP_FILTERED",{name:"NLM_F_DUMP_FILTERED",value:32,type:"integer",description:"Dump was filtered"}],["NLM_F_DUMP_INTR",{name:"NLM_F_DUMP_INTR",value:16,type:"integer",description:"Dump was interrupted"}],["NLM_F_ECHO",{name:"NLM_F_ECHO",value:8,type:"integer",description:"Echo this request"}],["NLM_F_EXCL",{name:"NLM_F_EXCL",value:512,type:"integer",description:"Do not touch, if it exists"}],["NLM_F_MATCH",{name:"NLM_F_MATCH",value:512,type:"integer",description:"Dump all matching entries"}],["NLM_F_MULTI",{name:"NLM_F_MULTI",value:2,type:"integer",description:"Multipart message"}],["NLM_F_NONREC",{name:"NLM_F_NONREC",value:256,type:"integer",description:"Do not delete recursively"}],["NLM_F_REPLACE",{name:"NLM_F_REPLACE",value:256,type:"integer",description:"Replace existing matching object"}],["NLM_F_REQUEST",{name:"NLM_F_REQUEST",value:1,type:"integer",description:"This message is a request"}],["NLM_F_ROOT",{name:"NLM_F_ROOT",value:256,type:"integer",description:"Specify tree root"}],["NL80211_CMD_GET_WIPHY",{name:"NL80211_CMD_GET_WIPHY",value:1,type:"integer",description:"Get wireless physical device info"}],["NL80211_CMD_SET_WIPHY",{name:"NL80211_CMD_SET_WIPHY",value:2,type:"integer",description:"Set wireless physical device configuration"}],["NL80211_CMD_NEW_WIPHY",{name:"NL80211_CMD_NEW_WIPHY",value:3,type:"integer",description:"Create new wireless physical device"}],["NL80211_CMD_DEL_WIPHY",{name:"NL80211_CMD_DEL_WIPHY",value:4,type:"integer",description:"Delete wireless physical device"}],["NL80211_CMD_GET_INTERFACE",{name:"NL80211_CMD_GET_INTERFACE",value:5,type:"integer",description:"Get wireless interface info"}],["NL80211_CMD_SET_INTERFACE",{name:"NL80211_CMD_SET_INTERFACE",value:6,type:"integer",description:"Set wireless interface configuration"}],["NL80211_CMD_NEW_INTERFACE",{name:"NL80211_CMD_NEW_INTERFACE",value:7,type:"integer",description:"Create new wireless interface"}],["NL80211_CMD_DEL_INTERFACE",{name:"NL80211_CMD_DEL_INTERFACE",value:8,type:"integer",description:"Delete wireless interface"}],["NL80211_CMD_GET_KEY",{name:"NL80211_CMD_GET_KEY",value:9,type:"integer",description:"Get encryption key"}],["NL80211_CMD_SET_KEY",{name:"NL80211_CMD_SET_KEY",value:10,type:"integer",description:"Set encryption key"}],["NL80211_CMD_NEW_KEY",{name:"NL80211_CMD_NEW_KEY",value:11,type:"integer",description:"Add new encryption key"}],["NL80211_CMD_DEL_KEY",{name:"NL80211_CMD_DEL_KEY",value:12,type:"integer",description:"Delete encryption key"}],["NL80211_CMD_GET_BEACON",{name:"NL80211_CMD_GET_BEACON",value:13,type:"integer",description:"Get beacon information"}],["NL80211_CMD_SET_BEACON",{name:"NL80211_CMD_SET_BEACON",value:14,type:"integer",description:"Set beacon configuration"}],["NL80211_CMD_START_AP",{name:"NL80211_CMD_START_AP",value:15,type:"integer",description:"Start access point"}],["NL80211_CMD_NEW_BEACON",{name:"NL80211_CMD_NEW_BEACON",value:15,type:"integer",description:"New beacon (alias for START_AP)"}],["NL80211_CMD_STOP_AP",{name:"NL80211_CMD_STOP_AP",value:16,type:"integer",description:"Stop access point"}],["NL80211_CMD_DEL_BEACON",{name:"NL80211_CMD_DEL_BEACON",value:16,type:"integer",description:"Delete beacon (alias for STOP_AP)"}],["NL80211_CMD_GET_STATION",{name:"NL80211_CMD_GET_STATION",value:17,type:"integer",description:"Get station information"}],["NL80211_CMD_SET_STATION",{name:"NL80211_CMD_SET_STATION",value:18,type:"integer",description:"Set station configuration"}],["NL80211_CMD_NEW_STATION",{name:"NL80211_CMD_NEW_STATION",value:19,type:"integer",description:"Add new station"}],["NL80211_CMD_DEL_STATION",{name:"NL80211_CMD_DEL_STATION",value:20,type:"integer",description:"Delete station"}],["NL80211_CMD_GET_MPATH",{name:"NL80211_CMD_GET_MPATH",value:21,type:"integer",description:"Get mesh path"}],["NL80211_CMD_SET_MPATH",{name:"NL80211_CMD_SET_MPATH",value:22,type:"integer",description:"Set mesh path"}],["NL80211_CMD_NEW_MPATH",{name:"NL80211_CMD_NEW_MPATH",value:23,type:"integer",description:"Add new mesh path"}],["NL80211_CMD_DEL_MPATH",{name:"NL80211_CMD_DEL_MPATH",value:24,type:"integer",description:"Delete mesh path"}],["NL80211_CMD_SET_BSS",{name:"NL80211_CMD_SET_BSS",value:25,type:"integer",description:"Set BSS configuration"}],["NL80211_CMD_SET_REG",{name:"NL80211_CMD_SET_REG",value:26,type:"integer",description:"Set regulatory domain"}],["NL80211_CMD_REQ_SET_REG",{name:"NL80211_CMD_REQ_SET_REG",value:27,type:"integer",description:"Request regulatory domain setting"}],["NL80211_CMD_GET_MESH_CONFIG",{name:"NL80211_CMD_GET_MESH_CONFIG",value:28,type:"integer",description:"Get mesh configuration"}],["NL80211_CMD_SET_MESH_CONFIG",{name:"NL80211_CMD_SET_MESH_CONFIG",value:29,type:"integer",description:"Set mesh configuration"}],["NL80211_CMD_GET_REG",{name:"NL80211_CMD_GET_REG",value:31,type:"integer",description:"Get regulatory domain"}],["NL80211_CMD_GET_SCAN",{name:"NL80211_CMD_GET_SCAN",value:32,type:"integer",description:"Get scan results"}],["NL80211_CMD_TRIGGER_SCAN",{name:"NL80211_CMD_TRIGGER_SCAN",value:33,type:"integer",description:"Trigger wireless scan"}],["NL80211_CMD_NEW_SCAN_RESULTS",{name:"NL80211_CMD_NEW_SCAN_RESULTS",value:34,type:"integer",description:"New scan results available"}],["NL80211_CMD_SCAN_ABORTED",{name:"NL80211_CMD_SCAN_ABORTED",value:35,type:"integer",description:"Scan was aborted"}],["NL80211_CMD_REG_CHANGE",{name:"NL80211_CMD_REG_CHANGE",value:36,type:"integer",description:"Regulatory domain changed"}],["NL80211_CMD_AUTHENTICATE",{name:"NL80211_CMD_AUTHENTICATE",value:37,type:"integer",description:"Authenticate with AP"}],["NL80211_CMD_ASSOCIATE",{name:"NL80211_CMD_ASSOCIATE",value:38,type:"integer",description:"Associate with AP"}],["NL80211_CMD_DEAUTHENTICATE",{name:"NL80211_CMD_DEAUTHENTICATE",value:39,type:"integer",description:"Deauthenticate from AP"}],["NL80211_CMD_DISASSOCIATE",{name:"NL80211_CMD_DISASSOCIATE",value:40,type:"integer",description:"Disassociate from AP"}],["NL80211_CMD_MICHAEL_MIC_FAILURE",{name:"NL80211_CMD_MICHAEL_MIC_FAILURE",value:41,type:"integer",description:"Michael MIC failure detected"}],["NL80211_CMD_REG_BEACON_HINT",{name:"NL80211_CMD_REG_BEACON_HINT",value:42,type:"integer",description:"Regulatory beacon hint"}],["NL80211_CMD_JOIN_IBSS",{name:"NL80211_CMD_JOIN_IBSS",value:43,type:"integer",description:"Join IBSS network"}],["NL80211_CMD_LEAVE_IBSS",{name:"NL80211_CMD_LEAVE_IBSS",value:44,type:"integer",description:"Leave IBSS network"}],["NL80211_CMD_TESTMODE",{name:"NL80211_CMD_TESTMODE",value:45,type:"integer",description:"Enter test mode"}],["NL80211_CMD_CONNECT",{name:"NL80211_CMD_CONNECT",value:46,type:"integer",description:"Connect to network"}],["NL80211_CMD_ROAM",{name:"NL80211_CMD_ROAM",value:47,type:"integer",description:"Roaming event"}],["NL80211_CMD_DISCONNECT",{name:"NL80211_CMD_DISCONNECT",value:48,type:"integer",description:"Disconnect from network"}],["NL80211_CMD_SET_WIPHY_NETNS",{name:"NL80211_CMD_SET_WIPHY_NETNS",value:49,type:"integer",description:"Set wiphy network namespace"}],["NL80211_CMD_GET_SURVEY",{name:"NL80211_CMD_GET_SURVEY",value:50,type:"integer",description:"Get channel survey"}],["NL80211_CMD_NEW_SURVEY_RESULTS",{name:"NL80211_CMD_NEW_SURVEY_RESULTS",value:51,type:"integer",description:"New survey results"}],["NL80211_CMD_SET_PMKSA",{name:"NL80211_CMD_SET_PMKSA",value:52,type:"integer",description:"Set PMKSA cache entry"}],["NL80211_CMD_DEL_PMKSA",{name:"NL80211_CMD_DEL_PMKSA",value:53,type:"integer",description:"Delete PMKSA cache entry"}],["NL80211_CMD_FLUSH_PMKSA",{name:"NL80211_CMD_FLUSH_PMKSA",value:54,type:"integer",description:"Flush PMKSA cache"}],["NL80211_CMD_REMAIN_ON_CHANNEL",{name:"NL80211_CMD_REMAIN_ON_CHANNEL",value:55,type:"integer",description:"Remain on channel"}],["NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL",{name:"NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL",value:56,type:"integer",description:"Cancel remain on channel"}],["NL80211_CMD_SET_TX_BITRATE_MASK",{name:"NL80211_CMD_SET_TX_BITRATE_MASK",value:57,type:"integer",description:"Set TX bitrate mask"}],["NL80211_CMD_REGISTER_FRAME",{name:"NL80211_CMD_REGISTER_FRAME",value:58,type:"integer",description:"Register for frame events"}],["NL80211_CMD_REGISTER_ACTION",{name:"NL80211_CMD_REGISTER_ACTION",value:58,type:"integer",description:"Register for action frame events"}],["NL80211_CMD_FRAME",{name:"NL80211_CMD_FRAME",value:59,type:"integer",description:"Frame event"}],["NL80211_CMD_ACTION",{name:"NL80211_CMD_ACTION",value:59,type:"integer",description:"Action frame event"}],["NL80211_CMD_FRAME_TX_STATUS",{name:"NL80211_CMD_FRAME_TX_STATUS",value:60,type:"integer",description:"Frame TX status"}],["NL80211_CMD_ACTION_TX_STATUS",{name:"NL80211_CMD_ACTION_TX_STATUS",value:60,type:"integer",description:"Action frame TX status"}],["NL80211_CMD_SET_POWER_SAVE",{name:"NL80211_CMD_SET_POWER_SAVE",value:61,type:"integer",description:"Set power save mode"}],["NL80211_CMD_GET_POWER_SAVE",{name:"NL80211_CMD_GET_POWER_SAVE",value:62,type:"integer",description:"Get power save mode"}],["NL80211_CMD_SET_CQM",{name:"NL80211_CMD_SET_CQM",value:63,type:"integer",description:"Set connection quality monitoring"}],["NL80211_CMD_NOTIFY_CQM",{name:"NL80211_CMD_NOTIFY_CQM",value:64,type:"integer",description:"Connection quality monitoring notification"}],["NL80211_CMD_SET_CHANNEL",{name:"NL80211_CMD_SET_CHANNEL",value:65,type:"integer",description:"Set channel"}],["NL80211_CMD_SET_WDS_PEER",{name:"NL80211_CMD_SET_WDS_PEER",value:66,type:"integer",description:"Set WDS peer"}],["NL80211_CMD_FRAME_WAIT_CANCEL",{name:"NL80211_CMD_FRAME_WAIT_CANCEL",value:67,type:"integer",description:"Cancel frame wait"}],["NL80211_CMD_JOIN_MESH",{name:"NL80211_CMD_JOIN_MESH",value:68,type:"integer",description:"Join mesh network"}],["NL80211_CMD_LEAVE_MESH",{name:"NL80211_CMD_LEAVE_MESH",value:69,type:"integer",description:"Leave mesh network"}],["NL80211_CMD_UNPROT_DEAUTHENTICATE",{name:"NL80211_CMD_UNPROT_DEAUTHENTICATE",value:70,type:"integer",description:"Unprotected deauthentication"}],["NL80211_CMD_UNPROT_DISASSOCIATE",{name:"NL80211_CMD_UNPROT_DISASSOCIATE",value:71,type:"integer",description:"Unprotected disassociation"}],["NL80211_CMD_NEW_PEER_CANDIDATE",{name:"NL80211_CMD_NEW_PEER_CANDIDATE",value:72,type:"integer",description:"New peer candidate"}],["NL80211_CMD_GET_WOWLAN",{name:"NL80211_CMD_GET_WOWLAN",value:73,type:"integer",description:"Get Wake-on-WLAN configuration"}],["NL80211_CMD_SET_WOWLAN",{name:"NL80211_CMD_SET_WOWLAN",value:74,type:"integer",description:"Set Wake-on-WLAN configuration"}],["NL80211_CMD_START_SCHED_SCAN",{name:"NL80211_CMD_START_SCHED_SCAN",value:75,type:"integer",description:"Start scheduled scan"}],["NL80211_CMD_STOP_SCHED_SCAN",{name:"NL80211_CMD_STOP_SCHED_SCAN",value:76,type:"integer",description:"Stop scheduled scan"}],["NL80211_CMD_SCHED_SCAN_RESULTS",{name:"NL80211_CMD_SCHED_SCAN_RESULTS",value:77,type:"integer",description:"Scheduled scan results"}],["NL80211_CMD_SCHED_SCAN_STOPPED",{name:"NL80211_CMD_SCHED_SCAN_STOPPED",value:78,type:"integer",description:"Scheduled scan stopped"}],["NL80211_CMD_SET_REKEY_OFFLOAD",{name:"NL80211_CMD_SET_REKEY_OFFLOAD",value:79,type:"integer",description:"Set rekey offload"}],["NL80211_CMD_PMKSA_CANDIDATE",{name:"NL80211_CMD_PMKSA_CANDIDATE",value:80,type:"integer",description:"PMKSA candidate"}],["NL80211_CMD_TDLS_OPER",{name:"NL80211_CMD_TDLS_OPER",value:81,type:"integer",description:"TDLS operation"}],["NL80211_CMD_TDLS_MGMT",{name:"NL80211_CMD_TDLS_MGMT",value:82,type:"integer",description:"TDLS management"}],["NL80211_CMD_UNEXPECTED_FRAME",{name:"NL80211_CMD_UNEXPECTED_FRAME",value:83,type:"integer",description:"Unexpected frame received"}],["NL80211_CMD_PROBE_CLIENT",{name:"NL80211_CMD_PROBE_CLIENT",value:84,type:"integer",description:"Probe client"}],["NL80211_CMD_REGISTER_BEACONS",{name:"NL80211_CMD_REGISTER_BEACONS",value:85,type:"integer",description:"Register for beacon events"}],["NL80211_CMD_UNEXPECTED_4ADDR_FRAME",{name:"NL80211_CMD_UNEXPECTED_4ADDR_FRAME",value:86,type:"integer",description:"Unexpected 4-address frame"}],["NL80211_CMD_SET_NOACK_MAP",{name:"NL80211_CMD_SET_NOACK_MAP",value:87,type:"integer",description:"Set no-ACK map"}],["NL80211_CMD_CH_SWITCH_NOTIFY",{name:"NL80211_CMD_CH_SWITCH_NOTIFY",value:88,type:"integer",description:"Channel switch notification"}],["NL80211_CMD_START_P2P_DEVICE",{name:"NL80211_CMD_START_P2P_DEVICE",value:89,type:"integer",description:"Start P2P device"}],["NL80211_CMD_STOP_P2P_DEVICE",{name:"NL80211_CMD_STOP_P2P_DEVICE",value:90,type:"integer",description:"Stop P2P device"}],["NL80211_CMD_CONN_FAILED",{name:"NL80211_CMD_CONN_FAILED",value:91,type:"integer",description:"Connection failed"}],["NL80211_CMD_SET_MCAST_RATE",{name:"NL80211_CMD_SET_MCAST_RATE",value:92,type:"integer",description:"Set multicast rate"}],["NL80211_CMD_SET_MAC_ACL",{name:"NL80211_CMD_SET_MAC_ACL",value:93,type:"integer",description:"Set MAC ACL"}],["NL80211_CMD_RADAR_DETECT",{name:"NL80211_CMD_RADAR_DETECT",value:94,type:"integer",description:"Radar detection"}],["NL80211_CMD_GET_PROTOCOL_FEATURES",{name:"NL80211_CMD_GET_PROTOCOL_FEATURES",value:95,type:"integer",description:"Get protocol features"}],["NL80211_CMD_UPDATE_FT_IES",{name:"NL80211_CMD_UPDATE_FT_IES",value:96,type:"integer",description:"Update fast transition IEs"}],["NL80211_CMD_FT_EVENT",{name:"NL80211_CMD_FT_EVENT",value:97,type:"integer",description:"Fast transition event"}],["NL80211_CMD_CRIT_PROTOCOL_START",{name:"NL80211_CMD_CRIT_PROTOCOL_START",value:98,type:"integer",description:"Start critical protocol"}],["NL80211_CMD_CRIT_PROTOCOL_STOP",{name:"NL80211_CMD_CRIT_PROTOCOL_STOP",value:99,type:"integer",description:"Stop critical protocol"}],["NL80211_CMD_GET_COALESCE",{name:"NL80211_CMD_GET_COALESCE",value:100,type:"integer",description:"Get coalesce configuration"}],["NL80211_CMD_SET_COALESCE",{name:"NL80211_CMD_SET_COALESCE",value:101,type:"integer",description:"Set coalesce configuration"}],["NL80211_CMD_CHANNEL_SWITCH",{name:"NL80211_CMD_CHANNEL_SWITCH",value:102,type:"integer",description:"Channel switch"}],["NL80211_CMD_VENDOR",{name:"NL80211_CMD_VENDOR",value:103,type:"integer",description:"Vendor-specific command"}],["NL80211_CMD_SET_QOS_MAP",{name:"NL80211_CMD_SET_QOS_MAP",value:104,type:"integer",description:"Set QoS map"}],["NL80211_CMD_ADD_TX_TS",{name:"NL80211_CMD_ADD_TX_TS",value:105,type:"integer",description:"Add TX traffic stream"}],["NL80211_CMD_DEL_TX_TS",{name:"NL80211_CMD_DEL_TX_TS",value:106,type:"integer",description:"Delete TX traffic stream"}],["NL80211_CMD_GET_MPP",{name:"NL80211_CMD_GET_MPP",value:107,type:"integer",description:"Get mesh proxy path"}],["NL80211_CMD_JOIN_OCB",{name:"NL80211_CMD_JOIN_OCB",value:108,type:"integer",description:"Join OCB network"}],["NL80211_CMD_LEAVE_OCB",{name:"NL80211_CMD_LEAVE_OCB",value:109,type:"integer",description:"Leave OCB network"}],["NL80211_CMD_CH_SWITCH_STARTED_NOTIFY",{name:"NL80211_CMD_CH_SWITCH_STARTED_NOTIFY",value:110,type:"integer",description:"Channel switch started notification"}],["NL80211_CMD_TDLS_CHANNEL_SWITCH",{name:"NL80211_CMD_TDLS_CHANNEL_SWITCH",value:111,type:"integer",description:"TDLS channel switch"}],["NL80211_CMD_TDLS_CANCEL_CHANNEL_SWITCH",{name:"NL80211_CMD_TDLS_CANCEL_CHANNEL_SWITCH",value:112,type:"integer",description:"Cancel TDLS channel switch"}],["NL80211_IFTYPE_ADHOC",{name:"NL80211_IFTYPE_ADHOC",value:1,type:"integer",description:"Ad-hoc network interface"}],["NL80211_IFTYPE_STATION",{name:"NL80211_IFTYPE_STATION",value:2,type:"integer",description:"Station interface"}],["NL80211_IFTYPE_AP",{name:"NL80211_IFTYPE_AP",value:3,type:"integer",description:"Access point interface"}],["NL80211_IFTYPE_AP_VLAN",{name:"NL80211_IFTYPE_AP_VLAN",value:4,type:"integer",description:"AP VLAN interface"}],["NL80211_IFTYPE_WDS",{name:"NL80211_IFTYPE_WDS",value:5,type:"integer",description:"Wireless distribution system interface"}],["NL80211_IFTYPE_MONITOR",{name:"NL80211_IFTYPE_MONITOR",value:6,type:"integer",description:"Monitor interface"}],["NL80211_IFTYPE_MESH_POINT",{name:"NL80211_IFTYPE_MESH_POINT",value:7,type:"integer",description:"Mesh point interface"}],["NL80211_IFTYPE_P2P_CLIENT",{name:"NL80211_IFTYPE_P2P_CLIENT",value:8,type:"integer",description:"P2P client interface"}],["NL80211_IFTYPE_P2P_GO",{name:"NL80211_IFTYPE_P2P_GO",value:9,type:"integer",description:"P2P group owner interface"}],["NL80211_IFTYPE_P2P_DEVICE",{name:"NL80211_IFTYPE_P2P_DEVICE",value:10,type:"integer",description:"P2P device interface"}],["NL80211_IFTYPE_OCB",{name:"NL80211_IFTYPE_OCB",value:11,type:"integer",description:"Outside context of BSS interface"}],["HWSIM_CMD_REGISTER",{name:"HWSIM_CMD_REGISTER",value:1,type:"integer",description:"Register hwsim instance"}],["HWSIM_CMD_FRAME",{name:"HWSIM_CMD_FRAME",value:2,type:"integer",description:"Frame transmission/reception"}],["HWSIM_CMD_TX_INFO_FRAME",{name:"HWSIM_CMD_TX_INFO_FRAME",value:3,type:"integer",description:"TX info frame"}],["HWSIM_CMD_NEW_RADIO",{name:"HWSIM_CMD_NEW_RADIO",value:4,type:"integer",description:"Create new radio"}],["HWSIM_CMD_DEL_RADIO",{name:"HWSIM_CMD_DEL_RADIO",value:5,type:"integer",description:"Delete radio"}],["HWSIM_CMD_GET_RADIO",{name:"HWSIM_CMD_GET_RADIO",value:6,type:"integer",description:"Get radio information"}],["HWSIM_CMD_ADD_MAC_ADDR",{name:"HWSIM_CMD_ADD_MAC_ADDR",value:7,type:"integer",description:"Add MAC address"}],["HWSIM_CMD_DEL_MAC_ADDR",{name:"HWSIM_CMD_DEL_MAC_ADDR",value:8,type:"integer",description:"Delete MAC address"}],["HWSIM_CMD_START_PMSR",{name:"HWSIM_CMD_START_PMSR",value:9,type:"integer",description:"Start peer measurement"}],["HWSIM_CMD_ABORT_PMSR",{name:"HWSIM_CMD_ABORT_PMSR",value:10,type:"integer",description:"Abort peer measurement"}],["HWSIM_CMD_REPORT_PMSR",{name:"HWSIM_CMD_REPORT_PMSR",value:11,type:"integer",description:"Report peer measurement"}]]),bt=new Map([["set_commands",{name:"set_commands",parameters:[{name:"cmds",type:"array",optional:!1}],returnType:"null",description:"Set the list of NL80211_CMD_* commands to listen for."}],["close",{name:"close",parameters:[],returnType:"null",description:"Close the listener and stop monitoring nl80211 events."}]]),vt={name:"nl80211",functions:Rt,constants:Et,importValidation:{isValid:e=>Rt.has(e)||Et.has(e)||"const"===e,getValidImports:()=>[...Array.from(Rt.keys()),...Array.from(Et.keys()),"const"]},documentation:"## NL80211 Module\n\n**WiFi/802.11 networking interface for ucode scripts**\n\nThe nl80211 module provides access to the Linux kernel's nl80211 subsystem for managing WiFi interfaces and wireless networking operations.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { request, listener, NL80211_CMD_GET_WIPHY, NLM_F_DUMP } from 'nl80211';\n\nlet wiphy = request(NL80211_CMD_GET_WIPHY, NLM_F_DUMP);\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as nl80211 from 'nl80211';\n\nlet wiphy = nl80211.request(nl80211.NL80211_CMD_GET_WIPHY, nl80211.NLM_F_DUMP);\n```\n\n### Available Functions\n\n- **`error()`** - Get last nl80211 error message\n- **`request()`** - Send netlink request to nl80211 subsystem\n- **`waitfor()`** - Wait for specific nl80211 commands\n- **`listener()`** - Create event listener for nl80211 messages\n\n### Constants\n\n**Netlink Message Flags:** NLM_F_ACK, NLM_F_DUMP, NLM_F_REQUEST, NLM_F_CREATE, NLM_F_EXCL, ...\n\n**NL80211 Commands:** NL80211_CMD_GET_WIPHY, NL80211_CMD_GET_INTERFACE, NL80211_CMD_TRIGGER_SCAN, NL80211_CMD_CONNECT, ...\n\n**Interface Types:** NL80211_IFTYPE_STATION, NL80211_IFTYPE_AP, NL80211_IFTYPE_MONITOR, ...\n\n*Hover over individual function names and constants for detailed parameter and return type information.*"},St={typeName:"nl80211.listener",methods:bt};var Ct;function At(e){return{type:"object",moduleName:e}}!function(e){e.NL80211_LISTENER="nl80211.listener"}(Ct||(Ct={}));const Ot=()=>Array.from(Et.keys()),Lt=e=>Et.get(e),It=e=>{const t=Et.get(e);return t?`**${t.name}** = \`${t.value}\`\n\n*${t.type}*\n\n${t.description}`:""},Dt=e=>{const t=Object.create(it);return t.right=e,t},kt=e=>{const t=Object.create(ot);return t.left=e,t},Pt=st,xt=at,wt=["debug","digest","fs","io","log","math","nl80211","resolv","rtnl","socket","struct","ubus","uci","uloop","zlib"],Mt=new Map([["memdump",{name:"memdump",parameters:[{name:"file",type:"string | module:fs.file | module:fs.proc",optional:!1}],returnType:"boolean | null",description:"Write a memory dump report to the given file. Returns `true` if the report has been written, `null` if the file could not be opened or if the handle was invalid."}],["traceback",{name:"traceback",parameters:[{name:"level",type:"number",optional:!0,defaultValue:1}],returnType:"module:debug.StackTraceEntry[]",description:"Capture call stack trace. The optional level parameter controls how many calls up the trace should start. Returns an array of stack trace entries describing the function invocations up to the point where `traceback()` is called."}],["sourcepos",{name:"sourcepos",parameters:[],returnType:"module:debug.SourcePosition | null",description:"Obtain information about the current source position. Returns a dictionary containing the filename, line number and line byte offset of the call site. Returns `null` if this function was invoked from C code."}],["getinfo",{name:"getinfo",parameters:[{name:"value",type:"any",optional:!1}],returnType:"module:debug.ValueInformation | null",description:"Obtain information about the given value. Allows querying internal information about the given ucode value, such as the current reference count, the mark bit state etc. Returns a dictionary with value type specific details."}],["getlocal",{name:"getlocal",parameters:[{name:"level",type:"number",optional:!0,defaultValue:1},{name:"variable",type:"string | number",optional:!1}],returnType:"module:debug.LocalInfo | null",description:"Obtain local variable. Retrieves information about the specified local variable at the given call stack depth. The variable to query might be either specified by name or by its index."}],["setlocal",{name:"setlocal",parameters:[{name:"level",type:"number",optional:!0,defaultValue:1},{name:"variable",type:"string | number",optional:!1},{name:"value",type:"any",optional:!0,defaultValue:null}],returnType:"module:debug.LocalInfo | null",description:"Set local variable. Manipulates the value of the specified local variable at the given call stack depth. The variable to update might be either specified by name or by its index."}],["getupval",{name:"getupval",parameters:[{name:"target",type:"function | number",optional:!1},{name:"variable",type:"string | number",optional:!1}],returnType:"module:debug.UpvalInfo | null",description:"Obtain captured variable (upvalue). Retrieves information about the specified captured variable associated with the given function value or the invoked function at the given call stack depth."}],["setupval",{name:"setupval",parameters:[{name:"target",type:"function | number",optional:!1},{name:"variable",type:"string | number",optional:!1},{name:"value",type:"any",optional:!1}],returnType:"module:debug.UpvalInfo | null",description:"Set upvalue. Manipulates the value of the specified captured variable associated with the given function value or the invoked function at the given call stack depth."}]]),Ft={name:"debug",functions:Mt,documentation:"## Debug Module\n\n**Runtime debug functionality for ucode scripts**\n\nThe debug module provides comprehensive debugging and introspection capabilities for ucode applications.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { memdump, traceback } from 'debug';\n\nlet stacktrace = traceback(1);\nmemdump(\"/tmp/dump.txt\");\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as debug from 'debug';\n\nlet stacktrace = debug.traceback(1);\ndebug.memdump(\"/tmp/dump.txt\");\n```\n\n### Available Functions\n\n- **`memdump()`** - Write memory dump report to file\n- **`traceback()`** - Generate stack trace from execution point\n- **`sourcepos()`** - Get current source position information\n- **`getinfo()`** - Get detailed information about a value\n- **`getlocal()`** - Get the value of a local variable\n- **`setlocal()`** - Set the value of a local variable\n- **`getupval()`** - Get the value of an upvalue (closure variable)\n- **`setupval()`** - Set the value of an upvalue (closure variable)\n\n### Environment Variables\n\n- **`UCODE_DEBUG_MEMDUMP_ENABLED`** - Enable/disable automatic memory dumps (default: enabled)\n- **`UCODE_DEBUG_MEMDUMP_SIGNAL`** - Signal for triggering memory dumps (default: SIGUSR2)\n- **`UCODE_DEBUG_MEMDUMP_PATH`** - Output directory for memory dumps (default: /tmp)\n\n*Hover over individual function names for detailed parameter and return type information.*",importValidation:{isValid:()=>!0,getValidImports:()=>Array.from(Mt.keys())}},Ut=new Map([["md5",{name:"md5",parameters:[{name:"str",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the MD5 hash of string and returns that hash. Returns `null` if a non-string argument is given."}],["sha1",{name:"sha1",parameters:[{name:"str",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the SHA1 hash of string and returns that hash. Returns `null` if a non-string argument is given."}],["sha256",{name:"sha256",parameters:[{name:"str",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the SHA256 hash of string and returns that hash. Returns `null` if a non-string argument is given."}],["md5_file",{name:"md5_file",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the MD5 hash of a given file and returns that hash. Returns `null` if an error occurred."}],["sha1_file",{name:"sha1_file",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the SHA1 hash of a given file and returns that hash. Returns `null` if an error occurred."}],["sha256_file",{name:"sha256_file",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the SHA256 hash of a given file and returns that hash. Returns `null` if an error occurred."}],["md2",{name:"md2",parameters:[{name:"str",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the MD2 hash of string and returns that hash. Returns `null` if a non-string argument is given."}],["md4",{name:"md4",parameters:[{name:"str",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the MD4 hash of string and returns that hash. Returns `null` if a non-string argument is given."}],["sha384",{name:"sha384",parameters:[{name:"str",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the SHA384 hash of string and returns that hash. Returns `null` if a non-string argument is given."}],["sha512",{name:"sha512",parameters:[{name:"str",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the SHA512 hash of string and returns that hash. Returns `null` if a non-string argument is given."}],["md2_file",{name:"md2_file",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the MD2 hash of a given file and returns that hash. Returns `null` if an error occurred."}],["md4_file",{name:"md4_file",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the MD4 hash of a given file and returns that hash. Returns `null` if an error occurred."}],["sha384_file",{name:"sha384_file",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the SHA384 hash of a given file and returns that hash. Returns `null` if an error occurred."}],["sha512_file",{name:"sha512_file",parameters:[{name:"path",type:"string",optional:!1}],returnType:"string | null",description:"Calculates the SHA512 hash of a given file and returns that hash. Returns `null` if an error occurred."}]]),Kt={name:"digest",functions:Ut,documentation:'## Digest Module\n\n**Cryptographic hash functions for ucode scripts**\n\nThe digest module provides secure hashing functionality using industry-standard algorithms.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { md5, sha256, sha1_file } from \'digest\';\n\nlet hash = md5("Hello World");\nlet fileHash = sha256_file("/path/to/file.txt");\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as digest from \'digest\';\n\nlet hash = digest.md5("Hello World");\nlet fileHash = digest.sha256_file("/path/to/file.txt");\n```\n\n### Available Functions\n\n**String hashing functions:**\n- **`md5()`** - Calculate MD5 hash of string\n- **`sha1()`** - Calculate SHA1 hash of string\n- **`sha256()`** - Calculate SHA256 hash of string\n- **`sha384()`** - Calculate SHA384 hash of string (extended)\n- **`sha512()`** - Calculate SHA512 hash of string (extended)\n- **`md2()`** - Calculate MD2 hash of string (extended)\n- **`md4()`** - Calculate MD4 hash of string (extended)\n\n**File hashing functions:**\n- **`md5_file()`** - Calculate MD5 hash of file\n- **`sha1_file()`** - Calculate SHA1 hash of file\n- **`sha256_file()`** - Calculate SHA256 hash of file\n- **`sha384_file()`** - Calculate SHA384 hash of file (extended)\n- **`sha512_file()`** - Calculate SHA512 hash of file (extended)\n- **`md2_file()`** - Calculate MD2 hash of file (extended)\n- **`md4_file()`** - Calculate MD4 hash of file (extended)\n\n### Notes\n\n- Extended algorithms (MD2, MD4, SHA384, SHA512) may not be available on all systems\n- All functions return `null` on error or invalid input\n- File functions return `null` if the file cannot be read\n\n*Hover over individual function names for detailed parameter and return type information.*',importValidation:{isValid:()=>!0,getValidImports:()=>Array.from(Ut.keys())}},Gt={name:"math",functions:new Map([["abs",{name:"abs",parameters:[{name:"number",type:"number",optional:!1}],returnType:"number",description:"Returns the absolute value of the given numeric value. Returns NaN if the argument cannot be converted to a number."}],["atan2",{name:"atan2",parameters:[{name:"y",type:"number",optional:!1},{name:"x",type:"number",optional:!1}],returnType:"number",description:"Calculates the principal value of the arc tangent of y/x, using the signs of the two arguments to determine the quadrant of the result. Returns the result in radians (range [-π, π])."}],["cos",{name:"cos",parameters:[{name:"x",type:"number",optional:!1}],returnType:"number",description:"Calculates the cosine of x, where x is given in radians. Returns NaN if x cannot be converted to a number."}],["exp",{name:"exp",parameters:[{name:"x",type:"number",optional:!1}],returnType:"number",description:"Calculates the value of e (the base of natural logarithms) raised to the power of x. Returns NaN if x cannot be converted to a number."}],["log",{name:"log",parameters:[{name:"x",type:"number",optional:!1}],returnType:"number",description:"Calculates the natural logarithm of x. Returns NaN if x cannot be converted to a number, or if x is negative."}],["sin",{name:"sin",parameters:[{name:"x",type:"number",optional:!1}],returnType:"number",description:"Calculates the sine of x, where x is given in radians. Returns NaN if x cannot be converted to a number."}],["sqrt",{name:"sqrt",parameters:[{name:"x",type:"number",optional:!1}],returnType:"number",description:"Calculates the nonnegative square root of x. Returns NaN if x cannot be converted to a number or if x is negative."}],["pow",{name:"pow",parameters:[{name:"x",type:"number",optional:!1},{name:"y",type:"number",optional:!1}],returnType:"number",description:"Calculates the value of x raised to the power of y. Returns NaN if either x or y cannot be converted to a number."}],["rand",{name:"rand",parameters:[{name:"a",type:"number",optional:!0},{name:"b",type:"number",optional:!0}],returnType:"number",description:"Without arguments, returns a pseudo-random integer 0..RAND_MAX. With one argument a, returns a random double 0..a. With two arguments a,b, returns a random double a..b."}],["srand",{name:"srand",parameters:[{name:"seed",type:"number",optional:!1}],returnType:"null",description:"Seeds the pseudo-random number generator with the given value. This affects the sequence produced by subsequent calls to rand()."}],["isnan",{name:"isnan",parameters:[{name:"x",type:"number",optional:!1}],returnType:"boolean",description:"Tests whether x is a NaN (not a number) double value. Returns true if the value is NaN, otherwise false."}]]),documentation:"## Math Module\n\n**Mathematical and trigonometric functions for ucode scripts**\n\nThe math module provides comprehensive mathematical operations including basic arithmetic, trigonometry, logarithms, and random number generation.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { sin, cos, pow, sqrt, abs } from 'math';\n\nlet angle = 3.14159 / 4; // 45 degrees in radians\nlet x = cos(angle); // ~0.707\nlet y = sin(angle); // ~0.707\nlet hypotenuse = sqrt(pow(x, 2) + pow(y, 2)); // ~1.0\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as math from 'math';\n\nlet angle = 3.14159 / 4; // 45 degrees in radians\nlet x = math.cos(angle); // ~0.707\nlet y = math.sin(angle); // ~0.707\nlet hypotenuse = math.sqrt(math.pow(x, 2) + math.pow(y, 2)); // ~1.0\n```\n\n### Available Functions\n\n**Basic operations:**\n- **`abs()`** - Absolute value\n- **`pow()`** - Exponentiation (x^y)\n- **`sqrt()`** - Square root\n\n**Trigonometric functions:**\n- **`sin()`** - Sine (radians)\n- **`cos()`** - Cosine (radians)\n- **`atan2()`** - Arc tangent of y/x (radians)\n\n**Logarithmic and exponential:**\n- **`log()`** - Natural logarithm\n- **`exp()`** - e raised to the power of x\n\n**Random number generation:**\n- **`rand()`** - Generate pseudo-random integer\n- **`srand()`** - Seed the random number generator\n\n**Utility functions:**\n- **`isnan()`** - Test if value is NaN (not a number)\n\n### Notes\n\n- All trigonometric functions use radians, not degrees\n- Functions return NaN for invalid inputs\n- `rand()` returns integers in range [0, RAND_MAX] (at least 32767)\n- `srand()` can be used to create reproducible random sequences\n\n*Hover over individual function names for detailed parameter and return type information.*"},Bt={name:"resolv",functions:new Map([["query",{name:"query",parameters:[{name:"names",type:"string | string[]",optional:!1},{name:"options",type:"object",optional:!0}],returnType:"object",description:"Perform DNS queries for specified domain names. Returns an object containing DNS query results organized by domain name.\n\nDomain name(s) to query. Can be a single domain name string or an array of domain name strings. IP addresses can also be provided for reverse DNS lookups.\n\n**Supported DNS Record Types:**\n- **A** - IPv4 address record\n- **AAAA** - IPv6 address record\n- **CNAME** - Canonical name record\n- **MX** - Mail exchange record\n- **NS** - Name server record\n- **PTR** - Pointer record (reverse DNS)\n- **SOA** - Start of authority record\n- **SRV** - Service record\n- **TXT** - Text record\n- **ANY** - Any available record type\n\nThe `options` parameter is an object with the following properties:\n- `type` (string[], optional) - Array of DNS record types: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT', 'ANY'\n- `nameserver` (string[], optional) - Array of DNS nameserver addresses (e.g., '8.8.8.8#53')\n- `timeout` (number, optional, default: 5000) - Total timeout in milliseconds\n- `retries` (number, optional, default: 2) - Number of retry attempts\n- `edns_maxsize` (number, optional, default: 4096) - Maximum UDP packet size for EDNS\n\n**Example:**\n```ucode\nimport { query } from 'resolv';\n\n// Basic lookup\nconst result = query(['example.com']);\n\n// Specific record types\nconst mx = query(['example.com'], { type: ['MX'] });\n\n// Multiple domains with custom nameserver\nconst results = query(['example.com', 'google.com'], {\n type: ['A', 'AAAA'],\n nameserver: ['8.8.8.8'],\n timeout: 10000\n});\n\n// Reverse DNS\nconst ptr = query(['192.0.2.1'], { type: ['PTR'] });\n```"}],["error",{name:"error",parameters:[],returnType:"string | null",description:"Get the last error message from DNS operations. Returns a descriptive error message for the last failed DNS operation, or null if no error occurred.\n\n**Example:**\n```ucode\nimport { query, error } from 'resolv';\n\nconst result = query('example.org', { nameserver: ['invalid.server'] });\nconst err = error();\nif (err) {\n print('DNS query failed: ', err, '\\n');\n}\n```"}]]),documentation:"## Resolv Module\n\n**DNS resolution functionality for ucode scripts**\n\nThe resolv module provides DNS resolution functionality for ucode, allowing you to perform DNS queries for various record types and handle responses.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { query, error } from 'resolv';\n\nlet result = query('example.com', { type: ['A'] });\nif (!result) {\n let err = error();\n print('DNS error: ', err, '\\n');\n}\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as resolv from 'resolv';\n\nlet result = resolv.query('example.com', { type: ['A'] });\nif (!result) {\n let err = resolv.error();\n print('DNS error: ', err, '\\n');\n}\n```\n\n### Available Functions\n\n**Core operations:**\n- **`query()`** - Perform DNS queries for specified domain names\n- **`error()`** - Get the last error message from DNS operations\n\n### Supported DNS Record Types\n\n- **A** - IPv4 address record\n- **AAAA** - IPv6 address record\n- **CNAME** - Canonical name record\n- **MX** - Mail exchange record\n- **NS** - Name server record\n- **PTR** - Pointer record (reverse DNS)\n- **SOA** - Start of authority record\n- **SRV** - Service record\n- **TXT** - Text record\n- **ANY** - Any available record type\n\n*Hover over individual function names for detailed parameter and return type information.*"},Wt={name:"struct",functions:new Map([["pack",{name:"pack",parameters:[{name:"format",type:"string",optional:!1},{name:"values",type:"any",optional:!1}],returnType:"string",description:"Pack given values according to specified format. Creates a byte string containing the argument values packed according to the given format string.\n\n**Examples:**\n```ucode\n// Pack three integers as network byte order\nlet data = pack('!III', 1, 2, 3);\n\n// Pack string and integer\nlet buffer = pack('10sI', 'hello', 12345);\n```\n\n**Format Characters:**\n- `b` - signed char (-128 to 127)\n- `B` - unsigned char (0 to 255)\n- `h` - short (2 bytes)\n- `H` - unsigned short (2 bytes)\n- `i` - int (4 bytes)\n- `I` - unsigned int (4 bytes)\n- `l` - long (4 bytes)\n- `L` - unsigned long (4 bytes)\n- `q` - long long (8 bytes)\n- `Q` - unsigned long long (8 bytes)\n- `f` - float (4 bytes)\n- `d` - double (8 bytes)\n- `s` - string\n- `p` - Pascal string\n- `?` - bool\n\n**Byte Order:**\n- `@` - native (default)\n- `<` - little-endian\n- `>` - big-endian\n- `!` - network (big-endian)"}],["unpack",{name:"unpack",parameters:[{name:"format",type:"string",optional:!1},{name:"input",type:"string",optional:!1},{name:"offset",type:"number",optional:!0,defaultValue:0}],returnType:"array",description:"Unpack given byte string according to specified format. Interprets a byte string according to the given format string and returns the resulting values.\n\n**Examples:**\n```ucode\n// Unpack three integers from network byte order\nlet values = unpack('!III', data);\nprint(values); // [1, 2, 3]\n\n// Unpack with offset\nlet result = unpack('I', buffer, 4);\n```"}],["new",{name:"new",parameters:[{name:"format",type:"string",optional:!1}],returnType:"struct.instance",description:"Precompile format string. Returns a struct object instance useful for packing and unpacking multiple items without having to recompute the internal format each time.\n\n**Examples:**\n```ucode\n// Create reusable format\nlet fmt = struct.new('!III');\nlet data = fmt.pack(1, 2, 3);\nlet values = fmt.unpack(data);\n```"}],["buffer",{name:"buffer",parameters:[{name:"initialData",type:"string",optional:!0}],returnType:"struct.buffer",description:"Creates a new struct buffer instance for incremental packing and unpacking of binary data. If initial data is provided, the buffer is initialized with this content.\n\n**Examples:**\n```ucode\n// Create empty buffer\nlet buf = struct.buffer();\nbuf.put('I', 1234);\nlet value = buf.get('I');\n\n// Create buffer with initial data\nlet buf2 = struct.buffer(\"\\x01\\x02\\x03\\x04\");\nlet num = buf2.get('I');\n```"}]]),documentation:"## Struct Module\n\n**Binary data packing/unpacking module for ucode scripts**\n\nThe struct module provides routines for interpreting byte strings as packed binary data, similar to Python's struct module.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { pack, unpack } from 'struct';\n\nlet buffer = pack('bhl', -13, 1234, 444555666);\nlet values = unpack('bhl', buffer);\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as struct from 'struct';\n\nlet buffer = struct.pack('bhl', -13, 1234, 444555666);\nlet values = struct.unpack('bhl', buffer);\n```\n\n### Available Functions\n\n**Core functions:**\n- **`pack()`** - Pack values into binary string according to format\n- **`unpack()`** - Unpack binary string into values according to format\n- **`new()`** - Create precompiled format instance for efficiency\n- **`buffer()`** - Create struct buffer for incremental operations\n\n### Format String Syntax\n\n**Format characters:**\n- **`b/B`** - signed/unsigned char (1 byte)\n- **`h/H`** - signed/unsigned short (2 bytes)\n- **`i/I`** - signed/unsigned int (4 bytes)\n- **`l/L`** - signed/unsigned long (4 bytes)\n- **`q/Q`** - signed/unsigned long long (8 bytes)\n- **`f`** - float (4 bytes)\n- **`d`** - double (8 bytes)\n- **`s`** - string\n- **`?`** - boolean\n\n**Byte order prefixes:**\n- **`@`** - native (default)\n- **`<`** - little-endian\n- **`>`** - big-endian\n- **`!`** - network (big-endian)\n\n*Hover over individual function names for detailed parameter and return type information.*"},$t=new Map([["openlog",{name:"openlog",parameters:[{name:"ident",type:"string",optional:!0},{name:"options",type:"number | string | string[]",optional:!0},{name:"facility",type:"number | string",optional:!0,defaultValue:"user"}],returnType:"boolean",description:"Open connection to system logger. Establishes a connection to the system log service and configures the default facility and identification for subsequent log operations."}],["syslog",{name:"syslog",parameters:[{name:"priority",type:"number | string",optional:!1},{name:"format",type:"any",optional:!1},{name:"args",type:"any",optional:!0}],returnType:"boolean",description:"Log a message to the system logger. Behaves in a sprintf-like manner, allowing the use of format strings and associated arguments to construct log messages."}],["closelog",{name:"closelog",parameters:[],returnType:"null",description:"Close connection to system logger. The usage of this function is optional, and usually an explicit log connection tear down is not required."}],["ulog_open",{name:"ulog_open",parameters:[{name:"channels",type:"number | string | string[]",optional:!0},{name:"facility",type:"number | string",optional:!0},{name:"ident",type:"string",optional:!0}],returnType:"boolean",description:"Configure ulog logger (OpenWrt specific). Configures the ulog mechanism and is analogous to using openlog() in conjunction with syslog()."}],["ulog",{name:"ulog",parameters:[{name:"priority",type:"number | string",optional:!1},{name:"format",type:"any",optional:!1},{name:"args",type:"any",optional:!0}],returnType:"boolean",description:"Log a message via the ulog mechanism (OpenWrt specific). Outputs the given log message to all configured ulog channels unless the given priority level exceeds the globally configured ulog priority threshold."}],["ulog_close",{name:"ulog_close",parameters:[],returnType:"null",description:"Close ulog logger (OpenWrt specific). Resets the ulog channels, the default facility and the log ident value to defaults."}],["ulog_threshold",{name:"ulog_threshold",parameters:[{name:"priority",type:"number | string",optional:!0}],returnType:"boolean",description:"Set ulog priority threshold (OpenWrt specific). Configures the application wide log message threshold for log messages emitted with ulog()."}],["INFO",{name:"INFO",parameters:[{name:"format",type:"any",optional:!1},{name:"args",type:"any",optional:!0}],returnType:"boolean",description:"Convenience wrapper for ulog(LOG_INFO, ...). Logs a message with LOG_INFO priority using the ulog mechanism."}],["NOTE",{name:"NOTE",parameters:[{name:"format",type:"any",optional:!1},{name:"args",type:"any",optional:!0}],returnType:"boolean",description:"Convenience wrapper for ulog(LOG_NOTICE, ...). Logs a message with LOG_NOTICE priority using the ulog mechanism."}],["WARN",{name:"WARN",parameters:[{name:"format",type:"any",optional:!1},{name:"args",type:"any",optional:!0}],returnType:"boolean",description:"Convenience wrapper for ulog(LOG_WARNING, ...). Logs a message with LOG_WARNING priority using the ulog mechanism."}],["ERR",{name:"ERR",parameters:[{name:"format",type:"any",optional:!1},{name:"args",type:"any",optional:!0}],returnType:"boolean",description:"Convenience wrapper for ulog(LOG_ERR, ...). Logs a message with LOG_ERR priority using the ulog mechanism."}]]),jt=new Set(["LOG_PID","LOG_CONS","LOG_NDELAY","LOG_ODELAY","LOG_NOWAIT","LOG_AUTH","LOG_AUTHPRIV","LOG_CRON","LOG_DAEMON","LOG_FTP","LOG_KERN","LOG_LPR","LOG_MAIL","LOG_NEWS","LOG_SYSLOG","LOG_USER","LOG_UUCP","LOG_LOCAL0","LOG_LOCAL1","LOG_LOCAL2","LOG_LOCAL3","LOG_LOCAL4","LOG_LOCAL5","LOG_LOCAL6","LOG_LOCAL7","LOG_EMERG","LOG_ALERT","LOG_CRIT","LOG_ERR","LOG_WARNING","LOG_NOTICE","LOG_INFO","LOG_DEBUG","ULOG_KMSG","ULOG_SYSLOG","ULOG_STDIO"]),qt=new Map([["LOG_PID","**LOG_PID** - Include PID with each message.\n\n*Log Option Constant*\n\nWhen passed to `openlog()`, this option includes the process ID (PID) with each log message."],["LOG_CONS","**LOG_CONS** - Log to console if error occurs while sending to syslog.\n\n*Log Option Constant*\n\nWhen passed to `openlog()`, this option causes messages to be written to the system console if there is an error while sending to syslog."],["LOG_NDELAY","**LOG_NDELAY** - Open the connection to the logger immediately.\n\n*Log Option Constant*\n\nWhen passed to `openlog()`, this option opens the connection to the logger immediately instead of waiting for the first message."],["LOG_ODELAY","**LOG_ODELAY** - Delay open until the first message is logged.\n\n*Log Option Constant*\n\nWhen passed to `openlog()`, this option delays opening the connection until the first message is logged."],["LOG_NOWAIT","**LOG_NOWAIT** - Do not wait for child processes created during logging.\n\n*Log Option Constant*\n\nWhen passed to `openlog()`, this option prevents waiting for child processes that might be created during logging."],["LOG_AUTH","**LOG_AUTH** - Authentication/authorization messages.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to authentication or authorization."],["LOG_AUTHPRIV","**LOG_AUTHPRIV** - Private authentication messages.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to private authentication."],["LOG_CRON","**LOG_CRON** - Clock daemon (cron and at commands).\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to the cron daemon."],["LOG_DAEMON","**LOG_DAEMON** - System daemons without separate facility values.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to system daemons."],["LOG_FTP","**LOG_FTP** - FTP server daemon.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to the FTP server."],["LOG_KERN","**LOG_KERN** - Kernel messages.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to the kernel."],["LOG_LPR","**LOG_LPR** - Line printer subsystem.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to the line printer subsystem."],["LOG_MAIL","**LOG_MAIL** - Mail system.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to the mail system."],["LOG_NEWS","**LOG_NEWS** - Network news subsystem.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to network news."],["LOG_SYSLOG","**LOG_SYSLOG** - Messages generated internally by syslogd.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages are generated internally by syslogd."],["LOG_USER","**LOG_USER** - Generic user-level messages.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages are generic user-level messages. This is the default facility."],["LOG_UUCP","**LOG_UUCP** - UUCP subsystem.\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify that messages relate to the UUCP subsystem."],["LOG_LOCAL0","**LOG_LOCAL0** - Local use 0 (custom facility).\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify custom local facility 0."],["LOG_LOCAL1","**LOG_LOCAL1** - Local use 1 (custom facility).\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify custom local facility 1."],["LOG_LOCAL2","**LOG_LOCAL2** - Local use 2 (custom facility).\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify custom local facility 2."],["LOG_LOCAL3","**LOG_LOCAL3** - Local use 3 (custom facility).\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify custom local facility 3."],["LOG_LOCAL4","**LOG_LOCAL4** - Local use 4 (custom facility).\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify custom local facility 4."],["LOG_LOCAL5","**LOG_LOCAL5** - Local use 5 (custom facility).\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify custom local facility 5."],["LOG_LOCAL6","**LOG_LOCAL6** - Local use 6 (custom facility).\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify custom local facility 6."],["LOG_LOCAL7","**LOG_LOCAL7** - Local use 7 (custom facility).\n\n*Log Facility Constant*\n\nUsed with `openlog()` to specify custom local facility 7."],["LOG_EMERG","**LOG_EMERG** - System is unusable.\n\n*Log Priority Constant*\n\nUsed with `syslog()` to indicate emergency conditions - system is unusable."],["LOG_ALERT","**LOG_ALERT** - Action must be taken immediately.\n\n*Log Priority Constant*\n\nUsed with `syslog()` to indicate alert conditions - action must be taken immediately."],["LOG_CRIT","**LOG_CRIT** - Critical conditions.\n\n*Log Priority Constant*\n\nUsed with `syslog()` to indicate critical conditions."],["LOG_ERR","**LOG_ERR** - Error conditions.\n\n*Log Priority Constant*\n\nUsed with `syslog()` to indicate error conditions."],["LOG_WARNING","**LOG_WARNING** - Warning conditions.\n\n*Log Priority Constant*\n\nUsed with `syslog()` to indicate warning conditions."],["LOG_NOTICE","**LOG_NOTICE** - Normal, but significant, condition.\n\n*Log Priority Constant*\n\nUsed with `syslog()` to indicate normal but significant conditions."],["LOG_INFO","**LOG_INFO** - Informational message.\n\n*Log Priority Constant*\n\nUsed with `syslog()` to indicate informational messages."],["LOG_DEBUG","**LOG_DEBUG** - Debug-level message.\n\n*Log Priority Constant*\n\nUsed with `syslog()` to indicate debug-level messages."],["ULOG_KMSG","**ULOG_KMSG** - Log messages to `/dev/kmsg` (dmesg).\n\n*Ulog Channel Constant (OpenWrt)*\n\nUsed with `ulog_open()` to specify that messages should be logged to `/dev/kmsg`, making them appear in dmesg output."],["ULOG_SYSLOG","**ULOG_SYSLOG** - Log messages to syslog.\n\n*Ulog Channel Constant (OpenWrt)*\n\nUsed with `ulog_open()` to specify that messages should be logged using the standard syslog mechanism."],["ULOG_STDIO","**ULOG_STDIO** - Log messages to stdout.\n\n*Ulog Channel Constant (OpenWrt)*\n\nUsed with `ulog_open()` to specify that messages should be logged to stdout."]]),Vt=new Map(Array.from(jt).map(e=>[e,{name:e,value:"number",type:"number",description:""}])),Ht={name:"log",functions:$t,constants:Vt,constantDocumentation:qt,documentation:'## Log Module\n\n**System logging functions for ucode scripts**\n\nThe log module provides bindings to the POSIX syslog functions as well as OpenWrt specific ulog library functions.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from \'log\';\n\nopenlog("my-log-ident", LOG_PID, LOG_USER);\nsyslog(LOG_ERR, "An error occurred!");\n\n// OpenWrt specific ulog functions\nimport { ulog_open, ulog, ULOG_SYSLOG, LOG_DAEMON, LOG_INFO } from \'log\';\n\nulog_open(ULOG_SYSLOG, LOG_DAEMON, "my-log-ident");\nulog(LOG_INFO, "The current epoch is %d", time());\n```\n\n### Available Functions\n\n**Standard syslog functions:**\n- **`openlog()`** - Open connection to system logger\n- **`syslog()`** - Log a message to the system logger\n- **`closelog()`** - Close connection to system logger\n\n**OpenWrt ulog functions:**\n- **`ulog_open()`** - Configure ulog logger\n- **`ulog()`** - Log a message via ulog mechanism\n- **`ulog_close()`** - Close ulog logger\n- **`ulog_threshold()`** - Set ulog priority threshold\n\n**Convenience functions:**\n- **`INFO()`** - Log with LOG_INFO priority\n- **`NOTE()`** - Log with LOG_NOTICE priority\n- **`WARN()`** - Log with LOG_WARNING priority\n- **`ERR()`** - Log with LOG_ERR priority\n\n### Constants\n\n**Log options:** LOG_PID, LOG_CONS, LOG_NDELAY, LOG_ODELAY, LOG_NOWAIT\n\n**Log facilities:** LOG_AUTH, LOG_AUTHPRIV, LOG_CRON, LOG_DAEMON, LOG_FTP, LOG_KERN, LOG_LPR, LOG_MAIL, LOG_NEWS, LOG_SYSLOG, LOG_USER, LOG_UUCP, LOG_LOCAL0-7\n\n**Log priorities:** LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG\n\n**Ulog channels:** ULOG_KMSG, ULOG_STDIO, ULOG_SYSLOG\n\n*Hover over individual function names for detailed parameter and return type information.*',importValidation:{isValid:e=>$t.has(e)||jt.has(e),getValidImports:()=>[...Array.from($t.keys()),...Array.from(jt)]}},Yt=new Map([["create",{name:"create",parameters:[{name:"domain",type:"number",optional:!0,defaultValue:"AF_INET"},{name:"type",type:"number",optional:!0,defaultValue:"SOCK_STREAM"},{name:"protocol",type:"number",optional:!0,defaultValue:0}],returnType:"socket | null",description:"Creates a network socket instance with the specified domain, type, and protocol."}],["connect",{name:"connect",parameters:[{name:"host",type:"string | number[] | SocketAddress",optional:!1},{name:"service",type:"string | number",optional:!0},{name:"hints",type:"object",optional:!0},{name:"timeout",type:"number",optional:!0,defaultValue:-1}],returnType:"socket | null",description:"Creates a network socket and connects it to the specified host and service."}],["listen",{name:"listen",parameters:[{name:"host",type:"string | number[] | SocketAddress",optional:!0},{name:"service",type:"string | number",optional:!0},{name:"hints",type:"object",optional:!0},{name:"backlog",type:"number",optional:!0,defaultValue:128},{name:"reuseaddr",type:"boolean",optional:!0}],returnType:"socket | null",description:"Binds a listening network socket to the specified host and service."}],["sockaddr",{name:"sockaddr",parameters:[{name:"address",type:"string | number[] | SocketAddress",optional:!1}],returnType:"SocketAddress | null",description:"Parses the provided address value into a socket address representation."}],["nameinfo",{name:"nameinfo",parameters:[{name:"address",type:"string | SocketAddress",optional:!1},{name:"flags",type:"number",optional:!0}],returnType:"{hostname: string, service: string} | null",description:"Resolves the given network address into hostname and service name."}],["addrinfo",{name:"addrinfo",parameters:[{name:"hostname",type:"string",optional:!1},{name:"service",type:"string",optional:!0},{name:"hints",type:"object",optional:!0}],returnType:"AddressInfo[] | null",description:"Resolves the given hostname and optional service name into a list of network addresses."}],["poll",{name:"poll",parameters:[{name:"timeout",type:"number",optional:!1},{name:"sockets",type:"socket | PollSpec",optional:!1}],returnType:"PollSpec[] | null",description:"Polls a number of sockets for state changes."}],["error",{name:"error",parameters:[{name:"numeric",type:"boolean",optional:!0}],returnType:"string | number | null",description:"Query error information, returning either a description or numeric error code."}],["strerror",{name:"strerror",parameters:[{name:"code",type:"number",optional:!1}],returnType:"string | null",description:"Returns a string containing a description of the error code."}]]),Xt=(e,t,n)=>[e,{name:e,value:t,type:"number",description:n}],zt=(e,t)=>Xt(e,"platform-defined",t),Jt=(e,t)=>Xt(e,"platform-defined (Linux only)",t),Qt=[Xt("AF_UNSPEC",0,"Unspecified address family"),Xt("AF_UNIX",1,"UNIX domain sockets"),Xt("AF_INET",2,"IPv4 Internet protocols"),Xt("AF_INET6",10,"IPv6 Internet protocols"),Xt("AF_PACKET",17,"Low-level packet interface (Linux only)"),Xt("SOCK_STREAM",1,"Provides sequenced, reliable, two-way, connection-based byte streams"),Xt("SOCK_DGRAM",2,"Supports datagrams (connectionless, unreliable messages)"),Xt("SOCK_RAW",3,"Provides raw network protocol access"),Xt("SOCK_PACKET",10,"Obsolete packet interface (Linux only)"),Xt("SOCK_NONBLOCK",2048,"Enables non-blocking operation"),Xt("SOCK_CLOEXEC",524288,"Sets the close-on-exec flag"),Xt("MSG_DONTROUTE",4,"Send without using routing tables"),Xt("MSG_DONTWAIT",64,"Enables non-blocking operation"),Xt("MSG_EOR",128,"End of record"),Xt("MSG_NOSIGNAL",16384,"Do not generate SIGPIPE"),Xt("MSG_OOB",1,"Process out-of-band data"),Xt("MSG_PEEK",2,"Peeks at incoming messages"),Xt("MSG_TRUNC",32,"Report if datagram truncation occurred"),Xt("MSG_WAITALL",256,"Wait for full message"),Xt("MSG_CONFIRM",2048,"Confirm path validity (Linux only)"),Xt("MSG_MORE",32768,"Sender will send more (Linux only)"),Xt("MSG_FASTOPEN",536870912,"Send data in TCP SYN (Linux only)"),Xt("MSG_CMSG_CLOEXEC",1073741824,"Sets close-on-exec flag on received file descriptor (Linux only)"),Xt("MSG_ERRQUEUE",8192,"Receive errors from ICMP (Linux only)"),Xt("IPPROTO_IP",0,"Dummy protocol for IP"),Xt("IPPROTO_IPV6",41,"The IPv6 protocol"),Xt("IPPROTO_TCP",6,"TCP protocol"),Xt("IPPROTO_UDP",17,"UDP protocol"),zt("IP_ADD_MEMBERSHIP","Add an IPv4 multicast group membership"),zt("IP_ADD_SOURCE_MEMBERSHIP","Add an IPv4 multicast group/source membership"),zt("IP_BLOCK_SOURCE","Block traffic from a multicast source"),zt("IP_DROP_MEMBERSHIP","Drop an IPv4 multicast group membership"),zt("IP_DROP_SOURCE_MEMBERSHIP","Drop an IPv4 multicast group/source membership"),zt("IP_HDRINCL","Outgoing packets include a user-supplied IP header"),zt("IP_MSFILTER","Configure multicast source filters"),zt("IP_MULTICAST_IF","Set the interface for outgoing multicast packets"),zt("IP_MULTICAST_LOOP","Control loopback of outgoing multicast packets"),zt("IP_MULTICAST_TTL","Set the TTL for outgoing multicast packets"),zt("IP_OPTIONS","Set or retrieve IPv4 options"),zt("IP_PKTINFO","Receive destination address and interface data"),zt("IP_RECVOPTS","Receive all IP options with incoming packets"),zt("IP_RECVTOS","Receive the IPv4 type of service field"),zt("IP_RECVTTL","Receive the IPv4 time-to-live value"),zt("IP_RETOPTS","Receive the IPv4 options actually used"),zt("IP_TOS","Set the IPv4 type-of-service field"),zt("IP_TTL","Set the default IPv4 time-to-live"),zt("IP_UNBLOCK_SOURCE","Unblock traffic from a multicast source"),Jt("IP_BIND_ADDRESS_NO_PORT","Allow binding without reserving a local port (Linux only)"),Jt("IP_FREEBIND","Allow binding to non-local IPv4 addresses (Linux only)"),Jt("IP_MTU","Retrieve or set the IPv4 path MTU (Linux only)"),Jt("IP_MTU_DISCOVER","Control IPv4 path MTU discovery (Linux only)"),Jt("IP_MULTICAST_ALL","Receive all multicast packets on the interface (Linux only)"),Jt("IP_NODEFRAG","Disable IPv4 fragmentation (Linux only)"),Jt("IP_PASSSEC","Receive IP security context information (Linux only)"),Jt("IP_RECVERR","Receive extended asynchronous error information (Linux only)"),Jt("IP_RECVORIGDSTADDR","Receive the original destination address (Linux only)"),Jt("IP_ROUTER_ALERT","Deliver packets with the router alert option (Linux only)"),Jt("IP_TRANSPARENT","Enable transparent proxying (Linux only)"),zt("IPV6_FLOWINFO_SEND","Control whether flow information is transmitted"),zt("IPV6_FLOWINFO","Receive flow label information with incoming packets"),zt("IPV6_FLOWLABEL_MGR","Manage IPv6 flow labels"),zt("IPV6_MULTICAST_HOPS","Set the hop limit for outgoing multicast packets"),zt("IPV6_MULTICAST_IF","Select the interface for outgoing multicast packets"),zt("IPV6_MULTICAST_LOOP","Control loopback of outgoing multicast packets"),zt("IPV6_RECVTCLASS","Receive the IPv6 traffic class field"),zt("IPV6_TCLASS","Set the IPv6 traffic class field"),zt("IPV6_UNICAST_HOPS","Set the default hop limit for unicast packets"),zt("IPV6_V6ONLY","Restrict the socket to IPv6 traffic only"),Jt("IPV6_ADD_MEMBERSHIP","Join an IPv6 multicast group (Linux only)"),Jt("IPV6_ADDR_PREFERENCES","Specify IPv6 address selection preferences (Linux only)"),Jt("IPV6_ADDRFORM","Convert an IPv6 socket to another address family (Linux only)"),Jt("IPV6_AUTHHDR","Receive IPv6 authentication headers (Linux only)"),Jt("IPV6_AUTOFLOWLABEL","Automatically manage IPv6 flow labels (Linux only)"),Jt("IPV6_DONTFRAG","Control IPv6 fragmentation behavior (Linux only)"),Jt("IPV6_DROP_MEMBERSHIP","Leave an IPv6 multicast group (Linux only)"),Jt("IPV6_DSTOPTS","Receive IPv6 destination options (Linux only)"),Jt("IPV6_FREEBIND","Allow binding to non-local IPv6 addresses (Linux only)"),Jt("IPV6_HOPLIMIT","Receive the IPv6 hop limit (Linux only)"),Jt("IPV6_HOPOPTS","Receive IPv6 hop-by-hop options (Linux only)"),Jt("IPV6_JOIN_ANYCAST","Join an IPv6 anycast group (Linux only)"),Jt("IPV6_LEAVE_ANYCAST","Leave an IPv6 anycast group (Linux only)"),Jt("IPV6_MINHOPCOUNT","Require a minimum IPv6 hop count (Linux only)"),Jt("IPV6_MTU_DISCOVER","Control IPv6 path MTU discovery (Linux only)"),Jt("IPV6_MTU","Retrieve or set the IPv6 path MTU (Linux only)"),Jt("IPV6_MULTICAST_ALL","Receive all IPv6 multicast packets (Linux only)"),Jt("IPV6_PKTINFO","Receive IPv6 packet information (Linux only)"),Jt("IPV6_RECVDSTOPTS","Receive IPv6 destination options control messages (Linux only)"),Jt("IPV6_RECVERR","Receive IPv6 asynchronous error information (Linux only)"),Jt("IPV6_RECVFRAGSIZE","Receive IPv6 fragment size information (Linux only)"),Jt("IPV6_RECVHOPLIMIT","Receive IPv6 hop limit information (Linux only)"),Jt("IPV6_RECVHOPOPTS","Receive IPv6 hop-by-hop options (Linux only)"),Jt("IPV6_RECVORIGDSTADDR","Receive the original IPv6 destination address (Linux only)"),Jt("IPV6_RECVPATHMTU","Receive IPv6 path MTU information (Linux only)"),Jt("IPV6_RECVPKTINFO","Receive IPv6 packet info control messages (Linux only)"),Jt("IPV6_RECVRTHDR","Receive IPv6 routing headers (Linux only)"),Jt("IPV6_ROUTER_ALERT_ISOLATE","Isolate IPv6 router alert traffic (Linux only)"),Jt("IPV6_ROUTER_ALERT","Receive packets with the IPv6 router alert option (Linux only)"),Jt("IPV6_RTHDR","Receive IPv6 routing headers control messages (Linux only)"),Jt("IPV6_RTHDRDSTOPTS","Receive IPv6 routing header destination options (Linux only)"),Jt("IPV6_TRANSPARENT","Enable IPv6 transparent proxying (Linux only)"),Jt("IPV6_UNICAST_IF","Select the interface for outgoing unicast packets (Linux only)"),Xt("SOL_SOCKET",1,"Socket options at the socket API level"),Xt("SO_ACCEPTCONN",30,"Reports whether socket listening is enabled"),Xt("SO_BROADCAST",6,"Allow transmission of broadcast messages"),Xt("SO_DEBUG",1,"Enable socket debugging"),Xt("SO_DONTROUTE",5,"Send packets directly without routing"),Xt("SO_ERROR",4,"Retrieves and clears the error status for the socket"),Xt("SO_KEEPALIVE",9,"Enable keep-alive packets"),Xt("SO_LINGER",13,"Set linger on close"),Xt("SO_OOBINLINE",10,"Enables out-of-band data to be received in the normal data stream"),Xt("SO_RCVBUF",8,"Set the receive buffer size"),Xt("SO_RCVLOWAT",18,"Set the minimum number of bytes to process for input operations"),Xt("SO_RCVTIMEO",20,"Set the timeout for receiving data"),Xt("SO_REUSEADDR",2,"Allow the socket to be bound to an address that is already in use"),Xt("SO_REUSEPORT",15,"Enable duplicate address and port bindings"),Xt("SO_SNDBUF",7,"Set the send buffer size"),Xt("SO_SNDLOWAT",19,"Set the minimum number of bytes to process for output operations"),Xt("SO_SNDTIMEO",21,"Set the timeout for sending data"),Xt("SO_TIMESTAMP",29,"Enable receiving of timestamps"),Xt("SO_TYPE",3,"Retrieves the type of the socket"),Jt("SO_ATTACH_BPF","Attach a classic BPF program to the socket (Linux only)"),Jt("SO_ATTACH_FILTER","Attach a socket filter program (Linux only)"),Jt("SO_ATTACH_REUSEPORT_CBPF","Attach a classic BPF program for reuseport (Linux only)"),Jt("SO_ATTACH_REUSEPORT_EBPF","Attach an eBPF program for reuseport (Linux only)"),Jt("SO_BINDTODEVICE","Bind the socket to a specific network interface (Linux only)"),Jt("SO_BUSY_POLL","Enable busy polling for reduced latency (Linux only)"),Jt("SO_DETACH_BPF","Detach a classic BPF program from the socket (Linux only)"),Jt("SO_DETACH_FILTER","Detach a socket filter program (Linux only)"),Jt("SO_DOMAIN","Retrieve the socket's address family (Linux only)"),Jt("SO_INCOMING_CPU","Retrieve the CPU that handled the last packet (Linux only)"),Jt("SO_INCOMING_NAPI_ID","Retrieve the NAPI ID of the receiving interface (Linux only)"),Jt("SO_LOCK_FILTER","Lock the attached socket filter (Linux only)"),Jt("SO_MARK","Set the mark value for outgoing packets (Linux only)"),Jt("SO_PASSCRED","Receive SCM_CREDENTIALS control messages (Linux only)"),Jt("SO_PASSSEC","Receive security context information (Linux only)"),Jt("SO_PEEK_OFF","Peek data without removing it from the queue (Linux only)"),Jt("SO_PEERCRED","Retrieve peer credentials (Linux only)"),Jt("SO_PEERSEC","Retrieve peer security context (Linux only)"),Jt("SO_PRIORITY","Set the protocol-defined priority for packets (Linux only)"),Jt("SO_PROTOCOL","Retrieve the protocol number (Linux only)"),Jt("SO_RCVBUFFORCE","Force the receive buffer size (Linux only)"),Jt("SO_RXQ_OVFL","Report receive queue overflow events (Linux only)"),Jt("SO_SNDBUFFORCE","Force the send buffer size (Linux only)"),Jt("SO_TIMESTAMPNS","Enable nanosecond-resolution timestamps (Linux only)"),Jt("SCM_CREDENTIALS","Pass process credentials in ancillary data (Linux only)"),Jt("SCM_RIGHTS","Pass file descriptors in ancillary data (Linux only)"),zt("TCP_FASTOPEN","Enable TCP Fast Open support"),zt("TCP_KEEPCNT","Configure the number of keepalive probes"),zt("TCP_KEEPINTVL","Configure the interval between keepalive probes"),zt("TCP_MAXSEG","Set the maximum TCP segment size"),zt("TCP_NODELAY","Disable Nagle's algorithm"),Jt("TCP_CONGESTION","Select the TCP congestion control algorithm (Linux only)"),Jt("TCP_CORK","Delay packet transmission until data is flushed (Linux only)"),Jt("TCP_DEFER_ACCEPT","Accept connections only when data arrives (Linux only)"),Jt("TCP_FASTOPEN_CONNECT","Enable client-side Fast Open (Linux only)"),Jt("TCP_INFO","Retrieve TCP connection state information (Linux only)"),Jt("TCP_KEEPIDLE","Set the idle time before keepalive probes (Linux only)"),Jt("TCP_LINGER2","Control linger in FIN_WAIT2 state (Linux only)"),Jt("TCP_QUICKACK","Enable quick acknowledgements (Linux only)"),Jt("TCP_SYNCNT","Limit SYN retransmissions (Linux only)"),Jt("TCP_USER_TIMEOUT","Set user-specified timeout for unacknowledged data (Linux only)"),Jt("TCP_WINDOW_CLAMP","Limit the advertised receive window (Linux only)"),Jt("SOL_PACKET","Socket options at the packet API level (Linux only)"),Jt("PACKET_ADD_MEMBERSHIP","Add a packet socket multicast membership (Linux only)"),Jt("PACKET_DROP_MEMBERSHIP","Drop a packet socket multicast membership (Linux only)"),Jt("PACKET_AUXDATA","Receive auxiliary packet data (Linux only)"),Jt("PACKET_FANOUT","Configure packet fanout across sockets (Linux only)"),Jt("PACKET_LOSS","Query packet loss statistics (Linux only)"),Jt("PACKET_RESERVE","Reserve space in packet socket buffers (Linux only)"),Jt("PACKET_RX_RING","Configure a packet socket receive ring (Linux only)"),Jt("PACKET_STATISTICS","Retrieve packet socket statistics (Linux only)"),Jt("PACKET_TIMESTAMP","Receive packet socket timestamps (Linux only)"),Jt("PACKET_TX_RING","Configure a packet socket transmit ring (Linux only)"),Jt("PACKET_VERSION","Select the packet socket protocol version (Linux only)"),Jt("PACKET_QDISC_BYPASS","Bypass queuing discipline for packet sockets (Linux only)"),Jt("PACKET_MR_PROMISC","Enable packet socket promiscuous mode (Linux only)"),Jt("PACKET_MR_MULTICAST","Enable packet socket multicast mode (Linux only)"),Jt("PACKET_MR_ALLMULTI","Receive all multicast packets (Linux only)"),Jt("PACKET_HOST","Receive packets destined for the host (Linux only)"),Jt("PACKET_BROADCAST","Receive broadcast packets (Linux only)"),Jt("PACKET_MULTICAST","Receive multicast packets (Linux only)"),Jt("PACKET_OTHERHOST","Receive packets destined for other hosts (Linux only)"),Jt("PACKET_OUTGOING","Mark outgoing packet socket traffic (Linux only)"),Jt("UDP_CORK","Cork UDP datagrams until uncorked (Linux only)"),Xt("SHUT_RD",0,"Disallow further receptions"),Xt("SHUT_WR",1,"Disallow further transmissions"),Xt("SHUT_RDWR",2,"Disallow further receptions and transmissions"),Xt("AI_ADDRCONFIG",32,"Address configuration flag"),Xt("AI_ALL",16,"Return IPv4 and IPv6 socket addresses"),Xt("AI_CANONIDN",128,"Canonicalize using the IDNA standard"),Xt("AI_CANONNAME",2,"Fill in the canonical name field"),Xt("AI_IDN",64,"Enable IDN encoding"),Xt("AI_NUMERICHOST",4,"Prevent hostname resolution"),Xt("AI_NUMERICSERV",1024,"Prevent service name resolution"),Xt("AI_PASSIVE",1,"Use passive socket"),Xt("AI_V4MAPPED",8,"Map IPv6 addresses to IPv4-mapped format"),Xt("NI_DGRAM",16,"Datagram socket type"),Xt("NI_IDN",64,"Enable IDN encoding"),Xt("NI_MAXHOST",1025,"Maximum hostname length"),Xt("NI_MAXSERV",32,"Maximum service name length"),Xt("NI_NAMEREQD",8,"Hostname resolution required"),Xt("NI_NOFQDN",4,"Do not force fully qualified domain name"),Xt("NI_NUMERICHOST",1,"Return numeric form of the hostname"),Xt("NI_NUMERICSERV",2,"Return numeric form of the service name"),Xt("POLLIN",1,"Data available to read"),Xt("POLLPRI",2,"Priority data available to read"),Xt("POLLOUT",4,"Writable data available"),Xt("POLLERR",8,"Error condition"),Xt("POLLHUP",16,"Hang up"),Xt("POLLNVAL",32,"Invalid request"),Xt("POLLRDHUP",8192,"Peer closed or shutdown writing (Linux only)")],Zt={name:"socket",functions:Yt,constants:new Map(Qt),documentation:"## Socket Module\n\n**Network socket functionality for ucode scripts**\n\nThe socket module provides comprehensive network socket functionality for creating TCP/UDP connections, listening for incoming connections, and handling network communication.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { connect, listen, AF_INET, SOCK_STREAM } from 'socket';\n\nlet client = connect('example.com', 80);\nlet server = listen('0.0.0.0', 8080);\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as socket from 'socket';\n\nlet client = socket.connect('example.com', 80);\n```\n\n### Available Functions\n\n- **`create()`** - Create a network socket instance\n- **`connect()`** - Create and connect a socket\n- **`listen()`** - Bind a listening socket\n- **`sockaddr()`** - Parse address into socket address\n- **`nameinfo()`** - Resolve address to hostname/service\n- **`addrinfo()`** - Resolve hostname to addresses\n- **`poll()`** - Poll sockets for state changes\n- **`error()`** - Query error information\n- **`strerror()`** - Get error description string\n\n*Hover over individual function names and constants for detailed parameter and return type information.*"},en={name:"ubus",functions:new Map([["error",{name:"error",parameters:[{name:"numeric",type:"boolean",optional:!0}],returnType:"integer | string | null",description:"Retrieve the last ubus error. Returns error code as integer if numeric is true, otherwise returns formatted error message as string. Returns null if no error occurred."}],["connect",{name:"connect",parameters:[{name:"socket",type:"string",optional:!0},{name:"timeout",type:"integer",optional:!0,defaultValue:30}],returnType:"object",description:"Establish a connection to the ubus daemon. Returns a connection object that can be used for further ubus operations."}],["open_channel",{name:"open_channel",parameters:[{name:"fd",type:"integer",optional:!1},{name:"cb",type:"function",optional:!0},{name:"disconnect_cb",type:"function",optional:!0},{name:"timeout",type:"integer",optional:!0,defaultValue:30}],returnType:"object",description:"Create a ubus channel connection using an existing file descriptor. Used for bidirectional communication over established connections.\n\n**Example:**\n```ucode\nimport { open_channel } from 'ubus';\n\nlet chan = open_channel(fd, function(msg) {\n printf(\"Received: %J\\n\", msg);\n});\n```"}],["guard",{name:"guard",parameters:[{name:"handler",type:"function",optional:!0}],returnType:"function | boolean",description:"Set or get the global ubus exception handler. If called without arguments, returns current handler. If called with a handler function, sets it as the exception handler."}]]),constants:new Map([["STATUS_OK",{name:"STATUS_OK",value:0,type:"integer",description:"Operation completed successfully"}],["STATUS_INVALID_COMMAND",{name:"STATUS_INVALID_COMMAND",value:1,type:"integer",description:"Invalid or unknown command"}],["STATUS_INVALID_ARGUMENT",{name:"STATUS_INVALID_ARGUMENT",value:2,type:"integer",description:"Invalid argument provided to function"}],["STATUS_METHOD_NOT_FOUND",{name:"STATUS_METHOD_NOT_FOUND",value:3,type:"integer",description:"Requested method not found on object"}],["STATUS_NOT_FOUND",{name:"STATUS_NOT_FOUND",value:4,type:"integer",description:"Requested object or resource not found"}],["STATUS_NO_DATA",{name:"STATUS_NO_DATA",value:5,type:"integer",description:"No data available or returned"}],["STATUS_PERMISSION_DENIED",{name:"STATUS_PERMISSION_DENIED",value:6,type:"integer",description:"Access denied due to insufficient permissions"}],["STATUS_TIMEOUT",{name:"STATUS_TIMEOUT",value:7,type:"integer",description:"Operation timed out"}],["STATUS_NOT_SUPPORTED",{name:"STATUS_NOT_SUPPORTED",value:8,type:"integer",description:"Operation or feature not supported"}],["STATUS_UNKNOWN_ERROR",{name:"STATUS_UNKNOWN_ERROR",value:9,type:"integer",description:"Unknown or unspecified error occurred"}],["STATUS_CONNECTION_FAILED",{name:"STATUS_CONNECTION_FAILED",value:10,type:"integer",description:"Failed to establish connection"}],["STATUS_NO_MEMORY",{name:"STATUS_NO_MEMORY",value:11,type:"integer",description:"Insufficient memory available"}],["STATUS_PARSE_ERROR",{name:"STATUS_PARSE_ERROR",value:12,type:"integer",description:"Error parsing data or message"}],["STATUS_SYSTEM_ERROR",{name:"STATUS_SYSTEM_ERROR",value:13,type:"integer",description:"System-level error occurred"}],["STATUS_CONTINUE",{name:"STATUS_CONTINUE",value:-1,type:"integer",description:"Virtual status code for continuing multi-part replies"}],["SYSTEM_OBJECT_ACL",{name:"SYSTEM_OBJECT_ACL",value:1,type:"integer",description:"System object access control list identifier"}]]),documentation:"## ubus Module\n\n**OpenWrt unified bus communication for ucode scripts**\n\nThe ubus module provides comprehensive access to the OpenWrt unified bus (ubus) system, enabling communication with system services and daemons.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { connect, error } from 'ubus';\n\nlet conn = connect();\nlet result = conn.call('system', 'info');\nif (!result) {\n print('ubus error: ', error(), '\\n');\n}\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as ubus from 'ubus';\n\nlet conn = ubus.connect();\nlet result = conn.call('system', 'info');\n```\n\n### Available Functions\n\n- **`error()`** - Retrieve the last ubus error\n- **`connect()`** - Establish connection to ubus daemon\n- **`open_channel()`** - Create ubus channel from file descriptor\n- **`guard()`** - Set/get global ubus exception handler\n\n### Status Constants\n\nSTATUS_OK, STATUS_INVALID_COMMAND, STATUS_INVALID_ARGUMENT, STATUS_METHOD_NOT_FOUND, STATUS_NOT_FOUND, STATUS_NO_DATA, STATUS_PERMISSION_DENIED, STATUS_TIMEOUT, STATUS_NOT_SUPPORTED, STATUS_UNKNOWN_ERROR, STATUS_CONNECTION_FAILED, STATUS_NO_MEMORY, STATUS_PARSE_ERROR, STATUS_SYSTEM_ERROR, STATUS_CONTINUE\n\n*Hover over individual function names for detailed parameter and return type information.*"},tn={name:"zlib",functions:new Map([["deflate",{name:"deflate",parameters:[{name:"str_or_resource",type:"string | object",optional:!1},{name:"gzip",type:"boolean",optional:!0,defaultValue:!1},{name:"level",type:"number",optional:!0,defaultValue:"Z_DEFAULT_COMPRESSION"}],returnType:"string | null",description:"Compresses data in Zlib or gzip format. If the input is a string, it is directly compressed. If an object/resource with a read() method is given, it will be read in chunks for incremental compression.\n\n**Example:**\n```ucode\n// deflate content using default compression\nconst deflated = deflate(content);\n\n// deflate content with gzip format and fastest compression\nconst deflated = deflate(content, true, Z_BEST_SPEED);\n```"}],["inflate",{name:"inflate",parameters:[{name:"str_or_resource",type:"string | object",optional:!1}],returnType:"string | null",description:"Decompresses data in Zlib or gzip format. If the input is a string, it is directly decompressed. If an object/resource with a read() method is given, it will be read in chunks for incremental decompression.\n\n**Example:**\n```ucode\n// inflate compressed data\nconst inflated = inflate(compressed_data);\n```"}],["deflater",{name:"deflater",parameters:[{name:"gzip",type:"boolean",optional:!0,defaultValue:!1},{name:"level",type:"number",optional:!0,defaultValue:"Z_DEFAULT_COMPRESSION"}],returnType:"zlib.deflate | null",description:'Initializes a deflate stream for streaming compression. Returns a stream handle that can be used with write() and read() methods.\n\n**Example:**\n```ucode\n// create streaming deflate\nconst zstrmd = deflater(true, Z_BEST_SPEED);\nzstrmd.write("data", Z_NO_FLUSH);\nconst compressed = zstrmd.read();\n```'}],["inflater",{name:"inflater",parameters:[],returnType:"zlib.inflate | null",description:"Initializes an inflate stream for streaming decompression. Can process either Zlib or gzip data. Returns a stream handle that can be used with write() and read() methods.\n\n**Example:**\n```ucode\n// create streaming inflate\nconst zstrmi = inflater();\nzstrmi.write(compressed_data, Z_NO_FLUSH);\nconst decompressed = zstrmi.read();\n```"}]]),constants:new Map([["Z_NO_COMPRESSION",{name:"Z_NO_COMPRESSION",value:0,type:"number",description:"No compression level - store data without compression"}],["Z_BEST_SPEED",{name:"Z_BEST_SPEED",value:1,type:"number",description:"Fastest compression level with minimal compression ratio"}],["Z_BEST_COMPRESSION",{name:"Z_BEST_COMPRESSION",value:9,type:"number",description:"Highest compression level with maximum compression ratio but slowest speed"}],["Z_DEFAULT_COMPRESSION",{name:"Z_DEFAULT_COMPRESSION",value:-1,type:"number",description:"Default compromise between speed and compression (currently equivalent to level 6)"}],["Z_NO_FLUSH",{name:"Z_NO_FLUSH",value:0,type:"number",description:"No flushing - accumulate data until buffer is full"}],["Z_PARTIAL_FLUSH",{name:"Z_PARTIAL_FLUSH",value:1,type:"number",description:"Partial flush - flush some output without closing the stream"}],["Z_SYNC_FLUSH",{name:"Z_SYNC_FLUSH",value:2,type:"number",description:"Sync flush - flush all pending output and align to byte boundary"}],["Z_FULL_FLUSH",{name:"Z_FULL_FLUSH",value:3,type:"number",description:"Full flush - flush all output and reset compression state"}],["Z_FINISH",{name:"Z_FINISH",value:4,type:"number",description:"Finish the stream - no more input data expected after this"}]]),documentation:"## Zlib Module\n\n**Data compression and decompression module**\n\nThe zlib module provides single-call and stream-oriented functions for interacting with zlib data compression.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { deflate, inflate, Z_BEST_SPEED } from 'zlib';\n\nlet compressed = deflate(\"Hello World\", false, Z_BEST_SPEED);\nlet original = inflate(compressed);\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as zlib from 'zlib';\n\nlet compressed = zlib.deflate(\"Hello World\");\nlet original = zlib.inflate(compressed);\n```\n\n### Available Functions\n\n- **`deflate()`** - Compress data in Zlib or gzip format\n- **`inflate()`** - Decompress data in Zlib or gzip format\n- **`deflater()`** - Create streaming deflate handle\n- **`inflater()`** - Create streaming inflate handle\n\n### Constants\n\n**Compression levels:** Z_NO_COMPRESSION, Z_BEST_SPEED, Z_BEST_COMPRESSION, Z_DEFAULT_COMPRESSION\n\n**Flush options:** Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH\n\n*Hover over individual function names for detailed parameter and return type information.*"};var nn;function rn(){return{type:C.OBJECT,moduleName:nn.IO_HANDLE}}!function(e){e.IO_HANDLE="io.handle"}(nn||(nn={}));const on=new Map([["error",{name:"error",parameters:[],returnType:"string | null",description:"Returns the last I/O error message, or null if no error occurred"}],["new",{name:"new",parameters:[{name:"fd",type:"number",optional:!1},{name:"takeOver",type:"boolean",optional:!0,defaultValue:!1}],returnType:"io.handle | null",description:"Creates an io.handle from an existing file descriptor number. If takeOver is true, the handle will close the fd when garbage collected"}],["open",{name:"open",parameters:[{name:"path",type:"string",optional:!1},{name:"flags",type:"number",optional:!0,defaultValue:"O_RDONLY"},{name:"mode",type:"number",optional:!0,defaultValue:438}],returnType:"io.handle | null",description:"Opens a file and returns an io.handle. Uses POSIX open() flags (O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, etc.)"}],["from",{name:"from",parameters:[{name:"source",type:"any",optional:!1}],returnType:"io.handle | null",description:"Creates an io.handle from an existing file handle (fs.file, fs.proc, fs.dir) or io.handle resource by extracting its underlying file descriptor"}],["pipe",{name:"pipe",parameters:[],returnType:"array | null",description:"Creates a pipe and returns an array of two io.handle objects [read_handle, write_handle], or null on error"}]]),sn=new Map([["read",{name:"read",parameters:[{name:"length",type:"number",optional:!1}],returnType:"string | null",description:"Reads up to length bytes from the handle. Returns the data as a string, empty string on EOF, or null on error"}],["write",{name:"write",parameters:[{name:"data",type:"string",optional:!1}],returnType:"number | null",description:"Writes data to the handle. Returns the number of bytes written, or null on error"}],["seek",{name:"seek",parameters:[{name:"offset",type:"number",optional:!1},{name:"whence",type:"number",optional:!0,defaultValue:"SEEK_SET"}],returnType:"number | null",description:"Repositions the file offset. whence is SEEK_SET, SEEK_CUR, or SEEK_END. Returns the new offset, or null on error"}],["tell",{name:"tell",parameters:[],returnType:"number | null",description:"Returns the current file offset, or null on error"}],["dup",{name:"dup",parameters:[],returnType:"io.handle | null",description:"Duplicates the file descriptor and returns a new io.handle, or null on error"}],["dup2",{name:"dup2",parameters:[{name:"newfd",type:"number",optional:!1}],returnType:"io.handle | null",description:"Duplicates the file descriptor to the specified newfd number. Returns a new io.handle, or null on error"}],["fileno",{name:"fileno",parameters:[],returnType:"number | null",description:"Returns the underlying file descriptor number, or null on error"}],["fcntl",{name:"fcntl",parameters:[{name:"cmd",type:"number",optional:!1},{name:"arg",type:"any",optional:!0}],returnType:"any",description:"Performs file control operations. Behavior depends on cmd (F_DUPFD, F_GETFD, F_SETFD, F_GETFL, F_SETFL, etc.)"}],["ioctl",{name:"ioctl",parameters:[{name:"direction",type:"number",optional:!1},{name:"type",type:"number",optional:!1},{name:"number",type:"number",optional:!1},{name:"argument",type:"any",optional:!0}],returnType:"any",description:"Performs device-specific I/O control operations (Linux only)"}],["isatty",{name:"isatty",parameters:[],returnType:"boolean",description:"Tests whether the file descriptor refers to a terminal"}],["close",{name:"close",parameters:[],returnType:"boolean | null",description:"Closes the file descriptor. Returns true on success, null on error"}],["error",{name:"error",parameters:[],returnType:"string | null",description:"Returns the last I/O error message, or null if no error occurred"}],["ptsname",{name:"ptsname",parameters:[],returnType:"string | null",description:"Returns the name of the slave pseudoterminal device corresponding to the master referred to by the handle"}],["tcgetattr",{name:"tcgetattr",parameters:[],returnType:"object | null",description:"Gets the terminal attributes. Returns an object with iflag, oflag, cflag, lflag, ispeed, ospeed, and cc fields"}],["tcsetattr",{name:"tcsetattr",parameters:[{name:"attrs",type:"object",optional:!1},{name:"when",type:"number",optional:!0,defaultValue:"TCSANOW"}],returnType:"boolean | null",description:"Sets the terminal attributes. when can be TCSANOW, TCSADRAIN, or TCSAFLUSH"}],["grantpt",{name:"grantpt",parameters:[],returnType:"boolean | null",description:"Grants access to the slave pseudoterminal. Returns true on success, null on error"}],["unlockpt",{name:"unlockpt",parameters:[],returnType:"boolean | null",description:"Unlocks the slave pseudoterminal. Returns true on success, null on error"}]]),an={name:"io",functions:on,constants:new Map([["O_RDONLY",{name:"O_RDONLY",value:0,type:"number",description:"Read-only file open flag"}],["O_WRONLY",{name:"O_WRONLY",value:1,type:"number",description:"Write-only file open flag"}],["O_RDWR",{name:"O_RDWR",value:2,type:"number",description:"Read-write file open flag"}],["O_CREAT",{name:"O_CREAT",value:64,type:"number",description:"Create file if it does not exist"}],["O_EXCL",{name:"O_EXCL",value:128,type:"number",description:"Fail if file already exists (used with O_CREAT)"}],["O_TRUNC",{name:"O_TRUNC",value:512,type:"number",description:"Truncate file to zero length on open"}],["O_APPEND",{name:"O_APPEND",value:1024,type:"number",description:"Append writes to end of file"}],["O_NONBLOCK",{name:"O_NONBLOCK",value:2048,type:"number",description:"Open in non-blocking mode"}],["O_NOCTTY",{name:"O_NOCTTY",value:256,type:"number",description:"Do not make the opened file the controlling terminal"}],["O_SYNC",{name:"O_SYNC",value:1052672,type:"number",description:"Synchronous I/O — writes block until data is physically written"}],["O_CLOEXEC",{name:"O_CLOEXEC",value:524288,type:"number",description:"Close file descriptor on exec()"}],["O_DIRECTORY",{name:"O_DIRECTORY",value:65536,type:"number",description:"Fail if path is not a directory"}],["O_NOFOLLOW",{name:"O_NOFOLLOW",value:131072,type:"number",description:"Do not follow symbolic links"}],["SEEK_SET",{name:"SEEK_SET",value:0,type:"number",description:"Seek relative to beginning of file"}],["SEEK_CUR",{name:"SEEK_CUR",value:1,type:"number",description:"Seek relative to current position"}],["SEEK_END",{name:"SEEK_END",value:2,type:"number",description:"Seek relative to end of file"}],["F_DUPFD",{name:"F_DUPFD",value:0,type:"number",description:"Duplicate file descriptor (fcntl command)"}],["F_DUPFD_CLOEXEC",{name:"F_DUPFD_CLOEXEC",value:1030,type:"number",description:"Duplicate file descriptor with close-on-exec (fcntl command)"}],["F_GETFD",{name:"F_GETFD",value:1,type:"number",description:"Get file descriptor flags (fcntl command)"}],["F_SETFD",{name:"F_SETFD",value:2,type:"number",description:"Set file descriptor flags (fcntl command)"}],["F_GETFL",{name:"F_GETFL",value:3,type:"number",description:"Get file status flags (fcntl command)"}],["F_SETFL",{name:"F_SETFL",value:4,type:"number",description:"Set file status flags (fcntl command)"}],["F_GETLK",{name:"F_GETLK",value:5,type:"number",description:"Get record lock (fcntl command)"}],["F_SETLK",{name:"F_SETLK",value:6,type:"number",description:"Set record lock (fcntl command)"}],["F_SETLKW",{name:"F_SETLKW",value:7,type:"number",description:"Set record lock and wait (fcntl command)"}],["F_GETOWN",{name:"F_GETOWN",value:9,type:"number",description:"Get process/group receiving SIGIO (fcntl command)"}],["F_SETOWN",{name:"F_SETOWN",value:8,type:"number",description:"Set process/group to receive SIGIO (fcntl command)"}],["FD_CLOEXEC",{name:"FD_CLOEXEC",value:1,type:"number",description:"Close-on-exec file descriptor flag"}],["TCSANOW",{name:"TCSANOW",value:0,type:"number",description:"Apply terminal changes immediately"}],["TCSADRAIN",{name:"TCSADRAIN",value:1,type:"number",description:"Apply terminal changes after output is drained"}],["TCSAFLUSH",{name:"TCSAFLUSH",value:2,type:"number",description:"Apply terminal changes after output is drained, discarding pending input"}],["IOC_DIR_NONE",{name:"IOC_DIR_NONE",value:0,type:"number",description:"No data transfer direction (ioctl)"}],["IOC_DIR_READ",{name:"IOC_DIR_READ",value:2,type:"number",description:"Read direction (ioctl)"}],["IOC_DIR_WRITE",{name:"IOC_DIR_WRITE",value:1,type:"number",description:"Write direction (ioctl)"}],["IOC_DIR_RW",{name:"IOC_DIR_RW",value:3,type:"number",description:"Read-write direction (ioctl)"}]]),documentation:"## IO Module\n\n**Object-oriented access to UNIX file descriptors**\n\nThe io module provides low-level I/O operations using POSIX file descriptors, with support for terminal control and pseudo-terminal operations.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { open, O_RDWR } from 'io';\n\nlet handle = open('/tmp/test.txt', O_RDWR);\nhandle.write('Hello World\\n');\nhandle.close();\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as io from 'io';\n\nlet handle = io.open('/tmp/test.txt', io.O_RDWR);\nhandle.write('Hello World\\n');\nhandle.close();\n```\n\n### Module Functions\n\n- **`open()`** - Open a file (POSIX open semantics)\n- **`new()`** - Create handle from existing fd number\n- **`from()`** - Create handle from existing file resource\n- **`pipe()`** - Create a pipe (returns [read, write] handles)\n- **`error()`** - Get last error message\n\n### Handle Methods\n\n- **`read()`**, **`write()`** - Read/write data\n- **`seek()`**, **`tell()`** - File position\n- **`dup()`**, **`dup2()`** - Duplicate file descriptors\n- **`fileno()`** - Get underlying fd number\n- **`fcntl()`**, **`ioctl()`** - File/device control\n- **`isatty()`** - Test if fd is a terminal\n- **`close()`** - Close the handle\n- **`ptsname()`**, **`grantpt()`**, **`unlockpt()`** - Pseudoterminal ops\n- **`tcgetattr()`**, **`tcsetattr()`** - Terminal attributes\n\n*Hover over individual function names for detailed parameter and return type information.*"},cn={typeName:"io.handle",methods:sn},ln=new Map([["error",{name:"error",parameters:[],returnType:"string | null",description:"Returns a string containing a description of the last occurred error or null if there is no error information."}],["cursor",{name:"cursor",parameters:[{name:"config_dir",type:"string",optional:!0,defaultValue:"/etc/config"},{name:"delta_dir",type:"string",optional:!0,defaultValue:"/tmp/.uci"},{name:"config2_dir",type:"string",optional:!0,defaultValue:"/var/run/uci"},{name:"flags",type:"object",optional:!0}],returnType:"uci.cursor | null",description:"Instantiate uci cursor. A uci cursor is a context for interacting with uci configuration files."}]]),un=new Map([["load",{name:"load",parameters:[{name:"config",type:"string",optional:!1}],returnType:"boolean | null",description:"Explicitly reload configuration file. Returns true if the configuration was successfully loaded."}],["unload",{name:"unload",parameters:[{name:"config",type:"string",optional:!1}],returnType:"boolean | null",description:"Explicitly unload configuration file. Returns true if the configuration was successfully unloaded."}],["get",{name:"get",parameters:[{name:"config",type:"string",optional:!1},{name:"section",type:"string",optional:!1},{name:"option",type:"string",optional:!0}],returnType:"string | string[] | null",description:"Query a single option value or section type. When invoked with three arguments, returns the option value. When invoked with two arguments, returns the section type."}],["get_all",{name:"get_all",parameters:[{name:"config",type:"string",optional:!1},{name:"section",type:"string",optional:!0}],returnType:"object | null",description:"Query a complete section or configuration. When invoked with two arguments, returns all values of the specified section. When invoked with one argument, returns a nested dictionary of all sections."}],["get_first",{name:"get_first",parameters:[{name:"config",type:"string",optional:!1},{name:"type",type:"string",optional:!1},{name:"option",type:"string",optional:!0}],returnType:"string | string[] | null",description:"Query option value or name of first section of given type. When invoked with three arguments, returns the option value. When invoked with two arguments, returns the section name."}],["add",{name:"add",parameters:[{name:"config",type:"string",optional:!1},{name:"type",type:"string",optional:!1}],returnType:"string | null",description:"Add anonymous section to given configuration. Returns the autogenerated, ephemeral name of the added unnamed section."}],["set",{name:"set",parameters:[{name:"config",type:"string",optional:!1},{name:"section",type:"string",optional:!1},{name:"option_or_type",type:"string",optional:!1},{name:"value",type:"string | string[] | number | boolean",optional:!0}],returnType:"boolean | null",description:"Set option value or add named section in given configuration. Returns true if the operation succeeded."}],["delete",{name:"delete",parameters:[{name:"config",type:"string",optional:!1},{name:"section",type:"string",optional:!1},{name:"option",type:"string",optional:!0}],returnType:"boolean | null",description:"Delete an option or section from given configuration. When invoked with three arguments, deletes the option. When invoked with two arguments, deletes the entire section."}],["list_append",{name:"list_append",parameters:[{name:"config",type:"string",optional:!1},{name:"section",type:"string",optional:!1},{name:"option",type:"string",optional:!1},{name:"value",type:"string | number | boolean",optional:!1}],returnType:"boolean | null",description:"Add an item to a list option in given configuration. The new value is appended to the end of the list."}],["list_remove",{name:"list_remove",parameters:[{name:"config",type:"string",optional:!1},{name:"section",type:"string",optional:!1},{name:"option",type:"string",optional:!1},{name:"value",type:"string | number | boolean",optional:!1}],returnType:"boolean | null",description:"Remove an item from a list option in given configuration. If the value appears multiple times, all matching occurrences will be removed."}],["rename",{name:"rename",parameters:[{name:"config",type:"string",optional:!1},{name:"section",type:"string",optional:!1},{name:"option_or_name",type:"string",optional:!1},{name:"name",type:"string",optional:!0}],returnType:"boolean | null",description:"Rename an option or section in given configuration. When invoked with four arguments, renames the option. When invoked with three arguments, renames the section."}],["reorder",{name:"reorder",parameters:[{name:"config",type:"string",optional:!1},{name:"section",type:"string",optional:!1},{name:"index",type:"number",optional:!1}],returnType:"boolean | null",description:"Reorder sections in given configuration. Moves a single section by repositioning it to the given index within the configuration's section list."}],["save",{name:"save",parameters:[{name:"config",type:"string",optional:!0}],returnType:"boolean | null",description:"Save accumulated cursor changes to delta directory. When config parameter is omitted, delta records for all currently loaded configuration files are written."}],["commit",{name:"commit",parameters:[{name:"config",type:"string",optional:!0}],returnType:"boolean | null",description:"Update configuration files with accumulated cursor changes. When config parameter is omitted, all currently loaded configuration files are updated."}],["revert",{name:"revert",parameters:[{name:"config",type:"string",optional:!0}],returnType:"boolean | null",description:"Revert accumulated cursor changes and associated delta records. When config parameter is omitted, all currently loaded configuration files are reverted."}],["changes",{name:"changes",parameters:[{name:"config",type:"string",optional:!0}],returnType:"object | null",description:"Enumerate pending changes. Returns a dictionary of change record arrays, keyed by configuration name."}],["foreach",{name:"foreach",parameters:[{name:"config",type:"string",optional:!1},{name:"type",type:"string",optional:!0},{name:"callback",type:"function",optional:!1}],returnType:"boolean | null",description:"Iterate configuration sections. The callback is invoked for each encountered section, optionally filtered by type."}],["configs",{name:"configs",parameters:[],returnType:"string[] | null",description:"Enumerate existing configurations. Returns an array of configuration files present in the cursor's associated configuration directory."}],["error",{name:"error",parameters:[],returnType:"string | null",description:"Query error information. Returns a string containing a description of the last occurred error or null if there is no error information."}]]);var pn;function dn(e){return{type:C.OBJECT,moduleName:e}}!function(e){e.UCI_CURSOR="uci.cursor"}(pn||(pn={}));const mn={name:"uci",functions:ln,documentation:"## UCI Module\n\n**OpenWrt UCI configuration interface for ucode scripts**\n\nThe uci module provides access to the native OpenWrt libuci API for reading and manipulating UCI configuration files.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { cursor, error } from 'uci';\n\nlet ctx = cursor();\nlet val = ctx.get('network', 'lan', 'proto');\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as uci from 'uci';\n\nlet ctx = uci.cursor();\nlet val = ctx.get('network', 'lan', 'proto');\n```\n\n### Available Functions\n\n- **`error()`** - Get last error description\n- **`cursor()`** - Create a UCI cursor for configuration access\n\n### Cursor Methods\n\n- **`load()`**, **`unload()`** - Load/unload configuration files\n- **`get()`**, **`get_all()`**, **`get_first()`** - Query configuration\n- **`set()`**, **`add()`**, **`delete()`** - Modify configuration\n- **`list_append()`**, **`list_remove()`** - List operations\n- **`rename()`**, **`reorder()`** - Rename/reorder sections\n- **`save()`**, **`commit()`**, **`revert()`** - Persistence\n- **`changes()`** - Enumerate pending changes\n- **`foreach()`** - Iterate sections\n- **`configs()`** - List available configurations\n\n*Hover over individual function names for detailed parameter and return type information.*"},hn={typeName:"uci.cursor",methods:un,formatDoc:(e,t)=>{const n=t.parameters.map(e=>e.optional&&void 0!==e.defaultValue?`[${e.name}: ${e.type}] = ${e.defaultValue}`:e.optional?`[${e.name}: ${e.type}]`:`${e.name}: ${e.type}`).join(", ");let r=`**${t.name}(${n}): ${t.returnType}**\n\n${t.description}\n\n`;return t.parameters.length>0&&(r+="**Parameters:**\n",t.parameters.forEach(e=>{const t=e.optional?" (optional)":"",n=void 0!==e.defaultValue?` (default: ${e.defaultValue})`:"";r+=`- \`${e.name}\` (${e.type}${t}${n})\n`}),r+="\n"),r+=`**Returns:** \`${t.returnType}\``,r}};new class{isVariableOfUciType(e){return"object"==typeof e&&"moduleName"in e&&e.moduleName===pn.UCI_CURSOR?pn.UCI_CURSOR:null}getUciMethod(e,t){if(e===pn.UCI_CURSOR)return un.get(t)}};const fn={name:"uloop",functions:new Map([["error",{name:"error",parameters:[],returnType:"string | null",description:"Retrieves the last error message generated by the uloop event loop. Returns null if no error occurred."}],["init",{name:"init",parameters:[],returnType:"boolean | null",description:'Initializes the uloop event loop, allowing subsequent usage of uloop functionalities. Returns true on success, null on error.\n\n**Example:**\n```ucode\n// Initialize the uloop event loop\nif (init())\n printf("uloop initialized successfully\\n");\nelse\n die(`Initialization failed: ${error()}\\n`);\n```'}],["run",{name:"run",parameters:[{name:"timeout",type:"integer",optional:!0,defaultValue:-1}],returnType:"integer | null",description:"Runs the uloop event loop. If timeout is provided and non-negative, runs for that many milliseconds. If timeout is omitted or negative, runs indefinitely until stopped.\n\n**Example:**\n```ucode\n// Run event loop for 5 seconds\nrun(5000);\n\n// Run event loop indefinitely\nrun();\n```"}],["cancelling",{name:"cancelling",parameters:[],returnType:"boolean",description:"Checks if the uloop event loop is currently shutting down. Returns true if shutting down, false otherwise."}],["running",{name:"running",parameters:[],returnType:"boolean",description:"Checks if the uloop event loop is currently started and running. Returns true if running, false otherwise."}],["end",{name:"end",parameters:[],returnType:"null",description:"Halts the uloop event loop, stopping its execution. Expired timeouts and already queued event callbacks are still run to completion."}],["done",{name:"done",parameters:[],returnType:"null",description:"Stops the uloop event loop and cancels pending timeouts and events, unregisters all handles, and deallocates associated resources."}],["timer",{name:"timer",parameters:[{name:"timeout",type:"integer",optional:!0,defaultValue:-1},{name:"callback",type:"function",optional:!1}],returnType:"uloop.timer | null",description:'Creates a timer instance for scheduling callbacks. Takes an optional timeout in milliseconds and a callback function to execute when the timer expires.\n\n**Example:**\n```ucode\n// Create a timer that fires after 1000ms\nlet myTimer = timer(1000, () => {\n printf("Timer expired!\\n");\n});\n```'}],["handle",{name:"handle",parameters:[{name:"handle",type:"integer | fs.file | fs.proc | socket.socket",optional:!1},{name:"callback",type:"function",optional:!1},{name:"events",type:"integer",optional:!1}],returnType:"uloop.handle | null",description:'Creates a handle instance for monitoring file descriptor events. Takes a file handle, callback function, and bitwise OR-ed flags of IO events (ULOOP_READ, ULOOP_WRITE).\n\n**Example:**\n```ucode\n// Monitor a file descriptor for read events\nlet myHandle = handle(3, (events) => {\n if (events & ULOOP_READ)\n printf("Data ready to read!\\n");\n}, ULOOP_READ);\n```'}],["process",{name:"process",parameters:[{name:"executable",type:"string",optional:!1},{name:"args",type:"array",optional:!0},{name:"env",type:"object",optional:!0},{name:"callback",type:"function",optional:!1}],returnType:"uloop.process | null",description:"Creates a process instance for executing external programs. Takes executable path, optional arguments array, optional environment variables, and callback function."}],["task",{name:"task",parameters:[{name:"taskFunction",type:"function",optional:!1},{name:"outputCallback",type:"function",optional:!0},{name:"inputCallback",type:"function",optional:!0}],returnType:"uloop.task | null",description:"Creates a task instance for executing background tasks. Takes the task function, optional output callback, and optional input callback."}],["interval",{name:"interval",parameters:[{name:"timeout",type:"integer",optional:!0,defaultValue:-1},{name:"callback",type:"function",optional:!1}],returnType:"uloop.interval | null",description:"Creates an interval instance for scheduling repeated callbacks. Takes optional interval in milliseconds and callback function to execute repeatedly."}],["signal",{name:"signal",parameters:[{name:"signal",type:"string | integer",optional:!1},{name:"callback",type:"function",optional:!1}],returnType:"uloop.signal | null",description:"Creates a signal instance for handling Unix signals. Takes signal name (with or without 'SIG' prefix) or signal number, and callback function."}],["guard",{name:"guard",parameters:[{name:"handler",type:"function",optional:!0}],returnType:"function | boolean | null",description:"Sets or gets the exception handler for uloop callbacks. If no arguments, returns current handler. If handler provided, sets it and returns true."}]]),constants:new Map([["ULOOP_READ",{name:"ULOOP_READ",value:1,type:"integer",description:"File or socket is readable - used with handle() to monitor read events"}],["ULOOP_WRITE",{name:"ULOOP_WRITE",value:2,type:"integer",description:"File or socket is writable - used with handle() to monitor write events"}],["ULOOP_EDGE_TRIGGER",{name:"ULOOP_EDGE_TRIGGER",value:4,type:"integer",description:"Enable edge-triggered event mode - used with handle() for edge-triggered notifications"}],["ULOOP_BLOCKING",{name:"ULOOP_BLOCKING",value:8,type:"integer",description:"Do not make descriptor non-blocking - used with handle() to keep descriptor in blocking mode"}]]),documentation:"## uloop Module\n\n**OpenWrt uloop event loop module**\n\nProvides event-driven programming capabilities for handling timers, file descriptors, processes, signals, and background tasks.\n\n### Usage\n\n**Named import syntax:**\n```ucode\nimport { init, run, timer, handle, ULOOP_READ } from 'uloop';\n\ninit();\nlet t = timer(1000, () => printf(\"tick\\n\"));\nrun();\n```\n\n**Namespace import syntax:**\n```ucode\nimport * as uloop from 'uloop';\n\nuloop.init();\nlet t = uloop.timer(1000, () => printf(\"tick\\n\"));\nuloop.run();\n```\n\n### Available Functions\n\n- **`init()`** - Initialize the event loop\n- **`run()`** - Run the event loop\n- **`end()`** / **`done()`** - Stop the event loop\n- **`timer()`** - Create a one-shot timer\n- **`interval()`** - Create a repeating interval\n- **`handle()`** - Monitor file descriptor events\n- **`process()`** - Launch and monitor external processes\n- **`task()`** - Run background tasks\n- **`signal()`** - Handle Unix signals\n- **`guard()`** - Set exception handler\n- **`cancelling()`** / **`running()`** - Query event loop state\n- **`error()`** - Get last error message\n\n### Constants\n\n**Event flags:** ULOOP_READ, ULOOP_WRITE, ULOOP_EDGE_TRIGGER, ULOOP_BLOCKING\n\n*Hover over individual function names for detailed parameter and return type information.*"};var gn;!function(e){e.ULOOP_TIMER="uloop.timer",e.ULOOP_HANDLE="uloop.handle",e.ULOOP_PROCESS="uloop.process",e.ULOOP_TASK="uloop.task",e.ULOOP_INTERVAL="uloop.interval",e.ULOOP_SIGNAL="uloop.signal",e.ULOOP_PIPE="uloop.pipe"}(gn||(gn={}));const yn=new Map([["set",{name:"set",parameters:[{name:"timeout",type:"integer",optional:!0,defaultValue:-1}],returnType:"boolean | null",description:"Rearms the uloop timer with the specified timeout in milliseconds. Returns true on success, null on error."}],["remaining",{name:"remaining",parameters:[],returnType:"integer",description:"Returns the number of milliseconds until the timer expires, or -1 if the timer is not armed."}],["cancel",{name:"cancel",parameters:[],returnType:"boolean",description:"Cancels the uloop timer, disarming it and removing it from the event loop. Returns true on success."}]]),Tn=new Map([["fileno",{name:"fileno",parameters:[],returnType:"integer",description:"Returns the file descriptor number associated with the handle."}],["handle",{name:"handle",parameters:[],returnType:"fs.file | fs.proc | socket.socket",description:"Returns the underlying file or socket instance associated with the uloop handle."}],["delete",{name:"delete",parameters:[],returnType:"null",description:"Unregisters the uloop handle from the event loop and frees associated resources."}]]),_n=new Map([["pid",{name:"pid",parameters:[],returnType:"integer",description:"Returns the process ID (PID) of the operating system process launched by process()."}],["delete",{name:"delete",parameters:[],returnType:"boolean",description:"Unregisters the process from the uloop event loop and releases associated resources. Returns true on success."}]]),Nn=new Map([["pid",{name:"pid",parameters:[],returnType:"integer",description:"Returns the process ID (PID) of the underlying forked process launched by task()."}],["kill",{name:"kill",parameters:[],returnType:"boolean | null",description:"Terminates the task process by sending SIGTERM. Returns true on success, null on error."}],["finished",{name:"finished",parameters:[],returnType:"boolean",description:"Checks if the task function has already run to completion. Returns true if finished, false otherwise."}]]),Rn=new Map([["set",{name:"set",parameters:[{name:"interval",type:"integer",optional:!0,defaultValue:-1}],returnType:"boolean | null",description:"Rearms the uloop interval with the specified interval in milliseconds. Returns true on success, null on error."}],["remaining",{name:"remaining",parameters:[],returnType:"integer",description:"Returns the milliseconds until the next expiration of the interval, or -1 if not armed."}],["expirations",{name:"expirations",parameters:[],returnType:"integer",description:"Returns the number of times the interval timer has expired (fired) since instantiation."}],["cancel",{name:"cancel",parameters:[],returnType:"boolean",description:"Cancels the uloop interval, disarming it and removing it from the event loop. Returns true on success."}]]),En=new Map([["signo",{name:"signo",parameters:[],returnType:"integer",description:"Returns the signal number that this uloop signal handler is configured to respond to."}],["delete",{name:"delete",parameters:[],returnType:"boolean",description:"Uninstalls the signal handler, restoring the previous or default handler for the signal. Returns true on success."}]]),bn=new Map([["send",{name:"send",parameters:[{name:"msg",type:"any",optional:!1}],returnType:"boolean | null",description:"Sends a serialized message to the task handle. Returns true on success, null on error."}],["receive",{name:"receive",parameters:[],returnType:"any | null",description:"Reads input from the task communication pipe. Returns the deserialized message or null on error."}],["sending",{name:"sending",parameters:[],returnType:"boolean",description:"Checks if the remote task handle has an input callback registered. Returns true if available, false otherwise."}],["receiving",{name:"receiving",parameters:[],returnType:"boolean",description:"Checks if the task handle has an output callback registered. Returns true if available, false otherwise."}]]),vn={typeName:"uloop.timer",methods:yn},Sn={typeName:"uloop.handle",methods:Tn},Cn={typeName:"uloop.process",methods:_n},An={typeName:"uloop.task",methods:Nn},On={typeName:"uloop.interval",methods:Rn},Ln={typeName:"uloop.signal",methods:En},In={typeName:"uloop.pipe",methods:bn};function Dn(e){return{type:C.OBJECT,moduleName:e}}const kn={[gn.ULOOP_TIMER]:yn,[gn.ULOOP_HANDLE]:Tn,[gn.ULOOP_PROCESS]:_n,[gn.ULOOP_TASK]:Nn,[gn.ULOOP_INTERVAL]:Rn,[gn.ULOOP_SIGNAL]:En,[gn.ULOOP_PIPE]:bn},Pn={debug:mt(Ft),digest:mt(Kt),fs:mt(ae),io:mt(an),log:mt(Ht),math:mt(Gt),nl80211:mt(vt),resolv:mt(Bt),rtnl:mt(yt),socket:mt(Zt),struct:mt(Wt),ubus:mt(en),uci:mt(mn),uloop:mt(fn),zlib:mt(tn)},xn={"fs.file":ht(Q),"fs.dir":ht(J),"fs.proc":ht(z),"fs.statvfs":ht(ce),"io.handle":ht(cn),"uloop.timer":ht(vn),"uloop.handle":ht(Sn),"uloop.process":ht(Cn),"uloop.task":ht(An),"uloop.interval":ht(On),"uloop.signal":ht(Ln),"uloop.pipe":ht(In),"uci.cursor":ht(hn),"nl80211.listener":ht(St),exception:ht(V)};function wn(e){return e in Pn}function Mn(e){return e in xn}function Fn(e){const t=e.trim();if(Mn(t))return t;for(const e of t.split("|")){const t=e.trim();if(t&&Mn(t))return t}return null}function Un(e,t){if(t&&wn(t)){const n=Pn[t].getFunction(e);return pt(n)?Fn(n.value.returnType):null}for(const t of wt){const n=Pn[t].getFunction(e);if(pt(n)){const e=Fn(n.value.returnType);if(e)return e}}return null}function Kn(e,t){const n=Pn[e],r=n.getFunctionDocumentation(t);return pt(r)?r:n.getConstantDocumentation(t)}function Gn(e,t){const n=Pn[e],r=n.getFunctionDocumentation(t);if(pt(r))return r;const i=n.getConstantDocumentation(t);return pt(i)?i:ut(n.getModuleDocumentation())}function Bn(e,t){return xn[e].getMethodDocumentation(t)}Object.keys(xn);class Wn{removeNullFromType(e){if(!L(e))return e===C.NULL?{narrowedType:C.UNKNOWN,excludedTypes:[C.NULL]}:{narrowedType:e,excludedTypes:[]};const t=I(e),n=t.filter(e=>e!==C.NULL);return t.includes(C.NULL)?{narrowedType:O(n),excludedTypes:[C.NULL]}:{narrowedType:e,excludedTypes:[]}}removeTypesFromUnion(e,t){if(!L(e))return t.includes(e)?{narrowedType:C.UNKNOWN,excludedTypes:[e]}:{narrowedType:e,excludedTypes:[]};const n=I(e),r=n.filter(e=>!t.includes(e)),i=n.filter(e=>t.includes(e));return{narrowedType:O(r),excludedTypes:i}}keepOnlyTypes(e,t){if(!L(e))return t.includes(e)?{narrowedType:e,excludedTypes:[]}:e===C.UNKNOWN&&t.length>0?{narrowedType:1===t.length?t[0]:O(t),excludedTypes:[]}:{narrowedType:C.UNKNOWN,excludedTypes:[e]};const n=I(e),r=n.filter(e=>t.includes(e)),i=n.filter(e=>!t.includes(e));return{narrowedType:O(r),excludedTypes:i}}getIncompatibleTypes(e,t){return I(e).filter(e=>!this.isTypeCompatible(e,t))}isSubtype(e,t){return I(e).every(e=>this.isTypeCompatible(e,t))}isSubtypeOfUnion(e,t){if(!t||0===t.length)return!1;const n=I(e),r=new Set(t);return n.every(e=>r.has(e))}getUnassignablePortion(e,t){return O(this.getIncompatibleTypes(e,t))}isTypeCompatible(e,t){return e===t||t===C.UNKNOWN||e===C.UNKNOWN||e===C.INTEGER&&t===C.DOUBLE||t===C.OBJECT&&e===C.ARRAY||t===C.ARRAY&&e===C.OBJECT}containsNull(e){return I(e).includes(C.NULL)}containsType(e,t){return I(e).includes(t)}getIncompatibilityDescription(e,t){const n=this.getIncompatibleTypes(e,t);return 0===n.length?"":1===n.length?`Argument is possibly '${n[0]}', expected '${t}'`:`Argument is possibly '${n.join("' or '")}', expected '${t}'`}requiresNullCheck(e,t){return!!this.containsNull(e)&&I(e).length>1}requiresTypeGuard(e,t){return!this.isSubtype(e,t)&&this.getIncompatibleTypes(e,t).length>0}generateTypeGuardCondition(e,t){switch(t){case C.ARRAY:return`type(${e}) == 'array'`;case C.OBJECT:return`type(${e}) == 'object'`;case C.STRING:return`type(${e}) == 'string'`;case C.INTEGER:return`type(${e}) == 'int'`;case C.DOUBLE:return`type(${e}) == 'double'`;case C.BOOLEAN:return`type(${e}) == 'bool'`;case C.NULL:return`${e} == null`;case C.FUNCTION:return`type(${e}) == 'function'`;default:return`type(${e}) == '${t}'`}}generateNullGuardCondition(e){return`${e} != null`}}const $n={length:0,keys:0,values:0,index:0,rindex:0,sort:0,reverse:0,uniq:0,pop:0,shift:0,slice:0,splice:0,join:1,trim:0,ltrim:0,rtrim:0,ord:0,split:0,substr:0,b64enc:0,b64dec:0,hexdec:0};class jn{narrowingEngine;symbolTable;flowTypeStack=[];currentScopeId=0;getActiveGuardCallback;constructor(e){this.symbolTable=e,this.narrowingEngine=new Wn,this.flowTypeStack.push([])}setActiveGuardCallback(e){this.getActiveGuardCallback=e}enterScope(){this.currentScopeId++;const e=`scope_${this.currentScopeId}`;return this.flowTypeStack.push([]),e}exitScope(){this.flowTypeStack.length>1&&this.flowTypeStack.pop()}getEffectiveType(e,t){for(let n=this.flowTypeStack.length-1;n>=0;n--){const r=this.flowTypeStack[n];if(r)for(const n of r)if(n.variableName===e&&t>=n.effectiveFromOffset&&(-1===n.effectiveToOffset||t<=n.effectiveToOffset))return n.narrowedType}return null}narrowTypeInCurrentScope(e,t,n,r=-1){const i=this.flowTypeStack[this.flowTypeStack.length-1];if(!i)return;const o=`scope_${this.currentScopeId}`;i.push({variableName:e,narrowedType:t,effectiveFromOffset:n,effectiveToOffset:r,scopeId:o})}analyzeIfStatement(e){const t=[];if(!e.test)return t;if("BinaryExpression"===e.test.type){const n=e.test,r=this.extractTypeGuard(n,e.test.start);if(r&&t.push(r),"&&"===n.operator&&"Identifier"===n.left.type){const e=n.left.name,r=this.getOriginalVariableType(e,n.left.start);if(r){const n=this.narrowingEngine.removeNullFromType(r);t.push({variableName:e,guard:{type:"null-check",expression:`${e} && ...`},positiveNarrowing:n.narrowedType,negativeNarrowing:r})}}}if("Identifier"===e.test.type){const n=e.test.name,r=this.getOriginalVariableType(n,e.test.start);if(r){const e=this.narrowingEngine.removeNullFromType(r);t.push({variableName:n,guard:{type:"null-check",expression:n},positiveNarrowing:e.narrowedType,negativeNarrowing:r})}}if("UnaryExpression"===e.test.type){const n=e.test;if("!"===n.operator&&"Identifier"===n.argument?.type){const e=n.argument.name,r=this.getOriginalVariableType(e,n.argument.start);if(r){const n=this.narrowingEngine.removeNullFromType(r);t.push({variableName:e,guard:{type:"null-check",expression:`!${e}`},positiveNarrowing:r,negativeNarrowing:n.narrowedType})}}}if("CallExpression"===e.test.type){const n=this.getNullPropagatingArg(e.test);if(n){const r=this.getVariableName(n.arg);if(r){const i=this.getOriginalVariableType(r,e.test.start);if(i){const e=this.narrowingEngine.removeNullFromType(i);t.push({variableName:r,guard:{type:"null-check",expression:`${n.funcName}(${r})`},positiveNarrowing:e.narrowedType,negativeNarrowing:i})}}}}return t}countOrBranches(e){if("||"!==e.operator)return 1;let t=0;return"BinaryExpression"===e.left.type&&"||"===e.left.operator?t+=this.countOrBranches(e.left):t+=1,"BinaryExpression"===e.right.type&&"||"===e.right.operator?t+=this.countOrBranches(e.right):t+=1,t}collectAndTypeGuards(e,t){const n=[];return"&&"===e.operator?("BinaryExpression"===e.left.type&&n.push(...this.collectAndTypeGuards(e.left,t)),"BinaryExpression"===e.right.type&&n.push(...this.collectAndTypeGuards(e.right,t)),n):this.extractSingleTypeGuardFromExpr(e)}collectOrTypeGuards(e,t){const n=[];return"||"===e.operator?("BinaryExpression"===e.left.type&&n.push(...this.collectOrTypeGuards(e.left,t)),"BinaryExpression"===e.right.type&&n.push(...this.collectOrTypeGuards(e.right,t)),n):this.extractSingleTypeGuardFromExpr(e)}extractSingleTypeGuardFromExpr(e){const t=[];if(("=="===e.operator||"==="===e.operator)&&this.isTypeCall(e.left)&&this.isStringLiteral(e.right)){const n=e.left;if(n.arguments&&n.arguments.length>0){const r=this.getVariableName(n.arguments[0]),i=e.right.value,o=this.stringToUcodeType(i);r&&o&&t.push({variableName:r,testedType:o,isNegative:!1})}}if(("!="===e.operator||"!=="===e.operator)&&this.isTypeCall(e.left)&&this.isStringLiteral(e.right)){const n=e.left;if(n.arguments&&n.arguments.length>0){const r=this.getVariableName(n.arguments[0]),i=e.right.value,o=this.stringToUcodeType(i);r&&o&&t.push({variableName:r,testedType:o,isNegative:!0})}}if(("!="===e.operator||"!=="===e.operator)&&this.isNullLiteral(e.right)){const n=this.getVariableName(e.left);n&&t.push({variableName:n,testedType:C.NULL,isNegative:!0})}if(("!="===e.operator||"!=="===e.operator)&&this.isNullLiteral(e.left)){const n=this.getVariableName(e.right);n&&t.push({variableName:n,testedType:C.NULL,isNegative:!0})}if(("=="===e.operator||"==="===e.operator)&&this.isNullLiteral(e.right)){const n=this.getVariableName(e.left);n&&t.push({variableName:n,testedType:C.NULL,isNegative:!1})}if(("=="===e.operator||"==="===e.operator)&&this.isNullLiteral(e.left)){const n=this.getVariableName(e.right);n&&t.push({variableName:n,testedType:C.NULL,isNegative:!1})}return t}getNullPropagatingArg(e){if("CallExpression"!==e.type)return null;const t=e;if("Identifier"!==t.callee.type)return null;const n=t.callee.name,r=$n[n];if(void 0===r)return null;const i=t.arguments[r];return i?{funcName:n,arg:i}:null}comparisonExcludesNull(e,t,n){if(n)switch(e){case">":return"number"==typeof t&&t>=0;case">=":return"number"==typeof t&&t>0;case"<":return"number"==typeof t&&t<=0;case"<=":return"number"==typeof t&&t<0;case"==":case"===":return null!==t;case"!=":case"!==":return null===t;default:return!1}else switch(e){case"<":return"number"==typeof t&&t>=0;case"<=":return"number"==typeof t&&t>0;case">":return"number"==typeof t&&t<=0;case">=":return"number"==typeof t&&t<0;case"==":case"===":return null!==t;case"!=":case"!==":return null===t;default:return!1}}extractTypeGuard(e,t){if("&&"===e.operator){const n=this.collectAndTypeGuards(e,t);if(n.length>=2){const e=n[0];if(!e)return null;const r=e.variableName;if(!n.every(e=>e.variableName===r))return null;const i=this.getOriginalVariableType(r,t);if(!i)return null;const o=I(i),s=n.filter(e=>o.includes(e.testedType));if(0===s.length)return null;const a=o.filter(e=>s.every(t=>t.isNegative?e!==t.testedType:e===t.testedType));if(0===a.length||a.length===o.length)return null;const c=this.narrowingEngine.keepOnlyTypes(i,a),l=this.narrowingEngine.removeTypesFromUnion(i,a),u=s.map(e=>`type(${e.variableName}) ${e.isNegative?"!=":"=="} '${this.ucodeTypeToString(e.testedType)}'`).join(" && "),p=s.find(e=>!e.isNegative)?.testedType||s[0]?.testedType;return p?{variableName:r,guard:{type:"type-check",expression:u,testedType:p},positiveNarrowing:c.narrowedType,negativeNarrowing:l.narrowedType}:null}}if("||"===e.operator){const n=this.countOrBranches(e),r=this.collectOrTypeGuards(e,t);if(r.length<n)return null;if(r.length>=2){const e=r[0];if(!e)return null;const n=e.variableName;if(!r.every(e=>e.variableName===n))return null;const i=this.getOriginalVariableType(n,t);if(!i)return null;const o=I(i),s=o.filter(e=>r.some(t=>t.isNegative?e!==t.testedType:e===t.testedType));if(r.some(e=>!!e.isNegative&&!o.includes(e.testedType))&&s.length===o.length)return null;const a=r.filter(e=>(e.isNegative,o.includes(e.testedType)));if(0===a.length)return null;if(0===s.length||s.length===o.length)return null;const c=this.narrowingEngine.keepOnlyTypes(i,s),l=this.narrowingEngine.removeTypesFromUnion(i,s),u=a.map(e=>`type(${e.variableName}) ${e.isNegative?"!=":"=="} '${this.ucodeTypeToString(e.testedType)}'`).join(" || "),p=a.find(e=>!e.isNegative)?.testedType||a[0]?.testedType;return p?{variableName:n,guard:{type:"type-check",expression:u,testedType:p},positiveNarrowing:c.narrowedType,negativeNarrowing:l.narrowedType}:null}return null}if(("!="===e.operator||"!=="===e.operator)&&this.isNullLiteral(e.right)){const n=this.getVariableName(e.left);if(n){const e=this.getOriginalVariableType(n,t);if(e)return{variableName:n,guard:{type:"null-check",expression:`${n} != null`},positiveNarrowing:this.narrowingEngine.removeNullFromType(e).narrowedType,negativeNarrowing:e}}}if(("!="===e.operator||"!=="===e.operator)&&this.isNullLiteral(e.left)){const n=this.getVariableName(e.right);if(n){const e=this.getOriginalVariableType(n,t);if(e)return{variableName:n,guard:{type:"null-check",expression:`${n} != null`},positiveNarrowing:this.narrowingEngine.removeNullFromType(e).narrowedType,negativeNarrowing:e}}}if(("=="===e.operator||"==="===e.operator)&&this.isNullLiteral(e.right)){const n=this.getVariableName(e.left);if(n){const e=this.getOriginalVariableType(n,t);if(e){const t=this.narrowingEngine.keepOnlyTypes(e,[C.NULL]),r=this.narrowingEngine.removeNullFromType(e);return{variableName:n,guard:{type:"null-check",expression:`${n} == null`},positiveNarrowing:t.narrowedType,negativeNarrowing:r.narrowedType}}}}if(("=="===e.operator||"==="===e.operator)&&this.isNullLiteral(e.left)){const n=this.getVariableName(e.right);if(n){const e=this.getOriginalVariableType(n,t);if(e){const t=this.narrowingEngine.keepOnlyTypes(e,[C.NULL]),r=this.narrowingEngine.removeNullFromType(e);return{variableName:n,guard:{type:"null-check",expression:`${n} == null`},positiveNarrowing:t.narrowedType,negativeNarrowing:r.narrowedType}}}}if(("=="===e.operator||"==="===e.operator)&&this.isTypeCall(e.left)&&this.isStringLiteral(e.right)){const n=e.left;if(n.arguments&&n.arguments.length>0){const r=this.getVariableName(n.arguments[0]),i=e.right.value,o=this.stringToUcodeType(i);if(r&&o){const e=this.getOriginalVariableType(r,t);if(e){const t=this.narrowingEngine.keepOnlyTypes(e,[o]),n=this.narrowingEngine.removeTypesFromUnion(e,[o]);return{variableName:r,guard:{type:"type-check",expression:`type(${r}) == '${i}'`,testedType:o},positiveNarrowing:t.narrowedType,negativeNarrowing:n.narrowedType}}}}}if(("!="===e.operator||"!=="===e.operator)&&this.isTypeCall(e.left)&&this.isStringLiteral(e.right)){const n=e.left;if(n.arguments&&n.arguments.length>0){const r=this.getVariableName(n.arguments[0]),i=e.right.value,o=this.stringToUcodeType(i);if(r&&o){const e=this.getOriginalVariableType(r,t);if(e){const t=this.narrowingEngine.removeTypesFromUnion(e,[o]),n=this.narrowingEngine.keepOnlyTypes(e,[o]);return{variableName:r,guard:{type:"type-check",expression:`type(${r}) != '${i}'`,testedType:o},positiveNarrowing:t.narrowedType,negativeNarrowing:n.narrowedType}}}}}if(("=="===e.operator||"==="===e.operator||"!="===e.operator||"!=="===e.operator)&&"Identifier"===e.left.type&&this.isStringLiteral(e.right)){const n=this.resolveIndirectTypeCall(e.left);if(n){const r=this.stringToUcodeType(e.right.value);if(r){const i=this.getOriginalVariableType(n.variableName,t);if(i){const t="=="===e.operator||"==="===e.operator,o=t?this.narrowingEngine.keepOnlyTypes(i,[r]):this.narrowingEngine.removeTypesFromUnion(i,[r]),s=t?this.narrowingEngine.removeTypesFromUnion(i,[r]):this.narrowingEngine.keepOnlyTypes(i,[r]);return{variableName:n.variableName,guard:{type:"type-check",expression:`type(${n.variableName}) ${e.operator} '${e.right.value}'`,testedType:r},positiveNarrowing:o.narrowedType,negativeNarrowing:s.narrowedType}}}}}const n=this.getNullPropagatingArg(e.left);if(n&&"Literal"===e.right.type){const r=e.right.value;if(this.comparisonExcludesNull(e.operator,r,!0)){const i=this.getVariableName(n.arg);if(i){const o=this.getOriginalVariableType(i,t);if(o){const t=this.narrowingEngine.removeNullFromType(o);return{variableName:i,guard:{type:"null-check",expression:`${n.funcName}(${i}) ${e.operator} ${r}`},positiveNarrowing:t.narrowedType,negativeNarrowing:o}}}}}const r=this.getNullPropagatingArg(e.right);if(r&&"Literal"===e.left.type){const n=e.left.value;if(this.comparisonExcludesNull(e.operator,n,!1)){const i=this.getVariableName(r.arg);if(i){const o=this.getOriginalVariableType(i,t);if(o){const t=this.narrowingEngine.removeNullFromType(o);return{variableName:i,guard:{type:"null-check",expression:`${n} ${e.operator} ${r.funcName}(${i})`},positiveNarrowing:t.narrowedType,negativeNarrowing:o}}}}}return null}isNullLiteral(e){return"Literal"===e.type&&null===e.value}isStringLiteral(e){return"Literal"===e.type&&"string"==typeof e.value}isTypeCall(e){return"CallExpression"===e.type&&"Identifier"===e.callee?.type&&"type"===e.callee?.name}getVariableName(e){return"Identifier"===e.type?e.name:null}resolveIndirectTypeCall(e){const t=this.symbolTable.lookupAtPosition(e.name,e.start)||this.symbolTable.lookup(e.name);if(!t?.initNode||"CallExpression"!==t.initNode.type)return null;const n=t.initNode;if("Identifier"!==n.callee.type||"type"!==n.callee.name||1!==n.arguments.length||!n.arguments[0])return null;const r=this.getVariableName(n.arguments[0]);return r?{variableName:r}:null}getOriginalVariableType(e,t){const n=this.symbolTable.lookup(e);if(n){if(this.getActiveGuardCallback){const n=this.getActiveGuardCallback(e,t);if(n)return n}return this.getEffectiveType(e,t)||n.dataType}return null}stringToUcodeType(e){switch(e){case"array":return C.ARRAY;case"object":return C.OBJECT;case"string":return C.STRING;case"int":return C.INTEGER;case"double":return C.DOUBLE;case"bool":return C.BOOLEAN;case"null":return C.NULL;case"function":return C.FUNCTION;case"regex":return C.REGEX;default:return null}}ucodeTypeToString(e){switch(e){case C.ARRAY:return"array";case C.OBJECT:return"object";case C.STRING:return"string";case C.INTEGER:return"int";case C.DOUBLE:return"double";case C.BOOLEAN:return"bool";case C.NULL:return"null";case C.FUNCTION:return"function";case C.REGEX:return"regex";default:return"unknown"}}debugFlowTypes(){console.log("Flow Type Stack:",this.flowTypeStack)}}const qn={length:0,keys:0,values:0,index:0,rindex:0,sort:0,reverse:0,uniq:0,pop:0,shift:0,slice:0,splice:0,join:1,trim:0,ltrim:0,rtrim:0,ord:0,split:0,substr:0,b64enc:0,b64dec:0,hexdec:0};class Vn{symbolTable;cfgQueryEngine=null;builtinFunctions;errors=[];warnings=[];builtinValidator;typeCompatibility;typeNarrowing;flowSensitiveTracker;guardContextStack=[];assignmentTargetDepth=0;truthinessDepth=0;currentAST=null;constantAssignmentProperties=new Map;strictMode=!1;transitiveTypeAliases=[];diagnosticTypeAliases=new Map;constructor(e,t){this.cfgQueryEngine=t||null,this.symbolTable=e,this.builtinFunctions=new Map,this.builtinValidator=new $,this.typeCompatibility=new j,this.typeNarrowing=new Wn,this.flowSensitiveTracker=new jn(e),this.builtinValidator.setTypeChecker(this.getNodeTypeDescription.bind(this)),this.builtinValidator.setFullTypeChecker(this.getFullTypeFromNode.bind(this)),this.flowSensitiveTracker.setActiveGuardCallback(this.getActiveGuardType.bind(this)),this.initializeBuiltins()}setCFGQueryEngine(e){this.cfgQueryEngine=e}setTruthinessDepth(e){this.truthinessDepth=e}getTypeNarrowing(){return this.typeNarrowing}initializeBuiltins(){const e=[{name:"print",parameters:[],returnType:C.INTEGER,variadic:!0},{name:"printf",parameters:[C.STRING],returnType:C.INTEGER,variadic:!0},{name:"sprintf",parameters:[C.STRING],returnType:C.STRING,variadic:!0},{name:"length",parameters:[C.UNKNOWN],returnType:C.INTEGER},{name:"substr",parameters:[C.STRING,C.INTEGER],returnType:C.STRING,minParams:2,maxParams:3},{name:"split",parameters:[C.STRING,C.STRING],returnType:O([C.ARRAY,C.NULL]),minParams:2,maxParams:3},{name:"join",parameters:[C.STRING,C.ARRAY],returnType:C.STRING},{name:"trim",parameters:[C.STRING],returnType:C.STRING,minParams:1,maxParams:2},{name:"ltrim",parameters:[C.STRING],returnType:C.STRING,minParams:1,maxParams:2},{name:"rtrim",parameters:[C.STRING],returnType:C.STRING,minParams:1,maxParams:2},{name:"chr",parameters:[C.INTEGER],returnType:C.STRING},{name:"ord",parameters:[C.STRING],returnType:C.INTEGER},{name:"uc",parameters:[C.STRING],returnType:C.STRING},{name:"lc",parameters:[C.STRING],returnType:C.STRING},{name:"type",parameters:[C.UNKNOWN],returnType:C.STRING},{name:"keys",parameters:[C.OBJECT],returnType:C.ARRAY},{name:"values",parameters:[C.OBJECT],returnType:C.ARRAY},{name:"push",parameters:[C.ARRAY],returnType:C.UNKNOWN,variadic:!0},{name:"pop",parameters:[C.ARRAY],returnType:C.UNKNOWN},{name:"shift",parameters:[C.ARRAY],returnType:C.UNKNOWN},{name:"unshift",parameters:[C.ARRAY],returnType:C.UNKNOWN,variadic:!0},{name:"filter",parameters:[C.ARRAY,C.FUNCTION],returnType:C.ARRAY},{name:"index",parameters:[C.UNKNOWN,C.UNKNOWN],returnType:C.INTEGER},{name:"rindex",parameters:[C.STRING,C.UNKNOWN],returnType:C.INTEGER},{name:"require",parameters:[C.STRING],returnType:C.UNKNOWN},{name:"include",parameters:[C.STRING],returnType:C.UNKNOWN},{name:"json",parameters:[C.UNKNOWN],returnType:C.UNKNOWN},{name:"match",parameters:[C.STRING,C.STRING],returnType:O([C.ARRAY,C.NULL])},{name:"replace",parameters:[C.STRING,C.STRING,C.STRING],returnType:C.STRING},{name:"system",parameters:[C.UNKNOWN],returnType:C.INTEGER,minParams:1,maxParams:2},{name:"time",parameters:[],returnType:C.INTEGER},{name:"sleep",parameters:[C.INTEGER],returnType:C.BOOLEAN},{name:"localtime",parameters:[],returnType:C.OBJECT,minParams:0,maxParams:1},{name:"gmtime",parameters:[],returnType:C.OBJECT,minParams:0,maxParams:1},{name:"timelocal",parameters:[C.OBJECT],returnType:C.INTEGER},{name:"timegm",parameters:[C.OBJECT],returnType:C.INTEGER},{name:"min",parameters:[],returnType:C.UNKNOWN,variadic:!0},{name:"max",parameters:[],returnType:C.UNKNOWN,variadic:!0},{name:"uniq",parameters:[C.ARRAY],returnType:C.ARRAY},{name:"b64enc",parameters:[C.STRING],returnType:C.STRING},{name:"b64dec",parameters:[C.STRING],returnType:C.STRING},{name:"hexenc",parameters:[C.STRING],returnType:C.STRING},{name:"hexdec",parameters:[C.STRING,C.STRING],returnType:C.STRING,minParams:1,maxParams:2},{name:"hex",parameters:[C.STRING],returnType:C.INTEGER},{name:"uchr",parameters:[C.INTEGER],returnType:C.STRING},{name:"iptoarr",parameters:[C.STRING],returnType:C.ARRAY},{name:"arrtoip",parameters:[C.ARRAY],returnType:C.STRING},{name:"int",parameters:[C.UNKNOWN],returnType:C.INTEGER},{name:"loadstring",parameters:[C.STRING],returnType:C.FUNCTION},{name:"loadfile",parameters:[C.STRING],returnType:C.FUNCTION},{name:"wildcard",parameters:[C.STRING,C.STRING],returnType:C.BOOLEAN},{name:"regexp",parameters:[C.STRING],returnType:C.REGEX,minParams:1,maxParams:2},{name:"assert",parameters:[],returnType:C.UNKNOWN,variadic:!0,minParams:0},{name:"call",parameters:[C.FUNCTION],returnType:C.UNKNOWN,variadic:!0},{name:"signal",parameters:[C.INTEGER],returnType:C.UNKNOWN,minParams:1,maxParams:2},{name:"clock",parameters:[C.BOOLEAN],returnType:C.ARRAY,minParams:0,maxParams:1},{name:"sourcepath",parameters:[C.INTEGER,C.BOOLEAN],minParams:0,maxParams:2,returnType:C.STRING},{name:"gc",parameters:[],returnType:C.NULL},{name:"die",parameters:[],returnType:C.NULL,minParams:0,maxParams:1},{name:"exists",parameters:[C.OBJECT,C.STRING],returnType:C.BOOLEAN},{name:"exit",parameters:[],returnType:C.NULL,minParams:0,maxParams:1},{name:"getenv",parameters:[C.STRING],returnType:C.STRING},{name:"map",parameters:[C.ARRAY,C.FUNCTION],returnType:C.ARRAY},{name:"reverse",parameters:[C.UNKNOWN],returnType:C.UNKNOWN},{name:"sort",parameters:[C.ARRAY],returnType:C.ARRAY,minParams:1,maxParams:2},{name:"splice",parameters:[C.ARRAY,C.INTEGER],returnType:C.ARRAY,variadic:!0},{name:"slice",parameters:[C.UNKNOWN,C.INTEGER],returnType:C.UNKNOWN,minParams:2,maxParams:3},{name:"warn",parameters:[],returnType:C.INTEGER,variadic:!0},{name:"trace",parameters:[],returnType:C.NULL,minParams:0,maxParams:1},{name:"proto",parameters:[C.OBJECT],returnType:C.OBJECT,minParams:1,maxParams:2},{name:"render",parameters:[C.STRING],returnType:C.STRING,minParams:1,maxParams:2},{name:"abs",parameters:[C.UNKNOWN],returnType:C.UNKNOWN},{name:"atan2",parameters:[C.UNKNOWN,C.UNKNOWN],returnType:C.DOUBLE},{name:"cos",parameters:[C.UNKNOWN],returnType:C.DOUBLE},{name:"exp",parameters:[C.UNKNOWN],returnType:C.DOUBLE},{name:"log",parameters:[C.UNKNOWN],returnType:C.DOUBLE},{name:"sin",parameters:[C.UNKNOWN],returnType:C.DOUBLE},{name:"sqrt",parameters:[C.UNKNOWN],returnType:C.DOUBLE},{name:"pow",parameters:[C.UNKNOWN,C.UNKNOWN],returnType:C.DOUBLE},{name:"rand",parameters:[],returnType:C.DOUBLE,minParams:0,maxParams:2},{name:"srand",parameters:[C.UNKNOWN],returnType:C.NULL},{name:"isnan",parameters:[C.UNKNOWN],returnType:C.BOOLEAN}];for(const t of e)this.builtinFunctions.set(t.name,t)}resetErrors(){this.errors=[],this.warnings=[],this.builtinValidator.resetErrors()}getErrors(){return this.errors}setErrors(e){this.errors=e}withAssignmentTarget(e){this.assignmentTargetDepth++;try{return e()}finally{this.assignmentTargetDepth--}}isAssignmentTargetContext(){return this.assignmentTargetDepth>0}getStaticPropertyName(e){if("Identifier"===e.type)return e.name;if("Literal"===e.type){const t=e;if(void 0!==t.value&&null!==t.value)return String(t.value)}return null}recordConstantAssignment(e,t){let n=this.constantAssignmentProperties.get(e);n||(n=new Set,this.constantAssignmentProperties.set(e,n)),n.add(t)}hasConstantAssignment(e,t){const n=this.constantAssignmentProperties.get(e);return!!n&&n.has(t)}ensureSymbolHasIntegerProperty(e,t){const n=this.symbolTable.lookup(e);n&&(n.propertyTypes||(n.propertyTypes=new Map),n.propertyTypes.has(t)||n.propertyTypes.set(t,C.INTEGER))}checkNode(e){if(!e)return C.UNKNOWN;switch(e.type){case"Literal":return this.checkLiteral(e);case"Identifier":return this.checkIdentifier(e);case"BinaryExpression":case"LogicalExpression":return this.checkBinaryExpression(e);case"UnaryExpression":return this.checkUnaryExpression(e);case"CallExpression":return this.checkCallExpression(e);case"MemberExpression":return this.checkMemberExpression(e);case"AssignmentExpression":return this.checkAssignmentExpression(e);case"ArrayExpression":return this.checkArrayExpression(e);case"ObjectExpression":return this.checkObjectExpression(e);case"ConditionalExpression":return this.checkConditionalExpression(e);case"ArrowFunctionExpression":return this.checkArrowFunctionExpression(e);case"FunctionExpression":return this.checkFunctionExpression(e);case"TemplateLiteral":return C.STRING;case"IfStatement":return this.checkIfStatement(e);case"ExpressionStatement":return this.checkExpressionStatement(e);case"VariableDeclaration":return this.checkVariableDeclaration(e);case"BlockStatement":return this.checkBlockStatement(e);case"ReturnStatement":return this.checkReturnStatement(e);case"BreakStatement":case"ContinueStatement":default:return C.UNKNOWN;case"SwitchStatement":return this.checkSwitchStatement(e);case"TryStatement":return this.checkTryStatement(e);case"CatchClause":return this.checkCatchClause(e);case"ThisExpression":return C.OBJECT}}getResult(){const e=this.builtinValidator.getErrors(),t=this.builtinValidator.getWarnings();return{type:C.UNKNOWN,errors:[...this.errors,...e],warnings:[...this.warnings,...t]}}checkLiteral(e){switch(e.literalType){case"number":return"number"==typeof e.value&&e.value%1==0?C.INTEGER:C.DOUBLE;case"double":return C.DOUBLE;case"string":return C.STRING;case"boolean":return C.BOOLEAN;case"null":return C.NULL;case"regexp":return C.REGEX;default:return C.UNKNOWN}}checkIdentifier(e){const t=this.symbolTable.lookup(e.name);if(t){this.symbolTable.markUsed(e.name,e.start);const n=this.getActiveGuardType(e.name,e.start);let r;r=n||(this.flowSensitiveTracker.getEffectiveType(e.name,e.start)||this.getEffectiveSymbolDataType(t,e.start));const i=e._fullType;return i&&!this.shouldUpdateFullType(i,r)||(e._fullType=r),"string"==typeof r?r:L(r)?C.UNKNOWN:D(r)?C.ARRAY:C.OBJECT}return v.has(e.name)?C.FUNCTION:C.UNKNOWN}getEffectiveSymbolDataType(e,t){return e.currentType&&void 0!==e.currentTypeEffectiveFrom&&t>=e.currentTypeEffectiveFrom?e.currentType:e.dataType}shouldUpdateFullType(e,t){if(this.isModuleLikeType(t)||this.isModuleLikeType(e))return!0;const n=I(e),r=I(t),i=r.every(e=>n.includes(e)),o=n.every(e=>r.includes(e));return!(!i||o)||!(!i||!o)||!(!i&&o)}isModuleLikeType(e){return"object"==typeof e&&!L(e)&&"moduleName"in e}checkBinaryExpression(e){const t=this.checkNode(e.left),n=this.checkNode(e.right);switch(e.operator){case"+":return U.inferAdditionType(t,n);case"-":case"*":case"/":case"%":return U.inferArithmeticType(t,n,e.operator);case"==":case"!=":case"===":case"!==":case"<":case">":case"<=":case">=":return this.typeCompatibility.getComparisonResultType();case"??":return t===C.NULL?n:(t===C.ARRAY||t===C.OBJECT||t===C.FUNCTION||C.REGEX,t);case"&&":case"||":{const r=e.left._fullType||t,i=e.right._fullType||n;let o;return o="||"===e.operator?F.inferLogicalOrFullType(r,i):F.inferLogicalAndFullType(r,i),e._fullType=o,L(o)?C.UNKNOWN:o}case"&":case"|":case"^":case"<<":case">>":const r=t===C.BOOLEAN||t===C.INTEGER||t===C.UNKNOWN,i=n===C.BOOLEAN||n===C.INTEGER||n===C.UNKNOWN;return r&&i||this.warnings.push({message:`Bitwise operation on unexpected types: ${t} ${e.operator} ${n}. Consider using boolean or integer types for clarity.`,start:e.start,end:e.end,severity:"warning"}),this.typeCompatibility.getBitwiseResultType();case"in":return this.checkInOperator(e,t,n);default:return C.UNKNOWN}}checkUnaryExpression(e){"!"===e.operator&&this.truthinessDepth++;const t=this.checkNode(e.argument);"!"===e.operator&&this.truthinessDepth--;const n=this.typeCompatibility.getUnaryResultType(t,e.operator);return n===C.UNKNOWN&&t!==C.UNKNOWN&&this.isDefinitelyInvalidUnaryOperation(t,e.operator)&&this.errors.push({message:`Cannot apply ${e.operator} to ${t}`,start:e.start,end:e.end,severity:"error"}),n}isDefinitelyInvalidUnaryOperation(e,t){switch(t){case"+":case"-":return e===C.ARRAY||e===C.OBJECT;case"++":case"--":case"~":return e===C.STRING||e===C.ARRAY||e===C.OBJECT;default:return!1}}checkInOperator(e,t,n){let r=this.getFullTypeFromNode(e.right)||this.getTypeAsDataType(n);if("Identifier"===e.right.type){const t=e.right.name,n=this.getActiveGuardType(t,e.right.start);if(n)r=n;else{const n=this.flowSensitiveTracker.getEffectiveType(t,e.right.start);n&&(r=n)}const i=this.getGuardsForPosition(this.currentAST,t,e.right.start);if(i.length>0){let e=r;for(const t of i)e=this.applyTypeGuard(e,t);if(this.typeNarrowing.isSubtype(e,C.OBJECT)||this.typeNarrowing.isSubtype(e,C.ARRAY))return C.BOOLEAN;r=e}}if(!this.typeNarrowing.isSubtype(r,C.OBJECT)&&!this.typeNarrowing.isSubtype(r,C.ARRAY)){const t=this.typeNarrowing.getIncompatibleTypes(r,C.OBJECT),n=this.typeNarrowing.isSubtype(r,C.ARRAY);if(t.length>0&&(n||this.typeNarrowing.containsType(r,C.OBJECT))){const t=this.typeNarrowing.getIncompatibilityDescription(r,C.OBJECT);this.warnings.push({message:`'in' operator: ${t}. Use a guard or assertion.`,start:e.right.start,end:e.right.end,severity:"warning"})}else this.errors.push({message:`'in' operator requires object or array on right side, got ${this.getTypeDescription(r)}`,start:e.right.start,end:e.right.end,severity:"error"});return C.BOOLEAN}return this.typeNarrowing.requiresNullCheck(r,"in")&&this.errors.push({message:"Object is possibly 'null'. Use a guard or the optional-in operator.",start:e.right.start,end:e.right.end,severity:"error",code:"nullable-in-operator",data:{variableName:this.getVariableName(e.right),operatorType:"in"}}),C.BOOLEAN}getTypeAsDataType(e){return e}getFullTypeFromNode(e){if("Identifier"===e.type&&this.cfgQueryEngine){const t=e.name,n=this.cfgQueryEngine.getTypeAtPosition(t,e.start);if(n){return this.getActiveGuardType(t,e.start)||n}}return e._fullType||null}getTypeDescription(e){return L(e)?I(e).map(e=>this.getTypeDescription(e)).join(" | "):D(e)?C.ARRAY:e}getVariableName(e){return"Identifier"===e.type?e.name:null}getNodeTypeDescription(e){if("Identifier"===e.type){const t=e.name;let n=this.getFullTypeFromNode(e)||C.UNKNOWN;const r=this.getActiveGuardType(t,e.start);r&&(n=r);const i=this.getGuardsForPosition(this.currentAST,t,e.start);if(i.length>0){let e=n;for(const t of i)e=this.applyTypeGuard(e,t);return this.getTypeDescription(e)}return this.getTypeDescription(n)}if("MemberExpression"===e.type){const t=this.getDottedPath(e);if(t){const n=this.getGuardsForPosition(this.currentAST,t,e.start);if(n.length>0){let t=this.getFullTypeFromNode(e)||C.UNKNOWN;for(const e of n)t=this.applyTypeGuard(t,e);return this.getTypeDescription(t)}}}if("BinaryExpression"===e.type){const t=e;if("||"===t.operator||"&&"===t.operator){const e=this.getNodeTypeDescription(t.left),n=this.getNodeTypeDescription(t.right);if("||"===t.operator){const t=F.inferLogicalOrFullType(e,n);return L(t)?this.getTypeDescription(t):t}{const t=F.inferLogicalAndFullType(e,n);return L(t)?this.getTypeDescription(t):t}}}const t=this.getFullTypeFromNode(e);if(t)return this.getTypeDescription(t);if("CallExpression"===e.type){const t=e;if("Identifier"===t.callee.type){const e=t.callee.name,n=this.symbolTable.lookup(e);if(n&&n.returnType)return this.getTypeDescription(n.returnType)}}return this.checkNode(e)}parseReturnType(e){if(e.includes(" | ")){const t=e.split(" | ").map(e=>e.trim()),n=[];for(const e of t)switch(e){case"boolean":n.push(C.BOOLEAN);break;case"string":n.push(C.STRING);break;case"number":case"integer":n.push(C.INTEGER);break;case"double":n.push(C.DOUBLE);break;case"object":n.push(C.OBJECT);break;case"array":case"string[]":n.push(C.ARRAY);break;case"null":n.push(C.NULL);break;case"function":n.push(C.FUNCTION);break;default:n.push(C.UNKNOWN)}return O(n)}switch(e){case"boolean":return C.BOOLEAN;case"string":return C.STRING;case"number":case"integer":return C.INTEGER;case"double":return C.DOUBLE;case"object":return C.OBJECT;case"array":return C.ARRAY;case"null":return C.NULL;case"function":return C.FUNCTION;default:return C.UNKNOWN}}checkCallExpression(e){if("Identifier"===e.callee.type){const t=e.callee.name;let n=this.symbolTable.lookupAtPosition(t,e.start);if(!n&&this.cfgQueryEngine){const r=this.cfgQueryEngine.getTypeAtPosition(t,e.start);r&&(n={name:t,type:S.VARIABLE,dataType:r,scope:0,declared:!0,used:!0,node:{},declaredAt:e.start,usedAt:[e.start]})}if(n){if(n.type===S.FUNCTION||n.type===S.IMPORTED){if(n.type===S.IMPORTED&&"fs"===n.importedFrom){const e=se.getFunction(t);if(e){const t=this.parseReturnType(e.returnType);return"string"==typeof t?t:L(t)&&I(t)[0]||C.UNKNOWN}}return n.returnType?this.dataTypeToUcodeType(n.returnType):C.UNKNOWN}if(n.type===S.VARIABLE){if("string"==typeof n.dataType){if(n.dataType===C.FUNCTION)return C.UNKNOWN;if(n.dataType===C.UNKNOWN)return C.UNKNOWN}}else if(n.type===S.PARAMETER&&"string"==typeof n.dataType&&(n.dataType===C.FUNCTION||n.dataType===C.UNKNOWN))return C.UNKNOWN}const r=this.builtinFunctions.get(t);return r?this.validateBuiltinCall(e,r):(this.errors.push({message:`Undefined function: ${t}`,start:e.start,end:e.end,severity:"error"}),C.UNKNOWN)}if("MemberExpression"===e.callee.type){const t=e.callee;if("Identifier"===t.object.type&&"Identifier"===t.property.type){const e=t.object.name,n=t.property.name,r=this.symbolTable.lookup(e);if(r?.propertyFunctionReturnTypes?.has(n))switch(r.propertyFunctionReturnTypes.get(n)){case"string":return C.STRING;case"integer":return C.INTEGER;case"double":return C.DOUBLE;case"boolean":return C.BOOLEAN;case"array":return C.ARRAY;case"object":return C.OBJECT;case"function":return C.FUNCTION;case"null":return C.NULL}}const n=this.checkNode(e.callee),r=e.callee._fullType;if(r&&(e._fullType=r,L(r)))return C.UNKNOWN;if(n!==C.UNKNOWN&&n!==C.FUNCTION)return n}if("Identifier"!==e.callee.type){const t=this.checkNode(e.callee);if(!this.typeCompatibility.isValidCallTarget(t))return this.errors.push({message:`Cannot call ${t} as function`,start:e.start,end:e.end,severity:"error"}),C.UNKNOWN}return C.UNKNOWN}validateBuiltinCall(e,t){for(const t of e.arguments)t&&this.checkNode(t);if(this.builtinValidator.inTruthinessContext=this.truthinessDepth>0,this.validateSpecialBuiltins(e,t)){const n=this.builtinValidator.narrowedReturnType;return this.builtinValidator.narrowedReturnType=null,null!==n?"string"!=typeof n?(e._fullType=n,this.dataTypeToUcodeType(n)):n:this.dataTypeToUcodeType(t.returnType)}const n=e.arguments.length,r=t.minParams??t.parameters.length,i=t.maxParams??(t.variadic?1/0:t.parameters.length);n<r?this.errors.push({message:`Function '${t.name}' expects at least ${r} arguments, got ${n}`,start:e.start,end:e.end,severity:"error"}):n>i&&this.errors.push({message:`Function '${t.name}' expects at most ${i} arguments, got ${n}`,start:e.start,end:e.end,severity:"error"});for(let r=0;r<Math.min(n,t.parameters.length);r++){const n=t.parameters[r],i=e.arguments[r];if(!i||!n)continue;const o=this.checkNode(i)||C.UNKNOWN;let s=this.getFullTypeFromNode(i)||this.getTypeAsDataType(o);if("Identifier"===i.type&&(L(s)||s===C.UNKNOWN)){const e=i.name,t=this.getGuardsForPosition(this.currentAST,e,i.start);if(t.length>0){let e=s;for(const n of t)e=this.applyTypeGuard(e,n);s=e}}if("MemberExpression"===i.type){const e=this.getDottedPath(i);if(e){const t=this.getGuardsForPosition(this.currentAST,e,i.start);if(t.length>0){let e=s;for(const n of t)e=this.applyTypeGuard(e,n);s=e}}}if(n!==C.UNKNOWN&&!this.typeNarrowing.isSubtype(s,n)){const e=this.typeNarrowing.getIncompatibleTypes(s,n),o=I(s).some(t=>t===C.UNKNOWN||-1===e.indexOf(t))&&e.length>0,a=this.typeNarrowing.getIncompatibilityDescription(s,n),c=a?`Function '${t.name}': ${a}. Use a guard or assertion.`:`Function '${t.name}' expects ${n} for argument ${r+1}, got ${this.getTypeDescription(s)}`,l={functionName:t.name,argumentIndex:r,expectedType:n,actualType:s,variableName:this.getVariableName(i)};o&&!this.strictMode?this.warnings.push({message:c,start:i.start,end:i.end,severity:"warning",code:"incompatible-function-argument",data:l}):this.errors.push({message:c,start:i.start,end:i.end,severity:"error",code:"incompatible-function-argument",data:l})}}return this.dataTypeToUcodeType(t.returnType)}detectObjectType(e){if("string"==typeof e)return null;if("object"==typeof e&&"moduleName"in e){const t=e.moduleName;if(Mn(t))return t}return null}returnTypeStringToUcodeType(e){if(Object.values(C).includes(e))return e;switch(e){case"integer":case"number":return C.INTEGER;case"string":return C.STRING;case"boolean":return C.BOOLEAN;case"null":return C.NULL;case"array":case"string[]":return C.ARRAY;case"object":case"io.handle":return C.OBJECT;default:return C.UNKNOWN}}dataTypeToUcodeType(e){if("string"==typeof e)return e;if(D(e))return C.ARRAY;const t=e;return t.type===C.UNION?C.UNKNOWN:t.type===C.OBJECT&&"moduleName"in t?C.OBJECT:t.type?t.type:C.UNKNOWN}validateSpecialBuiltins(e,t){switch(t.name){case"length":return this.builtinValidator.validateLengthFunction(e);case"index":return this.builtinValidator.validateIndexFunction(e);case"rindex":return this.builtinValidator.validateRindexFunction(e);case"match":return this.builtinValidator.validateMatchFunction(e);case"split":return this.builtinValidator.validateSplitFunction(e);case"replace":return this.builtinValidator.validateReplaceFunction(e);case"localtime":return this.builtinValidator.validateLocaltimeFunction(e);case"gmtime":return this.builtinValidator.validateGmtimeFunction(e);case"timelocal":return this.builtinValidator.validateTimelocalFunction(e);case"timegm":return this.builtinValidator.validateTimegmFunction(e);case"json":return this.builtinValidator.validateJsonFunction(e);case"call":return this.builtinValidator.validateCallFunction(e);case"signal":return this.builtinValidator.validateSignalFunction(e);case"system":return this.builtinValidator.validateSystemFunction(e);case"sleep":return this.builtinValidator.validateSleepFunction(e);case"min":return this.builtinValidator.validateMinFunction(e);case"max":return this.builtinValidator.validateMaxFunction(e);case"uniq":return this.builtinValidator.validateUniqFunction(e);case"printf":return this.builtinValidator.validatePrintfFunction(e);case"sprintf":return this.builtinValidator.validateSprintfFunction(e);case"iptoarr":return this.builtinValidator.validateIptoarrFunction(e);case"arrtoip":return this.builtinValidator.validateArrtoipFunction(e);case"int":return this.builtinValidator.validateIntFunction(e);case"hex":return this.builtinValidator.validateHexFunction(e);case"chr":return this.builtinValidator.validateChrFunction(e);case"ord":return this.builtinValidator.validateOrdFunction(e);case"uchr":return this.builtinValidator.validateUchrFunction(e);case"require":return this.builtinValidator.validateRequireFunction(e);case"include":return this.builtinValidator.validateIncludeFunction(e);case"hexdec":return this.builtinValidator.validateHexdecFunction(e);case"b64enc":return this.builtinValidator.validateB64encFunction(e);case"b64dec":return this.builtinValidator.validateB64decFunction(e);case"loadfile":return this.builtinValidator.validateLoadfileFunction(e);case"loadstring":return this.builtinValidator.validateLoadstringFunction(e);case"sourcepath":return this.builtinValidator.validateSourcepathFunction(e);case"regexp":return this.builtinValidator.validateRegexpFunction(e);case"wildcard":return this.builtinValidator.validateWildcardFunction(e);case"assert":return this.builtinValidator.validateAssertFunction(e);case"type":return this.builtinValidator.validateTypelocalFunction(e);case"clock":return this.builtinValidator.validateClockFunction(e);case"gc":return this.builtinValidator.validateGcFunction(e);case"push":return this.builtinValidator.validatePushFunction(e);case"pop":return this.builtinValidator.validatePopFunction(e);case"shift":return this.builtinValidator.validateShiftFunction(e);case"unshift":return this.builtinValidator.validateUnshiftFunction(e);case"slice":return this.builtinValidator.validateSliceFunction(e);case"splice":return this.builtinValidator.validateSpliceFunction(e);case"sort":return this.builtinValidator.validateSortFunction(e);case"reverse":return this.builtinValidator.validateReverseFunction(e);case"filter":return this.builtinValidator.validateFilterFunction(e);case"map":return this.builtinValidator.validateMapFunction(e);case"keys":return this.builtinValidator.validateKeysFunction(e);case"values":return this.builtinValidator.validateValuesFunction(e);case"exists":return this.builtinValidator.validateExistsFunction(e);case"trim":return this.builtinValidator.validateTrimFunction(e);case"ltrim":return this.builtinValidator.validateLtrimFunction(e);case"rtrim":return this.builtinValidator.validateRtrimFunction(e);case"substr":return this.builtinValidator.validateSubstrFunction(e);default:return!1}}checkMemberExpression(e){if("ThisExpression"===e.object.type){const t=this.symbolTable.lookup("this");if(t&&t.propertyTypes&&!e.computed){let n=null;if("Identifier"===e.property.type)n=e.property.name;else if("Literal"===e.property.type){const t=e.property;void 0!==t.value&&null!==t.value&&(n=String(t.value))}if(n&&t.propertyTypes.has(n)){const e=t.propertyTypes.get(n);return this.dataTypeToUcodeType(e)}}return C.UNKNOWN}if("Identifier"===e.object.type){const n=this.symbolTable.lookup(e.object.name);if(!n)return C.UNKNOWN;if(!e.computed&&("Identifier"===e.property.type||"Literal"===e.property.type)&&"Identifier"===e.object.type){let t=null;if("Identifier"===e.property.type)t=e.property.name;else{const n=e.property;void 0!==n.value&&null!==n.value&&(t=String(n.value))}if(t&&n.propertyTypes&&n.propertyTypes.has(t)){const e=n.propertyTypes.get(t);return this.dataTypeToUcodeType(e)}}const r=this.detectObjectType(n.dataType);if(r&&!e.computed){const t=e.property.name,n=xn[r].getMethod(t);if(pt(n)){const t=this.parseReturnType(n.value.returnType);return e._fullType=t,L(t)?C.UNKNOWN:this.returnTypeStringToUcodeType(n.value.returnType)}return this.errors.push({message:`Method '${t}' does not exist on ${r}`,start:e.start,end:e.end,severity:"error"}),C.UNKNOWN}if(n.dataType&&"object"==typeof n.dataType&&"moduleName"in n.dataType&&"rtnl-const"===n.dataType.moduleName&&!e.computed){const n=this.getStaticPropertyName(e.property);if(!n)return C.UNKNOWN;if(t=n,!gt.has(t)){const t="Identifier"===e.object.type?e.object.name:null;return t&&this.isAssignmentTargetContext()?(this.recordConstantAssignment(t,n),this.ensureSymbolHasIntegerProperty(t,n),C.INTEGER):t&&this.hasConstantAssignment(t,n)?C.INTEGER:(this.errors.push({message:`Property '${n}' does not exist on rtnl constants object. Available constants: ${Tt().join(", ")}`,start:e.property.start,end:e.property.end,severity:"error"}),C.UNKNOWN)}return C.INTEGER}if(n.dataType&&"object"==typeof n.dataType&&"moduleName"in n.dataType&&"nl80211-const"===n.dataType.moduleName&&!e.computed){const t=this.getStaticPropertyName(e.property);if(!t)return C.UNKNOWN;if(!(e=>Et.has(e))(t)){const n="Identifier"===e.object.type?e.object.name:null;return n&&this.isAssignmentTargetContext()?(this.recordConstantAssignment(n,t),this.ensureSymbolHasIntegerProperty(n,t),C.INTEGER):n&&this.hasConstantAssignment(n,t)?C.INTEGER:(this.errors.push({message:`Property '${t}' does not exist on nl80211 constants object. Available constants: ${Ot().join(", ")}`,start:e.property.start,end:e.property.end,severity:"error"}),C.UNKNOWN)}return C.INTEGER}}var t;if("Identifier"===e.object.type&&e.computed){const t=this.symbolTable.lookup(e.object.name);if(t&&(t.dataType===C.ARRAY||D(t.dataType))){if("Literal"===e.property.type){const n=String(e.property.value);if(t.propertyTypes&&t.propertyTypes.has(n)){const e=t.propertyTypes.get(n);return this.dataTypeToUcodeType(e)}}if(D(t.dataType)){const n=P(t.dataType),r=O([this.dataTypeToUcodeType(n),C.NULL]);return e._fullType=r,C.UNKNOWN}}}const n=this.checkNode(e.object);if(n===C.ARRAY&&e.computed){const t=e.object._fullType;if(t&&D(t)){const n=P(t),r=O([this.dataTypeToUcodeType(n),C.NULL]);return e._fullType=r,C.UNKNOWN}}if(n===C.ARRAY&&!e.computed){const t=e.property.name;return this.errors.push({message:`Property '${t}' does not exist on array type. Arrays in ucode have no properties or methods. Use builtin functions instead (e.g., length(array), filter(array, callback)).`,start:e.property.start,end:e.property.end,severity:"error"}),C.UNKNOWN}if(n===C.OBJECT)return this.typeCompatibility.getObjectPropertyType(n);if(n===C.STRING&&!e.computed){const t=e.property.name;return this.errors.push({message:`Property '${t}' does not exist on string type. Strings in ucode have no member variables or functions.`,start:e.property.start,end:e.property.end,severity:"error"}),C.UNKNOWN}if(n===C.REGEX&&!e.computed){const t=e.property.name;return this.errors.push({message:`Property '${t}' does not exist on regex type. Regular expressions in ucode have no properties or methods. Use builtin functions instead (e.g., match(string, regex), replace(string, regex, replacement)).`,start:e.property.start,end:e.property.end,severity:"error"}),C.UNKNOWN}return C.UNKNOWN}checkAssignmentExpression(e){const t=this.checkNode(e.left),n=this.checkNode(e.right);if("="===e.operator&&"MemberExpression"===e.left.type){const t=e.left;if("Identifier"===t.object.type&&t.computed){const e=t.object.name,r=this.symbolTable.lookup(e);if(r&&(r.dataType===C.ARRAY||D(r.dataType))){let e=null;if("Literal"===t.property.type){const n=t.property;e=String(n.value)}if(null!==e){r.propertyTypes||(r.propertyTypes=new Map);const t=this.ucodeTypeToDataType(n);r.propertyTypes.set(e,t)}}}}return"="===e.operator&&"Identifier"!==e.left.type&&t!==C.UNKNOWN&&n!==C.UNKNOWN&&(this.typeCompatibility.canAssign(t,n)||this.warnings.push({message:`Type mismatch: assigning ${n} to ${t}`,start:e.start,end:e.end,severity:"warning"})),n}ucodeTypeToDataType(e){return e}checkArrayExpression(e){const t=[];for(const n of e.elements)if(n){const e=this.checkNode(n),r=n._fullType;r&&(L(r)||D(r))?t.some(e=>"string"==typeof e&&"string"==typeof r&&e===r||"string"!=typeof e&&"string"!=typeof r&&JSON.stringify(e)===JSON.stringify(r))||t.push(r):e!==C.UNKNOWN&&(t.includes(e)||t.push(e))}if(t.length>0){let n;n=1===t.length?t[0]:O(t.every(e=>"string"==typeof e)?t:t.map(e=>"string"==typeof e?e:C.ARRAY)),e._fullType=k(n)}return C.ARRAY}checkObjectExpression(e){for(const t of e.properties)"SpreadElement"!==t.type&&(this.checkNode(t.key),this.checkNode(t.value));return C.OBJECT}checkConditionalExpression(e){this.truthinessDepth++,this.checkNode(e.test),this.truthinessDepth--;const t=this.checkNode(e.consequent),n=this.checkNode(e.alternate),r=this.typeCompatibility.getTernaryResultType(t,n);return this.getTypeDescription(r)}checkArrowFunctionExpression(e){return C.FUNCTION}checkFunctionExpression(e){return C.FUNCTION}checkIfStatement(e){this.truthinessDepth++,this.checkNode(e.test),this.truthinessDepth--;const t=this.flowSensitiveTracker.analyzeIfStatement(e),n=[];for(const e of t){const t=this.diagnosticTypeAliases.get(e.variableName);if(t)for(const r of t)n.push({...e,variableName:r})}if(t.push(...n),e.consequent){for(const n of t)this.pushGuardContext(n.variableName,n.positiveNarrowing,e.consequent.start,e.consequent.end);this.checkNode(e.consequent);for(let e=0;e<t.length;e++)this.popGuardContext()}if(e.alternate){for(const n of t)this.pushGuardContext(n.variableName,n.negativeNarrowing,e.alternate.start,e.alternate.end);this.checkNode(e.alternate);for(let e=0;e<t.length;e++)this.popGuardContext()}return C.UNKNOWN}checkExpressionStatement(e){return this.checkNode(e.expression)}checkVariableDeclaration(e){for(const t of e.declarations)t.init&&this.checkNode(t.init);return C.UNKNOWN}checkBlockStatement(e){const t=this.diagnosticTypeAliases;this.diagnosticTypeAliases=new Map(t);for(let t=0;t<e.body.length;t++){const n=e.body[t];if("IfStatement"===n.type){const r=n;if(r.consequent&&this.blockAlwaysTerminates(r.consequent)){const i=this.detectTypeEqualityAlias(r.test);i&&(this.diagnosticTypeAliases.has(i.var1)||this.diagnosticTypeAliases.set(i.var1,[]),this.diagnosticTypeAliases.get(i.var1).includes(i.var2)||this.diagnosticTypeAliases.get(i.var1).push(i.var2),this.diagnosticTypeAliases.has(i.var2)||this.diagnosticTypeAliases.set(i.var2,[]),this.diagnosticTypeAliases.get(i.var2).includes(i.var1)||this.diagnosticTypeAliases.get(i.var2).push(i.var1));const o=this.flowSensitiveTracker.analyzeIfStatement(r),s=[];for(const e of o){const t=this.diagnosticTypeAliases.get(e.variableName);if(t)for(const n of t)s.push({...e,variableName:n})}if(o.push(...s),o.length>0){this.checkNode(n);for(const t of o)this.pushGuardContext(t.variableName,t.negativeNarrowing,n.end,e.end);for(let n=t+1;n<e.body.length;n++)this.checkNode(e.body[n]);for(let e=0;e<o.length;e++)this.popGuardContext();return C.UNKNOWN}}}this.checkNode(n)}return this.diagnosticTypeAliases=t,C.UNKNOWN}blockAlwaysTerminates(e){let t;if(t="BlockStatement"===e.type?e.body:[e],0===t.length)return!1;const n=t[t.length-1];if("ReturnStatement"===n.type)return!0;if("BreakStatement"===n.type)return!0;if("ContinueStatement"===n.type)return!0;if("ExpressionStatement"===n.type){const e=n.expression;if("CallExpression"===e.type){const t=e;if("Identifier"===t.callee.type){const e=t.callee.name;if("die"===e||"exit"===e)return!0;const n=this.symbolTable.lookup(e);if(n?.neverReturns)return!0}}}return!1}checkReturnStatement(e){return e.argument?this.checkNode(e.argument):C.UNKNOWN}checkSwitchStatement(e){this.checkNode(e.discriminant);const t=this.getTypeSwitchVariable(e.discriminant),n=[];for(const r of e.cases){let e=!1;if(t&&r.consequent.length>0){const{start:i,end:o}=this.getCaseRange(r),s=this.getBaseTypeForPosition(t.variableName,i);let a=null;if(r.test&&"Literal"===r.test.type){const e=r.test;if("string"==typeof e.value){const t=this.stringLiteralToUcodeType(e.value);t&&(n.includes(t)||n.push(t),a=this.typeNarrowing.keepOnlyTypes(s,[t]).narrowedType)}}else!r.test&&n.length>0?a=this.typeNarrowing.removeTypesFromUnion(s,n).narrowedType:r.test||(a=s);a&&(this.pushGuardContext(t.variableName,a,i,o),e=!0)}for(const e of r.consequent)this.checkNode(e);t&&e&&this.popGuardContext()}return C.UNKNOWN}getTypeSwitchVariable(e){if("CallExpression"!==e.type)return null;const t=e;return"Identifier"!==t.callee.type||"type"!==t.callee.name?null:t.arguments.length&&t.arguments[0]&&"Identifier"===t.arguments[0].type?{variableName:t.arguments[0].name}:null}getCaseRange(e){if(e.consequent.length>0){const t=e.consequent[0],n=e.consequent[e.consequent.length-1];return{start:t.start,end:n.end}}return{start:e.start,end:e.end}}stringLiteralToUcodeType(e){switch(e){case"array":return C.ARRAY;case"object":return C.OBJECT;case"string":return C.STRING;case"int":return C.INTEGER;case"double":return C.DOUBLE;case"bool":return C.BOOLEAN;case"function":return C.FUNCTION;case"null":return C.NULL;case"regex":case"regexp":return C.REGEX;default:return null}}checkTryStatement(e){return e.block&&this.checkNode(e.block),e.handler&&this.checkNode(e.handler),e.finalizer&&this.checkNode(e.finalizer),C.UNKNOWN}checkCatchClause(e){if(this.symbolTable.enterScope(),e.param){const t=Y();this.symbolTable.declare(e.param.name,S.PARAMETER,t,e.param)}return e.body&&this.checkNode(e.body),this.symbolTable.exitScope(e.end),C.UNKNOWN}getBaseTypeForPosition(e,t){const n=this.getActiveGuardType(e,t);if(n)return n;const r=this.flowSensitiveTracker.getEffectiveType(e,t);if(r)return r;const i=this.symbolTable.lookup(e);return i?i.dataType:C.UNKNOWN}caseHasBreak(e){for(const t of e.consequent){if("BreakStatement"===t.type||"ReturnStatement"===t.type)return!0;if("BlockStatement"===t.type){const e=t;if(e.body&&Array.isArray(e.body))for(const t of e.body)if("BreakStatement"===t.type||"ReturnStatement"===t.type)return!0}}return!1}getCommonReturnType(e){return this.typeCompatibility.getCommonType(e)}get flowTracker(){return this.flowSensitiveTracker}setAST(e){this.currentAST=e,this.strictMode=this.detectStrictMode(e),this.builtinValidator.setStrictMode(this.strictMode)}detectStrictMode(e){if(!e.body||0===e.body.length)return!1;const t=e.body[0];if("ExpressionStatement"===t?.type){const e=t.expression;if("Literal"===e?.type&&"use strict"===e.value)return!0}return!1}getNarrowedTypeAtPosition(e,t){const n=this.getActiveGuardType(e,t);if(n)return n;const r=this.getGuardsForPosition(this.currentAST,e,t);let i=this.symbolTable.lookup(e);if(i||(i=this.symbolTable.lookupAtPosition(e,t)),!i){if(r.length>0){const e=this.inferTypeFromGuardsWithoutBase(r);if(e)return e}return null}const o=i.dataType;if(r.length>0){let e=o;for(const t of r)e=this.applyTypeGuard(e,t);return e}return null}getEqualityNarrowSymbolAtPosition(e,t){const n=this.getGuardsForPosition(this.currentAST,e,t);for(const e of n)if(e.equalitySymbol&&!e.isNegative)return e.equalitySymbol;return null}inferTypeFromGuardsWithoutBase(e){if(0===e.length)return null;const t=e.filter(e=>!e.isNegative&&null!==e.narrowToType).map(e=>e.narrowToType);if(0===t.length)return null;const n=Array.from(new Set(t));return 1===n.length?n[0]:O(n)}applyTypeGuard(e,t){if(void 0!==t.equalityNarrowType)return t.isNegative?e:t.equalityNarrowType;if(null===t.narrowToType)return e;if("string"==typeof e&&e.includes(" | ")){const t=e.split(" | ").map(e=>e.trim());e=O(t)}return t.isCombinedOr?t.narrowToType:t.narrowToType===C.NULL?t.isNegative?this.typeNarrowing.removeNullFromType(e).narrowedType:this.typeNarrowing.keepOnlyTypes(e,[C.NULL]).narrowedType:t.isNegative?this.typeNarrowing.removeTypesFromUnion(e,[t.narrowToType]).narrowedType:this.typeNarrowing.keepOnlyTypes(e,[t.narrowToType]).narrowedType}getGuardsForPosition(e,t,n){if(!e)return[];this.transitiveTypeAliases=[];const r=[];return this.collectGuards(e,t,n,r),r}collectGuards(e,t,n,r){if(!e)return;if("BinaryExpression"===e.type){const i=e;if("&&"===i.operator&&n>=i.right.start&&n<=i.right.end){const e=this.findGuardInCondition(i.left,t);return e&&r.push(e),void this.collectGuards(i.right,t,n,r)}}if("IfStatement"===e.type){const i=e;if(i.consequent&&n>=i.consequent.start&&n<=i.consequent.end){const e=this.extractTypeGuard(i.test,t);if(e&&r.push(e),"Identifier"===i.test.type&&i.test.name===t&&r.push({variableName:t,narrowToType:C.NULL,isNegative:!0}),"BinaryExpression"===i.test.type){const e=i.test;"&&"===e.operator&&"Identifier"===e.left.type&&e.left.name===t&&r.push({variableName:t,narrowToType:C.NULL,isNegative:!0})}if("CallExpression"===i.test.type){const e=this.getNullPropagatingArg(i.test);e&&this.getArgVariableName(e.arg)===t&&r.push({variableName:t,narrowToType:C.NULL,isNegative:!0})}return void this.collectGuards(i.consequent,t,n,r)}if(i.alternate&&n>=i.alternate.start&&n<=i.alternate.end){const e=this.extractTypeGuard(i.test,t);if(e&&r.push({...e,isNegative:!e.isNegative}),"UnaryExpression"===i.test.type){const e=i.test;"!"===e.operator&&"Identifier"===e.argument?.type&&e.argument.name===t&&r.push({variableName:t,narrowToType:C.NULL,isNegative:!0})}return void this.collectGuards(i.alternate,t,n,r)}}if("SwitchStatement"===e.type){const i=e,o=this.getTypeSwitchVariable(i.discriminant);if(o&&o.variableName===t){const e=[],o=[];for(const t of i.cases){let n=null;if(t.test&&"Literal"===t.test.type){const r=t.test;"string"==typeof r.value&&(n=this.stringLiteralToUcodeType(r.value),n&&!e.includes(n)&&e.push(n))}const r=this.caseHasBreak(t);o.push({caseNode:t,type:n,hasBreak:r})}for(let i=0;i<o.length;i++){const s=o[i];if(!s||0===s.caseNode.consequent.length)continue;const{start:a,end:c}=this.getCaseRange(s.caseNode);if(n>=a&&n<=c){const a=[];for(let e=0;e<=i;e++){const t=o[e];t&&(t.type&&a.push(t.type),e<i&&t.hasBreak&&t.caseNode.consequent.length>0&&(a.length=0))}if(s.caseNode.test)1===a.length&&void 0!==a[0]?r.push({variableName:t,narrowToType:a[0],isNegative:!1}):a.length>1&&r.push({variableName:t,narrowToType:O(a),isNegative:!1,isCombinedOr:!0});else{const n=e.filter(e=>!a.includes(e));if(n.length>0)for(const e of n)r.push({variableName:t,narrowToType:e,isNegative:!0})}return void this.collectGuards(s.caseNode.consequent[0]||s.caseNode,t,n,r)}}}}const i=this.getChildNodes(e);for(let e=0;e<i.length;e++){const o=i[e];if(n>=o.start&&n<=o.end){for(let n=0;n<e;n++){const e=i[n];if("IfStatement"===e.type){const n=e;if(n.consequent&&this.blockAlwaysTerminates(n.consequent)){const e=this.extractTypeGuard(n.test,t);if(e)e.isNullPropagation||r.push({...e,isNegative:!e.isNegative});else{const e=this.extractAndChainGuards(n.test,t);if(e.length>=2&&e.every(e=>e.isNegative)){const n=e.map(e=>e.narrowToType).filter(e=>null!==e);n.length>=2&&r.push({variableName:t,narrowToType:O(n),isNegative:!1,isCombinedOr:!0})}const i=this.extractOrChainGuards(n.test,t);for(const e of i)r.push({...e,isNegative:!e.isNegative})}if("UnaryExpression"===n.test.type){const e=n.test;if("!"===e.operator&&"Identifier"===e.argument?.type&&e.argument.name===t){const e=this.symbolTable.lookup(t);e&&L(e.dataType)&&I(e.dataType).includes(C.NULL)&&r.push({variableName:t,narrowToType:C.NULL,isNegative:!0})}}const i=this.detectTypeEqualityAlias(n.test);i&&(i.var1!==t||this.transitiveTypeAliases.includes(i.var2)?i.var2!==t||this.transitiveTypeAliases.includes(i.var1)||this.transitiveTypeAliases.push(i.var1):this.transitiveTypeAliases.push(i.var2))}}}return("FunctionDeclaration"===o.type||"FunctionExpression"===o.type||"ArrowFunctionExpression"===o.type)&&this.isShadowedInFunction(o,t)&&(r.length=0),void this.collectGuards(o,t,n,r)}}}isShadowedInFunction(e,t){if(t.includes("."))return!1;const n=e.params||[];for(const e of n)if("Identifier"===e.type&&e.name===t)return!0;const r=e.body;if(r&&"BlockStatement"===r.type)for(const e of r.body)if("VariableDeclaration"===e.type)for(const n of e.declarations)if("Identifier"===n.id?.type&&n.id.name===t)return!0;return!1}findGuardInCondition(e,t){const n=this.extractTypeGuard(e,t);if(n)return n;if("BinaryExpression"===e.type){const n=e;if("&&"===n.operator){const e=this.findGuardInCondition(n.left,t);if(e)return e;const r=this.findGuardInCondition(n.right,t);if(r)return r}}return null}isNullGuardCondition(e,t){if("BinaryExpression"===e.type){const n=e;if(("!="===n.operator||"!=="===n.operator)&&"Identifier"===n.left.type&&n.left.name===t&&"Literal"===n.right.type&&null===n.right.value)return!0;if(("!="===n.operator||"!=="===n.operator)&&"Identifier"===n.right.type&&n.right.name===t&&"Literal"===n.left.type&&null===n.left.value)return!0}return"Identifier"===e.type&&e.name===t}isNullCheckCondition(e,t){if("BinaryExpression"===e.type){const n=e;if(("=="===n.operator||"==="===n.operator)&&"Identifier"===n.left.type&&n.left.name===t&&"Literal"===n.right.type&&null===n.right.value)return!0;if(("=="===n.operator||"==="===n.operator)&&"Identifier"===n.right.type&&n.right.name===t&&"Literal"===n.left.type&&null===n.left.value)return!0}return!1}countOrBranches(e){if("||"!==e.operator)return 1;let t=0;return"BinaryExpression"===e.left.type&&"||"===e.left.operator?t+=this.countOrBranches(e.left):t+=1,"BinaryExpression"===e.right.type&&"||"===e.right.operator?t+=this.countOrBranches(e.right):t+=1,t}getNullPropagatingArg(e){if("CallExpression"!==e.type)return null;const t=e;if("Identifier"!==t.callee.type)return null;const n=t.callee.name,r=qn[n];if(void 0===r)return null;const i=t.arguments[r];return i?{funcName:n,arg:i}:null}comparisonExcludesNull(e,t,n){if(n)switch(e){case">":return"number"==typeof t&&t>=0;case">=":return"number"==typeof t&&t>0;case"<":return"number"==typeof t&&t<=0;case"<=":return"number"==typeof t&&t<0;case"==":case"===":return null!==t;case"!=":case"!==":return null===t;default:return!1}else switch(e){case"<":return"number"==typeof t&&t>=0;case"<=":return"number"==typeof t&&t>0;case">":return"number"==typeof t&&t<=0;case">=":return"number"==typeof t&&t<0;case"==":case"===":return null!==t;case"!=":case"!==":return null===t;default:return!1}}getArgVariableName(e){return"Identifier"===e.type?e.name:null}extractVariableEqualityGuard(e,t,n){let r=null;if("Identifier"===e.left.type&&e.left.name===t&&"Identifier"===e.right.type?r=e.right.name:"Identifier"===e.right.type&&e.right.name===t&&"Identifier"===e.left.type&&(r=e.left.name),!r)return null;let i=this.symbolTable.lookup(r);if(!i){const t="Identifier"===e.left.type&&e.left.name===r?e.left:e.right;i=this.symbolTable.lookupAtPosition(r,t.start)}if(!i)return null;const o=i.dataType;return o===C.UNKNOWN?null:{variableName:t,narrowToType:null,isNegative:!n,equalityNarrowType:o,equalitySymbol:i}}extractTypeGuard(e,t){if("BinaryExpression"===e.type){const n=e;if("||"===n.operator){const r=this.countOrBranches(n),i=this.collectOrGuards(e,t);if(i.length<r)return null;if(i.length>=2){const e=this.symbolTable.lookup(t);if(!e)return null;const n=e.dataType;let r=I(n);if(n===C.UNKNOWN&&i.every(e=>!e.isNegative&&e.narrowToType)){const e=i.map(e=>e.narrowToType).filter(e=>null!==e);if(e.length>=2)return{variableName:t,narrowToType:O(e),isNegative:!1,isCombinedOr:!0}}const o=r.filter(e=>i.some(t=>!!t.narrowToType&&(t.isNegative?e!==t.narrowToType:e===t.narrowToType)));return i.some(e=>!!e.narrowToType&&!!e.isNegative&&!r.includes(e.narrowToType))&&o.length===r.length||(0===i.filter(e=>!!e.narrowToType&&r.includes(e.narrowToType)).length||0===o.length||o.length===r.length)?null:{variableName:t,narrowToType:O(o),isNegative:!1,isCombinedOr:!0}}}}const n=this.extractTypeCallGuard(e,t);if(n)return{variableName:t,narrowToType:n,isNegative:!1};const r=this.extractNegativeTypeCallGuard(e,t);if(r)return{variableName:t,narrowToType:r,isNegative:!0};if(this.isNullGuardCondition(e,t))return{variableName:t,narrowToType:C.NULL,isNegative:!0};if(this.isNullCheckCondition(e,t))return{variableName:t,narrowToType:C.NULL,isNegative:!1};if("BinaryExpression"===e.type){const n=e,r=this.getNullPropagatingArg(n.left);if(r&&"Literal"===n.right.type&&this.getArgVariableName(r.arg)===t){const e=n.right.value;if(this.comparisonExcludesNull(n.operator,e,!0))return{variableName:t,narrowToType:C.NULL,isNegative:!0,isNullPropagation:!0}}const i=this.getNullPropagatingArg(n.right);if(i&&"Literal"===n.left.type&&this.getArgVariableName(i.arg)===t){const e=n.left.value;if(this.comparisonExcludesNull(n.operator,e,!1))return{variableName:t,narrowToType:C.NULL,isNegative:!0,isNullPropagation:!0}}}if("BinaryExpression"===e.type){const n=e;if("=="===n.operator||"==="===n.operator||"!="===n.operator||"!=="===n.operator){const e="=="===n.operator||"==="===n.operator,r=this.extractVariableEqualityGuard(n,t,e);if(r)return r}}return null}collectOrGuards(e,t){const n=[];if("BinaryExpression"===e.type){const r=e;if("||"===r.operator)return n.push(...this.collectOrGuards(r.left,t)),n.push(...this.collectOrGuards(r.right,t)),n}const r=this.extractSingleTypeGuard(e,t);return r&&n.push(r),n}extractSingleTypeGuard(e,t){const n=this.extractTypeCallGuard(e,t);if(n)return{variableName:t,narrowToType:n,isNegative:!1};const r=this.extractNegativeTypeCallGuard(e,t);return r?{variableName:t,narrowToType:r,isNegative:!0}:this.isNullGuardCondition(e,t)?{variableName:t,narrowToType:C.NULL,isNegative:!0}:this.isNullCheckCondition(e,t)?{variableName:t,narrowToType:C.NULL,isNegative:!1}:null}getDottedPath(e){if("Identifier"===e.type)return e.name;if("MemberExpression"===e.type){const t=e;if(t.computed)return null;const n=this.getDottedPath(t.object);return n&&"Identifier"===t.property.type?`${n}.${t.property.name}`:null}return null}extractAndChainGuards(e,t){if("BinaryExpression"!==e.type){const n=this.extractTypeGuard(e,t);return n?[n]:[]}const n=e;if("&&"===n.operator)return[...this.extractAndChainGuards(n.left,t),...this.extractAndChainGuards(n.right,t)];const r=this.extractTypeGuard(e,t);return r?[r]:[]}extractOrChainGuards(e,t){if("BinaryExpression"!==e.type){const n=this.extractTypeGuard(e,t);return n?[n]:[]}const n=e;if("||"===n.operator)return[...this.extractOrChainGuards(n.left,t),...this.extractOrChainGuards(n.right,t)];const r=this.extractTypeGuard(e,t);return r?[r]:[]}extractTypeCallGuard(e,t){if("BinaryExpression"!==e.type)return null;const n=e;if("=="!==n.operator&&"==="!==n.operator)return null;let r=null,i=null;"CallExpression"===n.left.type&&"Literal"===n.right.type?(r=n.left,i=n.right):"CallExpression"===n.right.type&&"Literal"===n.left.type&&(r=n.right,i=n.left);let o=!1;if(!r||!i){const e=this.resolveIndirectTypeCall(n,t);e&&(r=e.typeCall,i=e.typeLiteral,o=!0)}if(!r||!i)return null;if("Identifier"!==r.callee.type||"type"!==r.callee.name)return null;if(!o){if(1!==r.arguments.length||!r.arguments[0])return null;if(this.getDottedPath(r.arguments[0])!==t)return null}switch(i.value){case"object":return C.OBJECT;case"array":return C.ARRAY;case"string":return C.STRING;case"int":return C.INTEGER;case"double":return C.DOUBLE;case"bool":return C.BOOLEAN;case"function":return C.FUNCTION;case"regex":case"regexp":return C.REGEX;default:return null}}extractNegativeTypeCallGuard(e,t){if("BinaryExpression"!==e.type)return null;const n=e;if("!="!==n.operator&&"!=="!==n.operator)return null;let r=null,i=null;"CallExpression"===n.left.type&&"Literal"===n.right.type?(r=n.left,i=n.right):"CallExpression"===n.right.type&&"Literal"===n.left.type&&(r=n.right,i=n.left);let o=!1;if(!r||!i){const e=this.resolveIndirectTypeCall(n,t);e&&(r=e.typeCall,i=e.typeLiteral,o=!0)}if(!r||!i)return null;if("Identifier"!==r.callee.type||"type"!==r.callee.name)return null;if(!o){if(1!==r.arguments.length||!r.arguments[0])return null;if(this.getDottedPath(r.arguments[0])!==t)return null}switch(i.value){case"object":return C.OBJECT;case"array":return C.ARRAY;case"string":return C.STRING;case"int":return C.INTEGER;case"double":return C.DOUBLE;case"bool":return C.BOOLEAN;case"function":return C.FUNCTION;case"regex":case"regexp":return C.REGEX;default:return null}}resolveIndirectTypeCall(e,t){let n=null,r=null;if("Identifier"===e.left.type&&"Literal"===e.right.type?(n=e.left,r=e.right):"Identifier"===e.right.type&&"Literal"===e.left.type&&(n=e.right,r=e.left),!n||!r||"string"!=typeof r.value)return null;const i=this.symbolTable.lookupAtPosition(n.name,n.start)||this.symbolTable.lookup(n.name);if(!i?.initNode||"CallExpression"!==i.initNode.type)return null;const o=i.initNode;if("Identifier"!==o.callee.type||"type"!==o.callee.name||1!==o.arguments.length||!o.arguments[0])return null;const s=this.getDottedPath(o.arguments[0]);return s&&(s===t||this.transitiveTypeAliases.includes(s))?{typeCall:o,typeLiteral:r}:null}getTypeCallVariable(e){if("CallExpression"===e.type){const t=e;if("Identifier"===t.callee.type&&"type"===t.callee.name&&1===t.arguments.length&&t.arguments[0])return this.getDottedPath(t.arguments[0])}else if("Identifier"===e.type){const t=e,n=this.symbolTable.lookupAtPosition(t.name,t.start)||this.symbolTable.lookup(t.name);if("CallExpression"===n?.initNode?.type){const e=n.initNode;if("Identifier"===e.callee.type&&"type"===e.callee.name&&1===e.arguments.length&&e.arguments[0])return this.getDottedPath(e.arguments[0])}}return null}detectTypeEqualityAlias(e){if("BinaryExpression"!==e.type)return null;const t=e;if("!="!==t.operator&&"!=="!==t.operator)return null;const n=this.getTypeCallVariable(t.left),r=this.getTypeCallVariable(t.right);return n&&r&&n!==r?{var1:n,var2:r}:null}getChildNodes(e){const t=[];switch(e.type){case"Program":case"BlockStatement":t.push(...e.body);break;case"ExpressionStatement":t.push(e.expression);break;case"VariableDeclaration":for(const n of e.declarations)t.push(n);break;case"VariableDeclarator":{const n=e;t.push(n.id),n.init&&t.push(n.init);break}case"IfStatement":{const n=e;t.push(n.test,n.consequent),n.alternate&&t.push(n.alternate);break}case"ForStatement":{const n=e;n.init&&t.push(n.init),n.test&&t.push(n.test),n.update&&t.push(n.update),t.push(n.body);break}case"ForInStatement":{const n=e;t.push(n.left,n.right,n.body);break}case"WhileStatement":{const n=e;t.push(n.test,n.body);break}case"DoWhileStatement":{const n=e;t.push(n.body,n.test);break}case"ReturnStatement":{const n=e;n.argument&&t.push(n.argument);break}case"ThrowStatement":{const n=e;n.argument&&t.push(n.argument);break}case"BreakStatement":case"ContinueStatement":case"EmptyStatement":case"SwitchCase":case"TemplateElement":case"Literal":case"Identifier":case"ThisExpression":case"JsDocComment":case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"ExportSpecifier":case"ExportAllDeclaration":break;case"LabeledStatement":{const n=e;t.push(n.body);break}case"SwitchStatement":{const n=e;if(t.push(n.discriminant),n.cases)for(const e of n.cases)e.test&&t.push(e.test),t.push(...e.consequent);break}case"TryStatement":{const n=e;t.push(n.block),n.handler&&t.push(n.handler);break}case"CatchClause":{const n=e;t.push(n.body);break}case"FunctionDeclaration":{const n=e;t.push(n.id,...n.params,n.body);break}case"FunctionExpression":{const n=e;n.id&&t.push(n.id),t.push(...n.params,n.body);break}case"ArrowFunctionExpression":{const n=e;t.push(...n.params),n.body&&"object"==typeof n.body&&t.push(n.body);break}case"BinaryExpression":{const n=e;t.push(n.left,n.right);break}case"LogicalExpression":{const n=e;t.push(n.left,n.right);break}case"UnaryExpression":{const n=e;t.push(n.argument);break}case"AssignmentExpression":{const n=e;t.push(n.left,n.right);break}case"ConditionalExpression":{const n=e;t.push(n.test,n.consequent,n.alternate);break}case"CallExpression":{const n=e;t.push(n.callee),t.push(...n.arguments.filter(e=>null!=e));break}case"MemberExpression":{const n=e;t.push(n.object,n.property);break}case"DeleteExpression":{const n=e;t.push(n.argument);break}case"SpreadElement":{const n=e;t.push(n.argument);break}case"ObjectExpression":for(const n of e.properties)t.push(n);break;case"Property":{const n=e;n.key&&t.push(n.key),n.value&&t.push(n.value);break}case"ArrayExpression":t.push(...e.elements.filter(e=>null!=e));break;case"TemplateLiteral":{const n=e;for(const e of n.expressions)t.push(e);break}case"ImportDeclaration":{const n=e;t.push(...n.specifiers);break}case"ExportDefaultDeclaration":{const n=e;n.declaration&&t.push(n.declaration);break}case"ExportNamedDeclaration":{const n=e;n.declaration&&t.push(n.declaration);break}default:e.type}return t.filter(e=>null!=e)}pushGuardContext(e,t,n,r){this.guardContextStack.push({variableName:e,narrowedType:t,startPos:n,endPos:r})}popGuardContext(){this.guardContextStack.pop()}getActiveGuardType(e,t){for(let n=this.guardContextStack.length-1;n>=0;n--){const r=this.guardContextStack[n];if(r&&r.variableName===e&&t>=r.startPos&&t<=r.endPos)return r.narrowedType}return null}analyzeIfGuards(e){return this.flowSensitiveTracker.analyzeIfStatement(e)}pushGuardContextPublic(e,t,n,r){this.pushGuardContext(e,t,n,r)}popGuardContextPublic(){this.popGuardContext()}}class Hn{visit(e){switch(e.type){case"Program":this.visitProgram(e);break;case"Literal":this.visitLiteral(e);break;case"Identifier":this.visitIdentifier(e);break;case"BinaryExpression":this.visitBinaryExpression(e);break;case"UnaryExpression":this.visitUnaryExpression(e);break;case"CallExpression":this.visitCallExpression(e);break;case"MemberExpression":this.visitMemberExpression(e);break;case"AssignmentExpression":this.visitAssignmentExpression(e);break;case"ArrayExpression":this.visitArrayExpression(e);break;case"ObjectExpression":this.visitObjectExpression(e);break;case"Property":this.visitProperty(e);break;case"BlockStatement":this.visitBlockStatement(e);break;case"ExpressionStatement":this.visitExpressionStatement(e);break;case"VariableDeclaration":this.visitVariableDeclaration(e);break;case"VariableDeclarator":this.visitVariableDeclarator(e);break;case"IfStatement":this.visitIfStatement(e);break;case"ForStatement":this.visitForStatement(e);break;case"ForInStatement":this.visitForInStatement(e);break;case"WhileStatement":this.visitWhileStatement(e);break;case"FunctionDeclaration":this.visitFunctionDeclaration(e);break;case"FunctionExpression":this.visitFunctionExpression(e);break;case"ReturnStatement":this.visitReturnStatement(e);break;case"BreakStatement":this.visitBreakStatement(e);break;case"ContinueStatement":this.visitContinueStatement(e);break;case"TryStatement":this.visitTryStatement(e);break;case"CatchClause":this.visitCatchClause(e);break;case"SwitchStatement":this.visitSwitchStatement(e);break;case"SwitchCase":this.visitSwitchCase(e);break;case"ConditionalExpression":this.visitConditionalExpression(e);break;case"EmptyStatement":this.visitEmptyStatement(e);break;case"ThisExpression":this.visitThisExpression(e);break;case"DeleteExpression":this.visitDeleteExpression(e);break;case"ImportDeclaration":this.visitImportDeclaration(e);break;case"ImportSpecifier":this.visitImportSpecifier(e);break;case"ImportDefaultSpecifier":this.visitImportDefaultSpecifier(e);break;case"ImportNamespaceSpecifier":this.visitImportNamespaceSpecifier(e);break;case"ArrowFunctionExpression":this.visitArrowFunctionExpression(e);break;case"ExportNamedDeclaration":this.visitExportNamedDeclaration(e);break;case"ExportDefaultDeclaration":this.visitExportDefaultDeclaration(e);break;case"TemplateLiteral":this.visitTemplateLiteral(e)}}visitProgram(e){for(const t of e.body)this.visit(t)}visitLiteral(e){}visitIdentifier(e){}visitBinaryExpression(e){this.visit(e.left),this.visit(e.right)}visitUnaryExpression(e){this.visit(e.argument)}visitCallExpression(e){this.visit(e.callee);for(const t of e.arguments)this.visit(t)}visitMemberExpression(e){this.visit(e.object),this.visit(e.property)}visitAssignmentExpression(e){this.visit(e.left),this.visit(e.right)}visitArrayExpression(e){for(const t of e.elements)t&&this.visit(t)}visitObjectExpression(e){for(const t of e.properties)this.visit(t)}visitProperty(e){this.visit(e.key),this.visit(e.value)}visitBlockStatement(e){for(const t of e.body)this.visit(t)}visitExpressionStatement(e){this.visit(e.expression)}visitVariableDeclaration(e){for(const t of e.declarations)this.visit(t)}visitVariableDeclarator(e){this.visit(e.id),e.init&&this.visit(e.init)}visitIfStatement(e){this.visit(e.test),this.visit(e.consequent),e.alternate&&this.visit(e.alternate)}visitForStatement(e){e.init&&this.visit(e.init),e.test&&this.visit(e.test),e.update&&this.visit(e.update),this.visit(e.body)}visitForInStatement(e){this.visit(e.left),this.visit(e.right),this.visit(e.body)}visitWhileStatement(e){this.visit(e.test),this.visit(e.body)}visitFunctionDeclaration(e){this.visit(e.id);for(const t of e.params)this.visit(t);this.visit(e.body)}visitFunctionExpression(e){e.id&&this.visit(e.id);for(const t of e.params)this.visit(t);this.visit(e.body)}visitReturnStatement(e){e.argument&&this.visit(e.argument)}visitBreakStatement(e){}visitContinueStatement(e){}visitTryStatement(e){this.visit(e.block),e.handler&&this.visit(e.handler)}visitCatchClause(e){e.param&&this.visit(e.param),this.visit(e.body)}visitSwitchStatement(e){this.visit(e.discriminant);for(const t of e.cases)this.visit(t)}visitSwitchCase(e){e.test&&this.visit(e.test);for(const t of e.consequent)this.visit(t)}visitConditionalExpression(e){this.visit(e.test),this.visit(e.consequent),this.visit(e.alternate)}visitEmptyStatement(e){}visitThisExpression(e){}visitDeleteExpression(e){this.visit(e.argument)}visitImportDeclaration(e){for(const t of e.specifiers)this.visit(t);this.visit(e.source)}visitImportSpecifier(e){this.visit(e.imported),this.visit(e.local)}visitImportDefaultSpecifier(e){this.visit(e.local)}visitImportNamespaceSpecifier(e){this.visit(e.local)}visitArrowFunctionExpression(e){for(const t of e.params)this.visit(t);this.visit(e.body)}visitExportNamedDeclaration(e){e.declaration&&this.visit(e.declaration);for(const t of e.specifiers)this.visit(t.local),this.visit(t.exported)}visitExportDefaultDeclaration(e){e.declaration&&this.visit(e.declaration)}visitTemplateLiteral(e){for(const t of e.expressions)this.visit(t)}}var Yn,Xn;!function(e){e[e.NONE=0]="NONE",e[e.COMMA=1]="COMMA",e[e.ASSIGNMENT=2]="ASSIGNMENT",e[e.CONDITIONAL=3]="CONDITIONAL",e[e.NULLISH=4]="NULLISH",e[e.LOGICAL_OR=5]="LOGICAL_OR",e[e.LOGICAL_AND=6]="LOGICAL_AND",e[e.BITWISE_OR=7]="BITWISE_OR",e[e.BITWISE_XOR=8]="BITWISE_XOR",e[e.BITWISE_AND=9]="BITWISE_AND",e[e.EQUALITY=10]="EQUALITY",e[e.RELATIONAL=11]="RELATIONAL",e[e.SHIFT=12]="SHIFT",e[e.ADDITIVE=13]="ADDITIVE",e[e.MULTIPLICATIVE=14]="MULTIPLICATIVE",e[e.EXPONENTIAL=15]="EXPONENTIAL",e[e.UNARY=16]="UNARY",e[e.POSTFIX=17]="POSTFIX",e[e.CALL=18]="CALL",e[e.PRIMARY=19]="PRIMARY"}(Yn||(Yn={})),function(e){e[e.NONE=0]="NONE",e[e.STATEMENT=1]="STATEMENT",e[e.EXPRESSION=2]="EXPRESSION",e[e.BLOCK=3]="BLOCK"}(Xn||(Xn={}));const zn=[l.TK_SCOL,l.TK_RBRACE,l.TK_IF,l.TK_WHILE,l.TK_FOR,l.TK_FUNC,l.TK_RETURN,l.TK_BREAK,l.TK_CONTINUE,l.TK_TRY,l.TK_SWITCH,l.TK_LOCAL,l.TK_CONST,l.TK_EOF],Jn=[l.TK_SCOL,l.TK_RPAREN,l.TK_RBRACK,l.TK_RBRACE,l.TK_COMMA,l.TK_EOF];class Qn{tokens;current=0;errors=[];warnings=[];panicMode=!1;comments=[];sourceText="";constructor(e){this.tokens=e}setComments(e){this.comments=e}setSourceText(e){this.sourceText=e}findLeadingJsDoc(e){for(let t=this.comments.length-1;t>=0;t--){const n=this.comments[t];if(n.end>e)continue;if(n.end<e-500)break;const r=String(n.value);if(!r.startsWith("*"))break;if(this.sourceText&&this.sourceText.substring(n.end,e).trim().length>0)break;return{type:"JsDocComment",value:r,start:n.pos,end:n.end}}}tokenToOperator(e){return{[l.TK_ADD]:"+",[l.TK_SUB]:"-",[l.TK_MUL]:"*",[l.TK_DIV]:"/",[l.TK_MOD]:"%",[l.TK_EXP]:"**",[l.TK_EQ]:"==",[l.TK_NE]:"!=",[l.TK_EQS]:"===",[l.TK_NES]:"!==",[l.TK_LT]:"<",[l.TK_LE]:"<=",[l.TK_GT]:">",[l.TK_GE]:">=",[l.TK_AND]:"&&",[l.TK_OR]:"||",[l.TK_BAND]:"&",[l.TK_BOR]:"|",[l.TK_BXOR]:"^",[l.TK_LSHIFT]:"<<",[l.TK_RSHIFT]:">>",[l.TK_IN]:"in",[l.TK_COMMA]:",",[l.TK_NULLISH]:"??",[l.TK_NOT]:"!",[l.TK_COMPL]:"~",[l.TK_INC]:"++",[l.TK_DEC]:"--",[l.TK_ASSIGN]:"=",[l.TK_ASADD]:"+=",[l.TK_ASSUB]:"-=",[l.TK_ASMUL]:"*=",[l.TK_ASDIV]:"/=",[l.TK_ASMOD]:"%=",[l.TK_ASEXP]:"**=",[l.TK_ASLEFT]:"<<=",[l.TK_ASRIGHT]:">>=",[l.TK_ASBAND]:"&=",[l.TK_ASBXOR]:"^=",[l.TK_ASBOR]:"|=",[l.TK_ASAND]:"&&=",[l.TK_ASOR]:"||=",[l.TK_ASNULLISH]:"??="}[e]||"unknown"}isAtEnd(){return this.current>=this.tokens.length||this.peek()?.type===l.TK_EOF}peek(){return this.current>=this.tokens.length?null:this.tokens[this.current]||null}previous(){return this.current<=0?null:this.tokens[this.current-1]||null}advance(){return this.isAtEnd()||this.current++,this.previous()}check(e){return!this.isAtEnd()&&this.peek()?.type===e}match(...e){for(const t of e)if(this.check(t))return this.advance(),!0;return!1}consume(e,t){return this.check(e)?this.advance():(this.error(t),null)}error(e){const t=this.peek();t?this.errorAt(e,t.pos,t.end):this.errors.push({message:e,start:this.tokens[this.tokens.length-1]?.end||0,end:this.tokens[this.tokens.length-1]?.end||0,severity:"error"})}errorAt(e,t,n){this.panicMode||(this.panicMode=!0,this.errors.push({message:e,start:t,end:n,severity:"error"}))}warningAt(e,t,n){this.warnings.push({message:e,start:t,end:n,severity:"warning"})}synchronize(e){if(this.panicMode=!1,e===Xn.STATEMENT)for(;!this.isAtEnd();){if(this.previous()?.type===l.TK_SCOL)return;const e=this.peek()?.type;if(e&&zn.includes(e))return;this.advance()}else if(e===Xn.EXPRESSION)for(;!this.isAtEnd();){const e=this.peek()?.type;if(e&&Jn.includes(e))return;this.advance()}}}class Zn extends Qn{rules=new Map;initializeParseRules(){this.rules.set(l.TK_NUMBER,{prefix:()=>this.parseLiteral("number"),precedence:Yn.NONE}),this.rules.set(l.TK_DOUBLE,{prefix:()=>this.parseLiteral("double"),precedence:Yn.NONE}),this.rules.set(l.TK_STRING,{prefix:()=>this.parseLiteral("string"),precedence:Yn.NONE}),this.rules.set(l.TK_TRUE,{prefix:()=>this.parseLiteral("boolean"),precedence:Yn.NONE}),this.rules.set(l.TK_FALSE,{prefix:()=>this.parseLiteral("boolean"),precedence:Yn.NONE}),this.rules.set(l.TK_NULL,{prefix:()=>this.parseLiteral("null"),precedence:Yn.NONE}),this.rules.set(l.TK_TEMPLATE,{prefix:()=>this.parseTemplateLiteral(),precedence:Yn.NONE}),this.rules.set(l.TK_LABEL,{prefix:()=>this.parseIdentifier(),precedence:Yn.NONE}),this.rules.set(l.TK_THIS,{prefix:()=>this.parseThis(),precedence:Yn.NONE}),this.rules.set(l.TK_REGEXP,{prefix:()=>this.parseRegex(),precedence:Yn.NONE}),this.rules.set(l.TK_FROM,{prefix:()=>this.parseIdentifier(),precedence:Yn.NONE}),this.rules.set(l.TK_LPAREN,{prefix:()=>this.parseGrouping(),infix:e=>this.parseCall(e),precedence:Yn.CALL}),this.rules.set(l.TK_LBRACK,{prefix:()=>this.parseArray(),infix:e=>this.parseMemberAccess(e),precedence:Yn.CALL}),this.rules.set(l.TK_LBRACE,{prefix:()=>this.parseObject(),precedence:Yn.NONE}),this.rules.set(l.TK_NOT,{prefix:()=>this.parseUnary(),precedence:Yn.NONE}),this.rules.set(l.TK_SUB,{prefix:()=>this.parseUnary(),infix:e=>this.parseBinary(e),precedence:Yn.ADDITIVE}),this.rules.set(l.TK_ADD,{prefix:()=>this.parseUnary(),infix:e=>this.parseBinary(e),precedence:Yn.ADDITIVE}),this.rules.set(l.TK_COMPL,{prefix:()=>this.parseUnary(),precedence:Yn.NONE}),this.rules.set(l.TK_INC,{prefix:()=>this.parseUnary(),infix:e=>this.parsePostfix(e),precedence:Yn.POSTFIX}),this.rules.set(l.TK_DEC,{prefix:()=>this.parseUnary(),infix:e=>this.parsePostfix(e),precedence:Yn.POSTFIX}),this.addBinaryRule(l.TK_MUL,Yn.MULTIPLICATIVE),this.addBinaryRule(l.TK_DIV,Yn.MULTIPLICATIVE),this.addBinaryRule(l.TK_MOD,Yn.MULTIPLICATIVE),this.addBinaryRule(l.TK_EXP,Yn.EXPONENTIAL),this.addBinaryRule(l.TK_LT,Yn.RELATIONAL),this.addBinaryRule(l.TK_LE,Yn.RELATIONAL),this.addBinaryRule(l.TK_GT,Yn.RELATIONAL),this.addBinaryRule(l.TK_GE,Yn.RELATIONAL),this.addBinaryRule(l.TK_IN,Yn.RELATIONAL),this.addBinaryRule(l.TK_EQ,Yn.EQUALITY),this.addBinaryRule(l.TK_NE,Yn.EQUALITY),this.addBinaryRule(l.TK_EQS,Yn.EQUALITY),this.addBinaryRule(l.TK_NES,Yn.EQUALITY),this.addBinaryRule(l.TK_BAND,Yn.BITWISE_AND),this.addBinaryRule(l.TK_BXOR,Yn.BITWISE_XOR),this.addBinaryRule(l.TK_BOR,Yn.BITWISE_OR),this.addBinaryRule(l.TK_LSHIFT,Yn.SHIFT),this.addBinaryRule(l.TK_RSHIFT,Yn.SHIFT),this.addBinaryRule(l.TK_AND,Yn.LOGICAL_AND),this.addBinaryRule(l.TK_OR,Yn.LOGICAL_OR),this.addBinaryRule(l.TK_NULLISH,Yn.NULLISH),this.addBinaryRule(l.TK_COMMA,Yn.COMMA),this.addAssignmentRule(l.TK_ASSIGN),this.addAssignmentRule(l.TK_ASADD),this.addAssignmentRule(l.TK_ASSUB),this.addAssignmentRule(l.TK_ASMUL),this.addAssignmentRule(l.TK_ASDIV),this.addAssignmentRule(l.TK_ASMOD),this.addAssignmentRule(l.TK_ASEXP),this.addAssignmentRule(l.TK_ASLEFT),this.addAssignmentRule(l.TK_ASRIGHT),this.addAssignmentRule(l.TK_ASBAND),this.addAssignmentRule(l.TK_ASBXOR),this.addAssignmentRule(l.TK_ASBOR),this.addAssignmentRule(l.TK_ASAND),this.addAssignmentRule(l.TK_ASOR),this.addAssignmentRule(l.TK_ASNULLISH),this.rules.set(l.TK_DOT,{infix:e=>this.parseMemberAccess(e),precedence:Yn.CALL}),this.rules.set(l.TK_QDOT,{infix:e=>this.parseMemberAccess(e),precedence:Yn.CALL}),this.rules.set(l.TK_QLBRACK,{infix:e=>this.parseMemberAccess(e),precedence:Yn.CALL}),this.rules.set(l.TK_QLPAREN,{infix:e=>this.parseCall(e),precedence:Yn.CALL}),this.rules.set(l.TK_QMARK,{infix:e=>this.parseConditional(e),precedence:Yn.CONDITIONAL}),this.rules.set(l.TK_DELETE,{prefix:()=>this.parseDelete(),precedence:Yn.NONE}),this.rules.set(l.TK_FUNC,{prefix:()=>this.parseFunctionExpression(),precedence:Yn.NONE}),this.rules.set(l.TK_ARROW,{infix:e=>this.parseArrowFunction(e),precedence:Yn.ASSIGNMENT})}addBinaryRule(e,t){this.rules.set(e,{infix:e=>this.parseBinary(e),precedence:t})}addAssignmentRule(e){this.rules.set(e,{infix:e=>this.parseAssignment(e),precedence:Yn.ASSIGNMENT})}getRule(e){return e&&this.rules.get(e)||{precedence:Yn.NONE}}}class er extends Zn{parseIdentifier(){const e=this.previous();return e.type===l.TK_FROM?{type:"Identifier",start:e.pos,end:e.end,name:"from"}:e.type!==l.TK_LABEL?(this.error("Expected identifier"),null):{type:"Identifier",start:e.pos,end:e.end,name:e.value}}parseIdentifierName(){if(!this.check(l.TK_LABEL))return this.error("Expected identifier"),null;const e=this.advance();return{type:"Identifier",start:e.pos,end:e.end,name:e.value}}parseImportSpecifierName(){if(this.check(l.TK_LABEL))return this.parseIdentifierName();if(this.check(l.TK_FROM)){const e=this.advance();return{type:"Identifier",start:e.pos,end:e.end,name:"from"}}if(this.check(l.TK_STRING)){const e=this.advance();return{type:"Identifier",start:e.pos,end:e.end,name:e.value}}return this.error("Expected identifier or string literal in import specifier"),null}parseLiteral(e){const t=this.previous();let n;switch(e){case"number":case"double":n=Number(t.value);break;case"string":case"regexp":n=String(t.value);break;case"boolean":n=t.type===l.TK_TRUE;break;case"null":n=null;break;default:n=t.value}return{type:"Literal",start:t.pos,end:t.end,value:n,raw:String(t.value),literalType:e}}parseThis(){const e=this.previous();return{type:"ThisExpression",start:e.pos,end:e.end}}parseRegex(){const e=this.previous();return{type:"Literal",start:e.pos,end:e.end,value:String(e.value),raw:String(e.value),literalType:"regexp"}}parseGrouping(){const e=this.current;let t=!1;if(this.check(l.TK_RPAREN))this.advance(),this.check(l.TK_ARROW)&&(t=!0);else if(this.check(l.TK_LABEL)||this.check(l.TK_ELLIP)){if(this.check(l.TK_ELLIP)){if(this.advance(),!this.check(l.TK_LABEL))return this.current=e,this.parseExpression();this.advance()}else this.advance();if(this.check(l.TK_COMMA)){for(;this.check(l.TK_COMMA);){if(this.advance(),this.check(l.TK_ELLIP)){if(this.advance(),this.check(l.TK_LABEL)){this.advance();break}break}if(!this.check(l.TK_LABEL))break;this.advance()}this.check(l.TK_RPAREN)&&(this.advance(),this.check(l.TK_ARROW)&&(t=!0))}else this.check(l.TK_RPAREN)&&(this.advance(),this.check(l.TK_ARROW)&&(t=!0))}if(this.current=e,t){const e=[];if(!this.check(l.TK_RPAREN))do{if(this.match(l.TK_ELLIP)){const t=this.previous().pos;if(this.check(l.TK_LABEL)){const n=this.advance(),r={type:"Identifier",start:n.pos,end:n.end,name:n.value},i={type:"SpreadElement",start:t,end:n.end,argument:r};e.push(i);break}this.error("Expected parameter name after '...'")}else if(this.check(l.TK_LABEL)){const t=this.advance(),n={type:"Identifier",start:t.pos,end:t.end,name:t.value};e.push(n)}}while(this.match(l.TK_COMMA));this.consume(l.TK_RPAREN,"Expected ')' after arrow function parameters");const t=this.previous();return{type:"CallExpression",start:e.length>0?e[0].start:t?.pos||0,end:t?.end||0,callee:{type:"Identifier",start:0,end:0,name:"__arrow_params__"},arguments:e}}{const e=this.parseExpression(Yn.COMMA);return this.consume(l.TK_RPAREN,"Expected ')' after expression"),e}}parseFunctionExpression(){const e=this.previous().pos,t=this.findLeadingJsDoc(e);let n=null;this.check(l.TK_LABEL)&&(n=this.parseIdentifierName()),this.consume(l.TK_LPAREN,"Expected '(' after 'function'");const r=[];let i;if(!this.check(l.TK_RPAREN))do{if(this.match(l.TK_ELLIP)){const e=this.parseIdentifierName();if(e){i=e;break}}else{const e=this.parseIdentifierName();e&&r.push(e)}}while(this.match(l.TK_COMMA));this.consume(l.TK_RPAREN,"Expected ')' after parameters");const o=this.consume(l.TK_LBRACE,"Expected '{' to start function body"),s=this.parseBlockStatement(o,"function expression body"),a={type:"FunctionExpression",start:e,end:s.end,id:n,params:r,body:s};return i&&(a.restParam=i),t&&(a.leadingJsDoc=t),a}parseTemplateLiteral(){const e=this.previous(),t=e.pos,n=[],r=[];for(n.push({type:"TemplateElement",start:e.pos,end:e.end,value:{raw:String(e.value),cooked:String(e.value)},tail:!1});this.match(l.TK_PLACEH);){const e=this.parseExpression();if(!e)break;if(r.push(e),!this.match(l.TK_RBRACE))break;if(!this.match(l.TK_TEMPLATE))break;{const e=this.previous();n.push({type:"TemplateElement",start:e.pos,end:e.end,value:{raw:String(e.value),cooked:String(e.value)},tail:!1})}}if(n.length>0){const e=n[n.length-1];e&&(e.tail=!0)}const i=n.length>0?n[n.length-1]:null;return{type:"TemplateLiteral",start:t,end:i?i.end:e.end,expressions:r,quasis:n}}}class tr extends er{parseArray(){const e=this.previous().pos,t=[];if(!this.check(l.TK_RBRACK))do{if(this.check(l.TK_COMMA))t.push(null);else if(this.match(l.TK_ELLIP)){const e=this.previous().pos,n=this.parseExpression();if(n){const r={type:"SpreadElement",start:e,end:n.end,argument:n};t.push(r)}}else{const e=this.parseExpression();t.push(e)}}while(this.match(l.TK_COMMA)&&!this.check(l.TK_RBRACK));return this.consume(l.TK_RBRACK,"Expected ']' after array elements"),{type:"ArrayExpression",start:e,end:this.previous().end,elements:t}}parseObject(){const e=this.previous().pos,t=[];if(!this.check(l.TK_RBRACE))do{if(this.match(l.TK_ELLIP)){const e=this.previous().pos,n=this.parseExpression();if(n){const r={type:"SpreadElement",start:e,end:n.end,argument:n};t.push(r)}continue}let e,n=!1;if(this.match(l.TK_LBRACK))n=!0,e=this.parseExpression()||{type:"Identifier",start:0,end:0,name:""},this.consume(l.TK_RBRACK,"Expected ']' after computed property key");else if(this.check(l.TK_LABEL)||this.canUseAsIdentifier()){const n=this.advance(),r=this.getTokenAsIdentifierName(n);if(!this.check(l.TK_COLON)){e={type:"Literal",start:n.pos,end:n.end,value:r,raw:r,literalType:"string"};const i={type:"Identifier",start:n.pos,end:n.end,name:r};t.push({type:"Property",start:e.start,end:i.end,key:e,value:i,computed:!1});continue}e={type:"Literal",start:n.pos,end:n.end,value:r,raw:r,literalType:"string"}}else if(this.check(l.TK_NUMBER)||this.check(l.TK_DOUBLE)){const t=this.advance();e={type:"Literal",start:t.pos,end:t.end,value:t.value,raw:t.value,literalType:"string"}}else{if(!this.check(l.TK_STRING)){if(this.check(l.TK_RBRACE))break;this.error("Expected property name");break}this.advance(),e=this.parseLiteral("string")}this.consume(l.TK_COLON,"Expected ':' after property key");const r=this.parseExpression();r&&t.push({type:"Property",start:e.start,end:r.end,key:e,value:r,computed:n})}while(this.match(l.TK_COMMA));return this.consume(l.TK_RBRACE,"Expected '}' after object properties"),{type:"ObjectExpression",start:e,end:this.previous().end,properties:t}}parseMemberAccess(e){const t=this.previous(),n=t.type===l.TK_LBRACK||t.type===l.TK_QLBRACK,r=t.type===l.TK_QDOT||t.type===l.TK_QLBRACK;let i,o;if(n)i=this.parseExpression()||{type:"Identifier",start:0,end:0,name:""},this.consume(l.TK_RBRACK,"Expected ']' after computed property"),o=this.previous().end;else{if(!this.check(l.TK_LABEL))return this.error("Expected property name after '.' or '?.'"),null;i=this.parseIdentifierName()||{type:"Identifier",start:0,end:0,name:""},o=i.end}return{type:"MemberExpression",start:e.start,end:o,object:e,property:i,computed:n,optional:r}}canUseAsIdentifier(){const e=this.peek();return!!e&&[l.TK_TRY,l.TK_CATCH,l.TK_IF,l.TK_ELSE,l.TK_WHILE,l.TK_FOR,l.TK_RETURN,l.TK_BREAK,l.TK_CONTINUE,l.TK_FUNC,l.TK_LOCAL,l.TK_CONST,l.TK_TRUE,l.TK_FALSE,l.TK_NULL,l.TK_THIS,l.TK_SWITCH,l.TK_CASE,l.TK_DEFAULT,l.TK_IMPORT,l.TK_EXPORT,l.TK_IN,l.TK_DELETE,l.TK_FROM].includes(e.type)}getTokenAsIdentifierName(e){return e.type===l.TK_LABEL?e.value:{[l.TK_TRY]:"try",[l.TK_CATCH]:"catch",[l.TK_IF]:"if",[l.TK_ELSE]:"else",[l.TK_WHILE]:"while",[l.TK_FOR]:"for",[l.TK_RETURN]:"return",[l.TK_BREAK]:"break",[l.TK_CONTINUE]:"continue",[l.TK_FUNC]:"function",[l.TK_LOCAL]:"let",[l.TK_CONST]:"const",[l.TK_TRUE]:"true",[l.TK_FALSE]:"false",[l.TK_NULL]:"null",[l.TK_THIS]:"this",[l.TK_SWITCH]:"switch",[l.TK_CASE]:"case",[l.TK_DEFAULT]:"default",[l.TK_IMPORT]:"import",[l.TK_EXPORT]:"export",[l.TK_IN]:"in",[l.TK_DELETE]:"delete",[l.TK_FROM]:"from"}[e.type]||e.value||""}}class nr extends tr{parseUnary(){const e=this.previous(),t=this.tokenToOperator(e.type),n=this.parseExpression(Yn.UNARY);return n?{type:"UnaryExpression",start:e.pos,end:n.end,operator:t,argument:n,prefix:!0}:null}parseBinary(e){const t=this.previous(),n=this.tokenToOperator(t.type),r=this.getRule(t.type),i=this.parseExpression(r.precedence+1);return i?{type:"BinaryExpression",start:e.start,end:i.end,operator:n,left:e,right:i}:null}parseAssignment(e){const t=this.previous(),n=this.tokenToOperator(t.type);if("Identifier"!==e.type&&"MemberExpression"!==e.type)return this.error("Invalid assignment target"),null;const r=this.parseExpression(Yn.ASSIGNMENT);return r?{type:"AssignmentExpression",start:e.start,end:r.end,operator:n,left:e,right:r}:null}parsePostfix(e){const t=this.previous(),n=this.tokenToOperator(t.type);return{type:"UnaryExpression",start:e.start,end:t.end,operator:n,argument:e,prefix:!1}}parseArrowFunction(e){const t=this.findLeadingJsDoc(e.start),n=[];let r,i,o;if("Identifier"===e.type)n.push(e);else{if("CallExpression"!==e.type)return this.error("Invalid parameters for arrow function"),null;{const t=e;for(const e of t.arguments){if("Identifier"!==e.type){if("SpreadElement"===e.type){if(e.argument&&"Identifier"===e.argument.type){r=e.argument;break}return this.error("Invalid rest parameter in arrow function"),null}return this.error("Invalid parameter in arrow function"),null}n.push(e)}}}if(this.check(l.TK_LBRACE)){const e=this.consume(l.TK_LBRACE,"Expected '{' for arrow function body");i=this.parseBlockStatement(e,"arrow function body"),o=!1}else i=this.parseExpression(Yn.ASSIGNMENT),o=!0;if(!i)return null;const s={type:"ArrowFunctionExpression",start:e.start,end:i.end,params:n,body:i,expression:o};return r&&(s.restParam=r),t&&(s.leadingJsDoc=t),s}}class rr extends nr{parseCall(e){const t=e.start,n=[],r=this.previous(),i=r?.type===l.TK_QLPAREN;if(!this.check(l.TK_RPAREN))do{if(this.match(l.TK_ELLIP)){const e=this.parseExpression();if(e){const t={type:"SpreadElement",start:this.previous().pos,end:e.end,argument:e};n.push(t)}}else{const e=this.parseExpression();e&&n.push(e)}}while(this.match(l.TK_COMMA));return this.consume(l.TK_RPAREN,"Expected ')' after arguments"),{type:"CallExpression",start:t,end:this.previous().end,callee:e,arguments:n,optional:i}}parseConditional(e){const t=this.parseExpression();if(!t)return null;this.consume(l.TK_COLON,"Expected ':' after '?' in conditional expression");const n=this.parseExpression(Yn.CONDITIONAL);return n?{type:"ConditionalExpression",start:e.start,end:n.end,test:e,consequent:t,alternate:n}:null}parseDelete(){const e=this.previous().pos,t=this.parseExpression(Yn.UNARY);return t?{type:"DeleteExpression",start:e,end:t.end,argument:t}:null}}class ir extends rr{parseExpression(e=Yn.ASSIGNMENT){try{if(this.check(l.TK_ERROR)){const e=this.advance(),t=e.value?String(e.value):"Unexpected token";return this.errorAt(t,e.pos,e.end),null}const t=this.getRule(this.peek()?.type).prefix;if(!t)return this.error("Unexpected token in expression"),this.advance(),null;this.advance();let n=t();if(!n)return null;for(;e<=this.getRule(this.peek()?.type).precedence;){const e=this.getRule(this.peek()?.type).infix;if(!e)break;if(this.advance(),n=e(n),!n)break}return n}catch(e){return this.synchronize(Xn.EXPRESSION),null}}}class or extends ir{parseVariableDeclaration(){const e=this.previous().pos,t=this.findLeadingJsDoc(e),n=this.previous().type===l.TK_CONST?"const":"let",r=[];do{const e=this.parseVariableDeclarator();e&&r.push(e)}while(this.match(l.TK_COMMA));this.check(l.TK_SCOL)?this.advance():(this.errorAt("Expected ';' after variable declaration",this.previous()?.end||e,this.previous()?.end||e),this.panicMode=!1);const i={type:"VariableDeclaration",start:e,end:this.previous().end,kind:n,declarations:r};return t&&(i.leadingJsDoc=t),i}parseVariableDeclarator(){const e=this.peek()?.pos||0;if(!this.check(l.TK_LABEL))return this.error("Expected variable name"),null;const t=this.parseIdentifierName();if(!t)return null;let n=null;return this.match(l.TK_ASSIGN)&&(n=this.parseExpression()),{type:"VariableDeclarator",start:e,end:this.previous().end,id:t,init:n}}parseFunctionDeclaration(e=!1){const t=this.previous().pos,n=this.findLeadingJsDoc(t);let r=null;if(this.check(l.TK_LABEL)){if(r=this.parseIdentifierName(),!r)return null}else if(!e)return this.error("Expected function name"),null;this.consume(l.TK_LPAREN,r?"Expected '(' after function name":"Expected '(' after 'function'");const i=[];let o;if(!this.check(l.TK_RPAREN))do{if(this.match(l.TK_ELLIP)){const e=this.parseIdentifierName();if(e){o=e;break}}else{const e=this.parseIdentifierName();e&&i.push(e)}}while(this.match(l.TK_COMMA));this.consume(l.TK_RPAREN,"Expected ')' after parameters");const s=this.consume(l.TK_LBRACE,"Expected '{' to start function body"),a=this.parseBlockStatement(s,"function body"),c=this.check(l.TK_SCOL);if(c?this.advance():e&&(this.errorAt("Exported functions must end with a semicolon ';'",a.end,a.end),this.panicMode=!1),r){const e={type:"FunctionDeclaration",start:t,end:c?this.previous().end:a.end,id:r,params:i,body:a};return o&&(e.restParam=o),n&&(e.leadingJsDoc=n),e}{const e={type:"FunctionExpression",start:t,end:c?this.previous().end:a.end,id:null,params:i,body:a};return o&&(e.restParam=o),n&&(e.leadingJsDoc=n),e}}parseImportDeclaration(){const e=this.previous().pos,t=[];if(this.match(l.TK_LBRACE)){if(!this.check(l.TK_RBRACE))do{const e=this.parseImportSpecifierName();if(!e)continue;let n=e;if(this.match(l.TK_LABEL)&&"as"===this.previous().value){const e=this.parseIdentifierName();if(!e)continue;n=e}t.push({type:"ImportSpecifier",start:e.start,end:n.end,imported:e,local:n})}while(this.match(l.TK_COMMA));this.consume(l.TK_RBRACE,"Expected '}' after import specifiers")}else if(this.match(l.TK_MUL)){if(this.consume(l.TK_LABEL,"Expected 'as' after '*' in import"),"as"!==this.previous().value)return this.error("Expected 'as' after '*' in import"),null;const e=this.parseIdentifierName();if(!e)return null;t.push({type:"ImportNamespaceSpecifier",start:this.previous().pos,end:e.end,local:e})}else{const e=this.parseIdentifierName();if(!e)return null;if(t.push({type:"ImportDefaultSpecifier",start:e.start,end:e.end,local:e}),this.match(l.TK_COMMA))if(this.match(l.TK_MUL)){if(this.consume(l.TK_LABEL,"Expected 'as' after '*' in import"),"as"!==this.previous().value)return this.error("Expected 'as' after '*' in import"),null;const e=this.parseIdentifierName();if(!e)return null;t.push({type:"ImportNamespaceSpecifier",start:this.previous().pos,end:e.end,local:e})}else{if(!this.match(l.TK_LBRACE))return this.error("Expected '{' or '*' after ',' in mixed import"),null;if(!this.check(l.TK_RBRACE))do{const e=this.parseImportSpecifierName();if(!e)continue;let n=e;if(this.match(l.TK_LABEL)&&"as"===this.previous().value){const e=this.parseIdentifierName();if(!e)continue;n=e}t.push({type:"ImportSpecifier",start:e.start,end:n.end,imported:e,local:n})}while(this.match(l.TK_COMMA));this.consume(l.TK_RBRACE,"Expected '}' after import specifiers")}}if(!this.match(l.TK_FROM))return this.error("Expected 'from' after import specifiers"),null;if(!this.check(l.TK_STRING))return this.error("Expected string literal after 'from'"),null;const n=this.advance(),r={type:"Literal",start:n.pos,end:n.end,value:String(n.value),raw:String(n.value),literalType:"string"};return this.consume(l.TK_SCOL,"Expected ';' after import statement"),{type:"ImportDeclaration",start:e,end:this.previous().end,specifiers:t,source:r}}parseExportDeclaration(){const e=this.previous().pos;if(this.match(l.TK_DEFAULT)){const t=this.parseExportDefaultDeclaration();return t?{type:"ExportDefaultDeclaration",start:e,end:t.end,declaration:t}:null}if(this.match(l.TK_MUL))return this.parseExportAllDeclaration(e);if(this.match(l.TK_LBRACE))return this.parseExportNamedDeclaration(e);if(this.check(l.TK_FUNC)||this.check(l.TK_LOCAL)||this.check(l.TK_CONST)){let t=null;return this.match(l.TK_FUNC)?t=this.parseFunctionDeclaration(!0):this.match(l.TK_LOCAL,l.TK_CONST)&&(t=this.parseVariableDeclaration()),t?{type:"ExportNamedDeclaration",start:e,end:t.end,declaration:t,specifiers:[],source:null}:null}return this.error("Expected declaration or export specifiers after 'export'"),null}parseExportDefaultDeclaration(){if(this.match(l.TK_FUNC))return this.parseFunctionDeclaration(!0);{const e=this.parseExpression();return e&&this.consume(l.TK_SCOL,"Expected ';' after export default expression"),e}}parseExportAllDeclaration(e){let t=null;if(this.match(l.TK_LABEL)&&"as"===this.previous().value&&(t=this.parseIdentifierName(),!t))return null;if(!this.match(l.TK_FROM))return this.error("Expected 'from' after export * declaration"),null;if(!this.check(l.TK_STRING))return this.error("Expected string literal after 'from'"),null;const n=this.advance(),r={type:"Literal",start:n.pos,end:n.end,value:String(n.value),raw:String(n.value),literalType:"string"};return this.consume(l.TK_SCOL,"Expected ';' after export * declaration"),{type:"ExportAllDeclaration",start:e,end:this.previous().end,source:r,exported:t}}parseExportNamedDeclaration(e){const t=[];if(!this.check(l.TK_RBRACE))do{const e=this.parseIdentifierName();if(!e)continue;let n=e;if(this.match(l.TK_LABEL)&&"as"===this.previous().value){const e=this.parseIdentifierName();if(!e)continue;n=e}t.push({type:"ExportSpecifier",start:e.start,end:n.end,local:e,exported:n})}while(this.match(l.TK_COMMA));this.consume(l.TK_RBRACE,"Expected '}' after export specifiers");let n=null;if(this.match(l.TK_FROM)){if(!this.check(l.TK_STRING))return this.error("Expected string literal after 'from'"),null;const e=this.advance();n={type:"Literal",start:e.pos,end:e.end,value:String(e.value),raw:String(e.value),literalType:"string"}}return this.consume(l.TK_SCOL,"Expected ';' after export declaration"),{type:"ExportNamedDeclaration",start:e,end:this.previous().end,declaration:null,specifiers:t,source:n}}}class sr extends or{parseColonEndBlock(e,t){const n=this.peek()?.pos||0;this.consume(l.TK_COLON,`Expected ':' for ${t} block`);const r=[];for(;!this.check(e)&&!this.isAtEnd();){const e=this.parseStatement();e?r.push(e):this.advance()}return this.consume(e,`Expected '${t}' to close block`),{type:"BlockStatement",start:n,end:this.previous().end,body:r}}parseIfStatement(){const e=this.previous().pos;this.consume(l.TK_LPAREN,"Expected '(' after 'if'");const t=this.parseExpression();if(!t)return null;this.consume(l.TK_RPAREN,"Expected ')' after if condition");const n=this.parseStatement();if(!n)return null;let r=null;return this.match(l.TK_ELSE)&&(r=this.parseStatement()),{type:"IfStatement",start:e,end:(r||n).end,test:t,consequent:n,alternate:r}}parseWhileStatement(){const e=this.previous().pos;this.consume(l.TK_LPAREN,"Expected '(' after 'while'");const t=this.parseExpression();if(!t)return null;this.consume(l.TK_RPAREN,"Expected ')' after while condition");const n=this.parseStatement();return n?{type:"WhileStatement",start:e,end:n.end,test:t,body:n}:null}parseVariableDeclarationWithoutSemicolon(){const e=this.previous().pos,t=this.previous().type===l.TK_CONST?"const":"let",n=[];do{if(this.check(l.TK_LABEL)){const e=this.peek()?.pos||0,t=this.advance().value,r={type:"VariableDeclarator",start:e,end:this.previous().end,id:{type:"Identifier",start:e,end:this.previous().end,name:t},init:null};n.push(r)}if(this.check(l.TK_IN)||n.length>=2)break}while(this.match(l.TK_COMMA));return{type:"VariableDeclaration",start:e,end:this.previous().end,kind:t,declarations:n}}parseForStatement(){const e=this.previous().pos;if(this.consume(l.TK_LPAREN,"Expected '(' after 'for'"),this.check(l.TK_LABEL)||this.check(l.TK_LOCAL)||this.check(l.TK_CONST)){const t=this.current;let n=null;if(n=this.match(l.TK_LOCAL,l.TK_CONST)?this.parseVariableDeclarationWithoutSemicolon():this.parseIdentifierName(),n&&this.match(l.TK_IN)){const t=this.parseExpression();if(!t)return null;this.consume(l.TK_RPAREN,"Expected ')' after for-in");let r=null;return r=this.check(l.TK_COLON)?this.parseColonEndBlock(l.TK_ENDFOR,"endfor"):this.parseStatement(),r?{type:"ForInStatement",start:e,end:r.end,left:n,right:t,body:r}:null}this.current=t}let t=null;this.check(l.TK_SCOL)?this.advance():this.match(l.TK_LOCAL,l.TK_CONST)?t=this.parseVariableDeclaration():(t=this.parseExpression(),this.consume(l.TK_SCOL,"Expected ';' after for loop initializer"));let n=null;this.check(l.TK_SCOL)||(n=this.parseExpression()),this.consume(l.TK_SCOL,"Expected ';' after for loop condition");let r=null;this.check(l.TK_RPAREN)||(r=this.parseExpression(Yn.COMMA)),this.consume(l.TK_RPAREN,"Expected ')' after for loop");const i=this.parseStatement();return i?{type:"ForStatement",start:e,end:i.end,init:t,test:n,update:r,body:i}:null}parseReturnStatement(){const e=this.previous().pos;let t=null;return this.check(l.TK_SCOL)||this.isAtEnd()||(t=this.parseExpression()),this.consume(l.TK_SCOL,"Expected ';' after return value"),{type:"ReturnStatement",start:e,end:this.previous().end,argument:t}}parseBreakStatement(){const e=this.previous().pos;let t=null;return this.check(l.TK_LABEL)&&(t=this.parseIdentifierName()),this.consume(l.TK_SCOL,"Expected ';' after 'break'"),{type:"BreakStatement",start:e,end:this.previous().end,label:t}}parseContinueStatement(){const e=this.previous().pos;let t=null;return this.check(l.TK_LABEL)&&(t=this.parseIdentifierName()),this.consume(l.TK_SCOL,"Expected ';' after 'continue'"),{type:"ContinueStatement",start:e,end:this.previous().end,label:t}}parseTryStatement(){const e=this.previous().pos,t=this.consume(l.TK_LBRACE,"Expected '{' after 'try'"),n=this.parseBlockStatement(t,"try block");let r=null;if(this.match(l.TK_CATCH)){const e=this.previous().pos;let t=null;this.match(l.TK_LPAREN)&&(t=this.parseIdentifierName(),this.consume(l.TK_RPAREN,"Expected ')' after catch parameter"));const n=this.consume(l.TK_LBRACE,"Expected '{' after catch"),i=this.parseBlockStatement(n,"catch block");r={type:"CatchClause",start:e,end:i.end,param:t,body:i}}return r?{type:"TryStatement",start:e,end:(r||n).end,block:n,handler:r}:(this.error("Missing catch after try"),null)}parseSwitchStatement(){const e=this.previous().pos;this.consume(l.TK_LPAREN,"Expected '(' after 'switch'");const t=this.parseExpression();if(!t)return null;this.consume(l.TK_RPAREN,"Expected ')' after switch discriminant"),this.consume(l.TK_LBRACE,"Expected '{' after switch");const n=[];for(;!this.check(l.TK_RBRACE)&&!this.isAtEnd();){const e=this.peek()?.pos||0;let t=null;if(this.match(l.TK_CASE))t=this.parseExpression();else{if(!this.match(l.TK_DEFAULT)){this.error("Expected 'case' or 'default' in switch statement");break}t=null}this.consume(l.TK_COLON,"Expected ':' after case label");const r=[];for(;!(this.check(l.TK_CASE)||this.check(l.TK_DEFAULT)||this.check(l.TK_RBRACE)||this.isAtEnd());){const e=this.parseStatement();e&&r.push(e)}n.push({type:"SwitchCase",start:e,end:r.length>0?r[r.length-1].end:e,test:t,consequent:r})}return this.consume(l.TK_RBRACE,"Expected '}' after switch body"),{type:"SwitchStatement",start:e,end:this.previous().end,discriminant:t,cases:n}}}class ar extends sr{parseBlockStatement(e,t){const n=e.pos,r=[];for(;!this.check(l.TK_RBRACE)&&!this.isAtEnd();){const e=this.parseStatement();e&&r.push(e)}return this.consume(l.TK_RBRACE,`Expected '}' to close ${t}`),{type:"BlockStatement",start:n,end:this.previous().end,body:r}}parseExpressionStatement(){const e=this.peek()?.pos||0,t=this.parseExpression(Yn.COMMA);if(!t)return null;if(this.check(l.TK_SCOL))this.advance();else{const t=this.peek()?.type;t===l.TK_RBRACE||t===l.TK_EOF||(this.errorAt("Expected ';' after expression",this.previous()?.end||e,this.previous()?.end||e),this.panicMode=!1)}return{type:"ExpressionStatement",start:e,end:this.previous().end,expression:t}}parseEmptyStatement(){const e=this.previous();return{type:"EmptyStatement",start:e.pos,end:e.end}}}class cr extends ar{parseStatement(){if(this.check(l.TK_ERROR)){const e=this.advance(),t=e.value?String(e.value):"Unexpected token";return this.errorAt(t,e.pos,e.end),null}try{if(this.match(l.TK_IMPORT))return this.parseImportDeclaration();if(this.match(l.TK_EXPORT))return this.parseExportDeclaration();if(this.match(l.TK_LOCAL,l.TK_CONST))return this.parseVariableDeclaration();if(this.match(l.TK_FUNC))return this.parseFunctionDeclaration();if(this.match(l.TK_IF))return this.parseIfStatement();if(this.match(l.TK_WHILE))return this.parseWhileStatement();if(this.match(l.TK_FOR))return this.parseForStatement();if(this.match(l.TK_RETURN))return this.parseReturnStatement();if(this.match(l.TK_BREAK))return this.parseBreakStatement();if(this.match(l.TK_CONTINUE))return this.parseContinueStatement();if(this.match(l.TK_TRY))return this.check(l.TK_LBRACE)?this.parseTryStatement():(this.current--,this.warningAt("'try' keyword used as identifier",this.peek().pos,this.peek().end),this.parseExpressionStatement());if(this.match(l.TK_SWITCH))return this.parseSwitchStatement();if(this.match(l.TK_LBRACE)){const e=this.previous();return this.parseBlockStatement(e,"block statement")}return this.match(l.TK_SCOL)?this.parseEmptyStatement():this.parseExpressionStatement()}catch(e){return this.synchronize(Xn.STATEMENT),null}}}class lr extends cr{constructor(e,t=""){super(e),this.sourceText=t,this.initializeParseRules()}parse(){try{return{ast:this.parseProgram(),errors:this.errors,warnings:this.warnings}}catch(e){return{ast:null,errors:this.errors,warnings:this.warnings}}}parseProgram(){const e=this.peek()?.pos||0,t=[];for(;!this.isAtEnd();)try{const e=this.parseStatement();e&&t.push(e)}catch(e){if(this.synchronize(Xn.STATEMENT),this.isAtEnd())break}return{type:"Program",start:e,end:this.previous()?.end||e,body:t}}}var ur=n(5317),pr=n(857);const dr=wt;let mr=null,hr=null;const fr=new Map;function gr(){const e=pr.platform();return"linux"===e||"darwin"===e||"freebsd"===e||"openbsd"===e}function yr(){if(null!==hr)return hr;try{(0,ur.execSync)("command -v ucode",{stdio:"ignore",timeout:5e3}),hr=!0}catch{hr=!1}return hr}function Tr(){if(mr)return mr;const e=[];for(const t of dr)e.push({name:t,source:"builtin"});if(gr()&&yr())try{const t=function(e){const t=[];for(const n of e)try{if(n.includes("*")){const e=p.dirname(n),r=p.basename(n);if(u.existsSync(e)){const n=u.readdirSync(e),i=new RegExp(r.replace(/\*/g,".*"));for(const r of n)if(i.test(r)&&r.endsWith(".so")){const n=p.basename(r,".so"),i=p.join(e,r);dr.includes(n)||t.push({name:n,source:"system",path:i})}}}else if(u.existsSync(n)&&n.endsWith(".so")){const e=p.basename(n,".so");dr.includes(e)||t.push({name:e,source:"system",path:n})}}catch(e){continue}return t}(function(){try{return(0,ur.execSync)("ucode -e \"print(join('\\n', filter(global.REQUIRE_SEARCH_PATH, function(element) {return match(element, /.*so/);}))); \"",{encoding:"utf8",timeout:5e3}).trim().split("\n").filter(e=>e.trim().length>0)}catch(e){return console.warn("Failed to get ucode module search paths:",e),[]}}());e.push(...t)}catch(e){console.warn("Failed to discover system modules:",e)}return mr=e,e}function _r(e){const t=fr.get(e);if(t)return t;let n;try{const t=function(e){if(!gr()||!yr())return[];try{const t=(0,ur.execSync)(`ucode -e "import * as ${e} from '${e}'; for (thing in ${e}) {print(type(${e}[thing]), ' ', thing, '\\n');}"`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),n=[],r=t.trim().split("\n").filter(e=>e.trim().length>0);for(const e of r){const t=e.trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).join(" ");let i="unknown";"function"===e?i="function":"resource"===e&&(i="resource"),n.push({name:r,type:i})}}return n}catch(e){return[]}}(e);n=t.length>0?t:Nr(e)}catch(t){console.warn(`Failed to get module members for ${e}:`,t),n=Nr(e)}return n.length>0&&fr.set(e,n),n}function Nr(e){if(!wn(e))return[];const t=Pn[e],n=[];for(const e of t.getFunctionNames())n.push({name:e,type:"function"});for(const e of t.getConstantNames())n.push({name:e,type:"constant"});return"nl80211"!==e&&"rtnl"!==e||n.push({name:"const",type:"constant"}),n}class Rr{workspaceRoot;fileCache=new Map;exportCache=new Map;constructor(e){this.workspaceRoot=e||process.cwd()}isBuiltinModule(e){return Tr().some(t=>t.name===e&&"builtin"===t.source)}resolveImportPath(e,t){try{if(this.isBuiltinModule(e))return`builtin://${e}`;const n=this.uriToFilePath(t);if(!n)return null;const r=p.dirname(n);if(e.startsWith("./")||e.startsWith("../")){const t=p.resolve(r,e);if(u.existsSync(t))return this.filePathToUri(t);if(!t.endsWith(".uc")){const e=t+".uc";if(u.existsSync(e))return this.filePathToUri(e)}if(e.startsWith("./")){const t=p.resolve(this.workspaceRoot,e.replace(/^\.\//,""));if(u.existsSync(t))return this.filePathToUri(t);if(!t.endsWith(".uc")){const e=t+".uc";if(u.existsSync(e))return this.filePathToUri(e)}}}if(e.startsWith("/")){const t=p.resolve(this.workspaceRoot,e.substring(1));if(u.existsSync(t))return this.filePathToUri(t)}if(!e.includes("/")&&!e.startsWith(".")&&!e.includes(".")){const t=p.resolve(r,e+".uc");if(u.existsSync(t))return this.filePathToUri(t);const n=p.resolve(r,e);if(u.existsSync(n))return this.filePathToUri(n)}if(!e.includes("/")&&!e.startsWith(".")){const t=e.replace(/\./g,"/")+".uc",n=p.resolve(this.workspaceRoot,t);if(u.existsSync(n))return this.filePathToUri(n);const i=p.resolve(r,t);if(u.existsSync(i))return this.filePathToUri(i)}return null}catch(e){return console.error("Error resolving import path:",e),null}}findFunctionDefinition(e,t){try{const n=this.fileCache.get(e);if(n)return n.find(e=>e.name===t)||null;const r=this.loadFunctionDefinitions(e);return r?(this.fileCache.set(e,r),r.find(e=>e.name===t)||null):null}catch(e){return console.error("Error finding function definition:",e),null}}getModuleExports(e){try{if(e.startsWith("builtin://")){const t=e.replace("builtin://","");return this.getBuiltinModuleExports(t)}const t=this.exportCache.get(e);if(t)return t;const n=this.loadModuleExports(e);return n?(this.exportCache.set(e,n),n):null}catch(e){return console.error("Error getting module exports:",e),null}}getBuiltinModuleExports(e){const t=_r(e),n=[];for(const e of t)n.push({name:e.name,type:"named",isFunction:"function"===e.type});return n}loadFunctionDefinitions(e){try{const t=this.uriToFilePath(e);if(!t||!u.existsSync(t))return null;const n=u.readFileSync(t,"utf8"),r=new E(n,{rawMode:!0}),i=r.tokenize(),o=new lr(i,n);o.setComments(r.comments);const s=o.parse();if(!s.ast)return null;const a=[];return this.findFunctions(s.ast,a),a}catch(e){return console.error("Error loading function definitions:",e),null}}findFunctions(e,t){if("FunctionDeclaration"===e.type){const n=e;t.push({name:n.id.name,node:n,start:n.start,end:n.end})}this.visitChildren(e,e=>{this.findFunctions(e,t)})}visitChildren(e,t){for(const n in e){if("type"===n||"start"===n||"end"===n)continue;const r=e[n];if(Array.isArray(r))for(const e of r)e&&"object"==typeof e&&e.type&&t(e);else r&&"object"==typeof r&&r.type&&t(r)}}loadModuleExports(e){try{const t=this.uriToFilePath(e);if(!t||!u.existsSync(t))return null;const n=u.readFileSync(t,"utf-8"),r=new E(n,{rawMode:!0}),i=r.tokenize(),o=new lr(i,n);o.setComments(r.comments);const s=o.parse();if(!s.ast)return null;const a=new Set;for(const e of s.ast.body||[])"FunctionDeclaration"===e.type&&e.id?.name&&a.add(e.id.name);const c=[];return this.findExports(s.ast,c,a),c}catch(e){return console.error("Error loading module exports:",e),null}}findExports(e,t,n){if("ExportDefaultDeclaration"===e.type){const r=e.declaration,i="FunctionDeclaration"===r?.type||"FunctionExpression"===r?.type,o="Identifier"===r?.type&&n?.has(r.name),s="Identifier"===r?.type?r.name:void 0;t.push({name:"default",type:"default",isFunction:i||!!o,exportedName:s})}else if("ExportNamedDeclaration"===e.type){const n=e;if(n.declaration){if("FunctionDeclaration"===n.declaration.type){const e=n.declaration;t.push({name:e.id.name,type:"named",isFunction:!0})}else if("VariableDeclaration"===n.declaration.type){const e=n.declaration;for(const n of e.declarations)t.push({name:n.id.name,type:"named",isFunction:!1})}}else if(n.specifiers)for(const e of n.specifiers)t.push({name:e.exported.name,type:"named",isFunction:!1})}this.visitChildren(e,e=>{this.findExports(e,t,n)})}uriToFilePath(e){try{return e.startsWith("file://")?decodeURIComponent(e.substring(7)):e.startsWith("/")?e:p.resolve(this.workspaceRoot,e)}catch(e){return null}}filePathToUri(e){return"file://"+e}getDefaultExportPropertyTypes(e){try{const t=this.uriToFilePath(e);if(!t||!u.existsSync(t))return null;const n=u.readFileSync(t,"utf-8"),r=new E(n,{rawMode:!0}),i=r.tokenize(),o=new lr(i,n);o.setComments(r.comments);const s=o.parse();if(!s.ast)return null;const a=s.ast.body||[],c=new Map,l=new Set,p=new Map;for(const e of a)if("FunctionDeclaration"===e.type&&e.id?.name&&(l.add(e.id.name),p.set(e.id.name,e)),"VariableDeclaration"===e.type)for(const t of e.declarations||[])t.id?.name&&t.init&&c.set(t.id.name,t.init);let d=null;for(const e of a)if("ExportDefaultDeclaration"===e.type){d=e.declaration;break}if(!d)return null;let m=d;if("Identifier"===m.type&&c.has(m.name)&&(m=c.get(m.name)),"ObjectExpression"!==m.type)return null;const h=new Map,f=new Map,g=new Map;for(const e of m.properties||[]){const t=e.key?.name||e.key?.value;if(!t)continue;const n=e.value;if(n)if("FunctionExpression"===n.type||"ArrowFunctionExpression"===n.type){h.set(t,C.FUNCTION);const e=this.inferFunctionReturnType(n);e&&g.set(t,e)}else if("Identifier"===n.type&&l.has(n.name)){h.set(t,C.FUNCTION);const e=p.get(n.name);if(e){const n=this.inferFunctionReturnType(e);n&&g.set(t,n)}}else if("Literal"===n.type||"StringLiteral"===n.type)"number"==typeof n.value?h.set(t,C.INTEGER):"string"==typeof n.value?h.set(t,C.STRING):"boolean"==typeof n.value?h.set(t,C.BOOLEAN):h.set(t,C.UNKNOWN);else if("ObjectExpression"===n.type){h.set(t,C.OBJECT);const e=this.extractObjectPropertyTypes(n,l,c,new Map);e.size>0&&f.set(t,e)}else if("ArrayExpression"===n.type)h.set(t,C.ARRAY);else if("Identifier"===n.type){const e=c.get(n.name);if(e){if(h.set(t,this.inferNodeType(e)),"ObjectExpression"===e.type){const n=this.extractObjectPropertyTypes(e,l,c,new Map);n.size>0&&f.set(t,n)}}else h.set(t,C.UNKNOWN)}else h.set(t,C.UNKNOWN)}if(0===h.size)return null;const y={propertyTypes:h};return f.size>0&&(y.nestedPropertyTypes=f),g.size>0&&(y.functionReturnTypes=g),y}catch{return null}}getNamedExportTypeInfo(e,t){try{const n=this.uriToFilePath(e);if(!n||!u.existsSync(n))return null;const r=u.readFileSync(n,"utf-8"),i=new E(r,{rawMode:!0}),o=i.tokenize(),s=new lr(o,r);s.setComments(i.comments);const a=s.parse();if(!a.ast)return null;const c=a.ast.body||[],l=new Map,p=new Set;for(const e of c)if("FunctionDeclaration"===e.type&&e.id?.name&&p.add(e.id.name),"VariableDeclaration"===e.type)for(const t of e.declarations||[])t.id?.name&&t.init&&l.set(t.id.name,t.init);for(const e of c){if("ExportNamedDeclaration"!==e.type)continue;const n=e;if(n.declaration){if("FunctionDeclaration"===n.declaration.type){if(n.declaration.id.name===t)return{type:C.FUNCTION}}else if("VariableDeclaration"===n.declaration.type){const e=n.declaration;for(const n of e.declarations){if(n.id?.name!==t)continue;const e=n.init;if(!e)return{type:C.UNKNOWN};const r=this.inferNodeType(e);if("ObjectExpression"===e.type){const t=new Map,n=new Map;for(const r of e.properties||[]){const e=r.key?.name||r.key?.value;if(!e||!r.value)continue;const i=r.value;if("FunctionExpression"===i.type||"ArrowFunctionExpression"===i.type)t.set(e,C.FUNCTION);else if("ObjectExpression"===i.type){t.set(e,C.OBJECT);const r=this.extractObjectPropertyTypes(i,p,l,new Map);r.size>0&&n.set(e,r)}else t.set(e,this.inferNodeType(i))}const i={type:r};return t.size>0&&(i.propertyTypes=t),n.size>0&&(i.nestedPropertyTypes=n),i}return{type:r}}}}else if(n.specifiers)for(const e of n.specifiers){if(e.exported.name!==t)continue;const n=e.local.name;if(p.has(n))return{type:C.FUNCTION};const r=l.get(n);if(r){const e=this.inferNodeType(r);if("ObjectExpression"===r.type){const t=this.extractObjectPropertyTypes(r,p,l,new Map),n={type:e};return t.size>0&&(n.propertyTypes=t),n}return{type:e}}return{type:C.UNKNOWN}}}return null}catch{return null}}getDefaultExportFunctionReturnInfo(e){try{const t=this.uriToFilePath(e);if(!t||!u.existsSync(t))return null;const n=u.readFileSync(t,"utf-8"),r=new E(n,{rawMode:!0}),i=r.tokenize(),o=new lr(i,n);o.setComments(r.comments);const s=o.parse();if(!s.ast)return null;const a=s.ast.body||[],c=new Map,l=new Map;for(const e of a)if("FunctionDeclaration"===e.type&&e.id?.name&&c.set(e.id.name,e),"VariableDeclaration"===e.type)for(const t of e.declarations||[])t.id?.name&&t.init&&l.set(t.id.name,t.init);let p=null;for(const e of a)if("ExportDefaultDeclaration"===e.type){p=e.declaration;break}if(!p)return null;let d=null;if("FunctionDeclaration"===p.type||"FunctionExpression"===p.type)d=p;else if("Identifier"===p.type){const e=p.name;c.has(e)&&(d=c.get(e))}if(!d)return null;const m=d.body;if(!m)return null;const h=new Map,f=new Set,g=new Map,y=m.body||[];for(const e of y)if("FunctionDeclaration"===e.type&&e.id?.name&&(f.add(e.id.name),h.set(e.id.name,e)),"VariableDeclaration"===e.type)for(const t of e.declarations||[])t.id?.name&&t.init&&g.set(t.id.name,t.init);const T=[];if(this.collectReturnObjectProperties(y,f,g,c,T),0===T.length)return null;const _=new Map(T[0]);for(let e=1;e<T.length;e++){const t=T[e];for(const e of[..._.keys()])t.has(e)||_.delete(e)}if(0===_.size)return null;const N=this.analyzePropertyFunctionReturnTypes(_,h,g,c,d.params||[]),R={returnType:C.OBJECT,returnPropertyTypes:_};return N.size>0&&(R.propertyFunctionReturnTypes=N),R}catch{return null}}collectReturnObjectProperties(e,t,n,r,i){for(const o of e)if("ReturnStatement"===o.type){const e=o.argument;if("ObjectExpression"===e?.type){const o=this.extractObjectPropertyTypes(e,t,n,r);o.size>0&&i.push(o)}}else{if("FunctionDeclaration"===o.type||"FunctionExpression"===o.type||"ArrowFunctionExpression"===o.type)continue;if("IfStatement"===o.type){const e=o;if(e.consequent){const o="BlockStatement"===e.consequent.type?e.consequent.body:[e.consequent];this.collectReturnObjectProperties(o,t,n,r,i)}if(e.alternate){const o="BlockStatement"===e.alternate.type?e.alternate.body:[e.alternate];this.collectReturnObjectProperties(o,t,n,r,i)}}else"BlockStatement"===o.type&&this.collectReturnObjectProperties(o.body||[],t,n,r,i)}}extractObjectPropertyTypes(e,t,n,r){const i=new Map;for(const o of e.properties||[]){const e=o.key?.name||o.key?.value;if(!e)continue;const s=o.value;if(s)if("FunctionExpression"===s.type||"ArrowFunctionExpression"===s.type)i.set(e,C.FUNCTION);else if("Identifier"===s.type){const o=s.name;if(t.has(o)||r.has(o))i.set(e,C.FUNCTION);else if(n.has(o)){const t=n.get(o);i.set(e,this.inferNodeType(t))}else i.set(e,C.UNKNOWN)}else"Literal"===s.type?"number"==typeof s.value?i.set(e,Number.isInteger(s.value)?C.INTEGER:C.DOUBLE):"string"==typeof s.value?i.set(e,C.STRING):"boolean"==typeof s.value?i.set(e,C.BOOLEAN):i.set(e,C.UNKNOWN):"ObjectExpression"===s.type?i.set(e,C.OBJECT):"ArrayExpression"===s.type?i.set(e,C.ARRAY):i.set(e,C.UNKNOWN)}return i}analyzePropertyFunctionReturnTypes(e,t,n,r,i){const o=new Map,s=new Set;for(const e of i)"Identifier"===e.type&&s.add(e.name);for(const[i,a]of e){if(a!==C.FUNCTION)continue;const e=t.get(i)||r.get(i);if(!e)continue;const c=this.inferInnerFunctionReturnTypeHint(e,n,s);c&&o.set(i,c)}return o}inferInnerFunctionReturnTypeHint(e,t,n){const r=e.body;if(!r)return null;const i=r.body||[],o=new Map(t);this.collectAssignments(i,o);const s=[];for(const e of i)this.collectReturnValues(e,s);for(const e of s){const t=this.resolveNodeToKnownType(e,o,n);if(t)return t}return s.length>0?this.inferPrimitiveReturnType(s):null}inferPrimitiveReturnType(e){const t=new Set;for(const n of e){const e=this.inferReturnExprType(n);e&&t.add(e)}return 0===t.size?null:1===t.size?[...t][0]:[...t].join(" | ")}inferReturnExprType(e){if(!e)return null;if("Literal"===e.type){const t=e.value;return"string"==typeof t?"string":"number"==typeof t?Number.isInteger(t)?"integer":"double":"boolean"==typeof t?"boolean":null===t?"null":null}if("BinaryExpression"===e.type&&"+"===e.operator){const t=this.inferReturnExprType(e.left),n=this.inferReturnExprType(e.right);if("string"===t||"string"===n)return"string"}if("TemplateLiteral"===e.type)return"string";if("CallExpression"===e.type){const t=e;if("Identifier"===t.callee?.type){const e=t.callee.name,n=this.resolveBuiltinReturnType(e);if(n)return n}}if("ObjectExpression"===e.type)return"object";if("ArrayExpression"===e.type)return"array";if("UnaryExpression"===e.type&&"!"===e.operator)return"boolean";if("BinaryExpression"===e.type){const t=e.operator;if(["==","!=","===","!==","<",">","<=",">="].includes(t))return"boolean"}return"LogicalExpression"===e.type&&"||"===e.operator?this.inferReturnExprType(e.right):null}resolveBuiltinReturnType(e){switch(e){case"trim":case"ltrim":case"rtrim":case"replace":case"substr":case"sprintf":case"join":case"uc":case"lc":case"chr":case"hex":case"b64enc":case"type":case"proto":case"readline":return"string";case"split":case"sort":case"reverse":case"keys":case"values":case"filter":case"map":case"slice":return"array";case"length":case"index":case"rindex":case"ord":case"int":case"time":case"system":return"integer";case"exists":case"delete":return"boolean";case"match":return"array | null";default:return null}}collectAssignments(e,t){for(const n of e)if(n&&"FunctionDeclaration"!==n.type&&"FunctionExpression"!==n.type&&"ArrowFunctionExpression"!==n.type){if("ExpressionStatement"===n.type){const e=n.expression;if("AssignmentExpression"===e?.type&&"Identifier"===e.left?.type&&e.right){const n=e.left.name,r=t.get(n);(!r||"Literal"===r.type&&null===r.value)&&t.set(n,e.right)}}for(const e of["body","consequent","alternate","block"]){const r=n[e];Array.isArray(r)?this.collectAssignments(r,t):r&&"object"==typeof r&&r.type&&this.collectAssignments([r],t)}}}collectReturnValues(e,t){if(e&&"FunctionDeclaration"!==e.type&&"FunctionExpression"!==e.type&&"ArrowFunctionExpression"!==e.type){if("ReturnStatement"===e.type){const n=e.argument;return void(n&&t.push(n))}for(const n of["body","consequent","alternate","block","handler","finalizer"]){const r=e[n];if(Array.isArray(r))for(const e of r)this.collectReturnValues(e,t);else r&&"object"==typeof r&&r.type&&this.collectReturnValues(r,t)}}}resolveNodeToKnownType(e,t,n,r=0){if(r>5)return null;if("Identifier"===e.type){const i=e.name,o=t.get(i);return o?this.resolveNodeToKnownType(o,t,n,r+1):null}if("CallExpression"===e.type){const n=e;if("Identifier"===n.callee?.type){const e=n.callee.name,r=this.resolveKnownFunctionReturnType(e);if(r)return r;const i=t.get(e);if("MemberExpression"===i?.type){const e=i;if("Identifier"===e.property?.type){const t=e.property.name,n=this.resolveKnownFunctionReturnType(t);if(n)return n}}}if("MemberExpression"===n.callee?.type){const e=n.callee;if("Identifier"===e.property?.type){const t=e.property.name;return this.resolveKnownFunctionReturnType(t)}}}return null}resolveKnownFunctionReturnType(e){switch(e){case"cursor":return"uci.cursor";case"connect":return"ubus.connection";case"open":return"fs.file";case"opendir":return"fs.dir";case"popen":return"fs.proc";case"listener":return"nl80211.listener";default:return null}}inferNodeType(e){switch(e.type){case"ObjectExpression":return C.OBJECT;case"ArrayExpression":return C.ARRAY;case"FunctionExpression":case"ArrowFunctionExpression":return C.FUNCTION;case"TemplateLiteral":return C.STRING;case"Literal":{const t=e.value;return"string"==typeof t?C.STRING:"number"==typeof t?Number.isInteger(t)?C.INTEGER:C.DOUBLE:"boolean"==typeof t?C.BOOLEAN:null===t?C.NULL:C.UNKNOWN}case"BinaryExpression":{const t=e;if("+"===t.operator){const e=this.inferNodeType(t.left),n=this.inferNodeType(t.right);if(e===C.STRING||n===C.STRING)return C.STRING;if(!(e!==C.INTEGER&&e!==C.DOUBLE||n!==C.INTEGER&&n!==C.DOUBLE))return e===C.DOUBLE||n===C.DOUBLE?C.DOUBLE:C.INTEGER}return["==","!=","<",">","<=",">=","===","!=="].includes(t.operator)?C.BOOLEAN:["-","*","/","%"].includes(t.operator)?C.INTEGER:C.UNKNOWN}case"CallExpression":{const t=e;if("Identifier"===t.callee?.type){const e=t.callee.name;if("sprintf"===e||"substr"===e||"trim"===e||"ltrim"===e||"rtrim"===e||"join"===e||"replace"===e||"uchr"===e||"lc"===e||"uc"===e)return C.STRING;if("length"===e||"index"===e||"rindex"===e||"ord"===e||"hex"===e||"int"===e||"time"===e||"printf"===e)return C.INTEGER;if("split"===e||"keys"===e||"values"===e||"sort"===e||"reverse"===e||"splice"===e||"filter"===e||"map"===e)return C.ARRAY;if("type"===e)return C.STRING}return C.UNKNOWN}default:return C.UNKNOWN}}inferFunctionReturnType(e){const t=e.body;if(!t)return null;const n=t.body||t;if(!Array.isArray(n))return null;const r=[];return this.collectReturnTypes(n,r),0===r.length?null:1===[...new Set(r.map(e=>"string"==typeof e?e:"complex"))].length?r[0]:null}collectReturnTypes(e,t){for(const n of e)if("FunctionDeclaration"!==n.type&&"FunctionExpression"!==n.type&&"ArrowFunctionExpression"!==n.type){if("ReturnStatement"===n.type){const e=n.argument;e&&t.push(this.inferNodeType(e))}if(n.body){const e=n.body;Array.isArray(e)?this.collectReturnTypes(e,t):e.body&&Array.isArray(e.body)&&this.collectReturnTypes(e.body,t)}if(n.consequent){const e=n.consequent;Array.isArray(e)?this.collectReturnTypes(e,t):e.body&&Array.isArray(e.body)&&this.collectReturnTypes(e.body,t)}if(n.alternate){const e=n.alternate;Array.isArray(e)?this.collectReturnTypes(e,t):e.body&&Array.isArray(e.body)?this.collectReturnTypes(e.body,t):"IfStatement"===e.type&&this.collectReturnTypes([e],t)}}}clearCache(){this.fileCache.clear()}clearFileCache(e){this.fileCache.delete(e)}}class Er{types=new Map;clone(){const e=new Er;return e.types=new Map(this.types),e}get(e){return this.types.get(e)}set(e,t){this.types.set(e,t)}has(e){return this.types.has(e)}delete(e){return this.types.delete(e)}getAllKeys(){return Array.from(this.types.keys())}merge(e){const t=new Set([...this.types.keys(),...e.types.keys()]);for(const n of t){const t=this.types.get(n),r=e.types.get(n),i=this.computeUnion(t,r);this.types.set(n,i)}}computeUnion(e,t){if(!e)return t||C.UNKNOWN;if(!t)return e;if(this.typesEqual(e,t))return e;if(D(e)&&D(t)){const n=P(e),r=P(t);return k(this.computeUnion(n,r))}return O([...I(e),...I(t)])}typesEqual(e,t){if("string"==typeof e&&"string"==typeof t)return e===t;if(L(e)&&L(t)){const n=new Set(e.types),r=new Set(t.types);if(n.size!==r.size)return!1;for(const e of n)if(!r.has(e))return!1;return!0}return D(e)&&D(t)?this.typesEqual(e.elementType,t.elementType):!(D(e)&&t===C.ARRAY||D(t)&&e===C.ARRAY)&&"object"==typeof e&&"object"==typeof t&&("moduleName"in e&&"moduleName"in t?e.moduleName===t.moduleName:"isDefaultImport"in e&&"isDefaultImport"in t&&"type"in e&&"type"in t?e.isDefaultImport===t.isDefaultImport&&e.type===t.type:JSON.stringify(e)===JSON.stringify(t))}narrow(e,t){const n=this.types.get(e);if(n)if(L(n)){const r=I(t),i=n.types.filter(e=>r.includes(e));i.length>0?this.types.set(e,O(i)):this.types.set(e,t)}else this.types.set(e,t);else this.types.set(e,t)}exclude(e,t){const n=this.types.get(e);if(!n)return;const r=I(t);if(L(n)){const t=n.types.filter(e=>!r.includes(e));t.length>0?this.types.set(e,O(t)):this.types.set(e,C.UNKNOWN)}else r.includes(n)&&this.types.set(e,C.UNKNOWN)}toString(){return`{ ${Array.from(this.types.entries()).map(([e,t])=>`${e}: ${x(t)}`).sort().join(", ")} }`}equals(e){const t=this.getAllKeys(),n=e.getAllKeys();if(t.length!==n.length)return!1;for(const n of t){const t=this.types.get(n),r=e.types.get(n);if(!r||!this.typesEqual(t,r))return!1}return!0}size(){return this.types.size}clear(){this.types.clear()}}class br{cfg;currentBlock;nextBlockId=0;nodeToBlock=new Map;loopStack=[];terminatorNames;constructor(e,t){this.terminatorNames=t||new Set(["die","exit"]),this.cfg={entry:void 0,exit:void 0,blocks:[],...e&&{name:e}},this.cfg.entry=this.createBlock("entry"),this.cfg.exit=this.createBlock("exit"),this.currentBlock=this.cfg.entry}build(e){return this.visitNode(e),this.currentBlock!==this.cfg.exit&&this.connect(this.currentBlock,this.cfg.exit),this.cfg}getNodeToBlockMap(){return this.nodeToBlock}createBlock(e){const t={id:this.nextBlockId++,statements:[],predecessors:[],successors:[],typeStateIn:new Er,typeStateOut:new Er,...e&&{label:e}};return this.cfg.blocks.push(t),t}connect(e,t,n,r=!1){const i={target:t,...n&&{condition:n},...r&&{isNegative:r}};return e.successors.push(i),t.predecessors.push(e),i}addStatement(e){this.currentBlock.statements.push(e),this.nodeToBlock.set(e,this.currentBlock)}visitNode(e){switch(e.type){case"Program":this.visitProgram(e);break;case"IfStatement":this.visitIfStatement(e);break;case"WhileStatement":this.visitWhileStatement(e);break;case"ForStatement":this.visitForStatement(e);break;case"ForInStatement":this.visitForInStatement(e);break;case"SwitchStatement":this.visitSwitchStatement(e);break;case"TryStatement":this.visitTryStatement(e);break;case"ReturnStatement":this.visitReturnStatement(e);break;case"BreakStatement":this.visitBreakStatement(e);break;case"ContinueStatement":this.visitContinueStatement(e);break;case"ThrowStatement":this.visitThrowStatement(e);break;case"BlockStatement":this.visitBlockStatement(e);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":default:this.addStatement(e);break;case"ConditionalExpression":this.visitConditionalExpression(e);break;case"LogicalExpression":this.visitLogicalExpression(e);break;case"ExpressionStatement":{const t=e;if(this.addStatement(e),"CallExpression"===t.expression.type){const e=t.expression,n="Identifier"===e.callee.type?e.callee.name:null;n&&this.terminatorNames.has(n)&&(this.connect(this.currentBlock,this.cfg.exit),this.currentBlock=this.createBlock("after.die"))}break}}}visitProgram(e){for(const t of e.body)this.visitNode(t)}visitBlockStatement(e){for(const t of e.body)this.visitNode(t)}visitIfStatement(e){this.addStatement(e.test);const t=this.createBlock("if.then"),n=e.alternate?this.createBlock("if.else"):null,r=this.createBlock("if.merge");this.connect(this.currentBlock,t,e.test,!1),n?this.connect(this.currentBlock,n,e.test,!0):this.connect(this.currentBlock,r,e.test,!0),this.currentBlock=t,this.visitNode(e.consequent),0===this.currentBlock.successors.length&&this.connect(this.currentBlock,r),n&&e.alternate&&(this.currentBlock=n,this.visitNode(e.alternate),0===this.currentBlock.successors.length&&this.connect(this.currentBlock,r)),this.currentBlock=r}visitWhileStatement(e){const t=this.createBlock("while.condition"),n=this.createBlock("while.body"),r=this.createBlock("while.after");this.connect(this.currentBlock,t),this.currentBlock=t,this.addStatement(e.test),this.connect(t,n,e.test,!1),this.connect(t,r,e.test,!0),this.loopStack.push({continueTarget:t,breakTarget:r,type:"while"}),this.currentBlock=n,this.visitNode(e.body),0===this.currentBlock.successors.length&&this.connect(this.currentBlock,t),this.loopStack.pop(),this.currentBlock=r}visitForStatement(e){const t=this.createBlock("for.init"),n=this.createBlock("for.condition"),r=this.createBlock("for.body"),i=this.createBlock("for.update"),o=this.createBlock("for.after");this.connect(this.currentBlock,t),this.currentBlock=t,e.init&&this.addStatement(e.init),this.connect(this.currentBlock,n),this.currentBlock=n,e.test?(this.addStatement(e.test),this.connect(n,r,e.test,!1),this.connect(n,o,e.test,!0)):this.connect(n,r),this.loopStack.push({continueTarget:i,breakTarget:o,type:"for"}),this.currentBlock=r,this.visitNode(e.body),0===this.currentBlock.successors.length&&this.connect(this.currentBlock,i),this.currentBlock=i,e.update&&this.addStatement(e.update),this.connect(this.currentBlock,n),this.loopStack.pop(),this.currentBlock=o}visitForInStatement(e){const t=this.createBlock("for-in.setup"),n=this.createBlock("for-in.condition"),r=this.createBlock("for-in.body"),i=this.createBlock("for-in.after");this.connect(this.currentBlock,t),this.currentBlock=t,this.addStatement(e.left),this.addStatement(e.right),this.connect(this.currentBlock,n),this.currentBlock=n,this.connect(n,r),this.connect(n,i),this.loopStack.push({continueTarget:n,breakTarget:i,type:"for-in"}),this.currentBlock=r,this.visitNode(e.body),0===this.currentBlock.successors.length&&this.connect(this.currentBlock,n),this.loopStack.pop(),this.currentBlock=i}visitSwitchStatement(e){this.addStatement(e.discriminant);const t=this.currentBlock,n=this.createBlock("switch.after"),r=[];for(let n=0;n<e.cases.length;n++){const i=e.cases[n],o=i.test?`switch.case${n}`:"switch.default",s=this.createBlock(o);r.push(s),i.test?this.connect(t,s,i.test,!1):this.connect(t,s)}e.cases.some(e=>null===e.test)||this.connect(t,n),this.loopStack.push({continueTarget:n,breakTarget:n,type:"switch"});for(let t=0;t<e.cases.length;t++){const i=e.cases[t],o=r[t];this.currentBlock=o,i.test&&this.addStatement(i.test);for(const e of i.consequent)this.visitNode(e);0===this.currentBlock.successors.length&&t<e.cases.length-1?this.connect(this.currentBlock,r[t+1]):0===this.currentBlock.successors.length&&t===e.cases.length-1&&this.connect(this.currentBlock,n)}this.loopStack.pop(),this.currentBlock=n}visitTryStatement(e){const t=this.createBlock("try"),n=e.handler?this.createBlock("catch"):null,r=this.createBlock("try.after");this.connect(this.currentBlock,t),this.currentBlock=t,this.visitNode(e.block),0===this.currentBlock.successors.length&&this.connect(this.currentBlock,r),n&&e.handler&&(this.connect(t,n),this.currentBlock=n,e.handler.param&&this.addStatement(e.handler.param),this.visitNode(e.handler.body),0===this.currentBlock.successors.length&&this.connect(this.currentBlock,r)),this.currentBlock=r}visitReturnStatement(e){e.argument&&this.addStatement(e.argument),this.addStatement(e),this.connect(this.currentBlock,this.cfg.exit),this.currentBlock=this.createBlock("after.return")}visitBreakStatement(e){this.addStatement(e);const t=this.loopStack[this.loopStack.length-1];t&&this.connect(this.currentBlock,t.breakTarget),this.currentBlock=this.createBlock("after.break")}visitContinueStatement(e){this.addStatement(e);const t=this.loopStack[this.loopStack.length-1];t&&this.connect(this.currentBlock,t.continueTarget),this.currentBlock=this.createBlock("after.continue")}visitThrowStatement(e){this.addStatement(e.argument),this.addStatement(e),this.connect(this.currentBlock,this.cfg.exit),this.currentBlock=this.createBlock("after.throw")}visitConditionalExpression(e){this.addStatement(e)}visitLogicalExpression(e){this.addStatement(e)}}const vr=Symbol.for("@effect/matcher/Matcher"),Sr={[vr]:{_input:le,_filters:le,_remaining:le,_result:le,_provided:le,_return:le},_tag:"ValueMatcher",add(e){return"Right"===this.value._tag?this:"When"===e._tag&&!0===e.guard(this.provided)||"Not"===e._tag&&!1===e.guard(this.provided)?Cr(this.provided,Dt(e.evaluate(this.provided))):this},pipe(){return Ke(this,arguments)}};function Cr(e,t){const n=Object.create(Sr);return n.provided=e,n.value=t,n}const Ar=e=>{if("function"==typeof e)return e;if(Array.isArray(e)){const t=e.map(Ar),n=t.length;return e=>{if(!Array.isArray(e))return!1;for(let r=0;r<n;r++)if(!1===t[r](e[r]))return!1;return!0}}if(null!==e&&"object"==typeof e){const t=Object.entries(e).map(([e,t])=>[e,Ar(t)]),n=t.length;return e=>{if("object"!=typeof e||null===e)return!1;for(let r=0;r<n;r++){const[n,i]=t[r];if(!(n in e)||!1===i(e[n]))return!1}return!0}}return t=>t===e},Or=e=>{if("ValueMatcher"===e._tag)return e.value;const t=e.cases.length;if(1===t){const t=e.cases[0];return e=>"When"===t._tag&&!0===t.guard(e)||"Not"===t._tag&&!1===t.guard(e)?Dt(t.evaluate(e)):kt(e)}return n=>{for(let r=0;r<t;r++){const t=e.cases[r];if("When"===t._tag&&!0===t.guard(n))return Dt(t.evaluate(n));if("Not"===t._tag&&!1===t.guard(n))return Dt(t.evaluate(n))}return kt(n)}},Lr=(e,t)=>n=>n.add({_tag:"When",guard:Ar(e),evaluate:t}),Ir=e=>t=>{const n=Or(t);return Pt(n)?"Right"===n._tag?n.right:e(n.left):t=>{const r=n(t);return"Right"===r._tag?r.right:e(r.left)}},Dr=new M;class kr{cfg;symbolTable;config;constructor(e,t,n,r={}){this.cfg=e,this.symbolTable=t,this.config={maxIterations:r.maxIterations??1e3,debug:r.debug??!1}}analyze(){this.config.debug&&console.log(`\n=== Starting Data Flow Analysis for: ${this.cfg.name||"unnamed"} ===`),this.initializeEntryBlock();const e=[this.cfg.entry],t=new Set([this.cfg.entry.id]);let n=0;for(;e.length>0&&n<this.config.maxIterations;){n++;const r=e.shift();t.delete(r.id),this.config.debug&&console.log(`\nIteration ${n}: Processing block ${r.id} (${r.label||"unlabeled"})`),this.mergePredecessors(r);const i=r.typeStateOut.clone();if(r.typeStateOut=this.transfer(r),!i.equals(r.typeStateOut)){this.config.debug&&console.log(` Block ${r.id} output changed, adding successors to worklist`);for(const n of r.successors)t.has(n.target.id)||(e.push(n.target),t.add(n.target.id))}}const r=n<this.config.maxIterations;return this.config.debug&&console.log(`\n=== Analysis Complete: ${r?"CONVERGED":"MAX ITERATIONS"} (${n} iterations) ===\n`),{converged:r,iterations:n,cfg:this.cfg}}initializeEntryBlock(){const e=new Er,t=this.symbolTable.getAllSymbols();for(const n of t)e.set(n.name,n.dataType);this.cfg.entry.typeStateIn=e}mergePredecessors(e){if(0===e.predecessors.length)return;if(1===e.predecessors.length){const t=e.predecessors[0],n=t.successors.find(t=>t.target===e);return void(e.typeStateIn=n?.narrowedState?n.narrowedState.clone():t.typeStateOut.clone())}const t=new Er;for(const n of e.predecessors){const r=n.successors.find(t=>t.target===e);let i;i=r?.narrowedState?r.narrowedState:n.typeStateOut,t.merge(i)}e.typeStateIn=t}transfer(e){let t=e.typeStateIn.clone();for(const n of e.statements)t=this.applyStatement(t,n);return this.applyEdgeNarrowing(e,t),t}applyStatement(e,t){switch(t.type){case"VariableDeclaration":return this.applyVariableDeclaration(e,t);case"AssignmentExpression":return this.applyAssignment(e,t);case"ExpressionStatement":const n=t;return n.expression?this.applyStatement(e,n.expression):e;default:return e}}applyVariableDeclaration(e,t){for(const n of t.declarations){const t=n,r=t.id.name;if(t.init){const n=this.inferExpressionType(e,t.init);e.set(r,n)}else e.set(r,C.UNKNOWN)}return e}applyAssignment(e,t){if("Identifier"===t.left.type){const n=t.left.name,r=this.inferExpressionType(e,t.right);e.set(n,r)}return e}inferExpressionType(e,t){switch(t.type){case"Literal":return this.inferLiteralType(t);case"Identifier":{const n=t.name,r=e.get(n);if(r)return r;const i=this.symbolTable.lookup(n);return i&&i.dataType&&i.dataType!==C.UNKNOWN?i.dataType:C.UNKNOWN}case"ArrayExpression":{const n=t,r=[];for(const t of n.elements)if(t){const n=this.inferExpressionType(e,t);if(L(n))for(const e of I(n))r.includes(e)||r.push(e);else"string"==typeof n&&n!==C.UNKNOWN&&(r.includes(n)||r.push(n))}return r.length>0?k(1===r.length?r[0]:O(r)):C.ARRAY}case"ObjectExpression":return C.OBJECT;case"BinaryExpression":return this.inferBinaryExpressionType(e,t);case"UnaryExpression":return this.inferUnaryExpressionType(e,t);case"CallExpression":return this.inferCallExpressionType(e,t);case"LogicalExpression":{const n=t,r=this.inferExpressionType(e,n.left),i=this.inferExpressionType(e,n.right);return"||"===n.operator?Dr.inferLogicalOrFullType(r,i):"&&"===n.operator?Dr.inferLogicalAndFullType(r,i):r}default:return C.UNKNOWN}}inferLiteralType(e){switch(e.literalType){case"string":return C.STRING;case"number":case"double":return"number"==typeof e.value&&Number.isInteger(e.value)?C.INTEGER:C.DOUBLE;case"boolean":return C.BOOLEAN;case"null":return C.NULL;case"regexp":return C.REGEX;default:return C.UNKNOWN}}inferBinaryExpressionType(e,t){const n=this.inferExpressionType(e,t.left),r=this.inferExpressionType(e,t.right);return["==","!=","===","!==","<",">","<=",">="].includes(t.operator)?C.BOOLEAN:"||"===t.operator?Dr.inferLogicalOrFullType(n,r):"&&"===t.operator?Dr.inferLogicalAndFullType(n,r):["+","-","*","/","%","**"].includes(t.operator)?[...I(n),...I(r)].includes(C.DOUBLE)?C.DOUBLE:C.INTEGER:"+"===t.operator&&[...I(n),...I(r)].includes(C.STRING)?C.STRING:C.UNKNOWN}inferUnaryExpressionType(e,t){return"!"===t.operator?C.BOOLEAN:"-"===t.operator||"+"===t.operator?this.inferExpressionType(e,t.argument):C.UNKNOWN}inferCallExpressionType(e,t){if("Identifier"===t.callee.type){const e=t.callee.name;if("require"===e&&1===t.arguments.length){const e=t.arguments[0];if(e&&"Literal"===e.type&&"string"==typeof e.value){const t=e.value;if(wn(t))return{type:C.OBJECT,moduleName:t}}}const r=this.symbolTable.lookup(e);if(r?.returnType)return r.returnType;if(r?.type===S.IMPORTED&&r.importedFrom){const t=r.importSpecifier||e,i=(n=r.importedFrom,Cr(n,kt(n))).pipe(Lr("io",()=>"open"===t||"new"===t||"from"===t?rn():null),Lr("fs",()=>"open"===t?Z(X.FS_FILE):"opendir"===t?Z(X.FS_DIR):"popen"===t?Z(X.FS_PROC):null),Ir(()=>null));if(i)return i}const i=this.getBuiltinReturnType(e);if(i)return i}var n;return C.UNKNOWN}getBuiltinReturnType(e){return{print:C.INTEGER,printf:C.INTEGER,sprintf:C.STRING,length:C.INTEGER,substr:C.STRING,split:k(C.STRING),join:C.STRING,trim:C.STRING,ltrim:C.STRING,rtrim:C.STRING,chr:C.STRING,ord:C.INTEGER,uc:C.STRING,lc:C.STRING,type:C.STRING,keys:k(C.STRING),values:C.ARRAY,push:C.INTEGER,pop:C.UNKNOWN,shift:C.UNKNOWN,unshift:C.INTEGER,iptoarr:k(C.INTEGER),arrtoip:C.STRING,int:C.INTEGER,match:k(C.STRING),replace:C.STRING,system:C.INTEGER,time:C.INTEGER,sleep:C.NULL,wildcard:C.BOOLEAN,regexp:C.REGEX,exists:C.BOOLEAN}[e]||null}applyEdgeNarrowing(e,t){for(const n of e.successors)if(n.condition){const e=this.applyTypeGuard(t,n.condition,n.isNegative||!1);n.narrowedState=e}}applyTypeGuard(e,t,n){const r=e.clone(),i=this.extractTypeGuard(t);return i&&e.get(i.variableName)?("null-check"===i.guardType?n?r.exclude(i.variableName,C.NULL):r.narrow(i.variableName,C.NULL):"type-check"===i.guardType&&i.narrowToType&&(n?r.exclude(i.variableName,i.narrowToType):r.narrow(i.variableName,i.narrowToType)),r):r}extractTypeGuard(e){if("BinaryExpression"!==e.type)return null;const t=e;if("==="===t.operator||"!=="===t.operator||"=="===t.operator||"!="===t.operator){if("Identifier"===t.left.type&&"Literal"===t.right.type){const e=t.left.name;if(null===t.right.value)return{variableName:e,guardType:"null-check"}}if("CallExpression"===t.left.type){const e=t.left;if("Identifier"===e.callee.type&&"type"===e.callee.name&&1===e.arguments.length&&"Identifier"===e.arguments[0].type&&"Literal"===t.right.type){const n=e.arguments[0].name,r=t.right.value,i=this.stringToUcodeType(r);if(i)return{variableName:n,guardType:"type-check",narrowToType:i}}}}return null}stringToUcodeType(e){return{string:C.STRING,int:C.INTEGER,double:C.DOUBLE,bool:C.BOOLEAN,array:C.ARRAY,object:C.OBJECT,function:C.FUNCTION,null:C.NULL}[e]||null}}class Pr{cfg;nodeToBlock;constructor(e,t){this.cfg=e,this.nodeToBlock=t}getTypeAtPosition(e,t){const n=this.findBlockAtOffset(t);if(n)return n.typeStateIn.get(e)}getTypeStateAtPosition(e){const t=this.findBlockAtOffset(e);if(!t)return;let n=t.typeStateIn.clone();for(const r of t.statements){if(r.start>e)break;n=this.applyStatement(n,r)}return n}getVariablesInScope(e){const t=this.getTypeStateAtPosition(e);return t?t.getAllKeys():[]}findBlockAtOffset(e){for(const t of this.cfg.blocks)for(const n of t.statements)if(n.start<=e&&e<=n.end)return t}findBlockForNode(e){return this.nodeToBlock.get(e)}getTypeStateAtBlockEntry(e){return e.typeStateIn}getTypeStateAtBlockExit(e){return e.typeStateOut}applyStatement(e,t,n){return e}getCFGInfo(){const e=this.cfg.blocks.reduce((e,t)=>e+t.successors.length,0);return{blockCount:this.cfg.blocks.length,edgeCount:e,entryBlockId:this.cfg.entry.id,exitBlockId:this.cfg.exit.id,...this.cfg.name&&{name:this.cfg.name}}}isBlockReachable(e){const t=new Set,n=[this.cfg.entry];for(;n.length>0;){const r=n.shift();if(!t.has(r.id)){if(t.add(r.id),r.id===e.id)return!0;for(const e of r.successors)n.push(e.target)}}return!1}getUnreachableBlocks(){const e=new Set,t=[this.cfg.entry];for(;t.length>0;){const n=t.shift();if(!e.has(n.id)){e.add(n.id);for(const e of n.successors)t.push(e.target)}}return this.cfg.blocks.filter(t=>!e.has(t.id))}getCFG(){return this.cfg}}function xr(e){const t=[];let n;const r=e.split("\n").map(e=>e.replace(/^\s*\*\s?/,"")).join("\n").trim(),i=r.search(/@(?:param|returns?|type(?:def)?|property)\b/);i>0?n=r.substring(0,i).trim()||void 0:-1===i&&(n=r||void 0);const o=/@param\s+\{([^}]+)\}\s+(\w+)(?:\s+-\s+(.*))?/g,s=/@param\s+(\w+)\s+(\S+)(?:\s+-\s+(.*))?/g;let a;for(;null!==(a=o.exec(r));)t.push({tag:"param",typeExpression:a[1].trim(),name:a[2],description:a[3]?.trim()});if(0===t.filter(e=>"param"===e.tag).length)for(;null!==(a=s.exec(r));)t.push({tag:"param",name:a[1],typeExpression:a[2].trim(),description:a[3]?.trim()});const c=/@returns?\s+\{([^}]+)\}(?:\s+-?\s*(.*))?/.exec(r)||/@returns?\s+(\S+)(?:\s+-?\s*(.*))?/.exec(r);c&&t.push({tag:"returns",typeExpression:c[1].trim(),description:c[2]?.trim()});const l=/@typedef\s+\{([^}]+)\}\s+(\w+)/.exec(r);l&&t.push({tag:"typedef",typeExpression:l[1].trim(),name:l[2]});const u=/@property\s+\{([^}]+)\}\s+(\w+)(?:\s+-\s+(.*))?/g;for(;null!==(a=u.exec(r));)t.push({tag:"property",typeExpression:a[1].trim(),name:a[2],description:a[3]?.trim()});return{tags:t,description:n}}function wr(e){if((e=e.trim()).endsWith("?")){const t=wr(e.slice(0,-1));return null===t?null:"string"==typeof t?O([t,C.NULL]):t}if(e.includes("|")){const t=e.split("|").map(e=>e.trim()).filter(Boolean),n=[];for(const e of t){const t=wr(e);if(null===t)return null;"string"==typeof t?n.push(t):"object"==typeof t&&t.type===C.UNION?n.push(...t.types):n.push(t.type)}return O(n)}if(e.startsWith("module:")){const t=e.substring(7);return wn(t)?{type:C.OBJECT,moduleName:t}:null}if(Mn(e))return{type:C.OBJECT,moduleName:e};const t={string:C.STRING,number:C.DOUBLE,integer:C.INTEGER,int:C.INTEGER,double:C.DOUBLE,float:C.DOUBLE,boolean:C.BOOLEAN,bool:C.BOOLEAN,array:C.ARRAY,object:C.OBJECT,function:C.FUNCTION,null:C.NULL,regex:C.REGEX,regexp:C.REGEX,unknown:C.UNKNOWN,any:C.UNKNOWN},n=e.toLowerCase();return n in t?t[n]:wn(e)?{type:C.OBJECT,moduleName:e}:null}function Mr(e){const t=e.tags.find(e=>"typedef"===e.tag);if(!t||!t.name)return null;const n=new Map;for(const t of e.tags)if("property"===t.tag&&t.name){const e=wr(t.typeExpression);null!==e&&n.set(t.name,{type:e,description:t.description})}return{name:t.name,baseType:t.typeExpression,properties:n}}function Fr(e){const t=/^import\(\s*['"]([^'"]+)['"]\s*\)(?:\.(\w+))?$/.exec(e.trim());return t?{modulePath:t[1],propertyName:t[2]}:null}class Ur extends Hn{symbolTable;typeChecker;diagnostics=[];textDocument;options;functionScopes=[];loopScopes=[];switchScopes=[];commonjsImports=new Map;currentFunctionNode=null;functionReturnTypes=new Map;functionReturnPropertyTypes=new Map;processingFunctionCallCallee=!1;cfg=null;cfgQueryEngine=null;moduleFunctionProviders=Object.fromEntries(Object.entries(Pn).map(([e,t])=>[e,()=>t.getFunctionNames()]));disabledLines=new Set;disabledRanges=[];linesWithSuppressedDiagnostics=new Set;assignmentLeftDepth=0;fileResolver;currentASTRoot=null;thisPropertyStack=[];truthinessDepth=0;callbackElementType=null;typedefRegistry=new Map;strictMode=!1;constructor(e,t={}){super(),this.textDocument=e,this.symbolTable=new w,this.typeChecker=new Vn(this.symbolTable),this.fileResolver=new Rr(t.workspaceRoot),this.options={enableScopeAnalysis:!0,enableTypeChecking:!0,enableControlFlowAnalysis:!0,enableUnusedVariableDetection:!0,enableShadowingWarnings:!0,...t}}analyze(e){this.diagnostics=[],this.typeChecker.resetErrors(),this.functionScopes=[],this.loopScopes=[],this.switchScopes=[],this.currentFunctionNode=null,this.functionReturnTypes.clear(),this.functionReturnPropertyTypes.clear(),this.disabledLines.clear(),this.disabledRanges=[],this.linesWithSuppressedDiagnostics.clear(),"Program"===e.type&&(this.currentASTRoot=e,this.typeChecker.setAST(this.currentASTRoot),this.strictMode=this.detectStrictMode(this.currentASTRoot));try{if(this.parseDisableComments(),this.scanTypedefs(),this.visit(e),this.options.enableControlFlowAnalysis&&this.currentASTRoot)try{const e=new br("top-level");this.cfg=e.build(this.currentASTRoot);const t=new kr(this.cfg,this.symbolTable,this.textDocument.getText()).analyze();this.cfgQueryEngine=new Pr(this.cfg,e.getNodeToBlockMap()),this.typeChecker&&this.typeChecker.setCFGQueryEngine(this.cfgQueryEngine),this.filterUndefinedFunctionErrorsWithCFG(),this.detectUnreachableCode(),t.converged||console.warn(`CFG analysis did not converge after ${t.iterations} iterations`)}catch(e){console.error("CFG analysis error:",e),this.cfg=null,this.cfgQueryEngine=null,this.typeChecker&&this.typeChecker.setCFGQueryEngine(null)}this.options.enableUnusedVariableDetection&&this.checkUnusedVariables(),this.checkUnnecessaryDisableComments()}catch(n){this.addDiagnostic(`Semantic analysis error: ${n instanceof Error?n.message:"Unknown error"}`,e.start,e.end,t.DiagnosticSeverity.Error)}this.diagnostics=this.filterDiagnosticsWithFlowSensitiveAnalysis(this.diagnostics);const n={diagnostics:this.diagnostics,symbolTable:this.symbolTable,typeResults:new Map,typeChecker:this.typeChecker};return this.currentASTRoot&&(n.ast=this.currentASTRoot),this.cfg&&(n.cfg=this.cfg),this.cfgQueryEngine&&(n.cfgQueryEngine=this.cfgQueryEngine),n}visitProgram(e){this.hoistFunctionDeclarations(e),super.visitProgram(e)}hoistFunctionDeclarations(e){if(this.options.enableScopeAnalysis)for(const t of e.body)if("FunctionDeclaration"===t.type){const e=t;if(e.id&&e.id.name){const t={...e.id,start:0};this.symbolTable.declare(e.id.name,S.FUNCTION,C.FUNCTION,t)}}}visitVariableDeclaration(e){if(this.options.enableScopeAnalysis){if(e.leadingJsDoc&&1===e.declarations.length){const t=e.declarations[0]?.init;t&&(("FunctionExpression"!==t.type||t.leadingJsDoc)&&("ArrowFunctionExpression"!==t.type||t.leadingJsDoc)||(t.leadingJsDoc=e.leadingJsDoc))}for(const t of e.declarations)this.visitVariableDeclarator(t,e.kind)}else super.visitVariableDeclaration(e)}visitVariableDeclarator(e,n="let"){if(this.options.enableScopeAnalysis){const n=e.id.name;let r=S.VARIABLE,i=C.UNKNOWN;if(e.init)switch(e.init.type){case"ArrayExpression":i=C.ARRAY;break;case"ObjectExpression":i=C.OBJECT;break;case"Literal":const t=e.init;"regexp"===t.literalType?i=C.REGEX:"string"==typeof t.value?i=C.STRING:"number"==typeof t.value?i=Number.isInteger(t.value)?C.INTEGER:C.DOUBLE:"boolean"==typeof t.value?i=C.BOOLEAN:null===t.value&&(i=C.NULL)}if(e.init&&"CallExpression"===e.init.type){const t=e.init;if(t.callee&&"Identifier"===t.callee.type&&"require"===t.callee.name&&t.arguments&&1===t.arguments.length){const e=t.arguments[0];if("Literal"===e.type&&"string"==typeof e.value){const t=e.value;if(wn(t))r=S.MODULE,i={type:C.OBJECT,moduleName:t};else if(t.startsWith("./")||t.startsWith("../")||t.startsWith("/")){const e=this.fileResolver.resolveImportPath(t,this.textDocument.uri);e&&(r=S.IMPORTED,i={type:C.OBJECT,isDefaultImport:!0},this.commonjsImports.set(n,{importedFrom:this.normalizeImportedFrom(t,e),importSpecifier:"default"}))}else if(this.isDotNotationModule(t)){const e=this.convertDotNotationToPath(t),o=this.fileResolver.resolveImportPath(e,this.textDocument.uri);o&&(r=S.IMPORTED,i={type:C.OBJECT,isDefaultImport:!0},this.commonjsImports.set(n,{importedFrom:this.normalizeImportedFrom(e,o),importSpecifier:"default"}))}}}}if(e.init&&"BinaryExpression"===e.init.type){const t=e.init;if("||"===t.operator||"??"===t.operator){const e=t.right;if(e&&"CallExpression"===e.type){const t=e;if("Identifier"===t.callee?.type&&"require"===t.callee.name&&1===t.arguments?.length){const e=t.arguments[0];if(e&&"Literal"===e.type&&"string"==typeof e.value){const t=e.value;wn(t)&&(r=S.MODULE,i={type:C.OBJECT,moduleName:t})}}}}}if(e.init&&"MemberExpression"===e.init.type){const t=e.init;if(t.object&&"Identifier"===t.object.type){const e=t.object.name,o=this.symbolTable.lookup(e);o&&o.type===S.IMPORTED&&o.dataType&&"object"==typeof o.dataType&&"isDefaultImport"in o.dataType&&o.dataType.isDefaultImport&&t.property&&"Identifier"===t.property.type&&"default"===t.property.name&&(r=S.IMPORTED,i={type:C.OBJECT,isDefaultImport:!0},this.commonjsImports.set(n,{importedFrom:o.importedFrom,importSpecifier:"default"}))}}const o=this.symbolTable.lookupInCurrentScope(n);if(o&&o.type!==S.BUILTIN)this.addDiagnosticErrorCode(K.VARIABLE_REDECLARATION,`Variable '${n}' is already declared in this scope`,e.id.start,e.id.end,t.DiagnosticSeverity.Error);else{const o=this.symbolTable.lookup(n);o&&o.type===S.BUILTIN?this.addDiagnosticErrorCode(K.SHADOWING_BUILTIN,`Variable '${n}' shadows builtin function '${n}()'`,e.id.start,e.id.end,t.DiagnosticSeverity.Warning):o&&this.options.enableShadowingWarnings&&this.addDiagnosticErrorCode(K.VARIABLE_SHADOWING,`Variable '${n}' shadows ${o.type} '${n}' from outer scope`,e.id.start,e.id.end,t.DiagnosticSeverity.Warning),this.symbolTable.declare(n,r,i,e.id,e.init||void 0);const s=this.symbolTable.lookup(n);s&&e.init&&this.isLiteralType(i,e.init)&&(s.initialLiteralType=i),s&&this.setDeclarationTypeIfUnset(s,i);const a=this.commonjsImports.get(n);if(a){const e=this.symbolTable.lookup(n);e&&(e.importedFrom=a.importedFrom,e.importSpecifier=a.importSpecifier),this.commonjsImports.delete(n)}}if(e.init){if(this.visit(e.init),this.options.enableTypeChecking&&this.processInitializerTypeInference(e,n),"ArrayExpression"===e.init.type){const t=this.symbolTable.lookup(n);if(t){this.typeChecker.checkNode(e.init);const n=e.init._fullType;n&&D(n)&&(t.dataType=n,t.initialLiteralType=n)}}if("CallExpression"===e.init.type||"MemberExpression"===e.init.type){const t=this.symbolTable.lookup(n);if(t){this.typeChecker.checkNode(e.init);const n=e.init._fullType;n&&"object"==typeof n&&(t.dataType=n)}}if("Identifier"===e.init.type){const t=this.symbolTable.lookup(n);if(t&&t.dataType===C.UNKNOWN){const n=e.init.name,r=this.typeChecker.getNarrowedTypeAtPosition(n,e.init.start);if(r&&r!==C.UNKNOWN){t.dataType=r;const i=this.typeChecker.getEqualityNarrowSymbolAtPosition(n,e.init.start);i?.importedFrom&&(t.importedFrom=i.importedFrom,i.importSpecifier&&(t.importSpecifier=i.importSpecifier),t.type=S.IMPORTED)}}}if("ObjectExpression"===e.init.type){const t=this.symbolTable.lookup(n);if(t){const n=this.inferObjectLiteralPropertyTypes(e.init);n&&(t.propertyTypes=n)}}}}else super.visitVariableDeclarator(e)}visitImportDeclaration(e){if(this.options.enableScopeAnalysis){const t=e.source.value;for(const n of e.specifiers)this.validateAndProcessImportSpecifier(n,t,e.source)}}visitImportSpecifier(e){}visitProperty(e){e.computed&&this.visit(e.key),this.visit(e.value)}processImportSpecifier(e,n,r=!1,i){let o,s;"ImportSpecifier"===e.type?(o=e.local.name,s=e.imported.name):"ImportDefaultSpecifier"===e.type?(o=e.local.name,s="default"):(o=e.local.name,s="*");let a=C.UNKNOWN;if("ImportDefaultSpecifier"===e.type&&(a=r?C.FUNCTION:{type:C.OBJECT,isDefaultImport:!0}),"ImportNamespaceSpecifier"===e.type&&(a={type:C.OBJECT,moduleName:n}),"nl80211"===n&&"const"===s?a={type:C.OBJECT,moduleName:"nl80211-const"}:"nl80211"===n&&Array.from(Rt.keys()).includes(s)&&(a=C.FUNCTION),"rtnl"===n&&"const"===s&&(a={type:C.OBJECT,moduleName:"rtnl-const"}),"rtnl"===n&&Pn.rtnl.getFunctionNames().includes(s)&&(a=C.FUNCTION),"fs"===n&&Pn.fs.getFunctionNames().includes(s)&&(a=C.FUNCTION),wn(n)&&"ImportSpecifier"===e.type&&("nl80211"!==n&&"rtnl"!==n||"const"!==s)){const r=function(e,t){const n=Pn[e];return n.isValidImport(t)?Dt(!0):kt(`'${t}' is not exported by the ${e} module. Available exports: ${n.getValidImports().join(", ")}`)}(n,s);if(xt(r))return void this.addDiagnosticErrorCode(K.EXPORT_NOT_FOUND,r.left,e.imported.start,e.imported.end,t.DiagnosticSeverity.Error)}if(this.symbolTable.declare(o,S.IMPORTED,a,e.local)){const t=this.symbolTable.lookup(o);if(t){let o=n;this.isDotNotationModule(n)&&(o=this.convertDotNotationToPath(n));const a=i||this.fileResolver.resolveImportPath(o,this.textDocument.uri);if(t.importedFrom=this.normalizeImportedFrom(n,a),t.importSpecifier=s,"ImportDefaultSpecifier"===e.type&&!r&&a&&a.startsWith("file://")){const e=this.fileResolver.getDefaultExportPropertyTypes(a);if(e&&(t.propertyTypes=e.propertyTypes,e.nestedPropertyTypes&&(t.nestedPropertyTypes=e.nestedPropertyTypes),e.functionReturnTypes)){const n=new Map;for(const[t,r]of e.functionReturnTypes)n.set(t,"string"==typeof r?r:"unknown");n.size>0&&(t.propertyFunctionReturnTypes=n)}}if("ImportDefaultSpecifier"===e.type&&r&&a&&a.startsWith("file://")){const e=this.fileResolver.getDefaultExportFunctionReturnInfo(a);e&&(t.returnType=e.returnType,t.returnPropertyTypes=e.returnPropertyTypes,e.propertyFunctionReturnTypes&&(t.propertyFunctionReturnTypes=e.propertyFunctionReturnTypes))}}}else this.addDiagnosticErrorCode(K.INVALID_IMPORT,`Imported symbol '${o}' is already declared in current scope`,e.local.start,e.local.end,t.DiagnosticSeverity.Error)}validateAndProcessImportSpecifier(e,n,r){if(wn(n))return"ImportDefaultSpecifier"===e.type?void this.addDiagnosticErrorCode(K.EXPORT_NOT_FOUND,`Builtin module '${n}' does not have a default export. Use: import * as ${e.local.name} from '${n}'; or import { ... } from '${n}';`,e.local.start,e.local.start+e.local.name.length,t.DiagnosticSeverity.Error):void this.processImportSpecifier(e,n);let i=n;this.isDotNotationModule(n)&&(i=this.convertDotNotationToPath(n));const o=this.fileResolver.resolveImportPath(i,this.textDocument.uri);if(o){const r=this.fileResolver.getModuleExports(o);if(r&&"ImportSpecifier"===e.type){const i=e.imported.name;if(!r.some(e=>"named"===e.type&&e.name===i))return void this.addDiagnosticErrorCode(K.EXPORT_NOT_FOUND,`Module ${n} does not export '${i}'`,e.imported.start,e.imported.end,t.DiagnosticSeverity.Error)}else if(r&&"ImportDefaultSpecifier"===e.type&&!r.some(e=>"default"===e.type))return void this.addDiagnosticErrorCode(K.EXPORT_NOT_FOUND,`Module ${n} does not have a default export`,e.local.start,e.local.end,t.DiagnosticSeverity.Error);let i=!1;if("ImportDefaultSpecifier"===e.type&&r){const e=r.find(e=>"default"===e.type);e&&(i=e.isFunction)}this.processImportSpecifier(e,n,i,o)}else this.addDiagnosticErrorCode(K.MODULE_NOT_FOUND,`Cannot find module '${n}'`,r.start,r.end,t.DiagnosticSeverity.Warning),this.processImportSpecifier(e,n)}normalizeImportedFrom(e,t){return t&&t.startsWith("builtin://")?e:t||e}applyJsDocToParams(e,n){if(!e){for(const e of n)this.symbolTable.declare(e.name,S.PARAMETER,C.UNKNOWN,e);return}const r=xr(e.value).tags.filter(e=>"param"===e.tag),i=new Map;for(const n of r){if(!n.name)continue;const r=Fr(n.typeExpression);if(r){const e=this.resolveImportTypeExpression(r.modulePath,r.propertyName);if(e){i.set(n.name,{...e,description:n.description});continue}}const o=wr(n.typeExpression);if(null===o){const r=this.typedefRegistry.get(n.typeExpression);if(r){const e=new Map;for(const[t,n]of r.properties)e.set(t,n.type);i.set(n.name,{type:C.OBJECT,description:n.description,propertyTypes:e.size>0?e:void 0});continue}this.addDiagnosticErrorCode(K.JSDOC_UNKNOWN_TYPE,`Unknown type '${n.typeExpression}' in @param annotation`,e.start,e.end-1,t.DiagnosticSeverity.Warning);continue}i.set(n.name,{type:o,description:n.description})}const o=new Set(n.map(e=>e.name));for(const i of r)i.name&&!o.has(i.name)&&this.addDiagnosticErrorCode(K.JSDOC_PARAM_MISMATCH,`@param '${i.name}' does not match any parameter. Parameters: ${n.map(e=>e.name).join(", ")}`,e.start,e.end-1,t.DiagnosticSeverity.Warning);for(const e of n){const t=i.get(e.name);if(t){this.symbolTable.declare(e.name,S.PARAMETER,t.type,e);const n=this.symbolTable.lookup(e.name);n&&(t.description&&(n.jsdocDescription=t.description),t.propertyTypes&&(n.propertyTypes=t.propertyTypes),t.nestedPropertyTypes&&(n.nestedPropertyTypes=t.nestedPropertyTypes),t.propertyFunctionReturnTypes&&(n.propertyFunctionReturnTypes=t.propertyFunctionReturnTypes))}else this.symbolTable.declare(e.name,S.PARAMETER,C.UNKNOWN,e)}}resolveImportTypeExpression(e,t){if(wn(e)){if(t){const n=`${e}.${t}`;return Mn(n)?{type:{type:C.OBJECT,moduleName:n}}:null}return{type:{type:C.OBJECT,moduleName:e}}}const n=this.fileResolver.resolveImportPath(e,this.textDocument.uri);if(!n||!n.startsWith("file://"))return null;if(t){const e=this.fileResolver.getModuleExports(n),r=e?.find(e=>"named"===e.type&&e.name===t);if(r){const e=this.fileResolver.getNamedExportTypeInfo(n,t);if(e)return e}}const r=this.fileResolver.getModuleExports(n),i=r?.find(e=>"default"===e.type);if(i?.isFunction){const e=this.fileResolver.getDefaultExportFunctionReturnInfo(n);if(!e)return null;if(t){const n=e.returnPropertyTypes?.get(t);return n?{type:n}:null}return{type:e.returnType??C.OBJECT,propertyTypes:e.returnPropertyTypes,propertyFunctionReturnTypes:e.propertyFunctionReturnTypes}}const o=this.fileResolver.getDefaultExportPropertyTypes(n);if(!o)return null;if(t){const e=o.propertyTypes?.get(t);if(!e)return null;const n=o.nestedPropertyTypes?.get(t),r={type:e};return n&&(r.propertyTypes=n),r}return{type:{type:C.OBJECT,isDefaultImport:!0},propertyTypes:o.propertyTypes,nestedPropertyTypes:o.nestedPropertyTypes}}visitFunctionDeclaration(e){if(this.options.enableScopeAnalysis){const n=e.id.name,r=this.symbolTable.lookup(n);r&&r.type===S.FUNCTION?(r.node=e.id,r.declaredAt=e.id.start):this.symbolTable.declare(n,S.FUNCTION,C.FUNCTION,e.id)||this.addDiagnosticErrorCode(K.FUNCTION_REDECLARATION,`Function '${n}' is already declared in this scope`,e.id.start,e.id.end,t.DiagnosticSeverity.Error);const i=this.currentFunctionNode;if(this.currentFunctionNode=e,this.functionReturnTypes.set(e,[]),this.functionReturnPropertyTypes.set(e,[]),this.symbolTable.enterScope(),this.functionScopes.push(this.symbolTable.getCurrentScope()),this.applyJsDocToParams(e.leadingJsDoc,e.params),this.strictMode&&!e.leadingJsDoc&&e.params.length>0){const r=e.params.filter(e=>{const t=this.symbolTable.lookup(e.name);return!t||t.dataType===C.UNKNOWN});if(r.length>0){const i=r.map(e=>e.name).join(", ");this.addDiagnosticErrorCode(K.JSDOC_MISSING_ANNOTATIONS,`Function '${n}' has ${r.length} parameter${r.length>1?"s":""} with unknown type${r.length>1?"s":""}: ${i}. Add /** @param */ annotations.`,e.id.start,e.id.end,t.DiagnosticSeverity.Information)}}if(e.restParam){this.symbolTable.declare(e.restParam.name,S.PARAMETER,C.ARRAY,e.restParam);const t=this.symbolTable.lookup(e.restParam.name);t&&(t.isRestParam=!0)}this.visit(e.body);const o=(this.functionReturnTypes.get(e)||[]).map(e=>e.type),s=this.typeChecker.getCommonReturnType(o),a=this.symbolTable.lookup(n);if(a){a.dataType=C.FUNCTION,a.returnType=s;const t=this.functionReturnPropertyTypes.get(e)||[];if(t.length>0){const e=new Map(t[0]);for(let n=1;n<t.length;n++){const r=t[n];for(const t of e.keys())r.has(t)||e.delete(t)}e.size>0&&(a.returnPropertyTypes=e)}}this.symbolTable.exitScope(e.end),this.functionScopes.pop(),this.currentFunctionNode=i}else super.visitFunctionDeclaration(e)}visitObjectExpression(e){const t=this.inferObjectLiteralPropertyTypes(e);t&&this.thisPropertyStack.push(t),super.visitObjectExpression(e),t&&this.thisPropertyStack.pop()}visitFunctionExpression(e){if(this.options.enableScopeAnalysis){const t=this.currentFunctionNode;if(this.currentFunctionNode=e,this.functionReturnTypes.set(e,[]),this.functionReturnPropertyTypes.set(e,[]),this.symbolTable.enterScope(),this.functionScopes.push(this.symbolTable.getCurrentScope()),e.id&&this.symbolTable.declare(e.id.name,S.FUNCTION,C.UNKNOWN,e.id),this.applyJsDocToParams(e.leadingJsDoc,e.params),e.restParam){this.symbolTable.declare(e.restParam.name,S.PARAMETER,C.ARRAY,e.restParam);const t=this.symbolTable.lookup(e.restParam.name);t&&(t.isRestParam=!0)}if(this.thisPropertyStack.length>0){const t=this.thisPropertyStack[this.thisPropertyStack.length-1];this.symbolTable.declare("this",S.VARIABLE,C.OBJECT,e);const n=this.symbolTable.lookup("this");n&&(n.propertyTypes=new Map(t))}this.visit(e.body),this.symbolTable.exitScope(e.end),this.functionScopes.pop(),this.currentFunctionNode=t}else this.visit(e.body)}visitArrowFunctionExpression(e){if(this.options.enableScopeAnalysis){const t=this.currentFunctionNode;if(this.currentFunctionNode=e,this.functionReturnTypes.set(e,[]),this.functionReturnPropertyTypes.set(e,[]),this.symbolTable.enterScope(),this.functionScopes.push(this.symbolTable.getCurrentScope()),e.leadingJsDoc)this.applyJsDocToParams(e.leadingJsDoc,e.params);else for(let t=0;t<e.params.length;t++){const n=e.params[t],r=0===t&&this.callbackElementType?this.callbackElementType:C.UNKNOWN;this.symbolTable.declare(n.name,S.PARAMETER,r,n)}if(e.restParam){this.symbolTable.declare(e.restParam.name,S.PARAMETER,C.ARRAY,e.restParam);const t=this.symbolTable.lookup(e.restParam.name);t&&(t.isRestParam=!0)}if("BlockStatement"===e.body.type){const t=e.body.body;for(const e of t)this.visit(e)}else this.visit(e.body);this.symbolTable.exitScope(e.end),this.functionScopes.pop(),this.currentFunctionNode=t}else super.visitArrowFunctionExpression(e)}visitBlockStatement(e){if(this.options.enableScopeAnalysis){this.symbolTable.enterScope();for(const t of e.body)this.visit(t);this.symbolTable.exitScope(e.end)}else super.visitBlockStatement(e)}visitTryStatement(e){this.options.enableScopeAnalysis?(this.visit(e.block),e.handler&&this.visit(e.handler)):super.visit(e)}visitCatchClause(e){if(this.options.enableScopeAnalysis){if(this.symbolTable.enterScope(),e.param){const n=Y();if(this.symbolTable.declare(e.param.name,S.PARAMETER,n,e.param)){const t=this.symbolTable.lookup(e.param.name);t&&(t.propertyTypes=new Map([["message",C.STRING],["type",C.STRING],["stacktrace",C.ARRAY]]))}else this.addDiagnosticErrorCode(K.PARAMETER_REDECLARATION,`Parameter '${e.param.name}' is already declared in this scope`,e.param.start,e.param.end,t.DiagnosticSeverity.Error)}this.visit(e.body),this.symbolTable.exitScope(e.end)}else super.visit(e)}visitIdentifier(e){if(this.options.enableScopeAnalysis){if(!e.name||"string"!=typeof e.name||""===e.name.trim())return;if(this.symbolTable.lookup(e.name))this.symbolTable.markUsed(e.name,e.start);else{const n=v.has(e.name),r=this.symbolTable.lookup("global"),i=r?.propertyTypes?.has(e.name);n||i||this.processingFunctionCallCallee||this.addDiagnosticErrorCode(K.UNDEFINED_VARIABLE,`Undefined variable: ${e.name}`,e.start,e.end,t.DiagnosticSeverity.Error)}}}visitMemberExpression(e){if(this.options.enableScopeAnalysis){if(this.visit(e.object),!e.computed&&"Identifier"===e.object.type){const t=e.object.name;this.symbolTable.markUsed(t,e.object.start)}e.computed&&this.visit(e.property)}else super.visitMemberExpression(e);if(this.options.enableTypeChecking){this.assignmentLeftDepth>0?this.typeChecker.withAssignmentTarget(()=>this.typeChecker.checkNode(e)):this.typeChecker.checkNode(e);const n=this.typeChecker.getResult();for(const e of n.errors)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Error,e.code,e.data);for(const e of n.warnings)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Warning,e.code,e.data)}this.validateModuleMember(e)}validateModuleMember(e){if(e.computed||"Identifier"!==e.property.type)return;if("Identifier"!==e.object.type)return;const n=e.object.name,r=e.property.name,i=this.symbolTable.lookup(n);if(!i)return void(this.isKnownModuleName(n)&&this.addDiagnostic(`Cannot use '${n}' module without importing it first. Add: import { ${r} } from '${n}'; or import * as ${n} from '${n}';`,e.object.start,e.object.end,t.DiagnosticSeverity.Error));if(!this.processingFunctionCallCallee)return;const o=this.getModuleNameFromSymbol(i);if(!o)return;if("fs"===o)return void(this.isValidFsModuleMethod(r)||this.addDiagnosticErrorCode(K.INVALID_IMPORT,`Method '${r}' is not available on the fs module. Did you mean to call this on a file handle? Use fs.open() first.`,e.property.start,e.property.end,t.DiagnosticSeverity.Error));const s=this.moduleFunctionProviders[o];if(!s)return;const a=s();if(a.includes(r))return;const c=a.join(", ");this.addDiagnosticErrorCode(K.INVALID_IMPORT,`Method '${r}' is not available on the ${o} module. Available functions: ${c}`,e.property.start,e.property.end,t.DiagnosticSeverity.Error)}getStaticPropertyName(e){if("Identifier"===e.type)return e.name;if("Literal"===e.type){const t=e;return void 0===t.value||null===t.value?null:String(t.value)}return null}getModuleNameFromSymbol(e){if(e.type!==S.MODULE&&e.type!==S.IMPORTED)return null;let t;if(e.importedFrom&&"string"==typeof e.importedFrom&&(t=e.importedFrom),!t&&"object"==typeof e.dataType&&null!==e.dataType){const n=e.dataType;"string"==typeof n.moduleName&&(t=n.moduleName)}if(!t)return null;const n=t.replace(/^builtin:\/\//,"").split(/[.-]/)[0];return"fs"===n||"rtnl"===n||void 0!==n&&Object.prototype.hasOwnProperty.call(this.moduleFunctionProviders,n)?n:null}isValidFsModuleMethod(e){return se.isFsModuleFunction(e)||re.has(e)||"stdin"===e||"stdout"===e||"stderr"===e}inferImportedFsFunctionReturnType(e){if("CallExpression"===e.type){const t=e;if(t.callee&&"Identifier"===t.callee.type){const e=t.callee.name,n=this.symbolTable.lookup(e);if(n&&n.type===S.IMPORTED&&"fs"===n.importedFrom){const t=se.getFunction(e);if(t)return this.parseReturnTypeString(t.returnType)}}}return null}inferImportedRtnlFunctionReturnType(e){if("CallExpression"===e.type){const n=e;if(n.callee&&"Identifier"===n.callee.type){const e=n.callee.name,r=this.symbolTable.lookup(e);if(r&&r.type===S.IMPORTED&&"rtnl"===r.importedFrom){const n=(t=e,ft.get(t));if(n)return this.parseReturnTypeString(n.returnType)}}}var t;return null}parseReturnTypeString(e){if(e.includes(" | ")){const t=e.split(" | ").map(e=>e.trim()),n=[];for(const e of t)switch(e){case"boolean":n.push(C.BOOLEAN);break;case"string":n.push(C.STRING);break;case"number":case"integer":n.push(C.INTEGER);break;case"double":n.push(C.DOUBLE);break;case"object":n.push(C.OBJECT);break;case"array":case"string[]":case"array[]":n.push(C.ARRAY);break;case"null":n.push(C.NULL);break;case"function":n.push(C.FUNCTION);break;default:Mn(e)?n.push(e):n.push(C.UNKNOWN)}return O(n)}switch(e){case"boolean":return C.BOOLEAN;case"string":return C.STRING;case"number":case"integer":return C.INTEGER;case"double":return C.DOUBLE;case"object":return C.OBJECT;case"array":return C.ARRAY;case"null":return C.NULL;case"function":return C.FUNCTION;default:return Mn(e)?{moduleName:e}:C.UNKNOWN}}isKnownModuleName(e){return new Set(["fs","debug","log","math","digest","nl80211","resolv","socket","struct","ubus","uci","uloop","zlib","rtnl"]).has(e)}visitCallExpression(e){if(this.options.enableScopeAnalysis&&"Identifier"===e.callee.type){const t=e.callee.name;this.symbolTable.markUsed(t,e.callee.start)}if(this.options.enableTypeChecking){this.typeChecker.setTruthinessDepth(this.truthinessDepth),this.typeChecker.checkNode(e),this.typeChecker.setTruthinessDepth(0);const n=this.typeChecker.getResult();for(const e of n.errors)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Error,e.code,e.data);for(const e of n.warnings)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Warning,e.code,e.data)}this.processingFunctionCallCallee=!0,this.visit(e.callee),this.processingFunctionCallCallee=!1;const n=this.callbackElementType;if("Identifier"===e.callee.type&&e.arguments.length>=2){const t=e.callee.name;if("filter"===t||"map"===t||"sort"===t){const t=e.arguments[0],n=this.resolveNodeFullType(t);n&&D(n)&&(this.callbackElementType=P(n))}}for(const t of e.arguments)this.visit(t);this.callbackElementType=n}visitSpreadElement(e){this.visit(e.argument)}visitTemplateLiteral(e){for(const t of e.expressions)this.visit(t)}visitAssignmentExpression(e){if(this.assignmentLeftDepth++,this.visit(e.left),this.assignmentLeftDepth--,this.visit(e.right),this.options.enableTypeChecking){if("MemberExpression"===e.left.type){const t=e.left;if(!t.computed&&"Identifier"===t.object.type){const n=t.object.name,r=this.getStaticPropertyName(t.property);if(r){const t=this.symbolTable.lookup(n);if(t&&("global"===n||t.type!==S.MODULE&&t.type!==S.IMPORTED)){const n=this.inferAssignmentDataType(e.right);t.propertyTypes||(t.propertyTypes=new Map),t.propertyTypes.set(r,n)}}}}if("Identifier"===e.left.type){const t=e.left.name;if(!this.symbolTable.lookup(t)){const n=this.inferFsType(e.right),r=this.inferNl80211Type(e.right),i=this.inferUloopType(e.right),o=this.inferIoType(e.right),s=this.inferImportedRtnlFunctionReturnType(e.right);let a=null;n?a=Z(n):r?a=At(r):i?a=Dn(i):o?a=rn():s&&(a=s),a&&(this.symbolTable.declare(t,S.VARIABLE,a,e.left),n&&this.symbolTable.forceGlobalDeclaration(t,S.VARIABLE,a),i&&this.symbolTable.forceGlobalDeclaration(t,S.VARIABLE,a),o&&this.symbolTable.forceGlobalDeclaration(t,S.VARIABLE,a))}}this.typeChecker.withAssignmentTarget(()=>this.typeChecker.checkNode(e.left)),this.typeChecker.checkNode(e.right);const n=this.typeChecker.getResult();for(const e of n.errors)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Error,e.code,e.data);for(const e of n.warnings)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Warning,e.code,e.data);if("Identifier"===e.left.type){const t=e.left.name;let n=this.symbolTable.lookup(t);const r=this.inferFsType(e.right),i=this.inferNl80211Type(e.right),o=this.inferUloopType(e.right),s=this.inferIoType(e.right),a=this.inferImportedRtnlFunctionReturnType(e.right),c="CallExpression"===e.right.type&&"Identifier"===e.right.callee.type&&"require"===e.right.callee.name;if(s&&n){const e=rn();n.dataType=e,this.symbolTable.updateSymbolType(t,e),this.symbolTable.forceGlobalDeclaration(t,S.VARIABLE,e)}if(!(r||i||o||s||a||c)){const r=this.inferMethodReturnType(e.right),i=this.inferFunctionCallReturnType(e.right);let o;if(r)o=r;else if(i)o=i;else{const t=this.typeChecker.checkNode(e.right);o=e.right._fullType||t}if(n&&n.type===S.VARIABLE?void 0!==n.initialLiteralType?(n.currentType=o,n.currentTypeEffectiveFrom=e.end):(n.currentType=void 0,n.currentTypeEffectiveFrom=void 0,n.dataType=o,this.symbolTable.updateSymbolType(t,o)):n?n.type===S.PARAMETER||n&&void 0!==n.initialLiteralType?(n.currentType=o,n.currentTypeEffectiveFrom=e.end):(n.currentType=void 0,n.currentTypeEffectiveFrom=void 0,this.symbolTable.updateSymbolType(t,o)):this.symbolTable.declare(t,S.VARIABLE,o,e.left),"ObjectExpression"===e.right.type&&n){const t=this.inferObjectLiteralPropertyTypes(e.right);t&&(n.propertyTypes=t)}if(i&&n&&"CallExpression"===e.right.type){const t=e.right;if("Identifier"===t.callee.type){const e=this.symbolTable.lookup(t.callee.name);e?.returnPropertyTypes&&(n.propertyTypes=new Map(e.returnPropertyTypes)),e?.propertyFunctionReturnTypes&&(n.propertyFunctionReturnTypes=new Map(e.propertyFunctionReturnTypes))}}}}}}visitUnaryExpression(e){if("!"===e.operator&&this.truthinessDepth++,super.visitUnaryExpression(e),"!"===e.operator&&this.truthinessDepth--,this.options.enableTypeChecking){this.typeChecker.setTruthinessDepth(this.truthinessDepth),this.typeChecker.checkNode(e),this.typeChecker.setTruthinessDepth(0);const n=this.typeChecker.getResult();for(const e of n.errors)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Error,e.code,e.data);for(const e of n.warnings)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Warning,e.code,e.data)}}visitConditionalExpression(e){this.truthinessDepth++,this.visit(e.test),this.truthinessDepth--,this.visit(e.consequent),this.visit(e.alternate)}visitBinaryExpression(e){const n=">"===e.operator||">="===e.operator||"<"===e.operator||"<="===e.operator||"=="===e.operator||"!="===e.operator||"==="===e.operator||"!=="===e.operator;if(n&&this.truthinessDepth++,super.visitBinaryExpression(e),n&&this.truthinessDepth--,this.options.enableTypeChecking){const r=n?this.truthinessDepth+1:this.truthinessDepth;this.typeChecker.setTruthinessDepth(r),this.typeChecker.checkNode(e),this.typeChecker.setTruthinessDepth(0);const i=this.typeChecker.getResult();for(const e of i.errors)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Error,e.code,e.data);for(const e of i.warnings)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Warning,e.code,e.data)}}visitReturnStatement(e){if(super.visitReturnStatement(e),this.options.enableControlFlowAnalysis&&this.currentFunctionNode){const t=e.argument?this.typeChecker.checkNode(e.argument):C.NULL;if(this.functionReturnTypes.get(this.currentFunctionNode)?.push({node:e,type:t}),"ObjectExpression"===e.argument?.type){const t=this.inferObjectLiteralPropertyTypes(e.argument);t&&this.functionReturnPropertyTypes.get(this.currentFunctionNode)?.push(t)}}}visitBreakStatement(e){this.options.enableControlFlowAnalysis&&0===this.loopScopes.length&&0===this.switchScopes.length&&this.addDiagnosticErrorCode(K.SYNTAX_ERROR,"Break statement outside loop or switch",e.start,e.end,t.DiagnosticSeverity.Error),super.visitBreakStatement(e)}visitContinueStatement(e){this.options.enableControlFlowAnalysis&&0===this.loopScopes.length&&this.addDiagnosticErrorCode(K.SYNTAX_ERROR,"Continue statement outside loop",e.start,e.end,t.DiagnosticSeverity.Error),super.visitContinueStatement(e)}visitIfStatement(e){this.truthinessDepth++,this.visit(e.test),this.truthinessDepth--;let n=0;if(this.options.enableTypeChecking&&"BinaryExpression"===e.test?.type){const t=e.test;if("Identifier"===t.left.type&&"Literal"===t.right.type){const t=this.typeChecker.analyzeIfGuards(e);for(const r of t)e.consequent&&(this.typeChecker.pushGuardContextPublic(r.variableName,r.positiveNarrowing,e.consequent.start,e.consequent.end),n++)}}e.consequent&&this.visit(e.consequent);for(let e=0;e<n;e++)this.typeChecker.popGuardContextPublic();if(e.alternate&&this.visit(e.alternate),this.options.enableTypeChecking){this.typeChecker.checkNode(e);const n=this.typeChecker.getResult();for(const e of n.errors)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Error,e.code,e.data);for(const e of n.warnings)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Warning,e.code,e.data)}}visitWhileStatement(e){this.options.enableControlFlowAnalysis&&this.loopScopes.push(this.symbolTable.getCurrentScope()),super.visitWhileStatement(e),this.options.enableControlFlowAnalysis&&this.loopScopes.pop()}visitForStatement(e){this.options.enableControlFlowAnalysis&&this.loopScopes.push(this.symbolTable.getCurrentScope()),this.options.enableScopeAnalysis?(this.symbolTable.enterScope(),e.init&&this.visit(e.init),e.test&&this.visit(e.test),e.update&&this.visit(e.update),this.visit(e.body),this.symbolTable.exitScope(e.end)):super.visitForStatement(e),this.options.enableControlFlowAnalysis&&this.loopScopes.pop()}visitForInStatement(e){if(this.options.enableControlFlowAnalysis&&this.loopScopes.push(this.symbolTable.getCurrentScope()),this.options.enableScopeAnalysis){if(this.symbolTable.enterScope(),e.left&&"Identifier"===e.left.type){const t=e.left.name,n=e.left;this.symbolTable.declare(t,S.VARIABLE,C.UNKNOWN,n),this.symbolTable.markUsed(t,n.start)}else if(e.left&&"VariableDeclaration"===e.left.type&&e.left.declarations.length>0){const t=e.left.declarations;if(1===t.length){const n=t[0];if(n.id&&"Identifier"===n.id.type){const t=n.id.name,r=n.id,i=this.typeChecker.checkNode(e.right);let o;if(i===C.ARRAY){const t=this.getIterableFullType(e.right);o=t&&D(t)?P(t):C.UNKNOWN}else o=i===C.OBJECT||i===C.STRING?C.STRING:C.UNKNOWN;this.symbolTable.declare(t,S.VARIABLE,o,r),this.symbolTable.markUsed(t,r.start)}}else if(2===t.length){const n=t[0],r=t[1];if(n.id&&"Identifier"===n.id.type){const t=n.id.name,r=n.id,i=this.typeChecker.checkNode(e.right);let o;o=i===C.OBJECT?C.STRING:i===C.ARRAY?C.INTEGER:C.UNKNOWN,this.symbolTable.declare(t,S.VARIABLE,o,r),this.symbolTable.markUsed(t,r.start)}if(r.id&&"Identifier"===r.id.type){const t=r.id.name,n=r.id,i=this.getIterableFullType(e.right);let o=C.UNKNOWN;i&&D(i)&&(o=P(i)),this.symbolTable.declare(t,S.VARIABLE,o,n),this.symbolTable.markUsed(t,n.start)}}}this.visit(e.right),this.visit(e.body),this.symbolTable.exitScope(e.end)}else super.visitForInStatement(e);this.options.enableControlFlowAnalysis&&this.loopScopes.pop()}getIterableFullType(e){if("Identifier"===e.type){const t=this.symbolTable.lookup(e.name);if(t)return t.dataType}return e._fullType||null}visitSwitchStatement(e){if(this.options.enableControlFlowAnalysis&&this.switchScopes.push(this.symbolTable.getCurrentScope()),this.options.enableTypeChecking){this.typeChecker.checkNode(e.discriminant);const n=this.typeChecker.getResult();for(const e of n.errors)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Error,e.code,e.data);for(const e of n.warnings)this.addDiagnostic(e.message,e.start,e.end,t.DiagnosticSeverity.Warning,e.code,e.data)}super.visitSwitchStatement(e),this.options.enableControlFlowAnalysis&&this.switchScopes.pop()}checkUnusedVariables(){const e=this.symbolTable.getUnusedVariables(),n=new Set(["ARGV","NaN","Infinity","REQUIRE_SEARCH_PATH","modules","global"]);for(const r of e)r.type===S.PARAMETER||r.type===S.BUILTIN||n.has(r.name)||this.addDiagnosticErrorCode(K.UNUSED_VARIABLE,`Variable '${r.name}' is declared but never used`,r.node.start,r.node.end,t.DiagnosticSeverity.Warning)}inferFsType(e){if("CallExpression"!==e.type)return null;const t=e;if("Identifier"===t.callee.type){const e=t.callee.name,n=this.symbolTable.lookup(e);return n&&n.type===S.IMPORTED&&n.importedFrom&&"fs"!==n.importedFrom?null:ee(e)}if("MemberExpression"===t.callee.type){const e=t.callee;if("Identifier"===e.object.type&&"fs"===e.object.name&&"Identifier"===e.property.type)return ee(e.property.name)}return null}inferIoType(e){if("CallExpression"===e.type){const t=e;if("Identifier"===t.callee.type){const e=t.callee.name,n=this.symbolTable.lookup(e);if(!n||n.type!==S.IMPORTED||"io"!==n.importedFrom)return null;switch(n.importSpecifier||e){case"open":case"new":case"from":return nn.IO_HANDLE;default:return null}}else if("MemberExpression"===t.callee.type){const e=t.callee;if("Identifier"===e.object.type&&"Identifier"===e.property.type){const t=e.object.name,n=this.symbolTable.lookup(t);if(n&&"io"===n.importedFrom)switch(e.property.name){case"open":case"new":case"from":return nn.IO_HANDLE}}}}return null}inferNl80211Type(e){if("CallExpression"===e.type){const t=e;if("Identifier"===t.callee.type)return"listener"===t.callee.name?Ct.NL80211_LISTENER:null;if("MemberExpression"===t.callee.type){const e=t.callee;if("Identifier"===e.object.type&&"nl80211"===e.object.name&&"Identifier"===e.property.type&&"listener"===e.property.name)return Ct.NL80211_LISTENER}}return null}inferUciType(e){if("CallExpression"===e.type){const t=e;if("Identifier"===t.callee.type)return"cursor"===t.callee.name?pn.UCI_CURSOR:null;if("MemberExpression"===t.callee.type){const e=t.callee;if("Identifier"===e.object.type&&"uci"===e.object.name&&"Identifier"===e.property.type&&"cursor"===e.property.name)return pn.UCI_CURSOR}}return null}inferUloopType(e){if("CallExpression"===e.type){const t=e;if("Identifier"===t.callee.type)switch(t.callee.name){case"timer":return gn.ULOOP_TIMER;case"handle":return gn.ULOOP_HANDLE;case"process":return gn.ULOOP_PROCESS;case"task":return gn.ULOOP_TASK;case"interval":return gn.ULOOP_INTERVAL;case"signal":return gn.ULOOP_SIGNAL;default:return null}else if("MemberExpression"===t.callee.type){const e=t.callee;if("Identifier"===e.object.type&&"uloop"===e.object.name&&"Identifier"===e.property.type)switch(e.property.name){case"timer":return gn.ULOOP_TIMER;case"handle":return gn.ULOOP_HANDLE;case"process":return gn.ULOOP_PROCESS;case"task":return gn.ULOOP_TASK;case"interval":return gn.ULOOP_INTERVAL;case"signal":return gn.ULOOP_SIGNAL;default:return null}}}return null}inferMethodReturnType(e){if("CallExpression"!==e.type)return null;const t=e;if("MemberExpression"!==t.callee.type)return null;const n=t.callee;if("Identifier"!==n.property.type)return null;const r=n.property.name;if("Identifier"===n.object.type){const e=n.object.name,t=this.symbolTable.lookup(e);if(t){const e="string"==typeof(i=t.dataType)?null:"moduleName"in i&&"string"==typeof i.moduleName&&i.moduleName in kn?i.moduleName:null;if(e){const t=((e,t)=>{const n=kn[e];return n?.get(t)})(e,r);if(t&&"fs.file | fs.proc | socket.socket"===t.returnType)return Z(X.FS_FILE)}if(t.propertyFunctionReturnTypes?.has(r)){const e=t.propertyFunctionReturnTypes.get(r);return this.parseReturnTypeString(e)}if(t.dataType&&"object"==typeof t.dataType&&"moduleName"in t.dataType){const e=t.dataType.moduleName;if(Mn(e)){const t=xn[e].getMethod(r);if(pt(t))return this.parseReturnTypeString(t.value.returnType)}}}}var i;if("CallExpression"===n.object.type){const e=n.object,t=this.resolveCallExpressionObjectType(e);if(t&&Mn(t)){const e=xn[t].getMethod(r);if(pt(e))return this.parseReturnTypeString(e.value.returnType)}}return null}resolveCallExpressionObjectType(e){if("Identifier"===e.callee.type)return Un(e.callee.name);if("MemberExpression"===e.callee.type){const t=e.callee;if("Identifier"===t.object.type&&"Identifier"===t.property.type){const e=t.object.name;return Un(t.property.name,e)}}return null}resolveNodeFullType(e){if(e._fullType)return e._fullType;if("Identifier"===e.type){const t=this.symbolTable.lookup(e.name);if(t)return t.dataType}return null}inferAssignmentDataType(e){if("Identifier"===e.type){const t=e.name,n=this.symbolTable.lookup(t);if(n)return n.dataType}const t=this.inferFsType(e);if(t)return Z(t);const n=this.inferNl80211Type(e);if(n)return At(n);const r=this.inferUloopType(e);if(r)return Dn(r);if(this.inferIoType(e))return rn();const i=this.inferUciType(e);if(i)return dn(i);const o=this.inferImportedFsFunctionReturnType(e);if(o)return o;const s=this.inferImportedRtnlFunctionReturnType(e);if(s)return s;const a=this.inferMethodReturnType(e);if(a)return a;const c=this.inferFunctionCallReturnType(e);return c||this.typeChecker.checkNode(e)}inferObjectLiteralPropertyTypes(e){const t=new Map;for(const n of e.properties){if("SpreadElement"===n.type)continue;const e=this.getStaticPropertyName(n.key);if(!e)continue;const r=n.value;let i;if("FunctionExpression"===r.type||"ArrowFunctionExpression"===r.type)i=C.FUNCTION;else if("Identifier"===r.type){const e=this.symbolTable.lookup(r.name);i=e?e.dataType:C.UNKNOWN}else if("Literal"===r.type){const e=r;i="string"==typeof e.value?C.STRING:"boolean"==typeof e.value?C.BOOLEAN:"number"==typeof e.value?Number.isInteger(e.value)?C.INTEGER:C.DOUBLE:null===e.value?C.NULL:C.UNKNOWN}else i="ObjectExpression"===r.type?C.OBJECT:"ArrayExpression"===r.type?C.ARRAY:this.typeChecker.checkNode(r);t.set(e,i)}return t.size>0?t:null}inferFunctionCallReturnType(e){if("CallExpression"!==e.type)return null;const t=e;if("Identifier"!==t.callee.type)return null;const n=t.callee.name,r=this.symbolTable.lookup(n);return!r||r.type!==S.FUNCTION&&r.type!==S.IMPORTED?null:r.returnType||null}setDeclarationTypeIfUnset(e,t){void 0===e.initialLiteralType&&t!==C.UNKNOWN&&("string"==typeof t||D(t))&&(e.initialLiteralType=t)}isLiteralType(e,t){if(!t)return!1;switch(t.type){case"ArrayExpression":return e===C.ARRAY||D(e);case"ObjectExpression":return e===C.OBJECT;case"Literal":if("regexp"===t.literalType)return e===C.REGEX;if("string"==typeof t.value)return e===C.STRING;if("number"==typeof t.value)return e===C.INTEGER||e===C.DOUBLE;if("boolean"==typeof t.value)return e===C.BOOLEAN;if(null===t.value)return e===C.NULL}return!1}processInitializerTypeInference(e,t){if(!e.init)return;const n=this.symbolTable.lookup(t);if(n){if("Identifier"===e.init.type){const r=e.init.name,i=this.symbolTable.lookup(r);if(i&&(i.type===S.IMPORTED||i.type===S.MODULE))return n.type=i.type,n.dataType=i.dataType,void 0!==i.importedFrom?n.importedFrom=i.importedFrom:delete n.importedFrom,void 0!==i.importSpecifier?n.importSpecifier=i.importSpecifier:delete n.importSpecifier,void this.setDeclarationTypeIfUnset(n,n.dataType);if(i)return n.dataType=i.dataType,this.symbolTable.updateSymbolType(t,i.dataType),i.propertyTypes&&(n.propertyTypes=i.propertyTypes),void this.setDeclarationTypeIfUnset(n,n.dataType)}if("MemberExpression"===e.init.type){const r=e.init;if(!r.computed&&"Identifier"===r.object.type){const e=r.object.name,i=this.getStaticPropertyName(r.property);if(i){const r=this.symbolTable.lookup(e);if(r&&r.propertyTypes&&r.propertyTypes.has(i)){const e=r.propertyTypes.get(i);return n.dataType=e,this.symbolTable.updateSymbolType(t,e),this.setDeclarationTypeIfUnset(n,n.dataType),void(r.nestedPropertyTypes&&r.nestedPropertyTypes.has(i)&&(n.propertyTypes=r.nestedPropertyTypes.get(i)))}}}}const r=this.inferFsType(e.init);if(r){const e=Z(r);return n.dataType=e,this.symbolTable.forceGlobalDeclaration(t,S.VARIABLE,e),void this.setDeclarationTypeIfUnset(n,n.dataType)}const i=this.inferNl80211Type(e.init);if(i){const e=At(i);return n.dataType=e,this.symbolTable.forceGlobalDeclaration(t,S.VARIABLE,e),void this.setDeclarationTypeIfUnset(n,n.dataType)}const o=this.inferUloopType(e.init);if(o){const e=Dn(o);return n.dataType=e,this.symbolTable.forceGlobalDeclaration(t,S.VARIABLE,e),void this.setDeclarationTypeIfUnset(n,n.dataType)}if(this.inferIoType(e.init)){const e=rn();return n.dataType=e,this.symbolTable.forceGlobalDeclaration(t,S.VARIABLE,e),void this.setDeclarationTypeIfUnset(n,n.dataType)}const s=this.inferUciType(e.init);if(s){const e=dn(s);return n.dataType=e,this.symbolTable.forceGlobalDeclaration(t,S.VARIABLE,e),void this.setDeclarationTypeIfUnset(n,n.dataType)}if(n.type!==S.MODULE&&n.type!==S.IMPORTED&&!this.isLiteralType(n.dataType,e.init)){const t=this.inferImportedFsFunctionReturnType(e.init);if(t)return n.dataType=t,void this.setDeclarationTypeIfUnset(n,n.dataType);const r=this.inferMethodReturnType(e.init);if(r)return n.dataType=r,void this.setDeclarationTypeIfUnset(n,n.dataType);const i=this.inferFunctionCallReturnType(e.init);if(i){if(n.dataType=i,this.setDeclarationTypeIfUnset(n,n.dataType),"CallExpression"===e.init.type){const t=e.init;if("Identifier"===t.callee.type){const e=this.symbolTable.lookup(t.callee.name);e?.returnPropertyTypes&&(n.propertyTypes=new Map(e.returnPropertyTypes)),e?.propertyFunctionReturnTypes&&(n.propertyFunctionReturnTypes=new Map(e.propertyFunctionReturnTypes))}}return}this.typeChecker.setTruthinessDepth(1);const o=this.typeChecker.checkNode(e.init);this.typeChecker.setTruthinessDepth(0);const s=e.init._fullType;n.dataType=s||o,this.setDeclarationTypeIfUnset(n,n.dataType),e.init.type}}}visitExportNamedDeclaration(e){if(e.declaration&&(this.visit(e.declaration),this.options.enableScopeAnalysis))if("FunctionDeclaration"===e.declaration.type){const t=e.declaration;t.id&&this.symbolTable.markUsed(t.id.name,t.id.start)}else if("VariableDeclaration"===e.declaration.type){const t=e.declaration;for(const e of t.declarations)if("Identifier"===e.id.type){const t=e.id;this.symbolTable.markUsed(t.name,t.start)}}for(const t of e.specifiers)this.options.enableScopeAnalysis&&this.symbolTable.markUsed(t.local.name,t.local.start)}visitExportDefaultDeclaration(e){if(e.declaration&&(this.visit(e.declaration),this.options.enableScopeAnalysis))if("FunctionDeclaration"===e.declaration.type){const t=e.declaration;t.id&&this.symbolTable.markUsed(t.id.name,t.id.start)}else if("Identifier"===e.declaration.type){const t=e.declaration;this.symbolTable.markUsed(t.name,t.start)}}addDiagnosticErrorCode(e,n,r,i,o){if(this.shouldReduceSeverity(r,i))if(o===t.DiagnosticSeverity.Error){o=t.DiagnosticSeverity.Warning;const e=this.textDocument.positionAt(r);this.linesWithSuppressedDiagnostics.add(e.line)}else if(o===t.DiagnosticSeverity.Warning){o=t.DiagnosticSeverity.Information;const e=this.textDocument.positionAt(r);this.linesWithSuppressedDiagnostics.add(e.line)}const s=this.textDocument.positionAt(r),a=this.textDocument.positionAt(i);if(!this.diagnostics.some(e=>e.message===n&&e.severity===o&&e.range.start.line===s.line&&e.range.start.character===s.character&&e.range.end.line===a.line&&e.range.end.character===a.character)){const t={severity:o,range:{start:s,end:a},message:n,source:"ucode-semantic"};e&&(t.code=e),this.diagnostics.push(t)}}addDiagnostic(e,n,r,i,o,s){let a=i||t.DiagnosticSeverity.Error;if(this.shouldReduceSeverity(n,r))if(a===t.DiagnosticSeverity.Error){a=t.DiagnosticSeverity.Warning;const e=this.textDocument.positionAt(n);this.linesWithSuppressedDiagnostics.add(e.line)}else if(a===t.DiagnosticSeverity.Warning){a=t.DiagnosticSeverity.Information;const e=this.textDocument.positionAt(n);this.linesWithSuppressedDiagnostics.add(e.line)}const c=this.textDocument.positionAt(n),l=this.textDocument.positionAt(r);if(!this.diagnostics.some(t=>t.message===e&&t.severity===a&&t.range.start.line===c.line&&t.range.start.character===c.character&&t.range.end.line===l.line&&t.range.end.character===l.character)){const n={severity:a,range:{start:c,end:l},message:e,source:"ucode-semantic",...o&&{code:o},...s&&{data:s}};s?.unnecessary&&(n.tags=[t.DiagnosticTag.Unnecessary]),this.diagnostics.push(n)}}detectStrictMode(e){if(!e.body||0===e.body.length)return!1;const t=e.body[0];if("ExpressionStatement"===t?.type){const e=t.expression;if("Literal"===e?.type&&"use strict"===e.value)return!0}return!1}scanTypedefs(){this.typedefRegistry.clear();const e=this.textDocument.getText(),t=/\/\*\*([\s\S]*?)\*\//g;let n;for(;null!==(n=t.exec(e));){const e=n[1];if(!e.includes("@typedef"))continue;const t=Mr(xr(e));t&&this.typedefRegistry.set(t.name,t)}}parseDisableComments(){const e=this.textDocument.getText(),t=e.split(/\r?\n/);for(let n=0;n<t.length;n++){const r=t[n];if(r&&r.includes("// ucode-lsp disable")){this.disabledLines.add(n);const t=this.findStatementEnd(e,n);t>n&&this.disabledRanges.push({start:n,end:t})}}}findStatementEnd(e,t){let n=0,r=0,i=t;const o=e.split(/\r?\n/),s=o[t];if(!s)return t;for(const e of s)"("===e&&r++,")"===e&&r--,"{"===e&&n++,"}"===e&&n--;if(r>0||n>0)for(let e=t+1;e<o.length;e++){const t=o[e];if(t){for(const e of t)"("===e&&r++,")"===e&&r--,"{"===e&&n++,"}"===e&&n--;if(i=e,r<=0&&n<=0)break}}return i}shouldReduceSeverity(e,t){const n=this.textDocument.positionAt(e),r=this.textDocument.positionAt(t);if(this.disabledLines.has(n.line))return!0;for(const e of this.disabledRanges)if(n.line>=e.start&&r.line<=e.end)return!0;return!1}checkUnnecessaryDisableComments(){for(const e of this.disabledLines)if(!this.linesWithSuppressedDiagnostics.has(e)){const n=this.textDocument.getText({start:{line:e,character:0},end:{line:e+1,character:0}}).replace(/\r?\n$/,"").indexOf("// ucode-lsp disable");if(n>=0){const r=this.textDocument.offsetAt({line:e,character:n}),i=this.textDocument.offsetAt({line:e,character:n+20});this.addDiagnostic("No diagnostic disabled by this comment",r,i,t.DiagnosticSeverity.Error)}}}isDotNotationModule(e){return/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)+$/.test(e)}convertDotNotationToPath(e){const t=this.textDocument.uri.replace("file://","").split("/").slice(0,-1);for(let n=0;n<t.length;n++){const r=t.slice(n).join(".");if(e.startsWith(r+"."))return"./"+e.substring(r.length+1).replace(/\./g,"/")+".uc"}return"./"+e.replace(/\./g,"/")+".uc"}findContainingNullGuard(e,t,n){if("IfStatement"===e.type){const r=e;if(r.consequent&&n>=r.consequent.start&&n<=r.consequent.end&&this.isNullGuard(r.test,t))return!0}if(e.body){const r=e.body;if(Array.isArray(r)){for(const e of r)if(this.findContainingNullGuard(e,t,n))return!0}else if(this.findContainingNullGuard(r,t,n))return!0}const r=["consequent","alternate","test","left","right","argument","callee","arguments"];for(const i of r){const r=e[i];if(r)if(Array.isArray(r)){for(const e of r)if(e&&"object"==typeof e&&e.type&&this.findContainingNullGuard(e,t,n))return!0}else if("object"==typeof r&&r.type&&this.findContainingNullGuard(r,t,n))return!0}return!1}isNullGuard(e,t){if(!e||"BinaryExpression"!==e.type)return!1;const n=e;return("!="===n.operator||"!=="===n.operator)&&"Identifier"===n.left.type&&n.left.name===t&&"Literal"===n.right.type&&null===n.right.value}detectUnreachableCode(){if(this.cfgQueryEngine&&this.cfg&&this.emitUnreachableDiagnostics(this.cfgQueryEngine,this.cfg),this.currentASTRoot){const e=[];this.collectFunctionNodes(this.currentASTRoot,e);const t=new Set(["die","exit"]);this.analyzeAllFunctions(e,t);let n=!0;for(;n;){n=!1;for(const r of e){const e=r.id?.name;if(!e||!r.body)continue;const i=this.symbolTable.lookup(e);if(i&&!i.neverReturns)try{const o=new br(e,t).build(r.body);this.functionNeverReturns(o,t)&&(i.neverReturns=!0,t.add(e),n=!0)}catch(e){}}}t.size>2&&(this.diagnostics=this.diagnostics.filter(e=>e.code!==K.UNREACHABLE_CODE),this.cfgQueryEngine&&this.cfg&&this.emitUnreachableDiagnostics(this.cfgQueryEngine,this.cfg),this.analyzeAllFunctions(e,t))}}collectFunctionNodes(e,t){"FunctionDeclaration"!==e.type&&"FunctionExpression"!==e.type&&"ArrowFunctionExpression"!==e.type||t.push(e);for(const n of Object.keys(e)){const r=e[n];if(r&&"object"==typeof r)if(Array.isArray(r))for(const e of r)e&&"string"==typeof e.type&&this.collectFunctionNodes(e,t);else"string"==typeof r.type&&this.collectFunctionNodes(r,t)}}analyzeAllFunctions(e,t){for(const n of e)if(n.body)try{const e=new br(n.id?.name||"anonymous",t),r=e.build(n.body),i=new Pr(r,e.getNodeToBlockMap());this.emitUnreachableDiagnostics(i,r),this.narrowFunctionReturnType(n,i,r)}catch(e){}}functionNeverReturns(e,t){const n=new Set,r=[e.entry];for(;r.length>0;){const e=r.shift();if(!n.has(e.id)){n.add(e.id);for(const t of e.successors)r.push(t.target)}}if(!n.has(e.exit.id))return!0;for(const r of e.exit.predecessors){if(!n.has(r.id))continue;if(0===r.statements.length)return!1;const e=r.statements[r.statements.length-1];if("ThrowStatement"!==e.type){if("ExpressionStatement"===e.type){const n=e.expression;if(n&&"CallExpression"===n.type&&"Identifier"===n.callee?.type){const e=n.callee.name;if(e&&t.has(e))continue}}return!1}}return!0}emitUnreachableDiagnostics(e,n){const r=e.getUnreachableBlocks();for(const e of r){if(0===e.statements.length)continue;if(e===n.exit)continue;const r=e.statements[0],i=e.statements[e.statements.length-1];this.addDiagnostic("Unreachable code detected",r.start,i.end,t.DiagnosticSeverity.Hint,K.UNREACHABLE_CODE,{unnecessary:!0})}}narrowFunctionReturnType(e,t,n){const r=this.functionReturnTypes.get(e);if(!r||0===r.length)return;const i=new Set;for(const e of t.getUnreachableBlocks())if(e!==n.exit)for(const t of e.statements)i.add(t.start);const o=r.filter(e=>!i.has(e.node.start));if(o.length===r.length)return;this.functionReturnTypes.set(e,o);const s=e.id?.name;if(s){const e=this.symbolTable.lookup(s);if(e){const t=o.map(e=>e.type);e.returnType=this.typeChecker.getCommonReturnType(t)}}}filterUndefinedFunctionErrorsWithCFG(){if(!this.cfgQueryEngine||!this.typeChecker)return;const e=this.typeChecker.getErrors().filter(e=>{if(!e.message.startsWith("Undefined function:"))return!0;const t=e.message.match(/Undefined function: (\w+)/);if(!t)return!0;const n=t[1];if(!n)return!0;const r=this.symbolTable.lookupAtPosition(n,e.start);return(!r||"unknown"!==r.dataType)&&"unknown"!==this.cfgQueryEngine.getTypeAtPosition(n,e.start)});this.typeChecker.setErrors(e)}recheckExpressionWithCFG(e){const t=e.data;if(!(t&&t.variableName&&"number"==typeof t.argumentOffset&&Array.isArray(t.expectedTypes)&&0!==t.expectedTypes.length&&this.cfgQueryEngine&&this.typeChecker))return!1;const n=t.variableName,r=t.argumentOffset,i=this.cfgQueryEngine.getTypeAtPosition(n,r),o=t.expectedTypes,s=this.typeChecker.getTypeNarrowing();if(i&&s.isSubtypeOfUnion(i,o))return!0;const a=this.typeChecker.getNarrowedTypeAtPosition(n,r);if(a&&s.isSubtypeOfUnion(a,o))return!0;const c=this.findTypeGuardNarrowedTypes(n,r);return!!(c&&c.length>0&&c.every(e=>o.includes(e)))}filterDiagnosticsWithFlowSensitiveAnalysis(e){return this.currentASTRoot&&this.cfgQueryEngine?e.filter(e=>{if("nullable-argument"===e.code){const t=e.data;if(t&&t.variableName&&"number"==typeof t.argumentOffset&&Array.isArray(t.expectedTypes)&&this.recheckExpressionWithCFG(e))return!1;if(t&&!t.variableName&&"number"==typeof t.argumentOffset&&this.isNullableArgGuardedByPropertyAccess(t.argumentOffset))return!1}if(e.message.includes("may be")&&e.severity===t.DiagnosticSeverity.Warning){const t=e.data;t&&t.variableName}if(e.message.includes("'in' operator")&&e.message.includes("possibly 'null'")&&e.message.match(/Argument is possibly 'null'/)){const t=e.range.start.character,n=e.range.start.line,r=this.textDocument.getText().split("\n");let i=0;for(let e=0;e<n&&e<r.length;e++){const t=r[e];void 0!==t&&(i+=t.length+1)}if(i+=t,this.currentASTRoot&&this.findNullGuardAtPosition(this.currentASTRoot,i))return!1}return!0}):e}findTypeGuardNarrowedTypes(e,t){return this.currentASTRoot?this.searchTypeGuardForPosition(this.currentASTRoot,e,t):null}searchTypeGuardForPosition(e,t,n){if(!this.nodeContainsPosition(e,n))return null;switch(e.type){case"IfStatement":{const r=e;if(this.nodeContainsPosition(r.consequent,n)){const e=this.collectTypeGuardTypes(r.test,t);if(e.pure&&e.types.size>0)return Array.from(e.types)}const i=this.searchTypeGuardForPosition(r.consequent,t,n);if(i)return i;if(r.alternate){const e=this.searchTypeGuardForPosition(r.alternate,t,n);if(e)return e}return null}case"BlockStatement":{const r=e;for(const e of r.body){const r=this.searchTypeGuardForPosition(e,t,n);if(r)return r}return null}case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":{const r=e.body;return r?this.searchTypeGuardForPosition(r,t,n):null}}for(const r of Object.keys(e)){const i=e[r];if(i)if(Array.isArray(i)){for(const e of i)if(e&&"object"==typeof e&&"type"in e){const r=this.searchTypeGuardForPosition(e,t,n);if(r)return r}}else if("object"==typeof i&&"type"in i){const e=this.searchTypeGuardForPosition(i,t,n);if(e)return e}}return null}collectTypeGuardTypes(e,t){const n={types:new Set,pure:!0},r=e=>{if(e&&n.pure)switch(e.type){case"LogicalExpression":{const t=e;return r(t.left),void r(t.right)}case"BinaryExpression":{const r=e;if("=="===r.operator||"==="===r.operator){const e=this.extractTypeCheck(r.left,r.right,t),i=this.extractTypeCheck(r.right,r.left,t),o=e??i;if(o)return void n.types.add(o)}return void(n.pure=!1)}default:return void(n.pure=!1)}};return r(e),n}extractTypeCheck(e,t,n){if("CallExpression"===e.type&&this.isTypeCallOnVariable(e,n)&&"Literal"===t.type){const e=t;if("string"==typeof e.value)return this.mapTypeStringToUcodeType(e.value)}return null}isTypeCallOnVariable(e,t){if("Identifier"!==e.callee.type)return!1;if("type"!==e.callee.name)return!1;if(!e.arguments||1!==e.arguments.length)return!1;const n=e.arguments[0];return!!n&&"Identifier"===n.type&&n.name===t}mapTypeStringToUcodeType(e){switch(e){case"string":return C.STRING;case"int":return C.INTEGER;case"double":return C.DOUBLE;case"bool":return C.BOOLEAN;case"array":return C.ARRAY;case"object":return C.OBJECT;case"function":return C.FUNCTION;case"null":return C.NULL;default:return null}}nodeContainsPosition(e,t){return!(!e||"object"!=typeof e)&&"number"==typeof e.start&&"number"==typeof e.end&&t>=e.start&&t<=e.end}isNullableArgGuardedByPropertyAccess(e){if(!this.currentASTRoot)return!1;const t=this.findCallExpressionAt(this.currentASTRoot,e);if(!t||"CallExpression"!==t.type)return!1;const n=t;if("Identifier"!==n.callee.type)return!1;const r=n.callee.name;if(!["keys","values","length","sort","reverse","uniq","pop","shift","slice","splice","join","split","trim","ltrim","rtrim","index","rindex","filter","map","substr","match"].includes(r))return!1;if(!n.arguments||0===n.arguments.length)return!1;const i=n.arguments[0];if(!i)return!1;const o=this.getMemberExpressionPath(i);return!!o&&this.hasPropertyAccessGuard(this.currentASTRoot,o,e)}getMemberExpressionPath(e){if("Identifier"===e.type)return e.name;if("MemberExpression"===e.type){const t=e;if(!t.computed&&"Identifier"===t.property.type){const e=this.getMemberExpressionPath(t.object);if(e)return`${e}.${t.property.name}`}}return null}hasPropertyAccessGuard(e,t,n){if("IfStatement"===e.type){const r=e;if(r.consequent&&n>=r.consequent.start&&n<=r.consequent.end&&this.conditionImpliesObjectType(r.test,t))return!0}const r=["body","consequent","alternate"];for(const i of r){const r=e[i];if(r)if(Array.isArray(r)){for(const e of r)if(e&&"object"==typeof e&&e.type&&n>=e.start&&n<=e.end&&this.hasPropertyAccessGuard(e,t,n))return!0}else if("object"==typeof r&&r.type&&n>=r.start&&n<=r.end&&this.hasPropertyAccessGuard(r,t,n))return!0}return!1}conditionImpliesObjectType(e,t){if(!e)return!1;if("BinaryExpression"===e.type){const n=e;if("&&"===n.operator)return this.conditionImpliesObjectType(n.left,t)||this.conditionImpliesObjectType(n.right,t);if("!="===n.operator||"!=="===n.operator){const e=this.isNullLiteral(n.right)?n.left:this.isNullLiteral(n.left)?n.right:null;if(!e)return!1;if(this.getMemberExpressionPath(e)===t)return!0;if("MemberExpression"===e.type&&this.getMemberExpressionPath(e.object)===t)return!0}}if("LogicalExpression"===e.type){const n=e;if("&&"===n.operator)return this.conditionImpliesObjectType(n.left,t)||this.conditionImpliesObjectType(n.right,t)}return!1}isNullLiteral(e){return"Literal"===e.type&&null===e.value}findCallExpressionAt(e,t){if(!e||"object"!=typeof e)return null;if(e.start>t||e.end<t)return null;if("CallExpression"===e.type&&e.start===t)return e;const n=["body","consequent","alternate","test","left","right","argument","callee","arguments","init","update","declarations","expression","elements","properties","value","object","property"];for(const r of n){const n=e[r];if(n)if(Array.isArray(n)){for(const e of n)if(e&&"object"==typeof e&&e.type){const n=this.findCallExpressionAt(e,t);if(n)return n}}else if("object"==typeof n&&n.type){const e=this.findCallExpressionAt(n,t);if(e)return e}}return null}findNullGuardAtPosition(e,t){if("BinaryExpression"===e.type){const n=e;if("in"===n.operator&&t>=n.start&&t<=n.end&&n.right&&"Identifier"===n.right.type){const e=n.right.name;return this.findContainingNullGuard(this.currentASTRoot,e,t)}}const n=["body","consequent","alternate","test","left","right","argument","callee","arguments"];for(const r of n){const n=e[r];if(n)if(Array.isArray(n)){for(const e of n)if(e&&"object"==typeof e&&e.type&&this.findNullGuardAtPosition(e,t))return!0}else if("object"==typeof n&&n.type&&this.findNullGuardAtPosition(n,t))return!0}return!1}}const Kr=new class{isRegexLiteral(e){return"object"==typeof e&&null!==e&&"regexp"===e.type&&"string"==typeof e.pattern}getRegexDocumentation(e,t){return`**Regular Expression**${t?` with flags \`${t}\``:""}\n\nPattern: \`${e}\`\n\n**Type:** \`regex\`\n\nRegular expressions are independent objects used for pattern matching and text processing. They support standard regex syntax including:\n\n- **Character classes**: \`[a-z]\`, \`[0-9]\`, \`\\d\`, \`\\w\`, \`\\s\`\n- **Quantifiers**: \`+\`, \`*\`, \`?\`, \`{n,m}\`\n- **Anchors**: \`^\`, \`$\`\n- **Groups**: \`(pattern)\`, \`(?:pattern)\`\n- **Alternation**: \`pattern1|pattern2\`\n- **Escape sequences**: \`\\.\`, \`\\[\`, \`\\]\`, \`\\(\`, \`\\)\`\n\n**Common methods** (when used with builtin functions):\n- \`match(string, regex)\` - Find matches in string\n- \`replace(string, regex, replacement)\` - Replace matches\n- \`test(regex, string)\` - Test if pattern matches`}getBasicRegexInfo(){return"**regex** - Regular expression pattern for text matching"}validatePattern(e){try{return new RegExp(e),{valid:!0}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"Invalid regex pattern"}}}extractPattern(e){return e&&"string"==typeof e.pattern?{pattern:e.pattern,flags:e.flags||void 0}:{pattern:""}}};function Gr(e){return e+"\n\n---\n*Built-in C method — no source definition available*"}function Br(e){switch(e){case l.TK_ASSIGN:case l.TK_ASADD:case l.TK_ASSUB:case l.TK_ASMUL:case l.TK_ASDIV:case l.TK_ASMOD:case l.TK_ASLEFT:case l.TK_ASRIGHT:case l.TK_ASBAND:case l.TK_ASBXOR:case l.TK_ASBOR:case l.TK_ASEXP:case l.TK_ASAND:case l.TK_ASOR:case l.TK_ASNULLISH:return!0;default:return!1}}function Wr(e){if(!e||"object"!=typeof e||!("moduleName"in e))return null;const t=e.moduleName;return Mn(t)?t:null}const $r={d:"signed decimal integer",i:"signed decimal integer",u:"unsigned decimal integer",o:"unsigned octal",x:"unsigned hex (lowercase)",X:"unsigned hex (uppercase)",f:"decimal floating point",F:"decimal floating point",e:"scientific notation (lowercase)",E:"scientific notation (uppercase)",g:"shortest of %e/%f (lowercase)",G:"shortest of %E/%F (uppercase)",a:"hex floating point (lowercase)",A:"hex floating point (uppercase)",s:"string",c:"character",J:"JSON serialization (ucode-specific)",n:"number of characters written so far",p:"pointer address","%":"literal '%'"};function jr(e,n,r,i){const o=n.get(e.textDocument.uri);if(!o)return;const s=e.position,a=o.getText(),c=o.offsetAt(s);try{let n;n=i&&i.length>0?i:new E(a,{rawMode:!0}).tokenize();const s=function(e,t,n){const r=n.offsetAt(e);let i=-1;for(let e=0;e<t.length;e++){const n=t[e];if(n.pos<=r&&r<n.end){i=e;break}}if(-1===i)return;const o=t[i];if(o.type!==l.TK_LABEL)return;if(i<2)return;const s=t[i-1];if(s.type!==l.TK_DOT||s.end!==o.pos)return;const a=t[i-2];if(a.type===l.TK_LABEL&&a.end===s.pos)return{objectName:a.value,memberName:o.value,memberTokenPos:o.pos,memberTokenEnd:o.end};if(a.type===l.TK_THIS&&a.end===s.pos)return{objectName:"this",memberName:o.value,memberTokenPos:o.pos,memberTokenEnd:o.end};if(a.type===l.TK_RPAREN&&a.end===s.pos){let e=1,n=i-3;for(;n>=0&&e>0;)t[n].type===l.TK_RPAREN?e++:t[n].type===l.TK_LPAREN&&e--,n--;if(n>=0&&t[n].type===l.TK_LABEL){const e=t[n].value;let r;n>=2&&t[n-1].type===l.TK_DOT&&t[n-2].type===l.TK_LABEL&&(r=t[n-2].value);const i=Un(e,r);if(i)return{objectName:"__call_chain__",memberName:o.value,memberTokenPos:o.pos,memberTokenEnd:o.end,resolvedObjectType:i}}}}(e.position,n,o);if(s){const{objectName:e,memberName:n,resolvedObjectType:i}=s;if(i){const e=Bn(i,n);return pt(e)?{contents:{kind:t.MarkupKind.Markdown,value:Gr(e.value)},range:{start:o.positionAt(s.memberTokenPos),end:o.positionAt(s.memberTokenEnd)}}:void 0}if(!r||!r.symbolTable)return;{let i=r.symbolTable.lookupAtPosition(e,c);if(i||(i=r.symbolTable.lookup(e)),r.cfgQueryEngine&&!i){const t=r.cfgQueryEngine.getTypeAtPosition(e,c);t&&(i={name:e,type:S.VARIABLE,dataType:t,scope:0,declared:!0,used:!0,node:{},declaredAt:c,usedAt:[c]})}if(i&&i.propertyTypes&&i.propertyTypes.has(n)){const r=`**${n}**: \`${x(i.propertyTypes.get(n))}\`\n\n${"global"===e?`Global property on \`${e}\``:`Property on \`${e}\``}`;return{contents:{kind:t.MarkupKind.Markdown,value:r},range:{start:o.positionAt(s.memberTokenPos),end:o.positionAt(s.memberTokenEnd)}}}if(i&&i.type===S.IMPORTED){const e=i.importedFrom;let r;if(e&&wn(e)){const t=Kn(e,n);pt(t)&&(r=t.value)}if(r)return{contents:{kind:t.MarkupKind.Markdown,value:r},range:{start:o.positionAt(s.memberTokenPos),end:o.positionAt(s.memberTokenEnd)}}}else if(i){const e=Wr(i.dataType);if(e){const r=Bn(e,n);if(pt(r))return{contents:{kind:t.MarkupKind.Markdown,value:Gr(r.value)},range:{start:o.positionAt(s.memberTokenPos),end:o.positionAt(s.memberTokenEnd)}}}let r;if(i.dataType&&"object"==typeof i.dataType&&"moduleName"in i.dataType&&(r=i.dataType.moduleName),r&&wn(r)){const e=Kn(r,n);if(pt(e))return{contents:{kind:t.MarkupKind.Markdown,value:e.value},range:{start:o.positionAt(s.memberTokenPos),end:o.positionAt(s.memberTokenEnd)}}}return}}}const p=n.find(e=>e.pos<=c&&c<e.end),d=p?n.indexOf(p):-1;if(p&&p.type===l.TK_STRING&&d>=0){const e=function(e,n,r,i,o){let s=-1;for(let e=n-1;e>=0;e--){const t=r[e];if(t.type===l.TK_LPAREN){s=e;break}if(t.type===l.TK_COMMA||t.type===l.TK_RPAREN||t.type===l.TK_SCOL||t.type===l.TK_LBRACE)return}if(s<0)return;const a=s-1;if(a<0)return;const c=r[a];if(!c||c.type!==l.TK_LABEL)return;const u=c.value;if("printf"!==u&&"sprintf"!==u)return;let p=!1;for(let e=s+1;e<n;e++){p=!0;break}if(p)return;const d=G(e.value);if(0===d.length)return;const m=i-e.pos-1;let h=0;for(const n of d)if("%"!==n.specifier&&h++,m>=n.position&&m<n.endPosition){const r=$r[n.specifier];if(!r)return;let i=`**Format specifier: \`${n.fullMatch}\`**\n\n`;if(n.flags||n.width||n.precision){if(i+="| | |\n|---|---|\n",i+=`| Type | ${r} |\n`,n.flags){const e=[];n.flags.includes("-")&&e.push("left-align"),n.flags.includes("+")&&e.push("always show sign"),n.flags.includes(" ")&&e.push("space before positive"),n.flags.includes("0")&&e.push("zero-pad"),n.flags.includes("#")&&e.push("alternate form"),i+=`| Flags | \`${n.flags}\` (${e.join(", ")}) |\n`}n.width&&(i+=`| Width | ${"*"===n.width?"from argument":`${n.width} (minimum field width)`} |\n`),n.precision&&(i+=`| Precision | ${"*"===n.precision?"from argument":`${n.precision} (decimal places)`} |\n`)}else"%"===n.specifier?i+=`Prints a ${r}.`:i+=`Prints a **${r}**.`;"%"!==n.specifier&&(i+=`\n\nArgument ${h} in the call.`);const s=e.pos+1+n.position,a=e.pos+1+n.endPosition;return{contents:{kind:t.MarkupKind.Markdown,value:i},range:{start:o.positionAt(s),end:o.positionAt(a)}}}}(p,d,n,c,o);if(e)return e}if(p&&p.type===l.TK_LABEL&&"string"==typeof p.value&&d>0){const e=n[d-1];if(e&&e.type===l.TK_ELLIP)return{contents:{kind:t.MarkupKind.Markdown,value:`**(rest parameter)** **...${p.value}**: \`array\`\n\nRest parameter - collects remaining arguments into an array`},range:{start:o.positionAt(e.pos),end:o.positionAt(p.end)}}}if(p&&p.type===l.TK_ELLIP&&d+1<n.length){const e=n[d+1];if(e&&e.type===l.TK_LABEL)return{contents:{kind:t.MarkupKind.Markdown,value:`**(rest parameter)** **...${e.value}**: \`array\`\n\nRest parameter - collects remaining arguments into an array`},range:{start:o.positionAt(p.pos),end:o.positionAt(e.end)}}}if(p&&p.type===l.TK_FROM&&r){const e="from",i=r.symbolTable.lookup(e);if(i&&i.type===S.IMPORTED&&"io"===i.importedFrom){const r=i.importSpecifier||i.name,s=qr(c,n),a=Gn("io",r);let l=pt(a)?a.value:Pn.io.getModuleDocumentation();return s&&i.returnType&&(l=`(function call) **${e}()**: \`${x(i.returnType)}\`\n\n${l}`),{contents:{kind:t.MarkupKind.Markdown,value:l},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}}}}if(p&&p.type===l.TK_LABEL&&"string"==typeof p.value){const e=p.value;if(qr(c,n)&&r){let n=r.symbolTable.lookupAtPosition(e,c);if(n||(n=r.symbolTable.lookup(e)),!n&&r.cfgQueryEngine){const t=r.cfgQueryEngine.getTypeAtPosition(e,c);t&&(n={name:e,type:S.VARIABLE,dataType:t,scope:0,declared:!0,used:!0,node:{},declaredAt:c,usedAt:[c]})}if(n&&(n.type===S.FUNCTION||n.type===S.IMPORTED)&&n.returnType){const r=x(n.returnType);return{contents:{kind:t.MarkupKind.Markdown,value:`(function call) **${e}()**: \`${r}\`\n\nReturn type of function call`},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}}}}const i=function(e,t){const n=t.findIndex(t=>t.pos<=e&&e<t.end);if(-1===n)return;const r=t[n];if(n+2<t.length){const e=t[n+1],i=t[n+2];if(e.type===l.TK_DOT&&i.type===l.TK_LABEL&&r.type===l.TK_LABEL)return{objectName:r.value,propertyName:i.value,cursorOnObject:!0}}if(n>=2){const e=t[n-1],i=t[n-2];if(e.type===l.TK_DOT&&i.type===l.TK_LABEL&&r.type===l.TK_LABEL)return{objectName:i.value,propertyName:r.value,cursorOnObject:!1}}}(c,n);if(i&&r&&!i.cursorOnObject){const e=function(e,t){const{objectName:n,propertyName:r}=e;let i=t.symbolTable.lookup(n);if(!i&&t.cfgQueryEngine){const e=t.cfgQueryEngine.getTypeAtPosition(n,0);e&&(i={name:n,type:S.VARIABLE,dataType:e,scope:0,declared:!0,used:!0,node:{},declaredAt:0,usedAt:[0]})}if(!i)return null;const o=Wr(i.dataType);if(o){const e=Bn(o,r);if(pt(e))return Gr(e.value)}let s;if(i.type===S.IMPORTED&&i.importedFrom?s=i.importedFrom:i.dataType&&"object"==typeof i.dataType&&"moduleName"in i.dataType&&(s=i.dataType.moduleName),s&&wn(s)){const e=Kn(s,r);if(pt(e))return e.value}return null}(i,r);if(e)return{contents:{kind:t.MarkupKind.Markdown,value:e},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}}}if(p&&p.type===l.TK_LABEL&&"string"==typeof p.value){const e=p.value,n=a.lastIndexOf("\n",p.pos)+1,i=a.indexOf("\n",p.end),s=a.slice(n,-1===i?a.length:i);if(new RegExp(`\\b${e}\\s*:\\s*\\([^)]*\\)\\s*=>`).test(s)){let n=!1;if(r){const t=r.symbolTable.lookup(e);n=(t&&t.type===S.FUNCTION)??!1}if(!n){const n=s.match(new RegExp(`\\b${e}\\s*:\\s*(\\([^)]*\\)\\s*=>.*?)(?:,|$|\\})`));if(n){const e=function(e){const t=e.trim();if(t.includes("=>")){const e=t.indexOf("=>"),n=t.slice(0,e).trim();let r="";if(n.startsWith("(")&&n.includes(")")){const e=n.match(/^\((.*)\)/);r=e&&e[1]||""}else r=n;const i=r.includes("...");let o="unknown";const s=t.slice(t.indexOf("=>")+2).trim();if(s.startsWith("warn("))o="null";else if(s.includes("return ")){const e=s.match(/return\s+([^;]+)/);if(e&&e[1]){const t=e[1].trim();"null"===t||"undefined"===t?o=t:t.match(/^\d+$/)?o="number":t.match(/^["'`]/)?o="string":"true"!==t&&"false"!==t||(o="boolean")}}let a="Arrow function";return i&&(a+=" with rest parameters"),`**(function)** **(${r}) => ${o}**\n\n${a}`}if(t.startsWith("function")){const e=t.match(/^function\s*\(([^)]*)\)/),n=e?e[1]:"";let r="Function expression";return n&&n.includes("...")&&(r+=" with rest parameters"),`**(function)** **function(${n})**\\n\\n${r}`}return t.startsWith("[")?"**(array)** Array literal":t.startsWith("{")?"**(object)** Object literal":t.match(/^['"`]/)?"**(string)** String literal":t.match(/^\d/)?"**(number)** Number literal":"true"===t||"false"===t?"**(boolean)** Boolean literal":void 0}(n[1].trim());if(e)return{contents:{kind:t.MarkupKind.Markdown,value:e},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}}}}}}{const n=a.lastIndexOf("\n",c)+1,r=a.indexOf("\n",c),i=a.substring(n,-1===r?a.length:r).match(/^\s*import\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/);if(i&&i[2]){const n=i[2],r=i[1].split(",").map(e=>e.trim());for(const i of r){const r=i.split(/\s+as\s+/),s=r[0]?.trim();if(s===e&&wn(n)){const e=Gn(n,s);if(pt(e))return{contents:{kind:t.MarkupKind.Markdown,value:e.value},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}}}}}}if(r){let i=r.symbolTable.lookupAtPosition(e,c);const s=!!i;if(i||(i=r.symbolTable.lookup(e)),!i&&r.cfgQueryEngine){const t=r.cfgQueryEngine.getTypeAtPosition(e,c);t&&(i={name:e,type:S.VARIABLE,dataType:t,scope:0,declared:!0,used:!0,node:{},declaredAt:c,usedAt:[c]})}if(i&&!s&&r.cfgQueryEngine){const t=r.cfgQueryEngine.getTypeAtPosition(e,c);t&&t!==C.UNKNOWN&&t!==i.dataType&&(i={...i,dataType:t})}if(!i){const n=a.lastIndexOf("\n",c)+1,r=Math.max(0,n),i=a.slice(0,r),s=new RegExp(`\\([^)]*\\.\\.\\.${e}[^)]*\\)\\s*=>`,"g"),l=[...i.matchAll(s)];if(l.length>0){const n=l[l.length-1].index||0;if(c-n<200)return{contents:{kind:t.MarkupKind.Markdown,value:`**(rest parameter)** **${e}**: \`array\`\n\nRest parameter - collects remaining arguments into an array`},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}}}}if(i){const e=d>=0&&function(e,t){if(t<0||t>=e.length)return!1;let n=t-1;for(;n>=0;){const t=e[n];if(!t)break;if(t.type!==l.TK_NEWLINE&&t.type!==l.TK_SCOL){if(t.type===l.TK_LOCAL||t.type===l.TK_CONST)return!1;break}n--}const r=n>=0?e[n]:void 0;if(r&&(r.type===l.TK_LOCAL||r.type===l.TK_CONST))return!1;for(let n=t+1;n<e.length;n++){const t=e[n];if(!t)return!1;if(Br(t.type))return!0;if(t.type!==l.TK_DOT&&t.type!==l.TK_LBRACK&&t.type!==l.TK_RBRACK&&t.type!==l.TK_LABEL)return!1}return!1}(n,d),s=function(e,t,n,r){if(r&&r.typeChecker&&r.ast){const n=r.typeChecker.getNarrowedTypeAtPosition(e.name,t);if(n)return n}if(e.currentType){if(n)return e.currentType;if(void 0!==e.currentTypeEffectiveFrom&&t>=e.currentTypeEffectiveFrom)return e.currentType}return e.dataType}(i,c,e,r),a=x(s);let u="";switch(i.type){case S.VARIABLE:case S.PARAMETER:if(i.type===S.PARAMETER&&i.isRestParam)u=`**(rest parameter)** **${i.name}**: \`array\`\n\nRest parameter - collects remaining arguments into an array`;else{if(r?.typeChecker&&s===C.FUNCTION){const e=r.typeChecker.getEqualityNarrowSymbolAtPosition(i.name,c);if(e?.importedFrom&&wn(e.importedFrom)){const t=e.importSpecifier||e.name,n=Gn(e.importedFrom,t);if(pt(n)){u=`(${i.type}) **${i.name}** — narrowed via equality\n\n${n.value}`;break}}}u=`(${i.type}) **${i.name}**: \`${a}\``}i.jsdocDescription&&(u+=`\n\n${i.jsdocDescription}`);break;case S.FUNCTION:if(i.returnType){const e=x(i.returnType);u=`(function) **${i.name}**: \`function\`\n\nReturns: \`${e}\``}else u=`(function) **${i.name}**: \`function\``;break;case S.MODULE:u=`(module) **${i.name}**: \`${x(i.dataType)}\``;break;case S.IMPORTED:if(i.dataType&&"object"==typeof i.dataType&&"moduleName"in i.dataType){const e=i.dataType.moduleName;if("nl80211-const"===e){u=`(const object) **${i.name}**: \`object\`\n\nContainer for nl80211 module constants.`;break}if("rtnl-const"===e){u=`(const object) **${i.name}**: \`object\`\n\nContainer for rtnl module constants.`;break}}if(i.importedFrom&&wn(i.importedFrom)){const e=i.importSpecifier||i.name,t=Gn(i.importedFrom,e);pt(t)&&(u=t.value)}else u=`(imported) **${i.name}**: \`${x(i.dataType)}\``}if(u)return{contents:{kind:t.MarkupKind.Markdown,value:u},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}}}}const s=v.get(e);if(s)return{contents:{kind:t.MarkupKind.Markdown,value:`**${e}** (built-in function)\n\n${s}`},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}};if(u=e,q.has(u))return{contents:{kind:t.MarkupKind.Markdown,value:H(e)},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}};if(h(e))return{contents:{kind:t.MarkupKind.Markdown,value:`**${e}** (ucode keyword)`},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}}}if(p&&p.type===l.TK_REGEXP){const e=Kr.extractPattern(p.value);if(e.pattern)return{contents:{kind:t.MarkupKind.Markdown,value:Kr.getRegexDocumentation(e.pattern,e.flags)},range:{start:o.positionAt(p.pos),end:o.positionAt(p.end)}}}}catch(e){const n=function(e,t){const n=/[a-zA-Z_$][a-zA-Z0-9_$]*/g;let r;for(;null!==(r=n.exec(e));)if(r.index<=t&&t<r.index+r[0].length)return{start:r.index,end:r.index+r[0].length}}(a,c);if(!n)return;const r=a.substring(n.start,n.end),i=Pn.log.getFunctionDocumentation(r);if(pt(i))return{contents:{kind:t.MarkupKind.Markdown,value:i.value},range:{start:o.positionAt(n.start),end:o.positionAt(n.end)}};const s=v.get(r);if(s)return{contents:{kind:t.MarkupKind.Markdown,value:`**${r}** (built-in function)\n\n${s}`},range:{start:o.positionAt(n.start),end:o.positionAt(n.end)}}}var u}function qr(e,t){const n=t.findIndex(t=>t.pos<=e&&e<t.end);if(-1===n)return!1;const r=t[n];if(r.type!==l.TK_LABEL)return!1;if(n>0){const e=t[n-1];if(e&&e.type===l.TK_FUNC)return!1}if(n+1<t.length){const e=t[n+1];if(e.type===l.TK_LPAREN&&r.end===e.pos)return!0}return!1}var Vr=n(7016);const Hr=new Map;function Yr(e,t,n=0){let r=t.symbolTable.lookup(e);if(!r&&t.cfgQueryEngine){const i=t.cfgQueryEngine.getTypeAtPosition(e,n);i&&(r={name:e,type:S.VARIABLE,dataType:i,scope:0,declared:!0,used:!0,node:{},declaredAt:n,usedAt:[n]})}return r||void 0}function Xr(e,n,r){const i=[];n&&!e&&n.console.log("[WARNING] No analysisResult passed to createGeneralCompletions");for(const[e,n]of v.entries())i.push({label:e,kind:t.CompletionItemKind.Function,detail:"built-in function",documentation:{kind:t.MarkupKind.Markdown,value:n},insertText:e,sortText:`1${e}`,filterText:e});const o=["let","const","function","if","else","for","while","return","break","continue","try","catch","throw"];for(const e of o)i.push({label:e,kind:t.CompletionItemKind.Keyword,detail:"ucode keyword",insertText:e,sortText:`2${e}`,filterText:e});if(e&&e.symbolTable){const o=void 0!==r?e.symbolTable.getSymbolsAtPosition(r):e.symbolTable.getAllSymbols();n&&n.console.log(`[INFO] Found ${o.length} symbols in symbol table (offset: ${r})`);for(const e of o){const r=e.name;if(v.has(r))continue;let o,s;switch(e.dataType&&"object"==typeof e.dataType&&"moduleName"in e.dataType&&e.dataType.moduleName,e.type){case"variable":o=t.CompletionItemKind.Variable,s="variable";break;case"parameter":o=t.CompletionItemKind.Variable,s="parameter";break;case"function":o=t.CompletionItemKind.Function,s="user function";break;case"imported":o=t.CompletionItemKind.Module,s=`imported from ${e.importedFrom||"module"}`;break;default:o=t.CompletionItemKind.Variable,s="identifier"}i.push({label:r,kind:o,detail:s,insertText:r,sortText:`0${r}`,filterText:r}),n&&n.console.log(`[INFO] Added variable to completions: ${r} (${s})`)}}return n&&n.console.log(`[INFO] createGeneralCompletions returning ${i.length} completions total`),i}function zr(e,t){if(t){const n=Hr.get(t);if(n&&n.content===e)return n.properties}let n=[];try{const r=new E(e,{rawMode:!0}),i=r.tokenize(),o=new lr(i,e);o.setComments(r.comments);const s=o.parse();if(!s.ast)return t&&Hr.set(t,{content:e,properties:n}),n;const a=s.ast,c=new Map;for(const e of a.body||[])if("VariableDeclaration"===e?.type)for(const t of e.declarations||[])"Identifier"===t?.id?.type&&c.set(t.id.name,t.init||null);for(const e of a.body||[])if("ExportDefaultDeclaration"===e?.type){const t=Jr(e.declaration,c,new Set);if(t&&"ObjectExpression"===t.type){n=Qr(t);break}}}catch(e){n=[]}return t&&Hr.set(t,{content:e,properties:n}),n}function Jr(e,t,n){if(!e)return null;if("ObjectExpression"===e.type)return e;if("Identifier"===e.type){const r=e.name;if(!r||n.has(r))return null;n.add(r);const i=t.get(r);return i?Jr(i,t,n):null}if("CallExpression"===e.type){for(const r of e.arguments||[]){const e=Jr(r,t,n);if(e)return e}return null}return"AssignmentExpression"===e.type?Jr(e.right,t,n):"VariableDeclarator"===e.type?Jr(e.init,t,n):null}function Qr(e){const t=[];if(!e?.properties)return t;const n=new Set;for(const r of e.properties){if(!r||"Property"!==r.type)continue;const e=Zr(r);if(!e||n.has(e))continue;const i=ei(r.value);t.push({name:e,type:i}),n.add(e)}return t}function Zr(e){return e?e.computed?"Literal"===e.key?.type&&void 0!==e.key.value&&null!==e.key.value?String(e.key.value):null:"Identifier"===e.key?.type?e.key.name:"Literal"===e.key?.type?void 0===e.key.value||null===e.key.value?null:String(e.key.value):null:null}function ei(e){if(!e)return"property";switch(e.type){case"FunctionExpression":case"ArrowFunctionExpression":return"function";case"Literal":return"string"===e.literalType?"string":"number"===e.literalType||"double"===e.literalType?"number":"property";default:return"property"}}function ti(e){const t=[],n=e.match(/export\s+const\s+(\w+)\s*=/g);if(n)for(const e of n){const n=e.match(/export\s+const\s+(\w+)/)?.[1];n&&t.push({name:n,type:"constant"})}const r=e.match(/export\s+function\s+(\w+)\s*\(/g);if(r)for(const e of r){const n=e.match(/export\s+function\s+(\w+)/)?.[1];n&&t.push({name:n,type:"function"})}const i=e.match(/export\s*\{\s*([^}]+)\s*\}/g);if(i)for(const e of i){const n=e.match(/export\s*\{\s*([^}]+)\s*\}/)?.[1];if(n){const e=n.split(",").map(e=>e.trim()).filter(e=>e);for(const n of e)t.push({name:n,type:"symbol"})}}return t}function ni(e){switch(e){case"function":return t.CompletionItemKind.Method;case"string":case"number":return t.CompletionItemKind.Value;default:return t.CompletionItemKind.Property}}function ri(e){switch(e){case"function":return t.CompletionItemKind.Function;case"constant":return t.CompletionItemKind.Constant;default:return t.CompletionItemKind.Variable}}function ii(e){const t="builtin"===e.source?"builtin":"system";let n=`Import the **${e.name}** ${t} module\n\n`;return e.path&&(n+=`**Location:** \`${e.path}\`\n\n`),n+=`**Example:**\n\`\`\`ucode\nimport * as ${e.name} from '${e.name}';\n\`\`\``,n}let oi=null;function si(e,t,n){if(e.type===S.BUILTIN)return null;if(e.type===S.IMPORTED)return function(e,t,n){if(!e.importedFrom||!e.importSpecifier)return null;let r;if(e.importedFrom.startsWith("file://"))r=e.importedFrom;else{if(e.importedFrom.startsWith("builtin://"))return null;r=n.resolveImportPath(e.importedFrom,t.uri)}if(!r)return console.log(`Could not resolve import path: ${e.importedFrom}`),null;const i="*"===e.importSpecifier||"default"===e.importSpecifier?e.name:e.importSpecifier,o=n.findFunctionDefinition(r,i);if(!o)return console.log(`Could not find function definition for: ${i} in ${r}`),{uri:r,range:{start:{line:0,character:0},end:{line:0,character:0}}};try{const e=u.readFileSync(r.replace("file://",""),"utf8"),t={getText:()=>e,positionAt:t=>{const n=Math.max(0,Math.min(t,e.length)),r=e.slice(0,n).split("\n"),i=r.at(-1)??"";return{line:Math.max(0,r.length-1),character:i.length}}};return{uri:r,range:{start:t.positionAt(o.start),end:t.positionAt(o.end)}}}catch(e){return console.error("Error converting position:",e),{uri:r,range:{start:{line:0,character:0},end:{line:0,character:0}}}}}(e,t,n);if(e.type===S.FUNCTION||e.type===S.VARIABLE||e.type===S.PARAMETER){const n=t.positionAt(e.declaredAt),r={start:n,end:n};return{uri:t.uri,range:r}}return null}const ai=(0,t.createConnection)(t.ProposedFeatures.all),ci=new t.TextDocuments(e),li=new Map,ui=new Map;let pi=[],di=!1,mi=!1;function hi(e){return e.startsWith("file://")?decodeURIComponent(e.slice(7)):e}function fi(e){const t=p.normalize(e);return"file://"+encodeURIComponent(t).replace(/%2F/g,"/")}async function gi(e,t){try{const n=await u.promises.readdir(e,{withFileTypes:!0});for(const r of n){const n=p.join(e,r.name);if(r.isDirectory()){if(yi(r.name))continue;await gi(n,t)}else r.isFile()&&r.name.endsWith(".uc")&&t.push(n)}}catch(t){"EACCES"!==t.code&&"EPERM"!==t.code&&ai.console.warn(`Error reading directory ${e}: ${t}`)}}function yi(e){return["node_modules",".git",".vscode","dist","out",".nyc_output","coverage","__pycache__",".pytest_cache","build","target"].includes(e)||e.startsWith(".")}async function Ti(){if(0===pi.length)return void ai.console.log("No workspace folders to scan");ai.console.log(`Starting workspace scan of ${pi.length} folders...`);const t=await async function(e){const t=[];for(const n of e)try{await gi(n,t)}catch(e){ai.console.error(`Error scanning workspace folder ${n}: ${e}`)}return ai.console.log(`Found ${t.length} .uc files in workspace`),t}(pi);t.length>0&&await async function(t){for(const n of t)try{const t=fi(n),r=await u.promises.readFile(n,"utf8"),i=e.create(t,"ucode",1,r);await _i(i),await new Promise(e=>setImmediate(e))}catch(e){}ai.console.log("Completed analysis of workspace .uc files")}(t)}async function _i(e){const n=e.getText(),r=new E(n,{rawMode:!0}),i=r.tokenize(),o=new lr(i,n);o.setComments(r.comments);const s=o.parse();let a=s.errors.map(n=>{const r={severity:t.DiagnosticSeverity.Error,range:{start:e.positionAt(n.start),end:e.positionAt(n.end)},message:n.message,source:"ucode-parser"};return function(e,t){const n=e.getText().split(/\r?\n/),r=t.range.start.line,i=t.range.end.line;for(let e=r;e<=i;e++)if(e<n.length){const t=n[e];if(t&&t.includes("// ucode-lsp disable"))return!0}return!1}(e,r)&&(r.severity===t.DiagnosticSeverity.Error?r.severity=t.DiagnosticSeverity.Warning:r.severity===t.DiagnosticSeverity.Warning&&(r.severity=t.DiagnosticSeverity.Information)),r});if(s.ast){const t=new Ur(e,{enableTypeChecking:!0,enableScopeAnalysis:!0,enableControlFlowAnalysis:!0,enableUnusedVariableDetection:!0,enableShadowingWarnings:!0,workspaceRoot:pi.length>0?pi[0]:process.cwd()}).analyze(s.ast);li.set(e.uri,{result:t,tokens:i,timestamp:Date.now()}),a.push(...t.diagnostics)}else li.delete(e.uri);ai.sendDiagnostics({uri:e.uri,diagnostics:a})}function Ni(e,t,n,r=-1){for(let i=r>=0?r:Math.max(0,t-50);i<t;i++){const r=e.getText({start:{line:i,character:0},end:{line:i+1,character:0}});if(r.includes(n)){const n=r.match(/if\s*\((.+)\)/);if(n&&n[1].includes("&&")||n&&n[1].includes("||"))continue;const o=i+1<t?e.getText({start:{line:i+1,character:0},end:{line:i+2,character:0}}):"";if(/\b(return|continue)\b/.test(r)||/\b(return|continue)\b/.test(o))return!0}}return!1}function Ri(e,n,r,i,o,s){if(s){const a=s.getText({start:{line:r,character:0},end:{line:r+1,character:0}});return{title:e,kind:t.CodeActionKind.QuickFix,diagnostics:[o],edit:{changes:{[i]:[t.TextEdit.replace({start:{line:r,character:0},end:{line:r+1,character:0}},n+a)]}}}}return{title:e,kind:t.CodeActionKind.QuickFix,diagnostics:[o],edit:{changes:{[i]:[t.TextEdit.insert({line:r,character:0},n)]}}}}function Ei(e,n,r,i,o,s){return{title:e,kind:t.CodeActionKind.QuickFix,diagnostics:[s],edit:{changes:{[o]:[t.TextEdit.replace({start:{line:r,character:0},end:{line:r,character:i}},n)]}}}}function bi(e,t,n,r){const i=e.indexOf(t,r);return-1===i?e.replace(t,n):e.substring(0,i)+n+e.substring(i+t.length)}function vi(e,n,r,i,o,s,a){return{title:e,kind:t.CodeActionKind.QuickFix,diagnostics:[a],edit:{changes:{[s]:[t.TextEdit.replace({start:{line:r,character:0},end:{line:i,character:o}},n)]}}}}function Si(e,n,r,i,o){const s=Ci(e,n);if(!s)return null;if(!s.params||0===s.params.length)return null;if(s.leadingJsDoc)return null;const a=o.symbolTable,c=[];for(const e of s.params){const t=a.lookupAtPosition?a.lookupAtPosition(e.name,e.start):a.lookup(e.name);t&&"unknown"!==t.dataType||c.push(e.name)}if(0===c.length)return null;const l=r.positionAt(s.start),u=l.line,p=r.getText({start:{line:u,character:0},end:{line:u,character:l.character}}),d=[`${p}/**`];for(const e of s.params.map(e=>e.name))d.push(`${p} * @param {unknown} ${e}`);d.push(`${p} */`);const m=d.join("\n")+"\n";return{title:`Add JSDoc type annotations for ${c.length} parameter${c.length>1?"s":""}`,kind:t.CodeActionKind.QuickFix,edit:{changes:{[i]:[t.TextEdit.insert({line:u,character:0},m)]}}}}function Ci(e,t){if(!e||"object"!=typeof e)return null;if(e.start>t||e.end<t)return null;let n="FunctionDeclaration"===e.type||"FunctionExpression"===e.type||"ArrowFunctionExpression"===e.type?e:null;for(const r of Object.keys(e)){if("leadingJsDoc"===r)continue;const i=e[r];if(Array.isArray(i)){for(const e of i)if(e&&"object"==typeof e&&"type"in e){const r=Ci(e,t);r&&(n=r)}}else if(i&&"object"==typeof i&&"type"in i){const e=Ci(i,t);e&&(n=e)}}return n}function Ai(e,n,r){const i=[],o=/Unknown type '([^']+)'/.exec(e.message);if(!o)return i;const s=o[1],a=n.offsetAt(e.range.start),c=n.getText({start:e.range.start,end:e.range.end}),l=new RegExp(`\\{${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\}`).exec(c);if(!l)return i;const u=n.positionAt(a+l.index+1),d=n.positionAt(a+l.index+l[0].length-1),m=pi.length>0?pi[0]:p.dirname(r.replace("file://","")),h=new Rr(m),f=h.resolveImportPath(s,r);if(f&&f.startsWith("file://")){const n=h.getDefaultExportPropertyTypes(f);if(n?.propertyTypes&&n.propertyTypes.size>0)for(const[o,a]of n.propertyTypes){const n="string"==typeof a?a:"object";i.push({title:`Replace with import('${s}').${o} (${n})`,kind:t.CodeActionKind.QuickFix,diagnostics:[e],edit:{changes:{[r]:[t.TextEdit.replace({start:u,end:d},`import('${s}').${o}`)]}}})}i.push({title:`Replace with import('${s}')`,kind:t.CodeActionKind.QuickFix,diagnostics:[e],edit:{changes:{[r]:[t.TextEdit.replace({start:u,end:d},`import('${s}')`)]}}})}return i}function Oi(e,n,r,i,o){const s=[];if(!e.code||!e.data)return s;const{code:a,data:c}=e,l=e.range.start.line,u=i.match(/^(\s*)/)?.[1]||"",p=i.trim(),d=i.length,m=function(e,t,n){const r={inFunction:!1,inLoop:!1,inLoopHeader:!1,inCondition:!1,conditionOwnerLine:-1,enclosingControl:null,enclosingControlBody:null,enclosingStatementLine:-1,enclosingFunctionLine:-1};if(!e)return r;const i=t.offsetAt(n);return function e(n,o,s,a,c,l){if(!n||"object"!=typeof n||"number"!=typeof n.start)return;if(i<n.start||i>n.end)return;const u="FunctionDeclaration"===n.type||"FunctionExpression"===n.type||"ArrowFunctionExpression"===n.type,p="ForStatement"===n.type||"ForInStatement"===n.type||"WhileStatement"===n.type||"DoWhileStatement"===n.type,d=p||"IfStatement"===n.type,m=u||o,h=!u&&(p||s);if(r.inFunction=m,u&&(r.enclosingFunctionLine=t.positionAt(n.start).line),r.inLoop=h,r.inLoopHeader=a,r.inCondition=c,l&&(r.conditionOwnerLine=t.positionAt(l.start).line),d){const e="IfStatement"===n.type?n.consequent:n.body;e&&i>=e.start&&i<=e.end&&(r.enclosingControl=n,r.enclosingControlBody=e)}("ExpressionStatement"===n.type||"ReturnStatement"===n.type||"VariableDeclaration"===n.type||"IfStatement"===n.type||"WhileStatement"===n.type||"ForStatement"===n.type||"ForInStatement"===n.type||"DoWhileStatement"===n.type||"SwitchStatement"===n.type||"TryStatement"===n.type||"ThrowStatement"===n.type||"BreakStatement"===n.type||"ContinueStatement"===n.type)&&(r.enclosingStatementLine=t.positionAt(n.start).line);for(const t of Object.keys(n)){if("type"===t||"start"===t||"end"===t)continue;const r=n[t],i=p&&"body"!==t,o=i?s:h,u=!!i||(!p||"body"!==t)&&a,f=d&&"test"===t||p&&("init"===t||"update"===t||"right"===t),g=!!f||(!d||"body"!==t&&"consequent"!==t&&"alternate"!==t)&&c,y=f?n:d&&!f?null:l;if(Array.isArray(r))for(const t of r)t&&"object"==typeof t&&"number"==typeof t.start&&e(t,m,o,u,g,y);else r&&"object"==typeof r&&"number"==typeof r.start&&e(r,m,o,u,g,y)}}(e,!1,!1,!1,!1,null),r}(o,n,e.range.start),h=c.variableName||null,f=c.expectedType||c.expectedTypes?.[0]||"",g=m.enclosingStatementLine,y=g>=0&&g<l,T=m.inCondition?null:function(e){const t=e.match(/^(\s*)/)?.[1]||"",n=e.trimStart(),r=["else if","for","while","if"];for(const e of r){if(!n.startsWith(e))continue;const r=n[e.length];if(r&&" "!==r&&"\t"!==r&&"("!==r)continue;const i=n.indexOf("(",e.length);if(-1===i)continue;let o=0,s=-1;for(let e=i;e<n.length;e++)if("("===n[e])o++;else if(")"===n[e]&&(o--,0===o)){s=e;break}if(-1===s)continue;const a=n.substring(0,s+1),c=n.substring(s+1).trim();return c.startsWith("{")||!c?null:{indent:t,prefix:a,body:c}}if(n.startsWith("else")){const e=n.substring(4).trim();return e.startsWith("{")||e.startsWith("if")||!e?null:{indent:t,prefix:"else",body:e}}return null}(i),_=T||m.inCondition?null:function(e,t){for(let n=t-1;n>=Math.max(0,t-3);n--){const t=e.getText({start:{line:n,character:0},end:{line:n+1,character:0}}).replace(/\r?\n$/,""),r=t.trim();if(!r)continue;const i=["for","while","if","else if"];for(const e of i){if(!r.startsWith(e))continue;const i=r[e.length];if((!i||" "===i||"\t"===i||"("===i)&&r.endsWith(")"))return{parentIndent:t.match(/^(\s*)/)?.[1]||"",prefix:r,parentLine:n}}if("else"===r)return{parentIndent:t.match(/^(\s*)/)?.[1]||"",prefix:"else",parentLine:n};break}return null}(n,l),N=null!=m.enclosingControlBody&&"BlockStatement"!==m.enclosingControlBody.type,R=!m.inCondition&&(N||!(!T&&!_)),E=function(e){return!e.actualType||("string"==typeof e.actualType?e.actualType:"").split(" | ").map(e=>e.trim()).includes("null")}(c);if("nullable-argument"!==a&&"incompatible-function-argument"!==a&&"nullable-in-operator"!==a)return s;const b=p.match(/^(?:let|const)\s+(\w+)\s*=/)?.[1],v=!!b&&function(e,t,n){const r=e.lineCount,i=new RegExp(`\\b${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`);for(let n=t+1;n<r;n++){const t=e.getText({start:{line:n,character:0},end:{line:n+1,character:0}});if(i.test(t))return!0}return!1}(n,l,b);if(h){const a=h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N=e.range.start.character;let b=null;const S=new RegExp(`(?:let|const|var)\\s+${a}\\s*=[^;]*;`),C=i.match(S);if(C&&null!=C.index&&C.index+C[0].length<=N&&(b=C.index+C[0].length),null==b){const e=new RegExp(`function\\s+\\w*\\s*\\([^)]*\\b${a}\\b[^)]*\\)\\s*\\{`),t=i.match(e);t&&null!=t.index&&t.index+t[0].length<=N&&(b=t.index+t[0].length)}if(E){const o=`${h} == null`,a=`${h} != null`,c=`Add null guard for \`${h}\``,f=`Wrap in null guard for \`${h}\``;if(Ni(n,l,o,m.enclosingFunctionLine))return s;const N=m.inLoop?"continue":"return";if(y){const t=g,i=n.getText({start:{line:t,character:0},end:{line:t+1,character:0}}).replace(/\r?\n$/,""),a=i.match(/^(\s*)/)?.[1]||"";s.push(Ri(c,`${a}if (${o})\n${a}\treturn;\n`,t,r,e,n))}else if(m.inCondition){const t=m.conditionOwnerLine>=0?m.conditionOwnerLine:l,i=n.getText({start:{line:t,character:0},end:{line:t+1,character:0}}).replace(/\r?\n$/,""),a=i.match(/^(\s*)/)?.[1]||"";s.push(Ri(c,`${a}if (${o})\n${a}\t${N};\n`,t,r,e,n))}else if(null!=b)s.push({title:c,kind:t.CodeActionKind.QuickFix,diagnostics:[e],edit:{changes:{[r]:[t.TextEdit.insert({line:l,character:b},` if (${o}) ${N};`)]}}});else if(T)s.push(Ei(c,`${T.indent}${T.prefix} {\n${T.indent}\tif (${o}) ${N};\n${T.indent}\t${T.body}\n${T.indent}}`,l,d,r,e));else if(_){const t=_;s.push(vi(c,`${t.parentIndent}${t.prefix} {\n${u}if (${o}) ${N};\n${i}\n${t.parentIndent}}`,t.parentLine,l,d,r,e))}else m.inLoop?s.push(Ri(c,`${u}if (${o})\n${u}\tcontinue;\n`,l,r,e,n)):m.inFunction&&s.push(Ri(c,`${u}if (${o})\n${u}\treturn;\n`,l,r,e,n));y||v||m.inLoopHeader||m.inCondition||R||null!=b||p.endsWith("{")||s.push(Ei(f,`${u}if (${a}) {\n${u}\t${p}\n${u}}`,l,d,r,e))}else{let a=(c.expectedTypes||f.split(" | ").map(e=>e.trim())).filter(e=>"null"!==e);if(0===a.length)return s;if(o&&h){const t=n.offsetAt(e.range.start),r=function(e,t,n,r){if(!e||!t)return null;if(t.includes("."))return null;const i=[];if(function e(r){if(r&&"object"==typeof r&&!("number"==typeof r.start&&r.start<n&&"number"==typeof r.end&&r.end<n)&&("FunctionDeclaration"!==r.type&&"FunctionExpression"!==r.type&&"ArrowFunctionExpression"!==r.type||n>=r.start&&n<=r.end)){if("CallExpression"===r.type&&"Identifier"===r.callee?.type){const e=r.callee.name,n=Ii[e];if(n&&r.arguments)for(let e=0;e<r.arguments.length;e++){const o=r.arguments[e],s=n[e];"Identifier"===o?.type&&o.name===t&&s&&i.push(s)}}for(const t of Object.keys(r)){if("type"===t||"start"===t||"end"===t)continue;const n=r[t];if(Array.isArray(n))for(const t of n)e(t);else n&&"object"==typeof n&&"string"==typeof n.type&&e(n)}}}(e),0===i.length)return null;let o=new Set(r);for(const e of i){const t=new Set(e);o=new Set([...o].filter(e=>t.has(e)))}const s=[...o];return s.length>0&&s.length<r.length?s:null}(o,h,t,a);r&&(a=r)}const N=a.length>1,E=N?a.map(e=>`type(${h}) != "${e}"`).join(" && "):`type(${h}) != "${a[0]}"`,S=N?a.map(e=>`type(${h}) == "${e}"`).join(" || "):`type(${h}) == "${a[0]}"`;if(Ni(n,l,E,m.enclosingFunctionLine))return s;const C=m.inLoop?"continue":"return";if(y){const t=g,i=n.getText({start:{line:t,character:0},end:{line:t+1,character:0}}).replace(/\r?\n$/,""),o=i.match(/^(\s*)/)?.[1]||"";s.push(Ri(`Add type guard for \`${h}\``,`${o}if (${E})\n${o}\treturn;\n`,t,r,e,n))}else if(m.inCondition){const t=m.conditionOwnerLine>=0?m.conditionOwnerLine:l,i=n.getText({start:{line:t,character:0},end:{line:t+1,character:0}}).replace(/\r?\n$/,""),o=i.match(/^(\s*)/)?.[1]||"";s.push(Ri(`Add type guard for \`${h}\``,`${o}if (${E})\n${o}\t${C};\n`,t,r,e,n))}else if(null!=b)s.push({title:`Add type guard for \`${h}\``,kind:t.CodeActionKind.QuickFix,diagnostics:[e],edit:{changes:{[r]:[t.TextEdit.insert({line:l,character:b},` if (${E}) ${C};`)]}}});else if(T)s.push(Ei(`Add type guard for \`${h}\``,`${T.indent}${T.prefix} {\n${T.indent}\tif (${E}) ${C};\n${T.indent}\t${T.body}\n${T.indent}}`,l,d,r,e));else if(_){const t=_;s.push(vi(`Add type guard for \`${h}\``,`${t.parentIndent}${t.prefix} {\n${u}if (${E}) ${C};\n${i}\n${t.parentIndent}}`,t.parentLine,l,d,r,e))}else m.inLoop?s.push(Ri(`Add type guard for \`${h}\``,`${u}if (${E})\n${u}\tcontinue;\n`,l,r,e,n)):m.inFunction&&s.push(Ri(`Add type guard for \`${h}\``,`${u}if (${E})\n${u}\treturn;\n`,l,r,e,n));if(null!=c.fallbackStart&&null!=c.fullExprStart){const o=h||n.getText(e.range).trim(),p=n.getText({start:n.positionAt(c.fallbackStart),end:n.positionAt(c.fallbackEnd)}),m=n.getText({start:n.positionAt(c.fullExprStart),end:n.positionAt(c.fullExprEnd)}),f=xi(n),T=N?a.map(e=>`type(${f}) != "${e}"`).join(" && "):`type(${f}) != "${a[0]}"`,_=n.positionAt(c.fullExprStart).character,R=bi(i,m,f,_);if(R!==i)if(y){const i=g,a=n.getText({start:{line:i,character:0},end:{line:i+1,character:0}}).replace(/\r?\n$/,""),c=a.match(/^(\s*)/)?.[1]||"";s.push({title:"Add type guard with default",kind:t.CodeActionKind.QuickFix,diagnostics:[e],edit:{changes:{[r]:[t.TextEdit.insert({line:i,character:0},`${c}let ${f} = ${o};\n${c}if (${T})\n${c}\t${f} = ${p};\n`),t.TextEdit.replace({start:{line:l,character:0},end:{line:l,character:d}},R)]}}})}else s.push(Ei("Add type guard with default",`${u}let ${f} = ${o};\n${u}if (${T})\n${u}\t${f} = ${p};\n${R}`,l,d,r,e))}y||v||m.inLoopHeader||m.inCondition||R||null!=b||p.endsWith("{")||s.push(Ei(`Wrap in type guard for \`${h}\``,`${u}if (${S}) {\n${u}\t${p}\n${u}}`,l,d,r,e))}}else if(!m.inLoopHeader){const a=n.getText(e.range);if(!a)return s;if(!R&&o&&null!=c.argumentOffset){const t=function(e,t){const n=Pi(e,t);return n?Di(n):null}(o,c.argumentOffset);if(t){const i=t.expectedTypes.filter(e=>"null"!==e);if(0===i.length)return s;const o=i.length>1,a=i.join(" | "),c=o?i.map(e=>`type(${t.varName}) != "${e}"`).join(" && "):`type(${t.varName}) != "${a}"`;if(!Ni(n,l,c,m.enclosingFunctionLine)){if(y){const i=g,o=n.getText({start:{line:i,character:0},end:{line:i+1,character:0}}).replace(/\r?\n$/,""),a=o.match(/^(\s*)/)?.[1]||"";s.push(Ri(`Add type guard for \`${t.varName}\``,`${a}if (${c})\n${a}\treturn;\n`,i,r,e,n))}else if(m.inCondition){const i=m.conditionOwnerLine>=0?m.conditionOwnerLine:l,o=n.getText({start:{line:i,character:0},end:{line:i+1,character:0}}).replace(/\r?\n$/,""),a=o.match(/^(\s*)/)?.[1]||"",u=m.inLoop?"continue":"return";s.push(Ri(`Add type guard for \`${t.varName}\``,`${a}if (${c})\n${a}\t${u};\n`,i,r,e,n))}else m.inLoop?s.push(Ri(`Add type guard for \`${t.varName}\``,`${u}if (${c})\n${u}\tcontinue;\n`,l,r,e,n)):m.inFunction&&s.push(Ri(`Add type guard for \`${t.varName}\``,`${u}if (${c})\n${u}\treturn;\n`,l,r,e,n));return s}}}const p=xi(n),h=m.inLoop?"continue":"return",N=(c.expectedTypes||f.split(" | ").map(e=>e.trim())).filter(e=>"null"!==e);if(!E&&0===N.length)return s;const b=N.length>1,v=E?`${p} == null`:b?N.map(e=>`type(${p}) != "${e}"`).join(" && "):`type(${p}) != "${f}"`,S=a.length>30?a.substring(0,27)+"...":a,C=E?`Extract \`${S}\` and add null guard`:`Extract \`${S}\` and add type guard`,A=e.range.start.character;if(y){const o=g,u=n.getText({start:{line:o,character:0},end:{line:o+1,character:0}}).replace(/\r?\n$/,""),m=u.match(/^(\s*)/)?.[1]||"";let h=a,y=A;null!=c.fullExprStart&&null!=c.fullExprEnd&&(h=n.getText({start:n.positionAt(c.fullExprStart),end:n.positionAt(c.fullExprEnd)}),y=n.positionAt(c.fullExprStart).character);const T=bi(i,h,p,y);if(T!==i){if(null!=c.fallbackStart){const i=n.getText({start:n.positionAt(c.fallbackStart),end:n.positionAt(c.fallbackEnd)}),u=E?`${p} == null`:b?N.map(e=>`type(${p}) != "${e}"`).join(" && "):`type(${p}) != "${f}"`;s.push({title:"Add type guard with default",kind:t.CodeActionKind.QuickFix,diagnostics:[e],edit:{changes:{[r]:[t.TextEdit.insert({line:o,character:0},`${m}let ${p} = ${a};\n${m}if (${u})\n${m}\t${p} = ${i};\n`),t.TextEdit.replace({start:{line:l,character:0},end:{line:l,character:d}},T)]}}})}s.push({title:C,kind:t.CodeActionKind.QuickFix,diagnostics:[e],edit:{changes:{[r]:[t.TextEdit.insert({line:o,character:0},`${m}let ${p} = ${a};\n${m}if (${v})\n${m}\treturn;\n`),t.TextEdit.replace({start:{line:l,character:0},end:{line:l,character:d}},T)]}}})}}else if(T){const t=i.indexOf(T.body),n=bi(T.body,a,p,A-(t>=0?t:0));n!==T.body&&s.push(Ei(C,`${T.indent}${T.prefix} {\n${T.indent}\tlet ${p} = ${a};\n${T.indent}\tif (${v}) ${h};\n${T.indent}\t${n}\n${T.indent}}`,l,d,r,e))}else if(_){const t=_,n=bi(i,a,p,A);n!==i&&s.push(vi(C,`${t.parentIndent}${t.prefix} {\n${u}let ${p} = ${a};\n${u}if (${v}) ${h};\n${n}\n${t.parentIndent}}`,t.parentLine,l,d,r,e))}else if(m.inLoop||m.inFunction){const t=bi(i,a,p,A);t!==i&&s.push(Ei(C,`${u}let ${p} = ${a};\n${u}if (${v})\n${u}\t${h};\n${t}`,l,d,r,e))}else{const t=bi(i,a,p,A);if(t!==i){const n=E?`${p} != null`:b?N.map(e=>`type(${p}) == "${e}"`).join(" || "):`type(${p}) == "${f}"`;s.push(Ei(C,`${u}let ${p} = ${a};\n${u}if (${n}) {\n${u}\t${t.trim()}\n${u}}`,l,d,r,e))}}}return s}ai.onInitialize(e=>{ai.console.log("ucode language server initializing...");const n=e.capabilities;di=!(!n.workspace||!n.workspace.configuration),mi=!(!n.workspace||!n.workspace.workspaceFolders),e.workspaceFolders?(pi=e.workspaceFolders.map(e=>hi(e.uri)),ai.console.log(`Initialized with ${pi.length} workspace folders: ${pi.join(", ")}`)):e.rootUri?(pi=[hi(e.rootUri)],ai.console.log(`Initialized with root URI: ${pi[0]}`)):e.rootPath&&(pi=[e.rootPath],ai.console.log(`Initialized with root path: ${pi[0]}`));const r={capabilities:{textDocumentSync:t.TextDocumentSyncKind.Incremental,completionProvider:{resolveProvider:!0,triggerCharacters:[".","'",'"',",","@","{"],allCommitCharacters:["(","["],completionItem:{labelDetailsSupport:!0}},hoverProvider:!0,definitionProvider:!0,codeActionProvider:{codeActionKinds:[t.CodeActionKind.QuickFix]}}};return mi&&(r.capabilities.workspace={workspaceFolders:{supported:!0,changeNotifications:!0}}),r}),ai.onInitialized(async()=>{di&&ai.client.register(t.DidChangeConfigurationNotification.type,void 0),mi&&ai.workspace.onDidChangeWorkspaceFolders(async e=>{ai.console.log("Workspace folder change event received.");for(const t of e.removed){const e=hi(t.uri),n=pi.indexOf(e);n>-1&&(pi.splice(n,1),ai.console.log(`Removed workspace folder: ${e}`))}for(const t of e.added){const e=hi(t.uri);pi.includes(e)||(pi.push(e),ai.console.log(`Added workspace folder: ${e}`))}await Ti()});try{await ai.client.register(t.DidChangeWatchedFilesNotification.type,{watchers:[{globPattern:"**/*.uc",kind:7}]}),ai.console.log("File watcher registered for .uc files")}catch(e){ai.console.warn(`Failed to register file watcher: ${e}`)}Ti()}),ci.onDidClose(e=>{}),ci.onDidChangeContent(async e=>{const t=e.document.uri,n=ui.get(t);n&&clearTimeout(n),ui.set(t,setTimeout(async()=>{ui.delete(t),await _i(e.document)},50))}),ci.onDidOpen(async e=>{await _i(e.document)}),ai.onDidChangeWatchedFiles(async n=>{for(const r of n.changes){const n=hi(r.uri);if(n.endsWith(".uc"))switch(r.type){case t.FileChangeType.Created:case t.FileChangeType.Changed:try{const t=await u.promises.readFile(n,"utf8"),i=e.create(r.uri,"ucode",1,t);await _i(i)}catch(e){li.delete(r.uri)}break;case t.FileChangeType.Deleted:li.delete(r.uri)}}}),ai.onHover(e=>{const t=li.get(e.textDocument.uri);return t?.result?jr(e,ci,t.result,t.tokens):null}),ai.onCompletion(async e=>{let r=li.get(e.textDocument.uri),i=r?.result;if(!i){const t=ci.get(e.textDocument.uri);t&&(await _i(t),r=li.get(e.textDocument.uri),i=r?.result)}return function(e,r,i,o){i.console.log(`[COMPLETION_DEBUG] analysisResult provided: ${!!o}, symbolTable: ${!!o?.symbolTable}`);const s=r.get(e.textDocument.uri);if(!s)return i.console.log(`[COMPLETION] No document found for URI: ${e.textDocument.uri}`),Xr(o,i);i.console.log(`[COMPLETION] Document found, analysisResult: ${!!o}`);const a=e.position,c=s.getText(),d=s.offsetAt(a);try{const r=new E(c,{rawMode:!0}),s=r.tokenize(),a=function(e,t,n){for(const r of n)if(t>=r.pos&&t<=r.end){if(!String(r.value).startsWith("*"))continue;const n=e.substring(r.pos,t);if(n.match(/@(\w*)$/))return{kind:"tag"};const i=[/@param\s+\{[^}]*$/,/@param\s+\w+\s+\{?[^-]*$/,/@returns?\s+\{?[^-]*$/];for(const e of i)if(e.test(n))return{kind:"type"};return null}return null}(c,d,r.comments);if(a)return function(e){if("tag"===e.kind)return[{label:"param",kind:t.CompletionItemKind.Keyword,detail:"@param {type} name - description",insertText:"param ",sortText:"0param"},{label:"returns",kind:t.CompletionItemKind.Keyword,detail:"@returns {type} description",insertText:"returns ",sortText:"0returns"},{label:"typedef",kind:t.CompletionItemKind.Keyword,detail:"@typedef {object} TypeName",insertText:"typedef ",sortText:"0typedef"},{label:"property",kind:t.CompletionItemKind.Keyword,detail:"@property {type} name - description",insertText:"property ",sortText:"0property"},{label:"type",kind:t.CompletionItemKind.Keyword,detail:"@type {type}",insertText:"type ",sortText:"0type"},{label:"description",kind:t.CompletionItemKind.Keyword,detail:"@description text",insertText:"description ",sortText:"0description"}];const n=[],r=["string","number","integer","boolean","array","object","function","null"];for(const e of r)n.push({label:e,kind:t.CompletionItemKind.TypeParameter,sortText:`1${e}`});for(const e of Object.keys(Pn))n.push({label:`module:${e}`,kind:t.CompletionItemKind.Module,detail:`${e} module`,sortText:`2module:${e}`});for(const e of Object.keys(xn))n.push({label:e,kind:t.CompletionItemKind.Class,detail:`${e} object type`,sortText:`3${e}`});return n.push({label:"import('module').type",kind:t.CompletionItemKind.Snippet,detail:"Cross-file type reference",insertText:"import('$1').$2",insertTextFormat:t.InsertTextFormat.Snippet,sortText:"4import"}),n}(a);const m=function(e,t){for(let n=0;n<t.length;n++)if(t[n].type===l.TK_IMPORT){let r=-1,i=-1,o=-1,s="";for(let e=n+1;e<t.length;e++){const n=t[e];if(n.type===l.TK_LBRACE&&-1===r)r=e;else if(n.type===l.TK_FROM&&-1===i&&-1!==r)i=e;else{if(n.type===l.TK_STRING&&-1===o&&-1!==i){o=e,s=n.value;break}if(n.type===l.TK_IMPORT)break}}if(-1!==r&&-1!==i&&-1!==o){const n=t[r],o=t[i];if(e>n.pos&&e<o.pos){const e=[];for(let n=r+1;n<i;n++)t[n].type===l.TK_LABEL&&e.push(t[n].value);return{moduleName:s,alreadyImported:e}}}}}(d,s);if(m)return i.console.log(`Destructured import context detected: ${JSON.stringify(m)}`),function(e,n=[]){try{const r=_r(e);if(0===r.length)return[];const i=[];for(const o of r)if(!n.includes(o.name)){let n,r,s,a;switch(o.type){case"function":n=t.CompletionItemKind.Function,r=`${o.name}() from ${e}`,s="1",a=`**${o.name}** function from the **${e}** module\n\n**Usage:**\n\`\`\`ucode\nimport { ${o.name} } from '${e}';\n${o.name}(/* parameters */);\n\`\`\``;break;case"constant":n=t.CompletionItemKind.Constant,r=`${o.name} from ${e}`,s="2",a=`**${o.name}** constant from the **${e}** module\n\n**Usage:**\n\`\`\`ucode\nimport { ${o.name} } from '${e}';\nconsole.log(${o.name});\n\`\`\``;break;case"resource":n=t.CompletionItemKind.Value,r=`${o.name} resource from ${e}`,s="3",a=`**${o.name}** resource from the **${e}** module\n\n**Usage:**\n\`\`\`ucode\nimport { ${o.name} } from '${e}';\n// Use as resource\n\`\`\``;break;default:n=t.CompletionItemKind.Value,r=`${o.name} from ${e}`,s="4",a=`**${o.name}** from the **${e}** module\n\n**Usage:**\n\`\`\`ucode\nimport { ${o.name} } from '${e}';\n// Usage depends on actual type\n\`\`\``}i.push({label:o.name,kind:n,detail:r,documentation:{kind:t.MarkupKind.Markdown,value:a},insertText:o.name,sortText:`${s}_${o.name}`})}return i}catch(t){return console.warn(`Failed to get destructured import completions for ${e}:`,t),[]}}(m.moduleName,m.alreadyImported);const h=function(e,t,n){let r=-1,i=-1,o=-1;for(let n=t.length-1;n>=0;n--){const s=t[n];if(!(s.pos>e)){if(s.type===l.TK_STRING&&-1===o&&e>=s.pos&&e<=s.end&&(o=n),s.type===l.TK_FROM&&-1===i&&(i=n),s.type===l.TK_IMPORT&&-1===r){r=n;break}if(s.type===l.TK_SCOL||s.type===l.TK_RBRACE||s.type===l.TK_NEWLINE)break}}if(-1!==r&&-1!==i&&-1!==o&&r<i&&i<o){const r=t[o],i=r.pos+1,s=Math.min(r.end-1,e);return{inStringLiteral:!0,currentPath:n.substring(i,s)}}if(-1!==r&&-1!==i&&-1===o){const n=t[i];if(e>=n.end&&e<=n.end+10)return{inStringLiteral:!1}}}(d,s,c);if(h){if(i.console.log(`Import context detected: ${JSON.stringify(h)}`),h.currentPath&&(h.currentPath.startsWith("./")||h.currentPath.startsWith("../"))){const n=e.textDocument.uri;return function(e,n,r){try{const i=new Vr.URL(n).pathname,o=p.dirname(i);let s;if(e.startsWith("./")||e.startsWith("../")){const t=e.endsWith("/")?e:p.dirname(e);s=p.resolve(o,t)}else s=o;if(r.console.log(`[FS_COMPLETION] Document: ${i}, Target dir: ${s}, Current path: ${e}`),!u.existsSync(s)||!u.statSync(s).isDirectory())return r.console.log(`[FS_COMPLETION] Target directory does not exist: ${s}`),[];const a=u.readdirSync(s),c=[],l=e.lastIndexOf("/"),d=l>=0?e.substring(l+1):e;for(const e of a){const n=p.join(s,e),r=u.statSync(n);e.startsWith(".")&&!d.startsWith(".")||d&&!e.toLowerCase().startsWith(d.toLowerCase())||(r.isDirectory()?c.push({label:e+"/",kind:t.CompletionItemKind.Folder,detail:"Directory",sortText:"0_"+e,insertText:e+"/",documentation:{kind:t.MarkupKind.Markdown,value:`📁 **${e}/**\n\nDirectory`}}):e.endsWith(".uc")&&c.push({label:e,kind:t.CompletionItemKind.File,detail:"uCode module",sortText:"1_"+e,insertText:e,documentation:{kind:t.MarkupKind.Markdown,value:`📄 **${e}**\n\nuCode module file`}}))}return r.console.log(`[FS_COMPLETION] Generated ${c.length} file system completions`),c}catch(e){return r.console.log(`[FS_COMPLETION] Error: ${e instanceof Error?e.message:String(e)}`),[]}}(h.currentPath,n,i)}return function(){const e=Tr(),n=[];for(const r of e){const e="builtin"===r.source,i=e?"ucode builtin module":"ucode system module",o=e?"0_":"1_";n.push({label:r.name,kind:t.CompletionItemKind.Module,detail:i,documentation:{kind:t.MarkupKind.Markdown,value:ii(r)},insertText:r.name,sortText:`${o}${r.name}`})}return n}()}const f=function(e,t){let n=-1;for(let r=t.length-1;r>=0;r--){const i=t[r];if(i.type===l.TK_DOT&&i.pos<=e){n=r;break}}if(n<=0)return;const r=t[n];if(e<r.pos||e>r.end)return;const i=[];let o,s=n-1;for(;s>=0;){const e=t[s];if(e.type===l.TK_LABEL){if(s+1<t.length){const n=t[s+1];if(n.type===l.TK_DOT&&e.end===n.pos){if(i.unshift(e.value),s>0){const n=t[s-1];if(n.type===l.TK_DOT&&n.end===e.pos){s-=2;continue}}break}break}break}if(e.type===l.TK_RPAREN){let e=1,n=s-1;for(;n>=0&&e>0;)t[n].type===l.TK_RPAREN?e++:t[n].type===l.TK_LPAREN&&e--,n--;if(n>=0&&t[n].type===l.TK_LABEL){const e=t[n].value;let r;n>=2&&t[n-1].type===l.TK_DOT&&t[n-2].type===l.TK_LABEL&&(r=t[n-2].value);const i=Un(e,r);if(i){o=i;break}}break}break}if(o)return{objectName:"__call_chain__",resolvedObjectType:o};if(0===i.length)return;const a=i[0];if(!a)return;const c=i.slice(1),u={objectName:a};return c.length>0&&(u.propertyChain=c),u}(d,s);if(f){const{objectName:e,propertyChain:r,resolvedObjectType:s}=f;if(i.console.log(`Member expression detected for: ${e}${r?`, chain: ${r.join(".")}`:""}${s?`, resolvedObjectType: ${s}`:""}`),i.console.log(`[DEBUG] objectName: "${e}", propertyChain: ${JSON.stringify(r)}`),s){const e=xn[s],n=[],r=xn[s]?.isPropertyBased??!1;for(const i of e.getMethodNames()){const o=e.getMethodDocumentation(i),a={label:i,kind:r?t.CompletionItemKind.Property:t.CompletionItemKind.Method,detail:`${s} ${r?"property":"method"}`,insertText:i};pt(o)&&(a.documentation={kind:t.MarkupKind.Markdown,value:o.value}),n.push(a)}return i.console.log(`Returning ${n.length} call-chain completions for ${s}`),n}const a=function(e,n){if(!n||!n.symbolTable)return[];const r=Yr(e,n);if(!r||!r.dataType)return[];let i=null;if("object"==typeof r.dataType&&"moduleName"in r.dataType){const e=r.dataType.moduleName;Mn(e)&&(i=e)}if(!i)return[];const o=xn[i],s=[];for(const e of o.getMethodNames()){const n=o.getMethodDocumentation(e),r="exception"===i||"fs.statvfs"===i,a={label:e,kind:r?t.CompletionItemKind.Property:t.CompletionItemKind.Method,detail:`${i} ${r?"property":"method"}`,insertText:e};pt(n)&&(a.documentation={kind:t.MarkupKind.Markdown,value:n.value}),s.push(a)}return s}(e,o);if(a.length>0)return i.console.log(`Returning ${a.length} object type completions for ${e}`),a;const c=function(e,n){if(!n||!n.symbolTable)return[];const r=Yr(e,n);if(!r)return[];let i;if(r.dataType&&"object"==typeof r.dataType&&"moduleName"in r.dataType){const e=r.dataType.moduleName;if("nl80211-const"===e||"rtnl-const"===e)return[];wn(e)&&(i=e)}if(!i&&r.type===S.IMPORTED&&r.importedFrom&&(i=r.importedFrom),!i||!wn(i))return[];const o=Pn[i],s=[];for(const e of o.getFunctionNames()){const n=o.getFunctionDocumentation(e),r={label:e,kind:t.CompletionItemKind.Function,detail:`${i} module function`,sortText:`0_${e}`,insertText:e};pt(n)&&(r.documentation={kind:t.MarkupKind.Markdown,value:n.value}),s.push(r)}for(const e of o.getConstantNames()){const n=o.getConstantDocumentation(e),r={label:e,kind:t.CompletionItemKind.Constant,detail:`${i} module constant`,sortText:`1_${e}`,insertText:e,insertTextFormat:t.InsertTextFormat.PlainText};pt(n)&&(r.documentation={kind:t.MarkupKind.Markdown,value:n.value}),s.push(r)}return s}(e,o);if(c.length>0)return i.console.log(`Returning ${c.length} module completions for ${e}`),c;const l=function(e,n){if(console.log(`[NL80211_CONST_COMPLETION] Checking nl80211 constants completion for: ${e}`),!n||!n.symbolTable)return console.log(`[NL80211_CONST_COMPLETION] No analysisResult or symbolTable for ${e}`),[];const r=Yr(e,n);if(!r)return console.log(`[NL80211_CONST_COMPLETION] Symbol not found: ${e}`),[];if(console.log(`[NL80211_CONST_COMPLETION] Symbol found: ${e}, dataType: ${JSON.stringify(r.dataType)}`),r.dataType&&"object"==typeof r.dataType&&"moduleName"in r.dataType&&"nl80211-const"===r.dataType.moduleName){console.log(`[NL80211_CONST_COMPLETION] NL80211 constants object detected for ${e}`);const n=Ot(),r=[];for(const e of n){const n=Lt(e);n&&r.push({label:e,kind:t.CompletionItemKind.Constant,detail:`nl80211 constant: ${n.type}`,documentation:{kind:t.MarkupKind.Markdown,value:It(e)},insertText:e})}return console.log(`[NL80211_CONST_COMPLETION] Generated ${r.length} nl80211 constants completions: ${n.slice(0,5).join(", ")}...`),r}return console.log(`[NL80211_CONST_COMPLETION] Not an nl80211 constants object: ${e}`),[]}(e,o);if(l.length>0)return i.console.log(`Returning ${l.length} nl80211 constants completions for ${e}`),l;const d=function(e,n){if(console.log(`[RTNL_CONST_COMPLETION] Checking rtnl constants completion for: ${e}`),!n||!n.symbolTable)return console.log(`[RTNL_CONST_COMPLETION] No analysisResult or symbolTable for ${e}`),[];const r=Yr(e,n);if(!r)return console.log(`[RTNL_CONST_COMPLETION] Symbol not found: ${e}`),[];if(console.log(`[RTNL_CONST_COMPLETION] Symbol found: ${e}, dataType: ${JSON.stringify(r.dataType)}`),r.dataType&&"object"==typeof r.dataType&&"moduleName"in r.dataType&&"rtnl-const"===r.dataType.moduleName){console.log(`[RTNL_CONST_COMPLETION] RTNL constants object detected for ${e}`);const n=Tt(),r=[];for(const e of n)try{const n=_t(e);n&&r.push({label:e,kind:t.CompletionItemKind.Constant,detail:`rtnl constant: ${n.type}`,documentation:{kind:t.MarkupKind.Markdown,value:Nt(e)},insertText:e})}catch(t){console.log(`[RTNL_CONST_COMPLETION] Error creating completion for ${e}:`,t)}return console.log(`[RTNL_CONST_COMPLETION] Generated ${r.length} rtnl constants completions: ${n.slice(0,5).join(", ")}...`),r}return console.log(`[RTNL_CONST_COMPLETION] Not an rtnl constants object: ${e}`),[]}(e,o);if(d.length>0)return i.console.log(`Returning ${d.length} rtnl constants completions for ${e}`),d;const m=function(e,r){const i=n(9896);if(!r||!r.symbolTable)return[];const o=Yr(e,r);if(!o)return[];if(o.type===S.IMPORTED&&o.importedFrom&&o.dataType&&"object"==typeof o.dataType&&"isDefaultImport"in o.dataType&&o.dataType.isDefaultImport)try{let e;if(o.importedFrom.startsWith("file://"))e=o.importedFrom.replace("file://","");else if(o.importedFrom.startsWith("./")||o.importedFrom.startsWith("../"))e=p.resolve(process.cwd(),o.importedFrom);else if(/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)+$/.test(o.importedFrom)){const t="./"+o.importedFrom.replace(/\./g,"/")+".uc";e=p.resolve(process.cwd(),t)}else e=o.importedFrom;if(!i.existsSync(e))return[];const n=zr(i.readFileSync(e,"utf8"),e),r=[];for(const i of n)r.push({label:i.name,kind:ni(i.type),detail:`${i.type} from default export`,sortText:"0_"+i.name,documentation:{kind:t.MarkupKind.Markdown,value:`**${i.name}**\n\n${i.type} from default export of \`${p.basename(e)}\``}});return r}catch(e){return[]}return[]}(e,o);if(m.length>0)return i.console.log(`Returning ${m.length} default import completions for ${e}`),m;if(!r||0===r.length){const r=function(e,r){if(!r||!r.symbolTable)return[];const i=Yr(e,r);if(!i)return[];if(i.type===S.IMPORTED&&i.importedFrom&&("*"===i.importSpecifier||!(i.dataType&&"object"==typeof i.dataType&&"isDefaultImport"in i.dataType&&i.dataType.isDefaultImport)))try{const r=["uloop","rtnl","socket","math","log","debug","digest","fs","io","nl80211","resolv","struct","ubus","uci","zlib"].includes(i.importedFrom);let o,s=[];if(r)return[];let a=!1;if(i.importedFrom.startsWith("file://"))o=i.importedFrom.replace("file://",""),a=!0;else if(i.importedFrom.startsWith("./")||i.importedFrom.startsWith("../"))o=n(6928).resolve(process.cwd(),i.importedFrom),a=!0;else{if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)+$/.test(i.importedFrom))return[];{const e=n(6928),t="./"+i.importedFrom.replace(/\./g,"/")+".uc";o=e.resolve(process.cwd(),t),a=!0}}if(a&&u.existsSync(o)){const n=u.readFileSync(o,"utf8");n.includes("export default")&&s.push({label:"default",kind:t.CompletionItemKind.Property,detail:"default export",sortText:"0_default",documentation:{kind:t.MarkupKind.Markdown,value:`**default**\n\nDefault export from \`${p.basename(o)}\`\n\nAccess with: \`${e}.default.propertyName\``}});const r=ti(n);for(const e of r)s.push({label:e.name,kind:ri(e.type),detail:`${e.type} export`,sortText:"1_"+e.name,documentation:{kind:t.MarkupKind.Markdown,value:`**${e.name}**\n\n${e.type} export from \`${p.basename(o)}\``}})}return s}catch(e){return[]}return[]}(e,o);if(r.length>0)return i.console.log(`Returning ${r.length} namespace import completions for ${e}`),r;const s=function(e,r){const i=n(9896),o=n(6928);if(!r||!r.symbolTable)return[];const s=Yr(e,r);if(!s||!s.importedFrom||s.type!==S.IMPORTED)return[];if(["uloop","rtnl","socket","math","log","debug","digest","fs","io","nl80211","resolv","struct","ubus","uci","zlib"].includes(s.importedFrom))return[];try{let n;if(s.importedFrom.startsWith("file://"))n=s.importedFrom.replace("file://","");else if(s.importedFrom.startsWith("./")||s.importedFrom.startsWith("../"))n=o.resolve(process.cwd(),s.importedFrom);else{if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)+$/.test(s.importedFrom))return[];{const e="./"+s.importedFrom.replace(/\./g,"/")+".uc";n=o.resolve(process.cwd(),e)}}if(!i.existsSync(n))return[];const r=i.readFileSync(n,"utf8"),a=[];r.includes("export default")&&a.push({label:"default",kind:t.CompletionItemKind.Property,detail:"default export",sortText:"0_default",documentation:{kind:t.MarkupKind.Markdown,value:`**default**\n\nDefault export from \`${o.basename(n)}\`\n\nAccess with: \`${e}.default.propertyName\``}});const c=ti(r);for(const e of c)a.push({label:e.name,kind:ri(e.type),detail:`${e.type} export`,sortText:"1_"+e.name,documentation:{kind:t.MarkupKind.Markdown,value:`**${e.name}**\n\n${e.type} export from \`${o.basename(n)}\``}});return a}catch(e){return[]}}(e,o);if(s.length>0)return i.console.log(`Returning ${s.length} fallback namespace completions for ${e}`),s}if(r&&r.length>0){const s=function(e,r,i){const o=n(9896);if(!i||!i.symbolTable)return[];const s=Yr(e,i);if(!s)return[];if(s.type===S.IMPORTED&&s.importedFrom&&"*"===s.importSpecifier&&1===r.length&&"default"===r[0])try{const n=s.importedFrom.startsWith("file://")?s.importedFrom.replace("file://",""):s.importedFrom;if(!o.existsSync(n))return[];const r=zr(o.readFileSync(n,"utf8"),n),i=[];for(const o of r)i.push({label:o.name,kind:ni(o.type),detail:`${o.type} from default export`,sortText:"0_"+o.name,documentation:{kind:t.MarkupKind.Markdown,value:`**${o.name}**\n\n${o.type} from default export of \`${p.basename(n)}\`\n\nAccessed via: \`${e}.default.${o.name}\``}});return i}catch(e){return[]}return[]}(e,r,o);if(s.length>0)return i.console.log(`Returning ${s.length} property chain completions for ${e}.${r.join(".")}`),s}const h=function(e,n){if(!n||!n.symbolTable)return[];const r=Yr(e,n);return r&&r.type===S.IMPORTED&&r.importedFrom?(console.log(`[IMPORTED_COMPLETION] Found imported symbol: ${e} from ${r.importedFrom}`),function(e,n){console.log(`[IMPORTED_COMPLETION] Getting completions for ${e} imported from ${n}`);try{if(!u.existsSync(n))return console.log(`[IMPORTED_COMPLETION] File does not exist: ${n}`),[];const e=ti(u.readFileSync(n,"utf8"));console.log(`[IMPORTED_COMPLETION] Found ${e.length} exports in ${n}`);const r=[];for(const i of e)r.push({label:i.name,kind:ri(i.type),detail:`${i.type} from ${p.basename(n)}`,sortText:"0_"+i.name,documentation:{kind:t.MarkupKind.Markdown,value:`**${i.name}**\n\n${i.type} exported from \`${p.basename(n)}\``}});return r}catch(e){return console.log(`[IMPORTED_COMPLETION] Error processing ${n}: ${e instanceof Error?e.message:String(e)}`),[]}}(e,r.importedFrom)):[]}(e,o);return h.length>0?(i.console.log(`Returning ${h.length} variable completions for ${e}`),h):(i.console.log(`No specific completions for object: ${e}`),[])}return Xr(o,i,d)}catch(e){return i.console.log("Completion error: "+e),Xr(o,i)}}(e,ci,ai,i)}),ai.onCompletionResolve(e=>e),ai.onCodeAction(e=>{const n=ci.get(e.textDocument.uri);if(!n)return[];const r=[],i=li.get(e.textDocument.uri),o=i?.result?.ast,s=[...e.context.diagnostics].sort((e,t)=>1e4*(e.range.end.line-e.range.start.line)+(e.range.end.character-e.range.start.character)-(1e4*(t.range.end.line-t.range.start.line)+(t.range.end.character-t.range.start.character))),a=new Set;for(const t of s)if("ucode-semantic"===t.source){const s=t.range.start.line,c=n.getText({start:{line:s,character:0},end:{line:s+1,character:0}}).replace(/\r?\n$/,"");if(t.code){const i=Oi(t,n,e.textDocument.uri,c,o);r.push(...i)}if("UC7001"===t.code){const i=Ai(t,n,e.textDocument.uri);r.push(...i)}if("UC7003"===t.code&&o&&i?.result){const s=Si(o,n.offsetAt(t.range.start),n,e.textDocument.uri,i.result);s&&(s.diagnostics=[t],r.push(s))}c.includes("// ucode-lsp disable")||a.has(s)||a.add(s)}for(const i of a){const o=n.getText({start:{line:i,character:0},end:{line:i+1,character:0}}).replace(/\r?\n$/,"");r.push({title:"Disable ucode-lsp for this line",kind:t.CodeActionKind.QuickFix,diagnostics:e.context.diagnostics.filter(e=>"ucode-semantic"===e.source&&e.range.start.line===i),edit:{changes:{[e.textDocument.uri]:[t.TextEdit.insert({line:i,character:o.length}," // ucode-lsp disable")]}}})}const c=new Set,l=[];for(const e of r)c.has(e.title)||(c.add(e.title),l.push(e));return l}),ai.onDefinition(e=>{const t=new Map;for(const[e,n]of li.entries())t.set(e,n.result);return function(e,t,n){oi||(oi=new Rr);const r=t.get(e.textDocument.uri),i=n.get(e.textDocument.uri);if(!r||!i)return null;const o=e.position,s=r.getText(),a=r.offsetAt(o);try{const e=new E(s,{rawMode:!0}).tokenize(),t=e.find(e=>e.pos<=a&&a<=e.end);if(t&&t.type===l.TK_LABEL&&"string"==typeof t.value){const n=t.value,o=i.symbolTable.lookupAtPosition(n,a)||i.symbolTable.lookup(n);if(o)return si(o,r,oi);const s=e.indexOf(t);if(s>=2){const t=e[s-1],o=e[s-2];if(t&&t.type===l.TK_DOT&&o&&o.type===l.TK_LABEL&&"string"==typeof o.value){const e=i.symbolTable.lookupAtPosition(o.value,a)||i.symbolTable.lookup(o.value);if(e&&e.dataType&&"object"==typeof e.dataType&&"moduleName"in e.dataType){const t=e.dataType.moduleName;if(Mn(t)){const i=xn[t].getMethod(n);if(pt(i))return si(e,r,oi)}}}}}}catch(e){const t=function(e,t){const n=/[a-zA-Z_$][a-zA-Z0-9_$]*/g;let r;for(;null!==(r=n.exec(e));)if(r.index<=t&&t<=r.index+r[0].length)return{start:r.index,end:r.index+r[0].length}}(s,a);if(t){const e=s.substring(t.start,t.end),n=i.symbolTable.lookupAtPosition(e,a)||i.symbolTable.lookup(e);if(n)return si(n,r,oi)}}return null}(e,ci,t)});const Li={keys:["object"],values:["object"],push:["array"],pop:["array"],shift:["array"],unshift:["array"],splice:["array"],sort:["array"],reverse:["array"],join:["array"],split:["string"],substr:["string"],substring:["string"],trim:["string"],ltrim:["string"],rtrim:["string"],match:["string"],replace:["string"],index:["string","array"],rindex:["string","array"],length:["string","array","object"],lc:["string"],uc:["string"],ucfirst:["string"],lcfirst:["string"],chr:["integer"],ord:["string"],hex:["string"]},Ii={push:{0:["array"]},pop:{0:["array"]},shift:{0:["array"]},unshift:{0:["array"]},splice:{0:["array"]},sort:{0:["array"],1:["function"]},reverse:{0:["array","string"]},filter:{0:["array"],1:["function"]},map:{0:["array"],1:["function"]},join:{0:["string"],1:["array"]},slice:{0:["array"]},uniq:{0:["array"]},keys:{0:["object"]},values:{0:["object"]},split:{0:["string"],1:["string","regex"]},substr:{0:["string"]},match:{0:["string"],1:["regex"]},replace:{0:["string"],1:["string","regex"],2:["string","function"]},trim:{0:["string"]},ltrim:{0:["string"]},rtrim:{0:["string"]},lc:{0:["string"]},uc:{0:["string"]},ucfirst:{0:["string"]},lcfirst:{0:["string"]},index:{0:["string","array"]},rindex:{0:["string","array"]},ord:{0:["string"]},hex:{0:["string"]},length:{0:["string","array","object"]},writefile:{0:["string"]},call:{0:["function"],2:["object","null"]},exists:{0:["object"],1:["string"]},loadstring:{0:["string"]},regexp:{0:["string"]},sprintf:{0:["string"]},printf:{0:["string"]}};function Di(e){if("CallExpression"!==e.type)return null;if("Identifier"!==e.callee?.type)return null;const t=e.callee.name,n=e.arguments?.[0];if(!n)return null;const r=ki(n);if(r){const e=Li[t];if(e)return{varName:r,expectedTypes:e}}if("CallExpression"===n.type)return Di(n);if("BinaryExpression"===n.type&&("||"===n.operator||"??"===n.operator)){const e=ki(n.left);if(e){const n=Li[t];if(n)return{varName:e,expectedTypes:n}}}return null}function ki(e){if("Identifier"===e.type)return e.name;if("MemberExpression"===e.type&&!e.computed){const t=ki(e.object);if(t&&"Identifier"===e.property?.type)return`${t}.${e.property.name}`}return null}function Pi(e,t){if(!e||"object"!=typeof e||"number"!=typeof e.start)return null;if(t<e.start||t>e.end)return null;if("MemberExpression"===e.type&&e.computed&&"CallExpression"===e.object?.type)return null;for(const n of Object.keys(e)){if("type"===n||"start"===n||"end"===n)continue;const r=e[n];if(Array.isArray(r))for(const e of r){const n=Pi(e,t);if(n)return n}else if(r&&"object"==typeof r&&"number"==typeof r.start){const e=Pi(r,t);if(e)return e}}return"CallExpression"===e.type?e:null}function xi(e,t){const n=e.getText();let r="_val",i=2;for(;new RegExp(`(?:let|const|var)\\s+${r}\\b`).test(n);)r=`_val${i}`,i++;return r}ci.listen(ai),ai.listen()})(),module.exports={}})();
|